From castironpi at gmail.com Wed Jul 23 12:42:29 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 23 Jul 2008 09:42:29 -0700 (PDT) Subject: Python Written in C? References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> <6eosgtF7u58sU1@mid.uni-berlin.de> Message-ID: <537c58c3-d74c-41dd-8571-26cfbb415178@34g2000hsh.googlegroups.com> On Jul 23, 9:11?am, Marc 'BlackJack' Rintsch wrote: > On Wed, 23 Jul 2008 14:10:22 +0200, mk wrote: > > Marc 'BlackJack' Rintsch wrote: > >> I can't even remember when I deleted something from a list in the past. > > > Still, doesn't that strike you as.. workaround? > > No, I find it actually safer; I don't have to care where modifications of > the list might be seen elsewhere in the program. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch a[:]= newlist and a= newlist have two completely different effects, and one is just as safe as 'del'. Besides, del isn't safe to be seen elsewhere in the program in other threads, if they aren't locking the GIL. From Lie.1296 at gmail.com Mon Jul 21 17:47:31 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 21 Jul 2008 14:47:31 -0700 (PDT) Subject: Change PC to Win or Windows References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> <82873ccd-9667-4dfa-9ec4-a9ac7c672aa7@w1g2000prk.googlegroups.com> Message-ID: <0f3272c1-b1a7-4aef-9e4a-0f03af823a2d@z11g2000prl.googlegroups.com> On Mon, 2008-07-21 at 16:45 -0400, Derek Martin wrote: > On Mon, Jul 21, 2008 at 12:32:00PM -0700, Lie wrote: > > > The term "PC" is commonly used in English, in the United States > > > and other English speaking countries, to mean a computer running > > > Microsoft Windows. > > > > As far as I am aware, they're like that because most people aren't > > even aware that there are other OSes than Microsoft Windows. > > You are missing two points. > > The first one: It doesn't matter what the reasons are for the > terminology to be common. It only matters that it IS common. It is; > and it is therefore "correct" in the sense that it conveys a meaning > to the overwhelming majority of English speakers, which is the > intended one. > True, it doesn't actually matters, but it is a proof that it is technically incorrect to apply PC JUST to Windows-based PC. It is arguable whether the term should only be exclusively to IBM-PC or whether the term should be expanded to include its clones. But I'm against on using it just to refer Windows-based PC exclusively, since it is neither Microsoft's marketing term nor a literal meaning conveyed in the term. > As for the question of whether or not it is appropriate to refer to > Windows installations as "PC", it's as simple as that. It is, by > definition (via common usage). That is what this thread is about. > Common usage isn't always correct. For example, a physicist would not use weight when he meant mass. Although in daily use he might not care much, but in technical environment doing so would embarrass him. In this analogy, I consider download page for a software source code to be a technical area. > The reason why the world hasn't evolved to the two predictable cases > > ("all kinds of microcomputers" or "IBM-PC and clones"), is what I'll > > explain below. > > Your explanation is irrelevant to the argument of whether or not the > term PC is an inappropriate term to describe a Windows installation, > which is what this thread is about. That is the premise put forth by > the OP, and that is the notion to which I am responding. It simply is > not wrong or inappropriate in any sense; it is in fact correct, > regardless of how the meaning or usage resulted, and regardless of any > ADDITIONAL meanings the term may have. > > For what it's worth, your explanation is also WRONG; the term PC > began to be popularly used in the United States to describe > Intel-based Microsoft machines when there was a proliferation of other > kinds of personal computers available to consumers. When it was first > used this way, the IBM PC was *NOT* the most popular personal computer... > the Commodore 64 was. > True, but PC is IBM's marketing term, thus it originally belongs to them. Nevertheless, it is NOT Window's marketing term and the literal meaning of Personal Computer is in no way means Windows-based computers ONLY. > It dates from a time when the Commodore VIC-20 > and C64, Atari 400 and 800, Timex Sinclair, and other computers were > all very popluar home machines. But they aren't called PC, why? Because IBM hasn't invented the term. Nowadays, they might be called as PC or not depending on which side are you in: "PC as IBM-PC" or "PC as personal computer" (note the lower case) > The term probably originated primarily because IBM chose to name their > computer the IBM PC, and because of Americans' predeliction to > abbreviate everything that's more than 2 syllables. ;-) > > > > It wasn't something that Apple started; it's been used this way > > > in increasingly common usage for at least 20 years, although > > > exactly what combination of hardware and software was being > > > refered to as a "PC" has evolved over that timeframe. > > > > Apple popularizes the term by explicit marketing, > > And here is the last point you are missing: Apple does no such > thing. They did, by using the term PC to refer to other computers. IF they have used the term "Regular PC", noone would have complained, it's just like an apple farmer advertising his "Super Apples" and calls other apples "Regular Apples", there would be nothing wrong about it. But there is this specific apple farmer who advertised his apple as "Orange" and calls other apples as "Apples", which makes a problem since "Orange" is just a different variants of apple, and is still an apple. This kind of advertising Apple (the computer company) used is misleading, since it implied that their PC is not a PC. > They are only using a term in a way that has previously been > popularized by the computer industry as a whole, and its market (i.e. > consumers, predominantly American consumers historically) for > *DECADES*. > If I'm not mistaken, their ad campaign mentioning PCs is > less than 10 years old (though I can't quickly find any references as > to the date). The popularization of the term PC to refer to > Intel-compatible machines running Microsoft OSes PREDATES APPLE'S AD > CAMPAIGN BY OVER 10 YEARS. When did I say that Apple was the first one to start the term's misuse? Apple's is only making the term's misuse more widespread, nevertheless they might be the largest computer company that tried to _actively_ spread its misuse by persistently using the term in their ads in that manner. But even without Apple, yes, it is true that the misuse would still get widespread, simply because of Microsoft's dominance. > Therefore none of your points are valid or relevant, as to the > question of whether the usage of the term "PC" to describe windows > builds of Python is appropriate. > Because you are missing all the points. > Can we return to the subject of Python now? yes, in short, don't use PCBuild to refer Windows-only build. PCBuild should contain a universal build that is compatible with all platforms a PC is usually based on (i.e. it shouldn't exist except if such thing is possible). From socyl at 987jk.com.invalid Wed Jul 30 16:45:57 2008 From: socyl at 987jk.com.invalid (kj) Date: Wed, 30 Jul 2008 20:45:57 +0000 (UTC) Subject: how to split text into lines? References: Message-ID: In kj writes: >In Perl, one can break a chunk of text into an array of lines while >preserving the trailing line-termination sequence in each line, if >any, by splitting the text on the regular expression /^/: > DB<1> x split(/^/, "foo\nbar\nbaz") >0 'foo >' >1 'bar >' >2 'baz' >But nothing like this seems to work in Python: >>>> re.split('^', 'foo\nbar\nbaz') >['foo\nbar\nbaz'] >(One gets the same result if one adds the re.MULTILINE flag to the >re.split call.) >What's the Python idiom for splitting text into lines, preserving >the end-of-line sequence in each line? Sorry, I should have googled this first. I just found splitlines()... Still, for my own edification, is there a way to achieve the same effect using re.split? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From circularfunc at yahoo.se Wed Jul 2 17:11:52 2008 From: circularfunc at yahoo.se (defn noob) Date: Wed, 2 Jul 2008 14:11:52 -0700 (PDT) Subject: Run interpreter in emacs? References: <6d28ccFftk4U1@mid.uni-berlin.de> Message-ID: <9817b8df-a6bb-4392-86a9-66c2807bec31@z72g2000hsb.googlegroups.com> thanks but i dont quite understand the load-path, add to the load path. the loadpath has a lot of variables. so where i should i place the python-mode folder and should i then add that directory to the loadpath? From deets at nospam.web.de Mon Jul 28 05:41:20 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 11:41:20 +0200 Subject: os.symlink() References: Message-ID: <6f5ik2F9t9b5U1@mid.uni-berlin.de> Nikolaus Rath wrote: > Hello, > >>From `pydoc os`: > > symlink(...) > symlink(src, dst) > > Create a symbolic link pointing to src named dst. > > > Is there any reason why this is so deliberately confusing? Why is the > target of the symlink, the think where it points *to*, called the > `src`? It seems to me that the names of the parameters should be > reversed. I used the command the other day, and didn't feel the slightest confusion. To me, the process of creating a symlink is like a "virtual copy". Which the above parameter names reflect perfectly. Diez From josef.moellers at fujitsu-siemens.com Tue Jul 22 05:56:41 2008 From: josef.moellers at fujitsu-siemens.com (Josef Moellers) Date: Tue, 22 Jul 2008 11:56:41 +0200 Subject: The Importance of Terminology's Quality In-Reply-To: References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: Martin Gregorie wrote: > Are you sure about that? > I used Algol 60 on an Elliott 503 and the ICL 1900 series back when it was > a current language. The term "thunking" did not appear in either compiler > manual nor in any Algol 60 language definition I've seen. A60 could pass > values by name or value and procedures by name. That was it. Call by name > is what is now referred to as reference passing. Are you sure about that? ;-) AFAIK "Call by name" is *not* the same as passing an argument by reference. With "call by name" you can implement this wonderful thing called "Jensen's Device", which you cannot do when you pass parameters by reference! Josef -- These are my personal views and not those of Fujitsu Siemens Computers! Josef M?llers (Pinguinpfleger bei FSC) If failure had no penalty success would not be a prize (T. Pratchett) Company Details: http://www.fujitsu-siemens.com/imprint.html From bulg at ngs.ru Tue Jul 15 22:54:30 2008 From: bulg at ngs.ru (Yosifov Pavel) Date: Tue, 15 Jul 2008 19:54:30 -0700 (PDT) Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> <7348c0dc-028d-4f89-9d63-b1247fb6807c@m44g2000hsc.googlegroups.com> Message-ID: Kay, can you show example of such generator? ReIter, for example, work with usual generators. But for "big" iterator, I think is no any good solutions. IMHO we can discern 2 types of iterators: re-startable (based on internal Python objects) and not re-startable (with an external state, side- effects)... Best regards, Pavel From iainking at gmail.com Mon Jul 21 05:25:24 2008 From: iainking at gmail.com (Iain King) Date: Mon, 21 Jul 2008 02:25:24 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <143349c3-b0e9-49d8-9426-8b030b23d2c9@l42g2000hsc.googlegroups.com> On Jul 21, 6:58?am, "Krishnakant Mane" wrote: > > First off all c# is absolute rubbish waist of time. ?if I need to > learn it then I better lern java or pythonfor that matter. ?and by the > way what is a "real programmer?" The story of a Real Programmer: http://www.pbm.com/~lindahl/mel.html Iain From bruno.desthuilliers at gmail.com Wed Jul 9 16:26:27 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 9 Jul 2008 13:26:27 -0700 (PDT) Subject: FOSS projects exhibiting clean/good OOP? References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> Message-ID: <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> On 9 juil, 16:38, Phillip B Oldham wrote: > I'm wondering whether anyone can offer suggestions on FOSS projects/ > apps which exhibit solid OO principles, clean code, good inline > documentation, and sound design principles? This is somewhat subjective... Some would say that Python's object model is fundamentally broken and crappy (not MHO, needless to say) that Python + "solid OO principles" is antinomic !-) More seriously: > I'm devoting some time to reviewing other people's code to advance my > skills. Its good to review bad code (of which I have more than enough > examples) as well as good, but I'm lacking in finding good examples. > > Projects of varying sizes would be great. I'd recommand at least FormEncode and SQLAlchemy. From ojeeves at gmail.com Wed Jul 16 08:14:33 2008 From: ojeeves at gmail.com (oj) Date: Wed, 16 Jul 2008 05:14:33 -0700 (PDT) Subject: bad recursion, still works References: mailman.112.1216164093.922.python-list@python.org <20cba7ab-72d2-4c7b-8f3f-48f39eaf9625@m3g2000hsc.googlegroups.com> Message-ID: On Jul 16, 1:09?pm, Jeff wrote: > On Jul 15, 7:21?pm, Michael Torrie wrote: > > > iu2 wrote: > > > I still don't understand: In each recursive call to flatten, acc > > > should be bound to a new [], shouldn't it? Why does the binding happen > > > only on the first call to flatten? > > > Nope. ?In each new call it's (re)bound to the same original list, which > > you've added to as your function continues--it's mutable. ?Default > > variables that are bound to mutable objects are one of the big caveats > > that is mentioned in the FAQ. > > Is this avoidable by using a call to list() in the definition instead? No. Probably what you'd want to do, is something like this: def func(arg1, arg2=None): if arg2 is None: arg2 = list() ... So you create a list at runtime if arg2 has its default value. From nagle at animats.com Fri Jul 18 19:29:43 2008 From: nagle at animats.com (John Nagle) Date: Fri, 18 Jul 2008 16:29:43 -0700 Subject: Having trouble with some lists in BeautifulSoup In-Reply-To: References: Message-ID: <48812316$0$17149$742ec2ed@news.sonic.net> Alexnb wrote: > Okay, what I want to do with this code is to got to thesaurus.reference.com > and then search for a word and get the syns for it. Now, I can get the syns, > but they are still in html form and some are hyperlinks. But I can't get the > contents out. I am not that familiar with BeautifulSoup. So if anyone wants > to look over this code(if you run it, it will make a lot more sense) and > maybe help me out. The thesaurus site may become annoyed if you overdo this. However, it's not hard to do. Search the output for an "a" tag with class "noline", then extract the text content of the "a" tag. The BeautifulSoup manual will tell you how. If you want raw thesaurus data you can use freely, see "http://wordnet.princeton.edu". John Nagle From dullrich at sprynet.com Fri Jul 11 12:15:19 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 11 Jul 2008 11:15:19 -0500 Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: In article , Terry Reedy wrote: > David C. Ullrich wrote: > > In article > > <02ff4326-7b07-4ae6-8607-f58ea61802ef at z72g2000hsb.googlegroups.com>, > > ssecorp wrote: > > > >> I am never redefining the or reassigning the list when using validate > >> but since it spits the modified list back out that somehow means that > >> the modified list is part of the environment and not the old one. > >> i thought what happend inside a function stays inside a function > >> meaning what comes out is independent of what comes in. > >> Meaning if I want the list I send as a parameter to the function I > >> have to do x = func(x) and not just func(x) and x is magically what > >> comes out of func(). > > > > A function cannot modify the value of a global variable > > Yes it can. > >>> a=[] > >>> def f(): > a.append('yes I can') > > >>> f() > >>> a > ['yes I can'] > > > (unless it specifies "global"). It doesn't reassign anything. > > The statement 'global a' would allow f to *rebind* the global *name* > 'a'. Aargh. That's exactly what I meant, sorry. > The word 'variable' should almost not be used in discussing Python > since it is often unclear whether it refers to a name (or collection > slot) or an object bound thereto. Indeed. Which is exactly why I included those snippets of code that you snipped, one of which does exactly what your snippet above does... you're probably right, "variable" is a bad idea, and "modify the value of a variable" is a very bad idea. The code doesn't "modify the value of the variable" in the sense that the value of the variable is a certain object, and after the function call the value is the same object. It does "modify the value of the variable" in the sense that the object which is the value of the variable has been modified. There's a problem here. Please note that this is not a criticism, and I don't really know what anyone could do about the problem. The problem is that if the reader is not accustomed to thinking explicitly about what's going on under the hood when code is executed he's going to have a hard time understanding the difference between "assigning a value to a variable" and "binding a name to an object". Once I realized that dicts rule everything this became clear to me, but for some time the discussions I saw on all this made no sense to me. Which is why I think it's a good idea to include examples illustrating what can and cannot be done, which is why I did that. I tend to suspect that the OP is at least as confused on the subtlties as I was back then (evidence below). > > But in the functions below you're not reassigning a variable, > > you're _modifiying_ an object. A function _can_ modify an > > object you pass to it: > > It can modify any mutable object it can access. > > >> Doesnt Python have closure or that isnt what this is about? > > Python does have closures. This is not about that. This is why I suspect what I say I suspect. He's thought that the word "closure" meant something like "local scope"... > >> def validate(placed): > >> student = round(random.random()*401) > >> if student in placed: > >> return validate(placed) > >> else: > >> placed.append(student) > >> return student, placed > > Delete this. It is redundant with the below. > > >> def val(placed): > >> student = round(random.random()*401) > >> if student in placed: > >> return validate(placed) > >> else: > >> placed.append(student) > >> return student > > I believe this is equivalent to > > def addval(placed): > while True: > student = round(random.random()*401) > if student not in placed: > break > placed.append(student) > return student > > While this avoids the indefinite recursion depth problem, it does not > avoid the indefinite time problem. Use random.shuffle, or write your > own version if doing this for practice. Also consider removing the > return statement unless you actually directly use the added value. It > is easier to remember that addval mutates 'placed' without the return. > > >>>>> g = lambda x:validate(x) > > This is doubly diseased. > > First, never write a 'name = lambda...' statement since it is equivalent > to a def statement except that the resulting function object lacks a > proper .funcname attribute. The above only trivially abbreviates > def g(x): return validate(x) > by 3 characters. Another reason is that the lambda form somehow more > often tricks people into the next mistake . > > Second, never write a function (with either def or lambda) that simply > returns a function of the argument(s). The wrapping does nothing! This > is a waste of time and space for both you and the interpreter. The > above is functionally equivalent to > g = validate > and if you want that, you could name the function 'g' when you define it. > > >>>>> l=[] > In some fonts, 'l' and '1' are nearly identical; please use something > else for public code, which you made this to be by posting it;-) > > >>>>> for x in range(1,10): > >> g(l) > As said, the 'g' wrapper is useless. > addval(l) > > Hope this helps. > > Terry Jan Reedy -- David C. Ullrich From alokkat at gmail.com Thu Jul 10 21:20:21 2008 From: alokkat at gmail.com (Alok Kumar) Date: Thu, 10 Jul 2008 21:20:21 -0400 Subject: Basic Question about Python WebServer File handling Message-ID: Hi, I need to have a python webserver which can handle Get request from the clients and upload the *files* from 4 different directories. Can someone please point me what to exactly look for. Thanks you very much for this great help. Regards Alok Kumar -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Thu Jul 10 14:34:44 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jul 2008 14:34:44 -0400 Subject: Smal question In-Reply-To: <48763c7f$0$9609$426a74cc@news.free.fr> References: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> <48763c7f$0$9609$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Hans M?ller a ?crit : >> Hello group, >> >> I have some scripts sharing some common functions. >> So what I'd like to have is a modern include. >> Of course python does not have (with good reasons) no include statement. >> But I'm too lazy to create a module which has to be installed into the >> interpreter for some functions I need to share in a project. > > What do you mean "installed in the interpreter" ? He probably meant either compiled into the interpreter or installed in the interpreter directory, not knowing that one can import from the project directory, and that the project directory gets added to the front of sys.path (as '.'). From Russ.Paielli at gmail.com Sun Jul 27 18:11:13 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 15:11:13 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: On Jul 27, 12:39 pm, Bruno Desthuilliers wrote: > Derek Martin a ?crit : > > > > > On Sun, Jul 27, 2008 at 08:19:17AM +0000, Steven D'Aprano wrote: > >>> You take the name down to a single letter. As I suggested in an earlier > >>> post on this thread, why not take it down to zero letters? > >> The question isn't "why not", but "why". The status quo works well as it > >> is, even if it isn't perfect. Prove that implicit self is a good idea -- > >> or at least prove that it is an idea worth considering. > > > Come on, this sounds like a schoolyard argument. This comes down to a > > matter of style, and as such, is impossible to prove. It's largely a > > question of individual preference. > > > That said, the argument in favor is rather simple: > > > 1. This is an extremely common idiom in Python > > 2. It is completely unnecessary, and the language does not suffer for > > making it implicit > > 3. Making it implicit reduces typing, reduces opportunities for > > mistakes, and arguably increases consistency. > > "arguably", indeed, cf below. > > > As for the latter part of #3, self (or some other variable) is > > required in the parameter list of object methods, > > It's actually the parameter list of the *function* that is used as the > implementation of a method. Not quite the same thing. And then, > consistency mandates that the target object of the method is part of the > parameter list of the *function*, since that's how you make objects > availables to a function. > > > however when the > > method is *called*, it is omitted. > > Certainly not. You need to lookup the corresponding attribute *on a > given object* to get the method. Whether you write > > some_object.some_method() > > or > > some_function(some_object) > > you still need to explicitely mention some_object. > > > It is implied, supplied by Python. > > Neither. The target object is passed to the function by the method > object, which is itself returned by the __get__ method of function > objects, which is one possible application of the more general > descriptor protocol (the same protocol that is used for computed > attributes). IOW, there's nothing specific to 'methods' here, just the > use of two general features (functions and the descriptor protocol). > FWIW, you can write your own callable, and write it so it behave just > like a function here: > > import types > > class MyCallable(object): > def __call__(self, obj): > print "calling %s with %s" % (self, obj) > def __get__(self, instance, cls): > return types.MethodType(self.__call__, instance, cls) > > class Foo(object): > bar = MyCallable() > > print Foo.bar > f = Foo() > f.bar() > > > Thus when an object method is called, it must be called with one fewer > > arguments than those which are defined. This can be confusing, > > especially to new programmers. > > This is confusing as long as you insist on saying that what you > "def"ined is a method - which is not the case. > > > It can also be argued that it makes the code less ugly, though again, > > that's a matter of preference. > > >> It's not enough to show that a change "isn't bad" -- you have to show > >> that it is actively good. > > > But he did... he pointed out that *it saves work*, without actually > > being bad. Benefit, without drawback. Sounds good to me! > > >> "Don't need to look at the method signature" is not an argument in favour > >> of implicit self. > > > Yes, actually, it is. > > It isn't, since there's no "method signature" to look at !-) > > > If there is a well-defined feature of Python > > which provides access to the object within itself, > > The point is that you don't get access to the object "within itself". > You get access to an object *within a function*. > > The fact that a function is defined within a class statement doesn't > imply any "magic", it just creates a function object, bind it to a name, > and make that object an attribute of the class. You have the very same > result by defining the function outside the class statement and binding > it within the class statement, by defining the function outside the > class and binding it to the class outside the class statement, by > binding the name to a lambda within the class statement etc... > > > then the > > opportunities for mistakes when someone decides to use something else > > are lessened. > > >> You don't need to look at the method signature when you're using an > >> explicit self either. > > > That isn't necessarily true. If you're using someone else's code, and > > they didn't use "self" -- or worse yet, if they chose this variable's > > name randomly throughout their classes -- then you may well need to > > look back to see what was used. > > > It's bad programming, but the world is full of bad programmers, and we > > don't always have the choice not to use their code. Isn't one of > > Python's goals to minimize opportunities for bad programming? > > Nope. That's Java's goal. Python's goals are to maximize opportunities > for good programming, which is quite different. > > > Providing a keyword equivalent to self and removing the need to name > > it in object methods is one way to do that. > > It's also a way to make Python more complicated than it needs to be. At > least with the current state, you define your functions the same way > regardless of how they are defined, and the implementation is > (relatively) easy to explain. Special-casing functions definition that > happens within a class statement would only introduce a special case. > Then you'd have to explain why you need to specify the target object in > the function's parameters when the function is defined outside the class > but not when it's defined within the class. > > IOW : there's one arguably good reason to drop the target object from > functions used as methods implementation, which is to make Python looks > more like Java, and there's at least two good reason to keep it the way > it is, which are simplicity (no special case) and consistency (no > special case). > > Anyway, the BDFL has the final word, and it looks like he's not going to > change anything here - but anyone is free to propose a PEP, isn't it ? The issue here has nothing to do with the inner workings of the Python interpreter. The issue is whether an arbitrary name such as "self" needs to be supplied by the programmer. Neither I nor the person to whom you replied to here (as far as I can tell) is suggesting that Python adopt the syntax of Java or C++, in which member data or functions can be accessed the same as local variables. Any suggestion otherwise is a red herring. All I am suggesting is that the programmer have the option of replacing "self.member" with simply ".member", since the word "self" is arbitrary and unnecessary. Otherwise, everything would work *EXACTLY* the same as it does now. This would be a shallow syntactical change with no effect on the inner workings of Python, but it could significantly unclutter code in many instances. The fact that you seem to think it would change the inner functioning of Python just shows that you don't understand the proposal. From dickinsm at gmail.com Wed Jul 16 06:05:38 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 16 Jul 2008 03:05:38 -0700 (PDT) Subject: new itertools functions in Python 2.6 References: <4dd80ff2-5fda-405a-a637-08c985ff8add@e53g2000hsa.googlegroups.com> <498a38d4-10b5-4824-8401-5ebb510fcfa8@y38g2000hsy.googlegroups.com> Message-ID: <49e8f7eb-b4c6-4a51-af0d-54a257fcc353@x41g2000hsb.googlegroups.com> On Jul 16, 7:20?am, Mensanator wrote: > > > ## ?Combinations with replacement > > > ## ?----------------------------- > > > ## ?aaa aab aac aad aae abb abc abd abe acc acd ace > > > ## ?add ade aee bbb bbc bbd bbe bcc bcd bce bdd bde > > > ## ?bee ccc ccd cce cdd cde cee ddd dde dee eee > > > ## > > > ## ?actual words: 35 ? ?(m+n-1)!/(n!(m-1)!) words: 35 >>> for x in combinations(range(7), 4): ... x = [-1] + list(x) + [7] ... print ''.join(c*(x[i+1]-x[i]-1) for i, c in enumerate('abcde')) ... eee dee dde ddd cee cde cdd cce ccd ccc bee bde bdd bce bcd bcc bbe bbd bbc bbb aee ade add ace acd acc abe abd abc abb aae aad aac aab aaa Generalization left as an exercise for the reader. Mark From darcy at druid.net Sat Jul 26 10:08:09 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 26 Jul 2008 10:08:09 -0400 Subject: binding names doesn't affect the bound objects (was: print doesn't respect file inheritance?) In-Reply-To: <8763qtmgo7.fsf@benfinney.id.au> References: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> <8763qtmgo7.fsf@benfinney.id.au> Message-ID: <20080726100809.02fcca24.darcy@druid.net> On Sat, 26 Jul 2008 14:07:52 +1000 Ben Finney wrote: > > sys.stdout = n > > Re-binds the name 'sys.stdout' to the object already referenced by the > name 'n'. No objects are changed by this; only bindings of names to > objects. I do agree that the object formerly known as sys.stdout hasn't changed. > > print "Testing: 1, 2, 3..." > > Doesn't rely at all on the name 'sys.stdout', so isn't affected by all > the binding of names above. Hmm. Are you saying that the following doesn't work? $ python >>> f = open("test", "w") >>> import sys >>> sys.stdout = f >>> print "test message" >>> sys.exit(0) $ cat test test message > In other words, you can't change the object used by the 'print' > statement only by re-binding names (which is *all* that is done by the > '=' operator). Apparently I can. > You can, however, specify which file 'print' should use > . Which contains this statement. "Standard output is defined as the file object named stdout in the built-in module sys." I suppose that there might be some ambiguity there but the proof, as they say, is in the pudding. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From alif016 at gmail.com Sat Jul 26 12:19:45 2008 From: alif016 at gmail.com (Andrew) Date: Sat, 26 Jul 2008 11:19:45 -0500 Subject: Easier way to get the "here" path? In-Reply-To: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> References: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> Message-ID: <488B4EA1.6050506@gmail.com> bukzor wrote: >>>> from os.path import abspath, realpath >>>> realpath(path.__file__.rstrip("c")) >>>> > '/home/bgolemon/python/symlinks/path.py' > >>>> realpath(abspath(path.__file__.rstrip("c"))) >>>> > '/home/bgolemon/python/symlinks/symlinks/path.py' > -- > http://mail.python.org/mailman/listinfo/python-list > I find it interesting that I get something different: In [1]: import path path.pyc In [2]: path.__file__ Out[2]: 'path.pyc' In [3]: path.__file__.rstrip("c") Out[3]: 'path.py' In [4]: from os.path import abspath, realpath In [5]: realpath(path.__file__.rstrip("c")) Out[5]: '/home/andrew/sym/sym/path.py' In [6]: realpath(abspath(path.__file__.rstrip("c"))) Out[6]: '/home/andrew/sym/sym/path.py' I get the same thing for realpath() and realpath(abspath()) It seems to me you can just use: In [1]: import path path.pyc In [2]: from os.path import abspath In [3]: realpath(path.__file__.rstrip("c")) Out[3]: '/home/andrew/sym/sym/path.py' By the way, I am in /home/andrew/sym and path is symlinked from /home/andrew/sym/sym/path.py to /home/andrew/sym/path.py -- Andrew From girish.cfc at gmail.com Thu Jul 24 03:15:54 2008 From: girish.cfc at gmail.com (Girish) Date: Thu, 24 Jul 2008 00:15:54 -0700 (PDT) Subject: EXCEL API Message-ID: <8279561b-05b7-4935-9ded-def5663b4f93@y21g2000hsf.googlegroups.com> Hello, Does any one have a sample piece of code to search for a keyword in Excel sheet? if so plz post it.. Thanks, Girish.. From Xue.Huichao at gmail.com Mon Jul 14 21:03:40 2008 From: Xue.Huichao at gmail.com (Bighead) Date: Mon, 14 Jul 2008 18:03:40 -0700 (PDT) Subject: About the slot declaration decorator in PyQt4 References: Message-ID: <8486b24e-4d80-4bc2-85b7-db6b6519915f@m45g2000hsb.googlegroups.com> On Jul 15, 2:04 am, "Sebastian \"lunar\" Wiesner" wrote: > Bighead : > > > I remember when I did UI Design in PyQt4 for the first time, I found a > > manual. In it, no "connect" was used. Instead, an OO approach is > > applied, new UI classes inherit from old ones, and all the slot > > functions are automatically connected to some signals, using a > > decorator. In the __init__ function of our newly written class, > > "connect" is not invoked. > > > I like this style... > > > Unfortunately, I cannot find that manual now.... So anyone have read > > something like that before? If so, could you tell me where can I find > > that manual please? Thank you :) > > I guess, you're referring to QtCore.pyqtSignature and > QtCore.QMetaObject.connectSlotsByName. > > Seehttp://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#t... > > Especially "3.7.3 Connecting Slots By Name" > > Hih > > -- > Freedom is always the freedom of dissenters. > (Rosa Luxemburg) Oh yes, that's it! connectSlotsByName. That is the reason I though Qt was easy to use. This will be much easier :) Thank you very much. From http Mon Jul 28 12:27:08 2008 From: http (Paul Rubin) Date: 28 Jul 2008 09:27:08 -0700 Subject: with statement for two files References: <08d72316-15f1-45dd-b1f7-7b8ee06efef5@e39g2000hsf.googlegroups.com> Message-ID: <7xsktuvusj.fsf@ruckus.brouhaha.com> braver writes: > with open(src) as readin, open(dst,"w") as writin: # WRONG: comma > doesn't work > ... > -- so that you have transactional safety for two file descriptors? use contextlib.nexted(). From johnroth1 at gmail.com Sun Jul 13 15:30:23 2008 From: johnroth1 at gmail.com (John Roth) Date: Sun, 13 Jul 2008 12:30:23 -0700 (PDT) Subject: Mutually referencing imports -- impossible? References: Message-ID: <2e6bcb14-1db7-413b-afa7-62a11c9e33e4@26g2000hsk.googlegroups.com> On Jul 13, 11:55?am, Matthew Wilson wrote: > I started off with a module that defined a class Vehicle, and then > subclasses Car and Motorcycle. > > In the Car class, ?for some bizarre reason, I instantiated a Motorcycle. > Please pretend that this can't be avoided for now. > > Meanwhile, my Motorcycle class instantiated a Car as well. > > Then I moved the Car and Motorcycle classes into separate files. ?Each > imported the Vehicle module. > > Then I discovered that my Car module failed because the global > Motorcycle wasn't defined. ?The same problem happened in my Motorcycle > module. ?Car and Motorcycle can't both import each other. > > In the beginning, when all three (Vehicle, Car, and Motorcycle) were > defined in the same file, everything worked fine. > > I don't know how to split them out in separate files now though and I > really wish I could because the single file is enormous. > > Any ideas? > > Matt While it's possible for circular imports to work, it's very dangerous: it's not always possible to tell what went wrong without tracking down the process of the import step by step. There are more productive ways of banging your head against the wall and going insane. In your situation, it might be a whole lot easier to extract a common superclass that both of your classes could inherit from. John Roth From spandanagella at gmail.com Thu Jul 3 22:14:05 2008 From: spandanagella at gmail.com (spandana g) Date: Fri, 4 Jul 2008 10:14:05 +0800 Subject: HTTP request error with urlopen In-Reply-To: References: Message-ID: Hello , I have written a code to get the page source of the google search page .. this is working for other urls. I have this problem with import re from urllib2 import urlopen string='http://www.google.com/search?num=20&hl=en&q=ipod&btnG=Search' file_source=file("google_source.txt",'w') file_source.write(urlopen(string).read()) page_content=file_source.readlines() Traceback (most recent call last) : File "C:/Python25/google.py", line 5,in file_source.write(urlopen(string).read()) File "C:\Python25\lib\urllib2.py", line 124 , in urlopen return__opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 387 , in open response =meth(req, response) File "C:\Python25\lib\urllib2.py", line 498 , in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 425, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 360, in __call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 506, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: Forbidden Actually urlopen is working for google labs sets page but not for the google.com and even I have same problem with wikipedia . Please let me know .. If any one of have any idea about this . Thank You, Spandana. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chrispoliquin at gmail.com Thu Jul 31 16:07:16 2008 From: chrispoliquin at gmail.com (chrispoliquin at gmail.com) Date: Thu, 31 Jul 2008 13:07:16 -0700 (PDT) Subject: find and replace with regular expressions Message-ID: I am using regular expressions to search a string (always full sentences, maybe more than one sentence) for common abbreviations and remove the periods. I need to break the string into different sentences but split('.') doesn't solve the whole problem because of possible periods in the middle of a sentence. So I have... ---------------- import re middle_abbr = re.compile('[A-Za-z0-9]\.[A-Za-z0-9]\.') # this will find abbreviations like e.g. or i.e. in the middle of a sentence. # then I want to remove the periods. ---------------- I want to keep the ie or eg but just take out the periods. Any ideas? Of course newString = middle_abbr.sub('',txt) where txt is the string will take out the entire abbreviation with the alphanumeric characters included. From mva.led at gmail.com Mon Jul 21 01:15:45 2008 From: mva.led at gmail.com (Manuel Vazquez Acosta) Date: Mon, 21 Jul 2008 01:15:45 -0400 Subject: Python Written in C? Message-ID: <48841B81.3000704@gmail.com> I think your mixing things up. Even modern C compiler are mostly written in some other high level language. See GCC, for instance: it's mostly written in C. Many languages are made for build other major systems: * C was made in order to ease the build of Unix * Ada was made in order to ease the build of Air Traffic Control Systems. * and so on... On the other hand, Python's language features are, in a way, orthogonal to those of the underlying language in which Python *may* be implemented (take a look at PyPy: http://en.wikipedia.org/wiki/PyPy). I mean, I really don't care how Python mappings are implemented in C. What I care about is that I think in terms of (key, value) mappings, regardless of how lookups, insertions, deletions, and so are made internally. In C, I would have to resort to implement a hash table or so. Let's summarize: Python is a *new* language. C was the option to make it happen, there are others. Manuel. giveitawhril2008 at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. > -- > http://mail.python.org/mailman/listinfo/python-list > From timr at probo.com Thu Jul 31 03:10:14 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 31 Jul 2008 07:10:14 GMT Subject: Newbie Python questions References: Message-ID: <12p2941fee0nnimqmraqt9cm1vml7ra2kt@4ax.com> LessPaul wrote: > >...My >question is in regard to GUI platforms. My primary target would be >Windows, but I would also like be able to support Linux and Mac >versions if possible. I'm also interested in using a system that also >has support for pure C++ applications. As such, and after reading many >web pages regarding Python GUIs, I believe I have the candidates >narrowed down to pyQT and wxPython. > >The first question -- how steep is the curve to become proficient with >the above GUI packages? There is so much personal preference here that it is extremely hard to give any guidance. If you have done any Windows programming at all, so that you are familiar with the event-driven programming model, then I don't think you would see that much difference in learning curve. The two packages are more alike than they are different -- the various APIs are just spelled differently. I happen to be a big wxPython fan. I learn best by example, and wxPython has a 44,000-line demo suite with 167 source files that demonstrates virtually every class it includes. >Since there appears to be no commercial licencing fee for wxWidgets/ >wxPython, the last question is what do I gain from going QT over wx? >I've seen great applications written with both (on my computer I have >the wxPython Digsby and the pyQT apps "Mnemosyne" and "Anki". All seem >to be solid. Yep. Personal preference. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From fredrik at pythonware.com Tue Jul 15 07:04:17 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2008 13:04:17 +0200 Subject: SAX XML Parse Python error message In-Reply-To: References: <487A23A5.7000905@behnel.de> Message-ID: goldtech wrote: > I would be grateful for support with the code I cited. It's not long > and fairly standard. I'm sure my error(s) would be glaring to more > experienced coders. I appreciated the "heads-up" about other options > but I would be grateful for help getting this code to run. Thanks For comparison, here's how an experienced Python programmer might prefer to write your code: import xml.etree.cElementTree as ET description = None # most recently seen description for event, elem in ET.parse("somefile.xml"): if elem.tag == "description": description = elem.text elif elem.tag == "coordinates": print description.strip(), elem.text.strip() You may want to ask yourself why you prefer to struggle with obsolete, error-prone, and slow technology when there are more efficient tools available in Python's standard library. (the lxml library that Stefan linked to is a superset of xml.etree, in case you want more XML features). From dsc at ecs.soton.ac.uk Tue Jul 22 07:09:08 2008 From: dsc at ecs.soton.ac.uk (Dave Challis) Date: Tue, 22 Jul 2008 12:09:08 +0100 Subject: Automatically loading and initialising objects from a plugins directory Message-ID: <4885BFD4.9070502@ecs.soton.ac.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I'm trying to write some code which: 1. Finds all modules in a plugin directory 2. Imports those modules 3. Creates an instance of each object defined in the module (each module will contain exactly 1 object, which is a subclass of 'Plugin') The closest I've come so far is with something like: In plugin.py: # taken from http://docs.python.org/lib/built-in-funcs.html def my_import(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod def import_plugins(): mods = [] for filename in os.listdir('/plugins'): if filename.endswith('.py'): name = os.path.splitext(filename)[0] mods.append(my_import('plugins.' + name)) return mods class Plugin(object): pass In plugins/exampleplugin.py: class ExamplePlugin(Plugin): def __init__(self): pass Calling import_plugins() then gives me a list containing references to modules. How can I loop through that list and create an instance of whatever object was defined within the module? (In this case I'd want to construct an instance of ExamplePlugin) Thanks in advance, Dave - -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ( Dave Challis ) ><> ____dsc at ecs.soton.ac.uk_______________________(___________________________ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFIhb/Uv26GZvAVVFERAsGaAJ9KwtFI9yXdk2gBGxy0/bjCd5318wCgsiV9 m14BZSvxqZ1EP0OvaXBZoaw= =TYlD -----END PGP SIGNATURE----- From keith.hughitt at gmail.com Wed Jul 9 15:53:52 2008 From: keith.hughitt at gmail.com (Keith Hughitt) Date: Wed, 9 Jul 2008 12:53:52 -0700 (PDT) Subject: Allow tab completion when inputing filepath? References: Message-ID: <08e60124-51c1-40c1-bffe-52c22ff310db@l64g2000hse.googlegroups.com> On Jul 9, 10:18?am, Tim Golden wrote: > Keith Hughitt wrote: > > I've been looking around on the web for a way to do this, but so far > > have not come across anything for this particular application. I have > > found some ways to enable tab completion for program-related commands, > > but not for system filepaths. This would be nice to have when > > prompting the user to enter a file/directory location. > > What platform are you on? And what kind of display? > (Console / GUI / wxPython / Qt / Web...) > > TJG Hi TJG, Currently Unix/Console. Although I don't have any plans at the moment to add a GUI, it would be great if a cross-platform solution existed. Keith From ptmcg at austin.rr.com Sun Jul 20 01:11:55 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 19 Jul 2008 22:11:55 -0700 (PDT) Subject: Not entirely serious: recursive lambda? References: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> Message-ID: <3eb2d018-3230-49bf-840d-3650b614b016@8g2000hse.googlegroups.com> On Jul 19, 11:49?pm, Miles wrote: > On Sat, Jul 19, 2008 at 10:43 PM, Michael Tobis wrote: > > Can a lambda call itself without giving itself a name? > > Kind of. ?There's a couple ways I know of. > > The functional way, which involves the lambda receiving itself as an argument: > > (lambda f: f(10, f))(lambda n, f: n and (sys.stdout.write("%d\n" % n) > or f(n-1,f))) > > The stack frame examination way: > > import sys, inspect, new > (lambda:sys.stdout.write('recurse\n') or > new.function(inspect.currentframe().f_code, globals())())() > > The functional way is probably harder to grok unless you've studied > lambda calculus or had experience with "real" functional languages (I > haven't). ?For fun, try throwing a Y combinator in there. > > -Miles Here is Michael Tobis's original program, using the functional approach: print (lambda f:f(("",reduce(lambda c,m:c*95+''.join(map(chr,range(32,127))).index(m), "!b)'1Mgh0z+fYQ]g::i^<&y~g)cnE-d=K&{GMNQ1gx +ooY<~L##N'X]P2<@XYXwX3z", 0),f)))(lambda (r,N,f):N and f((" acdefijlmnopqrstuv"[N%19]+r,N/ 19,f))or(r,N,f))[0] Tr?s assombri! (according to Babelfish...). -- Paul From mail at timgolden.me.uk Tue Jul 15 12:18:53 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Jul 2008 17:18:53 +0100 Subject: About wmi In-Reply-To: References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> Message-ID: <487CCDED.2090705@timgolden.me.uk> patrol wrote: > Situation (2): > result = new_process.terminate() > File "C:\Python25\lib\wmi.py", line 494, in __getattr__ > handle_com_error (error_info) > File "C:\Python25\lib\wmi.py", line 190, in handle_com_error > raise x_wmi, "\n".join (exception_string) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > 14: ordinal > not in range(128) > > BTW, My windows' languange is Chinese. Well that looks embarrassingly like a complete lack of unicode-awareness in the wmi module. Would you mind trying this version: http://timgolden.me.uk/wmi-project/wmi.py which is a copy of the svn trunk to see if that improves the UnicodeDecode error, please? I'll try to get an install of a non-English edition of Windows but, as you might imagine, I normally run the UK version so don't hit these kind of issue myself. TJG From sk8in_zombi at yahoo.com.au Fri Jul 11 15:09:25 2008 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Fri, 11 Jul 2008 12:09:25 -0700 (PDT) Subject: Filechooser issues Message-ID: <576590.26999.qm@web54501.mail.re2.yahoo.com> Hi, I am using a gtk.filechooser dialog to open and save files.How do I add a filter so that only images are filtered ?I did something like this: ??? def get_save_filename(self): ??? ??????? filename = None ??????? chooser = gtk.FileChooserDialog("Save File...", self.window, ??????????????????????????????????????? gtk.FILE_CHOOSER_ACTION_SAVE, ??????????????????????????????????????? (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, ???????????????????????????????????????? gtk.STOCK_SAVE, gtk.RESPONSE_OK)) ??? ff = gtk.FileFilter.add_pixbuf_formats() ??????? chooser.add_filter(ff) ??????? response = chooser.run() ??????? if response == gtk.RESPONSE_OK: filename = chooser.get_filename() ??????? chooser.destroy() ??????? ??????? return filename Now I get an error when I add ff or a filefilter .The error is : Traceback (most recent call last): ? File "tutorial.py", line 91, in on_save_as_menu_item_activate ??? filename = self.get_save_filename() ? File "tutorial.py", line 231, in get_save_filename ??? ff = gtk.FileFilter.add_pixbuf_formats() TypeError: descriptor 'add_pixbuf_formats' of 'gtk.FileFilter' object needs an argument The documentation doesn't say anything about an argument to be passed: http://www.pygtk.org/docs/pygtk/class-gtkfilefilter.html#method-gtkfilefilter--add-pixbuf-formats Regards, SZ " life isn't heavy enough,it flies away and floats far above action" Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: From nicolas.pourcelot at gmail.com Mon Jul 21 04:58:17 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Mon, 21 Jul 2008 01:58:17 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> <6ebshqF67cpfU4@mid.uni-berlin.de> <5d6b8066-c941-4f0c-abea-20baed33b4ab@l64g2000hse.googlegroups.com> <6eg02pF6uhc3U2@mid.uni-berlin.de> Message-ID: <94b55395-f89e-4dda-828b-505dacdabeb4@l64g2000hse.googlegroups.com> On 20 juil, 07:17, Marc 'BlackJack' Rintsch wrote: > On Sat, 19 Jul 2008 13:13:40 -0700, nicolas.pourcelot wrote: > > On 18 juil, 17:52, Marc 'BlackJack' Rintsch wrote: > >> On Fri, 18 Jul 2008 07:39:38 -0700, nicolas.pourcelot wrote: > >> > So, I use something like this in 'sheet.objects.__setattr__(self, > >> > name, value)': > >> > if type(value) == Polygon: > >> > ? ? for edge in value.edges: > >> > ? ? ? ? if edge is_in sheet.objects.__dict__.itervalues(): > >> > ? ? ? ? ? ? object.__setattr__(self, self.__new_name(), edge) > > >> > Ok, I suppose it's confused, but it's difficult to sum up. ;-) > > >> You are setting attributes with computed names? ?How do you access them? > >> Always with `gettattr()` or via the `__dict__`? ?If the answer is yes, why > >> don't you put the objects the into a dictionary instead of the extra > >> redirection of an objects `__dict__`? > > > Yes, I may subclass dict, and change its __getitem__ and __setitem__ > > methods, instead of changing objets __setattr__ and __getattr__... But > > I prefer > >>>> sheet.objects.A = Point(0, 0) > > than > >>>> sheet.objects["A"] = Point(0, 0) > > But with computed names isn't the difference more like > > setattr(sheet.objects, name, Point(0, 0)) > vs. > sheet.objects[name] = Point(0, 0) > > and > > getattr(sheet.objects, name) > vs. > sheet.objects[name] > > Or do you really have ``sheet.objects.A`` in your code, in the hope that > an attribute named 'A' exists? > > >> Oh and the `type()` test smells like you are implementing polymorphism > >> in a way that should be replaced by OOP techniques. > > > I wrote 'type' here by mistake, but I used 'isinstance' in my code. ;-) > > Doesn't change the "code smell". ?OOP approach would be a method on the > geometric objects that know what to do instead of a type test to decide > what to do with each type of geometric object. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch Thank you for your advises, it's very interesting to have an external point of view. No, I have not anything like 'sheet.objects.A' in the library code, but I use then the library in different programs where things like sheet.objects.A sometimes occur. However, since it is not so frequent, I may indeed subclass dict, and change __getitem__, __setitem__ and __delitem__, and then redirect __getattr__, __setattr__, __delattr__ to previous methods... This would not break library external API, and it may speed-up a little internal stuff. I'm not very expert in OOP ; imho it's largely a mean and not a goal. On one hand, 'a method on the geometric objects that know what to do' would require them to contain some code concerning the object manager... I don't like that very much. On the other hand, object manager should not rely on object's implementation... I will think about that. Thank you all of you for your answers. I'm sorry I may not have time to reply further, it was interesting :-) (even if it's a bit difficult for me to write clearly in english ;-)) From casevh at gmail.com Sat Jul 5 15:04:51 2008 From: casevh at gmail.com (casevh) Date: Sat, 5 Jul 2008 12:04:51 -0700 (PDT) Subject: conflict between multiple installs of python (linux) References: <6bd22c06-a1e6-4247-9aff-2d0b29b1ec5e@d1g2000hsg.googlegroups.com> Message-ID: <6993e25b-7f81-4584-9c28-b5565cda7fcc@a70g2000hsh.googlegroups.com> On Jul 5, 11:09?am, david wrote: > You learn something new every day: > > On my ubuntu, update-manager is supposed to use the python2.5 > installed on /usr/bin. Well, I had subsequently installed a whole > bunch of stuff in /usr/local (/usr/local/bin/python and /usr/local/lib/ > python2.5 etc), which I have happily been using for development for a > year. I had thought that the two pythons were completely independent. > > Well, I was wrong. When /usr/bin/python2.5 runs, *by default*, it > adds /usr/local/lib/python2.5 to its sys path - and apparently there > are things in /usr/local which are inconsistent with those at /usr > (not suprising). > > I have fixed the problem - but I had to modify the actual update- > manager .py file itself. At the beginning, I set the sys.path in > python *explicitly* to not include the /usr/local stuff. > > But this is clearly a kludge. My question: how do I keep the Ubuntu > python stuff at /usr/bin/python2.5 from adding /usr/local/lib/ > python2.5 to the import search path in a clean and global way? I > really want both pythons completely isolated from one another! > > Thankyou. Python's path is build by site.py. In the file /usr/lib/python2.5/ site.py, look for the line "prefixes.insert(0, '/usr/local')" and comment it out. That should do it. casevh From notontheweb at noisp.com Sat Jul 26 13:52:51 2008 From: notontheweb at noisp.com (Jive Dadson) Date: Sat, 26 Jul 2008 17:52:51 GMT Subject: urllib and login with passwords Message-ID: Hey folks! There are various web pages that I would like to read using urllib, but they require login with passwords. Can anyone tell me how to find out how to do that, both in general and specifically for YouTube.com. Thankee. From mrkafk at gmail.com Thu Jul 17 10:57:08 2008 From: mrkafk at gmail.com (mk) Date: Thu, 17 Jul 2008 16:57:08 +0200 Subject: property getter with more than 1 argument? Message-ID: It seems like getter is defined in such way that it passes only 'self': class FunDict(dict): def __init__(self): self.fundict = dict() def fget(self, fun): return fundict[fun.func_name] def fset(self, newfun): self.fundict[newfun.func_name] = newfun newfun = property (fget, fset) >>> a=FunDict() >>> >>> a.newfun=f1 >>> >>> a.newfun('f1') Traceback (most recent call last): File "", line 1, in a.newfun('f1') TypeError: fget() takes exactly 2 arguments (1 given) Is it possible to pass more than one argument to fget function? I know: I can define a function with property name ('newfun' in the example) and call it with more arguments. But then I do not get the benefits of setter and property in general! From deets at nospam.web.de Fri Jul 11 05:59:55 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 11 Jul 2008 11:59:55 +0200 Subject: Question about: GUI Builder for Tkinter and call to C/C++ code In-Reply-To: References: Message-ID: <6dop8uF3lhrqU1@mid.uni-berlin.de> pauladospublicidad schrieb: > First I'll introduce myself. I normally programm in C/C++ and Java. > Sometimes I have to mix them (normally using C/C++ in java, because in > java is easier to make portable graphic user interfaces). However to > use C/C++ code in java is really complex and difficult. > > Not too much time ago, I discover python. I had think to use it for > developing portable graphic user intefaces, that will call my C/C++ > code / libraries / programs. > > I had thought to use tkinter for making the GUIs, for portability and > for not installing anything more than python. It's to say, for not > adding more packages because I'm new in python and I don't now too > much about install new packages. > > I have seen that for wxpython there is gui builders (such as boa) but > for tkinter I have not found anyon. I would like to know if anyone > knows a GUI Builder for tkinter in order to develop my GUI's > graphically and in a easier way. AFAIK there is none, at least not usable with python. However, back when I did tk, I found it easy and clear enough (especially with the powerful layout managemnt) to hand-craft the GUI. > Apart from this, I would like to call my C/C++ code / modulles / > applications from python. I have read that python is implemented > normally in C, so is easy to add new modules from C. I would like to > find any tutorial / manual / link for dummies in order to make this > (call my C code from python). There are various options, depending on if you are real about using C, or if you are more into C++. If you *can*, you should IMHO rely on a C-API (potentially layering a C++-lib). Then you can use the since python2.5 build-in ctypes-module to access any DLL/shared library you like. For extending and embedding, see the official docs: http://docs.python.org/ext/ext.html For C++ wrappers, there are several available: - SWIG - Boost::Python - SIP (used to wrap the great Qt gui toolkit) I can personally recommend the latter, others MMV. > Another solution could be to call the GUI made in python from C/C++ > code, but I'm sure this would be more complex. You don't want this, no. It's possible, but needlessly complex. HTH, Diez From mrkafk at gmail.com Mon Jul 21 12:06:45 2008 From: mrkafk at gmail.com (mk) Date: Mon, 21 Jul 2008 18:06:45 +0200 Subject: Seriously, though, about LLVM Message-ID: http://llvm.org/ This project has gained some publicity. There's IronPython, right, so has anybody thought about implementing Python using LLVM as backend, as it seems not out of question at all? From bourdenas at gmail.com Mon Jul 28 14:10:05 2008 From: bourdenas at gmail.com (Themis Bourdenas) Date: Mon, 28 Jul 2008 19:10:05 +0100 Subject: Module clarification In-Reply-To: <488E0887.6070803@internetnowasp.net> References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> <488E0887.6070803@internetnowasp.net> Message-ID: <7fd737460807281110y36a1e9dfk63ea7d692d9f8cb7@mail.gmail.com> I would recommend dive into python. Its available free online (just google it) and it tries to teach you python, not programming which unfortunately many books try to do. It assumes that you already have some experience with C++ or Java and contradicts python syntax/semantics to those languages. Very useful and fast if you already know how to program. Cheers, Themis On Mon, Jul 28, 2008 at 6:57 PM, Marcus.CM wrote: > Hi Hussein, > > Basically a module is a FILE and is considered as a singleton model. Yes ur > wow.py assumption is correct. > I recommend getting Mark Lutz Learning Python book to get you started. > > Marcus.CM > > > Hussein B wrote: > >> Hi. >> I'm a Java guy and I'm playing around Python these days... >> In Java, we organize our classes into packages and then jarring the >> packages into JAR files. >> What are modules in Python? >> What is the equivalent of modules in Java? >> Please correct me if I'm wrong: >> I saved my Python code under the file Wow.py >> Wow.py is now a module and I can use it in other Python code: >> import Wow >> >> Thanks. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> >> > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Fri Jul 18 15:10:33 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Jul 2008 19:10:33 GMT Subject: __del__ methods References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> Message-ID: <6ec859F67cpfU5@mid.uni-berlin.de> On Fri, 18 Jul 2008 11:31:20 -0700, Jason Baker wrote: > I have a class that I need to do some finalization on when it dies. I > know I can use the __del__ method, but I seem to recall that it > impedes garbage collection. Is this the case? `__del__()` is not a deterministic destructor. So forget about reliable automatic clean up. Do it yourself with an explicit call to a `close()` method or something like that. Ciao, Marc 'BlackJack' Rintsch From timr at probo.com Sun Jul 6 01:02:13 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 06 Jul 2008 05:02:13 GMT Subject: Python with Ecmascript References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> Message-ID: <8ek074tia4l47tcfo6tqfo9huv2hb68hkt@4ax.com> "jiri.zahradil at gmail.com" wrote: > >for my Python application (Windows platform) to be standards >compliant, I need to embbed Ecmascript(Javascript) interpreter - I >need to execute plugins written in this language. What standard are you hoping to comply with? I mean, what kind of a program is this? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mensanator at aol.com Mon Jul 14 16:26:19 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 14 Jul 2008 13:26:19 -0700 (PDT) Subject: new itertools functions in Python 2.6 Message-ID: <4dd80ff2-5fda-405a-a637-08c985ff8add@e53g2000hsa.googlegroups.com> With the new functions added to itertools in Python 2.6, I can finally get rid of this monstrosity: def ooloop6(a, n, perm=True, repl=True): if (not repl) and (n>len(a)): return r0 = range(n) r1 = r0[1:] if perm and repl: # ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) e = ''.join(["p = [''.join((",v,")) ",f,"]"]) exec e return p if (not perm) and repl: # ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) i = ' and '.join(['(c%s>=c%s)' % (j,j-1) for j in r1]) e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"]) exec e return p if perm and (not repl): # ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) i = ' and '.join([' and '.join(['(c%s!=c%s)' % (j,k) for k in range(j)]) for j in r1]) e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"]) exec e return p if (not perm) and (not repl): # ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) i = ' and '.join(['(c%s>c%s)' % (j,j-1) for j in r1]) e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"]) exec e return p If I use a single iterable with the repeat option, the Carteisan Product will give me Permutaions With Replacement. from itertools import * from math import factorial as fac s = 'abcde' m = len(s) n = 3 print 'For %d letters (%s) taken %d at a time:' % (m,s,n) print '========================================' ### Permutations with replacement m**n ### print 'Permutations with replacement' print '-----------------------------' p = [i for i in product('abcde',repeat=3)] for i in p: print ''.join(i), print print print 'actual words: %d m**n words: %d' % (len(p),m**n) print ## For 5 letters (abcde) taken 3 at a time: ## ======================================== ## Permutations with replacement ## ----------------------------- ## aaa aab aac aad aae aba abb abc abd abe aca acb ## acc acd ace ada adb adc add ade aea aeb aec aed ## aee baa bab bac bad bae bba bbb bbc bbd bbe bca ## bcb bcc bcd bce bda bdb bdc bdd bde bea beb bec ## bed bee caa cab cac cad cae cba cbb cbc cbd cbe ## cca ccb ccc ccd cce cda cdb cdc cdd cde cea ceb ## cec ced cee daa dab dac dad dae dba dbb dbc dbd ## dbe dca dcb dcc dcd dce dda ddb ddc ddd dde dea ## deb dec ded dee eaa eab eac ead eae eba ebb ebc ## ebd ebe eca ecb ecc ecd ece eda edb edc edd ede ## eea eeb eec eed eee ## ## actual words: 125 m**n words: 125 So what does "permutaions" mean in itertools? It actually means Permutions Without Replacement. ### Permutations without replacement m!/(m-n)! ### print 'Permutations without replacement' print '--------------------------------' p = [i for i in permutations('abcde',3)] for i in p: print ''.join(i), print print print 'actual words: %d m!/(m-n)! words: %d' % (len(p),fac(m)/fac(m- n)) print ## Permutations without replacement ## -------------------------------- ## abc abd abe acb acd ace adb adc ade aeb aec aed ## bac bad bae bca bcd bce bda bdc bde bea bec bed ## cab cad cae cba cbd cbe cda cdb cde cea ceb ced ## dab dac dae dba dbc dbe dca dcb dce dea deb dec ## eab eac ead eba ebc ebd eca ecb ecd eda edb edc ## ## actual words: 60 m!/(m-n)! words: 60 Not surprisingly, "combinations" actually means Combinations Without Replacement. ### Combinations without replacement m!/(n!(m-n)!) ### print 'Combinations without replacement' print '--------------------------------' p = [i for i in combinations('abcde',3)] for i in p: print ''.join(i), print print print 'actual words: %d m!/(n!(m-n)!) words: %d' % (len(p),fac(m)/ (fac(n)*factorial(m-n))) print ## Combinations without replacement ## -------------------------------- ## abc abd abe acd ace ade bcd bce bde cde ## ## actual words: 10 m!/(n!(m-n)!) words: 10 Hmm...that's only three subsets of the Cartesian Product. No Combinations With Replacement. Although you can always filter the Cartesian Product to get a subset. # Combinations with replacement (m+n-1)!/(n!(m-1)!) # print 'Combinations with replacement' print '-----------------------------' p = [i for i in ifilter(lambda x: list(x)==sorted(x),product('abcde',repeat=3))] for i in p: print ''.join(i), print print print 'actual words: %d (m+n-1)!/(n!(m-1)!) words: %d' % (len(p),fac(m+n-1)/(fac(n)*fac(m-1))) print ## Combinations with replacement ## ----------------------------- ## aaa aab aac aad aae abb abc abd abe acc acd ace ## add ade aee bbb bbc bbd bbe bcc bcd bce bdd bde ## bee ccc ccd cce cdd cde cee ddd dde dee eee ## ## actual words: 35 (m+n-1)!/(n!(m-1)!) words: 35 Although it works, it's somewhat slow as we have to iterate over the entire Cartesian Product and the filter list(x)==sorted(x) has got to be expensive (it's slower than the nested loop algorithm). Is there a better way to get Combinations With Replacement using itertools? From kris at FreeBSD.org Mon Jul 7 15:27:43 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Mon, 07 Jul 2008 21:27:43 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: <48726E2F.5030503@FreeBSD.org> Paddy wrote: > On Jul 4, 1:36 pm, Peter Otten <__pete... at web.de> wrote: >> Henning_Thornblad wrote: >>> What can be the cause of the large difference between re.search and >>> grep? >> grep uses a smarter algorithm ;) >> >> >> >>> This script takes about 5 min to run on my computer: >>> #!/usr/bin/env python >>> import re >>> row="" >>> for a in range(156000): >>> row+="a" >>> print re.search('[^ "=]*/',row) >>> While doing a simple grep: >>> grep '[^ "=]*/' input (input contains 156.000 a in >>> one row) >>> doesn't even take a second. >>> Is this a bug in python? >> You could call this a performance bug, but it's not common enough in real >> code to get the necessary brain cycles from the core developers. >> So you can either write a patch yourself or use a workaround. >> >> re.search('[^ "=]*/', row) if "/" in row else None >> >> might be good enough. >> >> Peter > > It is not a smarter algorithm that is used in grep. Python RE's have > more capabilities than grep RE's which need a slower, more complex > algorithm. > You could argue that if the costly RE features are not used then maybe > simpler, faster algorithms should be automatically swapped in but .... I can and do :-) It's a major problem that regular expression parsing in python has exponential complexity when polynomial algorithms (for a subset of regexp expressions, e.g. excluding back-references) are well-known. It rules out using python for entire classes of applications where regexp parsing is on the critical path. Kris From rocksportrocker at googlemail.com Wed Jul 2 04:38:56 2008 From: rocksportrocker at googlemail.com (rocksportrocker) Date: Wed, 2 Jul 2008 01:38:56 -0700 (PDT) Subject: distutils - setup - lib problem Message-ID: <6138c75a-601e-4c44-b765-364cadb16098@l64g2000hse.googlegroups.com> Hi, I've got some problems with the following setup.py file. using "python setup.py install -f" it shows that wrap_ica.so is copied to /usr and not to ..../site-packages as I assumed. What am I doing wrong ? I'm using Python 2.4 on Debian Linux. ----------------------------------------------------- from distutils.core import setup import glob setup(name='py_ica', py_modules=['py_ica'], data_files=[(".", ["wrap_ica.so"]), ] ) ----------------------------------------------------- Greetings, Uwe From Russ.Paielli at gmail.com Sun Jul 27 02:47:05 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 26 Jul 2008 23:47:05 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: On Jul 26, 11:22 pm, Terry Reedy wrote: > Russ P. wrote: > > On Jul 26, 2:25 pm, Terry Reedy > >> There is a lot of code you have not seen. Really. In informal code I > >> use 's' and 'o' for 'self' and 'other'. I don't usually post such > >> because it is not considered polite. So you have seen a biased sample > >> of the universe. > > > You take the name down to a single letter. As I suggested in an > > earlier post on this thread, why not take it down to zero letters? > > Because 1 letter is legal now, while no letters (already proposed and > rejected) is a major change and breakage of current simplicity and > consistency for zero functional benefit. Sorry, but I fail to see how it is a "major change." It only applies to the first argument of a class member function, and the parser only needs to look for an empty argument or a period. Furthermore, it would break no working code. It may indeed have been "proposed and rejected," but it would be a nice way to clean up code in many areas, and as long as it cannot break any working code, I think it should be reconsidered. From motoom at xs4all.nl Tue Jul 15 10:06:48 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Tue, 15 Jul 2008 16:06:48 +0200 Subject: Type Problem Message-ID: <2.2.32.20080715140648.0125a124@pop.xs4all.nl> Victor wrote... >len = len(dirs) The function 'len' is a built-in function in Python. If you assign an integer to the name 'len', that will replace the function with an int. And you can't call an int. My suggestion: Do not use 'len' as a variable name. Use something else, like: directorycount=len(dirs) Greetings, >>> type(len) >>> print len("Victor") 6 >>> len=42 >>> type(len) >>> len("Victor") Traceback (most recent call last): File "", line 1, in len("Victor") TypeError: 'int' object is not callable -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From deets at nospam.web.de Wed Jul 2 15:09:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Jul 2008 21:09:44 +0200 Subject: Pyro: ProtocolError('connection failed') In-Reply-To: References: Message-ID: <6d223oFetjoU1@mid.uni-berlin.de> jamitwidme at gmail.com schrieb: > Hello everyone > Can someone help me fix this problem? > > I am using an example from Pyro(Python Remote Object) website > directly. > It is the last example from > http://pyro.sourceforge.net/manual/8-example.htm > > I have two computers to run Server and Client. > ############################################ > server.py > > import Pyro.naming > import Pyro.core > from Pyro.errors import PyroError,NamingError > > > ###### testclass Pyro object > > class testclass(Pyro.core.ObjBase): > def mul(s, arg1, arg2): return arg1*arg2 > def add(s, arg1, arg2): return arg1+arg2 > def sub(s, arg1, arg2): return arg1-arg2 > def div(s, arg1, arg2): return arg1/arg2 > > ###### main server program > > def main(): > Pyro.core.initServer() > daemon = Pyro.core.Daemon() > # locate the NS > locator = Pyro.naming.NameServerLocator() > print 'searching for Name Server...' > ns = locator.getNS(host='drizzle.des.hep.uiuc.edu', port=9090) > daemon.useNameServer(ns) > > # connect a new object implementation (first unregister > previous one) > try: > # 'test' is the name by which our object will be known > to the outside world > ns.unregister('test') > except NamingError: > pass > > # connect new object implementation > daemon.connect(testclass(),'test') > > # enter the server loop. > print 'Server object "test" ready.' > daemon.requestLoop() > > if __name__=="__main__": > main() > > ################################### > > ################################### > client.py > > import Pyro.naming, Pyro.core > from Pyro.errors import NamingError > > # locate the NS > locator = Pyro.naming.NameServerLocator() > print 'Searching Name Server...', > ns = locator.getNS(host='drizzle.des.hep.uiuc.edu',port=9090) > > # resolve the Pyro object > print 'finding object' > try: > URI=ns.resolve('test') > print 'URI:',URI > except NamingError,x: > print 'Couldn\'t find object, name server says:',x > raise SystemExit > > # create a proxy for the Pyro object, and return that > test = Pyro.core.getProxyForURI(URI) > > print test.mul(111,9) > print test.add(100,222) > print test.sub(222,100) > print test.div(2.0,9.0) > print test.mul('*',10) > print test.add('String1','String2') > ####################################### > > It does not matter which computer Pyro NameServer is located. > When Server and Client are in a same computer, it works perfectly > fine. > But whenever Server and Client run in different computers, I get a > following error message. > > > ######################################## > Pyro Client Initialized. Using Pyro V3.7 > Searching Name Server... finding object > URI: PYRO://127.0.0.1:7888/7f000001193649ab6a89d5592bc843bb > Traceback (most recent call last): > File "client.py", line 22, in > print test.mul(111,9) > File "/usr/local/lib/python2.5/site-packages/Pyro/core.py", line > 390, in __call__ > return self.__send(self.__name, args, kwargs) > File "/usr/local/lib/python2.5/site-packages/Pyro/core.py", line > 467, in _invokePYRO > self.adapter.bindToURI(self.URI) > File "/usr/local/lib/python2.5/site-packages/Pyro/protocol.py", line > 255, in bindToURI > raise ProtocolError('connection failed') > Pyro.errors.ProtocolError: connection failed > ######################################## > > Thanks a lot. THis is just a guess - but it seems that somehow you don't bind your pyro objects to the NIC's IP address, but to localhost (127.0.0.1) - which of course won't work. That never happened to me though, try and see the pyro docs on how to prevent/control to which IP a proxy is bound. Diez From alexandru.palade at sellerengine.com Mon Jul 21 08:21:49 2008 From: alexandru.palade at sellerengine.com (Alexandru Palade) Date: Mon, 21 Jul 2008 15:21:49 +0300 Subject: Odd math related issue. In-Reply-To: References: <43332.3139710867$1216630189@news.gmane.org> Message-ID: <48847F5D.9080509@sellerengine.com> However, you should be carefully because using an %i modifier for a what-should-be a float value truncates the value in a way you may not expect. What I mean is that if you have sent 2 out of 3 bytes, the math will be 200/3 which with the %i modifier will print 66, rather than 66.6 (or at least 67 which is closer - have a look at the round() function). Another thing, you could have just added a dot after the constant in order to promote the expression to be evaluated as float. As in percentage = bytes_transferred / /self/.__sessions[path].total_bytes * 100. (notice the last dot) Fredrik Lundh wrote: > Robert Rawlins wrote: > >> I?ve got what seems to me to be a totally illogical math issue here >> which I can?t figure out. Take a look at the following code: >> >> /self/.__logger.info(/"%i / %i"/ % (bytes_transferred, >> /self/.__sessions[path].total_bytes)) >> >> percentage = bytes_transferred / >> /self/.__sessions[path].total_bytes * 100 >> >> /self/.__logger.info(/"%i"/ % percentage) >> >> Seems fairly straight forward, you would think. It takes two values >> and calculates the percentage of one from the other, however, >> percentage always comes back as ?0? for some reason, look at this log >> output. > > if you divide two integers, you'll get an integer back (in Python 2.X, > at least). quick fix: > > percentage = bytes_transferred * 100 / total_bytes > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Mon Jul 21 18:04:45 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 21 Jul 2008 18:04:45 -0400 Subject: Python Written in C? In-Reply-To: References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> Message-ID: mk wrote: > Seriously, though, would there be any advantage in re-implementing > Python in e.g. C++? Considered and rejected by Guido and the CPython developer crew. Anyone who wants C++Python is free to make one, just as people have done JavePython (Jython), C#Python, (IonPython), PythonPython (PyPy), and compiled-CPython (multiple). > Not that current implementation is bad, anything but, but if you're not > careful, the fact that lists are implemented as C arrays can bite your > rear from time to time (it recently bit mine while using lxml). Suppose > C++ re-implementation used some other data structure (like linked list, > possibly with twists like having an array containing pointers to 1st > linked list elements to speed lookups up), which would be a bit slower > on average perhaps, but it would behave better re deletion? This is a data structure issue, not a language issue. The tradeoffs for practical implementation include code-length, code-complexity, code-fragility, and ease of cross-platform compilation as well as classical time and space issues. tjr From bignose+hates-spam at benfinney.id.au Fri Jul 4 03:12:49 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 04 Jul 2008 17:12:49 +1000 Subject: Singleton implementation problems References: Message-ID: <87abgy2kcu.fsf@benfinney.id.au> Peter Otten <__peter__ at web.de> writes: > The problem is the structure of your program. The myset module is > imported twice by Python, once as "myset" and once as "__main__". Yes, this is the problem. Each module imports the other. > Therefore you get two distinct MySet classes, and consequently two > distinct MySet.__instance class attributes. Are you sure? This goes against my understanding: that 'import foo' will not re-import a module that's already been imported, but will instead simply return the existing module. So, I think if one evaluated 'myset is __main__', you'd find they are exactly the same module under different names; and therefore that there is only *one* instance of 'MySet', again under two names. -- \ ?Science doesn't work by vote and it doesn't work by | `\ authority.? ?Richard Dawkins, _Big Mistake_ (The Guardian, | _o__) 2006-12-27) | Ben Finney From kyrie at uh.cu Wed Jul 9 06:06:44 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 09 Jul 2008 06:06:44 -0400 Subject: Returning the positions of a list that are non-zero In-Reply-To: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> References: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> Message-ID: <1215598004.48748db468ec1@comuh.uh.cu> This could work: l = [0,0,1,2,1,0,0] indexes, values = zip(*((index,value) for index,value in enumerate(l) if value != 0)) But I guess it would be a little less cryptic (and maybe a lot more efficient) if there were an unzip function instead of using the zip(*sequence) trick. I think a more readable way would be: indexes = [index for index,value in enumerate(l) if value != 0] values = [value for value in l if value != 0] Cheers. -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie Quoting Benjamin Goudey : > I have a very large list of integers representing data needed for a > histogram that I'm going to plot using pylab. However, most of these > values (85%-95%) are zero and I would like to remove them to reduce > the amount of memory I'm using and save time when it comes to plotting > the data. To do this, I'm trying to find the best way to remove all of > the zero values and produce a list of indices of where the non-zero > values used to be. > > For example, if my original list is [0,0,1,2,1,0,0] I would like to > produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices > of where the non-zero values used to be). Removing non-zero values is > very easy but determining the indicies is where I'm having difficulty. > > Thanks in advance for any help > -- > http://mail.python.org/mailman/listinfo/python-list > From stefan_ml at behnel.de Thu Jul 3 15:04:47 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 03 Jul 2008 21:04:47 +0200 Subject: ANN: XML builder for Python In-Reply-To: References: <486C5CA1.3080105@behnel.de> <486C5D63.5030407@behnel.de> Message-ID: <486D22CF.3000505@behnel.de> Hi, Walter D?rwald wrote: > XIST has been using with blocks since version 3.0. > > Take a look at: > http://www.livinglogic.de/Python/xist/Examples.html > > > from __future__ import with_statement > > from ll.xist import xsc > from ll.xist.ns import html, xml, meta > > with xsc.Frag() as node: > +xml.XML() > +html.DocTypeXHTML10transitional() > with html.html(): > with html.head(): > +meta.contenttype() > +html.title("Example page") > with html.body(): > +html.h1("Welcome to the example page") > with html.p(): > +xsc.Text("This example page has a link to the ") > +html.a("Python home page", href="http://www.python.org/") > +xsc.Text(".") > > print node.conv().bytes(encoding="us-ascii") Interesting. Is the "+" actually required? Are there other operators that make sense here? I do not see what "~" or "-" could mean. Or is it just a technical constraint? I'm asking because I consider adding such a syntax to lxml as a separate module. And I'd prefer copying an existing syntax over a (badly) home grown one. Stefan From karthikbalaguru79 at gmail.com Thu Jul 24 05:33:01 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Thu, 24 Jul 2008 02:33:01 -0700 (PDT) Subject: Requires a character ... !! References: Message-ID: On Jul 24, 2:20 pm, Fredrik Lundh wrote: > karthikbalaguru wrote: > > I am new to python . I am face few problems related with > > python and iam trying to resolve it. > > > The below is the error that i get when i invoke my application by > > giving > > the necessary input file. > > > [root at localhost hello]# Analyzer hello_input > > Loading debug info: hello_input > > Traceback (most recent call last): > > File "/usr/local/SDK/host/bin/Analyzer", line 694, in ? > > app.dbg.readObjectInfo(elf) > > File "/usr/local/SDK/host/bin/debugprocessor.py", line 427, in > > readObjectInfo > > self.privateProcessorDwarfTree.readProcessorDwarfTree(filename) > > File "/usr/local/SDK/bin/debugprocessor.py", line 314, in > > readDwarfTree > > if "DW_OP_reg" in value: > > TypeError: 'in ' requires character as left operand > > > Is this related with the version conflicts ? > > Should i need to configure any environment variables or change some > > source code. > > You should run the code on a Python version that supports the features > your code is using. Support for arbitrary strings on the left side of > the "in" operator was added in Python 2.3, which was released in 2003. > Thx for that info. I understand. The requirements state that it needs Python 2.2, But i wonder how that program has been implemented using Python 2.3 features. Anyhow, this has to be resolved and i need your help. Kindly let me know a trick to make to resolve the 'in' operator related problem by using Python 2.2. Thx in advans, Karthik Balaguru From bronger at physik.rwth-aachen.de Thu Jul 24 05:40:46 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 24 Jul 2008 11:40:46 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> Message-ID: <874p6fzkkh.fsf@physik.rwth-aachen.de> Hall?chen! Bruno Desthuilliers writes: > [...] > > How would you handle this case with an implicit 'self' : > > class Foo(object): > pass > > def bar(self): > print self > > Foo.bar = bar Just like this. However, the compiler could add "self" to non-decorated methods which are defined within "class". Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From AWasilenko at gmail.com Thu Jul 31 00:36:51 2008 From: AWasilenko at gmail.com (Adam W.) Date: Wed, 30 Jul 2008 21:36:51 -0700 (PDT) Subject: Unicode characters, XML/RSS Message-ID: <832add51-92e1-4420-9279-5b503b453869@u6g2000prc.googlegroups.com> So I wrote a little video podcast downloading script that checks a list of RSS feeds and downloads any new videos. Every once in a while it find a character that is out of the 128 range in the feed and my script blows up: Traceback (most recent call last): File "C:\Users\Adam\Desktop\Rev3 DL\Rev3.py", line 88, in mainloop() File "C:\Users\Adam\Desktop\Rev3 DL\Rev3.py", line 75, in mainloop update() File "C:\Users\Adam\Desktop\Rev3 DL\Rev3.py", line 69, in update couldhave = getshowlst(x[1],episodecnt) File "C:\Users\Adam\Desktop\Rev3 DL\Rev3.py", line 30, in getshowlst masterlist = XMLWorkspace.parsexml(url) File "C:\Users\Adam\Desktop\Rev3 DL\XMLWorkspace.py", line 54, in parsexml parse(url, FeedHandlerInst) File "C:\Python25\lib\xml\sax\__init__.py", line 33, in parse parser.parse(source) File "C:\Python25\lib\xml\sax\expatreader.py", line 107, in parse xmlreader.IncrementalParser.parse(self, source) File "C:\Python25\lib\xml\sax\xmlreader.py", line 123, in parse self.feed(buffer) File "C:\Python25\lib\xml\sax\expatreader.py", line 207, in feed self._parser.Parse(data, isFinal) File "C:\Users\Adam\Desktop\Rev3 DL\XMLWorkspace.py", line 51, in characters self.data.append(string) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 236: ordinal not in range(128) Now its my understanding that XML can contain upper Unicode characters as long as the encoding is specified, which it is (UTF-8). The feed validates every validator I've ran it through, every program I open it with seems to be ok with it, except my python script. Why? Here is the URL of the feed in question: http://revision3.com/winelibraryreserve/ My script is complaining of the fancy e in Mourv?dre At first glance I though it was the data.append(string) that was un accepting of the Unicode, but even if I put a return in the Character handler loop, it still breaks. What am I doing wrong? From Russ.Paielli at gmail.com Sat Jul 26 23:21:17 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 26 Jul 2008 20:21:17 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <517d1643-3ae1-442b-9764-6c1847065207@p10g2000prf.googlegroups.com> On Jul 26, 7:23 pm, "Marcus.CM" > 1. python should hardcode the keyword "self". So whenever this keyword > is used, it would automatically implied that it is > referring to a class scope variable. This would be similar to how the > "this" keyword is used in C++. > > 2. Omit self from the parameter. That might make sense if you're starting from scratch on a new language, but it is not compatible with Python as it is currently stands. Yes, it could have been put into 3.0, but it's way too late now for a change that drastic. Beyond that, I don't like the idea of being forced to use "self" in every case. Yes, C++ and Java standardized on "this," but it is implied and is usually not explicitly needed. From feliphil at gmx.net Thu Jul 10 10:42:17 2008 From: feliphil at gmx.net (Wolfgang Keller) Date: Thu, 10 Jul 2008 16:42:17 +0200 Subject: Does omniORBpy 3.2 supports DII? References: Message-ID: <20080710164217.da8448a3.feliphil@gmx.net> > My apologies if this is not the correct forum for thses quiestions, It's not the wrong place to ask, but you're more likely to get answers from the omniORB mailing lists: http://www.omniorb-support.com/mailman/listinfo Sincerely, Wolfgang From tjreedy at udel.edu Tue Jul 29 15:43:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 15:43:51 -0400 Subject: Swap memory in Python ? - three questions In-Reply-To: <642068.13334.qm@web55102.mail.re4.yahoo.com> References: <642068.13334.qm@web55102.mail.re4.yahoo.com> Message-ID: Robert LaMarca wrote: > Hi, > > I am using numpy and wish to create very large arrays. My system is AMD 64 x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a 15 GB swap drive. > > The command I have been trying to use is; > g=numpy.ones([1000,1000,1000],numpy.int32) > > This returns a memory error. > A smaller array ([500,500,500]) worked fine.. > Two smaller arrays again crashed the system. > > So... I did the math. a 1000x1000x1000 array at 32 bits should be around 4gb RAM... Obviously larger than RAM, but much smaller than the swap drive. > > 1. So... does Numpy have a really lot of overhead? Or is my system just not somehow getting to make use of the 15gb swap area. > 2. Is there a way I can access the swap area, or direct numpy to do so? Or do I have to write out my own numpy cache system... > 3. How difficult is it to use data compression internally on numpy arrays? I do not know what numpy does, but constant arrays only need to store the dimensions and the constant value and have a getitem method that returns that constant value for any valid index. This is at most a few hundred bytes regardless of the dimensions. From arsyed at gmail.com Wed Jul 30 01:21:39 2008 From: arsyed at gmail.com (arsyed) Date: Wed, 30 Jul 2008 01:21:39 -0400 Subject: Dynamically adding methods to a class... In-Reply-To: <19ac19520807282117y4c34ed22n3bcb9c6cf7d198b8@mail.gmail.com> References: <19ac19520807282117y4c34ed22n3bcb9c6cf7d198b8@mail.gmail.com> Message-ID: <9a2cc7a70807292221k4dfd72a0nce0ade86e7d222f7@mail.gmail.com> On Tue, Jul 29, 2008 at 12:17 AM, Piyush Anonymous wrote: > class MyObject: > def __init__(self, name): > self.name = name > > def do_this_default(self): > print "default do_this implementation for %s" % self.name > > def custom_do_this(): #method to be added > print "custom do_this implementation for %s" % self.name > > > def funcToMethod(func,clas,method_name=None): > """Adds func to class so it is an accessible method; use method_name to > specify the name to be used for calling the method. > The new method is accessible to any instance immediately.""" > import new > method = new.instancemethod(func,None,clas) > print method > if not method_name: method_name=func.__name__ > clas.__dict__[method_name]=func > > > myobj = MyObject('myobj1') > funcToMethod(custom_do_this,MyObject) #trying 2 add method to class not > instance > print myobj.custom_do_this() > > --- > Error I am getting; > TypeError: custom_do_this() takes no arguments (1 given) > > Why am I getting it? > If your method is going to be bound to an instance, then it needs the expected signature: the first parameter is always a reference to the instance ("self"). Change it to "custom_do_this(self)" and it should work. > Also how can I do this in new style class (inherited from 'object')? > > What did you try and how did it fail? This seems to work: def foo(self): print 'foo' class Bar(object): pass Bar.foobar = new.instancemethod(foo, None, Bar) b = Bar() b.foobar() > > > -- > http://mail.python.org/mailman/listinfo/python-list > From svenn.bjerkem at googlemail.com Thu Jul 24 02:32:10 2008 From: svenn.bjerkem at googlemail.com (Svenn Are Bjerkem) Date: Wed, 23 Jul 2008 23:32:10 -0700 (PDT) Subject: Parsing VHDL with python, where to start. References: Message-ID: <31888260-86a9-46b0-b0a4-79f7852f256a@k30g2000hse.googlegroups.com> On Jul 23, 1:03 pm, christopher.saun... at durham.ac.uk (c d saunter) wrote: > How much of VHDL are you looking to parse? Are you just looking at files > intended for synthesis, or at simulation/testbench files as well? As a start I want to parse VHDL which is going to be synthesised, and I am limiting myself to the entities and the structural component placement. I will drop the processes and the concurrent assignments even if that will mask important information. It is a design viewer tool, not a design tool that I am writing. Xilinx ISE do give me the opportunity to browse my synthesised netlist, but there is simply too much information. Later the app can be extended with more functionality, depends on my success with the initial problems that I have. > If I started again I'd use pyparsing:http://pyparsing.wikispaces.com/ > > Looks like someone is already there in part:http://pyparsing.wikispaces.com/message/view/home/103973 I also got a pointer to SimpleParse and now try to translate the parts of the VHDL BNF that I need into a definition that SimpleParse can understand. But looking at the BNF it is clear that VHDL is no easy language to parse, just as it is no easy language to do structural design in. -- Svenn From vinoliya341 at gmail.com Sat Jul 19 02:12:59 2008 From: vinoliya341 at gmail.com (hot rathi) Date: Fri, 18 Jul 2008 23:12:59 -0700 (PDT) Subject: Your win 10, 000$ in my groups Pls register your name and address in below of the website http://www.geocities.com/cathrina39 Message-ID: <3ee7dc1f-38d4-431d-a0b2-93c37e4e4dad@y22g2000prd.googlegroups.com> Your win 10,000$ in my groups Pls register your name and address in below of the website http://www.geocities.com/cathrina39 From bignose+hates-spam at benfinney.id.au Wed Jul 16 05:35:35 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jul 2008 19:35:35 +1000 Subject: How can i use a variable without define it ? References: <87k5fm2p1x.fsf@benfinney.id.au> <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> Message-ID: <87fxqa2mu0.fsf@benfinney.id.au> zhw writes: > Here is a example that I want to complete: > >>> import sys, new > >>> context={"name":"david", "sex":"male"} Here you have a set of values addressible by name. > >>> sys.modules["foo"] = new.module("foo") Why do you believe you need to create a module object? > >>> import foo > >>> for attr in context: > setattr(foo, attr, context[attr]) This doesn't appear to get you anything that isn't already available with the 'context' mapping. > >>> def bar(): > # here is a error > # import * only allowed at module level > from foo import * > print name, sex You can simply do: >>> context = {'name': "david", 'sex': "male"} >>> def bar(): ... print context['name'], context['sex'] ... >>> bar() david male Or, more flexible and more explicit: >>> foo = {'name': "david", 'sex': "male"} >>> def bar(context): ... print context['name'], context['sex'] ... >>> bar(foo) david male What problem are you trying to solve? -- \ ?The best mind-altering drug is truth.? ?Jane Wagner, via Lily | `\ Tomlin | _o__) | Ben Finney From straton at lampsacos.demon.co.uk Tue Jul 15 16:56:53 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Tue, 15 Jul 2008 21:56:53 +0100 Subject: Measure class, precision, significant digits, and divmod() In-Reply-To: References: Message-ID: Ethan Furman wrote: > Hey all. > > > As I have mentioned before, I am making this Measure class for two > reasons: experience with unit testing, I like playing with numbers, I > am unaware of anything like this having yet been done (okay, three > reasons ;). > > > Any and all feedback welcome, particularly from anyone who might > actually use the Measure class. ;) > > ~Ethan I have been following this thread with interest, because i am doing something similar, namely writing python to provide myself with experience with unit tests and i like playing with numbers. In my case the numbers are 'long rationals' (infinite precision) and will include both floats, the decimal type, extended 'decimals' -- i.e. possibly with a repeating expansion (or in any base) -- and finite continued fractions as derived classes. I also hope to deal with repeating continued fractions later. +++++++++++++++++++++++++++++++++++++++ My principal interest in your work, however, is in the use of unit tests as a pedagogical method of teaching programming, whether self-taught or taught by an instructor. The students would be taught how to __run__ a unit test-suite at as early an opportunity as possible. I can't see why an eleven or twelve year old should not be able to cope with it in hour one or two of a carefully structured course. What is needed for such an approach is a copy--in a public place--of your unit tests for all methods that are really part of the funtionality; together with blanked-out definitions for them (i.e just the first line, any in-code documentation, and 'pass' ). You would not include any 'internal' methods that are merely the way __you__ happened to achieve the result. The programming 'exercise' would then be for the students, or groups of students, to roll their own version until their code passed all the unit tests. From tim.tadh at gmail.com Tue Jul 29 11:25:34 2008 From: tim.tadh at gmail.com (Tim Henderson) Date: Tue, 29 Jul 2008 08:25:34 -0700 (PDT) Subject: DB access without object-relation mapping? References: Message-ID: On Jul 29, 11:20?am, kj wrote: > Python noob here. > > I want to write a script that creates and populates a simple Postgres > database. > > The word on the street is to use something like SQLAlchemy for > database access in Python, but my experience in the past with > packages that perform automated SQL generation has been awful, so > I always return to lighter-weight solutions that allow me to write > my own SQL. ?(E.g. when coding in Perl I've used Perl's DBI package > and drivers, rather than the likes of Class::DBI.) ?So what's the > standard Python way to send SQL directly to a Postgres database > and get back results? > > TIA! > > kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. Hi, I believe there are a couple of options but pyscopg, and PyGreSQL seem to be popular. Tim From thogiti at gmail.com Mon Jul 7 16:31:31 2008 From: thogiti at gmail.com (Nagu) Date: Mon, 7 Jul 2008 13:31:31 -0700 (PDT) Subject: Memory error while saving dictionary using pickle Message-ID: I am trying to save a dictionary of size 65000X50 to a local file and I get the memory error problem. How do I go about resolving this? Is there way to partition the pickle object and combine later if this is a problem due to limited resources (memory) on the machine (it is 32 bit machine Win XP, with 4GB RAM). Please advice. Thank you, Nagu Here is the detail description of the error: Traceback (most recent call last): File "", line 1, in s = pickle.dumps(itemsim) File "C:\Python25\lib\pickle.py", line 1366, in dumps Pickler(file, protocol).dump(obj) File "C:\Python25\lib\pickle.py", line 224, in dump self.save(obj) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "C:\Python25\lib\pickle.py", line 663, in _batch_setitems save(v) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 600, in save_list self._batch_appends(iter(obj)) File "C:\Python25\lib\pickle.py", line 615, in _batch_appends save(x) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 562, in save_tuple save(element) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 477, in save_float self.write(FLOAT + repr(obj) + '\n') MemoryError: out of memory From norseman at hughes.net Tue Jul 15 14:48:00 2008 From: norseman at hughes.net (norseman) Date: Tue, 15 Jul 2008 11:48:00 -0700 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> <8a07445a-3ca8-4373-9312-cea8db83ec5c@l64g2000hse.googlegroups.com> <9f3c45f1-9cb2-46c1-838b-716180061956@e39g2000hsf.googlegroups.com> Message-ID: <487CF0E0.7000807@hughes.net> Mensanator wrote: > On Jul 15, 12:36 pm, defn noob wrote: >> On Jul 15, 7:28 pm, Mensanator wrote: >> >> >> >> >> >>> On Jul 15, 11:26 am, defn noob wrote: >>>> isPrime works when just calling a nbr but not when iterating on a >>>> list, why? adding x=1 makes it work though but why do I have to add >>>> it? >>>> Is there a cleaner way to do it? >>>> def isPrime(nbr): >>>> for x in range(2, nbr + 1): >>>> if nbr % x == 0: >>>> break >>>> if x == nbr: >>>> return True >>>> else: >>>> return False >>>>>>> [isPrime(y) for y in range(11)] >>>> Traceback (most recent call last): >>>> File "", line 1, in >>>> [isPrime(y) for y in range(11)] >>>> File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime >>>> if x == nbr: >>>> UnboundLocalError: local variable 'x' referenced before assignment >>>>>>> map(isPrime, range(100)) >>>> Traceback (most recent call last): >>>> File "", line 1, in >>>> map(isPrime, range(100)) >>>> File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime >>>> if x == nbr: >>>> UnboundLocalError: local variable 'x' referenced before assignment>>> isPrime(10) >>>> False >>>>>>> isPrime(11) >>>> True >>>> adding x=1 makes it work though: >>>> def isPrime(nbr): >>>> x=1 >>>> for x in range(2, nbr + 1): >>>> if nbr % x == 0: >>>> break >>>> if x == nbr: >>>> return True >>>> else: >>>> return False >>>>>>> [isPrime(y) for y in range(11)] >>>> [False, True, True, True, False, True, False, True, False, False, >>>> False] >>> No, it doesn't. You are falsely reporting that 1 is prime. >>> And instead of making the fake variable x, shouldn't you >>> instead test that nbr+1 is greater than 2? Or call it with >>> range(3,11) instead of range(11)? x isn't initialized >>> because if nbr+1 is <=2, the for loop has an invalid range >>> and doesn't even execute. >> def isPrime(nbr): >> for x in range(2, nbr + 1): >> if nbr % x == 0: >> break >> if x == nbr: >> return True >> else: >> return False >> >> this works for all primes, if i want to not include 1 i just do if >> nbr<=1 return false >> >> you are answering the wrong question. > > No, I also mentioned the for loop having an invalid range, > which is why your original failed. > > Pointing out that 1 isn't prime was a bonus. > >> anyway here is a clear one: >> def isPrime(nbr): >> if nbr < 2: >> return False >> for x in range(2, nbr + 1): >> if nbr % x == 0: >> return nbr == x > > I suppose you're not interested in knowing you don't > have to test anything higher than the square root of > the number. > > -- > http://mail.python.org/mailman/listinfo/python-list > =========================== "don't...test...higher than the square root..." I wondered when that was going to show up. I too had a good math teacher. Steve norseman at hughes.net From fuzzyman at gmail.com Tue Jul 29 16:02:59 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Tue, 29 Jul 2008 13:02:59 -0700 (PDT) Subject: Questions on 64 bit versions of Python References: <488aec52$0$21481$9b622d9e@news.freenet.de> <488B570C.8070202@v.loewis.de> Message-ID: On Jul 26, 8:02?pm, Rob Williscroft wrote: > Martin v. L?wis wrote innews:488B570C.8070202 at v.loewis.dein > comp.lang.python: > > >> I just tested, I built a default C# forms app using the "AnyCPU" > >> option and it ran as a 64 bit app (no *32 in Task Manager), this is > >> on XP64. > > >> I have though installed the AMD64 version of the 2.0 framework and > >> AFAICT neither windows update or the Visual Studio installer > >> will install that by default, you have to go get it your self. > > > Interesting. I only tested this in .NET 1.1. Perhaps they have changed > > something since. How exactly did you launch the program? Does it change > > if you use Python's os.spawn* to launch it? > > If subprocess.call will do then I can report the same results, a > 64 bit process, using 32 bit CPython 2.5 to call it. > > Also if the programme (C#) is built with the 3.5 framework I > get the same results, however interestingly there is no 64 bit > build for the 3.5 framework (or at least I was unable to find one). > > Rob. > --http://www.victim-prime.dsl.pipex.com/ .NET 3.5 is a set of extension assemblies and does not change the underlying runtime - so there is probably no need for a separate 63 bit build for .NET 3.5. Michael Foord -- http://www.ironpythoninaction.com/ From bj_666 at gmx.net Sun Jul 20 01:17:14 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Jul 2008 05:17:14 GMT Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> <6ebshqF67cpfU4@mid.uni-berlin.de> <5d6b8066-c941-4f0c-abea-20baed33b4ab@l64g2000hse.googlegroups.com> Message-ID: <6eg02pF6uhc3U2@mid.uni-berlin.de> On Sat, 19 Jul 2008 13:13:40 -0700, nicolas.pourcelot wrote: > On 18 juil, 17:52, Marc 'BlackJack' Rintsch wrote: >> On Fri, 18 Jul 2008 07:39:38 -0700, nicolas.pourcelot wrote: >> > So, I use something like this in 'sheet.objects.__setattr__(self, >> > name, value)': >> > if type(value) == Polygon: >> > ? ? for edge in value.edges: >> > ? ? ? ? if edge is_in sheet.objects.__dict__.itervalues(): >> > ? ? ? ? ? ? object.__setattr__(self, self.__new_name(), edge) >> >> > Ok, I suppose it's confused, but it's difficult to sum up. ;-) >> >> You are setting attributes with computed names? ?How do you access them? >> Always with `gettattr()` or via the `__dict__`? ?If the answer is yes, why >> don't you put the objects the into a dictionary instead of the extra >> redirection of an objects `__dict__`? >> > > Yes, I may subclass dict, and change its __getitem__ and __setitem__ > methods, instead of changing objets __setattr__ and __getattr__... But > I prefer >>>> sheet.objects.A = Point(0, 0) > than >>>> sheet.objects["A"] = Point(0, 0) But with computed names isn't the difference more like setattr(sheet.objects, name, Point(0, 0)) vs. sheet.objects[name] = Point(0, 0) and getattr(sheet.objects, name) vs. sheet.objects[name] Or do you really have ``sheet.objects.A`` in your code, in the hope that an attribute named 'A' exists? >> Oh and the `type()` test smells like you are implementing polymorphism >> in a way that should be replaced by OOP techniques. > > I wrote 'type' here by mistake, but I used 'isinstance' in my code. ;-) Doesn't change the "code smell". OOP approach would be a method on the geometric objects that know what to do instead of a type test to decide what to do with each type of geometric object. Ciao, Marc 'BlackJack' Rintsch From upton at virginia.edu Wed Jul 30 14:16:32 2008 From: upton at virginia.edu (Dan Upton) Date: Wed, 30 Jul 2008 14:16:32 -0400 Subject: How can I check nbr of cores of computer? In-Reply-To: <4890acd6$0$17215$742ec2ed@news.sonic.net> References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> <4890acd6$0$17215$742ec2ed@news.sonic.net> Message-ID: <5504f9ac0807301116i3907b46l383ed0dd683edfd1@mail.gmail.com> On Wed, Jul 30, 2008 at 2:22 PM, John Nagle wrote: > defn noob wrote: >> >> How can I check how many cores my computer has? >> Is it possible to do this in a Python-app? > > Why do you care? Python can't use more than one of them at > a time anyway. Per Python process, but you might fork multiple processes and want to know how many cores there are to know how many to fork, and which cores to pin them to. (I don't know if there's a direct way in Python to force it to a certain core, so I instead just wrote an extension to interface with sched_setaffinity on Linux.) On Linux, an almost assuredly non-ideal way to find out the number of cores is to read /proc/cpuinfo and look for the highest-numbered "processor: " line (and add 1). From larzluv at hotmail.com Thu Jul 17 12:40:15 2008 From: larzluv at hotmail.com (Larry Hale) Date: Thu, 17 Jul 2008 09:40:15 -0700 (PDT) Subject: Python Behind a Squid Corporate Proxy on Windows References: <7b541a3b-846f-496a-aee1-d5719217e011@m45g2000hsb.googlegroups.com> Message-ID: <821d7616-3faa-4dae-a988-18caf4f8598a@8g2000hse.googlegroups.com> Err, the line above should be: proxy_handler = urllib2.ProxyHandler( { "http": "http:// myusername:password at webfilter.xyz.local:3128" } ) (Sorry! :) From bj_666 at gmx.net Fri Jul 4 05:50:50 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 Jul 2008 09:50:50 GMT Subject: compatible image type References: Message-ID: <6d6a3qF134f0U1@mid.uni-berlin.de> On Fri, 04 Jul 2008 01:15:30 -0700, gordon wrote: > then later on i want to create a Photoimage using > > ImageTk.PhotoImage(file=pathname) and display it on a canvas. > > the extn can be anything ..even zip or bat ,doc whatever depending on > user selection...I want to put someway to raise an error message to > the user if he selects a file with extension not of a compatible image > type for PhotoImage.How should i do this? should i check 'extn' to a > list of compatible image type extensions(something like > [''jpg','jpeg','png','gif'...] ) or is there a better way? Just catch the exception raised by `PhotoImage` if a non compatible file was selected!? Ciao, Marc 'BlackJack' Rintsch From fredrik at pythonware.com Wed Jul 23 08:35:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 14:35:11 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> <216dcee8-ad3d-4ae1-ac4a-4f4819775c7e@d1g2000hsg.googlegroups.com> Message-ID: Jaco Naude wrote: > Fredrik, thanks for the help. I'm not sure why but it seems to work > now even if I don't include the extern "C" command. It also works with > both Python.h files (after I copied pyconfig.h from the PC folder). So > it seems like everything is working now. As it's supposed to do. It's times like this that you really want to use a system that takes snapshots of every single revision of the files you work on, so you can see what exactly it was you had done when it didn't work (it's more often a "do'h" thing than a heisenbug ;-). (fwiw, I'm currently trying to track down a problem at a customer site when the entire Python application managed to remove itself during a test run; the program crashed with "zipimport: IOError" when they tried to use a part of the system that did some lazy imports, and when they tried to restart the program, neither the startup script nor the ZIP archive that contained the bulk of the application were anywhere to be seen. Other PY files in the same directory were left intact. Fully patched Windows XP, clean bill of health from a virus scanner. If anyone's ever experienced anything similar, let me know.) From cwitts at gmail.com Thu Jul 17 05:03:26 2008 From: cwitts at gmail.com (Chris) Date: Thu, 17 Jul 2008 02:03:26 -0700 (PDT) Subject: Remove some characters from a string References: <35cff1a6-74f6-4a68-b81e-71d8ff9c4633@a70g2000hsh.googlegroups.com> Message-ID: <1329a007-e4e3-442a-b546-a14a94410937@r66g2000hsg.googlegroups.com> On Jul 17, 10:13?am, Julien wrote: > Hi, > > I can't seem to find the right regular expression to achieve what I > want. I'd like to remove all characters from a string that are not > numbers, letters or underscores. > > For example: > > >>> magic_function('si_98%u^d at .as-*gf') > > str: 'si_98udasgf' > > Would you have any hint? > > Thanks a lot! > > Julien One quick and dirty way would be... import string safe_chars = string.ascii_letters + string.digits + '_' test_string = 'si_98%u^d at .as-*gf' ''.join([char if char in safe_chars else '' for char in test_string]) you could also use a translation table, see string.translate (the table it uses can be made with string.maketrans) From mattheww at chiark.greenend.org.uk Wed Jul 30 15:55:03 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 30 Jul 2008 20:55:03 +0100 (BST) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: Terry Reedy wrote: >Carl Banks wrote: >> That's not what I was asking for. I was asking for a use case for "if >> x" that can't be replaced by a simple explicit test. Your example >> didn't satisfy that. > But I believe my example of an iterator with __bool__ but not with > __len__ does. On the other hand, iterators provide a clear example of problems with "if x": __nonzero__ for iterators (in general) returns True even if they are 'empty'. For example, this function (which attempts to avoid making an expensive call when not necessary) is buggy, but easy to write if you've been taught that "if x" will work with any kind of object. def frob(widgets, power): if widgets: frobber = Frobber(power) # expensive call for widget in widgets: frobber.frob(widget) -M- From KDawg44 at gmail.com Wed Jul 16 15:11:28 2008 From: KDawg44 at gmail.com (KDawg44) Date: Wed, 16 Jul 2008 12:11:28 -0700 (PDT) Subject: New to Python - Accessing Lotus Notes Message-ID: Hi, We have a Lotus Notes Database that tracks time spent on projects. What I would like to do is develop a Time Tracker in Python that communicates with the server. This would pull projects in and allow a use to start a timer as he/she works on a given project. The user would then be able to commit this back to the database (thus, preventing them from having to go to the calendar view and pick the project and enter the hours). As another potential feature, I would like the user to be able to create projects in the app and track time and then when a project exists in the database, it would retroactively add those hours (users cannot create their own projects and sometimes managers take some time to actually get a project in the system). Lasty, the user could run a report by date to get their hours on each project. Anyway, long story short, how can I communicate with Lotus Notes to accomplish these tasks? Lotus Notes 7. Thank you for your help. I am very new to Python and am hoping to learn a lot from this project so I can incorporate Python into my daily tasks. Also, forgive my rant as I figured out some of my specs as I typed this. Thanks again. Kevin From d3vvnull at gmail.com Fri Jul 4 15:18:09 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 4 Jul 2008 14:18:09 -0500 Subject: Getting a path from a file object In-Reply-To: <3c500ce7-c697-44e9-9f13-f65edc509e1c@a32g2000prf.googlegroups.com> References: <3c500ce7-c697-44e9-9f13-f65edc509e1c@a32g2000prf.googlegroups.com> Message-ID: <170543c70807041218g6a8324e2k3d6fca321504a742@mail.gmail.com> f.name will return the path. But if you want to guarantee getting the absolute pathname use os.path.abspath >>> import os >>> os.path.abspath(f.name) '/some/path/file.ext' On Fri, Jul 4, 2008 at 1:37 PM, Andrew Fong wrote: > Newbie question: > > Let's say I open a new file for writing in a certain path. How do I > get that path back? > > Example: > > >>> f = open('/some/path/file.ext') > >>> some_function(f) > '/some/path/file.ext' > > Does some_function(f) already exist? And if not, how would I define > it? > > -- Andrew > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon Jul 28 01:32:13 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Jul 2008 01:32:13 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <20080728033918.GG7373@dragontoe.org> References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <20080728033918.GG7373@dragontoe.org> Message-ID: Derek Martin wrote: > Furthermore, as you described, defining the function within the scope > of a class binds a name to the function and then makes it a method of > the class. Once that happens, *the function has become a method*. If you mean that a user-defined function object becomes a different class of object when bound to a class attribute name, that is wrong. Once a function, always a function. It may be called an 'instance method' but it is still a function. Any function object can be an attribute of multiple classes, without inheritance, or of none. When a function attribute is accessed via an instance of the class, it is *wrapped* with a bound method object that basically consists of references to the function and instance. When the 'bound method' is called, the instance is inserted in front of the other arguments to be matched with the first parameter. In 2.0, functions accessed through the class were rather uselessly wrapped as an 'unbound method', but those wrappers have been discarded in 3.0. > To be perfectly honest, the idea that an object method can be defined > outside the scope of an object (i.e. where the code has no reason to > have any knowledge of the object) seems kind of gross to me... I happen to like the simplicity that "def statements (and lambda expressions) create function objects." Period. ... > It does indeed -- it does more than imply. It states outright that > the function is defined within the namespace of that object, True. > and as such that it is inherently part of that object. False. That does not follow. Python objects generally exist independently of each other. Think of them as existing in a nameless dataspace if you want. Collection/container objects collect/contain references to their members, just as a club roster does, but they only metaphorically 'contain' their members. Any object can be a member of any number of collections, just as humans can join any number of clubs and groups. In mathematical set theory, membership is also non-exclusive. > So why should it need > to be explicitly told about the object of which it is already a part? Because it is not a 'part' of a class in the sense you seem to mean. What is true is that functions have a read-only reference to the global namespace of the module in which they are defined. But they do not have to be a member of that namespace. Terry Jan Reedy From george.sakkis at gmail.com Thu Jul 3 21:15:57 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 3 Jul 2008 18:15:57 -0700 (PDT) Subject: Singleton implementation problems References: Message-ID: <9ce89515-bb8a-455b-9f8c-ff95e9fb6265@c58g2000hsc.googlegroups.com> On Jul 3, 6:58 pm, Urizev wrote: > Hi everyone > > I have developed the singleton implementation. However I have found a > strange behaviour when using from different files. The code is > attached. > > Executing main > new MySet object > No singleton instance > New singleton: > <__main__.Singleton instance at 0x2b98be474a70> > new MySet object > There is a singlenton instance > new Member > new MySet object > No singleton instance > New singleton: > > new Member > new MySet object > There is a singlenton instance > new Member > new MySet object > There is a singlenton instance > > I do not know why, but it creates two instances of the singleton. Does > anybody know why? Because __init__() is called to initialize the state of an object *after* it has already been created. You should create a "new-style" class and define __new__() instead. Here's a working version: class Singleton(object): # new-style class def __new__(cls, *args, **kwds): # return the singleton (if already created) try: return cls.__dict__['__singleton'] except KeyError: # raised only the first time for a given class # create the singleton and store it to the class namespace singleton = object.__new__(cls, *args, **kwds) setattr(cls, '__singleton', singleton) return singleton class X(Singleton): def __init__(self, a): self.a = a assert X(1) is X(2) Note however that the classic Singleton pattern is usually frowned upon in Python; the preferred approach is to use (module level) globals. Also search for the "Borg pattern". George From ppearson at nowhere.invalid Mon Jul 7 00:09:08 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 7 Jul 2008 04:09:08 GMT Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> Message-ID: <6ddj74F21uhjU1@mid.individual.net> On Sun, 06 Jul 2008 23:42:26 +0200, TP wrote: > > $ python -c "print '\033[30;44m foo \033[0m'" [writes an escape sequence to stdout] > $ echo -e $esc$ColorBlackOnDarkblue foo $esc$ColorReset [also writes an escape sequence to stdout] > $ echo -n $esc$ColorBlackOnDarkblue foo $esc$ColorReset > \033[30;44m foo \033[0m [snip, shuffle] > $ export esc="\033" > $ export ColorBlackOnDarkblue="[30;44m" > $ export ColorReset="[0m" > > import os > Color = os.environ['ColorBlackOnDarkblue'] > ColorReset = os.environ['ColorReset'] > Esc = os.environ['esc'] > print '%s%s%s%s%s' % (Esc, Color, " foo ", Esc, ColorReset) [snip] > $ python color.py > \033[30;44m foo \033[0m The string "\033" is 4 characters long. Your shell variable "esc" is 4 characters long. Your Python program prints those four characters. You want it to re-interpret those 4 characters into a single escape character. One of this group's regular participants can (I hope) tell us three breathtakingly elegant ways to do that. I'm sorry I can't. When you run echo, it recognizes the 4-character "esc" as a convention for representing a single character, and performs the re-interpretation for you. When you tell python "print '\033[30;44m foo \033[0m'", python interprets the "\033" as a single character. -- To email me, substitute nowhere->spamcop, invalid->net. From circularfunc at yahoo.se Thu Jul 3 14:02:42 2008 From: circularfunc at yahoo.se (defn noob) Date: Thu, 3 Jul 2008 11:02:42 -0700 (PDT) Subject: manipulating movie files with Python References: Message-ID: <08cfeaab-33fc-4ae8-a502-6b2682d913b7@59g2000hsb.googlegroups.com> I would love the same thing. Dont know what you are doing but this might be relevant even if it is not what you are asking for: http://imdbpy.sourceforge.net/ library to take data from imdb. From gandalf at shopzeus.com Thu Jul 3 06:40:27 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 03 Jul 2008 12:40:27 +0200 Subject: multithreading in python ??? In-Reply-To: <674A912AA405814397CED58601AC8E251554964241@BLRKECMBX05.ad.infosys.com> References: <674A912AA405814397CED58601AC8E251554964241@BLRKECMBX05.ad.infosys.com> Message-ID: <486CAC9B.9000902@shopzeus.com> Abhishek Asthana wrote: > > Hi all , > > I have large set of data computation and I want to break it into > small batches and assign it to different threads .I am implementing it > in python only. Kindly help what all libraries should I refer to > implement the multithreading in python. > You should not do this. Python can handle multiple threads but they always use the same processor. (at least in CPython.) In order to take advantage of multiple processors, use different processes. L From mail at timgolden.me.uk Wed Jul 16 07:43:37 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 12:43:37 +0100 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: <8AEDA5E3386EA742B8C24C95FF0C758004623111@PDC-MAIL3.ubisoft.org> References: <8AEDA5E3386EA742B8C24C95FF0C758004623111@PDC-MAIL3.ubisoft.org> Message-ID: <487DDEE9.8060305@timgolden.me.uk> Andreas Tawn wrote: > Terry Reedy wrote: >> Wrong. > Thank you. > >> For loop variables continue after the loop exits. This is >> intentional. > I never knew that and I can't find reference to it in the docs. Interesting starting point. It never occurred to me that they might not. (So I didn't look for anything in the docs when they did :) ). TJG From ki4yjl at gmail.com Sat Jul 12 12:15:06 2008 From: ki4yjl at gmail.com (WDC) Date: Sat, 12 Jul 2008 09:15:06 -0700 (PDT) Subject: Using the Random Module. References: Message-ID: <63412f78-e3ba-4c68-9956-1b4562e59778@s50g2000hsb.googlegroups.com> On Jul 12, 10:06?am, Steven D'Aprano wrote: > On Fri, 11 Jul 2008 12:27:32 -0700, castironpi wrote: > > You want a random integer. ?Is there a range you want it in? > > > Past a certain point, you'll exceed the granularity of the random number > > generator, and some values in the range will never be generated. > > You might want to produce an unbounded random integer, where *every* > integer has a chance to be returned: > > def unbounded_randint(): > ? ? i = 0 > ? ? while True: > ? ? ? ? if random.random() < 0.5: > ? ? ? ? ? ? return i > ? ? ? ? i += 1 > > This returns 0 with probability 1/2, 1 with probability 1/4, 2 with > probability 1/8, etc. The probability distribution is centered close to > zero (the mode and median are both zero, and I'm too lazy to calculate > the mean) and it has an infinitely long tail. > > -- > Steven Thanks Steven. I like how that bit works. No range in particular. I was just wondering if there was a better way than what I had been doing. Thanks for help. From floris.bruynooghe at gmail.com Mon Jul 28 07:55:21 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Mon, 28 Jul 2008 04:55:21 -0700 (PDT) Subject: Module clarification References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> Message-ID: <896c547e-9fa1-4f84-8c9b-53a96e70246c@y21g2000hsf.googlegroups.com> On Jul 28, 9:54?am, Hussein B wrote: > Hi. > I'm a Java guy and I'm playing around Python these days... > In Java, we organize our classes into packages and then jarring the > packages into JAR files. > What are modules in Python? An importable or runable (i.e. script) collection of classes, functions, variables etc... > What is the equivalent of modules in Java? Don't know. Not even sure if it exists, but my Java is old and never been great. > Please correct me if I'm wrong: > I saved my Python code under the file ? Wow.py > Wow.py is now a module and I can use it in other Python code: > import Wow Indeed, you can now access things defined in Wow as Wow.foo Regards Floris From larry.bates at websafe.com` Wed Jul 9 12:09:07 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 09 Jul 2008 11:09:07 -0500 Subject: Determining when a file has finished copying In-Reply-To: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> Message-ID: writeson wrote: > Hi all, > > I'm writing some code that monitors a directory for the appearance of > files from a workflow. When those files appear I write a command file > to a device that tells the device how to process the file. The > appearance of the command file triggers the device to grab the > original file. My problem is I don't want to write the command file to > the device until the original file from the workflow has been copied > completely. Since these files are large, my program has a good chance > of scanning the directory while they are mid-copy, so I need to > determine which files are finished being copied and which are still > mid-copy. > > I haven't seen anything on Google talking about this, and I don't see > an obvious way of doing this using the os.stat() method on the > filepath. Anyone have any ideas about how I might accomplish this? > > Thanks in advance! > Doug The best way to do this is to have the program that copies the files copy them to a temporarily named file and rename it when it is completed. That way you know when it is done by scanning for files with a specific mask. If that is not possible you might be able to use pyinotify (http://pyinotify.sourceforge.net/) to watch for WRITE_CLOSE events on the directory and then process the files. -Larry From bearophileHUGS at lycos.com Wed Jul 30 11:10:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 30 Jul 2008 08:10:11 -0700 (PDT) Subject: Pointers/References in Python? References: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Message-ID: boblatest: > I have a long list of memory-heavy objects that I would like to access > in differently sorted order. Let's say I'd like to have lists called > by_date or by_size that I can use to access the objects in the > specified order. Just create a new list with a different sorting order, for example using: from operator import attrgetter by_date = sorted(input_data, key=attrgetter("date")) by_size = sorted(input_data, key=attrgetter("size")) Python doesn't copy by value by default, so you end having just a light list of references. To understand the situation better, there's a FAQ about how Python associates names to things. Bye, bearophile From larry.bates at websafe.com` Mon Jul 21 23:52:50 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 22:52:50 -0500 Subject: Website Creation using Python In-Reply-To: References: Message-ID: Amie wrote: > Afternoon, > > I would like some help on how to create a website using the python > programming language. > I've tried using enamel, but had some problems because I could not > create html tables and intergrating it with python, like you use it > when coding in php. > > Any help would be appreciated. > > Thanks Python is not PHP. Page generation is done differently. You might take a look at Django's web framework: http://www.djangoproject.com/ or http://pylonshq.com/ WARNING - Python web frameworks are MUCH more powerful than just using PHP to place some dynamic content on a web page. For many people, PHP will still be an easy to implement solution if your project isn't very complex. As the complexity grows, the need for additional power and flexibility grows also. -Larry From jonas.esp at googlemail.com Sun Jul 13 19:21:11 2008 From: jonas.esp at googlemail.com (Kless) Date: Sun, 13 Jul 2008 16:21:11 -0700 (PDT) Subject: Dictionary bidirectional Message-ID: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> I need a dictionary where get the result from a 'key' (on left), but also from a 'value' (on right), how to get it? I know that dictionaries aren't bidirectional, but is there any way without use two dictionaries? Thanks in advance! From d3vvnull at gmail.com Tue Jul 1 22:18:33 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Tue, 1 Jul 2008 21:18:33 -0500 Subject: Classes for processing/parsing Wiki Markup text In-Reply-To: References: <170543c70807010931x16938234n9df68ee3c6d0319a@mail.gmail.com> Message-ID: <170543c70807011918t2644fdd5mad09a6433d6e6f45@mail.gmail.com> Thanks! This looks like just what I need! :) On Tue, Jul 1, 2008 at 1:25 PM, Joshua Kugler wrote: > Michael Mabin wrote: > > > Does anyone know if there are any generally available classes for parsing > > various wiki markup formats? > > Several here: > > http://pypi.python.org/pypi?%3Aaction=search&term=wiki&submit=search > > I'm sure you could find a good one, and add your own markup if needed. > > j > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From code at pizzashack.org Fri Jul 18 17:28:32 2008 From: code at pizzashack.org (Derek Martin) Date: Fri, 18 Jul 2008 17:28:32 -0400 Subject: Multiple variable control in for loops. Doable in Python? In-Reply-To: <28efa6970807181221o67c90575w690464f1442dc47d@mail.gmail.com> References: <28efa6970807181221o67c90575w690464f1442dc47d@mail.gmail.com> Message-ID: <20080718212832.GA1994@dragontoe.org> On Fri, Jul 18, 2008 at 12:21:49PM -0700, mark floyd wrote: > I'm new to Python and have been doing work converting a few apps > from Perl to Python. I can not figure out the comparable Python > structures for multi-variable for loop control. [...] > I spent a good part of yesterday looking for a way to handle this > style for loop in Python and haven't been able to find an > appropriate way to handle this control style. One wonders why... :) > We have this style for loop all over the place and not being able to > find a similar structure in Python could be a problem. Any pointers > to a Python equivalent structure would be much appreciated Even if Python didn't offer a way to write a for loop in a similar fashion (someone else replied about that already), why should it be a problem? In general control structures can be rewritten as some other kind of control structure. For example, this does exactly what your for loop examples do: i = 0 j = 0 while i < 5 and j < 10: print i, j i += 1 j += 1 Though, this example is silly, as it will always terminate after the 5th iteration of the loop, and there is no need to have j being used as a control variable... it's termination condition will never be met. Though the example illustrates the techique, even if the example is bogus. Another way is to use functions to modify the values of i and j. Writing your loops this way, you can have as many control variables as you need, and your formula for incrementing those control variables can be as varied as complicated as you can imagine. def some_increment_function(i): # Do some complicated processing of i i = ... return i def other_incrjmental_function(j): # Do some complicated processing of j j = ... return j i = 0 j = 0 while i < 5 and j < 10: print i, j i = some_increment_function(i) j = other_increment_function(j) And of course, you could also replace the loop terminating conditions with functions that return a value which can be interpreted as a truth value. If you wanted to get really crazy, you could even code the control structure as a recursive function: def control(i, j): print i,j if not (i < 5 or j < 10): return else: control(some_increment_function(i), other_increment_function(j)) Should you really write control structures this way, generally? Absolutely not (unless you're writing LISP or Scheme :)). But the point is, even if a given language doesn't have a particular syntactic element that you're looking for, it's pretty much guaranteed to provide a way to do what you're trying to do. You just need to stop thinking about your problem in terms of a particular syntactic element, and start thinking about it in more general terms of what you are actually trying to accomplish, and apply whatever syntax (usually one of several) your language provides to do that. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From malaclypse2 at gmail.com Wed Jul 30 11:10:25 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 30 Jul 2008 11:10:25 -0400 Subject: Python parsing iTunes XML/COM In-Reply-To: <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Message-ID: <16651e80807300810l2ac2eba6tc5bb900e99a8dd@mail.gmail.com> On Wed, Jul 30, 2008 at 10:58 AM, william tanksley wrote: > Here's one example. The others are similar -- they have the same > things that look like problems to me. > > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" > > Note some problems here: > > 1. This isn't Unicode; it's missing the u"" (I printed using repr). > 2. It's got the UTF-8 bytes there in the middle. > > I tried doing track_id.encode("utf-8"), but it doesn't seem to make > any difference at all. I don't have anything to say about your iTunes problems, but encode() is the wrong method to turn a byte string into a unicode string. Instead, use decode(), like this: >>> track_id = "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" >>> utrack_id = track_id.decode('utf-8') >>> type(utrack_id) >>> print utrack_id Buffett Time - Annual Shareholders L.mp3 >>> print repr(utrack_id) u'Buffett Time - Annual Shareholders\xa0L.mp3' >>> -- Jerry From alif016 at gmail.com Fri Jul 18 11:18:13 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Fri, 18 Jul 2008 10:18:13 -0500 Subject: x, = y (???) In-Reply-To: References: Message-ID: <4880B435.8010200@gmail.com> kj wrote: > > I just came across an assignment of the form > > x, = y > > where y is a string (in case it matters). > > 1. What's the meaning of the comma in the LHS of the assignment? > 2. How could I have found this out on my own? > > (Regarding (2) above, I consulted the index of several Python > reference books but I could not find the answer to (1). I hope to > find a better Python reference!) > > TIA! > > kynn > Try this: >>> y = 'abc' >>> type(y) >>> type((y,)) >>> y = y, # y, is just short for (y,) you *have* to use a coma in 1 length tuples >>> y ('abc',) >>> type(y) >>> y[0] 'abc' >>> x, = y #same as x = y[0] OR more verbosely (x,) = (y,) >>> x 'abc' >>> type(x) Maybe that will hape you understand what the comma is for? From maric at aristote.info Thu Jul 31 11:31:44 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 31 Jul 2008 17:31:44 +0200 Subject: Difference between type and class In-Reply-To: <87r69a85ek.fsf@nokile.rath.org> References: <87myjy2vc6.fsf@nokile.rath.org> <87r69a85ek.fsf@nokile.rath.org> Message-ID: <200807311731.45441.maric@aristote.info> Le Thursday 31 July 2008 17:00:51 Nikolaus Rath, vous avez ?crit?: > > There are some confusion about the terms here. > > > > Classes are instances of type 'type', > > Could you please clarify what you mean with 'instance of type X'? I > guess you mean that 'y is an instance of type X' iif y is constructed > by instantiating X. Is that correct? > Correct, you can verify this with the isinstance builtin : >>>[1]: isinstance(int(), int) ...[1]: True >>>[2]: isinstance(int, object) ...[2]: True >>>[3]: isinstance(int, type) ...[3]: True >>>[4]: class A(object) : pass ...: >>>[5]: isinstance(A, type) ...[5]: True > > What the means is that int is not a user type but a > > builtin type, instances of int are not types (or classes) but common > > objects, so its nature is the same as any classes. > > > > The way it prints doesn't matter, it's just the __repr__ of any instance, > > and the default behavior for instances of type is to return '', > > but it can be easily customized. > > But 'int' is an instance of 'type' (the metaclass): > >>> int.__class__ > > > > so it should also return '' if that's the default behavior > of the 'type' metaclass. > The fact that a class is an instance of type, which it is always true, doesn't mean its metaclass is "type", it could be any subclass of type : >>>[6]: class A(object) : ...: class __metaclass__(type) : ...: def __repr__(self) : return "" ...: ...: >>>[7]: isinstance(A, type) ...[7]: True >>>[8]: A.__class__ ...[8]: >>>[9]: issubclass(A.__class__, type) ...[9]: True > I think that to get '' one would have to define a new > metaclass like this: > > def type_meta(type): > ? ? def __repr__(self) > ? ? ? ? ?return "" % self.__name__ > > and then one should have int.__class__ == type_meta. But obviously > that's not the case. Why? > > Moreover: > >>> class myint(int): > > ... ? ?pass > ... > > >>> myint.__class__ == int.__class__ > > True > *is* comparaison fits better here. > >>> int > > > > >>> myint > > > > despite int and myint having the same metaclass. So if the > representation is really defined in the 'type' metaclass, then > type.__repr__ has to make some kind of distinction between int and > myint, so they cannot be on absolute equal footing. You're right, type(int) is type, the way it renders differently is a detail of its implementation, you can do things with builtin types (written in C) you coudn't do in pure python, exactly as you couldn't write recursive types like 'object' and 'type'. -- _____________ Maric Michaud From jiri.zahradil at gmail.com Sun Jul 6 10:31:12 2008 From: jiri.zahradil at gmail.com (jiri.zahradil at gmail.com) Date: Sun, 6 Jul 2008 07:31:12 -0700 (PDT) Subject: Python with Ecmascript References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <8ek074tia4l47tcfo6tqfo9huv2hb68hkt@4ax.com> Message-ID: <7eaf458d-b355-4112-a947-b2b7fe0d1f8d@s50g2000hsb.googlegroups.com> On 6 ?ec, 07:02, Tim Roberts wrote: > "jiri.zahra... at gmail.com" wrote: > > >for my Python application (Windows platform) to be standards > >compliant, I need to embbed Ecmascript(Javascript) interpreter - I > >need to execute plugins written in this language. > > What standard are you hoping to comply with? I mean, what kind of a > program is this? > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. Thats for our speech recognition server - it should executed "tags" with Javascript code embbeded in some XML grammar format. I personally does not like COM solution. I prefer some simple library but may be it is just a hope. I will look to PyQT library and to Mozilla scripting engine, but I think that this one can get unnecessarily difficult. Does anyone work or use something similar? Jiri From dullrich at sprynet.com Thu Jul 24 11:12:39 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 24 Jul 2008 10:12:39 -0500 Subject: repr(string) References: Message-ID: In article , Fredrik Lundh wrote: > David C. Ullrich wrote: > > > I've been saving data in a file with one line per field. > > Now some of the fields may become multi-line strings... > > > > I was about to start escaping and unescaping linefeeds > > by hand, when I realized that repr() and eval() should > > do. Hence the question: If s is a string, is repr(s) > > guaranteed not to contain line breaks? > > yes. > > just keep in mind that using eval() on untrusted data isn't a very good > idea. Right. This data comes from me, gets put into a file and then read by me. Someone _could_ corrupt that file, but someone who could do that could more easily just throw the machine out the window... > -- David C. Ullrich From danielsb2 at hotmail.com Tue Jul 8 10:31:40 2008 From: danielsb2 at hotmail.com (Daniel de Sousa Barros) Date: Tue, 8 Jul 2008 11:31:40 -0300 Subject: Reportlab Image object opens filehandles Message-ID: Hi Mr Robin, I saw your post: http://mail.python.org/pipermail/python-list/2003-September/224781.html I'm trying to append more than 1000 images into one PDF report, but i get the IOError: Too many... know you a solution for it? Sorry by my english.... i'm brazilian and i'm learning english yet... -------------- next part -------------- An HTML attachment was scrubbed... URL: From cbc at unc.edu Mon Jul 14 09:02:44 2008 From: cbc at unc.edu (Chris Calloway) Date: Mon, 14 Jul 2008 09:02:44 -0400 Subject: BootCampArama Final Reminder Message-ID: <270C71C6-EB07-480E-86C1-C411EE2DD611@unc.edu> Final reminder, we're in the last two weeks of open registration for PyCamp, Plone Boot Camp, and Advanced Plone Boot Camp: http://trizpug.org/boot-camp/2008/ Registration is now open for: PyCamp: Python Boot Camp, August 4 - 8 Plone Boot Camp: Customizing Plone, July 28 - August 1 Advanced Plone Boot Camp: Plone 3 Techniques, August 4 - 7 All of these take place on the campus of the University of North Carolina at Chapel Hill in state of the art high tech classrooms, with free mass transit, low-cost accommodations with free wireless, and convenient dining options. Plone Boot Camp is taught by Joel Burton, twice chair of the Plone Foundation. Joel has logged more the 200 days at the head of Plone classrooms on four continents. See plonebootcamps.com for dozens of testimonials from Joel's students. PyCamp is taught by Chris Calloway, facilitator for TriZPUG and application analyst for the Southeast Coastal Ocean Observing System. Chris has developed PyCamp for over 1500 hours on behalf of Python user groups. Early bird registration runs through June 30. So register today! PyCamp is TriZPUG's Python Boot Camp, which takes a programmer familiar with basic programming concepts to the status of Python developer with one week of training. If you have previous scripting or programming experience and want to step into Python programming as quickly and painlessly as possible, this boot camp is for you. PyCamp is also the perfect follow-on to Plone Boot Camp: Customizing Plone the previous week. At Plone Boot Camp: Customizing Plone you will learn the essentials you need to build your Plone site and deploy it. This course is the most popular in the Plone world--for a good reason: it teaches you practical skills in a friendly, hands-on format. This bootcamp is aimed at: * people with HTML or web design experience * people with some or no Python experience * people with some or no Zope/Plone experience It covers using Plone, customizing, and deploying Plone sites. At Advanced Plone Boot Camp: Plone 3 Techniques you will learn to build a site using the best practices of Plone 3 as well as advance your skills in scripting and developing for Plone. The course covers the new technologies in Plone 3.0 and 3.1intended for site integrators and developers: our new portlet infrastructure, viewlets, versioning, and a friendly introduction to Zope 3 component architecture. Now, updated for Plone 3.1! The course is intended for people who have experience with the basics of Plone site development and HTML/CSS. It will cover what you need to know to take advantage of these new technologies in Plone 3. For more information contact: info at trizpug.org -- Sincerely, Chris Calloway http://www.secoora.org office: 332 Chapman Hall phone: (919) 599-3530 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From DWebre at dotd.la.gov Fri Jul 11 09:15:36 2008 From: DWebre at dotd.la.gov (DWebre at dotd.la.gov) Date: Fri, 11 Jul 2008 08:15:36 -0500 Subject: Pickle and wx.TextCtrl Message-ID: Trying to read a pickled filed and list contents. The attached program works using pprint, but I want to write to my frame. WriteText only produces half of the records. What is happening? (See attached file: ReadDB_b.py) D. J. Webre, Jr. PE & PLS Director of Engineering & Technical Support LA DOTD, Office of Public Works, Hurricane Flood Protection & Intermodal Transportation 8900 Jimmy Wedell Dr. Rm 215 Baton Rouge, LA 70807 http://www.dotd.louisiana.gov/sitemap.asp?ID=8 (225) 274-4339 e-mail: DJWebre at dotd.la.gov (225) 274-4322 Fac -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ReadDB_b.py Type: application/octet-stream Size: 1710 bytes Desc: not available URL: From kay.schluehr at gmx.net Tue Jul 15 04:11:05 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 15 Jul 2008 01:11:05 -0700 (PDT) Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> <7348c0dc-028d-4f89-9d63-b1247fb6807c@m44g2000hsc.googlegroups.com> Message-ID: On 15 Jul., 08:16, Yosifov Pavel wrote: > cloning of iterators in this manner is bad, more good is to use one, > single list(my_iter) instead of (seehttp://aquagnu.blogspot.com/2008/07/self-repair-iterator-in-python.html). This won't work for "big" iterators as mentioned by Peter Otten. With this recipe you can't even clone generator objects ( which are iterators ) that produce Fibonaccis in a lazy manner. Regards, Kay From babacity2 at gmail.com Thu Jul 24 16:58:07 2008 From: babacity2 at gmail.com (babacity2 at gmail.com) Date: Thu, 24 Jul 2008 13:58:07 -0700 (PDT) Subject: www efukt com - Amazing porn video collection Message-ID: <007227be-eec2-43ea-87bf-850af75062fa@w39g2000prb.googlegroups.com> www efukt com . >>>>>>>>>>Best Collection of Efukt Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE www efukt com VIDEOS<<<<<<<<<<< . www efukt com From ivan at datasyncorp.com Mon Jul 7 10:05:58 2008 From: ivan at datasyncorp.com (Ivan Ven Osdel) Date: Mon, 7 Jul 2008 09:05:58 -0500 (CDT) Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: Message-ID: <806987658.1043581215439558634.JavaMail.root@saturn.datasyncintra.net> >----- Original Message ----- >From: "Python Nutter" >To: "Ivan Ven Osdel" >Cc: python-list at python.org >Sent: Thursday, July 3, 2008 5:56:32 PM GMT -06:00 US/Canada Central >Subject: Re: Freesoftware for auto/intelligent code completing in Python > >If you guys can get your head out of IDE land, you'll find iPython >does a fantastic job at introspection and Auto-completion, you can >launch shell commands and editors and when done saving be back in the >iPython shell, save memory/variable space to disk so you can come back >the next day and continue off where you were. It puts IDEs to shame. > >If you can't get your Windows-centric IDE need eliminated, then Wing >IDE 101 will not auto-complete, its been deliberately disabled to >force students (hence 101) to memorize python/function names. > >Komodo Edit is a free download and will Auto-complete. >Cheers, >PN Thanks for the suggestion. I'll take a look at iPython today. Ivan From simon at brunningonline.net Wed Jul 23 04:31:49 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 23 Jul 2008 09:31:49 +0100 Subject: Strange problem .... In-Reply-To: <12fd8ef1-c7e0-470b-ba51-f946d8ea8e26@z6g2000pre.googlegroups.com> References: <12fd8ef1-c7e0-470b-ba51-f946d8ea8e26@z6g2000pre.googlegroups.com> Message-ID: <8c7f10c60807230131s35df199ele47fba527be25447@mail.gmail.com> 2008/7/23 karthikbalaguru : > I use Redhat 9.0, python-2.2.2-26, python-devel-2.2.2-26 and > db4-4.0.14-20. > > File "/usr/local/SDK/bin/../core/bin/processorlib.py", line 88 > yield ProcessorObjectInfo(child, self.pt) > ^ > SyntaxError: invalid syntax > > Is this error related with the version of python / python-devel that i > use . > Any ideas / tips ? Yup - generators (and hence the yield statement) were first introduced in Python 2.2, but in order to maintain backward compatibility, you'll need this line in any module using them: from __future__ import generators As of Python 2.3, this is no longer necessary, and I'd imagine that whatever you are running was targeted at a post 2.2 release. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From circularfunc at gmail.com Sat Jul 12 19:31:55 2008 From: circularfunc at gmail.com (ssecorp) Date: Sat, 12 Jul 2008 16:31:55 -0700 (PDT) Subject: Correct use of try,except and raise? Message-ID: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> Is this correct use of exceptions? to raise an indexerror and add my own string insetad of just letting it raise a IndexError by itself and "blaming" it on list.pop? class Stack(object): def __init__(self, *items): self.stack = list(items) def push(self, item): self.stack.append(item) def pop(self): try: return self.stack.pop() except: raise IndexError, "pop from empty stack" class Queue(object): def __init__(self, *items): self.queue = list(items) def append(self, item): self.queue.append(item) def pop(self): try: return self.queue.pop(0) except: raise IndexError, "pop from empty queue" From Nikolaus at rath.org Thu Jul 31 08:27:25 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Thu, 31 Jul 2008 14:27:25 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> Message-ID: <873alq9r2q.fsf@nokile.rath.org> Thomas Troeger writes: >> Can someone explain to me the difference between a type and a class? > > If your confusion is of a more general nature I suggest reading the > introduction of `Design Patterns' (ISBN-10: 0201633612), under > Specifying Object Interfaces'. > > In short: A type denotes a certain interface, i.e. a set of > signatures, whereas a class tells us how an object is implemented > (like a blueprint). A class can have many types if it implements all > their interfaces, and different classes can have the same type if they > share a common interface. The following example should clarify > matters: > > class A: > def bar(self): > print "A" > > class B: > def bar(self): > print "B" > > class C: > def bla(self): > print "C" > > def foo(x): > x.bar() > > you can call foo with instances of both A and B, because both classes > share a common type, namely the type that has a `bar' method), but not > with an instance of C because it has no method `bar'. Btw, this > example shows the use of duck typing > (http://en.wikipedia.org/wiki/Duck_typing). That would imply that I cannot create instances of a type, only of a class that implements the type, wouldn't it? But Python denotes 'int' as a type *and* I can instantiate it. Still confused, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From martin at v.loewis.de Thu Jul 10 00:33:05 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 10 Jul 2008 06:33:05 +0200 Subject: Py_BuildValue for char **? In-Reply-To: References: Message-ID: <48759101$0$9741$9b622d9e@news.freenet.de> > Is there any idiomatic way of mapping char ** to Python? My recommendation is to not use Py_BuildValue. Instead, use PyList_New, and then, in a loop, PyString_FromString/PyList_SetItem. Regards, Martin From duncan.booth at invalid.invalid Sat Jul 12 14:01:31 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jul 2008 18:01:31 GMT Subject: why is "self" used in OO-Python? References: Message-ID: ssecorp wrote: > 1. Why do I have to pass self into every method in a class? Since I am > always doing why cant this be automated or abstracted away? > Are the instances where I won't pass self? > I imagine there is some tradeoff involved otherwise it would have been > done away with. When you define a method in Java there is an implicit 'this' passed to the method. Python cannot tell when you define a function whether the function is going to be used as a function, an instance method, a class method, a static method or something else (or all of the above). Consider this: >>> class C: pass >>> def showme(*args, **kw): print args, kw >>> C.method = showme >>> C.staticmethod = staticmethod(showme) >>> C.classmethod = classmethod(showme) >>> showme(1,2,3) (1, 2, 3) {} >>> C().method(1,2,3) (<__main__.C instance at 0x00C4B580>, 1, 2, 3) {} >>> C().staticmethod(1,2,3) (1, 2, 3) {} >>> C().classmethod(1,2,3) (, 1, 2, 3) {} >>> The dynamic nature of Python means you can lift a method out of a class and re-use it in a different context or inject a function into a class as a method. There are two ways to handle this sort of code: javascript has an implied 'this' for everything whether a function or what passes for a method, Python makes it explicit. > 2. self.item instead of getters and setters. I thought one of the main > purposes of OO was encapsulation. Doesn't messing with internal object- > representations break this? That is correct. Some languages (e.g. Java) don't allow you to encapsulate attributes so you have to write getter and setter methods. If you expose an attribute in Java then you cannot later insert some code into the lookup or override the set without getting all users of your code to change the way they access the value. This is bad. Other languages (e.g. Python, C#) allow you to intercept the attribute lookup so you can change a plain attribute into a property without requiring the users of your class alter their source code. With C# I think they would still need to recompile their code so it may be more appropriate to avoid using public attributes if you are producing a class library for widespread reuse, but with Python there is no difference to the user of your class whether they are accessing an attribute or a property. Sadly a lot of Java programmers mistake the limitations of their language for rules of OO programming, and worse this has spread from Java into other languages where these restrictions no longer need apply. Your Stack class is a bad example: the stack attribute is purely internal so you wouldn't want to expose it as part of the public interface. Consider instead something like: class AddressBookEntry(object): def __init__(self, name, phone): self.name = name self.phone = phone @property def phone(self): return self._phone @property.setter def phone(self, number) validatephonenumber(number) # may throw an exception self._phone = number If later you want to add some processing to the name attribute it is easy, but putting in dummy property getter/setter methods before you need them would be pointless. From frank at chagford.com Wed Jul 30 03:49:36 2008 From: frank at chagford.com (Frank Millman) Date: Wed, 30 Jul 2008 00:49:36 -0700 (PDT) Subject: Questions about asyncore References: <5d30aad5-cad7-4e47-aa83-277202c70ae2@z72g2000hsb.googlegroups.com> Message-ID: <6db7042c-02bb-42ef-b578-3811d8f427f5@m36g2000hse.googlegroups.com> On Jul 29, 3:40?pm, "Giampaolo Rodola'" wrote: > On 29 Lug, 13:09, Frank Millman wrote: Thanks for the reply, Giampaolo. > > The benefit of asynchat is that it automatically handles the buffering > of both input and output. > Aside from set/found_terminator() the other two methods you could want > to look at are push() and push_with_producer(). > push() is a buffered version of asyncore.send(), push_with_producer() > accepts a data-producer object you can use in case you want to deal > with something other than strings (e.g. files, lists, generators, and > so on...). > I looked at push() and push_with_producer(). To be honest I don't fully understand why I would want to use them yet - I will have to go over them a few more times. However, my handle_write() method seems to be working ok and is not complicated, so I will stick with that for now. > > I'm not sure to understand but I doubt you have to use a thread. > If you "have to wait for the reply before continuing" just implement > this logic into handle_read() or found_terminator() method. > Maybe I am a bit slow, but I cannot figure out how to do this without adding a lot of complication. I will try to give a simple example. My server is a database server. It sits between the actual database and the client, and implements access control, automatic handling of foreign keys, etc. It accepts messages to read, update, and write data, and returns the results. For testing purposes, I want the client to send and receive messages such as the following (pseudocode) - -> Read Customer record with CustNo = 'A001'. <- Print data, check that it is correct. [1] -> Read customer's Branch record. <- Print data, check that it is correct. -> Update Customer record with new Branch code. [2] -> Read Branch code from Customer record. <- Print code, check that it has changed. -> Read customer's Branch record. <- Print data, check that it belongs to the new Branch. [1] Amongst other things, the server returns the id of the record [2] The update request uses the record id to identify which record to update These are just examples of the tests I might want to throw at the server. With my multi-threaded approach, the asyncore loop runs in the background, and in the foreground I can easily send any message I like and check the results. I cannot see how to implement this using handle_read() and found_terminator(). Maybe you can give a simple example of an alternative approach. Thanks Frank From jeffober at gmail.com Thu Jul 17 08:27:29 2008 From: jeffober at gmail.com (Jeff) Date: Thu, 17 Jul 2008 05:27:29 -0700 (PDT) Subject: bad recursion, still works References: <20cba7ab-72d2-4c7b-8f3f-48f39eaf9625@m3g2000hsc.googlegroups.com> Message-ID: <5ca91d8c-295e-412c-8bbc-7a0f9f4c8b46@27g2000hsf.googlegroups.com> Thanks, that made things very clear. I like that technique for adding memoization via the parameter. That is clever. It would be nice if there were a way to have multiple functions close over a shared local variable in Python, like let-binding in lisp. From deets at nospam.web.de Sun Jul 27 17:42:41 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2008 23:42:41 +0200 Subject: Rant (was Re: x*x if x>10 In-Reply-To: References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3qjoF9n3cpU1@mid.uni-berlin.de> Message-ID: <6f48ehF9p9bkU1@mid.uni-berlin.de> Terry Reedy schrieb: > > > DaveM wrote: >> On Sun, 27 Jul 2008 19:46:32 +0200, "Diez B. Roggisch" >> >> wrote: >>> As a rule of thumb, don't return objects you didn't create inside a >>> function from scratch. > > Unless its job is specifically to get/fetch an object (reference > thereto) from someplace the caller cannot or should not access. But > then it should probably not mutate the object before returning the > reference. I maybe should paraphrase "don't return objects you passed as arguments from a function". Of course there are exceptions to this rule - but these are few, the canonical being chained function calls like this: class Whatever(object): def do_something(self, arguments): .... return self Diez From Russ.Paielli at gmail.com Sat Jul 26 20:14:46 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 26 Jul 2008 17:14:46 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> Message-ID: <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> On Jul 26, 2:25 pm, Terry Reedy > There is a lot of code you have not seen. Really. In informal code I > use 's' and 'o' for 'self' and 'other'. I don't usually post such > because it is not considered polite. So you have seen a biased sample > of the universe. You take the name down to a single letter. As I suggested in an earlier post on this thread, why not take it down to zero letters? You could if Python accepted something like class Whatever: def fun( , cat): .cat = cat This is even better than the single-character name, not only because it is shorter, but also because there is no question that you are referring to "self." No need to look back at the method signature to verify that. For those who don't like the way the empty first argument looks, maybe something like this could be allowed: def fun( ., cat): From mccredie at gmail.com Tue Jul 15 16:00:52 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 15 Jul 2008 13:00:52 -0700 (PDT) Subject: 'if name is not None:' v. 'if name:' References: Message-ID: On Jul 15, 12:44?pm, "Victor Noagbodji" wrote: > >>what's the difference between these two statement? > >one checks if the given object is not None, the other checks if it's a true value: > >http://docs.python.org/ref/Booleans.html#Booleans > >>And which one should one use? > >depends on what you want to test for, of course. > > > > > Well that's exactly why I'm asking. Since None returns False in if > statements. Why do people use if name is not None: instead of simply > writing if not name? > > -- > NOAGBODJI Paul Victor 1. If you want to distinguish between None and something else that evaluates to False. 2. Speed, "is not" is checking identity of the objects. That can be (and usually is) much quicker than checking whether or not it evaluates to True. Checking the boolean value calls the "__nonzero__" method of an object. That method could be user defined and very complex. In general there are many cases where you use "None" as a placeholder (similar to NULL in C/C++). The best practice is to always compare identity with None. Matt From vuleetu at gmail.com Sun Jul 13 23:47:03 2008 From: vuleetu at gmail.com (Fisher) Date: Mon, 14 Jul 2008 11:47:03 +0800 Subject: Question about Stackless Python Message-ID: <004001c8e564$51fbb5c0$9600a8c0@WWW8D7149479C6> Hi, I have some question about Stackless Python. What is main tasklet? Usually we call stackless.run() to mainloop all the schedule tasklets. But if we just call sometaklet.channel.send(None) in main thread after all the necessary tasklets are created, what would happen? Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Fri Jul 4 01:40:32 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 04 Jul 2008 05:40:32 GMT Subject: How to bypass Windows 'cooking' the I/O? (One more time, please) References: Message-ID: norseman wrote: > >Problem: (sos=same old s...) Microsoft insists the world work it's way >even when the Microsoft way was proven wrong decades ago. In this case >it's (still) 'cooking' the writes even with 'rwb' and O_RDWR|O_BINARY in >(proper respective) use. No, it doesn't. Where did you get the idea that 'rwb' is a valid fopen mode? It's not. If you need to read and write an existing file, you want "r+b". C:\tmp>python Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('x.bat','r+b') >>> s = f.read() >>> s 'sed -e "s/[ \\t]*$//" -e "/^$/d" %1\rhow about that\r\n' >>> f.seek(-1,2) >>> f.write('xxx\r\n') >>> f.close() >>> f = open('x.bat','rb') >>> t = f.read() >>> t 'sed -e "s/[ \\t]*$//" -e "/^$/d" %1\rhow about that\rxxx\r\n' >>> >Same python program runs as expected in Linux. Maybe because that's >where it was written?! :) Perhaps your Linux C runtime library accepts the fopen mode 'rwb', but if it does, it's a non-standard extension. >What I seek is the way to slap Microsoft up side the head and make it >work correctly. OK, well, at least in this situation. It works correctly if you use it correctly. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From Russ.Paielli at gmail.com Wed Jul 30 19:22:19 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 30 Jul 2008 16:22:19 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> Message-ID: <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> On Jul 30, 1:07 am, Erik Max Francis wrote: > Russ P. wrote: > > Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > > __nonzero__ work in Python. It's very basic stuff. You can quit > > patronizing me (and Carl too, I'm sure). > > You suggested a syntax for testing non-emptiness (`x is not empty`) > which indicated a profound misunderstanding of what the `is` operator does. > > You then acknowledged that there might be a problem because of the > implication if the `is` operator and weren't sure whether it would work > or not: Oh, my. I wrote something like, "It would sure be nice to be able to write if x is not empty: because it reads like natural language. Immediately after I posted it, I thought, "oh, I'll bet some idiot takes that as a serious proposal." Sure enough, some idiot did just that almost immediately. And he is still patronizing me for it. Hey, dude, if you think I ever had any doubt about what "is" means in Python, you are simply wrong. Completely wrong. Can you get that through your thick skull? One of the problems with this site is that you have pedants who like to show off their knowledge of the Python language. I suspect that many of these people know little more than the rules of programming in Python. They are like someone who thinks he is a writer because he knows how to use Microsoft Word, or someone who thinks he is a chess expert because he knows the rules for moving the pieces. From tjreedy at udel.edu Fri Jul 11 14:53:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 Jul 2008 14:53:27 -0400 Subject: Simple question, how do you tell how many items in a list? In-Reply-To: <268ac2770807102256o4f41e784q79a0caf849c046b4@mail.gmail.com> References: <268ac2770807102256o4f41e784q79a0caf849c046b4@mail.gmail.com> Message-ID: Alex Bryan wrote: > I am just wondering how you get an integer value for how many items > there are in a list, preferably w/o a for loop. Read the library reference sections on built-in functions and classes. From mail at timgolden.me.uk Mon Jul 28 10:23:24 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 28 Jul 2008 15:23:24 +0100 Subject: GUID Generation In-Reply-To: <019c01c8f0bc$92b56b20$b8204160$@rawlins@thinkbluemedia.co.uk> References: <019c01c8f0bc$92b56b20$b8204160$@rawlins@thinkbluemedia.co.uk> Message-ID: <488DD65C.2040606@timgolden.me.uk> Robert Rawlins wrote: > I?ve been looking at the following recipe for generating a GUID > http://code.activestate.com/recipes/163604/ however I note that its > about 6 years old. Has python since adopted an internal module for GUID > generation? Or is this 3^rd part module still the best option? Not only is the answer, Yes: http://docs.python.org/lib/module-uuid.html but it's just featured as Doug Hellmann's module of the Week: http://blog.doughellmann.com/2008/07/pymotw-uuid.html TJG From circularfunc at yahoo.se Wed Jul 2 16:02:57 2008 From: circularfunc at yahoo.se (defn noob) Date: Wed, 2 Jul 2008 13:02:57 -0700 (PDT) Subject: Run interpreter in emacs? Message-ID: Can I run the python interpreter from with in Emacs? Do i have to change anything then? or is it by default? it already syntax-highlights python-files. From sleytr at gmail.com Fri Jul 4 09:36:32 2008 From: sleytr at gmail.com (Evren Esat Ozkan) Date: Fri, 4 Jul 2008 06:36:32 -0700 (PDT) Subject: Javascript - Python RSA encryption interoperability Message-ID: Hello, I'm trying to encrypt a string with RSA. But it needs to be compitable with Dave's JavaScript RSA implementation*. I'm already read and tried lots of different things about RSA and RSA in Python. But could not produce the same result with the javascript library. My experiments could be seen at: http://dpaste.com/hold/60741/ * JavaScript RSA Library: http://www.ohdave.com/rsa/ Python libraries which I tried; * PyCrtypo: http://www.amk.ca/python/code/crypto.html * rsa library from http://www.stuvel.eu/rsa How could I create the same results with the JS library in Python. Any help would be appreciated Evren, From mercado949 at gmail.com Wed Jul 23 18:14:30 2008 From: mercado949 at gmail.com (mercado mercado) Date: Wed, 23 Jul 2008 18:14:30 -0400 Subject: Importing different versions of a module Message-ID: <8b51e78c0807231514v47a3ab1ev28c816f3db714a27@mail.gmail.com> Thank you Fredrik. This is exactly what I was looking for. > cannot you just insert the appropriate directory in sys.path the first > thing you do in the scripts? e.g. > > import os, sys > > lib = "lib_dev" # change this for prod/rss.py > > sys.path.insert(0, > os.path.join( > os.path.dirname(os.__file__), "site-packages", lib > )) > > import parse # picks the right one -------------- next part -------------- An HTML attachment was scrubbed... URL: From livibetter at gmail.com Wed Jul 2 08:52:07 2008 From: livibetter at gmail.com (livibetter) Date: Wed, 2 Jul 2008 05:52:07 -0700 (PDT) Subject: Email Validation with domain References: <9d6f2e4f-099b-404d-a8db-c87ab15062d6@79g2000hsk.googlegroups.com> Message-ID: <1f5fe9e7-c3be-4076-93ac-5d10b99ef302@l28g2000prd.googlegroups.com> > If you want to validate the domain, do a DNS lookup on the domain or > some such. I don't think there are standard modules to provide this > functionality included with python. You could try using the socket > module, and reading up on the relevant protocols, or making calls to > external programs. I agreed. I made quick code for this. # Email address validator # # This module is in Public Domain # # This module was written for replying to # http://groups.google.com/group/comp.lang.python/browse_thread/thread/80d7d31bebc09190 # * It requires dnspython (http://www.dnspython.org/). # * It is a simple prototype. # * It would be slow if query mass email addresses, having cache mechanism # would be very helpful. # * It only checks hostname of email address. # # Author : Yu-Jie Lin # Creation Date: 2008-07-02T20:09:07+0800 import dns.resolver def CheckEmail(email): """This function directly extracts the hostname and query it""" email_parts = email.split('@') if len(email_parts) != 2: return False # Start querying try: answers = dns.resolver.query(email_parts[1], 'MX') except dns.resolver.NoAnswer: # This host doesn't have MX records return False except dns.resolver.NXDOMAIN: # No such hostname return False # Possible a valid hostname return True I also wrote a short blog post for this post and the code, if you are interested, you can read it at http://thetinybit.com/Blog/2008-07-02-2047-EmailHostnameCheck From thogiti at gmail.com Mon Jul 7 20:03:27 2008 From: thogiti at gmail.com (Nagu) Date: Mon, 7 Jul 2008 17:03:27 -0700 Subject: Memory error while saving dictionary of size 65000X50 using pickle Message-ID: <21da85430807071703t3d3df210le154070481a21343@mail.gmail.com> Thank you very much Martin. It worked like a charm. From sudhakar.koundinya at gmail.com Sun Jul 27 12:57:48 2008 From: sudhakar.koundinya at gmail.com (Sudhakar Chavali) Date: Sun, 27 Jul 2008 09:57:48 -0700 (PDT) Subject: Google Group: architectgurus Message-ID: Hi I have created a group called architectgurus (http://groups.google.com/ group/architectgurus) or architectgurus at googlegroups.com . Irrespective of technology, vendor, domain I will be discussing and share my thoughts in homogenous and harmonious way. If you are interested even you can join and contribute your thoughts in this group. My intention doing these activities is to spread the knowledge and thoughts across the globe. Best Regards Sudhakar Chavali From mensanator at aol.com Tue Jul 15 13:28:36 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 15 Jul 2008 10:28:36 -0700 (PDT) Subject: isPrime works but UnBoundLocalError when mapping on list References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> Message-ID: <8a07445a-3ca8-4373-9312-cea8db83ec5c@l64g2000hse.googlegroups.com> On Jul 15, 11:26?am, defn noob wrote: > isPrime works when just calling a nbr but not when iterating on a > list, why? adding x=1 makes it work though but why do I have to add > it? > Is there a cleaner way to do it? > > def isPrime(nbr): > ? ? for x in range(2, nbr + 1): > ? ? ? ? if nbr % x == 0: > ? ? ? ? ? ? break > ? ? if x == nbr: > ? ? ? ? return True > ? ? else: > ? ? ? ? return False > > >>> [isPrime(y) for y in range(11)] > > Traceback (most recent call last): > ? File "", line 1, in > ? ? [isPrime(y) for y in range(11)] > ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > ? ? if x == nbr: > UnboundLocalError: local variable 'x' referenced before assignment > > >>> map(isPrime, range(100)) > > Traceback (most recent call last): > ? File "", line 1, in > ? ? map(isPrime, range(100)) > ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > ? ? if x == nbr: > UnboundLocalError: local variable 'x' referenced before assignment>>> isPrime(10) > False > >>> isPrime(11) > > True > > adding x=1 makes it work though: > > def isPrime(nbr): > ? ? x=1 > ? ? for x in range(2, nbr + 1): > ? ? ? ? if nbr % x == 0: > ? ? ? ? ? ? break > ? ? if x == nbr: > ? ? ? ? return True > ? ? else: > ? ? ? ? return False > > >>> [isPrime(y) for y in range(11)] > > [False, True, True, True, False, True, False, True, False, False, > False] No, it doesn't. You are falsely reporting that 1 is prime. And instead of making the fake variable x, shouldn't you instead test that nbr+1 is greater than 2? Or call it with range(3,11) instead of range(11)? x isn't initialized because if nbr+1 is <=2, the for loop has an invalid range and doesn't even execute. From rookswood at suburbian.com.au Wed Jul 16 09:33:46 2008 From: rookswood at suburbian.com.au (John Savage) Date: Wed, 16 Jul 2008 13:33:46 +0000 (UTC) Subject: python's YENC.DECODE -> weird output Message-ID: <0807160233556.16Jul08$rookswood@suburbian.com> I save posts from a midi music newsgroup, some are encoded with yenc encoding. This gave me an opportunity to try out the decoders in Python. The UU decoder works okay, but my YENC effort gives results unexpected: import yenc, sys fd1=open(sys.argv[1],'r') #yenc.encode(sys.argv[1],"outfile.yenc",bytes=0) yenc.decode(sys.argv[1],"outfile.mid",bytes=0,crc_in='') I confirmed that yenc.decode exactly reverses yenc.encode, BUT the encoding itself seems to differ from the USENET standard. That is, when I decode USENET files the result isn't a valid music file. (I did try both with and w/o the headers.) Maybe it uses a different character set? I can't quite put my finger on what might be happening. What I can say is that the yenc coding from the newsgroup article, when viewed with Linux 'more', displays roughly 10% of its characters as a question mark, whereas when I give Python's yenc.encode a binary music file and view its output using 'more', it displays about 90% of the output as a question mark. Any ideas? -- John Savage (my news address is not valid for email) From fetchinson at googlemail.com Thu Jul 3 00:15:55 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 2 Jul 2008 21:15:55 -0700 Subject: Times where one would use new style classes vs classic classes In-Reply-To: <6700e4ba-8573-44da-b75a-3b3e5ba1fd9b@i36g2000prf.googlegroups.com> References: <6700e4ba-8573-44da-b75a-3b3e5ba1fd9b@i36g2000prf.googlegroups.com> Message-ID: > I'm really new to Python and I've been reading up some texts on older > versions of Python (2.2 to be specific). > > The text briefly mentioned new style and classic classes. > > I'd really like to know in the current context of Python 2.5, besides > in the cases of multi-inheritance, where would I use new style > classes? Is it a norm to use more new style classes even if I don't > have multi-inheritance in the industry, open source projects, etc > today? > > If this isn't the right place to ask these questions, could some one > point me somewhere more appropriate? As a general rule one always uses new style classes. In fact, in python 3.0 old style classes will cease to exist which fact alone justifies their abandonment from 2.x code too. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From fredrik at pythonware.com Mon Jul 21 04:52:33 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 10:52:33 +0200 Subject: Odd math related issue. In-Reply-To: <43332.3139710867$1216630189@news.gmane.org> References: <43332.3139710867$1216630189@news.gmane.org> Message-ID: Robert Rawlins wrote: > I?ve got what seems to me to be a totally illogical math issue here > which I can?t figure out. Take a look at the following code: > > /self/.__logger.info(/"%i / %i"/ % (bytes_transferred, > /self/.__sessions[path].total_bytes)) > > percentage = bytes_transferred / > /self/.__sessions[path].total_bytes * 100 > > /self/.__logger.info(/"%i"/ % percentage) > > Seems fairly straight forward, you would think. It takes two values and > calculates the percentage of one from the other, however, percentage > always comes back as ?0? for some reason, look at this log output. if you divide two integers, you'll get an integer back (in Python 2.X, at least). quick fix: percentage = bytes_transferred * 100 / total_bytes From samwyse at gmail.com Tue Jul 8 09:32:51 2008 From: samwyse at gmail.com (samwyse) Date: Tue, 8 Jul 2008 06:32:51 -0700 (PDT) Subject: numeric emulation and __pos__ References: Message-ID: <49875bd1-1b5a-4f37-ac29-f7f46fa43936@25g2000hsx.googlegroups.com> On Jul 7, 6:12?pm, Ethan Furman wrote: > Greetings, List! > > I'm working on a numeric data type for measured values that will keep > track of and limit results to the number of significant digits > originally defined for the values in question. > > I am doing this primarily because I enjoy playing with numbers, and also > to get some experience with unit testing. > > At this point I have the __init__ portion finished, and am starting on > the various operator functions. > > Questions for the group: > > 1) Any reason to support the less common operators? > ? ? ? ? i.e. <<, >>, &, ^, | > > 2) What, exactly, does .__pos__() do? ?An example would help, too. 1) Those make much less sense for non-integers. I'd say skip them. 2) It's an overridable no-op that implements the unary plus operator. Unary plus returns its value unchanged, as does __pos__. From jkrukoff at ltgc.com Mon Jul 28 18:13:00 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Mon, 28 Jul 2008 16:13:00 -0600 Subject: seemingly simple list indexing problem In-Reply-To: <488E4170.2020804@islandtraining.com> References: <488E4170.2020804@islandtraining.com> Message-ID: <1217283180.4123.101.camel@jmk> On Mon, 2008-07-28 at 15:00 -0700, Gary Herron wrote: > Guilherme Polo wrote: > > On Mon, Jul 28, 2008 at 6:24 PM, Ervan Ensis wrote: > > > >> My programming skills are pretty rusty and I'm just learning Python so this > >> problem is giving me trouble. > >> > >> I have a list like [108, 58, 68]. I want to return the sorted indices of > >> these items in the same order as the original list. So I should return [2, > >> 0, 1] > >> > > > > You could simply do this: > > > > a = [108, 58, 68] > > b = sorted(a) > > [b.index(c) for c in a] > > > > Yuck. Slow, and it fails if duplicate list elements exist. > > Also... This looks like a beginners programming assignment. Let's > let him try it himself. We can offer help rather than full solutions if > he has specific Python questions. > > > > > > > > >> For a list that's already in order, I'll just return the indices, i.e. [56, > >> 66, 76] should return [0, 1, 2] > >> > >> Any help would be appreciated. > >> > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > >> > >> > > > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list Sorry, problem was interesting to solve, so I may have jumped the gun. I do wonder why OP was asking for this though, as now that you mention it I can't think of a use case outside of a homework assignment. -- John Krukoff Land Title Guarantee Company From alif016 at gmail.com Sat Jul 26 12:46:45 2008 From: alif016 at gmail.com (Andrew) Date: Sat, 26 Jul 2008 11:46:45 -0500 Subject: Easier way to get the "here" path? In-Reply-To: <488B4A86.4010308@gmail.com> References: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> <488B4A86.4010308@gmail.com> Message-ID: <488B54F5.3090800@gmail.com> Andrew wrote: > bukzor wrote: >> I have to go into these convulsions to get the directory that the >> script is in whenever I need to use relative paths. I was wondering if >> you guys have a better way: >> ... >> > If you just need the current path (where it is executed) why not use > os.getcwd() > which returns a string of the absolute path to the module being executed. > > > $ echo "print __file__" > path.py > $ ipython > In [1]: import path > path.pyc > > In [2]: import os > > In [3]: os.path.join(os.getcwd(), path.__file__.rstrip("c")) > Out[3]: '/home/andrew/path.py' > -- > Andrew I was thinking of this in the module being imported, but now that I try, it doesn't work. It is still seeing itself from the symlink's position. This works, in the module being imported: $ less path.py from os.path import realpath here = realpath(__file__.rstrip("c")) $ python >>> import path >>> path.here '/home/andrew/sym/sym/path.py' -- Andrew From samwyse at gmail.com Wed Jul 9 11:03:39 2008 From: samwyse at gmail.com (samwyse) Date: Wed, 9 Jul 2008 08:03:39 -0700 (PDT) Subject: numeric emulation and __pos__ References: <92e3ea9f-5745-4072-9d09-7c14fd335828@f36g2000hsa.googlegroups.com> Message-ID: On Jul 8, 12:34?pm, Ethan Furman wrote: > Anybody have an example of when the unary + actually does something? > Besides the below Decimal example. ?I'm curious under what circumstances > it would be useful for more than just completeness (although > completeness for it's own sake is important, IMO). Well, as in Decimal, it would be a good operator to use for canonization. Let's say you implement complex numbers as an angle and radius. Then, unary plus could be used to normalize the angle to +/- Pi and the radius to a positive number (by inverting the angle). From alan.franzoni.blahblah at example.com.invalid Wed Jul 30 04:15:15 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Wed, 30 Jul 2008 08:15:15 GMT Subject: static variables in Python? References: Message-ID: <1wxwcddbkwzuy$.1urswtm09xu9q$.dlg@40tude.net> kj was kind enough to say: > In this case, foo is defined by assigning to it a closure that has > an associated variable, $x, in its scope. > > Is there an equivalent in Python? There've been plenty of answers, and I'm not absolutely sure about what you want... but closures are available in Python as well and you can use them, and by combining them through the partial module you can get a sort of closure factory: from functools import partial def getfunc(expensive_call, myfunc): val = expensive_call() f = partial(myfunc, val) return f you can then do something like that: >> f = getfunc(lambda: 1, lambda x,y:x*y) >> f(2) 6 -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From circularfunc at gmail.com Sun Jul 6 17:33:03 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 6 Jul 2008 14:33:03 -0700 (PDT) Subject: how are strings immutable in python? References: Message-ID: so if strings were mutable and i did a = b = "foo" and then did a += "bar" then a and b would be foobar? From Michael.Coll-Barth at VerizonWireless.com Mon Jul 21 12:57:53 2008 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Mon, 21 Jul 2008 12:57:53 -0400 Subject: Change PC to Win or Windows In-Reply-To: References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> Message-ID: <20080721171023.5CB321E4008@bag.python.org> > From: Derek Martin > The term "PC" is commonly used in > English, in the United States and other English speaking countries, to > mean a computer running Microsoft Windows. That isn't quite true. My kids are heading off to college and are in the market for laptops. The question they had for the salesman was if there was anything other than Vista available. I was so proud. His response was that they no longer bother with XP. Another customer suggested that they look at Apple and another customer suggested dual booting it with Ubuntu ( why not Fedora? ). I was shocked when I asked if either were in the field. Nope, a mechanic and doctor. While it might have been true that PCs were becoming synonymous with Windows boxes, I think that tide is heading back the other way. Particularly when I hear that the Apple boxes are becoming very popular as they work better with iPods and iPhones than does Windows. The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From mattheww at chiark.greenend.org.uk Thu Jul 31 17:01:48 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 31 Jul 2008 22:01:48 +0100 (BST) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <00a124e1$0$20313$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >On Wed, 30 Jul 2008 20:55:03 +0100, Matthew Woodcraft wrote: >> On the other hand, iterators provide a clear example of problems with >> "if x": __nonzero__ for iterators (in general) returns True even if they >> are 'empty'. > How do you propose telling whether an iterator is empty? > That's a generic problem with any sort of lazy function. You don't know > if it has finished unless you try grabbing data from it. Of course. The point is that if you tell people that "if x" is the standard way to check for emptiness, and also support a general principle along the lines of "write your function using the interfaces you expect, and call it using the object you have", you should expect to end up with bugs of this sort. >> For example, this function (which attempts to avoid making an expensive >> call when not necessary) is buggy, but easy to write if you've been >> taught that "if x" will work with any kind of object. >> >> def frob(widgets, power): >> if widgets: >> frobber = Frobber(power) # expensive call >> for widget in widgets: >> frobber.frob(widget) > AFAIK there's no great solution to this problem. It's inherent in the way > lazy functions work. Certainly you can't replace the call to "if widgets" > with "if len(widgets)", because iterators don't have a length. I'm not a fan of len() for testing emptiness. But it would have been better in this case, because it would have converted a hard-to-find performance bug into an obvious exception. >However, there is a good (but not great) solution: > >def frob(widgets, power): > widgets = iter(widgets) # in case widgets is a sequence > try: > first = widgets.next() > except StopIteration: > # empty iterator, nothing to do > return None > frobber = Frobber(power) # expensive call > frobber.frob(widget) > for widget in widgets: > frobber.frob(widget) I would use the following low-tech way: def frob(widgets, power): frobber = None for widget in widgets: if frobber is None: frobber = Frobber(power) frobber.frob(widget) -M- From M.Busetto at isac.cnr.it Wed Jul 23 06:20:06 2008 From: M.Busetto at isac.cnr.it (maurizio) Date: Wed, 23 Jul 2008 12:20:06 +0200 Subject: maximum value in a column of file In-Reply-To: References: <4886DCF3.10107@isac.cnr.it> <4886F4CD.8010704@isac.cnr.it> Message-ID: <488705D6.4090300@isac.cnr.it> thank you for your answer actually i've to do some statistics (maximum,minimum,mean,standard deviation,....) of a file of data in which each column is a particular type of data. (the file is a tab separated value). I was trying to do this by using python (usually i work with fortran or bash, but i'm learning python), that the reason why i tried to use numpy. Fredrik Lundh wrote: >
maurizio > wrote: > >> i tryed to use the module max of numpy, >> the problem is that i don't know how to put the column of the file in >> an array. >> (i'm new in phyton). >> anyway if you think there is a better way..... > > What kind of file is it? Did you pick numpy because you want to do > matrix operations (beyond just finding a maximum value), or was it > just the first thing you stumbled upon when researching the problem? > > A simple pattern for finding the maximum value in a file, using only > plain Python code, is: > > max_value = ... some very small value ... > for line in file: > value = ... extract value from line ... > if value > max_value: > max_value = value > > If it's not obvious what "some very small value" is, given the range > of data you're working with, you can do > > max_value = None > for line in file: > value = ... extract value from line ... > if max_value is None or value > max_value: > max_value = value > > instead (this leaves max_value set to None if the file is empty) > > A more experienced Python hacker might write > > def get_all_values(file): > for line in file: > value = ... extract value from line ... > yield value > > ... > > max_value = max(get_all_values(file)) > > instead. But this still leaves us with the problem of extracting the > value. The best way to do that depends on the kind of files you're > working with; for fixed-format text files, you could use string > slicing and int/float for conversion (e.g. "value = > float(line[10:20])", see the tutorial for details); for other text > formats, you could use split/partition or regular expressions, or > maybe an existing module (such as "csv"); for binary formats, there's > a large > number of existing tools. > > And if you really want to use numpy for other reasons than just > getting a maximum value from a column, there's plenty of stuff in > NumPy and SciPy (http://www.scipy.org/) that might be useful. > > So, in other words, I guess we still need more info. > > > > >
From r_e_s_01 at ZZZyahoo.com Thu Jul 10 15:57:51 2008 From: r_e_s_01 at ZZZyahoo.com (r.e.s.) Date: Thu, 10 Jul 2008 12:57:51 -0700 Subject: Can this program be shortened? Measuring program-length? Message-ID: <7Rtdk.16747$N87.3559@nlpi068.nbdc.sbc.com> Can the following program be shortened? ... def h(n,m): E=n, while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n return n h(9,9) Note: Although it halts eventually in principle, this program can't be expected to terminate on any machine in the universe, as it computes a number larger than Graham's number -- assuming Python is extended (if necessary?) to access unbounded storage. Besides using one-letter names and no unneeded whitespace, can something more be done to shorten it? ("Obfuscating" the code would be okay.) Also, I'm not really sure how best to measure a program's length, but this one is now 98 bytes long (or 102 bytes, depending on how newlines are handled). Is there a better measure of program-length? Thanks for any feedback. From norseman at hughes.net Thu Jul 24 13:14:24 2008 From: norseman at hughes.net (norseman) Date: Thu, 24 Jul 2008 10:14:24 -0700 Subject: Broken examples In-Reply-To: References: Message-ID: <4888B870.8090205@hughes.net> Lawrence D'Oliveiro wrote: > In message , norseman > wrote: > >> The OOo examples do not work. > > I have done OOo scripting in Python. What exactly does not work? > -- > http://mail.python.org/mailman/listinfo/python-list > ======================= file: z.scr ---------- #!/bin/bash cd /opt/openoffice.org2.0/program soffice "-accept=socket,host=localhost,port=2002;urp;" & sleep 9 ./python ./zhw.py echo "Did this Run?" # end of file --------- file: zhw.py --------- import uno # get the uno component context from the PyUNO runtime localContext = uno.getComponentContext() # create the UnoUrlResolver resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.b ridge.UnoUrlResolver", localContext ) # connect to the running office ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.Compo nentContext" ) smgr = ctx.ServiceManager # get the central desktop object desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx) # access the current writer document model = desktop.getCurrentComponent() # access the document's text property text = model.Text # create a cursor cursor = text.createTextCursor() # insert the text into the document text.insertString( cursor, "Hello World", 0 ) # Do a nasty thing before exiting the python process. In case the # last call is a oneway call (e.g. see idl-spec of insertString), # it must be forced out of the remote-bridge caches before python # exits the process. Otherwise, the oneway call may or may not reach # the target object. # I do this here by calling a cheap synchronous call (getPropertyValue). ctx.ServiceManager # end of file ------------ file: results ----------- SysOp(P):> sh z.scr Traceback (most recent call last): File "./zhw.py", line 20, in ? text = model.Text AttributeError: Text Did this Run? SysOp(P):> =============NO!!!!!! ----------------------- Haven't found any specific to scalc. The zhw contents is closest to working I have found to date. The z script was used to get to stated place and minimize typos. As results shows - I ran as root. As user it screams lots. (Permissions) The above is best effort so far. Others before it were even worse. If you have working code I would like to tryout your linkage (process). Before you send anything, can you use python to have scalc open a .xls and save it as a csv? I can get python to have scalc open a specific file and then point'n'click myself, but that isn't productive. I cannot get scalc to do a saveas instruction issued by a python program. I have no intentions of staying up all night pointing and clicking. Humans think, computers do the repetitive. Yes? Besides, it is far easier to train the computer than to train the ..... :) Any help is appreciated. Steve norseman at hughes.net From johnericaturnbull at yahoo.com Fri Jul 18 09:25:43 2008 From: johnericaturnbull at yahoo.com (johnericaturnbull at yahoo.com) Date: Fri, 18 Jul 2008 06:25:43 -0700 (PDT) Subject: Core Dump - Segmentation Fault -Newbie Message-ID: <8ba4373d-3d97-4e9a-a15e-723f6818c757@k36g2000pri.googlegroups.com> Hi - I am very new to python. I get this random core dump and am looking for a good way to catch the error. I know the function my core dump occurs. Is there any error catching/handling that I could use in python? From Tribulations at Paralleles.invalid Mon Jul 7 04:05:56 2008 From: Tribulations at Paralleles.invalid (TP) Date: Mon, 07 Jul 2008 10:05:56 +0200 Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> <6ddj74F21uhjU1@mid.individual.net> Message-ID: <4cv8k5-dsg.ln1@rama.nodalpoint> TP wrote: > So, the python print command *can* interpret these 4-character as a single > character. It would be odd if there were no possibility to do the same > thing when the characters are (i) stored in a python variable Sorry, it works when using variables. Try for example: col="[0;31m" esc="\033" colreset="[0m" print esc + col + "foobar" + esc + colreset -- TP (Tribulations Parall?les) "Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert). From __peter__ at web.de Wed Jul 2 03:23:19 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Jul 2008 09:23:19 +0200 Subject: How to pickle bound methods References: Message-ID: srinivasan srinivas wrote: > I would like?to know how to pickle a bound method?? $ cat pickle_method.py import copy_reg import new def make_instancemethod(inst, methodname): return getattr(inst, methodname) def pickle_instancemethod(method): return make_instancemethod, (method.im_self, method.im_func.__name__) copy_reg.pickle(new.instancemethod, pickle_instancemethod, make_instancemethod) if __name__ == "__main__": import pickle class A(object): def __init__(self, who): self.who = who def alpha(self): print "Hello,", self.who FILENAME = "method.pickle" import sys args = sys.argv[1:] if args: a = A(args[0]) m = a.alpha pickle.dump(m, open(FILENAME, "wb")) else: m = pickle.load(open(FILENAME, "rb")) m() $ python pickle_method.py world $ python pickle_method.py Hello, world $ python pickle_method.py Srini $ python pickle_method.py Hello, Srini Peter From clay at lakeserv.net Sat Jul 12 20:49:56 2008 From: clay at lakeserv.net (Clay Hobbs) Date: Sat, 12 Jul 2008 20:49:56 -0400 Subject: Problems with curses Message-ID: <1215910196.7852.7.camel@generator> I am making a text-based game similar to Zork with Python. I have decided to use the curses module, and have run into a problem. I want to scroll the commands and output up after a command is run instead of clearing the screen. But when I use std.scroll(), an exception is raised. Here is the program: #!/usr/bin/env python # text_adventure.py import curses import curses.wrapper def main(stdscr): curses.echo() stdscr.setscrreg(1, 24) score = 0 moves = 0 statusbar = stdscr.subwin(2, 80, 0, 0) statusbar.addstr(0, 0, 'Dingo'+' '*(58-len('Dingo'))+'Score: %03d Moves: %03d'%(score, moves), curses.A_REVERSE) stdscr.addstr(24, 0, '> ') x = stdscr.getstr(24, 2) x = str(x) stdscr.refresh() # stdscr.erase() stdscr.scroll(3) statusbar.erase() statusbar.addstr(0, 0, x+' '*(58-len(x))+'Score: %03d Moves: % 03d'%(score, moves), curses.A_REVERSE) stdscr.addstr(24, 0, '> ') stdscr.getstr(24, 2) curses.wrapper(main) Unfortunately, the error message isn't very helpful. I'm just hoping somebody out there knows curses and has the answer. -- Ratfink From s0suk3 at gmail.com Mon Jul 28 02:21:28 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Sun, 27 Jul 2008 23:21:28 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> <6385b0a8-f7f3-4dc3-91be-e6f158ffb439@a1g2000hsb.googlegroups.com> Message-ID: On Jul 27, 10:55 pm, Lawrence D'Oliveiro wrote: > In message > <6385b0a8-f7f3-4dc3-91be-e6f158ffb... at a1g2000hsb.googlegroups.com>, > > > > s0s... at gmail.com wrote: > > On Jul 26, 6:47 pm, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: > >> In message > >> <024ace13-f72f-4093-bcc9-f8a339c32... at v1g2000pra.googlegroups.com>, > > >> s0s... at gmail.com wrote: > >> > On Jul 24, 5:01 am, Lawrence D'Oliveiro >> > central.gen.new_zealand> wrote: > > >> >> In message > >> >> <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, > >> >> Jordan wrote: > > >> >> > Except when it comes to Classes. I added some classes to code that > >> >> > had previously just been functions, and you know what I did - or > >> >> > rather, forgot to do? Put in the 'self'. In front of some of the > >> >> > variable accesses, but more noticably, at the start of *every single > >> >> > method argument list.* > > >> >> The reason is quite simple. Python is not truly an "object-oriented" > >> >> language. It's sufficiently close to fool those accustomed to OO ways > >> >> of doing things, but it doesn't force you to do things that way. You > >> >> still have the choice. An implicit "self" would take away that choice. > > >> > By that logic, C++ is not OO. > > >> Yes it is, because it has "this". > > > You mean the keyword "this"? It's just a feature. How does that make a > > difference on being or not being OO? > > Because it was one of the things the OP was complaining about (see above). Wrong. What the OP complains about has no relevance on what makes a language OO or not. From ldo at geek-central.gen.new_zealand Thu Jul 24 06:08:10 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 24 Jul 2008 22:08:10 +1200 Subject: Broken examples References: Message-ID: In message , norseman wrote: > The OOo examples do not work. I have done OOo scripting in Python. What exactly does not work? From paul at boddie.org.uk Wed Jul 16 06:26:38 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 16 Jul 2008 03:26:38 -0700 (PDT) Subject: Using McMillan Installer, PyInstall or py2exe cross-platform? References: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> <487d100a$0$7538$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <6e1492db-6868-4554-9b85-96c1717b6b6a@s50g2000hsb.googlegroups.com> On 15 Jul, 23:00, Hartmut Goebel wrote: > > I started working on cross-pyinstall today. Let us know how you get on! In theory, one should be able to build Python (and derived works) using the mingw32 libraries and a suitable cross-compiler on platforms other than Windows, but I've never bothered to do so myself. Paul From ed.whyatt at gmail.com Wed Jul 16 11:42:50 2008 From: ed.whyatt at gmail.com (Whyatt) Date: Wed, 16 Jul 2008 08:42:50 -0700 (PDT) Subject: Setting Message Importance using SMTP Mail Message-ID: <33672217-148c-4c6a-96be-25ef88ba773f@k37g2000hsf.googlegroups.com> Hi all, I'm trying to create a message using SMTP Mail through Python with a message Importance of either 0 (Low) or 2 (High). If I do outer.Add_header('Importance', '0') it is ignored. If I do uter.Replace_header('Importance', '0') I get the error below. Traceback (most recent call last): File "#####", line 840, in outer.Replace_header('Importance', '0') AttributeError: MIMEMultipart instance has no attribute 'Replace_header' Can anyone provide any clues on the correct way of updating the Msg Importance header? Thanks in advance Ed From tjreedy at udel.edu Tue Jul 22 01:35:11 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2008 01:35:11 -0400 Subject: tail-rec decorator, well still blows the stack... In-Reply-To: References: Message-ID: ssecorp wrote: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 > > so I try it and when I run: > @Decorators.tail_recursion > def fibtr(n): > def fibt(a, b, n): > if n <= 1: > return b > else: > return fibt(b, a + b, n - 1) > if n == 0: > return 0 > else: > return fibt(0, 1, n); > > it still blows the stack. so what is the point? is it impossible to > get "real" tail-recursion in Python? As you have used it, the decorator wraps the *outer* non-recursive function which is just called once anyway. Useless. Try wrapping fibt instead. That said, this recipe significantly increases the running time by multiplying the number of function calls by about three. I do not regard it as removing the recursion, but, rather, as making it indirect (via two other calls) so as to remove the unneeded stack frames (and the space problem) in between recursive calls. Much simpler is the trivial rewrite with while to do 'in frame recursion', or iteration. This also removes the need for outer and inner function. rearrange fibt as def fibt(a,b,n): if n > 1: return fibt(b, a+b, n-1) else: return b and rewrite as def fibi(a,b,n): while n > 1: a,b,n = b,a+b,n-1 return b by directly binding the new arguments to the parameters. Move the initialization inside the function (and delete the outer wrapper) to get def fib(n): if n==0: return 0 else: a,b = 0,1 while n > 1: a,b,n = b,a+b,n-1 return b and even turn the induction back a step and simplify to def fib(n): a,b = 1,0 while n: a,b,n = b,a+b,n-1 return b Why do some people fight writing efficient beautiful code like this that works with Python's design to instead write less efficient and uglier code that works against Python's design? If you do not want function calls (and runtime name resolution), do not write them! Terry Jan Reedy From Robert.Bossy at jouy.inra.fr Fri Jul 11 12:38:58 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Fri, 11 Jul 2008 18:38:58 +0200 Subject: decorator to prevent adding attributes to class? In-Reply-To: <98c6e83e-4a54-49ce-a32e-f03f5ab97f28@k13g2000hse.googlegroups.com> References: <98c6e83e-4a54-49ce-a32e-f03f5ab97f28@k13g2000hse.googlegroups.com> Message-ID: <48778CA2.2000402@jouy.inra.fr> Michele Simionato wrote: > This article could give you same idea (it is doing the opposite, > warning you > if an attribute is overridden): > http://stacktrace.it/articoli/2008/06/i-pericoli-della-programmazione-con-i-mixin1/ > > There is also a recipe that does exactly what you want by means of a > metaclass: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158 > It is so short I can write it down here: > # requires Python 2.2+ > > def frozen(set): > "Raise an error when trying to set an undeclared name." > def set_attr(self,name,value): > if hasattr(self,name): > set(self,name,value) > else: > raise AttributeError("You cannot add attributes to %s" % > self) > return set_attr > > class Frozen(object): > """Subclasses of Frozen are frozen, i.e. it is impossibile to add > new attributes to them and their instances.""" > __setattr__=frozen(object.__setattr__) > class __metaclass__(type): > __setattr__=frozen(type.__setattr__) > I don't get it. Why use a metaclass? Wouldn't the following be the same, but easier to grasp: class Frozen(object): def __setattr__(self, name, value): if not hasattr(self, name): raise AttributeError, "cannot add attributes to %s" % self object.__setattr__(self, name, value) Btw, the main drawback with Frozen is that it will not allow to set any new attributes even inside __init__. Some people would advise to use __slots__: http://docs.python.org/ref/slots.html#l2h-222 Some other people would advise NOT to use __slots__: http://groups.google.com/group/comp.lang.python/msg/0f2e859b9c002b28 Personally, if I must absolutely, I'd go for explicitely freeze the object at the end of __init__: class Freezeable(object): def freeze(self): self._frozen = None def __setattr__(self, name, value): if hasattr(self, '_frozen') and not hasattr(self, name): raise AttributeError object.__setattr__(self, name, value) class Foo(Freezeable): def __init__(self): self.bar = 42 self.freeze() # ok, we set all variables, no more from here x = Foo() print x.bar x.bar = -42 print x.bar x.baz = "OMG! A typo!" Cheers, RB From pythonnutter at gmail.com Thu Jul 10 03:26:36 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Thu, 10 Jul 2008 17:26:36 +1000 Subject: ANN: Mac OS X versions of Rabbyt 0.81 - A fast 2D sprite engine using OpenGL Message-ID: Just a quick announcement, I have supplied PPC and Intel compiled eggs for the Rabbyt libary on Pypi http://pypi.python.org/pypi/Rabbyt/ Rabbyt-0.8.1-py2.5-macosx-10.3-ppc.egg (md5) Built on OS X 10.5.4 for PowerPC equipped Macs Rabbyt-0.8.1-py2.5-macosx-10.3-i386.egg (md5) Built on OS X 10.5.4 for Intel equipped Macs If you know anything about Rabbyt or want to run any of the Rabbyt + pyglet tutorials or demonstration programs, you can now easily install it onto your Mac. Cheers, PN From robert.rawlins at thinkbluemedia.co.uk Wed Jul 23 11:49:11 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Wed, 23 Jul 2008 16:49:11 +0100 Subject: Get dict value but not as reference. Message-ID: <007901c8ecdb$a67f9070$f37eb150$@rawlins@thinkbluemedia.co.uk> Guys, This feels like a strange question but it's not something I've done before, I'm sure it's quite simple. I have a dictionary, and I want to get one of the values from it, but rather than returning it as a reference I want to actually detach/remove the element from the dictionary. Like so: Def get_something(): Something = self.my_dict["keythatIwanttoredetach"] Return something I can then use something, however, it no longer exists in the dictionary. Sorry, I couldn't really explain this very well. How can I achieve this? Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From boaz at feldbaum.name Fri Jul 18 07:40:51 2008 From: boaz at feldbaum.name (Boaz Feldbaum) Date: Fri, 18 Jul 2008 14:40:51 +0300 Subject: How to register an extension DLL with python 2.5? Message-ID: Hello all, I wrote an extension dll in C++ using VS2005 to be used in windows platform. In pyhon 2.4 I used to copy my dll to the dlls sub-directory of python installation and import my dll and it worked fine. This doesn't work with python 2.5. I get the following when trying to import my dll: >>> import pywutil Traceback (most recent call last): File "", line 1, in ImportError: No module named pywutil >>> What should I do in 2.5 to be able to import my extension dll? Thanks a lot in advance, Boaz. From asd at pittle.org Wed Jul 2 14:15:04 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Wed, 2 Jul 2008 11:15:04 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: Message-ID: <4400a687-f424-45ba-93f5-e096913f52a9@s21g2000prm.googlegroups.com> On Jul 2, 7:55?pm, Ivan Ven Osdel wrote: > The free Python editors/IDEs really do need work as far as code completion goes but I am hopeful. > > IMO Stani's Python Editor comes closest by providing some code sense through a combination of history and doc strings for Python built-ins. Where it falls short is the ability to scan doc strings for your own code and non built-in modules in the Python path. Python already has the ground work in place to accomplish something similar to VS's XML commenting/intellisense system. With a Python interpretor you can type help(myModule) and get the doc string documentation. So I imagine implementing code sense for code being developed as well as non built-in modules would just be a matter of finding the appropriate module at the right time and piping the output of help([module]) to a popup window. > > If your willing to help work on something like that I suggest contacting Stani directlyhttp://pythonide.stani.be/or creating a plugin for Geanyhttp://geany.uvena.de/ > > Ivan Ven Osdel > Software Engineerhttp://www.datasyncsuite.com/ > > ----- Original Message ----- > From: "Ali Servet D?nmez" > To: python-l... at python.org > Sent: Wednesday, July 2, 2008 3:33:59 AM GMT -06:00 US/Canada Central > Subject: Re: Freesoftware for auto/intelligent code completing in Python > > On Jul 1, 12:15?am, Fuzzyman wrote: > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > I don't want to be so mean here, but how hard it could be be writing a > > > freesoftware which would automatically/intelligently auto complete > > > Python code? (I mean something that really does the job, like > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > name it, but just don't give me PyDev please...) > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > missing here? > > > > Could someone please point me out something that I'm really missing > > > which is already present in the wild, otherwise I'd like discuss with > > > whoever is willing to help me to get this thing done. I made my mind > > > and I could volunteer to make this happen as thesis project for my > > > incoming graduation in the next year. > > > > Regards you all, > > > Ali Servet D?nmez > > > Vim, Emacs, Wing, Komodo, ... more? > > > Yeah, I guess you're missing something. :-) > > > Michael Foordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > I've checkout Wing IDE's license and it doesnt' seem to be a > freesoftware; am I wrong? > > Ivan, thanks for your reply. I am curious how come you're suggesting me those two, but not others. Is there a good/particular reason for that? From brendandetracey at yahoo.com Thu Jul 10 08:05:49 2008 From: brendandetracey at yahoo.com (Brendan) Date: Thu, 10 Jul 2008 05:05:49 -0700 (PDT) Subject: B-Soup: broken iterator, tag a keyword? Message-ID: <413d8bc0-6156-4502-93c1-8c8790128f56@d45g2000hsc.googlegroups.com> Hi there, I have the following using Beautiful Soup: soup = BeautifulSoup(data) tags = soup.findAll(href=re.compile("/MER_FRS_L2_Canada/MER_FRS_\S +gz")) for tag in tags: print tag['href'] print tag.parent.nextSibling.string print tag.parent.nextSibling.nextSibling.string print tag.parent.nextSibling.nextSibling.nextSibling.string print tag.parent.nextSibling.nextSibling.nextSibling.nextSibling.contents[0].string For some reason I do not understand, using 'tag' as an iterator breaks the code. Can someone tell me why? reading dir(soup) did not illuminate me. Thanks From aspersieman at gmail.com Wed Jul 30 11:55:35 2008 From: aspersieman at gmail.com (Aspersieman) Date: Wed, 30 Jul 2008 17:55:35 +0200 Subject: Standard module for parsing emails? In-Reply-To: References: <6fb93eFap7j5U1@mid.individual.net> Message-ID: <48908EF7.7060301@gmail.com> Phillip B Oldham wrote: > If there isn't a standard library for parsing emails, is there one for > connecting to a pop/imap resource and reading the mailbox? > -- > http://mail.python.org/mailman/listinfo/python-list > > The search [1] yielded these results: 1) http://docs.python.org/lib/module-email.html 2) http://www.devshed.com/c/a/Python/Python-Email-Libraries-SMTP-and-Email-Parsing/ I have used the email module very successfully. Also you can try the following to connect to mailboxes: 1) poplib 2) smtplib For parsing the mails I would recommend pyparsing. [1] http://www.google.com/search?client=opera&rls=en&q=python+email&sourceid=opera&ie=utf-8&oe=utf-8 Regards Nicolaas -- The three things to remember about Llamas: 1) They are harmless 2) They are deadly 3) They are made of lava, and thus nice to cuddle. From sk8in_zombi at yahoo.com.au Fri Jul 11 12:16:05 2008 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Fri, 11 Jul 2008 09:16:05 -0700 (PDT) Subject: Simple Image Cropper Message-ID: <793799.70431.qm@web54501.mail.re2.yahoo.com> Hi, I am designing a simple image cropper which simply takes an image and use PIL to do the cropping.Now in order to do the cropping I simply draw a rectangle on the image by dragging the mouse over the image.I then use button press and button release events to find the mouse postition and send across the tuple to PIL? .Everything works fine but what I need is a way to show the user a dotted rectangle as he drags across the mouse as in every other standard image editor.I have learnt that using gnomecanvas will do that but given my time constraints and the lack of a tutorial on pygtk ,I used gtk.image + event box to do the above. Can someone point to using gnomecanvas in the following directions: 1.Load an image into the canvas from file as well as pixbuf. 2.Draw a dotted rectangle 3.Fire and capture mouse events 4.Use PIL I basically want to know about point 2. Also,will implementing cairo be easy on glade and pygtk? Regards, Abhishek " life isn't heavy enough,it flies away and floats far above action" Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: From maryam9646 at gmail.com Wed Jul 2 11:14:13 2008 From: maryam9646 at gmail.com (maryam9646 at gmail.com) Date: Wed, 2 Jul 2008 08:14:13 -0700 (PDT) Subject: free web design templates using free downloading Message-ID: <56b1ebf7-6ab2-4dfe-8210-eeac2d59e960@z24g2000prf.googlegroups.com> Success usually comes to those who are too busy to be looking for it Visit Mobiles & Computers?, http://www.mobilecomputers4all.blogspot.com/
Hi..Click me

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi..Click me

From ldo at geek-central.gen.new_zealand Thu Jul 24 06:03:26 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 24 Jul 2008 22:03:26 +1200 Subject: Confounded by Python objects References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> Message-ID: In message <33c9309a-9679-41f6-a777-2874aad1903a at z66g2000hsc.googlegroups.com>, boblatest at googlemail.com wrote: > class Channel: > name = '' > sample = [] These are class variables, not instance variables. Take them out, and ... > def __init__(self, name): > self.name = name ... add this line to the above function self.sample = [] From alan.franzoni.blahblah at example.com.invalid Thu Jul 31 04:44:08 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Thu, 31 Jul 2008 08:44:08 GMT Subject: Possible to have multiple loop variables? References: <5ff22b51-88e9-405c-aeb9-7b0abe9cf935@r66g2000hsg.googlegroups.com> Message-ID: <17l8ky2s9ntqz$.dn7j54skaf95$.dlg@40tude.net> laredotornado was kind enough to say: > How would I set up the ms1 array such that I can use three items per > object? Use tuples. But that should depend on which values make up the key for your mapping. E.g. ms1 = {('managed1':7019):8020, ('managed2':7020):8021} ms2 = {'managed1':(7019:8020), 'managed2':(7020:8021)} depending on what you want, and then iterate over such structure just like Marc suggested. Otherwise, you can create a custom class which returns three-tuples when iterated, in such case you can just extract m, lp, ssl_lp in the for cycle just like your example. -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From babacity4 at gmail.com Thu Jul 24 16:52:19 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:52:19 -0700 (PDT) Subject: free sextv1 tv - Amazing porn video collection Message-ID: free sextv1 tv . >>>>>>>>>>Best Collection of Sextv1 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE sextv1 tv VIDEOS<<<<<<<<<<< . free sextv1 tv From animator333 at gmail.com Fri Jul 25 13:05:14 2008 From: animator333 at gmail.com (King) Date: Fri, 25 Jul 2008 10:05:14 -0700 (PDT) Subject: object persistency, store instances relationship externally References: <3183af12-4b1e-4bd1-8d21-b9fc2b421008@v1g2000pra.googlegroups.com> Message-ID: Thanks Fredrik, It helped a lot and this is really an amazing this I have discovered today. :-)) From praveen.sunsetpoint at gmail.com Mon Jul 7 02:10:24 2008 From: praveen.sunsetpoint at gmail.com (Sallu) Date: Sun, 6 Jul 2008 23:10:24 -0700 (PDT) Subject: Validation in plone Message-ID: <3d02ab9e-6f81-4b56-b6ef-786e8e6f070a@m44g2000hsc.googlegroups.com> Hi all and one, How to do server side validation in plone? please help me its very urgent. i created a validator.py file where i wrote a script for 'special character are not allowed' and calling that script in movie.py its working fine by validators = ('splcharvalid',), and when i wrote another script for email validation and want to call in same field like validators = ('emailvalid',), and i am calling like this validators = ('splcharvalid',),('emailvalid',), but its not working even i wrote like this too validators = ('splcharvalid','emailvalid',), but its too not working.. could you please help mr to resolve this problem or may tell me another way to do validation in plone.. From ldo at geek-central.gen.new_zealand Sat Jul 26 19:43:09 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 27 Jul 2008 11:43:09 +1200 Subject: scanf in python References: <4884be5e$0$19722$426a74cc@news.free.fr> <6ek4cgF7hq4vU1@mid.uni-berlin.de> <4884e77a$0$29405$426a74cc@news.free.fr> <4889ae4a$0$3726$426a74cc@news.free.fr> Message-ID: In message <4889ae4a$0$3726$426a74cc at news.free.fr>, AMD wrote: >> In message <4884e77a$0$29405$426a74cc at news.free.fr>, AMD wrote: >> >>> Actually it is quite common, it is used for processing of files not for >>> reading parameters. You can use it whenever you need to read a simple >>> csv file or fixed format file which contains many lines with several >>> fields per line. >> >> I do that all the time, in Python and C++, but I've never felt the need >> for a scanf-type function. > > I agree scanf is not a must have function but rather a nice to have > function. I've never felt that scanf would be "nice" to have. Not in Python, not in C++. From norseman at hughes.net Wed Jul 9 12:59:32 2008 From: norseman at hughes.net (norseman) Date: Wed, 09 Jul 2008 09:59:32 -0700 Subject: start reading from certain line In-Reply-To: <1215601039.2873.972.camel@localhost.localdomain> References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> <1215601039.2873.972.camel@localhost.localdomain> Message-ID: <4874EE74.80801@hughes.net> Tim Cook wrote: > On Wed, 2008-07-09 at 03:30 -0700, antar2 wrote: >> I am a starter in python and would like to write a program that reads >> lines starting with a line that contains a certain word. >> For example the program starts reading the program when a line is >> encountered that contains 'item 1' >> >> >> The weather is nice >> Item 1 >> We will go to the seaside >> ... >> >> Only the lines coming after Item 1 should be read > > file=open(filename) > while True: > line=file.readline() > if not line: > break > > if 'Item 1' in line: > print line > > > HTH, > Tim > > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list ======================================================= I would use: readthem= 0 file=open(filename,'r') while readthem == 0: line=file.readline() if not line: break if 'Item 1' in line: readthem= 1 # print line # uncomment if 'Item 1' is to be printed while line: line= file.readline() print line # see note-1 below # end of segment The first while has lots of needed tests causing lots of bouncing about. May even need more tests to make sure it is right tag point. As in if 'Item 1' accidentally occurred in a line previous to intended one. The second while just buzzes on through. If the objective is to process from tag point on then processing code will be cleaner, easier to read in second while. note-1: in this form the line terminators in the file are also printed and then print attaches it's own EOL (newline). This gives a line double spacing effect, at least in Unix. Putting the comma at the end (print line,) will stop that. You will need to modify two lines if used. Which to use depends on you. Steve norseman at hughes.net From stochashtic at yahoo.ca Mon Jul 28 04:03:15 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 28 Jul 2008 10:03:15 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> Message-ID: <488d7d43$1@news2-rz-ap.ethz.ch> On Fri, 25 Jul 2008 05:46:56 -0700, Iain King wrote: > or 3. build a new list every iteration intead of deleting from the old > one: > > while processing: > new_off_list = [] > for x in off_list: > if goes_on(x): > on_list.append(x) > else: > new_off_list.append(x) > off_list = new_off_list > generation += 1 > > Iain Or 4, since the order of my nodes doesn't matter: swap the node to be deleted with the last node in the list and then remove the last node of the list. This is the fastest to date, if using native structures, for low number nodes being deleted per cycle (def if only deleting one). From __peter__ at web.de Fri Jul 11 07:53:09 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jul 2008 13:53:09 +0200 Subject: MySQLdb will only import for root References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> Message-ID: martinnorth wrote: > Hi, > > I am running Python and MySQL on Ubuntu and have installed MySQLdb. If I > try to import MySQLdb I get the following error: > > ActivePython 2.5.2.2 (ActiveState Software Inc.) based on > Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08) > [GCC 3.3.1 (SuSE Linux)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import MySQLdb > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named MySQLdb > > But if I lrun python as the root user it imports fine. Can anyone > suggest what might be wrong with the installation? Or is there nothing > wrong? I haven't seen any examples that mentioned being root to import a > module. You have probably installed two versions of Python. You can verify that by typing $ which python and $ sudo which python I suspect that root sees the python that comes with Ubuntu and that has MySQLdb installed while the normal user sees ActiveState's Python. Peter From callen314 at gmail.com Mon Jul 21 21:35:14 2008 From: callen314 at gmail.com (Craig Allen) Date: Mon, 21 Jul 2008 18:35:14 -0700 (PDT) Subject: Python Written in C? References: Message-ID: it's clear to me that the perfect language should exist a priori, coming to being causa sui. Having to actually implement a language is disgusting and unnatural. From __peter__ at web.de Wed Jul 9 02:17:03 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 09 Jul 2008 08:17:03 +0200 Subject: (silly?) speed comparisons References: Message-ID: mk wrote: > Now C++ version took over twice the time to execute in comparison to > Python time! > Am I comparing apples to oranges? Indeed. Where in Python you're passing references your C++ code produces copies of the vector. For starters you can change the function signature to void move_slice(vector& vec, int start, int stop, int dest) which should already give your C++ implementation a significant speed boost. Peter From weizhonghua.ati at gmail.com Wed Jul 16 05:06:56 2008 From: weizhonghua.ati at gmail.com (zhw) Date: Wed, 16 Jul 2008 02:06:56 -0700 (PDT) Subject: How can i use a variable without define it ? References: <87k5fm2p1x.fsf@benfinney.id.au> Message-ID: <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> On 7?16?, ??4?47?, Ben Finney wrote: > zhw writes: > > How can i use a variable without define it ? > > What do you mean by "use"? That's so vague I can think of many > possible interpretations. > > What do you mean by "variable"? That term carries a lot of baggage > that doesn't apply in Python. > > Can you give a small, complete example that demonstrates the issue > you're trying to solve? > > -- > \ ?The face of a child can say it all, especially the mouth part | > `\ of the face.? ?Jack Handey | > _o__) | > Ben Finney Thank you! Sorry for my poor english! Here is a example that I want to complete: >>> import sys, new >>> context={"name":"david", "sex":"male"} >>> sys.modules["foo"] = new.module("foo") >>> import foo >>> for attr in context: setattr(foo, attr, context[attr]) >>> def bar(): # here is a error # import * only allowed at module level from foo import * print name, sex >>> bar() From stef.mientki at gmail.com Tue Jul 29 03:43:26 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 29 Jul 2008 09:43:26 +0200 Subject: Is it allowed to use function results as default arguments ? In-Reply-To: References: <488E2BF1.8020003@gmail.com> Message-ID: <488ECA1E.8090706@gmail.com> Terry Reedy wrote: > To answer the subject line: > param= > will assign the result of the expression as the default argument > object for the parameter. > thanks Terry and others, brings me to one other question: I guess this function is only evaluated once, is that correct ? about os.curdir, I checked it, it's already a constant ;-) and because I use afterwards: os.path.abspath('.'') which is identical to os.path.getcwd() about '.' being the current directory, well I think windows was thrown at the market about 25 years ago, and since then we don't use '.' anymore ;-) cheers, Stef > tjr > > -- > http://mail.python.org/mailman/listinfo/python-list From jfabiani at yolo.com Tue Jul 22 09:54:09 2008 From: jfabiani at yolo.com (John Fabiani) Date: Tue, 22 Jul 2008 06:54:09 -0700 Subject: need thumbnail from video Message-ID: Hi, I need a py tool that will provide a thumbnail (bmp?) from a video (avi, wmv) that will be cross platform (linux, windows). Research has provided pymedia for Linux but I haven't found anything for windows. Hopefully, someone has had to do this in the past and knows what has to be done. Thanks in Advance, Johnf From phillip.oldham at gmail.com Thu Jul 10 05:25:26 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Thu, 10 Jul 2008 02:25:26 -0700 (PDT) Subject: FOSS projects exhibiting clean/good OOP? References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> Message-ID: <3bd416cf-6989-44fb-961d-658032231356@m73g2000hsh.googlegroups.com> Thanks all - lots to go through there! :D I'd heard previously that Trac was a nice example, or rather its core was, but I'd also heard that there were lots of problems with it and that they were redeveloping it from scratch? From omer at no-log.org Wed Jul 2 10:07:26 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Wed, 2 Jul 2008 16:07:26 +0200 Subject: simple UnZip In-Reply-To: <5b915a0e-a227-460f-8273-ecc01b800884@2g2000hsn.googlegroups.com> References: <5b915a0e-a227-460f-8273-ecc01b800884@2g2000hsn.googlegroups.com> Message-ID: <200807021607.26668.omer@no-log.org> Le Wednesday 02 July 2008 15:39:51 noydb, vous avez ?crit?: > Can someone help me with this script, which I found posted elsewhere? > I'm trying to figure out what is going on here so that I can alter it > for my needs, but the lack of descriptive names is making it > difficult. And, the script doesn't quite do anything worthwhile -- it > unzips one file from a zipfile, not all files in a zipfile. > > *** > import zipfile, os, sys, glob > > os.chdir("C:\\Temp") > zips = glob.glob('*.zip') > > for fzip in zips: > if zipfile.is_zipfile(fzip): > print fzip," is a zip" > z = zipfile.ZipFile(fzip,'r') > lstName = z.namelist() > sHgt = lstName[0] > print "Unpacking",sHgt > hgt = z.read(sHgt) > fHgt = open(sHgt,'wb') > fHgt.write(hgt) > # fHgt.flush > fHgt.close > print "Finished" > *** > > I changed it somewhat to > &&& > import zipfile, os, sys > > event_zip = ("C:\\Temp\\data4event.zip") > > z = zipfile.ZipFile(event_zip, 'r') > > zList = z.namelist() > > for zItem in zList: > print "Unpacking",zItem > zRead = z.read(zItem) > z1File = open(zItem,'wb') > z1File.write(zRead) > z1File.close namelist() returns a list of relative file names, so you can just put them anywhere you want with: zlFile = open(os.path.join(DESTDIR, zItem), 'wb') or change the current directory, but the first way should be preferred. > print "Finished" > &&& > > This works, but I want to be able to specify a different output > location. > -- C?dric Lucantis From lloyd at treleven.freeserve.co.uk Fri Jul 18 11:27:22 2008 From: lloyd at treleven.freeserve.co.uk (lloyd at treleven.freeserve.co.uk) Date: Fri, 18 Jul 2008 17:27:22 +0200 (CEST) Subject: Python evening class Message-ID: <33249062.1062901216394841974.JavaMail.www@wwinf3724> I am learning about python but I would like to attend and evening class at college as I find it hard to study at home. Does anyone know of such a class in London UK? From gnuarm at gmail.com Sun Jul 13 14:50:23 2008 From: gnuarm at gmail.com (rickman) Date: Sun, 13 Jul 2008 11:50:23 -0700 (PDT) Subject: spam References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> <487a0d4d$0$90272$14726298@news.sunsite.dk> Message-ID: <44d31c76-9909-46b1-943d-99e8bd363d8e@56g2000hsm.googlegroups.com> spam From wmcbrine at users.sf.net Fri Jul 4 23:28:32 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Sat, 05 Jul 2008 03:28:32 GMT Subject: Can't get Python for Windows to run References: Message-ID: On Fri, 04 Jul 2008 16:19:34 +0100, Tim Rowe wrote: > pythonw.exe (that's the windows executable, right?) python.exe and pythonw.exe are both Windows executables. There are no non- Windows executables in a Python for Windows package. python.exe is used for console apps or interactive sessions. pythonw.exe suppresses the console window. You use it to launch GUI apps that don't need a console. You can't use it for an interactive session, and it makes no sense to start it without also specifying a Python program to run. Python source files named with the ".pyw" extension are associated with pythonw.exe, while ".py" is associated with python.exe. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From pavlovevidence at gmail.com Fri Jul 4 23:34:03 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 4 Jul 2008 20:34:03 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: On Jul 4, 4:43 pm, "Filipe Fernandes" wrote: > On Fri, Jul 4, 2008 at 8:36 AM, Peter Otten <__pete... at web.de> wrote: > > Henning_Thornblad wrote: > > >> What can be the cause of the large difference between re.search and > >> grep? > > > grep uses a smarter algorithm ;) > > >> This script takes about 5 min to run on my computer: > >> #!/usr/bin/env python > >> import re > > >> row="" > >> for a in range(156000): > >> row+="a" > >> print re.search('[^ "=]*/',row) > > >> While doing a simple grep: > >> grep '[^ "=]*/' input (input contains 156.000 a in > >> one row) > >> doesn't even take a second. > > >> Is this a bug in python? > > > You could call this a performance bug, but it's not common enough in real > > code to get the necessary brain cycles from the core developers. > > So you can either write a patch yourself or use a workaround. > > > re.search('[^ "=]*/', row) if "/" in row else None > > > might be good enough. > > Wow... I'm rather surprised at how slow this is... using re.match > yields much quicker results, but of course it's not quite the same as > re.search > > Incidentally, if you add the '/' to "row" at the end of the string, > re.search returns instantly with a match object. This behavior is showing that you're getting n-squared performance; the regexp seems to be checking 156000*(156000-1)/2 substrings for a match. I don't think it's possible to avoid quadratic behavior in regexps in general, but clearly there are ways to optimize in some cases. I'm guessing that grep builds a table of locations of individual characters as it scans and, when the regexp exhausts the input, it tries to backtrack to the last slash it saw, except there wasn't one so it knows the regexp cannot be satisfied and it exits early. > @ Peter > I'm not versed enough in regex to tell if this is a bug or not > (although I suspect it is), I'm pretty sure it isn't: the regexp documentation makes no claims as to the performance of the regexp that I'm aware of. > but why would you say this particular > regex isn't common enough in real code? When re.search regexps start with things like [^...]* or .*, typically the excluded characters are a typically found frequently in the input. For example, the pattern .*hello.* could be used to find a line with hello in it, with the expectation that there are lots of newlines. But if there aren't any newlines the regexp wouldn't be very useful. Carl Banks From mattheww at chiark.greenend.org.uk Mon Jul 21 12:43:29 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 21 Jul 2008 17:43:29 +0100 (BST) Subject: Python Written in C? References: Message-ID: Roy Smith wrote: > C is the highest level assembler language I've ever used. And I've used a > few. It really is cool that you can add two 32-bit integers and not have > to worry about all those carry bits. I was ever so pleased when I found out that the LLVM people have learned this lesson from C. I look forward to the day when we can have similar treatment for all forms of error checking. Programming will be so much easier. -M- From stef.mientki at gmail.com Mon Jul 28 15:56:33 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 28 Jul 2008 21:56:33 +0200 Subject: how to upload files to "google code" filesection ? In-Reply-To: <63de76c2-349c-4371-8732-1681301c7ab0@a1g2000hsb.googlegroups.com> References: <7f6182a3-4504-4239-8239-673a7e4bfefd@s50g2000hsb.googlegroups.com> <63de76c2-349c-4371-8732-1681301c7ab0@a1g2000hsb.googlegroups.com> Message-ID: <488E2471.9050801@gmail.com> Mike Driscoll wrote: > Stef, > > >> Mike Driscoll wrote: >> >>> On Jul 26, 12:43 pm, Stef Mientki wrote: >>> >>>> hello, >>>> >>>> In a program I want to download (updated) files from google code (not >>>> the svn section). >>>> I could find a python script to upload files, >>>> but not for downloading. >>>> >>>> Anyone has a hint or a solution ? >>>> >>>> thanks, >>>> Stef Mientki >>>> >>> You should be able to use urllib to do that. The following link has a >>> recipe: >>> >>> http://code.activestate.com/recipes/496685/ >>> >> thanks Mike, >> >> I already found an even simpler solution (that works) >> >> filename, header = urllib.urlretrieve (url) >> >> >>> If you need to search Google Code, there's an API that appears to be >>> exposed through their gdata module. >>> >> Do you have perhaps a more specific link ? >> I saw the Google API's, but its'quit large / complex, so I couldnt find >> it there. >> >> cheers, >> Stef >> >> >>> Mike >>> > > I was looking at this page about Google Code Search: > http://code.google.com/apis/codesearch/ > > You should be able to use the API that's outlined there in conjunction > with the gdata module on this page: > > http://code.google.com/p/gdata-python-client/ > > thanks Mike, I'll take a look at those links. cheers, Stef > Mike > > -- > http://mail.python.org/mailman/listinfo/python-list > From max at alcyone.com Wed Jul 30 02:16:43 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 23:16:43 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > On Jul 29, 10:33 pm, Carl Banks wrote: >> On Jul 30, 1:15 am, "Russ P." wrote: > >>> Having said that, it would sure be nice to be able to write >>> if myList is not empty: >>> instead of >>> if len(myList) != 0: >> I can agree with this. > > But I guess that could only work if there were only one empty list > that represents all empty lists (as there is only one actual "None"). > I don't know if that makes sense or not. It really doesn't, since it presumably wouldn't apply to just list types. There are plenty of other sequence types: such as tuples, strings, or even arbitrary custom types. Emptiness is a test for the value of an object, not a test for whether it is identical to another object, so this is a very misleading of the `is` operator, bordering on abuse. This syntax would make far less sense than the existing Boolean test. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The doors of Heaven and Hell are adjacent and identical. -- Nikos Kazantzakis From mail at microcorp.co.za Mon Jul 7 09:31:15 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 7 Jul 2008 15:31:15 +0200 Subject: Cross Comiler for Python? Message-ID: <001001c8e036$e79ad940$0d00a8c0@hendrik> Diez wrote: >Look at the gumstix project, they do have a cross-compiled python in there. >You should be able to get an idea on how to do that yourself. > >It involves (or at least did back then) a bit of trickery as the >build-process of python uses the freshly created interpreter to pre-compile >modules. But it is possible. Thanks Diez will look at it. From mail at timgolden.me.uk Wed Jul 16 10:39:29 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 15:39:29 +0100 Subject: About wmi In-Reply-To: References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> Message-ID: <487E0821.3010808@timgolden.me.uk> patrol wrote: > The errors are in the following: > > Traceback (most recent call last): > File "D:\My Documents\code\python\wmi\test.py", line 5, in > c = wmi.WMI ("non-existent computer") > File "C:\Python25\lib\wmi.py", line 1199, in connect > handle_com_error (error_info) > File "C:\Python25\lib\wmi.py", line 184, in handle_com_error > exception_string = [u"%s - %s" % (hex (hresult_code), > hresult_name)] > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > 4: ordinal not in range(128) OK, I'm trying to set up a Virtual PC so I can install a non-English XP. But would you mind running the following code for me, please, so I can get a handle on what's coming back: import pythoncom import win32com.client try: win32com.client.GetObject ("winmgmts://blahblah") except pythoncom.com_error, info: for i in info: print repr (i) Thanks TJG From iainking at gmail.com Thu Jul 10 11:56:20 2008 From: iainking at gmail.com (Iain King) Date: Thu, 10 Jul 2008 08:56:20 -0700 (PDT) Subject: start reading from certain line References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> <1215601039.2873.972.camel@localhost.localdomain> <5de66f4b-b931-4618-b461-29a43e5a119d@25g2000hsx.googlegroups.com> Message-ID: On Jul 10, 4:54?pm, Iain King wrote: > On Jul 10, 2:45?pm, jstrick wrote: > > > Here's a simple way to do it with a minimum amount of loopiness (don't > > forget to use 'try-except' or 'with' in real life): > > > f = open("item1.txt") > > > for preline in f: > > ? ? if "Item 1" in preline: > > ? ? ? ? print preline, > > ? ? ? ? for goodline in f: > > ? ? ? ? ? ? # could put an end condition with a 'break' here > > ? ? ? ? ? ? print goodline, > > > f.close() > > No Ignore that From alif016 at gmail.com Sat Jul 19 21:14:08 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Sat, 19 Jul 2008 20:14:08 -0500 Subject: trying to match a string In-Reply-To: References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> <945275e9-8923-479c-8eec-258bd68063c0@z6g2000pre.googlegroups.com> <4881FE02.3000203@gmail.com> Message-ID: <48829160.4070800@gmail.com> John Machin wrote: > On Jul 20, 5:00 am, Andrew Freeman wrote: > >> Andrew Freeman wrote: >> >>> John Machin wrote: >>> >>>> A couple of points: >>>> (1) Instead of search(r'^blahblah', ...) use match(r'blahblah', ...) >>>> (2) You need to choose your end-anchor correctly; your pattern is >>>> permitting a newline at the end: >>>> >> I forgot to change search to match. This should be better: >> >> def match(var): >> if re.match(r'[LRM]*\Z', var): >> return True >> else: >> return False >> > > A bit wordy ... > > if blahblah: > return True > else: > return False > > can in total generality be replaced by: > > return blahblah > > > >> I was also thinking if you had a list of these items needing to be >> verified you could use this: >> > > You could, but I suggest you don't use it in a job interview :-) > > >> >>> l = ['LLMMRR', '00thLL', 'L', '\n'] >> > > (1) Don't use 'L'.lower() as a name; it slows down reading as people > need to fire up their mental parser to distinguish it from the result > of 3 - 2 > > >> >>> out = [] >> >>> map(lambda i: match(i)==False or out.append(i), l) >> > (2) Read PEP 8 > (3) blahblah == False ==> not blahblah > (4) You didn't show the output from map() i.e. something like [None, > True, None, True] > (5) or out.append(...) is a baroque use of a side-effect, and is quite > unnecessary. If you feel inexorably drawn to following the map way, > read up on the filter and reduce functions. Otherwise learn about list > comprehensions and generators. > > >> >>> print out >> ['LLMMRR', 'L'] >> >> > > Consider this: > > >>>> import re >>>> alist = ['LLMMRR', '00thLL', 'L', '\n'] >>>> zeroplusLRM = re.compile(r'[LRM]*\Z').match >>>> filter(zeroplusLRM, alist) >>>> > ['LLMMRR', 'L'] > >>>> [x for x in alist if zeroplusLRM(x)] >>>> > ['LLMMRR', 'L'] > Thank you for the pointers! (1) Depending on the typeface I totally agree, Courier New has a nearly indistinguishable 1 and l, I'm using Dejavu Sans Mono (Bitstream Vera based). I was just thinking of it as a generic variable name for some input. I'm fairly new to python and programming in general, it's more of a hobby. (2-3) This is actually the first time I've used map, maybe I should not give extra examples, I was actually using it as a learning tool for myself. I'm very thankful the mailing list has such skilled contributers, such as yourself, but I assume that it can't hurt to give working code, even though the style is less than perfect. (3) Personally I think map(lambda i: match(i)==False or out.append(i), l) is a little more readable than map(lambda i: not match(i) or out.append(i), l) even if "baroque", your use of filter is obviously much clearer than either. (4) I highly doubt that this code was actually to be used in an interactive session, the False/True output was truncated intentionally, it's an obvious, but superfluous output (unless you were to rely on this by attaching it to a variable which might lead to sorting issues). (5) Thank you very much, I've read of the filter and reduce functions, but haven't used them enough to recognize their usefulness. I did realize that a list comprehension would be useful, but wanted to try map() I put together a generic matcher that returns either a list of True data (if the input is a list or tuple) or a boolean value: def match(ex, var): "ex is the regular expression to match for, var the iterable or string to return a list of matching items or a boolean value respectively." ex = re.compile(ex).match if isinstance(var, (list, tuple)): return filter(ex, var) else: return bool(ex(var)) I believe this is fairly clean and succinct code, it would help my learning immensely if you feel there is a more succinct, generic way of writing this function. -- Andrew From vinay_sajip at yahoo.co.uk Tue Jul 15 19:21:52 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 15 Jul 2008 16:21:52 -0700 (PDT) Subject: Logging to different addressees References: <8df30038-86c1-4376-b046-a50f2bcf0a2b@s50g2000hsb.googlegroups.com> <7b829a76-ba2c-4cb7-b216-0c9c01e5cd02@f36g2000hsa.googlegroups.com> Message-ID: <4d3df1d9-339b-43b2-9f25-c792e9bf549c@k13g2000hse.googlegroups.com> On Jul 15, 5:17 pm, McA wrote: > > If you added the admin sink handler to the root logger, you're done. > > Isn't that the first thing above? What do you mean? I gave you a choice - to add the handler to the admin_logger OR the root logger. So I am saying here that if you added to the root logger (and not common_logger, assuming they're different), then there's nothing more to do... > > > Otherwise, you need to ensure that certain_logger is a child of > > common_logger. > > What I want to code is something like that. > a) I know thet this is a message for the admin only: > admin_logger.log('blabla') (admin_logger = root_logger =logging.get_logger("")) > > b) certain_logger.log('something' => log to the root/admin/-sink as > well as to the > certain-sink. > > Do I have to create a logger subclass where I do the multiplexing of > theloggingmessages? > I'm pretty sure I miss something. ;-) > No, the logging package is designed to allow flexibility of different events being logged to different destinations. There's no need to subclass Logger to achieve what you're asking for. The following script: # simple.py import logging admin_logger = logging.getLogger("") # The root logger addressee_logger = logging.getLogger("addressee") admin_sink = logging.FileHandler("admin.log", "w") addressee_sink = logging.FileHandler("addressee.log", "w") admin_logger.addHandler(admin_sink) addressee_logger.addHandler(addressee_sink) admin_logger.setLevel(logging.DEBUG) admin_logger.debug("This message appears in admin sink only.") addressee_logger.debug("This message appears in both admin sink and addressee sink." # - end of simple.py Generates the following results: ---------------------------------------------------------- admin.log ---------------------------------------------------------- This message appears in admin sink only. This message appears in both admin sink and addressee sink. ---------------------------------------------------------- addressee.log ---------------------------------------------------------- This message appears in both admin sink and addressee sink. Regards, Vinay Sajip From malaclypse2 at gmail.com Wed Jul 30 17:01:39 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 30 Jul 2008 17:01:39 -0400 Subject: Python parsing iTunes XML/COM In-Reply-To: References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Message-ID: <16651e80807301401ga381259u3f2833a35bea8e17@mail.gmail.com> On Wed, Jul 30, 2008 at 2:27 PM, william tanksley wrote: > Awesome... Thank you! I had my mental model of Python turned around > backwards. That's an odd feeling. Okay, so you decode to go from raw > byes into a given encoding, and you encode to go from a given encoding > to raw bytes. Not what I thought it was, but that's cool, makes sense. That's not quite right. Decoding takes a byte string that is already in a particular encoding and transforms it to unicode. Unicode isn't a encoding of it's own. Decoding takes a unicode string (which doesn't have any encoding associated with it), and gives you back a sequence of bytes in a particular encoding. This article isn't specific to Python, but it provides a good overview of unicode and character encodings that may be useful: http://www.joelonsoftware.com/articles/Unicode.html -- Jerry From james.b.looney at lmco.com Fri Jul 18 15:33:00 2008 From: james.b.looney at lmco.com (Looney, James B (N-ULA)) Date: Fri, 18 Jul 2008 13:33:00 -0600 Subject: Confused about error: invalid Python installation: unable to open ..../python2.4/config/Makefile Message-ID: I built and installed Python 2.4 on 12/12/2007. Recently, I tried installing python-ldap-2.3.4. The error I received was: error: invalid Python installation: unable to open /usr/local/openSource/architectureIndependent:/usr/local/openSource/IRIX 6/lib/python2.4/config/Makefile (No such file or directory) I figured out what I believe to be the origin of this string. When I ran configure to build/install Python, I used the following: ./configure --prefix=/usr/local/openSource/architectureIndependent --exec-prefix=/usr/local/openSource/IRIX6 --enable-shared --without-gcc --with-cxx=CC Somewhere along the lines, the prefix and exec-prefix strings were joined with a ':'. I just went searching around, and found that sys.prefix = '', and sys.exec_prefix="/usr/local/openSource/architectureIndependent:/usr/loca l/openSource/IRIX6" In past posts, I've found people referring to needing to install python-devel, and I have no idea why installing an additional package would help the installation of other packages. Does anyone have any thoughts as to why I'm getting the error? How about thoughts on why the prefix and exec-prefix strings were joined? Thanks, -James -------------- next part -------------- An HTML attachment was scrubbed... URL: From mnordhoff at mattnordhoff.com Mon Jul 7 04:23:18 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 07 Jul 2008 08:23:18 +0000 Subject: mirroring files and data via http In-Reply-To: <9a56e820-164f-4151-82f0-0bdf64c6a636@59g2000hsb.googlegroups.com> References: <9a56e820-164f-4151-82f0-0bdf64c6a636@59g2000hsb.googlegroups.com> Message-ID: <4871D276.2030600@mattnordhoff.com> Steve Potter wrote: > On Jul 6, 8:19 pm, Matt Nordhoff wrote: >> Steve Potter wrote: >>> I'm working on a project to create a central administration interface >>> for several websites located on different physical servers. >>> You can think of the websites as a blog type application. My >>> administration application will be used to create new blog posts with >>> associated media (images, etc..) >>> So I am thinking to setting up a script on each of the sites to "phone >>> home" once per day and download any new posts and media files. >>> I am thinking of transmitting the post data in an xml format that >>> could then be decoded an recorded into the database on the slave >>> site. Are there any easy ways to encode a python dictionary to and >>> from xml? >>> For the media files I am thinking that the administration interface >>> would also provide an xml file with a list of all of the media files >>> required along with an http path to retrieve them and a checksum of >>> some sort to verify that they were downloaded correctly. >>> Basically I am trying to figure out if anything already exists to >>> perform some of these functions or if I have to make them from >>> scratch. I know none of it should be too hard, but I hate to re- >>> invent the wheel. >>> Thanks, >>> Steven Potter >> It sounds like JSON would be perfect for this. For working with it in >> Python, the simplejson module is popular: >> >> >> -- > > Matt, > > You are correct JSON would be much easier to deal with than xml. That > takes care of several of the problems. > > Now it really just comes down to the file transfer from one server to > the other and a verification of some sort that the file transfer was > not corrupt. Is there a python module that takes care of file > downloads and verification? > > Thanks, > > Steve Not automatically, but this should be easy to do yourself. You could generate a simple JSON or plain text file listing URLs and hashes, and then use urllib or urllib2 to download them, and md5, sha1 or (in Python 2.5) hashlib to verify them. All of those modules are in the standard library. -- From sk8in_zombi at yahoo.com.au Fri Jul 11 16:55:32 2008 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Fri, 11 Jul 2008 13:55:32 -0700 (PDT) Subject: Adding a Cairo object into a vbox using pygtk Message-ID: <273437.63112.qm@web54507.mail.re2.yahoo.com> Hi , I am trying to attach a cairo object into a vbox.I can pack a textbox with the following code: ??? entry = gtk.Entry() ??? entry.set_max_length(50) ??? entry.connect("activate", self.enter_callback, entry) ??? entry.set_text("hello") ??? entry.insert_text(" world", len(entry.get_text())) ??? entry.select_region(0, len(entry.get_text())) ??? self.vbox.pack_start(entry, True, True, 0) ??? entry.show() but when I do the same for a cairo object I had created from the pycairo examples ,it wont. ??????? self.window = builder.get_object("mainwindow") ??????? self.vbox = builder.get_object("winvbox") ??? # connect signals ??????? builder.connect_signals(self) ??? .... ?? ??? self.cairorun(cairoshape) ??????? ??? def cairorun(self,Widget): ?? ??? widget = Widget() ??? self.vbox.pack_start(widget, True, True, 0) ??? widget.show() class cairoshape(framework.Screen): ??? def draw(self, cr, width, height): ??? image = cairo.ImageSurface.create_from_png ("image.png") ??? cr.set_source_surface (image, 0, 0) ??? cr.paint () and the framework.py from the examples: #! /usr/bin/env python import pygtk pygtk.require('2.0') import gtk, gobject, cairo # Create a GTK+ widget on which we will draw using Cairo class Screen(gtk.DrawingArea): ??? # Draw in response to an expose-event ??? __gsignals__ = { "expose-event": "override" } ??? # Handle the expose-event by drawing ??? def do_expose_event(self, event): ??????? # Create the cairo context ??????? cr = self.window.cairo_create() ??????? # Restrict Cairo to the exposed area; avoid extra work ??????? cr.rectangle(event.area.x, event.area.y, ??????????????? event.area.width, event.area.height) ??????? cr.clip() ??????? self.draw(cr, *self.window.get_size()) ??? def draw(self, cr, width, height): ??????? # Fill the background with gray ??????? cr.set_source_rgb(0.5, 0.5, 0.5) ??????? cr.rectangle(0, 0, width, height) ??????? cr.fill() # GTK mumbo-jumbo to show the widget in a window and quit when it's closed def run(Widget): ??? window = gtk.Window() ??? window.connect("delete-event", gtk.main_quit) ??? widget = Widget() ??? widget.show() ??? window.add(widget) ??? window.present() ??? gtk.main() if __name__ == "__main__": ??? run(Screen) In short,I can attach the cairo widget to a main window but I'm unable to pack it into a vbox. Regards, SZ " life isn't heavy enough,it flies away and floats far above action" Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: From sn.oo.py.9027 at gmail.com Mon Jul 14 06:05:56 2008 From: sn.oo.py.9027 at gmail.com (John Mechaniks) Date: Mon, 14 Jul 2008 03:05:56 -0700 (PDT) Subject: subprocess module References: <2e7f0504-cc1c-4cb6-b2d0-b67b004eca7d@x41g2000hsb.googlegroups.com> Message-ID: <39622612-5e43-45b4-800a-69277c2e2987@79g2000hsk.googlegroups.com> On Jul 14, 12:34?pm, Peter Otten <__pete... at web.de> wrote: > John Mechaniks wrote: > > from subprocess import call > > call(['ls', '-l']) > > > How do I get the result (not the exit status of the command) of "ls - > > l" into a variable? > > output = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE).stdout.read() > > Peter Thanks Peter. Just curious What difference does the following code makes? What are the advantages of the above method over this one? output = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE).communicate()[0] Also could someone show an example of using the optional input argument for communicate() From JordanNealBerg at gmail.com Thu Jul 10 00:42:58 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Wed, 9 Jul 2008 21:42:58 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: Message-ID: I realize I did a pretty bad job of explaining the problem. The problem is the python version is returning an r that is WAAAAY to big. Here is an example run through that function in each language: C: u starts at 1050 u += 0xe91aaa35; u is now -384127409 u ^= u >> 16; u is now -384153771 u += u << 8; u is now 56728661 u ^= u >> 4; u is now 56067472 b = (u >> 8) & 0x1ff; b is now 389 a = (u + (u << 2)) >> 19; a is now 534 r = a ^ hash_adjust[b]; r is now 6366 Python: u starts at 1050 u += 0xe91aaa35 u is now 3910839887L rut roh... From aoeui2008 at cox.net Sun Jul 20 20:58:56 2008 From: aoeui2008 at cox.net (Teiresias) Date: Sun, 20 Jul 2008 19:58:56 -0500 Subject: Python Written in C? References: Message-ID: <87mykcoxwv.fsf@cox.net> giveitawhril2008 at gmail.com writes: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? Well, yes, the interpreter and a handful of the core modules are written in C. However, most of Python -- especially the cool bits -- aren't written in C. They're written in ... Python! -- Teiresias From kyosohma at gmail.com Mon Jul 7 12:19:15 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 7 Jul 2008 09:19:15 -0700 (PDT) Subject: how to recognize IE window already opened using win32com extension References: <203fdfe3-78d6-4b08-a64f-a031df9cacc1@s50g2000hsb.googlegroups.com> Message-ID: <35175416-3e98-4151-a96e-a8a30def93c9@k13g2000hse.googlegroups.com> On Jul 7, 11:09?am, korean_dave wrote: > How do I use the win32com API to manipulate IE windows ALREADY open? > > ie = Dispatch("InternetExplorer.Application") opens a new window. > > But I'd like to be able to find, of windows already open, a specific > window (with a specified property, matching url, etc.) You'll probably want to re-post to the PyWin32 user's group, but in the mean time, here's one way to go about it. I use the following function: def windowEnumerationHandler(self, hwnd, resultList): ''' This is a handler to be passed to win32gui.EnumWindows() to generate a list of (window handle, window text) tuples. ''' resultList.append((hwnd, win32gui.GetWindowText(hwnd))) And call it like this: topWindows = [] win32gui.EnumWindows(self.windowEnumerationHandler, topWindows) Then you can use a for loop to iterate over the topWindows list to find the one with the correct title: for i in topWindows: if windowText in i[1]: # do something Notice that I use the win32gui module. Make sure you have the win32 modules installed or this won't work. Here's the link to PyWin32 group: http://mail.python.org/mailman/listinfo/python-win32 That should get you going...hopefully ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From bearophileHUGS at lycos.com Sat Jul 19 11:55:23 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 19 Jul 2008 08:55:23 -0700 (PDT) Subject: MethodChain Message-ID: Found from Reddit, it's for e ECMA(Java)Script, but something similar may be useful for Python too: http://jsclass.jcoglan.com/methodchain.html http://blog.jcoglan.com/2008/07/16/where-did-all-my-code-go-using-ojay-chains-to-express-yourself-clearly/ Bye, bearophile From matt at tplus1.com Sun Jul 13 13:55:04 2008 From: matt at tplus1.com (Matthew Wilson) Date: Sun, 13 Jul 2008 17:55:04 GMT Subject: Mutually referencing imports -- impossible? Message-ID: I started off with a module that defined a class Vehicle, and then subclasses Car and Motorcycle. In the Car class, for some bizarre reason, I instantiated a Motorcycle. Please pretend that this can't be avoided for now. Meanwhile, my Motorcycle class instantiated a Car as well. Then I moved the Car and Motorcycle classes into separate files. Each imported the Vehicle module. Then I discovered that my Car module failed because the global Motorcycle wasn't defined. The same problem happened in my Motorcycle module. Car and Motorcycle can't both import each other. In the beginning, when all three (Vehicle, Car, and Motorcycle) were defined in the same file, everything worked fine. I don't know how to split them out in separate files now though and I really wish I could because the single file is enormous. Any ideas? Matt From Lie.1296 at gmail.com Sat Jul 26 07:10:23 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 26 Jul 2008 04:10:23 -0700 (PDT) Subject: Insert character at a fixed position of lines References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> Message-ID: <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> On Jul 26, 5:42?pm, "Francesco Pietra" wrote: > I am still at the stone age, using scripts (e.g., to insert a string > after a string) of the type > > f = open("xxx.pdb", "r") > for line in f: > ? ?print line > ? ?if "H16Z POPC" in line: > ? ? ? ?print "TER" > f.close() > > That is, I have to learn about modules. In your scripts I am lost > about the filename for the pdb file to modify, In Python, stdin and stdout (as provided by the sys module) is a file- like object, i.e. it have similar behavior as regular files you opened with open(). stdin is a read-only file, while stdout is a write-only file. You already know how to make read-only file, f = open("xxx.pdb", "r"), to make it writable, you've got to use 'w' as the mode: f = open("xxx.pdb", "w") After that you can do this: f.write('some string') > francesco > > > > On Sat, Jul 26, 2008 at 11:35 AM, Lie wrote: > > On Jul 26, 2:41 pm, "Francesco Pietra" wrote: > >> How to insert letter "A" on each line (of a very long list of lines) > >> at position 22, i.e., one space after "LEU", leaving all other > >> characters at the same position as in the original example: > > >> ATOM ? ? ?1 ?N ? LEU ? ? 1 ? ? 146.615 ?40.494 103.776 ?1.00 73.04 ? ? ? 1SG ? 2 > > >> In all lines"ATOM" is constant as to both position and string, while > >> "LEU" is constant as to position only, i.e., "LEU" may be replaced by > >> three different uppercase letters. Therefore, the most direct > >> indication would be position 22. > > >> Should the script introduce blank lines, no problem. That I know how > >> to correct with a subsequent script. > > >> Thanks > >> chiendarret > > > If you want to leave the rest of the strings as-is (i.e. the letter A > > overwrites whatever on position 22), Peter's code need to be modified > > a little: > > line = line[:22] + " " + line[23:] > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Dr Francesco Pietra > Professor of Chemistry > Accademia Lucchese di Scienze, Lettere e Arti, founded in 1594 > Palazzo Ducale > 55100 Lucca (Italy) > e-mail chiendar... at gmail.com From bearophileHUGS at lycos.com Wed Jul 30 14:17:01 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 30 Jul 2008 11:17:01 -0700 (PDT) Subject: Reasoning behind 'self' parameter in classes? References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> Message-ID: <11adb25c-333f-4f1c-822f-0c770bb9418a@m44g2000hsc.googlegroups.com> Brett g Porter: > Fredrik Lundh has written a very clear explanation of this athttp://effbot.org/pyfaq/why-must-self-be-used-explicitly-in-method-de... Today lot of people know that Ruby exists, so such FAQ explanation must explain why Python doesn't use a shorter syntax like for example @foo to denote instance attributes (and maybe @@baz for the class attributes). Bye, bearophile From grumman at example.com Mon Jul 7 23:29:51 2008 From: grumman at example.com (Grumman) Date: Mon, 07 Jul 2008 23:29:51 -0400 Subject: How to make python scripts .py executable, not bring up editor In-Reply-To: References: Message-ID: korean_dave wrote: > From command Prompt, i type in a script, "tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? Start->My Computer->Properties->Advanced->Environment Variables in bottom pane "System Variables" add ";.py" to "PATHEXT" From dmitrey.kroshko at scipy.org Mon Jul 21 07:20:20 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Mon, 21 Jul 2008 04:20:20 -0700 (PDT) Subject: howto check is function capable of obtaining **kwargs? Message-ID: hi all, howto check is function capable of obtaining **kwargs? i.e. I have some funcs like def myfunc(a,b,c,...):... some like def myfunc(a,b,c,...,*args):... some like def myfunc(a,b,c,...,*args, **kwargs):... some like def myfunc(a,b,c,...,zz=zz0):... So I need to know is the given function capable of handling zz parameter, for example the call myfunc(a,b,c,...,zz=4,...) Thank you in advance, D. From usenetthrowaway at gmail.com Wed Jul 30 07:48:08 2008 From: usenetthrowaway at gmail.com (Gary) Date: Wed, 30 Jul 2008 12:48:08 +0100 Subject: Proxy server? References: <6f5rteF89muqU2@mid.uni-berlin.de> <6f6sk7Fa4tf5U1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote in message news:6f6sk7Fa4tf5U1 at mid.uni-berlin.de... > Gary schrieb: > > "Diez B. Roggisch" wrote in message > > news:6f5rteF89muqU2 at mid.uni-berlin.de... > You can't make any TCP/IP communication run through a proxy, unless it's > transparent. Thanks for all the info. I'm puzzled though that a such a transaction isn't possible by rewriting the headers. So client X connects to my PS, which passes on the data to the target but with the header changed to indicate the PS as the original source. The intended target responds to the PS, this is then resent to client X with the header modified so that the transaction appears transparent. So it's *effectively* transparent target>client but non-transparent client>target, if you see what I mean. Can you please explain why this wouldn't work? Thanks, Gary From python at barillari.org Tue Jul 8 17:56:45 2008 From: python at barillari.org (Joseph Barillari) Date: Tue, 08 Jul 2008 17:56:45 -0400 Subject: Impossible to change methods with special names of instances of new-style classes? Message-ID: <878wwcavky.fsf@bigbox.barillari.org> Hi python-list, I've just started using new-style classes and am a bit confused as to why I can't seem to alter methods with special names (__call__, etc.) of new-style class instances. In other words, I can do this: >>> class Z: ... pass ... >>> z = Z() >>> z.__call__ = lambda : 33 >>> z() 33 But apparently I can't do this: >>> class NZ(object): ... pass ... >>> nz = NZ() >>> nz.__call__ = lambda : 33 >>> nz() Traceback (most recent call last): File "", line 1, in TypeError: 'NZ' object is not callable I found this post from Bengt Richter three years ago which addressed a related problem: http://mail.python.org/pipermail/python-list/2005-July/332961.html >Apparently the issue, as stated implicitly or explicitly by most of >you, is that new-style class instances essentially defer their magic >methods to the class's static versions of same. This is good to know :) Actually, it's not just the "magic" methods. If you have an instance a of a newstyle class A, any attribute lookup a.attr will undergo the same search first to see if attr is a descriptor object, and if not, *then* to look in the instance attribute directory. But the descriptor search doesn't start in inst.__dict__, it goes through the chain of classes and base classes provided by type(inst).mro(), which starts in type(inst). And for our class A instance a, type(a) will be A, so the search for a.attr starts there. Same applies to a.__str__. This ensures that all instances of the same class will share the same methods. The way a method, which is just a class variable with a function as its value, gets to be a callable bound method, is the same as any attribute lookup looking for a descriptor with a __get__ method (which a function also has, for this purpose). If the descriptor doesn't have a __set__ method as well, then an instance attribute takes priority. If there is a __set__ method, and instance attribute can't shadow the attribute name, and the descriptor __get__ method takes precedence. Unshadowed, a method search looks something like cbm = ((base for base in type(inst).mro() if 'attr' in base.__dict__) .next().__dict__['attr'].__get__(inst, type(inst))) if this doesn't succeed and meet the __set__ vs shadowing logic, then you get the instance attribute per se. ...but if I understand correctly, this suggests that if the runtime can't find the attribute in the chain of classes and base classes, it will look in the instance dictionary. The behavior of NZ above suggests that it the runtime is _not_ doing that for __call__ as it would for a non-special name: >>> class NZ(object): ... pass ... >>> nz = NZ() >>> nz.f = lambda : 42 >>> nz.f() 42 My question is: did something about the way the special method names are implemented change for new-style classes? best, and thanks in advance, Joe From deets at nospam.web.de Thu Jul 31 09:59:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 15:59:56 +0200 Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> Message-ID: <6fdut5Fb0nvuU2@mid.uni-berlin.de> squishywaffle at gmail.com wrote: > Greetings, > > I'm trying to wrap a function in a C library as a compiled C Python > module. Everything is going great, but I've hit a snag. There's a > function in the form of this: > > First the typedef: > typedef void(*FPtr_DeviceMessageHandler) (const DeviceMessage, const > char*); > > Then the actual function prototype: > FPtr_DeviceMessageHandler > RegisterDeviceMessageHandler(FPtr_DeviceMessageHandler); > > Whenever this USB device I'm using generates a message, it's then sent > to that function whose reference you passed to > RegisterDeviceMessageHandler(). Here's an example: > > void testfunc() { > printf("test"); > } > ...on to main() > RegisterDeviceMessageHandler(&testfunc) > > So I've defined a similar function on my C module to do just this, > using the passed function reference to allow the device to send > messages to a Python function of the user's choice. I'm just not sure > how to do this, and the tutorials I've been digging through don't > offer any help. I've found some functions that look promising, but > can't figure out how to cast the function reference from Python into > something the C RegisterDevice... function can handle. Here's what > I've got: > > static PyObject * > Py1_RegisterDeviceMessageHandler(PyObject *self, PyObject *args) > { > PyObject *handle, *parsed; > > if(!PyArg_ParseTuple(args, "O", handle)) { > return NULL; > } > > parsed = PyMethod_Function(handle); > I1_RegisterDeviceMessageHandler(PyMethod_Function(handle)); > > Py_RETURN_TRUE; > } // end Py1_RegisterDeviceMessageHandler() > > This fails since PyMethod_Function returns a PyObject. Is there a way > to cast this to something generic? Casting to (void*) didn't seem to > work. > > Thanks in advance! May I suggest you move to ctypes for wrapping? It's easier, pure python and callbacks are already built-in. Diez From max at alcyone.com Wed Jul 30 03:55:43 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Jul 2008 00:55:43 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <0f0b03c9-794b-430b-88ab-18a68505109e@a21g2000prf.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> <6d906dd5-bf5a-44d5-a5a8-3875027f6b91@v26g2000prm.googlegroups.com> <0f0b03c9-794b-430b-88ab-18a68505109e@a21g2000prf.googlegroups.com> Message-ID: Russ P. wrote: > On Jul 29, 11:36 pm, Erik Max Francis wrote: >> Russ P. wrote: >>> Come to think of it, shouldn't the list type have an "isempty" method? >>> Or does it? >> Yes. It's written: >> >> if not aList: >> ... > > As you know, that is not quite exactly the same thing. An "isempty" > method would fail if aList were an integer, and such failure might be > desirable if someone mistakenly had aList pointing to an integer. If you're that concerned about what the type is, then you can do explicit typechecks. Those are discouraged precisely because of Python's dynamism. But knock yourself out. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The actor is not quite a human being -- but then, who is? -- George Sanders From geraint.williams at gmail.com Sun Jul 13 07:55:06 2008 From: geraint.williams at gmail.com (GHZ) Date: Sun, 13 Jul 2008 04:55:06 -0700 (PDT) Subject: Why is there no GUI-tools like this for Windows? References: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> Message-ID: There is http://www.codeplex.com/IronPythonStudio From dullrich at sprynet.com Tue Jul 8 11:53:13 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 08 Jul 2008 10:53:13 -0500 Subject: "in"consistency? References: <87vdzhwf1v.fsf@benfinney.id.au> Message-ID: In article , Mel wrote: > Ben Finney wrote: > > > "David C. Ullrich" writes: > > > >> >>> 'ab' in 'abc' > >> True > >> >>> [1,2] in [1,2,3] > >> False > > > > > > > >> Is there a reason for the inconsistency? > > > > Probably. The special behaviour of string types was changed in Python > > 2.3, according to that document. > > As it stands, you'd get > > [1,2] in [1,2,3] == False > > [1,2] in [1, [1,2], 3] == True > > > This could be a good thing. Oh, of course that's a good thing - changing "in" for lists to give True there would be awful. I was wondering why it _does_ work that way for strings. Maybe the answer is "because it can" - for strings the sort of possible problem you point out can't come up. > Mel. > > -- David C. Ullrich From castironpi at gmail.com Wed Jul 30 02:40:16 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 29 Jul 2008 23:40:16 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> Message-ID: <5be6b2bf-7bf3-42d7-9f31-5ccc886ec786@t54g2000hsg.googlegroups.com> I note that IronPython and Python's pickle.dumps do not return the same value. Perhaps this relates to the absence of interpreter loop. >>> p.dumps( { 'a': True, 'b': set( ) } ) IPy: '(dp0\nVb\np1\nc__builtin__\nset\np3\n((lp4\ntp5\nRp2\nsVa \np6\nI01\ns.' CPy: "(dp0\nS'a'\np1\nI01\nsS'b'\np2\nc__builtin__\nset \np3\n((lp4\ntp5\nRp6\ns." You make me think of a more elaborate example. for k in range( 100 ): i= j() g= h+ i e= f+ g c= d+ e a= b+ c Here, j creates a new class dynamically, and returns an instance of it. Addition is defined on it but the return type from it varies. If I read you correctly, IPy can leave hundreds of different addition stubs laying around at the end of the for-loop, each of which only gets executed once or twice, each of which was compiled for the exact combination of types it was called for. I might construe this to be a degenerate case, and the majority of times, you'll reexecute stubs enough to outweigh the length of time the compilation step takes. If you still do the bounds checking, it takes extra instructions (C doesn't), but operation switch-case BINARY_ADD, (PyInt_CheckExact(v) && PyInt_CheckExact(w)), and POP and TOP, are all handled by the selection of stubs from $addSite. I'm read from last April: >>> The most interesting cases to me are the 5 tests where CPython is more than 3x faster than IronPython and the other 5 tests where IronPython is more than 3x faster than CPython. CPython's strongest performance is in dictionaries with integer and string keys, list slicing, small tuples and code that actually throws and catches exceptions. IronPython's strongest performance is in calling builtin functions, if/then/else blocks, calling python functions, deep recursion, and try/except blocks that don't actually catch an exception. <<< http://lists.ironpython.com/pipermail/users-ironpython.com/2007-April/004773.html It's interesting that CPython can make those gains still by using a stack implementation. I'll observe that IronPython has the additional dependency of the full .NET runtime. (It was my point 7/18 about incorporating the GNU libs, that to compile to machine-native, as a JIT does, you need the instruction set of the machine.) Whereas, CPython can disregard them, having already been compiled for it. I think what I was looking for is that IronPython employs the .NET to compile to machine instructions, once it's known what the values of the variables are that are the operands. The trade-off is compilation time + type checks + stub look-up. What I want to know is, if __add__ performs an attribute look-up, is that optimized in any way, after the IP is already in compiled code? After all that, I don't feel so guilty about stepping on Tim's toes. On Jul 30, 12:12?am, Dino Viehland wrote: > IronPython doesn't have an interpreter loop and therefore has no POP / TOP / etc... ? Instead what IronPython has is a method call Int32Ops.Add which looks like: > > ? ? ? ? public static object Add(Int32 x, Int32 y) { > ? ? ? ? ? ? long result = (long) x + y; > ? ? ? ? ? ? if (Int32.MinValue <= result && result <= Int32.MaxValue) { > ? ? ? ? ? ? ? ? return Microsoft.Scripting.Runtime.RuntimeHelpers.Int32ToObject((Int32)(result)); > ? ? ? ? ? ? } > ? ? ? ? ? ? return BigIntegerOps.Add((BigInteger)x, (BigInteger)y); > ? ? ? ? } > > This is the implementation of int.__add__. ?Note that calling int.__add__ can actually return NotImplemented and that's handled by the method binder looking at the strong typing defined on Add's signature here - and then automatically generating the NotImplemented result when the arguments aren't ints. ?So that's why you don't see that here even though it's the full implementation of int.__add__. > > Ok, next if you define a function like: > > def adder(a, b): > ? ? ? ? return a + b > > this turns into a .NET method, which will get JITed, which in C# would look something like like: > > static object adder(object a, object b) { > ? ? return $addSite.Invoke(a, b) > > } > > where $addSite is a dynamically updated call site. > > $addSite knows that it's performing addition and knows how to do nothing other than update the call site the 1st time it's invoked. ?$addSite is local to the function so if you define another function doing addition it'll have its own site instance. > > So the 1st thing the call site does is a call back into the IronPython runtime which starts looking at a & b to figure out what to do. ?Python defines that as try __add__, maybe try __radd__, handle coercion, etc... ?So we go looking through finding the __add__ method - if that can return NotImplemented then we find the __radd__ method, etc... ?In this case we're just adding two integers and we know that the implementation of Add() won't return NotImplemented - so there's no need to call __radd__. ?We know we don't have to worry about NotImplemented because the Add method doesn't have the .NET attribute indicating it can return NotImplemented. > > At this point we need to do two things. ?We need to generate the test which is going to see if future arguments are applicable to what we just figured out and then we need to generate the code which is actually going to handle this. ?That gets combined together into the new call site delegate and it'll look something like: > > static void CallSiteStub(CallSite site, object a, object b) { > ? ? ? ? if (a != null && a.GetType() == typeof(int) && b != null && b.GetType() == typeof(int)) { > ? ? ? ? ? ? return IntOps.Add((int)a, (int)b); > ? ? ? ? } > ? ? ? ? return site.UpdateBindingAndInvoke(a, b); > > } > > That gets compiled down as a lightweight dynamic method which also gets JITed. ?The next time through the call site's Invoke body will be this method and things will go really fast if we have int's again. ?Also notice this is looking an awful lot like the inlined/fast-path(?) code dealing with int's that you quoted. ?If everything was awesome (currently it's not for a couple of reasons) the JIT would even inline the IntOps.Add call and it'd probably be near identical. ?And everything would be running native on the CPU. > > So that's how 2 + 2 works... ?Finally if it's a user type then we'd generate a more complicated test like (and getting more and more pseudo code to keep things simple): > > if (PythonOps.CheckTypeVersion(a, 42) && PythonOps.CheckTypeVersion(b, 42)) { > ? ? return $callSite.Invoke(__cachedAddSlot__.__get__(a), b); > > } > > Here $callSite is another stub which will handle doing optimal dispatch to whatever __add__.__get__ will return. ?It could be a Python type, it could be a user defined function, it could be the Python built-in sum function, etc... ?so that's the reason for the extra dynamic dispatch. > > So in summary: everything is compiled to IL. ?At runtime we have lots of stubs all over the place which do the work to figure out the dynamic operation and then cache the result of that calculation. > > Also what I've just described is how IronPython 2.0 works. ?IronPython 1.0 is basically the same but mostly w/o the stubs and where we use stub methods they're much less sophisticated. > > Also, IronPython is open source -www.codeplex.com/IronPython > > -----Original Message----- abriged: > This is from 7/22/08, same author: > > I wouldn't say "can't". ?The current CPython VM does not compile > > code. ?It COULD. ?The C#/.NET VM does. > > Three big claims here that I breezed right over and didn't believe. > > > It COULD. > > I'm evidently assuming that if it could, it would. > > > The current CPython VM does not compile code. > > Therefore it couldn't, or the assumption is wrong. ?Tim says it is. > And the glaring one-- > > WHY NOT? ?Why doesn't CPython do it? > > I am imagining that every Python implementation has something like > it. ?If IronPython does not, in particular, not have the 'POP(); > TOP();' sequence, then it isn't running on a stack machine. ?Is the > IronPython code open source, and can someone link to it? ?I'm not > wading through it from scratch. ?What does it have instead? ?Does > dynamic typing still work? From george.sakkis at gmail.com Thu Jul 3 22:09:54 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 3 Jul 2008 19:09:54 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> <7db52b03-7a8a-40c4-b3cb-f6dccd273b90@59g2000hsb.googlegroups.com> <45ce2acc-e4b5-4762-8daa-b67a78b02411@w7g2000hsa.googlegroups.com> Message-ID: On Jul 3, 7:51 pm, Mensanator wrote: > On Jul 3, 6:24 pm, George Sakkis wrote: > > > Taking into account 2.6 too (we're not talking about only 3.0 here), > > probably not much less than those who even know what is gmpy, let > > alone dismiss a beta Python release because their obscure pet module > > is not available yet. > > That was just an example. When you consider ALL the pet > modules like PIL, Numpy, Win32, etc., that's a lot, isn't it. A few points: - The OP acknowledged he's a newbie, and as a newbie he'll probably spend some time getting used to the language and the standard library before jumping to the dozens 3rd party packages. - I am sure many Python users are productive without ever touching an external package; that is after all the point of "batteries included". - Even if they do have external dependencies, chances are that they are pure Python modules, which typically work without modification on new 2.x versions. > I was just trying to be helpful (I admit I often sound > negative when I'm not trying to be). Well, something like "Until then, such solutions are worthless, i.e., of no value" is too strong, subjective and biased to be really helpful. George From fredrik at pythonware.com Mon Jul 21 16:55:14 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 22:55:14 +0200 Subject: Seriously, though, about LLVM In-Reply-To: References: Message-ID: mk wrote: >>> This project has gained some publicity. There's IronPython, right, so >>> has anybody thought about implementing Python using LLVM as backend, >>> as it seems not out of question at all? >> >> you mean like: >> >> http://llvm.org/ProjectsWithLLVM/#pypy >> >> ? > > No, I don't mean "Python written in Python", with whatever backend. so anyone attempting to write a Python implementation for the LLVM aren't allowed to use Python for the front-end? why not? From bj_666 at gmx.net Fri Jul 18 03:01:12 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Jul 2008 07:01:12 GMT Subject: None in comparison References: <549f01d2-1d15-4b0d-9440-a9402c0449ff@b2g2000prf.googlegroups.com> Message-ID: <6eatdoF67cpfU1@mid.uni-berlin.de> On Thu, 17 Jul 2008 23:52:13 -0700, r.grimm wrote: > Hello, > I'm a little confused about None in comparison. > >>>> id ( None ) > 3086100672L >>>> id ( 1 ) > 134541104 >>>> None < 1 > True >>>> > > I thought, the id of the object is the last comparison criterion. Obviously that expectation is false. The result of a comparison between different types, with no `__cmp__()` method that says otherwise, is a arbitrarily but consistent ordering by type. The language doesn't even guarantee that it must be consistent in different runs of the same program in the same interpreter, just within one run. So if you plan to rely on such implementation details, your program is broken. Ciao, Marc 'BlackJack' Rintsch From cyril.bazin at info.unicaen.fr Thu Jul 17 07:48:21 2008 From: cyril.bazin at info.unicaen.fr (Cyril Bazin) Date: Thu, 17 Jul 2008 13:48:21 +0200 Subject: Problem with MySQLdb and mod_python In-Reply-To: References: Message-ID: Thanks for your reply The apache log contains lines like : [Tue Jul 15 23:31:01 2008] [notice] mod_python (pid=11836, interpreter='www.toto.fr'): Importing module '/usr/local/apache2/htdocs/intranet/courrier/test.py' [Tue Jul 15 23:31:02 2008] [notice] child pid 11836 exit signal Segmentation fault (11) [Tue Jul 15 23:31:19 2008] [notice] mod_python (pid=11764, interpreter='www.toto.fr'): Importing module '/usr/local/apache2/htdocs/intranet/courrier/test.py' [Tue Jul 15 23:31:19 2008] [notice] child pid 11764 exit signal Segmentation fault (11) I think the problem comes from the MySQLdb module. If I can't find another solution, I think I will downgrade the MySQLdb version to 1.2.1 Cyril On Thu, Jul 17, 2008 at 7:27 AM, Lawrence D'Oliveiro wrote: > In message , Cyril Bazin > wrote: > >> But it seems, after many tests, that the script stops at the >> instruction : "c.execute(requete)" > > What's the error message? This should be in Apache's error_log file. > -- > http://mail.python.org/mailman/listinfo/python-list > From alexnbryan at gmail.com Wed Jul 16 14:37:35 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 11:37:35 -0700 (PDT) Subject: py2exe issues with pictures and icons Message-ID: <18493908.post@talk.nabble.com> Hello I am sure most of you are familiar with py2exe. I am having a bit of a problem. See the program has a few pictures involved and the .ico it uses for the windows. However, the pictures are stored in the same directory as the source, something like: C:\Docs and settings\me\My docs\python\program. When I run the program for the interpreter, just as a .py, everything works just as it should. However, when I compile the main source as an .exe, and say let a friend try the program. It fails because it is missing the .ico. The catch, is I don't want to have it have to installed, at least at this point, I want it to be able to just run. So how can I make it just run from any computer with the files not being in the immediate directory. If that is not possible, how can I put them in the immediate directory and still make it work. Because that directory may change a lot so the path will change. Just a few questions. I hope someone out there can help me out! -- View this message in context: http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp18493908p18493908.html Sent from the Python - python-list mailing list archive at Nabble.com. From musiccomposition at gmail.com Tue Jul 22 23:04:04 2008 From: musiccomposition at gmail.com (Benjamin) Date: Tue, 22 Jul 2008 20:04:04 -0700 (PDT) Subject: sys.stderr.write returns string length in Python 3 References: Message-ID: <43ab2eb4-31ec-4574-ab54-4467fa89d187@27g2000hsf.googlegroups.com> Alan G Isaac wrote: > Is this new behavior intentional? :: Yes, it's in the PEP http://www.python.org/dev/peps/pep-3116/. > > >>> sys.stderr.write("thisisatest\n") > thisisatest > 12 > > Here is the reason for it: > > >>> help(sys.stderr.write) > Help on method write in module io: > write(self, s: str) method of io.TextIOWrapper instance > > Thank you, > Alan Isaac From yanowitzmjy at yahoo.com Tue Jul 15 17:26:09 2008 From: yanowitzmjy at yahoo.com (Michael J. Yanowitz) Date: Tue, 15 Jul 2008 14:26:09 -0700 (PDT) Subject: Need Python Programmer (preferentially in Los Angeles) In-Reply-To: Message-ID: <594727.17052.qm@web58712.mail.re1.yahoo.com> Hello: I think I can do it but would like more details. I have been doing GUI work for years. I have been doin Python only for the last 2 and 1/2 years. The GUI work I have done there has been with TkInter and wxPython. Thanks: Michael Yanowitz --- On Tue, 7/15/08, robnhood00 wrote: > From: robnhood00 > Subject: Need Python Programmer (preferentially in Los Angeles) > To: python-list at python.org > Date: Tuesday, July 15, 2008, 4:54 PM > I need a python programmer that can integrate graphics into > an > existing python application. The application is a basic > application > and the job should be pretty easy for an experienced Python > programmer. Los Angeles programmer is preferred but this > can > obviously be done from anywhere. > Please contact me at robnhood007 at yahoo.com is you can help > me. > Thank you. > -- > http://mail.python.org/mailman/listinfo/python-list From bj_666 at gmx.net Wed Jul 30 14:02:20 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Jul 2008 18:02:20 GMT Subject: Possible to have multiple loop variables? References: <5ff22b51-88e9-405c-aeb9-7b0abe9cf935@r66g2000hsg.googlegroups.com> Message-ID: <6fbolbFaidktU1@mid.uni-berlin.de> On Wed, 30 Jul 2008 10:49:58 -0700, laredotornado wrote: > I don't know why I thought this would work, but I would like to have 3 > variables in my for loop per iteration. Those familiar will know that > this > > ms1 = {'managed1':7019:8020,'managed2':7020:8021} for m, lp, ssl_lp in > ms1.items(): > managedServer = create(m,'Server') > print 'creating managed server '+m > managedServer.setListenAddress('147.191.71.70') > managedServer.setListenPort(lp) > managedServer.setEnabled(0) > cd('SSL/cgServer') > managedServer.setEnabled(1) > managedServer.setListenPort(ssl_lp) > managedServer.setCluster(clus1) > > causes > > File "/export/third-party/etsbea/home/etsbea/tests/wlst/ > createcluster.py", line 9 > ms1 = {'managed1':7019:8020,'managed2':7020:8021} > ^ > SyntaxError: invalid syntax > > > How would I set up the ms1 array such that I can use three items per > object? `ms1` is a dictionary and not an array. You could use a tuple as value: In [5]: ms1 = {'managed1': (7019, 8020), 'managed2': (7020, 8021)} In [6]: for a, (b, c) in ms1.iteritems(): ...: print a, b, c ...: managed1 7019 8020 managed2 7020 8021 Ciao, Marc 'BlackJack' Rintsch From iainking at gmail.com Fri Jul 18 09:34:44 2008 From: iainking at gmail.com (Iain King) Date: Fri, 18 Jul 2008 06:34:44 -0700 (PDT) Subject: Best Python packages? References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> <17861f55-8ad1-4703-ad22-838675f2afc4@w1g2000prk.googlegroups.com> Message-ID: On Jul 18, 11:23?am, Ben Sizer wrote: > On Jul 16, 3:31?pm, Fredrik Lundh wrote: > > > Ben Sizer wrote: > > > make my development a lot easier. > > > Knowing what kind of development you do might help, of course. ?Some > > libraries are excellent in some contexts and suck badly in others... > > Sure. Mostly I'm just interested in what's out there though. In C++ > you have Boost which everybody knows are a source of high quality > libraries, covering a fairly wide set of applications. Obviously > that's more low-level and less application specific, and the Python > standard libs do pretty much everything that is in Boost, but it's > that sort of peer-reviewed and widely-applicable list that I'd like to > see. > > I (attempt to) use TurboGears for web development and that depends on > a whole bunch of libraries - SQLObject, PyProtocols, RuleDispatch, > SimpleJson, FormEncode, etc - and I would never have heard of these if > TurboGears' exposure of its internals wasn't so common. Some of these > are web-specific but some are not. And I'd never know to look for them > specificially, because in many cases it wouldn't occur to me that they > exist. (eg. Object-Relational Mappers like SQLObject may be obvious if > you come from certain areas of IT, but I'd never heard of them before > I started with TurboGears.) > > For what it's worth, my main areas of interest are gaming, multimedia, > and web development. But I just like to hear about anything that > people might use which makes their life a lot easier and which perhaps > is not application specific - like ORMs or something similar. > > > Looking at things that larger projects and distributions use can also be > > a good idea. ?For example, if you're doing scientific stuff, go directly > > to enthought.com. ?If you're doing web stuff, look at the libraries big > > Django applications use. ?Etc. > > Sadly, I know just as little about what major applications are out > there as I do about what libraries are out there! > > -- > Ben Sizer Well, if you're looking for a list of excellent 3rd party Python libraries, then I can give you the ones I like and use a lot: wxPython : powerful GUI library which generates native look & feel PIL : Imaging Library - if you need to manipulate bitmaps pyGame : SDL for python BeautifulSoup : for real-world (i.e. not-at-all-recommendation- compliant) HTML processing Iain From __peter__ at web.de Tue Jul 8 15:09:37 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Jul 2008 21:09:37 +0200 Subject: Relative Package Import References: Message-ID: Robert Hancock wrote: > mypackage/ > __init__.py > push/ > __init__.py > dest.py > feed/ > __init__py > subject.py > > In subject.py I have > from ..push import dest > > But i receive the error: > Caught exception importing module subject: > File "/usr/local/python/lib/python2.5/site-packages/pychecker/ > checker.py", line 621, in setupMainCode() > module = imp.load_module(self.moduleName, file, filename, smt) > File "subject.py", line 1, in () > from ..feed import dest > ValueError: Attempted relative import in non-package > > What am I missing? When you run subject as a file pychecker mypackage/feed/subject.py subject.py is regarded as a standalone script, not as part of a package. Try pychecker mypackage.feed.subject instead to invoke the module via the standard import mechanism. Peter From thisisspam0 at gmail.com Fri Jul 4 20:18:49 2008 From: thisisspam0 at gmail.com (thisisspam0 at gmail.com) Date: Fri, 4 Jul 2008 17:18:49 -0700 (PDT) Subject: http://vivalacuba.blogspot.com/ Message-ID: <70a28232-9657-4525-99e9-adc5f2befef1@e39g2000hsf.googlegroups.com> http://vivalacuba.blogspot.com/ From lie.1296 at gmail.com Tue Jul 22 09:19:05 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 22 Jul 2008 20:19:05 +0700 Subject: Change PC to Win or Windows In-Reply-To: <20080721225027.GF8793@dragontoe.org> References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> <82873ccd-9667-4dfa-9ec4-a9ac7c672aa7@w1g2000prk.googlegroups.com> <0f3272c1-b1a7-4aef-9e4a-0f03af823a2d@z11g2000prl.googlegroups.com> <20080721225027.GF8793@dragontoe.org> Message-ID: <1216732745.6470.46.camel@lieryan-laptop> On Mon, 2008-07-21 at 18:50 -0400, Derek Martin wrote: > On Mon, Jul 21, 2008 at 02:47:31PM -0700, Lie wrote: > > Common usage isn't always correct. > > Actually it is, inherently... When usage becomes common, the language > becomes redefined, and its correctness is therefore true by identity > (to borrow a mathematical term). The scholars complain for a while, > but eventually capitulate, and re-write the dictionary. Language > bends to its use by the people, not the other way around. Your > assumption is the opposite, and therefore all of your argument is > false. But until the dictionary is rewritten, it is incorrect usage. Since dictionary isn't rewritten unless (nearly) the whole world agrees with it, not all parts of the world used the term PC exclusively for Windows-based computer, in this part of the world specifically, PC is used for any desktop computers. Therefore your argument is false (at least: yet). > > For example, a physicist would not use weight when he meant mass. > > much, but in technical environment doing so would embarrass him. In > > this analogy, I consider download page for a software source code to > > be a technical area. > > Your analogy is still broken. The term "PC" has been used BY > TECHNCIAL PEOPLE, IN A TECHNICAL CONTEXT, to mean Microsoft on Intel, > FOR DECADES. ?Yes, and they are wrong on using it. So do some physicist, before the clear distinction is drawn explicitly between mass and weight. FOR DECADES, people used the term PC for all sorts of things, in the most technically correct usage, only IBM-branded home computers could be called a PC, since PC is ?officially their advertising term. However, since Personal Computer is a brand-neutral term (unlike iMac, Lifebook, etc), it have the tendency to be extended (by the people) to include other personally owned computers as well. The technically correct extension would be "PC is computers that is designed and marketed for personal possession and use", which means it doesn't matter what OS it is, what hardware it uses. A debate (or a long observation to the people) might be needed to determine whether that definition extension is acceptable, but the definition extension you mentioned: "PC is Windows-based computer" needs no debate, it is completely wrong and is a baseless misunderstanding. > + Authors of technical books, manuals, and other forms of > documentation have refered to them as PCs... for decades. > > + Educators in CS and EE at major universities have refer to them as > PCs, since at least as early as 1988 (when I started college). I'm sure they were mentioning IBM-PC and its clones, not mentioning Windows itself. (Well, it's true that IBM-PC and its clones is mostly Windows-based, but PC is a term for the combination of hardware and software that makes a personal computer, in the current incorrect usage, PC is Windows, a software.) > + Industry news publications such as Computer World have refered to > them as PCs, for decades. > > + There are even whole magazines dedicated to them! (PC Magazine, PC > Shopper, PC World, PC Gamer, etc.) They are dedicated to Microsoft > on Intel, and have existed (at least in some cases) long before > Apple started talking about PCs in their ads. Excuse me, those magazines (at least in this part of the world) also contain non-Microsoft articles. The fact that Windows articles is the dominant topic, is solely because most of their subscribers are Windows user, it is not as profitable to write about Linux and Mac and Unix. > All of this has been going on, essentially since there has been such > a thing as the IBM PC. I'm sorry, but you sir, are quite simply, > plainly, and completely, wrong. Compounded with misunderstanding, you sir, are very well ignorant. > With a catastrophic amount of > written documentation, written by technical people in the computer > industry over the last 20+ years, to prove it. > > > > > Apple popularizes the term by explicit marketing, > > > > > > And here is the last point you are missing: Apple does no such > > > thing. > > > > They did, by using the term PC to refer to other computers. > > APPLE CAN NOT POPULARIZE A TERM WHICH IS ALREADY POPULAR. Sure it catches the wave that has been going on for some time. And use it to their own advantage. I've mentioned that Apple could not be blamed so much for this, since with or without them, the term would become popular, although its meaning mightn't have been as twisted as nowadays. > > This kind of advertising Apple (the computer company) used is > > misleading, since it implied that their PC is not a PC. > > They haven't implied anything; they're stating it outright! Apple > sells personal computers, but they do not sell PCs. Apple's personal > computer is NOT a PC, and never was, and never will be. It's an > Apple. Apple's personal computer is NOT a PC? Aren't you contradicting yourself? Just like what Apple, you have just said: "I'm Apple, I'm a personal computer, but I'm not a personal computer." Completely nonsense. Last, probably my strongest argument: "If the folder has been called WinBuild/WindowsBuild, there is no need for arguments. PC as Windows is an arguable usage, Windows as Windows is not arguable." |||| |||| ____ / \ | 2c | \____/ _________ From pluskid at gmail.com Thu Jul 24 02:39:13 2008 From: pluskid at gmail.com (pluskid) Date: Wed, 23 Jul 2008 23:39:13 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: On Jul 24, 1:41?pm, Jordan wrote: > Hi everyone, > > I'm a big Python fan who used to be involved semi regularly in > comp.lang.python (lots of lurking, occasional posting) but kind of > trailed off a bit. I just wrote a frustration inspired rant on my > blog, and I thought it was relevant enough as a wider issue to the > Python community to post here for your discussion and consideration. > [...snip...] +1 for most of your opinion. I was also bitten by the __eq__/__ne__ problem this morning. :) From nagle at animats.com Thu Jul 31 11:44:19 2008 From: nagle at animats.com (John Nagle) Date: Thu, 31 Jul 2008 08:44:19 -0700 Subject: Swap memory in Python ? - three questions In-Reply-To: References: Message-ID: <4891d957$0$17213$742ec2ed@news.sonic.net> Robert LaMarca wrote: > Hi, > > I am using numpy and wish to create very large arrays. My system is AMD 64 > x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a 15 GB swap > drive. Does a full 64-bit version of CPython, one where all pointers and sizes are 64 bits, even exist? John Nagle From steve at REMOVE-THIS-cybersource.com.au Thu Jul 31 18:58:25 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Jul 2008 22:58:25 GMT Subject: How smart is the Python interpreter? References: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> Message-ID: <00a23efb$0$20313$c3e8da3@news.astraweb.com> On Thu, 31 Jul 2008 04:09:57 -0700, ssecorp wrote: > def str_sort(string): > s = "" > for a in sorted(string): > s+=a > return s > > > if i instead do: > > def str_sort(string): > s = "" > so = sorted(string) > for a in so: > s+=a > return s > > > will that be faster Oh dear. Premature optimization, the root of all (programming) evil. You can test which is faster by using the timeit module. In the interactive interpreter, define the two functions above with different names, and a string to supply as argument. Then call: from timeit import Timer t1 = Timer('str_sort1(s)', 'from __main__ import str_sort1, s') t2 = Timer('str_sort2(s)', 'from __main__ import str_sort2, s') t1.repeat(number=1000) t2.repeat(number=1000) I'll be hugely surprised if there was any meaningful difference. > or the interpreter can figure out that it only has > to do sorted(string) once? or that kind of cleverness is usually > reserved for compilers and not interpreters? Python uses a compiler. It doesn't do a lot of clever optimization, but it does some. In this case, no, it doesn't optimize your function, so technically the first may be a tiny bit faster. But, frankly, your function is so painfully inefficient, doing a lot of useless work, that you probably won't notice any real difference. The correct way to do what you have done above is ''.join(sorted(s)). Anything else is much slower. >>> def sort_str(s): ... ss = "" ... for c in sorted(s): ... ss += c ... return ss ... >>> s = "abcdefghijklmnopqrstuvwxyz"*100 >>> from timeit import Timer >>> t1 = Timer('"".join(sorted(s))', 'from __main__ import s') >>> t2 = Timer('sort_str(s)', 'from __main__ import sort_str, s') >>> t1.repeat(number=1000) [1.6792540550231934, 1.6882510185241699, 1.660383939743042] >>> t2.repeat(number=1000) [2.5500221252441406, 2.4761130809783936, 2.5888760089874268] -- Steven From circularfunc at gmail.com Mon Jul 21 23:06:44 2008 From: circularfunc at gmail.com (ssecorp) Date: Mon, 21 Jul 2008 20:06:44 -0700 (PDT) Subject: tail-rec decorator, well still blows the stack... References: Message-ID: I my function not proper tail-recursion? because this doesn't blow the stack: #!/usr/bin/env python2.4 # This program shows off a python decorator( # which implements tail call optimization. It # does this by throwing an exception if it is # it's own grandparent, and catching such # exceptions to recall the stack. import sys class TailRecurseException: def __init__(self, args, kwargs): self.args = args self.kwargs = kwargs def tail_call_optimized(g): """ This function decorates a function with tail call optimization. It does this by throwing an exception if it is it's own grandparent, and catching such exceptions to fake the tail call optimization. This function fails if the decorated function recurses in a non-tail context. """ def func(*args, **kwargs): f = sys._getframe() if f.f_back and f.f_back.f_back \ and f.f_back.f_back.f_code == f.f_code: raise TailRecurseException(args, kwargs) else: while 1: try: return g(*args, **kwargs) except TailRecurseException, e: args = e.args kwargs = e.kwargs func.__doc__ = g.__doc__ return func @tail_call_optimized def factorial(n, acc=1): "calculate a factorial" if n == 0: return acc return factorial(n-1, n*acc) print factorial(10000) # prints a big, big number, # but doesn't hit the recursion limit. @tail_call_optimized def fib(i, current = 0, next = 1): if i == 0: return current else: return fib(i - 1, next, current + next) print fib(10000) # also prints a big number, # but doesn't hit the recursion limit. From iainking at gmail.com Mon Jul 7 05:56:01 2008 From: iainking at gmail.com (Iain King) Date: Mon, 7 Jul 2008 02:56:01 -0700 (PDT) Subject: How to bypass Windows 'cooking' the I/O? (One more time, please) II References: Message-ID: On Jul 7, 10:18?am, Dennis Lee Bieber wrote: > On Mon, 07 Jul 2008 01:03:10 -0700, norseman > declaimed the following in comp.lang.python: > > > > > ?> Normal file I/O sequence: > > > ?> fp = open(target, 'wb') > > > ?> fp.seek(-1, 2) > > > ?> fp.write(record) > > > ? ?Except it doesn't do that in Windows. See below. > > ? ? ? ? I wouldn't expect that sequence to work on any system... The "w" > implies "create new file, or truncate existing file to 0-bytes, then > write data to it" -- with no seeking permitted. You must include the "+" > to do seeking, and if you want to retain the existing file contents you > probably need to open with "a+" ("a" for append). > > ? ? ? ? The rest of your situation I won't touch. Other than to wonder why > the situation hasn't hit any of the various database servers which must > be operating in binary mode, and perform lots of seeking... Surely > somewhere out someone else must have encountered a seek crossing an > apparent mark (which isn't a normal Windows sequence anyway -- > since Windows uses for EOL, I'd have expected to see a problem > if backing over a ) > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? ?wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ lol @ op not finding the answer to his question in the archives, then being answered again by someone who doesn't let his answer go in the archive. How useful. From arnimavidyarthy at gmail.com Fri Jul 18 06:33:50 2008 From: arnimavidyarthy at gmail.com (arnimavidyarthy at gmail.com) Date: Fri, 18 Jul 2008 03:33:50 -0700 (PDT) Subject: trying to match a string Message-ID: Hi, Hi, I am taking a string as an input from the user and it should only contain the chars:L , M or R I tried the folllowing in kodos but they are still not perfect: [^A-K,^N-Q,^S-Z,^0-9] [L][M][R] [LRM]?L?[LRM]? etc but they do not exactly meet what I need. For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. regards, SZ The string may or may not have all the three chars. From CracKPod at googlemail.com Mon Jul 14 17:37:08 2008 From: CracKPod at googlemail.com (CracKPod) Date: Mon, 14 Jul 2008 14:37:08 -0700 (PDT) Subject: Python Tiddlywiki class Message-ID: Hello, I wrote a Python class to interact with the TiddlyWiki. In case you are interested you can find it on my blog: http://crackpod.bplaced.net/ CracKPod From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 15:18:36 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 21:18:36 +0200 Subject: New to Python, familiar with Perl - Seeking info sources In-Reply-To: <18c8fc73-8ff9-4640-a020-de0be4b76ca4@z72g2000hsb.googlegroups.com> References: <18c8fc73-8ff9-4640-a020-de0be4b76ca4@z72g2000hsb.googlegroups.com> Message-ID: <4888d583$0$26943$426a74cc@news.free.fr> Brett Ritter a ?crit : > After many years happily coding Perl, I'm looking to expand my > horizons. [no flames please, I'm pretty aware of Perl's strengths and > weaknesses and I'm just here to learn more, not to enter religious > debates]. > > I've gone through some of the online tutorials and I'll be browsing > the reference before starting the "code a lot" phase. > > My question is: What are the best sources to learn best practices or > get the answers to questions? Are there any good sources to tell me > what Perl habits are good/bad in the Python paradigm? What about > common packages that will change my life? (I do a lot of web work, > but also a lot of DB reporting) wrt/ "best practices" and writing pythonic code, the best thing to do is probably to lurk here and post code snippets asking for code reviews (we just *love* that !-) Others already pointed you to useful readings like diveintopython. I'd like to add Fredrik Lundh (aka the effbot)'s excellent website to the list: http://effbot.org/ wrt/ packages, first take time to read the stdlib's package index - I've a couple time Reinvented The Square Wheel(tm) when a well-rounded one was just an import away. You'll also find useful resources on pypi (the Python's Package Index). > I'm also working as a Java developer > primarily, so I'm glad to see that Jython has been resurrected, but > I'm focusing on vanilla Python for the moment. > > As examples: PerlMonks has been my info source. The Perl Best > Practices and Higher Order Perl books have been my tutors into better > coding practices. This newsgroup, diveintopython, effbot.org... > CPAN has my life easy, Not quite close to CPAN, but the closest we actually have IMHO: pypi (for the package index) and easy_install. > giving me access to the DBI, > Class::DBI (and its successors), low-level : Python db-api hi-level : SQLAlchemy > HTML::FillInForm, Don't know what this one do... > Data::FormValidator, FormEncode > CGI::Application, cgi and wsgi... > and Text::CSV::Simple modules You probably want the csv package (in the stdlib). You may also want to have a look at templating engines like Mako or Genshi. > that are staples of my coding. The (occasionally complete) Perl > Advent calendars have proven to be a good source to learn about > helpful modules that I might not otherwise stumble across. python-announces ? > (I've encountered Django, but I'm getting my fill of "frameworks" from > Java for the moment, so I'm looking for lightweight pieces at the > moment) While not exactly lighweight by Python's standards, Django is certainly way lighter than the usual Java web framework. But Python is known to have more web frameworks than keywords, so you may find something lightweight enough for your taste - or of course write your own !-) From bob.martin at excite.com Thu Jul 31 04:46:52 2008 From: bob.martin at excite.com (Bob Martin) Date: Thu, 31 Jul 2008 08:46:52 GMT Subject: interpreter vs. compiled References: <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <4rl294duo83eujnq6tjbk215mavpl87o9r@4ax.com> Message-ID: <0_ekk.35361$E41.10772@text.news.virginmedia.com> in 76135 20080731 090911 Dennis Lee Bieber wrote: >On Thu, 31 Jul 2008 06:17:59 GMT, Tim Roberts declaimed >the following in comp.lang.python: > > >> And again, I never said that it did. CPython is an interpreter. the >> user's code is never translated into machine language. >> >Using that definition, the UCSD P-code Pascal and Java are also not >"compilers" -- all three create files containing instructions for a >non-hardware virtual machine. > >The only difference between Python, UCSD Pascal, and Java is that >Python foregoes the explicit "compiler" pass. > >BASIC (classical microcomputer implementations -- like the one M$ >supplied for TRS-80s) is an interpreter -- the pre-scan of the source >merely translated BASIC keywords into a byte index, not into opcodes for >any virtual machine. You are confusing languages with implementations, as I pointed out earlier. Java is a language. I have used at least 2 Java compilers, ie they compiled Java source to native machine language. From __peter__ at web.de Wed Jul 2 04:36:03 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Jul 2008 10:36:03 +0200 Subject: Problem with a for loop and a list References: Message-ID: Alexnb wrote: > > I am not sure what is going on here. Here is the code that is being run: > > def getWords(self): > self.n=0 The value of self.n only makes sense within the method, so you better use the local variable n instead of the instance attribute self.n > for entry in self.listBuffer: > self.wordList[self.n] = entry.get() > self.n=self.n+1 > > print self.wordList > > This is the "listBuffer" that you see: > > self.listBuffer=[self.e1, self.e2, self.e3, self.e4, > self.e5, self.e6, self.e7, self.e8, > self.e9, self.e10, self.e11, > self.e12, self.e13, self.e14] > > (side note, those are all tkinter entry widgets, and the get() function > gets the text) > > this is the error the interpreter is giving me when I run it: > > self.getWords() > File "C:/Documents and Settings/Alex/My > Documents/PYTHON/DictionaryApp/The > GUI.py", line 153, in getWords > self.wordList[self.n] = entry.get() > IndexError: list assignment index out of range > > I have no idea what "list assignment index out of range means?!?! As Albert explained this means that wordList is shorter than listBuffer. The most flexible remedy is to have wordList grow dynamically: def getWords(self): wordList = [] for entry in self.listBuffer: wordList.append(entry.get()) print wordList If for some reason you want to remember the values in wordList add self.wordList = wordList to the method (this is the same consideration as for self.n versus n). Peter From mimi.vx at gmail.com Thu Jul 3 07:00:19 2008 From: mimi.vx at gmail.com (mimi.vx) Date: Thu, 3 Jul 2008 04:00:19 -0700 (PDT) Subject: multithreading in python ??? References: <674A912AA405814397CED58601AC8E251554964241@BLRKECMBX05.ad.infosys.com> Message-ID: <9e0033c8-9292-486a-9c82-bb95f7026b23@k30g2000hse.googlegroups.com> On Jul 3, 12:40?pm, Laszlo Nagy wrote: > Abhishek Asthana wrote: > > > Hi all , > > > I ?have large set of data computation and I want to break it into > > small batches and assign it to different threads .I am implementing it > > in python only. Kindly help what all libraries should I refer to > > implement the multithreading in python. > > You should not do this. Python can handle multiple threads but they > always use the same processor. (at least in CPython.) In order to take > advantage of multiple processors, use different processes. > > ? L or use parallelpython module, very good in multi processor| multimachine prog. in python From grante at visi.com Tue Jul 15 14:28:51 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 15 Jul 2008 13:28:51 -0500 Subject: Testing for Internet Connection References: <18460572.post@talk.nabble.com> <1216113021.24038.0@proxy02.news.clara.net> Message-ID: On 2008-07-15, Alexnb wrote: > What exactly do you think will work? I am not sure what you > think I should do? If I use urlopen("http://www.google.com") > and I am not connected, I am not going to get an exception, > the program will fail. Bullshit. You get an exception. Here's my program: import urllib2 try: con = urllib2.urlopen("http://www.google.com/") data = con.read() print data except: print "failed" If I run it with no internet connection, I get this: $ python testit.py failed If I bring up the internet connection, then I get a bunch of HTML. -- Grant Edwards grante Yow! I'm ZIPPY the PINHEAD at and I'm totally committed visi.com to the festive mode. From fredrik at pythonware.com Thu Jul 24 16:05:00 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 22:05:00 +0200 Subject: need help with introducing more traffic In-Reply-To: <6es0m9F8mehmU1@mid.uni-berlin.de> References: <632875.28836.qm@web51808.mail.re2.yahoo.com> <6es0m9F8mehmU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> umm. are you saying that you run ruby-lang.org and want to write a >> stress tester in Python just for the fun of it, or are we missing >> something here... > > This: > > http://www.pylot.org/ > > Seems as if he *is* using various languages for fun... "load testing" other people's sites are known as something else, of course. From amnorvend at gmail.com Fri Jul 18 15:26:35 2008 From: amnorvend at gmail.com (Jason Baker) Date: Fri, 18 Jul 2008 12:26:35 -0700 (PDT) Subject: __del__ methods References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> <6ec859F67cpfU5@mid.uni-berlin.de> Message-ID: <17b5febd-602d-4d7e-9449-6cabf4d95e41@27g2000hsf.googlegroups.com> On Jul 18, 2:10?pm, Marc 'BlackJack' Rintsch wrote: > On Fri, 18 Jul 2008 11:31:20 -0700, Jason Baker wrote: > > I have a class that I need to do some finalization on when it dies. ?I > > know I can use the __del__ method, but I seem to recall that it > > impedes garbage collection. ?Is this the case? > > `__del__()` is not a deterministic destructor. ?So forget about reliable > automatic clean up. ?Do it yourself with an explicit call to a `close()` > method or something like that. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch I don't necessarily need deterministic cleanup. And I plan on doing something like a close() method as well. But I'd just like to make sure nothing slips between the cracks. :) From kkwweett at hotmail.fr Tue Jul 1 11:54:05 2008 From: kkwweett at hotmail.fr (kkwweett) Date: Tue, 01 Jul 2008 17:54:05 +0200 Subject: wrong md5 checksum In-Reply-To: <486a16ef$0$885$ba4acef3@news.orange.fr> References: <486a16ef$0$885$ba4acef3@news.orange.fr> Message-ID: <486a5316$0$864$ba4acef3@news.orange.fr> kkwweett a ?crit : > Hi, > > the download page (http://www.python.org/download/releases/3.0/) for > Python 3000 shows : > > 9119625244b17aa35ed94b655a2b2135 13491200 python-3.0b1.msi > > but I got > > 9119625244a57aa35ed94b655a2b2135 13491200 python-3.0b1.msi > > (44a57 rather than 44b17 ) > > with several md5 checkers ( MdChecker (http://getmd5checker.com/) or a C > prog I've written) Wrong md5 checksum even with Python2.5 : import md5 m=md5.new() message=open("python-3.0b1.msi","rb").read() m.update(message) m.hexdigest() Answer : '9119625244a57aa35ed94b655a2b2135' Does anyone know what can be done to decide wether the file is corrupted or the checksum given is wrong ? From Lie.1296 at gmail.com Wed Jul 30 08:43:02 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 30 Jul 2008 05:43:02 -0700 (PDT) Subject: Insert character at a fixed position of lines References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> <7895c8b2-fa01-483c-8ba9-d90975ea688d@o40g2000prn.googlegroups.com> <8b0f4fe2-d8ab-4230-9032-ccd02878d349@v39g2000pro.googlegroups.com> Message-ID: On Jul 27, 10:02?am, alex23 wrote: > Ugh, and in pointing our your inaccurate code I posted my own: > > > >>> f = open('dummy.txt','w') > > >>> f.write(line = 'this doesn't work') > > > ? File "", line 1 > > ? ? f.write(line = 'this doesn't work') > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?^ > > SyntaxError: invalid syntax > > That should be: > > >>> f.write(line = "this doesn't work") > > Traceback (most recent call last): > ? File "", line 1, in > TypeError: write() takes no keyword arguments > > Sorry about that :) Lessons learned, should test codes even if you thought it seemed trivial. From bignose+hates-spam at benfinney.id.au Tue Jul 1 10:30:45 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 02 Jul 2008 00:30:45 +1000 Subject: Disabling the magic "last expression" _ variable References: <486a108d$0$14358$e4fe514c@news.xs4all.nl> Message-ID: <87d4lxllre.fsf@benfinney.id.au> Peter Otten <__peter__ at web.de> writes: > >>> import sys > >>> def displayhook(result): > ... if result is not None: > ... __builtins__._last = result > ... print result > ... Better is to explicitly import the name '__builtin__' . The name '__builtins__' is an implementation detail not guaranteed to be present in any particular implementation. import __builtin__ import sys def displayhook(result): if result is not None: __builtin__._last = result print result -- \ ?If you continue running Windows, your system may become | `\ unstable.? ?Microsoft, Windows 95 error message | _o__) | Ben Finney From harald.luessen at gmx.de Thu Jul 10 16:04:49 2008 From: harald.luessen at gmx.de (Harald Luessen) Date: Thu, 10 Jul 2008 22:04:49 +0200 Subject: error when porting C code to Python (bitwise manipulation) References: <8feab8ce-1e09-4438-b00a-3b31956c56af@k37g2000hsf.googlegroups.com> <5c521979-aaf0-4b4b-9673-671a978d050a@j22g2000hsf.googlegroups.com> Message-ID: <3hqc74lhdkdqrjb20h34k6ab65g2hc8ucp@4ax.com> On Thu, 10 Jul 2008 Jordan wrote: >On Jul 10, 1:35?pm, MRAB wrote: >> On Jul 10, 4:56?am, Jordan wrote: >> >> >> >> > I am trying to rewrite some C source code for a poker hand evaluator >> > in Python. ?Putting aside all of the comments such as just using the C >> > code, or using SWIG, etc. ?I have been having problems with my Python >> > code not responding the same way as the C version. >> >> > C verison: >> >> > unsigned find_fast(unsigned u) >> > { >> > ? ? unsigned a, b, r; >> > ? ? u += 0xe91aaa35; >> > ? ? u ^= u >> 16; >> > ? ? u += u << 8; >> > ? ? u ^= u >> 4; >> > ? ? b ?= (u >> 8) & 0x1ff; >> > ? ? a ?= (u + (u << 2)) >> 19; >> > ? ? r ?= a ^ hash_adjust[b]; >> > ? ? return r; >> >> > } >> >> > my version (Python, hopefully ;)): >> >> > def find_fast(u): >> > ? ? u += 0xe91aaa35 >> > ? ? u ^= u >> 16 >> > ? ? u += u << 8 >> > ? ? u ^= u >> 4 >> > ? ? b ?= (u >> 8) & 0x1ff >> > ? ? a ?= (u + (u << 2)) >> 19 >> > ? ? r ?= a ^ hash_adjust[b] >> > ? ? return r >> >> > As far as I understand the unsigned instructions in C just increase >> > amount of bytes the int can hold, and Python automatically converts to >> > longs which have infinite size when necessary, so I am not sure why I >> > am getting different results. >> >> > I assume that I am missing something fairly simple here, so help a >> > n00b out if you can :) >> >> > Thanks in advance, >> >> > jnb >> >> You want to restrict the values to 32 bits. The result of + or << may >> exceed 32 bits, so you need to mask off the excess bits afterwards. >> >> def find_fast(u): >> ? ? mask = 0xffffffff >> ? ? u ?= (u + 0xe91aaa35) & mask >> ? ? u ^= u >> 16 >> ? ? u ?= (u + (u << 8)) & mask # can get away with only 1 mask here >> ? ? u ^= u >> 4 >> ? ? b ?= (u >> 8) & 0x1ff >> ? ? a ?= ((u + (u << 2)) & mask) >> 19 # can get away with only 1 mask >> here >> ? ? r ?= a ^ hash_adjust[b] >> ? ? return r >> >> HTH > >Well, I guess there are two problems....the masking and the fact the >in C it seems to for some reason overflow and become a negative >value....still not sure why it does it....So the code with just >masking doesn't work, you still need some sort of weird inversion like >the ~(0xFFFFFFFF - u).....weird > >anyone? In C unsigned can not be negative. Why do you believe the numbers are negative? If your debugger is telling you this thow away the debugger and use printf. If printf is telling you this then use the right format. printf("%u", u); // for unsigned int u printf("%lu", u); // for unsigned long u printf("%x", u); or printf("0x%08x", u); // to see u in hex Harald From fredrik at pythonware.com Wed Jul 16 03:36:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 09:36:13 +0200 Subject: Is there any library that can extract titles from PDFs? In-Reply-To: References: Message-ID: ZelluX wrote: > I want to write a script which will rename PDFs according to their > titles. I want to know if there is any library that can extract > titles(the first line of the PDF) from PDFs. Mathieu Fenniak's PyPdf should be able to do this: http://pybrary.net/pyPdf/ (but note that "the first line of the PDF" may not be the first thing that's rendered on the page, so don't expect such an approach to work for all files) From emrahayanoglu at gmail.com Fri Jul 11 06:58:35 2008 From: emrahayanoglu at gmail.com (hardemr) Date: Fri, 11 Jul 2008 03:58:35 -0700 (PDT) Subject: How to serialize and deserialize the objects into memory? Message-ID: <0a7ead85-2a38-41a8-98b8-59dede61f985@c58g2000hsc.googlegroups.com> Hello Everyone, I want to serialize and deserialize the objects into Memory not into file. How can i do that? Best Regards, From fredrik at pythonware.com Tue Jul 22 05:18:45 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 11:18:45 +0200 Subject: xpathEval fails for large files In-Reply-To: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> References: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> Message-ID: Kanchana wrote: > I tried to extract some data with xpathEval. Path contain more than > 100,000 elements. > > doc = libxml2.parseFile("test.xml") > ctxt = doc.xpathNewContext() > result = ctxt.xpathEval('//src_ref/@editions') > doc.freeDoc() > ctxt.xpathFreeContext() > > this will stuck in following line and will result in high usage of > CPU. > result = ctxt.xpathEval('//src_ref/@editions') > > Any suggestions to resolve this. what happens if you just search for "//src_ref"? what happens if you use libxml's command line tools to do the same search? > Is there any better alternative to handle large documents? the raw libxml2 API is pretty hopeless; there's a much nicer binding called lxml: http://codespeak.net/lxml/ but that won't help if the problem is with libxml2 itself, though (in case you probably should check with an appropriate libxml2 forum). there's also cElementTree (bundled with Python 2.5), but that has only limited xpath support in the current version. both lxml and other implementations of the ET API supports incremental tree parsing: http://effbot.org/zone/element-iterparse.htm which handles huge documents quite nicely, but requires you to write the search logic in Python: for event, elem in ET.iterparse("test.xml"): if elem.tag == "src_ref" and elem.get("editions"): ... process element ... elem.clear() From alexnbryan at gmail.com Mon Jul 7 16:31:11 2008 From: alexnbryan at gmail.com (Alexnb) Date: Mon, 7 Jul 2008 13:31:11 -0700 (PDT) Subject: Trouble with Tkinter text margins Message-ID: <18325944.post@talk.nabble.com> I am writing a program in which there is a textbox and in it the program auto inputs a series of words, and definitions for each word. I want to make it formatted nicely to where the word is indented, and the definitions indented even more. I don't even know how to make the margins work. I have read all the documentation but just need an example so that will help. But my bigger issue is that the way I have written it is like this: for entry in WordList: the definions go in. While that is very dumbed down, that is the gist. Meaning the words to be defined are in "wordlist" and for each entry it prints the entry and the definition. My problem is that I want the lmargin1 to be indented a little, and that will be the margin where the words are, and lmargin2 to be indented even further, and that will be where the definitions go. I want it to look like this: word: definition1 definition2 word2: definition1 and so on. So I need some help trying to figure out how to make this work with the for loop. -- View this message in context: http://www.nabble.com/Trouble-with-Tkinter-text-margins-tp18325944p18325944.html Sent from the Python - python-list mailing list archive at Nabble.com. From trentm at activestate.com Mon Jul 28 12:36:41 2008 From: trentm at activestate.com (Trent Mick) Date: Mon, 28 Jul 2008 09:36:41 -0700 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: <488D53AB.7090300@gmail.com> References: <487E2BCE.30108@hughes.net> <488A2E72.6030802@activestate.com> <488D53AB.7090300@gmail.com> Message-ID: <488DF599.7070904@activestate.com> Manuel Vazquez Acosta wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Just test for maxint value: > > from sys import maxint > if maxint >> 33: > print "more than 32 bits" # probably 64 > else: > print "32 bits" I believe that was already suggested in this thread. That test will just tell you if the Python *build* is 32-bit or 64-bit. If the answer is 32-bit, then that doesn't tell you if this is a 32-bit Python running on a 64-bit OS. Trent -- Trent Mick trentm at activestate.com From duncan.booth at invalid.invalid Sat Jul 19 14:01:21 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Jul 2008 18:01:21 GMT Subject: Change PC to Win or Windows References: <6eej73F6k7g3U3@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Sat, 19 Jul 2008 11:02:51 -0500, Grant Edwards wrote: > >> On 2008-07-19, Dennis Lee Bieber wrote: >> >>> Which term applied to the TRS-80, the Apple II, Altair even... >> >> Not that I remember. I had a homebrew S-100 bus system, worked >> with varioius Commodore machines, a few Apples, and some other >> CP/M systems. I never heard any of them called a 'PC'. My >> recollection is that 'PC' was a term that IBM coined. > > The C64 that still sits on my desk has a label on it saying > ???commodore 64 - personal computer???. > and I cut my programming teeth on a Sharp MZ80K personal computer. http://www.sharpmz.org/mz-80k/images/mz80kade1_1.jpg From mwilson at the-wire.com Sun Jul 6 16:36:13 2008 From: mwilson at the-wire.com (Mel) Date: Sun, 06 Jul 2008 16:36:13 -0400 Subject: how are strings immutable in python? References: Message-ID: ssecorp wrote: >>>> h = "aja baja" >>>> h += 'e' >>>> h > 'aja bajae' >>>> What Peter said, or, to put it another way: Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = b = "aja baja" >>> a += "e" >>> print a aja bajae >>> print b aja baja Mutability/immutability makes a difference in programs when different symbols (or container items) share a value. Mel. From pk.perl at gmail.com Wed Jul 2 07:24:10 2008 From: pk.perl at gmail.com (Prosenjit Kundu) Date: Wed, 02 Jul 2008 16:54:10 +0530 Subject: Scripting SAP GUI (Windows) In-Reply-To: <6d15tpFaec4U1@mid.individual.net> References: <6d15tpFaec4U1@mid.individual.net> Message-ID: <486B655A.8080408@gmail.com> First of all Linux is much better place. why you want to automate GUI with python. You can easily use QTP such GUI testing tools to automate your staff. But that does not mean I am saying the Python is bad in any way. Py and Perl are the two most good things in this world. py-py, Prosenjit Thomas Guettler wrote: > Hi, > > I need to script SAP GUI running on MS-Windows: > > Open SAP GUI window, if it is not already open, and then batch input > some keystrokes. > > The following solutions were found by google: > > - autohotkey: not preferred, since it has an own programming > language. This will slow down development. > - pyHook > - user pywin32 and SetWindowsHookEx > > I develop with python since seven years, but only on linux. > > Any hints? > > From Russ.Paielli at gmail.com Wed Jul 30 03:53:47 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 30 Jul 2008 00:53:47 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> Message-ID: <2da5350e-d74e-4760-b9b8-7cc9869dc607@n33g2000pri.googlegroups.com> On Jul 30, 12:49 am, Heiko Wundram wrote: > Am Mittwoch, 30. Juli 2008 09:18:48 schrieb Russ P.: > > > Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > > __nonzero__ work in Python. It's very basic stuff. You can quit > > patronizing me (and Carl too, I'm sure). > > I'll stop repeating what the current state is (which might sound like I'm > patronizing, but that's not the real intent actually, I'm just trying to get > the discussion straight with what is fact, namely that there already exists > an explicit way which doesn't seem to be recognized by some people here) if > you agree to my point that we're not talking about a problem with Python, but > about a personal stylistic issue with the language design. That's just what I > said in my last mail: I can concede that you, personally, have an issue with > the current state, but for me and seemingly also for a majority of people who > have posted in this thread, that's a non-issue. > > > The point that you seem to be missing, or refuse to acknowledge for > > some reason, is that "if x" can be mistakenly applied to any object > > when the programmer thinks that x is a list -- and the programmer will > > receive no feedback on the error. > > > I have made errors like that, and I could have saved some time had I > > used an "empty" method that only applies to a list or other sequence. > > For me, I've never had this kind of problem, simply because if I test for the > truth value of something, I'm going to do something with it later on, and as > soon as I'm doing something with it, I'll see whether the object supports the > interface I want it to support (and get an error there if the object doesn't > support the basic notions of a sequence type, for example, i.e. __iter__()). > Testing for truth is IMHO not doing something with an object, and as such I'm > more than happy that it's "foolproof". This is one thing that I personally > find attractive about Python's way of duck-typing. > > But, if you personally have been bitten by this, give an example, and I'm sure > that we can start discussing from there. I've already given an example why > the explicit test for length is less polymorphic than the explicit test for > truth of a container elsewhere as a proof for the point I'm trying to make. > > -- > Heiko Wundram Fair enough. I have no dog in this particular fight. I just think it wouldn't hurt to add an "isempty()" or "isnonempty()" method to the list type, and let people use it if they wish, or continue using "if x" if that's what they prefer. From alif016 at gmail.com Fri Jul 18 10:51:49 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Fri, 18 Jul 2008 09:51:49 -0500 Subject: trying to match a string In-Reply-To: <4880AD1A.6040707@gmail.com> References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> Message-ID: <4880AE05.2050005@gmail.com> Andrew Freeman wrote: > oj wrote: >> On Jul 18, 12:10 pm, John Machin wrote: >> >>> On Jul 18, 9:05 pm, oj wrote: >>> >>> >>> >>> >>>> On Jul 18, 11:33 am, arnimavidyar... at gmail.com wrote: >>>> >>>>> Hi, >>>>> Hi, >>>>> I am taking a string as an input from the user and it >>>>> should only >>>>> contain the chars:L , M or R >>>>> I tried the folllowing in kodos but they are still not >>>>> perfect: >>>>> [^A-K,^N-Q,^S-Z,^0-9] >>>>> [L][M][R] >>>>> [LRM]?L?[LRM]? etc but they do not exactly meet what I need. >>>>> For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' >>>>> .like that. >>>>> regards, >>>>> SZ >>>>> The string may or may not have all the three chars. >>>>> >>>> With regular expressions, [^LRM] matches a character that isn't L, R >>>> or M. So: >>>> import re >>>> var = "LRLRLRLNR" >>>> if re.search(r'[^LRM]', var): >>>> print "Invalid" >>>> >>> Fails if var refers to the empty string. >>> >> >> No it doesn't, it succeeds if var is an empty string. An empty string >> doesn't contain characters that are not L, R or M. >> >> The OP doesn't specify whether an empty string is valid or not. My >> interpretation was that an empty string would be valid. >> > Why not just use * instead of + like: > > if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of > string; $ means end of string > print "Invalid" > > This will *only* print invalid when there is a character other than L, > R, or M or a empty string. > Sorry, forget the beginning and ending markers, I just tried it out, it doesn't work. use this instead: if re.search(r'[^LRM]*', var): print "Invalid" From PengYu.UT at gmail.com Wed Jul 16 12:38:26 2008 From: PengYu.UT at gmail.com (Peng Yu) Date: Wed, 16 Jul 2008 09:38:26 -0700 (PDT) Subject: how to match whole word References: Message-ID: <97461ec5-151a-4527-a5fa-c5da07941e46@l42g2000hsc.googlegroups.com> On Jul 15, 10:29 pm, Gary Herron wrote: > Peng Yu wrote: > > Hi, > > > The following code snippet is from /usr/bin/rpl. I would like the it > > to match a word, for example, "abc" in ":abc:". But the current one > > would not match "abc" in ":abc:". I tried to modify it myself. Would > > you please let me know what is the corrected way to do it? > > > Thanks, > > Peng > > > if opts.whole_words: > > regex = re.compile(r"(?:(?<=\s)|^)" + re.escape(old_str) + r"(?=\s| > > $)", > > opts.ignore_case and re.I or 0) > > -- > >http://mail.python.org/mailman/listinfo/python-list > > The regular expression "\w+" will match (what might be your definition > of) a word, and in particular will match abc in :abc:. Regular > expressions have lots of other special \-sequences that might be worth > your while to read about: http://docs.python.org/lib/re-syntax.html > > Gary Herron I didn't read the docs and tried the following code. regex = re.compile(r"\A" + re.escape(old_str) + r"\Z", opts.ignore_case and re.I or 0) But I'm not sure why it is not working. Thanks, Peng From sukkopera at gmail.com Fri Jul 18 04:42:38 2008 From: sukkopera at gmail.com (sukkopera at gmail.com) Date: Fri, 18 Jul 2008 01:42:38 -0700 (PDT) Subject: Unexpected default arguments behaviour (Maybe bug?) References: <4f29ccf6-4daf-4e8e-8735-96cffd8a882e@t54g2000hsg.googlegroups.com> <475185e0-360a-452b-8d22-33ffc243b8a0@z66g2000hsc.googlegroups.com> <98fdc845-cb62-4e7b-891c-dfc75d741a2f@z66g2000hsc.googlegroups.com> Message-ID: <76c1fc77-ab6d-4d9e-a2eb-6d6a74c5bbcc@b2g2000prf.googlegroups.com> FYI, I have opened a bug on the official tracker: http://bugs.python.org/issue3403. From emen999 at gmail.com Wed Jul 23 13:06:03 2008 From: emen999 at gmail.com (code_berzerker) Date: Wed, 23 Jul 2008 10:06:03 -0700 (PDT) Subject: lxml, comparing nodes References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> Message-ID: On Jul 23, 6:29?pm, Stefan Behnel wrote: > Your requirements for a single Element are simple enough to write it in three > to five lines of Python code (depending on your definition of equality). > Checking this equality recursively is another two to three lines. Not complex > enough to be considered a wheel in the first place. Forgive my ignorance as I am new to both Python and lxml ;) From malaclypse2 at gmail.com Tue Jul 8 13:15:59 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 8 Jul 2008 13:15:59 -0400 Subject: problem with Tkinter after installing Python 2.5.2 on UBUNTU In-Reply-To: <83df18ac-e39c-4a1d-95a0-53886d873ea8@s50g2000hsb.googlegroups.com> References: <83df18ac-e39c-4a1d-95a0-53886d873ea8@s50g2000hsb.googlegroups.com> Message-ID: <16651e80807081015k104c686o1a6af8f71ba7a4db@mail.gmail.com> On Tue, Jul 8, 2008 at 12:44 PM, wrote: > I just installed Python 2.5.2 on UBUNTU Linux. It seems to work, > however I don't seem to have access Tkinter. This is the result of > "import Tkinter": I think ubuntu and debian both split Tkinter out of their main python packages. Try installing the python-tk package (via your favorite package manager, or from the command line 'sudo aptitude install python-tk') -- Jerry From tjreedy at udel.edu Fri Jul 4 04:37:04 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 04 Jul 2008 04:37:04 -0400 Subject: Singleton implementation problems In-Reply-To: <87abgy2kcu.fsf@benfinney.id.au> References: <87abgy2kcu.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Peter Otten <__peter__ at web.de> writes: > >> The problem is the structure of your program. The myset module is >> imported twice by Python, once as "myset" and once as "__main__". > > Yes, this is the problem. Each module imports the other. > >> Therefore you get two distinct MySet classes, and consequently two >> distinct MySet.__instance class attributes. > > Are you sure? This goes against my understanding: that 'import foo' > will not re-import a module that's already been imported, but will > instead simply return the existing module. Peter is correct that a module can only be imported once per *name*. In 3.0b1 temp.py ================= print(__name__) import temp print(__name__) from sys import modules as m print(m['__main__'] is m['temp']) produces ================== __main__ temp temp False __main__ False Duplicate imports under multiple names are a known problem, and this is not the only way to create such. But what can an interpreter do when it sees 'import x' other than check that 'x' is not already a key in sys.modules? Iterate through sys.modules (increasingly slow as the dict grows) and do what exactly? The semantics of 'import x' are to get sys.modules['x'] if it exists; otherwise 'initialize' module x according to what that means for the implementation and current state and mode of operation of the system. Modules are not required to have .__file__ attributes since they do not have to come from named files ;-). (And then the module is bound to 'x' in the importing namespace.) Terry Jan Reedy From motoom at xs4all.nl Fri Jul 11 14:15:39 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Fri, 11 Jul 2008 20:15:39 +0200 Subject: Using the Random Module. Message-ID: <2.2.32.20080711181539.01128274@pop.xs4all.nl> You wrote... >Is there a better way to do that besides doing this: > >>>>random.randint(00000000000000000, 99999999999999999) >09657398671238769 Maybe this? random.randint(0, 9e16) -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From bearophileHUGS at lycos.com Thu Jul 31 16:02:44 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 31 Jul 2008 13:02:44 -0700 (PDT) Subject: Hobbyist - Python vs. other languages References: Message-ID: <56c43c99-e525-4fad-9833-92359ce7e3da@y21g2000hsf.googlegroups.com> fprintf: > and yet they all end at the point where a person has enough > knowledge of the syntax, but not really enough to do anything. A programming language is a tool to solve problems, so first of all: do you have problems to solve? You can create some visualizations, some program with GUI, some networked code to download things and process them, etc. Another thing is that you probably have to learn beyond syntax, you can learn about GUIs, network protocols, PyGame, mathematics, some science, etc, they will give you both more things to learn (about the language too) and problems/ideas to solve. Bye, bearophile From mail at timgolden.me.uk Fri Jul 11 09:09:24 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 11 Jul 2008 14:09:24 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) In-Reply-To: References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: <48775B84.4040604@timgolden.me.uk> Bill Davy wrote: > and since then have been busy with work, and my other job, and the garden. Aha! So you're English, are you? Looks like you're in the West Country. Weather map suggests you're not short of rain over there :) > Now I am back looking at this (and using WInUSB to talk to a Maxim 3421E etc > etc but that's another story). So any help today will be much appreciated. > Rgds, Can't remember what the particular obstacles were you were facing, but this runs OK on my setup - Python 2.5.2 / pywin32 211 / Outlook 2003: import os, sys import win32com.client constants = win32com.client.constants def items (contacts): items = contacts.Items item = items.GetFirst () while item: yield item item = items.GetNext () # # Add whatever fields you like from: # http://msdn.microsoft.com/en-us/library/aa210907(office.11).aspx # FIELDS = ['FullName', 'CompanyName', 'Email1Address'] outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") ns = outlook.GetNamespace ("MAPI") for contact in items (ns.GetDefaultFolder (constants.olFolderContacts)): if contact.Class == constants.olContact: print contact for field in FIELDS: print " ", field, "=>", getattr (contact, field, "") Hope that helps. TJG From bignose+hates-spam at benfinney.id.au Wed Jul 16 03:34:10 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jul 2008 17:34:10 +1000 Subject: Python internals References: <008ca729$0$20313$c3e8da3@news.astraweb.com> <87hcaq7pja.fsf@benfinney.id.au> <008d93af$0$20327$c3e8da3@news.astraweb.com> Message-ID: <87wsjm2sgd.fsf@benfinney.id.au> Peter Anderson writes: > If Python doesn't do it like C and the others then what mechanism does > it use You've already been pointed to it, but here it is again: -- \ ?I may disagree with what you say, but I will defend to the | `\ death your right to mis-attribute this quote to Voltaire.? | _o__) ?Avram Grumer, rec.arts.sf.written, May 2000 | Ben Finney From stefan_ml at behnel.de Thu Jul 17 11:04:08 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 17 Jul 2008 17:04:08 +0200 Subject: Good HTML Parser In-Reply-To: References: Message-ID: <487f5f68$0$7543$9b4e6d93@newsspool1.arcor-online.net> Chris wrote: > Can anyone recommend a good HTML/XHTML parser, similar to > HTMLParser.HTMLParser or htmllib.HTMLParser, but able to intelligently > know that certain tags, like
, are implicitly closed? I need to > iterate through the entire DOM, building up a DOM path, but the stdlib > parsers aren't calling handle_endtag() for any implicitly closed tags. > I looked at BeautifulSoup, but it only seems to work by first parsing > the entire document, then allowing you to query the document > afterwards. I need something like a SAX parser. Try lxml.html. It's very memory friendly and extremely fast, so you may end up without any reason to use SAX anymore. http://codespeak.net/lxml/ Stefan From alif016 at gmail.com Sat Jul 26 12:02:14 2008 From: alif016 at gmail.com (Andrew) Date: Sat, 26 Jul 2008 11:02:14 -0500 Subject: Easier way to get the "here" path? In-Reply-To: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> References: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> Message-ID: <488B4A86.4010308@gmail.com> bukzor wrote: > I have to go into these convulsions to get the directory that the > script is in whenever I need to use relative paths. I was wondering if > you guys have a better way: > ... > If you just need the current path (where it is executed) why not use os.getcwd() which returns a string of the absolute path to the module being executed. $ echo "print __file__" > path.py $ ipython In [1]: import path path.pyc In [2]: import os In [3]: os.path.join(os.getcwd(), path.__file__.rstrip("c")) Out[3]: '/home/andrew/path.py' -- Andrew From deets at nospam.web.de Fri Jul 18 06:28:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 18 Jul 2008 12:28:19 +0200 Subject: Protecting instance variables In-Reply-To: References: Message-ID: <6eb9iaF6779oU1@mid.uni-berlin.de> Nikolaus Rath schrieb: > Hello, > > I am really surprised that I am asking this question on the mailing > list, but I really couldn't find it on python.org/doc. > > Why is there no proper way to protect an instance variable from access > in derived classes? > > I can perfectly understand the philosophy behind not protecting them > from access in external code ("protection by convention"), but isn't > it a major design flaw that when designing a derived class I first > have to study the base classes source code? Otherwise I may always > accidentally overwrite an instance variable used by the base class... Here we go again... http://groups.google.com/group/comp.lang.python/browse_thread/thread/188467d724b48b32/ To directly answer your question: that's what the __ (double underscore) name mangling is for. Diez From arne at vajhoej.dk Sun Jul 13 10:12:32 2008 From: arne at vajhoej.dk (=?UTF-8?B?QXJuZSBWYWpow7hq?=) Date: Sun, 13 Jul 2008 10:12:32 -0400 Subject: spam <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> In-Reply-To: References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> Message-ID: <487a0d4d$0$90272$14726298@news.sunsite.dk> Kevin McMurtrie wrote: > In article , > Lew wrote: >> WDC wrote: >>> BTW I reported it, yo should too. >> To whom did you report it, so that we may also report it there? > > Google does not accept spam complaints. Go ahead, try it. That's why > they've been the #1 Usenet spamming tool for years now. What you're > seeing is the spam slowly expanding into the software development > groups. uk.railway is probably a random group added to confuse spam > filters. Some groups, like rec.photo.digital, have been getting > hundreds of Google spams a day for about a year. > > Ask your news service for a Google UDP (Usenet Death Penalty) or > configure your reader to drop everything with "googlegroups.com" in the > Message-ID. Some real users do use GG. Arne From wuwei23 at gmail.com Tue Jul 22 09:00:49 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 22 Jul 2008 06:00:49 -0700 (PDT) Subject: Python embedding question (2). References: Message-ID: <4ed11a51-bc45-4660-bbd5-bfe468f66725@y21g2000hsf.googlegroups.com> On Jul 22, 10:07?pm, Thomas Troeger wrote: > Maybe this is the wrong list to ask, so please forgive the question but > direct me to somewhere better. http://groups.google.com/group/pygame-mirror-on-google-groups There are instructions on that page for joining the mailing list if Google Groups aren't your thing. From deets at nospam.web.de Tue Jul 29 12:20:17 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jul 2008 18:20:17 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <488d86e2$1@news2-rz-ap.ethz.ch> <488dc3eb$1@news2-rz-ap.ethz.ch> <488ddc3c$1@news2-rz-ap.ethz.ch> <488f3670$1@news2-rz-ap.ethz.ch> Message-ID: <6f8uc6FahulcU1@mid.uni-berlin.de> Suresh Pillai wrote: > On Mon, 28 Jul 2008 16:48:28 +0200, Suresh Pillai wrote: > >> Okay, please consider this my one absolutely stupid post for the year. >> I'd like to pretend it never happened but unfortunately the web doesn't >> allow that. Having never used sets, I unfort read something that lead >> to it, but ... > > Okay, got some sleep and what I meant to ask, although equally basic, but > not silly: > > For sets, I presume they are built on top of or like dicts, and there is > nothing crazy in the low level implementation so that I can be guaranteed > that if I don't alter the set, then the order, although arbitrary, will > be maintained in successive iterations over the contents? It is currently that way, but relying on it is certainly to be considered an implementation detail that might disappear without warning. Diez From jsanga at cox.net Wed Jul 23 21:14:09 2008 From: jsanga at cox.net (mzdude) Date: Wed, 23 Jul 2008 18:14:09 -0700 (PDT) Subject: Request Help Debugging Program References: <898dfe7a-4133-4337-8243-f4936b8a8092@8g2000hse.googlegroups.com> Message-ID: <9ba3340e-1048-4958-b988-d2a83559111d@d77g2000hsb.googlegroups.com> On Jul 23, 6:30?pm, Samir wrote: > Hi Everyone, > > > def findSumOfDivisor(n): > ? ? return sum(divisor) ? ? ? ? ? ? ? ?# fine using function sum() > > ? ? ? ? sum = findSumOfDivisor(i) ? ? ?# then find the sum of its divisors oops redefine what sum is. >>> x = [1,2] >>> sum(x) 3 >>> sum = 4 >>> sum(x) Traceback (most recent call last): File "", line 1, in sum(x) TypeError: 'int' object is not callable >>> From fredrik at pythonware.com Sun Jul 20 11:28:23 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jul 2008 17:28:23 +0200 Subject: Passing keywords In-Reply-To: <73285f0c-da54-4c43-b83e-27c3e1b26951@2g2000hsn.googlegroups.com> References: <73285f0c-da54-4c43-b83e-27c3e1b26951@2g2000hsn.googlegroups.com> Message-ID: Kless wrote: > I could use the next but I don't think... > > --------------- > def __check(self, **keywords): > --------------- don't think what? if you keep using the same variables in all submethods you call from a method inside the class, why not make them attributes? otherwise, using the **-form when *calling* the methods might work. you can use the **-form in the functions to ignore arguments that you're not interested in. self.__check(**kwargs) self.__check2(**kwargs) def __check(self, foo1, foo2, **extra): # use foo1 and foo2 here; ignore the rest etc. From gagsl-py2 at yahoo.com.ar Fri Jul 11 05:41:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Jul 2008 06:41:32 -0300 Subject: problem with exec and locals() References: <95f07476-e3c8-45e4-82b3-0e48c9188f8e@79g2000hsk.googlegroups.com> <2fc55416-76c7-48c8-8f49-64c10c5daeda@w7g2000hsa.googlegroups.com> Message-ID: En Fri, 11 Jul 2008 03:51:39 -0300, Uwe Schmitt escribi?: > On 1 Jul., 15:15, Mel wrote: >> rocksportrockerwrote: >> >> > the following code does not work until I ommit the "a=0" statement. >> >> > ? ?def test(): >> > ? ? ? ?exec "a=3" in locals() >> > ? ? ? ?print a >> > ? ? ? ?a=0 >> >> > ? ? test() >> >> > print raises: >> > ? ? ?UnboundLocalError: local variable 'a' referenced before >> > assignment >> >> > Can anybody explain what is going wrong here ? >> >> AFAIK, local variables are implemented rather like __slots__ in >> new-style >> classes. ?This is a very valuable efficiency measure, but it can cause >> this >> kind of trouble. ?Without `a=0`, the bytecode compiler makes no slot >> for a, > > Thanks for your answer. I wonder if this is a bug, or did I miss > something > in the docs ??? Read the warnings in the docs for the locals() builtin function: http://docs.python.org/lib/built-in-funcs.html#l2h-47 and the execfile function: http://docs.python.org/lib/built-in-funcs.html#l2h-26 -- Gabriel Genellina From ppearson at nowhere.invalid Tue Jul 1 12:31:39 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: Tue, 01 Jul 2008 11:31:39 -0500 Subject: wrong md5 checksum References: <486a16ef$0$885$ba4acef3@news.orange.fr> <486a5316$0$864$ba4acef3@news.orange.fr> Message-ID: <2-CdnaVu6892xvfVnZ2dnUVZ_gGdnZ2d@supernews.com> On Tue, 01 Jul 2008 17:54:05 +0200, kkwweett wrote: > kkwweett a ?crit : >> Hi, >> >> the download page (http://www.python.org/download/releases/3.0/) for >> Python 3000 shows : >> >> 9119625244b17aa35ed94b655a2b2135 13491200 python-3.0b1.msi >> >> but I got >> >> 9119625244a57aa35ed94b655a2b2135 13491200 python-3.0b1.msi >> >> (44a57 rather than 44b17 ) >> [snip] > Does anyone know what can be done to decide wether the file is corrupted > or the checksum given is wrong ? For what it's worth, md5sum (GNU coreutils) 5.93 agrees with your result. This interesting almost-agreement could result from A. an error in the software that computed the value for the web page, B. a transcription error in putting the checksum on the web page, C. accidental corruption of the file, or D. a deliberate attempt to substitute a file with a similar MD5 sum. Possibility C is unlikely, but would be the most exciting development in cryptology this year. If C turns out to be the explanation, I hope someone will make sure sci.crypt gets told. Possibility D would be awfully interesting, too. -- To email me, substitute nowhere->spamcop, invalid->net. From motoom at xs4all.nl Tue Jul 15 10:37:31 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Tue, 15 Jul 2008 16:37:31 +0200 Subject: Simplify Code Message-ID: <2.2.32.20080715143731.012ae780@pop.xs4all.nl> Victor wrote... ># Headers are kept in order to determine nesting of chapters ># They are labeled according to font size I'm not sure what you're trying to achieve (I can't divine it from your example code), but I suspect that a dictionary of sizes and header texts is somewhat more manegable than a slew of separate variables h12, h14, h16, h22, h36 etc... Maybe this gives an idea: # this could come from an input file or a parser source=( (18,"Hello"), (36,"Greetings"), # (11,"Boeh") , # uncomment to test this illegal size (36,"You too"), (12,"Bye"), ) # for each font size, remember the last seen header text headers={12:"", 14:"", 18:"", 22:"", 26:"", 36:""} # process the source, collect the header texts for (size,text) in source: if not size in headers: raise KeyError("%d is an illegal size. It must be one of %s" % (size,sorted(headers))) headers[size]=text # do something with the collected header texts for h in sorted(headers): print h,headers[h] Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From kris at FreeBSD.org Wed Jul 9 08:37:28 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Wed, 09 Jul 2008 14:37:28 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <20080709121848.GO26006@nexus.in-nomine.org> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <750f823a-f9de-4f81-9eb3-7c7b39237c90@y38g2000hsy.googlegroups.com> <4874A9C9.7020804@FreeBSD.org> <20080709121848.GO26006@nexus.in-nomine.org> Message-ID: <4874B108.9060205@FreeBSD.org> Jeroen Ruigrok van der Werven wrote: > -On [20080709 14:08], Kris Kennaway (kris at FreeBSD.org) wrote: >> It's compiler/build output. > > Sounds like the FreeBSD ports build cluster. :) Yes indeed! > Kris, have you tried a PGO build of Python with your specific usage? I > cannot guarantee it will significantly speed things up though. I am pretty sure the problem is algorithmic, not bad byte code :) If it was a matter of a few % then that is in the scope of compiler tweaks, but we're talking orders of magnitude. Kris > Also, a while ago I did tests with various GCC compilers and their effect on > Python running time as well as Intel's cc. Intel won on (nearly) all > accounts, meaning it was faster overall. > > From the top of my mind: GCC 4.1.x was faster than GCC 4.2.x. > From pyshib at googlemail.com Wed Jul 30 05:06:08 2008 From: pyshib at googlemail.com (pyshib at googlemail.com) Date: Wed, 30 Jul 2008 02:06:08 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> Message-ID: <8882ed70-2123-40a6-84a7-9fa170f1c384@k30g2000hse.googlegroups.com> If you want to convert the file names which use standard URL encoding (with %20 for space, etc) use: from urllib import unquote new_filename = unquote(filename) I have found this does not convert encoded characters of the form '&#CC;' so you may have to do that manually. I think these are just ascii encodings in hexadecimal. From linuxnow at gmail.com Wed Jul 9 18:21:09 2008 From: linuxnow at gmail.com (linuxnow at gmail.com) Date: Wed, 9 Jul 2008 15:21:09 -0700 (PDT) Subject: how to remove oldest files up to a limit efficiently References: <1eb168ac-fc63-4724-8604-45e995a06b51@s50g2000hsb.googlegroups.com> Message-ID: <01403c64-f282-4ed9-a624-5925089a297d@l64g2000hse.googlegroups.com> On Jul 9, 7:08?pm, Terry Reedy wrote: > Dan Stromberg wrote: > > On Tue, 08 Jul 2008 15:18:23 -0700, linux... at gmail.com wrote: > > >> I need to mantain a filesystem where I'll keep only the most recently > >> used (MRU) files; least recently used ones (LRU) have to be removed to > >> leave space for newer ones. The filesystem in question is a clustered fs > >> (glusterfs) which is very slow on "find" operations. To add complexity > >> there are more than 10^6 files in 2 levels: 16? dirs with equally > >> distributed number of files inside. > > >> Any suggestions of how to do it effectively? > > > os.walk once. > > > Build a list of all files in memory. > > > Sort them by whatever time you prefer - you can get times from os.stat. > > Since you do not need all 10**6 files sorted, you might also try the > heapq module. ?The entries into the heap would be (time, fileid) I'll look into it: probably sorting dirs by atime and adding the files inside to the heapq until I can remove enough of them would work very efficiently. Thanks Pau From andreas.mock at web.de Wed Jul 16 03:55:55 2008 From: andreas.mock at web.de (McA) Date: Wed, 16 Jul 2008 00:55:55 -0700 (PDT) Subject: Logging to different addressees References: <8df30038-86c1-4376-b046-a50f2bcf0a2b@s50g2000hsb.googlegroups.com> <7b829a76-ba2c-4cb7-b216-0c9c01e5cd02@f36g2000hsa.googlegroups.com> <4d3df1d9-339b-43b2-9f25-c792e9bf549c@k13g2000hse.googlegroups.com> Message-ID: <4e30c301-294c-4160-8cb8-c924aed00f71@f63g2000hsf.googlegroups.com> Hi Vinay, thank you for being so patient. On 16 Jul., 01:21, Vinay Sajip wrote: > On Jul 15, 5:17 pm, McA wrote: > > > > If you added the admin sink handler to the root logger, you're done. > > > Isn't that the first thing above? What do you mean? > > I gave you a choice - to add the handler to the admin_logger OR the > root logger. So I am saying here that if you added to the root logger > (and not common_logger, assuming they're different), then there's > nothing more to do... Reading the rest of your mail let me understand what you meant. > > # simple.py > import logging > > admin_logger = logging.getLogger("") # The root logger > addressee_logger = logging.getLogger("addressee") > > admin_sink = logging.FileHandler("admin.log", "w") > addressee_sink = logging.FileHandler("addressee.log", "w") > > admin_logger.addHandler(admin_sink) > addressee_logger.addHandler(addressee_sink) > > admin_logger.setLevel(logging.DEBUG) > > admin_logger.debug("This message appears in admin sink only.") > addressee_logger.debug("This message appears in both admin sink and > addressee sink." > Thank you for that snippet. That means, that the root-logger does inherit EVERY message (if it fits to the level and isn't filtered) and the inheritage chain is build by the chosen logger names, e.g. messages to logging.getLogger('tree.leave') would also show up in logging.getLogger('tree') automatically? If this is true, how can I avoid this "bubbling up" if I would like to? (You see, that's a new question, but I want to take the chance to get the answers from you personally ;-) Hope not to bother. Best regards Andreas Mock From mischneider1 at googlemail.com Wed Jul 23 12:45:22 2008 From: mischneider1 at googlemail.com (Michael Schneider) Date: 23 Jul 2008 16:45:22 GMT Subject: concatenate the elements in each list of a list of lists References: <72c425b7-d9c2-4a61-8b7f-075eae14e703@x41g2000hsb.googlegroups.com> Message-ID: <48876022$0$25953$6e1ede2f@read.cnntp.org> Am Wed, 23 Jul 2008 08:33:57 -0700 wrote antar2: > I already asked a similar question, but encounter problems with > python... > How can I concatenate the elements in each list of a list of lists > > list_of_listsA = > > [['klas*', '*', '*'], > ['mooi*', '*', '*', '*'], > ['arm*', '*', '*(haar)']] > > wanted result: > > list_of_listsA = > > [['klas* * *'] > ['mooi* * * *'] > ['arm* * *(haar)']] > > Thanks a lot ! Hello, maybe this will help: In [5]: list_of_listsA = [['klas*', '*', '*'], ['mooi*', '*', '*', '*'], ['arm*', '* ', '*(haar)']] In [6]: s = "" In [7]: print [[s.join(item)] for item in list_of_listsA] [['klas***'], ['mooi****'], ['arm** *(haar)']] regards Michael From richardlev at gmail.com Sat Jul 26 03:49:20 2008 From: richardlev at gmail.com (Richard Levasseur) Date: Sat, 26 Jul 2008 00:49:20 -0700 (PDT) Subject: SimpleJson is slow .... is there any C Compiled version ? References: Message-ID: <83a8a774-ddec-4137-9dbe-b6db3b4adfa2@p25g2000hsf.googlegroups.com> On Jul 25, 5:52?pm, Matt Nordhoff wrote: > Also, simplejson and python-cjson might not be entirely compatible: > there's one character that one escapes and the other doesn't, or something. > -- They also have different interface. simplejson uses load/loads/dump/ dumps, whereas cjson using encode/decode (its pretty simple to monkeypatch cjson with some lambda's so it has the same interface, though). Yeah, its frustrating that there are so many json encoders for python. Its a bit disappointing simplejson is going into the stdlib; i hope they rewrite it in C? http://blog.hill-street.net/?p=7 Has a good comparison of encoders. From kyosohma at gmail.com Wed Jul 23 16:11:00 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 23 Jul 2008 13:11:00 -0700 (PDT) Subject: Raw Strings (I Think) References: Message-ID: On Jul 24, 10:02?am, "Lanny" wrote: > I've used glob.glob to get a list of files in a directory > and now I want to use os.system to execute one of > those files, the problem is that python automatically > puts a escape charater infront of the back slashes > so the os.system gets X:\\####\\####\\ and is useless, > I think I need to convert my string to a raw string but > I don't know how. > > -- Posted on news://freenews.netfront.net - Complaints to n... at netfront.net -- This works fine for me on Windows XP. I did this: glob.glob(r'c:\test') which gave me something like this: ['c:\\test\\07-24TimeSheet.xls', 'c:\\test\\accts.CSV', 'c:\\test\ \Ataris Aqu\xe1ticos #2.txt', 'c:\\test\\changes.txt', 'c:\\test\ \change_g.txt', 'c:\\test\\config.ini', 'c:\\test\\County.txt', 'c:\ \test\\county1.txt', 'c:\\test\\ctypes-1.0.1.tar.gz', 'c:\\test\ \DAMNATUS_Soundtrack.zip', 'c:\\test\\doodad.1.12.3.doc', 'c:\\test\ \doodad.1.32.3.doc', 'c:\\test\\doodad.22.12.3.doc', 'c:\\test\ \emailMess.xml', 'c:\\test\\Eula.txt', 'c:\\test\\fasta.txt', 'c:\\test \\Funds.txt', 'c:\\test\\Funds2.txt', 'c:\\test\\Gmane.newsrc', 'c:\ \test\\groups.ini', 'c:\\test\\hammy.doc'] Now, if I use os.system like this, it works: os.system('notepad %s' % x[1]) This opens notepad with my *.csv file just fine. Windows XP, Python 2.5.2. Mike From fredrik at pythonware.com Tue Jul 22 05:10:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 11:10:51 +0200 Subject: proliferation of computer languages In-Reply-To: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> Message-ID: xahlee at gmail.com wrote: > There is a proliferation of computer languages today like never > before. "... today ... 1,700 special programming languages used to 'communicate' in over 700 application areas." -- Computer Software Issues, an American Mathematical Association Prospectus, July 1965. (as quoted in P. J. Landin's classic paper "The Next 700 Programming Languages" from March 1966). From happybrowndog at hotmail.com Sun Jul 13 04:19:41 2008 From: happybrowndog at hotmail.com (happybrowndog) Date: Sun, 13 Jul 2008 01:19:41 -0700 Subject: Building a Python app with Mozilla In-Reply-To: <4686CC45.9010405@sweetapp.com> References: <46867432.7060400@codebykevin.com> <4686CC45.9010405@sweetapp.com> Message-ID: Is that why Komodo is so damned slow???? Brian Quinlan wrote: > Kevin Walzer wrote: >> Komodo is not a Python application. It is a Mozilla application that >> supports Python development. Komodo is more akin to Thunderbird and >> Firefox than anything else; it uses the XUL framework for rendering >> widgets, if I'm not mistaken. If you want to build an application like >> Komodo, get a book on developing with the Mozilla framework (XUL, XPCOM, >> and all that) and look at that. Python has little to do with that. > > Most application logic in Komodo is implemented in Python, using the > PyXPCOM bindings. The UI is implemented using XUL and JavaScript. The > editor is Scintilla (C++). > > ../Komodo Edit.app/Contents/MacOS % find . -name "*.py" | xargs wc > ... > ... > 126392 456858 4949602 total > > This doesn't include the python code in the Python libraries themselves. > > Cheers, > Brian > > From workitharder at gmail.com Mon Jul 14 00:16:38 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 13 Jul 2008 21:16:38 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> <792048c1-5e18-4a2c-925d-a1c932d18a91@j22g2000hsf.googlegroups.com> <8923d0c5-29ce-495f-924a-6d9d2457138e@e39g2000hsf.googlegroups.com> Message-ID: On Jul 13, 6:53 pm, Larry Bates wrote: > bearophileH... at lycos.com wrote: > > bukzor: > >> You need to use two dictionaries. Here's a class that someone's > >> written that wraps it up into a single dict-like object for you: > >>http://www.faqts.com/knowledge_base/view.phtml/aid/4376 > > > It contains code like: > > > try: > > del self.data[item] > > except KeyError: > > pass > > > Exceptions are useful in python, but with dictionaries this is > > probably faster (and shorter), even if it may perform two lookups: > > > if item in self.data: > > del self.data[item] > > > Bye, > > bearophile > > The only case where it would be faster would be if most of the keys were NOT in > the dictionary (rather odd use case). Otherwise I believe you will find the > first way quicker as the exceptions are infrequent. > > -Larry /agree From M8R-yfto6h at mailinator.com Fri Jul 25 11:07:25 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Fri, 25 Jul 2008 08:07:25 -0700 Subject: ctypes and reading value under pointer passed as param of a callback References: <6erjpeF88slmU1@mid.individual.net> Message-ID: "waldek" wrote in message news:deaeba30-c160-4e55-9049-43af27e96217 at u12g2000prd.googlegroups.com... > On Jul 24, 5:01 pm, Thomas Heller wrote: >> waldekschrieb: >> >> > Hi, >> >> > I'm using C dll with py module and wanna read value (buffer of bytes) >> > returned in py callback as parameter passed to dll function. >> >> The callback receives a pointer instance. You can dereference the >> pointer >> to read individual bytes in this way: >> print data[0], data[5], data[42] >> or use slicing to read a bunch of bytes: >> print data[0:42] >> >> So, you probably want something like this: >> >> > -------------------------------------------------- >> > def mycallback(data, size): >> > # how to read data buffer here ? >> >> print data[:size] >> >> > return 0 >> >> > cbfunc = CFUNCTYPE(c_int, POINTER(c_uint8), c_int) >> >> > mydll = cdll.somedll >> > mdll.foo(cbfunct) >> > --------------------------------------------------------------- >> >> > Question: How to get bytes from the buffer passed to mycallback ??? >> > Let's assume that the buffer consist of 4 bytes 4 bytes 8 bytes. >> >> > I tried unpack("ii8s", data[0]) and nothing. I tried different ctypes >> > passed to callback and nothing. >> >> Thomas > > Cool, works fine now. > > ... and how to convert a list of bytes to py string or int ?? > > i.e > data[:4] -> py int > data[4:8] -> py int > data[8:] -> py strng > > I tried unpack and unpack_from but the buff should be an string or > buffer not a list of bytes as data is. > > any suggestions? Try: cbfunc = CFUNCTYPE(c_int, c_char_p, c_int) ctypes understands c_char_p as a null-terminated character string and will pass a string to your callback instead of a list of ints. --Mark From deets at nospam.web.de Tue Jul 1 17:24:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 Jul 2008 23:24:02 +0200 Subject: Attribute reference design In-Reply-To: References: Message-ID: <6cvlk4F3s90U1@mid.uni-berlin.de> chamalulu schrieb: > Hello. > I think I'm aware of how attribute access is resolved in python. When > referencing a class instance attribute which is not defined in the > scope of the instance, Python looks for a class attribute with the > same name. (For assignment or deletion this is not the case, > thankfully.) > I've been trying to understand why? What is the reason behind, or > practical purpose of, this design decision? Anyone, please enlighten > me. How else would you resolve methods which are of course defined on the class but invoked through the instance? Diez From mail at timgolden.me.uk Wed Jul 30 09:24:16 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 30 Jul 2008 14:24:16 +0100 Subject: variable expansion with sqlite In-Reply-To: References: <489059DC.5090501@timgolden.me.uk> Message-ID: <48906B80.5040705@timgolden.me.uk> Gerhard H?ring wrote: > My code would probably look very similar. Btw you don't need to use > list() on an iterable to pass to executemany(). pysqlite's executemany() > accepts anything iterable (so generators work fine, too). Thanks for that. My finger-memory told me to do that, possibly because some *other* dbapi interface only accepts lists. Can't quite remember. I'm usually all in favour of non-crystallised iterators. > Also, with SQLite you can just skip data type definitions like > VARCHAR(200). They're ignored anyway. Heh. Once again, finger memory forced me to put *something* in there. I've been developing Enterprise databases for too long :) TJG From dwahler at gmail.com Tue Jul 22 00:24:01 2008 From: dwahler at gmail.com (David Wahler) Date: Mon, 21 Jul 2008 23:24:01 -0500 Subject: tail-rec decorator, well still blows the stack... In-Reply-To: References: Message-ID: On Mon, Jul 21, 2008 at 10:01 PM, ssecorp wrote: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 > > so I try it and when I run: > @Decorators.tail_recursion > def fibtr(n): > def fibt(a, b, n): > if n <= 1: > return b > else: > return fibt(b, a + b, n - 1) > if n == 0: > return 0 > else: > return fibt(0, 1, n); > > it still blows the stack. so what is the point? is it impossible to > get "real" tail-recursion in Python? Python does not perform tail-call elimination, and there are currently no plans to make it do so. See http://mail.python.org/pipermail/python-dev/2004-July/046171.html and the ensuing discussion for an explanation. From Samnsparky at gmail.com Sun Jul 13 11:33:27 2008 From: Samnsparky at gmail.com (Sparky) Date: Sun, 13 Jul 2008 08:33:27 -0700 (PDT) Subject: Newbie Threading Question Message-ID: It seems strange, but I can't find a list of operating systems which support / don't support threading in Python. Can anyone point me in the right direction? Thanks, Sam From circularfunc at gmail.com Sun Jul 27 11:26:14 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 27 Jul 2008 08:26:14 -0700 (PDT) Subject: Rant (was Re: x*x if x>10 References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3g8rF9gfj0U1@mid.uni-berlin.de> <6f3gmaF9moqsU1@mid.uni-berlin.de> Message-ID: <552dcd4f-a821-4ac1-b588-b3727cff1679@m45g2000hsb.googlegroups.com> I might be misunderstanding OP but: a+b+c+d+e is simple way of concatenating 5 lists... as a function that takes any amount of lists and concatenates them: def concat(*args): c = [] for elem in args: c += elem return c don't know if extend is faster or slower or the same as + : def concat(*args): c = [] for elem in args: c.extend(elem) return c I don't know of a built-in. From __peter__ at web.de Fri Jul 4 01:56:16 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Jul 2008 07:56:16 +0200 Subject: Singleton implementation problems References: Message-ID: Urizev wrote: > Hi everyone > > I have developed the singleton implementation. However I have found a > strange behaviour when using from different files. The code is > attached. > > Executing main > New singleton: > <__main__.Singleton instance at 0x2b98be474a70> > New singleton: > > I do not know why, but it creates two instances of the singleton. Does > anybody know why? Do you see it now I snipped the irrelevant output? The problem is the structure of your program. The myset module is imported twice by Python, once as "myset" and once as "__main__". Therefore you get two distinct MySet classes, and consequently two distinct MySet.__instance class attributes. Move the if __name__ == "__main__": ... statements into a separate module, e. g. main.py: import myset import member if __name__ == "__main__": print "Executing main" set1 = myset.MySet() set2 = myset.MySet() mbr1 = member.Member() mbr2 = member.Member() mbr3 = member.Member() Now main.py and member.py share the same instance of the myset module and should work as expected. Peter From bdesth.quelquechose at free.quelquepart.fr Tue Jul 22 11:58:32 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 22 Jul 2008 17:58:32 +0200 Subject: convert list of lists to list In-Reply-To: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> References: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> Message-ID: <4886039a$0$4459$426a34cc@news.free.fr> antar2 a ?crit : > Is there a way to convert list_of_listsA to list_of_listsB, where one > list in listof lists A is one element of listB? > > list_of_listsA: > [['klas*', '*', '*'], > ['mooi*', '*', '*', '*'], > ['koe'], > ['arm*', '*', '*(haar)'], > ['groei*', '*', '*', '*', '*']] > > listB: > ['klas* * *', 'mooi* * * *, 'koe', 'arm* * * (haar)', 'groei* * * * > *'] Your example doesn't match your description. Assuming the example is correct and the description incorrect: listB = [' '.join(sublist) for sublist in list_of_listsA] NB : totally irrelevant, but your naming convention sucks big time IMHO. From stef.mientki at gmail.com Wed Jul 23 04:58:39 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 23 Jul 2008 10:58:39 +0200 Subject: Is this possible .... Message-ID: <4886F2BF.9060709@gmail.com> hello, I'm looking for a way to remove duplicate code. The problem is this: In all my modules I've version information, containing version information, date, author, testconditions etc, something like this: Version_Text = [ [ 0.2, '10-02-2008', 'Stef Mientki', 'Test Conditions:', (1,2), _(0, """ - scaling and offset is set for each individual signal - Time history window for 1 signal with min/max display - set attributes for all signals at once """) ], [ 0.1, '04-11-2007', 'Stef Mientki', 'Test Conditions:', (1,), """ - orginal release """ ] ] Now I've made modules that can generate docs, a library manager, etc, and that even in different languages. But for the simple case I would like to have a simple function, which just displays the version number. So in each module, there is a function: def version () : return ( version_text [0] [0] ) But is there a way to avoid the placing of this function "version" in each module, and still use a simple call like: .version() thanks, Stef Mientki From kyosohma at gmail.com Mon Jul 28 09:09:56 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 28 Jul 2008 06:09:56 -0700 (PDT) Subject: how to upload files to "google code" filesection ? References: Message-ID: <7f6182a3-4504-4239-8239-673a7e4bfefd@s50g2000hsb.googlegroups.com> On Jul 26, 12:43?pm, Stef Mientki wrote: > hello, > > In a program I want to download (updated) files from google code (not > the svn section). > I could find a python script to upload files, > but not for downloading. > > Anyone has a hint or a solution ? > > thanks, > Stef Mientki You should be able to use urllib to do that. The following link has a recipe: http://code.activestate.com/recipes/496685/ If you need to search Google Code, there's an API that appears to be exposed through their gdata module. Mike From nytrokiss at gmail.com Tue Jul 22 13:52:48 2008 From: nytrokiss at gmail.com (James Matthews) Date: Tue, 22 Jul 2008 10:52:48 -0700 Subject: Hello,who can help me! In-Reply-To: <6elngkF7mgmfU1@mid.uni-berlin.de> References: <163330b8-8d0d-44c4-baf7-450bd42f8402@c65g2000hsa.googlegroups.com> <6elngkF7mgmfU1@mid.uni-berlin.de> Message-ID: <8a6b8e350807221052x48c75f3elf4a3cb5f2e755c6e@mail.gmail.com> I would recommended on asking on the pywin32 mailing list. On Tue, Jul 22, 2008 at 2:26 AM, Diez B. Roggisch wrote: > birdprince at gmail.com wrote: > > > I have implemented a C++ COM,which contains two interface in one > > coclass. > > when i use this COM in python: > > dll=win32com.client.Dispatch("XXXXX") > > then i can only call default interface's method,but can't call non > > default interface's method. > > who can tell me how to call non default interface's method. > > thank you very much! > > you can send the answer to my mailbox:birdprince at hotmail.com > > AFAIK win32com only supports IDispatch-based interfaces, not custom > interfaces. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.jewelerslounge.com http://www.goldwatches.com/mens/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Wed Jul 2 12:18:30 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 02 Jul 2008 17:18:30 +0100 Subject: Win32.client, DAO.DBEngine and exceeding the file sharing count lock In-Reply-To: <9ab0cc2d-5a7e-40ca-a4da-084347f147cd@m36g2000hse.googlegroups.com> References: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> <9ab0cc2d-5a7e-40ca-a4da-084347f147cd@m36g2000hse.googlegroups.com> Message-ID: <486BAA56.4070303@timgolden.me.uk> Iain King wrote: > On Jul 2, 3:29 pm, Tim Golden wrote: >> Iain King wrote: >>> Hi. I'm using the win32 module to access an Access database, but I'm >>> running into the File Sharing lock count as inhttp://support.microsoft.com/kb/815281 >>> The solution I'd like to use is the one where you can temporarily >>> override the setting using (if we were in VB): >>> DAO.DBEngine.SetOption dbmaxlocksperfile,15000 >> Really hurried answer: >> >> >> import win32com.client >> >> dao = win32com.client.gencache.EnsureDispatch ("DAO.DBEngine.36") >> dao.SetOption (Option=win32com.client.constants.dbMaxLocksPerFile, Value=15000) >> >> >> TJG > > Thanks. I found this: http://blogs.msdn.com/michkap/archive/2007/07/13/3849288.aspx > which outlines some difference between DAO and ADO, including: > "Capability to set and change Jet options without making registry > changes (works in DAO through DBEngine.GetOption and > DBEngine.SetOption, fails in ADO, which has no such analogue)." > > Now, I'm pretty sure I tried to use DAO before and failed to get it to > work, but maybe you could look at my code and suggest the DAO > equivalent? I'm afraid I don't have the relevant experience myself. I'm sure I could muddle through a few web pages and work it out (but I'm sure you could, too!) Sorry TJG > aTdHvAaNnKcSe, PS - Like the .sig From fetchinson at googlemail.com Wed Jul 9 20:24:36 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 9 Jul 2008 17:24:36 -0700 Subject: FOSS projects exhibiting clean/good OOP? In-Reply-To: <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> Message-ID: >> I'm wondering whether anyone can offer suggestions on FOSS projects/ >> apps which exhibit solid OO principles, clean code, good inline >> documentation, and sound design principles? > > This is somewhat subjective... Some would say that Python's object > model is fundamentally broken and crappy (not MHO, needless to say) > that Python + "solid OO principles" is antinomic !-) > > More seriously: > >> I'm devoting some time to reviewing other people's code to advance my >> skills. Its good to review bad code (of which I have more than enough >> examples) as well as good, but I'm lacking in finding good examples. >> >> Projects of varying sizes would be great. > > I'd recommand at least FormEncode and SQLAlchemy. I'd object calling FormEncode a well-designed project. The classic dilemma has not been dealt with very well: should the software be uber-flexible and hence complex or more rigid but simple. Ideally, this dilemma is solved by being uber-flexible but the user (meaning developers using the code) experience is kept simple by hiding the complexity from developers who don't want to know about them but exposing it to advanced developers who do want to know about them. IMHO FormEncode is not a good example of this. But PIL definitely is! Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From rubbishemail at web.de Tue Jul 1 10:06:12 2008 From: rubbishemail at web.de (rubbishemail at web.de) Date: Tue, 1 Jul 2008 07:06:12 -0700 (PDT) Subject: frame grabber hardware References: Message-ID: <462e0151-04ec-4c40-810b-ceece2815d79@y38g2000hsy.googlegroups.com> > Do you mean something like this? > > Easy Cap Audio-Video Capturing Adapter http://www.youtube.com/watch?v=3AvT8JQ7NzI this would be suitable, if it had a documented driver, some sites said it could only be used with the included software. many bad comments, though: http://forums.ebay.com/db1/thread.jspa?threadID=2000392978&start=40 I found this library http://videocapture.sourceforge.net/ which may be useful to others I will probably go for a TWAIN enabled grabber like http://www.zarbeco.com/usb_videolink.htm and use twainmodule.sourceforge.net/ An alternative would be to use directshow, which seems to be supported by many cameras: http://directpython.sourceforge.net/index.html thanks for your input Daniel From leodp at yahoo.com Tue Jul 1 01:59:58 2008 From: leodp at yahoo.com (leodp) Date: Mon, 30 Jun 2008 22:59:58 -0700 (PDT) Subject: Getting sorting order References: <7cb9ebb7-e722-41e1-bdf2-693954a21b92@j22g2000hsf.googlegroups.com> Message-ID: > >>> x=zip(master,slave1,slave2) > >>> x.sort() > >>> master,slave1,slave2=zip(*x) > --Mark So nice is Python. Leo From bj_666 at gmx.net Fri Jul 18 11:52:26 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Jul 2008 15:52:26 GMT Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> Message-ID: <6ebshqF67cpfU4@mid.uni-berlin.de> On Fri, 18 Jul 2008 07:39:38 -0700, nicolas.pourcelot wrote: > So, I use something like this in 'sheet.objects.__setattr__(self, > name, value)': > if type(value) == Polygon: > for edge in value.edges: > if edge is_in sheet.objects.__dict__.itervalues(): > object.__setattr__(self, self.__new_name(), edge) > > Ok, I suppose it's confused, but it's difficult to sum up. ;-) You are setting attributes with computed names? How do you access them? Always with `gettattr()` or via the `__dict__`? If the answer is yes, why don't you put the objects the into a dictionary instead of the extra redirection of an objects `__dict__`? Oh and the `type()` test smells like you are implementing polymorphism in a way that should be replaced by OOP techniques. Ciao, Marc 'BlackJack' Rintsch From subhabrata.iisc at hotmail.com Fri Jul 18 04:31:59 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Fri, 18 Jul 2008 01:31:59 -0700 (PDT) Subject: Question on Joining of list Message-ID: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> Dear Group, I am trying the following code line: def try2(n): a1=raw_input("PRINT A STRING:") a2=a1.split() a3="God Godess Heaven Sky" for x in a2: a4=a3.find(x) if a4>-1: a5=a3[a4] print a5 elif a4<0: a6=x print "It is not found" print a6 else: print "Error" s=a5+" "+a6 print s Here, if I put a string like: Petrol Helium Heaven Sky In s it is giving me S Helium But I am looking for an output of a5 and a6 concatenating all its values not the last ones. Can you suggest me any help? Am I missing any minor point? Best Regards, Subhabrata. From casevh at gmail.com Tue Jul 8 23:41:41 2008 From: casevh at gmail.com (casevh) Date: Tue, 8 Jul 2008 20:41:41 -0700 (PDT) Subject: numeric emulation and __pos__ References: Message-ID: On Jul 7, 4:12?pm, Ethan Furman wrote: > Greetings, List! > > I'm working on a numeric data type for measured values that will keep > track of and limit results to the number of significant digits > originally defined for the values in question. > > I am doing this primarily because I enjoy playing with numbers, and also > to get some experience with unit testing. > > At this point I have the __init__ portion finished, and am starting on > the various operator functions. > > Questions for the group: > > 1) Any reason to support the less common operators? > ? ? ? ? i.e. <<, >>, &, ^, | Assuming you are working with decimal numbers, the &, ^, | may not be of any use for your application. The shift operators may be useful but there are two possible ways to define their behavior: 1) Multiplication or division by powers of 2. This mimics the common use of those operators as used with binary numbers. 2) Multiplication or division by powers of 10. > > 2) What, exactly, does .__pos__() do? ?An example would help, too. The unary + operator is frequently added for symmetry with -, however it is also used to force an existing number to match a new precision setting. For example, using the decimal module: >>> from decimal import * >>> t=Decimal('1.23456') >>> t Decimal("1.23456") >>> getcontext().prec = 5 >>> +t Decimal("1.2346") > > Thanks for the feedback. > -- > Ethan casevh From dstromberglists at gmail.com Thu Jul 24 20:55:06 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Fri, 25 Jul 2008 00:55:06 GMT Subject: curses problem References: Message-ID: On Thu, 24 Jul 2008 21:28:24 +0200, Dariusz Malec wrote: > forgot to post the code. Server does not allow to post attachments. The > code is here http://www.kos.wsiz.rzeszow.pl/~dmalec/src.zip You might google about SIGWINCH and see where that gets you. Of course, to my great disappointment, python programs that use signals become quite a bit more complex than they should because you have to restart interrupted system calls explicitly. Please, someone fix this! IMO, python functions and methods that could be be interrupted by a signal should restart themselves by default, and have an option to allow them to require themselves to be interrupted. Many Kernel programmers have negative perspectives on application programmers who don't bother this; python seems to have a significant culture of ignoring the issue. This makes me sad. I love python. I want it to do better. From martin at see_sig_for_address.invalid Tue Jul 22 05:21:50 2008 From: martin at see_sig_for_address.invalid (Martin Gregorie) Date: Tue, 22 Jul 2008 10:21:50 +0100 Subject: The Importance of Terminology's Quality References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: On Tue, 24 Jun 2008 18:42:15 -0400, John W Kennedy wrote: > David Combs wrote: >> passing >> *unnamed* functions as args (could Algol 60 also do something like that, >> via something it maybe termed a "thunk") > > No, the "thunks" were necessary at the machine-language level to > /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. > Are you sure about that? The first time I ran across the term "thunking" was when Windows 3 introduced the Win32S shim and hence the need to switch addressing between 16 bit and 32 bit modes across call interfaces. That was called "thunking" by Microsoft and even they would surely admit it was a kludge. I used Algol 60 on an Elliott 503 and the ICL 1900 series back when it was a current language. The term "thunking" did not appear in either compiler manual nor in any Algol 60 language definition I've seen. A60 could pass values by name or value and procedures by name. That was it. Call by name is what is now referred to as reference passing. I should also point out that Algol 60 was initially written as a means for communicating algorithms between people. Compiler implementations came later. In consequence the language did not define links to libraries or i/o methods. Both features were compiler specific - for instance the Elliott introduced 'input' and 'print' reserved words and syntax while the 1900 compilers used function calls. The Elliott approach was more readable. Algol 60 did not have 'functions'. It had procedures which could be declared to return values or not. A procedure that returned a value was equivalent to a function but the term 'function' was not used. Similarly it did not have a mechanism for declaring anonymous procedures. That, like the incorporation of machine code inserts, would have been a compiler-specific extension, so it is a terminological mistake to refer to it without specifying the implementing compiler. -- martin@ | Martin Gregorie gregorie. | org | Zappa fan & glider pilot From paul.hankin at gmail.com Mon Jul 7 17:22:47 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Mon, 7 Jul 2008 14:22:47 -0700 (PDT) Subject: The Yield statement References: <95354739-b4ba-47cb-b2c3-437365cc986b@z72g2000hsb.googlegroups.com> Message-ID: <1c979f9d-ba53-4af2-ad58-bcdcdc98778f@e53g2000hsa.googlegroups.com> On Jul 1, 12:45?am, Mensanator wrote: > Here's an example. > ... > def partition_generator(depth,width): > ? """creates all partions of a given depth,widtth (depth>=width) > ? depth objects in width bins such that each bin has at least 1 object > ? this function is a generator (does comb(depth-1,width-1) partitions) > > ? partition_generator(depth,width) > ? depth: ?total inverse rule 1 count (p of 2**p) > ? width: ?total inverse rule 2 count (q of 3**q) > ? sv: ? ? sequence vector (the partition) > ? returns sequence vector [sv] > ? """ > ? def move_col(c): > ? ? sv[c-1] += 1 > ? ? sv[c] -= 1 > ? def find_c(): > ? ? i = -1 > ? ? while i<0: > ? ? ? if sv[i]>1: > ? ? ? ? return i > ? ? ? i -= 1 > ? def rollover(c): > ? ? move_col(c) > ? ? sv[-1] = sv[c] > ? ? sv[c] = 1 > ? if depth ? ? print 'depth',depth,'must be >= to width',width > ? ? return ? ? ? ? ? ? ? ? ? ? ? # kills generator > ? max_element = depth - width + 1 > ? sv = [1 for i in range(width)] > ? sv[-1] = max_element > ? yield sv[:] ? ? ? ? ? ? ? ? ? ?# first partition > ? while sv[0] ? ? c = find_c() > ? ? if c < -1: > ? ? ? rollover(c) > ? ? ? yield sv[:] ? # must yield copy of sv, not sv > ? ? else: > ? ? ? move_col(c) > ? ? ? yield sv[:] It's just an example I know, but you can write this much more cleanly... def partitions(n, length): """Generate all sequences of positive numbers of the given length that sum to n.""" assert 0 < length <= n if length == 1: yield [n] return for i in xrange(1, n + 2 - length): for p in partitions(n - i, length - 1): yield [i] + p -- Paul Hankin From pavlovevidence at gmail.com Tue Jul 29 16:53:07 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 13:53:07 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> Message-ID: On Jul 29, 4:08 pm, Erik Max Francis wrote: > Carl Banks wrote: > > On Jul 29, 1:30 pm, Carl Banks wrote: > >> On Jul 29, 5:15 am, Heiko Wundram wrote: > > >>> I can't dig up a simple example from code I wrote quickly, but because of the > >>> fact that explicit comparisons always hamper polymorphism > >> I'm not going to take your word for it. Do you have code that > >> demonstrates how "if x" improves polymorphism relative to simple > >> explicit tests? > > > And, in case it wasn't obvious, the way to demonstrate that "if x" > > improves polymorphism relative to simple explicit tests would be > > posting an example where "if x" works but a simple explicit test > > doesn't. So don't accuse me of changing the question on you: it's the > > same question. > > It's pretty elementary, and people thought just describing the issue of > polymorphism and duck-typing was sufficient to explain it. Since it > apparently isn't: > > Let's say you come up with some kind of custom sequence class. You want > to act like any native sequence type (list, tuple, array, string, etc.) > in all reasonable ways (length testing, iteration, indexing, etc.) so > that it can be used in place of these things in code that doesn't > require explicit types. You know, standard polymorphism and duck-typing. > > So you want a test for whether your custom sequence isn't empty. To > create an "simple, explicit test" would be defined an `isntEmpty` method > that you can call, like so: > > if myObject.isntEmpty(): > # then do something > > However, this wouldn't be polymorphic since now someone would have to > call a "simple, explicit test" that doesn't exist on all the other > sequence-like objects. Therefore, you've broken polymorphism. > > The solution is to override the `__nonzero__` method so that you can use > Boolean testing, just like all the other sequence-like objects: > > if myObject: > # then do the same thing > > Now people who use your custom sequence type don't have to write special > code, and code written to deal with sequences using duck typing (which > is typically nearly all Python code) don't have to know anything special > about your custom sequence class. Bzzt. "if len(x)!=0" is a simple explicit that would work for this class and all built-in containers. (Or should--Steven D'Aprano's objections notwithstanding, any reasonable container type should support this invariant. From a language design standpoint, an "empty" builtin could have been created to simplify this even more, but since there isn't one len(x)!=0 will have to do.) Let me reframe the question to see if we can make some headway. The vast majority of true/false tests fit into one of the following four categories: 1. Testing the explicit result of a boolean operation (obviously) 2. Testing whether a numeric type is nonzero. 3. Testing whether a container type is empty. 4. Testing whether you have a (non-numeric, non-container) object of some sort, or None. There's a few other cases, but let's start with these to keep things simple and add other cases as necessary. We already know that cases 2, 3, and 4 can, individually, be converted to a simple explicit test (using x!=0, len(x)!=0, and x is not None, respectively). As long as you know which kind of object you're expecting, you can convert the implicit to an explicit test. Now, you guys keep whining "But what if you don't know what kind of object you're expecting?!!" It's a fair question, and my belief is that, in practice, this almost never happens. Duck typing happens between numeric types often, and between container types often, but almost never between both numeric and container types. Their usages are simply too different. So I present another question to you: Give me an useful, non-trivial, example of some code that where x could be either a numeric or container type. That would be the first step to finding a counterexample. (The next step would be to show that it's useful to use "if x" in such a context.) Once again, I'm invoking the contraint against simply using x in a boolean context, or passing x to a function expecting a boolean doesn't count, since in those cases x can be set to the result of the explicit test. So none of this: def nand(a,b): return not (a and b) Or anything trivial like this: def add(a,b): return a+b Carl Banks From castironpi at gmail.com Sun Jul 27 01:20:21 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 26 Jul 2008 22:20:21 -0700 (PDT) Subject: Insert character at a fixed position of lines References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> <7895c8b2-fa01-483c-8ba9-d90975ea688d@o40g2000prn.googlegroups.com> <8b0f4fe2-d8ab-4230-9032-ccd02878d349@v39g2000pro.googlegroups.com> Message-ID: On Jul 26, 10:02?pm, alex23 wrote: > Ugh, and in pointing our your inaccurate code I posted my own: > > > >>> f = open('dummy.txt','w') > > >>> f.write(line = 'this doesn't work') > > > ? File "", line 1 > > ? ? f.write(line = 'this doesn't work') > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?^ > > SyntaxError: invalid syntax > > That should be: > > >>> f.write(line = "this doesn't work") > > Traceback (most recent call last): > ? File "", line 1, in > TypeError: write() takes no keyword arguments > > Sorry about that :) This is close. import os size= os.path.getsize( 'test line_insertion.txt' ) f= open( 'test line_insertion.txt', 'r+' ) linelen= len( f.readline( ) ) f.seek( 20, os.SEEK_SET ) while f.tell( )< size: f.write( 'y' ) f.seek( linelen, os.SEEK_CUR ) f.flush( ) f.close( ) It assumes lines are a constant length (big assumption), and skips one line's length of characters starting from the 20th character. It repeats until current file position is past the original length of the file. From timr at probo.com Wed Jul 23 00:42:41 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 23 Jul 2008 04:42:41 GMT Subject: Python Written in C? References: Message-ID: Larry Bates wrote: > >I just learned something I did not know. I was under the impression that they >translated directly to machine code without ever actually generating Assembler >text files. Some do, some don't. It's an implementation chioce. gcc generates a text file and pipes it to gas. The __asm__ directive just adds strings to the assembler file. Visual C++ generates machine language. The compiler has to include an assembler for inline assembly. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ojeeves at gmail.com Mon Jul 21 07:08:05 2008 From: ojeeves at gmail.com (oj) Date: Mon, 21 Jul 2008 04:08:05 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> <7574170c-ea58-48a5-83b0-0cd909f07d06@k37g2000hsf.googlegroups.com> Message-ID: On Jul 21, 11:04?am, Fredrik Lundh wrote: > The drawback is that it's a lot easier to mess up the edge cases if you > do that (as this thread has shown). ?The small speedup you get in > typical cases is quickly offset by extra debugging/testing time (or, for > that matter, arguing with c.l.py:ers over more or less contrived ways to > interpret the original post). I disagree, from this thread, most of the erroneous solutions have been attempts to match the entire string. > Guess it's up to personal preferences for how to best help others. > Unless the OP explicitly asks for something else, I prefer to use simple > and straight-forward solutions with reasonable execution behaviour over > clever tricks or odd-ball solutions; it's not a JAPH contest, after all. [^LRM] *is* a simple and straight-forward regex - it isn't attempting to do any clever tricks or anything odd-ball. That said, I still think the sets solution is more elegant then the regex solutions. From grante at visi.com Mon Jul 28 10:18:03 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 28 Jul 2008 09:18:03 -0500 Subject: os.symlink() References: Message-ID: On 2008-07-28, Nikolaus Rath wrote: > Hello, > >>From `pydoc os`: > > symlink(...) > symlink(src, dst) > > Create a symbolic link pointing to src named dst. > > > Is there any reason why this is so deliberately confusing? Why is the > target of the symlink, the think where it points *to*, called the > `src`? It seems to me that the names of the parameters should be > reversed. I never looked at the names of the parameters. I just know that they're in the same order as they are when you do "ln -s" at a shell prompt. It's like you're copying a file (except the new one isn't really a copy, it's a link). -- Grant Edwards grante Yow! PEGGY FLEMMING is at stealing BASKET BALLS to visi.com feed the babies in VERMONT. From grflanagan at gmail.com Fri Jul 18 10:14:49 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Fri, 18 Jul 2008 16:14:49 +0200 Subject: Regular expression help In-Reply-To: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> References: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> Message-ID: nclbndk759 at googlemail.com wrote: > Hello, > > I am new to Python, with a background in scientific computing. I'm > trying to write a script that will take a file with lines like > > c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647 > 3pv=0 > > extract the values of afrac and etot and plot them. I'm really > struggling with getting the values of efrac and etot. So far I have > come up with (small snippet of script just to get the energy, etot): > > def get_data_points(filename): > file = open(filename,'r') > data_points = [] > while 1: > line = file.readline() > if not line: break > energy = get_total_energy(line) > data_points.append(energy) > return data_points > > def get_total_energy(line): > rawstr = r"""(?P.*?)=(?P.*?)\s""" > p = re.compile(rawstr) > return p.match(line,5) > > What is being stored in energy is '<_sre.SRE_Match object at > 0x2a955e4ed0>', not '-11.020107'. Why? 1. Consider using the 'split' method on each line rather than regexes 2. In your code you are compiling the regex for every line in the file, you should lift it out of the 'get_total-energy' function so that the compilation is only done once. 3. A Match object has a 'groups' function which is what you need to retrieve the data 4. Also look at the findall method: data = 'c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647 3pv=0 ' import re rx = re.compile(r'(\w+)=(\S+)') data = dict(rx.findall(data)) print data hth G. From circularfunc at gmail.com Sat Jul 12 15:59:20 2008 From: circularfunc at gmail.com (ssecorp) Date: Sat, 12 Jul 2008 12:59:20 -0700 (PDT) Subject: why is "self" used in OO-Python? References: Message-ID: On Jul 12, 8:44?pm, castironpi wrote: > On Jul 12, 1:01?pm, Duncan Booth wrote: > > > > > ssecorp wrote: > > > 1. Why do I have to pass self into every method in a class? Since I am > > > always doing why cant this be automated or abstracted away? > > > Are the instances where I won't pass self? > > > I imagine there is some tradeoff involved otherwise it would have been > > > done away with. > > > When you define a method in Java there is an implicit 'this' passed to the > > method. Python cannot tell when you define a function whether the function > > is going to be used as a function, an instance method, a class method, a > > static method or something else (or all of the above). Consider this: > > > The dynamic nature of Python means you can lift a method out of a class and > > re-use it in a different context or inject a function into a class as a > > method. There are two ways to handle this sort of code: javascript has an > > implied 'this' for everything whether a function or what passes for a > > method, Python makes it explicit. > > > > 2. self.item instead of getters and setters. I thought one of the main > > > purposes of OO was encapsulation. Doesn't messing with internal object- > > > representations break this? > > > That is correct. Some languages (e.g. Java) don't allow you to encapsulate > > attributes so you have to write getter and setter methods. If you expose an > > attribute in Java then you cannot later insert some code into the lookup or > > override the set without getting all users of your code to change the way > > they access the value. This is bad. > > > Other languages (e.g. Python, C#) allow you to intercept the attribute > > lookup so you can change a plain attribute into a property without > > requiring the users of your class alter their source code. With C# I > > think they would still need to recompile their code so it may be more > > appropriate to avoid using public attributes if you are producing a class > > library for widespread reuse, but with Python there is no difference to the > > user of your class whether they are accessing an attribute or a property. > > > Sadly a lot of Java programmers mistake the limitations of their language > > for rules of OO programming, and worse this has spread from Java into other > > languages where these restrictions no longer need apply. > > > Your Stack class is a bad example: the stack attribute is purely internal > > so you wouldn't want to expose it as part of the public interface. Consider > > instead something like: > > > class AddressBookEntry(object): > > ? ? def __init__(self, name, phone): > > ? ? ? ? self.name = name > > ? ? ? ? self.phone = phone > > > ? ? @property > > ? ? def phone(self): > > ? ? ? ? return self._phone > > > ? ? @property.setter > > ? ? def phone(self, number) > > ? ? ? ? validatephonenumber(number) # may throw an exception > > ? ? ? ? ? self._phone = number > > > If later you want to add some processing to the name attribute it is easy, > > but putting in dummy property getter/setter methods before you need them > > would be pointless. > > Part of the value of accessor methods appears when you're changing > class definitions, or changing classes, after you've already started > to use them-- the same interface with a different implementation. > > In the AddressBookEntry example, if you changed a pickled dictionary > to a shelf, you could reimplement the class and reprocess stored data > files, all without changing the code that uses the class-- especially > if there's a lot of it, or you don't know where it all is. > > Nothing stops you from using accessor methods to offer encapsulation, > and permit back-end changes later. ?But, nothing in Java stops you > from declaring class members public. > > Depending on your development process, data hiding may enforce > distribution of labor a little better, resulting in errors in Java > where Python relies only on discipline. ?If you're checking for value > validation, you can write a custom setter, regardless of language. > > Python doesn't break encapsulation; you do. > > In the Stack example, you have more options than you've mentioned. > Can you inherit from list directly? ?Can you delegate using > reflection? ?Are you studying this example specifically, or the class > model generally? ?If you're choosing a language, be careful that > stricter enforcement doesn't cause harder-to-find bugs. > > Useful link: Section 9.4 in the docs:http://docs.python.org/tut/node11.html ty for all the answers. Im not saying either is better Im just trying to fiugre out the philosophies behind each language and their respective pros and cons. and self is apparently not a reserved word so I could replace it with "blahaba". But basically Python trusts the programmer and relies on conventions rather than enforcements like Java does. From jiri.zahradil at gmail.com Sat Jul 5 09:28:42 2008 From: jiri.zahradil at gmail.com (jiri.zahradil at gmail.com) Date: Sat, 5 Jul 2008 06:28:42 -0700 (PDT) Subject: Python with Ecmascript Message-ID: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> Hello, for my Python application (Windows platform) to be standards compliant, I need to embbed Ecmascript(Javascript) interpreter - I need to execute plugins written in this language. Which engine is suitable for Python, I have found bunch of them. Any recomendations are welcome. To be more specific, I think that plugins will be pretty simple, they will be used to manipulate my class-based datamodel, no special libraries dependencies ... therefore I prefer some rather simple solution ... Jiri From tim.tadh at gmail.com Tue Jul 29 11:18:48 2008 From: tim.tadh at gmail.com (Tim Henderson) Date: Tue, 29 Jul 2008 08:18:48 -0700 (PDT) Subject: Overloaded Functions Message-ID: <3070b5ff-0914-4109-841a-ee622e4105a5@27g2000hsf.googlegroups.com> Hi, So this may have been asked before but i haven't found the answer by googling so far. My situation is this: I want this structure for my code: @overloaded def sign_auth(secret, salt, auth_normalized): return __sign_auth(saltedhash_bin(secret, salt), auth_normalized) @sign_auth.register(str, str) def sign_auth(secret_hash_normalized, auth_normalized): return __sign_auth(qcrypt.denormalize(secret_hash_normalized), auth_normalized) def __sign_auth(secret_hash_bin, auth_normalized): auth = qcrypt.denormalize(auth_normalized) aes = AES.new(secret_hash_bin, AES.MODE_CBC) plaintext = aes.decrypt(auth) ciphertext = qcrypt.normalize(xor_in_pi(plaintext)) if debug: print '\n------sign_auth------' print qcrypt.normalize(secret_hash_bin) print qcrypt.normalize(plaintext) print ciphertext print '-----sign_auth-------\n' return ciphertext I am using the overloading module from: http://svn.python.org/view/sandbox/trunk/overload/overloading.py?rev=43727&view=log However it doesn't actually support this functionality. Does any one know of a decorator that does this? It would be really nice to have a unified interface into the __sign_auth function for the two different use cases. Tim Henderson From pdorange at pas-de-pub-merci.mac.com Wed Jul 2 10:09:07 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Wed, 2 Jul 2008 16:09:07 +0200 Subject: Trouble using pinckle Message-ID: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> Hello, I'm new to python and i'm deelopping a small game with pygame. I got lot of fun with python. Trying to implement a config file to save user score and config. Reading doc and some tutorial about file handling i read about pickle, and yes it's very easy to implement. But i thought i miss something with the roots of python. I implement a Prefs class to handle config data and add it a load and save method. It works but when reading self, it OK inside the load function but outside the pref instance return to it's previus state... I don't really understand. Here's the test code : #!/usr/bin/env python import os, pickle kFileName='test.ini' class Prefs(): def __init__(self): self.test=1 self.zorglub='bonjour' def load(self): if os.path.exists(kFileName): try: print 'test %d (before)' % self.test f=open(kFileName,'r') self=pickle.load(f) f.close() print 'test %d (after)' % self.test except IOError: return 1 return 0 def save(self): f=open(kFileName,'w') pickle.dump(self,f) f.close() return 0 def main(): p=Prefs() p.load() print 'test %d (after load)' % p.test p.test+=1 print 'test %d (before save)' % p.test p.save() print '----------------------' if __name__ == '__main__': main() -- Pierre-Alain Dorange Vid?o, DV et QuickTime Clarus, the DogCow From babacity4 at gmail.com Thu Jul 24 16:52:04 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:52:04 -0700 (PDT) Subject: sextv1 tv com - Amazing porn video collection Message-ID: <301d6d18-833c-45d1-bd13-a2ea5b334fe8@z11g2000prl.googlegroups.com> sextv1 tv com . >>>>>>>>>>Best Collection of Sextv1 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE sextv1 tv com VIDEOS<<<<<<<<<<< . sextv1 tv com From darcy at druid.net Sat Jul 12 09:57:44 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 12 Jul 2008 09:57:44 -0400 Subject: Confused In-Reply-To: <000001c8e417$c2b5bc50$0a01a8c0@HOMEPC> References: <000001c8e417$c2b5bc50$0a01a8c0@HOMEPC> Message-ID: <20080712095744.f69818f8.darcy@druid.net> On Sat, 12 Jul 2008 14:06:37 +0200 "eric.butteriss" wrote: > Please tell me why may mail is being returned. The message says I have been blacklisted...for what reason? I never open mail that I know is not expected and I never send junk or spam. I am trying to send important info to my cousin. Well, the subject is accurate anyway. The problem is that sometimes error messages can be misleading. In this case the problem appears that you have arrived too late and the Internet is full. Please turn off your computer and go outside. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From PengYu.UT at gmail.com Tue Jul 15 23:40:31 2008 From: PengYu.UT at gmail.com (Peng Yu) Date: Tue, 15 Jul 2008 20:40:31 -0700 (PDT) Subject: how to match whole word Message-ID: Hi, The following code snippet is from /usr/bin/rpl. I would like the it to match a word, for example, "abc" in ":abc:". But the current one would not match "abc" in ":abc:". I tried to modify it myself. Would you please let me know what is the corrected way to do it? Thanks, Peng if opts.whole_words: regex = re.compile(r"(?:(?<=\s)|^)" + re.escape(old_str) + r"(?=\s| $)", opts.ignore_case and re.I or 0) From 5lvqbwl02 at sneakemail.com Sat Jul 26 18:22:11 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Sat, 26 Jul 2008 15:22:11 -0700 (PDT) Subject: wx.Timer not working References: <7a2a1c54-6d74-475c-9566-4d94cb5b5962@a3g2000prm.googlegroups.com> Message-ID: On Jul 26, 3:13?pm, Mike Driscoll wrote: > On Jul 26, 2:33?pm, 5lvqbw... at sneakemail.com wrote: > > > > > Windows XP SP3 > > Python 2.5 > > wx.version() = '2.8.1.1 (msw-unicode)' > > ------ > > I have written the following *simplest* implementation of wx.timer I > > can think of. ?No workie. ? I want an exception, a print statement, or > > something. > > > The wxpython demos all work, but for some reason this isn't. ?The > > demos are simple and straghtforward, so I think I understand how it > > should work. ?Clues please? ?I've tried variations of ID's, SetOwners, > > using and redefining Notify(), Bind, Connect, etc. ?In the cases where > > the interpreter doesn't complain about passed argument types, the > > callback function is never called. > > > import wx > > > class MyFrame(wx.Frame): > > ? ? ? ? def __init__(self, parent, id, title): > > ? ? ? ? ? ? ? ? wx.Frame.__init__(self, parent, id, ? ? title, pos=(100, 100)) > > > ? ? ? ? ? ? ? ? timer = wx.Timer(self, -1) > > ? ? ? ? ? ? ? ? self.Bind(wx.EVT_TIMER, self.OnTick, timer) > > ? ? ? ? ? ? ? ? timer.Start(100) > > > ? ? ? ? def OnTick(self, event): > > ? ? ? ? ? ? ? ? print 'Hi. Bye.' > > ? ? ? ? ? ? ? ? 1/0 #<-- should crash as evidence callback is being called > > > class MyApp(wx.App): > > ? ? ? ? def OnInit(self): > > ? ? ? ? ? ? ? ? frame1 = MyFrame(None, wx.ID_ANY, "This is a test") > > ? ? ? ? ? ? ? ? frame1.Show(True) > > ? ? ? ? ? ? ? ? return True > > > app ? ? = MyApp(0) > > app.MainLoop() > > > Thanks for any advice!! > > > Michael > > I'm not seeing anything either. Please post this to the wxPython > user's group for additional help: > > http://www.wxpython.org/maillist.php > > Mike I think I figured it out. By looking at the wxTimer example here: http://wiki.wxpython.org/AnotherTutorial#head-420329f7c159d81cb03a6dd226ddb822ea296c92 My code created a temporary timer object and did not make it a class member. When I changed it to be a class member with self.timer, then it worked. thanks Michael From karthikbalaguru79 at gmail.com Wed Jul 23 02:38:14 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Tue, 22 Jul 2008 23:38:14 -0700 (PDT) Subject: tkinter for my python program !! References: <6em5snF7r22oU3@mid.uni-berlin.de> <63ff0b6f-8c75-4172-b836-8497870544ca@s50g2000hsb.googlegroups.com> <6em86gF7q9djU1@mid.uni-berlin.de> Message-ID: <81554f58-cc9c-4649-afdd-45656ab0bf64@b2g2000prf.googlegroups.com> On Jul 22, 7:11 pm, "Diez B. Roggisch" wrote: > karthikbalaguru wrote: > > On Jul 22, 6:32 pm, "Diez B. Roggisch" wrote: > >> karthikbalaguru wrote: > >> > Hi, > > >> > One of my python program needs tkinter to be installed to run > >> > successfully. > >> > I am using Redhat 9.0 and hence tried installing by copying the > >> > tkinter-2.2.2-36.i386.rpm > >> > alone from the CD 3 to my pc. But, it is not getting installed and is > >> > failing by throwing > >> > the below errors. Should i need to configure / install any specific > >> > files for resolving this issue ? > > >> > [root at localhost karthik]# rpm -ivh tkinter-2.2.2-26.i386.rpm > >> > warning: tkinter-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, > >> > key ID db42a > >> > 60e > >> > error: Failed dependencies: > >> > libtcl8.3.so is needed by tkinter-2.2.2-26.i386 > >> > libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 > >> > libtk8.3.so is needed by tkinter-2.2.2-26.i386 > > >> > Any ideas ? > > >> Yes: you should consider reading error-messages. What does > > >> error: Failed dependencies: > >> libtcl8.3.so is needed by tkinter-2.2.2-26.i386 > >> libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 > >> libtk8.3.so is needed by tkinter-2.2.2-26.i386 > > >> look like for you? > > >> Small hint: if you install something that depends on something else, you > >> need to .... the missing dependency first. Fill in the dots... > > > I find that it needs python-2.2.2-26.i386 and hence i tried installing > > python and i > > land here :( :( > > > [root at localhost karthik]# rpm -ivh python-2.2.2-26.i386.rpm > > warning: python-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key > > ID db42a60e > > error: Failed dependencies: > > libdb-4.0.so is needed by python-2.2.2-26.i386 > > python < 2.4.3-18.fc6 conflicts with python- > > devel-2.4.3-18.fc6.i386 > > [root at localhost karthik]# > > > I find that python 2.4.3-18.fc6 is being used by many of applications. > > But, the program i am trying to run needs python-2.2.2-26. > > So, how to resolve this issue ? > > Are you *sure* it requires python2.2? If yes, why can't fedora install > several python versions together? Ubuntu for sure can. But Python2.2 is > *ancient* - you might need to compile it yourself. > I did the following to resolve the errors, many errors got resolved, but finally the python program is breaking with different error. I got the below errors when i invoked the python program - [root at localhost processor]# Analyzer The python module Tkinter is not installed properly. Tkinter is required for this program. Redhat 9 You need tkinter-2.2.2-26. This can be found on the Redhat install CD 3 $ rpm -i /mnt/cdrom/RedHat/RPMS/tkinter-2.2.2-26.i386.rpm When i tried to install tkinter, i got the below errors - [root at localhost karthik]# rpm -ivh tkinter-2.2.2-26.i386.rpm warning: tkinter-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key ID db42a60e error: Failed dependencies: libtcl8.3.so is needed by tkinter-2.2.2-26.i386 libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 libtk8.3.so is needed by tkinter-2.2.2-26.i386 To resolve the conflicts and bring up the python program. I did the following - I downloaded python-devel-2.2.2-26.i386.rpm & python-2.2.2-26.i386.rpm. [root at localhost karthik]# rpm -e --nodeps python- devel-2.4.3-18.fc6.i386 [root at localhost karthik]# rpm -e --nodeps python-2.4.3-18.fc6 [root at localhost karthik]# rpm -ivh python-devel-2.2.2-26.i386.rpm warning: python-devel-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key ID db42a60e Preparing... ########################################### [100%] 1:python-devel ########################################### [100%] [root at localhost karthik]# rpm -ivh python-2.2.2-26.i386.rpm warning: python-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key ID db42a60e error: Failed dependencies: libdb-4.0.so is needed by python-2.2.2-26.i386 To resolve the above dependency error , i downloaded db4-4.0.14-20.i386.rpm But, i got the below errors while installing - [root at localhost karthik]# rpm -ivh db4-4.0.14-20.i386.rpm warning: db4-4.0.14-20.i386.rpm: Header V3 DSA signature: NOKEY, key ID db42a60e Preparing... ########################################### [100%] package db4-4.3.29-9.fc6 (which is newer than db4-4.0.14-20) is already installed To resolve the above error i did the following - [root at localhost karthik]# rpm -e --nodeps db4-4.3.29-9.fc6.i386 [root at localhost karthik]# rpm -ivh db4-4.0.14-20.i386.rpm warning: db4-4.0.14-20.i386.rpm: Header V3 DSA signature: NOKEY, key ID db42a60e Preparing... ########################################### [100%] 1:db4 ########################################### [100%] Now, i did the python-2.2.2-26.i386 installation. [root at localhost karthik]# rpm -ivh python-2.2.2-26.i386.rpm warning: python-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key ID db42a60e Preparing... ########################################### [100%] 1:python ########################################### [100%] As you would have noticed i linux spitted warning messages during installations of various packages. But, i wonder why i get the warnings and will those warnings affect the working of python based programs ? Further, finally when i invoke the python program by giving the necessary input file, i get the following errors . Does it have any relation with the python version installed ? [root at localhost processor]# Analyzer processorcycle /usr/local/SDK/bin/../core/bin/processorlib.py:8 8: Warning: 'yield' will become a reserved keyword in the future Traceback (most recent call last): File "/usr/local/SDK/bin/Analyzer", line 48, in ? from debuglib import ProcessorInfo File "/usr/local/SDK/bin/../core/bin/processorlib.py", line 88 yield ProcessorObjectInfo(child, self.pt) ^ SyntaxError: invalid syntax Any ideas ? Thx in advans, Karthik Balaguru From kinokunya at gmail.com Mon Jul 14 22:17:49 2008 From: kinokunya at gmail.com (Kinokunya) Date: Mon, 14 Jul 2008 19:17:49 -0700 (PDT) Subject: Need help in writing up a Python Syntax checker References: <57817302-0aca-4cb5-9559-7af6b5bc9d4d@l42g2000hsc.googlegroups.com> Message-ID: <3cd37e84-73f3-4623-a09f-74a743e92b2e@m3g2000hsc.googlegroups.com> On Jul 14, 6:48 pm, Kay Schluehr wrote: > On 14 Jul., 08:22, Kinokunya wrote: > > > Hi guys, > > > My group and I will be working on our final year project, the scope to > > do a program/web-based application similar areas of functionalities > > like the PyLint and PyChecker; a Python syntax checker. We have no > > Python background, equipped only with some knowledge of Java and Dot > > net. > > Python doesn't need a syntax checker. Syntax is checked by the parser > and the parser is exposed to the user by means of the parser module. > What you probably mean are *semantical* checks which are typical for > compilers: e.g. whether names are used with prior assignments of > values that cause runtime exceptions. These issues are in fact covered > by PyLint and PyChecker. > > > We did some research on PyLint and found out that there are 2 common > > modules that PyLint & PyChecker are using, namely logilab-astng and > > logilab-common. I'm not really sure what these 2 modules are for. > > > Quoted from the offical site, > > > The aim of this module (logilab-astng) is to provide a common base > > representation of python source code > > > We're not really sure what they meant by common base representation of > > source codes. > > Just switch to \Scripts\ in your Vista installation > > and type `easy_install pylint`. This shall install PyLint in the > directory > > \lib\site-packages > > Additionally a pylint.bat file is placed in the \Scripts > \ directory. > > Type `pylint --help` and you get more information about the > functionality of PyLint. Thanks for replying Kay Schluehr, The topic of our project was to do a program/software similar to PyLint and PyChecker, and the project scope does not require us to compile the codes. I guess by that it means 'semantic' checks in this case. Does that means we can make use of the parser module as mentioned above for semantic syntax checking? Our situation now is that we are torn between the programming languages to go, Java, Jython or Python, with no definite direction to start off our development. Any pointers would be appreciated. Thank you. From bignose+hates-spam at benfinney.id.au Thu Jul 3 01:16:35 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 03 Jul 2008 15:16:35 +1000 Subject: Times where one would use new style classes vs classic classes References: <6700e4ba-8573-44da-b75a-3b3e5ba1fd9b@i36g2000prf.googlegroups.com> Message-ID: <87skur4kek.fsf@benfinney.id.au> Quek writes: > I'd really like to know in the current context of Python 2.5, > besides in the cases of multi-inheritance, where would I use new > style classes? Is it a norm to use more new style classes even if I > don't have multi-inheritance in the industry, open source projects, > etc today? Yes, it's the norm to use new-style classes. This makes one's classes part of the Python type hierarchy, allowing features such as 'super', 'property', etc. to work correctly. Use new-style classes for any new code you create. Old-style classes are deprecated in Python 2.5 (even earlier than that I believe), and will be removed in Python 3.0 . -- \ ?Good judgement comes from experience. Experience comes from | `\ bad judgement.? ?Frederick P. Brooks | _o__) | Ben Finney From mensanator at aol.com Sun Jul 27 11:34:59 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 27 Jul 2008 08:34:59 -0700 (PDT) Subject: Insert string into string References: <56ff99b9-b4d4-4077-8de1-97a771ac526a@k13g2000hse.googlegroups.com> Message-ID: <0b13960e-85a1-499f-872d-9e2b71987aad@26g2000hsk.googlegroups.com> On Jul 27, 1:41?am, Peter Otten <__pete... at web.de> wrote: > Mensanator wrote: > > I don't know why you're using stdin if you're reading from a file. > > From Francesco's initial post in his previous thread I inferred that he had > a script like > > f = open("xxx.pdb") > for line in f: > ? ? # process line > ? ? print line > > and was calling it > > python script.py >outfile > > My hope was that > > import sys > for line in sys.stdin: > ? ? # process line > ? ? sys.stdout.write(line) > > invoked as > > python script.py outfile > > would be an improvement as it avoids hardcoding the filename, but instead > chaos ensued... > > Francesco: Mensanator's script looks like you can take it "as is". Well, I didn't bother to insert the serial number into the extra line as the extra line wasn't given. Hopefully, it's obvious how to do that. > If you > want to use Python to do other interesting things I highly recommend that > you work your way through a tutorial of your choice. This will make > subsequent trial-and-error much more fun. > > Following Roy's suggestion I also had a brief look at Biopython's PDB parser > which has the advantage that it "understands" the file format. > Unfortunately it is probably too complex for you to use at this point of > your career as a pythonista ;) > > By the way, are you trying to modify the chain ID? Biopython locates that at > position 21, so take this as a reminder that indices in Python start at 0, > i. e. line[21] gives you the 22nd character in the line. > > Peter From thogiti at gmail.com Fri Jul 4 22:07:20 2008 From: thogiti at gmail.com (Nagu) Date: Fri, 4 Jul 2008 19:07:20 -0700 (PDT) Subject: Copyright issues for an application developed using django, python and mySQL References: <1f23a9fd-33a0-4a06-9733-241c8fd450d2@w4g2000prd.googlegroups.com> <87iqvm30cf.fsf@benfinney.id.au> Message-ID: Thank you for your explanations. On Jul 3, 6:27?pm, Ben Finney wrote: > Nagu writes: > > I made a small recommendation engine for our company using python, > > django, and mySQL. My supervisor and the senior management are > > worried about the copyright and licensing issues. > > It's good that they're raising these concerns and making sure. > > > They want to find out the details on how to go about start using it, > > like quoting python/django/ mySQL specifically on the bottom of the > > web page or some other thing. > > You should read the licenses for these products (they're not long), > and retain a lawyer to give an educated opinion addressing the > specific concerns your managers have. > > > How do I go about addressing the copyright and licensing issues? (I > > do not know if licensing is the right word here). > > Start with finding out exactly what those concerns are, gather the > license terms of the works you're using, and consult a copyright > lawyer. > > In parallel, you can read the license texts yourself and understand > them to satisfy yourself about what the terms allow and require. > However, that understanding is good only for making decisions that > affect yourself; for making decisions that affect the company, your > managers should get expert legal opinion. > > > Please advice. > > Hope that helps. > > -- > ?\ ? ? ? ? ?I was gratified to be able to answer promptly and I did. I | > ? `\ ? ? ? said I didn't know.? ?Mark Twain, _Life on the Mississippi_ | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| > Ben Finney From ethan at stoneleaf.us Thu Jul 10 16:37:42 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 10 Jul 2008 12:37:42 -0800 Subject: numeric emulation and the rich comparison operators Message-ID: <48767316.3060607@stoneleaf.us> Greetings, List! Still working on my Measure class, and my next question is... (drum roll please ;) What are the advantages of using __[eq|ne|lt|gt|le|ge]__ vs __cmp__? Thanks in advance! -- Ethan From casey.mcginty at gmail.com Thu Jul 10 16:18:41 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Thu, 10 Jul 2008 10:18:41 -1000 Subject: Unit Testing Techniques Message-ID: I'm familiar with the unittest module in Python, however I'm hoping someone can point me to some examples of more advanced usages of the framework. For example: 1. Using the framework to test a package with nested sub-packages and modules without having to hard code the location/name of each test module. 2. Testing class/methods that depend on file system directory structures, file data, or values read from system hardware. 3. Testing class/methods that require simulating functionality from imported modules. 4. Testing graphical interfaces and associated signal callback functions. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Russ.Paielli at gmail.com Mon Jul 28 02:00:51 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 23:00:51 -0700 (PDT) Subject: Attack a sacred Python Cow References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <20080728033918.GG7373@dragontoe.org> Message-ID: <3178aebe-88fd-483d-8068-b0a73e848a95@v1g2000pra.googlegroups.com> On Jul 27, 10:32 pm, Terry Reedy wrote: > Derek Martin wrote: > > Furthermore, as you described, defining the function within the scope > > of a class binds a name to the function and then makes it a method of > > the class. Once that happens, *the function has become a method*. > > If you mean that a user-defined function object becomes a different > class of object when bound to a class attribute name, that is wrong. > Once a function, always a function. It may be called an 'instance > method' but it is still a function. Any function object can be an > attribute of multiple classes, without inheritance, or of none. > > When a function attribute is accessed via an instance of the class, it > is *wrapped* with a bound method object that basically consists of > references to the function and instance. When the 'bound method' is > called, the instance is inserted in front of the other arguments to be > matched with the first parameter. > > In 2.0, functions accessed through the class were rather uselessly > wrapped as an 'unbound method', but those wrappers have been discarded > in 3.0. > > > To be perfectly honest, the idea that an object method can be defined > > outside the scope of an object (i.e. where the code has no reason to > > have any knowledge of the object) seems kind of gross to me... > > I happen to like the simplicity that "def statements (and lambda > expressions) create function objects." Period. > > ... > > > It does indeed -- it does more than imply. It states outright that > > the function is defined within the namespace of that object, > > True. > > > and as such that it is inherently part of that object. > > False. That does not follow. Python objects generally exist > independently of each other. Think of them as existing in a nameless > dataspace if you want. Collection/container objects collect/contain > references to their members, just as a club roster does, but they only > metaphorically 'contain' their members. Any object can be a member of > any number of collections, just as humans can join any number of clubs > and groups. In mathematical set theory, membership is also non-exclusive. > > > So why should it need > > to be explicitly told about the object of which it is already a part? > > Because it is not a 'part' of a class in the sense you seem to mean. > > What is true is that functions have a read-only reference to the global > namespace of the module in which they are defined. But they do not have > to be a member of that namespace. > > Terry Jan Reedy This whole discussion reminds me of discussions I saw on comp.lang.ada several years ago when I had a passing interest in Ada. My memory on this is a bit fuzzy, but IFIRC Ada 95 did not support standard OO "dot" syntax of the form myObject.myFunction(args) Instead, "myfunction" was just a "regular" function that took "myObject" and "args" as arguments. It was called as myFunction(myObject, args) It was put into the appropriate package or subpackage where it belonged rather than in a class definition. Namespaces were defined by a package hierarchy rather than by classes (which is actually more logical, but that's another topic). Well, so many people demanded the "dot" notation that it was finally implemented in Ada 2005. So now user can use the more familiar dot notation, but my understanding is that it is just "syntactic sugar" for the old notation. So when Python people go out of their way to point out that class "methods" in Python are implemented as regular functions, that seems fairly obvious to me -- but perhaps only because of my passing familiarity with Ada. From timothy.grant at gmail.com Tue Jul 22 19:49:18 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Tue, 22 Jul 2008 16:49:18 -0700 Subject: How do I compare files? In-Reply-To: <1216769247.18962.7.camel@generator> References: <1216769247.18962.7.camel@generator> Message-ID: On Tue, Jul 22, 2008 at 4:27 PM, Clay Hobbs wrote: > I am making a program that (with urllib) that downloads two jpeg files > and, if they are different, displays the new one. I need to find a way > to compare two files in Python. How is this done? > > -- Ratfink > > -- > http://mail.python.org/mailman/listinfo/python-list > I'd start with file sizes. If that's not enough you might look at the md5 library and check the md5 values for the files. -- Stand Fast, tjg. [Timothy Grant] -------------- next part -------------- An HTML attachment was scrubbed... URL: From upton at virginia.edu Mon Jul 21 00:08:13 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 21 Jul 2008 00:08:13 -0400 Subject: Python Written in C? In-Reply-To: References: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> Message-ID: <5504f9ac0807202108k764242f5i5c45b16f57dfe9aa@mail.gmail.com> On Sun, Jul 20, 2008 at 11:51 PM, Mensanator wrote: > On Jul 20, 10:05?pm, Stephen Johnson wrote: >> > Carry bits? Who worries about carry bits when you have >> > unlimited precision arithmetic? You want cool? >> > THIS is cool: >> >> > j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2])) >> > % xyz[1]**(k-1))/xyz[1]**(k-2) >> >> You call that "cool." I call it "unreadable." > > Ok, but not in the sense that something like > Scheme is unreadable as this is nothing but > algebra (albeit complicaed). > Scheme doesn't *have* to be unreadable... any more unreadable than any other language when poorly documented/formatted, anyway. From mail at timgolden.me.uk Fri Jul 4 11:26:29 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 04 Jul 2008 16:26:29 +0100 Subject: Can't get Python for Windows to run In-Reply-To: References: Message-ID: <486E4125.5080201@timgolden.me.uk> Tim Rowe wrote: > I have Python 2.5 working just fine on my system. > > I've tried downloading and installing the MS Windows Python > extensions, but can't get pythonw.exe (that's the windows executable, > right?) to do anything. I double-click it, nothing happens. I run it > from a command prompt, it just returns me to the command prompt. Ummm. That's the Python interpreter but without a window so (unhelpfully, from your point of view) it's doing exactly the right thing. I assume you were trying to run the PythonWin Python interpreter and dev env? On my system, that's: C:\Python25\Lib\site-packages\pythonwin\Pythonwin.exe HTH TJG From emfloyd2 at gmail.com Fri Jul 18 15:21:49 2008 From: emfloyd2 at gmail.com (mark floyd) Date: Fri, 18 Jul 2008 12:21:49 -0700 Subject: Multiple variable control in for loops. Doable in Python? Message-ID: <28efa6970807181221o67c90575w690464f1442dc47d@mail.gmail.com> I'm new to Python and have been doing work converting a few apps from Perl to Python. I can not figure out the comparable Python structures for multi-variable for loop control. Examples: # In Perl for($i = 0, j = 0; $i < I_MAX && $j < J_MAX; $i+=5, $j += 10) { ..... do something } // In Java class test { public static void main(String[] args){ int i = 0; int j = 1; for(i=1, j = 0; i<11 && j < 10; i++, j++){ System.out.println("I is: " + i); System.out.println("J is: " + j); } } } // In C #include int main() { int j = 0; int k = 0; for(j = 0, k = 0; j < 5 && k < 10; j++, k++) { printf("J = %d\n", j); printf("k = %d\n", k); } return 0; } I spent a good part of yesterday looking for a way to handle this style for loop in Python and haven't been able to find an appropriate way to handle this control style. We have this style for loop all over the place and not being able to find a similar structure in Python could be a problem. Any pointers to a Python equivalent structure would be much appreciated - Mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian at excess.org Tue Jul 15 23:59:25 2008 From: ian at excess.org (Ian Ward) Date: Tue, 15 Jul 2008 23:59:25 -0400 Subject: ANN: Urwid 0.9.8.3 - Console UI Library Message-ID: <487D721D.6010304@excess.org> Announcing Urwid 0.9.8.3 ------------------------ Urwid home page: http://excess.org/urwid/ Tarball: http://excess.org/urwid/urwid-0.9.8.3.tar.gz RSS: http://excess.org/feeds/tag/urwid/ About this release: =================== This is a maintenance release that fixes a memory leak and a canvas bug affecting Urwid 0.9.8, 0.9.8.1 and 0.9.8.2. New in this release: ==================== * Fixed a canvas cache memory leak affecting 0.9.8, 0.9.8.1 and 0.9.8.2 (found by John Goodfellow) * Fixed a canvas fill_attr() bug (found by Joern Koerner) About Urwid =========== Urwid is a console UI library for Python. It features fluid interface resizing, UTF-8 support, multiple text layouts, simple attribute markup, powerful scrolling list boxes and flexible interface design. Urwid is released under the GNU LGPL. From bierbaum at vierfalt.com Thu Jul 10 10:21:25 2008 From: bierbaum at vierfalt.com (Simon Bierbaum) Date: Thu, 10 Jul 2008 16:21:25 +0200 Subject: handling unexpected exceptions in pdb Message-ID: Hi all, I'm in an interactive session in pdb, debugging my code using pdb.runcall. Somewhere, an exception is raised and lands uncaught on stdout. Is there any way of picking up this exception and at least read the full message, or even accessing its stack trace to determine where exactly within the one line I just executed it was raised? This is where I'm stuck: > /usr/local/apache2/bin/Model/Database.py(287)disconnect() (Pdb) n FlushError: FlushErr...perly.",) > /usr/local/apache2/bin/Model/Database.py(287)disconnect() (Pdb) import sys (Pdb) sys.last_traceback *** AttributeError: 'module' object has no attribute 'last_traceback' Thanks, Simon From kjhishere at gmail.com Wed Jul 16 09:16:33 2008 From: kjhishere at gmail.com (Ken Hartling) Date: Wed, 16 Jul 2008 06:16:33 -0700 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: Thanks .. but I want to find out if the system is "running on 64bit" even when the interpreter is a 32-bit build executable ("what python was built on"). platform.architecture() and platform() in general seems to only be looking at the build executable and what it was built for on windows (sorry, I don't have a unix box available at the moment). platform.architecture() returns 32bit when on a windows 64bit box. Another recommendation was: import sys hex(sys.maxint) x = sys.maxint n = 1 while x: n += 1 x >>= 1 print n Unfortunately this too appears to be looking at the build executable ... on Windows 64 it returns '32'. Thanks for the suggestions, hopefully we'll come up with a winner. Ken On Tue, Jul 15, 2008 at 1:39 PM, Benjamin Kaplan wrote: > > > On Tue, Jul 15, 2008 at 4:10 PM, wrote: > >> I need to know if I'm running on 32bit or 64bit ... so far I haven't >> come up with how to get this info via python. sys.platform returns >> what python was built on ... but not what the current system is. >> >> I thought platform.uname() or just platform.processor() would have >> done it, but python returns an empty string on windows. Any ideas? >> >> Thanks, Ken >> -- > > > platform.architecture() should have it. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mathieu.prevot at ens.fr Fri Jul 11 06:43:04 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Fri, 11 Jul 2008 12:43:04 +0200 Subject: error with configure (svn 64857) In-Reply-To: <48770603$0$9695$9b622d9e@news.freenet.de> References: <487681e9$0$9745$9b622d9e@news.freenet.de> <48770603$0$9695$9b622d9e@news.freenet.de> Message-ID: <3e473cc60807110343s100b8866k1353b3e8e61049b7@mail.gmail.com> 2008/7/11 "Martin v. L?wis" : >> Thank you Martin. How can I remove -lgcc_s and use the Intel equivalent ? > > I'm not so sure that there is anything wrong in configure. configure > doesn't pass -lgcc_s to icc; instead, icc is making this up on its > own. So I would guess you need to get libgcc_s onto you system in a > way that the linker finds it. Else you need to read the icc > documentation (but I'm fairly sure that icc is *required* to link > with libgcc_s, for interoperability with gcc-compiled binaries). > > I'm somewhat puzzled that the wchar_t test is the one where it > crashes; this test comes fairly late, and configure has run multiple > compiler invocations before that. > > Can you build any binaries at all with your icc installation? Yes of course, I successfuly built and installed nmap, wget, so I thought there was something in the python configure process. If didn't investigate everything but I solved the problem by adding the "-static-libgcc" option: CFLAGS="-w -static-intel -static-libgcc" I think one should commit changes so configure can manage this. I can I want to help for further diagnosis or improvement. Also it seems -Wall will be deprecated, and usually we use -w: -w Control diagnostics, where is one of the following: 0 -- Display errors (same as -w) 1 -- Display warnings and errors (default) 2 -- Display remarks, warnings, and errors Cheers, Mathieu From d3vvnull at gmail.com Mon Jul 28 16:52:16 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Mon, 28 Jul 2008 15:52:16 -0500 Subject: Protecting instance variables In-Reply-To: <877ib6s3xi.fsf@nokile.rath.org> References: <6eb9iaF6779oU1@mid.uni-berlin.de> <877ib6s3xi.fsf@nokile.rath.org> Message-ID: <170543c70807281352w6858e7e0g51082b7b5b56611@mail.gmail.com> What about __setattr__()? On Mon, Jul 28, 2008 at 5:23 AM, Nikolaus Rath wrote: > Hi, > > Sorry for replying so late. Your MUA apparently messes up the > References:, so I saw you reply only now and by coincidence. > > "Diez B. Roggisch" writes: > > Nikolaus Rath schrieb: > >> Hello, > >> > >> I am really surprised that I am asking this question on the mailing > >> list, but I really couldn't find it on python.org/doc. > >> > >> Why is there no proper way to protect an instance variable from access > >> in derived classes? > >> > >> I can perfectly understand the philosophy behind not protecting them > >> from access in external code ("protection by convention"), but isn't > >> it a major design flaw that when designing a derived class I first > >> have to study the base classes source code? Otherwise I may always > >> accidentally overwrite an instance variable used by the base class... > > > > Here we go again... > > > > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/188467d724b48b32/ > > > > To directly answer your question: that's what the __ (double > > underscore) name mangling is for. > > > I understand that it is desirable not to completely hide instance > variables. But it seems silly to me that I should generally prefix > almost all my instance variables with two underscores. > > I am not so much concerned about data hiding, but about not > accidentally overwriting a variable of the class I'm inheriting from. > And, unless I misunderstood something, this is only possible if I'm > prefixing them with __. > > How is this problem solved in practice? I probably don't have a > representative sample, but in the libraries that I have been using so > far, there were a lot of undocumented (in the sense of: not being part > of the public API) instance variables not prefixed with __. I have > therefore started to first grep the source of all base classes > whenever I introduce a new variable in my derived class. Is that > really the way it's supposed to be? What if one of the base classes > introduces a new variable at a later point? > > > Best, > > -Nikolaus > > -- > ?It is not worth an intelligent man's time to be in the majority. > By definition, there are already enough people to do that.? > -J.H. Hardy > > PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From bsagert at gmail.com Wed Jul 2 02:25:53 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Tue, 1 Jul 2008 23:25:53 -0700 (PDT) Subject: n00bie wants advice. Message-ID: <8757c630-0518-4351-a319-124ced0ac92c@w4g2000prd.googlegroups.com> This simple script writes html color codes that can be viewed in a browser. I used short form hex codes (fff or 000, etc) and my list has only six hex numbers otherwise the results get rather large. I invite criticism as to whether my code is "pythonic". Are there other ways to generate the hex combos besides the nested "for" loops? Thanks in advance, Bill list = ['3','6','9','b','d','f'] s = '\n' for a in list: for b in list: for c in list: s += '

'+ a + b + c +'

\n' s += '' f = open('c:/x/test.htm', 'w') f.write(s) f.close() From tjreedy at udel.edu Thu Jul 10 14:29:32 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jul 2008 14:29:32 -0400 Subject: Changing self: if self is a tree how to set to a different self In-Reply-To: References: Message-ID: Bart Kastermans wrote: > I am playing with some trees. In one of the procedures I wrote > for this I am trying to change self to a different tree. A tree > here has four members (val/type/left/right). I found that self = SS > does not work; I have to write self.val = SS.val and the same for > the other members (as shown below). Is there a better way to do this? > > In the below self is part of a parse tree, F is the parse tree of a > function f with argument x. If a node in the parse tree is labelled > f, we should replace it by the parse tree for the function f, F, with > the remainder of the tree substituted for the input variable for the > function f, here x. > > def elimF (self): > if self.val == "f": > SS = F.copy () > SS.subst ('x', self.left) > self.val = SS.val # from here: set self to be SS > self.type = SS.type > self.left = SS.left > self.right = SS.right # completed: set self to be SS If you examine nodes from their parent, I believe you can do the substitution in one step. Something like: for slot,child in ( ('left',self.left), ('right',self.right) ): if child is not None: if child.val == 'f': setattr(self, slot, F.copy().subst('x', child.left)) child.elimF where .subst returns the modified tree. > > if self.left != None: # iterate onward, inf recursion if f > # appears. Would need a check in > # real version > self.left.elimF () > if self.right != None: > self.right.elimF () Terry Jan Reedy From sunp1028 at gmail.com Tue Jul 15 23:06:58 2008 From: sunp1028 at gmail.com (patrol) Date: Tue, 15 Jul 2008 20:06:58 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> Message-ID: <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> > http://timgolden.me.uk/wmi-project/wmi.py It cannot work either. > which is a copy of the svn trunk to see if that > improves the UnicodeDecode error, please? I'll > try to get an install of a non-English edition of > Windows but, as you might imagine, I normally run > the UK version so don't hit these kind of issue > myself. I expect you can test successfully at a non-English edition From sjmachin at lexicon.net Mon Jul 21 16:33:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 21 Jul 2008 13:33:01 -0700 (PDT) Subject: Converting List of String to Integer References: Message-ID: On Jul 22, 6:11 am, Samir wrote: [snip] > For some reason, the logic I posted seems to work ok while I'm using > the Python shell, but when used in my code, the program just hangs. > It never outputs the results. Below is the code in its entirety. Is > there a problem with my indendentation? > > a = n = [] > t = """ > 1 2 > 3 > 4 5 6 > 7 8 9 0 > """ > > d = t.split("\n") > > for x in range(1,len(d)-1): > a.append(d[x].split(" ")) > print a > > for k in a: > n.append([int(v) for v in k]) To see what is happening, insert some print statements, plus something to slow it down e.g. for k in a: print id(a), a print id(n), n n.append([int(v) for v in k]) raw_input('Hit Enter to continue ->') > > print n > From hat at se-162.se.wtb.tue.nl Mon Jul 7 05:49:57 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 07 Jul 2008 11:49:57 +0200 Subject: python beginner References: <1cd8ffae-62a7-4cfb-b3ab-61c7004841c9@8g2000hse.googlegroups.com> Message-ID: On 2008-07-07, cna wrote: > Hi all and one, > how may i learn python. is there any other website except python.org Yes, there are several millions web-sites, all across the world. They cover every possible topic you may and may not imagine. If you mean a website that tries to teach you about Python, the choice is slightly smaller. Did you look at the sites listed under "http://wiki.python.org/moin/BeginnersGuide"? If you find other useful sites, please add them. Sinceely, Albert From Russ.Paielli at gmail.com Wed Jul 30 23:24:38 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 30 Jul 2008 20:24:38 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> Message-ID: On Jul 30, 8:03 pm, Erik Max Francis wrote: > Russ P. wrote: > > The reason I wrote that "it would be nice to be able to write" > > > if x is not empty: > > > is that it reads naturally. It was not an actual proposal, and the > > fact that you took it as such was *your* mistake. > ... > > Now read carefully: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! Let > > me repeat that for you: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! > > Did you get that, idiot? > > So people who can read words but not minds are idiots. Go get 'em, tiger! I don't know if you can read minds, but you seem to have a lot of trouble reading words. Can you read "it would be nice to be able to write ..."? Can you understand what it means? Can you understand that it does *not* mean, "one *should* be able to write ..."? The really significant question here is why I waste my valuable time with pedants like you. From __peter__ at web.de Sat Jul 26 04:08:04 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 26 Jul 2008 10:08:04 +0200 Subject: Insert character at a fixed position of lines References: Message-ID: Francesco Pietra wrote: > How to insert letter "A" on each line (of a very long list of lines) > at position 22, i.e., one space after "LEU", leaving all other > characters at the same position as in the original example: > > > ATOM 1 N LEU 1 146.615 40.494 103.776 1.00 73.04 > 1SG 2 > > In all lines"ATOM" is constant as to both position and string, while > "LEU" is constant as to position only, i.e., "LEU" may be replaced by > three different uppercase letters. Therefore, the most direct > indication would be position 22. You insert a string into another one using slices line = line[:22] + " " + line[22:] (Python's strings are immutable, so you are not really modifying the old string but creating a new one) > Should the script introduce blank lines, no problem. That I know how > to correct with a subsequent script. You are probably printing lines read from a file. These lines already end with a newline, and print introduces a second one. Use the file's write() method instead of print to avoid that, e. g.: import sys for line in sys.stdin: line = line[:22] + " " + line[22:] sys.stdout.write(line) Peter From ldo at geek-central.gen.new_zealand Fri Jul 18 01:36:31 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 18 Jul 2008 17:36:31 +1200 Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> <41d4ffc7-7fd5-4202-92ea-132c7d4f5cd4@s50g2000hsb.googlegroups.com> Message-ID: In message , Gabriel Genellina wrote: > Note that I used %s everywhere (it's just a placeholder, not a format) ... >From /usr/lib64/python2.5/site-packages/MySQLdb/cursors.py, lines 150-151: if args is not None: query = query % db.literal(args) From tjreedy at udel.edu Wed Jul 30 13:22:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jul 2008 13:22:51 -0400 Subject: undo a dictionary In-Reply-To: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> References: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> Message-ID: mmm wrote: > I found code to undo a dictionary association. > > def undict(dd, name_space=globals()): > for key, value in dd.items(): > exec "%s = %s" % (key, repr(value)) in name_space You are not undoing anything. You are updating globals() from another dict. But why repr(value)? Without that, globals().update(dd) would work. In 2.6?/3.0, replace 'dd' with '{a:b for a,b in dd.items()} dd = { 'a':1, 'b': 'B'} globals().update({a:b for a,b in dd.items()}) print(a,b) # 1,B >>>> dx= { 'a':1, 'b': 'B'} >>>> undict(dx) > > I get >>>> print A, B > 1 B > > Here, a=1 and b='B' Don't fake interactive output. You would have to "print a,b". Above gives a NameError. > This works well enough for simple tasks and I understand the role of > globals() as the default names space, but creating local variables is > a problem. Within functions, yes. Just access the values in the dict. > Also having no output arguemtns to undict() seems > counterintuitive. In Python, this is standard for functions that mutate. > Also, the function fails if the key has spaces or > operand characters (-,$,/,%). Exec is tricky. Most people hardly ever use it. > Finally I know I will have cases where > not clearing (del(a,b)) each key-value pair might create problems in a > loop. You cannot mutate a dict while iterating through it. > So I wonder if anyone has more elegant code to do the task that is > basically the opposite of creating a dictionary from a set of > globally assigned variables. See above. > And for that matter a way to create a > dictionary from a set of variables (local or global). You have to be more specific: there are {} displays and dict(args) call and other methods. Read the manual. tjr From tommy.nordgren at comhem.se Sun Jul 13 13:02:54 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Sun, 13 Jul 2008 19:02:54 +0200 Subject: like py2exe, but on a mac In-Reply-To: <18424336.post@talk.nabble.com> References: <18424336.post@talk.nabble.com> Message-ID: <433B228E-A00F-4F7F-B2A6-8D4E6B42302A@comhem.se> On 13 jul 2008, at 00.39, Alexnb wrote: > > Hi All > > I am wondering what I can do to turn a python app (.py) into a mac OSX > applicaiton (.app). Just like py2exe does. But I am also wondering > since in > your applications folder on macs it usually doesn't have an actual > folder > for each app. Rather an icon. so for firefox, you just see the icon. > Unlike > windows where you have a folder with everything, and the actual > program is > in it. where is all the application info stored? just in the .app? > Finally > whether or not there is an app like py2exe for mac, is there a way > to skip > the middle man and turn it straight into a .dmg with the app inside? > -- > View this message in context: http://www.nabble.com/like-py2exe%2C-but-on-a-mac-tp18424336p18424336.html > Sent from the Python - python-list mailing list archive at Nabble.com. > > -- > http://mail.python.org/mailman/listinfo/python-list Platypus can bundle any script into an .app bundle. ----------------------------------- See the amazing new SF reel: Invasion of the man eating cucumbers from outer space. On congratulations for a fantastic parody, the producer replies : "What parody?" Tommy Nordgren tommy.nordgren at comhem.se From mbelzile at softimage.com Tue Jul 15 11:12:48 2008 From: mbelzile at softimage.com (=?iso-8859-1?Q?Marc-Andr=E9_Belzile?=) Date: Tue, 15 Jul 2008 11:12:48 -0400 Subject: installation error on linux 64 Message-ID: <0BCB4AE868D8934A8B3DCE3A58126A8902611161@tewk-mbpf3> Hi, I've compiled python 2.5.2 on red hat r4 and got this installation error: mtl-p1892:[Python-2.5.2] 1>make install ... Compiling /BuildViews/python252build/Python2.5.2.bin/lib/python2.5/test/test_module.py ... Compiling /BuildViews/python252build/Python2.5.2.bin/lib/python2.5/test/test_multibytecodec.py ... Sorry: UnicodeError: ("\\N escapes not supported (can't load unicodedata module)",) Compiling /BuildViews/python252build/Python2.5.2.bin/lib/python2.5/test/test_multibytecodec_support.py ... ... make: *** [libinstall] Error 1 Looks like I'm missing some codec. Any idea how I can fix that ? Thanks for your help. -mab -------------- next part -------------- An HTML attachment was scrubbed... URL: From Phillip.Ross.Taylor at gmail.com Fri Jul 25 09:30:14 2008 From: Phillip.Ross.Taylor at gmail.com (Philluminati) Date: Fri, 25 Jul 2008 06:30:14 -0700 (PDT) Subject: Working with ctypes and char** data type References: <14b44a64-ec58-4ff2-abce-1cc44557e4e4@27g2000hsf.googlegroups.com> <6erju5F88slmU2@mid.individual.net> Message-ID: <6ac2d2ef-a98d-4982-ad1a-7f444a5bf2b9@u12g2000prd.googlegroups.com> On Jul 24, 4:03?pm, Thomas Heller wrote: > Philluminati schrieb: > > > > > I'm a bit of a python newbie and I need to wrap a C library. > > > I can initialise the library using CDLL('mcclient.so') > > > and I can call functions correctly inside the library but I need to > > invoke one function which has this function definition: > > > char ** CAPAPI McSearch(HMCLINK Handle, > > ? ? ? ? ? ? ? ? ? ? ? ? short nSearchType, > > ? ? ? ? ? ? ? ? ? ? ? ? short nNoSelect, > > ? ? ? ? ? ? ? ? ? ? ? ? char **pSelect, > > ? ? ? ? ? ? ? ? ? ? ? ? short nNoWhere, > > ? ? ? ? ? ? ? ? ? ? ? ? char **pWhere, > > ? ? ? ? ? ? ? ? ? ? ? ? char **pData, > > ? ? ? ? ? ? ? ? ? ? ? ? int iTimeout); > > > For **pSelect I want to pass in an array of char points, which in C > > would be declared as > > > char *pData[] = { "ADDR", "POSTCODE" }; > > > Can someone tell me how use pointers + char pointers together in > > python with ctypes please? > > # create an array that holds two pointers to 'char *', and fill it with data: > pData = (c_char_p * 2)() > pData[0] = "ADDR" > pData[1] = "POSTCODE" > > # Another way: > pData = (c_char_p * 2)("ADDR", "POSTCODE") > > Thomas Thank you Thomas for your reply. I also got it working in a slightly less sophisticated manor like this: SelectType = c_char_p * 2 select = SelectType("ADDR", "POSTCODE") ptr = pointer(select) Anyway, thanks for taking the time to reply! Phill From tjreedy at udel.edu Thu Jul 10 02:21:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jul 2008 02:21:08 -0400 Subject: "in"consistency? In-Reply-To: References: <871c6735-f2d2-4cd0-811d-0cd774d55bdd@m45g2000hsb.googlegroups.com> Message-ID: castironpi wrote: > On Jul 8, 2:25 pm, Terry Reedy wrote: > Compare to an imaginary "set of ints" data type: > >>>> a= setofints( [ 0, 1, 2 ] ) > > Then, the semantics of > >>>> b= setofints( [ 0, 1 ] ) >>>> b in a > True > > are consistent and predictable. Correct me if I'm wrong. If you defined a subclass setofints of set with members restricted to being integers, so that [0,1] could not be a member, then you could (sensibly, in my opinion) override __contains__ to make the above work. On the other hand, 'b in a' as a synonym for 'b is a subset of a' is already available for general sets as b.issubset(a). So I would not do the work of subclassing just to abbreviate this call, but only if I wanted the membership guard. Also, the transition from 'int in setofints' to 'setofints in setofints' is not as smooth as the transition from 'length-1 string in string' to 'length-n string in string' because of the need to test and switch on whether the object tested is an int or setofints. Tuples and lists do not have a subsequence find or test method. However, if I wanted one (and I expect I will sometime), I would probably write a general function for sequence in sequence, without bothering with restricting sequence membership. Terry Jan Reedy From grante at visi.com Tue Jul 1 11:22:03 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 01 Jul 2008 10:22:03 -0500 Subject: How to use gnu readline library in program? Message-ID: I'm trying to figure out how to use the gnu readline library so that when my program is prompting the user for input there is line editing and history support. I've read and re-read the documentation for the "readline" module in the standard library and I still can't figure out how to use the module or even if the module is intended to do what I want. The example code all seems to be about on how to modify the behavior of an interactive Python interpreter session so you have things like auto-completion of Python identifiers. What I want to do is replace sys.stdin.readline() with something that will provide the user with line editing and history recall. In other languages, one uses the Gnu readline library to do that, but my reading of the Python library documentation is that's not what the Python readline module is for. Am I wrong? -- Grant Edwards grante Yow! On the road, ZIPPY at is a pinhead without a visi.com purpose, but never without a POINT. From MrJean1 at gmail.com Sat Jul 12 23:08:38 2008 From: MrJean1 at gmail.com (MrJean1) Date: Sat, 12 Jul 2008 20:08:38 -0700 (PDT) Subject: How to create a timer/scheduler in Python? References: <0stg74t0eksmnfsslukn5m7f9s4rbub8kt@4ax.com> Message-ID: <65766272-b3e3-462a-9fe3-456361732c97@m36g2000hse.googlegroups.com> There is a module called sched in the standard Python library /Jean Brouwers John Dann wrote: > I need what I'd call (in .Net) a timer, ie I need to run a function eg > every 2 seconds - it doesn't need to be millisec accurate but it would > be nice if it wasn't eg every 4 seconds or something. > > Rather surprisingly, Core Python (Chun) doesn't seem to index 'timer' > or 'scheduler', which leaves me wondering whether this is an aspect of > Python that isn't perhaps widely used? > > Looking around on the net I can see references to a thread timer, but > I'm not really looking to start any new threads (I just want part of > the GUI to update every 2 secs) and don't want to get into that sort > of complication while still just learning Python. > > Is there really no simple timer/scheduler function available in > Python? From squishywaffle at gmail.com Thu Jul 31 10:03:06 2008 From: squishywaffle at gmail.com (squishywaffle at gmail.com) Date: Thu, 31 Jul 2008 07:03:06 -0700 (PDT) Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> Message-ID: Hello Diez. > May I suggest you move to ctypes for wrapping? It's easier, pure python and > callbacks are already built-in. I'm pretty new to extending Python in C, I don't understand what you're saying. Are there any examples or a brief explanation/URL you could point me to? From victorsubervi at gmail.com Tue Jul 29 09:08:21 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 29 Jul 2008 15:08:21 +0200 Subject: RTF Parsing Message-ID: <4dc0cfea0807290608v3e89a5c6m7dc0ca70fd064a00@mail.gmail.com> Hi; I have this code: def a(): chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', '\\yz'] rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like the Beast? Who can wage war against him?\par' for char in chars: c = '(?<=' + char + ')' test = re.search(c, rtf_markup) try: junk = test.group(0) print char except: pass which gives this result: >>> a() \qc \b0 \i \u \b >>> which makes no sense at all. I expected this: >>> a() \qc \i >>> Why do I get more than that? Also, if I change this line thus: c = '(?<=' + char + ')[0 ]' I get this result: >>> a() \b >>> Why? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From krishnamurthi1921 at gmail.com Tue Jul 29 14:13:00 2008 From: krishnamurthi1921 at gmail.com (lakshmi) Date: Tue, 29 Jul 2008 11:13:00 -0700 (PDT) Subject: it is a computer langugage Message-ID: <533e5bb0-b76d-437d-aebc-a229c9a3357a@x29g2000prd.googlegroups.com> hai just click this a computer langugage www.insurances8blogspot From phillip.oldham at gmail.com Wed Jul 30 08:49:38 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Wed, 30 Jul 2008 05:49:38 -0700 (PDT) Subject: Standard module for parsing emails? Message-ID: Is there a standard library for parsing emails that can cope with the different way email clients quote? From babacity2 at gmail.com Thu Jul 24 16:56:54 2008 From: babacity2 at gmail.com (babacity2 at gmail.com) Date: Thu, 24 Jul 2008 13:56:54 -0700 (PDT) Subject: Peachy18 com - Amazing porn video collection Message-ID: peachy18 com . >>>>>>>>>>Best Collection of Peachy18 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE peachy18 com VIDEOS<<<<<<<<<<< . peachy18 com From jyoung79 at kc.rr.com Tue Jul 29 23:56:55 2008 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Tue, 29 Jul 2008 22:56:55 -0500 Subject: elementtree and rounding questions Message-ID: <8557669.817811217390216084.JavaMail.root@hrndva-web17-z02> Hi, Hoping that some of you won't mind taking a peek at my code and sharing your thoughts. I just started using the elementtree module yesterday to work with xml files. Here's an example of some xml code I might be parsing: ============================================================ ============================================================ What I'd like to do is get the attribute 'name' from the 2nd set 'fontData' tags. So what I'd end up with is ['Courier', 'Helvetica']. Here's the first lines of code I tested: ============================================================ from xml.etree import ElementTree as ET tree = ET.parse('/Users/jay/Desktop/test.txt') root = tree.getroot() fntList = [] f = root.getiterator('fonts') n = f[-1].getiterator('fontData') for i in n: i = i.get('name') if i != None: fntList.append(i) print fntList ============================================================ This gives me ['Courier', 'Helvetica'] which is what I'm wanting. If I'm understanding this correctly, it seems getiterator('fonts') will get both of the 2 sections of tags. Since I only want the second section, which is the last, I look at f[-1] and use the getiterator('fontData') in order to search through all the appropriate tags. Looks like getiterator also finds all nested tags as seen above when it grabbed both font names I was wanting. So I continued to experiment a bit and came up with this next: ============================================================ from xml.etree import ElementTree as ET tree = ET.parse('/Users/jay/Desktop/test.txt') root = tree.getroot() fntList = [] f = root.getiterator('fonts') n = f[-1].find('fontData') for i in n: fntList.append(i.get('name')) print fntList ============================================================ This code just gave me ['Courier']. Now if I change 'find' to 'findall' then I'll get [None, 'Helvetica']. Not exactly sure what exactly that's doing. Seems the 'findall' searches through the tags that aren't nested, but then just using 'find' found the first nested 'name'. Anyway, I'm hoping someone might tell me if the first example of code above is a decent way to parse xml files. I'm still new to Python and am looking for good code structure as well as accurate examples. -- One other question I had was about rounding floats. I was first looking at this syntax to round out to 6 decimal places if needed: >>> f = '508.5' >>> x = '%.6f' % (float(f)/72) >>> x '7.062500' However, in this instance I don't want the last 2 zeroes. So would it be better to do something like this: >> f = '508.5' >>> x = round(float(f)/72, 6) >>> x 7.0625 I've been reading a bit about some rounding bugs, but am really not that knowledgeable about the subject. Does anyone have a preference of how they like to round as well as the result they see? Thanks for looking at my questions. Jay From fredrik at pythonware.com Fri Jul 25 07:21:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 13:21:42 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> <216dcee8-ad3d-4ae1-ac4a-4f4819775c7e@d1g2000hsg.googlegroups.com> Message-ID: Ben Sizer wrote: > In theory, yeah. In practice, if his compiler was somehow not > respecting that, then a quicker fix is to enclose the #include than to > do individual prototypes. Admittedly that might obscure the problem > rather than solve it. Well, I'd say that the should in You should put the extern block around the #include call rather than individual functions, as surely the C calling convention should apply to everything within. makes it look way too much like "this is how you should use python.h" to be appropriate, given the earlier discussions in the thread, and that a casual inspection of the include files reveals that the included files contain exactly that thing. C compilers can be pretty stupid, indeed, but it's usually better to look for a solution that makes some sense (e.g. the wrong project settings) before blaming it all on deeper magic (it will look at this code if I put it here, but not if I put it there. hmm. must be a ley line over there. what if I add a comment?). From tjreedy at udel.edu Mon Jul 7 21:22:04 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 07 Jul 2008 21:22:04 -0400 Subject: "in"consistency? In-Reply-To: References: Message-ID: David C. Ullrich wrote: >>>> 'ab' in 'abc' > True 'a' in 'abc' works according to the standard meaning of o in collection. 'ab' in 'abc' could not work by that standard meaning because strings, as virtual sequences, only contain characters (length 1 strings). Among built-in collections, this limitation is unique to strings (and bytes, in 3.0). So in 2.3, 'in' was given a useful extension of meaning that is also unique to strings (and bytes). >>>> [1,2] in [1,2,3] > False [1,2] can be an member of tuples, lists, dicts and other general collections. [1,2] in collection therefore has that meaning, that it is a single element of collection. Extending the meaning would conflict with this basic meaning. > Is there a reason for the inconsistency? I would > have thought "in" would check for elements of a > sequence, regardless of what sort of sequence it was... It is not an inconsistency but an extension corresponding to the limitation of what an string element can be. Terry J. Reedy From mrkafk at gmail.com Tue Jul 1 05:36:53 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Tue, 01 Jul 2008 11:36:53 +0200 Subject: Embedding Python Message-ID: Hello everyone, I'm trying to embed Python interpreter in C code, but in a specific way: loading compiled bytecode into a memory location and executing it (don't ask why, complicated reasons). PyImport_ExecCodeModule seems like obvious candidate, docs say: "Given a module name (possibly of the form package.module) and a code object read from a Python bytecode file or obtained from the built-in function compile(), load the module." Code: ---cut--- #include #include #include #include #include int load_file(char *fname, unsigned char** result) { int size = 0; FILE *f = fopen(fname, "rb"); if (f == NULL) { *result = NULL; return -1; } fseek(f, 0, SEEK_END); size = ftell(f); *result = (unsigned char *) malloc(size+1); fseek(f, 0, SEEK_SET); size = fread(*result, sizeof(unsigned char), size, f); return size; } int main(int argc, char **argv) { int size; unsigned char *python_code; PyObject *mainobj; size = load_file("multiply.pyc", &python_code); Py_Initialize(); mainobj = PyImport_ExecCodeModule("multiply", (PyObject *) python_code); Py_Finalize(); } ---cut--- Compiling it following way works fine: ${CC} testit.c -g -o testit -I/usr/include/python2.4 -lpython2.4 -lm -lutil -lpthread -ldl -L/usr/lib/python2.4/config However, the damn thing crashes on this call: 33 mainobj = PyImport_ExecCodeModule("multiply", (PyObject *) python_code); (gdb) n Program received signal SIGSEGV, Segmentation fault. 0x0804e7f6 in PyImport_ExecCodeModuleEx () The .pyc file woks just fine in Python interpreter: >>> import multiply >>> multiply.multiply() The result of 12345 x 6789 : 83810205 83810205 >>> What I am doing wrong? Please help. From sysprv at gmail.com Mon Jul 7 08:39:10 2008 From: sysprv at gmail.com (sysprv) Date: Mon, 7 Jul 2008 05:39:10 -0700 (PDT) Subject: Python with Ecmascript References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <8ek074tia4l47tcfo6tqfo9huv2hb68hkt@4ax.com> <7eaf458d-b355-4112-a947-b2b7fe0d1f8d@s50g2000hsb.googlegroups.com> Message-ID: On Jul 7, 9:23?am, "jiri.zahra... at gmail.com" wrote: > On 7 ?ec, 08:21, alex23 wrote: > > > On Jul 7, 12:31 am, "jiri.zahra... at gmail.com" > > > wrote: > > > I personally does not like COM solution. I prefer some simple library > > > but may be it is just a hope. > > > Still looking for better solution ... > > JZ How about using Jython and Rhino [http://www.mozilla.org/rhino/] ? Could be worth your while, if you could live with coding for an older version of the Python spec. /sysprv From stef.mientki at gmail.com Mon Jul 28 14:40:42 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 28 Jul 2008 20:40:42 +0200 Subject: how to upload files to "google code" filesection ? In-Reply-To: <7f6182a3-4504-4239-8239-673a7e4bfefd@s50g2000hsb.googlegroups.com> References: <7f6182a3-4504-4239-8239-673a7e4bfefd@s50g2000hsb.googlegroups.com> Message-ID: <488E12AA.9090304@gmail.com> Mike Driscoll wrote: > On Jul 26, 12:43 pm, Stef Mientki wrote: > >> hello, >> >> In a program I want to download (updated) files from google code (not >> the svn section). >> I could find a python script to upload files, >> but not for downloading. >> >> Anyone has a hint or a solution ? >> >> thanks, >> Stef Mientki >> > > You should be able to use urllib to do that. The following link has a > recipe: > > http://code.activestate.com/recipes/496685/ > thanks Mike, I already found an even simpler solution (that works) filename, header = urllib.urlretrieve (url) > If you need to search Google Code, there's an API that appears to be > exposed through their gdata module. > Do you have perhaps a more specific link ? I saw the Google API's, but its'quit large / complex, so I couldnt find it there. cheers, Stef > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > From bdesth.quelquechose at free.quelquepart.fr Mon Jul 21 05:32:47 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 21 Jul 2008 11:32:47 +0200 Subject: Python Written in C? In-Reply-To: References: Message-ID: <488473b7$0$3470$426a74cc@news.free.fr> giveitawhril2008 at gmail.com a ?crit : (snip clueless nonsense) Surely a troll... No one on earth can be *that* clueless. From frankrentef at yahoo.com Thu Jul 24 10:04:50 2008 From: frankrentef at yahoo.com (frankrentef) Date: Thu, 24 Jul 2008 07:04:50 -0700 (PDT) Subject: Python / PAMIE Message-ID: Can someone help with a PAMIE issue? I'm new to Python / PAMIE and they seem like great tools but to be honest I'm finding that no responses to questions can be found (Experts Exchange, etc.) I'm hoping this will be the place. I tried to duplicate the authors "ie.writeScript" function shown at http://showmedo.com/videos/video?name=pythonMarchettiPamie3&fromSeriesID=25 I get "Attribute not found." I found one reference to where the command was written as "ie.scriptWrite" but that does not work either. I've emailed the author, Experts Exchange and other sites with ZERO responses. Can someone PLEASE assist? THNX From bignose+hates-spam at benfinney.id.au Wed Jul 16 08:16:41 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jul 2008 22:16:41 +1000 Subject: How can i use a variable without define it ? References: <87k5fm2p1x.fsf@benfinney.id.au> <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> <87fxqa2mu0.fsf@benfinney.id.au> <5dd91053-d239-4ff1-b693-d6afedf6bf24@x35g2000hsb.googlegroups.com> Message-ID: <87bq0y2fdi.fsf@benfinney.id.au> zhw writes: > On 7?16?, ??5?35?, Ben Finney > wrote: > > What problem are you trying to solve? > > I an sorry, I can't tell you. Perhaps I'm not being clear: What *programming* problem are you trying to solve? I ask because it seems you are focussed to much on some specific method, when it is very likely that your problem is better solved using different methods. > If you can't give a solution, just ignore it! I *did* give a solution. If that doesn't work for you, please tell us more about the problem so we can provide better solutions. -- \ ?Say what you will about the Ten Commandments, you must always | `\ come back to the pleasant fact that there are only ten of | _o__) them.? ?Henry L. Mencken | Ben Finney From asma61 at dsl.pipex.com Sun Jul 27 13:21:43 2008 From: asma61 at dsl.pipex.com (DaveM) Date: Sun, 27 Jul 2008 18:21:43 +0100 Subject: Rant (was Re: x*x if x>10 References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> Message-ID: On Sun, 27 Jul 2008 16:41:19 +0200, "Diez B. Roggisch" wrote: >You obviously aren't aware of the pitfalls regarding the mis-use of or >and and for this usage. Well, yes, I am (and the way around the problem), but as its never caught me out (so far), I hadn't considered it. >Can you tell us what you mean by "several names of one object"? You mean >this? > >a = range(10) >b = a > >id(a) == id(b) > > >? Passing references instead of values is an extremely important concept >of many languages, without it you would end up copying most of the time. OK. I've obviously been thinking about things the wrong way. In Forth you pass the memory address around, and presumably that's essentially what's happening when you pass a reference. The problem is, I get caught frequently in this situation: a = [1,2,3] def foo(x): do_something_with_x return x ... Then when I call foo(a), a gets changed. It just isn't the effect I expect from changing a local. DaveM From heikki at osafoundation.org Wed Jul 23 14:42:38 2008 From: heikki at osafoundation.org (Heikki Toivonen) Date: Wed, 23 Jul 2008 11:42:38 -0700 Subject: Undocumented Python 2.6 change: Py_None vs NULL when C implementation raises exception Message-ID: I was debugging M2Crypto function written in C which changed behavior between Python 2.6 and earlier Python versions. In an error condition the function was supposed to raise exception type A, but with 2.6 it raised type B, and further, there was no string value for the exception. I tracked this down to the C code incorrectly returning Py_None when it should have returned NULL. Changing the C code to return NULL made it behave correctly in 2.6. I don't know how common a mistake it is to return Py_None when NULL should have been returned, but it might be worth a note in the list of changes for 2.6 that this behavior changed, don't you think? -- Heikki Toivonen From fredrik at pythonware.com Wed Jul 16 09:20:23 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 15:20:23 +0200 Subject: bad recursion, still works In-Reply-To: <20cba7ab-72d2-4c7b-8f3f-48f39eaf9625@m3g2000hsc.googlegroups.com> References: <20cba7ab-72d2-4c7b-8f3f-48f39eaf9625@m3g2000hsc.googlegroups.com> Message-ID: Jeff wrote: > Is this avoidable by using a call to list() in the definition instead? No. Default values are *always* evaluated when, and only when, the "def" statement is executed; see: http://docs.python.org/ref/function.html Also note that "def" is an executable statement in Python, and that default arguments are evaluated in the "def" statement's environment. If you execute "def" multiple times, it'll create a new function object (with freshly calculated default values) each time. ::: The workaround is, as others have mentioned, to use a placeholder value instead of modifying the default value. None is a common value: def myfunc(value=None): if value is None: value = default() # go on an modify value If you need to handle arbitrary objects (including None), you can use a sentinel object: sentinel = object() def myfunc(value=sentinel): if value is sentinel: value = default() (in older code, written before "object" was introduced, you sometimes see things like "sentinel = ['placeholder']" used to create a non-false object with a unique identity; [] creates a new list every time it is evaluated.) ::: Finally, it should be noted that more advanced Python code often uses this mechanism to its advantage; for example, if you create a bunch of UI buttons in a loop, you might try something like: for i in range(10): def callback(): print "clicked button", i UI.Button("button %s" % i, callback) only to find that all callbacks print the same value (most likely 9, in this case). The reason for this is that Python's nested scopes bind to variables, not object values, so all callback instances will see the current (=last) value of the "i" variable. To fix this, use explicit binding: for i in range(10): def callback(i=i): print "clicked button", i UI.Button("button %s" % i, callback) The "i=i" part binds a local variable "i" to the *current* value of the outer variable "i". Two other uses are local caches/memoization; e.g. def calculate(a, b, c, memo={}): try: value = memo[a, b, c] # return already calculated value except KeyError: value = do calculation on a, b, c memo[a, b, c] = value # update the memo dictionary return value (this is especially nice for certain kinds of recursive algorithms) and, for highly optimized code, local rebinding of global names: def this_one_must_be_fast(x, sin=math.sin, cos=math.cos): ... Hope this helps more than it confuses. From misceverything at gmail.com Sun Jul 20 11:27:41 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Sun, 20 Jul 2008 08:27:41 -0700 (PDT) Subject: Web Server Message-ID: As part of a Python app I wrote recently (for Windows), I would like to give the option of an HTTP (HTTPS if possible, but not necessary) front end, which would then call some existing python scripts. My question is - I know I can write a simple HTTP server in Python, but if there's something simple already out there, I'd prefer to just use that. Basically all I need is a simple (i.e. preferably a single executable) web server that can serve up my content - the only thing I want the user to be able to configure is the port the web server listens on (or ports if HTTPS also), and the location of the HTML files... thanks in advance for your help. From fredrik at pythonware.com Wed Jul 23 03:13:04 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 09:13:04 +0200 Subject: Proper way to query user and group database on a Unix host? In-Reply-To: <1216792038.7380.7.camel@mmaccana-laptop> References: <1216792038.7380.7.camel@mmaccana-laptop> Message-ID: Mike MacCana wrote: > What's the proper way to query the passwd and group database on a Unix > host? > > I'd like to fetch the users in a group (obviously from name services), > but my many varied searches can't find any reference of someone ever > looking up users on a Unix system, just NT. Weird, I know. the relevant modules are "pwd", "spwd" and "grp"; see: http://docs.python.org/lib/unix.html From spandanagella at gmail.com Thu Jul 17 06:18:45 2008 From: spandanagella at gmail.com (spandana g) Date: Thu, 17 Jul 2008 18:18:45 +0800 Subject: Fwd: Hello In-Reply-To: References: Message-ID: Hello , Traceback (most recent call last): File "C:\Python25\hadi_yahoo.py", line 12, in file_source.write(urllib2.urlopen(req).read()) File "C:\Python25\lib\urllib2.py", line 124, in urlopen return _opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 387, in open response = meth(req, response) File "C:\Python25\lib\urllib2.py", line 498, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 425, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 506, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 999: Unable to process request at this time -- error 999 Previously i got the error which I have attached below when I use just urlopen . But now when I use this http request user_agent='Mozilla/3.0(compatible;MISE 5.5;Windows NT)' headers={'User-Agent':user_agent} req=urllib2.Request(url,None,headers) file_source.write(urllib2.urlopen(req).read() its still giving the error mentioned above .. Iam accessing the yahoo search engine .. link is "http://search.yahoo.com/search?n=20&p=ipod" I'm attaching the python file i have written just have a look and suggest me something that works for this query Thank You, Spandana. ---------- Forwarded message ---------- From: spandana g Date: Thu, Jul 3, 2008 at 2:52 PM Subject: HTTP request error with urlopen To: python-list at python.org Hello , I have written a code to get the page source of the google search page .. this is working for other urls. I have this problem with import re from urllib2 import urlopen string='http://www.google.com/search?num=20&hl=en&q=ipod&btnG=Search' file_source=file("google_source.txt",'w') file_source.write(urlopen(string).read()) page_content=file_source.readlines() Traceback (most recent call last) : File "C:/Python25/google.py", line 5,in file_source.write(urlopen(string).read()) File "C:\Python25\lib\urllib2.py", line 124 , in urlopen return__opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 387 , in open response =meth(req, response) File "C:\Python25\lib\urllib2.py", line 498 , in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 425, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 360, in __call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 506, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: Forbidden Actually urlopen is working for google labs sets page but not for the google.com and even I have same problem with wikipedia . Please let me know .. If any one of have any idea about this . Thank You, Spandana. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: hadi_yahoo.py URL: From adityashukla1983 at gmail.com Thu Jul 24 18:46:41 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Thu, 24 Jul 2008 17:46:41 -0500 Subject: file operations. Message-ID: <73045cca0807241546k3697a77cs999bad6d62867167@mail.gmail.com> Guys thanks for your previous help .I have a doubt again My text file is :- 0\9\10\11|0.50|c:\windows\apppatch/AcLayers.dll 0\9\10\11|0.50|c:\windows\apppatch/AcRedir.dll 0\9\10|0.66|c:\windows\apppatch/AcSpecfc.dll 0\9|0.83|c:\windows\apppatch/iebrshim.dll 0|0.92|c:\windows\apppatch/pcamain.sdb 0|0.92|c:\windows\apppatch/sysmain.sdb 0|0.93|c:\windows\apppatch/AcXtrnal.dll 0|0.97|c:\windows\apppatch/msimain.sdb 0|0.98|c:\windows\apppatch/AcRes.dll 0|0.98|c:\windows\apppatch/drvmain.sdb 0|0.98|c:\windows\apppatch/en-US/AcRes.dll.mui 0|0.99|c:\windows\apppatch/apihex86.dll 0|1.00|c:\windows\apppatch/AcGenral.dll now this is what happens >>> x=open("c:\\test2.txt","rb") >>> x.readline() '\n' ---? i am not able to understand why is new line character returned here >>> l =x.readline() >>> print l Also , because of this i am not able to extract the floating point values ie 0.50,0.50,0.66 respectively cause when i use the proposed solution given earlier data=[] for line in x: line=line.split("|") data.append(float(line[-2])) --> i am trying to get the floating point values from the back i receive this error message Traceback (most recent call last): File "", line 3, in d.append(float(line[-2])) IndexError: list index out of range Whereas the solution works well with the dummy text file which i have created which is a.txt jd|fj|dnv|jd|0.33|c:\\windows\\win32 shcbsbs|nscsjsj|0.93|hsbcjsnc x=open("a.txt","r") data=[] for line in x: line=line.split("|") data.append(float(line[-2])) print data 0.3300002,0.9300006 Please help me fix this problem Thanks in advance Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim_grove at sil.org Thu Jul 3 13:15:59 2008 From: tim_grove at sil.org (Tim Grove) Date: Thu, 03 Jul 2008 18:15:59 +0100 Subject: manipulating movie files with Python Message-ID: <486D094F.9000606@sil.org> I would like to write a python script which could take a movie file name (avi, mov, mpg) along with a start and stop time as parameters, and return to me a new movie file just containing that section of the original which I'm interested in. Is there a Python library which could already perform such magic? Thanks for any suggestions. Best regards, Tim From tjreedy at udel.edu Sun Jul 27 02:22:17 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 02:22:17 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > On Jul 26, 2:25 pm, Terry Reedy >> There is a lot of code you have not seen. Really. In informal code I >> use 's' and 'o' for 'self' and 'other'. I don't usually post such >> because it is not considered polite. So you have seen a biased sample >> of the universe. > > You take the name down to a single letter. As I suggested in an > earlier post on this thread, why not take it down to zero letters? Because 1 letter is legal now, while no letters (already proposed and rejected) is a major change and breakage of current simplicity and consistency for zero functional benefit. From grahn+nntp at snipabacken.se Mon Jul 7 13:43:16 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 7 Jul 2008 17:43:16 GMT Subject: The Yield statement References: Message-ID: On Sun, 6 Jul 2008 00:29:26 -0700, Mark Tolonen wrote: > > "inhahe" wrote in message > news:z6_bk.24960$AJ6.1423 at bignews8.bellsouth.net... ... >> note that this won't work; >> def f(): >> for x in xrange(10): >> for y in xrange(10): >> yield (x,y) >> >> yield just doesn't work right with multiple levels of loops. i had to >> discover that the hard way. > > Huh? Works fine: [...] Yes -- as is expected. Yield would be much less useful if it only work with strange restrictions on the structure of the function containing it. As far as I can tell, you can pick any function, stick zero or more yield statements into it, and it will work as expected: hit a yield, and you get another value for your sequence. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From peter.bulychev at gmail.com Tue Jul 1 14:54:29 2008 From: peter.bulychev at gmail.com (Peter Bulychev) Date: Tue, 1 Jul 2008 22:54:29 +0400 Subject: convert unicode characters to visibly similar ascii characters In-Reply-To: <486A7BB5.3000501@shopzeus.com> References: <486A7BB5.3000501@shopzeus.com> Message-ID: Thank you for you answer. If you only want this to work for a subset, please define that subset. Actually, I want to convert only punctuations (dots, commas, hyphens and so on). -- Best regards, Peter Bulychev. -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Mon Jul 14 18:32:33 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 14 Jul 2008 18:32:33 -0400 Subject: Bug when using with_statement with exec In-Reply-To: References: Message-ID: <16651e80807141532k391b452cmc5eb6deba38bbdbd@mail.gmail.com> On Mon, Jul 14, 2008 at 6:00 PM, Matimus wrote: > If I create a function by using exec on a string and _don't_ end the > string with a new-line it will work just fine unless I "from > __future__ import with_statement". [snip] > I searched python's issue database and didn't see anything similar to > this. If there is already an issue related to this, please point me to > it... or better yet, let me know how you found it. Possibly related to http://bugs.python.org/issue1184112, and/or http://bugs.python.org/issue501622? Since you asked, I found it by googling the words "python exec with newline". The second item was an email on Python-Dev with a similar bug and referencing an issue id. The comments on that issue led to the other one. -- Jerry From martin at v.loewis.de Mon Jul 7 18:55:16 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 Jul 2008 00:55:16 +0200 Subject: Memory error while saving dictionary of size 65000X50 using pickle In-Reply-To: References: Message-ID: <48729ed5$0$12966$9b622d9e@news.freenet.de> > I didn't have the problem with dumping as a string. When I tried to > save this object to a file, memory error pops up. That's not what the backtrace says. The backtrace says that the error occurs inside pickle.dumps() (and it is consistent with the functions being called, so it's plausible). > I am sorry for the mention of size for a dictionary. What I meant by > 65000X50 is that it has 65000 keys and each key has a list of 50 > tuples. [...] > > You exmple works just fine on my side. I can get the program import pickle d = {} for i in xrange(65000): d[i]=[(x,) for x in range(50)] print "Starting dump" s = pickle.dumps(d) to complete successfully, also, however, it consumes a lot of memory. I can reduce memory usage slightly by a) dumping directly to a file, and b) using cPickle instead of pickle i.e. import cPickle as pickle d = {} for i in xrange(65000): d[i]=[(x,) for x in range(50)] print "Starting dump" pickle.dump(d,open("/tmp/t.pickle","wb")) The memory consumed originates primarily from the need to determine shared references. If you are certain that no object sharing occurs in your graph, you can do import cPickle as pickle d = {} for i in xrange(65000): d[i]=[(x,) for x in range(50)] print "Starting dump" p = pickle.Pickler(open("/tmp/t.pickle","wb")) p.fast = True p.dump(d) With that, I see no additional memory usage, and pickling completes really fast. Regards, Martin From elessar at nienna.org Fri Jul 25 12:09:52 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 25 Jul 2008 10:09:52 -0600 Subject: Execution speed question In-Reply-To: <8c652342-fc15-43bc-bb6c-445e3ca7755f@u36g2000pro.googlegroups.com> References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> <4889e5bc$1@news2-rz-ap.ethz.ch> <8c652342-fc15-43bc-bb6c-445e3ca7755f@u36g2000pro.googlegroups.com> Message-ID: <4889FAD0.7010803@nienna.org> Iain King wrote: > On Jul 25, 4:22 pm, Matthew Fitzgibbons wrote: >> It seems like the probability calculation applies to all three equally, >> and can therefore be ignored for the simulations. > > The probability affects (1) more. My reasoning for this being: as > probability gets lower the number of times you have to loop over the > list increases. (1) always loops over the full list, but with each > successive iteration (2) and (3) are looping over smaller and smaller > lists. In the end this adds up, with (1) becoming slower than (2), > even though it starts out quicker. > > Iain > -- > http://mail.python.org/mailman/listinfo/python-list > I meant the _calculation_ of the probability affects all three equally, not the value itself. As your simulations show, different probabilities affect the algorithms differently; I'm talking about the algorithm to arrive at the probability value. -Matt From bearophileHUGS at lycos.com Sat Jul 5 09:29:08 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 5 Jul 2008 06:29:08 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Paddy: > You could argue that if the costly RE features are not used then maybe > simpler, faster algorithms should be automatically swapped in but .... Many Python implementations contains a TCL interpreter. TCL REs may be better than Python ones, so it can be interesting to benchmark the same RE with TCL, to see how much time it needs. If someone here knows TCL it may require to write just few lines of TCL code (used through tkinter, by direct call). Bye, bearophile From none at this.time Wed Jul 9 11:04:42 2008 From: none at this.time (The Pythonista) Date: Wed, 09 Jul 2008 11:04:42 -0400 Subject: Python equivalent of call/cc? Message-ID: Yesterday, I was hacking around a bit, trying to figure out how to implement the semantics of call/cc in Python. Specifically, I wanted to translate this Scheme code to equivalent Python: #### (define theContinuation #f) (define (test) (let ((i 0)) (call/cc (lambda (k) (set! theContinuation k))) (set! i (+ i 1)) i)) (test) (theContinuation) (theContinuation) #### Incidentally, those last three lines evaluate to 1, 2, and 3, respectively. The best Python translation I could come up with was something like this (targeted at Python 2.5): #### import inspect theContinuation = None def call_cc (f): f (inspect.currentframe().f_back) def invoke (c): exec c.f_code in c.f_globals, c.f_locals def test(): i = 0 call_cc (lambda k: globals().update({'theContinuation' : k })) i = i + 1 print i test() invoke (theContinuation) invoke (theContinuation) #### Now, this code is wrong on a number of levels [I am indeed aware of exactly how ugly that lambda is...], but, in particular, my continuations / stack frames don't seem to be resuming at the right point. I'd expect invoke (theContinuation) to restart on the line immediately following call_cc, but it does not. Not surprisingly, the output is also wrong. (I get 1, 1, and 1 rather than 1, 2, and 3.) Can anyone help me by, perhaps pointing out some silly error I made? Failing that, can someone show me a working implementation of call/cc (preferably based on some form of stack inspection)? Thanks! -- code.py: A blog about life, the universe, and Python http://pythonista.wordpress.com ** Posted from http://www.teranews.com ** From kotecha.ravi at googlemail.com Mon Jul 21 12:01:10 2008 From: kotecha.ravi at googlemail.com (Ravi Kotecha) Date: Mon, 21 Jul 2008 09:01:10 -0700 (PDT) Subject: Getting the name of a variable which was used as a function parameter. Message-ID: <9e2e64db-d594-408d-9418-b17133f23204@27g2000hsf.googlegroups.com> Hi guys, I thought this was pretty cool and since I spent 30 mins or so goggling before giving up and figuring out myself I thought I'd share it with you. >>> def a(a): ... for k,v in sys._getframe(1).f_locals.items(): ... if id(v) == id(a): ... print k ... >>> hello = 123 >>> a(hello) hello ## pretty cool. It's totally useless but I wanted to do it for logging purposes. It will still return weird results if you have two labels pointing to the same object but I'm not sure how to get around that, any ideas? Regards, Ravi Kotecha From steven at REMOVE.THIS.cybersource.com.au Tue Jul 29 05:27:41 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 09:27:41 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: On Tue, 29 Jul 2008 01:37:45 -0700, Carl Banks wrote: > On Jul 28, 8:15 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: >> > On Jul 28, 10:00 am, Steven D'Aprano > > cybersource.com.au> wrote: >> >> Cutting to the crux of the discussion... >> >> >> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: >> >> > I want something where "if x" will do but a simple explicit test >> >> > won't. >> >> >> Explicit tests aren't simple unless you know what type x is. If x >> >> could be of any type, you can't write a simple test. Does x have a >> >> length? Is it a number? Maybe it's a fixed-length circular length, >> >> and the length is non-zero even when it's empty? Who knows? How many >> >> cases do you need to consider? >> >> > Use case, please. I'm asking for code, not arguments. Please give >> > me a piece of code where you can write "if x" that works but a simple >> > explicit test won't. >> >> I gave you a piece of code, actual code from one of my own projects. If >> you wouldn't accept that evidence then, why would you accept it now? > > I would accept as "evidence" something that satisfies my criteria, which > your example did not: it could have easily (and more robustly) been > written with a simple explicit test. Only at the cost of completely ignoring the functional requirements and changing the API. In other words: you ignore my code, and invent your own imaginary code that does something completely different, then say that this imaginary code is better. And I question your assertion that a "simple explicit test" is more robust. Where's your evidence for that? > I am looking for one that can't. If you are writing code that needs to do the right thing with arbitrary types, then your so-called "simple explicit tests" simply can't work. If your code isn't expected to deal with arbitrary types, then you've got an excellent chance that it will work, because you know what types to expect. Until somebody passes a type that you didn't expect, and your code fails because it makes assumptions about the object. If you know that you only get lists, then "if len(x)!=0" is a perfectly good test (apart from being longer to type, harder to read, and slower to execute than "if x"). It will work so long as you only get objects where a length of zero is equivalent to being false. That's a good assumption to make, but it is an *unnecessary* assumption. Any reasonable object you get will know if it is false/nothing or true/something, so why make any assumptions? Just ask the object. It knows. > You keep bringing up this notion of "more complex with no benefit", > which I'm simply not interested in talking about that at this time, and > I won't respond to any of your points. Of course not. > I am seeking the answer to one > question: whether "if x" can usefully do something a simple explicit > test can't. "if x" is completely type agnostic. You can pass an object of any type to it, and it will work. (Excluding objects with buggy methods, naturally.) Try doing that with one of your so-called "simple explicit tests". -- Steven From __peter__ at web.de Thu Jul 3 04:44:54 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 Jul 2008 10:44:54 +0200 Subject: How to pickle bound methods References: Message-ID: srinivasan srinivas wrote: Please don't top-post. > No. It does not work. That's what I said. Try class A(object): @staticmethod def alpha(): print "Hello" alpha = A.alpha Peter From bignose+hates-spam at benfinney.id.au Wed Jul 2 09:25:24 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 02 Jul 2008 23:25:24 +1000 Subject: Email Validation with domain References: Message-ID: <873ams770b.fsf@benfinney.id.au> Sallu writes: > validateEmail(msg) i wrote a script above it works fine Actually, no. It rejects a great many email addresses that are valid. > but it does not check for valid domain like .com .org .in how to > validate with domain To validate a domain for delivery of email, check with the DNS by requesting the A or MX record for that domain. To validate an email address, check with the mail server for that domain by sending a message to the address. Neither of them should be "validated" by a regular expression. Please refer to RFC 3696 described as "Recommended techniques for applications checking or manipulating domain and other internet names". -- \ ?Pinky, are you pondering what I'm pondering?? ?Wuh, I think | `\ so, Brain, but wouldn't anything lose its flavor on the bedpost | _o__) overnight?? ?_Pinky and The Brain_ | Ben Finney From sublesi.try at gmail.com Sat Jul 26 11:32:23 2008 From: sublesi.try at gmail.com (lindi) Date: Sat, 26 Jul 2008 08:32:23 -0700 (PDT) Subject: Find Sofas Message-ID: <1edf7715-a312-40c8-8596-271c1d18df64@p10g2000prf.googlegroups.com> Huge Selections at Great Prices The Convenience of OneCart! http://good-furniture-care.page.tl/ From __peter__ at web.de Sat Jul 19 05:44:20 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 19 Jul 2008 11:44:20 +0200 Subject: Question References: Message-ID: perl_wizard at manx.net wrote: > Why is Perl so much better than python? Because you have the video: http://mail.python.org/pipermail/python-list/2004-March/253370.html From larry.bates at websafe.com` Tue Jul 8 20:01:26 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 08 Jul 2008 19:01:26 -0500 Subject: plugins using cvs/distutils? In-Reply-To: References: Message-ID: Deacon wrote: > Hi. I have an open-source application development environment that I > would like to enable an automated package download system for (like > downloadable plugins), using sourceforge as its repository. My > software will have a menu-based popup window, that will list the > packages (Applications) available through the project distribution > page. If a user selects a package from this window, it should be > automatically retrieved and installed by the development environment. > My software already has a system for automatically recognizing and > deploying new packages, so I'm only asking for help with distribution > logistics, I think. > > I'm thinking that I will use the built-in ftplib to list and retrieve > the files (but I'm not sure yet where to look), and then the distutils > should probably be used in a standardized manner to actually install > the packages, right? I've established a CVS, but I'm not aware of any > built-in-python tools for managing the CVS, and I would rather not add > any new user-has-to-download-dependencies for this. Is there an easier > or alternative advisable approach? I have a linux box, should I be > using it to build all of the platform versions? Any advice would be > much appreciated, this is my first distribution project > (sourceforge.net/projects/spade). > > Thanks a bunch, > > Deacon You might consider distributing as eggs and use setuptools/easyinstall to do this for you. -Larry http://peak.telecommunity.com/DevCenter/setuptools From teuben at verizon.net Mon Jul 28 23:26:45 2008 From: teuben at verizon.net (Peter Teuben) Date: Tue, 29 Jul 2008 03:26:45 GMT Subject: exec(code) not allowing import on top level? Message-ID: if I define a simple string code, with the following contents: import math def foo(x): return math.sqrt(x) and i run it using exec(code) in python, math is not known. But when I recode the string as: def foo(x): import math return math.sqrt(x) it works fine. That seemed like an inconsistency, since it works fine otherwise, as expected. It's easy to work around, but just odd to find this out. thanks peter From darcy at druid.net Sat Jul 26 10:11:13 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 26 Jul 2008 10:11:13 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87fxpxw0ku.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> Message-ID: <20080726101113.07d77b0a.darcy@druid.net> On Sat, 26 Jul 2008 09:45:21 +0200 Torsten Bronger wrote: > Of course, "self" would have to become a reserved word. You could > say that this may break some code, but I don't see much freedom Isn't this a showstopper all by itself? > removed from the language. After all, being a German, I still can't > write "F?r i in range(10)". ;-) Yes, this is why good languages try to limit the number of reserved words as much as possible. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From larry.bates at websafe.com` Wed Jul 23 08:11:26 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 23 Jul 2008 07:11:26 -0500 Subject: os.walk question In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Lanny wrote: > >> How would one make a list of the files in the top directory >> using os.walk. >> >> I need to pick a random file from said list. > > if you want a list of files from a single directory, use listdir, not walk: > > >>> import os, random > >>> random.choice(os.listdir("/")) > 'python25' > > > Or use glob. import glob random.choice([f for f in glob.glob(root, "*")]) -Larry From rhamph at gmail.com Wed Jul 30 13:54:51 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 30 Jul 2008 10:54:51 -0700 (PDT) Subject: proxy class and __add__ method References: <18715799.post@talk.nabble.com> Message-ID: <3d59a908-f585-4ff5-ad37-bb48579cc9cb@a21g2000prf.googlegroups.com> On Jul 29, 10:23?pm, "Gabriel Genellina" wrote: > En Tue, 29 Jul 2008 13:13:51 -0300, Magnus Schuster ? > escribi : > > > > > Hello, > > I have written the following small proxy class which I expect to pass all > > function calls to the 'original' object: > > > --- BEGIN --- > > class proxy(object): > > ? ? def __init__( self, subject ): > > ? ? ? ? self.__subject = subject > > ? ? def __getattr__( self, name ): > > ? ? ? ? return getattr( self.__subject, name ) > > > prx_i=proxy(1) > > print hasattr(prx_i,'__add__') > > j=prx_i.__add__(1) > > k=prx_i+1 > > --- END --- > > > Actually the "hasattr(prx_i,'__add__')" returns "True" as expected, and > > "j=prx_i.__add__(1)" sets j=2. > > > But "k=prx_i+1" raises a > > : unsupported operand type(s) for +: 'proxy' > > and 'int'. > > > How is this addition different from the previous line "j=..."? And how ? > > can I > > modify the proxy class so that all methods are passed on, which are not > > explicitly overloaded? > > __magic__ methods on new style classes are searched in the class, *not* in ? > the instance. prx_i+1 looks for __add__ in type(prx_i), that is, in the ? > proxy class. This much is true. > Try implementing a similar __getattr__ method in a metaclass. But I don't think they use __getattr__.. they bypass it. Effectively they catch the assignment to __add__ and cache it. You'll have to always define it in the class and have it be ineffectual in some cases. From elessar at nienna.org Sat Jul 26 00:47:28 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 25 Jul 2008 22:47:28 -0600 Subject: 2d graphics - what module to use? In-Reply-To: <5035d4cb-1976-47d5-8887-4e8381407a7b@m44g2000hsc.googlegroups.com> References: <5035d4cb-1976-47d5-8887-4e8381407a7b@m44g2000hsc.googlegroups.com> Message-ID: <488AAC60.8020903@nienna.org> sturlamolden wrote: > On Jul 25, 8:13 am, Pierre Dagenais wrote: >> What is the easiest way to draw to a window? I'd like to draw something >> like sine waves from a mathematical equation. >> Newbie to python. > > For mathematica equations, NumPy and matplotlib is probably the best > option. I prefer to embed matplotlib in wxPython. wxAgg is an > excellent backend. > > For more general 2D graphics, there are several options, including: > > - pygame (uses SDL) > - aggdraw module > - pycairo > - pyopengl > - wxPython's device context (ditto for other GUI libraries) > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > If you're using wx, there is also wx.lib.plot, which I found to be _much_ faster than matplotlib in my application, especially when resizing. -Matt From siona at chiark.greenend.org.uk Mon Jul 28 10:00:23 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 28 Jul 2008 15:00:23 +0100 (BST) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <488d86e2$1@news2-rz-ap.ethz.ch> <488dc3eb$1@news2-rz-ap.ethz.ch> Message-ID: Suresh Pillai wrote: > [ ... ] is >there any way to iterate over the items in a set other than converting to >a list or using the pop() method. Er, how about directly iterating over the set? -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From wtanksleyjr at gmail.com Tue Jul 29 15:42:07 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Tue, 29 Jul 2008 12:42:07 -0700 (PDT) Subject: iterating "by twos" References: Message-ID: kj wrote: > Is there a special pythonic idiom for iterating over a list (or > tuple) two elements at a time? I don't know of one, and I shouldn't be answering, but the following should work: def gulp_two(items): for i,j in zip(items[0::2], items[1::2]): yield (i,j) Let's see... >>> list(gulp_two(range(10))) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] Okay, it works. -Wm From kyosohma at gmail.com Fri Jul 18 16:21:33 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 18 Jul 2008 13:21:33 -0700 (PDT) Subject: Distributing Python App References: <072bf39b-d700-482e-ab59-36840e21e83e@a70g2000hsh.googlegroups.com> Message-ID: On Jul 18, 2:35?pm, KDawg44 wrote: > Hi, > > I am very new to Python but find it very interesting (from what I know > of it) and am considering writing an application. ?However, I have a > question regarding distribution of the app once it is done. ?Is there > a way to package everything a user needs to run the app or will they > have to install Python their machine? ?This is probably an obvious > question but most development I do is for administrative tasks on > servers and such, not usually development of an app for someone else. > > Thanks for your help. > > Kevin There is a variety of packaging programs. For Windows, you can use py2app and py2exe. I think the former can also be used for Mac and maybe Linux. If you are doing it on Windows, I would recommend packaging it with one of those and then using something like Inno Setup to create an installer. Mike From ggpolo at gmail.com Thu Jul 3 16:54:57 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 3 Jul 2008 17:54:57 -0300 Subject: controlling the windows In-Reply-To: <153e45a5-a161-4305-be6f-0fd56aee37e0@f1g2000prb.googlegroups.com> References: <153e45a5-a161-4305-be6f-0fd56aee37e0@f1g2000prb.googlegroups.com> Message-ID: On Thu, Jul 3, 2008 at 4:16 PM, varun chadha wrote: > i am developing an application using Tkinter where 'next' button > takes to another window and removes the first one from screen and > 'back' button bring me back to previous window and so on. > though i am able to move from one window to another but is unable to > remove the previous one from the screen. does anybody have a idea how > to do away with this problem. There are several solutions to this. You could just pack_forget the another window and pack a new one in its place. I have just prepared a simple Wizard, you can take a look at it here: http://code.google.com/p/python-ttk/wiki/ttkWizard and you will notice that it uses ttk. If you already use tk 8.5, and tkinter compiled against it, then ttk is available, otherwise you have to install tile or compile tkinter with tk 8.5 (python 2.6b1 includes tk 8.5.2 in the windows build). To use the ttk widgets you will need a wrapper and you will find one here: http://code.google.com/p/python-ttk/ > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From dwahler at gmail.com Tue Jul 22 00:39:58 2008 From: dwahler at gmail.com (David Wahler) Date: Mon, 21 Jul 2008 23:39:58 -0500 Subject: Time Complexity of String Operations In-Reply-To: References: Message-ID: On Mon, Jul 21, 2008 at 10:31 PM, youtoo wrote: > It has been extensively discussed the time complexity (quadratic) of > string concatenation (due to string's immutability). Actually, it is roughly linear, at least for reasonable string lengths: $ python -V Python 2.5.2 $ python -mtimeit -s "n=1000; a='#'*n" "a+a" 1000000 loops, best of 3: 1 usec per loop $ python -mtimeit -s "n=10000; a='#'*n" "a+a" 100000 loops, best of 3: 5.88 usec per loop $ python -mtimeit -s "n=100000; a='#'*n" "a+a" 10000 loops, best of 3: 59.8 usec per loop Repeatedly constructing a string by appending a constant number of characters at a time, however, is quadratic in the final string length (although VM optimizations may affect this). > But what is: > > == the time complexity of string indexing? Is it constant? Yes. > == the time complexity of string slicing? Is it O(K) with K the > slice's length? I suspect so, since the time is dominated by the time taken to copy the data into a new string object. > How are strings stored in Python? As arrays? As linked lists? Arrays; see Include/stringobject.h in the Python source distribution. -- David From fetchinson at googlemail.com Fri Jul 11 14:35:36 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Fri, 11 Jul 2008 11:35:36 -0700 Subject: Python with Ecmascript In-Reply-To: <7HMdk.14$6O4.10@trnddc06> References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <486fe241$0$867$ba4acef3@news.orange.fr> <7HMdk.14$6O4.10@trnddc06> Message-ID: >>>NJSModule? >>>http://en.wikipedia.org/wiki/NJS > >> This seems to be very good indeed. Just downloaded njs but the only >> njsmodule version I could find was for python 2.1. Does anyone have a >> recent copy? > > 1. You might ask here: > http://lists.njs-javascript.org/cgi-bin/mailman/listinfo/users > > 2. Did you try to compile it? > Is there anything obviously 2.5 incompatible? Well, so far I couldn't even compile njs (./configure complains about HOST setting or some such) so haven't looked at njsmodule yet. Thanks for the suggestions! Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From mva.led at gmail.com Mon Jul 28 01:05:47 2008 From: mva.led at gmail.com (Manuel Vazquez Acosta) Date: Mon, 28 Jul 2008 01:05:47 -0400 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: <488A2E72.6030802@activestate.com> References: <487E2BCE.30108@hughes.net> <488A2E72.6030802@activestate.com> Message-ID: <488D53AB.7090300@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Just test for maxint value: from sys import maxint if maxint >> 33: print "more than 32 bits" # probably 64 else: print "32 bits" Best regards, Manuel. Trent Mick wrote: > norseman wrote: >> >> > > I need to know if I'm running on 32bit or 64bit ... so far I haven't >> > > come up with how to get this info via python. sys.platform returns >> > > what python was built on ... but not what the current system is. >> > > >> > > I thought platform.uname() or just platform.processor() would have >> > > done it, but python returns an empty string on windows. Any ideas? > > If just for Windows I believe you can use the "PROCESSOR_ARCHITECTURE" > environment variable -- at least on NT-based Windows versions. > > Values are x86 (32-bit), IA64 (64-bit) and AMD64 (64-bit). > > Here is a "platinfo.py" module that might help if you need to do this > for other platforms: > > http://svn.openkomodo.com/openkomodo/view/openkomodo/trunk/util/platinfo.py > > > Cheers, > Trent > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkiNU6IACgkQI2zpkmcEAhi6sACgo1ZyGKCWtnBPLXr1EjgSq3V4 GEAAoL+zZStfGYaZxg/zYoUqk6UFa+oM =g+tz -----END PGP SIGNATURE----- From michele.simionato at gmail.com Thu Jul 10 09:10:35 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 10 Jul 2008 06:10:35 -0700 (PDT) Subject: python scalability References: Message-ID: <799d6ad1-8424-4b2a-96a6-6df9a24060d9@27g2000hsf.googlegroups.com> On Jul 10, 6:32?am, Tim Mitchell wrote: > Hi All, > > I work on a desktop application that has been developed using python and > GTK (seewww.leapfrog3d.com). ?We have around 150k lines of python code > (and 200k+ lines of C). We have bigger numbers than yours here (although not for a desktop application) and of course we have the problems of a large size application, but they have nothing to do with Python. The real problem are sociological, not language-related. Essentially, if a project takes 10+ years and 10+ people, with most of the people new, you have an issue, but this is independent from the language. Python is helping us at least because it is readable and the situation would be probably be worse with another language. But as I said the software development practices used are more important than the language in this context. From thomas.troeger.ext at siemens.com Thu Jul 17 09:57:51 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Thu, 17 Jul 2008 15:57:51 +0200 Subject: Python embedding question (2). References: Message-ID: > I'd say that PyGame could be a solution. > > Or otherwise you could do your own audio/graphics programming (you don't > tell us which OS you use, but there exist python modules that allow you > to do barebones graphics & sound programming on linux...). After some more reading I've stumbled over pyglet. Any experiences with it? It seems it does a lot of cool things, if anyone has used it more intensely I'd be happy to hear if the following things can be done: - Linux framebuffer (16, 24 bpp) display of 2d graphics with overlays (i.e. menues, contextual areas that pop up etc.). I don't have X on the embedded device, just the regular framebuffer. - alpha blending of several layers. - rendering of TTF fonts and unicode, for example display of arabic text (which renders from right to left) and mixed text support like in the unicode bidirectional algorithm. - hardware caching of bitmaps for faster graphics operations (needed for tool tips or similar tasks). I'll try to find that out myself (I'm pretty excited about the thing already ^^), but I'd be happy to hear of people who have used it already. Cheers, Thomas. From fredrik at pythonware.com Tue Jul 22 11:31:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 17:31:15 +0200 Subject: Is this a valid use of 'import'? In-Reply-To: References: Message-ID: Frank Millman wrote: > I know that when a module is imported the first time, it is > 'executed'. This normally entails setting up constants, classes, > functions, etc, that you want to make available to the importer. > > In this particular case, when it is executed, it does a whole lot > more. It reads in some parameters, establishes a socket connection, > starts a thread, and starts monitoring the socket using select.select. > It also exposes some functions that disguise the complexity of reading > from and writing to the socket. > > This enables me to write a 'client' program that look like this - > > --------------------------- > from Utils.client import * > > connect(userid='frank',pwd='') > cust = getRecord( > company='chagford',table='ArCustomers', > column='CustNo',value='A001') > print cust > close() > --------------------------- > > As you can see, it makes writing a client program very easy. > > Are there any problems with this approach? besides being fragile and not scalable and not thread-safe and incompatible with introspection tools and utterly surprising for people used to normal Python behaviour, and only marginally easier to write than, say: from Utils.client import Client c = Client() c.connect(userid='frank',pwd='') cust = c.getRecord( company='chagford',table='ArCustomers', column='CustNo',value='A001') print cust c.close() and some other problems that I cannot think of right now, you mean? From benjamin.kaplan at case.edu Sat Jul 26 23:07:24 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 26 Jul 2008 23:07:24 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <488BDC0A.50403@internetnowasp.net> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <488BDC0A.50403@internetnowasp.net> Message-ID: On Sat, Jul 26, 2008 at 10:23 PM, Marcus.CM wrote: > Well after reading some of these posts on "sacred python cow" on the "self" > , i would generally feel that most programmers > who started with C++/Java would find it odd. And its true, i agree > completely there should not be a need to put "self" into every single > member function. If you were writing an application and one of your classes > adds the same variable to each of its member function you would do away with > it too. > What could be done instead is :- > > 1. python should hardcode the keyword "self". So whenever this keyword is > used, it would automatically implied that it is > referring to a class scope variable. This would be similar to how the > "this" keyword is used in C++. > > 2. Omit self from the parameter. > > class Abc : > def DoSomething (a,b,c) : > # class variable > self.somevar = a > self.someblar = b > self.somec = c > somevar = a * b # local variable > > > So, what happens in this case, using your Abc class from before? def DoTheSameThing(abc, a, b, c) : abc.somevar = a abc.someblar = b abc.somec = c somevar = a * b Abc.DoSomething = DoTheSameThing Would methods defined this way never have access to the class instance? > > > Russ P. wrote: > >> On Jul 26, 2:25 pm, Terry Reedy >> >> >>> There is a lot of code you have not seen. Really. In informal code I >>> use 's' and 'o' for 'self' and 'other'. I don't usually post such >>> because it is not considered polite. So you have seen a biased sample >>> of the universe. >>> >>> >> >> You take the name down to a single letter. As I suggested in an >> earlier post on this thread, why not take it down to zero letters? You >> could if Python accepted something like >> >> class Whatever: >> >> def fun( , cat): >> >> .cat = cat >> >> This is even better than the single-character name, not only because >> it is shorter, but also because there is no question that you are >> referring to "self." No need to look back at the method signature to >> verify that. >> >> For those who don't like the way the empty first argument looks, maybe >> something like this could be allowed: >> >> def fun( ., cat): >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> >> > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alex.gaynor at gmail.com Tue Jul 29 22:12:15 2008 From: alex.gaynor at gmail.com (alex.gaynor at gmail.com) Date: Tue, 29 Jul 2008 19:12:15 -0700 (PDT) Subject: How can I check nbr of cores of computer? References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> <37e26af1-c6a7-4302-b93c-39164b222f26@34g2000hsf.googlegroups.com> Message-ID: On Jul 29, 7:44?pm, Mensanator wrote: > On Jul 29, 5:53?pm, defn noob wrote: > > > How can I check how many cores my computer has? > > Is it possible to do this in a Python-app? > > If you're using Windows, get PyWin32: > > win32api.GetSystemInfo > tuple = GetSystemInfo() > > Retrieves information about the current system. > > Win32 API References > > Search for GetSystemInfo at msdn, google or google groups. > > Return Value > The return value is a tuple of 9 values, > which corresponds to the Win32 SYSTEM_INFO structure. > The element names are: > dwOemId > dwPageSize > lpMinimumApplicationAddress > lpMaximumApplicationAddress > dwActiveProcessorMask > dwNumberOfProcessors > dwProcessorType > dwAllocationGranularity > (wProcessorLevel,wProcessorRevision) > > >>> import win32api > >>> win32api.GetSystemInfo() > > (0, 4096, 65536, 2147418111, 3L, 2, 586, 65536, (6, 3846)) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?processors This: http://pyprocessing.berlios.de/ has a method that returns CPU count. From robert.rawlins at thinkbluemedia.co.uk Thu Jul 17 12:52:05 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 17 Jul 2008 17:52:05 +0100 Subject: Unusual Exception Behaviour In-Reply-To: References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> Message-ID: <005b01c8e82d$71714480$5453cd80$@rawlins@thinkbluemedia.co.uk> Hi MK, >>Robert Rawlins wrote: >> >> I certainly like that implementation for logging the exceptions, however, at >> the moment I don't even know where the exceptions are occurring, or what >> type they are, could I still use this method to log any and all exceptions >> raised in the application? > Remember, Google is your friend, here's the crux of the method without > the fancy schmancy sugar coating: > > http://linux.byexamples.com/archives/365/python-convey-the-exception-traceba ck-into-log-file/ > > if __name__=="__main__": > try: > main() > except: > print "Trigger Exception, traceback info forward to log file." > traceback.print_exc(file=open("errlog.txt","a")) > sys.exit(1) > I've just given this solution a shot but I still seem to get the same result, it suddenly starts dumping the log data to the command line, and nothing gets printed in error.txt apart from the keyboard interrupt from when I kill the application. For some reason the exceptions don't seem to be raised properly so obviously aren't being caught at this higher level. So confusing. From mail at timgolden.me.uk Wed Jul 16 12:16:50 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 17:16:50 +0100 Subject: About wmi In-Reply-To: <487E1AD4.9020509@timgolden.me.uk> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> <487E1AD4.9020509@timgolden.me.uk> Message-ID: <487E1EF2.4090500@timgolden.me.uk> Assuming that the error comes back in the sys.stdout encoding, the following version *should* work ok. I still haven't got a non-English set up to test it on, but it certainly does return a Unicode error message. http://timgolden.me.uk/wmi-project/wmi.py The usual test case, if you wouldn't mind: import wmi wmi.WMI ("non-existent computer") should give a (language-specific) error message, not an UnicodeDecodeError TJG From mensanator at aol.com Sun Jul 20 22:31:23 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 20 Jul 2008 19:31:23 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> On Jul 20, 7:37?pm, Roy Smith wrote: > In article > , > > ?Mensanator wrote: > > C isn't a high level language, that's part of its problem. > > C is the highest level assembler language Isn't that like bragging about being the smartest kid on the short bus? > I've ever used. ?And I've used a > few. ?It really is cool that you can add two 32-bit integers and not have > to worry about all those carry bits. Carry bits? Who worries about carry bits when you have unlimited precision arithmetic? You want cool? THIS is cool: j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2])) % xyz[1]**(k-1))/xyz[1]**(k-2) From steve at REMOVE-THIS-cybersource.com.au Mon Jul 28 10:00:49 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Jul 2008 14:00:49 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> Message-ID: <009dcc93$0$20313$c3e8da3@news.astraweb.com> Cutting to the crux of the discussion... On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: > I want something where "if x" will do but a simple explicit test won't. Explicit tests aren't simple unless you know what type x is. If x could be of any type, you can't write a simple test. Does x have a length? Is it a number? Maybe it's a fixed-length circular length, and the length is non-zero even when it's empty? Who knows? How many cases do you need to consider? Explicit tests are not necessarily simple for custom classes. Testing for emptiness could be arbitrarily complex. That's why we have __nonzero__, so you don't have to fill your code with complex expressions like (say) if len(x.method()[x.attribute]) > -1 Instead you write it once, in the __nonzero__ method, and never need to think about it again. In general, you should write "if x" instead of an explicit test whenever you care whether or not x is something (true), as opposed to nothing (false), but you don't care what the type-specific definition of something vs. nothing actually is. To put it another way... using "if x" is just a form of duck-typing. Let the object decide itself whether it is something or nothing. -- Steven From jkugler at bigfoot.com Wed Jul 16 14:33:48 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Wed, 16 Jul 2008 10:33:48 -0800 Subject: Is re.findall guaranteed to be "in order?" References: Message-ID: Fredrik Lundh wrote: > Joshua Kugler wrote: > >> Experimenting has shown me that re.findall() will return a list with the >> matches in the order it found them. > > "in the order it found them" doesn't really say much, does it? ;-) > > "findall" and "finditer" both scans the string from left to right, and > will return matches in that order. > > (the documentation is a bit vague, so if you have the time, please add a > request for clarification to the bug tracker) Done. http://bugs.python.org/issue3384 j From dullrich at sprynet.com Mon Jul 7 17:19:33 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 07 Jul 2008 16:19:33 -0500 Subject: How to make a function associated with a class? References: <69e26f9b-2f00-4318-9bc5-6aa94e141bca@59g2000hsb.googlegroups.com> <4d7cf477-e791-4122-bc20-0dbd1a16bc12@j22g2000hsf.googlegroups.com> <0d9c534b-8720-4363-b3e5-eb546dd3637c@8g2000hse.googlegroups.com> Message-ID: In article <0d9c534b-8720-4363-b3e5-eb546dd3637c at 8g2000hse.googlegroups.com>, Kurda Yon wrote: > On Jul 1, 5:01 pm, "bruno.desthuilli... at gmail.com" > wrote: > > On 1 juil, 22:43, Kurda Yon wrote: > > > > > > > > > Hi, > > > > > I have a class called "vector". And I would like to define a function > > > "dot" which would return a dot product of any two "vectors". I want > > > to call this function as follow: dot(x,y). > > > > > Well, I can define a functions "dot" outside the class and it works > > > exactly as I want. However, the problem is that this function is not > > > associated with the class (like methods a method of the class). > > > > > For example, if I call "x.calc()" or "y.calc()", python will execute > > > different methods if "x" and "y" belongs to different classes. I want > > > to have the same with my "dot" function. I.e. I want it calculates the > > > dot product ONLY IF the both arguments of that function belong to the > > > "vector" class. > > > > > Is it possible? > > > > You don't need to make dot() a method of your Vector class to have > > this behaviour, and making it a method of the Vector class isn't > > enough to have this behaviour. > > > > The simplest solution would be: > > > > class Vector(object): > > def dot(self, other): > > if not isinstance(other, type(self)): > > raise TypeError("can only calculate the dot product of two > > vectors") > > # do the job here and return what's appropriate > > > > Now since it's a binary operator, you might as well implement it as > > such: > > > > class Vector(object): > > def __mul__(self, other): > > if not isinstance(other, type(self)): > > raise TypeError("can only calculate the dot product of two > > vectors") > > # do the job here and return what's appropriate > > > > Then use it as doproduct = vector1 * vector2 > > > > HTH > > As far as I understood, In the first case, you gave, I need to call > the function as follows "x.dot(y)". In the second case I need to call > the function as follows "x*y". But I want to call the function as > follows "dot(x,y)". You want to say dot(x,y), but to have the actual behavior determined by the class of which x and y are instances? You could do this: def dot(x,y): return x.dot(y) and now give Vector an appropriate dot(self, other) method. > By the way, "type(self)" returns the name of the class to which the > "self" belongs? > Does "instance" return "true" if the first argument belongs to the > class whose name is given in the second argument? -- David C. Ullrich From gagsl-py2 at yahoo.com.ar Tue Jul 15 01:25:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 02:25:29 -0300 Subject: how can I use exec with main module globals? References: Message-ID: En Sat, 12 Jul 2008 16:15:36 -0300, Akathorn Greyhat escribi?: > Hello, this is my first message in the group. Welcome! > I'm spanish so my english sometimes is really bad, sorry =( > > I have a problem and I hope someone has the answer. > > I'm trying to make an in-game python idle, it works great but the exec > statement can't access the main module globals but only the ones that are > inside the module in wich I defined the function. > > def execute(self, string): > exec(string, globals(), globals()) > > I realized that if I move the code to the main module, It works, but I > want > it to be inside another script. You have to pass in the namespace of the desired module - instead of globals. I'd use an explicit argument: def execute(self, string, namespace): # exec string in namespace # 2.5 exec(string, namespace) # 3.0 Use it this way: execute("a=1", target_module.__dict__) then target_module.a will be 1 -- Gabriel Genellina From arne at vajhoej.dk Sun Jul 13 13:01:13 2008 From: arne at vajhoej.dk (=?UTF-8?B?QXJuZSBWYWpow7hq?=) Date: Sun, 13 Jul 2008 13:01:13 -0400 Subject: spam <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> In-Reply-To: References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> <487a0d4d$0$90272$14726298@news.sunsite.dk> Message-ID: <487a34d5$0$90263$14726298@news.sunsite.dk> donald wrote: > Arne Vajh?j wrote: >>> >>> Google does not accept spam complaints. Go ahead, try it. That's >>> why they've been the #1 Usenet spamming tool for years now. What >>> you're seeing is the spam slowly expanding into the software >>> development groups. uk.railway is probably a random group added to >>> confuse spam filters. Some groups, like rec.photo.digital, have been >>> getting hundreds of Google spams a day for about a year. >>> >>> Ask your news service for a Google UDP (Usenet Death Penalty) or >>> configure your reader to drop everything with "googlegroups.com" in >>> the Message-ID. >> >> Some real users do use GG. > > This is true, however there are acceptable losses. Everybody is free to look at it that way. Arne From wuwei23 at gmail.com Thu Jul 17 19:27:13 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 17 Jul 2008 16:27:13 -0700 (PDT) Subject: x, = y (???) References: Message-ID: <869240fd-38ec-41ba-bd49-048a0693c253@s31g2000prg.googlegroups.com> On Jul 18, 8:01?am, DaveM wrote: > On Thu, 17 Jul 2008 17:32:30 -0400, Terry Reedy wrote: > > >>> *x, = [3] > > >>> x > >[3] > > What does *x signify? Mostly that Terry is using Python 3.0. See: http://www.python.org/dev/peps/pep-3132/ From q2w3qw14 at gmail.com Sun Jul 27 23:44:05 2008 From: q2w3qw14 at gmail.com (Sera Jackson) Date: Sun, 27 Jul 2008 20:44:05 -0700 (PDT) Subject: I love "shelf" BUT References: <1c2d28bb-06e8-4f02-a528-9d86f84366dd@n33g2000pri.googlegroups.com> Message-ID: On Jul 28, 6:25?am, alex23 wrote: > On Jul 28, 12:46?pm, Sera Jackson wrote: > > > ok, I know its an over discussed topic. Althought I understand why it > > is there I cant constantly see it in my argument list in parenthesis. > > > can someone give me an insight of the cons of a syntax like this: > > class Class: > > ? ? def self.method(arguments): > > ? ? ? ? etc, etc > > > In other words def method(self, arg1, arg2 ,argN) becomes-> ?def > > self.method(arg1, arg2 ,argN) > > Did you bother to check the group? You would've noticed it's being > discussed -right now-:http://groups.google.com/group/comp.lang.python/browse_frm/thread/a5f... > > And this -exact- suggestion has been turned down by Guido:http://mail.python.org/pipermail/python-3000/2006-April/000793.html alex thank you very much! I searched excessively python mailing list but unforurtunately I was using as query and I missed it, although I knew it should had been there. I mostly found threads insisting on a complete removal... And I sincerely apologise for missing the discussion here, I was tired digging python old mailing list. :D. Lot of thanks again, that's what I wanted to find, arguments against it, I was aware I wan not speaking of sth new. From ethan at stoneleaf.us Wed Jul 30 04:49:55 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 30 Jul 2008 00:49:55 -0800 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> Message-ID: <48902B33.3010205@stoneleaf.us> Carl Banks wrote: > On Jul 29, 6:42 pm, Matthew Fitzgibbons wrote: >> I don't have any postable code (it's in a half way state and I haven't >> touched it for a while), but I'll see if I can't find the time to bang >> something up to give you the gist. > > I wouldn't bother at this point. I was looking to see if someone > could come up with something to disprove my belief on the polymorphic > uselessness of "if x" relative to explicit tests, and if (as I > anticipated) they did not, I could claim that "if x" is really just a > glorified keystroke saver. But I now realize that the failure of this > bunch doesn't prove anything. I don't think most people even realize > why answering the question I asked would demonstrate the usefulness of > "if x". > > Your example isn't exactly the smoking gun I was looking for, but I > guess we'll have to admit that at least one usage will suffer for not > having it. > > Carl Banks Even for those that did realize, and in fact hoped that that is what you were attempting to accomplish, it was still quite frustrating to see you ignoring all the non-code, yet perfectly valid examples of why "if x" was not only valid, but the most pythonic[1] way to get the task done. I think it would have been a better discussion if you had responded with reasons why, and not just parroted the "show me the code!" line over and over and over and ... It seemed as if you thought you were the professor, impatiently trying to teach a class full of idiots by playing the devil's advocate. I was sure hoping someone would get the actual code example and post it, partly because I enjoy learning, but mostly because it would (hopefully) shut you up and move the conversation along. In fact, somebody did post some code about a custom matrix class, where __len__ was useless, and still you kept on with... pah. It's late, so before I say something stupid I'll finish this. My last thought on the matter -- up until this thread I had looked forward to your posts, Carl. I think you did more damage than good to yourself with this stunt. ~Ethan~ [1] by pythonic I mean using the features of the language that make sense. In this case, the __nonzero__ function to have the object in question tell us whether or not it's empty. This seems so basic (the __nonzero__ function, that is, and its purpose) -- do you really need code to prove it to yourself? From raghavendra.gv.vanam at gmail.com Thu Jul 10 08:00:39 2008 From: raghavendra.gv.vanam at gmail.com (vanam) Date: Thu, 10 Jul 2008 05:00:39 -0700 (PDT) Subject: Graphics Message-ID: hi all i am new to python programming a beginner. I Came to know from the groups that "How to think like a computer scientist" is preferable for begineers. i just looking through that i came to one section where a sample program for generation of graphics is present.i tried to copy the same script to the interpreter and it is showing an error i want to know whether is there anything that has to be installed in addition to python 2.5 below is the program from gasp import * begin_graphics() Circle((200, 200), 60) Line((100, 400), (580, 200)) Box((400, 350), 120, 100) end_graphics() From jonas.esp at googlemail.com Sat Jul 12 15:04:41 2008 From: jonas.esp at googlemail.com (Kless) Date: Sat, 12 Jul 2008 12:04:41 -0700 (PDT) Subject: SQLAlchmey - new data types for PostgreSQL Message-ID: It would be very interesting if the python community could to access since SQLAlchemy to more features of the PostgreSQL 8.3 RDBMS powerful, as are any new data types as: enumerated (ENUM) [1], XML [2], Universally Unique Identifiers (UUID) [3], and monetary [4]. For if anybody is interested on add them, see here: [5] [1] http://www.postgresql.org/docs/8.3/static/datatype-enum.html [2] http://www.postgresql.org/docs/8.3/static/datatype-xml.html [3] http://www.postgresql.org/docs/8.3/static/datatype-uuid.html [4] http://www.postgresql.org/docs/8.3/static/datatype-money.html [5] http://www.sqlalchemy.org/docs/05/sqlalchemy_databases_postgres.html http://www.sqlalchemy.org/trac/browser/sqlalchemy/trunk/lib/sqlalchemy/databases/postgres.py From sjmachin at lexicon.net Tue Jul 29 19:52:25 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 29 Jul 2008 16:52:25 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> Message-ID: <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> On Jul 30, 3:53 am, william tanksley wrote: > To ask another way: how do I convert from a file:// URL to a local > path in a standard way, so that filepaths from two different sources > will work the same way in a dictionary? > > Right now I'm using the following source: > > track_id = url2pathname(urlparse(track_id).path) > > url2pathname is from urllib; urlparse is from the urlparse module. > > The problems occur when the filenames have non-ascii characters in > them -- I suspect that the URLs are having some encoding placed on > them that Python's decoder doesn't know about. WHAT problems? WHAT non-ASCII characters?? Consider e.g. # track_id = url2pathname(urlparse(track_id).path) print repr(track_id) parse_result = urlparse(track_id).path print repr(parse_result) track_id_replacement = url2pathname(parse_result) print repr(track_id_replacement) and copy/paste the results into your next posting. From grante at visi.com Mon Jul 14 12:20:59 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 14 Jul 2008 11:20:59 -0500 Subject: Using McMillan Installer, PyInstall or py2exe cross-platform? References: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> Message-ID: On 2008-07-14, Hartmut Goebel wrote: > has anybody used McMillan Installer, PyInstall or py2exe cross-platform? I know that py2exe doesn't work "cross-platform". I'd be very surprised if the the others do. > I have a Windows partition with Python installed there, so > this would "only" required working on a different directory > and for a different OS. Since I'm working on Linux, it's awful > to boot Windows each time I want to build a new release. > > Any hint in this area? You can run Windows on a VM like Qemu and use that to build distribution packages. You still have to "boot windows", but at least you don't have to shut down Linux... -- Grant Edwards grante Yow! Here I am at the flea at market but nobody is buying visi.com my urine sample bottles ... From bj_666 at gmx.net Wed Jul 23 10:11:41 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 23 Jul 2008 14:11:41 GMT Subject: Python Written in C? References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> Message-ID: <6eosgtF7u58sU1@mid.uni-berlin.de> On Wed, 23 Jul 2008 14:10:22 +0200, mk wrote: > Marc 'BlackJack' Rintsch wrote: >> I can't even remember when I deleted something from a list in the past. > > Still, doesn't that strike you as.. workaround? No, I find it actually safer; I don't have to care where modifications of the list might be seen elsewhere in the program. Ciao, Marc 'BlackJack' Rintsch From mach.elf at gmail.com Wed Jul 2 18:07:12 2008 From: mach.elf at gmail.com (Pete Kirkham) Date: Wed, 2 Jul 2008 23:07:12 +0100 Subject: C++ or Python In-Reply-To: References: Message-ID: 2008/6/29 Dan Stromberg : > > On Sun, 29 Jun 2008 11:20:45 +0200, Sebastian \"lunar\" Wiesner wrote: > > > Dan Stromberg : > > > >> things like passing a method as a function parameter is a no-brainer > >> (requires extra syntax in java because of the cautious type system - > >> not sure about C++). > > > > C++ has function pointers and functors, therefore this is not really an > > issue with C++. > > Based on http://en.wikipedia.org/wiki/ > Function_object#Functors_in_C_and_C.2B.2B it looks like there's no > special syntax in the language core, but programs needing to pass an > object as though it were a function (for example) do need to add some > extra lines of code for each object needing such treatment. That's a slightly different case - creating a functor in C++ is more equivalent to making a Python object callable. Both require you to add a specially named method to the class - "__call__" or "operator()". The syntax for the pointer to the member function Bar of class Foo is "&Foo::Bar", which is the same as taking a pointer to anything else in C++. The standard C++ library also has functions which take a pointer to a member function and return a functor which can be used to call the member function on an instance. (Whether passing the pointer as an unbound method works correctly with functions which expect a reference to a functor is compiler dependent, so is discouraged in portable code) So it's quite easy to pass an unbound method in C++ - the only extra line of code is #include. The disadvantage is that member function pointers mostly behave like functors, except when they don't, so there's more cognitive load. What is a lot easier in Python is to pass a bound method as a first-class function - you just use "instance.method_name" - but in C++ there isn't a standard library function that takes an object reference and a member function pointer and returns a functor bound to that member. In the absence of automatic memory management, you have to ensure the instance lifecycle exceeds the functor lifecycle, and the standard library avoids making design decisions about lifecycles of objects it doesn't create. From grante at visi.com Tue Jul 29 11:46:14 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 29 Jul 2008 10:46:14 -0500 Subject: Is it allowed to use function results as default arguments ? References: <488E2BF1.8020003@gmail.com> Message-ID: On 2008-07-29, Stef Mientki wrote: > brings me to one other question: > I guess this function is only evaluated once, is that correct ? Yes. > about '.' being the current directory, well I think windows > was thrown at the market about 25 years ago, and since then we > don't use '.' anymore ;-) Who's "we"? I stull use "." as the current directory. -- Grant Edwards grante Yow! Mary Tyler Moore's at SEVENTH HUSBAND is wearing visi.com my DACRON TANK TOP in a cheap hotel in HONOLULU! From python at bdurham.com Fri Jul 25 02:13:44 2008 From: python at bdurham.com (python at bdurham.com) Date: Fri, 25 Jul 2008 02:13:44 -0400 Subject: Questions on 64 bit versions of Python Message-ID: <1216966424.4685.1265275245@webmail.messagingengine.com> Background: I'm going to be processing some raw transaction logs that are 30G in size. As part of this processing I may need to create some very large dictionary structures. I will be running my scripts on a version of Windows 2003 Server Enterprise Edition that supports 16G of RAM. Yes, I could use a database in place of dictionaries, but I'm looking for maximum performance. The following page lists two 64 bit versions of Python for Windows: http://www.python.org/download/releases/2.5.2/ For Win64-Itanium users: python-2.5.2.ia64.msi For Win64-AMD64 users: python-2.5.2.amd64.msi 1. It looks like the 64 bit versions of Python for Windows are CPU vendor specific, eg. it doesn't look like there's a single, universal executable for Windows 64 bit platforms. Is this true? 2. Are there limitations to the using the 64 bit versions of Python? I seem to remember reading that many 3rd party modules (especially Windows OS specific modules) may not be compatible with the 64 bit versions of Python for Windows. 3. If I wanted to run a 64 bit version of Python under Linux, would I need to recompile from source on 64 bit version of Linux or do 64 bit versions of Linux automatically ship with 64 bit versions of Python? (Any recommendations on a flavor of 64 bit of Linux for the Intel architecture would be appreciated) 4. Is there a stable version of IronPython compiled under a 64 bit version of .NET? Anyone have experience with such a beast? Thank you, Malcolm From mail at timgolden.me.uk Thu Jul 10 09:50:27 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 10 Jul 2008 14:50:27 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) In-Reply-To: References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: <487613A3.8020603@timgolden.me.uk> Bill Davy wrote: > I'm not sure OL2003 can read news. I think perhaps some later OL can (added > tot he View menu, perhaps?). So I use OL Express to read news. The OL with > which I wish to communicate is: > > Application name Outlook > Version 11.0 > Build 8217 > Product ID 70141-700-0350904-56905 > Language English (United States) > Application Path C:\Program Files\Microsoft Office\OFFICE11\ > System Language English (United Kingdom) > Mail Support Not Available > Current folder Inbox > Current item Not Available Where did you get to with this, Bill? I wasn't sure if no news was good news or whether you'd gone a different way, or were still trying things... TJG From fredrik at pythonware.com Thu Jul 17 05:09:24 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 11:09:24 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) In-Reply-To: <0T56pitfI5raNv8%stesch@parsec.no-spoon.de> References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> <0T56p3tmInifNv8%stesch@parsec.no-spoon.de> <6e7v9qF5q74kU1@mid.uni-berlin.de> <0T56pitfI5raNv8%stesch@parsec.no-spoon.de> Message-ID: Stefan Scholl wrote: > And by the way: The quote was changed by deleting something on > the same line: > > "June 2008 is a bit too early. Django isn't ready." > > vs. > > "Django isn't ready." Is this a language issue? That you meant to write "django 1.0 isn't done" (as in "completed; finished") but accidentally wrote "django isn't ready" (where "ready" is usually read as "completely prepared or in fit condition for immediate action or use")? (and the "stable release" and "much will change" stuff is pure FUD, of course. what competing project will I find if I google your name?) From mail at timgolden.me.uk Wed Jul 9 08:58:12 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 09 Jul 2008 13:58:12 +0100 Subject: Newbie question In-Reply-To: <3b1e6f480807090552m51be62a9tbb76085504e5d4e3@mail.gmail.com> References: <3b1e6f480807082337l419fd40ax91eaf13e0701c5b3@mail.gmail.com> <3b1e6f480807090552m51be62a9tbb76085504e5d4e3@mail.gmail.com> Message-ID: <4874B5E4.7000400@timgolden.me.uk> |e0 wrote: > I did not mean to use WMI on linux, but query win machines *from* linux. > Thank you for your clarifications In principle you ought to be able to use some kind of DCOM bridge (since WMI access if via COM/DCOM). I've no idea if anyone's attempted this or even if all the pieces are in place. If this won't fly, it should be simple enough to use one of the many, many RPC-ish mechanisms, whether all-Python or otherwise, to call into a WMI proxy service you could run on the chosen Windows boxes. TJG From maric at aristote.info Wed Jul 30 14:22:20 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 30 Jul 2008 20:22:20 +0200 Subject: Standard module for parsing emails? In-Reply-To: <6fbmilFanjibU1@mid.uni-berlin.de> References: <6fbmilFanjibU1@mid.uni-berlin.de> Message-ID: <200807302022.21390.maric@aristote.info> Le Wednesday 30 July 2008 19:25:31 Diez B. Roggisch, vous avez ?crit?: > Maric Michaud wrote: > > Le Wednesday 30 July 2008 17:55:35 Aspersieman, vous avez ?crit?: > >> For parsing the mails I would recommend pyparsing. > > > > Why ? email module is a great parser IMO. > > He talks about parsing the *content*, not the email envelope and possible > mime-body. Yes ? I don't know what the OP want to do with the content, but if it's just filtering the lines begining with a '>', pyparsing might be a bit overweighted. -- _____________ Maric Michaud From half.italian at gmail.com Wed Jul 23 15:22:42 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 23 Jul 2008 12:22:42 -0700 (PDT) Subject: Doubt References: Message-ID: On Jul 23, 7:51?am, ???????? wrote: > Friends > > I am a Perl programmer new to Python. I have a small doubt. > How to convert the perl notation > $a = ""; expression in Python ? > > How to represent the loop > for ($a = $b; $a<=$c;$a++){ > > } in Python > > Jagan > Linguist On most occasions you don't need to use the incrementing loop behavior. Lists are the main data structure comparable to an array, and you can iterate over them without using a counter. If you have: aList = [1, 2, 3] you can do for item in aList: print item Hope this helps. ~Sean From M8R-yfto6h at mailinator.com Mon Jul 21 10:09:13 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Mon, 21 Jul 2008 07:09:13 -0700 Subject: imported module no longer available References: Message-ID: <8qmdnYkOPPAVBRnVnZ2dnUVZ_rCdnZ2d@comcast.com> "Jeff Dyke" wrote in message news:mailman.406.1216648575.922.python-list at python.org... > I've come across an error that i'm not yet able to create a test case > for but wanted to get see if someone could shed light on this. > > I have imported a module at the top of my file with > import mymodulename > > this module is used many times in the current file successfully, but > then I attempt to use it one more time and get: UnboundLocalError: > local variable 'mymodulename' referenced before assignment > > if i add `print globals().keys()` right before the line where the > error occurs l see the module in the list (actual output, names > changed to protect the innocent) > ['HPADao', 'RDao', 'DriverBase', 'FKSUtility', 'PMDao', > 'mymodulename', 'IDriver', 'DriverTrack', 'HPPDao', 'setLogName', > 'HPDao', 'iparser', '__builtins__', '__file__', 'driver', '_LOGNAME', > 'sys', 'IClient', '__name__', 'copy', 'types', 'logging', 'iloader', > 'HPADao', '__doc__', 'PMDao', 'time', 'FormatLoad'] > Traceback (most recent call last): > File "testunbound.py", line 475, in > driver.getRData('0605', 22528) > File "testunbound.py", line 256, in getRData > print mymodulename > > the code that generates these two lines is: > print globals().keys() > print mymodulename > > I can solve this by placing > import mymodulename again in this method, but can't have that everywhere. > > I will try to come up with a generic reproduction of this issue, but > that might take some time. I've also seen this in the past with the > python builtin 'sys' > I did see a bug http://bugs.python.org/issue2378, which has very > similar behaviour, but is different. > > Python 2.5, ubuntu hardy > > Thanks for any insight, > Jeff That error will occur if somewhere in a function or method you accidently assign another value to a global variable, without declaring it with the global keyword first, even if it occurs later in the function. Example: import os print os.getcwd() def func(): print globals().keys() print os os=1 func() OUTPUT: c:\ ['__builtins__', '__file__', 'func', '__name__', 'os', '__doc__'] Traceback (most recent call last): File "C:\dev\python\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 414, in ImportFile exec codeObj in __main__.__dict__ File "", line 1, in File "test.py", line 10, in func() File "test.py", line 7, in func print os UnboundLocalError: local variable 'os' referenced before assignment Check in the function that caused the error to see if later in the code the module name is being used as a local variable. --Mark From norseman at hughes.net Tue Jul 15 14:43:18 2008 From: norseman at hughes.net (norseman) Date: Tue, 15 Jul 2008 11:43:18 -0700 Subject: Testing for Internet Connection In-Reply-To: References: <18460572.post@talk.nabble.com> <1216113021.24038.0@proxy02.news.clara.net> Message-ID: <487CEFC6.2080406@hughes.net> Grant Edwards wrote: > On 2008-07-15, Alexnb wrote: > >> What exactly do you think will work? I am not sure what you >> think I should do? If I use urlopen("http://www.google.com") >> and I am not connected, I am not going to get an exception, >> the program will fail. > > Bullshit. You get an exception. Here's my program: > > import urllib2 > try: > con = urllib2.urlopen("http://www.google.com/") > data = con.read() > print data > except: > print "failed" > > If I run it with no internet connection, I get this: > > $ python testit.py > failed > > If I bring up the internet connection, then I get a bunch of > HTML. > ============================= Yep -me two Process: copy/paste into afile slide lines left to create proper indent values save python afile I get same as Grant If one does a copy/paste into interactive Python, it does fail. (Lots of indent error messages. After all, it is Python :) Steve norseman at hughes.net From davidreynon at gmail.com Mon Jul 7 11:26:05 2008 From: davidreynon at gmail.com (korean_dave) Date: Mon, 7 Jul 2008 08:26:05 -0700 (PDT) Subject: win32com extension documentation/API Message-ID: <996ff65c-8611-483e-90d6-3cf73b9e1496@25g2000hsx.googlegroups.com> Hi. Where can i find the API for this extension? Sourceforge only has downloads. Python has stopped supporting the upkeep of the versions. Thanks. From robert.kern at gmail.com Mon Jul 28 18:56:08 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 28 Jul 2008 17:56:08 -0500 Subject: derivative in numpy In-Reply-To: References: Message-ID: knielsen73 at gmail.com wrote: > Hi, > > I am looking to do a simple derivative. I would expect such a function > to be available in numpy, but can't find it. I have written my own, > but just curious if anybody knows of such function in numpy. numpy.diff() handles the discrete difference. All you need to do is supply the scaling factor(s) to interpret it as a derivative. Again, numpy questions are best asked on the numpy mailing list. http://www.scipy.org/Mailing_Lists -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sjmachin at lexicon.net Mon Jul 7 18:30:08 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 7 Jul 2008 15:30:08 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <6deq2uF21vo2U1@mid.uni-berlin.de> <9b841be4-cd9c-4782-8498-55f053cdbb71@x41g2000hsb.googlegroups.com> Message-ID: <5ee3cbcd-22c1-41d9-97c6-b47655a04570@w7g2000hsa.googlegroups.com> On Jul 8, 2:51 am, Henning Thornblad wrote: > When trying to find an alternative way of solving my problem i found > that running this script: > > #!/usr/bin/env python > > import re > > row="" > for a in range(156000): > row+="a" > print "How many, dude?" > print re.search('/[^ "=]*',row) (the / has moved) > > wouldn't take even a second (The re.search part of course) > > This is for me very strange since this, > in theory, is the same problem as before. In theory. In practice, it is the same problem *iff* you start at the end of the text and work backwards. Your original pattern can be characterised as X*Y, where X and Y are character classes; your new one is YX*. You are asking each to search a text that contains many Xs and no Ys. The second pattern will cause a naive search engine to examine each character in the text (is it a Y?) as a candidate for the start of a successful match; each test fails, and the whole expedition has cost O(N). OTOH, the first pattern will start at offset 0, cheerfully cruising past all those lovely Xs, but failing (no Y) at the end of the text. It will then think that it's been too greedy, reduce the matched span of X* from N characters to N-1, fail to find Y, N-2, fail, ... so that's O(N**2) just for the first trial starting from offset 0. Being naive, it will try again starting from offset 1, 2, 3, ... an O(N**3) process. If you were to tell us what you are actually trying to do, we could probably help you with a faster method. BTW, if the text is 'aaa///bbb///ccc', your original search will find 'aaa///bbb///'; if you want it to find 'aaa/', the pattern should be: '[^ "=/]*/' Cheers, John From xahlee at gmail.com Sun Jul 6 04:05:09 2008 From: xahlee at gmail.com (xahlee at gmail.com) Date: Sun, 6 Jul 2008 01:05:09 -0700 (PDT) Subject: Elisp Lesson on file processing (make downloadable copy of a website) References: Message-ID: In this week i wrote a emacs program and tutorial that does archiving a website for offline reading. (See http://xahlee.org/emacs/make_download_copy.html ) In the process, i ran into a problem with the unix ?cp? utility. I've been a unix admin for Solaris during 1998-2004. Even the first time i learned about cp, i noticed some pecularity. But only today, i thought about it and wrote it out exactly what's going on. Here's a excerpt from my emacs tutorial above regarding the issue. ------------------ Copying a bunch of directories seems a trivial operation, but it actually took me a couple hours to arrive at the final code, due to the exact requirement of directory paths, and the unix ?cp? tool's lack of precision and flexibility. Originally, i thought the code would be something simple like several ?(shell-command (concat "cp -R " fromDir " " toDir))?, one for each source dir, where fromDir and toDir are full paths. However, it turns out the problem is slightly more complex. Suppose the source dir is ?/Users/xah/web/emacs? and dest dir is ?/ Users/xah/web/diklo/xahtut/emacs? and i want all branches under the source dir copied into the dest dir. If you do ?cp -R /Users/xah/web/emacs /Users/xah/web/diklo/xahtut/ emacs? with both xahtut and xahtut/emacs doesn't exist, then this error results: ?cp: /Users/xah/web/diklo/xahtut/emacs: No such file or directory?. If you do ?cp -R /Users/xah/web/emacs /Users/xah/web/diklo/xahtut/ emacs? with xahtut/emacs exists, then you got ?/Users/xah/web/diklo/ xahtut/emacs/emacs?, which is not what i want. If you do ?cp -R /Users/xah/web/emacs /Users/xah/web/diklo/xahtut? with xahtut doesn't exist, it results in all branches of emacs in xahtut, which is wrong. Only when you do ?cp -R /Users/xah/web/emacs /Users/xah/web/diklo/ xahtut? with xahtut exists, you get the correct result with the new dir ?/Users/xah/web/diklo/xahtut/emacs? having all branches of the original dir. So, the solution is to first create all the parent dirs of the dest dir, but without the dest dir node itself. Then, do a cp to the first parent of dest dir. Directories are abstractly a tree. Copying directories is like grafting a tree from one branch into another branch. To begin, we are given two spec: the source node and a destination node. The source node by definition is a existing node (i.e. existing dir or file), otherwise the copying won't make sense. However, the destination spec can be a node that doesn't exist, or its parents doesn't exist, or several levels of parents doesn't exist. When the destination spec has missing nodes, we can consider creating them as part of the grafting process, or we can consider it as a error. The unix ?cp? tool's behavior is mathematically inconsistent. When the destination node exist, the source node will become new children of destination node. When the destination node does not exist (but its parent exists), ?cp? will create the node, and copy only the children of the source node to it. When the destination node doesn't exist and its parent doesn't exist neither, then ?cp? considers it a error. --------------- Related readings: ? The Nature of the ?Unix Philosophy? http://xahlee.org/UnixResource_dir/writ/unix_phil.html Xah ? http://xahlee.org/ ? From ben at benfinney.id.au Thu Jul 10 21:59:27 2008 From: ben at benfinney.id.au (Ben Finney) Date: Fri, 11 Jul 2008 11:59:27 +1000 Subject: Python 3.0 and removal of the 'string' module Message-ID: <87wsjtqiyo.fsf@benfinney.id.au> Howdy all, The Python wiki page states on its page for Python 3.0 , in the section for "Standard Library Changes" , that the 'string' module is to be removed. It references PEP 4 , which has nothing to say about the status of the 'string' module. Further, the 'string' module has existing functionality (the Template class, the character sets 'whitespace' etc.) that, to my knowledge, has no replacement in Python 3.0. Can anyone see a reason to believe the above wiki page's statement about the 'string' module being removed? More to the point, can anyone see a reason why that statement should remain on that page? -- \ ?Ours is a world where people don't know what they want and are | `\ willing to go through hell to get it.? ?Donald Robert Perry | _o__) Marquis | Ben Finney From tjreedy at udel.edu Sat Jul 26 17:17:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 17:17:09 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87fxpxw0ku.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> Message-ID: Torsten Bronger wrote: > Hall?chen! > > Terry Reedy writes: > >> [...] >> >> Or the proposal would have to be that 'self' is mandatory for all >> programmers in all languages. I think *that* would be >> pernicious. People are now free to write the more compact 's.sum = >> s.a + s.b + s.c' if they want instead of the 'self' version. And >> again, not everyone writes in English. > > Of course, "self" would have to become a reserved word. You could > say that this may break some code, Will break. > but I don't see much freedom removed from the language. > After all, being a German, I still can't > write "F?r i in range(10)". ;-) But you can write 'for ubermenchen in range(10):' and in 3.0, with diacritics added. Would you really feel no loss of freedom if Guido make i0, i1, ... into keywords, which means they could not be used elsewhere, and mandated them as for loop index variables? From duncan.booth at invalid.invalid Mon Jul 28 09:11:22 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Jul 2008 13:11:22 GMT Subject: Module clarification References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> <896c547e-9fa1-4f84-8c9b-53a96e70246c@y21g2000hsf.googlegroups.com> <00c033b9-1b5a-4165-abec-4ff6119298a5@z66g2000hsc.googlegroups.com> Message-ID: Hussein B wrote: > If I have a couple of modules, is there a way to package them? or > there is no such a thing in Python? > > It sounds rather as though you haven't yet gone through the Python tutorial. You really should read it, even if you just skim through it to see what topics are covered. The tutorial explains both modules and packages: http://docs.python.org/tut/node8.html What it doesn't cover is that you can import modules or packages directly from a zip file. Then read about eggs. -- Duncan Booth http://kupuguy.blogspot.com From jazle at nospam.log.web.id Tue Jul 22 00:23:48 2008 From: jazle at nospam.log.web.id (Jaimy Azle) Date: Tue, 22 Jul 2008 11:23:48 +0700 Subject: Python Embedding Thread References: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> <87bf413d-eb98-47c0-8466-237c45fd1a0e@e53g2000hsa.googlegroups.com> Message-ID: "Benjamin" wrote: > Two threads should not be running through the Python VM concurrently > in the same process. The GIL has to be held *any* time you use the > Python API. When you want to release the GIL (to process something in > C), use PY_BEGIN_ALLOW_THREADS and > PY_END_ALLOW_THREADS around the > places where threads can run. I think he is trying to call python from thread, according to the documentation: "Beginning with version 2.3, threads can now take advantage of the PyGILState_*() functions to do all of the above automatically." - http://docs.python.org/api/threads.html I use it everywhere on my multithreaded server without problem. Salam, -Jaimy From Russ.Paielli at gmail.com Mon Jul 28 21:32:09 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jul 2008 18:32:09 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> <488e3520$0$16766$426a74cc@news.free.fr> <87myk1iknc.fsf@benfinney.id.au> Message-ID: <1d71bcce-2e82-4b8f-9ac6-f729fea634eb@z26g2000pre.googlegroups.com> On Jul 28, 5:44 pm, Ben Finney wrote: > Bruno Desthuilliers writes: > > Boy, I don't know who you think you're talking to, but you're > > obviously out of luck here. I'm 41, married, our son is now a > > teenager, I have an happy social life, quite a lot of work, and no > > time to waste in the streets. And FWIW, name-calling won't buy you > > much here. > > It has, at least, long ago bought him a place in my kill-file. Seeing > your side of the conversation, I can only confirm that decision as > correct. Now there's a classic reply from another comp.lang.python regular. All he needs is one side of the conversation to know what's going on! I'd really like to know where both of you guys find the time to spend here, because unless you type extremely fast, I figure it's about 10-20 hours per week every week. Sorry, but if you also have "quite a lot of work," I don't believe that leaves much time for a "happy social life." Each and every time I get involved in an extended discussion about Python here, I end up realizing that I've wasted a lot of time trying to reason with unreasonable people who are infatuated with Python and incapable of recognizing any deficiencies. I will thank you for one thing. By taking your best shot at my suggestion and coming up with nothing significant or relevant, you have given me confidence to go ahead with a PEP. I may just do it. If it is rejected, then so be it. Unlike you, they will have to give me a valid reason to reject it. From mattheww at chiark.greenend.org.uk Tue Jul 29 16:15:12 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 29 Jul 2008 21:15:12 +0100 (BST) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8d Message-ID: Steven D'Aprano wrote: > "if x" is completely type agnostic. You can pass an object of any type to > it, and it will work. (Excluding objects with buggy methods, naturally.) There are many circumstances where if a parameter is None I'd rather get an exception than have the code carry on with the 'empty container' branch (and silently give me a meaningless result). -M- From pavlovevidence at gmail.com Wed Jul 30 00:45:40 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 21:45:40 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> <7f4a3d37-e551-4e21-b660-3618016cb67b@z6g2000pre.googlegroups.com> Message-ID: <68448887-4736-4af9-9f27-837bb5312cbd@o40g2000prn.googlegroups.com> On Jul 30, 12:22 am, Erik Max Francis wrote: > Carl Banks wrote: > > That's not what I was asking for. I was asking for a use case for "if > > x" that can't be replaced by a simple explicit test. Your example > > didn't satisfy that. > > It's a completely artificial request. Bull. This is a request, that, if satisfied, would prove that "if x" is more polymorphic than a simple explicit test. I posed the question precisely to see if anyone could come up with a use case that shows this benefit of "if x". > "if x" _is_ a completely simple > test. Simpler, in fact, than the ones you were advocating. It's not explicit. Here's what we know for sure. 1. "if x" uses fewer keystrokes than an explicit test 2. "if x" creates fewer nodes in the parse tree than an explicit test 3. Couple minor things we somehow managed to uncover in this thread Is that it? Is that all the benefits of "if x"? This is what I want to establish. A bunch of people in this thread are crowing that it helps polymorphism, but I have only seen minor examples of it. I've explained why I doubt that it helps polymorphism that much: you almost never see code for which an integer and list both work, so having the ability to spell a test the same way for both types isn't useful. If you claim that "if x" does help polymorphism, please tell me what's wrong with the above analysis. Or just give me the use case I asked for. Carl Banks From jkrukoff at ltgc.com Mon Jul 28 18:10:13 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Mon, 28 Jul 2008 16:10:13 -0600 Subject: seemingly simple list indexing problem In-Reply-To: References: Message-ID: <1217283013.4123.98.camel@jmk> On Mon, 2008-07-28 at 16:24 -0500, Ervan Ensis wrote: > My programming skills are pretty rusty and I'm just learning Python so > this problem is giving me trouble. > > I have a list like [108, 58, 68]. I want to return the sorted indices > of these items in the same order as the original list. So I should > return [2, 0, 1] > > For a list that's already in order, I'll just return the indices, i.e. > [56, 66, 76] should return [0, 1, 2] > > Any help would be appreciated. > > -- > http://mail.python.org/mailman/listinfo/python-list If your lists aren't so large that memory is an issue, this might be a good place for a variation of decorate, sort, undecorate. >>> listToSort = [ 108, 58, 68 ] >>> decorated = [ ( data, index ) for index, data in enumerate( listToSort ) ] >>> decorated [(108, 0), (58, 1), (68, 2)] >>> result = [ None, ] * len( listToSort ) >>> for sortedIndex, ( ignoredValue, originalIndex ) in enumerate( sorted( decorated ) ): ... result[ originalIndex ] = sortedIndex ... >>> result [2, 0, 1] -- John Krukoff Land Title Guarantee Company From jordanrastrick at gmail.com Thu Jul 24 04:11:47 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 01:11:47 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> Of course not. I just think Explicit is better than Implicit is taken seriously by a large segment the Python community as a guiding principle, and overall its influence does more harm than good. Clearly self being in every argument list was a decision arrived at long before the Zen was ever coined. Its merely an example of what I feel is a shortcoming in the conventional 'pythonic' approach to thinking about problems. The reluctance to admit that the __eq__ behaviour is a poor design choice is further evidence; its something (unlike self) that quite conceivably could be changed, and should be changed, but its somehow seen (by certain people) as the way that Python should do things. From paul at subsignal.org Tue Jul 15 05:37:57 2008 From: paul at subsignal.org (paul) Date: Tue, 15 Jul 2008 11:37:57 +0200 Subject: FOSS projects exhibiting clean/good OOP? In-Reply-To: <3bd416cf-6989-44fb-961d-658032231356@m73g2000hsh.googlegroups.com> References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> <3bd416cf-6989-44fb-961d-658032231356@m73g2000hsh.googlegroups.com> Message-ID: Phillip B Oldham schrieb: > Thanks all - lots to go through there! :D > > I'd heard previously that Trac was a nice example, or rather its core > was, but I'd also heard that there were lots of problems with it and > that they were redeveloping it from scratch? They continually improve parts of it, but I don't know of any severe problems whatsoever. Yes people are moaning about lack of multi-project support but that was a design decision way back. From a programming POV, I highly recommend looking at the source. The component model looks simple but is very powerful. It's also a good example how code benefits from interfaces wrt. structuring and documentation. cheers Paul From fredrik at pythonware.com Wed Jul 16 09:55:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 15:55:13 +0200 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: Ken Hartling wrote: > Thanks .. but I want to find out if the system is "running on 64bit" > even when the interpreter is a 32-bit build executable ("what python > was built on"). platform.architecture() and platform() in general > seems to only be looking at the build executable You can pass in an arbitrary binary to architecture(), so I guess you could use this on some suitable thing under "/bin" on a Unix box. This doesn't work on Windows, though. In this message, http://mail.python.org/pipermail/python-list/2005-June/326158.html Thomas Heller suggests using ctypes to call the Windows API directly; so something like this could work: >>> import ctypes, sys >>> i = ctypes.c_int() >>> kernel32 = ctypes.windll.kernel32 >>> process = kernel32.GetCurrentProcess() >>> kernel32.IsWow64Process(process, ctypes.byref(i)) 1 >>> is64bit = (i.value != 0) >>> is64bit False (IsWow64Process returns a non-zero value if it manages to check the status, and sets the variable to a non-zero value if the process is running under WOW64. I only have 32-bit boxes here, so it's only partially tested). And yes, looks like official support for this might appear in 2.6: http://mail.python.org/pipermail/python-dev/2008-May/079022.html (in that thread, Mark Hammond suggests "'64 bit' in sys.version" as a workaround, but warns for false negatives). From siona at chiark.greenend.org.uk Wed Jul 30 09:07:06 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 30 Jul 2008 14:07:06 +0100 (BST) Subject: Build tool for Python References: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Message-ID: Hussein B wrote: >Apache Ant is the de facto building tool for Java (whether JSE, JEE >and JME) application. >With Ant you can do what ever you want: [ ... ] ... bash your head against your desk for hours trying to make sense of its classloader system, struggle for days on end trying to make it understand building anything outside the Java world, write piles of tedious and often boilerplate XML, wonder what happened to javac's ability to resolve dependencies to make this necessary ... Put it like this, my experience has lead me to regard Ant as a retrograde step compared to make. I can't understand why anyone would want to inflict such a thing on a Python project. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From __peter__ at web.de Fri Jul 18 08:21:55 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 14:21:55 +0200 Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: nicolas.pourcelot at gmail.com wrote: > On 18 juil, 13:13, Peter Otten <__pete... at web.de> wrote: >> nicolas.pource... at gmail.com wrote: >> > In fact, 'any(myobject is element for element in mylist)' is 2 times >> > slower than using a for loop, and 'id(myobject) in (id(element) for >> > element in mylist)' is 2.4 times slower. >> >> This is not a meaningful statement unless you at least qualify with the >> number of item that are actually checked. For sufficently long sequences >> both any() and the for loop take roughly the same amount of time over >> here. >> > > Sorry. I used short lists (a list of 20 floats) and the element > checked was not in the list. > (That was the case I usually deals with in my code.) What is your (concrete) use case, by the way? If you want efficiency you should use a dictionary instead of the list anyway: $ python -m timeit -s"d=dict((id(i), i) for i in range(1000)); x = 1000" "id(x) in d" 1000000 loops, best of 3: 0.275 usec per loop Peter From scottpig1 at comcast.net Sun Jul 27 20:54:26 2008 From: scottpig1 at comcast.net (pigmartian) Date: Sun, 27 Jul 2008 20:54:26 -0400 Subject: ctypes - unloading implicitly loaded dlls Message-ID: (my apologies if this is a repost, but it sure seems like the first attempt disappeared into the ether...) I'm writing a program that uses functionality from two different sets of cdlls which reside in two different directories, call them 'libA.dll' and 'libB.dll'. Although I don't directly use it, both directories contain a dll with the same name, although they aren't in fact identical. Call them, "libC.dll". However, the c-functions I call from the clls I do use seem to implicitly use "libC.dll". The problem that occurs after I load one dll and call functions in it, when I try to load the second dll I get windows errors because the second dll tries to call a function in its version of libC.dll, but it finds the version meant for libB.dll, which doesn't contain that function. Oy, I hope some sample code makes it clearer: def demo(): A = ctypes.cdll.LoadLibrary('/path1/libA.dll') A.foo() # implicitly uses '/path1/libC.dll' _ctypes.FreeLibrary(A._handle) # CRASH! B = ctypes.cdll.LoadLibrary('/path2/libB.dll') # "The procedure entry point some_func could not be located # in the dynamic link library libC.dll.": # libB.dll wants to use code from '/path2/libC.dll', but # instead it finds '/path1/libC.dll' already loaded # in memory, which doesn't # contain the function call it wants. Assuming my understanding of things is correct, then I believe what I need to do is to remove /path1/libC.dll from memory before I try loading libB.dll, but I haven't found any way of doing that. Can anyone offer my some suggestions? Or, am I S.O.L.? Notes: * the two sets of dlls are supplied by a vendor for working with its COTS packages; I don't have any control over the dll names used or the code therein. * If I leave out the call to A.foo(), then I don't crash, but if I leave out the FreeLibrary call as well then I do crash. * I've tried manipulating the PATH before loading the dlls, to no effect. * I've tried del'ing A and running gc.collect() before loading B. Thanks, Scott From jordanrastrick at gmail.com Thu Jul 24 06:24:31 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 03:24:31 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <8233fbfb-ad9b-43ef-b722-9738ef129d0b@q5g2000prf.googlegroups.com> On Jul 24, 8:01?pm, Lawrence D'Oliveiro wrote: > In message > <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, Jordan > wrote: > > > Except when it comes to Classes. I added some classes to code that had > > previously just been functions, and you know what I did - or rather, > > forgot to do? Put in the 'self'. In front of some of the variable > > accesses, but more noticably, at the start of *every single method > > argument list.* > > The reason is quite simple. Python is not truly an "object-oriented" > language. It's sufficiently close to fool those accustomed to OO ways of > doing things, but it doesn't force you to do things that way. You still > have the choice. An implicit "self" would take away that choice. You could still explicitly request non-implicit self on a method by method basis. From rharkins at nettrekker.com Tue Jul 1 17:13:19 2008 From: rharkins at nettrekker.com (Rich Harkins) Date: Tue, 01 Jul 2008 17:13:19 -0400 Subject: Why is recursion so slow? In-Reply-To: References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Message-ID: <486A9DEF.8030004@nettrekker.com> Nick Craig-Wood wrote: [snip] > By definition any function in a functional language will > always produce the same result if given the same arguments, so you can > memoize any function. > Ah, so that's why time.time() seems to be stuck... ;) Rich From abhishekatmanit at gmail.com Wed Jul 2 06:01:36 2008 From: abhishekatmanit at gmail.com (Abhishek Wadhava) Date: Wed, 2 Jul 2008 15:31:36 +0530 Subject: Using Bluetooth Module Message-ID: <6279b7260807020301q534d90f3k47a02079a32a9540@mail.gmail.com> Hi..!! I was thinking to perform bluetooth Communication with Python. So can any1 guide me from where to start...i mean any particular module or library for that, any documentations for that..etc etc... -------------- next part -------------- An HTML attachment was scrubbed... URL: From knielsen73 at gmail.com Wed Jul 23 21:06:50 2008 From: knielsen73 at gmail.com (knielsen73 at gmail.com) Date: Wed, 23 Jul 2008 18:06:50 -0700 (PDT) Subject: fill in 3D array Message-ID: <3180f972-f2d4-43ff-81de-bcdd0a2ef906@59g2000hsb.googlegroups.com> Hi, I am a python newbie, trying to convert my IDL scripts to python. I am kind of stuck at the moment. I am reading in a 1-D data file with 2000 data points. I need to put them in a 3-D array with size [10,10,20]. I have defined the field array as arr = zeros((10,10,20)) but don't know how to read the data into the array. Also, I need to extract a slice of a 3-D array and tried a = array_name(:,:,20) but that didn't work. Thanks, Kim From Nikolaus at rath.org Sat Jul 26 05:08:12 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Sat, 26 Jul 2008 11:08:12 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> Message-ID: <87ljzpt3lv.fsf@nokile.rath.org> Terry Reedy writes: > Nikolaus Rath wrote: >> Terry Reedy writes: >>> Torsten Bronger wrote: >>>> Hall?chen! >>> > And why does this make the implicit insertion of "self" difficult? >>>> I could easily write a preprocessor which does it after all. >>> class C(): >>> def f(): >>> a = 3 >>> >>> Inserting self into the arg list is trivial. Mindlessly deciding >>> correctly whether or not to insert 'self.' before 'a' is impossible >>> when 'a' could ambiguously be either an attribute of self or a local >>> variable of f. Or do you and/or Jordan plan to abolish local >>> variables for methods? >> >> Why do you think that 'self' should be inserted anywhere except in the >> arg list? AFAIU, the idea is to remove the need to write 'self' in the >> arg list, not to get rid of it entirely. > > Because you must prefix self attributes with 'self.'. If you do not > use any attributes of the instance of the class you are making the > function an instance method of, then it is not really an instance > method and need not and I would say should not be masqueraded as > one. If the function is a static method, then it should be labeled > as one and no 'self' is not needed and auto insertion would be a > mistake. In brief, I assume the OP wants 'self' inserted in the body > because inserting it only in the parameter list and never using it > in the body is either silly or wrong. I think you misunderstood him. What he wants is to write class foo: def bar(arg): self.whatever = arg + 1 instead of class foo: def bar(self, arg) self.whatever = arg + 1 so 'self' should *automatically* only be inserted in the function declaration, and *manually* be typed for attributes. Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From cjw at ncf.ca Fri Jul 25 08:12:59 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 25 Jul 2008 08:12:59 -0400 Subject: Autocompletion and Interactive Tables in a Python IDE In-Reply-To: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> References: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Message-ID: Anthony wrote: > Hi, I'm a FoxPro programmer, but I want to learn python before it's > too late. I do a lot of statistical programming, so I import SPSS > into python. In my opinion, the best features of Visual FoxPro 9.0 > were: > a) Intellisense (tells you what classes/methods are available and what > variables go into a function) > b) Code Completion (guesses your code after four letters) > c) Data-Orientation; multiple data sessions can be open, data can be > viewed easily > For Windows users, PyScripter provides a) and b). I don't understand what you are seeking with c). Colin W. From kyosohma at gmail.com Thu Jul 31 11:51:18 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 31 Jul 2008 08:51:18 -0700 (PDT) Subject: Newbie Python questions References: Message-ID: <2a30b583-16e2-41c2-a31a-3e66b1eb5dbc@x41g2000hsb.googlegroups.com> On Jul 29, 12:28?pm, LessPaul wrote: > I recently discovered Python and see it as a great language to use for > personal projects (and more). I made my living for over a decade as a > coder in C, C++, ADA, Fortran, and Assembly before moving to systems > engineering. > > I'm now retired, and would love to code again. I see Python as the > perfect language to get a good program working in a short time. My > question is in regard to GUI platforms. My primary target would be > Windows, but I would also like be able to support Linux and Mac > versions if possible. I'm also interested in using a system that also > has support for pure C++ applications. As such, and after reading many > web pages regarding Python GUIs, I believe I have the candidates > narrowed down to pyQT and wxPython. > > The first question -- how steep is the curve to become proficient with > the above GUI packages? If the answer is "not very" then there is no > need for the following questions as I can try both on for size to see > which I like best. However if it is a sizable investment in time, I'd > like to maximize my efforts and choose the one I'll end up using in > the end. > > The biggest hurdle I can see is the cost of the QT licence for > commercial software, though apparently it can be acquired for a > reasonable price via the BlackAdder package. Does purchasing the > BlackAdder also include the needed software support for C++ > development? Does the BlackAdder purchase also allow for licence of > standard C++ apps? > > Since there appears to be no commercial licencing fee for wxWidgets/ > wxPython, the last question is what do I gain from going QT over wx? > I've seen great applications written with both (on my computer I have > the wxPython Digsby and the pyQT apps "Mnemosyne" and "Anki". All seem > to be solid. Tim forgot to mention that the wxPython user's group is very helpful and fun. I don't know how the pyQT one is. You could try both toolkits just working on some toy projects before you work on anything commercial. Then they're both free! And you can find out which one better suits you. Mike From deets at nospam.web.de Fri Jul 11 07:07:04 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 11 Jul 2008 13:07:04 +0200 Subject: How to serialize and deserialize the objects into memory? In-Reply-To: <0a7ead85-2a38-41a8-98b8-59dede61f985@c58g2000hsc.googlegroups.com> References: <0a7ead85-2a38-41a8-98b8-59dede61f985@c58g2000hsc.googlegroups.com> Message-ID: <6dot6qF3m7fsU1@mid.uni-berlin.de> hardemr schrieb: > Hello Everyone, > > I want to serialize and deserialize the objects into Memory not into > file. How can i do that? Use pickle & module StringIO/cStringIO as file-to-memory-object. Diez From pavlovevidence at gmail.com Wed Jul 30 21:26:30 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 30 Jul 2008 18:26:30 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> <29a131a5-d813-407a-b774-6f90b7f8f3e3@w1g2000prk.googlegroups.com> Message-ID: <78ef923c-3065-4d9e-ad52-f94d91bee920@k13g2000hse.googlegroups.com> On Jul 30, 3:56 am, Erik Max Francis wrote: > Carl Banks wrote: > > I mean in general. I wouldn't spell it like that. I would prefer if > > empty(x), with an __empty__ method. (And support __nonzero__ aka > > __bool__ dropped completely.) > > So your argument is purely about style, then. You just wish it were > written differently. No, you misunderstand and/or misstate my position again. I realize I wasn't as clear as I could have been. First of all it's not my "argument": this is a tangent. There would be a built-in empty, which invokes __empty__, in the same way len invokes __len__. It would only be defined for container types. (Iterators could choose whether to define it and it would mean that the iterator is guaranteed stop on the next iteration. The iterator is free to read and store the item. If the iterator doesn't know whether it will stop, it must not define __empty__ or raise an exception in it.) It would become the One Obvious Way to test for emptiness. __nonzero__ would disappear and not be replaced with anything, and objects would not have implicit boolean conversion. Carl Banks From rocksportrocker at googlemail.com Tue Jul 22 03:05:48 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Tue, 22 Jul 2008 00:05:48 -0700 (PDT) Subject: fromfile error on windows, not mac References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> Message-ID: <9650a33b-40b5-46a7-a05e-5b059117891f@b1g2000hsg.googlegroups.com> jadamwil schrieb: > Hello, > I am using the numpy fromfile function to read binary data from a file > on disk. The problem is that the program runs fine on a Mac, but gives > an error or warning on windows when trying to read the data. I use it > like this: > > Signal = zeros((N, 16), dtype=float32) > for sample in range(0, N): > # this function gets the next position in the file to seek to > s = getFilePos(sample) > > # go to the correct location in the file; this IS checked to make > sure it is within the file > mFile.seek(s) > > # read the 16 float32 values from the file > D = fromfile(mFile, dtype=numpy.float32, 16) > > # save D in Signal > Signal[sample, :] = D > > This will fail when sample is ~4. If I change the range to (5,N), > skipping the "bad" file location, it will run fine for a few samples, > and then give another error. The message it gives is: > "16 items requested but only 7 read" > > So D is a 7x1 vector, and the program dies when it tries to assign D > to the slice of Signal ("ValueError: shape mismatch: objects cannot be > broadcast to a single shape"). > > On windows, the Python version is 2.5.2, and the most recent numpy and > scipy are being used as well. I tried using Enthought, but it gave > this error as well, in addition to a c runtime error whenever I > imported scipy (which is another post topic...). > > Any ideas on what might be causing this? Is there a way to debug the > fromfile function? And, remember, this works perfectly on a Mac. Would > compiling everything (python, scipy, numpy) potentially solve this? Did you open the file in binary mode ? Greetings, Uwe From snowballz.game at gmail.com Sun Jul 20 00:26:32 2008 From: snowballz.game at gmail.com (Michael Lubker) Date: Sat, 19 Jul 2008 23:26:32 -0500 Subject: Any Game Developers here? In-Reply-To: References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: <76b841590807192126r5ed40f55gc48ce7f9e1b423d2@mail.gmail.com> Rabbyt is developed by one of my colleagues. I'm currently using Python-Ogre and Anims (for 3D animation, broken off from Rabbyt by Matthew) for my game, SnowballZ. Thanks Michael On Sat, Jul 19, 2008 at 10:33 PM, Python Nutter wrote: > I used to use PyGame but the horrible delay waiting for OS X binaries > put me off. > > I now use Pyglet extensively, and combine Pyglet + Rabbyt to get > amazing sprite handling speeds. > > Pyglet/Rabbyt make use of OpenGL which comes installed on all the > major systems out there. > > PyGame requires the installation of the SDL library to work so is a > lot larger installation requirement. > > There are two books I know of currently in print on game programming, > both use PyGame as it was out first. One book is horrible and only > worth for cleaning yourself up after you use the bathroom. The second > is really well written (The L express game programming book) and > highly recommended if you need to get some basic game design and > programming under your belt in Python. > > That said its stupidly easy to port examples to work on Pyglet/Rabbyt > so you won't do yourself a dis-service if you want to buy the book but > want to develop later in Pyglet/Rabbyt. > > Cheers, > PN > > P.S. Since you've likely found Pyglet and PyGame already, the only > other reference URL you need is for Rabbyt so go here for that: > http://matthewmarshall.org/projects/rabbyt/ > > > 2008/7/19 Michael Lubker : >> Any people that use Python as the predominant language for their game >> development here? >> >> ~Michael >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > -- ~ "The world hates change, yet it is the only thing that has brought progress." ~ Charles Kettering http://snowballz.joey101.net From gherron at islandtraining.com Thu Jul 10 20:18:09 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 10 Jul 2008 17:18:09 -0700 Subject: Can anyone suggest a date peocedure... In-Reply-To: References: Message-ID: <4876A6C1.3010902@islandtraining.com> RV wrote: > On Thu, 10 Jul 2008 13:39:29 -0700, Gary Herron > wrote: > > > >> The datetime module has what you need. >> >> It has methods (with examples) on building a datetime object from a >> string, and it has a object named timedelta, and the ability to subtract >> a timedelta from a time. >> >> For instance, the time right now and the time exactly one day ago: >> >> >>>>> from datetime import * >>>>> datetime.today() >>>>> >> datetime.datetime(2008, 7, 10, 13, 38, 48, 279539) >> >>>>> datetime.today()-timedelta(1) >>>>> >> datetime.datetime(2008, 7, 9, 13, 38, 50, 939580) >> >> >> Gary Herron >> > > Thanks Gary! This works great. Now all I need to know is how to > plug the date into the datetime object from a string. > Use *strptime*( date_string, format) The format argument uses %-fields to describe how to pull data out of the date_string. It uses the same set of %-fields as the time modules strftime function Gary Herron > Ron > > -- > http://mail.python.org/mailman/listinfo/python-list > From larry.bates at websafe.com` Tue Jul 22 23:40:52 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 22 Jul 2008 22:40:52 -0500 Subject: Python Written in C? In-Reply-To: References: Message-ID: Grant Edwards wrote: > On 2008-07-22, Larry Bates wrote: >> Grant Edwards wrote: >>> On 2008-07-22, Larry Bates wrote: >>> >>>> You talk about "writing it in assembly language for each MPU >>>> chip". Actually it is even better than that. We now have >>>> these modern inventions, called compilers that do that type of >>>> work for us. They translate high level instructions, not >>>> into assembler but into machine language. >>> Actually, all of the compilers I'm familiar with (gcc and a >>> handful of cross compilers for various microprocessors) >>> translate from high-level languages (e.g. C, C++) into >>> assembly, which is then assembled into relocatable object >>> files, which are then linked/loaded to produce machine >>> language. >>> >> I just learned something I did not know. I was under the >> impression that they translated directly to machine code >> without ever actually generating Assembler text files. > > There may indeed be compilers that work that way. On Unix > systems (which is what I work with) compilers have > traditionally generated assembly language files. > >> Seems like a waste to generate the text and turn around run >> that through the assembler, but what do I know. I guess that >> way the compiler can have pluggable assembler back-ends. > > Since you probably need an assembler anyway, generating > assembly-language in the compiler prevents you from having to > duplicate a bunch of object-code-generation code in two places. > I'm not sure I understand what you mean here. The code generation phase of the top level compiler would have to generate assembler mnemonics instead of just generating machine coded directly. At that point it should be just as easy to generate machine code, unless you take advantage of macros, or other helpers provided in the assembly phase. My "compiler" work was way back on mainframes and the ones I worked with definitely didn't produce assembler then needed to be run through the assembler. They created likable objects directly. But that was over 30 years ago! All this may be a moot point, because assembler is just a mnemonic representations of machine language anyway. -Larry From asmodai at in-nomine.org Thu Jul 17 03:48:38 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 17 Jul 2008 09:48:38 +0200 Subject: Instance In-Reply-To: <120cea3a-33a9-49ec-8932-7cef2e5aef17@25g2000hsx.googlegroups.com> References: <120cea3a-33a9-49ec-8932-7cef2e5aef17@25g2000hsx.googlegroups.com> Message-ID: <20080717074838.GI83562@nexus.in-nomine.org> -On [20080717 09:01], karthikbalaguru (karthikbalaguru79 at gmail.com) wrote: >AttributeError : Classroom instance has no attribute 'desk_offset' You are using a Classroom instance and probably assigning something to the instance's variable/attribute 'desk_offset'. Except that the class Classroom has no self.desk_offset. So in your class definition you would need to add something to __init__() like: self.desk_offset = None # or 0 or... -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B A frightened mental vortex we will be, a Sun we seek, a Sun we flee... From gherron at islandtraining.com Tue Jul 22 02:25:10 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 21 Jul 2008 23:25:10 -0700 Subject: string[i:j:k] In-Reply-To: <811e72db-a8bc-475a-b32a-38a9b6922600@k30g2000hse.googlegroups.com> References: <4a9a4cf3-9ef4-4d9e-b714-bbf62b7c1917@v1g2000pra.googlegroups.com> <811e72db-a8bc-475a-b32a-38a9b6922600@k30g2000hse.googlegroups.com> Message-ID: <48857D46.2080905@islandtraining.com> konstantin wrote: > On Jul 22, 9:18 am, alex23 wrote: > >> On Jul 22, 3:10 pm, konstantin wrote: >> >> >>> some_string[i:j:k] >>> What does it mean? >>> >> i = start position, j = end position, k = step size >> >> >>>>> s = "ABABABABABABAB" >>>>> s[0:6:2] >>>>> >> 'AAA' >> >>>>> s = "ABCABCABCABCABC" >>>>> s[0:6:3] >>>>> >> 'AA' >> >> Hope this helps. >> >> - alex23 >> > > Thanks! > It seems that negative step leads in reverse direction. > But logic isn't completely clear for me. > >>>> s = '123456789' >>>> s[::-2] >>>> > '97531' > > but > >>>> s[:-1:-2] >>>> The slice s[:-1] means start at zero and go to n-1(where n-len(s)) (it does not mean start at zero and go to -1) So since the indexing is counting upward, the step size had better be positive. Thus: >>> s = '123456789' >>> s[:-1:2] '1357' >>> Gary Herron > '' > though I expected something like '8642' > What did i missed? > > -- > http://mail.python.org/mailman/listinfo/python-list > From remy.blank at pobox.com Tue Jul 8 14:39:37 2008 From: remy.blank at pobox.com (Remy Blank) Date: Tue, 08 Jul 2008 20:39:37 +0200 Subject: Relative Package Import In-Reply-To: References: Message-ID: Robert Hancock wrote: > mypackage/ > __init__.py > push/ > __init__.py > dest.py > feed/ > __init__py ^ Missing dot here? -----------| > In subject.py I have > from ..push import dest > > But i receive the error: > Caught exception importing module subject: > File "/usr/local/python/lib/python2.5/site-packages/pychecker/ > checker.py", line 621, in setupMainCode() > module = imp.load_module(self.moduleName, file, filename, smt) > File "subject.py", line 1, in () > from ..feed import dest This last line contradicts your statement above... -- Remy From google at mrabarnett.plus.com Mon Jul 28 11:41:55 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 28 Jul 2008 08:41:55 -0700 (PDT) Subject: Python FTP - NameError: name 'mydpa' is not defined References: Message-ID: On Jul 28, 2:27?pm, "Harry" wrote: > Hi there. I am trying to download a file(sn.last) from a public FTP > server with the following code: > > from ftplib import FTP > ftp=FTP('tgftp.nws.noaa.gov') > ftp.login() > ftp.cwd('SL.us008001/DF.of/DC.radar/DS.81dpr/SI.kbuf') > ftp.retrbinar('RETR sn.last', open(mydpa,'wb').write) open(mydpa,'wb') would open the file to which you're saving the data, but you haven't defined to mydpa, so Python will complain. > ftp.quit() > > but got an error message, which I think is normal: > > Traceback (most recent call last): > ? File "", line 1, in > ? ? ftp.retrbinary('RETR sn.last', open(mydpa,'wb').write) > NameError: name 'mydpa' is not defined Yep! > > I don't know much about python, but just try to use the code to > download data. I don't know where the file will be saved to. Is the > mydata a file name or a folder name? where will it be saved to even > if it's working? Please help be fixed the problem step by step? I am > using 2.5.2 by the way. > You need to tell it where to save the data by defining mydpa. > I really appreciate your help. Thanks. From nclbndk759 at googlemail.com Fri Jul 18 09:43:03 2008 From: nclbndk759 at googlemail.com (nclbndk759 at googlemail.com) Date: Fri, 18 Jul 2008 06:43:03 -0700 (PDT) Subject: Regular expression help Message-ID: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> Hello, I am new to Python, with a background in scientific computing. I'm trying to write a script that will take a file with lines like c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647 3pv=0 extract the values of afrac and etot and plot them. I'm really struggling with getting the values of efrac and etot. So far I have come up with (small snippet of script just to get the energy, etot): def get_data_points(filename): file = open(filename,'r') data_points = [] while 1: line = file.readline() if not line: break energy = get_total_energy(line) data_points.append(energy) return data_points def get_total_energy(line): rawstr = r"""(?P.*?)=(?P.*?)\s""" p = re.compile(rawstr) return p.match(line,5) What is being stored in energy is '<_sre.SRE_Match object at 0x2a955e4ed0>', not '-11.020107'. Why? I've been struggling with regular expressions for two days now, with no luck. Could someone please put me out of my misery and give me a clue as to what's going on? Apologies if it's blindingly obvious or if this question has been asked and answered before. Thanks, Nicole From romanticlover123 at gmail.com Sat Jul 19 00:35:04 2008 From: romanticlover123 at gmail.com (kick) Date: Fri, 18 Jul 2008 21:35:04 -0700 (PDT) Subject: hi this is very romantic actress photes Message-ID: <5a4d2a70-32d6-4078-9999-36777365fb3f@o40g2000prn.googlegroups.com> hi this is very romantic actress photes ******************************************************************************** http://lovegroup341.blogspot.com/ *********************************************************************** use this and enjoy each moments From dominic.rice at gmail.com Thu Jul 3 21:56:23 2008 From: dominic.rice at gmail.com (Dominic Rice) Date: Fri, 04 Jul 2008 02:56:23 +0100 Subject: running python from cmd.exe Message-ID: Hi, I can't seem to get python to run my scripts using the command: python .py If I type python the interpreter runs as I sorted out the Path property, I'm afraid I don't know much about this kind of thing as I'm a science student who needs some Python not a programmer! Thanks in advance From Lie.1296 at gmail.com Sun Jul 27 07:28:55 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 27 Jul 2008 04:28:55 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> Message-ID: On Jul 27, 2:48?am, "Russ P." wrote: > > If, as I wrote, you permit the omission of "self" in method signatures > > defined within class definitions, then you could still insist on > > instance attribute qualification using "self" - exactly as one would > > when writing Java according to certain style guidelines. > > I'm not sure exactly what people mean here by allowing "self" to be > "omitted" in method signatures. If it is omitted, then it seems to me > that a place holder would be needed to the interpreter that the first > argument is not just another name for "self." > > In an earlier post on this thread (don't feel like looking it up at > the moment), someone suggested that member data could be accessed > using simply ".member". I think he might be on to something. The dot > is a minimal indicator that the data is a class member rather than > just local. However, a placeholder is still needed in the signature. > > So why not allow something like this?: > > class MyClass: > > ? ? def func( , xxx, yyy): > Why not? Because that would make someone new to python scream in terror. > ? ? ? ? .xxx = xxx > > ? ? ? ? local = .yyy > OTOH, this might come as a handy syntax sugar, this is like With Statement in VB, although in VB, you have to state explicitly what you want to call implicitly when using something of the .methods. But I think implementing this might come with a heavy toll to the parser. > The "self" argument is replaced with nothing, but a comma is used as a > placeholder. From bgporter at acm.org Fri Jul 25 15:38:34 2008 From: bgporter at acm.org (Brett g Porter) Date: Fri, 25 Jul 2008 15:38:34 -0400 Subject: Python program as daemon? In-Reply-To: <8bb6bd1a-cd85-4b7a-8fc9-844f3794bca0@c58g2000hsc.googlegroups.com> References: <8bb6bd1a-cd85-4b7a-8fc9-844f3794bca0@c58g2000hsc.googlegroups.com> Message-ID: <488A2BBA.3060303@acm.org> Johny wrote: > Is it possible to run a Python program as daemon? Sure -- see http://code.activestate.com/recipes/66012/ for an example (and some useful stuff in the comments.) From tjreedy at udel.edu Wed Jul 9 13:08:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 09 Jul 2008 13:08:58 -0400 Subject: how to remove oldest files up to a limit efficiently In-Reply-To: References: <1eb168ac-fc63-4724-8604-45e995a06b51@s50g2000hsb.googlegroups.com> Message-ID: Dan Stromberg wrote: > On Tue, 08 Jul 2008 15:18:23 -0700, linuxnow at gmail.com wrote: > >> I need to mantain a filesystem where I'll keep only the most recently >> used (MRU) files; least recently used ones (LRU) have to be removed to >> leave space for newer ones. The filesystem in question is a clustered fs >> (glusterfs) which is very slow on "find" operations. To add complexity >> there are more than 10^6 files in 2 levels: 16? dirs with equally >> distributed number of files inside. > >> Any suggestions of how to do it effectively? > > os.walk once. > > Build a list of all files in memory. > > Sort them by whatever time you prefer - you can get times from os.stat. Since you do not need all 10**6 files sorted, you might also try the heapq module. The entries into the heap would be (time, fileid) From pdorange at pas-de-pub-merci.mac.com Thu Jul 3 08:15:52 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Thu, 3 Jul 2008 14:15:52 +0200 Subject: Trouble using pinckle References: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> <1ijgp2r.1j1k5xwwbtiwcN%pdorange@pas-de-pub-merci.mac.com> <486ba8a4$0$11957$426a74cc@news.free.fr> Message-ID: <1ijia9i.j7cls41raaazgN%pdorange@pas-de-pub-merci.mac.com> Bruno Desthuilliers wrote: > > I try the staticmethod, it works fine. Very helpful. > > > > But i don't like it very much, it seems 'complicated' (python was > > supposed to be simple). > > Try doing the same thing in C++ !-) OK ;-) I just ask myself what was the best method (according to python phylosophy). -- Pierre-Alain Dorange Vid?o, DV et QuickTime Clarus, the DogCow From Lie.1296 at gmail.com Sat Jul 26 11:41:04 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 26 Jul 2008 08:41:04 -0700 (PDT) Subject: print doesn't respect file inheritance? References: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> Message-ID: <6b8b16c2-1822-4e83-94a6-a9d3f98fddc7@k36g2000pri.googlegroups.com> On Jul 26, 8:50?am, bukzor wrote: > I was trying to change the behaviour of print (tee all output to a > temp file) by inheriting from file and overwriting sys.stdout, but it > looks like print uses C-level stuff ?to do its writes which bypasses > the python object/inhertiance system. It looks like I need to use > composition instead of inheritance, but thought this was strange > enough to note. > > $python -V > Python 2.5 > > """A short demo script""" > class notafile(file): > ? ? def __init__(self, *args, **kwargs): > ? ? ? ? readonly = ['closed', '__class__', 'encoding', 'mode', 'name', > 'newlines', 'softspace'] > ? ? ? ? file.__init__(self, *args, **kwargs) > ? ? ? ? for attr in dir(file): > ? ? ? ? ? ? if attr in readonly: continue > ? ? ? ? ? ? setattr(self, attr, None) > > def main(): > ? ? n = notafile('/dev/stdout', "w") > ? ? print vars(n) > > ? ? import sys > ? ? sys.stdout = n > ? ? print "Testing: 1, 2, 3..." > > output: > {'__str__': None, 'xreadlines': None, 'readlines': None, 'flush': > None, 'close': None, 'seek': None, '__init__': None, '__setattr__': > None, '__reduce_ex__': None, '__new__': None, 'readinto': None, > 'next': None, 'write': None, '__doc__': None, 'isatty': None, > 'truncate': None, 'read': None, '__reduce__': None, > '__getattribute__': None, '__iter__': None, 'readline': None, > 'fileno': None, 'writelines': None, 'tell': None, '__delattr__': None, > '__repr__': None, '__hash__': None} > Testing: 1, 2, 3... Use this: class fakefile(object): def __init__(self, writeto, transformer): self.target = writeto self.transform = transformer def write(self, s): s = self.transform(s) self.target.write(s) sys.stdout = fakefile(sys.stdout, lambda s: '"' + s + '"') Inheriting from file is not the best way to do it since there is a requirement that child class' interface must be compatible with the parent class' interface, since the file-like object you're creating must have extremely different interface than regular file, the best way is to use Duck Typing, i.e. write a class that have .write() method. From larry.bates at websafe.com` Tue Jul 15 23:07:54 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 22:07:54 -0500 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: David Lees wrote: > kjhishere at gmail.com wrote: >> I need to know if I'm running on 32bit or 64bit ... so far I haven't >> come up with how to get this info via python. sys.platform returns >> what python was built on ... but not what the current system is. >> >> I thought platform.uname() or just platform.processor() would have >> done it, but python returns an empty string on windows. Any ideas? >> >> Thanks, Ken > > On my windows box this works: > > >>> platform.architecture() > ('32bit', 'WindowsPE') > > > David On Fedora Core 5 64-bit here is what I see: >>> import platform >>> platform.architecture() ('64bit', 'ELF') -Larry From omer at no-log.org Wed Jul 2 06:43:36 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Wed, 2 Jul 2008 12:43:36 +0200 Subject: beginner's questions - manipulating text files In-Reply-To: <486ABACE.9050103@umbc.edu> References: <486ABACE.9050103@umbc.edu> Message-ID: <200807021243.37001.omer@no-log.org> Le Wednesday 02 July 2008 01:16:30 Ben Keshet, vous avez ?crit?: > Hi, > > I am a very beginner Python programmer with limited programming > experience overall. > > I am trying to write a script that will search for the second and third > appearance of the symbol '@' in a file, will read a random line between > them, and write the line into a new file. So far I was only able to open > the file using 'open', but I am not sure how to proceed. I tried to read > it line by line using 'readline' but was not sure how to manipulate the > text the way I need to. > If the file you're reading is not too big, you can use file.readlines() which read all the files and returns its content as a list of lines. > Could anyone please give me |a basic guidance as for what functions may > be useful for my purpose? (e.g how to search for a string '@' in a text? > how to identify its location? text.find('@') will return the position of the first occurence of '@', or a negative value if not found. > how to choose a random number in a defined > range? random.randrange(start, stop) > how to read that line number from a text file? etc.)| if you read the file with readlines(), just lines[lineno] you'll find more infos in the following sections: http://docs.python.org/lib/bltin-file-objects.html http://docs.python.org/lib/string-methods.html http://docs.python.org/lib/module-random.html -- C?dric Lucantis From deets at nospam.web.de Thu Jul 3 14:46:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jul 2008 20:46:47 +0200 Subject: imap4_SSL from behind a proxy server In-Reply-To: References: Message-ID: <6d4l4pFrogsU1@mid.uni-berlin.de> Dave schrieb: > First to admit I'm a newbie at Python, IMAP, or SSL. And it's been a > long time since I've posted anything to a Usenet group. But I've > spent countless hours spinning my wheels on this one, so I thought I'd > ask for help. > > I'm trying write some Python code to connect to Gmail from work, where > I need to direct all non-HTTP traffic through a proxy server. Can > anyone provide syntax which would redirect the imap4_SSL method > through a proxy server:port? I suspect there are some environment > variables which, when set, will do this very easily and elegantly. I > also suspect there is a really complicated way to 'wrap' the imap > classes so as to force requests to go through a proxy which, as a > newbie, I am trying to avoid. > > FYI, I'm currently running Python 2.5.2. via IDLE on Windows XP. But > when this project is done, I will move it to Linux. AFAIK that's simply not possible. Proxying that is not transparent is only (for practical matters, there might be esoteric protocols that do that as well) defined for HTTP. So "I need to direct all non-HTTP traffic through a proxy server." does not make much sense - at least to me. In other words: there is no such thing as general proxying, and thus no support in any library e.g. imaplib or such. Do you have an example of an application (e.g. mailclient or such) that *does* support the above scenario? Diez From bruno.desthuilliers at gmail.com Fri Jul 18 09:08:44 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 18 Jul 2008 06:08:44 -0700 (PDT) Subject: property getter with more than 1 argument? References: Message-ID: On 17 juil, 16:57, mk wrote: > It seems like getter is defined in such way that it passes only 'self': > > class FunDict(dict): > def __init__(self): > self.fundict = dict() What's the use of inheriting from dict here ??? > def fget(self, fun): wrong signature for a property.fget callback > return fundict[fun.func_name] > def fset(self, newfun): > self.fundict[newfun.func_name] = newfun > > newfun = property (fget, fset) > > >>> a=FunDict() > >>> > >>> a.newfun=f1 > >>> > >>> a.newfun('f1') Note that you're passing a string, when your (incorrect) getter expects a function object. > Traceback (most recent call last): > File "", line 1, in > a.newfun('f1') > TypeError: fget() takes exactly 2 arguments (1 given) > > Is it possible to pass more than one argument to fget function? Yes : call it directly !-) Or remember the old saying: """ Any software problem can be solved by adding another layer of indirection. Except, of course, the problem of too much indirection. """ Steve Bellovin of AT&T Labs Applied to your problem, it would mean making your getter return a closure that will take the func or func name and return the result of the lookup, ie: def fget(self): return lambda funcname: self.fundict[funcname] But anyway: this is still a typical case of arbitrary overcomplexification. A plain dict would be enough. Or, given the context (as exposed in an earlier post here), I'd suggest something like: class CallbacksRegister(object): def __init__(self, **kw): self._store = dict(**kw) def register(self, func, name=None): if name is None: name = func.__name__ self._store(name) = func return func def get(self, name, default=None): return self._store.get(name, default) def __getattr__(self, name): try: return self._store[name] except KeyError: raise AttributeError('%s object has no attribute '%s'" % (self, name) callbacks = CallbacksRegister() @callbacks.register def f1(arg): print "f1", arg callbacks.f1("yadda") callbacks.get('f1')('yadda') > I know: I can define a function with property name ('newfun' in the > example) and call it with more arguments. But then I do not get the > benefits of setter and property in general! The benefit of computed attributes (the property class being only one possible implementation) is to decouple interface (looks like an ordinary attribute) from implementation (is in fact computed). And the benefit from this decoupling is that you don't have to write getters/ setters until you really need them, since you can then turn a plain attribute into a computed one without breaking the interface. I fail to see what "benefits" you get from a property in your above snippet. From mcl.office at googlemail.com Mon Jul 7 07:30:33 2008 From: mcl.office at googlemail.com (mcl) Date: Mon, 7 Jul 2008 04:30:33 -0700 (PDT) Subject: Confused yet again: Very Newbie Question Message-ID: Why can I not the change the value of a variable in another class, when I have passed it via a parameter list. I am sure I am being stupid, but I thought passed objects were Read/ Write eg ------------------------------------------------------------ #!/usr/bin/python class one(): #my Global Vars fred = 'fred' class three(): def createJoe(self, myName): c1 = one() myName = 'Joe' #********************* Question why does this not change variable fred in 'class one' print 'Three(Local): ' + myName + ' Three(Global): ' + c1.fred def main(): c1 = one() c3 =three() c3.createJoe(c1.fred) if __name__ == '__main__' : main() Results: Three(Local): Joe Three(Global): fred 'fred' in 'class one' does not get changed to 'joe' in 'class three' 'createJoe', even though I have passed 'class one' 'fred' to 'createJoe' I hope this makes sense. I did not think you had to make the distinction between 'byvar' and 'byref' as in Basic. Thanks Richard From adityashukla1983 at gmail.com Fri Jul 25 14:50:05 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Fri, 25 Jul 2008 13:50:05 -0500 Subject: Histogram and \lambda parameter of the laplacian curve. Message-ID: <73045cca0807251150r15c2f9ebh24350482ab01190d@mail.gmail.com> Thanks everyone for your earlier help. I have to plot a histogram of values lets say [0.5,0.6,0.8,0.9].I guess the histogram would show an exponential decay ie, the laplacian curve. I need to find the \lambda parameter of this curve . So please tell me if it be done through http://matplotlib.sourceforge.net/and are there any other libraries which can be used. Thanks in advance. Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From Ilan.i18n at gmail.com Tue Jul 8 06:45:51 2008 From: Ilan.i18n at gmail.com (Ilan) Date: Tue, 8 Jul 2008 03:45:51 -0700 (PDT) Subject: Does omniORBpy 3.2 supports DII? Message-ID: Hello, My apologies if this is not the correct forum for thses quiestions, by I'm rather new to python+CORBA Has anyone used omniORBpy as CORBA implementation? are there any drawbacks? Does omniORBpy 3.2 supports the Dynamic Invocation Interface? Thanks. Ilan From gherron at islandtraining.com Mon Jul 28 00:34:24 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 27 Jul 2008 21:34:24 -0700 Subject: Where is the correct round() method? In-Reply-To: <90d24864-c67a-4594-b121-d0760f9e145b@m45g2000hsb.googlegroups.com> References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> <90d24864-c67a-4594-b121-d0760f9e145b@m45g2000hsb.googlegroups.com> Message-ID: <488D4C50.1030908@islandtraining.com> josh logan wrote: > On Jul 27, 8:45 pm, pigmartian wrote: > >> it could be that 3.0 is using "banker's rounding" --- rounding to the >> even digit. the idea behind it behind it being to reduce error >> accumulation when working with large sets of values. >> >> >>> Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo >>> CPU". What system are you on? >>> >>> It could be that 2.5 is really 2.49999... which would round down to 2, >>> but on any modern CPU (using IEEE floating point), 2.5 should be >>> representable exactly. >>> >> > > That's exactly what's happening, pigmartian. Thank you for explaining > the reasoning behind this change. > So am I relegated to building my own round() function that behaves > like the original function? Or did they move the functionality to a > new method somewhere for backwards-compatibility? > This will work as you wish: math.floor(x+0.5) Gary Herron > -- > http://mail.python.org/mailman/listinfo/python-list > From ggpolo at gmail.com Tue Jul 1 12:39:10 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 1 Jul 2008 13:39:10 -0300 Subject: dynamically load from module import xxx In-Reply-To: References: Message-ID: On Tue, Jul 1, 2008 at 12:55 PM, Neal Becker wrote: > Guilherme Polo wrote: > >> On Tue, Jul 1, 2008 at 12:11 PM, Neal Becker wrote: >>> What is a good way to emulate: >>> >>> from module import xxx >>> where 'module' is a dynamically generated string? >>> >>> __import__ ('modulename', fromlist=['xxx']) >>> >>> seems to be what I want, but then it seems 'xxx' is not placed in >>> globals() (which makes me wonder, what exactly did fromlist do?) >> >> fromlist is used for importing subpackages/submodules of the first arg >> of __import__. Since you are using "modulename", I'm guessing it is >> not a package, fromlist will do nothing for you. >> To solve your problem you could do getattr(__import__('modulename'), >> 'xxx'). > > This seems to be what I want, don't know if there is a simpler way: > > stuff =['A','B'] > module = __import__ (modulename) > for e in stuff: > globals().update({e : module.__dict__[e]}) > You could change that line to: globals()[e] = getattr(module, e) > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From jorgen.maillist at gmail.com Tue Jul 8 04:12:09 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Tue, 8 Jul 2008 10:12:09 +0200 Subject: Very weird bug! In-Reply-To: <1c7f6a82-bd0b-46bc-a6b7-23bf9f4b5ee3@m36g2000hse.googlegroups.com> References: <1c1c343a-dd63-454a-8e29-a5c70281ad90@c58g2000hsc.googlegroups.com> <1c7f6a82-bd0b-46bc-a6b7-23bf9f4b5ee3@m36g2000hse.googlegroups.com> Message-ID: <11e49df10807080112r6dd5e66ei22f9dde35cf0e365@mail.gmail.com> Maybe the interpreter remembered the values of some objects you used? If you type in the interpreter, the objects you create have a lifetime as long as the interpreter is active, which means it can get a state behaviour that otherwise is not present if you start a new interpreter instance. To be safe you should always try it with a script and run it from the commandline to get the same 'state' everytime your script runs. - Jorgen On Mon, Jul 7, 2008 at 7:36 PM, ssecorp wrote: > i know, idid try it again and it works as expected. but how the h*** > did it not work that one time? > -- > http://mail.python.org/mailman/listinfo/python-list > From bockman at virgilio.it Wed Jul 30 11:36:29 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Wed, 30 Jul 2008 08:36:29 -0700 (PDT) Subject: undo a dictionary References: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> Message-ID: <59548d6c-b30d-4dda-99e8-d2495000f4e1@d77g2000hsb.googlegroups.com> On 30 Lug, 16:51, mmm wrote: > I found code to undo a dictionary association. > > def undict(dd, name_space=globals()): > ? ? for key, value in dd.items(): > ? ? ? ? exec "%s = %s" % (key, repr(value)) in name_space > > So if i run > > >>> dx= { 'a':1, 'b': 'B'} > >>> undict(dx) > > I get>>> print A, B > > 1 B > > Here, ?a=1 and b='B' > > This works well enough for simple tasks and I understand the role of > globals() as the default names space, but creating local variables is > a problem. Also having no output arguemtns to undict() seems > counterintuitive. ?Also, the function fails if the key has spaces or > operand characters (-,$,/,%). ?Finally I know I will have cases where > not clearing (del(a,b)) each key-value pair might create problems in a > loop. > > So I wonder if anyone has more elegant code to do the task that is > basically the opposite of creating a dictionary from a set of > globally assigned variables. ?And for that matter a way to create a > dictionary from a set of variables (local or global). ?Note I am not > simply doing and ?undoing dict(zip(keys,values)) Maybe you can use objects as pseudo name spaces and do sommething like this: >>> class Scope(object): def dict(self): res = dict() for k, v in self.__dict__.items(): res[k] = v return res def undict(self, dict): for k,v in dict.items(): setattr(self, k, v ) >>> myscope = Scope() >>> myscope.undict(dict(A=1, B=2)) >>> myscope.A 1 >>> myscope.B 2 >>> myscope.dict() {'A': 1, 'B': 2} >>> Ciao ------ FB From larry.bates at websafe.com` Tue Jul 22 21:47:05 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 22 Jul 2008 20:47:05 -0500 Subject: How do I compare files? In-Reply-To: References: Message-ID: Clay Hobbs wrote: > I am making a program that (with urllib) that downloads two jpeg files > and, if they are different, displays the new one. I need to find a way > to compare two files in Python. How is this done? > > -- Ratfink > Use md5 to calculate checksum: import md5 md5file1 = md5.md5(open(filename1).read()).hexdigest() md5file2 = md5.md5(open(filename2).read()).hexdigest() if md5file1 != mdfile2: # # Do whatever you want # -Larry From Nikolaus at rath.org Mon Jul 28 03:35:16 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 28 Jul 2008 09:35:16 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <488D5B2C.10808@gmail.com> Message-ID: <87proysbpn.fsf@nokile.rath.org> Michael Torrie writes: > Colin J. Williams wrote: >>> >>> def fun( ., cat): >>> >> I don't see the need for the comma in fun. > > It (the entire first variable!) is needed because a method object is > constructed from a normal function object: > > def method(self,a,b): > pass > > class MyClass(object): > pass > > MyClass.testmethod=method > > That's precisely the same as if you'd defined method inside of the class > to begin with. A function becomes a method when the lookup procedure in > the instance object looks up the attribute and returns (from what I > understand) essentially a closure that binds the instance to the first > variable of the function. The result is known as a bound method, which > is a callable object: > >>>> instance=MyClass() > >>>> instance.testmethod > > > > > How would this work if there was not first parameter at all? > > In short, unlike what most of the implicit self advocates are > saying, it's not just a simple change to the python parser to do > this. It would require a change in the interpreter itself and how it > deals with classes. Thats true. But out of curiosity: why is changing the interpreter such a bad thing? (If we suppose for now that the change itself is a good idea). Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From ward.david at comcast.net Tue Jul 15 10:22:09 2008 From: ward.david at comcast.net (ward.david at comcast.net) Date: Tue, 15 Jul 2008 07:22:09 -0700 (PDT) Subject: Is it legal to rebuild Python.exe to include Version property tab? Message-ID: My company distributes a COM object that can be license and userd by our customers. Some of my company's internal application also use the COM object. However, for internal applications, instead of licensing the COM object, we just make the application registered as "friendly". We accomplish this be including various information in the "version" property tab of the calling EXE. In my case, the calling EXE is Python.exe. So, my question is, can we rebuild Python.exe to include the various "version" information? Is this allowed under the Python licensing agreement? From fuzzyman at gmail.com Sun Jul 13 09:44:00 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 13 Jul 2008 06:44:00 -0700 (PDT) Subject: Why is this blowing the stack, thought it was tail-recursive... References: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> Message-ID: On Jul 13, 7:56?am, Steven D'Aprano wrote: > On Sat, 12 Jul 2008 19:25:18 -0400, Terry Reedy wrote: > > ssecorp wrote: > >> def fib(n): > >> ? ? def fibt(a, b, n): > >> ? ? ? ? if n <= 1: > >> ? ? ? ? ? ? return b > >> ? ? ? ? else: > >> ? ? ? ? ? ? return fibt(b, a + b, n - 1) > >> ? ? if n == 0: > >> ? ? ? ? return 0 > >> ? ? else: > >> ? ? ? ? return fibt(0, 1, n); > > >> and can memoization speed up this even more? tesintg with memoization > >> doesnt really say anything because it is so fast it is instant anyway. > > > Except for the fact that a+b gets slower as a and b get bigger, this > > would already be linear time in n. ?Memoization (here by means of a > > linear list) only helps if the list is preserved and one makes repeated > > requests for various fib values. > > > I am just curious what input you tried that blew the stack? ?It had to > > be pretty large. > > No, not really. Try it for yourself: on my system, I get RuntimeError: > maximum recursion depth exceeded with fib(999). > > fib(999) is a large number, with 208 digits, but not that large: > > 268638100244853593861467272021429239676166093189869523401 > 231759976179817002478816893383696544833565641918278561614 > 433563129766736422103503246348504103776803673341511728991 > 69723197082763985615764450078474174626L > > -- > Steven The default CPython recursion limit is 1000 - so hitting it with an input of 999 is not that surprising... You can set a higher limit with sys.setrecursionlimit(...) Michael Foord http://www.ironpythoninaction.com/ From fredrik at pythonware.com Wed Jul 23 04:01:45 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 10:01:45 +0200 Subject: maximum value in a column of file In-Reply-To: <4886DCF3.10107@isac.cnr.it> References: <4886DCF3.10107@isac.cnr.it> Message-ID: maurizio wrote: > which is the best way for the calculation of the maximum value in a > column of a file? what approach have you tried, and what happened when you tried it? From google at mrabarnett.plus.com Sat Jul 26 12:26:23 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 26 Jul 2008 09:26:23 -0700 (PDT) Subject: Easier way to get the "here" path? References: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> Message-ID: <193ca421-7772-45cd-8fde-6ad594914732@p25g2000hsf.googlegroups.com> On Jul 25, 10:08?pm, bukzor wrote: > I have to go into these convulsions to get the directory that the > script is in whenever I need to use relative paths. I was wondering if > you guys have a better way: > > from os.path import dirname, realpath, abspath > here = dirname(realpath(abspath(__file__.rstrip("c")))) > > In particular, this takes care of the case of symlinked, compiled > scripts, which is fairly common at my workplace, and I imagine in many > *nix evironments. > > An illustration: > $echo "print __file__" > symlinks/path.py > $ln -s symlinks/path.py > $python>>> import path > path.py > >>> reload(path) > > path.pyc > >>> path.__file__ > 'path.pyc' > >>> path.__file__.rstrip("c") > 'path.py' > >>> from os.path import abspath, realpath > >>> realpath(path.__file__.rstrip("c")) > > '/home/bgolemon/python/symlinks/path.py'>>> realpath(abspath(path.__file__.rstrip("c"))) > > '/home/bgolemon/python/symlinks/symlinks/path.py' How about: import os import sys here = os.path.realpath(os.path.dirname(sys.argv[0])) It's a little clearer. :-) From s0suk3 at gmail.com Fri Jul 25 02:09:09 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Thu, 24 Jul 2008 23:09:09 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> On Jul 24, 5:01 am, Lawrence D'Oliveiro wrote: > In message > <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, Jordan > wrote: > > > Except when it comes to Classes. I added some classes to code that had > > previously just been functions, and you know what I did - or rather, > > forgot to do? Put in the 'self'. In front of some of the variable > > accesses, but more noticably, at the start of *every single method > > argument list.* > > The reason is quite simple. Python is not truly an "object-oriented" > language. It's sufficiently close to fool those accustomed to OO ways of > doing things, but it doesn't force you to do things that way. You still > have the choice. An implicit "self" would take away that choice. By that logic, C++ is not OO. By that logic, Ruby is not OO. By that logic, I know of only one OO language: Java :) The fact that a language doesn't force you to do object-oriented programming doesn't mean that it's not object-oriented. In other words, your words are nonsense. Sebastian From andreas.tawn at ubisoft.com Tue Jul 15 13:28:09 2008 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Tue, 15 Jul 2008 19:28:09 +0200 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: <487CD564.5020008@hughes.net> References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> <487CD564.5020008@hughes.net> Message-ID: <8AEDA5E3386EA742B8C24C95FF0C758004622F93@PDC-MAIL3.ubisoft.org> >defn noob wrote: >> isPrime works when just calling a nbr but not when iterating on a >> list, why? adding x=1 makes it work though but why do I have to add >> it? >> Is there a cleaner way to do it? >> >> >> def isPrime(nbr): >> for x in range(2, nbr + 1): >> if nbr % x == 0: >> break >> if x == nbr: >> return True >> else: >> return False >> >>>>> [isPrime(y) for y in range(11)] >> >> Traceback (most recent call last): >> File "", line 1, in >> [isPrime(y) for y in range(11)] >> File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime >> if x == nbr: >> UnboundLocalError: local variable 'x' referenced before assignment >> >> >>>>> map(isPrime, range(100)) >> >> Traceback (most recent call last): >> File "", line 1, in >> map(isPrime, range(100)) >> File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime >> if x == nbr: >> UnboundLocalError: local variable 'x' referenced before assignment >>>>> isPrime(10) >> False >>>>> isPrime(11) >> True >> >> >> >> adding x=1 makes it work though: >> >> def isPrime(nbr): >> x=1 >> for x in range(2, nbr + 1): >> if nbr % x == 0: >> break >> if x == nbr: >> return True >> else: >> return False >> >> >>>>> [isPrime(y) for y in range(11)] >> [False, True, True, True, False, True, False, True, False, False, >> False] >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > >======================================== >Yep - "local variable 'x' referenced before assignment" is correct. >You state: for x in range... but x doesn't exist until initialized. > To save a loop, initialize x=2 (the minimum value) and loop executes > on pass one. >In a straight 'C' program > ( for (x=1, x=(nbr+1), x++) etc... ) > the x is initialized and forceably incremented. > seems Python does not auto initialize but does auto increment. I think a better explanation is that in your original function, x only existed while the for loop was running. As soon as execution hit the break statement, x ceased to exist. When you attempted to reference it in the next line, Python has no variable called x so it complains that x hasn't been initialised. A more idiomatic way to write it... def isPrime(nbr): if nbr <= 1: return False for x in xrange(2, nbr+1): if not nbr % x: return x == nbr Cheers, Drea From randall at ymail.com Wed Jul 2 03:03:34 2008 From: randall at ymail.com (R W) Date: Wed, 2 Jul 2008 00:03:34 -0700 (PDT) Subject: extending auto_dict Message-ID: <694401.92884.qm@web46104.mail.sp1.yahoo.com> I'm using the excellent 'auto_dict' (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/537637) but I'd like to be able to extend it. Currently my program has class auto_dict(dict): def __getitem__(self, key): return self.setdefault(key, self.__class__()) daily=auto_dict() try: daily['today']['now'].append((1,2)) except AttributeError: daily['today']['now']=[(1,2)] Which works OK but I thought it would be easy to supply an 'append' method to the auto_dict class that would save me from having all those try/except blocks scattered through my code ie I could just say daily['today']['now'].append((1,2)) and the class would take care of catching the exception and assigning the list. I tried adding def append(self,item): self=[item] return self to the class definition but it doesnt actually assign the value. Can it be done this way? Some other way? Or am I stuck using the try/except blocks? (please CC me since I'm not subscribed to the list) Get the name you always wanted with the new y7mail email address. www.yahoo7.com.au/mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Jul 18 05:30:09 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 11:30:09 +0200 Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> Message-ID: nicolas.pourcelot at gmail.com wrote: > Hi, > > I want to test if an object IS in a list (identity and not equality > test). > I can if course write something like this : > > test = False > myobject = MyCustomClass(*args, **kw) > for element in mylist: > if element is myobject: > test = True > break > > and I can even write a isinlist(elt, mylist) function. > > But most of the time, when I need some basic feature in python, I > discover later it is in fact already implemented. ;-) > > So, is there already something like that in python ? > I tried to write : > 'element is in mylist' > but this appeared to be incorrect syntax... There is no "is in" operator in Python, but you can write your test more concisely as any(myobject is element for element in mylist) > PS: Btw, how is set element comparison implemented ? My first > impression was that 'a' and 'b' members are considered equal if and > only if hash(a) == hash(b), but I was obviously wrong : >>>> class A(object): > ... def __eq__(self,y): > ... return False > ... def __hash__(self): > ... return 5 > ... >>>> a=A();b=A() >>>> a==b > False >>>> hash(b)==hash(a) > True >>>> b in set([a]) > False >>>> S=set([a]) >>>> S.difference([b]) > set([<__main__.A object at 0xb7a91dac>]) > > So there is some equality check also, maybe only if '__eq__' is > implemented ? In general equality is determined by __eq__() or __cmp__(). By default object equality checks for identity. Some containers (like the built-in set and dict) assume that a==b implies hash(a) == hash(b). Peter From clay at lakeserv.net Tue Jul 22 19:27:27 2008 From: clay at lakeserv.net (Clay Hobbs) Date: Tue, 22 Jul 2008 19:27:27 -0400 Subject: How do I compare files? Message-ID: <1216769247.18962.7.camel@generator> I am making a program that (with urllib) that downloads two jpeg files and, if they are different, displays the new one. I need to find a way to compare two files in Python. How is this done? -- Ratfink From casey.mcginty at gmail.com Mon Jul 7 19:08:20 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Mon, 7 Jul 2008 13:08:20 -1000 Subject: Interest not met. In-Reply-To: <849453.75351.qm@web23404.mail.ird.yahoo.com> References: <849453.75351.qm@web23404.mail.ird.yahoo.com> Message-ID: On Thu, Jul 3, 2008 at 5:01 AM, david odey wrote: > I write to inform you that the reason I subscribed to this web page > is not been met. > > I want to be sent sample codes in programming languages especially > python and an email tutorial on C#. I will be happy if these demands > are met. > > Thanks in anticipation. > Haha. This is a joke, right? Funny. I will begin preparations for transportation and a fully fueled airplane for your escape. Please send me your location. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Wed Jul 23 08:55:49 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 14:55:49 +0200 Subject: maximum value in a column of file In-Reply-To: <488705D6.4090300@isac.cnr.it> References: <4886DCF3.10107@isac.cnr.it> <4886F4CD.8010704@isac.cnr.it> <488705D6.4090300@isac.cnr.it> Message-ID: maurizio wrote: > thank you for your answer > actually i've to do some statistics (maximum,minimum,mean,standard > deviation,....) of a file of data in which each column is a particular > type of data. (the file is a tab separated value). > I was trying to do this by using python (usually i work with fortran or > bash, but i'm learning python), that the reason why i tried to use numpy. As I implied, you can do all this in standard Python "by hand", but numpy/scipy can definitely make things easier. There's a dependency cost here (your program needs one or more extra libraries to work), but if that's no problem in your environment, I'd recommend that approach. The scipy add-on contains a bunch of things for file i/o; see http://www.scipy.org/doc/api_docs/SciPy.io.html for an overview. Since you're reading text files, the "array_import" module seems to be what you need: http://www.scipy.org/doc/api_docs/SciPy.io.array_import.html There are active user communities for both numpy and scipy that can help you sort out any remaining issues; for details, see: http://www.scipy.org/Mailing_Lists Hope this helps! From bignose+hates-spam at benfinney.id.au Mon Jul 7 18:44:59 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 08 Jul 2008 08:44:59 +1000 Subject: Python Agile Software Development Tools Screencasts References: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> Message-ID: <87lk0dwbys.fsf@benfinney.id.au> percious writes: > Hi All, > > I started a new series about python on showmedo. Please feel free to > take a look. I'd love to, but showmedo refuses to show presentations to me without installing non-free software. -- \ ?It takes a big man to cry, but it takes a bigger man to laugh | `\ at that man.? ?Jack Handey | _o__) | Ben Finney From trentm at activestate.com Fri Jul 11 13:41:00 2008 From: trentm at activestate.com (Trent Mick) Date: Fri, 11 Jul 2008 10:41:00 -0700 Subject: ActiveState Code: the new Python Cookbook site In-Reply-To: References: <4873F326.5010905@activestate.com> <4874698E.7000805@gmail.com> <4877053f$0$16181$5402220f@news.sunrise.ch> Message-ID: <48779B2C.1030308@activestate.com> Peter Otten wrote: > Thin Myrna wrote: > >> The old cookbook offered choices by category. Did you drop that feature? > > Looks like categories have become tags: > > http://code.activestate.com/recipes/tags/ Yes, that is correct. I should document the tag names to category mapping that I've used (mostly a straightforward "remove spaces and capitalization" thing). My hope is that allowing free form tagging and (importantly) multiple tags will allow for more interesting and useful grouping. However, there is value in there being good suggestions of common tags when adding tags. I need to add that to the recipe add form: http://code.activestate.com/recipes/add/ Trent -- Trent Mick trentm at activestate.com From tuckers4all911 at yahoo.co.uk Thu Jul 3 11:01:46 2008 From: tuckers4all911 at yahoo.co.uk (david odey) Date: Thu, 3 Jul 2008 15:01:46 +0000 (GMT) Subject: Interest not met. Message-ID: <849453.75351.qm@web23404.mail.ird.yahoo.com> I write to inform you that the reason I subscribed to this web page? is not been met. I want to be sent sample codes in programming languages especially?? python and an email tutorial on C#. I will be happy if these demands? are met. ?Thanks in anticipation. ALWAYS THERE FOR YOU __________________________________________________________ Not happy with your email address?. Get the one you really want - millions of new email addresses available now at Yahoo! http://uk.docs.yahoo.com/ymail/new.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From sk8in_zombi at yahoo.com.au Tue Jul 15 15:17:45 2008 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Tue, 15 Jul 2008 12:17:45 -0700 (PDT) Subject: Handling events using pycairo Message-ID: <936782.84072.qm@web54503.mail.re2.yahoo.com> Hi, I'm trying to create a rectangle when the user presses or releases the mouse over a cairo object.I'm using the eventBox to capture the mouse events. Now the problem is the shapes is beng drawn when I call it from the expose_event event handler and nothing happens when I call the same from the mouse release event handler. Here is my code : #!/usr/bin/env python import sys import cairo import gtk start = None #Starting co-ords stop = None #Ending co-ords box = None? #Tuple of co-ords for drawing rect ctx = None #Cairo Widget def button_press(widget, event, surface): ??? global start ??? start = (int(event.x),int(event.y)) def motion_notify(widget, event, surface): ??? pass def button_release(widget, event, surface): ??? global stop,ctx ??? ctx = None ??? ctx = widget.window.cairo_create() ??? ctx.set_source_surface(surface, 0,0) ??? ctx.paint() ??? print ctx ??? stop =? (int(event.x),int(event.y)) ??? box = (start[0],start[1]) ??? draw_dotrect(ctx,box) ??? print "Released" + str(box) def draw_dotrect(ctx,box): ??? ctx.set_source_rgba(0, 0, 0,0.5) ??? ctx.save() ??? ctx.new_path() ??? ctx.translate(3*20, 0) ??? square(ctx,box) ??? ctx.fill() ??? ctx.restore() ??? ctx.set_line_width(20 / 16) ??? ctx.set_tolerance(0.1) ??? ctx.set_line_join(cairo.LINE_JOIN_MITER) ??? ctx.set_dash([20/2.0, 20/2.0], 8) ??? ctx.save() ??? ctx.new_path() ??? ctx.set_source_rgb(0,0 ,0 ) ??? ctx.translate(3*20, 0) ??? square(ctx,box) ??? ctx.stroke_preserve() ??? ctx.restore() ??? def expose_event(widget, event, surface): ??? global ctx ??? ctx = widget.window.cairo_create() ??? ctx.set_source_surface(surface, 0,0) ??? ctx.paint() ??? ??? #draw_dotrect(ctx,(20,20)) # If called from here,it works ??? ??? def square(ctx,box): ??? ctx.move_to(0, 0) ??? ctx.rel_line_to(2*50, 0) ??? ctx.rel_line_to(0, 2*50) ??? ctx.rel_line_to(-2*50, 0) ??? ctx.close_path() ??? ??? if len(sys.argv) != 2: ??? ??? raise SystemExit('usage: png_view.py png_file') filename = sys.argv[1] surface = cairo.ImageSurface.create_from_png(filename) Width? = surface.get_width() Height = surface.get_height() win = gtk.Window() win.connect('destroy', gtk.main_quit) event_box = gtk.EventBox() win.add(event_box) drawingarea = gtk.DrawingArea() event_box.add(drawingarea) drawingarea.connect('expose_event', expose_event, surface) event_box.connect('button_press_event',button_press,surface) event_box.connect('button_release_event',button_release,surface) event_box.connect('motion_notify_event',motion_notify,surface) drawingarea.set_size_request(Width,Height) win.show_all() gtk.main() It doesn't throw me any error.I hardcoded the box to simplify things .??? I also create a new ctx in the release event handler else it throws an error:CAIRO_STATUS_SURFACE_FINISHED Any ideas why ? " life isn't heavy enough,it flies away and floats far above action" Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregvika at gmail.com Mon Jul 14 11:11:55 2008 From: gregvika at gmail.com (greg) Date: Mon, 14 Jul 2008 08:11:55 -0700 (PDT) Subject: screencapture with PIL question Message-ID: <8e9ca866-4f14-4dd6-a784-a76630d8d812@x35g2000hsb.googlegroups.com> I am able to use the PIL module to capture a screen or specific window. My problem is when capturing a window (on windows XP) I can only capture the "visible" portion of the window. Is there any way to capture the entire window? specifically the scrolled portion of a window that is not visible on the screen. Thanks for any help. From keshet1 at umbc.edu Wed Jul 9 07:22:08 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Wed, 09 Jul 2008 07:22:08 -0400 Subject: a simple 'for' question In-Reply-To: <1215599630.2873.965.camel@localhost.localdomain> References: <4874017D.2000401@umbc.edu> <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> <487437E6.8010609@umbc.edu> <1215599630.2873.965.camel@localhost.localdomain> Message-ID: <48749F60.7030106@umbc.edu> it didn't help. it reads the pathway "as is" (see errors for both tries). It looks like it had the write pathway the first time, but could not find it because it searched in the path/way instead of in the path\way. thanks for trying. folders= ['1','2','3'] for x in folders: print x # print the current folder filename='Folder/%s/myfile.txt' %[x] f=open(filename,'r') gives: IOError: [Errno 2] No such file or directory: "Folder/['1']/myfile.txt" Tim Cook wrote: > On Wed, 2008-07-09 at 00:00 -0400, Ben Keshet wrote: > >> oops, my mistake, actually it didn't work... >> when I tried: >> for x in folders: >> print x # print the current folder >> filename='Folder/%s/myfile.txt' %x >> f=open(filename,'r') >> >> it says: IOError: [Errno 2] No such file or directory: >> 'Folder/1/myfile.txt' >> >> > > I believe it's because x is the position marker what you want instead is > the contents of folders at x; therefore folders[x] > > HTH, > Tim > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Tue Jul 15 13:38:43 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Jul 2008 18:38:43 +0100 Subject: File Locking Forced? Newbie question. In-Reply-To: <216e2396-65f6-4281-b3c5-754ceb07f3eb@m36g2000hse.googlegroups.com> References: <216e2396-65f6-4281-b3c5-754ceb07f3eb@m36g2000hse.googlegroups.com> Message-ID: <487CE0A3.7060601@timgolden.me.uk> Sparky wrote: > Hello! I am writing some software that will have many users accessing > the same file resource at once for reading purposes only. I am > programming on (Ubuntu) Linux and my question is in Windows, can I > have it so that the same file can be open in read mode by more than > one person or could Window's file locking system get in the way? Assuming your question is: can processes A, B & C read from the same file at the same time, then: Yes. (You can try it out yourself fairly easily if you want. Just open a clutch of interpreter windows and do some open ("abc.txt", "r").read () stuff in each one). But I'm surprised you think that anything might get in the way of that. It would be a fairly limiting file system which prevented multiple simultaneous readers. TJG From gboutsioukis at gmail.com Tue Jul 29 20:19:21 2008 From: gboutsioukis at gmail.com (gbs) Date: Wed, 30 Jul 2008 00:19:21 +0000 (UTC) Subject: How can I check nbr of cores of computer? References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> Message-ID: On Tue, 29 Jul 2008 15:53:47 -0700, defn noob wrote: > How can I check how many cores my computer has? Is it possible to do > this in a Python-app? Well you can try the functions in the 'platform' module, although in my box(debian) nothing useful comes out. I don't think there's a simple & portable way, you probably have to find one specific to your platform . (if you are on linux, you can parse the output of 'cat /proc/cpuinfo') From sjmachin at lexicon.net Thu Jul 24 04:06:33 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 24 Jul 2008 01:06:33 -0700 (PDT) Subject: EXCEL API References: <8279561b-05b7-4935-9ded-def5663b4f93@y21g2000hsf.googlegroups.com> Message-ID: On Jul 24, 5:15?pm, Girish wrote in comp.lang.python: > Hello, > > Does any one have a sample piece of code to search for a keyword in > Excel sheet? if so plz post it.. > 8<--- xlkwsearch.py import xlrd, sys, glob def xlkwsearch(fname, query): book = xlrd.open_workbook(fname) for sheet in book.sheets(): for rowx in xrange(sheet.nrows): for colx in xrange(sheet.ncols): cell = sheet.cell(rowx, colx) if cell.ctype == xlrd.XL_CELL_TEXT and query in cell.value: yield fname, sheet.name, rowx, colx, cell.value if __name__ == '__main__': for fname in glob.glob(sys.argv[1]): for result in xlkwsearch(fname, sys.argv[2]): print result 8<--- Sample output: D:\junk>python xlkwsearch.py *search*.xls hello ('search_demo.xls', u'Sheet1', 0, 0, u'hello') ('search_demo.xls', u'Sheet1', 2, 6, u'hello world') D:\junk>python xlkwsearch.py *search*.xls world ('search_demo.xls', u'Sheet1', 1, 1, u'world') ('search_demo.xls', u'Sheet1', 2, 6, u'hello world') ('search_demo.xls', u'2nd Sheet', 0, 0, u'underworld') ('search_demo.xls', u'2nd Sheet', 0, 2, u'worldly') From timothywayne.cook at gmail.com Wed Jul 9 06:50:56 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Wed, 09 Jul 2008 07:50:56 -0300 Subject: start reading from certain line In-Reply-To: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> Message-ID: <1215600656.2873.970.camel@localhost.localdomain> On Wed, 2008-07-09 at 03:30 -0700, antar2 wrote: > I am a starter in python and would like to write a program that reads > lines starting with a line that contains a certain word. > For example the program starts reading the program when a line is > encountered that contains 'item 1' > > > The weather is nice > Item 1 > We will go to the seaside > ... > > Only the lines coming after Item 1 should be read file=open(filename) while True: line=file.readline() if not line: break if 'Item 1' in line: print line HTH, Tim -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From python at rcn.com Tue Jul 22 12:21:36 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 22 Jul 2008 09:21:36 -0700 (PDT) Subject: convert list of lists to list References: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> Message-ID: <947194bf-b885-4ca0-b75c-c0b99336d81f@25g2000hsx.googlegroups.com> On Jul 22, 8:25?am, Fredrik Lundh wrote: > if there's only one level of recursion, and the lists aren't too long, > you can simply do: > > ? ? ?sum(list_of_lists, []) > > (this has quadratic performance, so don't use it for large structures) For linear performance, you can use itertools: list(itertools.chain(*list_of_lists)) Raymond From gagsl-py2 at yahoo.com.ar Tue Jul 15 03:59:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 04:59:00 -0300 Subject: screencapture with PIL question References: <8e9ca866-4f14-4dd6-a784-a76630d8d812@x35g2000hsb.googlegroups.com> Message-ID: En Mon, 14 Jul 2008 12:11:55 -0300, greg escribi?: > I am able to use the PIL module to capture a screen or specific > window. My problem is when capturing a window (on windows XP) I can > only capture the "visible" portion of the window. Is there any way to > capture the entire window? specifically the scrolled portion of a > window that is not visible on the screen. Camtasia Studio -a commercial product- has a few ways to do that; one is to send many simulated mouse clicks to the window scroll bars, capturing the window contents in stripes. pywinauto would help on doing that from Python http://pywinauto.blogspot.com/ -- Gabriel Genellina From miki.tebeka at gmail.com Thu Jul 3 15:57:51 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 3 Jul 2008 12:57:51 -0700 (PDT) Subject: Spell suggest for locations References: Message-ID: <6d5cbf0a-e28f-4204-ab2e-4ca79ddbcb77@w8g2000prd.googlegroups.com> Hello, > I'm working on spell suggestions for a list of places(~10^6) e.g pizza > hut What data structure shall I use for max performance/efficiency? > > Typing pizza ?should yield something like > > pizza hut pizza corner<...<... > ... > ... > ... A trie? (http://en.wikipedia.org/wiki/Trie). Googling for "spell checker algorithm" yields many results. HTH, -- Miki http://pythonwise.blogspot.com From simon at simonwillison.net Wed Jul 30 12:17:45 2008 From: simon at simonwillison.net (Simon Willison) Date: Wed, 30 Jul 2008 09:17:45 -0700 (PDT) Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: <2a703a46-75bc-4228-95d1-05a4e6030b40@f63g2000hsf.googlegroups.com> Message-ID: On Jul 30, 4:59?pm, Simon Willison wrote: > I just tried it out on Python 2.4.2 on an Ubuntu machine and it worked > fine! I guess this must be an OS X Python bug. How absolutely > infuriating. Some very useful people in #python on Freenode pointed out that my bug occurs because I'm trying to display things interactively in the console. Saving to a variable instead fixes the problem. Thanks for your help, Simon From hubaghdadi at gmail.com Tue Jul 29 10:47:35 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Tue, 29 Jul 2008 07:47:35 -0700 (PDT) Subject: Continuous integration for Python projects Message-ID: Hi. Please correct my if I'm wrong but it seems to me that the major continuous integration servers (Hudson, CruiseControl, TeamCity ..) don't support Python based application. It seems they mainly support Java, .NET and Ruby. Can I use one of the previous listed servers for Python project? Thanks. From deets at nospam.web.de Mon Jul 28 13:02:35 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 19:02:35 +0200 Subject: with statement for two files References: <08d72316-15f1-45dd-b1f7-7b8ee06efef5@e39g2000hsf.googlegroups.com> <7xsktuvusj.fsf@ruckus.brouhaha.com> Message-ID: <6f6cfdFa22kkU1@mid.uni-berlin.de> Paul Rubin wrote: > braver writes: >> with open(src) as readin, open(dst,"w") as writin: # WRONG: comma >> doesn't work >> ... >> -- so that you have transactional safety for two file descriptors? > > use contextlib.nexted(). You mean contextlib.nested I guess. Didn't know about that module, cool! However, the fundamental problem stays: rolling back only works if the innermost context fails. Diez From kay.schluehr at gmx.net Mon Jul 28 13:15:50 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 28 Jul 2008 10:15:50 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> <7360bd9a-4ff6-4e75-821c-eabc88ee6258@u6g2000prc.googlegroups.com> Message-ID: On 28 Jul., 06:42, "Russ P." wrote: > On Jul 27, 8:58 pm, castironpi wrote: > > > On Jul 27, 2:39 pm, Bruno Desthuilliers > > > wrote: > > > Derek Martin a ?crit : > > > > It's bad programming, but the world is full of bad programmers, and we > > > > don't always have the choice not to use their code. Isn't one of > > > > Python's goals to minimize opportunities for bad programming? > > > > Nope. That's Java's goal. Python's goals are to maximize opportunities > > > for good programming, which is quite different. > > Oh, gosh, that is so clever. What a bunch of crap. > > > +1 QOTW > > Do you realize what an insult that is to everyone else who has posted > here in the past week? Nothing glues a community together so well as a common enemy. Or even better: two enemies i.e. Perl and Java in Pythons case. On the other hand, some enemies have to be ignored or declared to be not an enemy ( Ruby ), although oneself is clearly an enemy for them. The same antisymmetry holds for Python and Java. Java is an enemy for Python but Python is not worth for Java to be an enemy as long as it can be ignored. C++ and Java are enemies for each other. Same holds for Java and C#. From sureshku472 at gmail.com Wed Jul 2 11:17:47 2008 From: sureshku472 at gmail.com (sureshku472 at gmail.com) Date: Wed, 2 Jul 2008 08:17:47 -0700 (PDT) Subject: free sms all over the world & downloading free wallpaper ringtones Message-ID: <31aba42e-2ac1-45e0-a4fd-a7573ce6f0de@s21g2000prm.googlegroups.com> Success usually comes to those who are too busy to be looking for it Visit Mobiles & Computers?, http://www.mobilecomputers4all.blogspot.com/
Hi..Click me

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi..Click me

From peter.anderson at internode.on.net Mon Jul 21 01:14:32 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Mon, 21 Jul 2008 15:14:32 +1000 Subject: Python Written in C? Message-ID: <48841B38.4050900@internode.on.net> > Bah, new-fangled languages like Pascal... Real programmers write Fortran. Using punch-cards and paper-tape. Real programmers can edit their programs with a pointy stick and some home-made sticky-tape. -- Grant Edwards Reminds me of a funny story from my past working life. I had this fibre tipped pen, given to me as a freebie by some computer company. The pen had something like "Floppy Disk Pen" printed down the barrel. A colleague who was more into IT management than programming or hands-on support picked it up at a meeting and said something like - "That's interesting, what's it for?" Seeing an opportunity I replied "Its a new bit of technology that allows you to write directly to your floppy disks when you are away from your computer!" "What a great idea!" he replied in all seriousness! Maybe our friend could find one to code C# with! ;-) Peter -- Peter Anderson There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things ? Niccolo Machiavelli, /The Prince/, ch. 6 From thomas.troeger.ext at siemens.com Tue Jul 15 09:05:18 2008 From: thomas.troeger.ext at siemens.com (Troeger, Thomas (ext)) Date: Tue, 15 Jul 2008 15:05:18 +0200 Subject: AW: Python embedding question. In-Reply-To: <487C8E1C.7050600@preisshare.net> References: <487C8E1C.7050600@preisshare.net> Message-ID: Hi, > > I want to embed a Python application on a device with limited > > resources, esp. storage limitations. Is there a way to reduce the > > Python interpreter to a set of modules that's urgently needed? > Of course there is. What is the target platform ? Thanks for your answer. The plattform is x86, so basically it's a PC with a compact flash drive. The problem is that the compact flash is rather limited in speed and size (there is other stuff on it too). > > Or is there a method to have gzipped modules that are unzipped on the > > fly into memory when they're accessed? That would be even better. > Yes - also possible. That sounds promising, is there a link you can give? Or do I have to modify the module loading code for this, i.e. the interpreter? I think that wouldn't be too much of a problem if I understand where Python loads modules; I haven't checked the Python source yet for that one, and searching for Python and zip or similar always yields tons of links that use the Python zip or tar module :) > Regards > David Cheers, Thomas. From goldfita at signalsguru.net Mon Jul 7 11:26:28 2008 From: goldfita at signalsguru.net (Todd) Date: Mon, 7 Jul 2008 08:26:28 -0700 (PDT) Subject: python mysteriously halts References: <13a33043-21d1-40c0-a938-6e905d958064@m3g2000hsc.googlegroups.com> Message-ID: On Jul 7, 10:17?am, Tim Golden wrote: > Todd wrote: > > I ran a python script last night which connects to a matlab automation > > server via DCOM (using win32com). ?I expected to see the results when > > I came in this morning. ?But apparently, not long after I left, python > > stopped. ?I hit enter in the console, and it started again. > > Symptomatically, at least, this can be caused by someone starting to > select (with the mouse) an area of the screen: the process will pause > until is pressed, which copies the area to the clipboard. This > only happens with a console window, but it sounds like that's what > you had running. > > TJG That might be it, although I don't recall doing that. Fortunately/ unfortunately, it happened a few times, but it seems to have stopped now. From steve at REMOVE-THIS-cybersource.com.au Thu Jul 31 18:40:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Jul 2008 22:40:41 GMT Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> Message-ID: <00a23ad3$0$20313$c3e8da3@news.astraweb.com> On Thu, 31 Jul 2008 13:32:39 +0200, Thomas Troeger wrote: >> Can someone explain to me the difference between a type and a class? > > If your confusion is of a more general nature I suggest reading the > introduction of `Design Patterns' (ISBN-10: 0201633612), under > `Specifying Object Interfaces'. > > In short: A type denotes a certain interface, i.e. a set of signatures, > whereas a class tells us how an object is implemented (like a > blueprint). A class can have many types if it implements all their > interfaces, and different classes can have the same type if they share a > common interface. I fear you're introducing a rather complicated answer for a simple question. In Python, the simple answer is that built-in objects like int, float, str etc. are referred to as "types", and custom objects created using the class keyword are referred to as "classes". This is a historical distinction that will disappear in time. We can see that types and classes already have the same type in Python: >>> class Parrot(object): ... pass ... >>> type(Parrot) >>> type(str) > The following example should clarify matters: > > class A: > def bar(self): > print "A" Alas, you've chosen the worst-possible example to "clarify" matters, because old-style classic classes are *not* unified with types, and will disappear in the future: >>> class Old: # don't inherit from object ... pass ... >>> type(Old) So, to the Original Poster: In Python, new-style classes and types are the same, but it is traditional to refer to customer objects as "class" and built-in objects as "types". Old-style classes are different, but you are discouraged from using old-style classes unless you have a specific reason for needing them (e.g. backwards compatibility). -- Steven From timothywayne.cook at gmail.com Sat Jul 26 07:59:15 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Sat, 26 Jul 2008 08:59:15 -0300 Subject: Stripping parts of a path Message-ID: <1217073555.2771.41.camel@localhost.localdomain> Hi All, I just ran into an issue with the rstrip method when using it on path strings. When executing a function I have a need to strip off a portion of the current working directory and add on a path to a log file. Initially this worked great but then I added a branch in SVN which caused the path to contain 'LNCCWorkshop'. The rstrip() then began removing the characters 'shop' leaving an incorrect path to the log file. When I hard coded this path it worked okay but then did the same thing later in the file when I needed to point to a database. The code worked fine with a different path. Here are some code fragments. logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/at_build_errors.log' this worked when the path was: /home/tim/ref_impl_python/TRUNK/oship/src/oship/atbldr the code above returns: /home/tim/ref_impl_python/TRUNK/oship/log/at_build_errors.log but when I tried a branches version that has the path: /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/src/oship/atbldr it SHOULD return: /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/log/at_build_errors.log but I get: /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log logfile=os.getcwd() print logfile is correct; but when I add the .rstrip('src/oship/atbldr') it also strips the 'shop' off of LNCCWorkshop and returns /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log I had two other people looking at this as we did troubleshooting and we could not determine the cause. It is repeatable with this path name. In resolution I renamed the branch to just LNCC and it works fine. Thoughts? Tim -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. Home page: https://launchpad.net/oship/ Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From mrkafk at gmail.com Wed Jul 9 10:53:39 2008 From: mrkafk at gmail.com (mk) Date: Wed, 09 Jul 2008 16:53:39 +0200 Subject: (silly?) speed comparisons In-Reply-To: <200807091447.34094.maric@aristote.info> References: <84bdef3c0807081516g7872d1d8x2ecb448fd1fa900c@mail.gmail.com> <200807091447.34094.maric@aristote.info> Message-ID: Maric Michaud wrote: > Le Wednesday 09 July 2008 12:35:10 mk, vous avez ?crit : >> vector move_slice(vector& vec, int start, int stop, int >> dest) > > I guess the point is to make a vector of referene to string if you don't want > to copy string objects all around but just a word for an address each time. > > The signature should be : > vector move_slice(vector& vec, int start, int stop, int > dest) > > or > > vector move_slice(vector& vec, int start, int stop, int > dest) That matters too, but I just found, the main culprit was _returning the list instead of returning the reference to list_. The difference is staggering - some 25 sec vs 0.2 sec: $ time slice6 real 0m0.191s user 0m0.015s sys 0m0.030s #include #include #include using namespace std; list& move_slice(list& slist, int start, int stop, int dest) { int idx; if( dest > stop) idx = dest - (stop - start); else idx = dest; int i; list::iterator startiter; list::iterator enditer; list::iterator destiter; startiter = slist.begin(); destiter = slist.begin(); for (i = 0; i < start; i++) startiter++; enditer = startiter; for (i = start; i < stop; i++) enditer++; for (i = 0; i < dest; i++) destiter++; slist.splice(destiter, slist, startiter, enditer); /* cout << "frag " << endl; for (startiter = frag.begin(); startiter != frag.end(); startiter ++) cout << *startiter << " "; cout << endl;*/ /* cout << " after: "; for (startiter = slist.begin(); startiter != slist.end(); startiter++) cout << *startiter << " "; cout << endl;*/ return slist; } int main(int argc, char* argv) { list slice; string u = "abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij"; int pos; for (pos = 0; pos < u.length(); pos++) slice.push_back(new string(u)); int i; //for (i = 0; i<1000000; i++) /*list::iterator startiter; cout << "before: "; for (startiter = slice.begin(); startiter != slice.end(); startiter++) cout << *startiter << " "; cout << endl;*/ for (int i = 0; i<1000000; i++) move_slice(slice, 4, 6, 7); } From dullrich at sprynet.com Fri Jul 18 17:29:22 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 18 Jul 2008 16:29:22 -0500 Subject: wxPython code giving strange errors. References: <01694ab5-7b5e-4e57-8b86-bf89b0beec82@m44g2000hsc.googlegroups.com> Message-ID: In article , Mike Driscoll wrote: > On Jul 13, 10:18?am, teh_sAbEr wrote: > > I'm busy trying to learn wxPython, and i'm trying to run the following > > piece of code (its from the wxPyWiki tutorial): > > > > import wx > > [...] > > > > app = wx.PySimpleApp() > > frame = MainWindow(None, -1, "Sample editor") > > app.MainLoop() > >[...] > > This code works "as is" on Windows XP. However, I have gotten this > error when trying to run it from IDLE and I've heard that that can > happen in other Tkinter-based IDEs. So I've heard. Just for fun I tried running it in a wxPython-based shell - it worked fine. > Try running it from the command > line and I'll bet you won't get that error. > > Also, there's a great wxPython user's group you can join from the > official website: > > www.wxpython.org > > Mike -- David C. Ullrich From georgeoliverGO at gmail.com Sat Jul 12 03:08:09 2008 From: georgeoliverGO at gmail.com (George Oliver) Date: Sat, 12 Jul 2008 00:08:09 -0700 (PDT) Subject: sending input to an embedded application Message-ID: hi, I'm a novice programmer trying to better define a hobby project I'm thinking of. What I would like to do is take a program and embed it or put it within a Python-run GUI, using the GUI just to capture and send input to the application, and display the ouput. Specifically I want to use a Python module such as wxPython, pygame or pyglet to build the UI, capture key presses, and then send a string to the program, an interactive fiction interpreter; the reason for this is that the interpreter on its own doesn't have the capability to recognize certain key presses on the keyboard. I thought that writing a middle layer rather than a brand new interpreter would be easier for someone of my skill level. The interpreter would send its output to the Python GUI. The GUI then would be as light/translucent as possible, just accepting input, sending it to the interpreter, and displaying the output as if you were just running the interpreter by itself. As I don't really know the issues involved, I'm hoping someone can point me in the right direction. Do people 'frame' programs with something like wxPython or pygame and use the frame to capture and pass along input, and receive and display the output? thanks, George From Russ.Paielli at gmail.com Wed Jul 30 02:36:19 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 23:36:19 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> Message-ID: <6d906dd5-bf5a-44d5-a5a8-3875027f6b91@v26g2000prm.googlegroups.com> On Jul 29, 11:16 pm, Erik Max Francis wrote: > Russ P. wrote: > > On Jul 29, 10:33 pm, Carl Banks wrote: > >> On Jul 30, 1:15 am, "Russ P." wrote: > > >>> Having said that, it would sure be nice to be able to write > >>> if myList is not empty: > >>> instead of > >>> if len(myList) != 0: > >> I can agree with this. > > > But I guess that could only work if there were only one empty list > > that represents all empty lists (as there is only one actual "None"). > > I don't know if that makes sense or not. > > It really doesn't, since it presumably wouldn't apply to just list > types. There are plenty of other sequence types: such as tuples, > strings, or even arbitrary custom types. Emptiness is a test for the > value of an object, not a test for whether it is identical to another > object, so this is a very misleading of the `is` operator, bordering on > abuse. > > This syntax would make far less sense than the existing Boolean test. > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis > The doors of Heaven and Hell are adjacent and identical. > -- Nikos Kazantzakis Now that's more reasonable. Note that I said, "it would be nice to be able to write," not "this is how it should be done." Come to think of it, shouldn't the list type have an "isempty" method? Or does it? From johnroth1 at gmail.com Tue Jul 1 21:39:47 2008 From: johnroth1 at gmail.com (John Roth) Date: Tue, 1 Jul 2008 18:39:47 -0700 (PDT) Subject: How to make a function associated with a class? References: <69e26f9b-2f00-4318-9bc5-6aa94e141bca@59g2000hsb.googlegroups.com> Message-ID: On Jul 1, 2:43 pm, Kurda Yon wrote: > Hi, > > I have a class called "vector". And I would like to define a function > "dot" which would return a dot product of any two "vectors". I want > to call this function as follow: dot(x,y). > > Well, I can define a functions "dot" outside the class and it works > exactly as I want. However, the problem is that this function is not > associated with the class (like methods a method of the class). > > For example, if I call "x.calc()" or "y.calc()", python will execute > different methods if "x" and "y" belongs to different classes. I want > to have the same with my "dot" function. I.e. I want it calculates the > dot product ONLY IF the both arguments of that function belong to the > "vector" class. > > Is it possible? > > Thank you in advance. If I understand what you want, you could do it the same way most of the other functions are implemented. There's a function, and then each class which has the behavior has a private (actually a system) method that implements it. The general pattern is to get the class for the first operand, check to see if it has the implementation method, and call it if present. If it doesn't, get the class for the other operand, check and if it has the method call it with the operands reversed. Then if it isn't in either, you can look the actual implementation method up in a table. When all else fails, raise a type error. HTH John Roth From fredrik at pythonware.com Thu Jul 24 05:59:29 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 11:59:29 +0200 Subject: Confounded by Python objects In-Reply-To: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> Message-ID: boblatest at googlemail.com wrote: > take a look at the code snippet below. What I want to do is initialize > two separate Channel objects and put some data in them. However, > although two different objects are in fact created (as can be seen > from the different names they spit out with the "diag()" method), the > data in the "sample" member is the same although I stick different > values in. that's because you only have one sample object -- the one owned by the class object. since you're modifying that object in place (via the append method), your changes will be shared by all instances. python never copies attributes when it creates an instance; if you want a fresh object, you have to create it yourself. > class Channel: tip: if you're not 100% sure why you would want to put an attribute on the class level, don't do it. instead, just create all attributes inside the __init__ method: > def __init__(self, name): > self.name = name self.sample = [] # create fresh container for instance > def append(self, time, value): > self.sample.append((time, value)) > self.diag() > > def diag(self): > print (self.name, self.sample) hope this helps! From Pidgeot18 at verizon.invalid Tue Jul 22 22:29:16 2008 From: Pidgeot18 at verizon.invalid (Joshua Cranmer) Date: Wed, 23 Jul 2008 02:29:16 GMT Subject: OT: OT posts [was Re: proliferation of computer languages] In-Reply-To: <637ca9de-75d6-48e4-b6fd-0bd36020c209@c65g2000hsa.googlegroups.com> References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> <637ca9de-75d6-48e4-b6fd-0bd36020c209@c65g2000hsa.googlegroups.com> Message-ID: <0Iwhk.355$oU.209@trnddc07> xahlee at gmail.com wrote: > ? many says i'm posting off topic posts. In recent years they start to > say i'm posting tangentially relevant posts. That's not correct. In > fact, there are huge number of blatantly off-topics posts by regulars > that spawn off from threads, happens regularly. The topics vary > anywhere from discussing politics, law, licenses, free speech, math > education, yapping on happenings of celebrity programers, and > including rampant flamewars and accusations among themselves. There is a difference. Many of your claimant off-topic posts are buried in the end of threads, not at the explicit start of a thread. In those cases, I personally feel that not moving to another forum is trumped by the sake of continuity. Even then, it should be indicated as such by OT: in the subject, but it gets easy to forget it. Starting a thread that is OT does not have such continuity considerations, though. And realize that something is not on-topic merely because it's relevant to Java programmers. You can see people's responses to one of Roedy's threads as an example. > ? Most newsgroup tech geekers consider cross-posting wrong. I consider > the taboo of this convention being a major contribution to the > redundant creation of new languages, and foster the hostile faction > nature of programing language communities we see. X-Posting to groups as diverse as c.l.perl.misc, c.l.python, c.l.lisp, c.l.functional, and c.l.java.programmer (the last one especially, as it is not a functional language nor will it ever be) is generally a sign that you are not X-Posting in a germane fashion. Your original topic belongs in comp.programming or maybe (I can see a case for it) in c.l.functional, but not the other four groups. > I wrote detailed argument about my edit in > my Wikipedia's personal talk page. The Wikipedia fuckheads not only > ban'd me, "When in Rome, do as the Romans do." Fragrantly violating the established rules of an organization, especially after being reminded of these rules, is sufficient cause for disciplinary action. And you're entire post gets more and more OT every paragraph. I can in no good faith allow this to continue. Setting F-U header to take appropriate actions. -- Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth From simon at simonwillison.net Wed Jul 30 11:16:26 2008 From: simon at simonwillison.net (Simon Willison) Date: Wed, 30 Jul 2008 08:16:26 -0700 (PDT) Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: Message-ID: <16218185-7d69-411c-a219-31f2e4e8df9e@p25g2000hsf.googlegroups.com> Follow up question: what's the best way of incrementally consuming XML in Python that's character encoding aware? I have a very large file to consume but I'd rather not have to fall back to the raw SAX API. From p at ulmcnett.com Wed Jul 2 23:55:26 2008 From: p at ulmcnett.com (Paul McNett) Date: Wed, 02 Jul 2008 20:55:26 -0700 Subject: wxPython: How can I get window's HANDLE in wxPython. In-Reply-To: References: Message-ID: <486C4DAE.9050701@ulmcnett.com> Leo Lee wrote: > I need a window's handle to be passed to external c++. > Thanks in advance import wx help(wx.Window.GetHandle) """ GetHandle(*args, **kwargs) unbound wx._core.Window method GetHandle(self) -> long Returns the platform-specific handle (as a long integer) of the physical window. On wxMSW this is the win32 window handle, on wxGTK it is the XWindow ID, and on wxMac it is the ControlRef. """ Paul From salimfadhley at gmail.com Wed Jul 9 09:39:29 2008 From: salimfadhley at gmail.com (Salim Fadhley) Date: Wed, 9 Jul 2008 06:39:29 -0700 (PDT) Subject: Python / Windows process control Message-ID: <7b1097c5-7a8a-4bb8-b293-03d15aee98ed@m36g2000hse.googlegroups.com> Does anybody know of a python module which can do process management on Windows? The sort of thing that we might usually do with taskmgr.exe or process explorer? For example: * Kill a process by ID * Find out which process ID is locking an object in the filesystem * Find out all the IDs of a particular .exe file * Find all the details of a currently running process (e.g. given an ID tell me which files it uses, niceness, runtime) Thanks! Sal From emen999 at gmail.com Fri Jul 25 07:06:45 2008 From: emen999 at gmail.com (code_berzerker) Date: Fri, 25 Jul 2008 04:06:45 -0700 (PDT) Subject: lxml, comparing nodes References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> <6c91a4da-6443-4570-8dd3-01c4ec169bf3@t54g2000hsg.googlegroups.com> <4888ad28$0$9491$9b4e6d93@newsspool3.arcor-online.net> <4613042f-ed70-4cfa-8de9-a92b4df32923@k36g2000pri.googlegroups.com> <4889B2B1.5030204@behnel.de> Message-ID: > Not in your code. > > Stefan Not sure what you mean, but I tested and so far every document with the same order of elements had number of comparisons equal to number of nodes. From timr at probo.com Fri Jul 25 01:33:59 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 25 Jul 2008 05:33:59 GMT Subject: Broken examples References: Message-ID: norseman wrote: > >I'm only talking about IPC related. >I have googled, yahooed, and so forth for several months now. ALL >examples I've come across have failed including those pertinent in the >Python doc area. > >Outline: > cd somedir > ls -1 *.xls >thislist #ls hyphen one > python process.py > (yes - ls can go here if wanted. easier to edit outside) > open thislist > loop until done > start excel (or scalc) > have it open file > have it save file as a .csv (or .dbf) > close excell (or scalc) > >Would seem to be a trivial exercise. Excel is a COM-driven application. You have to drive it through the object model. import win32com.client excel = win32com.client.Dispatch( 'Excel.Application' ) xlCSV = 6 ... for nm in list_of_file_names: csv = os.path.splitext( nm )[0] + '.csv' wb = excel.Workbooks.Open( nm ) wb.SaveAs( csv, xlCSV ) wb.Close() If you want to watch the progress, add "excel.Visible=1" after the dispatch. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From kasterma at bart-kastermanss-macbook.local Sun Jul 13 06:32:12 2008 From: kasterma at bart-kastermanss-macbook.local (Bart Kastermans) Date: Sun, 13 Jul 2008 05:32:12 -0500 Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> <85c3da91-9f2f-4d19-ba98-dfdc99b1e1e3@79g2000hsk.googlegroups.com> Message-ID: Roy Smith writes: > ssecorp wrote: > >> i dont get what you mean, if i dont do anything python will raise an >> indexerror so it is an indexerror. > > You wrote: > >> > > ? ? def pop(self): >> > > ? ? ? ? try: >> > > ? ? ? ? ? ? return self.queue.pop(0) >> > > ? ? ? ? except: >> > > ? ? ? ? ? ? raise IndexError, "pop from empty queue" > > You are assuming that the only possible exception that can be thrown by > "return self.queue.pop(0)" is IndexError. Maybe, maybe not. I gave you > one example of how something else could be thrown -- a typo in your code > leading to a NameError. Maybe even something more exotic like MemoryError? > > The defensive thing to do is catch exactly the exception you expect to > happen. In this case, that means IndexError. And you do that by except IndexError: raise TheErrorYouNowWantToRaise And except IndexError, e: if you want access to the exception as well. From chiendarret at gmail.com Sat Jul 26 17:40:00 2008 From: chiendarret at gmail.com (Francesco Pietra) Date: Sat, 26 Jul 2008 23:40:00 +0200 Subject: Insert string into string Message-ID: I am posting ex novo as it became confusing to me. I take the opportunity to ask advice for a second problem. FIRST PROBLEM For file xxx.pdb, insert letter "A" into each line that starts with "ATOM". "A" should be inserted at position 22, i.e., one space after "LEU", leaving all other characters at the same position as in the original example: ATOM 1 N LEU 1 146.615 40.494 103.776 1.00 73.04 1SG 2 In all lines starting with "ATOM", "LEU" is constant as to position only (18-20), i.e., "LEU" may be replaced by three different uppercase letters. Therefore, the most direct indication would be position 22. If specifying line starting with "ATOM" makes complication, forget about that as most lines begin with "ATOM" so that hand correction will be easy. Script f = open("xxx.pdb", "w") import sys for line in sys.stdin: line = line[:22] + "A" + line[23:] sys.stdout.write(line) destroys the xxxx.pdb file and python exits witha non zero exit status. The same occurs with script f = open("hASIC1a.B99990003.pdb", "w") f.write(' line = line[:22] + "A" + line[23:]') f.close() I must have misunderstood the suggestion I received on previous posting. ____________________________________ SECOND PROBLEM File xxx.pdb above has 426 lines stating with "ATOM", this serial number occupying positions 7-11, right justified (Thus 1, as in the line example above, means first line). A second, similar file yyy.pdb has to be concatenated to xxx.pdb. Before that it should be added of "A" as above and renumbered at position 7-11, starting from 428 (there is an intermediate line to add). How should a script look like for this string insertion into string with recursive +1? Thanks francesco From paul.hankin at gmail.com Wed Jul 9 15:34:45 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 9 Jul 2008 12:34:45 -0700 (PDT) Subject: formatting list -> comma separated References: <48750e4f$0$15106$e4fe514c@dreader27.news.xs4all.nl> Message-ID: <3fe8c8a7-b47d-4d17-b4ba-5213ba389eb1@34g2000hsf.googlegroups.com> On Jul 9, 8:23?pm, "Robert" wrote: > given d: > > d = ["soep", "reeds", "ook"] > > I want it to print like > > soep, reeds, ook > > I've come up with : > > print ("%s"+", %s"*(len(d)-1)) % tuple(d) > > but this fails for d = [] > > any (pythonic) options for this? print ', '.join(d) -- Paul Hankin From adityashukla1983 at gmail.com Fri Jul 25 18:02:43 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Fri, 25 Jul 2008 17:02:43 -0500 Subject: Histogram of floating point values. Message-ID: <73045cca0807251502i58c6e83dt872c46a9e7bb6775@mail.gmail.com> Hello folks, I have a list say data=[0.99,0.98,0.98,0.98,0.97,0.93,0.92,0.92,0.83,0.66,0.50,0.50] i am trying to plot histogram of these values i have installed numpy and matplotlib and this is what i am doing* import numpy import pylab from numpy import * from pylab import * input_hist=array(data) pylab.hist(input_hist,bins=0.1) and this is the error that i am getting *(array([], dtype=int32), array([ 0.5]),
)* does this mean that i cannot plot a histogram of floating point values ? or is there a way around Thanks in advance Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From davidreynon at gmail.com Thu Jul 24 15:09:00 2008 From: davidreynon at gmail.com (korean_dave) Date: Thu, 24 Jul 2008 12:09:00 -0700 (PDT) Subject: readln() until EOF Message-ID: a = open("Thefile.txt","r") while ?????: result = a.readln() what do i put in ???? if i want to keep reading line by line until i reach the end of the file? I don't want to break the loop if there is a blank line, because there will be. Ex. of a file: map1 result1 map2 result 2 map3 result3 comments thanks... From alexnbryan at gmail.com Sat Jul 12 15:45:30 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sat, 12 Jul 2008 12:45:30 -0700 (PDT) Subject: Help with BeautifulSoup In-Reply-To: <2.2.32.20080712100911.01141b64@pop.xs4all.nl> References: <2.2.32.20080712100911.01141b64@pop.xs4all.nl> Message-ID: <18423003.post@talk.nabble.com> Michiel Overtoom wrote: > > Alex wrote... >> >>Okay, heres the general idea of the html I have to work with: >> >>
>> noun >> >>
>>
>>
>> verb >>
>>
>>
>> >> >>Okay, I left off some stuff. > > I wish you didn't, or at least provided an URL where I can get the page > which you are trying to parse. Now I don't have a valid testcase to > tinker > with. And maybe you can also show your code which you already came up > with. > > >> I can easily get the tables but it is the span's than I am having trouble > with. > > I can't see any SPAN tags in the example you provided. > > Greetings, > > -- > "The ability of the OSS process to collect and harness > the collective IQ of thousands of individuals across > the Internet is simply amazing." - Vinod Vallopillil > http://www.catb.org/~esr/halloween/halloween4.html > > -- > http://mail.python.org/mailman/listinfo/python-list > > Oh, well sorry, I wrote the span tags, but they didn't show up. But it was around the noun. Here is the code I have to get the definitions alone: import urllib from BeautifulSoup import BeautifulSoup class defWord: def __init__(self, word): self.word = word def get_defs(term): soup = BeautifulSoup(urllib.urlopen('http://dictionary.reference.com/search?q=%s' % term)) for tabs in soup.findAll('table', {'class': 'luna-Ent'}): yield tabs.findAll('td')[-1].contents[0].string self.mainList = list(get_defs(self.word)) Theres a bit more to it, but it doesn't matter here, and so if you look I am using dictionary.com as the website. If you look at the html, the "" tags are where the type of the word is and that is what I need, in order. Or if I can figure out how many
tags are inbetween each "" tag, that too would work. If you need anything else, feel free to ask! -- View this message in context: http://www.nabble.com/Re%3A-Help-with-BeautifulSoup-tp18418004p18423003.html Sent from the Python - python-list mailing list archive at Nabble.com. From tjreedy at udel.edu Sat Jul 12 19:57:38 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 19:57:38 -0400 Subject: Beginner Question : Iterators and zip In-Reply-To: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> References: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> Message-ID: moogyd at yahoo.co.uk wrote: > Hi group, > > I have a basic question on the zip built in function. > > I am writing a simple text file comparison script, that compares line > by line and character by character. The output is the original file, > with an X in place of any characters that are different. > > I have managed a solution for a fixed (3) number of files, but I want > a solution of any number of input files. > > The outline of my solution: > > for vec in zip(vec_list[0],vec_list[1],vec_list[2]): > res = '' > for entry in zip(vec[0],vec[1],vec[2]): > if len(set(entry)) > 1: > res = res+'X' > else: > res = res+entry[0] > outfile.write(res) > > So vec is a tuple containing a line from each file, and then entry is > a tuple containg a character from each line. > > 2 questions > 1) What is the general solution. Using zip in this way looks wrong. Is > there another function that does what I want zip(*vec_list) will zip together all entries in vec_list Do be aware that zip stops on the shortest iterable. So if vec[1] is shorter than vec[0] and matches otherwise, your output line will be truncated. Or if vec[1] is longer and vec[0] matches as far as it goes, there will be no signal either. res=rex+whatever can be written as res+=whatever > 2) I am using set to remove any repeated characters. Is there a > "better" way ? I might have written a third loop to compare vec[0] to vec[1]..., but your set solution is easier and prettier. If speed is an issue, don't rebuild the output line char by char. Just change what is needed in a mutable copy. I like this better anyway. res = list(vec[0]) # if all ascii, in 3.0 use bytearray for n, entry in enumerate(zip(vec[0],vec[1],vec[2])): if len(set(entry)) > 1: res[n] = 'X' outfile.write(''.join(res)) # in 3.0, write(res) tjr From iainking at gmail.com Thu Jul 10 11:54:02 2008 From: iainking at gmail.com (Iain King) Date: Thu, 10 Jul 2008 08:54:02 -0700 (PDT) Subject: start reading from certain line References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> <1215601039.2873.972.camel@localhost.localdomain> Message-ID: <5de66f4b-b931-4618-b461-29a43e5a119d@25g2000hsx.googlegroups.com> On Jul 10, 2:45?pm, jstrick wrote: > Here's a simple way to do it with a minimum amount of loopiness (don't > forget to use 'try-except' or 'with' in real life): > > f = open("item1.txt") > > for preline in f: > ? ? if "Item 1" in preline: > ? ? ? ? print preline, > ? ? ? ? for goodline in f: > ? ? ? ? ? ? # could put an end condition with a 'break' here > ? ? ? ? ? ? print goodline, > > f.close() No From x at y.z Tue Jul 1 10:33:16 2008 From: x at y.z (name) Date: Tue, 1 Jul 2008 14:33:16 +0000 (UTC) Subject: pyparsing problem References: Message-ID: Paul McGuire wrote in news:be7af822-70d7-44fb-96fa- 78b490192334 at r66g2000hsg.googlegroups.com: > > Looks like this is a bug in asXML(). Note that if I reverse the use > and host_name strings in the input and in your grammar, I get this XML > output: > > > host-01 > generic > host alias xyz > 10.0.0.1 > > > Fortunately, you have provided a nice short test case, which should > allow me to track down the problem. > > Thanks, > -- Paul > You are welcome! And I would like to thank you for this outstanding tool! Thanks, Bernhard From castironpi at gmail.com Thu Jul 24 17:34:38 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 24 Jul 2008 14:34:38 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <579f9d5b-8984-425d-8d4f-b2ed0be8eaba@o40g2000prn.googlegroups.com> <4888cd25$0$15527$426a74cc@news.free.fr> Message-ID: <0baa0dfc-8c33-4659-9ae7-438a31f7dfa9@j1g2000prb.googlegroups.com> On Jul 24, 11:43?am, Bruno Desthuilliers wrote: > Jordan a ?crit : > > >> I don't really mind, what you think about my response. ?Python will suffer > >> from it as little as it will suffer from your complaints: ?These things > >> will not change, whatever any of us says about them. ?So this discussion > >> unlikely to produce any new insight, especially because this as been > >> discussed over and over again in the past, without any effect on Python. ? > > > You're right, of course. Because Python is in so many ways what I'm > > looking for in a language, I transform it in my mind to my own, > > personal ideal, close to the real existing language but with what I > > consider to be the imperfections removed. > > I guess you'll find a lot of us guilty here too - but do we really agree > on what we consider to be "imperfections" ?-) > > (snip) > > > I was trying not to change explicit self, or even != (which has a much > > better case.) I was trying to ask the community to reconsider a > > premise that the language is built around. Explicit is actually kinda > > annoying a lot of the time, viz., java. This is about social and > > philosophical adjustments, not technical ones. > > "explicit-is-etc" - just like the remaining of Python's zen - is a > general philosophy statement, not an absolute rule. Another quote states > that practicality beats purity. > > So yes, Python has warts, and one can't get away dogmatically quoting > Python's zen. Even if I'm sometimes myself guilty here, it's certainly > worth taking time to better address criticism, either by aknowledging > effective warts when someone points them out or by explaining (or > pointing to explanations of) the unusual parts of Python's design. > > Now since most of the times, criticisms expressed here fall in the > second category, we're happy to learn you'll now take appropriate action > here and help us keep c.l.py a newbie-friendly place !-) Something that is pure and explicit is a conflict of priorities with something that is practical and implicit. As with any rules, there are going to be times when the priorities in the Zen conflict with one another, and the Zen is silent on which combination ranks higher. Some people will hate you for using 'sf' instead of 'self'... but some hate you for spelling errors too. A temper lost is a flamewar earned. If you post two equivalent code snippets that both work, we can help you compare them. From tdelaney at avaya.com Sun Jul 6 21:00:20 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 7 Jul 2008 09:00:20 +0800 Subject: how are strings immutable in python? In-Reply-To: <337db7c6-0fc9-465e-b780-322c3a5cf8da@y38g2000hsy.googlegroups.com> Message-ID: ssecorp wrote: > so why would you ever want mutability? > > > seems very counterintuitive and unreliable. Because immutability imposes a lot of restrictions and performance characteristics that mutable objects don't have. For example, compare building up a list and a tuple element-by-element (using the most appropriate methods for each): a = [] b = () for i in range(10): a.append(i) b += (i,) The list can simply grow its memory space and assign the new element. OTOH, we need to create two new tuples each time (the one containing the new element, and the one which is a concatenation of the old elements plus the new element). The old tuple and the temporary tuple then get thrown away. Even if you optimise away the temporary 1-tuple (which python doesn't) the need to allocate a new tuple every time and copy the old elements to it results in much worse time and memory usage. There are optimisations that can be done if the compiler/runtime system can determine that there is only one reference to the immutable object (python now does this in some cases for string concatenation), but in general you cannot rely on this and have to assume that the worst case applies. Tim Delaney From cito at online.de Fri Jul 11 10:45:20 2008 From: cito at online.de (Christoph Zwerschke) Date: Fri, 11 Jul 2008 16:45:20 +0200 Subject: strip() using strings instead of chars In-Reply-To: <487751a6$0$29402$426a74cc@news.free.fr> References: <487751a6$0$29402$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers schrieb: > DRY/SPOT violation. Should be written as : > > prefix = 'http://' > if url.startswith(prefix): > url = url[len(prefix):] That was exactly my point. This formulation is a bit better, but it still violates DRY, because you need to type "prefix" two times. It is exactly this idiom that I see so often and that I wanted to simplify. Your suggestions work, but I somehow feel such a simple task should have a simpler formulation in Python, i.e. something like url = url.lstripstr(('http://', 'https://')) instead of for prefix in ('http://', 'https://'): if url.startswith(prefix): url = url[len(prefix):] break -- Christoph From bdesth.quelquechose at free.quelquepart.fr Mon Jul 28 18:50:52 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 29 Jul 2008 00:50:52 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: <488e6943$0$20692$426a74cc@news.free.fr> Derek Martin a ?crit : > On Sun, Jul 27, 2008 at 09:39:26PM +0200, Bruno Desthuilliers wrote: >>> As for the latter part of #3, self (or some other variable) is >>> required in the parameter list of object methods, >> It's actually the parameter list of the *function* that is used as the >> implementation of a method. Not quite the same thing. > > The idea that Python behaves this way is new to me. For example, the > tutorials make no mention of it: > > http://docs.python.org/tut/node11.html#SECTION0011300000000000000000 > > The Python reference manual has very little to say about classes, > indeed. If it's discussed there, it's buried somewhere I could not > easily find it. Yeps, most of the doc didn't really follow Python's evolutions alas. But it's still documented - I've learned all this from the doc. You'll find more details starting here: http://www.python.org/doc/newstyle/ and a couple more stuff in the language specs part of the doc: http://docs.python.org/ref/descriptors.html http://docs.python.org/ref/descriptor-invocation.html >> consistency mandates that the target object of the method is part of >> the parameter list of the *function*, since that's how you make >> objects availables to a function. > > Fair enough, but I submit that this distinction is abstruse, The distinction between class interface (the method call) and class implementation (the function called by the method) ? > and > poorly documented, This is certainly true. Patches to the doc are welcome. > and also generally not something the average > application developer should want to or have to care about... I don't know what's an "average application developper", but as an application developper myself, I feel I have to care about the implementation of my programs, just like I feel I have to care about knowing enough about the languages I use to use them properly. > it's of > interest primarily to computer scientists and language enthusiasts. > The language should prefer to hide such details from the people using > it. There I beg to disagree. Transparently exposing most of it's object model is a design choice, and is for a great part responsible for Python expressive power and flexibility. And all this is really part of the language - I mean, it's a public API, not an implementation detail. FWIW, I'm certainly not what you'd call a "computer scientist" (I left school at 16 and have absolutely no formal education in CS). Anyway: "the language" (IOW: the language's designer) made a different choice, and I'm very grateful he did. >>> however when the method is *called*, it is omitted. >> Certainly not. > > Seems not so certain to me... We disagree, even after your careful > explanation. You're of course (and hopefully) entitled the right to disagree !-) > See below. > >> You need to lookup the corresponding attribute *on a given object* >> to get the method. Whether you write >> >> some_object.some_method() >> >> or >> >> some_function(some_object) >> >> you still need to explicitely mention some_object. > > But these two constructs are conceptually DIFFERENT, Why so ? > whether or not > their implementation is the same or similar. The first says that > some_method is defined within the name space of some_object. The first says that you're sending the message "some_method" to some_object. Or, to express it in Python terminology, that you're looking up the name "some_method" on some_object, and try to call the object returned by the attribute lookup mechanism, whatever that object is (function, method, class or any other callable). Now saying that it implies that "some_method is defined within the name space of some_object" depends on the definitions of 'defined', 'within' and 'namespace' (more on this below). > The > second says that some_object is a parameter of some_function... Yes. It also say that some_function knows enough about some_object to accept it as a parameter (or at least that the developper that passed some_object to some_function thought / expected it would be the case). You know, the dotted notation ("obj.attrib") is, well, just a notation. It's by no mean necessary to OO. You could have a perfectly valid object system where the base notation is "some_message(some_object)" instead of being "some_object.some_message" - and FWIW, in Common Lisp - which BTW have one of the richer object systems around -, the syntax for method call is the same as the syntax for function call, IOW "(func_or_method_name object arg1 arg2 argN)". > Namespace != parameter!!!!!!!!! Functions parameters are part of the namespace of the function body. Please don't get me wrong : I'm not saying your point is moot, just suggesting another possible way to look at the whole thing. > To many people previously familiar with OO programming in other > languages (not just Java or C++), but not intimately familiar with > Python's implementation details, It's actually not an implementation detail - it's part of the language spec. > the first also implies that > some_method is inherently part of some_object, There again, I disagree. To me, it implies that some_object understands the 'some_method' message. Which is not the same thing. Ok, here's a possible implementation: # foo.py def foo(obj): return obj.__class__.__name__ # bar.py from foo import foo class Meta(type): def __new__(meta, name, bases, attribs): cls = type.__new__(meta, name, bases, attribs) old_getattr = getattr(cls, '__getattr__', None) def _getattr(self, attrname): if attrname == 'some_method': return lambda self=self: foo(self) elif callable(old_getattr): return old_getattr(self, attrname) else: raise AttributeError("blah blah") cls.__getattr__ = _getattr return cls # baaz.py import bar class Quux(object): __metaclass__ = bar.Meta class Baaz(object): def __init__(self): self._nix = Quux() def __getattr__(self, name): return getattr(self._nix, name) # main.py import baaz some_object = baaz.Baaz() Is 'some_method' "inherently part of" some_object here ? There isn't even an object named 'some_method' anywhere in the above code... (and no, don't tell me, I know: it's a very convoluted way to do a simple thing - but that's not that far from things you could find in real-life library code for not-so-simple things). > in which case > explicitly providing a parameter to pass in the object naturally seems > kind of crazy. The method can and should have implicit knowledge of > what object it has been made a part. The method does. Not the function. Here's a possible (and incomplete) Python implementation of the method type: class Method(object): def __init__(self, func, instance, cls): self.im_func = func self.im_self = instance self.im_class = cls def __call__(self, *args, **kw): if self.im_self: args = (self.im_self, ) + args return self.im_func(*args, **kw) elif isinstance(args[0], self.im_class): return self.im_func(*args, **kw) else: raise TypeError("blah blah") > Part of the point of using > objects is that they do have special knowledge of themselves... s/do/seem to/ > they > (generally) manipulate data that's part of the object. Conceptually, > the idea that an object's methods can be defined outside of the scope > of the object, s/object/class/ > and need to be told what object they are part > of/operating on is somewhat nonsensical... That's still how other OOPLs work, you know. But they hide the whole damn thing out and close the box, while Python exposes it all. And I can tell you from experience that it's a sound idea - this gives you full control about your object's behaviour. wrt/ functions being defined outside classes then used as part of the implementation of a class, I fail to see where is the problem - but I surely see how it can help avoiding quite a lot of boilerplate when wisely used. >>> Thus when an object method is called, it must be called with one fewer >>> arguments than those which are defined. This can be confusing, >>> especially to new programmers. >> This is confusing as long as you insist on saying that what you >> "def"ined is a method - which is not the case. > > I can see now the distinction, but please pardon my prior ignorance, > since the documentation says it IS the case, as I pointed out earlier. Yeps. Part of the problem is that OO terminology doesn't have any clear, unambiguous definition - so terms like 'method' can be used with somewhar different meanings. Most of Python's doc use the term 'method' for functions defined within class statements - and FWIW, that's usually what I do to. > Furthermore, as you described, defining the function within the scope > of a class binds a name to the function and then makes it a method of > the class. Once that happens, *the function has become a method*. The function doesn't "become" a method - it's __get__ method returns a method object, that itself wraps the object and the function (cf above snippet). What's get stored in the class __dict__ is really the function: >>> class Foo(object): ... def bar(self): ... print "bar(%s)" % self ... >>> Foo.__dict__['bar'] >>> Whether you bind the name within or outside of the class statement doesn't change anything. > To be perfectly honest, the idea that an object method can be defined > outside the scope of an object I assume you meant "outside the class statement's body" ? > (i.e. where the code has no reason to > have any knowledge of the object) Just any code "using" an object need to have at least some knowledge of this object, you know. Or do you mean that one should not pass message to any other object than self ? This seems like a pretty severe restriction to me - in fact, I fail to see how one could write any code that way !-) > seems kind of gross to me... another > Python wart. Nope. A *great* strength. > One which could occasionally be useful I suppose, More than "occasionaly". Lots of frameworks use that (usually in conjonction with metaclasses) to inject attributes (usually functions) into your objects. Have a look at how most Python ORM work. > but a > wart nonetheless. Your opinion. But then you wont probably like Python. May I suggest Ruby instead - it has a much more canonical object model ?-) Err, no, wait - while dynamically adding attributes / methods to objects / classes is possible but not that common in Python (outside frameworks and ORMs at least), it's close to a national sport in Ruby. Nope, you won't like Ruby neither... > This seems inherently not object-oriented at all, Because things happens outside a class statement ? Remember, it's *object* oriented, not class oriented. Classes are not part of the base definitions of OO, and just aren't necessary to OO (have a look at Self, Io, or Javascript). As far as I'm concerned, "object oriented" is defined by 1/ an object has an identity, a state and a behaviour 2/ objects communicate by sending messages to each others And that's all for the OO theory - everything else is (more or less) language-specific. As you can see, there's no mention of "class" here, and not even of "method". All you have is identity, state, behaviour and messages - IOW, high level concepts that can be (are are indeed) implemented in many different ways. > for reasons I've already stated. It also strikes me as a feature > designed to encourage bad programming practices. For which definition of "bad" ? Your views on what OO is are IMHO very restricted - I'd say, restricted to what the C++/Java/UML guys defined as "being OO". Anyway: you'd be surprised by the self (no pun) discipline of most Python programmers. Python let you do all kind of crazy things, but almost no one seems to get over the board. FWIW, if you find the idea of a "method" defined outside the class statement shocking, what about rebinding the class of an object at runtime ? You may not know it, but the class of an object is just another attribute, and nothing prevents you from rebinding it to any other object whenever you want !-) > Even discounting that, if Python had a keyword which referenced the > object of which a given peice of code was a part, e.g. self, then a > function written to be an object method could use this keyword *even > if it is defined outside of the scope of a class*. The self keyword, > once the function was bound to an object, would automatically refer to > the correct object. If the function were called outside of the > context of an object, then referencing self would result in an > exception. This could probably be implemented, but it would introduce additional complexity. As I already said somewhere in this thread, as far as I'm concerned, as long as it doesn't break any existing code and doesn't impose restrictions on what is actually possible, I wouldn't care that much - but I think it would be mostly a waste of time (IMHO etc). > You'll probably argue that this takes away your ability to define a > function and subsequently use it both as a stand-alone function and > also as a method. I could. FWIW, I've almost never had a need for such a construction yet, and I don't remember having seen such a thing anywhere. But anyway, to avoid breaking code, the modification would still have to take into account functions using an explicit self (or cls) in the function's signature. I'm afraid this would end up making a mess of something that was originally simple. > I'm OK with that -- while it might occasionally > be useful, I think if you feel the need to do this, it probably means > your program design is wrong/bad. More than likely what you really > needed was to define a class that had the function as a method, and > another class (or several) that inherits from the first. Not designing things the CanonicalUMLJavaMainstreamWay(tm) doesn't mean the design is wrong. Also, there are some problems that just can't be solved that way - or are overly (and uselessly) tedious to solve that way. Talking about design, you may not have noticed yet, but quite a lot of the OO design patterns are mostly workaround the lack of flexibility in Java and C++ (hint: how would you implement the decorator pattern in Python ?). And while we're at it, the GoF (IMHO one of the best books on OO design) lousily insists on composition/delegation being often a way better design than inheritance (which FWIW is what Python does with method calls being delegated to functions). > >> The point is that you don't get access to the object "within itself". >> You get access to an object *within a function*. > > Thus methods are not really methods at all, Please show me where you get access to the object "within itself" in any other OO language. Methods (for the usual acceptation of the term) are *not* "within" the instances. And they access instances thru a reference to it, reference that get injected into the code one way or another. Most languages make this implicit, Python makes it explicit. So what ? > which would seem to > suggest that Python's OO model is inherently broken (albeit by design, > and perhaps occasionally to good effect). Here again, you are being overly dogmatic IMHO. Being explicit, or just being different from mainstream, is not the same as being "broken". >> The fact that a function is defined within a class statement doesn't >> imply any "magic", > > It does indeed -- it does more than imply. It states outright that > the function is defined within the namespace of that object, s/object/class/ > and as > such that it is inherently part of that object. s/object/class/ > So why should it need > to be explicitly told about the object of which it is already a part? Because it's the simplest thing to do ?-) More seriously, methods are usually (in Python - always in most OOPLs) part of a class, not of it's instances - IOW, the same code is shared by all instances of a same class. And the language implementation needs to make the instance accessible to the method code one way or another. From this POV, Python doesn't behave differently - except that it choosed to expose the fact and make it part of the API. > It further does indeed imply, to hordes of programmers experienced > with OO programming in other languages, that as a member, property, > attribute, or what ever you care to call it, of the object, it should > have special knowledge about the object of which it is a part. class Foo(object): some_dict = dict() def __init__(self, some_int, some_list, some_string): self.int = some_int self.list = some_list self.string = some_string foo = Foo(42, range(3), "yadda") Where do you see that 42, range(3) and "yadda" have any knowledge of foo? Translate this to any other OOPLs and tell me if the answer is different. >> IOW : there's one arguably good reason to drop the target object from >> functions used as methods implementation, which is to make Python looks >> more like Java > > No, that's not the reason. I don't especially like Java, nor do I use > it. Sorry, I usually use 'Java' as a generic branding for the whole static struct-based class-oriented mindset - UML / C++ / Java / C# etc - by opposition to dynamic OOPLs. Anyway, in this particular case, it was not even what I meant, so please accept my apologies and s/Java/canonical/ in the above remark. > The reason is to make the object model behave more intuitively. I understand that having to specify the target object can seem disturbing, at least at first. Now once you know why, I personnaly find it more "intuitive" to not have different constructs for functions, methods, and functions-to-be-used-as-methods. I write functions, period. IOW: >> , and there's at least two good reason to keep it the way it is, >> which are simplicity (no special case) and consistency (no special >> case). > > Clearly a lot of people find that it is less simple TO USE. I would say it requires a bit more typing. Does that make it less simple to use ? I'm not sure. Am I biased here ? After many years of Python programming, I don't even notice typing 'self' in the argument list no more, so very probably: yes. > The point > of computers is to make hard things easier... if there is a task that > is annoying, or tedious, or repetitive, it should be done by code, not > humans. Which BTW is why I really enjoy having the possibility to modify a class at runtime - believe me, it can save quite a lot of boilerplate... > This is something that Python should do automatically for its > users. This point is debatable, indeed. Still, the only serious reason I see here is to make Python look more like most mainstream OOPLs, and while it may be a good idea - I'm not making any judgement on this - I can happily live with the current state of things as far as I'm concerned. Anyway, the decision doesn't belong to me. From aonaran at yahoo.com Mon Jul 7 19:38:44 2008 From: aonaran at yahoo.com (DSM) Date: Tue, 08 Jul 2008 00:38:44 +0100 Subject: complex representation Message-ID: From the nothing-is-so-trivial-it's-not-worth-a-usenet-post file: Shouldn't the default representation of complex numbers be like that of floats? That is, have a decimal point? >>> 1 1 >>> 1.0 1.0 >>> 1j 1j >>> 1.0j 1j >>> 1.0+1.0j (1+1j) In the relevant bit of floatobject.c, there's a comment explaining that 1.0 isn't accidental: /* Subroutine for float_repr and float_print. We want float numbers to be recognizable as such, i.e., they should contain a decimal point or an exponent. However, %g may print the number as an integer; in such cases, we append ".0" to the string. */ ISTM the same reasoning applies equally to complex numbers. My interest arose because of what I think is a bug in pypy's complex printing: Python 2.4.1 (pypy 1.0.0 build 56124) on linux2 Type "help", "copyright", "credits" or "license" for more information. ``RPython: we use it so you don't have to'' >>>> (1.1+1.1j)**200 (240733537691613523198532543387690598400L+236495565429619338248192Lj) This strangeness comes about because a hack used to recover cpython's behaviour fails at large values. (x.real == floor(x.real), so it decides the value's an integer, and returns the repr of int(x.real).) It's trivial to fix but I think cpython's behaviour is slightly odd here, and the real and imaginary parts of the complex repr should be identical to those of the underlying floats. Or is there some reason I'm missing that things are the way they are? From gcmartijn at gmail.com Sun Jul 6 06:07:59 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Sun, 6 Jul 2008 03:07:59 -0700 (PDT) Subject: pythoncom InternetExplorer.Application don't work in vista || firefox pythoncom ? References: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> <486fe5cc$0$926$ba4acef3@news.orange.fr> Message-ID: <29c70427-07f2-43ae-b742-86af4431edd8@34g2000hsh.googlegroups.com> On 5 jul, 14:14, "M?ta-MCI \(MVP\)" wrote: > Hi! > > Your code run OK for me (Vista Ultimate). > This other version run also OK : > > def webbrowser(url=None): > ? ? import win32com.client, time > > ? ? ie=win32com.client.Dispatch('InternetExplorer.Application') ? ? > ? ? while ie.Busy==True: > ? ? ? ? time.sleep(0.125) > ? ? ie.Top = 0 > ? ? ie.Left = 0 > ? ? ie.Height = 400 > ? ? ie.Width = 400 > ? ? ie.AddressBar = False > ? ? ie.MenuBar ?= False > ? ? ie.Resizable = False > ? ? ie.StatusBar = False > ? ? ie.ToolBar = False > ? ? ie.Visible = 1 > ? ? return ie > > w = webbrowser() > w.Navigate('http://www.google.nl') > > @-salutations > -- > Michel Claveau I use your script now but I'm still getting 2 windows I uploaded a screenshot how it looks. 1 at the background my window (but that is loading nothing) 1 at on top with the site http://www.google.nl (because that is in the script) http://img376.imageshack.us/img376/5506/capturess8.jpg From dullrich at sprynet.com Thu Jul 24 12:21:58 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 24 Jul 2008 11:21:58 -0500 Subject: repr(string) References: Message-ID: In article , Fredrik Lundh wrote: > David C. Ullrich skrev: > > >> just keep in mind that using eval() on untrusted data isn't a very good > >> idea. > > > > Right. This data comes from me, gets put into a file and then > > read by me. Someone _could_ corrupt that file, but someone who > > could do that could more easily just throw the machine out > > the window... > > and then your boss finds your program useful, and it's installed on a > shared server, and then the guys at the office in Eggkleiva wants a > copy, and then people start shipping save files via mail to keep things > synchronized, and then someone sets up a web service... ;-) Heh-heh. Good point, except that the idea that someone's going to find it useful is utterly implausible. Nobody but me has ever found a program I wrote useful. People think it's funny that I write little Python programs to do things I could just do in Excel or Open Office. (When I have some accounting/secretarial sort of thing to do doing it by hand in Python is one way to make it tolerably interesting. Easier to add new features - instead of trying to find an Excel way to do something like delete the smallest _two_ items in a list I just do it.) > -- David C. Ullrich From tjreedy at udel.edu Fri Jul 18 03:48:19 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Jul 2008 03:48:19 -0400 Subject: None in comparison In-Reply-To: <6eatdoF67cpfU1@mid.uni-berlin.de> References: <549f01d2-1d15-4b0d-9440-a9402c0449ff@b2g2000prf.googlegroups.com> <6eatdoF67cpfU1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Thu, 17 Jul 2008 23:52:13 -0700, r.grimm wrote: > >> Hello, >> I'm a little confused about None in comparison. >> >>>>> id ( None ) >> 3086100672L >>>>> id ( 1 ) >> 134541104 >>>>> None < 1 >> True >> I thought, the id of the object is the last comparison criterion. > > Obviously that expectation is false. The result of a comparison between > different types, with no `__cmp__()` method that says otherwise, is a > arbitrarily but consistent ordering by type. The language doesn't even > guarantee that it must be consistent in different runs of the same program > in the same interpreter, just within one run. > > So if you plan to rely on such implementation details, your program is > broken. And in 3.0 such arbitrary comparisons are gone. >>> None < 1 Traceback (most recent call last): File "", line 1, in None < 1 TypeError: unorderable types: NoneType() < int() From hat at se-162.se.wtb.tue.nl Wed Jul 2 04:15:47 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 02 Jul 2008 10:15:47 +0200 Subject: Problem with a for loop and a list References: Message-ID: On 2008-07-02, Alexnb wrote: > I have no idea what "list assignment index out of range means?!?! You are assigning a value to a non-existing list element, as in >>> x = [1] >>> x[2] = 4 Traceback (most recent call last): File "", line 1, in ? IndexError: list assignment index out of range Albert From goldtech at worldpost.com Fri Jul 25 09:53:32 2008 From: goldtech at worldpost.com (goldtech) Date: Fri, 25 Jul 2008 06:53:32 -0700 (PDT) Subject: Python base distribution come with a validating XML parser? Message-ID: <4205c679-4a0e-41d6-8311-2e033b7b5e0d@j7g2000prm.googlegroups.com> Hi, Basic XML questions, I have a .xml file I want to validate against a .xsd file... Does the Python base distribution come with a validating XML parser? I want to make sure the elements in my xml file vs. the elements defined in my xsd are a match. I could parse both XML and xsd elements to lists and compare the lists, but I imagine the validation process can do this too... Some of this is basic stuff - just a link to a site or doc is sufficient. Thanks. From semanticist at gmail.com Sun Jul 20 00:49:55 2008 From: semanticist at gmail.com (Miles) Date: Sun, 20 Jul 2008 00:49:55 -0400 Subject: Not entirely serious: recursive lambda? In-Reply-To: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> References: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> Message-ID: On Sat, Jul 19, 2008 at 10:43 PM, Michael Tobis wrote: > Can a lambda call itself without giving itself a name? Kind of. There's a couple ways I know of. The functional way, which involves the lambda receiving itself as an argument: (lambda f: f(10, f))(lambda n, f: n and (sys.stdout.write("%d\n" % n) or f(n-1,f))) The stack frame examination way: import sys, inspect, new (lambda:sys.stdout.write('recurse\n') or new.function(inspect.currentframe().f_code, globals())())() The functional way is probably harder to grok unless you've studied lambda calculus or had experience with "real" functional languages (I haven't). For fun, try throwing a Y combinator in there. -Miles From kandasamy.lakshmanan at gmail.com Sat Jul 26 02:44:01 2008 From: kandasamy.lakshmanan at gmail.com (abcd) Date: Fri, 25 Jul 2008 23:44:01 -0700 (PDT) Subject: u just click u get some dollars Message-ID: http://www.parttimejobsu.blogspot.com/ From aspersieman at gmail.com Fri Jul 4 02:58:58 2008 From: aspersieman at gmail.com (Aspersieman) Date: Fri, 04 Jul 2008 08:58:58 +0200 Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: <20080704053113.GJ34192@nexus.in-nomine.org> References: <20080704053113.GJ34192@nexus.in-nomine.org> Message-ID: <486DCA32.5000705@gmail.com> Jeroen Ruigrok van der Werven wrote: > -On [20080630 23:51], Ali Servet D?nmez (asd at pittle.org) wrote: > >> This could be an extension, a plugin, an Emacs mode, a new editor or >> even a brand new huge all-fancy IDE, I don't care, but what am I >> missing here? >> > > Vim's omnicomplete (CTRL-X CTRL-O). > > See :help omnifunc within vim. > > I find Vim with ctags, omnicomplete and calltip support the BEST I've tried so far. And I've tried many. Here's a tutorial on setting this up. http://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/ Regards Nicol -- The three things to remember about Llamas: 1) They are harmless 2) They are deadly 3) They are made of lava, and thus nice to cuddle. From timothywayne.cook at gmail.com Wed Jul 9 11:03:44 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Wed, 09 Jul 2008 12:03:44 -0300 Subject: FOSS projects exhibiting clean/good OOP? In-Reply-To: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> Message-ID: <1215615824.2873.978.camel@localhost.localdomain> On Wed, 2008-07-09 at 07:38 -0700, Phillip B Oldham wrote: > I'm wondering whether anyone can offer suggestions on FOSS projects/ > apps which exhibit solid OO principles, clean code, good inline > documentation, and sound design principles? > > I'm devoting some time to reviewing other people's code to advance my > skills. Its good to review bad code (of which I have more than enough > examples) as well as good, but I'm lacking in finding good examples. > > Projects of varying sizes would be great. Of course 'I think' mine matches that description. :-) In addition to the two links in the signature below where you can get a description and source code; there is an entry on Ohloh that says it is well documented code. http://www.ohloh.net/projects/oship I would appreciate your feedback. Cheers, Tim PS. The Launchpad and Ohloh repositories lag the openEHR SVN by several hours. -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. Home page: https://launchpad.net/oship/ Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From bbkolde at gmail.com Thu Jul 10 13:02:29 2008 From: bbkolde at gmail.com (Bhagwat Kolde) Date: Thu, 10 Jul 2008 22:32:29 +0530 Subject: installing any python module Message-ID: Hi all, What is the correct process of installing any external python module? Once we downloaded any python module, Q1) Where this module should be placed in python installation file structure? Q2) How to execute setup.py file? Thanks, Bhagwat -------------- next part -------------- An HTML attachment was scrubbed... URL: From naude.jaco at gmail.com Wed Jul 23 07:50:25 2008 From: naude.jaco at gmail.com (Jaco Naude) Date: Wed, 23 Jul 2008 04:50:25 -0700 (PDT) Subject: Undefined calling conventions in Python.h References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> Message-ID: On Jul 23, 1:10?pm, Fredrik Lundh wrote: > Jaco Naude wrote: > > What Visual C++ is doing is that it is looking for mangled names since > > it does not know the DLL contains C functions. I've managed to work > > around this by declaring the Python functions as follows before using > > them in the C++ application side: > > > extern "C" > > { > > ? ? void Py_Initialize(void); > > } > > > This seems to work and the C++ application side is not looking for > > mangled names any more. Is this the right way of doing it? It seems > > unnecessary to have to declare each Python function you want to use > > using the extern "C" way as shown above. > > Eh, are you saying that you're not including the Python.h file? ?Because > it does exactly that, for each and every public function in the C API. > > > It is probably more of a C++ question it turns out, but I would think > > that someone in the Python group would use the Python DLL in C++. The > > documentation also suggest that there is no extra work needed when > > using C++ rather than C. > > Oh, but I do that all the time, without doing any extra work. ?Both > embedding Python in C++ programs and existing it with C++ extensions. > And I'm definitely not alone. > > Here's an actual session, using the version of Visual Studio I happen to > have on this machine (2003, I think) from the command line: > > ?> more test.cc > > #include "Python.h" > #include > > main() > { > ? ? ?Py_Initialize(); > ? ? ?PyRun_SimpleString("print 'hello'\n"); > ? ? ?Py_Finalize(); > > ? ? ?std::cout << "world\n"; > > } > > ?> cl cl -EHsc -MD -I \python25\include test.cc \python25\libs\python25.lib > Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 > for 80x86 > Copyright (C) Microsoft Corporation 1984-2002. All rights reserved. > > ... > > ?> test > hello > world > > If you cannot get the same console program to work in your compiler > setup, something's wrong with your configuration. > > Ok that's probably good news, although it points out that there is something wrong with my configuration since that does not work. I would rather sort out the problem that having to defined each function with a extern "C" command. That said, let me double check something which might be causing problems since you will be familiar with this. Which Python.h file do you include when including the DLL in your programs? The one in the source distribution of the one in the installation distribution? I've been including the one in the installation distribution all along. When I try to include the one in the source distribution it gets up to the point where it looks for the following include: #include "pyconfig.h" This file is not in the same directory as the Python.h file in the source distribution. Because of this I just used Python.h in the installation distribution. Thanks again, Jaco From cwitts at gmail.com Wed Jul 23 12:42:06 2008 From: cwitts at gmail.com (Chris) Date: Wed, 23 Jul 2008 09:42:06 -0700 (PDT) Subject: concatenate the elements in each list of a list of lists References: <72c425b7-d9c2-4a61-8b7f-075eae14e703@x41g2000hsb.googlegroups.com> Message-ID: <82b5e735-88ee-45d2-a2fc-0346ed43341b@d77g2000hsb.googlegroups.com> On Jul 23, 5:33?pm, antar2 wrote: > I already asked a similar question, but encounter problems with > python... > How can I concatenate the elements in each list of a list of lists > > list_of_listsA = > > [['klas*', '*', '*'], > ['mooi*', '*', '*', '*'], > ['arm*', '*', '*(haar)']] > > wanted result: > > list_of_listsA = > > [['klas* * *'] > ['mooi* * * *'] > ['arm* * *(haar)']] > > Thanks a lot ! Nice and easy. :) >>> list_of_listsA = [['klas*', '*', '*'], ['mooi*', '*', '*', '*'], ['arm*', '*', '*(haar)']] >>> [' '.join(l) for l in list_of_listsA] ['klas* * *', 'mooi* * * *', 'arm* * *(haar)'] From socyl at 987jk.com.invalid Tue Jul 29 09:49:38 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 13:49:38 +0000 (UTC) Subject: backspace problems References: Message-ID: In kj writes: Please ignore my question. I found a general solution that works not only for the python interactive interpreter but also for all programs that have a readline-type interaction. This solution has nothing to do with Python, but if anyone's interested, it's here: http://www.macosxhints.com/article.php?story=20040930002324870&query=backspace%2Bdebian kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From torriem at gmail.com Tue Jul 15 19:21:14 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 15 Jul 2008 17:21:14 -0600 Subject: bad recursion, still works In-Reply-To: <5be12739-7896-4112-9307-53897af4f691@f63g2000hsf.googlegroups.com> References: <7bf2bad5-d6b6-4929-a520-a82b7bb49916@34g2000hsf.googlegroups.com> <5be12739-7896-4112-9307-53897af4f691@f63g2000hsf.googlegroups.com> Message-ID: <487D30EA.2060707@gmail.com> iu2 wrote: > I still don't understand: In each recursive call to flatten, acc > should be bound to a new [], shouldn't it? Why does the binding happen > only on the first call to flatten? Nope. In each new call it's (re)bound to the same original list, which you've added to as your function continues--it's mutable. Default variables that are bound to mutable objects are one of the big caveats that is mentioned in the FAQ. From bj_666 at gmx.net Wed Jul 16 11:07:53 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Jul 2008 15:07:53 GMT Subject: Angle brackets in command-line arguments? References: <52f1cde3-6240-46b0-8b03-478454e87688@b1g2000hsg.googlegroups.com> Message-ID: <6e6h69F5eajaU3@mid.uni-berlin.de> On Wed, 16 Jul 2008 07:53:56 -0700, Keith Hughitt wrote: > I am using someone else's script which expects input in the form of: > > ./script.py arg2 > > I was wondering if the angle-brackets here have a special meaning? It > seems like they specify an input and output stream to use in place of the > console. I could not find anything in the python manual or Python in a > Nut-shell though. > > Anyone know? That's not Python's business but the command shell's. Those characters are used for redirecting input and ouput from/to files in shells, so it should be covered in the documentation of the shell you are using. Including ways to protect the characters, so they reach the called program in arguments. Ciao, Marc 'BlackJack' Rintsch From fetchinson at googlemail.com Sat Jul 12 12:42:18 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 12 Jul 2008 09:42:18 -0700 Subject: Bypassing WebFilter security In-Reply-To: <25ff817d-2d0f-4806-b635-96e220d920f5@m44g2000hsc.googlegroups.com> References: <563968a1-3cc3-4009-beca-d5d367d4ccff@k13g2000hse.googlegroups.com> <4876F153.2020406@behnel.de> <25ff817d-2d0f-4806-b635-96e220d920f5@m44g2000hsc.googlegroups.com> Message-ID: >> >> I am working in an organization, which is using a very strict >> >> webcontent filter management suite. Due to this i am unable to >> >> download any exe file, or surf web (even the necessary downloads from >> >> sourceforgenet are blocked). I was wondering, if python could be of >> >> any help. Say i have a python script, and i pass the URL of >> >> downloadable file, and it just downloads the file for me. >> >> > Nice try. Can I talk to your employer for a minute? :) >> >> > Honestly, the language doesn't make any difference here, and there isn't >> > much >> > you can do unless you control both sides, i.e. the server and the >> > client. >> > But >> > I would suggest you actually talk to your employer yourself to see if >> > there's >> > an official way to get what you want. >> >> Yes, the language itself doesn't matter as long as you go through the >> web. But if I were you I would use an ssh client to ssh to a remote >> machine on which I have an account, download the file there to that >> machine and scp it to the local machine. Assuming of course port 21 is >> not blocked. >> >> In fact, this is something I do regularly for similar reasons :) >> >> Good luck, >> Daniel >> -- >> Psss, psss, put it down! -http://www.cafepress.com/putitdown > > Daniel, cool even i thought of the same thing, but you see, the > assumption has no use in my case! It is also blocked, Anyways, i will > talk to the system admins here. Thanks all Wait, port 21 is the *incoming* ssh port, when you use a client to ssh *out* you open a generic high port number. So that should work, you ssh out, download, go back to your local machine and scp out to get the file. On your local machine port 21 is not needed simply because you don't run an ssh server. Good luck, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From jordanrastrick at gmail.com Thu Jul 24 10:26:03 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 07:26:03 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> Message-ID: <579f9d5b-8984-425d-8d4f-b2ed0be8eaba@o40g2000prn.googlegroups.com> > I don't really mind, what you think about my response. ?Python will suffer > from it as little as it will suffer from your complaints: ?These things > will not change, whatever any of us says about them. ?So this discussion > unlikely to produce any new insight, especially because this as been > discussed over and over again in the past, without any effect on Python. ? You're right, of course. Because Python is in so many ways what I'm looking for in a language, I transform it in my mind to my own, personal ideal, close to the real existing language but with what I consider to be the imperfections removed. I'm not suggesting getting rid of explicit self, even in "Python 4000." Not because of the advantages it gives, which are some but don't outweigh the net loss in my ledger. It just wouldn't be Pythonic. I know its not a Pythonic thing to want. Thats my problem - because I have a largely Pythonic approach in some areas, it upsets me when there's a mismatch. So lets say I'm -1 for introducing it into a language and +0 for keeping it in Python now that its entrenched. If a lot of users keep bringing up something like this, well my attitude used to be the same as yours - "learn to love Python for what it is." Maybe > Let's just drop this, and if you want to complain next time, just complain > about something, that is really worth being complained about, like for > instance old and outdated modules in the standard library, or real > showstoppers in Python (e.g. the GIL). Its worth complaining about because I'm not just someone who has stumbled across Python after years of Java and PHP, and hasn't really grokked it, and has jumped on the net at once to start a flamewar. I'm someone who loves Python, uses it in preference to other languages, and have now returned to it after a bit of a break and its finally hit me over the head like a tonne of bricks "Hey, I can see exactly what all those internet trolls were talking about. This *is* a really annoying and silly state of affairs." I was trying not to change explicit self, or even != (which has a much better case.) I was trying to ask the community to reconsider a premise that the language is built around. Explicit is actually kinda annoying a lot of the time, viz., java. This is about social and philosophical adjustments, not technical ones. In reality? I'll just keep writing Python (hopefully enough so that explicit self become burned into muscle memory), and use other languages when necessary (no more C than I have to, looking forward to dabbling in Erlang soon, and one day overcoming the parentheses phobia enough to really tackle Lisp properly). When I'm old enough and wise enough, and have the time, energy and inclination, maybe I'll sit down and put a proper effort into designing and implementing a new language that bests suits my own particular style and needs. Just maybe it'll be good enough that smart people will rally to defend its design principles from people attacking them on the internet :-) From rajanikanth at gmail.com Tue Jul 8 20:55:52 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Tue, 8 Jul 2008 17:55:52 -0700 Subject: a simple 'for' question In-Reply-To: <48740BA8.5050605@hughes.net> References: <4874017D.2000401@umbc.edu> <84bdef3c0807081732q33b3bccdvc1d2c361d8c34d80@mail.gmail.com> <48740BA8.5050605@hughes.net> Message-ID: <84bdef3c0807081755v4407b84fl4339aaae2386e14d@mail.gmail.com> Thanks for correcting my typo norseman. Ben: I forgot a slash after the first string as norseman pointed out. Raj On Tue, Jul 8, 2008 at 5:51 PM, norseman wrote: > > Almost correct: There is a typo. Should read: > > for x in folders: > open('my/path/way/'+x+'/myfile.txt','r') > > > > > Rajanikanth Jammalamadaka wrote: >> >> Hi! >> >> Try this >> >> for x in folders: >> open('my/path/way'+x+'myfile.txt','r') >> >> Cheers, >> >> Raj >> >> On Tue, Jul 8, 2008 at 5:08 PM, Ben Keshet wrote: >>> >>> Hi fans, >>> >>> I want to use a 'for' iteration to manipulate files in a set of folders, >>> something like: >>> >>> folders= ['1A28','1A6W','56Y7'] >>> for x in folders: >>> print x # print the current folder >>> f = open('my/path/way/x/my_file.txt', 'r') >>> ... >>> >>> where 'x' in the pathway should iterate over '1A28','1A6W','56Y7'. How >>> should I identify 'x' in the pathway line as the same x that is iterating >>> over 'folders'? >>> >>> I am getting the following error: >>> >>> Traceback (most recent call last): >>> File >>> "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", >>> line 310, in RunScript >>> exec codeObject in __main__.__dict__ >>> File "C:\Linux\Dock_method_validation\myscripts\test_for.py", line 5, in >>> >>> f = open('c:/Linux/Dock_method_validation/x/receptor.mol2', 'r') >>> IOError: [Errno 2] No such file or directory: >>> 'c:/Linux/Dock_method_validation/x/receptor.mol2' >>> >>> I tired several variations: %x, 'x', "x", etc. all gave me similar >>> errors. >>> >>> Thanks for your help, >>> BK >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> >> > > -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From bignose+hates-spam at benfinney.id.au Fri Jul 11 02:23:16 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 11 Jul 2008 16:23:16 +1000 Subject: Python 3.0 and removal of the 'string' module References: <87wsjtqiyo.fsf@benfinney.id.au> Message-ID: <87iqvdq6qz.fsf@benfinney.id.au> Terry Reedy writes: > Ben Finney wrote: > > Can anyone see a reason to believe the above wiki page's statement > > about the 'string' module being removed? More to the point, can > > anyone see a reason why that statement should remain on that page? > > Removing string and moving the functionality elsewhere was considered, > but... [?] Thanks for the pointer. > Feel free to edit the wiki. Done. This is rather disappointing. Is that entire page suspect? It reads like a canonical list of things that will happen in Python 3000. What other long-obsolete information is there? I'm not about to go digging to find out. -- \ ?[T]he question of whether machines can think [?] is about as | `\ relevant as the question of whether submarines can swim.? | _o__) ?Edsger W. Dijkstra | Ben Finney From jkugler at bigfoot.com Mon Jul 28 15:22:19 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Mon, 28 Jul 2008 11:22:19 -0800 Subject: SimpleJson is slow .... is there any C Compiled version ? References: Message-ID: sanket wrote: > Hello All, > > I have created an API which fetches some data from the database. > I am using simplejson to encode it and return it back. > > Now the problem is that, this API is being called for millions of > times in a sequence. > I ran a profiler and saw that most of the time is consumed in encoding > my database results in to json. > So I was just wondering is there any C compiled version of simplejson > is available? > or any help regarding this issue would be appreciated. simplejson does have a C module. It is compiled automatically when installed. If you're installing on Windows, then it probably isn't getting compiled. j From patf at well.com Mon Jul 28 20:44:15 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 17:44:15 -0700 (PDT) Subject: Download excel file from web? References: <6f6vhlFa7anrU1@mid.uni-berlin.de> <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> <19fa0bb2-e101-47c9-84d4-1bf05d08ba39@b2g2000prf.googlegroups.com> Message-ID: On Jul 28, 5:39?pm, MRAB wrote: > On Jul 29, 12:41?am, "p... at well.com" wrote: > > > > > On Jul 28, 4:20?pm, "Guilherme Polo" wrote: > > > > On Mon, Jul 28, 2008 at 8:04 PM, p... at well.com wrote: > > > > On Jul 28, 3:52 pm, "Guilherme Polo" wrote: > > > >> On Mon, Jul 28, 2008 at 7:43 PM, p... at well.com wrote: > > > >> > On Jul 28, 3:33 pm, "p... at well.com" wrote: > > > >> >> On Jul 28, 3:29 pm, "Diez B. Roggisch" wrote: > > > > >> >> > p... at well.com schrieb: > > > > >> >> > > On Jul 28, 3:00 pm, "p... at well.com" wrote: > > > >> >> > >> Hi - experienced programmer but this is my first Python program. > > > > >> >> > >> This URL will retrieve an excel spreadsheet containing (that day's) > > > >> >> > >> msci stock index returns. > > > > >> >> > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > > > >> >> > >> Want to write python to download and save the file. > > > > >> >> > >> So far I've arrived at this: > > > > >> >> > >> [quote] > > > >> >> > >> # import pdb > > > >> >> > >> import urllib2 > > > >> >> > >> from win32com.client import Dispatch > > > > >> >> > >> xlApp = Dispatch("Excel.Application") > > > > >> >> > >> # test 1 > > > >> >> > >> # xlApp.Workbooks.Add() > > > >> >> > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > > > >> >> > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > > > >> >> > >> # xlBook = xlApp.ActiveWorkbook > > > >> >> > >> # xlBook.SaveAs(Filename='C:\\test.xls') > > > > >> >> > >> # pdb.set_trace() > > > >> >> > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > > > >> >> > >> excel? > > > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional') > > > >> >> > >> # test 2 - returns check = False > > > >> >> > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > > > >> >> > >> indexperf/excel? > > > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > > > >> >> > >> xlApp = response.fp > > > >> >> > >> print(response.fp.name) > > > >> >> > >> print(xlApp.name) > > > >> >> > >> xlApp.write > > > >> >> > >> xlApp.Close > > > >> >> > >> [/quote] > > > > >> >> > > Woops hit Send when I wanted Preview. ?Looks like the html [quote] tag > > > >> >> > > doesn't work from groups.google.com (nice). > > > > >> >> > > Anway, in test 1 above, I determined how to instantiate an excel > > > >> >> > > object; put some stuff in it; then save to disk. > > > > >> >> > > So, in theory, I'm retrieving my excel spreadsheet with > > > > >> >> > > response = urllib2.urlopen() > > > > >> >> > > Except what then do I do with this? > > > > >> >> > > Well for one read some of the urllib2 documentation and found the > > > >> >> > > Request class with the method has_data() on it. ?It returns False. > > > >> >> > > Hmm that's not encouraging. > > > > >> >> > > I supposed the trick to understand what urllib2.urlopen is returning > > > >> >> > > to me; rummage around in there; and hopefully find my excel file. > > > > >> >> > > I use pdb to debug. ?This is interesting: > > > > >> >> > > (Pdb) dir(response) > > > >> >> > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > > > >> >> > > 'code', ' > > > >> >> > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > > > >> >> > > 'readline', ' > > > >> >> > > readlines', 'url'] > > > >> >> > > (Pdb) > > > > >> >> > > I suppose the members with __*_ are methods; and the names without the > > > >> >> > > underbars are attributes (variables) (?). > > > > >> >> > No, these are the names of all attributes and methods. read is a method, > > > >> >> > for example. > > > > >> >> right - I got it backwards. > > > > >> >> > > Or maybe this isn't at all the right direction to take (maybe there > > > >> >> > > are much better modules to do this stuff). ?Would be happy to learn if > > > >> >> > > that's the case (and if that gets the job done for me). > > > > >> >> > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty > > > >> >> > clear on this: > > > > >> >> > """ > > > >> >> > This function returns a file-like object with two additional methods: > > > >> >> > """ > > > > >> >> > And then for file-like objects: > > > > >> >> >http://docs.python.org/lib/bltin-file-objects.html > > > > >> >> > """ > > > >> >> > read( ? [size]) > > > >> >> > ? ? ?Read at most size bytes from the file (less if the read hits EOF > > > >> >> > before obtaining size bytes). If the size argument is negative or > > > >> >> > omitted, read all data until EOF is reached. The bytes are returned as a > > > >> >> > string object. An empty string is returned when EOF is encountered > > > >> >> > immediately. (For certain files, like ttys, it makes sense to continue > > > >> >> > reading after an EOF is hit.) Note that this method may call the > > > >> >> > underlying C function fread() more than once in an effort to acquire as > > > >> >> > close to size bytes as possible. Also note that when in non-blocking > > > >> >> > mode, less data than what was requested may be returned, even if no size > > > >> >> > parameter was given. > > > >> >> > """ > > > > >> >> > Diez > > > > >> >> Just stumbled upon .read: > > > > >> >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > > > >> >> excel? > > > >> >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > > >> >> +25%2C+2008&export=Excel_IEIPerfRegional').read > > > > >> >> Now the question is: what to do with this? ?I'll look at the > > > >> >> documentation that you point to. > > > > >> >> thanx - pat > > > > >> > Or rather (next iteration): > > > > >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > > > >> > excel? > > > >> > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > > >> > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > > > >> > The file is generally something like 26 KB so specifying 1,000,000 > > > >> > seems like a good idea (first approximation). > > > > >> > And then when I do: > > > > >> > print(response) > > > > >> > I get a whole lot of garbage (and some non-garbage), so I know I'm > > > >> > onto something. > > > > >> > When I read the .read documentation further, it says that read() has > > > >> > returned the data as a string object. ?Now - how do I convince Python > > > >> > that the string object is in fact an excel file - and save it to disk? > > > > >> You don't need to convince Python, just write it to a file. > > > >> More reading for you:http://docs.python.org/tut/node9.html > > > > >> > pat > > > >> > -- > > > >> >http://mail.python.org/mailman/listinfo/python-list > > > > >> -- > > > >> -- Guilherme H. Polo Goncalves > > > > > OK: > > > > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > > > > excel? > > > > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > > > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > > > # print(response) > > > > f = open("c:\\msci.xls",'w') > > > > f.write(response) > > > > I would initially change that to: > > > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&...) > > > > f = open("c:\\msci.xls", "wb") > > > for line in response: > > > ? ? f.write(line) > > > f.close() > > > > and then.. > > > > > OK this makes the file, and there's a c:\msci.xls in place and it's > > > > about the right size. But whether I make the second param to open 'w' > > > > or 'wb', when I try to open msci.xls from the Windows file explorer, > > > > excel tells me that the file is corrupted. > > > > try it. > > > > > pat > > > > -- > > > >http://mail.python.org/mailman/listinfo/python-list > > > > -- > > > -- Guilherme H. Polo Goncalves > > > A simple f.write(response) does work (click on a single row in Excel > > and you get a single row). > > > But I can see that what you recommend Guilherme is probably safer - > > thanx. > > > pat > > If response contains a string then: > > for line in response: > ? ? f.write(line) > > will actually be writing the string one character at a time! Hmm. In this case, response was a string object. (that's what urllib2.urlopen().read() returns). My concern was with line ending characters (delimiters). I was thinking that if the string object doesn't contain line ending delimiters then maybe the for loop was better. Although that begs the question of how for line in reponse recognizes lines (as defined by line ending delimiters) in the first place. pat From timaranz at gmail.com Thu Jul 10 16:43:25 2008 From: timaranz at gmail.com (Tim Mitchell) Date: Fri, 11 Jul 2008 08:43:25 +1200 Subject: python scalability In-Reply-To: <799d6ad1-8424-4b2a-96a6-6df9a24060d9@27g2000hsf.googlegroups.com> References: Message-ID: <4876746D.3090003@gmail.com> Thanks for all the replies - they have all been helpful. On reflection I think our problems are probably design and people related. Cheers, Tim Michele Simionato wrote: > On Jul 10, 6:32 am, Tim Mitchell wrote: > >> Hi All, >> >> I work on a desktop application that has been developed using python and >> GTK (seewww.leapfrog3d.com). We have around 150k lines of python code >> (and 200k+ lines of C). >> > > We have bigger numbers than yours here (although not for a desktop > application) > and of course we have the problems of a large size application, but > they have > nothing to do with Python. The real problem are sociological, not > language-related. > Essentially, if a project takes 10+ years and 10+ people, with most of > the people > new, you have an issue, but this is independent from the language. > Python is helping > us at least because it is readable and the situation would be probably > be worse with > another language. But as I said the software development practices > used are more > important than the language in this context. > -- > http://mail.python.org/mailman/listinfo/python-list > From pruebauno at latinmail.com Wed Jul 30 10:30:29 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Wed, 30 Jul 2008 07:30:29 -0700 (PDT) Subject: Native Code vs. Python code for modules References: Message-ID: On Jul 29, 11:56 pm, koblas wrote: > better if there was a way that if I have an "interface compatible" > native (aka C) module that has better performance that there could be > a way that python would give it preference. > > e.g. > > import random(version=1.2, lang=c) > or > import random(version=1.2, lang=py) # use the python version by > default > or > import random # use the latest version in the "fastest" code (C > given preference) > > where there could be a nice set of "standard" key value pairs that > could provide addtional hints as to what language and version of a > library was to be used. I will only make a comment on automatic cModule importing. Some of what you are suggesting already happens (e.g. Elementree). In Python 3.0 more of the "legacy" modules (e.g. StringIO) should also work that way. I don't know what the current status for Pickle is because cPickle had some additional internal functionality not available in regular Pickle that Zope was dependent on. From sri_annauni at yahoo.co.in Mon Jul 28 03:33:43 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Mon, 28 Jul 2008 13:03:43 +0530 (IST) Subject: We programming Message-ID: <789038.29418.qm@web7906.mail.in.yahoo.com> Hi, Could someone?suggest?me better python modules for developing web programming related projects like web-pages download and uopload?? Thanks, Srini Explore your hobbies and interests. Go to http://in.promos.yahoo.com/groups/ From enleverlesX.XmcX at XmclaveauX.com Wed Jul 2 17:12:36 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Wed, 2 Jul 2008 23:12:36 +0200 Subject: Scripting SAP GUI (Windows) In-Reply-To: <6d15tpFaec4U1@mid.individual.net> References: <6d15tpFaec4U1@mid.individual.net> Message-ID: <486bf04d$0$843$ba4acef3@news.orange.fr> Hi! You can use Autoit. Bad "conception" language ; but many good tools, for identify windows, process, send keystrokes, emulate mouse, etc. (Autohotkey is make on Autoit 2 ; Autoit is actually in version 3). Good trick : Autoit-X is a COM server, with the most importants functions of Autoit (nor GUI) ; and Autoit-X can be driven from Python+PyWin32. *sorry for my bad english* Michel Claveau PS : http://www.autoitscript.com/autoit3/ (& look also forums) From timr at probo.com Fri Jul 25 01:59:54 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 25 Jul 2008 05:59:54 GMT Subject: pci card adjusting References: Message-ID: "Oguz Yarimtepe" wrote: > >I need to adjust the dimming property of my video card. There is >currently a written application called nvclock but it is not >supporting my card right now. So i need to implement the requiered >register jobs on the card. This is already done to a degree in C. But >i don't want to dive in to the C code right now. > >I prefer Python so may i implement such a feature by Python? Not easily, at least not without a helper DLL in C. And since the app won't be that large, you might as well just do it in C. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From grante at visi.com Tue Jul 22 14:17:10 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 22 Jul 2008 13:17:10 -0500 Subject: The Importance of Terminology's Quality References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: On 2008-07-22, Steve Schafer wrote: > On Tue, 22 Jul 2008 10:21:50 +0100, Martin Gregorie > wrote: > >>The first time I ran across the term "thunking" was when Windows 3 >>introduced the Win32S shim and hence the need to switch addressing between >>16 bit and 32 bit modes across call interfaces. That was called "thunking" >>by Microsoft and even they would surely admit it was a kludge. What?! Microsoft took a technical term and used it to mean something completely different than the widely used meaning? Never. > Win32s thunks are a completely different beast from the > original Algol 60 thunks. As far as I know, the first > published description of thunks was: > > Ingerman PZ (1961) Thunks: A way of compiling procedure statements with > some comments on procedure declarations, CACM 4:55-58. The Algol usage is certainly what we were taught back in the late 70's. I wasn't even aware that Microsoft had hijacked it to mean something else. -- Grant Edwards grante Yow! My polyvinyl cowboy at wallet was made in Hong visi.com Kong by Montgomery Clift! From aljosa.mohorovic at gmail.com Thu Jul 31 12:11:48 2008 From: aljosa.mohorovic at gmail.com (Aljosa Mohorovic) Date: Thu, 31 Jul 2008 09:11:48 -0700 (PDT) Subject: current week / weeks in year - best practice References: <6fdur9Fb0nvuU1@mid.uni-berlin.de> <2ac30ca6-554a-4b40-bdb8-a61f2311ab24@l42g2000hsc.googlegroups.com> Message-ID: On Jul 31, 5:42 pm, Aljosa Mohorovic wrote: > what if i know current context week = 20 (example), what would be the > best way to get datetime objects for first and last day of current > context week? > by "current context week" i don't mean current week for current year > but current week when program is iterating all weeks in year. if w = current context week and now is current datetime object this is how i calculate days: first_day = datetime.strptime("%s %s" % (now.year, str((w-1)*7)), "%Y %j") last_day = first_day + timedelta(days=6) any comments on this? Aljosa Mohorovic From straton at lampsacos.demon.co.uk Mon Jul 7 06:51:42 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Mon, 07 Jul 2008 11:51:42 +0100 Subject: python beginner In-Reply-To: <1cd8ffae-62a7-4cfb-b3ab-61c7004841c9@8g2000hse.googlegroups.com> References: <1cd8ffae-62a7-4cfb-b3ab-61c7004841c9@8g2000hse.googlegroups.com> Message-ID: cna wrote: > Hi all and one, > how may i learn python. is there any other website except python.org For several video series, follow the link from python.org to the ShowMeDo site. http://www.python.org/doc/av/5minutes/ From hv at tbz-pariv.de Wed Jul 30 09:36:46 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Wed, 30 Jul 2008 15:36:46 +0200 Subject: Standard module for parsing emails? In-Reply-To: References: Message-ID: <6fb93eFap7j5U1@mid.individual.net> Phillip B Oldham schrieb: > Is there a standard library for parsing emails that can cope with the > different way email clients quote? What do you mean with "quote" here? 1. Encode utf8/latin1 to ascii 2. Prefix of quoted text like your text above in my mail Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From jeff.dyke at gmail.com Mon Jul 21 12:31:12 2008 From: jeff.dyke at gmail.com (Jeff Dyke) Date: Mon, 21 Jul 2008 12:31:12 -0400 Subject: imported module no longer available In-Reply-To: <8496caf30807210928m27456a1ex747221ea829409a6@mail.gmail.com> References: <8496caf30807210656y3d8467eer83a953e7c37e556c@mail.gmail.com> <8496caf30807210928m27456a1ex747221ea829409a6@mail.gmail.com> Message-ID: <8496caf30807210931y27f5a198q195c9fb752eea5f3@mail.gmail.com> my apologies, to Fredrick, my response when solely to him. reply below, hopefully keeping thread intact. On Mon, Jul 21, 2008 at 12:28 PM, Jeff Dyke wrote: > On Mon, Jul 21, 2008 at 10:19 AM, Fredrik Lundh wrote: >> Jeff Dyke wrote: >> >>> I've come across an error that i'm not yet able to create a test case >>> for but wanted to get see if someone could shed light on this. >>> >>> I have imported a module at the top of my file with >>> import mymodulename >>> >>> this module is used many times in the current file successfully, but >>> then I attempt to use it one more time and get: UnboundLocalError: >>> local variable 'mymodulename' referenced before assignment >> >> Let me guess: you've done >> >> def myfunc(): >> print mymodulename >> import mymodulename > > actually no, the only things in that fucntion were. > print globals().keys() - i see it here > print mymodulename - it fails here. > > the `import mymodulename` statement is at the very top of the file. > > plus the processing that was attempted after. in fact in the calling > method i was able to execute print mymodulename and it printed the > expected python output. > >> >> or something similar? Getting an exception in this case is the excepted >> behaviour; the reason being that a variable in a block only belongs to a >> single scope. for the entire block. For details, see: >> >> http://docs.python.org/ref/naming.html >> >> Especially this section: >> >> "If a name binding operation occurs anywhere within a code block, all uses >> of the name within the block are treated as references to the current block. >> This can lead to errors when a name is used within a block before it is >> bound. This rule is subtle. Python lacks declarations and allows name >> binding operations to occur anywhere within a code block. The local >> variables of a code block can be determined by scanning the entire text of >> the block for name binding operations." >> >> To fix this, mark the name as global: >> >> def myfunc(): >> global mymodulename # I mean the global name! >> print mymodulename >> import mymodulename > > > So i went back to check that the name 'mymodulename' was not getting > overwritten by something else and the error went away. I've been > working on something else entirely for the past few hours and have > changed none of the code...and now it works. which is even more > troublesome then the error itself. > > Follow on question. If this name, mymodulename, was imported in some > other module.fucntion local to a function like > def anotherfunc(): > import mymodulename > > would that remove it from the globals() and save it to a locals() ? I > would assume the answer to be no. > > Thanks for you response. > Jeff > > >> >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > From ivan at datasyncorp.com Thu Jul 3 16:24:08 2008 From: ivan at datasyncorp.com (Ivan Ven Osdel) Date: Thu, 3 Jul 2008 15:24:08 -0500 (CDT) Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: <552487307.956521215116093518.JavaMail.root@saturn.datasyncintra.net> Message-ID: <1020285372.957161215116648910.JavaMail.root@saturn.datasyncintra.net> >From: "Fuzzyman" >To: python-list at python.org >Sent: Thursday, July 3, 2008 12:41:11 PM GMT -06:00 US/Canada Central >Subject: Re: Freesoftware for auto/intelligent code completing in Python > >On Jul 2, 9:33?am, Ali Servet D?nmez wrote: > On Jul 1, 12:15?am, Fuzzyman wrote: > > > > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > I don't want to be so mean here, but how hard it could be be writing a > > > freesoftware which would automatically/intelligently auto complete > > > Python code? (I mean something that really does the job, like > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > name it, but just don't give me PyDev please...) > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > missing here? > > > > Could someone please point me out something that I'm really missing > > > which is already present in the wild, otherwise I'd like discuss with > > > whoever is willing to help me to get this thing done. I made my mind > > > and I could volunteer to make this happen as thesis project for my > > > incoming graduation in the next year. > > > > Regards you all, > > > Ali Servet D?nmez > > > Vim, Emacs, Wing, Komodo, ... more? > > > Yeah, I guess you're missing something. :-) > > > MichaelFoordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > I've checkout Wing IDE's license and it doesnt' seem to be a > freesoftware; am I wrong? > > >Wing 101 is free. The software is good enough though that it is worth >supporting its development by paying for it. > >Michael Foord >-- >http://www.ironpythoninaction.com/ >http://www.trypython.org/ According to the site, Wings 101 doesn't support "Auto-completion for Python and extension modules" but I agree that Wings is worth it if he (or his company) can afford the license(s). If not then he should at least contribute time or money to one of the free (as in free speech, not free beer) alternatives. Ivan Ven Osdel http://www.datasyncsuite.com/ From g.threepwood at gmail.com Fri Jul 18 11:48:50 2008 From: g.threepwood at gmail.com (C Martin) Date: Fri, 18 Jul 2008 08:48:50 -0700 (PDT) Subject: Using Tcl extensions with Python? References: <6f09cdf7-1156-4f41-af5f-c8e5b99eab2d@b1g2000hsg.googlegroups.com> Message-ID: <50f3b23a-127f-429d-b86e-ca9bc163eb4b@i20g2000prf.googlegroups.com> On Jul 17, 5:18 pm, "Guilherme Polo" wrote: [snip] > And.. for tkpng specifically, you won't need tk.call to use it, you > just need to create your images using Tkinter.PhotoImage with a "png" > type. Thank you Guilherme, that's all great info. > Thomas Troeger wrote: > ARGH, Tcl!!! ;-) I know that's not the question, but do you know PIL > (http://www.pythonware.com/products/pil)? Yes, I know about PIL. However, I need use PNGs with a full alpha channel. PIL only seems support simple transparency, whereas TkPNG seems to work as expected with them. If I am incorrect in this, then please let me know how to use it! Thanks. From jeremy at 54oaks.com Wed Jul 2 18:38:50 2008 From: jeremy at 54oaks.com (Jeremy Link) Date: Wed, 2 Jul 2008 15:38:50 -0700 Subject: libffi and ARM support for Python Message-ID: <009101c8dc94$66bd9470$8101a8c0@bocaron> The latest version of libffi is supposed to support the ARM processor. Has anyone taken this and folded into Python v2.5.2 so that we have support for this? I've tried but have run into a few issues: 1. Needed to enable FFI_CLOSURES 2. Added FFI_TRAMPOLINE_SIZE (set it to 32, not sure what this should actually be) 3. still missing ffi_prep_closure (it is not defined in arm/ffi.c) Any ideas or added info would be appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at REMOVE.THIS.cybersource.com.au Tue Jul 29 04:32:19 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 08:32:19 GMT Subject: Is it allowed to use function results as default arguments ? References: <488E2BF1.8020003@gmail.com> Message-ID: On Tue, 29 Jul 2008 09:43:26 +0200, Stef Mientki wrote: > about '.' being the current directory, well I think windows was thrown > at the market about 25 years ago, and since then we don't use '.' > anymore ;-) No, even Windows uses '.' as the current directory -- at least XP does, I haven't tried Vista. However, old Classic Mac OS (pre OS-X) used ':' for the current directory, so dot isn't universal. -- Steven From mrkafk at gmail.com Thu Jul 17 10:51:02 2008 From: mrkafk at gmail.com (mk) Date: Thu, 17 Jul 2008 16:51:02 +0200 Subject: storing references instead of copies in a dictionary In-Reply-To: <19eba037-f7e2-4934-a03b-f1956db8e999@a1g2000hsb.googlegroups.com> References: <19eba037-f7e2-4934-a03b-f1956db8e999@a1g2000hsb.googlegroups.com> Message-ID: Uwe Schmitt wrote: > Python stores references in dictionaries and does not copy ! (unless > you explicitly use the copy module) ! > > In your case the entry in the dictionary is a reference to the same > object which f1 references, that is the object at 0xb7f0ba04. > > If you now say "f1=...:" then f1 references a new object > at 0xb7f0b994, and the entry in your dictionary still references > the "old" object at 0xb7f0ba04. Erm, I theoretically knews that, I guess I suffered temporary insanity when I wrote "copies" of objects. To me it seems that Python actually stores _labels_ referencing _objects_. Here, the problem was that the label in the dictionary led to the "old" object. > I do not know any method to automatically update your dictionary > as there is no possibility to overload the assignement operator "=". > But may be somebody can teach me a new trick :-) Theoretically I could define a class inheriting from dictionary and define a property with a setter (and getter). But I would still have to update the attribute manually, so plain dictionary is just as good. From aaron.hildebrandt at gmail.com Wed Jul 23 15:06:02 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 23 Jul 2008 12:06:02 -0700 (PDT) Subject: Using variables across modules References: <855136ce-6c70-40ac-a462-dc0bbfa1fc3a@b2g2000prf.googlegroups.com> <121c5161-9485-4d6a-a447-9f9dd4227bac@d77g2000hsb.googlegroups.com> Message-ID: > Just wirte test code ! variables.py: myvar = 5 print myvar foo.py: from variables import * def PrintVar(): print myvar bar.py: from variables import * from foo import * print myvar myvar = 2 print myvar PrintVar() "python bar.py" output: 5 5 2 5 ... which is what I was expecting, but not what I want. Obviously, each import is creating its own instance of the variable. What I need is a way to change myvar from within "bar.py" so that PrintVar() returns the new value, even though it's in a different module. From aahz at pythoncraft.com Mon Jul 21 00:03:57 2008 From: aahz at pythoncraft.com (Aahz) Date: 20 Jul 2008 21:03:57 -0700 Subject: Any Game Developers here? References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: In article , Python Nutter wrote: > >There are two books I know of currently in print on game programming, >both use PyGame as it was out first. One book is horrible and only >worth for cleaning yourself up after you use the bathroom. The second >is really well written (The L express game programming book) and >highly recommended if you need to get some basic game design and >programming under your belt in Python. Unfortunately, there are some serious bugs in the L-line book because the author doesn't really understand Python. (I know this because I was one of the tech editors.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From arslanburney at gmail.com Thu Jul 17 04:11:18 2008 From: arslanburney at gmail.com (J-Burns) Date: Thu, 17 Jul 2008 01:11:18 -0700 (PDT) Subject: Rotating a cube References: Message-ID: <3d47df08-9734-4e0f-96ad-37da445b4faf@34g2000hsh.googlegroups.com> On Jul 17, 12:53 pm, Fredrik Lundh wrote: > J-Burns wrote: > > Is there a built in Python function for this? > > for answering questions that have nothing to do with programming, and > looks quite a bit like homework? don't think they've added that one yet. > > maybe you should look for a geometry newsgroup/forum? > > I meant to ask how would you do this in Python... :S From cjw at ncf.ca Sat Jul 26 17:03:49 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 26 Jul 2008 17:03:49 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> Message-ID: <488B9135.3010308@ncf.ca> Russ P. wrote: >> If, as I wrote, you permit the omission of "self" in method signatures >> defined within class definitions, then you could still insist on >> instance attribute qualification using "self" - exactly as one would >> when writing Java according to certain style guidelines. > > I'm not sure exactly what people mean here by allowing "self" to be > "omitted" in method signatures. If it is omitted, then it seems to me > that a place holder would be needed to the interpreter that the first > argument is not just another name for "self." > > In an earlier post on this thread (don't feel like looking it up at > the moment), someone suggested that member data could be accessed > using simply ".member". I think he might be on to something. The dot > is a minimal indicator that the data is a class member rather than > just local. However, a placeholder is still needed in the signature. > > So why not allow something like this?: > > class MyClass: > > def func( , xxx, yyy): > > .xxx = xxx > > local = .yyy > > The "self" argument is replaced with nothing, but a comma is used as a > placeholder. > (+1) but why retain the leading comma in the argument list? Colin W. From jjbutler88 at gmail.com Sun Jul 13 13:22:16 2008 From: jjbutler88 at gmail.com (jjbutler88 at gmail.com) Date: Sun, 13 Jul 2008 10:22:16 -0700 (PDT) Subject: Socket problems Message-ID: I am trying to write a simple python IRC client, roughly following this guide: http://www.devshed.com/c/a/Python/Python-and-IRC/ I have written some code, which uses the same commands as the guide, but I get this error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/threading.py", line 486, in __bootstrap_inner self.run() File "pythonirc.py", line 31, in run self.sock.send('NICK %s\r\n') % self.nick AttributeError: send Here is my code so far: [code] #!/usr/bin/env python from socket import * from threading import Thread import sys class IRCBot(Thread): def __init__(self, host, room, nick, port=6667, ssl=0): Thread.__init__(self) self.host = host self.port = port self.ssl = ssl self.room = room self.nick = nick self.sock = socket(AF_INET, SOCK_STREAM) def run(self): print "Connecting..." try: self.sock.connect((self.host, self.port)) except: print "Could not connect to %s" % self.host sys.exit(1) if self.ssl: try: self.sock = ssl(self.sock) except: print "Server does not suport SSL" sys.exit(1) self.sock.send('NICK %s\r\n') % self.nick self.sock.send('USER PyIRC PyIRC PyIRC :Python IRC\r\n') self.sock.send('JOIN #%s\r\n') % self.room while True: data = self.sock.recv(4096) if data.find('PING') != -1: self.sock.send('PONG' + data.split()[1]+'\r\n') print data def close(self): self.sock.send('PART #%s\r\n') % self.room self.sock.send('QUIT\r\n') self.sock.shutdown(SHIT_RDWR) self.sock.close() IRCBot('irc.psych0tik.net','hbh', 'pythonircclient',6697,1).start() [/code] Anyone know why it might be doing this? Config problem? Thanks in advance, Jon From larzluv at hotmail.com Thu Jul 17 12:22:44 2008 From: larzluv at hotmail.com (Larry Hale) Date: Thu, 17 Jul 2008 09:22:44 -0700 (PDT) Subject: Python Behind a Squid Corporate Proxy on Windows Message-ID: <7b541a3b-846f-496a-aee1-d5719217e011@m45g2000hsb.googlegroups.com> Greetings, Pythonistas! My employer has a Squid Proxy between my Python programs and The Internet. I've searched high-and-low, and can only find examples online of how to do basic authentication to connect TO an external Web Server, but not how to go THROUGH a (corporate) Proxy, thus my question here. I've tried all sorts of permutations based on my findings, but (obviously) nothing's working for me. I've come across conflicting information, including that urllib2 can't/won't do what I'm needing, though this statement was a couple years old. I'm running Python 2.5 on Windows XP SP2 64-bit. The Proxy is Squid (don't know what version, but can find out if this is relevant). urllib2 grabs the Proxy info fine: 'http': 'http://webfilter.xyz.local: 3128' (.getproxies()). There's the obvious necessity of telling "something" my ID/pass *somehow*. An example of one iteration: ###################### import urllib2 proxy_handler = urllib2.ProxyHandler( { "http": "http:// myusername:@webfilter.xyz.local:3128" } ) opener = urllib2.build_opener( proxy_handler ) urllib2.install_opener( opener ) response = opener.open( "http://python.org" ) print response ###################### I've tried situations using HTTPPasswordMgrWithDefaultRealm and its add_password method, also to no avail. (Again, THIS sort of thing seems related to the -external- Web Server, _not_ going *through* a Proxy. 'Course, I could be wrong. But if I am, I couldn't get this to work, either. ;) I've looked at what's happening with Wireshark; Py/my program/urllib2 makes the initial page request, Proxy replies HTTP Error 407: Proxy Authentication Required, and Py/my program/urllib2 simply stops at that, reporting the message/error. Please forgive me; I've been programming in Python for a few years now, but never had to deal with Web Proxies. I *have* tried to RTFMs, but the "documentation" for non-basic stuffs with urllib2 is... uh... well, I'm sure ye olde pro's know... :) Cheers, and *any* help would be appreciated! -Larry From __peter__ at web.de Fri Jul 18 06:05:53 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 12:05:53 +0200 Subject: sub typing built in type with common attributes. Am I right? References: <4d9c4b74-9c28-4b98-afe7-9eb774655c3a@v21g2000pro.googlegroups.com> <98c3de7d-f167-48f9-9736-b09938d96b92@f40g2000pri.googlegroups.com> Message-ID: King wrote: > My mistake... > The correct __slots__ is like: > __slots__ = ['_Attribute_name', '_Attribute_type', '_Attribute_range', > 'label'] > > Could you please suggest an alternative or code improvement for the > matter. How about class AttributesMixin(object): """Warning: If you change name, type, or range of an existing object your computer will explode and you will have noone else to blame. """ def __init__(self, name=None, type=None, range=None, label=None): self.name = name self.type = type self.range = range self.label = label class Float(float, AttributesMixin): pass class Int(int, AttributesMixin): pass Now go and write something useful :-) Peter From keith.hughitt at gmail.com Wed Jul 16 14:00:50 2008 From: keith.hughitt at gmail.com (Keith Hughitt) Date: Wed, 16 Jul 2008 11:00:50 -0700 (PDT) Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> Message-ID: <41d4ffc7-7fd5-4202-92ea-132c7d4f5cd4@s50g2000hsb.googlegroups.com> Thanks Gabriel! That helps clear things up for me. The above method works very well. I only have one remaining question: How can I pass a datetime object to MySQL?' So far, what I've been doing is building the query as a string, for example: query = "INSERT INTO image VALUES(%d, %d, %s, '%s')" % (id, meas, date, 'jpg') cursor.execute(query) This works fine for regular datetime objects, which are passed as strings similar to: "2003-10-01 00:00:00." When incorporating a timezone, however, the resulting string is of the form "2003-10-01 00:00:00+00:00." Unfortunately, MySQL does not recognize the offset. I know you said you don't use MySQL, but how would you do something execute a similar query on the database you normally interface with? Thanks, Keith On Jul 15, 12:04?am, "Gabriel Genellina" wrote: > En Mon, 14 Jul 2008 12:06:30 -0300,KeithHughitt ? > escribi?: > > > > > On Jul 12, 12:52?am, "Gabriel Genellina" > > wrote: > >> En Fri, 11 Jul 2008 15:42:37 -0300,KeithHughitt ? > >> escribi?: > > >> > I am having a little trouble figuring out how to convert a python > >> > datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would > >> > like to create a UTC date so that when I send it to MySQL (which > >> > treats all dates at local dates by default), it will already have > >> > incorporated the proper UTC offset. I've tried looking through the > >> > docshttp://python.active-venture.com/lib/datetime-datetime.html), but > >> > have not had any luck. > > >> You have to use a "timezone aware" datetime object. If all you want is ? > >> to ? > >> store an UTC date, the tzinfo demo classes that you can find in the ? > >> Python ? > >> docs at may be enough. > > > Thanks for advice Gabriel. I downloaded the tzinfo demo class, saved > > it as > > UTC.py and imported it. I'm still not exactly sure how to use it > > though. It looks like > > the file already creates an instance of the UTC tzinfo class (line 20: > > "utc = UTC()"), > > however, when I try to test it out in the interpreter, it cannot be > > found. I'm new > > to python, and there is probably something obvious I'm missing, but do > > you have any ideas? > > The import statement in Python doesn't behave the same way as similar ? > statements in other languages - and it may be confusing you. I'll try to ? > explain it using this example. > You have: > - a *file* UTC.py, containing the source code for the *module* UTC. It ? > contains: > - a *class* definition (UTC) and > - an *instance* of that class, utc. > > --- begin UTC.py ---If you pass a "timezone aware" datetime object as a SQL parameter > class UTC(tzinfo): > ? ?... > utc = UTC() > ... > --- end UTC.py --- > > > Here is what I'm attempting: > > > ============ output begin ============= > > > Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) > > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> import datetime, UTC > > Here you have imported the *module* UTC. That is, the name UTC now refers ? > to a newly created module just loaded from the UTC.py file. > > >>>> t = datetime.datetime(2008, 7, 14, 00, 00, 00, UTC()) > > Traceback (most recent call last): > > ? File "", line 1, in > > TypeError: 'module' object is not callable > > The error comes from UTC(): UTC is a module, UTC() is attempting to "call" ? > it, and since modules are not callable objects, we get a TypeError. > > >>>> utc > > Traceback (most recent call last): > > ? File "", line 1, in > > NameError: name 'utc' is not defined > > The *only* name we have imported so far is UTC - the module. Lowercase utc ? > isn't defined. > > >>>> utc = UTC() > > Traceback (most recent call last): > > ? File "", line 1, in > > TypeError: 'module' object is not callable > > Same as above... > > Ok, how to solve it? We know that UTC refers to the *module* with the same ? > name. To get the *class* inside that module, use UTC.UTC - try again in ? > the interpreter. To create a new instance of that class, you can use ? > UTC.UTC(). To obtain the instance already created in the UTC module, use ? > UTC.utc > > **OR** > > Import those names explicitely: > > py> from UTC import UTC > > In this case the name UTC refers to the *class* inside the module. > In this particular example it may be confusing - both have the same name. ? > Another example from the standard library: the poplib module contains a ? > POP3 class, so after executing this line: > > py> from poplib import POP3 > > the name POP3 refers to that class. The poplib module itself isn't ? > directly available. > Back to the UTC module, you could use: > > py> from UTC import utc > > and now utc refers to the *instance* already created inside the module. ? > This last form may be the most convenient in your case: > > py> import datetime > py> from UTC import utc > py> print datetime.datetime(2008, 7, 14, 20, 30, 0, 0, utc) > 2008-07-14 20:30:00+00:00 > > -- > Gabriel Genellina From __peter__ at web.de Wed Jul 30 13:23:46 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 Jul 2008 19:23:46 +0200 Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: <2a703a46-75bc-4228-95d1-05a4e6030b40@f63g2000hsf.googlegroups.com> <26c2fe8e-d464-44f0-8e57-3b8e82248691@x35g2000hsb.googlegroups.com> Message-ID: Paul Boddie wrote: > On 30 Jul, 18:17, Simon Willison wrote: >> >> Some very useful people in #python on Freenode pointed out that my bug >> occurs because I'm trying to display things interactively in the >> console. Saving to a variable instead fixes the problem. > > What's strange about that is how the object is represented when > displayed: > > ('CHARACTERS', ) > > Here, there's no attempt made to encode \u2019 as an ASCII byte > sequence. Does the OS X version of Python do anything special with > string representations? I'm on Kubuntu 7.10 and see the same error as Simon. The problem is in the minidom.CharacterData class which has the following method def __repr__(self): data = self.data if len(data) > 10: dotdotdot = "..." else: dotdotdot = "" return "" % ( self.__class__.__name__, data[0:10], dotdotdot) The data attribute is a unicode instance... Peter From castironpi at gmail.com Sat Jul 12 14:44:40 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 12 Jul 2008 11:44:40 -0700 (PDT) Subject: why is "self" used in OO-Python? References: Message-ID: On Jul 12, 1:01?pm, Duncan Booth wrote: > ssecorp wrote: > > 1. Why do I have to pass self into every method in a class? Since I am > > always doing why cant this be automated or abstracted away? > > Are the instances where I won't pass self? > > I imagine there is some tradeoff involved otherwise it would have been > > done away with. > > When you define a method in Java there is an implicit 'this' passed to the > method. Python cannot tell when you define a function whether the function > is going to be used as a function, an instance method, a class method, a > static method or something else (or all of the above). Consider this: > > The dynamic nature of Python means you can lift a method out of a class and > re-use it in a different context or inject a function into a class as a > method. There are two ways to handle this sort of code: javascript has an > implied 'this' for everything whether a function or what passes for a > method, Python makes it explicit. > > > 2. self.item instead of getters and setters. I thought one of the main > > purposes of OO was encapsulation. Doesn't messing with internal object- > > representations break this? > > That is correct. Some languages (e.g. Java) don't allow you to encapsulate > attributes so you have to write getter and setter methods. If you expose an > attribute in Java then you cannot later insert some code into the lookup or > override the set without getting all users of your code to change the way > they access the value. This is bad. > > Other languages (e.g. Python, C#) allow you to intercept the attribute > lookup so you can change a plain attribute into a property without > requiring the users of your class alter their source code. With C# I > think they would still need to recompile their code so it may be more > appropriate to avoid using public attributes if you are producing a class > library for widespread reuse, but with Python there is no difference to the > user of your class whether they are accessing an attribute or a property. > > Sadly a lot of Java programmers mistake the limitations of their language > for rules of OO programming, and worse this has spread from Java into other > languages where these restrictions no longer need apply. > > Your Stack class is a bad example: the stack attribute is purely internal > so you wouldn't want to expose it as part of the public interface. Consider > instead something like: > > class AddressBookEntry(object): > ? ? def __init__(self, name, phone): > ? ? ? ? self.name = name > ? ? ? ? self.phone = phone > > ? ? @property > ? ? def phone(self): > ? ? ? ? return self._phone > > ? ? @property.setter > ? ? def phone(self, number) > ? ? ? ? validatephonenumber(number) # may throw an exception > ? ? ? ? ? self._phone = number > > If later you want to add some processing to the name attribute it is easy, > but putting in dummy property getter/setter methods before you need them > would be pointless. Part of the value of accessor methods appears when you're changing class definitions, or changing classes, after you've already started to use them-- the same interface with a different implementation. In the AddressBookEntry example, if you changed a pickled dictionary to a shelf, you could reimplement the class and reprocess stored data files, all without changing the code that uses the class-- especially if there's a lot of it, or you don't know where it all is. Nothing stops you from using accessor methods to offer encapsulation, and permit back-end changes later. But, nothing in Java stops you from declaring class members public. Depending on your development process, data hiding may enforce distribution of labor a little better, resulting in errors in Java where Python relies only on discipline. If you're checking for value validation, you can write a custom setter, regardless of language. Python doesn't break encapsulation; you do. In the Stack example, you have more options than you've mentioned. Can you inherit from list directly? Can you delegate using reflection? Are you studying this example specifically, or the class model generally? If you're choosing a language, be careful that stricter enforcement doesn't cause harder-to-find bugs. Useful link: Section 9.4 in the docs: http://docs.python.org/tut/node11.html From JordanNealBerg at gmail.com Thu Jul 10 13:52:53 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Thu, 10 Jul 2008 10:52:53 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: <8feab8ce-1e09-4438-b00a-3b31956c56af@k37g2000hsf.googlegroups.com> Message-ID: <5c521979-aaf0-4b4b-9673-671a978d050a@j22g2000hsf.googlegroups.com> On Jul 10, 1:35?pm, MRAB wrote: > On Jul 10, 4:56?am, Jordan wrote: > > > > > I am trying to rewrite some C source code for a poker hand evaluator > > in Python. ?Putting aside all of the comments such as just using the C > > code, or using SWIG, etc. ?I have been having problems with my Python > > code not responding the same way as the C version. > > > C verison: > > > unsigned find_fast(unsigned u) > > { > > ? ? unsigned a, b, r; > > ? ? u += 0xe91aaa35; > > ? ? u ^= u >> 16; > > ? ? u += u << 8; > > ? ? u ^= u >> 4; > > ? ? b ?= (u >> 8) & 0x1ff; > > ? ? a ?= (u + (u << 2)) >> 19; > > ? ? r ?= a ^ hash_adjust[b]; > > ? ? return r; > > > } > > > my version (Python, hopefully ;)): > > > def find_fast(u): > > ? ? u += 0xe91aaa35 > > ? ? u ^= u >> 16 > > ? ? u += u << 8 > > ? ? u ^= u >> 4 > > ? ? b ?= (u >> 8) & 0x1ff > > ? ? a ?= (u + (u << 2)) >> 19 > > ? ? r ?= a ^ hash_adjust[b] > > ? ? return r > > > As far as I understand the unsigned instructions in C just increase > > amount of bytes the int can hold, and Python automatically converts to > > longs which have infinite size when necessary, so I am not sure why I > > am getting different results. > > > I assume that I am missing something fairly simple here, so help a > > n00b out if you can :) > > > Thanks in advance, > > > jnb > > You want to restrict the values to 32 bits. The result of + or << may > exceed 32 bits, so you need to mask off the excess bits afterwards. > > def find_fast(u): > ? ? mask = 0xffffffff > ? ? u ?= (u + 0xe91aaa35) & mask > ? ? u ^= u >> 16 > ? ? u ?= (u + (u << 8)) & mask # can get away with only 1 mask here > ? ? u ^= u >> 4 > ? ? b ?= (u >> 8) & 0x1ff > ? ? a ?= ((u + (u << 2)) & mask) >> 19 # can get away with only 1 mask > here > ? ? r ?= a ^ hash_adjust[b] > ? ? return r > > HTH Well, I guess there are two problems....the masking and the fact the in C it seems to for some reason overflow and become a negative value....still not sure why it does it....So the code with just masking doesn't work, you still need some sort of weird inversion like the ~(0xFFFFFFFF - u).....weird anyone? haha From waldemar.rymarkiewicz at gmail.com Wed Jul 23 09:34:16 2008 From: waldemar.rymarkiewicz at gmail.com (waldek) Date: Wed, 23 Jul 2008 06:34:16 -0700 (PDT) Subject: python.exe crash and ctypes use Message-ID: Hi, I have module A.py and B.dll which exports C functions by cdecl_ In A.py I pass callback (py callable) to dll. Next, thread inside dll simply calls my callback (in a loop). After few secs I got crash of python.exe. How to debug it? I'm using winxp and py 2.5.2 =========================== def mycallback(data, size) return 0 CBFUNC = CFUNCTYPE(c_int,POINTER(c_int), c_int) dll = cdll.mydll if dll.RegisterCallback(CBFUNC(mycallback)) != 0: print "Error." =========================== From circularfunc at yahoo.se Tue Jul 29 18:53:47 2008 From: circularfunc at yahoo.se (defn noob) Date: Tue, 29 Jul 2008 15:53:47 -0700 (PDT) Subject: How can I check nbr of cores of computer? Message-ID: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> How can I check how many cores my computer has? Is it possible to do this in a Python-app? From niklas.norrthon at hotmail.com Wed Jul 23 16:21:04 2008 From: niklas.norrthon at hotmail.com (Niklas Norrthon) Date: Wed, 23 Jul 2008 13:21:04 -0700 (PDT) Subject: concatenate the elements in each list of a list of lists References: <72c425b7-d9c2-4a61-8b7f-075eae14e703@x41g2000hsb.googlegroups.com> Message-ID: <0494db0a-d58d-48dc-bea1-36c1997f5384@26g2000hsk.googlegroups.com> On 23 Juli, 17:33, antar2 wrote: > I already asked a similar question, but encounter problems with > python... > How can I concatenate the elements in each list of a list of lists > > list_of_listsA = > > [['klas*', '*', '*'], > ['mooi*', '*', '*', '*'], > ['arm*', '*', '*(haar)']] > > wanted result: > > list_of_listsA = > > [['klas* * *'] > ['mooi* * * *'] > ['arm* * *(haar)']] > > Thanks a lot ! wanted_result = [[item] for item in map(' '.join, list_of_listsA)] From tonal at promsoft.ru Thu Jul 17 03:42:17 2008 From: tonal at promsoft.ru (Alexandr N Zamaraev) Date: Thu, 17 Jul 2008 14:42:17 +0700 Subject: Getting a unknown word out of a list with no spaces In-Reply-To: <18503144.post@talk.nabble.com> References: <18502758.post@talk.nabble.com> <487EF593.5060505@promsoft.ru> <18503144.post@talk.nabble.com> Message-ID: <487EF7D9.8010400@promsoft.ru> Alexnb wrote: >>>>> s = '--a href="/browse/brick"--brick--/a--' >>>>> s >> '--a href="/browse/brick"--brick--/a--' >>>>> ''.join('<%s>' % l if i % 2 == 1 else l for i, l in >> enumerate(s.split('--'))) >> ' /browse/brick brick ' > > I'm sorry, I don't think I was being clear. I replaced the <'s with -- so it > would post online w/o actually making a link. I just need to know how to get > the "brick" out. 1) if string really '--a href="/browse/brick"--brick--/a--' >>> s.split('--', 3)[2] brick 2) if string 'brick' >>> s.split('>', 1)[1].split('<')[0] brick From wolfram.hinderer at googlemail.com Wed Jul 30 17:08:01 2008 From: wolfram.hinderer at googlemail.com (wolfram.hinderer at googlemail.com) Date: Wed, 30 Jul 2008 14:08:01 -0700 (PDT) Subject: seemingly simple list indexing problem References: <999589a9-e1bb-4a64-801c-74ce060bc0c6@i24g2000prf.googlegroups.com> Message-ID: On 29 Jul., 01:05, Raymond Hettinger wrote: > [Ervan Ensis] > > > I have a list like [108, 58, 68]. I want to return > > the sorted indices of these items in the same order > > as the original list. So I should return [2, 0, 1] > > One solution is to think of the list indexes > being sorted according the their corresponding > values in the input array: > > >>> s = [ 108, 58, 68 ] > >>> sorted(range(len(s)), key=s.__getitem__) > > [1, 2, 0] > To get the desired output you have to apply it twice: >>> sorted(range(len(s)), key=sorted(range(len(s)), key=s.__getitem__).__getitem__) [2, 0, 1] Wolfram From pladow at gmail.com Wed Jul 2 11:16:05 2008 From: pladow at gmail.com (Peter LaDow) Date: Wed, 2 Jul 2008 08:16:05 -0700 Subject: AttributeError with embedded Python Message-ID: <9e264e780807020816h35aacf74rb190f5990dc95850@mail.gmail.com> I posted this on c.l.p, but with the high level of traffic there, I thought I'd try to post here as well. I've embedded Python in an extension for a program we are using here at work. And I'm a bit stumped as to why I am getting an AttributeError only in the embedded Python. First, a bit of what I am doing. We use a simulator for a microprocessor we are using in our systems. Our simulator allows for extensions that can be loaded as shared libraries. Rather than code the entire extension in C/C++, I would like to make use of Python to script the extension. So, I first initialize Python (examples below leave out the error checking, but it is there): Py_Initialize(); And then I make sure the script directory is in the path with Py_GetPath() and PySys_SetPath(). Finally, I import the script (say it is in a local file 'script.py'): pName = PyString_FromString("script"); pModule = PyImport_Import(pName); Once the module is imported, I get objects to the functions in the script I want to call later, which I do with: pName = PyString_FromString("foo"); pFunc = PyObject_GetAttr(pModule, pName); Later, I come back and call the function: pResult = PyObject_CallObject(pFunc, NULL); And it always fails whenever I iterate of a list. Say for example my Python function is: def foo(): a = ['cat', 'window', 'defenstrate'] for x in a: print x, len(x) Now, the function runs, i.e. I see the output ("cat 3\nwindow 6\ndefenstrate 11\n"), but I always get the following error message: Traceback (most recent call last): File "./script.py", line 3, in foo for x in a: AttributeError: 'module' object has no attribute 'reset' Now, if I run this exact same script using Python standalone, i.e.: Python 2.3.4 (#1, Nov 20 2007, 15:18:15) [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import script >>> script.foo() cat 3 window 6 defenstrate 11 (I know, and old version of Python. But we are stuck with it because our processes require us to validate a newer version if we change.) This works great. What is the difference? Why does it work in one context but not the other? Thanks, Pete -- -- "To love for the sake of being loved is human; to love for the sake of loving is Angelic." -- Alphonse de Lamartine From mensanator at aol.com Sun Jul 6 22:47:21 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 6 Jul 2008 19:47:21 -0700 (PDT) Subject: can't start IDLE 2.6 in Windows Vista Message-ID: <2b7b982d-7a5e-487e-9b32-f9b6a27d09b2@f63g2000hsf.googlegroups.com> Python 2.6b1 installed ok on my XP laptop but not my Vista desktop. First I got a strange application log error: Activation context generation failed for "C:\Python\Dlls\_socket.pyd". Error in manifest or policy file "C:\Python26\DLLs\Microsoft.VC90.CRT.MANIFEST" on line 12. The value "..\msvcr90.dll" of attribute "name" in element "urn:schemas-microsoft-com:asm.v1^file" is invalid. Oddly, It IS valid. Poking around, I changed the name in the manifest from "..\msvcr90.dll" to "msvcr90.dll" and copied the .dll from the parent directory. This stopped the app;ication error log messages. In Googling around, I found the suggestion to do python lib\idlelib\idle.py -n which gives me this error: Traceback (most recent call last): File "lib\idlelib\idle.py", line 21, in idlelib.PyShell.main() File "C:\Python26\lib\idlelib\PyShell.py", line 1382, in main root = Tk(className="Idle") File "C:\Python26\lib\lib-tk\Tkinter.py", line 1647, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: Can't find a usable init.tcl in the following directories: C:/Python26/lib/tcl8.5 C:/lib/tcl8.5 C:/lib/tcl8.5 C:/library C:/ library C:/tcl8.5.2/library C:/tcl8.5.2/library And, just like the previous error, the file DOES exist Directory of C:\Python26\tcl\tcl8.5 06/12/2008 06:07 PM 24,808 init.tcl But I note that the suggested places it looked have a forward slash instead of a the backward slash used by Windows. Is this why the file can't be found? I would try changing it but can't figure out where to look. From jr9445 at ATT.COM Thu Jul 24 14:55:06 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 24 Jul 2008 13:55:06 -0500 Subject: New to Python, familiar with Perl - Seeking info sources In-Reply-To: <18c8fc73-8ff9-4640-a020-de0be4b76ca4@z72g2000hsb.googlegroups.com> References: <18c8fc73-8ff9-4640-a020-de0be4b76ca4@z72g2000hsb.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Brett Ritter > Sent: Thursday, July 24, 2008 9:54 AM > To: python-list at python.org > Subject: New to Python, familiar with Perl - Seeking info sources > > After many years happily coding Perl, I'm looking to expand my > horizons. [no flames please, I'm pretty aware of Perl's strengths and > weaknesses and I'm just here to learn more, not to enter religious > debates]. > > > Any recommendations? Thanks in advance. > I have a Perl background and have found the O'Reilly books to be useful. The Learning Python book (or whatever it's called) is good because it covers the paradigm shifts and potential gotchas that you won't even consider thinking about otherwise. Only downside is wading through the novice 'how to program' parts. The Cookbook is also good for getting 'standard' apps up and running quickly (meaning you know how to do it in Perl, and just need the equivalent Python syntax/paradigm.) The Python help can be very hit or miss. You're going to have _fun_ with the Python regex module. *twitch*winch*sputter* Generally speaking, there's a Python module to do just about everything you could do in Perl. The only gap I've found is in the win32com with a class in a .tlb file (works fine in Perl, fails in Python.) But someone on the python-win32 list posted a potential workaround which I need to test. The really spiffy part is that when I converted a few Perl scripts to Python, the Python scripts were a bit smaller. =O Python does less compile time type checking than Perl. And finally, this mailing list does produce useful, polite answers about syntax to theory, despite some noise. From duncan.booth at invalid.invalid Thu Jul 31 05:02:16 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Jul 2008 09:02:16 GMT Subject: interpreter vs. compiled References: <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> Message-ID: Terry Reedy wrote: > 1. Portability: The Microsoft C# JIT compiler runs under Windows .NET > on x86/amd64 and maybe it64 and what else? Just porting .NET to run > 0n Linux on the same processors was/is a bit task. Does MONO have a > JIT also? Technically there is no such thing as a Microsoft C# JIT compiler: the C# compiler targets IL and the JIT compilers convert IL to the native machine, but C# is just one of the frontend compilers you could use. Microsoft do JIT compilers for .Net Compact Framework that target ARM, MIPS, SHx and x86. The Mono JIT supports: s390, s390x (32 and 64 bits) Linux SPARC(32) Solaris, Linux PowerPC Linux, Mac OSX x86 Linux, FreeBSD, OpenBSD, NetBSD, Microsoft Windows, Solaris, OS X x86-64: AMD64 and EM64T (64 bit) Linux, Solaris IA64 Itanium2 (64 bit) Linux ARM: little and big endian Linux (both the old and the new ABI) Alpha Linux MIPS Linux HPPA Linux (from http://www.mono-project.com/Supported_Platforms) So I'd say .Net scores pretty highly on the portability stakes. (Although of course code written for .Net might not do so well). -- Duncan Booth http://kupuguy.blogspot.com From grante at visi.com Sun Jul 20 23:06:50 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 20 Jul 2008 22:06:50 -0500 Subject: Python Written in C? References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> Message-ID: On 2008-07-21, Dan Upton wrote: >>> REAL WORLD programmers who want to be generally useful go and >>> learn C#. >> >> No: Real programmers first eat a quiche and then return to >> their Pascal programming. > > Bah, new-fangled languages like Pascal... Real programmers > write Fortran. Using punch-cards and paper-tape. Real programmers can edit their programs with a pointy stick and some home-made sticky-tape. -- Grant Edwards grante Yow! While I'm in at LEVITTOWN I thought I'd visi.com like to see the NUCLEAR FAMILY!! From desothier at yahoo.com Fri Jul 11 09:15:10 2008 From: desothier at yahoo.com (antar2) Date: Fri, 11 Jul 2008 06:15:10 -0700 (PDT) Subject: read file into list of lists Message-ID: Hello, I can not find out how to read a file into a list of lists. I know how to split a text into a list sentences = line.split(\n) following text for example should be considered as a list of lists (3 columns and 3 rows), so that when I make the print statement list[0] [0], that the word pear appears pear noun singular books nouns plural table noun singular Can someone help me? Thanks From bdesth.quelquechose at free.quelquepart.fr Tue Jul 22 11:38:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 22 Jul 2008 17:38:35 +0200 Subject: simple question about dictionaries In-Reply-To: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> References: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> Message-ID: <4885feed$0$12032$426a74cc@news.free.fr> skazhy a ?crit : > hi, i am new to python, so i've a really simple question about > dictionaries. > if i have a dictionary and I make have an input after it (to input > numbers) can i get the key of value that was in input? What if many keys are associated with a same value, ie: d = {'a':100, 'b':200, 'c':100} > somehting like this: > dict = { "key1"=100,"key2"=200,"key3"=300} 1/ don't use 'dict' as an indentifier - this shadows the builtin dict type. 2/ the 'dict literal' syntax is: d = {'key1":100, "key2": 200, "key3":300} > a = input() > print 'the key of inputted value is', dict['a'] > > this syntax of course is wrong, but i hope you got the point.. Assuming you don't have duplicate values, you just need to build a reverse dictionnary, that is using values as keys and keys as values, then lookup this dictionnary. The first operation can be done in one single line. reversed_d = dict((value, key) for key, value in d.items()) From israelu at elbit.co.il Wed Jul 16 03:47:35 2008 From: israelu at elbit.co.il (iu2) Date: Wed, 16 Jul 2008 00:47:35 -0700 (PDT) Subject: bad recursion, still works References: <7bf2bad5-d6b6-4929-a520-a82b7bb49916@34g2000hsf.googlegroups.com> <5be12739-7896-4112-9307-53897af4f691@f63g2000hsf.googlegroups.com> Message-ID: On Jul 16, 2:21?am, Michael Torrie wrote: > iu2 wrote: > > I still don't understand: In each recursive call to flatten, acc > > should be bound to a new [], shouldn't it? Why does the binding happen > > only on the first call to flatten? > > Nope. ?In each new call it's (re)bound to the same original list, which > you've added to as your function continues--it's mutable. ?Default > variables that are bound to mutable objects are one of the big caveats > that is mentioned in the FAQ. Thanks guys, it's clear now From gnewsg at gmail.com Wed Jul 30 13:50:34 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Wed, 30 Jul 2008 10:50:34 -0700 (PDT) Subject: Questions about asyncore References: <5d30aad5-cad7-4e47-aa83-277202c70ae2@z72g2000hsb.googlegroups.com> <6db7042c-02bb-42ef-b578-3811d8f427f5@m36g2000hse.googlegroups.com> Message-ID: <4903018c-feac-40fb-81fc-002dfc430f84@z66g2000hsc.googlegroups.com> On 30 Lug, 09:49, Frank Millman wrote: > On Jul 29, 3:40 pm, "Giampaolo Rodola'" wrote: > > > On 29 Lug, 13:09, Frank Millman wrote: > > Thanks for the reply, Giampaolo. Glad to help. > > The benefit of asynchat is that it automatically handles the buffering > > of both input and output. > > Aside from set/found_terminator() the other two methods you could want > > to look at are push() and push_with_producer(). > > push() is a buffered version of asyncore.send(), push_with_producer() > > accepts a data-producer object you can use in case you want to deal > > with something other than strings (e.g. files, lists, generators, and > > so on...). > > I looked at push() and push_with_producer(). To be honest I don't > fully understand why I would want to use them yet - I will have to go > over them a few more times. However, my handle_write() method seems to > be working ok and is not complicated, so I will stick with that for > now. I don't know whether you need to use them. I've just introduced the benefits of asynchat over asyncore. If you're already ok with your handle_read() implementation you probably don't need anything different. > > I'm not sure to understand but I doubt you have to use a thread. > > If you "have to wait for the reply before continuing" just implement > > this logic into handle_read() or found_terminator() method. > > Maybe I am a bit slow Or maybe my English is not good enough to properly understand what you need (it wouldn't be the first time, after all... =)). > ...but I cannot figure out how to do this without > adding a lot of complication. I will try to give a simple example. > > My server is a database server. It sits between the actual database > and the client, and implements access control, automatic handling of > foreign keys, etc. It accepts messages to read, update, and write > data, and returns the results. > > For testing purposes, I want the client to send and receive messages > such as the following (pseudocode) - > > -> Read Customer record with CustNo = 'A001'. > <- Print data, check that it is correct. [1] > -> Read customer's Branch record. > <- Print data, check that it is correct. > -> Update Customer record with new Branch code. [2] > -> Read Branch code from Customer record. > <- Print code, check that it has changed. > -> Read customer's Branch record. > <- Print data, check that it belongs to the new Branch. > > [1] Amongst other things, the server returns the id of the record > [2] The update request uses the record id to identify which record to > update > > These are just examples of the tests I might want to throw at the > server. With my multi-threaded approach, the asyncore loop runs in the > background, and in the foreground I can easily send any message I like > and check the results. I cannot see how to implement this using > handle_read() and found_terminator(). > > Maybe you can give a simple example of an alternative approach. > > Thanks > > Frank I pretty much have the same overview I had before. As far as I can tell the only reason you want to use a thread is when you have to do something which requires a consistent amount of time to complete so that the asyncore loop gets blocked. The question is: is there anything like that in your code? If the answer is no then you don't need to use threads. Maybe you are just not used to the asynchronous approach where "wait for server to respond" or "wait for the response to be complete" doesn't mean that YOU have to wait. It means that when a specific condition occurs (e.g. some data is received) a certain method of the framework you're using will be called and then it will be up to you deciding what do to. For example, if you're supposed to do something when a string of 5 digits is received, overwrite the handle_read() method and check if that's happened. If not instead of waiting for it to happen just "pass" and wait for handle_read() to be called again. This way you don't do anything which blocks the asynchronous loop and every peer (clients, servers or both) you have in your list of watchable channels will be served. If my response hasn't helped you any further try to post some code so that me or someone else could see what exactly you're trying to do. Hope this helps, anyway. --- Giampaolo http://code.google.com/p/pyftpdlib From python at rcn.com Fri Jul 18 19:51:12 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 18 Jul 2008 16:51:12 -0700 (PDT) Subject: __del__ methods References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> Message-ID: <426ec150-6136-4c3f-a5bb-ed109285b5ac@p31g2000prf.googlegroups.com> On Jul 18, 11:31?am, Jason Baker wrote: > I have a class that I need to do some finalization on when it dies. ?I > know I can use the __del__ method, but I seem to recall that it > impedes garbage collection. ?Is this the case? FWIW, I know a good number of top notch Python programmers who have programmed happily for years without ever using __del__. There are ways to get it to work for you, but it may be the smart thing to pretend that you've never heard of it. Raymond From JordanNealBerg at gmail.com Tue Jul 15 15:47:49 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Tue, 15 Jul 2008 12:47:49 -0700 (PDT) Subject: Testing for connection to a website References: Message-ID: On Jul 15, 3:43?pm, Alexnb wrote: > Okay, I already made this post, but it kinda got lost. So anyway I need to > figure out how to test if the user is able to connect to a specific website. > Last time I got pointed to the urllib2 page, but if I do urlopen() and and > am not connected, the program stops. So I don't know if that was what you > guys wanted me to do, but I don't think so, you guys are smarter than that. > So, how can I test for connection to a website. > -- > View this message in context:http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p... > Sent from the Python - python-list mailing list archive at Nabble.com. Ping it? ~_^ From gherron at islandtraining.com Thu Jul 17 14:23:27 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 17 Jul 2008 11:23:27 -0700 Subject: unpacking with default values In-Reply-To: <6a105194-a248-4ee6-be01-5aef9e5bb648@e53g2000hsa.googlegroups.com> References: <335e7a21-e35e-41ee-9f92-fd4c2f6bf166@f36g2000hsa.googlegroups.com> <6a105194-a248-4ee6-be01-5aef9e5bb648@e53g2000hsa.googlegroups.com> Message-ID: <487F8E1F.7040800@islandtraining.com> McA wrote: > On 17 Jul., 18:33, Gary Herron wrote: > >> In Python 2.x, you can't do that directly, but you should be able to >> create a function that lengthens or shortens an input tuple of arguments >> to the correct length so you can do: >> >> a,c,b = fix(1,2) >> d,e,f = fix(1,2,3,4) >> >> However, the function won't know the length of the left hand side >> sequence, so it will have to be passed in as an extra parameter or hard >> coded. >> > > Hi Gary, > > thank you for the answer. > Do you know the "protocol" used by python while unpacking? > Is it a direct assingnment? Or iterating? > Both I think, but what do you mean by *direct* assignment? > Best regards > Andreas Mock > -- > http://mail.python.org/mailman/listinfo/python-list > It RHS of such an assignment can be any iterable (I think). Lets test: (The nice thing about an interactive Python session, it that it's really easy to test.) >>> L = [1,2,3] >>> a,b,c=L >>> a,b=L Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack >>> a,b,c,d=L Traceback (most recent call last): File "", line 1, in ValueError: need more than 3 values to unpack >>> G = (f for f in [1,2,3]) # A generator expression >>> a,b,c = G >>> G = (f for f in [1,2,3]) # A generator expression >>> a,b = G Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack >>> G = (f for f in [1,2,3]) # A generator expression >>> a,b,c,d = G Traceback (most recent call last): File "", line 1, in ValueError: need more than 3 values to unpack I'd call that direct assignment with values supplied by any iterable. Gary Herron From jstrick at mindspring.com Thu Jul 10 09:45:47 2008 From: jstrick at mindspring.com (jstrick) Date: Thu, 10 Jul 2008 06:45:47 -0700 (PDT) Subject: start reading from certain line References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> <1215601039.2873.972.camel@localhost.localdomain> Message-ID: Here's a simple way to do it with a minimum amount of loopiness (don't forget to use 'try-except' or 'with' in real life): f = open("item1.txt") for preline in f: if "Item 1" in preline: print preline, for goodline in f: # could put an end condition with a 'break' here print goodline, f.close() From pavlovevidence at gmail.com Tue Jul 29 13:30:43 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 10:30:43 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> On Jul 29, 5:15 am, Heiko Wundram wrote: > I can't dig up a simple example from code I wrote quickly, but because of the > fact that explicit comparisons always hamper polymorphism I'm not going to take your word for it. Do you have code that demonstrates how "if x" improves polymorphism relative to simple explicit tests? Carl Banks From deets at nospam.web.de Sun Jul 27 13:46:32 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2008 19:46:32 +0200 Subject: Rant (was Re: x*x if x>10 In-Reply-To: References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> Message-ID: <6f3qjoF9n3cpU1@mid.uni-berlin.de> > >> Can you tell us what you mean by "several names of one object"? You mean >> this? >> >> a = range(10) >> b = a >> >> id(a) == id(b) >> >> >> ? Passing references instead of values is an extremely important concept >> of many languages, without it you would end up copying most of the time. > > OK. I've obviously been thinking about things the wrong way. In Forth you > pass the memory address around, and presumably that's essentially what's > happening when you pass a reference. Pretty much, yes. And I for once can say that I've been caught by modifying e.g. stack-locals instead of heap-objects in C++ by accident. > The problem is, I get caught frequently > in this situation: > > a = [1,2,3] > > def foo(x): > do_something_with_x > return x > > ... > > Then when I call foo(a), a gets changed. It just isn't the effect I expect > from changing a local. It's the way things work - mutables are mutables. If you want them to be modified, use the module copy. As a rule of thumb, don't return objects you didn't create inside a function from scratch. Which is the exact reasoning for the list.sort method btw - returning None is supposed to make you aware of the in-place modification. Diez From deets at nospam.web.de Sun Jul 27 12:40:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2008 18:40:00 +0200 Subject: Rant (was Re: x*x if x>10 In-Reply-To: <1q5p845o2j9htp6vf44u6nqinucsr1numf@4ax.com> References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3g8rF9gfj0U1@mid.uni-berlin.de> <6f3gmaF9moqsU1@mid.uni-berlin.de> <1q5p845o2j9htp6vf44u6nqinucsr1numf@4ax.com> Message-ID: <6f3mn0F9ia4rU1@mid.uni-berlin.de> DaveM schrieb: > On Sun, 27 Jul 2008 16:57:14 +0200, "Diez B. Roggisch" > wrote: > >> Marc 'BlackJack' Rintsch schrieb: >>> On Sun, 27 Jul 2008 16:41:19 +0200, Diez B. Roggisch wrote: >>> >>>> DaveM schrieb: >>>>> Getting back to the list concatenation, I finally found the itertools.chain >>>>> command which is the most compact and fastest (or second fastest by a >>>>> trivial amount, I can't remember which). Along the way, I must have >>>>> tried/used half a dozen methods, ...which brings me back my initial PERL >>>>> comment. There's more than one way to do it in Python, too. > >>>> But I *do* know that taking the python zen literally is fruitless. > >>> I think it should be taken more literally than the wrong reduction to >>> "there should be only one way". People tend to forget "obvious" and >>> "preferably" all the time. > >> Good point. The OP found the obvious way of extending. I wonder what his >> reasons were to abandon it. > > You'll have guessed, I'm sure, that I'm not a professional programmer. This > was the third rewrite of a program to match candidate groups to examiners on > a three day course I run, necessitated on this occasion by a change in the > structure of the course. I originally learnt python as I wrote, and some of > the early code was ugly and verbose, so once the current rewrite was working > I took the opportunity to tidy the code up and document it (yes, I know, but > as I said, I'm an amateur). The list concatenation was an itch I couldn't > scratch: > > temp = [] > for value in sessexam.values(): > temp.extend(value) > c_exam = [name for name in set(temp)] #See what I mean about verbose? > c_exam.sort() > return c_exam > > Six lines just didn't feel like it ought to be the best way to do something > so simple. I liked the attempt below better, but was foolish enough to time > it, so that was the end of that. > > return sorted(list(set(reduce(lambda x, y: x+y, sessexam.values())))) > > The current version (below) is a compromise, but I still feel there _ought_ > to be a simple one word command to join multiple lists. > > a = list(set(itertools.chain(*sessexam.values()))) > a.sort() #As I write I'm wondering if I really need it sorted. Hmm... > return a You are aware that the above is much more than "concatenate a bunch of lists?" You want unique values & sorting, which are two additional requirements. I'd say 3 lines of code for three requirements is ok, so all = sum(sessexam.values(), []) unique = set(all) sorted_result = sorted(unique) And obviously there are more ways to skin *that* cat, some (as itertools.chain) being less memory intensive: a = sorted(set(itertools.chain(*sessexam.values()))) It's debatable if this one-liner is really the way to go, but I fail to see how you expect there to be a specialized builtin for this kind of task. Diez From casey.mcginty at gmail.com Sat Jul 26 20:36:04 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Sat, 26 Jul 2008 14:36:04 -1000 Subject: Pwnie awards In-Reply-To: References: Message-ID: One more award from award winner Tim Neshman ... http://www.thenewsh.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Wed Jul 2 15:13:51 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 02 Jul 2008 20:13:51 +0100 Subject: Win32.client, DAO.DBEngine and exceeding the file sharing count lock In-Reply-To: <486BAA56.4070303@timgolden.me.uk> References: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> <9ab0cc2d-5a7e-40ca-a4da-084347f147cd@m36g2000hse.googlegroups.com> <486BAA56.4070303@timgolden.me.uk> Message-ID: <486BD36F.1060301@timgolden.me.uk> In case it helps, there's a recipe just shown up on the Python Cookbook which at least illustrates DAO use: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/572165 TJG From mal at egenix.com Mon Jul 21 17:54:21 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 21 Jul 2008 23:54:21 +0200 Subject: persistent deque (continued) In-Reply-To: <4c985e86-c0c4-4cb3-b7ce-f8e105b7f85d@y21g2000hsf.googlegroups.com> References: <4c985e86-c0c4-4cb3-b7ce-f8e105b7f85d@y21g2000hsf.googlegroups.com> Message-ID: <4885058D.7090304@egenix.com> On 2008-07-21 21:08, castironpi wrote: > Some time ago, I was asking about the feasibility of a persistent > deque, a double-ended queue. You might want to have a look at mxBeeBase: http://www.egenix.com/products/python/mxBase/mxBeeBase/ Using the integer index you could probably write an on-disk dequeue. The B*Tree indexes available in mxBeeBase keep the indexes sorted, so you'd only have to keep incrementing the index as you add new values and keep a record of the highest and lowest index currently in use. Details are left as exercise for the interested reader ;-) > It runs into the typical space allocation problems. If you're storing > a pickle, you have to allocate and fragment the file you've opened, > since pickles can be variable-length strings; i.e. if the new data is > too long, blank out its entry, and grow the file. If you're storing a > data-type, you lose Python's dynamic-type advantages, as well as its > long integers, as they can be any length. If you change the object in > the deque, such as when using any mutable type, you have to update the > container too. > > Does anyone have any experience storing pickles (I am aware of the > similarities to shelf) to a database? > Can the file system facilitate the variable-length string problem? > How feasible is a length-of-length - length - data solution to the > unbounded integer problem? > Is there any alternative to completely re-pickling a large (say 1k > pickled) object you only change slightly? > What other issues are there? > Is a hybrid-storage type possible, that stores the contents of its > Python-allocated memory block to disk, including reference count, even > if it's a lot slower? The object could not contain any references to > objects not allocated on disk. > > A first approach is for the file to look like this: > > 00 data 01 data 02 > 01 data 03 data 04 > 02 data 05 data 06 > > Append would add: > > 03 data 07 data 08 > > AppendLeft would add: > > -01 data 09 data 0a > > Pop would remove 03, PopLeft would remove -01. You would need a > length-and-head index to make 'rotate' available. Remove would run a > worst-case risk of renumbering half of the indices stored, plus a > rotate. > -- > http://mail.python.org/mailman/listinfo/python-list -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 21 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From sanket.s.patel at gmail.com Fri Jul 25 23:04:19 2008 From: sanket.s.patel at gmail.com (sanket) Date: Fri, 25 Jul 2008 20:04:19 -0700 (PDT) Subject: SimpleJson is slow .... is there any C Compiled version ? References: Message-ID: <711d141b-fe46-437d-b7ca-e11f91c8217f@w1g2000prk.googlegroups.com> On Jul 25, 5:52?pm, Matt Nordhoff wrote: > sanket wrote: > > Hello All, > > > I have created an API which fetches some data from the database. > > I am using simplejson to encode it and return it back. > > > Now the problem is that, this API is being called for millions of > > times in a sequence. > > I ran a profiler and saw that most of the time is consumed in encoding > > my database results in to json. > > So I was just wondering is there any C compiled version of simplejson > > is available? > > or any help regarding this issue would be appreciated. > > > Thank you, > > Sanket > > simplejson is not the only JSON library out there. For example, there's > python-cjson, which is written entirely in C: > > > > There's also an enhanced version of it: > > > > I think simplejson has some small, optional C bits that will improve > performance if you compile them. > > Also, be aware that I think simplejson is being integrated into the > stdlib in Python 2.6. > > Also, simplejson and python-cjson might not be entirely compatible: > there's one character that one escapes and the other doesn't, or something. > -- Thanks Matt. I used cjson and it appears to be 5-6 times faster. Thank you, Sanket From fernandes.fd at gmail.com Fri Jul 4 16:43:11 2008 From: fernandes.fd at gmail.com (Filipe Fernandes) Date: Fri, 4 Jul 2008 16:43:11 -0400 Subject: re.search much slower then grep on some regular expressions In-Reply-To: References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: <11397a330807041343w6697db55p92bf53505ebab8b5@mail.gmail.com> On Fri, Jul 4, 2008 at 8:36 AM, Peter Otten <__peter__ at web.de> wrote: > Henning_Thornblad wrote: > >> What can be the cause of the large difference between re.search and >> grep? > > grep uses a smarter algorithm ;) > >> This script takes about 5 min to run on my computer: >> #!/usr/bin/env python >> import re >> >> row="" >> for a in range(156000): >> row+="a" >> print re.search('[^ "=]*/',row) >> >> >> While doing a simple grep: >> grep '[^ "=]*/' input (input contains 156.000 a in >> one row) >> doesn't even take a second. >> >> Is this a bug in python? > > You could call this a performance bug, but it's not common enough in real > code to get the necessary brain cycles from the core developers. > So you can either write a patch yourself or use a workaround. > > re.search('[^ "=]*/', row) if "/" in row else None > > might be good enough. > Wow... I'm rather surprised at how slow this is... using re.match yields much quicker results, but of course it's not quite the same as re.search Incidentally, if you add the '/' to "row" at the end of the string, re.search returns instantly with a match object. @ Peter I'm not versed enough in regex to tell if this is a bug or not (although I suspect it is), but why would you say this particular regex isn't common enough in real code? filipe From leo_365 at yahoo.com Fri Jul 25 02:58:24 2008 From: leo_365 at yahoo.com (leo davis) Date: Thu, 24 Jul 2008 23:58:24 -0700 (PDT) Subject: need help with introducing more traffic In-Reply-To: Message-ID: <853354.27263.qm@web51803.mail.re2.yahoo.com> Fredrik Lundh, ? I'm with you and my apologies for not making the scenario more clearer in my previous post.... [QUOTE]"load testing" other people's sites are known as something else, of course[QUOTE]- ? ?yes,that could cause a DoS and its lame....I certainly dont intend to do that,was just?checking whether the code was running alright on a random webserver and so if you did notice ran it with only '1(or 5)?thread/s which cant hurt...I have setup an intranet in my uni and thats where i plan to carry out the actual tests as part of my dissertation'. ? Yes,i am trying to write a code to stress test webservers,i know there r many free tools out there but looking for opensource codes so that i couls tweak them. ? Cheers ? ? --- On Fri, 7/25/08, Fredrik Lundh wrote: From: Fredrik Lundh Subject: Re: need help with introducing more traffic To: python-list at python.org Date: Friday, July 25, 2008, 1:46 AM Fredrik Lundh wrote: > "load testing" other people's sites are known as something else, of course. message.replace(" are ", " is ") # do'h! (when do we get the ability to edit our c.l.python messages for, say, 30 minutes after they're posted? ;-) -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From noorhanabbas at yahoo.co.uk Wed Jul 9 06:18:05 2008 From: noorhanabbas at yahoo.co.uk (Noorhan Abbas) Date: Wed, 9 Jul 2008 10:18:05 +0000 (GMT) Subject: Opening Unicode files Message-ID: <636110.21350.qm@web27405.mail.ukl.yahoo.com> Hello, I wonder if you don't mind helping me out in this problem. I have been developing a tool in python that opens some unicode files, reading them and processing the data. It is working fine. When I started to write a cgi module that does the same thing for google appengine(actually it is using the same files that I used befoer), I get an error: ? f = codecs.open (FileName , 'rU', 'utf-8') ? It says that the above functions takes 3 arguments but 4 were given.? I wonder if I need to do something before using the codecs library from within the cgi module?! ? Thank you very much for your help, Nora __________________________________________________________ Not happy with your email address?. Get the one you really want - millions of new email addresses available now at Yahoo! http://uk.docs.yahoo.com/ymail/new.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Tue Jul 29 00:21:31 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 28 Jul 2008 21:21:31 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> Message-ID: On Jul 28, 5:58?pm, Fuzzyman wrote: > On Jul 27, 6:02?am, castironpi wrote: > > > > > On Jul 24, 11:04?pm, Tim Roberts wrote: > > > > castironpi wrote: > > > > >Compiling a program is different than running it. ?A JIT compiler is a > > > >kind of compiler and it makes a compilation step. ?I am saying that > > > >Python is not a compiler and in order to implement JIT, it would have > > > >to change that fact. > > > > And I'm saying you are wrong. ?There is NOTHING inherent in Python that > > > dictates that it be either compiled or interpreted. ?That is simply an > > > implementation decision. ?The CPython implementation happens to interpret. > > > The IronPython implementation compiles the intermediate language to native > > > machine language. > > > > >> of Python that uses .NET. ?In that case, the code *IS* JIT compiled to > > > >> assembly when the program starts. > > > > >But still not the user's code, only the interpreter, which is running > > > >in assembly already anyway in CPython. > > > > In CPython, yes. ?In IronPython, no; the user's code is compiled into > > > machine language. ?Both of them are "Python". > > > -- > > > Tim Roberts, t... at probo.com > > > Providenza & Boekelheide, Inc. > > > In CPython yes. ?In IronPython yes: ?the parts that are compiled into > > machine code are the interpreter, *not user's code*. ?Without that > > step, the interpreter would be running on an interpreter, but that > > doesn't get the user's statement 'a= b+ 1' into registers-- it gets > > 'push, push, add, pop' into registers. > > Well - in IronPython user code gets compiled to in memory assemblies > which can be JIT'ed. > > Michael Foord > --http://www.ironpythoninaction.com/ I don't believe so. Take a sample interpreted language, to be compiled by a sample JIT. a= stack( ) a.push( 0 ) a.push( 2 ) a.push( 4 ) Bytecode output is: allocate var0 call STACK_CONSTRUCTOR initialize var0 return call METH0 var0 const 0 call METH0 var0 const 2 call METH0 var0 const 4 JIT output is assembly: reg0 malloc 4 setjmp jmp STACK_CONSTRUCTOR popjmpv reg1 setjmp reg1 0 jmp METH0 reg1 2 jmp METH0 reg1 4 jmp METH0 But when you compare the C code for 'x= y+ 1' to Python JIT code for 'x= y+ 1', there is no stack and no error checking. They're quite different. In a JIT language, Python runs in native assembly, output similar to CPython, theoretically. User's code -does- -not- -run-. It is moved in to and out of a stack by a program that is running, namely the interpreter, whether it came from C and a compiler, or .NEt, bytecode, and a JIT. From deets at nospam.web.de Sun Jul 27 10:41:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2008 16:41:19 +0200 Subject: Rant (was Re: x*x if x>10 In-Reply-To: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> Message-ID: <6f3fogF9jpidU1@mid.uni-berlin.de> DaveM schrieb: > On Sun, 27 Jul 2008 05:24:36 -0700 (PDT), alex23 wrote: > >> On Jul 27, 10:13 pm, ssecorp wrote: >>> I have seen somewhere that you can write something like: > >>> x*x if x>10 >>> but exactly that doesn't work and I can't get any variation to work. > >> It's called a ternary operator. The format is: >>
verb
Okay, I left off some stuff. But what I need to do is get what is inside each and then each
. But the key is that I need everything in the EXACT order that it would be in the html. I can easily get the tables but it is the span's than I am having trouble with. -- View this message in context: http://www.nabble.com/Help-with-BeautifulSoup-tp18416200p18416200.html Sent from the Python - python-list mailing list archive at Nabble.com. From emen999 at gmail.com Tue Jul 29 06:51:36 2008 From: emen999 at gmail.com (code_berzerker) Date: Tue, 29 Jul 2008 03:51:36 -0700 (PDT) Subject: SWIG and char* newb questions :) Message-ID: <7ec26fb6-3d6a-4e1b-b2c9-a0a254780153@26g2000hsk.googlegroups.com> Hi i'm relatively new to Python and my C/C++ knowledge is near to None. Having said that I feel justified to ask stupid questions :) Ok now more seriously. I have question refering to char* used as function parameters to return values. I have read SWIG manual to find best way to overcome that, but there are many warnings about memory leaks and stuff, so I feel confused. Ok to put it more simply: how to safely define a variable in Python and have it modified by C/C++ function? Even better would be a way to make a tuple of return value and out parameters, but thats probably a lot more work. Any hint will be appreciated! From patf at well.com Tue Jul 29 00:47:08 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 21:47:08 -0700 (PDT) Subject: Download excel file from web? References: <6f6vhlFa7anrU1@mid.uni-berlin.de> <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> <19fa0bb2-e101-47c9-84d4-1bf05d08ba39@b2g2000prf.googlegroups.com> Message-ID: On Jul 28, 6:05?pm, "Guilherme Polo" wrote: > On Mon, Jul 28, 2008 at 9:39 PM, MRAB wrote: > > On Jul 29, 12:41 am, "p... at well.com" wrote: > >> On Jul 28, 4:20 pm, "Guilherme Polo" wrote: > > >> > On Mon, Jul 28, 2008 at 8:04 PM, p... at well.com wrote: > >> > > On Jul 28, 3:52 pm, "Guilherme Polo" wrote: > >> > >> On Mon, Jul 28, 2008 at 7:43 PM, p... at well.com wrote: > >> > >> > On Jul 28, 3:33 pm, "p... at well.com" wrote: > >> > >> >> On Jul 28, 3:29 pm, "Diez B. Roggisch" wrote: > > >> > >> >> > p... at well.com schrieb: > > >> > >> >> > > On Jul 28, 3:00 pm, "p... at well.com" wrote: > >> > >> >> > >> Hi - experienced programmer but this is my first Python program. > > >> > >> >> > >> This URL will retrieve an excel spreadsheet containing (that day's) > >> > >> >> > >> msci stock index returns. > > >> > >> >> > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > >> > >> >> > >> Want to write python to download and save the file. > > >> > >> >> > >> So far I've arrived at this: > > >> > >> >> > >> [quote] > >> > >> >> > >> # import pdb > >> > >> >> > >> import urllib2 > >> > >> >> > >> from win32com.client import Dispatch > > >> > >> >> > >> xlApp = Dispatch("Excel.Application") > > >> > >> >> > >> # test 1 > >> > >> >> > >> # xlApp.Workbooks.Add() > >> > >> >> > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > >> > >> >> > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > >> > >> >> > >> # xlBook = xlApp.ActiveWorkbook > >> > >> >> > >> # xlBook.SaveAs(Filename='C:\\test.xls') > > >> > >> >> > >> # pdb.set_trace() > >> > >> >> > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > >> >> > >> excel? > >> > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional') > >> > >> >> > >> # test 2 - returns check = False > >> > >> >> > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > >> > >> >> > >> indexperf/excel? > >> > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > >> > >> >> > >> xlApp = response.fp > >> > >> >> > >> print(response.fp.name) > >> > >> >> > >> print(xlApp.name) > >> > >> >> > >> xlApp.write > >> > >> >> > >> xlApp.Close > >> > >> >> > >> [/quote] > > >> > >> >> > > Woops hit Send when I wanted Preview. ?Looks like the html [quote] tag > >> > >> >> > > doesn't work from groups.google.com (nice). > > >> > >> >> > > Anway, in test 1 above, I determined how to instantiate an excel > >> > >> >> > > object; put some stuff in it; then save to disk. > > >> > >> >> > > So, in theory, I'm retrieving my excel spreadsheet with > > >> > >> >> > > response = urllib2.urlopen() > > >> > >> >> > > Except what then do I do with this? > > >> > >> >> > > Well for one read some of the urllib2 documentation and found the > >> > >> >> > > Request class with the method has_data() on it. ?It returns False. > >> > >> >> > > Hmm that's not encouraging. > > >> > >> >> > > I supposed the trick to understand what urllib2.urlopen is returning > >> > >> >> > > to me; rummage around in there; and hopefully find my excel file. > > >> > >> >> > > I use pdb to debug. ?This is interesting: > > >> > >> >> > > (Pdb) dir(response) > >> > >> >> > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > >> > >> >> > > 'code', ' > >> > >> >> > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > >> > >> >> > > 'readline', ' > >> > >> >> > > readlines', 'url'] > >> > >> >> > > (Pdb) > > >> > >> >> > > I suppose the members with __*_ are methods; and the names without the > >> > >> >> > > underbars are attributes (variables) (?). > > >> > >> >> > No, these are the names of all attributes and methods. read is a method, > >> > >> >> > for example. > > >> > >> >> right - I got it backwards. > > >> > >> >> > > Or maybe this isn't at all the right direction to take (maybe there > >> > >> >> > > are much better modules to do this stuff). ?Would be happy to learn if > >> > >> >> > > that's the case (and if that gets the job done for me). > > >> > >> >> > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty > >> > >> >> > clear on this: > > >> > >> >> > """ > >> > >> >> > This function returns a file-like object with two additional methods: > >> > >> >> > """ > > >> > >> >> > And then for file-like objects: > > >> > >> >> >http://docs.python.org/lib/bltin-file-objects.html > > >> > >> >> > """ > >> > >> >> > read( ? [size]) > >> > >> >> > ? ? ?Read at most size bytes from the file (less if the read hits EOF > >> > >> >> > before obtaining size bytes). If the size argument is negative or > >> > >> >> > omitted, read all data until EOF is reached. The bytes are returned as a > >> > >> >> > string object. An empty string is returned when EOF is encountered > >> > >> >> > immediately. (For certain files, like ttys, it makes sense to continue > >> > >> >> > reading after an EOF is hit.) Note that this method may call the > >> > >> >> > underlying C function fread() more than once in an effort to acquire as > >> > >> >> > close to size bytes as possible. Also note that when in non-blocking > >> > >> >> > mode, less data than what was requested may be returned, even if no size > >> > >> >> > parameter was given. > >> > >> >> > """ > > >> > >> >> > Diez > > >> > >> >> Just stumbled upon .read: > > >> > >> >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > >> >> excel? > >> > >> >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> >> +25%2C+2008&export=Excel_IEIPerfRegional').read > > >> > >> >> Now the question is: what to do with this? ?I'll look at the > >> > >> >> documentation that you point to. > > >> > >> >> thanx - pat > > >> > >> > Or rather (next iteration): > > >> > >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > >> > excel? > >> > >> > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > >> > >> > The file is generally something like 26 KB so specifying 1,000,000 > >> > >> > seems like a good idea (first approximation). > > >> > >> > And then when I do: > > >> > >> > print(response) > > >> > >> > I get a whole lot of garbage (and some non-garbage), so I know I'm > >> > >> > onto something. > > >> > >> > When I read the .read documentation further, it says that read() has > >> > >> > returned the data as a string object. ?Now - how do I convince Python > >> > >> > that the string object is in fact an excel file - and save it to disk? > > >> > >> You don't need to convince Python, just write it to a file. > >> > >> More reading for you:http://docs.python.org/tut/node9.html > > >> > >> > pat > >> > >> > -- > >> > >> >http://mail.python.org/mailman/listinfo/python-list > > >> > >> -- > >> > >> -- Guilherme H. Polo Goncalves > > >> > > OK: > > >> > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > > excel? > >> > > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > >> > > # print(response) > >> > > f = open("c:\\msci.xls",'w') > >> > > f.write(response) > > >> > I would initially change that to: > > >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&...) > > >> > f = open("c:\\msci.xls", "wb") > >> > for line in response: > >> > ? ? f.write(line) > >> > f.close() > > >> > and then.. > > >> > > OK this makes the file, and there's a c:\msci.xls in place and it's > >> > > about the right size. But whether I make the second param to open 'w' > >> > > or 'wb', when I try to open msci.xls from the Windows file explorer, > >> > > excel tells me that the file is corrupted. > > >> > try it. > > >> > > pat > >> > > -- > >> > >http://mail.python.org/mailman/listinfo/python-list > > >> > -- > >> > -- Guilherme H. Polo Goncalves > > >> A simple f.write(response) does work (click on a single row in Excel > >> and you get a single row). > > >> But I can see that what you recommend Guilherme is probably safer - > >> thanx. > > >> pat > > > If response contains a string then: > > Did you notice I removed the read(...) part ? > > > for line in response: > > ? ?f.write(line) > > > will actually be writing the string one character at a time! > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves Actually no I didn't Guilherme (although I'll take it out now). Would leaving the in urllib2.urlopen().read() imply, as MRAB would seem to indicate, that the following for loop would act byte-by-byte? And if so, how? Even with the .read() in, it was very fast. But it looks like it won't hurt (and very possibly helps) to take it out. pat From tjreedy at udel.edu Sat Jul 12 15:43:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 15:43:03 -0400 Subject: Changing self: if self is a tree how to set to a different self In-Reply-To: References: Message-ID: Kay Schluehr wrote: > > > Since it is acting on a tree why doesn't the code substitute self in > its parent by SS? That's the natural perspective if one considers a > tree as a linked structure and inserts and deletes nodes within this > structure. I think you are suggesting the same thing I did: > If you examine nodes from their parent, I believe you can do the > > substitution in one step. Something like: > > > > for slot,child in ( ('left',self.left), ('right',self.right) ): > > if child is not None: > > if child.val == 'f': > > setattr(self, slot, F.copy().subst('x', child.left)) > > child.elimF > > > > where .subst returns the modified tree. Where F.copy is what was called 'SS'. If not, I don't understand. From fredrik at pythonware.com Thu Jul 24 11:59:39 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 17:59:39 +0200 Subject: Encoding for Devanagari Script. In-Reply-To: References: Message-ID: Atul. skrev: > I wanted to know what encoding should I use to open the files with > Devanagari characters. I was thinking of UTF-8 but was not sure, any > leads on this? Anyone used it earlier? Are we talking about existing files? If you don't know what encoding the files use, you could always try using the UTF-8 codec; it's very likely to complain if you're attempting to decode something that's isn't UTF-8. If that doesn't work, it's a bit trickier -- there are several ways to encode Unicode, and then there's ISCII as well. If you cannot sort it out, try running this: >>> f = open("myfile.txt", "rb") >>> f.read(32) on one of your files, and post the result, and chances are that someone will be able to identify the encoding. From wtanksleyjr at gmail.com Thu Jul 31 09:44:57 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Thu, 31 Jul 2008 06:44:57 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> <4ae2518f-10c0-49f2-b5d7-a75993b0a67d@z66g2000hsc.googlegroups.com> <48915761$0$11736$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <5f3a28f9-5918-4d5a-857b-3fbe2af3b196@u12g2000prd.googlegroups.com> Stefan Behnel wrote: > william tanksley wrote: > > Okay, my answer is that ElementTree (in Python 2.5) is simply > > deranged when it comes to Unicode. It assumes everything's ASCII. > It does not "assume" that. It *requires* byte strings to be ASCII. You can't encode Unicode into an ASCII string. (Well, except using UTF-7.) Bad requirement. > If it > didn't enforce that, how could it possibly know what encoding they were using, > i.e. what they were supposed to mean at all? Read the Python Zen, in the face > of ambiguity, ElementTree refuses the temptation to guess. Python 2.x does > exactly the same thing when it comes to implicit conversion between encoded > strings and Unicode strings. An XML file that begins with the string is NOT ascii. You don't have to guess what encoding it's in. It's UTF-8. If you error out when you hit an 8-bit character, you're not going to be able to process that file. I'm completely lost on why you're claiming otherwise. Furthermore, when ElementTree returns (from one of its .text elements) a string-of-bytes instead of a decoded Unicode string, it doesn't merely "resist the temptation to guess"; instead, it forces ME to guess. I've now had to hardcode "utf-8" into my program, when IT just bypassed and ignored an explicit instruction to use UTF-8. I hope and assume that iTunes will never switch from UTF-8 to UTF-32 -- if it does, my code breaks, and I'll probably have to switch away from ElementTree (I guess that since it requires ASCII it won't even pretend to handle more than 8 bits per character). > If you want to pass plain ASCII strings, you can either pass a byte string or > a Unicode string (that's a plain convenience feature). If you want to pass > anything that's not ASCII, you *must* pass a Unicode string. I don't care about strings. I've never passed ElementTree a string. I'm using a file, a file that's correctly encoded as UTF-8, and it returns some text elements that are raw bytes (undecoded). I have to manually decode them. > > Reference:http://codespeak.net/lxml/compatibility.html > > (Note that the lxml version also doesn't handle Unicode correctly; it > > errors when XML declares its encoding.) > It definitely does "handle Unicode correctly". Actually, this is my bad -- I misread the webpage. lxml appears to handle unicode strings with a declared encoding correctly: it errors out. That's quite reasonable when confronted with a contradiction. According to that page, however, the standard ElementTree library doesn't work that way -- it simply assumes that byte strings are ASCII. I'm going to back down on this one, though. I realize that this is a single paragraph on a third-party website, and it's not really trying to document the official ElementTree (it's trying to document its own version, lxml). So it might not be correct, or it might be overly ambiguous. It might also be talking ONLY about strings, to the exclusion of file input. I don't know, and I don't have the energy to debug it, especially since I can't "fix" anything about it even if something was wrong :-). So I revert to my former position: I don't know why those two lines have to be in that order for my code to work correctly; I don't even know why the "encode" line has to be there at all. When I was using the old Python XML library, I didn't have to worry about encoding or decoding; everything just worked. I really prefer ElementTree, and I'm glad I upgraded, but it really looks like encoding is a problem. > Let me guess, you tried passing > XML as a Unicode string into the parser, and your XML declared itself as > having a byte encoding (). How can that *not* be an error? I thought you just said "resist the temptation to guess"? I didn't pass a string. I passed a file. It didn't error out; instead, it produced bytestring-encoded output (not Unicode). > Stefan -Wm From bdesth.quelquechose at free.quelquepart.fr Sun Jul 27 14:04:27 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Jul 2008 20:04:27 +0200 Subject: Confounded by Python objects In-Reply-To: <009c464f$0$20302$c3e8da3@news.astraweb.com> References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> <5ddae1dd-c7dd-4f04-84f6-ad71c3282c92@j7g2000prm.googlegroups.com> <6f1a6uF9ctsmU1@mid.uni-berlin.de> <009c464f$0$20302$c3e8da3@news.astraweb.com> Message-ID: <488cd4a2$0$21184$426a34cc@news.free.fr> Steven D'Aprano a ?crit : > On Sat, 26 Jul 2008 18:54:22 +0000, Robert Latest wrote: > >> Here's an interesting side note: After fixing my "Channel" thingy the >> whole project behaved as expected. But there was an interesting hitch. >> The main part revolves around another class, "Sequence", which has a >> list of Channels as attribute. I was curious about the performance of my >> script, because eventually this construct is supposed to handle >> megabytes of data. So I wrote a simple loop that creates a new Sequence, >> fills all the Channels with data, and repeats. >> >> Interistingly, the first couple of dozens iterations went satisfactorily >> quickly (took about 1 second total), but after a hundred or so times it >> got really slow -- like a couple of seconds per iteration. >> >> Playing around with the code, not really knowing what to do, I found >> that in the "Sequence" class I had again erroneously declared a >> class-level attribute -- rather harmlessly, just a string, that got >> assigned to once in each iteration on object creation. >> >> After I had deleted that, the loop went blindingly fast without slowing >> down. >> >> What's the mechanics behind this behavior? > > Without actually seeing the code, it's difficult to be sure, but my guess > is that you were accidentally doing repeated string concatenation. This > can be very slow. > > In general, anything that looks like this: > > s = '' > for i in range(10000): # or any big number > s = s + 'another string' > > can be slow. Very slow. But this is way faster: s = '' for i in range(10000): # or any big number s += 'another string' (snip) > It's harder to stumble across the slow behaviour these days, as Python > 2.4 introduced an optimization that, under some circumstances, makes > string concatenation almost as fast as using join(). yeps : using augmented assignment (s =+ some_string) instead of concatenation and rebinding (s = s + some_string). > But be warned: join() > is still the recommended approach. Don't count on this optimization to > save you from slow code. > > If you want to see just how slow repeated concatenation is compared to > joining, try this: > > >>>> import timeit >>>> t1 = timeit.Timer('for i in xrange(1000): x=x+str(i)+"a"', 'x=""') >>>> t2 = timeit.Timer('"".join(str(i)+"a" for i in xrange(1000))', '') >>>> >>>> t1.repeat(number=30) > [0.8506159782409668, 0.80239105224609375, 0.73254203796386719] >>>> t2.repeat(number=30) > [0.052678108215332031, 0.052067995071411133, 0.052803993225097656] > > Concatenation is more than ten times slower in the example above, Not using augmented assignment: >>> from timeit import Timer >>> t1 = Timer('for i in xrange(1000): x+= str(i)+"a"', 'x=""') >>> t2 = Timer('"".join(str(i)+"a" for i in xrange(1000))', '') >>> t1.repeat(number=30) [0.07472991943359375, 0.064207077026367188, 0.064996957778930664] >>> t2.repeat(number=30) [0.071865081787109375, 0.061071872711181641, 0.06132817268371582] (snip) > And even worse: > >>>> t1.repeat(number=50) > [2.7190279960632324, 2.6910948753356934, 2.7089321613311768] >>>> t2.repeat(number=50) > [0.087616920471191406, 0.088094949722290039, 0.087819099426269531] > Not that worse here: >>> t1.repeat(number=50) [0.12305188179016113, 0.10764503479003906, 0.10605692863464355] >>> t2.repeat(number=50) [0.11200308799743652, 0.10315108299255371, 0.10278487205505371] >>> I'd still advise using the sep.join(seq) approach, but not because of performances. From george.sakkis at gmail.com Wed Jul 2 10:40:52 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 2 Jul 2008 07:40:52 -0700 (PDT) Subject: How to pickle bound methods References: Message-ID: <3fecf76b-5785-46ec-bf61-61a498d699d0@34g2000hsh.googlegroups.com> On Jul 2, 8:26 am, srinivasan srinivas wrote: > I am writing client-server program. The server will send a methodname and its arguments to a client. The client has to execute the method and return back the results. Are you aware of Pyro [1] ? Btw, you use the terminology backwards: the client calls a method on a remote server and the server executes it and returns back the results to the client. George [1] http://pyro.sourceforge.net/ From modelnine at modelnine.org Tue Jul 29 15:43:02 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Tue, 29 Jul 2008 20:43:02 +0100 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: Am 29.07.2008, 18:30 Uhr, schrieb Carl Banks : > On Jul 29, 5:15 am, Heiko Wundram wrote: >> I can't dig up a simple example from code I wrote quickly, but because >> of the >> fact that explicit comparisons always hamper polymorphism > > I'm not going to take your word for it. Do you have code that > demonstrates how "if x" improves polymorphism relative to simple > explicit tests? As I wrote in the second reply email I sent, check out my integer set recipe on ASPN (and to save you the search: http://code.activestate.com/recipes/466286/). To test whether the integer set is empty or not (in a polymorphic function which accepts any kind of sequence type), the explicit test would be, as you proposed elsewhere: len(x) > 0. This simply WILL NOT work with some sets of that respective type, because, as I documented for the __len__() method there: the return value of __len__() has to (had to?) be in the range 0 <= len < 2**31 (which I think means, as I tested and implemented it on i386, that the return value has to fit in an ssize_t platform type, but someone with more knowledge of the interpreter internals might be able to comment here; I'm not in the mood for checking this out now). Another reason why the test for __nonzero__() is beneficial, at least here: testing whether the set is empty or not is easy, because an empty set has no ranges, and a set with at least one element has at least one range (i.e., to test whether the set is non-empty, check whether the _ranges member, a list, is __nonzero__()); taking the len() of a set always means adding the size of the ranges together (even though this could of course be precomputed/cached, as the set type is immutable, but I'm not doing that in that recipe's code). So, adding things up: the interpretation of __nonzero__(), i.e. the direct "conversion" to bool, for container-types, implements THE means to test whether the container is empty or not. Insisting on not using it, because a "simple explicit" test is supposedly better, will prove to not work in those cases where the container type might not have a representable length (because of the constraints on the return value of __len__()), even though the container has an empty/non-empty state. I think this does make a very compelling use case for "if x" instead of "if len(x) > 0". --- Heiko. From subhabrata.iisc at hotmail.com Fri Jul 25 11:46:21 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Fri, 25 Jul 2008 08:46:21 -0700 (PDT) Subject: Question Regarding XML Message-ID: Dear Group, I have some queries regarding XML conversion of some .txt/.doc files. I am thinking to use Satine. Is it OK? But it seems to support Python2.3 but does it support 2.5, too? If any one can kindly let me know. Best Regards, Subhabrata. From basti.wiesner at gmx.net Mon Jul 7 10:47:14 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Mon, 07 Jul 2008 16:47:14 +0200 Subject: GUI Programming by hand not code with Python Code References: <7003b665-3227-47a7-ab06-1a486f87939a@a1g2000hsb.googlegroups.com> <85ab371e-9926-4bb3-bcd4-f441de7aa046@k30g2000hse.googlegroups.com> Message-ID: Jason Scheirer : > On Jul 6, 7:33?pm, jayjaygi... at hotmail.co.uk wrote: >> Is their a program that lets you design a GUI by hand (like gambas) >> not by code (like wxpython) but the commands are in python? >> >> A program similar to gambas or vb >> >> Gambas with python code instead of gambas code would be perfect. >> >> Thanks in advance > > Glade for GTK, wxGlade for wxPython. And the designer for Qt4 -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From johnroth1 at gmail.com Tue Jul 15 09:15:35 2008 From: johnroth1 at gmail.com (John Roth) Date: Tue, 15 Jul 2008 06:15:35 -0700 (PDT) Subject: Suggestion: Python global scope References: Message-ID: On Jul 15, 5:57?am, Anonymous Bastard wrote: > I've been tossing this idea in my mind for some time now: > > In Python, declaring a variable using the global statement automatically > makes it available in all subsequent scopes. > > But to me, it makes more sense to use the global statement to 'import' a > variable from the global scope into the current scope. For instance: > > [code] > global X > X = 1 > > def P(): > ? ? ?X = 2 > ? ? ?print X > ? ? ?global X > ? ? ?print X > > print X > P() > print X > [code] > > Currently, this will print 1, 2, 2 and 2. But if global would be limited > to current scope, it would print 1, 2, 1, 1. > > 'X = 2' would work on the local version of X, 'global X' will 'import' > the global X into the local scope, so any actions on X would reference > the global X, rather than previous X. I suppose it could be done, but I for one would be against it on several grounds. First, global operates somewhat as a declaration currently. Declarations are easier for most developers to understand than redefinitions of a variable on the fly. Second, following up the first point, it redefines a variable. While this is common practice, it's unfortunate since it leads to some amount of confusion. It also seems like it would be most useful in large, poorly structured methods, which is exactly the wrong way to go. Finally, as Gerhard Haring has said, it's backward incompatible, so the window for considering it has past: the 3.x series is pretty much frozen. John Roth From Bill at SynectixLtd.com Fri Jul 4 08:25:33 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Fri, 4 Jul 2008 13:25:33 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) Message-ID: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> I am trying to edit Contacts in Outlook. This is so I can transfer numbers from my address book which is an Excel spreadsheet to my mobile phone. I came across the following snippet of code which enabled me to the contacts at least list. I had to root around to discover CdoDefaultFolderContacts (though it was guessable; how could I enumerate win32com.client.constants?). I now want to work through the Contacts in Outlook patching in data from my spreadsheet, and also making new contacts where there is an entry in my spreadsheet which has not gone into Contacts already. Where can I find the API? I downloaded OutlookSpy but it is not clear to me that it can display the structure of the data, nor does it list methods for objects (a Contact, a Folder of Contacts) that I had hoped. TIA, Bill class Folder (object): def __init__ (self, folder): self._folder = folder def __getattr__ (self, attribute): return getattr (self._folder, attribute) def __iter__ (self): # # NB You *must* collect a reference to the # Messages collection here; otherwise GetFirst/Next # resets every time. # messages = self._folder.Messages message = messages.GetFirst () while message: yield message message = messages.GetNext () if __name__ == '__main__': import win32com.client session = win32com.client.gencache.EnsureDispatch ("MAPI.Session") constants = win32com.client.constants session.Logon ("Outlook") # # CdoDefaultFolderInbox # CdoDefaultFolderSentItems # CdoDefaultFolderContacts # contact_items = Folder (session.GetDefaultFolder (constants.CdoDefaultFolderContacts)) for message in contact_items: print message sys.exit(1) print message.Subject From bearophileHUGS at lycos.com Sun Jul 13 21:18:06 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 13 Jul 2008 18:18:06 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> <792048c1-5e18-4a2c-925d-a1c932d18a91@j22g2000hsf.googlegroups.com> Message-ID: <8923d0c5-29ce-495f-924a-6d9d2457138e@e39g2000hsf.googlegroups.com> bukzor: > You need to use two dictionaries. Here's a class that someone's > written that wraps it up into a single dict-like object for you: > http://www.faqts.com/knowledge_base/view.phtml/aid/4376 It contains code like: try: del self.data[item] except KeyError: pass Exceptions are useful in python, but with dictionaries this is probably faster (and shorter), even if it may perform two lookups: if item in self.data: del self.data[item] Bye, bearophile From rcdailey at gmail.com Thu Jul 3 16:53:37 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 3 Jul 2008 15:53:37 -0500 Subject: Recursive wildcard file search Message-ID: <496954360807031353n4f91f691recb330f7350cbf70@mail.gmail.com> Hi, Is there a way to perform a recursive file search using wildcards in python 3.0b1? For example, if I have: C:\foo\abc*xyz.* I want all files in C:\foo and all subfolders (recursively) of C:\foo that match the wildcard abc*xyz.* to be matched. In the end, I want a list of files that matched the search, as well as the directory they're located in. Help is appreciated. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From subhabrata.iisc at hotmail.com Fri Jul 18 06:40:15 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Fri, 18 Jul 2008 03:40:15 -0700 (PDT) Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> Message-ID: <3db7c643-56ca-4d6e-99eb-16176e1a2e88@d19g2000prm.googlegroups.com> Hi Peter, Peter Otten wrote: > SUBHABRATA wrote: > > > Thanx Peter, > > I would change my variables next time I would post. > > No, you should use meaningful variable names when you write your code no > matter whether you plan to post it or not. Good You are teaching me something good in life. Thanx. > > > And obviously, > > thanx for your solution. I am reviewing it, I was also trying out some > > solutions. > > You misunderstood. I did not modify your code other than changing the > variable names. My hope was that with this modification any errors sprang > to you eye... I was seeing that. I am almost near the solution. You can also try some hands if you feel. Best Regards, Subhabrata. > > Peter From ludovic.mercier at gmail.com Wed Jul 9 06:54:53 2008 From: ludovic.mercier at gmail.com (lidiriel) Date: Wed, 9 Jul 2008 03:54:53 -0700 (PDT) Subject: mock with inheritance Message-ID: <87df8aea-a7e4-4e30-9384-960b0a8cfc89@27g2000hsf.googlegroups.com> Hello, i would like use a mock object for testing one class and its methods: Here my class : class Foo(Component): def __init__(self): self._db = self.env.get_db() def foomethod(self, arg): ..... But i don't know how to mock the class Component. Note that Component provide the attribut env. I use Pyhton mock module (author Dave Kirby's ) or mock (author Michael Foord (fuzzyman)) but if you have a generic solution i will adapt it to my problem. Thanks by advance and sorry for my poor english. From carroll at nospam-tjc.com Thu Jul 17 11:55:06 2008 From: carroll at nospam-tjc.com (Terry Carroll) Date: Thu, 17 Jul 2008 08:55:06 -0700 Subject: How to process a very large (4Gb) tarfile from python? References: <0e96241d-60a3-44fd-967a-394904ad5b34@e39g2000hsf.googlegroups.com> Message-ID: <4nqu74p3mmmdmf9pn7125voe6itko8d31k@4ax.com> On Thu, 17 Jul 2008 06:14:45 -0700 (PDT), Uwe Schmitt wrote: >I had a look at tarfile.py in my current Python 2.5 installations >lib path. The iterator caches TarInfo objects in a list >tf.members . If you only want to iterate and you are not interested >in more functionallity, you could use "tf.members=[]" inside >your loop. This is a dirty hack ! Thanks, Uwe. That works fine for me. It now reads through all 2.5 million members, in about 30 minutes, never going above a 4M working set. From alif016 at gmail.com Mon Jul 21 19:00:23 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Mon, 21 Jul 2008 18:00:23 -0500 Subject: Converting List of String to Integer In-Reply-To: References: Message-ID: <48851507.5040907@gmail.com> Samir wrote: > On Jul 21, 6:15 pm, Andrew Freeman wrote: > >> Samir wrote: >> >>> On Jul 21, 3:20 pm, Gary Herron wrote: >>> >>>> Samir wrote: >>>> >>>>> Hi Everyone, >>>>> >>>>> I am relatively new to Python so please forgive me for what seems like >>>>> a basic question. >>>>> >>>>> Assume that I have a list, a, composed of nested lists with string >>>>> representations of integers, such that >>>>> >>>>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] >>>>> >>>>> I would like to convert this to a similar list, b, where the values >>>>> are represented by integers, such as >>>>> >>>>> b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] >>>>> >>>>> I have unsuccessfully tried the following code: >>>>> >>>>> n = [] >>>>> for k in a: >>>>> n.append([int(v) for v in k]) >>>>> print n >>>>> >>>>> Does anyone know what I am doing wrong? >>>>> >>>>> Thanks in advance. >>>>> >>>>> Samir >>>>> -- >>>>> http://mail.python.org/mailman/listinfo/python-list >>>>> >>>> You didn't tell us how it failed for you, so I can't guess what's wrong. >>>> >>>> However, your code works for me: >>>> >>>> >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] >>>> >>> n = [] >>>> >>> for k in a: >>>> ... n.append([int(v) for v in k]) >>>> ... >>>> >>> print n >>>> [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] >>>> >>>> (Although you seem to have confused variables b and n.) >>>> >>>> Gary Herron- Hide quoted text - >>>> >>>> - Show quoted text - >>>> >>> Hi Gary, >>> >>> Thanks for your quick response (and sorry about mixing up b and n). >>> For some reason, the logic I posted seems to work ok while I'm using >>> the Python shell, but when used in my code, the program just hangs. >>> It never outputs the results. Below is the code in its entirety. Is >>> there a problem with my indendentation? >>> >>> a = n = [] >>> t = """ >>> 1 2 >>> 3 >>> 4 5 6 >>> 7 8 9 0 >>> """ >>> >>> d = t.split("\n") >>> >>> for x in range(1,len(d)-1): >>> a.append(d[x].split(" ")) >>> print a >>> >>> for k in a: >>> n.append([int(v) for v in k]) >>> >>> print n >>> >>> Thanks again. >>> >>> Samir >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> I think this will work better, a sub-list comprehension of sorts: >> n = [[int(i) for i in k] for k in a] >> >> here is an ipython interactive session using it: >> In [1]: a = n = [] >> >> In [2]: t = """ >> ...: 1 2 >> ...: 3 >> ...: 4 5 6 >> ...: 7 8 9 0 >> ...: """ >> >> In [3]: >> >> In [4]: d = t.split("\n") >> >> In [5]: for x in range(1,len(d)-1): >> ...: a.append(d[x].split(" ")) >> ...: >> ...: >> >> In [6]: a >> Out[6]: [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] >> >> In [7]: n = [[int(i) for i in k] for k in a] >> >> In [8]: n >> Out[8]: [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] >> -- >> Andrew- Hide quoted text - >> >> - Show quoted text - >> > > Andrew, > > Thanks for the tip, though the syntax makes my head spin a bit in > trying to comprehend it. For my small list, I didn't notice a > discernible increase in speed, but I may have to try it with a larger > list size. > > Incidentally, I had never heard of iPython but from their web site, it > looks like an interesting tool. I'll have to check it out. > > Thanks. > > Samir > -- > http://mail.python.org/mailman/listinfo/python-list > If it helps look at this: n = [[int(i) for i in k] for k in a] like this: n = [] for k in a: for i in k: n.append(int(i)) It is more verbose and easier to read and they both do exactly the same thing! iPython is great, to install it you might try easy_install: http://peak.telecommunity.com/DevCenter/EasyInstall Then in a command line type: easy_install ipython Then, once it is complete, to use iPython type: ipython -- Andrew From larzluv at hotmail.com Fri Jul 18 14:43:41 2008 From: larzluv at hotmail.com (Larry Hale) Date: Fri, 18 Jul 2008 11:43:41 -0700 (PDT) Subject: Python Behind a Squid Corporate Proxy on Windows References: <7b541a3b-846f-496a-aee1-d5719217e011@m45g2000hsb.googlegroups.com> <821d7616-3faa-4dae-a988-18caf4f8598a@8g2000hse.googlegroups.com> <84c473ed-6993-481a-b789-35851242895b@f1g2000prb.googlegroups.com> Message-ID: Thank you so much for the reply, but alas: I get the same results. (urllib2 makes the initial request, Squid replies "Error 407: Proxy Authentication Required", which urllib2 dutifully fails on/raises said error...) I do appreciate your time, though! :) -Larry On Jul 18, 3:08?am, Chris wrote: > On Jul 17, 6:40?pm, Larry Hale wrote: > > > Err, the line above should be: > > > proxy_handler = urllib2.ProxyHandler( { "http": "http:// > > myusername:passw... at webfilter.xyz.local:3128" } ) > > > (Sorry! ?:) > > some old code I wrote to download public domain info for our company, > also through a squid proxy and this still works for me > > import urllib2, urllib > > proxy = urllib2.ProxyHandler({'http': 'http:// > username:password at proxy_url:proxy_port'}) > auth = urllib2.HTTPBasicAuthHandler() > opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) > urllib2.install_opener(opener) > > conn = urllib2.urlopen('http://python.org') > return_str = conn.read() > > fp = open('python.html','w').write(return_str) From mercado949 at gmail.com Thu Jul 17 19:14:56 2008 From: mercado949 at gmail.com (mercado mercado) Date: Thu, 17 Jul 2008 19:14:56 -0400 Subject: Importing different versions of a module Message-ID: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> I have two versions of a script on my machine. One version is for new development and the other version is a production version. This script imports a module from a different directory, and this module again has two versions (a development version and a production version). What I want is for the development script to import the development module, and the production script to import the production module, without making any changes to the code in the script. For example, suppose the development script is in ~/dev/rss.py, and the production script is in ~/prod/rss.py. I want the dev version to import /usr/lib/python2.5/site-packages/lib_dev/parse.py, and the prod version to import usr/lib/python2.5/site-packages/lib_prod/parse.py. My first instinct was to place a .pth file in ~/dev that points to /usr/lib/python2.5/site-packages/lib_dev, and a .pth file in ~/prod that points to /usr/lib/python2.5/site-packages/lib_prod, but it seems that site.py doesn't look at .pth files in the current working directory. My next attempt was to create a symbolic link in ~/dev called parse.py, pointing to /usr/lib/python2.5/site-packages/lib_dev/parse.py, and a symbolic link in ~/prod called parse.py, pointing to /usr/lib/python2.5/site-packages/lib_prod/parse.py, but that didn't work either. Can anybody suggest a way to achieve my goal? Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From babacity4 at gmail.com Thu Jul 24 16:51:09 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:51:09 -0700 (PDT) Subject: sextv1 tv - Amazing porn video collection Message-ID: <03e2be10-3838-46b4-963f-e1d1425a314a@y22g2000prd.googlegroups.com> sextv1 tv . >>>>>>>>>>Best Collection of Sextv1 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE sextv1 tv VIDEOS<<<<<<<<<<< . sextv1 tv From mensanator at aol.com Mon Jul 21 18:58:20 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 21 Jul 2008 15:58:20 -0700 (PDT) Subject: Python Written in C? References: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> Message-ID: <943d208b-35f6-4010-85de-fa034e12b5a8@m36g2000hse.googlegroups.com> On Jul 21, 8:26?am, Johannes Bauer wrote: > Mensanator schrieb: > > > You want cool? > > THIS is cool: > > > j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2])) > > % xyz[1]**(k-1))/xyz[1]**(k-2) > > You call it cool, I call it NameError: name 'invert' is not defined. It is when you do: from gmpy import * That single line wasn't the whole program. What's cool is that it IS a single line, that does answers with >50000 decimal digits without breaking a sweat. Sure, you can use GMP with C (and I've done it). But it's nothing like doing it in Python. > > Regards, > Johannes > > -- > "Wer etwas kritisiert muss es noch lange nicht selber besser k?nnen. Es > reicht zu wissen, da? andere es besser k?nnen und andere es auch > besser machen um einen Vergleich zu bringen." ? ? - ? ? Wolfgang Gerber > ? ? ? ?in de.sci.electronics <47fa8447$0$11545$9b622... at news.freenet.de> From tjreedy at udel.edu Sun Jul 27 02:18:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 02:18:56 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <488B9135.3010308@ncf.ca> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> Message-ID: Colin J. Williams wrote: > Russ P. wrote: >> class MyClass: >> >> def func( , xxx, yyy): >> >> .xxx = xxx >> >> local = .yyy The use of '.' has been suggested before and rejected. From Lie.1296 at gmail.com Sun Jul 27 01:04:48 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 26 Jul 2008 22:04:48 -0700 (PDT) Subject: xml.dom's weirdness? References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> Message-ID: <1c837e71-a191-4495-8ec8-0126003ba9c6@n33g2000pri.googlegroups.com> On Jul 26, 6:03?pm, Fredrik Lundh wrote: > Lie wrote: > > If you have any idea what black magic is happening in my computer > > right now, I'd appreciate it. > > command completion? ?(no ubuntu within reach right now, so I cannot > check how they've set it up). > > try starting python with the "-v" option, so you can see exactly when > the import occurs. > > I run python as: python -v &> pyth.log As I've predicted, they imported the modules when there is an Error, any Error, it seems. I have made a hypothesis that it seems that there is something wrong with the Error Handler, it seems that Python have leaked the modules the Error handler used to my session. Although I am unable to access the modules itself unless I imported those modules by myself, any sub- modules that is loaded by the Error Handler is already loaded, so in my session, those modules are merely rebound to a name in my namespace. Question: Is there a way to list loaded modules, including those that aren't in my namespace? Remarks: In another, possibly unrelated, possibly related case, every time I typed: "help(modules)" (to list all modules installed on the system) I've got an error, I've previously made a thread about this in c.l.py, but I don't really mind that much back then since listing installed modules aren't that important for me (I can lookup standardly installed modules in the internet and the number of 3rd party modules installed, I can count with the fingers from a hand). The thread was: http://groups.google.com/group/comp.lang.python/browse_thread/thread/e981edb45fb3854a/ This is an example of the terminal session me at my-computer:~$ python -v &> pyth.log be_nice = 100 doerror xml import xml xml.dom import email email.mime exit() Python doesn't emit the prompts >>> because they're redirected to pyth.log Here is the SUMMARY of pyth.log (the real one is very long, so I append it at the end) * Typed "python -v &> pyth.log" to terminal * Python imports many modules: zipimport, site, os, errno, posix, posixpath, stat, UserDict, copy_reg, types, _types, sitecustomize, apport_python_hook, warnings, linecache, encodings (# directory /usr/lib/python2.5/encodings), encodings (# precompiled from /usr/lib/python2.5/encodings/ __init__.pyc), codecs, _codecs, encodings.aliases, encodings.utf_8 * Standard Python Heading: Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. * I don't know what this is: dlopen("/usr/lib/python2.5/lib-dynload/ readline.so", 2); * Python imported readline module * Python prompt: I typed "be_nice = 100", no output * Python prompt: I typed "doerror" (since doerror is not defined, it raises NameError, I've tried many other errors, like arithmetic error, etc and they did similar thing), python response with loading a lot of modules: apport (# directory /usr/lib/python2.5/site-packages/apport), apport (# precompiled from /usr/lib/python2.5/site-packages/apport/ __init__.pyc), apport.report, subprocess, traceback, gc, time, select, fcntl, pickle, marshal, struct, _struct, re, sre_compile, _sre, sre_constants, sre_parse, binascii, cStringIO, tempfile, random, math, _random, thread, urllib, string, strop, socket, _socket, _ssl, urlparse, pwd, grp, fnmatch, glob, atexit, xml, xml.dom, xml.dom.domreg, xml.dom.minicompat, xml.dom.minidom, xml.dom.xmlbuilder, copy, xml.dom.NodeFilter, xml.parsers (# directory /usr/lib/python2.5/xml/parsers), xml.parsers (# precompiled from /usr/lib/python2.5/xml/parsers/ __init__.pyc), xml.parsers.expat, pyexpat, problem_report, zlib, base64, gzip, email, email.mime (# directory /usr/lib/python2.5/email/mime), email.mime (# precompiled from /usr/lib/python2.5/email/mime/ __init__.pyc), email.encoders, email.quopri, email.mime.multipart, email.mime.base, email.message, uu, email.charset, email.base64mime, email.utils, email._parseaddr, email.quoprimime, email.errors, email.iterators, email.mime.text, email.mime.nonmultipart, unittest, apport.fileutils, apport.packaging.impl, apt (# directory /usr/lib/python2.5/site-packages/apt), apt (# precompiled from /usr/lib/python2.5/site-packages/apt/ __init__.pyc), apt_pkg, apt.package, gettext, locale, _locale, operator, apt.cache, apt.progress, apt.cdrom, apport.packaging, shutil. Among these imports, there are lines like these interleaved (generally right before the import of the modules with the same name): dlopen("/usr/lib/python2.5/lib-dynload/time.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/select.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/fcntl.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/_struct.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/binascii.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/cStringIO.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/math.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/_random.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/strop.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/_socket.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/_ssl.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/grp.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/pyexpat.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/zlib.so", 2); dlopen("/usr/lib/python2.5/site-packages/apt_pkg.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/_locale.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/operator.so", 2); * After those imports is the standard Python traceback (because of the doerror we made earlier) Traceback (most recent call last): File "", line 1, in NameError: name 'doerror' is not defined * The next few lines (edited[1] form the original, for viewing convenience): >>> xml Traceback (most recent call last): File "", line 1, in NameError: name 'xml' is not defined >>> import xml >>> xml.dom >>> import email >>> email.mime [1] Since this is a dump from IO redirection, the texts coming from stdin is absent, I inserted those stdin manually, so it looks more like terminal transcript, instead of IO redirection. * Python prompt - I typed "exit()", it displayed messages of it clearing itself and cleaning up the modules it have loaded TERMINAL TRANSCRIPT (the one already edited, to get the original, apply the diff far below): # installing zipimport hook import zipimport # builtin # installed zipimport hook # /usr/lib/python2.5/site.pyc matches /usr/lib/python2.5/site.py import site # precompiled from /usr/lib/python2.5/site.pyc # /usr/lib/python2.5/os.pyc matches /usr/lib/python2.5/os.py import os # precompiled from /usr/lib/python2.5/os.pyc import errno # builtin import posix # builtin # /usr/lib/python2.5/posixpath.pyc matches /usr/lib/python2.5/ posixpath.py import posixpath # precompiled from /usr/lib/python2.5/posixpath.pyc # /usr/lib/python2.5/stat.pyc matches /usr/lib/python2.5/stat.py import stat # precompiled from /usr/lib/python2.5/stat.pyc # /usr/lib/python2.5/UserDict.pyc matches /usr/lib/python2.5/ UserDict.py import UserDict # precompiled from /usr/lib/python2.5/UserDict.pyc # /usr/lib/python2.5/copy_reg.pyc matches /usr/lib/python2.5/ copy_reg.py import copy_reg # precompiled from /usr/lib/python2.5/copy_reg.pyc # /usr/lib/python2.5/types.pyc matches /usr/lib/python2.5/types.py import types # precompiled from /usr/lib/python2.5/types.pyc import _types # builtin # /usr/lib/python2.5/sitecustomize.pyc matches /usr/lib/python2.5/ sitecustomize.py import sitecustomize # precompiled from /usr/lib/python2.5/ sitecustomize.pyc # /usr/lib/python2.5/site-packages/apport_python_hook.pyc matches /usr/ lib/python2.5/site-packages/apport_python_hook.py import apport_python_hook # precompiled from /usr/lib/python2.5/site- packages/apport_python_hook.pyc # /usr/lib/python2.5/warnings.pyc matches /usr/lib/python2.5/ warnings.py import warnings # precompiled from /usr/lib/python2.5/warnings.pyc # /usr/lib/python2.5/linecache.pyc matches /usr/lib/python2.5/ linecache.py import linecache # precompiled from /usr/lib/python2.5/linecache.pyc import encodings # directory /usr/lib/python2.5/encodings # /usr/lib/python2.5/encodings/__init__.pyc matches /usr/lib/python2.5/ encodings/__init__.py import encodings # precompiled from /usr/lib/python2.5/encodings/ __init__.pyc # /usr/lib/python2.5/codecs.pyc matches /usr/lib/python2.5/codecs.py import codecs # precompiled from /usr/lib/python2.5/codecs.pyc import _codecs # builtin # /usr/lib/python2.5/encodings/aliases.pyc matches /usr/lib/python2.5/ encodings/aliases.py import encodings.aliases # precompiled from /usr/lib/python2.5/ encodings/aliases.pyc # /usr/lib/python2.5/encodings/utf_8.pyc matches /usr/lib/python2.5/ encodings/utf_8.py import encodings.utf_8 # precompiled from /usr/lib/python2.5/encodings/ utf_8.pyc Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. dlopen("/usr/lib/python2.5/lib-dynload/readline.so", 2); import readline # dynamically loaded from /usr/lib/python2.5/lib- dynload/readline.so >>> be_nice = 100 >>> doerror import apport # directory /usr/lib/python2.5/site-packages/apport # /usr/lib/python2.5/site-packages/apport/__init__.pyc matches /usr/ lib/python2.5/site-packages/apport/__init__.py import apport # precompiled from /usr/lib/python2.5/site-packages/ apport/__init__.pyc # /usr/lib/python2.5/site-packages/apport/report.pyc matches /usr/lib/ python2.5/site-packages/apport/report.py import apport.report # precompiled from /usr/lib/python2.5/site- packages/apport/report.pyc # /usr/lib/python2.5/subprocess.pyc matches /usr/lib/python2.5/ subprocess.py import subprocess # precompiled from /usr/lib/python2.5/subprocess.pyc # /usr/lib/python2.5/traceback.pyc matches /usr/lib/python2.5/ traceback.py import traceback # precompiled from /usr/lib/python2.5/traceback.pyc import gc # builtin dlopen("/usr/lib/python2.5/lib-dynload/time.so", 2); import time # dynamically loaded from /usr/lib/python2.5/lib-dynload/ time.so dlopen("/usr/lib/python2.5/lib-dynload/select.so", 2); import select # dynamically loaded from /usr/lib/python2.5/lib-dynload/ select.so dlopen("/usr/lib/python2.5/lib-dynload/fcntl.so", 2); import fcntl # dynamically loaded from /usr/lib/python2.5/lib-dynload/ fcntl.so # /usr/lib/python2.5/pickle.pyc matches /usr/lib/python2.5/pickle.py import pickle # precompiled from /usr/lib/python2.5/pickle.pyc import marshal # builtin # /usr/lib/python2.5/struct.pyc matches /usr/lib/python2.5/struct.py import struct # precompiled from /usr/lib/python2.5/struct.pyc dlopen("/usr/lib/python2.5/lib-dynload/_struct.so", 2); import _struct # dynamically loaded from /usr/lib/python2.5/lib- dynload/_struct.so # /usr/lib/python2.5/re.pyc matches /usr/lib/python2.5/re.py import re # precompiled from /usr/lib/python2.5/re.pyc # /usr/lib/python2.5/sre_compile.pyc matches /usr/lib/python2.5/ sre_compile.py import sre_compile # precompiled from /usr/lib/python2.5/ sre_compile.pyc import _sre # builtin # /usr/lib/python2.5/sre_constants.pyc matches /usr/lib/python2.5/ sre_constants.py import sre_constants # precompiled from /usr/lib/python2.5/ sre_constants.pyc # /usr/lib/python2.5/sre_parse.pyc matches /usr/lib/python2.5/ sre_parse.py import sre_parse # precompiled from /usr/lib/python2.5/sre_parse.pyc dlopen("/usr/lib/python2.5/lib-dynload/binascii.so", 2); import binascii # dynamically loaded from /usr/lib/python2.5/lib- dynload/binascii.so dlopen("/usr/lib/python2.5/lib-dynload/cStringIO.so", 2); import cStringIO # dynamically loaded from /usr/lib/python2.5/lib- dynload/cStringIO.so # /usr/lib/python2.5/tempfile.pyc matches /usr/lib/python2.5/ tempfile.py import tempfile # precompiled from /usr/lib/python2.5/tempfile.pyc # /usr/lib/python2.5/random.pyc matches /usr/lib/python2.5/random.py import random # precompiled from /usr/lib/python2.5/random.pyc dlopen("/usr/lib/python2.5/lib-dynload/math.so", 2); import math # dynamically loaded from /usr/lib/python2.5/lib-dynload/ math.so dlopen("/usr/lib/python2.5/lib-dynload/_random.so", 2); import _random # dynamically loaded from /usr/lib/python2.5/lib- dynload/_random.so import thread # builtin # /usr/lib/python2.5/urllib.pyc matches /usr/lib/python2.5/urllib.py import urllib # precompiled from /usr/lib/python2.5/urllib.pyc # /usr/lib/python2.5/string.pyc matches /usr/lib/python2.5/string.py import string # precompiled from /usr/lib/python2.5/string.pyc dlopen("/usr/lib/python2.5/lib-dynload/strop.so", 2); import strop # dynamically loaded from /usr/lib/python2.5/lib-dynload/ strop.so # /usr/lib/python2.5/socket.pyc matches /usr/lib/python2.5/socket.py import socket # precompiled from /usr/lib/python2.5/socket.pyc dlopen("/usr/lib/python2.5/lib-dynload/_socket.so", 2); import _socket # dynamically loaded from /usr/lib/python2.5/lib- dynload/_socket.so dlopen("/usr/lib/python2.5/lib-dynload/_ssl.so", 2); import _ssl # dynamically loaded from /usr/lib/python2.5/lib-dynload/ _ssl.so # /usr/lib/python2.5/urlparse.pyc matches /usr/lib/python2.5/ urlparse.py import urlparse # precompiled from /usr/lib/python2.5/urlparse.pyc import pwd # builtin dlopen("/usr/lib/python2.5/lib-dynload/grp.so", 2); import grp # dynamically loaded from /usr/lib/python2.5/lib-dynload/ grp.so # /usr/lib/python2.5/fnmatch.pyc matches /usr/lib/python2.5/fnmatch.py import fnmatch # precompiled from /usr/lib/python2.5/fnmatch.pyc # /usr/lib/python2.5/glob.pyc matches /usr/lib/python2.5/glob.py import glob # precompiled from /usr/lib/python2.5/glob.pyc # /usr/lib/python2.5/atexit.pyc matches /usr/lib/python2.5/atexit.py import atexit # precompiled from /usr/lib/python2.5/atexit.pyc import xml # directory /usr/lib/python2.5/xml # /usr/lib/python2.5/xml/__init__.pyc matches /usr/lib/python2.5/xml/ __init__.py import xml # precompiled from /usr/lib/python2.5/xml/__init__.pyc import xml.dom # directory /usr/lib/python2.5/xml/dom # /usr/lib/python2.5/xml/dom/__init__.pyc matches /usr/lib/python2.5/ xml/dom/__init__.py import xml.dom # precompiled from /usr/lib/python2.5/xml/dom/ __init__.pyc # /usr/lib/python2.5/xml/dom/domreg.pyc matches /usr/lib/python2.5/xml/ dom/domreg.py import xml.dom.domreg # precompiled from /usr/lib/python2.5/xml/dom/ domreg.pyc # /usr/lib/python2.5/xml/dom/minicompat.pyc matches /usr/lib/python2.5/ xml/dom/minicompat.py import xml.dom.minicompat # precompiled from /usr/lib/python2.5/xml/ dom/minicompat.pyc # /usr/lib/python2.5/xml/dom/minidom.pyc matches /usr/lib/python2.5/ xml/dom/minidom.py import xml.dom.minidom # precompiled from /usr/lib/python2.5/xml/dom/ minidom.pyc # /usr/lib/python2.5/xml/dom/xmlbuilder.pyc matches /usr/lib/python2.5/ xml/dom/xmlbuilder.py import xml.dom.xmlbuilder # precompiled from /usr/lib/python2.5/xml/ dom/xmlbuilder.pyc # /usr/lib/python2.5/copy.pyc matches /usr/lib/python2.5/copy.py import copy # precompiled from /usr/lib/python2.5/copy.pyc # /usr/lib/python2.5/xml/dom/NodeFilter.pyc matches /usr/lib/python2.5/ xml/dom/NodeFilter.py import xml.dom.NodeFilter # precompiled from /usr/lib/python2.5/xml/ dom/NodeFilter.pyc import xml.parsers # directory /usr/lib/python2.5/xml/parsers # /usr/lib/python2.5/xml/parsers/__init__.pyc matches /usr/lib/ python2.5/xml/parsers/__init__.py import xml.parsers # precompiled from /usr/lib/python2.5/xml/parsers/ __init__.pyc # /usr/lib/python2.5/xml/parsers/expat.pyc matches /usr/lib/python2.5/ xml/parsers/expat.py import xml.parsers.expat # precompiled from /usr/lib/python2.5/xml/ parsers/expat.pyc dlopen("/usr/lib/python2.5/lib-dynload/pyexpat.so", 2); import pyexpat # dynamically loaded from /usr/lib/python2.5/lib- dynload/pyexpat.so # /usr/lib/python2.5/site-packages/problem_report.pyc matches /usr/lib/ python2.5/site-packages/problem_report.py import problem_report # precompiled from /usr/lib/python2.5/site- packages/problem_report.pyc dlopen("/usr/lib/python2.5/lib-dynload/zlib.so", 2); import zlib # dynamically loaded from /usr/lib/python2.5/lib-dynload/ zlib.so # /usr/lib/python2.5/base64.pyc matches /usr/lib/python2.5/base64.py import base64 # precompiled from /usr/lib/python2.5/base64.pyc # /usr/lib/python2.5/gzip.pyc matches /usr/lib/python2.5/gzip.py import gzip # precompiled from /usr/lib/python2.5/gzip.pyc import email # directory /usr/lib/python2.5/email # /usr/lib/python2.5/email/__init__.pyc matches /usr/lib/python2.5/ email/__init__.py import email # precompiled from /usr/lib/python2.5/email/__init__.pyc import email.mime # directory /usr/lib/python2.5/email/mime # /usr/lib/python2.5/email/mime/__init__.pyc matches /usr/lib/ python2.5/email/mime/__init__.py import email.mime # precompiled from /usr/lib/python2.5/email/mime/ __init__.pyc # /usr/lib/python2.5/email/encoders.pyc matches /usr/lib/python2.5/ email/encoders.py import email.encoders # precompiled from /usr/lib/python2.5/email/ encoders.pyc # /usr/lib/python2.5/quopri.pyc matches /usr/lib/python2.5/quopri.py import quopri # precompiled from /usr/lib/python2.5/quopri.pyc # /usr/lib/python2.5/email/mime/multipart.pyc matches /usr/lib/ python2.5/email/mime/multipart.py import email.mime.multipart # precompiled from /usr/lib/python2.5/ email/mime/multipart.pyc # /usr/lib/python2.5/email/mime/base.pyc matches /usr/lib/python2.5/ email/mime/base.py import email.mime.base # precompiled from /usr/lib/python2.5/email/ mime/base.pyc # /usr/lib/python2.5/email/message.pyc matches /usr/lib/python2.5/ email/message.py import email.message # precompiled from /usr/lib/python2.5/email/ message.pyc # /usr/lib/python2.5/uu.pyc matches /usr/lib/python2.5/uu.py import uu # precompiled from /usr/lib/python2.5/uu.pyc # /usr/lib/python2.5/email/charset.pyc matches /usr/lib/python2.5/ email/charset.py import email.charset # precompiled from /usr/lib/python2.5/email/ charset.pyc # /usr/lib/python2.5/email/base64mime.pyc matches /usr/lib/python2.5/ email/base64mime.py import email.base64mime # precompiled from /usr/lib/python2.5/email/ base64mime.pyc # /usr/lib/python2.5/email/utils.pyc matches /usr/lib/python2.5/email/ utils.py import email.utils # precompiled from /usr/lib/python2.5/email/ utils.pyc # /usr/lib/python2.5/email/_parseaddr.pyc matches /usr/lib/python2.5/ email/_parseaddr.py import email._parseaddr # precompiled from /usr/lib/python2.5/email/ _parseaddr.pyc # /usr/lib/python2.5/email/quoprimime.pyc matches /usr/lib/python2.5/ email/quoprimime.py import email.quoprimime # precompiled from /usr/lib/python2.5/email/ quoprimime.pyc # /usr/lib/python2.5/email/errors.pyc matches /usr/lib/python2.5/email/ errors.py import email.errors # precompiled from /usr/lib/python2.5/email/ errors.pyc # /usr/lib/python2.5/email/iterators.pyc matches /usr/lib/python2.5/ email/iterators.py import email.iterators # precompiled from /usr/lib/python2.5/email/ iterators.pyc # /usr/lib/python2.5/email/mime/text.pyc matches /usr/lib/python2.5/ email/mime/text.py import email.mime.text # precompiled from /usr/lib/python2.5/email/ mime/text.pyc # /usr/lib/python2.5/email/mime/nonmultipart.pyc matches /usr/lib/ python2.5/email/mime/nonmultipart.py import email.mime.nonmultipart # precompiled from /usr/lib/python2.5/ email/mime/nonmultipart.pyc # /usr/lib/python2.5/unittest.pyc matches /usr/lib/python2.5/ unittest.py import unittest # precompiled from /usr/lib/python2.5/unittest.pyc # /usr/lib/python2.5/site-packages/apport/fileutils.pyc matches /usr/ lib/python2.5/site-packages/apport/fileutils.py import apport.fileutils # precompiled from /usr/lib/python2.5/site- packages/apport/fileutils.pyc # /usr/lib/python2.5/site-packages/apport/packaging_impl.pyc matches / usr/lib/python2.5/site-packages/apport/packaging_impl.py import apport.packaging_impl # precompiled from /usr/lib/python2.5/ site-packages/apport/packaging_impl.pyc import apt # directory /usr/lib/python2.5/site-packages/apt # /usr/lib/python2.5/site-packages/apt/__init__.pyc matches /usr/lib/ python2.5/site-packages/apt/__init__.py import apt # precompiled from /usr/lib/python2.5/site-packages/apt/ __init__.pyc dlopen("/usr/lib/python2.5/site-packages/apt_pkg.so", 2); import apt_pkg # dynamically loaded from /usr/lib/python2.5/site- packages/apt_pkg.so # /usr/lib/python2.5/site-packages/apt/package.pyc matches /usr/lib/ python2.5/site-packages/apt/package.py import apt.package # precompiled from /usr/lib/python2.5/site-packages/ apt/package.pyc # /usr/lib/python2.5/gettext.pyc matches /usr/lib/python2.5/gettext.py import gettext # precompiled from /usr/lib/python2.5/gettext.pyc # /usr/lib/python2.5/locale.pyc matches /usr/lib/python2.5/locale.py import locale # precompiled from /usr/lib/python2.5/locale.pyc dlopen("/usr/lib/python2.5/lib-dynload/_locale.so", 2); import _locale # dynamically loaded from /usr/lib/python2.5/lib- dynload/_locale.so dlopen("/usr/lib/python2.5/lib-dynload/operator.so", 2); import operator # dynamically loaded from /usr/lib/python2.5/lib- dynload/operator.so # /usr/lib/python2.5/site-packages/apt/cache.pyc matches /usr/lib/ python2.5/site-packages/apt/cache.py import apt.cache # precompiled from /usr/lib/python2.5/site-packages/ apt/cache.pyc # /usr/lib/python2.5/site-packages/apt/progress.pyc matches /usr/lib/ python2.5/site-packages/apt/progress.py import apt.progress # precompiled from /usr/lib/python2.5/site- packages/apt/progress.pyc # /usr/lib/python2.5/site-packages/apt/cdrom.pyc matches /usr/lib/ python2.5/site-packages/apt/cdrom.py import apt.cdrom # precompiled from /usr/lib/python2.5/site-packages/ apt/cdrom.pyc # /usr/lib/python2.5/site-packages/apport/packaging.pyc matches /usr/ lib/python2.5/site-packages/apport/packaging.py import apport.packaging # precompiled from /usr/lib/python2.5/site- packages/apport/packaging.pyc # /usr/lib/python2.5/shutil.pyc matches /usr/lib/python2.5/shutil.py import shutil # precompiled from /usr/lib/python2.5/shutil.pyc Traceback (most recent call last): File "", line 1, in NameError: name 'doerror' is not defined >>> xml Traceback (most recent call last): File "", line 1, in NameError: name 'xml' is not defined >>> import xml >>> xml.dom >>> import email >>> email.mime >>> exit() # clear __builtin__._ # clear sys.path # clear sys.argv # clear sys.ps1 # clear sys.ps2 # clear sys.exitfunc # clear sys.exc_type # clear sys.exc_value # clear sys.exc_traceback # clear sys.last_type # clear sys.last_value # clear sys.last_traceback # clear sys.path_hooks # clear sys.path_importer_cache # clear sys.meta_path # restore sys.stdin # restore sys.stdout # restore sys.stderr # cleanup __main__ # cleanup[1] apport # cleanup[1] zipimport # cleanup[1] quopri # cleanup[1] cStringIO # cleanup[1] apport.report # cleanup[1] math # cleanup[1] exceptions # cleanup[1] _locale # cleanup[1] sre_constants # cleanup[1] _codecs # cleanup[1] pwd # cleanup[1] _struct # cleanup[1] _types # cleanup[1] posix # cleanup[1] site # cleanup[1] problem_report # cleanup[1] pyexpat # cleanup[1] strop # cleanup[1] grp # cleanup[1] readline # cleanup[1] sitecustomize # cleanup[1] apport.packaging # cleanup[1] urlparse # cleanup[1] gzip # cleanup[1] signal # cleanup[1] apport.packaging_impl # cleanup[1] zlib # cleanup[1] apport.fileutils # cleanup[1] atexit # cleanup[1] unittest # cleanup[1] apport_python_hook # cleanup[1] shutil # cleanup[1] glob # cleanup[1] subprocess # cleanup[1] gc # cleanup[1] tempfile # cleanup[1] thread # cleanup[1] traceback # cleanup[1] fnmatch # cleanup[1] pickle # cleanup[1] marshal # cleanup[2] email.iterators # cleanup[2] random # cleanup[2] types # cleanup[2] email.mime # cleanup[2] xml # cleanup[2] struct # cleanup[2] base64 # cleanup[2] apt.cache # cleanup[2] pyexpat.errors # cleanup[2] apt_pkg # cleanup[2] encodings.utf_8 # cleanup[2] email.quoprimime # cleanup[2] email.mime.text # cleanup[2] email.encoders # cleanup[2] pyexpat.model # cleanup[2] locale # cleanup[2] email.charset # cleanup[2] xml.parsers.expat # cleanup[2] encodings # cleanup[2] urllib # cleanup[2] re # cleanup[2] email.mime.base # cleanup[2] email.errors # cleanup[2] email # cleanup[2] fcntl # cleanup[2] apt.progress # cleanup[2] UserDict # cleanup[2] codecs # cleanup[2] xml.dom.domreg # cleanup[2] socket # cleanup[2] xml.dom.xmlbuilder # cleanup[2] os # cleanup[2] _sre # cleanup[2] xml.parsers # cleanup[2] operator # cleanup[2] select # cleanup[2] posixpath # cleanup[2] errno # cleanup[2] _socket # cleanup[2] binascii # cleanup[2] email._parseaddr # cleanup[2] os.path # cleanup[2] apt.package # cleanup[2] xml.dom.NodeFilter # cleanup[2] email.utils # cleanup[2] copy # cleanup[2] apt.cdrom # cleanup[2] uu # cleanup[2] xml.dom.minidom # cleanup[2] apt # cleanup[2] encodings.aliases # cleanup[2] sre_parse # cleanup[2] copy_reg # cleanup[2] sre_compile # cleanup[2] _random # cleanup[2] email.message # cleanup[2] string # cleanup[2] email.mime.nonmultipart # cleanup[2] gettext # cleanup[2] xml.dom.minicompat # cleanup[2] stat # cleanup[2] _ssl # cleanup[2] warnings # cleanup[2] xml.dom # cleanup[2] email.base64mime # cleanup[2] email.mime.multipart # cleanup[2] linecache # cleanup[2] time # cleanup sys # cleanup __builtin__ # cleanup ints: 58 unfreed ints in 7 out of 17 blocks # cleanup floats: 33 unfreed floats in 2 out of 3 blocks 44,46c44 < >>> be_nice = 100 < >>> doerror < import apport # directory /usr/lib/python2.5/site-packages/apport --- > >>> >>> import apport # directory /usr/lib/python2.5/site-packages/apport 217,218c215 < >>> xml < Traceback (most recent call last): --- > >>> Traceback (most recent call last): 221,228c218,220 < >>> import xml < >>> xml.dom < < >>> import email < >>> email.mime < < >>> exit() < # clear __builtin__._ --- > >>> >>> > >>> >>> > >>> # clear __builtin__._ DIFF TO RAW TRANSCRIPT 44,46c44 < >>> be_nice = 100 < >>> doerror < import apport # directory /usr/lib/python2.5/site-packages/apport --- > >>> >>> import apport # directory /usr/lib/python2.5/site-packages/apport 217,218c215 < >>> xml < Traceback (most recent call last): --- > >>> Traceback (most recent call last): 221,228c218,220 < >>> import xml < >>> xml.dom < < >>> import email < >>> email.mime < < >>> exit() < # clear __builtin__._ --- > >>> >>> > >>> >>> > >>> # clear __builtin__._ From workitharder at gmail.com Fri Jul 25 17:08:01 2008 From: workitharder at gmail.com (bukzor) Date: Fri, 25 Jul 2008 14:08:01 -0700 (PDT) Subject: Easier way to get the "here" path? Message-ID: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> I have to go into these convulsions to get the directory that the script is in whenever I need to use relative paths. I was wondering if you guys have a better way: from os.path import dirname, realpath, abspath here = dirname(realpath(abspath(__file__.rstrip("c")))) In particular, this takes care of the case of symlinked, compiled scripts, which is fairly common at my workplace, and I imagine in many *nix evironments. An illustration: $echo "print __file__" > symlinks/path.py $ln -s symlinks/path.py $python >>> import path path.py >>> reload(path) path.pyc >>> path.__file__ 'path.pyc' >>> path.__file__.rstrip("c") 'path.py' >>> from os.path import abspath, realpath >>> realpath(path.__file__.rstrip("c")) '/home/bgolemon/python/symlinks/path.py' >>> realpath(abspath(path.__file__.rstrip("c"))) '/home/bgolemon/python/symlinks/symlinks/path.py' From aahz at pythoncraft.com Wed Jul 23 18:25:56 2008 From: aahz at pythoncraft.com (Aahz) Date: 23 Jul 2008 15:25:56 -0700 Subject: software engineering foundations? References: Message-ID: In article , wrote: > >There are software construction skills which are entirely distinct from the >language in which you are programming. We can tout object-oriented, >structured programming, test-driven development or other software >engineering techniques, but there is a body of knowledge out there which is >orthogonal to the language in which the code is written. People who are not >professional programmers often lack those skills and their code shows it. > >Are there any good online resources for this "software structure" axis? While this doesn't really directly address your question, I think that anyone who wants to do serious programming of any sort really should read _The Mythical Man-Month_ by Fred Brooks -- make sure to get the 25th anniversary edition. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From desothier at yahoo.com Thu Jul 17 04:30:47 2008 From: desothier at yahoo.com (antar2) Date: Thu, 17 Jul 2008 01:30:47 -0700 (PDT) Subject: common elements between list of lists and lists Message-ID: <2724c6f8-d75d-4fc2-ac8f-310f4f622aae@p25g2000hsf.googlegroups.com> Hello, I am a beginner in python. following program prints the second element in list of lists 4 for the first elements in list 4 that are common with the elements in list 5 list4 = [['1', 'a'],['4', 'd'],['8', 'g']] list5 = ['1', '2', '3'] for j in list4: for k in list5: if j[0] == k: print j[1] Result: a I would like to do the same thing starting with following lists, where the numbers in list 5 are without ''. Is there a way to convert integers in a list to integers in '' ? This is based on a situation where I want to find common numbers between a list and a list of lists where the numbers in the list are without '' and the numbers in the list of lists are with '' list4 = [['1', 'a'],['4', 'd'],['8', 'g']] list5 = [1, 2, 3] This might be a stupid question, but anyway, thanks for your answer It is not my first post on this site. In some way it is not possible to react on the messages that I receive to thank the persons that react. Anyway, thanks a lot From larry.bates at websafe.com` Tue Jul 15 10:21:29 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 09:21:29 -0500 Subject: logging via SocketHandler and TCPserver In-Reply-To: References: <81929250-449b-4686-acf3-dcc0095e341a@d1g2000hsg.googlegroups.com> Message-ID: Vinay Sajip wrote: > On Jul 14, 11:16 pm, Larry Bates wrote: >> Vinay, >> >> Thanks for your detailed explanation, but IMHO your suggested solution is almost >> the opposite (right idea wrong direction) of what I'm looking for. Hypothetical >> setup: >> >> application1 - SocketHandlerloggingturned on >> application2 - SocketHandlerloggingturned on >> application3 - SocketHandlerloggingturned on >> . >> . >> . >> applicationN >> >> monitoring app - ThreadingTCPServer target that Allows user to connect to ANY >> running application and to view the real-time log messages. After monitoring, >> it should be able to disconnect and connect to another application... The >> clients (application1..N) never stop sending and don't ever send anything short >> to disconnect themselves from the monitoring application. The disconnect/ >> reconnect is done at the monitoring app end based on input from the user. I >> think each one would beloggingto a different port, but I never really quite >> got that far. Perhaps there is some other way that I'm missing. It seems like >> this is something that might be able to be "generalized" into a robust >> monitoring application for an arbitrary number of asynchronously running >> applications. >> >> Each application's real-time log might be reached by clicking on a tab, menu, etc. > > Here's how I see it: the socket server listens, and receives logging > events from numerous applications in real time. If the server is > configured to monitor app1, then it quietly discards (or doesn't show > in the UI) all events from other apps - it only collects/shows events > from app1. When you click on a tab/menu/whatever to switch to > monitoring app2, then this information is used to tell the server to > discard (or not show) events from all apps except app2. You would of > course need to ensure the communication between UI thread and server > thread were done in a thread-safe manner. > >> As to the difficulty, I might just have a mental block but two modules that I've >> had a real hard time getting my mind wrapped around is yourLoggingand Twisted. >> They both have a multitude of options/ways to be used and not very many working >> examples to work from. Might be a chance to make some money on a book. If it >> was full of examples, I'd purchase it. >> > > But there are numerous examples in the logging docs - the script you > quoted as having put together after several hours of Googling is > pretty much the same as the (working) version in the logging docs! If > you have reviewed the logging docs and find them lacking examples, > please provide more detail about the kind of examples you think are > missing. And I can't speak for Twisted, but it does a lot more than > logging - and I don't think there's enough complexity in Python > logging to warrant a paid-for book. (No doubt people will tell me if > they disagree!) > > Best regards, > > Vinay Sajip Can multiple applications send SocketHandler logging records to the same socket server on the same port simultaneously? If so, then I understand your answer completely and will go in that direction. I guess I was trying to not use up bandwidth/CPU cycles on the applications that weren't being actively monitored by just not having the socket server connected to them. I think you may be a 'little to close' to the (excellent) application you have written to understand the steep learning curve that I see. You know the saying, "Brain surgery is easy to a brain surgeon". I should point out that I'm no newbie. I've used PIL, ReportLab, BeautifulSoup, Mechanize, Win32 extensions, ElementTree and a whole host of other modules with less difficulty. Please don't take this as anything more than an observation on my part. From what I see, you have written (and generously donated) an extremely powerful library and it is greatly appreciated. It is most likely just me. As far as the book is concerned, I guess I'd purchase the only copy ;-). I do appreciate your help very much. Regards, Larry From tjreedy at udel.edu Tue Jul 29 16:47:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 16:47:31 -0400 Subject: Python: SPREE HELP (willing to pay someone) In-Reply-To: <25fb9200-9be5-456f-b711-804a830b3297@m44g2000hsc.googlegroups.com> References: <25fb9200-9be5-456f-b711-804a830b3297@m44g2000hsc.googlegroups.com> Message-ID: TGD101 wrote: > I need someone who is able to install SPREE an open source program > see: http://www.askspree.de/ > > HOWEVER, here is the catch: It is on WINDOWS, but my server has > PYTHON..is there a miracle out there? If so please let me know what I > can do? Thank you. Since the site's 'Open Source' link to http:/project/askspree.de/ is dead, meaning there seems to be nothing to download and install, and since the question makes no sense, I cannot help but wonder if this is spam meant to drive traffic to the site. From dullrich at sprynet.com Thu Jul 10 12:12:15 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 10 Jul 2008 11:12:15 -0500 Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: In article <02ff4326-7b07-4ae6-8607-f58ea61802ef at z72g2000hsb.googlegroups.com>, ssecorp wrote: > I am never redefining the or reassigning the list when using validate > but since it spits the modified list back out that somehow means that > the modified list is part of the environment and not the old one. > i thought what happend inside a function stays inside a function > meaning what comes out is independent of what comes in. > Meaning if I want the list I send as a parameter to the function I > have to do x = func(x) and not just func(x) and x is magically what > comes out of func(). A function cannot modify the value of a global variable (unless it specifies "global"). It doesn't reassign anything. But in the functions below you're not reassigning a variable, you're _modifiying_ an object. A function _can_ modify an object you pass to it: >>> def DoesntReassign(x): ... x = 0 ... >>> def Modifies(x): ... x.append(0) ... >>> x=42 >>> DoesntReassign(x) >>> x 42 >>> x=[] >>> Modifies(x) >>> x [0] Hmm, look at this: >>> x=[] >>> id(x) 404296 >>> Modifies(x) >>> x [0] >>> id(x) 404296 'x' refers to exactly the same object before and after the call to Modifies. The function has _modified_ that object, but it hasn't redefined or reassigned anything. > Doesnt Python have closure or that isnt what this is about? > > > def validate(placed): > student = round(random.random()*401) > if student in placed: > return validate(placed) > else: > placed.append(student) > return student, placed > > def val(placed): > student = round(random.random()*401) > if student in placed: > return validate(placed) > else: > placed.append(student) > return student > > > > >>> g = lambda x:validate(x) > >>> l=[] > >>> for x in range(1,10): > g(l) > > > (141.0, [141.0]) > (19.0, [141.0, 19.0]) > (86.0, [141.0, 19.0, 86.0]) > (120.0, [141.0, 19.0, 86.0, 120.0]) > (76.0, [141.0, 19.0, 86.0, 120.0, 76.0]) > (262.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0]) > (234.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0]) > (74.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0]) > (325.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0, 325.0]) > >>> g = lambda x:val(x) > >>> l=[] > >>> for x in range(1,10): > g(l) > > > 183.0 > 33.0 > 315.0 > 244.0 > 308.0 > 168.0 > 146.0 > 378.0 > 297.0 > >>> -- David C. Ullrich From bj_666 at gmx.net Fri Jul 18 17:18:05 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Jul 2008 21:18:05 GMT Subject: __del__ methods References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> <6ec859F67cpfU5@mid.uni-berlin.de> <17b5febd-602d-4d7e-9449-6cabf4d95e41@27g2000hsf.googlegroups.com> Message-ID: <6ecfkdF67cpfU7@mid.uni-berlin.de> On Fri, 18 Jul 2008 12:26:35 -0700, Jason Baker wrote: > I don't necessarily need deterministic cleanup. And I plan on doing > something like a close() method as well. But I'd just like to make > sure nothing slips between the cracks. :) `__del__()` isn't guaranteed to be called *at all*, so can't make sure nothing slips between the cracks with it. Ciao, Marc 'BlackJack' Rintsch From bearophileHUGS at lycos.com Sat Jul 12 18:02:39 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 12 Jul 2008 15:02:39 -0700 (PDT) Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> Message-ID: Giampaolo Rodola': > Even if I avoid to re-heapify() it seems that the first element > returned by heappop() is always the smaller one. Yes, the heappop() function keeps the heap invariant, so it will keep giving you the smallest item. > I'd like to understand if there are cases where > deleting or moving an element of the heap, causes heappop() to return > an element which is not the smallest one. To be an heap it must keep its heap invariant true. The heap functions keep that invariant. Generally any time you move/delete an item yourself, you break the invariant, so you don't have an heap anymore and you need to re-heapify to restore the heap invariant :-) Bye, bearophile From hancock.robert at gmail.com Tue Jul 8 11:01:21 2008 From: hancock.robert at gmail.com (Robert Hancock) Date: Tue, 8 Jul 2008 08:01:21 -0700 (PDT) Subject: Relative Package Import Message-ID: mypackage/ __init__.py push/ __init__.py dest.py feed/ __init__py subject.py In subject.py I have from ..push import dest But i receive the error: Caught exception importing module subject: File "/usr/local/python/lib/python2.5/site-packages/pychecker/ checker.py", line 621, in setupMainCode() module = imp.load_module(self.moduleName, file, filename, smt) File "subject.py", line 1, in () from ..feed import dest ValueError: Attempted relative import in non-package What am I missing? From moijes12 at gmail.com Fri Jul 11 06:51:30 2008 From: moijes12 at gmail.com (moijes12) Date: Fri, 11 Jul 2008 03:51:30 -0700 (PDT) Subject: importing .dll in a python file References: <4dfaeb7b-8e7e-4f0b-80a8-ed24ed1c46d3@x35g2000hsb.googlegroups.com> Message-ID: <93f12156-e36e-41d4-9c37-524f5488e120@f36g2000hsa.googlegroups.com> On Jul 11, 2:09?pm, Tim Golden wrote: > moijes12 wrote: > > I need to use a .dll from a python script.I have installed pywin.But > > in the program ,which is like: > > > import dllName > > > I get : > > > Import Error : DLL not found > > > Please suggest a solution! > > Well, the short answer is: use the ctypes module. > > The longer answer is: read around the subject a > bit before you expect Python to import an arbitrary > DLL and then give up when it doesn't :) > > TJG Thanks a lot Tim. moijes12 From steve at REMOVE-THIS-cybersource.com.au Sat Jul 12 10:06:09 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jul 2008 09:06:09 -0500 Subject: Using the Random Module. References: Message-ID: On Fri, 11 Jul 2008 12:27:32 -0700, castironpi wrote: > You want a random integer. Is there a range you want it in? > > Past a certain point, you'll exceed the granularity of the random number > generator, and some values in the range will never be generated. You might want to produce an unbounded random integer, where *every* integer has a chance to be returned: def unbounded_randint(): i = 0 while True: if random.random() < 0.5: return i i += 1 This returns 0 with probability 1/2, 1 with probability 1/4, 2 with probability 1/8, etc. The probability distribution is centered close to zero (the mode and median are both zero, and I'm too lazy to calculate the mean) and it has an infinitely long tail. -- Steven From tjreedy at udel.edu Sun Jul 27 02:20:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 02:20:30 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87k5f88h2d.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f88h2d.fsf@physik.rwth-aachen.de> Message-ID: Torsten Bronger wrote: > No more than Python 3.0 breaks. This proposal would break 3.0 code without sufficient reason. From crazychimp132 at gmail.com Mon Jul 14 23:21:37 2008 From: crazychimp132 at gmail.com (crazychimp132 at gmail.com) Date: Mon, 14 Jul 2008 20:21:37 -0700 (PDT) Subject: Method behavior for user-created class instances References: <42433fcd-fcdc-4f42-a427-c28241734b7c@z66g2000hsc.googlegroups.com> Message-ID: On Jul 14, 9:04 pm, Larry Bates wrote: > crazychimp... at gmail.com wrote: > > Greetings. > > > I am looking for a way to achieve method behavior for a class I > > created. That is, it has a __call__ method, so can be called like a > > function. But I also want it to be treated as a method when it appears > > in a class body. > > > Eg. > > > class foo: > > def __call__(self, inst): pass > > > class bar: > > meth = foo() > > > such that bar().meth() will not raise an exception for too few > > arguments (because the inst argument in foo.__call__ is implicitly set > > to the bar instance). I know this has to do with writing the __get__ > > method of foo, but I am wondering if there is perhaps some class I can > > just inherit from to get the proper __get__, which behaves identically > > to that of regular Python functions. The need for this arises out of > > the implementation of a function decorator as a class. > > > Thanks. > > While it is not clear "why" you would want this, I believe this works. > If not, take a look at staticmethods or classmethods, they might work for you. > > >>> class foo(object): > ... def __call__(self, inst): > ... print "foo.__call__", inst > ... > > >>> class bar: > ... def __init__(self): > ... self.foo = foo() > ... self.meth = self.foo.__call__ > ... > >>> b = bar() > >>> b.meth(1) > foo.__call__ 1 > > -Larry This doesn't work for me. I have a class which is used to decorate functions, returning a callable object in the place of the original function. So, instances of this class must be able to be used anywhere a function would be used, and this means getting method behavior when it is used in a class body. A working implementation would be (in 3.0): from functools import partial from abc import ABCMeta, abstractmethod class method_behavior(metaclass = ABCMeta): def __get__(self, instance, owner): if instance is None: return self.__call__ return partial(self.__call__, instance) @abstractmethod def __call__(): pass Then, any decorator class can inherit from it: class foo(method_behavior): def __init__(self, func): self.func = func def __call__(self, *args, **kwds): print("calling decorated func") return self.func(*args, **kwds) Then, we can decorate a function with foo (via @foo) and it will work either inside a class body or outside, it works everywhere an undecorated function would work, eg.: @foo def bar(): print('bar') class baz: @foo def bar(self): print('bar') What I am asking is whether there is a way to directly inherit method behavior, instead of inexactly rewriting it as I did in method_behavior.__get__(). From martin at v.loewis.de Thu Jul 24 16:21:49 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 24 Jul 2008 22:21:49 +0200 Subject: Undocumented Python 2.6 change: Py_None vs NULL when C implementation raises exception In-Reply-To: References: <4887b13a$0$7677$9b622d9e@news.freenet.de> Message-ID: <4888E45D.7030406@v.loewis.de> > I have no plans to track down the exact change in Python code that > caused this. There does not seem to be much point, since according to > Fredrik this seems to be an area that is practically undefined and the > M2Crypto code was clearly buggy. I see, and I agree with Fredrik's analysis. It might actually be that there was *no* change in 2.6 causing this change in behavior, but just a difference in data returned in the actual application. E.g. if a PyInt_FromLong returns -1, the caller also needs to check for PyErr_Occurred, which would then detect an earlier exception. So it might be that if you have -1 in your data, you see the exception, but if you have -2 instead, you won't see it. Regards, Martin From bruno.desthuilliers at gmail.com Thu Jul 17 08:03:27 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 17 Jul 2008 05:03:27 -0700 (PDT) Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> Message-ID: On 16 juil, 10:35, Stefan Scholl wrote: > Dave U. Random wrote: > > >http://snipr.com/PracticalDjango > > June 2008 is a bit too early. Django isn't ready. Oh, really ? Too bad. But, wait... If Django isn't ready, what's that framework I've been using for almost three years now, then ??? From marcus at internetnowasp.net Mon Jul 28 13:57:27 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Tue, 29 Jul 2008 01:57:27 +0800 Subject: Module clarification In-Reply-To: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> Message-ID: <488E0887.6070803@internetnowasp.net> Hi Hussein, Basically a module is a FILE and is considered as a singleton model. Yes ur wow.py assumption is correct. I recommend getting Mark Lutz Learning Python book to get you started. Marcus.CM Hussein B wrote: > Hi. > I'm a Java guy and I'm playing around Python these days... > In Java, we organize our classes into packages and then jarring the > packages into JAR files. > What are modules in Python? > What is the equivalent of modules in Java? > Please correct me if I'm wrong: > I saved my Python code under the file Wow.py > Wow.py is now a module and I can use it in other Python code: > import Wow > > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > > From larry.bates at websafe.com` Sun Jul 27 22:17:22 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 27 Jul 2008 21:17:22 -0500 Subject: write unsigned integer 32 bits to socket In-Reply-To: References: Message-ID: rkmr.em at gmail.com wrote: > On Sun, Jul 27, 2008 at 7:01 PM, Larry Bates wrote: >> rkmr.em at gmail.com wrote: >>> i want to send unsigned 32 bit integer to socket, and looking for >>> something equivalent to this method... >>> http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt() >>> >>> is there such method / library available in python?! >> You will need to use struct module to build the 4 byte value and then send >> it. >> >> Something like (not tested): >> >> import struct >> us32bit = struct.pack("I", value) >> s.send(us32bit) > > thanks a lot!!! > > just to make sure if I want 32 bit or 4 bytes then should I use the > short or integer or long? > > this is short >>>> struct.pack('!h',3) > '\x00\x03' > > this is integer >>>> struct.pack('!i',3) > '\x00\x00\x00\x03' > > this is long >>>> struct.pack('!l',3) > '\x00\x00\x00\x03' Short is 16 bits, Integer is 32 bits, long is 64 bits (as I read and have found). -Larry From bearophileHUGS at lycos.com Wed Jul 30 14:35:26 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 30 Jul 2008 11:35:26 -0700 (PDT) Subject: Native Code vs. Python code for modules References: <4890aeb6$0$17192$742ec2ed@news.sonic.net> Message-ID: John Nagle: > Personally, I think the Shed Skin approach > is more promising. ShedSkin will probably have scaling problems: as the program size grows it may need too much time to infer all the types. The author has the strict policy of refusing any kind of type annotation, this make it unpractical. And, despite your interest in ShedSkin, so far very few people have given a hand actually developing SS (I think partially because ShedSkin Python sources aren't much hackable. This is very bad for an OpenSource project), so I think the author now has lost part of the will to develop this project (but probably we'll see one of two more versions). For me so far the most viable way to produce a faster Python system seems a version of CPython with Cython and something Psyco-like built- in (and a built-in compiler on Windows, like MinGW 4.2.1), maybe with some syntax support in the Python language, allowing to mix statically compiled Python code with dynamically compiled Python code in an easy way (as CLisp sometimes does). Bye, bearophile From mva.led at gmail.com Fri Jul 4 11:53:43 2008 From: mva.led at gmail.com (Manuel Vazquez Acosta) Date: Fri, 04 Jul 2008 11:53:43 -0400 Subject: A fix for OverflowError in 64bits platforms In-Reply-To: References: <486CE046.6080104@gmail.com> Message-ID: <486E4787.8090006@gmail.com> Terry Reedy wrote: > Manuel Vazquez Acosta wrote: >> Hi all, >> >> I'm debugging a Plone site in an AMD64 laptop. When I first tried to run >> Zope, I got this exception: > > In general, versions numbers for both Python and the app are helpful. > Python 2.4.5, Plone 2.5.5, Zope 2.9.8final >> OverflowError: signed integer is greater than maximum >> >> In the archives I encounter no solutions. > > Archives: Python? Zope? Plone? The three of them ;) > >> This is what I could find, so I share with you all: > > I hope you have/will report this to the appropriate place. > Well, not sure where to report to. According to your last comment, is an Archetypes' bug, isn't it? So it's best to report it there. >> >> I think the docstring should be appended with a "Note: On 64bits >> platform this raises an OverflowError blah blah..." > > Better to fix it ;-) Ok. Best regards, Manuel. From tom.machinski at gmail.com Mon Jul 21 19:22:15 2008 From: tom.machinski at gmail.com (Tom Machinski) Date: Mon, 21 Jul 2008 16:22:15 -0700 Subject: Python Written in C? In-Reply-To: References: Message-ID: On Mon, Jul 21, 2008 at 3:53 PM, DaveM wrote: > On Mon, 21 Jul 2008 03:18:01 +0200, Michiel Overtoom > wrote: > > > >Many major text/word processing programs (Emacs, vi, MS-Word) are also > >written in C. > > I thought Emacs was written in Lisp. Large parts of Emacs are indeed implemented in Emacs Lisp. There's are some core functions implemented in C. MS-Word, afaik, had very substantial parts written in Visual Basic. Tom > DaveM > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dp_pearce at hotmail.com Tue Jul 15 12:27:49 2008 From: dp_pearce at hotmail.com (dp_pearce) Date: Tue, 15 Jul 2008 09:27:49 -0700 (PDT) Subject: Zipping files References: Message-ID: <9400be29-9c00-4868-91a9-ae82ebfc6364@56g2000hsm.googlegroups.com> When I saw "Permission denied", this was my suspicion. And I think you are very right. I have just gone back and tried writing to a file outside of C:, in this case C:/output/, and it seems to work again. Would I be right in guessing there is no way around this? Dan From Lie.1296 at gmail.com Sun Jul 27 05:08:00 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 27 Jul 2008 02:08:00 -0700 (PDT) Subject: xml.dom's weirdness? References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> <1c837e71-a191-4495-8ec8-0126003ba9c6@n33g2000pri.googlegroups.com> <488C3645.8060304@behnel.de> Message-ID: On Jul 27, 3:48?pm, Stefan Behnel wrote: > Lie wrote: > > Question: Is there a way to list loaded modules, including those that > > aren't in my namespace? > > such as sys.modules? > > Modules are not unloaded automatically just because you do not use them > yourselves. I'm not surprised of that. > If the module is imported for whatever reason by whatever other > module, it stays alive until it's no longer referenced (including the > reference in sys.modules). I'm more concerned about the number of modules imported by making an error (from 30 on the startup to 187) and the side-effect of making an error, which makes modules such as xml.*/email.* that previously doesn't exist get imported out of the blue... this makes the effect that made me start the thread, a "command" that while getting NameError in the first call, gets a modules found on subsequent call, just because the Error Handler loaded it for you. I'm even more concerned by a few modules that got imported because of making the error, several of them isn't something that should be used by Error Handler (e.g. email.*, apt (seems to be related to Ubuntu's package manager of the same name), etc) I'm also concerned in that why Error handling is on python's level instead of built-in. PS: These concerns are based on the assumption that the offender is the "Error Handler", which I haven't proven completely, yet is the strongest candidate on why this odd behavior comes to be. From robert.kern at gmail.com Thu Jul 24 17:19:56 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 24 Jul 2008 16:19:56 -0500 Subject: need help with introducing more traffic In-Reply-To: References: <632875.28836.qm@web51808.mail.re2.yahoo.com> <6es0m9F8mehmU1@mid.uni-berlin.de> Message-ID: Fredrik Lundh wrote: > (when do we get the ability to edit our c.l.python messages for, say, 30 > minutes after they're posted? ;-) The IETF is waiting to borrow Guido's time machine for study before releasing the RFC for NNTTP (Network News Time Travel Protocol). Of course, if you have you get to borrow Guido's time machine, too, you can already comment on the RFC before the C's were R'ed. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ndbecker2 at gmail.com Thu Jul 10 11:10:33 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 10 Jul 2008 11:10:33 -0400 Subject: profiling question Message-ID: Just to confirm, the profiling numbers (from cProfile) do include time spent inside my own C functions that I import as modules? From circularfunc at gmail.com Tue Jul 22 02:15:32 2008 From: circularfunc at gmail.com (ssecorp) Date: Mon, 21 Jul 2008 23:15:32 -0700 (PDT) Subject: tail-rec decorator, well still blows the stack... References: Message-ID: <0c591e89-23ec-45ef-981f-a7927090f8cf@79g2000hsk.googlegroups.com> thanks i already have perfect iterative versions of fibonacci. def fib(n): a, b = 1, 0 while n: a, b, n = b, a+b, n-1 return b I know the example is not the way to write pythonic code, I was just learning about decorators and then I saw this example and tried it out. but thanks now i understand why it didn't work. From sri_annauni at yahoo.co.in Thu Jul 3 04:23:08 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Thu, 3 Jul 2008 13:53:08 +0530 (IST) Subject: How to pickle bound methods Message-ID: <248375.61171.qm@web7905.mail.in.yahoo.com> No. It does not work. def make_staticmethod(inst, methodname): ??? return getattr(inst, methodname) def pickle_function(method): ??? return make_staticmethod, (method.im_self, method.im_func.__name__) copy_reg.pickle(new.function, pickle_function, make_staticmethod) ----- Original Message ---- From: Peter Otten <__peter__ at web.de> To: python-list at python.org Sent: Thursday, 3 July, 2008 12:13:45 PM Subject: Re: How to pickle bound methods srinivasan srinivas wrote: Please don't top-post. > Could you please explain?the code breifly?? I am not getting what it does. >> import copy_reg >> import new >> >> def make_instancemethod(inst, methodname): >> ? ? return getattr(inst, methodname) >> >> def pickle_instancemethod(method): >> ? ? return make_instancemethod, (method.im_self, method.im_func.__name__) >> >> copy_reg.pickle(new.instancemethod, pickle_instancemethod, >> make_instancemethod) If you have a type that cannot be pickled because it is implemented in C you can make it "picklable" by registering it with the copy_reg.pickle() function. This function takes three arguments: 1 the type (here: new.instancemethod) 2 a function that takes an instance of the type. This returns a factory function and a tuple of the arguments this factory function needs to recreate the instance. 3 the factory function. In short the following must work, and out_method should do the same thing as in_method: factory, args = pickle_instancemethod(in_method) out_method = factory(*args) Now to your other problem, pickling static methods. The type of a static method is just new.function, the same as that of a global function. Global functions are already picklable, so the copy_reg mechanism doesn't kick in. Peter -- http://mail.python.org/mailman/listinfo/python-list Unlimited freedom, unlimited storage. Get it now, on http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/ From castironpi at gmail.com Fri Jul 18 02:26:24 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 17 Jul 2008 23:26:24 -0700 (PDT) Subject: storing references instead of copies in a dictionary References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: <7c26ca26-be96-4e8c-8eb5-e43bd78e4e70@v21g2000pro.googlegroups.com> On Jul 17, 7:36?pm, bgeddy wrote: > bgeddy wrote: > > castironpi wrote: > >> On Jul 17, 10:05 am, mk wrote: > >>>> def f2(arg): > >>>> ? ? return "f2 "+arg > >>>> def f1(arg): > >>>> ? ? return "f1 "+arg > >>>> a={"1":"f1","2":"f2"} > >>>> print [eval(x[1])(x[0]) for x in a.items()] > >>>> def f2(arg): > >>>> ? ? return "New f2 "+arg > >>>> print [eval(x[1])(x[0]) for x in a.items()] > >>> Neat trick, if probably dangerous in some circumstances. Anyway, thanks, > >>> I didn't think of that. > > >>>> Don't know if this is any use to you.. > >>> At least I learned something. :-) > > >> You want consistent access to a changing variable. ?Wrap it in an > >> object: > > >>>>> a= Blank( ) > >>>>> a.ref= 'X' > >>>>> a.ref > >> 'X' > >>>>> b= a > >>>>> b.ref > >> 'X' > >>>>> a.ref= 'Y' > >>>>> b.ref > >> 'Y' > > > My "old fashioned" programing paradigms think of this in terms of > > "pointers", a throw back to my schooling in 'C'. I find this general > > form of problem to be common across languages and in some ways hard to > > express in python. The whole idea of labels bound to objects is quite > > alien to traditional terminology. I find one of the main attractions of > > python is this new mindset that the language makes you adopt - a > > different set of tools are at hand for the old school programmer. > > > castironpi - please give an example of what you are thinking as I find > > this interesting. preferably post some brief example code. > > castironpi ?- please forgive the double post but my newsreader didn't > display your code correctly.. Doh !! Anyway - a nice way of addressing > the problem. However the OP's post revolved around having a rewritable > set of "labels" - which could be recorded at one time and when re > referenced the new definitions of those labels would be used. For > example a "collection" (list,dictionary,tuple) could be made of these > "labels" and then the underlying code accessed by the labels changed. If > the code was now ran indirectly by referencing the list then the new > code would be ran. These building blocks are how parsers are built and > the basis of language. > I can see how you form two ways of addressing the variable but can't > figure how this fits the original problem. Please elaborate for my > ignorance. > > EdH. In the OP's post, we have: def f1(): print 'f1' def f2(): print 'f2' funs= [ f1, f2 ] def f1(): print 'new f1' They wanted funs[ 0 ] to contain this new function / new definition too. Another language might permit: def funs[ 0 ](): print 'new f1' Python allows: def f1(): print 'new f1' funs[ 0 ]= f1 and @rebind( funs, 0 ) def f1(): print 'new f1' and @rebind_named( funs, 'funA' ) def f1(): print 'new f1' in the case funs was a dictionary or class or class instance. Functions remain to be first class objects; their definition syntax is merely restricted over normal assignments. To access "whatever 'f1' is pointing to right now", the only way is with eval, which you showed. Spealman's solution can accomplish redefinition, but only provided calling signature and closure, among others, don't change. If they do, you have to reassign those, too, and possibly more: >>> dir( f ) [snip] 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name' Roughly the same in 3.0. It's an option. > These building blocks are how parsers are built and > the basis of language. To address this, I observe altered references are easy for computers. Suppose: #--NOT PYTHON-- def f1(): print 'f1' 008902 f1: 0x008934 def f1(): print 'new f1' 008902 f1: 0x008938 'f1()' calls the function the address of which is stored at 008902 in each case: f1 (at 008934) in the first case, and new f1 (at 008938) in the second. Python eliminates that combination from the syntax, which strengthens object-name identity, at the cost of a slightly longer workaround (a.ref= f1) for keeping names but changing objects. In this sense, the only 'pointer' per se is the string name of an object, scoped by a namespace-- eval( 'f1', spaceA ). I delicately ask for an example in natural language and daily life in which we change what object a name refers to, or hold that Python conforms to natural language better than computer-native mutable pointers and references. From robert.rawlins at thinkbluemedia.co.uk Thu Jul 17 12:01:46 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 17 Jul 2008 17:01:46 +0100 Subject: Unusual Exception Behaviour In-Reply-To: References: <22681.110565509$1216308418@news.gmane.org> Message-ID: <004601c8e826$6a848490$3f8d8db0$@rawlins@thinkbluemedia.co.uk> Hi Mk, > Why not capture exceptions themselves to a log file? > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466332 Thanks for the reply mate, I appreciate you getting back to me so quickly. I certainly like that implementation for logging the exceptions, however, at the moment I don't even know where the exceptions are occurring, or what type they are, could I still use this method to log any and all exceptions raised in the application? I'm a little confused as to how I can modify that implementation to do so. Robert From misceverything at gmail.com Wed Jul 23 19:28:36 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Wed, 23 Jul 2008 16:28:36 -0700 (PDT) Subject: Web Server References: Message-ID: Thanks, guys..I think I am going to go the route Fredrik suggested. Thanks for all your help! From ggpolo at gmail.com Wed Jul 23 11:07:33 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 23 Jul 2008 12:07:33 -0300 Subject: Doubt In-Reply-To: References: Message-ID: On Wed, Jul 23, 2008 at 11:51 AM, ???????? wrote: > Friends > > I am a Perl programmer new to Python. I have a small doubt. > How to convert the perl notation > $a = ""; expression in Python ? a = "" > > How to represent the loop > for ($a = $b; $a<=$c;$a++){ > } in Python > for a in range(b, c + 1): pass > Jagan > Linguist > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From wtanksleyjr at gmail.com Mon Jul 28 19:42:46 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Mon, 28 Jul 2008 16:42:46 -0700 (PDT) Subject: Python parsing iTunes XML/COM Message-ID: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> I'm trying to convert the URLs contained in iTunes' XML file into a form comparable with the filenames returned by iTunes' COM interface. I'm writing a podcast sorter in Python; I'm using iTunes under Windows right now. iTunes' COM provides most of my data input and all of my mp3/aac editing capabilities; the one thing I can't access through COM is the Release Date, which is my primary sorting field. So I read everything in through COM, then read all the release dates from the iTunes XML file, then try to join the two together... But so far I have zero success. Is there _any_ way to match up tracks between iTunes COM and iTunes XML? I've spent far too much effort on this. I'm not stuck on using filenames, if that's a bad idea... But I haven't found anything else that works, and filenames seem like an obvious solution. -Wm From gh at ghaering.de Fri Jul 11 08:39:11 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 11 Jul 2008 14:39:11 +0200 Subject: How to serialize and deserialize the objects into memory? In-Reply-To: <0a7ead85-2a38-41a8-98b8-59dede61f985@c58g2000hsc.googlegroups.com> References: <0a7ead85-2a38-41a8-98b8-59dede61f985@c58g2000hsc.googlegroups.com> Message-ID: hardemr wrote: > Hello Everyone, > > I want to serialize and deserialize the objects into Memory not into > file. How can i do that? You want to serialize the objects, but only keep them in memory? That hardly makes any sense. Serialization is need if you want to store your objects in a file or if you want to communicate (via network) with other processes. -- Gerhard From bignose+hates-spam at benfinney.id.au Mon Jul 7 20:43:54 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 08 Jul 2008 10:43:54 +1000 Subject: Python Agile Software Development Tools Screencasts References: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> <87lk0dwbys.fsf@benfinney.id.au> Message-ID: <87hcb1w6gl.fsf@benfinney.id.au> Robert Kern writes: > Ben Finney wrote: > > percious writes: > > > >> I started a new series about python on showmedo. Please feel free > >> to take a look. > > > > I'd love to, but showmedo refuses to show presentations to me > > without installing non-free software. > > mplayer works just fine on the .flv's. Note that "works with mplayer" is not the same thing as "doesn't require non-free software"; many "works with mplayer" stories have the unspoken addendum of "... with these non-free codec libraries installed". But, not having the video files, I can't say whether that's the case in this instance. Okay. Where would the public link to those files be? If I need to "log in" just to download it, that's a needless barrier that's going to turn me away too. -- \ ?Don't worry about people stealing your ideas. If your ideas | `\ are any good, you'll have to ram them down people's throats.? | _o__) ?Howard Aiken | Ben Finney From mathieu.prevot at ens.fr Mon Jul 7 16:53:47 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Mon, 7 Jul 2008 22:53:47 +0200 Subject: do a sed / awk filter with python tools (at least as fast) In-Reply-To: References: Message-ID: <3e473cc60807071353t2b4c4c98pf01faeae244a7f60@mail.gmail.com> 2008/7/7 Peter Otten <__peter__ at web.de>: > Mathieu Prevot wrote: > >> I use in a bourne shell script the following filter: >> >> sed '/watch?v=/! d;s/.*v=//;s/\(.\{11\}\).*/\1/' \ >> | sort | uniq | awk 'ORS=" "{print $1}' >> >> that give me all sets of 11 characters that follows the "watch?v=" >> motif. I would like to do it in python on stdout from a >> subprocess.Popen instance, using python tools rather than sed awk etc. >> How can I do this ? Can I expect something as fast ? > > You should either do it in Python , e. g.: > > def process(lines): > candidates = (line.rstrip().partition("/watch?v=") for line in lines) > matches = (c[:11] for a, b, c in candidates if len(c) >= 11) > print " ".join(sorted(set(matches))) > > if __name__ == "__main__": > import sys > process(sys.stdin) > > or invoke your shell script via subprocess.Popen(). Invoking a python script > via subprocess doesn't make sense IMHO. :) Thanks. Mathieu From grante at visi.com Mon Jul 21 23:47:30 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 21 Jul 2008 22:47:30 -0500 Subject: Python Written in C? References: Message-ID: On 2008-07-22, Larry Bates wrote: > You talk about "writing it in assembly language for each MPU > chip". Actually it is even better than that. We now have > these modern inventions, called compilers that do that type of > work for us. They translate high level instructions, not > into assembler but into machine language. Actually, all of the compilers I'm familiar with (gcc and a handful of cross compilers for various microprocessors) translate from high-level languages (e.g. C, C++) into assembly, which is then assembled into relocatable object files, which are then linked/loaded to produce machine language. -- Grant Edwards grante Yow! "DARK SHADOWS" at is on!! Hey, I think visi.com the VAMPIRE forgot his UMBRELLA!! From dmitrey.kroshko at scipy.org Mon Jul 21 07:26:03 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Mon, 21 Jul 2008 04:26:03 -0700 (PDT) Subject: Genetic programming: pygene, pygp, AST, or (gasp) Lisp? References: <7bfb3c41-b08b-49dc-9711-6e39a4667db2@b1g2000hsg.googlegroups.com> Message-ID: <1ccf224d-096e-4afa-8bed-fce077e7f359@c65g2000hsa.googlegroups.com> also, you could look at the simple openopt example provided by GA "galileo" solver (connected to OO framework) http://projects.scipy.org/scipy/scikits/browser/trunk/openopt/scikits/openopt/examples/glp_1.py http://scipy.org/scipy/scikits/wiki/GLP Regards, D From alexnbryan at gmail.com Fri Jul 11 23:46:02 2008 From: alexnbryan at gmail.com (Alexnb) Date: Fri, 11 Jul 2008 20:46:02 -0700 (PDT) Subject: Help with using findAll() in BeautifulSoup Message-ID: <18415792.post@talk.nabble.com> Okay, I am not sure if there is a better way of doing this than findAll() but that is how I am doing it right now. I am making an app that screen scapes dictionary.com for definitions. However, I would like to have the type of the word for each definition. For example if def1 and def2 are noun defintions but def3 isn't: noun def1 def2 verb def3 Something like that. Now I can get the definitions just fine. But the problem comes when I want to get the type. I can get the types, but I don't know for what definitions they go with. So I can get noun and verb, but for all I know noun is def1, and verb is 2 and 3. I am wondering if there is a way to use findAll() but like stop once it hits a certain thing, or a way to do just that. for example, if I have noun
verb
I want to be able to do like findAll('span', {'class': 'pg'}), but tell me how many
things are after it, or before the next so I know how many defintions it has. Here is the code I am using(I used "cheese" because that is kinda my test word for everything in the app.): import urllib from BeautifulSoup import BeautifulSoup class defWord: def __init__(self, word): self.word = word def get_types(term): soup = BeautifulSoup(urllib.urlopen('http://dictionary.reference.com/search?q=%s' % term)) for tabs in soup.findAll('span', {'class': 'pg'}): yield tabs.contents[0].string self.mainList = list(get_types(self.word)) print self.mainList type = defWord("cheese") I don't know if this is really something anyone can help me fix or if I have to do it on my own. But I would love some help. -- View this message in context: http://www.nabble.com/Help-with-using-findAll%28%29-in-BeautifulSoup-tp18415792p18415792.html Sent from the Python - python-list mailing list archive at Nabble.com. From no-spam at no-spam-no-spam.invalid Sun Jul 6 10:42:04 2008 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sun, 06 Jul 2008 16:42:04 +0200 Subject: Hands-on HTML Table Parser/Matrix? In-Reply-To: References: Message-ID: Tim Cook wrote: > > On Sun, 2008-07-06 at 14:40 +0200, robert wrote: >> Often I want to extract some web table contents. Formats are >> mostly static, simple text & numbers in it, other tags to be >> stripped off. So a simple & fast approach would be ok. >> >> What of the different modules around is most easy to use, stable, >> up-to-date, iterator access or best matrix-access (without need >> for callback functions,classes.. for basic tasks)? >> > There are couple of HTML examples using Pyparsing here: > > http://pyparsing.wikispaces.com/Examples > > hm - nothing special with HTML tables. Meanwhile: I dislike "ClientTable" (file centric, too much parsing errors in real world). "TableParse" works. Very simple&fast 70-liner regexp->matrix and strip/clean/HTML-entities conversion. Fast success hands-on. Doesn't separate nested tables and such complexities consciously - but works though for simple hands-on tasks in real world. Robert From rocky at panix.com Thu Jul 10 14:52:42 2008 From: rocky at panix.com (R. Bernstein) Date: Thu, 10 Jul 2008 14:52:42 -0400 Subject: handling unexpected exceptions in pdb References: Message-ID: Simon Bierbaum writes: > Hi all, > > I'm in an interactive session in pdb, debugging my code using > pdb.runcall. Somewhere, an exception is raised and lands uncaught on > stdout. Is there any way of picking up this exception and at least > read the full message, or even accessing its stack trace to determine > where exactly within the one line I just executed it was raised? This > is where I'm stuck: > >> /usr/local/apache2/bin/Model/Database.py(287)disconnect() > (Pdb) n > FlushError: FlushErr...perly.",) >> /usr/local/apache2/bin/Model/Database.py(287)disconnect() > (Pdb) import sys > (Pdb) sys.last_traceback > *** AttributeError: 'module' object has no attribute 'last_traceback' > > Thanks, Simon I think basically you want runcall to be wrapped in a try block. So in pdb.py instead of: def runcall(*args, **kwds): return Pdb().runcall(*args, **kwds) Change with: def runcall(*args, **kwds): p=Pdb() try: return p.runcall(*args, **kwds) except: traceback.print_exc() print "Uncaught exception. Entering post mortem debugging" t = sys.exc_info()[2] p.interaction(t.tb_frame,t) print "Post mortem debugger finished." return None Code like this appears near the bottom of the pdb.py file. If that works, you may want to file a bug Python report to change pdb. Also note that one may want to do the same thing on run() and runeval() But also if this does what you want, please file a feature request to pydb: http://sourceforge.net/tracker/?func=add&group_id=61395&atid=497162 and I'll probably make it happen in the next release. This is the first time I've heard of anyone using runcall. From code at pizzashack.org Mon Jul 21 12:50:25 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 21 Jul 2008 12:50:25 -0400 Subject: Change PC to Win or Windows In-Reply-To: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> Message-ID: <20080721165025.GC8793@dragontoe.org> On Sat, Jul 19, 2008 at 02:56:07AM -0700, Lie wrote: > government, etc. IBM PC is one of the first computers that ordinary > people could possess, when IBM-clones appeared on the market, they're > referred as PCs too because they are Personal Computer, a computer > that is designed for personal use. Just to be clear, this statement is WRONG. PC-clones were so called because they were clones of the IBM-PC. The term is very specific to IBM-compatible hardware. http://en.wikipedia.org/wiki/Pc_clone IBM PC compatible computers are those generally similar to the original IBM PC, XT, and AT. Such computers used to be referred to as PC clones, or IBM clones since they almost exactly duplicated all the significant features of the PC, XT, or AT internal design, facilitated by various manufacturers' ability to legally reverse engineer the BIOS through cleanroom design. Wikipedia's article on the personal computer accurately reflects the multiple meanings of the term, and points out the common usage to mean a Windows box: http://en.wikipedia.org/wiki/Personal_computer Today a PC may be a desktop computer, a laptop computer or a tablet computer. The most common operating systems are Microsoft Windows, Mac OS X and Linux, while the most common microprocessors are x86 compatible CPUs. However, the term "PC" is often used only to refer to computers running Microsoft Windows. So please stop your whining and get used to the idea that THE REST OF THE WORLD uses PC to mean a Windows box. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From basti.wiesner at gmx.net Fri Jul 25 14:55:18 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Fri, 25 Jul 2008 20:55:18 +0200 Subject: Python program as daemon? References: <8bb6bd1a-cd85-4b7a-8fc9-844f3794bca0@c58g2000hsc.googlegroups.com> Message-ID: Johny : > Is it possible to run a Python program as daemon? You can write daemons in basically any language out there. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From stef.mientki at gmail.com Thu Jul 17 07:00:03 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 17 Jul 2008 13:00:03 +0200 Subject: Babelfish translation ... Message-ID: <487F2633.6000703@gmail.com> hello, I've build a translation tool, to translate all strings in a python source file. As a extra gadget I added translation through Babel Fish, using beautifulsoup. Although it works functionally, it can take lots of time waiting for the translation. What I basically do is, after selecting a new string to be translated: kwds = { 'trtext' : line_to_be_translated, 'lp' :'en_nl'} soup = BeautifulSoup (urlopen(url, urlencode ( kwds ) ) ) translation= soup.find ( 'div', style='padding:0.6em;' ).string self.Editor_Babel.SetLabel ( translation ) I'm using Python 2.5 and wxPython. Probably I should use a separate thread, but that's above my knowledge. I could also use a timer to check at regualr intervals when the translation is ready, but I've no idea how to implement that with the above code. thanks, Stef Mientki From matthieu.brucher at gmail.com Tue Jul 8 17:03:28 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Tue, 8 Jul 2008 23:03:28 +0200 Subject: sage vs enthought for sci computing In-Reply-To: <48729fe9$0$7550$9b4e6d93@newsspool1.arcor-online.net> References: <677e7819-e09e-43d3-8368-5864f91002be@34g2000hsh.googlegroups.com> <48729fe9$0$7550$9b4e6d93@newsspool1.arcor-online.net> Message-ID: 2008/7/8 three3q : > Hi, > >>> If my goal >>> is to replace matlab (we do signal processing and stats on >>> physiological data, with a lot of visualization), would sage or >>> enthought get me going quicker? > Pylab. Not a good idea, as pylab will be replaced by pyplot which only contains plot commands. The remaining will be left to numpy, and pylab does not have the same functions as numpy. My answer would be like Stuart's: a mix of Python, numpy, scipy and whatever scikit or additional numpy module I need, with ipython. That's if I want to do scientific computation. Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher From phillip.oldham at gmail.com Thu Jul 10 05:24:04 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Thu, 10 Jul 2008 02:24:04 -0700 (PDT) Subject: FOSS projects exhibiting clean/good OOP? References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> Message-ID: <1fdb9220-4ddd-4633-b5bd-91fbfc91453d@z66g2000hsc.googlegroups.com> On Jul 9, 9:26 pm, "bruno.desthuilli... at gmail.com" wrote: > This is somewhat subjective... Some would say that Python's object > model is fundamentally broken and crappy (not MHO, needless to say) > that Python + "solid OO principles" is antinomic !-) Really? Would you happen to be able to provide any further information on that? From deets at nospam.web.de Thu Jul 3 12:01:15 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jul 2008 18:01:15 +0200 Subject: site-packages, unzipepd there but import fails References: Message-ID: <6d4bfmFp3aoU1@mid.uni-berlin.de> defn noob wrote: > i unzipped and put the folder in site-packages. when i run setup.py > install nothing happens. Don't do that. Remove it from there. Put it somewhere else (temp), and use $ python setup.py install Look into site-packages afterwards, and see if it got placed there. Diez From michele.simionato at gmail.com Sat Jul 12 00:00:06 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 11 Jul 2008 21:00:06 -0700 (PDT) Subject: decorator to prevent adding attributes to class? References: <98c6e83e-4a54-49ce-a32e-f03f5ab97f28@k13g2000hse.googlegroups.com> <48778CA2.2000402@jouy.inra.fr> Message-ID: On Jul 11, 9:24?pm, Neal Becker wrote: > Robert Bossy wrote: > > class Foo(Freezeable): > > def __init__(self): > > self.bar = 42 > > self.freeze() # ok, we set all variables, no more from here > > > x = Foo() > > print x.bar > > x.bar = -42 > > print x.bar > > x.baz = "OMG! A typo!" > > Pretty nice, but unfortunately the subclass has to remember to call freeze > in it's init. ?Too bad that can't be automated. It can with a metaclass redefining the __call__ method to call freeze after instantation. But there would a lot of magic going on such a design. From desothier at yahoo.com Wed Jul 23 11:33:57 2008 From: desothier at yahoo.com (antar2) Date: Wed, 23 Jul 2008 08:33:57 -0700 (PDT) Subject: concatenate the elements in each list of a list of lists Message-ID: <72c425b7-d9c2-4a61-8b7f-075eae14e703@x41g2000hsb.googlegroups.com> I already asked a similar question, but encounter problems with python... How can I concatenate the elements in each list of a list of lists list_of_listsA = [['klas*', '*', '*'], ['mooi*', '*', '*', '*'], ['arm*', '*', '*(haar)']] wanted result: list_of_listsA = [['klas* * *'] ['mooi* * * *'] ['arm* * *(haar)']] Thanks a lot ! From basti.wiesner at gmx.net Sat Jul 12 10:16:28 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sat, 12 Jul 2008 16:16:28 +0200 Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> Message-ID: Gabriel Genellina : > En Fri, 11 Jul 2008 15:42:37 -0300, Keith Hughitt > escribi?: > >> I am having a little trouble figuring out how to convert a python >> datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would >> like to create a UTC date so that when I send it to MySQL (which >> treats all dates at local dates by default), it will already have >> incorporated the proper UTC offset. I've tried looking through the >> docs http://python.active-venture.com/lib/datetime-datetime.html), but >> have not had any luck. > > You have to use a "timezone aware" datetime object. If all you want is to > store an UTC date, the tzinfo demo classes that you can find in the Python > docs at may be enough. > A more complete implementation is at The python-dateutil package also provide classes to deal with timezone-aware datetime objects. See -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From Nikolaus at rath.org Sun Jul 27 03:56:43 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Sun, 27 Jul 2008 09:56:43 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> <87ljzpt3lv.fsf@nokile.rath.org> Message-ID: <871w1fu5dw.fsf@nokile.rath.org> Terry Reedy writes: >> What he wants is to write >> > > > class foo: >> def bar(arg): >> self.whatever = arg + 1 >> >> instead of >> >> class foo: >> def bar(self, arg) >> self.whatever = arg + 1 >> >> so 'self' should *automatically* only be inserted in the function >> declaration, and *manually* be typed for attributes. > > which means making 'self' a keyword just so it can be omitted. Silly > and pernicious. Well, I guess that's more a matter of personal preference. I would go for it immediately (and also try rename it to '@' at the same time). Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From bignose+hates-spam at benfinney.id.au Sat Jul 26 21:34:45 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 27 Jul 2008 11:34:45 +1000 Subject: binding names doesn't affect the bound objects References: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> <8763qtmgo7.fsf@benfinney.id.au> Message-ID: <87od4kkt3e.fsf@benfinney.id.au> "D'Arcy J.M. Cain" writes: > Hmm. Are you saying that the following doesn't work? > > $ python > >>> f = open("test", "w") > >>> import sys > >>> sys.stdout = f > >>> print "test message" > >>> sys.exit(0) > $ cat test > test message > > > In other words, you can't change the object used by the 'print' > > statement only by re-binding names (which is *all* that is done by > > the '=' operator). > > Apparently I can. I admit to not trying any of the above. I was explaining the behaviour reported by the original poster, without experimenting to see if I could reproduce the behaviour. Thanks for being more diligent. -- \ ?All persons, living and dead, are purely coincidental.? | `\ ?_Timequake_, Kurt Vonnegut | _o__) | Ben Finney From wtanksleyjr at gmail.com Wed Jul 30 10:58:36 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Wed, 30 Jul 2008 07:58:36 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> Message-ID: <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Thank you for the response. Here's some more info, including a little that you didn't ask me for but which might be useful. John Machin wrote: > william tanksley wrote: > > To ask another way: how do I convert from a file:// URL to a local > > path in a standard way, so that filepaths from two different sources > > will work the same way in a dictionary? > > The problems occur when the filenames have non-ascii characters in > > them -- I suspect that the URLs are having some encoding placed on > > them that Python's decoder doesn't know about. > # track_id = url2pathname(urlparse(track_id).path) > print repr(track_id) > parse_result = urlparse(track_id).path > print repr(parse_result) > track_id_replacement = url2pathname(parse_result) > print repr(track_id_replacement) The "important" value here is track_id_replacement; it contains the data that's throwing me. It appears that some UTF-8 characters are being read as multiple bytes by ElementTree rather than being decoded into Unicode. Could this be a bug in ElementTree's Unicode support? If so, can I work around it? Here's one example. The others are similar -- they have the same things that look like problems to me. "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" Note some problems here: 1. This isn't Unicode; it's missing the u"" (I printed using repr). 2. It's got the UTF-8 bytes there in the middle. I tried doing track_id.encode("utf-8"), but it doesn't seem to make any difference at all. Of course, my ultimate goal is to compare the track_id to the track_id I get from iTunes' COM interface, including hashing to the same value for dict lookups. > and copy/paste the results into your next posting. In addition to the above results, while trying to get more diagnostic printouts I got the following warning from Python: C:\projects\podcasts\podstrand\podcast.py:280: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal return track.databaseID == trackLocation The code that triggered this is as follows: if trackLocation in self.podcasts: track = self.podcasts[trackLocation] if trackRelease: track.release_date = trackRelease elif track.is_podcast: print "No release date:", repr(track.name) else: # For the sake of diagnostics, try to find the track. def track_has_location(track): return track.databaseID == trackLocation fillers = filter(track_has_location, self.fillers) if len(fillers): return disabled = filter(track_has_location, self.deferred) if len(disabled): return print "Location not known:", repr(trackLocation) -Wm From cheaplv at sina.com Fri Jul 18 01:35:52 2008 From: cheaplv at sina.com (cheaplv at sina.com) Date: Thu, 17 Jul 2008 22:35:52 -0700 (PDT) Subject: paypal wholesale men jordans 13 (paypal accept)(www goodsaler com Message-ID: <9436d005-27aa-4950-b184-c67a1c1fd78b@u12g2000prd.googlegroups.com> paypal wholesale men jordans (paypal accept)(www goodsaler com paypal wholesale men jordans 1 (paypal accept)(www goodsaler com paypal wholesale men jordans 2 (paypal accept)(www goodsaler com paypal wholesale men jordans 3 (paypal accept)(www goodsaler com paypal wholesale men jordans 4 (paypal accept)(www goodsaler com paypal wholesale men jordans 5 (paypal accept)(www goodsaler com paypal wholesale men jordans 6 (paypal accept)(www goodsaler com paypal wholesale men jordans 7 (paypal accept)(www goodsaler com paypal wholesale men jordans 8 (paypal accept)(www goodsaler com paypal wholesale men jordans 9 (paypal accept)(www goodsaler com paypal wholesale men jordans 10 (paypal accept)(www goodsaler com paypal wholesale men jordans 11 (paypal accept)(www goodsaler com paypal wholesale men jordans 12 (paypal accept)(www goodsaler com paypal wholesale men jordans 13 (paypal accept)(www goodsaler com paypal wholesale men jordans 14 (paypal accept)(www goodsaler com paypal wholesale men jordans 15 (paypal accept)(www goodsaler com paypal wholesale men jordans 16 (paypal accept)(www goodsaler com paypal wholesale men jordans 17 (paypal accept)(www goodsaler com paypal wholesale men jordans (paypal accept)(www goodsaler com paypal wholesale men jordans 1 (paypal accept)(www goodsaler com paypal wholesale men jordans 2 (paypal accept)(www goodsaler com paypal wholesale men jordans 3 (paypal accept)(www goodsaler com paypal wholesale men jordans 4 (paypal accept)(www goodsaler com paypal wholesale men jordans 5 (paypal accept)(www goodsaler com paypal wholesale men jordans 6 (paypal accept)(www goodsaler com paypal wholesale men jordans 7 (paypal accept)(www goodsaler com paypal wholesale men jordans 8 (paypal accept)(www goodsaler com paypal wholesale men jordans 9 (paypal accept)(www goodsaler com paypal wholesale men jordans 10 (paypal accept)(www goodsaler com paypal wholesale men jordans 11 (paypal accept)(www goodsaler com paypal wholesale men jordans 12 (paypal accept)(www goodsaler com paypal wholesale men jordans 13 (paypal accept)(www goodsaler com paypal wholesale men jordans 14 (paypal accept)(www goodsaler com paypal wholesale men jordans 15 (paypal accept)(www goodsaler com paypal wholesale men jordans 16 (paypal accept)(www goodsaler com paypal wholesale men jordans 17 (paypal accept)(www goodsaler com paypal wholesale men jordans (paypal accept)(www goodsaler com paypal wholesale men jordans 1 (paypal accept)(www goodsaler com paypal wholesale men jordans 2 (paypal accept)(www goodsaler com paypal wholesale men jordans 3 (paypal accept)(www goodsaler com paypal wholesale men jordans 4 (paypal accept)(www goodsaler com paypal wholesale men jordans 5 (paypal accept)(www goodsaler com paypal wholesale men jordans 6 (paypal accept)(www goodsaler com paypal wholesale men jordans 7 (paypal accept)(www goodsaler com paypal wholesale men jordans 8 (paypal accept)(www goodsaler com paypal wholesale men jordans 9 (paypal accept)(www goodsaler com paypal wholesale men jordans 10 (paypal accept)(www goodsaler com paypal wholesale men jordans 11 (paypal accept)(www goodsaler com paypal wholesale men jordans 12 (paypal accept)(www goodsaler com paypal wholesale men jordans 13 (paypal accept)(www goodsaler com paypal wholesale men jordans 14 (paypal accept)(www goodsaler com paypal wholesale men jordans 15 (paypal accept)(www goodsaler com paypal wholesale men jordans 16 (paypal accept)(www goodsaler com paypal wholesale men jordans 17 (paypal accept)(www goodsaler com From norseman at hughes.net Thu Jul 10 12:32:51 2008 From: norseman at hughes.net (norseman) Date: Thu, 10 Jul 2008 09:32:51 -0700 Subject: formatting list -> comma separated In-Reply-To: <48750e4f$0$15106$e4fe514c@dreader27.news.xs4all.nl> References: <48750e4f$0$15106$e4fe514c@dreader27.news.xs4all.nl> Message-ID: <487639B3.3020508@hughes.net> Robert wrote: > given d: > > d = ["soep", "reeds", "ook"] > > I want it to print like > > soep, reeds, ook > > I've come up with : > > print ("%s"+", %s"*(len(d)-1)) % tuple(d) > > but this fails for d = [] > > any (pythonic) options for this? > > Robert > > > > -- > http://mail.python.org/mailman/listinfo/python-list > ================================ the old fashion way would be: d = ["soep", "reeds", "ook"] if len(d) > 0: print ("%s"+", %s"*(len(d)-1)) % tuple(d) # if d= [] then print stmnt bypassed Steve norseman at hughes.net From sjmachin at lexicon.net Fri Jul 11 16:32:12 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 11 Jul 2008 13:32:12 -0700 (PDT) Subject: read file into list of lists References: <1388b868-aae9-4233-b3ec-a85ffc029283@56g2000hsm.googlegroups.com> Message-ID: On Jul 11, 11:35 pm, Paddy wrote: > On Jul 11, 2:15 pm, antar2 wrote: > > > > > Hello, > > > I can not find out how to read a file into a list of lists. I know how > > to split a text into a list > > > sentences = line.split(\n) > > > following text for example should be considered as a list of lists (3 > > columns and 3 rows), so that when I make the print statement list[0] > > [0], that the word pear appears > > > pear noun singular > > books nouns plural > > table noun singular > > > Can someone help me? > > > Thanks > > lofl = [line.strip().split() for line in the_opened_file] > >>> line = ' foo bar ' >>> line.strip().split() ['foo', 'bar'] >>> line.split() ['foo', 'bar'] From mattheww at chiark.greenend.org.uk Tue Jul 29 16:40:00 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 29 Jul 2008 21:40:00 +0100 (BST) Subject: Build tool for Python References: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Message-ID: Paul Boddie wrote: > I do understand that it can be awkward to work out which object files > need recompiling due to changes in source files, for example, and > that one doesn't want to see the logic involved reproduced all over > the place, but I do wonder whether the machinery around such matters > isn't sometimes more complicated in these tools as soon as one strays > outside the common cases. I think it often is. Tools like 'make' give you little declarative languages, and when things get a little bit complicated you end up wasting time working out how to fool it into doing what you want, when if only you could have direct access to its internals you could quite happily tell it explicitly. > It seems to me that some common build-related primitives implemented > as functions combined with plain Python would be a good enough > combination for a lot of tasks in this domain. I agree entirely; I've found this works well. I think there are three basic building blocks: - a way to invoke a compiler with suitable options (with some convenience support for describing project-wide default options and overriding them where appropriate); - a way to decide whether a file needs rebuilding (by comparing timestamps or stored hashes or whatever); - some kind of topological sort engine to work out what order to build things in. -M- From fredrik at pythonware.com Mon Jul 21 17:55:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 23:55:41 +0200 Subject: Importing different versions of a module In-Reply-To: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> References: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> Message-ID: mercado mercado wrote: > I have two versions of a script on my machine. One version is for new > development and the other version is a production version. This script > imports a module from a different directory, and this module again has > two versions (a development version and a production version). What I > want is for the development script to import the development module, and > the production script to import the production module, without making > any changes to the code in the script. if you already have two different versions of the script, what stops you from making changes to them? > For example, suppose the development script is in ~/dev/rss.py, and the > production script is in ~/prod/rss.py. I want the dev version to import > /usr/lib/python2.5/site-packages/lib_dev/parse.py, and the prod version > to import usr/lib/python2.5/site-packages/lib_prod/parse.py. cannot you just insert the appropriate directory in sys.path the first thing you do in the scripts? e.g. import os, sys lib = "lib_dev" # change this for prod/rss.py sys.path.insert(0, os.path.join( os.path.dirname(os.__file__), "site-packages", lib )) import parse # picks the right one From googler.1.webmaster at spamgourmet.com Tue Jul 22 02:43:07 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Mon, 21 Jul 2008 23:43:07 -0700 (PDT) Subject: Python Embedding Thread References: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> <87bf413d-eb98-47c0-8466-237c45fd1a0e@e53g2000hsa.googlegroups.com> Message-ID: <5081c3df-cb66-443b-ac71-be9661ae057d@27g2000hsf.googlegroups.com> Hi! Thank you very much for your answers. I have a menue with a script in it. So my app starts a new thread for each script. So I would like to run two scripts all the same time. Could someone give me a tip, what I have to set in my code? Thank you :) From rajanikanth at gmail.com Wed Jul 9 03:24:28 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Wed, 9 Jul 2008 00:24:28 -0700 Subject: Regular Expressions Quick Question In-Reply-To: References: Message-ID: <84bdef3c0807090024p3367981dq7e42ae0d4561ab81@mail.gmail.com> hi! Try this: >>> lis=['t','tes','test','testing'] >>> [elem for elem in lis if re.compile("^te").search(elem)] ['tes', 'test', 'testing'] Cheers, Raj On Wed, Jul 9, 2008 at 12:13 AM, Lamonte Harris wrote: > Alright, basically I have a list of words in a file and I load each word > from each line into the array. Then basically the question is how do I > check if the input word matches multiple words in the list. > > Say someone input "test", how could I check if that word matches these list > of words: > > test > testing > tested > > Out of the list of > > Hello > blah > example > test > ested > tested > testing > > I want it to loop then check if the input word I used starts any of the > words in the list so if I typed 'tes' > > Then: > > test > testing > testing > > would be appended to a new array. > > I'm unsure how to do this in python. > > Thanks in advanced. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From amdescombes at gmail.com Tue Jul 22 00:58:29 2008 From: amdescombes at gmail.com (AMD) Date: Tue, 22 Jul 2008 06:58:29 +0200 Subject: scanf in python In-Reply-To: References: <4884be5e$0$19722$426a74cc@news.free.fr> Message-ID: <488568f6$0$6120$426a74cc@news.free.fr> Robert Kern a ?crit : > AMD wrote: >> Hello, >> >> I often need to parse strings which contain a mix of characters, >> integers and floats, the C-language scanf function is very practical >> for this purpose. >> I've been looking for such a feature and I have been quite surprised >> to find that it has been discussed as far back as 2001 but never >> implemented. > > The second Google hit is a pure Python implementation of scanf. > > http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/ > Hi Robert, I had seen this pure python implementation, but it is not as fast or as elegant as would be an implementation written in C directly within python with no need for import. Cheers, Andr? From mccredie at gmail.com Tue Jul 22 11:27:07 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 22 Jul 2008 08:27:07 -0700 (PDT) Subject: Is this a valid use of 'import'? References: Message-ID: <3ed92b2e-a46f-41d9-a75c-c1ec74bb6137@f63g2000hsf.googlegroups.com> On Jul 22, 8:12?am, Frank Millman wrote: > Hi all > > I am familiar enough with the normal use of 'import'. However, I have > found a use for it which seems effective, but I have not seen it used > like this before, so I am not sure if there are any downsides. > > I know that when a module is imported the first time, it is > 'executed'. This normally entails setting up constants, classes, > functions, etc, that you want to make available to the importer. > > In this particular case, when it is executed, it does a whole lot > more. It reads in some parameters, establishes a socket connection, > starts a thread, and starts monitoring the socket using select.select. > It also exposes some functions that disguise the complexity of reading > from and writing to the socket. > > This enables me to write a 'client' program that look like this - > > --------------------------- > from Utils.client import * > > connect(userid='frank',pwd='') > cust = getRecord( > ? ? ? ? ? ? company='chagford',table='ArCustomers', > ? ? ? ? ? ? column='CustNo',value='A001') > print cust > close() > --------------------------- > > As you can see, it makes writing a client program very easy. > > Are there any problems with this approach? > > Frank Millman If it works for you that is great. That module however probably isn't very readable or easy to modify however. Also, you are hiding a lot of the complexity in a place where it isn't expected. Chances are it would be easy to do the same thing at the class level instead of the module level by putting all of that setup into the __init__ method of a class, which is the proper place to do that sort of thing. Making your code look something like this: from utils.client import Connection conn = Connection(userid='frank', pwd='') cust = conn.getRecord( company='chagford', table='ArCustomers', column='CustNo', value='A001' ) print cust conn.close() Without seeing your other code it is difficult to know what the issues might be. In general, this is what classes are for. Matt From fredrik at pythonware.com Thu Jul 24 11:42:46 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 17:42:46 +0200 Subject: need help with introducing more traffic In-Reply-To: <632875.28836.qm@web51808.mail.re2.yahoo.com> References: <632875.28836.qm@web51808.mail.re2.yahoo.com> Message-ID: leo davis skrev: > I found this code snippet(reference http://www.goldb.org) and wish to do > more with it than just send out a Http Get request.I would like to > introduce more traffic -say by downloading files,crawling through all > the links,logging in etc etc,and wish to see how the web server > reacts.I'm trying to stress the server to its limits....appreciate if > anyone could provide me code/ideas to inject into this. > the website -http://ftp.ruby-lang.org/pub/ruby/binaries/mswin32/ > selected as example has many downloads.i tried from urllib import umm. are you saying that you run ruby-lang.org and want to write a stress tester in Python just for the fun of it, or are we missing something here... From kasterma at bart-kastermanss-macbook.local Sun Jul 13 07:19:48 2008 From: kasterma at bart-kastermanss-macbook.local (Bart Kastermans) Date: Sun, 13 Jul 2008 06:19:48 -0500 Subject: Changing self: if self is a tree how to set to a different self References: <0101e32d-bba2-4821-aaf4-97944c9d8f3a@f63g2000hsf.googlegroups.com> Message-ID: Paul McGuire writes: > On Jul 12, 6:18?am, Bart Kastermans macbook.local> wrote: >> This uses the function: >> >> def NoneOr (tree, mem_function, *arguments): >> ? ? """ if tree is not None then tree.mem_function (arguments). """ >> ? ? if tree == None: >> ? ? ? ? return None >> ? ? else: >> ? ? ? ? return getattr (tree, mem_function) (*arguments) >> >> Bart > > First I want to say these comments are absolutely great. I *very* much appreciated getting them. This kind of analysis and thinking about code is exactly what I want to learn for myself; so this helped me a lot. From the many interesting thoughts I got from this there is only one that is a bit dissonant with me; it is the next paragraph. > This code reads wrongly to me on a couple of levels. First, I think > the general computing consensus is that if-then-else is more readable/ > logical if you assert the positive condition for the then-part, and > put the alternative condition in the else-part. My impression is that > the non-None-ness of tree is actually the positive assertion, as in: I had been experimenting with exactly this in some of my code. The choice seemed to be between (in the cases I had in front of me): 1) filter out the bad cases and deal with them, then have the code do the usual stuff, 2) set the conditions for being the usual case, then later deal with the bad stuff. I had been converging towards (1) as in def func (inputs): if inputs bad one way: deal with it if inputs bad another way: deal with it too take care of the generic remaining case case (2) would result in something like: def func (inputs): if inputs are not bad in any way: take care of the generic case elif in puts bad in one way: deal with it else: # bad in another way deal with it too Did I represent the case distinction as you had it in mind? I'll keep this more in mind when writing stuff and see how it works out. Better keep with "more readable", logically these are clearly equivalent. > > if tree != None: > return getattr(tree, mem_function)(*arguments) > else: > return None > > Next, the more Pythonic test for None-ness is most clearly written as: > > if tree is not None: > > as there is only one None, and the identity "is not" check is simpler/ > faster for Python to execute (and possibly - and more importantly - > also simpler for readers to follow, as this reads more like a > continuous sentence instead of a mixture of prose and mathematical > notations). > > One might even suggest you could further abbreviate this test to: > > if tree: > > and get the same behavior. I would quibble with that, however, that > this merely exploits a side-effect of Python, in which None values are > always False, and *most* non-None values are True. But Python also > interprets many non-None values as False, such as 0, or empty > containers, such as lists, tuples, dicts, and strings. In fact, your > tree class sounds like a structured container to me, and it would be > reasonable to assume that you might implement __nonzero__ (pre-Python > 2.6) or __bool__ (Python 2.6 and later) in your class to return False > for an empty tree, which would still be a valid and not-None tree. > You should be able to invoke methods on an empty tree just as one can > call "".upper(). So for this case, I would stick with the more > explicit "if tree is not None". > > Another Pythonicity is that methods will *always* return a value, even > if you do not write a return statement - and that value is None. So > if you assert the tree-not-None as the if condition, you don't even > need the else part. You could just write: > > def NoneOr (tree, mem_function, *arguments): > """ if tree is not None then tree.mem_function (arguments). > """ > if tree is not None: > return getattr(tree, mem_function)(*arguments) > > Surprisingly, this actually reads almost verbatim from your doc > string! So I would guess that this implementation is probably closest > to your original intent for this method. Still, for explicitness'- > sake, you might want to keep the else-part, just to make your intent > clear and spelled-out. (Complaining about the presence or absence of > this bit of code goes beyond "persnickety"...) > > > Note that the original code is perfectly valid Python, and will run > just as efficiently as any of my alternative suggestions, which is why > I enclosed my comments in 'persnickety' (http:// > dictionary.reference.com/browse/persnickety) tags. > > -- Paul From alokkat at gmail.com Thu Jul 3 18:18:35 2008 From: alokkat at gmail.com (Alok Kumar) Date: Thu, 3 Jul 2008 18:18:35 -0400 Subject: ImportError: No module named _md5 Message-ID: I am trying to move from python 2.4 to python 2.5.2. After compiling the python 2.5.2, I found it is throwing "ImportError: No module named _md5". I found this topic on the mailing list, but no solution to fix it. Can someone help me out. It will be highly appreciated. Regards Alok -------------- next part -------------- An HTML attachment was scrubbed... URL: From henning.vonbargen at arcor.de Tue Jul 29 03:00:43 2008 From: henning.vonbargen at arcor.de (henning.vonbargen at arcor.de) Date: Tue, 29 Jul 2008 00:00:43 -0700 (PDT) Subject: Importing different versions of a module References: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> <48811064.5010603@hughes.net> <8b51e78c0807181750x66fd0372y82367245630e921f@mail.gmail.com> <4884FC33.2090006@hughes.net> <8b51e78c0807221005k4ead9652i721a030c592273af@mail.gmail.com> Message-ID: Why not set up PYTHONPATH together with other environment variables in a shell script (bash, or CMD on Windows) and call that shell script instead of your Python script directly? This is probably the easiest and still a very powerful and generic solution for this kind of problem. We do it that way regardless of the programming language used. Henning From birdprince at gmail.com Tue Jul 29 03:19:20 2008 From: birdprince at gmail.com (birdprince at gmail.com) Date: Tue, 29 Jul 2008 00:19:20 -0700 (PDT) Subject: Python COM Message-ID: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> I have implemented a COM in C++,buy i don't know how to use this COM in python. For example: the COM's ProgID is "MyCOM1.AdvMethod".this COM have two interfaces,the default interface's name is IAdvMethod,the second interface's name is IBasicMethod. How do i use those interfaces in python.Thank you very much,please answer my question in code. From ethan at stoneleaf.us Tue Jul 8 18:54:37 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 08 Jul 2008 14:54:37 -0800 Subject: numeric emulation and __pos__ In-Reply-To: References: <92e3ea9f-5745-4072-9d09-7c14fd335828@f36g2000hsa.googlegroups.com> <4873A50C.5090003@stoneleaf.us> Message-ID: <4873F02D.5050600@stoneleaf.us> Terry Reedy wrote: > > > Ethan Furman wrote: > >> Anybody have an example of when the unary + actually does something? >> Besides the below Decimal example. I'm curious under what circumstances >> it would be useful for more than just completeness (although >> completeness for it's own sake is important, IMO). > > > All true operators and some built-in functions translate to special > method calls. > -x == x.__neg__() == type(x).__neg__(x) == x.__class__.__neg__(x) > > What should happen to '+x'? Raise SyntaxError? Ignore the '+'? Or > translate it to __pos__ in analogy with '-' and __neg__? Guido made the > third choice: partly for consistency perhaps, but also for the benefit > of user-written classes. Decimal started as user-contributed decimal.py. > > Does anything else use this hook? I don't know, but I do know that > there are periodic demands for *more* operators for user use. So I > expect it has been. > > tjr It definitely makes sense from that perspective. As I was reading the docs for numeric emulation I came across the unary + and wasn't sure what to make of it. I tried it out, and got exactly what I put in, for everything I tried. So I wondered if there were any situations where you would get something besides what you started with. Thanks to everyone for your comments and help. -- Ethan From alexnbryan at gmail.com Sat Jul 12 18:39:38 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sat, 12 Jul 2008 15:39:38 -0700 (PDT) Subject: like py2exe, but on a mac Message-ID: <18424336.post@talk.nabble.com> Hi All I am wondering what I can do to turn a python app (.py) into a mac OSX applicaiton (.app). Just like py2exe does. But I am also wondering since in your applications folder on macs it usually doesn't have an actual folder for each app. Rather an icon. so for firefox, you just see the icon. Unlike windows where you have a folder with everything, and the actual program is in it. where is all the application info stored? just in the .app? Finally whether or not there is an app like py2exe for mac, is there a way to skip the middle man and turn it straight into a .dmg with the app inside? -- View this message in context: http://www.nabble.com/like-py2exe%2C-but-on-a-mac-tp18424336p18424336.html Sent from the Python - python-list mailing list archive at Nabble.com. From larzluv at hotmail.com Fri Jul 18 14:43:57 2008 From: larzluv at hotmail.com (Larry Hale) Date: Fri, 18 Jul 2008 11:43:57 -0700 (PDT) Subject: Python Behind a Squid Corporate Proxy on Windows References: <7b541a3b-846f-496a-aee1-d5719217e011@m45g2000hsb.googlegroups.com> <821d7616-3faa-4dae-a988-18caf4f8598a@8g2000hse.googlegroups.com> <84c473ed-6993-481a-b789-35851242895b@f1g2000prb.googlegroups.com> Message-ID: Thank you so much for the reply, but alas: I get the same results. (urllib2 makes the initial request, Squid replies "Error 407: Proxy Authentication Required", which urllib2 dutifully fails on/raises said error...) I do appreciate your time, though! :) -Larry On Jul 18, 3:08?am, Chris wrote: > On Jul 17, 6:40?pm, Larry Hale wrote: > > > Err, the line above should be: > > > proxy_handler = urllib2.ProxyHandler( { "http": "http:// > > myusername:passw... at webfilter.xyz.local:3128" } ) > > > (Sorry! ?:) > > some old code I wrote to download public domain info for our company, > also through a squid proxy and this still works for me > > import urllib2, urllib > > proxy = urllib2.ProxyHandler({'http': 'http:// > username:password at proxy_url:proxy_port'}) > auth = urllib2.HTTPBasicAuthHandler() > opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) > urllib2.install_opener(opener) > > conn = urllib2.urlopen('http://python.org') > return_str = conn.read() > > fp = open('python.html','w').write(return_str) From norseman at hughes.net Thu Jul 10 20:03:21 2008 From: norseman at hughes.net (norseman) Date: Thu, 10 Jul 2008 17:03:21 -0700 Subject: Reportlab Image object opens filehandles In-Reply-To: References: <4873E0CC.9040306@hughes.net> Message-ID: <4876A349.7000600@hughes.net> Daniel de Sousa Barros wrote: > > ----- Original Message ----- From: "norseman" > To: "Daniel de Sousa Barros" > Cc: > Sent: Tuesday, July 08, 2008 6:49 PM > Subject: Re: Reportlab Image object opens filehandles > > >> >> Daniel de Sousa Barros wrote: >>> Hi Mr Robin, >>> >>> I saw your post: >>> http://mail.python.org/pipermail/python-list/2003-September/224781.html >>> >>> I'm trying to append more than 1000 images into one PDF report, but i >>> get the IOError: Too many... >>> >>> know you a solution for it? >>> >>> Sorry by my english.... i'm brazilian and i'm learning english yet... >>> >>> >>> ------------------------------------------------------------------------ >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> ==================== >> If you are using Microsoft: >> >> First reaction: Increase the system pagefile (virtual memory) size. >> >> Assuming lots of spare disk space you could change it to the 'on >> demand' or 'let system handle it' setting. I don't know about Vista >> but the rest top out about 4(or 2?)Gig per pagefile per disk. Forgot >> which. >> >> I don't know what imagery handling software you have, but if able, you >> could consider 1) resizing images to final printed paper display size >> and 2) make sure they are at or below 200dpi and jpeg in format before >> entering them into the report. >> >> If you are in Linux: >> >> see the man pages on mkswap and swapon. Use files for swapspace. Easy >> to create, easier to remove. Don't need to reconfigure hard drive. Can >> be on another mounted drive. Use AbiWord or OpenOffice to set up text >> pictures and all, print to file (will be a postscript) and use >> ghostview (gv) to check results then use ghostscript (gs) to convert >> to pdf. Final review in xpdf. ImageMagic's convert will do the image >> manipulations mentioned in last paragraph of Microsoft section and >> then some. All programs mentioned in the Linux section plus the >> operating system are free for the download. >> >> >> Steve >> norseman at hughes.net >> > ==================================================== > > I'm trying to generate de report using reportlab + PIL. > > This is the code: > > ------------------------------------------------------------------------------------------ > > for i in lista: > colab = Paragraph(i[0], style('1_b')) > imagem = Image(i[1]) #i tried lazy=2, but i get an error like this : > "_file" > imagem.drawHeight = 18*cm * imagem.drawHeight / imagem.drawWidth > imagem.drawWidth = 18*cm > story.append(imagem) > dados = [ > [colab, ''], > [imagem, ''] > ] > tabela = Table(dados, [19.3*cm, 0.01*cm], repeatRows=True) > tabela.hAlign = "LEFT" > story.append(tabela) > story.append(Spacer(0*cm, 1*cm)) > doc.build(story, onFirstPage = cabecalhoRetrato, > onLaterPages=cabecalhoRetrato) > ----------------------------------------------------------------------------------------------- > > > I only need to increase the virtual memory? How i do it? I'm using > windows xp. > > ================================================ Click Start/settings/control panel/system/advanced/settings(in \ performance area)/advanced/change set System managed size on click SET box to right of above line click positives (OK APPLY etc.) all way out, system will probably reboot what is 'cm' in your code? In my world it means centimeter. If you are trying to create full scale templates via raster methods you will probably need more than 'Mom's" email machine. Junior's whiz-bang game computer box probably won't work either. Even at 72dpi (72*72)*((18*2.54)*(18*2.54))*3 5184 *( 45.72 * 45.72) * 3 5184 * 2090.318 * 3 10,836,208 * 3 35,508,625.536 bytes per image 72dpi is normal for PDF/Postscript 5184 is dots per square inch 2090.318 is square inches per image 3 is one byte each, red,green,blue Add margins and offsets and space between and.... even without that, 35.5 million times 1000 = 35500 million or 35.5 Gigabytes !!!? In one file? Microsoft is going to have a problem with you. :) If that is what you are trying to do - reach me direct. I'll show you how. One of my photos takes 4 DVD's AFTER a 15 to 1 reduction in size. Can't find a calculator? 4*4.5*15 = 270Gigs uncompressed, more or less. Steve norseman at hughes.net From DWebre at dotd.la.gov Tue Jul 15 13:53:06 2008 From: DWebre at dotd.la.gov (DWebre at dotd.la.gov) Date: Tue, 15 Jul 2008 12:53:06 -0500 Subject: Pickle and wx.TextCtrl Message-ID: D. J. Webre, Jr. PE & PLS "Gabriel Genellina" python-list at python.org Sent by: cc python-list-bounc es Subject +djwebre=dotd.la. Re: Pickle and wx.TextCtrl gov at python.org 07/11/2008 10:51 PM Thanks for the response. En Fri, 11 Jul 2008 10:15:36 -0300, escribi?: > Trying to read a pickled file and list contents. > > The attached program works using pprint, but I want to write to my frame. > WriteText only produces half of the records. > What is happening? What do you mean by "only produces half of the records"? Write Text list records from "Assignment" to "Report" pprint list records from "Assignment" to "Report" and continues to "TaskWeek", about twice as many records Probably your problem has nothing to do with a TextCtrl - ensure you can save and load your data with a simple, console-based script, and only then write the GUI. The way you read the file is rather strange -mixing calls to readline and pickle.load- I'd write the data using pickle.dump calls *only* and then read it using pickle.load calls *only*. I used 13.1.7 Example of the Python Library Referencebut. Got an error message when I did not have the readline() statement. Additional ideas will be appreciated. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: graycol.gif Type: image/gif Size: 105 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: pic19718.gif Type: image/gif Size: 1255 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ecblank.gif Type: image/gif Size: 45 bytes Desc: not available URL: From nobby at invalid.invalid Fri Jul 11 19:21:08 2008 From: nobby at invalid.invalid (Nobody Here) Date: Fri, 11 Jul 2008 18:21:08 -0500 Subject: spam <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> Message-ID: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> rickman wrote: > spam No fucking shit, Sherlock, why double the volume by pointing out the obvious? From kay.schluehr at gmx.net Mon Jul 14 06:48:53 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 14 Jul 2008 03:48:53 -0700 (PDT) Subject: Need help in writing up a Python Syntax checker References: Message-ID: <57817302-0aca-4cb5-9559-7af6b5bc9d4d@l42g2000hsc.googlegroups.com> On 14 Jul., 08:22, Kinokunya wrote: > Hi guys, > > My group and I will be working on our final year project, the scope to > do a program/web-based application similar areas of functionalities > like the PyLint and PyChecker; a Python syntax checker. We have no > Python background, equipped only with some knowledge of Java and Dot > net. Python doesn't need a syntax checker. Syntax is checked by the parser and the parser is exposed to the user by means of the parser module. What you probably mean are *semantical* checks which are typical for compilers: e.g. whether names are used with prior assignments of values that cause runtime exceptions. These issues are in fact covered by PyLint and PyChecker. > We did some research on PyLint and found out that there are 2 common > modules that PyLint & PyChecker are using, namely logilab-astng and > logilab-common. I'm not really sure what these 2 modules are for. > > Quoted from the offical site, > > The aim of this module (logilab-astng) is to provide a common base > representation of python source code > > We're not really sure what they meant by common base representation of > source codes. Just switch to \Scripts\ in your Vista installation and type `easy_install pylint`. This shall install PyLint in the directory \lib\site-packages Additionally a pylint.bat file is placed in the \Scripts \ directory. Type `pylint --help` and you get more information about the functionality of PyLint. From linuxnow at gmail.com Wed Jul 9 18:19:41 2008 From: linuxnow at gmail.com (linuxnow at gmail.com) Date: Wed, 9 Jul 2008 15:19:41 -0700 (PDT) Subject: how to remove oldest files up to a limit efficiently References: <1eb168ac-fc63-4724-8604-45e995a06b51@s50g2000hsb.googlegroups.com> Message-ID: On Jul 9, 8:46?am, Dan Stromberg wrote: > On Tue, 08 Jul 2008 15:18:23 -0700, linux... at gmail.com wrote: > > I need to mantain a filesystem where I'll keep only the most recently > > used (MRU) files; least recently used ones (LRU) have to be removed to > > leave space for newer ones. The filesystem in question is a clustered fs > > (glusterfs) which is very slow on "find" operations. To add complexity > > there are more than 10^6 files in 2 levels: 16? dirs with equally > > distributed number of files inside. > > > My first idea was to "os.walk" the filesystem, find ?oldest files and > >removethem until I reach the threshold. But find proves to be too slow. > > > My second thought was to run find -atime several times toremovethe > > oldest ones, and repeat the process with most recent atime until > > threshold is reached. Again, this needs several walks through the fs. > > > Then I thought about tmpwatch, but it needs, as find, a date to start > > removing. > > > The ideal way is to keep a sorted list if files by atime, probably in a > > cache, something like updatedb. > > This list could be also be built based only on the diratime of the first > > level of dirs, seek them in order and so on, but it still seems > > expensive to get his first level of dir sorted. > > > Any suggestions of how to do it effectively? > os.walk once. > > Build a list of all files in memory. I was thinking of reuising updatedb but it does not contain atime. Reimplementing it seems overkill to only remove a few files regularily. Keeping this list easily would help a lot as old files would be always updated, the daily run (the one used to reupdate the db) would only add new ones which, in this case, are not interesting. > Sort them by whatever time you prefer - you can get times from os.stat. > > Then figure out how many you need to delete from one end of your list, > and delete them. > > If the filesystem is especially slow (or the directories especially > large), you might cluster the files to delete into groups by the > directories they're contained in, and cd to those directories prior to > removing them. 4096 dirs with equally distributed number of files inside. I'd probably play trick with diratime and then search inside in order and remove until threshold is reached, sorting seems too expensive, at the end this will run often and it should only need to remove a few tenths/ hundreths of files. From leo_365 at yahoo.com Wed Jul 23 06:23:59 2008 From: leo_365 at yahoo.com (leo davis) Date: Wed, 23 Jul 2008 03:23:59 -0700 (PDT) Subject: logging into a website using python Message-ID: <338837.60152.qm@web51802.mail.re2.yahoo.com> Hi, ? I''m trying achieve the following by running python programs -login to a website -automate filling up web forms ? So far I 've tried out the following codes: import cookielib, urllib, urllib2 login = 'cod45' password = 'mell' # Enable cookie support for urllib2 cookiejar = cookielib.CookieJar() urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) # Send login/password to the site and get the session cookie values = {'login':login, 'password':password } data = urllib.urlencode(values) request = urllib2.Request("https://student-webmail.surrey.ac.uk/webmail/", data) url = urlOpener.open(request)? # Our cookiejar automatically receives the cookies page = url.read(500000) # Make sure we are logged in by checking the presence of the cookie "id". # (which is the cookie containing the session identifier.) if not 'id' in [cookie.name for cookie in cookiejar]: ??? raise ValueError, "Login failed with login=%s, password=%s" % (login,password) print "We are logged in !" ? ? ***I get this error msg:Login failed with login?cod45' &? password ? ? Code 2: ? import urllib2 theurl = 'www.tek-tips.com' protocol = 'http://' username = 'ub007' password = 'with' passman = urllib2.HTTPPasswordMgrWithDefaultRealm() # this creates a password manager passman.add_password(None, theurl, username, password) # because we have put None at the start it will always # use this username/password combination for? urls # for which `theurl` is a super-url authhandler = urllib2.HTTPBasicAuthHandler(passman) # create the AuthHandler opener = urllib2.build_opener(authhandler) urllib2.install_opener(opener) # All calls to urllib2.urlopen will now use our handler # Make sure not to include the protocol in with the URL, or # HTTPPasswordMgrWithDefaultRealm will be very confused. # You must (of course) use it when fetching the page though. pagehandle = urllib2.urlopen(protocol + theurl) # authentication is now handled automatically for us the_page=pagehandle.read() print the_page ? **** This code prints out the html for? the home page ''www.tek-tips.com'.I was expecting it would log me in and take me to the members page.....What am i missing here? Why is it that the script doesnt attempt a login?Thanks in advance ? Cheers David -------------- next part -------------- An HTML attachment was scrubbed... URL: From max at alcyone.com Sun Jul 20 19:19:41 2008 From: max at alcyone.com (Erik Max Francis) Date: Sun, 20 Jul 2008 16:19:41 -0700 Subject: Python Written in C? In-Reply-To: References: Message-ID: giveitawhril2008 at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. Psst. What language do you think the primary implementations of C# is written in? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The actor is not quite a human being -- but then, who is? -- George Sanders From subhabrata.iisc at hotmail.com Tue Jul 22 02:25:15 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Mon, 21 Jul 2008 23:25:15 -0700 (PDT) Subject: Web Page Construction in Python Message-ID: Dear Group, I am getting some questions on doing Web Pages in Python. I have some interactive codes in python for which I like to make web pages. I am trying to use kid. Kid I learnt, and is easy, too. My questions are: i) Am I going correct? ii) Is there any language other than kid? iii) The worked out examples of kid are not opening properly, is there any other URL where I can see them. iv) Can cgi scripting be done with kid? If any one can spend time on my questions. Best Regards, Subhabrata. From comp.ogz at gmail.com Tue Jul 8 02:51:48 2008 From: comp.ogz at gmail.com (Oguz Yarimtepe) Date: Tue, 8 Jul 2008 09:51:48 +0300 Subject: system tray for Tk Message-ID: <20831c740807072351p9effd7dg598b5f16bffe4a9e@mail.gmail.com> Hi, Is there any binding that i can use for my python-tk application that will show an icon at the system tray when the application runs which will be able to be change during the process? -- O?uz Yar?mtepe From dingbat at codesmiths.com Wed Jul 30 10:46:32 2008 From: dingbat at codesmiths.com (Andy Dingley) Date: Wed, 30 Jul 2008 07:46:32 -0700 (PDT) Subject: SVN access with pysvn under Cygwin (Installation problems) Message-ID: <69da0a81-bf73-46cb-a762-b017a53e6ddf@e39g2000hsf.googlegroups.com> I'm building Python tools to wrap up access to our Subversion / SVN source control system. It's to run on my desktop (Cygwin under Windows XP) and then later under Redhat. Trying to install the pysvn module I'm running into problems getting it to work under Cygwin. Works fine from a Windows command prompt, with both the svn_cmd.py example and my own Python code. Under Cygwin though I just get import failures. pysvn/__init__.py seems to be invoked happily enough, but then fails when it tries to import _pysvn_2_5.pyd $ python svn_cmd.py Traceback (most recent call last): File "svn_cmd.py", line 10, in import pysvn File "/usr/lib/python2.5/pysvn/__init__.py", line 104, in import _pysvn_2_5 ImportError: No module named _pysvn_2_5 Is there some trick to getting .pyd to work under Cygwin? I've tried the obvious twiddling with environment variables (and regedit), but I'm just guessing blindly. Thanks for any assistance. From mccredie at gmail.com Tue Jul 22 12:35:58 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 22 Jul 2008 09:35:58 -0700 (PDT) Subject: Question about inheritence References: Message-ID: <26204bc2-a1f9-439c-aa0b-2d957ed81c5d@p25g2000hsf.googlegroups.com> On Jul 22, 9:26?am, Catherine Heathcote wrote: > If I create a new class inherited from another with a constructor, what > happens with the new class's constructer? > Thanks for your time. Nothing, unless you call it in your constructor. class Base(object): def __init__(self): print "Base constructor called" # without calling the base class constructor class C(Base): def __init__(self): print "C constructor called" # call the base class constructor using super class D(Base): def __init__(self): super(D, self).__init__() print "D constructor called" c = C() d = D() Matt From stefan_ml at behnel.de Sat Jul 19 15:09:25 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 19 Jul 2008 21:09:25 +0200 Subject: Question In-Reply-To: References: Message-ID: <48823be5$0$6563$9b4e6d93@newsspool3.arcor-online.net> perl_wizard at manx.net wrote: > Why is Perl so much better than python? Smart questions deserve smart answers: Yes. Stefan From wuwei23 at gmail.com Mon Jul 28 00:44:23 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 27 Jul 2008 21:44:23 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> <6a5506b1-632e-4bf6-b0ce-4d51d1751aa9@i24g2000prf.googlegroups.com> <8b4b11c3-e306-4fe7-82d1-0a948c725f2f@r15g2000prd.googlegroups.com> <239a084f-b73d-4c20-aaaf-bbd05d452638@a2g2000prm.googlegroups.com> Message-ID: <8f675d65-e302-4428-a4bc-f494b230cb59@w1g2000prk.googlegroups.com> > > > > On Jul 27, 4:26 pm, "Russ P." wrote: > > > > > Terry Reedy wrote: > > > > > > The use of '.' has been suggested before and rejected. > > > > > Where and why? > Dude, I agree with Guido completely on this one. You > seem to be clueless about the issue here. You're the > one with the reading comprehension problem. Please > quit wasting my time with your irrelevant crap. I pointed you at a thread -where it had been suggested and rejected-. And I'm the clueless one? I don't think I'm the one wasting anyone's time here, but fine. I've got far better things to do with my time than waste it talking to you. From deets at nospam.web.de Tue Jul 8 13:25:55 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 Jul 2008 19:25:55 +0200 Subject: extended setattr() References: <6dgfprF2ekq3U1@mid.uni-berlin.de> Message-ID: <6dhmahF2lhk6U1@mid.uni-berlin.de> Andre Adrian wrote: > Diez B. Roggisch nospam.web.de> writes: > >> > def ext_setattr(obj, attr, val): >> > for subattr in attr.split("."): >> > obj = getattr(obj, subattr) >> > obj = val >> > >> >>>> import test >> >>>> a = A() >> > Traceback (most recent call last): >> > File "", line 1, in >> > NameError: name 'A' is not defined >> >>>> a = test.A() >> >>>> a.B.C.txt >> > 'foo' >> >>>> ext_setattr(a, 'B.C.txt', 'bar') >> >>>> a.B.C.txt >> > 'foo' >> > >> > What am i doing wrong? >> >> obj = val won't work. > > Why is this so? Shouldn't it be the same? No, of course not! obj = val binds the object reffered to by val to the LOCAL name obj. That's python 101, make sure you get variables/names and scopes proper. >> You need to use a setattr(obj, name, val) >> on the last attribute-name. > > Ok, so this works: > > def ext_setattr(obj, attr, val): > attributes = attr.split('.') > for subattr in attributes[:-1]: > obj = getattr(obj, subattr) > setattr(obj, attributes[-1], val) Yep. Diez From sjmachin at lexicon.net Sun Jul 20 17:18:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 Jul 2008 14:18:34 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> <6ebshqF67cpfU4@mid.uni-berlin.de> <5d6b8066-c941-4f0c-abea-20baed33b4ab@l64g2000hse.googlegroups.com> <569da8b8-df8a-4115-a952-5d8c2d9744e0@i20g2000prf.googlegroups.com> <46c2153d-fef6-45b5-91af-9ecb359e6a2b@2g2000hsn.googlegroups.com> Message-ID: <141135ca-20fb-426e-a11f-bcd02aa01541@f40g2000pri.googlegroups.com> On Jul 21, 4:33 am, nicolas.pource... at gmail.com wrote: > > (1) You are searching through lists to find float objects by identity, > > not by value > > ???? You wrote """ I used short lists (a list of 20 floats) and the element checked was not in the list. (That was the case I usually deals with in my code.) """ From tavares at fe.up.pt Thu Jul 10 08:54:29 2008 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Thu, 10 Jul 2008 05:54:29 -0700 (PDT) Subject: Symposium "Image Processing and Data Visualization" within the SEECCM 2009, Greece - Announce & Call for Papers Message-ID: (Our apologies for cross-posting. We appreciate if you kindly distribute this information by your co- workers and colleagues.) *************************************************************************** Symposium ?Image Processing and Data Visualization? 2nd South-East European Conference on Computational Mechanics (SEECCM 2009) Island of Rhodes, Greece, 22-24 June 2009 http://www.seeccm2009.org (A special interest conference of the European Community on Computational Methods in Applied Sciences (ECCOMAS) and of the International Association for Computational Mechanics (IACM)) *************************************************************************** Dear Colleague, Within the 2nd South-East European Conference on Computational Mechanics (SEECCM 2009), to be held in Island of Rhodes, Greece, in 22-24 June 2009, we are organizing the Symposium ?Image Processing and Data Visualization?. The main goal of the Symposium ?Image Processing and Data Visualization? is to provide a platform for communications among specialists from complementary fields such as mechanics, computational vision, mathematics, physics, informatics, computer graphics, bio- medical-practice, psychology, clinicians and industry. Participants in this symposium should present and discuss their proposed methods in the corresponding fields that are related to the symposium topics and explore the translational potentials of this emerging technological field. Hence, this symposium should be an excellent opportunity to refine ideas for future work and to establish constructive cooperation. Due to your research activities in the related fields, we are pleased to invite you to submit your work and participate in the Symposium ?Image Processing and Data Visualization?. Topics of interest include (but are not restricted to): - Image Analysis; - Image Restoration, Compression, Segmentation and Description; - Object Tracking, Matching, Registration, Recognition and Reconstruction; - Visual Inspection; - 3D Vision; - Medical Imaging; - Data Processing, Modelling and Analysis; - Scientific Visualization; - Enhanced Visualization; - Human Computer Interaction; - Enhanced and Virtual Reality; - Simulation and Animation; - Software Development for Image Processing and Data Visualization; - Grid Computing in Image Processing and Data Visualization; - Applications of Image Processing and Data Visualization. Important dates and Instructions: - Deadline for submission one page abstract: 30 November 2008; - Authors notification: 31 December 2008; - Final contribution submission: 28 February 2009. - To submit your contribution, you should access the conference website at www.seeccm2009.org and select the Symposium ?Image Processing and Data Visualization? or send your file by email to the organizers (tavares at fe.up.pt, ceconst at stanford.edu). With kind regards, Yours sincerely, The Organizers, Jo?o Manuel R. S. Tavares (tavares at fe.up.pt) Faculty of Engineering of University of Porto, Porto, Portugal Christos E. Constantinou (ceconst at stanford.edu) Stanford University, USA From code at pizzashack.org Mon Jul 21 18:50:27 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 21 Jul 2008 18:50:27 -0400 Subject: Change PC to Win or Windows In-Reply-To: <0f3272c1-b1a7-4aef-9e4a-0f03af823a2d@z11g2000prl.googlegroups.com> References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> <82873ccd-9667-4dfa-9ec4-a9ac7c672aa7@w1g2000prk.googlegroups.com> <0f3272c1-b1a7-4aef-9e4a-0f03af823a2d@z11g2000prl.googlegroups.com> Message-ID: <20080721225027.GF8793@dragontoe.org> On Mon, Jul 21, 2008 at 02:47:31PM -0700, Lie wrote: > Common usage isn't always correct. Actually it is, inherently... When usage becomes common, the language becomes redefined, and its correctness is therefore true by identity (to borrow a mathematical term). The scholars complain for a while, but eventually capitulate, and re-write the dictionary. Language bends to its use by the people, not the other way around. Your assumption is the opposite, and therefore all of your argument is false. > For example, a physicist would not use weight when he meant mass. > much, but in technical environment doing so would embarrass him. In > this analogy, I consider download page for a software source code to > be a technical area. Your analogy is still broken. The term "PC" has been used BY TECHNCIAL PEOPLE, IN A TECHNICAL CONTEXT, to mean Microsoft on Intel, FOR DECADES. + Authors of technical books, manuals, and other forms of documentation have refered to them as PCs... for decades. + Educators in CS and EE at major universities have refer to them as PCs, since at least as early as 1988 (when I started college). + Industry news publications such as Computer World have refered to them as PCs, for decades. + There are even whole magazines dedicated to them! (PC Magazine, PC Shopper, PC World, PC Gamer, etc.) They are dedicated to Microsoft on Intel, and have existed (at least in some cases) long before Apple started talking about PCs in their ads. All of this has been going on, essentially since there has been such a thing as the IBM PC. I'm sorry, but you sir, are quite simply, plainly, and completely, wrong. With a catastrophic amount of written documentation, written by technical people in the computer industry over the last 20+ years, to prove it. > > > Apple popularizes the term by explicit marketing, > > > > And here is the last point you are missing: Apple does no such > > thing. > > They did, by using the term PC to refer to other computers. APPLE CAN NOT POPULARIZE A TERM WHICH IS ALREADY POPULAR. > This kind of advertising Apple (the computer company) used is > misleading, since it implied that their PC is not a PC. They haven't implied anything; they're stating it outright! Apple sells personal computers, but they do not sell PCs. Apple's personal computer is NOT a PC, and never was, and never will be. It's an Apple. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From swiftone at swiftone.org Mon Jul 28 09:48:46 2008 From: swiftone at swiftone.org (Brett Ritter) Date: Mon, 28 Jul 2008 06:48:46 -0700 (PDT) Subject: Module clarification References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> Message-ID: On Jul 28, 4:54?am, Hussein B wrote: > Hi. > I'm a Java guy and I'm playing around Python these days... > In Java, we organize our classes into packages and then jarring the > packages into JAR files. > What are modules in Python? > What is the equivalent of modules in Java? I'm new myself, coming from Perl and Java. Take my comments with the appropriate salt. Here's my understanding: 1) JARs are a bit of a Java oddity. The other languages I've worked with don't really combine their packaging method for transport with their packaging method of access. Put another way, you may get a zipfile or tarball of library files, but they aren't USED in that format, they are just transported in that format. You unzip them and use the compiled libraries directly. Java appears to be unusual there. I could be wrong (it's a big world), but such is my experience in the C and Perl worlds. 2) Java also dictates a single class per file (basically). Other languages do not have that restriction which leads to different collections. A file in Python (a module) may have several classes, or just one, or none. A package in Python is a directory containing modules (and possibly other packages) as well as a __init__.py file. This means that you cannot have the Java case of two packages offering the same fully qualified resource, because the namespace is tied to the filesystem (note you can alter this when importing the packages). 3) Java uses "import" to create a shortcut to the namespace, a convenience for the programmer that has little to no bearing on the execution of the code. Namespace is determined by the classloader. Python uses "import" to declare how a namespace is used by the code itself, which can be very significant, (For example, Java can access any fully qualified package without an import statement. Python cannot access any package until it has been made available by import.) Hope that helps and is remotely accurate. I'm sure someone will correct me if I'm wrong. From norseman at hughes.net Wed Jul 23 16:08:09 2008 From: norseman at hughes.net (norseman) Date: Wed, 23 Jul 2008 13:08:09 -0700 Subject: Importing different versions of a module Message-ID: <48878FA9.7020403@hughes.net> Mercado; Problem solved. The attached .zip file has the working example. It is modeled after my own uses in other languages. It's not quite as elegant as it should be but it does work and is both flexible and extendable. A word of caution: I run Linux. I make no promises about any of my code working on Microsoft. Fredrik's web links on __import__ was the first major door opener. The use of system environmentals took a ton of google time. Search that proved useful was "os enviro python'. Page two had a link to a google book. The Python Official Documentation does not make it clear as to how to use os.environ other than to note it's existence. The tutorial pretty much avoids it. Python docs, in general, seem to be for (and maybe by) persons writing less than one page of code per project. It does call itself a scripting language, but it is short in sight. Don't get me wrong, it is useful. Just that it doesn't seem to have originally been given a foundation for the scale of projects I see the questions coming in on. A more thorough search and use of regular dictionary terms would have been better. In python, 'global x' means for this file, not for the project as is normal. Anyway - Zip file has three files. .txt is test data. .py is sub or called module z (dot nothing) is program base put a copy of .txt and .py in each of two locations. something like: /tmp/scott to contain .txt and .py /tmp/scott/1 same in one or the other, but not both, make a change or two to the file(s) there. perhaps putting 6 'Z'z in a csv field of same size following the 12 in the last record. put z (no last name) in maybe your home dir. anywhere but in those two. fix the directories in both z files as needed, if needed. enter:> python z and check both the source(s) and the screen. in z change os.environ['ISTEST']='True' to ...'False' and rerun. There should be 'True' (or 'False') in the bottom of z's output and at the top of z.py's output. Any formatting changes and/or data changes should occur as expected. Do not think you have to use these 'as-is'. These are just concept proof. Actual real globals (project wide) are still the best but, well... perhaps in time. Gotta go to work; Steve norseman at hughes.net -------------- next part -------------- A non-text attachment was scrubbed... Name: test.zip Type: application/octet-stream Size: 2532 bytes Desc: not available URL: From bj_666 at gmx.net Tue Jul 22 17:49:42 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Jul 2008 21:49:42 GMT Subject: Iterating Through List or Tuple References: Message-ID: <6en2vlF7jml4U2@mid.uni-berlin.de> On Tue, 22 Jul 2008 14:43:10 -0700, Samir wrote: > Is there a way to loop or iterate through a list/tuple in such a way > that when you reach the end, you start over at the beginning? For > example, suppose I define a list "daysOfWeek" such that: > >>>> daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] > > If today is Sunday, I can set the variable "day" to today by: > >>>> i = iter(daysOfWeek) >>>> day = i.next() >>>> print day > sunday > > If I want to find out the day of the week 2 days from now, then this > code works ok: > >>>> for x in xrange(2): day = i.next() > >>>> print day > tuesday > > However, when extending my range beyond the number of items in the > list, I receive an error. For example, if I want to find out the day > of the week 11 days from today, I get this: > >>>> for x in xrange(11): day = i.next() > > > Traceback (most recent call last): > File "", line 1, in > for x in xrange(11): day = i.next() > StopIteration > > Is there a way to easily loop through a list or tuple (and starting > over at the beginning when reaching the end) without having to resort > to an "if" or "while" statement? For sequences: days_of_week[(today + offset) % len(days_of_week)] For iterables in general: `itertools.cycle()` Ciao, Marc 'BlackJack' Rintsch From sunp1028 at gmail.com Wed Jul 16 12:52:53 2008 From: sunp1028 at gmail.com (patrol) Date: Wed, 16 Jul 2008 09:52:53 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> <487E1AD4.9020509@timgolden.me.uk> Message-ID: <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> On 7?17?, ??12?16?, Tim Golden wrote: > Assuming that the error comes back in the sys.stdout encoding, the following version *should* work ok. I still haven't got a non-English set up to test it on, but it certainly does return a Unicode error message. > > http://timgolden.me.uk/wmi-project/wmi.py > > The usual test case, if you wouldn't mind: > > > import wmi > > wmi.WMI ("non-existent computer") > > > > should give a (language-specific) error message, not an UnicodeDecodeError > > TJG -------------------------------------------------------------------------------------- >>> import wmi >>> wmi.WMI('non-existent computer') Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\wmi.py", line 1199, in connect handle_com_error (error_info) File "C:\Python25\lib\wmi.py", line 184, in handle_com_error exception_string = [u"%s - %s" % (hex (hresult_code), hresult_name)] UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 4: ordinal not in range(128) -------------------------------------------------------------------------------------- yup,error_info contains the Chinese encoded string. All of the Simple Chinese Windows use the CP936.Every Chinese word utilizes two bytes.Maybe you can fix this bug by modifying handle_com_error. Patrol From castironpi at gmail.com Thu Jul 24 13:37:52 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 24 Jul 2008 10:37:52 -0700 (PDT) Subject: Python Written in C? References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> <6eosgtF7u58sU1@mid.uni-berlin.de> <537c58c3-d74c-41dd-8571-26cfbb415178@34g2000hsh.googlegroups.com> <6ep711F7u58sU2@mid.uni-berlin.de> Message-ID: <02635ba4-dbbd-4674-a1f7-b86f0f13dd4b@s21g2000prm.googlegroups.com> On Jul 23, 12:10?pm, Marc 'BlackJack' Rintsch wrote: > On Wed, 23 Jul 2008 09:42:29 -0700, castironpi wrote: > > On Jul 23, 9:11?am, Marc 'BlackJack' Rintsch wrote: > >> On Wed, 23 Jul 2008 14:10:22 +0200, mk wrote: > >> > Marc 'BlackJack' Rintsch wrote: > >> >> I can't even remember when I deleted something from a list in the past. > > >> > Still, doesn't that strike you as.. workaround? > > >> No, I find it actually safer; I don't have to care where modifications of > >> the list might be seen elsewhere in the program. > > >> Ciao, > >> ? ? ? ? Marc 'BlackJack' Rintsch > > > a[:]= newlist > > > and > > > a= newlist > > > have two completely different effects, and one is just as safe as > > 'del'. ?Besides, del isn't safe to be seen elsewhere in the program in > > other threads, if they aren't locking the GIL. > > As usual you are talking nonsense? > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch As usual you are taking flamebait! From levicc00123 at gmail.com Fri Jul 18 16:26:31 2008 From: levicc00123 at gmail.com (Levi Campbell) Date: Fri, 18 Jul 2008 13:26:31 -0700 (PDT) Subject: Writing a program under GNU/Linux for MS Windows. Message-ID: Hi, I'm trying to write a program for a friend of mine who uses windows but I use GNU/Linux. I know you can use mingw and link to the python dll, but is there a way to create a win32 service under Linux? From norseman at hughes.net Wed Jul 9 13:07:31 2008 From: norseman at hughes.net (norseman) Date: Wed, 09 Jul 2008 10:07:31 -0700 Subject: Determining when a file has finished copying In-Reply-To: <4874E2D3.4050707@gmail.com> References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> Message-ID: <4874F053.8060709@hughes.net> Also available: pgm-W copies/creates-fills whatever B/dummy when done, pgm-W renames B/dummy to B/F pgm-D only scouts for B/F and does it thing when found Steve norseman at hughes.net Manuel Vazquez Acosta wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > This seems a synchronization problem. A scenario description could clear > things up so we can help: > > Program W (The workflow) copies file F to directory B > Program D (the dog) polls directory B to find is there's any new file F > > In this scenario, program D does not know whether F has been fully > copied, but W does. > > Solution: > Create a custom lock mechanism. Program W writes a file D/F.lock to > indicate file F is not complete, it's removed when F is fully copied. > I program W crashes in mid-copy both F and F.lock are kept so program D > does not bother to process F. Recovery from the crash in W would another > issue to tackle down. > > Best regards, > Manuel. > > writeson wrote: >> Hi all, >> >> I'm writing some code that monitors a directory for the appearance of >> files from a workflow. When those files appear I write a command file >> to a device that tells the device how to process the file. The >> appearance of the command file triggers the device to grab the >> original file. My problem is I don't want to write the command file to >> the device until the original file from the workflow has been copied >> completely. Since these files are large, my program has a good chance >> of scanning the directory while they are mid-copy, so I need to >> determine which files are finished being copied and which are still >> mid-copy. >> >> I haven't seen anything on Google talking about this, and I don't see >> an obvious way of doing this using the os.stat() method on the >> filepath. Anyone have any ideas about how I might accomplish this? >> >> Thanks in advance! >> Doug >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (GNU/Linux) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iEYEARECAAYFAkh04skACgkQI2zpkmcEAhi0eQCgsVqg51fWiwi47jxqtbR8Gz2U > UukAoKm15UAm3KpEyjhsIGQ+68rq8WuU > =UFHi > -----END PGP SIGNATURE----- > -- > http://mail.python.org/mailman/listinfo/python-list > From stefan_ml at behnel.de Thu Jul 3 00:59:13 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 03 Jul 2008 06:59:13 +0200 Subject: ANN: XML builder for Python In-Reply-To: References: Message-ID: <486C5CA1.3080105@behnel.de> Jonas Galvez wrote: > Not sure if it's been done before, but still... Obviously ;) http://codespeak.net/lxml/tutorial.html#the-e-factory ... and tons of other tools that generate XML, check PyPI. Stefan From cyberco at gmail.com Mon Jul 21 07:53:12 2008 From: cyberco at gmail.com (Berco Beute) Date: Mon, 21 Jul 2008 04:53:12 -0700 (PDT) Subject: simple question about dictionaries References: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> Message-ID: <2c1ab8a0-ccbd-4c75-ae6d-d8e8000aa3df@r66g2000hsg.googlegroups.com> Sounds like a school assignment. Find the answer yourself here: http://diveintopython.org/toc/index.html You'll learn a lot more in the process. 2B From malaclypse2 at gmail.com Tue Jul 15 16:32:15 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 15 Jul 2008 16:32:15 -0400 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: <16651e80807151332o1a2b7446r651f515724a27e0@mail.gmail.com> On Tue, Jul 15, 2008 at 4:13 PM, Reedick, Andrew wrote: > If name is None: > Then name is NULL, nothing, nada, no object, no memory allocated, a > NULL pointer This is just plain untrue. If 'name is None' evaluates to true, then the variable 'name' is bound to the singleton value None. It has nothing to do with allocated memory or null pointers. All it means is that someplace along the line you did the equivalent of 'name = None' in your code. -- Jerry From torainLight at gmail.com Fri Jul 4 20:21:14 2008 From: torainLight at gmail.com (satoru) Date: Fri, 4 Jul 2008 17:21:14 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: <6d4bfmFp3aoU1@mid.uni-berlin.de> <0f6f795d-8041-463e-8e98-9d830ca3fc5b@l42g2000hsc.googlegroups.com> <45111722-3f2c-476d-8e7b-fd65cc5100a6@56g2000hsm.googlegroups.com> Message-ID: why don't you just download & excute the windown installer binary? On Jul 4, 2:47?am, defn noob wrote: > On Jul 3, 8:06?pm, "bruno.desthuilli... at gmail.com" > > wrote: > > On 3 juil, 18:51, defn noob wrote: > > > > well the reason i unzipped and placed it in site-packages was because > > > nothign happened when i ran setup.py(unzipped). > > > What do you mean, "running setup.py unzipped" ??? > > > The correct way to install a package is to: > > > - unzip (untar, whatever) the archive somewhere in your own directory > > - cd to the unzipped directory > > - *from there*, run python setup.py install > > yes, which i have done. > > the command row executes but nothing happens, no errors either. From elessar at nienna.org Wed Jul 30 12:52:35 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Wed, 30 Jul 2008 10:52:35 -0600 Subject: Reasoning behind 'self' parameter in classes? In-Reply-To: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> Message-ID: <48909C53.2060206@nienna.org> Robert Dailey wrote: > Hi, > > I want to point out first of all that I'm not as familiar with Python as > I should be, and for that reason I question a lot of things because I'm > mainly a C++ programmer and I'm used to certain conveniences. Having > said that... > > I've always been curious (more so than annoyed) as to why one must > explicitly specify a "self" parameter for member functions in a class in > Python. This seems very "C" like to me, since to do object oriented > programming in C you must devote one parameter to the object itself. In > a higher order language like Python, I would not have expected (and thus > am rather surprised) that this pattern would apply. Is there any > particular reason why 'self' parameters must be specified explicitly? I > am curious to understand the philosophy and design behind this. > > In Python 3 will there be any plans to eliminate this syntactic > artifact? As I said, it's not terribly annoying to me but it seems like > more of a hack than anything else. I would feel a bit better if I didn't > have to see it. I don't mean to start any syntax wars or anything, so I > hope everyone will keep an open mind and simply explain the design, > rather than defend it. I'm interested in only facts, and not opinions. > > This is an example of a response I'm looking for: > "The self parameter is required because the parser is a bit old and > needs to know the exact object you're referencing" > > This is _not_ an example of what I'm looking for: > "Specifying self is a great mysterious thing that we should never > question. Do not question the language! The language is mighty! Don't > bring C++ to Python!" > > I appreciate the community's time. > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list There was a massive thread "attack a sacred python cow" that brought up a lot of reasons why this is the case. If you can ignore the flames, you'll find some good info there. But it might not be wise to bring it up again a week after it happened last time. -Matt From drakonik at gmail.com Mon Jul 7 17:30:41 2008 From: drakonik at gmail.com (Nick Dumas) Date: Mon, 07 Jul 2008 17:30:41 -0400 Subject: "in"consistency? In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [1,2] in [1,2,3] checks to see if the list [1,2] is an item in [1,2,3]. Because the list [1,2,3] only contains the integers 1,2,3, the code returns a False. Try "[1,2] in [[1,2],[2,3]]" David C. Ullrich wrote: > Luckily I tried it before saying no, that's > not how "in" works: > >>>> 'ab' in 'abc' > True >>>> [1,2] in [1,2,3] > False > > Is there a reason for the inconsistency? I would > have thought "in" would check for elements of a > sequence, regardless of what sort of sequence it was... > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkhyiwEACgkQLMI5fndAv9jbiwCeKMXrAclILJMPro5VuSRgdkvB cGkAn1igcjFWRQJSwEDOxpk3spzceZGa =iq8L -----END PGP SIGNATURE----- From timothy.grant at gmail.com Tue Jul 22 18:11:29 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Tue, 22 Jul 2008 15:11:29 -0700 Subject: Function editing with Vim throws IndentError In-Reply-To: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: On Tue, Jul 22, 2008 at 2:02 PM, ptn wrote: > Hi everybody, > > I have a weird problem. Say I have a .py file with some functions in > it, like this: > > # (...) > def foo(): > print("bar") > > When I open it and add a line to one of the functions, > > # (...) > def foo(): > troz = "bar" > print(troz) > > I get the following traceback from the interpreter: > > Traceback (most recent call last): > File "SOMEWHERE/example.py", line ?? > troz = "bar" > ^ > IndentationError: unindent does not match any outer indentation > level > > And so I'm forced to rewrite the function entirely just to add the new > line. > > I thought that my problem was the w option from formatoptions, so I > changed my .vimrc file to this: > > augroup filetype > autocmd BufNewFile,BufRead *.txt set filetype=human > augroup END > autocmd FileType human setlocal formatoptions+=ta2w > autocmd FileType lisp,scheme,python,c,java,vim setlocal > formatoptions-=ta2w > > But the problem didn't go away. I don't think this has anything to > do > with the tabs and spaces, because I have them set up like this: > > set tabstop=4 shiftwidth=4 expandtab > > which is the standard way to handle them. > > The scripts I load are: qbuf, TagList, indent/python.vim and a reduced > version of the standard python.vim > > Could someone provide some pointers? > > Thanks, > > Pablo Torres N. > -- > http://mail.python.org/mailman/listinfo/python-list > Are you editing someone else's code? If you are, my guess is that the file uses tabs for indentation. You may want to do ":set list" within Vim to test that theory. That should show you what all the whitespace characters are. -- Stand Fast, tjg. [Timothy Grant] -------------- next part -------------- An HTML attachment was scrubbed... URL: From gherron at islandtraining.com Thu Jul 10 16:39:29 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 10 Jul 2008 13:39:29 -0700 Subject: Can anyone suggest a date peocedure... In-Reply-To: References: Message-ID: <48767381.9080303@islandtraining.com> RLV wrote: > I'd like to find a simple... (I'm a simple person) procedure to > subtract a numerical number from a six char date string > YYYYMMDD and then convert back to a new date string. > > I'm sure there's a way to do it, but the date modules haven't been > much help. > > TIA > Ron > > -- > http://mail.python.org/mailman/listinfo/python-list > The datetime module has what you need. It has methods (with examples) on building a datetime object from a string, and it has a object named timedelta, and the ability to subtract a timedelta from a time. For instance, the time right now and the time exactly one day ago: >>> from datetime import * >>> datetime.today() datetime.datetime(2008, 7, 10, 13, 38, 48, 279539) >>> datetime.today()-timedelta(1) datetime.datetime(2008, 7, 9, 13, 38, 50, 939580) Gary Herron From tjreedy at udel.edu Wed Jul 16 02:32:13 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 Jul 2008 02:32:13 -0400 Subject: Moving to functional programming In-Reply-To: <87vdz64j6j.fsf@benfinney.id.au> References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> <7xiqv68rrp.fsf@ruckus.brouhaha.com> <87vdz64j6j.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Paul Rubin writes: > >> I don't like square-bracket listcomps because they leak the index >> variables to the outside. > > According to PEP 289 , > this is an acknowledged wart that will be fixed in Python 3.0. Has been. IDLE 3.0b1 >>> a=[i for i in range(5)] >>> i Traceback (most recent call last): File "", line 1, in i NameError: name 'i' is not defined From giltay at gmail.com Tue Jul 29 15:42:19 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Tue, 29 Jul 2008 12:42:19 -0700 (PDT) Subject: iterating "by twos" References: <70a172ac-0491-4918-9c74-6a577f35068a@d45g2000hsc.googlegroups.com> Message-ID: On Jul 29, 2:36?pm, gil... at gmail.com wrote: > On Jul 29, 1:36?pm, kj wrote: > > > Is there a special pythonic idiom for iterating over a list (or > > tuple) two elements at a time? > > ? ? ?I use this one a lot: > > for x, y in zip(a, a[1:]): > ? ? frob(x, y) > > Geoff G-T Whoops, I misread the original post. That would be: for x, y in zip(a[::2], a[1::2]): frob(x, y) ... which I don't use a lot. >>> a = range(9) >>> for x, y in zip(a, a[1:]): ... print x, y ... 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 >>> for x, y in zip(a[::2], a[1::2]): ... print x, y ... 0 1 2 3 4 5 6 7 Geoff G-T From malaclypse2 at gmail.com Mon Jul 14 12:51:01 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 14 Jul 2008 12:51:01 -0400 Subject: Unicode confusion In-Reply-To: <1216053600.3028.59.camel@localhost.localdomain> References: <1216053600.3028.59.camel@localhost.localdomain> Message-ID: <16651e80807140951j1b4ecbfayb2f477a4bd000614@mail.gmail.com> On Mon, Jul 14, 2008 at 12:40 PM, Tim Cook wrote: > if I say units=unicode("?"). I get > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: > ordinal not in range(128) > > If I try x=unicode.decode(x,'utf-8'). I get > TypeError: descriptor 'decode' requires a 'unicode' object but received > a 'str' > > What is the correct way to interpret these symbols that come to me as a > string? Part of it depends on where you're getting them from. If they are in your source code, just define them like this: >>> units = u"?" >>> print units ? >>> print repr(units) u'\xb0' If they're coming from an external source, you have to know the encoding they're being sent in. Then you can decode them into unicode, like this: >>> units = "?" >>> unicode_units = units.decode('Latin-1') >>> print repr(unicode_units) u'\xb0' >>> print unicode_units ? -- Jerry From ptmcg at austin.rr.com Fri Jul 11 22:15:39 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 11 Jul 2008 19:15:39 -0700 (PDT) Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> <2a13cea6-5144-4f37-af8a-607601f923a9@79g2000hsk.googlegroups.com> Message-ID: <29434cc4-855e-4112-a234-f78cdd55205f@m73g2000hsh.googlegroups.com> On Jul 11, 6:20?pm, Mensanator wrote: > > Try this: > > > spam = ['a', 'n', 'n', 'a'] > > eggs = spam[:] > > if spam.reverse() == eggs: > > ? ? print "Palindrome" > > You could also do > > >>> spam = ['a','n','n','a'] > >>> if spam == [i for i in reversed(spam)]: > > ? ? ? ? print "Palindrome" > Or instead of this: [ i for i in generator_expression] just use the list constructor: list(generator_expression) -- Paul From sanket.s.patel at gmail.com Fri Jul 25 17:16:16 2008 From: sanket.s.patel at gmail.com (sanket) Date: Fri, 25 Jul 2008 14:16:16 -0700 (PDT) Subject: SimpleJson is slow .... is there any C Compiled version ? Message-ID: Hello All, I have created an API which fetches some data from the database. I am using simplejson to encode it and return it back. Now the problem is that, this API is being called for millions of times in a sequence. I ran a profiler and saw that most of the time is consumed in encoding my database results in to json. So I was just wondering is there any C compiled version of simplejson is available? or any help regarding this issue would be appreciated. Thank you, Sanket From Rakesh.Thakrar at microcom-it.com Thu Jul 31 09:51:28 2008 From: Rakesh.Thakrar at microcom-it.com (Rakesh Thakrar) Date: Thu, 31 Jul 2008 14:51:28 +0100 Subject: Python Contractor needed Message-ID: <17A5EF611D8AF34DA2E14B2354C9C3FE1EFAB1@ern-server-mail> Hi All, An opportunity for a talented Python Software Engineer has arisen to join a company which is currently going through a phase of rapid expansion. Candidates must have excellent software development skills to join an established team within this small company with offices in the U.K. and U.S. An ideal candidate will be familiar with Linux, have a passion for working with OpenSource software and a flair for creating innovative solutions to complex problems. The candidate will be a self motivated, flexible software engineer working within the existing I.T. Team. The day to day role will almost exclusively focus on new projects. Key elements of the role include l Work closely with the I.T. team and business managers to aid the design and implementation of a new web based application for our customers and data processing engine. l Work closely with the application design team to understand, agree, plan and develop the new application. l Assess software requirements and assist with the project planning stage. l Design, code and test various software elements in both Windows and Linux based environments. l Ability to train and mentor other members of the software development team. l Experience of working within a development team using source control and collaborative tools such as Subversion, CVS, Trac, etc. l Providing required documentation (specifications, test plans, processes, etc). This is a 6-12 month contract based near Portsmouth in Hampshire UK . Please do not hesitate to contact me for further information. Regards Rakesh ___________________ Rakesh Thakrar Manager Microcom Tel: 01923 851225 Mob: 079 7094 3227 Fax: 0845 389 2392 www.microcom-IT.com Beaumont Gate Shenley Hill Radlett Hertfordshire WD7 7AR Permanent and Contract IT Specialists ____________________________________ P SAVE A TREE - PLEASE DO NOT PRINT THIS EMAIL UNLESS YOU REALLY NEED TO. ************************************************************************ ************ The views expressed in this e-mail are not necessarily the views of European Recruitment Network Ltd, its directors, officers or employees make no representation or accept any liability for its accuracy or completeness unless expressly stated to the contrary. This e-mail, and any attachments are strictly confidential and intended for the addressee(s) only. The content may also contain legal, professional or other privileged information. Unless expressly stated to the contrary, no contracts may be concluded on behalf of European Recruitment Network Ltd by means of e-mail communication. You may report the matter by calling us on 0845 389 2322. Please ensure you have adequate virus protection before you open or detach any documents from this transmission. European Network Recruitment Ltd does not accept any liability for viruses. European Recruitment Network Ltd is registered in England: Company Number: 5651508. Registered Office: Greener House, 66-68 Haymarket, London, SW1Y 4RF ************************************************************************ ************ -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Jul 30 21:13:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 22:13:49 -0300 Subject: proxy class and __add__ method References: <18715799.post@talk.nabble.com> <3d59a908-f585-4ff5-ad37-bb48579cc9cb@a21g2000prf.googlegroups.com> Message-ID: En Wed, 30 Jul 2008 14:54:51 -0300, Rhamphoryncus escribi?: > On Jul 29, 10:23?pm, "Gabriel Genellina" > wrote: >> En Tue, 29 Jul 2008 13:13:51 -0300, Magnus Schuster ? >> escribi : >> >> > I have written the following small proxy class which I expect to pass >> all >> > function calls to the 'original' object: >> >> > --- BEGIN --- >> > class proxy(object): >> > ? ? def __init__( self, subject ): >> > ? ? ? ? self.__subject = subject >> > ? ? def __getattr__( self, name ): >> > ? ? ? ? return getattr( self.__subject, name ) >> >> > But "k=prx_i+1" raises a >> > : unsupported operand type(s) for +: >> 'proxy' >> > and 'int'. >> >> > How is this addition different from the previous line "j=..."? And >>> how ? >>> can I >>> modify the proxy class so that all methods are passed on, which are not >>> explicitly overloaded? >> >> Try implementing a similar __getattr__ method in a metaclass. > > But I don't think they use __getattr__.. they bypass it. Effectively > they catch the assignment to __add__ and cache it. You'll have to > always define it in the class and have it be ineffectual in some cases. Ouch, yes, thanks, I noticed the fact after some testing. -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Sun Jul 27 18:13:46 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Jul 2008 22:13:46 GMT Subject: Confounded by Python objects References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> <5ddae1dd-c7dd-4f04-84f6-ad71c3282c92@j7g2000prm.googlegroups.com> <6f1a6uF9ctsmU1@mid.uni-berlin.de> <009c464f$0$20302$c3e8da3@news.astraweb.com> <488cd4a2$0$21184$426a34cc@news.free.fr> Message-ID: <009ceea1$0$20302$c3e8da3@news.astraweb.com> On Sun, 27 Jul 2008 20:04:27 +0200, Bruno Desthuilliers wrote: >> In general, anything that looks like this: >> >> s = '' >> for i in range(10000): # or any big number >> s = s + 'another string' >> >> can be slow. Very slow. > > But this is way faster: > > s = '' > for i in range(10000): # or any big number > s += 'another string' Actually, no, for two reasons: (1) The optimizer works with both s = s+t and s += t, so your version is no faster than mine. (2) The optimization isn't part of the language. It only happens if you are using CPython versions better than 2.4, and even then not guaranteed. People forget that CPython isn't the language, it's just one implementation of the language, like Jython and IronPython. Relying on the optimization is relying on an implementation-specific trick. > yeps : using augmented assignment (s =+ some_string) instead of > concatenation and rebinding (s = s + some_string). Both are equally optimized. >>> timeit.Timer('s+=t', 's,t="xy"').repeat(number=100000) [0.027187108993530273, 0.026471138000488281, 0.027689933776855469] >>> timeit.Timer('s=s+t', 's,t="xy"').repeat(number=100000) [0.026300907135009766, 0.02638697624206543, 0.02637791633605957] But here's a version without it: >>> timeit.Timer('s=t+s', 's,t="xy"').repeat(number=100000) [2.1038830280303955, 2.1027638912200928, 2.1031770706176758] -- Steven From asma61 at dsl.pipex.com Sun Jul 27 15:29:39 2008 From: asma61 at dsl.pipex.com (DaveM) Date: Sun, 27 Jul 2008 20:29:39 +0100 Subject: Rant (was Re: x*x if x>10 References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3g8rF9gfj0U1@mid.uni-berlin.de> <6f3gmaF9moqsU1@mid.uni-berlin.de> <1q5p845o2j9htp6vf44u6nqinucsr1numf@4ax.com> Message-ID: On Sun, 27 Jul 2008 09:28:28 -0700, Gary Herron wrote: >> a = list(set(itertools.chain(*sessexam.values()))) >> a.sort() #As I write I'm wondering if I really need it sorted. Hmm... >> return a >Didn't someone already answer that. List addition and sum() both do >what you want. > > >>> A = [1,2,3] > >>> B = [4,5,6] > >>> C = [7,8,9] > > >>> A+B+C >[1, 2, 3, 4, 5, 6, 7, 8, 9] True, although unsuitable for my circumstance. > >>> sum([A,B,C], []) >[1, 2, 3, 4, 5, 6, 7, 8, 9] Ah. I had no luck with sum, but I hadn't realised it needed the "[]" term. I must read about it again. >It doesn't get any easier than that. Not only that, but it's exactly what I was after - and fastest, too, although speed isn't really an issue. Thank you. DaveM From salih84 at gmail.com Wed Jul 23 12:43:06 2008 From: salih84 at gmail.com (Eurotechzone) Date: Wed, 23 Jul 2008 09:43:06 -0700 (PDT) Subject: Europe's Best Computer Enthusiast Website, Eurotechzone is now Open! Message-ID: http://www.eurotechzone.com Catering to the computer enthusiasts from all over the world, Eurotechzone is Europe?s first multi-lingual website on hardware news&reviews. In this site you will find: ? The hottest news from IT Bussiness world ? The Reviews of the newest electronic components and PC hardwares. ? A dynamic community/forum to discuss IT subjects and technical issues. ? ?and more and more is awaiting for you in www.eurotechzone.com From lanclos at ucolick.org Wed Jul 16 19:56:56 2008 From: lanclos at ucolick.org (Kyle Lanclos) Date: Wed, 16 Jul 2008 16:56:56 -0700 Subject: Manually prompting garbage collection In-Reply-To: References: <20080716230911.GD22400@monkey.ucolick.org> Message-ID: <20080716235656.GE22400@monkey.ucolick.org> Fredrik Lundh wrote: > what magic do you expect the "manual garbage collection" to do here that > the DECREF doesn't already do? The DECREF decrements the reference count, but does not immediately prompt garbage collection when the reference count drops to zero; that garbage collection does not appear to occur until I return from the particular C function I am in the middle of executing. Ideally, I want to explicitly prompt garbage collection in the middle of a C function, without first returning to the larger Python interpreter. --Kyle From aquil.abdullah at gmail.com Tue Jul 15 10:42:32 2008 From: aquil.abdullah at gmail.com (Aquil H. Abdullah) Date: Tue, 15 Jul 2008 10:42:32 -0400 Subject: Using Python To Launch Python In-Reply-To: <23116d500807150741w157af9ffld1ace08a57896d71@mail.gmail.com> References: <20080714212454.GE16010@dragontoe.org> <23116d500807141440u402eed7du5e41d72bb0716c58@mail.gmail.com> <20080715003920.GF16010@dragontoe.org> <23116d500807150741w157af9ffld1ace08a57896d71@mail.gmail.com> Message-ID: <23116d500807150742n26de4d67p79d6b226e78d83f4@mail.gmail.com> Ahh, Win-BASH cool!!! On Tue, Jul 15, 2008 at 10:41 AM, Aquil H. Abdullah < aquil.abdullah at gmail.com> wrote: > Ack, .bat files! Yes, you are correct Windows does not ship with Python, > and there are ways to get bash (cygwin) on your Windoze system. I am > leaning towards a solution similar to your second suggestion as it will keep > me from having to distribute .bat files for one platform and .sh files for > another. Thank you for all of your suggestions. > > > On Mon, Jul 14, 2008 at 8:39 PM, Derek Martin wrote: > >> On Mon, Jul 14, 2008 at 05:40:43PM -0400, Aquil H. Abdullah wrote: >> > You've hit the proverbial nail with the hammer. The problem is that my >> > application needs to run under both the Linux and Windows OSs, so while >> I >> > would love to use a nice sh, csh, or bash shell script. My hands are >> tied >> > because Windows does not provide such wonderful shells. >> >> *Provides*, no... neither does it provide Python, for what that's >> worth. But you can certainly get it (bash): >> >> http://win-bash.sourceforge.net/ >> >> I suppose it's not worth installing just for this purpose though... >> But you can provide with your application a DoS batch file that does >> exactly the same thing (in addition to a shell script). The user >> would quite intuitively use whichever were appropriate, or follow your >> provided directions otherwise. Or, the equivalent in (hopefully >> OS-agnostic) Python: >> >> import os, sys >> >> # I believe this gets the name of the root in all major OSes >> def root_dir(path): >> if os.path.dirname(path) == path: >> return path >> return (root_dir(os.path.dirname(path))) >> >> appname = >> root = root_dir(os.getcwd()) >> install_path = os.path.join(root, "usr") >> bin_path = os.path.join(install_path, "bin") >> os.environ["PATH"] = bin_path + os.pathsep + os.environ["PATH"] >> python_path = os.path.join(bin_path, "python") >> args = sys.argv[1:] >> args.insert(0, os.path.join(bin_path, appname)) >> args.insert(0, python_path) >> args.insert(0, python_path) >> os.execv(python_path, args) >> >> >> >> > > > -- > Aquil H. Abdullah > aquil.abdullah at gmail.com > -- Aquil H. Abdullah aquil.abdullah at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From elessar at nienna.org Thu Jul 31 15:04:05 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Thu, 31 Jul 2008 13:04:05 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <00a121b4$0$20313$c3e8da3@news.astraweb.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <00a121b4$0$20313$c3e8da3@news.astraweb.com> Message-ID: <48920CA5.7050705@nienna.org> Steven D'Aprano wrote: > On Wed, 30 Jul 2008 09:23:05 -0600, Matthew Fitzgibbons wrote: > >> If you're expecting a list (and only a list) >> then your point makes sense. 'if x' can get you into trouble if you >> _don't_ want its polymorphism. > > "if x" is hardly unique in that way. If you're expecting a list, and only > a list, "len(x) != 0" will get you in trouble if somebody passes a string > or a dictionary. I don't see any reason why we should single out "if x" > as dangerous in the face of invalid types. With the exception of the "is" > and "is not" operators, nothing in Python is guaranteed to work with any > imaginable object. Even print can fail, if the object's __str__ method > raises an exception. Forgot respond to this point. I heartily agree. :) I singled out 'if x' only because that's the specific example under scrutiny. I think you and I are pretty much in agreement. -Matt From paul at subsignal.org Sat Jul 19 10:29:38 2008 From: paul at subsignal.org (paul) Date: Sat, 19 Jul 2008 16:29:38 +0200 Subject: Help with displaying images in CherryPy In-Reply-To: <4881DFFB.5060306@preisshare.net> References: <4881DFFB.5060306@preisshare.net> Message-ID: David Lyon schrieb: ... > All I want is a sample configuration file that will allow me to display > a page with a jpeg on it. .... > This really should only take a few minutes for somebody who has done > this in CherryPy before and I would certainly appreciate the assistance > because it doesn't seem covered in any documentation that i could find. Whats wrong with this page? http://www.cherrypy.org/wiki/StaticContent cheers Paul From sri_annauni at yahoo.co.in Wed Jul 2 07:14:29 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Wed, 2 Jul 2008 16:44:29 +0530 (IST) Subject: How to pickle bound methods Message-ID: <13944.78626.qm@web7913.mail.in.yahoo.com> HI Peter, It works will for instance and class methods. But it doesn't work for static methods. Can you tel me how to pickle static methods as well?? Thanks, Srini ----- Original Message ---- From: Peter Otten <__peter__ at web.de> To: python-list at python.org Sent: Wednesday, 2 July, 2008 12:53:19 PM Subject: Re: How to pickle bound methods srinivasan srinivas wrote: > I would like?to know how to pickle a bound method?? $ cat pickle_method.py import copy_reg import new def make_instancemethod(inst, methodname): ? ? return getattr(inst, methodname) def pickle_instancemethod(method): ? ? return make_instancemethod, (method.im_self, method.im_func.__name__) copy_reg.pickle(new.instancemethod, pickle_instancemethod, make_instancemethod) if __name__ == "__main__": ? ? import pickle ? ? class A(object): ? ? ? ? def __init__(self, who): ? ? ? ? ? ? self.who = who ? ? ? ? def alpha(self): ? ? ? ? ? ? print "Hello,", self.who ? ? FILENAME = "method.pickle" ? ? import sys ? ? args = sys.argv[1:] ? ? if args: ? ? ? ? a = A(args[0]) ? ? ? ? m = a.alpha ? ? ? ? pickle.dump(m, open(FILENAME, "wb")) ? ? else: ? ? ? ? m = pickle.load(open(FILENAME, "rb")) ? ? ? ? m() $ python pickle_method.py world $ python pickle_method.py Hello, world $ python pickle_method.py Srini $ python pickle_method.py Hello, Srini Peter -- http://mail.python.org/mailman/listinfo/python-list Bring your gang together. Do your thing. Find your favourite Yahoo! group at http://in.promos.yahoo.com/groups/ From guilhem.faure at gmail.com Wed Jul 23 03:33:07 2008 From: guilhem.faure at gmail.com (Guilhem Faure) Date: Wed, 23 Jul 2008 08:33:07 +0100 Subject: mean of arobase in python Message-ID: <7c49f36f0807230033k40722abfwdb28c34d3d88a32a@mail.gmail.com> Hello, What means @ in python ? In this script for exemple (this script return an error in my konsole...) @f1(arg) @f2 def func(): pass I see several script where used this symbol but I can't understand. G -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Tue Jul 29 13:59:25 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 10:59:25 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: <3a5fb076-c58a-45cf-80bb-e9fd4aab8276@v13g2000pro.googlegroups.com> On Jul 29, 5:27 am, Steven D'Aprano wrote: > On Tue, 29 Jul 2008 01:37:45 -0700, Carl Banks wrote: > > I would accept as "evidence" something that satisfies my criteria, which > > your example did not: it could have easily (and more robustly) been > > written with a simple explicit test. > > Only at the cost of completely ignoring the functional requirements and > changing the API. In other words: you ignore my code, and invent your own > imaginary code that does something completely different, then say that > this imaginary code is better. And, BTW, you keep making unsubstantiated assertions and keep expecting me to take them at face value. I'm really not going to take your word for it that your "functional requirements" would preclude the possibility of rewriting it as I said to, unless you provide details. Also, your third claim is false since it would have exactly the same behavior. Carl Banks From guilhem.faure at gmail.com Fri Jul 25 04:29:19 2008 From: guilhem.faure at gmail.com (Guilhem Faure) Date: Fri, 25 Jul 2008 10:29:19 +0200 Subject: 2d graphics - what module to use? In-Reply-To: <5519ca3a-bef6-4673-981a-fb327425cfee@w39g2000prb.googlegroups.com> References: <5519ca3a-bef6-4673-981a-fb327425cfee@w39g2000prb.googlegroups.com> Message-ID: <7c49f36f0807250129p4a5e892fie80d6661a12bcd8a@mail.gmail.com> You can try R cran also. Very powerfull and free. And with R you can use Rpy, a library R for python and can access to R function and R graph in a python script. Other mathematic library exist in python : Matplotlib for exemple. Summary : to draw graph easely in python : Rpy lib or Matplotlib. If you don't know R language (vectorial language) use Matplotlib. Adress : R site : http://cran.r-project.org/ Rpy lib for python : http://rpy.sourceforge.net/ Matplotlib for python : http://matplotlib.sourceforge.net/ On 7/25/08, King wrote: > > Use python's default GUI tkinter's drawing functions or you can use > wxPython GUI kit or you can use pyopengl. > If you are only interested to draw sin waves or math functions that > you should give try to matlab at www.mathworks.com > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Russ.Paielli at gmail.com Sun Jul 27 22:52:55 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 19:52:55 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <7eabe5a6-357a-4255-a958-0804959ce844@a6g2000prm.googlegroups.com> <009cf838$0$20302$c3e8da3@news.astraweb.com> Message-ID: On Jul 27, 3:54 pm, Steven D'Aprano wrote: > On Sun, 27 Jul 2008 12:33:16 -0700, Russ P. wrote: > > On Jul 27, 1:19 am, Steven D'Aprano > cybersource.com.au> wrote: > >> On Sat, 26 Jul 2008 17:14:46 -0700, Russ P. wrote: > > >> > You take the name down to a single letter. As I suggested in an > >> > earlier post on this thread, why not take it down to zero letters? > > >> The question isn't "why not", but "why". The status quo works well as > >> it is, even if it isn't perfect. Prove that implicit self is a good > >> idea -- or at least prove that it is an idea worth considering. > > >> "I don't like typing self" doesn't convince me. The same argument could > >> be made typing parentheses, colons, commas, etc. We could end up with > >> something like this: > > >> class Foo base > >> def method x y z > >> .args = list x y z > > >> That's not necessarily wrong, but it's not Python. > > > And what does that have to do with my suggestion? Absolutely nothing. > > Not at all. You're suggesting a change to Python's syntax. I've suggested > a couple more changes to Python syntax. I don't intend them to be taken > seriously, but only to illustrate a point that syntax defines how a > language is written. You want to change that. But the syntax change I am suggesting is trivial compared to the draconian examples you gave. > > It's a red herring that you seem to be using to obscure the fact that > > you have no rational argument to make. > > I don't have to make a rational argument for keeping the status quo. That > status quo just *is*. You want people to change, you need to convince > them that such a change is not just "not bad" but a serious advantage, > enough to make up for all the work required to implement it. > I'm listening. Tell me why removing self if not merely harmless, but > actively better. > > [...] I thought I did just that. I am very meticulous about the appearance of my code, and the less cluttered the better. That's one of the main reasons that I use Python. My suggestion would be relatively trivial to implement, yet it would dramatically reduce clutter. You may not agree, but I think the case is strong. > >> By "better" do you mean "uglier"? If so, I agree with you. If not, then > >> I disagree that it is better. > > > You seem to be freaked out by an empty argument. Actually, it bothers me > > a bit too, which is why I suggested that a period could be used as the > > first argument to indicate that, like Clint Eastwood in The Good, the > > Bad, and the Ugly, "self" had no name here. > > Well there you go now. How should we *talk* about this piece of code? Try > writing a comment or docstring, or even sitting down with a fellow > programmer and discussing it. What do you call this implicit Object With > No Name? How do Java and C++ programmers talk about the instance for which the method was called? I wasn't aware that that was a problem for them. > def fun( , cat): > .cat = cat # assumes that the Object With No Name has foo > > versus > > def fun(self, cat): > self.cat = cat # assumes that self has foo > > Before you suggest that people will continue to call the first argument > "self" but just not write it down anywhere, I suggest that's a terrible > idea and one which will confuse a lot of people. "Where's this 'self' > defined? I can't find it anywhere!" Any programmer who can't get past that point needs to find a new line of work -- such as moving furniture. > A slightly better suggestion is "the instance", but that fails here: > > class C(object): > def method(, other): > assert isinstance(other, C) > .cat = other # assumes that the instance has foo > # er, that is to say, the implicit instance, > # not the other instance > > The ability to talk easily about the code is invaluable. Implicit self > makes it harder to talk about the code. I can only imagine what you must think about lambda functions and list comprehensions. > [...] > > >> Even uglier than the first. Convince me there's a benefit. > > > Actually, I think it's elegant. And I'll bet that if Guido had suggested > > it, you would think it was beautiful. > > Oh please. I think the syntax for ternary if is ugly, and Guido came up > with that, and it doesn't even use punctuation. Off topic, but I happen to like Guido's ternary "if." I use it wherever I can, within reason. > > Why force a name to be used when none is needed? > > But a name is needed. > > class Foo(base1, base2, base3): > def meth(self, arg): > super(Foo, self).meth(arg) > print self > try: > value = _cache[self] > except KeyError: > value = some_long_calculation(self) > > How do you pass self to arbitrary functions without a name? I didn't say you *never* need the name. If you need it, then use it. But if you don't need it, you shouldn't be forced to use a name just for the sake of having a name. From tjreedy at udel.edu Sat Jul 26 17:25:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 17:25:02 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87k5f8afjl.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> Message-ID: Torsten Bronger wrote: > Hall?chen! > > D'Arcy J.M. Cain writes: > >> On Sat, 26 Jul 2008 09:45:21 +0200 >> Torsten Bronger wrote: >> >>> Of course, "self" would have to become a reserved word. You >>> could say that this may break some code, but I don't see much >>> freedom >> Isn't this a showstopper all by itself? > > Yes. But I've seen no code that uses some other word. There is a lot of code you have not seen. Really. In informal code I use 's' and 'o' for 'self' and 'other'. I don't usually post such because it is not considered polite. So you have seen a biased sample of the universe. From skip at pobox.com Tue Jul 22 14:52:50 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 22 Jul 2008 13:52:50 -0500 Subject: software engineering foundations? Message-ID: <18566.11394.326317.821553@montanaro-dyndns-org.local> Sorry for the off-topic-ish post. My son (a fairly junior sysadmin type) mentioned to me today that he was looking for online courses for Perl. (I don't hold that against him. Perl is still a lingua franca in the sysadmin realm.) In my work I have from time-to-time had to pick up and maintain scripts (generally shell/Python stuff) which non-professional programmers have written. It's never what you would call a "pleasant" task. There are software construction skills which are entirely distinct from the language in which you are programming. We can tout object-oriented, structured programming, test-driven development or other software engineering techniques, but there is a body of knowledge out there which is orthogonal to the language in which the code is written. People who are not professional programmers often lack those skills and their code shows it. Are there any good online resources for this "software structure" axis? Googling for "object oriented programming tutorial" yields a bunch of stuff, much of it language-specific. I'm trying to find something a bit more general than that though. I Googled for "software engineering tutorial" as well. Most of the early hits were either inaccessible (ACM subscription only) or contents-like stuff (conference announcements, for example). Number eight on the list was this rather promising page: http://www.cmcrossroads.com/bradapp/links/swe-links.html It was last updated over 10 years ago. I find it hard to believe that so little has changed in that time that some other page with more recent references hasn't percolated to the top of Google's page rank! After all, the Web has grown just a tad in that timeframe. I have a sneaking suspicion that what I'm looking for is out there, but that I'm not asking Google in the right manner. Any and all pointers/suggestions cheerfully accepted. Thx, -- Skip Montanaro - skip at pobox.com - http://www.webfast.com/~skip/ ------ ELON MUSK: If fuel cells were good, don't think you'd see them somewhere, like maybe in a laptop or a cell phone or a $200 million military satellite maybe? And yet, where do you see them? SPENCER MICHELS: You don't. ELON MUSK: Exactly. From ron.longo at cox.net Wed Jul 16 12:00:43 2008 From: ron.longo at cox.net (Ron Longo) Date: Wed, 16 Jul 2008 12:00:43 -0400 Subject: Is there any interest in working on an application? Message-ID: <005501c8e75d$1a06b0c0$6601a8c0@aristotle> Hello, I have an python application which I've been developing for several years (off and on, mostly off for lack of time) which I'm considering putting up to open source if I can find other developers interested in contributing. The application is a web publisher/information outliner. (See an example of a beta here: http://members.cox.net/ronpro/welcome.html where I test my ability to generate an interactive tree for the data in an outline.) The application is 100% Python. The gui is written using Tkinter and Tix -- I'm definitely open to other libraries for the GUI. The app supports unicode in the outlines. There's a spell-checker plugin (complements of the pyenchant project). The application is written on top of an application framework and plugin framework both of which I developed myself. Much of the application is actually plugins so it's very modular. For screen shots of the app so far see: http://members.cox.net/ronpro/scrnCap1.JPG and http://members.cox.net/ronpro/scrnCap2.JPG The development would probably be done through SourceForge. I'm in the process of documenting the current design in UML class diagrams using the free version of Visual Paradigm (if another tool is suggested we could switch). My motive: I'm a research scientist. My prefered method to record, review, edit and organize my notes is within an outline (rather than a flat notebook format used by most researchers). The ability to consider new ideas can be as easy as moving items around in the outline. I've used many commercial programs in the past but all have had some limitation or another. Most don't support unicode (I need unicode characters to record mathematical and logical formulae). Those that do produce html don't produce the side-by-side view of an interactive tree (able to expand or collapse nodes) beside the actual on-screen notes. The interactive tree is a necessity for me with over 2000 entries in my largest outline and growing fast. Design Philosophy: I've attempted to keep to the following design philosophy (prioritized by order). - User Experience -- everything should be easy for the user. - OO, Maximize modularity, minimize cross dependence. (e.g. The Application framework, plugin framework and word processor know nothing about the problem domain and nothing about the other modules in the application). - KISS, I prefer simple straightforward code over speedy "tricks". If it's hard to read or understand I'll probably hate it. - Minimize 3rd party modules in the core application. I know 3rd party libs can make it easier to develop and this would seem to violate KISS. However, with User Experience being higher priority, the less there is for a user to install the easier. Best case, the user installs Python and s/he's ready to go. I don't mind requiring 3rd party libs for most plugins. My take on this is here: - If it's part of the core distribution (the core application or a plugin that's part of the main distribution), do everything possible to avoid 3rd party libs. - For plugins distributed separately from the application installer, the plugin must check for the required libs upon loading and exit gracefully if the lib is not present (at most display a dialog stating that the required lib is not installed.) - If at all possible, provide unit test with each module (including plugins) Future Direction: - Some of the features in the menus and on the toolbars are not yet implemented. (e.g. find, search/replace, bulletized and numbered lists, tables) - The content of any tree entry is displayed in the content pane to the right of the outline. Right now the only supported content is formatted text in a word processor (actually a glorified Text widget). The Text widget is part of the core app. I want this widget to be turned into a plugin so that other kinds of content are possible with other content editor plugins. The main app would then select and display the appropriate content editor for a given kind of data. - Currently, cutting and pasting is possible, however cutting and pasing formatted text is only possible within the application. Want to support cutting and pasing stylized text with the system clipboard and other applications (word, star office, etc.) - Import export other formats (importers and exporters are already plugins). We just need to write more of them. - Support multiple views of a single outline so we can view different parts of the outline simultaneously. - Support cutting and pasting, dragging and dropping across different outlines. - Customizable appearance for HTML output. - Anything else the development group or users can think of. If you're interested in more information or trying out this app (note that it's very immature and probably only worthy of being called an alpa) please don't hesitate to contact me. Thanks for reading, Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From piet at cs.uu.nl Thu Jul 10 04:42:18 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 10 Jul 2008 10:42:18 +0200 Subject: Terminate a python script from linux shell / bash script References: Message-ID: >>>>> Gros Bedo (GB) wrote: >GB> I have a question about Python and Linux shell. I have a python >GB> program which is permanently resident in the end-user system. I'm >GB> currently producing a RPM package, and it works nicely. The problem is >GB> that when I uninstall it, my program keeps running in the background, >GB> even if the files are deleted. >GB> I know I can terminate python shell directly, but this is not a good >GB> idea because the end-user may be working with another important python >GB> application, and would be very angry if mine would close everything >GB> that is using python shell. That's not how it works. If you kill one running python script it will not effect other python scripts. Each script has its own interpreter process running. >GB> So, is there a way from the Linux shell or a bash script to terminate >GB> just one specific Python script ? So just kill it. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From mal at egenix.com Thu Jul 31 06:24:57 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 31 Jul 2008 12:24:57 +0200 Subject: Optimizing size of very large dictionaries In-Reply-To: <1217464179.31710.1266222419@webmail.messagingengine.com> References: <1217464179.31710.1266222419@webmail.messagingengine.com> Message-ID: <489192F9.3030005@egenix.com> On 2008-07-31 02:29, python at bdurham.com wrote: > Are there any techniques I can use to strip a dictionary data > structure down to the smallest memory overhead possible? > > I'm working on a project where my available RAM is limited to 2G > and I would like to use very large dictionaries vs. a traditional > database. > > Background: I'm trying to identify duplicate records in very > large text based transaction logs. I'm detecting duplicate > records by creating a SHA1 checksum of each record and using this > checksum as a dictionary key. This works great except for several > files whose size is such that their associated checksum > dictionaries are too big for my workstation's 2G of RAM. If you don't have a problem with taking a small performance hit, then I'd suggest to have a look at mxBeeBase, which is an on-disk dictionary implementation: http://www.egenix.com/products/python/mxBase/mxBeeBase/ Of course, you could also use a database table for this. Together with a proper index that should work as well (but it's likely slower than mxBeeBase). -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 31 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From fredrik at pythonware.com Tue Jul 22 17:49:00 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 23:49:00 +0200 Subject: Iterating Through List or Tuple In-Reply-To: References: Message-ID: Samir wrote: > Is there a way to loop or iterate through a list/tuple in such a way > that when you reach the end, you start over at the beginning? For > example, suppose I define a list "daysOfWeek" such that: > >>>> daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] >>> import itertools >>> help(itertools.cycle) Help on class cycle in module itertools: class cycle(__builtin__.object) | cycle(iterable) --> cycle object | | Return elements from the iterable until it is exhausted. | Then repeat the sequence indefinitely. ... >>> L = [1, 2, 3] >>> for i, x in enumerate(itertools.cycle(L)): ... print i, x ... if i >= 10: ... break ... 0 1 1 2 2 3 3 1 4 2 5 3 6 1 7 2 8 3 9 1 10 2 >>> From mccredie at gmail.com Thu Jul 24 16:02:41 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 24 Jul 2008 13:02:41 -0700 (PDT) Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: On Jul 24, 2:54?am, Lawrence D'Oliveiro wrote: > In message > , > > Matimus wrote: > > That isn't the standard. With that setup tabs will show up as 4 > > spaces, and still confuse you. > > Why should that be confusing? The most common tab-stop setting is 4 columns. I think if you continued reading my post you would see. The tabstop feature in Vi(m) sets how many spaces a tab character is displayed as. A tab character is specified as 8 spaces. The real problem is that the python interpreter itself follows the spec and interprets a tab as 8 spaces. If you are viewing the code and have mixed tabs and spaces and all of the tabs are showing up as 4 spaces you will not be able to spot the issues that will come up. 4 columns is not the most common setting, the most common setting is the default, which is 8. It is just very common for people to change it. I suggest that instead of changing the tabstop, just use spaces (not both) and use the `softtabstop` setting to allow a press of the tab key to insert four spaces instead. Matt From gnuarm at gmail.com Sun Jul 13 09:25:34 2008 From: gnuarm at gmail.com (rickman) Date: Sun, 13 Jul 2008 06:25:34 -0700 (PDT) Subject: spam References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> Message-ID: <1bc1ddbb-fbfc-4e0c-8337-71d2dd301e5d@z66g2000hsc.googlegroups.com> On Jul 12, 9:21 am, Scott in SoCal wrote: > In message > , > > rickman wrote: > >spam > > *PLONK!* I love the way that people who plonk others feel the need to inform everyone of it. That ranks up there with, "I know what you are, but what am I?" From wuwei23 at gmail.com Sun Jul 27 23:25:52 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 27 Jul 2008 20:25:52 -0700 (PDT) Subject: I love "shelf" BUT References: Message-ID: <1c2d28bb-06e8-4f02-a528-9d86f84366dd@n33g2000pri.googlegroups.com> On Jul 28, 12:46?pm, Sera Jackson wrote: > ok, I know its an over discussed topic. Althought I understand why it > is there I cant constantly see it in my argument list in parenthesis. > > can someone give me an insight of the cons of a syntax like this: > class Class: > ? ? def self.method(arguments): > ? ? ? ? etc, etc > > In other words def method(self, arg1, arg2 ,argN) becomes-> ?def > self.method(arg1, arg2 ,argN) Did you bother to check the group? You would've noticed it's being discussed -right now-: http://groups.google.com/group/comp.lang.python/browse_frm/thread/a5fa8ff0ffadd6ee/60e9dd04719e439a And this -exact- suggestion has been turned down by Guido: http://mail.python.org/pipermail/python-3000/2006-April/000793.html From bearophileHUGS at lycos.com Fri Jul 18 08:40:20 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 18 Jul 2008 05:40:20 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: Peter Otten: > PS: Take these numbers with a grain of salt, they vary a lot between runs. Another possibility :-) from itertools import imap id(x) in imap(id, items) >If you want efficiency you should use a dictionary instead of the list anyway: I agree, but sometimes you have few items to look for, so building the whole dict (that requires memory too) may be a waste of time. In theory this may be faster to build, but in practice you need a benchmark: ids = set(imap(id, items)) followed by: id(x) in ids Bye, bearophile From timr at probo.com Fri Jul 18 02:13:35 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 18 Jul 2008 06:13:35 GMT Subject: How can i use a variable without define it ? References: <87k5fm2p1x.fsf@benfinney.id.au> <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> <87fxqa2mu0.fsf@benfinney.id.au> <5dd91053-d239-4ff1-b693-d6afedf6bf24@x35g2000hsb.googlegroups.com> Message-ID: zhw wrote: >Ben Finney >wrote: >> >> What problem are you trying to solve? > >I an sorry, I can't tell you. That's nonsense. No one is asking you to reveal the design of your company's next product. However, you have some overall problem you are trying to solve, and you have focused in on one POSSIBLE solution. Instead, tell us about the PROBLEM, and we'll offer good solutions. >If you can't give a solution, just ignore it! NO ONE will be able to give you a solution, because you have not described the problem. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dylanwilson at ymail.com Fri Jul 18 13:33:52 2008 From: dylanwilson at ymail.com (Dylan Wilson) Date: Fri, 18 Jul 2008 10:33:52 -0700 (PDT) Subject: file() Message-ID: <191300.25030.qm@web59610.mail.ac4.yahoo.com> well, I'm in the beginings of making a random sentence generator for a mod my friend makes, but I want the nouns, verbs pastverbs, etc. to be easily customizable by editing a file, but, last night file() worked fine and today it's saying " line 1: `read_who = file('who.ini', 'r')'" here's what I have so far, but for reference it's possible I'm just being an idiot because I'm very new to Python and programming in general read_who = file('who.ini', 'r') who = read_who.read() read_what = file('what.ini', 'r') what = read_what.read() read_end = file('end.ini', 'r') end = read_end.read() read_because = file('because.ini', 'r') because = read_because.read() read_the = file('the.ini', 'r') da = read_the.read() read_period = file('punc.ini', 'r') period = read_period.read() prd = read_period.read() read_nouns = file('nouns.ini', 'r') nouns = read_nouns.read() read_verbs = file('verbs.ini', 'r') verbs = read_verbs.read() read_pastverbs = file('pastverbs.ini', 'r') pastverbs = read_pastverbs.read() -------------- next part -------------- An HTML attachment was scrubbed... URL: From dbpokorny at gmail.com Tue Jul 1 17:54:44 2008 From: dbpokorny at gmail.com (dbpokorny at gmail.com) Date: Tue, 1 Jul 2008 14:54:44 -0700 (PDT) Subject: How to make a function associated with a class? References: <69e26f9b-2f00-4318-9bc5-6aa94e141bca@59g2000hsb.googlegroups.com> <4d7cf477-e791-4122-bc20-0dbd1a16bc12@j22g2000hsf.googlegroups.com> <0d9c534b-8720-4363-b3e5-eb546dd3637c@8g2000hse.googlegroups.com> Message-ID: <607e76b4-d38f-43c4-8cc3-8c510c1785d2@u6g2000prc.googlegroups.com> On Jul 1, 2:24 pm, Kurda Yon wrote: > > By the way, "type(self)" returns the name of the class to which the > "self" belongs? > Does "instance" return "true" if the first argument belongs to the > class whose name is given in the second argument? $ python Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11) [GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> help(type) [...] >>> help(isinstance) [...] From ki4yjl at gmail.com Thu Jul 10 23:22:16 2008 From: ki4yjl at gmail.com (WDC) Date: Thu, 10 Jul 2008 20:22:16 -0700 (PDT) Subject: paypal wholesale men jordans 17 (paypal accept)(www super-saler com References: Message-ID: <5d746374-d2a0-411e-bf60-87256a219b7c@m44g2000hsc.googlegroups.com> On Jul 10, 10:33?pm, 128 wrote: > paypal wholesale men jordans (paypal accept)(www super-saler com > > paypal wholesale men jordans 1 (paypal accept)(www super-saler com > > paypal wholesale men jordans 2 (paypal accept)(www super-saler com > > paypal wholesale men jordans 3 (paypal accept)(www super-saler com > > paypal wholesale men jordans 4 (paypal accept)(www super-saler com > > paypal wholesale men jordans 5 (paypal accept)(www super-saler com > > paypal wholesale men jordans 6 (paypal accept)(www super-saler com > > paypal wholesale men jordans 7 (paypal accept)(www super-saler com > > paypal wholesale men jordans 8 (paypal accept)(www super-saler com > > paypal wholesale men jordans 9 (paypal accept)(www super-saler com > > paypal wholesale men jordans 10 (paypal accept)(www super-saler com > > paypal wholesale men jordans 11 (paypal accept)(www super-saler com > > paypal wholesale men jordans 12 (paypal accept)(www super-saler com > > paypal wholesale men jordans 13 (paypal accept)(www super-saler com > > paypal wholesale men jordans 14 (paypal accept)(www super-saler com > > paypal wholesale men jordans 15 (paypal accept)(www super-saler com > > paypal wholesale men jordans 16 (paypal accept)(www super-saler com > > paypal wholesale men jordans 17 (paypal accept)(www super-saler com > > paypal wholesale men jordans (paypal accept)(www super-saler com > > paypal wholesale men jordans 1 (paypal accept)(www super-saler com > > paypal wholesale men jordans 2 (paypal accept)(www super-saler com > > paypal wholesale men jordans 3 (paypal accept)(www super-saler com > > paypal wholesale men jordans 4 (paypal accept)(www super-saler com > > paypal wholesale men jordans 5 (paypal accept)(www super-saler com > > paypal wholesale men jordans 6 (paypal accept)(www super-saler com > > paypal wholesale men jordans 7 (paypal accept)(www super-saler com > > paypal wholesale men jordans 8 (paypal accept)(www super-saler com > > paypal wholesale men jordans 9 (paypal accept)(www super-saler com > > paypal wholesale men jordans 10 (paypal accept)(www super-saler com > > paypal wholesale men jordans 11 (paypal accept)(www super-saler com > > paypal wholesale men jordans 12 (paypal accept)(www super-saler com > > paypal wholesale men jordans 13 (paypal accept)(www super-saler com > > paypal wholesale men jordans 14 (paypal accept)(www super-saler com > > paypal wholesale men jordans 15 (paypal accept)(www super-saler com > > paypal wholesale men jordans 16 (paypal accept)(www super-saler com > > paypal wholesale men jordans 17 (paypal accept)(www super-saler com > > paypal wholesale men jordans (paypal accept)(www super-saler com > > paypal wholesale men jordans 1 (paypal accept)(www super-saler com > > paypal wholesale men jordans 2 (paypal accept)(www super-saler com > > paypal wholesale men jordans 3 (paypal accept)(www super-saler com > > paypal wholesale men jordans 4 (paypal accept)(www super-saler com > > paypal wholesale men jordans 5 (paypal accept)(www super-saler com > > paypal wholesale men jordans 6 (paypal accept)(www super-saler com > > paypal wholesale men jordans 7 (paypal accept)(www super-saler com > > paypal wholesale men jordans 8 (paypal accept)(www super-saler com > > paypal wholesale men jordans 9 (paypal accept)(www super-saler com > > paypal wholesale men jordans 10 (paypal accept)(www super-saler com > > paypal wholesale men jordans 11 (paypal accept)(www super-saler com > > paypal wholesale men jordans 12 (paypal accept)(www super-saler com > > paypal wholesale men jordans 13 (paypal accept)(www super-saler com > > paypal wholesale men jordans 14 (paypal accept)(www super-saler com > > paypal wholesale men jordans 15 (paypal accept)(www super-saler com > > paypal wholesale men jordans 16 (paypal accept)(www super-saler com > > paypal wholesale men jordans 17 (paypal accept)(www super-saler com > > paypal wholesale men jordans (paypal accept)(www super-saler com > > paypal wholesale men jordans 1 (paypal accept)(www super-saler com > > paypal wholesale men jordans 2 (paypal accept)(www super-saler com > > paypal wholesale men jordans 3 (paypal accept)(www super-saler com > > paypal wholesale men jordans 4 (paypal accept)(www super-saler com > > paypal wholesale men jordans 5 (paypal accept)(www super-saler com > > paypal wholesale men jordans 6 (paypal accept)(www super-saler com > > paypal wholesale men jordans 7 (paypal accept)(www super-saler com > > paypal wholesale men jordans 8 (paypal accept)(www super-saler com > > paypal wholesale men jordans 9 (paypal accept)(www super-saler com > > paypal wholesale men jordans 10 (paypal accept)(www super-saler com > > paypal wholesale men jordans 11 (paypal accept)(www super-saler com > > paypal wholesale men jordans 12 (paypal accept)(www super-saler com > > paypal wholesale men jordans 13 (paypal accept)(www super-saler com > > paypal wholesale men jordans 14 (paypal accept)(www super-saler com > > paypal wholesale men jordans 15 (paypal accept)(www super-saler com > > paypal wholesale men jordans 16 (paypal accept)(www super-saler com > > paypal wholesale men jordans 17 (paypal accept)(www super-saler com > > paypal wholesale men jordans 18 (paypal accept)(www super-saler com > > paypal wholesale men jordans 19 (paypal accept)(www super-saler com > > paypal wholesale men jordans 20 (paypal accept)(www super-saler com > > paypal wholesale men jordans 21 (paypal accept)(www super-saler com > > paypal wholesale men jordans 22 (paypal accept)(www super-saler com > > paypal wholesale men jordans 23 (paypal accept)(www super-saler com > > paypal wholesale men jordans (paypal accept)(www super-saler com > > paypal wholesale men jordans 1 (paypal accept)(www super-saler com > > paypal wholesale men jordans 2 (paypal accept)(www super-saler com > > paypal wholesale men jordans 3 (paypal accept)(www super-saler com > > paypal wholesale men jordans 4 (paypal accept)(www super-saler com > > paypal wholesale men jordans 5 (paypal accept)(www super-saler com > > paypal wholesale men jordans 6 (paypal accept)(www super-saler com > > paypal wholesale men jordans 7 (paypal accept)(www super-saler com > > paypal wholesale men jordans 8 (paypal accept)(www super-saler com > > paypal wholesale men jordans 9 (paypal accept)(www super-saler com > > paypal wholesale men jordans 10 (paypal accept)(www super-saler com > > paypal wholesale men jordans 11 (paypal accept)(www super-saler com > > paypal wholesale men jordans 12 (paypal accept)(www super-saler com > > paypal wholesale men jordans 13 (paypal accept)(www super-saler com > > paypal wholesale men jordans 14 (paypal accept)(www super-saler com > > paypal wholesale men jordans 15 (paypal accept)(www super-saler com > > paypal wholesale men jordans 16 (paypal accept)(www super-saler com > > paypal wholesale men jordans 17 (paypal accept)(www super-saler com > > paypal wholesale men jordans 18 (paypal accept)(www super-saler com > > paypal wholesale men jordans 19 (paypal accept)(www super-saler com > > paypal wholesale men jordans 20 (paypal accept)(www super-saler com > > paypal wholesale men jordans 21 (paypal accept)(www super-saler com > > paypal wholesale men jordans 22 (paypal accept)(www super-saler com > > paypal wholesale men jordans 23 (paypal accept)(www super-saler com > > paypal wholesale men jordans (paypal accept)(www super-saler com > > paypal wholesale men jordans 1 (paypal accept)(www super-saler com > > paypal wholesale men jordans 2 (paypal accept)(www super-saler com > > paypal wholesale men jordans 3 (paypal accept)(www super-saler com > > paypal wholesale men jordans 4 (paypal accept)(www super-saler com > > paypal wholesale men jordans 5 (paypal accept)(www super-saler com > > paypal wholesale men jordans 6 (paypal accept)(www super-saler com > > paypal wholesale men jordans 7 (paypal accept)(www super-saler com > > paypal wholesale men jordans 8 (paypal accept)(www super-saler com > > paypal wholesale men jordans 9 (paypal accept)(www super-saler com > > paypal wholesale men jordans 10 (paypal accept)(www super-saler com > > paypal wholesale men jordans 11 (paypal accept)(www super-saler com > > paypal wholesale men jordans 12 (paypal accept)(www super-saler com > > paypal wholesale men jordans 13 (paypal accept)(www super-saler com > > paypal wholesale men jordans 14 (paypal accept)(www super-saler com > > paypal wholesale men jordans 15 (paypal accept)(www super-saler com > > paypal wholesale men jordans 16 (paypal accept)(www super-saler com > > paypal wholesale men jordans 17 (paypal accept)(www super-saler com > > paypal wholesale men jordans 18 (paypal accept)(www super-saler com > > paypal wholesale men jordans 19 (paypal accept)(www super-saler com > > paypal wholesale men jordans 20 (paypal accept)(www super-saler com > > paypal wholesale men jordans 21 (paypal accept)(www super-saler com > > paypal wholesale men jordans 22 (paypal accept)(www super-saler com > > paypal wholesale men jordans 23 (paypal accept)(www super-saler com Is that spam i spy? From tim.tadh at gmail.com Tue Jul 29 11:22:52 2008 From: tim.tadh at gmail.com (Tim Henderson) Date: Tue, 29 Jul 2008 08:22:52 -0700 (PDT) Subject: Build tool for Python References: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Message-ID: On Jul 29, 11:08?am, Hussein B wrote: > Hi. > Apache Ant is the de facto building tool for Java (whether JSE, JEE > and JME) application. > With Ant you can do what ever you want: compile, generate docs, > generate code, packing, deploy, connecting to remote servers and every > thing. > Do we have such a tool for Python projects? > Thank you. You might want to take a look at Paver. http://www.blueskyonmars.com/projects/paver/ Tim From mail at timgolden.me.uk Tue Jul 29 09:12:37 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 29 Jul 2008 14:12:37 +0100 Subject: Windows Interpreter In-Reply-To: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> References: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> Message-ID: <488F1745.4020705@timgolden.me.uk> Victor Subervi wrote: > Hi: > I would like to make my windows python interpreter work like my linux > one. I want to be able to cut and paste multiple lines of code. You can already do this: what are you trying which isn't working? > Now I can only paste one line at a time. > I do not want it to indent > automatically. How can I change this? I realise this is a difficult thing to describe in words, but I regularly cut and paste multiple lines of code into my Python interpreter and it doesn't indent automatically. Can you give some specific examples of what you do and what does or doesn't work? TJG From babacity4 at gmail.com Thu Jul 24 16:52:55 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:52:55 -0700 (PDT) Subject: Xxxstash com - Amazing porn video collection Message-ID: <38c1e2dd-20c0-47b5-8976-b13cc96c6b69@x29g2000prd.googlegroups.com> xxxstash com . >>>>>>>>>>Best Collection of Xxxstash Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE xxxstash com VIDEOS<<<<<<<<<<< . xxxstash com From norseman at hughes.net Mon Jul 21 17:14:27 2008 From: norseman at hughes.net (norseman) Date: Mon, 21 Jul 2008 14:14:27 -0700 Subject: Importing different versions of a module In-Reply-To: <8b51e78c0807181750x66fd0372y82367245630e921f@mail.gmail.com> References: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> <48811064.5010603@hughes.net> <8b51e78c0807181750x66fd0372y82367245630e921f@mail.gmail.com> Message-ID: <4884FC33.2090006@hughes.net> mercado mercado wrote: > Thanks norseman for the reply. > > You're right that I didn't like it though. :-) > > Also note that my original question has to do with importing modules from > different locations. If all I had to do was use different paths within the > script (e.g. for sending to os.path.join or whatever), then I could just put > those in a config file. That's not a problem... > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list =================================== I started to import a module using its path and now see what you mean. Python is missing the concept: Programmer dictates what machine does. (I come from assembly. If the hardware can do it, so can I.) sys.path can be modified to switch between file sets (prod/test). if a global is set one way, use the normal paths, if set another, modify the needed to force the test_section into use. Unfortunately this is not much of an answer. It means hardcoding two paths into globals and using a third to control which is used. Since Python has a habit of coming and going on its own this may not work in a major effort. It may unload something and later reload with the sys.path set wrong. Docs say it will reload file that did load originally even if the file was modified between loads. Docs do not say it keeps original location. I'll need some time to set things up to test what it does. Nothing I've done in Python had bumped into your problem until I ran the test. Never dawned on me it would be this stupid. I had intended to use Python to talk to ESRI products and my stuff. I made a few minor routines just to get used to Python and was starting to tackle the real problem. My assembly, C, fortran & bash scripts all work as expected. They do, Python doesn't. ORIGINALLY, IN THIS REPLY, I HAD STARTED TO SAY: I've used this before. Maybe it will work in Python, maybe not. Global sets which section to use by being a prefix to each test module name. Something like "my_" for test and empty otherwise. global WHICH WHICH='my_' import WHICH+'subrtn' WHICH='' import WHICH+'subrtn2' gets my_subrtn from the test suite and gets subrtn2 from the production section. Each module would thus need to store/reset the Global's value upon init to be used in its own imports since it's status at any given time is in question. Python docs say Python keeps the original name of the originally successfully loaded file. The built-in 'reload' can get it back, even if it has been changed (edited) during the session. The files my_ whatever have the my_ removed from the disk name when they go production. ######################################################### BUT!!!! import WILL NOT TAKE VARS!!!!!!!! ######################################################### OK check#1 Python 2.5.2 (r252:60911, Mar 4 2008, 10:40:55) [GCC 3.3.6] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> WHICH="my_" >>> import WHICH+"popen2" File "", line 1 import WHICH+"popen2" ^ SyntaxError: invalid syntax >>> OK check#2 >>> >>> x=WHICH+"open2" >>> x 'my_open2' >>> import x Traceback (most recent call last): File "", line 1, in ImportError: No module named x >>> OK check#3 >>> >>> help(x) no Python documentation found for 'my_open2' #true, proves x OK >>> BOY-O-BOY, DOES THAT SCREW THE POOCH!!!! Mercado, like you, I'm not very happy right now. This means that prefixing cannot be used to control imports. For decades I have used prefixing in both scripts and compiled lib routines for controlling what gets loaded or not. Right now I'm not a happy Python camper, not at all. Steve norseman at hughes.net From bj_666 at gmx.net Sun Jul 27 10:50:04 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jul 2008 14:50:04 GMT Subject: Rant (was Re: x*x if x>10 References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> Message-ID: <6f3g8rF9gfj0U1@mid.uni-berlin.de> On Sun, 27 Jul 2008 16:41:19 +0200, Diez B. Roggisch wrote: > DaveM schrieb: >> Getting back to the >> list concatenation, I finally found the itertools.chain command which >> is the most compact and fastest (or second fastest by a trivial amount, >> I can't remember which). Along the way, I must have tried/used half a >> dozen methods, ...which brings me back my initial PERL comment. There's >> more than one way to do it in Python, too. > > Any non-trivial task has that property. I don't know enough perl to have > an example ready that shows something that python has only one way of > doing and perl has several. > > But I *do* know that taking the python zen literally is fruitless. I think it should be taken more literally than the wrong reduction to "there should be only one way". People tend to forget "obvious" and "preferably" all the time. Ciao, Marc 'BlackJack' Rintsch From zentraders at gmail.com Mon Jul 7 22:15:56 2008 From: zentraders at gmail.com (Zentrader) Date: Mon, 7 Jul 2008 19:15:56 -0700 (PDT) Subject: conflict between multiple installs of python (linux) References: <6bd22c06-a1e6-4247-9aff-2d0b29b1ec5e@d1g2000hsg.googlegroups.com> Message-ID: <7435a7c3-78b7-4339-a980-0d0ff3f34a5a@y38g2000hsy.googlegroups.com> On Jul 5, 11:09 am, david wrote: > You learn something new every day: > > On my ubuntu, update-manager is supposed to use the python2.5 > installed on /usr/bin. Well, I had subsequently installed a whole > bunch of stuff in /usr/local (/usr/local/bin/python and /usr/local/lib/ > python2.5 etc), which I have happily been using for development for a > year. I had thought that the two pythons were completely independent. > > Well, I was wrong. When /usr/bin/python2.5 runs, *by default*, it > adds /usr/local/lib/python2.5 to its sys path - and apparently there > are things in /usr/local which are inconsistent with those at /usr > (not suprising). > > I have fixed the problem - but I had to modify the actual update- > manager .py file itself. At the beginning, I set the sys.path in > python *explicitly* to not include the /usr/local stuff. > > But this is clearly a kludge. My question: how do I keep the Ubuntu > python stuff at /usr/bin/python2.5 from adding /usr/local/lib/ > python2.5 to the import search path in a clean and global way? I > really want both pythons completely isolated from one another! > > Thankyou. When you install a second version, let us say Python3.0, you want to download the source and do the normal config and make but not make install. Instead do a make altinstall. They will be kept separate. I have Ubuntu's 2.5 as well as 3.0. Ubuntu installs to /usr/bin and / usr/lib, so I installed 3.0 from /usr/local/Python-3.0 and those files installed into /usr/local/bin and lib and the executable is python3.0. Take a look at the README file that comes with the source code for other options. From jeffober at gmail.com Tue Jul 22 08:44:56 2008 From: jeffober at gmail.com (Jeff) Date: Tue, 22 Jul 2008 05:44:56 -0700 (PDT) Subject: simple question about dictionaries References: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> <8aedc744-f432-4a4a-a6e4-2bb714caf720@x35g2000hsb.googlegroups.com> Message-ID: On Jul 21, 8:14?am, Fredrik Lundh wrote: > Jeff wrote: > > ? throw KeyError('%s not found' % str(val)) > > "throw"? ?and shouldn't that be a ValueError? ;-) > > Whoops. Been working in too many different languages at the same time :). From cheappuma at 126.com Fri Jul 18 20:46:47 2008 From: cheappuma at 126.com (128) Date: Fri, 18 Jul 2008 17:46:47 -0700 (PDT) Subject: paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) Message-ID: paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) From ldo at geek-central.gen.new_zealand Thu Jul 24 05:56:02 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 24 Jul 2008 21:56:02 +1200 Subject: scanf in python References: <4884be5e$0$19722$426a74cc@news.free.fr> <6ek4cgF7hq4vU1@mid.uni-berlin.de> <4884e77a$0$29405$426a74cc@news.free.fr> Message-ID: In message <4884e77a$0$29405$426a74cc at news.free.fr>, AMD wrote: > Actually it is quite common, it is used for processing of files not for > reading parameters. You can use it whenever you need to read a simple > csv file or fixed format file which contains many lines with several > fields per line. I do that all the time, in Python and C++, but I've never felt the need for a scanf-type function. For reading delimited fields in Python, you can use .split string method. From deets at nospam.web.de Wed Jul 2 16:04:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Jul 2008 22:04:00 +0200 Subject: detection of unplugged cable In-Reply-To: References: Message-ID: <6d259gFfevuU1@mid.uni-berlin.de> Oguz Yarimtepe schrieb: > Hi, > > I am tring to develeop a gui with pyqt. I need to detect whether the > the cable to vga, dmi or s-video outputs are plugged or unplugged. > After detection i need to run a process. How can i do this? Not with python as is. This is OS-specific, and you should see what your OS supports regarding DDC support & how much of that is exposed to the user. And it might not be to reliable. You are not *forced* to use a DDC monitor. Diez From robert.rawlins at thinkbluemedia.co.uk Tue Jul 15 07:32:06 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 15 Jul 2008 12:32:06 +0100 Subject: Logging in __del__() Message-ID: <013601c8e66e$69a4faf0$3ceef0d0$@rawlins@thinkbluemedia.co.uk> Guys, I'm trying to help trace when instances of particular classes are being destroyed by the garbage collector and thought the cleanest way would be to implement a logging call in __del__() on the class. However, I'm having an issue. I inject a logger instance into my class upon construction and set it to self.logger, I then use this within the class to log actions going on within, works fine. Now, when I make the call in the __del__() method like so: def __del__(self): # Log the classes destruction. self.logger.debug("Class Instance Destroyed") I then get the following exception thrown when running my code: Traceback (most recent call last): File "/usr/lib/python2.5/logging/handlers.py", line 73, in emit if self.shouldRollover(record): File "/usr/lib/python2.5/logging/handlers.py", line 147, in shouldRollover self.stream.seek(0, 2) #due to non-posix-compliant Windows feature ValueError: I/O operation on closed file Does anyone have any ideas as to what I'm doing wrong here? Is this a known issue which has a neat little work around? Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From kanchana.senevirathna at gmail.com Wed Jul 23 01:33:10 2008 From: kanchana.senevirathna at gmail.com (Kanch) Date: Tue, 22 Jul 2008 22:33:10 -0700 (PDT) Subject: xpathEval fails for large files References: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> <48864b0d$0$9494$9b4e6d93@newsspool3.arcor-online.net> Message-ID: On Jul 23, 2:03 am, Stefan Behnel wrote: > Fredrik Lundh wrote: > > Kanchana wrote: > > >> I tried to extract some data with xpathEval. Path contain more than > >> 100,000 elements. > > >> doc = libxml2.parseFile("test.xml") > >> ctxt = doc.xpathNewContext() > >> result = ctxt.xpathEval('//src_ref/@editions') > >> doc.freeDoc() > >> ctxt.xpathFreeContext() > > >> this will stuck in following line and will result in high usage of > >> CPU. > >> result = ctxt.xpathEval('//src_ref/@editions') > > >> Any suggestions to resolve this. > > > what happens if you just search for "//src_ref"? what happens if you > > use libxml's command line tools to do the same search? > > >> Is there any better alternative to handle large documents? > > > the raw libxml2 API is pretty hopeless; there's a much nicer binding > > called lxml: > > > http://codespeak.net/lxml/ > > > but that won't help if the problem is with libxml2 itself, though > > It may still help a bit as lxml's setup of libxml2 is pretty memory friendly > and hand-tuned in a lot of places. But it's definitely worth trying with both > cElementTree and lxml to see what works better for you. Depending on your > data, this may be fastest in lxml 2.1: > > doc = lxml.etree.parse("test.xml") > for el in doc.iter("src_ref"): > attrval = el.get("editions") > if attrval is not None: > # do something > > Stefan Original file was 18MB, and contained 288328 element attributes for the particular path. I wonder whether for loop will cause a problem in iterating for 288328 times. From dobedani at gmx.net Tue Jul 15 11:30:19 2008 From: dobedani at gmx.net (Dobedani) Date: Tue, 15 Jul 2008 08:30:19 -0700 (PDT) Subject: Invoking non-static methods of a non-Python object instance Message-ID: <0dc2b4f4-a918-49bb-a793-f0a4fd144286@27g2000hsf.googlegroups.com> Dear All, For some time now, I have been working with the ctypes module on Windows. First I got my hands on a library developed with Delphi 7. That library is exporting plain functions. Internally, reference is made to the instance of a class, which is instantiated in a kind of initialization section. Everything works fine. Now, I have developed a library in C#. I am able to get the result from static methods, e.g. public static String sayHello() { String msg = "Hello from MyLib, working in folder "; return msg + Directory.GetCurrentDirectory(); } To make sure that the libray can work as a Win32 library, I have added a V-Table by disassembling and then editing the IL code then compiling again, see: http://www.blong.com/Articles/DotNetInteropD8/Interop1/Win32AndDotNetInterop.htm However, in my code I am actually exporting the methods of a class and I added non-static methods - unlike what was the case with the DLL developed in Delphi. Unfortunately, it appears impossible to keep a reference to an instance of my class in the Python code. Suppose, I remove the keyword "static" from the above method declaration, this fails whatever I try: from ctypes import *; mylib = windll.LoadLibrary("MyLib"); mylib.getInstance.restype = ? myInst = mylib.getInstance(); print myInst.sayHello(); Is there a way to do this? FYI: I don't want to work with win32client, because this will require that my users install an extra extension and I am expected to deliver something which can work without such extra extensions. I look forward to your ideas! Kind regards, Dobedani From greg at cosc.canterbury.ac.nz Tue Jul 29 00:29:53 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 29 Jul 2008 16:29:53 +1200 Subject: Rant (was Re: x*x if x>10 In-Reply-To: <6f48ehF9p9bkU1@mid.uni-berlin.de> References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3qjoF9n3cpU1@mid.uni-berlin.de> <6f48ehF9p9bkU1@mid.uni-berlin.de> Message-ID: <6f7l2nFa9d5lU1@mid.individual.net> Diez B. Roggisch wrote: > I maybe should paraphrase "don't return objects you passed as arguments > from a function". The important thing is that a function shouldn't modify any object unless it's the express purpose of the function to do so. You could call this the "look but don't touch" rule. -- Greg From naude.jaco at gmail.com Wed Jul 23 03:45:23 2008 From: naude.jaco at gmail.com (Jaco Naude) Date: Wed, 23 Jul 2008 00:45:23 -0700 (PDT) Subject: Undefined calling conventions in Python.h Message-ID: Hi there, This is my first post over here and I hope someone can give me some guidance. I'm trying to embed Python into a Visual C++ 2008 application and I'm getting linker problems. I've compiled a DLL of the Python source code using the pythoncode VC++ project in the PCbuild folder of the source download and this works 100% without any warnings etc. I've done this in Debug and Release mode without any problems. When I include python_install_path\include\Python.h in my application (with the linking setup correctly to the .lib and .dll files generated by myself) it builds fine. However as soon as I try to call any Python function (Py_Exit for example) I get linker errors as shown below: 1>application.obj : error LNK2031: unable to generate p/invoke for "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@$$J0YMXH at Z); calling convention missing in metadata 1>frmPythonInterface.obj : error LNK2031: unable to generate p/invoke for "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@$$J0YMXH at Z); calling convention missing in metadata I'm probably missing something but I can't find any calling convention details in Python.h or the other headers included in this file. In my VC++ DLL project I've specified the calling convention as __stdcall. I know the __clrcall naming convention has to do with managed code in VC+ + but thats as far as my knowledge on that goes. Should I define the calling conventions manually? Or is there a setting wrong somewhere in my application project? If anybody can give some guidance it would be greatly appreciated. Thanks Jaco From hat at se-162.se.wtb.tue.nl Mon Jul 7 10:18:23 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 07 Jul 2008 16:18:23 +0200 Subject: I am looking for svn library(module) References: <6e1097a0-2a99-4885-a1ef-0684af5aa6a1@d1g2000hsg.googlegroups.com> Message-ID: On 2008-07-07, sniipe at gmail.com wrote: > Hi, > > I am looking fo svn library(module) which is used in the svn- > mailer(http://opensource.perlig.de/svnmailer/) project. Does anybody > know where can I find it(download url)? This is information which I > received from python error: > > from svn import core as svn_core > ImportError: No module named svn The module is called 'pysvn', available at tigris.org. They use it in their work-branch program. From hyugaricdeau at gmail.com Wed Jul 30 10:10:34 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Wed, 30 Jul 2008 07:10:34 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <2da5350e-d74e-4760-b9b8-7cc9869dc607@n33g2000pri.googlegroups.com> Message-ID: On Jul 30, 3:53?am, "Russ P." wrote: > Fair enough. I have no dog in this particular fight. I just think it > wouldn't hurt to add an "isempty()" or "isnonempty()" method to the > list type, and let people use it if they wish, or continue using "if > x" if that's what they prefer. Go right on ahead. You could implement it like this: class superenhancedlist(list): def isempty(self): return not self >>> a = superenhancedlist() >>> a.isempty() True >>> a.append(1) >>> a.isempty() False Amazingly useful! Go ahead and use that in all your code. Anyone else who comes along and looks at it or tries to maintain it will really love you for it. From circularfunc at gmail.com Thu Jul 10 09:15:49 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 10 Jul 2008 06:15:49 -0700 (PDT) Subject: TypeError, I know why but not how!? References: <03cbb0d2-6a0c-4b86-a75e-b73c5677acc7@c65g2000hsa.googlegroups.com> Message-ID: I don't fully understand why I have to do this. On Jul 10, 4:17?am, Robert Kern wrote: > ssecorp wrote: > > Im looking into PvsNP: > >http://www.claymath.org/millennium/P_vs_NP/ > > so I thought I'd write the program just to get a feel for it. > > > But I run into a problem. Why does it all the sudden return None? I > > mean I know why the program aborts but I dont understand why the None > > is generated all the sudden. Hitting recursion depth isn't reported > > with that error. > > def validate(placed): > ? ? ?student = round(random.random()*401) > ? ? ?if student in placed: > ? ? ? ? ?# You need to explicitly return, here: > ? ? ? ? ?return validate(placed) > ? ? ?else: > ? ? ? ? ?placed.append(student) > ? ? ? ? ?return student, placed > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > ? that is made terrible by our own mad attempt to interpret it as though it had > ? an underlying truth." > ? ?-- Umberto Eco From Lie.1296 at gmail.com Mon Jul 21 15:32:00 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 21 Jul 2008 12:32:00 -0700 (PDT) Subject: Change PC to Win or Windows References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> Message-ID: <82873ccd-9667-4dfa-9ec4-a9ac7c672aa7@w1g2000prk.googlegroups.com> > It very much IS the point. Language evolves based on common usage > patterns of the people who use it. That is inarguably correct. > The term "PC" is commonly used in English, in the United States > and other English speaking countries, to mean a computer running > Microsoft Windows. As far as I am aware, they're like that because most people aren't even aware that there are other OSes than Microsoft Windows. If the world is still back in the 80s or 90s when people that use computers means they're knowledgeable enough about computer, PCs would be either applied to "all kinds of small computer/microcomputer" or only to "IBM- branded microcomputers", the latter because PC is originally IBM's marketing term, the former is a natural expansion of the meaning since "Personal Computer" is a neutral term, unlike marketing terms like: "TravelMate", "Lifebook", "MacBook", "GeForce", etc. "Personal Computer" is more like the term "Mobile Phone" which is brand-neutral and is usable by any brand, regardless of how the term originated. The reason why the world hasn't evolved to the two predictable cases ("all kinds of microcomputers" or "IBM-PC and clones"), is what I'll explain below. > That's a simple fact that you can not escape, no matter how > much you may not like it (it just so happens that I also don't l > ike it, but I realized long ago the futility of arguing against > its usage). It's still a fact, and I described roughly how > that fact came to be. > It wasn't something that Apple started; it's been used this way > in increasingly common usage for at least 20 years, although > exactly what combination of hardware and software was being > refered to as a "PC" has evolved over that timeframe. Apple popularizes the term by explicit marketing, but the real blame is to Microsoft's dominance, though it is without their explicit consent, blessing, or resistance. Not entirely Microsoft's fault for being dominant, but their dominance in the lower level users makes those lower level user unaware of other OSes and applied the term PC to Windows-based computers. When other OSes are gaining popularity again (i.e. when Microsoft starts to lose its total and complete dominance, i.e. around right now) the term's meaning become a huge matter because people associated the term with Microsoft Windows (i.e. software), not with IBM-PC and its clones anymore (i.e. hardware). On Jul 21, 11:50?pm, Derek Martin wrote: > On Sat, Jul 19, 2008 at 02:56:07AM -0700, Lie wrote: > > government, etc. IBM PC is one of the first computers that ordinary > > people could possess, when IBM-clones appeared on the market, they're > > referred as PCs too because they are Personal Computer, a computer > > that is designed for personal use. > > Just to be clear, this statement is WRONG. ?PC-clones were so called > because they were clones of the IBM-PC. ?The term is very specific to > IBM-compatible hardware. ? > > ?http://en.wikipedia.org/wiki/Pc_clone > > ? ? IBM PC compatible computers are those generally similar to the > ? ? original IBM PC, XT, and AT. Such computers used to be referred to > ? ? as PC clones, or IBM clones since they almost exactly duplicated > ? ? all the significant features of the PC, XT, or AT internal design, > ? ? facilitated by various manufacturers' ability to legally reverse > ? ? engineer the BIOS through cleanroom design. > > Wikipedia's article on the personal computer accurately reflects > the multiple meanings of the term, and points out the common usage > to mean a Windows box: > > ?http://en.wikipedia.org/wiki/Personal_computer > > ? ? Today a PC may be a desktop computer, a laptop computer or a > ? ? tablet computer. The most common operating systems are Microsoft > ? ? Windows, Mac OS X and Linux, while the most common microprocessors > ? ? are x86 compatible CPUs. ?However, the term "PC" is often used > ? ? only to refer to computers running Microsoft Windows. > > So please stop your whining and get used to the idea that THE REST OF > THE WORLD uses PC to mean a Windows box. The rest of the world? Not in this part of the world, not in my whole country at the least... From coolman.guron at gmail.com Tue Jul 29 09:51:26 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Tue, 29 Jul 2008 06:51:26 -0700 (PDT) Subject: pygtk treview, ListStore not displaying properly Message-ID: <5cd417cf-4169-4805-8317-fb82c7e7be90@x29g2000prd.googlegroups.com> hi group i am running into a problem with gtk. i have a treeview that just displays tabular data (no down arrows or trees etc). it has 5 columns. The tiny problem i am having is that it is just display the data of the column named `title` in all the colums! here the pic of the app in action http://i36.tinypic.com/2djcqqr.png the related code of the app is as follows: self.tv = self.glade.get_widget('treeview1') #the treeview object def show_sync_wind(self,obj, data = None): t = Template.select(Template.q.synced == '0') self.synclstore = gtk.ListStore(str,str,str,str,str) x = 0 cr = gtk.CellRendererText() col = gtk.TreeViewColumn('#', cr); col.add_attribute(cr, 'markup', 1) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(0) self.tv.append_column(col) self.sno_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Title', cr); col.add_attribute(cr, 'markup', 1) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(1) self.tv.append_column(col) self.title_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Section', cr); col.add_attribute(cr, 'markup', 1) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(2) self.tv.append_column(col) self.section_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Category', cr); col.add_attribute(cr, 'markup', 1) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(3) self.tv.append_column(col) self.category_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Sync', cr); col.add_attribute(cr, 'markup', 1) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(4) self.tv.append_column(col) self.sync_col = col self.tv.set_model(self.synclstore) self.tv.set_headers_clickable(True) #self.tv.set_expander_column(self.title_col) for y in t: row = self.synclstore.append([str(x),y.title,y.section.name,y.category.name,y.synced]) self.synclstore.set(row,0,'0') self.synclstore.set(row,1,y.title) self.synclstore.set(row,2,y.section.name) self.synclstore.set(row,3,y.category.name) self.synclstore.set(row,4,y.synced) self.sync_window.show() From volcimaster at gmail.com Tue Jul 29 15:45:27 2008 From: volcimaster at gmail.com (Warren Myers) Date: Tue, 29 Jul 2008 15:45:27 -0400 Subject: Python Written in C? In-Reply-To: <5504f9ac0807211105h4604d332y5671243cb34abfc6@mail.gmail.com> References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> <5504f9ac0807211105h4604d332y5671243cb34abfc6@mail.gmail.com> Message-ID: The OO overheads for C++ are almost non-existent. http://www.informit.com/articles/article.aspx?p=1192024&ns=15058 On Mon, Jul 21, 2008 at 2:05 PM, Dan Upton wrote: > On Mon, Jul 21, 2008 at 1:21 PM, Marc 'BlackJack' Rintsch > wrote: >> On Mon, 21 Jul 2008 18:12:54 +0200, mk wrote: >> >>> Seriously, though, would there be any advantage in re-implementing >>> Python in e.g. C++? >>> >>> Not that current implementation is bad, anything but, but if you're not >>> careful, the fact that lists are implemented as C arrays can bite your >>> rear from time to time (it recently bit mine while using lxml). Suppose >>> C++ re-implementation used some other data structure (like linked list, >>> possibly with twists like having an array containing pointers to 1st >>> linked list elements to speed lookups up), which would be a bit slower >>> on average perhaps, but it would behave better re deletion? > > Aside (actual reply below): at least for a sorted LL, you're basically > describing Henriksen's algorithm. They can asymptotically be faster, > based on amortized analysis, but they're somewhat more complicated to > implement. > >> >> An operation that most people avoid because of the penalty of "shifting >> down" all elements after the deleted one. Pythonistas tend to build new >> lists without unwanted elements instead. I can't even remember when I >> deleted something from a list in the past. >> >> Ciao, >> Marc 'BlackJack' Rintsch > > The other side of the equation though is the OO-overhead for C++ > programs as compared to C. (A couple years ago we used an > instrumentation tool to check the instruction count for a simple hello > world program written in C (ie, main(){printf("Hello world!"); return > 0;}) and Python (main(){cout<<"hello world"< instruction count was significantly higher for C++. I expect any sort > of C++ objects you used to implement Python structures will be slower > than the equivalent in C. So even if writing it in C++ would reduce > the overhead for deleting from a list, I expect you would lose a lot > more. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Warren Myers http://warrenmyers.com From ivan at datasyncorp.com Wed Jul 2 13:55:35 2008 From: ivan at datasyncorp.com (Ivan Ven Osdel) Date: Wed, 2 Jul 2008 12:55:35 -0500 (CDT) Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: <1777569623.855701215020919496.JavaMail.root@saturn.datasyncintra.net> Message-ID: <145286708.856441215021335297.JavaMail.root@saturn.datasyncintra.net> The free Python editors/IDEs really do need work as far as code completion goes but I am hopeful. IMO Stani's Python Editor comes closest by providing some code sense through a combination of history and doc strings for Python built-ins. Where it falls short is the ability to scan doc strings for your own code and non built-in modules in the Python path. Python already has the ground work in place to accomplish something similar to VS's XML commenting/intellisense system. With a Python interpretor you can type help(myModule) and get the doc string documentation. So I imagine implementing code sense for code being developed as well as non built-in modules would just be a matter of finding the appropriate module at the right time and piping the output of help([module]) to a popup window. If your willing to help work on something like that I suggest contacting Stani directly http://pythonide.stani.be/ or creating a plugin for Geany http://geany.uvena.de/ Ivan Ven Osdel Software Engineer http://www.datasyncsuite.com/ ----- Original Message ----- From: "Ali Servet D?nmez" To: python-list at python.org Sent: Wednesday, July 2, 2008 3:33:59 AM GMT -06:00 US/Canada Central Subject: Re: Freesoftware for auto/intelligent code completing in Python On Jul 1, 12:15?am, Fuzzyman wrote: > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > > I don't want to be so mean here, but how hard it could be be writing a > > freesoftware which would automatically/intelligently auto complete > > Python code? (I mean something that really does the job, like > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > name it, but just don't give me PyDev please...) > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > even a brand new huge all-fancy IDE, I don't care, but what am I > > missing here? > > > Could someone please point me out something that I'm really missing > > which is already present in the wild, otherwise I'd like discuss with > > whoever is willing to help me to get this thing done. I made my mind > > and I could volunteer to make this happen as thesis project for my > > incoming graduation in the next year. > > > Regards you all, > > Ali Servet D?nmez > > Vim, Emacs, Wing, Komodo, ... more? > > Yeah, I guess you're missing something. :-) > > Michael Foordhttp://www.ironpythoninaction.com/http://www.trypython.org/ I've checkout Wing IDE's license and it doesnt' seem to be a freesoftware; am I wrong? From bdesth.quelquechose at free.quelquepart.fr Mon Jul 28 15:08:26 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Jul 2008 21:08:26 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> Message-ID: <488e3520$0$16766$426a74cc@news.free.fr> Russ P. a ?crit : > On Jul 28, 4:23 am, Bruno Desthuilliers > wrote: >> Russ P. a ?crit : (snip) >>> A bonus is that it becomes >>> clearer at the point of usage that ".data" is member data rather than >>> a local variable. >> I totally disagree. The dot character is less obvious than the 'self.' >> sequence, so your proposition is bad at least wrt/ readability (it's >> IMHO bad for other reasons too but I won't continue beating that poor >> dead horse...) > > Man, you are one dense dude! Can I give you a bit of personal advice? > I suggest you quit advertising your denseness in public. Thanks. > Letting "self" (or whatever the first argument was) be implied in > ".cat" does absolutely *NOTHING* to change the internal workings of > the Python interpreter. You probably have a way better knowledge of Python's compiler and interpreter than I do to assert such a thing. But if it's so easy, please provide a working patch. > It's a very simple idea that you insist on > making complicated. As I said, I could write a pre-processor myself to > implement it in less than a day. Preprocessor are not a solution. Sorry. > As for "dot" being less obvious than "self.", no kidding? Nope. I'm deadly serious. (snip no-op argument and name-calling). > Your posts here are typical. I'm trying to make a suggestion to reduce > the clutter in Python code, s/the clutter/what Russ P. decided to consider as clutter/ > and you throw tomatoes mindlessly. Oh, you don't stand people disagreing with you, that's it ? > You seem to think that being a "regular" on this newsgroup somehow > gives you special status. Why so ? Because I answer to your proposition and not agree with your arguments ??? C'mon, be serious, you have the right to post your proposition here, I have the right to post my reaction to your proposition, period. Grow up, boy. > I sure wish I had one tenth the time to > spend here that you have. But even if I did, I have far more important > work to do than to "hang out" on comp.lang.python all day every day. > Man, what a waste of a life. Well, I guess it keeps you off the > streets at least. Boy, I don't know who you think you're talking to, but you're obviously out of luck here. I'm 41, married, our son is now a teenager, I have an happy social life, quite a lot of work, and no time to waste in the streets. And FWIW, name-calling won't buy you much here. From noagbodjivictor at gmail.com Tue Jul 1 17:44:27 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Tue, 1 Jul 2008 17:44:27 -0400 Subject: How to make a function associated with a class? Message-ID: > > Hi, > > I have a class called "vector". And I would like to define a function > "dot" which would return a dot product of any two "vectors". I want > to call this function as follow: dot(x,y). > > Well, I can define a functions "dot" outside the class and it works > exactly as I want. However, the problem is that this function is not > associated with the class (like methods a method of the class). > > For example, if I call "x.calc()" or "y.calc()", python will execute > different methods if "x" and "y" belongs to different classes. I want > to have the same with my "dot" function. I.e. I want it calculates the > dot product ONLY IF the both arguments of that function belong to the > "vector" class. > > Is it possible? > > Thank you in advance. > > Do you think a static method will do the thing? > Well you can define the function inside the class. Then create a name outside the class that references it. Is is. dot = Class.dot. By the way, why do you want to tie this function to the class? -- NOAGBODJI Paul Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Jul 1 15:46:45 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 01 Jul 2008 15:46:45 -0400 Subject: convert unicode characters to visibly similar ascii characters In-Reply-To: References: Message-ID: Peter Bulychev wrote: > Hello. > > I want to convert unicode character into ascii one. > The method ".encode('ASCII') " can convert only those unicode > characters, which fit into 0..128 range. > > But there are still lots of characters beyond this range, which can be > manually converted to some visibly similar ascii characters. For > instance, there are several quotation marks in unicode, which can be > converted into ascii quotation mark. > > Can this conversion be performed in automatic manner? After googling > I've only found that there exists Unicode database, which stores > human-readable information on notation of all unicode characters > (ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt). And there also > exists the Python adapter for this database > (http://docs.python.org/lib/module-unicodedata.html). Using this > database I can do something like `if > notation.find('QUOTATION')!=-1:\n\treturn "'"`. I believe there is more > elegant way. Am I right? I believe you will have to make up your own translation dictionary for the translations *you* want. You should then be able to use that with the .translate() method. tjr From mensanator at aol.com Thu Jul 31 17:23:13 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 31 Jul 2008 14:23:13 -0700 (PDT) Subject: find and replace with regular expressions References: <91a5aec2-9c70-41c7-a1b2-d8e8c4ed9578@2g2000hsn.googlegroups.com> Message-ID: <8a16bb81-9a7a-43d6-98b8-42c2b791fdd2@27g2000hsf.googlegroups.com> On Jul 31, 3:56?pm, Mensanator wrote: > On Jul 31, 3:07?pm, chrispoliq... at gmail.com wrote: > > > > > > > I am using regular expressions to search a string (always full > > sentences, maybe more than one sentence) for common abbreviations and > > remove the periods. ?I need to break the string into different > > sentences but split('.') doesn't solve the whole problem because of > > possible periods in the middle of a sentence. > > > So I have... > > > ---------------- > > > import re > > > middle_abbr = re.compile('[A-Za-z0-9]\.[A-Za-z0-9]\.') > > > # this will find abbreviations like e.g. or i.e. in the middle of a > > sentence. > > # then I want to remove the periods. > > > ---------------- > > > I want to keep the ie or eg but just take out the periods. ?Any > > ideas? ?Of course newString = middle_abbr.sub('',txt) where txt is the > > string will take out the entire abbreviation with the alphanumeric > > characters included. > >>> middle_abbr = re.compile('[A-Za-z0-9]\.[A-Za-z0-9]\.') > >>> s = 'A test, i.e., an example.' > >>> a = middle_abbr.search(s) ? ? ?# find the abbreviation > >>> b = re.compile('\.') ? ? ? ? ? # period pattern > >>> c = b.sub('',a.group(0)) ? ? ? # remove periods from abbreviation > >>> d = middle_abbr.sub(c,s) ? ? ? # substitute new abbr for old > >>> d > > 'A test, ie, an example.' A more versatile version: import re middle_abbr = re.compile('[A-Za-z0-9]\.[A-Za-z0-9]\.') s = 'A test, i.e., an example.' a = middle_abbr.search(s) # find the abbreviation b = re.compile('\.') # period pattern c = b.sub('',a.group(0)) # remove periods from abbreviation d = middle_abbr.sub(c,s) # substitute new abbr for old print d print print s = """A test, i.e., an example. Yet another test, i.e., example with 2 abbr.""" a = middle_abbr.search(s) # find the abbreviation c = b.sub('',a.group(0)) # remove periods from abbreviation d = middle_abbr.sub(c,s) # substitute new abbr for old print d print print s = """A test, i.e., an example. Yet another test, i.e., example with 2 abbr. A multi-test, e.g., one with different abbr.""" done = False while not done: a = middle_abbr.search(s) # find the abbreviation if a: c = b.sub('',a.group(0)) # remove periods from abbreviation s = middle_abbr.sub(c,s,1) # substitute new abbr for old ONCE else: # repeat until all removed done = True print s ## A test, ie, an example. ## ## ## A test, ie, an example. ## Yet another test, ie, example with 2 abbr.' ## ## ## A test, ie, an example. ## Yet another test, ie, example with 2 abbr. ## A multi-test, eg, one with different abbr. From haraldarminmassa at gmail.com Tue Jul 22 08:56:06 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Tue, 22 Jul 2008 05:56:06 -0700 (PDT) Subject: is it possible to add a property to an instance? References: Message-ID: <2dda482a-d15c-4f8d-9fca-3bfffe9e4fa1@f63g2000hsf.googlegroups.com> > Does anyone know if it is possible to add a property to an instance at > runtime? I didn't see anything about it in the standard library's new > module, google hasn't turned up much either. yes. You need nothing special, just add it: class fish(object): pass a=fish() a.legs=4 print a.legs (or print (a.legs) on Python 3.0 and above) so you add a property to an instance and proove that Darwin was right in one go. Harald From tcfg at sina.com Thu Jul 24 08:27:14 2008 From: tcfg at sina.com (fang) Date: Thu, 24 Jul 2008 05:27:14 -0700 (PDT) Subject: how to cut and paste in the windows of python(command line) References: <9500663c-0985-4dfd-8d0a-ae25411f00e5@v39g2000pro.googlegroups.com> Message-ID: <8488675c-1815-4b3a-8299-6fe06e030b05@i20g2000prf.googlegroups.com> Dear: Thank you very much! I can do it! It's very nice! From larry.bates at websafe.com` Mon Jul 14 00:27:11 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 13 Jul 2008 23:27:11 -0500 Subject: while var, but var ==16 != true In-Reply-To: <8c2cd9ff-bec2-4844-82a8-8ce02df5663e@w7g2000hsa.googlegroups.com> References: <8c2cd9ff-bec2-4844-82a8-8ce02df5663e@w7g2000hsa.googlegroups.com> Message-ID: maestro wrote: > why does this work? "while p" = "while p != 0" ? 1 is True and 0 is > false in python but other numbers have no boolean value so why doesnt > it abort. > > > >>>> p=16 >>>> p > 16 >>>> while p: > print p > p -= 1 > > > 16 > 15 > 14 > 13 > 12 > 11 > 10 > 9 > 8 > 7 > 6 > 5 > 4 > 3 > 2 > 1 > > > i can also do: > >>>> k=[] >>>> while k: > k.pop() > > >>>> k=[1,2,3] >>>> while k: > k.pop() > > > 3 > 2 > 1 > > > so obv while var means while not empty or why not zero but it isnt > something youd guess unless youd beeen shown it. Python manuals outline that 0, None, empty list, empty dictionary are False anything else evaluates to True. This is all over this list as well. -Larry From fetchinson at googlemail.com Thu Jul 10 01:46:07 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 9 Jul 2008 22:46:07 -0700 Subject: python scalability In-Reply-To: <487598C3.9080306@vapourforge.com> References: <487590E6.7020004@gmail.com> <487598C3.9080306@vapourforge.com> Message-ID: >> I work on a desktop application that has been developed using python >> and GTK (see www.leapfrog3d.com). We have around 150k lines of python >> code (and 200k+ lines of C). We also have a new project manager with >> a C# background who has deep concerns about the scalability of python >> as our code base continues to grow and we are looking at introducing >> more products. I am looking for examples of other people like us (who >> write desktop apps in python) with code bases of a similar size who I >> can point to (and even better talk to) to help convince him that >> python is scalable to 300+ lines of code and beyond. I have looked at >> the python success stories page and haven't come up with anyone quite >> like us. One of my project managers questions is: "Are we the only >> company in the world with this kind and size of project?" >> I want to say no, but am having trouble convincing myself, let alone him. >> >> If you are involved in this kind of thing please get in touch with me. If python is suitable for large projects with over 300k lines of code but not in the desktop app scene but web apps then probably it is also suitable for desktop apps. You can probably convince your manager that the previous statement is true. Once that is done you can point to youtube and google who are heavy python users without scalability issues. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From karthikbalaguru79 at gmail.com Wed Jul 23 12:24:13 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Wed, 23 Jul 2008 09:24:13 -0700 (PDT) Subject: Strange problem .... References: <12fd8ef1-c7e0-470b-ba51-f946d8ea8e26@z6g2000pre.googlegroups.com> Message-ID: On Jul 23, 1:31 pm, "Simon Brunning" wrote: > 2008/7/23 karthikbalaguru : > > > I use Redhat 9.0, python-2.2.2-26, python-devel-2.2.2-26 and > > db4-4.0.14-20. > > > File "/usr/local/SDK/bin/../core/bin/processorlib.py", line 88 > > yield ProcessorObjectInfo(child, self.pt) > > ^ > > SyntaxError: invalid syntax > > > Is this error related with the version of python / python-devel that i > > use . > > Any ideas / tips ? > > Yup - generators (and hence the yield statement) were first introduced > in Python 2.2, but in order to maintain backward compatibility, you'll > need this line in any module using them: > > from __future__ import generators > > As of Python 2.3, this is no longer necessary, and I'd imagine that > whatever you are running was targeted at a post 2.2 release. > Your answers helped me to solve the problem. I found some while loop inside def children(def). I initially tried by putting 'from __future__ import generators' just before the def children(self): present inside the class definition of 'DebugProcessorInfo'. But it did not work. Later i placed the 'from __future__ import generators' at the beginning of the python file and it worked sucessfully. Thx for that info. Karthik Balaguru From deets at nospam.web.de Wed Jul 9 09:00:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Jul 2008 15:00:57 +0200 Subject: Newbie question References: <3b1e6f480807082337l419fd40ax91eaf13e0701c5b3@mail.gmail.com> Message-ID: <6djr5pF2rqi0U1@mid.uni-berlin.de> |e0 wrote: > I did not mean to use WMI on linux, but query win machines *from* linux. What do you mean by "query"? Using the WMI module? No. It's Windows only. Diez From bronger at physik.rwth-aachen.de Thu Jul 24 13:34:15 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 24 Jul 2008 19:34:15 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> Message-ID: <87sktz425k.fsf@physik.rwth-aachen.de> Hall?chen! Sebastian \"lunar\" Wiesner writes: > Torsten Bronger : > >> Bruno Desthuilliers writes: >> >>> Torsten Bronger a ?crit : >>> >>>> Bruno Desthuilliers writes: >>>> >>>> [...] >>>> >>>> Just like this. However, the compiler could add "self" to >>>> non-decorated methods which are defined within "class". >>> >>> What's defined within classes are plain functions. It's actually >>> the lookup mechanism that wraps them into methods (and manage to >>> insert the current instance as first argument). >> >> And why does this make the implicit insertion of "self" >> difficult? I could easily write a preprocessor which does it >> after all. > > Who said, that it would be "difficult"? He just corrected your > statement about definitions inside a class, and did not make any > assumption about making "self" implicit. If it is not the implementation, I don't see why the "definition inside a class" matters at all. It can be realised as a transformation of the syntax tree and would even be transparent for the compiling steps after it. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From circularfunc at gmail.com Thu Jul 10 07:21:58 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 10 Jul 2008 04:21:58 -0700 (PDT) Subject: TypeError, I know why but not how!? References: <03cbb0d2-6a0c-4b86-a75e-b73c5677acc7@c65g2000hsa.googlegroups.com> Message-ID: <90eefcec-1a6c-46f1-9d13-eab7f3ed4075@l64g2000hse.googlegroups.com> ty I came to the same conckusion in bed :) now it works. however since there are 400 students and some are incompatible I shouldnt be able to generate a 200room list right? but it works sometimes the other times i get an error. might be because of recursion depth i never let the error finish. i saw i also generate student 0 which shouldnt exist. and the actual problem is generating all possible combinations right? i mean i can easily generate one list that is made randomly so problem solved. why does one need to generate all possible lists? i guess there are other problems where that might be needed so is this just a bad example or am i missing something? From steve at REMOVE-THIS-cybersource.com.au Tue Jul 29 19:31:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 23:31:21 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> Message-ID: <009fa3c2$0$20313$c3e8da3@news.astraweb.com> On Tue, 29 Jul 2008 10:42:50 -0700, Carl Banks wrote: > On Jul 29, 11:12 am, Matthew Fitzgibbons wrote: ... >> My use case involves a DAG of filters that pass data (of a variety of >> types--filters just pass on data types they don't understand) between >> them. I can also drop out of the filter chain at any point, using >> critera determined by the filters. These criteria, you guessed it, are >> bound to __nonzero__ in the filter and I determine whether or not to >> continue through the graph using "if x". You can't code explicit tests >> if you don't know what the tests even are beforehand. Also, I wanted to >> support builtins (ints and lists in particular) because they can be >> meaningful inputs to filters. Finally, as I add more filters and data >> types, I don't want to go back and mess with the code that decides >> whether or not to break out of the graph. > > Much like in Steven D'Aprano's example, still the only actual code > snippet I've seen, it seems that this can easily be done with a simple > explicit test by having all no-advance filters return None and testing > with "if x is not None". Yet again you ignore the actual functional requirements of the code, and made vague claims that if we change the function to another function that behaves differently, we can replace our simple code with your more complex code, and it (probably) won't break. Even if we could redesign the functional requirements of the code, why on earth would we want to? -- Steven From gagsl-py2 at yahoo.com.ar Fri Jul 11 05:29:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Jul 2008 06:29:15 -0300 Subject: Basic Question about Python WebServer File handling References: Message-ID: En Thu, 10 Jul 2008 22:20:21 -0300, Alok Kumar escribi?: > I need to have a python webserver which can handle Get request from the > clients and upload the *files* from 4 different directories. > > Can someone please point me what to exactly look for. Look at SimpleHTTPServer.py in the standard library - either use it as it is or subclass SimpleHTTPRequestHandler to suit your needs. -- Gabriel Genellina From timothywayne.cook at gmail.com Wed Jul 9 06:57:19 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Wed, 09 Jul 2008 07:57:19 -0300 Subject: start reading from certain line In-Reply-To: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> Message-ID: <1215601039.2873.972.camel@localhost.localdomain> On Wed, 2008-07-09 at 03:30 -0700, antar2 wrote: > I am a starter in python and would like to write a program that reads > lines starting with a line that contains a certain word. > For example the program starts reading the program when a line is > encountered that contains 'item 1' > > > The weather is nice > Item 1 > We will go to the seaside > ... > > Only the lines coming after Item 1 should be read file=open(filename) while True: line=file.readline() if not line: break if 'Item 1' in line: print line HTH, Tim -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. Home page: https://launchpad.net/oship/ Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From origami.takarana at gmail.com Sun Jul 20 22:48:59 2008 From: origami.takarana at gmail.com (origami.takarana at gmail.com) Date: Sun, 20 Jul 2008 19:48:59 -0700 (PDT) Subject: Solutions Fast Track - Monitoring and Intrusion Message-ID: Dear Reader, Designing for Detection ---------------------------- - Get the right equipment from the start. Make sure all of the features you need, or will need, are available from the start. - Know your environment. Identify potential physical barriers and possible sources of interference. - If possible, integrate security monitoring and intrusion detection in your network from its inception. Defensive Monitoring Considerations ------------------------------------------ - Define your wireless network boundaries, and monitor to know if they?re being exceeded. - Limit signal strength to contain your network. - Make a list of all authorized wireless Access Points (APs) in your environment. Knowing what?s there can help you immediately identify rogue APs. Intrusion Detection Strategies ----------------------------------- - Watch for unauthorized traffic on your network. Odd traffic can be a warning sign. - Choose an intrusion detection software that best suits the needs of your environment. Make sure it supports customizable and updateable signatures. - Keep your signature files current.Whether modifying them yourself, or downloading updates from the manufacturer, make sure this step isn?t forgotten. Conducting Vulnerability Assessments ------------------------------------------- - Use tools like NetStumbler and various client software to measure the strength of your 802.11b signal. - Identify weaknesses in your wireless and wired security infrastructure. - Use the findings to know where to fortify your defenses. - Increase monitoring of potential trouble spots. Incident Response and Handling -------------------------------------- - If you already have a standard incident response policy, make updates to it to reflect new potential wireless incidents. - Great incident response policy templates can be found on the Internet. - While updating the policy for wireless activity, take the opportunity to review the policy in its entirety, and make changes where necessary to stay current. An out-of-date incident response policy can be as damaging as not having one at all. Conducting Site Surveys for Rogue Access Points ------------------------------------------------------- - The threat is real, so be prepared. Have a notebook computer handy to use specifically for scanning networks. - Conduct walkthroughs of your premises regularly, even if you don?t have a wireless network. - Keep a list of all authorized APs. Remember, Rogue APs aren?t necessarily only placed by attackers.A well-meaning employee can install APs as well. --- Thank You --- James Conack http://www.centronet.uni.cc From kyosohma at gmail.com Mon Jul 7 09:05:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 7 Jul 2008 06:05:25 -0700 (PDT) Subject: GUI Programming by hand not code with Python Code References: <7003b665-3227-47a7-ab06-1a486f87939a@a1g2000hsb.googlegroups.com> Message-ID: <4b217d2c-a83c-4882-b3fa-ea2253d304bb@25g2000hsx.googlegroups.com> On Jul 6, 9:33?pm, jayjaygi... at hotmail.co.uk wrote: > Is their a program that lets you design a GUI by hand (like gambas) > not by code (like wxpython) but the commands are in python? > > A program similar to gambas or vb > > Gambas with python code instead of gambas code would be perfect. > > Thanks in advance I think Dabo also has a way to do some Visual programming too. And there's also XRC. See the following links for more info: http://dabodev.com/ http://xrced.sourceforge.net/ Mike From bignose+hates-spam at benfinney.id.au Tue Jul 29 09:21:53 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 29 Jul 2008 23:21:53 +1000 Subject: Boolean tests References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <488e4d2d$0$5967$ba624c82@nntp06.dk.telia.net> <009e5e66$0$20313$c3e8da3@news.astraweb.com> <488ee6c9$0$4463$ba624c82@nntp02.dk.telia.net> Message-ID: <87y73kg70u.fsf@benfinney.id.au> "Anders J. Munch" <2007 at jmunch.dk> writes: > Steven D'Aprano wrote: > > I'm sorry Anders, that was a needlessly harsh thing for me to say. > > I apologize for the unpleasant tone. > > > > Still, __nonzero__ is a fundamental part of Python's behaviour. > > You should learn about it. > > Hm, first you apologize, then you repeat the insult? That's no basis > for a conversation. Bye from here. No, he retracted the *insult* and restated the *advice* as a distinct statement. I think it's quite worthwhile to help people see the difference. -- \ ?People are very open-minded about new things, as long as | `\ they're exactly like the old ones.? ?Charles F. Kettering | _o__) | Ben Finney From modelnine at modelnine.org Thu Jul 31 07:38:49 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Thu, 31 Jul 2008 13:38:49 +0200 Subject: How smart is the Python interpreter? In-Reply-To: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> References: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> Message-ID: <200807311338.49915.modelnine@modelnine.org> Am Donnerstag, 31. Juli 2008 13:09:57 schrieb ssecorp: > def str_sort(string): > s = "" > for a in sorted(string): > s+=a > return s > > > if i instead do: > > def str_sort(string): > s = "" > so = sorted(string) > for a in so: > s+=a > return s > > > will that be faster or the interpreter can figure out that it only has > to do sorted(string) once? or that kind of cleverness is usually > reserved for compilers and not interpreters? In a statement of the form for in : the expression will only be evaluated once (to retrieve an iterator), so basically, both ways of stating it are equivalent and make negligible difference in runtime (the second version will be slower, because you have additional code to assign/fetch a local). Anyway, if you care about speed, probably: def str_sort(string): return "".join(sorted(string)) will be the fastest way of stating this. -- Heiko Wundram From sturlamolden at yahoo.no Sat Jul 26 09:11:37 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 26 Jul 2008 06:11:37 -0700 (PDT) Subject: 2d graphics - what module to use? References: <5035d4cb-1976-47d5-8887-4e8381407a7b@m44g2000hsc.googlegroups.com> Message-ID: <70bfa323-5e20-4df4-b93d-b779ce9c5b9e@a1g2000hsb.googlegroups.com> On Jul 26, 6:47?am, Matthew Fitzgibbons wrote: > If you're using wx, there is also wx.lib.plot, which I found to be > _much_ faster than matplotlib in my application, especially when resizing. Yes. Matplotlib creates beautiful graphics, but are terribly slow on large data sets. From alexnbryan at gmail.com Wed Jul 16 16:09:16 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 13:09:16 -0700 (PDT) Subject: py2exe issues with pictures and icons In-Reply-To: References: <18493908.post@talk.nabble.com> Message-ID: <18495626.post@talk.nabble.com> Mike Driscoll wrote: > > On Jul 16, 1:37?pm, Alexnb wrote: >> Hello >> >> I am sure most of you are familiar with py2exe. I am having a bit of a >> problem. See the program has a few pictures involved and the .ico it uses >> for the windows. However, the pictures are stored in the same directory >> as >> the source, something like: C:\Docs and settings\me\My >> docs\python\program. >> When I run the program for the interpreter, just as a .py, everything >> works >> just as it should. However, when I compile the main source as an .exe, >> and >> say let a friend try the program. It fails because it is missing the >> .ico. >> The catch, is I don't want to have it have to installed, at least at this >> point, I want it to be able to just run. So how can I make it just run >> from >> any computer with the files not being in the immediate directory. If that >> is >> not possible, how can I put them in the immediate directory and still >> make >> it work. Because that directory may change a lot so the path will change. >> >> Just a few questions. I hope someone out there can help me out! >> -- >> View this message in >> context:http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp1849390... >> Sent from the Python - python-list mailing list archive at Nabble.com. > > > Put the part of the code that needs the ico file(s) into a try/except > block. You could also try reading the py2exe wiki and tutorials. This > one looks like it has relevant data: > > http://www.py2exe.org/index.cgi/CustomIcons > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > > Well, that may solve the icon problem. But what about getting pictures in there? -- View this message in context: http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp18493908p18495626.html Sent from the Python - python-list mailing list archive at Nabble.com. From cheapkobe at sina.com Fri Jul 18 01:13:28 2008 From: cheapkobe at sina.com (14789) Date: Thu, 17 Jul 2008 22:13:28 -0700 (PDT) Subject: wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal Message-ID: wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal From tjreedy at udel.edu Tue Jul 29 16:00:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 16:00:40 -0400 Subject: Windows Interpreter In-Reply-To: <488F1DB3.4010608@timgolden.me.uk> References: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> <488F1745.4020705@timgolden.me.uk> <4dc0cfea0807290626p4b05376en49ccb18f0e1eb4bb@mail.gmail.com> <488F1DB3.4010608@timgolden.me.uk> Message-ID: Tim Golden wrote: > Victor Subervi wrote: >> def a(): >> chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', >> '\\b', '\\yz'] >> rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is >> like the Beast? Who can wage war against him?\par' >> for char in chars: >> c = '(?<=' + char + ')' >> test = re.search(c, rtf_markup) >> try: >> junk = test.group(0) >> print char >> except: >> pass >> >> Now, I can paste that entire fn in linux. But in windows I have to >> paste it line_by_line. Pain in butt! And it indents automatically. How >> change that behavior. > > Well, I'm not really sure what to say. I've just copied that > whole section with drag-mouse, Ctrl-C. I then opened a new > interpreter window (effectively, Start > Run > python) and > right-clicked over the window. At this point, the lines I > copied were copied in and the function accepted by the > interpreter. > > I do have QuickEdit on by default in all by console windows, > but the only difference I expect that to make is that you'd > otherwise have to use the window's System Menu (Alt-Space, > Edit, Paste). I have to right-click on the title bar (or left-click on the icon on the title bar), select edit and then select paste -- but it does work. I just found the QuickEdit option. While in an administrator account (if Python is installed for all users), bring up the menu as specified above, select Properties instead, then the Options tab, then select QuickEdit on the right. When clicking OK, being admin allows modification of the shortcut and not just the current window. Learn something new every day. Thanks. Terry Jan Reedy From fredrik at pythonware.com Thu Jul 17 05:41:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 11:41:41 +0200 Subject: Getting a unknown word out of a list with no spaces In-Reply-To: <18503830.post@talk.nabble.com> References: <18502758.post@talk.nabble.com> <487EF593.5060505@promsoft.ru> <18503144.post@talk.nabble.com> <487EF7D9.8010400@promsoft.ru> <93164ef9-7079-44db-9ac4-b0a18b0ddf3e@b1g2000hsg.googlegroups.com> <18503830.post@talk.nabble.com> Message-ID: Alexnb wrote: >>>>> "hello"[0] >> 'h' >>>>> "hello"[0] == "<" >> False >>>>> "hello"[0] == "h" >> True >>>>> "hello".startswith("h") >> True > really? That's just like C. I thought that it would fail because of the way > lists work. Thanks! what way? the first three will fail if the string is empty. >>> ""[0] Traceback (most recent call last): File "", line 1, in IndexError: string index out of range if you may end up doing this on an empty string, use slicing instead: >>> "hello"[:1] == "<" False >>> ""[:1] == "<" False (startswith is perhaps more convenient, but method calls are rather expensive in Python, so if you're in a hurry, it's often better to use operators. when in doubt, benchmark the alternatives.) From chrispoliquin at gmail.com Thu Jul 31 16:21:45 2008 From: chrispoliquin at gmail.com (chrispoliquin at gmail.com) Date: Thu, 31 Jul 2008 13:21:45 -0700 (PDT) Subject: Case tagging and python References: Message-ID: I second the idea of just using the islower(), isupper(), and istitle() methods. So, you could have a function - let's call it checkCase() - that returns a string with the tag you want... def checkCase(word): if word.islower(): tag = 'nocap' elif word.isupper(): tag = 'allcaps' elif word.istitle(): tag = 'cap' return tag Then let's take an input file and pass every word through the function... f = open(path:to:file, 'r') corpus_text = f.read() f.close() tagged_corpus = '' all_words = corpus_text.split() for w in all_words: tagtext = checkCase(w) tagged_corpus = tagged_corpus + ' ' + w + '/' + tagtext output_file = open(path:to:file, 'w') output_file.write(tagged_corpus) print 'All Done!' Also, if you're doing natural language processing in Python, you should get NLTK. From dstromberglists at gmail.com Sat Jul 26 16:41:15 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Sat, 26 Jul 2008 20:41:15 GMT Subject: tcp socket problem References: Message-ID: On Fri, 25 Jul 2008 16:09:13 -0700, jm.carp wrote: > I'm writing a tcp client that grabs data from a server at 32hz. But the > connection drops exactly one minute after it's opened. I can get data > from the server fine for the first 60s, and then the connection goes > dead. What's going on? What does "goes dead" mean in this case? Is python giving a traceback? Is some I/O blocking? I'd probably use a system call tracer to track down something like that, unless there's a useful traceback. It may be useful in the client, or the server, or both. http://stromberg.dnsalias.org/~strombrg/debugging-with-syscall- tracers.html Also, be careful to check that you aren't reading two chunks when you think you're getting one or something. That could cause some I/O to block in a hard-to-track-down way. IOW, TCP feels free to chop your packets into multiple packets, or to aggregate multiple packets into a smaller number of them - whatever it wants, pretty much. This sometimes helps performance or reliability, but it complicates writing socket programs at times. Put another way, a single send might show up as two recv's, for example. Oh, and using a sniffer may help too. I like wireshark or tshark (GUI and text interfaces of the same underlying sniffer), but there are many available. Old hands seem to prefer tcpdump, though I'm clear on why. If you fire up a sniffer against your network communication, it should be possible to see, for example, the last packet transferred, which system it was to, and which system it was from. You may not know which host is having the problem without a detailed knowledge of the protocol, but since you're coding the program, you may have that. :) This may show packet splitting/aggregation too, but keep in mind that a sniffer only shows you the data stream at a particular point in the transfer - you could see different things when running a sniffer on the client, on the server, or even on a subnet in between the two. Oh, and many networks are switched now, so most sniffers don't do that well on subnets in between, but they frequently still work well on the client and server themselves. HTH . From dd55 at cornell.edu Tue Jul 22 08:20:39 2008 From: dd55 at cornell.edu (Darren Dale) Date: Tue, 22 Jul 2008 08:20:39 -0400 Subject: is it possible to add a property to an instance? Message-ID: Does anyone know if it is possible to add a property to an instance at runtime? I didn't see anything about it in the standard library's new module, google hasn't turned up much either. Thanks, Darren From ki4yjl at gmail.com Thu Jul 10 23:26:24 2008 From: ki4yjl at gmail.com (WDC) Date: Thu, 10 Jul 2008 20:26:24 -0700 (PDT) Subject: error with configure (svn 64857) References: <487681e9$0$9745$9b622d9e@news.freenet.de> Message-ID: On Jul 10, 6:57?pm, "Mathieu Prevot" wrote: > 2008/7/10 "Martin v. L?wis" : > > >> I have the following error when I run configure: > > >> checking size of wchar_t... configure: error: cannot compute sizeof (wchar_t) > > >> what can I do ? > > > Study config.log for the source of the problem. > > Thank you Martin. How can I remove -lgcc_s and use the Intel equivalent ? > > configure:21939: checking for wchar_t > configure:21970: icc -c -g -O2 ?conftest.c >&5 > conftest.c(123): warning #279: controlling expression is constant > ? if ((ac__type_new_ *) 0) > ? ? ? ^ > > configure:21976: $? = 0 > configure:21991: result: yes > configure:21998: checking size of wchar_t > configure:22306: icc -o conftest -g -O2 ? conftest.c ?>&5 > ld: library not found for -lgcc_s > configure:22309: $? = 1 > configure: program exited with status 1 > > Mathieu I think he wanted YOU to find the problem. The best way to learn is to figure it out yourself! Good luck. From nicolas.pourcelot at gmail.com Fri Jul 18 10:39:38 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Fri, 18 Jul 2008 07:39:38 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> > What is your (concrete) use case, by the way? I try to make it simple (there is almost 25000 lines of code...) I have a sheet with geometrical objects (points, lines, polygons, etc.) The sheet have an object manager. So, to simplify : >>> sheet.objects.A = Point(0, 0) >>> sheet.objects.B = Point(0, 2) >>> sheet.objects.C = Middle(A, B) Then we have : >>> sheet.objects.A == sheet.objects.B True since have and B have the same coordinates. But of course A and B objects are not same python objects. In certain cases, some geometrical objects are automatically referenced in the sheet, without being defined by the user. (Edges for polygons, for example...) But they must not be referenced twice. So if the edge of the polygon is already referenced (because the polygon uses an already referenced object for its construction...), it must not be referenced again. However, if there is an object, which accidentally have the same coordinates, it must be referenced with a different name. So, I use something like this in 'sheet.objects.__setattr__(self, name, value)': if type(value) == Polygon: for edge in value.edges: if edge is_in sheet.objects.__dict__.itervalues(): object.__setattr__(self, self.__new_name(), edge) Ok, I suppose it's confused, but it's difficult to sum up. ;-) > Another possibility :-) > from itertools import imap > id(x) in imap(id, items) I didn't know itertools. Thanks :-) From martin at v.loewis.de Sat Jul 26 05:28:53 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 26 Jul 2008 11:28:53 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: References: Message-ID: <488AEE55.3010503@v.loewis.de> > (Any recommendations on a flavor of 64 bit of Linux for the Intel > architecture would be appreciated) My recommendation is to use Debian or Ubuntu, as that's my personal preference. As MAL said, any recent distribution that supports AMD64 should be fine (assuming you are not interested in Itanium, SPARC64, HPPA (2.0), PPC64, or Alpha, which are all 64-bit flavors of Linux). Regards, Martin From gcmartijn at gmail.com Sat Jul 26 06:03:51 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Sat, 26 Jul 2008 03:03:51 -0700 (PDT) Subject: re.findall(a patern,'function(dsf sdf sdf)') Message-ID: <8fc6d72a-cfc5-4e9d-af56-a009a464c6bb@27g2000hsf.googlegroups.com> H! First I have some random string below. bla = """ """ Now I'm trying to get each BlaObject with the first (variable) function argument And I can say that this isn't working for a in re.findall(r'([BlaObject ])(.*)([)] *)',bla): print a The output must be something like: # ('BlaObject','argh 1a') # ('BlaObject','argh 1a') or # Blaobject("argh 1a", "argh 2a", "24", 24, 345) # BlaObject("argh 1b", "argh 2b", ""+(sv), ""+(2f), "4"); My simple idea was to a. the start position is the BlaObject b. the stop position is the character ) (not ); because its a javascript function) c. the output [a (everything between) b] Who knows the answer ? Thanks very much, GCMartijn From Scott.Daniels at Acm.Org Wed Jul 23 08:51:56 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 23 Jul 2008 05:51:56 -0700 Subject: maximum value in a column of file In-Reply-To: References: <4886DCF3.10107@isac.cnr.it> <4886F4CD.8010704@isac.cnr.it> Message-ID: maurizio wrote: > thank you for your answer > actually i've to do some statistics (maximum,minimum,mean,standard > deviation,....) of a file of data in which each column is a particular > type of data. (the file is a tab separated value). > I was trying to do this by using python (usually i work with fortran or > bash, but i'm learning python), that the reason why i tried to use numpy. > Look into the csv module (comma separated values). It also can deal with tab separated values. --Scott David Daniels Scott.Daniels at Acm.Org From jeffm_ at email.com Sun Jul 13 02:12:22 2008 From: jeffm_ at email.com (JeffM) Date: Sat, 12 Jul 2008 23:12:22 -0700 (PDT) Subject: spam <...googlegroups.com> <...googlegroups.com> References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> Message-ID: >WDC wrote: >>BTW I reported it, yo should too. >> Lew wrote: >To whom did you report it, so that we may also report it there? Reports made to Google Groups are a complete waste of time. Google will only cancel *that* account (without blocking the IP address). It takes the spammer 30 seconds to enable *another* account. That is, ZERO real effect. It should also be noted that each time this is done plonk files could grow by one item. For Blogspot/Googlepages spam, report those to mailto:adsense-abuse at google.com adsense-abuse@ google.com That puts his site into Google Hell (screws up his GoogleRank). The most effective effort you can make is to do a reverse-DNS on the NNTP-Posting-Host http://private.dnsstuff.com/tools/whois.ch?ip=122.164.105.235&email=on and report abusers to their providers. This assumes their ISPs aren't complete rogues. From keshet1 at umbc.edu Tue Jul 8 23:41:45 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Tue, 08 Jul 2008 23:41:45 -0400 Subject: a simple 'for' question In-Reply-To: <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> References: <4874017D.2000401@umbc.edu> <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> Message-ID: <48743379.3020303@umbc.edu> thanks for the reply - it worked. I just want to make sure that I understand the general syntax - when can I use the iteration variable as x (e..g. print x), and when do I need to use the ...%s... %x syntax? is it only when I need to call x as a "string"? I am not sure I am asking the question right or using the right terms as I am fairly new to programing and python. Thanks for your time. Ben Brian Blais wrote: > On Jul 8, 2008, at Jul 8:8:08 PM, Ben Keshet wrote: > >> I want to use a 'for' iteration to manipulate files in a set of >> folders, something like: >> >> folders= ['1A28','1A6W','56Y7'] >> for x in folders: >> print x # print the current folder >> f = open('my/path/way/x/my_file.txt', 'r') >> ... >> > > > I think: > > f = open('my/path/way/%s/my_file.txt' % x, 'r') > > should work, although I would probably be more clear about the names, > like: > > folders=['1A28','1A6W','56Y7'] > for folder in folders: > filename='my/path/way/%s/my_file.txt' % x > fid=open(filename,'r') > .... > > also, make sure that you do mean the relative path my/path/way/... > # in current folder > as opposed to the absolute path: /my/path/way > # in root folder > > > bb > -- > Brian Blais > bblais at bryant.edu > http://web.bryant.edu/~bblais > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Thu Jul 17 15:21:15 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 17 Jul 2008 12:21:15 -0700 (PDT) Subject: storing references instead of copies in a dictionary References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: On Jul 17, 10:05?am, mk wrote: > > def f2(arg): > > ? ? return "f2 "+arg > > > def f1(arg): > > ? ? return "f1 "+arg > > > a={"1":"f1","2":"f2"} > > print [eval(x[1])(x[0]) for x in a.items()] > > def f2(arg): > > ? ? return "New f2 "+arg > > print [eval(x[1])(x[0]) for x in a.items()] > > Neat trick, if probably dangerous in some circumstances. Anyway, thanks, > I didn't think of that. > > > Don't know if this is any use to you.. > > At least I learned something. :-) You want consistent access to a changing variable. Wrap it in an object: >>> a= Blank( ) >>> a.ref= 'X' >>> a.ref 'X' >>> b= a >>> b.ref 'X' >>> a.ref= 'Y' >>> b.ref 'Y' >>> From marc.wyburn at googlemail.com Wed Jul 30 07:45:50 2008 From: marc.wyburn at googlemail.com (marc wyburn) Date: Wed, 30 Jul 2008 04:45:50 -0700 (PDT) Subject: variable expansion with sqlite Message-ID: Hi I'm using SQlite and the CSV module and trying to create a class that converts data from CSV file into a SQLite table. My script curently uses functions for everything and I'm trying to improve my class programming. The problem I'm having is with variable expansion. self.cursor.executemany('INSERT INTO test VALUES (?)', CSVinput) If CSVinput is a tuple with only 1 value, everything is fine. If I want to use a tuple with more than 1 value, I need to add more question marks. As I'm writing a class I don't want to hard code a specific number of ?s into the INSERT statement. The two solutions I can think of are; using python subsitution to create a number of question marks, but this seems very dirty or finding someway to substitue tuples or lists into the statement - I'm not sure if this should be done using Python or SQLite substitution though. Any tips on where to start looking? Thanks, Marc. From max at alcyone.com Mon Jul 21 02:53:46 2008 From: max at alcyone.com (Erik Max Francis) Date: Sun, 20 Jul 2008 23:53:46 -0700 Subject: Genetic programming: pygene, pygp, AST, or (gasp) Lisp? In-Reply-To: <7bfb3c41-b08b-49dc-9711-6e39a4667db2@b1g2000hsg.googlegroups.com> References: <7bfb3c41-b08b-49dc-9711-6e39a4667db2@b1g2000hsg.googlegroups.com> Message-ID: John Ladasky wrote: > Why not do genetic programming directly on Python code? Maybe my code > tree data structure is redundant to something which already exists? > But apparently Python's "_ast" module offers only one-way access -- it > will generate an AST from a piece of code, but you can't modify an > AST, and turn it back into executable code? I would definitely need > this latter feature. > > ALTERNATELY -- and I don't mention this to start a flame war -- in > pondering this problem I've noticed the frightening fact that Lisp > seems set up to handle genetic programming by design. The s- > expression syntax IS essentially a parse tree. Now, I've spent a few > hours with Lisp so far, and I can't make it do much of anything -- but > I DO see how Lisp could be helpful. Still, I'm reluctant to pursue a > language I don't know, and which I'm finding much harder to grasp than > any language I've tried before. The main advantages that Lisp has to a structural language like Python are that in Lisp there is no distinction between code and data -- they're represented in the same way -- and the syntatic uniformity of the language. Originally the idea with Lisp was that s-expressions were a lower-level syntax that a more Algol-like syntax would be translated to ... then it became aware that the syntax was actually a benefice in many ways, not a hindrance. > Is there a way to interface Lisp to Python, so that I can do all the > interface programming in the language I already know best -- and just > do the genetic parts in Lisp? I haven't seen exception handling in > Lisp, a feature I've come to love in Python. Since it is fairly easy > for a randomly-generated program to generate illegal output (I already > know this from my initial experiments in Python), I don't think I can > live without exception handling. It is not likely you want to do this. Genetic programming systems are probably best run in a sandbox, for reasons which should be pretty reasonable. The point of genetic programming is to manipulate programs into new programs; thus, complicated syntax for those programs only increases the chances that either 1. you have to do an awful lot of extra work to make sure that you end up with valid programs or 2. you end up with an awful lot of syntactically invalid programs. Both of these waste large amounts of processing cycles that you could be focusing on creating new, valid programs from old ones. > I also think that Python has a higher-level understanding of a > variable's "type" or an object's "class" than Lisp does -- if I'm > hacking at a parse tree and I want to minimize syntax errors, I need > to know more than the fact that an element in an expression is an atom > or a list. If you're interested in typed genetic programming systems, then you might want to check out some of the stack-based genetic programming languages like Push or PushGP. These are in effect a stack-based form of Lisp, but which use different data stacks for different types. > Producing human-readable code from my genetic programming search would > be a great bonus -- and for me, at this moment, this seems to mean > Algol-style syntax. (Sigh.) But it's not a requirement. Well, you could always translate s-expressions into m-expressions ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis It isn't important to come out on top, what matters is to be the one who comes out alive. -- Bertolt Brecht, 1898-1956 From mrkafk at gmail.com Fri Jul 18 06:11:41 2008 From: mrkafk at gmail.com (mk) Date: Fri, 18 Jul 2008 12:11:41 +0200 Subject: Unusual Exception Behaviour In-Reply-To: <1214.94685668058$1216317006@news.gmane.org> References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> <8904.90077804333$1216313689@news.gmane.org> <006001c8e831$5c1487b0$143d9710$@rawlins@thinkbluemedia.co.uk> <1214.94685668058$1216317006@news.gmane.org> Message-ID: > Ok, Just to add a little interest, when I comment out the configuration line > for my logging, like so: > > #logging.config.fileConfig("/myapp/configuration/logging.conf") > It appears to throw the exceptions as normal :-) :-s To tell the truth I have never used logging module extensively, so I'm not expert in this area and can't help you there. However, it seems to me that you may have stumbled upon some subtle bug / side effect of logging module that could cause some side effects in exceptions. Or perhaps it surfaces only in combination with glib? If you discover the root cause, please let us know on this ng, I'm also using Python extensions and bindings to other libraries and this could be of interest at least to me. From mail at timgolden.me.uk Thu Jul 10 11:58:57 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 10 Jul 2008 16:58:57 +0100 Subject: Local User Control In-Reply-To: References: Message-ID: <487631C1.20403@timgolden.me.uk> Sparky wrote: > I don't know how feasible this is, but is it possible to have users > log in to access a local database file in such a way that allows the > program to know what user name and password they logged in with? This > would involve separate user names and passwords for each user. Well, this is a question which is crying out for some context. Are you talking about an existing database on an existing platform? If so, which one? Are you talking about a database youo're thinking of building? If so, the answer's probably yes but only you can know. Are you talking about something else altogether? TJG From cs at zip.com.au Sun Jul 27 19:10:58 2008 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 28 Jul 2008 09:10:58 +1000 Subject: Not entirely serious: recursive lambda? In-Reply-To: Message-ID: <20080727231058.GA24171@cskk.homeip.net> On 20Jul2008 00:08, Kay Schluehr wrote: | > Google was not my friend on this one, and I suspect there is no | > answer. | | Even the Great Google can't help if you don't use the right | keywords ;) Actually, I was shown an useful Google search syntax the other day: Searching for: foo looks just for "foo", but searching for: ~foo matches similar words. This came up in a discussion of web sites that use badly chosen keywords (the NSW Police gun licensing information talks only about "firearms", making it surprisingly hard to find; not that I have or want a gun license, but it was the example discussed). Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Humans are incapable of securely storing high quality cryptographic keys and they have unacceptable speed and accuracy when performing cryptographic operations. (They are also large, expensive to maintain diffcult to manage and they pollute the environment.) It is astonishing that these devices continue to be manufactured and deployed. But they are suffciently pervasive that we must design our protocols around their limitations. - C Kaufman, R Perlman, M Speciner _Network Security: PRIVATE Communication in a PUBLIC World_, Prentice Hall, 1995, pp. 205. From stefan_ml at behnel.de Wed Jul 2 12:22:16 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 02 Jul 2008 18:22:16 +0200 Subject: lxml validation and xpath id function In-Reply-To: <018b5155-64f5-46b3-b426-7e6d6d1b20e3@k37g2000hsf.googlegroups.com> References: <018b5155-64f5-46b3-b426-7e6d6d1b20e3@k37g2000hsf.googlegroups.com> Message-ID: <486bab38$0$27446$9b4e6d93@newsspool4.arcor-online.net> Floris Bruynooghe wrote: > I'm trying to use the .xpath('id("foo")') function on an lxml tree but > can't get it to work. Quick follow-up: this has been answered on the lxml mailing list: http://comments.gmane.org/gmane.comp.python.lxml.devel/3815 Stefan From fred.sells at adventistcare.org Fri Jul 11 14:20:36 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Fri, 11 Jul 2008 14:20:36 -0400 Subject: imaplib -- can't read body In-Reply-To: Message-ID: <0A53725C4A497848A7B3A0874B259831011B0992@acesxch01.ADVENTISTCORP.NET> I'm trying to read mail using the imaplib module. I can get the subject and date, but not the body, have not found any example on how to do that and I don't know much about imap. Here's what I have, working as noted... If anyone can show me what I'm missing in order to get the body of a mail message, that would be greatly appreciated, Fred ------------------- code starts below------------------------------- import imaplib, sys, os, re, rfc822 OK = "OK" FETCHTHIS = '(BODY[HEADER.FIELDS (SUBJECT FROM)])' ### got inemsg from the web, works up to the last line; msg.fp has no read and readline returns empty string. class inemsg: def __init__(self,msg): (self.msgfromname, self.msgfrom) = msg.getaddr('from') self.msgto = msg.getaddr('to') self.msgsubject = msg.getheader('subject') self.msgdate = msg.getheader('date') self.msgtext = msg.fp.read() class msg: # a file-like object for passing a string to rfc822.Message def __init__(self, text): self.lines = text.split('\015\012') self.lines.reverse() def readline(self): try: return self.lines.pop() + '\n' except: return '' class MailReader: def __init__(self, mailserver, user, password): self.M = imaplib.IMAP4(mailserver) self.M.login(user, password) result, message = self.M.select(readonly=1) print ( 'constructor', result, message) if result != OK: raise Exception, message def getMessages(self, *mailboxes): if mailboxes: filter = '(%s)' % ' '.join(list(mailboxes)) else: filter = '(UNSEEN UNDELETED)' mtype, data = self.M.search(None, filter ) print ('getMessages', mtype, data) for num in data[0].split(): f = self.M.fetch(num, FETCHTHIS) print ('fetch', f) m = rfc822.Message(msg(f[1][0][1]), 0) subject = m['subject'] fromaddr = m.getaddr('from') if fromaddr[0]=='': n = fromaddr[1] else: n=fromaddr[0] print (subject, fromaddr) return None #no reason to return until I can get the message content/body. if __name__=='__main__': x = MailReader("myserver", "myuser", "mypassword") messages = x.getMessages() print messages --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From paul.nospam at rudin.co.uk Tue Jul 22 02:30:52 2008 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Tue, 22 Jul 2008 07:30:52 +0100 Subject: Python Written in C? References: Message-ID: <87hcaiqvkz.fsf@rudin.co.uk> DaveM writes: > On Mon, 21 Jul 2008 03:18:01 +0200, Michiel Overtoom > wrote: > > >>Many major text/word processing programs (Emacs, vi, MS-Word) are also >>written in C. > > I thought Emacs was written in Lisp. The core - including the lisp interpreter - is written in C. A lot of the user functionality is written in (emacs) lisp. From __peter__ at web.de Tue Jul 22 11:31:10 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 22 Jul 2008 17:31:10 +0200 Subject: convert list of lists to list References: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> Message-ID: antar2 wrote: > Is there a way to convert list_of_listsA to list_of_listsB, where one > list in listof lists A is one element of listB? > > list_of_listsA: > [['klas*', '*', '*'], > ['mooi*', '*', '*', '*'], > ['koe'], > ['arm*', '*', '*(haar)'], > ['groei*', '*', '*', '*', '*']] > > listB: > ['klas* * *', 'mooi* * * *, 'koe', 'arm* * * (haar)', 'groei* * * * > *'] >>> outer = [['klas*', '*', '*'], ... ['mooi*', '*', '*', '*'], ... ['koe'], ... ['arm*', '*', '*(haar)'], ... ['groei*', '*', '*', '*', '*']] >>> [" ".join(inner) for inner in outer] ['klas* * *', 'mooi* * * *', 'koe', 'arm* * *(haar)', 'groei* * * * *'] Peter From bearophileHUGS at lycos.com Mon Jul 21 10:01:51 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 21 Jul 2008 07:01:51 -0700 (PDT) Subject: Almost keywords Message-ID: <30d1a9c0-331f-4263-9775-a1e639082769@m44g2000hsc.googlegroups.com> Once in a while I feel free to write about less defined things, saying mostly wrong things. This post is mostly chat, if you aren't interested please ignore it. Python is fit enough for newbie programmers, but some of its characteristics can confuse them still, like the variables referenced by name (that can be solved with a language that gives the illusion of always manging values), the finite nature of floating point numbers (that may be partially solved with interval arithmetic used in a smart way, even if it may end being quite slower than Python floats), the case sensitivity of all the language (in natural languages the case is often irrelevant), the absence of rational numbers from integer divisions, the code formatting precision required by significant indentations, the "artificial" difference between lazy and eager things, the silly syntax of tuples, some problems with closures that partially come from automatic creation of variable names, many inconsistencies present in the standard library, etc. Python 3.0 solved some of those problems, especially the smaller ones (for example the "nonlocal" keyword workaround, etc). If you take a look at the Python newsgroup, you can see that newbies there do many similar mistakes all the time. A language fit for newbies can adapt itself to avoiding those most common mistakes (but today Python is becoming larger and more complex, more fit for real programmers and less for programming newbies. This may be inevitable in the evolution of a a language with commercial success). One of the mistakes you see often is the rebinding of built-in things, like map, list, etc. (Python 3.0 again turns some of those names into keywords, avoiding part of those problems). So you can see code like this that may lead to bugs in programs written by newbies: list = [x*x for x in range(100) A possible way to avoid such bugs is to turn all those names like "list", "map", "filter", "self", etc into keywords. But this may have some disadvantages (well, I think I'd like to have "self" as keyword, seen how all Python books strong suggest to not use a name different from "self"). An intermediate solution is to change Python so that it allows you to rebind those half-keywords only of you want it and you know what you are doing, with a kind of comment at the top of the module: # rebinding = True This allows you to do: list = [x*x for x in range(100)] By default rebinding is False, so this produces a SyntaxError: list = [x*x for x in range(100)] This may be a silly idea. Designing a good syntax for a language isn't easy at all. Note that a widely used Scheme implementation, DrScheme, implements various sub-languages fit for newbies or almost-newbies or low- experienced programmers. What is possible for experts can be a syntax error for newbies. I don't like this feature much, I like more freedom, but for purely learning purposes it may have its place. So what I have said regarding the "almost keywords" isn't a totally new idea :-) Bye, bearophile From johnroth1 at gmail.com Fri Jul 11 10:22:19 2008 From: johnroth1 at gmail.com (John Roth) Date: Fri, 11 Jul 2008 07:22:19 -0700 (PDT) Subject: Python 3.0 and removal of the 'string' module References: <87wsjtqiyo.fsf@benfinney.id.au> <87iqvdq6qz.fsf@benfinney.id.au> <487706b7$0$9695$9b622d9e@news.freenet.de> <87abgorgiv.fsf@benfinney.id.au> Message-ID: <76f1bf48-b05f-472b-9bfc-cf59dd2a97ca@m45g2000hsb.googlegroups.com> On Jul 11, 6:26?am, Benjamin wrote: > On Jul 11, 3:06 am, Ben Finney > wrote: > > > "Martin v. L?wis" writes: > > > > > This is rather disappointing. Is that entire page suspect? > > > > All documentation about Python 3 is suspect until Python 3 gets > > > actually released (nobody can say for sure how the release will > > > look like in all details). > > > Is there a better information source, then, for the current state of > > what's expected in Python 3.0? > > Look at the development docs. We try to keep them up to date:http://doc.python.org/dev/3.0 > > > > > -- > > ?\ ? ? ? ??Somebody told me how frightening it was how much topsoil we | > > ? `\ ? are losing each year, but I told that story around the campfire | > > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? and nobody got scared.? ?Jack Handey | > > Ben Finney > > The PEPs are also a good source; library changes are all listed in PEP 3008. PEP 361 not only gives the schedule but it also gives a lot of detail on 3.0 features backported to 2.6 and incompatible features that raise warnings in 3.0 PEP 3000, PEP 3100 and PEP 3099 are also well worth reviewing. John Roth From rsimoes at gmail.com Wed Jul 16 01:57:32 2008 From: rsimoes at gmail.com (=?ISO-8859-1?Q?Richard_Sim=F5es?=) Date: Tue, 15 Jul 2008 22:57:32 -0700 (PDT) Subject: Redirecting stdout to another script Message-ID: Hopefully, this explanation will sufficiently clear despite the lack of code. I wrote a python script that takes data via stdin, does stuff with the data, and outputs the result to stdout. A friend wrote a perl script that opens a pipe to my script, feeds it data, and then accepts the result. The problem here is that the python script's outputting the result to stdout via print statements isn't doing what we expected: my friend's perl script isn't getting the result back via the pipe. Is there is simple solution for this problem? Whose script needs to be modified? Thanks, Richard Sim?es From wuwei23 at gmail.com Thu Jul 31 00:59:25 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 30 Jul 2008 21:59:25 -0700 (PDT) Subject: Native Code vs. Python code for modules References: Message-ID: On Jul 30, 11:14?pm, Sion Arrowsmith wrote: > >Well, the snarky response is most Python developers are too busy > >working on actual real world projects :) > > The follow-up snarky response is that working on actual real world > projects has lead Python developers to realise that most real world > bottlenecks arise from disk access, network speed, and user > interaction, and you should only sweat about code speed in the rare > case when you *know* that it's not its interface to the real world > that's slow. You won't hear any disagreement from me on that point :) From aahz at pythoncraft.com Sat Jul 26 20:03:50 2008 From: aahz at pythoncraft.com (Aahz) Date: 26 Jul 2008 17:03:50 -0700 Subject: Pwnie awards Message-ID: Boy, am I glad we're not listed: http://pwnie-awards.org/2008/awards.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From bearophileHUGS at lycos.com Tue Jul 29 19:07:35 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 29 Jul 2008 16:07:35 -0700 (PDT) Subject: static variables in Python? References: Message-ID: <115a132d-7edd-4b07-ba4f-7855577992d1@x41g2000hsb.googlegroups.com> kj: > OK, I guess that in Python the only way to do what I want to do > is with objects... There are other ways, like assigning the value out of the function, because Python functions too are objects: def iamslow(): return 100 def foo(x): return x + foo.y foo.y = iamslow() # slow computation print foo(1) print foo(2) Output is: 101 102 Another way is this, a bit more clean, with the same output: def iamslow(): return 100 def foo(x, y=iamslow()): return x + y print foo(1) print foo(2) But I suggest you to use a class in this situation, it's often the way that will keep your code more bug-free, and more readable by near- casual readers too. Python philosophy asks you to write readable code instead of clever code when possible, this is a difference from Perl, I presume. Bye, bearophile From fredrik at pythonware.com Thu Jul 17 06:16:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 12:16:11 +0200 Subject: Question about properties In-Reply-To: References: Message-ID: Frank Millman wrote: > I thought that the main point of using property was to prevent direct > access to the attribute. Not "prevent access to" as much as "add behaviour to". > Is this a valid comment, or does it come under the category of 'we are > all adults here'? The latter. And the "__" doesn't provide much protection, really (as we'll see below). > While experimenting, I came across the following curiosity. > > I know that prefixing a class attribute with a double-underscore makes > it difficult to access the attribute externally. Here is a simple > example - > >>>> class Test(object): > ... def __init__(self,x): > ... self.x = x > ... self.__y = 123 > ... def get_y(self): > ... return self.__y > >>>> t = Test(99) >>>> t.x > 99 >>>> t.get_y() > 123 >>>> t.__y > AttributeError: 'Test' object has no attribute '__y' > > I was surprised that I could do the following - > >>>> t.__y = 456 >>>> t.__y > 456 >>>> t.get_y() > 123 > > It's not important, but I am curious to know what is going on > internally here. hint: >>> dir(t) ['_Test__y', ..., '__y', 'get_y', 'x'] >>> t._Test__y 123 >>> t.__y 456 From ezindy at gmail.com Sat Jul 19 06:33:17 2008 From: ezindy at gmail.com (Egor Zindy) Date: Sat, 19 Jul 2008 11:33:17 +0100 Subject: ftdi chip + ctypes + ftd2xx... need help with reading chipid! (now with the right source code!) In-Reply-To: <4881C210.7000307@gmail.com> References: <4881C210.7000307@gmail.com> Message-ID: <4881C2ED.2080108@gmail.com> Egor Zindy wrote: > Dear List, > > This one is way beyond my comprehension skills, I just don't > understand what I'm doing wrong. > > I am trying to read the chipid from an FTDI chip based USB key > (DLP-D, http://www.ftdichip.com/Products/EvaluationKits/DLP-D.htm ), > using: > > - the ftd2xx module http://pypi.python.org/pypi/ftd2xx/0.1 > - the ftd2xx.dll which comes with the driver install > - the chipid dll (1.1.0) from here: > http://www.ftdichip.com/Projects/FTDIChip-ID.htm > - a ctypes interface I wrote by hand (only 7 functions to wrap, I > thought it'd be easy!) > > The ftd2xx is used for testing, to open / close the device. > > My Problem is that neither of the following two wrapped functions > (with the exact same arguments) return the right result (full > chipid.py library attached): > > def FTID_GetDeviceLocationID(DeviceIndex): > n = DWORD() > status = ftchipid.FTID_GetDeviceLocationID(DeviceIndex, > ctypes.byref(n)) > > if status != FTID_SUCCESS: > raise DeviceError,FTID_GetErrorCodeString("EN",status) > > return n.value > > def FTID_GetDeviceChipID(DeviceIndex): > n = DWORD() > status = ftchipid.FTID_GetDeviceChipID(DeviceIndex, > ctypes.byref(n)) > > if status != FTID_SUCCESS: > raise DeviceError,FTID_GetErrorCodeString("EN",status) > > return n.value > > * On my machine (XP, 32 bits), if I plug two keys in, I can get the > device chip id from the device with index=1. The one with index=0 > always gives the message "Invalid device handle." > * I get the wrong location id as well, 0 instead of 0x21... > * the FTID_GetNumDevices function also uses a byref, c_ulong and works. > * FTDI's win32 console example returns the right results (and uses c > unsigned longs) - available from > http://www.ftdichip.com/Projects/FTDIChip-ID.htm > > Any help appreciated! > > Regards, > Egor > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: chipid.py URL: From barry at python.org Thu Jul 17 23:42:31 2008 From: barry at python.org (Barry Warsaw) Date: Thu, 17 Jul 2008 23:42:31 -0400 Subject: RELEASED Python 2.6b2 and 3.0b2 Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team and the Python community, I am happy to announce the second beta releases of Python 2.6 and Python 3.0. Please note that these are beta releases, and as such are not suitable for production environments. We continue to strive for a high degree of quality, and these releases are intended to freeze the feature set for Python 2.6 and 3.0. From now until the planned final releases in October 2008, we will be fixing known problems and stabilizing these new Python versions. You can help by downloading and testing them, providing feedback and hopefully helping to fix bugs. You can also use these releases to determine how changes in 2.6 and 3.0 might impact you. ONLY ONE MORE BETA RELEASE IS PLANNED, so now is a great time to download the releases and try them with your code. If you find things broken or incorrect, please submit bug reports at http://bugs.python.org For more information and downloadable distributions, see the Python 2.6 website: http://www.python.org/download/releases/2.6/ and the Python 3.0 web site: http://www.python.org/download/releases/3.0/ See PEP 361 for release schedule details: http://www.python.org/dev/peps/pep-0361/ Enjoy, - -Barry Barry Warsaw barry at python.org Python 2.6/3.0 Release Manager (on behalf of the entire python-dev team) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSIARKHEjvBPtnXfVAQL7AQQAjPSbfKz2Oh/au/hPzS4x2IR5/R6FVe+g o9UYrONNRKJ14UHpbZRzvIvw/4G3PdpzzGxjYFIhVGEesEGJnMzT3YdkMHt4NW9d HOZxL3hseGbTdpUJPCsIkNG+4hX7iuY3NSV81Z75LGAL4tqbooGqwwUslXMT5f8s lRrZUcBRKZ0= =ju6s -----END PGP SIGNATURE----- From Tribulations at Paralleles.invalid Mon Jul 7 01:32:42 2008 From: Tribulations at Paralleles.invalid (TP) Date: Mon, 07 Jul 2008 07:32:42 +0200 Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> <6ddj74F21uhjU1@mid.individual.net> Message-ID: Peter Pearson wrote: Thanks for your answer. > When you run echo, it recognizes the 4-character "esc" as a > convention for representing a single character, and performs > the re-interpretation for you. When you tell python > "print '\033[30;44m foo \033[0m'", python interprets > the "\033" as a single character. So, the python print command *can* interpret these 4-character as a single character. It would be odd if there were no possibility to do the same thing when the characters are (i) stored in a python variable, or (ii) come from the environment variables. Does anybody know any way to re-interpret a string in Python? I have tried to play with "eval" (as in bash), but it does not yield anything. -- TP (Tribulations Parall?les) "Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert). From phillip.oldham at gmail.com Wed Jul 16 14:01:18 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Wed, 16 Jul 2008 11:01:18 -0700 (PDT) Subject: Is there any component-oriented (non-MVC) web framework available for Python? References: <5fdd1388-bb1e-4a59-8fd1-2aa1ce7fa6e0@79g2000hsk.googlegroups.com> Message-ID: On Jul 16, 6:48?pm, Alis wrote: > Hi > > Is there any component-oriented (non-MVC) web framework available for > Python? > > That is something like Apache Wicket, Tapestry or JSF, but I need it > to be in Python. > > Regards, > Ali Have you looked at kamaelia? http://kamaelia.sourceforge.net/ From larry.bates at websafe.com` Tue Jul 22 23:42:51 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 22 Jul 2008 22:42:51 -0500 Subject: Python Written in C? In-Reply-To: <6ejutcF6vgp3U4@mid.uni-berlin.de> References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Mon, 21 Jul 2008 18:12:54 +0200, mk wrote: > >> Seriously, though, would there be any advantage in re-implementing >> Python in e.g. C++? >> >> Not that current implementation is bad, anything but, but if you're not >> careful, the fact that lists are implemented as C arrays can bite your >> rear from time to time (it recently bit mine while using lxml). Suppose >> C++ re-implementation used some other data structure (like linked list, >> possibly with twists like having an array containing pointers to 1st >> linked list elements to speed lookups up), which would be a bit slower >> on average perhaps, but it would behave better re deletion? > > An operation that most people avoid because of the penalty of "shifting > down" all elements after the deleted one. Pythonistas tend to build new > lists without unwanted elements instead. I can't even remember when I > deleted something from a list in the past. > > Ciao, > Marc 'BlackJack' Rintsch When I use os.walk and need to remove directories or files. Seems to be the only way to do the in-place delete that is required. But you are right, it is very seldom. -Larry From larry.bates at websafe.com` Tue Jul 15 16:00:11 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 15:00:11 -0500 Subject: Testing for connection to a website In-Reply-To: References: Message-ID: Alexnb wrote: > Okay, I already made this post, but it kinda got lost. So anyway I need to > figure out how to test if the user is able to connect to a specific website. > Last time I got pointed to the urllib2 page, but if I do urlopen() and and > am not connected, the program stops. So I don't know if that was what you > guys wanted me to do, but I don't think so, you guys are smarter than that. > So, how can I test for connection to a website. You can test DNS resolution by doing this: import socket # # Check to make sure domain is legal and that I can resolve it to IP addr # try: ipaddr=socket.gethostbyname(domain) except socket.gaierror: print "Internet connection or DNS error" For the "connect to a specific website" portion you just have to wait until it times out to determine failure. -Larry From bj_666 at gmx.net Fri Jul 4 09:13:24 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 Jul 2008 13:13:24 GMT Subject: Static Class Initialization Question. References: <486e16c8$0$22780$426a34cc@news.free.fr> Message-ID: <6d6lvkF134f0U2@mid.uni-berlin.de> On Fri, 04 Jul 2008 14:59:05 +0200, Thomas Troeger wrote: > Bruno Desthuilliers wrote: >>> I want to have a list of such classes instantiated automatically on > > Of course I meant class instances ... sorry :) It's always good to have > an example to compensate for English errors *g*. Well, "class instances" is still a little bit ambiguous in a language where classes are objects too. ;-) > Ah I knew there was something and I couldn't find it in the docs > anymore! Now my potential follow-up question is answered as well, namely > how I can instantiate with variable argument lists, like this: > > >>> bla = [A(*args) for args in ((), (1,), (1, 2))] > >>> map(str, bla) > ['A(0,1)', 'A(1,1)', 'A(1,2)'] Looks like you want default values for the arguments of `A.__init__()`. Ciao, Marc 'BlackJack' Rintsch From mal at egenix.com Wed Jul 2 13:30:02 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 02 Jul 2008 19:30:02 +0200 Subject: Win32.client, DAO.DBEngine and exceeding the file sharing count lock In-Reply-To: <9ab0cc2d-5a7e-40ca-a4da-084347f147cd@m36g2000hse.googlegroups.com> References: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> <9ab0cc2d-5a7e-40ca-a4da-084347f147cd@m36g2000hse.googlegroups.com> Message-ID: <486BBB1A.5070305@egenix.com> On 2008-07-02 16:54, Iain King wrote: > On Jul 2, 3:29 pm, Tim Golden wrote: >> Iain King wrote: >>> Hi. I'm using the win32 module to access an Access database, but I'm >>> running into the File Sharing lock count as inhttp://support.microsoft.com/kb/815281 >>> The solution I'd like to use is the one where you can temporarily >>> override the setting using (if we were in VB): >>> DAO.DBEngine.SetOption dbmaxlocksperfile,15000 >> Really hurried answer: >> >> >> import win32com.client >> >> dao = win32com.client.gencache.EnsureDispatch ("DAO.DBEngine.36") >> dao.SetOption (Option=win32com.client.constants.dbMaxLocksPerFile, Value=15000) >> >> >> TJG > > Thanks. I found this: http://blogs.msdn.com/michkap/archive/2007/07/13/3849288.aspx > which outlines some difference between DAO and ADO, including: > "Capability to set and change Jet options without making registry > changes (works in DAO through DBEngine.GetOption and > DBEngine.SetOption, fails in ADO, which has no such analogue)." You could try to use the Access ODBC driver and access the database that way via mxODBC. That would be faster as well: http://www.microsoft.com/technet/prodtechnol/windows2000serv/technologies/iis/reskit/iischp7.mspx (scroll down to table 7.1) Apart from that option and if you are really in need for larger transactions, I'd suggest that you move to SQL Server for processing (if you can). Access is not really made for heavy-lifting and big transactions. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 02 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania 4 days to go :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From steve at REMOVE-THIS-cybersource.com.au Tue Jul 29 19:42:59 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 23:42:59 GMT Subject: Boolean tests References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <87y73kg70u.fsf@benfinney.id.au> Message-ID: <009fa67c$0$20313$c3e8da3@news.astraweb.com> On Tue, 29 Jul 2008 21:25:44 +0100, Matthew Woodcraft wrote: > Ben Finney wrote: >> No, he retracted the *insult* and restated the *advice* as a distinct >> statement. I think it's quite worthwhile to help people see the >> difference. > > Ben, it was quite clear from Anders' post that he knows about > __nonzero__ . That's why the so-called advice is insulting. The original > phrasing was just the icing on the cake. Anders wrote: "But then you decide to name the method "__nonzero__", instead of some nice descriptive name?" That suggests to me that Anders imagined that __nonzero__ is something I just made up, instead of a standard Python method. What does it suggest to you? -- Steven From musiccomposition at gmail.com Thu Jul 24 22:45:27 2008 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 24 Jul 2008 19:45:27 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <579f9d5b-8984-425d-8d4f-b2ed0be8eaba@o40g2000prn.googlegroups.com> <4888cd25$0$15527$426a74cc@news.free.fr> Message-ID: <89fdab20-3e1e-459d-af7d-697942bd5159@j1g2000prb.googlegroups.com> On Jul 24, 11:43?am, Bruno Desthuilliers wrote: > > "explicit-is-etc" - just like the remaining of Python's zen - is a > general philosophy statement, not an absolute rule. Another quote states > that practicality beats purity. Very much so. In fact, I'd like you all to take a detour to a recent bug report [1] where I gained some interesting insight into the Zen. [1] http://bugs.python.org/issue3364 From motoom at xs4all.nl Sun Jul 20 21:18:01 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Mon, 21 Jul 2008 03:18:01 +0200 Subject: Python Written in C? Message-ID: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> Giveitawhril wrote... > REAL WORLD programmers who want to be generally useful go > and learn C#. No: Real programmers first eat a quiche and then return to their Pascal programming. > But the SOURCE is some old, high level language which no one wants to > use anymore! C is alive and kicking. Every language has its place. Plus, there exists implementations of Python written in Python itself; see PyPy: http://codespeak.net/pypy/dist/pypy/doc/home.html > Just noting that, if it is written in C, that throws a curve at me > in trying to balance the value of learning Python vs. some other > major language. Many major text/word processing programs (Emacs, vi, MS-Word) are also written in C. Does that mean you should do all your text processing in C? Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From socyl at 987jk.com.invalid Tue Jul 29 14:22:54 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 18:22:54 +0000 (UTC) Subject: Where is the documentation for psycopg2? Message-ID: Hi. I can't find any documentation for psycopg2. I'm a noob, so I'm sure I'm just not looking in the right place... Anybody know where it is? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From martin at v.loewis.de Sat Jul 26 05:28:53 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 26 Jul 2008 11:28:53 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: References: Message-ID: <488AEE55.3010503@v.loewis.de> > (Any recommendations on a flavor of 64 bit of Linux for the Intel > architecture would be appreciated) My recommendation is to use Debian or Ubuntu, as that's my personal preference. As MAL said, any recent distribution that supports AMD64 should be fine (assuming you are not interested in Itanium, SPARC64, HPPA (2.0), PPC64, or Alpha, which are all 64-bit flavors of Linux). Regards, Martin From crazychimp132 at gmail.com Tue Jul 15 12:18:20 2008 From: crazychimp132 at gmail.com (crazychimp132 at gmail.com) Date: Tue, 15 Jul 2008 09:18:20 -0700 (PDT) Subject: Method behavior for user-created class instances References: <42433fcd-fcdc-4f42-a427-c28241734b7c@z66g2000hsc.googlegroups.com> Message-ID: <5826b9d9-dc73-40c1-a476-209beff4e104@f36g2000hsa.googlegroups.com> On Jul 15, 9:53 am, "bruno.desthuilli... at gmail.com" wrote: > On 15 juil, 01:24, crazychimp... at gmail.com wrote: > > > Greetings. > > > I am looking for a way to achieve method behavior for a class I > > created. That is, it has a __call__ method, so can be called like a > > function. But I also want it to be treated as a method when it appears > > in a class body. > > You need to implement the descriptor protocol the same way the > function type do. > > import types > > class Foo(object): > def __call__(self, instance): > print "%s - %s" % (self, instance) > > def __get__(self, instance, cls): > return types.MethodType(self, instance, cls) > > class Bar(object): > foo = Foo() > > b = Bar() > b.foo() > > > I know this has to do with writing the __get__ > > method of foo, but I am wondering if there is perhaps some class I can > > just inherit from to get the proper __get__, which behaves identically > > to that of regular Python functions. > > Extending types.FunctionType doesn't work OOTB (there's some > incompatibility wrt/ metaclasses) Thanks, this got me started in writing it for 3.0. There are no more unbound methods in 3.0, so a check for whether instance is None is necessary to give the right behavior. Here is the final implementation I came up with: from abc import ABCMeta, abstractmethod from functools import update_wrapper from types import MethodType class decorator(metaclass = ABCMeta): def __init__(self, function): update_wrapper(self, function) self.function = function def __get__(self, instance, cls): if instance is None: return self return MethodType(self, instance) @abstractmethod def __call__(): pass To use it, write a class that inherits decorator and overrides __call__, probably doing something with self.function. From torriem at gmail.com Tue Jul 15 03:56:51 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 15 Jul 2008 01:56:51 -0600 Subject: Why is there no GUI-tools like this for Windows? In-Reply-To: <48796BD1.9030406@internetnowasp.net> References: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> <48796BD1.9030406@internetnowasp.net> Message-ID: <487C5843.3020802@gmail.com> Marcus.CM wrote: > So python for me is for anything except GUI. It becomes self rejecting > notion to do GUI in python when you type in those stuff that could have > been handled by an IDE, > thus for linux project i just do the web interface + php and let python > do all the other hard core work. This is probably exactly backwards of how I think of it. Python is ideally suited for creating and driving GUIs, things that dispatch work to libraries and routines that do the real work. This is known as the separation of the user interface from the backend business logic. While I feel python is equally good at backend processing as it as front-end stuff, many folks feel that Python may be too slow for certain kinds of data processing. Therefore by that logic, python only makes sense on the front end. To the original poster, get yourself this package: http://gladewin32.sourceforge.net/ Then google around for getting PyGTK working on Win32 and you're in business. Don't use glade's code-generation tools; they are obsolete. Instead use the glade xml file and the libglade or GTK Builder python bindings for GTK to load and create the GUIs on the fly. Personally I think that designing good-looking guis in Python using wxWidgets, PyGTK or PyQT in plain code is very fast and very easy. In fact I think that GUI builders are somewhat overrated as they cannot possibly cope with a GUI that will display data dynamically, or use custom widgets. That said, check out PyQT (definitely available on windows) and Qt's Designer. It pretty much blows glade and anything else I've seen out of the water. From fredrik at pythonware.com Mon Jul 21 17:38:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 23:38:06 +0200 Subject: Getting the name of a variable which was used as a function parameter. In-Reply-To: <9c24ced1-4a0b-4e04-9ce2-1d730e3d8dd7@d77g2000hsb.googlegroups.com> References: <9e2e64db-d594-408d-9418-b17133f23204@27g2000hsf.googlegroups.com> <6ekbg0F6vgp3U5@mid.uni-berlin.de> <9c24ced1-4a0b-4e04-9ce2-1d730e3d8dd7@d77g2000hsb.googlegroups.com> Message-ID: Ravi Kotecha wrote: > Of course I wouldn't, it is a total hack, mostly useless but fun. I > tried to do it after someone in #python efnet said it was impossible! your function only finds *some* name (if it finds a name at all), not *the* name, so you haven't really proven that someone wrong yet. you can get a lot closer by using more radical approaches, but I don't think it's possible to do this in a fully robust way, at least not from the Python level. From bdesth.quelquechose at free.quelquepart.fr Mon Jul 28 14:53:25 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Jul 2008 20:53:25 +0200 Subject: Protecting instance variables In-Reply-To: References: <6eb9iaF6779oU1@mid.uni-berlin.de> Message-ID: <488e319c$0$14077$426a34cc@news.free.fr> Nikolaus Rath a ?crit : > Hi, > > Sorry for replying so late. Your MUA apparently messes up the > References:, so I saw you reply only now and by coincidence. > > "Diez B. Roggisch" writes: >> Nikolaus Rath schrieb: >>> Hello, >>> >>> I am really surprised that I am asking this question on the mailing >>> list, but I really couldn't find it on python.org/doc. >>> >>> Why is there no proper way to protect an instance variable from access >>> in derived classes? >>> >>> I can perfectly understand the philosophy behind not protecting them >>> from access in external code ("protection by convention"), but isn't >>> it a major design flaw that when designing a derived class I first >>> have to study the base classes source code? Otherwise I may always >>> accidentally overwrite an instance variable used by the base class... >> Here we go again... >> >> http://groups.google.com/group/comp.lang.python/browse_thread/thread/188467d724b48b32/ >> >> To directly answer your question: that's what the __ (double >> underscore) name mangling is for. > > > I understand that it is desirable not to completely hide instance > variables. But it seems silly to me that I should generally prefix > almost all my instance variables with two underscores. Why on earth would you protect "almost all" your attributes ??? > I am not so much concerned about data hiding, but about not > accidentally overwriting a variable of the class I'm inheriting from. > > And, unless I misunderstood something, this is only possible if I'm > prefixing them with __. > > How is this problem solved in practice? Which "problem" ?-) What your afraid of almost never happens. FWIW, it *never* happened to me in now 8+ years. And I almost never use __name_mangling_protection (I'd say about half a dozen times, and mostly because I was getting a bit paranoid on these occasions). > I probably don't have a > representative sample, but in the libraries that I have been using so > far, there were a lot of undocumented (in the sense of: not being part > of the public API) instance variables not prefixed with __. Oh, while we're at it: the convention for "protected" attributes (that is: not part of the API, but ok to override) is to use a single leading undescore. > I have > therefore started to first grep the source of all base classes > whenever I introduce a new variable in my derived class. Is that > really the way it's supposed to be? What if one of the base classes > introduces a new variable at a later point? Well... Since Python is dynamicall typed, and since it has good support for composition/delegation, type hierarchies tends to be *way* much flatter than in Java or C++. So there's way less name collision hazards. As I said, what you fear just never happened to me so far, even in frameworks like Zope which is probably where you'll find the worst case of deep type hierarchies and multiple inheritance abuse in Python. IOW : unless your code suddenly breaks in strange ways after you've added a new attribute (or renamed one), just don't worry. From steve at REMOVE-THIS-cybersource.com.au Thu Jul 10 02:55:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 10 Jul 2008 01:55:45 -0500 Subject: Impossible to change methods with special names of instances of new-style classes? References: Message-ID: On Tue, 08 Jul 2008 17:56:45 -0400, Joseph Barillari wrote: > Hi python-list, > > I've just started using new-style classes and am a bit confused as to > why I can't seem to alter methods with special names (__call__, etc.) of > new-style class instances. [deploy weapon of mass snippage] Here is a possible work-around: >>> class Special(object): ... def __call__(self): ... try: ... return self.__dict__['__call__']() ... except KeyError: ... return 'foo' ... >>> s = Special() >>> s() 'foo' >>> s.__call__ = lambda: 'bar' >>> s() 'bar' -- Steven From starsareblueandfaraway at gmail.com Thu Jul 17 10:41:22 2008 From: starsareblueandfaraway at gmail.com (Roy H. Han) Date: Thu, 17 Jul 2008 10:41:22 -0400 Subject: % sign in python? In-Reply-To: References: Message-ID: <6a5569ec0807170741q524fedaatd6d1f1f9dd52b6d7@mail.gmail.com> The percent sign is a placeholder. For example, if level = 1 msg = 'look' Then '[[Log level %d: %s]]' % ( level, msg ) becomes '[[Log level 1: look]]' %d means insert an integer %s means insert a string You can also use dictionaries. d = {'string1': 'hey', 'string2': 'you'} Then '%(string1)s %(string2)s' % d becomes 'hey you' On Thu, Jul 17, 2008 at 10:33 AM, korean_dave wrote: > What does this operator do? Specifically in this context > > test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) > > (Tried googling and searching, but the "%" gets interpreted as an > operation and distorts the search results) > -- > http://mail.python.org/mailman/listinfo/python-list > From thomas.bugzilla at gmx.net Wed Jul 9 06:22:46 2008 From: thomas.bugzilla at gmx.net (Thomas) Date: Wed, 09 Jul 2008 12:22:46 +0200 Subject: Manipulating sys.path Message-ID: Hi all, I want to manipulate sys.path outside of PYTHONPATH (environment) and sys.path.append() (programmatically). A bit of background: We're maintaining a small application that includes a couple of Python scripts. Over time, a decent amount of code has been forked into modules, so the overall file system layout of our kit looks like this: tool/ bin/ prog1.py prog2.py ... lib/ pack1/ mod1.py mod2.py ... The issue I have is that I want to add the 'lib' directory to the module search path so that our programs prog1.py, prog2.py,... can find the modules pack1.mod1, pack1.mod2, ... But I want to keep this out of the program's source code which rules out statements like 'sys.path.insert(0, "../lib")'. We also want to be minimal-invasive for the hosting environment, so no copying of 'lib' into the standard Python lib directories (like /usr/local/lib/python2.5/site-packages etc.), nor forcing the user to change his PYTHONPATH shell environment. It should be solved locally in our kit's directory tree. I was thinking about putting code into a 'bin/__init__.py' file but that's only working for modules and not for executable scripts, right?! Then I came across the '.pth' files, but unfortunately they only seem to work in some standard paths (like the before mentioned /usr/local/lib/python2.5/site-packages), and not in the script directory (like 'bin' in my case) which is automatically added to sys.path. Can anybody think of something that could be of help here? Thanks, Thomas From duncan.booth at invalid.invalid Sun Jul 13 05:35:03 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Jul 2008 09:35:03 GMT Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> Message-ID: "Giampaolo Rodola'" wrote: > Having said that I'd like to understand if there are cases where > deleting or moving an element of the heap, causes heappop() to return > an element which is not the smallest one. Yes, of course there are: any time you delete element 0 of the heap you can do that. >>> heap = [0, 2, 1, 4, 5, 6, 7, 8, 9] >>> heapify(heap) >>> heap [0, 2, 1, 4, 5, 6, 7, 8, 9] >>> del heap[0] >>> heappop(heap) 2 >>> By definition, element 0 is always the smallest but the next two elements could be in any order. If you delete an element other than 0 then the next pop won't be guaranteed to work. If you delete an element other than 0 the very next pop will work, but the heap conditions won't necessarily be restored so subsequent elements may come out in the wrong order. A simple example: >>> heap = [0, 1, 3, 4, 2, 5] >>> heapify(heap) >>> heap [0, 1, 3, 4, 2, 5] >>> del heap[1] >>> heappop(heap), heappop(heap), heappop(heap) (0, 3, 2) From gagsl-py2 at yahoo.com.ar Mon Jul 28 04:29:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 Jul 2008 05:29:14 -0300 Subject: Command line arguements References: <73045cca0807272113y397de468yfcb00ffbbec7990a@mail.gmail.com> Message-ID: En Mon, 28 Jul 2008 01:43:52 -0300, Henry Chang escribi?: > try optparse :) > http://docs.python.org/lib/module-optparse.html (optparse might be too much for a single argument) > On Sun, Jul 27, 2008 at 9:13 PM, aditya shukla > wrote: > >> in other words i do not want to do hard code the name of the file in my >> code every time i need to read it. >> >> I was reading about the sys module and i guess sys.argv would take the >> input from the command line whenever i run the python script . Exactly. Try this: import sys print sys.argv with no arguments, one, and several, and see what happens. -- Gabriel Genellina From python at rcn.com Sun Jul 20 02:38:24 2008 From: python at rcn.com (Raymond Hettinger) Date: Sat, 19 Jul 2008 23:38:24 -0700 (PDT) Subject: Question References: Message-ID: <6f98da19-d1d1-4e3f-ad5d-04c65a497894@y22g2000prd.googlegroups.com> On Jul 19, 2:27?am, perl_wiz... at manx.net wrote: > Why is Perl so much better than python? Because dollar signs are a superior form of punctuation. Raymond From goldtech at worldpost.com Sun Jul 13 11:30:14 2008 From: goldtech at worldpost.com (goldtech) Date: Sun, 13 Jul 2008 08:30:14 -0700 (PDT) Subject: SAX XML Parse Python error message Message-ID: SAX XML Parse Python error message Hi, My first attempt at SAX, but have an error message I need help with. I cite the error message, code, and xml below. Be grateful if anyone can tell me what the fix is. Thanks. >>> Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\pythonscripts\xml\parse3.py", line 43, in ? parser.parse(r'C:\perlscripts\xml\Document2.kml') File "C:\Python24\lib\xml\sax\expatreader.py", line 107, in parse xmlreader.IncrementalParser.parse(self, source) File "C:\Python24\lib\xml\sax\xmlreader.py", line 123, in parse self.feed(buffer) File "C:\Python24\lib\xml\sax\expatreader.py", line 207, in feed self._parser.Parse(data, isFinal) File "C:\Python24\lib\xml\sax\expatreader.py", line 303, in end_element self._cont_handler.endElement(name) File "C:\pythonscripts\xml\parse3.py", line 39, in endElement print self.description, str(self.coordinates) AttributeError: G_Handler instance has no attribute 'coordinates' >>> Code: from xml.sax import make_parser from xml.sax.handler import ContentHandler import string class G_Handler(ContentHandler): def __init__ (self): self.isFolderElement = 0 self.isdescriptionElement = 0 self.iscoordinatesElement = 0 def startElement(self, name , attrs): if name == 'Folder': self.isFolderElement= 1 self.Folder = "" if name == 'description': self.isdescriptionElement= 1 self.description = "" if name == 'coordinates': self.iscoordinatesElement = 1 self.coordinates = "" def characters (self, ch): if self.isFolderElement == 1: self.Folder = ch if self.isdescriptionElement == 1: self.description = ch if self.iscoordinatesElement == 1: self.coordinates = ch def endElement(self, name): if name == 'Folder': self.isFolderElement = 0 if name == 'description': self.isdescriptionElement= 0 if name == 'coordinates': self.iscoordinatesElement = 0 print self.description, str(self.coordinates) parser = make_parser() parser.setContentHandler(G_Handler()) parser.parse(r'C:\perlscripts\xml\Document2.kml') abc -84.4, 33.7 abc -86.7, 36.1 From castironpi at gmail.com Tue Jul 8 11:29:08 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 8 Jul 2008 08:29:08 -0700 (PDT) Subject: "in"consistency? References: Message-ID: <871c6735-f2d2-4cd0-811d-0cd774d55bdd@m45g2000hsb.googlegroups.com> On Jul 7, 5:02?pm, Gary Herron wrote: > Nick Dumas wrote: > > -----BEGIN PGP SIGNED MESSAGE----- > > Hash: SHA1 > > > [1,2] in [1,2,3] checks to see if the list [1,2] is an item in [1,2,3]. > > Because the list [1,2,3] only contains the integers 1,2,3, the code > > returns a False. Try "[1,2] in [[1,2],[2,3]]" > > The inconsistency goes deeper than that. ?For instance, the type of a > value returned by the indexing operation: > > ? ?Indexing a string returns a string (of length 1 of course), > ? ?while indexing a list does not (necessarily) return a list. > > Conclusion: ?They are different types supporting different operations. ? > Given all the obvious differences (mutability, sorting and other > methods, types of individual elements), I'd say there are more > differences than similarities, even though, as sequences, ?they both > support a small subset of similar operations. > > Gary Herron > > > David C. Ullrich wrote: > > >> Luckily I tried it before saying no, that's > >> not how "in" works: > > >>>>> 'ab' in 'abc' > > >> True > > >>>>> [1,2] in [1,2,3] > > >> False > > >> Is there a reason for the inconsistency? I would > >> have thought "in" would check for elements of a > >> sequence, regardless of what sort of sequence it was... Strings are not containers. Another container type: Python 3.0b1 on win32 >>> {0} in {0,1} False Another string-like, non-container type: >>> bytes( [ 0, 1 ] ) in bytes( [ 0, 1, 2 ] ) True From kay.schluehr at gmx.net Sun Jul 27 03:03:58 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 27 Jul 2008 00:03:58 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> Message-ID: On 26 Jul., 19:20, Michele Simionato wrote: > On Jul 26, 5:28 pm, a... at pythoncraft.com (Aahz) wrote: > > > IMO, you made a big mistake in combining your point with two other meaty > > issues (whether method definitions should include self and whether != > > should use __eq__() as a fallback). > > > If solid discussion > > is your goal, I suggest that you wait a couple of weeks and start over > > with a brand-new thread. > > I fully subscribe this. The point about __eq__ is legitimate and could > be discussed with quite tones. > I was bitten by this surprising behavior just a few > days ago, I had defined __eq__ and I expected __neq__ > to be defined in the obvious way. I saw that it was > not the case and I figured out immediately that > I had to override __neq__ explicitely (I have > the "explicit is better than implicit" mantra > ingrained in my mind too), I did so and everything > worked out as a charm. Total time loss: five minutes. > So, it is not a big point. Still I think > that it would make sense to automatically > define __neq__ as the negation of __eq__. > I suppose the developers did not want to make a special > case in the implementation and this is also a legitimate > concern. > > Michele Simionato Incidentally I knew that I had to overload the negation of __eq__ explicitely and did so writing an __neq__ method. A few minutes later I found out it's not __neq__ but __ne__. So another few minutes were lost. From dullrich at sprynet.com Wed Jul 23 11:04:52 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Wed, 23 Jul 2008 10:04:52 -0500 Subject: repr(string) Message-ID: I've been saving data in a file with one line per field. Now some of the fields may become multi-line strings... I was about to start escaping and unescaping linefeeds by hand, when I realized that repr() and eval() should do. Hence the question: If s is a string, is repr(s) guaranteed not to contain line breaks? -- David C. Ullrich From jr9445 at ATT.COM Tue Jul 15 16:13:18 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Tue, 15 Jul 2008 15:13:18 -0500 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Victor Noagbodji > Sent: Tuesday, July 15, 2008 3:44 PM > To: python-list at python.org > Subject: Re: 'if name is not None:' v. 'if name:' > > >>what's the difference between these two statement? > >one checks if the given object is not None, the other checks if it's a > true value: > >http://docs.python.org/ref/Booleans.html#Booleans > >>And which one should one use? > >depends on what you want to test for, of course. > > > > > > Well that's exactly why I'm asking. Since None returns False in if > statements. Why do people use if name is not None: instead of simply > writing if not name? > If name is None: Then name is NULL, nothing, nada, no object, no memory allocated, a NULL pointer If name is not None: Then name is an object. It's a pointer to some kind of allocated structure in memory. No idea if it contains a false or true value. If name: Then either a) name is an object, and that object does not have a 'false' value, such as False, zero, or empty. or b) name is NULL/None. No object. Try this: d = dict() if not d: d['a'] = 1 print d d = None if not d: d['c'] = 3 print d ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA622 From ajdamico at gmail.com Thu Jul 24 06:23:54 2008 From: ajdamico at gmail.com (Anthony) Date: Thu, 24 Jul 2008 03:23:54 -0700 (PDT) Subject: Autocompletion and Interactive Tables in a Python IDE References: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Message-ID: FoxPro is data-oriented, which means that at any time you have any number of data sets open in the workspace and browse them immediately by running one line of code in the command window. It's a really important feature in terms of efficiency; I don't want to have to move back and forth between SPSS and an IDE when I'm figuring out what code to write, that takes six keystrokes for what FoxPro can do in one. Again, here's what the BROWSE command presents: http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=vfptoolkit_figure02.tif Does VIM have the capability to keep data open? -- Do any of these IDEs have this browse capability?? On Jul 24, 4:10?am, Aspersieman wrote: > Anthony wrote: > > Hi, I'm a FoxPro programmer, but I want to learn python before it's > > too late. ?I do a lot of statistical programming, so I import SPSS > > into python. ?In my opinion, the best features of Visual FoxPro 9.0 > > were: > > a) Intellisense (tells you what classes/methods are available and what > > variables go into a function) > > b) Code Completion (guesses your code after four letters) > > c) Data-Orientation; multiple data sessions can be open, data can be > > viewed easily > > > Python's IDLE has only half of the first of these features. ?I did a > > lot of searching and found the PyDev extensions for Eclipse's Python > > IDE, and found that they've got Intellisense. ?I'm still missing b and > > c, and am getting extremely frustrated programming so slowly.. > > > So two questions: > > Is there any package, gui, IDE, anything that will do FoxPro-style > > code completion? ?If it works in Eclipse, even better.. > > I can't find a good screenshot, but here's a better description: > > You type "BROW" and it pops up a window that says "BROWSE" ..at this > > point if you hit enter it completes the word.. > > > and > > > How can I view open SPSS data in one of the Python GUIs? ?Again, > > Eclipse would be the preference. > > Here's an example of how I'd like to browse the data: > >http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=... > > I don't want to have to switch back and forth between Python and SPSS > > while I'm programming; I just want to stay in one of them.. > > > What can I do? ?I feel extremely inefficient when I don't have these > > three features.. > > > Thanks in advance. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > You might want to try vim. It has a steep learning curve, but definitely > increases productivity _alot_. > > Here is a tutorial on setting up vim with : > ? ? 1) Code completion (intellisense) - including tooltips (!!!) > ? ? 2) Jump between your python code and the python class libraries. > ? ? 3) Syntax checking > ? ? 4) A handy source browser > ? ? 5) Debugging (using pdb) > ? ? 6) [All the other vim goodies - already included] > Above instructions available herehttp://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/ > > I have been using the above setup for a while and find it superior to > _any_ IDE I've ever worked with. > > I'm not sure what you mean by 'Data-Orientation' but I'm sure there's a > suitable alternative/replacement for it in vim. > > Regards > > Nicolaas > > -- > > The three things to remember about Llamas: > 1) They are harmless > 2) They are deadly > 3) They are made of lava, and thus nice to cuddle. From wuwei23 at gmail.com Fri Jul 25 10:39:01 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 25 Jul 2008 07:39:01 -0700 (PDT) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <6c5e878b-8e82-4ffb-bd8a-c673804774fe@x29g2000prd.googlegroups.com> Message-ID: On Jul 25, 9:54?pm, Jeff wrote: > Look at using reduce(). ?You can collect information about all of the > nodes without necessarily building a large, intermediate list in the > process. From the OP's description, I assumed there'd be a list of all nodes, from which he wishes to derive a 2nd list of specific nodes. reduce() applies "a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value", which doesn't seem to me to be what the OP was asking for. I could understand using map() across the filter'd list, or embedding the conditional check within the map'd function and ignoring filter(), but at no point does the OP ask to perform any kind of function based on two nodes... I may have misunderstand your point, though :) Could you provide a quick code sample to clarify? From skeept at gmail.com Thu Jul 10 17:46:50 2008 From: skeept at gmail.com (skeept) Date: Thu, 10 Jul 2008 14:46:50 -0700 (PDT) Subject: redirecting output of process to a file using subprocess.Popen() References: <515ad1dd-15b0-4f7a-8ea2-87e0bb0cb47e@f36g2000hsa.googlegroups.com> Message-ID: <6bed3372-e049-4301-9d6b-6b7cf0a4c2d9@y21g2000hsf.googlegroups.com> On Jul 9, 7:32?pm, rpar... at gmail.com wrote: > I am trying to redirect stderr of a process to a temporary file and > then read back the contents of the file, all in the same python > script. As a simple exercise, I launched /bin/ls but this doesn't > work: > > #!/usr/bin/python > import subprocess as proc > import tempfile > name = tempfile.NamedTemporaryFile(mode='w+b') > print 'name is '+ name.name > > cmd = [] > cmd.append('/bin/ls') > cmd.append('-l') > cmd.append('/tmp') > p = proc.Popen(cmd, stdout=name, stderr=proc.STDOUT, close_fds=True) > while True: > ? ?ret = p.poll() > ? ?if (ret is not None): > ? ? ? output = name.readlines() > ? ? ? print 'out = ', output > ? ? ? break > > $python sub.py > name is /tmp/tmpjz4NJY > out = ?[] > > I tried calling flush() on the file object but this didn't help > either. Tried closing and re-opening the file, but closing the file > object results in it getting deleted. Can the above be made to work by > using tempfiles? > > thanks your script works just fine. The problem is that you have to move to the beggining of the file to read the actual contents of the file. name.seek(0) The whole program would be: #!/usr/bin/python import subprocess as proc import tempfile name = tempfile.NamedTemporaryFile(mode='w+b') print 'name is '+ name.name cmd = [] cmd.append('/bin/ls') cmd.append('-l') cmd.append('/tmp') p = proc.Popen(cmd, stdout=name, stderr=proc.STDOUT, close_fds=True) while True: ret = p.poll() if (ret is not None): name.seek(0) output = name.readlines() print 'out = ', output break From no at spam.no Fri Jul 11 03:01:19 2008 From: no at spam.no (Thin Myrna) Date: Fri, 11 Jul 2008 09:01:19 +0200 Subject: ActiveState Code: the new Python Cookbook site References: <4873F326.5010905@activestate.com> <4874698E.7000805@gmail.com> Message-ID: <4877053f$0$16181$5402220f@news.sunrise.ch> Trent Mick wrote: > Stef Mientki wrote: >> one small remark, >> If I want to browse 200 recipes, at 10 per page .... >> ... please make something like 100 available per page, >> are internet is fast enough nowadays. > > Touche. Done: > > http://code.activestate.com/recipes/?paginate_by=100 > The old cookbook offered choices by category. Did you drop that feature? > Cheers, > Trent > Thin From rw.segaar at xs4all.nl Wed Jul 9 15:23:20 2008 From: rw.segaar at xs4all.nl (Robert) Date: Wed, 9 Jul 2008 21:23:20 +0200 Subject: formatting list -> comma separated Message-ID: <48750e4f$0$15106$e4fe514c@dreader27.news.xs4all.nl> given d: d = ["soep", "reeds", "ook"] I want it to print like soep, reeds, ook I've come up with : print ("%s"+", %s"*(len(d)-1)) % tuple(d) but this fails for d = [] any (pythonic) options for this? Robert From bj_666 at gmx.net Tue Jul 15 11:44:26 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Jul 2008 15:44:26 GMT Subject: Python internals question References: Message-ID: <6e3uuqF527ucU2@mid.uni-berlin.de> On Tue, 15 Jul 2008 23:54:46 +1000, Peter Anderson wrote: > "Python is a dynamically typed language in which names can represent > values of different types during the execution of a program. In fact the > names used in the program are really just labels for various quantities > and objects. The assignment operator simply creates an association > between a name and a value. This is different from C, for example, in > which a name (variable) represents a fixed size and location in memory..." > > As an old mainframe programmer, I understand the way C does things with > variable but this text got me wondering how Python handles this > "association" between variable name and value at the lower level. Is it > like a fifo list? Why a fifo list? Names don't remember the values and types they are bound to over time, there's just one binding at any time if a name exists. Internally you can think of a pointer to a struct that represents the object. Ciao, Marc 'BlackJack' Rintsch From walter at livinglogic.de Thu Jul 3 17:48:27 2008 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Thu, 03 Jul 2008 23:48:27 +0200 Subject: ANN: XML builder for Python In-Reply-To: <10df03a30807030812g201f35aet87477a245ae71fc4@mail.gmail.com> References: <486C5CA1.3080105@behnel.de> <486C5D63.5030407@behnel.de> <486CB9F3.3020902@livinglogic.de> <10df03a30807030812g201f35aet87477a245ae71fc4@mail.gmail.com> Message-ID: <486D492B.9070706@livinglogic.de> Jonas Galvez wrote: > Walter D?rwald wrote: >> XIST has been using with blocks since version 3.0. >> [...] >> with xsc.Frag() as node: >> +xml.XML() >> +html.DocTypeXHTML10transitional() >> with html.html(): >> [...] > > Sweet! I don't like having to use the unary operator tho, I wanted > something as simple as possible, so I wouldn't even have to assign a > variable on the with block ("as something"). You only have to assign the node a name in the outermost with block so that you can use the node object afterwards. But of course you can always implement the outermost __enter__/__exit__ in such a way, that the node gets written to an outputstream immediately. > I plan to add some > validation and error checking, but for generating feeds for my Atom > store it's reasonably fast and lean (just over 50 lines of code). Servus, Walter From fredrik at pythonware.com Thu Jul 24 07:48:39 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 13:48:39 +0200 Subject: how to cut and paste in the windows of python(command line) In-Reply-To: <9500663c-0985-4dfd-8d0a-ae25411f00e5@v39g2000pro.googlegroups.com> References: <9500663c-0985-4dfd-8d0a-ae25411f00e5@v39g2000pro.googlegroups.com> Message-ID: fang wrote: > The mouse cannot be responded in the windows of python(command > line) and cut and paste cannot be done. ctrl c and ctrl v do not work. > But they do work in IDLE. that has absolutely nothing to do with Python, and everything to do with what console or terminal program you're using. if you're using windows, you'll find edit commands, including copy and paste, commands in the window menu (click on the icon in the upper left corner). Python also supports the standard "doskey" commands (text+F8 to search in history, UP/DOWN to recall commands, ESC to clear, etc). if you want better console support, consider installing the "ipython" shell: http://ipython.scipy.org/moin/ From tjreedy at udel.edu Thu Jul 24 21:21:46 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jul 2008 21:21:46 -0400 Subject: Encoding for Devanagari Script. In-Reply-To: References: Message-ID: Atul. wrote: > Hello All, > > I wanted to know what encoding should I use to open the files with > Devanagari characters. I was thinking of UTF-8 but was not sure, any > leads on this? Anyone used it earlier? You cannot hurt your machine by giving that a try. This is a general comment for all beginners. Before posting, open the interactive interpreter (or IDLE) and try something(s). If the result puzzles you, copy and paste into a post. Or if more appropriate, open the Python manuals and search a bit, or try a search engine. From motoom at xs4all.nl Sat Jul 12 08:45:53 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Sat, 12 Jul 2008 14:45:53 +0200 Subject: Use of index Message-ID: <2.2.32.20080712124553.00ca3e8c@pop.xs4all.nl> SUBHABRATA wrote... > Now, my q is can we use index like find? Yes, you can. There is only a difference when the string is not found: the 'find()' function will return -1, whereas 'index()' function will raise a ValueError exception. For example: >>> b="A spaghetti monster is always great" >>> print "monster" in b True >>> print b.find("monster") 12 >>> print b.index("monster") 12 >>> print b.find("pasta") -1 >>> print b.index("pasta") Traceback (most recent call last): File "", line 1, in print b.index("pasta") ValueError: substring not found >>> This is also documented in the built-in help: >>> help(b.index) Help on built-in function index: index(...) S.index(sub [,start [,end]]) -> int Like S.find() but raise ValueError when the substring is not found. >>> help(b.find) Help on built-in function find: find(...) S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. Hope this helps, Greetings -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From code at pizzashack.org Mon Jul 21 12:36:59 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 21 Jul 2008 12:36:59 -0400 Subject: Change PC to Win or Windows In-Reply-To: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> Message-ID: <20080721163659.GB8793@dragontoe.org> On Sat, Jul 19, 2008 at 02:56:07AM -0700, Lie wrote: > On Jul 19, 6:14?am, Derek Martin wrote: > > On Fri, Jul 18, 2008 at 03:46:13PM -0700, Joel Teichroeb wrote: > > Much like the English word "bank" (and numerous others), the term "PC" > > has come to have several meanings, one of which is the above. ?You may > > not like it, but we're pretty much stuck with the term, so you may as > > well get used to it. > > That's not the point, It very much IS the point. Language evolves based on common usage patterns of the people who use it. The term "PC" is commonly used in English, in the United States and other English speaking countries, to mean a computer running Microsoft Windows. That's a simple fact that you can not escape, no matter how much you may not like it (it just so happens that I also don't like it, but I realized long ago the futility of arguing against its usage). It's still a fact, and I described roughly how that fact came to be. It wasn't something that Apple started; it's been used this way in increasingly common usage for at least 20 years, although exactly what combination of hardware and software was being refered to as a "PC" has evolved over that timeframe. PC was a short form of "personal computer", which is how IBM came up with the name. Nevertheless, with the ubiquity of IBM hardware, and subsequent popularity of clones running Microsoft operating systems, the term "PC" has, in the present day, come to mean "a personal computer based on Intel-compatible hardware running a flavor of Microsoft Windows." It is used this way by the consumer computer industry, and it is used this way by the common population. Ipso facto "PC" means a windows box, in common English usage today. You don't have to like it, and you don't even have to acknowledge it. But if you choose not to, or argue against using it that way, you're in denial, plain and simple. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From fredrik at pythonware.com Thu Jul 24 07:58:18 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 13:58:18 +0200 Subject: Requires a character ... !! In-Reply-To: References: Message-ID: John Machin wrote: > You don't need a crystal ball; you just need to have been reading this > group/list for the last day or so --- the OP is trying to use Python > 2.2 on some *.py that are obviously written for a later version, > refuses to contemplate upgrading, and starts a new thread every time > he gets a syntax error. The traceback indicates that this is some software for working with debug data (http://dwarfstd.org/), but neither Google nor Kodos finds anything similar to the code you see in the tracebacks, so it's probably some proprietary stuff. And for some reason, the OP seems to be a bit unwilling to ask the supplier for help... From deets at nospam.web.de Wed Jul 30 13:25:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 30 Jul 2008 19:25:31 +0200 Subject: Standard module for parsing emails? References: <48908EF7.7060301@gmail.com> Message-ID: <6fbmilFanjibU1@mid.uni-berlin.de> Maric Michaud wrote: > Le Wednesday 30 July 2008 17:55:35 Aspersieman, vous avez ?crit?: >> For parsing the mails I would recommend pyparsing. > > Why ? email module is a great parser IMO. He talks about parsing the *content*, not the email envelope and possible mime-body. Diez From roy at panix.com Sat Jul 12 15:41:52 2008 From: roy at panix.com (Roy Smith) Date: Sat, 12 Jul 2008 15:41:52 -0400 Subject: why is "self" used in OO-Python? References: Message-ID: In article , Duncan Booth wrote: > Sadly a lot of Java programmers mistake the limitations of their language > for rules of OO programming, and worse this has spread from Java into other > languages where these restrictions no longer need apply. You can generalize that to, "a lot of programmers assume that OO is defined by whatever happens to be the first OO language they learn". In fact, it generalizes even further to the Law of Primacy (http://en.wikipedia.org/wiki/Principles_of_learning#Primacy). I recognize this drivel from the crud the FAA publishes: > Primacy, the state of being first, often creates a strong, almost unshakable, > impression. Things learned first create a strong impression in the mind that > is difficult to erase. For the instructor, this means that what is taught > must be right the first time. For the student, it means that learning must be > right. ?Unteaching? wrong first impressions is harder than teaching them > right the first time. If, for example, a student learns a faulty technique, > the instructor will have a difficult task correcting bad habits and > ?reteaching? correct ones. but fundamentally, it's true. If the first programming language (or the first OOPL) a person learns is Java, it should come as no surprise when they think they way Java does things is the only way to do things. Having seen no other ways yet, what else *could* they think? I have no objection to teaching Java in a CS curriculum. Or even making it the first language you teach. What I do object to is making it the ONLY language you teach. My next door neighbor's kid just finished a MSCS program. The curriculum did a pretty good job of covering most of the important topics, but they did it all in Java. Web development in Java, graphics programming in Java, algorithms in Java, etc. He's well prepared to get a job as a Java programmer (and, in fact, he did), but I don't think he's really trained to be a computer scientist. A good CS program should include a survey of different programming languages. Today, I would certainly want to give students exposure to C++, at least one of {Python,Ruby}, and a random sampling of some less main-line languages like Erlang, Lisp, PHP, Groovy, Smalltalk, or PostScript. Exactly which ones is not so important as getting to see a wide variety of different approaches. Only after you've seen a bunch of different ways of doing something can you start to appreciate the choices different language designers made. BTW, there's an interesting article in the July 2008 Computer Magazine: "In Priase of Scripting: Real Programming Pragmatism". Ronald Loui argues (amongst other things) that Python would make a good first language to teach in a CS curriculum. From sturlamolden at yahoo.no Fri Jul 11 14:16:37 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 11 Jul 2008 11:16:37 -0700 (PDT) Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> Message-ID: <13e282e4-cdf8-43f0-a42b-60158d36d56d@w7g2000hsa.googlegroups.com> On Jul 11, 12:00?pm, James Fassett wrote: > tuple_list = ( > ? ? ('John', 'Doe'), > ? ? ('Mark', 'Mason'), > ? ? ('Jeff', 'Stevens'), > ? ? ('Bat', 'Man') > ? ) > > # what I'd do in C or other procedural languages > result_list = [] > for item in tuple_list: > ? ? result_list.append(item[0]) Here are some various 'functional' solutions. Pick the one that fits your problem best: result_list = [fn for fn,ln in tuple_list] result_generator = (fn for fn,ln in tuple_list) result_list = map(lambda (fn,ln): fn, result_list) result_generator = itertools.imap(lambda (fn,ln): fn, result_list) From marcus at internetnowasp.net Mon Jul 21 12:17:44 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Tue, 22 Jul 2008 00:17:44 +0800 Subject: Python Written in C? In-Reply-To: References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> <4884B3EB.4090001@timgolden.me.uk> Message-ID: <4884B6A8.6070300@internetnowasp.net> Its called a BMW today. Fredrik Lundh wrote: > Tim Golden wrote: > >>> Wrong! Real programmers can program using only Touring machine >> >> Is that some kind of bicycle? > > there's a nearly infinite number of software projects with that name, > but the Ultimate Touring Machine could be found in sydney not long ago: > > http://tinyurl.com/5t2dl4 > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From s0suk3 at gmail.com Wed Jul 16 00:32:49 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Tue, 15 Jul 2008 21:32:49 -0700 (PDT) Subject: Modify a string's value References: Message-ID: <8c7245ed-2341-4283-988c-8a8adf3e58fd@56g2000hsm.googlegroups.com> On Jul 15, 6:46 pm, Larry Bates wrote: > s0s... at gmail.com wrote: > > Hi everyone, > > > I've heard that a 'str' object is immutable. But is there *any* way to > > modify a string's internal value? > > > Thanks, > > Sebastian > > Why would you care? Just create a new string (with the changed contents) and > let garbage collection take care of the old one when all the references to it > have gone away. Since these types of questions seem to appear almost every day > on this list, this Python stuff is so much different than old languages people > have hard time making the conceptual "jump". You can basically quite worrying > about how/where things are stored, they just are. > Thanks for the reply. It's not that I'm having a hard time learning Python. I've been programming it for some time. I just came across this unusual situation where I'd like to modify a string passed to a function, which seems impossible since Python passes arguments by value. (Whereas in C, you'd customarily pass a pointer to the first character in the string.) I was playing around trying to simulate C++-like stream operations: import sys from os import linesep as endl class PythonCout: def __lshift__(self, obj): sys.stdout.write(str(obj)) return self def __repr__(self): return "" cout = PythonCout() cout << "hello" << endl But then trying to simulate cin: class PythonCin: def __rshift__(self, string): string = sys.stdin.readline() # which doesn't make sense line = "" cin >> line And there goes the need to modify a string. :) From fredrik at pythonware.com Wed Jul 16 03:31:30 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 09:31:30 +0200 Subject: Is this correct behavior for default parameters? In-Reply-To: <344469045.20080716120322@wn.com.au> References: <344469045.20080716120322@wn.com.au> Message-ID: Bruce Pearson wrote: > The first call to test has the file_list empty but on the second call to > test the file_list is no longer empty but contains the values appended > in the first call. > > Is this correct behavior? I'm using python 2.5 yes: http://docs.python.org/ref/function.html "Default parameter values are evaluated when the function definition is executed." (in bold, even) it's also explained in the tutorial (section 4.7.1) and in the FAQ. (it's always a good idea to double-check the documentation or google a little before convincing yourself that you may have found a bug in a commonly used part of a system that's over 15 years old and has been used by hundred of thousands of programmers). From fredrik at pythonware.com Mon Jul 21 17:10:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 23:10:35 +0200 Subject: imported module no longer available In-Reply-To: <8496caf30807210931y27f5a198q195c9fb752eea5f3@mail.gmail.com> References: <8496caf30807210656y3d8467eer83a953e7c37e556c@mail.gmail.com> <8496caf30807210928m27456a1ex747221ea829409a6@mail.gmail.com> <8496caf30807210931y27f5a198q195c9fb752eea5f3@mail.gmail.com> Message-ID: Jeff Dyke wrote: >> actually no, the only things in that fucntion were. >> print globals().keys() - i see it here >> print mymodulename - it fails here. >> >> the `import mymodulename` statement is at the very top of the file. >> >> plus the processing that was attempted after. so how did that processing use the "mymodulename" name? >> in fact in the calling >> method i was able to execute print mymodulename and it printed the >> expected python output. the calling method has nothing to do with what's considered to be a local variable in the method being called, so that only means that the name is indeed available in the global scope. >> So i went back to check that the name 'mymodulename' was not getting >> overwritten by something else and the error went away. I've been >> working on something else entirely for the past few hours and have >> changed none of the code...and now it works. which is even more >> troublesome then the error itself. more likely, it indicates that you removed the line that caused Python to treat that name as a local variable. >> Follow on question. If this name, mymodulename, was imported in some >> other module.fucntion local to a function like >> def anotherfunc(): >> import mymodulename >> >> would that remove it from the globals() and save it to a locals() ? I >> would assume the answer to be no. even after reading the page I pointed you to? import binds a name, so an import statement inside a function will cause Python to treat that name as a local variable (unless you add a global declaration to that function). maybe a few examples will make this clearer; the following snippets are complete programs: snippet 1: import module # adds module to the global namespace def func(): module.func() # uses module from the global namespace func() # no error here snippet 2: def func(): import module # adds module to the *local* namespace module.func() func() # no error here module.func() # doesn't work; no module in global namespace snippet 3: def func(): global module # marks module as a global name import module # adds module to the *global* namespace module.func() func() # no error here module.func() # no error here; global module set by function snippet 4: import module # adds module to global namespace def func(): import module # adds module to local namespace too print module # prints local variable module = None # sets local variable to None func() # no error here module.func() # no error here either; uses global namespace snippet 5: import module def func(): print module # fails with an UnboundLocalError. # lots of lines import module # adds to local namespace; marks name as local # some more code func() # will fail at print statement my guess is that the last snippet corresponds to your case. From mariusz.karpowicz.84 at gmail.com Thu Jul 17 10:46:35 2008 From: mariusz.karpowicz.84 at gmail.com (=?ISO-8859-2?Q?Mariusz_=28Bia=B3ystok=29?=) Date: Thu, 17 Jul 2008 07:46:35 -0700 (PDT) Subject: twistedmatrix Message-ID: <9b545be3-4ab4-4398-933b-f75ac3dca03a@x41g2000hsb.googlegroups.com> Hi. I'm newbie in Twisted. Can anyone explain how does twisted server work? What happens after reactor.listenTCP running? I've got many connections from one client (one connection-one socket), each of them is served by class serve(Protocol). every protocol owns transport every transport owns socket for me it's obvious that protocol returning data to client should use it's own socket but transport.write(data) writes data into buffer what happens then? when my server handles two requests from one client (one by one) it writes first data part to buffer, then second part ... and then writes back to socket. what more it buffers data when I start many clients and sends it to last one. help me? please? Mariusz From gagsl-py2 at yahoo.com.ar Wed Jul 30 20:47:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 21:47:06 -0300 Subject: proxy class and __add__ method References: <18715799.post@talk.nabble.com> <18730676.post@talk.nabble.com> Message-ID: En Wed, 30 Jul 2008 07:48:45 -0300, Magnus Schuster escribi?: >> __magic__ methods on new style classes are searched in the class, *not* >> in >> the instance. prx_i+1 looks for __add__ in type(prx_i), that is, in the >> proxy class. > > With this explanation the behaviour is absolutely clear. Can I find some > documentation anywhere containing more background information how magic > functions are resolved? I haven't been successful with the Python > Language > Reference. There is some documentation collected in http://www.python.org/doc/newstyle/ and you can see also PEP252 and PEP253... >> Try implementing a similar __getattr__ method in a metaclass. > > I am totally clueless how to do this. Below you find my attempt. Neither > __getattr__ nor __add__ of the metaclass 'meta' are ever called. May I > ask > you for some more guidance or corrections to the code below? Unfortunately, as you have noted, my suggestion of using a metaclass with __getattr__ doesn't work. That method isn't invoked when resolving those names. I've found this recipe http://code.activestate.com/recipes/252151/ which goes step by step: first a Proxy for old-style classes that works fine, then a version for new-style classes identical to yours, then a metaclass version with __getattr__ that doesn't work either, and finally a working version. Very nice example. Another -more complete- version is at http://code.activestate.com/recipes/496741/ I hope you can adapt these to match your requirements. -- Gabriel Genellina From workitharder at gmail.com Mon Jul 28 13:34:40 2008 From: workitharder at gmail.com (bukzor) Date: Mon, 28 Jul 2008 10:34:40 -0700 (PDT) Subject: Easier way to get the "here" path? References: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> Message-ID: <649bb102-51aa-4781-ad40-3762e59db626@56g2000hsm.googlegroups.com> On Jul 26, 9:19?am, Andrew wrote: > bukzor wrote: > >>>> from os.path import abspath, realpath > >>>> realpath(path.__file__.rstrip("c")) > > > '/home/bgolemon/python/symlinks/path.py' > > >>>> realpath(abspath(path.__file__.rstrip("c"))) > > > '/home/bgolemon/python/symlinks/symlinks/path.py' > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I find it interesting that I get something different: > > In [1]: import path > path.pyc > > In [2]: path.__file__ > Out[2]: 'path.pyc' > > In [3]: path.__file__.rstrip("c") > Out[3]: 'path.py' > > In [4]: from os.path import abspath, realpath > > In [5]: realpath(path.__file__.rstrip("c")) > Out[5]: '/home/andrew/sym/sym/path.py' > > In [6]: realpath(abspath(path.__file__.rstrip("c"))) > Out[6]: '/home/andrew/sym/sym/path.py' > > I get the same thing for realpath() and realpath(abspath()) > It seems to me you can just use: > > In [1]: import path > path.pyc > > In [2]: from os.path import abspath > > In [3]: realpath(path.__file__.rstrip("c")) > Out[3]: '/home/andrew/sym/sym/path.py' > > By the way, I am in /home/andrew/sym and path is symlinked from > /home/andrew/sym/sym/path.py to /home/andrew/sym/path.py > > -- > Andrew As you can see above, I get the wrong think if I do that. It's very strange that we're getting different things. I'm using python 2.4, maybe it was updated in 2.5? From tdelaney at avaya.com Mon Jul 28 19:45:33 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 29 Jul 2008 07:45:33 +0800 Subject: Getting python 2.4 dll In-Reply-To: Message-ID: Guillermo wrote: > Hi there, > > Is it possible to get a 2.4 dll of python for Windows easily? I need > it to use python as scripting language for Vim. http://www.python.org/ which leads you to: http://www.python.org/download/ which leads you to: http://www.python.org/download/releases/2.4.5/ which leads you to (for a binary release): http://www.python.org/download/releases/2.4.4/ Further questions along this line should be directed to: http://www.catb.org/~esr/faqs/smart-questions.html#before Tim Delaney From bj_666 at gmx.net Wed Jul 16 10:35:35 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Jul 2008 14:35:35 GMT Subject: Logging in __del__() References: <17056.2125546441$1216121658@news.gmane.org> Message-ID: <6e6f9nF5eajaU2@mid.uni-berlin.de> On Wed, 16 Jul 2008 12:38:50 +0100, Robert Rawlins wrote: > So, am I right to assume that python will still handle its garbage disposal > if I implement __del__(), it just handles circular references in a slightly > different way, but to the same effect. Right? No. Circular references in objects with a `__del__()` implementation are not collected! Why are you using `__del__()` anyway? Are you aware of the promises that are *not* made! It's not guaranteed when the method is called nor if it is called at all! Ciao, Marc 'BlackJack' Rintsch From circularfunc at gmail.com Wed Jul 9 22:07:55 2008 From: circularfunc at gmail.com (ssecorp) Date: Wed, 9 Jul 2008 19:07:55 -0700 (PDT) Subject: TypeError, I know why but not how!? Message-ID: <03cbb0d2-6a0c-4b86-a75e-b73c5677acc7@c65g2000hsa.googlegroups.com> Im looking into PvsNP: http://www.claymath.org/millennium/P_vs_NP/ so I thought I'd write the program just to get a feel for it. But I run into a problem. Why does it all the sudden return None? I mean I know why the program aborts but I dont understand why the None is generated all the sudden. Hitting recursion depth isn't reported with that error. Guess I am missing something very obvious. Traceback (most recent call last): File "C:\Python25\Progs\PNP\pnp.py", line 34, in gen(50) File "C:\Python25\Progs\PNP\pnp.py", line 32, in gen return generateList([], [(1,10),(4,272),(34,442),(112,42)], [], rooms) File "C:\Python25\Progs\PNP\pnp.py", line 27, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 27, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 27, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 27, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 27, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 25, in generateList room, placed = pair(incompatibles, placed) File "C:\Python25\Progs\PNP\pnp.py", line 12, in pair student1, placed = validate(placed) TypeError: 'NoneType' object is not iterable >>> ---------------------------------- the program: import random def validate(placed): student = round(random.random()*401) if student in placed: validate(placed) else: placed.append(student) return student, placed def pair(incompatibles, placed): student1, placed = validate(placed) student2, placed = validate(placed) pair1 = (student1,student2) pair2 = (student2,student1) if (pair1 or pair2) in incompatibles: placed.remove(student1) placed.remove(student2) pair(incompatibles, placed) else: return pair1, placed def generateList(dormlist,incompatibles, placed, rooms): if len(dormlist) < (rooms + 1): room, placed = pair(incompatibles, placed) dormlist.append(room) generateList(dormlist,incompatibles,placed,rooms) else: return dormlist def gen(rooms): return generateList([], [(1,10),(4,272),(34,442),(112,42)], [], rooms) gen(50) ------------------------------------------------------------------------------------------------------------------- some tests inserted: import random def validate(placed): student = round(random.random()*401) if student in placed: validate(placed) else: placed.append(student) return student, placed def pair(incompatibles, placed): x = validate(placed) print "x",x y = validate(placed) print "y",y print "-------------------------------------" student1, placed = x student2, placed = y #student1, placed = validate(placed) #student2, placed = validate(placed) pair1 = (student1,student2) pair2 = (student2,student1) if (pair1 or pair2) in incompatibles: placed.remove(student1) placed.remove(student2) pair(incompatibles, placed) else: return pair1, placed def generateList(dormlist,incompatibles, placed, rooms): ## print dormlist ## print placed ## print "---------------------------------------------------" if len(dormlist) < (rooms + 1): room, placed = pair(incompatibles, placed) dormlist.append(room) generateList(dormlist,incompatibles,placed,rooms) else: return dormlist def gen(rooms): return generateList([], [(1,10),(4,272),(34,442),(112,42)], [], rooms) gen(50) ------------------------ x (283.0, [283.0]) y (8.0, [283.0, 8.0]) ------------------------------------- x (359.0, [283.0, 8.0, 359.0]) y (158.0, [283.0, 8.0, 359.0, 158.0]) ------------------------------------- x (249.0, [283.0, 8.0, 359.0, 158.0, 249.0]) y (371.0, [283.0, 8.0, 359.0, 158.0, 249.0, 371.0]) ------------------------------------- x (199.0, [283.0, 8.0, 359.0, 158.0, 249.0, 371.0, 199.0]) y (292.0, [283.0, 8.0, 359.0, 158.0, 249.0, 371.0, 199.0, 292.0]) ------------------------------------- x None y (227.0, [283.0, 8.0, 359.0, 158.0, 249.0, 371.0, 199.0, 292.0, 47.0, 227.0]) ------------------------------------- Traceback (most recent call last): File "C:\Python25\Progs\PNP\pnp.py", line 44, in gen(50) File "C:\Python25\Progs\PNP\pnp.py", line 42, in gen return generateList([], [(1,10),(4,272),(34,442),(112,42)], [], rooms) File "C:\Python25\Progs\PNP\pnp.py", line 37, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 37, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 37, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 37, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 35, in generateList room, placed = pair(incompatibles, placed) File "C:\Python25\Progs\PNP\pnp.py", line 17, in pair student1, placed = x TypeError: 'NoneType' object is not iterable From grahn+nntp at snipabacken.se Mon Jul 7 13:57:14 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 7 Jul 2008 17:57:14 GMT Subject: Cross Compiler for Python? References: Message-ID: On Mon, 7 Jul 2008 10:15:59 +0200, Hendrik van Rooyen wrote: > Up to now, I have been innocently using the vanilla python > that comes with the Linux distribution (Suse in my case). > > For the past few days, I have been playing with a little > device called an eBox - it is basically a 486 with 128Mb > memory, and a 1Gig pcmcia flash drive. > > We want to try to use this as an industrial controller, so > I want to load python onto it. > > So I downloaded the sources, and got them into the box, > over its ethernet connection. > > Then I got stymied - the configure script will not run, > because the "distribution" has no C compiler - it is > basically a kernel, and Busybox, with precious little else. ... This is a special case of a more general, non-Python problem which you will have to address if you want to build an industrial controller. If your target has no C compiler[1], you have to set up a cross-compiling environment. I'd be surprised if the eBox doesn't come with documentation covering this. If there are special procedures and requirements for cross-compiling Python (someone else indicated there are), I guess the Python installation notes must cover this in a general way. /Jorgen [1] Or even if it has one. It is much more convenient to build in your normal work environment where you have plenty of disk, CPU and RAM, a good text editor, version control, Perl ... -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From davidreynon at gmail.com Thu Jul 24 16:48:46 2008 From: davidreynon at gmail.com (korean_dave) Date: Thu, 24 Jul 2008 13:48:46 -0700 (PDT) Subject: Neat way to get rid of [" "] in sys.argv[n:] returns Message-ID: so, i code this: ----------------------------- #!/usr/bin/python import sys import os for param in os.environ.keys(): print "%20s %s" % (param,os.environ[param]) print(os.environ['PATH']) print(sys.argv[1:]) -------------------------- and then when i type in --> python test.py "testparameter" I get this output: ------------- ['testparameter'] ---------------- Is there a way to neatly, in one call to the parameter, to get rid of the [' and '] without bothering to replace() '[ with "" and replace() '] with ''? Thanks, From phil.lemelin at gmail.com Fri Jul 18 09:45:19 2008 From: phil.lemelin at gmail.com (phil lemelin) Date: Fri, 18 Jul 2008 09:45:19 -0400 Subject: Core Dump - Segmentation Fault -Newbie In-Reply-To: <8ba4373d-3d97-4e9a-a15e-723f6818c757@k36g2000pri.googlegroups.com> References: <8ba4373d-3d97-4e9a-a15e-723f6818c757@k36g2000pri.googlegroups.com> Message-ID: I would suggest importing traceback. import traceback try : mystuff except : print str(traceback.format_exc()) But in the case of a SegFault or core dump, it might not help you at all. Can you post part of the function ? On Fri, Jul 18, 2008 at 9:25 AM, wrote: > Hi - I am very new to python. I get this random core dump and am > looking for a good way to catch the error. I know the function my core > dump occurs. Is there any error catching/handling that I could use in > python? > -- > http://mail.python.org/mailman/listinfo/python-list > -- Philippe-Alexandre Lemelin -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Jul 25 18:10:17 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Jul 2008 18:10:17 -0400 Subject: Histogram of floating point values. In-Reply-To: <73045cca0807251502i58c6e83dt872c46a9e7bb6775@mail.gmail.com> References: <73045cca0807251502i58c6e83dt872c46a9e7bb6775@mail.gmail.com> Message-ID: aditya shukla wrote: > Hello folks, > > I have a list say > > data=[0.99,0.98,0.98,0.98,0.97,0.93,0.92,0.92,0.83,0.66,0.50,0.50] > > i am trying to plot histogram of these values > > i have installed numpy and matplotlib and this is what i am doing* > import numpy > import pylab > from numpy import * > from pylab import * > > input_hist=array(data) > pylab.hist(input_hist,bins=0.1) > and this is the error that i am getting > > _*(array([], dtype=int32), array([ 0.5]), )*_ > > > does this mean that i cannot plot a histogram of floating point values ? > or is there a way around Ask the pylab (matplotlib?) people what their error message means. From timr at probo.com Tue Jul 29 02:46:56 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 29 Jul 2008 06:46:56 GMT Subject: interpreter vs. compiled References: <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> Message-ID: castironpi wrote: > >In CPython yes. In IronPython yes: the parts that are compiled into >machine code are the interpreter, *not user's code*. WRONG! You are WRONG. At "compile" time, the Python code is compiled to an intermediate language. At "run" time, the intermediate language (which is still the user's code, just in another representation) is compiled into machine language. It is the user's program, not the interpreter. It's the exact same process that occurs in a C compiler. Most C compilers translate the C program to an intermediate form before finally converting it to machine language. The only difference is that, in a C compiler, both steps occur within the compiler. In IronPython, the two steps are separated in time. There is no other difference. >Without that >step, the interpreter would be running on an interpreter, but that >doesn't get the user's statement 'a= b+ 1' into registers-- it gets >'push, push, add, pop' into registers. You have a fundamental misunderstanding of the compilation process. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From basti.wiesner at gmx.net Sun Jul 6 14:13:37 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sun, 06 Jul 2008 20:13:37 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Mark Wooding : > Sebastian "lunar" Wiesner wrote: > >> I just wanted to illustrate, that the speed of the given search is >> somehow related to the complexity of the engine. >> >> Btw, other pcre implementation are as slow as Python or "grep -P". I >> tried a sample C++-code using pcre++ (a wrapper around libpcre) and saw >> it running equally long. > > So some other implementations are equally poor. I note that Perl itself > handles this case very quickly, as does Edi Weitz's CL-PPCRE library. I don't know about the latter, but perl doesn't use any smart algorithm, it just heavily relies on memoization to gain speed. This makes perl perform poorly in other situations, as mentioned in the paper cited by Mark Dickinson: # perl -e '("a" x 100000) =~ /^(ab?)*$/;' zsh: segmentation fault perl -e '("a" x 100000) =~ /^(ab?)*$/;' In Python on the other, this pattern works fine, at the cost of performance losses on other patterns. It'd be interesting to know, how CL-PPCRE performs here (I don't know this library). > Yes, Perl-compatible `regular expressions' are more complicated than > POSIX extended regular expressions; but that doesn't mean that you have > to implement them in a dumb way. Indeed, it stands to reason that > expressions describing truly regular languages can be matched using the > same old algorithms that grep uses. I completely agree. I'd just believe, that the combination of some finite state machine for "classic" expressions with some backtracking code is terribly hard to implement. But I'm not an expert in this, probably some libraries out there already do this. In this case, it'd be time to give pythons re engine a more sophisticated implementation ;) -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From elessar at nienna.org Mon Jul 21 10:27:35 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Mon, 21 Jul 2008 23:27:35 +0900 Subject: Python Written in C? In-Reply-To: <488498f0$0$15075$e4fe514c@dreader28.news.xs4all.nl> References: <488473b7$0$3470$426a74cc@news.free.fr> <488498f0$0$15075$e4fe514c@dreader28.news.xs4all.nl> Message-ID: <48849CD7.2010501@nienna.org> Martin P. Hellwig wrote: > I disagree he has upper management written all over him. > In any case, the OP should remember that programming languages are all theoretically the same: if you can do it in one language, then you can theoretically do it any other. When choosing a language, you just need to find one that (a) has the right tools to do the job (libraries, methods of deployment, supported platforms, etc.) and (b) that you and your team are comfortable using. Python has the tools to tackle a huge range of problems (you can often use the standard library when you would have to write C code from scratch), and many find it, dare I say, fun to use (whereas I find C# roughly equivalent to being shot). Whether you should use it depends on your domain and your team's preference. -Matt From norseman at hughes.net Mon Jul 7 17:17:59 2008 From: norseman at hughes.net (norseman) Date: Mon, 07 Jul 2008 14:17:59 -0700 Subject: How to bypass Windows 'cooking' the I/O? (One more time, please) II In-Reply-To: References: Message-ID: <48728807.1010708@hughes.net> Dennis Lee Bieber wrote: > On Mon, 07 Jul 2008 01:03:10 -0700, norseman > declaimed the following in comp.lang.python: > >> > >> > Normal file I/O sequence: >> > >> > fp = open(target, 'wb') >> > >> > fp.seek(-1, 2) >> > >> > fp.write(record) >> > >> >> Except it doesn't do that in Windows. See below. >> > I wouldn't expect that sequence to work on any system... The "w" > implies "create new file, or truncate existing file to 0-bytes, then > write data to it" -- with no seeking permitted. You must include the "+" > to do seeking, and if you want to retain the existing file contents you > probably need to open with "a+" ("a" for append). > > The rest of your situation I won't touch. Other than to wonder why > the situation hasn't hit any of the various database servers which must > be operating in binary mode, and perform lots of seeking... Surely > somewhere out someone else must have encountered a seek crossing an > apparent mark (which isn't a normal Windows sequence anyway -- > since Windows uses for EOL, I'd have expected to see a problem > if backing over a ) ============================================= "I wouldn't expect..." ABSOLUTELY CORRECT. No append because the hex-1A has to be overwritten. (use r+b) There can be only one of those and it has to be the last byte of the file. The hex-0D at the beginning of a 32 BYTE segment signifies end of structure definition. The hex-1A double checks the record count. (standard Ashton-Tate dBASE file) If someone wants to check it out, appending the hex-1A to each record and backing up one byte on each write reduces coding complexity and machine cycles considerably. "The rest of..." I have seen the answer posted but can't find it. I'm hoping someone has it, sees this and posts the original solution again. Or knows how to set things to bypass the nonsense and posts that. Steve norseman at hughes.net From kmtracey at gmail.com Fri Jul 18 22:52:32 2008 From: kmtracey at gmail.com (Karen Tracey) Date: Fri, 18 Jul 2008 22:52:32 -0400 Subject: Change in Decimal repr in Python 2.6 In-Reply-To: References: Message-ID: On Fri, Jul 18, 2008 at 10:12 PM, Terry Reedy wrote: > If answers here do not satisfy, the pydev list would be the place to > request that this change be put off until 3.0, when changes that break are > more permissible. I do not remember any discussion of this issue. You can > also post there via news.gmane.org/g.c.python.devel (the mail to news > gateway). > Thanks, I'll probably try posting to pydev. Karen -------------- next part -------------- An HTML attachment was scrubbed... URL: From knielsen73 at gmail.com Mon Jul 28 18:34:54 2008 From: knielsen73 at gmail.com (knielsen73 at gmail.com) Date: Mon, 28 Jul 2008 15:34:54 -0700 (PDT) Subject: derivative in numpy Message-ID: Hi, I am looking to do a simple derivative. I would expect such a function to be available in numpy, but can't find it. I have written my own, but just curious if anybody knows of such function in numpy. Cheers, Kim From 2007 at jmunch.dk Tue Jul 29 05:45:44 2008 From: 2007 at jmunch.dk (Anders J. Munch) Date: Tue, 29 Jul 2008 11:45:44 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <488e4d2d$0$5967$ba624c82@nntp06.dk.telia.net> <009e5e66$0$20313$c3e8da3@news.astraweb.com> Message-ID: <488ee6c9$0$4463$ba624c82@nntp02.dk.telia.net> Steven D'Aprano wrote: > On Tue, 29 Jul 2008 00:23:02 +0000, Steven D'Aprano wrote: > >> Dude. Dude. Just... learn some Python before you embarrass yourself >> further. > > > I'm sorry Anders, that was a needlessly harsh thing for me to say. I > apologize for the unpleasant tone. > > Still, __nonzero__ is a fundamental part of Python's behaviour. You > should learn about it. Hm, first you apologize, then you repeat the insult? That's no basis for a conversation. Bye from here. regards, Anders From gherron at islandtraining.com Wed Jul 30 11:31:25 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 30 Jul 2008 08:31:25 -0700 Subject: Pointers/References in Python? In-Reply-To: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> References: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Message-ID: <4890894D.8020303@islandtraining.com> boblatest at googlemail.com wrote: > Hello, > > I have a long list of memory-heavy objects that I would like to access > in differently sorted order. Let's say I'd like to have lists called > by_date or by_size that I can use to access the objects in the > specified order. > > Of course I can just build those lists naively by creating copies of > the original list and then sorting them according to my wishes. But > that would create huge memory overhead. Of course I could use lists of > indices into the "master" list, just as in C I'd create lists or > arrays of pointers into the original data. > > Is there a clever Python way to do this, or should I just use lists of > indices? > No need. A Python list contains *references* to objects, not copies of objects. (The same is true of variables, dictionaries, sets, and so on...). For example, in the following code, only one copy of HeavyObject exists, however, it is referred to many times. a = HeavyObject() b = a A = [a,b] B = [b,a] C = set([a,b]) D = {1:a, 2:b} ... and do on Implementation wise, a long list consumes about 4 bytes per list element (that's one address per), plus a tine amount of overhead. Gary Herron > I know there is a thing called "shallow copy" that has something to do > with not duplicating memory content but I don't understand the > concept. Maybe that's what would help here, too. > > Thanks, > robert > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Tue Jul 22 11:42:08 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 17:42:08 +0200 Subject: convert list of lists to list In-Reply-To: References: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> Message-ID: Fredrik Lundh wrote: >> ['klas* * *', 'mooi* * * *, 'koe', 'arm* * * (haar)', 'groei* * * * >> *'] > > if there's only one level of recursion, and the lists aren't too long, > you can simply do: > > sum(list_of_lists, []) oops. that's what you get for taking the subject line too literally... From bruno.42.desthuilliers at websiteburo.invalid Tue Jul 1 05:41:38 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 01 Jul 2008 11:41:38 +0200 Subject: Functions associated with a class. In-Reply-To: References: Message-ID: <4869fbcd$0$4459$426a74cc@news.free.fr> Kurda Yon a ?crit : > Hi, > > I start to learn the object oriented programing in Python. As far as I > understood, every class has a set of corresponding methods and > variables. Every object has a set of attributes. Some of these attributes are methods (which are thmeselves objects too), some are not. Some are in fact attributes of the class of the object accessed thru the instance (mostly, the methods), some are instance-specific (mostly, non-methods). > For me it is easy to understand a method as a one-argument Why "one-argument" ? A method can take as amny arguments as necessary. > function associated with a class. s/class/object/. While methods are usually attributes of the class (accessed thru an instance), nothing prevents you from adding methods on a per-instance basis. This set aside, truth is that methods are just thin wrapper objects around a function, an instance and/or a class. The responsability of the method object is to delegate call to it's function object, inserting the instance (or the class in the case of a classmethod) as the first argument. > For example, if I call "x.calc" and > "y.calc" and if "x" and "y" belongs to different classes I, actually, > call to different function (the first one is associated with the first > class and the second one with the second class). Here again, it's a bit more complex. But this is a correct enough description of the most common case. > If "x" and "y" > belongs to the same class, the "x.calc" and "y.calc" refer to the same > function Usually, yes, but not necessarily: def yadda(obj): print "yadda(%s)" % obj class Bar(object): def foo(self): print "foo(%s)" % self b1 = Bar() b1.foo() b2 = Bar() b2.foo() b2.foo = yadda.__get__(b2, type(b2)) b2.foo() > (but called with different arguments ("x" and "y", > respectively)). > > In the above described case we have one-argument function. But what > should we do if we one two have a two-argument function. class Baaz(object): def gluuk(self, other): print "gluuk(%s, %s)" % (self, other) > For example, > we want to have a method "calc" which take two objects and returns one > value. How do we call this method? Like "x&y.calc"? class X(object): def calc(self, other): # this is silly since we don't use neither # self nor other, but you get the idea return "one value" Nope. > Or just calc(x,y)? That's one of the possibilities, but it's not a method anymore, just a plain function. The others solutions are either "x.calc(y)" or "y.calc(x)". Now which one is the right one depends on what calc do and how it relates to the respective classes of x and y. If the operation is really a responsability of one of the classes, then it should be a method of this class. Else it's probably better to stick to a plain function. > In the case of the one-argument functions Pythons automatically decide > which function to call Actually, x.calc() is (usually) a shortcut for type(x).calc(x), so you could say that in fact *you* make the decision of which function will be called !-) > (associated with the first class or with the > second class). Will it be the same in the case of the two-argument > function. It can't. OO polymorphic dispatch is (more or less by nature) a single dispatch mechanism. If you want a multiple dispatch (ie: dispatch on an arbitrary number of arguments) system, there are a couple packages providing this kind of features, but nothing builtin. Also, for a double dispatch mechanism, you can have a look at the Visitor design pattern. HTH From stesch at no-spoon.de Thu Jul 17 04:06:12 2008 From: stesch at no-spoon.de (Stefan Scholl) Date: Thu, 17 Jul 2008 10:06:12 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> <0T56p3tmInifNv8%stesch@parsec.no-spoon.de> <6e7v9qF5q74kU1@mid.uni-berlin.de> Message-ID: <0T56pitfI5raNv8%stesch@parsec.no-spoon.de> Marc 'BlackJack' Rintsch wrote: > On Thu, 17 Jul 2008 05:41:11 +0200, Stefan Scholl wrote: >> Fredrik Lundh wrote: >>> Stefan Scholl wrote: >>> >>>> Django isn't ready. >>> >>> That's a remarkably ignorant statement. >> >> The 1.0 release will be in September. > > So what? It's not the version number that matters but features and > stability. It's not uncommon in open source projects to have very usable > software with a version number below 1.0. The book is about the development version, which was current at the time the book was written. See page 4. Nobody says something about "Book after feature freeze" (or similar). Instead I get "ignorant statement" and "usable software". My conclusion: This book isn't about a stable release and not about a future stable release. (And even if it was about the last stable relase, too much has changed and will change until September 2008. IMHO.) And by the way: The quote was changed by deleting something on the same line: "June 2008 is a bit too early. Django isn't ready." vs. "Django isn't ready." -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 9 05:09:04 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 09 Jul 2008 11:09:04 +0200 Subject: Regular Expressions Quick Question In-Reply-To: References: Message-ID: <48748001$0$11973$426a74cc@news.free.fr> Rajanikanth Jammalamadaka a ?crit : (top-post corrected - Please, Rajanikanth, learn to trim"e properly, and by all means avoid top-posting) > > On Wed, Jul 9, 2008 at 12:13 AM, Lamonte Harris wrote: >> Alright, basically I have a list of words in a file and I load each word >> from each line into the array. I assume you meant 'list' ? > Then basically the question is how do I >> check if the input word matches multiple words in the list. >> >> Say someone input "test", how could I check if that word matches these list >> of words: >> >> test >> testing >> tested >> >> Out of the list of >> >> Hello >> blah >> example >> test >> ested >> tested >> testing >> >> I want it to loop then check if the input word I used starts any of the >> words in the list so if I typed 'tes' >> >> Then: >> >> test >> testing >> testing I assume you meant: test tested testing >> would be appended to a new array. > hi! > > Try this: > >>>> lis=['t','tes','test','testing'] >>>> [elem for elem in lis if re.compile("^te").search(elem)] Using a regexp for this is total overkill. But please at least use the proper regexp, and use re.compile correctly: exp = re.compile(r'^tes') found = [word for word in lis if exp.match(word)] But you just don't need a regexp for this - str.startswith is your friend: words = ['Hello', 'blah', 'example', 'test', 'ested', 'tested', 'testing'] found = [word for word in words if word.starswith('tes')] assert found == ['test', 'tested', 'testing'] HTH From ojeeves at gmail.com Fri Jul 18 08:21:19 2008 From: ojeeves at gmail.com (oj) Date: Fri, 18 Jul 2008 05:21:19 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> Message-ID: <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> On Jul 18, 12:10?pm, John Machin wrote: > On Jul 18, 9:05 pm, oj wrote: > > > > > On Jul 18, 11:33 am, arnimavidyar... at gmail.com wrote: > > > > Hi, > > > > Hi, > > > > I am taking a string as an input from the user and it should only > > > contain the chars:L , M or R > > > > I tried the folllowing in kodos but they are still not perfect: > > > > [^A-K,^N-Q,^S-Z,^0-9] > > > [L][M][R] > > > [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > > > > For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. > > > > regards, > > > SZ > > > > The string may or may not have all the three chars. > > > With regular expressions, [^LRM] matches a character that isn't L, R > > or M. So: > > > import re > > > var = "LRLRLRLNR" > > > if re.search(r'[^LRM]', var): > > ? ? print "Invalid" > > Fails if var refers to the empty string. No it doesn't, it succeeds if var is an empty string. An empty string doesn't contain characters that are not L, R or M. The OP doesn't specify whether an empty string is valid or not. My interpretation was that an empty string would be valid. From larry.bates at websafe.com` Sat Jul 19 16:31:47 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 19 Jul 2008 15:31:47 -0500 Subject: create instance attributes for every method argument In-Reply-To: <4780837f-a5bc-4071-94d3-28e2f206163e@k30g2000hse.googlegroups.com> References: <4780837f-a5bc-4071-94d3-28e2f206163e@k30g2000hse.googlegroups.com> Message-ID: Berco Beute wrote: > I remember reading somewhere how to create an instance attribute for > every method argument, but although Google is my friend, I can't seem > to find it. This could likely be done way more elegant: > > ========================= > class Test(object): > > def __init__(self, a, b, c, d, e, f): > self.a = a > self.b = b > self.c = c > self.d = d > ========================= > > 2B IMHO you can't do much better than that with positional arguments, but you can if they are keyword arguments. class foo(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) -Larry From andreas.mock at web.de Thu Jul 17 12:06:07 2008 From: andreas.mock at web.de (McA) Date: Thu, 17 Jul 2008 09:06:07 -0700 (PDT) Subject: unpacking with default values Message-ID: <335e7a21-e35e-41ee-9f92-fd4c2f6bf166@f36g2000hsa.googlegroups.com> Hi all, probably a dumb question, but I didn't find something elegant for my problem so far. In perl you can unpack the element of a list to variables similar as in python (a, b, c = [0, 1, 2]), but the number of variables need not to fit the number of list elements. That means, if you have less list elements variables are filled with 'undef' (None in python), if you have more list elements as necessary the rest is ignored. How can I achieve this behaviour with python in an elegant and fast way? Best regards Andreas Mock From basti.wiesner at gmx.net Wed Jul 23 12:00:26 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Wed, 23 Jul 2008 18:00:26 +0200 Subject: lxml, comparing nodes References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> Message-ID: code_berzerker : > I'd like to know if there is any built in mechanism in lxml that lets > you check equality of two nodes from separate documents. I'd like it > to ignore attribute order and so on. It would be even better if there > was built in method for checking equality of whole documents (ignoring > document order). Please let me know if you know of such method or > existing scipt. I dont like reinventing the wheel :) Did you try the equality operator? -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From code at pizzashack.org Sun Jul 27 23:39:18 2008 From: code at pizzashack.org (Derek Martin) Date: Sun, 27 Jul 2008 23:39:18 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <488ceae5$0$11227$426a34cc@news.free.fr> References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: <20080728033918.GG7373@dragontoe.org> On Sun, Jul 27, 2008 at 09:39:26PM +0200, Bruno Desthuilliers wrote: > >As for the latter part of #3, self (or some other variable) is > >required in the parameter list of object methods, > > It's actually the parameter list of the *function* that is used as the > implementation of a method. Not quite the same thing. The idea that Python behaves this way is new to me. For example, the tutorials make no mention of it: http://docs.python.org/tut/node11.html#SECTION0011300000000000000000 The Python reference manual has very little to say about classes, indeed. If it's discussed there, it's buried somewhere I could not easily find it. > consistency mandates that the target object of the method is part of > the parameter list of the *function*, since that's how you make > objects availables to a function. Fair enough, but I submit that this distinction is abstruse, and poorly documented, and also generally not something the average application developer should want to or have to care about... it's of interest primarily to computer scientists and language enthusiasts. The language should prefer to hide such details from the people using it. > >however when the method is *called*, it is omitted. > > Certainly not. Seems not so certain to me... We disagree, even after your careful explanation. See below. > You need to lookup the corresponding attribute *on a given object* > to get the method. Whether you write > > some_object.some_method() > > or > > some_function(some_object) > > you still need to explicitely mention some_object. But these two constructs are conceptually DIFFERENT, whether or not their implementation is the same or similar. The first says that some_method is defined within the name space of some_object. The second says that some_object is a parameter of some_function... Namespace != parameter!!!!!!!!! To many people previously familiar with OO programming in other languages (not just Java or C++), but not intimately familiar with Python's implementation details, the first also implies that some_method is inherently part of some_object, in which case explicitly providing a parameter to pass in the object naturally seems kind of crazy. The method can and should have implicit knowledge of what object it has been made a part. Part of the point of using objects is that they do have special knowledge of themselves... they (generally) manipulate data that's part of the object. Conceptually, the idea that an object's methods can be defined outside of the scope of the object, and need to be told what object they are part of/operating on is somewhat nonsensical... > >Thus when an object method is called, it must be called with one fewer > >arguments than those which are defined. This can be confusing, > >especially to new programmers. > > This is confusing as long as you insist on saying that what you > "def"ined is a method - which is not the case. I can see now the distinction, but please pardon my prior ignorance, since the documentation says it IS the case, as I pointed out earlier. Furthermore, as you described, defining the function within the scope of a class binds a name to the function and then makes it a method of the class. Once that happens, *the function has become a method*. To be perfectly honest, the idea that an object method can be defined outside the scope of an object (i.e. where the code has no reason to have any knowledge of the object) seems kind of gross to me... another Python wart. One which could occasionally be useful I suppose, but a wart nonetheless. This seems inherently not object-oriented at all, for reasons I've already stated. It also strikes me as a feature designed to encourage bad programming practices. Even discounting that, if Python had a keyword which referenced the object of which a given peice of code was a part, e.g. self, then a function written to be an object method could use this keyword *even if it is defined outside of the scope of a class*. The self keyword, once the function was bound to an object, would automatically refer to the correct object. If the function were called outside of the context of an object, then referencing self would result in an exception. You'll probably argue that this takes away your ability to define a function and subsequently use it both as a stand-alone function and also as a method. I'm OK with that -- while it might occasionally be useful, I think if you feel the need to do this, it probably means your program design is wrong/bad. More than likely what you really needed was to define a class that had the function as a method, and another class (or several) that inherits from the first. > The point is that you don't get access to the object "within itself". > You get access to an object *within a function*. Thus methods are not really methods at all, which would seem to suggest that Python's OO model is inherently broken (albeit by design, and perhaps occasionally to good effect). > The fact that a function is defined within a class statement doesn't > imply any "magic", It does indeed -- it does more than imply. It states outright that the function is defined within the namespace of that object, and as such that it is inherently part of that object. So why should it need to be explicitly told about the object of which it is already a part? It further does indeed imply, to hordes of programmers experienced with OO programming in other languages, that as a member, property, attribute, or what ever you care to call it, of the object, it should have special knowledge about the object of which it is a part. It just so happens that in Python, this implication is false. > IOW : there's one arguably good reason to drop the target object from > functions used as methods implementation, which is to make Python looks > more like Java No, that's not the reason. I don't especially like Java, nor do I use it. The reason is to make the object model behave more intuitively. >, and there's at least two good reason to keep it the way it is, >which are simplicity (no special case) and consistency (no special >case). Clearly a lot of people find that it is less simple TO USE. The point of computers is to make hard things easier... if there is a task that is annoying, or tedious, or repetitive, it should be done by code, not humans. This is something that Python should do automatically for its users. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From kyosohma at gmail.com Wed Jul 16 17:20:06 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 16 Jul 2008 14:20:06 -0700 (PDT) Subject: py2exe issues with pictures and icons References: <18493908.post@talk.nabble.com> <18495626.post@talk.nabble.com> Message-ID: <0c5dcb1e-11c2-4c3d-a485-625e76f00a95@m3g2000hsc.googlegroups.com> On Jul 16, 3:22?pm, Alexnb wrote: > Alexnb wrote: > > > Mike Driscoll wrote: > > >> On Jul 16, 1:37?pm, Alexnb wrote: > >>> Hello > > >>> I am sure most of you are familiar with py2exe. I am having a bit of a > >>> problem. See the program has a few pictures involved and the .ico it > >>> uses > >>> for the windows. However, the pictures are stored in the same directory > >>> as > >>> the source, something like: C:\Docs and settings\me\My > >>> docs\python\program. > >>> When I run the program for the interpreter, just as a .py, everything > >>> works > >>> just as it should. However, when I compile the main source as an .exe, > >>> and > >>> say let a friend try the program. It fails because it is missing the > >>> .ico. > >>> The catch, is I don't want to have it have to installed, at least at > >>> this > >>> point, I want it to be able to just run. So how can I make it just run > >>> from > >>> any computer with the files not being in the immediate directory. If > >>> that is > >>> not possible, how can I put them in the immediate directory and still > >>> make > >>> it work. Because that directory may change a lot so the path will > >>> change. > > >>> Just a few questions. I hope someone out there can help me out! > >>> -- > >>> View this message in > >>> context:http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp1849390... > >>> Sent from the Python - python-list mailing list archive at Nabble.com. > > >> Put the part of the code that needs the ico file(s) into a try/except > >> block. You could also try reading the py2exe wiki and tutorials. This > >> one looks like it has relevant data: > > >>http://www.py2exe.org/index.cgi/CustomIcons > > >> Mike > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > > Well, that may solve the icon problem. But what about getting pictures in > > there? > > Okay, the icon fix didn't really fix it, what it did was make the .exe have > the icon as the little picture for the shortcut, but it isn't really a > shortcut. Whatever. But, I went and ran it on another computer and this was > the error log it created right off the bat. > > Traceback (most recent call last): > ? File "The GUI.py", line 696, in > ? File "Tkinter.pyc", line 1515, in wm_iconbitmap > _tkinter.TclError: bitmap "C:\Documents and Settings\Alex\My > Documents\PYTHON\DictionaryApp\Windows.ico" not defined > > -- > View this message in context:http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp1849390... > Sent from the Python - python-list mailing list archive at Nabble.com. Crumb! I actually use a GUI wrapper for py2exe called GUI2Exe which makes this sort of thing much easier. Unfortunately, it also makes me less knowledgeable. You can check it out here: http://xoomer.alice.it/infinity77/main/GUI2Exe.html Also, there's a distutils group and a py2exe group. Both of them would know a lot more about how to do this. https://lists.sourceforge.net/lists/listinfo/py2exe-users http://www.python.org/community/sigs/current/distutils-sig/list/ Mike From bignose+hates-spam at benfinney.id.au Sun Jul 13 07:44:40 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 13 Jul 2008 21:44:40 +1000 Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> <85c3da91-9f2f-4d19-ba98-dfdc99b1e1e3@79g2000hsk.googlegroups.com> Message-ID: <87y746c8k7.fsf@benfinney.id.au> Bart Kastermans writes: > Roy Smith writes: > > The defensive thing to do is catch exactly the exception you > > expect to happen. In this case, that means IndexError. > > And you do that by > > except IndexError: > raise TheErrorYouNowWantToRaise You only do that if you want to throw away important information, such as the traceback associated with the original exception. Not very friendly to debugging. > And > except IndexError, e: > > if you want access to the exception as well. Usually best if it can be achieved. Not least because the bare 'raise' statement will re-raise the original exception, complete with all its context. -- \ ?If we don't believe in freedom of expression for people we | `\ despise, we don't believe in it at all.? ?Noam Chomsky, | _o__) 1992-11-25 | Ben Finney From upton at virginia.edu Mon Jul 7 08:02:55 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 7 Jul 2008 08:02:55 -0400 Subject: Cross Compiler for Python? In-Reply-To: <000901c8e009$dbd29e40$0d00a8c0@hendrik> References: <000901c8e009$dbd29e40$0d00a8c0@hendrik> Message-ID: <5504f9ac0807070502ub8258adx2eadfd6bde199df8@mail.gmail.com> On Mon, Jul 7, 2008 at 4:15 AM, Hendrik van Rooyen wrote: > Up to now, I have been innocently using the vanilla python > that comes with the Linux distribution (Suse in my case). > > For the past few days, I have been playing with a little > device called an eBox - it is basically a 486 with 128Mb > memory, and a 1Gig pcmcia flash drive. > > We want to try to use this as an industrial controller, so > I want to load python onto it. > > So I downloaded the sources, and got them into the box, > over its ethernet connection. > > Then I got stymied - the configure script will not run, > because the "distribution" has no C compiler - it is > basically a kernel, and Busybox, with precious little else. > > So I googled, and I found mobile python, and portable python, > both aimed at windows. - no good to me. > > Adding "embedded" to the Google string is also useless, > as it basically brings up instances of embedding the > interpreter into another app, not for small processors. > > So how does one do a compile of python on one machine > aimed at another one? - All I want is a vanilla installation > with the stuff in all the usual places. And just to make matters > interesting, the two Linux boxes I have available are both > 64 bit dual core animals, one Intel, one AMD... > > I don't need much more than the interpreter, sys, os, sockets > and ctypes. > > Alternatively, where can one find a set of binaries for > 32 bit Linux? > If you don't have a 32 bit system to build it on, you could always set up a VMWare machine... but that might be more effort than necessary. You can probably just run configure on your normal machine and then edit the makefile to add -m32 to the compiler or linker flags--that will force gcc to generate 32-bit code. You'd have to copy the files over and get the paths right yourself though. Alternately, if you can mount the eBox somewhere in Linux, you should be able to do configure --prefix=/path/to/eBox/mount and then make install will work for you too. (I haven't tried this before, but that's how I'd go about it.) From gherron at islandtraining.com Sun Jul 27 19:58:56 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 27 Jul 2008 16:58:56 -0700 Subject: Where is the correct round() method? In-Reply-To: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> Message-ID: <488D0BC0.3080701@islandtraining.com> josh logan wrote: > Hello, > > I need a round function that _always_ rounds to the higher integer if > the argument is equidistant between two integers. In Python 3.0, this > is not the advertised behavior of the built-in function round() as > seen below: > > >>>> round(0.5) >>>> > 0 > >>>> round(1.5) >>>> > 2 > >>>> round(2.5) >>>> > 2 > > Huh? >>> round(2.5) 3.0 Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo CPU". What system are you on? It could be that 2.5 is really 2.49999... which would round down to 2, but on any modern CPU (using IEEE floating point), 2.5 should be representable exactly. However, as with any floating point calculations, if you expect exact representation or calculations with any numbers, then you are misusing floating points. Gary Herron > I would think this is a common need, but I cannot find a function in > the Python library to do it. I wrote my own, but did I miss such a > method in my search of the Python library? > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > From grante at visi.com Fri Jul 25 12:50:39 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 25 Jul 2008 11:50:39 -0500 Subject: Calling external program from within python References: <6eu684F91muhU1@mid.uni-berlin.de> <6eu75mF92mqcU1@mid.uni-berlin.de> Message-ID: On 2008-07-25, Diez B. Roggisch wrote: > Because usually if a program *prompts* the user to enter input (and that > was what I read from the OP's post), one has to deal with pseudo > terminals, not with stdin/out. > >>> If interaction is required, the OP might consider using >>> pexpect. >> >> Pexpect is a good option, but it's just an automation layer on >> top of the same facilities that subprocess provides. > > AFAIK it's more than that. I'm not an expert on pseudo terminals, but > AFAIK setting using module pty isn't possible using subprocess. You're right. I forgot that pexect uses a pty. You could use a pty with the subprocess module, but it's a hassle to set up. -- Grant Edwards grante Yow! The PINK SOCKS were at ORIGINALLY from 1952!! visi.com But they went to MARS around 1953!! From fizzi at my10sen.com Thu Jul 3 06:34:43 2008 From: fizzi at my10sen.com (fizzi) Date: Thu, 03 Jul 2008 18:34:43 +0800 Subject: Iphone Going 3G! Message-ID: <486cab43$1_2@news.tm.net.my> For the Iphone lovers out there, The next generation of Iphone has been released with the additional features. You guess it, now Iphone comes with 3G. That ?s what we missed during the first release of Iphone which turn it into major drawback for Iphone buyers wannabe. Even more good news to those who wish to keep new iphone in the pocket the rest of the entry : http://www.my10sen.com/2008/07/03/iphone-going-3g/ From duncan.booth at invalid.invalid Thu Jul 17 13:27:22 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jul 2008 17:27:22 GMT Subject: properly delete item during "for item in..." References: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> <487F770D.8070405@islandtraining.com> Message-ID: mk wrote: > Iterating over a copy may _probably_ work: > > >>> t=['a', 'c', 'b', 'd'] > >>> > >>> for el in t[:]: > del t[t.index(el)] > > > >>> t > [] > > > However, is it really safe? Defining safe as "works reliably in every > corner case for every indexable data type"? No, because you cannot necessarily copy every indexable data type using t[:], and not all types will support index. Also it is inefficient to delete from the start of the list. If you are working with a list and deleting every object: del t[:] will suffice. If you don't want to delete everything then you could do: for index, el in enumerate(reversed(t)): if not wewant(el): del t[index] but the pythonic way is just: t[:] = [ el for el in t if wewant(el) ] or if you just want the filtered list and don't care about updating the original: t = [ el for el in t if wewant(el) ] > Con: suppose the data structure t is really, really big. Just deleting > some items from t temporarily doubles the memory consumption. No it doesn't. Copying a list doesn't copy any of the elements in the list, it just copies the references to those element. From nicola.musatti at gmail.com Wed Jul 9 07:20:54 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Wed, 9 Jul 2008 04:20:54 -0700 (PDT) Subject: GUI Programming by hand not code with Python Code References: <7003b665-3227-47a7-ab06-1a486f87939a@a1g2000hsb.googlegroups.com> Message-ID: <21f87365-ac36-452f-ac29-6df28f09abfa@56g2000hsm.googlegroups.com> On Jul 8, 10:09 pm, sturlamolden wrote: [...] > I use wxFormBuilder with wxPython. Works like a charm. Design the GUI > graphically, export it like a wx XML resource (.xrc). All you nedd to > code in Python is the event handlers and the code to bind/hook the > events. > > http://sturlamolden.blogspot.com/2008/03/howto-using-wxformbuilder-wi... I also use wxFormBuilder, but I use XRCed from wxPython 2.8.6.x to generate an application Skeleton from my .xrc file. This version creates explicit attributes for all the visual elements that have a name in the xrc file. Unfortunately the latest XRCed version requires you to annotate the xrc in order to obtain the same effect which is not only tedious, but as far as I can tell it also makes it impossible to round trip between XRCed and wxFormBuilder. Cheers, Nicola Musatti From nicolas.pourcelot at gmail.com Sun Jul 20 18:17:48 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Sun, 20 Jul 2008 15:17:48 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> <6ebshqF67cpfU4@mid.uni-berlin.de> <5d6b8066-c941-4f0c-abea-20baed33b4ab@l64g2000hse.googlegroups.com> <569da8b8-df8a-4115-a952-5d8c2d9744e0@i20g2000prf.googlegroups.com> <46c2153d-fef6-45b5-91af-9ecb359e6a2b@2g2000hsn.googlegroups.com> <141135ca-20fb-426e-a11f-bcd02aa01541@f40g2000pri.googlegroups.com> Message-ID: <7ecef9f2-567c-497c-aeaf-651f6c070f2b@2g2000hsn.googlegroups.com> On 20 juil, 23:18, John Machin wrote: > On Jul 21, 4:33 am, nicolas.pource... at gmail.com wrote: > > > > (1) You are searching through lists to find float objects by identity, > > > not by value > > > ???? > > You wrote """ > I used short lists (a list of 20 floats) and the element > checked was not in the list. > (That was the case I usually deals with in my code.) > """ :-D From bj_666 at gmx.net Tue Jul 1 06:52:54 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Jul 2008 10:52:54 GMT Subject: Having problems using Tkinter References: <144f93d3-b493-4280-a3a4-23a2b13b59c6@i36g2000prf.googlegroups.com> Message-ID: <6cugk6F3e7podU2@mid.uni-berlin.de> On Tue, 01 Jul 2008 03:13:42 -0700, viv1tyagi wrote: > Hi everyone ! ! ! > > I'm just a month old in the world of Python and trying to develop an > application using Tkinter in which a new window pops out on a > particular button press.The code for this new window is in > "AddKlas.py" file. > The problem is all the content of the new window is overwritten on > the previous window. > Below is the code of the two files There can be only one `Tkinter.Tk` instance per running program. Other top level windows have to be `Tkinter.Toplevel` instances. And you should reconsider your usage of classes. You are just abusing them as containers for functions without using `self` really. And you should pass the instance of the parent widget as first argument to constructors of widgets. Otherwise the very first, i.e. the `Tk` instance, is assumed, which is not true for the widgets that should appear in the `Toplevel` instance. Ciao, Marc 'BlackJack' Rintsch From bruno.42.desthuilliers at websiteburo.invalid Mon Jul 7 09:47:51 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 07 Jul 2008 15:47:51 +0200 Subject: yo... In-Reply-To: <1a767250-c2e6-4a07-8650-84b79bf628af@26g2000hsk.googlegroups.com> References: <1a767250-c2e6-4a07-8650-84b79bf628af@26g2000hsk.googlegroups.com> Message-ID: <48721e63$0$1120$426a74cc@news.free.fr> cokofreedom at gmail.com a ?crit : (snip) > However welcome to Python and this Google > Group. This is *not* a google group. This is the usenet newsgroup comp.lang.python, made accessible TTW by google. From fredrik at pythonware.com Wed Jul 16 05:01:30 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 11:01:30 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) In-Reply-To: <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> Message-ID: Stefan Scholl wrote: > Django isn't ready. That's a remarkably ignorant statement. From zellux at gmail.com Wed Jul 16 01:49:32 2008 From: zellux at gmail.com (ZelluX) Date: Tue, 15 Jul 2008 22:49:32 -0700 (PDT) Subject: Is there any library that can extract titles from PDFs? Message-ID: Hi, all I want to write a script which will rename PDFs according to their titles. I want to know if there is any library that can extract titles(the first line of the PDF) from PDFs. Many thanks for your reply ;-) From termim at gmail.com Thu Jul 3 15:41:37 2008 From: termim at gmail.com (Mike) Date: Thu, 3 Jul 2008 12:41:37 -0700 (PDT) Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> <6a8d3b30-b7d6-4f41-b491-0cfc44e46109@27g2000hsf.googlegroups.com> <3232ac82-97ee-4297-a511-5e1b61315b8e@t54g2000hsg.googlegroups.com> <2308f07f-61c8-46ae-8e91-d1c3f0629945@34g2000hsf.googlegroups.com> Message-ID: <31dd9e93-842a-40d3-898d-b40f0fcf1a8b@56g2000hsm.googlegroups.com> On Jul 2, 11:09 am, George Sakkis wrote: > On Jun 30, 3:16 pm, Mike wrote: > > > On Jun 30, 1:41 pm, George Sakkis wrote: > > > > Because _typically_ a web template consists of mostly HTML, with > > > relatively little presentational logic and (ideally) no business > > > logic. Now, if all one wants to do is a quick and dirty way to, say, > > > view a log file in the browser, a separate template is probably an > > > The keyword here is "(ideally)". These _typical_ cases are pretty much > > restricted to a helloworld-like examples or to a pure men log file > > browser ;). > > That's the opposite of what I said. For helloworld-like examples, a > web template is an overkill. It's non-trivial applications that can > show off what a template language buys you. > Yes, I really meant the opposite - _typically_ a web template consits of more than just HTML. Exception - helloworld-like examples. > > Real application templates quickly became complicated and > > require full blown scripting engine. Zope/Plone/Trac templates are > > good examples of this. > > What does "this" refer to? Injecting business logic or just > complicated presentational logic? > By "this" I try to support my statement that in real life applications templates are much mor complicated than just HTML. > > I took a look and as much as I like Python for general programming, I > find these templates more readable and maintenable than straight > string-concatenating Python. YMMV. > Completely agree here - straight string-concatenating in Python is not better. From bojannastic at googlemail.com Mon Jul 21 21:47:30 2008 From: bojannastic at googlemail.com (bojannastic at googlemail) Date: Mon, 21 Jul 2008 18:47:30 -0700 (PDT) Subject: Python Written in C? References: Message-ID: On Jul 20, 6:50 pm, giveitawhril2... at gmail.com wrote: > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! Young people these days... I will just answer using one of old Microsoft's ads: "My compiler compiled yours." From Nikolaus at rath.org Thu Jul 31 11:00:51 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Thu, 31 Jul 2008 17:00:51 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> <12072cbe-139a-430f-81aa-b64bc31b43e5@e39g2000hsf.googlegroups.com> <87zlny8cdg.fsf@nokile.rath.org> Message-ID: <87r69a85ek.fsf@nokile.rath.org> Maric Michaud writes: > Le Thursday 31 July 2008 14:30:19 Nikolaus Rath, vous avez ?crit?: >> oj writes: >> > On Jul 31, 11:37?am, Nikolaus Rath wrote: >> >> So why does Python distinguish between e.g. the type 'int' and the >> >> class 'myclass'? Why can't I say that 'int' is a class and 'myclass' >> >> is a type? >> > >> > I might be wrong here, but I think the point is that there is no >> > distinction. A class (lets call it SomeClass for this example) is an >> > object of type 'type', and an instance of a class is an object of type >> > 'SomeClass'. >> >> But there seems to be a distinction: >> >>> class int_class(object): >> >> ... pass >> ... >> >> >>> int_class >> >> >> >> >>> int >> >> >> >> why doesn't this print >> >> >>> class int_class(object): >> >> ... pass >> ... >> >> >>> int_class >> >> >> >> >>> int >> >> >> >> or >> >> >>> class int_class(object): >> >> ... pass >> ... >> >> >>> int_class >> >> >> >> >>> int >> >> >> >> If there is no distinction, how does the Python interpreter know when >> to print 'class' and when to print 'type'? >> > > There are some confusion about the terms here. > > Classes are instances of type 'type', Could you please clarify what you mean with 'instance of type X'? I guess you mean that 'y is an instance of type X' iif y is constructed by instantiating X. Is that correct? > What the means is that int is not a user type but a > builtin type, instances of int are not types (or classes) but common > objects, so its nature is the same as any classes. > > The way it prints doesn't matter, it's just the __repr__ of any instance, and > the default behavior for instances of type is to return '', but it > can be easily customized. But 'int' is an instance of 'type' (the metaclass): >>> int.__class__ so it should also return '' if that's the default behavior of the 'type' metaclass. I think that to get '' one would have to define a new metaclass like this: def type_meta(type): def __repr__(self) return "" % self.__name__ and then one should have int.__class__ == type_meta. But obviously that's not the case. Why? Moreover: >>> class myint(int): ... pass ... >>> myint.__class__ == int.__class__ True >>> int >>> myint despite int and myint having the same metaclass. So if the representation is really defined in the 'type' metaclass, then type.__repr__ has to make some kind of distinction between int and myint, so they cannot be on absolute equal footing. Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From tjreedy at udel.edu Wed Jul 23 23:24:45 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Jul 2008 23:24:45 -0400 Subject: Broken examples In-Reply-To: <4887DDA5.1010707@hughes.net> References: <4887DDA5.1010707@hughes.net> Message-ID: norseman wrote: > > I'm only talking about IPC related. > I have googled, yahooed, and so forth for several months now. ALL > examples I've come across have failed including those pertinent in the > Python doc area. > > Outline: > cd somedir > ls -1 *.xls >thislist #ls hyphen one > python process.py > (yes - ls can go here if wanted. easier to edit outside) > open thislist > loop until done > start excel (or scalc) > have it open file > have it save file as a .csv (or .dbf) > close excell (or scalc) > > Would seem to be a trivial exercise. > Starting Excel or any other executable in system path works fine. > popen3 opens whatever and reports no errors. r,w,and e all check as > being created. > > r,w,e= os.popen3('ls -l') > print r.read() # works as expected > > ALL attempts to send instructions to Excel or scalc FAIL COMPLETELY. > Actually, any attempt to communicate with a 'Point'n'Click' program > fails without errors being cited. They don't use redirectable command > line interfaces (like piping between programs) do they? :) > > Trying to use the examples I have found that supposedly setup IPC's of > one type or another have all failed with errors that point to things > that make no sense in the first place. > > Before you post a code example or a link to one be kind enough to run it > yourself first. You may get a surprise. The OOo examples do not work. > Not even when switching my system to their version. One problem they > have is asking a general user to change to places the user has no place > being and then to work there without permissions. I guess somebody > insists on doing all their work with root clearance down in the middle > of the vendor's tree. I don't think that's a healthy way to do things, > do you? > > In OOo in particular, using their version of VBA one can create the > macro and even port it to python. If one found the correct Microsoft > suite docs I suspect that same could be done there too. But that doesn't > activate it from a python control. As for setting the macro to run at > startup, well... maybe I had other uses in mind today???? Besides the > moment I change it, coworker in other room is going to decide to... :) > > Let's stick to Microsoft Office and OpenSource products for now. My > final goal will require specific conversations with a commercial vendor. > I would like those spread sheets working though. > > > Thanks > > Steve > norseman at hughes.net > -- > http://mail.python.org/mailman/listinfo/python-list > From stesch at no-spoon.de Sat Jul 19 05:33:33 2008 From: stesch at no-spoon.de (Stefan Scholl) Date: Sat, 19 Jul 2008 11:33:33 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> <0T56p3tmInifNv8%stesch@parsec.no-spoon.de> <6e7v9qF5q74kU1@mid.uni-berlin.de> <0T56pitfI5raNv8%stesch@parsec.no-spoon.de> Message-ID: <0T56v18vI5u9Nv8%stesch@parsec.no-spoon.de> Fredrik Lundh wrote: > (and the "stable release" and "much will change" stuff is pure FUD, of > course. what competing project will I find if I google your name?) Found something? Maybe this could help me to choose a web framework. -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ From ethan at stoneleaf.us Mon Jul 14 13:28:18 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 14 Jul 2008 09:28:18 -0800 Subject: Determining when a file has finished copying In-Reply-To: <7198df5e-e5e6-4b2d-9a7c-9ef2e30c87d1@x35g2000hsb.googlegroups.com> References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> <7198df5e-e5e6-4b2d-9a7c-9ef2e30c87d1@x35g2000hsb.googlegroups.com> Message-ID: <487B8CB2.6030400@stoneleaf.us> Sean DiZazzo wrote: > On Jul 9, 5:34 pm, keith wrote: > >>-----BEGIN PGP SIGNED MESSAGE----- >>Hash: SHA1 >> >> >> >>Ethan Furman wrote: >> >>>writeson wrote: >>> >>>>Guys, >> >>>>Thanks for your replies, they are helpful. I should have included in >>>>my initial question that I don't have as much control over the program >>>>that writes (pgm-W) as I'd like. Otherwise, the write to a different >>>>filename and then rename solution would work great. There's no way to >>>>tell from the os.stat() methods to tell when the file is finished >>>>being copied? I ran some test programs, one of which continously >>>>copies big files from one directory to another, and another that >>>>continously does a glob.glob("*.pdf") on those files and looks at the >>>>st_atime and st_mtime parts of the return value of os.stat(filename). >>>> >>>>>From that experiment it looks like st_atime and st_mtime equal each >>>> >>>>other until the file has finished being copied. Nothing in the >>>>documentation about st_atime or st_mtime leads me to think this is >>>>true, it's just my observations about the two test programs I've >>>>described. >> >>>>Any thoughts? Thanks! >>>>Doug >> >>>The solution my team has used is to monitor the file size. If the file >>>has stopped growing for x amount of time (we use 45 seconds) the file is >>>done copying. Not elegant, but it works. >>>-- >>>Ethan >> >>Also I think that matching the md5sums may work. Just set up so that it >>checks the copy's md5sum every couple of seconds (or whatever time >>interval you want) and matches against the original's. When they match >>copying's done. I haven't actually tried this but think it may work. >>Any more experienced programmers out there let me know if this is >>unworkable please. >>K >>-----BEGIN PGP SIGNATURE----- >>Version: GnuPG v1.4.6 (GNU/Linux) >>Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org >> >>iD8DBQFIdVkX8vmNfzrLpqoRAsJ2AKCp8wMz93Vz8y9K+MDSP33kH/WHngCgl/wM >>qTFBfyIEGhu/dNSQzeRrwYQ= >>=Xvjq >>-----END PGP SIGNATURE----- > > > I use a combination of both the os.stat() on filesize, and md5. > Checking md5s works, but it can take a long time on big files. To fix > that, I wrote a simple sparse md5 sum generator. It takes a small > number bytes from various areas of the file, and creates an md5 by > combining all the sections. This is, in fact, the only solution I have > come up with for watching a folder for windows copys. > > The filesize solution doesn't work when a user copies into the watch > folder using drag and drop on Windows because it allocates all the > attributes of the file before any data is written. The filesize will > always show the full size of the file. > > ~Sean Good info, Sean, thanks. One more option may be to attempt to rename the file -- if it's still open for copying, that will fail; success indicates the copy is done. Of course, as Larry Bates pointed out, this could fail if the copy is followed by a re-open and appending. Hopefully that's not an issue for the OP. -- Ethan From robert.rawlins at thinkbluemedia.co.uk Tue Jul 8 09:05:16 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 8 Jul 2008 14:05:16 +0100 Subject: Logger Configuration In-Reply-To: <001d01c8e0f4$b2c0c900$18425b00$@rawlins@thinkbluemedia.co.uk> References: <001d01c8e0f4$b2c0c900$18425b00$@rawlins@thinkbluemedia.co.uk> Message-ID: <004501c8e0fb$44a29d20$cde7d760$@rawlins@thinkbluemedia.co.uk> Ok, I've managed to resolve this issue, it seems it was because I had the file size and number of archives to keep in "" and was thus setting them as strings instead of numerical values. Robert From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Robert Rawlins Sent: 08 July 2008 13:18 To: python-list at python.org Subject: Logger Configuration Hello guys, I've attached an example of my logging configuration file for you to look at. The problem I'm experiencing is that the log files are not rotating as I would expect them to, they just keep growing and growing. Can you see any reason for this to happen? This is the first time I've used a config file and not just configured the logger programmatically. Thanks guys, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From jason at tishler.net Thu Jul 31 08:29:24 2008 From: jason at tishler.net (Jason Tishler) Date: Thu, 31 Jul 2008 08:29:24 -0400 Subject: SVN access with pysvn under Cygwin (Installation problems) In-Reply-To: <4cd368f8-6402-4f3e-8496-d9d227b39dd9@m73g2000hsh.googlegroups.com> References: <69da0a81-bf73-46cb-a762-b017a53e6ddf@e39g2000hsf.googlegroups.com> <4cd368f8-6402-4f3e-8496-d9d227b39dd9@m73g2000hsh.googlegroups.com> Message-ID: <20080731122924.GA3504@tishler.net> Andy, On Thu, Jul 31, 2008 at 03:10:26AM -0700, Andy Dingley wrote: > On 30 Jul, 20:30, Jason Tishler wrote: > > You need to build (and install) pysvn under Cygwin. The pre-built > > Windows version will not work under Cygwin. > > Thanks. Presumably this same problem would affect anything that uses a > .pyd under Cygwin? Yes, Python shared extension modules are specific to the Python used to build them. This is the situation even though Windows Python and Cygwin Python both run on the same operating system. BTW, this is why I added shared extension module support to Cygwin Python almost 8 years ago. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From larry.bates at websafe.com` Sun Jul 27 22:01:05 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 27 Jul 2008 21:01:05 -0500 Subject: write unsigned integer 32 bits to socket In-Reply-To: References: Message-ID: rkmr.em at gmail.com wrote: > hi > i want to send unsigned 32 bit integer to socket, and looking for > something equivalent to this method... > > http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt() > > is there such method / library available in python?! > > > this is as far as i have gotten along >>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>>> s.connect(('127.0.0.1',3000)) You will need to use struct module to build the 4 byte value and then send it. Something like (not tested): import struct us32bit = struct.pack("I", value) s.send(us32bit) -Larry From quarkthedark at gmail.com Wed Jul 16 09:55:51 2008 From: quarkthedark at gmail.com (AM) Date: Wed, 16 Jul 2008 06:55:51 -0700 (PDT) Subject: Playing stereo wav files in Python Message-ID: -Hello all, I am trying to play stereo wavefiles in python with no success. I can play mono wavefiles, using either pygames mixer library, python's winsound library or wxPython's wx.Sound library, but i cannot get stereo wavefiles to play in any of these. Normally i wouldn't care and covert the files to mono, but the phase difference between the two ears in important for this application. Does anyone know of a way that i have missed? I am using a LynxONE soundcard if that is important. -AM From ward.david at comcast.net Tue Jul 15 11:38:31 2008 From: ward.david at comcast.net (ward.david at comcast.net) Date: Tue, 15 Jul 2008 08:38:31 -0700 (PDT) Subject: Is it legal to rebuild Python.exe to include Version property tab? References: Message-ID: On Jul 15, 7:42?am, Michiel Overtoom wrote: > Why rebuild it? You can use a resource editor tool to add/edit/delete the > VERSIONINFO from any Windows executable, including Python.exe ;-) M, Thanks for you suggestion. I didn't know that there was anything like a "resource editor" outside of a dev IDE. You learn something new everyday. :) So, we've established that there is a different way to edit the VERSIONINFO of an EXE. However, the question still remains as to whether is is legal to edit the VERSIONINFO on Python.exe and distribute it? From gherron at islandtraining.com Sun Jul 13 14:16:46 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 13 Jul 2008 11:16:46 -0700 Subject: Mutually referencing imports -- impossible? In-Reply-To: References: Message-ID: <487A468E.5000000@islandtraining.com> Matthew Wilson wrote: > I started off with a module that defined a class Vehicle, and then > subclasses Car and Motorcycle. > > In the Car class, for some bizarre reason, I instantiated a Motorcycle. > Please pretend that this can't be avoided for now. > > Meanwhile, my Motorcycle class instantiated a Car as well. > > Then I moved the Car and Motorcycle classes into separate files. Each > imported the Vehicle module. > > Then I discovered that my Car module failed because the global > Motorcycle wasn't defined. The same problem happened in my Motorcycle > module. Car and Motorcycle can't both import each other. > > In the beginning, when all three (Vehicle, Car, and Motorcycle) were > defined in the same file, everything worked fine. > > I don't know how to split them out in separate files now though and I > really wish I could because the single file is enormous. > > Any ideas? > > Matt > It is easy for imports to be mutually referencing. This presents no problem to Python if the importing of one module is interrupted by the import of another. However, if one of them imports specific names from a module, from ABC import abc or from ABC import * then it's possible that the (interrupted) import of module ABC has not progressed to the point that abc is defined. The solution: Just import ABC and later reference ABC.abc That being said, it is still a good design practice to structure your modules hierarchically rather than a circularly. Gary Herron > > -- > http://mail.python.org/mailman/listinfo/python-list > From python at bdurham.com Tue Jul 29 01:02:43 2008 From: python at bdurham.com (python at bdurham.com) Date: Tue, 29 Jul 2008 01:02:43 -0400 Subject: Questions on 64 bit versions of Python (Thank-you!) In-Reply-To: <488cbeeb$0$17104$9b622d9e@news.freenet.de> References: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> <488cbeeb$0$17104$9b622d9e@news.freenet.de> Message-ID: <1217307763.13376.1265835765@webmail.messagingengine.com> Dear List, Thanks for everyone's feedback - excellent detail - all my questions have been answered. BTW: Roel was correct that I got confused over the AMD and Intel naming conventions regarding the 64 bit versions of Python for Windows. (I missed that nuance that the Intel build refered to the Itanium vs. the standard off-the-rack 64 bit version of Intel's 586/686 CPU) Best regards, Malcolm From __peter__ at web.de Sun Jul 13 06:30:52 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 13 Jul 2008 12:30:52 +0200 Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> Message-ID: Yosifov Pavel wrote: > On 13 ???, 14:12, Peter Otten <__pete... at web.de> wrote: >> Yosifov Pavel wrote: >> > Whats is the way to clone "independent" iterator? I can't use tee(), >> > because I don't know how many "independent" iterators I need. copy and >> > deepcopy doesn't work... >> >> There is no general way. For "short" sequences you can store the items in >> a list which is also the worst-case behaviour of tee(). >> >> What are you trying to do? >> >> Peter > > I try to generate iterators (iterator of iterators). Peter, you are > right! Thank you. For example, it's possible to use something like > this: > > def cloneiter( it ): > """return (clonable,clone)""" > return tee(it) [snip] That is too abstract, sorry. What concrete problem are you trying to solve with your cloned iterators? There might be a way to rearrange your setup in a way that doesn't need them. > But I think (I'm sure!) it's deficiency of Python iterators! They are > not very good... Well, I think Python's iterators, especially the generators, are beautiful. More importantly, I think there is no general way to make iterators copyable, regardless of the programming language. The problem is that most of the useful ones depend on external state. Peter From ggpolo at gmail.com Tue Jul 1 11:22:28 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 1 Jul 2008 12:22:28 -0300 Subject: dynamically load from module import xxx In-Reply-To: References: Message-ID: On Tue, Jul 1, 2008 at 12:11 PM, Neal Becker wrote: > What is a good way to emulate: > > from module import xxx > where 'module' is a dynamically generated string? > > __import__ ('modulename', fromlist=['xxx']) > > seems to be what I want, but then it seems 'xxx' is not placed in globals() > (which makes me wonder, what exactly did fromlist do?) fromlist is used for importing subpackages/submodules of the first arg of __import__. Since you are using "modulename", I'm guessing it is not a package, fromlist will do nothing for you. To solve your problem you could do getattr(__import__('modulename'), 'xxx'). > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From james at reggieband.com Mon Jul 14 05:51:39 2008 From: james at reggieband.com (James Fassett) Date: Mon, 14 Jul 2008 02:51:39 -0700 (PDT) Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> Message-ID: <6daf86f6-0a96-4811-90c4-2bc6ccbff9fb@x41g2000hsb.googlegroups.com> On Jul 12, 12:18?am, George Sakkis wrote: > It relies on positional arguments, tuple unpacking and > the signature of zip(), It moreso relies on the fact that: >>> t1 = (0,1,2,3) >>> t2 = (7,6,5,4) >>> [t1, t2] == zip(*zip(t1, t2)) True This is mathematically true given the definition of zip. To me that is very functional. Basically, unpacking a pair list into zip is the canonical definition of unzipping the list (which is exactly my intention). > Second, it is less readable, For a Python programmer - you are correct. For someone familiar with the use of zip (as described above) - I wonder. Since I am new to this I can't say for sure. If I posted the same code to a Haskell list or a ML list would their opinion be the same? > robust and efficient than the list comprehension. I don't know the internals of how the Python interpreter treats list comprehensions and zip but it seems reasonable to assume an extra list is created for the zip approach. However, in the limited functional code I have seen this is actually a common practice. I would suppose in languages with lazy evaluation this isn't a problem - but in Python it would be. > The list comprehension is still the most pythonic approach though. I agree that it is more Pythonic and preferable in this case. Cheers, James From jeffrey at fro.man Mon Jul 14 16:10:45 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Mon, 14 Jul 2008 13:10:45 -0700 Subject: while var, but var ==16 != true References: <8c2cd9ff-bec2-4844-82a8-8ce02df5663e@w7g2000hsa.googlegroups.com> Message-ID: Tim Roberts wrote: > Everything has a boolean value in > Python. ?0, None, False, '' (empty string), [] (empty list), () (empty > tuple), and {} (empty dictionary) all have a False value. ?Everything else > has a True value. Empty set objects also evaluate as false in a boolean context. Jeffrey From pavlovevidence at gmail.com Wed Jul 30 02:50:17 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 23:50:17 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> Message-ID: <29a131a5-d813-407a-b774-6f90b7f8f3e3@w1g2000prk.googlegroups.com> On Jul 30, 1:58 am, "Russ P." wrote: > On Jul 29, 10:33 pm, Carl Banks wrote: > > > On Jul 30, 1:15 am, "Russ P." wrote: > > > Having said that, it would sure be nice to be able to write > > > > if myList is not empty: > > > > instead of > > > > if len(myList) != 0: > > > I can agree with this. > > But I guess that could only work if there were only one empty list > that represents all empty lists (as there is only one actual "None"). > I don't know if that makes sense or not. I mean in general. I wouldn't spell it like that. I would prefer if empty(x), with an __empty__ method. (And support __nonzero__ aka __bool__ dropped completely.) Carl Banks From misterwang at gmail.com Mon Jul 21 12:58:46 2008 From: misterwang at gmail.com (Peter Wang) Date: Mon, 21 Jul 2008 09:58:46 -0700 (PDT) Subject: how to create GUI dynamically References: <84f144db-0d6c-44d5-a1ef-6e7778304c2a@r66g2000hsg.googlegroups.com> Message-ID: <80b2d543-cb76-4d2e-8958-3557fb617bd0@j22g2000hsf.googlegroups.com> On Jul 21, 8:19?am, hitechpun... at gmail.com wrote: > Hi; > > i m working on a project where i need ?run time creation of GUI. > > i have some no. of entities for which i want checkboxes in front of > them which can be checked/ unchecked by user. > > But the problem is that the number and name of entities is not fixed > and it depends on the file which is used as input. > > So is there any way to tackle this problem. > > By the way ; i use Boa constructor (zope editor) for GUI now. > > regards > pawan pundir You should check out Traits and Traits UI: http://code.enthought.com/projects/traits/examples.php It allows you to dynamically create views and UIs in an easy, declarative manner. It is also powerful enough to build much more complex interactions and dialogs. It currently supports both WX and Qt toolkits. -Peter From sjmachin at lexicon.net Mon Jul 28 20:59:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 28 Jul 2008 17:59:35 -0700 (PDT) Subject: seemingly simple list indexing problem References: Message-ID: <5c118411-5703-44b3-888f-3785b517b8d4@u12g2000prd.googlegroups.com> On Jul 29, 8:10 am, John Krukoff wrote: > On Mon, 2008-07-28 at 16:24 -0500, Ervan Ensis wrote: > > My programming skills are pretty rusty and I'm just learning Python so > > this problem is giving me trouble. > > > I have a list like [108, 58, 68]. I want to return the sorted indices > > of these items in the same order as the original list. So I should > > return [2, 0, 1] > > > For a list that's already in order, I'll just return the indices, i.e. > > [56, 66, 76] should return [0, 1, 2] > > > Any help would be appreciated. > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > If your lists aren't so large that memory is an issue, this might be a > good place for a variation of decorate, sort, undecorate. > > >>> listToSort = [ 108, 58, 68 ] > >>> decorated = [ ( data, index ) for index, data in > > enumerate( listToSort ) ]>>> decorated > > [(108, 0), (58, 1), (68, 2)]>>> result = [ None, ] * len( listToSort ) > >>> for sortedIndex, ( ignoredValue, originalIndex ) in > > enumerate( sorted( decorated ) ): > ... result[ originalIndex ] = sortedIndex > ...>>> result > > [2, 0, 1] > Simpliciter: >>> data = [99, 88, 77, 88, 66] >>> [x[1] for x in sorted(zip(data, xrange(len(data))))] [4, 2, 1, 3, 0] >>> Use case? Think data == database table, result == index ... From mensanator at aol.com Wed Jul 2 18:21:00 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 2 Jul 2008 15:21:00 -0700 (PDT) Subject: Generating list of possible configurations References: Message-ID: On Jul 2, 4:53?pm, "bjorklund.e... at gmail.com" wrote: > Hello pythonistas. > > I'm a newbie to pretty much both programming and Python. I have a task > that involves writing a test script for every possible combination of > preference settings for a software I'm testing. I figured that this > was something that a script could probably do pretty easily, given all > the various possibilites. > > I started creating a dictionary of all the settings, where each key > has a value that is a list of the possible values for that setting. > Most of the settings are simple booleans (setting is on or off), some > of them are drop-downs with several values. For example: > > settings = { > ? ? 'setting_a': (True, False), > ? ? 'setting_b': (True, False), > ? ? 'setting_c': (1, 2, 3, 4), > > } > > After this I tried figuring out a function that would generate the > different possible configurations, but I couldn't quite wrap my head > around it... Basically, for each setting of a, you must do each possible b, and for each a,b setting you must do each possible c, etc. > Are there any general patterns/structures that are suited > for this type of task? Lookup "Cartesian Product". > Any pointers as to how one would go about > solving something like this would be greatly appreciated. for a in [True,False]: for b in [True,False]: for c in [1,2,3,4]: print 'combined settings:',a,'\t',b,'\t',c combined settings: True True 1 combined settings: True True 2 combined settings: True True 3 combined settings: True True 4 combined settings: True False 1 combined settings: True False 2 combined settings: True False 3 combined settings: True False 4 combined settings: False True 1 combined settings: False True 2 combined settings: False True 3 combined settings: False True 4 combined settings: False False 1 combined settings: False False 2 combined settings: False False 3 combined settings: False False 4 > It's not > that I really need to use Python for it, but I thought it could be a > good learning excercise... :-) You may, then, also be interested in Permutations with Replacement Permutations without Replacement Combinations with Replacement Combinations without Replacement > > Kind regards, > //Emil From python at hope.cz Fri Jul 25 14:34:55 2008 From: python at hope.cz (Johny) Date: Fri, 25 Jul 2008 11:34:55 -0700 (PDT) Subject: How to find processes from Python Message-ID: <9f04931c-867b-4ff3-820c-3f8d0bfd2618@e53g2000hsa.googlegroups.com> Is there a way how to find out running processes?E.g. how many Appache's processes are running? Thanks for help. BB. From noelob at gmail.com Wed Jul 16 13:56:50 2008 From: noelob at gmail.com (noelob) Date: Wed, 16 Jul 2008 10:56:50 -0700 (PDT) Subject: Uploading an image using PUT Message-ID: <2375be12-6470-493c-9d4f-979e20c35502@k13g2000hse.googlegroups.com> Hi All, Let me start by saying that's I'm relatively new to Python, so please be gentle! I need to up upload a file to a Tomcat web app using httplib. The web app requires the following: Files need to be split into 100kb (102400b) and each file segment loaded using the PUT request. It is also a requirement that the following headers be sent: For simplicity I've used an image (jpg) smaller than 100kb, so it doesn't need to be chunked headers = { "Accept": "text/xml", "Authorization": "testAuthHeader", "Content-Length": 50172, "Content-Range": "bytes 0-50172/50172", "Content-Type": "image/jpeg", "If-Match": "1", "User-Agent": "(en-IE; Grinder)", } I make the following connection: conn = httplib.HTTPConnection(url) conn.request(method, uriStr, body, additionalHeaders) where: method = PUT uriStr is the web app specific URI body is the raw data (bytes) from the jpg image additionalHeaders are the headers above For some reason I keep getting a Status 400 error from the web server. Is it possible to PUT (or POST?) data in this fashion using httplib? Many thanks for your help Noelob From pavlovevidence at gmail.com Sat Jul 5 08:54:48 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 5 Jul 2008 05:54:48 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: On Jul 5, 6:44 am, "Sebastian \"lunar\" Wiesner" wrote: > Carl Banks : > > > > > On Jul 5, 4:12 am, "Sebastian \"lunar\" Wiesner" > > wrote: > >> Paddy : > > >> > On Jul 4, 1:36 pm, Peter Otten <__pete... at web.de> wrote: > >> >> Henning_Thornblad wrote: > >> >> > What can be the cause of the large difference between re.search and > >> >> > grep? > > >> >> grep uses a smarter algorithm ;) > > >> >> > This script takes about 5 min to run on my computer: > >> >> > #!/usr/bin/env python > >> >> > import re > > >> >> > row="" > >> >> > for a in range(156000): > >> >> > row+="a" > >> >> > print re.search('[^ "=]*/',row) > > >> >> > While doing a simple grep: > >> >> > grep '[^ "=]*/' input (input contains 156.000 a in > >> >> > one row) > >> >> > doesn't even take a second. > > >> >> > Is this a bug in python? > > >> >> You could call this a performance bug, but it's not common enough in > >> >> real code to get the necessary brain cycles from the core developers. > >> >> So you can either write a patch yourself or use a workaround. > > >> >> re.search('[^ "=]*/', row) if "/" in row else None > > >> >> might be good enough. > > >> >> Peter > > >> > It is not a smarter algorithm that is used in grep. Python RE's have > >> > more capabilities than grep RE's which need a slower, more complex > >> > algorithm. > > >> FWIW, grep itself can confirm this statement. The following command > >> roughly takes as long as Python's re.search: > > >> # grep -P '[^ "=]*/' input > > >> -P tells grep to use real perl-compatible regular expressions. > > > This confirms that a particular engine might not be optimized for it, > > but it's not necessarily a reflection that the engine is more complex. > > My posting wasn't intended to reflect the differences in complexity between > normal GNU grep expressions (which are basically extended POSIX > expressions) and perl-compatible expressions. The latter just _are_ more > complex, having additional features like look aheads or non-greedy > qualifiers. > > I just wanted to illustrate, that the speed of the given search is somehow > related to the complexity of the engine. I don't think you've illustrated that at all. What you've illustrated is that one implementation of regexp optimizes something that another doesn't. It might be due to differences in complexity; it might not. (Maybe there's something about PCREs that precludes the optimization that the default grep uses, but I'd be inclined to think not.) Carl Banks From max at alcyone.com Wed Jul 30 02:07:28 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 23:07:28 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: Russ P. wrote: > All this discussion about "if x" has me wondering. I use it all the > time because a fully explicit test just seems redundant. But maybe it > does have some value in terms of readability and type checking. After > all, it is possible to forget whether something is a number or a list. > > Having said that, it would sure be nice to be able to write > > if myList is not empty: I sure hope that's a joke. `x is not y` means something quite different. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The doors of Heaven and Hell are adjacent and identical. -- Nikos Kazantzakis From diordna at gmail.com Wed Jul 23 11:08:40 2008 From: diordna at gmail.com (Stephen Johnson) Date: Wed, 23 Jul 2008 11:08:40 -0400 Subject: Doubt In-Reply-To: References: Message-ID: <6165DF11-444D-4CCE-A35A-BA7A6A087B45@gmail.com> You don't need a mailing list, you need to read the tutorial. Those are completely trivial questions. http://docs.python.org/tut/tut.html -Steve Johnson On Jul 23, 2008, at 10:51 AM, ???????? wrote: > Friends > > I am a Perl programmer new to Python. I have a small doubt. > How to convert the perl notation > $a = ""; expression in Python ? > > How to represent the loop > for ($a = $b; $a<=$c;$a++){ > } in Python > > Jagan > Linguist > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From dorjetarap at googlemail.com Fri Jul 11 18:42:44 2008 From: dorjetarap at googlemail.com (kdt) Date: Fri, 11 Jul 2008 15:42:44 -0700 (PDT) Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: <4ae1e559-038d-4440-85d4-ae3e469fc7e8@b1g2000hsg.googlegroups.com> On Jul 11, 11:34?pm, Denis Kasak wrote: > On Sat, Jul 12, 2008 at 12:22 AM, kdt wrote: > > ?> Hi all, > ?> > ?> Can someone please explain to me why the following evaluates as false? > ?> > ?>>>>list=['a','n','n','a'] > ?>>>>list==list.reverse() > ?>>>>False > ?> > ?> I'm stumped :s > > Read the documentation on list.reverse(). > > Basically, it reverses the list in place, so it modifies the list which > called it. It does not return a /new/ list which is a reversed version > of the original, as you expected it to. Since it doesn't return anything > explicitly, Python makes it return None. Hence, the comparison you are > doing is between the original list and a None, which is False, naturally. > Try this: > > spam = ['a', 'n', 'n', 'a'] > eggs = spam[:] > if spam.reverse() == eggs: > ? ? print "Palindrome" > > Also, 'list' is a really bad name for a list, since this is the name of > the builtin type object for the list type. > > -- > Denis Kasak thanks for the explanation :D From tjreedy at udel.edu Sat Jul 26 17:07:13 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 17:07:13 -0400 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> Message-ID: Carl Banks wrote: > On Jul 24, 4:11 am, Jordan wrote: >> Of course not. >> >> I just think Explicit is better than Implicit is taken seriously by a >> large segment the Python community as a guiding principle, > > Yeah, try telling that to the people who advise writing "if x" instead > of "if x==0", or "if s" instead of "if len(s)==0". Whether or not one should write 'if x' or 'if x != 0' [typo corrected] depends on whether one means the general 'if x is any non-null object for which bool(x) == True' or the specific 'if x is anything other than numeric zero'. The two are not equivalent. Ditto for the length example. What people do properly advise against is the strictly redundant 'if x is True' or 'if x == True'. Both imply a misunderstanding of how 'if' works in Python. As a side note, the usefulness of specific comparisons is greater in 3.0 where spurious comparisons raise exceptions. In 3.0, 'if x >= 0' specifically means 'if x is a number comparable to ints that is greater than or equal to 0'. In 3.0, [] ==/!= 0 are still False/True, but one could exclude incomparables with 'if 0 <= x >= 0' (==0) or 'if x > 0 or x < 0' (!=0). Any such specific comparisons could be used with this pattern. try: x = [] if x >= 0: print('should not get here') except TypeError as m: if m.args[0].startswith('unorderable types:'): print('Here because of bad comparison') Terry Jan Reedy From GDavidson7 at gmail.com Thu Jul 10 14:50:14 2008 From: GDavidson7 at gmail.com (Guy Davidson) Date: Thu, 10 Jul 2008 11:50:14 -0700 (PDT) Subject: Problems Returning an HTTP 200 Ok Message Message-ID: <1cf880cc-2036-42dc-8217-d52a714c1710@a70g2000hsh.googlegroups.com> Hi Folks, I'm having some issues with an small socket based server I'm writing, and I was hoping I could get some help. My code (attached below) us supposed to read an HTTP Post message coming from a power meter, parse it, and return a proper HTTP 200 Ok message. The problem is that the socket fails to send the entire message as one message, creating a fragmented message which the power meter then fails to read and accept. Is there any way to force the socket to send the entire message at once? Am I doing anything wrong? Is there an easier way to implement this functionality? Thanks, Guy Davidson Code: # server application to read data from power meter # listens on port 80 # receives HTTP POST messages # author: Maria Kazandjieva , Guy Davidson # updated: July 7th, 2008: staring to add database writing functionality import time import datetime #datetime for response message from socket import * #socket module import DataPacket #local file with data packet class import library import MySQLdb #formats a proper response message myHost = "" myPort = 80 #response = "HTTP/1.1 200 OK\r\nDate: Fri, 20 June 2008 20:40:34 GMT\r \nServer:SING\r\nX-Powered-By: maria\r\nContent-Length: 7\r \nConnection:close\r\nContent-Type: text/html\r\n\r\n[0!:20]\n" #initializing the socket: s = socket(AF_INET, SOCK_STREAM) # create a TCP socket s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # allow port reuse? I hope s.bind((myHost, myPort)) # bind it to the server port s.listen(50) # allow 50 simultaneous pending connections print('Socket initialized') #intializing the database db = MySQLdb.connect(host='localhost', user='powernet', passwd='jplicks', db='test') cursor = db.cursor() print('Database cursor intialized') while 1: print('In while 1') connection, address = s.accept() # connection is a new socket print('Accepted a connection') # TODO: # verify connection is from powernet so we don't get random connections to port 80 # best way to get the data would be: # read until we get all the headers # parse Content header to get length of data # read for that many additional bytes while 1: print('In while 1 2') data = connection.recv(4096) # receive up to 4K bytes print('First set of data receieved:') #print(data) ''' if data: print data #connection.send(response) #send response; OK 200 HTTP message else: break ''' if data: # second read should recieve the rest of the packet # finding how long the content is length = data.find('Content-Length: ') print('Index of "Content-Length" = ' + str(length)) length = int(data[length+16:length+18]) # adding the bytes from the "Content-Type section:" length += 51 data += connection.recv(length) print('Second set of data received:') print(data) if data: #print('Found data:') #print data #print the string data packet = DataPacket.DataPacket(data) #use the string data to create a DataPacket object print(packet) #print the contents of the object, I hope :) #we have a packet, let's write it to the mysql DB packet.mysql_insert(cursor) #connection.send(response) #send response; OK 200 HTTP message print('Sending response') response = library.response_message() #get the response message totalsent = 0 #initialize a variable to track how much we've sent so far while totalsent < len(response): #while we haven't sent everything sent = connection.send(response[totalsent:]) #send whatever we can starting where we stopped totalsent += sent #increment the count of how much we've sent. else: print('No data') break else: print('No data') break From martinnorth at westnet.com.au Sat Jul 12 04:28:25 2008 From: martinnorth at westnet.com.au (martinnorth) Date: Sat, 12 Jul 2008 18:28:25 +1000 Subject: MySQLdb will only import for root In-Reply-To: References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> Message-ID: Peter Otten wrote: > martinnorth wrote: > >> Hi, >> >> I am running Python and MySQL on Ubuntu and have installed MySQLdb. If I >> try to import MySQLdb I get the following error: >> >> ActivePython 2.5.2.2 (ActiveState Software Inc.) based on >> Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08) >> [GCC 3.3.1 (SuSE Linux)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import MySQLdb >> Traceback (most recent call last): >> File "", line 1, in >> ImportError: No module named MySQLdb >> >> But if I lrun python as the root user it imports fine. Can anyone >> suggest what might be wrong with the installation? Or is there nothing >> wrong? I haven't seen any examples that mentioned being root to import a >> module. > > You have probably installed two versions of Python. You can verify that by > typing > > $ which python > > and > > $ sudo which python > > I suspect that root sees the python that comes with Ubuntu and that has > MySQLdb installed while the normal user sees ActiveState's Python. > > Peter > Thanks Peter, that was it. Located the ActiveState directory and removed it. Now the module imports for all users. Martin From tjreedy at udel.edu Mon Jul 21 17:47:26 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 21 Jul 2008 17:47:26 -0400 Subject: Python Written in C? In-Reply-To: References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> Message-ID: Fredrik Lundh wrote: > rynt wrote: > >> You're either --- >> A. A Troll >> B. A young, immature programmer trying to show off >> or >> C. A total idiot. > > you forgot the "All of the above" choice. Or Aspiring Comic. This is certain one of the more entertaining troll posts we have had ;-). From toby at tobiah.org Tue Jul 1 15:35:01 2008 From: toby at tobiah.org (Tobiah) Date: Tue, 01 Jul 2008 12:35:01 -0700 Subject: Please check my understanding... Message-ID: list.append([1,2]) will add the two element list as the next element of the list. list.extend([1,2]) is equivalent to list = list + [1, 2] and the result is that each element of the added list becomes it's own new element in the original list. Is that the only difference? >From the manual: s.extend(x) | same as s[len(s):len(s)] = x But: (python 2.5.2) >>> a [1, 2, 3] >>> a[len(a):len(a)] = 4 Traceback (most recent call last): File "", line 1, in TypeError: can only assign an iterable >>> Also, what is the difference between list[x:x] and list[x]? >>> a[3:3] = [4] >>> a [1, 2, 3, 4] ** Posted from http://www.teranews.com ** From ldo at geek-central.gen.new_zealand Fri Jul 25 00:44:35 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 25 Jul 2008 16:44:35 +1200 Subject: Question about inheritence References: Message-ID: In message , Fredrik Lundh wrote: > Python doesn't really have constructors; when you create an object, > Python first creates the object and then calls the __init__ method, if > available That's the usual meaning of "constructor". It doesn't actually "construct" the object, it really "initializes" it. From tjreedy at udel.edu Sat Jul 5 18:22:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 05 Jul 2008 18:22:02 -0400 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <9cae59d9-ead4-45bc-a980-2ac2e1616f9b@p25g2000hsf.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <9cae59d9-ead4-45bc-a980-2ac2e1616f9b@p25g2000hsf.googlegroups.com> Message-ID: Mark Dickinson wrote: > On Jul 5, 1:54 pm, Carl Banks wrote: > Part of the problem is a lack of agreement on what > 'regular expression' means. Twenty years ago, there was. Calling a extended re-derived grammar expression like Perl's a 'regular-expression' is a bit like calling a Hummer a 'car' -- perhaps to hide its gas-guzzling behavior. > Strictly speaking, PCREs aren't > regular expressions at all, for some values of the term > 'regular expression'. See > > http://en.wikipedia.org/wiki/Regular_expression From larry.bates at websafe.com` Wed Jul 9 20:25:22 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 09 Jul 2008 19:25:22 -0500 Subject: Terminate a python script from linux shell / bash script In-Reply-To: References: Message-ID: Gros Bedo wrote: > Hello :-) > > I have a question about Python and Linux shell. I have a python program which is permanently resident in the end-user system. I'm currently producing a RPM package, and it works nicely. The problem is that when I uninstall it, my program keeps running in the background, even if the files are deleted. > > I know I can terminate python shell directly, but this is not a good idea because the end-user may be working with another important python application, and would be very angry if mine would close everything that is using python shell. > > So, is there a way from the Linux shell or a bash script to terminate just one specific Python script ? > _________________________________________________________________ > Votre contact a choisi Hotmail, l'e-mail nouvelle g?n?ration. Cr?ez un compte. > http://www.windowslive.fr/hotmail/default.asp You should use the signal module to look for SIGINT signal and exit if it is received. -Larry From circularfunc at gmail.com Sat Jul 12 21:10:58 2008 From: circularfunc at gmail.com (ssecorp) Date: Sat, 12 Jul 2008 18:10:58 -0700 (PDT) Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> Message-ID: <85c3da91-9f2f-4d19-ba98-dfdc99b1e1e3@79g2000hsk.googlegroups.com> On Jul 13, 2:32?am, Roy Smith wrote: > In article > <3b78898b-6131-4137-9c1d-64deaf460... at p25g2000hsf.googlegroups.com>, > > > > ?ssecorp wrote: > > Is this correct use of exceptions? to raise an indexerror and add my > > own string insetad of just letting it raise a IndexError by itself and > > "blaming" it on list.pop? > > > class Stack(object): > > ? ? def __init__(self, *items): > > ? ? ? ? self.stack = list(items) > > > ? ? def push(self, item): > > ? ? ? ? self.stack.append(item) > > > ? ? def pop(self): > > ? ? ? ? try: > > ? ? ? ? ? ? return self.stack.pop() > > ? ? ? ? except: > > ? ? ? ? ? ? raise IndexError, "pop from empty stack" > > > class Queue(object): > > ? ? def __init__(self, *items): > > ? ? ? ? self.queue = list(items) > > > ? ? def append(self, item): > > ? ? ? ? self.queue.append(item) > > > ? ? def pop(self): > > ? ? ? ? try: > > ? ? ? ? ? ? return self.queue.pop(0) > > ? ? ? ? except: > > ? ? ? ? ? ? raise IndexError, "pop from empty queue" > > I think you would do better defining a new exception, PopError, or > something like that. ?Then you can write code which specifically catches > that and do something with it. > > It's also not a good idea to catch all exceptions. ?Catch the most specific > thing you can. ?Consider something like: > > try: > ? ? kew.pop(0) > except: > ? ?raise IndexError, "pop from empty kew" > > When I run it, it prints, "IndexError: pop from empty kew". ?The problem > is, the *real* error is "NameError: name 'kew' is not defined". ?By > catching all exceptions, I've masked a programming error by turning the > NameError into an IndexError. i dont get what you mean, if i dont do anything python will raise an indexerror so it is an indexerror. From tjreedy at udel.edu Tue Jul 22 12:28:29 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2008 12:28:29 -0400 Subject: string[i:j:k] In-Reply-To: References: Message-ID: konstantin wrote: > Hello, > I'm not a newbie in python, but recently faced a problem in simple > expression: > some_string[i:j:k] > What does it mean? I believe this grammar (http://docs.python.org/ref/ > slicings.html) describes the syntax. But I can't grasp it. When you post a link, please put it on one line by itself, like this: http://docs.python.org/ref/slicings.html so it will be clickable as a whole by modern newsreaders. Experimenting with bits of code in the interactive interpreter (or IDLE, which is easier to cut from), like the responders did, is a great way to learn. From ldo at geek-central.gen.new_zealand Fri Jul 18 01:38:51 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 18 Jul 2008 17:38:51 +1200 Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> <98eae1fc-ff34-4dcc-b46d-9e3da2850c28@r66g2000hsg.googlegroups.com> Message-ID: In message <98eae1fc-ff34-4dcc-b46d-9e3da2850c28 at r66g2000hsg.googlegroups.com>, Craig Allen wrote: > On Jul 16, 7:01 pm, Lawrence D'Oliveiro central.gen.new_zealand> wrote: >> >> >>> class TehLibrary(object) : >> >> ... @classmethod >> ... def __new__(self, cls) : >> ... return self >> >> >>> s = TehLibrary() >> >>> s == TehLibrary() >> >> True > > That's great, I simply didn't find that when looking. Thanks! Also note that s == TehLibrary will be true (the instance equals the class). I assume that doesn't matter for your purposes. :) From Scott.Daniels at Acm.Org Wed Jul 16 09:01:55 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 16 Jul 2008 06:01:55 -0700 Subject: Need Python Programmer (preferentially in Los Angeles) In-Reply-To: References: Message-ID: robnhood00 wrote: > I need a python programmer that can integrate graphics into an > existing python application. The application is a basic application > and the job should be pretty easy for an experienced Python > programmer. Los Angeles programmer is preferred but this can > obviously be done from anywhere. > Please contact me at robnhood007 at yahoo.com is you can help me. > Thank you. I get worried when I hear people tell me that a job they don't know how to do "should be pretty easy," but at least it is better than "should only take a week." What I'd rather hear is, "seems like it is a simple job." Beware of customers who know something will take little effort without being able to characterize that effort. --Scott David Daniels Scott.Daniels at Acm.Org From svenn.bjerkem at googlemail.com Mon Jul 28 17:49:19 2008 From: svenn.bjerkem at googlemail.com (Svenn Are Bjerkem) Date: Mon, 28 Jul 2008 14:49:19 -0700 (PDT) Subject: Parsing VHDL with python, where to start. References: <31888260-86a9-46b0-b0a4-79f7852f256a@k30g2000hse.googlegroups.com> Message-ID: Hi again, when I get far enough to parse the VHDL (which is not currently the fact, but I have to look at the work coming up downstream) I will have to put it into an internal data structure and then write some classes to handle the MVC between whatever data I have and the PyQt4 widget that is going to show the block diagram. I own the book "Rapig GUI Programming with Python and Qt" by Mark Summerfield and try to read up on the PyQt way of doing things as I try to make a plan for my application. I have been looking for possible data structures with google just to find out that most of the ideas are stored in proceedings or to conferences or ieee papers not generally available to me. Is anybody experienced with designing data structures willing to share some ideas with me? Since I am using the open-source version of PyQt4, any information will eventually be available to public (if the app pass the planning stage) if that makes helping out any easier: :-) There is already an app called Qucs that is running in Qt-3 and being ported to Qt-4 that is written in C++, but I don't know how wise it is to just reverse-engineering C++ classes and translate them into python classes. -- Svenn From jsanga at cox.net Thu Jul 10 08:24:57 2008 From: jsanga at cox.net (mzdude) Date: Thu, 10 Jul 2008 05:24:57 -0700 (PDT) Subject: Retrieving BSTR * from a DLL References: <500e422d-5868-4a2b-a213-7d4d13a51d23@j22g2000hsf.googlegroups.com> Message-ID: <3fe43184-d2d8-456b-a5b4-b8a878806bba@z72g2000hsb.googlegroups.com> On Jul 10, 6:15?am, Andrew MacIntyre wrote: > This likely indicates that the DLL is using the C calling convention > and not the stdcall calling convention. ?Use CDLL rather than WinDLL > to load the DLL. using cdll got me over the calling hurdle. However, I'm not seeing the returned BSTR. > You might like to join the ctypes-users mailing list at sourceforge. I did, thanks. From Scott.Daniels at Acm.Org Fri Jul 18 09:08:26 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 18 Jul 2008 06:08:26 -0700 Subject: trying to match a string In-Reply-To: References: Message-ID: arnimavidyarthy at gmail.com wrote: > I am taking a string as an input from the user and it should only > contain the chars:L , M or R How about skipping re's and doing something like: set(input_string) <= set('LMR') If you want to disallow the empty string: set([]) < set(input_string) <= set('LMR') --Scott David Daniels Scott.Daniels at Acm.Org From mrkafk at gmail.com Thu Jul 17 09:56:13 2008 From: mrkafk at gmail.com (mk) Date: Thu, 17 Jul 2008 15:56:13 +0200 Subject: storing references instead of copies in a dictionary In-Reply-To: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: Calvin Spealman wrote: > To your actual problem... Why do you wanna do this anyway? If you want > to change the function in the dictionary, why don't you simply define > the functions you'll want to use, and change the one you have bound to > the key in the dictionary when you want to change it? In other words, > define them all at once, and then just d['1'] = new_f1. What is wrong > with that? Well, basically nothing except I need to remember I have to do that. Suppose one does that frequently in a program. It becomes tedious. I think I will define some helper function then: >>> def helper(fundict, newfun): ... fundict[newfun.func_name] = newfun ... _If_ there were some shorter and still "proper" way to do it, I'd use it. If not, no big deal. > For completeness: > > def new_f1(arg): > return "NEW f1 " + arg > f1.func_code = new_f1.func_code > > Don't use that unless you really have to and I nearly promise that you don't. I promise I won't use it. :-) It seems like a 'wrong thing to do'. From stuart.a.hall at gmail.com Thu Jul 31 14:32:01 2008 From: stuart.a.hall at gmail.com (fprintf) Date: Thu, 31 Jul 2008 11:32:01 -0700 (PDT) Subject: Hobbyist - Python vs. other languages Message-ID: I have been playing with computers since I first learned to program moving shapes on an Atari 800XL in BASIC. After many years of dabbling in programming languages as a hobbyist (I am not a computer scientist or other IT professional), I have never found a way to stick with a language far enough to do anything useful. I learn all about loops and data structures and functions/methods etc. but never get to create a program that will do anything of value that I can't more easily do via freeware. Well, except the slot car timing system I wrote in C++ for Linux many moons ago. Honestly Python seems like a breath of fresh air and possibly a way to get back to my BASIC roots, you know, programming just for the fun of it. Since I don't have a specific problem to solve, besides Pythonchallenge (which I found very cryptic), and Project Euler (which I found beyond my mathematics skills), is there a place to go for increasingly difficult problems to solve? I have followed a number of the recommended online tutorials that contain a logical progression of problems and yet they all end at the point where a person has enough knowledge of the syntax, but not really enough to do anything. From larry.bates at websafe.com` Thu Jul 3 20:56:46 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 03 Jul 2008 19:56:46 -0500 Subject: How to bypass Windows 'cooking' the I/O? (One more time, please) In-Reply-To: References: Message-ID: norseman wrote: > > > I know I saw the answer recently, as in since February '08, but I can't > re-find it. :( I tried the mail archives and such and my own > collections but the piece I saw still eludes me. > > > Problem: (sos=same old s...) Microsoft insists the world work it's way > even when the Microsoft way was proven wrong decades ago. In this case > it's (still) 'cooking' the writes even with 'rwb' and O_RDWR|O_BINARY in > (proper respective) use. > > Specific: python created and inspected binary file ends: > 00460: 0D 1A (this is correct) > > after a write > os.lseek(target, -1, 2) > os.write(target,record) > the expected result would be: > 00460: 0D 20 .....data bytes.... 1A > > BUT I get: > 00460: 20 .... data bytes... 1A > > It is one byte off!!! And the 0D has to be there. Signifies the end of > the header. > > > Same python program runs as expected in Linux. Maybe because that's > where it was written?! :) > > > What I seek is the way to slap Microsoft up side the head and make it > work correctly. OK, well, at least in this situation. > > > Note: Things like this justify Python implementers bypassing OS calls > (data fetch, data write) and using the BIOS direct. Remember, the CPU > understands bit patterns only. It has no comprehension of 'text', > 'program', 'number', 'pointer', blah blah blah.... All that is totally > beyond it's understanding. A given bit pattern means 'do that'. The CPU > is 100% binary. Memory, storage and the rest is just bits-on, bits-off. > Patterns. Proper binary I/O is mandatory for the machine to function. > > > Anyway - if whoever mentioned the flags and such to 'over ride' > Microsoft's BS would re-send that piece I would be very appreciative. > > > Steve > norseman at hughes.net Since you didn't show any code context, I'll try my mind reading superpowers..... You may be the victim of buffering (not calling .flush() or .close() to commit your write to disk). Why aren't you using the file object to do you seek and write? Normal file I/O sequence: fp = open(target, 'wb') fp.seek(-1, 2) fp.write(record) by going through os. methods instead of the file instance I think you are accessing the file through 2 different I/O buffers. I could be all wrong here. -Larry From Nikolaus at rath.org Mon Jul 28 03:38:36 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 28 Jul 2008 09:38:36 +0200 Subject: Attack a sacred Python Cow References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c29cc$0$20302$c3e8da3@news.astraweb.com> <20080727193416.GE7373@dragontoe.org> <488D580B.9050001@gmail.com> Message-ID: <87myk2sbk3.fsf@nokile.rath.org> Michael Torrie writes: > I think the biggest reason why an implicit self is bad is because it > prevents monkey-patching of existing class objects. Right now I can add > a new method to any existing class just with a simple attribute like so > (adding a new function to an existing instance object isn't so simple, > but ah well): > > def a(self, x, y): > self.x = x > self.y = y > > class Test(object): > pass > > Test.setxy = a > > b = Test() > > b.setxy(4,4) > > print b.x, b.y > > If self was implicit, none of this would work. No, but it could work like this: def a(x, y): self.x = x self.y = y class Test(object): pass Test.setxy = a b = Test() # Still all the same until here # Since setxy is called as an instance method, it automatically # gets a 'self' variable and everything works nicely b.setxy(4,4) # This throws an exception, since self is undefined a(4,4) Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From gnuarm at gmail.com Sat Jul 12 00:05:16 2008 From: gnuarm at gmail.com (rickman) Date: Fri, 11 Jul 2008 21:05:16 -0700 (PDT) Subject: spam References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> Message-ID: spam From Russ.Paielli at gmail.com Wed Jul 30 02:39:45 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 23:39:45 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> Message-ID: On Jul 29, 11:36 pm, Erik Max Francis wrote: > Russ P. wrote: > > On Jul 29, 11:09 pm, Erik Max Francis wrote: > > >> I'm getting this sneaking suspicion that you guys are all putting us on. > > > As I said in an earlier post, I realize that this would only work if > > there were only one copy of "empty" (as there is only one copy of > > "None"). I don't know off hand if that is feasible or not. > > It's only feasible if you change what `is` means for this one bizarre > use case, which isn't a good idea. > > > You reply reeks of the kind of pedantic snobbishness that makes me > > sick. > > Well, if understanding what the `is` operator means is pedantic > snobbishness, then hey, go right ahead. > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis > The doors of Heaven and Hell are adjacent and identical. > -- Nikos Kazantzakis I fully understand what the "is" operator is, and I never had any problem with it at all, thank you. But then again, I suppose that depends on what the meaning of "is" is ... From timr at probo.com Sun Jul 27 00:20:37 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 27 Jul 2008 04:20:37 GMT Subject: How to close all python-opened file identifiers? References: Message-ID: BAnderton wrote: > >Question: Is there a way in Python to determine what all file >identifiers have been opened by Python, and to close them all? No. You are expected to be able to track this yourself. Python doesn't open any files that you didn't request. >Extra info on this specific problem: In my program, python (through >subprocess) launched a text editor on a text file, and I can't seem to >save the text file through that editor (I get a "this document is in >use by another application and cannot be accessed" error from the >editor [wordpad on winXp]). The text file in question is modified by >my program prior to its loading into the launched editor. Although I >can't find unmatched "open" and "fid.close()" statements, I'd like to >implement a check for open file identifiers before launching the >editor. If you want to post some code, perhaps we can find something. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From rkmr.em at gmail.com Sun Jul 27 21:26:13 2008 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Sun, 27 Jul 2008 18:26:13 -0700 Subject: write unsigned integer 32 bits to socket Message-ID: hi i want to send unsigned 32 bit integer to socket, and looking for something equivalent to this method... http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt() is there such method / library available in python?! this is as far as i have gotten along >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> s.connect(('127.0.0.1',3000)) From praveen.sunsetpoint at gmail.com Wed Jul 2 07:41:08 2008 From: praveen.sunsetpoint at gmail.com (Sallu) Date: Wed, 2 Jul 2008 04:41:08 -0700 (PDT) Subject: Email Validation with domain Message-ID: Hi All, import re msg=raw_input('Enter the email : ') def validateEmail(email): #if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9] {1,3})(\\]?)$", email) != None: if re.match("^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$", email) != None: print 'Valis' else: print 'not' validateEmail(msg) i wrote a script above it works fine but it does not check for valid domain like .com .org .in how to validate with domain From seberino at spawar.navy.mil Tue Jul 1 02:28:43 2008 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: Mon, 30 Jun 2008 23:28:43 -0700 (PDT) Subject: How make regex that means "contains regex#1 but NOT regex#2" ?? Message-ID: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> I'm looking over the docs for the re module and can't find how to "NOT" an entire regex. For example..... How make regex that means "contains regex#1 but NOT regex#2" ? Chris From Inyeol.Lee at gmail.com Fri Jul 11 09:01:33 2008 From: Inyeol.Lee at gmail.com (Inyeol.Lee at gmail.com) Date: Fri, 11 Jul 2008 06:01:33 -0700 (PDT) Subject: How to serialize and deserialize the objects into memory? References: <0a7ead85-2a38-41a8-98b8-59dede61f985@c58g2000hsc.googlegroups.com> Message-ID: <099408eb-30d4-4ad5-bb22-af238c7aca58@l64g2000hse.googlegroups.com> On Jul 11, 12:58 pm, hardemr wrote: > Hello Everyone, > > I want to serialize and deserialize the objects into Memory not into > file. How can i do that? pickle.dumps and pickle.loads. --Inyeol From mdw at distorted.org.uk Sun Jul 6 12:50:20 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Sun, 6 Jul 2008 16:50:20 +0000 (UTC) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Sebastian "lunar" Wiesner wrote: > I just wanted to illustrate, that the speed of the given search is somehow > related to the complexity of the engine. > > Btw, other pcre implementation are as slow as Python or "grep -P". I tried > a sample C++-code using pcre++ (a wrapper around libpcre) and saw it > running equally long. So some other implementations are equally poor. I note that Perl itself handles this case very quickly, as does Edi Weitz's CL-PPCRE library. Yes, Perl-compatible `regular expressions' are more complicated than POSIX extended regular expressions; but that doesn't mean that you have to implement them in a dumb way. Indeed, it stands to reason that expressions describing truly regular languages can be matched using the same old algorithms that grep uses. -- [mdw] From asmodai at in-nomine.org Thu Jul 24 07:59:53 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 24 Jul 2008 13:59:53 +0200 Subject: how to cut and paste in the windows of python(command line) In-Reply-To: References: <9500663c-0985-4dfd-8d0a-ae25411f00e5@v39g2000pro.googlegroups.com> Message-ID: <20080724115953.GU57040@nexus.in-nomine.org> -On [20080724 13:50], Fredrik Lundh (fredrik at pythonware.com) wrote: >if you want better console support, consider installing the "ipython" >shell: Unless you work with non-ASCII. Ipython mangles non-ASCII unfortunately. [Full UTF-8 environment] In [1]: a = u'?' In [2]: a Out[2]: u'\xe6\x84\x9b' Normal python shell: >>> a = u'?' >>> a u'\u611b' I wonder if it can be easily fixed with a getpreferredencoding() or by using an .encode(sys.stdout.encoding or getpreferredencoding() or 'ascii', 'replace') triplet. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B One who knows that enough is enough will always have enough... From adityashukla1983 at gmail.com Mon Jul 28 00:13:19 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Sun, 27 Jul 2008 23:13:19 -0500 Subject: Command line arguements Message-ID: <73045cca0807272113y397de468yfcb00ffbbec7990a@mail.gmail.com> Hello folks ,I have a program in which a text file is generated as an output eg C:\prog\ prog -x test.txt Right now whenever i have to read the test file i have to put its name manually in my code. eg f=open("c:\\prog\\test.txt","r") How ever i want to add the name of the test file dynamically to my program ie , if every time i give C:\prog\ prog -x test.txt The filename (test.txt) automatically comes in f=open("c:\\prog\\test.txt","r") C:\prog\ prog -x file1.txt f=open("c:\\prog\\file1","r") in other words i do not want to do hard code the name of the file in my code every time i need to read it. I was reading about the sys module and i guess sys.argv would take the input from the command line whenever i run the python script . Please guide me in the right direction on how to tackle the problem. Thanks in advance Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From dullrich at sprynet.com Thu Jul 24 12:26:12 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 24 Jul 2008 11:26:12 -0500 Subject: repr(string) References: Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > David C. Ullrich wrote: > > > In article , > > Fredrik Lundh wrote: > > > >> David C. Ullrich wrote: > >> > >> > I've been saving data in a file with one line per field. > >> > Now some of the fields may become multi-line strings... > >> > > >> > I was about to start escaping and unescaping linefeeds > >> > by hand, when I realized that repr() and eval() should > >> > do. Hence the question: If s is a string, is repr(s) > >> > guaranteed not to contain line breaks? > >> > >> yes. > >> > >> just keep in mind that using eval() on untrusted data isn't a very good > >> idea. > > > > Right. This data comes from me, gets put into a file and then > > read by me. Someone _could_ corrupt that file, but someone who > > could do that could more easily just throw the machine out > > the window... > > You could also use a csv file with a single row. Excellent suggestion. I have a different point of view on all this than most of you guys (see reply to F). From my curious point of view csv was no fun anymore when csvlib got added to Python... > Peter -- David C. Ullrich From grante at visi.com Tue Jul 1 10:07:07 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 01 Jul 2008 09:07:07 -0500 Subject: Implementing an 8 bit fixed point register References: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> Message-ID: On 2008-07-01, nickooooola wrote: > Hello to all > I'm about to write a simulator for a microcontroller in python > (why python? because I love it!!!) > > but I have a problem. > > The registry of this processor are all 8 bit long (and 10 bit > for some other strange register) and I need to simulate the > fixed point behaviour of the register, Somebody posted a class that impliments fixed-width integer types a while back. > and to access the single bit. The bitwise operators &, |, ~, ^ all work just like they do in C. You can write methods to dip those in syntactic sugar if you want. > f.x. (this is a pseudo python session, only for understanding) > >>>> reg1 = fixed_int(8) >>>> reg2 = fixed_int(10) >>>> reg1[0].set() > or >>>> reg1[0] = 1 # or True? how to rapresent a binary bit >>>> reg1[0] > 1 >>>> reg1[1] > 0 >>>> reg1[9] > >>>> reg2 = 0x7FE # in binary 11111111110 , or 11 bit long >>>> reg2 > 0x7FE > #or 1111111110, the memorization truncate the upper bits ( or perhaps > generate an exception?) >>>> reg2 += 0x02 #the result is 10000000000, again not contained in 10 bit >>>> reg2 > 0x00 > # truncated again >>>> myprocessor.flags['z'] > 1 > # or True? Z flag indicated an overflow in arithmetic operations > > Is possibile to do so in python? Yes. Everything shown above is possible. If you really want to get clever, you'll want to read up on the __setattr__, __getattr__, __getitem__, and __setitem__ object methods. They'll allow you to define special handling for the semantics below: foo.something = x # calls foo.__setattr___('something',x) x = foo.something # calls foo.__getattr___('something,) foo[n] = x # calls foo.__setitem__(n,x) x = foo[n] # calls foo.__getitme__(n) In the latter two cases, you can support slicing if you want. That could allows you to grab a "bitfield" out of a register: x = processor.regA[4:7] # get bits 4,5,6 processor.regA[4:7] # set bits 4,5,6 Just remember that in Python slices are traditionally half-open intervals -- they don't include the "right" endpoint. That's going to confuse people who are more used to reading processor data sheets where bit-ranges are traditionally closed intervals. You _could_ implment your __[sg]etitem__ slice handling so that they're treated as closed intervals. That will be a lot more intuitive to people used to dealing with microprocessor register definitions, but could confuse an experienced Python programmer. Writing methods for __setattr__ and __getattr__ is a little tricky. It's very easy to end up with infinite recursion. It's not that hard to fix/avoid, but it takes a while to get the hang of it. -- Grant Edwards grante Yow! at visi.com From manuel.dipl at gmail.com Tue Jul 15 03:36:21 2008 From: manuel.dipl at gmail.com (manu) Date: Tue, 15 Jul 2008 00:36:21 -0700 (PDT) Subject: trying to use sax for a very basic first xml parser References: <6ff86003-a3e8-4c5b-9276-1cd3c7f0ffa7@56g2000hsm.googlegroups.com> <3a7148a9-b95d-4e95-b3b7-492e0d016ab8@f36g2000hsa.googlegroups.com> <3cd4f2b6-8bd1-49c3-9958-de1af69b86af@f36g2000hsa.googlegroups.com> Message-ID: <882147ac-8998-465a-b16e-5a3a767d91d1@i76g2000hsf.googlegroups.com> > > May I suggest you ask in the blender list? > Will do that and report back. Thank you! Manuel From pyth0nc0d3r at gmail.com Wed Jul 9 03:13:48 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Wed, 9 Jul 2008 02:13:48 -0500 Subject: Regular Expressions Quick Question Message-ID: Alright, basically I have a list of words in a file and I load each word from each line into the array. Then basically the question is how do I check if the input word matches multiple words in the list. Say someone input "test", how could I check if that word matches these list of words: test testing tested Out of the list of Hello blah example test ested tested testing I want it to loop then check if the input word I used starts any of the words in the list so if I typed 'tes' Then: test testing testing would be appended to a new array. I'm unsure how to do this in python. Thanks in advanced. -------------- next part -------------- An HTML attachment was scrubbed... URL: From animator333 at gmail.com Fri Jul 18 05:36:20 2008 From: animator333 at gmail.com (King) Date: Fri, 18 Jul 2008 02:36:20 -0700 (PDT) Subject: sub typing built in type with common attributes. Am I right? References: <4d9c4b74-9c28-4b98-afe7-9eb774655c3a@v21g2000pro.googlegroups.com> Message-ID: <98c3de7d-f167-48f9-9736-b09938d96b92@f40g2000pri.googlegroups.com> My mistake... The correct __slots__ is like: __slots__ = ['_Attribute_name', '_Attribute_type', '_Attribute_range', 'label'] Could you please suggest an alternative or code improvement for the matter. Prashant From 4564 at 755189.45 Tue Jul 29 03:45:07 2008 From: 4564 at 755189.45 (Enrico) Date: Tue, 29 Jul 2008 09:45:07 +0200 Subject: multiple inheritance and __getattr__ References: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> <488e2e70$0$29472$426a74cc@news.free.fr> Message-ID: <488ecaaa$0$1090$4fafbaef@reader1.news.tin.it> "Bruno Desthuilliers" ha scritto nel messaggio news:488e2e70$0$29472$426a74cc at news.free.fr... > Indeed. You explicitely raise, so the lookup stops here. You'd need to > explicitely call on superclass instead to have B.__getattr__ called, ie: > > class A(object): > def __getattr__(self, name): > if name == 'a': > return 1 > return super(A, self).__getattr__(name) > > class B(object): > def __getattr__(self, name): > if name == 'b': > return 2 > return super(B, self).__getattr__(name) Hi Bruno, this is an interisting point. Just to understand better: when I raise an AttributeError the search stops but if I call a superclass (that for my understanding raises an AttributeError) the search continues. At this point I suspect that the search is doing something else, like checking if the class is at the top of the hierarchy. Do you know where I can look for this, probably in the core code of Python? > > Since A and B are not written by me I can only work on C. > > Really ? You know, Python is a *very* dynamic language. If A and B are > ordinary Python classes (ie: not builtin types, not C extensions, etc), > you can monkeypatch them. But that's not necessarily the best thing to > do (it would require more work than your actual solution). I know that I can do whatIwant with class A and class B (monkeypatch!) but I prefer to concentrate on my code and write a clean solution. Thanks for your help. Enrico From pyth0nc0d3r at gmail.com Sat Jul 19 15:13:04 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Sat, 19 Jul 2008 14:13:04 -0500 Subject: win32api not found? Message-ID: Where can I get the win32api module? I been searching all day on google and nothing, i installed https://sourceforge.net/project/showfiles.php?group_id=78018 which requires win32api and its not found... -------------- next part -------------- An HTML attachment was scrubbed... URL: From Bill at SynectixLtd.com Thu Jul 10 09:39:28 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Thu, 10 Jul 2008 14:39:28 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: "Tim Roberts" wrote in message news:h6k074119o4gomqlkju3mp7rj3i1bvha6j at 4ax.com... > "Bill Davy" wrote: >> >>I am trying to edit Contacts in Outlook. This is so I can transfer >>numbers >>from my address book which is an Excel spreadsheet to my mobile phone. > > Are you actually running Outlook? Your news posting was made from Outlook > Express, and Outlook Express cannot be controlled by COM (although MAPI > works). > -- > Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. I'm not sure OL2003 can read news. I think perhaps some later OL can (added tot he View menu, perhaps?). So I use OL Express to read news. The OL with which I wish to communicate is: Application name Outlook Version 11.0 Build 8217 Product ID 70141-700-0350904-56905 Language English (United States) Application Path C:\Program Files\Microsoft Office\OFFICE11\ System Language English (United Kingdom) Mail Support Not Available Current folder Inbox Current item Not Available Not sure why its says "Mail Support Not Available" as all I use it for is email (oh, and the calendar). Hey and ho Bill From h.goebel at goebel-consult.de Mon Jul 14 12:02:23 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Mon, 14 Jul 2008 18:02:23 +0200 Subject: Using McMillan Installer, PyInstall or py2exe cross-platform? Message-ID: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> Hi, has anybody used McMillan Installer, PyInstall or py2exe cross-platform? I have a Windows partition with Python installed there, so this would "only" required working on a different directory and for a different OS. Since I'm working on Linux, it's awful to boot Windows each time I want to build a new release. Any hint in this area? -- Sch?nen Gru? - Regards Hartmut Goebel Goebel Consult Spezialist f?r IT-Sicherheit in komplexen Umgebungen http://www.goebel-consult.de From davidreynon at gmail.com Thu Jul 17 10:33:08 2008 From: davidreynon at gmail.com (korean_dave) Date: Thu, 17 Jul 2008 07:33:08 -0700 (PDT) Subject: % sign in python? Message-ID: What does this operator do? Specifically in this context test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) (Tried googling and searching, but the "%" gets interpreted as an operation and distorts the search results) From basti.wiesner at gmx.net Sun Jul 6 11:34:04 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sun, 06 Jul 2008 17:34:04 +0200 Subject: Hands-on HTML Table Parser/Matrix? References: Message-ID: robert : > Often I want to extract some web table contents. Formats are > mostly static, simple text & numbers in it, other tags to be > stripped off. So a simple & fast approach would be ok. > > What of the different modules around is most easy to use, stable, > up-to-date, iterator access or best matrix-access (without need > for callback functions,classes.. for basic tasks)? Not more than a handful of lines with lxml.html: def htmltable2matrix(table): """Converts a html table to a matrix. :param table: The html table element :type table: An lxml element """ matrix = [] for row in table: matrix.append([e.text_content() for e in row]) return matrix -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From elessar at nienna.org Fri Jul 4 03:52:04 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 04 Jul 2008 01:52:04 -0600 Subject: Singleton implementation problems In-Reply-To: <87abgy2kcu.fsf@benfinney.id.au> References: <87abgy2kcu.fsf@benfinney.id.au> Message-ID: <486DD6A4.2080307@nienna.org> Ben Finney wrote: > Peter Otten <__peter__ at web.de> writes: > >> The problem is the structure of your program. The myset module is >> imported twice by Python, once as "myset" and once as "__main__". > > Yes, this is the problem. Each module imports the other. > >> Therefore you get two distinct MySet classes, and consequently two >> distinct MySet.__instance class attributes. > > Are you sure? This goes against my understanding: that 'import foo' > will not re-import a module that's already been imported, but will > instead simply return the existing module. > > So, I think if one evaluated 'myset is __main__', you'd find they are > exactly the same module under different names; and therefore that > there is only *one* instance of 'MySet', again under two names. > You can see that they're distinct by checking the addresses (the instances in the OP also have different addresses). Besides, __main__ isn't imported normally. -Matt From ptmcg at austin.rr.com Tue Jul 22 13:36:14 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 22 Jul 2008 10:36:14 -0700 (PDT) Subject: Not entirely serious: recursive lambda? References: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> Message-ID: On Jul 22, 11:52?am, Michael Tobis wrote: > Thanks all! What a remarkable set of answers, intelligent, thought > provoking and informative without exception. > > Of course, now I can't use Paul's version; it hardly counts as a japh > if someone else wrote it! It is probably the closest to my original > vision, alas. Miles' second suggestion was the one I was fumbling > toward; I will study it. No spoilers please. > > best > mt Michael - Sorry to spoil your fun - the concept of a recursive lambda was such an interesting diversion, I couldn't resist! I'll try to restrain myself next time. -- Paul From stefan_ml at behnel.de Wed Jul 23 12:29:22 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 23 Jul 2008 18:29:22 +0200 Subject: lxml, comparing nodes In-Reply-To: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> Message-ID: <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> code_berzerker wrote: > I'd like to know if there is any built in mechanism in lxml that lets > you check equality of two nodes from separate documents. No, because, as you state yourself, equality is not something that everyone defines the same way. > I'd like it > to ignore attribute order and so on. It would be even better if there > was built in method for checking equality of whole documents (ignoring > document order). Please let me know if you know of such method or > existing scipt. I dont like reinventing the wheel :) Your requirements for a single Element are simple enough to write it in three to five lines of Python code (depending on your definition of equality). Checking this equality recursively is another two to three lines. Not complex enough to be considered a wheel in the first place. Stefan From kyosohma at gmail.com Mon Jul 28 15:21:02 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 28 Jul 2008 12:21:02 -0700 (PDT) Subject: how to upload files to "google code" filesection ? References: <7f6182a3-4504-4239-8239-673a7e4bfefd@s50g2000hsb.googlegroups.com> Message-ID: <63de76c2-349c-4371-8732-1681301c7ab0@a1g2000hsb.googlegroups.com> Stef, > Mike Driscoll wrote: > > On Jul 26, 12:43 pm, Stef Mientki wrote: > > >> hello, > > >> In a program I want to download (updated) files from google code (not > >> the svn section). > >> I could find a python script to upload files, > >> but not for downloading. > > >> Anyone has a hint or a solution ? > > >> thanks, > >> Stef Mientki > > > You should be able to use urllib to do that. The following link has a > > recipe: > > >http://code.activestate.com/recipes/496685/ > > thanks Mike, > > I already found an even simpler solution (that works) > > ? ? filename, header = urllib.urlretrieve (url) > > > If you need to search Google Code, there's an API that appears to be > > exposed through their gdata module. > > Do you have perhaps a more specific link ? > I saw the Google API's, but its'quit large / complex, so I couldnt find > it there. > > cheers, > Stef > > > Mike I was looking at this page about Google Code Search: http://code.google.com/apis/codesearch/ You should be able to use the API that's outlined there in conjunction with the gdata module on this page: http://code.google.com/p/gdata-python-client/ Mike From wtanksleyjr at gmail.com Tue Jul 29 13:53:41 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Tue, 29 Jul 2008 10:53:41 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> Message-ID: <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> To ask another way: how do I convert from a file:// URL to a local path in a standard way, so that filepaths from two different sources will work the same way in a dictionary? Right now I'm using the following source: track_id = url2pathname(urlparse(track_id).path) url2pathname is from urllib; urlparse is from the urlparse module. The problems occur when the filenames have non-ascii characters in them -- I suspect that the URLs are having some encoding placed on them that Python's decoder doesn't know about. Thank you all in advance, and thank you for Python. -Wm From bj_666 at gmx.net Mon Jul 21 13:21:48 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Jul 2008 17:21:48 GMT Subject: Python Written in C? References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> Message-ID: <6ejutcF6vgp3U4@mid.uni-berlin.de> On Mon, 21 Jul 2008 18:12:54 +0200, mk wrote: > Seriously, though, would there be any advantage in re-implementing > Python in e.g. C++? > > Not that current implementation is bad, anything but, but if you're not > careful, the fact that lists are implemented as C arrays can bite your > rear from time to time (it recently bit mine while using lxml). Suppose > C++ re-implementation used some other data structure (like linked list, > possibly with twists like having an array containing pointers to 1st > linked list elements to speed lookups up), which would be a bit slower > on average perhaps, but it would behave better re deletion? An operation that most people avoid because of the penalty of "shifting down" all elements after the deleted one. Pythonistas tend to build new lists without unwanted elements instead. I can't even remember when I deleted something from a list in the past. Ciao, Marc 'BlackJack' Rintsch From rhamph at gmail.com Wed Jul 30 13:51:00 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 30 Jul 2008 10:51:00 -0700 (PDT) Subject: static variables in Python? References: Message-ID: <977b55ed-6fb1-4f5e-9090-047972e69c0c@n33g2000pri.googlegroups.com> On Jul 29, 2:40?pm, kj wrote: > Yet another noob question... > > Is there a way to mimic C's static variables in Python? ?Or something > like it? ?The idea is to equip a given function with a set of > constants that belong only to it, so as not to clutter the global > namespace with variables that are not needed elsewhere. I'd go ahead and use globals. If these really are constant you should just name them clearly (and possibly use all caps). If they have a possibility of becoming non-constant in the future, write a class. No fancy tricks needed to store state. From deets at nospam.web.de Tue Jul 22 08:51:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 14:51:30 +0200 Subject: is it possible to add a property to an instance? References: Message-ID: <6em3gfF7o4qgU2@mid.uni-berlin.de> Darren Dale wrote: > Does anyone know if it is possible to add a property to an instance at > runtime? I didn't see anything about it in the standard library's new > module, google hasn't turned up much either. Depending on what you *really* want - yes or no. It is *not* possible to have a property *only* on one instance, because properties rely on the descriptor-protocol being used, and that only works for class-attributes. So it's not a matter of "only" adding a = Foo() a.something = property(...) However, you can of course try & come up with a scheme that only invokes getters and setters if defined, and otherwise returns a default-value/raises an attribute-error. Roughly like this: class Base(object): def x_get(self): return self.x_get_overload() x = property(x_get) a = Base() def foo(self): return "something" a.x_get_overload = new.instancemethod(foo) Diez From Samnsparky at gmail.com Tue Jul 15 14:16:09 2008 From: Samnsparky at gmail.com (Sparky) Date: Tue, 15 Jul 2008 11:16:09 -0700 (PDT) Subject: File Locking Forced? Newbie question. References: <216e2396-65f6-4281-b3c5-754ceb07f3eb@m36g2000hse.googlegroups.com> Message-ID: On Jul 15, 11:38?am, Tim Golden wrote: > Sparky wrote: > > Hello! I am writing some software that will have many users accessing > > the same file resource at once for reading purposes only. I am > > programming on (Ubuntu) Linux and my question is in Windows, can I > > have it so that the same file can be open in read mode by more than > > one person or could Window's file locking system get in the way? > > Assuming your question is: can processes A, B & C read > from the same file at the same time, then: Yes. (You > can try it out yourself fairly easily if you want. Just > open a clutch of interpreter windows and do some > open ("abc.txt", "r").read () stuff in each one). > > But I'm surprised you think that anything might get > in the way of that. It would be a fairly limiting file > system which prevented multiple simultaneous readers. > > TJG Thank you. For some reason I thought there was a file locking system on Windows (http://en.wikipedia.org/wiki/ File_locking#File_locking_in_Microsoft_Windows). But, I believe that that only applies to those using Microsoft's file methods and only for writing. Thanks for clearing that up. Sam From moogyd at yahoo.co.uk Sat Jul 12 14:55:54 2008 From: moogyd at yahoo.co.uk (moogyd at yahoo.co.uk) Date: Sat, 12 Jul 2008 11:55:54 -0700 (PDT) Subject: Beginner Question : Iterators and zip Message-ID: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> Hi group, I have a basic question on the zip built in function. I am writing a simple text file comparison script, that compares line by line and character by character. The output is the original file, with an X in place of any characters that are different. I have managed a solution for a fixed (3) number of files, but I want a solution of any number of input files. The outline of my solution: for vec in zip(vec_list[0],vec_list[1],vec_list[2]): res = '' for entry in zip(vec[0],vec[1],vec[2]): if len(set(entry)) > 1: res = res+'X' else: res = res+entry[0] outfile.write(res) So vec is a tuple containing a line from each file, and then entry is a tuple containg a character from each line. 2 questions 1) What is the general solution. Using zip in this way looks wrong. Is there another function that does what I want 2) I am using set to remove any repeated characters. Is there a "better" way ? Any other comments/suggestions appreciated. Thanks, Steven From larry.bates at websafe.com` Tue Jul 1 14:57:16 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 01 Jul 2008 13:57:16 -0500 Subject: Convert string to char array In-Reply-To: <0%uak.283$4a3.73@trnddc04> References: <0%uak.283$4a3.73@trnddc04> Message-ID: Brandon wrote: > How do I convert a string to a char array? I am doing this so I can edit > the string received from an sql query so I can remove unnecessary > characters. > > The precise answer is: >>> s = 'abcdefghi' >>> l = list(s) >>> l ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] >>> But quite often you can just to the replace without doing the conversion >>> s = 'abc,de,fghi' >>> s2 = s.replace(',','') >>> s2 = s.replace(',','') 'abcdefghi' >>> -Larry From mhansen at gmail.com Wed Jul 9 22:40:59 2008 From: mhansen at gmail.com (Mike Hansen) Date: Wed, 9 Jul 2008 19:40:59 -0700 (PDT) Subject: sage vs enthought for sci computing References: <677e7819-e09e-43d3-8368-5864f91002be@34g2000hsh.googlegroups.com> Message-ID: On Jul 7, 3:35?pm, jadamwils... at gmail.com wrote: > Hello, > I have recently become interested in using python for scientific > computing, and came across both sage and enthought. I am curious if > anyone can tell me what the differences are between the two, since > there seems to be a lot of overlap (from what I have seen). If my goal > is to replace matlab (we do signal processing and stats on > physiological data, with a lot of visualization), would sage or > enthought get me going quicker? I realize that this is a pretty vague > question, and I can probably accomplish the same with either, but what > would lead me to choose one over the other? > Thanks! Hello, If you are using Windows, you're better off using Enthought for now since Sage does not run natively on Windows yet. Hopefully by the end of the year there will be a native version on Windows. If you're on Linux or OS X (or Solaris in the near future), then Sage does have some advantages. If you build Sage from source (which consists solely of type "make" once), then you get a copy of ATLAS tuned to your machine which can provide a solid speedup for numerical linear algebra problems. You also get all of the symbolic and exact arithmetic which may or may not be beneficial for your application. Sage also comes with libraries so that you can script Octave or Matlab or most any other system. --Mike Full disclosure: I'm a Sage developer :-) From paddy3118 at googlemail.com Sat Jul 12 01:49:30 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 11 Jul 2008 22:49:30 -0700 (PDT) Subject: read file into list of lists References: <1388b868-aae9-4233-b3ec-a85ffc029283@56g2000hsm.googlegroups.com> Message-ID: <59724a9a-6f49-448f-aaa3-dcf4c79ef96b@56g2000hsm.googlegroups.com> On Jul 11, 9:32?pm, John Machin wrote: > On Jul 11, 11:35 pm, Paddy wrote: > > > > > On Jul 11, 2:15 pm, antar2 wrote: > > > > Hello, > > > > I can not find out how to read a file into a list of lists. I know how > > > to split a text into a list > > > > sentences = line.split(\n) > > > > following text for example should be considered as a list of lists (3 > > > columns and 3 rows), so that when I make the print statement list[0] > > > [0], that the word pear appears > > > > pear noun singular > > > books nouns plural > > > table noun singular > > > > Can someone help me? > > > > Thanks > > > lofl = [line.strip().split() for line in the_opened_file] > > >>> line = ' ? foo ? bar ? ' > >>> line.strip().split() > ['foo', 'bar'] > >>> line.split() > > ['foo', 'bar'] Thanks , ta. - Paddy. From dingbat at codesmiths.com Thu Jul 31 06:10:26 2008 From: dingbat at codesmiths.com (Andy Dingley) Date: Thu, 31 Jul 2008 03:10:26 -0700 (PDT) Subject: SVN access with pysvn under Cygwin (Installation problems) References: <69da0a81-bf73-46cb-a762-b017a53e6ddf@e39g2000hsf.googlegroups.com> Message-ID: <4cd368f8-6402-4f3e-8496-d9d227b39dd9@m73g2000hsh.googlegroups.com> On 30 Jul, 20:30, Jason Tishler wrote: > You need to build (and install) pysvn under Cygwin. ?The pre-built > Windows version will not work under Cygwin. Thanks. Presumably this same problem would affect anything that uses a .pyd under Cygwin? From google at mrabarnett.plus.com Thu Jul 31 19:26:32 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 31 Jul 2008 16:26:32 -0700 (PDT) Subject: find and replace with regular expressions References: Message-ID: On Jul 31, 9:07?pm, chrispoliq... at gmail.com wrote: > I am using regular expressions to search a string (always full > sentences, maybe more than one sentence) for common abbreviations and > remove the periods. ?I need to break the string into different > sentences but split('.') doesn't solve the whole problem because of > possible periods in the middle of a sentence. > > So I have... > > ---------------- > > import re > > middle_abbr = re.compile('[A-Za-z0-9]\.[A-Za-z0-9]\.') > > # this will find abbreviations like e.g. or i.e. in the middle of a > sentence. > # then I want to remove the periods. > > ---------------- > > I want to keep the ie or eg but just take out the periods. ?Any > ideas? ?Of course newString = middle_abbr.sub('',txt) where txt is the > string will take out the entire abbreviation with the alphanumeric > characters included. It's recommended that you should use a raw strings for regular expressions. Capture the letters using parentheses: middle_abbr = re.compile(r'([A-Za-z0-9])\.([A-Za-z0-9])\.') and replace what was found with what was captured: newString = middle_abbr.sub(r'\1\2', txt) HTH From glman74 at gmail.com Sun Jul 27 11:44:07 2008 From: glman74 at gmail.com (glman74 at gmail.com) Date: Sun, 27 Jul 2008 08:44:07 -0700 (PDT) Subject: Iterating through 2 files simultaneously References: <7ae96aff-c1a7-4763-8db7-ff23766296df@u6g2000prc.googlegroups.com> Message-ID: > > So import STDOUT and make stderr=STDOUT in the Popen call, you will then > have one file/pipe to deal with p1.stdout. Thank you - that works great! Mahesh From semanticist at gmail.com Sun Jul 13 21:31:53 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 21:31:53 -0400 Subject: socket.connect() hangs in SYN_SENT state. In-Reply-To: References: <804bccb2-42c7-42e9-8f50-7a780d3438fd@j22g2000hsf.googlegroups.com> Message-ID: On Sun, Jul 13, 2008 at 8:35 PM, bukzor wrote: > The problem only manifests about 1 in 20 runs. Below there's code for > a client that shows the problem 100% of the time. > > The two URL's that I seem to be "confused" about point to the same IP. > Maybe this will make it clear: > > PING bukzor.hopto.org (75.61.84.249) 56(84) bytes of data. > 64 bytes from adsl-75-61-84-249.dsl.pltn13.sbcglobal.net > (75.61.84.249): icmp_seq=1 ttl=255 time=1.68 ms For me, buzkor.hopto.org resolves to 69.65.19.125, which I hope explains why I thought you were confused, and increases my own suspicion that DNS settings are to blame. I let the script run for about five minutes without it failing. Does your luck change if you use "localhost" or a numeric IP address in the ServerProxy URL? -Miles From tmohr at s.netic.de Fri Jul 18 11:03:43 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Fri, 18 Jul 2008 17:03:43 +0200 Subject: create PyString Message-ID: Hi, in an extension module i'd like to create a very large PyString. As the string is very large i'd first like to create the string and let Python allocate the space for it and then fill it from my code. But the only interface that i can find in Python/stringobject.h is: PyAPI_FUNC(PyObject *) PyString_FromStringAndSize(const char *, Py_ssize_t); But my extension module does not have the data consecutively in memory. If i'd use this function i'd first have to allocate the data, construct the string and then let python _again_ allocate the same amount of memory and copy my data. Is there a way to tell python to: 1. let python create a PyString with an allocated buffer 2. let my extension module fill the buffer 3. let python validate the strings hash value and whatever else is necessary? Thanks for any hints, Torsten. From bignose+hates-spam at benfinney.id.au Wed Jul 30 00:10:17 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 30 Jul 2008 14:10:17 +1000 Subject: Is it allowed to use function results as default arguments ? References: Message-ID: <87abg0dnbq.fsf@benfinney.id.au> "fred.haab" writes: > Well, others have answered the question, but I thought I'd throw in > that it would be more pythonic to do something like: > > def Get_Relative_Path(target, base = None): > if base is None: > base = os.curdir > ... Even more Pythonic would be to name the function by the style guide (PEP 8): def get_relative_path(target, base=None): if base is None: base = os.curdir # ? -- \ ?If trees could scream, would we be so cavalier about cutting | `\ them down? We might, if they screamed all the time, for no good | _o__) reason.? ?Jack Handey | Ben Finney From robert.rawlins at thinkbluemedia.co.uk Wed Jul 16 07:56:08 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Wed, 16 Jul 2008 12:56:08 +0100 Subject: Get current class namespace. Message-ID: <011401c8e73a$ef2fdd30$cd8f9790$@rawlins@thinkbluemedia.co.uk> Guys, What's the simplest way to access a classes namespace from within itself. I want to use it in a custom __repr__() method so it prints the current namespace for the class like package.module.class. Suggestions? I'm sure there is a simple enough method built in to help me here, I've just not seen it before. Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Sun Jul 13 09:56:40 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 13 Jul 2008 23:56:40 +1000 Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> <87skuems49.fsf@benfinney.id.au> Message-ID: <873amddh0n.fsf@benfinney.id.au> Roy Smith writes: > Ben Finney wrote: > > > If you are passing a sequence conceptually, then it's more Pythonic to > > pass it as a sequence explicitly:: > > > > def __init__(self, items): > > """ Call with e.g. Stack(["foo", "bar"]) """ > > self.stack = list(items) > > I don't get this. You're forcing a copy to be made of the list. The 'items' object might not be a list; it might be some other sequence. The rest of the class (as shown by the original poster) requires it to be a list. > This changes the semantics of the original class, because the > operations no longer change the original list. Which "original class" are you referring to? The one posted by the original poster of this thread had no "original list"; it gathered the positional arguments (using '*items') into an 'items' parameter, which *doesn't exist* until the function body executes. There *is* no "original list" in that implementation posed by the original poster; it's constructed at call time from the positional parameters to the function. If anything, my implementation above *preserves* that semantic, by making a new list from the passed-in sequence. -- \ ?Consider the daffodil. And while you're doing that, I'll be | `\ over here, looking through your stuff.? ?Jack Handey | _o__) | Ben Finney From max at alcyone.com Thu Jul 31 01:43:21 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Jul 2008 22:43:21 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > On Jul 30, 9:27 pm, Erik Max Francis wrote: >> You're sure going on about a distinction without a difference for a guy >> who childishly likes to call other people names. A reasonable person >> would have long ago moved on instead of blaming others for not >> immediately intuiting your thoughts, rather than straightforwardly >> reading your words. Which, by the way, includes at least three people >> other than myself. >> >> But I'll bet the mindless namecalling is really working out for you. >> Go, team, go! > > You earned the "childish name calling" by acting like a child -- with > your petty little game of trying to show that I don't understand a > basic concept in Python. As I said, your initial misunderstanding, > while silly, was at least forgivable. But your insistence on repeating > it time after time is not. It is truly pathetic. Sis, boom, rah rah rah! You're kind of skipping over the point where three other people had the same misunderstanding about your original statement and correction, so maybe the reader is not the problem but rather the writer, but hey, don't let that get in the way of a good public shitfit. You're winning! -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis I am not a Virginian, but an American. -- Patrick Henry From sunp1028 at gmail.com Sun Jul 13 08:16:46 2008 From: sunp1028 at gmail.com (patrol) Date: Sun, 13 Jul 2008 05:16:46 -0700 (PDT) Subject: About wmi Message-ID: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> I want to prevent some process from running. The code is in the following. I encounter some unexpected troubles. Probelm1: This program cannot terminate "scrcons.exe" and "FNPLicensingService.exe",which are system processes. Problem2:After a while, this program will abort by error File "C:\Python25\lib\wmi.py", line 397, in __call__ handle_com_error (error_info) File "C:\Python25\lib\wmi.py", line 190, in handle_com_error raise x_wmi, "\n".join (exception_string) UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 14: ordinal not in range(128) ---------------------------------------------------- code---------------------------------------------------------------------------------- # -*- coding:utf-8 -*- import pythoncom import wmi import threading import time from xml.dom.minidom import parse, parseString class Info (threading.Thread): def __init__ (self): threading.Thread.__init__ (self) def run (self): print 'In Another Thread...' pythoncom.CoInitialize () dom1 = parse('processTerminateList.xml') config_element = dom1.getElementsByTagName("processTerminateList") [0] servers = config_element.getElementsByTagName("processName") try: c = wmi.WMI () for process in c.Win32_Process (): for server in servers: if process.name == getText(server.childNodes): process.Terminate() print process.name process_watcher = c.Win32_Process.watch_for("creation") while True: new_process = process_watcher() name = new_process.Caption print name for server in servers: if name == getText(server.childNodes): new_process.Terminate() finally: pythoncom.CoUninitialize () def getText(nodelist): rc = "" for node in nodelist: if node.nodeType == node.TEXT_NODE: rc = rc + node.data return rc if __name__ == '__main__': Info().start() ------------------------------------------------------ processTerminateList.xml----------------------------------------------------------------------- scrcons.exe TXPlatform.exe mdm.exe FNPLicensingService.exe notepad.exe uedit32.exe From Lie.1296 at gmail.com Sat Jul 26 01:15:04 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 25 Jul 2008 22:15:04 -0700 (PDT) Subject: xml.dom's weirdness? Message-ID: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> Why this generates AttributeError, then not? Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import xml >>> xml.dom Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'dom' >>> xml.dom >>> From sjmachin at lexicon.net Tue Jul 15 20:19:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 15 Jul 2008 17:19:35 -0700 (PDT) Subject: How to figure out if the platform is 32bit or 64bit? References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: On Jul 16, 6:10 am, kjhish... at gmail.com wrote: > I need to know if I'm running on 32bit or 64bit ... so far I haven't > come up with how to get this info via python. sys.platform returns > what python was built on ... but not what the current system is. > > I thought platform.uname() or just platform.processor() would have > done it, but python returns an empty string on windows. Any ideas? > >>> import sys >>> hex(sys.maxint) '0x7fffffff' >>> x = sys.maxint >>> n = 1 >>> while x: ... n += 1 ... x >>= 1 ... >>> n 32 WARNING: Assumes nobody will be silly enough to build a machine with ones-complement integers in future :-) From WookieTim at gmail.com Sun Jul 6 09:18:57 2008 From: WookieTim at gmail.com (furby) Date: Sun, 6 Jul 2008 06:18:57 -0700 (PDT) Subject: Hi there! I need what is probably a very basic lesson in events.... Message-ID: <4d5a5286-f4cf-480e-9432-b4b337f7c145@x35g2000hsb.googlegroups.com> I am teaching myself Python... I'm nowhere near even intermediate level yet, so treat me like an idiot. I am using Boa Constructor on Ubuntu 8.04 if that helps. Here is what I have right now : I am plying with reading a URL (An RSS feed to be exact) and displaying it inside a HTMLWindow. I have that part working - It shows the title as a link and displays the description next to it. What I want to do is trap the mouseclick on the link and use that to grab just the text that is on the site. Right now, if I click on it, the HTML window control takes me to the site and doesn't really show the site very well, since it doesn't seem to do CSS. That's okay - I just want to display the text.... How do I trap the mouse clicking on the link? I know that HTMLwindow has a "OnLinkClicked" event - I can see it in the docs for that control. But it seems that Boa Constructor doesn't expose that event in it's frame designer.... How do I code a event that fires off instead of the default event? I don't know if I am being clear enough, so if not just tell me what I should say... Liek I said, I am a newbie right now. From Robert.Bossy at jouy.inra.fr Thu Jul 17 10:39:07 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Thu, 17 Jul 2008 16:39:07 +0200 Subject: % sign in python? In-Reply-To: References: Message-ID: <487F598B.9040208@jouy.inra.fr> korean_dave wrote: > What does this operator do? Specifically in this context > > test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) > > (Tried googling and searching, but the "%" gets interpreted as an > operation and distorts the search results) > It's the string formatting operator: http://docs.python.org/lib/typesseq-strings.html Btw, a good place to start searching would be: http://docs.python.org/lib/lib.html especially: http://docs.python.org/lib/genindex.html Cheers RB From norseman at hughes.net Thu Jul 10 17:44:32 2008 From: norseman at hughes.net (norseman) Date: Thu, 10 Jul 2008 14:44:32 -0700 Subject: Terminate a python script from linux shell / bash script In-Reply-To: References: Message-ID: <487682C0.70905@hughes.net> Gros Bedo wrote: > >>> That's not how it works. If you kill one running python script it will not >>> effect other python scripts. Each script has its own interpreter process >>> running. > >> GB> So, is there a way from the Linux shell or a bash script to terminate >> GB> just one specific Python script ? > >>> So just kill it. > > Yes I've seen that each python script calls its own instance of Python. But how to know which is the good one in bash ? Is there a command that gets the parameters of process, so I could use grep to select the one containing the name of my script ? > _________________________________________________________________ > Votre contact a choisi Hotmail, l'e-mail nouvelle g?n?ration. Cr?ez un compte. > http://www.windowslive.fr/hotmail/default.asp > -- > http://mail.python.org/mailman/listinfo/python-list > ============================== Yes. man ps explains try ps -AFL | grep [known filename or cmdlin token] then kill -9 [PID] found (check it more than twice) 1) If your script is known to hang use what another wrote: py s.py tokens & capture=$! (get the PID ready) kill -9 $capture 2) If you are like the other 99% needing the PID because we didn't know we were going to need it, use the ps/grep combo. Try not to damage your system. Which means: Trying to automate this is VERY dangerous! How long since your last full backup? And of course you can redo everything since last backup from memory, yes? It hangs, you kill it manually. Steve norseman at hughes.net From code at pizzashack.org Sun Jul 27 15:34:16 2008 From: code at pizzashack.org (Derek Martin) Date: Sun, 27 Jul 2008 15:34:16 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <009c29cc$0$20302$c3e8da3@news.astraweb.com> References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c29cc$0$20302$c3e8da3@news.astraweb.com> Message-ID: <20080727193416.GE7373@dragontoe.org> On Sun, Jul 27, 2008 at 08:13:53AM +0000, Steven D'Aprano wrote: > On Sun, 27 Jul 2008 10:23:06 +0800, Marcus.CM wrote: > > > Well after reading some of these posts on "sacred python cow" on the > > "self" , i would generally feel that most programmers who started with > > C++/Java would find it odd. > > You know, there are some programmers who haven't started with C++ or Java. Indeed, I'm one of them. In fact, I've never written even a single program in either language (except maybe hello world or the equivalent), and still, I have always thought that explicitly naming the class instance variable in the parameter list of the object's methods was a wart (albeit a very minor one) in Python. It's a waste of typing. > > And its true, i agree completely there should not be a need to put > > "self" into every single member function. If you were writing an > > application and one of your classes adds the same variable to each > > of its member function you would do away with it too. > > Would I? How would I do that here? You missed the point. The variable "other" in your posted class is not intended to always refer to the same *object*... Whereas "self" is and does, and that was what was meant. In such a case, you'd obviously convert the variable to a class property. Regardless of how it's implementd, it's such a common idiom to use self to refer to object instances within a class in Python that it ought to be more automatic. Personally, I kind of like the idea of using @ and thinking of it more like an operator... Kind of like dereferencing a pointer, only with an implied pointer name. class foo: def __init__(): @.increment = 2 def bar(a) return a + @.increment I'm sure all the Pythonistas will hate this idea though... ;-) To be honest, it smacks a little of Perl's magic variables, which I actually hate with a passion. This is the only place in Python I'd consider doing something like this. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From stef.mientki at gmail.com Mon Jul 7 18:47:01 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 08 Jul 2008 00:47:01 +0200 Subject: sage vs enthought for sci computing In-Reply-To: <677e7819-e09e-43d3-8368-5864f91002be@34g2000hsh.googlegroups.com> References: <677e7819-e09e-43d3-8368-5864f91002be@34g2000hsh.googlegroups.com> Message-ID: <48729CE5.3080704@gmail.com> jadamwilson2 at gmail.com wrote: > Hello, > I have recently become interested in using python for scientific > computing, and came across both sage and enthought. I am curious if > anyone can tell me what the differences are between the two, since > there seems to be a lot of overlap (from what I have seen). If my goal > is to replace matlab (we do signal processing and stats on > physiological data, with a lot of visualization), would sage or > enthought get me going quicker? I realize that this is a pretty vague > question, and I can probably accomplish the same with either, but what > would lead me to choose one over the other? > Scipy or the new x-y distro is almost identical like MatLab ( but you'll miss the var browser), and therefor get started faster. I've the same kind of applications and support medical researchers with collecting and analyzing physio data. About 2 years ago I wasn't satisfied with MatLab anymore, so I looked at LabView, SciLab, Octave and a few others, and decided to stay with Matlab, but embed it in my own shell. Worked with that for about half a year, then I tried Scipy (also embedded) and found it much better than MatLab. At the moment I switched totally to Python, and I'm working on a Labview like environment for Python. hopes that helps, cheers, Stef > Thanks! > -- > http://mail.python.org/mailman/listinfo/python-list > From dullrich at sprynet.com Mon Jul 7 17:23:43 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 07 Jul 2008 16:23:43 -0500 Subject: "in"consistency? Message-ID: Luckily I tried it before saying no, that's not how "in" works: >>> 'ab' in 'abc' True >>> [1,2] in [1,2,3] False Is there a reason for the inconsistency? I would have thought "in" would check for elements of a sequence, regardless of what sort of sequence it was... -- David C. Ullrich From fredrik at pythonware.com Mon Jul 21 06:16:57 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 12:16:57 +0200 Subject: calling source command within python In-Reply-To: References: Message-ID: Jie wrote: > i'm having trouble executing os.system('source .bashrc') command > within python, it always says that source not found and stuff. Any > clue? like in $ python >>> import os >>> os.system("source .bashrc") sh: source not found and stuff 256 ? I get $ python >>> import os >>> os.system("source .bashrc") /... stuff printed by my .bashrc file .../ 0 What happens if you do >>> import os >>> os.system("bash .bashrc") instead? From RonV at Nospam.com Thu Jul 10 20:04:27 2008 From: RonV at Nospam.com (RV) Date: Thu, 10 Jul 2008 20:04:27 -0400 Subject: Can anyone suggest a date peocedure... References: Message-ID: On Thu, 10 Jul 2008 13:39:29 -0700, Gary Herron wrote: >The datetime module has what you need. > >It has methods (with examples) on building a datetime object from a >string, and it has a object named timedelta, and the ability to subtract >a timedelta from a time. > >For instance, the time right now and the time exactly one day ago: > > >>> from datetime import * > >>> datetime.today() >datetime.datetime(2008, 7, 10, 13, 38, 48, 279539) > >>> datetime.today()-timedelta(1) >datetime.datetime(2008, 7, 9, 13, 38, 50, 939580) > > >Gary Herron Thanks Gary! This works great. Now all I need to know is how to plug the date into the datetime object from a string. Ron From deets at nospam.web.de Thu Jul 31 10:33:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 16:33:38 +0200 Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> Message-ID: <6fe0scFaus40U1@mid.uni-berlin.de> squishywaffle at gmail.com wrote: >> Ctypes is a since python2.5 built-in module that allows to declare >> interfaces to C-libraries in pure python. You declare datatypes and >> function prototypes, load a DLL/SO and then happily work with it. No C, >> no compiler, no refcounts, no nothing. >> >> And you can pass python-functions as callbacks. > > The first sentence (and some really crummy licensing restrictions > imposed by the library distributor) alone here excludes this as a > valid option for this particular case, I definitely need Python 2.4 > support. How much more liberal can it get than MIT-licensed? """ to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: """ But then, if you insist, go down the hard road. Diez From max at alcyone.com Wed Jul 30 04:07:10 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Jul 2008 01:07:10 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> Message-ID: Russ P. wrote: > Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > __nonzero__ work in Python. It's very basic stuff. You can quit > patronizing me (and Carl too, I'm sure). You suggested a syntax for testing non-emptiness (`x is not empty`) which indicated a profound misunderstanding of what the `is` operator does. You then acknowledged that there might be a problem because of the implication if the `is` operator and weren't sure whether it would work or not: | But I guess that could only work if there were only one empty list | that represents all empty lists (as there is only one actual "None"). | I don't know if that makes sense or not. This ends with you still sounding confused about what the operator does, because that can't make sense if you take into account the meaning of the `is` operator (surely not all empty lists are the same object) and polymorphism (not all empty containers are empty lists). Hey, everybody goofs. But pointing figures here doesn't help, since it's not unreasonable to assume that someone who says something clearly misunderstanding a feature of the language, and followups to responses _continuing to be confused about it_, is, in fact, confused. The only reason anyone thought you were confused was by your bizarre suggestion about the `empty` syntax and then your confused responses afterwards. Maybe chalk it up to experience and move on? > The point that you seem to be missing, or refuse to acknowledge for > some reason, is that "if x" can be mistakenly applied to any object > when the programmer thinks that x is a list -- and the programmer will > receive no feedback on the error. > > I have made errors like that, and I could have saved some time had I > used an "empty" method that only applies to a list or other sequence. Well, that's what you get when you use a dynamic language. There are times when `x + y` doesn't mean numeric addition, or in fact anything like it. Or `x % y` where it _really_ doesn't mean anything like the modulus operator. In dynamic languages, the effect of operations depend on their types. There's really no way around that, and Boolean testing if an object as in `if x: ...` is no different. It means different things depending on what `x` is. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The actor is not quite a human being -- but then, who is? -- George Sanders From asmodai at in-nomine.org Thu Jul 10 03:43:22 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 10 Jul 2008 09:43:22 +0200 Subject: Fwd: [ANN] Genshi 0.5.1 released Message-ID: <20080710074322.GO68329@nexus.in-nomine.org> We have put up eggs for various operating systems as well. ----- Forwarded message from Christopher Lenz ----- From: Christopher Lenz To: genshi at googlegroups.com Subject: [ANN] Genshi 0.5.1 released Date: Wed, 9 Jul 2008 21:44:11 +0200 X-Mailer: Apple Mail (2.926) Genshi 0.5.1 - Jul 9, 2008 ========================== We're proud to present the latest release of the Genshi: 0.5.1. Genshi is a Python library that provides an integrated set of components for parsing, generating, and processing HTML, XML or other textual content for output generation on the web. The major feature is a template language. This release contains a number of important bug fixes over the 0.5 release. You can download the new release here: Please don't hesitate to report any issues you may find with this release: For questions, comments and user discussions, please use the Genshi mailing list: What's New: ----------- * Fix problem with nested match templates not being applied when buffering on the outer `py:match` is disabled. Thanks to Erik Bray for reporting the problem and providing a test case! * Fix problem in `Translator` filter that would cause the translation of text nodes to fail if the translation function returned an object that was not directly a string, but rather something like an instance of the `LazyProxy` class in Babel (ticket #145). * Fix problem with match templates incorrectly being applied multiple times. * Includes from templates loaded via an absolute path now include the correct file in nested directories as long if no search path has been configured (ticket #240). * Unbuffered match templates could result in parts of the matched content being included in the output if the match template didn't actually consume it via one or more calls to the `select()` function (ticket #243). Acknowledgments ---------------- A big thank you to everyone who tried Genshi and provided feedback, reported bugs, and/or contributed patches! Cheers, -- Christopher Lenz cmlenz at gmx.de http://www.cmlenz.net/ ----- End forwarded message ----- -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Time is a twofold teacher, harsh and yet patient like no-one... From Jie.Bao at gmail.com Mon Jul 21 06:03:58 2008 From: Jie.Bao at gmail.com (Jie) Date: Mon, 21 Jul 2008 03:03:58 -0700 (PDT) Subject: calling source command within python Message-ID: Hi all, i'm having trouble executing os.system('source .bashrc') command within python, it always says that source not found and stuff. Any clue? Thanks, Jie From phillip.oldham at gmail.com Wed Jul 30 11:15:07 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Wed, 30 Jul 2008 08:15:07 -0700 (PDT) Subject: Standard module for parsing emails? References: <6fb93eFap7j5U1@mid.individual.net> Message-ID: If there isn't a standard library for parsing emails, is there one for connecting to a pop/imap resource and reading the mailbox? From kyosohma at gmail.com Thu Jul 3 12:27:38 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 3 Jul 2008 09:27:38 -0700 (PDT) Subject: distutils - setup - lib problem References: <6138c75a-601e-4c44-b765-364cadb16098@l64g2000hse.googlegroups.com> Message-ID: <33f8ff1e-6643-4880-9a25-ec3617c4d750@25g2000hsx.googlegroups.com> On Jul 2, 3:38?am, rocksportrocker wrote: > Hi, > > I've got some problems with the following setup.py file. > using "python setup.py install -f" it shows that wrap_ica.so is copied > to /usr and not to ..../site-packages as I assumed. > What am I doing wrong ? I'm using Python 2.4 on Debian Linux. > > ----------------------------------------------------- > > from distutils.core import setup > import glob > > setup(name='py_ica', > ? ? ? py_modules=['py_ica'], > ? ? ? data_files=[(".", ["wrap_ica.so"]), > ? ? ? ? ? ? ? ? ?] > ? ? ? ) > ----------------------------------------------------- > > Greetings, Uwe Try the distutils group. They'd probably be a little more helpful: http://mail.python.org/mailman/listinfo/distutils-sig Mike From bignose+hates-spam at benfinney.id.au Fri Jul 11 04:49:23 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 11 Jul 2008 18:49:23 +1000 Subject: Trying to learn References: Message-ID: <8763rcrejw.fsf@benfinney.id.au> luster123 writes: > Can someone please teach me the basics of Python and Pygame? Yes, you can do it. -- \ ?Too many pieces of music finish too long after the end.? ?Igor | `\ Stravinskey | _o__) | Ben Finney From jonas.esp at googlemail.com Mon Jul 14 08:04:54 2008 From: jonas.esp at googlemail.com (Kless) Date: Mon, 14 Jul 2008 05:04:54 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> <792048c1-5e18-4a2c-925d-a1c932d18a91@j22g2000hsf.googlegroups.com> <8923d0c5-29ce-495f-924a-6d9d2457138e@e39g2000hsf.googlegroups.com> <8933b108-45b4-438d-87d8-aad92a15188b@e53g2000hsa.googlegroups.com> Message-ID: Akathorn Greyhat sent me by email the next solution, which althought isn't generic it works well: ------------- You could make your own class for that, maybe something like ######### class MyCoolDictionary(dict): def __init__(self, *args, **kargs): dict.__init__(self, *args, **kargs) def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: keys=[] for i in dictio.keys(): if dictio[i]==item: keys.append(i) return keys dictio=MyCoolDictionary({"a" : 1, "b" : 2, "c" : 2}) print dictio["a"] print dictio["b"] print dictio[1] print dictio[2] ######### The output of this code is: 1 2 ['a'] ['c', 'b'] Note that it isn't finish, maybe you'll need to make some kind of test before adding a new value because with this code one value can have multiple keys, and I have fixed it by returning a list of keys instead a single value. It's up to you =) I'm sorry of my poor english =( Regards, Akathorn Greyhat ------------- From subhabrata.iisc at hotmail.com Fri Jul 18 06:00:41 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Fri, 18 Jul 2008 03:00:41 -0700 (PDT) Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> <6eb733F67cpfU2@mid.uni-berlin.de> Message-ID: <32a81d0c-a74f-4b22-8add-15beb2643529@h17g2000prg.googlegroups.com> Sorry if I didn't say that. The input is a string "Petrol Helium Heaven Sky" Now, in a3 it is "God Goddess Heaven Sky" is there, it is matching Heaven and Sky but not Petrol and Helium as they are not in a3. Now, as per the code it is giving me an output "S" of "Sky" and "Helium" But I was looking for an output of "H S Petrol Helium" and not "S Helium" meaning all the values of a5 and a6 will be concatenated in s. Best Regards, Subhabrata.. Marc 'BlackJack' Rintsch wrote: > On Fri, 18 Jul 2008 01:31:59 -0700, SUBHABRATA wrote: > > > def try2(n): > > a1=raw_input("PRINT A STRING:") > > a2=a1.split() > > a3="God Godess Heaven Sky" > > for x in a2: > > a4=a3.find(x) > > if a4>-1: > > a5=a3[a4] > > print a5 > > elif a4<0: > > a6=x > > print "It is not found" > > print a6 > > else: > > print "Error" > > s=a5+" "+a6 > > print s > > > > Here, if I put a string like: > > Petrol Helium Heaven Sky > > In s it is giving me S Helium > > But I am looking for an output of a5 and a6 concatenating all its > > values not the last ones. Can you suggest me any help? Am I missing > > any minor point? > > Maybe you should describe what the input looks like and what output you > want to have and how the input and output are connected. In words, not in > not very clear code with "numbered names". That's a silly idea and makes > understanding the code very hard. Please use meaningful names! > > Ciao, > Marc 'BlackJack' Rintsch From mail at timgolden.me.uk Tue Jul 15 12:35:40 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Jul 2008 17:35:40 +0100 Subject: Zipping files In-Reply-To: <9400be29-9c00-4868-91a9-ae82ebfc6364@56g2000hsm.googlegroups.com> References: <9400be29-9c00-4868-91a9-ae82ebfc6364@56g2000hsm.googlegroups.com> Message-ID: <487CD1DC.3050907@timgolden.me.uk> dp_pearce wrote: > When I saw "Permission denied", this was my suspicion. And I think you > are very right. I have just gone back and tried writing to a file > outside of C:, in this case C:/output/, and it seems to work again. > > Would I be right in guessing there is no way around this? Well, you could (presumably) alter your own user's groups / rights and/or the permissions on the root of the C: drive so that you *can* zip to that location. On the other hand, chucking random stuff into the root of the system drive has never been considered a brilliant idea. (Altho' I know a lot of people who do it :) ). Why not create a suitable folder lower down, or in your own %APPDATA% area, or using the tempfile module, depending on your needs? TJG From ethan at stoneleaf.us Tue Jul 15 12:56:59 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 15 Jul 2008 08:56:59 -0800 Subject: Measure class, precision, significant digits, and divmod() Message-ID: <487CD6DB.60500@stoneleaf.us> Hey all. My thanks to all who have responded so far with my other questions. It is much appreciated. Some background on what I'm doing (a good explanation can be found at http://www.hazelwood.k12.mo.us/~grichert/sciweb/phys8.htm): When measuring, there is some uncertainty as to the *exact* value; so, when doing calculations with these measured numbers, one should not present an answer that seems more accurate than the source. For addition and subtraction this means the final answer cannot be more precise than the least precise input: 5.0 + 21.23 = 26.2 (first number only measured to the tenths, so answer only good to the tenths); for multiplication and division this means the answer cannot have more significant digits than the input with the fewest significant digits: 231 * 0.25 = 58 (0.25 only has two significant digits, so answer only has two significant digits). Important point -- counting is not subject to precision error. As I have mentioned before, I am making this Measure class for two reasons: experience with unit testing, I like playing with numbers, I am unaware of anything like this having yet been done (okay, three reasons ;). So far, I have the init, add, sub, mul, div, cmp, neg, pos, and abs done, and I'm ready to tackle floordiv, mod, and divmod... okay, maybe 'ready' is too strong a word -- one of the obstacle's I'm facing is that I, myself, don't have any real use for this class, so I'm stuck on deciding how floordiv, mod, and divmod should function. As mentioned above, counting is precise... so should divmod (a // b, a % b), which returns the count of times b goes into a, and the remainder, be an exact number, or should it behave like floor(a / b), and preserve the inherent inaccury present in the measured value a? Should I have floordiv preserve inaccuracy, and divmod be exact? Any and all feedback welcome, particularly from anyone who might actually use the Measure class. ;) ~Ethan From tjreedy at udel.edu Wed Jul 23 18:31:11 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Jul 2008 18:31:11 -0400 Subject: Segv in mmap.move() In-Reply-To: References: Message-ID: magnus.lycka at gmail.com wrote: > Does anyone recognize this little Python crasher? > > I'll file a bug report unless someone notices it as an already > documented bug. I found some open mmap bugs, but it wasn't > obvious to me that this problem was one of those... > > Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import mmap >>>> data = mmap.mmap(-1, 1) >>>> data.move(1,1,-1) > Segmenteringsfel (core dumped) > > I first noticed the problem under Windows in 2.5.1. On WinXP Py3.0b2, I see two bugs here. 1. For a length 1 sequence, the only offsets allowed should be 0. However, I can index to what I suspect is a null terminator byte at offset len(seq). This should be internally accessible only just as for regular strings and bytes (which also have null terminators, I believe). Indexing any farther past what should be the end gives the IndexError I expected when indexing just past the end. (Slicing and iterating, however, work correctly.) >>> import mmap >>> d=mmap.mmap(-1,5) >>> d[:]=b'abcde' >>> d[0], d[4],d[5] (97, 101, 0) 2. Running your code, or d.move(1,2,-1), I get python.exe 'encountered a problem ...shutting down ... Send report?' (yes) and window closed. Running IDLE, same msg, but after send report, IDLE shell restarted. Cute. Modules/mmapmodule.c - mmap_move_method declares count as unsigned. Further experimentation shows that the problem is telling it to move exactly -1 bytes, which I am sure gets translated to 2**32-1 = 4294967295 by PyArg_ParseTuple(args, "kkk:move", &dest, &src, &count) Passing 2**32-1 also crashes, while 2*32-2 and other bad values give >>> d.move(1,2,2**32-2) Traceback (most recent call last): File "", line 1, in d.move(1,2,2**32-2) ValueError: source or destination out of range I suspect the 2**32-1 bug is in C memmove, perhap inherited from a common source. I think either a)the docs should warn that a count of -1== 4294967295 (on 32bit machines) and just that may crash the interpreter or b) the wrapper of the underlying C function should raise ValueError for -1 also. The goal of 'no crashes' suggests the latter if sensibly possible. Terry Jan Reedy From semanticist at gmail.com Wed Jul 30 17:55:10 2008 From: semanticist at gmail.com (Miles) Date: Wed, 30 Jul 2008 17:55:10 -0400 Subject: how to split text into lines? In-Reply-To: References: Message-ID: On Wed, Jul 30, 2008 at 4:45 PM, kj wrote: >>What's the Python idiom for splitting text into lines, preserving >>the end-of-line sequence in each line? > > > Sorry, I should have googled this first. I just found splitlines()... > > Still, for my own edification, is there a way to achieve the same > effect using re.split? Not directly: re.split doesn't split on zero-length matches. http://mail.python.org/pipermail/python-dev/2004-August/047272.html http://bugs.python.org/issue852532 http://bugs.python.org/issue988761 http://bugs.python.org/issue3262 -Miles From grante at visi.com Mon Jul 21 11:04:40 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 21 Jul 2008 10:04:40 -0500 Subject: ntlm authentication References: <7B3D44209E8C944288889D4132FEC4125B98D8@IMCSRV6.MITRE.ORG> Message-ID: On 2008-07-21, Tim Golden wrote: > Neuberger, Sheldon N. wrote: >> Is there any way to make urllib2 handle NTLM authentication? > > Frankly, I'd hate to try. Have a look at this: > > http://sourceforge.net/projects/ntlmaps/ Here's a library that can be used to handle the NTLM authentication stuff: http://josefsson.org/libntlm/ There's no reason you couldn't translate it into Python (or just call it). -- Grant Edwards grante Yow! I wonder if I could at ever get started in the visi.com credit world? From weizhonghua.ati at gmail.com Wed Jul 16 04:29:19 2008 From: weizhonghua.ati at gmail.com (zhw) Date: Wed, 16 Jul 2008 01:29:19 -0700 (PDT) Subject: How can i use a variable without define it ? Message-ID: How can i use a variable without define it ? I have thought about the __import__ function, but the docs says "the __import__() function does not set the local variable named eggs"? From Henning.Thornblad at gmail.com Fri Jul 4 07:43:48 2008 From: Henning.Thornblad at gmail.com (Henning_Thornblad) Date: Fri, 4 Jul 2008 04:43:48 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions Message-ID: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> What can be the cause of the large difference between re.search and grep? This script takes about 5 min to run on my computer: #!/usr/bin/env python import re row="" for a in range(156000): row+="a" print re.search('[^ "=]*/',row) While doing a simple grep: grep '[^ "=]*/' input (input contains 156.000 a in one row) doesn't even take a second. Is this a bug in python? Thanks... Henning Thornblad From malaclypse2 at gmail.com Mon Jul 7 09:54:49 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 7 Jul 2008 09:54:49 -0400 Subject: Confused yet again: Very Newbie Question In-Reply-To: References: Message-ID: <16651e80807070654j12d55802yf3950e2375bbe67d@mail.gmail.com> On Mon, Jul 7, 2008 at 7:30 AM, mcl wrote: > I did not think you had to make the distinction between 'byvar' and > 'byref' as in Basic. Python does not use "call by value" or "call by reference" semantics. Instead, python's model is "call by object". See this writeup for some details: http://effbot.org/zone/call-by-object.htm -- Jerry From motoom at xs4all.nl Wed Jul 23 05:40:10 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Wed, 23 Jul 2008 11:40:10 +0200 Subject: maximum value in a column of file Message-ID: <2.2.32.20080723094010.01275db0@pop.xs4all.nl> Maurizio wrote... > the problem is that i don't know how to put the column of the file in an > array. (i'm new in phyton). Give us an example of how your file looks, and what you want to extract from it, so that we don't have to guess. Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From __peter__ at web.de Fri Jul 18 06:26:44 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 12:26:44 +0200 Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: nicolas.pourcelot at gmail.com wrote: > I think something like >>>> id(myobject) in (id(element) for element in mylist) > would also work, also it's not so readable, and maybe not so fast > (?)... > > An "is in" operator would be nice... And rarely used. Probably even less than the (also missing) < in, | in, you-name-it operators... > So, precisely, you mean that if hash(a) != hash(b), a and b are > considered distinct, and else [ie. if hash(a) == hash(b)], a and b are > the same if and only if a == b ? Correct for set, dict. For lists etc. the hash doesn't matter: >>> class A(object): ... def __hash__(self): ... return nexthash() ... def __eq__(self, other): ... return True ... >>> from itertools import count >>> nexthash = count().next >>> A() in [A() for _ in range(3)] True >>> d = dict.fromkeys([A() for a in range(3)]) >>> d.keys()[0] in d False Peter From snowballz.game at gmail.com Fri Jul 18 22:39:38 2008 From: snowballz.game at gmail.com (Michael Lubker) Date: Fri, 18 Jul 2008 19:39:38 -0700 (PDT) Subject: Any Game Developers here? References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> <4A235BC6-5E46-4402-AF2D-BA3DBC175517@gmail.com> Message-ID: <2a277fdc-e878-4f68-a758-03e22a72cd18@d1g2000hsg.googlegroups.com> I also know about Panda. ~Michael On Jul 18, 6:05?pm, "Michael Lubker" wrote: > I'm interested in general... I know about PyGame and Pyglet, and have > used both. We're currently using Python-Ogre. In the end, I am looking > to find people interested in my project ( seehttp://youtube.com/watch?v=E0QQ9JuclxE), but I also want to find > people experienced with Python in general, not just one library. > (though of course I know that's not too likely) > > Aren't you one of the Escort Wing developers? :) > > Thanks > Michael > > > > On Fri, Jul 18, 2008 at 5:13 PM, Stephen Johnson wrote: > > I use the Pyglet library to make games. You want to look at the pyglet and > > pygame mailing lists, not this one. Use Google. > > In my opinion, PyGame is clunky and Pyglet is elegant, simple, and > > comprehensive. PyGame has more examples available, but Pyglet has great > > documentation and enough examples to answer any questions you might have. > > Both have active communities. > > > -Steve Johnson > > On Jul 18, 2008, at 5:38 PM, Michael Lubker wrote: > > > Any people that use Python as the predominant language for their game > > development here? > > > ~Michael > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > ~ "The world hates change, yet it is the only thing that has brought > progress." ~ Charles Kettering > > http://snowballz.joey101.net From ldo at geek-central.gen.new_zealand Sat Jul 26 19:44:44 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 27 Jul 2008 11:44:44 +1200 Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> <24a548ad-4cb3-410c-89df-21da6ef4220f@j7g2000prm.googlegroups.com> Message-ID: In message <24a548ad-4cb3-410c-89df-21da6ef4220f at j7g2000prm.googlegroups.com>, Matimus wrote: > On Jul 24, 9:32?pm, Lawrence D'Oliveiro central.gen.new_zealand> wrote: > >> In message >> , >> Matimus wrote: >> >> > On Jul 24, 2:54?am, Lawrence D'Oliveiro > > central.gen.new_zealand> wrote: >> >> In message >> >> , >> >> >> Matimus wrote: >> >> > That isn't the standard. With that setup tabs will show up as 4 >> >> > spaces, and still confuse you. >> >> >> Why should that be confusing? The most common tab-stop setting is 4 >> >> columns. >> >> > A tab character is specified as 8 spaces. >> >> Specified by whom? The most common setting these days is 4 columns. > > All argument about specification aside, Python interprets a tab > character as equivalent to 8 spaces. If you are treating tabs as > equivalent to 4 spaces in your python code it will cause > IndentationError exceptions to be raised. I have Emacs configured to show tabs as 4 columns wide, and I've never had such an exception happen in my Python code as a result. From semanticist at gmail.com Sun Jul 13 21:49:11 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 21:49:11 -0400 Subject: socket.connect() hangs in SYN_SENT state. In-Reply-To: References: <804bccb2-42c7-42e9-8f50-7a780d3438fd@j22g2000hsf.googlegroups.com> Message-ID: On Sun, Jul 13, 2008 at 9:31 PM, Miles wrote: > On Sun, Jul 13, 2008 at 8:35 PM, bukzor wrote: >> The problem only manifests about 1 in 20 runs. Below there's code for >> a client that shows the problem 100% of the time. >> >> The two URL's that I seem to be "confused" about point to the same IP. >> Maybe this will make it clear: >> >> PING bukzor.hopto.org (75.61.84.249) 56(84) bytes of data. >> 64 bytes from adsl-75-61-84-249.dsl.pltn13.sbcglobal.net >> (75.61.84.249): icmp_seq=1 ttl=255 time=1.68 ms > > For me, buzkor.hopto.org resolves to 69.65.19.125 Ahhh... "bukzor". Well, that makes sense. Pardon my temporary dyslexia. -Miles From elessar at nienna.org Thu Jul 3 19:11:34 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Thu, 03 Jul 2008 17:11:34 -0600 Subject: Singleton implementation problems In-Reply-To: References: Message-ID: <486D5CA6.6020204@nienna.org> Urizev wrote: > Hi everyone > > I have developed the singleton implementation. However I have found a > strange behaviour when using from different files. The code is > attached. > > Executing main > new MySet object > No singleton instance > New singleton: > <__main__.Singleton instance at 0x2b98be474a70> > new MySet object > There is a singlenton instance > new Member > new MySet object > No singleton instance > New singleton: > > new Member > new MySet object > There is a singlenton instance > new Member > new MySet object > There is a singlenton instance > > I do not know why, but it creates two instances of the singleton. Does > anybody know why? > > Regards > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list I've run into a similar problem. Basically, when you refer to a class from __main__ (i.e., the .py file you're actually running) versus from an imported module, Python doesn't realize they're the same class. Your Singleton implementation is creating one instance for __main__ and one for everything else. I'm sure there's someone around here who can say why Python behaves this way. You should be fine if you can restructure your code so you don't use your Singleton from __main__. In my case, I added a new main.py file. -Matt From mrkafk at gmail.com Tue Jul 1 12:06:47 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Tue, 01 Jul 2008 18:06:47 +0200 Subject: Embedding Python In-Reply-To: <207312b70807010525m3a8e3acdj352a0b3c7d1a4f7d@mail.gmail.com> References: <207312b70807010525m3a8e3acdj352a0b3c7d1a4f7d@mail.gmail.com> Message-ID: Pau Freixes wrote: > If you search this function name into Google you will can found some > examples, use for example PyMarshal_ReadObjectFromString or > PyMarshal_ReadObjectFromFile Rest assured I looked at a lot of code, but none of it was reading in the .pyc file. I had no idea about the 8-byte header in the .pyc file, Carsten was so kind to show it. From http Thu Jul 17 11:19:01 2008 From: http (Paul Rubin) Date: 17 Jul 2008 08:19:01 -0700 Subject: Javascript - Python RSA encryption interoperability References: Message-ID: <7xhcaosfmi.fsf@ruckus.brouhaha.com> Evren Esat Ozkan writes: > I'm trying to encrypt a string with RSA. But it needs to be compitable > with Dave's JavaScript RSA implementation*. What exactly are you trying to do? That Javascript implementation looks like bad news. If you're trying to secure a web page, use SSL, don't mess around with trying to encrypt it with Javascript. From craig.pastro at gmail.com Fri Jul 11 13:08:26 2008 From: craig.pastro at gmail.com (craig75) Date: Fri, 11 Jul 2008 10:08:26 -0700 (PDT) Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> <3ebed664-a6ba-4e30-acc5-f7d5edb25e32@56g2000hsm.googlegroups.com> Message-ID: On Jul 11, 3:36?am, bearophileH... at lycos.com wrote: > James Fassett: > > > # the first Pythonic attempt using comprehensions > > result_list = [x[0] for x in tuple_list] > > > # the final functional way > > [result_list, _] = zip(*tuple_list) > > > I really like how Python allows me to do what I feel is the most > > natural solution (for a seasoned procedural programmer) while allowing > > a satisfying path towards a more functional approach. > > The list comprehension is quite more readable to me, so I suggest you > to use it. It's probably the default way to do it in Python. > > If you want functional code this is another way (I have not tested the > relative performance but it may be quick): > > >>> tuple_list = ( > > ... ? ? ('John', 'Doe'), > ... ? ? ('Mark', 'Mason'), > ... ? ? ('Jeff', 'Stevens'), > ... ? ? ('Bat', 'Man') > ... ? )>>> from operator import itemgetter > >>> map(itemgetter(0), tuple_list) > > ['John', 'Mark', 'Jeff', 'Bat'] > > Bye, > bearophile Functional programmers love pattern matching (which I think makes the code much easier to understand): [x for (x,y) in tuple_list] or map(lambda (x,y):x, tuple_list) From pavlovevidence at gmail.com Sat Jul 26 02:14:15 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 25 Jul 2008 23:14:15 -0700 (PDT) Subject: 2d graphics - what module to use? References: <5519ca3a-bef6-4673-981a-fb327425cfee@w39g2000prb.googlegroups.com> Message-ID: <8d4c2ba8-77e9-45ef-9c60-960e41b68c8b@34g2000hsh.googlegroups.com> On Jul 25, 4:10?am, King wrote: > Use python's default GUI tkinter's drawing functions or you can use > wxPython GUI kit or you can use pyopengl. > If you are only interested to draw sin waves or math functions that > you should give try to matlab atwww.mathworks.com If you're only interested in sine waves you most certainly should not give Matlab a try; even with student pricing it's going to be way expensive for something that simple. For just popping up a window and drawing on it I recommend PyGame. Carl Banks From cwitts at gmail.com Wed Jul 9 09:32:37 2008 From: cwitts at gmail.com (Chris) Date: Wed, 9 Jul 2008 06:32:37 -0700 (PDT) Subject: Returning the positions of a list that are non-zero References: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> Message-ID: On Jul 9, 7:48?am, "Rajanikanth Jammalamadaka" wrote: > Try this: > > >>> li=[0,0,1,2,1,0,0] > >>> li > > [0, 0, 1, 2, 1, 0, 0]>>> [i for i in range(len(li)) if li[i] != 0] > > [2, 3, 4] > > Cheers, > > Raj > > > > On Tue, Jul 8, 2008 at 10:26 PM, Benjamin Goudey wrote: > > I have a very large list of integers representing data needed for a > > histogram that I'm going to plot using pylab. However, most of these > > values (85%-95%) are zero and I would like to remove them to reduce > > the amount of memory I'm using and save time when it comes to plotting > > the data. To do this, I'm trying to find the best way to remove all of > > the zero values and produce a list of indices of where the non-zero > > values used to be. > > > For example, if my original list is [0,0,1,2,1,0,0] I would like to > > produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices > > of where the non-zero values used to be). Removing non-zero values is > > very easy but determining the indicies is where I'm having difficulty. > > > Thanks in advance for any help > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > "For him who has conquered the mind, the mind is the best of friends; > but for one who has failed to do so, his very mind will be the > greatest enemy." > > Rajanikanth Whoops, misread the question li =[0,0,1,2,1,0,0] [(index,data) for index,data in enumerate(li) if data] From circularfunc at gmail.com Thu Jul 3 16:39:07 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 3 Jul 2008 13:39:07 -0700 (PDT) Subject: PIL(Py Image lib), show() not showing picture... References: <84a8f15a-594f-4e02-aa89-b70932eae420@59g2000hsb.googlegroups.com> <486d366d$0$879$ba4acef3@news.orange.fr> Message-ID: On Jul 3, 10:20?pm, "M?ta-MCI \(MVP\)" wrote: > Hi! > > Which OS? ? On Vista, you MUST reconfig the "aper?u images et > t?l?copies" (in french ; sorry, I don't know the english translation). > > @-salutations > > Michel Claveau VISTA. i will try google translate :) From larry.bates at websafe.com` Mon Jul 21 17:33:50 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 16:33:50 -0500 Subject: Trying to solve a python/mechanize "error 500" http error In-Reply-To: References: Message-ID: <46-dnVVwBPBbnRjVnZ2dnUVZ_ojinZ2d@comcast.com> bruce wrote: > i'm getting the following error: > mechanize._response.httperror_seek_wrapper: HTTP Error 500: > > i'm running python 5.1 > and mechanize 0.1.7b > > I have no idea as to what I have to change/modify/include to handle this > issue. The link that I'm testing is at the bottom of the page. When I insert > the link into the browser, I actually get an err page.. so, I suspect that > there is a handler that I should be able to modify/use to handle this > situation... > > Thoughts/Comments will be greatly appreciated... > > Thanks > > > the output is: > > www = www.1800ink.com > url2= http://www.quantcast.com/www.1800ink.com/traffic > Traceback (most recent call last): > File "./reseller_scrape_child.py", line 288, in > q1 = shopfuncs.quant(rhref) > File "/adkiller/shopfuncs.py", line 56, in quant > br.open(url2) > File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 203, in > open > File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 254, in > _mech_open > mechanize._response.httperror_seek_wrapper: HTTP Error 500: > [root at toshiba adkiller]# ./reseller_scrape_child.py > > > > my code segment looks like: > ==================================== > from mechanize import Browser > import mechanize > br = Browser() > user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' > values1 = {'name' : 'Michael Foord', > 'location' : 'Northampton', > 'language' : 'Python' } > headers = { 'User-Agent' : user_agent } > > #br.set_cookiejar(cj) > br.set_handle_redirect(True) > br.set_handle_referer(True) > br.set_handle_robots(False) > br.addheaders = [('User-Agent', 'Firefox')] > > url2 ="http://www.quantcast.com/xxxx/traffic" > #gets the page (url) from the quantcast app > url2=url2.replace("xxxx",url) > print "url2=",url2 > br.open(url2) > > ======================================= > > this works ok for most of the sites.. but something weird is happening with > the actual page: > http://www.quantcast.com/www.1800ink.com/traffic > > > thanks... > > > Looking up 500 error (here http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) gives me: 10.5.1 500 Internal Server Error The server encountered an unexpected condition which prevented it from fulfilling the request. On some servers (Amazon), when you get 500 errors you are instructed to try the request again. I don't know about this server. -Larry From thomas.bugzilla at gmx.net Wed Jul 9 10:25:23 2008 From: thomas.bugzilla at gmx.net (Thomas) Date: Wed, 09 Jul 2008 16:25:23 +0200 Subject: Relative Package Import In-Reply-To: References: Message-ID: Robert Hancock wrote: > mypackage/ > __init__.py > push/ > __init__.py > dest.py > feed/ > __init__py > subject.py > > In subject.py I have > from ..push import dest There is no such thing as relative package imports. See http://www.python.org/doc/essays/packages.html Thomas > > But i receive the error: > Caught exception importing module subject: > File "/usr/local/python/lib/python2.5/site-packages/pychecker/ > checker.py", line 621, in setupMainCode() > module = imp.load_module(self.moduleName, file, filename, smt) > File "subject.py", line 1, in () > from ..feed import dest > ValueError: Attempted relative import in non-package > > What am I missing? > > > From tjreedy at udel.edu Thu Jul 10 14:09:16 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jul 2008 14:09:16 -0400 Subject: Weird lambda rebinding/reassignment without me doing it In-Reply-To: References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: David C. Ullrich wrote: > In article > <02ff4326-7b07-4ae6-8607-f58ea61802ef at z72g2000hsb.googlegroups.com>, > ssecorp wrote: > >> I am never redefining the or reassigning the list when using validate >> but since it spits the modified list back out that somehow means that >> the modified list is part of the environment and not the old one. >> i thought what happend inside a function stays inside a function >> meaning what comes out is independent of what comes in. >> Meaning if I want the list I send as a parameter to the function I >> have to do x = func(x) and not just func(x) and x is magically what >> comes out of func(). > > A function cannot modify the value of a global variable Yes it can. >>> a=[] >>> def f(): a.append('yes I can') >>> f() >>> a ['yes I can'] > (unless it specifies "global"). It doesn't reassign anything. The statement 'global a' would allow f to *rebind* the global *name* 'a'. The word 'variable' should almost not be used in discussing Python since it is often unclear whether it refers to a name (or collection slot) or an object bound thereto. > But in the functions below you're not reassigning a variable, > you're _modifiying_ an object. A function _can_ modify an > object you pass to it: It can modify any mutable object it can access. >> Doesnt Python have closure or that isnt what this is about? Python does have closures. This is not about that. >> def validate(placed): >> student = round(random.random()*401) >> if student in placed: >> return validate(placed) >> else: >> placed.append(student) >> return student, placed Delete this. It is redundant with the below. >> def val(placed): >> student = round(random.random()*401) >> if student in placed: >> return validate(placed) >> else: >> placed.append(student) >> return student I believe this is equivalent to def addval(placed): while True: student = round(random.random()*401) if student not in placed: break placed.append(student) return student While this avoids the indefinite recursion depth problem, it does not avoid the indefinite time problem. Use random.shuffle, or write your own version if doing this for practice. Also consider removing the return statement unless you actually directly use the added value. It is easier to remember that addval mutates 'placed' without the return. >>>>> g = lambda x:validate(x) This is doubly diseased. First, never write a 'name = lambda...' statement since it is equivalent to a def statement except that the resulting function object lacks a proper .funcname attribute. The above only trivially abbreviates def g(x): return validate(x) by 3 characters. Another reason is that the lambda form somehow more often tricks people into the next mistake . Second, never write a function (with either def or lambda) that simply returns a function of the argument(s). The wrapping does nothing! This is a waste of time and space for both you and the interpreter. The above is functionally equivalent to g = validate and if you want that, you could name the function 'g' when you define it. >>>>> l=[] In some fonts, 'l' and '1' are nearly identical; please use something else for public code, which you made this to be by posting it;-) >>>>> for x in range(1,10): >> g(l) As said, the 'g' wrapper is useless. addval(l) Hope this helps. Terry Jan Reedy From code at pizzashack.org Fri Jul 18 19:14:43 2008 From: code at pizzashack.org (Derek Martin) Date: Fri, 18 Jul 2008 19:14:43 -0400 Subject: Change PC to Win or Windows In-Reply-To: References: Message-ID: <20080718231443.GB3043@dragontoe.org> On Fri, Jul 18, 2008 at 03:46:13PM -0700, Joel Teichroeb wrote: > Calling Windows PC seems to be something that Apple did so they would > not have to directly mention Windows. Actually it's something IBM did when they created the IBM PC. Of course, all IBM PCs ran MS-DOS, since that's how IBM sold them... Then others started to build copies the IBM PC based on Intel hardware, and the resulting class of computers was called, collectively, "PC Clones" -- shortened to PCs -- by the industry and its market. Then companies like AMD and Cyrix started building Intel-compatible CPUs, and the term PC was extended to include systems built using those architectures. Eventually Windows was released, and PCs became Windows boxen running on Intel-compatible hardware, and I personally know no one who doesn't use the term that way... Much like the English word "bank" (and numerous others), the term "PC" has come to have several meanings, one of which is the above. You may not like it, but we're pretty much stuck with the term, so you may as well get used to it. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From animator333 at gmail.com Fri Jul 25 01:33:01 2008 From: animator333 at gmail.com (King) Date: Thu, 24 Jul 2008 22:33:01 -0700 (PDT) Subject: object persistency, store instances relationship externally Message-ID: <3183af12-4b1e-4bd1-8d21-b9fc2b421008@v1g2000pra.googlegroups.com> This is a new test for object persistency. I am trying to store the relationship between instances externally. It's not working as expected. May be I am doing it in wrong way. Any suggestions? import shelve class attrib(object): pass class node(object): def __init__(self): self.a = attrib() self.b = attrib() self.c = attrib() self.d = attrib() a = node() #store pair relationship. This relationship is created at run time. lst = [[a.a, a.b], [a.c, a.d]] #Write objects into file shelf = shelve.open('shelve_test_01.txt', writeback=True) shelf['node'] = a shelf['lst'] = lst shelf.sync() shelf.close() #Read objects from file shelf = shelve.open('shelve_test_01.txt', 'r') a = shelf['node'] lst = shelf['lst'] print a.a, a.b, a.c, a.d #lst does not contains the relationship of object 'a''s attributes, instead it's creating new instances #of 'attrib' class print lst From jordanrastrick at gmail.com Thu Jul 24 01:41:54 2008 From: jordanrastrick at gmail.com (Jordan) Date: Wed, 23 Jul 2008 22:41:54 -0700 (PDT) Subject: Attack a sacred Python Cow Message-ID: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Hi everyone, I'm a big Python fan who used to be involved semi regularly in comp.lang.python (lots of lurking, occasional posting) but kind of trailed off a bit. I just wrote a frustration inspired rant on my blog, and I thought it was relevant enough as a wider issue to the Python community to post here for your discussion and consideration. This is not flamebait. I love Python, and I'm not out to antagonise the community. I also realise that one of the issues I raise is way too ingrained to be changed now. I'd just like to share my thinking on a misstep in Python's guiding principles that has done more harm than good IMO. So anyway, here's the post. I've become utterly convinced that at least one criticism leveled at my favourite overall programming language, Python, is utterly true and fair. After quite a while away from writing Python code, I started last night on a whim to knock up some code for a prototype of an idea I once had. It's going swimmingly; the Python Image Library, which I'd never used before, seems quick, intuitive, and with the all the features I need for this project. As for Python itself, well, my heart still belongs to whitespace delimitation. All the basics of Python coding are there in my mind like I never stopped using them, or like I've been programming in this language for 10 years. Except when it comes to Classes. I added some classes to code that had previously just been functions, and you know what I did - or rather, forgot to do? Put in the 'self'. In front of some of the variable accesses, but more noticably, at the start of *every single method argument list.* This cannot be any longer blamed as a hangover from Java - I've written a ton more code, more recently in Python than in Java or any other OO language. What's more, every time I go back to Python after a break of more than about a week or so, I start making this 'mistake' again. The perennial justification for this 'feature' of the language? That old Python favourite, "Explicit is better than implicit." I'm sorry, but EXPLICIT IS NOT NECESSARILY BETTER THAN IMPLICIT. Assembler is explicit FFS. Intuitive, clever, dependable, expected, well-designed *implicit* behaviour is one of the chief reasons why I use a high level language. Implicitly garbage collect old objects for me? Yes, please! I was once bitten by a Python wart I felt was bad enough to raise and spend some effort advocating change for on comp.lang.python (never got around to doing a PEP; partly laziness, partly young and inexperienced enough to be intimidated at the thought. Still am, perhaps.) The following doesn't work as any sane, reasonable person would expect: # Blog code, not tested class A(): def __eq__(self, obj): return True a = A() b = [] assert a == b assert not (a != b) The second assertion fails. Why? Because coding __eq__, the most obvious way to make a class have equality based comparisons, buys you nothing from the != operator. != isn't (by default) a synonym for the negation of == (unlike in, say, every other language ever); not only will Python let you make them mean different things, without documenting this fact - it actively encourages you to do so. There were a disturbingly high number of people defending this (including one quite renowned Pythonista, think it might have been Effbot). Some had the temerity to fall back on "Explicit is better than implict: if you want != to work, you should damn well code __ne__!" Why, for heaven's sake, should I have to, when in 99.99% of use cases (and of those 0.01% instances quoted in the argument at the time only one struck me as remotely compelling) every programmer is going to want __ne__ to be the logical negation of __eq__? Why, dear Python, are you making me write evil Java-style language power reducing boilerplate to do the thing you should be doing yourself anyway? What's more, every programmer is going to unconciously expect it to work this way, and be as utterly as mystified as me when it fails to do so. Don't tell me to RTFM and don't tell me to be explicit. I'll repeat myself - if I wanted to be explicit, I'd be using C and managing my own memory thank you very much. Better yet, I'd explicitly and graphically swear - swear in frustration at this entrenched design philosophy madness that afflicts my favourite language. I think the real problem with the explicit is better than implicit, though, is that while you can see the underlying truth its trying to get at (which is perhaps better expressed by Ruby's more equivocal, less dependable, but more useful Principle of Least Surprise), in its stated form its actually kind of meanginless and is used mainly in defence of warts - no, we'll call them for what they are, a language design *bugs*. You see, the problem is, there's no such thing of explict in programming. Its not a question of not doing things implicitly; its a question of doing the most sensible thing implicitly. For example this python code: some_obj.some_meth(some_arg1, some_arg2) is implicitly equivalent to SomeClass.some_meth(some_obj, some_arg1, some_arg2) which in turn gives us self as a reference to some_obj, and Python's OO model merrily pretends its the same as Java's when in fact is a smarter version that just superficially looks the same. The problem is that the explicit requirement to have self at the start of every method is something that should be shipped off to the implicit category. You should have to be explicit, yes - explicit when you want the *other* behaviour, of self *not* being an argument, because thats the more unusual, less likely case. Likewise, a != b is implicitly equivalent to something like calling this function (may not be correct, its a while since I was heavily involved in this issue): def equal(a, b): if hasattr(a, "__ne__"): return a.__ne__(b) if hasattr(b, "__ne__"): return b.__ne__(a) if hasattr(a, "__cmp__"): return not (a.__cmp__(b) == 0) if hasattr(b, "__cmp__"): return not (b.__cmp__(a) == 0) return not (a is b) There's absolutely nothing explicit about this. I wasn't arguing for making behaviour implicit; I was arguing for changing the stupid implict behaviour to something more sensible and less surprising. The sad thing is there are plenty of smart Python programmers who will justify all kinds of idiocy in the name of their holy crusade against the implict. If there was one change I could make to Python, it would be to get that damn line out of the Zen. From noagbodjivictor at gmail.com Sun Jul 6 23:17:37 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Sun, 6 Jul 2008 23:17:37 -0400 Subject: GUI Programming by hand not code with Python Code Message-ID: > Is their a program that lets you design a GUI by hand (like gambas) > not by code (like wxpython) but the commands are in python? > > A program similar to gambas or vb > > Gambas with python code instead of gambas code would be perfect. > > Thanks in advance Check out the Designer program that comes with PyQt. -- NOAGBODJI Paul Victor From fredrik at pythonware.com Wed Jul 16 10:07:02 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 16:07:02 +0200 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: <487DFF56.7010405@timgolden.me.uk> References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> <487DFF56.7010405@timgolden.me.uk> Message-ID: Tim Golden wrote: > This is included in the latest pywin32-211 as well: > > > import win32process > print win32process.IsWow64Process () > on the other hand, "ctypes" is only an import away if you have a current Python... From adamc55 at gmail.com Tue Jul 8 10:33:02 2008 From: adamc55 at gmail.com (Adam C.) Date: Tue, 8 Jul 2008 07:33:02 -0700 (PDT) Subject: Dynamically Changing the Base Class References: <6d60c362-ba17-4414-babd-2cc254526bca@c58g2000hsc.googlegroups.com> <68bba759-864e-4943-9f1e-f19b99408ef7@l64g2000hse.googlegroups.com> Message-ID: <72e2ec01-2baa-45a6-a4d6-aaedf5451937@m3g2000hsc.googlegroups.com> On Jul 7, 4:04?pm, Carl Banks wrote: > On Jul 7, 9:31 am, "Adam C." wrote: > > > > > We have a situation where we want a Swig-generated Python class to > > have a different base (not object). It doesn't appear that we can > > coerce Swig into generating the class we want at present (but we are > > still enquiring). > > > Is it possible to dynamically change the base class to something else? > > Initial experiments appear to show it is not: > > -------------------------------- snip -------------------------------->>> class Foo(object): > > > ? ? ? ? pass > > > >>> class Foozle(object): > > > ? ? ? ? pass > > > >>> Foozle.__bases__ = (Foo,) > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? ? Foozle.__bases__ = (Foo,) > > TypeError: __bases__ assignment: 'Foo' deallocator differs from > > 'object' > > -------------------------------- snip -------------------------------- > > > Is there a solution I am missing? > > > Thanks in advance. > > You get the same effect as subclassing by using multiple inheritance. > Suppose your SWIG class called Foo to have a base class of Base. ?You > could instead call the SWIG class _Foo, and define Foo as a Python > class like this: > > class Foo(_Foo,Base): pass > > If you do that, the resulting class will behave exactly as if _Foo > were a subclass of base (apart from some introspection methods and > edge cases). ?You can see that this is so if you look at the MRO: > > Foo, _Foo, Base, object > > Which is the same MRO that would occur if _Foo derived from Base > directly. > > The drawback (which is also a drawback to the hypothetical base > reassignment) is that Foo's __init__ method won't call Base's. ?The > only way you can make SWIG __init__ call it's superclass's __init__ is > apparently a patch. > > Carl Banks Thanks. Looks like I will just write a patch step and hook it into the makefile. From bulg at ngs.ru Wed Jul 16 04:39:57 2008 From: bulg at ngs.ru (Yosifov Pavel) Date: Wed, 16 Jul 2008 01:39:57 -0700 (PDT) Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> <7348c0dc-028d-4f89-9d63-b1247fb6807c@m44g2000hsc.googlegroups.com> <6e5bu8F5eajaU1@mid.uni-berlin.de> Message-ID: On 16 ???, 11:32, Marc 'BlackJack' Rintsch wrote: > On Tue, 15 Jul 2008 19:54:30 -0700, Yosifov Pavel wrote: > > Kay, can you show example of such generator? ReIter, for example, work > > with usual generators. > > > But for "big" iterator, I think is no any good solutions. IMHO we can > > discern 2 types of iterators: re-startable (based on internal Python > > objects) and not re-startable (with an external state, side- > > effects)... > > Has nothing to do with internal vs. external. > Examples: ``itertools.count(1)``, ``itertools.cycle(iterable)``, or > > def fib(): > a, b = 0, 1 > while True: > yield a > a, b = b, a + b > > Ciao, > Marc 'BlackJack' Rintsch Yes. So, I'm disconcerted: what Python "means" about iterators. Why iterator's are not clonable in default?.. ``itertools.count(it) `` "suppose" ``it`` will be restarted after count? So ``count(it)`` "suppose" ``it`` is restarable and therefore clonable (why not?!). Generator is only function, so can be restarted/cloned. Generator keeps "position" and can't be iterated again. But this position can be reseted (main rule: if generator function has not side-effects/ external state, see below)! Iterator, I think, is more general method (for naturally serial access). For example, you can read values from some device (RS323 or other) and represent it in program like iterator. In this case, ``__iter__()`` make some preparation, ``next()`` read next value from RS232. In this case, iterator can't be restarted and really cloned. It has external state (state of device) and can't to return it at start. But when series of values are generated (are born) in the program: no problem to have the feature of clone/restart iterator. And is very interesting to research Icon iterators. Is possible to create something in Python such theirs, for non-deterministic solving purpose... :-) --pavel From norseman at hughes.net Tue Jul 8 20:51:52 2008 From: norseman at hughes.net (norseman) Date: Tue, 08 Jul 2008 17:51:52 -0700 Subject: a simple 'for' question In-Reply-To: <84bdef3c0807081732q33b3bccdvc1d2c361d8c34d80@mail.gmail.com> References: <4874017D.2000401@umbc.edu> <84bdef3c0807081732q33b3bccdvc1d2c361d8c34d80@mail.gmail.com> Message-ID: <48740BA8.5050605@hughes.net> Almost correct: There is a typo. Should read: for x in folders: open('my/path/way/'+x+'/myfile.txt','r') Rajanikanth Jammalamadaka wrote: > Hi! > > Try this > > for x in folders: > open('my/path/way'+x+'myfile.txt','r') > > Cheers, > > Raj > > On Tue, Jul 8, 2008 at 5:08 PM, Ben Keshet wrote: >> Hi fans, >> >> I want to use a 'for' iteration to manipulate files in a set of folders, >> something like: >> >> folders= ['1A28','1A6W','56Y7'] >> for x in folders: >> print x # print the current folder >> f = open('my/path/way/x/my_file.txt', 'r') >> ... >> >> where 'x' in the pathway should iterate over '1A28','1A6W','56Y7'. How >> should I identify 'x' in the pathway line as the same x that is iterating >> over 'folders'? >> >> I am getting the following error: >> >> Traceback (most recent call last): >> File >> "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", >> line 310, in RunScript >> exec codeObject in __main__.__dict__ >> File "C:\Linux\Dock_method_validation\myscripts\test_for.py", line 5, in >> >> f = open('c:/Linux/Dock_method_validation/x/receptor.mol2', 'r') >> IOError: [Errno 2] No such file or directory: >> 'c:/Linux/Dock_method_validation/x/receptor.mol2' >> >> I tired several variations: %x, 'x', "x", etc. all gave me similar errors. >> >> Thanks for your help, >> BK >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > From mail at timgolden.me.uk Thu Jul 24 11:25:37 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 24 Jul 2008 16:25:37 +0100 Subject: Attack a sacred Python Cow In-Reply-To: <48889a72$0$25165$426a74cc@news.free.fr> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <32e12408-fc9f-4eb4-8b9d-fb7fa69bd2fc@f36g2000hsa.googlegroups.com> <87zlo7y2wn.fsf@physik.rwth-aachen.de> <48889a72$0$25165$426a74cc@news.free.fr> Message-ID: <48889EF1.4000901@timgolden.me.uk> Just wondered whether the OP's Subject was a deliberate play on "flog a dead horse" or merely an ironic one :) TJG From Lie.1296 at gmail.com Tue Jul 8 06:45:41 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 8 Jul 2008 03:45:41 -0700 (PDT) Subject: Confused yet again: Very Newbie Question References: <13be8c54-3fa9-4a37-a0e6-45bb019bff7e@a1g2000hsb.googlegroups.com> Message-ID: On Jul 7, 7:09?pm, Jeff wrote: > When you call c3.createJoe(c1.fred), you are passing a copy of the > value stored in c1.fred to your function. ?Python passes function > parameters by value. No, python doesn't pass variable either by value or by reference. The behavior in python is a bit of mix between passing by value and by reference, because python use different variable model than Basic (in short, saying passing by reference or value in python doesn't make sense). In python, variables are names referring to an object, in Basic variables are the object itself. In python, when you pass variable as function parameter, you pass the object to the function and inside the function a new name is rebound to that object. These two names are not related in any way except that they refers to the same object. In python an immutable object can't be changed after creation and string is immutable, so when you reassign 'Joe' to myName, a string object 'Joe' is created and assigned to myName, myName's original string object ('fred') isn't affected and other names that refers to the string object 'fred' (i.e. c1.fred, one.fred) isn't changed. If you want to change all those values too, you'd have to change the inner string object itself (which is impossible since string object is immutable). If the object referred is mutable (e.g. list, dictionary) that example would work. >?The function will not destructively modify its > arguments; you must expliticly state your intention to modify an > object: > > class one(): > ? ? fred = 'fred' > > class three(): > ? ? def createJoe(self, myName): > ? ? ? ? return "Joe" > > def main(): > ? ? c1 = one() > ? ? c3 = three() > ? ? c1.fred = c3.createJoe() # Modify c1's attribute, fred, with the > return value from c3.createJoe From alan.franzoni.blahblah at example.com.invalid Mon Jul 28 04:02:42 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Mon, 28 Jul 2008 08:02:42 GMT Subject: write unsigned integer 32 bits to socket References: Message-ID: Michael Torrie was kind enough to say: > Of course any time you send coherent numbers over the network, I highly > recommend you use what's called network byte order. In C, you'd use the > htonl() call, and then when pulling it off the wire on the other end > you'd use ntohl(). If you don't then you will have problems when the > endianness is different between the hosts. Standard convention (even in > the MS word) is to use big-ending across the network. I'm sure python > has some convention in the struct module for dealing with this. Not in the struct module; such functions are available in the socket module, and should be employed indeed. -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From Russ.Paielli at gmail.com Mon Jul 28 21:54:02 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jul 2008 18:54:02 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> <488e3520$0$16766$426a74cc@news.free.fr> Message-ID: On Jul 28, 12:08 pm, Bruno Desthuilliers wrote: > > It's a very simple idea that you insist on > > making complicated. As I said, I could write a pre-processor myself to > > implement it in less than a day. > > Preprocessor are not a solution. Sorry. I never said that a pre-processor is a good permanent solution, but the simple fact that my proposal can be done with a simple pre- processor means that it does not change the inner workings of the Python interpreter. > Oh, you don't stand people disagreing with you, that's it ? I can stand people disagreeing with me all day long, so long as they are making sense. You are simply making the issue more complicated that it is because you are apparently incapable of understanding the substance of it. > > You seem to think that being a "regular" on this newsgroup somehow > > gives you special status. > > Why so ? Because I answer to your proposition and not agree with your > arguments ??? C'mon, be serious, you have the right to post your > proposition here, I have the right to post my reaction to your > proposition, period. Grow up, boy. > Boy, I don't know who you think you're talking to, but you're obviously > out of luck here. I'm 41, married, our son is now a teenager, I have an > happy social life, quite a lot of work, and no time to waste in the > streets. And FWIW, name-calling won't buy you much here. There you go again. Do you think you are proving something by addressing me as "boy"? I'll make a little wager with you. I'll bet that what I am using Python for dwarfs in importance what you are using it for. Care to put the cards on the table, big man? I'll tell you something else while I'm at it. I'm ten years older than you, but I pump iron and stay in excellent shape. If you addressed me as "boy" in person, I'd be more than happy to teach you a badly needed lesson you won't soon forget, big man. From noelob at gmail.com Wed Jul 23 04:44:13 2008 From: noelob at gmail.com (noelob) Date: Wed, 23 Jul 2008 01:44:13 -0700 (PDT) Subject: Uploading an image using PUT References: <2375be12-6470-493c-9d4f-979e20c35502@k13g2000hse.googlegroups.com> Message-ID: <8018550e-a5a2-46b7-a989-64b1aa6d2a26@2g2000hsn.googlegroups.com> Hi All, I finally figured it out, thanks to Wireshark! I was adding my own "Content-Length: 50173" header to the request, but httplib appears to add its own header (also "Content-Length: 50173") which must have been causing a conflict and making the sever return "HTTP/1.1 400 Bad Request\r\n". As soon as I removed my own Content-Length header, it worked! Regards, Noel From jr9445 at ATT.COM Tue Jul 15 16:21:24 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Tue, 15 Jul 2008 15:21:24 -0500 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Reedick, Andrew > Sent: Tuesday, July 15, 2008 4:13 PM > To: Victor Noagbodji; python-list at python.org > Subject: RE: 'if name is not None:' v. 'if name:' > > If name: > Then either > a) name is an object, and that object does not have a 'false' > value, such as False, zero, or empty. > or > b) name is NULL/None. No object. Change that to: If not name: Then either a) name is an object, and that object does not have a 'false' value, such as False, zero, or empty. or b) name is NULL/None. No object. From danb_83 at yahoo.com Mon Jul 21 22:34:57 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Mon, 21 Jul 2008 19:34:57 -0700 (PDT) Subject: Odd math related issue. References: <43332.3139710867$1216630189@news.gmane.org> Message-ID: <69374534-64bd-4784-9255-7238883ae51a@z6g2000pre.googlegroups.com> On Jul 21, 3:52?am, Fredrik Lundh wrote: > Robert Rawlins wrote: > > I?ve got what seems to me to be a totally illogical math issue here > > which I can?t figure out. Take a look at the following code: > > > ? ? ? ? /self/.__logger.info(/"%i / %i"/ % (bytes_transferred, > > /self/.__sessions[path].total_bytes)) > > > ? ? ? ? percentage = bytes_transferred / > > /self/.__sessions[path].total_bytes * 100 > > > ? ? ? ? /self/.__logger.info(/"%i"/ % percentage) > > > Seems fairly straight forward, you would think. It takes two values and > > calculates the percentage of one from the other, however, percentage > > always comes back as ?0? for some reason, look at this log output. > > if you divide two integers, you'll get an integer back (in Python 2.X, > at least). ?quick fix: > > ? ? ? percentage = bytes_transferred * 100 / total_bytes > > The most wonderful statement in the Python language is from __future__ import division From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 15:25:59 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 21:25:59 +0200 Subject: readln() until EOF In-Reply-To: References: Message-ID: <4888d744$0$5450$426a34cc@news.free.fr> korean_dave a ?crit : > a = open("Thefile.txt","r") > > while ?????: > result = a.readln() I assume you meant "a.readline()" ? Anyway... > what do i put in ???? if i want to keep reading line by line until i > reach the end of the file? a = open("path/to/file.ext") for line in a: do_something_with(line) a.close() From semanticist at gmail.com Sun Jul 13 16:08:28 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 16:08:28 -0400 Subject: socket.connect() hangs in SYN_SENT state. In-Reply-To: <804bccb2-42c7-42e9-8f50-7a780d3438fd@j22g2000hsf.googlegroups.com> References: <804bccb2-42c7-42e9-8f50-7a780d3438fd@j22g2000hsf.googlegroups.com> Message-ID: On Sun, Jul 13, 2008 at 2:32 PM, bukzor wrote: > On Jul 13, 1:14 am, Miles wrote: >> On Sat, Jul 12, 2008 at 11:23 PM, bukzor wrote: >> > I'm connecting to an apache2 process on the same machine, >> > for testing. When looking at netstat, the socket is in the SYN_SENT >> > state, like this: >> >> > $netstat -a -tcp >> > tcp 0 0 *:www *:* LISTEN 7635/apache2 >> > tcp 0 1 bukzor:38234 adsl-75-61-84-249.d:www SYN_SENT 9139/python >> >> > Anyone know a general reason this might happen? Even better, a way to >> > fix it? >> >> That socket connection is to a remote machine, not the same one. Your >> test code works fine for me. The "hang then crash" (and I'm assuming >> "crash" here means an uncaught exception) just means that your packets >> are being silently ignored by whatever machine you're actually >> attempting to connect to. It's possible that your machine has odd DNS >> settings causing buzkor.hopto.org to resolve to the wrong address. > > I'm connecting to my machine through the internet, and the resolved > URL of my router is what you're seeing above. If you run the code > above you'll see what I mean. I did run the code, and as I said, it works fine. Your description of the setup is not consistent. The netstat output unambiguously states that a Python script on "buzkor" is attempting to open a connection to the HTTP port on the "adsl" machine (and failing because "adsl" is not responding). The problem here is not Python; you seem to be confused about which machine is connecting to which. -Miles From google at mrabarnett.plus.com Wed Jul 30 13:25:42 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 30 Jul 2008 10:25:42 -0700 (PDT) Subject: Standard module for parsing emails? References: <6fb93eFap7j5U1@mid.individual.net> Message-ID: <86cbbf9d-e568-42a4-8839-5015225937dc@34g2000hsf.googlegroups.com> On Jul 30, 3:11?pm, Phillip B Oldham wrote: > On Jul 30, 2:36 pm, Thomas Guettler wrote: > > > What do you mean with "quote" here? > > ? 2. Prefix of quoted text like your text above in my mail > > Basically, just be able to parse an email into its actual and "quoted" > parts - lines which have been prefixed to indent from a previous > email. > > Most clients use ">" which is easy to check for, but I've seen some > which use "|" and some which *don't* quote at all. Its causing us > nightmares in parsing responses to system-generated emails. I was > hoping someone might've seen the problem previously and released some > code. The problem is that sometimes lines might start with ">" for other reasons, eg text copied from an interactive Python session, which could occur in ... um ... _this_ newsgroup. :-) From aoeui2008 at nospam.cox.net Sun Jul 20 20:50:38 2008 From: aoeui2008 at nospam.cox.net (Teiresias) Date: Sun, 20 Jul 2008 19:50:38 -0500 Subject: Python Written in C? References: Message-ID: <87r69ooyap.fsf@cox.net> giveitawhril2008 at gmail.com writes: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? Well, yes, the interpreter and a handful of the core modules are written in C. However, most of Python -- especially the cool bits -- aren't written in C. They're written in ... Python! -- Teiresias From circularfunc at yahoo.se Tue Jul 15 13:36:23 2008 From: circularfunc at yahoo.se (defn noob) Date: Tue, 15 Jul 2008 10:36:23 -0700 (PDT) Subject: isPrime works but UnBoundLocalError when mapping on list References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> <8a07445a-3ca8-4373-9312-cea8db83ec5c@l64g2000hse.googlegroups.com> Message-ID: <9f3c45f1-9cb2-46c1-838b-716180061956@e39g2000hsf.googlegroups.com> On Jul 15, 7:28?pm, Mensanator wrote: > On Jul 15, 11:26?am, defn noob wrote: > > > > > isPrime works when just calling a nbr but not when iterating on a > > list, why? adding x=1 makes it work though but why do I have to add > > it? > > Is there a cleaner way to do it? > > > def isPrime(nbr): > > ? ? for x in range(2, nbr + 1): > > ? ? ? ? if nbr % x == 0: > > ? ? ? ? ? ? break > > ? ? if x == nbr: > > ? ? ? ? return True > > ? ? else: > > ? ? ? ? return False > > > >>> [isPrime(y) for y in range(11)] > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? ? [isPrime(y) for y in range(11)] > > ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > > ? ? if x == nbr: > > UnboundLocalError: local variable 'x' referenced before assignment > > > >>> map(isPrime, range(100)) > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? ? map(isPrime, range(100)) > > ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > > ? ? if x == nbr: > > UnboundLocalError: local variable 'x' referenced before assignment>>> isPrime(10) > > False > > >>> isPrime(11) > > > True > > > adding x=1 makes it work though: > > > def isPrime(nbr): > > ? ? x=1 > > ? ? for x in range(2, nbr + 1): > > ? ? ? ? if nbr % x == 0: > > ? ? ? ? ? ? break > > ? ? if x == nbr: > > ? ? ? ? return True > > ? ? else: > > ? ? ? ? return False > > > >>> [isPrime(y) for y in range(11)] > > > [False, True, True, True, False, True, False, True, False, False, > > False] > > No, it doesn't. You are falsely reporting that 1 is prime. > > And instead of making the fake variable x, shouldn't you > instead test that nbr+1 is greater than 2? Or call it with > range(3,11) instead of range(11)? x isn't initialized > because if nbr+1 is <=2, the for loop has an invalid range > and doesn't even execute. def isPrime(nbr): for x in range(2, nbr + 1): if nbr % x == 0: break if x == nbr: return True else: return False this works for all primes, if i want to not include 1 i just do if nbr<=1 return false you are answering the wrong question. anyway here is a clear one: def isPrime(nbr): if nbr < 2: return False for x in range(2, nbr + 1): if nbr % x == 0: return nbr == x From fredrik at pythonware.com Wed Jul 23 08:26:39 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 14:26:39 +0200 Subject: os.walk question In-Reply-To: <79b8d5e1-709f-4a4f-957d-8acbee20018b@c2g2000pra.googlegroups.com> References: <79b8d5e1-709f-4a4f-957d-8acbee20018b@c2g2000pra.googlegroups.com> Message-ID: alex23 wrote: >> if you want a list of files from a single directory, use listdir, not walk: >> >> >>> import os, random >> >>> random.choice(os.listdir("/")) >> 'python25' > > This will include folders as well, though, which isn't what the OP > asked for. as illustrated by my example (cut and pasted from a windows machine). oops. random.choice(filter(os.path.isfile, glob.glob("/*"))) isn't that bad, though. From circularfunc at gmail.com Thu Jul 31 07:09:57 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 31 Jul 2008 04:09:57 -0700 (PDT) Subject: How smart is the Python interpreter? Message-ID: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> def str_sort(string): s = "" for a in sorted(string): s+=a return s if i instead do: def str_sort(string): s = "" so = sorted(string) for a in so: s+=a return s will that be faster or the interpreter can figure out that it only has to do sorted(string) once? or that kind of cleverness is usually reserved for compilers and not interpreters? From tjreedy at udel.edu Thu Jul 17 17:32:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jul 2008 17:32:30 -0400 Subject: x, = y (???) In-Reply-To: References: Message-ID: kj wrote: > > > I just came across an assignment of the form > > x, = y > > where y is a string (in case it matters). > > 1. What's the meaning of the comma in the LHS of the assignment? > 2. How could I have found this out on my own? 1.Experiment with the interactive interpreter. It is sooo easy. >>> x, = '1' >>> x '1' >>> x, = '12' Traceback (most recent call last): File "", line 1, in x, = '12' ValueError: too many values to unpack >>> x,y = '12' >>> x,y ('1', '2') >>> x, = 3 Traceback (most recent call last): File "", line 1, in x, = 3 TypeError: 'int' object is not iterable >>> *x, = [3] >>> x [3] 2. Read the Python docs which come with the interpreter. LanguageReference/SimpleStatements/AssignmentStatements: "If the target list is a comma-separated list of targets: ... Else: The object must be a sequence with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets." which is exactly the behavior observed above. From cjw at ncf.ca Sun Jul 27 16:04:43 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sun, 27 Jul 2008 16:04:43 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > On Jul 26, 2:25 pm, Terry Reedy >> There is a lot of code you have not seen. Really. In informal code I >> use 's' and 'o' for 'self' and 'other'. I don't usually post such >> because it is not considered polite. So you have seen a biased sample >> of the universe. > > You take the name down to a single letter. As I suggested in an > earlier post on this thread, why not take it down to zero letters? You > could if Python accepted something like > > class Whatever: > > def fun( , cat): > > .cat = cat > > This is even better than the single-character name, not only because > it is shorter, but also because there is no question that you are > referring to "self." No need to look back at the method signature to > verify that. > > For those who don't like the way the empty first argument looks, maybe > something like this could be allowed: > > def fun( ., cat): > I don't see the need for the comma in fun. Colin W. From tommy.nordgren at comhem.se Mon Jul 28 13:51:26 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Mon, 28 Jul 2008 19:51:26 +0200 Subject: like py2exe, but on a mac In-Reply-To: <5K9jk.278$rb5.198@trnddc04> References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> Message-ID: On 28 jul 2008, at 03.59, William McBrine wrote: > On Sun, 13 Jul 2008 00:58:59 +0200, Python.Arno wrote: > >> http://undefined.org/python/py2app.html > > py2app bundles Python itself into the app, right? I wonder, is there > no > way to create an app bundle that relies on the existing installation > of > Python, since OS X already comes with Python? I have a tiny little > program (~20k) that I'd like to make into an app bundle, if only to > suppress the console window, and I'd rather not lump in the whole > Python > interpreter if I can avoid it. > > -- > 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on > -- > http://mail.python.org/mailman/listinfo/python-list There is Platypus, a general open source program to wrap a script in an Macintosh (GUI) Application. -------------- next part -------------- A non-text attachment was scrubbed... Name: Platypus 4.0 software download - Mac OS X - VersionTracker.webloc Type: application/octet-stream Size: 286 bytes Desc: not available URL: -------------- next part -------------- ---------------------------------- Skinheads are so tired of immigration, that they are going to move to a country that don't accept immigrants! Tommy Nordgren tommy.nordgren at comhem.se From giltay at gmail.com Tue Jul 29 17:48:31 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Tue, 29 Jul 2008 14:48:31 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: <2ac250ee-131d-44a3-9b0a-f2fb34758147@c65g2000hsa.googlegroups.com> On Jul 29, 1:30?pm, Carl Banks wrote: > On Jul 29, 5:15 am, Heiko Wundram wrote: > > > I can't dig up a simple example from code I wrote quickly, but because of the > > fact that explicit comparisons always hamper polymorphism > > I'm not going to take your word for it. ?Do you have code that > demonstrates how "if x" improves polymorphism relative to simple > explicit tests? > > Carl Banks I think "if x" works in some cases, but not in others. Here's an example I just made up and a counterexample from my own code. Example: Here's a function, print_members. It's just something that takes some iterable and prints its members in XML. It's special-cased so that an empty iterable gets an empty tag. (This is a bit of a trivial example, I admit; the point is that the empty iterable is a special case.) def print_members(iterable): if not iterable: print '' return print '' for item in iterable: print '%s' % item print '' >>> print_members(['a', 'b', 'c']) a b c >>> print_members([]) I could have used "if len(iterable) == 0:" for these cases, but only because the length of a list means something. Say I were to implement a matrix class. The length of a matrix isn't well-defined, so I won't implement __len__. I will, however, implement __nonzero__, since if it has no members, it's empty. class SimpleMatrix(object): def __init__(self, *rows): self.rows = rows def __nonzero__(self): for row in self.rows: if row: return True return False def __iter__(self): return iter(sum(self.rows, [])) >>> a = SimpleMatrix([1, 2, 3], [4, 5, 6]) >>> print_members(a) 1 2 3 4 5 6 >>> b = SimpleMatrix([],[],[]) >>> len(b) Traceback (most recent call last): File "", line 1, in TypeError: object of type 'SimpleMatrix' has no len() >>> print_members(b) So print_members can work on iterables that have no len(), and handle the special case of an empty iterable, as long as __nonzero__ is implemented. Counterexample: While "if x" works well in some circumstances, I don't like using it for purely numeric types. For instance, I have a mutable Signal class for doing some basic DSP. Among other things, I can apply a DC offset to the signal (it just adds the offset to all the samples). I have a special case for an offset of 0 so I don't have to loop through all the samples (I also have a two-pass remove_offset method that subtracts the average; if it's already properly centred, I can skip a step). class Signal: [...] def dc_offset(self, amount): if amount == 0: return self.samples = [sample + amount for sample in self.samples] Here, "if amount == 0" is deliberate. At no point should I be adding an offset that's a list or a dict, even an empty one. Signal.dc_offset should raise an exception if I try to do that, because that indicates there's a bug somewhere. If I do pass in [] or {}, that test will fail, and it will try to add the list or dict to the samples, at which point I get a TypeError. Geoff G-T From thomas.troeger.ext at siemens.com Fri Jul 4 08:59:05 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Fri, 04 Jul 2008 14:59:05 +0200 Subject: Static Class Initialization Question. References: <486e16c8$0$22780$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > return "%s(%d,%d)" % (type(self).__name__, self.a, self.b) Er, yes exactly! I noticed it a few seconds after I had sent the message ;-( >> I want to have a list of such classes instantiated automatically on Of course I meant class instances ... sorry :) It's always good to have an example to compensate for English errors *g*. > bla = [A(*args) for args in ((1,2), (3,4))] ... > Note that it's not a list of classes, but a list of instances of A. But > given your specs, nope, your approach is the right one. Ah I knew there was something and I couldn't find it in the docs anymore! Now my potential follow-up question is answered as well, namely how I can instantiate with variable argument lists, like this: >>> bla = [A(*args) for args in ((), (1,), (1, 2))] >>> map(str, bla) ['A(0,1)', 'A(1,1)', 'A(1,2)'] > Basically (no pun intended[1]), Python is not C. Trying to write C in > Python will only buy you pain and frustration (and this can be > generalized for any combination of two languages for any known > programming language). Hehe. I am trying to develop a program prototype in python because of it's repaid prototyping properties, and once it's working I will port it to C, because of speed issues and the fact that it's running on an embedded machine without space for a python interpreter. I have like 4 Megs left, but until now noone has answered my question how I can cut down a standard python installation so that it fit's into 4 megs. Thanks for your quick answer :) T. From robinsiebler at gmail.com Thu Jul 31 17:41:22 2008 From: robinsiebler at gmail.com (robinsiebler at gmail.com) Date: Thu, 31 Jul 2008 14:41:22 -0700 (PDT) Subject: saving an e-mail attachement Message-ID: I'm trying to figure out how to save an e-mail attachment from a POP3 mailbox. I've scoured the web, but -none- of the examples I have found have actually worked. For instance, in this example: http://groups.google.com/group/comp.lang.python/browse_thread/thread/8423cad79ff21730/0d8922943a164ccf?lnk=gst&q=email+attachment#0d8922943a164ccf, fn is always None, but the e-mail -does- have an attachment (an xml file). From sri_annauni at yahoo.co.in Mon Jul 14 06:41:45 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Mon, 14 Jul 2008 16:11:45 +0530 (IST) Subject: Do we have perl's Data::Dumper equivalent in Python?? Message-ID: <502717.38540.qm@web7902.mail.in.yahoo.com> Thanks, Srini Bollywood, fun, friendship, sports and more. You name it, we have it on http://in.promos.yahoo.com/groups/bestofyahoo/ From __peter__ at web.de Tue Jul 1 07:22:37 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Jul 2008 13:22:37 +0200 Subject: Disabling the magic "last expression" _ variable References: <486a108d$0$14358$e4fe514c@news.xs4all.nl> Message-ID: Koen Vossen wrote: > A project I'm currently working on uses Turbogears as a framework. I'd > like to interact with it using the tg-admin shell. We also use gettext's > _() function for internationalization. Now, this function is overwritten > in interactive mode, which causes annoying exceptions. Is it possible to > disable this behavior? [correct overzealous snip] >>> import sys >>> def displayhook(result): ... if result is not None: ... __builtins__._last = result ... print result ... >>> sys.displayhook = displayhook >>> _ Traceback (most recent call last): File "", line 1, in NameError: name '_' is not defined >>> "yadda" yadda >>> _ Traceback (most recent call last): File "", line 1, in NameError: name '_' is not defined >>> _last yadda Peter From sjmachin at lexicon.net Sat Jul 19 17:44:24 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 19 Jul 2008 14:44:24 -0700 (PDT) Subject: regex doubts References: <532965.570.qm@web54502.mail.re2.yahoo.com> <504d473e-375a-4111-ae2e-c06aaa37b096@p25g2000pri.googlegroups.com> <5a77d3ef-2313-4f3a-9486-d27136ac0409@b1g2000hsg.googlegroups.com> Message-ID: <0d3a6680-3dce-4353-b389-c0e3b2930847@j1g2000prb.googlegroups.com> On Jul 20, 6:35 am, MRAB wrote: > On Jul 19, 9:12 pm, John Machin wrote: > > > > > On Jul 20, 5:04 am, Fredrik Lundh wrote: > > > > Mr SZ wrote: > > > > I am taking a string as an input from the user and it should only > > > > contain the chars:L , M or R > > > > > I tried the folllowing in kodos but they are still not perfect: > > > > > [^A-K,^N-Q,^S-Z,^0-9] > > > > [L][M][R] > > > > [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > > > > > For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. > > > > try "[LRM]+$" (an L or an R or an M, one or more times, all the way to > > > the end of the string). > > > Ummm ... with the default flag settings, shouldn't that be \Z instead > > of $ > > ? > > $ means end of string unless the multiline flag is used, in which case > it means end of line. What manual are you quoting that from? What version of Python are you using? Can you demonstrate that the pattern "[LRM]+$" will fail to match the string "L\n"? From ggpolo at gmail.com Mon Jul 28 19:43:39 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 28 Jul 2008 20:43:39 -0300 Subject: Tkinter fullscreen with Mac OS X In-Reply-To: References: Message-ID: On Mon, Jul 28, 2008 at 8:10 PM, C Martin wrote: > Is there a way to create a full screen app using Tkinter with Mac OS > X?? On windows, this is relatively easy with overrideredirect(1). > However, on the Mac, the top menu bar and dock are still displayed > over the app. Is there a way to get rid of them? > You could try this, supposing tl is a toplevel: tl.tk.call("::tk::unsupported::MacWindowStyle", "style", tl._w, "plain", "none") and if you are using python with tk 8.5 or newer (unlikely): tl.wm_attributes('-fullscreen', 1) But I don't have a mac, so I can't say for sure if these solve your problem. > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From fredrik at pythonware.com Mon Jul 21 03:17:55 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 09:17:55 +0200 Subject: Web Server In-Reply-To: References: Message-ID: James Tanis wrote: >> there's also apache, of course, and a bunch of others, including several >> Python solutions (more or less pre-packaged). but the "open up" part >> still sounds a bit risky. maybe you could turn things around, and let >> the application "push" data to your server instead? > > Either way requires an open port, otherwise there's no way to negotiate new > clients. The scenario I had in mind was rather to make his application the client for an external server, instead of using some external client to connect to someone's PC over HTTPS. That wouldn't need an open server port on the client; any Comet-style protocol would work. But at this point, only the OP knows enough about his application to be able to figure out if that's a usable approach. From alan.franzoni.blahblah at example.com.invalid Wed Jul 30 08:05:31 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Wed, 30 Jul 2008 12:05:31 GMT Subject: Continuous integration for Python projects References: Message-ID: Hussein B was kind enough to say: > Hi. > Please correct my if I'm wrong but it seems to me that the major > continuous integration servers (Hudson, CruiseControl, TeamCity ..) > don't support Python based application. If you want, you can use ant as a build script, and then define the usual targets (build, dist, test), ecc. and then use xmlrunner to publish them in a junit-like format which can be read through cruisecontrol or other CI tools. -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From animator333 at gmail.com Fri Jul 18 03:32:46 2008 From: animator333 at gmail.com (King) Date: Fri, 18 Jul 2008 00:32:46 -0700 (PDT) Subject: sub typing built in type with common attributes. Am I right? Message-ID: <4d9c4b74-9c28-4b98-afe7-9eb774655c3a@v21g2000pro.googlegroups.com> I am new to python and getting into classes. Here I am trying to create subtype of built in types with some additional attributes and function. 'Attributes' is the main class and holds all the common attributes that requires by these subtypes. This is what I came out with. I need to know whether everything is right here ? or there are some better ways to do it. class Attribute(object): """ Common attributes and methods for custom types """ def __init__(self, name=None, type=None, range=None, label=None): #read only attributes self._name = name self._type = type self._range = range #read/write attribute self.label = label #make read only attributes name = property(lambda self: self._name) type = property(lambda self: self._type) range = property(lambda self: self._range) class Float(float, Attribute): '''Custom Float class with some additional attributes.''' __slots__ = ['_Attribute__name', '_Attribute__type', '_Attribute__range', 'label'] def __new__(cls, value=0.0, *args, **kwargs): return float.__new__(cls, value) def __init__(self, value=0.0, name=None, label=None, type=None, range=(0.0, 1.0)): super(Float, self).__init__(name=name, label=label, type=type, range=range) def __str__(self): return '{ %s }' % (float.__str__(self)) class Int(int, Attribute): '''Custom Int class with some additional attributes.''' __slots__ = ['_Attribute__name', '_Attribute__type', '_Attribute__range', 'label'] def __new__(cls, value=0.0, *args, **kwargs): return int.__new__(cls, value) def __init__(self, value=0.0, name=None, label=None, type=None, range=(0.0, 1.0)): super(Int, self).__init__(name=name, label=label, type=type, range=range) def __str__(self): return '{ %s }' % (int.__str__(self)) From andreas.mock at web.de Wed Jul 16 10:18:39 2008 From: andreas.mock at web.de (McA) Date: Wed, 16 Jul 2008 07:18:39 -0700 (PDT) Subject: Logging to different addressees References: <8df30038-86c1-4376-b046-a50f2bcf0a2b@s50g2000hsb.googlegroups.com> <7b829a76-ba2c-4cb7-b216-0c9c01e5cd02@f36g2000hsa.googlegroups.com> <4d3df1d9-339b-43b2-9f25-c792e9bf549c@k13g2000hse.googlegroups.com> <4e30c301-294c-4160-8cb8-c924aed00f71@f63g2000hsf.googlegroups.com> <9566e05f-7ad6-499d-8404-52d60e23b6e8@m36g2000hse.googlegroups.com> Message-ID: <39b03da6-d8f4-4f4e-95c5-375be42035e3@j22g2000hsf.googlegroups.com> On 16 Jul., 15:38, Vinay Sajip wrote: > On Jul 16, 8:55 am, McA wrote: > > > messages tologging.getLogger('tree.leave') would also show up inlogging.getLogger('tree') automatically? > > Yes. Ok. > > > Hope not to bother. > > Use the propagate flag, which is mentioned in the documentation. That's the right hint. > In fact, please make sure you've reviewed all the documentation before > posting, as the documentation is intended to answer the more > straightforward and common questions which come up. I did it and I'll do it again. :-) You know, sometimes a piece of text/documentation starts to become information for the reader when he exactly hits the problem. Anyway, thank you for your help and for that module. > Best regards, > > Vinay Sajip Best regards Andreas Mock From ggpolo at gmail.com Mon Jul 28 18:52:36 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 28 Jul 2008 19:52:36 -0300 Subject: Download excel file from web? In-Reply-To: <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> References: <6f6vhlFa7anrU1@mid.uni-berlin.de> <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> Message-ID: On Mon, Jul 28, 2008 at 7:43 PM, patf at well.com wrote: > On Jul 28, 3:33 pm, "p... at well.com" wrote: >> On Jul 28, 3:29 pm, "Diez B. Roggisch" wrote: >> >> >> >> > p... at well.com schrieb: >> >> > > On Jul 28, 3:00 pm, "p... at well.com" wrote: >> > >> Hi - experienced programmer but this is my first Python program. >> >> > >> This URL will retrieve an excel spreadsheet containing (that day's) >> > >> msci stock index returns. >> >> > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... >> >> > >> Want to write python to download and save the file. >> >> > >> So far I've arrived at this: >> >> > >> [quote] >> > >> # import pdb >> > >> import urllib2 >> > >> from win32com.client import Dispatch >> >> > >> xlApp = Dispatch("Excel.Application") >> >> > >> # test 1 >> > >> # xlApp.Workbooks.Add() >> > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' >> > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' >> > >> # xlBook = xlApp.ActiveWorkbook >> > >> # xlBook.SaveAs(Filename='C:\\test.xls') >> >> > >> # pdb.set_trace() >> > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ >> > >> excel? >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> > >> +25%2C+2008&export=Excel_IEIPerfRegional') >> > >> # test 2 - returns check = False >> > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ >> > >> indexperf/excel? >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() >> >> > >> xlApp = response.fp >> > >> print(response.fp.name) >> > >> print(xlApp.name) >> > >> xlApp.write >> > >> xlApp.Close >> > >> [/quote] >> >> > > Woops hit Send when I wanted Preview. Looks like the html [quote] tag >> > > doesn't work from groups.google.com (nice). >> >> > > Anway, in test 1 above, I determined how to instantiate an excel >> > > object; put some stuff in it; then save to disk. >> >> > > So, in theory, I'm retrieving my excel spreadsheet with >> >> > > response = urllib2.urlopen() >> >> > > Except what then do I do with this? >> >> > > Well for one read some of the urllib2 documentation and found the >> > > Request class with the method has_data() on it. It returns False. >> > > Hmm that's not encouraging. >> >> > > I supposed the trick to understand what urllib2.urlopen is returning >> > > to me; rummage around in there; and hopefully find my excel file. >> >> > > I use pdb to debug. This is interesting: >> >> > > (Pdb) dir(response) >> > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', >> > > 'code', ' >> > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', >> > > 'readline', ' >> > > readlines', 'url'] >> > > (Pdb) >> >> > > I suppose the members with __*_ are methods; and the names without the >> > > underbars are attributes (variables) (?). >> >> > No, these are the names of all attributes and methods. read is a method, >> > for example. >> >> right - I got it backwards. >> >> >> >> >> >> > > Or maybe this isn't at all the right direction to take (maybe there >> > > are much better modules to do this stuff). Would be happy to learn if >> > > that's the case (and if that gets the job done for me). >> >> > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty >> > clear on this: >> >> > """ >> > This function returns a file-like object with two additional methods: >> > """ >> >> > And then for file-like objects: >> >> >http://docs.python.org/lib/bltin-file-objects.html >> >> > """ >> > read( [size]) >> > Read at most size bytes from the file (less if the read hits EOF >> > before obtaining size bytes). If the size argument is negative or >> > omitted, read all data until EOF is reached. The bytes are returned as a >> > string object. An empty string is returned when EOF is encountered >> > immediately. (For certain files, like ttys, it makes sense to continue >> > reading after an EOF is hit.) Note that this method may call the >> > underlying C function fread() more than once in an effort to acquire as >> > close to size bytes as possible. Also note that when in non-blocking >> > mode, less data than what was requested may be returned, even if no size >> > parameter was given. >> > """ >> >> > Diez >> >> Just stumbled upon .read: >> >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ >> excel? >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> +25%2C+2008&export=Excel_IEIPerfRegional').read >> >> Now the question is: what to do with this? I'll look at the >> documentation that you point to. >> >> thanx - pat > > Or rather (next iteration): > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > excel? > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > The file is generally something like 26 KB so specifying 1,000,000 > seems like a good idea (first approximation). > > And then when I do: > > print(response) > > I get a whole lot of garbage (and some non-garbage), so I know I'm > onto something. > > When I read the .read documentation further, it says that read() has > returned the data as a string object. Now - how do I convince Python > that the string object is in fact an excel file - and save it to disk? > You don't need to convince Python, just write it to a file. More reading for you: http://docs.python.org/tut/node9.html > pat > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From dstromberglists at gmail.com Sat Jul 26 16:54:07 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Sat, 26 Jul 2008 20:54:07 GMT Subject: SimpleJson is slow .... is there any C Compiled version ? References: <83a8a774-ddec-4137-9dbe-b6db3b4adfa2@p25g2000hsf.googlegroups.com> Message-ID: On Sat, 26 Jul 2008 00:49:20 -0700, Richard Levasseur wrote: > On Jul 25, 5:52?pm, Matt Nordhoff wrote: >> Also, simplejson and python-cjson might not be entirely compatible: >> there's one character that one escapes and the other doesn't, or >> something. -- > > They also have different interface. simplejson uses load/loads/dump/ > dumps, whereas cjson using encode/decode (its pretty simple to > monkeypatch cjson with some lambda's so it has the same interface, > though). > > Yeah, its frustrating that there are so many json encoders for python. > Its a bit disappointing simplejson is going into the stdlib; i hope they > rewrite it in C? C's great for performance, but if you want something featureful and reliable, you're probably better off in something else - including but not limited to python, optionally with psyco. I wish the pypy people would package up their stuff into a form that you can just ./configure && make && make install and then #! to - I believe it'd grow/mature faster than it is if they did (and they may have, but last time I looked it didn't appear so). But once they do, that might be a convenient way of getting better performance. From aljosa.mohorovic at gmail.com Thu Jul 31 09:36:08 2008 From: aljosa.mohorovic at gmail.com (Aljosa Mohorovic) Date: Thu, 31 Jul 2008 06:36:08 -0700 (PDT) Subject: current week / weeks in year - best practice Message-ID: i use this to find out current week and total number of weeks for current year: now = datetime.now() weeks_in_year = int(date(now.year, 12, 31).strftime("%W")) current_week = int(date(now.year, now.month, now.day).strftime("%W")) is this the best way or is there a better way? Aljosa Mohorovic From hyoogle at gmail.com Fri Jul 11 20:34:02 2008 From: hyoogle at gmail.com (Hugh M) Date: Fri, 11 Jul 2008 20:34:02 -0400 Subject: palindrome function In-Reply-To: References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: > Basically, it reverses the list in place, so it modifies the list which > called it. It does not return a /new/ list which is a reversed version of > the original, as you expected it to. Since it doesn't return anything > explicitly, Python makes it return None. Hence, the comparison you are doing > is between the original list and a None, which is False, naturally. > Try this: > > spam = ['a', 'n', 'n', 'a'] > eggs = spam[:] > if spam.reverse() == eggs: > print "Palindrome" > > Um, wouldn't this suffer the same problem- spam.reverse() would return None, so None==eggs test would return false? I think you meant to say: spam = ['a', 'n', 'n', 'a'] eggs = spam[:] spam.reverse() if spam == eggs: print "Palindrome" -Hugh > -- > Denis Kasak > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jkrukoff at ltgc.com Wed Jul 30 16:50:04 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Wed, 30 Jul 2008 14:50:04 -0600 Subject: seemingly simple list indexing problem In-Reply-To: References: <5c118411-5703-44b3-888f-3785b517b8d4@u12g2000prd.googlegroups.com> <46b0becc-2f24-41de-a9e5-3013c6089d24@8g2000hse.googlegroups.com> Message-ID: <1217451004.4123.160.camel@jmk> On Wed, 2008-07-30 at 12:06 -0700, Tobiah wrote: > On Mon, 28 Jul 2008 23:41:51 -0700, iu2 wrote: > > > On Jul 29, 3:59 am, John Machin wrote: > >> On Jul 29, 8:10 am, John Krukoff wrote: > >> > >> > >> > >> > >> > >> > On Mon, 2008-07-28 at 16:24 -0500, Ervan Ensis wrote: > >> > > My programming skills are pretty rusty and I'm just learning Python so > >> > > this problem is giving me trouble. > >> > >> > > I have a list like [108, 58, 68]. I want to return the sorted indices > >> > > of these items in the same order as the original list. So I should > >> > > return [2, 0, 1] > >> > >> > > For a list that's already in order, I'll just return the indices, i.e. > >> > > [56, 66, 76] should return [0, 1, 2] > >> > >> > > Any help would be appreciated. > >> > >> > > -- > >> > >http://mail.python.org/mailman/listinfo/python-list > >> > >> > If your lists aren't so large that memory is an issue, this might be a > >> > good place for a variation of decorate, sort, undecorate. > >> > >> > >>> listToSort = [ 108, 58, 68 ] > >> > >>> decorated = [ ( data, index ) for index, data in > >> > >> > enumerate( listToSort ) ]>>> decorated > >> > >> > [(108, 0), (58, 1), (68, 2)]>>> result = [ None, ] * len( listToSort ) > >> > >>> for sortedIndex, ( ignoredValue, originalIndex ) in > >> > >> > enumerate( sorted( decorated ) ): > >> > ... result[ originalIndex ] = sortedIndex > >> > ...>>> result > >> > >> > [2, 0, 1] > >> > >> Simpliciter: > >> > >> > >> > >> >>> data = [99, 88, 77, 88, 66] > >> >>> [x[1] for x in sorted(zip(data, xrange(len(data))))] > >> [4, 2, 1, 3, 0] > >> > >> Use case? Think data == database table, result == index ...- Hide quoted text - > >> > >> - Show quoted text - > > > > I think it is wrong, using this on my data returns the wrong result > > data = [108, 58, 68, 108] > >>>> [x[1] for x in sorted(zip(data, xrange(len(data))))] > > [1, 2, 0, 3] > > It looked wrong to me at first, but I think this is correct. > The two largest numbers were at positions 0 and 3. They come > last in the result. 58 is the smallest, and was at position > 1, which is the first in the result. > > > > ** Posted from http://www.teranews.com ** > -- > http://mail.python.org/mailman/listinfo/python-list It's wrong for the OP's sample, at least: >>> data = [ 108, 58, 68 ] >>> [x[1] for x in sorted(zip(data, xrange(len(data))))] [1, 2, 0] Which should be [2, 0, 1], according to the OP. I don't think the problem description makes it clear until you stare at the example a bit, but he's asking for a list where each value is the index in the sorted list of the value in that position in the original list. What you've got here is the index in the original list of the value that would be in that location when sorted. Clear as mud? Stealing the quite clever __getitem__ as indirect key idea, this is as short a solution as I've got: >>> listToSort = [ 108, 58, 68 ] >>> result = [ None, ] * len( listToSort ) >>> for sortedIndex, originalIndex in enumerate( sorted( range( len( listToSort ) ), key = listToSort.__getitem__ ) ): ... result[ originalIndex ] = sortedIndex ... >>> result [2, 0, 1] I haven't benchmarked, but I bet it'd be better overall to do the range sort in place, instead of with sorted. I'd like to be able to get rid of the intermediate result initialization, but I haven't found a method that's sane. This'd be my entry for obfuscated one-liner, though :) >>> listToSort = [ 108, 58, 68 ] >>> import operator >>> map( operator.itemgetter( 1 ), sorted( dict( ( originalIndex, sortedIndex ) for sortedIndex, originalIndex in enumerate( sorted( xrange( len( listToSort ) ), key = listToSort.__getitem__ ) ) ).items( ) ) ) [2, 0, 1] -- John Krukoff Land Title Guarantee Company From drakonik at gmail.com Thu Jul 10 11:04:00 2008 From: drakonik at gmail.com (Nick Dumas) Date: Thu, 10 Jul 2008 11:04:00 -0400 Subject: Smal question In-Reply-To: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> References: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 This is easy. Simply create a .py file containing all the methods you want to share. Put this file in the same directory as the rest of your project files. In each of your project files that requires one of the methods, simply "import ". Python supports impromptu module creation, which is great just for circumstances like this. Hans M?ller wrote: > Hello group, > > I have some scripts sharing some common functions. > So what I'd like to have is a modern include. > Of course python does not have (with good reasons) no include statement. > But I'm too lazy to create a module which has to be installed into the > interpreter for some functions I need to share in a project. > Is there any idea to do this ? > > Thanks a lot > > Hans -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkh2JOAACgkQLMI5fndAv9gZiACeP3puvMknR2HQTOXKaNeBtC+h tyEAn3C6g9E5U5xXE4SQ7u368xdvkRx4 =J6Sv -----END PGP SIGNATURE----- From david.lyon at preisshare.net Tue Jul 15 07:37:40 2008 From: david.lyon at preisshare.net (David Lyon) Date: Tue, 15 Jul 2008 21:37:40 +1000 Subject: Using McMillan Installer, PyInstall or py2exe cross-platform? In-Reply-To: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> References: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <487C8C04.2030307@preisshare.net> Hi Hartmut, I can sympathise with you on this one... There are a few options... there is a python based "bake" make like program... that is useful... http://projects.bertram-scharpf.de/bake/bake1.html then there is Wine... that is a windows emulator under linux... that might be pretty easy.... http://www.winehq.org/ If you want to get more heavy-weight, then get a virtual machine. But as per your question... the above specified options might satisfy your requests for speed and ease of use without having to change O/S. Regards David Hartmut Goebel wrote: > Hi, > > has anybody used McMillan Installer, PyInstall or py2exe cross-platform? > > I have a Windows partition with Python installed there, so this would > "only" required working on a different directory and for a different OS. > Since I'm working on Linux, it's awful to boot Windows each time I > want to build a new release. > > Any hint in this area? > From maric at aristote.info Wed Jul 9 08:47:33 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 9 Jul 2008 14:47:33 +0200 Subject: (silly?) speed comparisons In-Reply-To: References: <84bdef3c0807081516g7872d1d8x2ecb448fd1fa900c@mail.gmail.com> Message-ID: <200807091447.34094.maric@aristote.info> Le Wednesday 09 July 2008 12:35:10 mk, vous avez ?crit?: > vector move_slice(vector& vec, int start, int stop, int > dest) I guess the point is to make a vector of referene to string if you don't want to copy string objects all around but just a word for an address each time. The signature should be : vector move_slice(vector& vec, int start, int stop, int dest) or vector move_slice(vector& vec, int start, int stop, int dest) -- _____________ Maric Michaud From circularfunc at yahoo.se Thu Jul 3 05:28:54 2008 From: circularfunc at yahoo.se (defn noob) Date: Thu, 3 Jul 2008 02:28:54 -0700 (PDT) Subject: PIL(Py Image lib), show() not showing picture... Message-ID: <84a8f15a-594f-4e02-aa89-b70932eae420@59g2000hsb.googlegroups.com> from PIL import Image import os print os.path.exists('C:/Users/saftarn/Desktop/images/blob.jpg') im2 = Image.open('C:/Users/saftarn/Desktop/images/blob.jpg') im2.show() first the command prompt pops up then the normal window to display pictures but it doenst show a picture. the prin os.path.exists returns true and opening the file by clicking on it works. ive also tried gif-files with no success. From bruno.desthuilliers at gmail.com Thu Jul 3 14:06:56 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 3 Jul 2008 11:06:56 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: <6d4bfmFp3aoU1@mid.uni-berlin.de> <0f6f795d-8041-463e-8e98-9d830ca3fc5b@l42g2000hsc.googlegroups.com> Message-ID: <45111722-3f2c-476d-8e7b-fd65cc5100a6@56g2000hsm.googlegroups.com> On 3 juil, 18:51, defn noob wrote: > well the reason i unzipped and placed it in site-packages was because > nothign happened when i ran setup.py(unzipped). What do you mean, "running setup.py unzipped" ??? The correct way to install a package is to: - unzip (untar, whatever) the archive somewhere in your own directory - cd to the unzipped directory - *from there*, run python setup.py install From bdesth.quelquechose at free.quelquepart.fr Sun Jul 27 14:25:57 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Jul 2008 20:25:57 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <488cd9ac$0$14746$426a74cc@news.free.fr> Marcus.CM a ?crit : > Well after reading some of these posts on "sacred python cow" on the > "self" , i would generally feel that most programmers > who started with C++/Java would find it odd. And its true, i agree > completely there should not be a need to put "self" into every single > member function. "member function" is C++. The way Python works is that you defines functions (inside or outside a class, that doesn't matter) that, when set as *class* attributes, are used as the *implementation* of the corresponding method. I think it's very important to use appropriate terms to understand what's really going on here. As soon as you understand that what you "def"ine is a *not* a method, but a *function* (eventually) used as the *implementation* of a method, the necessary declaration of the target object (instance or class) in the function's signature just makes sense - the usual way to make some object accessible to the body of a function is to pass this object as argument, isn't it ? (snip) > What could be done instead is :- > > 1. python should hardcode the keyword "self". So whenever this keyword > is used, it would automatically implied that it is > referring to a class scope variable. Usually, 'self' is used for *instance* attributes, you know. "class attribute" are attributes of the class object itself (that is, shared by all instances of the class). > This would be similar to how the > "this" keyword is used in C++. > > 2. Omit self from the parameter. Now how would it work for functions defined outside a class statement, but used as the implementation of a method ? def toto(self): # dummy exemple code return self class Tata(object): pass Tata.tutu = toto class Titi(object): tutu = toto (snip) From jzakiya at mail.com Sat Jul 19 15:39:28 2008 From: jzakiya at mail.com (jzakiya) Date: Sat, 19 Jul 2008 12:39:28 -0700 (PDT) Subject: Ultimate Prime Sieve -- Sieve Of Zakiya (SoZ) References: <5ebb27cd-e938-4f06-9aad-4ea056b851a9@c65g2000hsa.googlegroups.com> <0acbf903-0d27-411f-8fa5-40e2da21ee95@m36g2000hse.googlegroups.com> Message-ID: On Jun 18, 7:58?pm, George Sakkis wrote: > On Jun 13, 1:12 pm, jzakiya wrote: > > > The paper presents benchmarks with Ruby 1.9.0-1 (YARV). ?I would love > > to see my variousprimegenerators benchmarked with optimized > > implementations in other languages. ?I'm hoping Python gurus will do > > better than I, though the methodology is very very simple, since all I > > do is additions, multiplications, and array reads/writes. > > After playing a little with it, I managed to get a 32-47% improvement > on average for the pure Python version, and a 230-650% improvement > with an extra "import psyco; psyco.full()" (pasted athttp://codepad.org/C2nQ8syr) > The changes are: > > - Replaced range() with xrange() > - Replaced x**2 with x*x > - Replaced (a,b) = (c,d) with a=c; b=d > - Replaced generator expressions with list comprehensions. This was > the big one for letting psyco do its magic. > > I also tried adding type declarations and running it through Cython > but the improvement was much less impressive than Psyco. I'm not a > Pyrex/Cython expert though so I may have missed something obvious. > > George George, I took your code and included more efficient/optimized versions of SoZ versions P3, P5, P7, and P11. I ran the code on my PCLinuxOS, Intel P4, Python 2.4.3 system and noted this. The SoZ code run much faster than the SoA in pure Python. When psyco is used the SoA is significantly faster than the pure Python version. The SoZ versions are faster too, but now they are slower than the SoA. You can download the code from http://www.4shared.com/dir/7467736/97bd7b71/sharing.html It would be interesting to see how this code runs in newer versions of Python (Psyco). FYI, someone else coded P7 in C on a QuadCore Intel 9650 3.67GHz overclocked cpu, using multiple threads, and got it to be faster than the SoA, SoE, Here's some of his results (times in seconds). Case nPrime7x nPrime7x nPrime7x nPrime7x Atkin Zakiya Eratosthenes Zakiya (8 core 2.5ghz) 100 billion 52.58 44.27 50.56 200 b 110.14 92.38 108.99 88.01 300 b 169.81 140.92 167.47 400 b 232.34 190.84 228.08 177.72 500 b 297.44 241.84 291.28 600 b 364.84 293.92 355.27 273.04 700 b 434.33 346.97 420.41 800 b 506.67 400.97 486.72 373.29 900 b 579.58 456.53 555.09 1 trillion 654.03 513.11 624.00 479.22 Jabari From bogus.relic2 at cjb.net Thu Jul 3 14:19:39 2008 From: bogus.relic2 at cjb.net (relic) Date: Thu, 3 Jul 2008 11:19:39 -0700 Subject: Iphone Going 3G! References: <486cab43$1_2@news.tm.net.my> Message-ID: <20fqou.nq0.19.1@news.alt.net> fizzi wrote: > For the Iphone lovers out there, Wrong group. No weirdos here. From fabio.oikawa at gmail.com Mon Jul 28 16:22:17 2008 From: fabio.oikawa at gmail.com (Fabio Oikawa) Date: Mon, 28 Jul 2008 17:22:17 -0300 Subject: xlrd: error open_workbook Message-ID: <47e3464c0807281322l458d2634v3370d7429152ee95@mail.gmail.com> Hello. I am trying to open an .xls (excel) file using xlrd, but an error message occurs when I open the workbook. I can open any other .xls file made by myself (either by MS Excel 2003 SP3 in Windows Vista or by OpenOffice 2.0 in Debian) using the *open_workbook*function: wb = xlrd.open_workbook('myworkbook.xls') but when I try to open a file from one specific site, I get the error message: In [2]: wb = xlrd.open_workbook('balanco.xls') WARNING *** file size (81192) not 512 + multiple of sector size (512) WARNING *** OLE2 inconsistency: SSCS size is 0 but SSAT size is non-zero --------------------------------------------------------------------------- struct.error Traceback (most recent call last) /home/oikawa/DB/ /usr/lib/python2.4/site-packages/xlrd/__init__.py in open_workbook(filename, logfile, verbos ity, pickleable, use_mmap, file_contents, encoding_override, formatting_info) 380 bk.parse_globals() 381 else: --> 382 bk.parse_globals() 383 bk.get_sheets() 384 bk.nsheets = len(bk._sheet_list) /usr/lib/python2.4/site-packages/xlrd/__init__.py in parse_globals(self) 1309 self.handle_name(data) 1310 elif rc == XL_PALETTE: -> 1311 self.handle_palette(data) 1312 elif rc == XL_STYLE: 1313 self.handle_style(data) /usr/lib/python2.4/site-packages/xlrd/formatting.py in handle_palette(book, data) 550 "PALETTE record with %d colours\n", n_colours) 551 fmt = ' 552 colours = unpack(fmt, data) 553 assert book.palette_record == [] # There should be only 1 PALETTE record 554 # a colour will be 0xbbggrr error: unpack str size does not match format I ran the xlrd in both Windows Vista / Python 2.5 and Debian / Python 2.4.4 and got the same problem, so I suppose there is something wrong with the .xls files (which can be downloaded at www.fundamentus.com.br --> "Dados Hist?ricos" menu --> "Balancos em Excel" --> choose any company). However, I need the files in order to create my database system. Actually I want to build all companies' informations in a mySQL database, and the fastest and easiest way I found is to download .xls files, to get the data using xlrd-Python and to add them in the mySQL database. Any sugestions for both questions? Thanks in advance. Best regards, Fabio Oikawa -------------- next part -------------- An HTML attachment was scrubbed... URL: From hobesh at gmail.com Mon Jul 21 14:12:30 2008 From: hobesh at gmail.com (Zach Hobesh) Date: Mon, 21 Jul 2008 11:12:30 -0700 Subject: automating python programs Message-ID: Hi, I'm trying to figure out how to run a python program on a schedule, maybe every half an hour... Is this possible? Thanks! -Zach -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Fri Jul 11 17:13:53 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 11 Jul 2008 23:13:53 +0200 Subject: error with configure (svn 64857) In-Reply-To: <3e473cc60807110343s100b8866k1353b3e8e61049b7@mail.gmail.com> References: <487681e9$0$9745$9b622d9e@news.freenet.de> <48770603$0$9695$9b622d9e@news.freenet.de> <3e473cc60807110343s100b8866k1353b3e8e61049b7@mail.gmail.com> Message-ID: <4877CD11.7030608@v.loewis.de> > If didn't investigate everything but I solved the problem by adding > the "-static-libgcc" option: > > CFLAGS="-w -static-intel -static-libgcc" > > I think one should commit changes so configure can manage this. I don't think that change should be made. I'm almost certain that it is correct. Many people build Python with icc, and never reported any such problem. So there must something be wrong with your icc installation. Regards, Martin From LessPaul at gmail.com Tue Jul 29 13:28:52 2008 From: LessPaul at gmail.com (LessPaul) Date: Tue, 29 Jul 2008 10:28:52 -0700 (PDT) Subject: Newbie Python questions Message-ID: I recently discovered Python and see it as a great language to use for personal projects (and more). I made my living for over a decade as a coder in C, C++, ADA, Fortran, and Assembly before moving to systems engineering. I'm now retired, and would love to code again. I see Python as the perfect language to get a good program working in a short time. My question is in regard to GUI platforms. My primary target would be Windows, but I would also like be able to support Linux and Mac versions if possible. I'm also interested in using a system that also has support for pure C++ applications. As such, and after reading many web pages regarding Python GUIs, I believe I have the candidates narrowed down to pyQT and wxPython. The first question -- how steep is the curve to become proficient with the above GUI packages? If the answer is "not very" then there is no need for the following questions as I can try both on for size to see which I like best. However if it is a sizable investment in time, I'd like to maximize my efforts and choose the one I'll end up using in the end. The biggest hurdle I can see is the cost of the QT licence for commercial software, though apparently it can be acquired for a reasonable price via the BlackAdder package. Does purchasing the BlackAdder also include the needed software support for C++ development? Does the BlackAdder purchase also allow for licence of standard C++ apps? Since there appears to be no commercial licencing fee for wxWidgets/ wxPython, the last question is what do I gain from going QT over wx? I've seen great applications written with both (on my computer I have the wxPython Digsby and the pyQT apps "Mnemosyne" and "Anki". All seem to be solid. From larry.bates at websafe.com` Wed Jul 9 20:42:39 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 09 Jul 2008 19:42:39 -0500 Subject: Determining when a file has finished copying In-Reply-To: References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> Message-ID: keith wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Ethan Furman wrote: >> writeson wrote: >>> Guys, >>> >>> Thanks for your replies, they are helpful. I should have included in >>> my initial question that I don't have as much control over the program >>> that writes (pgm-W) as I'd like. Otherwise, the write to a different >>> filename and then rename solution would work great. There's no way to >>> tell from the os.stat() methods to tell when the file is finished >>> being copied? I ran some test programs, one of which continously >>> copies big files from one directory to another, and another that >>> continously does a glob.glob("*.pdf") on those files and looks at the >>> st_atime and st_mtime parts of the return value of os.stat(filename). >>>> From that experiment it looks like st_atime and st_mtime equal each >>> other until the file has finished being copied. Nothing in the >>> documentation about st_atime or st_mtime leads me to think this is >>> true, it's just my observations about the two test programs I've >>> described. >>> >>> Any thoughts? Thanks! >>> Doug >> The solution my team has used is to monitor the file size. If the file >> has stopped growing for x amount of time (we use 45 seconds) the file is >> done copying. Not elegant, but it works. >> -- >> Ethan > Also I think that matching the md5sums may work. Just set up so that it > checks the copy's md5sum every couple of seconds (or whatever time > interval you want) and matches against the original's. When they match > copying's done. I haven't actually tried this but think it may work. > Any more experienced programmers out there let me know if this is > unworkable please. > K > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (GNU/Linux) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iD8DBQFIdVkX8vmNfzrLpqoRAsJ2AKCp8wMz93Vz8y9K+MDSP33kH/WHngCgl/wM > qTFBfyIEGhu/dNSQzeRrwYQ= > =Xvjq > -----END PGP SIGNATURE----- If the files are large this could consume a lot of CPU and I/O to recalculate the checksum over and over. I would try the "hasn't been modified/accessed/created" in some amount of time first. -Larry From jason-sage at creativetrax.com Sat Jul 26 09:58:43 2008 From: jason-sage at creativetrax.com (jason-sage at creativetrax.com) Date: Sat, 26 Jul 2008 08:58:43 -0500 Subject: clearing all warning module caches in a session Message-ID: <488B2D93.2070800@creativetrax.com> Hi all, I just started using the warnings module in Python 2.5.2. When I trigger a warning using the default warning options, an entry is created in a module-level cache so that the warning is ignored in the future. However, I don't see an easy way to clear or invalidate these module-level caches of previously triggered warnings. That means that if I ever have a warning triggered with a "once" or a default warning level or filter, I can never see that warning again until I restart python (or figure out what module contains the cache and delete it manually). I thought resetwarnings would invalidate the module-level caches, so that I could trigger a "once" warning, then do resetwarnings() and make the default an "always" action and see my warning displayed again. At least, the name seems to indicate that all *warnings* would be reset, not just the filter list. But apparently resetwarnings() just clears the filter list, which is helpful, but doesn't do anything for the already-cached warnings. A very small change in the code would make this possible. Instead of making the value of the warnings module-level cache just "1", make it an integer which is incremented each time resetwarnings() is called. That way calling resetwarnings() can invalidate the cache (i.e., the warnings processing would ignore the cache record if the value wasn't the current integer). Again, the question is: is there an easy way to invalidate all the module-level caches of warnings so that the entire warning system is truly reset? Thanks, Jason From dan at catfolks.net Wed Jul 9 17:12:12 2008 From: dan at catfolks.net (Daniel Mahoney) Date: Wed, 09 Jul 2008 16:12:12 -0500 Subject: Determining when a file has finished copying References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> Message-ID: > Thanks for your replies, they are helpful. I should have included in > my initial question that I don't have as much control over the program > that writes (pgm-W) as I'd like. Otherwise, the write to a different > filename and then rename solution would work great. There's no way to > tell from the os.stat() methods to tell when the file is finished > being copied? I ran some test programs, one of which continously > copies big files from one directory to another, and another that > continously does a glob.glob("*.pdf") on those files and looks at the > st_atime and st_mtime parts of the return value of os.stat(filename). > From that experiment it looks like st_atime and st_mtime equal each > other until the file has finished being copied. Nothing in the > documentation about st_atime or st_mtime leads me to think this is > true, it's just my observations about the two test programs I've > described. > > Any thoughts? Thanks! > Doug Could you maybe us the os module to call out to lsof to see if anyone still has the target file open? I am assuming that when the write process finishes writing it would close the file. Check "man lsof" From Murphy.MarkS at epamail.epa.gov Tue Jul 22 10:23:36 2008 From: Murphy.MarkS at epamail.epa.gov (Murphy.MarkS at epamail.epa.gov) Date: Tue, 22 Jul 2008 10:23:36 -0400 Subject: Question about admin rights and IDLE Message-ID: Hi All, Apologies in advance for a potentially redundant posting -- I sent a similar question to the help box yesterday. I have a Geographic Info System (GIS) user that is having problems editing with Python IDLE on a WindowsXP machine unless she has admin rights. I had initially thought there might be a place where you can change the 'user rights' settings in Python, but wasn't able to find it. So, I did a fresh install of Python 2.5.1 and told it to be available to all users during the install process. The problem is that IDLE still seems to be available only to the person who has admin rights on a given machine. Can anybody make sense of this and help me fix it? Thanks in advance! Mark Mark S. Murphy GIS/Remote Sensing Analyst Computer Sciences Corporation ITS-EPA Contract 79 T.W. Alexander Drive Bldg. 4201Rm 3259 Research Triangle Park, NC 27709 Work 919-767-7088 FAX 919-767-7082 Cell 951-252-4325 Murphy.Marks at epa.gov From fkaanonymity at mail.com Thu Jul 3 14:06:18 2008 From: fkaanonymity at mail.com (Dave) Date: Thu, 3 Jul 2008 11:06:18 -0700 (PDT) Subject: imap4_SSL from behind a proxy server Message-ID: First to admit I'm a newbie at Python, IMAP, or SSL. And it's been a long time since I've posted anything to a Usenet group. But I've spent countless hours spinning my wheels on this one, so I thought I'd ask for help. I'm trying write some Python code to connect to Gmail from work, where I need to direct all non-HTTP traffic through a proxy server. Can anyone provide syntax which would redirect the imap4_SSL method through a proxy server:port? I suspect there are some environment variables which, when set, will do this very easily and elegantly. I also suspect there is a really complicated way to 'wrap' the imap classes so as to force requests to go through a proxy which, as a newbie, I am trying to avoid. FYI, I'm currently running Python 2.5.2. via IDLE on Windows XP. But when this project is done, I will move it to Linux. Thanks for any help. Dave fkaprince, at Gmail, dot-com From gherron at islandtraining.com Thu Jul 17 12:33:32 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 17 Jul 2008 09:33:32 -0700 Subject: unpacking with default values In-Reply-To: <335e7a21-e35e-41ee-9f92-fd4c2f6bf166@f36g2000hsa.googlegroups.com> References: <335e7a21-e35e-41ee-9f92-fd4c2f6bf166@f36g2000hsa.googlegroups.com> Message-ID: <487F745C.5080605@islandtraining.com> McA wrote: > Hi all, > > probably a dumb question, but I didn't find something elegant for my > problem so far. > In perl you can unpack the element of a list to variables similar as > in python > (a, b, c = [0, 1, 2]), but the number of variables need not to fit the > number > of list elements. > That means, if you have less list elements variables are filled with > 'undef' (None in python), if you have more list elements as necessary > the rest is ignored. > > How can I achieve this behaviour with python in an elegant and fast > way? > > Best regards > Andreas Mock > -- > http://mail.python.org/mailman/listinfo/python-list > Python 3.0 has something a bit like this. Excess values can be bound (as a list) to the last variable: a,b,*c = [1,2,3,4,5] will result in c containing [3,4,5]. In Python 2.x, you can't do that directly, but you should be able to create a function that lengthens or shortens an input tuple of arguments to the correct length so you can do: a,c,b = fix(1,2) d,e,f = fix(1,2,3,4) However, the function won't know the length of the left hand side sequence, so it will have to be passed in as an extra parameter or hard coded. Gary Herron From sturlamolden at yahoo.no Tue Jul 8 16:09:36 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 8 Jul 2008 13:09:36 -0700 (PDT) Subject: GUI Programming by hand not code with Python Code References: <7003b665-3227-47a7-ab06-1a486f87939a@a1g2000hsb.googlegroups.com> Message-ID: On 7 Jul, 04:33, jayjaygi... at hotmail.co.uk wrote: > Is their a program that lets you design a GUI by hand (like gambas) > not by code (like wxpython) but the commands are in python? > > A program similar to gambas or vb > > Gambas with python code instead of gambas code would be perfect. > > Thanks in advance I use wxFormBuilder with wxPython. Works like a charm. Design the GUI graphically, export it like a wx XML resource (.xrc). All you nedd to code in Python is the event handlers and the code to bind/hook the events. http://sturlamolden.blogspot.com/2008/03/howto-using-wxformbuilder-with-wxpython.html If you can accept a Windows only solution, you can use Microsoft's IronPython with MS VisualStudio. It will be just like using VB, except you are coding in Python. But remember that extension libraries to CPython is generally not available for IronPython. Insted you must rely more on .NET and COM/ActiveX objects. From ajdamico at gmail.com Wed Jul 23 17:28:10 2008 From: ajdamico at gmail.com (Anthony) Date: Wed, 23 Jul 2008 14:28:10 -0700 (PDT) Subject: Autocompletion and Interactive Tables in a Python IDE Message-ID: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Hi, I'm a FoxPro programmer, but I want to learn python before it's too late. I do a lot of statistical programming, so I import SPSS into python. In my opinion, the best features of Visual FoxPro 9.0 were: a) Intellisense (tells you what classes/methods are available and what variables go into a function) b) Code Completion (guesses your code after four letters) c) Data-Orientation; multiple data sessions can be open, data can be viewed easily Python's IDLE has only half of the first of these features. I did a lot of searching and found the PyDev extensions for Eclipse's Python IDE, and found that they've got Intellisense. I'm still missing b and c, and am getting extremely frustrated programming so slowly.. So two questions: Is there any package, gui, IDE, anything that will do FoxPro-style code completion? If it works in Eclipse, even better.. I can't find a good screenshot, but here's a better description: You type "BROW" and it pops up a window that says "BROWSE" ..at this point if you hit enter it completes the word.. and How can I view open SPSS data in one of the Python GUIs? Again, Eclipse would be the preference. Here's an example of how I'd like to browse the data: http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=vfptoolkit_figure02.tif I don't want to have to switch back and forth between Python and SPSS while I'm programming; I just want to stay in one of them.. What can I do? I feel extremely inefficient when I don't have these three features.. Thanks in advance. From mal at egenix.com Sat Jul 26 14:30:06 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Sat, 26 Jul 2008 20:30:06 +0200 Subject: Gracefull application exit. In-Reply-To: <00ba01c8eda7$2e61ecb0$8b25c610$@rawlins@thinkbluemedia.co.uk> References: <00ba01c8eda7$2e61ecb0$8b25c610$@rawlins@thinkbluemedia.co.uk> Message-ID: <488B6D2E.2040403@egenix.com> On 2008-07-24 18:06, Robert Rawlins wrote: > Chaps, > > > > I'm looking to implement an exit/termination process for an application > which can be triggered by A) a keyboard interrupt or B) termination of the > application as a Daemon using a signal. > > > > I have a whole bunch of tasks I want to perform as a cleanup before the > application is terminated, cleaning files, database calls, closing open > connections and a few other things. > > > > I know we have: > > > > # I'm the main application started method. > > if __name__ == "__main__": > > > > For starting an application, but do we have an equivalent methods for when > an application is terminated which we can use to close down any current > internal processes before the application exits? > > > > I'd really love to have your thoughts and experience on gracefully killing > an application. Warp your whole application into a main() function and then use: try: main() finally: cleanup() -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 25 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From circularfunc at yahoo.se Wed Jul 2 12:34:16 2008 From: circularfunc at yahoo.se (defn noob) Date: Wed, 2 Jul 2008 09:34:16 -0700 (PDT) Subject: Most efficient way to get pixelcolors of an image? Message-ID: <2c4e285c-f355-4e09-bd67-6de5656dc6c9@m36g2000hse.googlegroups.com> i want to process a large number of images and store their respective pixels in a matrix. what is the mostt efficient way of opening and checking them? i doubt pygame is made for this purpose :) i guess i could also use tkinter? and why cant i print out matrix after getting the pixels? do i have to deinit() pygame somehow? import pygame import sys import os print os.path.exists('C:/users/saftarn/desktop/images/bloba.bmp') pygame.init() screen = pygame.display.set_mode((800, 600)) image = pygame.image.load('C:/users/saftarn/desktop/images/bloba.bmp') imrect = image.get_rect() imrect = imrect.move(200, 200) matrix = [] while 1: pygame.display.flip() screen.fill((255,255,255)) screen.blit(image, imrect) pygame.event.wait() event = pygame.event.wait() for x in range(1, 301): for y in range(1, 301): matrix.append(screen.get_at((x, y))) #print matrix if event.type == pygame.QUIT: #print matrix sys.exit() From aahz at pythoncraft.com Thu Jul 10 18:31:41 2008 From: aahz at pythoncraft.com (Aahz) Date: 10 Jul 2008 15:31:41 -0700 Subject: Smal question References: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> Message-ID: [contextectomy] If we answer a small question, are we making smalltalk? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From tjreedy at udel.edu Tue Jul 8 14:52:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 08 Jul 2008 14:52:52 -0400 Subject: "in"consistency? In-Reply-To: References: Message-ID: David C. Ullrich wrote: > In article , > Terry Reedy wrote: >>> Is there a reason for the inconsistency? I would >>> have thought "in" would check for elements of a >>> sequence, regardless of what sort of sequence it was... >> It is not an inconsistency but an extension corresponding to the >> limitation of what an string element can be. > > It's an inconsistency. That doesn't mean it's a bad thing or that > I want my money back. It may well be a reasonable inconsistency - > strings _can_ work that way while it's clear lists had better not. > But it's an inconsistency. To decisively argue 'inconsistency' as factual or not, versus us having divergent opinions, you would have to supply a technical definition ;-) The math definition of 'leading to a contradiction' in the sense of being able to prove False is True, does not seem to apply here. However, a) In common English, 'in' and 'contains', applied to strings of characters (text), is understood as applying to substrings that appear in the text. This is also true of many other programming languages. 'Dictionary' contains 'diction'. This is even the basis of various word games. b) Python otherwise allows operators to vary in meaning for different classes. In any case, back to your original question: the extension of meaning, 'inconsistent' or not, was deliberated and adopted on the basis that the usefulness of the extension would outweigh the confusion wrought by the class-specific nature of the extension. (In other words, threads such as this *were* anticipated ;-) Terry Jan Reedy From M8R-yfto6h at mailinator.com Tue Jul 15 03:03:51 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Tue, 15 Jul 2008 00:03:51 -0700 Subject: Unicode confusion References: <1216053600.3028.59.camel@localhost.localdomain> Message-ID: "Jerry Hill" wrote in message news:mailman.14.1216054283.922.python-list at python.org... > On Mon, Jul 14, 2008 at 12:40 PM, Tim Cook > wrote: >> if I say units=unicode("?"). I get >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: >> ordinal not in range(128) >> >> If I try x=unicode.decode(x,'utf-8'). I get >> TypeError: descriptor 'decode' requires a 'unicode' object but received >> a 'str' >> >> What is the correct way to interpret these symbols that come to me as a >> string? > > Part of it depends on where you're getting them from. If they are in > your source code, just define them like this: > >>>> units = u"?" >>>> print units > ? >>>> print repr(units) > u'\xb0' > > If they're coming from an external source, you have to know the > encoding they're being sent in. Then you can decode them into > unicode, like this: > >>>> units = "?" >>>> unicode_units = units.decode('Latin-1') >>>> print repr(unicode_units) > u'\xb0' >>>> print unicode_units > ? > > -- > Jerry > Even with source code you have to know the encoding. for pre-3.x, Python defaults to ascii encoding for source files: test.py contains: units = u"?" >>> import test Traceback (most recent call last): File "", line 1, in File "test.py", line 1 SyntaxError: Non-ASCII character '\xb0' in file test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details The encoding of the source file can be declared: # coding: latin-1 units = u"?" >>> import test >>> test.units u'\xb0' >>> print test.units ? Make sure to use the correct encoding! Here the file was saved in latin-1, but declared utf8: # coding: utf8 units = u"?" >>> import test Traceback (most recent call last): File "", line 1, in UnicodeDecodeError: 'utf8' codec can't decode byte 0xb0 in position 0: unexpected code byte >>> -- Mark From saluk64007 at gmail.com Wed Jul 30 15:48:14 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Wed, 30 Jul 2008 12:48:14 -0700 Subject: Reasoning behind 'self' parameter in classes? In-Reply-To: <496954360807301227h1dea050eg735314beb0b5ff16@mail.gmail.com> References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> <4890ACE4.4060703@acm.org> <496954360807301227h1dea050eg735314beb0b5ff16@mail.gmail.com> Message-ID: On Wed, Jul 30, 2008 at 12:27 PM, Robert Dailey wrote: > > Given the code samples above, is there any technical reason why this cannot > be done? Thanks for the input guys, and thanks more over for keeping this > easy-going. > > -- > http://mail.python.org/mailman/listinfo/python-list > Well, the linked thread gives many reasons, but as mentioned it is a flamewar thread. Philosophically python is not an "object oriented" language per say, it has an object system, a not bolted on one I might add, but it doesn't force developers to use that methodology. You can be functional or procedural if you'd rather. Following this philosophy, when methods were designed, they were merely functions that got passed an instance as the first argument. The parser followed this design choice. As far as I understand it, the underlying method object is not different from a function argument, thus it cannot have any magic arguments built in. The only magic involved is the fact that the object, when calling a method, will pass its instance as the first argument. I don't believe there is any chance of this changing in python 3, python 4 is anyone's guess... This does allow some good things that come for free, like adding methods later, or changing functions into methods or methods into functions. If you start out developing a class, but feel a class is too bulky, you can delete the "class" line, dedent the methods, and have a set of functions instead for free. Or, if you have functions that are set up to take instances as their first argument already, you can bundle them up into a class very easily. If by "hack" you mean using features already available in the language to accomplish things, that kind of is what it is, and that's kind of what python is about. New syntax for a new feature is uncommon, but it happens. New syntax that breaks old code is very uncommon, and is only now coming out in python 3. And the biggest change in python 3 is to eliminate added syntax, such as print being a statement, and make the code reuse more python features rather than have every feature exist as an island. Print being a function, for instance, lets you use the same syntax for it that you use for other functions, making everything clearer and more unified. A common thing programmers might do when upgrading their code is to turn print statements into better logging functions - if print was a function in the first place this would be an easier task. Eliminating self doesn't accomplish much, and changes of this nature just don't get done without a good reason. It takes away something that might be annoying, but doesn't add anything. The benefits of changing have to be significant for a code change to break the existing syntax. Many people are upset even about some of the changes in python 3, that the benefits don't outweight the cost of change, and most of those changes are less damaging than playing around with the self businss would be :) So no, self not a mysterious thing that we should never question. Self is an understood thing that has been questioned very often (weekly, monthly) for many many years - there are not enough good reasons to bother with changing it, and there enough good reasons for it that it's best to keep it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kris at FreeBSD.org Wed Jul 9 08:06:33 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Wed, 09 Jul 2008 14:06:33 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <750f823a-f9de-4f81-9eb3-7c7b39237c90@y38g2000hsy.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <750f823a-f9de-4f81-9eb3-7c7b39237c90@y38g2000hsy.googlegroups.com> Message-ID: <4874A9C9.7020804@FreeBSD.org> John Machin wrote: >> Hmm, unfortunately it's still orders of magnitude slower than grep in my >> own application that involves matching lots of strings and regexps >> against large files (I killed it after 400 seconds, compared to 1.5 for >> grep), and that's leaving aside the much longer compilation time (over a >> minute). If the matching was fast then I could possibly pickle the >> lexer though (but it's not). >> > > Can you give us some examples of the kinds of patterns that you are > using in practice and are slow using Python re? Trivial stuff like: (Str('error in pkg_delete'), ('mtree', 'mtree')), (Str('filesystem was touched prior to .make install'), ('mtree', 'mtree')), (Str('list of extra files and directories'), ('mtree', 'mtree')), (Str('list of files present before this port was installed'), ('mtree', 'mtree')), (Str('list of filesystem changes from before and after'), ('mtree', 'mtree')), (re('Configuration .* not supported'), ('arch', 'arch')), (re('(configure: error:|Script.*configure.*failed unexpectedly|script.*failed: here are the contents of)'), ('configure_error', 'configure')), ... There are about 150 of them and I want to find which is the first match in a text file that ranges from a few KB up to 512MB in size. > How large is "large"? > What kind of text? It's compiler/build output. > Instead of grep, you might like to try nrgrep ... google("nrgrep > Navarro Raffinot"): PDF paper about it on Citeseer (if it's up), > postscript paper and C source findable from Gonzalo Navarro's home- > page. Thanks, looks interesting but I don't think it is the best fit here. I would like to avoid spawning hundreds of processes to process each file (since I have tens of thousands of them to process). Kris From JordanNealBerg at gmail.com Tue Jul 22 12:39:42 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Tue, 22 Jul 2008 09:39:42 -0700 (PDT) Subject: Question about inheritence References: Message-ID: <4400226c-f077-46d9-9310-a8d1d7f4dfda@w7g2000hsa.googlegroups.com> On Jul 22, 12:26?pm, Catherine Heathcote wrote: > If I create a new class inherited from another with a constructor, what > happens with the new class's constructer? > Thanks for your time. Well, the __init__ method of the subclass is called, and from within it you can call the superclass constructor. Here is a sample code: class A(): def __init__(self, bla): #do some stuff here class B(A): def __init__(self, bla2): #do some stuff here A.__init__(self,bla) From castironpi at gmail.com Fri Jul 18 02:31:07 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 17 Jul 2008 23:31:07 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> Message-ID: On Jul 17, 11:39?pm, Kay Schluehr wrote: > On 18 Jul., 01:15, castironpi wrote: > > > > > On Jul 17, 5:37 pm, I V wrote: > > > > On Thu, 17 Jul 2008 15:08:17 -0700, castironpi wrote: > > > > The Python disassembly is baffling though. > > > > >>>> y= 3 > > > >>>> dis.dis('x=y+1') > > > > You can't disassemble strings of python source (well, you can, but, as > > > you've seen, the results are not meaningful). You need to compile the > > > source first: > > > > >>> code = compile('y=x+1','-', 'single') > > > >>> dis.dis(code) > > > > ? 1 ? ? ? ? ? 0 LOAD_NAME ? ? ? ? ? ? ? ?0 (x) > > > ? ? ? ? ? ? ? 3 LOAD_CONST ? ? ? ? ? ? ? 0 (1) > > > ? ? ? ? ? ? ? 6 BINARY_ADD > > > ? ? ? ? ? ? ? 7 STORE_NAME ? ? ? ? ? ? ? 1 (y) > > > ? ? ? ? ? ? ?10 LOAD_CONST ? ? ? ? ? ? ? 1 (None) > > > ? ? ? ? ? ? ?13 RETURN_VALUE > > > > You may well find these byte codes more meaningful. Note that there is a > > > list of opcodes athttp://docs.python.org/lib/bytecodes.html > > > Oh. ?How is the stack represented? > > As a pointer to a pointer of PyObject structs. > > > Does it keep track of which stack > > positions (TOS, TOS1, etc.) are in what registers? ?Does stack > > manipulation consume processor cycles? > > Python does not store values in registers. It stores locals in arrays > and accesses them by position ( you can see the positional index in > the disassembly right after the opcode name ) and globals / object > attributes in dicts. > > For more information you might just download the source distribution > and look for src/Python/ceval.c. This file contains the main > interpreter loop. Oh. I was interpreting, no pun, that the column of numbers to the left indicated how many processor cycles were consumed in each operation. It doesn't quite make sense, unless BINARY_ADD can refer to memory outside of the registers, which I doubt on the basis that two addresses would have to fit into a single operation, plus the architecture opcode. Given that, what does that column indicate? I'm intimidated by the source but I may look. From mensanator at aol.com Thu Jul 3 17:49:40 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 3 Jul 2008 14:49:40 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> Message-ID: <7db52b03-7a8a-40c4-b3cb-f6dccd273b90@59g2000hsb.googlegroups.com> On Jul 3, 2:52?pm, Terry Reedy wrote: > Mensanator wrote: > > On Jul 3, 2:13?am, Bruno Desthuilliers > 42.desthuilli... at websiteburo.invalid> wrote: > >> Terry Reedy a ?crit : > >>> This has been added to itertools at least for 2.6/3.0 > >> Great ! > > > Well, it will be great at some point in the future > > when Python 2.6/3.0 have actually been released and > > The betas 'have actually been released' and I am happily using 3.0. ? But you're not using it for production work. Unless you're ignoring the recommendations. > The > core features that I care about have mostly been untouched and where > they have, they work. That's not the issue. > > > third party extensions such as gmpy have caught up. > > Not my personal concern. ? Right. Which is why your 3.0 specific advice is worthless. Those ARE personal concerns of just about everyone else. > And certainly not a direct concern for nearly > all uses of itertools.product. > > > Until then, such solutions are worthless, i.e., of no value. > > Why are you so anxious to generalize your personal negative views to > everyone else. ? Not to everyone else, to the new and inexperienced Pyhton users. Maybe you don't remember what it was like being a new user where you need to have such things pointed out to you. And I'm not being negative, just realistic. If I ask a question today, I want an answer I can use tomorrow, not one I can use six months from now. > Worthless to you, worthwhile to me. ? The OP's opinion is the only one that matters. What do you suppose is the percentage of posts on this newsgroup by those using 3.0? > And for someone who > does not need cross-products today or in the next few months, > potentially valuable information for when the final releases do arrive, > maybe in September. That's fine for them. It's been said here that they will be a minority for a long time. > > tjr From speedoman11 at yahoo.com Mon Jul 14 18:50:28 2008 From: speedoman11 at yahoo.com (Ty hensons) Date: Mon, 14 Jul 2008 15:50:28 -0700 (PDT) Subject: How can I save command prompt screen Message-ID: <401698.26103.qm@web44903.mail.sp1.yahoo.com> how can i save my command prompt screen? -------------- next part -------------- An HTML attachment was scrubbed... URL: From iainking at gmail.com Fri Jul 25 11:08:57 2008 From: iainking at gmail.com (Iain King) Date: Fri, 25 Jul 2008 08:08:57 -0700 (PDT) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> <4889e5bc$1@news2-rz-ap.ethz.ch> Message-ID: <331bd56e-e446-4b08-bf72-be7482051f32@y22g2000prd.googlegroups.com> On Jul 25, 3:39 pm, Suresh Pillai wrote: > That's a good comparison for the general question I posed. Thanks. > Although I do believe lists are less than ideal here and a different data > structure should be used. > > To be more specific to my case: > As mentioned in my original post, I also have the specific condition that > one does not know which nodes to turn ON until after all the > probabilities are calculated (lets say we take the top m for example). > In this case, the second and third will perform worse as the second one > will require a remove from the list after the fact and the third will > require another loop through the nodes to build the new list. So you need to loops through twice regardless? i.e. loop once to gather data on off nodes, do some calculation to work out what to turn on, then loop again to turn on the relevant nodes? If so, then I think the functions above remain the same, becoming the 2nd loop. Every iteration you do a first loop over the off_nodes (or them all for (1)) to gather the data on them, perform your calculation, and then perform one of the above functions (minus the setup code at the begining; basically starting at the 'for') as a second loop, with the goes_on function now returning a value based on the calculation (rather than the calculation itself as I had it). Performance should be similar. Iain From bruno.desthuilliers at gmail.com Mon Jul 14 12:34:29 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 14 Jul 2008 09:34:29 -0700 (PDT) Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> <6daf86f6-0a96-4811-90c4-2bc6ccbff9fb@x41g2000hsb.googlegroups.com> Message-ID: <2ebe7d8a-acac-488c-80b6-fdc4d7618f21@l42g2000hsc.googlegroups.com> On 14 juil, 11:51, James Fassett wrote: > On Jul 12, 12:18 am, George Sakkis wrote: > > > It relies on positional arguments, tuple unpacking and > > the signature of zip(), > > It moreso relies on the fact that: > > >>> t1 = (0,1,2,3) > >>> t2 = (7,6,5,4) > >>> [t1, t2] == zip(*zip(t1, t2)) > > True > > This is mathematically true given the definition of zip. To me that is > very functional. Basically, unpacking a pair list into zip is the > canonical definition of unzipping the list (which is exactly my > intention). > > > Second, it is less readable, > > For a Python programmer - you are correct. For someone familiar with > the use of zip (as described above) - I wonder. Since I am new to this > I can't say for sure. If I posted the same code to a Haskell list or a > ML list would their opinion be the same? You might find interesting than Python's list comprehensions were stolen from Haskell then !-) > > robust and efficient than the list comprehension. > > I don't know the internals of how the Python interpreter treats list > comprehensions According to a post on the pypy team's blog, mostly as sugar candy for the procedural version (IOW: the generated byte-code will be roughly equivalent). > and zip but it seems reasonable to assume an extra list > is created for the zip approach. > > However, in the limited functional code I have seen this is actually a > common practice. I would suppose in languages with lazy evaluation > this isn't a problem - but in Python it would be. Python has some kind of lazy evaluation too - look for yield, generator expressions, iterators, and the itertools package. From lepto.python at gmail.com Tue Jul 1 03:16:03 2008 From: lepto.python at gmail.com (oyster) Date: Tue, 1 Jul 2008 15:16:03 +0800 Subject: how to judge urllib.Request is finished? Message-ID: <6a4f17690807010016s44ec90c2p2603ec408ff3f025@mail.gmail.com> currently I am using [code] req=urllib2.Request(url) data='' if '' not in data: fd=urllib2.urlopen(req) data=fd.read() time.sleep(10) time.sleep(10) blahblah [/code] Is there any other ready-to-use function? And what if the internet connection is chocked so that the html page can not be loaded entirely? From mail at timgolden.me.uk Mon Jul 21 10:45:39 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 21 Jul 2008 15:45:39 +0100 Subject: ntlm authentication In-Reply-To: <7B3D44209E8C944288889D4132FEC4125B98D8@IMCSRV6.MITRE.ORG> References: <7B3D44209E8C944288889D4132FEC4125B98D8@IMCSRV6.MITRE.ORG> Message-ID: <4884A113.6070305@timgolden.me.uk> Neuberger, Sheldon N. wrote: > Is there any way to make urllib2 handle NTLM authentication? Frankly, I'd hate to try. Have a look at this: http://sourceforge.net/projects/ntlmaps/ in case it helps, either by providing a solution or at least by illustrating some code. In addition, look at the sspi package in the latest pywin32 releases. There some sample code in the demos area there, too. Haven't used it myself (and I know it's messy) but I'm sure someone must have. TJG From diordna at gmail.com Fri Jul 18 18:13:24 2008 From: diordna at gmail.com (Stephen Johnson) Date: Fri, 18 Jul 2008 18:13:24 -0400 Subject: Any Game Developers here? In-Reply-To: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: <4A235BC6-5E46-4402-AF2D-BA3DBC175517@gmail.com> I use the Pyglet library to make games. You want to look at the pyglet and pygame mailing lists, not this one. Use Google. In my opinion, PyGame is clunky and Pyglet is elegant, simple, and comprehensive. PyGame has more examples available, but Pyglet has great documentation and enough examples to answer any questions you might have. Both have active communities. -Steve Johnson On Jul 18, 2008, at 5:38 PM, Michael Lubker wrote: > Any people that use Python as the predominant language for their game > development here? > > ~Michael > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rschroev_nospam_ml at fastmail.fm Sun Jul 27 04:34:18 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 27 Jul 2008 10:34:18 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> References: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> Message-ID: Tim Roberts schreef: > python at bdurham.com wrote: >> For Win64-Itanium users: python-2.5.2.ia64.msi >> For Win64-AMD64 users: python-2.5.2.amd64.msi >> >> 1. It looks like the 64 bit versions of Python for Windows are CPU >> vendor specific, eg. it doesn't look like there's a single, universal >> executable for Windows 64 bit platforms. Is this true? > > It's true for ALL operating systems, not just Windows. The ia64 (Itanium) > and the amd64 are completely separate processors with VERY different > instruction sets. Maybe I'm wrong, but I have the impression that Malcolm is a bit confused about the different 64-bit processors from Intel and AMD. So, to clear things up a bit: - The Itanium (ia64) is a 64-bit processor made by Intel, mostly for use in high-end systems (servers etc.) IIRC. It's instruction set is indeed completely different from the i386 instruction set (though I think there's an emulation mode) - AMD64 (or x86-64 or x64 or EMT64 or Intel64) is a 64-bit instruction set from AMD which is an extension to the i386 instruction set, and runs 32-bit (and 16-bit) i386-code natively. But, and this is important, despite the name the instruction set is also used by Intel (though they call it EMT64 and made a few minor changes). If you have or buy a 64-bit computer, it almost certainly uses the AMD64 instruction set, even if it has an Intel CPU (if you have an Itanium or other 64-bit CPU, I suppose you would know; it would not be something you buy from the shelf in a regular computer store). So you almost certainly need the AMD64 version of Python. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From wtanksleyjr at gmail.com Thu Jul 31 09:54:59 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Thu, 31 Jul 2008 06:54:59 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Message-ID: <4609709f-dc0f-47cc-905e-1552a02ec3b6@r15g2000prd.googlegroups.com> John Machin wrote: > william tanksley wrote: > > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" > > 1. This isn't Unicode; it's missing the u"" (I printed using repr). > > 2. It's got the UTF-8 bytes there in the middle. > > In addition to the above results, > *WHAT* results? I don't see any repr() output, just your > interpretation of what you think you saw! That *is* the repr. I said it's the repr, and it IS. It's not an interpretation; it's a screenscrape. Really, truly. If I paste it in again it'll look the same. What do you want? Can I post something that will convince you it's a repr? Oh well. You guys have been immensely helpful; my mental model of how Python works was vastly backwards, so it's a relief to get it corrected. Thanks to that, I was able to hack my code into working. I wish I could get entirely correct behavior, but at this point the miscommunication is too strong. I'll settle for the hack I've got now, and hope iTunes doesn't ever change its XML encoding (hey, I think I've got cause to be optimistic). -Wm From kay.schluehr at gmx.net Mon Jul 28 13:45:41 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 28 Jul 2008 10:45:41 -0700 (PDT) Subject: ActiveState Code (the new Python Cookbook) has been launched References: Message-ID: On 28 Jul., 18:55, Trent Mick wrote: > Nick Craig-Wood wrote: > > Trent Mick wrote: > >> I happy to announce that ActiveState Code has been taken out of beta. > >> This is the new site replacing the ASPN Cookbooks -- in particular the > >> Python Cookbook. > > >> http://code.activestate.com/ > > > Looks great and much faster than the old site! > > Thanks! > > > Mind telling us how it is implemented? I'm guessing python/django by > > the url and the fact that you have python stuff on your home pages but > > I could be wrong! > > Yup, it is a Django-based site -- a pleasure to work with, that. Using > django-tagging, django-template-utils & universal feedparser (for > hooking in Atom content for News section on home page), django-voting, > python-markdown2 (for rendering comments, discussion/descriptions), > recaptcha-client (for feedback when not logged in), pygments (for syntax > coloring). > > I've just submitted the site tohttp://www.djangosites.org/ > > I hope to do some blog posts about some parts of the site soon and > release the small re-usable "feedback" app I've put together for getting > feedback on the site. > > Cheers, > Trent > > -- > Trent Mick > trentm at activestate.com Hmm... overview is lost on the new site. My 15" notebook does not even display 3 full recipes in a firefox browser window ( with some tabs being opened ). I didn't check out the site on my 12" notebook but I suspect it tends to be close to 1. Otherwise the whole screen is filled with administrative debris which is a pitty. The dialogs seem to be pretty responsive and straightforward though. I used "submit recipe", typed my login data and got the input form immediately - instead of the main page (!) in the old system which was gruesome in this respect. From bignose+hates-spam at benfinney.id.au Tue Jul 15 18:26:01 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jul 2008 08:26:01 +1000 Subject: Python internals References: <008ca729$0$20313$c3e8da3@news.astraweb.com> Message-ID: <87hcaq7pja.fsf@benfinney.id.au> Larry Bates writes: > Names are pointers in Python that point to values in memory. The term "pointer" carries much extra baggage for a programmer thinking of C (as the original poster is). Python names give no access to the "address" of the value, and don't need to be "de-referenced". I've had better success explaining Python names to such people in terms of "references": there is no "address" and no "de-reference" needed. Access the name, and you get its value. On the other hand, I prefer to avoid using either of those concepts, and talk in terms of "name tags" or "sticky notes". Names (and other references, like list elements) attach to the object, and have no other value or purpose. They don't affect the object they're attached to; they are entirely independent of other bindings to the same object; they re-bind to another object with no history of what they were bound to previously. The analogy is quite robust, and carries none of the confusing baggage of "variable" or "pointer" or other overloaded language terms. -- \ ?Are you pondering what I'm pondering?? ?I think so, Brain, but | `\ I don't think Kay Ballard's in the union.? ?_Pinky and The | _o__) Brain_ | Ben Finney From google at mrabarnett.plus.com Sun Jul 20 17:40:06 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 20 Jul 2008 14:40:06 -0700 (PDT) Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> <3db7c643-56ca-4d6e-99eb-16176e1a2e88@d19g2000prm.googlegroups.com> <7b2d0e3b-0ee4-4f1b-90d5-90eae9f258a0@u6g2000prc.googlegroups.com> <3dd3ce99-e75b-4d5c-84dc-7854abd9d0e1@w8g2000prd.googlegroups.com> Message-ID: <0e86b400-b8a1-444f-bb1f-db423ffae71f@59g2000hsb.googlegroups.com> On Jul 19, 6:34?am, Dennis Lee Bieber wrote: > On Fri, 18 Jul 2008 16:43:35 -0700 (PDT), John Machin > declaimed the following in comp.lang.python: > > > > > The only language I remember that had implicit typing was FORTRAN (GOD > > is real, but JESUS is an integer). > > Hadn't seen that one before -- maybe because I learned FORTRAN IV at a > college in the middle of west Michigan; I think half the population was > one step away from turning Amish > > I learned it by the word: Indian -- implicit integers began at I, and > ended with N. > You could've just used the first 2 letters of 'integer'! :-) From lxz3002 at yahoo.com.cn Wed Jul 2 21:40:22 2008 From: lxz3002 at yahoo.com.cn (Leo Lee) Date: Thu, 3 Jul 2008 09:40:22 +0800 Subject: wxPython: How can I get window's HANDLE in wxPython. Message-ID: I need a window's handle to be passed to external c++. Thanks in advance From jonas at codeazur.com.br Thu Jul 3 11:12:17 2008 From: jonas at codeazur.com.br (Jonas Galvez) Date: Thu, 3 Jul 2008 12:12:17 -0300 Subject: ANN: XML builder for Python In-Reply-To: <486CB9F3.3020902@livinglogic.de> References: <486C5CA1.3080105@behnel.de> <486C5D63.5030407@behnel.de> <486CB9F3.3020902@livinglogic.de> Message-ID: <10df03a30807030812g201f35aet87477a245ae71fc4@mail.gmail.com> Walter D?rwald wrote: > XIST has been using with blocks since version 3.0. > [...] > with xsc.Frag() as node: > +xml.XML() > +html.DocTypeXHTML10transitional() > with html.html(): > [...] Sweet! I don't like having to use the unary operator tho, I wanted something as simple as possible, so I wouldn't even have to assign a variable on the with block ("as something"). I plan to add some validation and error checking, but for generating feeds for my Atom store it's reasonably fast and lean (just over 50 lines of code). --Jonas Galvez, http://jonasgalvez.com.br/log From Maria.Gordon at afconsult.com Tue Jul 29 09:31:58 2008 From: Maria.Gordon at afconsult.com (Gordon Maria) Date: Tue, 29 Jul 2008 15:31:58 +0200 Subject: Defunct when using subprocess.Popen References: <6D3D064BBC122445A4577CE1895FA06501755913@afsegbgex1.af.se> Message-ID: <6D3D064BBC122445A4577CE1895FA06501755914@afsegbgex1.af.se> An HTML attachment was scrubbed... URL: From stochashtic at yahoo.ca Fri Jul 25 10:59:18 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 25 Jul 2008 16:59:18 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> Message-ID: <4889ea46$1@news2-rz-ap.ethz.ch> On Fri, 25 Jul 2008 16:51:42 +0200, Fredrik Lundh wrote: > Unless I'm missing something, your example keeps going until it's > flagged *all* nodes as "on", which, obviously, kills performance for the > first version as the probability goes down. The OP's question was about > a single pass (but he did mention "as the simulation progresses", so I > guess it's fair to test a complete simulation.) I was referring to multiple passes as in Iain' test cases. Although not necessarily till all nodes are ON, let's say to to a large proportion at least. From kyosohma at gmail.com Tue Jul 8 10:05:07 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 8 Jul 2008 07:05:07 -0700 (PDT) Subject: How to make python scripts .py executable, not bring up editor References: Message-ID: <1160b521-eebb-4338-a66b-fa79ac7e0019@c65g2000hsa.googlegroups.com> On Jul 7, 4:56?pm, korean_dave wrote: > From command Prompt, i type in a script, ?"tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? You need to add python.exe to your system's path. In Windows XP, you need right-click "My Computer", choose Properties, and then the Advanced tab. Click the Environment Variables button. Then go to the System Variables section and double-click the Path entry (you may have to scroll down to get to it). Notice that everything in this list is separated by semi-colons. You should be at the end of the list, so just put a semi-colon at the end and then type C:\Python24 Then it should work. You'll probably need to restart your command line window though, as it doesn't always take affect on open windows. HTH ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From half.italian at gmail.com Tue Jul 8 15:35:54 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Tue, 8 Jul 2008 12:35:54 -0700 (PDT) Subject: Python for Kids Message-ID: Pretty cool!! Our base will be *much* bigger in about twenty years. I remember doing Basic on my dads Apple IIe. http://wiki.laptop.org/go/Pippy#Summary From grante at visi.com Mon Jul 28 13:18:25 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 28 Jul 2008 12:18:25 -0500 Subject: write unsigned integer 32 bits to socket References: <9_KdnfSDZ9xHIRDVnZ2dnUVZ_gCdnZ2d@pdx.net> Message-ID: On 2008-07-28, Alan Franzoni wrote: > Scott David Daniels was kind enough to say: > >> Alan Franzoni wrote: > >> Please don't pass this misinformation along. >> >> In the struct module document, see the section on the initial character: >> Character Byte order Size and alignment >> @ native native >> = native standard >> < little-endian standard >> > big-endian standard >> ! network (= big-endian) standard > > Sure, that's is one way to do it... but I was answering > Micheal Torrie, who said: > >> htonl() call, and then when pulling it off the wire on the >> other end you'd use ntohl(). If you don't then you will have >> problems when the > > htonl() and ntohl() are available in Python in the socket > module, so: > 1) i was just pointing the OP to the right place where to find > such functions > 2) they work just the same way, hence I can't see why the > "struct" way should be the preferred one while the "socket" > way should be misinformation Yes, the socket module does have ntohX and htonX calls. But they're superfluous, since you still have to call struct.pack/unpack to convert integer objects to/from the byte-strings that are transferred via send() and recv() calls. Changing the initial "=" in the format string to a "!" eliminates the need to pass the integer objects though calls to socket.ntohX() and socket.htonX() -- Grant Edwards grante Yow! Do you have exactly at what I want in a plaid visi.com poindexter bar bat?? From walter at livinglogic.de Thu Jul 3 17:46:39 2008 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Thu, 03 Jul 2008 23:46:39 +0200 Subject: ANN: XML builder for Python In-Reply-To: <486D22CF.3000505@behnel.de> References: <486C5CA1.3080105@behnel.de> <486C5D63.5030407@behnel.de> <486D22CF.3000505@behnel.de> Message-ID: <486D48BF.3050007@livinglogic.de> Stefan Behnel wrote: > Hi, > > Walter D?rwald wrote: >> XIST has been using with blocks since version 3.0. >> >> Take a look at: >> http://www.livinglogic.de/Python/xist/Examples.html >> >> >> from __future__ import with_statement >> >> from ll.xist import xsc >> from ll.xist.ns import html, xml, meta >> >> with xsc.Frag() as node: >> +xml.XML() >> +html.DocTypeXHTML10transitional() >> with html.html(): >> with html.head(): >> +meta.contenttype() >> +html.title("Example page") >> with html.body(): >> +html.h1("Welcome to the example page") >> with html.p(): >> +xsc.Text("This example page has a link to the ") >> +html.a("Python home page", href="http://www.python.org/") >> +xsc.Text(".") >> >> print node.conv().bytes(encoding="us-ascii") > > Interesting. Is the "+" actually required? Are there other operators that make > sense here? I do not see what "~" or "-" could mean. Of course the node constructor could append the node to the currently active element. However there might be cases where you want to do something else with the newly created node, so always appending the node is IMHO the wrong thing. > Are there other operators that make > sense here? I do not see what "~" or "-" could mean. > > Or is it just a technical constraint? You need *one* operator/method that appends a node to the currently active block without opening another new block. This operator should be short to type and should have the right connotations. I find that unary + is perfect for that. > I'm asking because I consider adding such a syntax to lxml as a separate > module. And I'd prefer copying an existing syntax over a (badly) home grown one. "Existing syntax" might be a little exaggeration, I know of no other Python package that uses __pos__ for something similar. (But then again, I know of no other Python package that uses with block for generating XML ;)). Servus, Walter From jadamwilson2 at gmail.com Wed Jul 23 15:37:06 2008 From: jadamwilson2 at gmail.com (jadamwil) Date: Wed, 23 Jul 2008 12:37:06 -0700 (PDT) Subject: fromfile error on windows, not mac References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> Message-ID: I found the problem: I thought it was opening in binary mode on BOTH windows and the mac, but on windows I passed "rb" with double quotes, not 'rb' with single quotes to the open file function. Changing it to 'rb' fixed it. On Jul 23, 8:25?am, Tommy Nordgren wrote: > One question : Did you remember to open the file in binary mode? > This MUST be done on windows. > On 22 jul 2008, at 06.36, jadamwil wrote: > > > > > Hello, > > I am using the numpy fromfile function to read binary data from a file > > on disk. The problem is that the program runs fine on a Mac, but gives > > an error or warning on windows when trying to read the data. I use it > > like this: > > > Signal = zeros((N, 16), dtype=float32) > > for sample in range(0, N): > > ?# this function gets the next position in the file to seek to > > ?s = getFilePos(sample) > > > ?# go to the correct location in the file; this IS checked to make > > sure it is within the file > > ?mFile.seek(s) > > > ?# read the 16 float32 values from the file > > ?D = fromfile(mFile, dtype=numpy.float32, 16) > > > ?# save D in Signal > > ?Signal[sample, :] = D > > > This will fail when sample is ~4. If I change the range to (5,N), > > skipping the "bad" file location, it will run fine for a few samples, > > and then give another error. The message it gives is: > > "16 items requested but only 7 read" > > > So D is a 7x1 vector, and the program dies when it tries to assign D > > to the slice of Signal ("ValueError: shape mismatch: objects cannot be > > broadcast to a single shape"). > > > On windows, the Python version is 2.5.2, and the most recent numpy and > > scipy are being used as well. I tried using Enthought, but it gave > > this error as well, in addition to a c runtime error whenever I > > imported scipy (which is another post topic...). > > > Any ideas on what might be causing this? Is there a way to debug the > > fromfile function? And, remember, this works perfectly on a Mac. Would > > compiling everything (python, scipy, numpy) potentially solve this? > > > Thanks! > > -- > >http://mail.python.org/mailman/listinfo/python-list > > ---------------------------------- > Skinheads are so tired of immigration, that they are going to move to ? > a country that don't accept immigrants! > Tommy Nordgren > tommy.nordg... at comhem.se From fredrik at pythonware.com Wed Jul 16 20:39:32 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 02:39:32 +0200 Subject: Manually prompting garbage collection In-Reply-To: References: <20080716230911.GD22400@monkey.ucolick.org> <20080716235656.GE22400@monkey.ucolick.org> Message-ID: Fredrik Lundh wrote: > Do these objects have direct references to a resource that you're > explicitly destroying from your C code? and yes, if this is the problem, the correct solution is to create an separate object type that's designed to manages the resource and act as a proxy against it, and then let all operations against the resource (from other objects) go via the proxy. never let more than one object "own" an external resource. if you need to explicitly kill the external resource, design the proxy so you can tell it to ignore (or reject) any subsequent calls to the resource from other parts of the program. From gherron at islandtraining.com Fri Jul 18 18:13:56 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 18 Jul 2008 15:13:56 -0700 Subject: Any Game Developers here? In-Reply-To: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: <488115A4.3070201@islandtraining.com> Michael Lubker wrote: > Any people that use Python as the predominant language for their game > development here? > You can find several whole (and reasonably large) communities of Python/Game developers associated with some Open Source projects: These two come to mind immediately. (Both have active new groups.) Pygame: http://www.pygame.org/news.html Pyglet: http://pyglet.org/ Gary Herron > ~Michael > -- > http://mail.python.org/mailman/listinfo/python-list > From circularfunc at gmail.com Mon Jul 21 23:01:35 2008 From: circularfunc at gmail.com (ssecorp) Date: Mon, 21 Jul 2008 20:01:35 -0700 (PDT) Subject: tail-rec decorator, well still blows the stack... Message-ID: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 so I try it and when I run: @Decorators.tail_recursion def fibtr(n): def fibt(a, b, n): if n <= 1: return b else: return fibt(b, a + b, n - 1) if n == 0: return 0 else: return fibt(0, 1, n); it still blows the stack. so what is the point? is it impossible to get "real" tail-recursion in Python? From vinay_sajip at yahoo.co.uk Wed Jul 16 09:38:56 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 16 Jul 2008 06:38:56 -0700 (PDT) Subject: Logging to different addressees References: <8df30038-86c1-4376-b046-a50f2bcf0a2b@s50g2000hsb.googlegroups.com> <7b829a76-ba2c-4cb7-b216-0c9c01e5cd02@f36g2000hsa.googlegroups.com> <4d3df1d9-339b-43b2-9f25-c792e9bf549c@k13g2000hse.googlegroups.com> <4e30c301-294c-4160-8cb8-c924aed00f71@f63g2000hsf.googlegroups.com> Message-ID: <9566e05f-7ad6-499d-8404-52d60e23b6e8@m36g2000hse.googlegroups.com> On Jul 16, 8:55 am, McA wrote: > Thank you for that snippet. That means, that the root-logger does > inherit > EVERY message (if it fits to the level and isn't filtered) and the > inheritage chain is build by the chosen logger names, e.g. > messages tologging.getLogger('tree.leave') would also show up inlogging.getLogger('tree') automatically? Yes. > If this is true, how can I avoid this "bubbling up" if I would like > to? > (You see, that's a new question, but I want to take the chance to get > the answers from you personally ;-) > > Hope not to bother. > Use the propagate flag, which is mentioned in the documentation. In fact, please make sure you've reviewed all the documentation before posting, as the documentation is intended to answer the more straightforward and common questions which come up. Best regards, Vinay Sajip From fredrik at pythonware.com Thu Jul 17 05:13:26 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 11:13:26 +0200 Subject: Remove some characters from a string In-Reply-To: <35cff1a6-74f6-4a68-b81e-71d8ff9c4633@a70g2000hsh.googlegroups.com> References: <35cff1a6-74f6-4a68-b81e-71d8ff9c4633@a70g2000hsh.googlegroups.com> Message-ID: Julien wrote: > I can't seem to find the right regular expression to achieve what I > want. I'd like to remove all characters from a string that are not > numbers, letters or underscores. > > For example: > >>>> magic_function('si_98%u^d at .as-*gf') > str: 'si_98udasgf' the easiest way is to replace the things you don't want with an empty string: >>> re.sub("\W", "", "si_98%u^d at .as-*gf") 'si_98udasgf' ("\W" matches everything that is "not numbers, letters, or underscores", where the alphabet defaults to ASCII. to include non-ASCII letters, add "(?u)" in front of the expression, and pass in a Unicode string). From pdorange at pas-de-pub-merci.mac.com Wed Jul 2 11:49:31 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Wed, 2 Jul 2008 17:49:31 +0200 Subject: Trouble using pinckle References: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <1ijgp2r.1j1k5xwwbtiwcN%pdorange@pas-de-pub-merci.mac.com> C?dric Lucantis wrote: > Here self is only a local variable and its meaning is only a convention. So > assigning it to a new value won't change the object itself (and is not a good > idea as it may be confusing for the reader). Thanks, i was thinking about something like that. > You should either use a static method which returns a new object: > > class Prefs (object) : > > def save (self, f) : > pickle.dump(self, f) > > @staticmethod > def load (f) : > return pickle.load(f) > > and load it with "prefs = Prefs.load(filename)" > > or store all the values in a dictionary and only pickle this object: > > class Prefs (object) : > > def __init__ (self) : > self.values = { 'test': 1, ... } > > def save (self, f) : > pickle.dump(self.values, f) > > def load (self, f) : > self.values = pickle.load(f) I try the staticmethod, it works fine. Very helpful. But i don't like it very much, it seems 'complicated' (python was supposed to be simple). I'll also try the dictionnary method. My final idea was that a dictionnary would be perhaps simple in the future to save/load as XML and a parser. But perhaps i'm wrong with my vision of python. On a more global perspective, what are the best method to implement a simple config file with pyhton. Assuming i finally want to made a bundle app for Mac, Windows and perhaps Linux. I develop on Mac, and on this platform the config fil (preferences) have to be stored in a special directory : ~/Library/Preferences, no problem. But on other platform that's not the same directory and perhaps i would also faced to permissions issues... But first is there a way to determine on which platfrom the python script is running ? -- Pierre-Alain Dorange Vid?o, DV et QuickTime Clarus, the DogCow From norseman at hughes.net Tue Jul 8 17:13:38 2008 From: norseman at hughes.net (norseman) Date: Tue, 08 Jul 2008 14:13:38 -0700 Subject: Cross Compiler for Python? In-Reply-To: <001101c8e0d2$36a50ec0$0d00a8c0@hendrik> References: <001101c8e0d2$36a50ec0$0d00a8c0@hendrik> Message-ID: <4873D882.6090109@hughes.net> Hendrik van Rooyen wrote: > norseman wrote: > >> ================================================== >> In case all else fails: >> >> This is not a cookbook answer, but: >> 1) gnu's gcc will compile to 16,32 or 64 bit intel architectures >> OK, the 32 bit version compiles to 16 or 32 & the 64 should. >> The 64 will run 32 bit programs, including the 32 bit gcc. >> chgroot can be (messy but) useful to maintain separation. >> 2) info gcc and look for compiler directives >> then info nasm and look for directives >> same for the linker >> I'm not specific because I use Slackware and different >> distros can use different modules. You may have an assembler >> with a different name. Switches can be different and so >> forth. >> On Slackware the installpkg (for tarballs already compiled) records the >> locations of where things go in /var/log/packages. I have to assume >> other distros have something similar since these are used to remove >> things later. Can we say 'updates'? If not you will need to wade >> through the .configure and Makefiles to root out what happens to get >> 'vanilla' locations. >> >> Like I said, it's not cookbook, but it will get you there and you will >> gain quite an insight into Linux. While the path may not be well marked >> in Linux, there usually is one. >> >> Sorry I don't have a more straight forward approach. >> >> - Steve >> > > Thanks Steve, for the tips. > > In a sense, I have dreaded an answer like this, as it is cold comfort > to realise that I will be hassled off my objective to take a side trip > through Linux's complexities, just so that I can play with the hardware > to evaluate if we can use it for what we want to do. > > I had fondly hoped that somebody would have blazed the way > before me. But it seems not. Tough. > > I will report here what I do and find - It may help some other > poor sod some day... > > - Hendrik > > > -- > http://mail.python.org/mailman/listinfo/python-list > ============================================= ....dreaded.... Yep! I know the feeling. Got lots of those T-Shirts. ;) I re-read your original post. I got the feeling the eBox is running a stripped down Linux. Is that so? If it is, then: You mention pcmcia. Is it external, a plug in? Do any of your desktops/etc have pcmcia slots? Because if so..... 1) Card can be mounted on your machine 2) Compile and install can be direct to card (rem 32bit output) just change the install path(s). Look over the eBox /lib ( I'm assuming Linux again) and put that lib path first in the compile command line. If no desktop pcmcia adapter - pay the $40 or so for an USB attachable pcmcia adapter sample: plug in card (if current drives on desktop are scsi or sata drives you may need to change sda to sdb or sdc or .... use fdisk /dev/sda to check existence. the single letter 'q' to exit without changing anything. Careful with fdisk - damage comes quickly, easily and unrepairable. All you are after is which letter to use. Last one before No such drive is the one. ) cd /mnt mkdir sda mount /dev/sda1 /mnt/sda ls /mnt/sda should give base dir listing of flashdrive (linux will treat the pcmcia flash as a removable HardDrive) install to /mnt/sda/usr/local/lib (or /mnt/sda/--where ever--) then: back on eBox cd /mnt mkdir sda cd sda ln -s /usr usr I did the soft link process above on my machine, then: ls /mnt/sda/usr/local/lib/python2.5 should list contents correctly (and does on my machine since it is located in /usr/local/lib/python2.5) thus keeping compile and install paths working. The use of the midnight commander (mc) with card mounted makes transferring whole trees simple. Soft links were invented for a reason! OF COURSE, if the eBox is not running Linux, all this is useless! ;) Steve norseman at hughes.net From bignose+hates-spam at benfinney.id.au Mon Jul 7 17:38:20 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 08 Jul 2008 07:38:20 +1000 Subject: "in"consistency? References: Message-ID: <87vdzhwf1v.fsf@benfinney.id.au> "David C. Ullrich" writes: > >>> 'ab' in 'abc' > True > >>> [1,2] in [1,2,3] > False > Is there a reason for the inconsistency? Probably. The special behaviour of string types was changed in Python 2.3, according to that document. -- \ ?I put contact lenses in my dog's eyes. They had little | `\ pictures of cats on them. Then I took one out and he ran around | _o__) in circles.? ?Steven Wright | Ben Finney From squishywaffle at gmail.com Thu Jul 31 10:41:34 2008 From: squishywaffle at gmail.com (squishywaffle at gmail.com) Date: Thu, 31 Jul 2008 07:41:34 -0700 (PDT) Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> <6fe0scFaus40U1@mid.uni-berlin.de> Message-ID: <6bc8bc07-eab0-4303-b8a4-c9470f96038d@c65g2000hsa.googlegroups.com> > How much more liberal can it get than MIT-licensed? Again, the licensing issue is everything to do with the original library distributor, NOT ctypes. > But then, if you insist, go down the hard road. Irrelevant and unnecessary. If you don't want to help, don't please don't reply. From mcmurtri at dslextreme.com Fri Jul 11 23:18:05 2008 From: mcmurtri at dslextreme.com (Kevin McMurtrie) Date: Fri, 11 Jul 2008 20:18:05 -0700 Subject: paypal wholesale men jordans 17 (paypal accept)(www super-saler com References: <5d746374-d2a0-411e-bf60-87256a219b7c@m44g2000hsc.googlegroups.com> <87skuhqerl.fsf@benfinney.id.au> Message-ID: In article <87skuhqerl.fsf at benfinney.id.au>, Ben Finney wrote: > WDC writes: > > > On Jul 10, 10:33?pm, 128 wrote: > > [?] > > > > > Is that spam i spy? > > It is, clearly. Please don't make the problem worse by repeating the > entire thing. I strongly recommend dropping all articles with "googlegroups.com" in the Message-ID. Some groups are getting hit with hundreds of Google spams a day and it's only going to get worse. -- I will not see your reply if you use Google. From kris at FreeBSD.org Thu Jul 10 13:15:13 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Thu, 10 Jul 2008 19:15:13 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <1215704825.11618.6.camel@aalcdl07.lib.unc.edu> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <1343fa73-fd32-46c3-8a75-0efc85b2660e@a70g2000hsh.googlegroups.com> <1215704825.11618.6.camel@aalcdl07.lib.unc.edu> Message-ID: <487643A1.3070705@FreeBSD.org> J. Cliff Dyer wrote: > On Wed, 2008-07-09 at 12:29 -0700, samwyse wrote: >> On Jul 8, 11:01 am, Kris Kennaway wrote: >>> samwyse wrote: >>>> You might want to look at Plex. >>>> http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/ >>>> "Another advantage of Plex is that it compiles all of the regular >>>> expressions into a single DFA. Once that's done, the input can be >>>> processed in a time proportional to the number of characters to be >>>> scanned, and independent of the number or complexity of the regular >>>> expressions. Python's existing regular expression matchers do not have >>>> this property. " >>> Hmm, unfortunately it's still orders of magnitude slower than grep in my >>> own application that involves matching lots of strings and regexps >>> against large files (I killed it after 400 seconds, compared to 1.5 for >>> grep), and that's leaving aside the much longer compilation time (over a >>> minute). If the matching was fast then I could possibly pickle the >>> lexer though (but it's not). >> That's funny, the compilation is almost instantaneous for me. >> However, I just tested it to several files, the first containing >> 4875*'a', the rest each twice the size of the previous. And you're >> right, for each doubling of the file size, the match take four times >> as long, meaning O(n^2). 156000*'a' would probably take 8 hours. >> Here are my results: >> >> compile_lexicon() took 0.0236021580595 secs >> test('file-0.txt') took 24.8322969831 secs >> test('file-1.txt') took 99.3956799681 secs >> test('file-2.txt') took 398.349623132 secs > > Sounds like a good strategy would be to find the smallest chunk of the > file that matches can't cross, and iterate your search on units of those > chunks. For example, if none of your regexes cross line boundaries, > search each line of the file individually. That may help turn around > the speed degradation you're seeing. That's what I'm doing. I've also tried various other things like mmapping the file and searching it at once, etc, but almost all of the time is spent in the regexp engine so optimizing other things only gives marginal improvement. Kris From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 09:07:07 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 15:07:07 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <87zlo7y2wn.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <32e12408-fc9f-4eb4-8b9d-fb7fa69bd2fc@f36g2000hsa.googlegroups.com> <87zlo7y2wn.fsf@physik.rwth-aachen.de> Message-ID: <48889a72$0$25165$426a74cc@news.free.fr> Torsten Bronger a ?crit : > Hall?chen! > > Kay Schluehr writes: > >> On 24 Jul., 11:40, Torsten Bronger >> wrote: >>> Bruno Desthuilliers writes: >>> >>>> [...] >>>> >>>> How would you handle this case with an implicit 'self' : >>>> >>>> class Foo(object): >>>> pass >>>> >>>> def bar(self): >>>> print self >>>> >>>> Foo.bar = bar >>> Just like this. However, the compiler could add "self" to >>> non-decorated methods which are defined within "class". >> And $self2, $self3, ... to the object methods of nested classes >> and $cls2, $cls3, ... to the classmethods of those classes...? > > One could surely find ways to realise this. However, the design > goal should be: Make the frequent case simple, and the rare case > possible. Given the (more and more prominent) use of decorators, metaclasses and other meta-programming techniques in Python, I'm not sure the cases where you really need access to Python's object model inners are that "rare". Not in my code at least. From ivlenin at gmail.com Thu Jul 17 18:37:59 2008 From: ivlenin at gmail.com (I V) Date: Thu, 17 Jul 2008 22:37:59 GMT Subject: interpreter vs. compiled References: Message-ID: On Thu, 17 Jul 2008 15:08:17 -0700, castironpi wrote: > The Python disassembly is baffling though. > >>>> y= 3 >>>> dis.dis('x=y+1') You can't disassemble strings of python source (well, you can, but, as you've seen, the results are not meaningful). You need to compile the source first: >>> code = compile('y=x+1','-', 'single') >>> dis.dis(code) 1 0 LOAD_NAME 0 (x) 3 LOAD_CONST 0 (1) 6 BINARY_ADD 7 STORE_NAME 1 (y) 10 LOAD_CONST 1 (None) 13 RETURN_VALUE You may well find these byte codes more meaningful. Note that there is a list of opcodes at http://docs.python.org/lib/bytecodes.html From gagsl-py2 at yahoo.com.ar Tue Jul 15 01:51:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 02:51:39 -0300 Subject: How to write a custom tracer/profiler? References: <28ee2efb-6c8a-4884-8d25-4b91fb73ebb2@f63g2000hsf.googlegroups.com> Message-ID: En Mon, 14 Jul 2008 23:48:20 -0300, AK at SYD escribi?: > The main logic will issue a number of calls to the DS in order to get > the data it needs and then carry out some calculations. > > I want to have a non-intrusive way to find out all the DS data > requested by the main logic. > > One thing to note, the DS is a big, messy bit of code. So putting > logger everywhere within DS and main logic is not a reliably, > satisfactory solution. > > I have thought about using somehting like aspect. But seems to me > there is no mature, widely-used aspect lib out there. > > Another idea is: let's roll a custom tracer/profiler. Whenever any > method/attributes in the DS package are called, the return values will > be logged. > > I have taken a quick look at profile.py in python 2.4, It seems sys > module will pass a frames to the profile class. Can I access the > return value of a function via these frame objects? You don't have to use a profiler; just replace the original DS functions that you're interested in monitoring, with a "wrapped" version that logs its parameters and then calls the original code. A skeleton example (suppose DS.open is one function you want to monitor): import DS original_open = DS.open def wrapped_open(*args, **kw): trace("open", *args, **kw) return original_open(*args, **kw) DS.open = wrapped_open This approach has some problems (it does not preserve the original function signature, by example). You may overcome this (and other problems) using the decorator module from M. Simionato; see -- Gabriel Genellina From mwalsh at groktech.org Mon Jul 14 02:21:19 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Mon, 14 Jul 2008 01:21:19 -0500 Subject: Why is there no GUI-tools like this for Windows? In-Reply-To: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> References: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> Message-ID: <487AF05F.4050409@groktech.org> maestro wrote: > I can just do the layout with my mouse and then there is a program > that writes the code for me. > GUI-programming is hard for no reason. One good program then forever > easy... > > Is there not something like this for Python/Windows? Is the Linux one > only for ruby or for any language? > I only watched a small part of the video so I'm making some assumptions about it's content. But there is nothing preventing you from using the same(/similar) toolchain on windows, which I believe would include python, pygtk, the gtk+ runtime, and glade -- last I checked all have windows binary distributions. To quote the glade website """ The user interfaces designed in Glade are saved as XML, and by using the libglade library these can be loaded by applications dynamically as needed. By using libglade, Glade XML files can be used in numerous programming languages including C, C++, Java, Perl, Python, C#, Pike, Ruby, Haskell, Objective Caml and Scheme. Adding support for other languages is easy too. """ HTH, Marty From deets at nospam.web.de Mon Jul 28 08:19:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 14:19:57 +0200 Subject: Proxy server? References: Message-ID: <6f5rteF89muqU2@mid.uni-berlin.de> Gary wrote: > I've seen examples for HTTP and FTP use, but not for simply any TCP data > on any port, which is what I require. Can anyone please point me in the > right direction? For what? How to use such a thing, a transparent proxy? There is nothing to it, just plug it between your router and the internet, that's all. Or do you want to know how to capture all traffic using some other process, for analysis? Use wireshark. Diez From vino341 at gmail.com Sat Jul 19 04:06:35 2008 From: vino341 at gmail.com (hot rathi) Date: Sat, 19 Jul 2008 01:06:35 -0700 (PDT) Subject: Your win 10, 000$ in my groups Pls register your name and address in below of the website http://www.geocities.com/cathrina39 http://namithawithyou.blogspot.com/ Message-ID: <7f3d4b94-5fff-4cad-b688-d56aeb4ad1a2@v1g2000pra.googlegroups.com> Your win 10,000$ in my groups Pls register your name and address in below of the website http://www.geocities.com/cathrina39 http://namithawithyou.blogspot.com/ From socyl at 987jk.com.invalid Tue Jul 29 17:37:43 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 21:37:43 +0000 (UTC) Subject: iterating "by twos" References: Message-ID: In Terry Reedy writes: >kj wrote: >> Is there a special pythonic idiom for iterating over a list (or >> tuple) two elements at a time? >> >> I mean, other than >> >> for i in range(0, len(a), 2): >> frobnicate(a[i], a[i+1]) >There have been requests to add a grouper function to itertools, but its >author has resisted because there are at least three things one might do >with the short remainder group left over when the group size does not >evenly divide the sequence size: drop it, return it, or fill it to the >requested groupsize with a dummy value and then return it. Why not make this choice a third argument to the grouper function? Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From jr9445 at ATT.COM Tue Jul 1 10:06:42 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Tue, 1 Jul 2008 09:06:42 -0500 Subject: How make regex that means "contains regex#1 but NOT regex#2" ?? In-Reply-To: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> References: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of > seberino at spawar.navy.mil > Sent: Tuesday, July 01, 2008 2:29 AM > To: python-list at python.org > Subject: How make regex that means "contains regex#1 but NOT regex#2" > ?? > > I'm looking over the docs for the re module and can't find how to > "NOT" an entire regex. > > For example..... > > How make regex that means "contains regex#1 but NOT regex#2" ? > Match 'foo.*bar', except when 'not' appears between foo and bar. import re s = 'fooAAABBBbar' print "Should match:", s m = re.match(r'(foo(.(?!not))*bar)', s); if m: print m.groups() print s = 'fooAAAnotBBBbar' print "Should not match:", s m = re.match(r'(foo(.(?!not))*bar)', s); if m: print m.groups() == Output == Should match: fooAAABBBbar ('fooAAABBBbar', 'B') Should not match: fooAAAnotBBBbar ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA621 From lars at gustaebel.de Sat Jul 19 06:11:11 2008 From: lars at gustaebel.de (Lars =?iso-8859-1?Q?Gust=E4bel?=) Date: Sat, 19 Jul 2008 12:11:11 +0200 Subject: How to process a very large (4Gb) tarfile from python? In-Reply-To: <1fe948fd-63a3-48ef-b5a8-84f0e4dd48a2@y22g2000prd.googlegroups.com> References: <0e96241d-60a3-44fd-967a-394904ad5b34@e39g2000hsf.googlegroups.com> <4nqu74p3mmmdmf9pn7125voe6itko8d31k@4ax.com> <1fe948fd-63a3-48ef-b5a8-84f0e4dd48a2@y22g2000prd.googlegroups.com> Message-ID: <20080719101104.GA20323@axis.g33x.de> On Thu, Jul 17, 2008 at 11:41:50PM -0700, Uwe Schmitt wrote: > On 17 Jul., 22:21, Lars Gust?bel wrote: > > > > > Maybe we should post this issue to python-dev mailing list. > > > Parsing large tar-files is not uncommon. > > > > This issue is known and was fixed for Python 3.0, seehttp://bugs.python.org/issue2058. > > The proposed patch does not avoid caching the previous values of the > iterator, it just reduces the size of each cached object. > It would be nice to be able to avoid caching on demand, which would > make iteration independent of the size of the tar file. The size of the archive doesn't matter, it's the number of members. And I wouldn't call it caching either. The members are stored in order to have a table of contents and to allow random access. Also, the members list is required for resolving hard links within the archive. It cannot be dropped without side-effects. -- Lars Gust?bel lars at gustaebel.de Those who would give up essential liberty, to purchase a little temporary safety, deserve neither liberty nor safety. (Benjamin Franklin) From Henning.Thornblad at gmail.com Mon Jul 7 12:51:40 2008 From: Henning.Thornblad at gmail.com (Henning Thornblad) Date: Mon, 7 Jul 2008 09:51:40 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <6deq2uF21vo2U1@mid.uni-berlin.de> Message-ID: <9b841be4-cd9c-4782-8498-55f053cdbb71@x41g2000hsb.googlegroups.com> When trying to find an alternative way of solving my problem i found that running this script: #!/usr/bin/env python import re row="" for a in range(156000): row+="a" print "How many, dude?" print re.search('/[^ "=]*',row) (the / has moved) wouldn't take even a second (The re.search part of course) This is for me very strange since this, in theory, is the same problem as before. /Henning Thornblad From fredrik at pythonware.com Mon Jul 21 08:03:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 14:03:25 +0200 Subject: simple question about dictionaries In-Reply-To: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> References: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> Message-ID: skazhy wrote: > hi, i am new to python, so i've a really simple question about > dictionaries. > if i have a dictionary and I make have an input after it (to input > numbers) can i get the key of value that was in input? A dictionary contains (key, value) pairs, and is optimized for quickly finding the value in a pair, if given the key. > somehting like this: > dict = { "key1"=100,"key2"=200,"key3"=300} dict() is a built-in function; you're free to reuse the names of such functions as variable names in Python, but if you do, you won't be able to use those functions in that part of your program. And in this case, the dict() built-in might be useful (see below): > a = input() > print 'the key of inputted value is', dict['a'] > > this syntax of course is wrong, but i hope you got the point.. Assuming that you want the *key* in Python's sense, for a given value, you can either loop over the dictionary (called D below): for k, v in D.items(): if v == a: print 'the key of inputted value is', v break else: print "not found" or create an reverse mapping and use that (you only have to do this every time the dictionary changes, of course), e.g. reverse_D = dict((D[k], k) for k in D) a = input() print "the key for value", a, "is", reverse_D[a] (this doesn't work if you call your dictionary "dict", obviously.) From Russ.Paielli at gmail.com Tue Jul 29 21:33:30 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 18:33:30 -0700 (PDT) Subject: static variables in Python? References: Message-ID: <39a2e1f0-b919-4065-8a7a-e3a4b837a347@25g2000hsx.googlegroups.com> On Jul 29, 1:40 pm, kj wrote: > Yet another noob question... > > Is there a way to mimic C's static variables in Python? Or something > like it? The idea is to equip a given function with a set of > constants that belong only to it, so as not to clutter the global > namespace with variables that are not needed elsewhere. > > For example, in Perl one can define a function foo like this > > *foo = do { > my $x = expensive_call(); > sub { > return do_stuff_with( $x, @_ ); > } > > }; > > In this case, foo is defined by assigning to it a closure that has > an associated variable, $x, in its scope. > > Is there an equivalent in Python? > > Thanks! > > kynn > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. If the constant parameters are really only needed in one particular function, you can use default function arguments. An added benefit is that you can override them with another value if necessary. def fun(x, y, parameter1=0, parameter2=1): ... From jeffober at gmail.com Fri Jul 11 07:36:18 2008 From: jeffober at gmail.com (Jeff) Date: Fri, 11 Jul 2008 04:36:18 -0700 (PDT) Subject: MySQLdb will only import for root References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> <6dothnF3lqqmU1@mid.uni-berlin.de> Message-ID: <85d26ae4-757f-494c-bf7e-412323e26b8a@x41g2000hsb.googlegroups.com> Is it possible the module was installed with priviledges set too strict? Perhaps the interpreter cannot see the module when it is run from a normal user account. From modelnine at modelnine.org Thu Jul 31 09:58:10 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Thu, 31 Jul 2008 15:58:10 +0200 Subject: problem when reading file In-Reply-To: <8e50c4e80807310644u3c456ab4qce06c6997707db8d@mail.gmail.com> References: <8e50c4e80807310644u3c456ab4qce06c6997707db8d@mail.gmail.com> Message-ID: <200807311558.11141.modelnine@modelnine.org> Am Donnerstag, 31. Juli 2008 15:44:33 schrieb shrimpy: > hi every one, i am new to python, > and coz i want to write a handy command for my linux machine, to find > a word in all the files which are under the current folder. What about grep -R "myword" . ? Even works on regular expression (with e/fgrep). Type grep --help to see all the options you get (context display, ignoring anything that's not a proper file or directory, only printing filenames with matches, not the matches themselves, etc.). -- Heiko Wundram From alexnbryan at gmail.com Thu Jul 17 01:36:20 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 22:36:20 -0700 (PDT) Subject: Need help getting BeautifulSoup contents Message-ID: <18501881.post@talk.nabble.com> The trick to this one is that the html looks something like this: " My question is I want everything inside, the contents of each ad the regular text of the
american, a href="/browse/blue" linkindex="12" set="yes">blue , a href="/browse/brick" linkindex="13" set="yes">brick , brie, cheddar, cheshire, a href="/browse/churn" linkindex="14" set="yes">churn , a href="/browse/cottage" linkindex="15" set="yes">cottage , a href="/browse/cream" linkindex="16" set="yes">cream , dunlop, and it goes on . I know I can do like a.contents, but it only gives me the first one, in this case being "blue". I want the contents of each of those and the regular contents of the . Can anyone help? -- View this message in context: http://www.nabble.com/Need-help-getting-BeautifulSoup-contents-tp18501881p18501881.html Sent from the Python - python-list mailing list archive at Nabble.com. From Nikolaus at rath.org Thu Jul 31 13:59:58 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Thu, 31 Jul 2008 19:59:58 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> <87r69a85ek.fsf@nokile.rath.org> Message-ID: <87fxpq7x41.fsf@nokile.rath.org> Maric Michaud writes: >>> What the means is that int is not a user type but a >>> builtin type, instances of int are not types (or classes) but common >>> objects, so its nature is the same as any classes. >>> >>> The way it prints doesn't matter, it's just the __repr__ of any instance, >>> and the default behavior for instances of type is to return '', >>> but it can be easily customized. >> >> But 'int' is an instance of 'type' (the metaclass): >> >>> int.__class__ >> >> >> >> so it should also return '' if that's the default behavior >> of the 'type' metaclass. >> > > The fact that a class is an instance of type, which it is always true, doesn't > mean its metaclass is "type", it could be any subclass of type : Yes, that is true. But it's not what I said above (and below). 'obj.__class__' gives the class of 'obj', so if 'int.__class__ is type' then 'type' is the class of 'int' and 'int' is *not* an instance of some metaclass derived from 'type'. >> I think that to get '' one would have to define a new >> metaclass like this: >> >> def type_meta(type): >> ? ? def __repr__(self) >> ? ? ? ? ?return "" % self.__name__ >> >> and then one should have int.__class__ is type_meta. But obviously >> that's not the case. Why? >> >> Moreover: >> >>> class myint(int): >> >> ... ? ?pass >> ... >> >> >>> myint.__class__ is int.__class__ >> True >> >> >>> int >> >> >> >>> myint >> >> >> despite int and myint having the same metaclass. So if the >> representation is really defined in the 'type' metaclass, then >> type.__repr__ has to make some kind of distinction between int and >> myint, so they cannot be on absolute equal footing. > > You're right, type(int) is type, the way it renders differently is a > detail of its implementation, you can do things with builtin types > (written in C) you coudn't do in pure python, exactly as you > couldn't write recursive types like 'object' and 'type'. If it is just a matter of different rendering, what's the reason for doing it like that? Wouldn't it be more consistent and straightforward to denote builtin types as classes as well? And where exactly is this different rendering implemented? Could I write my own type (in C, of course) and make it behave like e.g. 'int'? I.e. its rendering should be different and not inherited to subclasses: >>> my_type >>> a = my_type(42) >>> a.__class__ >>> class derived(my_type): >>> pass or would I have to change the implemention of 'type' for this (since it contains the __repr__ function that renders the type)? This is of course purely theoretical and probably without any practical relevance. I'm if I just can't stop drilling, but I think this is really interesting. Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From circularfunc at gmail.com Mon Jul 7 13:36:31 2008 From: circularfunc at gmail.com (ssecorp) Date: Mon, 7 Jul 2008 10:36:31 -0700 (PDT) Subject: Very weird bug! References: <1c1c343a-dd63-454a-8e29-a5c70281ad90@c58g2000hsc.googlegroups.com> Message-ID: <1c7f6a82-bd0b-46bc-a6b7-23bf9f4b5ee3@m36g2000hse.googlegroups.com> i know, idid try it again and it works as expected. but how the h*** did it not work that one time? From norseman at hughes.net Thu Jul 10 14:34:53 2008 From: norseman at hughes.net (norseman) Date: Thu, 10 Jul 2008 11:34:53 -0700 Subject: sort(cmp=func) In-Reply-To: References: Message-ID: <4876564D.9060906@hughes.net> Tobiah wrote: > I have a list of objects that generate code. Some > of them depend on others being listed first, to > satisfy dependencies of others. > > I wrote a cmp function something like this: > > def dep_cmp(ob1, ob2): > > if ob1.name in ob2.deps: > return -1 > else: > return 1 > > I also tried returning 0 when there were no dependency > relationships between the objects. > > This failed, because every object was not compared with > ever other. I imagine that this is because sort assumes > that if a > b and b > c, then a > c. In my case, this > isn't really true. If a is not dependent on b, and > b is not dependent on c, that doesn't mean that a is not > dependent on c. > > Is there a better way? > > Thanks > > Tobiah > ** Posted from http://www.teranews.com ** > -- > http://mail.python.org/mailman/listinfo/python-list > ================================== If you are running Linux take a look at /lib/modules/[kernel-ver]/modules.dep In other words, to create a list like: this module: depends on these module-a module-f, module-g copy ALL modules to a scratch directory ls -1 | sort >file.lst (or dir /b/l | sort >file.lst) concept: #outer loop get a filename from file.lst create a list of all imports in it compare filename, in turn, to each line in file if it finds itself loop #inner loop otherwise open module and create 2nd list of all imports in this file compare each item in list one to each item in list two and output one line for each match to imports1.lst, format: module name needing, module name wanted (filenames not def names) #outer loop2 get a line from dep1.lst parse to f1=first-name, f2=second-name create list of imports for f2 #inner loop2 check each import of f2 against name of f1 if there is a match, print Circular conflict with: f1 and f2 to problems.lst A sort on second filename on line combined with a visual inspection will often help point out any 3-way (or more) circulars. (a needs b needs c needs a) No guarantees, though. You will have to resolve circulars yourself. Usually involves changing code. If A needs output from B to run and B needs output from A to run you have an obvious circular. Rewrite/fix the code. Perhaps make a lib file of all the imports for the project. (Which is the preferred practice.) Load it with the main logic. Thus none will be run until all are present. Then eliminate whatever circular nonsense still exists... If problems.lst is empty all that needs to be done is for each import to check the dep1.lst and first load the second filename on the line for each first-name matching module wanted. For a given first filename not being in a circular, manual ordering of the dep1.lst can be done if needed. (Perhaps f1,a1:f1,b1:f1,c1 needs to be f1,c1:f1,a1:f1,b1 ? Simply because descriptive alpha name sort winds up being wrong load sequence.) Just because a piece of code can be reused does not mean it is generically practical to do so. The why of this is your current problem. My first reaction to your original post is that you inherited something and are setting about cleaning it up so you can work on it. Best of luck. Succeed and you get to claim another T-shirt. :) Steve norseman at hughes.net From matt at tplus1.com Tue Jul 15 10:04:41 2008 From: matt at tplus1.com (Matthew Wilson) Date: Tue, 15 Jul 2008 14:04:41 GMT Subject: How to package a logging.config file? References: <0a5713d6-8337-44a3-8347-012814345dd8@79g2000hsk.googlegroups.com> Message-ID: On Mon 14 Jul 2008 09:25:19 AM EDT, Vinay Sajip wrote: > Is your package a library or an application? If it's a library, you > should avoid configuring logging using a config file - this is because > logging configuration is process-wide, and if multiple libraries use > fileConfig to configure their logging, you may get unexpected results. I thought that the point of using logging.getLogger('foo.bar.baz') was to allow each module/class/function to choose from the available configurations. So, I can define a really weird logger and still be a good citizen. As long as I don't tweak the root logger, is it safe to use a config file? Matt From martin at v.loewis.de Tue Jul 22 14:52:08 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 22 Jul 2008 20:52:08 +0200 Subject: CPython VM internals - Wiki page In-Reply-To: <48862716$0$17157$742ec2ed@news.sonic.net> References: <48862716$0$17157$742ec2ed@news.sonic.net> Message-ID: <48862C58.1020905@v.loewis.de> > That's interesting. It's dumber than I thought. All temporaries > on the stack are "boxed" as PyObjects. That's simple and portable, > but slow. Not only that - Python does not ever have the concept of unboxed values, except for local variables in the C implementations of arithmetic operations and system calls. Using true objects is slow only if allocation and deallocation is slow, which it fortunately isn't. Regards, Martin From modelnine at modelnine.org Tue Jul 29 06:36:32 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Tue, 29 Jul 2008 12:36:32 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <200807291115.05701.modelnine@modelnine.org> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <200807291115.05701.modelnine@modelnine.org> Message-ID: <200807291236.32517.modelnine@modelnine.org> Am Dienstag, 29. Juli 2008 11:15:05 schrieb Heiko Wundram: > I can't dig up a simple example from code I wrote quickly... Just to get back to that: an example I found where "if x" (the generic __nonzero__() test) will work to test for emptiness/non-emptiness of a container, whereas "if len(x) > 0" (the "specific" test for this example) will not, is my for own integer set type I wrote a while back (which you can find on ASPN). The corresponding set type allows you to create infinitely sized sets of integers (which of course are stored as pairs of ,-values, so the storage itself for the set is bounded), for which len(x) does not have a "proper" meaning anymore, and __len__() is limited to returning a (platform dependent) ssize_t anyway IIRC, so even with a bounded set, the length of the set might not necessarily be accessible using len(x); that's why the set type additionally got a member function called .len() to work around this restriction. I should think is a non-contrieved example where the generic test whether the object considers itself True/False (which for containers means non-empty/empty) is preferrable over the special case test whether the length is positive. A polymorphic function, which for example only accesses the first ten members of the container is able to work with an infinite set if it uses the generic test, but is not in case it uses len(x) > 0. -- Heiko Wundram From jcoglan at googlemail.com Sun Jul 20 05:20:58 2008 From: jcoglan at googlemail.com (James Coglan) Date: Sun, 20 Jul 2008 02:20:58 -0700 (PDT) Subject: MethodChain References: <6eej10F6k7g3U2@mid.uni-berlin.de> <342b5431-5ead-4827-8bdd-ab2cd50c2acc@i76g2000hsf.googlegroups.com> <6efv5cF6uhc3U1@mid.uni-berlin.de> Message-ID: > Name clashes aren't an issue, since MethodChain doesn't apply any > special meaning to the method names it knows; the limitation is > because JavaScript doesn't allow you to modify property lookup > behavior. ?And since we can make the chain object callable, we don't > need "fire" or "toFunction" methods. I'm the author of MethodChain, so just thought I'd confirm the above statement. All MethodChain does is store method calls so they can later be replayed on any object. All methods in MethodChain simply add their name and arguments to an array inside the MethodChain instance, they don't implement any concrete functionality. All that's important is the names of the methods -- the object the chain is fired on will decide how to handle those calls itself, so naming clashes aren't a problem. For example: var chain = it().toLowerCase().split('-').map(function() {...}); chain.fire('my-String'); is the same as 'my-String'.toLowerCase().split('-').map(function() {...}); So split() gets called on 'my-string', map() gets called on ['my', 'string']. The methods 'fire' and 'toFunction' are a problem but I can't see any way around having them in JavaScript -- you need some way of getting the method list out of the chain object. if JavaScript had method_missing, we wouldn't need to tell MethodChain about names in advance either. From basti.wiesner at gmx.net Wed Jul 2 10:12:18 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Wed, 02 Jul 2008 16:12:18 +0200 Subject: Scripting SAP GUI (Windows) References: <6d15tpFaec4U1@mid.individual.net> Message-ID: Thomas Guettler : > Hi, > > I need to script SAP GUI running on MS-Windows: Doesn't that thing have a COM interface? -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From shevitz at lanl.gov Wed Jul 23 19:01:41 2008 From: shevitz at lanl.gov (Danny Shevitz) Date: Wed, 23 Jul 2008 23:01:41 +0000 (UTC) Subject: problem doing unpickle in an exec statement Message-ID: Howdy, In my app I need to exec user text that defines a function. I want this function to unpickle an object. Pickle breaks because it is looking for the object definition that isn't in the calling namespace. I have mocked up a simple example that shows the problem. Run this first code (from create_pickle.py) to create the pickle. create_pickle.py: (run this first) ############################################# import cPickle # the pickle file name file_name = 'd:\\temp\\test1.pickle' # define a class class Tree(object): pass def main(): # instantiate t = Tree() # create the sweet pickle fp = open(file_name, 'wb') cPickle.dump(t, fp) fp.close() # try to unpickle directly fp = open(file_name, 'rb') result = cPickle.load(fp) fp.close() print "unpickling directly works just fine, result = ", result if __name__=='__main__': main() ############################################# run this second: exec_pickle.py ############################################# # this file shows a problem with sweet pickle in an exec statement # the pickle file name file_name = 'd:\\temp\\test1.pickle' # code to be turned into a function code_text = ''' def include(): print "this works!" ''' # a function for creating functions def create_fun(code_text): clean_dict = {} exec code_text in clean_dict return clean_dict['include'] # include_fun is a bona fide function include_fun = create_fun(code_text) # this works include_fun() # now try to load the pickle in an exec statement code_text = ''' def include(file_name): print "processing file_name: ", file_name import cPickle fp = open(file_name, "rb") result = cPickle.load(fp) fp.close() print "result = ", result ''' # create the new include_fun include_fun = create_fun(code_text) # run it include_fun(file_name) ############################################# Can anyone enlighten me what I need to do to exec_pickle.py to get this to work? thanks, Danny From mensanator at aol.com Thu Jul 31 13:46:50 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 31 Jul 2008 10:46:50 -0700 (PDT) Subject: Non Continuous Subsequences References: Message-ID: <8b59f734-b992-4977-97cd-90dcbc0f3ee5@w7g2000hsa.googlegroups.com> On Jul 30, 11:32?am, bearophileH... at lycos.com wrote: > This post is not about practical stuff, so if you have little time, > you may ignore it. > > This is a task of the rosettacode.org site:http://www.rosettacode.org/wiki/Non_Continuous_Subsequences > > A subsequence contains some subset of the elements of this sequence, > in the same order. A continuous subsequence is one in which no > elements are missing between the first and last elements of the > subsequence. The task is to enumerate all non-continuous subsequences > for a given sequence. > That's equivalent to asking which n-bit binary numbers have at least one 0 bracketed by 1s, isn't it? import gmpy import re for i in xrange(32): s = gmpy.digits(i,2).zfill(5) # convert to base 2 (padded) m = re.search('10+1',s) # at least one 0 between 1s if m: z = [j+1 for j,i in enumerate(s) if i=='1'] print z ## [3, 5] ## [2, 5] ## [2, 4] ## [2, 4, 5] ## [2, 3, 5] ## [1, 5] ## [1, 4] ## [1, 4, 5] ## [1, 3] ## [1, 3, 5] ## [1, 3, 4] ## [1, 3, 4, 5] ## [1, 2, 5] ## [1, 2, 4] ## [1, 2, 4, 5] ## [1, 2, 3, 5] From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 2 10:44:23 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Jul 2008 16:44:23 +0200 Subject: How do web templates separate content and logic? In-Reply-To: References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> <87vdzpmxv3.fsf@internal.daycos.com> Message-ID: <486b9441$0$24646$426a74cc@news.free.fr> TheDarkTrumpet a ?crit : > Another thing I'd like to add on this subject. > > I agree with others here that having logic in the view isn't really a > bad thing. I used to think it did, but now I don't think it does as > much. I feel that when you're separating out the view, you're giving > really non-programmers the ability to actually do the content. That > doesn't mean that non-programmers can't learn very very basic > programming logic. Take, for example, the Django code. The Django > template system is a very watered down version of a language. It > supports very basic stuff, and I feel that really anyone can pick up > on it. > > By totally separating out the logic, and using tags, you're adding a > lot of overhead in my opinion. It's another file that needs to be > included, and the logic of how it's displayed on the page is then > split a bit - between the developer and the designer. If the designer > feels that they want only 5 products to show on one page, they should > be able to change it. > > THis is how I feel on the whole idea anyways. Yeps. Kirk and you both expressed MHO better than I did... I did the half-backed-template Kirk describes a couple times, and what you wrote above apply to my own experience with too-dumbed-down templating systems that finally make it harder for both the programmer and the designer, since a good part of the presentation logic then moves up to the controller, which somehow ruins the whole idea. From tjreedy at udel.edu Tue Jul 29 03:03:46 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 03:03:46 -0400 Subject: Is it allowed to use function results as default arguments ? In-Reply-To: <488E2BF1.8020003@gmail.com> References: <488E2BF1.8020003@gmail.com> Message-ID: To answer the subject line: param= will assign the result of the expression as the default argument object for the parameter. tjr From gagsl-py2 at yahoo.com.ar Tue Jul 15 04:28:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 05:28:12 -0300 Subject: Using Python To Launch Python References: <20080714212454.GE16010@dragontoe.org> <23116d500807141440u402eed7du5e41d72bb0716c58@mail.gmail.com> <20080715003920.GF16010@dragontoe.org> Message-ID: En Mon, 14 Jul 2008 21:39:20 -0300, Derek Martin escribi?: > On Mon, Jul 14, 2008 at 05:40:43PM -0400, Aquil H. Abdullah wrote: >> You've hit the proverbial nail with the hammer. The problem is that my >> application needs to run under both the Linux and Windows OSs, so while >> I >> would love to use a nice sh, csh, or bash shell script. My hands are >> tied >> because Windows does not provide such wonderful shells. > > *Provides*, no... neither does it provide Python, for what that's > worth. But you can certainly get it (bash): > > http://win-bash.sourceforge.net/ Using the standard cmd.exe, the previously posted shell script becomes: === begin appname.cmd === set INSTALLPATH= call %INSTALLPATH%\bin\python %INSTALLPATH%\APPNAME.py %* === end appname.cmd === -- Gabriel Genellina From xdicry at gmail.com Mon Jul 14 21:00:22 2008 From: xdicry at gmail.com (Evan) Date: Mon, 14 Jul 2008 18:00:22 -0700 (PDT) Subject: Is it possible to create "network conneciton" on windows system? References: Message-ID: On Jul 15, 6:22 am, Larry Bates wrote: > Evan wrote: > > Hello, > > > one of my PC is window system, and in "control panel ->Network > >Connections", I can see somenetworkconnectionssuch as PPPOE or VPN > > which I created by click "create a new connection". > > > My question is, is it possible to create a new connection by using > > Python script? which means I do not want to use Window UI (via > > "control panel"), if it is possible, I can save so many time to > > create variousnetworkconnection when I want to do testing in the > > lab. > > > Thanks very much. > > Evan > > It is very likely that it is possible to do this. Most control panel > applications store the results of their GUI setup in the registry. If you can > determine what registry keys have been added/changed. Here is an open source > registry compare utility that might help: > > https://sourceforge.net/projects/regshot > > You can then use the _winreg module to make such changes on a new machine. > > HTH, > Larry Thanks Larry, The thing is, if I change the registry, I have to reboot the PC for applying new configuration of system. Any idea to apply the changing without reboot after modify registry? Thanks, From alexnbryan at gmail.com Wed Jul 16 14:29:24 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 11:29:24 -0700 (PDT) Subject: Testing for connection to a website In-Reply-To: References: <18473382.post@talk.nabble.com> <18476597.post@talk.nabble.com> Message-ID: <18493785.post@talk.nabble.com> Fredrik Lundh wrote: > > Alexnb wrote: > >> e = '' > >> try: >> ... >> except HTTPError, e: >> print e.code >> except URLError, e: >> print e.reason >> >> if e == '': >> print "good to go" > > footnote: here's a better way to test if an exception was raised or not: > > try: > ... > except HTTPError, e: > print e.code > except URLError, e: > print e.reason > else: > print "good to go" > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > Thanks! can't believe I didn't think of that. -- View this message in context: http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p18493785.html Sent from the Python - python-list mailing list archive at Nabble.com. From http Tue Jul 15 22:52:26 2008 From: http (Paul Rubin) Date: 15 Jul 2008 19:52:26 -0700 Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> Message-ID: <7xiqv68rrp.fsf@ruckus.brouhaha.com> James Fassett writes: > tuple_list = ( > ('John', 'Doe'), > ('Mark', 'Mason'), > ('Jeff', 'Stevens'), > ('Bat', 'Man') > ) > # the final functional way > [result_list, _] = zip(*tuple_list) That's really ugly IMO. I'd use: result_list = list(x for (x,y) in tuple_list) I don't like square-bracket listcomps because they leak the index variables to the outside. From ptmcg at austin.rr.com Tue Jul 1 10:05:55 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 1 Jul 2008 07:05:55 -0700 (PDT) Subject: pyparsing problem References: Message-ID: On Jul 1, 8:02?am, name wrote: > Hi, > > I try to parse a file with pyparsing and get this output: > > ? ? ['generic', 'host-01', 'host alias xyz', '10.0.0.1'] > ? ? - alias: host alias xyz > ? ? - host_name: ['host-01'] > ? ? - ip_address: ['10.0.0.1'] > ? ? - use: ['generic'] > > ? ? > ? ? ? generic > ? ? ? host-01 > ? ? ? host alias xyz > ? ? ? 10.0.0.1 > ? ? > > ? ? ['generic', 'host-01', 'host alias xyz', '10.0.0.1'] > > ? ? finished > > What I don't understand is why I get the line > > ? ? generic > > and not > > ? ? generic > > as there is an associated name in the dump() output. > > Thank you very much in advance for any clue or help you could > provide. > > The code: > --------- > > #!/usr/bin/env python > > from pyparsing import * > > sample = """ > define host{ > ? use ? ? ? ? ? ? ? ? ? generic > ? host_name ? ? ? ? ? ? host-01 > ? alias ? ? ? ? ? ? ? ? host alias xyz > ? address ? ? ? ? ? ? ? ? ? ? ? 10.0.0.1} > > """ > > # define tokens > LBRACE,RBRACE = map(Suppress, '{}') > ipAddress = Combine(Word(nums) + ('.' + Word(nums))*3) > useTemplate = oneOf('generic user') > > # define grammar > > deviceName = Word(alphanums+'-') > hostDef = Literal('define').suppress() + Literal('host').suppress() > useLine = Suppress('use') + useTemplate + Suppress(SkipTo(lineEnd)) > host_nameLine = Suppress('host_name') + deviceName + Suppress(SkipTo > (lineEnd)) > aliasLine = Suppress('alias') + SkipTo(lineEnd) > aliasLine.setParseAction(lambda x: ' '.join(x[0].split())) > ip_addressLine = Suppress('address') + ipAddress > > use = useLine.setResultsName('use') > host_name = host_nameLine.setResultsName('host_name') > alias = aliasLine.setResultsName('alias') > ip_address = ip_addressLine.setResultsName('ip_address') > > host_stmt = (use + host_name + alias + ip_address) > host = hostDef + LBRACE + host_stmt ?+ RBRACE > > test_file = OneOrMore(host) + stringEnd > > # test > x = test_file.parseString(sample) > print x.dump() > print > print x.asXML('Hosts') > print > print x.asList() > print > > print 'finished' Looks like this is a bug in asXML(). Note that if I reverse the use and host_name strings in the input and in your grammar, I get this XML output: host-01 generic host alias xyz 10.0.0.1 Fortunately, you have provided a nice short test case, which should allow me to track down the problem. Thanks, -- Paul From npropadovic at googlemail.com Thu Jul 31 09:55:33 2008 From: npropadovic at googlemail.com (Propad) Date: Thu, 31 Jul 2008 06:55:33 -0700 (PDT) Subject: Debugging of a long running process under Windows Message-ID: Hello, I know this issue pops up once in a while, but I haven't found a good answer to it. I need to debug a long running application under windows. The application is a combined java/python framework for testing ECUs in the automotive industry. Basically, the Java GUI (Eclipse-based) starts test-cases written in Python and provides the console where the test-logs are seen. When there is a exception somewhere in the testcases (or the underlying functionallity, also written in Python), those are also logged, and then the framework usually continues with the next command in the same test case. I'd like to have a debugging facillity better than print statements. I imagine: a) something like a debugger poping up when I get an exception, or b) something debugger-like poping up when it reaches a command I entered something in the code, or c) Me pressing on a button and getting a debugger-like-thing that lets me look into the running, possibly halted code. I've done some little experiments with the code module, which looks nice but does not seem to get over the control from the java-part, and with popen2("cmd"), which seems not even to work if I start the code from a dosbox (the same console is keept), and same thing when strated by the Java-App. Just to add, using pdb (or pythonwin debugger) seems not to be an option, as it makes the test-runs much slower. Does somebody have an idea? It seems there used to be a python debugger called Pygdb, able to attach to a running application, but now it seems it disapeared (now there is a python debugger with the same name, linked to ViM). Thanx, Propad From robert.rawlins at thinkbluemedia.co.uk Mon Jul 21 07:10:53 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Mon, 21 Jul 2008 12:10:53 +0100 Subject: Daemonize an application. Message-ID: <011101c8eb22$71685ee0$54391ca0$@rawlins@thinkbluemedia.co.uk> Guys, I've been looking to run one of my applications as a Deamon on a linux based system. I've been looking at this recipe this morning and it all looks relatively fine: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 I just noted that the recipe was written 5 years ago and thought I would see if there have been any progressions in Python which allow a more native approach to forking my application as a daemon? I essentially want to add a command line parameter "--as-daemon" to my application which would fork it as a daemon instead of running it as a standard python script, I also want to ensure that stdin/out/err are all configured in a way which means any exceptions thrown by the application or data output to the command line, which I haven't foreseen will be stored in a log file for review. I'd really appreciate your advice and experience. Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmcmonagle at velseis.com.au Sat Jul 5 04:52:00 2008 From: jmcmonagle at velseis.com.au (John McMoangle) Date: Sat, 5 Jul 2008 18:52:00 +1000 Subject: Tkinter Text widget get() In-Reply-To: <682C7C6A-9172-4673-955E-5B775115A689@gmail.com> References: <682C7C6A-9172-4673-955E-5B775115A689@gmail.com> Message-ID: <20080705084539.M83810@velseis.com.au> > Hey guys. I am having trouble understanding the get() method from > the Tkinter Text() widget. It isn't like the entry.get() one I am > used to. I know you have to put tags in, or at least I read. I > tried this but it didn't work. I think I was putting the tags in > wrong but I am not sure. I just need an example. So if someone > could maybe modify this code to get EVERYTHING inside the text widget. > > text = Text(parent) > text.pack() > > text.insert(END, "I am text!") > > Of course, I will have much more text, but I still want to get > everything in the box. > The arguments to the get method of the Text widget are strings in the form of "line.position". So, text.get('1.5', '2.7') returns the text from line 1 position 5 to line 2 position 7. There are also some special tagged names such as END and SEL. So, if you want to get all the text in your Text widget, text.get('1.0', END) will do the trick. I recommend finding the appropriate documentation at http://www.pythonware.com/library/tkinter/introduction/tkinter-reference.htm Regards, John From bignose+hates-spam at benfinney.id.au Sat Jul 19 20:04:59 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 20 Jul 2008 10:04:59 +1000 Subject: __del__ methods References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> Message-ID: <87hcalxvx0.fsf@benfinney.id.au> "Robert Rawlins" writes: > What is the benefit of extending the base 'object' class? What does that > give me that en empty, non subclassed object doesn't? In Python 2.x, "classic" classes (which are not part of the unified type hierarchy) are deprecated, and exist only for backward compatibility with old code. You need to create "new-style" classes by inheriting from some class that is part of the unified type hierarchy; if there is no obvious candidate, 'object' is the recommended choice. In Python 3.0, classic classes are no longer supported and this issue goes away. -- \ Q: ?I've heard that Linux causes cancer...? Torvalds: ?That's a | `\ filthy lie. Besides, it was only in rats and has not been | _o__) reproduced in humans.? ?Linus Torvalds | Ben Finney From straton at lampsacos.demon.co.uk Wed Jul 16 12:29:38 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Wed, 16 Jul 2008 17:29:38 +0100 Subject: Eclipse, Pydev, question In-Reply-To: References: Message-ID: I have a small project for further development in eclipse, using the pyDev plug-in. I am working on foo.py and bar.pyc is also in the directory. bar.py is not in the directory; it is someone else's (confidential) file, and I don't get the python source. Can I run bar.pyc from eclipse ? From spython01 at gmail.com Mon Jul 21 18:39:13 2008 From: spython01 at gmail.com (Samir) Date: Mon, 21 Jul 2008 15:39:13 -0700 (PDT) Subject: Converting List of String to Integer References: Message-ID: On Jul 21, 6:15?pm, Andrew Freeman wrote: > Samir wrote: > > On Jul 21, 3:20 pm, Gary Herron wrote: > > >> Samir wrote: > > >>> Hi Everyone, > > >>> I am relatively new to Python so please forgive me for what seems like > >>> a basic question. > > >>> Assume that I have a list, a, composed of nested lists with string > >>> representations of integers, such that > > >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > > >>> I would like to convert this to a similar list, b, where the values > >>> are represented by integers, such as > > >>> b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > >>> I have unsuccessfully tried the following code: > > >>> n = [] > >>> for k in a: > >>> ? ? n.append([int(v) for v in k]) > >>> print n > > >>> Does anyone know what I am doing wrong? > > >>> Thanks in advance. > > >>> Samir > >>> -- > >>>http://mail.python.org/mailman/listinfo/python-list > > >> You didn't tell us how it failed for you, so I can't guess what's wrong. > > >> However, your code works for me: > > >> ?>>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > >> ?>>> n = [] > >> ?>>> for k in a: > >> ... ? ?n.append([int(v) for v in k]) > >> ... > >> ?>>> print n > >> [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > >> (Although you seem to have confused variables b and n.) > > >> Gary Herron- Hide quoted text - > > >> - Show quoted text - > > > Hi Gary, > > > Thanks for your quick response (and sorry about mixing up b and n). > > For some reason, the logic I posted seems to work ok while I'm using > > the Python shell, but when used in my code, the program just hangs. > > It never outputs the results. ?Below is the code in its entirety. ?Is > > there a problem with my indendentation? > > > a = n = [] > > t = """ > > 1 2 > > 3 > > 4 5 6 > > 7 8 9 0 > > """ > > > d = t.split("\n") > > > for x in range(1,len(d)-1): > > ? ? a.append(d[x].split(" ")) > > print a > > > for k in a: > > ? ? n.append([int(v) for v in k]) > > > print n > > > Thanks again. > > > Samir > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I think this will work better, a sub-list comprehension of sorts: > n = [[int(i) for i in k] for k in a] > > here is an ipython interactive session using it: > In [1]: a = n = [] > > In [2]: t = """ > ? ?...: 1 2 > ? ?...: 3 > ? ?...: 4 5 6 > ? ?...: 7 8 9 0 > ? ?...: """ > > In [3]: > > In [4]: d = t.split("\n") > > In [5]: for x in range(1,len(d)-1): > ? ?...: ? ? a.append(d[x].split(" ")) > ? ?...: ? ? > ? ?...: ? ? > > In [6]: a > Out[6]: [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > > In [7]: n = [[int(i) for i in k] for k in a] > > In [8]: n > Out[8]: [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > -- > Andrew- Hide quoted text - > > - Show quoted text - Andrew, Thanks for the tip, though the syntax makes my head spin a bit in trying to comprehend it. For my small list, I didn't notice a discernible increase in speed, but I may have to try it with a larger list size. Incidentally, I had never heard of iPython but from their web site, it looks like an interesting tool. I'll have to check it out. Thanks. Samir From stefan_ml at behnel.de Thu Jul 17 10:29:21 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 17 Jul 2008 14:29:21 +0000 (UTC) Subject: Babelfish translation ... References: <487F2633.6000703@gmail.com> Message-ID: Stef Mientki gmail.com> writes: > Although it works functionally, > it can take lots of time waiting for the translation. > > What I basically do is, after selecting a new string to be translated: > > kwds = { 'trtext' : line_to_be_translated, 'lp' :'en_nl'} > soup = BeautifulSoup (urlopen(url, urlencode ( kwds ) ) ) > translation= soup.find ( 'div', style='padding:0.6em;' ).string > self.Editor_Babel.SetLabel ( translation ) You should give lxml.html a try. http://codespeak.net/lxml/ It can parse directly from HTTP URLs (no need to go through urlopen), and it frees the GIL while parsing, so it will become efficient to create a little Thread that doesn't do more than parsing the web site, as in (untested): def read_bablefish(text, lang, result): url = BABLEFISH_URL + '?' + urlencode({'trtext':text, 'lp':lang}) page = lxml.html.parse(url) for div in page.iter('div'): style = div.get('style') if style is not None and 'padding:0.6em;' in style: result.append( lxml.html.tostring(div, method="text", with_tail=False)) result = [] thread = threading.Thread(target=read_bablefish, args=("...", "en_nl", result)) thread.start() while thread.isAlive(): # ... do other stuff if result: print result[0] Stefan From mrkafk at gmail.com Thu Jul 17 07:45:06 2008 From: mrkafk at gmail.com (mk) Date: Thu, 17 Jul 2008 13:45:06 +0200 Subject: storing references instead of copies in a dictionary Message-ID: Hello everyone, I'm storing functions in a dictionary (this is basically for cooking up my own fancy schmancy callback scheme, mainly for learning purpose): >>> def f2(arg): ... return "f2 " + arg ... >>> >>> def f1(arg): ... return "f1" + arg ... >>> a={'1': f1, '2': f2} >>> >>> [ x[1](x[0]) for x in a.items() ] ['f11', 'f2 2'] Well, neat. Except if I change function definitions now, old functions are called. And rightly: {'1': , '2': } >>> f1 >>> >>> def f1(arg): ... return "NEW f1 " + arg ... >>> f1 The address of function f1 has obviously changed on redefinition. Storing value copies in a dictionary on assignment is a reasonable default behaviour. However, in this particular case I need to specifically store _references to objects_ (e.g. f1 function), or should I say _labels_ (leading to objects)? Of course, I can basically update the dictionary with a new function definition. But I wonder, is there not a way _in general_ to specifically store references to functions/variables/first-class objects instead of copies in a dictionary? From deets at nospam.web.de Mon Jul 21 07:30:40 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 21 Jul 2008 13:30:40 +0200 Subject: Please recommend a RPC system working with twisted. References: <312040c6-4011-451e-8a45-f982c2e4462f@j1g2000prb.googlegroups.com> Message-ID: <6ejacrF7dd9lU1@mid.uni-berlin.de> ??? wrote: > Hi all, > > I'm looking for an RPC system working with twisted. > > 1. Binary. I want it run faster than any xml based RPC. > > 2. Bidirectional. Unlike HTTP, on which the client has to poll the > sever for events, the server should "call" the client's method to > notify events. > > 3. C/Python support. Part of the system shall be written in C. CORBA, especially the very good omniORB-implementation for Python. > 4. Could easily integrated with twisted. > > Unfortunately, there seems no such resolution existed. So maybe I > have to give up some requirements. The last one, yes. At least it should be possible to integrate using threading though. And *maybe* you can even provide some event loop integration as well - I think omniORB should be that flexible. Diez From bdesth.quelquechose at free.quelquepart.fr Sat Jul 26 03:58:39 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 26 Jul 2008 09:58:39 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> Message-ID: <488af527$0$14761$426a74cc@news.free.fr> Matthew Fitzgibbons a ?crit : (snip) > As for !=, it seems like there is a technical reason for the behavior. > Remember, there is no default __ne__ method, so the behavior you want > would have to live in the interpreter. If __ne__ isn't defined, it would > have to try to call __eq__ and negate the result. Is there any other > lookup that is treated this way? There are quite a few cases in Python where there are both a specific magic method *and* a default behaviour based on another magic method if the specific one is not implemented. Just out of my mind: * __contains__ and __getitem__ * __iter__ and __getitem__ * __nonzero__ and __len__ Not to mention the fact that lookup rules even check the existence of special methods on class attributes (remember the descriptor protocol ?)... From waldemar.rymarkiewicz at gmail.com Thu Jul 24 10:30:57 2008 From: waldemar.rymarkiewicz at gmail.com (waldek) Date: Thu, 24 Jul 2008 07:30:57 -0700 (PDT) Subject: ctypes and reading value under pointer passed as param of a callback Message-ID: Hi, I'm using C dll with py module and wanna read value (buffer of bytes) returned in py callback as parameter passed to dll function. -------------------------------------------------- def mycallback(data, size): # how to read data buffer here ? return 0 cbfunc = CFUNCTYPE(c_int, POINTER(c_uint8), c_int) mydll = cdll.somedll mdll.foo(cbfunct) --------------------------------------------------------------- Question: How to get bytes from the buffer passed to mycallback ??? Let's assume that the buffer consist of 4 bytes 4 bytes 8 bytes. I tried unpack("ii8s", data[0]) and nothing. I tried different ctypes passed to callback and nothing. Any sugestions ? Thanks, Waldek From fetchinson at googlemail.com Thu Jul 10 17:23:24 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 10 Jul 2008 14:23:24 -0700 Subject: Python with Ecmascript In-Reply-To: References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <486fe241$0$867$ba4acef3@news.orange.fr> Message-ID: >> Is there a way to do similar things on linux? > > NJSModule? > http://en.wikipedia.org/wiki/NJS This seems to be very good indeed. Just downloaded njs but the only njsmodule version I could find was for python 2.1. Does anyone have a recent copy? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From mtobis at gmail.com Tue Jul 22 12:52:56 2008 From: mtobis at gmail.com (Michael Tobis) Date: Tue, 22 Jul 2008 09:52:56 -0700 (PDT) Subject: Not entirely serious: recursive lambda? References: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> Message-ID: Thanks all! What a remarkable set of answers, intelligent, thought provoking and informative without exception. Of course, now I can't use Paul's version; it hardly counts as a japh if someone else wrote it! It is probably the closest to my original vision, alas. Miles' second suggestion was the one I was fumbling toward; I will study it. No spoilers please. best mt From martinnorth at westnet.com.au Fri Jul 11 07:09:27 2008 From: martinnorth at westnet.com.au (martinnorth) Date: Fri, 11 Jul 2008 21:09:27 +1000 Subject: MySQLdb will only import for root Message-ID: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> Hi, I am running Python and MySQL on Ubuntu and have installed MySQLdb. If I try to import MySQLdb I get the following error: ActivePython 2.5.2.2 (ActiveState Software Inc.) based on Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08) [GCC 3.3.1 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb Traceback (most recent call last): File "", line 1, in ImportError: No module named MySQLdb But if I lrun python as the root user it imports fine. Can anyone suggest what might be wrong with the installation? Or is there nothing wrong? I haven't seen any examples that mentioned being root to import a module. Martin From geraint.williams at gmail.com Tue Jul 1 11:41:11 2008 From: geraint.williams at gmail.com (GHZ) Date: Tue, 1 Jul 2008 08:41:11 -0700 (PDT) Subject: Installing paramiko and pycrypto References: <4856638d-1c86-4d4d-ba50-4a808f722f10@79g2000hsk.googlegroups.com> Message-ID: <17d5049b-89cd-40af-81a2-80306a86eaf8@i36g2000prf.googlegroups.com> I installed from here: http://bazaar-vcs.org/WindowsInstall first pycrypto-2.0.1.win32-py2.5.zip then paramiko-1.7.1-ctypes.win32.exe From theller at python.net Thu Jul 24 11:01:28 2008 From: theller at python.net (Thomas Heller) Date: Thu, 24 Jul 2008 17:01:28 +0200 Subject: ctypes and reading value under pointer passed as param of a callback In-Reply-To: References: Message-ID: <6erjpeF88slmU1@mid.individual.net> waldek schrieb: > Hi, > > I'm using C dll with py module and wanna read value (buffer of bytes) > returned in py callback as parameter passed to dll function. > The callback receives a pointer instance. You can dereference the pointer to read individual bytes in this way: print data[0], data[5], data[42] or use slicing to read a bunch of bytes: print data[0:42] So, you probably want something like this: > -------------------------------------------------- > def mycallback(data, size): > # how to read data buffer here ? print data[:size] > return 0 > > cbfunc = CFUNCTYPE(c_int, POINTER(c_uint8), c_int) > > mydll = cdll.somedll > mdll.foo(cbfunct) > --------------------------------------------------------------- > > Question: How to get bytes from the buffer passed to mycallback ??? > Let's assume that the buffer consist of 4 bytes 4 bytes 8 bytes. > > I tried unpack("ii8s", data[0]) and nothing. I tried different ctypes > passed to callback and nothing. Thomas From __peter__ at web.de Sun Jul 13 03:12:03 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 13 Jul 2008 09:12:03 +0200 Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> Message-ID: Yosifov Pavel wrote: > Whats is the way to clone "independent" iterator? I can't use tee(), > because I don't know how many "independent" iterators I need. copy and > deepcopy doesn't work... There is no general way. For "short" sequences you can store the items in a list which is also the worst-case behaviour of tee(). What are you trying to do? Peter From fredrik at pythonware.com Tue Jul 22 11:25:43 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 17:25:43 +0200 Subject: convert list of lists to list In-Reply-To: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> References: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> Message-ID: antar2 wrote: > Is there a way to convert list_of_listsA to list_of_listsB, where one > list in listof lists A is one element of listB? > list_of_listsA: > [['klas*', '*', '*'], > ['mooi*', '*', '*', '*'], > ['koe'], > ['arm*', '*', '*(haar)'], > ['groei*', '*', '*', '*', '*']] > > listB: > ['klas* * *', 'mooi* * * *, 'koe', 'arm* * * (haar)', 'groei* * * * > *'] if there's only one level of recursion, and the lists aren't too long, you can simply do: sum(list_of_lists, []) (this has quadratic performance, so don't use it for large structures) for recursive solutions, see: http://www.google.com/search?q=flatten+lists+python From aahz at pythoncraft.com Tue Jul 1 09:14:04 2008 From: aahz at pythoncraft.com (Aahz) Date: 1 Jul 2008 06:14:04 -0700 Subject: [Employment] New TurboGears Job in Eugene, OR References: <4df107ec-7193-412a-addf-ecbb4b6a3f3a@p25g2000hsf.googlegroups.com> Message-ID: In article , Tim Roberts wrote: >aahz at pythoncraft.com (Aahz) wrote: >>Paul McNett

wrote: >>> >>>They want an expert for a maximum of $25 per hour? If they find someone, >>>it'll be a pretty good bullshitter looking for experience. >> >>Note that it's an "academic year" position -- lots and lots of vacation >>time. This would actually be a good job for e.g. a retired person who >>doesn't need lots of money. Also note that Eugene is not exactly an >>area with a high cost of living. > >I take it you're not from Oregon. Eugene is the second largest city. >Prices are not quite up to the San Jose at its peak, but there are no >bargains left in any of the urban sections of the state. It's certainly >far more expensive here than in the midwest or most of the south. Depends where you look in the midwest, of course. It's certainly cheaper than Minneapolis or Chicago. It's even cheaper than Cleveland or Columbus. It's cheaper than Atlanta. So yeah, I stick by my comment. It's all a matter of which perspective you're looking from. ;-) FYI, I'm pulling my info from http://swz.salary.com/CostOfLivingWizard/layouthtmls/coll_metrodetail_58.html which differs some from http://www.eugenechamber.com/relo/facts_figures.htm -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From miki.tebeka at gmail.com Fri Jul 4 00:53:16 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 3 Jul 2008 21:53:16 -0700 (PDT) Subject: manipulating movie files with Python References: Message-ID: <863b1ce8-9114-442e-b7f2-4c1391d5162d@z24g2000prf.googlegroups.com> Hello, > I would like to write a python script which could take a movie file name > (avi, mov, mpg) along with a start and stop time as parameters, and > return to me a ?new movie file just containing that section of the > original which I'm interested in. Is there a Python library which could > already perform such magic? Thanks for any suggestions. I think you'll find ffmpeg the right tool for the job. HTH, -- Miki http://pythonwise.blogspot.com From paul at boddie.org.uk Tue Jul 22 06:28:09 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 22 Jul 2008 03:28:09 -0700 (PDT) Subject: xpathEval fails for large files References: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> Message-ID: <720d459e-fc11-482c-91c2-4197feb295d6@s50g2000hsb.googlegroups.com> On 22 Jul, 11:00, Kanchana wrote: > > I tried to extract some data with xpathEval. Path contain more than > 100,000 elements. > > doc = libxml2.parseFile("test.xml") > ctxt = doc.xpathNewContext() > result = ctxt.xpathEval('//src_ref/@editions') > doc.freeDoc() > ctxt.xpathFreeContext() Another note on libraries: if you want a pure Python library which works on top of libxml2 and the bundled Python bindings, consider libxml2dom [1]. > this will stuck in following line and will result in high usage of > CPU. > result = ctxt.xpathEval('//src_ref/@editions') > > Any suggestions to resolve this. How big is your document and how much memory is the process using after you have parsed the document? Sometimes, you won't be able to effectively handle very large documents by having them loaded completely in memory because you'll require more main memory than your system has available, making operations on the document somewhat inefficient. > Is there any better alternative to handle large documents? Fredrik pointed out a few. There's also xml.dom.pulldom and xml.sax in the standard library - the latter attractive mostly if you have previous experience with it - providing stream-based processing of documents if you don't mind writing more code. Paul [1] http://www.python.org/pypi/libxml2dom From timr at probo.com Sun Jul 6 00:59:59 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 06 Jul 2008 04:59:59 GMT Subject: win32com.client (Howto edit Contacts in Outlook) References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: "Bill Davy" wrote: > >I am trying to edit Contacts in Outlook. This is so I can transfer numbers >from my address book which is an Excel spreadsheet to my mobile phone. Are you actually running Outlook? Your news posting was made from Outlook Express, and Outlook Express cannot be controlled by COM (although MAPI works). -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mrkafk at gmail.com Mon Jul 21 12:19:53 2008 From: mrkafk at gmail.com (mk) Date: Mon, 21 Jul 2008 18:19:53 +0200 Subject: Please recommend a RPC system working with twisted. In-Reply-To: <312040c6-4011-451e-8a45-f982c2e4462f@j1g2000prb.googlegroups.com> References: <312040c6-4011-451e-8a45-f982c2e4462f@j1g2000prb.googlegroups.com> Message-ID: > Unfortunately, there seems no such resolution existed. So maybe I > have to give up some requirements. Why not PYRO? Note: I haven't used it. From mrkafk at gmail.com Sun Jul 13 06:41:50 2008 From: mrkafk at gmail.com (mk) Date: Sun, 13 Jul 2008 12:41:50 +0200 Subject: Using SWIG to build C++ extension In-Reply-To: <4877ec43$0$877$ba4acef3@news.orange.fr> References: <4877ec43$0$877$ba4acef3@news.orange.fr> Message-ID: Hello Bas, Thanks, man! Your recipe worked on Debian system, though not on RedHat, and I still have no idea why. :-) Anyway, I have it working. Thanks again. > I took your example files and did the following: > changed the #include "edit_distance.h" to #include "edit_distance.c" > in the edit_distance.i file. > Then I changed the first few lines of your function definition > unsigned int edit_distance( const char* c1, const char* c2 ) > { > std::string s1( c1), s2( c2); > and also adapted the signature in the edit_distance.i file. > Then > swig -shadow -c++ -python edit_distance.i > g++ -c -fpic -I/usr/include/python edit_distance_wrap.cxx > g++ -shared edit_distance_wrap.o -o _edit_distance.so From r_e_s_01 at ZZZyahoo.com Thu Jul 10 21:03:24 2008 From: r_e_s_01 at ZZZyahoo.com (r.e.s.) Date: Thu, 10 Jul 2008 18:03:24 -0700 Subject: Can this program be shortened? Measuring program-length? References: <7Rtdk.16747$N87.3559@nlpi068.nbdc.sbc.com> <2ed6de5b-bf2f-4e3d-94af-c8e6c6a28f95@s50g2000hsb.googlegroups.com> Message-ID: "r.e.s." wrote ... > wrote ... >> "r.e.s." wrote: >>> Can the following program be shortened? ... >>> >>> def h(n,m): >>> E=n, >>> while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n >>> return n >>> h(9,9) >>> >> >> Some ideas... >> >> # h is your version >> def h(n,m): >> E=n, >> while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n >> return n >> >> def g(n,m): >> E=n, >> while E*m:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n ^ g >> return n >> >> def f(n,m): >> E=n, >> while E*m:n=h(n+1,m-1);E=(E[0]>0)*(E[0]-1,)*n+E[1:] ^ f >> return n >> >> def e(n,m): >> E=[n] >> while E*m:n=h(n+1,m-1);E[:1]=(E[0]>0)*[E[0]-1]*n ^ e >> return n >> >> # some tests >> print h(1,1), h(2,1), h(0,2) >> print g(1,1), g(2,1), g(0,2) >> print f(1,1), f(2,1), f(0,2) >> print e(1,1), e(2,1), e(0,2) > > Very instructive! Thank you for the "step-by-step". I forgot to mention the obvious typos. Thanks again. From victorsubervi at gmail.com Tue Jul 15 08:42:16 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 15 Jul 2008 14:42:16 +0200 Subject: Characters Being Misread Message-ID: <4dc0cfea0807150542j52bf645dy54d604088c2f950c@mail.gmail.com> Hi; Forgive multiple posts in one day: online very infrequently I'm having the darndest time trying to figure out how the character '\b0' is being read in "('\x0c')" >>> test = re.search('(?<=\\b)[0]', '\x0c0') >>> test.group(0) '0' >>> type('\x0c') >>> import binascii >>> binascii.unhexlify('\x0c') Traceback (most recent call last): File "", line 1, in binascii.unhexlify('\x0c') TypeError: Odd-length string What gives here? Here's another one: >>> rtf_markup = '\viewkind4\\uc1\\pard\nowidctlpar\\qc\\i\x0c0\x0cs36' >>> a = [] >>> a.append(re.compile('\\i').match(rtf_markup, 1)) >>> a [<_sre.SRE_Match object at 0x011802F8>] >>> a = [] >>> a.append(re.compile('\\qc').match(rtf_markup, 1)) [None] What's the problem? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Mon Jul 28 16:28:33 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 28 Jul 2008 22:28:33 +0200 Subject: Is it allowed to use function results as default arguments ? Message-ID: <488E2BF1.8020003@gmail.com> hello, I've a perfect working procedure, at least as far I've tested it it works perfect. But I was just experimenting with inspect, and saw that the default argument was not parsed correctly. So I wonder if this is allowed: def Get_Relative_Path ( target, base=os.curdir ) : ... As inspect returns the following: (['target', 'base'], None, None, ('.',)) thanks, Stef Mientki From spython01 at gmail.com Wed Jul 23 21:30:11 2008 From: spython01 at gmail.com (Samir) Date: Wed, 23 Jul 2008 18:30:11 -0700 (PDT) Subject: Request Help Debugging Program References: <898dfe7a-4133-4337-8243-f4936b8a8092@8g2000hse.googlegroups.com> <9ba3340e-1048-4958-b988-d2a83559111d@d77g2000hsb.googlegroups.com> Message-ID: On Jul 23, 9:14?pm, mzdude wrote: > On Jul 23, 6:30?pm, Samir wrote: > > > Hi Everyone, > > > def findSumOfDivisor(n): > > > ? ? return sum(divisor) ? ? ? ? ? ? ? ?# fine using function sum() > > > ? ? ? ? sum = findSumOfDivisor(i) ? ? ?# then find the sum of its divisors > > oops redefine what sum is. > > > > >>> x = [1,2] > >>> sum(x) > 3 > >>> sum = 4 > >>> sum(x) > > Traceback (most recent call last): > ? File "", line 1, in > ? ? sum(x) > TypeError: 'int' object is not callable > > > > - Hide quoted text - > > - Show quoted text - I am an IDIOT! Thanks, mzdude! That did the trick. Sorry for posting something this stupid. From bruno.desthuilliers at gmail.com Fri Jul 18 10:13:41 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 18 Jul 2008 07:13:41 -0700 (PDT) Subject: substitution of list elements References: <247ab26d-ba98-42cc-bf6e-738b4b32a70c@q28g2000prh.googlegroups.com> Message-ID: <9cf77901-60ee-4754-901b-a43f1fc1ef66@f40g2000pri.googlegroups.com> On 18 juil, 14:33, antar2 wrote: > I want to replace each first element in list 5 that is equal to the > first element of the list of lists4 by the fourth element. I wrote > following code that does not work: > > list4 = [['1', 'a', 'b', 'c'], ['2', 'd', 't', 'e'], ['8', 'g', 'q', > 'f']] > list5 = ['1', '2', '3'] > > for j in list4: > for k in list5: > if j[0] == k: > k = j[3] > print list5 > Wanted result: ['c', 'e', '3'] > > thanks! select = lambda item, lst: (item, lst[3])[item == lst[0]] list5[:] = [select(*pair) for pair in zip(list5, list4)] # or if you prefer a more procedural solution: for index, (item, lst) in enumerate(zip(list5, list4)): if item == lst[0]: list5[index] = lst[3] From ndbecker2 at gmail.com Tue Jul 1 11:55:34 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 01 Jul 2008 11:55:34 -0400 Subject: dynamically load from module import xxx References: Message-ID: Guilherme Polo wrote: > On Tue, Jul 1, 2008 at 12:11 PM, Neal Becker wrote: >> What is a good way to emulate: >> >> from module import xxx >> where 'module' is a dynamically generated string? >> >> __import__ ('modulename', fromlist=['xxx']) >> >> seems to be what I want, but then it seems 'xxx' is not placed in >> globals() (which makes me wonder, what exactly did fromlist do?) > > fromlist is used for importing subpackages/submodules of the first arg > of __import__. Since you are using "modulename", I'm guessing it is > not a package, fromlist will do nothing for you. > To solve your problem you could do getattr(__import__('modulename'), > 'xxx'). This seems to be what I want, don't know if there is a simpler way: stuff =['A','B'] module = __import__ (modulename) for e in stuff: globals().update({e : module.__dict__[e]}) From gagsl-py2 at yahoo.com.ar Wed Jul 30 22:40:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 23:40:21 -0300 Subject: Optimizing size of very large dictionaries References: <1217464179.31710.1266222419@webmail.messagingengine.com> Message-ID: En Wed, 30 Jul 2008 21:29:39 -0300, escribi?: > Are there any techniques I can use to strip a dictionary data > structure down to the smallest memory overhead possible? > > I'm working on a project where my available RAM is limited to 2G > and I would like to use very large dictionaries vs. a traditional > database. > > Background: I'm trying to identify duplicate records in very > large text based transaction logs. I'm detecting duplicate > records by creating a SHA1 checksum of each record and using this > checksum as a dictionary key. This works great except for several > files whose size is such that their associated checksum > dictionaries are too big for my workstation's 2G of RAM. You could use a different hash algorithm yielding a smaller value (crc32, by example, fits on an integer). At the expense of having more collisions, and more processing time to check those possible duplicates. -- Gabriel Genellina From drakonik at gmail.com Sun Jul 20 09:57:55 2008 From: drakonik at gmail.com (Nick Dumas) Date: Sun, 20 Jul 2008 09:57:55 -0400 Subject: a question that can accelerate learning python? In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Simple. dir(object) wangziqing1984 at hotmail.com wrote: > I am new to python .But interest in it . > I think if python could provide a method that show every method of an > object or an module.it will be great! We can save a lot of time to > find the document > take win32com as an example: > if code like this > "win32com.query"(or some other name that means query) > it would return a list of module or method that win32com have. > Does python have implement such interface yet? 'cause I have not so > familiar with python. > best wishes! > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkiDRGMACgkQLMI5fndAv9g76ACdGJsxrSuaFot0SnHmlnFYaw7W muoAn0KZvyG2PgE2hoaQZLIjD5YvBYuK =WFxU -----END PGP SIGNATURE----- From sterlingsomers at gmail.com Thu Jul 31 11:13:32 2008 From: sterlingsomers at gmail.com (sterling) Date: Thu, 31 Jul 2008 08:13:32 -0700 (PDT) Subject: win32com ChartObject pythonwin vs idle References: <670b57b7-d48e-44c0-abd0-b6772d23688d@79g2000hsk.googlegroups.com> Message-ID: <9236f4cd-8808-411a-835a-04e75e1927c1@34g2000hsf.googlegroups.com> On Jul 31, 4:28?am, Tim Golden wrote: > sterling wrote: > > I'm curious as to why the difference between IDLE and pythonWin when > > using win32com. > > opening an excel file, i've attempted to grab the chart information > > out of the file. > > > commands like co = ChartObjects(1) ?works in pythonWin but doesn't > > work in IDLE. > > > however, on both co = chartobjects(1) works just fine. > > I can't speak for IDLE vs PythonWin but in general > case-sensitivity of win32com stuff is related to > early vs late Dispatch. If you've explicitly generated > proxy modules for the Excel objects (via makepy, > EnsureDispatch or whatever) then those are Python > modules with case-sensitivity. If you're using dynamic > dispatch then Python is simply passing your attribute > name along to COM, which isn't case-sensitive, so either > case will work. > > Not sure why IDLE vs PythonWin should make a difference > here, but maybe the above explanation sheds some light... > > TJG Thanks Tim. I'm wondering if it's an OS issues with Vista (I'm strangly ashamed to admit that both my laptop and main computer are running it). I decided to try the same code on my main computer (do most of my work on my laptop) and the exact same thing has happened: I can run it in pythonwin and not idle. I found that I can't even run Open (I must have been running open() previously): i.e. >>> import win32com.client >>> ex = win32com.client.Dispatch("Excel.Application") >>> wb = ex.Workbooks.Open("C:\Temp\SalesChart.xls") Traceback (most recent call last): File "", line 1, in wb = ex.Workbooks.Open("C:\Temp\SalesChart.xlsx") File "C:\Python25\Lib\site-packages\win32com\client\dynamic.py", line 467, in __getattr__ if self._olerepr_.mapFuncs.has_key(attr): return self._make_method_(attr) File "C:\Python25\Lib\site-packages\win32com\client\dynamic.py", line 295, in _make_method_ methodCodeList = self._olerepr_.MakeFuncMethod(self._olerepr_.mapFuncs[name], methodName,0) File "C:\Python25\Lib\site-packages\win32com\client\build.py", line 297, in MakeFuncMethod return self.MakeDispatchFuncMethod(entry, name, bMakeClass) File "C:\Python25\Lib\site-packages\win32com\client\build.py", line 318, in MakeDispatchFuncMethod s = linePrefix + 'def ' + name + '(self' + BuildCallList(fdesc, names, defNamedOptArg, defNamedNotOptArg, defUnnamedArg, defOutArg) + '):' File "C:\Python25\Lib\site-packages\win32com\client\build.py", line 604, in BuildCallList argName = MakePublicAttributeName(argName) File "C:\Python25\Lib\site-packages\win32com\client\build.py", line 542, in MakePublicAttributeName return filter( lambda char: char in valid_identifier_chars, className) File "C:\Python25\Lib\site-packages\win32com\client\build.py", line 542, in return filter( lambda char: char in valid_identifier_chars, className) UnicodeDecodeError: 'ascii' codec can't decode byte 0x83 in position 52: ordinal not in range(128) but the exact same code works in PythonWin. Perhaps I will just find a way to code everything I want in the older lowercase. From benjamin.kaplan at case.edu Tue Jul 1 19:23:29 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 1 Jul 2008 19:23:29 -0400 Subject: Required items in a form In-Reply-To: <45yak.331$Ae3.313@trnddc05> References: <45yak.331$Ae3.313@trnddc05> Message-ID: On Tue, Jul 1, 2008 at 6:20 PM, Brandon wrote: > What I'm trying to do is essentially force a user to fill in required items > in a form, which will be saved to a database. How can I get it so that > once > the user clicks "OK" on the dialog box, it transfers control back to the > form, and not save the empty fields into the database? > > What GUI toolkit are you using? > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kirk at daycos.com Tue Jul 1 11:24:00 2008 From: kirk at daycos.com (Kirk Strauser) Date: Tue, 01 Jul 2008 10:24:00 -0500 Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> Message-ID: <87vdzpmxv3.fsf@internal.daycos.com> At 2008-06-30T19:34:53Z, Mike writes: > I should have say "why embedding HTML into Python is not good enough?" ;=) I'm a programmer and would be able to cope with embedding HTML in assembler if the need arose. Having said that, embedding HTML in anything but HTML tends to be a bad idea in the long run. Inevitably, you're going to want to move stuff around, and find out that you can't just move print "

    " for item in itemlist: print "
  • %s
  • " % item print "
" up near the top because you don't actually define itemlist until near the end of your function, because it's built on the results of a bunch of other code. So then you "solve" the problem by leaving that snippet where it is and moving all the other HTML print commands after it. Oh, crud! You realize too late that some of your print commands have side effects: for item in deletelist: print "

Deleting %s: %s

" % (str(item), mangle(item)) and if you run that code *after* you generate itemlist, the results will be all screwed up. So you go back and move all of your logic to the top of the function and all of the HTML print statements to the bottom. And then you realize you've written your very own page template, and that it's ugly, and that you should've used something different from the very beginning. That's why you don't embed HTML in Python, at least not for anything more complicated than "Hello, world". -- Kirk Strauser The Day Companies From google at mrabarnett.plus.com Thu Jul 10 13:35:33 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 10 Jul 2008 10:35:33 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: Message-ID: <8feab8ce-1e09-4438-b00a-3b31956c56af@k37g2000hsf.googlegroups.com> On Jul 10, 4:56?am, Jordan wrote: > I am trying to rewrite some C source code for a poker hand evaluator > in Python. ?Putting aside all of the comments such as just using the C > code, or using SWIG, etc. ?I have been having problems with my Python > code not responding the same way as the C version. > > C verison: > > unsigned find_fast(unsigned u) > { > ? ? unsigned a, b, r; > ? ? u += 0xe91aaa35; > ? ? u ^= u >> 16; > ? ? u += u << 8; > ? ? u ^= u >> 4; > ? ? b ?= (u >> 8) & 0x1ff; > ? ? a ?= (u + (u << 2)) >> 19; > ? ? r ?= a ^ hash_adjust[b]; > ? ? return r; > > } > > my version (Python, hopefully ;)): > > def find_fast(u): > ? ? u += 0xe91aaa35 > ? ? u ^= u >> 16 > ? ? u += u << 8 > ? ? u ^= u >> 4 > ? ? b ?= (u >> 8) & 0x1ff > ? ? a ?= (u + (u << 2)) >> 19 > ? ? r ?= a ^ hash_adjust[b] > ? ? return r > > As far as I understand the unsigned instructions in C just increase > amount of bytes the int can hold, and Python automatically converts to > longs which have infinite size when necessary, so I am not sure why I > am getting different results. > > I assume that I am missing something fairly simple here, so help a > n00b out if you can :) > > Thanks in advance, > > jnb You want to restrict the values to 32 bits. The result of + or << may exceed 32 bits, so you need to mask off the excess bits afterwards. def find_fast(u): mask = 0xffffffff u = (u + 0xe91aaa35) & mask u ^= u >> 16 u = (u + (u << 8)) & mask # can get away with only 1 mask here u ^= u >> 4 b = (u >> 8) & 0x1ff a = ((u + (u << 2)) & mask) >> 19 # can get away with only 1 mask here r = a ^ hash_adjust[b] return r HTH From larry.bates at websafe.com` Mon Jul 14 18:27:50 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 14 Jul 2008 17:27:50 -0500 Subject: Using Python To Launch Python In-Reply-To: References: Message-ID: aha wrote: > Hello All, > I have a situation where I can count on a Python installation being > available on a system, but I can't count on it being a version of > Python needed by my application. Since my application has it's own > version of Python installed with it how should I use the system Python > to launch the version of Python that launches my Application. Yes, > this is a convoluted process, but not all Pythons are built the > same :) > > Right now I am leaning towards using exec to start a new process, but > I thought I would check to see if anyone else has had the need to > perform a task similar to this one. > > AHA You didn't tell us what operating system, but if by chance it is Windows you should use py2exe to package up your program (along with the proper pythonXX.dll) into a distributable package. On Linux, others have posted answers. -Larry From russblau at hotmail.com Wed Jul 9 16:41:17 2008 From: russblau at hotmail.com (Russell Blau) Date: Wed, 9 Jul 2008 16:41:17 -0400 Subject: variable question References: <01da01c8e1fb$7615a4f0$a701a8c0@office.ipglobal.net> Message-ID: "Support Desk" wrote in message news:01da01c8e1fb$7615a4f0$a701a8c0 at office.ipglobal.net... > I am trying to assign a variable using an if / else statement like so: > If condition1: > Variable = something > If condition2: > Variable = something else > Do stuff with variable. > > But the variable assignment doesn't survive outside the if statement. Is > there > any better way to assign variables using an if statement or exception so I > don't > have to write two almost identical if statements. This is probably a dumb > question. The variable assignment should survive outside the if statements: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> if "yes" == "no": value = "impossible" >>> if "no" == "no": value = "possible" >>> print value possible >>> You probably want to watch out for the possibility that both Condition1 and Condition2 are false; otherwise, you will get a NameError when you try to access Variable without initializing it. (By the way, as a matter of style, Python variable names are usually written in all lower-case letters.) Russ From steve at REMOVE-THIS-cybersource.com.au Thu Jul 31 18:25:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Jul 2008 22:25:23 GMT Subject: Standard module for parsing emails? References: <6fb93eFap7j5U1@mid.individual.net> <00a11e11$0$20313$c3e8da3@news.astraweb.com> Message-ID: <00a2373d$0$20313$c3e8da3@news.astraweb.com> On Thu, 31 Jul 2008 02:25:37 +0000, Steven D'Aprano wrote: > On Wed, 30 Jul 2008 07:11:45 -0700, Phillip B Oldham wrote: > >> Most clients use ">" which is easy to check for, but I've seen some >> which use "|" and some which *don't* quote at all. Its causing us >> nightmares in parsing responses to system-generated emails. I was >> hoping someone might've seen the problem previously and released some >> code. > > My sympathies. > > I've even seen clients that prefix new (unquoted) text with the quote > character ">". Well, this is a new one I've never seen before: found on the python-dev mailing list, somebody who (apparently) marks quoted text by inserting a bare quote character on an otherwise empty line after each line of text, similar to this: I've even seen clients that prefix new (unquoted) text with the quote > character ">". > The user in question seems to be using gmail. I suspect a PEBCAK error. -- Steven From larry.bates at websafe.com` Mon Jul 21 23:40:21 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 22:40:21 -0500 Subject: Python Written in C? In-Reply-To: References: Message-ID: giveitawhril2008 at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. SPSS (was and may still be) written in Fortran and the Fortran compiler was written in C. But NOBODY would suggest that you try to solve the problems that SPSS is used for in C. You talk about "writing it in assembly language for each MPU chip". Actually it is even better than that. We now have these modern inventions, called compilers that do that type of work for us. They translate high level instructions, not into assembler but into machine language. -Larry From Caseyweb at gmail.com Mon Jul 28 09:42:39 2008 From: Caseyweb at gmail.com (Casey) Date: Mon, 28 Jul 2008 06:42:39 -0700 (PDT) Subject: Where is the correct round() method? References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> <90d24864-c67a-4594-b121-d0760f9e145b@m45g2000hsb.googlegroups.com> Message-ID: <765f65f2-9870-44d6-b6d9-d8efc07cb5f3@c65g2000hsa.googlegroups.com> On Jul 28, 12:34?am, Gary Herron wrote: > This will work as you wish: > ? math.floor(x+0.5) This works fine for positive x but what about negative: >>> round(2.5) 3.0 >>> floor(2.5 + 0.5) 3.0 >>> round(-2.5) -3.0 >>> floor(-2.5 + 0.5) -2.0 Maybe: def round2(x): return math.floor(x + (0.5 if x >= 0 else -0.5)) From KDawg44 at gmail.com Fri Jul 18 15:35:39 2008 From: KDawg44 at gmail.com (KDawg44) Date: Fri, 18 Jul 2008 12:35:39 -0700 (PDT) Subject: Distributing Python App Message-ID: <072bf39b-d700-482e-ab59-36840e21e83e@a70g2000hsh.googlegroups.com> Hi, I am very new to Python but find it very interesting (from what I know of it) and am considering writing an application. However, I have a question regarding distribution of the app once it is done. Is there a way to package everything a user needs to run the app or will they have to install Python their machine? This is probably an obvious question but most development I do is for administrative tasks on servers and such, not usually development of an app for someone else. Thanks for your help. Kevin From michael at stroeder.com Sun Jul 6 14:03:58 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Sun, 06 Jul 2008 20:03:58 +0200 Subject: ANN: python-ldap-2.3.5 Message-ID: Find a new release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.3.5 2008-07-06 Changes since 2.3.4: Lib/ * Fixed methods ldap.cidict.__contains__() and ldap.schema.models.Entry.__contains__() * FWIW method LDAPObject.cancel_s() returns a result now * Fixed ldap.schema.models.NameForm: Class attribute oc is now of type string, not tuple to be compliant with RFC 4512 From basti.wiesner at gmx.net Wed Jul 23 11:59:53 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Wed, 23 Jul 2008 17:59:53 +0200 Subject: Proper way to query user and group database on a Unix host? References: <87d4l5ozsc.fsf@cox.net> Message-ID: Guilherme Polo : > On Wed, Jul 23, 2008 at 9:16 AM, Sebastian lunar Wiesner > wrote: >> Chris Brannon : >> >> Iirc since Python 2.5 these tuples are named ... >> >>> Instead, do this: >>> >>> import grp >>> groupname = 'users' >>> groupusers = grp.getgrnam(groupname)[3] >> ... thus this line could be written as: >> >> groupusers = grp.getgrnam(groupname).gr_mem >> > > That is valid since Python 2.3 actually Thanks for clarification -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From usenet at solar-empire.de Tue Jul 15 06:36:44 2008 From: usenet at solar-empire.de (Marc Christiansen) Date: Tue, 15 Jul 2008 12:36:44 +0200 Subject: Testing for Internet Connection References: <1216113021.24038.0@proxy02.news.clara.net> Message-ID: Alex Marandon wrote: > Alexnb wrote: >> I am wondering, is there a simple way to test for Internet connection? If >> not, what is the hard way :p > > Trying to fetch the homepage from a few major websites (Yahoo, Google, > etc.)? If all of them are failing, it's very likely that the connection > is down or there is a mandatory proxy... Does it count as internet connection, when only port 80 and port 443 are accessible and those require going through a proxy (very strict firewall policy)? Or everything requires using SOCKS? Just some possible problems I came up with. I don't know how often some- thing like this will happen. Ciao Marc From Younger.Wang at packetfront.com Fri Jul 18 05:15:41 2008 From: Younger.Wang at packetfront.com (Younger Wang) Date: Fri, 18 Jul 2008 11:15:41 +0200 Subject: DocBook support of Python Message-ID: Hi, Is there any module for parsing DocBook? Thanks! BR Younger Wang -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcfg at sina.com Thu Jul 17 11:02:17 2008 From: tcfg at sina.com (fang) Date: Thu, 17 Jul 2008 08:02:17 -0700 (PDT) Subject: how to debug python's extend module written in c/c++ on windows References: <64d771b2-fbc8-4b6a-9725-3dc5063c5328@p25g2000hsf.googlegroups.com> <6e83v4F5pfg0U1@mid.uni-berlin.de> <6e8cfgF5n34gU1@mid.uni-berlin.de> <3ac0db1c-81d2-4922-9133-5da830f5a346@34g2000hsh.googlegroups.com> <6e93qhF60lqfU1@mid.uni-berlin.de> Message-ID: <0a809ea4-2211-4b02-84a3-784862248f23@b1g2000hsg.googlegroups.com> Dear Diez: I see. I appreciate your help really. best regards fang From barun.saha04 at gmail.com Wed Jul 23 09:32:20 2008 From: barun.saha04 at gmail.com (barun.saha04 at gmail.com) Date: Wed, 23 Jul 2008 06:32:20 -0700 (PDT) Subject: Problem with Python Server Pages (PSP) References: <9766b993-03e6-4b75-92a2-06244c41e51c@a1g2000hsb.googlegroups.com> <8ce2ffdd-0fb3-4f5f-bde8-1598f9b231bc@i20g2000prf.googlegroups.com> <53b1f015-edc8-4225-aeab-1082e07c57c3@j33g2000pri.googlegroups.com> Message-ID: <49fc194a-938b-4b36-b521-eaf9f474c85c@v39g2000pro.googlegroups.com> On Jul 23, 6:18 pm, Graham Dumpleton wrote: > On Jul 22, 1:54 pm, barun.sah... at gmail.com wrote: > > > > > On Jul 22, 5:18 am, Graham Dumpleton > > wrote: > > > > On Jul 21, 9:42 pm, barun.sah... at gmail.com wrote: > > > > > Hi, > > > > > I am facing a very basic problem with PSP. I have installedmod_python > > > > (in fedora Core 1), added the lines required for loading Python > > > > modules and handling PSP pages. I have created a hello.psp page. But > > > > when I try to view this hello.psp page, all Python code are getting > > > > displayed. > > > > > The said page is stored at /var/www/html/psp/hello.psp. I guess this > > > > is some configuration problem with Apache, but not able to figure out > > > > the exact problem. I have tried putting those configuration lines for > > > > psp in both httpd.conf and python.conf files. But still it is not > > > > working. > > > > > The Python module (mod_python) is getting loaded. Because when I > > > > telnet to my server, I can find that in the headers. > > > > > These are the versions of the softwares: > > > > Apache: 2.0.47 > > > > Python: 2.2.3mod_python: 3.0.3 > > > > > Thnaks for all your suggestions. > > > > What is the Apache configuration snippet you are using to enable > > >mod_pythonand PSP file handling? > > > > Graham- Hide quoted text - > > > > - Show quoted text - > > > Hi Graham, > > > The configuration used in httpd.conf file looks like: > > > > AddHandler .psp .psp_ > > PythonHandler modules/python > > PythonDebug On > > > > Go read the documentation properly. > > http://www.modpython.org/live/current/doc-html/hand-psp.html > > What is PythonHandler set to? > > Graham Hi Graham, I'm extremely sorry. I had typed wrongly the configuration. Following is the one I'm using: AddHandler mod_python .psp .psp_ PythonHandler mod_python.psp PythonDebug On Strange thing is, same thing is working in windows, but not in Linux. From fredrik at pythonware.com Wed Jul 23 16:06:18 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 22:06:18 +0200 Subject: repr(string) In-Reply-To: References: Message-ID: David C. Ullrich wrote: > I've been saving data in a file with one line per field. > Now some of the fields may become multi-line strings... > > I was about to start escaping and unescaping linefeeds > by hand, when I realized that repr() and eval() should > do. Hence the question: If s is a string, is repr(s) > guaranteed not to contain line breaks? yes. just keep in mind that using eval() on untrusted data isn't a very good idea. From tjreedy at udel.edu Fri Jul 18 16:37:07 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Jul 2008 16:37:07 -0400 Subject: Question on Joining of list In-Reply-To: <32a81d0c-a74f-4b22-8add-15beb2643529@h17g2000prg.googlegroups.com> References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> <6eb733F67cpfU2@mid.uni-berlin.de> <32a81d0c-a74f-4b22-8add-15beb2643529@h17g2000prg.googlegroups.com> Message-ID: SUBHABRATA wrote: > Sorry if I didn't say that. > The input is a string "Petrol Helium Heaven Sky" > Now, in a3 it is "God Goddess Heaven Sky" is there, > ...I was looking for an output of "H S Petrol Helium" Meaningful names, splitting the target string, and using 'in' makes the code much easier. inwords = "Petrol Helium Heaven Sky".split() targets = "God Goddess Heaven Sky".split() found = [] not_found = [] for word in inwords: if word in targets: found.append(word[0]) else: not_found.append(word) found.extend(not_found) print(' '.join(found)) # 3.0 #prints the requested H S Petrol Helium From steve at REMOVE-THIS-cybersource.com.au Wed Jul 30 22:41:08 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Jul 2008 02:41:08 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> Message-ID: <00a121b4$0$20313$c3e8da3@news.astraweb.com> On Wed, 30 Jul 2008 09:23:05 -0600, Matthew Fitzgibbons wrote: > If you're expecting a list (and only a list) > then your point makes sense. 'if x' can get you into trouble if you > _don't_ want its polymorphism. "if x" is hardly unique in that way. If you're expecting a list, and only a list, "len(x) != 0" will get you in trouble if somebody passes a string or a dictionary. I don't see any reason why we should single out "if x" as dangerous in the face of invalid types. With the exception of the "is" and "is not" operators, nothing in Python is guaranteed to work with any imaginable object. Even print can fail, if the object's __str__ method raises an exception. > Although, if my function is expecting a list, my preference is to do: > > if not isinstance(x, list): > raise SomeMeaningfulException() > # do stuff with the list > > I put my type checking at the top of the function, so readers can > reference it easily. And thus you break duck-typing and upset anybody who wants to pass a sequence that doesn't inherit directly from list. There are other (and arguably better, although more labour-intensive) techniques for defensive programming that don't break duck-typing. You can google for Look Before You Leap and Easier To Ask Forgiveness Than Permission for more information. Alex Martelli has a fine recipe in the Python Cookbook -- search for the recipe "Checking if an object has the necessary attributes". But in a nutshell, here's a toy example: def spam(seq): try: seq.append seq.extend seq[0] = seq[0] except Exception: raise TypeError("argument isn't sufficiently sequence-like") # No exceptions expected from here on seq.append(seq[0]) seq.extend([1,2,3]) seq[0] = "spam" -- Steven From kay.schluehr at gmx.net Sun Jul 20 03:08:02 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 20 Jul 2008 00:08:02 -0700 (PDT) Subject: Not entirely serious: recursive lambda? References: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> Message-ID: On 20 Jul., 04:43, Michael Tobis wrote: > Can a lambda call itself without giving itself a name? Sure, use a fixed point combinator. I've just added this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/576366 > Google was not my friend on this one, and I suspect there is no > answer. Even the Great Google can't help if you don't use the right keywords ;) From fredrik at pythonware.com Thu Jul 17 03:53:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 09:53:13 +0200 Subject: Rotating a cube In-Reply-To: References: Message-ID: J-Burns wrote: > Is there a built in Python function for this? for answering questions that have nothing to do with programming, and looks quite a bit like homework? don't think they've added that one yet. maybe you should look for a geometry newsgroup/forum? From cheappuma at 126.com Fri Jul 18 20:40:26 2008 From: cheappuma at 126.com (128) Date: Fri, 18 Jul 2008 17:40:26 -0700 (PDT) Subject: paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) Message-ID: paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) From mrmakent at cox.net Tue Jul 1 14:58:55 2008 From: mrmakent at cox.net (Mike Kent) Date: Tue, 1 Jul 2008 11:58:55 -0700 (PDT) Subject: Convert string to char array References: <0%uak.283$4a3.73@trnddc04> Message-ID: <4670347e-2531-4449-a171-e352e1053864@r66g2000hsg.googlegroups.com> On Jul 1, 2:49?pm, "Brandon" wrote: > How do I convert a string to a char array? ?I am doing this so I can edit > the string received from an sql query so I can remove unnecessary > characters. Answering your specific question: Python 2.5.1 (r251:54863, Mar 31 2008, 11:09:52) [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> s = 'hello' >>> l = list(s) >>> l ['h', 'e', 'l', 'l', 'o'] >>> But more generally, you might want to read up on the string methods available to you, such as replace(): http://docs.python.org/lib/string-methods.html From rocksportrocker at googlemail.com Wed Jul 23 14:56:03 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Wed, 23 Jul 2008 11:56:03 -0700 (PDT) Subject: Using variables across modules References: <855136ce-6c70-40ac-a462-dc0bbfa1fc3a@b2g2000prf.googlegroups.com> Message-ID: <121c5161-9485-4d6a-a447-9f9dd4227bac@d77g2000hsb.googlegroups.com> Aaron Scott schrieb: > I'm having some trouble understanding how Python handles variables > across multiple modules. I've dug through the documentation, but I > still find myself at a loss. > > When you import a module, are you creating an instance of the > variables within? For instance, if I have one file, "variables.py", > which contains "myvar = 0", and I import it into both "foo.py" and > "bar.py" with the line "from variables import *", and then set myvar > in "foo.py" and "bar.py" to different values, will each file have a > different value for myvar? If so, how can I ensure that a change to > myvar in "bar.py" is reflected by "foo.py"? Or am I completely off > base? Just wirte test code ! Python is cool for checking such things, you do do not have to compile, you need not write boilerplate main() stuff. Greetings, Uwe From aisaac at american.edu Thu Jul 10 15:07:19 2008 From: aisaac at american.edu (Alan Isaac) Date: Thu, 10 Jul 2008 19:07:19 GMT Subject: Python with Ecmascript In-Reply-To: References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <486fe241$0$867$ba4acef3@news.orange.fr> Message-ID: Daniel Fetchinson wrote: > Is there a way to do similar things on linux? NJSModule? http://en.wikipedia.org/wiki/NJS Alan Isaac From jordanrastrick at gmail.com Thu Jul 24 11:03:45 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 08:03:45 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <40449826-c71d-4c6e-8b74-13069269e5da@z6g2000pre.googlegroups.com> <488896bf$0$3493$426a74cc@news.free.fr> Message-ID: <3d56ad67-bcd7-4840-979a-8648292afcff@j7g2000prm.googlegroups.com> > Then why do you write, let me quote: > > """ > (snip) coding __eq__ (snip) buys you > nothing from the != operator. != isn't (by default) a synonym for the > negation of == (unlike in, say, every other language ever); not only > will Python let you make them mean different things, without > documenting this fact - it actively encourages you to do so. > """ My words aren't as clear as they should be. I mean that Python lets *you* do something without documenting, or rather stating to use a better term, that your intention is the non-obvious one. I'm not saying that Python itself lacks documentation for its own behaviour; I'm saying it should force you to make your intentions clear and visible to someone reading your code when you want to do something non- obvious. > I was not commenting on the actual design choice, just stating that it > is actually documented. Yes, it is. I apologise for the poor construction of my statement which led to this confusion. > And you're talking about strawman ??? Come on, you obviously can tell > the difference between a one-line statement and your above strawman > argument, don't you ? I'm talking about strawmen because I was deliberately choosing to invoke one with rhetorical flourish for the purposes of making my point forcefully. I wanted people to be clear that I knew perfectly well what I was doing and that they needn't call me out on it. > Please understand that I'm not arguing about this particular design > choice (and FWIW, I'd mostly agree on the point that having a != b > different from not (a == b) is actually a wart). I'm just correcting > your statement about the behaviour of __eq__ / __ne__ not being > documented, which is obviously false. Good, at least we've come to a point in this discussion where I can firmly agree with somebody. From motoom at xs4all.nl Sat Jul 19 15:45:03 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Sat, 19 Jul 2008 21:45:03 +0200 Subject: win32api not found? In-Reply-To: References: Message-ID: <200807192145.03118.motoom@xs4all.nl> On Saturday 19 July 2008 21:13:04 Lamonte Harris wrote: > Where can I get the win32api module? I been searching all day on google and > nothing, i installed > https://sourceforge.net/project/showfiles.php?group_id=78018 which requires > win32api and its not found... What are the actions you do and the commands you give, and what is the precise error you get? Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From mccredie at gmail.com Mon Jul 14 21:56:34 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 14 Jul 2008 18:56:34 -0700 (PDT) Subject: One step up from str.split() References: Message-ID: <2f7e2895-e1ee-4113-a6bf-a3a15235f27c@w7g2000hsa.googlegroups.com> On Jul 14, 6:33 pm, "Joel Koltner" wrote: > I normally use str.split() for simple splitting of command line arguments, but > I would like to support, e.g., long file names which-- under windows -- are > typically provided as simple quoted string. E.g., > > myapp --dosomething --loadthis "my file name.fil" > > ...and I'd like to get back a list wherein ListEntry[3]="my file name.fil" , > but just running str.split() on the above string creates: > > >>> ListEntry='myapp --dosomething --loadthis "my file name.fil"' > >>> ListEntry.split() > > ['myapp', '--dosomething', '--loadthis', '"my', 'file', 'name.fil"'] > > Is there an easy way to provide just this one small additional feature > (keeping quoted names as a single entry) rather than going to a full-blown > command-line argument parsing tool? Even regular expressions seem like they'd > probably be overkill here? Or no? > > Thanks, > ---Joel look at the shlex module: >>> import shlex >>> txt = 'myapp --dosomething --loadthis "my file name.fil"' >>> shlex.split(txt) ['myapp', '--dosomething', '--loadthis', 'my file name.fil'] Matt From bruno.desthuilliers at gmail.com Tue Jul 15 09:53:31 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Tue, 15 Jul 2008 06:53:31 -0700 (PDT) Subject: Method behavior for user-created class instances References: <42433fcd-fcdc-4f42-a427-c28241734b7c@z66g2000hsc.googlegroups.com> Message-ID: On 15 juil, 01:24, crazychimp... at gmail.com wrote: > Greetings. > > I am looking for a way to achieve method behavior for a class I > created. That is, it has a __call__ method, so can be called like a > function. But I also want it to be treated as a method when it appears > in a class body. You need to implement the descriptor protocol the same way the function type do. import types class Foo(object): def __call__(self, instance): print "%s - %s" % (self, instance) def __get__(self, instance, cls): return types.MethodType(self, instance, cls) class Bar(object): foo = Foo() b = Bar() b.foo() > I know this has to do with writing the __get__ > method of foo, but I am wondering if there is perhaps some class I can > just inherit from to get the proper __get__, which behaves identically > to that of regular Python functions. Extending types.FunctionType doesn't work OOTB (there's some incompatibility wrt/ metaclasses) From JordanNealBerg at gmail.com Thu Jul 10 01:45:21 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Wed, 9 Jul 2008 22:45:21 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: Message-ID: <47741438-f523-4a9b-ad7f-86e5628dade8@m36g2000hse.googlegroups.com> if after the first step (u += 0xe91aaa35) you apply this function: invert = lambda x: ~int(hex(0xffffffff - x)[0:-1],16) it returns the correct value (corrected the overflow) but there is still something wrong, still looking into it, if someone knows how to do this, feel free to comment :) From jkugler at bigfoot.com Tue Jul 15 18:07:09 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Tue, 15 Jul 2008 14:07:09 -0800 Subject: Is re.findall guaranteed to be "in order?" Message-ID: I tried looking through re.py and sre_compile.py, but I can't really see an answer to my question. Experimenting has shown me that re.findall() will return a list with the matches in the order it found them. Am I lucky so far, or does the _sre.c's logic dictate the items will be added in order found? http://svn.python.org/view/python/tags/r25c1/Modules/_sre.c?rev=51334&view=auto (search for "pattern_findall") seems to indicate they will be added in order, but can someone with a better handle on Python internals (and quite frankly, C) confirm this? Thanks! j From jim.hefferon at gmail.com Tue Jul 1 20:42:28 2008 From: jim.hefferon at gmail.com (Jim) Date: Tue, 1 Jul 2008 17:42:28 -0700 (PDT) Subject: convert unicode characters to visibly similar ascii characters References: <17d4c282-8606-4d29-9e71-d34f5e6d13bb@m44g2000hsc.googlegroups.com> Message-ID: On Jul 1, 8:29 pm, John Machin wrote: > On Jul 2, 9:55 am, Jim wrote: > > Comments on the above grep output: > 1. You have SOFT HYPHEN twice, mapping it to u'-' and '-' Hmph. I'll correct that. Thanks. > 2. The idea of a soft hyphen is as a hint to a hyphenator about where > to insert a hyphen if one is necessary and the hyphenator is suspected > of acting cluelessly without the hint. IMHO, asciification should > substitute u'', not u'-'. Thanks also here. I'll think about it. > 3. Read PEP 8. s/:/: / I don't like the spacing in 8, personally. Thanks, Jim From ldo at geek-central.gen.new_zealand Wed Jul 23 19:12:59 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 24 Jul 2008 11:12:59 +1200 Subject: Is this a valid use of 'import'? References: Message-ID: In message , Frank Millman wrote: > from Utils.client import * Besides the objections that others have mentioned, I HATE seeing wildcard imports. From jeffober at gmail.com Tue Jul 8 07:47:58 2008 From: jeffober at gmail.com (Jeff) Date: Tue, 8 Jul 2008 04:47:58 -0700 (PDT) Subject: caseless dict - questions References: <77798300-820f-4175-a9cb-aef639d42a32@m45g2000hsb.googlegroups.com> Message-ID: <7370727f-7b15-4dbc-9f42-35ec2df34806@56g2000hsm.googlegroups.com> Use the __str__ and __unicode__ methods to control the printed representation of a class. From workitharder at gmail.com Mon Jul 28 13:30:51 2008 From: workitharder at gmail.com (bukzor) Date: Mon, 28 Jul 2008 10:30:51 -0700 (PDT) Subject: binding names doesn't affect the bound objects (was: print doesn't respect file inheritance?) References: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> <8763qtmgo7.fsf@benfinney.id.au> Message-ID: <87d64aab-49a1-4753-ac0e-6f7cbfd17e39@f36g2000hsa.googlegroups.com> On Jul 26, 7:08?am, "D'Arcy J.M. Cain" wrote: > On Sat, 26 Jul 2008 14:07:52 +1000 > > Ben Finney wrote: > > > ? ? sys.stdout = n > > > Re-binds the name 'sys.stdout' to the object already referenced by the > > name 'n'. No objects are changed by this; only bindings of names to > > objects. > > I do agree that the object formerly known as sys.stdout hasn't changed. > > > > ? ? print "Testing: 1, 2, 3..." > > > Doesn't rely at all on the name 'sys.stdout', so isn't affected by all > > the binding of names above. > > Hmm. ?Are you saying that the following doesn't work? > > $ python>>> f = open("test", "w") > >>> import sys > >>> sys.stdout = f > >>> print "test message" > >>> sys.exit(0) > > $ cat test > test message > > > In other words, you can't change the object used by the 'print' > > statement only by re-binding names (which is *all* that is done by the > > '=' operator). > > Apparently I can. > > > You can, however, specify which file 'print' should use > > . > > Which contains this statement. > > "Standard output is defined as the file object named stdout in the > built-in module sys." > > I suppose that there might be some ambiguity there but the proof, as > they say, is in the pudding. > > -- > D'Arcy J.M. Cain ? ? ? ? | ?Democracy is three wolveshttp://www.druid.net/darcy/? ? ? ? ? ? ? ?| ?and a sheep voting on > +1 416 425 1212 ? ? (DoD#0082) ? ?(eNTP) ? | ?what's for dinner. Thanks for backing me up. Nobody here thinks it's strange that print uses *none* of the attributes or methods of sys.stdout to do its job? The implementation seems to bypass the whole python system and use C-level FILE* pointers directly instead. From thogiti at gmail.com Mon Jul 7 17:48:12 2008 From: thogiti at gmail.com (Nagu) Date: Mon, 7 Jul 2008 14:48:12 -0700 Subject: Memory error while saving dictionary of size 65000X50 using pickle Message-ID: <21da85430807071448s43b69432q806705039aa3531a@mail.gmail.com> I didn't have the problem with dumping as a string. When I tried to save this object to a file, memory error pops up. I am sorry for the mention of size for a dictionary. What I meant by 65000X50 is that it has 65000 keys and each key has a list of 50 tuples. I was able to save a dictionary object with 65000 keys and a list of 15-tuple values to a file. But I could not do the same when I have a list of 25-tuple values for 65000 keys. You exmple works just fine on my side. Thank you, Nagu From fredrik at pythonware.com Wed Jul 23 16:18:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 22:18:25 +0200 Subject: interpreter vs. compiled In-Reply-To: <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> Message-ID: castironpi wrote: > Compiling a program is different than running it. A JIT compiler is a > kind of compiler and it makes a compilation step. I am saying that > Python is not a compiler and in order to implement JIT, it would have > to change that fact. good thing Python don't have to listen to you, then, so it can keep using its built-in compiler to produce programs for its built-in VM. > But still not the user's code, only the interpreter, which is running > in assembly already anyway in CPython. good luck with your future career in computing! From gnewsg at gmail.com Wed Jul 9 07:13:22 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Wed, 9 Jul 2008 04:13:22 -0700 (PDT) Subject: Doubts about how implementing asynchronous timeouts through a heap Message-ID: <80430d47-aac5-4123-8835-0591faf0baed@34g2000hsf.googlegroups.com> Hi, I'm trying to implement an asynchronous scheduler for asyncore to call functions at a later time without blocking the main loop. The logic behind it consists in: - adding the scheduled functions into a heapified list - calling a "scheduler" function at every loop which checks the scheduled functions due to expire soonest Note that, by using a heap, the first element of the list is always supposed to be the one with the lower timeout. Here's the code I wrote: <--- snippet ---> import heapq import time import sys delayed_map = [] class delayed_call: """Calls a function at a later time. The instance returned is an object that can be used to cancel the scheduled call, by calling its cancel() method. It also may be rescheduled by calling delay() or reset()} methods. """ def __init__(self, delay, target, *args, **kwargs): """ - delay: the number of seconds to wait - target: the callable object to call later - args: the arguments to call it with - kwargs: the keyword arguments to call it with """ assert callable(target), "%s is not callable" %target assert sys.maxint >= delay >= 0, "%s is not greater than or equal " \ "to 0 seconds" % (delay) self.__delay = delay self.__target = target self.__args = args self.__kwargs = kwargs # seconds from the epoch at which to call the function self.timeout = time.time() + self.__delay self.cancelled = False heapq.heappush(delayed_map, self) def __le__(self, other): return self.timeout <= other.timeout def active(self): """Return True if this scheduler has not been cancelled.""" return not self.cancelled def call(self): """Call this scheduled function.""" self.__target(*self.__args, **self.__kwargs) def reset(self): """Reschedule this call resetting the current countdown.""" assert not self.cancelled, "Already cancelled" self.timeout = time.time() + self.__delay if delayed_map[0] is self: heapq.heapify(delayed_map) def delay(self, seconds): """Reschedule this call for a later time.""" assert not self.cancelled, "Already cancelled." assert sys.maxint >= seconds >= 0, "%s is not greater than or equal " \ "to 0 seconds" %(seconds) self.__delay = seconds self.reset() def cancel(self): """Unschedule this call.""" assert not self.cancelled, "Already cancelled" del self.__target, self.__args, self.__kwargs if self in delayed_map: if delayed_map[0] is self: delayed_map.remove(self) heapq.heapify(delayed_map) else: delayed_map.remove(self) self.cancelled = True def fun(arg): print arg a = delayed_call(0.6, fun, '0.6') b = delayed_call(0.5, fun, '0.5') c = delayed_call(0.4, fun, '0.4') d = delayed_call(0.3, fun, '0.3') e = delayed_call(0.2, fun, '0.2') f = delayed_call(0.1, fun, '0.1') while delayed_map: now = time.time() while delayed_map and now >= delayed_map[0].timeout: delayed = heapq.heappop(delayed_map) try: delayed.call() finally: if not delayed.cancelled: delayed.cancel() time.sleep(0.01) Here comes the questions. Since that the timeouts of the scheduled functions contained in the list can change when I reset() or cancel() them I don't know exactly *when* the list needs to be heapified(). By doing some tests I came to the conclusion that I need the heapify() the list only when the function I reset() or cancel() is the *first of the list* but I'm not absolutely sure about it. When do you think it would be necessary calling heapify()? I wrote a short test suite which tests the code above and I didn't notice strange behaviors but since that I don't know much about the logic behind heaps I'd need some help. Thanks a lot in advance. --- Giampaolo http://code.google.com/p/pyftpdlib/ From mail at microcorp.co.za Wed Jul 9 03:09:14 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 9 Jul 2008 09:09:14 +0200 Subject: Cross Compiler for Python? References: <001101c8e0d2$36a50ec0$0d00a8c0@hendrik> <4873D882.6090109@hughes.net> Message-ID: <000e01c8e192$b4010660$0d00a8c0@hendrik> "norseman" wrote: 8< --------------------------------------------------------- > ....dreaded.... Yep! I know the feeling. Got lots of those T-Shirts. ;) > > > I re-read your original post. I got the feeling the eBox is running a > stripped down Linux. Is that so? If it is, then: Correct - a kernel, and busybox masquerading as the whole of GNU... > > You mention pcmcia. Is it external, a plug in? Do any of your > desktops/etc have pcmcia slots? Because if so..... Its part of the eBox - quite a neat implementation > > 1) Card can be mounted on your machine > 2) Compile and install can be direct to card (rem 32bit output) > just change the install path(s). Look over the eBox /lib > ( I'm assuming Linux again) and put that lib path first in > the compile command line. > > If no desktop pcmcia adapter - pay the $40 or so for an USB attachable > pcmcia adapter This is sane - I would need it if ever we get to using the thing, for loading software onto the devices anyway. > > sample: > plug in card > > (if current drives on desktop are scsi or sata drives you may need to > change sda to sdb or sdc or .... use fdisk /dev/sda to check existence. > the single letter 'q' to exit without changing anything. Careful with > fdisk - damage comes quickly, easily and unrepairable. All you are after > is which letter to use. Last one before No such drive is the one. > ) should be able to look in /dev - but I will be carefull... Also Suse and GUI should just pop up, like a USB stick does. > > cd /mnt > mkdir sda > mount /dev/sda1 /mnt/sda > ls /mnt/sda should give base dir listing of flashdrive > (linux will treat the pcmcia flash as a removable HardDrive) > > install to /mnt/sda/usr/local/lib (or /mnt/sda/--where ever--) > then: back on eBox > cd /mnt > mkdir sda > cd sda > ln -s /usr usr > > I did the soft link process above on my machine, then: > > ls /mnt/sda/usr/local/lib/python2.5 should list contents correctly > (and does on my machine since it is located in /usr/local/lib/python2.5) > thus keeping compile and install paths working. The use of the midnight > commander (mc) with card mounted makes transferring whole trees simple. > Soft links were invented for a reason! > > OF COURSE, if the eBox is not running Linux, all this is useless! ;) > > Steve Thanks a lot - this seems the way to go... - Hendrik From abumoaas1987 at yahoo.com Tue Jul 1 11:51:19 2008 From: abumoaas1987 at yahoo.com (ah) Date: Tue, 1 Jul 2008 08:51:19 -0700 (PDT) Subject: Discover Islam - The Fastest Growing Religion in the World ! Message-ID: <9d3ed65e-335c-4d45-8374-505ae7d434b1@p25g2000hsf.googlegroups.com> Correct your information about Islam , The Misunderstood Religion When you are ready_ you can enter this place!!! http://sultan.org From __peter__ at web.de Thu Jul 10 02:11:11 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Jul 2008 08:11:11 +0200 Subject: Relative Package Import References: Message-ID: Kay Schluehr wrote: > On 8 Jul., 21:09, Peter Otten <__pete... at web.de> wrote: >> Robert Hancock wrote: >> > mypackage/ >> > __init__.py >> > push/ >> > __init__.py >> > dest.py >> > feed/ >> > __init__py >> > subject.py >> >> > In subject.py I have >> > from ..push import dest >> >> > But i receive the error: >> > Caught exception importing module subject: >> > File "/usr/local/python/lib/python2.5/site-packages/pychecker/ >> > checker.py", line 621, in setupMainCode() >> > module = imp.load_module(self.moduleName, file, filename, smt) >> > File "subject.py", line 1, in () >> > from ..feed import dest >> > ValueError: Attempted relative import in non-package >> >> > What am I missing? >> >> When you run subject as a file >> >> pychecker mypackage/feed/subject.py >> >> subject.py is regarded as a standalone script, not as part of a package. >> Try >> >> pychecker mypackage.feed.subject >> >> instead to invoke the module via the standard import mechanism. >> >> Peter > > Since when are Python modules not regarded as standalone scripts but > as a "part of a package"? > > The only indication that there is some duality and that it is relevant > at all are those relative imports that came in with Python 2.5. As it > seems this feature is justified by the artificial semantic differences > it produces. I'm probably misunderstanding you, but the ambiguity I wanted to point out has existed before and has nothing artificial: $ tree . `-- mypackage |-- __init__.py |-- feed | |-- __init__.py | |-- subject.py | `-- subject.py~ `-- push |-- __init__.py `-- dest.py 3 directories, 6 files $ python2.4 -c "import mypackage.push.dest as d; print d.__name__" mypackage.push.dest $ cd mypackage/push/ $ python2.4 -c "import dest as d; print d.__name__" dest ".." in the import goes one up in the package name, not in the filesystem and therefore won't work in the second example. Peter From max at alcyone.com Wed Jul 30 02:36:58 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 23:36:58 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <6d906dd5-bf5a-44d5-a5a8-3875027f6b91@v26g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> <6d906dd5-bf5a-44d5-a5a8-3875027f6b91@v26g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > Come to think of it, shouldn't the list type have an "isempty" method? > Or does it? Yes. It's written: if not aList: ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The doors of Heaven and Hell are adjacent and identical. -- Nikos Kazantzakis From mensanator at aol.com Wed Jul 2 14:22:44 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 2 Jul 2008 11:22:44 -0700 (PDT) Subject: Python and timezones References: Message-ID: <66de1777-ab65-4708-904b-3e511409a662@m36g2000hse.googlegroups.com> On Jul 2, 12:43?am, "shand... at gmail.com" wrote: > I'm trying to write some code to deal with world timezones, and I'm > getting a strange result. ?America/Iqaluit should not be showing up in > UTC+00:00, but it is. ?Can anyone see what's wrong with this code? > > import time > from datetime import datetime > import os > import pytz > > def getZoneNamesOnThisComputer(): > ? ? for i in pytz.all_timezones: > ? ? ? ? if os.path.exists( os.path.join('/tmp/usr/share/zoneinfo/', > i)): > ? ? ? ? ? ? yield i > > def getZonesGroupedByOffset(): > ? ? '''return a dict of all the zone names , grouped by their offset > ? ? eg: > ? ? {'-0400': ['America/Blanc-Sablon', 'Etc/GMT+4'], > ? ? ?'+0000': ['America/Iqaluit', 'Etc/GMT', 'Europe/Belfast', 'GB', > 'GMT'], > ? ? ?... > ? ? } > ? ? ''' > ? ? Y,M,D,h,m,s = time.localtime()[:6] > > ? ? zonesGroupedByOffset = {} > > ? ? for name in getZoneNamesOnThisComputer(): > ? ? ? ? tz = pytz.timezone(name) > ? ? ? ? now = datetime(Y,M,D,h,m,s, tzinfo=tz) > ? ? ? ? # strfime returns a string like "-0800" or "+0430" or "0000" > ? ? ? ? offsetKey = now.strftime('%z') > ? ? ? ? if not zonesGroupedByOffset.has_key(offsetKey): > ? ? ? ? ? ? zonesGroupedByOffset[offsetKey] = [] > ? ? ? ? zonesGroupedByOffset[offsetKey].append(name) > ? ? return zonesGroupedByOffset > > z = getZonesGroupedByOffset() > print z['+0000'] > > # Why is America/Iqaluit showing up here??? The database contains an error. Shit happens, deal with it. From gh at ghaering.de Fri Jul 11 08:48:00 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 11 Jul 2008 14:48:00 +0200 Subject: python scalability In-Reply-To: <4876746D.3090003@gmail.com> References: <4876746D.3090003@gmail.com> Message-ID: Tim Mitchell wrote: > Thanks for all the replies - they have all been helpful. > > On reflection I think our problems are probably design and people related. I strongly agree. "Scalability" is becoming a buzzword lately, which is meaningless unless qualified what exactly is meant. It's overused wrt technologies, programming languages, tools, etc. But in other interesting areas people think much less about "scalability". Will the current software development process work with a team of 5, 10, 20, 50 team members? Does it "scale" here? Will the software development process still work with an increased turnover rate? Does it "scale"? Will the way of doing things still work with an increasingly aging codebase? -- Gerhard From tpt at kamstrup.dk Tue Jul 29 04:34:58 2008 From: tpt at kamstrup.dk (mindmind) Date: Tue, 29 Jul 2008 01:34:58 -0700 (PDT) Subject: ironpython, exception in mscorlib when reading .py file from network share Message-ID: <6dfb578a-17ff-434d-a071-646ed3ef2b03@z72g2000hsb.googlegroups.com> Hello, I have a ironpython 1.1.1.0 host in my c# app, and When doing a engine.ExecuteFile(file); i often get the error below, when "file" is on a network share : (winXp client , windows ??? server) 21-07-2008 12:47:28 : Traceback (most recent call last): 21-07-2008 12:47:28 : File c:\sandbox\xxx.cs 21-07-2008 12:47:28 : File c:\sandboxx\yyy.cs 21-07-2008 12:47:28 : File mscorlib, line unknown, in ReadAllBytes 21-07-2008 12:47:28 : File mscorlib, line unknown, in Read 21-07-2008 12:47:28 : File mscorlib, line unknown, in ReadCore 21-07-2008 12:47:28 : File mscorlib, line unknown, in WinIOError 21-07-2008 12:47:28 : IOError: The specified network name is no longer available. 21-07-2008 12:47:28 : Exception is caught before first line in python is executed. Other parts of the program is also accessing the network (for copying files etc), and never fails, so networks connection is "ok" (maybe not perfect, but at least present.) Is the ExecuteFile reading the contents of the .py file differently than a "copy" primitive is (other timeout/retry values) ? Does anyone have any ideas of how to setup windows , ironpython host or .NET lib differently, to stop it doing this ? Fallback solution is to copy file locally before execution, but I would rather fix this. thx From mail at timgolden.me.uk Thu Jul 17 04:22:37 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 17 Jul 2008 09:22:37 +0100 Subject: About wmi In-Reply-To: <3d1db021-6766-4d5d-9105-fdd81e27b671@26g2000hsk.googlegroups.com> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> <487E1AD4.9020509@timgolden.me.uk> <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> <3d1db021-6766-4d5d-9105-fdd81e27b671@26g2000hsk.googlegroups.com> Message-ID: <487F014D.40008@timgolden.me.uk> patrol wrote: > I will try to modify the wmi.py ,however I'm a novice.It will take a > long time. You can give it up temporarily. If you don't mind ,can you > tell me where needs modifying and how? Just unicode? Or Other? OK. Thanks for your patience on this one, Patrol. What I propose to do is to dig into the pywin32 sources to determine what's going on when the error messages are fetched. Then I'll be better placed to decide what to do when they come out. On the surface, the current module should be handling things correctly; but I've obviously missed an encode/decode somewhere. If I can think of an (even hackish) workaround for you in the meantime, I'll let you know. Until then... TJG From bj_666 at gmx.net Wed Jul 23 13:10:58 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 23 Jul 2008 17:10:58 GMT Subject: Python Written in C? References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> <6eosgtF7u58sU1@mid.uni-berlin.de> <537c58c3-d74c-41dd-8571-26cfbb415178@34g2000hsh.googlegroups.com> Message-ID: <6ep711F7u58sU2@mid.uni-berlin.de> On Wed, 23 Jul 2008 09:42:29 -0700, castironpi wrote: > On Jul 23, 9:11?am, Marc 'BlackJack' Rintsch wrote: >> On Wed, 23 Jul 2008 14:10:22 +0200, mk wrote: >> > Marc 'BlackJack' Rintsch wrote: >> >> I can't even remember when I deleted something from a list in the past. >> >> > Still, doesn't that strike you as.. workaround? >> >> No, I find it actually safer; I don't have to care where modifications of >> the list might be seen elsewhere in the program. >> >> Ciao, >> ? ? ? ? Marc 'BlackJack' Rintsch > > a[:]= newlist > > and > > a= newlist > > have two completely different effects, and one is just as safe as > 'del'. Besides, del isn't safe to be seen elsewhere in the program in > other threads, if they aren't locking the GIL. As usual you are talking nonsense? Ciao, Marc 'BlackJack' Rintsch From mathieu.prevot at ens.fr Fri Jul 11 06:50:20 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Fri, 11 Jul 2008 12:50:20 +0200 Subject: error with configure (svn 64857) In-Reply-To: References: <487681e9$0$9745$9b622d9e@news.freenet.de> Message-ID: <3e473cc60807110350s7db7f215hae510a1b9448144b@mail.gmail.com> 2008/7/11 WDC : > On Jul 10, 6:57 pm, "Mathieu Prevot" wrote: >> 2008/7/10 "Martin v. L?wis" : >> >> >> I have the following error when I run configure: >> >> >> checking size of wchar_t... configure: error: cannot compute sizeof (wchar_t) >> >> >> what can I do ? >> >> > Study config.log for the source of the problem. >> >> Thank you Martin. How can I remove -lgcc_s and use the Intel equivalent ? >> >> configure:21939: checking for wchar_t >> configure:21970: icc -c -g -O2 conftest.c >&5 >> conftest.c(123): warning #279: controlling expression is constant >> if ((ac__type_new_ *) 0) >> ^ >> >> configure:21976: $? = 0 >> configure:21991: result: yes >> configure:21998: checking size of wchar_t >> configure:22306: icc -o conftest -g -O2 conftest.c >&5 >> ld: library not found for -lgcc_s >> configure:22309: $? = 1 >> configure: program exited with status 1 >> >> Mathieu > > I think he wanted YOU to find the problem. The best way to learn is to > figure it out yourself! Good luck. Yes WDC I know, but for some problems 1) we can gain much efficiency with getting help from guys that are familiar with the environment and 2) we also allow the committers to know a problem and improve the sources. That's the way an open source group works IMHO :) Now that the problem is solved for me, it is for all MacOSX+Intel icc guys. Cheers, Mathieu From arnimavidyarthy at gmail.com Fri Jul 18 06:33:55 2008 From: arnimavidyarthy at gmail.com (arnimavidyarthy at gmail.com) Date: Fri, 18 Jul 2008 03:33:55 -0700 (PDT) Subject: trying to match a string Message-ID: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> Hi, Hi, I am taking a string as an input from the user and it should only contain the chars:L , M or R I tried the folllowing in kodos but they are still not perfect: [^A-K,^N-Q,^S-Z,^0-9] [L][M][R] [LRM]?L?[LRM]? etc but they do not exactly meet what I need. For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. regards, SZ The string may or may not have all the three chars. From timothywayne.cook at gmail.com Sun Jul 27 04:23:38 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Sun, 27 Jul 2008 05:23:38 -0300 Subject: Stripping parts of a path In-Reply-To: <8utn84hs5c713k54l5kmfrgbg3k2dr1oce@4ax.com> References: <8utn84hs5c713k54l5kmfrgbg3k2dr1oce@4ax.com> Message-ID: <1217147018.2920.1.camel@localhost.localdomain> On Sun, 2008-07-27 at 04:32 +0000, Tim Roberts wrote: > This doesn't do what you think it does. The parameter to rstrip is a set: > as long as the last character is in the set 'abcdhiloprs/', it will remove > it and check the next one. All of the characters in "shop" are in that > set. Thanks for all the replies. You are correct I misunderstood the docs. Finding and slicing works great. Cheers, Tim -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. Home page: https://launchpad.net/oship/ Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From sturlamolden at yahoo.no Tue Jul 8 16:35:49 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 8 Jul 2008 13:35:49 -0700 (PDT) Subject: sage vs enthought for sci computing References: <677e7819-e09e-43d3-8368-5864f91002be@34g2000hsh.googlegroups.com> Message-ID: On 7 Jul, 22:35, jadamwils... at gmail.com wrote: > Hello, > I have recently become interested in using python for scientific > computing, and came across both sage and enthought. I am curious if > anyone can tell me what the differences are between the two, since > there seems to be a lot of overlap (from what I have seen). If my goal > is to replace matlab (we do signal processing and stats on > physiological data, with a lot of visualization), would sage or > enthought get me going quicker? I realize that this is a pretty vague > question, and I can probably accomplish the same with either, but what > would lead me to choose one over the other? > Thanks! I work in neuroscience, and use Python of signal processing. I've used Matlab before. Python is just better. I do not use either Sage or Enthought. Instead I have istalled a vanilla Python and the libraries I need. The most important parts are: - Python 2.5.2 - NumPy - SciPy - Matplotlib - wxPython - pywin32 - PIL - Cython - PyOpenGL - mpi4py - processing module - gfortran and gcc (not a Python library, but I need a C and Fortran compiler) Less important stuff I also have installed: - Twisted - PyGame - MySQL and mysqldb - Python for .NET (http://pythonnet.sourceforge.net) - VideoCapture From asmodai at in-nomine.org Fri Jul 4 04:22:13 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 4 Jul 2008 10:22:13 +0200 Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: <486DCA32.5000705@gmail.com> References: <20080704053113.GJ34192@nexus.in-nomine.org> <486DCA32.5000705@gmail.com> Message-ID: <20080704082213.GN34192@nexus.in-nomine.org> -On [20080704 09:00], Aspersieman (aspersieman at gmail.com) wrote: >Here's a tutorial on setting this up. > http://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/ Thanks Nicol, there's some things there that can speed up my current setup as well. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Whispering winds in moonlit wood, a totem oak once golden stood... From mwilson at the-wire.com Tue Jul 8 21:54:30 2008 From: mwilson at the-wire.com (Mel) Date: Tue, 08 Jul 2008 21:54:30 -0400 Subject: "in"consistency? References: <87vdzhwf1v.fsf@benfinney.id.au> Message-ID: David C. Ullrich wrote: > Oh, of course that's a good thing - changing "in" for lists > to give True there would be awful. I was wondering why it > _does_ work that way for strings. > > Maybe the answer is "because it can" - for strings the sort > of possible problem you point out can't come up. I think that's it. When people realized how handy small_string in big_string would be, they expanded the string behaviour. Python is a pragmatic language. Cheers, Mel. From straton at lampsacos.demon.co.uk Mon Jul 28 19:12:50 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Tue, 29 Jul 2008 00:12:50 +0100 Subject: derivative in numpy In-Reply-To: References: Message-ID: knielsen73 at gmail.com wrote: > Hi, > > I am looking to do a simple derivative. I would expect such a function > to be available in numpy, but can't find it. I have written my own, > but just curious if anybody knows of such function in numpy. > > Cheers, > Kim numpy and much more are wrapped together in 'sage' and you should get the functionality you need there. For a review, see: http://vnoel.wordpress.com/2008/05/03/bye-matlab-hello-python-thanks-sage/ From skazhy at gmail.com Mon Jul 21 07:35:46 2008 From: skazhy at gmail.com (skazhy) Date: Mon, 21 Jul 2008 04:35:46 -0700 (PDT) Subject: simple question about dictionaries Message-ID: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> hi, i am new to python, so i've a really simple question about dictionaries. if i have a dictionary and I make have an input after it (to input numbers) can i get the key of value that was in input? somehting like this: dict = { "key1"=100,"key2"=200,"key3"=300} a = input() print 'the key of inputted value is', dict['a'] this syntax of course is wrong, but i hope you got the point.. thanks in advance! From castironpi at gmail.com Mon Jul 28 14:23:23 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 28 Jul 2008 11:23:23 -0700 (PDT) Subject: QOTW [was Re: Attack a sacred Python Cow] References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> <7360bd9a-4ff6-4e75-821c-eabc88ee6258@u6g2000prc.googlegroups.com> <009dce32$0$20313$c3e8da3@news.astraweb.com> Message-ID: <7e9ab1b7-75f8-4374-890d-2d9414acf254@c65g2000hsa.googlegroups.com> On Jul 28, 9:07?am, Steven D'Aprano wrote: > On Sun, 27 Jul 2008 21:42:37 -0700, Russ P. wrote: > >> +1 QOTW > > > Do you realize what an insult that is to everyone else who has posted > > here in the past week? > > Actually I don't. I hadn't realised that when a person believes that > somebody has made an especially clever, witty, insightful or fun remark, > that's actually a put-down of all the other people whose remarks weren't > quite as clever, witty, insightful or fun. > > But now that I've had this pointed out to me, why, I see insults > everywhere! Tonight, my wife said to me that she liked my new shirt, so I > replied "What's the matter, you think my trousers are ugly?" > > -- > Steven No insult was intended. The writer stated that where Java minimizes bad, Python maximizes good. This is a non-trivial truth, and a non- trivial observation. Also, clever. I agreed and said so, and compliments go a long way. Do you? > everywhere! Tonight, my wife said to me that she liked my new shirt, so I > replied "What's the matter, you think my trousers are ugly?" Arf, arf. -- For my special power, I want immunity to insults. From imxmwu at gmail.com Thu Jul 31 09:44:33 2008 From: imxmwu at gmail.com (shrimpy) Date: Thu, 31 Jul 2008 23:44:33 +1000 Subject: problem when reading file Message-ID: <8e50c4e80807310644u3c456ab4qce06c6997707db8d@mail.gmail.com> hi every one, i am new to python, and coz i want to write a handy command for my linux machine, to find a word in all the files which are under the current folder. the code is half done, but when i run it, it complain, and i don`t know why??? can anyone help me have a look at it? here is the message it complain ======================================= file is : qt_plugins_3.3rc Traceback (most recent call last): File "./python_script/svn_grep.py", line 34, in searPatten(file,'are','no') File "./python_script/svn_grep.py", line 8, in searPatten openFile = open(file, 'r') IOError: [Errno 2] No such file or directory: 'qt_plugins_3.3rc' here are the code i wrote ---------------------------------------------------------------code begin #!/usr/bin/python import os import string def searPatten(file, patten, isCaseSensitive): openFile = open(file, 'r') lines = openFile.readlines() lineNum = 1 for text in lines : words = text.split() existed = 0 for word in words : if isCaseSensitive == 'yes' : if word.lower() == patten.lower(): existed = 1 break else: if word == patten : existed = 1 break if existed == 1: print "line : " + str(lineNum) + " " + text lineNum += 1 openFile.close() for root, dirs, files in os.walk(os.getcwd()): for file in files: print "=======================================" print "file is : " + file + "\n" searPatten(file,'are','no') ---------------------------------------------------------------code end From castironpi at gmail.com Tue Jul 29 00:00:24 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 28 Jul 2008 21:00:24 -0700 (PDT) Subject: block/lambda References: <0406eb4f-8dec-4ce2-b506-8e597de2958d@56g2000hsm.googlegroups.com> <01754831-dde2-4c15-805c-236f841e3e2b@d77g2000hsb.googlegroups.com> Message-ID: On Jul 28, 3:12?pm, iu2 wrote: > On Jul 28, 10:06?pm, iu2 wrote: > > > > > Hi, > > > Playing with imitating lambdas and ruby blocks in Python, I came up > > with a very simple construct, for example: > > > import compiler > > > def dotimes(i, code): > > ? ? for i in range(i): > > ? ? ? ? exec code > > > dotimes(5, ''' > > for j in range(i): > > ? ? ? ? print j, > > print > > ''', '', 'exec') > > > This will print > > 0 > > 0 1 > > 0 1 2 > > 0 1 2 3 > > > A more efficient code would probably be > > > dotimes(5, compiler.compile(''' > > for j in range(i): > > ? ? ? ? print j, > > print > > ''', '', 'exec')) > > > which is, to my understanding, exactly what a ruby block is. > > > But the actual "discovery" here, is that the triple quote - ''' - > > makes a syntax for block passing. Having a code editor that keeps > > colorizing what's inside the quotes like a normal code would make it > > easier to maintain. > > > Is it possible to grant Python another syntactic mark, similar to > > triple quotes, that will actually make the enclosed code a compiled > > code, or an anonymous function? > > > I know that anonymous functions (long lambdas...) are not on the road > > map. But I ask this because, as I understand it, the triple quote > > actually presents a syntax for it. > > Isn't it actually a matter of taking the triple-quotes a little bit > > further? > > > Thanks > > There is a mistake in my first example, the code is, of course: > dotimes(5, ''' > for j in range(i): > ? ? ? ? print j, > print > ''') > > Sorry... You could do code= '''# for _ in range( 2 ): pass ''' and signify the code block to your editor with the leading blank comment. From yuwenwu001 at gmail.com Sat Jul 19 10:17:42 2008 From: yuwenwu001 at gmail.com (kjldf) Date: Sat, 19 Jul 2008 07:17:42 -0700 (PDT) Subject: cheap shox NZ shoes PayPal Message-ID: cheap shox NZ shoes PayPal welcome to shopping on www.cheapest-paypal.cn 1.5% paypal handling charge supports the online payment! 2.Use your intergla replacement more good gift! 3.notes by email and website of deliver each package at first time. Have a good day! Sincerely yours, CHINASILKROAD EXPORTS CO., LTD From tcfg at sina.com Thu Jul 24 07:17:03 2008 From: tcfg at sina.com (fang) Date: Thu, 24 Jul 2008 04:17:03 -0700 (PDT) Subject: how to cut and paste in the windows of python(command line) Message-ID: <9500663c-0985-4dfd-8d0a-ae25411f00e5@v39g2000pro.googlegroups.com> Dear all: The mouse cannot be responded in the windows of python(command line) and cut and paste cannot be done. ctrl c and ctrl v do not work. But they do work in IDLE. please teach me about the python(command line). From bj_666 at gmx.net Wed Jul 16 00:32:08 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Jul 2008 04:32:08 GMT Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> <7348c0dc-028d-4f89-9d63-b1247fb6807c@m44g2000hsc.googlegroups.com> Message-ID: <6e5bu8F5eajaU1@mid.uni-berlin.de> On Tue, 15 Jul 2008 19:54:30 -0700, Yosifov Pavel wrote: > Kay, can you show example of such generator? ReIter, for example, work > with usual generators. > > But for "big" iterator, I think is no any good solutions. IMHO we can > discern 2 types of iterators: re-startable (based on internal Python > objects) and not re-startable (with an external state, side- > effects)... Has nothing to do with internal vs. external. Examples: ``itertools.count(1)``, ``itertools.cycle(iterable)``, or def fib(): a, b = 0, 1 while True: yield a a, b = b, a + b Ciao, Marc 'BlackJack' Rintsch From kyosohma at gmail.com Wed Jul 16 13:33:49 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 16 Jul 2008 10:33:49 -0700 (PDT) Subject: how can i save my command prompt screen? References: Message-ID: <0e67407b-c595-4b02-9d25-21c9ee7ea9ed@f36g2000hsa.googlegroups.com> On Jul 16, 12:28?pm, norseman wrote: > Ty hensons wrote: > > ?> how can i save my command prompt screen? > > ============================================== > > That by itself leaves lots of questions. ?Taken literally to be the > "box" then: > > In Microsoft use the "Print Screen" followed by mspaint and Edit/paste > ? ?(Or SHIFT-PrintScreen if whole screen showed up, I forget which it is. > ? ? ?One does just the box that is hot while the other gets all) > In Windows you can right-click, choose "Mark" and then select the text. Hit to copy it to the clipboard. Then you can paste it into any text editor you like. > Steve > norse... at hughes.net Mike From bedouglas at earthlink.net Mon Jul 21 16:19:21 2008 From: bedouglas at earthlink.net (bruce) Date: Mon, 21 Jul 2008 13:19:21 -0700 Subject: Trying to solve a python/mechanize "error 500" http error Message-ID: <24db01c8eb6f$103783b0$0301a8c0@tmesa.com> i'm getting the following error: mechanize._response.httperror_seek_wrapper: HTTP Error 500: i'm running python 5.1 and mechanize 0.1.7b I have no idea as to what I have to change/modify/include to handle this issue. The link that I'm testing is at the bottom of the page. When I insert the link into the browser, I actually get an err page.. so, I suspect that there is a handler that I should be able to modify/use to handle this situation... Thoughts/Comments will be greatly appreciated... Thanks the output is: www = www.1800ink.com url2= http://www.quantcast.com/www.1800ink.com/traffic Traceback (most recent call last): File "./reseller_scrape_child.py", line 288, in q1 = shopfuncs.quant(rhref) File "/adkiller/shopfuncs.py", line 56, in quant br.open(url2) File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 203, in open File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 254, in _mech_open mechanize._response.httperror_seek_wrapper: HTTP Error 500: [root at toshiba adkiller]# ./reseller_scrape_child.py my code segment looks like: ==================================== from mechanize import Browser import mechanize br = Browser() user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values1 = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } #br.set_cookiejar(cj) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.addheaders = [('User-Agent', 'Firefox')] url2 ="http://www.quantcast.com/xxxx/traffic" #gets the page (url) from the quantcast app url2=url2.replace("xxxx",url) print "url2=",url2 br.open(url2) ======================================= this works ok for most of the sites.. but something weird is happening with the actual page: http://www.quantcast.com/www.1800ink.com/traffic thanks... From castironpi at gmail.com Fri Jul 11 15:27:32 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 11 Jul 2008 12:27:32 -0700 (PDT) Subject: Using the Random Module. References: Message-ID: On Jul 11, 1:29?pm, WDC wrote: > On Jul 11, 2:15?pm, Michiel Overtoom wrote: > > > You wrote... > > >Is there a better way to do that besides doing this: > > > >>>>random.randint(00000000000000000, 99999999999999999) > > >09657398671238769 > > > Maybe this? > > > ? ? ? ? random.randint(0, 9e16) > > > -- > > "The ability of the OSS process to collect and harness > > the collective IQ of thousands of individuals across > > the Internet is simply amazing." - Vinod Vallopillilhttp://www.catb.org/~esr/halloween/halloween4.html > > That would work yes, but is there a random() function that would do > that without the attributes? Not trying to be lazy, I just want to > know if there is a built in way. > > Thanks Michiel. You want a random integer. Is there a range you want it in? Past a certain point, you'll exceed the granularity of the random number generator, and some values in the range will never be generated. From eckhardt at satorlaser.com Thu Jul 31 07:30:21 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 31 Jul 2008 13:30:21 +0200 Subject: How smart is the Python interpreter? References: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> Message-ID: ssecorp wrote: > def str_sort(string): > s = "" > for a in sorted(string): > s+=a > return s > > > if i instead do: > > def str_sort(string): > s = "" > so = sorted(string) > for a in so: > s+=a > return s > > will that be faster or the interpreter can figure out that it only has > to do sorted(string) once? Actually, by replacing sorted() with a function that outputs when it is called you could have seen that this is only called once in both cases. It must not be called more than once in fact, consider e.g. the case that it introduces side effects (like e.g. reading a file). Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From google at mrabarnett.plus.com Wed Jul 16 17:54:33 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 16 Jul 2008 14:54:33 -0700 (PDT) Subject: Setting Message Importance using SMTP Mail References: <33672217-148c-4c6a-96be-25ef88ba773f@k37g2000hsf.googlegroups.com> Message-ID: On Jul 16, 4:42?pm, Whyatt wrote: > Hi all, > > I'm trying to create a message using SMTP Mail through Python with a > message Importance of either 0 (Low) or 2 (High). > > If I do outer.Add_header('Importance', '0') it is ignored. > > If I do uter.Replace_header('Importance', '0') I get the error below. > Traceback (most recent call last): > ? File "#####", line 840, in > ? ? outer.Replace_header('Importance', '0') > AttributeError: MIMEMultipart instance has no attribute > 'Replace_header' > > Can anyone provide any clues on the correct way of updating the Msg > Importance header? > Are you sure that shouldn't be outer.add_header(...) and outer.replace_header()? From bignose+hates-spam at benfinney.id.au Wed Jul 30 09:18:27 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 30 Jul 2008 23:18:27 +1000 Subject: Standard module for parsing emails? References: Message-ID: <87provbjdo.fsf@benfinney.id.au> Phillip B Oldham writes: > Is there a standard library for parsing emails that can cope with > the different way email clients quote? "Cope with" in what sense? i.e., what would the behaviour of such a library be? What would it do? Note also that it's not merely the mail client that does the quoting; frequently the user composing the message will have a heavy hand in how the quoted material appears. -- \ ?Time flies like an arrow. Fruit flies like a banana.? ?Groucho | `\ Marx | _o__) | Ben Finney From ewertman at gmail.com Sat Jul 26 16:10:58 2008 From: ewertman at gmail.com (Eric Wertman) Date: Sat, 26 Jul 2008 16:10:58 -0400 Subject: os.walk question In-Reply-To: References: Message-ID: <92da89760807261310r39df1109j4cf7133d8144508b@mail.gmail.com> I do this, mabye a no-no? import os for root,dirs,files in os.walk(dir) : break From kyosohma at gmail.com Fri Jul 25 09:46:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 25 Jul 2008 06:46:25 -0700 (PDT) Subject: Calling external program from within python References: Message-ID: On Jul 25, 7:56?am, Emmanouil Angelakis wrote: > Hi, > > I am tryiong to do something obviously trivial such as: > I have a c program called "tsys2list" that when it is ran it asks the user to give the value of "tcal" which is a variable. I want to call the ?"tsys2list" from within a pyrthon script lets call it "gamma.py" >>>but<<< I want to pass the value of "tcal" to th eprogram automatically and not by interacting with the keyboard. > > How do I do that? > > thanks i advance! > manolis There are probably many ways to do this. I would recommend checking out the subprocess module and see if it does what you want. Or you could learn a little Tkinter or wxPython and use that to get the user's variable. Or you could even do it via the command line using the "raw_input" command. http://docs.python.org/lib/module-subprocess.html Mike From nagle at animats.com Wed Jul 30 14:30:11 2008 From: nagle at animats.com (John Nagle) Date: Wed, 30 Jul 2008 11:30:11 -0700 Subject: Native Code vs. Python code for modules In-Reply-To: References: Message-ID: <4890aeb6$0$17192$742ec2ed@news.sonic.net> koblas wrote: > Ruby has been getting pummeled for the last year or more on the > performance subject. They've been working hard at improving it. From > my arm chair perspective Python is sitting on it's laurels and not > taking this as seriously as it probably should. PyPy was supposed to help, but that project has been dragging on for half a decade now. Personally, I think the Shed Skin approach is more promising. PyPy has too many different goals, and tends to generate lots of auxiliary tools, blogs, videos, and "sprints", but not a usable PyPy compiler. We'll have to see if PyPy 1.1 works. John Nagle From socyl at 987jk.com.invalid Tue Jul 29 16:40:36 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 20:40:36 +0000 (UTC) Subject: static variables in Python? Message-ID: Yet another noob question... Is there a way to mimic C's static variables in Python? Or something like it? The idea is to equip a given function with a set of constants that belong only to it, so as not to clutter the global namespace with variables that are not needed elsewhere. For example, in Perl one can define a function foo like this *foo = do { my $x = expensive_call(); sub { return do_stuff_with( $x, @_ ); } }; In this case, foo is defined by assigning to it a closure that has an associated variable, $x, in its scope. Is there an equivalent in Python? Thanks! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From paul.hankin at gmail.com Sat Jul 12 02:28:35 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Fri, 11 Jul 2008 23:28:35 -0700 (PDT) Subject: python scalability References: Message-ID: On Jul 10, 5:32?am, Tim Mitchell wrote: > I work on a desktop application that has been developed using python and > GTK (seewww.leapfrog3d.com). ?We have around 150k lines of python code > (and 200k+ lines of C). ?We also have a new project manager with a C# > background who has deep concerns about the scalability of python as our > code base continues to grow and we are looking at introducing more > products. ?I am looking for examples of other people like us (who write > desktop apps in python) with code bases of a similar size who I can > point to (and even better talk to) to help convince him that python is > scalable to 300+ lines of code and beyond. ?I have looked at the python > success stories page and haven't come up with anyone quite like us. > One of my project managers questions is: "Are we the only company in the > world with this kind and size of project?" > I want to say no, but am having trouble convincing myself, let alone him. > > If you are involved in this kind of thing please get in touch with me. Perhaps your manager is more concerned about python because he's less familiar with it, rather than because of scalability problems? Perhaps using python is actually a competitive advantage for your company? Have you seen this? http://www.paulgraham.com/pypar.html -- Paul Hankin From dullrich at sprynet.com Tue Jul 8 11:58:44 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 08 Jul 2008 10:58:44 -0500 Subject: "in"consistency? References: Message-ID: In article , Terry Reedy wrote: > David C. Ullrich wrote: > > >>>> 'ab' in 'abc' > > True > > 'a' in 'abc' works according to the standard meaning of o in collection. > > 'ab' in 'abc' could not work by that standard meaning because strings, > as virtual sequences, only contain characters (length 1 strings). Among > built-in collections, this limitation is unique to strings (and bytes, > in 3.0). So in 2.3, 'in' was given a useful extension of meaning that > is also unique to strings (and bytes). Ah, I didn't realize that this was new. Thanks - at least this means I was right about the way it worked formerly. > >>>> [1,2] in [1,2,3] > > False > > [1,2] can be an member of tuples, lists, dicts and other general > collections. [1,2] in collection therefore has that meaning, that it is > a single element of collection. Extending the meaning would conflict > with this basic meaning. Well of course. > > Is there a reason for the inconsistency? I would > > have thought "in" would check for elements of a > > sequence, regardless of what sort of sequence it was... > > It is not an inconsistency but an extension corresponding to the > limitation of what an string element can be. It's an inconsistency. That doesn't mean it's a bad thing or that I want my money back. It may well be a reasonable inconsistency - strings _can_ work that way while it's clear lists had better not. But it's an inconsistency. > Terry J. Reedy -- David C. Ullrich From wuwei23 at gmail.com Mon Jul 28 00:27:36 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 27 Jul 2008 21:27:36 -0700 (PDT) Subject: I love "shelf" BUT References: <1c2d28bb-06e8-4f02-a528-9d86f84366dd@n33g2000pri.googlegroups.com> Message-ID: <3f22dbca-43c8-497f-af77-c28d3df9ba1b@t1g2000pra.googlegroups.com> On Jul 28, 1:44?pm, Sera Jackson wrote: > Lot of thanks again, that's what I wanted to find, arguments against > it, I was aware I wan not speaking of sth new. Guido seems to keep hinting that someone should write a PEP, just so it can be officially denied and then there'll be a place to point to when the question arises again (as it inevitably will...) So if you wanna take a shot... :) From carsten.haese at gmail.com Tue Jul 15 13:32:40 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Tue, 15 Jul 2008 13:32:40 -0400 Subject: MySQL Insert In-Reply-To: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> References: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> Message-ID: maestroQC wrote: > cursor.execute("INSERT INTO es_accounts (dateCreated, > accountNumber, description, openingBalance) VALUES (%s, %s, %s > , %d)", (date, accountNumber, description, dec)) > File "c:\python25\lib\site-packages\MySQLdb\cursors.py", line 151, > in execute > query = query % db.literal(args) > TypeError: int argument required The placeholder for query parameters in MySQLdb is always %s, regardless of the data type the actual value might have. HTH, -- Carsten Haese http://informixdb.sourceforge.net From bdesth.quelquechose at free.quelquepart.fr Sat Jul 26 08:05:39 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 26 Jul 2008 14:05:39 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <488af527$0$14761$426a74cc@news.free.fr> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> <488af527$0$14761$426a74cc@news.free.fr> Message-ID: <488b1322$0$1294$426a74cc@news.free.fr> Bruno Desthuilliers a ?crit : (snip) > There are quite a few cases in Python where there are both a specific > magic method *and* a default behaviour based on another magic method if > the specific one is not implemented. Just out of my mind: s/out of my mind/Off the top of my head/ Pardon my french, and thanks to Tim Golden for the correction !-) From timothywayne.cook at gmail.com Sun Jul 13 23:28:06 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Mon, 14 Jul 2008 00:28:06 -0300 Subject: Malaysia python user group In-Reply-To: <487AC086.3010600@internetnowasp.net> References: <487AC086.3010600@internetnowasp.net> Message-ID: <1216006086.3028.25.camel@localhost.localdomain> Marcus, You should probably contact the Malaysian Public Sector Open Source Competency Centre (OSCC) in Cyberjaya. http://www.oscc.org.my HTH, Tim On Mon, 2008-07-14 at 10:57 +0800, Marcus.CM wrote: > Hi, > > I am thinking of promoting Python for the local developers here in > Malaysia, via Universities , seminars etc . > Is there already a user group here in Malaysia? Any pointers would help. > > Marcus. > > -- > http://mail.python.org/mailman/listinfo/python-list -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. Home page: https://launchpad.net/oship/ Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From max at alcyone.com Tue Jul 29 16:08:26 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 13:08:26 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> Message-ID: Carl Banks wrote: > On Jul 29, 1:30 pm, Carl Banks wrote: >> On Jul 29, 5:15 am, Heiko Wundram wrote: >> >>> I can't dig up a simple example from code I wrote quickly, but because of the >>> fact that explicit comparisons always hamper polymorphism >> I'm not going to take your word for it. Do you have code that >> demonstrates how "if x" improves polymorphism relative to simple >> explicit tests? > > And, in case it wasn't obvious, the way to demonstrate that "if x" > improves polymorphism relative to simple explicit tests would be > posting an example where "if x" works but a simple explicit test > doesn't. So don't accuse me of changing the question on you: it's the > same question. It's pretty elementary, and people thought just describing the issue of polymorphism and duck-typing was sufficient to explain it. Since it apparently isn't: Let's say you come up with some kind of custom sequence class. You want to act like any native sequence type (list, tuple, array, string, etc.) in all reasonable ways (length testing, iteration, indexing, etc.) so that it can be used in place of these things in code that doesn't require explicit types. You know, standard polymorphism and duck-typing. So you want a test for whether your custom sequence isn't empty. To create an "simple, explicit test" would be defined an `isntEmpty` method that you can call, like so: if myObject.isntEmpty(): # then do something However, this wouldn't be polymorphic since now someone would have to call a "simple, explicit test" that doesn't exist on all the other sequence-like objects. Therefore, you've broken polymorphism. The solution is to override the `__nonzero__` method so that you can use Boolean testing, just like all the other sequence-like objects: if myObject: # then do the same thing Now people who use your custom sequence type don't have to write special code, and code written to deal with sequences using duck typing (which is typically nearly all Python code) don't have to know anything special about your custom sequence class. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Everything's gonna be all right / Everything's gonna be okay -- Sweetbox From ethan at stoneleaf.us Wed Jul 30 05:17:56 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 30 Jul 2008 01:17:56 -0800 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> Message-ID: <489031C4.1030409@stoneleaf.us> Russ P. wrote: > Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > __nonzero__ work in Python. It's very basic stuff. You can quit > patronizing me (and Carl too, I'm sure). > > The point that you seem to be missing, or refuse to acknowledge for > some reason, is that "if x" can be mistakenly applied to any object > when the programmer thinks that x is a list -- and the programmer will > receive no feedback on the error. You know... or maybe you don't, since you did just say what you just said... that is such a ridiculous point it only barely qualifies as deserving comment. Rather than be really rude, I'll just say: test it's type() if the function is that specific, or your code that brittle. Python is not there to catch your logic mistakes, that's up to you. > I have made errors like that, and I could have saved some time had I > used an "empty" method that only applies to a list or other sequence. > > Is that an important issue? I don't know. I'm not claiming it is. But > you cannot just sweep it away as nothing. I don't sweep it away as nothing -- I sweep it away as stupid. The programmer is responsible for his (or her) program. An analogy would be a driver and a car -- if the driver cannot handle the power and speed of a fancy car (python :), then the driver should get a different car better matched to his abilities. It's not up to the car to say "oh, the speed limit is 50 here, I better apply the brakes for the driver." ~Ethan~ From motoom at xs4all.nl Tue Jul 15 19:47:19 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Wed, 16 Jul 2008 01:47:19 +0200 Subject: Python for Kids Message-ID: <2.2.32.20080715234719.01194a70@pop.xs4all.nl> Sean wrote... > Pretty cool!! Our base will be *much* bigger in about twenty years. > I remember doing Basic on my dads Apple IIe. Gee, I wish Python existed back then. I had to endure Commore Basic on the PET2001. The biggest challenge was how to fit the program in 8K... It didn't take me long to switch to 6502 machine language to get more out of it. And I was a really happy kid when the S100 systems with FORTRAN and simple C compilers came along ;-) I wish I still had my original K&R "Programming C" and Kernighan&Plaughers "Software Tools" using RATFOR, but they have been lost in the mist of years. Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From matt at tplus1.com Sun Jul 13 20:21:04 2008 From: matt at tplus1.com (Matthew Wilson) Date: Mon, 14 Jul 2008 00:21:04 GMT Subject: How to package a logging.config file? Message-ID: I'm working on a package that uses the standard library logging module along with a .cfg file. In my code, I use logging.config.fileConfig('/home/matt/mypackage/matt.cfg') to load in the logging config file. However, it seems really obvious to me that this won't work when I share this package with others. I can't figure out what path to use when I load my .cfg file. Any ideas? Matt From kraus at hagen-partner.de Fri Jul 18 08:41:18 2008 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Fri, 18 Jul 2008 14:41:18 +0200 Subject: substitution of list elements In-Reply-To: <247ab26d-ba98-42cc-bf6e-738b4b32a70c@q28g2000prh.googlegroups.com> References: <247ab26d-ba98-42cc-bf6e-738b4b32a70c@q28g2000prh.googlegroups.com> Message-ID: Am 18.07.2008 14:33, antar2 schrieb: > I want to replace each first element in list 5 that is equal to the > first element of the list of lists4 by the fourth element. I wrote > following code that does not work: > > list4 = [['1', 'a', 'b', 'c'], ['2', 'd', 't', 'e'], ['8', 'g', 'q', > 'f']] > list5 = ['1', '2', '3'] > > for j in list4: > for k in list5: for i,k in enumerate(list5): > if j[0] == k: > k = j[3] list5[i] = j[3] > print list5 > Wanted result: ['c', 'e', '3'] > > thanks! You didn't replace the list element itself. HTH, Wolfram From s0suk3 at gmail.com Fri Jul 25 05:27:34 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Fri, 25 Jul 2008 02:27:34 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> <5d3729f0-6e5d-4e3f-b4ed-e25f8ebc655f@q5g2000prf.googlegroups.com> Message-ID: <43d32584-e762-4578-82d9-0d4395bb4138@k36g2000pri.googlegroups.com> On Jul 25, 3:38 am, cokofreedom at gmail.com wrote: > > By that logic, C++ is not OO. By that logic, Ruby is not OO. By that > > logic, I know of only one OO language: Java :) > > > The fact that a language doesn't force you to do object-oriented > > programming doesn't mean that it's not object-oriented. In other > > words, your words are nonsense. > > No, what it means is that it might support OO but doesn't have to, it > isn't the only way to code. > "Support OO but it doesn't have to"? That sounds like saying that in some Python implementations you'll be able to use OO, but that you just might bump into a Python distribution where you would type class MClass: pass at the interpreter and it would give you an syntax error. Is that what you mean? > Supporting and Being OO are very different. I guess at this point it's rather pointless to discuss this because of the different and deep level of interpretation that we might have on the words "support" and "be." IMO, the obvious thing to say is that a language that *supports* OO can also be said to *be* OO. However, it would seem just ridiculous to me to say the same thing about a language like, e.g., Perl, where OO is so pathetic. But maybe this is just a game of words... I consider Python to *be* OO, anyway. Sebastian From jadamwilson2 at gmail.com Mon Jul 7 16:35:05 2008 From: jadamwilson2 at gmail.com (jadamwilson2 at gmail.com) Date: Mon, 7 Jul 2008 13:35:05 -0700 (PDT) Subject: sage vs enthought for sci computing Message-ID: <677e7819-e09e-43d3-8368-5864f91002be@34g2000hsh.googlegroups.com> Hello, I have recently become interested in using python for scientific computing, and came across both sage and enthought. I am curious if anyone can tell me what the differences are between the two, since there seems to be a lot of overlap (from what I have seen). If my goal is to replace matlab (we do signal processing and stats on physiological data, with a lot of visualization), would sage or enthought get me going quicker? I realize that this is a pretty vague question, and I can probably accomplish the same with either, but what would lead me to choose one over the other? Thanks! From gherron at islandtraining.com Thu Jul 24 16:27:52 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 24 Jul 2008 13:27:52 -0700 Subject: Reading a file In-Reply-To: <73045cca0807241306h370166ebwdd1b12227cef43c2@mail.gmail.com> References: <73045cca0807241306h370166ebwdd1b12227cef43c2@mail.gmail.com> Message-ID: <4888E5C8.1050502@islandtraining.com> aditya shukla wrote: > I have a text file whose contents are like this:- > > jd|fj|dnv|jd|0.33|c:\\windows\\win32 > shcbsbs|nscsjsj|0.93|hsbcjsnc > > I am trying to read the file like this:- > > >>> x = open("c:\\a.txt","r") Better to use "rb" (for binary read) rather than "r" mode. > >>> x.read() Now, tell us what you *really* did. Not that -- that would read the contents of the file, put throw the returned result away. You must have done something like c = x.read() > > the result that i get is ike this:- > 'jd|fj|dnv|jd|0.33|c:\\\\windows\\\\win32\nshcbsbs|nscsjsj|0.93|hsbcjsnc\n' > > My doubt is how can i read the file as it is? You *have* read the file as it is. Examine each character, and you'll see that the string is exactly as you expect. However, your output to the screen is escaping some character with backslashes. But that's just because of the method you used to print to the screen. What method *did* you use to print? If you just typed the variable into which you had read the contents, then you get the equivalent of print repr(c) which explains the escapes. Try print c and that won't happen. Gary Herron > > ie my output should be > > d|fj|dnv|jd|0.33|c:\\windows\\win32 > shcbsbs|nscsjsj|0.93|hsbcjsnc > > > Thanks in advance > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From jeffober at gmail.com Mon Jul 7 08:09:34 2008 From: jeffober at gmail.com (Jeff) Date: Mon, 7 Jul 2008 05:09:34 -0700 (PDT) Subject: Confused yet again: Very Newbie Question References: Message-ID: <13be8c54-3fa9-4a37-a0e6-45bb019bff7e@a1g2000hsb.googlegroups.com> When you call c3.createJoe(c1.fred), you are passing a copy of the value stored in c1.fred to your function. Python passes function parameters by value. The function will not destructively modify its arguments; you must expliticly state your intention to modify an object: class one(): fred = 'fred' class three(): def createJoe(self, myName): return "Joe" def main(): c1 = one() c3 = three() c1.fred = c3.createJoe() # Modify c1's attribute, fred, with the return value from c3.createJoe From barun.saha04 at gmail.com Mon Jul 21 07:42:35 2008 From: barun.saha04 at gmail.com (barun.saha04 at gmail.com) Date: Mon, 21 Jul 2008 04:42:35 -0700 (PDT) Subject: Problem with Python Server Pages (PSP) Message-ID: <9766b993-03e6-4b75-92a2-06244c41e51c@a1g2000hsb.googlegroups.com> Hi, I am facing a very basic problem with PSP. I have installed mod_python (in fedora Core 1), added the lines required for loading Python modules and handling PSP pages. I have created a hello.psp page. But when I try to view this hello.psp page, all Python code are getting displayed. The said page is stored at /var/www/html/psp/hello.psp. I guess this is some configuration problem with Apache, but not able to figure out the exact problem. I have tried putting those configuration lines for psp in both httpd.conf and python.conf files. But still it is not working. The Python module (mod_python) is getting loaded. Because when I telnet to my server, I can find that in the headers. These are the versions of the softwares: Apache: 2.0.47 Python: 2.2.3 mod_python: 3.0.3 Thnaks for all your suggestions. From bastard at example.org Tue Jul 15 07:57:41 2008 From: bastard at example.org (Anonymous Bastard) Date: Tue, 15 Jul 2008 14:57:41 +0300 Subject: Suggestion: Python global scope Message-ID: I've been tossing this idea in my mind for some time now: In Python, declaring a variable using the global statement automatically makes it available in all subsequent scopes. But to me, it makes more sense to use the global statement to 'import' a variable from the global scope into the current scope. For instance: [code] global X X = 1 def P(): X = 2 print X global X print X print X P() print X [code] Currently, this will print 1, 2, 2 and 2. But if global would be limited to current scope, it would print 1, 2, 1, 1. 'X = 2' would work on the local version of X, 'global X' will 'import' the global X into the local scope, so any actions on X would reference the global X, rather than previous X. From paul at boddie.org.uk Thu Jul 31 06:41:17 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 31 Jul 2008 03:41:17 -0700 (PDT) Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: <2a703a46-75bc-4228-95d1-05a4e6030b40@f63g2000hsf.googlegroups.com> <26c2fe8e-d464-44f0-8e57-3b8e82248691@x35g2000hsb.googlegroups.com> Message-ID: <69428617-ffc3-4f30-a267-102b68385341@34g2000hsf.googlegroups.com> On 30 Jul, 20:15, Peter Otten <__pete... at web.de> wrote: > Paul Boddie wrote: > > Who wants to be first to submit a patch? ;-) > > And where? The sourceforge page says > > "PyXML is no longer maintained." The minidom code is in the standard library: http://svn.python.org/view/python/trunk/Lib/xml/dom/ Paul From you2000too at gmail.com Mon Jul 21 23:31:59 2008 From: you2000too at gmail.com (youtoo) Date: Mon, 21 Jul 2008 20:31:59 -0700 (PDT) Subject: Time Complexity of String Operations Message-ID: It has been extensively discussed the time complexity (quadratic) of string concatenation (due to string's immutability). But what is: == the time complexity of string indexing? Is it constant? == the time complexity of string slicing? Is it O(K) with K the slice's length? How are strings stored in Python? As arrays? As linked lists? Thanks a lot! yt. From maric at aristote.info Thu Jul 31 11:08:08 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 31 Jul 2008 17:08:08 +0200 Subject: Difference between type and class In-Reply-To: <87tze6862j.fsf@nokile.rath.org> References: <87myjy2vc6.fsf@nokile.rath.org> <87tze6862j.fsf@nokile.rath.org> Message-ID: <200807311708.09241.maric@aristote.info> Le Thursday 31 July 2008 16:46:28 Nikolaus Rath, vous avez ?crit?: > Maric Michaud writes: > >> > Can someone explain to me the difference between a type and a class? > >> > >> If your confusion is of a more general nature I suggest reading the > >> introduction of `Design Patterns' (ISBN-10: 0201633612), under > >> `Specifying Object Interfaces'. > >> > >> In short: A type denotes a certain interface, i.e. a set of signatures, > >> whereas a class tells us how an object is implemented (like a > >> blueprint). A class can have many types if it implements all their > >> interfaces, and different classes can have the same type if they share a > >> common interface. The following example should clarify matters: > > > > Of course, this is what a type means in certain literature about OO > > (java-ish), but this absolutely not what type means in Python. Types > > are a family of object with a certain status, and they're type is > > "type", conventionnaly named a metatype in standard OO. > > [...] > > Hmm. Now you have said a lot about Python objects and their type, but > you still haven't said what a type actually is (in Python) and in what > way it is different from a class. Or did I miss something? This paragraph ? """ - types, or classes, are all instance of type 'type' (or a subclass of it), they can be instantiated and they produce objects (ordinary object in general) with theirslef as a type. """ Maybe it's still unclear that "types" and "classes" *are* synonyms in Python. -- _____________ Maric Michaud From frankrentef at yahoo.com Thu Jul 31 11:00:22 2008 From: frankrentef at yahoo.com (frankrentef) Date: Thu, 31 Jul 2008 08:00:22 -0700 (PDT) Subject: HELP - Attribute Error, no matter what I do on PAMIE... Message-ID: <38ed1b14-fb96-4891-9188-c62337aeef89@f36g2000hsa.googlegroups.com> Greetings all. I'm new to PAMIE and I've watched / followed to PAMIE videos on Show me Do. I've tried to duplicate the "scriptWrite" function in an attempt to automate the forms process... without success. Can someone PLEASE Assist!? I'm using the following code.... from cPAMIE import PAMIE #Imports - used to setup / control finding files import time import os import sys import cReport #import elementtree.ElementTree as ET #Create New Pamie Object ie=PAMIE() ie=Visible =1 t=time ie=PAMIE () ie.navigate ('http://bir1edptest2/iswebcommander/fi/default.aspx') ie.scriptWrite() And getting the following error.... Atribute Error:.nameProp File "C:\PYCODE\scriptWrite TEST.py", line 19, in ? ie.scriptWrite() File "C:\Python24\Lib\site-packages\cPAMIE.py", line 1837, in scriptWrite nameProp = getattr(x,"nameProp") File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 496, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) From hnsri49 at gmail.com Mon Jul 7 05:14:46 2008 From: hnsri49 at gmail.com (cna) Date: Mon, 7 Jul 2008 02:14:46 -0700 (PDT) Subject: python beginner Message-ID: <1cd8ffae-62a7-4cfb-b3ab-61c7004841c9@8g2000hse.googlegroups.com> Hi all and one, how may i learn python. is there any other website except python.org From jurgenex at hotmail.com Tue Jul 22 06:38:07 2008 From: jurgenex at hotmail.com (Jürgen Exner) Date: Tue, 22 Jul 2008 10:38:07 GMT Subject: proliferation of computer languages References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> <40429b65-23a0-489b-b5fd-ae6b8eee607d@t54g2000hsg.googlegroups.com> Message-ID: Chris Rathman wrote: >I can't say that I see any particular point to the essay. You must be new here. There never is any particular point to Xah Lee's rantings except to cross-post borderline topics to borderline relevant NGs and then lay back and enjoy the ensuing slaughter. PLEASE DO NOT FEED THE TROLL >On Jul 18, 12:17 pm, "xah... at gmail.com" wrote: jue From deanfamily11 at verizon.net Tue Jul 1 18:20:48 2008 From: deanfamily11 at verizon.net (Brandon) Date: Tue, 01 Jul 2008 22:20:48 GMT Subject: Required items in a form Message-ID: <45yak.331$Ae3.313@trnddc05> What I'm trying to do is essentially force a user to fill in required items in a form, which will be saved to a database. How can I get it so that once the user clicks "OK" on the dialog box, it transfers control back to the form, and not save the empty fields into the database? From stef.mientki at gmail.com Tue Jul 8 18:43:03 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 09 Jul 2008 00:43:03 +0200 Subject: find all ODBC databases ? Message-ID: <4873ED77.7080507@gmail.com> hello, I'm working on a general database manager, which will be open source and should preferable work under all OS. Now in windows I can find the ODBC databases by reading some reg key. I also know that ODBC is supported under Linux (I don't know anything of Linux), but how can I get all ODBC databases in a platform independant way ? thanks, Stef Mientki From emen999 at gmail.com Wed Jul 23 11:37:38 2008 From: emen999 at gmail.com (code_berzerker) Date: Wed, 23 Jul 2008 08:37:38 -0700 (PDT) Subject: lxml, comparing nodes Message-ID: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> I'd like to know if there is any built in mechanism in lxml that lets you check equality of two nodes from separate documents. I'd like it to ignore attribute order and so on. It would be even better if there was built in method for checking equality of whole documents (ignoring document order). Please let me know if you know of such method or existing scipt. I dont like reinventing the wheel :) From diordna at gmail.com Tue Jul 15 09:42:39 2008 From: diordna at gmail.com (Stephen Johnson) Date: Tue, 15 Jul 2008 09:42:39 -0400 Subject: Python embedding question. In-Reply-To: <5e0e47aa-a7bc-4e43-98cd-07fc0f6fe454@l42g2000hsc.googlegroups.com> References: <45f657a0-315f-421e-8d69-1c5b24e23887@k37g2000hsf.googlegroups.com> <5e0e47aa-a7bc-4e43-98cd-07fc0f6fe454@l42g2000hsc.googlegroups.com> Message-ID: The Pyglet library has all the functionality of pygame, but is smaller and much more self-contained. Pygame requires SDL, pyglet only OpenGL. On Jul 15, 2008, at 6:26 AM, Uwe Schmitt wrote: > On 15 Jul., 12:14, Thomas Troeger > wrote: >> Kay Schluehr wrote: >>> On 15 Jul., 11:51, Thomas Troeger >>> wrote: >> >>>> I've really looked at a lot of places but haven't found a suitable >>>> solutions yet, so I'm asking here in hope that someone has >>>> experience >>>> with that topic. >> >>> Which solutions did you rule out? >> >> - Python + Qt, because it's definitely overkill for my plans. I only >> need simple graphics and some sound, no widgets. Basically I'm >> looking >> for something really lightweight that has methods for drawing graphic >> primitives and renders fonts -- no complicated widgets, windows, >> scrollbars and the like. And, for example, the Qt library is a real >> heavyweight with approx. 10 MB for qt-3.3.8 alone. >> >> - The same holds for cairo/pango, I've written a test program (in >> C, I >> must say) that has dynamic links to 10 libraries that are all like >> 250kb >> in size. That's a lot for a small embedded device. >> > Did you try pygame ? I think it has a small footprint. > > Greetings, Uwe > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From ki4yjl at gmail.com Fri Jul 11 14:29:04 2008 From: ki4yjl at gmail.com (WDC) Date: Fri, 11 Jul 2008 11:29:04 -0700 (PDT) Subject: Using the Random Module. References: Message-ID: On Jul 11, 2:15?pm, Michiel Overtoom wrote: > You wrote... > >Is there a better way to do that besides doing this: > > >>>>random.randint(00000000000000000, 99999999999999999) > >09657398671238769 > > Maybe this? > > ? ? ? ? random.randint(0, 9e16) > > -- > "The ability of the OSS process to collect and harness > the collective IQ of thousands of individuals across > the Internet is simply amazing." - Vinod Vallopillilhttp://www.catb.org/~esr/halloween/halloween4.html That would work yes, but is there a random() function that would do that without the attributes? Not trying to be lazy, I just want to know if there is a built in way. Thanks Michiel. From siona at chiark.greenend.org.uk Thu Jul 10 08:09:10 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 10 Jul 2008 13:09:10 +0100 (BST) Subject: Allow tab completion when inputing filepath? References: <08e60124-51c1-40c1-bffe-52c22ff310db@l64g2000hse.googlegroups.com> Message-ID: Keith Hughitt wrote: >> Keith Hughitt wrote: >> > [ ... ] I have >> > found some ways to enable tab completion for program-related commands, >> > but not for system filepaths. >Currently Unix/Console. What's wrong with the readline module? http://docs.python.org/lib/module-readline.html -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From james at reggieband.com Thu Jul 10 13:06:36 2008 From: james at reggieband.com (James Fassett) Date: Thu, 10 Jul 2008 10:06:36 -0700 (PDT) Subject: Idiomatic Python to convert list to dict Message-ID: <7ec9405c-4e6f-491d-84b2-c81152302b13@79g2000hsk.googlegroups.com> Hi all, Simple question really on a best practice. I want to avoid adding duplicates to a list. my_list = ['a', 'b', 'c', 'd', 'e'] dup_map = {} for item in my_list: dup_map[item] = True # ... sometime later for complex_dict in large_list: if complex_dict["char"] not in dup_map: my_list.append(complex_dict["char"]) dup_map[complex_dict["char"]] = True For the first part (generating the duplicate map) is there a more idiomatic Python method for flipping the list into a dict? Is there a better way to achieve the overall objective (as hinted at by the above algorithm)? Thanks in advance for any tips. James. From animator333 at yahoo.com Thu Jul 17 00:29:08 2008 From: animator333 at yahoo.com (Prashant Saxena) Date: Wed, 16 Jul 2008 21:29:08 -0700 (PDT) Subject: subtype and super method. How to? Message-ID: <623762.62274.qm@web33406.mail.mud.yahoo.com> import sys class Attribute(object): ??? """ ??? Common attributes and methods for custom types ??? """ ??? __slots__ = [] ?? ? ??? def __init__(self, name=None, type=None, range=(0,1)): ??????? self.__name = name ??????? self.__type = type ??????? self.__range = range ?? ? ??? #Read only attributes ??? name = property(lambda self: self.__name) ??? type = property(lambda self: self.__type) ??? range = property(lambda self: self.__range) ?????? ? class Float(float, Attribute): ??? '''Custom Float type''' ??? __slots__ = ('__name', '__type', '__range') ??? def __new__(self, value=0.0, name=None, type=None, range=(0.0, 1.0)): ??????? try: ??????????? super(Float, self).__init__(name=name, type=type, range=range) ??????????? return float.__new__(self, value) ??????? except: ??????????? print 'Error : %s %s' % sys.exc_info()[:2] ?????????????? ? class Int(int, Attribute): ??? '''Custom Int type''' ??? __slots__ = ('__name', '__type', '__range') ??? def __new__(self, value=0, name=None, type=None, range=(0, 1)): ??????? try: ??????????? super(Int, self).__init__(name=name, type=type, range=range) ??????????? return int.__new__(self, value) ??????? except: ??????????? print 'Error : %s %s' % sys.exc_info()[:2] a = Float(2.0, name='myFloat') print a 'Float' & 'Int' instances are not getting initialize. How to solve? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From desothier at yahoo.com Wed Jul 9 04:56:19 2008 From: desothier at yahoo.com (antar2) Date: Wed, 9 Jul 2008 01:56:19 -0700 (PDT) Subject: delete lines Message-ID: <35d53620-16c7-4c2c-b904-04dbab6bc91a@z66g2000hsc.googlegroups.com> I am new in python and I have the following problem: Suppose I have a list with words of which I want to remove each time the words in the lines below item1 and above item2: item1 a b item2 c d item3 e f item4 g h item1 i j item2 k l item3 m n item4 o p I did not find out how to do this: Part of my script was f = re.compile("item\[1\]\:") g = re.compile("item\[2\]\:") for i, line in enumerate(list1): f_match = f.search(line) g_match = g.search(line) if f_match: if g_match: if list1[i] > f_match: if list1[i] < g_match: del list1[i] But this does not work If someone can help me, thanks! From carsten.haese at gmail.com Sun Jul 20 00:24:25 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Sun, 20 Jul 2008 00:24:25 -0400 Subject: atan2 weirdness In-Reply-To: <3b3ce28f-55d0-4db4-8eac-df0a9d1bc558@o40g2000prn.googlegroups.com> References: <3b3ce28f-55d0-4db4-8eac-df0a9d1bc558@o40g2000prn.googlegroups.com> Message-ID: narutocanada at gmail.com wrote: > hi > > atan2 is supposed to return the angle to x-axis when given y and x, I > suppose if I take [x,y] to one full circle, I should get 0-360 degree > back---- but no, I get 3 full revolutions! > maybe my understanding is wrong. > > from math import * > > def f(ang): > a=ang > if a>360: a-=360 > if a>360: a-=360 > if a<0: a+=360 > if a<0: a+=360 > return round(a) > > for i in range(0,360): > t=2*pi*i/360.0 > print i,f(atan2(sin(t),cos(t))*180.0) Your understanding of atan2 is correct, but your conversion from radians to degrees is off by a factor of pi. Since pi is close to 3, you're getting what appears to be three full revolutions. HTH, -- Carsten Haese http://informixdb.sourceforge.net From arazak73 at yahoo.com.my Tue Jul 1 23:12:14 2008 From: arazak73 at yahoo.com.my (ajak_yahoo) Date: Wed, 2 Jul 2008 11:12:14 +0800 Subject: how to used pyodbc to connect foxpro table Message-ID: <014501c8dbf1$70018c10$1f01a8c0@RAZAK> Good Morning to All, Can anyone help me to connect pyodbc to foxpro table. Below code can't works. import pyodbc cnxn = pyodbc.connect("DSN=sls_detl") Traceback (most recent call last): File "", line 1, in cnxn = pyodbc.connect("DSN=sls_detl") Error: ('S1000', "[S1000] [Microsoft][ODBC Visual FoxPro Driver]File is not open. (113) (SQLDriverConnectW); [01000] [Microsoft][ODBC Driver Manager] The driver doesn't support the version of ODBC behavior that the application requested (see SQLSetEnvAttr). (0)") T.q -------------- next part -------------- An HTML attachment was scrubbed... URL: From maric at aristote.info Fri Jul 18 06:28:26 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 18 Jul 2008 12:28:26 +0200 Subject: sub typing built in type with common attributes. Am I right? In-Reply-To: <98c3de7d-f167-48f9-9736-b09938d96b92@f40g2000pri.googlegroups.com> References: <4d9c4b74-9c28-4b98-afe7-9eb774655c3a@v21g2000pro.googlegroups.com> <98c3de7d-f167-48f9-9736-b09938d96b92@f40g2000pri.googlegroups.com> Message-ID: <200807181228.26446.maric@aristote.info> Le Friday 18 July 2008 11:36:20 King, vous avez ?crit?: > Could you please suggest an alternative or code improvement for the > matter. I'm not sure what you are trying to achieve with your snippet, but I suspect it's some sort of templating, right ? If so, using the dynamic nature of python should help : >>>[103]: def make_subtype_with_attr(type_, ro_attr, rw_attr) : dic = {} for i in ro_attr : dic[i] = property(lambda s, n=i : getattr(s, '_'+n)) def __new__(cls, *args, **kwargs) : instance = type_.__new__(cls, *args) for i in rw_attr : setattr(instance, i, kwargs[i]) for i in ro_attr : setattr(instance, '_'+i, ro_attr[i]) return instance dic['__new__'] = __new__ return type('my_' + type_.__name__, (type_,), dic) .....: >>>[113]: my_int = make_subtype_with_attr(int, {'name' : 'myint', 'id':123452}, ('foo',)) >>>[114]: i = my_int(5, foo=3) >>>[115]: i.foo ...[115]: 3 >>>[116]: i ...[116]: 5 >>>[117]: i.id ...[117]: 123452 >>>[118]: i.id = 2 --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /home/maric/ in () AttributeError: can't set attribute -- _____________ Maric Michaud From chrisspen at gmail.com Sun Jul 13 21:01:01 2008 From: chrisspen at gmail.com (Chris) Date: Sun, 13 Jul 2008 18:01:01 -0700 (PDT) Subject: Using Groups inside Braces with Regular Expressions References: <10284e46-1601-4269-a1a0-ef3831e9f85c@z66g2000hsc.googlegroups.com> <87e2b1a0-e732-42d3-aa94-061dcd81d35c@z72g2000hsb.googlegroups.com> Message-ID: <262021b7-ebdf-47ec-817f-54e42e84a94e@f63g2000hsf.googlegroups.com> On Jul 13, 8:14 pm, MRAB wrote: > On Jul 14, 12:05 am, Chris wrote:> I'm trying to delimit sentences in a block of text by defining the > > end-of-sentence marker as a period followed by a space followed by an > > uppercase letter or end-of-string. > > > I'd imagine the regex for that would look something like: > > [^(?:[A-Z]|$)]\.\s+(?=[A-Z]|$) > > > However, Python keeps giving me an "unbalanced parenthesis" error for > > the [^] part. If this isn't valid regex syntax, how else would I match > > a block of text that doesn't the delimiter pattern? > > What is the [^(?:[A-Z]|$)] part meant to be doing? Is it meant to be > matching everything up to the end of the sentence? > > [...] is a character class, so Python is parsing the character class > as: > > [^(?:[A-Z]|$)] > ^^^^^^^^^^ It was meant to include everything except the end-of-sentence pattern. However, I just realized that I can simply replace it with ".*?" From fuzzyman at gmail.com Fri Jul 11 09:25:47 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Fri, 11 Jul 2008 06:25:47 -0700 (PDT) Subject: ANN: P4D 1.1 References: Message-ID: On Jul 11, 10:09?am, Kay Schluehr wrote: > P4D = E4X style embedded DSL for Python but without E and X. > > For more information see: > > http://pypi.python.org/pypi/P4D/1.1-py2.5 That looks a lot like YAML. Any reason to use it over YAML? Michael Foord http://www.ironpythoninaction.com/ From google at mrabarnett.plus.com Mon Jul 14 11:44:55 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 14 Jul 2008 08:44:55 -0700 (PDT) Subject: Python beginner, unicode encode/decode Q References: <487B4BC5.7FA8FFF9@anonymous.com> Message-ID: <5ebb3820-4452-418a-bc01-9084701053bc@k30g2000hse.googlegroups.com> On Jul 14, 1:51?pm, anonymous wrote: > 1 Objective to write little programs to help me learn German. ?See code > after numbered comments. //Thanks in advance for any direction or > suggestions. > > tk > > 2 ?Want keyboard answer input, for example: ? > > answer_str ?= raw_input(' Enter answer > ') Herr ??? > > [ I keyboard in the following characters Herr ?? ] > print answer_str > Output on screen is > Herr ?? > > 3 ? history 1 and 2 ?code run interactively under Debian Linux Python > 2.4 and interactively under windows98, first edition IDLE, Python 2.3.5 > and it works. > > 4 ?history 3 and 4 code run from within a .py file produce different > output from example in book. > > 5 want to operate under Debian Linux but because the program failed > under Linux when I tried to run the code from a file in Linux Python, I > thougt I should fire up the win98 Idle/python program and try it to see > if ran there but it failed, too from within a file. > > 6 The sample code is from page 108-109 of: ? "Python for Dummies" > ? ? ? It says in the book: ?"Python's file objects and StringIO objects > don't support raw Unicode; the usual workaround is to encode Unicode as > UTF-8 before saving it to a file or stringIO object. ? > The sample code from the book is French as indicate here but trying > German produces the same result. > > 7 I have searched the net under all the keywords but this is as close as > I get to accomplishing my task. ?I suspect I may not be understanding: > StringIO objects don't support raw Unicode, but I don't know. > > #_*_ coding: utf-8 _*_ > > # code run under linux debian ?interactively from a terminal and works > > print " u'Libert\u00e9' " > > # y = raw_input('Enter >') ?commented out > > y = u'Lbert\u00e9' > y.encode('utf-8') > q = y.encode('utf-8') > q.decode('utf-8') > print q.decode('utf-8') > > history 1 works and here is the screen copy of interactive > > ?>>> y = raw_input ('>') > ?>Libert\xc3\xa9 > ?>>> q = 'Libert\xc3\xa9' > ?>>> q.decode('utf-8') > u'Libert\xe9' > ?>>> print q > Libert? > ?>>> > > [ ?screen output is next line ] > > Lbert? > > history 2 > # code run under win98, first edition, within IDLE interactively and > succeeded in produce correct results. > > # y = raw_input('Enter >') ?commented out > > y = u'Lbert\u00e9' > y.encode('utf-8') > q = y.encode('utf-8') > q.decode('utf-8') > print q.decode('utf-8') > > history 1 works and here is the screen copy of interactive > > ?>>> y = raw_input ('>') > ?>Libert\xc3\xa9 > ?>>> q = 'Libert\xc3\xa9' > ?>>> q.decode('utf-8') > u'Libert\xe9' > ?>>> print q > Libert? > ?>>> > > [ ?screen output is next line ] > > Lbert? > > # history 3 > > # this code is run from within idle on win98 and inside a python file. ? > # ?The code DOES NOT produce the proper outout. > > #_*_ coding: utf-8 _*_ > > # print "u'Libert\u00e9'" ?printed to screen > > y = raw_input('Enter >') > > # y = u'Lbert\u00e9' commented out > > y.encode('utf-8') > q = y.encode('utf-8') > q.decode('utf-8') > print q.decode('utf-8') > > # output is ?on the lines ?below was produced on the screen after run > > enter u'Libert\u00e9' on screen to copy into into y string > Enter >u'Libert\u00e9' > > u'Libert\u00e9' > > The code DOES NOT produce Libert? but instead produce u'Libert\u00e9' > > # history 4 > > # this code is run from within terminal on Debian linux ? inside a > python file. ? > # The code does not produce proper outout but produces the same output > as run on > # windows. > > #_*_ coding: utf-8 _*_ > > print "u'Libert\u00e9'" ?printed to screen > > y = raw_input('Enter >') > > # y = u'Lbert\u00e9' commented out > > y.encode('utf-8') > q = y.encode('utf-8') > q.decode('utf-8') > print q.decode('utf-8') > > # output is ?on the lines ?below was produced on the screen after run > > enter u'Libert\u00e9' on screen to copy into into y string > Enter >u'Libert\u00e9' > u'Libert\u00e9' > > The code DID NOT produce Libert? but instead produce u'Libert\u00e9' raw_input returns what you entered. You entered u'Libert\u00e9' so that's what was printed out. If you want to be able to enter escape sequences like \u00e9 and have them decoded to the appropriate character then you must do something like this: # The code text = raw_input('Enter >') decoded_text = text.decode("unicode-escape") print decoded_text # The output Enter >Libert\u00e9 Libert? HTH From deets at nospam.web.de Thu Jul 24 14:41:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 Jul 2008 20:41:13 +0200 Subject: need help with introducing more traffic In-Reply-To: References: <632875.28836.qm@web51808.mail.re2.yahoo.com> Message-ID: <6es0m9F8mehmU1@mid.uni-berlin.de> Fredrik Lundh schrieb: > leo davis skrev: > >> I found this code snippet(reference http://www.goldb.org) and wish to >> do more with it than just send out a Http Get request.I would like to >> introduce more traffic -say by downloading files,crawling through all >> the links,logging in etc etc,and wish to see how the web server >> reacts.I'm trying to stress the server to its limits....appreciate if >> anyone could provide me code/ideas to inject into this. >> the website -http://ftp.ruby-lang.org/pub/ruby/binaries/mswin32/ >> selected as example has many downloads.i tried from urllib import > > umm. are you saying that you run ruby-lang.org and want to write a > stress tester in Python just for the fun of it, or are we missing > something here... This: http://www.pylot.org/ Seems as if he *is* using various languages for fun... Diez From mrkafk at gmail.com Sun Jul 13 12:40:18 2008 From: mrkafk at gmail.com (mk) Date: Sun, 13 Jul 2008 18:40:18 +0200 Subject: Magic? Message-ID: So I was playing around with properties and wrote this: class lstr(str): def __init__(self, initval): self._s = initval self._len = len(self._s) def fget_s(self): return str(self._s) def fset_s(self, val): self._s = val self._len = len(self._s) s = property(fget_s, fset_s) def fget_len(self): return self._len def fset_len(self, val): raise AttributeError, "Attribute is read-only." len = property(fget_len, fset_len) I obviously aimed at defining setters and getters for 's' and 'len' attributes via using properties to that. However, it appears that somehow this object prints the value of 's' attribute without me setting any specific methods to do that: >>> astr = lstr('abcdef') >>> astr 'abcdef' >>> astr.swapcase() 'ABCDEF' How does it know to do that? I mean, I can understand how it knows to do that since I used property: >>> astr.s 'abcdef' >>> vars(astr) {'_len': 6, '_s': 'abcdef'} How does the instance know to use _s value to return when the instance is called? Is this due to some trick handling of overriden __init__ method (i.e. it knows to treat initval argument somehow specially)? Some other way? If so, how? From dorjetarap at googlemail.com Fri Jul 11 18:22:32 2008 From: dorjetarap at googlemail.com (kdt) Date: Fri, 11 Jul 2008 15:22:32 -0700 (PDT) Subject: palindrome function Message-ID: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Hi all, Can someone please explain to me why the following evaluates as false? >>>list=['a','n','n','a'] >>>list==list.reverse() >>>False I'm stumped :s From ptmcg at austin.rr.com Tue Jul 1 04:04:50 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 1 Jul 2008 01:04:50 -0700 (PDT) Subject: How make regex that means "contains regex#1 but NOT regex#2" ?? References: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> Message-ID: On Jul 1, 2:34?am, "A.T.Hofkamp" wrote: > On 2008-07-01, seber... at spawar.navy.mil wrote: > > > I'm looking over the docs for the re module and can't find how to > > "NOT" an entire regex. > > (?! R) > > > How make regex that means "contains regex#1 but NOT regex#2" ? > > (\1|(?!\2)) > > should do what you want. > > Albert I think the OP wants both A AND not B, not A OR not B. If the OP want to do re.match(A and not B), then I think this can be done as ((?! \2)\1), but if he really wants CONTAINS A and not B, then I think this requires 2 calls to re.search. See test code below: import re def test(restr,instr): print "%s match %s? %s" % (restr,instr,bool(re.match(restr,instr))) a = "AAA" b = "BBB" aAndNotB = "(%s|(?!%s))" % (a,b) test(aAndNotB,"AAA") test(aAndNotB,"BBB") test(aAndNotB,"AAABBB") test(aAndNotB,"zAAA") test(aAndNotB,"CCC") aAndNotB = "((?!%s)%s)" % (b,a) test(aAndNotB,"AAA") test(aAndNotB,"BBB") test(aAndNotB,"AAABBB") test(aAndNotB,"zAAA") test(aAndNotB,"CCC") def test2(arestr,brestr,instr): print "%s contains %s but NOT %s? %s" % \ (instr,arestr,brestr, bool(re.search(arestr,instr) and not re.search(brestr,instr))) test2(a,b,"AAA") test2(a,b,"BBB") test2(a,b,"AAABBB") test2(a,b,"zAAA") test2(a,b,"CCC") Prints: (AAA|(?!BBB)) match AAA? True (AAA|(?!BBB)) match BBB? False (AAA|(?!BBB)) match AAABBB? True (AAA|(?!BBB)) match zAAA? True (AAA|(?!BBB)) match CCC? True ((?!BBB)AAA) match AAA? True ((?!BBB)AAA) match BBB? False ((?!BBB)AAA) match AAABBB? True ((?!BBB)AAA) match zAAA? False ((?!BBB)AAA) match CCC? False AAA contains AAA but NOT BBB? True BBB contains AAA but NOT BBB? False AAABBB contains AAA but NOT BBB? False zAAA contains AAA but NOT BBB? True CCC contains AAA but NOT BBB? False As we've all seen before, posters are not always the most precise when describing whether they want match vs. search. Given that the OP used the word "contains", I read that to mean "search". I'm not an RE pro by any means, but I think the behavior that the OP wants is given in the last 4 tests, and I don't know how to do that in a single RE. -- Paul From Samnsparky at gmail.com Thu Jul 10 12:16:15 2008 From: Samnsparky at gmail.com (Sparky) Date: Thu, 10 Jul 2008 09:16:15 -0700 (PDT) Subject: Local User Control References: Message-ID: On Jul 10, 10:13?am, Tim Golden wrote: > Sparky wrote: > > On Jul 10, 9:58 am, Tim Golden wrote: > >> Sparky wrote: > >>> I don't know how feasible this is, but is it possible to have users > >>> log in to access a local database file in such a way that allows the > >>> program to know what user name and password they logged in with? This > >>> would involve separate user names and passwords for each user. > >> Well, this is a question which is crying out for some > >> context. Are you talking about an existing database > >> on an existing platform? If so, which one? Are you > >> talking about a database youo're thinking of building? > >> If so, the answer's probably yes but only you can > >> know. Are you talking about something else altogether? > > >> TJG > > > Thanks for the timely response. This would be a database that I am > > building myself. The question comes down to is there a feasible way to > > verify a user's user name and password from inside that database. > > Obviously the file would be encrypted, but if there is going to be > > more than one user using it I suppose there would be a separate file > > for a log-in. I am just asking for some guidance on how this would > > theoretically be implemented. > > Maybe someone else on the list has a clearer idea than I do, > but at this distance from an implementation, all I can say is: > yes, I'm sure you can achieve some kind of user authentication. > After all, lots of other products already do. Or is your proposed > db very different? > > TJG Thanks. I suppose I probably should get further down the road and come back with a more specific question. Thanks again, Sam From robert.kern at gmail.com Tue Jul 1 16:14:46 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 01 Jul 2008 15:14:46 -0500 Subject: ImportError: No module named _md5 In-Reply-To: References: Message-ID: neridaj at gmail.com wrote: > Hello, > > Does anyone know how to fix this error when trying to build MySQL- > python-1.2.2: > > python setup.py build > Traceback (most recent call last): > File "setup.py", line 5, in > import ez_setup; ez_setup.use_setuptools() > File "/Users/jasonnerida/Downloads/MySQL-python-1.2.2/ez_setup.py", > line 83, in use_setuptools > egg = download_setuptools(version, download_base, to_dir, > download_delay) > File "/Users/jasonnerida/Downloads/MySQL-python-1.2.2/ez_setup.py", > line 111, in download_setuptools > import urllib2, shutil > File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/ > lib/python2.5/urllib2.py", line 91, in > import hashlib > File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/ > lib/python2.5/hashlib.py", line 133, in > md5 = __get_builtin_constructor('md5') > File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/ > lib/python2.5/hashlib.py", line 60, in __get_builtin_constructor > import _md5 > ImportError: No module named _md5 > > I then tried installing py25-hashlib via macports, which never > completes: > > sudo port install py25-hashlib > Password: > Waiting for lock on /opt/local/var/macports/build/ > _opt_local_var_macports_sources_rsync.macports.org_release_ports_python_py25- > hashlib/work/.macports.py25-hashlib.state > > Do I need to completely reinstall python? I'm using 2.5.2 which > shipped with Leopard. Delete the directory /opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_python_py25-hashlib/ and try building py25-hashlib again. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From fuzzyman at gmail.com Mon Jul 28 18:52:48 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 28 Jul 2008 15:52:48 -0700 (PDT) Subject: ANN: PyCon UK Talks and Tutorials List Up Message-ID: PyCon UK 2008 is the second PyCon event in the UK, and is being held on 12th to 14th September at the Birmingham Conservatoire. We have a bevy of national and international Python stars speaking as well as a host of members of the Python community. The conference starts with a day of tutorials on the Friday. The timetable for the tutorials day has now been published: http://www.pyconuk.org/timetable.html We have abstracts of currently accepted talks, tutorials and BOFs: http://www.pyconuk.org/talk_abstracts.html The early bird rate is still open (but not for too much longer): http://www.pyconuk.org/booking.html We are almost there with the schedule, the plenary sessions will include Lightning talks as well as keynotes from Mark Shuttleworth and Ted Leung. We may be accepting a couple more talks if we can squeeze them in somewhere. (If you are expecting to give a talk but have not given us an abstract, then please give it to us ASAP) Michael Foord and the other PyCon UK Organisers From sjmachin at lexicon.net Sat Jul 19 17:55:23 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 19 Jul 2008 14:55:23 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> <6ebshqF67cpfU4@mid.uni-berlin.de> <5d6b8066-c941-4f0c-abea-20baed33b4ab@l64g2000hse.googlegroups.com> Message-ID: <569da8b8-df8a-4115-a952-5d8c2d9744e0@i20g2000prf.googlegroups.com> On Jul 20, 6:13 am, nicolas.pource... at gmail.com wrote: > On 18 juil, 17:52, Marc 'BlackJack' Rintsch wrote: > > > On Fri, 18 Jul 2008 07:39:38 -0700, nicolas.pourcelot wrote: > > > So, I use something like this in 'sheet.objects.__setattr__(self, > > > name, value)': > > > if type(value) == Polygon: > > > for edge in value.edges: > > > if edge is_in sheet.objects.__dict__.itervalues(): > > > object.__setattr__(self, self.__new_name(), edge) > > > > Ok, I suppose it's confused, but it's difficult to sum up. ;-) > > > You are setting attributes with computed names? How do you access them? > > Always with `gettattr()` or via the `__dict__`? If the answer is yes, why > > don't you put the objects the into a dictionary instead of the extra > > redirection of an objects `__dict__`? > > Yes, I may subclass dict, and change its __getitem__ and __setitem__ > methods, instead of changing objets __setattr__ and __getattr__... But > I prefer > > >>> sheet.objects.A = Point(0, 0) > than > >>> sheet.objects["A"] = Point(0, 0) > > Oh and the `type()` test smells like you are implementing polymorphism > > in a way that should be replaced by OOP techniques. > > I wrote 'type' here by mistake, but I used 'isinstance' in my > code. ;-) > > > If you make Point immutable you might be able to drop the "must not be > > referenced twice" requirement. > > Yes, but unfortunately I can't (or it would require complete > redesign...) (1) You are searching through lists to find float objects by identity, not by value (2) Peter says he doesn't understand (3) Marc thinks it smells IOW, the indications are that it *already* requires complete redesign. From theller at python.net Mon Jul 28 10:03:15 2008 From: theller at python.net (Thomas Heller) Date: Mon, 28 Jul 2008 16:03:15 +0200 Subject: ctypes and how to copy data passed to callback In-Reply-To: <2059b8a4-7651-4c3c-afbf-44caa8605c64@m3g2000hsc.googlegroups.com> References: <2059b8a4-7651-4c3c-afbf-44caa8605c64@m3g2000hsc.googlegroups.com> Message-ID: <6f61s7Fa0pq9U1@mid.individual.net> waldek schrieb: > Hi, > > I'm trying to handle data passed to Py Callback which is called from > C dll. Callback passes data to another thread using Queue module and > there the data are printed out. > > If data is printed out in a callback itself it's ok. If I put on > queue and next get from queue in another thread script prints some > trash. Looks like the data is released when callback returned. I tired > to make d = copy.deepcopy(data), but it does not work - I got nothing. > Any idea why it's happening ? > > --------------------- main thread -------- > def callback(data, size): > myqueue.put((data, size)) > > mydll = cdll.MyDLL > cbproto = CFUNCTYPE(c_int, POINTER(c_char), c_int) > mycallback = cbproto(callback) > > mydll.RegisterCallback(mycallback) > > ---------------------------------- thread listener > ---------------------- > > while True: > data, size = myqueue.get() > print "***", data[:size] > > ------------------------------------------------------------------------------ I guess your code would work if you change it in this way: > def callback(data, size): > myqueue.put(data[:size]) > while True: > data = myqueue.get() > print "***", data Thomas From cokofreedom at gmail.com Tue Jul 22 03:03:14 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 22 Jul 2008 00:03:14 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <9803eab7-3b01-4a9e-8672-43d153c1617e@w7g2000hsa.googlegroups.com> On Jul 22, 5:59 am, Larry Bates wrote: > Grant Edwards wrote: > > On 2008-07-22, Larry Bates wrote: > > >> You talk about "writing it in assembly language for each MPU > >> chip". Actually it is even better than that. We now have > >> these modern inventions, called compilers that do that type of > >> work for us. They translate high level instructions, not > >> into assembler but into machine language. > > > Actually, all of the compilers I'm familiar with (gcc and a > > handful of cross compilers for various microprocessors) > > translate from high-level languages (e.g. C, C++) into > > assembly, which is then assembled into relocatable object > > files, which are then linked/loaded to produce machine > > language. > > I just learned something I did not know. I was under the impression that they > translated directly to machine code without ever actually generating Assembler > text files. Seems like a waste to generate the text and turn around run that > through the assembler, but what do I know. I guess that way the compiler can > have pluggable assembler back-ends. > > -Larry I also I have just learned something new! Troll threads are useful. Yay. From fetchinson at googlemail.com Sat Jul 12 12:49:25 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 12 Jul 2008 09:49:25 -0700 Subject: How to create a timer/scheduler in Python? In-Reply-To: <0stg74t0eksmnfsslukn5m7f9s4rbub8kt@4ax.com> References: <0stg74t0eksmnfsslukn5m7f9s4rbub8kt@4ax.com> Message-ID: > I need what I'd call (in .Net) a timer, ie I need to run a function eg > every 2 seconds - it doesn't need to be millisec accurate but it would > be nice if it wasn't eg every 4 seconds or something. > > Rather surprisingly, Core Python (Chun) doesn't seem to index 'timer' > or 'scheduler', which leaves me wondering whether this is an aspect of > Python that isn't perhaps widely used? > > Looking around on the net I can see references to a thread timer, but > I'm not really looking to start any new threads (I just want part of > the GUI to update every 2 secs) and don't want to get into that sort > of complication while still just learning Python. > > Is there really no simple timer/scheduler function available in > Python? You might want to look at scheduler.py from turbogears which is exactly the tool you describe and luckily is 99.99% independent of turbogears. I'd think you need to modify 1-2 lines: http://svn.turbogears.org/tags/1.0.4.4/turbogears/scheduler.py Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From bearophileHUGS at lycos.com Thu Jul 31 15:59:02 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 31 Jul 2008 12:59:02 -0700 (PDT) Subject: simple problem with lists I am just forgetting References: Message-ID: <31fc98d7-ea8f-47b2-91f5-04a8f68313da@k37g2000hsf.googlegroups.com> Alexnb: > How can I test if the list item is empty without getting that exception? In Python such list cell isn't empty, it's absent. So you can use len(somelist) to see how much long the list is before accessing its items. Often you can iterate on the list with a for, so you don't need to care of the len(). Bye, bearophile From __peter__ at web.de Fri Jul 11 04:14:28 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jul 2008 10:14:28 +0200 Subject: ActiveState Code: the new Python Cookbook site References: <4873F326.5010905@activestate.com> <4874698E.7000805@gmail.com> <4877053f$0$16181$5402220f@news.sunrise.ch> Message-ID: Thin Myrna wrote: > The old cookbook offered choices by category. Did you drop that feature? Looks like categories have become tags: http://code.activestate.com/recipes/tags/ Peter From elessar at nienna.org Wed Jul 30 11:23:05 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Wed, 30 Jul 2008 09:23:05 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> Message-ID: <48908759.60202@nienna.org> Russ P. wrote: > On Jul 30, 12:03 am, Heiko Wundram wrote: >> Am Mittwoch, 30. Juli 2008 08:30:48 schrieb Russ P.: >> >>> On Jul 29, 11:09 pm, Erik Max Francis wrote: >>>> I'm getting this sneaking suspicion that you guys are all putting us on. >>> As I said in an earlier post, I realize that this would only work if >>> there were only one copy of "empty" (as there is only one copy of >>> "None"). I don't know off hand if that is feasible or not. >>> You reply reeks of the kind of pedantic snobbishness that makes me >>> sick. >> I can understand (and pretty much sympathise) that you get this kind of reply, >> simply because the point you and Carl Banks (formulated somewhat differently) >> put up has been answered again and again (in this thread), and I can only >> repeat it once more: >> >> __nonzero__(), i.e. the "cast" to boolean, is THE WAY to test whether a >> container is empty or not. Like this design decision, or don't like it, but >> the discussion is not going to go anywhere unless you concede that there is a >> (very explicit!) way to test for non-emptiness of a container already, and >> you're currently simply discussing about adding/using syntactic sugar >> (different means of expressing the test) to suit your own personal taste >> better. Anyway, check the documentation for __nonzero__(): if the object >> doesn't implement that, but implements __len__(), the interpreter "replaces" >> the __nonzero__() test by __len__()>0, so I guess someone in the design >> department must've seen it logical for the truth value of a container to >> express the test "len(x)>0" at some point in time to make this interpretation >> for the truth value of a container. >> >> There cannot be an argument about missing/misplaced functionality (that's what >> you make it sound like), if the functionality for doing what you want to do >> is there and you simply don't like the syntax, which I can somewhat relate to >> because style is a personal thing, even though I don't see either points made >> by you or Carl Banks, because implicit casting to bool is so common in pretty >> much every programming language to test for "truth" of an object, and IMHO >> it's completely logical to extend that idea to containers to mean >> empty/non-empty. >> >> Eric Max Francis tried to explain why your syntactic "enhancement" would come >> at a much greater price than its worth, and he's absolutely right in that, as >> it's an abuse of the "is" operator, but again, that's a somewhat different >> point. It changes nothing about the fact that all this discussion centers >> around something that is a non-point, but simply a matter of personal taste. >> >> -- >> Heiko Wundram > > Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > __nonzero__ work in Python. It's very basic stuff. You can quit > patronizing me (and Carl too, I'm sure). > > The point that you seem to be missing, or refuse to acknowledge for > some reason, is that "if x" can be mistakenly applied to any object > when the programmer thinks that x is a list -- and the programmer will > receive no feedback on the error. > > I have made errors like that, and I could have saved some time had I > used an "empty" method that only applies to a list or other sequence. > > Is that an important issue? I don't know. I'm not claiming it is. But > you cannot just sweep it away as nothing. > -- > http://mail.python.org/mailman/listinfo/python-list > See, I can agree with this. If you're expecting a list (and only a list) then your point makes sense. 'if x' can get you into trouble if you _don't_ want its polymorphism. Although, if my function is expecting a list, my preference is to do: if not isinstance(x, list): raise SomeMeaningfulException() # do stuff with the list I put my type checking at the top of the function, so readers can reference it easily. However, Carl's point is that 'if x' is never preferable to the more verbose and slower "simple test". I do not agree with this. -Matt From mingtian_good at sina.com Thu Jul 10 22:17:22 2008 From: mingtian_good at sina.com (128) Date: Thu, 10 Jul 2008 19:17:22 -0700 (PDT) Subject: paypal wholesale men jordans 17 (paypal accept)(www super-saler com Message-ID: <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans 18 (paypal accept)(www super-saler com paypal wholesale men jordans 19 (paypal accept)(www super-saler com paypal wholesale men jordans 20 (paypal accept)(www super-saler com paypal wholesale men jordans 21 (paypal accept)(www super-saler com paypal wholesale men jordans 22 (paypal accept)(www super-saler com paypal wholesale men jordans 23 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans 18 (paypal accept)(www super-saler com paypal wholesale men jordans 19 (paypal accept)(www super-saler com paypal wholesale men jordans 20 (paypal accept)(www super-saler com paypal wholesale men jordans 21 (paypal accept)(www super-saler com paypal wholesale men jordans 22 (paypal accept)(www super-saler com paypal wholesale men jordans 23 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans 18 (paypal accept)(www super-saler com paypal wholesale men jordans 19 (paypal accept)(www super-saler com paypal wholesale men jordans 20 (paypal accept)(www super-saler com paypal wholesale men jordans 21 (paypal accept)(www super-saler com paypal wholesale men jordans 22 (paypal accept)(www super-saler com paypal wholesale men jordans 23 (paypal accept)(www super-saler com From Ross at nomail.spam.thanks Fri Jul 4 15:37:31 2008 From: Ross at nomail.spam.thanks (RossGK) Date: Fri, 04 Jul 2008 15:37:31 -0400 Subject: pydev and psycopg2 - weird behaviour Message-ID: <486e7bfc@news.alcatel.com> I've been using pydev for a short while successfully, and Django with postgresql as well. psycopg2 is part of that behind the scenes I would imagine, to make django work. Now I'm trying to use psycopg2 in a non-Django program, I'm seeing some weird behaviour My "import psycopg2" is tagged in pyDev (eclipse) as "Unresolved Import: psycopg2" But when I run my code anyway, I seem to connect to the postgresql DB okay. If I remove the import, and try it, it fails. So it seems to use it, but thinks it's unresolved. Any idea what's going on there? Just to be sure it's installed right, I reinstalled with no change. I also opened a python shell (cmd window in winXP environment) and on the command line issued a psycopg2 connect request which succeeds as well. So it mostly seems to be an erroneous report from pydev that it can't resolve psycopg2 when it apparently can? Your input appreciated... Ross. From bourdenas at gmail.com Tue Jul 29 07:45:02 2008 From: bourdenas at gmail.com (Themis Bourdenas) Date: Tue, 29 Jul 2008 12:45:02 +0100 Subject: method decorators and more on decorators In-Reply-To: References: <7fd737460807271126m3dbdea8cv4dbd8c9058d4faea@mail.gmail.com> Message-ID: <7fd737460807290445p3b0a017dw54566fefd46edf0b@mail.gmail.com> On Mon, Jul 28, 2008 at 11:12 AM, Gabriel Genellina wrote: > En Sun, 27 Jul 2008 15:26:39 -0300, Themistoklis Bourdenas < > tbourden at doc.ic.ac.uk> escribi?: > > > On a related note, as the actual instance method of myclass is not foo > but > > decorate(foo), why are they called method decorators? This does not > decorate > > methods, they decorate functions and eventually the decorated functions > > become methods. The name method decorator sounds a bit misleading to me. > > Where have you found it? I've always seen the expression "function > decorator" or just "decorator", not "method decorator". > well a few occurrences of it can be found in PEP 318 > > > So returning to my original question is there any way I can get the class > > inside decorate()? I guess there is not, but just asking to make sure. > > "the class inside decorate"? What do you mean? The type of the x instance > in an x.foo() call? That should be determined inside the wrapped function > -when it is actually called-. > > Yes, what I was hoping is that it might be possible to get the name of the class the function is eventually is going to be bound to, but I guess that's not very likely to be possible. I wanted the name well before the function is called, actually even before an instance of the class is created. Anyway, I 've solved my problem with other means. Just out curiosity though, has there been any talk about actual method decorators? I guess you can work around them with the introduction of class decorators or even now with meta-classes, but you have to wrap methods manually with no syntactic sugar. Cheers, Themis -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Wed Jul 2 03:32:58 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Jul 2008 07:32:58 GMT Subject: n00bie wants advice. References: <8757c630-0518-4351-a319-124ced0ac92c@w4g2000prd.googlegroups.com> Message-ID: <6d0p98F6he9U1@mid.uni-berlin.de> On Tue, 01 Jul 2008 23:25:53 -0700, bsagert wrote: > This simple script writes html color codes that can be viewed in a > browser. I used short form hex codes (fff or 000, etc) and my list > has only six hex numbers otherwise the results get rather large. I > invite criticism as to whether my code is "pythonic". You should not rebind the name `list` because it shadows the built in type of that name then. A more descriptive name would be nice anyway, i.e. `hex_digits`. And strings are iterable too, so it's a bit shorter and easier to type the digits a string. Repeatedly concatenating strings with ``+=`` might be performance problem. Python strings are immutable so this operation has to copy the involved and growing strings over and over again. Although the current CPython implementation can optimize here in some cases, the usual idiom is to use the `join()` method of strings to build a string from components in a list or iterable. Alternative implementation of your script: from __future__ import with_statement def main(): html_template = ('\n' '%s\n' '\n') header_template = '

%s

' hex_digits = '369bdf' colors = (a + b + c for a in hex_digits for b in hex_digits for c in hex_digits) html = html_template % '\n'.join(header_template % (c, c) for c in colors) with open('test.html', 'w') as html_file: html_file.write(html) if __name__ == '__main__': main() From kib2 at free.fr Sun Jul 20 09:34:12 2008 From: kib2 at free.fr (kib2) Date: Sun, 20 Jul 2008 15:34:12 +0200 Subject: Genetic programming: pygene, pygp, AST, or (gasp) Lisp? In-Reply-To: References: <7bfb3c41-b08b-49dc-9711-6e39a4667db2@b1g2000hsg.googlegroups.com> Message-ID: <48833f5b$0$20551$426a34cc@news.free.fr> David Boddie a ?crit : > On Sunday 20 July 2008 09:52, John Ladasky wrote: > >> Is there a way to interface Lisp to Python, so that I can do all the >> interface programming in the language I already know best -- and just >> do the genetic parts in Lisp? I haven't seen exception handling in >> Lisp, a feature I've come to love in Python. Since it is fairly easy >> for a randomly-generated program to generate illegal output (I already >> know this from my initial experiments in Python), I don't think I can >> live without exception handling. > > Just searching the Web for Python and Lisp yielded some interesting > projects: > > http://www.biostat.wisc.edu/~annis/creations/PyLisp/ > http://www.livelogix.net/logix/ > > I've no idea if they're really that relevant to your problem, but they > might lead somewhere useful. > > David CLPython seems also a good alternative : http://common-lisp.net/project/clpython/ From animator333 at gmail.com Mon Jul 21 10:53:19 2008 From: animator333 at gmail.com (King) Date: Mon, 21 Jul 2008 07:53:19 -0700 (PDT) Subject: Safe guard .pyc files Message-ID: After google a lot I didn't find any way to safe guard .pyc files from decompilation. One way I can think of is to wrap important functions/classes as a libraby using SWIG/PyRex, but again is going to be a lot more of work and doesn't sound good. any body out there has done something for this? From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 3 08:25:18 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 03 Jul 2008 14:25:18 +0200 Subject: Trouble using pinckle In-Reply-To: <1ijia9i.j7cls41raaazgN%pdorange@pas-de-pub-merci.mac.com> References: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> <1ijgp2r.1j1k5xwwbtiwcN%pdorange@pas-de-pub-merci.mac.com> <486ba8a4$0$11957$426a74cc@news.free.fr> <1ijia9i.j7cls41raaazgN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <486cc523$0$12000$426a74cc@news.free.fr> Pierre-Alain Dorange a ?crit : > Bruno Desthuilliers wrote: > >>> I try the staticmethod, it works fine. Very helpful. >>> >>> But i don't like it very much, it seems 'complicated' (python was >>> supposed to be simple). >> Try doing the same thing in C++ !-) > > OK ;-) > > I just ask myself what was the best method (according to python > phylosophy). I'd personnaly use either one of the existing config packages, or something like json or yaml. From enleverlesX.XmcX at XmclaveauX.com Wed Jul 2 17:14:25 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Wed, 2 Jul 2008 23:14:25 +0200 Subject: Scripting SAP GUI (Windows) In-Reply-To: References: <6d15tpFaec4U1@mid.individual.net> Message-ID: <486bf048$0$843$ba4acef3@news.orange.fr> Hi! > Linux is much better place You confuse proselitism and objectivity... @-salutations -- Michel Claveau From googler.1.webmaster at spamgourmet.com Tue Jul 22 06:51:36 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Tue, 22 Jul 2008 03:51:36 -0700 (PDT) Subject: Python Embedding Thread References: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> <87bf413d-eb98-47c0-8466-237c45fd1a0e@e53g2000hsa.googlegroups.com> <5081c3df-cb66-443b-ac71-be9661ae057d@27g2000hsf.googlegroups.com> Message-ID: Hi! I fixed the code. This code snippet runs in a seperate thread: PyObject *dict=NULL; PyGILState_STATE state = PyGILState_Ensure(); dict = CreateMyGlobalDictionary(); PyRun_String(, Py_file_input, dict, dict); ReleaseGlobalDictionary(dict); But it still does not work... :-/ From cjw at ncf.ca Fri Jul 25 18:37:54 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 25 Jul 2008 18:37:54 -0400 Subject: An Attempt to download and install traits - to a Windows XP Message-ID: Using >easy_install -v -f http://code.enthought.com/enstaller/eggs/source enthought.traits The result is: ... many lines ... copying enthought\traits\ui\tests\shell_editor_test.py -> build\lib.win32-2.5\enthought\traits\ui\tests copying enthought\traits\ui\tests\table_editor_color_test.py -> build\lib.win32-2.5\enthought\traits\ui\tests copying enthought\traits\ui\tests\table_editor_focus_bug.py -> build\lib.win32-2.5\enthought\traits\ui\tests copying enthought\traits\ui\tests\table_editor_test.py -> build\lib.win32-2.5\enthought\traits\ui\tests copying enthought\traits\ui\tests\table_editor_test2.py -> build\lib.win32-2.5\enthought\traits\ui\tests copying enthought\traits\ui\tests\table_list_editor_test.py -> build\lib.win32-2.5\enthought\traits\ui\tests copying enthought\traits\ui\tests\tree_editor_test.py -> build\lib.win32-2.5\enthought\traits\ui\tests running build_ext error: Setup script exited with error: Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. Visual Studio 2003 was not found on this system. If you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py. C:\Documents and Settings\cjw\Desktop>python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> I would welcome any guidance. Colin W. From bdesth.quelquechose at free.quelquepart.fr Mon Jul 28 07:23:56 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Jul 2008 13:23:56 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> Message-ID: <488dc843$0$15497$426a74cc@news.free.fr> Russ P. a ?crit : > On Jul 27, 3:11 pm, "Russ P." wrote: >> On Jul 27, 12:39 pm, Bruno Desthuilliers >> >> >> >> wrote: >>> Derek Martin a ?crit : >>>> On Sun, Jul 27, 2008 at 08:19:17AM +0000, Steven D'Aprano wrote: >>>>>> You take the name down to a single letter. As I suggested in an earlier >>>>>> post on this thread, why not take it down to zero letters? >>>>> The question isn't "why not", but "why". The status quo works well as it >>>>> is, even if it isn't perfect. Prove that implicit self is a good idea -- >>>>> or at least prove that it is an idea worth considering. >>>> Come on, this sounds like a schoolyard argument. This comes down to a >>>> matter of style, and as such, is impossible to prove. It's largely a >>>> question of individual preference. >>>> That said, the argument in favor is rather simple: >>>> 1. This is an extremely common idiom in Python >>>> 2. It is completely unnecessary, and the language does not suffer for >>>> making it implicit >>>> 3. Making it implicit reduces typing, reduces opportunities for >>>> mistakes, and arguably increases consistency. >>> "arguably", indeed, cf below. >>>> As for the latter part of #3, self (or some other variable) is >>>> required in the parameter list of object methods, >>> It's actually the parameter list of the *function* that is used as the >>> implementation of a method. Not quite the same thing. And then, >>> consistency mandates that the target object of the method is part of the >>> parameter list of the *function*, since that's how you make objects >>> availables to a function. >>>> however when the >>>> method is *called*, it is omitted. >>> Certainly not. You need to lookup the corresponding attribute *on a >>> given object* to get the method. Whether you write >>> some_object.some_method() >>> or >>> some_function(some_object) >>> you still need to explicitely mention some_object. >>>> It is implied, supplied by Python. >>> Neither. The target object is passed to the function by the method >>> object, which is itself returned by the __get__ method of function >>> objects, which is one possible application of the more general >>> descriptor protocol (the same protocol that is used for computed >>> attributes). IOW, there's nothing specific to 'methods' here, just the >>> use of two general features (functions and the descriptor protocol). >>> FWIW, you can write your own callable, and write it so it behave just >>> like a function here: >>> import types >>> class MyCallable(object): >>> def __call__(self, obj): >>> print "calling %s with %s" % (self, obj) >>> def __get__(self, instance, cls): >>> return types.MethodType(self.__call__, instance, cls) >>> class Foo(object): >>> bar = MyCallable() >>> print Foo.bar >>> f = Foo() >>> f.bar() >>>> Thus when an object method is called, it must be called with one fewer >>>> arguments than those which are defined. This can be confusing, >>>> especially to new programmers. >>> This is confusing as long as you insist on saying that what you >>> "def"ined is a method - which is not the case. >>>> It can also be argued that it makes the code less ugly, though again, >>>> that's a matter of preference. >>>>> It's not enough to show that a change "isn't bad" -- you have to show >>>>> that it is actively good. >>>> But he did... he pointed out that *it saves work*, without actually >>>> being bad. Benefit, without drawback. Sounds good to me! >>>>> "Don't need to look at the method signature" is not an argument in favour >>>>> of implicit self. >>>> Yes, actually, it is. >>> It isn't, since there's no "method signature" to look at !-) >>>> If there is a well-defined feature of Python >>>> which provides access to the object within itself, >>> The point is that you don't get access to the object "within itself". >>> You get access to an object *within a function*. >>> The fact that a function is defined within a class statement doesn't >>> imply any "magic", it just creates a function object, bind it to a name, >>> and make that object an attribute of the class. You have the very same >>> result by defining the function outside the class statement and binding >>> it within the class statement, by defining the function outside the >>> class and binding it to the class outside the class statement, by >>> binding the name to a lambda within the class statement etc... >>>> then the >>>> opportunities for mistakes when someone decides to use something else >>>> are lessened. >>>>> You don't need to look at the method signature when you're using an >>>>> explicit self either. >>>> That isn't necessarily true. If you're using someone else's code, and >>>> they didn't use "self" -- or worse yet, if they chose this variable's >>>> name randomly throughout their classes -- then you may well need to >>>> look back to see what was used. >>>> It's bad programming, but the world is full of bad programmers, and we >>>> don't always have the choice not to use their code. Isn't one of >>>> Python's goals to minimize opportunities for bad programming? >>> Nope. That's Java's goal. Python's goals are to maximize opportunities >>> for good programming, which is quite different. >>>> Providing a keyword equivalent to self and removing the need to name >>>> it in object methods is one way to do that. >>> It's also a way to make Python more complicated than it needs to be. At >>> least with the current state, you define your functions the same way >>> regardless of how they are defined, and the implementation is >>> (relatively) easy to explain. Special-casing functions definition that >>> happens within a class statement would only introduce a special case. >>> Then you'd have to explain why you need to specify the target object in >>> the function's parameters when the function is defined outside the class >>> but not when it's defined within the class. >>> IOW : there's one arguably good reason to drop the target object from >>> functions used as methods implementation, which is to make Python looks >>> more like Java, and there's at least two good reason to keep it the way >>> it is, which are simplicity (no special case) and consistency (no >>> special case). >>> Anyway, the BDFL has the final word, and it looks like he's not going to >>> change anything here - but anyone is free to propose a PEP, isn't it ? >> The issue here has nothing to do with the inner workings of the Python >> interpreter. The issue is whether an arbitrary name such as "self" >> needs to be supplied by the programmer. >> >> Neither I nor the person to whom you replied to here (as far as I can >> tell) is suggesting that Python adopt the syntax of Java or C++, in >> which member data or functions can be accessed the same as local >> variables. Any suggestion otherwise is a red herring. >> >> All I am suggesting is that the programmer have the option of >> replacing "self.member" with simply ".member", since the word "self" >> is arbitrary and unnecessary. Otherwise, everything would work >> *EXACTLY* the same as it does now. This would be a shallow syntactical >> change with no effect on the inner workings of Python, but it could >> significantly unclutter code in many instances. >> >> The fact that you seem to think it would change the inner functioning >> of Python just shows that you don't understand the proposal. > > It just occurred to me that Python could allow the ".member" access > regardless of the name supplied in the argument list: > > class Whatever: > > def fun(self, cat): > > .cat = cat > self.cat += 1 > > This allows the programmer to use ".cat" and "self.cat" > interchangeably. If the programmer intends to use only the ".cat" > form, the first argument becomes arbitrary. Allowing him to use an > empty argument or "." would simply tell the reader of the code that > the ".cat" form will be used exclusively. > > When I write a function in which a data member Python has nothing like "data member" (nor "member function" etc). It has class attributes and instance attributes, period. *Python is not C++*. So please stop using C++ terms which have nothing to do with Python's object model. > will be used several > times, I usually do something like this: > > data = self.data > > so I can avoid the clutter of repeated use of "self.data". If I could > just use ".data", I could avoid most of the clutter without the extra > line of code renaming the data member. The main reason to alias an attribute is to avoid the overhead of attribute lookup. > A bonus is that it becomes > clearer at the point of usage that ".data" is member data rather than > a local variable. I totally disagree. The dot character is less obvious than the 'self.' sequence, so your proposition is bad at least wrt/ readability (it's IMHO bad for other reasons too but I won't continue beating that poor dead horse...) From alan.franzoni.blahblah at example.com.invalid Wed Jul 30 15:32:04 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Wed, 30 Jul 2008 19:32:04 GMT Subject: undo a dictionary References: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> <192b4786-85b2-43d3-bb7c-b5716068ff12@56g2000hsm.googlegroups.com> Message-ID: <5kcky4amfzdf.tw6k5ru36ohn.dlg@40tude.net> mmm was kind enough to say: > My desire is to take a set of data items in an alpha-numeric range and > oput them into a dictionary > > i.e., > x1=1 > x2=20 > x3=33 > > to yield the dictionary > > { 'x1':1, 'x2':20, 'x3':33 } > > without having to type in as above but instead invoke a function > > maybe with syntax of > > dd=make_dict('x1--x99') you'll need to pass the locals() or globals() manually. Can't be done (cleanly) otherwise. Check the following code: import re x1=1 x2=20 x3=30 q6=40 def make_dict(regex, nsmapping): output_dict = {} compiled_regex = re.compile(regex) for key, value in nsmapping.items(): if compiled_regex.match(key): output_dict[key] = value return output_dict d = make_dict("x[123]", locals()) print d -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From marcus at internetnowasp.net Sat Jul 12 22:43:29 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Sun, 13 Jul 2008 10:43:29 +0800 Subject: Why is there no GUI-tools like this for Windows? In-Reply-To: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> References: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> Message-ID: <48796BD1.9030406@internetnowasp.net> Hi, Coming from a windows world i could understand this. For GUI, there is nothing near the power of the Visual Studio, this is especially true since C#. So python for me is for anything except GUI. It becomes self rejecting notion to do GUI in python when you type in those stuff that could have been handled by an IDE, thus for linux project i just do the web interface + php and let python do all the other hard core work. But looking at the video, i think if they could do this for ruby, then the python community should be able to come out with a similar one. There is something called BOA i read somewhere but its having some kind of compatibility problem with newer versions of wxpyhon. (;-) i didnt really manage to see that video it took forever to load, but the comments gave enuf hints). Marcus. maestro wrote: > http://www.youtube.com/watch?v=PXpwC1o5AcI > > I have done some GUI-programming for windows with Python but the > Tkinter interface sucked and while it is the only one I tried I got > the impression they are all the same. > > It's amazing how retarded a lot of the stuff programmers do is. > Watcing that video, that is how it should be. > > I can just do the layout with my mouse and then there is a program > that writes the code for me. > GUI-programming is hard for no reason. One good program then forever > easy... > > Is there not something like this for Python/Windows? Is the Linux one > only for ruby or for any language? > > Oh well im switching to Linux anyway and mostly write webapps but > still... > -- > http://mail.python.org/mailman/listinfo/python-list > > From laredotornado at zipmail.com Wed Jul 30 13:43:11 2008 From: laredotornado at zipmail.com (laredotornado) Date: Wed, 30 Jul 2008 10:43:11 -0700 (PDT) Subject: Syntax error in my script References: Message-ID: <85a24d4f-aa04-416b-833b-44ca85c979a2@d1g2000hsg.googlegroups.com> On Jul 30, 11:26?am, Alan Franzoni wrote: > laredotornadowas kind enough to say: > > [cut] > > Indentation counts in Python. You're probably doing something wrong with > whitespace/tab/carriage return. > > -- > Alan Franzoni > - > Remove .xyz from my email in order to contact me. > - > GPG Key Fingerprint: > 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E That was it. Thanks, - From googler.1.webmaster at spamgourmet.com Mon Jul 21 12:35:53 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Mon, 21 Jul 2008 09:35:53 -0700 (PDT) Subject: Python Embedding Thread References: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> Message-ID: Does anyone has a tip? From mail at timgolden.me.uk Wed Jul 9 10:18:39 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 09 Jul 2008 15:18:39 +0100 Subject: Allow tab completion when inputing filepath? In-Reply-To: References: Message-ID: <4874C8BF.7060108@timgolden.me.uk> Keith Hughitt wrote: > I've been looking around on the web for a way to do this, but so far > have not come across anything for this particular application. I have > found some ways to enable tab completion for program-related commands, > but not for system filepaths. This would be nice to have when > prompting the user to enter a file/directory location. What platform are you on? And what kind of display? (Console / GUI / wxPython / Qt / Web...) TJG From nick at craig-wood.com Tue Jul 1 16:46:50 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 01 Jul 2008 15:46:50 -0500 Subject: Why is recursion so slow? References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Message-ID: Luis Zarrabeitia wrote: > > is that what lazy evaluation in functional languages avoids thus > > making recursive versions much faster? > > Not exactly... Functional languages are (or should be) optimized for recursion, > but if the algorithm you write is still exponential, it will still > take a long time. Actually I think functional language are likely to perform memoization. By definition any function in a functional language will always produce the same result if given the same arguments, so you can memoize any function. See here for a python memoize which makes the recursive algorithm run fast... http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201 -- Nick Craig-Wood -- http://www.craig-wood.com/nick From lepto.python at gmail.com Mon Jul 14 22:47:52 2008 From: lepto.python at gmail.com (oyster) Date: Tue, 15 Jul 2008 10:47:52 +0800 Subject: a module.pth question Message-ID: <6a4f17690807141947n1e052c6dj436702f70ac1fda0@mail.gmail.com> there are 2 reasons: 1. I use both py24 and py25, I don't like to install 2 copies of pyglet, which is a pure python module and can be used by py24/25 at the same time, thus I am not willing to put a module under site-packages, instead I use a separate directory(h:\pure_pylib in my case) 2. I also carry python on my U-disk, as you know the driver letter assigned to it is not always same. so I can't use full path name > ---------- ????? ---------- > From: Mike Driscoll > To: python-list at python.org > Date: Mon, 14 Jul 2008 06:12:25 -0700 (PDT) > Subject: Re: a module.pth question > On Jul 14, 6:26 am, oyster wrote: > > My py24 is installed in h:\python24 > > I installed pyglet(http://pyglet.org/) in > > H:\pure_pylib\Multimedia\pyglet-1.0\, if I do > > [code]>>> import sys > > >>> > sys.path.append(r'H:\pure_pylib\Multimedia\pyglet-1.0') > > >>> import pyglet > > > > [/code] > > it is ok. > > > > but if I created h:\pure_pylib\pyglet.pth file, which containts > > [code] > > Multimedia\pyglet-1.0 > > [/code] > > > > then > > [code]>>> import sys > > >>> sys.path.append(r'h:\pure_pylib') > > >>> import pyglet > > > > Traceback (most recent call last): > > File "", line 1, in ? > > ImportError: No module named pyglet > > > > [/code] > > > > what is wrong with it? and How to fix it? thanks in advance > > I looked in my easy_install.pth and it looks like it should be: > > .\Multimedia\pyglet-1.0 > > But I don't really see any reason not to do it the way you were > earlier with the full path name. Besides, you should be able to > install pyglet to your site-packages folder. Or you could use buildout > if you're just testing modules and you don't want to screw up your > namespace. > > Mike From wuwei23 at gmail.com Fri Jul 25 06:52:56 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 25 Jul 2008 03:52:56 -0700 (PDT) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> Message-ID: On Jul 25, 7:57?pm, Suresh Pillai wrote: > The nodes in my network may be ON or OFF. ?The network starts off with > all nodes in the OFF state. ?I loop through the nodes. ?For each node > that is OFF, I consider some probability of it turning ON based on the > states of its neighbours. ?I MUST GO THROUGH ALL NODES BEFORE DECIDING > WHICH ONES TO TURN ON. > > So my question is whether it is faster to > > 1. loop through a list of ALL nodes and check for OFF nodes using ifs I'd recommend using 'filter' and list comprehensions. >>> import random >>> class Node: ... def __init__(self): ... self.on = False ... def toggle(self): ... self.on = random.choice([True, False]) ... >>> nodes = [Node() for i in range(0, 10000)] >>> for node in nodes: ... node.toggle() ... >>> off_nodes = filter(lambda x: not x.on, nodes) >>> len(off_nodes) 5050 From yuwenwu001 at gmail.com Thu Jul 24 11:00:23 2008 From: yuwenwu001 at gmail.com (kjldf) Date: Thu, 24 Jul 2008 08:00:23 -0700 (PDT) Subject: adidas adicolor shoes PayPal Message-ID: <46e6ef6f-5b18-4e0c-8f0f-c9a2d4351630@p10g2000prf.googlegroups.com> adidas adicolor shoes PayPal We export our brand shoes all over world because of our competitive price, good quality products and good service. All our products are guaranteed to be a minimum of AAA+ quality. Our price and good service are often appreciated by our customers. So we can get repeat order to sustain our development. Your support of our business is very thankful. Dear friend welcome to shopping on www.electronic-paypal.cn 1.5% paypal handling charge supports the online payment! 2.Use your intergla replacement more good gift! 3.notes by email and website of deliver each package at first time. From maheha845 at gmail.com Wed Jul 2 11:11:15 2008 From: maheha845 at gmail.com (maheha845 at gmail.com) Date: Wed, 2 Jul 2008 08:11:15 -0700 (PDT) Subject: internatinal jobs in USA free submet your resume Message-ID: Success usually comes to those who are too busy to be looking for it Visit Mobiles & Computers?, http://www.mobilecomputers4all.blogspot.com/
Hi..Click me

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi..Click me

From ggpolo at gmail.com Wed Jul 2 09:15:14 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 2 Jul 2008 10:15:14 -0300 Subject: dynamically load from module import xxx In-Reply-To: References: Message-ID: On Tue, Jul 1, 2008 at 1:46 PM, Gary Duzan wrote: > In article , > Neal Becker wrote: >>What is a good way to emulate: >> >>from module import xxx >>where 'module' is a dynamically generated string? >> >>__import__ ('modulename', fromlist=['xxx']) >> >>seems to be what I want, but then it seems 'xxx' is not placed in globals() >>(which makes me wonder, what exactly did fromlist do?) > > You might want to read what "help(__import__)" tells you. It > sounds like what you want is: But have you read it yourself ? > > mynamespace['xxx'] = __import__('modulename.xxx', fromlist=['xxx']) Only if modulename is actually a package, which doesn't really make sense for a "modulename". Also, fromlist doesn't need to be ['xxx'] if you want to import the submodule 'xxx' from the, now supposed, 'modulename' package, it could be anything that is not an empty list. > > Seems a bit weird to me, but that's the way it is, and I'm sure > there is a reason for it. > > Good luck. > > Gary Duzan > Motorola H&NM > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From basti.wiesner at gmx.net Tue Jul 15 12:47:06 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Tue, 15 Jul 2008 18:47:06 +0200 Subject: fork after creating temporary file using NamedTemporaryFile References: <0435315d-7b7d-4587-bc8c-000e3f2644a2@z72g2000hsb.googlegroups.com> Message-ID: rparimi at gmail.com : > When I create temporary file using the tempfile module, and forkI) > later on in my program, I always see errors when the program exits. Is > this because the child process deletes temp file? > Here's a stripped down version of my script that exhibits this > problem: > > #!/usr/bin/python > > import os > import tempfile > import sys > > cmd = [] > cmd.append('/bin/ls') > cmd.append('-l') > cmd.append('/tmp') > > foo = tempfile.NamedTemporaryFile(mode='w+b') > > pid = os.fork() > if pid: > print 'I am parent' > else: > print 'I am child' > sys.exit(0) > > $ python sub.py > I am child > I am parent > Exception exceptions.OSError: (2, 'No such file or directory', '/tmp/ > tmp-mZTPq') in file '', mode 'w+b' at 0xb7d2a578>> ignored NamedTemporaryFile attempts to delete the file, when "close" is invoked (which is done by the destructor in this case, because you're senselessly not closing that file explicitly). A "fork()" clones the whole process memory, after fork() is done, there are *two* NamedTemporaryFile objects, pointing to the *same* file, existing in two separate process (one in the parent, the other, cloned one, in the child). When the first process exists, the file is removed cleanly, the second process can't remove anything anymore, since there's nothing left to remove. Since the order of process execution is not deterministic and completely up to the systems scheduler, you can *never* say, which one will exit first. You should replace NamedTempraryFile with "mkstemp" and take care of deletion yourself. You could for instance call "os.wait" to wait for the child's termination in the parent process and thus delete the temporary file, once the child has gone. Of course, you could also catch the exception, if you properly close the file object (what you should be doing anyway!), but I'd consider this a not very robust solution. If one of the two processes exit unexpectedly early, the directory entry is gone, though it might still be needed by the parent process. > How can these warnings be avoided? I tried to catch this exception > using try/except but it didn't work. If you want to catch that exception, you should properly close the named temporary file and wrap the "close" call inside a try-except statement. Beginning with Python 2.5 you might also want to use the with-statement here. Relying on the destructor is *always* a bad idea, you should always close files explicitly! -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From asma61 at dsl.pipex.com Sun Jul 27 12:18:22 2008 From: asma61 at dsl.pipex.com (DaveM) Date: Sun, 27 Jul 2008 17:18:22 +0100 Subject: Rant (was Re: x*x if x>10 References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3g8rF9gfj0U1@mid.uni-berlin.de> <6f3gmaF9moqsU1@mid.uni-berlin.de> Message-ID: <1q5p845o2j9htp6vf44u6nqinucsr1numf@4ax.com> On Sun, 27 Jul 2008 16:57:14 +0200, "Diez B. Roggisch" wrote: >Marc 'BlackJack' Rintsch schrieb: >> On Sun, 27 Jul 2008 16:41:19 +0200, Diez B. Roggisch wrote: >> >>> DaveM schrieb: >>>> Getting back to the list concatenation, I finally found the itertools.chain >>>> command which is the most compact and fastest (or second fastest by a >>>> trivial amount, I can't remember which). Along the way, I must have >>>> tried/used half a dozen methods, ...which brings me back my initial PERL >>>> comment. There's more than one way to do it in Python, too. >>> But I *do* know that taking the python zen literally is fruitless. >> I think it should be taken more literally than the wrong reduction to >> "there should be only one way". People tend to forget "obvious" and >> "preferably" all the time. >Good point. The OP found the obvious way of extending. I wonder what his >reasons were to abandon it. You'll have guessed, I'm sure, that I'm not a professional programmer. This was the third rewrite of a program to match candidate groups to examiners on a three day course I run, necessitated on this occasion by a change in the structure of the course. I originally learnt python as I wrote, and some of the early code was ugly and verbose, so once the current rewrite was working I took the opportunity to tidy the code up and document it (yes, I know, but as I said, I'm an amateur). The list concatenation was an itch I couldn't scratch: temp = [] for value in sessexam.values(): temp.extend(value) c_exam = [name for name in set(temp)] #See what I mean about verbose? c_exam.sort() return c_exam Six lines just didn't feel like it ought to be the best way to do something so simple. I liked the attempt below better, but was foolish enough to time it, so that was the end of that. return sorted(list(set(reduce(lambda x, y: x+y, sessexam.values())))) The current version (below) is a compromise, but I still feel there _ought_ to be a simple one word command to join multiple lists. a = list(set(itertools.chain(*sessexam.values()))) a.sort() #As I write I'm wondering if I really need it sorted. Hmm... return a DaveM From metaperl at gmail.com Tue Jul 15 21:12:33 2008 From: metaperl at gmail.com (E. J. Gold is the Hi-Tech Shaman) Date: Tue, 15 Jul 2008 18:12:33 -0700 (PDT) Subject: graphing lifelines References: Message-ID: On Jul 15, 3:38?pm, Larry Bates wrote: > > Certainly a "Hi-Tech Shaman" can whip something up to do this, right? > Yes, well E.J. Gold is the Hi-Tech Shaman. I'm Terrence Brannon, stating that fact :) So, maybe EJ could whip up such a thing :) I like the sci.math answer I got the best and will go with that approach - http://groups.google.com/group/sci.math/browse_thread/thread/09b254718d4cbfeb# From tjreedy at udel.edu Wed Jul 2 04:27:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 02 Jul 2008 04:27:15 -0400 Subject: Problem with a for loop and a list In-Reply-To: <18232298.post@talk.nabble.com> References: <18232298.post@talk.nabble.com> Message-ID: Alexnb wrote: > I am not sure what is going on here. Here is the code that is being run: > > def getWords(self): > self.n=0 > for entry in self.listBuffer: > self.wordList[self.n] = entry.get() And what does self.wordList begin as? If {}, then the assignemt is invalid. Perhaps you want self.wordList.append(entry.get()) > self.n=self.n+1 Is this supposed to be incremented once per entry or once per getWords()? If the former, you would overwrite previous assignment (if it worked) for every item except the last. From gagsl-py2 at yahoo.com.ar Wed Jul 30 00:06:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 01:06:08 -0300 Subject: method decorators and more on decorators References: <7fd737460807271126m3dbdea8cv4dbd8c9058d4faea@mail.gmail.com> <7fd737460807290445p3b0a017dw54566fefd46edf0b@mail.gmail.com> Message-ID: En Tue, 29 Jul 2008 08:45:02 -0300, Themis Bourdenas escribi?: > On Mon, Jul 28, 2008 at 11:12 AM, Gabriel Genellina > wrote: > >> En Sun, 27 Jul 2008 15:26:39 -0300, Themistoklis Bourdenas < >> tbourden at doc.ic.ac.uk> escribi?: >> >> > On a related note, as the actual instance method of myclass is not foo >> but >> > decorate(foo), why are they called method decorators? This does not >> decorate >> > methods, they decorate functions and eventually the decorated >> functions >> > become methods. The name method decorator sounds a bit misleading to >> me. >> >> Where have you found it? I've always seen the expression "function >> decorator" or just "decorator", not "method decorator". > > well a few occurrences of it can be found in PEP 318 In a very strict sense, I'd say that all those references to "method decorators" are wrong - because those "def" statements inside a "class" statement define functions, not methods. In that sense almost every Python programmer is wrong too: in this example class X: @decorator def foo(self): pass most (if not all) people would refer to "foo" as "the foo method in class X" - even if foo is really a function, not a method. So a less restrictive meaning is usually adopted - and we all consider "foo" a method, and we're all happy... except in your case, when you just hit a point where the distinction is relevant. Perhaps a more careful wording in the PEP would help in those corner cases. >> > So returning to my original question is there any way I can get the >> class >> > inside decorate()? I guess there is not, but just asking to make sure. >> >> "the class inside decorate"? What do you mean? The type of the x >> instance >> in an x.foo() call? That should be determined inside the wrapped >> function >> -when it is actually called-. >> >> Yes, what I was hoping is that it might be possible to get the name of >> the > class the function is eventually is going to be bound to, but I guess > that's > not very likely to be possible. I wanted the name well before the > function > is called, actually even before an instance of the class is created. No, I think it's not possible - not using a function decorator, because when it is applied, the class doesn't exist yet. You might use a metaclass (or a class decorator, available on 2.6 and 3.0); iterate over the dictionary of the class about to be created and process their functions in any way you like. > Anyway, > I 've solved my problem with other means. Just out curiosity though, has > there been any talk about actual method decorators? I guess you can work > around them with the introduction of class decorators or even now with > meta-classes, but you have to wrap methods manually with no syntactic > sugar. Mmm... methods are ephemeral objects, once the call is completed, the method usually gets destroyed, so I don't think a true "method decorator" would be very useful. If you really want to customize a method, since they are created by the function type's __get__, a crazy idea would be to inherit from the function type and return something different in its __get__ - but I've never done something like that and don't even know if it's possible at all... -- Gabriel Genellina From ppearson at nowhere.invalid Wed Jul 16 14:24:04 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 16 Jul 2008 18:24:04 GMT Subject: bad recursion, still works References: <20cba7ab-72d2-4c7b-8f3f-48f39eaf9625@m3g2000hsc.googlegroups.com> Message-ID: <6e6sm3F5mk28U1@mid.individual.net> On Wed, 16 Jul 2008 15:20:23 +0200, Fredrik Lundh wrote: [snip] > Hope this helps more than it confuses. Absolutely. It is wonderfully enlightening. Many thanks. -- To email me, substitute nowhere->spamcop, invalid->net. From james at reggieband.com Thu Jul 10 13:35:32 2008 From: james at reggieband.com (James Fassett) Date: Thu, 10 Jul 2008 10:35:32 -0700 (PDT) Subject: Idiomatic Python to convert list to dict References: <7ec9405c-4e6f-491d-84b2-c81152302b13@79g2000hsk.googlegroups.com> <6dmuacF33kciU1@mid.uni-berlin.de> Message-ID: <9c057b7c-4cfb-49ea-9b80-d24df810d6a8@b1g2000hsg.googlegroups.com> On Jul 10, 6:13?pm, "Diez B. Roggisch" wrote: > > my_list = ['a', 'b', 'c', 'd', 'e'] > > dup_map = {} > > for item in my_list: > > ? ? dup_map[item] = True > > > # ... sometime later > > > for complex_dict in large_list: > > ? ? if complex_dict["char"] not in dup_map: > > ? ? ? ? my_list.append(complex_dict["char"]) > > ? ? ? ? dup_map[complex_dict["char"]] = True > > Instead of a dict, use a set. It's immediatly contructable from my_list, > and better suited for the task anyway. Cheers, I rewrote it similar to: dup_map = set(['a', 'b', 'c', 'd', 'e']) # ... sometime later for complex_dict in large_list: dup_map.add(complex_dict["char"]) my_list = list(dup_map) That is a little nicer. Thanks again, James. From m.liu.jin at gmail.com Fri Jul 18 02:58:38 2008 From: m.liu.jin at gmail.com (m.liu.jin at gmail.com) Date: Thu, 17 Jul 2008 23:58:38 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> Message-ID: On Jul 18, 2:31?pm, castironpi wrote: > Given that, what does that column indicate? Offset. From paddy3118 at googlemail.com Wed Jul 30 03:06:43 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 30 Jul 2008 00:06:43 -0700 (PDT) Subject: Native Code vs. Python code for modules References: Message-ID: On Jul 30, 4:56?am, koblas wrote: > Ruby has been getting pummeled for the last year or more on the > performance subject. ?They've been working hard at improving it. ?From > my arm chair perspective Python is sitting on it's laurels and not > taking this as seriously as it probably should. I personally DON'T think that the developers should be chasing down every micro-benchmark. Someone has to look-up and see the bigger picture. If you take a look at a larger set of micro benchmarks, then Ruby is below par when compared to Python and Perl on speed. I had the misfortune to read their development group entries when a critical bug was 'fixed' by a release from Japan that didn't have enough testing and so think the Ruby development 'group' have problems of quality that they also need to address. (And are doing I think by adding to their test-suite). PyPy and previous tools like Psyco are ways in which Python developers are continuing to see above the eternal grind of micro- optimising the C-interpreter to try and give us tools that can approach compiled language speeds from the language we love. I like to think of it as working smarter rather than harder - the brains a much better muscle :-) - Paddy. From hat at se-162.se.wtb.tue.nl Wed Jul 2 03:43:48 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 02 Jul 2008 09:43:48 +0200 Subject: Required items in a form References: <45yak.331$Ae3.313@trnddc05> Message-ID: On 2008-07-01, Brandon wrote: > What I'm trying to do is essentially force a user to fill in required items > in a form, which will be saved to a database. How can I get it so that once > the user clicks "OK" on the dialog box, it transfers control back to the > form, and not save the empty fields into the database? Follow the golden rule of not trusting user input. When you get back values for the fields, check them, and if not correct, ask again, give an error, abort the program, erase the data base, reboot the system, whatever is appropiate to handle such an error. Sincerely Albert From durand1 at gmail.com Sat Jul 19 15:09:56 2008 From: durand1 at gmail.com (Durand) Date: Sat, 19 Jul 2008 20:09:56 +0100 Subject: matplotlib: Plotting a graph against time Message-ID: Hi, I'm trying to plot a simple graph against date or time using matplotlib. I've read about date_plot but I'm not really sure how to use it. At the moment, I have some data arranged into lists, where list1 contains x values (time) and list2 contains y values just like is needed for the normal plot function. The time values are simply the output of datetime.date.today(), etc which I don't mind changing the format of. My question is, how do I plot the graph with list1 on the x axis and list2 on the y axis. Using plot and unixtime I get a very ugly scale as is to be expected so I want to know how to use the date_plot function efficiently. At the moment, I'm only concerned about the actual plotting but help with Locater Ticks (Months and Years) is also very appreciated. Thanks a lot! From marc.wyburn at googlemail.com Wed Jul 30 11:39:43 2008 From: marc.wyburn at googlemail.com (marc wyburn) Date: Wed, 30 Jul 2008 08:39:43 -0700 (PDT) Subject: variable expansion with sqlite References: <489059DC.5090501@timgolden.me.uk> Message-ID: Hi and thanks, I was hoping to avoid having to weld qmarks together but I guess that's why people use things like SQL alchemy instead. It's a good lesson anyway. Thanks, Marc. On Jul 30, 2:24?pm, Tim Golden wrote: > Gerhard H?ring wrote: > > My code would probably look very similar. Btw you don't need to use > > list() on an iterable to pass to executemany(). pysqlite's executemany() > > accepts anything iterable (so generators work fine, too). > > Thanks for that. My finger-memory told me to do that, possibly > because some *other* dbapi interface only accepts lists. Can't > quite remember. I'm usually all in favour of non-crystallised > iterators. > > > Also, with SQLite you can just skip data type definitions like > > VARCHAR(200). They're ignored anyway. > > Heh. Once again, finger memory forced me to put *something* > in there. I've been developing Enterprise databases for too > long :) > > TJG From pranny at gmail.com Fri Jul 11 00:34:07 2008 From: pranny at gmail.com (pranav) Date: Thu, 10 Jul 2008 21:34:07 -0700 (PDT) Subject: Bypassing WebFilter security Message-ID: <563968a1-3cc3-4009-beca-d5d367d4ccff@k13g2000hse.googlegroups.com> Hello everyone, I am working in an organization, which is using a very strict webcontent filter management suite. Due to this i am unable to download any exe file, or surf web (even the necessary downloads from sourceforgenet are blocked). I was wondering, if python could be of any help. Say i have a python script, and i pass the URL of downloadable file, and it just downloads the file for me. From daisha52014 at gmail.com Fri Jul 25 05:49:14 2008 From: daisha52014 at gmail.com (wholesale) Date: Fri, 25 Jul 2008 02:49:14 -0700 (PDT) Subject: sell shoes jeans t-shirt sunglasses swimsuit parda air jordan Message-ID: www.yahoo808.cn Your satisfactions,Our pursuit! From howe.steven at gmail.com Thu Jul 17 16:04:16 2008 From: howe.steven at gmail.com (Steven Howe) Date: Thu, 17 Jul 2008 13:04:16 -0700 Subject: % sign in python? In-Reply-To: References: Message-ID: <487FA5C0.30206@gmail.com> Terry Reedy wrote: > > > korean_dave wrote: >> What does this operator do? Specifically in this context >> >> test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) >> >> (Tried googling and searching, but the "%" gets interpreted as an >> operation and distorts the search results) > > Having seen a number of comments like this over the years (about the > difficulty of searching for symbol meanings), I just started, last > night, a symbol index listing nearly all Python syntax uses of > non-alpha-or-digit ascii symbols. When I finish and upload it > somewhere, I will post an announcement with the link. > > tjr > > -- > http://mail.python.org/mailman/listinfo/python-list > I thought, in this contexted, it was mapping operator. sph From asd at pittle.org Thu Jul 3 16:15:51 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Thu, 3 Jul 2008 13:15:51 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> <9cdbb215-d427-4694-a455-f2571ad42390@x19g2000prg.googlegroups.com> <54e0e7c5-113e-4296-a62f-e649d6ffa2d6@z66g2000hsc.googlegroups.com> Message-ID: <87b10cf3-4fd4-46e3-a33a-528f1180f69a@s21g2000prm.googlegroups.com> On Jul 3, 7:42?pm, Fuzzyman wrote: > On Jun 30, 11:25?pm, Ali Servet D?nmez wrote: > > > > > On Jul 1, 12:15?am, Fuzzyman wrote: > > > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > > I don't want to be so mean here, but how hard it could be be writing a > > > > freesoftware which would automatically/intelligently auto complete > > > > Python code? (I mean something that really does the job, like > > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > > name it, but just don't give me PyDev please...) > > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > > missing here? > > > > > Could someone please point me out something that I'm really missing > > > > which is already present in the wild, otherwise I'd like discuss with > > > > whoever is willing to help me to get this thing done. I made my mind > > > > and I could volunteer to make this happen as thesis project for my > > > > incoming graduation in the next year. > > > > > Regards you all, > > > > Ali Servet D?nmez > > > > Vim, Emacs, Wing, Komodo, ... more? > > > > Yeah, I guess you're missing something. :-) > > > > MichaelFoordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > > I probabily am... Could you please kindly tell me what's the way to > > get it work for Emacs? > > Not personally I'm afraid. Although I did use Emacs today for the > first time (pairing with a colleague who inflicted it upon me). We did > have code completion working fine, but I have no idea how to set it up > (maybe the intarwebz can help?). > > Michael Foord > --http://www.ironpythoninaction.com/http://www.trypython.org/ I tried code come completion options in Emacs for Python, but none of them was satisfactory to me. I'd be glad to hear how did your friend get it work though. From paul at boddie.org.uk Sat Jul 26 14:15:10 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 26 Jul 2008 11:15:10 -0700 (PDT) Subject: Questions on 64 bit versions of Python References: <1216966424.4685.1265275245@webmail.messagingengine.com> Message-ID: On 25 Jul, 12:35, "M.-A. Lemburg" wrote: > > But then Intel Itanium is being phased out anyway Citation needed! ;-) Paul From rotlaus at gmail.com Tue Jul 8 06:59:32 2008 From: rotlaus at gmail.com (Andre Adrian) Date: Tue, 8 Jul 2008 10:59:32 +0000 (UTC) Subject: extended setattr() References: <6dgfprF2ekq3U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch nospam.web.de> writes: > > def ext_setattr(obj, attr, val): > > for subattr in attr.split("."): > > obj = getattr(obj, subattr) > > obj = val > > > >>>> import test > >>>> a = A() > > Traceback (most recent call last): > > File "", line 1, in > > NameError: name 'A' is not defined > >>>> a = test.A() > >>>> a.B.C.txt > > 'foo' > >>>> ext_setattr(a, 'B.C.txt', 'bar') > >>>> a.B.C.txt > > 'foo' > > > > What am i doing wrong? > > obj = val won't work. Why is this so? Shouldn't it be the same? > You need to use a setattr(obj, name, val) > on the last attribute-name. Ok, so this works: def ext_setattr(obj, attr, val): attributes = attr.split('.') for subattr in attributes[:-1]: obj = getattr(obj, subattr) setattr(obj, attributes[-1], val) From jeff.dyke at gmail.com Mon Jul 21 09:56:03 2008 From: jeff.dyke at gmail.com (Jeff Dyke) Date: Mon, 21 Jul 2008 09:56:03 -0400 Subject: imported module no longer available Message-ID: <8496caf30807210656y3d8467eer83a953e7c37e556c@mail.gmail.com> I've come across an error that i'm not yet able to create a test case for but wanted to get see if someone could shed light on this. I have imported a module at the top of my file with import mymodulename this module is used many times in the current file successfully, but then I attempt to use it one more time and get: UnboundLocalError: local variable 'mymodulename' referenced before assignment if i add `print globals().keys()` right before the line where the error occurs l see the module in the list (actual output, names changed to protect the innocent) ['HPADao', 'RDao', 'DriverBase', 'FKSUtility', 'PMDao', 'mymodulename', 'IDriver', 'DriverTrack', 'HPPDao', 'setLogName', 'HPDao', 'iparser', '__builtins__', '__file__', 'driver', '_LOGNAME', 'sys', 'IClient', '__name__', 'copy', 'types', 'logging', 'iloader', 'HPADao', '__doc__', 'PMDao', 'time', 'FormatLoad'] Traceback (most recent call last): File "testunbound.py", line 475, in driver.getRData('0605', 22528) File "testunbound.py", line 256, in getRData print mymodulename the code that generates these two lines is: print globals().keys() print mymodulename I can solve this by placing import mymodulename again in this method, but can't have that everywhere. I will try to come up with a generic reproduction of this issue, but that might take some time. I've also seen this in the past with the python builtin 'sys' I did see a bug http://bugs.python.org/issue2378, which has very similar behaviour, but is different. Python 2.5, ubuntu hardy Thanks for any insight, Jeff From norseman at hughes.net Tue Jul 8 13:36:09 2008 From: norseman at hughes.net (norseman) Date: Tue, 08 Jul 2008 10:36:09 -0700 Subject: How to make python scripts .py executable, not bring up editor In-Reply-To: References: <4872BC20.3080702@hughes.net> Message-ID: <4873A589.4070201@hughes.net> OK- ; In Windows use the Window Explorer and go find a something.py. Right click on it and select Open With then Browse and go find your Python24\python.exe and select it. Then check the box that says "Always use this for..." and test it by closing/re-opening WinExplorer and left clicking (or double clicking if so set) and it should attempt to run. IF so then use the 'dos window' and try typing in just it's name. ie... tryme.py this should attempt to run also. If not, check the C:\autoexec.bat PATH line. It just might be that it has the unwanted Python editor's path there. If so, consider putting your python24 path BEFORE it. (Don't forget to re-boot after mods to autoexec.bat) If that isn't the problem you might consider a complete scrub, reformat and re-install of Windows and ALL your stuff. (Uggg!) Don't be surprised if at some point it may "reset itself" back to it's current bad behavior. The Python editor shouldn't unless it is re-installed for some reason. The use of the bat file ignores any 'self reset' nonsense by forcing the desired action(s) by keeping Windows from wandering about. During the development cycle a modified copy in the working directory can delete program created files before (re)running script. This keeps Microsoft from yelling it can't function because something is in it's way. And hardcoding the file under development, along with any needed tokens, simplifies the command line and the cycle. ( del any files created in this loop (one line each) ( drive:\path_to\python pgm.py token tokens..... ( don't remember if pause or whatever - but give time to inspect screen ( preferred_editor pgm.py if in t.bat then t tests it and returns you to edit. Saves lots of typos, lowers anxiety, speeds up cycle, increases confidence in progress. NOTE: I use Linux and I do have a typo in my original reply. USE %1 NOT %f in the .bat file. Sorry ^numeric one Steve norseman at hughes.net ======================================================================= David Eynon wrote: > When my anyname.py runs, instead of executing the script, it opens up > the file within the Pythonwin text editor. > ======================================================================= > On Mon, Jul 7, 2008 at 9:00 PM, norseman wrote: >> korean_dave wrote: >>>> From command Prompt, i type in a script, "tryme.py". >>> This, instead, brings up PythonWin editor and Interactive Window. >>> >>> Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) >>> >>> How do I make it so that the script runs? >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> ====================================== >> I get tired of Microsoft jerking me around too. Rather than spend hours >> trying to undo somebody's reorganizing my system preferences I just ignore >> them completely. >> >> py tryme is how I do it. >> >> py.bat is a file placed in a directory listed in PATH in autoexec.bat. Edit >> autoexec.bat to include directory you put it in and reboot system or it >> won't find it. something like: PATH=.;c:\py-stuff;[anything already >> listed] Don't forget the semicolons. >> >> The . (period) up front means look here first. here being where ever you are >> when you issued the command. (The pRESENT wORKING dIRECTORY :-) The >> c:\py-stuff (fix to suit yourself and make sure it exists) is where you can >> put your efforts to be called at your leisure. Your .py files you write and >> use. Even the py.bat can go there. >> >> (Short note: Microsoft usually does look in pwd first. But good form >> dictates being specific.) >> >> contents of py.bat: >> ======================== >> rem name: py.bat >> @echo off >> c:\Python24\python %f.py make it fit your path >> rem end of file >> ======================== >> >> This way - you get what you expect, when you expect it, & nothing else. >> Yeah - dumb, but it works! I have one similar for each of my compilers. >> They contain the whole command line switches stuff as well as things like >> remove old stuff before trying to over write with new since MS can be >> temperamental about that. >> >> Easiest way in the world to give it the finger and make it behave. >> >> Steve >> norseman at hughes.ney >> > From mcl.office at googlemail.com Mon Jul 7 08:41:22 2008 From: mcl.office at googlemail.com (mcl) Date: Mon, 7 Jul 2008 05:41:22 -0700 (PDT) Subject: Confused yet again: Very Newbie Question References: <13be8c54-3fa9-4a37-a0e6-45bb019bff7e@a1g2000hsb.googlegroups.com> Message-ID: <593b44b7-9a0a-4665-9926-19890d29eabe@2g2000hsn.googlegroups.com> On 7 Jul, 13:09, Jeff wrote: > When you call c3.createJoe(c1.fred), you are passing a copy of the > value stored in c1.fred to your function. ?Python passes function > parameters by value. ?The function will not destructively modify its > arguments; you must expliticly state your intention to modify an > object: > > class one(): > ? ? fred = 'fred' > > class three(): > ? ? def createJoe(self, myName): > ? ? ? ? return "Joe" > > def main(): > ? ? c1 = one() > ? ? c3 = three() > ? ? c1.fred = c3.createJoe() # Modify c1's attribute, fred, with the > return value from c3.createJoe Thank you very much for your helpful replies. Two questions: One: My use of classes is because I want two classes one for global variables and one for global functions. A function may set multiple global variable values, so what is the best way to do this as 'return' only appears to be able to set one value. Two: I am sorry but I do not understand the significance defining a Class as: >>> class MyClass(object): what is object ? I am using python with Google App Engine, and I only have Alex Martelli's book up to Python 2.2, if they has any relevance ? Thanks again for your help. I now understand what my mistakes were and why I was not getting the results I had expected. Richard From alexnbryan at gmail.com Thu Jul 17 03:34:33 2008 From: alexnbryan at gmail.com (Alexnb) Date: Thu, 17 Jul 2008 00:34:33 -0700 (PDT) Subject: Getting a unknown word out of a list with no spaces In-Reply-To: <487EF593.5060505@promsoft.ru> References: <18502758.post@talk.nabble.com> <487EF593.5060505@promsoft.ru> Message-ID: <18503144.post@talk.nabble.com> Alexandr N Zamaraev wrote: > >>>> s = '--a href="/browse/brick"--brick--/a--' >>>> s > '--a href="/browse/brick"--brick--/a--' >>>> ''.join('<%s>' % l if i % 2 == 1 else l for i, l in > enumerate(s.split('--'))) > ' /browse/brick brick ' > > -- > http://mail.python.org/mailman/listinfo/python-list > > I'm sorry, I don't think I was being clear. I replaced the <'s with -- so it would post online w/o actually making a link. I just need to know how to get the "brick" out. -- View this message in context: http://www.nabble.com/Getting-a-unknown-word-out-of-a-list-with-no-spaces-tp18502758p18503144.html Sent from the Python - python-list mailing list archive at Nabble.com. From fredrik at pythonware.com Wed Jul 23 07:44:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 13:44:37 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> Message-ID: Fredrik Lundh wrote: > > cl cl -EHsc -MD -I \python25\include test.cc \python25\libs\python25.lib cut and paste error there: the "cl cl" should be just one "cl", of course. and just for the record/google, if I 1) don't include the header file, I get test.cc(5) : error C3861: 'Py_Initialize': identifier not found, even with argument-dependent lookup 2) attempt to undef the __cplusplus macro, I get test.cc(1) : warning C4117: macro name '__cplusplus' is reserved, '#undef' ignored 3) cut and paste declarations from the header files to my own file instead of including the files, ignoring the extern "C" part, I get test.obj : error LNK2019: unresolved external symbol "int __cdecl Py_Finalize(void)" (?Py_Finalize@@YAHXZ) referenced in function _main which looks pretty similar to the errors posted earlier. From mattheww at chiark.greenend.org.uk Thu Jul 31 19:51:25 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 01 Aug 2008 00:51:25 +0100 (BST) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <00a124e1$0$20313$c3e8da3@news.astraweb.com> <00a24168$0$20313$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >On Thu, 31 Jul 2008 22:01:48 +0100, Matthew Woodcraft wrote: >> The point is that if you tell people that "if x" is the standard way to >> check for emptiness, and also support a general principle along the >> lines of "write your function using the interfaces you expect, and call >> it using the object you have", you should expect to end up with bugs of >> this sort. > I'm not sure that an occasional performance hit justifies calling it a > bug. I suppose you might come up with a scenario or two where it really > is a problem, but then I'm also free to imagine scenarios where calling > len(obj) takes a massive performance hit, or has irreversible side > effects. Of course performance problems can be bugs! And it was explicit in my example that this was supposed to be such a case. But here, have an example where it's a non-performance bug: def load_widgets(self, widgets): if not widgets: raise ValueError("no widgets specified") self._prepare_for_widgets() for widget in widgets: self._load_widget(widget) self._is_widgetty = True This way you can end up with an object in an invalid state. >> I'm not a fan of len() for testing emptiness. But it would have been >> better in this case, because it would have converted a hard-to-find >> performance bug into an obvious exception. > At the cost of wrongly raising a exception for perfectly good arguments, > namely non-empty iterators. Sure, which will be fixed when the code passing an iterator is first tested, whether the iterator is empty or not. It's the errors which pass silently that are most dangerous. As I said, I'm not a fan of len() for testing emptiness. But "if x" isn't good either. Often I end up rearranging things so I can get rid of the explicit test altogether, but there can be a cost in readability. I think any Python-like language would be better off with an explicit way of asking 'is this container empty?'. -M- From tjreedy at udel.edu Sat Jul 12 22:02:54 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 22:02:54 -0400 Subject: palindrome function In-Reply-To: References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: Mensanator wrote: > It hasn't. and here's why: > > IDLE 2.6b1 >>>> seq=['a','n','n','a'] >>>> seq.reversed() > > Traceback (most recent call last): > File "", line 1, in > seq.reversed() > AttributeError: 'list' object has no attribute 'reversed' My apologies. reversed() is a builtin func, not a method, and it produces an iterator, not a seq. SO, corrected, >>> for s in ((1,2,3,2,1), [1,2,3,2,1]): ... type(s)(reversed(s)) == s ... True True >>> s = '12121' >>> ''.join(reversed(s)) == s True From mathieu.prevot at gmail.com Tue Jul 8 11:09:16 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Tue, 8 Jul 2008 17:09:16 +0200 Subject: Tricky problem: loss of terminal control after python script running (depending on internal parameters) Message-ID: <3e473cc60807080809v54ebd453i574f2d4de4db06d8@mail.gmail.com> Hi there, I have a python script that runs subprocesses (task = ffmpeg for convertion of videos to images) from threads [1]. I want to run at most 4 (default) tasks at the same time, and I usually ask the python script to process 10 files for testing. I'll run it on thousands of files for primetime. It seems that when I ask to process < 4 files everything is ok, but if I ask for > 4 files to process, I loose terminal features (no more newlines, etc). What's happening ? What is wrong in my script ? Thanks, Mathieu [1]: ,-- thread -- subprocess script --|-- thread -- subprocess |-- thread -- subprocess '-- thread -- subprocess -------------- next part -------------- A non-text attachment was scrubbed... Name: youff.py Type: application/octet-stream Size: 1279 bytes Desc: not available URL: From robert.rawlins at thinkbluemedia.co.uk Sun Jul 20 07:30:28 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Sun, 20 Jul 2008 12:30:28 +0100 Subject: __del__ methods In-Reply-To: <48831cca$0$16250$426a74cc@news.free.fr> References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> <87hcalxvx0.fsf@benfinney.id.au> <87prp8x23x.fsf@benfinney.id.au> <48831cca$0$16250$426a74cc@news.free.fr> Message-ID: <008201c8ea5c$03462a80$09d27f80$@rawlins@thinkbluemedia.co.uk> > Are you talking about the __new__ method ? Or about metaclasses ? Sorry Bruno, I should have made that a little clearer. I was talking about the __new__ method. Cheers mate, Robert From wuwei23 at gmail.com Wed Jul 23 03:06:31 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 23 Jul 2008 00:06:31 -0700 (PDT) Subject: os.walk question References: Message-ID: <58aaf7f2-c0bc-4041-a14f-503b0eb0b0a9@y22g2000prd.googlegroups.com> On Jul 24, 11:52?am, "Lanny" wrote: > How would one make a list of the files in the top directory > using os.walk. > > I need to pick a random file from said list. So you -only- want the files from one directory? Try: _, _, files = os.walk('/top/folder/here').next() The single underscore is a convention to indicate we don't care about those results. The .next() is needed to step through os.walk once, which will start at the path you specify. Hope this helps. - alex23 From iainking at gmail.com Tue Jul 29 05:27:22 2008 From: iainking at gmail.com (Iain King) Date: Tue, 29 Jul 2008 02:27:22 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> <466157f1-adcb-45f6-8c2d-b3c245a6ce8d@p31g2000prf.googlegroups.com> <47a24fed-6822-4767-aad3-07a72ddc3a1a@m73g2000hsh.googlegroups.com> Message-ID: <7a090a5e-c103-4182-b8d9-c1c0c4819696@y38g2000hsy.googlegroups.com> On Jul 29, 5:33 am, "Russ P." wrote: > On Jul 28, 8:44 pm, alex23 wrote: > > > On Jul 29, 4:46 am, "Russ P." wrote: > > > > As I said, I could write a pre-processor myself to > > > implement it in less than a day. > > > So WHY DON'T YOU WRITE IT ALREADY? > > I'm working on something else right now if you don't mind, but I'll > get to it in good time. > > Conceptually, the matter is simple. All I need to do is to grab the > first formal argument of each def, then search for occurrences of any > word in the body of the def that starts with a dot, and insert that > first argument in front of it. > > I expect the "hard" part will be breaking up the body of the def into > "words." I could just split each line on white space, except for > situations like > > x+=.zzz > > So I need to account for the fact that operators do not need to be > surrounded by spaces. That's the hardest part I can think of off the > top of my head. > > Maybe I'll encounter an insurmountable problem and realize that the > idea can't work in general. If so, then so be it. Certainly, no one on > this thread has anticipated such a problem. Had someone pointed out an > actual technical problem with the idea, I would have gladly thanked > them. But I got a load of irrelevant crap instead, not to mention > being addressed as "boy." > > > If you're meeting so much resistance to your idea, why not scratch > > your own damn itch and just do it? > > > Or doesn't that afford you as many chances to insult others while > > feeling smugly superior? > > This coming from a guy who insulted my reading comprehension ability > -- when he was the one who was wrong! Are you actually this stupid? I mean, you were entertaining while you were mouthing of and insulting your betters, but now you're gonna complain the second anyone insults you (and I mean, 'boy' - what an insult!). Never mind that you're never gonna get off your ass to write a PEP, which would be rejected on language design grounds anyway (as demonstrated by alex23's link - the one you aren't comprehending). The most irritating thing is that I like the idea of being able to use '.x = 10' type notation (and have been for a long time), but the person arguing for it is an insufferable buffoon who's too dense to understand a cogent argument, never mind make one. So great, thanks, the chances of this (or a VB 'with'-like 'using' keyword) ever making it into the language get smaller every time you fire up your keyboard. Nice work. Iain p.s. am looking forward to your post whining about the invalid reasons your PEP got rejected, in the slim hope you actually write one. From Rakesh.Thakrar at microcom-it.com Thu Jul 31 07:50:11 2008 From: Rakesh.Thakrar at microcom-it.com (Rakesh Thakrar) Date: Thu, 31 Jul 2008 12:50:11 +0100 Subject: Python Contractor needed Message-ID: <17A5EF611D8AF34DA2E14B2354C9C3FE1EFA00@ern-server-mail> Hi All, An opportunity for a talented Python Software Engineer has arisen to join a company which is currently going through a phase of rapid expansion. Candidates must have excellent software development skills to join an established team within this small company with offices in the U.K. and U.S. An ideal candidate will be familiar with Linux, have a passion for working with OpenSource software and a flair for creating innovative solutions to complex problems. The candidate will be a self motivated, flexible software engineer working within the existing I.T. Team. The day to day role will almost exclusively focus on new projects. Key elements of the role include l Work closely with the I.T. team and business managers to aid the design and implementation of a new web based application for our customers and data processing engine. l Work closely with the application design team to understand, agree, plan and develop the new application. l Assess software requirements and assist with the project planning stage. l Design, code and test various software elements in both Windows and Linux based environments. l Ability to train and mentor other members of the software development team. l Experience of working within a development team using source control and collaborative tools such as Subversion, CVS, Trac, etc. l Providing required documentation (specifications, test plans, processes, etc). This is a 6-12 month contract based near Portsmouth in Hampshire UK . Please do not hesitate to contact me for further information. Regards Rakesh ___________________ Rakesh Thakrar Manager Microcom Tel: 01923 851225 Mob: 079 7094 3227 Fax: 0845 389 2392 www.microcom-IT.com Beaumont Gate Shenley Hill Radlett Hertfordshire WD7 7AR Permanent and Contract IT Specialists ____________________________________ P SAVE A TREE - PLEASE DO NOT PRINT THIS EMAIL UNLESS YOU REALLY NEED TO. ************************************************************************ ************ The views expressed in this e-mail are not necessarily the views of European Recruitment Network Ltd, its directors, officers or employees make no representation or accept any liability for its accuracy or completeness unless expressly stated to the contrary. This e-mail, and any attachments are strictly confidential and intended for the addressee(s) only. The content may also contain legal, professional or other privileged information. Unless expressly stated to the contrary, no contracts may be concluded on behalf of European Recruitment Network Ltd by means of e-mail communication. You may report the matter by calling us on 0845 389 2322. Please ensure you have adequate virus protection before you open or detach any documents from this transmission. European Network Recruitment Ltd does not accept any liability for viruses. European Recruitment Network Ltd is registered in England: Company Number: 5651508. Registered Office: Greener House, 66-68 Haymarket, London, SW1Y 4RF ************************************************************************ ************ -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Jul 25 16:47:47 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Jul 2008 16:47:47 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87d4l2v1op.fsf@nokile.rath.org> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> Message-ID: Nikolaus Rath wrote: > Terry Reedy writes: >> Torsten Bronger wrote: >>> Hall?chen! >> > And why does this make the implicit insertion of "self" difficult? >>> I could easily write a preprocessor which does it after all. >> class C(): >> def f(): >> a = 3 >> >> Inserting self into the arg list is trivial. Mindlessly deciding >> correctly whether or not to insert 'self.' before 'a' is impossible >> when 'a' could ambiguously be either an attribute of self or a local >> variable of f. Or do you and/or Jordan plan to abolish local >> variables for methods? > > Why do you think that 'self' should be inserted anywhere except in the > arg list? AFAIU, the idea is to remove the need to write 'self' in the > arg list, not to get rid of it entirely. Because you must prefix self attributes with 'self.'. If you do not use any attributes of the instance of the class you are making the function an instance method of, then it is not really an instance method and need not and I would say should not be masqueraded as one. If the function is a static method, then it should be labeled as one and no 'self' is not needed and auto insertion would be a mistake. In brief, I assume the OP wants 'self' inserted in the body because inserting it only in the parameter list and never using it in the body is either silly or wrong. tjr From gordon at panix.com Thu Jul 24 11:24:16 2008 From: gordon at panix.com (John Gordon) Date: Thu, 24 Jul 2008 15:24:16 +0000 (UTC) Subject: Inserting cookies into a web session References: Message-ID: In =?ISO-8859-1?Q?Michael_Str=F6der?= writes: > John Gordon wrote: > > I'm developing a web application that needs a semi-persistent way to > > store information. > > > > I've looked at some options such as writing entries to a database table > > or creating small textfiles, but I'm not thrilled with anything I've come > > up with so far. > What's the problem? The problem is databases and textfiles are too heavyweight. I only need the information for the duration of a session; I don't want to have to worry about cleaning up the database or textfile afterwards. To explain my requirements a bit more, I'm writing a web-based contact manager application. The basic contact unit is a person, and I'm currently working on the page layout for displaying information relating to a person. The top section of the page is always the same: it shows your personal information. Name, userid, title, etc. But the bottom section of the page can change; it shows one of several different kinds of information. It can either display your home and office address, or it can show all the ways you can be contacted (phone, email, pager, etc), or it can show the times during which you wish to be contacted. (I didn't choose this layout; it was all done and approved before I joined the project. I just have to implement it.) My problem is if the user goes to the top portion of the page and changes some of the information there, for example he wants to change his title, that information is self-contained in a form and knows nothing about the choice the user made of what to show at the bottom of the page. Of course, I could add the choice as a hidden form element at the top of the page. But that seems kludgy -- that form *shouldn't* have to know. And the page layout isn't as simple as I've described here; there are actually lots of these little self-contained forms that are unrelated to the information at the bottom of the page, and I'd rather not have to add a hidden element to all of them. Using a cookie seems like an ideal solution. When the session starts, I can set the choice to the default setting of "address", and if the user ever clicks on "show me my contact methods" or "show me my times", I just set the cookie to that choice. I don't have to worry about passing the choice around in each of the dozen or so forms that are on the page. > Before using cookies keep in mind that the cookies returned by the > browser are not trustworthy! You have to validate the values each time. I'm not sure it's worth the trouble in my case. I won't be depending on the cookie for sensitive information; I'm just using it as a stored setting for which kind of information to display on the page. > http://docs.python.org/lib/module-Cookie.html That looks great! > Ciao, Michael. Thanks Michael. :-) -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From sunp1028 at gmail.com Wed Jul 16 20:50:40 2008 From: sunp1028 at gmail.com (patrol) Date: Wed, 16 Jul 2008 17:50:40 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> <487E1AD4.9020509@timgolden.me.uk> <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> Message-ID: <26354141-eeaf-4e86-afaf-7cb79fa1a3b8@f36g2000hsa.googlegroups.com> On 7?17?, ??3?20?, Tim Golden wrote: > patrol wrote: > > On 7?17?, ??12?16?, Tim Golden wrote: > >> Assuming that the error comes back in the sys.stdout encoding, the following version *should* work ok. I still haven't got a non-English set up to test it on, but it certainly does return a Unicode error message. > > >>http://timgolden.me.uk/wmi-project/wmi.py > > >> The usual test case, if you wouldn't mind: > > >> > >> import wmi > > >> wmi.WMI ("non-existent computer") > > >> > > >> should give a (language-specific) error message, not an UnicodeDecodeError > > >> TJG > > -------------------------------------------------------------------------------------- > >>>> import wmi > >>>> wmi.WMI('non-existent computer') > > Traceback (most recent call last): > > File "", line 1, in > > File "C:\Python25\lib\wmi.py", line 1199, in connect > > handle_com_error (error_info) > > File "C:\Python25\lib\wmi.py", line 184, in handle_com_error > > exception_string = [u"%s - %s" % (hex (hresult_code), > > hresult_name)] > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > > 4: ordinal > > not in range(128) > > -------------------------------------------------------------------------------------- > > yup,error_info contains the Chinese encoded string. All of the Simple > > Chinese Windows use the CP936.Every Chinese word utilizes two > > bytes.Maybe you can fix this bug by modifying handle_com_error. > > Can you confirm that that last bit of > code was run with the version of wmi.py > currently at: > > http://timgolden.me.uk/wmi-project/wmi.py > > That version should already be decoding the > string correctly. > > TJG ---------------------------------------------------------------------------------------- >>> import wmi >>> wmi.WMI('non-existent computer') Traceback (most recent call last): File "", line 1, in wmi.WMI('non-existent computer') File "C:\Python25\lib\wmi.py", line 1199, in connect handle_com_error (error_info) File "C:\Python25\lib\wmi.py", line 189, in handle_com_error raise x_wmi, u"\n".join (exception_string) x_wmi: ------------------------------------------------------------------------------------------ # -*- coding:utf-8 -*- import wmi from time import sleep c = wmi.WMI () process_watcher = c.Win32_Process.watch_for("creation") while True: new_process = process_watcher() if new_process.Caption == 'notepad.exe': print "start killing.." sleep(5) result = new_process.Terminate() print "killed" When I kill the notepad.exe manually,it also results in errors. Traceback (most recent call last): File "C:\Documents and Settings\patrol\??\test.py", line 12, in result = new_process.Terminate() File "C:\Python25\lib\wmi.py", line 396, in __call__ handle_com_error (error_info) File "C:\Python25\lib\wmi.py", line 188, in handle_com_error exception_string.append (u" %s - %s" % (hex (scode), (error_description or u"").decode (sys.stdout.encoding).strip ())) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin al not in range(128) ----------------------------------------------------------------------------------------------- Patrol From CracKPod at googlemail.com Tue Jul 15 04:04:06 2008 From: CracKPod at googlemail.com (CracKPod) Date: Tue, 15 Jul 2008 01:04:06 -0700 (PDT) Subject: Python Tiddlywiki class References: Message-ID: <4ac68650-b2c0-4992-86aa-e0572bf7f0cb@m36g2000hse.googlegroups.com> On 15 Jul., 03:04, David wrote: > CracKPod wrote: > > Hello, I wrote a Python class to interact with the TiddlyWiki. In case > > you are interested you can find it on my blog: > > >http://crackpod.bplaced.net/ > > > CracKPod > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Thank you :) > > -- > Powered by Gentoo GNU/LINUXhttp://www.linuxcrazy.com You're welcome! If I may beg you, redownload it from my Blog. I had to make a small change that's why I released 1.0.1, elsewise you won't be able to change the tiddler content and save it afterwards. From fredrik at pythonware.com Mon Jul 21 12:16:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 18:16:31 +0200 Subject: Seriously, though, about LLVM In-Reply-To: References: Message-ID: mk wrote: > This project has gained some publicity. There's IronPython, right, so > has anybody thought about implementing Python using LLVM as backend, as > it seems not out of question at all? you mean like: http://llvm.org/ProjectsWithLLVM/#pypy ? From fredrik at pythonware.com Mon Jul 21 08:47:32 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 14:47:32 +0200 Subject: error In-Reply-To: <5f4395d7-9f5c-45c3-b137-655e5c618b8c@8g2000hse.googlegroups.com> References: <5f4395d7-9f5c-45c3-b137-655e5c618b8c@8g2000hse.googlegroups.com> Message-ID: Anish Chapagain wrote: > from Tkinter import * > root=Tk() > f=Frame(root,height=200,width=200) > b=Button(f,text="quit",command=f.quit) > f.pack() > root.mainloop() > > -------------------------------------------------- > from Tkinter import * > import sys > root=Tk() > f=Frame(root,height=200,width=200) > b=Button(f,text="quit",command=sys.exit) > f.pack() > root.mainloop() > > I am wondering that why the button after clikcing is not closing the > window..please any suggestion.. > i tries command=f.quit, sys.quit also.. > if there is something i'm missing please help Assuming you accidentally left out the line where you're displaying the button (e.g. "b.pack()"), both your samples work when running this from the command line. Are you perhaps running this code from inside IDLE? IDLE is itself written in Tkinter, and it doesn't always shut down the Tkinter subsystem properly. ... and I have to admit that I don't know what the currently recommended workaround is -- you'll find plenty of documentation on the net that just says "don't do that" (run Tkinter programs from within IDLE, that is), but surely someone should have fixed that issue by now?. From frankrentef at yahoo.com Thu Jul 24 12:09:12 2008 From: frankrentef at yahoo.com (frankrentef) Date: Thu, 24 Jul 2008 09:09:12 -0700 (PDT) Subject: Python / PAMIE References: <9e077ec9-9a07-4a3a-b5dc-bfd593162350@8g2000hse.googlegroups.com> Message-ID: On Jul 24, 10:45?am, Tim Golden wrote: > frankrentef wrote: > > THNX for your response. ?Based on the authors code it's very simple. > > > from cPAMIE import PAMIE > > ie=PAMIE () > > > #ie.navigate ("google.com") > > > #ie.linkClick > > #ie.textBoxSet > > #ie.writeScript > > > ie.navigate ('https://login.yahoo.com/config/mail?.intl=us') > > #ie.scriptWrite () > > > ie.scriptWrite() > > > Below is the error I get... > > > ?File "C:\Python24\lib\site-packages\cPAMIE.py", line 1837, in > > scriptWrite > > ? ? nameProp = getattr(x,"nameProp") > > ? File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", > > line 500, in __getattr__ > > ? ? raise AttributeError, "%s.%s" % (self._username_, attr) > > AttributeError: .nameProp > > I'm afraid I'm no IE expert (read: never use it if I can > avoid it) but I suspect here a combination of slightly > flaky code in the Python module plus, maybe, a change in > the IE dom object model. > > If you change lines 1832-1836 of cPAMIE.py to be as follows: > > > ? ? ? ? ? ? for j in range(doc.length): > ? ? ? ? ? ? ? ? x = doc[j] > ? ? ? ? ? ? ? ? etype = getattr(x,"type", "") > ? ? ? ? ? ? ? ? name = getattr(x,"name", "") > ? ? ? ? ? ? ? ? nameProp = getattr(x,"nameProp", "") > > > > then at least some kind of output is produced. But I'm > not entirely sure what this function is trying to achieve > so I don't guarantee it's doing the right thing yet. > > TJG- Hide quoted text - > > - Show quoted text - The idea is to run through a given url, detect any "form fields" that require populating and build a script listing the field names, etc. From there a PAMIE user can take the script returned and build a test case. In other words the user does not have to search through the HTML code for all the field names (blanks) radio button names, etc. It works "great" on the video tutorial but dang if I or any of our senior guys can get it to work here in house. THNX for input, we'll give it a try. From circularfunc at yahoo.se Thu Jul 3 14:47:11 2008 From: circularfunc at yahoo.se (defn noob) Date: Thu, 3 Jul 2008 11:47:11 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: <6d4bfmFp3aoU1@mid.uni-berlin.de> <0f6f795d-8041-463e-8e98-9d830ca3fc5b@l42g2000hsc.googlegroups.com> <45111722-3f2c-476d-8e7b-fd65cc5100a6@56g2000hsm.googlegroups.com> Message-ID: On Jul 3, 8:06?pm, "bruno.desthuilli... at gmail.com" wrote: > On 3 juil, 18:51, defn noob wrote: > > > well the reason i unzipped and placed it in site-packages was because > > nothign happened when i ran setup.py(unzipped). > > What do you mean, "running setup.py unzipped" ??? > > The correct way to install a package is to: > > - unzip (untar, whatever) the archive somewhere in your own directory > - cd to the unzipped directory > - *from there*, run python setup.py install yes, which i have done. the command row executes but nothing happens, no errors either. From alif016 at gmail.com Fri Jul 18 10:47:54 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Fri, 18 Jul 2008 09:47:54 -0500 Subject: trying to match a string In-Reply-To: <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> Message-ID: <4880AD1A.6040707@gmail.com> oj wrote: > On Jul 18, 12:10 pm, John Machin wrote: > >> On Jul 18, 9:05 pm, oj wrote: >> >> >> >> >>> On Jul 18, 11:33 am, arnimavidyar... at gmail.com wrote: >>> >>>> Hi, >>>> >>>> Hi, >>>> >>>> I am taking a string as an input from the user and it should only >>>> contain the chars:L , M or R >>>> >>>> I tried the folllowing in kodos but they are still not perfect: >>>> >>>> [^A-K,^N-Q,^S-Z,^0-9] >>>> [L][M][R] >>>> [LRM]?L?[LRM]? etc but they do not exactly meet what I need. >>>> >>>> For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. >>>> >>>> regards, >>>> SZ >>>> >>>> The string may or may not have all the three chars. >>>> >>> With regular expressions, [^LRM] matches a character that isn't L, R >>> or M. So: >>> >>> import re >>> >>> var = "LRLRLRLNR" >>> >>> if re.search(r'[^LRM]', var): >>> print "Invalid" >>> >> Fails if var refers to the empty string. >> > > No it doesn't, it succeeds if var is an empty string. An empty string > doesn't contain characters that are not L, R or M. > > The OP doesn't specify whether an empty string is valid or not. My > interpretation was that an empty string would be valid. > Why not just use * instead of + like: if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of string; $ means end of string print "Invalid" This will *only* print invalid when there is a character other than L, R, or M or a empty string. From __peter__ at web.de Thu Jul 3 02:43:45 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 Jul 2008 08:43:45 +0200 Subject: How to pickle bound methods References: Message-ID: srinivasan srinivas wrote: Please don't top-post. > Could you please explain?the code breifly?? I am not getting what it does. >> import copy_reg >> import new >> >> def make_instancemethod(inst, methodname): >> ? ? return getattr(inst, methodname) >> >> def pickle_instancemethod(method): >> ? ? return make_instancemethod, (method.im_self, method.im_func.__name__) >> >> copy_reg.pickle(new.instancemethod, pickle_instancemethod, >> make_instancemethod) If you have a type that cannot be pickled because it is implemented in C you can make it "picklable" by registering it with the copy_reg.pickle() function. This function takes three arguments: 1 the type (here: new.instancemethod) 2 a function that takes an instance of the type. This returns a factory function and a tuple of the arguments this factory function needs to recreate the instance. 3 the factory function. In short the following must work, and out_method should do the same thing as in_method: factory, args = pickle_instancemethod(in_method) out_method = factory(*args) Now to your other problem, pickling static methods. The type of a static method is just new.function, the same as that of a global function. Global functions are already picklable, so the copy_reg mechanism doesn't kick in. Peter From sjmachin at lexicon.net Thu Jul 31 19:19:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 31 Jul 2008 16:19:37 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> <4609709f-dc0f-47cc-905e-1552a02ec3b6@r15g2000prd.googlegroups.com> <416f2710-1295-4d8b-a356-98fd9e9a56ad@j7g2000prm.googlegroups.com> Message-ID: <33e97e69-84ec-4553-a7bd-aaba5ffe6944@v13g2000pro.googlegroups.com> On Aug 1, 7:44 am, william tanksley wrote: > John Machin wrote: > > william tanksley wrote: > > Let's try again: > > Cool. Sorry for the misunderstanding. Thank you for helping again! > > Postscript: your request to print the actual data did the trick. I'd back inspecting actual data against armchair philosophy any time :-) > I'm > including the rest of my reply just to provide context, but the answer > was the the Unicode was actually embedded in the URL, encoded as > distinct bytes. Thus, it *had* to be url-decoded and then UTF-8 > decoded, in that order, in order to recover the original filename. > > So the problem was indeed purely in my head -- I should have looked at > the original data (unfortunately, I was fooled by looking at the song > title, which is the same thing but with the raw UTF-8 bytes instead of > the URL escape codes). > > > > > >> track_id = url2pathname(urlparse(track_id).path) > > >> print repr(track_id) > > >> parse_result = urlparse(track_id).path > > >> print repr(parse_result) > > >> track_id_replacement = url2pathname(parse_result) > > >> print repr(track_id_replacement) > > > The "important" value here is track_id_replacement; it contains the > > > data that's throwing me. It appears that some UTF-8 characters are > > > being read as multiple bytes by ElementTree rather than being decoded > > > into Unicode. > > > Here's one example. The others are similar -- they have the same > > > things that look like problems to me. > > > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" > > ROTFL! I thought the Buffett thing was a Windows filename! What I was > > expecting was THREE lots of repr() output, and I'm quite unused to > > seeing repr() output with quotes around it instead of apostrophes; how > > did you achieve that? > > I don't know -- but I got it again when I printed out the original > version. My *guess* would be that this is what repr prints when asked > to print a byte string (but I don't know how to confirm that). > Alternately, the fact that I'm running these inside SPE might be > changing some defaults. I'm not sure. > > You're right that single quotes are expected -- and I'd expect a > preceding u, since they're supposed to be Unicode. I dunno what's > going on. Why do you suppose that the contents are Unicode? It's a URL-encoded string i.e. *deliberately* ASCII, in fact sub-ASCII (see all the %20 stuff?). What's going on is that ElementTree presents text as ASCII if it can be so represented, otherwise as Unicode. This is actually a *convenience*. Get used to it. Enjoy it. > > > So you're saying that track_id_replacement contains utf8 characters. > > It is obtained by track_id_replacement = url2pathname(parse_result). > > You don't show us what is in parse_result. url2pathname() is nothing > > to do with ElementTree. urlparse() is nothing to do with ElementTree. > > You have provided no evidence that ElementTree is doing what you > > accuse it of. > > Okay. Here's the evidence... Or something. Looking at this I begin to > see why things work the way they do. It's utterly bizzare, quite > frankly. > > > Please try again. Backtrack in your code to where you are pulling the > > url out of an element. Do print repr(some_element.some_attribute). > > Show us. > > Okay, the repr of the string that comes out of the .text attribute is: > > "file://localhost/C:/Documents%20and%20Settings/TanksleyJrW/My > %20Documents/My%20Music/iTunes/iTunes%20Music/Podcasts/Brian > %20Preston's%20_Money%20Guy_%20Blog%20and%20Pod/Buffett%20Time%20- > %20Annual%20Shareholders%C2%A0L.mp3" > > Looking at the XML, and THIS TIME actually looking at the correct > attribute (I was looking at the title before) I see... surprise! > That's the correct data. > > So all of the mysteries are solved (except for my Python's > doublequotes, but who cares), and ElementTree is entirely vindicated. Shucks. I can sense that you'd been looking forward to conducting an auto-da-fe followed by tossing the author on a bonfire ... but you can't burn a bot anyway :-) From rocksportrocker at googlemail.com Wed Jul 2 09:30:03 2008 From: rocksportrocker at googlemail.com (rocksportrocker) Date: Wed, 2 Jul 2008 06:30:03 -0700 (PDT) Subject: Distribute ctypes based modules Message-ID: Hi, how do you distribute ctypes based modules on a linux machine ? What does your setup.py look like ? I have to copy my shared library to /usr/lib or another common place, but I would prefer .../site-packages/... In the latter case I have to modify LD_LIBRARY_PATH oder some ld.so.conf configuration file. So, what is the prefered method for this task ? Greetings, Uwe From desothier at yahoo.com Tue Jul 22 11:10:41 2008 From: desothier at yahoo.com (antar2) Date: Tue, 22 Jul 2008 08:10:41 -0700 (PDT) Subject: convert list of lists to list Message-ID: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> Is there a way to convert list_of_listsA to list_of_listsB, where one list in listof lists A is one element of listB? list_of_listsA: [['klas*', '*', '*'], ['mooi*', '*', '*', '*'], ['koe'], ['arm*', '*', '*(haar)'], ['groei*', '*', '*', '*', '*']] listB: ['klas* * *', 'mooi* * * *, 'koe', 'arm* * * (haar)', 'groei* * * * *'] Thankx! From ojeeves at gmail.com Mon Jul 21 05:23:43 2008 From: ojeeves at gmail.com (oj) Date: Mon, 21 Jul 2008 02:23:43 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> Message-ID: <7574170c-ea58-48a5-83b0-0cd909f07d06@k37g2000hsf.googlegroups.com> On Jul 19, 3:04?am, Andrew Freeman wrote: > let me revise it please: > > To show if valid: > > if re.search(r'^[LRM]*$', 'LM'): > ? ? print 'Valid' Fine, this works, although match instead of search blah blah blah as has already been mentioned. I still think searching for one invalid character is more elegant then trying to match the entire string, but that's just personal preference, I guess. > > To show if invalid, > > if re.search(r'^[^LRM]*$', '0'): > ? ? print 'Inalid' No. This is wrong. This only matches strings that consist entirely of characters that are not L, R or M: >>> import re >>> if re.search(r'^[^LRM]*$', 'ZZZLZZZ'): ... print "Invalid" ... >>> This doesn't print "Invalid" because there is one non-invalid character there, which is clearly not what the OP wanted. From karthikbalaguru79 at gmail.com Thu Jul 17 02:56:05 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Wed, 16 Jul 2008 23:56:05 -0700 (PDT) Subject: Instance Message-ID: <120cea3a-33a9-49ec-8932-7cef2e5aef17@25g2000hsx.googlegroups.com> Hi, I am new to python. I am trying to use the python files given to me for bringing up a setup. I get the following error while trying to use a python file - AttributeError : Classroom instance has no attribute 'desk_offset' How to resolve this ? Should i need to define desk_offset to zero in the python file ? Any ideas .. Thx in advans, Karthik Balaguru From __peter__ at web.de Fri Jul 18 05:16:54 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 11:16:54 +0200 Subject: sub typing built in type with common attributes. Am I right? References: <4d9c4b74-9c28-4b98-afe7-9eb774655c3a@v21g2000pro.googlegroups.com> Message-ID: King wrote: > I am new to python and getting into classes. Here I am trying to > create subtype of built in types with some additional attributes and > function. 'Attributes' is the main class and holds all the common > attributes that requires by these subtypes. This is what I came out > with. I need to know whether everything is right here ? or there are > some better ways to do it. There may be some technical errors in your code, e. g. - the __slots__ look like a bit of bullshit: you already have a __dict__ from the Attribute base class - name mangling is done for attributes starting with two underscores But the greater problem I see is that you are building up a huge bureaucracy where pythonic code would concentrate on a concrete goal with minimal administrative overhead. Peter From stefan_ml at behnel.de Thu Jul 3 09:32:06 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 3 Jul 2008 13:32:06 +0000 (UTC) Subject: ANN: XML builder for Python References: <10df03a30807021716v33518930g951e903c2529ef82@mail.gmail.com> Message-ID: Hi, two comments. Gerard flanagan gmail.com> writes: > Nice! Here's a version that uses elementtree: [...] > def __call__(self, value='', **kargs): > self.element.text = value This should spell def __call__(self, value=None, **kargs): > class builder(element): > def __init__(self, version, encoding): > self.parent = ET.Element('root') And this might need some more work to fix as the root element shouldn't be necessary. But it's a good start. Look at the link I posted for some more ideas. Stefan From h.goebel at goebel-consult.de Tue Jul 15 17:00:58 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Tue, 15 Jul 2008 23:00:58 +0200 Subject: Using McMillan Installer, PyInstall or py2exe cross-platform? In-Reply-To: References: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <487d100a$0$7538$9b4e6d93@newsspool1.arcor-online.net> David Lyon schrieb: > there is a python based "bake" make like program... that is useful... > http://projects.bertram-scharpf.de/bake/bake1.html I'm not in the need of a build program :-) I would use Scons therefor, anyway. > then there is Wine... that is a windows emulator under linux... that > might be pretty easy.... http://www.winehq.org/ I don't like to use winw here, it would nor fit into my release process. I started working on cross-pyinstall today. -- Sch?nen Gru? - Regards Hartmut Goebel Goebel Consult Spezialist f?r IT-Sicherheit in komplexen Umgebungen http://www.goebel-consult.de From noorhanabbas at yahoo.co.uk Wed Jul 9 12:32:31 2008 From: noorhanabbas at yahoo.co.uk (Noorhan Abbas) Date: Wed, 9 Jul 2008 16:32:31 +0000 (GMT) Subject: Openine unicode files Message-ID: <92793.41064.qm@web27403.mail.ukl.yahoo.com> Hello, I wonder if someone can advise me on how to open unicode utf-8 files without using the codecs library . I am trying to use the codecs.open() from within Google Appengine but it is not working.?? Thank you very much in advance, Nora __________________________________________________________ Not happy with your email address?. Get the one you really want - millions of new email addresses available now at Yahoo! http://uk.docs.yahoo.com/ymail/new.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Thu Jul 24 04:57:53 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 24 Jul 2008 09:57:53 +0100 Subject: Recursion Performance Question In-Reply-To: References: Message-ID: <48884411.3020303@timgolden.me.uk> B wrote: > Now it works, but it runs quite slow (compared to the c++ app). I > changed gwl from strait recursion to use a generator and that helped, > but it still takes 0.5-1.0 seconds to populate the tree. What I'm > wondering is am I doing it in a really inefficient way, or is it just > python? Well I did just enough to get your code to work and ran it through timeit on my respectable but hardly bleeding-edge desktop PC. C:\temp>python -m timeit "import get_windows; get_windows.run ()" 100 loops, best of 3: 17.1 msec per loop So it's not that slow. Full code is posted below; uncomment the "print_tree" bit to see the results to confirm that it's doing what you think. I did this really quickly so it's possibly I've misunderstood what your code's up to. I'm not saying there aren't other ways to do this, but your code (at least inside my guessed-at wrapper) seems to do an adequate job in a reasonable time. import time from win32gui import GetWindow, GetWindowText, GetDesktopWindow from win32con import GW_CHILD, GW_HWNDNEXT class Node (object): def __init__ (self, hwnd): self.hwnd = hwnd self.children = [] def addChild (self, hwnd): self.children.append (Node (hwnd)) def gwl(node, hwnd): if hwnd: yield node, hwnd for nd, wnd in gwl(node.children[-1], GetWindow(hwnd, GW_CHILD)): yield nd, wnd for nd, wnd in gwl(node, GetWindow(hwnd, GW_HWNDNEXT)): yield nd, wnd def generateTree(self): t = time.clock() if self is not None: self.children = [] for nd, wnd in gwl(self, GetWindow(self.hwnd, GW_CHILD)): nd.addChild(wnd) def print_tree (root, level=0): print level * " ", GetWindowText (root.hwnd) or hex (root.hwnd) for child in root.children: print_tree (child, level + 1) def run (): desktop = Node (GetDesktopWindow ()) generateTree (desktop) #~ print_tree (desktop) > The second problem is reseting the list. In C++ I would use the STL > Vector's clear() method. In python, I can't think of a good way to free > all the nodes, so there is a large memory leak. I'm not clear here what you're getting at. Memory handling in Python is usually best left to Python unless you've got a very specific case -- and they do crop up occasionally. Just to be clear on something: Python does its own internal memory management, alloc-ing and free-ing with a variety of policies broadly managed by an internal pool. You're unlikely to see much memory released back to the system while Python's running. But this isn't a memory leak as such. You don't need to (and, in effect, can't) release the memory explicitly. But I'd be surprised if you had enough windows open for this to be even noticeable. TJG From paddy3118 at googlemail.com Tue Jul 22 18:11:35 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 22 Jul 2008 15:11:35 -0700 (PDT) Subject: Bidirectional Generators References: <8e2cf6b7-4b5f-4701-8a4c-bc779ed7305c@m45g2000hsb.googlegroups.com> Message-ID: <976df308-3855-4f2b-a82a-dacba480e7d7@i76g2000hsf.googlegroups.com> On Jul 22, 10:07?pm, william tanksley wrote: > Okay, I'm almost finished with my first bidirectional generator. By > "almost finished" I mean both that it's almost working, and that I'm > almost about to replace it with a class that works a bit more like > what I currently understand. > > Surely some other people have worked with this feature... Are there > any pages that discuss how it's been useful? > > No, I don't want to see an implementation of coroutines. I get that > one already. :-) > > -Wm What's one of them then? - Paddy. From victorsubervi at gmail.com Tue Jul 29 09:26:34 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 29 Jul 2008 15:26:34 +0200 Subject: Windows Interpreter In-Reply-To: <488F1745.4020705@timgolden.me.uk> References: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> <488F1745.4020705@timgolden.me.uk> Message-ID: <4dc0cfea0807290626p4b05376en49ccb18f0e1eb4bb@mail.gmail.com> def a(): chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', '\\yz'] rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like the Beast? Who can wage war against him?\par' for char in chars: c = '(?<=' + char + ')' test = re.search(c, rtf_markup) try: junk = test.group(0) print char except: pass Now, I can paste that entire fn in linux. But in windows I have to paste it line_by_line. Pain in butt! And it indents automatically. How change that behavior. TIA, Victor On 7/29/08, Tim Golden wrote: > > Victor Subervi wrote: > >> Hi: >> I would like to make my windows python interpreter work like my linux one. >> I want to be able to cut and paste multiple lines of code. >> > > You can already do this: what are you trying which isn't working? > > Now I can only paste one line at a time. I do not want it to indent >> automatically. How can I change this? >> > > I realise this is a difficult thing to describe in words, > but I regularly cut and paste multiple lines of code > into my Python interpreter and it doesn't indent automatically. Can you > give some specific examples of what you do and what does or doesn't work? > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alif016 at gmail.com Sat Jul 19 15:00:52 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Sat, 19 Jul 2008 14:00:52 -0500 Subject: trying to match a string In-Reply-To: <4881FE02.3000203@gmail.com> References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> <945275e9-8923-479c-8eec-258bd68063c0@z6g2000pre.googlegroups.com> <4881FE02.3000203@gmail.com> Message-ID: <488239E4.1010900@gmail.com> Andrew Freeman wrote: > John Machin wrote: >> A couple of points: >> (1) Instead of search(r'^blahblah', ...) use match(r'blahblah', ...) >> (2) You need to choose your end-anchor correctly; your pattern is >> permitting a newline at the end: I forgot to change search to match. This should be better: def match(var): if re.match(r'[LRM]*\Z', var): return True else: return False I was also thinking if you had a list of these items needing to be verified you could use this: >>> l = ['LLMMRR', '00thLL', 'L', '\n'] >>> out = [] >>> map(lambda i: match(i)==False or out.append(i), l) >>> print out ['LLMMRR', 'L'] -- Andrew From ggpolo at gmail.com Mon Jul 28 17:40:24 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 28 Jul 2008 18:40:24 -0300 Subject: seemingly simple list indexing problem In-Reply-To: References: Message-ID: On Mon, Jul 28, 2008 at 6:24 PM, Ervan Ensis wrote: > My programming skills are pretty rusty and I'm just learning Python so this > problem is giving me trouble. > > I have a list like [108, 58, 68]. I want to return the sorted indices of > these items in the same order as the original list. So I should return [2, > 0, 1] You could simply do this: a = [108, 58, 68] b = sorted(a) [b.index(c) for c in a] > > For a list that's already in order, I'll just return the indices, i.e. [56, > 66, 76] should return [0, 1, 2] > > Any help would be appreciated. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From stefan_ml at behnel.de Sun Jul 27 09:28:15 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 27 Jul 2008 15:28:15 +0200 Subject: Read .txt file like .py file In-Reply-To: <90f13013-bb20-4224-ac58-02947f3f9358@i24g2000prf.googlegroups.com> References: <90f13013-bb20-4224-ac58-02947f3f9358@i24g2000prf.googlegroups.com> Message-ID: <488c77ee$0$29452$9b4e6d93@newsspool4.arcor-online.net> King wrote: > I have a text file and contents are: > > Help=""" > Code is written by xteam. > """ > value = 0.0 > > > How do I read this file like python syntax. What I mean is first > readline operation should return complete declaration of 'Help' > variable. If I evaluate this string then it should create a 'Help' > variable with it's value. If you trust the author of the file and you're sure the code in the text file isn't an Internet worm and won't delete all your files, you can get away with the built-in "execfile" function. If you want more security, look at the compiler module and the ast module. They allow you to parse the file like a normal Python source file, and IIRC, there are also ways to execute single statements from a syntax tree. Stefan From gh at ghaering.de Tue Jul 15 08:17:06 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 15 Jul 2008 14:17:06 +0200 Subject: Suggestion: Python global scope In-Reply-To: References: Message-ID: Anonymous Bastard wrote: > I've been tossing this idea in my mind for some time now: > > In Python, declaring a variable using the global statement automatically > makes it available in all subsequent scopes. > > But to me, it makes more sense to use the global statement to 'import' a > variable from the global scope into the current scope. For instance: > > [code] > global X > X = 1 > > def P(): > X = 2 > print X > global X > print X > > print X > P() > print X > [code] > > Currently, this will print 1, 2, 2 and 2. But if global would be limited > to current scope, it would print 1, 2, 1, 1. > > 'X = 2' would work on the local version of X, 'global X' will 'import' > the global X into the local scope, so any actions on X would reference > the global X, rather than previous X. Anything backwards incompatible like this will never happen. -- Gerhard From mail at timgolden.me.uk Thu Jul 31 04:28:32 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 31 Jul 2008 09:28:32 +0100 Subject: win32com ChartObject pythonwin vs idle In-Reply-To: <670b57b7-d48e-44c0-abd0-b6772d23688d@79g2000hsk.googlegroups.com> References: <670b57b7-d48e-44c0-abd0-b6772d23688d@79g2000hsk.googlegroups.com> Message-ID: <489177B0.7000509@timgolden.me.uk> sterling wrote: > I'm curious as to why the difference between IDLE and pythonWin when > using win32com. > opening an excel file, i've attempted to grab the chart information > out of the file. > > commands like co = ChartObjects(1) works in pythonWin but doesn't > work in IDLE. > > however, on both co = chartobjects(1) works just fine. I can't speak for IDLE vs PythonWin but in general case-sensitivity of win32com stuff is related to early vs late Dispatch. If you've explicitly generated proxy modules for the Excel objects (via makepy, EnsureDispatch or whatever) then those are Python modules with case-sensitivity. If you're using dynamic dispatch then Python is simply passing your attribute name along to COM, which isn't case-sensitive, so either case will work. Not sure why IDLE vs PythonWin should make a difference here, but maybe the above explanation sheds some light... TJG From thomas.troeger.ext at siemens.com Fri Jul 18 09:59:49 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Fri, 18 Jul 2008 15:59:49 +0200 Subject: Using Tcl extensions with Python? References: <6f09cdf7-1156-4f41-af5f-c8e5b99eab2d@b1g2000hsg.googlegroups.com> Message-ID: C Martin wrote: > How do you setup a Tcl extension to be accessible through Python? I > understand that I'll have to use native Tcl calls to use it (tk.call() > etc), but I can't figure out where to put the files or how to > initialize them so I can call them. > > The package I would like to use is TkPNG: http://www.muonics.com/FreeStuff/TkPNG/ > > Thanks. ARGH, Tcl!!! ;-) I know that's not the question, but do you know PIL (http://www.pythonware.com/products/pil)? From usenetthrowaway at gmail.com Mon Jul 28 14:24:04 2008 From: usenetthrowaway at gmail.com (Gary) Date: Mon, 28 Jul 2008 19:24:04 +0100 Subject: Proxy server? References: <6f5rteF89muqU2@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote in message news:6f5rteF89muqU2 at mid.uni-berlin.de... > Gary wrote: > For what? A non-transparent proxy, for anonymity purposes only. From guilhem.faure at gmail.com Thu Jul 17 06:20:31 2008 From: guilhem.faure at gmail.com (Guilhem Faure) Date: Thu, 17 Jul 2008 12:20:31 +0200 Subject: Python Pmw ScrollListBox selectioncommand dblclickcommand Message-ID: <7c49f36f0807170320r60ad22cbwbf35b4b91cdfc5b5@mail.gmail.com> Hello everybody, I try to use Pmw library -> ScrollListBox. If I take the example of the reference web site (see below, I just quote the minimal code to launch, I note by <----- the line which are not execute when I click) It works, except selectioncommand and dblclickcommand: associate function doesn't run when I click one or two time. Could you have an idea about that ? Is it about my tried code ? Thank, Guilhem from Tkinter import * import Pmw #from pymol import * class Demo: def __init__(self): parent=Tk() Pmw.initialise(parent) # Create the ScrolledListBox. self.box = Pmw.ScrolledListBox(parent, items=('Sydney', 'Melbourne', 'Brisbane'), labelpos='nw', label_text='Cities', listbox_height = 6, selectioncommand=self.selectionCommand, dblclickcommand=self.defCmd, usehullsize = 1, hull_width = 200, hull_height = 200, ) # Create a group widget to contain the scrollmode options. w = Pmw.Group(parent, tag_text='Scroll mode') w.pack(side = 'bottom', padx = 5, pady = 5) hmode = Pmw.OptionMenu(w.interior(), labelpos = 'w', label_text = 'Horizontal:', items = ['none', 'static', 'dynamic'], command = self.sethscrollmode, menubutton_width = 8, ) hmode.pack(side = 'top', padx = 5, pady = 5) hmode.invoke('dynamic') vmode = Pmw.OptionMenu(w.interior(), labelpos = 'w', label_text = 'Vertical:', items = ['none', 'static', 'dynamic'], command = self.setvscrollmode, menubutton_width = 8, ) vmode.pack(side = 'top', padx = 5, pady = 5) vmode.invoke('dynamic') buttonBox = Pmw.ButtonBox(parent) buttonBox.pack(side = 'bottom') buttonBox.add('yview', text = 'Show\nyview', command = self.showYView) buttonBox.add('scroll', text = 'Page\ndown', command = self.pageDown) buttonBox.add('center', text = 'Center', command = self.centerPage) # Pack this last so that the buttons do not get shrunk when # the window is resized. self.box.pack(fill = 'both', expand = 1, padx = 5, pady = 5) # Do this after packing the scrolled list box, so that the # window does not resize as soon as it appears (because # alignlabels has to do an update_idletasks). Pmw.alignlabels((hmode, vmode)) def sethscrollmode(self, tag): self.box.configure(hscrollmode = tag) def setvscrollmode(self, tag): self.box.configure(vscrollmode = tag) def selectionCommand(self): print "toto" # <----------- doesn t run !!! def defCmd(self): print "toto2" # <----------- doen t run !!! def showYView(self): print self.box.yview() def pageDown(self): self.box.yview('scroll', 1, 'page') def centerPage(self): top, bottom = self.box.yview() size = bottom - top middle = 0.5 - size / 2 self.box.yview('moveto', middle) Demo() -------------- next part -------------- An HTML attachment was scrubbed... URL: From circularfunc at gmail.com Sun Jul 6 19:37:24 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 6 Jul 2008 16:37:24 -0700 (PDT) Subject: how are strings immutable in python? References: Message-ID: <337db7c6-0fc9-465e-b780-322c3a5cf8da@y38g2000hsy.googlegroups.com> so why would you ever want mutability? seems very counterintuitive and unreliable. From aaron.hildebrandt at gmail.com Mon Jul 21 13:30:38 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Mon, 21 Jul 2008 10:30:38 -0700 (PDT) Subject: Error importing modules with mod_python Message-ID: I've installed mod_python, and everything seems to be working, but it fails when I try to import another file into the file that's actually producing the output. I have these lines at the top of index.py: from mod_python import apache from storylab import * ... and in the directory where index.py resides (/htdocs/python/), I have a directory called "storylab". Inside that directory is __init__.py. When I try to execute /htdocs/python/index.py, I get the following error: --- MOD_PYTHON ERROR ProcessId: 828 Interpreter: 'localhost' ServerName: 'localhost' DocumentRoot: 'C:/htdocs' URI: '/python/index.py' Location: None Directory: 'C:/htdocs/python/' Filename: 'C:/htdocs/python/index.py' PathInfo: '' Phase: 'PythonHandler' Handler: 'index' Traceback (most recent call last): File "C:\Python25\lib\site-packages\mod_python\importer.py", line 1537, in HandlerDispatch default=default_handler, arg=req, silent=hlist.silent) File "C:\Python25\lib\site-packages\mod_python\importer.py", line 1202, in _process_target module = import_module(module_name, path=path) File "C:\Python25\lib\site-packages\mod_python\importer.py", line 296, in import_module log, import_path) File "C:\Python25\lib\site-packages\mod_python\importer.py", line 680, in import_module execfile(file, module.__dict__) File "C:\htdocs\python\index.py", line 2, in from storylab import * ImportError: No module named storylab --- What am I doing wrong? Any insight would be greatly appreciated. Thanks, Aaron From arkanes at gmail.com Thu Jul 17 16:03:52 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 17 Jul 2008 15:03:52 -0500 Subject: x, = y (???) In-Reply-To: References: Message-ID: <4866bea60807171303l6430ce58l16f9855fac0fd8b0@mail.gmail.com> On Thu, Jul 17, 2008 at 2:55 PM, kj wrote: > In Erik Max Francis writes: > >>kj wrote: > >>> I just came across an assignment of the form >>> >>> x, = y >>> >>> where y is a string (in case it matters). >>> >>> 1. What's the meaning of the comma in the LHS of the assignment? > >>It's unpacking a 1-tuple: > >> (x,) = y > >>The parentheses here are not necessary and are sometimes left out. > > I still don't get it. If we write > > y = 'Y' > x, = y > > what's the difference now between x and y? And if there's no > difference, what's the point of performing such "unpacking"? > > TIA! >>> y = (1,) >>> y (1,) >>> x, = y >>> x 1 >>> From bruno.desthuilliers at gmail.com Sat Jul 12 15:50:25 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 12 Jul 2008 12:50:25 -0700 (PDT) Subject: Beginner Question : Iterators and zip References: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> Message-ID: On 12 juil, 20:55, moo... at yahoo.co.uk wrote: > Hi group, > > I have a basic question on the zip built in function. > > I am writing a simple text file comparison script, that compares line > by line and character by character. The output is the original file, > with an X in place of any characters that are different. > > I have managed a solution for a fixed (3) number of files, but I want > a solution of any number of input files. > > The outline of my solution: > > for vec in zip(vec_list[0],vec_list[1],vec_list[2]): > res = '' > for entry in zip(vec[0],vec[1],vec[2]): > if len(set(entry)) > 1: > res = res+'X' > else: > res = res+entry[0] > outfile.write(res) > > So vec is a tuple containing a line from each file, and then entry is > a tuple containg a character from each line. > > 2 questions > 1) What is the general solution. Using zip in this way looks wrong. Is > there another function that does what I want zip is (mostly) ok. What you're missing is how to use it for any arbitrary number of sequences. Try this instead: >>> lists = [range(5), range(5,11), range(11, 16)] >>> lists [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15]] >>> for item in zip(*lists): ... print item ... (0, 5, 11) (1, 6, 12) (2, 7, 13) (3, 8, 14) (4, 9, 15) >>> lists = [range(5), range(5,11), range(11, 16), range(16, 20)] >>> for item in zip(*lists): ... print item ... (0, 5, 11, 16) (1, 6, 12, 17) (2, 7, 13, 18) (3, 8, 14, 19) >>> The only caveat with zip() is that it will only use as many items as there are in your shorter sequence, ie: >>> zip(range(3), range(10)) [(0, 0), (1, 1), (2, 2)] >>> zip(range(30), range(10)) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)] >>> So you'd better pad your sequences to make them as long as the longer one. There are idioms for doing this using the itertools package's chain and repeat iterators, but I'll leave concrete example as an exercice to the reader !-) > 2) I am using set to remove any repeated characters. Is there a > "better" way ? That's probably what I'd do too. > Any other comments/suggestions appreciated. There's a difflib package in the standard lib. Did you give it a try ? From michele.simionato at gmail.com Mon Jul 7 23:44:57 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 7 Jul 2008 20:44:57 -0700 (PDT) Subject: Dynamically Changing the Base Class References: <6d60c362-ba17-4414-babd-2cc254526bca@c58g2000hsc.googlegroups.com> Message-ID: <46e28471-54fc-4d15-b136-c17c35326bb3@t54g2000hsg.googlegroups.com> On Jul 7, 8:08?pm, "Adam C." wrote: > Thanks. I think we would want new-style classes, and 6-year-old > patches strike me as maybe a little out of the desired path... so this > really just doesn't work in modern Python? Can you use (multiple) inheritance instead of changing the bases? Alternatively, try using an old-style class, changing the bases and subclassing it inheriting from object too: class NewStyle(OldStyle, object): pass From Samnsparky at gmail.com Thu Jul 10 11:51:34 2008 From: Samnsparky at gmail.com (Sparky) Date: Thu, 10 Jul 2008 08:51:34 -0700 (PDT) Subject: Local User Control Message-ID: I don't know how feasible this is, but is it possible to have users log in to access a local database file in such a way that allows the program to know what user name and password they logged in with? This would involve separate user names and passwords for each user. Thanks for your time and help, Sam From basti.wiesner at gmx.net Mon Jul 14 14:00:29 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Mon, 14 Jul 2008 20:00:29 +0200 Subject: subprocess module References: <2e7f0504-cc1c-4cb6-b2d0-b67b004eca7d@x41g2000hsb.googlegroups.com> <39622612-5e43-45b4-800a-69277c2e2987@79g2000hsk.googlegroups.com> Message-ID: Peter Otten <__peter__ at web.de>: > - communicate() waits for the subprocess to terminate. > - stdout.read() is retried if an EINTR occurs (Not sure when this would > happen). EINTR happens, if the "read" syscall is interrupted by a signal handler. For instance, if a daemon handles SIGUSR to re-read its configuration, and the user issues SIGUSR in exactly that very moment, the daemon wants to read from a pipe, the read attempt would fail with EINTR. Shouldn't happen that often ... -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From subhabrata.iisc at hotmail.com Sat Jul 12 06:16:22 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Sat, 12 Jul 2008 03:16:22 -0700 (PDT) Subject: Use of index Message-ID: Dear All, I have a small question. If I have code line like the following: a1="God" a2="God is always great" a3=a2.index(a1) a4=a2.find(a1) a5=a2.split() a6=a5.index(a1) a7=a5.find(a1) # Invalid as find is applicable only in string but not in list. if a4>-1: print "God may be always great" -------------------------------------------------------------- Now, my q is can we use index like find? Regards, Subhabrata. From bruno.desthuilliers at gmail.com Sat Jul 12 14:35:01 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 12 Jul 2008 11:35:01 -0700 (PDT) Subject: why is "self" used in OO-Python? References: Message-ID: <00530f42-d086-4449-a6ca-7a9a65903d10@m3g2000hsc.googlegroups.com> On 12 juil, 18:32, ssecorp wrote: > I first learned about OO from Java. > > I much prefer to program in Python though. > > However I am consufed about 2 things. > > 1. Why do I have to pass self into every method in a class? You mean "declare self as the first argument", I assume ? This has been explained many times here. Anyway: the point is that what you define is not a method, but a function. This function needs to have a way to get at the instance on which it's called, and the simplest way to do so is to use the common way: passing it as an argument. This avoids having to have two different constructs - functions and methods - when one is enough. > Since I am > always doing why cant this be automated or abstracted away? This could, probably, but you'd had complexity, break uniformity and loose some interesting features of the language. > > 2. self.item instead of getters and setters. I thought one of the main > purposes of OO was encapsulation. I don't know if it's "one of the main purposes", but you're missing the point: you have to use explicit getters and setters in Java because Java doesn't have any support for computed attributes. In Python, the object.attribute syntax doesn't mean you are directly accessing an instance attribute. First because lookup rules are more complex than that (not only the instance, but also it's class and it's class parents are looked up), then because there are several ways to hook into these lookup rules. Given that you can decouple the interface (looks like an access attribute) from the implementation (anything from an instance attribute to a method call in a distantly related class, possibly including a network connection and database access), you just don't need explicit getters and setters when directly accessing an instance attribute is enough (and that's more than often the case). > Doesn't messing with internal object- > representations break this? It does, indeed, but it's sometimes necessary (as a matter of fact, there are ways to get at private attributes even in Java). Anyway, this is unrelated to your above question about getters and setters. > I see how the getters and setters could be just visual clutter and you > have to add them to every class so it is annoying a bit in the same > way as self described above. > However I feel like I want getters and setters when I write classes, > not sure of the advantages/disadvantages though. Unless you need to do something else than accessing an instance attribute, explicit getters and setters in Python are a pure waste of time for you, anyone using your code, and even the computer. > Only looking at the documentation of a Python-class, will internal > representations be provided? For which definition of "internal representation" ? > If I have a class: > > class Stack(object): > def __init__(self, *items): > self.stack = list(items) > > def append(self, item): > self.stack.append(item) # OT : canonically, it's stac.push(item), not stack.append(item) > def pop(self): > return self.stack.pop() > > I can get to see the stack with var.stack but then why even implement > append when I could do self.stack.append(x) etc. Because you may want to change the implementation, as usual. But you shouldn't expose stack as part of your API. The convention in Python is to name implementation stuff with a leading underscore. This a *very* strong convention saying "don't mess with this unless you know exactly what you're doing and are willing and able to take full responsability if you break anything or if your code breaks when I'll change my class implementation". So just rename 'stack' to '_stack', and anyone using your class will ignore it unless they have a pretty good reason to mess with it and are ok to suffer the potential consequences. > That way you could do away with OO completely. You could, but what would be the point ? Why would I mess with implementation when I get what I need using the API ? > So why let people > access the main attribute but not let them manipulate it? You just can't stop them from manipulating it if they really want, you know. Don't worry, whatever the language, if someone want to mess with implementation, he will find a way. > Makes more sense to draw the line to not access any attributes at all > no? No. Most programmers are of at least median intelligence, and won't even have a look at your implementation as long as they can - because they don't want to have to worry about implementation. As long as you clearly marked something as being "implementation, don't touch", and provided a sound API, then you've done your job. I know this can sound disturbing when coming from the ultra-dogmatic chains-and-bondage world of Java, but from experience (from dozens of years of thousands of programmers), Python's pragmatic approach JustWorks(tm). From tjreedy at udel.edu Tue Jul 8 22:21:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 08 Jul 2008 22:21:31 -0400 Subject: (silly?) speed comparisons In-Reply-To: References: Message-ID: mk wrote: > Out of curiosity I decided to make some speed comparisons of the same > algorithm in Python and C++. Moving slices of lists of strings around > seemed like a good test case. If you use Python to, in effect, call well-written C functions, and most of the computation time is spent in the C functions, then the total time may be less than using C++ to call C or C++ functions that have not been as heavily optimized. (Python is nearly 2 decades old, and several people have perused the code base looking for speedups.) From samwyse at gmail.com Thu Jul 10 15:38:27 2008 From: samwyse at gmail.com (samwyse) Date: Thu, 10 Jul 2008 12:38:27 -0700 (PDT) Subject: Problems Returning an HTTP 200 Ok Message References: <1cf880cc-2036-42dc-8217-d52a714c1710@a70g2000hsh.googlegroups.com> Message-ID: <9bc65e72-be16-4f73-9dfb-6ddeaae34c21@m73g2000hsh.googlegroups.com> On Jul 10, 1:50?pm, Guy Davidson wrote: > Hi Folks, > > I'm having some issues with an small socket based server I'm writing, > and I was hoping I could get some help. > > My code (attached below) us supposed to read an HTTP Post message > coming from a power meter, parse it, and return a proper HTTP 200 Ok > message. The problem is that the socket fails to send the entire > message as one message, creating a fragmented message which the power > meter then fails to read and accept. > > Is there any way to force the socket to send the entire message at > once? Am I doing anything wrong? Is there an easier way to implement > this functionality? By 'message', do you mean a single IP datagram? In general, the answer is no. Each call to 'connection.send()' will (in general, see the next paragraph) transmit as much data as will fit into a single IP datagram, given the current MTU for the transmission circuit. The fact that you're calling it in a loop indicates that the data being sent may be larger than will fit into a datagram. Or, by 'message', do you mean a single TCP segment? Again, the answer is no. Your network stack will try to make the TCP segments the right size to fit within a single IP datagram, leading to the same result as above. From your description, I get the feeling that your power meter has a broken network stack, and you're trying to program around it. You need to repair the meter. From pavlovevidence at gmail.com Tue Jul 29 04:37:45 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 01:37:45 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> Message-ID: <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> On Jul 28, 8:15 pm, Steven D'Aprano wrote: > On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: > > On Jul 28, 10:00 am, Steven D'Aprano > cybersource.com.au> wrote: > >> Cutting to the crux of the discussion... > > >> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: > >> > I want something where "if x" will do but a simple explicit test > >> > won't. > > >> Explicit tests aren't simple unless you know what type x is. If x could > >> be of any type, you can't write a simple test. Does x have a length? Is > >> it a number? Maybe it's a fixed-length circular length, and the length > >> is non-zero even when it's empty? Who knows? How many cases do you need > >> to consider? > > > Use case, please. I'm asking for code, not arguments. Please give me a > > piece of code where you can write "if x" that works but a simple > > explicit test won't. > > I gave you a piece of code, actual code from one of my own projects. If > you wouldn't accept that evidence then, why would you accept it now? I would accept as "evidence" something that satisfies my criteria, which your example did not: it could have easily (and more robustly) been written with a simple explicit test. I am looking for one that can't. You keep bringing up this notion of "more complex with no benefit", which I'm simply not interested in talking about that at this time, and I won't respond to any of your points. I am seeking the answer to one question: whether "if x" can usefully do something a simple explicit test can't. Everyone already knows that "if x" requires fewer keystrokes and parses to fewer nodes. Carl Banks From M8R-yfto6h at mailinator.com Sun Jul 6 17:55:35 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Sun, 6 Jul 2008 14:55:35 -0700 Subject: how are strings immutable in python? References: Message-ID: "ssecorp" wrote in message news:a08a6406-6d54-402c-9271-9d1940f3dff6 at z72g2000hsb.googlegroups.com... > so if strings were mutable and i did > a = b = "foo" > and then did > a += "bar" > then a and b would be foobar? This can be demonstrated with a list of characters, which *is* mutable: >>> a = b = list('foo') >>> a += list('bar') >>> a ['f', 'o', 'o', 'b', 'a', 'r'] >>> b ['f', 'o', 'o', 'b', 'a', 'r'] --Mark From jim.hefferon at gmail.com Tue Jul 1 19:55:28 2008 From: jim.hefferon at gmail.com (Jim) Date: Tue, 1 Jul 2008 16:55:28 -0700 (PDT) Subject: convert unicode characters to visibly similar ascii characters References: Message-ID: <17d4c282-8606-4d29-9e71-d34f5e6d13bb@m44g2000hsc.googlegroups.com> Peter Bulychev wrote: > I want to convert unicode character into ascii one. You have to make some arbitrary choices of what to translate. Based on some materials on effbot's site, and a recipe, I made ftp://alan.smcvt.edu/hefferon/unicode2ascii.py which has at least some of what you are looking for. $ grep HYPHEN unicode2ascii.py u'\N{SOFT HYPHEN}':u'-', u'\N{HYPHEN}':u'-', u'\N{NON-BREAKING HYPHEN}':u'-', u'\N{SOFT HYPHEN}': '-', No doubt I have some terrible gaffes and some things missing. Corrections appreciated. Jim From george.sakkis at gmail.com Thu Jul 3 19:24:23 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 3 Jul 2008 16:24:23 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> <7db52b03-7a8a-40c4-b3cb-f6dccd273b90@59g2000hsb.googlegroups.com> Message-ID: On Jul 3, 5:49?pm, Mensanator wrote: > On Jul 3, 2:52?pm, Terry Reedy wrote: > > > Worthless to you, worthwhile to me. ? > > The OP's opinion is the only one that matters. I bet the OP doesn't know (or care) what gmpy is. > What do you suppose > is the percentage of posts on this newsgroup by those using 3.0? Taking into account 2.6 too (we're not talking about only 3.0 here), probably not much less than those who even know what is gmpy, let alone dismiss a beta Python release because their obscure pet module is not available yet. You will probably sound less negative if you refrain from projecting your own very specialized needs to those of the average pythonista. George From goldspin at gmail.com Mon Jul 28 00:43:52 2008 From: goldspin at gmail.com (Henry Chang) Date: Sun, 27 Jul 2008 21:43:52 -0700 Subject: Command line arguements In-Reply-To: <73045cca0807272113y397de468yfcb00ffbbec7990a@mail.gmail.com> References: <73045cca0807272113y397de468yfcb00ffbbec7990a@mail.gmail.com> Message-ID: try optparse :) http://docs.python.org/lib/module-optparse.html On Sun, Jul 27, 2008 at 9:13 PM, aditya shukla wrote: > Hello folks ,I have a program in which a text file is generated as an > output > eg > > C:\prog\ prog -x test.txt > Right now whenever i have to read the test file i have to put its name > manually in my code. > eg > f=open("c:\\prog\\test.txt","r") > > How ever i want to add the name of the test file dynamically to my program > ie , if every time i give > > C:\prog\ prog -x test.txt > The filename (test.txt) automatically comes in > f=open("c:\\prog\\test.txt","r") > > C:\prog\ prog -x file1.txt > f=open("c:\\prog\\file1","r") > > > in other words i do not want to do hard code the name of the file in my > code every time i need to read it. > > I was reading about the sys module and i guess sys.argv would take the > input from the command line whenever i run the python script . > > Please guide me in the right direction on how to tackle the problem. > > Thanks in advance > > Aditya > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wmcbrine at users.sf.net Mon Jul 28 14:59:13 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Mon, 28 Jul 2008 18:59:13 GMT Subject: Questions on 64 bit versions of Python References: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> <488cbeeb$0$17104$9b622d9e@news.freenet.de> Message-ID: <5Gojk.254$wS4.153@trnddc03> On Sun, 27 Jul 2008 20:31:07 +0200, Martin v. L?wis wrote: > Originally, AMD called it x86-64, and later renamed it to AMD64. Intel > originally implemented it under the name EM64T (for Extended Memory 64 > Technology), and now calls the architecture Intel 64. I hadn't heard "Intel 64" before. That's a bit nervy, isn't it? Plus it seems to conflict with their own use of "IA-64" (Intel Architecture 64) for the Itanium (vs. "IA-32" for traditional x86). -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From kurdayon at yahoo.com Tue Jul 1 17:24:48 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Tue, 1 Jul 2008 14:24:48 -0700 (PDT) Subject: How to make a function associated with a class? References: <69e26f9b-2f00-4318-9bc5-6aa94e141bca@59g2000hsb.googlegroups.com> <4d7cf477-e791-4122-bc20-0dbd1a16bc12@j22g2000hsf.googlegroups.com> Message-ID: <0d9c534b-8720-4363-b3e5-eb546dd3637c@8g2000hse.googlegroups.com> On Jul 1, 5:01 pm, "bruno.desthuilli... at gmail.com" wrote: > On 1 juil, 22:43, Kurda Yon wrote: > > > > > Hi, > > > I have a class called "vector". And I would like to define a function > > "dot" which would return a dot product of any two "vectors". I want > > to call this function as follow: dot(x,y). > > > Well, I can define a functions "dot" outside the class and it works > > exactly as I want. However, the problem is that this function is not > > associated with the class (like methods a method of the class). > > > For example, if I call "x.calc()" or "y.calc()", python will execute > > different methods if "x" and "y" belongs to different classes. I want > > to have the same with my "dot" function. I.e. I want it calculates the > > dot product ONLY IF the both arguments of that function belong to the > > "vector" class. > > > Is it possible? > > You don't need to make dot() a method of your Vector class to have > this behaviour, and making it a method of the Vector class isn't > enough to have this behaviour. > > The simplest solution would be: > > class Vector(object): > def dot(self, other): > if not isinstance(other, type(self)): > raise TypeError("can only calculate the dot product of two > vectors") > # do the job here and return what's appropriate > > Now since it's a binary operator, you might as well implement it as > such: > > class Vector(object): > def __mul__(self, other): > if not isinstance(other, type(self)): > raise TypeError("can only calculate the dot product of two > vectors") > # do the job here and return what's appropriate > > Then use it as doproduct = vector1 * vector2 > > HTH As far as I understood, In the first case, you gave, I need to call the function as follows "x.dot(y)". In the second case I need to call the function as follows "x*y". But I want to call the function as follows "dot(x,y)". By the way, "type(self)" returns the name of the class to which the "self" belongs? Does "instance" return "true" if the first argument belongs to the class whose name is given in the second argument? From aspersieman at gmail.com Thu Jul 24 04:10:29 2008 From: aspersieman at gmail.com (Aspersieman) Date: Thu, 24 Jul 2008 10:10:29 +0200 Subject: Autocompletion and Interactive Tables in a Python IDE In-Reply-To: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> References: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Message-ID: <488838F5.20803@gmail.com> Anthony wrote: > Hi, I'm a FoxPro programmer, but I want to learn python before it's > too late. I do a lot of statistical programming, so I import SPSS > into python. In my opinion, the best features of Visual FoxPro 9.0 > were: > a) Intellisense (tells you what classes/methods are available and what > variables go into a function) > b) Code Completion (guesses your code after four letters) > c) Data-Orientation; multiple data sessions can be open, data can be > viewed easily > > Python's IDLE has only half of the first of these features. I did a > lot of searching and found the PyDev extensions for Eclipse's Python > IDE, and found that they've got Intellisense. I'm still missing b and > c, and am getting extremely frustrated programming so slowly.. > > So two questions: > Is there any package, gui, IDE, anything that will do FoxPro-style > code completion? If it works in Eclipse, even better.. > I can't find a good screenshot, but here's a better description: > You type "BROW" and it pops up a window that says "BROWSE" ..at this > point if you hit enter it completes the word.. > > and > > How can I view open SPSS data in one of the Python GUIs? Again, > Eclipse would be the preference. > Here's an example of how I'd like to browse the data: > http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=vfptoolkit_figure02.tif > I don't want to have to switch back and forth between Python and SPSS > while I'm programming; I just want to stay in one of them.. > > What can I do? I feel extremely inefficient when I don't have these > three features.. > > Thanks in advance. > -- > http://mail.python.org/mailman/listinfo/python-list > > You might want to try vim. It has a steep learning curve, but definitely increases productivity _alot_. Here is a tutorial on setting up vim with : 1) Code completion (intellisense) - including tooltips (!!!) 2) Jump between your python code and the python class libraries. 3) Syntax checking 4) A handy source browser 5) Debugging (using pdb) 6) [All the other vim goodies - already included] Above instructions available here http://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/ I have been using the above setup for a while and find it superior to _any_ IDE I've ever worked with. I'm not sure what you mean by 'Data-Orientation' but I'm sure there's a suitable alternative/replacement for it in vim. Regards Nicolaas -- The three things to remember about Llamas: 1) They are harmless 2) They are deadly 3) They are made of lava, and thus nice to cuddle. From s0suk3 at gmail.com Tue Jul 15 09:59:33 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Tue, 15 Jul 2008 06:59:33 -0700 (PDT) Subject: Modify a string's value Message-ID: Hi everyone, I've heard that a 'str' object is immutable. But is there *any* way to modify a string's internal value? Thanks, Sebastian From mensanator at aol.com Thu Jul 3 09:54:58 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 3 Jul 2008 06:54:58 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> Message-ID: On Jul 3, 2:13?am, Bruno Desthuilliers wrote: > Terry Reedy a ?crit : > > > > > Mensanator wrote: > (snip) > >> Lookup "Cartesian Product". > (snip) > >> for a in [True,False]: > >> ? for b in [True,False]: > >> ? ? for c in [1,2,3,4]: > >> ? ? ? print 'combined settings:',a,'\t',b,'\t',c > > > This has been added to itertools at least for 2.6/3.0 > > Great ! Well, it will be great at some point in the future when Python 2.6/3.0 have actually been released and third party extensions such as gmpy have caught up. Until then, such solutions are worthless, i.e., of no value. From socyl at 987jk.com.invalid Tue Jul 29 17:31:01 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 21:31:01 +0000 (UTC) Subject: static variables in Python? References: Message-ID: In Larry Bates writes: >kj wrote: >> Yet another noob question... >> >> Is there a way to mimic C's static variables in Python? Or something >> like it? The idea is to equip a given function with a set of >> constants that belong only to it, so as not to clutter the global >> namespace with variables that are not needed elsewhere. >> >> For example, in Perl one can define a function foo like this >> >> *foo = do { >> my $x = expensive_call(); >> sub { >> return do_stuff_with( $x, @_ ); >> } >> }; >> >> In this case, foo is defined by assigning to it a closure that has >> an associated variable, $x, in its scope. >> >> Is there an equivalent in Python? >> >> Thanks! >> >> kynn >First names in Python are just that, names that point to objects. Those objects >can contain any type of information including other objects. They are NOT >buckets where things are stored. >1) Names (variables in Perl/C) defined within a Python function are placed in >its local namespace. They are not visible in the global namespace. >2) Yes you can have a local name point to a global. This is often used in >classes with attributes because looking up local is somewhat quicker than >looking up the class attribute. >def foo(): > x = expensive_call > return do_stuff_with(x()) Maybe I'm missing your point, the goal is to have a "runtime constant" associated with the function. In the your definition of foo, expensive_call gets called every time that foo gets called; this is what I'm trying to avoid! Maybe it's easier to see what I mean with JavaScript: function foo() { if (foo.x === undefined) foo.x = expensive_call(); return do_stuff_with(foo.x); } Here, expensive_call is called only once (assuming it never returns undefined). OK, I guess that in Python the only way to do what I want to do is with objects... kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From kay.schluehr at gmx.net Sun Jul 20 01:13:34 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 19 Jul 2008 22:13:34 -0700 (PDT) Subject: Best Python packages? References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> <17861f55-8ad1-4703-ad22-838675f2afc4@w1g2000prk.googlegroups.com> <86b446d2-0d11-4410-bf89-a2a05fac81b2@s50g2000hsb.googlegroups.com> Message-ID: <086cffec-44a8-4eac-ac67-f9ae4f30a61b@d77g2000hsb.googlegroups.com> On 20 Jul., 05:54, "Python Nutter" wrote: > I think the hidden gems in multimedia/game production are Pyglet and > Rabbyt. Whereas PyGame is the older api, its large and bloated and has > of course a heavy dependency on SDL. Pyglet and Rabbyt are > lightweight, efficient, have some amazing functions and hit native > OpenGL in all the major OS distributions and Bruce The Presentation > Tool utilizes the former to take on MS PowerPoint to show what you can > do besides games =) > > Pyglet:http://pyglet.org/ > Rabbyt:http://matthewmarshall.org/projects/rabbyt/ > Bruce The Presentation Tool:http://code.google.com/p/bruce-tpt/ > > Cheers, > PN > > > > > In the original post you asked for "hidden gems" and now it seems you > > just want to know about Madonna or Justin Timberlake. > > > Maybe a look on this collection helps > > >http://wiki.python.org/moin/UsefulModules > > -- > >http://mail.python.org/mailman/listinfo/python-list Maybe someone starts a blog with the title "Hidden Pythons"? Just one short remark about Python game toolkits. The single reason I won't use them is browser accessibility. It doesn't matter to me where Python scripts are running but less so where applications are executed. Right now I'm stuck with AS3/Flash. Given Adobes recent OSS commitments and PyPys efforts in translating RPython to several backends I'm not too pessimistic that we'll see Python in the Flashplayer in a year or two from now. From claird at lairds.us Thu Jul 3 22:02:29 2008 From: claird at lairds.us (Cameron Laird) Date: Fri, 4 Jul 2008 02:02:29 +0000 Subject: Testing for an empty list References: <18268092.post@talk.nabble.com> Message-ID: In article , Matthew Fitzgibbons wrote: >Alexnb wrote: >> Okay this is a simple question I just don't know how. If I have a list, say: >> >> funList = [] >> >> and after a while something possible should have been appended to it, but >> wasn't. How can I test if that list is empty. > >if not funList: > do_something() . . . It's also perfectly legitimate--and arguably even more precise--to write if funList == []: do_something() From bignose+hates-spam at benfinney.id.au Mon Jul 7 03:14:10 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 07 Jul 2008 17:14:10 +1000 Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> <6ddj74F21uhjU1@mid.individual.net> Message-ID: <874p72xj25.fsf@benfinney.id.au> TP writes: > Peter Pearson wrote: > > > When you tell python "print '\033[30;44m foo \033[0m'", python > > interprets the "\033" as a single character. > > So, the python print command *can* interpret these 4-character as a > single character. Not "interpret", no. It's more accurate to say that the Python *compiler* will translate "\033" within a string literal into a single character in the compiled executable byte code. That is, the input to the Python interpreter will not have "\033" in the string literal at all, but instead a single character produced by the Python compiler at that point in the byte code. > It would be odd if there were no possibility to do the same thing > when the characters are (i) stored in a python variable, or (ii) > come from the environment variables. Since those are not the input to the Python compiler, they can't be translated this way. -- \ ?You know I could rent you out as a decoy for duck hunters?? | `\ ?Groucho Marx | _o__) | Ben Finney From M8R-yfto6h at mailinator.com Tue Jul 15 02:39:25 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Mon, 14 Jul 2008 23:39:25 -0700 Subject: Python pack and unpack question References: Message-ID: "joe shoemaker" wrote in message news:mailman.25.1216087716.922.python-list at python.org... > If you have the following: > > data = unpack('>L', sock.recv(4)) > > Does this line of code means that incoming data is big endian and > unpack it to endianess of local machine? If local machine is little > endian, then big endian is automatically converted to little endian > format? > > thank you. Try it: >>> data = unpack('>L','\xaa\xbb\xcc\xdd') >>> data (2864434397L,) >>> hex(data[0]) '0xaabbccddL' >>> data = unpack('>L','\x11\x22\x33\x44') >>> data (287454020,) >>> hex(data[0]) '0x11223344' >>> Yes, it treats the incoming data as big-endian. The Python data type returned varies as needed to hold the value. You'd get the same results on a big-endian and little-endian local machine. How the Python data type is represented internally is an implementation detail and could be anything. -- Mark From gh at ghaering.de Wed Jul 30 09:15:33 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 30 Jul 2008 15:15:33 +0200 Subject: variable expansion with sqlite In-Reply-To: <489059DC.5090501@timgolden.me.uk> References: <489059DC.5090501@timgolden.me.uk> Message-ID: Tim Golden wrote: > marc wyburn wrote: >> Hi I'm using SQlite and the CSV module and trying to create a class >> that converts data from CSV file into a SQLite table. >> >> My script curently uses functions for everything and I'm trying to >> improve my class programming. The problem I'm having is with variable >> expansion. >> >> self.cursor.executemany('INSERT INTO test VALUES (?)', CSVinput) >> >> If CSVinput is a tuple with only 1 value, everything is fine. If I >> want to use a tuple with more than 1 value, I need to add more >> question marks. As I'm writing a class I don't want to hard code a >> specific number of ?s into the INSERT statement. >> >> The two solutions I can think of are; >> using python subsitution to create a number of question marks, but >> this seems very dirty >> or >> finding someway to substitue tuples or lists into the statement - I'm >> not sure if this should be done using Python or SQLite substitution >> though. > > > I do this kind of thing sometimes: > > > a,b,c > 1,2,3 > 4,5,6 > > > > import csv > import sqlite3 > > reader = csv.reader (open ("test.csv", "rb")) > csv_colnames = reader.next () > > db = sqlite3.connect (":memory:") > coldefs = ", ".join ("%s VARCHAR (200)" % c for c in csv_colnames) > db.execute ("CREATE TABLE test (%s)" % coldefs) > > insert_cols = ", ".join (csv_colnames) > insert_qmarks = ", ".join ("?" for _ in csv_colnames) > insert_sql = "INSERT INTO test (%s) VALUES (%s)" % (insert_cols, > insert_qmarks) > > db.executemany (insert_sql, list (reader)) > for row in db.execute ("SELECT * FROM test"): > print row > > > > Obviously, this is a proof-of-concept code. I'm (ab)using > the convenience functions at database level, I'm hardcoding > the column definitions, and I'm making a few other assumptions, but I > think it serves as an illustration. [..] My code would probably look very similar. Btw you don't need to use list() on an iterable to pass to executemany(). pysqlite's executemany() accepts anything iterable (so generators work fine, too). Also, with SQLite you can just skip data type definitions like VARCHAR(200). They're ignored anyway. -- Gerhard From deets at nospam.web.de Wed Jul 23 06:39:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 23 Jul 2008 12:39:56 +0200 Subject: Strange problem .... References: <12fd8ef1-c7e0-470b-ba51-f946d8ea8e26@z6g2000pre.googlegroups.com> Message-ID: <6eog5rF82itrU1@mid.uni-berlin.de> karthikbalaguru wrote: > Hi, > > I am new to python, Kindly suggest to resolve a problem with a python > file. > What does the below error refer to ? > I use Redhat 9.0, python-2.2.2-26, python-devel-2.2.2-26 and > db4-4.0.14-20. > > [root at localhost processor]# Analyzer processorcycle > /usr/local/SDK/bin/../core/bin/processorlib.py:8 > 8: Warning: 'yield' will become a reserved keyword in the future > Traceback (most recent call last): > File "/usr/local/SDK/bin/Analyzer", line 48, in ? > from debuglib import ProcessorInfo > File "/usr/local/SDK/bin/../core/bin/processorlib.py", line 88 > yield ProcessorObjectInfo(child, self.pt) > ^ > SyntaxError: invalid syntax > > Is this error related with the version of python / python-devel that i > use . > Any ideas / tips ? I asked you yesterday why you are under the impression that your script is destined for version 2.2. The above error proves: it is *not*. Why don't you try running it with the installed version 2.4 or whatever fedora ships? Diez From frank at chagford.com Tue Jul 29 07:09:27 2008 From: frank at chagford.com (Frank Millman) Date: Tue, 29 Jul 2008 04:09:27 -0700 (PDT) Subject: Questions about asyncore Message-ID: <5d30aad5-cad7-4e47-aa83-277202c70ae2@z72g2000hsb.googlegroups.com> Hi all I have been using my own home-brewed client/server technique for a while, using socket and select. It seems to work ok. The server can handle multiple clients. It does this by creating a new thread for each connection. Each thread runs its own select loop. I am making some fairly big changes, so I thought I would look at asyncore. I modified my program to use asyncore without much trouble, and it feels nicer. It uses async I/O instead of threading, and it relieves me of having to run my own select loop. I have two questions. They both relate to whether I am using the module as intended. The documentation is rather sparse, and I know from experience that just getting something working is no guarantee that I am getting the full benefit. Firstly, having got asyncore working, I had a look at asynchat. As far as I can see I get very little benefit from using it. I have already set up a 'messaging' protocol between server and client, where all messages consist of 5 digits for the message length, followed by the message. The message consists of a pickled tuple, where the first element is a message identifier, and the rest is the message body. This is how it works in asyncore - def __init__(self,channel): [...] self.msgLength = 0 self.recvData = '' # temporary buffer def handle_read(self): self.recvData += self.recv(8192) if not self.msgLength: if len(self.recvData) < 5: # 1st 5 bytes = msg length return self.msgLength = int(self.recvData[:5]) self.recvData = self.recvData[5:] if len(self.recvData) < self.msgLength: return data = loads(self.recvData[:self.msgLength]) self.recvData = self.recvData[self.msgLength:] self.msgLength = 0 [handle data] This is how I got it working in asynchat - def __init__(self,channel): [...] self.recvData = '' # temporary buffer self.set_terminator(5) self.gotMsgLength = False def collect_incoming_data(self, data): self.recvData += data def found_terminator(self): if self.gotMsgLength: # what follows is the message data = loads(self.recvData) self.set_terminator(5) self.gotMsgLength = False [handle data] else: # what follows is the message length self.set_terminator(int(self.recvData)) self.gotMsgLength = True self.recvData = '' It may be slightly neater, but it does not seem worth adding an extra layer just for that. Does asynchat give me any other benefits I may have overlooked? My second question relates to writing a dummy client program to test the server. I just want to send it some messages and print the responses. Some messages incorporate data extracted from previous responses, so I have to wait for the reply before continuing. I am using asyncore for this as well. However, the only way I can think of to get it working is to run asyncore.dispatcher in a separate thread. To send messages, I append them to a list of messages to be sent. The dispatcher method writable() returns True if there is anything in the list, else False. To receive messages, I run a 'while 1' loop in the main thread, with a sleep of 0.1, until recvData has something in it. It works, but it seems odd to use a separate thread, as one of the points of asyncore is to avoid multi-threading. Is there a better way to write the client program? Thanks Frank Millman From __peter__ at web.de Wed Jul 30 14:15:39 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 Jul 2008 20:15:39 +0200 Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: <2a703a46-75bc-4228-95d1-05a4e6030b40@f63g2000hsf.googlegroups.com> <26c2fe8e-d464-44f0-8e57-3b8e82248691@x35g2000hsb.googlegroups.com> Message-ID: Paul Boddie wrote: > Who wants to be first to submit a patch? ;-) And where? The sourceforge page says "PyXML is no longer maintained." Peter From urizev at gmail.com Sat Jul 5 17:31:23 2008 From: urizev at gmail.com (Urizev) Date: Sat, 5 Jul 2008 23:31:23 +0200 Subject: Singleton implementation problems In-Reply-To: References: <87abgy2kcu.fsf@benfinney.id.au> Message-ID: Great! Thanks everyone for so many references and comments. Lots of doubts have been solved. On Fri, Jul 4, 2008 at 10:33 AM, Peter Otten <__peter__ at web.de> wrote: > Ben Finney wrote: > >> Peter Otten <__peter__ at web.de> writes: >> >>> The problem is the structure of your program. The myset module is >>> imported twice by Python, once as "myset" and once as "__main__". >> >> Yes, this is the problem. Each module imports the other. >> >>> Therefore you get two distinct MySet classes, and consequently two >>> distinct MySet.__instance class attributes. >> >> Are you sure? This goes against my understanding: that 'import foo' >> will not re-import a module that's already been imported, but will >> instead simply return the existing module. > > The main script is put into the sys.modules cache as "__main__", not under > the script's name. Therefore the cache lookup fails. > >> So, I think if one evaluated 'myset is __main__', you'd find they are >> exactly the same module under different names; and therefore that >> there is only *one* instance of 'MySet', again under two names. > > No: > > $ cat tmp.py > import tmp > import __main__ > > print tmp is __main__ > > $ python tmp.py > False > False > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > -- Saludos Juan Carlos "??Viva lo rancio!!" From keith.hughitt at gmail.com Wed Jul 16 10:53:56 2008 From: keith.hughitt at gmail.com (Keith Hughitt) Date: Wed, 16 Jul 2008 07:53:56 -0700 (PDT) Subject: Angle brackets in command-line arguments? Message-ID: <52f1cde3-6240-46b0-8b03-478454e87688@b1g2000hsg.googlegroups.com> Hi all, I am using someone else's script which expects input in the form of: ./script.py arg2 I was wondering if the angle-brackets here have a special meaning? It seems like they specify an input and output stream to use in place of the console. I could not find anything in the python manual or Python in a Nut-shell though. Anyone know? Thanks, Keith From google at mrabarnett.plus.com Sun Jul 20 17:52:34 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 20 Jul 2008 14:52:34 -0700 (PDT) Subject: regex doubts References: <532965.570.qm@web54502.mail.re2.yahoo.com> <504d473e-375a-4111-ae2e-c06aaa37b096@p25g2000pri.googlegroups.com> <5a77d3ef-2313-4f3a-9486-d27136ac0409@b1g2000hsg.googlegroups.com> <0d3a6680-3dce-4353-b389-c0e3b2930847@j1g2000prb.googlegroups.com> Message-ID: <5a8416e9-b436-4ae4-b188-6c66b218e8d3@27g2000hsf.googlegroups.com> On Jul 19, 10:44?pm, John Machin wrote: > On Jul 20, 6:35 am, MRAB wrote: > > > > > On Jul 19, 9:12 pm, John Machin wrote: > > > > On Jul 20, 5:04 am, Fredrik Lundh wrote: > > > > > Mr SZ wrote: > > > > > I am taking a string as an input from the user and it should only > > > > > contain the chars:L , M or R > > > > > > I tried the folllowing in kodos but they are still not perfect: > > > > > > [^A-K,^N-Q,^S-Z,^0-9] > > > > > [L][M][R] > > > > > [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > > > > > > For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. > > > > > try "[LRM]+$" (an L or an R or an M, one or more times, all the way to > > > > the end of the string). > > > > Ummm ... with the default flag settings, shouldn't that be \Z instead > > > of $ > > > ? > > > $ means end of string unless the multiline flag is used, in which case > > it means end of line. > > What manual are you quoting that from? What version of Python are you > using? Can you demonstrate that the pattern "[LRM]+$" will fail to > match the string "L\n"? > I see what you mean: $ does match end of line if the newline is the last character of the string. From rocksportrocker at googlemail.com Thu Jul 17 08:15:13 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 17 Jul 2008 05:15:13 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Message-ID: <09811f1f-c007-49a6-bb13-f92ec9ccc030@a70g2000hsh.googlegroups.com> On 17 Jul., 00:20, Craig Allen wrote: > > I have several classes in our system which need to act like > singletons, they are libraries of data classifications, and other such > libraries of configurations for the system which need to be global. > ... > > Is it pythonic? My approach in this situation is to use the Borg pattern instead of singeltons. This is really pythonic, very simple and usefull. Look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 The german wikipedia shows another solution using metaclasse: http://de.wikipedia.org/wiki/Singleton_(Entwurfsmuster)#Das_Borg-Pattern Greetings, Uwe From tjreedy at udel.edu Sun Jul 13 13:49:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 13 Jul 2008 13:49:52 -0400 Subject: Beginner Question : Iterators and zip In-Reply-To: <0ea30e6f-fcf4-4f39-a091-10b2a2178efd@l64g2000hse.googlegroups.com> References: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> <0ea30e6f-fcf4-4f39-a091-10b2a2178efd@l64g2000hse.googlegroups.com> Message-ID: moogyd at yahoo.co.uk wrote: > What is this *lis operation called? I am having trouble finding any > reference to it in the python docs or the book learning python. One might call this argument unpacking, but Language Manual / Expressions / Primaries / Calls simply calls it *expression syntax. "If the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments; if there are positional arguments x1,...,*xN* , and expression evaluates to a sequence y1,...,*yM*, this is equivalent to a call with M+N positional arguments x1,...,*xN*,*y1*,...,*yM*." See Compound Statements / Function definitions for the mirror syntax in definitions. tjr From nodrogbrown at gmail.com Fri Jul 4 09:10:21 2008 From: nodrogbrown at gmail.com (gordon) Date: Fri, 4 Jul 2008 06:10:21 -0700 (PDT) Subject: origin of error message Message-ID: hi i was trying to create an image using user selection of a file in tix fileselection box ..and i check for exception like below ... from string import split from os.path import basename ... #this is done inside __init__method self.imgsel=FileSelectBox(self.imgSelectFrame) ... def button1Click(self): starttime=datetime.now() self.okButton.configure(state=DISABLED) #will clear canvas self.canvorig.delete(ALL) self.canvresult.delete(ALL) self.resultdisplay.delete(ALL) #image file selection by tix widget self.cursel=self.imgsel.selection.cget("value") print "self.cursel:",self.cursel self.imgsel.selection.selection_clear() #here i want to check if anything is selected by user if self.cursel: ext=split(basename(self.cursel),'.')[1] print "image extn:",ext try: self.selimg=ImageTk.PhotoImage(file=self.cursel) except Exception,inst: print "xceptn::",inst.message self.showresult(inst.message,"red") else: self.selimgtag=self.canvorig.create_image(70,100,image=self.selimg) self.canvorig.update_idletasks() ..... # some other tasks done ..... else: #no file was selected by user print "self.cursel=",self.cursel self.showresult("nothing selected","red") self.okButton.configure(state=NORMAL) endtime=datetime.now() print "total time:", endtime-starttime,"seconds" user is supposed to select an image to be displayed. when i select some file with a non compatible extension (say .zip) i get the following output >>>> self.cursel: F:/docs/python/gui3.zip image extn: zip xceptn:: cannot identify image file total time: 0:00:00.341000 seconds Exception exceptions.AttributeError: "PhotoImage instance has no attribute '_Pho toImage__photo'" in > ignored My belief was that the message 'total time: 0:00:00.341000 seconds ' should have been the last output message .I don't know where the Exception exceptions.AttributeError: etc comes from. Already i am catching the exception when creating PhotoImage .The message 'xceptn:: cannot identify image file' comes from there Can someone help me find how this error msg happens gordon From emen999 at gmail.com Thu Jul 24 06:03:17 2008 From: emen999 at gmail.com (code_berzerker) Date: Thu, 24 Jul 2008 03:03:17 -0700 (PDT) Subject: lxml, comparing nodes References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <6c91a4da-6443-4570-8dd3-01c4ec169bf3@t54g2000hsg.googlegroups.com> > off the top of my head (untested): > > ?>>> def equal(a, b): > ... ? ? if a.tag != b.tag or a.attrib != b.attrib: > ... ? ? ? ? return False > ... ? ? if a.text != b.text or a.tail != b.tail: > ... ? ? ? ? return False > ... ? ? if len(a) != len(b): > ... ? ? ? ? return False > ... ? ? if any(not equal(a, b) for a, b in zip(a, b)): > ... ? ? ? ? return False > ... ? ? return True > > this should work for arbitrary ET implementations (lxmk, xml.etree, ET, > etc). ?tweak as necessary. > > Thanks for help. Thats inspiring, tho not exactly what I need, coz ignoring document order is requirement (ignoring changes in order of different siblings of the same type, etc). I plan to try something like that: def xmlCmp(xmlStr1, xmlStr2): et1 = etree.XML(xmlStr1) et2 = etree.XML(xmlStr2) queue = [] tmpq = deque([et1]) tmpq2 = deque([et2]) while tmpq: el = tmpq.popleft() tmpq.extend(el) queue.append(el.tag) while queue: el = queue.pop() foundEl = findMatchingElem(el, et2) if foundEl: et1.remove(el) tmpq2.remove(foundEl) else: return False if len(tmpq2) == 0: return True else: return False def findMatchingElem(el, eTree): for elem in eTree: if elemCmp(el, elem): return elem return None def elemCmp(el1, el2): pass # yet to be implemented ;) From michele.simionato at gmail.com Fri Jul 11 13:03:55 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 11 Jul 2008 10:03:55 -0700 (PDT) Subject: decorator to prevent adding attributes to class? References: <98c6e83e-4a54-49ce-a32e-f03f5ab97f28@k13g2000hse.googlegroups.com> Message-ID: <6936f3a9-5402-4b41-9d55-315d251c402d@34g2000hsf.googlegroups.com> On Jul 11, 6:38?pm, Robert Bossy > I don't get it. Why use a metaclass? Wouldn't the following be the same, > but easier to grasp: > > class Frozen(object): > ? ? def __setattr__(self, name, value): > ? ? ? ?if not hasattr(self, name): > ? ? ? ? ? raise AttributeError, "cannot add attributes to %s" % self > ? ? ? ?object.__setattr__(self, name, value) This is easier, but it does not stop the user from adding class level attributes: this is the job of the metaclass. If you don't care about class level attributes (including methods, properties, etc) and you are content with restricting only the instance attributes your recipe is fine, yes. From straton at lampsacos.demon.co.uk Fri Jul 18 05:47:36 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 18 Jul 2008 10:47:36 +0100 Subject: % sign in python? In-Reply-To: References: Message-ID: Terry Reedy wrote: > > > korean_dave wrote: >> What does this operator do? Specifically in this context >> >> test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) >> >> (Tried googling and searching, but the "%" gets interpreted as an >> operation and distorts the search results) > > Having seen a number of comments like this over the years (about the > difficulty of searching for symbol meanings), I just started, last > night, a symbol index listing nearly all Python syntax uses of > non-alpha-or-digit ascii symbols. When I finish and upload it > somewhere, I will post an announcement with the link. > > tjr > This will be excellent, Terry. For the present case, perhaps we should also point out that in python 3.0: " Note The formatting operations described here are obsolete and may go away in future versions of Python. Use the new String Formatting in new code." (Taken from the provisional documentation at: http://docs.python.org/dev/3.0/library/stdtypes.html#old-string-formatting ) From you2000too at gmail.com Tue Jul 22 08:17:28 2008 From: you2000too at gmail.com (youtoo) Date: Tue, 22 Jul 2008 05:17:28 -0700 (PDT) Subject: Time Complexity of String Operations References: Message-ID: <8a7fc656-aa91-4609-9502-21be6596e5bf@25g2000hsx.googlegroups.com> On 22 jul, 01:39, "David Wahler" wrote: > On Mon, Jul 21, 2008 at 10:31 PM, youtoo wrote: > > It has been extensively discussed the time complexity (quadratic) of > > string concatenation (due to string's immutability). > > Actually, it is roughly linear, at least for reasonable string lengths: > > $ python -V > Python 2.5.2 > $ python -mtimeit -s "n=1000; a='#'*n" "a+a" > 1000000 loops, best of 3: 1 usec per loop > $ python -mtimeit -s "n=10000; a='#'*n" "a+a" > 100000 loops, best of 3: 5.88 usec per loop > $ python -mtimeit -s "n=100000; a='#'*n" "a+a" > 10000 loops, best of 3: 59.8 usec per loop > > Repeatedly constructing a string by appending a constant number of > characters at a time, however, is quadratic in the final string length > (although VM optimizations may affect this). > > > But what is: > > > == the time complexity of string indexing? Is it constant? > > Yes. > > > == the time complexity of string slicing? Is it O(K) with K the > > slice's length? > > I suspect so, since the time is dominated by the time taken to copy > the data into a new string object. > > > How are strings stored in Python? As arrays? As linked lists? > > Arrays; see Include/stringobject.h in the Python source distribution. > > -- David Thank you very much! yt. From knielsen73 at gmail.com Wed Jul 23 21:32:50 2008 From: knielsen73 at gmail.com (knielsen73 at gmail.com) Date: Wed, 23 Jul 2008 18:32:50 -0700 (PDT) Subject: fill in 3D array References: <3180f972-f2d4-43ff-81de-bcdd0a2ef906@59g2000hsb.googlegroups.com> Message-ID: <49fd3d80-d062-4c39-8274-f0b717486ad4@z66g2000hsc.googlegroups.com> On Jul 23, 9:18 pm, Robert Kern wrote: > knielse... at gmail.com wrote: > > Hi, > > > I am a python newbie, trying to convert my IDL scripts to python. I am > > kind of stuck at the moment. I am reading in a 1-D data file with 2000 > > data points. I need to put them in a 3-D array with size [10,10,20]. I > > have defined the field array as arr = zeros((10,10,20)) but don't know > > how to read the data into the array. > > I assume that you are using numpy. Use numpy.fromfile() and the .reshape() > method. Assuming that your file is ASCII with numbers separated by whitespace: > > import numpy > arr = numpy.fromfile(thefilename, sep=' ').reshape((10,10,20)) > > There is no need, in this case, to create an array before reading the data. > > > Also, I need to extract a slice of a 3-D array and tried a = > > array_name(:,:,20) but that didn't work. > > Python uses [] brackets for indexing, not (). > > arr[:,:,20] > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco Thanks, working like a charm. From rajanikanth at gmail.com Tue Jul 8 20:32:31 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Tue, 8 Jul 2008 17:32:31 -0700 Subject: a simple 'for' question In-Reply-To: <4874017D.2000401@umbc.edu> References: <4874017D.2000401@umbc.edu> Message-ID: <84bdef3c0807081732q33b3bccdvc1d2c361d8c34d80@mail.gmail.com> Hi! Try this for x in folders: open('my/path/way'+x+'myfile.txt','r') Cheers, Raj On Tue, Jul 8, 2008 at 5:08 PM, Ben Keshet wrote: > Hi fans, > > I want to use a 'for' iteration to manipulate files in a set of folders, > something like: > > folders= ['1A28','1A6W','56Y7'] > for x in folders: > print x # print the current folder > f = open('my/path/way/x/my_file.txt', 'r') > ... > > where 'x' in the pathway should iterate over '1A28','1A6W','56Y7'. How > should I identify 'x' in the pathway line as the same x that is iterating > over 'folders'? > > I am getting the following error: > > Traceback (most recent call last): > File > "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Linux\Dock_method_validation\myscripts\test_for.py", line 5, in > > f = open('c:/Linux/Dock_method_validation/x/receptor.mol2', 'r') > IOError: [Errno 2] No such file or directory: > 'c:/Linux/Dock_method_validation/x/receptor.mol2' > > I tired several variations: %x, 'x', "x", etc. all gave me similar errors. > > Thanks for your help, > BK > -- > http://mail.python.org/mailman/listinfo/python-list > -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From callen314 at gmail.com Thu Jul 17 18:26:34 2008 From: callen314 at gmail.com (Craig Allen) Date: Thu, 17 Jul 2008 15:26:34 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> <09811f1f-c007-49a6-bb13-f92ec9ccc030@a70g2000hsh.googlegroups.com> Message-ID: <25516604-0050-4300-b071-4c80dc99a5b7@f1g2000prb.googlegroups.com> On Jul 17, 2:15 am, Uwe Schmitt wrote: > On 17 Jul., 00:20, Craig Allen wrote: > > > > > I have several classes in our system which need to act like > > singletons, they are libraries of data classifications, and other such > > libraries of configurations for the system which need to be global. > > ... > > > Is it pythonic? > > My approach in this situation is to use the Borg pattern instead > of singeltons. This is really pythonic, very simple and usefull. > > Look athttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 > The german wikipedia shows another solution using metaclasse:http://de.wikipedia.org/wiki/Singleton_(Entwurfsmuster)#Das_Borg-Pattern > > Greetings, Uwe thanks uwe, doing some searching I ran into the borg pattern this morning. Definitely relevant. Thanks again and all for the feedback, I feel much reassured about the options when this sort of thing is required. From justin.mailinglists at gmail.com Fri Jul 4 05:59:31 2008 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Fri, 4 Jul 2008 02:59:31 -0700 (PDT) Subject: Newbie, list has no attribute iteritems References: <12caa75c-455a-4ab3-a9c3-4bd191b6965d@k13g2000hse.googlegroups.com> Message-ID: def handle_starttag(self, tag, attrs): # <-- attrs here is a list if 'a' != tag: self.stack.append(self.__html_start_tag(tag, attrs)) # <-- attrs here is still a list return attrs = dict(attrs) # <-- now attrs is a dictionary From sjmachin at lexicon.net Tue Jul 29 22:16:39 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 29 Jul 2008 19:16:39 -0700 (PDT) Subject: static variables in Python? References: <39a2e1f0-b919-4065-8a7a-e3a4b837a347@25g2000hsx.googlegroups.com> <27e92c0a-840a-4341-9185-3d8099ad1e99@w7g2000hsa.googlegroups.com> Message-ID: <913e8721-35b4-4e17-afd9-00c550411c86@u6g2000prc.googlegroups.com> On Jul 30, 11:57 am, "Russ P." wrote: > On Jul 29, 6:33 pm, "Russ P." wrote: > > > > > On Jul 29, 1:40 pm, kj wrote: > > > > Yet another noob question... > > > > Is there a way to mimic C's static variables in Python? Or something > > > like it? The idea is to equip a given function with a set of > > > constants that belong only to it, so as not to clutter the global > > > namespace with variables that are not needed elsewhere. > > > > For example, in Perl one can define a function foo like this > > > > *foo = do { > > > my $x = expensive_call(); > > > sub { > > > return do_stuff_with( $x, @_ ); > > > } > > > > }; > > > > In this case, foo is defined by assigning to it a closure that has > > > an associated variable, $x, in its scope. > > > > Is there an equivalent in Python? > > > > Thanks! > > > > kynn > > > -- > > > NOTE: In my address everything before the first period is backwards; > > > and the last period, and everything after it, should be discarded. > > > If the constant parameters are really only needed in one particular > > function, you can use default function arguments. An added benefit is > > that you can override them with another value if necessary. > > > def fun(x, y, parameter1=0, parameter2=1): > > ... > > I should add that the parameters need not be literal numbers. They can > be computed values as well. They will be computed only once, on the > first pass through the function definition, which I presume is exactly > what you want. > > I think this is the simplest solution to the problem you posed. Here's a real-life example, where the second and third args are run- time constants: def unescape(s, subber=re.compile(r'_x[0-9A-Fa-f]{4,4}_').sub, repl=lambda mobj: unichr(int(mobj.group(0)[2:6], 16)), ): if "_" in s: return subber(repl, s) return s # The if test is just an optimisation that unfortunately the re module doesn't nut out for itself. Cheers, John From winter at biotec.tu-dresden.de Mon Jul 28 06:32:58 2008 From: winter at biotec.tu-dresden.de (Christof Winter) Date: Mon, 28 Jul 2008 12:32:58 +0200 Subject: SOAPpy WSDL problem: namespace of schema and import match error Message-ID: <6f5lirF9vmv1U1@mid.dfncis.de> I am trying to use a webservice with SOAPpy: import SOAPpy intact_wsdl = "http://www.ebi.ac.uk/intact/binary-search-ws/binarysearch?wsdl" intact_serv = SOAPpy.WSDL.Proxy(intact_wsdl) The resulting error message is posted below. If I understand it right, XMLSchema.py complains about the imported XSD namespace being the same as the existing targetNamespace. Perl and Java have no problems with the WSDL document (see sample code at http://www.ebi.ac.uk/~intact/devsite/remote/binarysearch_ws.html) My question: - Is there a problem with the WSDL file being not valid? - Is there a problem with the Python SOAP/WSDL implementation? Any suggestions? Christof > Traceback (most recent call last): > File "testEBIIntactWebservice.py", line 3, in > intact_serv = SOAPpy.WSDL.Proxy(intact_wsdl) > File "/var/lib/python-support/python2.5/SOAPpy/WSDL.py", line 62, in __init__ > self.wsdl = reader.loadFromStream(stream, wsdlsource) > File "/var/lib/python-support/python2.5/SOAPpy/wstools/WSDLTools.py", line 34, in loadFromStream > wsdl.load(document) > File "/var/lib/python-support/python2.5/SOAPpy/wstools/WSDLTools.py", line 260, in load > schema = reader.loadFromNode(WSDLToolsAdapter(self), item) > File "/var/lib/python-support/python2.5/SOAPpy/wstools/XMLSchema.py", line 80, in loadFromNode > schema.load(reader) > File "/var/lib/python-support/python2.5/SOAPpy/wstools/XMLSchema.py", line 1076, in load > tp.fromDom(node) > File "/var/lib/python-support/python2.5/SOAPpy/wstools/XMLSchema.py", line 1177, in fromDom > raise SchemaError, 'namespace of schema and import match' > SOAPpy.wstools.XMLSchema.SchemaError: namespace of schema and import match From toby at tobiah.org Tue Jul 1 15:26:44 2008 From: toby at tobiah.org (Tobiah) Date: Tue, 01 Jul 2008 12:26:44 -0700 Subject: Getting sorting order References: <7cb9ebb7-e722-41e1-bdf2-693954a21b92@j22g2000hsf.googlegroups.com> Message-ID: >>>> master,slave1,slave2=zip(*x) What does the asterisk do here? Thanks ** Posted from http://www.teranews.com ** From dominik.raymann at gmail.com Mon Jul 28 11:54:48 2008 From: dominik.raymann at gmail.com (raymi) Date: Mon, 28 Jul 2008 08:54:48 -0700 (PDT) Subject: Using Python Modules from JAVA Message-ID: <65861251-6a40-44a2-b2e3-48928bb2e1d0@z72g2000hsb.googlegroups.com> Hi all, I'd like to use the pygments syntax highlighting module from within a JAVA application. While I understand how to use Jython to execute a script file or interpret single statements, I don't know how I can use a whole module (i.e. the several files pygments consists of). In order to deploy the application easily I don't want to install Jython or anything else on the system and then call pygment's installer from the shell. I imagine being able to just copy a jar (e.g. jython.jar) and an egg file to the target system and load the module in JAVA. Is this possible? Has anybody any experience with that? Thanks in advance for your help, raymi From tonal at promsoft.ru Wed Jul 30 23:46:14 2008 From: tonal at promsoft.ru (Alexandr N Zamaraev) Date: Thu, 31 Jul 2008 10:46:14 +0700 Subject: Interbase In-Reply-To: References: Message-ID: <48913586.1070602@promsoft.ru> Mike Hjorleifsson wrote: > Has anyone gotten python working with Interbase database platform ? I See KInterbasDB: http://kinterbasdb.sourceforge.net/ From samirg at lorentzsolution.com Fri Jul 11 18:57:14 2008 From: samirg at lorentzsolution.com (Samir Grover) Date: Fri, 11 Jul 2008 15:57:14 -0700 Subject: PyQt QScrollView/QGridLayout question Message-ID: <1215817034.3117.29.camel@localhost.localdomain> folks, I am trying put some user input fields into a scrollable (QScrollView) window. So, I placed a QLabel at 0,0 and QLineEdit at 0,1, next to QLabel. Somehow, results are not what I am expecting.It is placing QLineEdit below QLabel. I am not using designer for this. Please, notice that I convert vbox's box layout into grid layout, so that, I can place QLabel at 0,0 and QLineEdit at 0,1. But it does not do that. any advice on correcting this piece of code will be helpfull. regards, here is how this code looks like: ----- import sys, qt from qt import * class MyDialog(QDialog): def __init__(self,parent = None,name = None,modal = 0,fl = 0): QDialog.__init__(self,parent,name,modal,fl) if not name: self.setName("MyDialog") self.setSizeGripEnabled(1) self.build_window() def build_window(self): toplayout = QGridLayout(self,1,1,11,6,"toplayout") vbMain = qt.QVBox(self) toplayout.addWidget(vbMain, 0, 0) sview = qt.QScrollView(vbMain) vp = sview.viewport() vbox = qt.QVBox(vp) sview.addChild(vbox) vplayout = qt.QGridLayout(vp, 0, 0, 1,-1, 'vpl') vplayout.addWidget(vbox, 0, 0) grid = qt.QGridLayout(vbox.layout(), 2, 2) ll = qt.QLabel('circuit name', vbox) grid.addWidget(ll, 0,0, qt.Qt.AlignLeft) nameinput = qt.QLineEdit(vbox) grid.addWidget(nameinput, 0,1, qt.Qt.AlignLeft) if __name__ == "__main__": app = QApplication(sys.argv) f = MyDialog() f.show() app.setMainWidget(f) app.exec_loop() From babacity4 at gmail.com Thu Jul 24 16:53:12 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:53:12 -0700 (PDT) Subject: www Xxxstash - Amazing porn video collection Message-ID: <1e062eee-4685-4722-bf87-51aaab0b1851@z11g2000prl.googlegroups.com> www xxxstash . >>>>>>>>>>Best Collection of Xxxstash Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE www xxxstash VIDEOS<<<<<<<<<<< . www xxxstash From jr9445 at ATT.COM Thu Jul 17 15:56:27 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 17 Jul 2008 14:56:27 -0500 Subject: properly delete item during "for item in..." In-Reply-To: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> References: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Ratko > Sent: Thursday, July 17, 2008 12:27 PM > To: python-list at python.org > Subject: properly delete item during "for item in..." > > Say you have something like this: > > for item in myList: > del item > > Would this actually delete the item from the list or just decrement > the reference counter because the item in myList is not associated > with name "item" anymore (but still is with myList[itemIndex])? In > other words, is "item" a temporary reference to myList[itemIndex] or > is it actually that reference that myList has stored? > > I am not sure if this question even makes any sense anymore. I've been > using python for years and never had any problems (and I don't now > either) but now that I had to revisit c++/STL, I had to deal about > these issues and was wondering how python does it. > Walk the list backwards when deleting. master = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print "Deletes nothing" a = master[:] print a for i in a: del i print a print print print "Deletes safely from end" a = master[:] print a for i in range(len(a)-1, -1, -1): print i if i % 2 == 0: print " removing ", master[i] del a[i] print " ", a, if master[i] in a: print "Ooops, deleted wrong thing...", print print a print print print "Delete from front. Deletes wrong things and throws an exception..." a = master[:] print a #for i in range(len(a)-1, -1, -1): for i in range(len(a)): print i if i % 2 == 0: print " removing ", master[i] del a[i] print " ", a, if master[i] in a: print "Ooops, deleted wrong thing...", print print a From gnewsg at gmail.com Tue Jul 29 09:40:10 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Tue, 29 Jul 2008 06:40:10 -0700 (PDT) Subject: Questions about asyncore References: <5d30aad5-cad7-4e47-aa83-277202c70ae2@z72g2000hsb.googlegroups.com> Message-ID: On 29 Lug, 13:09, Frank Millman wrote: > Firstly, having got asyncore working, I had a look at asynchat. As far > as I can see I get very little benefit from using it. I have already > set up a 'messaging' protocol between server and client, where all > messages consist of 5 digits for the message length, followed by the > message. The message consists of a pickled tuple, where the first > element is a message identifier, and the rest is the message body. > > This is how it works in asyncore - > > def __init__(self,channel): > [...] > self.msgLength = 0 > self.recvData = '' # temporary buffer > > def handle_read(self): > self.recvData += self.recv(8192) > if not self.msgLength: > if len(self.recvData) < 5: # 1st 5 bytes = msg length > return > self.msgLength = int(self.recvData[:5]) > self.recvData = self.recvData[5:] > if len(self.recvData) < self.msgLength: > return > data = loads(self.recvData[:self.msgLength]) > self.recvData = self.recvData[self.msgLength:] > self.msgLength = 0 > [handle data] > > This is how I got it working in asynchat - > > def __init__(self,channel): > [...] > self.recvData = '' # temporary buffer > self.set_terminator(5) > self.gotMsgLength = False > > def collect_incoming_data(self, data): > self.recvData += data > > def found_terminator(self): > if self.gotMsgLength: # what follows is the message > data = loads(self.recvData) > self.set_terminator(5) > self.gotMsgLength = False > [handle data] > else: # what follows is the message length > self.set_terminator(int(self.recvData)) > self.gotMsgLength = True > self.recvData = '' > > It may be slightly neater, but it does not seem worth adding an extra > layer just for that. Does asynchat give me any other benefits I may > have overlooked? The benefit of asynchat is that it automatically handles the buffering of both input and output. Aside from set/found_terminator() the other two methods you could want to look at are push() and push_with_producer(). push() is a buffered version of asyncore.send(), push_with_producer() accepts a data-producer object you can use in case you want to deal with something other than strings (e.g. files, lists, generators, and so on...). > My second question relates to writing a dummy client program to test > the server. I just want to send it some messages and print the > responses. Some messages incorporate data extracted from previous > responses, so I have to wait for the reply before continuing. > > I am using asyncore for this as well. However, the only way I can > think of to get it working is to run asyncore.dispatcher in a separate > thread. > > To send messages, I append them to a list of messages to be sent. The > dispatcher method writable() returns True if there is anything in the > list, else False. > > To receive messages, I run a 'while 1' loop in the main thread, with a > sleep of 0.1, until recvData has something in it. > > It works, but it seems odd to use a separate thread, as one of the > points of asyncore is to avoid multi-threading. Is there a better way > to write the client program? I'm not sure to understand but I doubt you have to use a thread. If you "have to wait for the reply before continuing" just implement this logic into handle_read() or found_terminator() method. --- Giampaolo http://code.google.com/p/pyftpdlib/ From cs at zip.com.au Thu Jul 24 18:43:55 2008 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 25 Jul 2008 08:43:55 +1000 Subject: Gracefull application exit. Message-ID: <20080724224355.GA30988@cskk.homeip.net> On 24Jul2008 17:30, Robert Rawlins wrote: | > but mind the caveats: | | Thanks Tim, the main caveat which worries me is the fact that it doesn't get | called when being killed by SIGTERM. When I look at implementing the | application as Daemon will cause complications. | The implementation looks nice and is certainly the way I would like to go, | but unless it'll work when killed by sigterm it likely won't be for me. If you catch SIGTERM with the signal module and call sys.exit() they should fire. This all gets harder with threads. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ We _like_ the starter! Wouldn't have it any other way. If it doesn't grind, take it back to the dealer and make them fix it! - Jon N. Steiger, DoD#1038, From Russ.Paielli at gmail.com Mon Jul 28 15:00:49 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jul 2008 12:00:49 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> <6a5506b1-632e-4bf6-b0ce-4d51d1751aa9@i24g2000prf.googlegroups.com> <8b4b11c3-e306-4fe7-82d1-0a948c725f2f@r15g2000prd.googlegroups.com> <239a084f-b73d-4c20-aaaf-bbd05d452638@a2g2000prm.googlegroups.com> <8f675d65-e302-4428-a4bc-f494b230cb59@w1g2000prk.googlegroups.com> <744c27d4-e166-4b3a-9c2c-d4bf1a207fb8@a2g2000prm.googlegroups.com> <553e2d69-7ac7-4b27-bd09-4c35548ce5ec@a3g2000prm.googlegroups.com> Message-ID: <09a41b92-5f4f-4fe6-9592-bb06c17374ca@u12g2000prd.googlegroups.com> On Jul 28, 2:52 am, alex23 wrote: > On Jul 28, 3:07 pm, "Russ P." wrote: > > > What was "suggested in rejected" on the thread you pointed me to was > > not what I suggested. Not even close. Get it, genius? > > *sigh* Clearly I don't have better things to do right now than waste > my time. > > You wrote: > > So why not allow something like this?: > > class MyClass: > > def func( , xxx, yyy): > > .xxx = xxx > > local = .yyy > > The "self" argument is replaced with nothing, but a comma is used as a > > placeholder. > > Philip Eby suggested in the thread I linked to: > > > def .aMethod(arg1, arg2): > > return .otherMethod(arg1*2+arg2) > > In other words, 'self' here is uniformly replaced by an empty string. > > So you honestly see no similarity between your suggestion and the > latter? > > Or do you seriously think that placing an errant comma in the argument > list is somehow substantively different from placing a period before > the function name? Yes, in terms of Python syntax, it's completely different. Forget the empty first argument. As I explained in other posts on this thread, it is not even needed for my proposal. It was just a distraction from the main idea. From steve at REMOVE-THIS-cybersource.com.au Sun Jul 27 04:13:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Jul 2008 08:13:53 GMT Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <009c29cc$0$20302$c3e8da3@news.astraweb.com> On Sun, 27 Jul 2008 10:23:06 +0800, Marcus.CM wrote: > Well after reading some of these posts on "sacred python cow" on the > "self" , i would generally feel that most programmers who started with > C++/Java would find it odd. You know, there are some programmers who haven't started with C++ or Java. > And its true, i agree completely there > should not be a need to put "self" into every single member function. If > you were writing an application and one of your classes adds the same > variable to each of its member function you would do away with it too. Would I? How would I do that here? # untested class FunnyNumber(int): """Silly class that acts like an integer, only one larger.""" def __add__(self, other): return int(self)+1+other def __mul__(self, other): return (self+1)*other def __sub__(self, other): return int(self)+1-other -- Steven From Scott.Daniels at Acm.Org Wed Jul 16 08:40:30 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 16 Jul 2008 05:40:30 -0700 Subject: Python internals In-Reply-To: <008d93af$0$20327$c3e8da3@news.astraweb.com> References: <008ca729$0$20313$c3e8da3@news.astraweb.com> <87hcaq7pja.fsf@benfinney.id.au> <008d93af$0$20327$c3e8da3@news.astraweb.com> Message-ID: Peter Anderson wrote: > Thanks everyone! Just a quick correction - "as the original poster is" > is a bit of a jump that does not reflect my original question. I DO > understand how C and other programming languages handle variables > internally (the bits of actual memory reserved, etc. etc.) and that's > why I asked the question in the first place. > > If Python doesn't do it like C and the others then what mechanism does > it use - it's the sort of issue that helps me understand how the > language is interacting with the underlying operating system/hardware. The easiest way to think of this is that Python uses mostly dictionaries dictionaries for namespaces, and a few places it uses other techniques if there are over-riding considerations that make the dictionaries impractical in particular cases. Python performance would be crippled if their dictionary implementation(s) slowed down, much as C performance would suffer is access to RAM slowed down. --Scott David Daniels Scott.Daniels at Acm.Org From Ilan.i18n at gmail.com Sat Jul 12 14:39:38 2008 From: Ilan.i18n at gmail.com (Ilan) Date: Sat, 12 Jul 2008 11:39:38 -0700 (PDT) Subject: Does omniORBpy 3.2 supports DII? References: <20080710164217.da8448a3.feliphil@gmx.net> Message-ID: <9ac3c420-7be7-4c7b-839c-a5d89eed309e@8g2000hse.googlegroups.com> On 10 ????, 17:42, Wolfgang Keller wrote: > > My apologies if this is not the correct forum for thses quiestions, > > It's not the wrong place to ask, but you're more likely to get answers > from the omniORB mailing lists: > > http://www.omniorb-support.com/mailman/listinfo > > Sincerely, > > Wolfgang Thank you for your response. I already posted this question at that list, i did not get any response yet.. From spython01 at gmail.com Mon Jul 21 15:06:39 2008 From: spython01 at gmail.com (Samir) Date: Mon, 21 Jul 2008 12:06:39 -0700 (PDT) Subject: Converting List of String to Integer Message-ID: Hi Everyone, I am relatively new to Python so please forgive me for what seems like a basic question. Assume that I have a list, a, composed of nested lists with string representations of integers, such that a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] I would like to convert this to a similar list, b, where the values are represented by integers, such as b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] I have unsuccessfully tried the following code: n = [] for k in a: n.append([int(v) for v in k]) print n Does anyone know what I am doing wrong? Thanks in advance. Samir From fredrik at pythonware.com Fri Jul 25 07:08:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 13:08:38 +0200 Subject: scanf in python In-Reply-To: <4889ae4a$0$3726$426a74cc@news.free.fr> References: <4884be5e$0$19722$426a74cc@news.free.fr> <6ek4cgF7hq4vU1@mid.uni-berlin.de> <4884e77a$0$29405$426a74cc@news.free.fr> <4889ae4a$0$3726$426a74cc@news.free.fr> Message-ID: AMD wrote: >> For reading delimited fields in Python, you can use .split string method. > Yes, that is what I use right now, but I still have to do the conversion > to integers, floats, dates as several separate steps. What is nice about > the scanf function is that it is all done on the same step. Exactly like > when you use % to format a string and you pass it a dictionary, it does > all the conversions to string for you. You're confusing surface syntax with processing steps. If you want to do things on one line, just add a suitable helper to take care of the processing. E.g. for whitespace-separated data: >>> def scan(s, *types): ... return tuple(f(v) for (f, v) in zip(types, s.split())) ... >>> scan("1 2 3", int, int, float) (1, 2, 3.0) This has the additional advantage that it works with any data type that provides a way to convert from string to that type, not just a small number of built-in types. And you can even pass in your own local helper, of course: >>> def myfactory(n): ... return int(n) * "!" ... >>> scan("1 2 3", int, float, myfactory) (1, 2.0, '!!!') If you're reading multiple columns of the same type, you might as well inline the whole thing: data = map(int, line.split()) For other formats, replace the split with slicing or a regexp. Or use a ready-made module; there's hardly every any reason to read standard CSV files by hand when you can just do "import csv", for example. Also note that function *creation* is relatively cheap in Python, and since "def" is an executable statement, you can create them pretty much anywhere; if you find that need a helper somewhere in your code, just put it there. The following is a perfectly valid pattern: def myfunc(...): def myhelper(...): ... myhelper(...) myhelper(...) for line in open(file): myhelper(...) (I'd say knowing when and how to abstract things away into a local helper is an important step towards full Python fluency -- that is, the point where you're able to pack "a lot of action in a small amount of clear code" most of the time.) From doug.farrell at gmail.com Wed Jul 9 12:47:32 2008 From: doug.farrell at gmail.com (writeson) Date: Wed, 9 Jul 2008 09:47:32 -0700 (PDT) Subject: Anyone happen to have optimization hints for this loop? References: <43111321-2cc1-4a5e-9189-744131555841@26g2000hsk.googlegroups.com> Message-ID: <080b4c75-ef41-477b-967b-05bf5c445dd1@d1g2000hsg.googlegroups.com> On Jul 9, 12:04?pm, dp_pearce wrote: > I have some code that takes data from an Access database and processes > it into text files for another application. At the moment, I am using > a number of loops that are pretty slow. I am not a hugely experienced > python user so I would like to know if I am doing anything > particularly wrong or that can be hugely improved through the use of > another method. > > Currently, all of the values that are to be written to file are pulled > from the database and into a list called "domainVa". These values > represent 3D data and need to be written to text files using line > breaks to seperate 'layers'. I am currently looping through the list > and appending a string, which I then write to file. This list can > regularly contain upwards of half a million values... > > count = 0 > dmntString = "" > for z in range(0, Z): > ? ? for y in range(0, Y): > ? ? ? ? for x in range(0, X): > ? ? ? ? ? ? fraction = domainVa[count] > ? ? ? ? ? ? dmntString += " ?" > ? ? ? ? ? ? dmntString += fraction > ? ? ? ? ? ? count = count + 1 > ? ? ? ? dmntString += "\n" > ? ? dmntString += "\n" > dmntString += "\n***\n > > dmntFile ? ? = open(dmntFilename, 'wt') > dmntFile.write(dmntString) > dmntFile.close() > > I have found that it is currently taking ~3 seconds to build the > string but ~1 second to write the string to file, which seems wrong (I > would normally guess the CPU/Memory would out perform disc writing > speeds). > > Can anyone see a way of speeding this loop up? Perhaps by changing the > data format? Is it wrong to append a string and write once, or should > hold a file open and write at each instance? > > Thank you in advance for your time, > > Dan Hi Dan, Looking at the code sample you sent, you could do some clever stuff making dmntString a list rather than a string and appending everywhere you're doing a +=. Then at the end you build the string your write to the file one time with a dmntFile.write(''.join(dmntList). But I think the more straightforward thing would be to replace all the dmntString += ... lines in the loops with a dmntFile.write(whatever), you're just constantly adding onto the file in various ways. I think the slowdown you're seeing your code as written comes from Python string being immutable. Every time you perform a dmntString += ... in the loops you're creating a new dmntString, copying in the contents of the old, plus the appended content. And if your list can reach a half a million items, well that's a TON of string create, string copy operations. Hope you find this helpful, Doug From duncan.booth at invalid.invalid Sun Jul 13 16:16:14 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Jul 2008 20:16:14 GMT Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> Message-ID: "Giampaolo Rodola'" wrote: > Thanks, that's what I wanted to know. > I understand that heapq is not that efficient to implement timeouts as > I thought at first. > It would have been perfect if there were functions to remove arbitrary > elements withouth needing to re-heapify() the heap every time. > Thanks for your help anyway. > > There could be suitable functions, but there aren't any. I *think* this would work (untested): def popitem(heap, pos): if pos == 0: return heappop(heap) if pos == len(heap)-1: return heap.pop(pos) res = heap[pos] heap[pos] = heap.pop() heapq._siftup(heap, pos) return res the catch is that _siftup is written in Python whereas the publicly exposed heapq functions are written in C, so although in theory this is 'more efficient' than calling heapify() on the entire heap it may actually be slower. Bottom line though is that heaps aren't really suitable for timeouts. From bronger at physik.rwth-aachen.de Sat Jul 26 03:45:21 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 26 Jul 2008 09:45:21 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> Message-ID: <87fxpxw0ku.fsf@physik.rwth-aachen.de> Hall?chen! Terry Reedy writes: > [...] > > Or the proposal would have to be that 'self' is mandatory for all > programmers in all languages. I think *that* would be > pernicious. People are now free to write the more compact 's.sum = > s.a + s.b + s.c' if they want instead of the 'self' version. And > again, not everyone writes in English. Of course, "self" would have to become a reserved word. You could say that this may break some code, but I don't see much freedom removed from the language. After all, being a German, I still can't write "F?r i in range(10)". ;-) Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From timr at probo.com Mon Jul 21 01:33:18 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 21 Jul 2008 05:33:18 GMT Subject: Python Written in C? References: Message-ID: giveitawhril2008 at gmail.com wrote: > >I'm just learning about Python now and it sounds interesting. But I >just read (on the Wiki page) that mainstream Python was written in C. >That's what I was searching for: Python was written in what other >language? > >See, my concern was something like: OK, if Python is so hot, then, >hopefully someone is writing it in assembly language for each MPU chip >out there. ... No one writes compilers in assembly language. Most people don't even write assemblers in assembly language. >So I was suspecting the Python compiler or interpreter is written in a >REAL language like C#. So, Wiki says it's written in C! It's almost as >if it were an intentional trick...write your own, new language in an >OLD, real world language that is passe. You seem to believe that, because YOU are just learning about Python, that necessarily means that Python itself is new. That is incorrect. Python was originally conceived and developed in 1990. Anders Hejlsberg, who designed C#, was still at Borland at that time, and had not even created Delphi yet. C++ was still many years away from becoming an ISO standard. >I'm not dissing Python, here. Just noting that, if it is written in C, >that throws a curve at me in trying to balance the value of learning >Python vs. some other major language. I would say you have a very strange criteria for deciding whether a language is worth learning. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From vlastimil.brom at gmail.com Fri Jul 25 12:01:07 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 25 Jul 2008 18:01:07 +0200 Subject: Execution speed question In-Reply-To: <4889a36f$1@news2-rz-ap.ethz.ch> References: <4889a36f$1@news2-rz-ap.ethz.ch> Message-ID: <9fdb569a0807250901w6998115atca5e32bf3fb2d29e@mail.gmail.com> 2008/7/25 Suresh Pillai : > ... > I naturally started coding with (2), but couldn't decide on the best data > structure for python. A set seemed ideal for speedy removal, but then I > can't iterate through them with out popping. An ordered list? Some > creative solution with numpy arrays? > > ... Maybe I am missing something, but I'm not sure, where is the problem with non-destructive iterating over a set, e.g.: >>> my_set = set([1,2,3,4,5]) >>> my_set set([1, 2, 3, 4, 5]) >>> for item in my_set: print item, ... 1 2 3 4 5 >>> my_set set([1, 2, 3, 4, 5]) >>> my_set -= set([2,4]) >>> my_set set([1, 3, 5]) >>> Of course, the suitability for your application would depend on other factors too. vbr -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Mon Jul 7 18:40:47 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 08 Jul 2008 08:40:47 +1000 Subject: Emacs/Python Essentials? References: Message-ID: <87prppwc5s.fsf@benfinney.id.au> xkenneth writes: > What does everyone consider essential for emacs python dev? GNU Emacs 22. The 'whitespace-mode' and 'python-mode' are good improvements in that version of Emacs. I've heard good things also about: 'ropemacs' , an Emacs mode for using 'rope', a Python refactoring tool 'ido.el' , an alternative mode for navigating multiple related buffers and files. -- \ ?A society that will trade a little liberty for a little order | `\ will lose both, and deserve neither.? ?Thomas Jefferson, in a | _o__) letter to Madison | Ben Finney From anishchapagain at gmail.com Tue Jul 22 05:59:35 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Tue, 22 Jul 2008 02:59:35 -0700 (PDT) Subject: automating python programs References: Message-ID: <1d39f8f1-80a3-4644-a564-6b26e2206e23@s50g2000hsb.googlegroups.com> On Jul 21, 7:28?pm, "Dan Upton" wrote: > On Mon, Jul 21, 2008 at 2:12 PM, Zach Hobesh wrote: > > Hi, > > > I'm trying to figure out how to run a python program on a schedule, maybe > > every half an hour... ?Is this possible? > > > Thanks! > > > -Zach > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > On Linux, man cron. Hi!! I hope if you have written the Python code in Class and module then you can call the execution of module in main module using yourroot.after(millisecond,moduletobe executed) like, parent_root.after(3000, child1_root.destroy)#will destroy the child1_root module after 3second at this stage in mainmodule. parent_root.mainloop() anish From marcus at internetnowasp.net Mon Jul 28 14:00:54 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Tue, 29 Jul 2008 02:00:54 +0800 Subject: We programming In-Reply-To: <789038.29418.qm@web7906.mail.in.yahoo.com> References: <789038.29418.qm@web7906.mail.in.yahoo.com> Message-ID: <488E0956.8070002@internetnowasp.net> Hi , I hope this doesnt invite flames.....but for webpages i suggest stick with php... I'm outta here.....wooosh.... srinivasan srinivas wrote: > Hi, > Could someone suggest me better python modules for developing web programming related projects like web-pages download and uopload?? > Thanks, > Srini > > > Explore your hobbies and interests. Go to http://in.promos.yahoo.com/groups/ > -- > http://mail.python.org/mailman/listinfo/python-list > > From dsc at ecs.soton.ac.uk Fri Jul 25 07:27:04 2008 From: dsc at ecs.soton.ac.uk (Dave Challis) Date: Fri, 25 Jul 2008 12:27:04 +0100 Subject: Automatically loading and initialising objects from a plugins directory In-Reply-To: References: <488607BC.3040204@ecs.soton.ac.uk> Message-ID: <4889B888.8000600@ecs.soton.ac.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Fredrik Lundh wrote: > so now you're no longer supporting mixins and multiple-level > inheritance? why not just tweak Diez' example a little: > > for name in dir(plugin): > > thing = getattr(plugin, name) > > # make sure this is a plugin > try: > if thing is Plugin: > continue > if not issubclass(thing, Plugin): > continue > except ValueError: # issubclass sucks > continue # not a class > > thing() # probably needs error handling around this > > (I also moved the thing call out of the thing validation part, to allow > you to distinguish between ValueErrors caused by issubclass and errors > caused by things) > > (btw, another approach would be to use a metaclass to make Plugin > classes register themselves on import) > > Thanks, that works much better. I've only been using python a couple of months, so still getting to grips with how it treats classes/subclasses. I'll have a look into metaclasses too, haven't stumbled upon those yet at all. Cheers, Dave - -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ) <>< <>< ( Dave Challis ) ____dsc at ecs.soton.ac.uk_______(___________________________________________ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFIibiHv26GZvAVVFERAgcmAJ4tmC7jp6TTb3Dx2Lw+rKSmJkcSLQCfYFsA e0ZLOf8lQXhqHcz/Me8ok0E= =Qcg7 -----END PGP SIGNATURE----- From benjamin.kaplan at case.edu Mon Jul 14 17:25:27 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 14 Jul 2008 17:25:27 -0400 Subject: Using McMillan Installer, PyInstall or py2exe cross-platform? In-Reply-To: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> References: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> Message-ID: On Mon, Jul 14, 2008 at 12:02 PM, Hartmut Goebel wrote: > Hi, > > has anybody used McMillan Installer, PyInstall or py2exe cross-platform? > > I have a Windows partition with Python installed there, so this would > "only" required working on a different directory and for a different OS. > Since I'm working on Linux, it's awful to boot Windows each time I want to > build a new release. > > Any hint in this area? > > -- > Sch?nen Gru? - Regards > Hartmut Goebel > > Goebel Consult > Spezialist f?r IT-Sicherheit in komplexen Umgebungen > http://www.goebel-consult.de > -- I don't know if this will work, but you can try running them on Wine. I know that python 2.5 works fine right now. > > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hotsexq at gmail.com Fri Jul 18 07:01:03 2008 From: hotsexq at gmail.com (hot) Date: Fri, 18 Jul 2008 04:01:03 -0700 (PDT) Subject: welcome to $500 monthly in onlin jobs jest join him with in all datting in girls frined available Message-ID: <74695ab1-b155-4533-9878-2a35b5ce021a@c2g2000pra.googlegroups.com> welcome to $500 monthly in onlin jobs jest join him with in all datting in girls frined available in all information viset welcome to $500 monthly in onlin jobs jest join him with in all datting in girls frined available in all information viset web http://www.friendfinder.com/go/g775836-pmem http://mountanbikes.blogspot.com/ From josiah.carlson at gmail.com Sat Jul 12 15:16:54 2008 From: josiah.carlson at gmail.com (Josiah Carlson) Date: Sat, 12 Jul 2008 12:16:54 -0700 (PDT) Subject: Doubts about how implementing asynchronous timeouts through a heap References: <80430d47-aac5-4123-8835-0591faf0baed@34g2000hsf.googlegroups.com> Message-ID: <72232593-3138-4bec-9101-16cfa4259461@d45g2000hsc.googlegroups.com> On Jul 9, 4:13?am, "Giampaolo Rodola'" wrote: > Hi, > I'm trying to implement an asynchronous scheduler for asyncore to call > functions at a later time without blocking the main loop. > The logic behind it consists in: > > - adding the scheduled functions into a heapified list > - calling a "scheduler" function at every loop which checks the > scheduled functions due to expire soonest > > Note that, by using a heap, the first element of the list is always > supposed to be the one with the lower timeout. > Here's the code I wrote: > > <--- snippet ---> > import heapq > import time > import sys > > delayed_map = [] > > class delayed_call: > ? ? """Calls a function at a later time. > > ? ? The instance returned is an object that can be used to cancel the > ? ? scheduled call, by calling its cancel() method. > ? ? It also may be rescheduled by calling delay() or reset()} methods. > ? ? """ > > ? ? def __init__(self, delay, target, *args, **kwargs): > ? ? ? ? """ > ? ? ? ? - delay: the number of seconds to wait > ? ? ? ? - target: the callable object to call later > ? ? ? ? - args: the arguments to call it with > ? ? ? ? - kwargs: the keyword arguments to call it with > ? ? ? ? """ > ? ? ? ? assert callable(target), "%s is not callable" %target > ? ? ? ? assert sys.maxint >= delay >= 0, "%s is not greater than or > equal " \ > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"to 0 seconds" % (delay) > ? ? ? ? self.__delay = delay > ? ? ? ? self.__target = target > ? ? ? ? self.__args = args > ? ? ? ? self.__kwargs = kwargs > ? ? ? ? # seconds from the epoch at which to call the function > ? ? ? ? self.timeout = time.time() + self.__delay > ? ? ? ? self.cancelled = False > ? ? ? ? heapq.heappush(delayed_map, self) > > ? ? def __le__(self, other): > ? ? ? ? return self.timeout <= other.timeout > > ? ? def active(self): > ? ? ? ? """Return True if this scheduler has not been cancelled.""" > ? ? ? ? return not self.cancelled > > ? ? def call(self): > ? ? ? ? """Call this scheduled function.""" > ? ? ? ? self.__target(*self.__args, **self.__kwargs) > > ? ? def reset(self): > ? ? ? ? """Reschedule this call resetting the current countdown.""" > ? ? ? ? assert not self.cancelled, "Already cancelled" > ? ? ? ? self.timeout = time.time() + self.__delay > ? ? ? ? if delayed_map[0] is self: > ? ? ? ? ? ? heapq.heapify(delayed_map) > > ? ? def delay(self, seconds): > ? ? ? ? """Reschedule this call for a later time.""" > ? ? ? ? assert not self.cancelled, "Already cancelled." > ? ? ? ? assert sys.maxint >= seconds >= 0, "%s is not greater than or > equal " \ > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"to 0 seconds" %(seconds) > ? ? ? ? self.__delay = seconds > ? ? ? ? self.reset() > > ? ? def cancel(self): > ? ? ? ? """Unschedule this call.""" > ? ? ? ? assert not self.cancelled, "Already cancelled" > ? ? ? ? del self.__target, self.__args, self.__kwargs > ? ? ? ? if self in delayed_map: > ? ? ? ? ? ? if delayed_map[0] is self: > ? ? ? ? ? ? ? ? delayed_map.remove(self) > ? ? ? ? ? ? ? ? heapq.heapify(delayed_map) > ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? delayed_map.remove(self) > ? ? ? ? self.cancelled = True > > def fun(arg): > ? ? print arg > > a = delayed_call(0.6, fun, '0.6') > b = delayed_call(0.5, fun, '0.5') > c = delayed_call(0.4, fun, '0.4') > d = delayed_call(0.3, fun, '0.3') > e = delayed_call(0.2, fun, '0.2') > f = delayed_call(0.1, fun, '0.1') > > while delayed_map: > ? ? now = time.time() > ? ? while delayed_map and now >= delayed_map[0].timeout: > ? ? ? ? delayed = heapq.heappop(delayed_map) > ? ? ? ? try: > ? ? ? ? ? ? delayed.call() > ? ? ? ? finally: > ? ? ? ? ? ? if not delayed.cancelled: > ? ? ? ? ? ? ? ? delayed.cancel() > ? ? time.sleep(0.01) > > > Here comes the questions. > Since that the timeouts of the scheduled functions contained in the > list can change when I reset() or cancel() them I don't know exactly > *when* the list needs to be heapified(). > By doing some tests I came to the conclusion that I need the heapify() > the list only when the function I reset() or cancel() is the *first of > the list* but I'm not absolutely sure about it. > When do you think it would be necessary calling heapify()? > I wrote a short test suite which tests the code above and I didn't > notice strange behaviors but since that I don't know much about the > logic behind heaps I'd need some help. > Thanks a lot in advance. > > --- Giampaolohttp://code.google.com/p/pyftpdlib/ I dug through my old pair heap implementation, did a little hacking on heapq, and wrote a task scheduler system that plugs in to asyncore. To schedule a task, you use: task = asyncore.schedule_task(schedule, delay, callable, *args, **kwargs) Once you have that task object, you can then use: asyncore.reschedule_task(schedule, delay, task) asyncore.abs_reschedule_task(schedule, time, task) ... to reschedule the task into the future (or past). You can also: asyncore.delete_task(schedule, task) ... to completely remove the task from the scheduler. Each one of these operations are O(logn), where n is the number of tasks currently known to the scheduler. To accommodate the new scheduler, asyncore.loop() now has the following call signature. def loop(timeout=30.0, use_poll=False, map=None, count=None, schedule=None, use_schedule=False): To try to help prevent poll_fcn() starvation (in the case of long- running scheduled tasks), the task window execution is set just prior to the poll_fun() call to be now + .01 seconds. That is, window is set, poll_fun() is called (which should handle current I/O operations), and all tasks that are to be completed prior to the end of the task window (now+.01 seconds, set prior to the poll_fun() call). Asyncore objects will not gain a set_scheduler() method, nor will they gain a schedule keyword argument on instantiation. Why? Because the scheduler is not required for socket I/O to work properly. If you want to use the scheduler from your own subclasses, asyncore.(asyncore.scheduled_tasks, ...) should be sufficient. This scheduler can be easily plugged into other systems, and it's likely that I'll add it as an interactive scheduler to sched.py, put the pair heap implementation into collections, and call it good. - Josiah From bearophileHUGS at lycos.com Thu Jul 17 04:15:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 17 Jul 2008 01:15:58 -0700 (PDT) Subject: Getting a unknown word out of a list with no spaces References: <18502758.post@talk.nabble.com> <487EF593.5060505@promsoft.ru> <18503144.post@talk.nabble.com> <487EF7D9.8010400@promsoft.ru> Message-ID: <93164ef9-7079-44db-9ac4-b0a18b0ddf3e@b1g2000hsg.googlegroups.com> On Jul 17, 9:50 am, Alexnb: > how can I test to see if the first char of a string is "<"? I suggest you to try the interactive shell: >>> "hello"[0] 'h' >>> "hello"[0] == "<" False >>> "hello"[0] == "h" True >>> "hello".startswith("h") True Bye, bearophile From rjagodic at gmail.com Thu Jul 17 13:03:31 2008 From: rjagodic at gmail.com (Ratko) Date: Thu, 17 Jul 2008 10:03:31 -0700 (PDT) Subject: properly delete item during "for item in..." References: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> <487F770D.8070405@islandtraining.com> Message-ID: On Jul 17, 9:57 am, mk wrote: > Gary Herron wrote: > > You could remove the object from the list with > > del myList[i] > > if you knew i. HOWEVER, don't do that while looping through the list! > > Changing a list's length will interact badly with the for loop's > > indexing through the list, causing the loop to mis the element following > > the deleted item. > > Jumping into a thread, I know how not to do it, but not how to do it > properly? > > Iterating over a copy may _probably_ work: > > >>> t=['a', 'c', 'b', 'd'] > >>> > >>> for el in t[:]: > del t[t.index(el)] > > >>> t > [] > > However, is it really safe? Defining safe as "works reliably in every > corner case for every indexable data type"? > > Con: suppose the data structure t is really, really big. Just deleting > some items from t temporarily doubles the memory consumption. Would this work (safely) then? It does in my test cases but that of course doesn't prove it works in a general case... for item in myList: myList.remove(item) For dictionaries we can just iterate over values() or items() as opposed to itervalues() or iteritems() since that's technically a copy of values or items in the dict, right? R From john.smith at john-smith.con Fri Jul 4 17:30:54 2008 From: john.smith at john-smith.con (Aloysius Hibblenire-Ozzleridge) Date: Fri, 04 Jul 2008 14:30:54 -0700 Subject: Iphone Going 3G! References: <486cab43$1_2@news.tm.net.my> <20fqou.nq0.19.1@news.alt.net> Message-ID: <8w3konjjs1gg714.040720082231@gazwad.serveftp.com> On Thu, 3 Jul 2008 11:19:39 -0700 relic bogus.relic2 at cjb.net wrote in news:20fqou.nq0.19.1 at news.alt.net... > fizzi wrote: >> For the Iphone lovers out there, > > Wrong group. No weirdos here. The dumb cunt is posting old news too. From gherron at islandtraining.com Tue Jul 29 11:58:13 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 29 Jul 2008 08:58:13 -0700 Subject: Overloaded Functions In-Reply-To: <3070b5ff-0914-4109-841a-ee622e4105a5@27g2000hsf.googlegroups.com> References: <3070b5ff-0914-4109-841a-ee622e4105a5@27g2000hsf.googlegroups.com> Message-ID: <488F3E15.8000308@islandtraining.com> Tim Henderson wrote: > Hi, > > So this may have been asked before but i haven't found the answer by > googling so far. My situation is this: > > I want this structure for my code: > > @overloaded > def sign_auth(secret, salt, auth_normalized): > return __sign_auth(saltedhash_bin(secret, salt), auth_normalized) > > @sign_auth.register(str, str) > def sign_auth(secret_hash_normalized, auth_normalized): > return __sign_auth(qcrypt.denormalize(secret_hash_normalized), > auth_normalized) > > def __sign_auth(secret_hash_bin, auth_normalized): > auth = qcrypt.denormalize(auth_normalized) > aes = AES.new(secret_hash_bin, AES.MODE_CBC) > plaintext = aes.decrypt(auth) > ciphertext = qcrypt.normalize(xor_in_pi(plaintext)) > if debug: > print '\n------sign_auth------' > print qcrypt.normalize(secret_hash_bin) > print qcrypt.normalize(plaintext) > print ciphertext > print '-----sign_auth-------\n' > return ciphertext > > I am using the overloading module from: > http://svn.python.org/view/sandbox/trunk/overload/overloading.py?rev=43727&view=log > > However it doesn't actually support this functionality. Does any one > know of a decorator that does this? It would be really nice to have a > unified interface into the __sign_auth function for the two different > use cases. > Are you aware that you can do this kind of thing yourself, without using a module/decorator. def sign_auth(*args): if len(args) == 3: secret, salt, auth_normalized = args return __sign_auth(saltedhash_bin(secret, salt), auth_normalized) elif len(args) == 2: secret_hash_normalized, auth_normalized = args return __sign_auth(qcrypt.denormalize(secret_hash_normalized), auth_normalized) The checks could be more involved, perhaps checking not jsut the nuimber of args, but their types, and even their values, before calling __sign_auth(...). Gary Herron > Tim Henderson > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Sun Jul 6 16:50:33 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 06 Jul 2008 16:50:33 -0400 Subject: how are strings immutable in python? In-Reply-To: References: Message-ID: Peter Otten wrote: > ssecorp wrote: > >>>>> h = "aja baja" >>>>> h += 'e' >>>>> h >> 'aja bajae' > > The inplace-add operator doesn't mutate the lvalue, it just rebinds it: In Python, neither '=' nor members of the 'op=' family are operators. They all mark *assignment* or *augmented assignment* statements that *all* bind objects to targets. Augmented assignments are, rather obviously, restricted to binding one object to one target. For 'x op= y', if the object originally bound to x is mutable, the arithmetic operation part of the augmented assignment can (should) be implemented by an inplace __i__ special method that (normally, but not necessarily) mutates and returns self to be rebound. Otherwise, the interpreter calls the normal ____ special method (if it exits) that returns a new object to be bound. Thus, '+=' is neither an operator nor is the indicated operation necessarily inplace. Immutable built-in classes do not have __i__ methods. So given that name h is bound to a string, h += 'e' has exactly the same effect as h = h + 'e' which has exactly the same effect as h = h.__add__('e') The same is true for immutable instances of other built-in classes. Terry Jan Reedy From bignose+hates-spam at benfinney.id.au Mon Jul 28 23:20:59 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 29 Jul 2008 13:20:59 +1000 Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> <488e3520$0$16766$426a74cc@news.free.fr> <87myk1iknc.fsf@benfinney.id.au> Message-ID: <87od4hgyuc.fsf@benfinney.id.au> Ben Finney writes: > It has, at least, long ago bought him a place in my kill-file. > Seeing your side of the conversation, I can only confirm that > decision as correct. This should perhaps say "seeing the parts of his communication that leak through by being quoted in others's posts, I can only confirm my decision as correct." -- \ ?Pinky, are you pondering what I'm pondering?? ?Wuh, I think | `\ so, Brain, but wouldn't anything lose its flavor on the bedpost | _o__) overnight?? ?_Pinky and The Brain_ | Ben Finney From kmtracey at gmail.com Fri Jul 18 17:30:30 2008 From: kmtracey at gmail.com (Karen Tracey) Date: Fri, 18 Jul 2008 17:30:30 -0400 Subject: Change in Decimal repr in Python 2.6 Message-ID: I noticed when trying out Python's 2.6b2 release that the repr of Decimal has changed since 2.5. On 2.5: Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import decimal >>> decimal.Decimal(7) Decimal("7") >>> double quotes were used whereas on 2.6b2: Python 2.6b2 (r26b2:65082, Jul 18 2008, 13:36:54) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import decimal >>> decimal.Decimal(7) Decimal('7') >>> single quotes are used. Searching around I see this was done in r60773 with the log message: Fix decimal repr which should have used single quotes like other reprs. but I can't find any discussion other than that. My problem is this breaks a bunch of doctests that were written assuming the prior repr. I can't just update the tests to assume the new single quotes because they are for code that is supposed to run on everything back to Python 2.3. So my question: Is this backwards-incompatible change really necessary and could it be reconsidered? If it's here to stay, is there some straightforward why that I am unaware of to construct tests that use Decimal repr but will work correctly on Python 2.3-2.6? Also, if this is not the right list for this question please let me know where would be more appropriate and I will go there. Thanks for any feedback, Karen -------------- next part -------------- An HTML attachment was scrubbed... URL: From wtanksleyjr at gmail.com Wed Jul 30 14:27:28 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Wed, 30 Jul 2008 11:27:28 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Message-ID: "Jerry Hill" wrote: > william tanksley wrote: > > Here's one example. The others are similar -- they have the same > > things that look like problems to me. > > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" > > I tried doing track_id.encode("utf-8"), but it doesn't seem to make > > any difference at all. > I don't have anything to say about your iTunes problems, but encode() > is the wrong method to turn a byte string into a unicode string. > Instead, use decode(), like this: Awesome... Thank you! I had my mental model of Python turned around backwards. That's an odd feeling. Okay, so you decode to go from raw byes into a given encoding, and you encode to go from a given encoding to raw bytes. Not what I thought it was, but that's cool, makes sense. At first I thought this fixed my problem, but I had to tweak the obvious fix to make it work, and I don't understand why. Fix #1: track_id = track_id.decode('utf-8') track_id = url2pathname(urlparse(track_id).path) That doesn't work -- it produces no error, but the raw bytes appear in the unicode string. Fix #2: track_id = url2pathname(urlparse(track_id).path) track_id = track_id.decode('utf-8') This one appears to work. (Although I can't confirm it for sure, because although all my debug prints are now correct, the overall application fails in the same way it did before, back before I put in debug printfs. I'm going to spend some time assuming that the problem is elsewhere in my code, since at least I definitely fixed one serious problem.) I've got a few questions for Python-XML-Unicode experts... 1. Why does the order of those statements matter? 2. Shouldn't it be more correct to decode BEFORE transforming the string? Why does that kill the decoding? 3. Why is ElementTree dumping raw bytes on me instead of decoding to UTF-8? The XML file has its encoding set to: , so it seems like it should know what codec to use. > Jerry -Wm From maric at aristote.info Thu Jul 31 09:00:27 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 31 Jul 2008 15:00:27 +0200 Subject: Difference between type and class In-Reply-To: <87zlny8cdg.fsf@nokile.rath.org> References: <87myjy2vc6.fsf@nokile.rath.org> <12072cbe-139a-430f-81aa-b64bc31b43e5@e39g2000hsf.googlegroups.com> <87zlny8cdg.fsf@nokile.rath.org> Message-ID: <200807311500.27747.maric@aristote.info> Le Thursday 31 July 2008 14:30:19 Nikolaus Rath, vous avez ?crit?: > oj writes: > > On Jul 31, 11:37?am, Nikolaus Rath wrote: > >> So why does Python distinguish between e.g. the type 'int' and the > >> class 'myclass'? Why can't I say that 'int' is a class and 'myclass' > >> is a type? > > > > I might be wrong here, but I think the point is that there is no > > distinction. A class (lets call it SomeClass for this example) is an > > object of type 'type', and an instance of a class is an object of type > > 'SomeClass'. > > But there seems to be a distinction: > >>> class int_class(object): > > ... pass > ... > > >>> int_class > > > > >>> int > > > > why doesn't this print > > >>> class int_class(object): > > ... pass > ... > > >>> int_class > > > > >>> int > > > > or > > >>> class int_class(object): > > ... pass > ... > > >>> int_class > > > > >>> int > > > > If there is no distinction, how does the Python interpreter know when > to print 'class' and when to print 'type'? > There are some confusion about the terms here. Classes are instances of type 'type', but types are both instances and subclasses of 'type'. This recursivity is the base of the object model. An instance of 'type' is a class (or a new type), but instances of a classes are not. 'type' is a metatype in term of OO. What the means is that int is not a user type but a builtin type, instances of int are not types (or classes) but common objects, so its nature is the same as any classes. The way it prints doesn't matter, it's just the __repr__ of any instance, and the default behavior for instances of type is to return '', but it can be easily customized. >>>[1]: class A(object) : ...: class __metaclass__(type) : ...: def __repr__(self) : return "" ...: ...: >>>[2]: A ...[2]: >>>[3]: type('toto', (object,), {}) ...[3]: -- _____________ Maric Michaud From stochashtic at yahoo.ca Mon Jul 28 10:48:28 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 28 Jul 2008 16:48:28 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <488d86e2$1@news2-rz-ap.ethz.ch> <488dc3eb$1@news2-rz-ap.ethz.ch> Message-ID: <488ddc3c$1@news2-rz-ap.ethz.ch> On Mon, 28 Jul 2008 15:04:43 +0200, Suresh Pillai wrote: > On Mon, 28 Jul 2008 10:44:18 +0200, Suresh Pillai wrote: > >> Since I am doing A LOT of loops over the nodes and the number of nodes >> is also huge, my concern using sets is that in order to iterate over >> the set in each step of my simulation, the set items need to be >> converted to a list every time. So while removal from a set is much >> cheaper than say from a list, what about this conversion overhead in >> order to iterate over the items. > > I could of course use the old trick of using a dictionary with 'None' > values and then using iterkeys(). But I thought sets were supposed to > replace this. So maybe I should be asking a more basic question: is > there any way to iterate over the items in a set other than converting > to a list or using the pop() method. Okay, please consider this my one absolutely stupid post for the year. I'd like to pretend it never happened but unfortunately the web doesn't allow that. Having never used sets, I unfort read something that lead to it, but ... From mal at egenix.com Thu Jul 17 13:55:44 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 17 Jul 2008 19:55:44 +0200 Subject: Converting from local -> UTC In-Reply-To: <41d4ffc7-7fd5-4202-92ea-132c7d4f5cd4@s50g2000hsb.googlegroups.com> References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> <41d4ffc7-7fd5-4202-92ea-132c7d4f5cd4@s50g2000hsb.googlegroups.com> Message-ID: <487F87A0.9040702@egenix.com> On 2008-07-16 20:00, Keith Hughitt wrote: > Thanks Gabriel! > > That helps clear things up for me. The above method works very well. I > only have one remaining question: > How can I pass a datetime object to MySQL?' > > So far, what I've been doing is building the query as a string, for > example: > > query = "INSERT INTO image VALUES(%d, %d, %s, '%s')" % (id, meas, > date, 'jpg') > cursor.execute(query) Use binding parameters and it should work: query = "INSERT INTO image VALUES(%d, %d, %s, '%s')" cursor.execute(query, (id, meas, date, 'jpg')) Database interfaces typically do not support timezones, so I'm not sure why you are making things more complicated by adding a timezone to the date/time value. > This works fine for regular datetime objects, which are passed as > strings similar > to: "2003-10-01 00:00:00." When incorporating a timezone, however, the > resulting string > is of the form "2003-10-01 00:00:00+00:00." Unfortunately, MySQL does > not recognize > the offset. > > I know you said you don't use MySQL, but how would you do something > execute a similar query > on the database you normally interface with? > Thanks, > Keith > > > On Jul 15, 12:04 am, "Gabriel Genellina" > wrote: >> En Mon, 14 Jul 2008 12:06:30 -0300,KeithHughitt >> escribi?: >> >> >> >>> On Jul 12, 12:52 am, "Gabriel Genellina" >>> wrote: >>>> En Fri, 11 Jul 2008 15:42:37 -0300,KeithHughitt >>>> escribi?: >>>>> I am having a little trouble figuring out how to convert a python >>>>> datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would >>>>> like to create a UTC date so that when I send it to MySQL (which >>>>> treats all dates at local dates by default), it will already have >>>>> incorporated the proper UTC offset. I've tried looking through the >>>>> docshttp://python.active-venture.com/lib/datetime-datetime.html), but >>>>> have not had any luck. >>>> You have to use a "timezone aware" datetime object. If all you want is >>>> to >>>> store an UTC date, the tzinfo demo classes that you can find in the >>>> Python >>>> docs at may be enough. >>> Thanks for advice Gabriel. I downloaded the tzinfo demo class, saved >>> it as >>> UTC.py and imported it. I'm still not exactly sure how to use it >>> though. It looks like >>> the file already creates an instance of the UTC tzinfo class (line 20: >>> "utc = UTC()"), >>> however, when I try to test it out in the interpreter, it cannot be >>> found. I'm new >>> to python, and there is probably something obvious I'm missing, but do >>> you have any ideas? >> The import statement in Python doesn't behave the same way as similar >> statements in other languages - and it may be confusing you. I'll try to >> explain it using this example. >> You have: >> - a *file* UTC.py, containing the source code for the *module* UTC. It >> contains: >> - a *class* definition (UTC) and >> - an *instance* of that class, utc. >> >> --- begin UTC.py ---If you pass a "timezone aware" datetime object as a SQL parameter >> class UTC(tzinfo): >> ... >> utc = UTC() >> ... >> --- end UTC.py --- >> >>> Here is what I'm attempting: >>> ============ output begin ============= >>> Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) >>> [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>>>>> import datetime, UTC >> Here you have imported the *module* UTC. That is, the name UTC now refers >> to a newly created module just loaded from the UTC.py file. >> >>>>>> t = datetime.datetime(2008, 7, 14, 00, 00, 00, UTC()) >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: 'module' object is not callable >> The error comes from UTC(): UTC is a module, UTC() is attempting to "call" >> it, and since modules are not callable objects, we get a TypeError. >> >>>>>> utc >>> Traceback (most recent call last): >>> File "", line 1, in >>> NameError: name 'utc' is not defined >> The *only* name we have imported so far is UTC - the module. Lowercase utc >> isn't defined. >> >>>>>> utc = UTC() >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: 'module' object is not callable >> Same as above... >> >> Ok, how to solve it? We know that UTC refers to the *module* with the same >> name. To get the *class* inside that module, use UTC.UTC - try again in >> the interpreter. To create a new instance of that class, you can use >> UTC.UTC(). To obtain the instance already created in the UTC module, use >> UTC.utc >> >> **OR** >> >> Import those names explicitely: >> >> py> from UTC import UTC >> >> In this case the name UTC refers to the *class* inside the module. >> In this particular example it may be confusing - both have the same name. >> Another example from the standard library: the poplib module contains a >> POP3 class, so after executing this line: >> >> py> from poplib import POP3 >> >> the name POP3 refers to that class. The poplib module itself isn't >> directly available. >> Back to the UTC module, you could use: >> >> py> from UTC import utc >> >> and now utc refers to the *instance* already created inside the module. >> This last form may be the most convenient in your case: >> >> py> import datetime >> py> from UTC import utc >> py> print datetime.datetime(2008, 7, 14, 20, 30, 0, 0, utc) >> 2008-07-14 20:30:00+00:00 >> >> -- >> Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 17 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From g.threepwood at gmail.com Mon Jul 28 19:10:25 2008 From: g.threepwood at gmail.com (C Martin) Date: Mon, 28 Jul 2008 16:10:25 -0700 (PDT) Subject: Tkinter fullscreen with Mac OS X Message-ID: Is there a way to create a full screen app using Tkinter with Mac OS X?? On windows, this is relatively easy with overrideredirect(1). However, on the Mac, the top menu bar and dock are still displayed over the app. Is there a way to get rid of them? Thanks. From jason.scheirer at gmail.com Sun Jul 6 23:14:21 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Sun, 6 Jul 2008 20:14:21 -0700 (PDT) Subject: GUI Programming by hand not code with Python Code References: <7003b665-3227-47a7-ab06-1a486f87939a@a1g2000hsb.googlegroups.com> Message-ID: <85ab371e-9926-4bb3-bcd4-f441de7aa046@k30g2000hse.googlegroups.com> On Jul 6, 7:33?pm, jayjaygi... at hotmail.co.uk wrote: > Is their a program that lets you design a GUI by hand (like gambas) > not by code (like wxpython) but the commands are in python? > > A program similar to gambas or vb > > Gambas with python code instead of gambas code would be perfect. > > Thanks in advance Glade for GTK, wxGlade for wxPython. From rcdailey at gmail.com Wed Jul 30 12:39:34 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 30 Jul 2008 11:39:34 -0500 Subject: Reasoning behind 'self' parameter in classes? Message-ID: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> Hi, I want to point out first of all that I'm not as familiar with Python as I should be, and for that reason I question a lot of things because I'm mainly a C++ programmer and I'm used to certain conveniences. Having said that... I've always been curious (more so than annoyed) as to why one must explicitly specify a "self" parameter for member functions in a class in Python. This seems very "C" like to me, since to do object oriented programming in C you must devote one parameter to the object itself. In a higher order language like Python, I would not have expected (and thus am rather surprised) that this pattern would apply. Is there any particular reason why 'self' parameters must be specified explicitly? I am curious to understand the philosophy and design behind this. In Python 3 will there be any plans to eliminate this syntactic artifact? As I said, it's not terribly annoying to me but it seems like more of a hack than anything else. I would feel a bit better if I didn't have to see it. I don't mean to start any syntax wars or anything, so I hope everyone will keep an open mind and simply explain the design, rather than defend it. I'm interested in only facts, and not opinions. This is an example of a response I'm looking for: "The self parameter is required because the parser is a bit old and needs to know the exact object you're referencing" This is _not_ an example of what I'm looking for: "Specifying self is a great mysterious thing that we should never question. Do not question the language! The language is mighty! Don't bring C++ to Python!" I appreciate the community's time. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuwei23 at gmail.com Sun Jul 20 19:22:00 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 20 Jul 2008 16:22:00 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <55888f61-d179-4d6a-9003-a9fa2ca21373@x36g2000prg.googlegroups.com> On Jul 21, 8:50 am, giveitawhril2... at gmail.com wrote: > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. The advantage of Python over C - to me - is in the higher order abstractions it provides, not in pointless discussions of purity. Even better, Python allows me to -mix- both C & Python together, to take advantage of the strengths of each as appropriate. Try writing something of complexity in Python. Then write the same thing in C. -Then- make your decision which you prefer. From maestroQC at gmail.com Wed Jul 16 11:32:44 2008 From: maestroQC at gmail.com (maestroQC) Date: Wed, 16 Jul 2008 08:32:44 -0700 (PDT) Subject: MySQL Insert References: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> Message-ID: Thanks to all for your time and patience with this! The insert is working fine based on the suggestions in this thread. I now have another problem that should be resolved with a regular expression to remove currency formatting before inserting into the db. From larry.bates at websafe.com` Mon Jul 14 18:16:26 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 14 Jul 2008 17:16:26 -0500 Subject: logging via SocketHandler and TCPserver In-Reply-To: <81929250-449b-4686-acf3-dcc0095e341a@d1g2000hsg.googlegroups.com> References: <81929250-449b-4686-acf3-dcc0095e341a@d1g2000hsg.googlegroups.com> Message-ID: Vinay Sajip wrote: > On Jul 13, 9:25 pm, Larry Bates wrote: >> Every time I look at theloggingmodule (up until now) I've given up and >> continue to use my home-grown logger that I've been using for years. I'm not >> giving up this time ;-) >> >> I find that I REALLY need to be able to monitor LOTS of running >> programs/processes and thought it would be nice to have them use SocketHandlerloggingand then I would write TCPServer to accept the log messages for >> real-time monitoring. I Googled (is that now a verb?) for several hours and >> came up with some code that I've turned in to something that works, but I can't >> figure out how to disconnect the server once it is connected The goal is to be >> able to start TCPServer, monitor the log messages sent via SocketHandler logger, >> disconnect, and move to the next application. Eventually I would like to wrap a >> GUI around all of this for monitoring a complex web application. >> >> Everything works, it just appears that I get into the while loop in >> LogRecordStreamHandler.handle and it never breaks out (until I kill the client). >> I can't seem to do anything with the LogRecordSocketReceiver.abort attribute to >> make it quit. >> >> I'm sure it is something simple (stupid?), but I've spent about 4 hours and I'm >> not getting anywhere. >> >> Thanks in advance for any assistance. >> >> Regards, >> Larry >> >> Below is my code: >> >> import sys >> import time >> importlogging >> >> if sys.argv[1] == 'client': >> importlogging.config >> >> logging.config.fileConfig("logging.conf") >> >> #create logger >> logger =logging.getLogger("VESconsole") >> >> while 1: >> logger.debug("debug message") >> logger.info("info message") >> logger.warn("warn message") >> logger.error("error message") >> logger.critical("critical message") >> time.sleep(2) >> >> elif sys.argv[1] == 'server': >> import cPickle >> importlogging.handlers >> import SocketServer >> import struct >> import signal >> >> class LogRecordStreamHandler(SocketServer.StreamRequestHandler): >> """Handler for a streamingloggingrequest. >> >> This basically logs the record using whateverloggingpolicy is >> configured locally. >> """ >> >> def handle(self): >> """ >> Handle multiple requests - each expected to be a 4-byte length, >> followed by the LogRecord in pickle format. Logs the record >> according to whatever policy is configured locally. >> """ >> while 1: >> chunk = self.connection.recv(4) >> if len(chunk) < 4: >> break >> >> slen = struct.unpack(">L", chunk)[0] >> chunk = self.connection.recv(slen) >> while len(chunk) < slen: >> chunk = chunk + self.connection.recv(slen - len(chunk)) >> >> obj = self.unPickle(chunk) >> record =logging.makeLogRecord(obj) >> self.handleLogRecord(record) >> >> def unPickle(self, data): >> return cPickle.loads(data) >> >> def handleLogRecord(self, record): >> t = time.strftime('%a, %d %b %y %H:%M:%S', >> time.localtime(record.created)) >> >> print "%s %s" % (t, record.getMessage()) >> >> class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer): >> """simple TCP socket-basedloggingreceiver suitable for testing. >> """ >> >> allow_reuse_address = 1 >> >> def __init__(self, host='localhost', >> port=logging.handlers.DEFAULT_TCP_LOGGING_PORT, >> handler=LogRecordStreamHandler): >> >> SocketServer.ThreadingTCPServer.__init__(self, >> (host, port), >> handler) >> self.abort = 0 >> self.timeout = 1 >> self.logname = None >> >> def serve_until_stopped(self): >> import select >> abort = 0 >> while not abort: >> rd, wr, ex = select.select([self.socket.fileno()], >> [], [], >> self.timeout) >> if rd: >> self.handle_request() >> >> abort = self.abort >> >> print "serve_until_stopped exiting" >> >> # >> # Start ThreadingTCPServer instance to accept SocketHandler log >> # messages from client. >> # >> tcpserver = LogRecordSocketReceiver() >> print "Starting ThreadingTCPServer..." >> tcpserver.serve_until_stopped() >> >> ''' >> #-----logging.conf----- >> [loggers] >> keys=root >> >> [handlers] >> keys=socketHandler >> >> [formatters] >> keys=simpleFormatter >> >> [logger_root] >> level=DEBUG >> handlers=socketHandler >> >> [handler_socketHandler] >> class=handlers.SocketHandler >> level=DEBUG >> args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT) >> host=localhost >> port=DEFAULT_TCP_LOGGING_PORT >> >> [formatter_simpleFormatter] >> format=%(asctime)s - %(name)s - %(levelname)s - %(message)s >> datefmt= >> ''' > > Hi Larry, > > You can make the server quit (set abort to True) by changing the logic > of the server appropriately. In your script (as in the example at > http://docs.python.org/lib/network-logging.html), nothing sets > server.abort, so the server never quits. If you were to insert a line > "self.server.abort = True" before the break in the check "if > len(chunk) < 4:", then the server will quit whenever a message shorter > than 4 bytes is received; ordinarily, a SocketHandler will always send > a 4-byte length followed by content. You can test this easily as > follows: > > Run the server after modifying the script as described above. > Run the client and observe some messages printed by the server. > Kill the client. The server should still be waiting for events from > clients, though it might quit if, when you kill the client, a > truncated message is sent. > Run "telnet localhost 9020" and type a character. > The server should quit. If you make the "quitting" message a > raw_input() call, then you can see that the server has exited normally > via the abort flag. > > Don't forget, the receiver can receive events from several > applications. You don't need to disconnect and reconnect. Simply have > each event sent by an app identify the app in some way - e.g. the > logger name could be "VESconsole.app1" for one app and > "VESconsole.app2" in another. In your server's handleRecord code, you > can get the logger name, decode the sending app from that and route > the event appropriately. > > Another approach is to subclass SocketHandler and override the > makePickle method. This determines the wire format of the event sent > to the server, and if you change the wire format and modify the server > end to suit, then you can have any amount of flexibility in the > communications between the applications generating the events and the > server collating them. > > I'm not sure why you've had so much trouble with logging in the past, > or why it took several hours of Googling to find a solution relating > to logging events across a network. I Googled for "python network > logging" and the link in the Python docs which I referenced earlier > was the first result, and hence also available via the "I'm Feeling > Lucky" button ;-) > > Best regards, > > Vinay Vinay, Thanks for your detailed explanation, but IMHO your suggested solution is almost the opposite (right idea wrong direction) of what I'm looking for. Hypothetical setup: application1 - SocketHandler logging turned on application2 - SocketHandler logging turned on application3 - SocketHandler logging turned on . . . applicationN monitoring app - ThreadingTCPServer target that Allows user to connect to ANY running application and to view the real-time log messages. After monitoring, it should be able to disconnect and connect to another application... The clients (application1..N) never stop sending and don't ever send anything short to disconnect themselves from the monitoring application. The disconnect/ reconnect is done at the monitoring app end based on input from the user. I think each one would be logging to a different port, but I never really quite got that far. Perhaps there is some other way that I'm missing. It seems like this is something that might be able to be "generalized" into a robust monitoring application for an arbitrary number of asynchronously running applications. Each application's real-time log might be reached by clicking on a tab, menu, etc. As to the difficulty, I might just have a mental block but two modules that I've had a real hard time getting my mind wrapped around is your Logging and Twisted. They both have a multitude of options/ways to be used and not very many working examples to work from. Might be a chance to make some money on a book. If it was full of examples, I'd purchase it. Regards, Larry From stefan_ml at behnel.de Sun Jul 27 09:19:44 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 27 Jul 2008 15:19:44 +0200 Subject: xml.dom's weirdness? In-Reply-To: References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> <1c837e71-a191-4495-8ec8-0126003ba9c6@n33g2000pri.googlegroups.com> <488C3645.8060304@behnel.de> Message-ID: <488c75ee$0$29448$9b4e6d93@newsspool4.arcor-online.net> Lie wrote: > I'm more concerned about the number of modules imported by making an > error (from 30 on the startup to 187) and the side-effect of making an > error, which makes modules such as xml.*/email.* that previously > doesn't exist get imported out of the blue... Using my system Python (2.5.1 on Ubunutu Gutsy): $ strace -e open python -c '' 2>&1 | wc -l 551 $ strace -e open python -c '<><<' 2>&1 | wc -l 4631 Using a self-built Python I have lying around: $ strace -e open python2.3 -c '' 2>&1 | wc -l 210 $ strace -e open python2.3 -c '<><<' 2>&1 | wc -l 214 $ strace -e open python2.6 -c '' 2>&1 | wc -l 138 $ strace -e open python2.6 -c '<><<' 2>&1 | wc -l 142 Blame Ubuntu/Debian. Stefan From rocksportrocker at googlemail.com Fri Jul 18 08:19:00 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Fri, 18 Jul 2008 05:19:00 -0700 (PDT) Subject: How to process a very large (4Gb) tarfile from python? References: <0e96241d-60a3-44fd-967a-394904ad5b34@e39g2000hsf.googlegroups.com> <4nqu74p3mmmdmf9pn7125voe6itko8d31k@4ax.com> <1fe948fd-63a3-48ef-b5a8-84f0e4dd48a2@y22g2000prd.googlegroups.com> Message-ID: <1f1c0b2f-eb74-4949-95ff-0307acd490f7@p25g2000pri.googlegroups.com> Due to the discussion above I wrote a python module for scanning of large tarfiles. You can get it from http://www.procoders.net/wp-content/tarfile_scanner.zip Greetings, Uwe From dgeller at gmail.com Sat Jul 5 14:09:44 2008 From: dgeller at gmail.com (david) Date: Sat, 5 Jul 2008 11:09:44 -0700 (PDT) Subject: conflict between multiple installs of python (linux) Message-ID: <6bd22c06-a1e6-4247-9aff-2d0b29b1ec5e@d1g2000hsg.googlegroups.com> You learn something new every day: On my ubuntu, update-manager is supposed to use the python2.5 installed on /usr/bin. Well, I had subsequently installed a whole bunch of stuff in /usr/local (/usr/local/bin/python and /usr/local/lib/ python2.5 etc), which I have happily been using for development for a year. I had thought that the two pythons were completely independent. Well, I was wrong. When /usr/bin/python2.5 runs, *by default*, it adds /usr/local/lib/python2.5 to its sys path - and apparently there are things in /usr/local which are inconsistent with those at /usr (not suprising). I have fixed the problem - but I had to modify the actual update- manager .py file itself. At the beginning, I set the sys.path in python *explicitly* to not include the /usr/local stuff. But this is clearly a kludge. My question: how do I keep the Ubuntu python stuff at /usr/bin/python2.5 from adding /usr/local/lib/ python2.5 to the import search path in a clean and global way? I really want both pythons completely isolated from one another! Thankyou. From stefan_ml at behnel.de Tue Jul 22 17:03:09 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 22 Jul 2008 23:03:09 +0200 Subject: xpathEval fails for large files In-Reply-To: References: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> Message-ID: <48864b0d$0$9494$9b4e6d93@newsspool3.arcor-online.net> Fredrik Lundh wrote: > Kanchana wrote: > >> I tried to extract some data with xpathEval. Path contain more than >> 100,000 elements. >> >> doc = libxml2.parseFile("test.xml") >> ctxt = doc.xpathNewContext() >> result = ctxt.xpathEval('//src_ref/@editions') >> doc.freeDoc() >> ctxt.xpathFreeContext() >> >> this will stuck in following line and will result in high usage of >> CPU. >> result = ctxt.xpathEval('//src_ref/@editions') >> >> Any suggestions to resolve this. > > what happens if you just search for "//src_ref"? what happens if you > use libxml's command line tools to do the same search? > >> Is there any better alternative to handle large documents? > > the raw libxml2 API is pretty hopeless; there's a much nicer binding > called lxml: > > http://codespeak.net/lxml/ > > but that won't help if the problem is with libxml2 itself, though It may still help a bit as lxml's setup of libxml2 is pretty memory friendly and hand-tuned in a lot of places. But it's definitely worth trying with both cElementTree and lxml to see what works better for you. Depending on your data, this may be fastest in lxml 2.1: doc = lxml.etree.parse("test.xml") for el in doc.iter("src_ref"): attrval = el.get("editions") if attrval is not None: # do something Stefan From jordanrastrick at gmail.com Thu Jul 24 05:58:26 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 02:58:26 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> Message-ID: On Jul 24, 7:40?pm, Torsten Bronger wrote: > Hall?chen! > > Bruno Desthuilliers writes: > > [...] > > > How would you handle this case with an implicit 'self' : > > > class Foo(object): > > ? ?pass > > > def bar(self): > > ? ?print self > > > Foo.bar = bar > > Just like this. ?However, the compiler could add "self" to > non-decorated methods which are defined within "class". > > Tsch?, > Torsten. > > -- > Torsten Bronger, aquisgrana, europa vetus > ? ? ? ? ? ? ? ? ? ?Jabber ID: torsten.bron... at jabber.rwth-aachen.de Yeah, forgot what I said, Torsten's reply is much better :-) From basti.wiesner at gmx.net Thu Jul 10 12:46:37 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Thu, 10 Jul 2008 18:46:37 +0200 Subject: Emacs/Python Essentials? References: Message-ID: xkenneth : > What does everyone consider essential for emacs python dev? yasnippet is worth being looked at -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From catherine.heathcote at gmail.com Tue Jul 22 12:37:39 2008 From: catherine.heathcote at gmail.com (Catherine Heathcote) Date: Tue, 22 Jul 2008 17:37:39 +0100 Subject: Question about inheritence References: <26204bc2-a1f9-439c-aa0b-2d957ed81c5d@p25g2000hsf.googlegroups.com> Message-ID: On Tue, 22 Jul 2008 09:35:58 -0700, Matimus wrote: > On Jul 22, 9:26?am, Catherine Heathcote > wrote: >> If I create a new class inherited from another with a constructor, what >> happens with the new class's constructer? >> Thanks for your time. > > Nothing, unless you call it in your constructor. > > class Base(object): > def __init__(self): > print "Base constructor called" > > # without calling the base class constructor > class C(Base): > def __init__(self): > print "C constructor called" > > # call the base class constructor using super > class D(Base): > def __init__(self): > super(D, self).__init__() > print "D constructor called" > > c = C() > d = D() > > > Matt Aha! Makes sence, thankyou. As you can probably tell I am new to Python, but not programming as a whole. From kyosohma at gmail.com Thu Jul 31 14:58:54 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 31 Jul 2008 11:58:54 -0700 (PDT) Subject: Hobbyist - Python vs. other languages References: Message-ID: <68545bc7-6dfd-4988-b697-f93b8e26c527@s50g2000hsb.googlegroups.com> On Jul 31, 1:32?pm, fprintf wrote: > I have been playing with computers since I first learned to program > moving shapes on an Atari 800XL in BASIC. After many years of dabbling > in programming languages as a hobbyist (I am not a computer scientist > or other IT professional), I have never found a way to stick with a > language far enough to do anything useful. ?I learn all about loops > and data structures and functions/methods etc. but never get to create > a program that will do anything of value that I can't more easily do > via freeware. Well, except the slot car timing system I wrote in C++ > for Linux many moons ago. > > Honestly Python seems like a breath of fresh air and possibly a way to > get back to my BASIC roots, you know, programming just for the fun of > it. > > Since I don't have a specific problem to solve, besides > Pythonchallenge (which I found very cryptic), and Project Euler (which > I found beyond my mathematics skills), is there a place to go for > increasingly difficult problems to solve? I have followed a number of > the recommended online tutorials that contain a logical progression of > problems and yet they all end at the point where a person has enough > knowledge of the syntax, but not really enough to do anything. I've noticed that there's a gap between learning the syntax and actually being able to do something myself. It's pretty annoying. However, all you need is to come up with some projects that you'd like to do, such as inventorying some collection you have (CDs, DVDs, Clocks, whatever). Then you have a place to start. The next step is to break the project down into smaller parts until you have parts to tackle. Let's say you want to inventory your DVDs for example. First, you'd need to figure out how much data about each title you want. Examples might include Title, Director, top 3 actors, price, and purchase date. Once you know what you want to store, you can learn about data persistence (i.e. databases!). Or you could join a local Python Users Group or an open source project. I learn a lot just helping people on this and other Python lists. Mike From rcdailey at gmail.com Wed Jul 30 15:49:41 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 30 Jul 2008 14:49:41 -0500 Subject: Reasoning behind 'self' parameter in classes? In-Reply-To: <4890C526.70204@nienna.org> References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> <4890ACE4.4060703@acm.org> <496954360807301227h1dea050eg735314beb0b5ff16@mail.gmail.com> <4890C526.70204@nienna.org> Message-ID: <496954360807301249w6a5080d5p1efd0af4dd1252e5@mail.gmail.com> On Wed, Jul 30, 2008 at 2:46 PM, Matthew Fitzgibbons wrote: > Robert Dailey wrote: > >> On Wed, Jul 30, 2008 at 1:03 PM, Brett g Porter > bgporter at acm.org>> wrote: >> >> Robert Dailey wrote: >> >> This is an example of a response I'm looking for: >> "The self parameter is required because the parser is a bit old >> and needs to know the exact object you're referencing" >> >> This is _not_ an example of what I'm looking for: >> "Specifying self is a great mysterious thing that we should >> never question. Do not question the language! The language is >> mighty! Don't bring C++ to Python!" >> >> >> Fredrik Lundh has written a very clear explanation of this at >> >> http://effbot.org/pyfaq/why-must-self-be-used-explicitly-in-method-definitions-and-calls.htm >> >> (or http://bit.ly/3EUiCf if you don't feel like stitching that URL >> back together...) >> >> >> This sounds like an article of opinion. He's not really given any reasons >> other than "Well, it makes this easier or look better". True that >> declarations are the determining factor in C/C++, however I was thinking of >> more or less an implied 'self'. For example: >> >> # Consider this normal syntax: >> class MyFoo: >> def DoFoo( self ): >> self._member = 6 >> >> # Elimintating 'self' in the parameter list should still work as far as >> the >> # interpreter is concerned, since 'self' in this case now acts like 'this' >> # in C++. The below code should be equivalent. >> class MyFoo: >> def DoFoo(): >> self._member = 6 >> >> Given the code samples above, is there any technical reason why this >> cannot be done? Thanks for the input guys, and thanks more over for keeping >> this easy-going. >> >> >> ------------------------------------------------------------------------ >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > Your first example could be written: > > class MyFoo(object): > def do_foo(the_foo_instance): > the_foo_instance._member = 6 > > 'self' is not special the way 'this' is in C++. It's just a name for an > object reference just like any other name for any other object reference. > > -Matt > Yes, I realize that it can have any name. But this does not change its purpose. It was simply an example. In the second code snippet I gave you, 'self' would become a reserved word and a user would have to use that to reference the object from which the function was called. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at fenestra.com Tue Jul 22 12:29:40 2008 From: steve at fenestra.com (Steve Schafer) Date: Tue, 22 Jul 2008 12:29:40 -0400 Subject: The Importance of Terminology's Quality References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: On Tue, 22 Jul 2008 10:21:50 +0100, Martin Gregorie wrote: >The first time I ran across the term "thunking" was when Windows 3 >introduced the Win32S shim and hence the need to switch addressing between >16 bit and 32 bit modes across call interfaces. That was called "thunking" >by Microsoft and even they would surely admit it was a kludge. Win32s thunks are a completely different beast from the original Algol 60 thunks. As far as I know, the first published description of thunks was: Ingerman PZ (1961) Thunks: A way of compiling procedure statements with some comments on procedure declarations, CACM 4:55-58. Steve Schafer Fenestra Technologies Corp. http://www.fenestra.com/ From ggpolo at gmail.com Tue Jul 1 21:14:50 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 1 Jul 2008 22:14:50 -0300 Subject: SQLite and Python 2.4 In-Reply-To: <200807020051.m620pxS4011942@vm-mailout2.fpw.ch> References: <200807020051.m620pxS4011942@vm-mailout2.fpw.ch> Message-ID: On Tue, Jul 1, 2008 at 9:51 PM, Joe Goldthwaite wrote: > I'm confused. (Not a new experience). I've got a web application running > under Zope. I use the Wing IDE for testing and debugging. When trying to > recreate problems that come up on the web, I wrote some little routines that > pull my cookies out of the Firefox cookies.txt file into my code. That way, > I'm working with all the same options under Wing that my app uses when > running under Zope. > > That's worked great until I upgraded to Firefox 3. Firefox 3 moved their > cookies from cookies.txt to cookies.sqlite. I haven't worked with SQLite at > all so I started searching for examples and found this; > > import sqlite3 > conn = sqlite3.connect('test.db') > c = conn.cursor() > rows = c.execute('SELECT * from somefile') > > Looks simple enough but I can't get it to work. Here are my questions; > > 1. How do you get sqlite3 for Python 2.4? I can't find it anywhere. You need sqlite itself (www.sqlite.org) and bindings, pysqlite 2 (http://oss.itsystementwicklung.de/trac/pysqlite/) or aspw (http://code.google.com/p/apsw/) > > 2. If sqlite3 is only for Python 2.5, does sqlite2 work the same way? > You are confused, yes. The sqlite3 package that comes with python2.5 is actually pysqlite2, which interfaces with sqlite3. Also, sqlite3 and sqlite2 files format are not compatible. > 3. Looking at the cookies.sqlite file, I see some text right at the top > "SQLite format 3". Does that mean that I need to use sqlite3? Yes > > I kind of got the above example using pysqlite2.4.1 for python 2.4. I get > through the part where I create the connection object but the resulting > object doesn't have a cursor method. I thought that maybe it wasn't > recognizing the cookies.sqlite file as a SQLite database so I tried the same > code giving it a junk text file instead and it behaved the same way. Since > I didn't get an error message, I'm thinking that I've got the wrong version > for the Firefox cookies.sqlite file. > > I don't have a clue as to where else to look to trace it down. I'm hoping > that someone here is more familiar with it and can give me some pointers. > > Thanks, > > Joe Goldthwaite > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From dave.hirschfeld at gmail.com Tue Jul 1 06:51:11 2008 From: dave.hirschfeld at gmail.com (Dave) Date: Tue, 1 Jul 2008 03:51:11 -0700 (PDT) Subject: PyPy questions References: Message-ID: On 1 Jul, 04:09, Allen wrote: > I read the website of some information about PyPy, and how a translator > translates the RPython code to C/CLI/Java/etc to be compiled to a native > executable or something like that. ?Would it be possible, in PyPy, to > write such an extension that could easily be compiled to native code > from Python code? ?Is this functionality planned in a future release of > it? ?Also, how is the source distributed (If I opt to use it I will end > up compiling it on a system without an initial python install (a scratch > linux system)), so does the source include the generated C code? > > B. Vanderburg II Were you thinking of something like this? http://www.enthought.com/~ischnell/compdec.html -Dave From __peter__ at web.de Thu Jul 10 02:37:01 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Jul 2008 08:37:01 +0200 Subject: error when porting C code to Python (bitwise manipulation) References: Message-ID: Jordan wrote: > C: > > u starts at 1050 > > u += 0xe91aaa35; > > u is now -384127409 Hm, a negative unsigned... > Python: > > ? ?u starts at 1050 > > ? ?u += 0xe91aaa35 > > ? ?u is now ?3910839887L Seriously, masking off the leading ones is the way to go: >>> -384127409 & 0xffffffff == 3910839887 & 0xffffffff True Peter From jonnojohnson at gmail.com Tue Jul 1 17:46:35 2008 From: jonnojohnson at gmail.com (Jonno) Date: Tue, 1 Jul 2008 16:46:35 -0500 Subject: Combination of element-wise and matrix multiplication Message-ID: <3d15ebce0807011446k4347f2b7l462bb2491c79db2e@mail.gmail.com> I have two 2x2 arrays a & b. a=(([c,d],[e,f])) b=(([g,h],[i,j])) Each of c,d,e,f,g,h,i,j are all 1xN arrays I want to matrix multiply a & b to create a 2x2 array x, where the elements of x are created with element-wise math and result in the following: x[0,0] = c*g+d*i x[0,1] = c*h+d*j x[1,0] = e*g+f*i x[1,1] = e*h+f*j What is the simplest way to do this? I ended up doing the matrix multiplication manually as above but this doesn't scale very nicely if a & b become larger size. Cheers, Jonno. -- "If a theory can't produce hypotheses, can't be tested, can't be disproven, and can't make predictions, then it's not a theory and certainly not science." by spisska on Slashdot, Monday April 21, 2008 -------------- next part -------------- An HTML attachment was scrubbed... URL: From aspersieman at gmail.com Thu Jul 24 07:10:15 2008 From: aspersieman at gmail.com (Aspersieman) Date: Thu, 24 Jul 2008 13:10:15 +0200 Subject: Autocompletion and Interactive Tables in a Python IDE In-Reply-To: References: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Message-ID: <48886317.6040801@gmail.com> > > On Jul 24, 4:10 am, Aspersieman wrote: > >> Anthony wrote: >> >>> Hi, I'm a FoxPro programmer, but I want to learn python before it's >>> too late. I do a lot of statistical programming, so I import SPSS >>> into python. In my opinion, the best features of Visual FoxPro 9.0 >>> were: >>> a) Intellisense (tells you what classes/methods are available and what >>> variables go into a function) >>> b) Code Completion (guesses your code after four letters) >>> c) Data-Orientation; multiple data sessions can be open, data can be >>> viewed easily >>> >>> Python's IDLE has only half of the first of these features. I did a >>> lot of searching and found the PyDev extensions for Eclipse's Python >>> IDE, and found that they've got Intellisense. I'm still missing b and >>> c, and am getting extremely frustrated programming so slowly.. >>> >>> So two questions: >>> Is there any package, gui, IDE, anything that will do FoxPro-style >>> code completion? If it works in Eclipse, even better.. >>> I can't find a good screenshot, but here's a better description: >>> You type "BROW" and it pops up a window that says "BROWSE" ..at this >>> point if you hit enter it completes the word.. >>> >>> and >>> >>> How can I view open SPSS data in one of the Python GUIs? Again, >>> Eclipse would be the preference. >>> Here's an example of how I'd like to browse the data: >>> http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=... >>> I don't want to have to switch back and forth between Python and SPSS >>> while I'm programming; I just want to stay in one of them.. >>> >>> What can I do? I feel extremely inefficient when I don't have these >>> three features.. >>> >>> Thanks in advance. >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> You might want to try vim. It has a steep learning curve, but definitely >> increases productivity _alot_. >> >> Here is a tutorial on setting up vim with : >> 1) Code completion (intellisense) - including tooltips (!!!) >> 2) Jump between your python code and the python class libraries. >> 3) Syntax checking >> 4) A handy source browser >> 5) Debugging (using pdb) >> 6) [All the other vim goodies - already included] >> Above instructions available herehttp://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/ >> >> I have been using the above setup for a while and find it superior to >> _any_ IDE I've ever worked with. >> >> I'm not sure what you mean by 'Data-Orientation' but I'm sure there's a >> suitable alternative/replacement for it in vim. >> >> Regards >> >> Nicolaas >> >> -- >> Anthony wrote: > FoxPro is data-oriented, which means that at any time you have any > number of data sets open in the workspace and browse them immediately > by running one line of code in the command window. It's a really > important feature in terms of efficiency; I don't want to have to move > back and forth between SPSS and an IDE when I'm figuring out what code > to write, that takes six keystrokes for what FoxPro can do in one. > Again, here's what the BROWSE command presents: > > http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=vfptoolkit_figure02.tif > > > Does VIM have the capability to keep data open? -- Do any of these > IDEs have this browse capability?? I see what you mean by 'Data Oriented', however I'm not aware of such a 'data set' persistence functionality in vim. You can set up a similar (to FoxPro) environment using DBExt [1] plugin in vim and by using its (vims') built-in session functionality. To set up dbext for FoxPro in vim you might need to use ODBC but it should be quite straight forward provided you read the help. I work on SQL Server (using python and vim) and frequently have many queries result sets open that I'm busy with. When I have to go, all I do is save my session in vim. When I return the next day, I open the session, and it there I have all the queries (not the data sets they return (however you can save that too)) and scripts etc, I was working on. To execute a query (even one embedded in some python code) I merely select the lines the query is on and type the key-mapping (I set up) to execute the query (3 key strokes) and I can view the result set in a split window below the current one. The aforementioned vim setup for python [2] and the DBExt plugin for vim give me all the functionality I need to develop python and/or database applications/scripts in one editor (IDE?). Also, there are so many other useful plugins [3] for vim I have no need of any other IDE (I've replaced Visual Studio .Net with vim as my IDE for Asp.Net applications). I'm sure that vim can meet all the required features you wanted initially. [1] http://www.vim.org/scripts/script.php?script_id=356 [2] here it is again : http://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/ [3] http://www.vim.org/scripts/script.php?script_id=1318 and http://www.vim.org/scripts/script.php?script_id=910 and http://vim.sourceforge.net/scripts/script.php?script_id=69 and http://www.vim.org/scripts/script.php?script_id=1658 Hope this helps :) Regards Nicolaas -- The three things to remember about Llamas: 1) They are harmless 2) They are deadly 3) They are made of lava, and thus nice to cuddle. From tdelaney at avaya.com Tue Jul 29 17:17:07 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 30 Jul 2008 05:17:07 +0800 Subject: Execution speed question In-Reply-To: <6f8uc6FahulcU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> For sets, I presume they are built on top of or like dicts, and >> there is nothing crazy in the low level implementation so that I can >> be guaranteed that if I don't alter the set, then the order, >> although arbitrary, will be maintained in successive iterations over >> the contents? > > It is currently that way, but relying on it is certainly to be > considered an implementation detail that might disappear without > warning. Fortunately, that's incorrect - it is a documented feature that *so long as the set is not modified in any way*, iterating over the set will return the elements in the same order each time. Tim Delaney From larry.bates at websafe.com` Sun Jul 27 21:55:10 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 27 Jul 2008 20:55:10 -0500 Subject: Where is the correct round() method? In-Reply-To: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> Message-ID: josh logan wrote: > Hello, > > I need a round function that _always_ rounds to the higher integer if > the argument is equidistant between two integers. In Python 3.0, this > is not the advertised behavior of the built-in function round() as > seen below: > >>>> round(0.5) > 0 >>>> round(1.5) > 2 >>>> round(2.5) > 2 > > > I would think this is a common need, but I cannot find a function in > the Python library to do it. I wrote my own, but did I miss such a > method in my search of the Python library? > > Thanks I think what you want is something like: math.ceil(x-0.4999999999999) -Larry From luster123 at gmail.com Fri Jul 11 04:40:50 2008 From: luster123 at gmail.com (luster123) Date: Fri, 11 Jul 2008 01:40:50 -0700 (PDT) Subject: Trying to learn Message-ID: Hey, Can someone please teach me the basics of Python and Pygame? From trinityedusystems at gmail.com Thu Jul 24 12:04:18 2008 From: trinityedusystems at gmail.com (francis) Date: Thu, 24 Jul 2008 09:04:18 -0700 (PDT) Subject: earn from home blogging Message-ID: <9231e7f9-71a6-4405-9a4e-9ae62d8bcdd2@z6g2000pre.googlegroups.com> visit for more information http://2earnfromblog.blogspot.com http://trinityedusystems.blogspot.com From pauladospublicidad at yahoo.com Fri Jul 11 05:45:00 2008 From: pauladospublicidad at yahoo.com (pauladospublicidad) Date: Fri, 11 Jul 2008 09:45:00 -0000 Subject: Question about: GUI Builder for Tkinter and call to C/C++ code Message-ID: First I'll introduce myself. I normally programm in C/C++ and Java. Sometimes I have to mix them (normally using C/C++ in java, because in java is easier to make portable graphic user interfaces). However to use C/C++ code in java is really complex and difficult. Not too much time ago, I discover python. I had think to use it for developing portable graphic user intefaces, that will call my C/C++ code / libraries / programs. I had thought to use tkinter for making the GUIs, for portability and for not installing anything more than python. It's to say, for not adding more packages because I'm new in python and I don't now too much about install new packages. I have seen that for wxpython there is gui builders (such as boa) but for tkinter I have not found anyon. I would like to know if anyone knows a GUI Builder for tkinter in order to develop my GUI's graphically and in a easier way. Apart from this, I would like to call my C/C++ code / modulles / applications from python. I have read that python is implemented normally in C, so is easy to add new modules from C. I would like to find any tutorial / manual / link for dummies in order to make this (call my C code from python). Another solution could be to call the GUI made in python from C/C++ code, but I'm sure this would be more complex. To sum up, if anyone knows something about this subjects, about what I would like to do, I'll appreciate any answer :D Byee!!!!! From gros_bedo at hotmail.com Thu Jul 10 11:07:44 2008 From: gros_bedo at hotmail.com (Gros Bedo) Date: Thu, 10 Jul 2008 17:07:44 +0200 Subject: Terminate a python script from linux shell / bash script Message-ID: >>That's not how it works. If you kill one running python script it will not >>effect other python scripts. Each script has its own interpreter process >>running. >GB> So, is there a way from the Linux shell or a bash script to terminate >GB> just one specific Python script ? >>So just kill it. Yes I've seen that each python script calls its own instance of Python. But how to know which is the good one in bash ? Is there a command that gets the parameters of process, so I could use grep to select the one containing the name of my script ? _________________________________________________________________ Votre contact a choisi Hotmail, l'e-mail nouvelle g?n?ration. Cr?ez un compte. http://www.windowslive.fr/hotmail/default.asp From keshet1 at umbc.edu Wed Jul 9 00:00:38 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Wed, 09 Jul 2008 00:00:38 -0400 Subject: a simple 'for' question In-Reply-To: <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> References: <4874017D.2000401@umbc.edu> <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> Message-ID: <487437E6.8010609@umbc.edu> oops, my mistake, actually it didn't work... when I tried: for x in folders: print x # print the current folder filename='Folder/%s/myfile.txt' %x f=open(filename,'r') it says: IOError: [Errno 2] No such file or directory: 'Folder/1/myfile.txt' I should mention that I am working in windows, could it be the / vs. \? I tried: for x in folders: print x # print the current folder filename='Folder\%s\myfile.txt' %x f=open(filename,'r') filename is now 'Folder\\1\\myfile.txt', and the pathway doesn't exist. Any suggestions? Thanks again for your time. Ben Brian Blais wrote: > On Jul 8, 2008, at Jul 8:8:08 PM, Ben Keshet wrote: > >> I want to use a 'for' iteration to manipulate files in a set of >> folders, something like: >> >> folders= ['1A28','1A6W','56Y7'] >> for x in folders: >> print x # print the current folder >> f = open('my/path/way/x/my_file.txt', 'r') >> ... >> > > > I think: > > f = open('my/path/way/%s/my_file.txt' % x, 'r') > > should work, although I would probably be more clear about the names, > like: > > folders=['1A28','1A6W','56Y7'] > for folder in folders: > filename='my/path/way/%s/my_file.txt' % x > fid=open(filename,'r') > .... > > also, make sure that you do mean the relative path my/path/way/... > # in current folder > as opposed to the absolute path: /my/path/way > # in root folder > > > bb > -- > Brian Blais > bblais at bryant.edu > http://web.bryant.edu/~bblais > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Samnsparky at gmail.com Sun Jul 13 22:52:16 2008 From: Samnsparky at gmail.com (Sparky) Date: Sun, 13 Jul 2008 19:52:16 -0700 (PDT) Subject: Newbie Threading Question References: Message-ID: <6e92ab0c-0371-4897-b4c4-f607a16c49ce@m36g2000hse.googlegroups.com> On Jul 13, 1:30?pm, Nick Dumas wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > I'm not an expert on Python threading, so don't take my word as low, > however, I believe that there's no need for a list of systems which > support it because the Python virtual machine handles it. Thus, any > system which supports Python (or at least Python versions with > threading) will support Python threading. Again, I don't know a lot > about this, but it would make sense. > > Sparky wrote: > > It seems strange, but I can't find a list of operating systems which > > support / don't support threading in Python. Can anyone point me in > > the right direction? > > > Thanks, > > Sam > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (MingW32) > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > iEYEARECAAYFAkh6V8YACgkQLMI5fndAv9hVKgCePbrN4nwbsdZXNfIcnm3cXac5 > 5kUAnR0OeNB0gjsksRD2W5gcZ8c0pby0 > =p3U+ > -----END PGP SIGNATURE----- Thanks. I think that should make sense. Plus, if it is part of the standard distribution, I would assume it is supported in most places. Sam From usenetthrowaway at gmail.com Mon Jul 28 07:56:03 2008 From: usenetthrowaway at gmail.com (Gary) Date: Mon, 28 Jul 2008 12:56:03 +0100 Subject: Proxy server? Message-ID: I've seen examples for HTTP and FTP use, but not for simply any TCP data on any port, which is what I require. Can anyone please point me in the right direction? TIA From kris at FreeBSD.org Tue Jul 8 09:58:31 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Tue, 08 Jul 2008 15:58:31 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> Message-ID: <48737287.1080909@FreeBSD.org> samwyse wrote: > On Jul 4, 6:43 am, Henning_Thornblad > wrote: >> What can be the cause of the large difference between re.search and >> grep? > >> While doing a simple grep: >> grep '[^ "=]*/' input (input contains 156.000 a in >> one row) >> doesn't even take a second. >> >> Is this a bug in python? > > You might want to look at Plex. > http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/ > > "Another advantage of Plex is that it compiles all of the regular > expressions into a single DFA. Once that's done, the input can be > processed in a time proportional to the number of characters to be > scanned, and independent of the number or complexity of the regular > expressions. Python's existing regular expression matchers do not have > this property. " Very interesting! Thanks very much for the pointer. Kris From alexnbryan at gmail.com Tue Jul 15 15:43:38 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 15 Jul 2008 12:43:38 -0700 (PDT) Subject: Testing for connection to a website Message-ID: <18473382.post@talk.nabble.com> Okay, I already made this post, but it kinda got lost. So anyway I need to figure out how to test if the user is able to connect to a specific website. Last time I got pointed to the urllib2 page, but if I do urlopen() and and am not connected, the program stops. So I don't know if that was what you guys wanted me to do, but I don't think so, you guys are smarter than that. So, how can I test for connection to a website. -- View this message in context: http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p18473382.html Sent from the Python - python-list mailing list archive at Nabble.com. From akineko at gmail.com Sat Jul 5 00:57:37 2008 From: akineko at gmail.com (akineko) Date: Fri, 4 Jul 2008 21:57:37 -0700 (PDT) Subject: Python XML-RPC Server with clientside Javascript Message-ID: Hello everyone, I have used Python SimpleXMLRPCServer to expose several methods to be used. My Python script creates a free-standing server and not a CGI script. I have tested its exposed methods using the following Python script: import xmlrpclib s = xmlrpclib.ServerProxy('http://localhost:8765') print s.my_method() I tested all methods one by one and they are working as I intended. Now, I want to use those exposed methods from a static html file (without any web server) using client side javascript. (i.e. Open File... from the browser (or file://...) ) I found many XML-RPC examples with javascript but all of them I found assume XML-RPC services to be deliver from a web server, such as Apache, as a CGI. I tried those examples with placing 'http://localhost:8765' as url, but they didn't work. How can I utilize the XML-RPC services from a free-standing SimpleXMLRPCServer in a static HTML page? Is it possible to do such? Do I need web server to use client-side javascript? I have searched the Internet for similar questions. I found similar postings but there were no clear answers. Any suggestions will be highly appreciated. Best regards, Aki Niimura From snowballz.game at gmail.com Fri Jul 18 22:51:19 2008 From: snowballz.game at gmail.com (Michael Lubker) Date: Fri, 18 Jul 2008 21:51:19 -0500 Subject: Any Game Developers here? In-Reply-To: <9B960401-8D79-44BC-B4A5-4BE2BD1869BC@gmail.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> <4A235BC6-5E46-4402-AF2D-BA3DBC175517@gmail.com> <76b841590807181605r106995d2k98486993a4eaccc4@mail.gmail.com> <9B960401-8D79-44BC-B4A5-4BE2BD1869BC@gmail.com> Message-ID: <76b841590807181951p10159677n881d2bdadf4f69fc@mail.gmail.com> PyOhio sounds fun... I've been wanting to get some sort of Barcamp or GameJam running where I live (in Austin, so you'd think there would be people interested) but no-one will bite. :/ Escort Wing was a fun project... I did a few mods for EW1. Will you release this demo anywhere? Just curious. Thanks Michael On Fri, Jul 18, 2008 at 7:52 PM, Stephen Johnson wrote: > Yes, I wrote the music, the GUI, and bits of code here and there.. Will > Hogben is working on EW 2 for Freeverse right now. But that was in BlitzMax, > and I'm in greener pastures now, working on my demo for PyOhio. > -Steve Johnson > On Jul 18, 2008, at 7:05 PM, Michael Lubker wrote: > > I'm interested in general... I know about PyGame and Pyglet, and have > used both. We're currently using Python-Ogre. In the end, I am looking > to find people interested in my project ( see > http://youtube.com/watch?v=E0QQ9JuclxE ), but I also want to find > people experienced with Python in general, not just one library. > (though of course I know that's not too likely) > > Aren't you one of the Escort Wing developers? :) > > Thanks > Michael > > On Fri, Jul 18, 2008 at 5:13 PM, Stephen Johnson wrote: > > I use the Pyglet library to make games. You want to look at the pyglet and > > pygame mailing lists, not this one. Use Google. > > In my opinion, PyGame is clunky and Pyglet is elegant, simple, and > > comprehensive. PyGame has more examples available, but Pyglet has great > > documentation and enough examples to answer any questions you might have. > > Both have active communities. > > -Steve Johnson > > On Jul 18, 2008, at 5:38 PM, Michael Lubker wrote: > > Any people that use Python as the predominant language for their game > > development here? > > ~Michael > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > ~ "The world hates change, yet it is the only thing that has brought > progress." ~ Charles Kettering > > http://snowballz.joey101.net > > -- ~ "The world hates change, yet it is the only thing that has brought progress." ~ Charles Kettering http://snowballz.joey101.net From robert.kern at gmail.com Mon Jul 28 19:21:58 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 28 Jul 2008 18:21:58 -0500 Subject: derivative in numpy In-Reply-To: <488E4F1D.3060908@islandtraining.com> References: <488E4F1D.3060908@islandtraining.com> Message-ID: Gary Herron wrote: > knielsen73 at gmail.com wrote: >> Hi, >> >> I am looking to do a simple derivative. I would expect such a function >> to be available in numpy, but can't find it. I have written my own, >> but just curious if anybody knows of such function in numpy. >> > > Derivatives are a property of functions. Since numpy provides > representations of arrays not functions, how would you expect this to work? > > To be more concrete, what you you expect the derivative of > [ [ 1 2 ] > [ 3 4 ] > ] > to be? > > Or do you have in mind some array representation of the coefficients of > a function of some pre-defined type - like a polynomial? Typically, when people ask questions like this, they have a uniform, discretely sampled version of the function, and they want the (forward,central,backward)-difference approximation of the derivative. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mail at timgolden.me.uk Thu Jul 24 10:50:40 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 24 Jul 2008 15:50:40 +0100 Subject: Python / PAMIE In-Reply-To: References: Message-ID: <488896C0.7000007@timgolden.me.uk> frankrentef wrote: > Can someone help with a PAMIE issue? I'm new to Python / PAMIE and > they seem like great tools but to be honest I'm finding that no > responses to questions can be found (Experts Exchange, etc.) I'm > hoping this will be the place. > > I tried to duplicate the authors "ie.writeScript" function shown at > > http://showmedo.com/videos/video?name=pythonMarchettiPamie3&fromSeriesID=25 I'd rather you posted the code you've tried. I'm not too keen on viewing a video just to get hold of a piece of code, and in any case that would only show me what the author's done. We need to see what you've done, and what the traceback was. Would you mind posting some code, please? Thanks TJG From rtw at freenet.co.uk Sat Jul 26 15:02:59 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 26 Jul 2008 14:02:59 -0500 Subject: Questions on 64 bit versions of Python References: <488aec52$0$21481$9b622d9e@news.freenet.de> <488B570C.8070202@v.loewis.de> Message-ID: Martin v. L?wis wrote in news:488B570C.8070202 at v.loewis.de in comp.lang.python: >> I just tested, I built a default C# forms app using the "AnyCPU" >> option and it ran as a 64 bit app (no *32 in Task Manager), this is >> on XP64. >> >> I have though installed the AMD64 version of the 2.0 framework and >> AFAICT neither windows update or the Visual Studio installer >> will install that by default, you have to go get it your self. > > Interesting. I only tested this in .NET 1.1. Perhaps they have changed > something since. How exactly did you launch the program? Does it change > if you use Python's os.spawn* to launch it? If subprocess.call will do then I can report the same results, a 64 bit process, using 32 bit CPython 2.5 to call it. Also if the programme (C#) is built with the 3.5 framework I get the same results, however interestingly there is no 64 bit build for the 3.5 framework (or at least I was unable to find one). Rob. -- http://www.victim-prime.dsl.pipex.com/ From rpw3 at rpw3.org Tue Jul 22 08:23:22 2008 From: rpw3 at rpw3.org (Rob Warnock) Date: Tue, 22 Jul 2008 07:23:22 -0500 Subject: The Importance of Terminology's Quality References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: Martin Gregorie wrote: +--------------- | John W Kennedy wrote: | > No, the "thunks" were necessary at the machine-language level to | > /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. | | Are you sure about that? +--------------- I don't know if John is, but *I* am! ;-} +--------------- | I used Algol 60 on an Elliott 503 and the ICL 1900 series back when | it was a current language. The term "thunking" did not appear in either | compiler manual nor in any Algol 60 language definition I've seen. +--------------- It wouldn't have been. Thunks were something used by Algol 60 *compiler writers* in the code generated by their compilers to implement the semantics of Algol 60 call-by-name, but were not visible to users at all [except that they allowed call-by-name to "work right"]. +--------------- | A60 could pass values by name or value and procedures by name. That | was it. Call by name is what is now referred to as reference passing. +--------------- (*sigh*) NO, IT IS NOT!!! Please go read the following: http://en.wikipedia.org/wiki/Thunk http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_name http://en.wikipedia.org/wiki/Jensen%27s_Device +--------------- | [Algol 60] did not have a mechanism for declaring anonymous procedures. +--------------- Quite correct, but completely off the mark. While an Algol 60 *user* could not declare an anonymous procedure, the *implementation* of an Algol 60 compilers required the ability for the compiler itself to generate/emit internal anonymous procedures, to wit, the above-mentioned thunks, sometimes creating them dynamically during the procedure call. [Actually, a pair of them for each actual argument in a procedure call.] +--------------- | That, like the incorporation of machine code inserts, would have been | a compiler-specific extension, so it is a terminological mistake to | refer to it without specifying the implementing compiler. +--------------- Again, "incompetent, irrelevant, and immaterial" [as Perry Mason used to so frequently object during trials]. Thunks were not "extensions" to Algol 60 compilers; they were part of the basic implementation strategy *within* Algol 60 compilers, necessary because of the semantics required by call-by-name. Basically, in Algol 60, each parameter must be passed [in general, that is, one can optimize away many special cases] as *two* closures -- conventionally called "thunks" by Algol 60 compiler writers -- one for "getting" (evaluating) and the other for "setting" the parameter [if the parameter was a "place" in Common Lisp terms, else an error was signalled]... IN THE CALLER'S LEXICAL ENVIRONMENT!! The big deal was two-fold: (1) each time a formal parameter was *referenced* in a callee, the expression for the actual parameter in the caller had to be *(re)evaluated* in the *caller's* lexical environment, and the value of that (re)evaluation used as the value of the referenced formal parameter in the callee; and (2) if a variable appeared twice (or more) in a parameter list, say, once as a naked variable [which is a "place", note!] and again as a sub-expression of a more complicated parameter, then setting the formal parameter in the *callee* would *change* the value of the actual parameter in the caller(!!), which in turn would change the value of the *other* actual parameter in the caller the next time it was referenced in the callee. The above-referenced "Jensen's Device" shows how this can be used to do "very tricky stuff". A simpler and shorter example is here: http://www.cs.rit.edu/~afb/20013/plc/slides/procedures-07.html Because the actual parameters in the callee had to be evaluated in the *caller's* lexical environment -- and because Algol 60 was fully recursive, allowed nested procedure definitions, and could pass "local" procedures as arguments -- efficient implementation of Algol 60 procedure calls almost necessitated placing the bodies of the compiler-generated actual parameter thunks on the caller's dynamic stack frame [or at least call instructions *to* the thunks which could pass the current lexical contours as sub-arguments]. Knuth's nasty "man or boy test" stressed this to the limit: http://en.wikipedia.org/wiki/Man_or_boy_test -Rob p.s. IIRC [but it's been a *long* time!], the ALGOL-10 compiler for the DEC PDP-10 passed each actual parameter as the address of a triple of words, of which the first two were executable and the third could be used to store a variables value (simple case) or to pass the lexical contour (more complicated case). When the callee needed to reference (evaluate) an argument, it used the PDP-10 XCT ("execute") instruction to execute the first word of the block, which was required to deliver the value to a standard register [let's say "T0", just for concreteness], and if the callee wanted to *set* an argument, it executed the *second* word pointed to by the passed address, with the new value also in a defined place [again, let's use T0]. So to implement "X := X + 1;" in the callee, the compiler would emit code like this: MOVE T1,{the arg (address) corresponding to "X"} XCT 0(T1) ; fetch the current value of X into T0. ADDI T0, 1 ; increment it XCT 1(T1) ; execute the "setter" for X. Now in the case where the actual parameter in the caller was a simple global variable, call it "Y", then the address passed as the arg could be the following "YTHNK" in static data space: YTHNK: MOVE T0,.+2 ; one-instruction "getter" MOVEM T0,.+1 ; one-instruction "setter" Y: BLOCK 1 ; the actual place where the value "Y" lives Whereas if the argument being passed were some more complicated expression, such as an array reference or a reference to a local procedure in the caller, then the 3-word arg block would be passed on the stack and the passed address would point to this [possibly dynamically-constructed] triple, where PUSHJ is the PDP-10 stack- oriented subroutine call instruction: PUSHJ P,{lambda-lifted getter code} PUSHJ P,{lambda-lifted setter code} EXP {lexical contour info needed for getter/setter to work} Efficient for the simple case; slow-but-correct for the messy case. ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From kyosohma at gmail.com Mon Jul 14 17:32:14 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 14 Jul 2008 14:32:14 -0700 (PDT) Subject: Using Python To Launch Python References: Message-ID: <77f3294e-4c1d-42cc-804b-ed1d5ad0a5a4@f63g2000hsf.googlegroups.com> On Jul 14, 4:01?pm, aha wrote: > Hello All, > ? I have a situation where I can count on a Python installation being > available on a system, but I can't count on it being a version of > Python needed by my application. ?Since my application has it's own > version of Python installed with it how should I use the system Python > to launch the version of Python that launches my Application. ?Yes, > this is a convoluted process, but not all Pythons are built the > same :) > > Right now I am leaning towards using exec to start a new process, but > I thought I would check to see if anyone else has had the need to > perform a task similar to this one. > > AHA As an alternative, you may be able to use the subprocess module of Python to do this too. Mike From angelaki at mpifr-bonn.mpg.de Fri Jul 25 08:56:51 2008 From: angelaki at mpifr-bonn.mpg.de (Emmanouil Angelakis) Date: Fri, 25 Jul 2008 14:56:51 +0200 Subject: Calling external program from within python Message-ID: <4889CD93.10908@mpifr-bonn.mpg.de> Hi, I am tryiong to do something obviously trivial such as: I have a c program called "tsys2list" that when it is ran it asks the user to give the value of "tcal" which is a variable. I want to call the "tsys2list" from within a pyrthon script lets call it "gamma.py" >>>but<<< I want to pass the value of "tcal" to th eprogram automatically and not by interacting with the keyboard. How do I do that? thanks i advance! manolis From detlev at die-offenbachs.de Sat Jul 5 03:51:04 2008 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 05 Jul 2008 09:51:04 +0200 Subject: ANN: eric 4.1.6 released Message-ID: Hi, this is to inform all of you about the immediate availability of eric 4.1.5. It is a bug fix release. As usual, it is available via http://www.die-offenbachs.de/eric/index.html. Eric4 is a Python IDE written using PyQt4 and QScintilla2. It comes with batteries included. For more details see the link above. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 10 03:39:34 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 10 Jul 2008 09:39:34 +0200 Subject: Impossible to change methods with special names of instances of new-style classes? In-Reply-To: <429cbef9-0027-4717-a39f-d7e7599e07ae@x35g2000hsb.googlegroups.com> References: <429cbef9-0027-4717-a39f-d7e7599e07ae@x35g2000hsb.googlegroups.com> Message-ID: <4875bc82$0$14076$426a34cc@news.free.fr> samwyse a ?crit : > On Jul 8, 4:56 pm, Joseph Barillari wrote: > >> My question is: did something about the way the special method names are >> implemented change for new-style classes? > > Just off the top of my head, I'd guess that it's due to classes > already having a default __call__ method, >>> object.__dict__.keys() ['__setattr__', '__reduce_ex__', '__new__', '__reduce__', '__str__', '__getattribute__', '__class__', '__delattr__', '__repr__', '__hash__', '__doc__', '__init__'] No __call__ method here. > used when you instatiate. The __call__ method used to instanciate a class is actually the metaclass __call__ method. >>> class MyType(type): ... def __call__(self, *args, **kw): ... print "pikaboo" ... return type.__call__(self, *args, **kw) ... >>> class MyClass(object): ... __metaclass__ = MyType ... >>> MyClass() pikaboo <__main__.MyClass object at 0x8334eec> >>> From coolman.guron at gmail.com Tue Jul 29 11:28:56 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Tue, 29 Jul 2008 08:28:56 -0700 (PDT) Subject: pygtk treview, ListStore not displaying properly References: <5cd417cf-4169-4805-8317-fb82c7e7be90@x29g2000prd.googlegroups.com> Message-ID: finally i solved it. This for any googler who comes this way def show_sync_wind(self,obj, data = None): t = Template.select(Template.q.synced == '0') self.synclstore = gtk.ListStore(str,str,str,str,str) x = 0 cr = gtk.CellRendererText() col = gtk.TreeViewColumn('#', cr); col.set_attributes(cr, text=0)#<------ attaches col to the 0`th item of liststore col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(0) self.tv.append_column(col) self.sno_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Title', cr); col.set_attributes(cr, text=1) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(1) self.tv.append_column(col) self.title_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Section', cr); col.set_attributes(cr, text=2) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(2) self.tv.append_column(col) self.section_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Category', cr); col.set_attributes(cr, text=3) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(3) self.tv.append_column(col) self.category_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Sync', cr); col.set_attributes(cr, text=4) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(4) self.tv.append_column(col) self.sync_col = col self.tv.set_model(self.synclstore) self.tv.set_headers_clickable(True) #self.tv.set_expander_column(self.title_col) for y in t: x = x+1 row = self.synclstore.append([str(x),y.title,y.section.name,y.category.name,y.synced]) self.sync_window.show() From alif016 at gmail.com Mon Jul 21 19:38:32 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Mon, 21 Jul 2008 18:38:32 -0500 Subject: Converting List of String to Integer In-Reply-To: References: Message-ID: <48851DF8.6070807@gmail.com> Samir wrote: > For my small list, I didn't notice a > discernible increase in speed, but I may have to try it with a larger > list size. > About speed, and memory consumption: List comprehensions (http://docs.python.org/tut/node7.html#SECTION007140000000000000000) are just shortcuts for for-loops. I do not believe there is any speed benefit. However, there are generators, they basically load one part of an iterator (a list in this case) at a time, this can greatly reduce memory usage. Have a look at PEP 289: http://www.python.org/dev/peps/pep-0289/ Here is the list comprehension as a generator (actually 2): n = ((int(i) for i in k) for k in a) Note, you can't just print a generator, it only computes something when needed: >>> print n You can, however iterate over it: In [2]: for k in n: ....: for i in k: ....: print i, ....: ....: 1 2 3 4 5 6 7 8 9 0 In [3]: n = ((int(i) for i in k) for k in a) In [49]: list(n) Out[49]: [, , , ] Each sub-list is a generator too! In [50]: n = ((int(i) for i in k) for k in a) In [51]: for i in list(n): # list() converts the variable n to a list ....: list(i) ....: ....: Out[51]: [1, 2] Out[51]: [3] Out[51]: [4, 5, 6] Out[51]: [7, 8, 9, 0] This is only going to make a difference if you were dealing with a *very* large data set. I thought I would show you even if you never user them, for learning purposes. Note: a generator is one way, redefine it every time you use it. -- Andrew From fredrik at pythonware.com Wed Jul 16 10:31:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 16:31:42 +0200 Subject: Best Python packages? In-Reply-To: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> Message-ID: Ben Sizer wrote: > make my development a lot easier. Knowing what kind of development you do might help, of course. Some libraries are excellent in some contexts and suck badly in others... Looking at things that larger projects and distributions use can also be a good idea. For example, if you're doing scientific stuff, go directly to enthought.com. If you're doing web stuff, look at the libraries big Django applications use. Etc. From ethan at stoneleaf.us Tue Jul 15 18:32:30 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 15 Jul 2008 14:32:30 -0800 Subject: Measure class, precision, significant digits, and divmod() In-Reply-To: References: Message-ID: <487D257E.7080506@stoneleaf.us> Ken Starks wrote: > Ethan Furman wrote: > >> Hey all. >> > > >> >> As I have mentioned before, I am making this Measure class for two >> reasons: experience with unit testing, I like playing with numbers, I >> am unaware of anything like this having yet been done (okay, three >> reasons ;). >> > > >> >> Any and all feedback welcome, particularly from anyone who might >> actually use the Measure class. ;) >> >> ~Ethan > [snip] > +++++++++++++++++++++++++++++++++++++++ > > My principal interest in your work, however, is in the use of > unit tests as a pedagogical method of teaching programming, whether > self-taught or taught by an instructor. > > The students would be taught how to __run__ a unit test-suite > at as early an opportunity as possible. I can't see > why an eleven or twelve year old should not be able to cope > with it in hour one or two of a carefully structured course. > > What is needed for such an approach is a copy--in a public > place--of your unit tests for all methods > that are really part of the funtionality; together with > blanked-out definitions for them (i.e just the first line, > any in-code documentation, and 'pass' ). > > You would not include any 'internal' methods that are merely the way > __you__ happened to achieve the result. > > The programming 'exercise' would then be for the students, or > groups of students, to roll their own version until their code > passed all the unit tests. Definitely an interesting idea. I'm not sure if I should be worried about the 12-13 year old students tackling a complex class such as a new number class, or if I should prepare to be embarrased by how much simpler they are able to make equivalent code! ;) At any rate, once I'm done the code will be released under a very friendly license, so you'll be free to do that should you desire to. ~Ethan From arsyed at gmail.com Thu Jul 24 01:22:58 2008 From: arsyed at gmail.com (arsyed) Date: Thu, 24 Jul 2008 01:22:58 -0400 Subject: PyOpenGL Tutorial? In-Reply-To: <1216843629.18962.16.camel@generator> References: <1216843629.18962.16.camel@generator> Message-ID: <9a2cc7a70807232222t7d401279t5d91d5b8a9220ceb@mail.gmail.com> On Wed, Jul 23, 2008 at 4:07 PM, Clay Hobbs wrote: > I need a tutorial for PyOpenGL (specifically, to be used with wxPython). > I searched with Google and didn't find one. Does anybody know where one > is? > > -- Ratfink > > -- > http://mail.python.org/mailman/listinfo/python-list > Showmedo recently put up a tutorial screencast of using wx, opengl, python to build a molecular viewer: http://showmedo.com/videos/series?name=vXJsRwlBX Also, see: http://www.siafoo.net/browse?keyword_id=245 From digetl.try at gmail.com Sat Jul 26 06:04:52 2008 From: digetl.try at gmail.com (raja) Date: Sat, 26 Jul 2008 03:04:52 -0700 (PDT) Subject: Superfruit strategy Message-ID: <4cd96b23-ec87-4ca5-b401-6b70c1a98c0b@y22g2000prd.googlegroups.com> Six Elements of Superfruit Success Buy new book of expert insights! http://food-drinks.page.tl/ From jwashin at vt.edu Tue Jul 22 07:48:01 2008 From: jwashin at vt.edu (Jim Washington) Date: Tue, 22 Jul 2008 07:48:01 -0400 Subject: xpathEval fails for large files In-Reply-To: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> References: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> Message-ID: <4885C8F1.6070904@vt.edu> Kanchana wrote: > Hi, > > I tried to extract some data with xpathEval. Path contain more than > 100,000 elements. > > doc = libxml2.parseFile("test.xml") > ctxt = doc.xpathNewContext() > result = ctxt.xpathEval('//src_ref/@editions') > doc.freeDoc() > ctxt.xpathFreeContext() > > this will stuck in following line and will result in high usage of > CPU. > result = ctxt.xpathEval('//src_ref/@editions') > > Any suggestions to resolve this. > > Is there any better alternative to handle large documents? One option might be an XML database. I'm familiar with Sedna ( http://modis.ispras.ru/sedna/ ). In practice, you store the document in the database, and let the database do the extracting for you. Sedna does XQuery, which is a very nice way to get just what you want out of your document or collection of documents. Good: It's free (Apache 2.0 license) It's cross-platform (later Windows x86, Linux x86, FreeBSD, MacOS X) It has python bindings (zif.sedna at the cheese shop and others). It's pretty fast, particularly if you set-up indexes. Document and document collection size are limited only by disk space. Not so good: Sedna runs as a server. Expect to use in the range of 100M of RAM per database. A database can contain many many documents, so you probably only want one database, anyway. Disclosure: I'm the author of the zif.sedna package, and I'm interpreting the fact that I have not received much feedback as "It works pretty well" :) - Jim Washington From grante at visi.com Tue Jul 22 16:23:09 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 22 Jul 2008 15:23:09 -0500 Subject: proliferation of computer languages References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> <40429b65-23a0-489b-b5fd-ae6b8eee607d@t54g2000hsg.googlegroups.com> Message-ID: On 2008-07-22, szr wrote: > J?rgen Exner wrote: >> Chris Rathman wrote: >> >>> I can't say that I see any particular point to the essay. >> >> You must be new here. There never is any particular point to >> Xah Lee's rantings except to cross-post borderline topics to >> borderline relevant NGs and then lay back and enjoy the >> ensuing slaughter. > > Admittedly, I'm not all too familiar with his postings, but on > a general note, isn't it possible that someone else might not > see it the same as you do? I really didn't see anything really > sinister about the posting or it's content. That's the, uh, "beauty" of Xah Lee's posts. There's enough "there" there to suck people into what they think is going to be a conversation. But it's not really a conversation. He doesn't really read (or doesn't comprehend) responses to his posts and will just continue to ramble on in a somewhat insulting, half-rational stream of utterly opaque metaphors that he thinks makes him sound deeply philosphical. It has been theorized that he's an AI project. > It may very well be someone attempting to create a > conversation, someone who may not be generally well received a > lot of the time I gather. Quite a few people here in c.l.p put forth a a lot of effort (for Usenet, anyway) trying to have a reasonable exchange with xah lee, but it seems to be pointless. He's a perpetual critic who looks down his nose at everything and thinks he could do everything better than everybody else (not that he has actually ever _done_ anything, AFAICT). > Also, if have such a distaste for his postings, you are free > to ignore them as well. That said, I am all for alerting > someone of something which may be a complete waste of their > time, It's not a waste of your time if you find him entertaining, but I wouldn't expect any actual conversation where he reads and understands your replies and responds to them in a rational manner. > but in this case it feels like you are projecting your > own dislike for the OP. Unless the OP really is deserving of > such branding (in which case I'd stand corrected), I don't > think it is reason enough to tell others not to read of his > work just because you aren't particularly fond of it. > > Perhaps citing an actual example illustrating a reason to > avoid him like the plague would of helped :-) google groups should be able to find you plenty of examples both here and in perl groups. -- Grant Edwards grante Yow! I feel partially at hydrogenated! visi.com From mnordhoff at mattnordhoff.com Thu Jul 10 18:31:02 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 10 Jul 2008 22:31:02 +0000 Subject: redirecting output of process to a file using subprocess.Popen() In-Reply-To: <6bed3372-e049-4301-9d6b-6b7cf0a4c2d9@y21g2000hsf.googlegroups.com> References: <515ad1dd-15b0-4f7a-8ea2-87e0bb0cb47e@f36g2000hsa.googlegroups.com> <6bed3372-e049-4301-9d6b-6b7cf0a4c2d9@y21g2000hsf.googlegroups.com> Message-ID: <48768DA6.6040709@mattnordhoff.com> skeept wrote: > On Jul 9, 7:32 pm, rpar... at gmail.com wrote: >> I am trying to redirect stderr of a process to a temporary file and >> then read back the contents of the file, all in the same python >> script. As a simple exercise, I launched /bin/ls but this doesn't >> work: >> >> #!/usr/bin/python >> import subprocess as proc >> import tempfile >> name = tempfile.NamedTemporaryFile(mode='w+b') >> print 'name is '+ name.name >> >> cmd = [] >> cmd.append('/bin/ls') >> cmd.append('-l') >> cmd.append('/tmp') >> p = proc.Popen(cmd, stdout=name, stderr=proc.STDOUT, close_fds=True) >> while True: >> ret = p.poll() >> if (ret is not None): >> output = name.readlines() >> print 'out = ', output >> break >> >> $python sub.py >> name is /tmp/tmpjz4NJY >> out = [] >> >> I tried calling flush() on the file object but this didn't help >> either. Tried closing and re-opening the file, but closing the file >> object results in it getting deleted. Can the above be made to work by >> using tempfiles? >> >> thanks > > > your script works just fine. > The problem is that you have to move to the beggining of the file to > read the actual contents of > the file. > name.seek(0) > > The whole program would be: > > #!/usr/bin/python > import subprocess as proc > import tempfile > name = tempfile.NamedTemporaryFile(mode='w+b') > print 'name is '+ name.name > > cmd = [] > cmd.append('/bin/ls') > cmd.append('-l') > cmd.append('/tmp') > p = proc.Popen(cmd, stdout=name, stderr=proc.STDOUT, close_fds=True) > while True: > ret = p.poll() > if (ret is not None): > name.seek(0) > output = name.readlines() > print 'out = ', output > break This is an aside, but why the loop? ... p = ... p.wait() name.seek(0) ... (p.wait() returns p.returncode, just like p.poll() does, but you aren't using it anyway...) -- From timothywayne.cook at gmail.com Mon Jul 14 12:40:00 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Mon, 14 Jul 2008 13:40:00 -0300 Subject: Unicode confusion Message-ID: <1216053600.3028.59.camel@localhost.localdomain> Hi All, I'm not clear on how to use the unicode module. I need to be able to use certain characters such as the degree symbol and the mu symbol, i.e.: units = <"?"> if I say units=unicode("?"). I get UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128) If I try x=unicode.decode(x,'utf-8'). I get TypeError: descriptor 'decode' requires a 'unicode' object but received a 'str' What is the correct way to interpret these symbols that come to me as a string? Thanks, Tim -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. Home page: https://launchpad.net/oship/ Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From irmen.NOSPAM at xs4all.nl Wed Jul 2 17:31:00 2008 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 02 Jul 2008 23:31:00 +0200 Subject: Pyro: ProtocolError('connection failed') In-Reply-To: <6d223oFetjoU1@mid.uni-berlin.de> References: <6d223oFetjoU1@mid.uni-berlin.de> Message-ID: <486bf396$0$14360$e4fe514c@news.xs4all.nl> Diez B. Roggisch wrote: > > THis is just a guess - but it seems that somehow you don't bind your > pyro objects to the NIC's IP address, but to localhost (127.0.0.1) - > which of course won't work. That never happened to me though, try and > see the pyro docs on how to prevent/control to which IP a proxy is bound. > This problem has been discussed quite a bit on the Pyro mailinglist. What's happening is that Pyro is indeed binding the server on the loopback adapter (making it invisible from the outside). It does this because of what I (and several others) believe to be a bug in the default hosts file of many linux distributions: the local hostname resolves to the loopback adapter's address 127.0.0.1 instead of a sensible IP address. Pyro provides some ways to work around this issue, if you can't or won't fix the /etc/hosts file. --irmen PS I've replied to the original poster by private email conversation. I'm filtering newsgroups posts that originate from google groups, hence I only saw this message because of Diez's reply. From python at rcn.com Mon Jul 28 19:05:58 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 28 Jul 2008 16:05:58 -0700 (PDT) Subject: seemingly simple list indexing problem References: Message-ID: <999589a9-e1bb-4a64-801c-74ce060bc0c6@i24g2000prf.googlegroups.com> [Ervan Ensis] > I have a list like [108, 58, 68]. ?I want to return > the sorted indices of these items in the same order > as the original list. ?So I should return [2, 0, 1] One solution is to think of the list indexes being sorted according the their corresponding values in the input array: >>> s = [ 108, 58, 68 ] >>> sorted(range(len(s)), key=s.__getitem__) [1, 2, 0] Raymond From tjreedy at udel.edu Wed Jul 30 12:22:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jul 2008 12:22:56 -0400 Subject: Correct Attribute Assignment Methodology? In-Reply-To: <1217355766.2930.10.camel@localhost.localdomain> References: <1217355766.2930.10.camel@localhost.localdomain> Message-ID: Tim Cook wrote: > Say I have these classes: > > class Parent(object): > """Parent is abstract""" > a=None > def showA(): > return self.a > > class Child(Parent): > """inherits a and showA from Parent""" > > def __init__(self,a,b): > self.a=a > self.b=b > > def showAB(): > return self.a,self.b > > > class GrandChild(Child): > """inherits all of the above""" > > def __init__(self,a,b,c): > self.a=a > self.b=b > """should this be Child.__init__(a,b)? or Child.__init__(b)?"" Child.__init__(self,a,b) # requires all three params. > """if so; why? if not why not?""" In this simple case, I would probably do what you did. But a reason to call the baseclass init would be to not repeat yourself and keep the derived class in sync. Suppose, for instance, Child.__init__ had 'self.frob = math.sin(a) + math.cos(b) - math.sqrt(a*a+b*b)', and then you realize that the formula needs to be changed. Better to have it in one place. > self.c=c > > Thanks for answering these very basic questions but I am not certain > about the correct way. I know that in Python, assignment in the > GrandChild class will work but is that correct? From gherron at islandtraining.com Thu Jul 17 14:33:28 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 17 Jul 2008 11:33:28 -0700 Subject: properly delete item during "for item in..." In-Reply-To: References: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> <487F770D.8070405@islandtraining.com> Message-ID: <487F9078.2000205@islandtraining.com> Ratko wrote: > On Jul 17, 9:57 am, mk wrote: > >> Gary Herron wrote: >> >>> You could remove the object from the list with >>> del myList[i] >>> if you knew i. HOWEVER, don't do that while looping through the list! >>> Changing a list's length will interact badly with the for loop's >>> indexing through the list, causing the loop to mis the element following >>> the deleted item. >>> >> Jumping into a thread, I know how not to do it, but not how to do it >> properly? >> >> Iterating over a copy may _probably_ work: >> >> >>> t=['a', 'c', 'b', 'd'] >> >>> >> >>> for el in t[:]: >> del t[t.index(el)] >> >> >>> t >> [] >> >> However, is it really safe? Defining safe as "works reliably in every >> corner case for every indexable data type"? >> >> Con: suppose the data structure t is really, really big. Just deleting >> some items from t temporarily doubles the memory consumption. >> > > > > Would this work (safely) then? It does in my test cases but that of > course doesn't prove it works in a general case... > > for item in myList: > myList.remove(item) > No. Same problem, The for loop iterates through the list by keeping and incrementing an internal index. Any modification of the list does not change the index correspondingly. One proper way: newList = [] for item in myList: if ... whatever... newList.append(item) myList = newList Another, using list comprehension (it's the same thing really as the above): myList = [item for item in myList if ... whatever...] > > For dictionaries we can just iterate over values() or items() as > opposed to itervalues() or iteritems() since that's technically a copy > of values or items in the dict, right? > No! In fact the whole point of iteritems and itervalues and iterkeys is that they *DO NOT* make copies, so changing the dictionary out from under them is a programming error. If you use dict.items(), dict.keys() or dict.values(), then you're OK, because these methods *do* create new lists for both. Gary Herron > > R > > -- > http://mail.python.org/mailman/listinfo/python-list > From mseverin at bedlamgames.com Fri Jul 25 12:18:48 2008 From: mseverin at bedlamgames.com (Matthew Severin) Date: Fri, 25 Jul 2008 12:18:48 -0400 Subject: Trouble with rpdb2 and winpdb debuggers in embedded Python script Message-ID: Having some trouble getting rpdb2 and winpdb running properly with Python embedded in a C++ project. Our implementation has a number of C++ classes associated with Python classes. I am able to attach to the embedded script with the debugger and the program freezes and waits. However, when I step, next or go with the debugger, it instantly gives control back to C++ and doesn't step nicely through the python. Similarly, if I set a breakpoint, the program pauses momentarily but then doesn't break properly in the debugger. Just wondering if anyone had encountered anything similar, or had an idea what we are doing wrong. Thanks, Matt From leo_365 at yahoo.com Thu Jul 24 11:24:00 2008 From: leo_365 at yahoo.com (leo davis) Date: Thu, 24 Jul 2008 08:24:00 -0700 (PDT) Subject: need help with introducing more traffic Message-ID: <632875.28836.qm@web51808.mail.re2.yahoo.com> Hiya, I found this code snippet(reference http://www.goldb.org) and wish to do more with it than just send out a Http Get request.I would like to introduce more traffic -say by downloading files,crawling through all the links,logging in?etc etc,and wish to see how the web server reacts.I'm trying to stress the server to its limits....appreciate if anyone could provide me code/ideas to inject into this. the website -http://ftp.ruby-lang.org/pub/ruby/binaries/mswin32/ selected as example has many downloads.i tried from urllib import urlretrieve urlretrieve('http://ftp.ruby-lang.org/pub/ruby/binaries/mswin32/ruby-1.6.4-i586-mswin32.zip','ruby-1.6.4-i586-mswin32.zip'),but didnt work..... [QUOTE]import time import os import sys, urllib, re import httplib #from urllib import urlretrieve import urllib2 from threading import Thread class LoadManager: ??? def __init__(self): ??????? self.thread_refs = [] ??????? self.msg = ('localhost') # default ??? ??? def stop(self): ??????? for thread in self.thread_refs: ??????????? thread.stop() ??????????? ??? def start(self, threads=1, interval=0, rampup=1): ??????? for i in range(threads): ??????????? spacing = (i * (float(rampup) / float(threads))) ??????????? time.sleep(spacing) ??????????? agent = LoadAgent(interval, self.msg) ??????????? agent.setDaemon(True) ??????????? agent.start() ??????????? # print 'started thread # ' + str(i + 1) ??????????? self.thread_refs.append(agent) ??????? class LoadAgent(Thread): ??? def __init__(self, interval, msg): ??????? Thread.__init__(self) ??????? self.running = True ??????? self.interval = interval ??????? self.msg = msg ??????? ??? def stop(self): ??????? self.running = False ??????? ??? def run(self): ??????? while self.running: ??????????? start_time = time.time() ??????????? if self.send(self.msg): ??????????????? end_time = time.time() ??????????????? raw_latency = end_time - start_time ??????????????? expire_time = (self.interval - raw_latency) ??????????????? latency = ('%.3f' % raw_latency) ??????????????? print latency ??????????? else: ??????????????? raw_latency = 0 ??????????????? expire_time = (self.interval - raw_latency) ??????????? if expire_time > 0: ??????????????? time.sleep(expire_time) ??????????????? ??? def send(self, msg): ??????? ??????? try: ??????????? ??????????? req = urllib2.Request(msg) ??????????? response = urllib2.urlopen(req) ??????????? the_page = response.read() ??????????? ??????????? return True ??????? except: ??????????? print 'failed request' ??????????? return False ? def main(): ??? # sample usage ??? manager = LoadManager() ??? manager.msg = ('http://ftp.ruby-lang.org/pub/ruby/binaries/mswin32') ??? manager.start(threads=5, interval=2, rampup=2) if __name__ == '__main__': ??? main()[/QUOTE] -------------- next part -------------- An HTML attachment was scrubbed... URL: From larry.bates at websafe.com` Tue Jul 15 19:06:43 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 18:06:43 -0500 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: kjhishere at gmail.com wrote: > I need to know if I'm running on 32bit or 64bit ... so far I haven't > come up with how to get this info via python. sys.platform returns > what python was built on ... but not what the current system is. > > I thought platform.uname() or just platform.processor() would have > done it, but python returns an empty string on windows. Any ideas? > > Thanks, Ken How about sys.maxint? 64 bit returns 9223372036854775807 on 64-bit Linux for me. -Larry From anishchapagain at gmail.com Mon Jul 21 08:30:19 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Mon, 21 Jul 2008 05:30:19 -0700 (PDT) Subject: error Message-ID: <5f4395d7-9f5c-45c3-b137-655e5c618b8c@8g2000hse.googlegroups.com> from Tkinter import * root=Tk() f=Frame(root,height=200,width=200) b=Button(f,text="quit",command=f.quit) f.pack() root.mainloop() -------------------------------------------------- from Tkinter import * import sys root=Tk() f=Frame(root,height=200,width=200) b=Button(f,text="quit",command=sys.exit) f.pack() root.mainloop() I am wondering that why the button after clikcing is not closing the window..please any suggestion.. i tries command=f.quit, sys.quit also.. if there is something i'm missing please help From max at alcyone.com Thu Jul 31 00:27:53 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Jul 2008 21:27:53 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > I don't know if you can read minds, but you seem to have a lot of > trouble reading words. > > Can you read "it would be nice to be able to write ..."? Can you > understand what it means? Can you understand that it does *not* mean, > "one *should* be able to write ..."? You're sure going on about a distinction without a difference for a guy who childishly likes to call other people names. A reasonable person would have long ago moved on instead of blaming others for not immediately intuiting your thoughts, rather than straightforwardly reading your words. Which, by the way, includes at least three people other than myself. But I'll bet the mindless namecalling is really working out for you. Go, team, go! -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis You are my martyr / I'm a vestige of a revolution -- Lamya From gherron at islandtraining.com Wed Jul 16 11:16:04 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 16 Jul 2008 08:16:04 -0700 Subject: Angle brackets in command-line arguments? In-Reply-To: <52f1cde3-6240-46b0-8b03-478454e87688@b1g2000hsg.googlegroups.com> References: <52f1cde3-6240-46b0-8b03-478454e87688@b1g2000hsg.googlegroups.com> Message-ID: <487E10B4.7010103@islandtraining.com> Keith Hughitt wrote: > Hi all, > > I am using someone else's script which expects input in the form of: > > ./script.py arg2 > > I was wondering if the angle-brackets here have a special meaning? It > seems like > they specify an input and output stream to use in place of the > console. I could not > find anything in the python manual or Python in a Nut-shell though. > > Anyone know? > > > Thanks, > Keith > -- > http://mail.python.org/mailman/listinfo/python-list > In most Unix/Linux and related OS shells, the angled brackets *do* specify input and output streams as you surmise. However, they are *not* seen by the script as command line arguments. (And they are *not* brackets, and do not need to be matched. ) For any command, cmd < file redirects the contents of file to cmd's standard input, which in Python is accessed by reading from sys.stdin (use input or raw_input or sys.stdin.read...) Also for any command, cmd > file redirects the output of cmd to the named file. In Python this can be accessed using print, sys.stdout.write, ... Anything written to sys.stderr will not be caught by the ">" redirection, ans so will probably end up on the screen instead of in file. Also various shells will provide similar functionality using a variety of similar syntaxes: <<, >>, >&, and |, and so on. Gary Herron From dear.jay.logan at gmail.com Sun Jul 27 20:48:08 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Sun, 27 Jul 2008 17:48:08 -0700 (PDT) Subject: Where is the correct round() method? References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> Message-ID: <1aa8d56d-2deb-4c31-93b0-b20008ddb7d3@l42g2000hsc.googlegroups.com> On Jul 27, 7:58?pm, Gary Herron wrote: > josh logan wrote: > > Hello, > > > I need a round function that _always_ rounds to the higher integer if > > the argument is equidistant between two integers. In Python 3.0, this > > is not the advertised behavior of the built-in function round() as > > seen below: > > >>>> round(0.5) > > > 0 > > >>>> round(1.5) > > > 2 > > >>>> round(2.5) > > > 2 > > Huh? > > ?>>> round(2.5) > 3.0 > > Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo > CPU". ?What system are you on? > > It could be that 2.5 is really 2.49999... which would round down to 2, > but on any modern CPU (using IEEE floating point), 2.5 should be > representable exactly. > > However, as with any floating point calculations, if you expect exact > representation or calculations with any numbers, then you are misusing > floating points. > > Gary Herron > > > I would think this is a common need, but I cannot find a function in > > the Python library to do it. I wrote my own, but did I miss such a > > method in my search of the Python library? > > > Thanks > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I should reiterate that I am using Python 3.0 and not Python 2.x. It looks like the behavior round() has changed between these two versions. Here is the documentation for round() in Python 3.0: http://docs.python.org/dev/3.0/library/functions.html#round Of interest in this discussion is the second paragraph, which explains the change: Does anyone know the reason behind this change, and what replacement method I can use to get the original behavior? From straton at lampsacos.demon.co.uk Sat Jul 5 07:13:46 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Sat, 05 Jul 2008 12:13:46 +0100 Subject: Getting a path from a file object In-Reply-To: <3c500ce7-c697-44e9-9f13-f65edc509e1c@a32g2000prf.googlegroups.com> References: <3c500ce7-c697-44e9-9f13-f65edc509e1c@a32g2000prf.googlegroups.com> Message-ID: Andrew Fong wrote: > Newbie question: > > Let's say I open a new file for writing in a certain path. How do I > get that path back? > > Example: > >>>> f = open('/some/path/file.ext') >>>> some_function(f) > '/some/path/file.ext' > > Does some_function(f) already exist? And if not, how would I define > it? > > -- Andrew Read about f.name which is a kind of read-only attribute with caveats in the documentation: http://docs.python.org/lib/bltin-file-objects.html From castironpi at gmail.com Mon Jul 28 14:16:28 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 28 Jul 2008 11:16:28 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> <490769a4-2a48-41dc-a069-2cc003b332a2@b1g2000hsg.googlegroups.com> Message-ID: On Jul 28, 2:26?am, Nikolaus Rath wrote: > castironpi writes: > >> I think you misunderstood him. What he wants is to write > > >> class foo: > >> ? ?def bar(arg): > >> ? ? ? ?self.whatever = arg + 1 > > >> instead of > > >> class foo: > >> ? ?def bar(self, arg) > >> ? ? ? ?self.whatever = arg + 1 > > >> so 'self' should *automatically* only be inserted in the function > >> declaration, and *manually* be typed for attributes. > > > There's a further advantage: > > > class A: > > ? def get_auxclass( self, b, c ): > > ? ? class B: > > ? ? ? def auxmeth( self2, d, e ): > > ? ? ? ? #here, ... > > ? ? return B > > In auxmeth, self would refer to the B instance. In get_auxclass, it > would refer to the A instance. If you wanted to access the A instance > in auxmeth, you'd have to use > > class A: > ? ?def get_auxclass(b, c ): > ? ? ?a_inst = self > ? ? ?class B: > ? ? ? ?def auxmeth(d, e ): > ? ? ? ? ?self # the B instance > ? ? ? ? ?a_inst # the A instance > ? ? ?return B > > This seems pretty natural to me (innermost scope takes precedence), > and AFAIR this is also how it is done in Java. True. Net keystrokes are down in this method. Consider this: class A: def get_auxclass(b, c ): a_inst = self class B: @staticmethod #<--- change def auxmeth(d, e ): self # -NOT- the B instance a_inst # the A instance return B What are the semantics here? Error, No 'self' allowed in staticmethod- wrapped functions. Or, the a instance, just like a_inst? Do you find no advantage to being able to give 'self' different names in different cases? From jeffober at gmail.com Fri Jul 25 07:54:40 2008 From: jeffober at gmail.com (Jeff) Date: Fri, 25 Jul 2008 04:54:40 -0700 (PDT) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> Message-ID: <6c5e878b-8e82-4ffb-bd8a-c673804774fe@x29g2000prd.googlegroups.com> > I'd recommend using 'filter' and list comprehensions. Look at using reduce(). You can collect information about all of the nodes without necessarily building a large, intermediate list in the process. You might get some ideas from here [http://en.wikipedia.org/wiki/ Antiobjects]. From mathieu.prevot at gmail.com Thu Jul 10 16:35:26 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Thu, 10 Jul 2008 22:35:26 +0200 Subject: error with configure (svn 64857) Message-ID: <3e473cc60807101335p74fb61fdn875cdfd6b3826902@mail.gmail.com> Hi, I have the following error when I run configure: checking size of wchar_t... configure: error: cannot compute sizeof (wchar_t) what can I do ? Mathieu From kay.schluehr at gmx.net Mon Jul 14 07:11:03 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 14 Jul 2008 04:11:03 -0700 (PDT) Subject: importing from .pyd References: <3d66daeb-d45a-46be-bd4d-34a2225683d1@2g2000hsn.googlegroups.com> Message-ID: <3d0c2dbb-6835-44c8-b663-ecb8677a46dd@2g2000hsn.googlegroups.com> On 14 Jul., 06:03, moijes12 wrote: > hi > > there is a .pyd file present in the same folder as the script abc.py > by the name foo.pyd .I don't have foo.py .In the script abc.py I try > > import foo > > Error i get is > ImportError: DLL load failed: The specified module could not be found. It looks like the module that was accessed is either corrupt ( unavailable entry point ) or it contains dependencies to other modules which are not available. At least the latter can be checked without access to the source using the DependencyWalker: http://www.dependencywalker.com/ Notice that the message clearly indicates that Python found the module but failed to load it i.e. performing a LoadLibrary() which yielded a NULL pointer. From bruno.42.desthuilliers at websiteburo.invalid Tue Jul 1 11:18:16 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 01 Jul 2008 17:18:16 +0200 Subject: Scope and program structure problems In-Reply-To: <2kck641lali2uenplo8rhp3l9qks3idl03@4ax.com> References: <486a210f$0$15472$426a34cc@news.free.fr> <2kck641lali2uenplo8rhp3l9qks3idl03@4ax.com> Message-ID: <486a4ab8$0$23808$426a74cc@news.free.fr> John Dann a ?crit : > Many thanks for the repsonse - much appreciated. > > And sorry - yes I was probably compounding two separate issues here - > the GUI one and the variable scope one. Maybe the wxPython list would > be the best place to ask more about the GUI side of things. > > Then actually I can simplify my remaining question quite a lot - I > know you've partly answered this already but let me just rephrase > this: > > It must be commonplace to first use a variable or object What difference do you make between a variable and an object in this context ? > within one > function in a module and then want to use it again - perhaps still > with the same value For which definition of "same value" ? Remember, Python has *no* primitive types. Everything is an object. > as in the first function - in a second function. > So what's the recommended Python way round this? This is way too general to give a single straight answer - whatever the language FWIW. Are both function in the same module ? Are they methods of a same object ? Is the first function calling the second or are they totally unrelated ? > If I was using .Net > then I'd be declaring the variables/objects explicitly I personnally find the assignment, import, class and def statements (all having a binding behaviour) to be rather explicit. > and could set > their scope according to how/where they were declared. Names bound at the top-level are globals to the module. Names bound within a function (including arguments) are locals, unless there has been a global statement for them before in the same function's body. Names bound within a class statement lives in the class's namespace (IOW : they become class attributes, shared by all instances). And names bound as object attributes (using either obj.name = whatever or setattr(obj, "name", whatever)) become, well, object attributes. Now there may be a couple points worth paying attention to : 1/ some types (numerics, strings and tuples at least) are immutable. When doing : i = 1 i = 2 the second assignment doesnt mutate the integer object bound to i, but rebinds i to another integer object. 2/ the scope of a name isn't necessarily related to the scope of the object bound to that name. As an example, function's parameters *names* are local to the function, but the actual arguments - the objects passed when calling the function - are not. IOW, rebinding a parameter name withing a function body will rebind the name locally, but will not affect the object originally bound to that name. But *mutating* an object passed as argument *will* (off course) affect the object outside the function. > But if the > Python way is not to declare vars before use For which definition of "var" and "use" ? Did you really try to use a name that didn't exist in the accessible namespace - I mean, "use" for anything else than binding ? The first binding of a name in a namespace *is* the 'declaration'. If a name is not defined in the currently accessible namespace, and you try to do anything else than binding it, you'll get an exception. > then this must create > some problems for cross-function use. If what you mean is that it makes it harder to litter you code with true global variables, then it's obviously a *very* good thing IMHO !-) But no, there's no more problem with shared state in Python than in any other (imperative) language I know - usually less in fact since there's no "application global" namespace. Most of the time, the appropriate way to share state is to use classes - heck, that's what they were created for, isn't it ?-). Sharing state thru module-level variables is ok as long you only access it for reading (pseudo-constants etc). Sometimes, it's ok to use a module-level variable read-write, but this should be restricted to this particular module's implementation stuff (IOW : the name is not part of the API, and only functions / methods in this same module access it), and never done without a clear enough understanding of Python's namespaces and bindings. > So it is best to declare such vars at the module level (ie outside of > a function) and set eg to Null/None or to assign them with a keyword > such as global or static (assuming that concept applies in Python) it doesnt. > at first use inside a function or what? Usually, when you really need a module-level variable to be shared read-write between functions, it happens that you can bind it to a sensible default. Now what is a "sensible default" depends on the concrete use case. Anyway, by all means, explicitely bind this name at the top-level, before any code accessing it, and if possible with a comment about this name being shared read/write by functions x and y. My 2 cents... From kent.t.pinegar at lmco.com Thu Jul 24 09:38:54 2008 From: kent.t.pinegar at lmco.com (Pinegar, Kent T) Date: Thu, 24 Jul 2008 08:38:54 -0500 Subject: FW: [Jython-users] Jython Licensing Question Message-ID: <051C069C08E8EE49BB81482A4470BDF11C659EF8@emss07m14.us.lmco.com> All, Can anyone answer my question about the licensing for SocketServer.py? I would appreciate it. Kent -----Original Message----- From: Tobias Ivarsson [mailto:thobes at gmail.com] Sent: Thursday, July 24, 2008 2:13 AM To: Pinegar, Kent T Subject: Re: [Jython-users] Jython Licensing Question No I don't, I spent a few minutes yesterday when researching in what revision it got in to try and find where a list of contributors who have signed the contributors agreement could be found, but without success. I think you should try asking on python-list (python-list at python.org), the e-mail list for discussion about Python in general. /Tobias On Wed, Jul 23, 2008 at 9:25 PM, Pinegar, Kent T wrote: Tobias, Thanks. Do you know where I can get information on CPython? Specifically, licensing information. Kent ________________________________ From: Tobias Ivarsson [mailto:thobes at gmail.com] Sent: Wednesday, July 23, 2008 10:10 AM To: Pinegar, Kent T Cc: jython-users at lists.sourceforge.net Subject: Re: [Jython-users] Jython Licensing Question SocketServer.py is imported from CPython to where this copyright notice was committed in revision 18872, Jan 19 2001. IANAL so I don't know what is required to be able to redistribute this with Jython. But I guess that if it has been part of CPython since version 2.0 it should be fine for us as well... In fact this file (with that copyright notice) was included in the previous version of Jython as well. /Tobias On Wed, Jul 23, 2008 at 4:27 PM, Pinegar, Kent T wrote: The file SocketServer.py in the latest version of Jython, contains a copyright by Luke Kenneth Casson Leighton. There is not, however, any license agreement to cover this copyright in the Jython download. Does anyone know if this was an oversight, or existing licenses covers it? Kent Pinegar ------------------------------------------------------------------------ - This SF.Net email is sponsored by the Moblin Your Move Developer's challenge Build the coolest Linux based applications with Moblin SDK & win great prizes Grand prize is a trip for two to an Open Source event anywhere in the world http://moblin-contest.org/redirect.php?banner_id=100&url=/ _______________________________________________ Jython-users mailing list Jython-users at lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/jython-users From nicolas.pourcelot at gmail.com Fri Jul 18 07:49:04 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Fri, 18 Jul 2008 04:49:04 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: On 18 juil, 13:13, Peter Otten <__pete... at web.de> wrote: > nicolas.pource... at gmail.com wrote: > > In fact, 'any(myobject is element for element in mylist)' is 2 times > > slower than using a for loop, and 'id(myobject) in (id(element) for > > element in mylist)' is 2.4 times slower. > > This is not a meaningful statement unless you at least qualify with the > number of item that are actually checked. For sufficently long sequences > both any() and the for loop take roughly the same amount of time over here. > Sorry. I used short lists (a list of 20 floats) and the element checked was not in the list. (That was the case I usually deals with in my code.) From marek.rocki at wp.pl Sun Jul 13 13:42:17 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Sun, 13 Jul 2008 10:42:17 -0700 (PDT) Subject: Unexpected default arguments behaviour (Maybe bug?) References: <4f29ccf6-4daf-4e8e-8735-96cffd8a882e@t54g2000hsg.googlegroups.com> Message-ID: <475185e0-360a-452b-8d22-33ffc243b8a0@z66g2000hsc.googlegroups.com> sukkop... at gmail.com napisa?(a): > Hi, I have just encountered a Python behaviour I wouldn't expect. Take > the following code: > > ------------------------------------------------------------------------ > class Parent: > a = 1 > > def m (self, param = a): > print "param = %d" % param > > class Child (Parent): > a = 2 > > > p = Parent () > p.m () > > c = Child () > c.m () > ------------------------------------------------------------------------ > > I would expect to receive the following output: > param = 1 > param = 2 > > But actually I get: > param = 1 > param = 1 > > Is this the correct behaviour, and then why, or is it a bug? For > reference, I am using Python 2.5.1 on UNIX. > > Thanks in advance! I expect it's because default values for parameters are evaluated and bound at definition time. So once "def m (self, param = a):" line executes, the default value for parameter is forever bound to be 1. What you can do is for example: > def m (self, param = None): > if param is None: param = self.a > print "param = %d" % param Regards, Marek From JordanNealBerg at gmail.com Thu Jul 17 18:19:38 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Thu, 17 Jul 2008 15:19:38 -0700 (PDT) Subject: % sign in python? References: Message-ID: On Jul 17, 3:42?pm, Terry Reedy wrote: > korean_dave wrote: > > What does this operator do? Specifically in this context > > > test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) > > > (Tried googling and searching, but the "%" gets interpreted as an > > operation and distorts the search results) > > Having seen a number of comments like this over the years (about the > difficulty of searching for symbol meanings), I just started, last > night, a symbol index listing nearly all Python syntax uses of > non-alpha-or-digit ascii symbols. ?When I finish and upload it > somewhere, I will post an announcement with the link. > > tjr That sounds great Terry! I look forward to seeing this. ~Jordan From bblais at bryant.edu Tue Jul 8 20:29:52 2008 From: bblais at bryant.edu (Brian Blais) Date: Tue, 8 Jul 2008 20:29:52 -0400 Subject: a simple 'for' question In-Reply-To: <4874017D.2000401@umbc.edu> References: <4874017D.2000401@umbc.edu> Message-ID: <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> On Jul 8, 2008, at Jul 8:8:08 PM, Ben Keshet wrote: > I want to use a 'for' iteration to manipulate files in a set of > folders, something like: > > folders= ['1A28','1A6W','56Y7'] > for x in folders: > print x # print the current folder > f = open('my/path/way/x/my_file.txt', 'r') > ... > I think: f = open('my/path/way/%s/my_file.txt' % x, 'r') should work, although I would probably be more clear about the names, like: folders=['1A28','1A6W','56Y7'] for folder in folders: filename='my/path/way/%s/my_file.txt' % x fid=open(filename,'r') .... also, make sure that you do mean the relative path my/path/way/... # in current folder as opposed to the absolute path: /my/path/way # in root folder bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rcn.com Sun Jul 20 00:50:11 2008 From: python at rcn.com (Raymond Hettinger) Date: Sat, 19 Jul 2008 21:50:11 -0700 (PDT) Subject: atan2 weirdness References: <3b3ce28f-55d0-4db4-8eac-df0a9d1bc558@o40g2000prn.googlegroups.com> Message-ID: On Jul 19, 9:12?pm, "narutocan... at gmail.com" wrote: > hi > > atan2 is supposed to return the angle to x-axis when given y and x, I > suppose if I take [x,y] to one full circle, I should get 0-360 degree > back---- but no, I get 3 full revolutions! > maybe my understanding is wrong. > > from math import * > > def f(ang): > ?a=ang > ?if a>360: a-=360 > ?if a>360: a-=360 > ?if a<0: a+=360 > ?if a<0: a+=360 > ?return round(a) > > for i in range(0,360): > ?t=2*pi*i/360.0 > ?print i,f(atan2(sin(t),cos(t))*180.0) The "*180.0" part should be "*180/pi". Do yourself some favors. First use the degrees and radians functions in the math module. Second, when in doubt, print the intermediate results (that would have made the error obvious). Third, pick just one line of the result and compute it with your calculator by hand (to make sure you know what your program is doing. Lastly, when working with trig functions, always check the docs to make sure you know the ranges of values returned (i.e. atan2 returns from -pi to +pi). Here's a proposed revision: from math import pi, atan2, radians, degrees, cos, sin for i in range(360): t = radians(i) x = cos(t) y = sin(t) a = degrees(atan2(y, x)) print i, t, x, y, a Raymond From ojeeves at gmail.com Fri Jul 18 07:05:47 2008 From: ojeeves at gmail.com (oj) Date: Fri, 18 Jul 2008 04:05:47 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> Message-ID: <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> On Jul 18, 11:33?am, arnimavidyar... at gmail.com wrote: > Hi, > > Hi, > > I am taking a string as an input from the user and it should only > contain the chars:L , M or R > > I tried the folllowing in kodos but they are still not perfect: > > [^A-K,^N-Q,^S-Z,^0-9] > [L][M][R] > [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > > For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. > > regards, > SZ > > The string may or may not have all the three chars. With regular expressions, [^LRM] matches a character that isn't L, R or M. So: import re var = "LRLRLRLNR" if re.search(r'[^LRM]', var): print "Invalid" From cjw at ncf.ca Fri Jul 25 19:44:28 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 25 Jul 2008 19:44:28 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> Message-ID: Fuzzyman wrote: > On Jul 24, 6:41 am, Jordan wrote: >> Hi everyone, >> >> I'm a big Python fan who used to be involved semi regularly in >> comp.lang.python (lots of lurking, occasional posting) but kind of >> trailed off a bit. I just wrote a frustration inspired rant on my >> blog, and I thought it was relevant enough as a wider issue to the >> Python community to post here for your discussion and consideration. >> >> This is not flamebait. I love Python, and I'm not out to antagonise >> the community. I also realise that one of the issues I raise is way >> too ingrained to be changed now. I'd just like to share my thinking on >> a misstep in Python's guiding principles that has done more harm than >> good IMO. So anyway, here's the post. >> >> I've become utterly convinced that at least one criticism leveled at >> my favourite overall programming language, Python, is utterly true and >> fair. After quite a while away from writing Python code, I started >> last night on a whim to knock up some code for a prototype of an idea >> I once had. It's going swimmingly; the Python Image Library, which I'd >> never used before, seems quick, intuitive, and with the all the >> features I need for this project. As for Python itself, well, my heart >> still belongs to whitespace delimitation. All the basics of Python >> coding are there in my mind like I never stopped using them, or like >> I've been programming in this language for 10 years. >> >> Except when it comes to Classes. I added some classes to code that had >> previously just been functions, and you know what I did - or rather, >> forgot to do? Put in the 'self'. In front of some of the variable >> accesses, but more noticably, at the start of *every single method >> argument list.* This cannot be any longer blamed as a hangover from >> Java - I've written a ton more code, more recently in Python than in >> Java or any other OO language. What's more, every time I go back to >> Python after a break of more than about a week or so, I start making >> this 'mistake' again. The perennial justification for this 'feature' >> of the language? That old Python favourite, "Explicit is better than >> implicit." >> > > > It's damn useful for scoping. You can look in the body of your method > and tell whether you are accessing local variables or instance > variables. > > I'm a great fan of self and I'm afraid you're flogging a dead horse on > that one. > > Your point about rich comparison (at least the == != problem) is fair.. > This one is fixed in Python 3 though I believe. > > Michael Foord > -- > http://www.ironpythoninaction.com/ I hope that the OP will develop some specific proposal, narrowly focused on the "self" issue. It has always seemed redundant on the argument line of a definition. It does permit one to use some other word but is that of any real value. One can still use self.a= 'z' or perhaps .a= 'z'. Colin W. From wtanksleyjr at gmail.com Wed Jul 30 20:53:53 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Wed, 30 Jul 2008 17:53:53 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> <4ae2518f-10c0-49f2-b5d7-a75993b0a67d@z66g2000hsc.googlegroups.com> Message-ID: william tanksley wrote: > I'm still puzzled why I'm getting some non-Unicode out of an > ElementTree's text, though. Now I know. Okay, my answer is that cElementTree (in Python 2.5) is simply deranged when it comes to Unicode. It assumes everything's ASCII. Reference: http://codespeak.net/lxml/compatibility.html (Note that the lxml version also doesn't handle Unicode correctly; it errors when XML declares its encoding.) This is unpleasant, but at least now I know WHY it was driving me insane. > -Wm -Wm From subhabrata.iisc at hotmail.com Fri Jul 18 06:10:48 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Fri, 18 Jul 2008 03:10:48 -0700 (PDT) Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> <6eb733F67cpfU2@mid.uni-berlin.de> <32a81d0c-a74f-4b22-8add-15beb2643529@h17g2000prg.googlegroups.com> Message-ID: Hi Peter, In your code s would print first_char(of the last word)+" "+missing_word(the last word) I was looking all. Best Regards, Subhabrata. SUBHABRATA wrote: > Sorry if I didn't say that. > The input is a string "Petrol Helium Heaven Sky" > Now, in a3 it is "God Goddess Heaven Sky" is there, > it is matching Heaven and Sky but not Petrol and Helium as they are > not in a3. > Now, as per the code it is giving me an output "S" of "Sky" and > "Helium" > But I was looking for an output of "H S Petrol Helium" and not "S > Helium" meaning all the values of a5 and a6 will be concatenated in s. > Best Regards, > Subhabrata.. > > Marc 'BlackJack' Rintsch wrote: > > On Fri, 18 Jul 2008 01:31:59 -0700, SUBHABRATA wrote: > > > > > def try2(n): > > > a1=raw_input("PRINT A STRING:") > > > a2=a1.split() > > > a3="God Godess Heaven Sky" > > > for x in a2: > > > a4=a3.find(x) > > > if a4>-1: > > > a5=a3[a4] > > > print a5 > > > elif a4<0: > > > a6=x > > > print "It is not found" > > > print a6 > > > else: > > > print "Error" > > > s=a5+" "+a6 > > > print s > > > > > > Here, if I put a string like: > > > Petrol Helium Heaven Sky > > > In s it is giving me S Helium > > > But I am looking for an output of a5 and a6 concatenating all its > > > values not the last ones. Can you suggest me any help? Am I missing > > > any minor point? > > > > Maybe you should describe what the input looks like and what output you > > want to have and how the input and output are connected. In words, not in > > not very clear code with "numbered names". That's a silly idea and makes > > understanding the code very hard. Please use meaningful names! > > > > Ciao, > > Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Thu Jul 24 05:01:42 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 24 Jul 2008 02:01:42 -0700 (PDT) Subject: instance comparison References: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> Message-ID: On Jul 24, 6:50?pm, King wrote: > I am facing a problem where I am really confused about it. > > I am trying to compare to instances using: > > if inst1 == inst2 > > These instances have a overridden method __str__ which returns same > string. The condition result is true although they are different > instances. > > If I use: > > if id(inst1) == id(inst2) > > The results is false. What's happening here? > > If I am trying to store this pair in a set where other instances are > already stored, but it's not storing it. Although I am sure that there > is no pair already stored of same but even if Set is comparing by > using string return by __str__ method then it won't. > > How do I solve this? > > Is this mean when you have overridden __str__ method then it comapre > with results of __str__ No. Do you have a __cmp__ method, or an __eq__ method? Any other __twounderscores__ methods? It is impossible to tell what is going on from your description. Please supply the source of a *short* class that demonstrates the problem, and demonstrate it. From ddasilva at umd.edu Thu Jul 10 17:06:25 2008 From: ddasilva at umd.edu (Daniel da Silva) Date: Thu, 10 Jul 2008 17:06:25 -0400 Subject: You, spare time and SyntaxError In-Reply-To: References: Message-ID: <8d9ec3dd0807101406t441b6c23qea16f4097b926181@mail.gmail.com> I applaud your creativity. Very nice. On Wed, Jul 9, 2008 at 10:56 AM, wrote: > def ine(you): > yourself = "what?" > go = list("something"), list("anything") > be = "something" > please = be, yourself > yourself = "great" > for good in yourself: > if you is good: > good in you > please.add(more, good) > else: > def inition(lacks, clarity): > if clarity not in you: > please.remove(everything and go) > for bad in yourself: > list(bad) if bad else (ignore, yourself) > try: > (to, escape, your, fate, but) > except (Exception), son: > if bad in (you, son): > (you is bad, son), so > finally: > if bad in you: > lie, cheat, steal, be, bad > else: > print you, "is", yourself > you is good and yourself is not bad > please, go > > ine("Everyone") > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From asd at pittle.org Sun Jul 6 07:15:40 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Sun, 6 Jul 2008 04:15:40 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <20080704053113.GJ34192@nexus.in-nomine.org> Message-ID: <57dd27f6-1eab-4131-b169-2c327e4eb496@i76g2000hsf.googlegroups.com> On Jul 4, 8:58?am, Aspersieman wrote: > Jeroen Ruigrok van der Werven wrote:> -On [20080630 23:51], Ali Servet D?nmez (a... at pittle.org) wrote: > > >> This could be an extension, a plugin, an Emacs mode, a new editor or > >> even a brand new huge all-fancy IDE, I don't care, but what am I > >> missing here? > > > Vim's omnicomplete (CTRL-X CTRL-O). > > > See :help omnifunc within vim. > > I find Vim with ctags, omnicomplete and calltip support the BEST I've > tried so far. And I've tried many. > > Here's a tutorial on setting this up. > ? ?http://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/ > > Regards > > Nicol > > -- > > The three things to remember about Llamas: > 1) They are harmless > 2) They are deadly > 3) They are made of lava, and thus nice to cuddle. Oh my, that thing seems to work! I didn't try it my self, but checked out the URL you've mentioned. I think I've been unfair to Yu-Xi Lim before... Thank you. From aahz at pythoncraft.com Sun Jul 20 13:05:23 2008 From: aahz at pythoncraft.com (Aahz) Date: 20 Jul 2008 10:05:23 -0700 Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Message-ID: In article <2476438f-eaa2-495f-95fa-eb9efec25875 at e39g2000hsf.googlegroups.com>, Craig Allen wrote: > >(option 2) >Therefore option two is a family of options where class level members >can be used to share whatever needs to be shared, though strictly the >class is not a singleton since multiple instances are created which >merely share the data that should be single (say a big dictionary of >configuration information the class manages). That's only true if you actually instantiate the class. You can just use the class directly -- that's what I do. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From gagsl-py2 at yahoo.com.ar Fri Jul 11 05:24:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Jul 2008 06:24:03 -0300 Subject: numeric emulation and the rich comparison operators References: <48767316.3060607@stoneleaf.us> Message-ID: En Thu, 10 Jul 2008 17:37:42 -0300, Ethan Furman escribi?: > Greetings, List! > > Still working on my Measure class, and my next question is... (drum roll > please ;) > > What are the advantages of using __[eq|ne|lt|gt|le|ge]__ vs __cmp__? If your objects obey the trichotomy law (an object MUST BE less than, greater than, or equal to another one, and there is no other possibility) then __cmp__ is enough, and easier to define than all the rich comparison operations. In other cases, __cmp__ is not suitable: by example, complex numbers can't define "greater than" [in a way that preserves the meaning for real numbers]; you can only use "equal" or "not equal". You can't use __cmp__ for this, because it *has* to return either >0 or <0 (implying "greater than" or "less than"). In this case it's best to use the rich comparison operators: define __eq__ and __ne__ and make all other comparisons between complex numbers raise an exception. -- Gabriel Genellina From Russ.Paielli at gmail.com Sun Jul 27 18:34:10 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 15:34:10 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> On Jul 27, 3:11 pm, "Russ P." wrote: > On Jul 27, 12:39 pm, Bruno Desthuilliers > > > > wrote: > > Derek Martin a ?crit : > > > > On Sun, Jul 27, 2008 at 08:19:17AM +0000, Steven D'Aprano wrote: > > >>> You take the name down to a single letter. As I suggested in an earlier > > >>> post on this thread, why not take it down to zero letters? > > >> The question isn't "why not", but "why". The status quo works well as it > > >> is, even if it isn't perfect. Prove that implicit self is a good idea -- > > >> or at least prove that it is an idea worth considering. > > > > Come on, this sounds like a schoolyard argument. This comes down to a > > > matter of style, and as such, is impossible to prove. It's largely a > > > question of individual preference. > > > > That said, the argument in favor is rather simple: > > > > 1. This is an extremely common idiom in Python > > > 2. It is completely unnecessary, and the language does not suffer for > > > making it implicit > > > 3. Making it implicit reduces typing, reduces opportunities for > > > mistakes, and arguably increases consistency. > > > "arguably", indeed, cf below. > > > > As for the latter part of #3, self (or some other variable) is > > > required in the parameter list of object methods, > > > It's actually the parameter list of the *function* that is used as the > > implementation of a method. Not quite the same thing. And then, > > consistency mandates that the target object of the method is part of the > > parameter list of the *function*, since that's how you make objects > > availables to a function. > > > > however when the > > > method is *called*, it is omitted. > > > Certainly not. You need to lookup the corresponding attribute *on a > > given object* to get the method. Whether you write > > > some_object.some_method() > > > or > > > some_function(some_object) > > > you still need to explicitely mention some_object. > > > > It is implied, supplied by Python. > > > Neither. The target object is passed to the function by the method > > object, which is itself returned by the __get__ method of function > > objects, which is one possible application of the more general > > descriptor protocol (the same protocol that is used for computed > > attributes). IOW, there's nothing specific to 'methods' here, just the > > use of two general features (functions and the descriptor protocol). > > FWIW, you can write your own callable, and write it so it behave just > > like a function here: > > > import types > > > class MyCallable(object): > > def __call__(self, obj): > > print "calling %s with %s" % (self, obj) > > def __get__(self, instance, cls): > > return types.MethodType(self.__call__, instance, cls) > > > class Foo(object): > > bar = MyCallable() > > > print Foo.bar > > f = Foo() > > f.bar() > > > > Thus when an object method is called, it must be called with one fewer > > > arguments than those which are defined. This can be confusing, > > > especially to new programmers. > > > This is confusing as long as you insist on saying that what you > > "def"ined is a method - which is not the case. > > > > It can also be argued that it makes the code less ugly, though again, > > > that's a matter of preference. > > > >> It's not enough to show that a change "isn't bad" -- you have to show > > >> that it is actively good. > > > > But he did... he pointed out that *it saves work*, without actually > > > being bad. Benefit, without drawback. Sounds good to me! > > > >> "Don't need to look at the method signature" is not an argument in favour > > >> of implicit self. > > > > Yes, actually, it is. > > > It isn't, since there's no "method signature" to look at !-) > > > > If there is a well-defined feature of Python > > > which provides access to the object within itself, > > > The point is that you don't get access to the object "within itself". > > You get access to an object *within a function*. > > > The fact that a function is defined within a class statement doesn't > > imply any "magic", it just creates a function object, bind it to a name, > > and make that object an attribute of the class. You have the very same > > result by defining the function outside the class statement and binding > > it within the class statement, by defining the function outside the > > class and binding it to the class outside the class statement, by > > binding the name to a lambda within the class statement etc... > > > > then the > > > opportunities for mistakes when someone decides to use something else > > > are lessened. > > > >> You don't need to look at the method signature when you're using an > > >> explicit self either. > > > > That isn't necessarily true. If you're using someone else's code, and > > > they didn't use "self" -- or worse yet, if they chose this variable's > > > name randomly throughout their classes -- then you may well need to > > > look back to see what was used. > > > > It's bad programming, but the world is full of bad programmers, and we > > > don't always have the choice not to use their code. Isn't one of > > > Python's goals to minimize opportunities for bad programming? > > > Nope. That's Java's goal. Python's goals are to maximize opportunities > > for good programming, which is quite different. > > > > Providing a keyword equivalent to self and removing the need to name > > > it in object methods is one way to do that. > > > It's also a way to make Python more complicated than it needs to be. At > > least with the current state, you define your functions the same way > > regardless of how they are defined, and the implementation is > > (relatively) easy to explain. Special-casing functions definition that > > happens within a class statement would only introduce a special case. > > Then you'd have to explain why you need to specify the target object in > > the function's parameters when the function is defined outside the class > > but not when it's defined within the class. > > > IOW : there's one arguably good reason to drop the target object from > > functions used as methods implementation, which is to make Python looks > > more like Java, and there's at least two good reason to keep it the way > > it is, which are simplicity (no special case) and consistency (no > > special case). > > > Anyway, the BDFL has the final word, and it looks like he's not going to > > change anything here - but anyone is free to propose a PEP, isn't it ? > > The issue here has nothing to do with the inner workings of the Python > interpreter. The issue is whether an arbitrary name such as "self" > needs to be supplied by the programmer. > > Neither I nor the person to whom you replied to here (as far as I can > tell) is suggesting that Python adopt the syntax of Java or C++, in > which member data or functions can be accessed the same as local > variables. Any suggestion otherwise is a red herring. > > All I am suggesting is that the programmer have the option of > replacing "self.member" with simply ".member", since the word "self" > is arbitrary and unnecessary. Otherwise, everything would work > *EXACTLY* the same as it does now. This would be a shallow syntactical > change with no effect on the inner workings of Python, but it could > significantly unclutter code in many instances. > > The fact that you seem to think it would change the inner functioning > of Python just shows that you don't understand the proposal. It just occurred to me that Python could allow the ".member" access regardless of the name supplied in the argument list: class Whatever: def fun(self, cat): .cat = cat self.cat += 1 This allows the programmer to use ".cat" and "self.cat" interchangeably. If the programmer intends to use only the ".cat" form, the first argument becomes arbitrary. Allowing him to use an empty argument or "." would simply tell the reader of the code that the ".cat" form will be used exclusively. When I write a function in which a data member will be used several times, I usually do something like this: data = self.data so I can avoid the clutter of repeated use of "self.data". If I could just use ".data", I could avoid most of the clutter without the extra line of code renaming the data member. A bonus is that it becomes clearer at the point of usage that ".data" is member data rather than a local variable. From mail at microcorp.co.za Mon Jul 7 04:15:59 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 7 Jul 2008 10:15:59 +0200 Subject: Cross Compiler for Python? Message-ID: <000901c8e009$dbd29e40$0d00a8c0@hendrik> Up to now, I have been innocently using the vanilla python that comes with the Linux distribution (Suse in my case). For the past few days, I have been playing with a little device called an eBox - it is basically a 486 with 128Mb memory, and a 1Gig pcmcia flash drive. We want to try to use this as an industrial controller, so I want to load python onto it. So I downloaded the sources, and got them into the box, over its ethernet connection. Then I got stymied - the configure script will not run, because the "distribution" has no C compiler - it is basically a kernel, and Busybox, with precious little else. So I googled, and I found mobile python, and portable python, both aimed at windows. - no good to me. Adding "embedded" to the Google string is also useless, as it basically brings up instances of embedding the interpreter into another app, not for small processors. So how does one do a compile of python on one machine aimed at another one? - All I want is a vanilla installation with the stuff in all the usual places. And just to make matters interesting, the two Linux boxes I have available are both 64 bit dual core animals, one Intel, one AMD... I don't need much more than the interpreter, sys, os, sockets and ctypes. Alternatively, where can one find a set of binaries for 32 bit Linux? Looking for some sane advice please. - Hendrik From aaa at bbb.it Thu Jul 31 07:00:52 2008 From: aaa at bbb.it (Fred Mangusta) Date: Thu, 31 Jul 2008 12:00:52 +0100 Subject: Case tagging and python Message-ID: Hi, I'm relatively new to programming in general, and totally new to python, and I've been told that this language is particularly good for what I need to do. Let me explain. I have a large corpus of English text, in the form of several files. First of all I would like to scan each file. Then, for each word I find, I'd like to examine its case status, and write the (lower case) word back to another text file - with, appended, a tag stating the case it had in the original file. An example. Suppose we have three possible "case conditions" -all lowercase -all uppercase -initial uppercase only Three corresponding tags for each of these might be, respectively: -nocap -allcaps -cap Therefore, given the string "The Chairman of BP was asleep" I would like to produce "the/cap chairman/cap of/nocap /bp/allcaps was/nocap /asleep/nocap" and writing this into a file. I have the following algorithm in mind: -open input file -open output file -get line of text -split line into words -for each word -tag = checkCase(word) -newword = lowercase(word) + append(tag) rejoin words into line write line into output file Now, I managed to write the following initial code for s in file: lines += 1 if lines % 1000 == 0: print '%d lines' % We print the total lines sent = s.split() #split string by spaces #... But then I don't quite know what would be the fastest/best way to do this. Could I use the join function to reform the string? And, regarding the casetest() function, what do you suggest to do? Should I test each character of each word or there are faster methods? Thanks very much, F. From larry.bates at websafe.com` Mon Jul 21 16:01:38 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 15:01:38 -0500 Subject: persistent deque (continued) In-Reply-To: <4c985e86-c0c4-4cb3-b7ce-f8e105b7f85d@y21g2000hsf.googlegroups.com> References: <4c985e86-c0c4-4cb3-b7ce-f8e105b7f85d@y21g2000hsf.googlegroups.com> Message-ID: castironpi wrote: > Some time ago, I was asking about the feasibility of a persistent > deque, a double-ended queue. > > It runs into the typical space allocation problems. If you're storing > a pickle, you have to allocate and fragment the file you've opened, > since pickles can be variable-length strings; i.e. if the new data is > too long, blank out its entry, and grow the file. If you're storing a > data-type, you lose Python's dynamic-type advantages, as well as its > long integers, as they can be any length. If you change the object in > the deque, such as when using any mutable type, you have to update the > container too. > > Does anyone have any experience storing pickles (I am aware of the > similarities to shelf) to a database? > Can the file system facilitate the variable-length string problem? > How feasible is a length-of-length - length - data solution to the > unbounded integer problem? > Is there any alternative to completely re-pickling a large (say 1k > pickled) object you only change slightly? > What other issues are there? > Is a hybrid-storage type possible, that stores the contents of its > Python-allocated memory block to disk, including reference count, even > if it's a lot slower? The object could not contain any references to > objects not allocated on disk. > > A first approach is for the file to look like this: > > 00 data 01 data 02 > 01 data 03 data 04 > 02 data 05 data 06 > > Append would add: > > 03 data 07 data 08 > > AppendLeft would add: > > -01 data 09 data 0a > > Pop would remove 03, PopLeft would remove -01. You would need a > length-and-head index to make 'rotate' available. Remove would run a > worst-case risk of renumbering half of the indices stored, plus a > rotate. It is so much easier to implement this using a database table that IMHO most people would go that route. -Larry From newptcai at gmail.com Mon Jul 21 03:27:37 2008 From: newptcai at gmail.com (=?GB2312?B?0rvK18qr?=) Date: Mon, 21 Jul 2008 00:27:37 -0700 (PDT) Subject: Please recommend a RPC system working with twisted. Message-ID: <312040c6-4011-451e-8a45-f982c2e4462f@j1g2000prb.googlegroups.com> Hi all, I'm looking for an RPC system working with twisted. 1. Binary. I want it run faster than any xml based RPC. 2. Bidirectional. Unlike HTTP, on which the client has to poll the sever for events, the server should "call" the client's method to notify events. 3. C/Python support. Part of the system shall be written in C. 4. Could easily integrated with twisted. Unfortunately, there seems no such resolution existed. So maybe I have to give up some requirements. --------------------------------------------------------------------------------------------------------------------------- It would be wonderful if ICE could integrate with twisted! From vinay_sajip at yahoo.co.uk Tue Jul 15 19:31:37 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 15 Jul 2008 16:31:37 -0700 (PDT) Subject: How to package a logging.config file? References: <0a5713d6-8337-44a3-8347-012814345dd8@79g2000hsk.googlegroups.com> Message-ID: <779746bc-93db-4225-9b9f-46419ab44282@f36g2000hsa.googlegroups.com> On Jul 15, 3:04 pm, Matthew Wilson wrote: > On Mon 14 Jul 2008 09:25:19 AM EDT, Vinay Sajip wrote: > > > Is your package a library or an application? If it's a library, you > > should avoid configuringloggingusing a config file - this is because > >loggingconfiguration is process-wide, and if multiple libraries use > > fileConfig to configure theirlogging, you may get unexpected results. > > I thought that the point of usinglogging.getLogger('foo.bar.baz') was > to allow each module/class/function to choose from the available > configurations. > > So, I can define a really weird logger and still be a good citizen. > > As long as I don't tweak the root logger, is it safe to use a config > file? > > Matt The reason why using fileConfig in libraries is problematic is that fileConfig assumes it does the entire logging configuration. Whenever fileConfig is called, any loggers which are not explicitly mentioned in the config file (but are present in the logging system) are disabled. (They are not actually removed, since there may be still- running threads that have references to them.) You may think this is odd, but it's only because fileConfig was never intended for incremental configuration, only for a one-off configuration. So, a fileConfig'd configuration is meant to completely replace the existing configuration. So - you can use hierarchical naming of loggers to avoid stepping on other loggers - for example, prefixing with the company domain name if there's a possibility of use outside the company (in the same way as Java packages use e.g. com.sun.XXX for Sun's proprietary Java packages, or com.ibm.YYY for IBM's proprietary packages). However, I'd advise against using fileConfig in library code, as it is likely to disable already-instantiated loggers in other library packages. Best regards, Vinay Sajip From ldo at geek-central.gen.new_zealand Thu Jul 17 01:16:55 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 17 Jul 2008 17:16:55 +1200 Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> Message-ID: In message <4627d685-6eb0-443d-83bb-6392ea83e8d1 at 2g2000hsn.googlegroups.com>, Keith Hughitt wrote: > I have a UTC date (e.g. 2008-07-11 00:00:00). I would like to create a > UTC date ... >>> import calendar >>> calendar.timegm((2008, 7, 11, 0, 0, 0, 0, 0, -1)) 1215734400 ldo at theon> TZ=NZ date -d "00:00:00 01-Jan-1970Z +1215734400 seconds" Fri Jul 11 12:00:00 NZST 2008 The general form of the call is "calendar.timegm((Y, M, D, hh, mm, ss, 0, 0, -1))". See also , . > ... so that when I send it to MySQL (which treats all dates at local dates > by default) ... I don't like to use MySQL's date/time types. Instead, I usually have a simple integer field containing seconds since some origin time in UTC. If the time is that of some event, an origin of 00:00:00 01-Jan-1970 lets you use Unix/Linux system times directly. For recording dates/times that might go further back (e.g. dates of birth, historical events), I have used the Julian day origin, 1st January 4713 BC. From hat at se-162.se.wtb.tue.nl Wed Jul 9 07:09:09 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 09 Jul 2008 13:09:09 +0200 Subject: start reading from certain line References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> Message-ID: On 2008-07-09, antar2 wrote: > I am a starter in python and would like to write a program that reads > lines starting with a line that contains a certain word. > For example the program starts reading the program when a line is > encountered that contains 'item 1' > > > The weather is nice > Item 1 > We will go to the seaside > ... > > Only the lines coming after Item 1 should be read Not possible at most OSes, file reading always starts at the first character at the first line. Also, most OSes don't understand the 'line' concept natively, a file is just a long sequence of characters to them (end-of-line is also just a character, namely '\n' (or '\r\n' if you are using Windows). So you have to read the entire file, then throw away the bits you don't want to keep. Luckily, Python does understand what a 'line' is, which makes the prblem simpler. Have a look at the readline() function (or the readlines() function if your file is not too long). That should give you a start. Albert From gh at ghaering.de Fri Jul 4 04:41:01 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 04 Jul 2008 10:41:01 +0200 Subject: Recursive wildcard file search In-Reply-To: <496954360807031353n4f91f691recb330f7350cbf70@mail.gmail.com> References: <496954360807031353n4f91f691recb330f7350cbf70@mail.gmail.com> Message-ID: Robert Dailey wrote: > Hi, > > Is there a way to perform a recursive file search using wildcards in > python 3.0b1? [...] glob.glob() or glob.iglob(). -- Gerhard From __peter__ at web.de Fri Jul 18 05:57:11 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 11:57:11 +0200 Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> Message-ID: SUBHABRATA wrote: > I am trying the following code line: def try2(n): user_line = raw_input("PRINT A STRING:") user_words = user_line.split() my_line = "God Godess Heaven Sky" for word in user_words: pos = my_line.find(word) if pos >- 1: first_char = my_line[pos] print first_char elif pos < 0: missing_word = word print "It is not found" print missing_word else: print "Error" s = first_char + " " + missing_word print s try2(1) Do you recognise your code? With that jumpstart you should find the error in no time ;) > Here, if I put a string like: > Petrol Helium Heaven Sky > In s it is giving me S Helium > But I am looking for an output of a5 and a6 concatenating all its > values not the last ones. Can you suggest me any help? Am I missing > any minor point? Yes, use meaningful variables. They won't make your code magically correct but will make it a lot easier to pinpoint mistakes and false assumptions -- for you and others. Peter From larry.bates at websafe.com` Wed Jul 9 12:04:20 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 09 Jul 2008 11:04:20 -0500 Subject: FOSS projects exhibiting clean/good OOP? In-Reply-To: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> Message-ID: Phillip B Oldham wrote: > I'm wondering whether anyone can offer suggestions on FOSS projects/ > apps which exhibit solid OO principles, clean code, good inline > documentation, and sound design principles? > > I'm devoting some time to reviewing other people's code to advance my > skills. Its good to review bad code (of which I have more than enough > examples) as well as good, but I'm lacking in finding good examples. > > Projects of varying sizes would be great. I think the following are very good: Python Imaging Library (PIL) elementTree (actually anything that Fredrick Lundh has written is an excellent example) ReportLab wxPython Django That should keep you busy for a while. -Larry From jkrukoff at ltgc.com Wed Jul 30 17:20:13 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Wed, 30 Jul 2008 15:20:13 -0600 Subject: seemingly simple list indexing problem In-Reply-To: References: <999589a9-e1bb-4a64-801c-74ce060bc0c6@i24g2000prf.googlegroups.com> Message-ID: <1217452813.4123.168.camel@jmk> On Wed, 2008-07-30 at 14:08 -0700, wolfram.hinderer at googlemail.com wrote: > On 29 Jul., 01:05, Raymond Hettinger wrote: > > [Ervan Ensis] > > > > > I have a list like [108, 58, 68]. I want to return > > > the sorted indices of these items in the same order > > > as the original list. So I should return [2, 0, 1] > > > > One solution is to think of the list indexes > > being sorted according the their corresponding > > values in the input array: > > > > >>> s = [ 108, 58, 68 ] > > >>> sorted(range(len(s)), key=s.__getitem__) > > > > [1, 2, 0] > > > > To get the desired output you have to apply it twice: > >>> sorted(range(len(s)), key=sorted(range(len(s)), key=s.__getitem__).__getitem__) > [2, 0, 1] > > Wolfram > -- > http://mail.python.org/mailman/listinfo/python-list Thanks, I knew I was missing something simpler. -- John Krukoff Land Title Guarantee Company From deets at nospam.web.de Wed Jul 23 10:07:34 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 23 Jul 2008 16:07:34 +0200 Subject: python.exe crash and ctypes use References: Message-ID: <6eosb5F83oe6U1@mid.uni-berlin.de> waldek wrote: > Hi, > > I have module A.py and B.dll which exports C functions by cdecl_ > > In A.py I pass callback (py callable) to dll. Next, thread inside dll > simply calls my callback (in a loop). After few secs I got crash of > python.exe. > > How to debug it? > > I'm using winxp and py 2.5.2 > > > =========================== > def mycallback(data, size) > return 0 > > CBFUNC = CFUNCTYPE(c_int,POINTER(c_int), c_int) > dll = cdll.mydll > > if dll.RegisterCallback(CBFUNC(mycallback)) != 0: > print "Error." > =========================== Attach a debugger of choice to your python-process, and see what happens. Diez From nicolas.pourcelot at gmail.com Fri Jul 18 06:27:35 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Fri, 18 Jul 2008 03:27:35 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: In fact, 'any(myobject is element for element in mylist)' is 2 times slower than using a for loop, and 'id(myobject) in (id(element) for element in mylist)' is 2.4 times slower. From mcfletch at vrplumber.com Fri Jul 25 07:22:42 2008 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Fri, 25 Jul 2008 07:22:42 -0400 Subject: PyOpenGL Tutorial? In-Reply-To: <9a2cc7a70807232222t7d401279t5d91d5b8a9220ceb@mail.gmail.com> References: <1216843629.18962.16.camel@generator> <9a2cc7a70807232222t7d401279t5d91d5b8a9220ceb@mail.gmail.com> Message-ID: <4889B782.4090809@vrplumber.com> arsyed wrote: ... > Also, see: > > http://www.siafoo.net/browse?keyword_id=245 > But note regarding the second tutorial there that the PyOpenGL 3.x *does* supply wrappers for most publicly known extensions, so you shouldn't have to create your own wrappers for them any more. There's also tutorials that are not wxPython specific on the PyOpenGL documentation page. HTH, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From ashmir.d at gmail.com Fri Jul 4 01:50:29 2008 From: ashmir.d at gmail.com (ashmir.d at gmail.com) Date: Thu, 3 Jul 2008 22:50:29 -0700 (PDT) Subject: problem parsing utf-8 encoded xml - minidom Message-ID: Hi, I am trying to parse an xml file using the minidom parser. from xml.dom import minidom xmlfilename = "sample.xml" xmldoc = minidom.parse(xmlfilename) The parser is failing on this line: Heinrich K?ufner, Norbert Nedopil, Heinz Sch?och (Hrsg.). This is the error message I get: Traceback (most recent call last): File "readXML.py", line 11, in xmldoc = minidom.parse(xmlfilename) File "C:\Python25\lib\xml\dom\minidom.py", line 1913, in parse return expatbuilder.parse(file) File "C:\Python25\lib\xml\dom\expatbuilder.py", line 924, in parse result = builder.parseFile(fp) File "C:\Python25\lib\xml\dom\expatbuilder.py", line 207, in parseFile parser.Parse(buffer, 0) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 2254, column 21 It seems to me that it is having an issue with the '?' character. I have even tried the following to make sure it recognises the file as utf-8 file: from xml.dom import minidom import codecs xmlfilename = "sample.xml" xmlfile = codecs.open(xmlfilename,"r","utf-8") xmlstring = xmlfile.read() xmldoc = minidom.parse(xmlfilename) However, this doesn't work either and I get the following error message: Traceback (most recent call last): File "readXML.py", line 9, in xmlstring = xmlfile.read() File "C:\Python25\lib\codecs.py", line 618, in read return self.reader.read(size) File "C:\Python25\lib\codecs.py", line 424, in read newchars, decodedbytes = self.decode(data, self.errors) UnicodeDecodeError: 'utf8' codec can't decode bytes in position 69343-69345: invalid data I'm assuming here that it is failing at the same place... Can someone please point me in the right direction? Thanks, Ashmir From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 12:43:25 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 18:43:25 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <579f9d5b-8984-425d-8d4f-b2ed0be8eaba@o40g2000prn.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <579f9d5b-8984-425d-8d4f-b2ed0be8eaba@o40g2000prn.googlegroups.com> Message-ID: <4888cd25$0$15527$426a74cc@news.free.fr> Jordan a ?crit : >> I don't really mind, what you think about my response. Python will suffer >> from it as little as it will suffer from your complaints: These things >> will not change, whatever any of us says about them. So this discussion >> unlikely to produce any new insight, especially because this as been >> discussed over and over again in the past, without any effect on Python. > > You're right, of course. Because Python is in so many ways what I'm > looking for in a language, I transform it in my mind to my own, > personal ideal, close to the real existing language but with what I > consider to be the imperfections removed. I guess you'll find a lot of us guilty here too - but do we really agree on what we consider to be "imperfections" ?-) (snip) > I was trying not to change explicit self, or even != (which has a much > better case.) I was trying to ask the community to reconsider a > premise that the language is built around. Explicit is actually kinda > annoying a lot of the time, viz., java. This is about social and > philosophical adjustments, not technical ones. > "explicit-is-etc" - just like the remaining of Python's zen - is a general philosophy statement, not an absolute rule. Another quote states that practicality beats purity. So yes, Python has warts, and one can't get away dogmatically quoting Python's zen. Even if I'm sometimes myself guilty here, it's certainly worth taking time to better address criticism, either by aknowledging effective warts when someone points them out or by explaining (or pointing to explanations of) the unusual parts of Python's design. Now since most of the times, criticisms expressed here fall in the second category, we're happy to learn you'll now take appropriate action here and help us keep c.l.py a newbie-friendly place !-) From robert.kern at gmail.com Sat Jul 26 04:29:31 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 26 Jul 2008 01:29:31 -0700 (PDT) Subject: An Attempt to download and install traits - to a Windows XP References: Message-ID: On Jul 25, 5:37?pm, "Colin J. Williams" wrote: > Using >easy_install -v -fhttp://code.enthought.com/enstaller/eggs/sourceenthought.traits > > The result is: > > ... > ? ?many lines > ... > > copyingenthought\traits\ui\tests\shell_editor_test.py > -> > build\lib.win32-2.5\enthought\traits\ui\tests > copyingenthought\traits\ui\tests\table_editor_color_test.py > -> > build\lib.win32-2.5\enthought\traits\ui\tests > copyingenthought\traits\ui\tests\table_editor_focus_bug.py > -> > build\lib.win32-2.5\enthought\traits\ui\tests > copyingenthought\traits\ui\tests\table_editor_test.py > -> > build\lib.win32-2.5\enthought\traits\ui\tests > copyingenthought\traits\ui\tests\table_editor_test2.py > -> > build\lib.win32-2.5\enthought\traits\ui\tests > copyingenthought\traits\ui\tests\table_list_editor_test.py > -> > build\lib.win32-2.5\enthought\traits\ui\tests > copyingenthought\traits\ui\tests\tree_editor_test.py > -> > build\lib.win32-2.5\enthought\traits\ui\tests > running build_ext > error: Setup script exited with error: > Python was built with Visual Studio 2003; > extensions must be built with a compiler > than can generate compatible binaries. > Visual Studio 2003 was not found on this > system. If you have Cygwin installed, > you can try compiling with MingW32, by > passing "-c mingw32" to setup.py. Traits includes an extension module. You will need a suitable compiler. http://www.develer.com/oss/GccWinBinaries To tell distutils to use this compiler for all extension modules, create pydistutils.cfg file with the following contents: [build_ext] compiler=mingw32 See this page for details about this file: http://docs.python.org/inst/config-syntax.html You will get the most help about Traits and the rest of the Enthought Tool Suite on the enthought-dev mailing list. https://mail.enthought.com/mailman/listinfo/enthought-dev -- Robert Kern From larry.bates at websafe.com` Sun Jul 13 21:53:44 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 13 Jul 2008 20:53:44 -0500 Subject: Dictionary bidirectional In-Reply-To: <8923d0c5-29ce-495f-924a-6d9d2457138e@e39g2000hsf.googlegroups.com> References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> <792048c1-5e18-4a2c-925d-a1c932d18a91@j22g2000hsf.googlegroups.com> <8923d0c5-29ce-495f-924a-6d9d2457138e@e39g2000hsf.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > bukzor: >> You need to use two dictionaries. Here's a class that someone's >> written that wraps it up into a single dict-like object for you: >> http://www.faqts.com/knowledge_base/view.phtml/aid/4376 > > It contains code like: > > try: > del self.data[item] > except KeyError: > pass > > Exceptions are useful in python, but with dictionaries this is > probably faster (and shorter), even if it may perform two lookups: > > if item in self.data: > del self.data[item] > > Bye, > bearophile The only case where it would be faster would be if most of the keys were NOT in the dictionary (rather odd use case). Otherwise I believe you will find the first way quicker as the exceptions are infrequent. -Larry From manuel.dipl at gmail.com Mon Jul 14 09:44:00 2008 From: manuel.dipl at gmail.com (manu) Date: Mon, 14 Jul 2008 06:44:00 -0700 (PDT) Subject: trying to use sax for a very basic first xml parser Message-ID: <6ff86003-a3e8-4c5b-9276-1cd3c7f0ffa7@56g2000hsm.googlegroups.com> Hi, I need to parse xml files for the Blender Game Engine. ATM I am trying to get this script running in the BGE. This is my first script and I dont have much experience programming... import xml.sax class PnmlHandler(xml.sax.ContentHandler): def __init__(self): self.inPlace=0 def startElement(self, name, attrs): if name != "place": return if attrs.getLength()==0: return print 'Starting element:', name print "attrs:", attrs.keys() id = attrs.get("id", None) print "id:", id if name == "place": self.inPlace=1 def endElement(self, name): if name == "place": self.inPlace=0 parser = xml.sax.make_parser() parser.setContentHandler(PnmlHandler()) parser.parse(open("bpm.pnml","r")) this works in the IDLE ide. Output: Starting element: place attrs: [u'id'] id: p9723441 Starting element: place attrs: [u'id'] id: p26811937 Starting element: place attrs: [u'id'] id: p24278422[/code] but when I copy the script into blender and run it I get: [code]Compiled with Python version 2.5. Checking for installed Python... got it! Traceback (most recent call last): File "Text", line 27, in File "H:\Python25\lib\xml\sax\__init__.py", line 93, in make_parser raise SAXReaderNotAvailable("No parsers found", None) xml.sax._exceptions.SAXReaderNotAvailable: No parsers found[/code] Its probably a stupid question but thanks anyway! From sjmachin at lexicon.net Fri Jul 4 18:47:31 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 4 Jul 2008 15:47:31 -0700 (PDT) Subject: running python from cmd.exe References: Message-ID: On Jul 5, 7:38 am, Dominic Rice wrote: > Chris Hulan wrote: > > On Jul 4, 5:38 am, Dominic Rice wrote: > >> Dominic Rice wrote: > >>> Miki wrote: > >>>> Hello, > >>>>> I can't seem to get python to run my scripts using the command: python > >>>>> .py > >>>>> If I type python the interpreter runs as I sorted out the Path property, > >>>>> I'm afraid I don't know much about this kind of thing as I'm a science > >>>>> student who needs some Python not a programmer! > >>>> Can you be more specific about the error you get? > >>>> Say you have a script hw.py that contains one line: > >>>> print "Hello Python" > >>>> and you run > >>>> python hw.py > >>>> What is the error you get? > >>>> HTH, > >>>> -- > >>>> Miki > >>>>http://pythonwise.blogspot.com > >>> Sure, I get: > >>> can't open file .py: [errorno 2]No such file or directory. > >>> Now if I've noticed that if I change directory to (for instance) > >>> \Python25 where the script is the command runs fine.(?) > >> Oh I just noticed you specified hw.py, in that case just to clarify it > >> would be can't open file hw.py: [errorno 2]No such file or directory > > > When you run a script, are you in the directory where the script is > > located? > > when it works yes! Does it have to be the case then? I assumed that > there was a default folder (eg \Python25) that the python command would > look for the file in, I take it this is not the case then? The default folder *is* the "current" folder, i.e. "the directory that you are in". If you want to run a script in another folder, you specify the path to that script. This is usual in Windows command-line operation, not special to Python. By the way, storing your own files in the same folder structure as a software package (e.g. \Python25) is not a good idea. Keep them somewhere else e.g. a separate folder for each significantly different project, a folder for commonly useful stuff, and a junk folder for mucking about trying things out. Then when e.g. you upgrade to Python 2.6 the possibility of drama is reduced. HTH, John From robert.rawlins at thinkbluemedia.co.uk Fri Jul 18 07:03:24 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Fri, 18 Jul 2008 12:03:24 +0100 Subject: Unusual Exception Behaviour In-Reply-To: References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> <8904.90077804333$1216313689@news.gmane.org> <006001c8e831$5c1487b0$143d9710$@rawlins@thinkbluemedia.co.uk> <1214.94685668058$1216317006@news.gmane.org> Message-ID: <000d01c8e8c5$e6f8de50$b4ea9af0$@rawlins@thinkbluemedia.co.uk> Hi Mk, > To tell the truth I have never used logging module extensively, so I'm > not expert in this area and can't help you there. > > However, it seems to me that you may have stumbled upon some subtle bug > / side effect of logging module that could cause some side effects in > exceptions. Or perhaps it surfaces only in combination with glib? > > If you discover the root cause, please let us know on this ng, I'm also > using Python extensions and bindings to other libraries and this could > be of interest at least to me. Yeah it's got me a little bemused to be honest, I've tried playing around with configuration options this morning and not been able to achieve anything that works properly. I'll keep testing though and as soon as I have a root cause to the problem I'll be sure to let the list know. Thanks mate, Robert From xdicry at gmail.com Mon Jul 14 11:31:44 2008 From: xdicry at gmail.com (Evan) Date: Mon, 14 Jul 2008 08:31:44 -0700 (PDT) Subject: Is it possible to create "network conneciton" on windows system? Message-ID: Hello, one of my PC is window system, and in "control panel -> Network Connections", I can see some network connections such as PPPOE or VPN which I created by click "create a new connection". My question is, is it possible to create a new connection by using Python script? which means I do not want to use Window UI (via "control panel"), if it is possible, I can save so many time to create various network connection when I want to do testing in the lab. Thanks very much. Evan From bj_666 at gmx.net Sat Jul 19 12:31:31 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Jul 2008 16:31:31 GMT Subject: Change PC to Win or Windows References: Message-ID: <6eej73F6k7g3U3@mid.uni-berlin.de> On Sat, 19 Jul 2008 11:02:51 -0500, Grant Edwards wrote: > On 2008-07-19, Dennis Lee Bieber wrote: > >> Which term applied to the TRS-80, the Apple II, Altair even... > > Not that I remember. I had a homebrew S-100 bus system, worked > with varioius Commodore machines, a few Apples, and some other > CP/M systems. I never heard any of them called a 'PC'. My > recollection is that 'PC' was a term that IBM coined. The C64 that still sits on my desk has a label on it saying ?commodore 64 - personal computer?. Ciao, Marc 'BlackJack' Rintsch From kay.schluehr at gmx.net Fri Jul 25 01:06:35 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 24 Jul 2008 22:06:35 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> Message-ID: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> On 25 Jul., 03:01, Terry Reedy wrote: > Torsten Bronger wrote: > > Hall?chen! > > > And why does this make the implicit insertion of "self" difficult? > > > I could easily write a preprocessor which does it after all. > > class C(): > def f(): > a = 3 > > Inserting self into the arg list is trivial. Mindlessly deciding > correctly whether or not to insert 'self.' before 'a' is impossible when > 'a' could ambiguously be either an attribute of self or a local variable > of f. Or do you and/or Jordan plan to abolish local variables for methods? > > tjr This isn't the problem Jordan tries to address. It's really just about `self` in the argument signature of f, not about its omission in the body. Some problems occur when not `self` shall be used but e.g. `this`. Here one has to specify more: class C(): __self__ = 'this' # use `this` instead of `self` def f(a): this.a = a or class C(): def f($this, a): # use `this` instead of `self` this.a = a When an $-prefixed parameter is found the automatic insertion of `self` will be blocked and the $-prefixed parameter name will be used instead but without the prefix. From murugesan550 at gmail.com Thu Jul 24 23:40:59 2008 From: murugesan550 at gmail.com (muruges) Date: Thu, 24 Jul 2008 20:40:59 -0700 (PDT) Subject: .............................on line jobs........................................ Message-ID: <5a9a7101-d5f0-4dc1-a8d3-2c900965f8ad@a21g2000prf.googlegroups.com> we are selecting you for this online jobs. For more information see this website in this.............................. we are selecting you for this online jobs. For more information see this website in this.............................. Details .................. Name of the job.........................Online job.......................... Nature of work...........................Like data entry.......................... Qualification required........................good knowledge in computer Basics Earnings................More then Rs=1000 per day......................Earnings depends on your work............................. FOR MORE DETAILS: WWW.Bigconstructions5.blogspot.com From dp_pearce at hotmail.com Wed Jul 9 12:04:25 2008 From: dp_pearce at hotmail.com (dp_pearce) Date: Wed, 9 Jul 2008 09:04:25 -0700 (PDT) Subject: Anyone happen to have optimization hints for this loop? Message-ID: <43111321-2cc1-4a5e-9189-744131555841@26g2000hsk.googlegroups.com> I have some code that takes data from an Access database and processes it into text files for another application. At the moment, I am using a number of loops that are pretty slow. I am not a hugely experienced python user so I would like to know if I am doing anything particularly wrong or that can be hugely improved through the use of another method. Currently, all of the values that are to be written to file are pulled from the database and into a list called "domainVa". These values represent 3D data and need to be written to text files using line breaks to seperate 'layers'. I am currently looping through the list and appending a string, which I then write to file. This list can regularly contain upwards of half a million values... count = 0 dmntString = "" for z in range(0, Z): for y in range(0, Y): for x in range(0, X): fraction = domainVa[count] dmntString += " " dmntString += fraction count = count + 1 dmntString += "\n" dmntString += "\n" dmntString += "\n***\n dmntFile = open(dmntFilename, 'wt') dmntFile.write(dmntString) dmntFile.close() I have found that it is currently taking ~3 seconds to build the string but ~1 second to write the string to file, which seems wrong (I would normally guess the CPU/Memory would out perform disc writing speeds). Can anyone see a way of speeding this loop up? Perhaps by changing the data format? Is it wrong to append a string and write once, or should hold a file open and write at each instance? Thank you in advance for your time, Dan From ki4yjl at gmail.com Fri Jul 11 15:25:45 2008 From: ki4yjl at gmail.com (WDC) Date: Fri, 11 Jul 2008 12:25:45 -0700 (PDT) Subject: Simple question, how do you tell how many items in a list? References: <268ac2770807102256o4f41e784q79a0caf849c046b4@mail.gmail.com> Message-ID: On Jul 11, 2:53?pm, Terry Reedy wrote: > Alex Bryan wrote: > > I am just wondering how you get an integer value for how many items > > there are in a list, preferably w/o a for loop. > > Read the library reference sections on built-in functions and classes. Quite simple. If I understand you correctly, you have a list like this: >>> list = ['a', 'b', 'c', 'd'] As you can see, the list has 4 entries. The len() function also says that we have 4 entries. >>> len(list) 4 Now, if we wanted a particular entry, we would do this: >>> list[0] 'a' (Remember, when calling something in a list we count zero.) >>> list[3] 'd' Hope this helped. David From robert.rawlins at thinkbluemedia.co.uk Mon Jul 21 05:02:27 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Mon, 21 Jul 2008 10:02:27 +0100 Subject: Odd math related issue. In-Reply-To: References: <43332.3139710867$1216630189@news.gmane.org> Message-ID: <00de01c8eb10$7fb23a50$7f16aef0$@rawlins@thinkbluemedia.co.uk> > if you divide two integers, you'll get an integer back (in Python 2.X, > at least). quick fix: > > percentage = bytes_transferred * 100 / total_bytes > > Hey That worked a charm mate, thanks for the info. From larry.bates at websafe.com` Sun Jul 13 01:16:13 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 13 Jul 2008 00:16:13 -0500 Subject: Determining when a file has finished copying In-Reply-To: <7198df5e-e5e6-4b2d-9a7c-9ef2e30c87d1@x35g2000hsb.googlegroups.com> References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> <7198df5e-e5e6-4b2d-9a7c-9ef2e30c87d1@x35g2000hsb.googlegroups.com> Message-ID: Sean DiZazzo wrote: > On Jul 9, 5:34 pm, keith wrote: >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> >> >> Ethan Furman wrote: >>> writeson wrote: >>>> Guys, >>>> Thanks for your replies, they are helpful. I should have included in >>>> my initial question that I don't have as much control over the program >>>> that writes (pgm-W) as I'd like. Otherwise, the write to a different >>>> filename and then rename solution would work great. There's no way to >>>> tell from the os.stat() methods to tell when the file is finished >>>> being copied? I ran some test programs, one of which continously >>>> copies big files from one directory to another, and another that >>>> continously does a glob.glob("*.pdf") on those files and looks at the >>>> st_atime and st_mtime parts of the return value of os.stat(filename). >>>>> From that experiment it looks like st_atime and st_mtime equal each >>>> other until the file has finished being copied. Nothing in the >>>> documentation about st_atime or st_mtime leads me to think this is >>>> true, it's just my observations about the two test programs I've >>>> described. >>>> Any thoughts? Thanks! >>>> Doug >>> The solution my team has used is to monitor the file size. If the file >>> has stopped growing for x amount of time (we use 45 seconds) the file is >>> done copying. Not elegant, but it works. >>> -- >>> Ethan >> Also I think that matching the md5sums may work. Just set up so that it >> checks the copy's md5sum every couple of seconds (or whatever time >> interval you want) and matches against the original's. When they match >> copying's done. I haven't actually tried this but think it may work. >> Any more experienced programmers out there let me know if this is >> unworkable please. >> K >> -----BEGIN PGP SIGNATURE----- >> Version: GnuPG v1.4.6 (GNU/Linux) >> Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org >> >> iD8DBQFIdVkX8vmNfzrLpqoRAsJ2AKCp8wMz93Vz8y9K+MDSP33kH/WHngCgl/wM >> qTFBfyIEGhu/dNSQzeRrwYQ= >> =Xvjq >> -----END PGP SIGNATURE----- > > I use a combination of both the os.stat() on filesize, and md5. > Checking md5s works, but it can take a long time on big files. To fix > that, I wrote a simple sparse md5 sum generator. It takes a small > number bytes from various areas of the file, and creates an md5 by > combining all the sections. This is, in fact, the only solution I have > come up with for watching a folder for windows copys. > > The filesize solution doesn't work when a user copies into the watch > folder using drag and drop on Windows because it allocates all the > attributes of the file before any data is written. The filesize will > always show the full size of the file. > > ~Sean While a lot depends on HOW the copying program does its copy, I've recently been able to get pyinotify to watch folders. By watching for IN_CLOSE_WRITE events I can see when files are closed by the writer and then process them instantly after they have been written. Now if the writer does something like: open write close open append write close . . . This won't work as well. FYI, Larry From is_this at visible.com Tue Jul 29 21:23:00 2008 From: is_this at visible.com (Bruce Frederiksen) Date: Wed, 30 Jul 2008 01:23:00 +0000 Subject: static variables in Python? References: Message-ID: <417ec$488fc274$18607848$7519@KNOLOGY.NET> On Tue, 29 Jul 2008 21:31:01 +0000, kj wrote: > In Larry Bates writes: > > [snip] > > Maybe it's easier to see what I mean with JavaScript: > > function foo() { > if (foo.x === undefined) foo.x = expensive_call(); > return do_stuff_with(foo.x); > } def foo(): if not hasattr(foo, 'x'): foo.x = expensive_call() return do_stuff_with(foo.x) or, maybe just define foo in two steps: def foo(): return do_stuff_with(foo.x) foo.x = expensive_call() From rNOSPAMon at flownet.com Sun Jul 6 03:47:50 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 06 Jul 2008 00:47:50 -0700 Subject: Parsing MIME-encoded data in an HTTP request References: <3a11k5-al7.ln1@nb2.stroeder.com> <5fq3k5-eva.ln1@nb2.stroeder.com> Message-ID: In article <5fq3k5-eva.ln1 at nb2.stroeder.com>, Michael Str?der wrote: > Ron Garret wrote: > > In article , > > Ron Garret wrote: > > > >> In article <3a11k5-al7.ln1 at nb2.stroeder.com>, > >> Michael Str?der wrote: > >> > >>> Ron Garret wrote: > >>>> I'm writing a little HTTP server and need to parse request content that > >>>> is mime-encoded. All the MIME routines in the Python standard library > >>>> seem to have been subsumed into the email package, which makes this > >>>> operation a little awkward. > >>> How about using cgi.parse_multipart()? > >>> > >> Unfortunately cgi.parse_multipart doesn't handle nested multiparts, > >> which the requests I'm getting have. You have to use a FieldStorage > >> object to do that, and that only works if you're actually in a cgi > >> environment, which I am not. The server responds to these requests > >> directly. > >> > >> Anyway, thanks for the idea. > > > > Hm, it actually seems to work if I manually pass in the outerboundary > > parameter and environ={'REQUEST_METHOD':'POST'} That seems like the > > Right Answer. > > I'm also using it to parse form parameters in a message body received by > POST. > > CIao, Michael. Just for the record, here's the incantation I ended up with: class post_handler(BaseHTTPRequestHandler): def do_POST(self): form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST'}) ... works like a charm. rg From deliverable at gmail.com Sun Jul 27 17:23:04 2008 From: deliverable at gmail.com (braver) Date: Sun, 27 Jul 2008 14:23:04 -0700 (PDT) Subject: with statement for two files Message-ID: <08d72316-15f1-45dd-b1f7-7b8ee06efef5@e39g2000hsf.googlegroups.com> Can open two files in a with statement: with open(src) as readin, open(dst,"w") as writin: # WRONG: comma doesn't work ... -- so that you have transactional safety for two file descriptors? The comma syntax doesn't work, but is there a way, except for with open(src) as readin: with open(dst,"w) as writin: ... Cheers, Alexy From maric at aristote.info Wed Jul 30 11:20:05 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 30 Jul 2008 17:20:05 +0200 Subject: Pointers/References in Python? In-Reply-To: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> References: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Message-ID: <200807301720.06023.maric@aristote.info> Le Wednesday 30 July 2008 16:46:37 boblatest at googlemail.com, vous avez ?crit?: > Hello, > > I have a long list of memory-heavy objects that I would like to access > in differently sorted order. Let's say I'd like to have lists called > by_date or by_size that I can use to access the objects in the > specified order. > ... > I know there is a thing called "shallow copy" that has something to do > with not duplicating memory content but I don't understand the > concept. Maybe that's what would help here, too. > In fact, all containers in python contains references of objects. >>>[54]: a = [1] >>>[55]: b = [a] >>>[56]: c = list(sorted(b)) >>>[57]: b, c ...[57]: ([[1]], [[1]]) >>>[58]: b.append(3) >>>[59]: b, c ...[59]: ([[1], 3], [[1]]) >>>[60]: a.append(0) >>>[61]: b, c ...[61]: ([[1, 0], 3], [[1, 0]]) This is if you want to make a true copy (called deep copy) that you'll have to do extra steps (using copy module for example). -- _____________ Maric Michaud From sjmachin at lexicon.net Mon Jul 21 08:36:39 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 21 Jul 2008 05:36:39 -0700 (PDT) Subject: Odd math related issue. References: <43332.3139710867$1216630189@news.gmane.org> Message-ID: <32ee578a-3c8e-4312-ba51-682cacd1d536@i20g2000prf.googlegroups.com> On Jul 21, 10:21 pm, Alexandru Palade wrote: > > Another thing, you could have just added a dot after the constant in > order to promote the expression to be evaluated as float. As in > percentage = bytes_transferred / /self/.__sessions[path].total_bytes > * 100. > (notice the last dot) > True, you get a float result, but not a very useful one: >>> a = 2 >>> b = 11 >>> a / b * 100 # OP's problem 0 >>> a / b * 100. # Your suggestion; same as (a / b) *100. 0.0 >>> a * 100 / b # Fredrik's suggestion 18 >>> a * 100. / b # What you probably meant 18.181818181818183 >>> From kay.schluehr at gmx.net Fri Jul 18 00:39:58 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 17 Jul 2008 21:39:58 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> Message-ID: On 18 Jul., 01:15, castironpi wrote: > On Jul 17, 5:37 pm, I V wrote: > > > > > On Thu, 17 Jul 2008 15:08:17 -0700, castironpi wrote: > > > The Python disassembly is baffling though. > > > >>>> y= 3 > > >>>> dis.dis('x=y+1') > > > You can't disassemble strings of python source (well, you can, but, as > > you've seen, the results are not meaningful). You need to compile the > > source first: > > > >>> code = compile('y=x+1','-', 'single') > > >>> dis.dis(code) > > > 1 0 LOAD_NAME 0 (x) > > 3 LOAD_CONST 0 (1) > > 6 BINARY_ADD > > 7 STORE_NAME 1 (y) > > 10 LOAD_CONST 1 (None) > > 13 RETURN_VALUE > > > You may well find these byte codes more meaningful. Note that there is a > > list of opcodes athttp://docs.python.org/lib/bytecodes.html > > Oh. How is the stack represented? As a pointer to a pointer of PyObject structs. > Does it keep track of which stack > positions (TOS, TOS1, etc.) are in what registers? Does stack > manipulation consume processor cycles? Python does not store values in registers. It stores locals in arrays and accesses them by position ( you can see the positional index in the disassembly right after the opcode name ) and globals / object attributes in dicts. For more information you might just download the source distribution and look for src/Python/ceval.c. This file contains the main interpreter loop. From pop.alert at gmail.com Wed Jul 2 10:40:18 2008 From: pop.alert at gmail.com (nabblepop) Date: Wed, 2 Jul 2008 07:40:18 -0700 (PDT) Subject: Spell suggest for locations Message-ID: <18239043.post@talk.nabble.com> I'm working on spell suggestions for a list of places(~10^6) e.g pizza hut I was trying to change the behaviour of print (tee all output to a temp file) by inheriting from file and overwriting sys.stdout, but it looks like print uses C-level stuff to do its writes which bypasses the python object/inhertiance system. It looks like I need to use composition instead of inheritance, but thought this was strange enough to note. $python -V Python 2.5 """A short demo script""" class notafile(file): def __init__(self, *args, **kwargs): readonly = ['closed', '__class__', 'encoding', 'mode', 'name', 'newlines', 'softspace'] file.__init__(self, *args, **kwargs) for attr in dir(file): if attr in readonly: continue setattr(self, attr, None) def main(): n = notafile('/dev/stdout', "w") print vars(n) import sys sys.stdout = n print "Testing: 1, 2, 3..." output: {'__str__': None, 'xreadlines': None, 'readlines': None, 'flush': None, 'close': None, 'seek': None, '__init__': None, '__setattr__': None, '__reduce_ex__': None, '__new__': None, 'readinto': None, 'next': None, 'write': None, '__doc__': None, 'isatty': None, 'truncate': None, 'read': None, '__reduce__': None, '__getattribute__': None, '__iter__': None, 'readline': None, 'fileno': None, 'writelines': None, 'tell': None, '__delattr__': None, '__repr__': None, '__hash__': None} Testing: 1, 2, 3... From ojeeves at gmail.com Tue Jul 8 11:13:18 2008 From: ojeeves at gmail.com (oj) Date: Tue, 8 Jul 2008 08:13:18 -0700 (PDT) Subject: caseless dict - questions References: <77798300-820f-4175-a9cb-aef639d42a32@m45g2000hsb.googlegroups.com> Message-ID: <3d9a9693-b333-484e-abde-b1933f2e2b65@c65g2000hsa.googlegroups.com> On Jul 5, 1:57?am, Phoe6 wrote: > I have a requirement for using caseless dict. I searched the web for > many different implementations and found one snippet which was > implemented in minimal and useful way. > > ############# > import UserDict > > class CaseInsensitiveDict(dict, UserDict.DictMixin): > ? ? def __init__(self, *args, **kwargs): > ? ? ? ? self.orig = {} > ? ? ? ? super(CaseInsensitiveDict, self).__init__(*args, **kwargs) > ? ? def items(self): > ? ? ? ? keys = dict.keys(self) > ? ? ? ? values = dict.values(self) > ? ? ? ? return [(self.orig[k],v) for k in keys for v in values] > ? ? def __setitem__(self, k, v): > ? ? ? ? hash_val = hash(k.lower()) > ? ? ? ? self.orig[hash_val] = k > ? ? ? ? dict.__setitem__(self, hash_val, v) > ? ? def __getitem__(self, k): > ? ? ? ? return dict.__getitem__(self, hash(k.lower())) > > obj = CaseInsensitiveDict() > obj['Name'] = 'senthil' > print obj > print obj.items() > > obj1 = {} > obj1['Name'] = 'senthil' > print obj1 > print obj1.items() > ########### > [ors at goofy python]$ python cid1.py > {15034981: 'senthil'} > [('Name', 'senthil')] > {'Name': 'senthil'} > [('Name', 'senthil')] > > --- > The difference between the Caselessdict and {} is that when called as > the object, the Caselessdict() is giving me the internal > representation. > obj = CaseInsensitiveDict() > obj['Name'] = 'senthil' > print obj > gives: {15034981: 'senthil'} > > obj1 = {} > obj1['Name'] = 'senthil' > print obj1 > Correctly gives {'Name': 'senthil'} > > What changes should I make to CaseInsensitiveDict ( written above), so > that its instance gives the actual dictionary instead of its internal > representation. > Constructing a dictionary and returning from __init__ method did not > work. > > TIA, > Senthil What I think you need to do, is define a __repr__(self) method (see http://docs.python.org/ref/customization.html) Something like: def __repr__(self): return dict(self.items()) I /think/ will work. I haven't tested it though. This isn't exactly what repr is supposed to do - evaling it won't give you the correct object back. Defining __str__ might be a better approach. -Oli From Scott.Daniels at Acm.Org Mon Jul 28 08:45:38 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 28 Jul 2008 05:45:38 -0700 Subject: write unsigned integer 32 bits to socket In-Reply-To: References: Message-ID: <9_KdnfSDZ9xHIRDVnZ2dnUVZ_gCdnZ2d@pdx.net> Alan Franzoni wrote: > Michael Torrie was kind enough to say: > >> Of course any time you send coherent numbers over the network, I highly >> recommend you use what's called network byte order.... I'm sure python >> has some convention in the struct module for dealing with this. > > Not in the struct module; such functions are available in the socket > module, and should be employed indeed. Please don't pass this misinformation along. In the struct module document, see the section on the initial character: Character Byte order Size and alignment @ native native = native standard < little-endian standard > big-endian standard ! network (= big-endian) standard and notes @ is the default. >>> print struct.pack('>> print struct.pack('>lh', 3,4) >>> print struct.pack('lh', 3,4) >>> print struct.pack('!lh', 3,4) From larry.bates at websafe.com` Tue Jul 15 15:38:01 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 14:38:01 -0500 Subject: graphing lifelines In-Reply-To: References: Message-ID: E. J. Gold is the Hi-Tech Shaman wrote: > (crossposted to sci.math) > > I'm looking for a tool which will take a dataset of tuples indicating > the year of birth and death of a person: > > (1872, 1950, "Sri Aurobindo") > (1821, 1910, "Mary Baker Eddy") > (1831, 1891, "HP. Blavatksy") > > And graph them out, in bars, annotating them with the person's name. > > A simple spreadsheet would've worked, but they seem to start from > zero. Thus, I would only be able to indicate the span of life (by > subtracting death year from birth year). Certainly a "Hi-Tech Shaman" can whip something up to do this, right? -Larry P. S. you will need look for something like a high-low graph or do something custom. I've used ReportLab's Graphing module quite effectively. All depends on what format you want the output to be in. From fuzzyman at gmail.com Mon Jul 28 18:58:38 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 28 Jul 2008 15:58:38 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> Message-ID: <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> On Jul 27, 6:02?am, castironpi wrote: > On Jul 24, 11:04?pm, Tim Roberts wrote: > > > > > castironpi wrote: > > > >Compiling a program is different than running it. ?A JIT compiler is a > > >kind of compiler and it makes a compilation step. ?I am saying that > > >Python is not a compiler and in order to implement JIT, it would have > > >to change that fact. > > > And I'm saying you are wrong. ?There is NOTHING inherent in Python that > > dictates that it be either compiled or interpreted. ?That is simply an > > implementation decision. ?The CPython implementation happens to interpret. > > The IronPython implementation compiles the intermediate language to native > > machine language. > > > >> of Python that uses .NET. ?In that case, the code *IS* JIT compiled to > > >> assembly when the program starts. > > > >But still not the user's code, only the interpreter, which is running > > >in assembly already anyway in CPython. > > > In CPython, yes. ?In IronPython, no; the user's code is compiled into > > machine language. ?Both of them are "Python". > > -- > > Tim Roberts, t... at probo.com > > Providenza & Boekelheide, Inc. > > In CPython yes. ?In IronPython yes: ?the parts that are compiled into > machine code are the interpreter, *not user's code*. ?Without that > step, the interpreter would be running on an interpreter, but that > doesn't get the user's statement 'a= b+ 1' into registers-- it gets > 'push, push, add, pop' into registers. Well - in IronPython user code gets compiled to in memory assemblies which can be JIT'ed. Michael Foord -- http://www.ironpythoninaction.com/ From larry.bates at websafe.com` Tue Jul 15 19:46:01 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 18:46:01 -0500 Subject: Modify a string's value In-Reply-To: References: Message-ID: s0suk3 at gmail.com wrote: > Hi everyone, > > I've heard that a 'str' object is immutable. But is there *any* way to > modify a string's internal value? > > Thanks, > Sebastian Why would you care? Just create a new string (with the changed contents) and let garbage collection take care of the old one when all the references to it have gone away. Since these types of questions seem to appear almost every day on this list, this Python stuff is so much different than old languages people have hard time making the conceptual "jump". You can basically quite worrying about how/where things are stored, they just are. -Larry From catherine.heathcote at gmail.com Tue Jul 22 12:26:22 2008 From: catherine.heathcote at gmail.com (Catherine Heathcote) Date: Tue, 22 Jul 2008 17:26:22 +0100 Subject: Question about inheritence Message-ID: If I create a new class inherited from another with a constructor, what happens with the new class's constructer? Thanks for your time. From mal at egenix.com Wed Jul 2 04:39:13 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 02 Jul 2008 10:39:13 +0200 Subject: convert unicode characters to visibly similar ascii characters In-Reply-To: References: Message-ID: <486B3EB1.6050907@egenix.com> On 2008-07-01 20:31, Peter Bulychev wrote: > Hello. > > I want to convert unicode character into ascii one. > The method ".encode('ASCII') " can convert only those unicode characters, > which fit into 0..128 range. > > But there are still lots of characters beyond this range, which can be > manually converted to some visibly similar ascii characters. For instance, > there are several quotation marks in unicode, which can be converted into > ascii quotation mark. > > Can this conversion be performed in automatic manner? After googling I've > only found that there exists Unicode database, which stores human-readable > information on notation of all unicode characters ( > ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt). And there also exists > the Python adapter for this database ( > http://docs.python.org/lib/module-unicodedata.html). Using this database I > can do something like `if notation.find('QUOTATION')!=-1:\n\treturn "'"`. I > believe there is more elegant way. Am I right? You could write a codec which translates Unicode into a ASCII lookalike characters, but AFAIK there is no standard for doing this. I guess the best choice is to use the Unicode code point names as basis. These can be accessed via unicodedata.name(). You can then create a mapping which can be processed by the character map codec. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 02 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania 4 days to go :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From adam at krusty.madoff.com Thu Jul 3 11:06:12 2008 From: adam at krusty.madoff.com (Adam Lanier) Date: Thu, 03 Jul 2008 11:06:12 -0400 Subject: Interest not met. In-Reply-To: <849453.75351.qm@web23404.mail.ird.yahoo.com> References: <849453.75351.qm@web23404.mail.ird.yahoo.com> Message-ID: <486CEAE4.6010301@krusty.madoff.com> david odey wrote: > I write to inform you that the reason I subscribed to this web page > is not been met. > > I want to be sent sample codes in programming languages especially > python and an email tutorial on C#. I will be happy if these demands > are met. > > Thanks in anticipation. > > > > ALWAYS THERE FOR YOU Well, good luck getting your demands met. From castironpi at gmail.com Wed Jul 30 00:20:04 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 29 Jul 2008 21:20:04 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> Message-ID: On Jul 29, 7:39?am, alex23 wrote: > On Jul 29, 2:21?pm, castironpi wrote: > > > On Jul 28, 5:58?pm, Fuzzyman wrote: > > > Well - in IronPython user code gets compiled to in memory assemblies > > > which can be JIT'ed. > > > I don't believe so. > > Uh, you're questioning someone who is not only co-author of a book on > IronPython, but also a developer on one of the first IronPython-based > commercial applications. > > I know authorship isn't always a guarantee of correctness, but what > experience do you have with IronPython that makes you so unwilling to > accept the opinion of someone with substantial knowledge of the > subject? None, no experience, no authority, only the stated premises & classifications, which I am generally tending to misinterpret. I'm overstepping my bounds and trying to do it politely. (Some might call it learning, which yes, though uncustomary, *requires questioning authorities*, or reinventing.) Evidently, I have a "fundamental misunderstanding of the compilation process", which I'm trying to correct by stating what I believe. I'm trying to elaborate, and I'm meeting with increasingly much detail. So, perhaps I'll learn something out of this. Until then... What I know I have is two conflicting, contradictory, inconsistent beliefs. Maybe I've spent too much time in Python to imagine how a dynamic language can compile. This is from 7/22/08, same author: > I wouldn't say "can't". The current CPython VM does not compile > code. It COULD. The C#/.NET VM does. Three big claims here that I breezed right over and didn't believe. > It COULD. I'm evidently assuming that if it could, it would. > The current CPython VM does not compile code. Therefore it couldn't, or the assumption is wrong. Tim says it is. And the glaring one-- WHY NOT? Why doesn't CPython do it? From 7/18/08, own author: >> #define TOP() (stack_pointer[-1]) #define BASIC_POP() (*--stack_pointer) ...(line 1159)... w = POP(); v = TOP(); if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { /* INLINE: int + int */ register long a, b, i; a = PyInt_AS_LONG(v); b = PyInt_AS_LONG(w); i = a + b; << I am imagining that every Python implementation has something like it. If IronPython does not, in particular, not have the 'POP(); TOP();' sequence, then it isn't running on a stack machine. Is the IronPython code open source, and can someone link to it? I'm not wading through it from scratch. What does it have instead? Does dynamic typing still work? If you're bluffing, bluff harder; I call. If you're not, I apologize; teach me something. If you can ask better, teach me that too. From ggpolo at gmail.com Wed Jul 23 11:44:24 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 23 Jul 2008 12:44:24 -0300 Subject: Proper way to query user and group database on a Unix host? In-Reply-To: References: <87d4l5ozsc.fsf@cox.net> Message-ID: On Wed, Jul 23, 2008 at 9:16 AM, Sebastian lunar Wiesner wrote: > Chris Brannon : > > Iirc since Python 2.5 these tuples are named ... > >> Instead, do this: >> >> import grp >> groupname = 'users' >> groupusers = grp.getgrnam(groupname)[3] > ... thus this line could be written as: > > groupusers = grp.getgrnam(groupname).gr_mem > That is valid since Python 2.3 actually > Slightly more readable, imho > > > > -- > Freedom is always the freedom of dissenters. > (Rosa Luxemburg) > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From rkmr.em at gmail.com Sun Jul 27 22:15:10 2008 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Sun, 27 Jul 2008 19:15:10 -0700 Subject: write unsigned integer 32 bits to socket In-Reply-To: References: Message-ID: On Sun, Jul 27, 2008 at 7:01 PM, Larry Bates wrote: > rkmr.em at gmail.com wrote: >> i want to send unsigned 32 bit integer to socket, and looking for >> something equivalent to this method... >> http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt() >> >> is there such method / library available in python?! > You will need to use struct module to build the 4 byte value and then send > it. > > Something like (not tested): > > import struct > us32bit = struct.pack("I", value) > s.send(us32bit) thanks a lot!!! just to make sure if I want 32 bit or 4 bytes then should I use the short or integer or long? this is short >>> struct.pack('!h',3) '\x00\x03' this is integer >>> struct.pack('!i',3) '\x00\x00\x00\x03' this is long >>> struct.pack('!l',3) '\x00\x00\x00\x03' From sleytr at gmail.com Thu Jul 17 08:48:50 2008 From: sleytr at gmail.com (Evren Esat Ozkan) Date: Thu, 17 Jul 2008 05:48:50 -0700 (PDT) Subject: Javascript - Python RSA encryption interoperability References: <79934f50-2208-4e68-8d61-1fd33d34a468@a1g2000hsb.googlegroups.com> Message-ID: <3e907959-32ab-4b98-bf7c-b19cf2776880@27g2000hsf.googlegroups.com> Hi, Thank you very much. Your code is worked like a charm and saved my honeymoon :) Thanks again, Evren On Jul 4, 6:19?pm, marek.ro... at wp.pl wrote: > Evren Esat Ozkan napisa?(a): > > > > > > > Hello, > > > I'm trying to encrypt a string with RSA. But it needs to be compitable > > with Dave's JavaScript RSA implementation*. I'm already read and tried > > lots of different things about RSA and RSA in Python. But could not > > produce the same result with the javascript library. > > > My experiments could be seen at:http://dpaste.com/hold/60741/ > > > * JavaScript RSA Library:http://www.ohdave.com/rsa/ > > > Python libraries which I tried; > > * PyCrtypo:http://www.amk.ca/python/code/crypto.html > > * rsa library fromhttp://www.stuvel.eu/rsa > > > How could I create the same results with the JS library in Python. > > > Any help would be appreciated > > > Evren, > > It seems that this Javascript is doing weird things to its input, > namely processing it in reverse. Try encrypting ciphertext[::-1] > instead of just ciphertext. > > public_modulus_hex = '9F2E..snip..4BC7' > public_exponent_hex = '10001' > public_modulus = int(public_modulus_hex, 16) > public_exponent = int(public_exponent_hex, 16) > > def encrypt(plaintext_text): > ? ? ? ? # Beware, plaintext must be short enough to fit in a single block! > ? ? ? ? plaintext = int(plaintext_text.encode('hex'), 16) > ? ? ? ? ciphertext = pow(plaintext, public_exponent, public_modulus) > ? ? ? ? return '%X' % ciphertext # return hex representation > > print encrypt('12345') > print encrypt('12345'[::-1]) # Will return the value compatible with > JS output > > Regards, > Marek From circularfunc at yahoo.se Thu Jul 3 12:51:44 2008 From: circularfunc at yahoo.se (defn noob) Date: Thu, 3 Jul 2008 09:51:44 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: <6d4bfmFp3aoU1@mid.uni-berlin.de> Message-ID: <0f6f795d-8041-463e-8e98-9d830ca3fc5b@l42g2000hsc.googlegroups.com> well the reason i unzipped and placed it in site-packages was because nothign happened when i ran setup.py(unzipped). this has worked with other packages before. From elbertlev at hotmail.com Mon Jul 14 02:53:08 2008 From: elbertlev at hotmail.com (Lev Elbert) Date: Sun, 13 Jul 2008 23:53:08 -0700 (PDT) Subject: Newbie Threading Question References: Message-ID: <52334d8a-c9ca-4560-8ad6-729ca4175811@8g2000hse.googlegroups.com> On Jul 13, 8:33?am, Sparky wrote: > It seems strange, but I can't find a list of operating systems which > support / don't support threading in Python. Can anyone point me in > the right direction? > > Thanks, > Sam Here is the list (from Python documentation of thread module): ================================================== 7.4 thread -- Multiple threads of control This module provides low-level primitives for working with multiple threads (a.k.a. light-weight processes or tasks) -- multiple threads of control sharing their global data space. For synchronization, simple locks (a.k.a. mutexes or binary semaphores) are provided. The module is optional. It is supported on Windows, Linux, SGI IRIX, Solaris 2.x, as well as on systems that have a POSIX thread (a.k.a. ``pthread'') implementation. For systems lacking the thread module, the dummy_thread module is available. It duplicates this module's interface and can be used as a drop-in replacement. ================================================== From motoom at xs4all.nl Tue Jul 15 10:15:39 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Tue, 15 Jul 2008 16:15:39 +0200 Subject: Characters Being Misread Message-ID: <2.2.32.20080715141539.0125b010@pop.xs4all.nl> Victor wrote... >>>> import binascii >>>> binascii.unhexlify('\x0c') >TypeError: Odd-length string >What gives here? The function unhexlify() wants an even-length string. From the online help: >>> help(binascii.unhexlify) unhexlify(...) a2b_hex(hexstr) -> s; Binary data of hexadecimal representation. hexstr must contain an even number of hex digits (upper or lower case). This function is also available as "unhexlify()" And you use it like this: >>> binascii.unhexlify("41") 'A' You feed it data without any '0x' prefixes. What are you trying to do? Parsing an RTF file which contains unicode characerts, encoded as hexadecimal? Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From cokofreedom at gmail.com Tue Jul 1 10:15:43 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 1 Jul 2008 07:15:43 -0700 (PDT) Subject: Installing paramiko and pycrypto Message-ID: <4856638d-1c86-4d4d-ba50-4a808f722f10@79g2000hsk.googlegroups.com> I am really stuck presently, trying to install these on my Windows XP. I have downloaded easy_install and it is now in Python25\Scripts but none of the commands I have read in either program folder have worked to install them. I was hoping someone could give me a step by step guide to installing these so I can use paramiko to perform SSH. Or at least point me in the right direction... Thanks Coko From deets at nospam.web.de Thu Jul 17 03:59:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 17 Jul 2008 09:59:38 +0200 Subject: how to debug python's extend module written in c/c++ on windows In-Reply-To: References: <64d771b2-fbc8-4b6a-9725-3dc5063c5328@p25g2000hsf.googlegroups.com> <6e83v4F5pfg0U1@mid.uni-berlin.de> Message-ID: <6e8cfgF5n34gU1@mid.uni-berlin.de> tcfg at sina.com schrieb: > dear Diez: > > I need step into c function in extending module(DLL) when debugging > the script. and I want Single-step debugging the extend module itself, > but python script Launched The whole process. That is exactly what attaching a C-debugger to python will give you. Did you actually try it? Do you know how to debug C-programs? Diez From miki.tebeka at gmail.com Thu Jul 3 16:00:41 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 3 Jul 2008 13:00:41 -0700 (PDT) Subject: Using Gnuplot and making an exe file outv the prog References: Message-ID: <54f1a50a-364d-4b71-ab3e-05b3b8b01db3@w1g2000prd.googlegroups.com> Hello, > Hello. Been using the gnuplot lately. Program runs fine. And its plots > as well. Now i want to make an exe file out of this program using > py2exe. Cud some1 help me in telling me how this is done. Thnks You probably mean the Python gnuplot bindings (otherwise you're in the wrong mailing list). Can you be more descriptive about the problem you have with py2exe? HTH, -- Miki http://pythonwise.blogspot.com From qgallet at gmail.com Fri Jul 18 06:45:49 2008 From: qgallet at gmail.com (Quentin Gallet-Gilles) Date: Fri, 18 Jul 2008 12:45:49 +0200 Subject: Question on Joining of list In-Reply-To: References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> <6eb733F67cpfU2@mid.uni-berlin.de> <32a81d0c-a74f-4b22-8add-15beb2643529@h17g2000prg.googlegroups.com> <8b943f2b0807180311p5ec7abady6736c381b06f19c6@mail.gmail.com> Message-ID: <8b943f2b0807180345u30dd9908va4a910e6818298dd@mail.gmail.com> Actually, since you want to keep the missing words apart from the found ones, it's not necessary to do that. Using "first_char" and "missing_word" (quoting Peter's code) as lists instead of strings comes to mind, then you can join both lists into a string once the code exits the for loop. Cheers, Quentin On Fri, Jul 18, 2008 at 12:34 PM, Subhabrata Banerjee < subhabrata.iisc at hotmail.com> wrote: > Dear Quentin, > That's true but where to place, if I use it after elif it is not giving > result but if I give in after for there is no use of iteration. > I'm thinking to use a3.find(s) whichever not availiable to split and > iterate and join with s. > Best Regards, > Subhabrata. > > > ------------------------------ > > Date: Fri, 18 Jul 2008 12:11:00 +0200 > From: qgallet at gmail.com > To: subhabrata.iisc at hotmail.com > Subject: Re: Question on Joining of list > > > > In that case, the line 's=a5+" "+a6' should be inside the for loop (and > slightly modified to concatenate the results) > > Cheers, > Quentin > > On Fri, Jul 18, 2008 at 12:00 PM, SUBHABRATA > wrote: > > Sorry if I didn't say that. > The input is a string "Petrol Helium Heaven Sky" > Now, in a3 it is "God Goddess Heaven Sky" is there, > it is matching Heaven and Sky but not Petrol and Helium as they are > not in a3. > Now, as per the code it is giving me an output "S" of "Sky" and > "Helium" > But I was looking for an output of "H S Petrol Helium" and not "S > Helium" meaning all the values of a5 and a6 will be concatenated in s. > Best Regards, > Subhabrata.. > > Marc 'BlackJack' Rintsch wrote: > > On Fri, 18 Jul 2008 01:31:59 -0700, SUBHABRATA wrote: > > > > > def try2(n): > > > a1=raw_input("PRINT A STRING:") > > > a2=a1.split() > > > a3="God Godess Heaven Sky" > > > for x in a2: > > > a4=a3.find(x) > > > if a4>-1: > > > a5=a3[a4] > > > print a5 > > > elif a4<0: > > > a6=x > > > print "It is not found" > > > print a6 > > > else: > > > print "Error" > > > s=a5+" "+a6 > > > print s > > > > > > Here, if I put a string like: > > > Petrol Helium Heaven Sky > > > In s it is giving me S Helium > > > But I am looking for an output of a5 and a6 concatenating all its > > > values not the last ones. Can you suggest me any help? Am I missing > > > any minor point? > > > > Maybe you should describe what the input looks like and what output you > > want to have and how the input and output are connected. In words, not > in > > not very clear code with "numbered names". That's a silly idea and makes > > understanding the code very hard. Please use meaningful names! > > > > Ciao, > > Marc 'BlackJack' Rintsch > -- > http://mail.python.org/mailman/listinfo/python-list > > > > ------------------------------ > This is your window into tinsel town. Keep abreast with the latest movie > releases, star shockers and juicy gossip. Try it! > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Nikolaus at rath.org Mon Jul 28 03:43:30 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 28 Jul 2008 09:43:30 +0200 Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: <87k5f6sbbx.fsf@nokile.rath.org> Bruno Desthuilliers writes: > The fact that a function is defined within a class statement doesn't > imply any "magic", it just creates a function object, bind it to a > name, and make that object an attribute of the class. You have the > very same result by defining the function outside the class statement > and binding it within the class statement, by defining the function > outside the class and binding it to the class outside the class > statement, by binding the name to a lambda within the class statement > etc... But why can't the current procedure to resolve method calls be changed to automatically define a 'self' variable in the scope of the called function, instead of binding its first argument? Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From kanchana.senevirathna at gmail.com Wed Jul 23 03:55:58 2008 From: kanchana.senevirathna at gmail.com (Kanch) Date: Wed, 23 Jul 2008 00:55:58 -0700 (PDT) Subject: xpathEval fails for large files References: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> <48864b0d$0$9494$9b4e6d93@newsspool3.arcor-online.net> <4886ca3b$0$18828$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <3157e3bd-12f0-4559-90e5-0090e1a28bee@h1g2000prh.googlegroups.com> On Jul 23, 11:05 am, Stefan Behnel wrote: > Kanch wrote: > > Original file was 18MB, and contained 288328 element attributes for > > the particular path. > > You didn't say how many elements there are in total, but I wouldn't expect > that to be a problem, unless you have very little free memory (say, way below > 256MB). I just tried with lxml 2.1 and a 40MB XML file with 300 000 elements > and it lets the whole Python interpreter take up some 140MB of memory in > total. Looping over all elements by calling "list(root.iter())" takes a bit > more than one second on my laptop. That suggests that /any/ solution involving > lxml (or cElementTree) will do just fine for you. > > > I wonder whether for loop will cause a problem in iterating for 288328 > > times. > > You are heavily underestimating the power of the Python here. > > Stefan Hi, thanks for the help. lxml will suit my work. I have not being working with python for that long. :) Kanch From jgardner at jonathangardner.net Thu Jul 17 16:03:57 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 17 Jul 2008 13:03:57 -0700 (PDT) Subject: x, = y (???) References: Message-ID: <028d7d39-f0b4-49fd-8061-3836d3f0dac4@v21g2000pro.googlegroups.com> On Jul 17, 12:55?pm, kj wrote: > what's the point of performing such "unpacking"? record = [name, address, telephone] ... name, address, telephone = record From tjreedy at udel.edu Thu Jul 3 16:11:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 03 Jul 2008 16:11:21 -0400 Subject: A fix for OverflowError in 64bits platforms In-Reply-To: <486CE046.6080104@gmail.com> References: <486CE046.6080104@gmail.com> Message-ID: Manuel Vazquez Acosta wrote: > Hi all, > > I'm debugging a Plone site in an AMD64 laptop. When I first tried to run > Zope, I got this exception: In general, versions numbers for both Python and the app are helpful. > OverflowError: signed integer is greater than maximum > > In the archives I encounter no solutions. Archives: Python? Zope? Plone? > This is what I could find, so I share with you all: I hope you have/will report this to the appropriate place. > It seems that on 64bit platforms, sys.maxint is much greater than list's > insertion maximum index. I'm not sure if this a bug in python or a This strikes me as an app bug. In any case, released versions of Python will not change. > logical bound ---given the amount of RAM it would take to insert > 9,223,372,036,854,775,807 items ;)--- Maybe a bug in the documentation, > though > > However, Archetypes.Schema.moveField method documents the use of maxint > for inserting at the end of the Schema:: > maxint can be used to move the field to the last position possible This is a bit flakey. If they are going to use a surrogate for len(schemalist)-1, they might as well accept anything larger and shrink it to the proper value as slicing does. In 2.5.2 >>> a=[1,2,3] >>> a[1:1000000000000000000000] [2, 3] > >>> from sys import maxint > >>> spos = schema.copy() > >>> spos.moveField('a', pos=maxint) > >>> spos.keys() > ['b', 'c', 'a'] > > I have seen this usage in some products. This raises and OverflowError > on 64bit platforms. > > The fix is simple in the code of the caller:: > from sys import maxint > if maxint >> 33: # Am I running on 64bits? > maxint = maxint >> 33 > theschema.moveField(the_name, pos=maxint) > > Now, the maxint variable holds an acceptable value. > > I think the docstring should be appended with a "Note: On 64bits > platform this raises an OverflowError blah blah..." Better to fix it ;-) From timr at probo.com Wed Jul 23 00:38:18 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 23 Jul 2008 04:38:18 GMT Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> Message-ID: castironpi wrote: > >You're saying the VM can't compile code. That makes sense, it's not a >compiler. I wouldn't say "can't". The current CPython VM does not compile code. It COULD. The C#/.NET VM does. IronPython, for example, is an implementation of Python that uses .NET. In that case, the code *IS* JIT compiled to assembly when the program starts. >Do I understand correctly that JIT does compile to native >code in some cases? VMs that use JIT do, yes. >But that's not the only thing that stops python >from precompiling to assembly directly. GNU doesn't come with >Python. Do you mean Linux? >What sorts of minimal information would be necessary to take >from the GNU libs for the user's specific processor, (the one they're >downloading their version of Python for), to move Python to the >further step of outputting the machine code? I don't know why you think GNU has anything to do with this. There's nothing that prevents the Python run-time from JIT compiling the code. IronPython does this. CPython does not. It's an implementation decision. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From maric at aristote.info Tue Jul 29 04:59:01 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 29 Jul 2008 10:59:01 +0200 Subject: multiple inheritance and __getattr__ In-Reply-To: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> References: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> Message-ID: <200807291059.01408.maric@aristote.info> Le Monday 28 July 2008 16:48:09 Enrico, vous avez ?crit?: > Hi there, > I have the following situation (I tryed to minimize the code to concentrate > > on the issue): > >>> class A(object): > > def __getattr__(self, name): > print 'A.__getattr__' > if name == 'a': return 1 > raise AttributeError('%s not found in A' % name) > > >>> class B(object): > > def __getattr__(self, name): > print 'B.__getattr__' > if name == 'b': return 1 > raise AttributeError('%s not found in B' % name) > > Both classes have a __getattr__ method. > > Now I want to have a class that inherits from both so I write: > >>> class C(B,A): > > pass > > The problem arise when I try something like this: > >>> c=C() > >>> c.a > > A.__getattr__ > 1 > > >>> c.b > > A.__getattr__ > > Traceback (most recent call last): > File "", line 1, in > c.b > File "", line 5, in __getattr__ > raise AttributeError('%s not found in A' % name) > AttributeError: b not found in A > > I was expecting, after a fail in A.__getattr__, a call to the __getattr__ > method of B but it seems that after A.__getattr__ fails the exception stops > the flow. So, if I did understand well, B.__getattr__ will be never called > "automatically". I don't know if this has a reason, if it is a design > choice or what else, any explanation is welcome. > No getattr is a lookup fallback, classes which implement them in a non-collaborative way are unlikely to be used for multiple inheritance. Given how multiple inheritance work and __getattr__ semantic, I was surprised it is not that easy to figure out how it could work in a collaborative, and how far fromm this are common implementation of __getattr__. Normally they should be implemented like that : >>>[89]: class A(object) : def __getattr__(self, name) : if name == 'a' : return 'a' try : g = super(A, self).__getattr__ except : raise AttributeError('no more __getattr__') return g(name) ....: ....: >>>[95]: class B(object) : def __getattr__(self, name) : if name == 'b' : return 'b' try : g = super(B, self).__getattr__ except : raise AttributeError('no more __getattr__') return g(name) .....: .....: >>>[101]: class C(A, B) : def __getattr__(self, name) : if name == 'c' : return 'c' try : g = super(C, self).__getattr__ except : raise AttributeError('no more __getattr__') return g(name) .....: .....: >>>[107]: C().a ...[107]: 'a' >>>[108]: C().b ...[108]: 'b' >>>[109]: C().c ...[109]: 'c' >>>[110]: C().k --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /home/maric/ in () /home/maric/ in __getattr__(self, name) /home/maric/ in __getattr__(self, name) /home/maric/ in __getattr__(self, name) AttributeError: no more __getattr__ > Since A and B are not written by me I can only work on C. The solution that > comes to my mind is to define a __getattr__ also in C and write something > > like: > >>> class C(A,B): > > def __getattr__(self, name): > try: > return A.__getattr__(self, name) > except AttributeError: > return B.__getattr__(self, name) > > >>> c=C() > >>> c.a > > A.__getattr__ > 1 > > >>> c.b > > A.__getattr__ > B.__getattr__ > 1 > > A better solution is welcome. There is no way to repair those clases for mulitple inheritance except monkey patching them. The idea of this patch would be : def collaborative_getattr(class_, old_name) : old_one = getattr(class_, old_name) def __getattr__(self, name) : try : return old_one(self, name) except AttributeError : try : g = super(class_, self).__getattr__ except : raise AttributeError('no more __getattr__') return g(name) if not getattr(C, '_C_fixed__', False) : C._C_fixed__ = C.__getattr__ C.__getattr__ = collaborative_getattr(C, '_C_fixed__') That said, if your class C is a real facade for its ancestors A and B (A and B won't appear at all in the hierarchies of your subclasses), your solution is near the best one in terms of simplicity-efficiency. I said near the best one because your __getattr__ isn't collaborative yet ! :). -- _____________ Maric Michaud From geraint.williams at gmail.com Tue Jul 22 20:02:03 2008 From: geraint.williams at gmail.com (GHZ) Date: Tue, 22 Jul 2008 17:02:03 -0700 (PDT) Subject: How do I compare files? References: Message-ID: <1fd4550e-1271-4c44-b14d-fe7de1be73ea@k37g2000hsf.googlegroups.com> On Jul 23, 1:27?am, Clay Hobbs wrote: > I am making a program that (with urllib) that downloads two jpeg files > and, if they are different, displays the new one. ?I need to find a way > to compare two files in Python. ?How is this done? > > -- Ratfink import hashlib file = open(path) m = hashlib.md5() m.update(file.read()) digest = m.hexdigest() file.close() and compare the digest on both files From phillip.oldham at gmail.com Wed Jul 30 10:11:45 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Wed, 30 Jul 2008 07:11:45 -0700 (PDT) Subject: Standard module for parsing emails? References: <6fb93eFap7j5U1@mid.individual.net> Message-ID: On Jul 30, 2:36 pm, Thomas Guettler wrote: > What do you mean with "quote" here? > 2. Prefix of quoted text like your text above in my mail Basically, just be able to parse an email into its actual and "quoted" parts - lines which have been prefixed to indent from a previous email. Most clients use ">" which is easy to check for, but I've seen some which use "|" and some which *don't* quote at all. Its causing us nightmares in parsing responses to system-generated emails. I was hoping someone might've seen the problem previously and released some code. From jsanga at cox.net Wed Jul 9 17:34:59 2008 From: jsanga at cox.net (mzdude) Date: Wed, 9 Jul 2008 14:34:59 -0700 (PDT) Subject: Retrieving BSTR * from a DLL Message-ID: <500e422d-5868-4a2b-a213-7d4d13a51d23@j22g2000hsf.googlegroups.com> I need to interface with a windows DLL that has the following signature extern "C" void Foo( BSTR in, BSTR *out ) Code so far >>> from ctypes import * >>> import comtypes >>> LPBSTR = POINTER(comtypes.BSTR) >>> >>> hdl = windll.MyDll.Foo >>> hdl.rettype = None >>> hdl.argtypes = [comtypes.BSTR, LPBSTR] >>> >>> inStr = comtypes.BSTR(u'Some Silly String') >>> out = comtypes.BSTR >>> >>> hdl(inStr,byref(out)) Traceback (most recent call last): File "", line 1, in hdl(inStr,byref(out)) TypeError: byref() argument must be a ctypes instance, not '_ctypes.SimpleType' Also tried the following >>> out = comtypes.BSTR(u'') >>> p = pointer(out) >>> hdl(inStr,p) Traceback (most recent call last): File "", line 1, in hdl(inStr,p) ValueError: Procedure probably called with too many arguments (8 bytes in excess) Any feedback would be appreciated. From ggpolo at gmail.com Tue Jul 29 06:32:30 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 29 Jul 2008 07:32:30 -0300 Subject: Download excel file from web? In-Reply-To: References: <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> <19fa0bb2-e101-47c9-84d4-1bf05d08ba39@b2g2000prf.googlegroups.com> Message-ID: On Tue, Jul 29, 2008 at 1:47 AM, patf at well.com wrote: > On Jul 28, 6:05 pm, "Guilherme Polo" wrote: >> On Mon, Jul 28, 2008 at 9:39 PM, MRAB wrote: >> > On Jul 29, 12:41 am, "p... at well.com" wrote: >> >> On Jul 28, 4:20 pm, "Guilherme Polo" wrote: >> >> >> > On Mon, Jul 28, 2008 at 8:04 PM, p... at well.com wrote: >> >> > > On Jul 28, 3:52 pm, "Guilherme Polo" wrote: >> >> > >> On Mon, Jul 28, 2008 at 7:43 PM, p... at well.com wrote: >> >> > >> > On Jul 28, 3:33 pm, "p... at well.com" wrote: >> >> > >> >> On Jul 28, 3:29 pm, "Diez B. Roggisch" wrote: >> >> >> > >> >> > p... at well.com schrieb: >> >> >> > >> >> > > On Jul 28, 3:00 pm, "p... at well.com" wrote: >> >> > >> >> > >> Hi - experienced programmer but this is my first Python program. >> >> >> > >> >> > >> This URL will retrieve an excel spreadsheet containing (that day's) >> >> > >> >> > >> msci stock index returns. >> >> >> > >> >> > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... >> >> >> > >> >> > >> Want to write python to download and save the file. >> >> >> > >> >> > >> So far I've arrived at this: >> >> >> > >> >> > >> [quote] >> >> > >> >> > >> # import pdb >> >> > >> >> > >> import urllib2 >> >> > >> >> > >> from win32com.client import Dispatch >> >> >> > >> >> > >> xlApp = Dispatch("Excel.Application") >> >> >> > >> >> > >> # test 1 >> >> > >> >> > >> # xlApp.Workbooks.Add() >> >> > >> >> > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' >> >> > >> >> > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' >> >> > >> >> > >> # xlBook = xlApp.ActiveWorkbook >> >> > >> >> > >> # xlBook.SaveAs(Filename='C:\\test.xls') >> >> >> > >> >> > >> # pdb.set_trace() >> >> > >> >> > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ >> >> > >> >> > >> excel? >> >> > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> >> > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional') >> >> > >> >> > >> # test 2 - returns check = False >> >> > >> >> > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ >> >> > >> >> > >> indexperf/excel? >> >> > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> >> > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() >> >> >> > >> >> > >> xlApp = response.fp >> >> > >> >> > >> print(response.fp.name) >> >> > >> >> > >> print(xlApp.name) >> >> > >> >> > >> xlApp.write >> >> > >> >> > >> xlApp.Close >> >> > >> >> > >> [/quote] >> >> >> > >> >> > > Woops hit Send when I wanted Preview. Looks like the html [quote] tag >> >> > >> >> > > doesn't work from groups.google.com (nice). >> >> >> > >> >> > > Anway, in test 1 above, I determined how to instantiate an excel >> >> > >> >> > > object; put some stuff in it; then save to disk. >> >> >> > >> >> > > So, in theory, I'm retrieving my excel spreadsheet with >> >> >> > >> >> > > response = urllib2.urlopen() >> >> >> > >> >> > > Except what then do I do with this? >> >> >> > >> >> > > Well for one read some of the urllib2 documentation and found the >> >> > >> >> > > Request class with the method has_data() on it. It returns False. >> >> > >> >> > > Hmm that's not encouraging. >> >> >> > >> >> > > I supposed the trick to understand what urllib2.urlopen is returning >> >> > >> >> > > to me; rummage around in there; and hopefully find my excel file. >> >> >> > >> >> > > I use pdb to debug. This is interesting: >> >> >> > >> >> > > (Pdb) dir(response) >> >> > >> >> > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', >> >> > >> >> > > 'code', ' >> >> > >> >> > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', >> >> > >> >> > > 'readline', ' >> >> > >> >> > > readlines', 'url'] >> >> > >> >> > > (Pdb) >> >> >> > >> >> > > I suppose the members with __*_ are methods; and the names without the >> >> > >> >> > > underbars are attributes (variables) (?). >> >> >> > >> >> > No, these are the names of all attributes and methods. read is a method, >> >> > >> >> > for example. >> >> >> > >> >> right - I got it backwards. >> >> >> > >> >> > > Or maybe this isn't at all the right direction to take (maybe there >> >> > >> >> > > are much better modules to do this stuff). Would be happy to learn if >> >> > >> >> > > that's the case (and if that gets the job done for me). >> >> >> > >> >> > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty >> >> > >> >> > clear on this: >> >> >> > >> >> > """ >> >> > >> >> > This function returns a file-like object with two additional methods: >> >> > >> >> > """ >> >> >> > >> >> > And then for file-like objects: >> >> >> > >> >> >http://docs.python.org/lib/bltin-file-objects.html >> >> >> > >> >> > """ >> >> > >> >> > read( [size]) >> >> > >> >> > Read at most size bytes from the file (less if the read hits EOF >> >> > >> >> > before obtaining size bytes). If the size argument is negative or >> >> > >> >> > omitted, read all data until EOF is reached. The bytes are returned as a >> >> > >> >> > string object. An empty string is returned when EOF is encountered >> >> > >> >> > immediately. (For certain files, like ttys, it makes sense to continue >> >> > >> >> > reading after an EOF is hit.) Note that this method may call the >> >> > >> >> > underlying C function fread() more than once in an effort to acquire as >> >> > >> >> > close to size bytes as possible. Also note that when in non-blocking >> >> > >> >> > mode, less data than what was requested may be returned, even if no size >> >> > >> >> > parameter was given. >> >> > >> >> > """ >> >> >> > >> >> > Diez >> >> >> > >> >> Just stumbled upon .read: >> >> >> > >> >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ >> >> > >> >> excel? >> >> > >> >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> >> > >> >> +25%2C+2008&export=Excel_IEIPerfRegional').read >> >> >> > >> >> Now the question is: what to do with this? I'll look at the >> >> > >> >> documentation that you point to. >> >> >> > >> >> thanx - pat >> >> >> > >> > Or rather (next iteration): >> >> >> > >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ >> >> > >> > excel? >> >> > >> > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> >> > >> > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) >> >> >> > >> > The file is generally something like 26 KB so specifying 1,000,000 >> >> > >> > seems like a good idea (first approximation). >> >> >> > >> > And then when I do: >> >> >> > >> > print(response) >> >> >> > >> > I get a whole lot of garbage (and some non-garbage), so I know I'm >> >> > >> > onto something. >> >> >> > >> > When I read the .read documentation further, it says that read() has >> >> > >> > returned the data as a string object. Now - how do I convince Python >> >> > >> > that the string object is in fact an excel file - and save it to disk? >> >> >> > >> You don't need to convince Python, just write it to a file. >> >> > >> More reading for you:http://docs.python.org/tut/node9.html >> >> >> > >> > pat >> >> > >> > -- >> >> > >> >http://mail.python.org/mailman/listinfo/python-list >> >> >> > >> -- >> >> > >> -- Guilherme H. Polo Goncalves >> >> >> > > OK: >> >> >> > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ >> >> > > excel? >> >> > > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> >> > > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) >> >> > > # print(response) >> >> > > f = open("c:\\msci.xls",'w') >> >> > > f.write(response) >> >> >> > I would initially change that to: >> >> >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&...) >> >> >> > f = open("c:\\msci.xls", "wb") >> >> > for line in response: >> >> > f.write(line) >> >> > f.close() >> >> >> > and then.. >> >> >> > > OK this makes the file, and there's a c:\msci.xls in place and it's >> >> > > about the right size. But whether I make the second param to open 'w' >> >> > > or 'wb', when I try to open msci.xls from the Windows file explorer, >> >> > > excel tells me that the file is corrupted. >> >> >> > try it. >> >> >> > > pat >> >> > > -- >> >> > >http://mail.python.org/mailman/listinfo/python-list >> >> >> > -- >> >> > -- Guilherme H. Polo Goncalves >> >> >> A simple f.write(response) does work (click on a single row in Excel >> >> and you get a single row). >> >> >> But I can see that what you recommend Guilherme is probably safer - >> >> thanx. >> >> >> pat >> >> > If response contains a string then: >> >> Did you notice I removed the read(...) part ? >> >> > for line in response: >> > f.write(line) >> >> > will actually be writing the string one character at a time! >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> -- >> -- Guilherme H. Polo Goncalves > > Actually no I didn't Guilherme (although I'll take it out now). > > Would leaving the in urllib2.urlopen().read() imply, as MRAB would > seem to indicate, that the following for loop would act byte-by-byte? > And if so, how? .read() returns a string, so yes. The point in removing the .read(xxxxx) is that you no longer need to guess how long is the file to read it entirely. > > Even with the .read() in, it was very fast. But it looks like it > won't hurt (and very possibly helps) to take it out. > > pat > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From arsyed at gmail.com Mon Jul 21 14:16:26 2008 From: arsyed at gmail.com (arsyed) Date: Mon, 21 Jul 2008 14:16:26 -0400 Subject: calling source command within python In-Reply-To: References: Message-ID: <9a2cc7a70807211116o4b1cb766k3833d1bf4958bdfc@mail.gmail.com> On Mon, Jul 21, 2008 at 1:59 PM, mk wrote: > Jie wrote: > >> Hi all, >> >> i'm having trouble executing os.system('source .bashrc') command >> within python, it always says that source not found and stuff. Any >> clue? >> > > It _might_ be that the shell it fires up is /bin/sh and this in turn is not > bash. > > Anyway, it's better to use subprocess / Popen for this sort of operation. > > > "source" is a bash built-in command and not an executable file. That's why you need to do something like execute "/bin/bash .bashrc". -------------- next part -------------- An HTML attachment was scrubbed... URL: From jordanrastrick at gmail.com Thu Jul 24 06:12:41 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 03:12:41 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> Message-ID: <40449826-c71d-4c6e-8b74-13069269e5da@z6g2000pre.googlegroups.com> OK, it seems my original reply to Bruno got lost in the Aether (apologies therefore if a paraphrased "quantum duplicate" of this message is eventually forthcoming.) Torsten has adequately responded to his second point, so I need only replicated what I said for the first. > Please get your facts, the behaviour *is* actually fully documented: I have the facts. I know full well the behaviour is documented - it was pointed out at the time of the original discussion. Documenting a confusing, unintuitive design decision (whether its in a programming language, an end user GUI app or anything in between) doesn't justify it. To attack a strawman: "foolanguage uses the bar IO library; printing to stdout takes about 10 mins on the average machine. But thats ok, because look, its documented right here." > FWIW, the __lt__ / __le__ / __eq__ / __ne__ / __gt__ / __ge__ methods > set, known as "rich comparisons", was added in Python 2.1 to give more > fine-grained control on comparisons. If you don't need such a > granularity, just implement the __cmp__ method and you'll have all > comparison operators working as expected. First, the most serious justification for rich comparisons I remember seeing was that scipy "needed" them. I never saw a good reason scipy couldnt use methods like the rest of us mortals, nor why it was justifiable introducing a wart into the entire language for the sake of mildly conveniencing an (admittedly important and widely used) library. Second, fine, have silly C++-operator-overloading-style rich comparisons that confuse people reading your code if you must. Why does it have to be the default behaviour? Its people wanting __ne__ do do something other than not __eq__ who should have to be explicit about it. Third, __cmp__ is no good as a fix. Most classes that wan't equality comparison (== and !=) don't want ordered based comparison (>= etc.) thrown in as well. I shouldn't implement __cmp__ unless I want my class to implement every order comparison operator. Fourth, I'm trying to examine the wider implications of the Explicit > Implict mantra here, not resurrect an old campaign to change != behaviour that I think is probably a lost cause (if it happens as a side effect though, that'd be kinda cool.) From socyl at 987jk.com.invalid Tue Jul 29 13:24:15 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 17:24:15 +0000 (UTC) Subject: DB access without object-relation mapping? References: Message-ID: In Tim Henderson writes: >I believe there are a couple of options but pyscopg, and PyGreSQL seem >to be popular. Great. Thanks! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From Scott.Daniels at Acm.Org Tue Jul 29 09:03:10 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 29 Jul 2008 06:03:10 -0700 Subject: Swap memory in Python ? - three questions In-Reply-To: References: Message-ID: Robert LaMarca wrote: > Hi, > > I am using numpy and wish to create very large arrays. My system is AMD 64 x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a 15 GB swap drive. > > The command I have been trying to use is; > g=numpy.ones([1000,1000,1000],numpy.int32) > > This returns a memory error. > A smaller array ([500,500,500]) worked fine.. > Two smaller arrays again crashed the system. > > So... I did the math. a 1000x1000x1000 array at 32 bits should be around 4gb RAM... Obviously larger than RAM, but much smaller than the swap drive. > > 1. So... does Numpy have a really lot of overhead? Or is my system just not somehow getting to make use of the 15gb swap area. > 2. Is there a way I can access the swap area, or direct numpy to do so? Or do I have to write out my own numpy cache system... > 3. How difficult is it to use data compression internally on numpy arrays? > > thanks very much > Robert There are architectural issues that you should not expect (and really do not want) the libraries / languages / os to handle for you automatically. The reason you don't even _want_ an automatic solution is that the computer has no understanding of the problem you are trying to solve. If the machine guesses wrong, it will be doing computations at I/O speeds, and for 4G of data, that will result in geological computing times. On big problems the programming issue is how to break the problem into tractable sub-problems (of feasible computing size), and how to stitch those results together. This is a place to apply human intellect, not machine effort. So, sorry, there is no way to solve the problem without understanding the field it occurs in and the question being addressed by the code. --Scott David Daniels Scott.Daniels at Acm.Org From gandalf at shopzeus.com Tue Jul 1 14:47:17 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 01 Jul 2008 20:47:17 +0200 Subject: convert unicode characters to visibly similar ascii characters In-Reply-To: References: Message-ID: <486A7BB5.3000501@shopzeus.com> Peter Bulychev wrote: > Hello. > > I want to convert unicode character into ascii one. > The method ".encode('ASCII') " can convert only those unicode > characters, which fit into 0..128 range. > > But there are still lots of characters beyond this range, which can be > manually converted to some visibly similar ascii characters. For > instance, there are several quotation marks in unicode, which can be > converted into ascii quotation mark. Please be more specific. There is no general solution. Unicode can handle latin, cyrilic (russian), chinese, japanese and arabic characters in the same string. There are thousands of possible non-ascii characters and many of them are not similar to any ascii character. If you only want this to work for a subset, please define that subset. Laszlo From pavlovevidence at gmail.com Sat Jul 5 04:21:41 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 5 Jul 2008 01:21:41 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: On Jul 5, 4:12 am, "Sebastian \"lunar\" Wiesner" wrote: > Paddy : > > > > > On Jul 4, 1:36 pm, Peter Otten <__pete... at web.de> wrote: > >> Henning_Thornblad wrote: > >> > What can be the cause of the large difference between re.search and > >> > grep? > > >> grep uses a smarter algorithm ;) > > >> > This script takes about 5 min to run on my computer: > >> > #!/usr/bin/env python > >> > import re > > >> > row="" > >> > for a in range(156000): > >> > row+="a" > >> > print re.search('[^ "=]*/',row) > > >> > While doing a simple grep: > >> > grep '[^ "=]*/' input (input contains 156.000 a in > >> > one row) > >> > doesn't even take a second. > > >> > Is this a bug in python? > > >> You could call this a performance bug, but it's not common enough in real > >> code to get the necessary brain cycles from the core developers. > >> So you can either write a patch yourself or use a workaround. > > >> re.search('[^ "=]*/', row) if "/" in row else None > > >> might be good enough. > > >> Peter > > > It is not a smarter algorithm that is used in grep. Python RE's have > > more capabilities than grep RE's which need a slower, more complex > > algorithm. > > FWIW, grep itself can confirm this statement. The following command roughly > takes as long as Python's re.search: > > # grep -P '[^ "=]*/' input > > -P tells grep to use real perl-compatible regular expressions. This confirms that a particular engine might not be optimized for it, but it's not necessarily a reflection that the engine is more complex. I'm not sure of the specifics and maybe that is the case, but it could also be a case of a different codebase which is optimized differently. Carl Banks From bignose+hates-spam at benfinney.id.au Wed Jul 16 19:30:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 17 Jul 2008 09:30:38 +1000 Subject: python doc in command line References: <2dae4588-7321-493b-8c9f-c4df1e44a02a@27g2000hsf.googlegroups.com> Message-ID: <87iqv5z9sx.fsf@benfinney.id.au> Peng Yu writes: > Perl has a command line help perldoc. I'm wondering if python has a > similar help command. The interactive interpreter has a "help" command, and a corresponding "help" function which can be passed an object to display its docstrings recursively and nicely-formatted. The same facility is available with the external 'pydoc' command. -- \ ?The right to search for truth implies also a duty; one must | `\ not conceal any part of what one has recognized to be true.? | _o__) ?Albert Einstein | Ben Finney From mccredie at gmail.com Mon Jul 14 11:36:57 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 14 Jul 2008 08:36:57 -0700 (PDT) Subject: screencapture with PIL question References: <8e9ca866-4f14-4dd6-a784-a76630d8d812@x35g2000hsb.googlegroups.com> Message-ID: <3176a1a8-0c38-43f9-a3c1-748eb2dbdfef@8g2000hse.googlegroups.com> On Jul 14, 8:11?am, greg wrote: > Is there any way to capture the entire window? ?specifically > the scrolled portion of a window that is _not_visible_on_the_screen_. I don't think there is. That is why it is called a _screen_ capture. Matt From jaganadhg at gmail.com Wed Jul 23 10:51:17 2008 From: jaganadhg at gmail.com (=?UTF-8?B?4LSc4LSX4LSo4LWN4LSo4LS+4LSl4LWN?=) Date: Wed, 23 Jul 2008 07:51:17 -0700 (PDT) Subject: Doubt Message-ID: Friends I am a Perl programmer new to Python. I have a small doubt. How to convert the perl notation $a = ""; expression in Python ? How to represent the loop for ($a = $b; $a<=$c;$a++){ } in Python Jagan Linguist From ethan at stoneleaf.us Mon Jul 14 23:05:39 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 14 Jul 2008 19:05:39 -0800 Subject: Determining when a file has finished copying In-Reply-To: <2.2.32.20080714163026.01217970@pop.xs4all.nl> References: <2.2.32.20080714163026.01217970@pop.xs4all.nl> Message-ID: <487C1403.8040107@stoneleaf.us> Michiel Overtoom wrote: > Ethan wrote: > >> One more option may be to attempt to rename >> the file -- if it's still open for copying, that will fail; >> success indicates the copy is done. > > Caveat -- this is dependent on the operating system! > > Windows will indeed not allow you to rename or delete a file that's still > open for writing by another process, at least not when the file is on a > local NTFS filesystem, but don't count on this on Unix or networked > filesystems. There you can easily rename, move or delete a filename from a > directory whilst other processes still write to it. After all, a directory > is nothing else than a list of filenames which map to certain inodes. Very good point. Thanks. ~Ethan From the.blue.valkyrie at gmail.com Wed Jul 16 06:39:53 2008 From: the.blue.valkyrie at gmail.com (=?ISO-8859-1?Q?Cristina_Yenyxe_Gonz=E1lez_Garc=EDa?=) Date: Wed, 16 Jul 2008 12:39:53 +0200 Subject: How can i use a variable without define it ? In-Reply-To: <5dd91053-d239-4ff1-b693-d6afedf6bf24@x35g2000hsb.googlegroups.com> References: <87k5fm2p1x.fsf@benfinney.id.au> <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> <87fxqa2mu0.fsf@benfinney.id.au> <5dd91053-d239-4ff1-b693-d6afedf6bf24@x35g2000hsb.googlegroups.com> Message-ID: Hello. 2008/7/16 zhw : > On 7?16?, ??5?35?, Ben Finney > wrote: >> zhw writes: >> > Here is a example that I want to complete: >> > >>> import sys, new >> > >>> context={"name":"david", "sex":"male"} >> >> Here you have a set of values addressible by name. >> >> > >>> sys.modules["foo"] = new.module("foo") >> >> Why do you believe you need to create a module object? >> >> > >>> import foo >> > >>> for attr in context: >> > setattr(foo, attr, context[attr]) >> Forgetting these considerations (I agree with Ben, though), your error is trying to use an 'import *' inside a function. You should take it outside the function, and try to run it again. >> >> > >>> def bar(): >> > # here is a error >> > # import * only allowed at module level >> > from foo import * >> > print name, sex >> There are different import statements you can use in Python. I recommend you to take a look at the tutorial to learn about the differences between them: http://docs.python.org/tut/node8.html Good luck. From Caseyweb at gmail.com Mon Jul 14 12:18:35 2008 From: Caseyweb at gmail.com (Casey) Date: Mon, 14 Jul 2008 09:18:35 -0700 (PDT) Subject: screencapture with PIL question References: <8e9ca866-4f14-4dd6-a784-a76630d8d812@x35g2000hsb.googlegroups.com> Message-ID: On Jul 14, 11:11?am, greg wrote: > I am able to use the PIL module to capture a screen or specific > window. ?My problem is when capturing a window (on windows XP) I can > only capture the "visible" portion of the window. ?Is there any way to > capture the entire window? ?specifically the scrolled portion of a > window that is not visible on the screen. > > Thanks for any help. You might want to check out http://wiki.wxpython.org/index.cgi/WorkingWithImages#head-e962ac20ad55c25bc069523cd7e0246068110233 . wxPython supports different types of device contexts including wx.ClientDC (the client area of a window), wx.WindowDC (a specific window), and wx.ScreenDC (anywhere or everywhere on the underlying screen). From larry.bates at websafe.com` Mon Jul 21 12:49:02 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 11:49:02 -0500 Subject: Run as Service In-Reply-To: <09c0bfa9-c86b-4153-ba91-cb9bf2e85e2a@k30g2000hse.googlegroups.com> References: <09c0bfa9-c86b-4153-ba91-cb9bf2e85e2a@k30g2000hse.googlegroups.com> Message-ID: misceverything at gmail.com wrote: > I have, in the past, used SRVANY to run a Python app as a Windows > service. However, now I am interested in distributing my scripts and > want to make it as painless for the end user as possible (hands-off is > best :). How can you go about running a Python app as a Windows > service without SRVANY? Pick up a copy of Mark Hammond's book "Python on Win32". It has an excellent chapter on using Win32 extensions to write Windows Services. Also you might consider looking at gmane.comp.python.windows usergroup. -Larry From fredrik at pythonware.com Wed Jul 16 05:28:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 11:28:58 +0200 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: <8AEDA5E3386EA742B8C24C95FF0C758004623111@PDC-MAIL3.ubisoft.org> References: <8AEDA5E3386EA742B8C24C95FF0C758004623111@PDC-MAIL3.ubisoft.org> Message-ID: Andreas Tawn wrote: > I never knew that and I can't find reference to it in the docs. the for-in loop does ordinary assignments in the current scope: http://docs.python.org/ref/for.html "Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed." somewhat simplified, "for vars in expression: code" is equivalent to inlining: _ = iter(expression) while 1: try: vars = _.next() except StopIteration: break else: body where "_" is an internal variable. From dickinsm at gmail.com Fri Jul 18 18:32:53 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 18 Jul 2008 15:32:53 -0700 (PDT) Subject: round function error??? References: Message-ID: <56957ba6-380e-4398-a974-07d76659eae7@34g2000hsf.googlegroups.com> On Jul 18, 11:15?pm, Terry Reedy wrote: > No, round() return binary floats that, in general, cannot represent > decimal floats exactly. ?Formatted printing gives what you expect. > ?>>> '%8.2f' % x > ' 3499.35' Sure. But it's still true that the second printed value (printed as 3499.3499999999999) is strictly less than 3499.35, so when rounding to 1 decimal place an ideal rounding routine would round it *down* to 3499.3 instead of up to 3499.4. This is what '%.1f' does, for example, on a platform where printf does correct rounding: Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = 3499.35 >>> x 3499.3499999999999 >>> print '%.1f' % x 3499.3 >>> print round(x, 1) 3499.4 Mark From rbossy at jouy.inra.fr Sat Jul 12 05:07:23 2008 From: rbossy at jouy.inra.fr (rbossy at jouy.inra.fr) Date: Sat, 12 Jul 2008 11:07:23 +0200 Subject: decorator to prevent adding attributes to class? Message-ID: <1215853643.4878744b60059@www.jouy.inra.fr> >> class Foo(Freezeable): >> def __init__(self): >> self.bar = 42 >> self.freeze() # ok, we set all variables, no more from here >> >> >> x = Foo() >> print x.bar >> x.bar = -42 >> print x.bar >> x.baz = "OMG! A typo!" >> > >Pretty nice, but unfortunately the subclass has to remember to call freeze >in it's init. Too bad that can't be automated. Not to mention that subclasses constructors could be bit, like that: class Foo(Freezeable): ... class Bar(Foo): def __init__(self, *args, **kw): Foo.__init__(self, *args, **kw) self.something_bar = 42 # this should raise AttributeError Cheers RB From code at pizzashack.org Mon Jul 14 20:39:20 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 14 Jul 2008 20:39:20 -0400 Subject: Using Python To Launch Python In-Reply-To: <23116d500807141440u402eed7du5e41d72bb0716c58@mail.gmail.com> References: <20080714212454.GE16010@dragontoe.org> <23116d500807141440u402eed7du5e41d72bb0716c58@mail.gmail.com> Message-ID: <20080715003920.GF16010@dragontoe.org> On Mon, Jul 14, 2008 at 05:40:43PM -0400, Aquil H. Abdullah wrote: > You've hit the proverbial nail with the hammer. The problem is that my > application needs to run under both the Linux and Windows OSs, so while I > would love to use a nice sh, csh, or bash shell script. My hands are tied > because Windows does not provide such wonderful shells. *Provides*, no... neither does it provide Python, for what that's worth. But you can certainly get it (bash): http://win-bash.sourceforge.net/ I suppose it's not worth installing just for this purpose though... But you can provide with your application a DoS batch file that does exactly the same thing (in addition to a shell script). The user would quite intuitively use whichever were appropriate, or follow your provided directions otherwise. Or, the equivalent in (hopefully OS-agnostic) Python: import os, sys # I believe this gets the name of the root in all major OSes def root_dir(path): if os.path.dirname(path) == path: return path return (root_dir(os.path.dirname(path))) appname = root = root_dir(os.getcwd()) install_path = os.path.join(root, "usr") bin_path = os.path.join(install_path, "bin") os.environ["PATH"] = bin_path + os.pathsep + os.environ["PATH"] python_path = os.path.join(bin_path, "python") args = sys.argv[1:] args.insert(0, os.path.join(bin_path, appname)) args.insert(0, python_path) args.insert(0, python_path) os.execv(python_path, args) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From timothywayne.cook at gmail.com Tue Jul 29 14:22:46 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Tue, 29 Jul 2008 15:22:46 -0300 Subject: Correct Attribute Assignment Methodology? Message-ID: <1217355766.2930.10.camel@localhost.localdomain> Say I have these classes: class Parent(object): """Parent is abstract""" a=None def showA(): return self.a class Child(Parent): """inherits a and showA from Parent""" def __init__(self,a,b): self.a=a self.b=b def showAB(): return self.a,self.b class GrandChild(Child): """inherits all of the above""" def __init__(self,a,b,c): self.a=a self.b=b """should this be Child.__init__(a,b)? or Child.__init__(b)?"" """if so; why? if not why not?""" self.c=c Thanks for answering these very basic questions but I am not certain about the correct way. I know that in Python, assignment in the GrandChild class will work but is that correct? --Tim -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. Home page: https://launchpad.net/oship/ Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 05:26:40 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 11:26:40 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <48884afe$0$10430$426a74cc@news.free.fr> Jordan a ?crit : (snip rant about self and __eq__ / __ne__) 1/ about the __eq__ / __ne__ stuff: Please get your facts, the behaviour *is* actually fully documented: """ There are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false. Accordingly, when defining __eq__(), one should also define __ne__() so that the operators will behave as expected. """ http://docs.python.org/ref/customization.html FWIW, the __lt__ / __le__ / __eq__ / __ne__ / __gt__ / __ge__ methods set, known as "rich comparisons", was added in Python 2.1 to give more fine-grained control on comparisons. If you don't need such a granularity, just implement the __cmp__ method and you'll have all comparison operators working as expected. 2/ wrt/ self in functions signatures: How would you handle this case with an implicit 'self' : class Foo(object): pass def bar(self): print self Foo.bar = bar From bignose+hates-spam at benfinney.id.au Tue Jul 15 23:11:32 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jul 2008 13:11:32 +1000 Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> <7xiqv68rrp.fsf@ruckus.brouhaha.com> Message-ID: <87vdz64j6j.fsf@benfinney.id.au> Paul Rubin writes: > I don't like square-bracket listcomps because they leak the index > variables to the outside. According to PEP 289 , this is an acknowledged wart that will be fixed in Python 3.0. -- \ ?None can love freedom heartily, but good men; the rest love | `\ not freedom, but license.? ?John Milton | _o__) | Ben Finney From rjagodic at gmail.com Thu Jul 17 15:32:00 2008 From: rjagodic at gmail.com (Ratko) Date: Thu, 17 Jul 2008 12:32:00 -0700 (PDT) Subject: properly delete item during "for item in..." References: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> <487F770D.8070405@islandtraining.com> Message-ID: <7436c7ba-a548-453a-8166-304bd2b2f7ef@k36g2000pri.googlegroups.com> > > For dictionaries we can just iterate over values() or items() as > > opposed to itervalues() or iteritems() since that's technically a copy > > of values or items in the dict, right? > > No! In fact the whole point of iteritems and itervalues and iterkeys is > that they *DO NOT* make copies, so changing the dictionary out from > under them is a programming error. > > If you use dict.items(), dict.keys() or dict.values(), then you're OK, > because these methods *do* create new lists for both. That's what I meant, it just didn't come across correctly I guess. Thanks for clarifying these issues. I think I have a better understanding now. R From timr at probo.com Sun Jul 27 00:14:15 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 27 Jul 2008 04:14:15 GMT Subject: Questions on 64 bit versions of Python References: Message-ID: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> python at bdurham.com wrote: > >For Win64-Itanium users: python-2.5.2.ia64.msi >For Win64-AMD64 users: python-2.5.2.amd64.msi > >1. It looks like the 64 bit versions of Python for Windows are CPU >vendor specific, eg. it doesn't look like there's a single, universal >executable for Windows 64 bit platforms. Is this true? It's true for ALL operating systems, not just Windows. The ia64 (Itanium) and the amd64 are completely separate processors with VERY different instruction sets. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 3 03:13:45 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 03 Jul 2008 09:13:45 +0200 Subject: Generating list of possible configurations In-Reply-To: References: Message-ID: <486c7c1f$0$10446$426a74cc@news.free.fr> Terry Reedy a ?crit : > > > Mensanator wrote: (snip) >> Lookup "Cartesian Product". (snip) >> for a in [True,False]: >> for b in [True,False]: >> for c in [1,2,3,4]: >> print 'combined settings:',a,'\t',b,'\t',c > > This has been added to itertools at least for 2.6/3.0 Great ! From adityashukla1983 at gmail.com Thu Jul 24 19:38:33 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Thu, 24 Jul 2008 18:38:33 -0500 Subject: File operations. Message-ID: <73045cca0807241638v55c8a5fem63bd716cf93017eb@mail.gmail.com> Guys i just understood the problem.Thanks for all your help Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajdamico at gmail.com Fri Jul 18 17:17:34 2008 From: ajdamico at gmail.com (Anthony) Date: Fri, 18 Jul 2008 14:17:34 -0700 (PDT) Subject: round function error??? Message-ID: Isn't this a mistake??? >>> round(3499.349439034,44) 3499.3494390340002 >>> round(_,2) 3499.3499999999999 >>> round(_,1) 3499.4000000000001 My Python 2.5.1 spat that out.. From jonas.haulin at gmail.com Thu Jul 24 21:54:11 2008 From: jonas.haulin at gmail.com (jrh) Date: Thu, 24 Jul 2008 18:54:11 -0700 (PDT) Subject: import dll instead of pyd Message-ID: <68310600-2efd-4f52-81d7-d0f3b40c7809@h17g2000prg.googlegroups.com> Hello, >From previous posts and documentation it seems python should be able to import a module that is compiled into a .dll just as well as a .pyd. I have a pyd that works fine, but after renaming it to dll the import fails. Running python with -vv flag indicates it doesn't actually look for the dll (see below). Has dll import been defeatured in python? Thanks! >>> import _mydllpythonmodule # trying _mydllpythonmodule.pyd # trying _mydllpythonmodule.py # trying _mydllpythonmodule.pyw # trying _mydllpythonmodule.pyc # trying C:\Python25\DLLs\_mydllpythonmodule.pyd # trying C:\Python25\DLLs\_mydllpythonmodule.py # trying C:\Python25\DLLs\_mydllpythonmodule.pyw # trying C:\Python25\DLLs\_mydllpythonmodule.pyc # trying C:\Python25\lib\_mydllpythonmodule.pyd # trying C:\Python25\lib\_mydllpythonmodule.py # trying C:\Python25\lib\_mydllpythonmodule.pyw # trying C:\Python25\lib\_mydllpythonmodule.pyc # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyd # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.py # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyw # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyc # trying C:\Python25\_mydllpythonmodule.pyd # trying C:\Python25\_mydllpythonmodule.py # trying C:\Python25\_mydllpythonmodule.pyw # trying C:\Python25\_mydllpythonmodule.pyc # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyd # trying C:\Python25\lib\site-packages\_mydllpythonmodule.py # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyw # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyc # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyd # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.py # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyw # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyc # trying C:\Python25\lib\site-packages\win32\lib \_mydllpythonmodule.pyd # trying C:\Python25\lib\site-packages\win32\lib\_mydllpythonmodule.py # trying C:\Python25\lib\site-packages\win32\lib \_mydllpythonmodule.pyw # trying C:\Python25\lib\site-packages\win32\lib \_mydllpythonmodule.pyc # trying C:\Python25\lib\site-packages\Pythonwin \_mydllpythonmodule.pyd # trying C:\Python25\lib\site-packages\Pythonwin\_mydllpythonmodule.py # trying C:\Python25\lib\site-packages\Pythonwin \_mydllpythonmodule.pyw # trying C:\Python25\lib\site-packages\Pythonwin \_mydllpythonmodule.pyc Traceback (most recent call last): File "", line 1, in ImportError: No module named _mydllpythonmodule >>> From pavlovevidence at gmail.com Tue Jul 29 13:47:01 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 10:47:01 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> On Jul 29, 1:30 pm, Carl Banks wrote: > On Jul 29, 5:15 am, Heiko Wundram wrote: > > > I can't dig up a simple example from code I wrote quickly, but because of the > > fact that explicit comparisons always hamper polymorphism > > I'm not going to take your word for it. Do you have code that > demonstrates how "if x" improves polymorphism relative to simple > explicit tests? And, in case it wasn't obvious, the way to demonstrate that "if x" improves polymorphism relative to simple explicit tests would be posting an example where "if x" works but a simple explicit test doesn't. So don't accuse me of changing the question on you: it's the same question. You see, what you are stating and expecting me to take for granted is exactly what I'm asking for a concrete example of. Carl Banks From grante at visi.com Tue Jul 22 08:51:48 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 22 Jul 2008 07:51:48 -0500 Subject: Python Written in C? References: Message-ID: On 2008-07-22, Larry Bates wrote: > Grant Edwards wrote: >> On 2008-07-22, Larry Bates wrote: >> >>> You talk about "writing it in assembly language for each MPU >>> chip". Actually it is even better than that. We now have >>> these modern inventions, called compilers that do that type of >>> work for us. They translate high level instructions, not >>> into assembler but into machine language. >> >> Actually, all of the compilers I'm familiar with (gcc and a >> handful of cross compilers for various microprocessors) >> translate from high-level languages (e.g. C, C++) into >> assembly, which is then assembled into relocatable object >> files, which are then linked/loaded to produce machine >> language. >> > I just learned something I did not know. I was under the > impression that they translated directly to machine code > without ever actually generating Assembler text files. There may indeed be compilers that work that way. On Unix systems (which is what I work with) compilers have traditionally generated assembly language files. > Seems like a waste to generate the text and turn around run > that through the assembler, but what do I know. I guess that > way the compiler can have pluggable assembler back-ends. Since you probably need an assembler anyway, generating assembly-language in the compiler prevents you from having to duplicate a bunch of object-code-generation code in two places. -- Grant Edwards grante Yow! Okay ... I'm going at home to write the "I HATE visi.com RUBIK's CUBE HANDBOOK FOR DEAD CAT LOVERS" ... From max at alcyone.com Wed Jul 30 03:56:57 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Jul 2008 00:56:57 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <29a131a5-d813-407a-b774-6f90b7f8f3e3@w1g2000prk.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> <29a131a5-d813-407a-b774-6f90b7f8f3e3@w1g2000prk.googlegroups.com> Message-ID: Carl Banks wrote: > I mean in general. I wouldn't spell it like that. I would prefer if > empty(x), with an __empty__ method. (And support __nonzero__ aka > __bool__ dropped completely.) So your argument is purely about style, then. You just wish it were written differently. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The actor is not quite a human being -- but then, who is? -- George Sanders From ptmcg at austin.rr.com Sun Jul 27 22:51:46 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 27 Jul 2008 19:51:46 -0700 (PDT) Subject: Where is the correct round() method? References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> Message-ID: On Jul 27, 8:55?pm, Larry Bates wrote: > josh logan wrote: > > Hello, > > > I need a round function that _always_ rounds to the higher integer if > > the argument is equidistant between two integers. In Python 3.0, this > > is not the advertised behavior of the built-in function round() as > > seen below: > > >>>> round(0.5) > > 0 > >>>> round(1.5) > > 2 > >>>> round(2.5) > > 2 > > > I would think this is a common need, but I cannot find a function in > > the Python library to do it. I wrote my own, but did I miss such a > > method in my search of the Python library? > > > Thanks > > I think what you want is something like: > > math.ceil(x-0.4999999999999) > > -Larry- Hide quoted text - > > - Show quoted text - The version I learned back in my FORTRAN days was: int(x + 0.5) -- Paul From miki.tebeka at gmail.com Sun Jul 13 15:46:50 2008 From: miki.tebeka at gmail.com (Miki) Date: Sun, 13 Jul 2008 12:46:50 -0700 (PDT) Subject: Generating Lip-Synched animation? Message-ID: Hello, I'm trying to write something like http://blabberize.com/, generating a video file with lip-sync. Currently the general idea is: * Generate animation images using GIMP * Sample voice and detect when there is sound and when there is silence - Still working on details for this one, will probably using audioop and wave modules * Generate a list of images according to the voice (using the bitrate for sync) * Generate video from images using mencoder Before I venture into this, does anybody has a better idea? Thanks, -- Miki http://pythonwise.blogspot.com From __peter__ at web.de Fri Jul 18 06:17:09 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 12:17:09 +0200 Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> Message-ID: SUBHABRATA wrote: > Thanx Peter, > I would change my variables next time I would post. No, you should use meaningful variable names when you write your code no matter whether you plan to post it or not. > And obviously, > thanx for your solution. I am reviewing it, I was also trying out some > solutions. You misunderstood. I did not modify your code other than changing the variable names. My hope was that with this modification any errors sprang to you eye... Peter From fredrik at pythonware.com Wed Jul 16 19:22:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 01:22:53 +0200 Subject: python doc in command line In-Reply-To: <2dae4588-7321-493b-8c9f-c4df1e44a02a@27g2000hsf.googlegroups.com> References: <2dae4588-7321-493b-8c9f-c4df1e44a02a@27g2000hsf.googlegroups.com> Message-ID: Peng Yu wrote: > Perl has a command line help perldoc. I'm wondering if python has a > similar help command. it's built into the interpreter, and Python tells you how to use it when you start Python in interactive mode. $ python Python 2.5.1 Type "help", "copyright", "credits" or "license" for more information. >>> help Type help() for interactive help, or help(object) for help about object. >>> help() Welcome to Python 2.5! This is the online help utility. If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://www.python.org/doc/tut/. Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit". To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam". help> quit You are now leaving help and returning to the Python interpreter. If you want to ask for help on a particular object directly from the interpreter, you can type "help(object)". Executing "help('string')" has the same effect as typing a particular string at the help> prompt. >>> help("string") Help on module string: NAME string - A collection of string operations (most are no longer used). FILE string.py ... >>> help(len) Help on built-in function len in module __builtin__: len(...) len(object) -> integer Return the number of items of a sequence or mapping. >>> (etc) From jeffober at gmail.com Wed Jul 16 08:09:30 2008 From: jeffober at gmail.com (Jeff) Date: Wed, 16 Jul 2008 05:09:30 -0700 (PDT) Subject: bad recursion, still works References: mailman.112.1216164093.922.python-list@python.org Message-ID: <20cba7ab-72d2-4c7b-8f3f-48f39eaf9625@m3g2000hsc.googlegroups.com> On Jul 15, 7:21?pm, Michael Torrie wrote: > iu2 wrote: > > I still don't understand: In each recursive call to flatten, acc > > should be bound to a new [], shouldn't it? Why does the binding happen > > only on the first call to flatten? > > Nope. ?In each new call it's (re)bound to the same original list, which > you've added to as your function continues--it's mutable. ?Default > variables that are bound to mutable objects are one of the big caveats > that is mentioned in the FAQ. Is this avoidable by using a call to list() in the definition instead? From fredrik at pythonware.com Sun Jul 20 10:30:16 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jul 2008 16:30:16 +0200 Subject: regex doubts In-Reply-To: <504d473e-375a-4111-ae2e-c06aaa37b096@p25g2000pri.googlegroups.com> References: <532965.570.qm@web54502.mail.re2.yahoo.com> <504d473e-375a-4111-ae2e-c06aaa37b096@p25g2000pri.googlegroups.com> Message-ID: John Machin wrote: >> try "[LRM]+$" (an L or an R or an M, one or more times, all the way to >> the end of the string). > > Ummm ... with the default flag settings, shouldn't that be \Z instead > of $ ? Why? The OP was reading input from a user; whether he gets a trailing newline or not depends on the input method, and $ does the right thing for all normal input methods. From tpt at kamstrup.dk Tue Jul 29 07:07:16 2008 From: tpt at kamstrup.dk (mindmind) Date: Tue, 29 Jul 2008 04:07:16 -0700 (PDT) Subject: ironpython, exception in mscorlib when reading .py file from network share References: <6dfb578a-17ff-434d-a071-646ed3ef2b03@z72g2000hsb.googlegroups.com> <15144d50-319d-48ce-bd16-0ead4226dd08@f63g2000hsf.googlegroups.com> Message-ID: > > I don't know the answer - I do know that .NET permissions issues and > accessing network resources are a bit 'weird'. You're likely to get an > answer if you ask on the IronPython mailing list. > I had it running through the night, ~100 times, 25 of these gave the above exception. Hard to see any pattern. From fredrik at pythonware.com Tue Jul 15 17:13:30 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2008 23:13:30 +0200 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: <16651e80807151332o1a2b7446r651f515724a27e0@mail.gmail.com> References: <16651e80807151332o1a2b7446r651f515724a27e0@mail.gmail.com> Message-ID: Jerry Hill wrote: > This is just plain untrue. If 'name is None' evaluates to true, then > the variable 'name' is bound to the singleton value None. It has > nothing to do with allocated memory or null pointers. All it means is > that someplace along the line you did the equivalent of 'name = None' > in your code. On the other hand, there's nothing that keeps a Python implementation from using NULL to represent the None value. From deets at nospam.web.de Tue Jul 22 08:42:18 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 14:42:18 +0200 Subject: Automatically loading and initialising objects from a plugins directory References: Message-ID: <6em2v8F7o4qgU1@mid.uni-berlin.de> Dave Challis wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > I'm trying to write some code which: > 1. Finds all modules in a plugin directory > 2. Imports those modules > 3. Creates an instance of each object defined in the module (each module > will contain exactly 1 object, which is a subclass of 'Plugin') > > The closest I've come so far is with something like: > > In plugin.py: > # taken from http://docs.python.org/lib/built-in-funcs.html > def my_import(name): > mod = __import__(name) > components = name.split('.') > for comp in components[1:]: > mod = getattr(mod, comp) > return mod > > def import_plugins(): > mods = [] > for filename in os.listdir('/plugins'): > if filename.endswith('.py'): > name = os.path.splitext(filename)[0] > mods.append(my_import('plugins.' + name)) > return mods > > class Plugin(object): > pass > > > In plugins/exampleplugin.py: > class ExamplePlugin(Plugin): > def __init__(self): > pass > > > Calling import_plugins() then gives me a list containing references to > modules. > > How can I loop through that list and create an instance of whatever > object was defined within the module? (In this case I'd want to > construct an instance of ExamplePlugin) Like this: for name in dir(plugin): thing = getattr(plugin, name) try: if issubclass(thing, Plugin): thing() except ValueError: # issubclass sucks pass Diez From wuwei23 at gmail.com Tue Jul 22 01:06:49 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 21 Jul 2008 22:06:49 -0700 (PDT) Subject: Website Creation using Python References: Message-ID: <3bdf7eb8-22a7-49f9-85c1-fce2a20e9fed@t12g2000prg.googlegroups.com> On Jul 22, 12:44?am, Amie wrote: > I would like some help on how to create a website using the python > programming language. > I've tried using enamel, but had some problems because I could not > create html tables and intergrating it with python, like you use it > when coding in php. If you're familiar with the PHP approach and are planning on using Apache, you might find mod_python and Python Server Pages more accessible: * http://en.wikipedia.org/wiki/Mod_python * http://www.onlamp.com/pub/a/python/2004/02/26/python_server_pages.html There are a *lot* of web frameworks for Python (I hadn't even heard of Enamel prior to your post) which provide varying degrees of support and ease of use, there's a nice overview here: * http://wiki.python.org/moin/WebFrameworks Django does seem to be leading in terms of popularity atm. Having developed an application in TurboGears, I can testify that having a large user base to draw support help from can be -very- handy. Hope this helps. - alex23 From jwkenne at attglobal.net Sun Jul 20 18:29:25 2008 From: jwkenne at attglobal.net (John W Kennedy) Date: Sun, 20 Jul 2008 18:29:25 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <48617847$0$5021$607ed4bc@cv.net> <486ae06b$0$5011$607ed4bc@cv.net> Message-ID: <4883bc90$0$7327$607ed4bc@cv.net> Robert Maas, http://tinyurl.com/uh3t wrote: >>>> ... the "thunks" were necessary at the machine-language level to >>>> /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. >>> Ah, thanks for the clarification. Is that info in the appropriate >>> WikiPedia page? If not, maybe you would edit it in? >> From: John W Kennedy >> It is explained s.v. "thunk", which is referenced from "ALGOL >> 60". The ALGOL "pass-by-name" argument/parameter matching was >> perhaps the most extreme example ever of a language feature that >> was "elegant" but insane. What it meant, in effect, was that, >> unless otherwise marked, every argument was passed as two closures, >> one that returned a fresh evaluation of the expression given as the >> argument, which was called every time the parameter was read, and >> one that set the argument to a new value, which was called every >> time the parameter was set. > > Wow! All these years when I occasionally heard of a "thunk" I never > was told, until now, what it really meant. Thanks for the info!! > > Followup question #1: I assume these are lexical closures in the > environment of the point of the call, right? Yes. (Actually, subprogram calls are first described as working like macro expansions, but then the specification adds that there must be magic fixups so that variable names are resolved in point-of-call context anyway.) At this point in the history of computing, the conceptual distinction between subprograms and macros was not at all clear. It was quite possible to have "macros" that generated an out-of-line subprogram once and then generated calling code the first time and every time thereafter (it was a way of life on systems without linkage editors or linking loaders), and it was also quite possible to refer to in-line macro expansions as "subprograms". I suspect that the triumph of FORTRAN may have had something to do with cleaning up the terminological mess by the mid-60s. Into the 60s, indeed, there were still machines being made that had no instruction comparable to the mainframe BASx/BALx family, or to Intel's CALL. You had to do a subprogram call by first overwriting the last instruction of what you were calling with a branch instruction that would return back to you. > Followup question #2: For simple arithmetic expressions, I can > possibly understand how the UPDATE closure might be implemeted > (expressed in Lisp to make the intent clear): > Call form: MyFunction(X+2); > GET closure: (+ closedX 2) > UPDATE closure: (lambda (newval) (setf closedX (- newval 2)) > Thus from inside MyFunction where formal parameter Arg1 is bound > to actual parameter X+2, after doing Arg1 := 7; X will have the > value 5 so that calling Arg1 will return 7 as expected, right? > But if the actual argument is something complicated, especially if > it makes a nested function call, how can that possibly be > implemented? It was forbidden. In the formal definition of ALGOL 60, there was no such thing as an external subprogram (except for non-ALGOL code, which was treated as magic), so the whole program was supposed to be one compile. Therefore, a theoretical compiler could verify that any parameter used as an LHS was always matched with an argument that was a variable. (However, a "thunk" was still required to evaluate any array index and, possibly, to convert between REAL and INTEGER variables.) Many actual compilers /did/ support separate complication as a language extension -- I suppose they had to use run-time checking. -- John W. Kennedy "Compact is becoming contract, Man only earns and pays." -- Charles Williams. "Bors to Elayne: On the King's Coins" From giltay at gmail.com Tue Jul 29 14:36:20 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Tue, 29 Jul 2008 11:36:20 -0700 (PDT) Subject: iterating "by twos" References: Message-ID: <70a172ac-0491-4918-9c74-6a577f35068a@d45g2000hsc.googlegroups.com> On Jul 29, 1:36?pm, kj wrote: > Is there a special pythonic idiom for iterating over a list (or > tuple) two elements at a time? I use this one a lot: for x, y in zip(a, a[1:]): frob(x, y) Geoff G-T From norseman at hughes.net Mon Jul 21 16:36:15 2008 From: norseman at hughes.net (norseman) Date: Mon, 21 Jul 2008 13:36:15 -0700 Subject: sending input to an embedded application In-Reply-To: <4884A558.2000209@nienna.org> References: <4884A558.2000209@nienna.org> Message-ID: <4884F33F.7000200@hughes.net> Matthew Fitzgibbons wrote: > > mefyl wrote: >> Uwe Schmitt wrote: >>> On 12 Jul., 09:08, George Oliver wrote: >>>> What I would like to do is take a program and embed it or put it >>>> within a Python-run GUI, using the GUI just to capture and send input >>>> to the application, and display the ouput. >>> Which interface does your interpreter provide ? Just commandline or >>> can you access by other methods ? >>> >>> http://sourceforge.net/projects/pexpect/ might help you >>> >> >> Although Pexpect looks more advanced and complete, you might want to >> take a >> look at popen* modules. It enables you to easily run a subprocess, >> feed him >> data on stdin, retrieve output from stdout/stderr, and wait for its >> completion. >> >> http://docs.python.org/lib/module-popen2.html >> > > I believe the subprocess module is the recommended module to use now. > > -Matt > -- > http://mail.python.org/mailman/listinfo/python-list > ===================================== HUMMMMMM! # print "popen3 run" ########## from existing python docs: from popen2 import * r,w,e= popen3('dmesg | grep hda') print r.read() print "subprocess run" ########## from existing python docs: # "... Replacing older functions with the subprocess module..." from subprocess import * p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0] #documentation quits print p2.communicate() # """ Why do children insists on making things more complicated than necessary? If the stated bragging rights of Python is that one writes less code to accomplish more, then I have to say "bullshit", just count the printable characters. to write less would be to change something like this: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close() ### I have to guess what type error to code for and I'll need another module to decode what actually went wrong. to this: if (fd = os.open(filename, 'O_RDRW|O_BINARY, 0666) == -1) ...handle it if fd.err.type == THIS #catagory if fd.err == this #specific do this etc. ## just to see what went wrong? print fd.err.type, fd.err else: #just to match above continue processing ### error reporting actually usefull who says fd cannot be simple interger or pointer to error block depending on whether it's valid or not? The bonus is, if there is no trap it will stop anyway first time fd is used as a file number. The crash usually actually points to the correct place. :) All that aside: subprocess seems to have a problem: """ # When I run the above I get: ============== PY:> py test.py popen3 run ide0: BM-DMA at 0x1400-0x1407, BIOS settings: hda:DMA, hdb:pio hda: ST9160821A, ATA DISK drive hda: attached ide-disk driver. hda: host protected area => 1 hda: cannot use LBA48 - capacity reset from 312581808 to 268435456 hda: 268435456 sectors (137439 MB) w/8192KiB Cache, CHS=19457/255/63, UDMA(100) hda: hda1 hda2 hda3 < hda5 hda6 hda7 hda8 > subprocess run ('', None) PY:> ============= Note subprocess yields unexpected answer. Probably needs better documentation and less typing. :) The "PY:> " is result of script to change to dir python and set the PATH py is copy of python renamed to afford less typing. (Unix vs Microsoft) Note: without lots of extra effort, the piping only works for commands like grep that are built to accept redirected I/O. I have yet to get it to work with the GUI type. Those need special things implanted at compile time because they don't use or even want the command line interface. Typically they are "Point'n'Click" or take a hike. GUIs are visually more appealing but don't play well in the production world. Steve norseman at hughes.net From keith.hughitt at gmail.com Mon Jul 14 11:06:30 2008 From: keith.hughitt at gmail.com (Keith Hughitt) Date: Mon, 14 Jul 2008 08:06:30 -0700 (PDT) Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> Message-ID: <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> On Jul 12, 12:52?am, "Gabriel Genellina" wrote: > En Fri, 11 Jul 2008 15:42:37 -0300, Keith Hughitt ? > escribi?: > > > I am having a little trouble figuring out how to convert a python > > datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would > > like to create a UTC date so that when I send it to MySQL (which > > treats all dates at local dates by default), it will already have > > incorporated the proper UTC offset. I've tried looking through the > > docshttp://python.active-venture.com/lib/datetime-datetime.html), but > > have not had any luck. > > You have to use a "timezone aware" datetime object. If all you want is to ? > store an UTC date, the tzinfo demo classes that you can find in the Python ? > docs at may be enough. > A more complete implementation is at > > If you pass a "timezone aware" datetime object as a SQL parameter, the ? > database should store it correctly (but I don't have a MySQL instance at ? > hand to test it) > > -- > Gabriel Genellina Thanks for advice Gabriel. I downloaded the tzinfo demo class, saved it as UTC.py and imported it. I'm still not exactly sure how to use it though. It looks like the file already creates an instance of the UTC tzinfo class (line 20: "utc = UTC()"), however, when I try to test it out in the interpreter, it cannot be found. I'm new to python, and there is probably something obvious I'm missing, but do you have any ideas? Here is what I'm attempting: ============ output begin ============= Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import datetime, UTC >>> t = datetime.datetime(2008, 7, 14, 00, 00, 00, UTC()) Traceback (most recent call last): File "", line 1, in TypeError: 'module' object is not callable >>> utc Traceback (most recent call last): File "", line 1, in NameError: name 'utc' is not defined >>> utc = UTC() Traceback (most recent call last): File "", line 1, in TypeError: 'module' object is not callable >>> ============ output begin ============= Any ideas? Thanks, Keith From jdscript at gmail.com Fri Jul 11 23:13:04 2008 From: jdscript at gmail.com (happy) Date: Fri, 11 Jul 2008 20:13:04 -0700 (PDT) Subject: variable question Message-ID: <6f02608a-2b2e-478d-a153-d10bbfb58981@c58g2000hsc.googlegroups.com> Can a variable be considered the simplest of the data structures. I am tutoring some kids about basics of programming using python. Not an expert in computer sciences, but am a python enthusiast. I wanted to know if it is correct to say a variable is a data structure, it has a name and a value. Put a stack of variables in a special data structure called a dictionary where the each name associates to a value. If in a data structure, one uses numbers starting from 0 to describe the name, it becomes a list and so forth.... From timothy.grant at gmail.com Mon Jul 14 22:14:39 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Mon, 14 Jul 2008 19:14:39 -0700 Subject: One step up from str.split() In-Reply-To: References: Message-ID: On Mon, Jul 14, 2008 at 6:33 PM, Joel Koltner wrote: > I normally use str.split() for simple splitting of command line arguments, > but > I would like to support, e.g., long file names which-- under windows -- are > typically provided as simple quoted string. E.g., > > myapp --dosomething --loadthis "my file name.fil" > > ...and I'd like to get back a list wherein ListEntry[3]="my file name.fil" > , > but just running str.split() on the above string creates: > > >>> ListEntry='myapp --dosomething --loadthis "my file name.fil"' > >>> ListEntry.split() > ['myapp', '--dosomething', '--loadthis', '"my', 'file', 'name.fil"'] > > Is there an easy way to provide just this one small additional feature > (keeping quoted names as a single entry) rather than going to a full-blown > command-line argument parsing tool? Even regular expressions seem like > they'd > probably be overkill here? Or no? > > Thanks, > ---Joel I've found that anytime I have more than one option on the command line, optparse is the way to go. It works very very well for every circumstance I've been able to throw at it. -- Stand Fast, tjg. [Timothy Grant] -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun Jul 27 19:00:51 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Jul 2008 23:00:51 GMT Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <009cf9ab$0$20302$c3e8da3@news.astraweb.com> On Sun, 27 Jul 2008 16:04:43 -0400, Colin J. Williams wrote: >> For those who don't like the way the empty first argument looks, maybe >> something like this could be allowed: >> >> def fun( ., cat): >> > I don't see the need for the comma in fun. Or the parentheses and colon. Can we remove them too? -- Steven From javaboy.ms at gmail.com Mon Jul 21 09:38:40 2008 From: javaboy.ms at gmail.com (sahasranaman) Date: Mon, 21 Jul 2008 06:38:40 -0700 (PDT) Subject: Odd math related issue. References: <43332.3139710867$1216630189@news.gmane.org> <48847F5D.9080509@sellerengine.com> Message-ID: <2dede424-2ed9-4634-8e18-1ff44cc8320d@y22g2000prd.googlegroups.com> On Jul 21, 5:30?pm, Fredrik Lundh wrote: > Alexandru Palade wrote: > > However, you should be carefully because using an %i modifier for a > > what-should-be a float value truncates the value in a way you may not > > expect. > > > What I mean is that if you have sent 2 out of 3 bytes, the math will be > > 200/3 which with the %i modifier will print 66, rather than 66.6 (or at > > least 67 which is closer - have a look at the round() function). > > My suggested workaround doesn't use floats. ?As for rounding, that's > more of a usability issue -- seeing the download process getting stuck > at 100% can be rather frustrating for the poor user. ?Better truncate > towards zero. > > > Another thing, you could have just added a dot after the constant in > > order to promote the expression to be evaluated as float. As in > > ? ?percentage = bytes_transferred / /self/.__sessions[path].total_bytes > > * 100. > > (notice the last dot) > > Did you try that? > > ?>>> 2 / 3 * 100. > 0.0 > > You can fix this with parentheses, but I usually recommend an explicit > "cast" instead, to make it obvious what you're doing: > > ? ? ?result = float(a) / b > > try 2.0 / 3 * 100 that would solve all trouble From Bill at SynectixLtd.com Sat Jul 12 08:36:16 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Sat, 12 Jul 2008 13:36:16 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: "Tim Golden" wrote in message news:mailman.332.1215788687.20628.python-list at python.org... > Bill Davy wrote: >> Traceback (most recent call last): >> File "H:/Personal/OutlookIF1/t2.py", line 18, in >> outlook = win32com.client.gencache.EnsureDispatch >> ("Outlook.Application") >> File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line >> 536, in EnsureDispatch >> mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], >> bForDemand=bForDemand) >> File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line >> 393, in EnsureModule >> module = GetModuleForTypelib(typelibCLSID, lcid, major, minor) >> File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line >> 262, in GetModuleForTypelib >> AddModuleToCache(typelibCLSID, lcid, major, minor) >> File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line >> 554, in AddModuleToCache >> dict = mod.CLSIDToClassMap >> AttributeError: 'module' object has no attribute 'CLSIDToClassMap' > > > Just in case, could you delete the contents of your gen_py > directory (probably in %TEMP%\gen_py) > > TJG OK, Put the following ahead with the following results. TempDir = os.getenv("TEMP"); WorkDir = TempDir + '\\gen_py' print WorkDir try: os.rmdir(WorkDir); except WindowsError, detail: print "Ignoring Windows error: ", detail ... Result: C:\DOCUME~1\Bill\LOCALS~1\Temp\gen_py Ignoring Windows error: [Error 2] The system cannot find the file specified: 'C:\\DOCUME~1\\Bill\\LOCALS~1\\Temp\\gen_py' Traceback (most recent call last): File "H:\Personal\OutlookIF1\t2.py", line 26, in outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 536, in EnsureDispatch mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], bForDemand=bForDemand) File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 393, in EnsureModule module = GetModuleForTypelib(typelibCLSID, lcid, major, minor) File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 262, in GetModuleForTypelib AddModuleToCache(typelibCLSID, lcid, major, minor) File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 554, in AddModuleToCache dict = mod.CLSIDToClassMap AttributeError: 'module' object has no attribute 'CLSIDToClassMap' >>> So, although that directory did exist, it does not now (even after the program has run). Any other ideas? But many thnaks, Bill From grflanagan at gmail.com Fri Jul 11 09:58:41 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Fri, 11 Jul 2008 15:58:41 +0200 Subject: read file into list of lists In-Reply-To: References: Message-ID: antar2 wrote: > Hello, > > I can not find out how to read a file into a list of lists. I know how > to split a text into a list > > sentences = line.split(\n) > > following text for example should be considered as a list of lists (3 > columns and 3 rows), so that when I make the print statement list[0] > [0], that the word pear appears > > > pear noun singular > books nouns plural > table noun singular > > Can someone help me? > class Table(object): def __init__(self, text=None): self.rows = [] if text: self.write(text) def write(self, text): self.rows.extend(line.split() for line in text.splitlines()) def read(self): return '\n'.join(' '.join(row) for row in self.rows) def __getitem__(self, i): return self.rows[i] def __iter__(self): return iter(self.rows) table = Table() table.write('apple orange coconut') print table[0][1] print table.read() table.write('clematis rose lily') print table[1][2] print table.read() for row in table: print row (If you have quoted items, it is more difficult) G. From mail at timgolden.me.uk Wed Jul 16 13:45:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 18:45:03 +0100 Subject: About wmi In-Reply-To: <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> <487E1AD4.9020509@timgolden.me.uk> <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> Message-ID: <487E339F.3040801@timgolden.me.uk> patrol wrote: >>>> import wmi >>>> wmi.WMI('non-existent computer') > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\wmi.py", line 1199, in connect > handle_com_error (error_info) > File "C:\Python25\lib\wmi.py", line 184, in handle_com_error > exception_string = [u"%s - %s" % (hex (hresult_code), > hresult_name)] > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > 4: ordinal > not in range(128) > -------------------------------------------------------------------------------------- > yup,error_info contains the Chinese encoded string. All of the Simple > Chinese Windows use the CP936.Every Chinese word utilizes two > bytes.Maybe you can fix this bug by modifying handle_com_error. Well, that's what I've done in that latest version. Only I naively assumed that I could use sys.stdout.encoding to determine the encoding. I'll have to try harder. TJG From yuwenwu010 at gmail.com Fri Jul 18 10:32:28 2008 From: yuwenwu010 at gmail.com (yuwenwu010 at gmail.com) Date: Fri, 18 Jul 2008 07:32:28 -0700 (PDT) Subject: cheap air max 87 shoes PayPal Message-ID: cheap air max 87 shoes PayPal Dear friend welcome to shopping on www.electronic-paypal.cn 1.5% paypal handling charge supports the online payment! 2.Use your intergla replacement more good gift! 3.notes by email and website of deliver each package at first time. Have a good day! Sincerely yours, CHINASILKROAD EXPORTS CO., LTD From __peter__ at web.de Tue Jul 1 07:20:28 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Jul 2008 13:20:28 +0200 Subject: Disabling the magic "last expression" _ variable References: <486a108d$0$14358$e4fe514c@news.xs4all.nl> Message-ID: Koen Vossen wrote: > A project I'm currently working on uses Turbogears as a framework. I'd > like to interact with it using the tg-admin shell. We also use gettext's > _() function for internationalization. Now, this function is overwritten > in interactive mode, which causes annoying exceptions. Is it possible to > disable this behavior? >>> import sys >>> def displayhook(result): ... if result is not None: ... __builtins__._last = result ... print result ... >>> "yadda" yadda >>> _ Traceback (most recent call last): File "", line 1, in NameError: name '_' is not defined >>> _last yadda Peter From B.L.Michielsen at wanadoo.fr Fri Jul 11 19:25:00 2008 From: B.L.Michielsen at wanadoo.fr (Bas Michielsen) Date: Sat, 12 Jul 2008 01:25:00 +0200 Subject: Using SWIG to build C++ extension References: Message-ID: <4877ec43$0$877$ba4acef3@news.orange.fr> mk wrote: > Hello, > > I'm having terrible problems building C++ extension to Python 2.4 using > SWIG. I'd appreciate if somebody knowledgeable at the subject took a > look at it. swig-1.3.29, g++ (GCC) 4.1.1 20070105 (Red Hat 4.1.1-52). > > I used following commands to build C++ extension: > > # swig -c++ -python edit_distance.i > # c++ -c edit_distance.c edit_distance_wrap.cxx edit_distance.cpp -I. > -I/usr/include/python2.4 > > > Linux RH (9.156.44.105) root ~/tmp # c++ -c edit_distance.c > edit_distance_wrap.cxx edit_distance.cpp -I. -I/usr/include/python2.4 > c++: edit_distance.cpp: No such file or directory > edit_distance_wrap.cxx: In function ?PyObject* > _wrap_edit_distance(PyObject*, PyObject*)?: > edit_distance_wrap.cxx:2579: error: ?string? was not declared in this > scope edit_distance_wrap.cxx:2579: error: ?arg1? was not declared in this > scope edit_distance_wrap.cxx:2580: error: ?arg2? was not declared in this > scope edit_distance_wrap.cxx:2597: error: expected type-specifier before > ?string? edit_distance_wrap.cxx:2597: error: expected `>' before ?string? > edit_distance_wrap.cxx:2597: error: expected `(' before ?string? > edit_distance_wrap.cxx:2597: error: expected primary-expression before > ?>? token > edit_distance_wrap.cxx:2597: error: expected `)' before ?;? token > edit_distance_wrap.cxx:2605: error: expected type-specifier before > ?string? edit_distance_wrap.cxx:2605: error: expected `>' before ?string? > edit_distance_wrap.cxx:2605: error: expected `(' before ?string? > edit_distance_wrap.cxx:2605: error: expected primary-expression before > ?>? token > edit_distance_wrap.cxx:2605: error: expected `)' before ?;? token > > What's weird is that I _did_ use std:: namespace prefix carefully in the > code: > > #include > #include > #include > > const unsigned int cost_del = 1; > const unsigned int cost_ins = 1; > const unsigned int cost_sub = 1; > > > unsigned int edit_distance( std::string& s1, std::string& s2 ) > { > const size_t len1 = s1.length(), len2 = s2.length(); > std::vector > d(len1 + 1, > std::vector(len2 + 1)); > > for(int i = 1; i <= len1; ++i) > for(int j = 1; j <= len2; ++j) > d[i][j] = std::min(d[i - 1][j] + 1, > std::min(d[i][j - 1] + 1, d[i - 1][j - 1] + (s1[i - 1] == s2[j - 1] ? 0 > : 1))); > > return d[len1][len2]; > } > > Ok, anyway I fixed it in the generated code (edit_distance_wrap.cxx). It > compiled to .o file fine then. It linked to _edit_distance.so as well: > > # c++ -shared edit_distance_wrap.o -o _edit_distance.so > > But now I get import error in Python! > > Linux RH root ~/tmp # python > Python 2.4.3 (#1, Dec 11 2006, 11:38:52) > [GCC 4.1.1 20061130 (Red Hat 4.1.1-43)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import edit_distance > Traceback (most recent call last): > File "", line 1, in ? > File "edit_distance.py", line 5, in ? > import _edit_distance > ImportError: ./_edit_distance.so: undefined symbol: _Z13edit_distanceRSsS_ > > > > What did I do to deserve this? :-) > > > edit_distance.i file just in case: > > %module edit_distance > %{ > #include "edit_distance.h" > %} > > extern unsigned int edit_distance(string& s1, string& s2); Hello, I took your example files and did the following: changed the #include "edit_distance.h" to #include "edit_distance.c" in the edit_distance.i file. Then I changed the first few lines of your function definition unsigned int edit_distance( const char* c1, const char* c2 ) { std::string s1( c1), s2( c2); and also adapted the signature in the edit_distance.i file. Then swig -shadow -c++ -python edit_distance.i g++ -c -fpic -I/usr/include/python edit_distance_wrap.cxx g++ -shared edit_distance_wrap.o -o _edit_distance.so I could import edit_distance without any error messages >>> import edit_distance >>> print edit_distance.edit_distance( "toto", "titi") 2 >>> print edit_distance.edit_distance( "toto", "toti") 1 Perhaps I changed too many things, but this may get you started, Regards, Bas From mail at timgolden.me.uk Mon Jul 7 10:17:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 07 Jul 2008 15:17:03 +0100 Subject: python mysteriously halts In-Reply-To: <13a33043-21d1-40c0-a938-6e905d958064@m3g2000hsc.googlegroups.com> References: <13a33043-21d1-40c0-a938-6e905d958064@m3g2000hsc.googlegroups.com> Message-ID: <4872255F.6000204@timgolden.me.uk> Todd wrote: > I ran a python script last night which connects to a matlab automation > server via DCOM (using win32com). I expected to see the results when > I came in this morning. But apparently, not long after I left, python > stopped. I hit enter in the console, and it started again. Symptomatically, at least, this can be caused by someone starting to select (with the mouse) an area of the screen: the process will pause until is pressed, which copies the area to the clipboard. This only happens with a console window, but it sounds like that's what you had running. TJG From is_this at visible.com Wed Jul 30 08:10:53 2008 From: is_this at visible.com (Bruce Frederiksen) Date: Wed, 30 Jul 2008 12:10:53 +0000 Subject: Defunct when using subprocess.Popen References: <6D3D064BBC122445A4577CE1895FA06501755913@afsegbgex1.af.se> Message-ID: <7802d$48905a4d$18607848$7519@KNOLOGY.NET> On Wed, 30 Jul 2008 01:56:28 -0300, Gabriel Genellina wrote: > You should call os.waitpid() after killing the child process, to let the > OS free the resources allocated to it. > The subprocess.Popen object supports a 'wait' method directly. From sri_annauni at yahoo.co.in Wed Jul 30 07:17:26 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Wed, 30 Jul 2008 16:47:26 +0530 (IST) Subject: Python Modules To convert PDF files to HTML files Message-ID: <217761.61697.qm@web7905.mail.in.yahoo.com> Hi, could someone tel me any python modules which can be used to convert PDF files to HTML files?? Thanks, Srini Unlimited freedom, unlimited storage. Get it now, on http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/ From tjreedy at udel.edu Wed Jul 30 12:39:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jul 2008 12:39:02 -0400 Subject: Pointers/References in Python? In-Reply-To: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> References: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Message-ID: boblatest at googlemail.com wrote: > Hello, > > I have a long list of memory-heavy objects that I would like to access > in differently sorted order. Let's say I'd like to have lists called > by_date or by_size that I can use to access the objects in the > specified order. > > Of course I can just build those lists naively by creating copies of > the original list and then sorting them according to my wishes. But > that would create huge memory overhead. Of course I could use lists of > indices into the "master" list, just as in C I'd create lists or > arrays of pointers into the original data. > > Is there a clever Python way to do this, or should I just use lists of > indices? > > I know there is a thing called "shallow copy" that has something to do > with not duplicating memory content but I don't understand the > concept. Maybe that's what would help here, too. A containers/collections contain/collect references to objects, not the objects themselves. lcopy = somelist[:] # or list(somelist) makes a shallow copy, which only copies the references. There are applications for lists of indexes, but they are fairly specialized. tjr From zstumgoren at gmail.com Thu Jul 31 15:01:36 2008 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 31 Jul 2008 15:01:36 -0400 Subject: Hobbyist - Python vs. other languages In-Reply-To: References: Message-ID: >From this noob's perspective, I'd say take a look at Magnus Lie Hetland's Beginning Pythonbook. It covers the core syntax (which it sounds like you're familiar with already) and then includes a bunch of projects, from text processing to cgi programming to remote file editing and basic game programming. Granted, you can find a lot of these examples as freeware, but I guess you stand to learn plenty by extending the code he provides. Good luck! Serdar T. On Thu, Jul 31, 2008 at 2:32 PM, fprintf wrote: > I have been playing with computers since I first learned to program > moving shapes on an Atari 800XL in BASIC. After many years of dabbling > in programming languages as a hobbyist (I am not a computer scientist > or other IT professional), I have never found a way to stick with a > language far enough to do anything useful. I learn all about loops > and data structures and functions/methods etc. but never get to create > a program that will do anything of value that I can't more easily do > via freeware. Well, except the slot car timing system I wrote in C++ > for Linux many moons ago. > > Honestly Python seems like a breath of fresh air and possibly a way to > get back to my BASIC roots, you know, programming just for the fun of > it. > > Since I don't have a specific problem to solve, besides > Pythonchallenge (which I found very cryptic), and Project Euler (which > I found beyond my mathematics skills), is there a place to go for > increasingly difficult problems to solve? I have followed a number of > the recommended online tutorials that contain a logical progression of > problems and yet they all end at the point where a person has enough > knowledge of the syntax, but not really enough to do anything. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Serdar Tumgoren The Record 150 River Street Hackensack, NJ 07601 201-403-0834 tumgoren at northjersey.com northjersey.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Wed Jul 9 01:55:06 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 09 Jul 2008 15:55:06 +1000 Subject: Returning the positions of a list that are non-zero References: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> Message-ID: <87bq17vbyd.fsf@benfinney.id.au> Benjamin Goudey writes: > For example, if my original list is [0,0,1,2,1,0,0] I would like to > produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices > of where the non-zero values used to be). Removing non-zero values > is very easy but determining the indicies is where I'm having > difficulty. The built-in 'enumerate' function is made for this. Creating the new list can be done efficiently and clearly with a list comprehension. Further, presumably you want to do further operations on these new series of data; wouldn't it be better to have the values and original indices actually correlated together? This code produces a two-element tuple for each original non-zero value: >>> sparse_data = [0, 0, 1, 2, 1, 0, 0] >>> nonzero_data = [(index, value) ... for (index, value) in enumerate(sparse_data) ... if value != 0] >>> nonzero_data [(2, 1), (3, 2), (4, 1)] >>> for (index, value) in nonzero_data: ... print "Value %(value)r was originally at index %(index)r" % vars() ... Value 1 was originally at index 2 Value 2 was originally at index 3 Value 1 was originally at index 4 -- \ ?Experience is that marvelous thing that enables you to | `\ recognize a mistake when you make it again.? ?Franklin P. Jones | _o__) | Ben Finney From mlowicki at gmail.com Thu Jul 31 04:33:45 2008 From: mlowicki at gmail.com (=?ISO-8859-2?Q?=A3owik?=) Date: Thu, 31 Jul 2008 10:33:45 +0200 Subject: hosting on djangodomain.com Message-ID: Hi! Did anyone used this hosting or heard about it? It's good or not? what can you talk about it? From ironfroggy at gmail.com Thu Jul 17 08:30:13 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Thu, 17 Jul 2008 08:30:13 -0400 Subject: storing references instead of copies in a dictionary In-Reply-To: References: Message-ID: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> On Thu, Jul 17, 2008 at 7:45 AM, mk wrote: > Hello everyone, > > I'm storing functions in a dictionary (this is basically for cooking up my > own fancy schmancy callback scheme, mainly for learning purpose): > >>>> def f2(arg): > ... return "f2 " + arg > ... >>>> >>>> def f1(arg): > ... return "f1" + arg > ... > >>>> a={'1': f1, '2': f2} >>>> >>>> [ x[1](x[0]) for x in a.items() ] > ['f11', 'f2 2'] > > Well, neat. Except if I change function definitions now, old functions are > called. And rightly: > > {'1': , '2': } >>>> f1 > >>>> >>>> def f1(arg): > ... return "NEW f1 " + arg > ... >>>> f1 > > > The address of function f1 has obviously changed on redefinition. > > Storing value copies in a dictionary on assignment is a reasonable default > behaviour. > > However, in this particular case I need to specifically store _references to > objects_ (e.g. f1 function), or should I say _labels_ (leading to objects)? > > Of course, I can basically update the dictionary with a new function > definition. > > But I wonder, is there not a way _in general_ to specifically store > references to functions/variables/first-class objects instead of copies in a > dictionary? As was pointed out already, this is a basic misunderstanding of assignment, which is common with people learning Python. To your actual problem... Why do you wanna do this anyway? If you want to change the function in the dictionary, why don't you simply define the functions you'll want to use, and change the one you have bound to the key in the dictionary when you want to change it? In other words, define them all at once, and then just d['1'] = new_f1. What is wrong with that? For completeness: def new_f1(arg): return "NEW f1 " + arg f1.func_code = new_f1.func_code Don't use that unless you really have to and I nearly promise that you don't. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From fredrik at pythonware.com Mon Jul 21 12:12:17 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 18:12:17 +0200 Subject: Python Written in C? In-Reply-To: <4884B3EB.4090001@timgolden.me.uk> References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> <4884B3EB.4090001@timgolden.me.uk> Message-ID: Tim Golden wrote: >> Wrong! Real programmers can program using only Touring machine > > Is that some kind of bicycle? there's a nearly infinite number of software projects with that name, but the Ultimate Touring Machine could be found in sydney not long ago: http://tinyurl.com/5t2dl4 From stochashtic at yahoo.ca Tue Jul 29 11:25:36 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 29 Jul 2008 17:25:36 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <488d86e2$1@news2-rz-ap.ethz.ch> <488dc3eb$1@news2-rz-ap.ethz.ch> <488ddc3c$1@news2-rz-ap.ethz.ch> Message-ID: <488f3670$1@news2-rz-ap.ethz.ch> On Mon, 28 Jul 2008 16:48:28 +0200, Suresh Pillai wrote: > Okay, please consider this my one absolutely stupid post for the year. > I'd like to pretend it never happened but unfortunately the web doesn't > allow that. Having never used sets, I unfort read something that lead > to it, but ... Okay, got some sleep and what I meant to ask, although equally basic, but not silly: For sets, I presume they are built on top of or like dicts, and there is nothing crazy in the low level implementation so that I can be guaranteed that if I don't alter the set, then the order, although arbitrary, will be maintained in successive iterations over the contents? From michael at stroeder.com Tue Jul 8 04:58:27 2008 From: michael at stroeder.com (=?UTF-8?B?TWljaGFlbCBTdHLDtmRlcg==?=) Date: Tue, 08 Jul 2008 10:58:27 +0200 Subject: windows active directory ldap output encoding In-Reply-To: References: Message-ID: Michael Str?der wrote: > jo3c wrote: >> Im trying to get some information out of a windows sever 2003 chinese >> active directory system >> so let's say encoding is probably big5 or utf-8 > > The Unicode encoding of LDAP attributes with syntax Directory String is > always UTF-8 (e.g. attributes 'cn', 'sn', 'givenName' or 'displayName'). BTW: I'd be curious to see whether my web2ldap works with Chinese characters. Since you already have python-ldap installed it's easy to download (from http://www.web2ldap.de/download.html) and unpack the tar.gz and start it as stand-alone web server: python /sbin/web2ldap.py -d off Ah forgot, pyweblib needs to also be installed with usual python setup.py install: http://www.stroeder.com/pylib/PyWebLib/ If everything is correctly configured in your browser you should the correct Unicode chars. Maybe you can even maintain your AD entries. Ciao, Michael. From 2007 at jmunch.dk Sun Jul 27 14:35:19 2008 From: 2007 at jmunch.dk (Anders J. Munch) Date: Sun, 27 Jul 2008 20:35:19 +0200 Subject: Rant (was Re: x*x if x>10 In-Reply-To: References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3g8rF9gfj0U1@mid.uni-berlin.de> <6f3gmaF9moqsU1@mid.uni-berlin.de> <1q5p845o2j9htp6vf44u6nqinucsr1numf@4ax.com> Message-ID: <488cbfe7$0$4452$ba624c82@nntp02.dk.telia.net> Gary Herron wrote: > >>> A = [1,2,3] > >>> B = [4,5,6] > >>> C = [7,8,9] > > >>> A+B+C > [1, 2, 3, 4, 5, 6, 7, 8, 9] > > >>> sum([A,B,C], []) > [1, 2, 3, 4, 5, 6, 7, 8, 9] Careful now, this can be very slow. sum uses __add__, not __iadd__, which gives this approach quadratic worst-case runtime. - Anders From norseman at hughes.net Mon Jul 21 12:26:42 2008 From: norseman at hughes.net (norseman) Date: Mon, 21 Jul 2008 09:26:42 -0700 Subject: win32api not found? In-Reply-To: References: Message-ID: <4884B8C2.9020905@hughes.net> Lamonte Harris wrote: > Where can I get the win32api module? I been searching all day on google and > nothing, i installed > https://sourceforge.net/project/showfiles.php?group_id=78018 which requires > win32api and its not found... > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list ============================ I followed the links from python.org to Mark Harmond's win32 package. It loads into (in my case) c:\\Python25\\Lib\\site-packages\\win32 as win32api.pyd Also: try the import win32api command another has suggested before searching all over. HTH Steve norseman at hughes.net From gerard.blais at gmail.com Mon Jul 14 10:24:28 2008 From: gerard.blais at gmail.com (Gerry) Date: Mon, 14 Jul 2008 07:24:28 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> <378b8499-4b1b-4eda-bb13-91bf59c77bfc@a70g2000hsh.googlegroups.com> Message-ID: If keys and values are unique, maybe just store both in the same dictionary: mydict[a] = b mydict[b] = a ... Gerry On Jul 14, 8:31?am, Impotent Verse wrote: > If keys and values are unique you could do this... > > -------------- > > # ? ? ? ? Left ? ? ?: Right > roman = { "One" ? ? : "I", > ? ? ? ? ? "Two" ? ? : "II", > ? ? ? ? ? "Three" ? : "III", > ? ? ? ? ? "Four" ? ?: "IV", > ? ? ? ? ? "Five" ? ?: "V", > ? ? ? ? ? "Six" ? ? : "VI", > ? ? ? ? ? "Seven" ? : "VII", > ? ? ? ? ? "Eight" ? : "VIII", > ? ? ? ? ? "Nine" ? ?: "IX", > ? ? ? ? ? "Ten" ? ? : "X" } > > left, right = zip( *roman.items() ) > left = list(left) > right = list(right) > > print left[ right.index("VIII") ] > > -------------- > > ... result is "Eight". > > Hmmm! zip returns tuples, which need to be turned into lists to do > much with. Maybe not the best solution in this case. > > Verse. From ruabag at gmail.com Fri Jul 4 05:37:38 2008 From: ruabag at gmail.com (rabad) Date: Fri, 4 Jul 2008 02:37:38 -0700 (PDT) Subject: Newbie, list has no attribute iteritems Message-ID: <12caa75c-455a-4ab3-a9c3-4bd191b6965d@k13g2000hse.googlegroups.com> Hi, I've created a custom filter based on HTMLParser, with the following source: class Filter(HTMLParser): def __init__(self, keyfile): HTMLParser.__init__(self) mykwfile = open(keyfile, 'r') self._keywords = [] for kw in mykwfile.read().split('\n'): self._keywords.append(kw) print kw mykwfile.close() self._toProcess = False self.stack = [] def handle_starttag(self, tag, attrs): if 'a' != tag: self.stack.append(self.__html_start_tag(tag, attrs)) return attrs = dict(attrs) self._toProcess = True for key in self._keywords: if 'a' == tag: p = re.compile(key, re.IGNORECASE) if 'href' in attrs: attrs['href'] = p.sub(r'XXXXX',attrs['href']) self.stack.append(self.__html_start_tag(tag, attrs)) def handle_startendtag(self, tag, attrs): if 'img' != tag and 'meta' != tag: self.stack.append(self.__html_startend_tag(tag, attrs)) return attrs = dict(attrs) self._toProcess = True for key in self._keywords: p = re.compile(key, re.IGNORECASE) if 'img' == tag: if 'src' in attrs: attrs['src'] = p.sub(r'XXXXX',attrs['src']) if 'alt' in attrs: attrs['alt'] = p.sub(r'XXXXX',attrs['alt']) if 'meta' == tag: if 'description' in attrs: attrs['description'] = p.sub(r'XXXXX',attrs['description']) if 'content' in attrs: attrs['content'] = p.sub(r'XXXXX',attrs['content']) if 'meta' == tag or 'img' == tag: self._toProcess = False self.stack.append(self.__html_startend_tag(tag, attrs)) def handle_endtag(self, tag): self.stack.append(self.__html_end_tag(tag)) if self._toProcess: self._toProcess = False def handle_data(self, data): if self._toProcess: for key in self._keywords: p = re.compile(key,re.IGNORECASE) data = p.sub(r'XXXXX',data) self.stack.append(data) def __html_start_tag(self, tag, attrs): return '<%s%s>' % (tag, self.__html_attrs(attrs)) def __html_startend_tag(self, tag, attrs): return '<%s%s/>' % (tag, self.__html_attrs(attrs)) def __html_end_tag(self, tag): return '' % (tag) def __html_attrs(self, attrs): _attrs = '' if attrs: _attrs = ' %s' % (' '.join([('%s="%s"' % (k,v)) for k,v in attrs.iteritems()])) return _attrs But when I use it, it gives me the following error message: ERROR Processor exception: AttributeError: 'list' object has no attribute 'it eritems' Traceback (most recent call last): File "d:\esp\lib\python2.3\processors\DocDumpF.py", line 87, in Process p.feed(document.GetValue("data")) File "HTMLParser.py", line 108, in feed File "HTMLParser.py", line 148, in goahead File "HTMLParser.py", line 281, in parse_starttag File "d:\esp\lib\python2.3\processors\DocDumpF.py", line 121, in handle_startt ag self.stack.append(self.__html_start_tag(tag, attrs)) File "d:\esp\lib\python2.3\processors\DocDumpF.py", line 167, in __html_start_ tag return '<%s%s>' % (tag, self.__html_attrs(attrs)) File "d:\esp\lib\python2.3\processors\DocDumpF.py", line 178, in __html_attrs _attrs = ' %s' % (' '.join([('%s="%s"' % (k,v)) for k,v in attrs.iteritems() ])) Anybody knows why it says attrs is not a list element? Thanks, Rub?n From robnhood007 at yahoo.com Tue Jul 15 16:54:39 2008 From: robnhood007 at yahoo.com (robnhood00) Date: Tue, 15 Jul 2008 13:54:39 -0700 (PDT) Subject: Need Python Programmer (preferentially in Los Angeles) Message-ID: I need a python programmer that can integrate graphics into an existing python application. The application is a basic application and the job should be pretty easy for an experienced Python programmer. Los Angeles programmer is preferred but this can obviously be done from anywhere. Please contact me at robnhood007 at yahoo.com is you can help me. Thank you. From mccredie at gmail.com Fri Jul 25 18:43:09 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 25 Jul 2008 15:43:09 -0700 (PDT) Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: <24a548ad-4cb3-410c-89df-21da6ef4220f@j7g2000prm.googlegroups.com> On Jul 24, 9:32?pm, Lawrence D'Oliveiro wrote: > In message > , Matimus > wrote: > > > On Jul 24, 2:54?am, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: > >> In message > >> , > > >> Matimus wrote: > >> > That isn't the standard. With that setup tabs will show up as 4 > >> > spaces, and still confuse you. > > >> Why should that be confusing? The most common tab-stop setting is 4 > >> columns. > > > A tab character is specified as 8 spaces. > > Specified by whom? The most common setting these days is 4 columns. All argument about specification aside, Python interprets a tab character as equivalent to 8 spaces. If you are treating tabs as equivalent to 4 spaces in your python code it will cause IndentationError exceptions to be raised. If you set 'tabstop' to 4 in Vim all of the blocks of code indented using 4 spaces will be aligned with code indented with tabs. That is obviously problematic. Setting 'et' will fix the problem of inserting tabs, but does nothing to adjust the way tabs are displayed. Vim has a feature 'softtabspace'/'sts' which is used to modify the way tabs are inserted without modifying the way they are displayed. If you are writing python code using Vim and you intend to indent using 4 spaces (as recommended by pep8), the best practice I have found is to `set sw=4 ts=8 sts=4 et`. Matt From sisson.j at gmail.com Sun Jul 13 14:52:18 2008 From: sisson.j at gmail.com (Jonathon Sisson) Date: Sun, 13 Jul 2008 13:52:18 -0500 Subject: Socket problems In-Reply-To: References: Message-ID: <487A4EE2.2010600@gmail.com> SSL objects use "write", not "send". You also need to change this: self.sock.write('NICK %s\r\n') % self.nick to this: self.sock.write('NICK %s\r\n' % self.nick) If you don't, the interpreter will bomb on trying to concatenate the return value for "write" (an integer) with the string self.nick. Hope this helps... Jonathon jjbutler88 at gmail.com wrote: > I am trying to write a simple python IRC client, roughly following > this guide: http://www.devshed.com/c/a/Python/Python-and-IRC/ > > I have written some code, which uses the same commands as the guide, > but I get this error: > Traceback (most recent call last): > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/threading.py", line 486, in __bootstrap_inner > self.run() > File "pythonirc.py", line 31, in run > self.sock.send('NICK %s\r\n') % self.nick > AttributeError: send > > Here is my code so far: > [code] > #!/usr/bin/env python > > from socket import * > from threading import Thread > import sys > > class IRCBot(Thread): > def __init__(self, host, room, nick, port=6667, ssl=0): > Thread.__init__(self) > self.host = host > self.port = port > self.ssl = ssl > self.room = room > self.nick = nick > self.sock = socket(AF_INET, SOCK_STREAM) > > def run(self): > print "Connecting..." > try: > self.sock.connect((self.host, self.port)) > except: > print "Could not connect to %s" % self.host > sys.exit(1) > if self.ssl: > try: > self.sock = ssl(self.sock) > except: > print "Server does not suport SSL" > sys.exit(1) > > self.sock.send('NICK %s\r\n') % self.nick > self.sock.send('USER PyIRC PyIRC PyIRC :Python IRC\r\n') > self.sock.send('JOIN #%s\r\n') % self.room > while True: > data = self.sock.recv(4096) > if data.find('PING') != -1: > self.sock.send('PONG' + data.split()[1]+'\r\n') > print data > > def close(self): > self.sock.send('PART #%s\r\n') % self.room > self.sock.send('QUIT\r\n') > self.sock.shutdown(SHIT_RDWR) > self.sock.close() > > IRCBot('irc.psych0tik.net','hbh', 'pythonircclient',6697,1).start() > [/code] > > Anyone know why it might be doing this? Config problem? > > Thanks in advance, > Jon > > -- > http://mail.python.org/mailman/listinfo/python-list > > From bkasterm at gmail.com Thu Jul 10 09:19:38 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Thu, 10 Jul 2008 08:19:38 -0500 Subject: Changing self: if self is a tree how to set to a different self Message-ID: I am playing with some trees. In one of the procedures I wrote for this I am trying to change self to a different tree. A tree here has four members (val/type/left/right). I found that self = SS does not work; I have to write self.val = SS.val and the same for the other members (as shown below). Is there a better way to do this? In the below self is part of a parse tree, F is the parse tree of a function f with argument x. If a node in the parse tree is labelled f, we should replace it by the parse tree for the function f, F, with the remainder of the tree substituted for the input variable for the function f, here x. def elimF (self): if self.val == "f": SS = F.copy () SS.subst ('x', self.left) self.val = SS.val # from here: set self to be SS self.type = SS.type self.left = SS.left self.right = SS.right # completed: set self to be SS if self.left != None: # iterate onward, inf recursion if f # appears. Would need a check in # real version self.left.elimF () if self.right != None: self.right.elimF () Best, Bart From jtanis at mdchs.org Sun Jul 20 13:58:11 2008 From: jtanis at mdchs.org (James Tanis) Date: Sun, 20 Jul 2008 13:58:11 -0400 Subject: Web Server In-Reply-To: <1dc5311f-6243-41d4-b5da-78183c9668e4@m44g2000hsc.googlegroups.com> Message-ID: <4498d5b98057018dd1a9c7cae17732a2@portal.mdchs.org> misceverything at gmail.com wrote: > Thanks, Fredrik - that definitely works. Now to get a little greedy - > is there something along those lines that is a bit more secure (i.e. > allows HTTPS, possibly with authentication)? Basically something that > you would feel more comfortable opening up to the Internet.. > > -- > http://mail.python.org/mailman/listinfo/python-list > You can do HTTPS with Twisted, you'll have to learn how to use Twisted which can sometimes be a task in itself. Most everything is pretty easy to learn although I get a little befuddled by the way they handle authentication myself. I personally think it's worth it though, Twisted is a great resource for rapid development of certain types of clients/servers. -- James Tanis Technical Coordinator Monsignor Donovan Catholic High School e: jtanis at mdchs.org From cyberco at gmail.com Sat Jul 19 15:24:59 2008 From: cyberco at gmail.com (Berco Beute) Date: Sat, 19 Jul 2008 12:24:59 -0700 (PDT) Subject: create instance attributes for every method argument Message-ID: <4780837f-a5bc-4071-94d3-28e2f206163e@k30g2000hse.googlegroups.com> I remember reading somewhere how to create an instance attribute for every method argument, but although Google is my friend, I can't seem to find it. This could likely be done way more elegant: ========================= class Test(object): def __init__(self, a, b, c, d, e, f): self.a = a self.b = b self.c = c self.d = d ========================= 2B From semanticist at gmail.com Sun Jul 13 04:14:15 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 04:14:15 -0400 Subject: socket.connect() hangs in SYN_SENT state. In-Reply-To: References: Message-ID: On Sat, Jul 12, 2008 at 11:23 PM, bukzor wrote: > I'm connecting to an apache2 process on the same machine, > for testing. When looking at netstat, the socket is in the SYN_SENT > state, like this: > > $netstat -a -tcp > tcp 0 0 *:www *:* LISTEN 7635/apache2 > tcp 0 1 bukzor:38234 adsl-75-61-84-249.d:www SYN_SENT 9139/python > > Anyone know a general reason this might happen? Even better, a way to > fix it? That socket connection is to a remote machine, not the same one. Your test code works fine for me. The "hang then crash" (and I'm assuming "crash" here means an uncaught exception) just means that your packets are being silently ignored by whatever machine you're actually attempting to connect to. It's possible that your machine has odd DNS settings causing buzkor.hopto.org to resolve to the wrong address. -Miles From lemcoe9 at bellsouth.net Sun Jul 20 17:07:42 2008 From: lemcoe9 at bellsouth.net (David M Lemcoe Jr.) Date: Sun, 20 Jul 2008 21:07:42 +0000 (UTC) Subject: Testing out Newsproxy. Message-ID: Going to see if Newsproxy actually blocks google groups. -=___________________________=- David M Lemcoe Jr. Roswell, Georgia http://www.davidlemcoe.com/ lemcoe9 at bellsouth.net QRZ: KI4YJL AIM: lemcoe9 YIM: lemcoe9 GTalk: ki4yl at gmail.com MSN: lemcoe9 at hotmail.com Xfire: shawtylo1 ICQ: 359114839 Alternate e-mail: lemcoe9.alt at gmail.com -=___________________________=- From ethan at stoneleaf.us Wed Jul 9 16:48:44 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 09 Jul 2008 12:48:44 -0800 Subject: a simple 'for' question In-Reply-To: <48749F60.7030106@umbc.edu> References: <4874017D.2000401@umbc.edu> <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> <487437E6.8010609@umbc.edu> <1215599630.2873.965.camel@localhost.localdomain> <48749F60.7030106@umbc.edu> Message-ID: <4875242C.8020009@stoneleaf.us> Ben Keshet wrote: > it didn't help. it reads the pathway "as is" (see errors for both > tries). It looks like it had the write pathway the first time, but > could not find it because it searched in the path/way instead of in the > path\way. thanks for trying. The form of slash ('\' vs '/') is irrelevant to Python. At least on Windows. > folders= ['1','2','3'] > for x in folders: > print x # print the current folder > filename='Folder/%s/myfile.txt' %[x] ^- brackets not needed > f=open(filename,'r') > > gives: IOError: [Errno 2] No such file or directory: > "Folder/['1']/myfile.txt" > Pay attention to the error message. Do you actually have the file "Folder\['1']\myfile.txt" on your machine? And did you really want brackets and quotes? Is the path located relative to whereever your python script is running from? If it's an absolute path, precede it with a leading slash. As far as the Python question of string substitution, "%s" % var is an appropriate way. Your above code should read: folders = ['1', '2', '3'] for x in folders: print x filename = 'Folder/%s/myfile.txt' % x f = open(filename, 'r') Again, in order for that to work, you *must* have a path/file of 'Folder\1\myfile.txt' existing from the same folder that this code is running from. This is O/S related, not Python related. -- Ethan From Nikolaus at rath.org Thu Jul 31 08:30:19 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Thu, 31 Jul 2008 14:30:19 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> <12072cbe-139a-430f-81aa-b64bc31b43e5@e39g2000hsf.googlegroups.com> Message-ID: <87zlny8cdg.fsf@nokile.rath.org> oj writes: > On Jul 31, 11:37?am, Nikolaus Rath wrote: >> So why does Python distinguish between e.g. the type 'int' and the >> class 'myclass'? Why can't I say that 'int' is a class and 'myclass' >> is a type? > > I might be wrong here, but I think the point is that there is no > distinction. A class (lets call it SomeClass for this example) is an > object of type 'type', and an instance of a class is an object of type > 'SomeClass'. But there seems to be a distinction: >>> class int_class(object): ... pass ... >>> int_class >>> int why doesn't this print >>> class int_class(object): ... pass ... >>> int_class >>> int or >>> class int_class(object): ... pass ... >>> int_class >>> int If there is no distinction, how does the Python interpreter know when to print 'class' and when to print 'type'? Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From larry.bates at websafe.com` Mon Jul 21 12:51:25 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 11:51:25 -0500 Subject: Please recommend a RPC system working with twisted. In-Reply-To: <312040c6-4011-451e-8a45-f982c2e4462f@j1g2000prb.googlegroups.com> References: <312040c6-4011-451e-8a45-f982c2e4462f@j1g2000prb.googlegroups.com> Message-ID: ??? wrote: > Hi all, > > I'm looking for an RPC system working with twisted. > > 1. Binary. I want it run faster than any xml based RPC. > > 2. Bidirectional. Unlike HTTP, on which the client has to poll the > sever for events, the server should "call" the client's method to > notify events. > > 3. C/Python support. Part of the system shall be written in C. > > 4. Could easily integrated with twisted. > > Unfortunately, there seems no such resolution existed. So maybe I > have to give up some requirements. > > --------------------------------------------------------------------------------------------------------------------------- > > It would be wonderful if ICE could integrate with twisted! Twisted Perspective Broker? -Larry From spython01 at gmail.com Tue Jul 22 17:43:10 2008 From: spython01 at gmail.com (Samir) Date: Tue, 22 Jul 2008 14:43:10 -0700 (PDT) Subject: Iterating Through List or Tuple Message-ID: Is there a way to loop or iterate through a list/tuple in such a way that when you reach the end, you start over at the beginning? For example, suppose I define a list "daysOfWeek" such that: >>> daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] If today is Sunday, I can set the variable "day" to today by: >>> i = iter(daysOfWeek) >>> day = i.next() >>> print day sunday If I want to find out the day of the week 2 days from now, then this code works ok: >>> for x in xrange(2): day = i.next() >>> print day tuesday However, when extending my range beyond the number of items in the list, I receive an error. For example, if I want to find out the day of the week 11 days from today, I get this: >>> for x in xrange(11): day = i.next() Traceback (most recent call last): File "", line 1, in for x in xrange(11): day = i.next() StopIteration Is there a way to easily loop through a list or tuple (and starting over at the beginning when reaching the end) without having to resort to an "if" or "while" statement? (My question concerns the more general use of lists and tuples, not necessarily determining days of the week. I know about using "import datetime" and "from calendar import weekday" but thought that using the days of the week would best illustrate my problem.) As always, thanks in advance. Samir From Russ.Paielli at gmail.com Wed Jul 30 23:44:40 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 30 Jul 2008 20:44:40 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> Message-ID: <8892522e-08b6-4506-a25d-c417e6342f3c@v1g2000pra.googlegroups.com> On Jul 30, 8:24 pm, "Russ P." wrote: > On Jul 30, 8:03 pm, Erik Max Francis wrote: > > > Russ P. wrote: > > > The reason I wrote that "it would be nice to be able to write" > > > > if x is not empty: > > > > is that it reads naturally. It was not an actual proposal, and the > > > fact that you took it as such was *your* mistake. > > ... > > > Now read carefully: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! Let > > > me repeat that for you: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! > > > Did you get that, idiot? > > > So people who can read words but not minds are idiots. Go get 'em, tiger! > > I don't know if you can read minds, but you seem to have a lot of > trouble reading words. > > Can you read "it would be nice to be able to write ..."? Can you > understand what it means? Can you understand that it does *not* mean, > "one *should* be able to write ..."? > > The really significant question here is why I waste my valuable time > with pedants like you. Folks, I'm sorry for being so harsh here. But this guy keeps insisting that I dispayed a "fundamental lack of understanding" of the correct usage of "is" in Python. If that were true, I would have gladly admitted it and dropped the matter. But it is completely false. The simple fact is that I fully understood how "is" works in Python from the first time I read about it -- as I'm sure most others here did too. It just gets my goat that someone would latch onto some whimsical suggestion I wrote to try to prove otherwise. He did not need to play that silly little game, and he could have easily avoided my insults had he not played it. From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 09:16:31 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 15:16:31 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <48889ca7$0$10455$426a34cc@news.free.fr> Lawrence D'Oliveiro a ?crit : > In message > <52404933-ce08-4dc1-a558-935bbbae779b at r35g2000prm.googlegroups.com>, Jordan > wrote: > >> Except when it comes to Classes. I added some classes to code that had >> previously just been functions, and you know what I did - or rather, >> forgot to do? Put in the 'self'. In front of some of the variable >> accesses, but more noticably, at the start of *every single method >> argument list.* > > The reason is quite simple. Python is not truly an "object-oriented" > language. Oh yes ? What's missing exactly ? You have objects that have an id, state and behaviour, and you have a message-passing mechanism. You meant "Python is not truly a mainstream class-based language", I think. > It's sufficiently close to fool those accustomed to OO ways of > doing things, s/OO/class-based/ > but it doesn't force you to do things that way. You still > have the choice. An implicit "self" would take away that choice. It's not even a question of OO/non-OO. An implicit "self" would take away some things that makes Python's *object* model so powerful. From lemcoe9 at bellsouth.net Sat Jul 19 11:05:55 2008 From: lemcoe9 at bellsouth.net (David M Lemcoe Jr.) Date: Sat, 19 Jul 2008 15:05:55 +0000 (UTC) Subject: Question References: Message-ID: Hello perl_wizard at manx.net, No language is better than another because Python is not intended for the same uses and/or people. Your question has no place here. David -=___________________________=- David M Lemcoe Jr. Roswell, Georgia http://www.davidlemcoe.com/ lemcoe9 at bellsouth.net QRZ: KI4YJL AIM: lemcoe9 YIM: lemcoe9 GTalk: ki4yl at gmail.com MSN: lemcoe9 at hotmail.com Xfire: shawtylo1 ICQ: 359114839 Alternate e-mail: lemcoe9.alt at gmail.com -=___________________________=- > Why is Perl so much better than python? > From kay.schluehr at gmx.net Thu Jul 31 17:19:32 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 31 Jul 2008 14:19:32 -0700 (PDT) Subject: Non Continuous Subsequences References: Message-ID: <650df4ae-2f63-4428-b780-3f7045164690@p25g2000hsf.googlegroups.com> Here is an evil imperative, non-recursive generator: def ncsub(seq): n = len(seq) R = xrange(n+1) for i in xrange(1,2**n): S = [] nc = False for j in R: k = i>>j if k == 0: if nc: yield S break elif k%2 == 1: S.append(seq[j]) elif S: nc = True And here is a cython version without yield expression which won't work with cython: def ncsub(seq): n = len(seq) cdef int i,j,k,nc res = [] R = xrange(n+1) for i in xrange(1,2**n): S = [] nc = False for j in R: k = i>>j if k == 0: if nc: res.append(S) break elif k%2 == 1: S.append(seq[j]) elif S: nc = True return res Application: list(ncsub(range(19))) On my 1.5GHz notebook your original version needed 11.2s ( psyco version = 9.5s), my pure Python generator got it in 7.75s and the cython version in 2.3s. [Yes, I have too much time...] From babacity2 at gmail.com Thu Jul 24 16:57:31 2008 From: babacity2 at gmail.com (babacity2 at gmail.com) Date: Thu, 24 Jul 2008 13:57:31 -0700 (PDT) Subject: Efukt com - Amazing porn video collection Message-ID: <86db5004-3bdb-461a-8ece-59406fae30ba@u36g2000pro.googlegroups.com> efukt com . >>>>>>>>>>Best Collection of Efukt Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE efukt com VIDEOS<<<<<<<<<<< . efukt com From tjreedy at udel.edu Sat Jul 5 18:27:23 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 05 Jul 2008 18:27:23 -0400 Subject: pythoncom InternetExplorer.Application don't work in vista || firefox pythoncom ? In-Reply-To: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> References: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> Message-ID: gcmartijn at gmail.com wrote: > H! > > I using a script that opens a internet page in a small window (what I > can control) > In XP everything was working fine, but now I'm using Vista with IE7 > and this is what happends now: > > First a small window opens at the postion x0 y0 (like I want) but then > IE thinks "Hey lets open a other main window too". > And that window opens the url 'http://www.google.nl' Perhaps on XP you changed the IE homepage to about:blank. On your Vista machine, it is set to Google, perhaps by the manufacturer (for a fee). Try changing it. From barun.saha04 at gmail.com Wed Jul 23 09:01:20 2008 From: barun.saha04 at gmail.com (barun.saha04 at gmail.com) Date: Wed, 23 Jul 2008 06:01:20 -0700 (PDT) Subject: Problem with Python Server Pages (PSP) References: <9766b993-03e6-4b75-92a2-06244c41e51c@a1g2000hsb.googlegroups.com> Message-ID: On Jul 22, 5:36 pm, "Sebastian \"lunar\" Wiesner" wrote: > barun.sah... at gmail.com : > > > Hi, > > > I am facing a very basic problem with PSP. I have installed mod_python > > (in fedora Core 1), added the lines required for loading Python > > modules and handling PSP pages. I have created a hello.psp page. But > > when I try to view this hello.psp page, all Python code are getting > > displayed. > > Not directly related to this issue, but I wouldn't start developing with > PSP. Modern web development is better done with a WSGI compatible > framework like Django ... > > -- > Freedom is always the freedom of dissenters. > (Rosa Luxemburg) Thanks to all. But can someone suggest me what the possible cause/ solution for this behaviour could be? From bblais at bryant.edu Wed Jul 30 11:13:04 2008 From: bblais at bryant.edu (Brian Blais) Date: Wed, 30 Jul 2008 11:13:04 -0400 Subject: Pointers/References in Python? In-Reply-To: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> References: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Message-ID: On Jul 30, 2008, at 10:46 , boblatest at googlemail.com wrote: > Of course I can just build those lists naively by creating copies of > the original list and then sorting them according to my wishes. But > that would create huge memory overhead. If the list itself is not memory intensive, but only the objects, then you shouldn't have to worry. For example, In [1]:big_object=[0.0]*int(1e7) # about 40 meg In [2]:big_object2=[0.0]*int(1e7) # another 40 meg In [3]:list1=[big_object,big_object2] # maybe a few bytes more, but no copy In [4]:list2=[big_object2,big_object] # maybe a few bytes more, but no copy after this, my python process takes about 80 meg. names like big_object are just names, and they reference an object in memory. if you say a=big_object, you are saying that the name "a" should also reference that same object. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From 4564 at 755189.45 Mon Jul 28 10:48:09 2008 From: 4564 at 755189.45 (Enrico) Date: Mon, 28 Jul 2008 16:48:09 +0200 Subject: multiple inheritance and __getattr__ Message-ID: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> Hi there, I have the following situation (I tryed to minimize the code to concentrate on the issue): >>> class A(object): def __getattr__(self, name): print 'A.__getattr__' if name == 'a': return 1 raise AttributeError('%s not found in A' % name) >>> class B(object): def __getattr__(self, name): print 'B.__getattr__' if name == 'b': return 1 raise AttributeError('%s not found in B' % name) Both classes have a __getattr__ method. Now I want to have a class that inherits from both so I write: >>> class C(B,A): pass The problem arise when I try something like this: >>> c=C() >>> c.a A.__getattr__ 1 >>> c.b A.__getattr__ Traceback (most recent call last): File "", line 1, in c.b File "", line 5, in __getattr__ raise AttributeError('%s not found in A' % name) AttributeError: b not found in A I was expecting, after a fail in A.__getattr__, a call to the __getattr__ method of B but it seems that after A.__getattr__ fails the exception stops the flow. So, if I did understand well, B.__getattr__ will be never called "automatically". I don't know if this has a reason, if it is a design choice or what else, any explanation is welcome. Since A and B are not written by me I can only work on C. The solution that comes to my mind is to define a __getattr__ also in C and write something like: >>> class C(A,B): def __getattr__(self, name): try: return A.__getattr__(self, name) except AttributeError: return B.__getattr__(self, name) >>> c=C() >>> c.a A.__getattr__ 1 >>> c.b A.__getattr__ B.__getattr__ 1 A better solution is welcome. Many thanks, Enrico From kay.schluehr at gmx.net Sat Jul 19 12:59:23 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 19 Jul 2008 09:59:23 -0700 (PDT) Subject: Best Python packages? References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> <17861f55-8ad1-4703-ad22-838675f2afc4@w1g2000prk.googlegroups.com> Message-ID: <86b446d2-0d11-4410-bf89-a2a05fac81b2@s50g2000hsb.googlegroups.com> On 18 Jul., 12:23, Ben Sizer wrote: > On Jul 16, 3:31 pm, Fredrik Lundh wrote: > > > Ben Sizer wrote: > > > make my development a lot easier. > > > Knowing what kind of development you do might help, of course. Some > > libraries are excellent in some contexts and suck badly in others... > > Sure. Mostly I'm just interested in what's out there though. In C++ > you have Boost which everybody knows are a source of high quality > libraries, covering a fairly wide set of applications. Obviously > that's more low-level and less application specific, and the Python > standard libs do pretty much everything that is in Boost, but it's > that sort of peer-reviewed and widely-applicable list that I'd like to > see. > > I (attempt to) use TurboGears for web development and that depends on > a whole bunch of libraries - SQLObject, PyProtocols, RuleDispatch, > SimpleJson, FormEncode, etc - and I would never have heard of these if > TurboGears' exposure of its internals wasn't so common. Some of these > are web-specific but some are not. And I'd never know to look for them > specificially, because in many cases it wouldn't occur to me that they > exist. (eg. Object-Relational Mappers like SQLObject may be obvious if > you come from certain areas of IT, but I'd never heard of them before > I started with TurboGears.) > > For what it's worth, my main areas of interest are gaming, multimedia, > and web development. But I just like to hear about anything that > people might use which makes their life a lot easier and which perhaps > is not application specific - like ORMs or something similar. > > > Looking at things that larger projects and distributions use can also be > > a good idea. For example, if you're doing scientific stuff, go directly > > to enthought.com. If you're doing web stuff, look at the libraries big > > Django applications use. Etc. > > Sadly, I know just as little about what major applications are out > there as I do about what libraries are out there! > > -- > Ben Sizer In the original post you asked for "hidden gems" and now it seems you just want to know about Madonna or Justin Timberlake. Maybe a look on this collection helps http://wiki.python.org/moin/UsefulModules From mal at egenix.com Thu Jul 31 06:20:00 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 31 Jul 2008 12:20:00 +0200 Subject: Interbase In-Reply-To: References: Message-ID: <489191D0.40104@egenix.com> On 2008-07-30 18:49, Mike Hjorleifsson wrote: > Has anyone gotten python working with Interbase database platform ? I > need to query some info from an interbase database on another server > need a lil help getting started. You could try the EasySoft ODBC driver for InterBase: http://www.easysoft.com/products/data_access/odbc_interbase_driver/index.html together with our mxODBC interface for Python: http://www.egenix.com/products/python/mxODBC/ -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 31 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From israelu at elbit.co.il Tue Jul 29 02:41:51 2008 From: israelu at elbit.co.il (iu2) Date: Mon, 28 Jul 2008 23:41:51 -0700 (PDT) Subject: seemingly simple list indexing problem References: <5c118411-5703-44b3-888f-3785b517b8d4@u12g2000prd.googlegroups.com> Message-ID: <46b0becc-2f24-41de-a9e5-3013c6089d24@8g2000hse.googlegroups.com> On Jul 29, 3:59?am, John Machin wrote: > On Jul 29, 8:10 am, John Krukoff wrote: > > > > > > > On Mon, 2008-07-28 at 16:24 -0500, Ervan Ensis wrote: > > > My programming skills are pretty rusty and I'm just learning Python so > > > this problem is giving me trouble. > > > > I have a list like [108, 58, 68]. ?I want to return the sorted indices > > > of these items in the same order as the original list. ?So I should > > > return [2, 0, 1] > > > > For a list that's already in order, I'll just return the indices, i.e. > > > [56, 66, 76] should return [0, 1, 2] > > > > Any help would be appreciated. > > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > If your lists aren't so large that memory is an issue, this might be a > > good place for a variation of decorate, sort, undecorate. > > > >>> listToSort = [ 108, 58, 68 ] > > >>> decorated = [ ( data, index ) for index, data in > > > enumerate( listToSort ) ]>>> decorated > > > [(108, 0), (58, 1), (68, 2)]>>> result = [ None, ] * len( listToSort ) > > >>> for sortedIndex, ( ignoredValue, originalIndex ) in > > > enumerate( sorted( decorated ) ): > > ... ? ? result[ originalIndex ] = sortedIndex > > ...>>> result > > > [2, 0, 1] > > Simpliciter: > > > > >>> data = [99, 88, 77, 88, 66] > >>> [x[1] for x in sorted(zip(data, xrange(len(data))))] > [4, 2, 1, 3, 0] > > Use case? Think data == database table, result == index ...- Hide quoted text - > > - Show quoted text - I think it is wrong, using this on my data returns the wrong result data = [108, 58, 68, 108] >>> [x[1] for x in sorted(zip(data, xrange(len(data))))] [1, 2, 0, 3] From bruno.42.desthuilliers at websiteburo.invalid Fri Jul 11 08:28:17 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 11 Jul 2008 14:28:17 +0200 Subject: strip() using strings instead of chars In-Reply-To: References: Message-ID: <487751a6$0$29402$426a74cc@news.free.fr> Christoph Zwerschke a ?crit : > In Python programs, you will quite frequently find code like the > following for removing a certain prefix from a string: > > if url.startswith('http://'): > url = url[7:] DRY/SPOT violation. Should be written as : prefix = 'http://' if url.startswith(prefix): url = url[len(prefix):] (snip) > My problem with this is that it's cumbersome and error prone to count > the number of chars of the prefix or suffix. cf above > If you want to change it > from 'http://' to 'https://', you must not forget to change the 7 to 8. > If you write len('http://') instead of the 7, you see this is actually > a DRY problem. cf above > Things get even worse if you have several prefixes to consider: > > if url.startswith('http://'): > url = url[7:] > elif url.startswith('https://'): > url = url[8:] > > You can't take use of url.startswith(('http://', 'https://')) here. for prefix in ('http://', 'https://'): if url.startswith(prefix): url = url[len(prefix):] break For most complex use case, you may want to consider regexps, specifically re.sub: >>> import re >>> pat = re.compile(r"(^https?://|\.txt$)") >>> urls = ['http://toto.com', 'https://titi.com', 'tutu.com', 'file://tata.txt'] >>> [pat.sub('', u) for u in urls] ['toto.com', 'titi.com', 'tutu.com', 'file://tata'] Not to dismiss your suggestion, but I thought you might like to know how to solve your problem with what's currently available !-) From mail at timgolden.me.uk Tue Jul 29 09:40:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 29 Jul 2008 14:40:03 +0100 Subject: Windows Interpreter In-Reply-To: <4dc0cfea0807290626p4b05376en49ccb18f0e1eb4bb@mail.gmail.com> References: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> <488F1745.4020705@timgolden.me.uk> <4dc0cfea0807290626p4b05376en49ccb18f0e1eb4bb@mail.gmail.com> Message-ID: <488F1DB3.4010608@timgolden.me.uk> Victor Subervi wrote: > def a(): > chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', > '\\yz'] > rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like > the Beast? Who can wage war against him?\par' > for char in chars: > c = '(?<=' + char + ')' > test = re.search(c, rtf_markup) > try: > junk = test.group(0) > print char > except: > pass > > Now, I can paste that entire fn in linux. But in windows I have to paste > it line_by_line. Pain in butt! And it indents automatically. How change > that behavior. Well, I'm not really sure what to say. I've just copied that whole section with drag-mouse, Ctrl-C. I then opened a new interpreter window (effectively, Start > Run > python) and right-clicked over the window. At this point, the lines I copied were copied in and the function accepted by the interpreter. I do have QuickEdit on by default in all by console windows, but the only difference I expect that to make is that you'd otherwise have to use the window's System Menu (Alt-Space, Edit, Paste). TJG From digetl.try at gmail.com Sat Jul 26 06:01:58 2008 From: digetl.try at gmail.com (raja) Date: Sat, 26 Jul 2008 03:01:58 -0700 (PDT) Subject: Weinhaus Weiler Message-ID: <2e8f47b7-b657-44c3-8d4b-2a2db427a7e8@w39g2000prb.googlegroups.com> Historical half-timbered house with excellent cuisine in Oberwesel http://food-drinks.page.tl/ From gagsl-py2 at yahoo.com.ar Tue Jul 29 22:48:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Jul 2008 23:48:47 -0300 Subject: I CAN connect socket to any localhost port but I shouldn't be able to References: <13c78fbf-751f-4d70-a012-53aa1eb64e53@79g2000hsk.googlegroups.com> Message-ID: En Tue, 29 Jul 2008 14:56:08 -0300, qvx escribi?: > I don't have server listening on port 8084 but I can open socket to it > (and to many other ports, tested for all<8000) Your example fails -as expected- on my PC running Python 2.5.2 + Windows XP SP2. It may be something specific to your setup or your platform. py> test(8084) Traceback (most recent call last): File "", line 1, in File "", line 5, in test File "", line 1, in connect socket.error: (10061, 'Connection refused') -- Gabriel Genellina From kyosohma at gmail.com Mon Jul 7 13:30:27 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 7 Jul 2008 10:30:27 -0700 (PDT) Subject: VNC capture in python References: Message-ID: On Jul 6, 11:12?pm, Astan Chee wrote: > Hi, > I was wondering if I can do a capture of a VNC screen in python. Kinda > like this http://search.cpan.org/~lbrocard/Net-VNC-0.35/lib/Net/VNC.pm > but without opening a VNC window or doing a screen capture. > Thanks for any suggestions > > -- > "Formulations of number theory: Complete, Consistent, Non-trivial. Choose two." > > Animal Logichttp://www.animallogic.com > How can you do a screen capture without doing a screen capture? You'll probably have to use some kind of automation techniques, SendKeys, and/ or the subprocess module. If you can find a VNC program that has a COM interface, then you may be able to use Python's win32com module, which is a part of the win32 package. Mike From orsenthil at gmail.com Fri Jul 4 20:57:18 2008 From: orsenthil at gmail.com (Phoe6) Date: Fri, 4 Jul 2008 17:57:18 -0700 (PDT) Subject: caseless dict - questions Message-ID: <77798300-820f-4175-a9cb-aef639d42a32@m45g2000hsb.googlegroups.com> I have a requirement for using caseless dict. I searched the web for many different implementations and found one snippet which was implemented in minimal and useful way. ############# import UserDict class CaseInsensitiveDict(dict, UserDict.DictMixin): def __init__(self, *args, **kwargs): self.orig = {} super(CaseInsensitiveDict, self).__init__(*args, **kwargs) def items(self): keys = dict.keys(self) values = dict.values(self) return [(self.orig[k],v) for k in keys for v in values] def __setitem__(self, k, v): hash_val = hash(k.lower()) self.orig[hash_val] = k dict.__setitem__(self, hash_val, v) def __getitem__(self, k): return dict.__getitem__(self, hash(k.lower())) obj = CaseInsensitiveDict() obj['Name'] = 'senthil' print obj print obj.items() obj1 = {} obj1['Name'] = 'senthil' print obj1 print obj1.items() ########### [ors at goofy python]$ python cid1.py {15034981: 'senthil'} [('Name', 'senthil')] {'Name': 'senthil'} [('Name', 'senthil')] --- The difference between the Caselessdict and {} is that when called as the object, the Caselessdict() is giving me the internal representation. obj = CaseInsensitiveDict() obj['Name'] = 'senthil' print obj gives: {15034981: 'senthil'} obj1 = {} obj1['Name'] = 'senthil' print obj1 Correctly gives {'Name': 'senthil'} What changes should I make to CaseInsensitiveDict ( written above), so that its instance gives the actual dictionary instead of its internal representation. Constructing a dictionary and returning from __init__ method did not work. TIA, Senthil From alexnbryan at gmail.com Sat Jul 12 15:47:01 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sat, 12 Jul 2008 12:47:01 -0700 (PDT) Subject: Help with BeautifulSoup Message-ID: <18423003.post@talk.nabble.com> Michiel Overtoom wrote: > > Alex wrote... >> >>Okay, heres the general idea of the html I have to work with: >> >>
>> noun >> >>
>>
>>
>> verb >>
>>
>>
>> >> >>Okay, I left off some stuff. > > I wish you didn't, or at least provided an URL where I can get the page > which you are trying to parse. Now I don't have a valid testcase to > tinker > with. And maybe you can also show your code which you already came up > with. > > >> I can easily get the tables but it is the span's than I am having trouble > with. > > I can't see any SPAN tags in the example you provided. > > Greetings, > > -- > "The ability of the OSS process to collect and harness > the collective IQ of thousands of individuals across > the Internet is simply amazing." - Vinod Vallopillil > http://www.catb.org/~esr/halloween/halloween4.html > > -- > http://mail.python.org/mailman/listinfo/python-list > > Oh, well sorry, I wrote the span tags, but they didn't show up. But it was around the noun. Here is the code I have to get the definitions alone: import urllib from BeautifulSoup import BeautifulSoup class defWord: def __init__(self, word): self.word = word def get_defs(term): soup = BeautifulSoup(urllib.urlopen('http://dictionary.reference.com/search?q=%s' % term)) for tabs in soup.findAll('table', {'class': 'luna-Ent'}): yield tabs.findAll('td')[-1].contents[0].string self.mainList = list(get_defs(self.word)) Theres a bit more to it, but it doesn't matter here, and so if you look I am using dictionary.com as the website. If you look at the html, the "" tags are where the type of the word is and that is what I need, in order. Or if I can figure out how many
tags are inbetween each "" tag, that too would work. This is the type the code I am talking about if it helps: ?noun
1. the curd of milk separated from the whey and prepared in many ways as a food.
2. a definite mass of this substance, often in the shape of a wheel or cylinder.
?verb (used without object)
9.
?verb (used with object) If you need anything else, feel free to ask! -- View this message in context: http://www.nabble.com/Re%3A-Help-with-BeautifulSoup-tp18418004p18423003.html Sent from the Python - python-list mailing list archive at Nabble.com. From gagsl-py2 at yahoo.com.ar Fri Jul 11 23:51:13 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 12 Jul 2008 00:51:13 -0300 Subject: Pickle and wx.TextCtrl References: Message-ID: En Fri, 11 Jul 2008 10:15:36 -0300, escribi?: > Trying to read a pickled filed and list contents. > > The attached program works using pprint, but I want to write to my frame. > WriteText only produces half of the records. > What is happening? What do you mean by "only produces half of the records"? Probably your problem has nothing to do with a TextCtrl - ensure you can save and load your data with a simple, console-based script, and only then write the GUI. The way you read the file is rather strange -mixing calls to readline and pickle.load- I'd write the data using pickle.dump calls *only* and then read it using pickle.load calls *only*. -- Gabriel Genellina From pavlovevidence at gmail.com Sat Jul 26 03:51:00 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 26 Jul 2008 00:51:00 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> Message-ID: On Jul 24, 4:11?am, Jordan wrote: > Of course not. > > I just think Explicit is better than Implicit is taken seriously by a > large segment the Python community as a guiding principle, Yeah, try telling that to the people who advise writing "if x" instead of "if x==0", or "if s" instead of "if len(s)==0". Carl Banks From basti.wiesner at gmx.net Thu Jul 10 12:34:25 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Thu, 10 Jul 2008 18:34:25 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <6deq2uF21vo2U1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch : > On Mon, 07 Jul 2008 16:44:22 +0200, Sebastian \"lunar\" Wiesner wrote: > >> Mark Wooding : >> >>> Sebastian "lunar" Wiesner wrote: >>> >>>> # perl -e '("a" x 100000) =~ /^(ab?)*$/;' >>>> zsh: segmentation fault perl -e '("a" x 100000) =~ /^(ab?)*$/;' >>> >>> (Did you really run that as root?) >> >> How come, that you think so? > > The '#' is usually the prompt of root accounts while ordinary users get a > '$'. Oh ... I just used "#" as a general placeholder, because I didn't want to copy my whole two-line prompt ;) I can assure, that I did not try this as root ;) and will use "$" in future ;) -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From snowballz.game at gmail.com Fri Jul 18 17:38:21 2008 From: snowballz.game at gmail.com (Michael Lubker) Date: Fri, 18 Jul 2008 14:38:21 -0700 (PDT) Subject: Any Game Developers here? Message-ID: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Any people that use Python as the predominant language for their game development here? ~Michael From bdesth.quelquechose at free.quelquepart.fr Sat Jul 19 06:12:38 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 19 Jul 2008 12:12:38 +0200 Subject: Question In-Reply-To: References: Message-ID: <4881da0e$0$11232$426a74cc@news.free.fr> Peter Otten a ?crit : > perl_wizard at manx.net wrote: > >> Why is Perl so much better than python? > > Because you have the video: > > http://mail.python.org/pipermail/python-list/2004-March/253370.html > KEYBOARD !-) From carsten.haese at gmail.com Thu Jul 31 13:31:55 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Thu, 31 Jul 2008 13:31:55 -0400 Subject: Function References In-Reply-To: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> Message-ID: squishywaffle at gmail.com wrote: > Greetings, > > I'm trying to wrap a function in a C library as a compiled C Python > module. Everything is going great, but I've hit a snag. There's a > function in the form of this: > > First the typedef: > typedef void(*FPtr_DeviceMessageHandler) (const DeviceMessage, const > char*); > > Then the actual function prototype: > FPtr_DeviceMessageHandler > RegisterDeviceMessageHandler(FPtr_DeviceMessageHandler); > [...] > [I] can't figure out how to cast the function reference from Python into > something the C RegisterDevice... function can handle. Mere casting won't do the trick. The function reference from Python is basically just an object that contains byte-code to be executed by the Python Virtual Machine. There is no way you can magically transform that into a C function by casting the Python object pointer to anything. You'll need a write a C function that will call a given Python function, and then you need to supply the pointer to that C function as your DeviceMessageHandler callback function, and somehow communicate to your C function which Python function it should call. Good luck. -- Carsten Haese http://informixdb.sourceforge.net From shandy.b at gmail.com Thu Jul 3 19:18:08 2008 From: shandy.b at gmail.com (shandy.b at gmail.com) Date: Thu, 3 Jul 2008 16:18:08 -0700 (PDT) Subject: Python and timezones References: <66de1777-ab65-4708-904b-3e511409a662@m36g2000hse.googlegroups.com> Message-ID: Nah, it's got to be something more than that. A bunch of them are screwed up. It's showing America/Saskatchewan as UTC-06:59. I think there's something wrong with my code. I've put it up at a pastebin so that it's easier to read. http://pastebin.ca/1061776 On Jul 2, 11:22?am, Mensanator wrote: > On Jul 2, 12:43?am, "shand... at gmail.com" wrote: > > > > > I'm trying to write some code to deal with world timezones, and I'm > > getting a strange result. ?America/Iqaluit should not be showing up in > > UTC+00:00, but it is. ?Can anyone see what's wrong with this code? > > > import time > > from datetime import datetime > > import os > > import pytz > > > def getZoneNamesOnThisComputer(): > > ? ? for i in pytz.all_timezones: > > ? ? ? ? if os.path.exists( os.path.join('/tmp/usr/share/zoneinfo/', > > i)): > > ? ? ? ? ? ? yield i > > > def getZonesGroupedByOffset(): > > ? ? '''return a dict of all the zone names , grouped by their offset > > ? ? eg: > > ? ? {'-0400': ['America/Blanc-Sablon', 'Etc/GMT+4'], > > ? ? ?'+0000': ['America/Iqaluit', 'Etc/GMT', 'Europe/Belfast', 'GB', > > 'GMT'], > > ? ? ?... > > ? ? } > > ? ? ''' > > ? ? Y,M,D,h,m,s = time.localtime()[:6] > > > ? ? zonesGroupedByOffset = {} > > > ? ? for name in getZoneNamesOnThisComputer(): > > ? ? ? ? tz = pytz.timezone(name) > > ? ? ? ? now = datetime(Y,M,D,h,m,s, tzinfo=tz) > > ? ? ? ? # strfime returns a string like "-0800" or "+0430" or "0000" > > ? ? ? ? offsetKey = now.strftime('%z') > > ? ? ? ? if not zonesGroupedByOffset.has_key(offsetKey): > > ? ? ? ? ? ? zonesGroupedByOffset[offsetKey] = [] > > ? ? ? ? zonesGroupedByOffset[offsetKey].append(name) > > ? ? return zonesGroupedByOffset > > > z = getZonesGroupedByOffset() > > print z['+0000'] > > > # Why is America/Iqaluit showing up here??? > > The database contains an error. Shit happens, deal with it. From xdicry at gmail.com Mon Jul 7 09:40:50 2008 From: xdicry at gmail.com (Evan) Date: Mon, 7 Jul 2008 06:40:50 -0700 (PDT) Subject: Is there a good way to implement file updating? such as lock, update, reload... References: <2ebcf7f9-a8d9-403f-a05a-f26a9ca420b0@x41g2000hsb.googlegroups.com> <6deef6F271g5U1@mid.uni-berlin.de> Message-ID: If I get rid of the XML, I have to change my script more and more, it is not easy to do that. :( :( Thanks, From egbert.bouwman at hccnet.nl Wed Jul 9 17:08:22 2008 From: egbert.bouwman at hccnet.nl (egbert) Date: Wed, 9 Jul 2008 23:08:22 +0200 Subject: formatting list -> comma separated (slightly different) In-Reply-To: <2.2.32.20080709202533.01137964@pop.xs4all.nl> References: <2.2.32.20080709202533.01137964@pop.xs4all.nl> Message-ID: <20080709210822.GA28498@hccnet.nl> On Wed, Jul 09, 2008 at 10:25:33PM +0200, Michiel Overtoom wrote: > Formatting a sequence of items such that they are separated by > commas, except the last item, which is separated by the word 'and'. > > For example: > > Three friends have a dinner: Anne, Bob and Chris row = ["Anne","Bob","Chris"] txt = ", ".join(row) pos = txt.rfind(", ") new = "%s and %s" % (txt[0:pos], txt[pos+2:]) egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From hat at se-162.se.wtb.tue.nl Thu Jul 10 10:10:32 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 10 Jul 2008 16:10:32 +0200 Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: Python doesn't use value semantics for variables but reference semantics: a = [1] b = a In many languages, you'd now have 2 lists. In Python you still have one list, and both a and b refer to it. Now if you modify the data (the list), both variables will change a.append(2) # in-place modification of the list print b # will print [1,2] If you don't want this, you should make a copy somewhere a = a + [2] or b = a[:] It takes a bit of getting used to, but it is very handy in practice. Read the docs about 'immutable' and 'mutable' types. (I expected this to be a FAQ, but I couldn't quickly find a matching entry) Albert From mensanator at aol.com Thu Jul 3 23:10:14 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 3 Jul 2008 20:10:14 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> Message-ID: <3f59ead2-1fd2-4fee-a5fd-06147d48d086@e53g2000hsa.googlegroups.com> On Jul 3, 8:10?pm, casevh wrote: > On Jul 3, 6:54?am, Mensanator wrote: > > > > > Well, it will be great at some point in the future > > when Python 2.6/3.0 have actually been released and > > third party extensions such as gmpy have caught up. > > > Until then, such solutions are worthless, i.e., of > > no value. > > gmpy is supported on Python 2.6. A new version and Windows binaries > were released shortly after 2.6b1 was released. Great! Looks like I'll be installing 2.6 this weekend. > > casevh From hubaghdadi at gmail.com Mon Jul 28 08:07:54 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Mon, 28 Jul 2008 05:07:54 -0700 (PDT) Subject: Module clarification References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> <896c547e-9fa1-4f84-8c9b-53a96e70246c@y21g2000hsf.googlegroups.com> Message-ID: <00c033b9-1b5a-4165-abec-4ff6119298a5@z66g2000hsc.googlegroups.com> On Jul 28, 6:55 am, Floris Bruynooghe wrote: > On Jul 28, 9:54 am, Hussein B wrote: > > > Hi. > > I'm a Java guy and I'm playing around Python these days... > > In Java, we organize our classes into packages and then jarring the > > packages into JAR files. > > What are modules in Python? > > An importable or runable (i.e. script) collection of classes, > functions, variables etc... > > > What is the equivalent of modules in Java? > > Don't know. Not even sure if it exists, but my Java is old and never > been great. > > > Please correct me if I'm wrong: > > I saved my Python code under the file Wow.py > > Wow.py is now a module and I can use it in other Python code: > > import Wow > > Indeed, you can now access things defined in Wow as Wow.foo > > Regards > Floris If I have a couple of modules, is there a way to package them? or there is no such a thing in Python? From usenet at janc.be Tue Jul 15 15:00:47 2008 From: usenet at janc.be (Jan Claeys) Date: Tue, 15 Jul 2008 19:00:47 GMT Subject: Python internals References: <008ca729$0$20313$c3e8da3@news.astraweb.com> Message-ID: Op Tue, 15 Jul 2008 09:29:58 -0500, schreef Larry Bates: > Names are pointers in Python that point to values in memory. But "pointers" doesn't have the same meaning as in "C" here. Memory in Python is not (necessarily) an "array of bytes"; how & where the values are stored in "physical memory" at any time during the lifetime of an object is an implementation detail. Maybe you can compare it to how a (university) library works: you ask a librarian for a book named "The Taste Of Man by Slavenka Draculi?" and they fetch it for you, using whatever internal classification/retrieval system they use. -- JanC From enleverlesX.XmcX at XmclaveauX.com Sun Jul 6 02:10:12 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sun, 6 Jul 2008 08:10:12 +0200 Subject: Python with Ecmascript In-Reply-To: References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com><486fe241$0$867$ba4acef3@news.orange.fr> Message-ID: <48706543$1$860$ba4acef3@news.orange.fr> Hi! > Is there a way to do similar things on linux? I think no. Because these tech use COM. And COM don't exist under xxnux. But: - look if XPCOM, or dBus) can help you - search with the word "MOZLAB", who work a solution (plugin) for drive Firefox, from an external software. Good luck! -- Michel Claveau From __peter__ at web.de Fri Jul 4 08:36:52 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Jul 2008 14:36:52 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: Henning_Thornblad wrote: > What can be the cause of the large difference between re.search and > grep? grep uses a smarter algorithm ;) > This script takes about 5 min to run on my computer: > #!/usr/bin/env python > import re > > row="" > for a in range(156000): > row+="a" > print re.search('[^ "=]*/',row) > > > While doing a simple grep: > grep '[^ "=]*/' input (input contains 156.000 a in > one row) > doesn't even take a second. > > Is this a bug in python? You could call this a performance bug, but it's not common enough in real code to get the necessary brain cycles from the core developers. So you can either write a patch yourself or use a workaround. re.search('[^ "=]*/', row) if "/" in row else None might be good enough. Peter From noagbodjivictor at gmail.com Mon Jul 14 06:18:06 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Mon, 14 Jul 2008 06:18:06 -0400 Subject: Simple Image Cropper Message-ID: >Hi, > >I am designing a simple image cropper which simply takes an image and use PIL > to do the cropping.Now in order to do the cropping I simply draw a rectangle on > the image by dragging the mouse over the image.I then use button press and > button release events to find the mouse postition and send across the tuple to PIL. > Everything works fine but what I need is a way to show the user a dotted rectangle > as he drags across the mouse as in every other standard image editor. I have learnt > that using gnomecanvas will do that but given my time constraints and the lack of a > tutorial on pygtk ,I used gtk.image + event box to do the above. > >Can someone point to using gnomecanvas in the following directions: >1.Load an image into the canvas from file as well as pixbuf. >2.Draw a dotted rectangle >3.Fire and capture mouse events >4.Use PIL >I basically want to know about point 2. Also,will implementing cairo be easy on glade and pygtk? > >Regards, >Abhishek Hello, first of all I have no knowledge of pygtk. But after some googling I have found something that might help you: http://trac.bjourne.webfactional.com/ GtkImageViewer. It also comes with Python bindings. For the crop functionality, check the docs: http://trac.bjourne.webfactional.com/chrome/common/pygtkimageview-docs/ , there is a function ImageToolSelector (http://trac.bjourne.webfactional.com/chrome/common/pygtkimageview-docs/gtkimageview.ImageToolSelector-class.html) that can be customized to make an image cropper. Well, I hope my little finding can help. -- NOAGBODJI Paul Victor From sniipe at gmail.com Fri Jul 18 07:50:01 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Fri, 18 Jul 2008 04:50:01 -0700 (PDT) Subject: https in pylons Message-ID: Hello, I have a question about framework pylons - how to run(in paster) webpages over https? Is it possible, or not? Best regards From robert.rawlins at thinkbluemedia.co.uk Wed Jul 23 12:05:50 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Wed, 23 Jul 2008 17:05:50 +0100 Subject: Get dict value but not as reference. In-Reply-To: <16651e80807230855l745bba66u4c506e9fab5b38fa@mail.gmail.com> References: <4357936148771237039@unknownmsgid> <16651e80807230855l745bba66u4c506e9fab5b38fa@mail.gmail.com> Message-ID: <008f01c8ecdd$fa158120$ee408360$@rawlins@thinkbluemedia.co.uk> > Use the pop() method of the dictionary, like this: Ah, of course! Pop! I have seen this before I think Jerry, seems to do the trick nicely. Thank you. Robert From torriem at gmail.com Fri Jul 25 01:37:50 2008 From: torriem at gmail.com (Michael Torrie) Date: Thu, 24 Jul 2008 23:37:50 -0600 Subject: Doubt In-Reply-To: References: Message-ID: <488966AE.9040001@gmail.com> You wrote: > How to represent the loop > for ($a = $b; $a<=$c;$a++){ > } in Python As other pointed out, iterating through a list or range is often a far more elegant way to do a loop than a C-style loop. But the C-style for loop is just syntactic sugar for a while loop. In some cases, C-style for loops can have an initializer, a set of conditions, and incrementer parts that are all based on different variables. For example: for (a=begin_func() ; x < 3 and sometest(b) ; i=somefunc() ) This highly illogical and contrived function could not be represented in python with a simple "for x in blah" statement. Rather you have to represent it in its true form, which is a while loop: a=begin_func() while x < 3 and sometest(b): #do stuff #loop body i=somefunc() In fact, the perl/c for loop of the form: for (;;) always translates directly to: while : #loop body From norseman at hughes.net Mon Jul 7 04:03:10 2008 From: norseman at hughes.net (norseman) Date: Mon, 07 Jul 2008 01:03:10 -0700 Subject: How to bypass Windows 'cooking' the I/O? (One more time, please) II Message-ID: <4871CDBE.5050809@hughes.net> I know I saw the answer recently, as in since February '08, but I can't re-find it. :( I tried the mail archives and such and my own collections but the piece I saw still eludes me. Problem: (sos=same old s...) Microsoft insists the world work it's way even when the Microsoft way was proven wrong decades ago. In this case it's (still) 'cooking' the writes even with 'rwb' and O_RDWR|O_BINARY in (proper respective) use. Specific: python created and inspected binary file ends: 00460: 0D 1A (this is correct) after a write os.lseek(target, -1, 2) os.write(target,record) the expected result would be: 00460: 0D 20 .....data bytes.... 1A BUT I get: 00460: 20 .... data bytes... 1A It is one byte off!!! And the 0D has to be there. Signifies the end of the header. Same python program runs as expected in Linux. Maybe because that's where it was written?! :) What I seek is the way to slap Microsoft up side the head and make it work correctly. OK, well, at least in this situation. Note: Things like this justify Python implementers bypassing OS calls (data fetch, data write) and using the BIOS direct. Remember, the CPU understands bit patterns only. It has no comprehension of 'text', 'program', 'number', 'pointer', blah blah blah.... All that is totally beyond it's understanding. A given bit pattern means 'do that'. The CPU is 100% binary. Memory, storage and the rest is just bits-on, bits-off. Patterns. Proper binary I/O is mandatory for the machine to function. Anyway - if whoever mentioned the flags and such to 'over ride' Microsoft's BS would re-send that piece I would be very appreciative. Steve norseman at hughes.net ================================================================== Above is original request. I assume the answer I seek is by someone not receiving the list currently. I'm on and off myself so I can understand. I received two replies the the original request. Both insist on trying to use TEXT modes to do BINARY work. Allow me to explain before hooting and hollering that I'm all wet. Yes - 'rwb' is a typo. The compiler catches it every time I use it. READ as in read only, WRITE as in write only but NOT READ/WRITE in syntax when using STREAM I/O. One is to use r+ for rw and w+ for wr and tack on the b to eliminate the default of 'cooking' the data. File.verb is defined as being --- well a STREAM I/O handler. The docs insist on calling it a file descriptor somehow. Or at least that is the way it reads. Larry's 'fp' (file pointer) is a correct short form. Let's start with Larry: > You may be the victim of buffering (not calling .flush() or .close() > to commit your write to disk). Why aren't you using the file object > to do you seek and write? STREAM things take a great deal of overhead. I'm just reading, re-arranging and writing. (supposedly) Simple buffer stuff. > > Normal file I/O sequence: > > fp = open(target, 'wb') > > fp.seek(-1, 2) > > fp.write(record) > Except it doesn't do that in Windows. See below. > by going through os. methods instead of the file instance I think you > are accessing the file through 2 different I/O buffers. I could be > all wrong here. Nope (on 2 diff...) and You are but I can see where you might think as you do. Tim is my next victim: >>> f = open('x.bat','r+b') >>> >>> s = f.read() >>> >>> s 'sed -e "s/[ \\t]*$//" -e "/^$/d" %1\rhow about that\r\n' >>> >>> f.seek(-1,2) >>> >>> f.write('xxx\r\n') >>> >>> f.close() >>> >>> f = open('x.bat','rb') >>> >>> t = f.read() >>> >>> t 'sed -e "s/[ \\t]*$//" -e "/^$/d" %1\rhow about that\rxxx\r\n' >>> >>> If you put that in a binary file, that file will never work again. If you don't believe me, try it on ntldr and see what happens. (Tim - please don't. Your Window$ system won't boot if you do. Originally ALL STREAM I/O was supposed to 'cook' the stream for 'text' transmission. It has evolved, BUT.... legacy tends to linger.) This is the 'see below' place: concerning seek and write: let: 0123456789 be contents of a file. (offsets zero through nine) File size will be reported as 10 bytes If you seek to EOF and append ABC it will move to OFFSET 10 and put in ABC with a result of 0123456789ABC and report a file size of 13. With offsets it is simple math, quick and efficient. So move filesize minus 3 shifts to byte 10 which has a content of 9 This is correct and this is what Python on Linux does. (How many just got lost? Remember, byte 10 is offset 9) (or offset plus 1 is byte count) using ...seek(-1,2) (be it: os.lseek, file.seek, whatever - don't get dum on me) What Microsoft does is go to EOF and IF it is a hex-1A preceded by a hex-0D it then backs over the hex-0D also. If the last character of the file is a hex-1A and no EOL precedes it, it starts next write on top of hex-1A as it was told. Result: file is shifted left one byte. using ...seek(0,2) (os.lseek, file.seek, whatever - staaayy....) What Microsoft does is go to EOF and IF it is a hex-1A preceded by a line terminator hex-0D it then backs over the hex-1A and starts writing there. If the last character of the file is a hex-1A and no EOL precedes it, it starts next right after the hex-1A. Leaving the 1A in the file. Result: file data shifts one byte right for each record appended having a hex-1A terminator unless the 1A was preceded by a hex-0D. Fun Huh? BOTH CASES occur whichever I/O system is chosen and used. BOTH CASES are unacceptable behavior when the 'b' is added to the file use mode. Once in binary there is supposed to be no bullshit. In the mid 1960's I was updating code written in the early 1950's and my 0-9+ABC thing above was rule then too. Over half a century of legacy. Who's got the 'two by four' to pound Microsoft's nonsense switch into the off position? OK - the hooting and hollering that I'm all wet can start. :) Steve norseman at hughes.net From deets at nospam.web.de Thu Jul 17 02:00:04 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 17 Jul 2008 08:00:04 +0200 Subject: Is there any component-oriented (non-MVC) web framework available for Python? In-Reply-To: <5fdd1388-bb1e-4a59-8fd1-2aa1ce7fa6e0@79g2000hsk.googlegroups.com> References: <5fdd1388-bb1e-4a59-8fd1-2aa1ce7fa6e0@79g2000hsk.googlegroups.com> Message-ID: <6e85faF5le5kU1@mid.uni-berlin.de> Alis schrieb: > Hi > > Is there any component-oriented (non-MVC) web framework available for > Python? > > That is something like Apache Wicket, Tapestry or JSF, but I need it > to be in Python. ToscaWidgets, can be used with any WSGI-compliant framework. Diez From gagsl-py2 at yahoo.com.ar Tue Jul 15 00:04:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 01:04:21 -0300 Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> Message-ID: En Mon, 14 Jul 2008 12:06:30 -0300, Keith Hughitt escribi?: > On Jul 12, 12:52?am, "Gabriel Genellina" > wrote: >> En Fri, 11 Jul 2008 15:42:37 -0300, Keith Hughitt ? >> escribi?: >> >> > I am having a little trouble figuring out how to convert a python >> > datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would >> > like to create a UTC date so that when I send it to MySQL (which >> > treats all dates at local dates by default), it will already have >> > incorporated the proper UTC offset. I've tried looking through the >> > docshttp://python.active-venture.com/lib/datetime-datetime.html), but >> > have not had any luck. >> >> You have to use a "timezone aware" datetime object. If all you want is >> to ? >> store an UTC date, the tzinfo demo classes that you can find in the >> Python ? >> docs at may be enough. > > Thanks for advice Gabriel. I downloaded the tzinfo demo class, saved > it as > UTC.py and imported it. I'm still not exactly sure how to use it > though. It looks like > the file already creates an instance of the UTC tzinfo class (line 20: > "utc = UTC()"), > however, when I try to test it out in the interpreter, it cannot be > found. I'm new > to python, and there is probably something obvious I'm missing, but do > you have any ideas? The import statement in Python doesn't behave the same way as similar statements in other languages - and it may be confusing you. I'll try to explain it using this example. You have: - a *file* UTC.py, containing the source code for the *module* UTC. It contains: - a *class* definition (UTC) and - an *instance* of that class, utc. --- begin UTC.py --- class UTC(tzinfo): ... utc = UTC() ... --- end UTC.py --- > Here is what I'm attempting: > > ============ output begin ============= > > Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import datetime, UTC Here you have imported the *module* UTC. That is, the name UTC now refers to a newly created module just loaded from the UTC.py file. >>>> t = datetime.datetime(2008, 7, 14, 00, 00, 00, UTC()) > Traceback (most recent call last): > File "", line 1, in > TypeError: 'module' object is not callable The error comes from UTC(): UTC is a module, UTC() is attempting to "call" it, and since modules are not callable objects, we get a TypeError. >>>> utc > Traceback (most recent call last): > File "", line 1, in > NameError: name 'utc' is not defined The *only* name we have imported so far is UTC - the module. Lowercase utc isn't defined. >>>> utc = UTC() > Traceback (most recent call last): > File "", line 1, in > TypeError: 'module' object is not callable Same as above... Ok, how to solve it? We know that UTC refers to the *module* with the same name. To get the *class* inside that module, use UTC.UTC - try again in the interpreter. To create a new instance of that class, you can use UTC.UTC(). To obtain the instance already created in the UTC module, use UTC.utc **OR** Import those names explicitely: py> from UTC import UTC In this case the name UTC refers to the *class* inside the module. In this particular example it may be confusing - both have the same name. Another example from the standard library: the poplib module contains a POP3 class, so after executing this line: py> from poplib import POP3 the name POP3 refers to that class. The poplib module itself isn't directly available. Back to the UTC module, you could use: py> from UTC import utc and now utc refers to the *instance* already created inside the module. This last form may be the most convenient in your case: py> import datetime py> from UTC import utc py> print datetime.datetime(2008, 7, 14, 20, 30, 0, 0, utc) 2008-07-14 20:30:00+00:00 -- Gabriel Genellina From eckhardt at satorlaser.com Thu Jul 24 05:23:02 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 24 Jul 2008 11:23:02 +0200 Subject: Requires a character ... !! References: Message-ID: karthikbalaguru wrote: > [root at localhost hello]# Analyzer hello_input ^^^^^^^^^^^^^^ This is often a bad idea. Anyhow, that has nothing to do with Python. > Loading debug info: hello_input > Traceback (most recent call last): > File "/usr/local/SDK/host/bin/Analyzer", line 694, in ? > app.dbg.readObjectInfo(elf) > File "/usr/local/SDK/host/bin/debugprocessor.py", line 427, in > readObjectInfo > self.privateProcessorDwarfTree.readProcessorDwarfTree(filename) > File "/usr/local/SDK/bin/debugprocessor.py", line 314, in > readDwarfTree > if "DW_OP_reg" in value: > TypeError: 'in ' requires character as left operand > > Is this related with the version conflicts ? Which version conflict? Sorry, but my crystal ball is getting a new polish today, so I can't see the actual code that causes the error. I suggest that you reduce your code to the smallest possible piece of code that still shows the error and post it here, otherwise nobody will be able to help you. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From torriem at gmail.com Mon Jul 28 01:52:24 2008 From: torriem at gmail.com (Michael Torrie) Date: Sun, 27 Jul 2008 23:52:24 -0600 Subject: write unsigned integer 32 bits to socket In-Reply-To: References: Message-ID: <488D5E98.3080600@gmail.com> rkmr.em at gmail.com wrote: > thanks a lot!!! re-read it again!!! > > from the struct doc! > Standard size and alignment are as follows: no alignment is required > for any type (so you have to use pad bytes); short is 2 bytes; int and > long are 4 bytes; long long (__int64 on Windows) is 8 bytes; float and > double are 32-bit and 64-bit IEEE floating point numbers, > respectively. Of course any time you send coherent numbers over the network, I highly recommend you use what's called network byte order. In C, you'd use the htonl() call, and then when pulling it off the wire on the other end you'd use ntohl(). If you don't then you will have problems when the endianness is different between the hosts. Standard convention (even in the MS word) is to use big-ending across the network. I'm sure python has some convention in the struct module for dealing with this. From grante at visi.com Sat Jul 19 12:02:51 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 19 Jul 2008 11:02:51 -0500 Subject: Change PC to Win or Windows References: Message-ID: On 2008-07-19, Dennis Lee Bieber wrote: > On Fri, 18 Jul 2008 19:14:43 -0400, Derek Martin > declaimed the following in comp.lang.python: > >> On Fri, Jul 18, 2008 at 03:46:13PM -0700, Joel Teichroeb wrote: >> > Calling Windows PC seems to be something that Apple did so they would >> > not have to directly mention Windows. >> >> Actually it's something IBM did when they created the IBM PC. Of > > Bah... PC was short for Personal Computer... I had never heard PC or "Personal Computer" until the IBM-PC. Before that, such compturs were called "micro computers" > Which term applied to the TRS-80, the Apple II, Altair even... Not that I remember. I had a homebrew S-100 bus system, worked with varioius Commodore machines, a few Apples, and some other CP/M systems. I never heard any of them called a 'PC'. My recollection is that 'PC' was a term that IBM coined. > Being a computer small enough to be single-user ("personal") > vs a department-wide mini, or company-wide mainframe... I remember those being called microcomputers. A "PC" meant an IBM. -- Grant From michele.simionato at gmail.com Fri Jul 11 11:45:27 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 11 Jul 2008 08:45:27 -0700 (PDT) Subject: decorator to prevent adding attributes to class? References: Message-ID: <98c6e83e-4a54-49ce-a32e-f03f5ab97f28@k13g2000hse.googlegroups.com> On Jul 11, 5:29?pm, Neal Becker wrote: > After spending the morning debugging where I had misspelled the name of an > attribute (thus adding a new attr instead of updating an existing one), I > would like a way to decorate a class so that attributes cannot be (easily) > added. > > I guess class decorators are not available yet (pep 3129), but probably > inheritance can be used. > > Can anyone suggest an implementation? This article could give you same idea (it is doing the opposite, warning you if an attribute is overridden): http://stacktrace.it/articoli/2008/06/i-pericoli-della-programmazione-con-i-mixin1/ There is also a recipe that does exactly what you want by means of a metaclass: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158 It is so short I can write it down here: # requires Python 2.2+ def frozen(set): "Raise an error when trying to set an undeclared name." def set_attr(self,name,value): if hasattr(self,name): set(self,name,value) else: raise AttributeError("You cannot add attributes to %s" % self) return set_attr class Frozen(object): """Subclasses of Frozen are frozen, i.e. it is impossibile to add new attributes to them and their instances.""" __setattr__=frozen(object.__setattr__) class __metaclass__(type): __setattr__=frozen(type.__setattr__) Of course using frozen classes is not Pythonic at all, and I wrote the recipe as a proof of concept, not to use it. Michele Simionato From semanticist at gmail.com Sun Jul 13 16:35:45 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 16:35:45 -0400 Subject: heapq question In-Reply-To: References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> <487a3c0d$0$32256$9b622d9e@news.freenet.de> Message-ID: On Sun, Jul 13, 2008 at 3:05 PM, Giampaolo Rodola' wrote: > On 13 Lug, 19:31, "Martin v. L?wis" wrote: >> > I understand that heapq is not that efficient to implement timeouts as >> > I thought at first. >> > It would have been perfect if there were functions to remove arbitrary >> > elements withouth needing to re-heapify() the heap every time. >> >> It is efficient for that - you just need to use it correctly. >> >> To remove the nth element from a heap, replace it with the last element, >> and then _siftup that element: >> >> The time complexity for that operation is O(log(len(heap))). The problem is that in order to remove an arbitrary element from a heap, you usually have to do an O(n) linear search in order to find it first, since you can't know ahead of time which index an arbitrary element is at. (You can, actually, but only if your heap implementation somehow notifies the elements of their new index when it moves them in the heap, which the Python heapq module doesn't do, so you'd have to write your own heap implementation.) > And if instead of removing an element I'd want to change its value? > E.g.: > > >>> heap = [0, 2, 1, 4, 5, 6, 7, 8, 9] > >>> heapify(heap) > >>> heap > [0, 2, 1, 4, 5, 6, 7, 8, 9] > >>> heap[4] = 12 Don't do that; you must first remove the element and then reinsert it. -Miles From timothywayne.cook at gmail.com Thu Jul 3 16:05:31 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Thu, 03 Jul 2008 17:05:31 -0300 Subject: Instance Names In-Reply-To: References: Message-ID: <1215115531.2873.540.camel@localhost.localdomain> On Thu, 2008-07-03 at 14:20 -0500, Larry Bates wrote: > I suspect there is some "misunderstanding" here. Why exactly do you think you > need to have your instances named with [] characters in them? > I often misunderstand. :-) But, I am implementing specifications in Python that are already implemented in other languages. http://www.openehr.org/releases/1.0.1/roadmap.html These specifications say that an archetype node id consists of identifiers like [at0000] and [at0001]. Now these are valid URIs and the associated query language (AQL) used by other services will send queries with those characters in them. For example: FROM EHR [ehr_id/value=$ehrUid] CONTAINS COMPOSITION [openEHR-EHR-COMPOSITION.encounter.v1] CONTAINS OBSERVATION obs [openEHR-EHR-OBSERVATION.blood_pressure.v1] WHERE obs/data[at0001]/events[at0006]/data[at0003]/items[at0004]/value/value >= 140 Since I am also using Zope3 it would be easier on me to name the instances with those characters. But my fall back is to set at0000.__name__='[at0000]' and manipulate the query to match __name__ instead of the actual instance ID. Thoughts? --Tim -- Timothy Cook, MSc Health Informatics Research & Development Services LinkedIn Profile:http://www.linkedin.com/in/timothywaynecook Skype ID == timothy.cook ************************************************************** *You may get my Public GPG key from popular keyservers or * *from this link http://timothywayne.cook.googlepages.com/home* ************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From jonas at codeazur.com.br Thu Jul 3 23:34:38 2008 From: jonas at codeazur.com.br (Jonas Galvez) Date: Fri, 4 Jul 2008 00:34:38 -0300 Subject: HTTP request error with urlopen In-Reply-To: References: Message-ID: <10df03a30807032034w69370ec3s81395cf0854e5eec@mail.gmail.com> Try: import re import urllib2 url = 'http://www.google.com/search?num=20&hl=en&q=ipod&btnG=Search' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' headers = {'User-Agent' : user_agent} req = urllib2.Request(url, None, headers) file_source=open("google_source.txt", 'w') file_source.write(urllib2.urlopen(req).read()) file_source.close() I think Google blocks the User-Agent urllib2 sends. --Jonas Galvez, http://jonasgalvez.com.br/log On Thu, Jul 3, 2008 at 3:52 AM, spandana g wrote: > Hello , > > I have written a code to get the page source of the google search > page .. this is working for other urls. I have this problem with > > import re > from urllib2 import urlopen > string='http://www.google.com/search?num=20&hl=en&q=ipod&btnG=Search' > file_source=file("google_source.txt",'w') > file_source.write(urlopen(string).read()) > page_content=file_source.readlines() > > Traceback (most recent call last) : > File "C:/Python25/google.py", line 5,in > file_source.write(urlopen(string).read()) > File "C:\Python25\lib\urllib2.py", line 124 , in urlopen > return__opener.open(url, data) > File "C:\Python25\lib\urllib2.py", line 387 , in open > response =meth(req, response) > File "C:\Python25\lib\urllib2.py", line 498 , in http_response > 'http', request, response, code, msg, hdrs) > File "C:\Python25\lib\urllib2.py", line 425, in error > return self._call_chain(*args) > File "C:\Python25\lib\urllib2.py", line 360, in __call_chain > result = func(*args) > File "C:\Python25\lib\urllib2.py", line 506, in http_error_default > raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) > HTTPError: HTTP Error 403: Forbidden > > Actually urlopen is working for google labs sets page but not for the > google.com and even I have same problem with wikipedia . Please let me know > .. If any one of have any idea about this . > > Thank You, > Spandana. > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From josiah.carlson at gmail.com Thu Jul 10 20:31:41 2008 From: josiah.carlson at gmail.com (Josiah Carlson) Date: Thu, 10 Jul 2008 17:31:41 -0700 (PDT) Subject: Doubts about how implementing asynchronous timeouts through a heap References: <80430d47-aac5-4123-8835-0591faf0baed@34g2000hsf.googlegroups.com> <156ca6dc-2120-4107-9cc5-a05088ae1c63@27g2000hsf.googlegroups.com> Message-ID: <344ff89f-d8e0-468e-ba61-0438491b5496@56g2000hsm.googlegroups.com> On Jul 10, 11:30?am, Josiah Carlson wrote: > On Jul 9, 4:13?am, "Giampaolo Rodola'" wrote: > > > > > Hi, > > I'm trying to implement an asynchronous scheduler for asyncore to call > > functions at a later time without blocking the main loop. > > The logic behind it consists in: > > > - adding the scheduled functions into a heapified list > > - calling a "scheduler" function at every loop which checks the > > scheduled functions due to expire soonest > > > Note that, by using a heap, the first element of the list is always > > supposed to be the one with the lower timeout. > > Here's the code I wrote: > > > <--- snippet ---> > > import heapq > > import time > > import sys > > > delayed_map = [] > > > class delayed_call: > > ? ? """Calls a function at a later time. > > > ? ? The instance returned is an object that can be used to cancel the > > ? ? scheduled call, by calling its cancel() method. > > ? ? It also may be rescheduled by calling delay() or reset()} methods. > > ? ? """ > > > ? ? def __init__(self, delay, target, *args, **kwargs): > > ? ? ? ? """ > > ? ? ? ? - delay: the number of seconds to wait > > ? ? ? ? - target: the callable object to call later > > ? ? ? ? - args: the arguments to call it with > > ? ? ? ? - kwargs: the keyword arguments to call it with > > ? ? ? ? """ > > ? ? ? ? assert callable(target), "%s is not callable" %target > > ? ? ? ? assert sys.maxint >= delay >= 0, "%s is not greater than or > > equal " \ > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"to 0 seconds" % (delay) > > ? ? ? ? self.__delay = delay > > ? ? ? ? self.__target = target > > ? ? ? ? self.__args = args > > ? ? ? ? self.__kwargs = kwargs > > ? ? ? ? # seconds from the epoch at which to call the function > > ? ? ? ? self.timeout = time.time() + self.__delay > > ? ? ? ? self.cancelled = False > > ? ? ? ? heapq.heappush(delayed_map, self) > > > ? ? def __le__(self, other): > > ? ? ? ? return self.timeout <= other.timeout > > > ? ? def active(self): > > ? ? ? ? """Return True if this scheduler has not been cancelled.""" > > ? ? ? ? return not self.cancelled > > > ? ? def call(self): > > ? ? ? ? """Call this scheduled function.""" > > ? ? ? ? self.__target(*self.__args, **self.__kwargs) > > > ? ? def reset(self): > > ? ? ? ? """Reschedule this call resetting the current countdown.""" > > ? ? ? ? assert not self.cancelled, "Already cancelled" > > ? ? ? ? self.timeout = time.time() + self.__delay > > ? ? ? ? if delayed_map[0] is self: > > ? ? ? ? ? ? heapq.heapify(delayed_map) > > > ? ? def delay(self, seconds): > > ? ? ? ? """Reschedule this call for a later time.""" > > ? ? ? ? assert not self.cancelled, "Already cancelled." > > ? ? ? ? assert sys.maxint >= seconds >= 0, "%s is not greater than or > > equal " \ > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"to 0 seconds" %(seconds) > > ? ? ? ? self.__delay = seconds > > ? ? ? ? self.reset() > > > ? ? def cancel(self): > > ? ? ? ? """Unschedule this call.""" > > ? ? ? ? assert not self.cancelled, "Already cancelled" > > ? ? ? ? del self.__target, self.__args, self.__kwargs > > ? ? ? ? if self in delayed_map: > > ? ? ? ? ? ? if delayed_map[0] is self: > > ? ? ? ? ? ? ? ? delayed_map.remove(self) > > ? ? ? ? ? ? ? ? heapq.heapify(delayed_map) > > ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? delayed_map.remove(self) > > ? ? ? ? self.cancelled = True > > > def fun(arg): > > ? ? print arg > > > a = delayed_call(0.6, fun, '0.6') > > b = delayed_call(0.5, fun, '0.5') > > c = delayed_call(0.4, fun, '0.4') > > d = delayed_call(0.3, fun, '0.3') > > e = delayed_call(0.2, fun, '0.2') > > f = delayed_call(0.1, fun, '0.1') > > > while delayed_map: > > ? ? now = time.time() > > ? ? while delayed_map and now >= delayed_map[0].timeout: > > ? ? ? ? delayed = heapq.heappop(delayed_map) > > ? ? ? ? try: > > ? ? ? ? ? ? delayed.call() > > ? ? ? ? finally: > > ? ? ? ? ? ? if not delayed.cancelled: > > ? ? ? ? ? ? ? ? delayed.cancel() > > ? ? time.sleep(0.01) > > > > > Here comes the questions. > > Since that the timeouts of the scheduled functions contained in the > > list can change when I reset() or cancel() them I don't know exactly > > *when* the list needs to be heapified(). > > By doing some tests I came to the conclusion that I need the heapify() > > the list only when the function I reset() or cancel() is the *first of > > the list* but I'm not absolutely sure about it. > > When do you think it would be necessary calling heapify()? > > I wrote a short test suite which tests the code above and I didn't > > notice strange behaviors but since that I don't know much about the > > logic behind heaps I'd need some help. > > Thanks a lot in advance. > > > --- Giampaolohttp://code.google.com/p/pyftpdlib/ > > According to a quick scan, there is some inefficiencies with your > code. ?In particular, you don't need to re-heapify if the item you > need to remove is the first item; you only need to heappop(). > > In any case, if the Python standard library heapq module supported non- > lists as containers, then the pair heap implementation I wrote a > couple years ago would be perfect for this particular task. ?Because > of the rewriting of heapq in C, without a bit of monkeypatching, we > can't re-use that implementation (which offered insert/remove of > arbitrary entries in the heap in O(logn) time, which is significantly > faster than the O(n) time of your implementation). > > What I'm thinking is that we should add a pair heap implementation to > the heapq module (which can cache the pure Python functions if it > needs to use them), which would then allow us to use that (and others > to use it generally), add scheduling, etc. > > Regardless, it's a 2.7/3.1 feature, so it's ok if we take it slow. > > ?- Josiah Also...first I need to fix the unittest failures. ;) - Josiah From giveitawhril2008 at gmail.com Sun Jul 20 18:50:41 2008 From: giveitawhril2008 at gmail.com (giveitawhril2008 at gmail.com) Date: Sun, 20 Jul 2008 15:50:41 -0700 (PDT) Subject: Python Written in C? Message-ID: I'm just learning about Python now and it sounds interesting. But I just read (on the Wiki page) that mainstream Python was written in C. That's what I was searching for: Python was written in what other language? See, my concern was something like: OK, if Python is so hot, then, hopefully someone is writing it in assembly language for each MPU chip out there. Otherwise, if, say, they've written it in C#, then it looks like the REAL, generally useful language to learn is C# and Python is akin to Visual Basic or something: a specialty language....whereas REAL WORLD programmers who want to be generally useful go and learn C#. So I was suspecting the Python compiler or interpreter is written in a REAL language like C#. So, Wiki says it's written in C! It's almost as if it were an intentional trick...write your own, new language in an OLD, real world language that is passe. Compile it into executable modules of course, so it is a real, working compiler, alright. But the SOURCE is some old, high level language which no one wants to use anymore! So now you've got a hot new language package and no one can say "well, it is written in, the SOURCE code is written in, a REAL language." No, it's not! The source is some outdated language and compiler and no one is going to prefer learning THAT to learning your hot new language! I'm not dissing Python, here. Just noting that, if it is written in C, that throws a curve at me in trying to balance the value of learning Python vs. some other major language. From rtw at freenet.co.uk Sat Jul 26 15:43:09 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 26 Jul 2008 14:43:09 -0500 Subject: urllib and login with passwords References: Message-ID: Jive Dadson wrote in news:SvJik.317138$fz6.173226 at fe08.news.easynews.com in comp.lang.python: > Hey folks! > > There are various web pages that I would like to read using urllib, but > they require login with passwords. Can anyone tell me how to find out > how to do that, both in general and specifically for YouTube.com. > A typical pattern is submit a form to login and get a cookie back, subsuquent request with the cookie set are then "loged in". import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cj) ) page = opener.open( LOGIN_URL, data = LOGIN_FORM ) page.close() page = opener.open( DOWNLOAD_URL ) print page.read() page.close() You will need to work out what goes in LOGIN_FORM, it likely something like: LOGIN_FORM = "username=name&password=pass&submit-button=Some+value" where username, password and submit-button are the name of the controls on the form you would normally login from. If the form has an enctype='multipart/form-data' then things get a little more complex, possibly start here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 Rob. -- http://www.victim-prime.dsl.pipex.com/ From toby at tobiah.org Wed Jul 9 17:27:10 2008 From: toby at tobiah.org (Tobiah) Date: Wed, 09 Jul 2008 14:27:10 -0700 Subject: sort(cmp=func) Message-ID: I have a list of objects that generate code. Some of them depend on others being listed first, to satisfy dependencies of others. I wrote a cmp function something like this: def dep_cmp(ob1, ob2): if ob1.name in ob2.deps: return -1 else: return 1 I also tried returning 0 when there were no dependency relationships between the objects. This failed, because every object was not compared with ever other. I imagine that this is because sort assumes that if a > b and b > c, then a > c. In my case, this isn't really true. If a is not dependent on b, and b is not dependent on c, that doesn't mean that a is not dependent on c. Is there a better way? Thanks Tobiah ** Posted from http://www.teranews.com ** From callen314 at gmail.com Thu Jul 17 06:25:01 2008 From: callen314 at gmail.com (Craig Allen) Date: Thu, 17 Jul 2008 03:25:01 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Message-ID: <98eae1fc-ff34-4dcc-b46d-9e3da2850c28@r66g2000hsg.googlegroups.com> On Jul 16, 7:01 pm, Lawrence D'Oliveiro wrote: > In message > , Craig > > Allen wrote: > > ... the ideal is still that > > > tl = TehLibrary() would always return the same object. > >> class TehLibrary(object) : > > ... @classmethod > ... def __new__(self, cls) : > ... return self > > >>> s = TehLibrary() > >>> s == TehLibrary() > > True That's great, I simply didn't find that when looking. Thanks! From kyosohma at gmail.com Mon Jul 7 11:36:07 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 7 Jul 2008 08:36:07 -0700 (PDT) Subject: win32com extension documentation/API References: <996ff65c-8611-483e-90d6-3cf73b9e1496@25g2000hsx.googlegroups.com> Message-ID: <1fc3452a-8eca-4437-8322-5a7c10b14e48@f36g2000hsa.googlegroups.com> On Jul 7, 10:26?am, korean_dave wrote: > Hi. Where can i find the API for this extension? > > Sourceforge only has downloads. Python has stopped supporting the > upkeep of the versions. > > Thanks. I usually use ActiveState's docs: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/PyWin32.html http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/html/com/win32com/HTML/docindex.html There is a book on using the win32 modules that is still relevant by Mark Hammond. It's fairly pricey, but good. And there's also the PyWin32 mailing list. ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From mail at timgolden.me.uk Thu Jul 10 11:39:39 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 10 Jul 2008 16:39:39 +0100 Subject: Python / Windows process control In-Reply-To: <7b1097c5-7a8a-4bb8-b293-03d15aee98ed@m36g2000hse.googlegroups.com> References: <7b1097c5-7a8a-4bb8-b293-03d15aee98ed@m36g2000hse.googlegroups.com> Message-ID: <48762D3B.10205@timgolden.me.uk> Salim Fadhley wrote: > Does anybody know of a python module which can do process management > on Windows? The sort of thing that we might usually do with > taskmgr.exe or process explorer? > > For example: > > * Kill a process by ID > * Find out which process ID is locking an object in the filesystem > * Find out all the IDs of a particular .exe file > * Find all the details of a currently running process (e.g. given an > ID tell me which files it uses, niceness, runtime) As far as I know, the closest you're going to come here is WMI [1]. It won't do everything you ask, though. I don't know how to find out which processes have a lock on a filesystem object. When you say "Find all the ids of a particular .exe file" I assume you mean: all the processes which were started by running that file. import subprocess import time import wmi c = wmi.WMI () # # Kill a process by id # notepad = subprocess.Popen (["notepad.exe"]) time.sleep (1) for process in c.Win32_Process (ProcessId=notepad.pid): process.Terminate () # # Which process ids correspond to an .exe # for i in range (5): subprocess.Popen (["notepad.exe"]) for process in c.Win32_Process (caption="notepad.exe"): print process.ProcessId # # _Some_ (but not all) of the information about each file # for process in c.Win32_Process (caption="notepad.exe"): print process process.Terminate () HTH TJG [1] http://timgolden.me.uk/python/wmi.html From keithb at bailworthsolutions.com Sun Jul 6 06:33:08 2008 From: keithb at bailworthsolutions.com (Keith Bailey) Date: Sun, 06 Jul 2008 11:33:08 +0100 Subject: Python / WxPython error message Message-ID: <48709F64.3040707@bailworthsolutions.com> Dear All, Any help on this would be hugely appreciated. I have had a Python programme written for me, but when I try to run it, I get the following error message: /*Traceback (most recent call last): File "iTeddyConverter.py", line 3, in File "zipextimporter.pyc", line 82, in load_module File "iTeddyConverterPanel.pyc", line 4, in File "zipextimporter.pyc", line 98, in load_module ImportError: MemoryLoadLibrary failed loading win32file.pyd*/ I hav etrawled through the net trying to find a resolution but nothing works. I tried putting the DLL msvcp71.dll in the system32 folder but that made no difference. Please help if you can. Thanks Keith From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 3 03:11:45 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 03 Jul 2008 09:11:45 +0200 Subject: Times where one would use new style classes vs classic classes In-Reply-To: <6700e4ba-8573-44da-b75a-3b3e5ba1fd9b@i36g2000prf.googlegroups.com> References: <6700e4ba-8573-44da-b75a-3b3e5ba1fd9b@i36g2000prf.googlegroups.com> Message-ID: <486c7ba7$0$10446$426a74cc@news.free.fr> Quek a ?crit : > Hi all, > > I'm really new to Python and I've been reading up some texts on older > versions of Python (2.2 to be specific). > > The text briefly mentioned new style and classic classes. > > I'd really like to know in the current context of Python 2.5, besides > in the cases of multi-inheritance, where would I use new style > classes? Everywhere you don't have to support compat with ages-old versions of Python. MI is not the main point of newstyle classes (FWIW, you can do MI with old-style classes too), they have quite a lot more to offer. Consider "classic" classes as a legacy feature, period. From frank at chagford.com Thu Jul 17 05:57:32 2008 From: frank at chagford.com (Frank Millman) Date: Thu, 17 Jul 2008 02:57:32 -0700 (PDT) Subject: Question about properties Message-ID: Hi all I have started experimenting with properties. The example in the 2.5 docs uses an inconsistent mixture of single and double underscores for the internal representation of the attribute. I was going to file a documentation bug, but then I checked the 2.6 docs online, and I see it has been fixed, by using single underscores throughout. IMHO, it would make more sense to use double underscores throughout. I thought that the main point of using property was to prevent direct access to the attribute. With a single underscore you can access it if you prefix the attribute name with a single underscore, thus bypassing the logic in 'property'. Is this a valid comment, or does it come under the category of 'we are all adults here'? While experimenting, I came across the following curiosity. I know that prefixing a class attribute with a double-underscore makes it difficult to access the attribute externally. Here is a simple example - >>>class Test(object): ... def __init__(self,x): ... self.x = x ... self.__y = 123 ... def get_y(self): ... return self.__y >>>t = Test(99) >>>t.x 99 >>>t.get_y() 123 >>>t.__y AttributeError: 'Test' object has no attribute '__y' I was surprised that I could do the following - >>>t.__y = 456 >>>t.__y 456 >>>t.get_y() 123 It's not important, but I am curious to know what is going on internally here. Frank Millman From lxz3002 at yahoo.com.cn Wed Jul 16 22:04:45 2008 From: lxz3002 at yahoo.com.cn (Leo Lee) Date: Thu, 17 Jul 2008 10:04:45 +0800 Subject: wxpython: visual effects missing after py2exe Message-ID: Please take close look at the details of the two snapshots. I need explanation and correcting this problem. begin 666 after.png MB5!.1PT*&@H````-24A$4@```;0```#-" ,```#GL'7)`````7-21T(`KLX< MZ0````1G04U!``"QCPO\804````@8TA230``>B8``("$``#Z````@.@``'4P M``#J8 ``.I@``!=PG+I1/ ```P!03%1%````$S=X<6]D"AB#`!BK`!J\$CJ* M$CR)$CR*`"2F`!G/`!K/`!_2`"#(`"/6`#+!`#'&`#?+`#W,`#;2!S'8!S3: M`#O2`#_2`#C8`#W<"#'8"#'9"33:`#O@`#OB`$Z8%D"1`$'*`$//`$O-`$[( M`$_+`430`$?7`$#<`4S0`$K8`$K<`4W<`E#(`E'*`U#,`E'-`E3/`E;.`%/: M`EC2`%K?"%7=`$;D`$;J`$O@`$OG`$WC`$OK`%#@`%#B`%/A`%'E`%3C`%7E M`%'K`%7J`%CF`%KD`%KG`%[G`%GH`%CK`%CN`%SI`%[I`%SL`%OR`%KU`%_R M`&O+`&K/`&W/`&_/`&;8`&O1`&W1`&[0`&[1`W+2!7'1`'+8!G?:"GC5"7C: M"'G;#'K;#7O<#GS<$GW;%7_<`V#G!F?E!6;F`6'J`V/H`&+I`F#L`&#N`67K M`&?M!F3I!F?J!FGF!FGK`V#Q`6#U`V'V`V7Q!F?T`&#Y`&#\`63Y`&7]`&GR M`VCT`FSQ`V[U`VCZ`6KZ`VO[`FK^`V_Z`6S^`V[^`V[_!FKY!F_Z!FS\!V_] M`'OG`'/]`W+_!G'^!W+]!W3^%FKN$WK_&H+_-XW4(X7_(8G_)XW_*Y#_,8S_ M,93_.I'_/97_/Y?_0)?E1*+V:YO5:IS7;9G0:)[;_B___Y___Z___[___\ M___]___^____```````````````````````````````````````````````` M```````````````````````````````````````````````````````````` M```````````````````````````````````````````````````````````` M```````````````````````````````````````````````````````````` M````````````````````````````````````/^X!3@```!AT15AT4V]F='=A M%[MG8M_%4<5Q]>D1:4H MMKZM6 L*!E#16%&14"*/$$)"U/JH5EN?):4DVI)8##8-C;44"DEL:Q\4W^^F M4 at VONO^;\]C9G=V[]^[,W#UU)O=W/DGN37+V[-G?=\[,W)W)370;MPT]/9LV M;=Z\>>>N?0/[!L8.[1\Z-#0T--B9=M![BQBRGIY'%IYY]MG?O/#2A9=?OGCQ MM\HN=J:EU^_M$P:M9^B1F<5G&+7GGW_A1687+ES@#S!O%8ANN[VO=WQ\8F)B MYK%?+IX[?W[QW")[6#QW;G%^X3S,2P48M UW,!LX.CXQ,S/SF+*91YG]#$:B M0-1FU&CME at V]O;V<&L,V,?$+9NQA8OS8L6/#G6EL"D9L4=3>":*U:V_O4=#& M13\Y,3Y^=.S0H:']^_?"2!2(XJBMN-%;);1]O-*$'67$!@;V)6U$Q?'ME" 06N+&H>VJ?>.[_[H>_?= M]_T?_/#>>^_YSCU/?TUVC1U99_W]].V-0VN'6G3#.]Z[>>?N+W_]F]_XUK?O M_NK==_WN*[__YUT?[=S.\8UHJ0):'#F?*H'VGTNO,;MTZ;5+K_[KU7\_]Q% MR"^PHM,V1^W/3@\R(J-0^O>PS]A M=2J at QK2(F4OX8-9'/,'\70$5I,"[-[CR BGYA at O6K-N^Y[AT5AC=O7Z M7SXU-34U.V)$[R7[#X!JTN!2 3BU-PB,FA?&!R=_/"J5:O>PNS-PM[TF;E3ITZ> M[$YL>IH]X1AA=2K H;G%B]9\Z(L'1R(.,A4 at 3:A34[- MSIXY>W9!0LNH<7(=9Z::M^\7N17:G*BT$59JT[.G!;:%>6:RTMK/"A%(%(AN M6L>@'1PY?GSJT=G3IT^?.7/F<6ES<[.=:2>]-PYMQ^Z]>P>'CXVRC5U\X]SL M*6$GIZ?=)J2A'_5S[XU!6_?Y6]9OW+B1;>7?NG7KSAU]?7V[V&=?WPZ8IPH( M:.O7^+/\H[K.3OF!J>6[3ZW;_^[#(L* 4`+2A<,EE `[0`%0 at P950: MH 6H0( I:Y7&MYE$?)CCG^)9HR4NN5^4>P:H13 IZ]TC4S\#T 1%SB>8JUQA MB>:A::0`S5_2.6BR=Y2XDJ]%=DFE<2?>A6%-Z!Y@<$N"4"ST\L+;P%-_:D%'L-00$![!1:4`M'J M#P):4,18LH 6&C% "Y"8#FUYV7P0]F(*U<%)I-WCIR[PJI2>/;7:,G:=YSBO)TQ&:<5$FCJPV#2O9RG,ED;"X%D=H%F<0KJPV M#2O9QM,VBY7B#V@!DFR EJQ&J^67TF68)>N9B$W]F-=D@'K7DG(5M-*3M(:6 M<,[ASD%KN1Z7>5:MV]DWG5H4\R!((S2YL2K9(B>>-2Q[ELM5*$X#:&7T4FB5 M2ZV ]HKJE"0OM>U1(&-M*Z]@794&:&YEVZ+2!"M]FUQZ!@DM at 9GNIM.*4VZP M$]N#Y$%9_M=;TV`:T1FA),Z%3:/:I.-"G'%%K"3MO*FE:: M%BS%G(^NCVF)=_Z at 0KV[=3!A'U72/:J"J>H>%2O1C4FPLDM+H65;MXJ5EG22 MPC,_SVD!K<$S;.G=LV\.31&HJ+2L!U/H,FB-G9Y6.TFE%:KI?=MA' MMG5'1,FHX](K+>M8]4K3"C/I>/,CE3:FJ9H5PQN at J:;6-K2L2TR[Q[3O*Y\] M:O-*M0-=:_BY2M,VI^M?"NZ?=,Q:9 A^$2K;Y6[L7R$UEI 0 .T$$HLR=&QTLRV#L"+1@$G:,O+ MMML-X%^G`CEH-;<+Z^T_%>?W/5X=\G4M&5@>6IW-X3*?,=9IOL>KXUJ7NI:Z MJJT`K<[1V'R:;W96W^.97475C-AD>R*@U:%U;3%XI57WLBL#6N/M$@,9ZZY< M at U-6NCA#2_=C:>]+X:)*?@U:SU=%T]Z'I/)RLM7ODK_5=TDO6^/+!70*99"] MF4L-T.2)2M9FC#(H6:U6+P[5HU7HYO$*:[1&V6F-(."-+MZ&T!I"+I[:\),NX:430 M1-'F]G85EDTK-"C=9Y(VK$1A;3E/=1+-PA:@:9LF%*XWGEH-T-+=`TZMKKG( MZ9B6;.\QZR5;0LM":HOCK;O-W)@KUM&S15UM8*B_G%I$; -:LKE*[QX=&EUQ M(J)O(,E$:;)+K^3"FL?3WG,RJ[22^4H^:+'2LL%;'EOI_A"9:FNIN^XV 3SZ1CLXE7ER95<9S'M*K IK^O6Q33 M>)4EEER :3S3ZZW#SP6:P5J.A4M7;.%LX.I[/(-+J'0QO&'\KFQC3_5*#CRH M%3"[RZ]!JUX4@ >U`H!&K3!!?$ C$)4Z)*!1*TP0'] (1*4."6C4"A/$!S0" M4:E#`AJUP at 3Q`8U 5.J0@$:M,$%\0",0E3HDH%$K3! ?T A$I0X):-0*$\0' M- )1J4,"&K7"!/$!C4!4ZI" 1JTP07Q (Q"5.B2 at 42M,$!_0"$2E#@EHU H3 MQ $M%0`T"P% M\\$=T'R at 8)D#H%D*YH,[H/E P3('0+,4S =W0/.!@F4.@&8IF _N at .8#!GDE1>@>87#+!E ,]/) M*R] \PJ'63* 9J:35UZ YA4.LV0`S4PGK[P`S2L<9LD`FIE.7GD!FE>4%:%[A,$L&T,QT\LK+#!K>9 at G0O%(@P&10:8 6 MH (!IHQ*`[0`%0 at P950:H 6H0( IH](`+4 %`DP9E09H`2H08,JH-$ +4($` M4T:E`5J "@28,BH-T )4(,"446F %J "`::,2 at .T`!4(,&6S2KL5__3.)[: CYA,-PUP`S5 HG]Q,H/T/?S'YF:RO\Y `````245.1*Y"8((` ` end begin 666 before.png MB5!.1PT*&@H````-24A$4@```:(```"M" (```!]2.Q9`````7-21T(`KLX< MZ0````1G04U!``"QCPO\804````@8TA230``>B8``("$``#Z````@.@``'4P M``#J8 ``.I@``!=PG+I1/ ```!AT15AT4V]F='=A%[MG7^,'-==P.=NZ=F-@#]2$97^`ZA(_ &J9 0D M;1PU50M(#2V)TJ T25NGK1OGDCB*@T32 at AJ!^*.%("P5#$H`M4@@X#^H2BT0 MB(HV;A+W[*--S^=S[=B^\_WR^>Y\=NR[O5N^L^_NW;LWL[.SL_-VWNQ\5E^M MYF9GWON^SYOWV??VQ^U \-&_"LS;^J\.#-1D1V-M5[B[-K#YX-#N<'M7+?BQ M6E!?E_N!6JVQW at CJ&\'@8# 8!!M;I=3E#VX0Z&\"X1CA5AX"HKEF#/S6"8FA MQU9V'5I_Q^<;[_K#,-[]QXU?>+&QYT\;>[[2>-_A,.[ZBS#>?Z1EJ ,("/0Q M at 83KGX<\)!!HQPU^8D8<-_CDTJ[?W1#-:=/]W)<:$B*[7_SS[1#KJ3!WL at T! M"$# 0P)-S7W at U>#>\\']XP/[YR2"QRZK$.75#EZK/;TJX at N>7:\=:DBH;;G7 M.]6&VCGTS(9,!M61! 0@``$?"&QI[I[CP4-GM^.3EX)/SRCEB>Q4A,IK$>&C M!U:V8_]2C8 `!"#@!X$@^.7_"3X\$8CF[A_?#.6[INFT[#:G>(\O!SJV)GWR M4"C$?0N;\"GOCCQXY\__?;G3^]^_O1/?&'B M)W]_XM8_.'W+\^.[GQL/#HT-_=YX\.Q8\(5+P>?&8A:J??P<3M, at H A400W] MU,90.)D#IT;"^Z=' M[CXR&0R/?.AKU]>'WR-_!K_]&LM55N at 0@(#7!**:^][9B:.CIX[^W_C1T?'P M/HQ3X1[Y<_34-T;&_OWDJ:^/C/WSZ(7;7_Q^\-%C:,[K#F;^!0$(!._ZS^#V MUX([938W$=S_IHS81GA;31&-3__]^5:::Q;2L,:_VAG[$*: ``0 at X(I J+E? M&PWNG@@U)RO63N-QH;8:O_7S@[>]VKP\>G-4)\C:3YU*)?= M\LX_TGGK/=&'7+6-)S$(0 `"0F"'YN[3AA*CU1N-M<0Y7>/ WYZNW7>\]@GY M//",:;KHK$VK38E/[DT#HCD(0 `"#@EL:TZ^UBISL8]/-Y6D)F[1"=V.^=WP MRS_Y1S2W8SV[=;P^D0T(0 `"^1,( M?F8TN&LBG,W)"W7;FI-7Y>2UN3:SN6?^\O5!>6WNT>L#^ZX%#S7CX67S9;C- M-U6-G=8!FWY4EB0@``$(N" 0:N[.+_7C"_=NG='O./VYP8?'!TFQQZ?"J,QR;?]KDI%;6#&[6#C8$G-R3$=P0$( `!WPC(QX-'M.;$ M1YK^WW_RUFO#K$.$O M=7UJ>?NG",V?*#P0OK5JA;19O6/B]KUA/H,"@>()U(-]1'D(;&HNG-"=DU^$ M"#XX,O"A$_*[$.%/0\C_$V[&P$FNBK7$J"Y*G<_ M;2^0 at -(ZZ7RG??P*FYC"=T_Y"'HH]FRS6V MHI1%\7952E . M2*NYMA9K>T":U-%<&DH5TPJ32GK&'UD)5!JP,ZZJJH MYM+L24 at OX?2\"%(.!+(1,#6GMSL:+]GJK>!9:367++58T43G4VWYQEK)*D<= MDZS=5E/+V'E?VZPX``(N")AJ0W,N"!L+T';?:8U]>FF[:,WVI)1R\A6U5:>3 M3:=,*1P":0 at HM9G7/-_]2L,MPS%I/U!BK5A-T;1Z-:'3V9Q93D)U"3/'MF;ZB at RFS7 30G(O^ M0G-H#@)^$>"-LMQ-MT-SZN5/;A" ``3ZB< .S;W #0(0@$#?$0 at U]_:MG[SI MN];1( A ``(OH#DN`@A H,\)H+D^[V":!P$(M-33^M at L%0@`"E2+04G/BN(6_VW/SZ!V-8WL+B;7_>J\D(&E4 MJC]H+ 0 at D#N!EIH[\]7[;W[SCL8K>PL,24#2^*>C_WWX'[_N0WSUW_[CV,GC M,L%4<>*-$[W,K<#:K:ISOPHI$ ).";34W.&77J[7-PH/2>/BS+PG'^&YO'3U M&_][7.RF'"?;OF I' 7!$J at N0V/;NL79N9D!B=#7>XOS,SW M-K4":]^N&LVY&(>4Z91 "32WOEYOWM8*C[6UU>LKR[)\EJ$N]Y)8+W,KL':S M:C3G=$!2N L"'6M.?>'.7,Q&]^A'K2,S+(%ET;JZ>M./N'%M97EQ859K;C6\ M]2RW`FO?436::R^ UZQ31W(T;UW,/\6^TS-B=^K"WWKIV=6GA M\NR4UMR-&V\E))9<6JLKIM/#DXZVJT9S3`4GA+ at ADT9R82$_3U(;Y MISFY,Q_5_S6S(_>)YJY?7[E^_6JVD$IC3XS=W^I at 5<*U:\M+BW-ST^>UYIJ) MMH_5;A^F"SNI65 MQ<4K,[.7SAF:D\2VV:C3G8AQ2IE," M&36G%JIZ7F9NZ-&E%[/6]*W3V5Q;S5GBBS57PC':AI89+?>E$8WI"%.148W& M&BUZBCZL;>U1IT>;G#(]*S>K:C3G=$!2N L">6K.])?:-N^SO?W:G,TMR4C3 M(67*MKJW(OI0]+#8T\V=UBGZSZM7KUQ9F)Z9VI[-*1U8B;7ZT\PY-OE6C5(% MMJT]H?R$)D?!1JE:5:,Y%^.0,IT2R*ZYZ#K4D>;4(-B#[4] M1I^B2S8+U!4M+R\L7+XT/1E^8DY];DX+2%<1S3.:GI5A[ %F.6J[;>UFL28< MJW46QC2U6U6C.:<#DL)=$,A34/?FAM[6#Z7< M8QUFGF[6N[Q\>>'RU/3DCPS-73%SLTZT\DS..=H6LVK9;EM[J_)C(220L>J- M5HWF7(Q#RG1*H&/-I7_W()TZ?W-#G1N;24)Z5@)6U6C.Z8"DIDI^\U'];:Y#E7'6'O,$Z,/R:.+B_/S24M4<+M&CH>M/7;E6-YER,0\IT2J 4F at OG,H7' MXN+<_-S%J0L3>C:GYUD]R*VCVIL*:T,LS3&J$*MJ-.=T0%*X"P(ET)P::87' ME2LS<[,7)L^?UIK3%NA!;AW5+ at J+3/&SYWYOM:<)-.;W'I:#B[\B90$(% X`327@[!>^?:_RG-%X7W9LP1H M;\]04U&7!-2UBN;07,<$T%R78X_3>T8`S74\O%OU#<,^KZM6OG&15U$YEE.U M_LT17>%%%:DY]?TA$X'>8WT]7A]C[B^?'TN"Y_-1<%$75BCV$E5Y=FV%M.3Y-_J367H;VEUER: M#O6V at 2F3+^-A!6O.['(UGLW[;(.DJ&[(K#D]"U"96QRL1\V)K35 at M!![,^?- MJ[VJ%68S3;-'&Q4[M>]!VSMMK]F;5L]&&YO0S**NYWZJ%\WU[K6YMK-1+;C8 M<6Y==M'G@]AG"'?KHTZ'?323MD]IL:< MZZ_FDI_AU:->]5^GPR#EL&_53//Y/SH-M,:8"U".VILPHV_;S,(U9UZT5@>U M>NIJV[\N^JYJ91:O.>L)K>TS? \&<+:+(,VPM]RMQVVK)9NU+&VUBC>A.1WJ M9@*.VMMJ at I/PM&>:,58TV3K4.BM->UM5E- IT8?,BR&7S"D$S16V:#7G)FWG M*@S=YJ9G=.V5$U\7F at N^1)O-7WS[3K( M- at RB5WS*Z5CL+" Z^XNN;?.ZQ!VUUVQ";/*QUHA=!.1[A61K;^P:',WE=1&F M+*=,FM/+&3]G]=T, at X1%:\(BSGIZ,*40193OF)>J\VJOU:V6J1,:%0O-6MNF M' 9I#DO3WNB2.<%HK=3LY^6=!I&WQQ2I.6^A9$NL[3#(5JRW9WG5WMPE'L7N M57N]O2K\3 S-Y?;:G)\=W,=9N9NX]3&T*CD% @!"/A%`,WYU1]D`P$(Y$X`S>6.E (A``&_"* YO_J#;" `@=P)H+G< MD5(@!"#@%P$WFEO;J*]M^-50LH$`!*I*`,U5M>=I-P0J0P#-5::K:2@$JDH` MS56UYVDW!"I#`,U5IJMI* 2J2@#-5;7G:3<$*D,`S56FJVDH!*I*`,U5M>=I M-P0J0P#-5::K:2@$JDH`S56UYVDW!"I#`,U5IJMI* 2J2@#-5;7G:3<$*D,` MS56FJVDH!*I*`,U5M>=I-P0J0\")YM;6UB4JPY"&0@`"7A- P)HKGN&E `!"'A-`,UYW3TD!P$(=$\` MS77/D!(@``&O": YK[N'Y" `@>X)H+GN&5("!"#@-0$TYW7WD!P$(- ]`337 M/4-*@ `$O": YKSN'I*#``2Z)X#FNF=("1" @-<$'&FNOK96][K=) MYGSO(?*#``2Z)(#FN at 3(Z1" @.\$W&ANM;ZV6O>]Z>0'`0A4 at P":JT8_TTH( M5)@`FJMPY]-T"%2#0';-[4KX92\6K=6X>F at E!$I!`,V5HIM($@(0R$X`S65G MQYD0@$ I"*"Y4G0324(``MD)H+GL[#@3`A H!0$T5XIN(DD(0" [`327G1UG M0@`"I2" YDK1320)`0AD)X#FLK/C3 A H!0$T%PINHDD(0"![ 307'9VG D! M")2"@!/-K:ZN292B_20)`0CT/0$TU_==3 ,A4'4":*[J5P#MAT#?$\BFN?\' 4/X>GA=<>(=D`````245.1*Y"8((` ` end From torriem at gmail.com Mon Jul 28 01:24:27 2008 From: torriem at gmail.com (Michael Torrie) Date: Sun, 27 Jul 2008 23:24:27 -0600 Subject: Attack a sacred Python Cow In-Reply-To: <20080727193416.GE7373@dragontoe.org> References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c29cc$0$20302$c3e8da3@news.astraweb.com> <20080727193416.GE7373@dragontoe.org> Message-ID: <488D580B.9050001@gmail.com> Derek Martin wrote: > Regardless of how it's implementd, it's such a common idiom to use > self to refer to object instances within a class in Python that it > ought to be more automatic. Personally, I kind of like the idea of > using @ and thinking of it more like an operator... Kind of like > dereferencing a pointer, only with an implied pointer name. > > class foo: > def __init__(): > @.increment = 2 > > def bar(a) > return a + @.increment > > I'm sure all the Pythonistas will hate this idea though... ;-) To be > honest, it smacks a little of Perl's magic variables, which I actually > hate with a passion. This is the only place in Python I'd consider > doing something like this. I think the biggest reason why an implicit self is bad is because it prevents monkey-patching of existing class objects. Right now I can add a new method to any existing class just with a simple attribute like so (adding a new function to an existing instance object isn't so simple, but ah well): def a(self, x, y): self.x = x self.y = y class Test(object): pass Test.setxy = a b = Test() b.setxy(4,4) print b.x, b.y If self was implicit, none of this would work. Now this contrived example is not useful, and maybe not even correct, but I have patched existing classes on several occasions using this method. How could python retain it's dynamic nature and still have an implicit self? How would the interpreter know when to add the self variable and when not to? From wuwei23 at gmail.com Thu Jul 24 05:47:10 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 24 Jul 2008 02:47:10 -0700 (PDT) Subject: Requires a character ... !! References: Message-ID: On Jul 24, 7:33 pm, karthikbalaguru wrote: > Kindly let me know a trick to make to resolve > the 'in' operator related problem by using Python 2.2. You seem to be making life -very- difficult for yourself. Your distro is running Python 2.4, you've gone out of your way to get Py2.2 installed. Why are you so convinced that you -need- Python 2.2 over 2.4? Everyone problem you've posted here seems due to that assumption... Generally, Python is pretty good about backwards compatibility. Code written for 2.2 should run fine under 2.4. As you're discovering, the opposite isn't true. __future__ isn't a cure-all. From cito at online.de Fri Jul 11 07:55:05 2008 From: cito at online.de (Christoph Zwerschke) Date: Fri, 11 Jul 2008 13:55:05 +0200 Subject: strip() using strings instead of chars Message-ID: In Python programs, you will quite frequently find code like the following for removing a certain prefix from a string: if url.startswith('http://'): url = url[7:] Similarly for stripping suffixes: if filename.endswith('.html'): filename = filename[:-5] My problem with this is that it's cumbersome and error prone to count the number of chars of the prefix or suffix. If you want to change it from 'http://' to 'https://', you must not forget to change the 7 to 8. If you write len('http://') instead of the 7, you see this is actually a DRY problem. Things get even worse if you have several prefixes to consider: if url.startswith('http://'): url = url[7:] elif url.startswith('https://'): url = url[8:] You can't take use of url.startswith(('http://', 'https://')) here. Here is another concrete example taken from the standard lib: if chars.startswith(BOM_UTF8): chars = chars[3:].decode("utf-8") This avoids hardcoding the BOM_UTF8, but its length is still hardcoded, and the programmer had to know it or look it up when writing this line. So my suggestion is to add another string method, say "stripstr" that behaves like "strip", but instead of stripping *characters* strips *strings* (similarly for lstrip and rstrip). Then in the case above, you could simply write url = url.lstripstr('http://') or url = url.lstripstr(('http://', 'https://')). The new function would actually comprise the old strip function, you would have strip('aeiou') == stripstr(set('aeio')). Instead of a new function, we could also add another parameter to strip (lstrip, rstrip) for passing strings or changing the behavior, or we could create functions with the signature of startswith and endswith which instead of only checking whether the string starts or ends with the substring, remove the substring (startswith and endswith have additional "start" and "end" index parameters that may be useful). Or did I overlook anything and there is already a good idiom for this? Btw, in most other languages, "strip" is called "trim" and behaves like Python's strip, i.e. considers the parameter as a set of chars. There is one notable exception: In MySQL, trim behaves like stripstr proposed above (differently to SQLite, PostgreSQL and Oracle). -- Christoph From 1x7y2z9 at gmail.com Thu Jul 17 15:58:56 2008 From: 1x7y2z9 at gmail.com (1x7y2z9 at gmail.com) Date: Thu, 17 Jul 2008 12:58:56 -0700 (PDT) Subject: decorating a method in multiple child classes Message-ID: Say, we have a (parent) class P. It has N child classes C1(P), C2(P) ... CN(P) Each of the child classes defines (differently) a method func(). I wish to decorate all of the CX.func() in the same way. One way to do this is to add a decorator to each of the derived classes. But this is tedious and involves modifying multiple files. Is there a way to modify the parent class and have the same effect? Or some other way neater than the above? Thanks. visual: class P(object): ... class C1(P): def func(self, ...): ... class C2(P): def func(self, ...): ... From atulskulkarni at gmail.com Mon Jul 28 12:28:38 2008 From: atulskulkarni at gmail.com (Atul.) Date: Mon, 28 Jul 2008 09:28:38 -0700 (PDT) Subject: Encoding for Devanagari Script. References: Message-ID: Thanks, Tim that did work. I will proceed with my playing around now. Thanks a ton. Atul. > > Only slightly. You're importing the codecs module > but you're not using it. So you're *actually* using > the built-in open function, which doesn't have an > encoding parameter. It does have a third param > which is to do with the buffer size. > > Just change your code to use codecs.open ("...") > and, I suggest, either use raw strings for your > filename (r"c:\docume...") or use the other kind > of slash ("c:/documen..."). Otherwise you might > run into some problems. > > TJG From fredrik at pythonware.com Mon Jul 21 03:26:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 09:26:50 +0200 Subject: running a script with an input file In-Reply-To: References: Message-ID: David Bikard wrote: > I'd like to run a program so that it reads the input() or raw_input() > statements from an input file instead of > reading from keyboard. I'd also like it to write the print statements in > an output file rather than on the screen. > > I'm on windows XP and when I run: > > prog_name.py input_file output_file > > I get an EOF error. > > What should I do to make this work? Was that supposed to be prog_name.py output_file ? (< and > does i/o redirection; random google link: http://www.ss64.com/ntsyntax/redirection.html If you want to do the same thing from inside the program, you can do: import sys sys.stdin = open("input_file") sys.stdout = open("output_file", "w") before you start reading or writing stuff. From no-spam at no-spam-no-spam.invalid Sun Jul 6 08:40:06 2008 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sun, 06 Jul 2008 14:40:06 +0200 Subject: Hands-on HTML Table Parser/Matrix? Message-ID: Often I want to extract some web table contents. Formats are mostly static, simple text & numbers in it, other tags to be stripped off. So a simple & fast approach would be ok. What of the different modules around is most easy to use, stable, up-to-date, iterator access or best matrix-access (without need for callback functions,classes.. for basic tasks)? Robert From javaboy.ms at gmail.com Mon Jul 21 09:31:40 2008 From: javaboy.ms at gmail.com (sahasranaman) Date: Mon, 21 Jul 2008 06:31:40 -0700 (PDT) Subject: Odd math related issue. References: <43332.3139710867$1216630189@news.gmane.org> <48847F5D.9080509@sellerengine.com> Message-ID: <6472d2d2-1f0e-44af-8bdb-b7e475080e26@v28g2000pro.googlegroups.com> On Jul 21, 5:30?pm, Fredrik Lundh wrote: > Alexandru Palade wrote: > > However, you should be carefully because using an %i modifier for a > > what-should-be a float value truncates the value in a way you may not > > expect. > > > What I mean is that if you have sent 2 out of 3 bytes, the math will be > > 200/3 which with the %i modifier will print 66, rather than 66.6 (or at > > least 67 which is closer - have a look at the round() function). > > My suggested workaround doesn't use floats. ?As for rounding, that's > more of a usability issue -- seeing the download process getting stuck > at 100% can be rather frustrating for the poor user. ?Better truncate > towards zero. > > > Another thing, you could have just added a dot after the constant in > > order to promote the expression to be evaluated as float. As in > > ? ?percentage = bytes_transferred / /self/.__sessions[path].total_bytes > > * 100. > > (notice the last dot) > > Did you try that? > > ?>>> 2 / 3 * 100. > 0.0 > > You can fix this with parentheses, but I usually recommend an explicit > "cast" instead, to make it obvious what you're doing: > > ? ? ?result = float(a) / b > > Use 2.0 / 3 * 100 to solve this. Why make things look bigger? From gandalf at shopzeus.com Tue Jul 1 15:16:57 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 01 Jul 2008 21:16:57 +0200 Subject: convert unicode characters to visibly similar ascii characters In-Reply-To: References: <486A7BB5.3000501@shopzeus.com> Message-ID: <486A82A9.2050008@shopzeus.com> Peter Bulychev wrote: > Thank you for you answer. > > If you only want this to work for a subset, please define that subset. > > Actually, I want to convert only punctuations (dots, commas, hyphens > and so on). Then make your translation table manually and apply this method: unicode.translate Finally print s.encode('ascii') If you get an UnicodeEncodeError then it means you had other (not translated, non-ascii) characters in the original string. Best, Laszlo From python at rcn.com Sat Jul 12 10:11:35 2008 From: python at rcn.com (Raymond Hettinger) Date: Sat, 12 Jul 2008 07:11:35 -0700 (PDT) Subject: Perfect hashing for Py References: Message-ID: On Jul 12, 10:13?am, Raymond Hettinger wrote: > On Jul 11, 3:01?pm, bearophileH... at lycos.com wrote: > > > I have found this perfect hash (minimal too) implementation:http://burtleburtle.net/bob/hash/perfect.html > > > I have already translated part of it to D, and it seems to work well > > enough. As discussed in the PyConDue, I think this may be used in > > frozenset (and frozendict) to build a (minimal too?) perfect hash on > > the fly, to allow (hopefully) faster retrieval of items that don't > > change. I played around with the idea and have a rough implementation sketch: class PerfectSet(collections.Set): __slots__ = ['len', 'hashvalue', 'hashfunc', 'hashtable'] DUMMY = object() def __init__(self, keys, sparseness=0.5): keys = frozenset(keys) self.len = len(keys) self.hashvalue = hash(keys) n = (len(keys) / sparseness) + 1 assert n > self.len self.hashfunc = make_perfect_hash_function(keys, n) self.hashtable = [self.DUMMY] * n for k in keys: self.hashtable[self.hashfunc(k)] = k del __len__(self, k): return self.len def __iter__(self, k) return (k for k in self.hashtable if k is not self.DUMMY) def __contains__(self, k): return self.table[self.hashfunc(k)] is not self.DUMMY The perfect hash function will need to use the regular hash(obj) as a starting point. This helps with non-string types and it preserves existing relationships between __hash__ and __eq__. The construction is more expensive than with regular frozensets so it is only useful when lookups are very common. Playing around with the idea suggests that a sparseness variable for frozensets would largely accomplish the same goal without the overhead of creating and applying a perfect hash function. Sparse hash tables rarely collide. Raymond From jphalip at gmail.com Thu Jul 17 04:13:21 2008 From: jphalip at gmail.com (Julien) Date: Thu, 17 Jul 2008 01:13:21 -0700 (PDT) Subject: Remove some characters from a string Message-ID: <35cff1a6-74f6-4a68-b81e-71d8ff9c4633@a70g2000hsh.googlegroups.com> Hi, I can't seem to find the right regular expression to achieve what I want. I'd like to remove all characters from a string that are not numbers, letters or underscores. For example: >>> magic_function('si_98%u^d at .as-*gf') str: 'si_98udasgf' Would you have any hint? Thanks a lot! Julien From __peter__ at web.de Thu Jul 24 11:25:56 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 Jul 2008 17:25:56 +0200 Subject: repr(string) References: Message-ID: David C. Ullrich wrote: > In article , > Fredrik Lundh wrote: > >> David C. Ullrich wrote: >> >> > I've been saving data in a file with one line per field. >> > Now some of the fields may become multi-line strings... >> > >> > I was about to start escaping and unescaping linefeeds >> > by hand, when I realized that repr() and eval() should >> > do. Hence the question: If s is a string, is repr(s) >> > guaranteed not to contain line breaks? >> >> yes. >> >> just keep in mind that using eval() on untrusted data isn't a very good >> idea. > > Right. This data comes from me, gets put into a file and then > read by me. Someone _could_ corrupt that file, but someone who > could do that could more easily just throw the machine out > the window... You could also use a csv file with a single row. Peter From bruno.42.desthuilliers at websiteburo.invalid Tue Jul 1 08:20:37 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 01 Jul 2008 14:20:37 +0200 Subject: Scope and program structure problems In-Reply-To: References: Message-ID: <486a210f$0$15472$426a34cc@news.free.fr> John Dann a ?crit : > Trying to learn Python here, but getting tangled up with variable > scope across functions, modules etc and associated problems. Can > anyone advise please? > > Learning project is a GUI-based (wxPython) Python program that needs > to access external data across a serial port. > > The first thing that I need the program to do when it starts up is to > check that it can see the serial port, the first step of which is to > check that it can import the pySerial module, and display an > appropriate message in the statusbar of the main frame. (I know there > may be other ways of doing this but this is what I'm trying to do > currently and I'd like to understand how to make this approach work > robustly even if there are other options.) > (snip) > > ----------- > # Can't put serial import code here because there's no GUI yet to send > messages to. > > Class Frame(wx.Frame) > def __init__() > etc > #code to check and use serial port has to go below?? > def CheckSerial() # eg triggered by appropriate menu click event > Try: > import serial > etc > ser = Serial.etc # set ser object as handle to serial port > def UseSerial(): > # Code to perform serial IO > > app=App(wx.App) > app.MainLoop() > > # Can't put serial import code here because it won't execute until > frame closes? > ----------- > > But then I hit another problem. If I set the object ser to point to > the serial port in the CheckSerial function, then it's just got local > scope within the function and can't be seen from the UseSerial > function. > > So I've got 2 questions. The main one is whether there's any way of > explicitly giving the ser object global scope in the code line: > > ser = Serial.etc # set ser object as handle to serial port It is possible - for the python definition of 'global' being 'module-global' - but it's not necessarily the best solution. Look up the doc for the 'global' statement to learn more. Another solution would be to make ser an attribute of your Frame object: class Frame(wx.Frame): def __init__(self): self.serial = None #code to check and use serial port has to go below?? def setup_serial(self) # eg triggered by appropriate menu click event try: import serial except ImportError, e: # display an error message and either crash # or return else: # set self.serial object as handle to serial port self.serial = serial.etc() def use_serial(self): # Code to perform serial IO # won't work if setupSerial failed > And, second, does my overall description above reveal any serious > misunderstanding about how best to handle this sort of problem in > Python? Well... You'd get a very similar result by doing your import at the top-level but within a try/except block, then when you have a gui setup takes appropriate actions. try: import serial serial_import_error = None except ImportError, e: serial = None serial_import_error = e class Frame(wx.Frame): def __init__(self): self.serial = None def setup_serial(self): if serial is None: # display an error message and either crash # or return else: self.serial = serial.whatever() But anyway: I have no real (read : anything requiring any brain-cell) experience writing rich GUI apps in Python, and I haven't done rich GUI programming for four last years at least, so there may be better solutions here. So : Any wxPython guru around ?-) From jm.carp at gmail.com Fri Jul 25 19:09:13 2008 From: jm.carp at gmail.com (jm.carp at gmail.com) Date: Fri, 25 Jul 2008 16:09:13 -0700 (PDT) Subject: tcp socket problem Message-ID: I'm writing a tcp client that grabs data from a server at 32hz. But the connection drops exactly one minute after it's opened. I can get data from the server fine for the first 60s, and then the connection goes dead. What's going on? From tjreedy at udel.edu Sun Jul 27 21:21:10 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 21:21:10 -0400 Subject: Attack a sacred Python Cow In-Reply-To: References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: Russ P. wrote: > On Jul 27, 12:39 pm, Bruno Desthuilliers > All I am suggesting is that the programmer have the option of > replacing "self.member" with simply ".member", since the word "self" > is arbitrary and unnecessary. I presume you are proposing the opposite also, that ".member" would internally be expanded to "self.member". As I said before, that, or something near like it (it is hard to exactly compare underspecified proposals) has be suggested and rejected, even if someone gave you not the exact reference. For one thing, as Guido noted, a single . can be hard to see and easy to miss, depending on one's eyesight, environmental lighting, and exact display medium, including font. I suspect Guido's other reasons have been covered, but I do not want misquote him. I will leave you to search the pydev list archives. > Otherwise, everything would work *EXACTLY* the same as it does now. If I understand you, that would mean that .attribute would raise NameError: name 'self' is not defined if used anywhere where 'self' was not defined. From elessar at nienna.org Fri Jul 11 10:48:53 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 11 Jul 2008 08:48:53 -0600 Subject: Unit Testing Techniques In-Reply-To: References: Message-ID: <487772D5.3050308@nienna.org> I'm by no means a testing expert, but I'll take a crack at it. Casey McGinty wrote: > I'm familiar with the unittest module in Python, however I'm hoping > someone can point me to some examples of more advanced usages of the > framework. For example: > > 1. Using the framework to test a package with nested sub-packages and > modules without having to hard code the location/name of each test module. I've never run into this. > 2. Testing class/methods that depend on file system directory > structures, file data, or values read from system hardware. Rule of thumb: always separate software from hardware. Write mock classes or functions that do your hardware/file access that always return known data (but remember to test for alpha and beta errors--make sure both valid and invalid data are handled correctly). That way you can test the client code that is accessing the hardware. Testing the actual hardware/file access code can get more interesting. If you're just reading files, your test suite should write the test files in setUp, try to read them in the test* methods, then clean up in tearDown. Again, remember to test both good and bad files. In my shop, we do both hardware and software, and testing the comms between them can be a real pain. We've done lots of interesting things like wiring faults into the hardware with switches to connect and disconnect them, recording command sequences, etc., but I expect this is beyond the scope of what you're interested in. Just keep in mind that testing a chunk of code requires at least as much creativity as writing the code in the first place. > 3. Testing class/methods that require simulating functionality from > imported modules. You can do neat things like this: import unittest import mymodule def my_mock_function(): """Returns known values.""" class MyTest(unittest.TestCase): def setUp(self): self._orig_function = mymodule.function mymodule.function = my_mock_function def tearDown(self): # remember to restore the original function # unittest doesn't re-import modules mymodule.function = self._orig_function def test1(self): """Test some code that uses mymodule.""" # etc... The dynamic nature of Python makes this sort of thing much easier than other languages. > 4. Testing graphical interfaces and associated signal callback functions. Again, there are lots of strategies you can use; the specifics depend on you design and the toolkit. 1) You can mock the backend: make sure the right functions get called in response the user actions. 2) Simulate user actions by manually posting events, calling functions, etc. 3) Mock the gui: make sure the backend is calling all the right GUI functions. Try to keep your backend and gui as independent as possible, it will make testing much easier. > > Thank you. > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list I typically make a bunch of different suites that can be run individually, in various combinations, or all together. Testing I/O tends to be very slow, so it's nice to be able to turn of these tests when you're working on other parts of the system. There are many other testing tools besides unittest. The one I use the most is coverage.py, to determine if my test suites are hitting all my code. But you can check out pymock, doctest, nose, etc. too. You may have to use a combination of tools to meet your needs. There is also the Testing in Python mailing list (http://lists.idyll.org/listinfo/testing-in-python). You can probably get some advice there as well. The more specifics you can give, the better. As you solve your testing problems, please take the time to post your solutions (if you can) so we can all learn from your experiences. -Matt From tjreedy at udel.edu Sun Jul 27 14:00:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 14:00:27 -0400 Subject: Rant (was Re: x*x if x>10 In-Reply-To: <1q5p845o2j9htp6vf44u6nqinucsr1numf@4ax.com> References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3g8rF9gfj0U1@mid.uni-berlin.de> <6f3gmaF9moqsU1@mid.uni-berlin.de> <1q5p845o2j9htp6vf44u6nqinucsr1numf@4ax.com> Message-ID: DaveM wrote: > On Sun, 27 Jul 2008 16:57:14 +0200, "Diez B. Roggisch" > You'll have guessed, I'm sure, that I'm not a professional programmer. This > was the third rewrite of a program to match candidate groups to examiners on > a three day course I run, necessitated on this occasion by a change in the > structure of the course. I originally learnt python as I wrote, and some of > the early code was ugly and verbose, so once the current rewrite was working > I took the opportunity to tidy the code up and document it (yes, I know, but > as I said, I'm an amateur). The list concatenation was an itch I couldn't > scratch: > > temp = [] > for value in sessexam.values(): > temp.extend(value) > c_exam = [name for name in set(temp)] #See what I mean about verbose? > c_exam.sort() > return c_exam > > Six lines just didn't feel like it ought to be the best way to do something > so simple. I liked the attempt below better, but was foolish enough to time > it, so that was the end of that. > > return sorted(list(set(reduce(lambda x, y: x+y, sessexam.values())))) > > The current version (below) is a compromise, but I still feel there _ought_ > to be a simple one word command to join multiple lists. There is, as others have posted, but if you are going to dump the lists into a set, there is no need to concatenate them together first, and it is better not to. Just dump them directly into set. > > a = list(set(itertools.chain(*sessexam.values()))) This is a pretty good way of skipping the intermediate long list. Another: a = set() for l in sessexam.values(): a.update(set(l)) If course, if sessexam.values() does not need to be ordered and returns sets instead, the set call in not needed. > a.sort() #As I write I'm wondering if I really need it sorted. Hmm... > return a If you want all in one line... return sorted(set(itertools.chain(*sessexam.values()))) There is no virtue to calling list then .sort, since that is what sorted basically does. def sorted(iterable): tem = list(iterable) tem.sort() return tem tjr tjr From henrik at chamalulu.com Tue Jul 1 19:31:32 2008 From: henrik at chamalulu.com (chamalulu) Date: Tue, 1 Jul 2008 16:31:32 -0700 (PDT) Subject: Attribute reference design References: <6cvlk4F3s90U1@mid.uni-berlin.de> Message-ID: On Jul 2, 1:17 am, Gary Herron wrote: > No need. Also, you can define a class attribute (C++ might call it a > static attribute) and access it transparently through an instance. > > class C: > aClassAttribute = 123 > def __init__(self, ...): > ... > > c = C() > ... do something with c.aClassAttribute ... > Actually, this is why I started too look into the attribute reference mechanics to begin with. Coming from mostly C# development I think it's weird to be able to refer to class attributes (static members) through a class instance (object). But I think I'm getting the picture. Function objects lay flat in memory (some heap...). When defined inside classes they are wrapped in method objects. When refered through classes or class instances they are unbound method objects or bound method objects respectively. Am I on the right track? I still don't get why these methods show up when I dir() a class instance. /Henrik From lists at nanl.de Fri Jul 11 07:50:44 2008 From: lists at nanl.de (Mirko Vogt) Date: Fri, 11 Jul 2008 13:50:44 +0200 Subject: socket-module: different behaviour on windows / unix when a timeout is set In-Reply-To: References: <4874FD50.1070404@nanl.de> Message-ID: <48774914.3040902@nanl.de> Gabriel Genellina wrote: > En Wed, 09 Jul 2008 15:02:56 -0300, Mirko Vogt escribi?: > >> it seems that the socket-module behaves differently on unix / windows >> when a timeout is set. > [...] >> Now I will change the code slightly - to be precise I set a timeout on >> the socket: >> >> >> # test.py >> >> import socket >> sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) >> sock.settimeout(3.0) # <----- >> print 'trying to connect...' >> sock.connect(('127.0.0.1',9999)) >> print 'connected!' >> >> >> # executed on linux >> >> $ python test.py >> trying to connect... >> Traceback (most recent call last): >> File "test.py", line 5, in >> sock.connect(('127.0.0.1',9999)) >> File "", line 1, in connect >> socket.error: (111, 'Connection refused') >> $ >> >> >> # executed on windows >> >>> C:\Python25\python.exe test.py >> trying to connect... >> connected! > > Which Python version? Which Windows version? I've tried 2.3.4, 2.4.4, > 2.5.1 and 3.0a4, all on WinXP SP2, and in all cases I got an exception > (details differ between versions). In no case I could make the > connection succeed when nobody was listening at port 9999, as expected. > Hey, this is strange. Linux: $ python --version Python 2.5.2 $ Windows: C:\Python25>python.exe --version Python 2.5.2 C:\Python25> Mirko From deets at nospam.web.de Thu Jul 10 13:13:46 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 10 Jul 2008 19:13:46 +0200 Subject: Idiomatic Python to convert list to dict In-Reply-To: <7ec9405c-4e6f-491d-84b2-c81152302b13@79g2000hsk.googlegroups.com> References: <7ec9405c-4e6f-491d-84b2-c81152302b13@79g2000hsk.googlegroups.com> Message-ID: <6dmuacF33kciU1@mid.uni-berlin.de> James Fassett schrieb: > Hi all, > > Simple question really on a best practice. I want to avoid adding > duplicates to a list. > > my_list = ['a', 'b', 'c', 'd', 'e'] > dup_map = {} > for item in my_list: > dup_map[item] = True > > # ... sometime later > > for complex_dict in large_list: > if complex_dict["char"] not in dup_map: > my_list.append(complex_dict["char"]) > dup_map[complex_dict["char"]] = True > > For the first part (generating the duplicate map) is there a more > idiomatic Python method for flipping the list into a dict? > > Is there a better way to achieve the overall objective (as hinted at > by the above algorithm)? > > Thanks in advance for any tips. Instead of a dict, use a set. It's immediatly contructable from my_list, and better suited for the task anyway. Diez From kay.schluehr at gmx.net Sun Jul 20 05:08:35 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 20 Jul 2008 02:08:35 -0700 (PDT) Subject: Genetic programming: pygene, pygp, AST, or (gasp) Lisp? References: <7bfb3c41-b08b-49dc-9711-6e39a4667db2@b1g2000hsg.googlegroups.com> Message-ID: On 20 Jul., 09:52, John Ladasky wrote: > Why not do genetic programming directly on Python code? Maybe my code > tree data structure is redundant to something which already exists? > But apparently Python's "_ast" module offers only one-way access -- it > will generate an AST from a piece of code, but you can't modify an > AST, and turn it back into executable code? Why not? You can compile ASTs. Another option is to use EasyExtend http://www.fiber-space.de/EasyExtend/doc/EE.html which is a bit heavyweight though without prior knowledge of the framework. EE provides some generic functions over languages like parse/unparse. Python is just a special case. So you can do the following from EasyExtend.langlets.zero.langlet import parse, unparse src = """ if disc(a) < c: b = f1(a) else: b = f2(a) """ parse(src) # yields a parse tree unparse(parse(src)) # yields the source code of the parse tree Here `zero` means Python which is just the trivial/featureless langlet of the system or some kind of embedding. For meshing fragments together on random one can use cst.py. For each rule in Pythons grammar cst.py implements a corresponding function that produces the parse tree accordingly. So if there is a rule test: or_test ['if' or_test 'else' test] | lambdef a corresponding function test(*args) exists that produces a parse tree from components that were built using or_test(), test() or lambdef(). chaining these functions is just like building s-expr. > I would definitely need > this latter feature. > > ALTERNATELY -- and I don't mention this to start a flame war -- in > pondering this problem I've noticed the frightening fact that Lisp > seems set up to handle genetic programming by design. Definitely. But this is nothing new. Lisp was the original language used by John Koza to implement GP. > The s- > expression syntax IS essentially a parse tree. Now, I've spent a few > hours with Lisp so far, and I can't make it do much of anything -- but > I DO see how Lisp could be helpful. Still, I'm reluctant to pursue a > language I don't know, and which I'm finding much harder to grasp than > any language I've tried before. You can write a primitive s-expr evaluator/manipulator using Pythons overloading capabilities. But this way you will just produce s-expr and not Python functions. Kay From jwahlmann at gmail.com Mon Jul 21 11:51:10 2008 From: jwahlmann at gmail.com (jwahlmann at gmail.com) Date: Mon, 21 Jul 2008 08:51:10 -0700 (PDT) Subject: Weird Python startup behavior between different drives on PowerPC platform References: <616d9012-5b71-43c7-9141-bc4b37072642@y22g2000prd.googlegroups.com> Message-ID: <6c635cef-4605-4fb8-ae0c-7d8161196999@t12g2000prg.googlegroups.com> Bump. Anyone have any ideas on this? My next step is to either link together a static version of the compiler or create a debug version. Thanks, Jon On Jul 18, 11:43 am, jwahlm... at gmail.com wrote: > I'm experiencing some strange behavior when starting up python on a > Debian-based PowerPC platform. Normally, I operate from this platform > with a root file system on an IDE flash drive (/dev/hda1). However, > I'm trying to get my system to run with root on a mechanical SATA > drive (/dev/sda1). Both are installed on a PowerPC board via a PMC > daughter board. > > When running off the flash drive, the Python interpreter loads and > runs just fine. However, when running from SATA, the interpreter > seems to have problems with importing things like site, os, etc. I've > played around with PYTHONHOME to no effect. I even went as far as > setting PYTHONHOME to some off the wall location (so no stdlibs will > load) and invoking Python as: > > host$ PYTHONHOME=/tmp python -d -v -S > # installing zipimport hook > import zipimport # builtin > # installed zipimport hook > Python 2.4.4 (#2, Apr 5 2007, 19:01:44) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2>>> i=0 > > File "", line 1 > i=0 > ^ > SyntaxError: invalid syntax > > > > You'll note that doing something as simple as setting "i=0" results in > a syntax error. If I run the same thing on the IDE flash drive, it > works: > > host$ PYTHONHOME=/tmp python -d -v -S > # installing zipimport hook > import zipimport # builtin > # installed zipimport hook > Python 2.4.4 (#2, Apr 5 2007, 19:01:44) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > > >>> i=0 > > Any ideas?! What could possibly cause a difference of operation > between running from a IDE flash drive (/dev/hda1) vs. SATA (/dev/ > sda1)? Other than toggling hda1 vs. sda1 in /etc/fstab, the > filesystems are being built identically. Could it be that shared > libraries aren't being loaded correctly or fast enough off the SATA > drive vs. flash? Shooting in the dark here... > > Thanks, > Jon Wahlmann From mathieu.prevot at ens.fr Thu Jul 10 18:57:05 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Fri, 11 Jul 2008 00:57:05 +0200 Subject: error with configure (svn 64857) In-Reply-To: <487681e9$0$9745$9b622d9e@news.freenet.de> References: <487681e9$0$9745$9b622d9e@news.freenet.de> Message-ID: <3e473cc60807101557v202235f9s853c3bd2b39087b5@mail.gmail.com> 2008/7/10 "Martin v. L?wis" : >> I have the following error when I run configure: >> >> checking size of wchar_t... configure: error: cannot compute sizeof (wchar_t) >> >> what can I do ? > > Study config.log for the source of the problem. Thank you Martin. How can I remove -lgcc_s and use the Intel equivalent ? configure:21939: checking for wchar_t configure:21970: icc -c -g -O2 conftest.c >&5 conftest.c(123): warning #279: controlling expression is constant if ((ac__type_new_ *) 0) ^ configure:21976: $? = 0 configure:21991: result: yes configure:21998: checking size of wchar_t configure:22306: icc -o conftest -g -O2 conftest.c >&5 ld: library not found for -lgcc_s configure:22309: $? = 1 configure: program exited with status 1 Mathieu From martin at v.loewis.de Thu Jul 10 17:40:57 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 10 Jul 2008 23:40:57 +0200 Subject: error with configure (svn 64857) In-Reply-To: References: Message-ID: <487681e9$0$9745$9b622d9e@news.freenet.de> > I have the following error when I run configure: > > checking size of wchar_t... configure: error: cannot compute sizeof (wchar_t) > > what can I do ? Study config.log for the source of the problem. Regards, Martin From qvx3000 at gmail.com Tue Jul 29 13:56:08 2008 From: qvx3000 at gmail.com (qvx) Date: Tue, 29 Jul 2008 10:56:08 -0700 (PDT) Subject: I CAN connect socket to any localhost port but I shouldn't be able to Message-ID: <13c78fbf-751f-4d70-a012-53aa1eb64e53@79g2000hsk.googlegroups.com> Hi, I don't have server listening on port 8084 but I can open socket to it (and to many other ports, tested for all<8000) import socket def test(port): af, socktype, proto, canonname, sa = socket.getaddrinfo('localhost', port, socket.AF_INET, socket.SOCK_STREAM)[0] s = socket.socket(af, socktype, proto) s.settimeout(1.0) s.connect(('localhost', port)) s.close() # This doesn't throw socket.error, it happily finishes for x in range(1, 8000): test(x) Thanks, Tvrtko From apardon at forel.vub.ac.be Wed Jul 30 05:49:16 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 30 Jul 2008 09:49:16 GMT Subject: Change PC to Win or Windows References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> Message-ID: On 2008-07-21, Derek Martin wrote: > > --tsOsTdHNUZQcU9Ye > Content-Type: text/plain; charset=iso-8859-1 > Content-Disposition: inline > Content-Transfer-Encoding: quoted-printable > > On Sat, Jul 19, 2008 at 02:56:07AM -0700, Lie wrote: >> On Jul 19, 6:14=A0am, Derek Martin wrote: >> > On Fri, Jul 18, 2008 at 03:46:13PM -0700, Joel Teichroeb wrote: >> > Much like the English word "bank" (and numerous others), the term "PC" >> > has come to have several meanings, one of which is the above. =A0You may >> > not like it, but we're pretty much stuck with the term, so you may as >> > well get used to it. >> >> That's not the point,=20 > > It very much IS the point. Language evolves based on common usage > patterns of the people who use it. The term "PC" is commonly used in > English, in the United States and other English speaking countries, to > mean a computer running Microsoft Windows. You mean the same computer is no longer considered a PC if someone install linux on it? -- Antoon Pardon From fuzzyman at gmail.com Fri Jul 25 18:08:20 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Fri, 25 Jul 2008 15:08:20 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> On Jul 24, 6:41?am, Jordan wrote: > Hi everyone, > > I'm a big Python fan who used to be involved semi regularly in > comp.lang.python (lots of lurking, occasional posting) but kind of > trailed off a bit. I just wrote a frustration inspired rant on my > blog, and I thought it was relevant enough as a wider issue to the > Python community to post here for your discussion and consideration. > > This is not flamebait. I love Python, and I'm not out to antagonise > the community. I also realise that one of the issues I raise is way > too ingrained to be changed now. I'd just like to share my thinking on > a misstep in Python's guiding principles that has done more harm than > good IMO. So anyway, here's the post. > > I've become utterly convinced that at least one criticism leveled at > my favourite overall programming language, Python, is utterly true and > fair. After quite a while away from writing Python code, I started > last night on a whim to knock up some code for a prototype of an idea > I once had. It's going swimmingly; the Python Image Library, which I'd > never used before, seems quick, intuitive, and with the all the > features I need for this project. As for Python itself, well, my heart > still belongs to whitespace delimitation. All the basics of Python > coding are there in my mind like I never stopped using them, or like > I've been programming in this language for 10 years. > > Except when it comes to Classes. I added some classes to code that had > previously just been functions, and you know what I did - or rather, > forgot to do? Put in the 'self'. In front of some of the variable > accesses, but more noticably, at the start of *every single method > argument list.* This cannot be any longer blamed as a hangover from > Java - I've written a ton more code, more recently in Python than in > Java or any other OO language. What's more, every time I go back to > Python after a break of more than about a week or so, I start making > this 'mistake' again. The perennial justification for this 'feature' > of the language? That old Python favourite, "Explicit is better than > implicit." > It's damn useful for scoping. You can look in the body of your method and tell whether you are accessing local variables or instance variables. I'm a great fan of self and I'm afraid you're flogging a dead horse on that one. Your point about rich comparison (at least the == != problem) is fair. This one is fixed in Python 3 though I believe. Michael Foord -- http://www.ironpythoninaction.com/ From laredotornado at zipmail.com Wed Jul 30 13:49:58 2008 From: laredotornado at zipmail.com (laredotornado) Date: Wed, 30 Jul 2008 10:49:58 -0700 (PDT) Subject: Possible to have multiple loop variables? Message-ID: <5ff22b51-88e9-405c-aeb9-7b0abe9cf935@r66g2000hsg.googlegroups.com> I don't know why I thought this would work, but I would like to have 3 variables in my for loop per iteration. Those familiar will know that this ms1 = {'managed1':7019:8020,'managed2':7020:8021} for m, lp, ssl_lp in ms1.items(): managedServer = create(m,'Server') print 'creating managed server '+m managedServer.setListenAddress('147.191.71.70') managedServer.setListenPort(lp) managedServer.setEnabled(0) cd('SSL/cgServer') managedServer.setEnabled(1) managedServer.setListenPort(ssl_lp) managedServer.setCluster(clus1) causes File "/export/third-party/etsbea/home/etsbea/tests/wlst/ createcluster.py", line 9 ms1 = {'managed1':7019:8020,'managed2':7020:8021} ^ SyntaxError: invalid syntax How would I set up the ms1 array such that I can use three items per object? Thanks, - Dave From asma61 at dsl.pipex.com Sun Jul 27 15:43:58 2008 From: asma61 at dsl.pipex.com (DaveM) Date: Sun, 27 Jul 2008 20:43:58 +0100 Subject: Rant (was Re: x*x if x>10 References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3qjoF9n3cpU1@mid.uni-berlin.de> Message-ID: On Sun, 27 Jul 2008 19:46:32 +0200, "Diez B. Roggisch" wrote: >As a rule of thumb, don't return objects you didn't create inside a >function from scratch. I wish I'd had that advice when I started learning python. It would have saved me no end of grief. DaveM From ethan at stoneleaf.us Tue Jul 29 20:55:48 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 29 Jul 2008 16:55:48 -0800 Subject: Boolean tests In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8d <87y73kg70u.fsf@benfinney.id.au> Message-ID: <488FBC14.4090003@stoneleaf.us> Matthew Woodcraft wrote: > Ben Finney wrote: > >>No, he retracted the *insult* and restated the *advice* as a distinct >>statement. I think it's quite worthwhile to help people see the >>difference. > > > Ben, it was quite clear from Anders' post that he knows about > __nonzero__ . That's why the so-called advice is insulting. The > original phrasing was just the icing on the cake. > > -M- I got just the opposite -- it seems quite clear to me that Anders did *not* know about __nonzero__, and perhaps doesn't know about double-underscore functions in general... Here's his quote: > Okay, so you have this interesting object property that you often need > to test for, so you wrap the code for the test up in a method, because > that way you only need to write the complex formula once. I'm with > you so far. But then you decide to name the method "__nonzero__", > instead of some nice descriptive name? What's up with that? His last question, "What's up with that?" is the indicator. His comments after that, such as > Even if we find out that C.__nonzero__ is called, what was it that > __nonzero__ did again? reinforce the impression that he is unaware of the double-underscore functions and what they do and how they work. One can find out when they are called with a simple search of the python documentation. > Better dig up the class C documentation and find out, because there is > no single obvious interpretation of what is means for an object to > evaluate to true. If you are using somebody else's code, and maybe even your own, you should always check the docs if you don't know/can't remember what a function does. ~Ethan~ From Lie.1296 at gmail.com Sat Jul 19 05:23:11 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 19 Jul 2008 02:23:11 -0700 (PDT) Subject: Rotating a cube References: <3d47df08-9734-4e0f-96ad-37da445b4faf@34g2000hsh.googlegroups.com> Message-ID: <8156f68a-3f65-4fca-a725-2e0c4240abd1@v21g2000pro.googlegroups.com> On Jul 17, 3:11?pm, J-Burns wrote: > On Jul 17, 12:53 pm, Fredrik Lundh wrote: > > > J-Burns wrote: > > > Is there a built in Python function for this? > > > for answering questions that have nothing to do with programming, and > > looks quite a bit like homework? ?don't think they've added that one yet. > > > maybe you should look for a geometry newsgroup/forum? > > > > > I meant to ask how would you do this in Python... :S The same as you do it in any other languages. This question is marked correctly as having no relationship to python whatsoever. You'd get a better answer if you asked in mathematics/geometry group, many mathematician are adept programmer as well. From tjreedy at udel.edu Fri Jul 11 14:51:07 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 Jul 2008 14:51:07 -0400 Subject: Python 3.0 and removal of the 'string' module In-Reply-To: <87abgorgiv.fsf@benfinney.id.au> References: <87wsjtqiyo.fsf@benfinney.id.au> <87iqvdq6qz.fsf@benfinney.id.au> <487706b7$0$9695$9b622d9e@news.freenet.de> <87abgorgiv.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > "Martin v. L?wis" writes: > >>> This is rather disappointing. Is that entire page suspect? >> All documentation about Python 3 is suspect until Python 3 gets >> actually released (nobody can say for sure how the release will >> look like in all details). > > Is there a better information source, then, for the current state of > what's expected in Python 3.0? Start with the actual beta release. That is what is there. There are a few tweaks that might happen, and a few modules that might be added, and some bugs that should be fixed. The issue tracker has information on the day-to-day state of most of these. From robert.kern at gmail.com Tue Jul 8 16:11:01 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 08 Jul 2008 15:11:01 -0500 Subject: Logging to zero or more destinations In-Reply-To: References: Message-ID: samwyse wrote: > In the Python 2.5 Library Reference, section 14.5.3 (Logging to > multiple destinations), an example is given of logging to both a file > and the console. This is done by using logging.basicConfig() to > configure a log file, and then calling > logging.getLogger('').addHandler(console) to add the console. > > However, in section 14.5.4 (Sending and receiving logging events > across a network), a call is made to > rootLogger.addHandler(socketHandler), and later it is stated that "On > the client side, nothing is printed on the console". > > Finally, back in section 14.5.2 (Basic example), it's stated that "by > default, the root logger is configured to only handle messages with a > severity of WARNING or above. The message format is also a > configuration default, as is the output destination of the messages - > sys.stderr." > > The only way that I can see for all three statements to be consistent > is that the root logger starts with an empty list of handlers, and > doesn't instantiate a default handler until either > logging.basicConfig() is called, or the first time that a message is > logged. This would also seem to imply that there's no way to use an > empty handler list (say, if you want to suppress all logging), because > the root handler will instantiate a handler for you. Is this correct? Sort of. Your analysis of what happens is entirely correct (see below). However, a way to suppress all logging is to have a single Handler where the emit() method does nothing. Or you can set the level above CRITICAL. $ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> logging.warn('foo') WARNING:root:foo >>> logger = logging.getLogger() >>> logger.handlers [] >>> $ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> logger = logging.getLogger() >>> logger.handlers [] >>> logging.basicConfig() >>> logger.handlers [] >>> logger.handlers = [] >>> class NullHandler(logging.Handler): ... def emit(self, record): ... pass ... >>> logger.addHandler(NullHandler()) >>> logging.warn('foo') >>> > P.S. I tried researching this further by myself, but the logging > module doesn't come with source (apparently it's written in C?) and I > don't have the time to find and download the source to my laptop. No it's all Python. Look in c:\Python25\Lib\logging\ . -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From yuxi at ece.gatech.edu Fri Jul 4 01:10:57 2008 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Fri, 04 Jul 2008 01:10:57 -0400 Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: <87b10cf3-4fd4-46e3-a33a-528f1180f69a@s21g2000prm.googlegroups.com> References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> <9cdbb215-d427-4694-a455-f2571ad42390@x19g2000prg.googlegroups.com> <54e0e7c5-113e-4296-a62f-e649d6ffa2d6@z66g2000hsc.googlegroups.com> <87b10cf3-4fd4-46e3-a33a-528f1180f69a@s21g2000prm.googlegroups.com> Message-ID: Ali Servet D?nmez wrote: > > I tried code come completion options in Emacs for Python, but none of > them was satisfactory to me. I'd be glad to hear how did your friend > get it work though. Perhaps it would help to say what ways the completion in Emacs was not satisfactory? FWIW, it should be possible to get IPython-type completion in Emacs, but I hadn't managed that yet :( Refactoring, too. Both involve Pymacs but I've had limited success with that. As for PyDev (I know you said "No" to this already), the main problem I have with PyDev/Eclipse is the woefully underpowered editor (compared to Emacs), and poor indentation logic. On the plus side, refactoring works pretty well. So why not PyDev? I'm just wondering, you insist on Free/Libre software solutions, and say the ones you tried don't work for you. Why not "use the source" and fix them so they work your way? ;) To quote you: "how hard it could be be writing a freesoftware which would automatically/intelligently auto complete Python code?" From ethan at stoneleaf.us Tue Jul 22 10:43:31 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 22 Jul 2008 06:43:31 -0800 Subject: Python Written in C? In-Reply-To: <143349c3-b0e9-49d8-9426-8b030b23d2c9@l42g2000hsc.googlegroups.com> References: <143349c3-b0e9-49d8-9426-8b030b23d2c9@l42g2000hsc.googlegroups.com> Message-ID: <4885F213.2030101@stoneleaf.us> Iain King wrote: > On Jul 21, 6:58 am, "Krishnakant Mane" wrote: > >> First off all c# is absolute rubbish waist of time. if I need to >> learn it then I better lern java or pythonfor that matter. and by the >> way what is a "real programmer?" > > The story of a Real Programmer: > > http://www.pbm.com/~lindahl/mel.html > > Iain Wow. Awesome story. ~Ethan From sturlamolden at yahoo.no Fri Jul 25 16:21:53 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 25 Jul 2008 13:21:53 -0700 (PDT) Subject: 2d graphics - what module to use? References: Message-ID: <5035d4cb-1976-47d5-8887-4e8381407a7b@m44g2000hsc.googlegroups.com> On Jul 25, 8:13?am, Pierre Dagenais wrote: > What is the easiest way to draw to a window? I'd like to draw something > ? like sine waves from a mathematical equation. > Newbie to python. For mathematica equations, NumPy and matplotlib is probably the best option. I prefer to embed matplotlib in wxPython. wxAgg is an excellent backend. For more general 2D graphics, there are several options, including: - pygame (uses SDL) - aggdraw module - pycairo - pyopengl - wxPython's device context (ditto for other GUI libraries) From kirby.urner at gmail.com Sat Jul 12 22:41:15 2008 From: kirby.urner at gmail.com (kirby.urner at gmail.com) Date: Sat, 12 Jul 2008 19:41:15 -0700 (PDT) Subject: New TTF fonts in IDLE on Linux question Message-ID: So I'm using this Akbar font, a truetype, related to Simpsons, for coding in Python, just for kicks (looks pretty good actually). No prob on Windows, but when I sudo cp akbar.ttf to /usr/share/fonts/ truetype/ttf-misc, a directory I made myself (root root), then OpenOffice and WingWare find it right away, but IDLEs in Python 2.5 and 3.0 don't seem to see it. Is there some special place IDLE looks for fonts that I'm missing? http://worldgame.blogspot.com/2008/07/idle-language-games.html http://www.flickr.com/photos/17157315 at N00/2662994560/ Kirby From sjmachin at lexicon.net Thu Jul 31 16:41:38 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 31 Jul 2008 13:41:38 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> <4609709f-dc0f-47cc-905e-1552a02ec3b6@r15g2000prd.googlegroups.com> Message-ID: <416f2710-1295-4d8b-a356-98fd9e9a56ad@j7g2000prm.googlegroups.com> On Jul 31, 11:54 pm, william tanksley wrote: > John Machin wrote: > > william tanksley wrote: > > > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" > > > 1. This isn't Unicode; it's missing the u"" (I printed using repr). > > > 2. It's got the UTF-8 bytes there in the middle. > > > In addition to the above results, > > *WHAT* results? I don't see any repr() output, just your > > interpretation of what you think you saw! > > That *is* the repr. I said it's the repr, and it IS. It's not an > interpretation; it's a screenscrape. Really, truly. If I paste it in > again it'll look the same. > > What do you want? Can I post something that will convince you it's a > repr? > Let's try again: >> # track_id = url2pathname(urlparse(track_id).path) >> print repr(track_id) >> parse_result = urlparse(track_id).path >> print repr(parse_result) >> track_id_replacement = url2pathname(parse_result) >> print repr(track_id_replacement) > The "important" value here is track_id_replacement; it contains the > data that's throwing me. It appears that some UTF-8 characters are > being read as multiple bytes by ElementTree rather than being decoded > into Unicode. > Here's one example. The others are similar -- they have the same > things that look like problems to me. > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" ROTFL! I thought the Buffett thing was a Windows filename! What I was expecting was THREE lots of repr() output, and I'm quite unused to seeing repr() output with quotes around it instead of apostrophes; how did you achieve that? So you're saying that track_id_replacement contains utf8 characters. It is obtained by track_id_replacement = url2pathname(parse_result). You don't show us what is in parse_result. url2pathname() is nothing to do with ElementTree. urlparse() is nothing to do with ElementTree. You have provided no evidence that ElementTree is doing what you accuse it of. Please try again. Backtrack in your code to where you are pulling the url out of an element. Do print repr(some_element.some_attribute). Show us. From semanticist at gmail.com Sun Jul 13 22:37:06 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 22:37:06 -0400 Subject: socket.connect() hangs in SYN_SENT state. In-Reply-To: References: Message-ID: On Sun, Jul 13, 2008 at 10:29 PM, Miles wrote: > On Sat, Jul 12, 2008 at 11:23 PM, bukzor wrote: >> Anyone know a general reason this might happen? Even better, a way to >> fix it? > > Maybe your client has an unusually low socket timeout for some reason, > though; does increasing it (with socket.setdefaulttimeout) help? Never mind on that, as you already said that it hangs for about two minutes. Clearly my reading comprehension and retention rate are at an all-time low today. low-signal-to-noise-ratio-ly yours, Miles From pavlovevidence at gmail.com Tue Jul 15 12:39:02 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 15 Jul 2008 09:39:02 -0700 (PDT) Subject: Suggestion: Python global scope References: Message-ID: On Jul 15, 7:57?am, Anonymous Bastard wrote: > I've been tossing this idea in my mind for some time now: > > In Python, declaring a variable using the global statement automatically > makes it available in all subsequent scopes. > > But to me, it makes more sense to use the global statement to 'import' a > variable from the global scope into the current scope. No way. You'd need to find another keyword. "localize" might be a better word to use. > For instance: > > [code] > global X > X = 1 > > def P(): > ? ? ?X = 2 > ? ? ?print X > ? ? ?global X > ? ? ?print X > > print X > P() > print X > [code] > > Currently, this will print 1, 2, 2 and 2. But if global would be limited > to current scope, it would print 1, 2, 1, 1. What would it print if you changed P to this? def P(): X = 2 print X global X print X X = 3 Would it print 1, 2, 1, 1 or 1, 2, 1, 3? > 'X = 2' would work on the local version of X, 'global X' will 'import' > the global X into the local scope, so any actions on X would reference > the global X, rather than previous X. Do you have a specific use case in mind? Where would this sort of thing be useful? (The be sure, I can think of a use case for something like this, namely optimizing away hash lookups for frequently used globals. But such an optimization doesn't justify new syntax, especially when you can already do it only slightly less conveniently.) Carl Banks From __peter__ at web.de Fri Jul 18 07:13:18 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 13:13:18 +0200 Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: nicolas.pourcelot at gmail.com wrote: > In fact, 'any(myobject is element for element in mylist)' is 2 times > slower than using a for loop, and 'id(myobject) in (id(element) for > element in mylist)' is 2.4 times slower. This is not a meaningful statement unless you at least qualify with the number of item that are actually checked. For sufficently long sequences both any() and the for loop take roughly the same amount of time over here. $ python -m timeit -s"items=range(1000); x = 1000" "any(x is item for item in items)" 1000 loops, best of 3: 249 usec per loop $ python -m timeit -s"items=range(1000); x = 1000" "for item in items:" " if x is item: break" 1000 loops, best of 3: 276 usec per loop $ python -m timeit -s"items=range(1000); x = 0" "any(x is item for item in items)" 100000 loops, best of 3: 3 usec per loop $ python -m timeit -s"items=range(1000); x = 0" "for item in items:" " if x is item: break" 1000000 loops, best of 3: 0.317 usec per loop Peter PS: Take these numbers with a grain of salt, they vary a lot between runs. From fredrik at pythonware.com Fri Jul 25 03:57:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 09:57:58 +0200 Subject: file operations. In-Reply-To: <73045cca0807241546k3697a77cs999bad6d62867167@mail.gmail.com> References: <73045cca0807241546k3697a77cs999bad6d62867167@mail.gmail.com> Message-ID: aditya shukla wrote: > Guys thanks for your previous help .I have a doubt again (I'm sure you mean "a question"; in english, "a doubt" is something slightly different, and quite often more negative.) > Also , because of this i am not able to extract the floating point > values ie 0.50,0.50,0.66 respectively > cause when i use the proposed solution given earlier > > data=[] > for line in x: print repr(line) # added for debugging! > line=line.split("|") > data.append(float(line[-2])) --> i am trying to get the floating > point values from the back > > i receive this error message > > Traceback (most recent call last): > File "", line 3, in > d.append(float(line[-2])) > IndexError: list index out of range one or more lines in your file doesn't match the description; try adding a print statement (see above) to see what they might look like, and make sure that you filter them out (e.g. by checking the size of the list you get from the split, as Terry explains). From mmaccana at au1.ibm.com Wed Jul 23 20:54:51 2008 From: mmaccana at au1.ibm.com (Mike MacCana) Date: Thu, 24 Jul 2008 10:54:51 +1000 Subject: Proper way to query user and group database on a Unix host? In-Reply-To: References: <1216792038.7380.7.camel@mmaccana-laptop> Message-ID: <1216860891.7380.14.camel@mmaccana-laptop> On Wed, 2008-07-23 at 09:13 +0200, Fredrik Lundh wrote: > http://mail.python.org/mailman/listinfo/python-list Thanks - in the midst of trying to filter out search results for every damn python 'user group' 'yahoo group' 'interest group' etc, I seem to have missed this. Thanks to the other posters too. Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjw at ncf.ca Tue Jul 29 09:50:27 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Tue, 29 Jul 2008 09:50:27 -0400 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <200807291115.05701.modelnine@modelnine.org> Message-ID: Heiko Wundram wrote: > Am Dienstag, 29. Juli 2008 11:15:05 schrieb Heiko Wundram: >> I can't dig up a simple example from code I wrote quickly... > > Just to get back to that: an example I found where "if x" (the generic > __nonzero__() test) will work to test for emptiness/non-emptiness of a > container, whereas "if len(x) > 0" (the "specific" test for this example) > will not, is my for own integer set type I wrote a while back (which you can > find on ASPN). > > The corresponding set type allows you to create infinitely sized sets of > integers (which of course are stored as pairs of ,-values, so > the storage itself for the set is bounded), for which len(x) does not have > a "proper" meaning anymore, and __len__() is limited to returning a (platform > dependent) ssize_t anyway IIRC, so even with a bounded set, the length of the > set might not necessarily be accessible using len(x); that's why the set type > additionally got a member function called .len() to work around this > restriction. > > I should think is a non-contrieved example where the generic test whether the > object considers itself True/False (which for containers means > non-empty/empty) is preferrable over the special case test whether the length > is positive. A polymorphic function, which for example only accesses the > first ten members of the container is able to work with an infinite set if it > uses the generic test, but is not in case it uses len(x) > 0. > (+1) This an Heiko's previous post sets things out clearly. Colin W. From gherron at islandtraining.com Tue Jul 29 00:18:24 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 28 Jul 2008 21:18:24 -0700 Subject: exec(code) not allowing import on top level? In-Reply-To: References: Message-ID: <488E9A10.7040208@islandtraining.com> Peter Teuben wrote: > > if I define a simple string code, with the following contents: > > import math > def foo(x): > return math.sqrt(x) What? You have not told us something important here. First, that code won't fail because it does not even execute the function foo -- it just defines it. Second, if I extended your string with one more line "foo(123)" to actually execute the code, it still works as expected. So let's try this again... and this time please please also show us the full text of the error message. Gary Herron > > and i run it using exec(code) in python, math is not known. But when I > recode the string as: > > def foo(x): > import math > return math.sqrt(x) > > it works fine. That seemed like an inconsistency, since it works > fine otherwise, as expected. It's easy to work around, but > just odd to find this out. > > thanks > > peter > -- > http://mail.python.org/mailman/listinfo/python-list From swiftone at swiftone.org Sat Jul 26 14:32:36 2008 From: swiftone at swiftone.org (Brett Ritter) Date: Sat, 26 Jul 2008 11:32:36 -0700 (PDT) Subject: Simple Path issues Message-ID: <7bef6df9-45d6-4ef6-b802-1dd201ec66e3@k30g2000hse.googlegroups.com> New to Python, and I have some questions on how to best set up a basic development environment, particular relating to path issues. Note: I am not root on my development box (which is some flavor of BSD) Where should I develop my own modules so as to refer to them in the standard way. I.E. I want: import proj to work regardless of my current working directory, and to function as if "proj" were a core or third-party module. I saw that I can set PYTHONPATH, but that seems sub-prime. I noted that in installing pysqlite (the local installation of python is 2.4) that I had it install in a lib under my home dir...should I use that locale? What is the command to tell me what directories python is checking in? While I'm at it, what is the best (read: standard) locale to stick my test cases? same dir as my project? A subdir? Thanks in advance From sturlamolden at yahoo.no Fri Jul 25 16:05:31 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 25 Jul 2008 13:05:31 -0700 (PDT) Subject: Python program as daemon? References: <8bb6bd1a-cd85-4b7a-8fc9-844f3794bca0@c58g2000hsc.googlegroups.com> Message-ID: <13866da4-01ed-4330-8297-8bdecce1393a@x35g2000hsb.googlegroups.com> On Jul 25, 8:37?pm, Johny wrote: > Is it possible to run a Python program as daemon? > Thanks Here is an example on how to run a Python script as a Unix daemon: http://svn.plone.org/svn/collective/bda.daemon/trunk/bda/daemon/daemon.py Basically it forks twice and redirects open file descriptors to /dev/ null. On Windows, 'daemons' are called services. You can write Windows services in Python using the Pywin32 extension. See Mark Hammond's book for an explanation. From afriere at yahoo.co.uk Wed Jul 16 23:05:47 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Wed, 16 Jul 2008 20:05:47 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Message-ID: <30e884cf-a52e-4d74-8e2a-fc1f185ef7c2@d45g2000hsc.googlegroups.com> On Jul 17, 8:20 am, Craig Allen wrote: > Is it pythonic? You probably can't get anymore pythonic than something written by the BDFL. In describing the use of __new__ in Unifying types and classes in Python 2.2 he gives this recipe for a Singleton. class Singleton(object): def __new__(cls, *args, **kwds): it = cls.__dict__.get("__it__") if it is not None: return it cls.__it__ = it = object.__new__(cls) it.init(*args, **kwds) return it def init(self, *args, **kwds): pass You might find this a useful starting point. From peter.anderson at internode.on.net Wed Jul 16 02:47:53 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Wed, 16 Jul 2008 16:47:53 +1000 Subject: Python internals question In-Reply-To: <487cc4bb$0$2855$ba620e4c@news.skynet.be> References: <487cc4bb$0$2855$ba620e4c@news.skynet.be> Message-ID: <008d95ab$0$15868$c3e8da3@news.astraweb.com> Helmut Jarausch wrote: > > Please have a look at > ... > http://rg03.wordpress.com/2007/04/21/semantics-of-python-variable-names-from-a-c-perspective/ > Helmut, I found the second reference (the one above) very useful thank you. Most other respondents to my original question did not seem to understand what I was asking or didn't read the question and simply proceeded to re-state what I had quoted from Beazley - well I understood what he was saying, I simply wanted to find out how Python did it at a lower level. Your reference answered the question ;-) Thanks, Peter -- Peter Anderson There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things -- Niccolo Machiavelli, The Prince, ch. 6 From mcl.office at googlemail.com Mon Jul 7 13:39:42 2008 From: mcl.office at googlemail.com (mcl) Date: Mon, 7 Jul 2008 10:39:42 -0700 (PDT) Subject: Confused yet again: Very Newbie Question References: <13be8c54-3fa9-4a37-a0e6-45bb019bff7e@a1g2000hsb.googlegroups.com> <593b44b7-9a0a-4665-9926-19890d29eabe@2g2000hsn.googlegroups.com> Message-ID: On Jul 7, 5:07?pm, Dennis Lee Bieber wrote: > On Mon, 7 Jul 2008 05:41:22 -0700 (PDT), mcl > declaimed the following in comp.lang.python: > > > My use of classes is because I want two classes one for ?global > > variables and one for global functions. > > ? ? ? ? Which seems to violate the entire reason for using "classes" (and > sounds like something that Java's syntax forces upon one). Classes (and > instances of them) are typically defined to /combine/ the class/instance > specific data and the functions that operate upon that data into a > single object. > > ? ? ? ? If you just need a container for so-called "global" data, create a > module. Same for utility functions. > > -=-=-=-=-=- ? ? ? ? ? ? myGlobalData.py > > something = 1 > else = 3 > > -=-=-=-=-=- ? ? ? ? ? ? myUtilityFuncs.py > > def weird(a, b): > ? ? ? ? return (a-b, b-a, a*b, a/b, float(a)/b) > > -=-=-=-=-=- ? ? ? ? ? ? main.py > > import myGlobalData > import myUtilityFuncs > > results = myUtilityFuncs.weird(myGlobalData.something, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? myGlobalData.else) > print results > myGlobalData.something = results[2] > > > A function may set multiple global variable values, so what is the > > best way to do this as 'return' only appears to be able to set one > > value. > > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ Dennis, Thank you for this reply. You are correct in what I was trying to do and thank you for your very good example. I will now rewrite my code changing classes to modules, which make more sense to me, even if it is not proper Python. I am much wiser about classes, but still a long way from fully comprehending when and where to best use them. Thank you all for your replies and links, as it solved my problems enough, to get some code working. Richard From nagle at animats.com Wed Jul 30 14:22:12 2008 From: nagle at animats.com (John Nagle) Date: Wed, 30 Jul 2008 11:22:12 -0700 Subject: How can I check nbr of cores of computer? In-Reply-To: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> Message-ID: <4890acd6$0$17215$742ec2ed@news.sonic.net> defn noob wrote: > How can I check how many cores my computer has? > Is it possible to do this in a Python-app? Why do you care? Python can't use more than one of them at a time anyway. John Nagle From gherron at islandtraining.com Mon Jul 21 15:20:44 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 21 Jul 2008 12:20:44 -0700 Subject: Converting List of String to Integer In-Reply-To: References: Message-ID: <4884E18C.8060302@islandtraining.com> Samir wrote: > Hi Everyone, > > I am relatively new to Python so please forgive me for what seems like > a basic question. > > Assume that I have a list, a, composed of nested lists with string > representations of integers, such that > > a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > > I would like to convert this to a similar list, b, where the values > are represented by integers, such as > > b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > I have unsuccessfully tried the following code: > > n = [] > for k in a: > n.append([int(v) for v in k]) > print n > > Does anyone know what I am doing wrong? > > Thanks in advance. > > Samir > -- > http://mail.python.org/mailman/listinfo/python-list > You didn't tell us how it failed for you, so I can't guess what's wrong. However, your code works for me: >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] >>> n = [] >>> for k in a: ... n.append([int(v) for v in k]) ... >>> print n [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] (Although you seem to have confused variables b and n.) Gary Herron From robert.kern at gmail.com Mon Jul 7 17:58:32 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 07 Jul 2008 16:58:32 -0500 Subject: Standard Equation Description Language? In-Reply-To: <1cd1baf2-9816-4ac1-91ea-90f148167549@t54g2000hsg.googlegroups.com> References: <1cd1baf2-9816-4ac1-91ea-90f148167549@t54g2000hsg.googlegroups.com> Message-ID: xkenneth wrote: > Does anyone know of a standard inter-language syntax for describing > scientific/mathematical equations? Preferably something with parsers > in multiple libraries. MathML http://www.w3.org/Math/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From alexnbryan at gmail.com Tue Jul 15 20:58:49 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 15 Jul 2008 17:58:49 -0700 (PDT) Subject: Testing for connection to a website In-Reply-To: References: <18473382.post@talk.nabble.com> <18476597.post@talk.nabble.com> Message-ID: <18478103.post@talk.nabble.com> Timothy Grant wrote: > > On Tue, Jul 15, 2008 at 3:48 PM, Alexnb wrote: > >> >> >> >> Alexnb wrote: >> > >> > Okay, I already made this post, but it kinda got lost. So anyway I need >> to >> > figure out how to test if the user is able to connect to a specific >> > website. Last time I got pointed to the urllib2 page, but if I do >> > urlopen() and and am not connected, the program stops. So I don't know >> if >> > that was what you guys wanted me to do, but I don't think so, you guys >> are >> > smarter than that. So, how can I test for connection to a website. >> > >> >> Just for anyone looking this up later here is code that works :) >> >> from urllib2 import * >> import urllib2 >> e = '' >> >> req = urllib2.Request('http://www.dictionary.com') >> try: >> response = urlopen(req) >> >> except HTTPError, e: >> print e.code >> except URLError, e: >> print e.reason >> >> if e == '': >> print "good to go" >> -- >> View this message in context: >> http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p18476597.html >> Sent from the Python - python-list mailing list archive at Nabble.com. >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > I'm glad to see you found the old post and implemented the code suggested > there. > > -- > Stand Fast, > tjg. [Timothy Grant] > > -- > http://mail.python.org/mailman/listinfo/python-list > well I can tel you it didn't work for me. In fact I didn't see the code you posted on there, I ended up figuring it out on my own with a little help from the missing manual for urllib2. Also, being rude is kinda stupid because you don't have to help in the first place... -- View this message in context: http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p18478103.html Sent from the Python - python-list mailing list archive at Nabble.com. From kyosohma at gmail.com Fri Jul 18 16:51:08 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 18 Jul 2008 13:51:08 -0700 (PDT) Subject: Writing a program under GNU/Linux for MS Windows. References: Message-ID: <492dfb6f-9bbe-48f6-935d-b68ef63784c2@e39g2000hsf.googlegroups.com> On Jul 18, 3:26?pm, Levi Campbell wrote: > Hi, I'm trying to write a program for a friend of mine who uses > windows but I use GNU/Linux. I know you can use mingw and link to the > python dll, but is there a way to create a win32 service under Linux? Technically, you can probably write the code for the service in Linux, but I doubt you could test it. Here are some links on the subject, though: http://essiene.blogspot.com/2005/04/python-windows-services.html http://agiletesting.blogspot.com/2005/09/running-python-script-as-windows.html Mike From pfreixes at gmail.com Tue Jul 1 08:25:18 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Tue, 1 Jul 2008 14:25:18 +0200 Subject: Embedding Python In-Reply-To: References: Message-ID: <207312b70807010525m3a8e3acdj352a0b3c7d1a4f7d@mail.gmail.com> Hi If PyImport_ExecCodeModule have a two parameteres and second parameter is PyObject type why you are make a call with a unsigned char value ? If you search this function name into Google you will can found some examples, use for example PyMarshal_ReadObjectFromString or PyMarshal_ReadObjectFromFile Bye On Tue, Jul 1, 2008 at 11:36 AM, Marcin Krol wrote: > Hello everyone, > > I'm trying to embed Python interpreter in C code, but in a specific way: > loading compiled bytecode into a memory location and executing it (don't > ask why, complicated reasons). > > PyImport_ExecCodeModule seems like obvious candidate, docs say: > > "Given a module name (possibly of the form package.module) and a code > object read from a Python bytecode file or obtained from the built-in > function compile(), load the module." > > Code: > > ---cut--- > #include > #include > #include > #include > #include > > > int load_file(char *fname, unsigned char** result) > { > int size = 0; > FILE *f = fopen(fname, "rb"); > if (f == NULL) > { > *result = NULL; > return -1; > } > fseek(f, 0, SEEK_END); > size = ftell(f); > *result = (unsigned char *) malloc(size+1); > fseek(f, 0, SEEK_SET); > size = fread(*result, sizeof(unsigned char), size, f); > return size; > } > > int main(int argc, char **argv) > { > int size; > unsigned char *python_code; > PyObject *mainobj; > size = load_file("multiply.pyc", &python_code); > > Py_Initialize(); > mainobj = PyImport_ExecCodeModule("multiply", (PyObject *) > python_code); > Py_Finalize(); > > } > ---cut--- > > Compiling it following way works fine: > > ${CC} testit.c -g -o testit -I/usr/include/python2.4 -lpython2.4 -lm > -lutil -lpthread -ldl -L/usr/lib/python2.4/config > > > However, the damn thing crashes on this call: > > 33 mainobj = PyImport_ExecCodeModule("multiply", (PyObject > *) python_code); > (gdb) n > > Program received signal SIGSEGV, Segmentation fault. > 0x0804e7f6 in PyImport_ExecCodeModuleEx () > > The .pyc file woks just fine in Python interpreter: > > import multiply >>>> multiply.multiply() >>>> >>> The result of 12345 x 6789 : 83810205 > 83810205 > >> >>>> > > What I am doing wrong? Please help. > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Fri Jul 25 13:07:35 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 25 Jul 2008 10:07:35 -0700 (PDT) Subject: POP3 - Using poplib only shows the first few hundred messages in the mailbox References: <503aa944-bbf6-4d86-bd98-b58adcd5a2bd@y22g2000prd.googlegroups.com> Message-ID: On Jul 25, 1:18?pm, SteveC wrote: > Hello, > > I am trying to use POP3_SSL class of the poplib module to read email > from my gmail account. ?I can connect just fine using the example herehttp://www.python.org/doc/lib/pop3-example.html > > import getpass, poplib > > M = poplib.POP3('localhost') > M.user(getpass.getuser()) > M.pass_(getpass.getpass()) > numMessages = len(M.list()[1]) > for i in range(numMessages): > ? ? for j in M.retr(i+1)[1]: > ? ? ? ? print j > > That is the above sample code from the python doc. ?While everything > works fine, the problem is that when I use the list() function it only > returns about 400 messages starting from the beginning of my inbox. ?I > have probably 10,000 emails in my gmail account. ?I don't see any pop3 > object functions to "move" around the inbox or anything of the like. > > Could someone point me in the right direction? ?I'm sure there must be > something simple I am missing. > That's a lot of emails! :-) I had a quick look at poplib.py and I couldn't see any limit in the code itself. Perhaps it's the gmail server that's doing it. Can you retrieve the later messages, eg have you tried M.retr(500)? If you can then you could just try retrieving messages beyond what M.list() says until it says there's no such message. From malaclypse2 at gmail.com Tue Jul 15 09:31:08 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 15 Jul 2008 09:31:08 -0400 Subject: Python embedding question. In-Reply-To: References: Message-ID: <16651e80807150631m1b1a5b75t34fbdbbb006b9910@mail.gmail.com> On Tue, Jul 15, 2008 at 5:51 AM, Thomas Troeger wrote: > Or is there a method to have gzipped > modules that are unzipped on the fly into memory when they're accessed? That > would be even better. Yes. See the documentation for the zipimport module, and PEP 273. http://docs.python.org/lib/module-zipimport.html http://www.python.org/dev/peps/pep-0273/ -- Jerry From sbcook at gmail.com Fri Jul 25 08:18:44 2008 From: sbcook at gmail.com (SteveC) Date: Fri, 25 Jul 2008 05:18:44 -0700 (PDT) Subject: POP3 - Using poplib only shows the first few hundred messages in the mailbox Message-ID: <503aa944-bbf6-4d86-bd98-b58adcd5a2bd@y22g2000prd.googlegroups.com> Hello, I am trying to use POP3_SSL class of the poplib module to read email from my gmail account. I can connect just fine using the example here http://www.python.org/doc/lib/pop3-example.html import getpass, poplib M = poplib.POP3('localhost') M.user(getpass.getuser()) M.pass_(getpass.getpass()) numMessages = len(M.list()[1]) for i in range(numMessages): for j in M.retr(i+1)[1]: print j That is the above sample code from the python doc. While everything works fine, the problem is that when I use the list() function it only returns about 400 messages starting from the beginning of my inbox. I have probably 10,000 emails in my gmail account. I don't see any pop3 object functions to "move" around the inbox or anything of the like. Could someone point me in the right direction? I'm sure there must be something simple I am missing. Thanks, Steve From goldfita at signalsguru.net Mon Jul 7 09:02:31 2008 From: goldfita at signalsguru.net (Todd) Date: Mon, 7 Jul 2008 06:02:31 -0700 (PDT) Subject: python mysteriously halts Message-ID: <13a33043-21d1-40c0-a938-6e905d958064@m3g2000hsc.googlegroups.com> Hello everyone, I ran a python script last night which connects to a matlab automation server via DCOM (using win32com). I expected to see the results when I came in this morning. But apparently, not long after I left, python stopped. I hit enter in the console, and it started again. I scoured the handful of lines of code to see if there was any kind of input statement put there by accident but couldn't find one. Furthermore, I've run this code many times without it pausing. It's still possible I've done something boneheaded, but I'm wondering if there is another reason (e.g. a pause in the win32com module, some kind of timeout feature if the system is idle, etc.). thank you From deets at nospam.web.de Tue Jul 22 09:30:36 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 15:30:36 +0200 Subject: regarding SWIG References: <12e21dec-b269-4c34-9492-98424d207397@w7g2000hsa.googlegroups.com> Message-ID: <6em5ppF7r22oU2@mid.uni-berlin.de> Anish Chapagain wrote: > Hi.. > I'm new to SWIG and need to create Wrapper for C code, > so, I have installed the SWIG already but doesnot know how to run it > for generating Interface file... > My C code is in message.c so what do i need to do the first > step..uisng SWIG..i read the documentation but cannot grasp creating > interface file. If it's pure C, stop using SWIG. Create a DLL/SO-file of your message.c & use ctypes to wrap that. Diez From spython01 at gmail.com Mon Jul 21 16:11:38 2008 From: spython01 at gmail.com (Samir) Date: Mon, 21 Jul 2008 13:11:38 -0700 (PDT) Subject: Converting List of String to Integer References: Message-ID: On Jul 21, 3:20?pm, Gary Herron wrote: > Samir wrote: > > Hi Everyone, > > > I am relatively new to Python so please forgive me for what seems like > > a basic question. > > > Assume that I have a list, a, composed of nested lists with string > > representations of integers, such that > > > a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > > > I would like to convert this to a similar list, b, where the values > > are represented by integers, such as > > > b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > > I have unsuccessfully tried the following code: > > > n = [] > > for k in a: > > ? ? n.append([int(v) for v in k]) > > print n > > > Does anyone know what I am doing wrong? > > > Thanks in advance. > > > Samir > > -- > >http://mail.python.org/mailman/listinfo/python-list > > You didn't tell us how it failed for you, so I can't guess what's wrong. > > However, your code works for me: > > ?>>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > ?>>> n = [] > ?>>> for k in a: > ... ? ?n.append([int(v) for v in k]) > ... > ?>>> print n > [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > (Although you seem to have confused variables b and n.) > > Gary Herron- Hide quoted text - > > - Show quoted text - Hi Gary, Thanks for your quick response (and sorry about mixing up b and n). For some reason, the logic I posted seems to work ok while I'm using the Python shell, but when used in my code, the program just hangs. It never outputs the results. Below is the code in its entirety. Is there a problem with my indendentation? a = n = [] t = """ 1 2 3 4 5 6 7 8 9 0 """ d = t.split("\n") for x in range(1,len(d)-1): a.append(d[x].split(" ")) print a for k in a: n.append([int(v) for v in k]) print n Thanks again. Samir From paul.hankin at gmail.com Thu Jul 17 05:13:08 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 17 Jul 2008 02:13:08 -0700 (PDT) Subject: Remove some characters from a string References: <35cff1a6-74f6-4a68-b81e-71d8ff9c4633@a70g2000hsh.googlegroups.com> Message-ID: On Jul 17, 9:13?am, Julien wrote: > Hi, > > I can't seem to find the right regular expression to achieve what I > want. I'd like to remove all characters from a string that are not > numbers, letters or underscores. > > For example: > > >>> magic_function('si_98%u^d at .as-*gf') > > str: 'si_98udasgf' For speed, you can use 'string.translate', but simplest is to use a comprehension: import string def magic_function(s, keep=string.ascii_letters + string.digits + '_'): return ''.join(c for c in s if c in keep) -- Paul Hankin From grante at visi.com Wed Jul 23 00:07:58 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 22 Jul 2008 23:07:58 -0500 Subject: Python Written in C? References: Message-ID: On 2008-07-23, Larry Bates wrote: >> Since you probably need an assembler anyway, generating >> assembly-language in the compiler prevents you from having to >> duplicate a bunch of object-code-generation code in two places. > > I'm not sure I understand what you mean here. The code > generation phase of the top level compiler would have to > generate assembler mnemonics instead of just generating > machine coded directly. At that point it should be just as > easy to generate machine code, unless you take advantage of > macros, or other helpers provided in the assembly phase. Generating assembly language can be a lot easier than generating machine code. One of the big advantage if you're generating assembly language is you don't have to handle relocation and address fix-up issues -- you can let the assembler and linker take care of it. Letting the linker do the final machine-code generation step also allows certain optimizations that can't really be done by the compiler. > My "compiler" work was way back on mainframes and the ones I > worked with definitely didn't produce assembler then needed to > be run through the assembler. They created likable objects > directly. There probably are plenty of compilers that do that. My background is Unix and microprocessor stuff, and it could be that for various reasons the "emit assembly" approach was more common in that genre. > But that was over 30 years ago! > > All this may be a moot point, because assembler is just a > mnemonic representations of machine language anyway. On many architectures, a particular mnemonic can end up being translated into one of several slightly different machine instructions -- for example a simple "jump" mnemonic might generate any one of several instructions depending on how far away the destination is located. If you've already got an assembler and linker than know how to deal with that stuff, then rather than duplicate the same functionality in the compiler, one might just decided to emit a "jump mnemonic" and a label. -- Grant Edwards grante Yow! Wow! Look!! A stray at meatball!! Let's interview visi.com it! From fuzzyman at gmail.com Thu Jul 3 13:41:11 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 3 Jul 2008 10:41:11 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> <9ad840e1-e12f-4125-8537-4bad2ef77f51@w5g2000prd.googlegroups.com> Message-ID: On Jul 2, 9:33?am, Ali Servet D?nmez wrote: > On Jul 1, 12:15?am, Fuzzyman wrote: > > > > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > I don't want to be so mean here, but how hard it could be be writing a > > > freesoftware which would automatically/intelligently auto complete > > > Python code? (I mean something that really does the job, like > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > name it, but just don't give me PyDev please...) > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > missing here? > > > > Could someone please point me out something that I'm really missing > > > which is already present in the wild, otherwise I'd like discuss with > > > whoever is willing to help me to get this thing done. I made my mind > > > and I could volunteer to make this happen as thesis project for my > > > incoming graduation in the next year. > > > > Regards you all, > > > Ali Servet D?nmez > > > Vim, Emacs, Wing, Komodo, ... more? > > > Yeah, I guess you're missing something. :-) > > > MichaelFoordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > I've checkout Wing IDE's license and it doesnt' seem to be a > freesoftware; am I wrong? Wing 101 is free. The software is good enough though that it is worth supporting its development by paying for it. Michael Foord -- http://www.ironpythoninaction.com/ http://www.trypython.org/ From littlesweetmelon at gmail.com Mon Jul 21 04:47:38 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Mon, 21 Jul 2008 16:47:38 +0800 Subject: What is the role of python2.6 and C++? In-Reply-To: <74c92ee2-7b89-4579-b25a-a68262e2fee7@a70g2000hsh.googlegroups.com> References: <74c92ee2-7b89-4579-b25a-a68262e2fee7@a70g2000hsh.googlegroups.com> Message-ID: > I will program larger projects in 2.5 for a while and then perhaps > look to move it to 2.6 and 2.7, I won't touch the 3.x series until it > is the common choice, much as a lot of people still program in 2.3/4. Oh, I see. It seems the gap between 2.5 and 3.0 is not so small. Therefore, even if 3.0 is released, it may take many months for porting old projects. I agree with you to wait until python 3.0 becomes common choice. Hope this day comes as soon as possible. :P -- ShenLei From Tribulations at Paralleles.invalid Mon Jul 7 05:29:16 2008 From: Tribulations at Paralleles.invalid (TP) Date: Mon, 07 Jul 2008 11:29:16 +0200 Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> <6ddj74F21uhjU1@mid.individual.net> Message-ID: Peter Otten wrote: >>>> esc = os.environ["esc"].decode("string-escape") >>>> esc > '\x1b' >>>> print "%s[30;44malles so schoen bunt hier%s[0m" % (esc, esc) > alles so schoen bunt hier Thanks a lot for your help. It works perfectly. Indeed, one can read in the documentation concerning encodings: "Produce a string that is suitable as string literal in Python source code" -- TP (Tribulations Parall?les) "Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert). From sukkopera at gmail.com Sun Jul 13 18:29:17 2008 From: sukkopera at gmail.com (sukkopera at gmail.com) Date: Sun, 13 Jul 2008 15:29:17 -0700 (PDT) Subject: Unexpected default arguments behaviour (Maybe bug?) References: <4f29ccf6-4daf-4e8e-8735-96cffd8a882e@t54g2000hsg.googlegroups.com> <475185e0-360a-452b-8d22-33ffc243b8a0@z66g2000hsc.googlegroups.com> Message-ID: <98fdc845-cb62-4e7b-891c-dfc75d741a2f@z66g2000hsc.googlegroups.com> On 13 Lug, 19:42, marek.ro... at wp.pl wrote: > I expect it's because default values for parameters are evaluated and > bound at definition time. So once "def m (self, param = a):" line > executes, the default value for parameter is forever bound to be 1. > What you can do is for example: Yes, that's what I thought, too. Although, it does not seem to me the correct thing that has to be done, that is why I reported it. Also thanks for your suggestion, that might work, even though I already have implemented a workaround (two different methods). Regards! From victorsubervi at gmail.com Tue Jul 15 08:37:47 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 15 Jul 2008 14:37:47 +0200 Subject: Simplify Code Message-ID: <4dc0cfea0807150537w1361ccabq75039886600ce9f8@mail.gmail.com> Hi; Forgive multiple posts in one day: online very infrequently I set the following variables: # Headers are kept in order to determine nesting of chapters # They are labeled according to font size h36 = '' h26 = '' h22 = '' h18 = '' h14 = '' h12 = '' header_sizes = [36, 26, 22, 18, 14, 12] # Size is the font size of the header size = 0 I write code that grabs the size var. Then I have the following very laborious spaghetti code: if size == 36: h36 = line h26 = '' h22 = '' h18 = '' h14 = '' h12 = '' elif size == 26: h26 = line h22 = '' h18 = '' h14 = '' h12 = '' elif size == 22: h22 = line h18 = '' h14 = '' h12 = '' elif size == 18: h18 = line h14 = '' h12 = '' elif size == 14: h14 = line h12 = '' elif size == 12: h12 = line else: # THROW ERROR! I would like something more elegant, like this: # del is used to determine if should reset the lower header values to '' del = 0 for header_size in header_sizes: if header_size == size: # The following line is ILLEGAL h + string(header_size) = line del = 1 if del = 1 # The following line is ILLEGAL h + string(header_size) = '' How can I rewrite those illegal lines, such that I can create the proper name for the variable, and write the necessary data? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From omer at no-log.org Wed Jul 2 10:45:21 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Wed, 2 Jul 2008 16:45:21 +0200 Subject: Trouble using pinckle In-Reply-To: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> References: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <200807021645.21312.omer@no-log.org> Le Wednesday 02 July 2008 16:09:07 Pierre-Alain Dorange, vous avez ?crit?: > Hello, > > I'm new to python and i'm deelopping a small game with pygame. > I got lot of fun with python. > > Trying to implement a config file to save user score and config. > Reading doc and some tutorial about file handling i read about pickle, > and yes it's very easy to implement. > But i thought i miss something with the roots of python. > > I implement a Prefs class to handle config data and add it a load and > save method. It works but when reading self, it OK inside the load > function but outside the pref instance return to it's previus state... > I don't really understand. > > Here's the test code : > > #!/usr/bin/env python > > import os, pickle > > kFileName='test.ini' > > class Prefs(): note that using new-style classes is recommended today: class Prefs (object) : > def __init__(self): > self.test=1 > self.zorglub='bonjour' > > def load(self): > if os.path.exists(kFileName): > try: > print 'test %d (before)' % self.test > f=open(kFileName,'r') > self=pickle.load(f) > f.close() > print 'test %d (after)' % self.test > except IOError: > return 1 > > return 0 > Here self is only a local variable and its meaning is only a convention. So assigning it to a new value won't change the object itself (and is not a good idea as it may be confusing for the reader). You should either use a static method which returns a new object: class Prefs (object) : def save (self, f) : pickle.dump(self, f) @staticmethod def load (f) : return pickle.load(f) and load it with "prefs = Prefs.load(filename)" or store all the values in a dictionary and only pickle this object: class Prefs (object) : def __init__ (self) : self.values = { 'test': 1, ... } def save (self, f) : pickle.dump(self.values, f) def load (self, f) : self.values = pickle.load(f) -- C?dric Lucantis From eckhardt at satorlaser.com Mon Jul 7 06:30:04 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Mon, 07 Jul 2008 12:30:04 +0200 Subject: How to bypass Windows 'cooking' the I/O? (One more time, please) References: Message-ID: norseman wrote: > In this case it's [MS Windows] (still) 'cooking' the writes even > with 'rwb' and O_RDWR|O_BINARY in (proper respective) use. > > Specific: python created and inspected binary file ends: > 00460: 0D 1A (this is correct) I'm not actually sure what the 0x1a is supposed to do there. The 0x0d is a '\r' which looks like a MacOS line ending, but I also seem to remember 0x1a being use as EOF signal in some old system's text files. Anyway, you mentioned some "binary file" (aren't they all?) so this might not matter after all. > after a write > os.lseek(target, -1, 2) That should be os.SEEK_END and not 2. In any case, it moves the write position to the last byte (-1 offset to the end of the file). > os.write(target,record) > the expected result would be: > 00460: 0D 20 .....data bytes.... 1A I'm sorry, but I don't see that. write() will not insert the bytes but first overwrite till EOF and then append further output, i.e. the 0x1a at the end is only present if it was present in the record. > BUT I get: > 00460: 20 .... data bytes... 1A > > It is one byte off!!! And the 0D has to be there. Signifies the end of > the header. Okay, this looks strange, both the offset and the fact that it seems to insert bytes. How about providing a minimal example? > Anyway - if whoever mentioned the flags and such to 'over ride' > Microsoft's BS would re-send that piece I would be very appreciative. You are not one with the Tao, which is why you programs don't run. ;) Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From asma61 at dsl.pipex.com Thu Jul 17 18:01:37 2008 From: asma61 at dsl.pipex.com (DaveM) Date: Thu, 17 Jul 2008 23:01:37 +0100 Subject: x, = y (???) References: Message-ID: On Thu, 17 Jul 2008 17:32:30 -0400, Terry Reedy wrote: > >>> *x, = [3] > >>> x >[3] What does *x signify? DaveM From bignose+hates-spam at benfinney.id.au Fri Jul 18 20:48:43 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 19 Jul 2008 10:48:43 +1000 Subject: Trickiness with unittesting References: Message-ID: <873am6zok4.fsf@benfinney.id.au> arockstar at gmail.com writes: > Basically, I'm trying to implement a setUp() and TearDown() for a > python TestSuite (as opposed to an individual test within the suite). > > Sort of. I think your described requirements are well met by the 'nose' extension . It lets you continue writing 'unittest' tests, but also allows you to declare setup and teardown functions at package, module, class, and function-decorator level. -- \ ?I hate it when my foot falls asleep during the day, because | `\ that means it's gonna be up all night.? ?Steven Wright | _o__) | Ben Finney From tjreedy at udel.edu Tue Jul 29 16:38:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 16:38:53 -0400 Subject: iterating "by twos" In-Reply-To: References: Message-ID: kj wrote: > Is there a special pythonic idiom for iterating over a list (or > tuple) two elements at a time? > > I mean, other than > > for i in range(0, len(a), 2): > frobnicate(a[i], a[i+1]) There have been requests to add a grouper function to itertools, but its author has resisted because there are at least three things one might do with the short remainder group left over when the group size does not evenly divide the sequence size: drop it, return it, or fill it to the requested groupsize with a dummy value and then return it. Here is a version of the first alternative. def grouper(iterable,n): '''Return items from iterable in groups of n. This version drops incomplete groups. Python 3.0''' it=iter(iterable) ranger = range(n) while True: ret = [] for i in ranger: ret.append(next(it)) yield ret for pair in grouper(range(11),2): print(pair) [0, 1] [2, 3] [4, 5] [6, 7] [8, 9] >>> From sunp1028 at gmail.com Mon Jul 14 03:24:14 2008 From: sunp1028 at gmail.com (patrol) Date: Mon, 14 Jul 2008 00:24:14 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <51cb0fe0-58f2-4f56-a59e-59986177f3d5@c65g2000hsa.googlegroups.com> Message-ID: <573962d4-ae98-4cdd-bf8d-26c22ac221f1@m3g2000hsc.googlegroups.com> On 7?14?, ??12?29?, Larry Bates wrote: > patrol wrote: > > On 7?13?, ??10?26?, Larry Bates wrote: > >> patrol wrote: > >>> I want to prevent some process from running. The code is in the > >>> following. I encounter some unexpected troubles. > >>> Probelm1: This program cannot terminate "scrcons.exe" and > >>> "FNPLicensingService.exe",which are system processes. > >>> Problem2:After a while, this program will abort by error > >>> File "C:\Python25\lib\wmi.py", line 397, in __call__ > >>> handle_com_error (error_info) > >>> File "C:\Python25\lib\wmi.py", line 190, in handle_com_error raise > >>> x_wmi, "\n".join (exception_string) > >>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > >>> 14: ordinal not in range(128) > >>> ---------------------------------------------------- > >>> code------------------------------------------------------------------------------------ > >>> # -*- coding:utf-8 -*- > >>> import pythoncom > >>> import wmi > >>> import threading > >>> import time > >>> from xml.dom.minidom import parse, parseString > >>> class Info (threading.Thread): > >>> def __init__ (self): > >>> threading.Thread.__init__ (self) > >>> def run (self): > >>> print 'In Another Thread...' > >>> pythoncom.CoInitialize () > >>> dom1 = parse('processTerminateList.xml') > >>> config_element = dom1.getElementsByTagName("processTerminateList") > >>> [0] > >>> servers = config_element.getElementsByTagName("processName") > >>> try: > >>> c = wmi.WMI () > >>> for process in c.Win32_Process (): > >>> for server in servers: > >>> if process.name == getText(server.childNodes): > >>> process.Terminate() > >>> print process.name > >>> process_watcher = c.Win32_Process.watch_for("creation") > >>> while True: > >>> new_process = process_watcher() > >>> name = new_process.Caption > >>> print name > >>> for server in servers: > >>> if name == getText(server.childNodes): > >>> new_process.Terminate() > >>> finally: > >>> pythoncom.CoUninitialize () > >>> def getText(nodelist): > >>> rc = "" > >>> for node in nodelist: > >>> if node.nodeType == node.TEXT_NODE: > >>> rc = rc + node.data > >>> return rc > >>> if __name__ == '__main__': > >>> Info().start() > >>> ------------------------------------------------------ > >>> processTerminateList.xml------------------------------------------------------------------------- > >>> > >>> > >>> scrcons.exe > >>> TXPlatform.exe > >>> mdm.exe > >>> FNPLicensingService.exe > >>> notepad.exe > >>> uedit32.exe > >>> > >> You should probably post this to comp.python.windows. Tim Golden (author of WMI > >> interface) monitors that list religously (thanks Tim). > > >> -Larry- ??????? - > > >> - ??????? - > > > I cannot find comp.python.windows.What's the URL? > > http://news.gmane.org/gmane.comp.python.windows/cutoff=7565 > > -Larry- ??????? - > > - ??????? - Thanks From __peter__ at web.de Sun Jul 13 01:32:22 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 13 Jul 2008 07:32:22 +0200 Subject: filtering keyword arguments References: <633d6159-7803-4d9b-8f16-2a4a0a197a86@t54g2000hsg.googlegroups.com> Message-ID: Amir wrote: > How do you filter keyword arguments before passing them to a function? > > For example: > > def f(x=1): return x > > def g(a, **kwargs): print a, f(**kwargs) > > In [5]: g(1, x=3) > 1 3 > > In [6]: g(1, x=3, y=4) > TypeError: f() got an unexpected keyword argument 'y' > > Is there a way to do something like: > > def g(a, **kwargs): print a, f(filter_rules(f, **kwargs)) > > so only {'x': 3} is passed to f? I think you have to come up with something yourself. Here's a start: import inspect def filter_kw(f, **kw): names = inspect.getargspec(f)[0] return dict((n, kw[n]) for n in names if n in kw) Peter From utkualtinkaya at gmail.com Mon Jul 14 06:15:05 2008 From: utkualtinkaya at gmail.com (Utku Altinkaya) Date: Mon, 14 Jul 2008 03:15:05 -0700 (PDT) Subject: RPC Client acts like a server Message-ID: <1ae49371-ce95-469b-bc09-1c189bfa737c@c58g2000hsc.googlegroups.com> Hello, I need a client that connects to the server and answers remote calls. Is there a way to dot that using sandart xmlrpclib ? Currently I am using Remote Python Call library, but looking for alternative solutions as well. regards From bronger at physik.rwth-aachen.de Thu Jul 24 11:39:28 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 24 Jul 2008 17:39:28 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> Message-ID: <87zlo747gv.fsf@physik.rwth-aachen.de> Hall?chen! Bruno Desthuilliers writes: > Torsten Bronger a ?crit : > >> Bruno Desthuilliers writes: >> >>> [...] >>> >>> How would you handle this case with an implicit 'self' : >>> >>> class Foo(object): >>> pass >>> >>> def bar(self): >>> print self >>> >>> Foo.bar = bar >> >> Just like this. However, the compiler could add "self" to >> non-decorated methods which are defined within "class". > > What's defined within classes are plain functions. It's actually > the lookup mechanism that wraps them into methods (and manage to > insert the current instance as first argument). And why does this make the implicit insertion of "self" difficult? I could easily write a preprocessor which does it after all. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From bedouglas at earthlink.net Mon Jul 21 16:18:27 2008 From: bedouglas at earthlink.net (bruce) Date: Mon, 21 Jul 2008 13:18:27 -0700 Subject: Trying to solve a python/mechanize "error 500" http error Message-ID: <24da01c8eb6e$ef9ea2a0$0301a8c0@tmesa.com> i'm getting the following error: mechanize._response.httperror_seek_wrapper: HTTP Error 500: i'm running python 5.1 and mechanize 0.1.7b I have no idea as to what I have to change/modify/include to handle this issue. The link that I'm testing is at the bottom of the page. When I insert the link into the browser, I actually get an err page.. so, I suspect that there is a handler that I should be able to modify/use to handle this situation... Thoughts/Comments will be greatly appreciated... Thanks the output is: www = www.1800ink.com url2= http://www.quantcast.com/www.1800ink.com/traffic Traceback (most recent call last): File "./reseller_scrape_child.py", line 288, in q1 = shopfuncs.quant(rhref) File "/adkiller/shopfuncs.py", line 56, in quant br.open(url2) File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 203, in open File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 254, in _mech_open mechanize._response.httperror_seek_wrapper: HTTP Error 500: [root at toshiba adkiller]# ./reseller_scrape_child.py my code segment looks like: ==================================== from mechanize import Browser import mechanize br = Browser() user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values1 = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } #br.set_cookiejar(cj) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.addheaders = [('User-Agent', 'Firefox')] url2 ="http://www.quantcast.com/xxxx/traffic" #gets the page (url) from the quantcast app url2=url2.replace("xxxx",url) print "url2=",url2 br.open(url2) ======================================= this works ok for most of the sites.. but something weird is happening with the actual page: http://www.quantcast.com/www.1800ink.com/traffic thanks... From larry.bates at websafe.com` Tue Jul 29 18:47:21 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 29 Jul 2008 17:47:21 -0500 Subject: Python COM In-Reply-To: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> References: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> Message-ID: birdprince at gmail.com wrote: > I have implemented a COM in C++,buy i don't know how to use this COM > in python. > For example: the COM's ProgID is "MyCOM1.AdvMethod".this COM have two > interfaces,the default interface's name is IAdvMethod,the second > interface's name is IBasicMethod. > How do i use those interfaces in python.Thank you very much,please > answer my question in code. Suggestion: Post this to comp.python.windows instead of here. I think you will find that a better place for this question. -Larry From max at alcyone.com Wed Jul 30 22:05:48 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Jul 2008 19:05:48 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > On Jul 30, 1:07 am, Erik Max Francis wrote: >> Russ P. wrote: >>> Oh, Lordy. I understand perfectly well how boolean tests, __len__, and >>> __nonzero__ work in Python. It's very basic stuff. You can quit >>> patronizing me (and Carl too, I'm sure). >> You suggested a syntax for testing non-emptiness (`x is not empty`) >> which indicated a profound misunderstanding of what the `is` operator does. >> >> You then acknowledged that there might be a problem because of the >> implication if the `is` operator and weren't sure whether it would work >> or not: > > Oh, my. I wrote something like, "It would sure be nice to be able to > write > > if x is not empty: > > because it reads like natural language. Immediately after I posted it, > I thought, "oh, I'll bet some idiot takes that as a serious proposal." > Sure enough, some idiot did just that almost immediately. Yes, all people are idiots for reading what you wrote, reading your later realization that it was wrong, and taking both at face value. I'll be sure never to make that mistake again! > And he is > still patronizing me for it. No, I'm not patronizing you for your initial misstatement. I'm mocking you for your pathetic and transparent attempt to backpedal away from it. Just give it up, already. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Drifting from woman-who-tries misconstrued / Shifting to woman-wise -- Lamya From murugesan550 at gmail.com Thu Jul 24 23:18:56 2008 From: murugesan550 at gmail.com (muruges) Date: Thu, 24 Jul 2008 20:18:56 -0700 (PDT) Subject: .............................on line jobs........................................ Message-ID: we are selecting you for this online jobs. For more information see this website in this.............................. we are selecting you for this online jobs. For more information see this website in this.............................. Details .................. Name of the job.........................Online job.......................... Nature of work...........................Like data entry.......................... Qualification required........................good knowledge in computer Basics Earnings................More then Rs=1000 per day......................Earnings depends on your work............................. FOR MORE DETAILS: WWW.Bigconstructions5.blogspot.com From grflanagan at gmail.com Wed Jul 30 11:49:44 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Wed, 30 Jul 2008 17:49:44 +0200 Subject: ANN: Google custom search engine for Python Message-ID: What is it? ----------- A Google custom search engine which targets only the following sites: + `The Hazel Tree `__ + `The Python standard library docs `__ + `The Python wiki `__ + `Python Package Index `__ Where can I access it? ---------------------- The home page of the search engine is here: http://www.google.com/coop/cse?cx=002031040340806163079:nkigkp_irqk As well as accessing it from its home page, you can link to it from your own web sites, or add it as a gadget to your Google home page (if you have one) - see the above link for details. No ads ------ `The Hazel Tree `__ is a not-for-profit site and no ads will appear in the search results. Using refinements ----------------- To refine the search to any of the individual sites, you can specify a refinement using the following labels: stdlib, wiki, pypi, thehazeltree So, to just search the python wiki, you would do: somesearchterm more:wiki and similarly: somesearchterm more:stdlib somesearchterm more:pypi somesearchterm more:thehazeltree About http://thehazeltree.org ----------------------------- `The Hazel Tree `__ is a collection of popular Python texts that I have converted to reStructuredText and put together using `Sphinx `__. It's in a publishable state, but not as polished as I'd like, and since I'll be mostly offline for the next month it will have to remain as it is for the present. However, the search engine is ready now and the clock is ticking on its subscription (one year, renewal depending on success of site), so if it's useful to anyone, it's all yours (and a link back to http://thehazeltree.org would be appreciated). Cheers, G. From tjreedy at udel.edu Tue Jul 15 16:50:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Jul 2008 16:50:30 -0400 Subject: Modify a string's value In-Reply-To: References: Message-ID: s0suk3 at gmail.com wrote: > Hi everyone, > > I've heard that a 'str' object is immutable. But is there *any* way to > modify a string's internal value? In 3.0, ascii chars and encoded unicode chars in general can be stored in a mutable bytearray. From digetl.try at gmail.com Sat Jul 26 06:03:10 2008 From: digetl.try at gmail.com (raja) Date: Sat, 26 Jul 2008 03:03:10 -0700 (PDT) Subject: How I Lost My Belly Fat Message-ID: I fought with excess belly fat for years until I found this 1 trick. http://food-drinks.page.tl/ From deacon.sweeney at gmail.com Tue Jul 8 12:44:04 2008 From: deacon.sweeney at gmail.com (Deacon) Date: Tue, 8 Jul 2008 09:44:04 -0700 (PDT) Subject: plugins using cvs/distutils? Message-ID: Hi. I have an open-source application development environment that I would like to enable an automated package download system for (like downloadable plugins), using sourceforge as its repository. My software will have a menu-based popup window, that will list the packages (Applications) available through the project distribution page. If a user selects a package from this window, it should be automatically retrieved and installed by the development environment. My software already has a system for automatically recognizing and deploying new packages, so I'm only asking for help with distribution logistics, I think. I'm thinking that I will use the built-in ftplib to list and retrieve the files (but I'm not sure yet where to look), and then the distutils should probably be used in a standardized manner to actually install the packages, right? I've established a CVS, but I'm not aware of any built-in-python tools for managing the CVS, and I would rather not add any new user-has-to-download-dependencies for this. Is there an easier or alternative advisable approach? I have a linux box, should I be using it to build all of the platform versions? Any advice would be much appreciated, this is my first distribution project (sourceforge.net/projects/spade). Thanks a bunch, Deacon From pythonnutter at gmail.com Thu Jul 3 18:56:32 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Fri, 4 Jul 2008 08:56:32 +1000 Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: <1020285372.957161215116648910.JavaMail.root@saturn.datasyncintra.net> References: <552487307.956521215116093518.JavaMail.root@saturn.datasyncintra.net> <1020285372.957161215116648910.JavaMail.root@saturn.datasyncintra.net> Message-ID: If you guys can get your head out of IDE land, you'll find iPython does a fantastic job at introspection and Auto-completion, you can launch shell commands and editors and when done saving be back in the iPython shell, save memory/variable space to disk so you can come back the next day and continue off where you were. It puts IDEs to shame. If you can't get your Windows-centric IDE need eliminated, then Wing IDE 101 will not auto-complete, its been deliberately disabled to force students (hence 101) to memorize python/function names. Komodo Edit is a free download and will Auto-complete. Cheers, PN From norseman at hughes.net Wed Jul 16 13:11:42 2008 From: norseman at hughes.net (norseman) Date: Wed, 16 Jul 2008 10:11:42 -0700 Subject: How to figure out if the platform is 32bit or 64bit? Message-ID: <487E2BCE.30108@hughes.net> > > I need to know if I'm running on 32bit or 64bit ... so far I haven't > > come up with how to get this info via python. sys.platform returns > > what python was built on ... but not what the current system is. > > > > I thought platform.uname() or just platform.processor() would have > > done it, but python returns an empty string on windows. Any ideas? > > > > Thanks, Ken =========================================== From what I'm reading I think the answer lies in being able to see Microsoft's OS 'About' statement. One of the Python guru's should be able to supply the code. On Linux you should be able to uname -m and get a pretty good idea. See man uname. something like: #contents of t.py #----------- import os zstatflg= os.system("uname -m") #----------- EOF --- then: python t.py i686 (I'm running a stock Python 2.5.2) If the Python itself was compiled 32 bit and installed on a 64 bit machine that runs 32 bit code (like most all do during transition times) then all attempts with Python to check itself will return 32 bit responses. Using math and/or 'kibitz' (cheater text) will be useless. Hope this helps; Steve norseman at hughes.net From bearophileHUGS at lycos.com Mon Jul 14 07:48:22 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 14 Jul 2008 04:48:22 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> <792048c1-5e18-4a2c-925d-a1c932d18a91@j22g2000hsf.googlegroups.com> <8923d0c5-29ce-495f-924a-6d9d2457138e@e39g2000hsf.googlegroups.com> Message-ID: <8933b108-45b4-438d-87d8-aad92a15188b@e53g2000hsa.googlegroups.com> Larry Bates: > The only case where it would be faster would be if most of the keys were NOT in > the dictionary (rather odd use case). Otherwise I believe you will find the > first way quicker as the exceptions are infrequent. I have written a small benchmark: from random import shuffle def test1(data, to_delete): for item in to_delete: try: del data[item] except KeyError: pass def test2(data, to_delete): for item in to_delete: if item in data: del data[item] N = 1000000 M = 2 * N data = dict.fromkeys(xrange(N), 0) to_delete = range(M) shuffle(to_delete) from timeit import default_timer as clock t = clock() #test1(data, to_delete) # 2.4 s test2(data, to_delete) # 0.8 s print round(clock() - t, 2), "s" It creates a dictionary of the first million integers, and then tries to delete the first two million of integers. So about 1/2 numbers are present to be deleted. In this situation the version with the try- except seems about 3 times slower than the other. Bye, bearophile From bignose+hates-spam at benfinney.id.au Tue Jul 15 06:45:37 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jul 2008 20:45:37 +1000 Subject: Testing for Internet Connection References: Message-ID: <87bq0z8lym.fsf@benfinney.id.au> Alexnb writes: > I am wondering, is there a simple way to test for Internet > connection? If not, what is the hard way :p Refine the question: What do you mean by "internet"? It isn't a single entity. Do you mean "some particular internet host responding on a particular network port"? If you can define exactly what you mean by "internet connection", the test for it becomes correspondingly easier. -- \ ?Why should I care about posterity? What's posterity ever done | `\ for me?? ?Groucho Marx | _o__) | Ben Finney From circularfunc at gmail.com Sun Jul 6 17:47:40 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 6 Jul 2008 14:47:40 -0700 (PDT) Subject: Very weird bug! Message-ID: <1c1c343a-dd63-454a-8e29-a5c70281ad90@c58g2000hsc.googlegroups.com> I was looking into currying and Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.2.2 >>> h = "aja baja" >>> h += 'e' >>> h 'aja bajae' >>> h = h+'a' >>> h 'aja bajaea' >>> a = b = "foo" >>> a 'foo' >>> b 'foo' >>> a==b True >>> id(a) 35018400 >>> id(b) 35018400 >>> a += "bar" >>> id(a),a (35110112, 'foobar') >>> id(b),b (35018400, 'foo') >>> fac Traceback (most recent call last): File "", line 1, in fac NameError: name 'fac' is not defined >>> factorial Traceback (most recent call last): File "", line 1, in factorial NameError: name 'factorial' is not defined >>> import math >>> math >>> math.factorial Traceback (most recent call last): File "", line 1, in math.factorial AttributeError: 'module' object has no attribute 'factorial' >>> math.fac Traceback (most recent call last): File "", line 1, in math.fac AttributeError: 'module' object has no attribute 'fac' >>> dir(math) ['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] >>> pow >>> tan Traceback (most recent call last): File "", line 1, in tan NameError: name 'tan' is not defined >>> math.tan >>> def build(a,b): return a+b >>> build(5,4) (5, 4) >>> def build(x,y): a=x+y return a >>> build(5,4) 9 >>> def b(n, p): return n + p >>> b(1, 10) 11 >>> def b(n,p): return n+p >>> b(5,2) 7 >>> def build(x,y): return a+b >>> build(5,4) Traceback (most recent call last): File "", line 1, in build(5,4) File "", line 2, in build return a+b TypeError: cannot concatenate 'str' and 'function' objects >>> def build(x,y): yreturn x+ SyntaxError: invalid syntax >>> def build(x,y): return x+y >>> build(5,4) 9 >>> def build(a,b): return a+b >>> build(5,4) 9 >>> wtf was this in the middle!? >>> def build(a,b): return a+b >>> build(5,4) (5, 4) From bob.martin at excite.com Fri Jul 25 05:56:48 2008 From: bob.martin at excite.com (Bob Martin) Date: Fri, 25 Jul 2008 09:56:48 GMT Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> Message-ID: in 75186 20080725 050433 Tim Roberts wrote: >castironpi wrote: >> >>Compiling a program is different than running it. A JIT compiler is a >>kind of compiler and it makes a compilation step. I am saying that >>Python is not a compiler and in order to implement JIT, it would have >>to change that fact. > >And I'm saying you are wrong. There is NOTHING inherent in Python that >dictates that it be either compiled or interpreted. That is simply an >implementation decision. The CPython implementation happens to interpret. >The IronPython implementation compiles the intermediate language to native >machine language. > >>> of Python that uses .NET. In that case, the code *IS* JIT compiled to >>> assembly when the program starts. >> >>But still not the user's code, only the interpreter, which is running >>in assembly already anyway in CPython. > >In CPython, yes. In IronPython, no; the user's code is compiled into >machine language. Both of them are "Python". >-- >Tim Roberts, timr at probo.com >Providenza & Boekelheide, Inc. It's amazing how many people cannot differentiate between language and implementation. How many times have I read "x is an interpreted language"? I know many languages are designed for either compilation or interpretation, but I have used C and Pascal interpreters as well as Java and Rexx compilers. From metaperl at gmail.com Tue Jul 15 14:56:59 2008 From: metaperl at gmail.com (E. J. Gold is the Hi-Tech Shaman) Date: Tue, 15 Jul 2008 11:56:59 -0700 (PDT) Subject: graphing lifelines Message-ID: (crossposted to sci.math) I'm looking for a tool which will take a dataset of tuples indicating the year of birth and death of a person: (1872, 1950, "Sri Aurobindo") (1821, 1910, "Mary Baker Eddy") (1831, 1891, "HP. Blavatksy") And graph them out, in bars, annotating them with the person's name. A simple spreadsheet would've worked, but they seem to start from zero. Thus, I would only be able to indicate the span of life (by subtracting death year from birth year). From kak at purdue.edu Sat Jul 12 14:28:33 2008 From: kak at purdue.edu (Avi Kak) Date: Sat, 12 Jul 2008 11:28:33 -0700 (PDT) Subject: fix for wxPython incompatibility of BitTornado 0.3.18 Message-ID: If you are unable to use the wxPython-based GUI interfaces in the BitTornado 0.3.18 library on your Ubuntu 8.04 machine, you may wish to download a directory of the library available through http://cobweb.ecn.purdue.edu/~kak/distbt/ If any problems, send me email at kak at purdue.edu with "BitTornado" in the subject line to get past my procmail filter. Avi Kak From Graham.Dumpleton at gmail.com Fri Jul 18 09:06:00 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Fri, 18 Jul 2008 06:06:00 -0700 (PDT) Subject: Problem with MySQLdb and mod_python References: <48802594$0$17225$742ec2ed@news.sonic.net> Message-ID: <1d9296bb-9288-40ec-a9fc-b0048a6f20d5@z6g2000pre.googlegroups.com> On Jul 18, 3:28?pm, John Nagle wrote: > Cyril Bazin wrote: > > Thanks for your reply > > > The apache log contains lines like : > > > [Tue Jul 15 23:31:01 2008] [notice]mod_python(pid=11836, > > interpreter='www.toto.fr'):Importing module > > '/usr/local/apache2/htdocs/intranet/courrier/test.py' > > [Tue Jul 15 23:31:02 2008] [notice] child pid 11836 exit signal > > Segmentation fault (11) > > [Tue Jul 15 23:31:19 2008] [notice]mod_python(pid=11764, > > interpreter='www.toto.fr'):Importing module > > '/usr/local/apache2/htdocs/intranet/courrier/test.py' > > [Tue Jul 15 23:31:19 2008] [notice] child pid 11764 exit signal > > Segmentation fault (11) > > > I think the problem comes from the MySQLdb module. > > If I can't find another solution, I think I will downgrade the MySQLdb > > version to 1.2.1 > > ? ? Sounds like version hell. ?mod_python and MySQLdb have to be > compiled with exactly the same compiler for this to work. Use of compatible compilers applies to anything you want to use together. This is nothing specific to mod_python, so this comment is a bit misleading. These days with with GNU C everywhere, it is hardly and issue, and was usually only an issue with C++ code and not C code anyway. > ? ?mod_python is usually troublesome. ? Python doesn't really have > quite enough isolation to run multiple unrelated instances reliably. The isolation issue is nothing to do with Python itself. Isolation is an issue in this case, but most likely comes about because the OP is trying to use both PHP and mod_python together in the same Apache instance. In particular, the PHP package is likely loading a MySQL module and it is linked against a different version of the MySQL client libraries than what the Python MySQL package is wanting. People like to blame mod_python for these problems, but it can equally be attributed to PHP. In practice the reason it shows up as a mod_python issue is that PHP tries to preload a lot of stuff and so manages to load its version of shared libraries first. Python with its lazy loading comes in second, and so conflicts will occur. If mod_python preloaded stuff like PHP did and this was occurring before PHP got a chance, it would be the other way around and mod_python would work fine and PHP would instead be what crashes all the time. > We use FCGI, which has the isolation of CGI but doesn't reload the > application for every transaction. ?Also, it's easier to debug if > CPython is crashing. With the reason that FCGI works being that the processes, even if they are spawned by Apache, use a fork/exec, thus meaning they have a clean memory space when starting up. In summary, look at what version of MySQL libraries are used by PHP modules and ensure that Python MySQL module is compiled against the same version. Graham From arslanburney at gmail.com Wed Jul 2 09:00:25 2008 From: arslanburney at gmail.com (J-Burns) Date: Wed, 2 Jul 2008 06:00:25 -0700 (PDT) Subject: Using Gnuplot and making an exe file outv the prog Message-ID: Hello. Been using the gnuplot lately. Program runs fine. And its plots as well. Now i want to make an exe file out of this program using py2exe. Cud some1 help me in telling me how this is done. Thnks From mail at timgolden.me.uk Thu Jul 24 11:07:43 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 24 Jul 2008 16:07:43 +0100 Subject: Python / PAMIE In-Reply-To: References: Message-ID: <48889ABF.3080006@timgolden.me.uk> frankrentef wrote: > Can someone help with a PAMIE issue? I'm new to Python / PAMIE and > they seem like great tools but to be honest I'm finding that no > responses to questions can be found (Experts Exchange, etc.) I'm > hoping this will be the place. > > I tried to duplicate the authors "ie.writeScript" function shown at > > http://showmedo.com/videos/video?name=pythonMarchettiPamie3&fromSeriesID=25 I'd rather you posted the code you've tried. I'm not too keen on viewing a video just to get hold of a piece of code, and in any case that would only show me what the author's done. We need to see what you've done, and what the traceback was. Would you mind posting some code, please? Thanks TJG From kkwweett at hotmail.fr Wed Jul 2 16:26:06 2008 From: kkwweett at hotmail.fr (kkwweett) Date: Wed, 02 Jul 2008 22:26:06 +0200 Subject: wrong md5 checksum In-Reply-To: <2-CdnaVu6892xvfVnZ2dnUVZ_gGdnZ2d@supernews.com> References: <486a16ef$0$885$ba4acef3@news.orange.fr> <486a5316$0$864$ba4acef3@news.orange.fr> <2-CdnaVu6892xvfVnZ2dnUVZ_gGdnZ2d@supernews.com> Message-ID: <486be45d$0$859$ba4acef3@news.orange.fr> > > A. an error in the software that computed the value for the web page, > B. a transcription error in putting the checksum on the web page, > C. accidental corruption of the file, or > D. a deliberate attempt to substitute a file with a similar MD5 sum. > It seems that the answer is probably B. But, according to the release website manager, a mystery remains : http://mail.python.org/pipermail/python-3000/2008-July/014281.html From BruceP at wn.com.au Wed Jul 16 00:03:22 2008 From: BruceP at wn.com.au (Bruce Pearson) Date: Wed, 16 Jul 2008 12:03:22 +0800 Subject: Is this correct behavior for default parameters? Message-ID: <344469045.20080716120322@wn.com.au> The first call to test has the file_list empty but on the second call to test the file_list is no longer empty but contains the values appended in the first call. Is this correct behavior? I'm using python 2.5 def test(param_1, file_list = []): if len(file_list) == 0: print "Empty list" file_list.append("list item 1") file_list.append("list item 2") else: raise if __name__ == "__main__": test(1) test(2) -------------- next part -------------- An HTML attachment was scrubbed... URL: From upton at virginia.edu Mon Jul 21 14:05:49 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 21 Jul 2008 14:05:49 -0400 Subject: Python Written in C? In-Reply-To: <6ejutcF6vgp3U4@mid.uni-berlin.de> References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> Message-ID: <5504f9ac0807211105h4604d332y5671243cb34abfc6@mail.gmail.com> On Mon, Jul 21, 2008 at 1:21 PM, Marc 'BlackJack' Rintsch wrote: > On Mon, 21 Jul 2008 18:12:54 +0200, mk wrote: > >> Seriously, though, would there be any advantage in re-implementing >> Python in e.g. C++? >> >> Not that current implementation is bad, anything but, but if you're not >> careful, the fact that lists are implemented as C arrays can bite your >> rear from time to time (it recently bit mine while using lxml). Suppose >> C++ re-implementation used some other data structure (like linked list, >> possibly with twists like having an array containing pointers to 1st >> linked list elements to speed lookups up), which would be a bit slower >> on average perhaps, but it would behave better re deletion? Aside (actual reply below): at least for a sorted LL, you're basically describing Henriksen's algorithm. They can asymptotically be faster, based on amortized analysis, but they're somewhat more complicated to implement. > > An operation that most people avoid because of the penalty of "shifting > down" all elements after the deleted one. Pythonistas tend to build new > lists without unwanted elements instead. I can't even remember when I > deleted something from a list in the past. > > Ciao, > Marc 'BlackJack' Rintsch The other side of the equation though is the OO-overhead for C++ programs as compared to C. (A couple years ago we used an instrumentation tool to check the instruction count for a simple hello world program written in C (ie, main(){printf("Hello world!"); return 0;}) and Python (main(){cout<<"hello world"< Message-ID: On 20 Jul., 13:08, bearophileH... at lycos.com wrote: > Kay Schluehr: > > > Sure, use a fixed point combinator. I've just added this recipe: > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/576366 > > Does it work? > > Bye, > bearophile There are lots of informal derivations of the Y combinator on the web. I used one a while ago and translated the result into Python. So if there isn't an implementation bug it shall work. I added two examples for illustration purposes. From mail at timgolden.me.uk Fri Jul 4 09:25:57 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 04 Jul 2008 14:25:57 +0100 Subject: Recursive wildcard file search In-Reply-To: <496954360807031353n4f91f691recb330f7350cbf70@mail.gmail.com> References: <496954360807031353n4f91f691recb330f7350cbf70@mail.gmail.com> Message-ID: <486E24E5.8090000@timgolden.me.uk> [sorry; this got stuck in my outbox] Robert Dailey wrote: > Is there a way to perform a recursive file search using wildcards in > python 3.0b1? > > For example, if I have: > > C:\foo\abc*xyz.* > > I want all files in C:\foo and all subfolders (recursively) of C:\foo > that match the wildcard abc*xyz.* to be matched. In the end, I want a > list of files that matched the search, as well as the directory they're > located in. I haven't checked but I doubt this has changed from Python 2.x. Just use os.walk and filter on what you want. Vaguest and most untested code sample: import os import fnmatch ROOT = "c:/temp" PATTERN = "*c*.zip" filepaths = [] for dirpath, dirnames, filenames in os.walk (ROOT): filepaths.extend ( os.path.join (dirpath, f) for f in fnmatch.filter (filenames, PATTERN) ) If you need to match on directory names as well, then you'd have to adjust accordingly. TJG From bockman at virgilio.it Fri Jul 11 09:29:13 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Fri, 11 Jul 2008 06:29:13 -0700 (PDT) Subject: read file into list of lists References: Message-ID: <4570e246-3b36-469e-b1b0-f4c547fe079b@c65g2000hsa.googlegroups.com> On 11 Lug, 15:15, antar2 wrote: > Hello, > > I can not find out how to read a file into a list of lists. I know how > to split a text into a list > > sentences = line.split(\n) > > following text for example should be considered as a list of lists (3 > columns and 3 rows), so that when I make the print statement list[0] > [0], that the word pear appears > > pear noun singular > books nouns plural > table noun singular > > Can someone help me? > > Thanks You can use split again, using ' ' or nothing(defaults to whitespace characters) as separator, like this: >>> text = """pear noun singular books nouns plural table noun singular""" >>> words = [ x.split() for x in text.split('\n') ] >>> print words [['pear', 'noun', 'singular', ''], ['books', 'nouns', 'plural', ''], ['table', 'noun', 'singular']] Ciao ----- FB From mal at egenix.com Sat Jul 26 14:32:39 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Sat, 26 Jul 2008 20:32:39 +0200 Subject: Gracefull application exit. In-Reply-To: <488B6D2E.2040403@egenix.com> References: <00ba01c8eda7$2e61ecb0$8b25c610$@rawlins@thinkbluemedia.co.uk> <488B6D2E.2040403@egenix.com> Message-ID: <488B6DC7.2030809@egenix.com> On 2008-07-26 20:30, M.-A. Lemburg wrote: > On 2008-07-24 18:06, Robert Rawlins wrote: >> Chaps, >> >> >> >> I'm looking to implement an exit/termination process for an application >> which can be triggered by A) a keyboard interrupt or B) termination of >> the >> application as a Daemon using a signal. >> >> >> >> I have a whole bunch of tasks I want to perform as a cleanup before the >> application is terminated, cleaning files, database calls, closing open >> connections and a few other things. >> >> >> >> I know we have: >> >> >> >> # I'm the main application started method. >> >> if __name__ == "__main__": >> >> >> >> For starting an application, but do we have an equivalent methods for >> when >> an application is terminated which we can use to close down any current >> internal processes before the application exits? >> >> >> >> I'd really love to have your thoughts and experience on gracefully >> killing >> an application. > > Wrap your whole application into a main() function and then use: > > try: > main() > finally: > cleanup() > BTW: In order to catch signals, you'll have to install signal handlers which then raise Python exceptions, e.g. SystemExit. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 26 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From mail at timgolden.me.uk Wed Jul 9 06:05:40 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 09 Jul 2008 11:05:40 +0100 Subject: Newbie question In-Reply-To: References: <3b1e6f480807082337l419fd40ax91eaf13e0701c5b3@mail.gmail.com> Message-ID: <48748D74.8090701@timgolden.me.uk> A.T.Hofkamp wrote: > On 2008-07-09, |e0 wrote: >> So, i can't use wmi module on linux? >> >> On Wed, Jul 9, 2008 at 9:14 AM, Lamonte Harris wrote: >>> I think the win32 module is only for windows. >>> > > Welcome to the world outside MS. > > Many python modules don't actually do anything than passing on calls to an > existing underlying library. They are cheap to make, and make it possible to > use the functionality of the library from a Python program. The down-side is, > as you have discovered, that you need the underlying library to make it work. And this is of course true both ways. Python users under Windows miss out on about half [*] of the os module since it's just handing off to the *nix system calls. At the same time, *nix users won't be able to add Shell Namespace Extensions or use the Windows API to monitor directory changes. > So, the answer is no, you cannot use wmi under a non-MS OS. (But what did you > expect, given that wmi means WINDOWS Management Instrumentation?) I don't know if anyone's tried to get something like WMI running under Wine. In principal it might work but I suspect it would involve a lot of time and effort. Strictly, WMI is an implementation of the WBEM [2] standards. Googling around suggests that implementations exist for Linux but I've no idea how mature or robust they are, and I'm quite sure they're not going to be using a Windows API model for their interface. TJG [1] A pardonable exaggeration [2] http://www.dmtf.org/standards/wbem/ From petite.abeille at gmail.com Thu Jul 24 14:07:26 2008 From: petite.abeille at gmail.com (Petite Abeille) Date: Thu, 24 Jul 2008 20:07:26 +0200 Subject: instance comparison In-Reply-To: References: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> <4888879a$0$1043$426a74cc@news.free.fr> Message-ID: On Jul 24, 2008, at 7:53 PM, King wrote: > The the class is not subclass of another one. Problem still persist. > The code is pretty huge and I am trying to post the information as > clear as possible. Mark V. Shaney, from Dissociated Press, I presume? -- PA. http://alt.textdrive.com/nanoki/ From mccredie at gmail.com Wed Jul 23 10:55:50 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 23 Jul 2008 07:55:50 -0700 (PDT) Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: On Jul 22, 2:02?pm, ptn wrote: > Hi everybody, > > I have a weird problem. ?Say I have a .py file with some functions in > it, like this: > > ? ? # (...) > ? ? def foo(): > ? ? ? ? print("bar") > > When I open it and add a line to one of the functions, > > ? ? # (...) > ? ? def foo(): > ? ? ? ? troz = "bar" > ? ? ? ? print(troz) > > I get the following traceback from the interpreter: > > ? ? Traceback (most recent call last): > ? ? ? File "SOMEWHERE/example.py", line ?? > ? ? ? ? troz = "bar" > ? ? ? ? ? ? ? ? ? ? ? ? ? ^ > ? ? IndentationError: unindent does not match any outer indentation > level > > And so I'm forced to rewrite the function entirely just to add the new > line. > > I thought that my problem was the w option from formatoptions, so I > changed my .vimrc file to this: > > ? ? augroup filetype > ? ? ? autocmd BufNewFile,BufRead *.txt set filetype=human > ? ? augroup END > ? ? autocmd FileType human setlocal formatoptions+=ta2w > ? ? autocmd FileType lisp,scheme,python,c,java,vim setlocal > formatoptions-=ta2w > > But the problem didn't go away. ?I don't think this has anything to > do > with the tabs and spaces, because I have them set up like this: > > ? ? set tabstop=4 shiftwidth=4 expandtab > > which is the standard way to handle them. > > The scripts I load are: qbuf, TagList, indent/python.vim and a reduced > version of the standard python.vim > > Could someone provide some pointers? > > Thanks, > > Pablo Torres N. That isn't the standard. With that setup tabs will show up as 4 spaces, and still confuse you. You want this: set shiftwidth=4 set tabstop=8 set softtabstop=4 set expandtab tab characters in the file will show up as 8 characters long (which is how the python interpreter sees them also) but pressing tab will insert 4 spaces. Matt From tjreedy at udel.edu Wed Jul 30 11:07:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jul 2008 11:07:03 -0400 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <7f4a3d37-e551-4e21-b660-3618016cb67b@z6g2000pre.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> <7f4a3d37-e551-4e21-b660-3618016cb67b@z6g2000pre.googlegroups.com> Message-ID: Carl Banks wrote: > That's not what I was asking for. I was asking for a use case for "if > x" that can't be replaced by a simple explicit test. Your example > didn't satisfy that. But I believe my example of an iterator with __bool__ but not with __len__ does. From comp.ogz at gmail.com Wed Jul 2 06:32:59 2008 From: comp.ogz at gmail.com (Oguz Yarimtepe) Date: Wed, 2 Jul 2008 13:32:59 +0300 Subject: detection of unplugged cable Message-ID: <20831c740807020332y456a38d8rccce67abe320a629@mail.gmail.com> Hi, I am tring to develeop a gui with pyqt. I need to detect whether the the cable to vga, dmi or s-video outputs are plugged or unplugged. After detection i need to run a process. How can i do this? -- O?uz Yar?mtepe From tjreedy at udel.edu Sat Jul 12 15:18:06 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 15:18:06 -0400 Subject: palindrome function In-Reply-To: References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: Peter Otten wrote: > Denis Kasak wrote: > >> Basically, it reverses the list in place, so it modifies the list which >> called it. It does not return a /new/ list which is a reversed version >> of the original, as you expected it to. Since it doesn't return anything >> explicitly, Python makes it return None. Hence, the comparison you are >> doing is between the original list and a None, which is False, naturally. >> Try this: >> >> spam = ['a', 'n', 'n', 'a'] >> eggs = spam[:] >> if spam.reverse() == eggs: >> print "Palindrome" > > Your explanation is correct, but your example code compares None to > ['a', 'n', 'n', 'a'] and therefore won't print "Palindrome", either. I don't know if this was posted yet, but 'seq.reversed() == seq' is the simple way to test for 'palindomeness'. From gagsl-py2 at yahoo.com.ar Sat Jul 12 00:52:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 12 Jul 2008 01:52:16 -0300 Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> Message-ID: En Fri, 11 Jul 2008 15:42:37 -0300, Keith Hughitt escribi?: > I am having a little trouble figuring out how to convert a python > datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would > like to create a UTC date so that when I send it to MySQL (which > treats all dates at local dates by default), it will already have > incorporated the proper UTC offset. I've tried looking through the > docs http://python.active-venture.com/lib/datetime-datetime.html), but > have not had any luck. You have to use a "timezone aware" datetime object. If all you want is to store an UTC date, the tzinfo demo classes that you can find in the Python docs at may be enough. A more complete implementation is at If you pass a "timezone aware" datetime object as a SQL parameter, the database should store it correctly (but I don't have a MySQL instance at hand to test it) -- Gabriel Genellina From vinay_sajip at yahoo.co.uk Tue Jul 15 09:51:11 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 15 Jul 2008 06:51:11 -0700 (PDT) Subject: Logging to different addressees References: <8df30038-86c1-4376-b046-a50f2bcf0a2b@s50g2000hsb.googlegroups.com> Message-ID: <7b829a76-ba2c-4cb7-b216-0c9c01e5cd02@f36g2000hsa.googlegroups.com> On Jul 15, 1:27 pm, McA wrote: > Hi all, > > I need a recommendation. I would to like to use theloggingmodule to > create log messages the following way: > a) Every log message does go to a admin sink. > b) Theloggingof special messages should go to the admin sink AND to > a sink specifically for > a certain addressee. > c) I don't want to write the log message to two different loggers for > that purpose. I would like to do it this way: > common_logger.log('bla') -> message to admin sink > certain_logger.log('something' -> message to admin sink and addressee- > sink > d) Filtering and debug level should work as expected. > > I could I achieve this in a elegant way? > > Best regards > Andreas Mock Add a handler to the root logger (or common_logger) to send to the admin sink. Add a handler to certain_logger to send to the addressee sink. If you added the admin sink handler to the root logger, you're done. Otherwise, you need to ensure that certain_logger is a child of common_logger. Regards, Vinay Sajip From thermostat at gmail.com Fri Jul 18 15:13:02 2008 From: thermostat at gmail.com (Dan) Date: Fri, 18 Jul 2008 12:13:02 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> Message-ID: <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> On Jul 18, 2:17 pm, castironpi wrote: > On Jul 17, 11:39 pm, Kay Schluehr wrote: > > > > > On 18 Jul., 01:15, castironpi wrote: > > > > On Jul 17, 5:37 pm, I V wrote: > > > > > On Thu, 17 Jul 2008 15:08:17 -0700, castironpi wrote: > > > > > The Python disassembly is baffling though. > > > > > >>>> y= 3 > > > > >>>> dis.dis('x=y+1') > > > > > You can't disassemble strings of python source (well, you can, but, as > > > > you've seen, the results are not meaningful). You need to compile the > > > > source first: > > > > > >>> code = compile('y=x+1','-', 'single') > > > > >>> dis.dis(code) > > > > > 1 0 LOAD_NAME 0 (x) > > > > 3 LOAD_CONST 0 (1) > > > > 6 BINARY_ADD > > > > 7 STORE_NAME 1 (y) > > > > 10 LOAD_CONST 1 (None) > > > > 13 RETURN_VALUE > > > > > You may well find these byte codes more meaningful. Note that there is a > > > > list of opcodes athttp://docs.python.org/lib/bytecodes.html > > > > Oh. How is the stack represented? > > > As a pointer to a pointer of PyObject structs. > > > > Does it keep track of which stack > > > positions (TOS, TOS1, etc.) are in what registers? Does stack > > > manipulation consume processor cycles? > > > Python does not store values in registers. It stores locals in arrays > > and accesses them by position ( you can see the positional index in > > the disassembly right after the opcode name ) and globals / object > > attributes in dicts. > > > For more information you might just download the source distribution > > and look for src/Python/ceval.c. This file contains the main > > interpreter loop. > > Ah, found it. The parts that are making sense are: > > register PyObject **stack_pointer; > #define TOP() (stack_pointer[-1]) > #define BASIC_POP() (*--stack_pointer) > > ...(line 1159)... > w = POP(); > v = TOP(); > if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { > /* INLINE: int + int */ > register long a, b, i; > a = PyInt_AS_LONG(v); > b = PyInt_AS_LONG(w); > i = a + b; > if ((i^a) < 0 && (i^b) < 0) > goto slow_add; > x = PyInt_FromLong(i); > > ... Which is more than I was picturing was involved. I understand it > is also specific to CPython. Thanks for the pointer to the code. > > My basic question was, what is the difference between compilers and > interpreters, and why are interpreters slow? I'm looking at some of > the answer right now in "case BINARY_ADD:". The basic difference between a (traditional) compiler and an interpreter is that a compiler emits (assembly) code for a specific machine. Therefore it must know the specifics of the machine (how many registers, memory addressing modes, etc), whereas interpreters normally define themselves by their conceptual state, that is, a virtual machine. The instructions (bytecode) of the virtual machine are generally more high-level than real machine instructions, and the semantics of the bytecode are implemented by the interpreter, usually in a sort-of high level language like C. This means the interpreter can run without detailed knowledge of the machine as long as a C compiler exists. However, the trade off is that the interpreter semantics are not optimized for that machine. This all gets a little more hairy when you start talking about JITs, runtime optimizations, and the like. For a real in-depth look at the general topic of interpretation and virtual machines, I'd recommend Virtual Machines by Smith and Nair (ISBN:1-55860910-5). -Dan From durand1 at gmail.com Thu Jul 10 16:40:33 2008 From: durand1 at gmail.com (Durand) Date: Thu, 10 Jul 2008 21:40:33 +0100 Subject: PIL: Transparent PNGs and im.paste: ValueError: bad transparency mask Message-ID: I posted this too soon. Converting the images to png with image magick's convert did the trick...However, I'm still not sure why I need to convert the images in the first place. Are there different types of PNGs? From torriem at gmail.com Mon Jul 28 04:56:29 2008 From: torriem at gmail.com (Michael Torrie) Date: Mon, 28 Jul 2008 02:56:29 -0600 Subject: Attack a sacred Python Cow In-Reply-To: <87myk2sbk3.fsf@nokile.rath.org> References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c29cc$0$20302$c3e8da3@news.astraweb.com> <20080727193416.GE7373@dragontoe.org> <488D580B.9050001@gmail.com> <87myk2sbk3.fsf@nokile.rath.org> Message-ID: <488D89BD.8060708@gmail.com> Nikolaus Rath wrote: > No, but it could work like this: > > def a(x, y): > self.x = x > self.y = y > Frankly this would make reading and debugging the code by a third party to be a nightmare. Rather than calling the variable self as I did in my example, I could it in a much better way: def method(my_object, a, b): my_object.a = a my_object.b = b Now if I saw this function standalone, I'd immediately know what it was doing. In fact, I can even unit test this function by itself, without even having to know that later on it's monkey-patched into an existing class. With your idea, I might get the picture this function should be used as a method in some object because of the self reference, but I can't test the method by itself. Trying to call it would instantly result in an exception. And if this was a large function, I might not even see the self reference right away. From basti.wiesner at gmx.net Wed Jul 23 08:16:03 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Wed, 23 Jul 2008 14:16:03 +0200 Subject: Proper way to query user and group database on a Unix host? References: <87d4l5ozsc.fsf@cox.net> Message-ID: Chris Brannon : Iirc since Python 2.5 these tuples are named ... > Instead, do this: > > import grp > groupname = 'users' > groupusers = grp.getgrnam(groupname)[3] ... thus this line could be written as: groupusers = grp.getgrnam(groupname).gr_mem Slightly more readable, imho -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From fredrik at pythonware.com Tue Jul 15 17:11:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2008 23:11:52 +0200 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: Victor Noagbodji wrote: > Well that's exactly why I'm asking. Since None returns False in if > statements. Why do people use if name is not None: instead of simply > writing if not name? Because they want to distinguish between None and other values that evaluate to False, of course. As the page I linked to explains, there are many objects that evaluate to false in a boolean context; None is just one of them. Or to spell it out: if you need to distinguish between None and other false values, use an explicit test. If you don't need to distinguish between None and other false values, don't use an explicit test. From asd at pittle.org Thu Jul 3 16:13:48 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Thu, 3 Jul 2008 13:13:48 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> <9ad840e1-e12f-4125-8537-4bad2ef77f51@w5g2000prd.googlegroups.com> <6b1e8a6c-4d21-488d-a8b9-74388f1f5c43@m45g2000hsb.googlegroups.com> Message-ID: <4574e6fb-0146-45b9-a84c-028787464f05@i36g2000prf.googlegroups.com> On Jul 3, 7:38?pm, Fuzzyman wrote: > On Jul 2, 9:33?am, Ali Servet D?nmez wrote: > > > > > On Jul 1, 12:15?am, Fuzzyman wrote: > > > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > > I don't want to be so mean here, but how hard it could be be writing a > > > > freesoftware which would automatically/intelligently auto complete > > > > Python code? (I mean something that really does the job, like > > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > > name it, but just don't give me PyDev please...) > > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > > missing here? > > > > > Could someone please point me out something that I'm really missing > > > > which is already present in the wild, otherwise I'd like discuss with > > > > whoever is willing to help me to get this thing done. I made my mind > > > > and I could volunteer to make this happen as thesis project for my > > > > incoming graduation in the next year. > > > > > Regards you all, > > > > Ali Servet D?nmez > > > > Vim, Emacs, Wing, Komodo, ... more? > > > > Yeah, I guess you're missing something. :-) > > > > MichaelFoordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > > I've checkout Wing IDE's license and it doesnt' seem to be a > > freesoftware; am I wrong? > > Wing 101 is free. The software is good enough though that it is worth > supporting its development by paying for it. > > Michael Foord > --http://www.ironpythoninaction.com/http://www.trypython.org/ I wasn't referring to its fee, but the fact of having a freedom restricting license. From Ilan.i18n at gmail.com Sun Jul 13 08:11:10 2008 From: Ilan.i18n at gmail.com (Ilan) Date: Sun, 13 Jul 2008 05:11:10 -0700 (PDT) Subject: Dynamic Invocation Interface Message-ID: <08386e58-5972-449b-8107-05bca20c6260@y38g2000hsy.googlegroups.com> Is there any python CORBA ORB that support Dynamic Invocation Interface? Thanks From pavlovevidence at gmail.com Sun Jul 13 14:30:36 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 13 Jul 2008 11:30:36 -0700 (PDT) Subject: Mutually referencing imports -- impossible? References: Message-ID: On Jul 13, 1:55?pm, Matthew Wilson wrote: > I started off with a module that defined a class Vehicle, and then > subclasses Car and Motorcycle. > > In the Car class, ?for some bizarre reason, I instantiated a Motorcycle. > Please pretend that this can't be avoided for now. > > Meanwhile, my Motorcycle class instantiated a Car as well. > > Then I moved the Car and Motorcycle classes into separate files. ?Each > imported the Vehicle module. > > Then I discovered that my Car module failed because the global > Motorcycle wasn't defined. ?The same problem happened in my Motorcycle > module. ?Car and Motorcycle can't both import each other. > > In the beginning, when all three (Vehicle, Car, and Motorcycle) were > defined in the same file, everything worked fine. > > I don't know how to split them out in separate files now though and I > really wish I could because the single file is enormous. > > Any ideas? First thing to do is ask yourself: Are the Car and Motorcycle being created at import time, or are they being created after the imports by a function call? If it's the former, then yes, it's impossible. You can't do this, for instance: car.py: ----------------- import motorcycle a = motorcycle.Motorcycle() ----------------- motorcycle.py: ----------------- import car b = car.Car() ----------------- However, you can stick them in functions and call them afterwards and it will work: car.py: ----------------- import motorcycle def create_motorcycle(): global a a = motorcycle.Motorcycle() ----------------- motorcycle.py: ----------------- import car def create_car(): global b a = car.Car() ----------------- vehicle.py ----------------- import car import motorcycle car.create_motorcycle() motorcycle.create_car() ----------------- Second, if you're using from ... import statements, it won't work; you should change it to use plain imports as I did above. So the following wouldn't work : motorcycle.py: ----------------- from car import * a = Motorcycle() ----------------- car.py: ----------------- from motorcycle import * b = Car() ----------------- Third, if Motorcycle and Car are inside packages, you still need to avoid from ... import even just to import the module (unless you're willing to hook into the import machinery). For example, if car.py, motorcycle.py, and vehicle.py are all parts of the package carsim, then you'd have to do this: motorcycle.py: ---------------- import carsim.car def create_car(): global a a = carsim.car.Car() ---------------- and not motorcycle.py: ---------------- from carsim import car def create_car(): global a a = car.Car() ---------------- This last limitation is due to a wart in the import logic. Carl Banks From babacity2 at gmail.com Thu Jul 24 16:56:39 2008 From: babacity2 at gmail.com (babacity2 at gmail.com) Date: Thu, 24 Jul 2008 13:56:39 -0700 (PDT) Subject: Peachy18 forum - Amazing porn video collection Message-ID: peachy18 forum . >>>>>>>>>>Best Collection of Peachy18 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE peachy18 forum VIDEOS<<<<<<<<<<< . peachy18 forum From workitharder at gmail.com Sat Jul 12 23:23:16 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 12 Jul 2008 20:23:16 -0700 (PDT) Subject: socket.connect() hangs in SYN_SENT state. Message-ID: I'm having an issue where my program hangs while doing socket.connect() for a couple minutes, then times out the connection and crashes. I'm connecting to an apache2 process on the same machine, for testing. When looking at netstat, the socket is in the SYN_SENT state, like this: $netstat -a -tcp tcp 0 0 *:www *:* LISTEN 7635/apache2 tcp 0 1 bukzor:38234 adsl-75-61-84-249.d:www SYN_SENT 9139/python Anyone know a general reason this might happen? Even better, a way to fix it? Doing a minimal amount of research, I found this in the netstat manual: The state SYN_SENT means that an application has made arequest for a TCP session, but has not yet received the return SYN+ACK packet. This would indicate it's a server issue, but it seems very stable when I look at it via a browser. Here's the server. If you browse to it, it documents the exported functions: http://bukzor.hopto.org/modpython/xmlrpc.py Here's my test client that's hanging. Turn 'verbose' to True to get more debugging info. [code] #!/usr/bin/env python from xmlrpclib import ServerProxy s = ServerProxy("http://bukzor.hopto.org/modpython/xmlrpc.py", verbose=False) print s.helloworld() print s.add(1,2) print s.subtract(1,2) [/code] Thanks, --Buck From Nikolaus at rath.org Mon Jul 28 05:31:29 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 28 Jul 2008 11:31:29 +0200 Subject: os.symlink() Message-ID: <87d4kys6by.fsf@nokile.rath.org> Hello, >From `pydoc os`: symlink(...) symlink(src, dst) Create a symbolic link pointing to src named dst. Is there any reason why this is so deliberately confusing? Why is the target of the symlink, the think where it points *to*, called the `src`? It seems to me that the names of the parameters should be reversed. Puzzled, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From gagsl-py2 at yahoo.com.ar Mon Jul 28 06:12:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 Jul 2008 07:12:38 -0300 Subject: method decorators and more on decorators References: <7fd737460807271126m3dbdea8cv4dbd8c9058d4faea@mail.gmail.com> Message-ID: En Sun, 27 Jul 2008 15:26:39 -0300, Themistoklis Bourdenas escribi?: > Hi, is there any possible way to get the class or class name inside a method > decorator? For example in the code sample below: > > def decorate(func): > print type(func) > return func > > class myclass: > > @decorate > def foo(self): > pass > > The output of this program will be the type of the supplied func in > decorate, i.e. method foo. However, the type is function foo, a free > function, not an instance method myclass.foo. Because the decorator is applied when the function is defined - and as you already noted, foo is a plain function (stored into myclass's namespace). Only when, later, the name foo is searched in the class, the descriptor protocol comes into play and a method object is built from the function and the myclass instance. > On a related note, as the actual instance method of myclass is not foo but > decorate(foo), why are they called method decorators? This does not decorate > methods, they decorate functions and eventually the decorated functions > become methods. The name method decorator sounds a bit misleading to me. Where have you found it? I've always seen the expression "function decorator" or just "decorator", not "method decorator". > So returning to my original question is there any way I can get the class > inside decorate()? I guess there is not, but just asking to make sure. "the class inside decorate"? What do you mean? The type of the x instance in an x.foo() call? That should be determined inside the wrapped function -when it is actually called-. > Speaking of decorators I'd also like to ask on the pending class decorators > that should be coming in a following version of the language. Are they going > to be in 2.6 or just 3.0? In the following example: Both versions come with class decorators. > In essence what is the order of application of class decorators compared to > the function decorators of their methods? I couldn't find any mention of > that issue in any of the PEPs. I guess it would be the latter, following the > behavior of metaclasses, but better be certain than speculate :) I don't have a 2.6/3.0 Python at hand to check, but the (decorated) functions must be built before the class is created (because they are contained in the class's namespace). So the function decorators should be aplied before the class decorator... -- Gabriel Genellina From israelu at elbit.co.il Mon Jul 28 19:00:31 2008 From: israelu at elbit.co.il (iu2) Date: Mon, 28 Jul 2008 16:00:31 -0700 (PDT) Subject: seemingly simple list indexing problem References: Message-ID: <1ad9234a-6bba-48ce-ad40-ea0aeabce492@79g2000hsk.googlegroups.com> On Jul 29, 12:10?am, John Krukoff wrote: > On Mon, 2008-07-28 at 16:24 -0500, Ervan Ensis wrote: > > My programming skills are pretty rusty and I'm just learning Python so > > this problem is giving me trouble. > > > I have a list like [108, 58, 68]. ?I want to return the sorted indices > > of these items in the same order as the original list. ?So I should > > return [2, 0, 1] > > > For a list that's already in order, I'll just return the indices, i.e. > > [56, 66, 76] should return [0, 1, 2] > > > Any help would be appreciated. > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > If your lists aren't so large that memory is an issue, this might be a > good place for a variation of decorate, sort, undecorate. > > >>> listToSort = [ 108, 58, 68 ] > >>> decorated = [ ( data, index ) for index, data in > > enumerate( listToSort ) ]>>> decorated > > [(108, 0), (58, 1), (68, 2)]>>> result = [ None, ] * len( listToSort ) > >>> for sortedIndex, ( ignoredValue, originalIndex ) in > > enumerate( sorted( decorated ) ): > ... ? ? result[ originalIndex ] = sortedIndex > ...>>> result > > [2, 0, 1] > > -- > John Krukoff > Land Title Guarantee Company Inspired by your idea and the above one, here is another try: >>> a0 = [108, 58, 68, 108, 58] >>> a1 = [(x, y) for x, y in enumerate(a0)] >>> a1 [(0, 108), (1, 58), (2, 68), (3, 108), (4, 58)] >>> a2 = sorted(a1, lambda x, y: cmp(x[1], y[1])) >>> a2 [(1, 58), (4, 58), (2, 68), (0, 108), (3, 108)] >>> a3 = [a2.index(x) for x in a1] >>> a3 [3, 0, 2, 4, 1] The idea is to make each item unique (by making it a tuple), and then apply the naive solution. From mensanator at aol.com Tue Jul 29 20:44:41 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 29 Jul 2008 17:44:41 -0700 (PDT) Subject: How can I check nbr of cores of computer? References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> Message-ID: <37e26af1-c6a7-4302-b93c-39164b222f26@34g2000hsf.googlegroups.com> On Jul 29, 5:53?pm, defn noob wrote: > How can I check how many cores my computer has? > Is it possible to do this in a Python-app? If you're using Windows, get PyWin32: win32api.GetSystemInfo tuple = GetSystemInfo() Retrieves information about the current system. Win32 API References Search for GetSystemInfo at msdn, google or google groups. Return Value The return value is a tuple of 9 values, which corresponds to the Win32 SYSTEM_INFO structure. The element names are: dwOemId dwPageSize lpMinimumApplicationAddress lpMaximumApplicationAddress dwActiveProcessorMask dwNumberOfProcessors dwProcessorType dwAllocationGranularity (wProcessorLevel,wProcessorRevision) >>> import win32api >>> win32api.GetSystemInfo() (0, 4096, 65536, 2147418111, 3L, 2, 586, 65536, (6, 3846)) | processors From deets at nospam.web.de Fri Jul 11 07:12:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 11 Jul 2008 13:12:53 +0200 Subject: MySQLdb will only import for root In-Reply-To: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> Message-ID: <6dothnF3lqqmU1@mid.uni-berlin.de> martinnorth schrieb: > Hi, > > I am running Python and MySQL on Ubuntu and have installed MySQLdb. If I > try to import MySQLdb I get the following error: > > ActivePython 2.5.2.2 (ActiveState Software Inc.) based on > Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08) > [GCC 3.3.1 (SuSE Linux)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import MySQLdb > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named MySQLdb > > But if I lrun python as the root user it imports fine. Can anyone > suggest what might be wrong with the installation? Or is there nothing > wrong? I haven't seen any examples that mentioned being root to import a > module. Try importing sys and printing out sys.path both with a "normal" account and the root-account, to see if there are any differences. And of course make sure both actually use the same interpreter. Beyond that, you are right: there is no root-only-importing. Diez From roy at panix.com Sun Jul 13 10:16:31 2008 From: roy at panix.com (Roy Smith) Date: Sun, 13 Jul 2008 10:16:31 -0400 Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> <87skuems49.fsf@benfinney.id.au> <873amddh0n.fsf@benfinney.id.au> Message-ID: In article <873amddh0n.fsf at benfinney.id.au>, Ben Finney wrote: > Which "original class" are you referring to? The one posted by the > original poster of this thread had no "original list"; it gathered the > positional arguments (using '*items') into an 'items' parameter, which > *doesn't exist* until the function body executes. Ah, I didn't notice that. From stefan_ml at behnel.de Wed Jul 30 13:40:42 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 30 Jul 2008 19:40:42 +0200 Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? In-Reply-To: <16218185-7d69-411c-a219-31f2e4e8df9e@p25g2000hsf.googlegroups.com> References: <16218185-7d69-411c-a219-31f2e4e8df9e@p25g2000hsf.googlegroups.com> Message-ID: <4890a79a$0$12954$9b4e6d93@newsspool2.arcor-online.net> Simon Willison wrote: > Follow up question: what's the best way of incrementally consuming XML > in Python that's character encoding aware? iterparse(), as implemented in (c)ElementTree and lxml. Note that ElementTree and cElementTree are part of Python 2.5, in the xml.etree package. > I have a very large file to > consume but I'd rather not have to fall back to the raw SAX API. Large is fairly relative. Both cElementTree and lxml are pretty memory friendly, even when parsing into an in-memory tree. Stefan From callen314 at gmail.com Fri Jul 18 21:17:42 2008 From: callen314 at gmail.com (Craig Allen) Date: Fri, 18 Jul 2008 18:17:42 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> <7ac1b818-8aa9-478f-a922-82baf0d51c5b@w39g2000prb.googlegroups.com> Message-ID: On Jul 17, 9:04 pm, Paddy wrote: > On Jul 16, 11:20 pm, Craig Allen wrote: > > > Hey, forgive me for just diving in, but I have a question I was > > thinking of asking on another list but it really is a general question > > so let me ask it here. It's about how to approach making singletons. > > Hi Craig, > This might be good for a general background on Design Patters in > Python: > > http://uk.youtube.com/watch?v=0vJJlVBVTFg > > - Paddy. thanks for the link paddy, I'll watch it. From hubaghdadi at gmail.com Tue Jul 29 11:08:46 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Tue, 29 Jul 2008 08:08:46 -0700 (PDT) Subject: Build tool for Python Message-ID: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Hi. Apache Ant is the de facto building tool for Java (whether JSE, JEE and JME) application. With Ant you can do what ever you want: compile, generate docs, generate code, packing, deploy, connecting to remote servers and every thing. Do we have such a tool for Python projects? Thank you. From bearophileHUGS at lycos.com Tue Jul 29 14:04:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 29 Jul 2008 11:04:13 -0700 (PDT) Subject: iterating "by twos" References: Message-ID: <9c269ce1-9f0b-430b-b448-1cb79f09263e@56g2000hsm.googlegroups.com> Something like this may be fast enough: >>> from itertools import izip >>> xpartition = lambda seq, n=2: izip(*(iter(seq),) * n) >>> xprimes = (x for x in xrange(2, 100) if all(x % i for i in xrange(2, x))) >>> list(xpartition(xprimes)) [(2, 3), (5, 7), (11, 13), (17, 19), (23, 29), (31, 37), (41, 43), (47, 53), (59, 61), (67, 71), (73, 79), (83, 89)] Bye, bearophile From sturlamolden at yahoo.no Fri Jul 25 10:24:17 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 25 Jul 2008 07:24:17 -0700 (PDT) Subject: PyOpenGL Tutorial? References: Message-ID: <204e0b01-b2e3-496c-98d6-620f373d69ff@n33g2000pri.googlegroups.com> On Jul 23, 10:07?pm, Clay Hobbs wrote: > I need a tutorial for PyOpenGL (specifically, to be used with wxPython). > I searched with Google and didn't find one. ?Does anybody know where one > is? PyOpenGL is just a wrapper for OpenGL. The API is identical. Do you need an OpenGL tutorial? As for wxPython, you just subclass wxGLCanvas. Call the method SetCurrent() before you call OpenGL (e.g. through PyOpenGL) and SwapBuffers() when you are done. See the wxWidgets reference. Personally I think PyOpenGL is a slow beast. It is not just a thin wrapper over OpenGL, but bloated with sanity checks, exception handling, etc (look at the code, it is pure Python and easy to read). I prefer to put all calls to OpenGL in a C DLL, and call that with ctypes. If I make repeated calls to functions like glVertex3f, I want them to to be fast, thus C is indicated over Python. And if all I do in C is to make calls into OpenGL, there is no real advantage to using Python here - the Python code would look almost exactly the same, but would be slower by several orders of magnitude. By the way, I still use wxGLCanvas from wxPython to set things up. The ctypes call into my C DLL is called between SetCurrent() and SwapBuffers(). If you want a pure Python solution, you will need to use display lists, vertex arrays (with NumPy) or vertex buffers (if your graphics card supports it) to get acceptable performance. Here is a short tutorial: import wx import wx.glcanvas import ctypes glrender = ctypes.pydll.glrender.render # use ctypes.cdll to call with GIL released glrender.argtypes = (ctypes.c_int, ctypes.c_int,) glrender.restype = None class MyCanvas(wx.glcanvas.GLCanvas): def __init__(self, parent): attribList = (wx.glcanvas.WX_GL_DOUBLEBUFFER, wx.glcanvas.WX_GL_RGBA, 0) wx.glcanvas.GLCanvas.__init__(self, parent, -1, attribList = attribList) self.context = wx.glcanvas.GLContext(self) self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_PAINT, self.OnPaint) def OnSize(self, evt): w,h = self.GetClientSize() self.w = w self.h = h dc = wx.ClientDC(self) self.Render(dc) def OnPaint(self, evt): dc = wx.PaintDC(self) self.Render(dc) def Render(self, dc): self.SetCurrent() glrender(self.w, self.h) self.SwapBuffers() And then in glrender.c, put the following: #include #include #include __declspec(dllexport) void render(int w, int h) { /* calls to OpenGL goes here */ return; } And for Python 2.5.x on Windows, compile with: gcc -O2 -o glrender.dll -shared -lopengl -lmsvcr71 glrender.c From mail at timgolden.me.uk Fri Jul 4 05:42:39 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 04 Jul 2008 10:42:39 +0100 Subject: better way to search the Python archive In-Reply-To: <00e901c8dd24$c3301ad0$8101a8c0@bocaron> References: <00e901c8dd24$c3301ad0$8101a8c0@bocaron> Message-ID: <486DF08F.4050501@timgolden.me.uk> Jeremy Link wrote: > Just an FYI out to folks that want a better way to search the Python > archive? > > I?ve been using MarkMail (www.markmail.org ) > to search the archives and it works MUCH better than the Google archive. > It is a free hosting of all sorts of GNU/open source mailing lists > (registration NOT required or even available). I agree; it *is* good. However, for a quick-and-dirty, a simple Google search for "site:mail.python.org blah blah" is also useful. TJG From david at abbottdavid.com Wed Jul 23 14:38:33 2008 From: david at abbottdavid.com (David) Date: Wed, 23 Jul 2008 14:38:33 -0400 Subject: tkinter for my python program !! In-Reply-To: <81554f58-cc9c-4649-afdd-45656ab0bf64@b2g2000prf.googlegroups.com> References: <6em5snF7r22oU3@mid.uni-berlin.de> <63ff0b6f-8c75-4172-b836-8497870544ca@s50g2000hsb.googlegroups.com> <6em86gF7q9djU1@mid.uni-berlin.de> <81554f58-cc9c-4649-afdd-45656ab0bf64@b2g2000prf.googlegroups.com> Message-ID: <48877AA9.9050908@abbottdavid.com> > > Further, finally when i invoke the python program by > giving the necessary input file, i get the following > errors . > Does it have any relation with the python version installed ? > yes > I am using Redhat 9.0 You may want to install a current Linux distro. From x at y.z Tue Jul 1 09:02:58 2008 From: x at y.z (name) Date: Tue, 1 Jul 2008 13:02:58 +0000 (UTC) Subject: pyparsing problem Message-ID: Hi, I try to parse a file with pyparsing and get this output: ['generic', 'host-01', 'host alias xyz', '10.0.0.1'] - alias: host alias xyz - host_name: ['host-01'] - ip_address: ['10.0.0.1'] - use: ['generic'] generic host-01 host alias xyz 10.0.0.1 ['generic', 'host-01', 'host alias xyz', '10.0.0.1'] finished What I don't understand is why I get the line generic and not generic as there is an associated name in the dump() output. Thank you very much in advance for any clue or help you could provide. The code: --------- #!/usr/bin/env python from pyparsing import * sample = """ define host{ use generic host_name host-01 alias host alias xyz address 10.0.0.1 } """ # define tokens LBRACE,RBRACE = map(Suppress, '{}') ipAddress = Combine(Word(nums) + ('.' + Word(nums))*3) useTemplate = oneOf('generic user') # define grammar deviceName = Word(alphanums+'-') hostDef = Literal('define').suppress() + Literal('host').suppress() useLine = Suppress('use') + useTemplate + Suppress(SkipTo(lineEnd)) host_nameLine = Suppress('host_name') + deviceName + Suppress(SkipTo (lineEnd)) aliasLine = Suppress('alias') + SkipTo(lineEnd) aliasLine.setParseAction(lambda x: ' '.join(x[0].split())) ip_addressLine = Suppress('address') + ipAddress use = useLine.setResultsName('use') host_name = host_nameLine.setResultsName('host_name') alias = aliasLine.setResultsName('alias') ip_address = ip_addressLine.setResultsName('ip_address') host_stmt = (use + host_name + alias + ip_address) host = hostDef + LBRACE + host_stmt + RBRACE test_file = OneOrMore(host) + stringEnd # test x = test_file.parseString(sample) print x.dump() print print x.asXML('Hosts') print print x.asList() print print 'finished' From forum at namit.org Fri Jul 11 05:31:54 2008 From: forum at namit.org (Christian Kortenhorst (Forum)) Date: Fri, 11 Jul 2008 10:31:54 +0100 Subject: Django admin multi layour Message-ID: Hey All Just been messing around with django and found that can not seam to get admin to work how, it does not support multilayer input I want it I know there is some way of writing your own "view", but wondering would it be possible to write a multilayer setup or what is the wok around or what should i be looking for? my setup is class Faculty(models.Model): class Admin: pass name = models.CharField(maxlength=200) director = models.CharField(maxlength=200) web_url = models.CharField(maxlength=200) def __str__(self): return self.name class School(models.Model): class Admin: pass faculty = models.ForeignKey(Faculty) name = models.CharField(maxlength=200) def __str__(self): return self.name class Programme(models.Model): class Admin: pass duration_choices = ( ('Years', 'years'), ('Days', 'days') ) school = models.ForeignKey(School) name = models.CharField(maxlength=200) description = models.CharField(maxlength=1000) def __str__(self): return self.name class Stream(models.Model): class Admin: pass programme_code = models.ForeignKey(Programme, edit_inline=models.TABULAR, num_in_admin=3) stream_number = models.IntegerField(core=True) ..... Want to be able to click in and keep adding programs to a school and when i do that a new box is created and a steam is created. e.g. add a Faculty -> input for school is shown -> add a school -> -> input for Programme is shown -> -> add a programme -> -> -> etc.. also the option to add new school and program so can have a one to many relationship. Thanks Christian K -- Christian Kortenhorst mod: +353-(0)87-6183349 home: +353-(0)1-4966287 -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Sun Jul 20 10:22:50 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 20 Jul 2008 16:22:50 +0200 Subject: Rotating a cube In-Reply-To: References: <3d47df08-9734-4e0f-96ad-37da445b4faf@34g2000hsh.googlegroups.com> <8156f68a-3f65-4fca-a725-2e0c4240abd1@v21g2000pro.googlegroups.com> <4881BBCF.2060905@preisshare.net> Message-ID: <48834A3A.4020502@gmail.com> Fredrik Lundh wrote: > David Lyon wrote: > >> But is the question about display graphics ? >> >> ie rotating a cube using a python framework ? >> >> With something like python and OpenGL ? or Python and PovRay... or >> perphaps python and imagemagick ? > > can you name one graphics framework that represents a cube as "x + 4*y > + 16*z" ? no, but ... I don't think the notation is so strange, in electronics (and others) I'm used to a 2-dimensional complex notation: vector = 3 + 4*i = 3*x +4*y but although my English isn;t very well, a "cube of 4*4" looks strange to me. cheers, Stef > > > > -- > http://mail.python.org/mailman/listinfo/python-list From gagsl-py2 at yahoo.com.ar Wed Jul 30 01:09:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 02:09:01 -0300 Subject: Dynamically adding methods to a class... References: <19ac19520807282117y4c34ed22n3bcb9c6cf7d198b8@mail.gmail.com> Message-ID: En Tue, 29 Jul 2008 01:17:13 -0300, Piyush Anonymous escribi?: > class MyObject: > def __init__(self, name): > self.name = name > > def do_this_default(self): > print "default do_this implementation for %s" % self.name > > def custom_do_this(): #method to be added > print "custom do_this implementation for %s" % self.name You forget the self argument (this explains the error you got). > def funcToMethod(func,clas,method_name=None): > """Adds func to class so it is an accessible method; use method_name > to > specify the name to be used for calling the method. > The new method is accessible to any instance immediately.""" > import new > method = new.instancemethod(func,None,clas) > print method > if not method_name: method_name=func.__name__ > clas.__dict__[method_name]=func It's a lot easier than that; just add the *function* object to the class namespace: setattr(clas, method_name, func) If you know the name when you write the code, just set the attribute: py> o = MyObject("hello") py> MyObject.custom_do_this = custom_do_this py> o.custom_do_this() custom do_this implementation for hello new.instancemethod is useful to add specific methods to individual instances, but it's not used to add methods globally to the class. > Error I am getting; > TypeError: custom_do_this() takes no arguments (1 given) Add the self argument and you're done. > Why am I getting it? > > Also how can I do this in new style class (inherited from 'object')? It's the same thing, no difference. -- Gabriel Genellina From Russ.Paielli at gmail.com Mon Jul 28 14:46:34 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jul 2008 11:46:34 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> Message-ID: <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> On Jul 28, 4:23 am, Bruno Desthuilliers wrote: > Russ P. a ?crit : > > > > > On Jul 27, 3:11 pm, "Russ P." wrote: > >> On Jul 27, 12:39 pm, Bruno Desthuilliers > > >> wrote: > >>> Derek Martin a ?crit : > >>>> On Sun, Jul 27, 2008 at 08:19:17AM +0000, Steven D'Aprano wrote: > >>>>>> You take the name down to a single letter. As I suggested in an earlier > >>>>>> post on this thread, why not take it down to zero letters? > >>>>> The question isn't "why not", but "why". The status quo works well as it > >>>>> is, even if it isn't perfect. Prove that implicit self is a good idea -- > >>>>> or at least prove that it is an idea worth considering. > >>>> Come on, this sounds like a schoolyard argument. This comes down to a > >>>> matter of style, and as such, is impossible to prove. It's largely a > >>>> question of individual preference. > >>>> That said, the argument in favor is rather simple: > >>>> 1. This is an extremely common idiom in Python > >>>> 2. It is completely unnecessary, and the language does not suffer for > >>>> making it implicit > >>>> 3. Making it implicit reduces typing, reduces opportunities for > >>>> mistakes, and arguably increases consistency. > >>> "arguably", indeed, cf below. > >>>> As for the latter part of #3, self (or some other variable) is > >>>> required in the parameter list of object methods, > >>> It's actually the parameter list of the *function* that is used as the > >>> implementation of a method. Not quite the same thing. And then, > >>> consistency mandates that the target object of the method is part of the > >>> parameter list of the *function*, since that's how you make objects > >>> availables to a function. > >>>> however when the > >>>> method is *called*, it is omitted. > >>> Certainly not. You need to lookup the corresponding attribute *on a > >>> given object* to get the method. Whether you write > >>> some_object.some_method() > >>> or > >>> some_function(some_object) > >>> you still need to explicitely mention some_object. > >>>> It is implied, supplied by Python. > >>> Neither. The target object is passed to the function by the method > >>> object, which is itself returned by the __get__ method of function > >>> objects, which is one possible application of the more general > >>> descriptor protocol (the same protocol that is used for computed > >>> attributes). IOW, there's nothing specific to 'methods' here, just the > >>> use of two general features (functions and the descriptor protocol). > >>> FWIW, you can write your own callable, and write it so it behave just > >>> like a function here: > >>> import types > >>> class MyCallable(object): > >>> def __call__(self, obj): > >>> print "calling %s with %s" % (self, obj) > >>> def __get__(self, instance, cls): > >>> return types.MethodType(self.__call__, instance, cls) > >>> class Foo(object): > >>> bar = MyCallable() > >>> print Foo.bar > >>> f = Foo() > >>> f.bar() > >>>> Thus when an object method is called, it must be called with one fewer > >>>> arguments than those which are defined. This can be confusing, > >>>> especially to new programmers. > >>> This is confusing as long as you insist on saying that what you > >>> "def"ined is a method - which is not the case. > >>>> It can also be argued that it makes the code less ugly, though again, > >>>> that's a matter of preference. > >>>>> It's not enough to show that a change "isn't bad" -- you have to show > >>>>> that it is actively good. > >>>> But he did... he pointed out that *it saves work*, without actually > >>>> being bad. Benefit, without drawback. Sounds good to me! > >>>>> "Don't need to look at the method signature" is not an argument in favour > >>>>> of implicit self. > >>>> Yes, actually, it is. > >>> It isn't, since there's no "method signature" to look at !-) > >>>> If there is a well-defined feature of Python > >>>> which provides access to the object within itself, > >>> The point is that you don't get access to the object "within itself". > >>> You get access to an object *within a function*. > >>> The fact that a function is defined within a class statement doesn't > >>> imply any "magic", it just creates a function object, bind it to a name, > >>> and make that object an attribute of the class. You have the very same > >>> result by defining the function outside the class statement and binding > >>> it within the class statement, by defining the function outside the > >>> class and binding it to the class outside the class statement, by > >>> binding the name to a lambda within the class statement etc... > >>>> then the > >>>> opportunities for mistakes when someone decides to use something else > >>>> are lessened. > >>>>> You don't need to look at the method signature when you're using an > >>>>> explicit self either. > >>>> That isn't necessarily true. If you're using someone else's code, and > >>>> they didn't use "self" -- or worse yet, if they chose this variable's > >>>> name randomly throughout their classes -- then you may well need to > >>>> look back to see what was used. > >>>> It's bad programming, but the world is full of bad programmers, and we > >>>> don't always have the choice not to use their code. Isn't one of > >>>> Python's goals to minimize opportunities for bad programming? > >>> Nope. That's Java's goal. Python's goals are to maximize opportunities > >>> for good programming, which is quite different. > >>>> Providing a keyword equivalent to self and removing the need to name > >>>> it in object methods is one way to do that. > >>> It's also a way to make Python more complicated than it needs to be. At > >>> least with the current state, you define your functions the same way > >>> regardless of how they are defined, and the implementation is > >>> (relatively) easy to explain. Special-casing functions definition that > >>> happens within a class statement would only introduce a special case. > >>> Then you'd have to explain why you need to specify the target object in > >>> the function's parameters when the function is defined outside the class > >>> but not when it's defined within the class. > >>> IOW : there's one arguably good reason to drop the target object from > >>> functions used as methods implementation, which is to make Python looks > >>> more like Java, and there's at least two good reason to keep it the way > >>> it is, which are simplicity (no special case) and consistency (no > >>> special case). > >>> Anyway, the BDFL has the final word, and it looks like he's not going to > >>> change anything here - but anyone is free to propose a PEP, isn't it ? > >> The issue here has nothing to do with the inner workings of the Python > >> interpreter. The issue is whether an arbitrary name such as "self" > >> needs to be supplied by the programmer. > > >> Neither I nor the person to whom you replied to here (as far as I can > >> tell) is suggesting that Python adopt the syntax of Java or C++, in > >> which member data or functions can be accessed the same as local > >> variables. Any suggestion otherwise is a red herring. > > >> All I am suggesting is that the programmer have the option of > >> replacing "self.member" with simply ".member", since the word "self" > >> is arbitrary and unnecessary. Otherwise, everything would work > >> *EXACTLY* the same as it does now. This would be a shallow syntactical > >> change with no effect on the inner workings of Python, but it could > >> significantly unclutter code in many instances. > > >> The fact that you seem to think it would change the inner functioning > >> of Python just shows that you don't understand the proposal. > > > It just occurred to me that Python could allow the ".member" access > > regardless of the name supplied in the argument list: > > > class Whatever: > > > def fun(self, cat): > > > .cat = cat > > self.cat += 1 > > > This allows the programmer to use ".cat" and "self.cat" > > interchangeably. If the programmer intends to use only the ".cat" > > form, the first argument becomes arbitrary. Allowing him to use an > > empty argument or "." would simply tell the reader of the code that > > the ".cat" form will be used exclusively. > > > When I write a function in which a data member > > Python has nothing like "data member" (nor "member function" etc). It > has class attributes and instance attributes, period. *Python is not > C++*. So please stop using C++ terms which have nothing to do with > Python's object model. > > > will be used several > > times, I usually do something like this: > > > data = self.data > > > so I can avoid the clutter of repeated use of "self.data". If I could > > just use ".data", I could avoid most of the clutter without the extra > > line of code renaming the data member. > > The main reason to alias an attribute is to avoid the overhead of > attribute lookup. > > > A bonus is that it becomes > > clearer at the point of usage that ".data" is member data rather than > > a local variable. > > I totally disagree. The dot character is less obvious than the 'self.' > sequence, so your proposition is bad at least wrt/ readability (it's > IMHO bad for other reasons too but I won't continue beating that poor > dead horse...) Man, you are one dense dude! Can I give you a bit of personal advice? I suggest you quit advertising your denseness in public. Letting "self" (or whatever the first argument was) be implied in ".cat" does absolutely *NOTHING* to change the internal workings of the Python interpreter. It's a very simple idea that you insist on making complicated. As I said, I could write a pre-processor myself to implement it in less than a day. As for "dot" being less obvious than "self.", no kidding? Hey, "self." is less obvious than "extraspecialme.", so why don't you start using the latter? Has it occurred to you that the difference between 1.000 and 1000 is just a dot? Can you see the difference, Mr. Magoo? Your posts here are typical. I'm trying to make a suggestion to reduce the clutter in Python code, and you throw tomatoes mindlessly. You seem to think that being a "regular" on this newsgroup somehow gives you special status. I sure wish I had one tenth the time to spend here that you have. But even if I did, I have far more important work to do than to "hang out" on comp.lang.python all day every day. Man, what a waste of a life. Well, I guess it keeps you off the streets at least. From martin at v.loewis.de Sat Jul 26 05:20:18 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 26 Jul 2008 11:20:18 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: References: <1216966424.4685.1265275245@webmail.messagingengine.com> <4889AC5E.8090909@egenix.com> Message-ID: <488aec52$0$21481$9b622d9e@news.freenet.de> > The end result of that is on a 32-bit machine IronPython runs in a > 32-bit process and on a 64-bit machine it runs in a 64-bit process. That's probably not exactly true (although I haven't checked). When you start a .NET .exe program, the operating system needs to decide whether to create a 32-bit or a 64-bit process (assuming the processor supports 64-bit mode). The Microsoft .NET commercial framework uses the PE architecture of the executable to make that decision (or, rather, it doesn't decide at all, but the underlying OS decides). The C# compiler (more specifically, the assembly linker) offers a choice of setting the .NET architecture to Itanium, AMD64, x86, or "any"; people use typically "any". This "any" choice is implemented by setting the PE architecture to "any", and then indicating to the .NET run-time that any other architecture would be fine as well. As a consequence, an architecture-any executable launches as a 32-bit process on a 64-bit system. To have the executable launch as 64-bit code, you must tell csc.exe to create an AMD64 binary (say), which then means that the binary won't launch on a 32-bit system. I haven't checked, but my guess is that IronPython uses architecture-any executables (unless you adjust the build process). Things are different in a DLL: an architecture-any DLL will load into a 32-bit process as 32-bit code, and into a 64-bit process as 64-bit code. Regards, Martin From fredrik at pythonware.com Wed Jul 23 15:52:46 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 21:52:46 +0200 Subject: Using variables across modules In-Reply-To: <855136ce-6c70-40ac-a462-dc0bbfa1fc3a@b2g2000prf.googlegroups.com> References: <855136ce-6c70-40ac-a462-dc0bbfa1fc3a@b2g2000prf.googlegroups.com> Message-ID: Aaron Scott wrote: > I'm having some trouble understanding how Python handles variables > across multiple modules. I've dug through the documentation, but I > still find myself at a loss. > > When you import a module, are you creating an instance of the > variables within? For instance, if I have one file, "variables.py", > which contains "myvar = 0", and I import it into both "foo.py" and > "bar.py" with the line "from variables import *", and then set myvar > in "foo.py" and "bar.py" to different values, will each file have a > different value for myvar? If so, how can I ensure that a change to > myvar in "bar.py" is reflected by "foo.py"? Or am I completely off > base? first read this to learn how objects and variables work in Python: http://effbot.org/zone/python-objects.htm and then read this to learn how from-import works, and when you're supposed to use it: http://effbot.org/zone/import-confusion.htm hope this helps! From mva.led at gmail.com Thu Jul 3 10:20:54 2008 From: mva.led at gmail.com (Manuel Vazquez Acosta) Date: Thu, 03 Jul 2008 10:20:54 -0400 Subject: A fix for OverflowError in 64bits platforms Message-ID: <486CE046.6080104@gmail.com> Hi all, I'm debugging a Plone site in an AMD64 laptop. When I first tried to run Zope, I got this exception: OverflowError: signed integer is greater than maximum In the archives I encounter no solutions. This is what I could find, so I share with you all: It seems that on 64bit platforms, sys.maxint is much greater than list's insertion maximum index. I'm not sure if this a bug in python or a logical bound ---given the amount of RAM it would take to insert 9,223,372,036,854,775,807 items ;)--- Maybe a bug in the documentation, though However, Archetypes.Schema.moveField method documents the use of maxint for inserting at the end of the Schema:: maxint can be used to move the field to the last position possible >>> from sys import maxint >>> spos = schema.copy() >>> spos.moveField('a', pos=maxint) >>> spos.keys() ['b', 'c', 'a'] I have seen this usage in some products. This raises and OverflowError on 64bit platforms. The fix is simple in the code of the caller:: from sys import maxint if maxint >> 33: # Am I running on 64bits? maxint = maxint >> 33 theschema.moveField(the_name, pos=maxint) Now, the maxint variable holds an acceptable value. I think the docstring should be appended with a "Note: On 64bits platform this raises an OverflowError blah blah..." Best regards, Manuel. From deets at nospam.web.de Tue Jul 29 07:32:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jul 2008 13:32:26 +0200 Subject: Python COM References: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> <488eff34$0$869$ba4acef3@news.orange.fr> Message-ID: <6f8dgfFabuohU1@mid.uni-berlin.de> M?ta-MCI (MVP) wrote: > Hi! > > Example, with Pywin32: > > import win32com.client > moncom = win32com.client.Dispatch('MyCOM1.AdvMethod') > moncom.IAdvMethod(... > > See Pywin32 here: http://sourceforge.net/projects/pywin32/ That's not working, because the OP has a custom interface, not IDispatch-based. Diez From jeffober at gmail.com Mon Jul 21 08:01:40 2008 From: jeffober at gmail.com (Jeff) Date: Mon, 21 Jul 2008 05:01:40 -0700 (PDT) Subject: simple question about dictionaries References: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> Message-ID: <8aedc744-f432-4a4a-a6e4-2bb714caf720@x35g2000hsb.googlegroups.com> On Jul 21, 7:35?am, skazhy wrote: > hi, i am new to python, so i've a really simple question about > dictionaries. > if i have a dictionary and I make have an input after it (to input > numbers) can i get the key of value that was in input? > > somehting like this: > dict = { "key1"=100,"key2"=200,"key3"=300} > a = input() > print 'the key of inputted value is', dict['a'] > > this syntax of course is wrong, but i hope you got the point.. > > thanks in advance! I don't think there is a built-in that retrieves dict keys by value, but if the dictionary were small enough, you could search the list of key/value pairs returned by dict.items(). You can also iterate through all pairs with dict.iteritems(), which returns an iterator. Something like: def key_by_value(dct, val): for k, v in dct.iteritems(): if v == val: return v throw KeyError('%s not found' % str(val)) From deets at nospam.web.de Thu Jul 31 05:29:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 11:29:02 +0200 Subject: working pylint anyone? Message-ID: <6fdf17Fb2bboU1@mid.uni-berlin.de> Hi, until yesterday I was a happy user of pylint. Then I upgraded to ubuntu hardy heron - and the trouble began. The packaged version of pylint (0.13.2) fails with this error (last line): logilab.common.configuration.UnsupportedAction: callback The same error happens if I use easy_install-2.5 http://release.ingeniweb.com/third-party-dist/logilab.installer-0.1.tgz as found on the net. Using easy_install pylint misses logilab-common & astng, installing these additionally (easy_install) creates two eggs - but unfortunately, the don't actually create a namespace-package logilab, instead either one of them is picked up depending on installation order. Then I tried the source releases - no luck either, either they produce the same error or something similar. I tried looking into the MLs - the last posts are from around 2006, so I refrained from actually subscribing. So - anybody out here having an actually working pylint config and can tell me what versions work together? I've become pretty dependend on it to be honest... Diez From boaz at feldbaum.name Fri Jul 18 09:14:27 2008 From: boaz at feldbaum.name (Boaz Feldbaum) Date: Fri, 18 Jul 2008 16:14:27 +0300 Subject: How to register an extension DLL with python 2.5? References: Message-ID: OK, found it! I just had to give my dll a new file extension: PYD, that is rename it from foo.dll to foo.pyd "Boaz Feldbaum" wrote in message news:g5pvco$j4c$1 at news4.netvision.net.il... > Hello all, > > I wrote an extension dll in C++ using VS2005 to be used in windows > platform. In pyhon 2.4 I used to copy my dll to the dlls sub-directory of > python installation and import my dll and it worked fine. This doesn't > work with python 2.5. I get the following when trying to import my dll: > >>>> import pywutil > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named pywutil >>>> > > What should I do in 2.5 to be able to import my extension dll? > > Thanks a lot in advance, > Boaz. > From mail at timgolden.me.uk Sun Jul 20 11:36:25 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 20 Jul 2008 16:36:25 +0100 Subject: Missing sqlite3.h Error when Building Debug Python -- Windows Vista In-Reply-To: <048b8df4-8468-47a1-ae15-d84ca9d43e0a@y38g2000hsy.googlegroups.com> References: <048b8df4-8468-47a1-ae15-d84ca9d43e0a@y38g2000hsy.googlegroups.com> Message-ID: <48835B79.6030105@timgolden.me.uk> Bev in TX wrote: > I am a complete newbie at building Python. I am trying to build it > under MS Windows Vista (64-bit AMD) with MS VS2005. I'm doing that > because I need debug libraries, which I did not see in the standard > distribution. I'll leave others to comment on whether or not it's expected to build with VS2005, but the easiest way to get a debug build is to pretend to be a buildbot. 1) Check out the python source into, say, c:\dev\python svn co http://svn.python.org/projects/python/trunk c:\dev\python 2) Switch to that directory cd \dev\python 3) Pretend to be a buildbot tools\buildbot\build This will checkout all the necessary sources into, in my example, c:\dev. It will then run all the build steps necessary to get a debug build which will then be in c:\dev\python\pcbuild\python_d.exe TJG From youlan_hao at sina.com Thu Jul 10 22:33:22 2008 From: youlan_hao at sina.com (128) Date: Thu, 10 Jul 2008 19:33:22 -0700 (PDT) Subject: paypal wholesale men jordans 17 (paypal accept)(www super-saler com Message-ID: paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans 18 (paypal accept)(www super-saler com paypal wholesale men jordans 19 (paypal accept)(www super-saler com paypal wholesale men jordans 20 (paypal accept)(www super-saler com paypal wholesale men jordans 21 (paypal accept)(www super-saler com paypal wholesale men jordans 22 (paypal accept)(www super-saler com paypal wholesale men jordans 23 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans 18 (paypal accept)(www super-saler com paypal wholesale men jordans 19 (paypal accept)(www super-saler com paypal wholesale men jordans 20 (paypal accept)(www super-saler com paypal wholesale men jordans 21 (paypal accept)(www super-saler com paypal wholesale men jordans 22 (paypal accept)(www super-saler com paypal wholesale men jordans 23 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans 18 (paypal accept)(www super-saler com paypal wholesale men jordans 19 (paypal accept)(www super-saler com paypal wholesale men jordans 20 (paypal accept)(www super-saler com paypal wholesale men jordans 21 (paypal accept)(www super-saler com paypal wholesale men jordans 22 (paypal accept)(www super-saler com paypal wholesale men jordans 23 (paypal accept)(www super-saler com From cromulent at justextrememetal.com Tue Jul 15 09:37:37 2008 From: cromulent at justextrememetal.com (Cromulent) Date: Tue, 15 Jul 2008 14:37:37 +0100 Subject: Why is there no GUI-tools like this for Windows? References: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> Message-ID: <2008071514373716807-cromulent@justextrememetalcom> On 2008-07-12 22:35:58 +0100, maestro said: > http://www.youtube.com/watch?v=PXpwC1o5AcI > > I have done some GUI-programming for windows with Python but the > Tkinter interface sucked and while it is the only one I tried I got > the impression they are all the same. > > It's amazing how retarded a lot of the stuff programmers do is. > Watcing that video, that is how it should be. > > I can just do the layout with my mouse and then there is a program > that writes the code for me. > GUI-programming is hard for no reason. One good program then forever > easy... > > Is there not something like this for Python/Windows? Is the Linux one > only for ruby or for any language? > > Oh well im switching to Linux anyway and mostly write webapps but > still... PyQt4 is available for Windows and lets you use the Qt Designer application which is pretty good. Works well, you should take a look. -- "I disapprove of what you say, but I'll defend to the death your right to say it." - Voltaire From george.sakkis at gmail.com Fri Jul 11 19:18:34 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jul 2008 16:18:34 -0700 (PDT) Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> Message-ID: On Jul 11, 1:00?pm, James Fassett wrote: > Hi all, > > Had a simple problem that turned into an interesting solution and I > thought I would share it here. > > I had a list of tuples that I needed to get the first value from and > generate a list. > > tuple_list = ( > ? ? ('John', 'Doe'), > ? ? ('Mark', 'Mason'), > ? ? ('Jeff', 'Stevens'), > ? ? ('Bat', 'Man') > ? ) > > # what I'd do in C or other procedural languages > result_list = [] > for item in tuple_list: > ? ? result_list.append(item[0]) > > # the first Pythonic attempt using comprehensions > result_list = [x[0] for x in tuple_list] > > # the final functional way > [result_list, _] = zip(*tuple_list) > > I really like how Python allows me to do what I feel is the most > natural solution (for a seasoned procedural programmer) while allowing > a satisfying path towards a more functional approach. First off, what exactly does make you think of the last approach as "functional" ? It relies on positional arguments, tuple unpacking and the signature of zip(), none of which are functional in the usual programming language sense of the word. Second, it is less readable, robust and efficient than the list comprehension. An example of a really functional approach without all these drawbacks would be bearophile's map(itemgetter(0), tuple_list) since itemgetter() is a high order function (more specifically, a function that returns another function). The list comprehension is still the most pythonic approach though. Regards, George From tjreedy at udel.edu Thu Jul 24 21:33:17 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jul 2008 21:33:17 -0400 Subject: file operations. In-Reply-To: <73045cca0807241546k3697a77cs999bad6d62867167@mail.gmail.com> References: <73045cca0807241546k3697a77cs999bad6d62867167@mail.gmail.com> Message-ID: aditya shukla wrote: > Guys thanks for your previous help .I have a doubt again > > My text file is :- > > 0\9\10\11|0.50|c:\windows\apppatch/AcLayers.dll ... > > now this is what happens > > >>> x=open("c:\\test2.txt","rb") > >>> x.readline() > > '\n' ---? i am not able to understand why is new line character > returned here Either because your text file starts with a blank line or because .readline does not work when you open in binary mode. In any case, you should probably change 'rb' to 'r'. > > >>> l =x.readline() > >>> print l > > > Also , because of this i am not able to extract the floating point > values ie 0.50,0.50,0.66 respectively > cause when i use the proposed solution given earlier > > data=[] > for line in x: > line=line.split("|") > data.append(float(line[-2])) --> i am trying to get the floating > point values from the back > > i receive this error message > > Traceback (most recent call last): > File "", line 3, in > d.append(float(line[-2])) > IndexError: list index out of range If you have a blank line, splitting returns a list of length 0 or 1, so there is no -2 element. Add something like if len(line) < 2: raise SomeError(message) after the split. If you should always have 3 parts, check '==3' and index to line[1]. tjr From siona at chiark.greenend.org.uk Wed Jul 30 09:14:42 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 30 Jul 2008 14:14:42 +0100 (BST) Subject: Native Code vs. Python code for modules References: Message-ID: alex23 wrote: >On Jul 30, 1:56=A0pm, koblas wrote: >> Ruby has been getting pummeled for the last year or more on the >> performance subject. =A0They've been working hard at improving it. =A0Fro= >m >> my arm chair perspective Python is sitting on it's laurels and not >> taking this as seriously as it probably should. > >Well, the snarky response is most Python developers are too busy >working on actual real world projects :) The follow-up snarky response is that working on actual real world projects has lead Python developers to realise that most real world bottlenecks arise from disk access, network speed, and user interaction, and you should only sweat about code speed in the rare case when you *know* that it's not its interface to the real world that's slow. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From Russ.Paielli at gmail.com Wed Jul 30 02:30:48 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 23:30:48 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> Message-ID: <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> On Jul 29, 11:09 pm, Erik Max Francis wrote: > I'm getting this sneaking suspicion that you guys are all putting us on. As I said in an earlier post, I realize that this would only work if there were only one copy of "empty" (as there is only one copy of "None"). I don't know off hand if that is feasible or not. You reply reeks of the kind of pedantic snobbishness that makes me sick. From kdawg44 at gmail.com Fri Jul 18 16:09:58 2008 From: kdawg44 at gmail.com (K-Dawg) Date: Fri, 18 Jul 2008 16:09:58 -0400 Subject: Distributing Python App In-Reply-To: References: <072bf39b-d700-482e-ab59-36840e21e83e@a70g2000hsh.googlegroups.com> Message-ID: <5caea3690807181309x686727dbs6d72fa6f594978d8@mail.gmail.com> On Fri, Jul 18, 2008 at 3:43 PM, Stephen Johnson wrote: > Look up py2app and py2exe, for OS X and Windows, respectively. They are > extensively documented and easy to use. > On Jul 18, 2008, at 3:35 PM, KDawg44 wrote: > > Hi, > > I am very new to Python but find it very interesting (from what I know > of it) and am considering writing an application. However, I have a > question regarding distribution of the app once it is done. Is there > a way to package everything a user needs to run the app or will they > have to install Python their machine? This is probably an obvious > question but most development I do is for administrative tasks on > servers and such, not usually development of an app for someone else. > > Thanks for your help. > > Kevin > -- > http://mail.python.org/mailman/listinfo/python-list > > > Thanks! I'll look into that. -- Kevin "We are what we repeatedly do. Excellence, then, is not an act, but a habit." - Aristotle." -------------- next part -------------- An HTML attachment was scrubbed... URL: From hat at se-162.se.wtb.tue.nl Wed Jul 9 05:04:21 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 09 Jul 2008 11:04:21 +0200 Subject: Newbie question References: <3b1e6f480807082337l419fd40ax91eaf13e0701c5b3@mail.gmail.com> Message-ID: On 2008-07-09, |e0 wrote: > So, i can't use wmi module on linux? > > On Wed, Jul 9, 2008 at 9:14 AM, Lamonte Harris wrote: >> I think the win32 module is only for windows. >> Welcome to the world outside MS. Many python modules don't actually do anything than passing on calls to an existing underlying library. They are cheap to make, and make it possible to use the functionality of the library from a Python program. The down-side is, as you have discovered, that you need the underlying library to make it work. So, the answer is no, you cannot use wmi under a non-MS OS. (But what did you expect, given that wmi means WINDOWS Management Instrumentation?) No doubt there are also open source variants of this package, however, I am not familiar with them, so I cannot help you. Albert From joe at goldthwaites.com Tue Jul 1 20:51:35 2008 From: joe at goldthwaites.com (Joe Goldthwaite) Date: Tue, 1 Jul 2008 17:51:35 -0700 Subject: SQLite and Python 2.4 Message-ID: <200807020051.m620pxS4011942@vm-mailout2.fpw.ch> I'm confused. (Not a new experience). I've got a web application running under Zope. I use the Wing IDE for testing and debugging. When trying to recreate problems that come up on the web, I wrote some little routines that pull my cookies out of the Firefox cookies.txt file into my code. That way, I'm working with all the same options under Wing that my app uses when running under Zope. That's worked great until I upgraded to Firefox 3. Firefox 3 moved their cookies from cookies.txt to cookies.sqlite. I haven't worked with SQLite at all so I started searching for examples and found this; import sqlite3 conn = sqlite3.connect('test.db') c = conn.cursor() rows = c.execute('SELECT * from somefile') Looks simple enough but I can't get it to work. Here are my questions; 1. How do you get sqlite3 for Python 2.4? I can't find it anywhere. 2. If sqlite3 is only for Python 2.5, does sqlite2 work the same way? 3. Looking at the cookies.sqlite file, I see some text right at the top "SQLite format 3". Does that mean that I need to use sqlite3? I kind of got the above example using pysqlite2.4.1 for python 2.4. I get through the part where I create the connection object but the resulting object doesn't have a cursor method. I thought that maybe it wasn't recognizing the cookies.sqlite file as a SQLite database so I tried the same code giving it a junk text file instead and it behaved the same way. Since I didn't get an error message, I'm thinking that I've got the wrong version for the Firefox cookies.sqlite file. I don't have a clue as to where else to look to trace it down. I'm hoping that someone here is more familiar with it and can give me some pointers. Thanks, Joe Goldthwaite From bronger at physik.rwth-aachen.de Sat Jul 26 17:49:29 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 26 Jul 2008 23:49:29 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> Message-ID: <87fxpw8geu.fsf@physik.rwth-aachen.de> Hall?chen! Terry Reedy writes: > Torsten Bronger wrote: > >> D'Arcy J.M. Cain writes: >> >>> On Sat, 26 Jul 2008 09:45:21 +0200 >>> Torsten Bronger wrote: >>> >>>> Of course, "self" would have to become a reserved word. You >>>> could say that this may break some code, but I don't see much >>>> freedom >>> >>> Isn't this a showstopper all by itself? >> >> Yes. But I've seen no code that uses some other word. > > There is a lot of code you have not seen. Really. In informal > code I use 's' and 'o' for 'self' and 'other'. I don't usually > post such because it is not considered polite. So you have seen a > biased sample of the universe. I didn't say that no code breaks, nor that I've analysed more than 0.1% of the global Python code. But still, this doesn't convice me. I still think that only a very small fraction of Python code would break. Since no one can make a global analysis, it is more sensible to compare it with the amount of code broken by Python 3.0 in my opinion. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From alexnbryan at gmail.com Sat Jul 5 04:15:32 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Sat, 5 Jul 2008 03:15:32 -0500 Subject: Tkinter Text widget get() Message-ID: <682C7C6A-9172-4673-955E-5B775115A689@gmail.com> Hey guys. I am having trouble understanding the get() method from the Tkinter Text() widget. It isn't like the entry.get() one I am used to. I know you have to put tags in, or at least I read. I tried this but it didn't work. I think I was putting the tags in wrong but I am not sure. I just need an example. So if someone could maybe modify this code to get EVERYTHING inside the text widget. text = Text(parent) text.pack() text.insert(END, "I am text!") Of course, I will have much more text, but I still want to get everything in the box. From fredrik at pythonware.com Tue Jul 22 12:28:28 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 18:28:28 +0200 Subject: Automatically loading and initialising objects from a plugins directory In-Reply-To: <488607BC.3040204@ecs.soton.ac.uk> References: <488607BC.3040204@ecs.soton.ac.uk> Message-ID: Dave Challis wrote: > Thanks for that, it helped as a starting point. I had some trouble with > using issubclass though (issubclass(Plugin, Plugin) returns true), which > was complicating things. > > I modified your code to the following instead (which may well have it's > own pitfalls I'm not aware of!): > > for name in dir(plugin): > thing = getattr(plugin, name) > if hasattr(thing, '__bases__') and \ > getattr(thing, '__bases__')[0] == Plugin: > thing() so now you're no longer supporting mixins and multiple-level inheritance? why not just tweak Diez' example a little: for name in dir(plugin): thing = getattr(plugin, name) # make sure this is a plugin try: if thing is Plugin: continue if not issubclass(thing, Plugin): continue except ValueError: # issubclass sucks continue # not a class thing() # probably needs error handling around this (I also moved the thing call out of the thing validation part, to allow you to distinguish between ValueErrors caused by issubclass and errors caused by things) (btw, another approach would be to use a metaclass to make Plugin classes register themselves on import) From larry.bates at websafe.com` Thu Jul 3 15:20:14 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 03 Jul 2008 14:20:14 -0500 Subject: Instance Names In-Reply-To: References: Message-ID: Tim Cook wrote: > Hi All, > > I have a need (if at all possible) to create instance names using '[' > and ']', i.e. [at0000]=ClassA0(), [at0001]=ClassB2(), etc. > > Of course Python tries to unpack a sequence when I do that. Is there > anyway to do this? > > I do have a workaround but it is an ugly, nasty URL mangling thing. :-) > > Cheers, > Tim > > > I suspect there is some "misunderstanding" here. Why exactly do you think you need to have your instances named with [] characters in them? You could put them in a dictionary: instances = {} instance['[at0000']] = ClassA0() but that isn't really different than: instance['at0000'] = ClassA0() -Larry From tamim.shahriar at gmail.com Sun Jul 6 06:32:48 2008 From: tamim.shahriar at gmail.com (subeen) Date: Sun, 6 Jul 2008 03:32:48 -0700 (PDT) Subject: Not necessarily related to python Web Crawlers References: Message-ID: <9fe3fff7-00c5-495f-a6d0-c64187af746b@d45g2000hsc.googlegroups.com> On Jul 5, 2:31?pm, disappeare... at gmail.com wrote: > Hi > Does anyone here have a good recommendation for an open source crawler > that I could get my hands on? It doesn't have to be python based. I am > interested in learning how crawling works. I think python based > crawlers will ensure a high degree of flexibility but at the same time > I am also torn between looking for open source crawlers in python vs C > ++ because the latter is much more efficient(or so I heard. I will be > crawling on very cheap hardware.) > > I am definitely open to suggestions. > > Thx You can check my python blog. There are some tips and codes on crawlers. http://love-python.blogspot.com/ regards, Subeen http://love-python.blogspot.com/ From steve at REMOVE-THIS-cybersource.com.au Tue Jul 29 19:30:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 23:30:12 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: <009fa37d$0$20313$c3e8da3@news.astraweb.com> On Tue, 29 Jul 2008 10:30:43 -0700, Carl Banks wrote: > On Jul 29, 5:15 am, Heiko Wundram wrote: >> I can't dig up a simple example from code I wrote quickly, but because >> of the fact that explicit comparisons always hamper polymorphism > > I'm not going to take your word for it. Do you have code that > demonstrates how "if x" improves polymorphism relative to simple > explicit tests? On the rapidly decreasing chance that you're not trolling (looking more and more unlikely every time you post): # The recommended way: if x: do_something # Carl's so-called "simple explicit tests" applied to polymorphic code: try: # could be a sequence or mapping? # WARNING: must do this test *before* the number test, otherwise # "if [] != 0" will return True, leading to the wrong branch being # taken. if len(x) != 0: do_something except AttributeError: # not a sequence or mapping, maybe it's a number of some sort try: int(x) except TypeError: # not convertable to numbers # FIXME: not really sure what to do here for arbitrary types # so fall back on converting to a boolean, and hope that works if bool(x): do_something else: if x != 0: do_something But wait... that can be re-written as follows: if bool(x): do_something and that can be re-written without the call to bool: if x: do_something -- Steven From __peter__ at web.de Mon Jul 14 11:44:20 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 14 Jul 2008 17:44:20 +0200 Subject: subprocess module References: <2e7f0504-cc1c-4cb6-b2d0-b67b004eca7d@x41g2000hsb.googlegroups.com> <39622612-5e43-45b4-800a-69277c2e2987@79g2000hsk.googlegroups.com> Message-ID: John Mechaniks wrote: > On Jul 14, 12:34?pm, Peter Otten <__pete... at web.de> wrote: >> John Mechaniks wrote: >> > from subprocess import call >> > call(['ls', '-l']) >> >> > How do I get the result (not the exit status of the command) of "ls - >> > l" into a variable? >> >> output = subprocess.Popen(["ls", "-l"], >> stdout=subprocess.PIPE).stdout.read() > What difference does the following code makes? What are the advantages > of the above method over this one? > output = subprocess.Popen(['ls', '-l'], > stdout=subprocess.PIPE).communicate()[0] Hm, I chose it because it looks cleaner. Looking into the source Popen.communicate() seems to do the following: output = p._fo_read_no_intr(p.stdout) p.wait() So there are two differences in this case - communicate() waits for the subprocess to terminate. - stdout.read() is retried if an EINTR occurs (Not sure when this would happen). > Also could someone show an example of using the optional input > argument for communicate() http://blog.doughellmann.com/2007/07/pymotw-subprocess.html I didn't read it myself, but Doug Hellmann's articles are usually quite good. Peter From larry.bates at websafe.com` Tue Jul 15 19:39:53 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 18:39:53 -0500 Subject: Python internals In-Reply-To: <87hcaq7pja.fsf@benfinney.id.au> References: <008ca729$0$20313$c3e8da3@news.astraweb.com> <87hcaq7pja.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Larry Bates writes: > >> Names are pointers in Python that point to values in memory. > > The term "pointer" carries much extra baggage for a programmer > thinking of C (as the original poster is). Python names give no access > to the "address" of the value, and don't need to be "de-referenced". > > I've had better success explaining Python names to such people in > terms of "references": there is no "address" and no "de-reference" > needed. Access the name, and you get its value. > > On the other hand, I prefer to avoid using either of those concepts, > and talk in terms of "name tags" or "sticky notes". Names (and other > references, like list elements) attach to the object, and have no > other value or purpose. They don't affect the object they're attached > to; they are entirely independent of other bindings to the same > object; they re-bind to another object with no history of what they > were bound to previously. > > The analogy is quite robust, and carries none of the confusing baggage > of "variable" or "pointer" or other overloaded language terms. > You are, of course, correct. Since I'm not a C programmer, the term pointer doesn't carry the same "baggage" as it might to others. The "problem" I had when I first started is that people were using such "vague" terms like names, tags, etc. that it had no meaning to me. I like your idea of "references". -Larry From M8R-yfto6h at mailinator.com Sun Jul 20 12:50:30 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Sun, 20 Jul 2008 09:50:30 -0700 Subject: getting with statement to deal with various exceptions References: Message-ID: "mk" wrote in message news:mailman.349.1216557748.922.python-list at python.org... > Hello, > > I'm trying to learn how with statement can be used to avoid writing: > > prepare() > try: > something_that_can_raise_SomeException() > except SomeException, err: > deal_with_SomeException > finally: > tear_it_down() > > Verbose, not very readable. OK, "with" to the rescue? > > Let's take a textbook example from PEP: > > with open('/etc/passwd', 'r') as f: > BLOCK > > Well, great, it's neat that "with" closes the file after BLOCK has > finished execution, but what if the file isn't there and attempt to open > it raises IOException? I'd like to be able to catch it precisely to avoid > writing verbose try: .. except: .. finally: .. blocks which as I > understand has been much of the rationale behind creating "with" statement > in the first place. > > "with" statement only allows easy dealing with prepare() and > tear_it_down(). When I try to get it to deal with exceptions that might > happen, it becomes more complicated: > > class FileContextManager: > def __enter__(self, filename, mode): > f = open(filename, mode) > return f > def __exit__(self, etype, evalue, etraceback): > print "etype", etype, "evalue", evalue, "etraceback", etraceback > > > >>> with FileContextManager("somefile", "r") as f: > a = f.readlines() > > > > Traceback (most recent call last): > File "", line 1, in > with FileContextManager("somefile", "r") as f: > TypeError: this constructor takes no arguments > > > Bummer. > > Plus, no documentation I've read (on effbot, in PEP 343, etc) says how to > deal with the exception happening in __enter__ method of context manager, > which is precisely what I'd like to do. > > This is only natural, isn't it? When e.g. reading the file, preparation > phase is typically checking if it can be opened in the first place. So it > falls into __enter__ method of context manager. > > "with" limited only to successful execution of a_statement from "with > a_statement" seems like limited benefit to me. > > I'd like to be able to write smth like > > class FileContextManager: > def __enter__(self, filename, mode): > f = open(filename, mode) > return f > def __except__(IOError, err): > do_this > print err > def __except__(RuntimeError, err): > do_that > print "something bad happened", err > def __exit__(self, etype, evalue, etraceback): > print "etype", etype, "evalue", evalue, "etraceback", etraceback > > __exit__ deals with exceptions happening in the BLOCK below "with" > statement, not with exceptions raised in "a_statement", when executing > > with a_statement as var: > BLOCK > > In the above way "with" would give me the benefit of more terse, but still > understandable and efficient code. > > Well, I can always do this: > > try: > with open("somefile.txt") as txtfile: > for line in txtfile: > print line > except IOError: > print "No such file." > > > No such file. > > > But that's just ugly, nested too many times (flat is better than nested, > right?) and not all that more readable. I just started looking at the with statement myself. How about: from __future__ import with_statement class ExceptionManager(object): def __enter__(self): pass def __exit__(self,exc_type,exc_value,tb): if exc_type == IOError: print 'IOError',exc_value[1] return True # suppress it with ExceptionManager(): with open('test.txt') as f: f.read() -- Mark From babacity4 at gmail.com Thu Jul 24 16:55:38 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:55:38 -0700 (PDT) Subject: Peachy18 com - Amazing porn video collection Message-ID: peachy18 com . >>>>>>>>>>Best Collection of Peachy18 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE peachy18 VIDEOS<<<<<<<<<<< . peachy18 com From news at prodata.co.uk Tue Jul 1 07:23:22 2008 From: news at prodata.co.uk (John Dann) Date: Tue, 01 Jul 2008 12:23:22 +0100 Subject: Scope and program structure problems Message-ID: Trying to learn Python here, but getting tangled up with variable scope across functions, modules etc and associated problems. Can anyone advise please? Learning project is a GUI-based (wxPython) Python program that needs to access external data across a serial port. The first thing that I need the program to do when it starts up is to check that it can see the serial port, the first step of which is to check that it can import the pySerial module, and display an appropriate message in the statusbar of the main frame. (I know there may be other ways of doing this but this is what I'm trying to do currently and I'd like to understand how to make this approach work robustly even if there are other options.) So it seems that if I want to write to the frame's statusbar, I can't do anything re serial import until the frame is initialising. And I can't put any serial import code after the app.Mainloop() code line because it won't run until the frame closes. In other words, I seem to be stuck with importing the serial library either in the __init__ function or - if implemented slightly differently - in a separate function of the wxPython Frame class, ie a code structure of: ----------- # Can't put serial import code here because there's no GUI yet to send messages to. Class Frame(wx.Frame) def __init__() etc #code to check and use serial port has to go below?? def CheckSerial() # eg triggered by appropriate menu click event Try: import serial etc ser = Serial.etc # set ser object as handle to serial port def UseSerial(): # Code to perform serial IO app=App(wx.App) app.MainLoop() # Can't put serial import code here because it won't execute until frame closes? ----------- But then I hit another problem. If I set the object ser to point to the serial port in the CheckSerial function, then it's just got local scope within the function and can't be seen from the UseSerial function. So I've got 2 questions. The main one is whether there's any way of explicitly giving the ser object global scope in the code line: ser = Serial.etc # set ser object as handle to serial port And, second, does my overall description above reveal any serious misunderstanding about how best to handle this sort of problem in Python? Apologies for the long post and hope that my description is clear enough to make sense. JGD From grante at visi.com Tue Jul 1 18:44:19 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 01 Jul 2008 17:44:19 -0500 Subject: Implementing an 8 bit fixed point register References: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> Message-ID: On 2008-07-01, Terry Reedy wrote: >>> A bytearray subclass could enforce that all 'bits' (stored as >>> bytes) are 0 or 1, have a customized representation to your >>> taste, and add methods like .flipall(). >> >> It seems like implementing ALU operations on such arrays would >> be a lot more work than implementing bit-indexing on a type >> derived on a more "integer" like base. I'm pretty fuzzy on how >> one sub-classes basic things like integers, so maybe I'm all >> wet, and adding __getitem__ and __setitem__ to an integer type >> isn't even possible. > > If one only wants bit operations, then the array approach is > easy. If one only wants int arithmetic and all-bits logic, > then int approach is easy. OP did not completely specify > needs. He said he's writing a microprocessor simulator, so he's going to want integer operations, all-bits logical operations, and individual bit acess (by number and by name) and bit-slice access. > The problem with the int approach is that ints are immutable. That dawned on me after I started googling around a little. > Therefore, if one wants to subclass int to hide the bit > masking for the bit operations, one must override *every* > operation one might use, including all arithmetic and all-bits > logic, even when the int operation gives the correct answer > other than the class of the result. Since we're doing fixed-width operations, Python's int operations don't give the correct answer other than the class of the result. > class bits(int): > ... > def __add__(self,other): > return bit(self+other) > ... > > If one does not, > > a,b = bits(1),bits(2) > c = a+b #c is now an int, not a bits > > So there is a tendency to not subclass and instead either leave the > extra functionality unmasked in repeated code or to put it in functions > instead. > > setters = (1,2,4,8,16,32,64, ..., 2147483648)# slightly pseudocode > unsetters = (~1,~2,~4,...~2147483648) # ditto > def bitset(n, bit): return n | setters[bit] > def bitunset(n,bit): return n & unsetters[bit] On a machine with a barrel shifter, it's probably faster to do this: def bitset(n,bit): return n | (1< thus not getting the nice reg[n] functionality, nor an easy > display of individual bits without callings *another* > function. > > One the other hand, with mutable arrays, setting bits is a > mutation and so no override of __setitem__ is required unless > one wants to be fancy and enforce setting to 0 or 1. More importantly, I presume that slices are supported so when you need values of bit-fields, you can do this: op = instruction[6:8] src = instruction[3:6] dest = instruction[0:3] The half-closed interval notation for slices is probably going to drive the programmer up the wall because all of the documentation that's being followed uses closed intervals. > It is a trade-off. And Python programmers are awfully spoiled. :) -- Grant Edwards grante Yow! I think my career at is ruined! visi.com From rocksportrocker at googlemail.com Sun Jul 13 12:32:47 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Sun, 13 Jul 2008 09:32:47 -0700 (PDT) Subject: wxPython Tab References: Message-ID: <75018ae6-6d8c-4962-9fd0-aedb52ad626f@k30g2000hse.googlegroups.com> On Jul 13, 6:20?pm, Sparky wrote: > Is there a way to get wxPython to change the visible tab in a notebook > (like I have tab 1 open but the computer will automatically change to > tab 2)? > > Thanks, > Sam look at http://docs.wxwidgets.org/stable/wx_wxnotebook.html#wxnotebooksetpagetext greetings, uwe From steve at REMOVE-THIS-cybersource.com.au Sun Jul 13 02:49:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 13 Jul 2008 01:49:31 -0500 Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: On Sat, 12 Jul 2008 16:32:25 -0400, Terry Reedy wrote: > Steven D'Aprano wrote: >> On Thu, 10 Jul 2008 14:09:16 -0400, Terry Reedy wrote: >> >>>>>>>> g = lambda x:validate(x) >>> This is doubly diseased. >>> >>> First, never write a 'name = lambda...' statement since it is >>> equivalent to a def statement except that the resulting function >>> object lacks a proper .funcname attribute. >> >> Using lambda in this way is no more "diseased" than aliasing any other >> object. > > In the context of giving advice to a confused beginner, I disagree. He > must learn def statements. Lambda expressions are optional. Lots of things are optional. sets and frozen sets and decorators and classes and all sorts of things are optional, *and* capable of being misused and/or abused. Would you describe properties as "diseased" because some people might fill their classes with useless getters and setters? > > It's a matter of personal preference not to bind a lambda to a >> name. Functions, whether created by lambda or def, are first class >> objects, and as such there's nothing wrong with binding them to names. > > When I brought this up on pydev, in the context of a style guide > addition, about 9 of 10 respondants agreed that this should be > discouraged. Alex Martelli reported his experience that this > construction more often leads people to the useless wrapping of function > calls, such as the OP posted, than the def statement equivalent does. I have great respect for Alex, but anecdotes of that nature aren't proof. Such anecdotal evidence is subject to confirmation bias. I'm sure that Alex remembers the stupid pieces of code where people make such mistakes but I doubt very much he remembers the cases where they don't. But as a style guide... fine. Tell people it is discouraged. Tell them that other Python developers will laugh at them if they do it, apart from the ten percent who don't mind named lambdas. Point out that, like factory functions, there's a debugging cost to having functions with a unhelpful func_name attribute. But don't cross that line from discouragement to telling people that it is wrong to use named lambdas. That's what I object to. > One of the major reasons people give for wanting lambda expressions kept > in Python and for using them is that they do not want to have to think > up a name for short expressions. If such a person then turns around and > binds the resulting function object to a name, then that rationale > disappears. That does not follow. The fact that I might choose to occasionally bind a lambda to a name doesn't mean I never use unbound functions. Your argument is like saying that the rationale for air conditioners ("cooling in the hot weather") disappears because we can also use reverse-cycle air conditioners for heating in the cold weather. Lambdas are *necessary* if you want anonymous functions, just as we have anonymous strings, anonymous integers and so forth. It would be a poor language that forced people to write this: x = 1 s = 'two' def f(arg): return arg+3 mylist = [x, s, f] instead of the more sensible: mylist = [1, 'two', lambda arg: arg+3] That's why we need lambda. But once we have lambda, there is absolutely no reason why we must prohibit other uses of it. Given the above definition of mylist, would you then describe the following piece of code as "diseased"? def foo(mylist): g = mylist[2] for i in xrange(10000): print g(i) That's a perfectly good micro-optimization technique, and I would hope you would not reject it merely because the function was anonymous. That would be irrational. I'm not defending the Original Poster's use of lambda in that specific piece of code. You are right to criticize it *specifically*. What I object to is that you generalize that criticism, and treat a personal preference as an absolute rule. By all means think my code is ugly for using named lambdas, and by all means tell me you think it is ugly, but don't tell me I'm corrupting the youth of today with my filthy disease- ridden code. -- Steven From cjw at ncf.ca Mon Jul 28 07:21:05 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 28 Jul 2008 07:21:05 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <488D5B2C.10808@gmail.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <488D5B2C.10808@gmail.com> Message-ID: <488DABA1.6030207@ncf.ca> An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sun Jul 13 19:17:52 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 13 Jul 2008 16:17:52 -0700 (PDT) Subject: Mutually referencing imports -- impossible? References: <2e6bcb14-1db7-413b-afa7-62a11c9e33e4@26g2000hsk.googlegroups.com> Message-ID: On Jul 14, 5:30 am, John Roth wrote: > On Jul 13, 11:55 am, Matthew Wilson wrote: > > > > > I started off with a module that defined a class Vehicle, and then > > subclasses Car and Motorcycle. > > > In the Car class, for some bizarre reason, I instantiated a Motorcycle. > > Please pretend that this can't be avoided for now. > > > Meanwhile, my Motorcycle class instantiated a Car as well. > > > Then I moved the Car and Motorcycle classes into separate files. Each > > imported the Vehicle module. > > > Then I discovered that my Car module failed because the global > > Motorcycle wasn't defined. The same problem happened in my Motorcycle > > module. Car and Motorcycle can't both import each other. > > > In the beginning, when all three (Vehicle, Car, and Motorcycle) were > > defined in the same file, everything worked fine. > > > I don't know how to split them out in separate files now though and I > > really wish I could because the single file is enormous. > > > Any ideas? > > > Matt > > While it's possible for circular imports to work, it's very dangerous: > it's not always possible to tell what went wrong without tracking down > the process of the import step by step. There are more productive ways > of banging your head against the wall and going insane. > > In your situation, it might be a whole lot easier to extract a common > superclass that both of your classes could inherit from. > Like the Vehicle class the OP mentioned? From fredrik at pythonware.com Fri Jul 25 07:54:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 13:54:34 +0200 Subject: object persistency, store instances relationship externally In-Reply-To: <3183af12-4b1e-4bd1-8d21-b9fc2b421008@v1g2000pra.googlegroups.com> References: <3183af12-4b1e-4bd1-8d21-b9fc2b421008@v1g2000pra.googlegroups.com> Message-ID: King wrote: > This is a new test for object persistency. I am trying to store the > relationship between instances externally. > It's not working as expected. May be I am doing it in wrong way. Any > suggestions? The shelve module pickles each stored item individually. To preserve inter-object relations, try putting all related things in a tuple, and store that instead. E.g. shelf['data'] = (a, lst) a, lst = shelf['data'] From trentm at activestate.com Mon Jul 14 13:52:51 2008 From: trentm at activestate.com (Trent Mick) Date: Mon, 14 Jul 2008 10:52:51 -0700 Subject: Building a Python app with Mozilla In-Reply-To: References: <46867432.7060400@codebykevin.com> <4686CC45.9010405@sweetapp.com> Message-ID: <487B9273.9010200@activestate.com> > Brian Quinlan wrote: >> Most application logic in Komodo is implemented in Python, using the >> PyXPCOM bindings. The UI is implemented using XUL and JavaScript. The >> editor is Scintilla (C++). >> >> ../Komodo Edit.app/Contents/MacOS % find . -name "*.py" | xargs wc >> ... >> ... >> 126392 456858 4949602 total >> >> This doesn't include the python code in the Python libraries themselves. An interesting breakdown here: http://www.ohloh.net/projects/10861/analyses/latest happybrowndog wrote: > Is that why Komodo is so damned slow???? Probably not, no. Pinpointing the reasons for slowness is often a lot more complicated. Particular slow points in any app/module -- especially pathologically slow things -- are more often algoritmic than a function of the language used. Komodo's use of Python is perhaps partially responsible for a slower startup time than might otherwise be possible -- but otherwise my experience in Komodo perf work has been algorithmic issues. Also, if Komodo hadn't been using Python for application logic since day one we probably wouldn't be much further than Notepad right now. :) Cheers, Trent (komodo developer) -- Trent Mick trentm at activestate.com From 2007 at jmunch.dk Thu Jul 24 08:24:38 2008 From: 2007 at jmunch.dk (Anders J. Munch) Date: Thu, 24 Jul 2008 14:24:38 +0200 Subject: Recursion Performance Question In-Reply-To: References: Message-ID: <48886e03$0$5958$ba624c82@nntp06.dk.telia.net> B wrote: > > # pass in window handle and parent node > def gwl(node, hwnd): > if hwnd: > yield node, hwnd > for nd, wnd in Wnd.gwl(node.children[-1], GetWindow(hwnd, > GW_CHILD)): > yield nd, wnd > for nd, wnd in Wnd.gwl(node, GetWindow(hwnd, GW_HWNDNEXT)): > yield nd, wnd [...] > > Now it works, but it runs quite slow (compared to the c++ app). I > changed gwl from strait recursion to use a generator and that helped, > but it still takes 0.5-1.0 seconds to populate the tree. Actually the generator could well be the problem here, because of time spent on yield propagation: gwl has worst-case quadratic performance, the worst case being if the tree is unbalanced and deep, because every yielded value must pass through a chain of propagation for-loops. Straight recursion should be faster; I don't know what you did to make it slow, but try something along these lines: def gwl_helper(node, hwnd, collect): if hwnd: collect((node,hwnd)) gwl_helper(node.children[-1], GetWindow(hwnd, GW_CHILD), collect) gwl_helper(node, GetWindow(hwnd, GW_HWNDNEXT), collect) def gwl(node, hwnd): result = [] gwl_helper(node, hwnd, result.append) return result - Anders From cokofreedom at gmail.com Wed Jul 9 10:56:04 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 9 Jul 2008 07:56:04 -0700 (PDT) Subject: You, spare time and SyntaxError Message-ID: def ine(you): yourself = "what?" go = list("something"), list("anything") be = "something" please = be, yourself yourself = "great" for good in yourself: if you is good: good in you please.add(more, good) else: def inition(lacks, clarity): if clarity not in you: please.remove(everything and go) for bad in yourself: list(bad) if bad else (ignore, yourself) try: (to, escape, your, fate, but) except (Exception), son: if bad in (you, son): (you is bad, son), so finally: if bad in you: lie, cheat, steal, be, bad else: print you, "is", yourself you is good and yourself is not bad please, go ine("Everyone") From conman5525 at gmail.com Fri Jul 18 18:47:00 2008 From: conman5525 at gmail.com (conman5525 at gmail.com) Date: Fri, 18 Jul 2008 15:47:00 -0700 (PDT) Subject: Any Game Developers here? References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: On Jul 18, 2:38?pm, Michael Lubker wrote: > Any people that use Python as the predominant language for their game > development here? > > ~Michael The Panda3d engine supports the development of 3d simulations in python. Disney uses the engine in two of their MMO games (toontown and pirates of the carribean). CMU uses it in their virtual reality lab course. The source and pre built binaries are available at www.panda3d.org From asd at pittle.org Sun Jul 6 07:09:22 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Sun, 6 Jul 2008 04:09:22 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> <9cdbb215-d427-4694-a455-f2571ad42390@x19g2000prg.googlegroups.com> <54e0e7c5-113e-4296-a62f-e649d6ffa2d6@z66g2000hsc.googlegroups.com> <87b10cf3-4fd4-46e3-a33a-528f1180f69a@s21g2000prm.googlegroups.com> Message-ID: <6df87bb6-12c1-4a2d-9d3d-3eec0f94069f@e53g2000hsa.googlegroups.com> On Jul 4, 7:10?am, Yu-Xi Lim wrote: > Ali Servet D?nmez wrote: > > > I tried code come completion options in Emacs for Python, but none of > > them was satisfactory to me. I'd be glad to hear how did your friend > > get it work though. > > Perhaps it would help to say what ways the completion in Emacs was not > satisfactory? I simply couldn't manage to get it work. > FWIW, it should be possible to get IPython-type completion in Emacs, but > I hadn't managed that yet :( Refactoring, too. Both involve Pymacs but > I've had limited success with that. Yeah, that's what I'm talking about. > As for PyDev (I know you said "No" to this already), the main problem I > have with PyDev/Eclipse is the woefully underpowered editor (compared to > Emacs), and poor indentation logic. On the plus side, refactoring works > pretty well. So why not PyDev? I tried PyDev with Eclipse too and it's an aweful environment to me. Auto-completion was a total failure too... > I'm just wondering, you insist on Free/Libre software solutions, and say > the ones you tried don't work for you. Why not "use the source" and fix > them so they work your way? ;) To quote you: "how hard it could be be > writing a freesoftware which would automatically/intelligently auto > complete Python code?" Yes Yu-Xi Lim, you are right. Let me quote my self here: "I made my mind and I could volunteer to make this happen as thesis project for my incoming graduation in the next year." From bruno.desthuilliers at gmail.com Mon Jul 14 12:36:41 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 14 Jul 2008 09:36:41 -0700 (PDT) Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> Message-ID: On 13 juil, 12:05, Yosifov Pavel wrote: (snip) > def cloneiter( it ): > """return (clonable,clone)""" > return tee(it) This might as well be written as cloneiter = tee Or yet better, just remove the above code and s/cloneiter/tee/g in the remaining... From kay.schluehr at gmx.net Tue Jul 15 05:57:32 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 15 Jul 2008 02:57:32 -0700 (PDT) Subject: Python embedding question. References: Message-ID: <45f657a0-315f-421e-8d69-1c5b24e23887@k37g2000hsf.googlegroups.com> On 15 Jul., 11:51, Thomas Troeger wrote: > I've really looked at a lot of places but haven't found a suitable > solutions yet, so I'm asking here in hope that someone has experience > with that topic. Which solutions did you rule out? From digetl.try at gmail.com Sat Jul 26 06:03:45 2008 From: digetl.try at gmail.com (raja) Date: Sat, 26 Jul 2008 03:03:45 -0700 (PDT) Subject: Parmigiano Reggiano DOP Message-ID: <727be5c4-3c59-4c8a-96fb-3ddb5701b043@b30g2000prf.googlegroups.com> Eccelsa Qualit? di Montagna per Rivenditori, Ristoranti e Privati. http://food-drinks.page.tl/ From timr at probo.com Thu Jul 10 03:34:06 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 10 Jul 2008 07:34:06 GMT Subject: a simple 'for' question References: <4874017D.2000401@umbc.edu> <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> <487437E6.8010609@umbc.edu> <1215599630.2873.965.camel@localhost.localdomain> <48749F60.7030106@umbc.edu> Message-ID: Ethan Furman wrote: >Ben Keshet wrote: >> it didn't help. it reads the pathway "as is" (see errors for both >> tries). It looks like it had the write pathway the first time, but >> could not find it because it searched in the path/way instead of in the >> path\way. thanks for trying. > >The form of slash ('\' vs '/') is irrelevant to Python. At least on >Windows. > >> folders= ['1','2','3'] >> for x in folders: >> print x # print the current folder >> filename='Folder/%s/myfile.txt' %[x] > ^- brackets not needed More than that, the brackets are CAUSING this problem. The "%" formatting operator expects to find either a single item, or a tuple containing multiple items. It does NOT look for a generic iterator. In this case, the %s will use the whole list as its parameter. Python converts the list to string, and the string representation of that one-item list is ['1']. >> f=open(filename,'r') >> >> gives: IOError: [Errno 2] No such file or directory: >> "Folder/['1']/myfile.txt" Just like that. >As far as the Python question of string substitution, "%s" % var is an >appropriate way. Right. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From paddy3118 at googlemail.com Tue Jul 29 17:33:25 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 29 Jul 2008 14:33:25 -0700 (PDT) Subject: Parsing VHDL with python, where to start. References: Message-ID: <09ec2cd2-37e6-4abe-bed9-fc593c4751ce@8g2000hse.googlegroups.com> On Jul 21, 12:09?pm, Svenn Are Bjerkem wrote: > Hi, > I am in the need to write an application for PyQt to visualise the > structure of a VHDL project I am working on. Looking for a sensible > way to parse VHDL files and putting them into a data structure that > PyQt can represent as a tree (or whatever the MVC is supporting) > through search engines does not give me many hints. From what I know, > VHDL is not a very easy language to parse. There seems to be a parser > for perl available, but I do not know if it is wise to use a perl > module as a template for writing something similar in python. > > My initial idea is to start simple and extend features in my > application, but I fear that I may start off with wrong ideas how to > parse and then code myself into a dead-end requiring myself to rewrite > the whole application in order to get any further. I would start > finding definitions of entities and the instantiations of these and > build a tree from a set of external vhdl files stored in a file > hierarchy. If somebody have a starting point where to get going with a > task like this, I would be happy to know. > > -- > kind regards, > Svenn Been their, partially done that. I started parsing an old version of VHDL (VHDL 87 I think); using regular expressions and carrying state around myself. It was tough, and I was doing it , but then Work mentioned that they were going to need to parse later versions of VHDL and that was a whole new ball- game, specifically configuration type information could be mixed in with the architecture. Luckily work had also decided to by in a commercial parser. I learned that add-hoc parsers have limits to their maintainability and become complex. You might not have such problems if your VHDL is all in one library. - Paddy. From pranny at gmail.com Fri Jul 11 03:13:31 2008 From: pranny at gmail.com (pranav) Date: Fri, 11 Jul 2008 00:13:31 -0700 (PDT) Subject: Bypassing WebFilter security References: <563968a1-3cc3-4009-beca-d5d367d4ccff@k13g2000hse.googlegroups.com> <4876F153.2020406@behnel.de> Message-ID: <25ff817d-2d0f-4806-b635-96e220d920f5@m44g2000hsc.googlegroups.com> On Jul 11, 11:42?am, "Daniel Fetchinson" wrote: > >> I am working in an organization, which is using a very strict > >> webcontent filter management suite. Due to this i am unable to > >> download any exe file, or surf web (even the necessary downloads from > >> sourceforgenet are blocked). I was wondering, if python could be of > >> any help. Say i have a python script, and i pass the URL of > >> downloadable file, and it just downloads the file for me. > > > Nice try. Can I talk to your employer for a minute? :) > > > Honestly, the language doesn't make any difference here, and there isn't > > much > > you can do unless you control both sides, i.e. the server and the client. > > But > > I would suggest you actually talk to your employer yourself to see if > > there's > > an official way to get what you want. > > Yes, the language itself doesn't matter as long as you go through the > web. But if I were you I would use an ssh client to ssh to a remote > machine on which I have an account, download the file there to that > machine and scp it to the local machine. Assuming of course port 21 is > not blocked. > > In fact, this is something I do regularly for similar reasons :) > > Good luck, > Daniel > -- > Psss, psss, put it down! -http://www.cafepress.com/putitdown Daniel, cool even i thought of the same thing, but you see, the assumption has no use in my case! It is also blocked, Anyways, i will talk to the system admins here. Thanks all From bignose+hates-spam at benfinney.id.au Fri Jul 11 19:43:03 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 12 Jul 2008 09:43:03 +1000 Subject: How to serialize and deserialize the objects into memory? References: <0a7ead85-2a38-41a8-98b8-59dede61f985@c58g2000hsc.googlegroups.com> Message-ID: <87wsjsoum0.fsf@benfinney.id.au> Gerhard H?ring writes: > You want to serialize the objects, but only keep them in memory? > That hardly makes any sense. Serialization is need if you want to > store your objects in a file or if you want to communicate (via > network) with other processes. If one needs to do further processing on the serialised stream before storing or transporting it, one needs to handle it in memory. Fortunately (as pointed out elsewhere in this thread) the pickle module provides for this. -- \ ?I love and treasure individuals as I meet them, I loathe and | `\ despise the groups they identify with and belong to.? ?George | _o__) Carlin, 2007 | Ben Finney From elessar at nienna.org Thu Jul 31 15:07:59 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Thu, 31 Jul 2008 13:07:59 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <4891FD6F.8090604@nienna.org> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <00a121b4$0$20313$c3e8da3@news.astraweb.com> <4891FD6F.8090604@nienna.org> Message-ID: <48920D8F.3030602@nienna.org> Matthew Fitzgibbons wrote: > Steven D'Aprano wrote: >> On Wed, 30 Jul 2008 09:23:05 -0600, Matthew Fitzgibbons wrote: >> >>> If you're expecting a list (and only a list) >>> then your point makes sense. 'if x' can get you into trouble if you >>> _don't_ want its polymorphism. >> >> "if x" is hardly unique in that way. If you're expecting a list, and >> only a list, "len(x) != 0" will get you in trouble if somebody passes >> a string or a dictionary. I don't see any reason why we should single >> out "if x" as dangerous in the face of invalid types. With the >> exception of the "is" and "is not" operators, nothing in Python is >> guaranteed to work with any imaginable object. Even print can fail, if >> the object's __str__ method raises an exception. >> >> >>> Although, if my function is expecting a list, my preference is to do: >>> >>> if not isinstance(x, list): >>> raise SomeMeaningfulException() >>> # do stuff with the list >>> >>> I put my type checking at the top of the function, so readers can >>> reference it easily. >> >> And thus you break duck-typing and upset anybody who wants to pass a >> sequence that doesn't inherit directly from list. >> >> There are other (and arguably better, although more labour-intensive) >> techniques for defensive programming that don't break duck-typing. You >> can google for Look Before You Leap and Easier To Ask Forgiveness Than >> Permission for more information. Alex Martelli has a fine recipe in >> the Python Cookbook -- search for the recipe "Checking if an object >> has the necessary attributes". >> >> But in a nutshell, here's a toy example: >> >> def spam(seq): >> try: >> seq.append >> seq.extend >> seq[0] = seq[0] >> except Exception: >> raise TypeError("argument isn't sufficiently sequence-like") >> # No exceptions expected from here on >> seq.append(seq[0]) >> seq.extend([1,2,3]) >> seq[0] = "spam" >> >> >> >> > > Yes, I know it breaks duck typing, which is why I do it only very > rarely, and never with e.g. sequence types. If I use ifinstance for type > checking, it's because I need some _very_ specific class, almost always > one that I wrote. My more usual use case for ifinstance is to figure out > how to handle a particular object using introspection. > > That said, your example is still helpful. It's a good approach, and I > should use it more often. Although I'd also lean toward hasattr and > iscallable and ordinary ifs instead of the try ... except where > possible. Depending on what you put in the try ... except, you risk > masking legit exceptions. > > Ahhh, Programing. Where no rule of thumb seems to last five minutes. > > -Matt > -- > http://mail.python.org/mailman/listinfo/python-list > Where by ifinstance I mean isinstance and by iscallable I mean callable. *hides* -Matt From fuzzyman at gmail.com Thu Jul 3 13:42:53 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 3 Jul 2008 10:42:53 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> <9cdbb215-d427-4694-a455-f2571ad42390@x19g2000prg.googlegroups.com> Message-ID: <54e0e7c5-113e-4296-a62f-e649d6ffa2d6@z66g2000hsc.googlegroups.com> On Jun 30, 11:25?pm, Ali Servet D?nmez wrote: > On Jul 1, 12:15?am, Fuzzyman wrote: > > > > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > I don't want to be so mean here, but how hard it could be be writing a > > > freesoftware which would automatically/intelligently auto complete > > > Python code? (I mean something that really does the job, like > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > name it, but just don't give me PyDev please...) > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > missing here? > > > > Could someone please point me out something that I'm really missing > > > which is already present in the wild, otherwise I'd like discuss with > > > whoever is willing to help me to get this thing done. I made my mind > > > and I could volunteer to make this happen as thesis project for my > > > incoming graduation in the next year. > > > > Regards you all, > > > Ali Servet D?nmez > > > Vim, Emacs, Wing, Komodo, ... more? > > > Yeah, I guess you're missing something. :-) > > > MichaelFoordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > I probabily am... Could you please kindly tell me what's the way to > get it work for Emacs? Not personally I'm afraid. Although I did use Emacs today for the first time (pairing with a colleague who inflicted it upon me). We did have code completion working fine, but I have no idea how to set it up (maybe the intarwebz can help?). Michael Foord -- http://www.ironpythoninaction.com/ http://www.trypython.org/ From rocksportrocker at googlemail.com Thu Jul 17 13:39:23 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 17 Jul 2008 10:39:23 -0700 (PDT) Subject: How to process a very large (4Gb) tarfile from python? References: <0e96241d-60a3-44fd-967a-394904ad5b34@e39g2000hsf.googlegroups.com> <4nqu74p3mmmdmf9pn7125voe6itko8d31k@4ax.com> Message-ID: On 17 Jul., 17:55, Terry Carroll wrote: > On Thu, 17 Jul 2008 06:14:45 -0700 (PDT), Uwe Schmitt > > wrote: > >I had a look at tarfile.py in my current Python 2.5 installations > >lib path. The iterator caches TarInfo objects in a list > >tf.members . If you only want to iterate and you ?are not interested > >in more functionallity, you could use "tf.members=[]" inside > >your loop. This is a dirty hack ! > > Thanks, Uwe. ?That works fine for me. ?It now reads through all 2.5 > million members, in about 30 minutes, never going above a 4M working > set. Maybe we should post this issue to python-dev mailing list. Parsing large tar-files is not uncommon. Greetings, Uwe From bignose+hates-spam at benfinney.id.au Wed Jul 16 00:55:54 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jul 2008 14:55:54 +1000 Subject: Modify a string's value References: <8c7245ed-2341-4283-988c-8a8adf3e58fd@56g2000hsm.googlegroups.com> Message-ID: <87k5fm4ecl.fsf@benfinney.id.au> s0suk3 at gmail.com writes: > I just came across this unusual situation where I'd like to modify a > string passed to a function Again: Why? The normal way to do this is to create a new string and return that. > which seems impossible since Python passes arguments by value. No, Python passes arguments by reference . -- \ ?For of those to whom much is given, much is required.? ?John | `\ F. Kennedy | _o__) | Ben Finney From cwitts at gmail.com Wed Jul 16 07:38:52 2008 From: cwitts at gmail.com (Chris) Date: Wed, 16 Jul 2008 04:38:52 -0700 (PDT) Subject: How can i use a variable without define it ? References: <87k5fm2p1x.fsf@benfinney.id.au> <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> Message-ID: <616b3539-c3e1-41ae-82d4-c9698ff0056e@k30g2000hse.googlegroups.com> On Jul 16, 11:06 am, zhw wrote: > On 7?16?, ??4?47?, Ben Finney > wrote: > > > > > zhw writes: > > > How can i use a variable without define it ? > > > What do you mean by "use"? That's so vague I can think of many > > possible interpretations. > > > What do you mean by "variable"? That term carries a lot of baggage > > that doesn't apply in Python. > > > Can you give a small, complete example that demonstrates the issue > > you're trying to solve? > > > -- > > \ "The face of a child can say it all, especially the mouth part | > > `\ of the face." --Jack Handey | > > _o__) | > > Ben Finney > > Thank you! Sorry for my poor english! > > Here is a example that I want to complete:>>> import sys, new > >>> context={"name":"david", "sex":"male"} > >>> sys.modules["foo"] = new.module("foo") > >>> import foo > >>> for attr in context: > > setattr(foo, attr, context[attr]) > > >>> def bar(): > > # here is a error > # import * only allowed at module level > from foo import * > print name, sex > > >>> bar() > > def bar(): from foo import name, sex print name, sex You will need to know beforehand what attributes you want to import into the function. From andreas.mock at web.de Thu Jul 17 13:27:38 2008 From: andreas.mock at web.de (McA) Date: Thu, 17 Jul 2008 10:27:38 -0700 (PDT) Subject: unpacking with default values References: <335e7a21-e35e-41ee-9f92-fd4c2f6bf166@f36g2000hsa.googlegroups.com> Message-ID: <6a105194-a248-4ee6-be01-5aef9e5bb648@e53g2000hsa.googlegroups.com> On 17 Jul., 18:33, Gary Herron wrote: > > In Python 2.x, you can't do that directly, but you should be able to > create a function that lengthens or shortens an input tuple of arguments > to the correct length so you can do: > > a,c,b = fix(1,2) > d,e,f = fix(1,2,3,4) > > However, the function won't know the length of the left hand side > sequence, so it will have to be passed in as an extra parameter or hard > coded. Hi Gary, thank you for the answer. Do you know the "protocol" used by python while unpacking? Is it a direct assingnment? Or iterating? Best regards Andreas Mock From jim.hefferon at gmail.com Tue Jul 1 19:55:11 2008 From: jim.hefferon at gmail.com (Jim) Date: Tue, 1 Jul 2008 16:55:11 -0700 (PDT) Subject: convert unicode characters to visibly similar ascii characters References: Message-ID: <040bbdba-169b-4340-aa76-a7d2d0954346@34g2000hsf.googlegroups.com> Peter Bulychev wrote: > I want to convert unicode character into ascii one. You have to make some arbitrary choices of what to translate. Based on some materials on effbot's site, and a recipe, I made ftp://alan.smcvt.edu/hefferon/unicode2ascii.py which has at least some of what you are looking for. $ grep HYPHEN unicode2ascii.py u'\N{SOFT HYPHEN}':u'-', u'\N{HYPHEN}':u'-', u'\N{NON-BREAKING HYPHEN}':u'-', u'\N{SOFT HYPHEN}': '-', No doubt I have some terrible gaffes and some things missing. Corrections appreciated. Jim From ezindy at gmail.com Sat Jul 19 06:29:36 2008 From: ezindy at gmail.com (Egor Zindy) Date: Sat, 19 Jul 2008 11:29:36 +0100 Subject: ftdi chip + ctypes + ftd2xx... need help with reading chipid! Message-ID: <4881C210.7000307@gmail.com> Dear List, This one is way beyond my comprehension skills, I just don't understand what I'm doing wrong. I am trying to read the chipid from an FTDI chip based USB key (DLP-D, http://www.ftdichip.com/Products/EvaluationKits/DLP-D.htm ), using: - the ftd2xx module http://pypi.python.org/pypi/ftd2xx/0.1 - the ftd2xx.dll which comes with the driver install - the chipid dll (1.1.0) from here: http://www.ftdichip.com/Projects/FTDIChip-ID.htm - a ctypes interface I wrote by hand (only 7 functions to wrap, I thought it'd be easy!) The ftd2xx is used for testing, to open / close the device. My Problem is that neither of the following two wrapped functions (with the exact same arguments) return the right result (full chipid.py library attached): def FTID_GetDeviceLocationID(DeviceIndex): n = DWORD() status = ftchipid.FTID_GetDeviceLocationID(DeviceIndex, ctypes.byref(n)) if status != FTID_SUCCESS: raise DeviceError,FTID_GetErrorCodeString("EN",status) return n.value def FTID_GetDeviceChipID(DeviceIndex): n = DWORD() status = ftchipid.FTID_GetDeviceChipID(DeviceIndex, ctypes.byref(n)) if status != FTID_SUCCESS: raise DeviceError,FTID_GetErrorCodeString("EN",status) return n.value * On my machine (XP, 32 bits), if I plug two keys in, I can get the device chip id from the device with index=1. The one with index=0 always gives the message "Invalid device handle." * I get the wrong location id as well, 0 instead of 0x21... * the FTID_GetNumDevices function also uses a byref, c_ulong and works. * FTDI's win32 console example returns the right results (and uses c unsigned longs) - available from http://www.ftdichip.com/Projects/FTDIChip-ID.htm Any help appreciated! Regards, Egor -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: chipid.py URL: From babacity2 at gmail.com Thu Jul 24 16:57:51 2008 From: babacity2 at gmail.com (babacity2 at gmail.com) Date: Thu, 24 Jul 2008 13:57:51 -0700 (PDT) Subject: www Efukt - Amazing porn video collection Message-ID: www efukt . >>>>>>>>>>Best Collection of Efukt Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE www efukt VIDEOS<<<<<<<<<<< . www efukt From Russ.Paielli at gmail.com Tue Jul 29 00:33:15 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jul 2008 21:33:15 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> <466157f1-adcb-45f6-8c2d-b3c245a6ce8d@p31g2000prf.googlegroups.com> Message-ID: <47a24fed-6822-4767-aad3-07a72ddc3a1a@m73g2000hsh.googlegroups.com> On Jul 28, 8:44 pm, alex23 wrote: > On Jul 29, 4:46 am, "Russ P." wrote: > > > As I said, I could write a pre-processor myself to > > implement it in less than a day. > > So WHY DON'T YOU WRITE IT ALREADY? I'm working on something else right now if you don't mind, but I'll get to it in good time. Conceptually, the matter is simple. All I need to do is to grab the first formal argument of each def, then search for occurrences of any word in the body of the def that starts with a dot, and insert that first argument in front of it. I expect the "hard" part will be breaking up the body of the def into "words." I could just split each line on white space, except for situations like x+=.zzz So I need to account for the fact that operators do not need to be surrounded by spaces. That's the hardest part I can think of off the top of my head. Maybe I'll encounter an insurmountable problem and realize that the idea can't work in general. If so, then so be it. Certainly, no one on this thread has anticipated such a problem. Had someone pointed out an actual technical problem with the idea, I would have gladly thanked them. But I got a load of irrelevant crap instead, not to mention being addressed as "boy." > If you're meeting so much resistance to your idea, why not scratch > your own damn itch and just do it? > > Or doesn't that afford you as many chances to insult others while > feeling smugly superior? This coming from a guy who insulted my reading comprehension ability -- when he was the one who was wrong! From pavlovevidence at gmail.com Tue Jul 29 13:28:10 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 10:28:10 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: On Jul 29, 5:27 am, Steven D'Aprano wrote: > On Tue, 29 Jul 2008 01:37:45 -0700, Carl Banks wrote: > > I am looking for one that can't. > > If you are writing code that needs to do the right thing with arbitrary > types, then your so-called "simple explicit tests" simply can't work. I asked for a code example. You say this is true, but neither you nor anyone else here has provided useful code that demonstrates it. Carl Banks From bronger at physik.rwth-aachen.de Sat Jul 26 17:35:22 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 26 Jul 2008 23:35:22 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> Message-ID: <87k5f88h2d.fsf@physik.rwth-aachen.de> Hall?chen! Terry Reedy writes: > Torsten Bronger wrote: > >> Terry Reedy writes: >> >>> [...] >>> >>> Or the proposal would have to be that 'self' is mandatory for >>> all programmers in all languages. I think *that* would be >>> pernicious. People are now free to write the more compact 's.sum >>> = s.a + s.b + s.c' if they want instead of the 'self' version. >>> And again, not everyone writes in English. >> >> Of course, "self" would have to become a reserved word. You >> could say that this may break some code, > > Will break. No more than Python 3.0 breaks. >> but I don't see much freedom removed from the language. After >> all, being a German, I still can't write "F?r i in range(10)". >> ;-) > > But you can write 'for ubermenchen in range(10):' and in 3.0, with > diacritics added. Would you really feel no loss of freedom if > Guido make i0, i1, ... into keywords, which means they could not > be used elsewhere, and mandated them as for loop index variables? I would, but I consider "self" becoming a keyword not even in the same league as i0, i1 etc. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From mrkafk at gmail.com Fri Jul 4 06:59:22 2008 From: mrkafk at gmail.com (mk) Date: Fri, 04 Jul 2008 12:59:22 +0200 Subject: Naming conventions for regular variables Message-ID: http://www.python.org/dev/peps/pep-0008/ "Function Names Function names should be lowercase, with words separated by underscores as necessary to improve readability." However, this PEP does not recommend any particular style for naming regular (local) variables. Personally I like "mixedCase", however using both styles looks a bit weird: def some_function_name(someVariableName, anotherVar) Naming both functions and variables using "lowercase with underscore separator between words for readability" leads to confusing function names with variable names - and distinguishing between variables and function names just by looking at them would be nice. Recommendations? From tjreedy at udel.edu Fri Jul 18 16:49:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Jul 2008 16:49:21 -0400 Subject: checking if an object IS in a list In-Reply-To: References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: Peter Otten wrote: >> So, precisely, you mean that if hash(a) != hash(b), a and b are >> considered distinct, and else [ie. if hash(a) == hash(b)], a and b are >> the same if and only if a == b ? > > Correct for set, dict. For lists etc. the hash doesn't matter: Since CPython saves strings hashes as part of the string object (last I read, as part of internal string caching), it does something similar. Compare lengths, then hashes, then C array. From fredrik at pythonware.com Tue Jul 22 04:59:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 10:59:13 +0200 Subject: scanf in python In-Reply-To: <488568f6$0$6120$426a74cc@news.free.fr> References: <4884be5e$0$19722$426a74cc@news.free.fr> <488568f6$0$6120$426a74cc@news.free.fr> Message-ID: AMD wrote: > I had seen this pure python implementation, but it is not as fast or as > elegant as would be an implementation written in C directly within > python with no need for import. maybe you should wait with disparaging comments about how Python is not what you want it to be until you've learned the language? From robert.kern at gmail.com Tue Jul 8 18:04:40 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 08 Jul 2008 17:04:40 -0500 Subject: Logging to zero or more destinations In-Reply-To: <87r6a4du2k.fsf@merkury.smsnet.pl> References: <87r6a4du2k.fsf@merkury.smsnet.pl> Message-ID: Rob Wolfe wrote: > samwyse writes: >> The only way that I can see for all three statements to be consistent >> is that the root logger starts with an empty list of handlers, and >> doesn't instantiate a default handler until either >> logging.basicConfig() is called, > > That is correct. > >> or the first time that a message is >> logged. > > That is not correct. The list of handlers is empty until `basicConfig` > or explicit `addHandler` is called. > >> This would also seem to imply that there's no way to use an >> empty handler list (say, if you want to suppress all logging), because >> the root handler will instantiate a handler for you. Is this correct? > > No. Consider this: > >>>> import logging >>>> logging.root.warning('error message') > No handlers could be found for logger "root" >>>> logging.root.warning('error message') > > Note only one warning message. Ah, right. It is the module-level functions logging.warn(), etc. that invoke basicConfig() if no handler is present. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From google at mrabarnett.plus.com Thu Jul 10 19:33:02 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 10 Jul 2008 16:33:02 -0700 (PDT) Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: <8397d958-2c0e-40c7-8488-152559711163@c65g2000hsa.googlegroups.com> On Jul 10, 9:46?pm, ssecorp wrote: > >>> def mod(x,y): > > ? ? ? ? return x.append(y) > append adds y to list x and returns None, which is then returned by mod. > > > >>> mod([1,2],3) > >>> k=[1,2,3] > >>> k > [1, 2, 3] > >>> l = mod(k,4) 4 has been appended to list k and mod has returned None, so l is now None. > >>> l > >>> k > [1, 2, 3, 4] > >>> l > >>> k==l > False Because k is [1, 2, 3, 4] and l is None. > >>> mod(k,5) > >>> k > [1, 2, 3, 4, 5] > >>> mod(l,4) > > Traceback (most recent call last): > ? File "", line 1, in > ? ? mod(l,4) > ? File "", line 2, in mod > ? ? return x.append(y) > AttributeError: 'NoneType' object has no attribute 'append' > l is None, not a list, so it complains! > >>> l > >>> l=k > >>> l > [1, 2, 3, 4, 5] > >>> i=mod(k,1) > >>> i > > same stuff but i dont find this intuitive. It's usual for methods which modify to return None. From tjreedy at udel.edu Tue Jul 8 17:17:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 08 Jul 2008 17:17:52 -0400 Subject: numeric emulation and __pos__ In-Reply-To: <4873A50C.5090003@stoneleaf.us> References: <92e3ea9f-5745-4072-9d09-7c14fd335828@f36g2000hsa.googlegroups.com> <4873A50C.5090003@stoneleaf.us> Message-ID: Ethan Furman wrote: > Anybody have an example of when the unary + actually does something? > Besides the below Decimal example. I'm curious under what circumstances > it would be useful for more than just completeness (although > completeness for it's own sake is important, IMO). All true operators and some built-in functions translate to special method calls. -x == x.__neg__() == type(x).__neg__(x) == x.__class__.__neg__(x) What should happen to '+x'? Raise SyntaxError? Ignore the '+'? Or translate it to __pos__ in analogy with '-' and __neg__? Guido made the third choice: partly for consistency perhaps, but also for the benefit of user-written classes. Decimal started as user-contributed decimal.py. Does anything else use this hook? I don't know, but I do know that there are periodic demands for *more* operators for user use. So I expect it has been. tjr From robert.rawlins at thinkbluemedia.co.uk Thu Jul 24 12:06:06 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 24 Jul 2008 17:06:06 +0100 Subject: Gracefull application exit. Message-ID: <00ba01c8eda7$2e61ecb0$8b25c610$@rawlins@thinkbluemedia.co.uk> Chaps, I'm looking to implement an exit/termination process for an application which can be triggered by A) a keyboard interrupt or B) termination of the application as a Daemon using a signal. I have a whole bunch of tasks I want to perform as a cleanup before the application is terminated, cleaning files, database calls, closing open connections and a few other things. I know we have: # I'm the main application started method. if __name__ == "__main__": For starting an application, but do we have an equivalent methods for when an application is terminated which we can use to close down any current internal processes before the application exits? I'd really love to have your thoughts and experience on gracefully killing an application. Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeffrey at fro.man Fri Jul 11 09:29:16 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Fri, 11 Jul 2008 06:29:16 -0700 Subject: MySQLdb will only import for root References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> <85d26ae4-757f-494c-bf7e-412323e26b8a@x41g2000hsb.googlegroups.com> <6dp092F3mhbaU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> Is it possible the module was installed with priviledges set too >> strict? ?Perhaps the interpreter cannot see the module when it is run >> from a normal user account. > > Possible - certainly. Yet unrealistic, because usually root access is > required to system-wide install a package - thus the normal install > processes ensure proper rights. According to the OP, it is root that *does* have access to MySQLdb and a normal user that does not. It is a very realistic possibility to install something as root to which normal users do not have access. Installation scripts that assume a particular umask during install, for example, are especial culprits. I have noticed this problem myself with python modules that include compiled C extensions, as MySQLdb does. However, in the case where the extension module itself has incorrect permissions, the error would point to a missing _mysql, rather than a missing MySQLdb. Jeffrey From support.desk.ipg at gmail.com Mon Jul 28 13:32:33 2008 From: support.desk.ipg at gmail.com (Support Desk) Date: Mon, 28 Jul 2008 12:32:33 -0500 Subject: python lists and newline character Message-ID: <053101c8f0d7$ebd7c340$a601a8c0@office.ipglobal.net> Hello all, I am using os.popen to get a list returned of vpopmail users, something like this x = os.popen('/home/vpopmail/bin/vuserinfo -n -D mydomain.com).readlines() x returns a list, of usernames, and I am trying to append the usernames with the domain like so for line in x: print line + '@' + domain but instead of getting user at domain.com im getting a newline character like: user @domain.com User @comain.com User2 @domain.com Is there some way I can get this list without the newline characters being added. or somehow remove the newline characters. Any help would be appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexnbryan at gmail.com Thu Jul 17 04:23:57 2008 From: alexnbryan at gmail.com (Alexnb) Date: Thu, 17 Jul 2008 01:23:57 -0700 (PDT) Subject: Getting a unknown word out of a list with no spaces In-Reply-To: <93164ef9-7079-44db-9ac4-b0a18b0ddf3e@b1g2000hsg.googlegroups.com> References: <18502758.post@talk.nabble.com> <487EF593.5060505@promsoft.ru> <18503144.post@talk.nabble.com> <487EF7D9.8010400@promsoft.ru> <93164ef9-7079-44db-9ac4-b0a18b0ddf3e@b1g2000hsg.googlegroups.com> Message-ID: <18503830.post@talk.nabble.com> bearophileHUGS wrote: > > On Jul 17, 9:50 am, Alexnb: >> how can I test to see if the first char of a string is "<"? > > I suggest you to try the interactive shell: > >>>> "hello"[0] > 'h' >>>> "hello"[0] == "<" > False >>>> "hello"[0] == "h" > True >>>> "hello".startswith("h") > True > > Bye, > bearophile > -- > http://mail.python.org/mailman/listinfo/python-list > > really? That's just like C. I thought that it would fail because of the way lists work. Thanks! -- View this message in context: http://www.nabble.com/Getting-a-unknown-word-out-of-a-list-with-no-spaces-tp18502758p18503830.html Sent from the Python - python-list mailing list archive at Nabble.com. From tjreedy at udel.edu Wed Jul 9 15:38:46 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 09 Jul 2008 15:38:46 -0400 Subject: Impossible to change methods with special names of instances of new-style classes? In-Reply-To: <429cbef9-0027-4717-a39f-d7e7599e07ae@x35g2000hsb.googlegroups.com> References: <429cbef9-0027-4717-a39f-d7e7599e07ae@x35g2000hsb.googlegroups.com> Message-ID: samwyse wrote: > On Jul 8, 4:56 pm, Joseph Barillari wrote: > >> My question is: did something about the way the special method names are >> implemented change for new-style classes? I believe the difference is that for new-style classes, when special methods are called 'behind the scenes' to implement built-in syntax and methods, they are looked up directly on the class instead of first on the instance. Note that functions attached to instances are *not* methods and do not get combined with the instance as a bound method. From bernhard.voigt at gmail.com Wed Jul 23 09:30:19 2008 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: Wed, 23 Jul 2008 06:30:19 -0700 (PDT) Subject: maximum value in a column of file References: <4886DCF3.10107@isac.cnr.it> <4886F4CD.8010704@isac.cnr.it> <488705D6.4090300@isac.cnr.it> Message-ID: <29926261-1f5b-48c3-8ed7-985dc7e3a072@j22g2000hsf.googlegroups.com> > > thank you for your answer > > actually i've to do some statistics (maximum,minimum,mean,standard > > deviation,....) of a file of data in which each column is a particular > > type of data. (the file is a tab separated value). > > I was trying to do this by using python (usually i work with fortran or > > bash, but i'm learning python), that the reason why i tried to use numpy. numpy.loadtxt is probably what your looking for, provided your file contains only numbers and comment lines. check the example here: http://www.scipy.org/Numpy_Example_List_With_Doc#head-88ade192dacf0c15e4f1377096134ee559df07a0 X = numpy.loadtxt('data.txt') X[:,0].mean() # mean of first column X[:,0].max() # mux of first column X[:,0].var() # variance of first column ... enjoy! bernhard > > As I implied, you can do all this in standard Python "by hand", but > numpy/scipy can definitely make things easier. There's a dependency > cost here (your program needs one or more extra libraries to work), but > if that's no problem in your environment, I'd recommend that approach. > > The scipy add-on contains a bunch of things for file i/o; see > > http://www.scipy.org/doc/api_docs/SciPy.io.html > > for an overview. Since you're reading text files, the "array_import" > module seems to be what you need: > > http://www.scipy.org/doc/api_docs/SciPy.io.array_import.html > > There are active user communities for both numpy and scipy that can help > you sort out any remaining issues; for details, see: > > http://www.scipy.org/Mailing_Lists > > Hope this helps! > > From morse at edoug.org Fri Jul 18 10:07:45 2008 From: morse at edoug.org (Doug Morse) Date: Fri, 18 Jul 2008 14:07:45 +0000 (UTC) Subject: Core Dump - Segmentation Fault -Newbie References: <8ba4373d-3d97-4e9a-a15e-723f6818c757@k36g2000pri.googlegroups.com> <4880A0FA.6030603@behnel.de> Message-ID: On Fri, 18 Jul 2008 15:56:10 +0200, Stefan Behnel wrote: > johnericaturnbull at yahoo.com wrote: > > Hi - I am very new to python. I get this random core dump and am > > looking for a good way to catch the error. I know the function my core > > dump occurs. Is there any error catching/handling that I could use in > > python? > > Since you are using Windows, this is somewhat non-trivial due to the lack of > tools shipped by Microsoft. Are you really getting crashes of the interpreter > and not just an exception with a stacktrace? > > Stefan Hi John, Well, I must be missing something re: why Stefan states that you are using Windows. I don't see that stated in your original post, and, AFAIK, the phrase "core dump" is seen much more in the Unix world than in the Windows world. So, just in case you are on some *nix variant, you can of course log all the system calls up until your core dump by running: $ strace -o logfile.txt python [...] where [...] should be replaced with any parameters to the python interpreter, such as the Python script you're running, e.g., $ strace -o logfile.txt python Hello.py The trace of system calls will be in the file logfile.txt. For more info on strace, see the strace(1) man page (i.e., run "man strace"). Doug From viv1tyagi at gmail.com Tue Jul 1 06:13:42 2008 From: viv1tyagi at gmail.com (viv1tyagi at gmail.com) Date: Tue, 1 Jul 2008 03:13:42 -0700 (PDT) Subject: Having problems using Tkinter Message-ID: <144f93d3-b493-4280-a3a4-23a2b13b59c6@i36g2000prf.googlegroups.com> Hi everyone ! ! ! I'm just a month old in the world of Python and trying to develop an application using Tkinter in which a new window pops out on a particular button press.The code for this new window is in "AddKlas.py" file. The problem is all the content of the new window is overwritten on the previous window. Below is the code of the two files PLEASE help me out ! ! ! ! #1st file #Klass.py from Tkinter import * import AddKlass class Klass(Frame): def __init__(self): self.labels() self.buttons() self.menubuttons() self.scrollandcanvas() def labels(self): label1=Label(relief='groove',text=" Class Id",width=20,anchor=W) label1.grid(row=0,column=0) label2=Label(relief='groove',text=" Class Name",width=20,anchor=W) label2.grid(row=0,column=1) label3=Label(relief='groove',text=" Class Room No.",width=20,anchor=W) label3.grid(row=0,column=2) label4=Label(relief='groove',text=" Category Id",width=80,anchor=W) label4.grid(row=0,column=3) def buttons(self): button1=Button(text="Add",width=10,command=self.CallAdd) button1.grid(row=2,column=5) button2=Button(text="View",width=10,state=DISABLED) button2.grid(row=3,column=5) button3=Button(text="Next",width=10,state=DISABLED) button3.grid(row=4,column=5) def menubuttons(self): menubutton=Menubutton(text="Options",width=10,relief="raised") menubutton.grid(row=5,column=5) menubutton.menu=Menu(menubutton) menubutton["menu"]=menubutton.menu menubutton.menu.add_command(label="Modify") menubutton.menu.add_command(label="Delete") def scrollandcanvas(self): yscroll=Scrollbar() yscroll.grid(row=1,column=4,rowspan=7,sticky=N+S) canva=Canvas(bg="#fff",yscrollcommand=yscroll.set) canva.grid(row=1,column=0,rowspan=7,columnspan=4,sticky=N+E+S +W) def CallAdd(self): AddKlass.root=Tk() AddKlass.AddKlas() AddKlass.root.focus_force() AddKlass.root.geometry("275x250") AddKlass.root.title("Add Class Information") AddKlass.root.resizable(width=False,height=False) AddKlass.root.mainloop() root=Tk() app = Klass() root.geometry("960x300") root.title("Class Information") root.resizable(width=False,height=False) root.mainloop() #2nd file #AddKlass.py from Tkinter import * class AddKlas(Frame): #root=None def __init__(self): self.labels() self.buttons() self.entry() def labels(self): label1=Label(relief='flat',text=" Class Id :",height=3,width=20) label1.grid() label2=Label(relief='flat',text=" Class Name :",height=3,width=20) label2.grid() label3=Label(relief='flat',text=" Class Room No. :",height=3,width=20) label3.grid() label4=Label(relief='flat',text=" Category Id :",height=3,width=20) label4.grid() def buttons(self): button1=Button(text="Add",width=10,state=DISABLED) button1.grid(row=5,column=0) button2=Button(text="Cancel",width=10,command=self.quit) button2.grid(row=5,column=1) def entry(self): entry1=Entry() #by default width =20 entry1.grid(row=0,column=1) entry2=Entry() entry2.grid(row=1,column=1) entry3=Entry() entry3.grid(row=2,column=1) entry4=Entry() entry4.grid(row=3,column=1) #root=Tk() #app = AddKlas() #root.geometry("275x250") #root.title("Add Class Information") #root.resizable(width=False,height=False) #root.mainloop() From mail at microcorp.co.za Tue Jul 8 04:10:35 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 8 Jul 2008 10:10:35 +0200 Subject: Cross Compiler for Python? Message-ID: <001101c8e0d2$36a50ec0$0d00a8c0@hendrik> norseman wrote: >================================================== >In case all else fails: > >This is not a cookbook answer, but: > 1) gnu's gcc will compile to 16,32 or 64 bit intel architectures > OK, the 32 bit version compiles to 16 or 32 & the 64 should. > The 64 will run 32 bit programs, including the 32 bit gcc. > chgroot can be (messy but) useful to maintain separation. > 2) info gcc and look for compiler directives > then info nasm and look for directives > same for the linker > I'm not specific because I use Slackware and different > distros can use different modules. You may have an assembler > with a different name. Switches can be different and so > forth. >On Slackware the installpkg (for tarballs already compiled) records the >locations of where things go in /var/log/packages. I have to assume >other distros have something similar since these are used to remove >things later. Can we say 'updates'? If not you will need to wade >through the .configure and Makefiles to root out what happens to get >'vanilla' locations. > >Like I said, it's not cookbook, but it will get you there and you will >gain quite an insight into Linux. While the path may not be well marked >in Linux, there usually is one. > >Sorry I don't have a more straight forward approach. > >- Steve > Thanks Steve, for the tips. In a sense, I have dreaded an answer like this, as it is cold comfort to realise that I will be hassled off my objective to take a side trip through Linux's complexities, just so that I can play with the hardware to evaluate if we can use it for what we want to do. I had fondly hoped that somebody would have blazed the way before me. But it seems not. Tough. I will report here what I do and find - It may help some other poor sod some day... - Hendrik From Lie.1296 at gmail.com Tue Jul 8 06:53:17 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 8 Jul 2008 03:53:17 -0700 (PDT) Subject: how are strings immutable in python? References: Message-ID: <1df93c62-3443-488c-9069-dcdc83842c8e@34g2000hsh.googlegroups.com> On Jul 7, 1:45?am, ssecorp wrote: > >>> h = "aja baja" # 'aja baja' is created and assigned to the name h > >>> h += 'e' # Is the equivalent of: # h = h + 'e' # # In there, a h and 'e' is concatenated and assigned to # a new string object which is bound to h. The # original string object which contains # 'aja baja' is "garbage collected"[1]. > >>> h # printing h which contains the new string object containing 'aja bajae' > 'aja bajae' [1] actually python uses reference counting first to choose which object to delete From gherron at islandtraining.com Tue Jul 1 19:47:53 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 01 Jul 2008 16:47:53 -0700 Subject: Attribute reference design In-Reply-To: References: <6cvlk4F3s90U1@mid.uni-berlin.de> Message-ID: <486AC229.60300@islandtraining.com> chamalulu wrote: > On Jul 2, 1:17 am, Gary Herron wrote: > >> No need. Also, you can define a class attribute (C++ might call it a >> static attribute) and access it transparently through an instance. >> >> class C: >> aClassAttribute = 123 >> def __init__(self, ...): >> ... >> >> c = C() >> ... do something with c.aClassAttribute ... >> >> > > Actually, this is why I started too look into the attribute reference > mechanics to begin with. Coming from mostly C# development I think > it's weird to be able to refer to class attributes (static members) > through a class instance (object). But I think I'm getting the > picture. Function objects lay flat in memory (some heap...). Not quite. Not *flat memory* or a heap. Modules are first class objects, and functions (and classes and anything else) defined at the top level of the module are *attributes* of the module. Gary Herron > When > defined inside classes they are wrapped in method objects. When > refered through classes or class instances they are unbound method > objects or bound method objects respectively. Am I on the right track? > I still don't get why these methods show up when I dir() a class > instance. > > /Henrik > -- > http://mail.python.org/mailman/listinfo/python-list > From stochashtic at yahoo.ca Mon Jul 28 03:50:54 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 28 Jul 2008 09:50:54 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> <4889e5bc$1@news2-rz-ap.ethz.ch> Message-ID: <488d7a5e$1@news2-rz-ap.ethz.ch> On Fri, 25 Jul 2008 09:22:06 -0600, Matthew Fitzgibbons wrote: > As for different data structures, it largely depends on how you need to > access the data. If you don't need to index the data, just loop through > it, you might try a linked list. The performance hit in (2) is coming > from the list del; using a linked list would make the removal constant > rather than O(n), and may even execute faster than (3) as well. > > -Matt Yes, this was my first inclination. So my question, as alluded to in my original post, is whether there are C compiled modules for linked lists, doubly linked lists, ordered lists ... (the standard data structures) somewhere, to get the extra performance out of them. With python we have all built up creative ways of using the native structures for efficiency reasons. This project was the first time (due to its extreme use of resources) that I've had to worry about these minute considerations of native vs new structure but also take into account native vs python level construct vs compiled module. [P.S. The linked list does compare well with (3) as expected.] From robert.kern at gmail.com Mon Jul 7 21:04:42 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 07 Jul 2008 20:04:42 -0500 Subject: Python Agile Software Development Tools Screencasts In-Reply-To: <87hcb1w6gl.fsf@benfinney.id.au> References: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> <87lk0dwbys.fsf@benfinney.id.au> <87hcb1w6gl.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Robert Kern writes: > >> Ben Finney wrote: >>> percious writes: >>> >>>> I started a new series about python on showmedo. Please feel free >>>> to take a look. >>> I'd love to, but showmedo refuses to show presentations to me >>> without installing non-free software. >> mplayer works just fine on the .flv's. > > Note that "works with mplayer" is not the same thing as "doesn't > require non-free software"; many "works with mplayer" stories have the > unspoken addendum of "... with these non-free codec libraries > installed". But, not having the video files, I can't say whether > that's the case in this instance. I believe .flv is entirely handled by ffmpeg. > Okay. Where would the public link to those files be? > > If I need to "log in" just to download it, that's a needless barrier > that's going to turn me away too. Yes, you do need to log in. If you don't want to do it, that's fine. I certainly don't care. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sneuberger at mitre.org Fri Jul 18 16:35:07 2008 From: sneuberger at mitre.org (Neuberger, Sheldon N.) Date: Fri, 18 Jul 2008 16:35:07 -0400 Subject: Writing a program under GNU/Linux for MS Windows. In-Reply-To: References: Message-ID: <7B3D44209E8C944288889D4132FEC4125B98C5@IMCSRV6.MITRE.ORG> If you're just writing Python code then it will run unmodified on his Windows machine. Are you planning on using other languages too? -----Original Message----- From: python-list-bounces+sneuberger=mitre.org at python.org [mailto:python-list-bounces+sneuberger=mitre.org at python.org] On Behalf Of Levi Campbell Sent: Friday, July 18, 2008 4:27 PM To: python-list at python.org Subject: Writing a program under GNU/Linux for MS Windows. Hi, I'm trying to write a program for a friend of mine who uses windows but I use GNU/Linux. I know you can use mingw and link to the python dll, but is there a way to create a win32 service under Linux? -- http://mail.python.org/mailman/listinfo/python-list From casevh at gmail.com Thu Jul 3 21:10:51 2008 From: casevh at gmail.com (casevh) Date: Thu, 3 Jul 2008 18:10:51 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> Message-ID: On Jul 3, 6:54?am, Mensanator wrote: > > Well, it will be great at some point in the future > when Python 2.6/3.0 have actually been released and > third party extensions such as gmpy have caught up. > > Until then, such solutions are worthless, i.e., of > no value. gmpy is supported on Python 2.6. A new version and Windows binaries were released shortly after 2.6b1 was released. casevh From michele.simionato at gmail.com Sat Jul 26 13:20:43 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 26 Jul 2008 10:20:43 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> Message-ID: On Jul 26, 5:28?pm, a... at pythoncraft.com (Aahz) wrote: > IMO, you made a big mistake in combining your point with two other meaty > issues (whether method definitions should include self and whether != > should use __eq__() as a fallback). > ?If solid discussion > is your goal, I suggest that you wait a couple of weeks and start over > with a brand-new thread. I fully subscribe this. The point about __eq__ is legitimate and could be discussed with quite tones. I was bitten by this surprising behavior just a few days ago, I had defined __eq__ and I expected __neq__ to be defined in the obvious way. I saw that it was not the case and I figured out immediately that I had to override __neq__ explicitely (I have the "explicit is better than implicit" mantra ingrained in my mind too), I did so and everything worked out as a charm. Total time loss: five minutes. So, it is not a big point. Still I think that it would make sense to automatically define __neq__ as the negation of __eq__. I suppose the developers did not want to make a special case in the implementation and this is also a legitimate concern. Michele Simionato From semanticist at gmail.com Sun Jul 13 17:33:37 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 17:33:37 -0400 Subject: Magic? In-Reply-To: References: Message-ID: On Sun, Jul 13, 2008 at 12:55 PM, mk wrote: > So my updated question is where does this lstr() instance keep the original > value ('abcdef')? It obviously has smth to do with inheriting after str > class, but I don't get the details of the mechanism. Through the str.__new__ method: http://docs.python.org/ref/customization.html Calling a constructor: foo = Foo(1, 2, 3) Is roughly equivalent to: foo = Foo.__new__(Foo, 1, 2, 3) Foo.__init__(foo, 1, 2, 3) As a side note, you may already know this, but it's not necessary to create a property setter that raises an error to make a property read-only; you can simply not define a setter method. -Miles From sunp1028 at gmail.com Tue Jul 15 23:10:36 2008 From: sunp1028 at gmail.com (patrol) Date: Tue, 15 Jul 2008 20:10:36 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> Message-ID: > At any rate, try using: > > result, = new_process.Terminate () Windows is sometime case insensitive,but the python is case sensitive. I also encountered this kind of problems. Thanks for Tim's help. Patrol From thomas.troeger.ext at siemens.com Tue Jul 15 05:51:47 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Tue, 15 Jul 2008 11:51:47 +0200 Subject: Python embedding question. Message-ID: Hi, Sorry I've posted a similar question some weeks ago, but I got no answers. I want to embed a Python application on a device with limited resources, esp. storage limitations. Is there a way to reduce the Python interpreter to a set of modules that's urgently needed? Or is there a method to have gzipped modules that are unzipped on the fly into memory when they're accessed? That would be even better. Additionally, is there a Python module that contains all the stuff needed for an embedded application like graphics, sound etc. or do I have to use the various bindings to libraries like cairo, Qt or similar? Is there a site that helps with those decisions? I've really looked at a lot of places but haven't found a suitable solutions yet, so I'm asking here in hope that someone has experience with that topic. Regards, Thomas. From mhansen at gmail.com Thu Jul 10 05:45:23 2008 From: mhansen at gmail.com (Mike Hansen) Date: Thu, 10 Jul 2008 02:45:23 -0700 (PDT) Subject: python scalability References: Message-ID: > I have looked at the python > success stories page and haven't come up with anyone quite like us. > One of my project managers questions is: "Are we the only company in the > world with this kind and size of project?" > I want to say no, but am having trouble convincing myself, let alone him. > > If you are involved in this kind of thing please get in touch with me. While Sage ( http://www.sagemath.org ) is more of a library than an application, it is approximately 350k lines of Python and Cython (in roughly a 2 to 1 ratio). I think it has scaled surprisingly well. --Mike From chris.hulan at gmail.com Fri Jul 4 09:55:34 2008 From: chris.hulan at gmail.com (Chris Hulan) Date: Fri, 4 Jul 2008 06:55:34 -0700 (PDT) Subject: running python from cmd.exe References: Message-ID: On Jul 4, 5:38 am, Dominic Rice wrote: > Dominic Rice wrote: > > Miki wrote: > >> Hello, > > >>> I can't seem to get python to run my scripts using the command: python > >>> .py > > >>> If I type python the interpreter runs as I sorted out the Path property, > > >>> I'm afraid I don't know much about this kind of thing as I'm a science > >>> student who needs some Python not a programmer! > >> Can you be more specific about the error you get? > > >> Say you have a script hw.py that contains one line: > >> print "Hello Python" > > >> and you run > >> python hw.py > > >> What is the error you get? > > >> HTH, > >> -- > >> Miki > >>http://pythonwise.blogspot.com > > > Sure, I get: > > > can't open file .py: [errorno 2]No such file or directory. > > > Now if I've noticed that if I change directory to (for instance) > > \Python25 where the script is the command runs fine.(?) > > Oh I just noticed you specified hw.py, in that case just to clarify it > would be can't open file hw.py: [errorno 2]No such file or directory When you run a script, are you in the directory where the script is located? From deets at nospam.web.de Thu Jul 31 19:35:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 01 Aug 2008 01:35:43 +0200 Subject: Function References In-Reply-To: References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> <6fe0scFaus40U1@mid.uni-berlin.de> <6bc8bc07-eab0-4303-b8a4-c9470f96038d@c65g2000hsa.googlegroups.com> <6fe1n2Faus40U3@mid.uni-berlin.de> Message-ID: <6ff0ifFbbpfbU1@mid.uni-berlin.de> squishywaffle at gmail.com schrieb: > On Jul 31, 10:47 am, "Diez B. Roggisch" wrote: >> I take the freedom to do so as I see fit - this is usenet... > > Fine, then keep beating a dead horse by replying to this thread with > things that do nobody any good. It seems like there are a lot better > way to waste time, though. You mean like trying to wrap ones head around the rather simple Python C API, not getting a callback mechanism implemented? For the record: I've wrapped C-libs myself, including callbacks. Been there, done that, discovered (years later) cytpes, been there for good. > The Python/C API can get me back further without reliance on third- > party libraries than ctypes. You don't consider your own library a third party lib? And unless you're wrapping C++, you're opinion is as uninformed as it is wrong. > It also isn't subject to the quirks that > ctypes is on platforms other than Windows (the target application runs > on Windows, Mac, and eventually Linux once the original distributor > has drivers for the device). I'm not even sure ctypes could load the > lib/driver the distributor packaged. Oh please. I'm 98% working on linux & osx. ctypes does a great job on these platforms. Regarding your objections I can only say: whatever the python runtime can load because of the underlying ld, ctypes can load. simply because they are the same. If *that* was the actual cause of problems, we wouldn't even talk about callbacks here. > So really, I appreciate the option in ctypes, it's good stuff. But > it's not for this project. Stop finding lame excuses for not wanting to ditch the work you've done in favor of a easier solution. You like your code, you want to keep it, you want to discover the intricasies of the Python C API? Be my guest. But stop embarassing yourself inventing reasons like licensing or linker problems you don't support with any facts whatsoever. > Once again, the original question stands for anyone who has experience > with the Python/C API callbacks. You know what? Just for the fun of it, I'll take a stab at it. It's easy: Create a "proxy-function" that matches the prototype of the c8allback which converts the passed arguments to python values using the C-api. Then call the registered python function using PyObject_CallFunction. Convert the return-value back to C, and return it. Make the function get the PyObject* for the call fetch from a global variable you set in the register-callback function, where you also register the proxy-function for the first time, or de-register if the passed value is None or such. Have fun. Diez From timr at probo.com Sun Jul 27 00:32:59 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 27 Jul 2008 04:32:59 GMT Subject: Stripping parts of a path References: Message-ID: <8utn84hs5c713k54l5kmfrgbg3k2dr1oce@4ax.com> Tim Cook wrote: > >I just ran into an issue with the rstrip method when using it on path >strings. > >When executing a function I have a need to strip off a portion of the >current working directory and add on a path to a log file. Initially >this worked great but then I added a branch in SVN which caused the path >to contain 'LNCCWorkshop'. The rstrip() then began removing the >characters 'shop' leaving an incorrect path to the log file. When I >hard coded this path it worked okay but then did the same thing later in >the file when I needed to point to a database. The code worked fine with >a different path. Here are some code fragments. > >logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/at_build_errors.log' This doesn't do what you think it does. The parameter to rstrip is a set: as long as the last character is in the set 'abcdhiloprs/', it will remove it and check the next one. All of the characters in "shop" are in that set. In a few minutes, I couldn't think of a clever one-liner to do this. You could do it with re.sub, but that seems like overkill. chk = '/src/oship/atbldr' cwd = os.getcwd() if cwd.endswith( chk ): cwd = cwd[:-len(chk)] -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steven.potter at gmail.com Sun Jul 6 23:55:02 2008 From: steven.potter at gmail.com (Steve Potter) Date: Sun, 6 Jul 2008 20:55:02 -0700 (PDT) Subject: mirroring files and data via http References: Message-ID: <9a56e820-164f-4151-82f0-0bdf64c6a636@59g2000hsb.googlegroups.com> On Jul 6, 8:19 pm, Matt Nordhoff wrote: > Steve Potter wrote: > > I'm working on a project to create a central administration interface > > for several websites located on different physical servers. > > > You can think of the websites as a blog type application. My > > administration application will be used to create new blog posts with > > associated media (images, etc..) > > > So I am thinking to setting up a script on each of the sites to "phone > > home" once per day and download any new posts and media files. > > > I am thinking of transmitting the post data in an xml format that > > could then be decoded an recorded into the database on the slave > > site. Are there any easy ways to encode a python dictionary to and > > from xml? > > > For the media files I am thinking that the administration interface > > would also provide an xml file with a list of all of the media files > > required along with an http path to retrieve them and a checksum of > > some sort to verify that they were downloaded correctly. > > > Basically I am trying to figure out if anything already exists to > > perform some of these functions or if I have to make them from > > scratch. I know none of it should be too hard, but I hate to re- > > invent the wheel. > > > Thanks, > > > Steven Potter > > It sounds like JSON would be perfect for this. For working with it in > Python, the simplejson module is popular: > > > -- Matt, You are correct JSON would be much easier to deal with than xml. That takes care of several of the problems. Now it really just comes down to the file transfer from one server to the other and a verification of some sort that the file transfer was not corrupt. Is there a python module that takes care of file downloads and verification? Thanks, Steve From fredrik at pythonware.com Wed Jul 16 12:46:46 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 18:46:46 +0200 Subject: how to match whole word In-Reply-To: <97461ec5-151a-4527-a5fa-c5da07941e46@l42g2000hsc.googlegroups.com> References: <97461ec5-151a-4527-a5fa-c5da07941e46@l42g2000hsc.googlegroups.com> Message-ID: Peng Yu wrote: > I didn't read the docs and tried the following code. > > regex = re.compile(r"\A" + re.escape(old_str) + r"\Z", > opts.ignore_case and re.I or 0) > > But I'm not sure why it is not working. as the documentation says, \A and \Z matches at the beginning/end of a *string*, not a word. From tcfg at sina.com Thu Jul 17 08:16:27 2008 From: tcfg at sina.com (fang) Date: Thu, 17 Jul 2008 05:16:27 -0700 (PDT) Subject: how to debug python's extend module written in c/c++ on windows References: <64d771b2-fbc8-4b6a-9725-3dc5063c5328@p25g2000hsf.googlegroups.com> <6e83v4F5pfg0U1@mid.uni-berlin.de> <6e8cfgF5n34gU1@mid.uni-berlin.de> Message-ID: <3ac0db1c-81d2-4922-9133-5da830f5a346@34g2000hsh.googlegroups.com> Dear Diez: It is attaching a C-debugger to python. I can attach python- debugger(for example:wingIDE) to c-debugger(for example:VS2008), but I cannot attach VS2008 to wingIDE. I need both python statement and c statement can be single-step debugged. best regards fang From eliben at gmail.com Fri Jul 11 01:27:24 2008 From: eliben at gmail.com (eliben) Date: Thu, 10 Jul 2008 22:27:24 -0700 (PDT) Subject: using Python's AST generator for other languages References: <6d31532b-9946-42a3-a20b-56c403a388b2@l42g2000hsc.googlegroups.com> Message-ID: > > 2) What is the meaning of the comment in astgen.py ? Are the Python > > maintainers unhappy with the design of the AST ?3 > > Node, I think, is talking about a node in the parse tree. (AST is > generated from another parse tree.) See PEP 339 for details. > Thanks, PEP 339 clarified a lot to me. I wonder, though, at the need for two Python compilation frameworks in the same code base. While CPython uses the flow described in PEP 339 (parsing to an AST generated from ASDL), the compiler module of the standard library takes a different approach, with a custom AST description syntax in ast.txt Why aren't the two methods unified. I.e. can't the compiler.ast module be also generated from ASDL, and provide a more unified interface to the real thing ? Eli From fredrik at pythonware.com Thu Jul 24 16:21:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 22:21:34 +0200 Subject: Reading a file In-Reply-To: <73045cca0807241306h370166ebwdd1b12227cef43c2@mail.gmail.com> References: <73045cca0807241306h370166ebwdd1b12227cef43c2@mail.gmail.com> Message-ID: aditya shukla wrote: > I have a text file whose contents are like this:- > > jd|fj|dnv|jd|0.33|c:\\windows\\win32 > shcbsbs|nscsjsj|0.93|hsbcjsnc > > I am trying to read the file like this:- > > >>> x = open("c:\\a.txt","r") > >>> x.read() eh, wouldn't it be easier if you actually read the replies to your last post on this topic? here's an excerpt from the reply you got last time: > Extracting is easy; you can do something like > > data = [] > for line in open("test.txt"): > line = line.split("|") > data.append(float(line[1])) which fetches floating point values from the text file example you posted last time: > 0\9\10\11|0.50|c:\windows\apppatch/AcLayers.dll > 0\9\10\11|0.50|c:\windows\apppatch/AcRedir.dll > 0\9\10|0.66|c:\windows\apppatch/AcSpecfc.dll > 0\9|0.83|c:\windows\apppatch/iebrshim.dll if the values have moved to some other column, adjust line[1] accordingly. From karthikbalaguru79 at gmail.com Wed Jul 23 04:19:48 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Wed, 23 Jul 2008 01:19:48 -0700 (PDT) Subject: Strange problem .... Message-ID: <12fd8ef1-c7e0-470b-ba51-f946d8ea8e26@z6g2000pre.googlegroups.com> Hi, I am new to python, Kindly suggest to resolve a problem with a python file. What does the below error refer to ? I use Redhat 9.0, python-2.2.2-26, python-devel-2.2.2-26 and db4-4.0.14-20. [root at localhost processor]# Analyzer processorcycle /usr/local/SDK/bin/../core/bin/processorlib.py:8 8: Warning: 'yield' will become a reserved keyword in the future Traceback (most recent call last): File "/usr/local/SDK/bin/Analyzer", line 48, in ? from debuglib import ProcessorInfo File "/usr/local/SDK/bin/../core/bin/processorlib.py", line 88 yield ProcessorObjectInfo(child, self.pt) ^ SyntaxError: invalid syntax Is this error related with the version of python / python-devel that i use . Any ideas / tips ? Thx in advans, Karthik Balaguru From jarausch at skynet.be Tue Jul 15 11:39:39 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 15 Jul 2008 17:39:39 +0200 Subject: Python internals question In-Reply-To: References: Message-ID: <487cc4bb$0$2855$ba620e4c@news.skynet.be> Peter Anderson wrote: > Hi! I am slowly teaching myself Python. I was reading David Beazley's > excellent book "Python - Essential Reference"; in particular about > variables. Let me quote: > > "Python is a dynamically typed language in which names can represent > values of different types during the execution of a program. In fact the > names used in the program are really just labels for various quantities > and objects. The assignment operator simply creates an association > between a name and a value. This is different from C, for example, in > which a name (variable) represents a fixed size and location in memory..." > > As an old mainframe programmer, I understand the way C does things with > variable but this text got me wondering how Python handles this > "association" between variable name and value at the lower level. Is it > like a fifo list? > > If there is any Python guru that can help I would be most interested in > your thoughts. > Please have a look at http://effbot.org/zone/call-by-object.htm and http://rg03.wordpress.com/2007/04/21/semantics-of-python-variable-names-from-a-c-perspective/ -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From pladow at gmail.com Tue Jul 1 17:49:23 2008 From: pladow at gmail.com (PlayDough) Date: Tue, 1 Jul 2008 14:49:23 -0700 (PDT) Subject: AttributeError with embedded Python Message-ID: <67f2b99f-2f9b-48b9-bb38-7f47c9097df6@e53g2000hsa.googlegroups.com> I've embedded Python in an extension for a program we are using here at work. And I'm a bit stumped as to why I am getting an AttributeError only in the embedded Python. First, a bit of what I am doing. We use a simulator for a microprocessor we are using in our systems. Our simulator allows for extensions that can be loaded as shared libraries. Rather than code the entire extension in C/C++, I would like to make use of Python to script the extension. So, I first initialize Python (examples below leave out the error checking, but it is there): Py_Initialize(); And then I make sure the script directory is in the path with Py_GetPath() and PySys_SetPath(). Finally, I import the script (say it is in a local file 'script.py'): pName = PyString_FromString("script"); pModule = PyImport_Import(pName); Once the module is imported, I get objects to the functions in the script I want to call later, which I do with: pName = PyString_FromString("foo"); pFunc = PyObject_GetAttr(pModule, pName); Later, I come back and call the function: pResult = PyObject_CallObject(pFunc, NULL); And it always fails whenever I iterate of a list. Say for example my Python function is: def foo(): a = ['cat', 'window', 'defenstrate'] for x in a: print x, len(x) Now, the function runs, i.e. I see the output ("cat 3\nwindow 6\ndefenstrate 11\n"), but I always get the following error message: Traceback (most recent call last): File "./script.py", line 3, in foo for x in a: AttributeError: 'module' object has no attribute 'reset' Now, if I run this exact same script using Python standalone, i.e.: Python 2.3.4 (#1, Nov 20 2007, 15:18:15) [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import script >>> script.foo() cat 3 window 6 defenstrate 11 >>> (I know, and old version of Python. But we are stuck with it because our processes require us to validate a newer version if we change.) This works great. What is the difference? Why does it work in one context but not the other? Thanks, Pete From tjreedy at udel.edu Thu Jul 17 15:42:38 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jul 2008 15:42:38 -0400 Subject: % sign in python? In-Reply-To: References: Message-ID: korean_dave wrote: > What does this operator do? Specifically in this context > > test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) > > (Tried googling and searching, but the "%" gets interpreted as an > operation and distorts the search results) Having seen a number of comments like this over the years (about the difficulty of searching for symbol meanings), I just started, last night, a symbol index listing nearly all Python syntax uses of non-alpha-or-digit ascii symbols. When I finish and upload it somewhere, I will post an announcement with the link. tjr From cito at online.de Sat Jul 12 11:09:15 2008 From: cito at online.de (Christoph Zwerschke) Date: Sat, 12 Jul 2008 17:09:15 +0200 Subject: strip() using strings instead of chars In-Reply-To: References: Message-ID: Duncan Booth schrieb: >> if url.startswith('http://'): >> url = url[7:] > > If I came across this code I'd want to know why they weren't using > urlparse.urlsplit()... Right, such code can have a smell since in the case of urls, file names, config options etc. there are specialized functions available. But I'm not sure whether the need for removing string prefix/suffixes in general is really so rare that we shouldn't worry to offer a simpler solution. -- Christoph From JordanNealBerg at gmail.com Thu Jul 10 16:26:28 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Thu, 10 Jul 2008 13:26:28 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: <8feab8ce-1e09-4438-b00a-3b31956c56af@k37g2000hsf.googlegroups.com> <5c521979-aaf0-4b4b-9673-671a978d050a@j22g2000hsf.googlegroups.com> <3hqc74lhdkdqrjb20h34k6ab65g2hc8ucp@4ax.com> Message-ID: On Jul 10, 4:04?pm, Harald Luessen wrote: > On Thu, 10 Jul 2008 Jordan wrote: > > > > >On Jul 10, 1:35?pm, MRAB wrote: > >> On Jul 10, 4:56?am, Jordan wrote: > > >> > I am trying to rewrite some C source code for a poker hand evaluator > >> > in Python. ?Putting aside all of the comments such as just using the C > >> > code, or using SWIG, etc. ?I have been having problems with my Python > >> > code not responding the same way as the C version. > > >> > C verison: > > >> > unsigned find_fast(unsigned u) > >> > { > >> > ? ? unsigned a, b, r; > >> > ? ? u += 0xe91aaa35; > >> > ? ? u ^= u >> 16; > >> > ? ? u += u << 8; > >> > ? ? u ^= u >> 4; > >> > ? ? b ?= (u >> 8) & 0x1ff; > >> > ? ? a ?= (u + (u << 2)) >> 19; > >> > ? ? r ?= a ^ hash_adjust[b]; > >> > ? ? return r; > > >> > } > > >> > my version (Python, hopefully ;)): > > >> > def find_fast(u): > >> > ? ? u += 0xe91aaa35 > >> > ? ? u ^= u >> 16 > >> > ? ? u += u << 8 > >> > ? ? u ^= u >> 4 > >> > ? ? b ?= (u >> 8) & 0x1ff > >> > ? ? a ?= (u + (u << 2)) >> 19 > >> > ? ? r ?= a ^ hash_adjust[b] > >> > ? ? return r > > >> > As far as I understand the unsigned instructions in C just increase > >> > amount of bytes the int can hold, and Python automatically converts to > >> > longs which have infinite size when necessary, so I am not sure why I > >> > am getting different results. > > >> > I assume that I am missing something fairly simple here, so help a > >> > n00b out if you can :) > > >> > Thanks in advance, > > >> > jnb > > >> You want to restrict the values to 32 bits. The result of + or << may > >> exceed 32 bits, so you need to mask off the excess bits afterwards. > > >> def find_fast(u): > >> ? ? mask = 0xffffffff > >> ? ? u ?= (u + 0xe91aaa35) & mask > >> ? ? u ^= u >> 16 > >> ? ? u ?= (u + (u << 8)) & mask # can get away with only 1 mask here > >> ? ? u ^= u >> 4 > >> ? ? b ?= (u >> 8) & 0x1ff > >> ? ? a ?= ((u + (u << 2)) & mask) >> 19 # can get away with only 1 mask > >> here > >> ? ? r ?= a ^ hash_adjust[b] > >> ? ? return r > > >> HTH > > >Well, I guess there are two problems....the masking and the fact the > >in C it seems to for some reason overflow and become a negative > >value....still not sure why it does it....So the code with just > >masking doesn't work, you still need some sort of weird inversion like > >the ~(0xFFFFFFFF - u).....weird > > >anyone? > > In C unsigned can not be negative. Why do you believe > the numbers are negative? If your debugger is telling > you this thow away the debugger and use printf. > If printf is telling you this then use the right format. > printf("%u", u); // for unsigned int u > printf("%lu", u); // for unsigned long u > printf("%x", u); > or > printf("0x%08x", u); // to see u in hex > > Harald haha....I was using printf, but for some reason I decided not to use %u...hmm...looking back over things now... From mrkafk at gmail.com Wed Jul 23 08:14:00 2008 From: mrkafk at gmail.com (mk) Date: Wed, 23 Jul 2008 14:14:00 +0200 Subject: Python Written in C? In-Reply-To: References: Message-ID: > Actually, all of the compilers I'm familiar with (gcc and a > handful of cross compilers for various microprocessors) > translate from high-level languages (e.g. C, C++) into > assembly, which is then assembled into relocatable object > files, which are then linked/loaded to produce machine > language. Doesn't g++ translate C++ into C and then compile C? Last I heard, most C++ compilers were doing that. From larry.bates at websafe.com` Mon Jul 14 18:22:50 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 14 Jul 2008 17:22:50 -0500 Subject: Is it possible to create "network conneciton" on windows system? In-Reply-To: References: Message-ID: Evan wrote: > Hello, > > one of my PC is window system, and in "control panel -> Network > Connections", I can see some network connections such as PPPOE or VPN > which I created by click "create a new connection". > > My question is, is it possible to create a new connection by using > Python script? which means I do not want to use Window UI (via > "control panel"), if it is possible, I can save so many time to > create various network connection when I want to do testing in the > lab. > > Thanks very much. > Evan It is very likely that it is possible to do this. Most control panel applications store the results of their GUI setup in the registry. If you can determine what registry keys have been added/changed. Here is an open source registry compare utility that might help: https://sourceforge.net/projects/regshot You can then use the _winreg module to make such changes on a new machine. HTH, Larry From wuwei23 at gmail.com Sun Jul 27 23:38:26 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 27 Jul 2008 20:38:26 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> <6a5506b1-632e-4bf6-b0ce-4d51d1751aa9@i24g2000prf.googlegroups.com> <8b4b11c3-e306-4fe7-82d1-0a948c725f2f@r15g2000prd.googlegroups.com> Message-ID: <239a084f-b73d-4c20-aaaf-bbd05d452638@a2g2000prm.googlegroups.com> On Jul 28, 4:59?am, "Russ P." wrote: > On Jul 27, 3:11 am, alex23 wrote: > > > On Jul 27, 4:26 pm, "Russ P." wrote: > > > > On Jul 26, 11:18 pm, Terry Reedy wrote: > > > > The use of '.' has been suggested before and rejected. > > > > Where and why? > > > Google is your friend:http://mail.python.org/pipermail/python-3000/2006-April/000793.html > > What Guido rejected there is most certainly *not* > what I suggested. I agree with Guido on that one. Orly? Ian Bicking wrote: "I propose that the self argument be removed from method definitions." Philip Eby suggested: > def .aMethod(arg1, arg2): > return .otherMethod(arg1*2+arg2) Guido shot them all down by stating: > [Y]ou're proposing to hide a > fundamental truth in Python, that methods are "just" functions whose > first argument can be supplied using syntactic sugar Any more reading comprehension we can do for you? From bdesth.quelquechose at free.quelquepart.fr Mon Jul 28 14:39:53 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Jul 2008 20:39:53 +0200 Subject: multiple inheritance and __getattr__ In-Reply-To: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> References: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> Message-ID: <488e2e70$0$29472$426a74cc@news.free.fr> Enrico a ?crit : > Hi there, > I have the following situation (I tryed to minimize the code to concentrate > on the issue): > >>>> class A(object): > def __getattr__(self, name): > print 'A.__getattr__' > if name == 'a': return 1 > raise AttributeError('%s not found in A' % name) > >>>> class B(object): > def __getattr__(self, name): > print 'B.__getattr__' > if name == 'b': return 1 > raise AttributeError('%s not found in B' % name) > > Both classes have a __getattr__ method. > Now I want to have a class that inherits from both so I write: > >>>> class C(B,A): > pass > > The problem arise when I try something like this: >>>> c=C() >>>> c.a > A.__getattr__ > 1 >>>> c.b > A.__getattr__ > > Traceback (most recent call last): > File "", line 1, in > c.b > File "", line 5, in __getattr__ > raise AttributeError('%s not found in A' % name) > AttributeError: b not found in A That's what I would have expected. > I was expecting, after a fail in A.__getattr__, a call to the __getattr__ > method of B but it seems that after A.__getattr__ fails the exception stops > the flow. Indeed. You explicitely raise, so the lookup stops here. You'd need to explicitely call on superclass instead to have B.__getattr__ called, ie: class A(object): def __getattr__(self, name): if name == 'a': return 1 return super(A, self).__getattr__(name) class B(object): def __getattr__(self, name): if name == 'b': return 2 return super(B, self).__getattr__(name) class C(A, B): pass c = C() c.a => 1 c.b => 2 > So, if I did understand well, B.__getattr__ will be never called > "automatically". I don't know if this has a reason, if it is a design choice > or what else, any explanation is welcome. > > Since A and B are not written by me I can only work on C. Really ? You know, Python is a *very* dynamic language. If A and B are ordinary Python classes (ie: not builtin types, not C extensions, etc), you can monkeypatch them. But that's not necessarily the best thing to do (it would require more work than your actual solution). > The solution that > comes to my mind is to define a __getattr__ also in C and write something > like: > >>>> class C(A,B): > def __getattr__(self, name): > try: > return A.__getattr__(self, name) > except AttributeError: > return B.__getattr__(self, name) or more generically: class C(A, B): def __getattr__(self, name): for cls in type(self).__mro__[1:]: try: return cls.__getattr__(self, name) except AttributeError: pass else: raise AttributeError('blah blah') You could also override __getattribute__, but then again, this wouldn't be better (more code, and possible performances loss). > A better solution is welcome. If you don't have commit rights on the module(s) defining A and B, then your solution is probably the simplest thing to do. From gagsl-py2 at yahoo.com.ar Wed Jul 30 00:46:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 01:46:02 -0300 Subject: Windows Interpreter References: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> <488F1745.4020705@timgolden.me.uk> <4dc0cfea0807290626p4b05376en49ccb18f0e1eb4bb@mail.gmail.com> <488F1DB3.4010608@timgolden.me.uk> Message-ID: En Tue, 29 Jul 2008 17:00:40 -0300, Terry Reedy escribi?: > I just found the QuickEdit option. While in an administrator account > (if Python is installed for all users), bring up the menu as specified > above, select Properties instead, then the Options tab, then select > QuickEdit on the right. When clicking OK, being admin allows > modification of the shortcut and not just the current window. > > Learn something new every day. Thanks. Just as a side note, setting QuickEdit on by default is not as good idea as it may appear. If you click or drag accidentally with the mouse over the console, the running program is blocked indefinitely (waiting for the selection to be completed; someone has to press ). Not very nice if you launched a long process and are waiting for it to finish... -- Gabriel Genellina From martin at v.loewis.de Sun Jul 13 13:31:57 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jul 2008 19:31:57 +0200 Subject: heapq question In-Reply-To: References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> Message-ID: <487a3c0d$0$32256$9b622d9e@news.freenet.de> > I understand that heapq is not that efficient to implement timeouts as > I thought at first. > It would have been perfect if there were functions to remove arbitrary > elements withouth needing to re-heapify() the heap every time. It is efficient for that - you just need to use it correctly. To remove the nth element from a heap, replace it with the last element, and then _siftup that element: def remove_at_index_n(heap, n): if n == len(heap)-1: return heap.pop() result = heap[n] heap[n] = heap.pop() heapq._siftup(heap, n) return result The time complexity for that operation is O(log(len(heap))). HTH, Martin From s0suk3 at gmail.com Tue Jul 1 21:31:47 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Tue, 1 Jul 2008 18:31:47 -0700 (PDT) Subject: raw_input into Tkinter ? References: <634e2b50-45ba-4b93-89b4-0afd739adaf3@z66g2000hsc.googlegroups.com> Message-ID: On Jun 30, 11:55 am, jamitwi... at gmail.com wrote: > Is there any way to type into a Tkinter frame window? > I want to use raw_input() within a Tkinter frame. import sys import Tkinter import cStringIO class GUIInputMgr(Tkinter.Entry): def __init__(self, parent): Tkinter.Entry.__init__(self, parent) sys.stdin = cStringIO.StringIO() self.bind("", self.__UpdateBuffer) def __UpdateBuffer(self, event): sys.stdin.truncate(0) sys.stdin.write(self.get()) entry = GUIInputMgr(top) # top is your Tk() instance entry.pack() raw_input() # should now get you user input :) Sebastian From bruno.42.desthuilliers at websiteburo.invalid Fri Jul 4 08:34:34 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 04 Jul 2008 14:34:34 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <486e17b2$0$12609$426a74cc@news.free.fr> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <486e17b2$0$12609$426a74cc@news.free.fr> Message-ID: <486e18c9$0$12609$426a74cc@news.free.fr> Bruno Desthuilliers a ?crit : > Henning_Thornblad a ?crit : >> What can be the cause of the large difference between re.search and >> grep? >> >> This script takes about 5 min to run on my computer: >> #!/usr/bin/env python >> import re >> >> row="" >> for a in range(156000): >> row+="a" >> print re.search('[^ "=]*/',row) >> >> >> While doing a simple grep: >> grep '[^ "=]*/' input (input contains 156.000 a in >> one row) >> doesn't even take a second. >> >> Is this a bug in python? > > Please re-read carefully your python code. Don't you think there's a > subtle difference between reading a file and buildin 156000 string > objects ? > Mmm... This set aside, after testing it (building the string in a somewhat more efficient way), the call to re.search effectively takes ages to return. Please forget my previous post. From hitechpundir at gmail.com Mon Jul 21 09:19:49 2008 From: hitechpundir at gmail.com (hitechpundir at gmail.com) Date: Mon, 21 Jul 2008 06:19:49 -0700 (PDT) Subject: how to create GUI dynamically Message-ID: <84f144db-0d6c-44d5-a1ef-6e7778304c2a@r66g2000hsg.googlegroups.com> Hi; i m working on a project where i need run time creation of GUI. i have some no. of entities for which i want checkboxes in front of them which can be checked/ unchecked by user. But the problem is that the number and name of entities is not fixed and it depends on the file which is used as input. So is there any way to tackle this problem. By the way ; i use Boa constructor (zope editor) for GUI now. regards pawan pundir From circularfunc at gmail.com Thu Jul 10 09:27:10 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 10 Jul 2008 06:27:10 -0700 (PDT) Subject: Weird lambda rebinding/reassignment without me doing it Message-ID: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> I am never redefining the or reassigning the list when using validate but since it spits the modified list back out that somehow means that the modified list is part of the environment and not the old one. i thought what happend inside a function stays inside a function meaning what comes out is independent of what comes in. Meaning if I want the list I send as a parameter to the function I have to do x = func(x) and not just func(x) and x is magically what comes out of func(). Doesnt Python have closure or that isnt what this is about? def validate(placed): student = round(random.random()*401) if student in placed: return validate(placed) else: placed.append(student) return student, placed def val(placed): student = round(random.random()*401) if student in placed: return validate(placed) else: placed.append(student) return student >>> g = lambda x:validate(x) >>> l=[] >>> for x in range(1,10): g(l) (141.0, [141.0]) (19.0, [141.0, 19.0]) (86.0, [141.0, 19.0, 86.0]) (120.0, [141.0, 19.0, 86.0, 120.0]) (76.0, [141.0, 19.0, 86.0, 120.0, 76.0]) (262.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0]) (234.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0]) (74.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0]) (325.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0, 325.0]) >>> g = lambda x:val(x) >>> l=[] >>> for x in range(1,10): g(l) 183.0 33.0 315.0 244.0 308.0 168.0 146.0 378.0 297.0 >>> From denis.kasak2718281828 at gmail.com Sat Jul 12 03:13:05 2008 From: denis.kasak2718281828 at gmail.com (Denis Kasak) Date: Sat, 12 Jul 2008 09:13:05 +0200 Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: Peter Otten wrote: > Denis Kasak wrote: > >> Basically, it reverses the list in place, so it modifies the list which >> called it. It does not return a /new/ list which is a reversed version >> of the original, as you expected it to. Since it doesn't return anything >> explicitly, Python makes it return None. Hence, the comparison you are >> doing is between the original list and a None, which is False, naturally. >> Try this: >> >> spam = ['a', 'n', 'n', 'a'] >> eggs = spam[:] >> if spam.reverse() == eggs: >> print "Palindrome" > > Your explanation is correct, but your example code compares None to > ['a', 'n', 'n', 'a'] and therefore won't print "Palindrome", either. Of course. Thank you for the correction. I guess you know your caffeine has started to wear off when you start making the same mistakes you were trying to fix. :-) -- Denis Kasak From mrkafk at gmail.com Mon Jul 21 13:59:11 2008 From: mrkafk at gmail.com (mk) Date: Mon, 21 Jul 2008 19:59:11 +0200 Subject: calling source command within python In-Reply-To: References: Message-ID: Jie wrote: > Hi all, > > i'm having trouble executing os.system('source .bashrc') command > within python, it always says that source not found and stuff. Any > clue? It _might_ be that the shell it fires up is /bin/sh and this in turn is not bash. Anyway, it's better to use subprocess / Popen for this sort of operation. From gary at byoteki.com Sun Jul 27 01:41:08 2008 From: gary at byoteki.com (Gary Josack) Date: Sun, 27 Jul 2008 01:41:08 -0400 Subject: Simple Path issues In-Reply-To: <6093d9df-d68d-43e7-90d4-44f964529299@m3g2000hsc.googlegroups.com> References: <7bef6df9-45d6-4ef6-b802-1dd201ec66e3@k30g2000hse.googlegroups.com> <6093d9df-d68d-43e7-90d4-44f964529299@m3g2000hsc.googlegroups.com> Message-ID: <488C0A74.10908@byoteki.com> Brett Ritter wrote: > On Jul 26, 2:57 pm, Gary Josack wrote: > >> sys.path is a list that will tell you where python is looking. You can >> append to this in your scripts to have python look in a specific >> directory for your own modules. >> > > I can, but that is almost certainly not the standard way to develop a > module. > > I see nothing in sys.path that I have write permissions to. > > Is altering my PYTHONPATH the normal way to develop (under the > assumption that later users will install in their conventional python > search path)? > > -- > http://mail.python.org/mailman/listinfo/python-list > If you plan to put your module in a non-standard location then your only options are adding to sys.path in you program or setting PYTHONPATH. If this is only for development then you're better off just using PYTHONPATH with the assumption "users will install in their conventional python search path". From mail at timgolden.me.uk Thu Jul 24 11:45:42 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 24 Jul 2008 16:45:42 +0100 Subject: Python / PAMIE In-Reply-To: <9e077ec9-9a07-4a3a-b5dc-bfd593162350@8g2000hse.googlegroups.com> References: <9e077ec9-9a07-4a3a-b5dc-bfd593162350@8g2000hse.googlegroups.com> Message-ID: <4888A3A6.7010801@timgolden.me.uk> frankrentef wrote: > THNX for your response. Based on the authors code it's very simple. > > from cPAMIE import PAMIE > ie=PAMIE () > > #ie.navigate ("google.com") > > #ie.linkClick > #ie.textBoxSet > #ie.writeScript > > ie.navigate ('https://login.yahoo.com/config/mail?.intl=us') > #ie.scriptWrite () > > ie.scriptWrite() > > > Below is the error I get... > > File "C:\Python24\lib\site-packages\cPAMIE.py", line 1837, in > scriptWrite > nameProp = getattr(x,"nameProp") > File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", > line 500, in __getattr__ > raise AttributeError, "%s.%s" % (self._username_, attr) > AttributeError: .nameProp I'm afraid I'm no IE expert (read: never use it if I can avoid it) but I suspect here a combination of slightly flaky code in the Python module plus, maybe, a change in the IE dom object model. If you change lines 1832-1836 of cPAMIE.py to be as follows: for j in range(doc.length): x = doc[j] etype = getattr(x,"type", "") name = getattr(x,"name", "") nameProp = getattr(x,"nameProp", "") then at least some kind of output is produced. But I'm not entirely sure what this function is trying to achieve so I don't guarantee it's doing the right thing yet. TJG From stefan_ml at behnel.de Wed Jul 30 16:51:16 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 30 Jul 2008 22:51:16 +0200 Subject: Python parsing iTunes XML/COM In-Reply-To: References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Message-ID: <4890d444$0$12943$9b4e6d93@newsspool2.arcor-online.net> william tanksley wrote: > Okay, so you decode to go from raw > byes into a given encoding, and you encode to go from a given encoding > to raw bytes. No, decoding goes from a byte sequence to a Unicode string and encoding goes from a Unicode string to a byte sequence. Unicode is not an encoding. A Unicode string is a character sequence, not a byte sequence. Stefan From steve at REMOVE-THIS-cybersource.com.au Sun Jul 27 06:15:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Jul 2008 10:15:31 GMT Subject: Confounded by Python objects References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> <5ddae1dd-c7dd-4f04-84f6-ad71c3282c92@j7g2000prm.googlegroups.com> <6f1a6uF9ctsmU1@mid.uni-berlin.de> Message-ID: <009c464f$0$20302$c3e8da3@news.astraweb.com> On Sat, 26 Jul 2008 18:54:22 +0000, Robert Latest wrote: > Here's an interesting side note: After fixing my "Channel" thingy the > whole project behaved as expected. But there was an interesting hitch. > The main part revolves around another class, "Sequence", which has a > list of Channels as attribute. I was curious about the performance of my > script, because eventually this construct is supposed to handle > megabytes of data. So I wrote a simple loop that creates a new Sequence, > fills all the Channels with data, and repeats. > > Interistingly, the first couple of dozens iterations went satisfactorily > quickly (took about 1 second total), but after a hundred or so times it > got really slow -- like a couple of seconds per iteration. > > Playing around with the code, not really knowing what to do, I found > that in the "Sequence" class I had again erroneously declared a > class-level attribute -- rather harmlessly, just a string, that got > assigned to once in each iteration on object creation. > > After I had deleted that, the loop went blindingly fast without slowing > down. > > What's the mechanics behind this behavior? Without actually seeing the code, it's difficult to be sure, but my guess is that you were accidentally doing repeated string concatenation. This can be very slow. In general, anything that looks like this: s = '' for i in range(10000): # or any big number s = s + 'another string' can be slow. Very slow. The preferred way is to build a list of substrings, then put them together in one go. L = [] for i in range(10000): L.append('another string') s = ''.join(L) It's harder to stumble across the slow behaviour these days, as Python 2.4 introduced an optimization that, under some circumstances, makes string concatenation almost as fast as using join(). But be warned: join() is still the recommended approach. Don't count on this optimization to save you from slow code. If you want to see just how slow repeated concatenation is compared to joining, try this: >>> import timeit >>> t1 = timeit.Timer('for i in xrange(1000): x=x+str(i)+"a"', 'x=""') >>> t2 = timeit.Timer('"".join(str(i)+"a" for i in xrange(1000))', '') >>> >>> t1.repeat(number=30) [0.8506159782409668, 0.80239105224609375, 0.73254203796386719] >>> t2.repeat(number=30) [0.052678108215332031, 0.052067995071411133, 0.052803993225097656] Concatenation is more than ten times slower in the example above, but it gets worse: >>> t1.repeat(number=40) [1.5138671398162842, 1.5060651302337646, 1.5035550594329834] >>> t2.repeat(number=40) [0.072292804718017578, 0.070636987686157227, 0.070624113082885742] And even worse: >>> t1.repeat(number=50) [2.7190279960632324, 2.6910948753356934, 2.7089321613311768] >>> t2.repeat(number=50) [0.087616920471191406, 0.088094949722290039, 0.087819099426269531] -- Steven From ethan at stoneleaf.us Thu Jul 31 00:13:07 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 30 Jul 2008 20:13:07 -0800 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> Message-ID: <48913BD3.9000708@stoneleaf.us> Carl Banks wrote: > On Jul 30, 4:49 am, Ethan Furman wrote: >> Even for those that did realize, and in fact hoped that that is what you >> were attempting to accomplish, > > I was not attempting to accomplish what you think I was. > > I was looking for it, but I didn't want to see it. I didn't expect to > see it. I wanted to show that "if x" doesn't have the polymorphic > advantage people mindlessly claim it does by posing the challenge and > having people fail to meet it, and for the most part the examples that > met the challenge were for minor usages. Ok, someone wrote a filter > that truly benefits from polymorphism of "if x" against very different > types, but really, these use cases aren't all that common. > > It's not like it's an everyday thing for you to write "if x" instead > of "if x!=0", and that it actually saves you from having to rewrite > the condition because later you decided to use a list. Actually, I use this construction a lot. But everybody has their own style, and I'm certainly not going to tell you yours is wrong. One of the fellows that works for me *loves* the (result if false, result if true)[condition] style of immediate if's -- it's one of the first things he learned about when studying Python, and he grins every time he talks about it; *I* know it's not the best way to do it, and that it has it's own set of gotchas -- so I made sure he was also aware of them, and uses them where and when they won't blow up in our faces. > So I stand by the point I was trying to make: for your average day-to- > day programming, the main benefit of "if x" is to save keystrokes. It > doesn't help your code become more polymophic in practice. A little > more polymorphic, yes. A lot, no. [snippitysnipsnip] > Carl Banks Hmmm... well, I see your point. Unfortunately, even though it feels incorrect to me, I do not (yet) have the breadth and depth of Python experience to come up with an example that would display such exquisite polymorphism. It also seems to me that such an example would be non-trivial in nature. Perhaps starting a new thread with this challenge, and adequate time (couple weeks at least, I would think) would net you the smoking gun you were after. At any rate, from my point of view, I like it. I like the visual clarity and simplistic nature of "if x" -- it tells me "if x is something", and I trust myself enough to know what I can do with the something that is x. I also expect anyone else passing me a something to know it has the appropriate interface to work with my code. ~Ethan~ From pythonnutter at gmail.com Sat Jul 19 23:54:08 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Sun, 20 Jul 2008 13:54:08 +1000 Subject: Best Python packages? In-Reply-To: <86b446d2-0d11-4410-bf89-a2a05fac81b2@s50g2000hsb.googlegroups.com> References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> <17861f55-8ad1-4703-ad22-838675f2afc4@w1g2000prk.googlegroups.com> <86b446d2-0d11-4410-bf89-a2a05fac81b2@s50g2000hsb.googlegroups.com> Message-ID: I think the hidden gems in multimedia/game production are Pyglet and Rabbyt. Whereas PyGame is the older api, its large and bloated and has of course a heavy dependency on SDL. Pyglet and Rabbyt are lightweight, efficient, have some amazing functions and hit native OpenGL in all the major OS distributions and Bruce The Presentation Tool utilizes the former to take on MS PowerPoint to show what you can do besides games =) Pyglet: http://pyglet.org/ Rabbyt: http://matthewmarshall.org/projects/rabbyt/ Bruce The Presentation Tool: http://code.google.com/p/bruce-tpt/ Cheers, PN > > In the original post you asked for "hidden gems" and now it seems you > just want to know about Madonna or Justin Timberlake. > > Maybe a look on this collection helps > > http://wiki.python.org/moin/UsefulModules > -- > http://mail.python.org/mailman/listinfo/python-list > From musiccomposition at gmail.com Thu Jul 10 18:54:27 2008 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 10 Jul 2008 15:54:27 -0700 (PDT) Subject: using Python's AST generator for other languages References: Message-ID: <6d31532b-9946-42a3-a20b-56c403a388b2@l42g2000hsc.googlegroups.com> On Jul 10, 12:40 pm, eliben wrote: > Hello, > > I'm building a parser in Python, and while pondering on the design of > my ASTs had the idea to see what Python uses. I quickly got to the > compiler.ast module, and understood it's automatically generated. So I > went to the source, ast.txt and tools/compiler/astgen.py, where I was > this unexpected message: > > """Generate ast module from specification > > This script generates the ast module from a simple specification, > which makes it easy to accomodate changes in the grammar. This > approach would be quite reasonable if the grammar changed often. > Instead, it is rather complex to generate the appropriate code. And > the Node interface has changed more often than the grammar. > """ > > Now, to me the design of the AST in Python looks quite elegant, > especially from the point of view of the AST's user (using Visitors to > walk the AST). And astgen.py looks like a nice approach to generate > tons of boilerplate code. > So, my questions: > 1) Is the compiler.ast module really employed during the compilation > of Python into .pyc files ? No, the comment refers to the builtin _ast module. The compiler package is a compiler for Python written in Python. > 2) What is the meaning of the comment in astgen.py ? Are the Python > maintainers unhappy with the design of the AST ?3 Node, I think, is talking about a node in the parse tree. (AST is generated from another parse tree.) See PEP 339 for details. > 3) What other approach would be recommended to generate a very > detailed AST hierarchy, if the one in astgen.py is dissapointing ? astgen.py contains things that are specific to writing Python's AST C code. Have a look at spark.py in the Parser dir. It is what astgen.py is based on. > > Thanks in advance > Eli From joshdw4 at gmail.com Wed Jul 30 17:33:37 2008 From: joshdw4 at gmail.com (joshdw4 at gmail.com) Date: Wed, 30 Jul 2008 14:33:37 -0700 (PDT) Subject: Tkinter- Possibly a basic question Message-ID: <59dee72b-3fb6-414b-ab49-33cab8f9c9e8@26g2000hsk.googlegroups.com> I hate to do this, but I've thoroughly exhausted google search. Yes, it's that pesky root window and I have tried withdraw to no avail. I'm assuming this is because of the methods I'm using. I guess my question is two-fold. 1) How do I get rid of that window? 2) Any comments in general? I am just learning python (and coding with classes), so I'm sure there are things I should pound into my head before I learn bad habits. Here's the code. It will eventually be a voltage measurement using an Arduino board. Just a simple plot for now. import Tkinter, time class App(Tkinter.Toplevel): def __init__(self,parent): Tkinter.Toplevel.__init__(self,parent) self.parent = parent self.initialize(parent) def initialize(self,parent): #create a menu self.menu = Tkinter.Menu(self) self.config(menu=self.menu) self.menu.filemenu = Tkinter.Menu(self.menu) self.menu.add_cascade(label="File", menu=self.menu.filemenu) #for later use #self.menu.filemenu.add_separator() self.menu.filemenu.add_command(label="Exit", command=self.kill) self.menu.helpmenu = Tkinter.Menu(self.menu) self.menu.add_cascade(label="Help", menu=self.menu.helpmenu) self.menu.helpmenu.add_command(label="About...", command=self.callback) #plotting canvas creation self.axis = SimplePlot(self,1000,500) #status bar self.status = StatusBar(self) self.resizable(width=Tkinter.FALSE,height=Tkinter.FALSE) def callback(self): #calls the function within status bar to set the new text, uses a tuple self.status.settext("%s %s","This callback","holds a place for now!") def kill(self): self.parent.quit() self.parent.destroy() def plot_data(self,data): self.axis.plot(data) class StatusBar(Tkinter.Frame): #initializes and draws def __init__(self,parent): Tkinter.Frame.__init__(self, parent) self.parent = parent self.label = Tkinter.Label(self.parent, bd=1, relief=Tkinter.SUNKEN, anchor=Tkinter.W,text='None') self.label.pack(fill=Tkinter.X) def settext(self, format,*args): self.label.config(text=format % args) self.label.update_idletasks() def clear(self): self.label.config(text="") self.label.update_idletasks() class SimplePlot(Tkinter.Frame): "Creates a simple plot frame of time<10 and V<5 of pixel size wxh" def __init__(self,parent,w,h): #this line was taken from online... not sure why it works, #but it allows packing outside of this __init__ Tkinter.Frame.__init__(self, parent) self.parent = parent self.canvas = Tkinter.Canvas(parent,width=w,height=h) #frame height in pixels self.canvas.h = h #frame width in pixels self.canvas.w = w self.canvas.pack(fill=Tkinter.X) #draw gridlines self.gridon() def gridon(self): "Draws gridlines on the plot at every 1 unit" for i in range(100,self.canvas.w,100): self.canvas.create_line(i,0,i,self.canvas.h) for i in range(100,self.canvas.h,100): self.canvas.create_line(0,i,self.canvas.w,i) def plot(self, data): "Plots data given as data = [], data.append( (x,y) )" for x, y in data: px = int(x/10*self.canvas.w) py = int(self.canvas.h-y/5*self.canvas.h) self.canvas.create_rectangle((px-1, py-1, px+1, py+1), outline="red") if __name__ == "__main__": root = Tkinter.Tk() root.withdraw() #create main window a = App(root) a.title('Plot') #create a sample data range for testing #data ranges from x=0, y=0 to x=10, y=5 data = [] for i in range(1000): data.append( (float(i)/1000*10,float(i)/1000*5) ) a.plot_data(data) #loop until destroy a.mainloop() From henryar2 at gmail.com Fri Jul 11 11:42:18 2008 From: henryar2 at gmail.com (Henry Read) Date: Fri, 11 Jul 2008 23:42:18 +0800 Subject: Editra In-Reply-To: References: Message-ID: It has been already in wxpython-doc-demos package. On Fri, Jul 11, 2008 at 11:38 PM, Henry Read wrote: > Editra is a multi-platform text editor with an implementation that focuses > on creating an easy to use interface and features that aid in code > development. Currently it supports syntax highlighting and variety of other > useful features for over 60 programming languages. > > Editra is freely available under the terms of the wxWindows Licence. > > > Currently the project is in the alpha development phase but test builds of > "stable" points are available for download and trial as Windows and Mac > OSX(Universal) binaries, currently other Unix and Linux based systems will > have to install from source using the included setup script. Please feel > free give it a try and to report bugs and request features. > > *Editra*.org | News > It is a good editor for Python, also it is small.It can also support auto > completion with Python modules. > It is suitable for Python beginners. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Wed Jul 23 16:30:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 22:30:06 +0200 Subject: fromfile error on windows, not mac In-Reply-To: <50af02ed0807231309p2f7b1333sf45f96a9f082d8f0@mail.gmail.com> References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> <50af02ed0807231309p2f7b1333sf45f96a9f082d8f0@mail.gmail.com> Message-ID: Manu Hack wrote: > by the way, anyone could explain why changing to single quote makes a > difference? > > >>> "rb" == 'rb' > True There's no difference between single quotes and double quotes in Python. My guess is cargo cult debugging. From stefan_ml at behnel.de Fri Jul 25 07:16:02 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 25 Jul 2008 13:16:02 +0200 Subject: lxml, comparing nodes In-Reply-To: References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> <6c91a4da-6443-4570-8dd3-01c4ec169bf3@t54g2000hsg.googlegroups.com> <4888ad28$0$9491$9b4e6d93@newsspool3.arcor-online.net> <4613042f-ed70-4cfa-8de9-a92b4df32923@k36g2000pri.googlegroups.com> <4889B2B1.5030204@behnel.de> Message-ID: <4889B5F2.4090605@behnel.de> code_berzerker wrote: >> Not in your code. >> >> Stefan > > Not sure what you mean, but I tested and so far every document with > the same order of elements had number of comparisons equal to number > of nodes. Sorry, missed the "let2.remove(foundEl)" line. Stefan From aahz at pythoncraft.com Sat Jul 26 11:28:21 2008 From: aahz at pythoncraft.com (Aahz) Date: 26 Jul 2008 08:28:21 -0700 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> Message-ID: In article <5845bf4f-65bf-4a36-b9fe-25cd896b6926 at q28g2000prh.googlegroups.com>, Jordan wrote: > >The point I was trying to make originally was that applying any mantra >dogmatically, including Explicit is better than implicit, can lead to >bad results. Perhaps having Practicality beats purity is enough of a >reminder of that fact for the Python community :-) IMO, you made a big mistake in combining your point with two other meaty issues (whether method definitions should include self and whether != should use __eq__() as a fallback). Moreover, your point is IMO not sufficiently proven (that is, I see little evidence that Python development follows any one point of the Zen of Python dogmatically). You should therefore not be particularly surprised that the discussion has gone sideways to your intentions -- especially when you start with a flamebait Subject: line of "attacking sacred cows"! If solid discussion is your goal, I suggest that you wait a couple of weeks and start over with a brand-new thread. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From giltay at gmail.com Wed Jul 30 10:00:27 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Wed, 30 Jul 2008 07:00:27 -0700 (PDT) Subject: iterating "by twos" References: <70a172ac-0491-4918-9c74-6a577f35068a@d45g2000hsc.googlegroups.com> Message-ID: <0e10dfb8-b1f7-4318-8244-7a0af7021b52@27g2000hsf.googlegroups.com> On Jul 29, 4:11?pm, Erik Max Francis wrote: > gil... at gmail.com wrote: > > for x, y in zip(a, a[1:]): > > ? ? frob(x, y) > > What you meant was this: > > ?>>> [(x, y) for x, y in zip(a[::2], a[1::2])] > [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] > > but this creates three sublists through slicing and zip. ?The use of > islice and izip is better, particularly if the list that's being > iterated over is large. The lists I use it with are generally pretty small (a few thousand items at most) so I decided to go with simple rather than clever. That said, I use it enough that it should become its own function, at which point I'll probably grab something from this thread. Cheers, Geoff G-T From deets at nospam.web.de Wed Jul 9 11:48:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Jul 2008 17:48:00 +0200 Subject: Anyone happen to have optimization hints for this loop? References: <32fd142e-b198-430e-888b-01aee4e63ac0@c65g2000hsa.googlegroups.com> Message-ID: <6dk4v0F311k1U1@mid.uni-berlin.de> dp_pearce wrote: > I have some code that takes data from an Access database and processes > it into text files for another application. At the moment, I am using > a number of loops that are pretty slow. I am not a hugely experienced > python user so I would like to know if I am doing anything > particularly wrong or that can be hugely improved through the use of > another method. > > Currently, all of the values that are to be written to file are pulled > from the database and into a list called "domainVa". These values > represent 3D data and need to be written to text files using line > breaks to seperate 'layers'. I am currently looping through the list > and appending a string, which I then write to file. This list can > regularly contain upwards of half a million values... > > count = 0 > dmntString = "" > for z in range(0, Z): > for y in range(0, Y): > for x in range(0, X): > fraction = domainVa[count] > dmntString += " " > dmntString += fraction > count = count + 1 > dmntString += "\n" > dmntString += "\n" > dmntString += "\n***\n > > dmntFile = open(dmntFilename, 'wt') > dmntFile.write(dmntString) > dmntFile.close() > > I have found that it is currently taking ~3 seconds to build the > string but ~1 second to write the string to file, which seems wrong (I > would normally guess the CPU/Memory would out perform disc writing > speeds). > > Can anyone see a way of speeding this loop up? Perhaps by changing the > data format? Is it wrong to append a string and write once, or should > hold a file open and write at each instance? Don't use in-place adding to concatenate strings. It might lead to quadaratic behavior. Use the "".join()-idiom instead: dmntStrings = [] .... dmntStrings.append("\n") .... dmntFile.write("".join(dmntStrings)) Diez From akathorn at gmail.com Sun Jul 13 22:28:39 2008 From: akathorn at gmail.com (Akathorn Greyhat) Date: Mon, 14 Jul 2008 03:28:39 +0100 Subject: Dictionary bidirectional In-Reply-To: References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> Message-ID: ---------- Forwarded message ---------- From: Akathorn Greyhat Date: 2008/7/14 Subject: Re: Dictionary bidirectional To: Kless 2008/7/14 Kless : I need a dictionary where get the result from a 'key' (on left), but > also from a 'value' (on right), how to get it? > > I know that dictionaries aren't bidirectional, but is there any way > without use two dictionaries? > > > Thanks in advance! > -- > http://mail.python.org/mailman/listinfo/python-list > You could make your own class for that, maybe something like ######### class MyCoolDictionary(dict): def __init__(self, *args, **kargs): dict.__init__(self, *args, **kargs) def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: keys=[] for i in dictio.keys(): if dictio[i]==item: keys.append(i) return keys dictio=MyCoolDictionary({"a" : 1, "b" : 2, "c" : 2}) print dictio["a"] print dictio["b"] print dictio[1] print dictio[2] ######### The output of this code is: 1 2 ['a'] ['c', 'b'] Note that it isn't finish, maybe you'll need to make some kind of test before adding a new value because with this code one value can have multiple keys, and I have fixed it by returning a list of keys instead a single value. It's up to you =) I'm sorry of my poor english =( Regards, Akathorn Greyhat -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Fri Jul 18 19:20:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 18 Jul 2008 16:20:44 -0700 (PDT) Subject: round function error??? References: <2da2f5f1-7ff2-46d7-a768-f0817e414615@f36g2000hsa.googlegroups.com> Message-ID: On Jul 19, 8:05 am, Mark Dickinson wrote: > On Jul 18, 10:17 pm, Anthony wrote: > > > Isn't this a mistake??? > > Which 'this'? That is, what were you expecting? > > If you're objecting to the fact that the second result > produces 3499.3499999999999 instead of 3499.35, then > no, that's not a mistake; see > > http://www.python.org/doc/faq/general/#why-are-floating-point-calcula... > > for more information. But I'm guessing that you're > questioning the fact that a value that's apparently > *less* than 3499.35 is rounded up to 3499.4, rather > than down to 3499.3. ? "apparently" being the operative word. >>> x = 3499.35 >>> repr(x) '3499.3499999999999' >>> float(repr(x)) == x True >>> float(repr(x)) < x False > > Then yes, I'd agree that's less than ideal, though I > don't consider it a particularly serious bug. > It's been on my list of things to fix for a while. I'd suggest adding this to the list of floating point strangenesses in the FAQ and/or the appendix to the tutorial, rather than "fixing" it. > (See http://bugs.python.org/issue1869). The example you give there seems to be somewhat more deserving of a fix. Cheers, John From drakonik at gmail.com Thu Jul 24 22:03:24 2008 From: drakonik at gmail.com (Nick Dumas) Date: Thu, 24 Jul 2008 22:03:24 -0400 Subject: import dll instead of pyd In-Reply-To: <68310600-2efd-4f52-81d7-d0f3b40c7809@h17g2000prg.googlegroups.com> References: <68310600-2efd-4f52-81d7-d0f3b40c7809@h17g2000prg.googlegroups.com> Message-ID: <6O2dnfUikbwXqRTVnZ2dnUVZ_j2dnZ2d@earthlink.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Is this DLL in the same directory as your script? If not, is it part of your pythonpath? If neither are true, then you won't be able to import it, regardless of whether it's a good file or not. jrh wrote: > Hello, > > From previous posts and documentation it seems python should be able > to import a module that is compiled into a .dll just as well as > a .pyd. I have a pyd that works fine, but after renaming it to dll the > import fails. Running python with -vv flag indicates it doesn't > actually look for the dll (see below). Has dll import been defeatured > in python? > > Thanks! > >>>> import _mydllpythonmodule > # trying _mydllpythonmodule.pyd > # trying _mydllpythonmodule.py > # trying _mydllpythonmodule.pyw > # trying _mydllpythonmodule.pyc > # trying C:\Python25\DLLs\_mydllpythonmodule.pyd > # trying C:\Python25\DLLs\_mydllpythonmodule.py > # trying C:\Python25\DLLs\_mydllpythonmodule.pyw > # trying C:\Python25\DLLs\_mydllpythonmodule.pyc > # trying C:\Python25\lib\_mydllpythonmodule.pyd > # trying C:\Python25\lib\_mydllpythonmodule.py > # trying C:\Python25\lib\_mydllpythonmodule.pyw > # trying C:\Python25\lib\_mydllpythonmodule.pyc > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyd > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.py > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyw > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyc > # trying C:\Python25\_mydllpythonmodule.pyd > # trying C:\Python25\_mydllpythonmodule.py > # trying C:\Python25\_mydllpythonmodule.pyw > # trying C:\Python25\_mydllpythonmodule.pyc > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyd > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.py > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyw > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyc > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyd > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.py > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyw > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyc > # trying C:\Python25\lib\site-packages\win32\lib > \_mydllpythonmodule.pyd > # trying C:\Python25\lib\site-packages\win32\lib\_mydllpythonmodule.py > # trying C:\Python25\lib\site-packages\win32\lib > \_mydllpythonmodule.pyw > # trying C:\Python25\lib\site-packages\win32\lib > \_mydllpythonmodule.pyc > # trying C:\Python25\lib\site-packages\Pythonwin > \_mydllpythonmodule.pyd > # trying C:\Python25\lib\site-packages\Pythonwin\_mydllpythonmodule.py > # trying C:\Python25\lib\site-packages\Pythonwin > \_mydllpythonmodule.pyw > # trying C:\Python25\lib\site-packages\Pythonwin > \_mydllpythonmodule.pyc > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named _mydllpythonmodule -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkiJNGwACgkQLMI5fndAv9hykgCcDf4cTZU0iDo+ELQ5aFGs9FIO 8GEAn3+egrPDtNrlbsssqti8YeZXXIeM =q31k -----END PGP SIGNATURE----- From tjreedy at udel.edu Sun Jul 27 21:22:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 21:22:41 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> Message-ID: Russ P. wrote: > When I write a function in which a data member will be used several > times, I usually do something like this: > > data = self.data > > so I can avoid the clutter of repeated use of "self.data". Another reason people do this is for speed, even if self.data is used just once but in a loop. From gherron at islandtraining.com Mon Jul 21 16:44:38 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 21 Jul 2008 13:44:38 -0700 Subject: Converting List of String to Integer In-Reply-To: References: Message-ID: <4884F536.5060307@islandtraining.com> Samir wrote: > On Jul 21, 3:20 pm, Gary Herron wrote: > >> Samir wrote: >> >>> Hi Everyone, >>> >>> I am relatively new to Python so please forgive me for what seems like >>> a basic question. >>> >>> Assume that I have a list, a, composed of nested lists with string >>> representations of integers, such that >>> >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] >>> >>> I would like to convert this to a similar list, b, where the values >>> are represented by integers, such as >>> >>> b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] >>> >>> I have unsuccessfully tried the following code: >>> >>> n = [] >>> for k in a: >>> n.append([int(v) for v in k]) >>> print n >>> >>> Does anyone know what I am doing wrong? >>> >>> Thanks in advance. >>> >>> Samir >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> You didn't tell us how it failed for you, so I can't guess what's wrong. >> >> However, your code works for me: >> >> >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] >> >>> n = [] >> >>> for k in a: >> ... n.append([int(v) for v in k]) >> ... >> >>> print n >> [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] >> >> (Although you seem to have confused variables b and n.) >> >> Gary Herron- Hide quoted text - >> >> - Show quoted text - >> > > Hi Gary, > > Thanks for your quick response (and sorry about mixing up b and n). > For some reason, the logic I posted seems to work ok while I'm using > the Python shell, but when used in my code, the program just hangs. > It never outputs the results. Below is the code in its entirety. Is > there a problem with my indendentation? > > Aha. There's the problem, right there in the first line. > a = n = [] > This sets a and n to the *same* empty list. This line creates one empty list and binds both n and a to that list. Note carefully, there is only one empty list here, but it can be accessed under two names Later in your code, for k in a: runs through that list, and n.append(...) append to the end of the same list. Thus the loop never get to the end of the (continually growing) list. Solve it by creating two different empty lists: a = [] n = [] Gary Herron > t = """ > 1 2 > 3 > 4 5 6 > 7 8 9 0 > """ > > d = t.split("\n") > > for x in range(1,len(d)-1): > a.append(d[x].split(" ")) > print a > > for k in a: > n.append([int(v) for v in k]) > > print n > > Thanks again. > > Samir > -- > http://mail.python.org/mailman/listinfo/python-list > From simon at simonwillison.net Wed Jul 30 11:59:16 2008 From: simon at simonwillison.net (Simon Willison) Date: Wed, 30 Jul 2008 08:59:16 -0700 (PDT) Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: <2a703a46-75bc-4228-95d1-05a4e6030b40@f63g2000hsf.googlegroups.com> Message-ID: On Jul 30, 4:43?pm, Paul Boddie wrote: > I can't reproduce this on Python 2.3.6 or 2.4.4 on RHEL 4. Instead, I > get the usual... > > ('CHARACTERS', ) I'm using Python 2.5.1 on OS X Leopard: $ python Python 2.5.1 (r251:54863, Feb 4 2008, 21:48:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin I just tried it out on Python 2.4.2 on an Ubuntu machine and it worked fine! I guess this must be an OS X Python bug. How absolutely infuriating. Thanks, Simon From ggpolo at gmail.com Thu Jul 17 18:18:29 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 17 Jul 2008 19:18:29 -0300 Subject: Using Tcl extensions with Python? In-Reply-To: <6f09cdf7-1156-4f41-af5f-c8e5b99eab2d@b1g2000hsg.googlegroups.com> References: <6f09cdf7-1156-4f41-af5f-c8e5b99eab2d@b1g2000hsg.googlegroups.com> Message-ID: On Thu, Jul 17, 2008 at 6:48 PM, C Martin wrote: > How do you setup a Tcl extension to be accessible through Python? I > understand that I'll have to use native Tcl calls to use it (tk.call() > etc), but I can't figure out where to put the files or how to > initialize them so I can call them. > > The package I would like to use is TkPNG: http://www.muonics.com/FreeStuff/TkPNG/ > You can put them anywhere, but if it is on tcl's auto_path then you just need a call to "package require tkpng". To check what directories are part of auto_path, start tclsh and enter "set auto_path". Follows a sample code to demonstrate how to load the required package: import Tkinter root = Tkinter.Tk() tkpnglib = "/usr/lib/tkpng0.9" root.tk.eval(""" global auto_path lappend auto_path {%s}""" % tkpnglib) root.tk.eval("package require tkpng") If tkpng were installed in some directory belonging to auto_path, then you wouldn't need that call to tk.eval. And.. for tkpng specifically, you won't need tk.call to use it, you just need to create your images using Tkinter.PhotoImage with a "png" type. > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From wuwei23 at gmail.com Tue Jul 15 20:13:24 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 15 Jul 2008 17:13:24 -0700 (PDT) Subject: Suggestion: Python global scope References: Message-ID: Anonymous Bastard wrote: > In Python, declaring a variable using the global statement automatically > makes it available in all subsequent scopes. > > But to me, it makes more sense to use the global statement to 'import' a > variable from the global scope into the current scope. My understanding is that this is exactly what the 'nonlocal' keyword in Python 3.0 provides. http://www.python.org/dev/peps/pep-3104/ From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 12:24:50 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 18:24:50 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <3d56ad67-bcd7-4840-979a-8648292afcff@j7g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <40449826-c71d-4c6e-8b74-13069269e5da@z6g2000pre.googlegroups.com> <488896bf$0$3493$426a74cc@news.free.fr> <3d56ad67-bcd7-4840-979a-8648292afcff@j7g2000prm.googlegroups.com> Message-ID: <4888c8cc$0$7205$426a74cc@news.free.fr> Jordan a ?crit : >> Then why do you write, let me quote: >> >> """ >> (snip) coding __eq__ (snip) buys you >> nothing from the != operator. != isn't (by default) a synonym for the >> negation of == (unlike in, say, every other language ever); not only >> will Python let you make them mean different things, without >> documenting this fact - it actively encourages you to do so. >> """ > > My words aren't as clear as they should be. I mean that Python lets > *you* do something without documenting, or rather stating to use a > better term, that your intention is the non-obvious one. > I'm not > saying that Python itself lacks documentation for its own behaviour; > I'm saying it should force you to make your intentions clear and > visible to someone reading your code when you want to do something non- > obvious. One could then answer than, the behaviour of __eq__ / __ne__ being clearly defined and documented, implementing one without the other - or in such a way that a != b is different from not(a == b) - is by itself an explicit 'statement of intention' !-) (snip strawmens) >> Please understand that I'm not arguing about this particular design >> choice (and FWIW, I'd mostly agree on the point that having a != b >> different from not (a == b) is actually a wart). > > Good, at least we've come to a point in this discussion where I can > firmly agree with somebody. On that concrete case, a priori, yes. wrt/ the 'explicit self', there are in fact two points: 1/ The mandatory use of 'self' to access the current instance. As far as I'm concerned, and *even if there was no other technical reasons*, I wholefully, happily and definitively agree with this choice - specially in a language like Python (it's not quite the same problem with Java where you just can't put anything outside a class). It's truly (and IMHO, of course) a case where explicit-is-better-than-implicit, period. Strange enough, I never heard of anyone complaining about the mandatory use of $this-> in PHP. Nor about the mandatory use of @/@@ in Ruby. Nor about the 'm_whatever' naming convention in C++. Nor about [add your own example here]. 2/ The need to explicitely declare the 'target' object (self or cls) as first param of a 'function-to-be-used-as-method'. Granted, this one may feel a bit "unfinished" at first. And I would not bet my life on it, but I think one could possibly find some "solution" that would not as a side-effect impose any restriction wrt/ the current implementation. OTHO, given 1/, and since the way Python builds "methods" out of just two more general constructs (the def statement and the descriptor protocol) is part of what makes it's object model so powerful, I don't feel like the price to pay to keep the implementation as simple as possible is too high. IOW, while I would not turn down a "solution" like the one mentionned above (let's say -0 as far as I'm concerned), I just don't think it would be worth the time spent. Anyway, "explicit is better than implicit" is not the appropriate dogmatic justification here - but a couple other quotes from the Python's Zen could apply (left as an exercice to the reader) !-) From robert.kern at gmail.com Mon Jul 7 20:09:41 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 07 Jul 2008 19:09:41 -0500 Subject: Python Agile Software Development Tools Screencasts In-Reply-To: <87lk0dwbys.fsf@benfinney.id.au> References: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> <87lk0dwbys.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > percious writes: > >> Hi All, >> >> I started a new series about python on showmedo. Please feel free to >> take a look. > > I'd love to, but showmedo refuses to show presentations to me without > installing non-free software. mplayer works just fine on the .flv's. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From bronger at physik.rwth-aachen.de Sat Jul 26 10:25:18 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 26 Jul 2008 16:25:18 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> Message-ID: <87k5f8afjl.fsf@physik.rwth-aachen.de> Hall?chen! D'Arcy J.M. Cain writes: > On Sat, 26 Jul 2008 09:45:21 +0200 > Torsten Bronger wrote: > >> Of course, "self" would have to become a reserved word. You >> could say that this may break some code, but I don't see much >> freedom > > Isn't this a showstopper all by itself? Yes. But I've seen no code that uses some other word. Emacs' syntax highlighting even treats it as reserved. So I think that other counter-arguments are stronger. The in my opinion strongest one is that automatic insertion of "self" would make Python less verbose but more complicated. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From mdsherry at gmail.com Tue Jul 15 16:39:33 2008 From: mdsherry at gmail.com (mdsherry at gmail.com) Date: Tue, 15 Jul 2008 13:39:33 -0700 (PDT) Subject: bad recursion, still works References: <7bf2bad5-d6b6-4929-a520-a82b7bb49916@34g2000hsf.googlegroups.com> <5be12739-7896-4112-9307-53897af4f691@f63g2000hsf.googlegroups.com> Message-ID: <47c4e651-b102-4ec0-907e-fa4712ae5b51@26g2000hsk.googlegroups.com> On Jul 15, 4:12?pm, iu2 wrote: > On Jul 15, 9:30?pm, mdshe... at gmail.com wrote: > > > > > On Jul 15, 2:59?pm, iu2 wrote: > > > > Hi, > > > > I wrote this wrong recursive function that flattens a list: > > > > def flatten(lst, acc=[]): > > > ? ? #print 'acc =', acc, 'lst =', lst > > > ? ? if type(lst) != list: > > > ? ? ? ? acc.append(lst) > > > ? ? else: > > > ? ? ? ? for item in lst: > > > ? ? ? ? ? ? flatten(item) > > > ? ? return acc > > > > a = [1, 2, [3, 4, 5], [6, [7, 8, [9, 10], 11], 12], 13, 14] > > > b = flatten(a) > > > print b > > > > I was amazed to realize that it flattens the list alright. Why? 'acc' > > > should be an empty list on each invocation of flatten, but is seems to > > > accumulate anyway... > > > When you say acc=[] in the function declaration, it binds acc to a > > particular list object, rather than to a concept of an empty list. > > Thus, all operations being performed on acc are being performed on the > > same list. If, after the sample code you provided, were to call > > > c = flatten([15,16,17,[18,19]]) > > print c > > > you would get back the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, > > 13, 14, 15, 16, 17, 18, 19]. > > > Mark Sherry > > I still don't understand: In each recursive call to flatten, acc > should be bound to a new [], shouldn't it? Why does the binding happen > only on the first call to flatten? Default values are bound when the function is defined, not when it's called. For example, >>> import random >>> def foo(bar = random.random()): ... print bar ... >>> foo() 0.632312549821312 >>> foo() 0.632312549821312 If you view [...] just as shorthand for list(...), it might make a bit more sense. For immutable values, one can't change the value bound to the name, only what the name is bound to, so this behaviour is less obvious. But still there. As to why default values are evaluated at define time vs. call time, I'd argue reasons of scope and speed - if the default value is a computed constant, it makes little sense to recompute it every time the function is called. Mark Sherry From fredrik at pythonware.com Sat Jul 19 14:58:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 19 Jul 2008 20:58:25 +0200 Subject: XML Parsing: Expat Error In-Reply-To: <0FF698F7C0354F42987734704458117F015DD7F0@EVS3.rose-hulman.edu> References: <0FF698F7C0354F42987734704458117F015DD7F0@EVS3.rose-hulman.edu> Message-ID: Gerth, William D wrote: > Hey all, I?m simply trying to get my feet wet with XML parsing, and I > tried to just do something simple with ElementTree, just throw the XML > tags from a file into a list. The code is as follows (and may be wrong): ... > xml.parsers.expat.ExpatError: no element found: line 3, column 0 > > What can I do to fix this, if anything? My overall goal has been to > simply get the text of the XML document into a text file, but even that > has failed (I get naught but gibberish), so any help would be appreciated. your XML file is broken (note that it's the "parse" function that throws this error). From lanny at freshells.ch Wed Jul 23 21:52:10 2008 From: lanny at freshells.ch (Lanny) Date: Wed, 23 Jul 2008 18:52:10 -0700 Subject: os.walk question Message-ID: How would one make a list of the files in the top directory using os.walk. I need to pick a random file from said list. Thanks. -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- From tjreedy at udel.edu Tue Jul 1 15:14:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 01 Jul 2008 15:14:15 -0400 Subject: Implementing an 8 bit fixed point register In-Reply-To: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> References: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> Message-ID: nickooooola wrote: > Hello to all > I'm about to write a simulator for a microcontroller in python > (why python? because I love it!!!) > > but I have a problem. > > The registry of this processor are all 8 bit long (and 10 bit for some > other strange register) > and I need to simulate the fixed point behaviour of the register, > and to access the single bit. In Python3, I would use a (mutable) bytearray. IDLE 3.0b1 >>> reg1 = bytearray((0,)*8) # or *10 for 10 bits >>> reg1 bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00') >>> reg1[1]=1 >>> reg1[1] 1 >>> tuple(reg1) (0, 1, 0, 0, 0, 0, 0, 0) A bytearray subclass could enforce that all 'bits' (stored as bytes) are 0 or 1, have a customized representation to your taste, and add methods like .flipall(). The overhead of using 8 bytes instead of 1 to hold the object value is actually small compared to the minimum object size of 16 bytes (on Win32XP). >>> sys.getsizeof(reg1) 24 In Python2.x, you can use the array module to make equivalent mutable arrays of chars. Terry Jan Reedy From drakonik at gmail.com Fri Jul 18 10:35:12 2008 From: drakonik at gmail.com (Nick Dumas) Date: Fri, 18 Jul 2008 10:35:12 -0400 Subject: Regular expression help In-Reply-To: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> References: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I think you're over-complicating this. I'm assuming that you're going to do a line graph of some sorta, and each new line of the file contains a new set of data. The problem you mentioned with your regex returning a match object rather than a string is because you're simply using a re function that doesn't return strings. re.findall() is what you want. That being said, here is working code to mine data from your file. [code] line = 'c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 mad=-3.597647 3pv=0' energypat = r'\betot=(-?\d*?[.]\d*)' #Note: To change the data grabbed from the line, you can change the #'etot' to 'afrac' or 'emad' or anything that doesn't contain a regex #special character. energypat = re.compile(energypat) re.findall(energypat, line)# returns a STRING containing '-12.020107' [/code] This returns a string, which is easy enough to convert to an int. After that, you can datapoints.append() to your heart's content. Good luck with your work. nclbndk759 at googlemail.com wrote: > Hello, > > I am new to Python, with a background in scientific computing. I'm > trying to write a script that will take a file with lines like > > c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647 > 3pv=0 > > extract the values of afrac and etot and plot them. I'm really > struggling with getting the values of efrac and etot. So far I have > come up with (small snippet of script just to get the energy, etot): > > def get_data_points(filename): > file = open(filename,'r') > data_points = [] > while 1: > line = file.readline() > if not line: break > energy = get_total_energy(line) > data_points.append(energy) > return data_points > > def get_total_energy(line): > rawstr = r"""(?P.*?)=(?P.*?)\s""" > p = re.compile(rawstr) > return p.match(line,5) > > What is being stored in energy is '<_sre.SRE_Match object at > 0x2a955e4ed0>', not '-11.020107'. Why? I've been struggling with > regular expressions for two days now, with no luck. Could someone > please put me out of my misery and give me a clue as to what's going > on? Apologies if it's blindingly obvious or if this question has been > asked and answered before. > > Thanks, > > Nicole -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkiAqiAACgkQLMI5fndAv9h7HgCfU6a7v1nE5iLYcUPbXhC6sfU7 mpkAn1Q/DyOI4Zo7QJhF9zqfqCq6boXv =L2VZ -----END PGP SIGNATURE----- From rocksportrocker at googlemail.com Thu Jul 17 08:04:52 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 17 Jul 2008 05:04:52 -0700 (PDT) Subject: storing references instead of copies in a dictionary References: Message-ID: <19eba037-f7e2-4934-a03b-f1956db8e999@a1g2000hsb.googlegroups.com> On 17 Jul., 13:45, mk wrote: > Hello everyone, > > I'm storing functions in a dictionary (this is basically for cooking up > my own fancy schmancy callback scheme, mainly for learning purpose): > > ?>>> def f2(arg): > ... ? ? return "f2 " + arg > ... > ?>>> > ?>>> def f1(arg): > ... ? ? return "f1" + arg > ... > > ?>>> a={'1': f1, '2': f2} > ?>>> > ?>>> [ x[1](x[0]) for x in a.items() ] > ['f11', 'f2 2'] > > Well, neat. Except if I change function definitions now, old functions > are called. And rightly: > > {'1': , '2': } > ?>>> f1 > > ?>>> > ?>>> def f1(arg): > ... ? ? return "NEW f1 " + arg > ... > ?>>> f1 > > > The address of function f1 has obviously changed on redefinition. > > Storing value copies in a dictionary on assignment is a reasonable > default behaviour. > > However, in this particular case I need to specifically store > _references to objects_ (e.g. f1 function), or should I say _labels_ > (leading to objects)? > > Of course, I can basically update the dictionary with a new function > definition. > > But I wonder, is there not a way _in general_ to specifically store > references to functions/variables/first-class objects instead of copies > in a dictionary? Python stores references in dictionaries and does not copy ! (unless you explicitly use the copy module) ! In your case the entry in the dictionary is a reference to the same object which f1 references, that is the object at 0xb7f0ba04. If you now say "f1=...:" then f1 references a new object at 0xb7f0b994, and the entry in your dictionary still references the "old" object at 0xb7f0ba04. I do not know any method to automatically update your dictionary as there is no possibility to overload the assignement operator "=". But may be somebody can teach me a new trick :-) Greetings, Uwe From cjstuttle at hotmail.com Sat Jul 26 17:16:33 2008 From: cjstuttle at hotmail.com (chris) Date: Sat, 26 Jul 2008 14:16:33 -0700 (PDT) Subject: pixel colour on screen References: Message-ID: <22940391-cf14-4022-8b00-8d7974590072@e39g2000hsf.googlegroups.com> On Jun 30, 4:37?am, Tim Roberts wrote: > cjstut... at hotmail.com wrote: > > >Could anyone help me, I'm a python noob and need some help. im trying > >to find some code that will, given ascreenco-ordinate, will give me > >thecolourof thatpixelin RGB. i have found a lot about getting the > >pixelcolourfrom a picture file with a given co-ordinate, but is it > >possible to do it from the wholescreenoutput regardless what > >application the selectedpixelis in? > > Which operating system? ?If you are on Windows, and you have pywin32 > loaded. you can use the Windows APIs GetDC and GetPixel. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. i have ubuntu hardy. does that help? From weihao89 at gmail.com Thu Jul 24 17:19:41 2008 From: weihao89 at gmail.com (Wei Hao) Date: Thu, 24 Jul 2008 17:19:41 -0400 Subject: Question about optimization Message-ID: Hi: I'm pretty new to python and I have some optimization issues. I'll show you the piece of code which is causing it, with pseudo-code before it and comments. I'm accessing a gigantic table (like 15 million rows) in SQL. d is some dictionary, r is a precompiled regex string Big loop, so I search through the table in chunks given by delta SQL query ("select * from table where rowID >= n and rowID < (n + delta)"), result of query stored in a. Each individual row is a[n1], columns of rows are a[n1][n2]. t1 = time.clock() #to track speed for m in a: for temp in m: if str(temp) == "None": #basically skip over the columns that are null for this particular row continue s += temp #get the columns into one long string s = s.replace("between", "") s = s.replace("and", "") s = s.replace("where", "") s = s.replace("like", "") #these words cause problems, need to get rid of them. b = re.findall(r,s) #looking for the stuff I want, always at least one per row of table, about 3-4 on average. for t in b: #store count of things I want in dictionary if t in d: d[t] += 1 else: d[t] = 1 print n, (time.clock()-t1) #to track speed I am 100% sure it's this code snippet that's the cause of my problems. Here's what I can tell you. Each chunk of rows that I grab is essentially equal in size (rowID skips over stuff, but rather arbitrarily). The time it takes to fetch the SQL query doesn't change. But as the program progresses, this snippet gets slower. Here's the output: 2500 0.441551299341 5000 1.26162739664 7500 2.35092688403 10000 3.48417469666 12500 4.59031305491 15000 5.78972588775 17500 6.28305527139 20000 6.73344570903 22500 8.31732146487 25000 9.65322872159 27500 8.98186042757 30000 11.8042818095 32500 12.1965593712 35000 13.2735763291 37500 14.0282617344 What is it in the code snippet that slows down as n increases? Is there something about the way low level python functions I don't understand which is slowing me down? Thanks in advance for your time. -Wei -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Wed Jul 23 18:31:21 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 24 Jul 2008 00:31:21 +0200 Subject: Undocumented Python 2.6 change: Py_None vs NULL when C implementation raises exception In-Reply-To: References: Message-ID: <4887b13a$0$7677$9b622d9e@news.freenet.de> Heikki Toivonen wrote: > I was debugging M2Crypto function written in C which changed behavior > between Python 2.6 and earlier Python versions. In an error condition > the function was supposed to raise exception type A, but with 2.6 it > raised type B, and further, there was no string value for the exception. > > I tracked this down to the C code incorrectly returning Py_None when it > should have returned NULL. Changing the C code to return NULL made it > behave correctly in 2.6. Can you please be specific what function you are talking about? > I don't know how common a mistake it is to return Py_None when NULL > should have been returned, but it might be worth a note in the list of > changes for 2.6 that this behavior changed, don't you think? Perhaps. OTOH, perhaps the change is completely erroneous. In that case, rather than documenting it, it should be reverted. Unfortunately, as you keep the specific issue secret, none of this will happen, as we have no clue what you are talking about. I'm sure there are tons of silent changes, in this release, all past releases, and all future releases, not only in Python, but in any software. Regards, Martin From mattheww at chiark.greenend.org.uk Tue Jul 29 15:30:11 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 29 Jul 2008 20:30:11 +0100 (BST) Subject: Where is the documentation for psycopg2? References: Message-ID: kj wrote: > Hi. I can't find any documentation for psycopg2. > > I'm a noob, so I'm sure I'm just not looking in the right place... > > Anybody know where it is? For basic use, psycopg2 follows the dbapi, which is described in http://www.python.org/dev/peps/pep-0249/ Additional features are described in doc/extensions.rst in the psycopg2 tarball. This leaves a gap for documentation of the basic features which the dbapi doesn't nail down (in particular, connecting to a database in the first place). I don't think there is any proper documentation covering this, but the scripts in examples/ (particularly simple.py) should make it reasonably clear. -M- From samwyse at gmail.com Wed Jul 9 15:29:00 2008 From: samwyse at gmail.com (samwyse) Date: Wed, 9 Jul 2008 12:29:00 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> Message-ID: <1343fa73-fd32-46c3-8a75-0efc85b2660e@a70g2000hsh.googlegroups.com> On Jul 8, 11:01?am, Kris Kennaway wrote: > samwyse wrote: > > You might want to look at Plex. > >http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/ > > > "Another advantage of Plex is that it compiles all of the regular > > expressions into a single DFA. Once that's done, the input can be > > processed in a time proportional to the number of characters to be > > scanned, and independent of the number or complexity of the regular > > expressions. Python's existing regular expression matchers do not have > > this property. " > Hmm, unfortunately it's still orders of magnitude slower than grep in my > own application that involves matching lots of strings and regexps > against large files (I killed it after 400 seconds, compared to 1.5 for > grep), and that's leaving aside the much longer compilation time (over a > minute). ?If the matching was fast then I could possibly pickle the > lexer though (but it's not). That's funny, the compilation is almost instantaneous for me. However, I just tested it to several files, the first containing 4875*'a', the rest each twice the size of the previous. And you're right, for each doubling of the file size, the match take four times as long, meaning O(n^2). 156000*'a' would probably take 8 hours. Here are my results: compile_lexicon() took 0.0236021580595 secs test('file-0.txt') took 24.8322969831 secs test('file-1.txt') took 99.3956799681 secs test('file-2.txt') took 398.349623132 secs And here's my (probably over-engineered) testbed: from __future__ import with_statement from os.path import exists from timeit import Timer from Plex import * filename = "file-%d.txt" def create_files(n): for x in range(0,n): fname = filename % x if not exists(fname): print 'creating', fname with open(fname, 'w') as f: print >>f, (4875*2**x)*'a', def compile_lexicon(): global lexicon lexicon = Lexicon([ (Rep(AnyBut(' "='))+Str('/'), TEXT), (AnyBut('\n'), IGNORE), ]) def test(fname): with open(fname, 'r') as f: scanner = Scanner(lexicon, f, fname) while 1: token = scanner.read() #print token if token[0] is None: break def my_timed_test(func_name, *args): stmt = func_name + '(' + ','.join(map(repr, args)) + ')' t = Timer(stmt, "from __main__ import "+func_name) print stmt, 'took', t.timeit(1), 'secs' if __name__ == '__main__': create_files(6) my_timed_test('compile_lexicon') for x in range(0,4): my_timed_test('test', filename%x) From david.lyon at preisshare.net Tue Jul 15 07:46:36 2008 From: david.lyon at preisshare.net (David Lyon) Date: Tue, 15 Jul 2008 21:46:36 +1000 Subject: Python embedding question. In-Reply-To: References: Message-ID: <487C8E1C.7050600@preisshare.net> Thomas Troeger wrote: > I want to embed a Python application on a device with limited > resources, esp. storage limitations. Is there a way to reduce the > Python interpreter to a set of modules that's urgently needed? Of course there is. What is the target platform ? What can be done is to go through the python source code and comment out everything that *you* find unneccessary. I can't tell you what this would be - because I don't know exactly what you are after. But to your question - the answer is yes.. of course. > Or is there a method to have gzipped modules that are unzipped on the > fly into memory when they're accessed? That would be even better. Yes - also possible. > > Additionally, is there a Python module that contains all the stuff > needed for an embedded application like graphics, sound etc. No. Because that depends on what hardware platform you want to run on. > or do I have to use the various bindings to libraries like cairo, Qt > or similar? Is there a site that helps with those decisions? I doubt it. These are decisions for you to make according to the limitations of your hardware. > > I've really looked at a lot of places but haven't found a suitable > solutions yet, so I'm asking here in hope that someone has experience > with that topic. > :-) Regards David From dullrich at sprynet.com Fri Jul 25 11:42:58 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 25 Jul 2008 10:42:58 -0500 Subject: repr(string) References: Message-ID: In article , MRAB wrote: > On Jul 23, 4:04?pm, "David C. Ullrich" wrote: > > I've been saving data in a file with one line per field. > > Now some of the fields may become multi-line strings... > > > > I was about to start escaping and unescaping linefeeds > > by hand, when I realized that repr() and eval() should > > do. Hence the question: If s is a string, is repr(s) > > guaranteed not to contain line breaks? > > > Might I suggest you use encode and decode instead? Ah, you certainly might! Seems exactly right, thanks. Many years ago I thought I had some idea of what was available in Python - these days it's full of all this neat stuff I never heard of... > >>> 'first line\nsecond line'.encode('string-escape') > 'first line\\nsecond line' > >>> _.decode('string-escape') > 'first line\nsecond line' > >>> u'first line\nsecond line'.encode('unicode-escape') > 'first line\\nsecond line' > >>> _.decode('unicode-escape') > u'first line\nsecond line' -- David C. Ullrich From victorsubervi at gmail.com Tue Jul 29 09:06:48 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 29 Jul 2008 15:06:48 +0200 Subject: Windows Interpreter Message-ID: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> Hi: I would like to make my windows python interpreter work like my linux one. I want to be able to cut and paste multiple lines of code. Now I can only paste one line at a time. I do not want it to indent automatically. How can I change this? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From HeinTest at web.de Thu Jul 10 11:32:34 2008 From: HeinTest at web.de (=?ISO-8859-1?Q?Hans_M=FCller?=) Date: Thu, 10 Jul 2008 17:32:34 +0200 Subject: Smal question In-Reply-To: References: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> Message-ID: <48762b92$0$11102$8e6e7893@newsreader.ewetel.de> Thanks a lot, you made my day. As often in python, it's really simple and useful ! Greetings Hans From Lie.1296 at gmail.com Sat Jul 26 05:35:57 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 26 Jul 2008 02:35:57 -0700 (PDT) Subject: Insert character at a fixed position of lines References: Message-ID: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> On Jul 26, 2:41?pm, "Francesco Pietra" wrote: > How to insert letter "A" on each line (of a very long list of lines) > at position 22, i.e., one space after "LEU", leaving all other > characters at the same position as in the original example: > > ATOM ? ? ?1 ?N ? LEU ? ? 1 ? ? 146.615 ?40.494 103.776 ?1.00 73.04 ? ? ? 1SG ? 2 > > In all lines"ATOM" is constant as to both position and string, while > "LEU" is constant as to position only, i.e., "LEU" may be replaced by > three different uppercase letters. Therefore, the most direct > indication would be position 22. > > Should the script introduce blank lines, no problem. That I know how > to correct with a subsequent script. > > Thanks > chiendarret If you want to leave the rest of the strings as-is (i.e. the letter A overwrites whatever on position 22), Peter's code need to be modified a little: line = line[:22] + " " + line[23:] From diordna at gmail.com Mon Jul 28 13:38:43 2008 From: diordna at gmail.com (Stephen Johnson) Date: Mon, 28 Jul 2008 13:38:43 -0400 Subject: python lists and newline character In-Reply-To: <053101c8f0d7$ebd7c340$a601a8c0@office.ipglobal.net> References: <053101c8f0d7$ebd7c340$a601a8c0@office.ipglobal.net> Message-ID: <46AF4AD1-8622-4E7E-BF26-6DECC0B5BF37@gmail.com> domain.strip() Assuming domain is the string with the newline. -Steve Johnson On Jul 28, 2008, at 1:32 PM, Support Desk wrote: > Hello all, > I am using os.popen to get a list returned of vpopmail > users, something like this > > x = os.popen('/home/vpopmail/bin/vuserinfo -n -D > mydomain.com).readlines() > > x returns a list, of usernames, and I am trying to append the > usernames with the domain like so > > for line in x: > print line + ?@? + domain > > but instead of getting > > user at domain.com > > im getting a newline character like: > user > @domain.com > User > @comain.com > User2 > @domain.com > > > Is there some way I can get this list without the newline characters > being added. or somehow remove the newline characters. Any help > would be appreciated. > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From dullrich at sprynet.com Tue Jul 29 11:40:39 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 29 Jul 2008 10:40:39 -0500 Subject: multiple inheritance and __getattr__ References: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> <488e2e70$0$29472$426a74cc@news.free.fr> Message-ID: In article <488e2e70$0$29472$426a74cc at news.free.fr>, Bruno Desthuilliers wrote: > Enrico a ?crit : > > Hi there, > > I have the following situation (I tryed to minimize the code to concentrate > > on the issue): > > > >>>> class A(object): > > def __getattr__(self, name): > > print 'A.__getattr__' > > if name == 'a': return 1 > > raise AttributeError('%s not found in A' % name) > > > >>>> class B(object): > > def __getattr__(self, name): > > print 'B.__getattr__' > > if name == 'b': return 1 > > raise AttributeError('%s not found in B' % name) > > > > Both classes have a __getattr__ method. > > Now I want to have a class that inherits from both so I write: > > > >>>> class C(B,A): > > pass > > > > The problem arise when I try something like this: > >>>> c=C() > >>>> c.a > > A.__getattr__ > > 1 > >>>> c.b > > A.__getattr__ > > > > Traceback (most recent call last): > > File "", line 1, in > > c.b > > File "", line 5, in __getattr__ > > raise AttributeError('%s not found in A' % name) > > AttributeError: b not found in A > > That's what I would have expected. > > > I was expecting, after a fail in A.__getattr__, a call to the __getattr__ > > method of B but it seems that after A.__getattr__ fails the exception stops > > the flow. > > Indeed. You explicitely raise, so the lookup stops here. ??? Surely the reason the lookup stops there is that a __getattr__ was _found_. In the code below the lookup is not continuing, there's a _second_ lookup started by the request for super.__getattr__. > You'd need to > explicitely call on superclass instead to have B.__getattr__ called, ie: > > class A(object): > def __getattr__(self, name): > if name == 'a': > return 1 > return super(A, self).__getattr__(name) > > class B(object): > def __getattr__(self, name): > if name == 'b': > return 2 > return super(B, self).__getattr__(name) > > class C(A, B): > pass > -- David C. Ullrich From paddy3118 at googlemail.com Tue Jul 22 16:21:34 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 22 Jul 2008 13:21:34 -0700 (PDT) Subject: software engineering foundations? References: Message-ID: <776bfd4d-a9c7-42f7-936f-967f58e7362d@59g2000hsb.googlegroups.com> On Jul 22, 7:52?pm, s... at pobox.com wrote: > Sorry for the off-topic-ish post. ?My son (a fairly junior sysadmin type) > mentioned to me today that he was looking for online courses for Perl. ?(I > don't hold that against him. ?Perl is still a lingua franca in the sysadmin > realm.) ?In my work I have from time-to-time had to pick up and maintain > scripts (generally shell/Python stuff) which non-professional programmers > have written. ?It's never what you would call a "pleasant" task. > > There are software construction skills which are entirely distinct from the > language in which you are programming. ?We can tout object-oriented, > structured programming, test-driven development or other software > engineering techniques, but there is a body of knowledge out there which is > orthogonal to the language in which the code is written. ?People who are not > professional programmers often lack those skills and their code shows it. > > Are there any good online resources for this "software structure" axis? > Googling for "object oriented programming tutorial" yields a bunch of stuff, > much of it language-specific. ?I'm trying to find something a bit more > general than that though. > > I Googled for "software engineering tutorial" as well. ?Most of the early > hits were either inaccessible (ACM subscription only) or contents-like stuff > (conference announcements, for example). ?Number eight on the list was this > rather promising page: > > ? ?http://www.cmcrossroads.com/bradapp/links/swe-links.html > > It was last updated over 10 years ago. ?I find it hard to believe that > so little has changed in that time that some other page with more recent > references hasn't percolated to the top of Google's page rank! ?After all, > the Web has grown just a tad in that timeframe. > > I have a sneaking suspicion that what I'm looking for is out there, but that > I'm not asking Google in the right manner. ?Any and all pointers/suggestions > cheerfully accepted. > > Thx, > > -- > Skip Montanaro - s... at pobox.com -http://www.webfast.com/~skip/ > ------ > ELON MUSK: If fuel cells were good, don't think you'd see them somewhere, > like maybe in a laptop or a cell phone or a $200 million military satellite > maybe? ?And yet, where do you see them? > SPENCER MICHELS: You don't. > ELON MUSK: Exactly. Is this the kind of thing you are after? http://www.swc.scipy.org/ "Software Carpentry" Overview Many scientists and engineers spend much of their lives programming, but only a handful have ever been taught how to do this well. As a result, they spend their time wrestling with software, instead of doing research, but have no idea how reliable or efficient their programs are. This course is an intensive introduction to basic software development practices for scientists and engineers that can reduce the time they spend programming by 20-25%. All of the material is open source: it may be used freely by anyone for educational or commercial purposes, and research groups in academia and industry are actively encouraged to adapt it to their needs. - Paddy. From pavlovevidence at gmail.com Wed Jul 30 02:48:07 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 23:48:07 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> <7f4a3d37-e551-4e21-b660-3618016cb67b@z6g2000pre.googlegroups.com> <68448887-4736-4af9-9f27-837bb5312cbd@o40g2000prn.googlegroups.com> Message-ID: <13bad2cb-32ec-4a61-bc44-09f5d6a89416@q5g2000prf.googlegroups.com> On Jul 30, 2:06 am, Erik Max Francis wrote: > Perhaps in the particular use case you're thinking of (numeric types vs. > container types), there aren't any good examples. But who cares? You don't have to. I am trying to set the record straight on just how much polymophism "if x" supports relative to explicit tests, which is to say, not much. BTW, I haven't changed my criteria since I asked for the challenge. Carl Banks From deets at nospam.web.de Mon Jul 28 07:13:41 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 13:13:41 +0200 Subject: Google Group: architectgurus References: Message-ID: <6f5o17F99fqqU1@mid.uni-berlin.de> Gerhard H?ring wrote: > Dear Guru, > > Sudhakar Chavali wrote: >> Hi >> >> I have created a group called architectgurus (http://groups.google.com/ >> group/architectgurus) or architectgurus at googlegroups.com . >> Irrespective of technology, vendor, domain I will be discussing and >> share my thoughts in homogenous and harmonious way. If you are >> interested *even you* can join and contribute your thoughts in this >> group. My intention doing these activities is to spread the knowledge >> and thoughts across the globe. > > What? even me? That's really nice of you. It's amazing - all his thoughts can be summarized in 2 lines of postings + a PDF-link to thoughts of *other* people. Lively discussions are to emerge pretty soon I'm sure.. Diez From scottpig1 at comcast.net Mon Jul 28 21:48:26 2008 From: scottpig1 at comcast.net (pigmartian) Date: Mon, 28 Jul 2008 21:48:26 -0400 Subject: ctypes - unloading implicitly loaded dlls In-Reply-To: References: Message-ID: Nick Craig-Wood wrote: > You could try loading C explicitly with ctypes.LoadLibrary() before > loading A, then you'll have a handle to unload it before you load B. I did think of that, but no luck. Guess the cdll doesn't look for a dll loaded already by python. I guess that does make sense. > I think I'd probably split the code into two or three processes > though. Perhaps use http://pypi.python.org/pypi/processing to > communicate between them. That should get you out of DLL Hell! > (Don't load any of the DLLs before you start the worker processes > off.) That was quite a helpful suggestion, thank you. I had been using the subprocess module actually, but really didn't like that approach. processing is much nicer. Pipes, in particular, is quite handy. ~Scott From gagsl-py2 at yahoo.com.ar Tue Jul 15 03:34:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 04:34:32 -0300 Subject: python mysteriously halts References: <13a33043-21d1-40c0-a938-6e905d958064@m3g2000hsc.googlegroups.com> Message-ID: En Mon, 07 Jul 2008 12:26:28 -0300, Todd escribi?: > On Jul 7, 10:17?am, Tim Golden wrote: >> Todd wrote: >> > I ran a python script last night which connects to a matlab automation >> > server via DCOM (using win32com). ?I expected to see the results when >> > I came in this morning. ?But apparently, not long after I left, python >> > stopped. ?I hit enter in the console, and it started again. >> >> Symptomatically, at least, this can be caused by someone starting to >> select (with the mouse) an area of the screen: the process will pause >> until is pressed, which copies the area to the clipboard. This >> only happens with a console window, but it sounds like that's what >> you had running. > > That might be it, although I don't recall doing that. Fortunately/ > unfortunately, it happened a few times, but it seems to have stopped > now. You could disable that behaviour by unchecking "Quick edit mode" (or something like that) in the Default preferences for the console window. (It's unchecked by default on WinXP and Win2003, I think). -- Gabriel Genellina From pavlovevidence at gmail.com Wed Jul 30 00:28:10 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 21:28:10 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <009fa37d$0$20313$c3e8da3@news.astraweb.com> Message-ID: On Jul 29, 7:30 pm, Steven D'Aprano wrote: > On Tue, 29 Jul 2008 10:30:43 -0700, Carl Banks wrote: > > On Jul 29, 5:15 am, Heiko Wundram wrote: > >> I can't dig up a simple example from code I wrote quickly, but because > >> of the fact that explicit comparisons always hamper polymorphism > > > I'm not going to take your word for it. Do you have code that > > demonstrates how "if x" improves polymorphism relative to simple > > explicit tests? > > On the rapidly decreasing chance that you're not trolling (looking more > and more unlikely every time you post): > > # The recommended way: > if x: > do_something > > # Carl's so-called "simple explicit tests" applied to polymorphic code: No, the following isn't my way. > try: > # could be a sequence or mapping? > # WARNING: must do this test *before* the number test, otherwise > # "if [] != 0" will return True, leading to the wrong branch being > # taken. > if len(x) != 0: > do_something > except AttributeError: > # not a sequence or mapping, maybe it's a number of some sort > try: > int(x) > except TypeError: > # not convertable to numbers > # FIXME: not really sure what to do here for arbitrary types > # so fall back on converting to a boolean, and hope that works > if bool(x): > do_something > else: > if x != 0: > do_something I say that you will never, ever have to do this because there isn't a do_something that's actually useful for all these types. Ok, tell me, oh indignant one, what is do_something? What could possibly be the contents of do_something such that it actually does something useful? If you can tell me what do_something is you will have answered my question. Carl Banks From fredrik at pythonware.com Thu Jul 24 11:35:40 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 17:35:40 +0200 Subject: repr(string) In-Reply-To: References: Message-ID: David C. Ullrich skrev: >> just keep in mind that using eval() on untrusted data isn't a very good >> idea. > > Right. This data comes from me, gets put into a file and then > read by me. Someone _could_ corrupt that file, but someone who > could do that could more easily just throw the machine out > the window... and then your boss finds your program useful, and it's installed on a shared server, and then the guys at the office in Eggkleiva wants a copy, and then people start shipping save files via mail to keep things synchronized, and then someone sets up a web service... ;-) From castironpi at gmail.com Sun Jul 27 14:20:38 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 27 Jul 2008 11:20:38 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> Message-ID: <490769a4-2a48-41dc-a069-2cc003b332a2@b1g2000hsg.googlegroups.com> On Jul 26, 4:08?am, Nikolaus Rath wrote: > Terry Reedy writes: > > Nikolaus Rath wrote: > >> Terry Reedy writes: > >>> Torsten Bronger wrote: > >>>> Hall?chen! > >>> ?> And why does this make the implicit insertion of "self" difficult? > >>>> I could easily write a preprocessor which does it after all. > >>> class C(): > >>> ? def f(): > >>> ? ? a = 3 > > >>> Inserting self into the arg list is trivial. ?Mindlessly deciding > >>> correctly whether or not to insert 'self.' before 'a' is impossible > >>> when 'a' could ambiguously be either an attribute of self or a local > >>> variable of f. ?Or do you and/or Jordan plan to abolish local > >>> variables for methods? > > >> Why do you think that 'self' should be inserted anywhere except in the > >> arg list? AFAIU, the idea is to remove the need to write 'self' in the > >> arg list, not to get rid of it entirely. > > > Because you must prefix self attributes with 'self.'. If you do not > > use any attributes of the instance of the class you are making the > > function an instance method of, then it is not really an instance > > method and need not and I would say should not be masqueraded as > > one. If the function is a static method, then it should be labeled > > as one and no 'self' is not needed and auto insertion would be a > > mistake. In brief, I assume the OP wants 'self' inserted in the body > > because inserting it only in the parameter list and never using it > > in the body is either silly or wrong. > > I think you misunderstood him. What he wants is to write > > class foo: > ? ?def bar(arg): > ? ? ? ?self.whatever = arg + 1 > > instead of > > class foo: > ? ?def bar(self, arg) > ? ? ? ?self.whatever = arg + 1 > > so 'self' should *automatically* only be inserted in the function > declaration, and *manually* be typed for attributes. > > Best, > > ? ?-Nikolaus > > -- > ??It is not worth an intelligent man's time to be in the majority. > ? By definition, there are already enough people to do that.? > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?-J.H. Hardy There's a further advantage: class A: def get_auxclass( self, b, c ): class B: def auxmeth( self2, d, e ): #here, ... return B Because Python permits you to name 'the current instance' any name you want, you're able to hold more than one current instance at one time. In this case, you could write 'return self.val+ self2.val' with no trouble, while I'm not even sure that anything like that is possible in C, C++, Java, or anything higher other than Python. (This is a good point, outside of the usual, by the way.) From thogiti at gmail.com Thu Jul 3 20:33:31 2008 From: thogiti at gmail.com (Nagu) Date: Thu, 3 Jul 2008 17:33:31 -0700 (PDT) Subject: Copyright issues for an application developed using django, python and mySQL Message-ID: <1f23a9fd-33a0-4a06-9733-241c8fd450d2@w4g2000prd.googlegroups.com> Hi, I made a small recommendation engine for our company using python, django, and mySQL. My supervisor and the senior management are worried about the copyright and licensing issues. They want to find out the details on how to go about start using it, like quoting python/django/ mySQL specifically on the bottom of the web page or some other thing. I would like our sales force to start using this new toy to recommend products to customers. They are going to type an intranet page in their browser, and enter the customer ID to get the product recommendations. How do I go about addressing the copyright and licensing issues? (I do not know if licensing is the right word here). Please advice. Thank you, Nagu From bj_666 at gmx.net Fri Jul 11 11:07:59 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Jul 2008 15:07:59 GMT Subject: strip() using strings instead of chars References: <487751a6$0$29402$426a74cc@news.free.fr> Message-ID: <6dpbaeF3l2h2U1@mid.uni-berlin.de> On Fri, 11 Jul 2008 16:45:20 +0200, Christoph Zwerschke wrote: > Bruno Desthuilliers schrieb: >> DRY/SPOT violation. Should be written as : >> >> prefix = 'http://' >> if url.startswith(prefix): >> url = url[len(prefix):] > > That was exactly my point. This formulation is a bit better, but it > still violates DRY, because you need to type "prefix" two times. It is > exactly this idiom that I see so often and that I wanted to simplify. > Your suggestions work, but I somehow feel such a simple task should have > a simpler formulation in Python, i.e. something like > > url = url.lstripstr(('http://', 'https://')) I would prefer a name like `remove_prefix()` instead of a variant with `strip` and abbreviations in it. Ciao, Marc 'BlackJack' Rintsch From fredrik at pythonware.com Thu Jul 17 06:26:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 12:26:42 +0200 Subject: Fwd: Hello In-Reply-To: References: Message-ID: spandana g wrote: > HTTPError: HTTP Error 999: Unable to process request at this time -- > error 999 > > Previously i got the error which I have attached below when I use just > urlopen . But now when I use this http request > user_agent='Mozilla/3.0(compatible;MISE 5.5;Windows NT)' > headers={'User-Agent':user_agent} > req=urllib2.Request(url,None,headers) > file_source.write(urllib2.urlopen(req).read() > > its still giving the error mentioned above .. Iam accessing the yahoo > search engine .. link is "http://search.yahoo.com/search?n=20&p=ipod > " > > I'm attaching the python file i have written just have a look and > suggest me something that works for this query they have an official API, you know: http://developer.yahoo.com/search/boss/ here's an article showing how to install and use it: http://lethain.com/entry/2008/jul/11/search-recipes-for-yahoo-s-boss-in-python/ From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 08:59:26 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 14:59:26 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <874p6fzkkh.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> Message-ID: <488898a5$0$12027$426a34cc@news.free.fr> Torsten Bronger a ?crit : > Hall?chen! > > Bruno Desthuilliers writes: > >> [...] >> >> How would you handle this case with an implicit 'self' : >> >> class Foo(object): >> pass >> >> def bar(self): >> print self >> >> Foo.bar = bar > > Just like this. However, the compiler could add "self" to > non-decorated methods which are defined within "class". What's defined within classes are plain functions. It's actually the lookup mechanism that wraps them into methods (and manage to insert the current instance as first argument). From tedshab at gmail.com Mon Jul 7 15:27:36 2008 From: tedshab at gmail.com (TBS) Date: Mon, 7 Jul 2008 12:27:36 -0700 (PDT) Subject: tale of two attachments Message-ID: <66ba192a-9430-45dc-968f-c41c1c8029d4@k30g2000hse.googlegroups.com> Hi, I have a script that is invoked by .forward on a Unix mailbox. It works fine parsing an attachment and saving to disk when the email is sent directly to the email address (header 1), but doesn't work when the email is sent via a majordomo mailing list (header 2). I've looked at the mime files coming into mail, and they look the same. I've attached the headers, and I don't see any major different, although there is a warning on the mailing list that "X-Authentication- Warning: lists...: pmx set sender to owner-list-report at ... using -f". Here is the code fragment, it seems to fail on the second header on the part.get_param call: parser=email.Parser.Parser() msg = parser.parsestr(raw_email) counter = 1 for part in msg.walk(): if part.get_main_type()== 'multipart': continue log.write("gets here") #gets to this point for majordomo send filename = part.get_param("name") log.write("...but not here") #but not to this point if filename==None: filename = "part-%1" % counter counter += 1 fp = open(os.path.join(dir, filename), 'wb') fp.write(part.get_payload(decode=1)) fp.close() ============================= Header 1 ============================= >From tshab at ... Mon Jul 7 11:00:46 2008 Received: from nospam3... by mail... with ESMTP id m67I0jSg023687 for ; Mon, 7 Jul 2008 11:00:45 -0700 (PDT) (envelope-from tshab at ...) X-MimeOLE: Produced By Microsoft Exchange V6.5 Content-class: urn:content-classes:message MIME-Version: 1.0 Content-Type: application/vnd.ms-excel; name="po_test.xls" Content-Transfer-Encoding: base64 Content-Description: po_test.xls Content-Disposition: attachment; filename="po_test.xls" Subject: test case Date: Mon, 7 Jul 2008 11:00:44 -0700 Message-ID: In-Reply-To: X-MS-Has-Attach: yes X-MS-TNEF-Correlator: Thread-Topic: test case thread-index: AcjgWxsfx8N1mNqFSOq9C/j/8FIZIQAADqBg References: From: "Shab, Theodore" To: "arf" Content-Length: 18675 Status: RO ============================= Header 2 ============================= >From owner-list-report at ... Mon Jul 7 11:01:05 2008 Received: from list... (list...) by mail with ESMTP id m67I14uL023715; Mon, 7 Jul 2008 11:01:04 -0700 (PDT) (envelope-from owner-list-report at ...) Received: from lists... by list... with ESMTP id m67I13bD017476 for ; Mon, 7 Jul 2008 11:01:03 -0700 (PDT) (envelope-from owner-list-report at ...) Received: (from pmx at localhost) by list.../Submit) id m67I13lG017475 for list-report-outgoing; Mon, 7 Jul 2008 11:01:03 -0700 (PDT) (envelope-from owner-list-report at ...) X-Authentication-Warning: lists...: pmx set sender to owner-list- report at ... using -f Received: from nospam... (nospam...) by lists... with ESMTP id m67I127h017471 for ; Mon, 7 Jul 2008 11:01:02 -0700 (PDT) (envelope-from tshab at ...) Received: from exch-mai...) by nospam... with ESMTP id m67I11g2014193 for ; Mon, 7 Jul 2008 11:01:02 -0700 (envelope-from tshab at ...) X-MimeOLE: Produced By Microsoft Exchange V6.5 Content-class: urn:content-classes:message MIME-Version: 1.0 Content-Type: application/vnd.ms-excel; name="po_test.xls" Content-Transfer-Encoding: base64 Content-Description: po_test.xls Content-Disposition: attachment; filename="po_test.xls" Subject: test case 2 Date: Mon, 7 Jul 2008 11:01:01 -0700 Message-ID: X-MS-Has-Attach: yes X-MS-TNEF-Correlator: Thread-Topic: test case 2 thread-index: AcjgW2qv6AWa1eUxTXGlSQ5a2g7OuA== From: "Shab, Theodore" To: "list-report" Sender: owner-list-report at ... Precedence: bulk Content-Length: 18675 Status: O From phillip.oldham at gmail.com Wed Jul 9 10:38:59 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Wed, 9 Jul 2008 07:38:59 -0700 (PDT) Subject: FOSS projects exhibiting clean/good OOP? Message-ID: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> I'm wondering whether anyone can offer suggestions on FOSS projects/ apps which exhibit solid OO principles, clean code, good inline documentation, and sound design principles? I'm devoting some time to reviewing other people's code to advance my skills. Its good to review bad code (of which I have more than enough examples) as well as good, but I'm lacking in finding good examples. Projects of varying sizes would be great. From thogiti at gmail.com Mon Jul 7 15:05:47 2008 From: thogiti at gmail.com (Nagu) Date: Mon, 7 Jul 2008 12:05:47 -0700 (PDT) Subject: Memory error while saving dictionary of size 65000X50 using pickle Message-ID: <43b21f62-edb6-4e37-89b8-f2460fdc36b3@25g2000hsx.googlegroups.com> I am trying to save a dictionary of size 65000X50 to a local file and I get the memory error problem. How do I go about resolving this? Is there way to partition the pickle object and combine later if this is a problem due to limited resources (memory) on the machine (it is 32 bit machine Win XP, with 4GB RAM). Here is the detail description of the error: Traceback (most recent call last): File "", line 1, in s = pickle.dumps(itemsim) File "C:\Python25\lib\pickle.py", line 1366, in dumps Pickler(file, protocol).dump(obj) File "C:\Python25\lib\pickle.py", line 224, in dump self.save(obj) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "C:\Python25\lib\pickle.py", line 663, in _batch_setitems save(v) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 600, in save_list self._batch_appends(iter(obj)) File "C:\Python25\lib\pickle.py", line 615, in _batch_appends save(x) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 562, in save_tuple save(element) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 477, in save_float self.write(FLOAT + repr(obj) + '\n') MemoryError: out of memory From modelnine at modelnine.org Tue Jul 29 17:06:46 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Tue, 29 Jul 2008 22:06:46 +0100 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: Also, just a couple of points: Am 29.07.2008, 22:27 Uhr, schrieb Carl Banks : > 1. Any container type that returns a length that isn't exactly the > number of elements in it is broken. I agree, but how do you ever expect to return an infinite element count? The direction I took in that recipe was not returning some "magic" value but raising an OverflowError (for example, you could've also cropped the length at 2**31-1 as meaning anything equal to or larger). This is the thing that breaks your explicit test for non-emptyness using len(x) > 0, but it's also the only possible thing to do if you want to return the number of elements exactly where possible and inform the user when not (and OverflowError should make the point clear). Anyway, that's why there is a separate member function which is explicitly documented to return a magic value in case of an infinite set (i.e., -1) and an exact element count otherwise, but using that (you could write x.len() != 0 for the type in question to test for non-emptiness) breaks polymorphism. > 2. The need for __nonzero__ in this case depends on a limitation in > the language. True, but only for sets with are finite. For an infinite set, as I said above: what would you want __len__() to return? There is no proper interpretation of __len__() for an infinite set, even though the set is non-empty, except if you introduced the magic value infinity into Python (which I did as -1 for my "personal" length protocol). > 3. On the other hand, I will concede that sometimes calculating len is > a lot more expensive than determining emptiness, and at a basic level > it's important to avoid these costs. You have found a practical use > case for __nonzero__. This is just a somewhat additional point I was trying to make; the main argument are the two points you see above. > However, I'd like to point out the contrasting example of numpy > arrays. For numpy arrays, "if x" fails (it raises an exception) but > "if len(x)!=0" succeeds. > > The only sane advice for dealing with nonconformant classes like numpy > arrays or your interger set is to be wary of nonconformances and don't > expect polymorphism to work all the time. The thing is: my integer set type IS conformant to the protocols of all other sequence types that Python offers directly, and as such can be used in any polymorphic function that expects a sequence type and doesn't test for the length (because of the obvious limitation that the length might not have a bound), but only for emptiness/non-emptiness. It's the numpy array that's non-conformant (at least from what you're saying here; I haven't used numpy yet, so I can't comment). > So I guess I'll concede that in the occasional cases with > nonconformant classes the "if x" might help increase polymorphism a > little. > > (BTW: here's another little thing to think about: the "if x" is useful > here only because there isn't an explicit way to test emptiness > without len.) The thing being, again, as others have already stated: __nonzero__() IS the explicit way to test non-emptiness of a container (type)! If I wanted to make things more verbose, I'd not use "if len(x)>0", but "if bool(x)" anyway, because "casting" to a boolean calls __nonzero__(). "if len(x)>0" solves a different problem (even though in set theory the two are logically similar), and might not apply to all container types because of the restrictions on the return value of __len__(), which will always exist. --- Heiko. From trentm at activestate.com Thu Jul 10 12:48:16 2008 From: trentm at activestate.com (Trent Mick) Date: Thu, 10 Jul 2008 09:48:16 -0700 Subject: ActiveState Code: the new Python Cookbook site In-Reply-To: <4874698E.7000805@gmail.com> References: <4873F326.5010905@activestate.com> <4874698E.7000805@gmail.com> Message-ID: <48763D50.8010608@activestate.com> Stef Mientki wrote: > one small remark, > If I want to browse 200 recipes, at 10 per page .... > ... please make something like 100 available per page, > are internet is fast enough nowadays. Touche. Done: http://code.activestate.com/recipes/?paginate_by=100 Cheers, Trent -- Trent Mick trentm at activestate.com From robertmlamarca at yahoo.com Tue Jul 29 06:46:14 2008 From: robertmlamarca at yahoo.com (Robert LaMarca) Date: Tue, 29 Jul 2008 03:46:14 -0700 (PDT) Subject: Swap memory in Python ? - three questions Message-ID: <642068.13334.qm@web55102.mail.re4.yahoo.com> Hi, I am using numpy and wish to create very large arrays. My system is AMD 64 x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a 15 GB swap drive. The command I have been trying to use is; g=numpy.ones([1000,1000,1000],numpy.int32) This returns a memory error. A smaller array ([500,500,500]) worked fine.. Two smaller arrays again crashed the system. So... I did the math. a 1000x1000x1000 array at 32 bits should be around 4gb RAM... Obviously larger than RAM, but much smaller than the swap drive. 1. So... does Numpy have a really lot of overhead? Or is my system just not somehow getting to make use of the 15gb swap area. 2. Is there a way I can access the swap area, or direct numpy to do so? Or do I have to write out my own numpy cache system... 3. How difficult is it to use data compression internally on numpy arrays? thanks very much Robert From bignose+hates-spam at benfinney.id.au Fri Jul 11 20:13:14 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 12 Jul 2008 10:13:14 +1000 Subject: Python 3.0 and removal of the 'string' module References: <87wsjtqiyo.fsf@benfinney.id.au> <87iqvdq6qz.fsf@benfinney.id.au> <487706b7$0$9695$9b622d9e@news.freenet.de> <87abgorgiv.fsf@benfinney.id.au> <76f1bf48-b05f-472b-9bfc-cf59dd2a97ca@m45g2000hsb.googlegroups.com> Message-ID: <87od54ot7p.fsf@benfinney.id.au> John Roth writes: > library changes are all listed in PEP 3008. I assume you mean PEP 3108, "Standard Library Reorganization" . -- \ ?I have one rule to live by: Don't make it worse.? ?Hazel | `\ Woodcock | _o__) | Ben Finney From kyosohma at gmail.com Mon Jul 7 12:20:18 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 7 Jul 2008 09:20:18 -0700 (PDT) Subject: how to recognize IE window already opened using win32com extension References: <203fdfe3-78d6-4b08-a64f-a031df9cacc1@s50g2000hsb.googlegroups.com> Message-ID: <712283ff-7ed3-4bac-acc3-938bafef9639@i76g2000hsf.googlegroups.com> On Jul 7, 11:16?am, Tim Golden wrote: > korean_dave wrote: > > How do I use the win32com API to manipulate IE windows ALREADY open? > > > ie = Dispatch("InternetExplorer.Application") opens a new window. > > > But I'd like to be able to find, of windows already open, a specific > > window (with a specified property, matching url, etc.) > > I have this strange feeling of deja vu. Is there some sort of > "opening IE windows with Python" conference going on > somewhere? > > Have a look at Roger Upole's answer from the other day: > > http://mail.python.org/pipermail/python-win32/2008-June/007796.html > > TJG Crumb! That's way easier than the one I mentioned! Mike From steve at REMOVE-THIS-cybersource.com.au Wed Jul 30 22:25:37 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Jul 2008 02:25:37 GMT Subject: Standard module for parsing emails? References: <6fb93eFap7j5U1@mid.individual.net> Message-ID: <00a11e11$0$20313$c3e8da3@news.astraweb.com> On Wed, 30 Jul 2008 07:11:45 -0700, Phillip B Oldham wrote: > Most clients use ">" which is easy to check for, but I've seen some > which use "|" and some which *don't* quote at all. Its causing us > nightmares in parsing responses to system-generated emails. I was hoping > someone might've seen the problem previously and released some code. My sympathies. I've even seen clients that prefix new (unquoted) text with the quote character ">". Well, possibly it's not the mail client, but the user. Who knows? I will sometimes quote text like this: [quote] Something quoted. [end quote] But I'm writing for a human audience, not for a program. The simple answer is that you can catch 90% of cases by checking for ">", and another 1% by checking for "|". If the email contains HTML, I have found that quoted text is sometimes in another colour. As for the rest, well, sometimes even human beings can't easily determine what's quoted and what isn't. Good luck getting a program to do it. (Percentages are plucked out of thin air. YMMV.) -- Steven From cokofreedom at gmail.com Thu Jul 24 11:00:19 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 24 Jul 2008 08:00:19 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <40449826-c71d-4c6e-8b74-13069269e5da@z6g2000pre.googlegroups.com> <488896bf$0$3493$426a74cc@news.free.fr> Message-ID: > > Please understand that I'm not arguing about this particular design > choice (and FWIW, I'd mostly agree on the point that having a != b > different from not (a == b) is actually a wart). I'm just correcting > your statement about the behaviour of __eq__ / __ne__ not being > documented, which is obviously false. > > (snip) What was the reasoning behind having both __eq__ / __ne__ anyway? To fit in with the equality comparisons? I do agree this one seems like a wart, but not a serious one. I'd say it would make more sense for the interpreter to provide a warning on classes that define one and not that other, at least if set to a certain level, similar to -3 for depreciated. (Or does this exist? I think a "wart" catching level that outputs potential warts and issues would be a useful addition!) From mnordhoff at mattnordhoff.com Mon Jul 7 08:07:19 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 07 Jul 2008 12:07:19 +0000 Subject: Confused yet again: Very Newbie Question In-Reply-To: References: Message-ID: <487206F7.2070609@mattnordhoff.com> mcl wrote: > Why can I not the change the value of a variable in another class, > when I have passed it via a parameter list. > > I am sure I am being stupid, but I thought passed objects were Read/ > Write In Python, there are names which are bound to objects. Doing "foo = bar" and then "foo = spam" (re)binds the name "foo" to the same object as "spam" is bound to. This doesn't have any effect on any other names that were bound to the same object as "bar". > eg > ------------------------------------------------------------ > #!/usr/bin/python > > class one(): #my Global Vars > fred = 'fred' > > class three(): > def createJoe(self, myName): Here, the local name "myName" is bound to the same string object as one.fred. > c1 = one() > myName = 'Joe' #********************* Question why does this > not change variable fred in 'class one' Here, you rebind the local name "myName" to the string object 'Joe'. This doesn't change what one.fred is bound to. > print 'Three(Local): ' + myName + ' Three(Global): ' + > c1.fred > > def main(): > c1 = one() > c3 =three() > c3.createJoe(c1.fred) > > > if __name__ == '__main__' : main() > > Results: > Three(Local): Joe Three(Global): fred > > 'fred' in 'class one' does not get changed to 'joe' in 'class three' > 'createJoe', even though I have passed 'class one' 'fred' to > 'createJoe' > > I hope this makes sense. > > I did not think you had to make the distinction between 'byvar' and > 'byref' as in Basic. > > Thanks > > Richard There are a couple good articles about this online. The one below is lengthy and has ASCII art, but I don't remember if I liked it. BTW, in this example, there doesn't seem to be any need for you to be using classes. Also, you should always use new-style classes unless you have a specific reason not to >>> class MyClass(object): -- From ryntech at gmail.com Mon Jul 21 10:19:16 2008 From: ryntech at gmail.com (rynt) Date: Mon, 21 Jul 2008 07:19:16 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> On Jul 20, 3:50?pm, giveitawhril2... at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. You're either --- A. A Troll B. A young, immature programmer trying to show off or C. A total idiot. Who cares what language a language is written in as long as you can be productive - which you certainly can be in Python. RCB From naude.jaco at gmail.com Wed Jul 23 08:06:50 2008 From: naude.jaco at gmail.com (Jaco Naude) Date: Wed, 23 Jul 2008 05:06:50 -0700 (PDT) Subject: Undefined calling conventions in Python.h References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> Message-ID: <2690be50-3fee-4327-aeae-0c6e236f9aab@27g2000hsf.googlegroups.com> On Jul 23, 1:50?pm, Jaco Naude wrote: > On Jul 23, 1:10?pm, Fredrik Lundh wrote: > > > > > Jaco Naude wrote: > > > What Visual C++ is doing is that it is looking for mangled names since > > > it does not know the DLL contains C functions. I've managed to work > > > around this by declaring the Python functions as follows before using > > > them in the C++ application side: > > > > extern "C" > > > { > > > ? ? void Py_Initialize(void); > > > } > > > > This seems to work and the C++ application side is not looking for > > > mangled names any more. Is this the right way of doing it? It seems > > > unnecessary to have to declare each Python function you want to use > > > using the extern "C" way as shown above. > > > Eh, are you saying that you're not including the Python.h file? ?Because > > it does exactly that, for each and every public function in the C API. > > > > It is probably more of a C++ question it turns out, but I would think > > > that someone in the Python group would use the Python DLL in C++. The > > > documentation also suggest that there is no extra work needed when > > > using C++ rather than C. > > > Oh, but I do that all the time, without doing any extra work. ?Both > > embedding Python in C++ programs and existing it with C++ extensions. > > And I'm definitely not alone. > > > Here's an actual session, using the version of Visual Studio I happen to > > have on this machine (2003, I think) from the command line: > > > ?> more test.cc > > > #include "Python.h" > > #include > > > main() > > { > > ? ? ?Py_Initialize(); > > ? ? ?PyRun_SimpleString("print 'hello'\n"); > > ? ? ?Py_Finalize(); > > > ? ? ?std::cout << "world\n"; > > > } > > > ?> cl cl -EHsc -MD -I \python25\include test.cc \python25\libs\python25.lib > > Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 > > for 80x86 > > Copyright (C) Microsoft Corporation 1984-2002. All rights reserved. > > > ... > > > ?> test > > hello > > world > > > If you cannot get the same console program to work in your compiler > > setup, something's wrong with your configuration. > > > > > Ok that's probably good news, although it points out that there is > something wrong with my configuration since that does not work. I > would rather sort out the problem that having to defined each function > with a extern "C" command. > > That said, let me double check something which might be causing > problems since you will be familiar with this. Which Python.h file do > you include when including the DLL in your programs? The one in the > source distribution of the one in the installation distribution? I've > been including the one in the installation distribution all along. > When I try to include the one in the source distribution it gets up to > the point where it looks for the following include: > > #include "pyconfig.h" > > This file is not in the same directory as the Python.h file in the > source distribution. Because of this I just used Python.h in the > installation distribution. > > Thanks again, > Jaco I only saw your last message after posting my previous one. Ok, so the problem is definitely with the include file Python.h. As I said in my last post, I might be including the wrong one. I would appreciate it if you can tell me which one it the correct one to use: The one in the source distribution or the one in the release distribution (installation done from the .msi file). Thanks Jaco From exarkun at divmod.com Tue Jul 29 10:49:17 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 29 Jul 2008 10:49:17 -0400 Subject: [unittest] Run setUp only once In-Reply-To: <877ib4rc50.fsf@nokile.rath.org> Message-ID: <20080729144917.29191.1051727928.divmod.quotient.8220@ohm> On Tue, 29 Jul 2008 16:35:55 +0200, Nikolaus Rath wrote: >Hello, > >I have a number of conceptually separate tests that nevertheless need >a common, complicated and expensive setup. > >Unfortunately, unittest runs the setUp method once for each defined >test, even if they're part of the same class as in > >class TwoTests(unittest.TestCase): > def setUp(self): > # do something very time consuming > > def testOneThing(self): > > > def testADifferentThing(self): > > >which would call setUp twice. > > >Is there any way to avoid this, without packing all the unrelated >tests into one big function? > class TwoTests(unittest.TestCase): setUpResult = None def setUp(self): if self.setUpResult is None: self.setUpResult = computeIt() ... There are plenty of variations on this pattern. Jean-Paul > >Best, > > -Nikolaus > >-- > ?It is not worth an intelligent man's time to be in the majority. > By definition, there are already enough people to do that.? > -J.H. Hardy > > PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C > >-- >http://mail.python.org/mailman/listinfo/python-list > From kevin.dahlhausen at gmail.com Tue Jul 29 09:51:29 2008 From: kevin.dahlhausen at gmail.com (kpd) Date: Tue, 29 Jul 2008 06:51:29 -0700 (PDT) Subject: Automatically loading and initialising objects from a plugins directory References: <488607BC.3040204@ecs.soton.ac.uk> <4889B888.8000600@ecs.soton.ac.uk> Message-ID: On Jul 25, 7:50 am, Fredrik Lundh wrote: > It's a potentially brain-exploding topic, -that you made very understandable. Thanks for posting that explanation and example. From mccredie at gmail.com Tue Jul 8 14:23:42 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 8 Jul 2008 11:23:42 -0700 (PDT) Subject: How to make python scripts .py executable, not bring up editor References: Message-ID: <7a34ceb4-4f2e-4c79-aeb2-587235cab19d@z72g2000hsb.googlegroups.com> On Jul 7, 2:56?pm, korean_dave wrote: > From command Prompt, i type in a script, ?"tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? You can do this by editing the registry, but here is the general way to click through chaning file associations: Right click on any python file (*.py) and choose "Open With" from the context menu and select "Choose Program..." . From there select "Python" if it appears, or click "Browse" and browse to "C: \Python25\python.exe", or the appropriate location if you have it installed somewhere else. Make sure to check the box next to "Always use the selected program to open this kind of file." Click "Ok". Matt From spython01 at gmail.com Tue Jul 22 10:41:25 2008 From: spython01 at gmail.com (Samir) Date: Tue, 22 Jul 2008 07:41:25 -0700 (PDT) Subject: Converting List of String to Integer References: Message-ID: <71c13b1e-dca2-4246-adc2-4879e8f47ad5@k30g2000hse.googlegroups.com> Wow! Thanks for all of the great additional feedback and responses since I last checked in. The help this group provides is amazing. I'm glad I found it. @Andrew -- Thanks for the clarification on the nested for loop and how to intrepret it. Also, thanks for the information on generators. I have never come across this before so I will look into it a bit more. The same thing goes for iPython. I have been looking for an IDE that comes with better debugging capabilities that the default Python shell. @dusans -- Just when I thought I couldn't simplify my code anymore, you provide come up with another way. Thank you. @ptn -- Thanks for the explanation between "append" and "extend". I guess I've gotten lazy and have always used "append", apparently even in situations where it may not be appropriate. Thanks again, everyone! Samir From stodge at gmail.com Wed Jul 9 11:39:09 2008 From: stodge at gmail.com (Stodge) Date: Wed, 9 Jul 2008 08:39:09 -0700 (PDT) Subject: Boost Python - C++ class' private static data blown away before accessing in Python? References: Message-ID: <8741a327-0f93-452d-8bd0-3260993d5e41@27g2000hsf.googlegroups.com> Thanks. Maybe it's a DLL boundary issue? I'll look into this too. On Jul 5, 11:14?pm, Giuseppe Ottaviano wrote: > > In Python, I retrive an Entity from the EntityList: > > > elist = EntityList() > > elist.append(Entity()) > > elist.append(Entity()) > > > entity = elist.get_at(0) > > > entity.foo() > > > But it crashes inside foo() as the private static data is empty; or > > rather the string array is empty. I know before that point that the > > private static data is valid when accessed earlier by the C++ code as > > the program works fine. It just won't work from Python, so somehow the > > private static data has been blown away but I can't work out where or > > why. > > Probably it is a problem of lifetime. What is the signature of append? ? > Who deletes the appended Entity in C++ code? > If append takes a raw pointer, Boost.Python copies the pointer but ? > destroys the Entity object because it is a temporary and its reference ? > count went to zero. So the pointer in the list is referring to a ? > destroyed object, which results in undefined behaviour. > > Did you have a look at the lifetime policies of Boost.Python? The ? > simplest way to workaround the problem is using const reference ? > arguments, and always use value semantics. If it can result in a ? > performance penalty, another simple way is using shared_ptr's, which ? > have their own reference count (different from the one in CPython ? > lib), but Boost.Python does the magic to make them work together. > > HTH, > Giuseppe From richie at entrian.com Fri Jul 4 07:14:20 2008 From: richie at entrian.com (Richie Hindle) Date: Fri, 04 Jul 2008 12:14:20 +0100 Subject: Bug in re.findall? In-Reply-To: References: Message-ID: Hi Marcin, > subnetlist="192.168.100.0 , 192.168.101.0" > ipre=re.compile("([0-9]{1,3}\.){3}[0-9]{1,3}") > > >>> ipre.findall(subnetlist) > ['100.', '101.'] Correct - it returns the most recently captured text for your sole group. > a=ipre.finditer(subnetlist) > >>> a.next().group() > '192.168.100.0' Also correct, because match.group() returns the whole of the matched text. If you wanted just your captured piece, you need this: > >>> a.next().group(1) > '100.' Hope that helps! -- Richie Hindle richie at entrian.com http://entrian.com From tjreedy at udel.edu Wed Jul 30 12:12:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jul 2008 12:12:52 -0400 Subject: interpreter vs. compiled In-Reply-To: References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> Message-ID: castironpi wrote: >> The current CPython VM does not compile code. CPython compiles Python code to bytecode for its CPython *hardware independent* VM using standard compiler methdods and tools (lexer, parser, code generator, and optimizer). That VM (interpreter) is written in portable-as-possible C, with machine/OS #ifdefs added as needed. > WHY NOT? Why doesn't CPython do it? 1. Portability: The Microsoft C# JIT compiler runs under Windows .NET on x86/amd64 and maybe it64 and what else? Just porting .NET to run 0n Linux on the same processors was/is a bit task. Does MONO have a JIT also? There is a JIT for Python: Psyco. It originally only worked on x86. I am not sure what else. It originated as a PhD project, working with CPython, and was developed further as part of PyPy, but I do not know if there is any current progress. Python VM runs on numerous platforms. 2. Money: C#, its JIT, and IronPython were and are funded by MS. Getting JIT right is hard and tedious. CPython is mostly a volunteer project. It is also the Python development platform. So it has to be simple enough for volunteers to pick up on its innards and for experimentation to be possible. Give the PSF more resources and tjr From wmcbrine at users.sf.net Wed Jul 30 12:57:35 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Wed, 30 Jul 2008 16:57:35 GMT Subject: like py2exe, but on a mac References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> Message-ID: <341kk.407$aA5.312@trnddc05> On Tue, 29 Jul 2008 12:24:49 -0700, Russell E. Owen wrote: > That is exactly what py2app does by default if you run py2app with the > system python. Thanks. I see that it* avoids the issue with Tk starting in the background that I get with Platypus, too. In fact, it looks like the bundlebuilder module is adequate for my needs. It does put in a version-specific #! line, but if I change that to #!/usr/bin/env python, the app still works, and it seems to me that it will work for any version of Python on OS 10.4, 10.5, and maybe 10.3. * I still haven't actually tried "it" (py2app), since I realized that I already had bundlebuilder, but I'm assuming it's the same in this respect. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From gnewsg at gmail.com Sun Jul 13 15:05:07 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sun, 13 Jul 2008 12:05:07 -0700 (PDT) Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> <487a3c0d$0$32256$9b622d9e@news.freenet.de> Message-ID: On 13 Lug, 19:31, "Martin v. L?wis" wrote: > > I understand that heapq is not that efficient to implement timeouts as > > I thought at first. > > It would have been perfect if there were functions to remove arbitrary > > elements withouth needing to re-heapify() the heap every time. > > It is efficient for that - you just need to use it correctly. > > To remove the nth element from a heap, replace it with the last element, > and then _siftup that element: > > def remove_at_index_n(heap, n): > ? ? if n == len(heap)-1: > ? ? ? ? return heap.pop() > ? ? result = heap[n] > ? ? heap[n] = heap.pop() > ? ? heapq._siftup(heap, n) > ? ? return result > > The time complexity for that operation is O(log(len(heap))). > > HTH, > Martin Thanks, by doing some quick benchamrks it seems 20% faster than using heapify(). And if instead of removing an element I'd want to change its value? E.g.: >>> heap = [0, 2, 1, 4, 5, 6, 7, 8, 9] >>> heapify(heap) >>> heap [0, 2, 1, 4, 5, 6, 7, 8, 9] >>> heap[4] = 12 --- Giampaolo http://code.google.com/p/pyftpdlib/ From kylotan at gmail.com Wed Jul 16 10:16:24 2008 From: kylotan at gmail.com (Ben Sizer) Date: Wed, 16 Jul 2008 07:16:24 -0700 (PDT) Subject: Best Python packages? Message-ID: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> Although the standard library in Python is great, there are undoubtedly some great packages available from 3rd parties, and I've encountered a few almost by accident. However, I don't know how a user would become aware of many of these. http://pypi.python.org/pypi/ presumably lists most of the decent ones, but there's a lot there and little indication as to quality or popularity - great if you know exactly what you need, but not so great for just browsing. I'd love to have some way of finding out what hidden gems are out there in the Python world which could make my development a lot easier. Any suggestions? -- Ben Sizer From robert.kern at gmail.com Wed Jul 23 21:51:34 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 23 Jul 2008 20:51:34 -0500 Subject: fill in 3D array In-Reply-To: <49fd3d80-d062-4c39-8274-f0b717486ad4@z66g2000hsc.googlegroups.com> References: <3180f972-f2d4-43ff-81de-bcdd0a2ef906@59g2000hsb.googlegroups.com> <49fd3d80-d062-4c39-8274-f0b717486ad4@z66g2000hsc.googlegroups.com> Message-ID: knielsen73 at gmail.com wrote: > On Jul 23, 9:18 pm, Robert Kern wrote: >> knielse... at gmail.com wrote: >>> Hi, >>> I am a python newbie, trying to convert my IDL scripts to python. I am >>> kind of stuck at the moment. I am reading in a 1-D data file with 2000 >>> data points. I need to put them in a 3-D array with size [10,10,20]. I >>> have defined the field array as arr = zeros((10,10,20)) but don't know >>> how to read the data into the array. >> I assume that you are using numpy. Use numpy.fromfile() and the .reshape() >> method. Assuming that your file is ASCII with numbers separated by whitespace: >> >> import numpy >> arr = numpy.fromfile(thefilename, sep=' ').reshape((10,10,20)) >> >> There is no need, in this case, to create an array before reading the data. >> >>> Also, I need to extract a slice of a 3-D array and tried a = >>> array_name(:,:,20) but that didn't work. >> Python uses [] brackets for indexing, not (). >> >> arr[:,:,20] > > Thanks, working like a charm. Great. If you have more numpy questions, you will probably want to ask them on the numpy mailing list instead of here. http://www.scipy.org/Mailing_Lists -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From pavlovevidence at gmail.com Wed Jul 30 01:24:47 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 22:24:47 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> Message-ID: <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> On Jul 29, 6:42 pm, Matthew Fitzgibbons wrote: > Carl Banks wrote: > > Much like in Steven D'Aprano's example, still the only actual code > > snippet I've seen, it seems that this can easily be done with a simple > > explicit test by having all no-advance filters return None and testing > > with "if x is not None". So it doesn't pass my criterion of being not > > replaceable with simple explicit test. > > > Maybe that's not workable for some reason. Perhaps if you'd post a > > code example that shows this, rather than just talking about it, you > > might be more persuasive. > > > Carl Banks > > -- > >http://mail.python.org/mailman/listinfo/python-list > > The no-advance filters have to return the object because I don't just > forget about it; I evaluate whether I pass it to the next filter or drop > it in a completely different queue for use in the next stage of the > operation. True means 'I'm ready to move on to the next stage,' False > means 'Do the filter thing some more.' I think I see what you're saying, and yeah I guess that could really take advantage of polymorphism between very different types. > Furthermore, the argument that I should just change my API to make a > 'simple test' work is not very convincing. I wasn't suggesting you change it: I was trying to ascertain whether it would have suffered much if you had written it with explicit tests in the first place, or if Python didn't even have magical booleans. > The natural, obvious way for > a filter to work is to pass through the data it operates on; why on > Earth would it return None? I want to DO something with the data. In > this case, make a decision about where to pass the data next. If you don't mind me asking: what do you do actually DO with a zero or empty list? > In Java, > to accomplish this I would have to do lots of introspection and value > checking (adding more any time I came up with a new kind of input), or > make a new kind of interface that gives me a method so I can do a > 'simple test' (including wrappers for ints and arrays and anything else > I decide to pass in down the road). But Python supports duck typing and > gives me a handy __nonzero__ method; I can rebind __nonzero__ in my > filters for my own classes, and ints and lists are handled how I want > them to be by default. So why jump through hoops instead of just using > 'if x'? Ah, so it's just happens to work. Still, just happening to work works. (shrug) > I don't have any postable code (it's in a half way state and I haven't > touched it for a while), but I'll see if I can't find the time to bang > something up to give you the gist. I wouldn't bother at this point. I was looking to see if someone could come up with something to disprove my belief on the polymorphic uselessness of "if x" relative to explicit tests, and if (as I anticipated) they did not, I could claim that "if x" is really just a glorified keystroke saver. But I now realize that the failure of this bunch doesn't prove anything. I don't think most people even realize why answering the question I asked would demonstrate the usefulness of "if x". Your example isn't exactly the smoking gun I was looking for, but I guess we'll have to admit that at least one usage will suffer for not having it. Carl Banks From fredrik at pythonware.com Wed Jul 23 06:34:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 12:34:15 +0200 Subject: logging into a website using python In-Reply-To: <338837.60152.qm@web51802.mail.re2.yahoo.com> References: <338837.60152.qm@web51802.mail.re2.yahoo.com> Message-ID: leo davis wrote: > I''m trying achieve the following by running python programs > > -login to a website > -automate filling up web forms http://twill.idyll.org/ From castironpi at gmail.com Thu Jul 24 00:35:38 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 23 Jul 2008 21:35:38 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <488765A7.7030400@v.loewis.de> Message-ID: <71a1a016-08f0-41e0-9bed-0c93d850b09e@u36g2000pro.googlegroups.com> On Jul 23, 12:08?pm, "Martin v. L?wis" wrote: > >> Oh. ?How is the stack represented? > > > As usual, as successive locations in memory. > > I have the impression that CPython uses the same stack C does. > > Actually, it doesn't (at least not for the evaluation stack). > > In CPython, when a Python function starts, the maximum depth of the > evaluation stack is known, but it depends on the specific function > (of course). So Python needs to allocate an array for the evaluation > stack with known size, but can't do so on the C stack (at least not > portably), since you can't allocate dynamically-sized array as > a local variable in C. > > So instead, pymalloc is used to allocate the evaluation stack, and > it is part of the frame object (so the entire frame object is allocated > in one chunk, and then split up into local variables and evaluation > stack. > > > While conceptually, CPython may put objects on the stack, I am pretty > > sure it actually stacks references (C pointers) to objects in heap memory. > > Correct. > > >> Does it keep track of which stack > >> positions (TOS, TOS1, etc.) are in what registers? > > > I am sure they are not in registers, just normal memory. > > Correct. As discussed above, they are located on the heap (making > Python's frame stack a spaghetti stack). > > Regards, > Martin Martin, I am curious and pursuing it as an independent project. I'd like to write a specialized function to allocate memory from an memory-mapped file instead of the heap. On Windows, to use CreateFileMapping and MapViewOfFile. The companion function, premalloc, would re-open an existing Python object from a handle. (It would need a name or index - > offset look-up.) svn.python.org is down, so I can't tell if Python already implements its own memory management, and if so how that would extrapolate to a byte-array allocated specifically. From duncan.booth at invalid.invalid Thu Jul 31 04:11:33 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Jul 2008 08:11:33 GMT Subject: How can I check nbr of cores of computer? References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> <4890acd6$0$17215$742ec2ed@news.sonic.net> <00a1215d$0$20313$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I don't expect that Python will have a built-in core-counting function. > You would probably need to ask the operating system. On Linux, you could > do this: > > import os > text = os.popen('cat /proc/cpuinfo').read() > > > How you would do it in Windows or Mac, I have no idea. > One way on windows: >>> import win32pdhutil >>> def howmanycores(): for i in range(9999): try: win32pdhutil.GetPerformanceAttributes("Processor(%d)" % i,"% Processor Time") except: break return i >>> print howmanycores() 2 -- Duncan Booth http://kupuguy.blogspot.com From digetl.try at gmail.com Sat Jul 26 06:02:36 2008 From: digetl.try at gmail.com (raja) Date: Sat, 26 Jul 2008 03:02:36 -0700 (PDT) Subject: "Gain 700% More Muscle" Message-ID: How To Gain Freaky Muscle Mass. As Seen On CNN. http://food-drinks.page.tl/ From digetl.try at gmail.com Sat Jul 26 06:04:14 2008 From: digetl.try at gmail.com (raja) Date: Sat, 26 Jul 2008 03:04:14 -0700 (PDT) Subject: Traditional cuisine Message-ID: with italian regional recipes with italian master chefs http://food-drinks.page.tl/ From tjreedy at udel.edu Tue Jul 22 01:37:04 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2008 01:37:04 -0400 Subject: Time Complexity of String Operations In-Reply-To: References: Message-ID: youtoo wrote: > It has been extensively discussed the time complexity (quadratic) of > string concatenation (due to string's immutability). > But what is: > > == the time complexity of string indexing? Is it constant? > == the time complexity of string slicing? Is it O(K) with K the > slice's length? > > How are strings stored in Python? As arrays? As linked lists? There is a Py wiki page on such issues. A wiki search should find it. From joe.p.cool at googlemail.com Sat Jul 5 04:01:23 2008 From: joe.p.cool at googlemail.com (Joe P. Cool) Date: Sat, 5 Jul 2008 01:01:23 -0700 (PDT) Subject: multi-platform browser embedding Message-ID: <2b76ba49-14c1-4e22-a08b-de3b910f4687@8g2000hse.googlegroups.com> I fiddled a little with pyGTK and was quite happy to discover gtkMozEmbed because I want to write an application for Linux and Windows with a powerful browser widget. Unfortunatly I couldnt find a way to make gtkMozEmbed work on Windows. Are there alternatives? I'm lazy so I prefer to download binaries for Windows :) but I don't mind building from source as long as I can use MinGW/Msys and avoid an incalculable odyssey through cryptic compiler errors and makefile surgery. Thanks in advance for your hints. -- Joe From jkugler at bigfoot.com Wed Jul 16 14:40:53 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Wed, 16 Jul 2008 10:40:53 -0800 Subject: Framework recommendations for web service? References: Message-ID: Phillip B Oldham wrote: > So, can anyone suggest a lightweight python framework which just does > the essentials? web.py is pretty slim (not to be confused with web2py). Pylons isn't very large, depending on what you call "essential." j From chris at percious.com Mon Jul 7 17:42:00 2008 From: chris at percious.com (percious) Date: Mon, 7 Jul 2008 14:42:00 -0700 (PDT) Subject: Python Agile Software Development Tools Screencasts Message-ID: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> Hi All, I started a new series about python on showmedo. Please feel free to take a look. They are as follows: virtualenv pastescript nosetests coverage Here is the link: http://showmedo.com/videos/video?name=2910000&fromSeriesID=291 Tutorial materials can be found at http://pythontutorials.googlecode.com cheers. -chris From maric at aristote.info Wed Jul 30 12:02:46 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 30 Jul 2008 18:02:46 +0200 Subject: Standard module for parsing emails? In-Reply-To: <48908EF7.7060301@gmail.com> References: <48908EF7.7060301@gmail.com> Message-ID: <200807301802.46574.maric@aristote.info> Le Wednesday 30 July 2008 17:55:35 Aspersieman, vous avez ?crit?: > For parsing the mails I would recommend pyparsing. Why ? email module is a great parser IMO. -- _____________ Maric Michaud From exarkun at divmod.com Tue Jul 29 11:00:53 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 29 Jul 2008 11:00:53 -0400 Subject: Continuous integration for Python projects In-Reply-To: Message-ID: <20080729150053.29191.647320859.divmod.quotient.8226@ohm> On Tue, 29 Jul 2008 07:47:35 -0700 (PDT), Hussein B wrote: >Hi. >Please correct my if I'm wrong but it seems to me that the major >continuous integration servers (Hudson, CruiseControl, TeamCity ..) >don't support Python based application. >It seems they mainly support Java, .NET and Ruby. >Can I use one of the previous listed servers for Python project? >Thanks. I haven't used CruiseControl or the other CIS you mention, but I suspect they can probably support Python programs. The CruiseControl docs suggest that it supports builder plugins which can do arbitrary things. However, one CIS written in Python (which can also handle arbitrary builds, not just builds of Python software) is buildbot: http://buildbot.net/ Jean-Paul From gagsl-py2 at yahoo.com.ar Thu Jul 17 19:44:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 17 Jul 2008 20:44:28 -0300 Subject: Pickle and wx.TextCtrl References: Message-ID: En Thu, 17 Jul 2008 09:40:29 -0300, escribi?: > The way you read the file is rather strange -mixing calls to readline and > pickle.load- I'd write the data using pickle.dump calls *only* and then > read it using pickle.load calls *only*. > > I used 13.1.7 Example of the Python Library Referencebut. Got an error > message when I did not have the readline() statement. The example doesn't have any readline(). Make sure you open the file in binary format ('wb' or 'rb'). If you have a list of objects: just write the list. It takes a single call to pickle.dump(), and later, a single call to picle.load() If you have too many objects and don't want to save/load all of them at once, write them one at a time using pickle.dump(element, output_file, -1), ending with a sentinel value (e.g. None): pickle.dump(None, ...) You may read them again using something like this: pfile = open(..., 'rb') while True: element = pickle.load(pfile) if element is None: break do_something_with(element) pfile.close() Ensure that you can save and load your data using a simple script, *before* writing the GUI. -- Gabriel Genellina From ptmcg at austin.rr.com Tue Jul 8 09:37:28 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 8 Jul 2008 06:37:28 -0700 (PDT) Subject: How to make python scripts .py executable, not bring up editor References: Message-ID: <71fe0699-6e09-4fbb-8145-bd1bbe3a0356@k30g2000hse.googlegroups.com> On Jul 7, 4:56?pm, korean_dave wrote: > From command Prompt, i type in a script, ?"tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? type: python tryme.py or: C:\Python24\python tryme.py -- Paul From spython01 at gmail.com Wed Jul 23 18:30:54 2008 From: spython01 at gmail.com (Samir) Date: Wed, 23 Jul 2008 15:30:54 -0700 (PDT) Subject: Request Help Debugging Program Message-ID: <898dfe7a-4133-4337-8243-f4936b8a8092@8g2000hse.googlegroups.com> Hi Everyone, In order to get a better command of Python, I have been trying to solve the puzzles on the Project Euler web site. I've made my way down to problem 21: http://projecteuler.net/index.php?section=problems&id=21 I've created a function (findSumOfDivisor), that when passed an integer, will return the sum of the argument's natural divisors. When tested in isolation, it seems to do what I intended. When I incorporate it into the larger program, however, I start getting run-time errors that for the life of me I cannot debug. My brute-force approach is to cycle through all of the integers to find the sum of their divisors and then enter the number (as key) and the sum of the divisors (as values) to a dictionary called "amicable". I only call findSumOfDivisor if the key:value combination does not already exist in the dictionary (hoping to save some time when I loop through 10,000 integers). Below is the code I have so far. I'm not completely certain if my logic will lead me to the correct solution, but that is a different matter. For now, the program seems to get through the first integer, 2, successfully, but errors out in line 20 when it tries to call the function. Apparently, Python doesn't like line 12 in the function where it returns the sum of the divisors. The code, which is best viewed using a fixed-font, is: from math import sqrt def findSumOfDivisor(n): divisor = [1] # start list of divisors at 1 for x in range(2, int(sqrt(n))+1): # search for possible divisors between 2 and sqrt(n) if n%x == 0: # if x is a divisor of n if ((n/x) == x): # and if x is the sqrt of n divisor.append(x) # add x to the list of divisors else: # otherwise divisor.append(x) # add x to the list of divisors divisor.append(n/x) # and add n/x to the list as well return sum(divisor) # return the sum of the divisors answer = [] # initialize answer to empty amicable = {1:0} # initialize amicable dictionary for 1 (sum is 0) for i in range(2,10): # loop through integers 2 through 9 if not amicable.has_key(i): # if i not found in amicable keys sum = findSumOfDivisor(i) # then find the sum of its divisors amicable[i] = sum # and add both to amicable dictionary else: # otherwise sum = amicable[i] # just get its sum if not amicable.has_key(sum): sum2 = findSumOfDivisor(sum) # if sum of i's divisors not in amicable keys amicable[sum] = sum2 # then add both to amicable dictionary else: # otherwise sum2 = amicable[sum] # just get its sum if i == sum2: # if i is amicable with sum2 answer.append(i) # append i to list of answers answer.append(sum2) # and append sum2 to list of answers print "amicable =", amicable print "answer =", answer The error I receive is: Traceback (most recent call last): File "pe_prob021.py", line 19, in sum = findSumOfDivisor(i) # then find the sum of its divisors File "pe_prob021.py", line 12, in findSumOfDivisor return sum(divisor) # return the sum of the divisors TypeError: 'int' object is not callable Even after cluttering the code with print statements every other line, I am completely lost. Does anyone know why I get this error? Thanks in advance. Samir From busybeejoey at yahoo.com Sat Jul 19 03:46:21 2008 From: busybeejoey at yahoo.com (busybeejoe) Date: Sat, 19 Jul 2008 00:46:21 -0700 (PDT) Subject: Buy/sell/trade your used stuff and promote your small business to people in california Message-ID: <2c15e366-aa91-4527-b294-239b351736ec@i36g2000prf.googlegroups.com> Buy/sell/trade your used stuff and promote your small business to people in california I created a NEW forum where you can buy/sell/trade your used stuff and for small business owners to promote their services to others in their area... Its a simple and easy way to let everyone know about your company and services you offer....and its free to join http://www.yansbb.com/ From bj_666 at gmx.net Fri Jul 25 11:28:38 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Jul 2008 15:28:38 GMT Subject: Calling external program from within python References: <6eu684F91muhU1@mid.uni-berlin.de> <6eu75mF92mqcU1@mid.uni-berlin.de> Message-ID: <6eu9p6F8v6ooU1@mid.uni-berlin.de> On Fri, 25 Jul 2008 08:13:55 -0700, oj wrote: > On Jul 25, 3:44?pm, "Diez B. Roggisch" wrote: >> Because usually if a program *prompts* the user to enter input (and that >> was what I read from the OP's post), one has to deal with pseudo >> terminals, not with stdin/out. > > How does the program writing some text before taking input change how > it takes input? It might not write the text before taking input because it is buffered. But if the controlling program waits for some text before sending input to the other program all hangs. > If it runs in a terminal and takes input from the user via keyboard, > as in the user types a response and presses enter, it's most likely > using stdin, in which case subprocess would be perfect. But buffering messes with the order of inputs and outputs. Buffering is different if you "talk" to a real (or pseudo) terminal or to a file or pipe and the calling program can't influence the called programs buffering except if it pretends to be a terminal, which pexpect does. Ciao, Marc 'BlackJack' Rintsch From deets at nospam.web.de Thu Jul 31 09:58:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 15:58:56 +0200 Subject: current week / weeks in year - best practice References: Message-ID: <6fdur9Fb0nvuU1@mid.uni-berlin.de> Aljosa Mohorovic wrote: > i use this to find out current week and total number of weeks for > current year: > now = datetime.now() > weeks_in_year = int(date(now.year, 12, 31).strftime("%W")) > current_week = int(date(now.year, now.month, now.day).strftime("%W")) > > is this the best way or is there a better way? Instead of datetime.now() use date.today(), which removes a lot of boilerplate. int(date.today().strftime("%W")) Apart from that, I think it's the way to go. Diez From kay.schluehr at gmx.net Thu Jul 24 06:40:59 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 24 Jul 2008 03:40:59 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> Message-ID: <32e12408-fc9f-4eb4-8b9d-fb7fa69bd2fc@f36g2000hsa.googlegroups.com> On 24 Jul., 11:40, Torsten Bronger wrote: > Hall?chen! > > Bruno Desthuilliers writes: > > [...] > > > How would you handle this case with an implicit 'self' : > > > class Foo(object): > > pass > > > def bar(self): > > print self > > > Foo.bar = bar > > Just like this. However, the compiler could add "self" to > non-decorated methods which are defined within "class". And $self2, $self3, ... to the object methods of nested classes and $cls2, $cls3, ... to the classmethods of those classes...? And when we are at it, here is a nice little exercise for the proponents of compiler magic. Write a decorator that takes and returns a method and prints the object the method is bound to. It's very easy to do it when the object is passed explicitely: def print_self(func): def call(self, *args, **kwd): print self return func(self, *args, **kwd) return call Conceptual clarity isn't always an entirely bad thing to have. From svenn.bjerkem at googlemail.com Mon Jul 21 07:09:33 2008 From: svenn.bjerkem at googlemail.com (Svenn Are Bjerkem) Date: Mon, 21 Jul 2008 04:09:33 -0700 (PDT) Subject: Parsing VHDL with python, where to start. Message-ID: Hi, I am in the need to write an application for PyQt to visualise the structure of a VHDL project I am working on. Looking for a sensible way to parse VHDL files and putting them into a data structure that PyQt can represent as a tree (or whatever the MVC is supporting) through search engines does not give me many hints. From what I know, VHDL is not a very easy language to parse. There seems to be a parser for perl available, but I do not know if it is wise to use a perl module as a template for writing something similar in python. My initial idea is to start simple and extend features in my application, but I fear that I may start off with wrong ideas how to parse and then code myself into a dead-end requiring myself to rewrite the whole application in order to get any further. I would start finding definitions of entities and the instantiations of these and build a tree from a set of external vhdl files stored in a file hierarchy. If somebody have a starting point where to get going with a task like this, I would be happy to know. -- kind regards, Svenn From cjw at ncf.ca Sat Jul 12 08:22:12 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 12 Jul 2008 08:22:12 -0400 Subject: Python 3.0 and removal of the 'string' module In-Reply-To: References: <87wsjtqiyo.fsf@benfinney.id.au> <87iqvdq6qz.fsf@benfinney.id.au> <487706b7$0$9695$9b622d9e@news.freenet.de> <87abgorgiv.fsf@benfinney.id.au> Message-ID: Benjamin wrote: > On Jul 11, 3:06 am, Ben Finney > wrote: >> "Martin v. L?wis" writes: >> >>>> This is rather disappointing. Is that entire page suspect? >>> All documentation about Python 3 is suspect until Python 3 gets >>> actually released (nobody can say for sure how the release will >>> look like in all details). >> Is there a better information source, then, for the current state of >> what's expected in Python 3.0? > > Look at the development docs. We try to keep them up to date: > http://doc.python.org/dev/3.0 >> -- It would be good if the PEP references in 'What's New' could be clickable. Colin W. From duncan.booth at invalid.invalid Sat Jul 12 13:36:01 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jul 2008 17:36:01 GMT Subject: strip() using strings instead of chars References: Message-ID: Christoph Zwerschke wrote: > Duncan Booth schrieb: >>> if url.startswith('http://'): >>> url = url[7:] >> >> If I came across this code I'd want to know why they weren't using >> urlparse.urlsplit()... > > Right, such code can have a smell since in the case of urls, file names, > config options etc. there are specialized functions available. But I'm > not sure whether the need for removing string prefix/suffixes in general > is really so rare that we shouldn't worry to offer a simpler solution. > One of the great things about Python is that it resists bloating the builtin classes with lots of methods that just seem like a good idea at the time. If a lot of people make a case for this function then it might get added, but I think it is unlikely given how simple it is to write a function to do this for yourself. From fredrik at pythonware.com Fri Jul 25 06:52:09 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 12:52:09 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: <4889AC5E.8090909@egenix.com> References: <1216966424.4685.1265275245@webmail.messagingengine.com> <4889AC5E.8090909@egenix.com> Message-ID: M.-A. Lemburg wrote: >> 4. Is there a stable version of IronPython compiled under a 64 bit >> version of .NET? Anyone have experience with such a beast? > > Can't comment on that one. Should that matter? Isn't IronPython pure CLR? From mgeorge at gmail.com Wed Jul 9 12:02:49 2008 From: mgeorge at gmail.com (mg) Date: Wed, 9 Jul 2008 09:02:49 -0700 (PDT) Subject: trouble building Python 2.5.1 on solaris 10 Message-ID: <7c490a26-b967-4d33-933f-c692d111201a@m73g2000hsh.googlegroups.com> When make gets to the _ctypes section, I am getting the following in my output: building '_ctypes' extension creating build/temp.solaris-2.10-i86pc-2.5/home/ecuser/Python-2.5.1/ Modules/_ctypes creating build/temp.solaris-2.10-i86pc-2.5/home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi creating build/temp.solaris-2.10-i86pc-2.5/home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi/src creating build/temp.solaris-2.10-i86pc-2.5/home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi/src/x86 gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/_ctypes.c -o build/temp.solaris-2.10-i86pc-2.5/home/ ecuser/Python-2.5.1/Modules/_ctypes/_ctypes.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/callbacks.c -o build/temp.solaris-2.10-i86pc-2.5/home/ ecuser/Python-2.5.1/Modules/_ctypes/callbacks.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/callproc.c -o build/temp.solaris-2.10-i86pc-2.5/home/ ecuser/Python-2.5.1/Modules/_ctypes/callproc.o /home/ecuser/Python-2.5.1/Modules/_ctypes/callproc.c: In function `_CallProc': /home/ecuser/Python-2.5.1/Modules/_ctypes/callproc.c:918: warning: implicit declaration of function `alloca' gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/stgdict.c -o build/temp.solaris-2.10-i86pc-2.5/home/ ecuser/Python-2.5.1/Modules/_ctypes/stgdict.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/cfield.c -o build/temp.solaris-2.10-i86pc-2.5/home/ ecuser/Python-2.5.1/Modules/_ctypes/cfield.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/malloc_closure.c -o build/temp.solaris-2.10-i86pc-2.5/ home/ecuser/Python-2.5.1/Modules/_ctypes/malloc_closure.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi/src/prep_cif.c -o build/temp.solaris-2.10- i86pc-2.5/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/src/ prep_cif.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi/src/x86/ffi64.c -o build/temp.solaris-2.10- i86pc-2.5/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ ffi64.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi/src/x86/unix64.S -o build/temp.solaris-2.10- i86pc-2.5/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ unix64.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi/src/x86/ffi.c -o build/temp.solaris-2.10- i86pc-2.5/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ ffi.o /home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ffi.c:177: warning: function declaration isn't a prototype /home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ffi.c:194: warning: function declaration isn't a prototype gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi/src/x86/sysv.S -o build/temp.solaris-2.10- i86pc-2.5/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ sysv.o Assembler: "/var/tmp//ccbsqiOB.s", line 236 : Syntax error Near line: ".section .note.GNU-stack,"",%progbits" my configure looks like this: ./configure --prefix=/home/ecuser/dev -- with-gcc --with-system-ffi any ideas? From castironpi at gmail.com Thu Jul 24 00:07:33 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 23 Jul 2008 21:07:33 -0700 (PDT) Subject: problem doing unpickle in an exec statement References: Message-ID: On Jul 23, 6:01?pm, Danny Shevitz wrote: > Howdy, > > In my app I need to exec user text that defines a function. I want this > function to unpickle an object. Pickle breaks because it is looking for > the object definition that isn't in the calling namespace. > > I have mocked up a simple example that shows the problem. Run this > first code (from create_pickle.py) to create the pickle. > > create_pickle.py: (run this first) > > ############################################# > import cPickle > > # the pickle file name > file_name = 'd:\\temp\\test1.pickle' > > # define a class > class Tree(object): > ? ? ? ? pass > > def main(): > ? ? ? ? # instantiate ? > ? ? ? ? t = Tree() > > ? ? ? ? # create the sweet pickle > ? ? ? ? fp = open(file_name, 'wb') > ? ? ? ? cPickle.dump(t, fp) > ? ? ? ? fp.close() > > ? ? ? ? # try to unpickle directly > ? ? ? ? fp = open(file_name, 'rb') > ? ? ? ? result = cPickle.load(fp) > ? ? ? ? fp.close() > ? ? ? ? print "unpickling directly works just fine, result = ", result > > if __name__=='__main__': > ? ? ? ? main() > ############################################# > > run this second: > > exec_pickle.py > ############################################# > # this file shows a problem with sweet pickle in an exec statement > > # the pickle file name > file_name = 'd:\\temp\\test1.pickle' > > # code to be turned into a function > code_text = ''' > def include(): > ? print "this works!" > ''' > > # a function for creating functions > def create_fun(code_text): > ? ? ? ? clean_dict = {} > ? ? ? ? exec code_text in clean_dict > ? ? ? ? return clean_dict['include'] > > # include_fun is a bona fide function > include_fun = create_fun(code_text) > > # this works > include_fun() > > # now try to load the pickle in an exec statement > code_text = ''' > def include(file_name): > ? print "processing file_name: ", file_name > ? import cPickle > ? fp = open(file_name, "rb") > ? result = cPickle.load(fp) > ? fp.close() > ? print "result = ", result > ''' > > # create the new include_fun > include_fun = create_fun(code_text) > > # run it > include_fun(file_name) > > ############################################# > > Can anyone enlighten me what I need to do to exec_pickle.py > to get this to work? > > thanks, > Danny Hi, It works if you paste # define a class class Tree(object): pass into exec_pickle.py. There are inherent dilemmas in pickling instances of non-primitive types, such as definition location, and change in definition across versions. How does 'class Tree' fit in to your design module? From user at domain.invalid Wed Jul 16 13:06:15 2008 From: user at domain.invalid (Dennis Cote) Date: Wed, 16 Jul 2008 17:06:15 GMT Subject: Best Python packages? In-Reply-To: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> Message-ID: Ben Sizer wrote: > I'd love to have some way of finding out what hidden gems are out > there in the Python world If they were easy to find, they wouldn't be "hidden gems". :-) Dennis Cote From philr at aspexconsulting.co.nz Mon Jul 21 16:48:19 2008 From: philr at aspexconsulting.co.nz (Phil Runciman) Date: Tue, 22 Jul 2008 08:48:19 +1200 Subject: Python Written in C? In-Reply-To: <5e098db8-38f0-42ac-9cb7-9eada66f9a00@z72g2000hsb.googlegroups.com> Message-ID: On 20 jul, 19:50, giveitawhril2... at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > > So I was suspecting the Python compiler or interpreter is written in a ".. if Python is so hot.." Python represents progress not the ultimate goal. Thank goodness we are continuing to learn from past mistakes. All compilers and interpreters started out being written in another language. You do not help us by stating the obvious. This is even true of the interpreter in your own brain that processes English. IMHO The latter still has some bugs in it. ;-) From __peter__ at web.de Thu Jul 24 03:13:59 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 Jul 2008 09:13:59 +0200 Subject: problem doing unpickle in an exec statement References: Message-ID: Danny Shevitz wrote: > Howdy, > > In my app I need to exec user text that defines a function. I want this > function to unpickle an object. Pickle breaks because it is looking for > the object definition that isn't in the calling namespace. > > I have mocked up a simple example that shows the problem. Run this > first code (from create_pickle.py) to create the pickle. > > create_pickle.py: (run this first) > > ############################################# > import cPickle > > # the pickle file name > file_name = 'd:\\temp\\test1.pickle' > > # define a class > class Tree(object): > pass > > > def main(): > # instantiate > t = Tree() > > # create the sweet pickle > fp = open(file_name, 'wb') > cPickle.dump(t, fp) > fp.close() > > # try to unpickle directly > fp = open(file_name, 'rb') > result = cPickle.load(fp) > fp.close() > print "unpickling directly works just fine, result = ", result > > if __name__=='__main__': > main() > ############################################# > > run this second: > > exec_pickle.py > ############################################# > # this file shows a problem with sweet pickle in an exec statement > > # the pickle file name > file_name = 'd:\\temp\\test1.pickle' > > # code to be turned into a function > code_text = ''' > def include(): > print "this works!" > ''' > > # a function for creating functions > def create_fun(code_text): > clean_dict = {} > exec code_text in clean_dict > return clean_dict['include'] > > # include_fun is a bona fide function > include_fun = create_fun(code_text) > > # this works > include_fun() > > > # now try to load the pickle in an exec statement > code_text = ''' > def include(file_name): > print "processing file_name: ", file_name > import cPickle > fp = open(file_name, "rb") > result = cPickle.load(fp) > fp.close() > print "result = ", result > ''' > > # create the new include_fun > include_fun = create_fun(code_text) > > # run it > include_fun(file_name) > > ############################################# > > Can anyone enlighten me what I need to do to exec_pickle.py > to get this to work? Pickling saves the name of the module and the class (and of course the instance data). Because you put the class in your main script the module name is __main__, and when you unpickle later pickle imports __main__ which unfortunately is now a different script that doesn't contain the/a Tree class. To solve that problem put the Tree class in a separate module, say tree.py, that can be imported by both create_pickle.py and exec_pickle.py. You only need an explicit from tree import Tree in create_pickle. Peter From bgeddy at home.havin.a.break Thu Jul 17 10:47:34 2008 From: bgeddy at home.havin.a.break (bgeddy) Date: Thu, 17 Jul 2008 15:47:34 +0100 Subject: storing references instead of copies in a dictionary In-Reply-To: References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: mk wrote: > Calvin Spealman wrote: >> To your actual problem... Why do you wanna do this anyway? If you want >> to change the function in the dictionary, why don't you simply define >> the functions you'll want to use, and change the one you have bound to >> the key in the dictionary when you want to change it? In other words, >> define them all at once, and then just d['1'] = new_f1. What is wrong >> with that? > > Well, basically nothing except I need to remember I have to do that. > > Suppose one does that frequently in a program. It becomes tedious. I > think I will define some helper function then: > > >>> def helper(fundict, newfun): > ... fundict[newfun.func_name] = newfun > ... > > _If_ there were some shorter and still "proper" way to do it, I'd use > it. If not, no big deal. > >> For completeness: >> >> def new_f1(arg): >> return "NEW f1 " + arg >> f1.func_code = new_f1.func_code >> >> Don't use that unless you really have to and I nearly promise that you >> don't. > > I promise I won't use it. :-) It seems like a 'wrong thing to do'. > > Well it's probably totally "non pythonic" but this does what you want: def f2(arg): return "f2 "+arg def f1(arg): return "f1 "+arg a={"1":"f1","2":"f2"} print [eval(x[1])(x[0]) for x in a.items()] def f2(arg): return "New f2 "+arg print [eval(x[1])(x[0]) for x in a.items()] Don't know if this is any use to you.. From hat at se-162.se.wtb.tue.nl Mon Jul 7 05:55:25 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 07 Jul 2008 11:55:25 +0200 Subject: yo... References: Message-ID: On 2008-07-07, abhishek wrote: > hey guys...me nu 2 python yo...help me...by da way...jus joined > in....thanks Ask a specific question and you may get an answer. If you want an answer from me, it helps *a lot* if you write full english sentences (starting with a capital letter and ending with a single '.') rather than the short-hand you seem to favor. (It costs me a lot of effort to decipher). Sincerely, Albert From martin at v.loewis.de Fri Jul 18 19:32:23 2008 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 19 Jul 2008 01:32:23 +0200 Subject: Change PC to Win or Windows In-Reply-To: References: Message-ID: <48812807.3000100@v.loewis.de> > Calling Windows PC seems to be something that Apple did so they would > not have to directly mention Windows. Could all the places that say PC > that are not referring to Personal Computers in general be changed to > Win or Windows. That's bikeshedding. If the name stops you from building your own binaries, you should use prebuilt binaries, or read the documentation. Regards, Martin From gros_bedo at hotmail.com Wed Jul 9 18:51:18 2008 From: gros_bedo at hotmail.com (Gros Bedo) Date: Thu, 10 Jul 2008 00:51:18 +0200 Subject: Terminate a python script from linux shell / bash script Message-ID: Hello :-) I have a question about Python and Linux shell. I have a python program which is permanently resident in the end-user system. I'm currently producing a RPM package, and it works nicely. The problem is that when I uninstall it, my program keeps running in the background, even if the files are deleted. I know I can terminate python shell directly, but this is not a good idea because the end-user may be working with another important python application, and would be very angry if mine would close everything that is using python shell. So, is there a way from the Linux shell or a bash script to terminate just one specific Python script ? _________________________________________________________________ Votre contact a choisi Hotmail, l'e-mail nouvelle g?n?ration. Cr?ez un compte. http://www.windowslive.fr/hotmail/default.asp From tjreedy at udel.edu Fri Jul 25 18:07:59 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Jul 2008 18:07:59 -0400 Subject: Quesion on class.attributes assignment In-Reply-To: References: Message-ID: John Hanks wrote: > Hi, > > I am reading a python program now but I just cannot understand how the > values of class attributes are assigned and changed. Here is the > original code url: > http://agolb.blogspot.com/2006/01/sudoku-solver-in-python.html > Here I am concerned is how attribute matrix.rows is changed. Through pdb > debugging, I can see in line 97, once "self.solutions = set((val,))" is > executed, cell.row and matrix.rows will be updated. But I did not see > any assignment codes here. How could this change happen then? Thanks a lot! Newsreaders do not typically have line counters. I presume you are referring to def setSolution(self, val): self.solved = True self.solutions = set((val,)) self.matrix.changed = True for other in self.row+self.col+self.submatrix: if other is self: continue if other.solutions == self.solutions: raise DeadEnd() other.delSolutions(self.solutions) First, self is an instance of the class, so these are all instance attributes, not class attributes. The difference is important. As to your question, the last line mutates (modifies, updates) each member of self.row, self.col, and self.submatrix that is not self itself. The method delSolutions has the actual target rebindings. tjr From mensanator at aol.com Fri Jul 11 19:20:47 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 11 Jul 2008 16:20:47 -0700 (PDT) Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: <2a13cea6-5144-4f37-af8a-607601f923a9@79g2000hsk.googlegroups.com> On Jul 11, 5:34?pm, Denis Kasak wrote: > On Sat, Jul 12, 2008 at 12:22 AM, kdt wrote: > > ?> Hi all, > ?> > ?> Can someone please explain to me why the following evaluates as false? > ?> > ?>>>>list=['a','n','n','a'] > ?>>>>list==list.reverse() > ?>>>>False > ?> > ?> I'm stumped :s > > Read the documentation on list.reverse(). > > Basically, it reverses the list in place, so it modifies the list which > called it. It does not return a /new/ list which is a reversed version > of the original, as you expected it to. Since it doesn't return anything > explicitly, Python makes it return None. Hence, the comparison you are > doing is between the original list and a None, which is False, naturally. > Try this: > > spam = ['a', 'n', 'n', 'a'] > eggs = spam[:] > if spam.reverse() == eggs: > ? ? print "Palindrome" You could also do >>> spam = ['a','n','n','a'] >>> if spam == [i for i in reversed(spam)]: print "Palindrome" > > Also, 'list' is a really bad name for a list, since this is the name of > the builtin type object for the list type. > > -- > Denis Kasak From zondo42 at googlemail.com Fri Jul 18 10:44:16 2008 From: zondo42 at googlemail.com (Glenn Hutchings) Date: Fri, 18 Jul 2008 15:44:16 +0100 Subject: [ANN] PyStar 0.1 -- A* graph search algorithm Message-ID: Announcing PyStar, a python module implementing the A* graph search algorithm. Available under the GPL, you can find it at http://fluffybunny.memebot.com/pystar.html I tried to find a decent Python version of this on the Interweb, but the only one I found (http://arainyday.se/projects/python/AStar) was just a bit too cryptic for me to understand and use. So I knocked this up from pseudocode on the Wikipedia A* page, and rewrote the AStar demo program in Tkinter. Comments, bug reports, big wads of cash, etc., are welcome. From kyosohma at gmail.com Wed Jul 23 16:18:35 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 23 Jul 2008 13:18:35 -0700 (PDT) Subject: need thumbnail from video References: Message-ID: <853c0f7d-0243-4829-8149-29afce203f40@d1g2000hsg.googlegroups.com> On Jul 22, 8:54?am, John Fabiani wrote: > Hi, > I need a py tool that will provide a thumbnail (bmp?) from a video (avi, > wmv) that will be cross platform (linux, windows). ?Research has provided > pymedia for Linux but I haven't found anything for windows. ?Hopefully, > someone has had to do this in the past and knows what has to be done. > > Thanks in Advance, > Johnf PyMedia works on Windows too, according to their website. Mike From steve at REMOVE-THIS-cybersource.com.au Tue Jul 29 19:59:50 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 23:59:50 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> Message-ID: <009faa6f$0$20313$c3e8da3@news.astraweb.com> On Tue, 29 Jul 2008 13:53:07 -0700, Carl Banks wrote: > Bzzt. "if len(x)!=0" is a simple explicit that would work for this > class and all built-in containers. (Or should--Steven D'Aprano's > objections notwithstanding, any reasonable container type should support > this invariant. What's the length of an empty list with a sentinel at the end? What's the length of a binary tree? Does it even have a length? What's the length of a constant-sized table where each position might be in use or free? You're making assumptions about what an empty object "should" look like. I say, just ask the object if it's empty, don't try to guess how you would find out. Maybe the object carries around a flag x.isempty. Who knows? Why do you care? You're basing your code on implementation details. That should be avoided whenever possible. [...] > Once again, I'm invoking the contraint against simply using x in a > boolean context, So, to put it another way... you want us to give you an example of using x in a boolean context, but you're excluding any example where we use x in a boolean context. Right-o, I've had enough of your trolling. I'm out of here. -- Steven From desothier at yahoo.com Wed Jul 9 06:30:22 2008 From: desothier at yahoo.com (antar2) Date: Wed, 9 Jul 2008 03:30:22 -0700 (PDT) Subject: start reading from certain line Message-ID: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> I am a starter in python and would like to write a program that reads lines starting with a line that contains a certain word. For example the program starts reading the program when a line is encountered that contains 'item 1' The weather is nice Item 1 We will go to the seaside ... Only the lines coming after Item 1 should be read Thanks! From deets at nospam.web.de Mon Jul 7 07:55:14 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 07 Jul 2008 13:55:14 +0200 Subject: Cross Compiler for Python? References: Message-ID: <6deeidF271g5U2@mid.uni-berlin.de> Hendrik van Rooyen wrote: > Up to now, I have been innocently using the vanilla python > that comes with the Linux distribution (Suse in my case). > > For the past few days, I have been playing with a little > device called an eBox - it is basically a 486 with 128Mb > memory, and a 1Gig pcmcia flash drive. > > We want to try to use this as an industrial controller, so > I want to load python onto it. > > So I downloaded the sources, and got them into the box, > over its ethernet connection. > > Then I got stymied - the configure script will not run, > because the "distribution" has no C compiler - it is > basically a kernel, and Busybox, with precious little else. > > So I googled, and I found mobile python, and portable python, > both aimed at windows. - no good to me. > > Adding "embedded" to the Google string is also useless, > as it basically brings up instances of embedding the > interpreter into another app, not for small processors. > > So how does one do a compile of python on one machine > aimed at another one? - All I want is a vanilla installation > with the stuff in all the usual places. And just to make matters > interesting, the two Linux boxes I have available are both > 64 bit dual core animals, one Intel, one AMD... > > I don't need much more than the interpreter, sys, os, sockets > and ctypes. > > Alternatively, where can one find a set of binaries for > 32 bit Linux? > > Looking for some sane advice please. Look at the gumstix project, they do have a cross-compiled python in there. You should be able to get an idea on how to do that yourself. It involves (or at least did back then) a bit of trickery as the build-process of python uses the freshly created interpreter to pre-compile modules. But it is possible. Diez From gary at byoteki.com Mon Jul 28 20:56:16 2008 From: gary at byoteki.com (Gary Josack) Date: Mon, 28 Jul 2008 20:56:16 -0400 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: <488DF599.7070904@activestate.com> References: <487E2BCE.30108@hughes.net> <488A2E72.6030802@activestate.com> <488D53AB.7090300@gmail.com> <488DF599.7070904@activestate.com> Message-ID: <488E6AB0.4000109@byoteki.com> Trent Mick wrote: > Manuel Vazquez Acosta wrote: >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> Just test for maxint value: >> >> from sys import maxint >> if maxint >> 33: >> print "more than 32 bits" # probably 64 >> else: >> print "32 bits" > > I believe that was already suggested in this thread. That test will > just tell you if the Python *build* is 32-bit or 64-bit. If the answer > is 32-bit, then that doesn't tell you if this is a 32-bit Python > running on a 64-bit OS. > > Trent > have you tried platform.architecture()? From paul at subsignal.org Sat Jul 5 06:39:34 2008 From: paul at subsignal.org (paul) Date: Sat, 05 Jul 2008 12:39:34 +0200 Subject: Python XML-RPC Server with clientside Javascript In-Reply-To: References: Message-ID: akineko schrieb: > Hello everyone, > > I have used Python SimpleXMLRPCServer to expose several methods to be > used. > My Python script creates a free-standing server and not a CGI script. > I have tested its exposed methods using the following Python script: > > import xmlrpclib > s = xmlrpclib.ServerProxy('http://localhost:8765') > print s.my_method() > > I tested all methods one by one and they are working as I intended. > > Now, I want to use those exposed methods from a static html file > (without any web server) using client side javascript. (i.e. Open > File... from the browser (or file://...) ) > > I found many XML-RPC examples with javascript but all of them I found > assume XML-RPC services to be deliver from a web server, such as > Apache, as a CGI. I'd think this has nothing to do with CGI vs. "free-standing", the client couldn't tell the difference anyway. It looks like you're running in the "same origin" javascript security restriction enforced by the browser. That is, the origin of your javascript is file://... and you're trying to access http://localhost:8765. This is not allowed. hth Paul From varun.consit at gmail.com Thu Jul 3 15:16:25 2008 From: varun.consit at gmail.com (varun chadha) Date: Thu, 3 Jul 2008 12:16:25 -0700 (PDT) Subject: controlling the windows Message-ID: <153e45a5-a161-4305-be6f-0fd56aee37e0@f1g2000prb.googlegroups.com> i am developing an application using Tkinter where 'next' button takes to another window and removes the first one from screen and 'back' button bring me back to previous window and so on. though i am able to move from one window to another but is unable to remove the previous one from the screen. does anybody have a idea how to do away with this problem. From jkrukoff at ltgc.com Mon Jul 28 19:26:12 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Mon, 28 Jul 2008 17:26:12 -0600 Subject: seemingly simple list indexing problem In-Reply-To: <1ad9234a-6bba-48ce-ad40-ea0aeabce492@79g2000hsk.googlegroups.com> References: <1ad9234a-6bba-48ce-ad40-ea0aeabce492@79g2000hsk.googlegroups.com> Message-ID: <1217287572.4123.118.camel@jmk> On Mon, 2008-07-28 at 16:00 -0700, iu2 wrote: > On Jul 29, 12:10 am, John Krukoff wrote: > > On Mon, 2008-07-28 at 16:24 -0500, Ervan Ensis wrote: > > > My programming skills are pretty rusty and I'm just learning Python so > > > this problem is giving me trouble. > > > > > I have a list like [108, 58, 68]. I want to return the sorted indices > > > of these items in the same order as the original list. So I should > > > return [2, 0, 1] > > > > > For a list that's already in order, I'll just return the indices, i.e. > > > [56, 66, 76] should return [0, 1, 2] > > > > > Any help would be appreciated. > > > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > > If your lists aren't so large that memory is an issue, this might be a > > good place for a variation of decorate, sort, undecorate. > > > > >>> listToSort = [ 108, 58, 68 ] > > >>> decorated = [ ( data, index ) for index, data in > > > > enumerate( listToSort ) ]>>> decorated > > > > [(108, 0), (58, 1), (68, 2)]>>> result = [ None, ] * len( listToSort ) > > >>> for sortedIndex, ( ignoredValue, originalIndex ) in > > > > enumerate( sorted( decorated ) ): > > ... result[ originalIndex ] = sortedIndex > > ...>>> result > > > > [2, 0, 1] > > > > -- > > John Krukoff > > Land Title Guarantee Company > > Inspired by your idea and the above one, here is another try: > > >>> a0 = [108, 58, 68, 108, 58] > >>> a1 = [(x, y) for x, y in enumerate(a0)] You know this line is a no-op, right? > >>> a1 > [(0, 108), (1, 58), (2, 68), (3, 108), (4, 58)] > >>> a2 = sorted(a1, lambda x, y: cmp(x[1], y[1])) If you're going to do the unpacking here for the sort, just use enumerate directly. Since this is a simple case, should use the key parameter instead of the cmp parameter for speed. Can also use the operator module to avoid a bit of lambda overhead: >>> import operator >>> a2 = sorted( enumerate( a0 ), key = operator.itemgetter( 1 ) ) > >>> a2 > [(1, 58), (4, 58), (2, 68), (0, 108), (3, 108)] > >>> a3 = [a2.index(x) for x in a1] > >>> a3 > [3, 0, 2, 4, 1] > > The idea is to make each item unique (by making it a tuple), and then > apply the naive solution. > > -- > http://mail.python.org/mailman/listinfo/python-list Using index is still kinda evil, due to the exponential time required since you're rescanning half the list (on average) to find each index value. -- John Krukoff Land Title Guarantee Company From yuxi at ece.gatech.edu Mon Jul 21 01:31:21 2008 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Mon, 21 Jul 2008 01:31:21 -0400 Subject: Python Written in C? In-Reply-To: References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> Message-ID: Grant Edwards wrote: > On 2008-07-21, Dan Upton wrote: > >>>> REAL WORLD programmers who want to be generally useful go and >>>> learn C#. >>> No: Real programmers first eat a quiche and then return to >>> their Pascal programming. >> Bah, new-fangled languages like Pascal... Real programmers >> write Fortran. > > Using punch-cards and paper-tape. Real programmers can edit > their programs with a pointy stick and some home-made > sticky-tape. > Bah. Butterflies! http://xkcd.com/378/ From patf at well.com Mon Jul 28 19:41:36 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 16:41:36 -0700 (PDT) Subject: Download excel file from web? References: <6f6vhlFa7anrU1@mid.uni-berlin.de> <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> <19fa0bb2-e101-47c9-84d4-1bf05d08ba39@b2g2000prf.googlegroups.com> Message-ID: On Jul 28, 4:20?pm, "Guilherme Polo" wrote: > On Mon, Jul 28, 2008 at 8:04 PM, p... at well.com wrote: > > On Jul 28, 3:52 pm, "Guilherme Polo" wrote: > >> On Mon, Jul 28, 2008 at 7:43 PM, p... at well.com wrote: > >> > On Jul 28, 3:33 pm, "p... at well.com" wrote: > >> >> On Jul 28, 3:29 pm, "Diez B. Roggisch" wrote: > > >> >> > p... at well.com schrieb: > > >> >> > > On Jul 28, 3:00 pm, "p... at well.com" wrote: > >> >> > >> Hi - experienced programmer but this is my first Python program. > > >> >> > >> This URL will retrieve an excel spreadsheet containing (that day's) > >> >> > >> msci stock index returns. > > >> >> > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > >> >> > >> Want to write python to download and save the file. > > >> >> > >> So far I've arrived at this: > > >> >> > >> [quote] > >> >> > >> # import pdb > >> >> > >> import urllib2 > >> >> > >> from win32com.client import Dispatch > > >> >> > >> xlApp = Dispatch("Excel.Application") > > >> >> > >> # test 1 > >> >> > >> # xlApp.Workbooks.Add() > >> >> > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > >> >> > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > >> >> > >> # xlBook = xlApp.ActiveWorkbook > >> >> > >> # xlBook.SaveAs(Filename='C:\\test.xls') > > >> >> > >> # pdb.set_trace() > >> >> > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> >> > >> excel? > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional') > >> >> > >> # test 2 - returns check = False > >> >> > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > >> >> > >> indexperf/excel? > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > >> >> > >> xlApp = response.fp > >> >> > >> print(response.fp.name) > >> >> > >> print(xlApp.name) > >> >> > >> xlApp.write > >> >> > >> xlApp.Close > >> >> > >> [/quote] > > >> >> > > Woops hit Send when I wanted Preview. ?Looks like the html [quote] tag > >> >> > > doesn't work from groups.google.com (nice). > > >> >> > > Anway, in test 1 above, I determined how to instantiate an excel > >> >> > > object; put some stuff in it; then save to disk. > > >> >> > > So, in theory, I'm retrieving my excel spreadsheet with > > >> >> > > response = urllib2.urlopen() > > >> >> > > Except what then do I do with this? > > >> >> > > Well for one read some of the urllib2 documentation and found the > >> >> > > Request class with the method has_data() on it. ?It returns False. > >> >> > > Hmm that's not encouraging. > > >> >> > > I supposed the trick to understand what urllib2.urlopen is returning > >> >> > > to me; rummage around in there; and hopefully find my excel file. > > >> >> > > I use pdb to debug. ?This is interesting: > > >> >> > > (Pdb) dir(response) > >> >> > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > >> >> > > 'code', ' > >> >> > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > >> >> > > 'readline', ' > >> >> > > readlines', 'url'] > >> >> > > (Pdb) > > >> >> > > I suppose the members with __*_ are methods; and the names without the > >> >> > > underbars are attributes (variables) (?). > > >> >> > No, these are the names of all attributes and methods. read is a method, > >> >> > for example. > > >> >> right - I got it backwards. > > >> >> > > Or maybe this isn't at all the right direction to take (maybe there > >> >> > > are much better modules to do this stuff). ?Would be happy to learn if > >> >> > > that's the case (and if that gets the job done for me). > > >> >> > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty > >> >> > clear on this: > > >> >> > """ > >> >> > This function returns a file-like object with two additional methods: > >> >> > """ > > >> >> > And then for file-like objects: > > >> >> >http://docs.python.org/lib/bltin-file-objects.html > > >> >> > """ > >> >> > read( ? [size]) > >> >> > ? ? ?Read at most size bytes from the file (less if the read hits EOF > >> >> > before obtaining size bytes). If the size argument is negative or > >> >> > omitted, read all data until EOF is reached. The bytes are returned as a > >> >> > string object. An empty string is returned when EOF is encountered > >> >> > immediately. (For certain files, like ttys, it makes sense to continue > >> >> > reading after an EOF is hit.) Note that this method may call the > >> >> > underlying C function fread() more than once in an effort to acquire as > >> >> > close to size bytes as possible. Also note that when in non-blocking > >> >> > mode, less data than what was requested may be returned, even if no size > >> >> > parameter was given. > >> >> > """ > > >> >> > Diez > > >> >> Just stumbled upon .read: > > >> >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> >> excel? > >> >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> >> +25%2C+2008&export=Excel_IEIPerfRegional').read > > >> >> Now the question is: what to do with this? ?I'll look at the > >> >> documentation that you point to. > > >> >> thanx - pat > > >> > Or rather (next iteration): > > >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > excel? > >> > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > >> > The file is generally something like 26 KB so specifying 1,000,000 > >> > seems like a good idea (first approximation). > > >> > And then when I do: > > >> > print(response) > > >> > I get a whole lot of garbage (and some non-garbage), so I know I'm > >> > onto something. > > >> > When I read the .read documentation further, it says that read() has > >> > returned the data as a string object. ?Now - how do I convince Python > >> > that the string object is in fact an excel file - and save it to disk? > > >> You don't need to convince Python, just write it to a file. > >> More reading for you:http://docs.python.org/tut/node9.html > > >> > pat > >> > -- > >> >http://mail.python.org/mailman/listinfo/python-list > > >> -- > >> -- Guilherme H. Polo Goncalves > > > OK: > > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > > excel? > > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > # print(response) > > f = open("c:\\msci.xls",'w') > > f.write(response) > > I would initially change that to: > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&...) > > f = open("c:\\msci.xls", "wb") > for line in response: > ? ? f.write(line) > f.close() > > and then.. > > > > > OK this makes the file, and there's a c:\msci.xls in place and it's > > about the right size. But whether I make the second param to open 'w' > > or 'wb', when I try to open msci.xls from the Windows file explorer, > > excel tells me that the file is corrupted. > > try it. > > > > > pat > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves A simple f.write(response) does work (click on a single row in Excel and you get a single row). But I can see that what you recommend Guilherme is probably safer - thanx. pat From vinay_sajip at yahoo.co.uk Mon Jul 14 09:58:46 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Mon, 14 Jul 2008 06:58:46 -0700 (PDT) Subject: logging via SocketHandler and TCPserver References: Message-ID: <81929250-449b-4686-acf3-dcc0095e341a@d1g2000hsg.googlegroups.com> On Jul 13, 9:25 pm, Larry Bates wrote: > Every time I look at theloggingmodule (up until now) I've given up and > continue to use my home-grown logger that I've been using for years. I'm not > giving up this time ;-) > > I find that I REALLY need to be able to monitor LOTS of running > programs/processes and thought it would be nice to have them use SocketHandlerloggingand then I would write TCPServer to accept the log messages for > real-time monitoring. I Googled (is that now a verb?) for several hours and > came up with some code that I've turned in to something that works, but I can't > figure out how to disconnect the server once it is connected The goal is to be > able to start TCPServer, monitor the log messages sent via SocketHandler logger, > disconnect, and move to the next application. Eventually I would like to wrap a > GUI around all of this for monitoring a complex web application. > > Everything works, it just appears that I get into the while loop in > LogRecordStreamHandler.handle and it never breaks out (until I kill the client). > I can't seem to do anything with the LogRecordSocketReceiver.abort attribute to > make it quit. > > I'm sure it is something simple (stupid?), but I've spent about 4 hours and I'm > not getting anywhere. > > Thanks in advance for any assistance. > > Regards, > Larry > > Below is my code: > > import sys > import time > importlogging > > if sys.argv[1] == 'client': > importlogging.config > > logging.config.fileConfig("logging.conf") > > #create logger > logger =logging.getLogger("VESconsole") > > while 1: > logger.debug("debug message") > logger.info("info message") > logger.warn("warn message") > logger.error("error message") > logger.critical("critical message") > time.sleep(2) > > elif sys.argv[1] == 'server': > import cPickle > importlogging.handlers > import SocketServer > import struct > import signal > > class LogRecordStreamHandler(SocketServer.StreamRequestHandler): > """Handler for a streamingloggingrequest. > > This basically logs the record using whateverloggingpolicy is > configured locally. > """ > > def handle(self): > """ > Handle multiple requests - each expected to be a 4-byte length, > followed by the LogRecord in pickle format. Logs the record > according to whatever policy is configured locally. > """ > while 1: > chunk = self.connection.recv(4) > if len(chunk) < 4: > break > > slen = struct.unpack(">L", chunk)[0] > chunk = self.connection.recv(slen) > while len(chunk) < slen: > chunk = chunk + self.connection.recv(slen - len(chunk)) > > obj = self.unPickle(chunk) > record =logging.makeLogRecord(obj) > self.handleLogRecord(record) > > def unPickle(self, data): > return cPickle.loads(data) > > def handleLogRecord(self, record): > t = time.strftime('%a, %d %b %y %H:%M:%S', > time.localtime(record.created)) > > print "%s %s" % (t, record.getMessage()) > > class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer): > """simple TCP socket-basedloggingreceiver suitable for testing. > """ > > allow_reuse_address = 1 > > def __init__(self, host='localhost', > port=logging.handlers.DEFAULT_TCP_LOGGING_PORT, > handler=LogRecordStreamHandler): > > SocketServer.ThreadingTCPServer.__init__(self, > (host, port), > handler) > self.abort = 0 > self.timeout = 1 > self.logname = None > > def serve_until_stopped(self): > import select > abort = 0 > while not abort: > rd, wr, ex = select.select([self.socket.fileno()], > [], [], > self.timeout) > if rd: > self.handle_request() > > abort = self.abort > > print "serve_until_stopped exiting" > > # > # Start ThreadingTCPServer instance to accept SocketHandler log > # messages from client. > # > tcpserver = LogRecordSocketReceiver() > print "Starting ThreadingTCPServer..." > tcpserver.serve_until_stopped() > > ''' > #-----logging.conf----- > [loggers] > keys=root > > [handlers] > keys=socketHandler > > [formatters] > keys=simpleFormatter > > [logger_root] > level=DEBUG > handlers=socketHandler > > [handler_socketHandler] > class=handlers.SocketHandler > level=DEBUG > args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT) > host=localhost > port=DEFAULT_TCP_LOGGING_PORT > > [formatter_simpleFormatter] > format=%(asctime)s - %(name)s - %(levelname)s - %(message)s > datefmt= > ''' Hi Larry, You can make the server quit (set abort to True) by changing the logic of the server appropriately. In your script (as in the example at http://docs.python.org/lib/network-logging.html), nothing sets server.abort, so the server never quits. If you were to insert a line "self.server.abort = True" before the break in the check "if len(chunk) < 4:", then the server will quit whenever a message shorter than 4 bytes is received; ordinarily, a SocketHandler will always send a 4-byte length followed by content. You can test this easily as follows: Run the server after modifying the script as described above. Run the client and observe some messages printed by the server. Kill the client. The server should still be waiting for events from clients, though it might quit if, when you kill the client, a truncated message is sent. Run "telnet localhost 9020" and type a character. The server should quit. If you make the "quitting" message a raw_input() call, then you can see that the server has exited normally via the abort flag. Don't forget, the receiver can receive events from several applications. You don't need to disconnect and reconnect. Simply have each event sent by an app identify the app in some way - e.g. the logger name could be "VESconsole.app1" for one app and "VESconsole.app2" in another. In your server's handleRecord code, you can get the logger name, decode the sending app from that and route the event appropriately. Another approach is to subclass SocketHandler and override the makePickle method. This determines the wire format of the event sent to the server, and if you change the wire format and modify the server end to suit, then you can have any amount of flexibility in the communications between the applications generating the events and the server collating them. I'm not sure why you've had so much trouble with logging in the past, or why it took several hours of Googling to find a solution relating to logging events across a network. I Googled for "python network logging" and the link in the Python docs which I referenced earlier was the first result, and hence also available via the "I'm Feeling Lucky" button ;-) Best regards, Vinay From deets at nospam.web.de Thu Jul 31 08:18:40 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 14:18:40 +0200 Subject: working pylint anyone? References: <6fdf17Fb2bboU1@mid.uni-berlin.de> Message-ID: <6fdovaFb2tndU1@mid.uni-berlin.de> Stefan Rank wrote: > on 31.07.2008 11:29 Diez B. Roggisch said the following: > >> >> The packaged version of pylint (0.13.2) fails with this error (last >> line): >> > >> >> So - anybody out here having an actually working pylint config and can >> tell me what versions work together? I've become pretty dependend on it >> to be honest... > > Three installations of pylint 0.14.0 that I have access to from here: > > pylint.bat 0.14.0, > astng 0.17.2, common 0.27.0 > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > (Intel)] > > pylint 0.14.0, > astng 0.17.2, common 0.31.0 > Python 2.5.2 (r252:60911, Jul 23 2008, 00:17:15) > [GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] > > pylint 0.14.0, > astng 0.17.2, common 0.27.0 > Python 2.5.1 (r251:54863, Jul 11 2007, 15:07:18) > [GCC 3.3.5 (Debian 1:3.3.5-13)] > > > All of them installed using good old setup.py (times 3). > easy_install does not work as you noted. Thanks, that helped. I got the same errors - but these are because of custom init-hooks I created. Now I need to debug these.. thanks! Diez From larry.bates at websafe.com` Sat Jul 26 09:59:18 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 26 Jul 2008 08:59:18 -0500 Subject: Stripping parts of a path In-Reply-To: References: Message-ID: Tim Cook wrote: > Hi All, > > I just ran into an issue with the rstrip method when using it on path > strings. > > When executing a function I have a need to strip off a portion of the > current working directory and add on a path to a log file. Initially > this worked great but then I added a branch in SVN which caused the path > to contain 'LNCCWorkshop'. The rstrip() then began removing the > characters 'shop' leaving an incorrect path to the log file. When I > hard coded this path it worked okay but then did the same thing later in > the file when I needed to point to a database. The code worked fine with > a different path. Here are some code fragments. > > logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/at_build_errors.log' > > this worked when the path was: > /home/tim/ref_impl_python/TRUNK/oship/src/oship/atbldr > > the code above returns: > /home/tim/ref_impl_python/TRUNK/oship/log/at_build_errors.log > > but when I tried a branches version that has the path: > /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/src/oship/atbldr > > it SHOULD return: > /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/log/at_build_errors.log > > but I get: > /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log > > logfile=os.getcwd() > print logfile is correct; but when I add the .rstrip('src/oship/atbldr') > it also strips the 'shop' off of LNCCWorkshop and returns > /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log > > I had two other people looking at this as we did troubleshooting and we > could not determine the cause. It is repeatable with this path name. > In resolution I renamed the branch to just LNCC and it works fine. > > Thoughts? > > Tim > > > > > > > Always helps to consult documentation when things don't work. Help on built-in function rstrip: rstrip(...) S.rstrip([chars]) -> string or unicode Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping If you give chars to rstrip() it removes all those characters from the string not that substring. -Larry From benjamin.kaplan at case.edu Mon Jul 7 21:05:58 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 7 Jul 2008 21:05:58 -0400 Subject: How to make python scripts .py executable, not bring up editor In-Reply-To: References: Message-ID: On Mon, Jul 7, 2008 at 5:56 PM, korean_dave wrote: > >From command Prompt, i type in a script, "tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? > -- > http://mail.python.org/mailman/listinfo/python-list > You need to set the file associations to use python.exe, instead of PythonWin. In Vista, you can to this from Control Panel -> Programs -> Default Programs. -------------- next part -------------- An HTML attachment was scrubbed... URL: From larry.bates at websafe.com` Tue Jul 15 23:09:16 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 22:09:16 -0500 Subject: graphing lifelines In-Reply-To: References: Message-ID: E. J. Gold is the Hi-Tech Shaman wrote: > On Jul 15, 3:38 pm, Larry Bates wrote: > >> Certainly a "Hi-Tech Shaman" can whip something up to do this, right? >> > > Yes, well E.J. Gold is the Hi-Tech Shaman. I'm Terrence Brannon, > stating that fact :) > > So, maybe EJ could whip up such a thing :) > > I like the sci.math answer I got the best and will go with that > approach - > http://groups.google.com/group/sci.math/browse_thread/thread/09b254718d4cbfeb# Hey you're the one using his email address ;-). -Larry From __peter__ at web.de Fri Jul 4 04:33:20 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Jul 2008 10:33:20 +0200 Subject: Singleton implementation problems References: <87abgy2kcu.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Peter Otten <__peter__ at web.de> writes: > >> The problem is the structure of your program. The myset module is >> imported twice by Python, once as "myset" and once as "__main__". > > Yes, this is the problem. Each module imports the other. > >> Therefore you get two distinct MySet classes, and consequently two >> distinct MySet.__instance class attributes. > > Are you sure? This goes against my understanding: that 'import foo' > will not re-import a module that's already been imported, but will > instead simply return the existing module. The main script is put into the sys.modules cache as "__main__", not under the script's name. Therefore the cache lookup fails. > So, I think if one evaluated 'myset is __main__', you'd find they are > exactly the same module under different names; and therefore that > there is only *one* instance of 'MySet', again under two names. No: $ cat tmp.py import tmp import __main__ print tmp is __main__ $ python tmp.py False False Peter From pavlovevidence at gmail.com Wed Jul 30 21:10:08 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 30 Jul 2008 18:10:08 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> <7f4a3d37-e551-4e21-b660-3618016cb67b@z6g2000pre.googlegroups.com> Message-ID: <035ef824-0fc2-408e-a6fc-e35df45ab625@d45g2000hsc.googlegroups.com> On Jul 30, 11:07 am, Terry Reedy wrote: > Carl Banks wrote: > > That's not what I was asking for. I was asking for a use case for "if > > x" that can't be replaced by a simple explicit test. Your example > > didn't satisfy that. > > But I believe my example of an iterator with __bool__ but not with > __len__ does. And I believe I followed up to your post saying as much. :) Carl Banks From socyl at 987jk.com.invalid Tue Jul 29 11:20:38 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 15:20:38 +0000 (UTC) Subject: DB access without object-relation mapping? Message-ID: Python noob here. I want to write a script that creates and populates a simple Postgres database. The word on the street is to use something like SQLAlchemy for database access in Python, but my experience in the past with packages that perform automated SQL generation has been awful, so I always return to lighter-weight solutions that allow me to write my own SQL. (E.g. when coding in Perl I've used Perl's DBI package and drivers, rather than the likes of Class::DBI.) So what's the standard Python way to send SQL directly to a Postgres database and get back results? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From martinskou at gmail.com Tue Jul 22 08:08:00 2008 From: martinskou at gmail.com (martinskou at gmail.com) Date: Tue, 22 Jul 2008 05:08:00 -0700 (PDT) Subject: Web Page Construction in Python References: Message-ID: Also, look at: http://www.djangoproject.com/ /Martin From support.desk.ipg at gmail.com Wed Jul 9 15:39:09 2008 From: support.desk.ipg at gmail.com (Support Desk) Date: Wed, 9 Jul 2008 14:39:09 -0500 Subject: variable question Message-ID: <01da01c8e1fb$7615a4f0$a701a8c0@office.ipglobal.net> I am trying to assign a variable using an if / else statement like so: If condition1: Variable = something If condition2: Variable = something else Do stuff with variable. But the variable assignment doesn't survive outside the if statement. Is there any better way to assign variables using an if statement or exception so I don't have to write two almost identical if statements. This is probably a dumb question. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bcurtu at gmail.com Tue Jul 22 06:19:00 2008 From: bcurtu at gmail.com (bcurtu) Date: Tue, 22 Jul 2008 03:19:00 -0700 (PDT) Subject: DB Pool Message-ID: <40f3a61b-8c37-4e26-90f6-02de760ce00e@c58g2000hsc.googlegroups.com> Hi, I use MySQLdb lib to access my DB, because I want to opttimize my sql queries. The application I'm working on has quite a few traffic load, so I want to minimize the time of creating/destroying cursors: My typical code is sth like: cursor=con.cursor() cursor.execute(sql) all= cursor.fetchall() cursor.close() So, the question is... how can I minimize this cost? I was thinking on Connection Pools, but I didn't find any good documentation or sample. Any idea? From ali.sakebi at gmail.com Wed Jul 16 13:48:13 2008 From: ali.sakebi at gmail.com (Alis) Date: Wed, 16 Jul 2008 10:48:13 -0700 (PDT) Subject: Is there any component-oriented (non-MVC) web framework available for Python? Message-ID: <5fdd1388-bb1e-4a59-8fd1-2aa1ce7fa6e0@79g2000hsk.googlegroups.com> Hi Is there any component-oriented (non-MVC) web framework available for Python? That is something like Apache Wicket, Tapestry or JSF, but I need it to be in Python. Regards, Ali From castironpi at gmail.com Mon Jul 21 15:08:43 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 21 Jul 2008 12:08:43 -0700 (PDT) Subject: persistent deque (continued) Message-ID: <4c985e86-c0c4-4cb3-b7ce-f8e105b7f85d@y21g2000hsf.googlegroups.com> Some time ago, I was asking about the feasibility of a persistent deque, a double-ended queue. It runs into the typical space allocation problems. If you're storing a pickle, you have to allocate and fragment the file you've opened, since pickles can be variable-length strings; i.e. if the new data is too long, blank out its entry, and grow the file. If you're storing a data-type, you lose Python's dynamic-type advantages, as well as its long integers, as they can be any length. If you change the object in the deque, such as when using any mutable type, you have to update the container too. Does anyone have any experience storing pickles (I am aware of the similarities to shelf) to a database? Can the file system facilitate the variable-length string problem? How feasible is a length-of-length - length - data solution to the unbounded integer problem? Is there any alternative to completely re-pickling a large (say 1k pickled) object you only change slightly? What other issues are there? Is a hybrid-storage type possible, that stores the contents of its Python-allocated memory block to disk, including reference count, even if it's a lot slower? The object could not contain any references to objects not allocated on disk. A first approach is for the file to look like this: 00 data 01 data 02 01 data 03 data 04 02 data 05 data 06 Append would add: 03 data 07 data 08 AppendLeft would add: -01 data 09 data 0a Pop would remove 03, PopLeft would remove -01. You would need a length-and-head index to make 'rotate' available. Remove would run a worst-case risk of renumbering half of the indices stored, plus a rotate. From qvx3000 at gmail.com Wed Jul 30 03:02:53 2008 From: qvx3000 at gmail.com (qvx) Date: Wed, 30 Jul 2008 00:02:53 -0700 (PDT) Subject: I CAN connect socket to any localhost port but I shouldn't be able to References: <13c78fbf-751f-4d70-a012-53aa1eb64e53@79g2000hsk.googlegroups.com> Message-ID: <55820cec-e899-406b-8bb9-00b4028a3ca7@z72g2000hsb.googlegroups.com> On Jul 30, 4:48?am, "Gabriel Genellina" wrote: > En Tue, 29 Jul 2008 14:56:08 -0300, qvx escribi : > > > I don't have server listening on port 8084 but I can open socket to it > > (and to many other ports, tested for all<8000) > > Your example fails -as expected- on my PC running Python 2.5.2 + Windows ? > XP SP2. It may be something specific to your setup or your platform. > > py> test(8084) > Traceback (most recent call last): > ? ?File "", line 1, in > ? ?File "", line 5, in test > ? ?File "", line 1, in connect > socket.error: (10061, 'Connection refused') > -- > Gabriel Genellina Thanks for confirmation. There is a similar function in CherryPy server which won't start anymore but it used to. I am currently examining Windows and any recently installed software. -- Tvrtko From socyl at 987jk.com.invalid Thu Jul 17 15:11:36 2008 From: socyl at 987jk.com.invalid (kj) Date: Thu, 17 Jul 2008 19:11:36 +0000 (UTC) Subject: x, = y (???) Message-ID: I just came across an assignment of the form x, = y where y is a string (in case it matters). 1. What's the meaning of the comma in the LHS of the assignment? 2. How could I have found this out on my own? (Regarding (2) above, I consulted the index of several Python reference books but I could not find the answer to (1). I hope to find a better Python reference!) TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From paddy3118 at googlemail.com Fri Jul 18 03:04:04 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 18 Jul 2008 00:04:04 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Message-ID: <7ac1b818-8aa9-478f-a922-82baf0d51c5b@w39g2000prb.googlegroups.com> On Jul 16, 11:20?pm, Craig Allen wrote: > Hey, forgive me for just diving in, but I have a question I was > thinking of asking on another list but it really is a general question > so let me ask it here. ?It's about how to approach making singletons. Hi Craig, This might be good for a general background on Design Patters in Python: http://uk.youtube.com/watch?v=0vJJlVBVTFg - Paddy. From matthieu.brucher at gmail.com Wed Jul 23 09:06:34 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Wed, 23 Jul 2008 15:06:34 +0200 Subject: Python Written in C? In-Reply-To: References: Message-ID: 2008/7/23 mk : >> Actually, all of the compilers I'm familiar with (gcc and a >> handful of cross compilers for various microprocessors) >> translate from high-level languages (e.g. C, C++) into >> assembly, which is then assembled into relocatable object >> files, which are then linked/loaded to produce machine >> language. > > Doesn't g++ translate C++ into C and then compile C? > > Last I heard, most C++ compilers were doing that. GCC translates every language into its one as a tree, which is then translated to assembly. Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher From robert.rawlins at thinkbluemedia.co.uk Thu Jul 17 11:23:47 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 17 Jul 2008 16:23:47 +0100 Subject: Unusual Exception Behaviour Message-ID: <002d01c8e821$1b870f20$52952d60$@rawlins@thinkbluemedia.co.uk> Hello Chaps, I have an unusual situation with my application which I've also seen once or twice in the past but never found a solution too. Basically the application stops properly reporting Exceptions when they are thrown. My application logs extensively to a file using the python logging module, when an exception is throw all the log data starts being thrown to the command prompt instead of the file, however, I don't get any actual exception information output. I have looked through the application for any unusual or bare try/except blocks that don't actually do anything with the except just in case any of them are causing the issue but can't seem to see any. This little issue makes debugging my application VERY hard, when running the app I can see it crash, but I get no information as to where the exception is being thrown from, as you can imagine, quite frustrating. Even when throwing my own exceptions just for testing like so: Raise Exception, "This is a test exception." In certain parts of the application it doesn't print the exception to screen, but all subsequent requests to the logger seem to print out at the command prompt. I would really love some suggestions on what might be causing this. Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From moogyd at yahoo.co.uk Sun Jul 13 03:23:40 2008 From: moogyd at yahoo.co.uk (moogyd at yahoo.co.uk) Date: Sun, 13 Jul 2008 00:23:40 -0700 (PDT) Subject: Beginner Question : Iterators and zip References: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> Message-ID: <0ea30e6f-fcf4-4f39-a091-10b2a2178efd@l64g2000hse.googlegroups.com> On 12 Jul, 21:50, "bruno.desthuilli... at gmail.com" wrote: > On 12 juil, 20:55, moo... at yahoo.co.uk wrote: > > > > zip is (mostly) ok. What you're missing is how to use it for any > arbitrary number of sequences. Try this instead: > > >>> lists = [range(5), range(5,11), range(11, 16)] > >>> lists > > [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]>>> for item in zip(*lists): > > ... print item > ... > (0, 5, 11) > (1, 6, 12) > (2, 7, 13) > (3, 8, 14) > (4, 9, 15) What is this *lis operation called? I am having trouble finding any reference to it in the python docs or the book learning python. > > Any other comments/suggestions appreciated. > > There's a difflib package in the standard lib. Did you give it a try ? I'll check it out, but I am a newbie, so I am writing this as a (useful) learning excercise. Thanks for the help Steven From dp_pearce at hotmail.com Wed Jul 9 11:44:38 2008 From: dp_pearce at hotmail.com (dp_pearce) Date: Wed, 9 Jul 2008 08:44:38 -0700 (PDT) Subject: Anyone happen to have optimization hints for this loop? Message-ID: <32fd142e-b198-430e-888b-01aee4e63ac0@c65g2000hsa.googlegroups.com> I have some code that takes data from an Access database and processes it into text files for another application. At the moment, I am using a number of loops that are pretty slow. I am not a hugely experienced python user so I would like to know if I am doing anything particularly wrong or that can be hugely improved through the use of another method. Currently, all of the values that are to be written to file are pulled from the database and into a list called "domainVa". These values represent 3D data and need to be written to text files using line breaks to seperate 'layers'. I am currently looping through the list and appending a string, which I then write to file. This list can regularly contain upwards of half a million values... count = 0 dmntString = "" for z in range(0, Z): for y in range(0, Y): for x in range(0, X): fraction = domainVa[count] dmntString += " " dmntString += fraction count = count + 1 dmntString += "\n" dmntString += "\n" dmntString += "\n***\n dmntFile = open(dmntFilename, 'wt') dmntFile.write(dmntString) dmntFile.close() I have found that it is currently taking ~3 seconds to build the string but ~1 second to write the string to file, which seems wrong (I would normally guess the CPU/Memory would out perform disc writing speeds). Can anyone see a way of speeding this loop up? Perhaps by changing the data format? Is it wrong to append a string and write once, or should hold a file open and write at each instance? Thank you in advance for your time, Dan From brad at 16systems.com Fri Jul 18 10:12:34 2008 From: brad at 16systems.com (Brad) Date: Fri, 18 Jul 2008 10:12:34 -0400 Subject: Regular expression help In-Reply-To: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> References: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> Message-ID: nclbndk759 at googlemail.com wrote: > Hello, > > I am new to Python, with a background in scientific computing. I'm > trying to write a script that will take a file with lines like > > c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647 > 3pv=0 > > extract the values of afrac and etot... Why not just split them out instead of using REs? fp = open("test.txt") lines = fp.readlines() fp.close() for line in lines: split = line.split() for pair in split: pair_split = pair.split("=") if len(pair_split) == 2: try: print pair_split[0], "is", pair_split[1] except: pass Results: IDLE 1.2.2 ==== No Subprocess ==== >>> afrac is .7 mmom is 0 sev is -9.56646 erep is 0 etot is -11.020107 emad is -3.597647 3pv is 0 >>> From mrkafk at gmail.com Fri Jul 11 13:06:54 2008 From: mrkafk at gmail.com (mk) Date: Fri, 11 Jul 2008 19:06:54 +0200 Subject: Using SWIG to build C++ extension In-Reply-To: References: Message-ID: And what's infuriating is that the .o files do contain the necessary symbol: # grep _Z13edit_distanceRSsS_ * Binary file edit_distance.o matches Binary file _edit_distance.so matches Binary file edit_distance_wrap.o matches From bdesth.quelquechose at free.quelquepart.fr Sun Jul 27 14:58:16 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Jul 2008 20:58:16 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <78446ee7-b035-49a8-ac73-46895391543d@o40g2000prn.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <87abg7pe16.fsf@benfinney.id.au> <78446ee7-b035-49a8-ac73-46895391543d@o40g2000prn.googlegroups.com> Message-ID: <488ce13e$0$11953$426a34cc@news.free.fr> Jordan a ?crit : (snip) about Python Zen: > Perhaps we're just looking at an instance of a wider problem - smart > people boil good ideas down into short slogans, which are nice and > memorable and somewhat helpful, but can lead to bad consequences when > lots of others start overusing or misunderstanding them. This is true for just each and every "golden rule" in programming - like "goto are evil", "globals are evil", "side effects are evil", "early returns are evil", "public attributes are evil", etc... If you blindly apply any rule without understanding the rationales behind it, then you're into cargo-cult thinking. And once you understand the reasons that led someone to formulate such a rule, you just don't have to bother about it anymore - you just use your common sense to do what seems appropriate in a given situation. From roy at panix.com Tue Jul 29 21:20:53 2008 From: roy at panix.com (Roy Smith) Date: Tue, 29 Jul 2008 21:20:53 -0400 Subject: [unittest] Run setUp only once References: <871w1cr49a.fsf@nokile.rath.org> Message-ID: In article <871w1cr49a.fsf at nokile.rath.org>, Nikolaus Rath wrote: > But at least this variation doesn't work, because unittest apparently > also creates two separate TwoTests instances for the two tests. Isn't > there some way to convince unittest to reuse the same instance instead > of trying to solve the problem in the test code itself? Nope. It's a fundamental part of the Xunit design that every test gets a complete, virgin environment in which to run. The sample code that Jean-Paul gave you: > class TwoTests(unittest.TestCase): > setUpResult = None > > def setUp(self): > if self.setUpResult is None: > self.setUpResult = computeIt() does indeed create two instances of TwoTests, but it only calls computeIt() once, into which (presumably) all the expensive stuff has been refactored. This is, of course, a violation of the rule that says each test must run in a clean environment, but if you want to violate that rule, that's up to you. Presumably you know your system and have made an informed decision as a consenting adult that you understand the risks and this is what you want to do. Another variation on this would be to take this code out of setUp(), and instead create a singleton class (there's a good recipe for this on active state) which does your shared setup. Then in the two tests which need this, explicitly call the singleton factory. I think this is a little cleaner than Jean-Paul's way, because at least it isolates the shared stuff to exactly the two tests which need it. From bwgoudey at gmail.com Wed Jul 9 01:26:36 2008 From: bwgoudey at gmail.com (Benjamin Goudey) Date: Tue, 8 Jul 2008 22:26:36 -0700 (PDT) Subject: Returning the positions of a list that are non-zero Message-ID: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> I have a very large list of integers representing data needed for a histogram that I'm going to plot using pylab. However, most of these values (85%-95%) are zero and I would like to remove them to reduce the amount of memory I'm using and save time when it comes to plotting the data. To do this, I'm trying to find the best way to remove all of the zero values and produce a list of indices of where the non-zero values used to be. For example, if my original list is [0,0,1,2,1,0,0] I would like to produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices of where the non-zero values used to be). Removing non-zero values is very easy but determining the indicies is where I'm having difficulty. Thanks in advance for any help From robert.rawlins at thinkbluemedia.co.uk Tue Jul 15 08:51:25 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 15 Jul 2008 13:51:25 +0100 Subject: Logging in __del__() In-Reply-To: References: <17056.2125546441$1216121658@news.gmane.org> Message-ID: <016e01c8e679$7ddc4cc0$7994e640$@rawlins@thinkbluemedia.co.uk> Hi Fredrik, > When the application is running, or when it is shutting down? This is interesting, I did a test where I explicitly destroyed the instance using 'del my_instance' while the application was running and no error was thrown. It would see you are right, when the application ends it kills the logging module before my classes. I think you're on the right approach just try/except it and leave it be. Am I right in thinking that Python destroys instances of classes when it deems they are no longer needed? I shouldn't have to explicitly delete the classes, right? Thanks Fredrik, Robert From Russ.Paielli at gmail.com Mon Jul 28 01:07:31 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 22:07:31 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> <6a5506b1-632e-4bf6-b0ce-4d51d1751aa9@i24g2000prf.googlegroups.com> <8b4b11c3-e306-4fe7-82d1-0a948c725f2f@r15g2000prd.googlegroups.com> <239a084f-b73d-4c20-aaaf-bbd05d452638@a2g2000prm.googlegroups.com> <8f675d65-e302-4428-a4bc-f494b230cb59@w1g2000prk.googlegroups.com> Message-ID: <744c27d4-e166-4b3a-9c2c-d4bf1a207fb8@a2g2000prm.googlegroups.com> On Jul 27, 9:44 pm, alex23 wrote: > > > > > On Jul 27, 4:26 pm, "Russ P." wrote: > > > > > > Terry Reedy wrote: > > > > > > > The use of '.' has been suggested before and rejected. > > > > > > Where and why? > > Dude, I agree with Guido completely on this one. You > > seem to be clueless about the issue here. You're the > > one with the reading comprehension problem. Please > > quit wasting my time with your irrelevant crap. > > I pointed you at a thread -where it had been suggested and rejected-. > And I'm the clueless one? > > I don't think I'm the one wasting anyone's time here, but fine. I've > got far better things to do with my time than waste it talking to you. What was "suggested in rejected" on the thread you pointed me to was not what I suggested. Not even close. Get it, genius? From stefan_ml at behnel.de Fri Jul 18 11:40:44 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 18 Jul 2008 17:40:44 +0200 Subject: Core Dump - Segmentation Fault -Newbie In-Reply-To: References: <8ba4373d-3d97-4e9a-a15e-723f6818c757@k36g2000pri.googlegroups.com> <4880A0FA.6030603@behnel.de> Message-ID: <4880B97C.2050708@behnel.de> Doug Morse wrote: > Well, I must be missing something re: why Stefan states that you are using > Windows. I don't see that stated in your original post It's stated in the mail headers of his post, though. That's the problem with newbies - you never know where that stops being right. Stefan From fredrik at pythonware.com Tue Jul 15 07:10:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2008 13:10:15 +0200 Subject: why is "self" used in OO-Python? In-Reply-To: References: Message-ID: ssecorp wrote: > def append(self, item): > self.stack.append(item) > > I can get to see the stack with var.stack but then why even implement > append when I could do self.stack.append(x) etc. > That way you could do away with OO completely. Umm. Even if you were to write that, self and stack would still be objects, and the "append" would still be a method defined by the stack object, right? What you seem to be referring to is the Law of Demeter, which is a design guideline for avoiding unnecessary coupling, not an absolute requirement for object-orientation: http://en.wikipedia.org/wiki/Law_of_Demeter As for the rest, I suspect you will have more success in using Python if you use it to write Python programs, not Java programs: http://dirtsimple.org/2004/12/python-is-not-java.html From tjreedy at udel.edu Thu Jul 3 15:52:16 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 03 Jul 2008 15:52:16 -0400 Subject: Generating list of possible configurations In-Reply-To: References: <486c7c1f$0$10446$426a74cc@news.free.fr> Message-ID: Mensanator wrote: > On Jul 3, 2:13?am, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> Terry Reedy a ?crit : >>> This has been added to itertools at least for 2.6/3.0 >> Great ! > > Well, it will be great at some point in the future > when Python 2.6/3.0 have actually been released and The betas 'have actually been released' and I am happily using 3.0. The core features that I care about have mostly been untouched and where they have, they work. > third party extensions such as gmpy have caught up. Not my personal concern. And certainly not a direct concern for nearly all uses of itertools.product. > Until then, such solutions are worthless, i.e., of no value. Why are you so anxious to generalize your personal negative views to everyone else. Worthless to you, worthwhile to me. And for someone who does not need cross-products today or in the next few months, potentially valuable information for when the final releases do arrive, maybe in September. tjr From Younger.Wang at packetfront.com Mon Jul 14 12:11:20 2008 From: Younger.Wang at packetfront.com (Younger Wang) Date: Mon, 14 Jul 2008 18:11:20 +0200 Subject: How to package a logging.config file? In-Reply-To: References: Message-ID: I had the similar question and my solution is: default_config = os.path.join(os.getcwd(), "log.config") def get_logger(name, config_file=None): if config_file: logging.config.fileConfig(config_file) else: logging.basicConfig(level=logging.INFO, format='%(levelname)s %(module)s:%(lineno)d: %(message)s') return logging.getLogger(name) I had to make this helper function because calling logging.getLogger will fail in an exception without configuring logging module. I wish it is not like that. BR Younger Wang -----Original Message----- From: python-list-bounces+younger.wang=packetfront.com at python.org [mailto:python-list-bounces+younger.wang=packetfront.com at python.org] On Behalf Of Matthew Wilson Sent: Monday, July 14, 2008 8:21 AM To: python-list at python.org Subject: How to package a logging.config file? I'm working on a package that uses the standard library logging module along with a .cfg file. In my code, I use logging.config.fileConfig('/home/matt/mypackage/matt.cfg') to load in the logging config file. However, it seems really obvious to me that this won't work when I share this package with others. I can't figure out what path to use when I load my .cfg file. Any ideas? Matt -- http://mail.python.org/mailman/listinfo/python-list From noagbodjivictor at gmail.com Tue Jul 15 11:55:23 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Tue, 15 Jul 2008 11:55:23 -0400 Subject: Is it legal to rebuild Python.exe to include Version property tab? Message-ID: I think it is. I got a bundle of Python named EnthoughtPython and the version string gave something different from original Python. -- NOAGBODJI Paul Victor From python at rcn.com Sat Jul 12 03:13:26 2008 From: python at rcn.com (Raymond Hettinger) Date: Sat, 12 Jul 2008 00:13:26 -0700 (PDT) Subject: Perfect hashing for Py References: Message-ID: On Jul 11, 3:01?pm, bearophileH... at lycos.com wrote: > I have found this perfect hash (minimal too) implementation:http://burtleburtle.net/bob/hash/perfect.html > > I have already translated part of it to D, and it seems to work well > enough. As discussed in the PyConDue, I think this may be used in > frozenset (and frozendict) to build a (minimal too?) perfect hash on > the fly, to allow (hopefully) faster retrieval of items that don't > change. A few thoughts: Objects currently have their own hash function that is independent of a given container. We also have to hash types other than strings (used in the examples in the links you provided). While a container such as a dict or set is being built, we don't even know how many unique keys there are until the container is fully populated. Set-to-set operations and set-to-dict operations get their speed from knowing that both containers use the same hash values -- this would get disrupted if each container had its own hash function. Some types like strings (especially interned strings) remember their own hash value -- this makes it very fast to look their values in a set or dict -- that would be defeated if each container has its own hash function which would need to be recomputed for every lookup. An important use case for sets is uniquification -- in that use case, speed is determined by insertion time, we just don't care about subsequent lookup time -- anything that slows down insertion (such as computing a perfect hash value) works to the detriment of that use case). In the current design, sets and dicts are never more than 2/3 full and are usually much more sparse than that -- accordingly lookups average between 1 and 1.5 probes per lookup. This is somewhat hard to beat with perfect hashing since we typically get very few collisions anyway -- so you get the cost of increased insertion time, loss of objects being able to remember their own hash, challenges with non- string keys, a more complicated algorithm, and decreased interoperability for set-to-set and set-to-dict options -- the only benefits are to reduce collisions to zero when they are already not that common. For frozensets, it may be possible to add an optimize() method that takes a completely built frozenset and optimizes its insertion order and/or increases its size to make it arbitrarily sparse. That would only be useful for cases when the costs of optimizing the table is fully repaid by an extensive number of lookups. There are use some cases where it would be pay table optimization costs in order to win decreased lookup costs, but there are plenty of use cases where that would not be a winning trade-off. So, the optimize() step would need to be optional, not builtin. Raymond FWIW, I mentioned all this at PyConDue but the message must have gotten lost. From paul at boddie.org.uk Sat Jul 19 09:43:36 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 19 Jul 2008 06:43:36 -0700 (PDT) Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> <0T56p3tmInifNv8%stesch@parsec.no-spoon.de> <6e7v9qF5q74kU1@mid.uni-berlin.de> <0T56pitfI5raNv8%stesch@parsec.no-spoon.de> Message-ID: On 17 Jul, 11:09, Fredrik Lundh wrote: > > (and the "stable release" and "much will change" stuff is pure FUD, of > course. what competing project will I find if I google your name?) That's a bit unfair. Maybe the guy was stung by previous experiences with books and certain other frameworks. It seems to me that the Django people have been quite cautious with the APIs and with their own book, but it isn't as if nothing has been changing with respect to the APIs and the preferred ways of doing things in Django. And I have to add that books which refer the reader to various Web sites in order to find out the status of the code, qualifying the prose with "by the time you read this", don't give a great impression. I can't say that the book referenced here does that, although short of a 1.0 release, I find it unlikely that the author could avoid it. Paul From dinov at exchange.microsoft.com Wed Jul 30 11:40:03 2008 From: dinov at exchange.microsoft.com (Dino Viehland) Date: Wed, 30 Jul 2008 08:40:03 -0700 Subject: interpreter vs. compiled In-Reply-To: <5be6b2bf-7bf3-42d7-9f31-5ccc886ec786@t54g2000hsg.googlegroups.com> References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> <5be6b2bf-7bf3-42d7-9f31-5ccc886ec786@t54g2000hsg.googlegroups.com> Message-ID: <7AD436E4270DD54A94238001769C2227012C9376BA99@DF-GRTDANE-MSG.exchange.corp.microsoft.com> It looks like the pickle differences are due to two issues. First IronPython doesn't have ASCII strings so it serializes strings as Unicode. Second there are dictionary ordering differences. If you just do: { 'a': True, 'b': set( ) } Cpy prints: {'a': True, 'b': set([])} Ipy prints: {'b': set([]), 'a': True} The important thing is that we interop - and indeed you can send either pickle string to either implementation and the correct results are deserialized (modulo getting Unicode strings). For your more elaborate example you're right that there could be a problem here. But the DLR actually recognizes this sort of pattern and optimizes for it. All of the additions in your code are what I've been calling serially monomorphic call sites. That is they see the same types for a while, maybe even just once as in your example, and then they switch to a new type - never to return to the old one. When IronPython gives the DLR the code for the call site the DLR can detect when the code only differs by constants - in this case type version checks. It will then re-write the code turning the changing constants into variables. The next time through when it sees the same code again it'll re-use the existing compiled code with the new sets of constants. That's still slower than we were in 1.x so we'll need to push on this more in the future - for example producing a general rule instead of a type-specific rule. But for the time being having the DLR automatically handle this has been working good enough for these situations. -----Original Message----- From: python-list-bounces+dinov=microsoft.com at python.org [mailto:python-list-bounces+dinov=microsoft.com at python.org] On Behalf Of castironpi Sent: Tuesday, July 29, 2008 11:40 PM To: python-list at python.org Subject: Re: interpreter vs. compiled I note that IronPython and Python's pickle.dumps do not return the same value. Perhaps this relates to the absence of interpreter loop. >>> p.dumps( { 'a': True, 'b': set( ) } ) IPy: '(dp0\nVb\np1\nc__builtin__\nset\np3\n((lp4\ntp5\nRp2\nsVa \np6\nI01\ns.' CPy: "(dp0\nS'a'\np1\nI01\nsS'b'\np2\nc__builtin__\nset \np3\n((lp4\ntp5\nRp6\ns." You make me think of a more elaborate example. for k in range( 100 ): i= j() g= h+ i e= f+ g c= d+ e a= b+ c Here, j creates a new class dynamically, and returns an instance of it. Addition is defined on it but the return type from it varies. If I read you correctly, IPy can leave hundreds of different addition stubs laying around at the end of the for-loop, each of which only gets executed once or twice, each of which was compiled for the exact combination of types it was called for. I might construe this to be a degenerate case, and the majority of times, you'll reexecute stubs enough to outweigh the length of time the compilation step takes. If you still do the bounds checking, it takes extra instructions (C doesn't), but operation switch-case BINARY_ADD, (PyInt_CheckExact(v) && PyInt_CheckExact(w)), and POP and TOP, are all handled by the selection of stubs from $addSite. I'm read from last April: >>> The most interesting cases to me are the 5 tests where CPython is more than 3x faster than IronPython and the other 5 tests where IronPython is more than 3x faster than CPython. CPython's strongest performance is in dictionaries with integer and string keys, list slicing, small tuples and code that actually throws and catches exceptions. IronPython's strongest performance is in calling builtin functions, if/then/else blocks, calling python functions, deep recursion, and try/except blocks that don't actually catch an exception. <<< http://lists.ironpython.com/pipermail/users-ironpython.com/2007-April/004773.html It's interesting that CPython can make those gains still by using a stack implementation. I'll observe that IronPython has the additional dependency of the full .NET runtime. (It was my point 7/18 about incorporating the GNU libs, that to compile to machine-native, as a JIT does, you need the instruction set of the machine.) Whereas, CPython can disregard them, having already been compiled for it. I think what I was looking for is that IronPython employs the .NET to compile to machine instructions, once it's known what the values of the variables are that are the operands. The trade-off is compilation time + type checks + stub look-up. What I want to know is, if __add__ performs an attribute look-up, is that optimized in any way, after the IP is already in compiled code? After all that, I don't feel so guilty about stepping on Tim's toes. On Jul 30, 12:12 am, Dino Viehland wrote: > IronPython doesn't have an interpreter loop and therefore has no POP / TOP / etc... Instead what IronPython has is a method call Int32Ops.Add which looks like: > > public static object Add(Int32 x, Int32 y) { > long result = (long) x + y; > if (Int32.MinValue <= result && result <= Int32.MaxValue) { > return Microsoft.Scripting.Runtime.RuntimeHelpers.Int32ToObject((Int32)(result)); > } > return BigIntegerOps.Add((BigInteger)x, (BigInteger)y); > } > > This is the implementation of int.__add__. Note that calling int.__add__ can actually return NotImplemented and that's handled by the method binder looking at the strong typing defined on Add's signature here - and then automatically generating the NotImplemented result when the arguments aren't ints. So that's why you don't see that here even though it's the full implementation of int.__add__. > > Ok, next if you define a function like: > > def adder(a, b): > return a + b > > this turns into a .NET method, which will get JITed, which in C# would look something like like: > > static object adder(object a, object b) { > return $addSite.Invoke(a, b) > > } > > where $addSite is a dynamically updated call site. > > $addSite knows that it's performing addition and knows how to do nothing other than update the call site the 1st time it's invoked. $addSite is local to the function so if you define another function doing addition it'll have its own site instance. > > So the 1st thing the call site does is a call back into the IronPython runtime which starts looking at a & b to figure out what to do. Python defines that as try __add__, maybe try __radd__, handle coercion, etc... So we go looking through finding the __add__ method - if that can return NotImplemented then we find the __radd__ method, etc... In this case we're just adding two integers and we know that the implementation of Add() won't return NotImplemented - so there's no need to call __radd__. We know we don't have to worry about NotImplemented because the Add method doesn't have the .NET attribute indicating it can return NotImplemented. > > At this point we need to do two things. We need to generate the test which is going to see if future arguments are applicable to what we just figured out and then we need to generate the code which is actually going to handle this. That gets combined together into the new call site delegate and it'll look something like: > > static void CallSiteStub(CallSite site, object a, object b) { > if (a != null && a.GetType() == typeof(int) && b != null && b.GetType() == typeof(int)) { > return IntOps.Add((int)a, (int)b); > } > return site.UpdateBindingAndInvoke(a, b); > > } > > That gets compiled down as a lightweight dynamic method which also gets JITed. The next time through the call site's Invoke body will be this method and things will go really fast if we have int's again. Also notice this is looking an awful lot like the inlined/fast-path(?) code dealing with int's that you quoted. If everything was awesome (currently it's not for a couple of reasons) the JIT would even inline the IntOps.Add call and it'd probably be near identical. And everything would be running native on the CPU. > > So that's how 2 + 2 works... Finally if it's a user type then we'd generate a more complicated test like (and getting more and more pseudo code to keep things simple): > > if (PythonOps.CheckTypeVersion(a, 42) && PythonOps.CheckTypeVersion(b, 42)) { > return $callSite.Invoke(__cachedAddSlot__.__get__(a), b); > > } > > Here $callSite is another stub which will handle doing optimal dispatch to whatever __add__.__get__ will return. It could be a Python type, it could be a user defined function, it could be the Python built-in sum function, etc... so that's the reason for the extra dynamic dispatch. > > So in summary: everything is compiled to IL. At runtime we have lots of stubs all over the place which do the work to figure out the dynamic operation and then cache the result of that calculation. > > Also what I've just described is how IronPython 2.0 works. IronPython 1.0 is basically the same but mostly w/o the stubs and where we use stub methods they're much less sophisticated. > > Also, IronPython is open source -www.codeplex.com/IronPython > > -----Original Message----- abriged: > This is from 7/22/08, same author: > > I wouldn't say "can't". The current CPython VM does not compile > > code. It COULD. The C#/.NET VM does. > > Three big claims here that I breezed right over and didn't believe. > > > It COULD. > > I'm evidently assuming that if it could, it would. > > > The current CPython VM does not compile code. > > Therefore it couldn't, or the assumption is wrong. Tim says it is. > And the glaring one-- > > WHY NOT? Why doesn't CPython do it? > > I am imagining that every Python implementation has something like > it. If IronPython does not, in particular, not have the 'POP(); > TOP();' sequence, then it isn't running on a stack machine. Is the > IronPython code open source, and can someone link to it? I'm not > wading through it from scratch. What does it have instead? Does > dynamic typing still work? -- http://mail.python.org/mailman/listinfo/python-list From bj_666 at gmx.net Mon Jul 21 16:59:19 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Jul 2008 20:59:19 GMT Subject: Python Written in C? References: Message-ID: <6ekbl7F6vgp3U6@mid.uni-berlin.de> On Mon, 21 Jul 2008 11:26:27 -0700, castironpi wrote: > On Jul 20, 11:59?pm, Michael Torrie wrote: >> giveitawhril2... at gmail.com wrote: >> > I'm not dissing Python, here. Just noting that, if it is written in C, >> > that throws a curve at me in trying to balance the value of learning >> > Python vs. some other major language. >> >> Definitely one of the most non-sequitor statements I have ever heard. >> Actually your entire post doesn't make much sense. ?Maybe you are a >> brother bot to castropini? ?Perhaps a less-trained one, although none of >> castropini's posts seem to make sense either. ?The AI needs a bit of work. > > Are you saying Python is not good for writing A.I., or the A.I. isn't > good at writing Python? Are you saying python is not as smart as you. Ciao, Marc 'BlackJack' Rintsch From andreas.mock at web.de Tue Jul 15 12:17:47 2008 From: andreas.mock at web.de (McA) Date: Tue, 15 Jul 2008 09:17:47 -0700 (PDT) Subject: Logging to different addressees References: <8df30038-86c1-4376-b046-a50f2bcf0a2b@s50g2000hsb.googlegroups.com> <7b829a76-ba2c-4cb7-b216-0c9c01e5cd02@f36g2000hsa.googlegroups.com> Message-ID: Hi Vinary, thank you for answering. I start be proud that the author of the logging package himself is answering. :-) On 15 Jul., 15:51, Vinay Sajip wrote: > On Jul 15, 1:27 pm, McA wrote: > > > > > Add a handler to the root logger (or common_logger) to send to the > admin sink. That's clear. > Add a handler to certain_logger to send to the addressee sink. That's also clear. > If you added the admin sink handler to the root logger, you're done. Isn't that the first thing above? What do you mean? > Otherwise, you need to ensure that certain_logger is a child of > common_logger. What I want to code is something like that. a) I know thet this is a message for the admin only: admin_logger.log('blabla') (admin_logger = root_logger = logging.get_logger("")) b) certain_logger.log('something' => log to the root/admin/-sink as well as to the certain-sink. Do I have to create a logger subclass where I do the multiplexing of the logging messages? I'm pretty sure I miss something. ;-) > > Regards, > > Vinay Sajip Regards Andreas Mock From jonas.haulin at gmail.com Fri Jul 25 02:51:03 2008 From: jonas.haulin at gmail.com (jrh) Date: Thu, 24 Jul 2008 23:51:03 -0700 (PDT) Subject: import dll instead of pyd References: <68310600-2efd-4f52-81d7-d0f3b40c7809@h17g2000prg.googlegroups.com> <6O2dnfUikbwXqRTVnZ2dnUVZ_j2dnZ2d@earthlink.com> Message-ID: <21d0cf65-0366-4473-8b3e-81f818aeb289@h17g2000prg.googlegroups.com> Yes it is in the same directory. The problem is it does not seem to look for dll's at all. So is this by design, or am I missing something? On 25 Juli, 10:03, Nick Dumas wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Is this DLL in the same directory as your script? If not, is it part of > your pythonpath? If neither are true, then you won't be able to import > it, regardless of whether it's a good file or not. > > > > jrh wrote: > > Hello, > > > From previous posts and documentation it seems python should be able > > to import a module that is compiled into a .dll just as well as > > a .pyd. I have a pyd that works fine, but after renaming it to dll the > > import fails. Running python with -vv flag indicates it doesn't > > actually look for the dll (see below). Has dll import been defeatured > > in python? > > > Thanks! > > >>>> import _mydllpythonmodule > > # trying _mydllpythonmodule.pyd > > # trying _mydllpythonmodule.py > > # trying _mydllpythonmodule.pyw > > # trying _mydllpythonmodule.pyc > > # trying C:\Python25\DLLs\_mydllpythonmodule.pyd > > # trying C:\Python25\DLLs\_mydllpythonmodule.py > > # trying C:\Python25\DLLs\_mydllpythonmodule.pyw > > # trying C:\Python25\DLLs\_mydllpythonmodule.pyc > > # trying C:\Python25\lib\_mydllpythonmodule.pyd > > # trying C:\Python25\lib\_mydllpythonmodule.py > > # trying C:\Python25\lib\_mydllpythonmodule.pyw > > # trying C:\Python25\lib\_mydllpythonmodule.pyc > > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyd > > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.py > > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyw > > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyc > > # trying C:\Python25\_mydllpythonmodule.pyd > > # trying C:\Python25\_mydllpythonmodule.py > > # trying C:\Python25\_mydllpythonmodule.pyw > > # trying C:\Python25\_mydllpythonmodule.pyc > > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyd > > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.py > > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyw > > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyc > > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyd > > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.py > > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyw > > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyc > > # trying C:\Python25\lib\site-packages\win32\lib > > \_mydllpythonmodule.pyd > > # trying C:\Python25\lib\site-packages\win32\lib\_mydllpythonmodule.py > > # trying C:\Python25\lib\site-packages\win32\lib > > \_mydllpythonmodule.pyw > > # trying C:\Python25\lib\site-packages\win32\lib > > \_mydllpythonmodule.pyc > > # trying C:\Python25\lib\site-packages\Pythonwin > > \_mydllpythonmodule.pyd > > # trying C:\Python25\lib\site-packages\Pythonwin\_mydllpythonmodule.py > > # trying C:\Python25\lib\site-packages\Pythonwin > > \_mydllpythonmodule.pyw > > # trying C:\Python25\lib\site-packages\Pythonwin > > \_mydllpythonmodule.pyc > > Traceback (most recent call last): > > File "", line 1, in > > ImportError: No module named _mydllpythonmodule > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (MingW32) > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > iEYEARECAAYFAkiJNGwACgkQLMI5fndAv9hykgCcDf4cTZU0iDo+ELQ5aFGs9FIO > 8GEAn3+egrPDtNrlbsssqti8YeZXXIeM > =q31k > -----END PGP SIGNATURE----- From martin at v.loewis.de Sat Jul 26 12:55:40 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 26 Jul 2008 18:55:40 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: References: <488aec52$0$21481$9b622d9e@news.freenet.de> Message-ID: <488B570C.8070202@v.loewis.de> >> The Microsoft .NET commercial framework uses the PE architecture of the > > Whats the "Commercial framework" ? I've only come accross 3, the > standard 32 bit one and 2 64 bit variants. That's the name of the Microsoft .NET product available for Windows. There are other implementations as well, such as the Compact Framework, or GNU Mono. It's correct that the commercial framework is available for three architectures. In addition, the compact framework is also available for ARM. Mono is available for many more platforms, such as SPARC, PowerPC, MIPS and HPPA. > I just tested, I built a default C# forms app using the "AnyCPU" option > and it ran as a 64 bit app (no *32 in Task Manager), this is on XP64. > > I have though installed the AMD64 version of the 2.0 framework and > AFAICT neither windows update or the Visual Studio installer > will install that by default, you have to go get it your self. Interesting. I only tested this in .NET 1.1. Perhaps they have changed something since. How exactly did you launch the program? Does it change if you use Python's os.spawn* to launch it? Regards, Martin From google at mrabarnett.plus.com Tue Jul 15 18:17:43 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 15 Jul 2008 15:17:43 -0700 (PDT) Subject: Modify a string's value References: <87lk036y2u.fsf@benfinney.id.au> Message-ID: On Jul 15, 3:06?pm, Ben Finney wrote: > s0s... at gmail.com writes: > > I've heard that a 'str' object is immutable. But is there *any* way to > > modify a string's internal value? > > If there were, it would not be immutable. The 'str' type has only > immutable values. > > You could implement your own string type, and have it allow mutable > values. You'd have to take care of creating those values explicitly, > though. > You could write a C extension which modifies strings, but that would be a Bad Idea. From konstantin.selivanov at gmail.com Tue Jul 22 01:49:37 2008 From: konstantin.selivanov at gmail.com (konstantin) Date: Mon, 21 Jul 2008 22:49:37 -0700 (PDT) Subject: string[i:j:k] References: <4a9a4cf3-9ef4-4d9e-b714-bbf62b7c1917@v1g2000pra.googlegroups.com> Message-ID: <811e72db-a8bc-475a-b32a-38a9b6922600@k30g2000hse.googlegroups.com> On Jul 22, 9:18 am, alex23 wrote: > On Jul 22, 3:10 pm, konstantin wrote: > > > some_string[i:j:k] > > What does it mean? > > i = start position, j = end position, k = step size > > >>> s = "ABABABABABABAB" > >>> s[0:6:2] > 'AAA' > >>> s = "ABCABCABCABCABC" > >>> s[0:6:3] > > 'AA' > > Hope this helps. > > - alex23 Thanks! It seems that negative step leads in reverse direction. But logic isn't completely clear for me. >>> s = '123456789' >>> s[::-2] '97531' but >>> s[:-1:-2] '' though I expected something like '8642' What did i missed? From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 2 04:13:46 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Jul 2008 10:13:46 +0200 Subject: Attribute reference design In-Reply-To: References: <6cvlk4F3s90U1@mid.uni-berlin.de> Message-ID: <486b38b6$0$7210$426a74cc@news.free.fr> chamalulu a ?crit : > On Jul 2, 1:17 am, Gary Herron wrote: >> No need. Also, you can define a class attribute (C++ might call it a >> static attribute) and access it transparently through an instance. >> >> class C: >> aClassAttribute = 123 >> def __init__(self, ...): >> ... >> >> c = C() >> ... do something with c.aClassAttribute ... >> > > Actually, this is why I started too look into the attribute reference > mechanics to begin with. Coming from mostly C# development I think > it's weird to be able to refer to class attributes (static members) > through a class instance (object). But I think I'm getting the > picture. Function objects lay flat in memory (some heap...). Python's functions are ordinary objects, instance of type 'function'. > When > defined inside classes they are wrapped in method objects. Nope. The wrapping happens at lookup time, thru the descriptor protocol (the same thing that gives support for properties). > When > refered through classes or class instances they are unbound method > objects or bound method objects respectively. That's what function.__get__() returns, yes. What is stored in the class object's __dict__ is the plain function. > Am I on the right track? > I still don't get why these methods show up when I dir() a class > instance. """ Help on built-in function dir in module __builtin__: dir(...) dir([object]) -> list of strings Return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it: No argument: the names in the current scope. Module object: the module attributes. Type or class object: its attributes, and recursively the attributes of its bases. Otherwise: its attributes, its class's attributes, and recursively the attributes of its class's base classes. """ > /Henrik From amirnntp at gmail.com Sat Jul 12 23:44:13 2008 From: amirnntp at gmail.com (Amir) Date: Sat, 12 Jul 2008 20:44:13 -0700 (PDT) Subject: filtering keyword arguments Message-ID: <633d6159-7803-4d9b-8f16-2a4a0a197a86@t54g2000hsg.googlegroups.com> How do you filter keyword arguments before passing them to a function? For example: def f(x=1): return x def g(a, **kwargs): print a, f(**kwargs) In [5]: g(1, x=3) 1 3 In [6]: g(1, x=3, y=4) TypeError: f() got an unexpected keyword argument 'y' Is there a way to do something like: def g(a, **kwargs): print a, f(filter_rules(f, **kwargs)) so only {'x': 3} is passed to f? I was hoping for a pythonic way of doing what in Mathematica is done by FilterRules: http://reference.wolfram.com/mathematica/ref/FilterRules.html From alexnbryan at gmail.com Tue Jul 15 04:45:25 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 15 Jul 2008 01:45:25 -0700 (PDT) Subject: Testing for Internet Connection Message-ID: <18460572.post@talk.nabble.com> Hello internet. I am wondering, is there a simple way to test for Internet connection? If not, what is the hard way :p -- View this message in context: http://www.nabble.com/Testing-for-Internet-Connection-tp18460572p18460572.html Sent from the Python - python-list mailing list archive at Nabble.com. From deets at nospam.web.de Tue Jul 8 02:29:14 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 Jul 2008 08:29:14 +0200 Subject: extended setattr() In-Reply-To: References: Message-ID: <6dgfprF2ekq3U1@mid.uni-berlin.de> Rotlaus schrieb: > On 7 Jul., 08:01, Rotlaus wrote: >> 2 weeks ago i asked for a etended getattr() which worked really fine, >> but now i would love to have a extendedsetattr() as well. > > I've tried the following, but it doesn't work: > > class A(object): > def __init__(self): > self.B = B() > > class B(object): > def __init__(self): > self.C = C('foo') > > class C(object): > def __init__(self, txt=''): > self.txt = txt > > def ext_setattr(obj, attr, val): > for subattr in attr.split("."): > obj = getattr(obj, subattr) > obj = val > >>>> import test >>>> a = A() > Traceback (most recent call last): > File "", line 1, in > NameError: name 'A' is not defined >>>> a = test.A() >>>> a.B.C.txt > 'foo' >>>> ext_setattr(a, 'B.C.txt', 'bar') >>>> a.B.C.txt > 'foo' > > What am i doing wrong? obj = val won't work. You need to use a setattr(obj, name, val) on the last attribute-name. Diez From fredrik at pythonware.com Fri Jul 25 03:20:16 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 09:20:16 +0200 Subject: import dll instead of pyd In-Reply-To: <21d0cf65-0366-4473-8b3e-81f818aeb289@h17g2000prg.googlegroups.com> References: <68310600-2efd-4f52-81d7-d0f3b40c7809@h17g2000prg.googlegroups.com> <6O2dnfUikbwXqRTVnZ2dnUVZ_j2dnZ2d@earthlink.com> <21d0cf65-0366-4473-8b3e-81f818aeb289@h17g2000prg.googlegroups.com> Message-ID: jrh wrote: > Yes it is in the same directory. The problem is it does not seem to > look for dll's at all. So is this by design, or am I missing > something? looks like that was removed in 2.5; from Misc/NEWS: - On Windows, .DLL is not an accepted file name extension for extension modules anymore; extensions are only found if they end in .PYD. which is easily confirmed: Python 2.4.3 >>> import imp >>> imp.get_suffixes() [('.pyd', 'rb', 3), ('.dll', 'rb', 3), ('.py', 'U', 1), ('.pyw', 'U', 1), ('.pyc', 'rb', 2)] Python 2.5 >>> import imp >>> imp.get_suffixes() [('.pyd', 'rb', 3), ('.py', 'U', 1), ('.pyw', 'U', 1), ('.pyc', 'rb', 2)] (the DLL support was a compatibility thing anyway, so I guess removing it after 10+ years is a reasonable thing to do...) From DWebre at dotd.la.gov Thu Jul 17 08:40:29 2008 From: DWebre at dotd.la.gov (DWebre at dotd.la.gov) Date: Thu, 17 Jul 2008 07:40:29 -0500 Subject: Pickle and wx.TextCtrl Message-ID: D. J. Webre, Jr. PE & PLS "Gabriel Genellina" python-list at python.org Sent by: cc python-list-bounc es Subject +djwebre=dotd.la. Re: Pickle and wx.TextCtrl gov at python.org 07/11/2008 10:51 PM Thanks for the response. En Fri, 11 Jul 2008 10:15:36 -0300, escribi?: > Trying to read a pickled file and list contents. > > The attached program works using pprint, but I want to write to my frame. > WriteText only produces half of the records. > What is happening? What do you mean by "only produces half of the records"? Write Text list records from "Assignment" to "Report" pprint list records from "Assignment" to "Report" and continues to "TaskWeek", about twice as many records Probably your problem has nothing to do with a TextCtrl - ensure you can save and load your data with a simple, console-based script, and only then write the GUI. The way you read the file is rather strange -mixing calls to readline and pickle.load- I'd write the data using pickle.dump calls *only* and then read it using pickle.load calls *only*. I used 13.1.7 Example of the Python Library Referencebut. Got an error message when I did not have the readline() statement. Additional ideas will be appreciated. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: graycol.gif Type: image/gif Size: 105 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: pic20037.gif Type: image/gif Size: 1255 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ecblank.gif Type: image/gif Size: 45 bytes Desc: not available URL: From tomkur2006-takehome at yahoo.com Tue Jul 1 21:38:21 2008 From: tomkur2006-takehome at yahoo.com (tom) Date: Tue, 1 Jul 2008 18:38:21 -0700 (PDT) Subject: httplib HTTP: Logging request message References: <57053381-d73a-4099-af6b-da672b8718be@i36g2000prf.googlegroups.com> Message-ID: <170d29ce-054a-42ee-9251-1ec5c1595a37@f24g2000prh.googlegroups.com> I guess the easies way to do it is to copy and modify the httplib module to log both outgoing and incoming messages. From robinsiebler at gmail.com Thu Jul 31 20:07:15 2008 From: robinsiebler at gmail.com (robinsiebler at gmail.com) Date: Thu, 31 Jul 2008 17:07:15 -0700 (PDT) Subject: Decoding an attachment Message-ID: I figured out how to save an e-mail message as a text file, but I'm not sure how to decode the encoded part as I am not sure how much I need to include to decode it properly. Here is what a message looks like: Received: from INGESTOR2SQA ([10.220.83.198]) by sqaserver300 with Microsoft SMTPSVC(6.0.3790.0); Thu, 31 Jul 2008 12:10:26 -0700 mime-version: 1.0 from: "AVDN Ingestor" to: sqatest at ictvsys.pvt date: 31 Jul 2008 17:53:40 +0000 subject: Upload Status for test content-type: multipart/mixed; boundary=--boundary_2_09ab8836- ff06-41a6-94d6-59258539bf88 Return-Path: sqatest at ictvsys.pvt Message-ID: X-OriginalArrivalTime: 31 Jul 2008 19:10:26.0125 (UTC) FILETIME=[16D08FD0:01C8F341] ----boundary_2_09ab8836-ff06-41a6-94d6-59258539bf88 content-type: text/plain; charset=us-ascii content-transfer-encoding: quoted-printable For additional information, please see attachment. ----boundary_2_09ab8836-ff06-41a6-94d6-59258539bf88 content-type: text/xml; name=status.xml; charset=utf-8 content-transfer-encoding: base64 content-disposition: attachment PGF2ZG5fcG5tIHZlcnNpb249IjEuMSIgc2VuZGVyPSJhdmRud2VzdGRjMSIgZG9jbnVtYmVy PSJvaHV0bHBxeXptM25xd3lrYm9wd3pwdTUiIHN0YXR1cz0ic3VjY2Vzc2Z1bCI +PGNvbnRh Y3QgcGhvbmU9IjQwOC05MzEtOTIzMiIgZW1haWw9Im0uY2hhbkBhdm5ldHdvcmtzLmNvbSIg Lz48YXNzZXRzdGF0ZSBwcm92aWRlcmlkPSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJjZjcw NDcwNWFjIiBmaWxlbmFtZT0iXHZpZGVvXGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2NfYWMz XzAxLmpwZyIgbm90aWZpY2F0aW9uPSIxMjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJpZD0i U1FBIiBhc3NldGlkPSJhY2YxZTNkNmViY2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRlb1xm b29cYm91Z2UwMDMuMzIwXzI0MF9udHNjX2FjM18wMy5qcGciIG5vdGlmaWNhdGlvbj0iMTIw IiAvPjxhc3NldHN0YXRlIHByb3ZpZGVyaWQ9IlNRQSIgYXNzZXRpZD0iYWNmMWUzZDZlYmNm NzA0NzA1YWMiIGZpbGVuYW1lPSJcdmlkZW9cZm9vXGJvdWdlMDAzLjMyMF8yNDBfbnRzY19h YzNfMDQuanBnIiBub3RpZmljYXRpb249IjEyMCIgLz48YXNzZXRzdGF0ZSBwcm92aWRlcmlk PSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJjZjcwNDcwNWFjIiBmaWxlbmFtZT0iXHZpZGVv XGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2NfYWMzXzAyLmpwZyIgbm90aWZpY2F0aW9uPSIx MjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJpZD0iU1FBIiBhc3NldGlkPSJhY2YxZTNkNmVi Y2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRlb1xmb29cYm91Z2UwMDMuMzIwXzI0MF9udHNj X2FjMy5qcGciIG5vdGlmaWNhdGlvbj0iMTIwIiAvPjxhc3NldHN0YXRlIHByb3ZpZGVyaWQ9 IlNRQSIgYXNzZXRpZD0iYWNmMWUzZDZlYmNmNzA0NzA1YWMiIGZpbGVuYW1lPSJcdmlkZW9c Zm9vXGJvdWdlMDAzLjMyMF8yNDBfbnRzY19hYzNfMDguanBnIiBub3RpZmljYXRpb249IjEy MCIgLz48YXNzZXRzdGF0ZSBwcm92aWRlcmlkPSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJj ZjcwNDcwNWFjIiBmaWxlbmFtZT0iXHZpZGVvXGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2Nf YWMzXzA3LmpwZyIgbm90aWZpY2F0aW9uPSIxMjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJp ZD0iU1FBIiBhc3NldGlkPSJhY2YxZTNkNmViY2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRl b1xmb29cYm91Z2UwMDMuMzIwXzI0MF9udHNjX2FjM18wNi5qcGciIG5vdGlmaWNhdGlvbj0i MTIwIiAvPjxhc3NldHN0YXRlIHByb3ZpZGVyaWQ9IlNRQSIgYXNzZXRpZD0iYWNmMWUzZDZl YmNmNzA0NzA1YWMiIGZpbGVuYW1lPSJcdmlkZW9cZm9vXGJvdWdlMDAzLjMyMF8yNDBfbnRz Y19hYzNfMDUuanBnIiBub3RpZmljYXRpb249IjEyMCIgLz48YXNzZXRzdGF0ZSBwcm92aWRl cmlkPSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJjZjcwNDcwNWFjIiBmaWxlbmFtZT0iXHZp ZGVvXGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2NfYWMzXzA5LmpwZyIgbm90aWZpY2F0aW9u PSIxMjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJpZD0iU1FBIiBhc3NldGlkPSJhY2YxZTNk NmViY2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRlb1xmb29cYm91Z2UwMDMuMzIwXzI0MF9u dHNjX2FjMy50cyIgbm90aWZpY2F0aW9uPSIxMjAiIC8+PC9hdmRuX3BubT4= ----boundary_2_09ab8836-ff06-41a6-94d6-59258539bf88-- From szrRE at szromanMO.comVE Tue Jul 22 14:49:34 2008 From: szrRE at szromanMO.comVE (szr) Date: Tue, 22 Jul 2008 11:49:34 -0700 Subject: proliferation of computer languages References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> <40429b65-23a0-489b-b5fd-ae6b8eee607d@t54g2000hsg.googlegroups.com> Message-ID: J?rgen Exner wrote: > Chris Rathman wrote: > >> I can't say that I see any particular point to the essay. > > You must be new here. There never is any particular point to Xah > Lee's rantings except to cross-post borderline topics to borderline > relevant NGs and then lay back and enjoy the ensuing slaughter. Admittedly, I'm not all too familiar with his postings, but on a general note, isn't it possible that someone else might not see it the same as you do? I really didn't see anything really sinister about the posting or it's content. It may very well be someone attempting to create a conversation, someone who may not be generally well received a lot of the time I gather. Also, if have such a distaste for his postings, you are free to ignore them as well. That said, I am all for alerting someone of something which may be a complete waste of their time, but in this case it feels like you are projecting your own dislike for the OP. Unless the OP really is deserving of such branding (in which case I'd stand corrected), I don't think it is reason enough to tell others not to read of his work just because you aren't particularly fond of it. Perhaps citing an actual example illustrating a reason to avoid him like the plague would of helped :-) -- szr From sunp1028 at gmail.com Mon Jul 14 21:29:11 2008 From: sunp1028 at gmail.com (patrol) Date: Mon, 14 Jul 2008 18:29:11 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> Message-ID: Hi, > 1) I'm not sure if WMI can be forced to close down system processes, > but if it can it's probably by means of specifying one or more > privileges when you connect. Try looking in the WMI newsgroups > for a more general (non-Python) answer to this and I'll happily > explain how to apply it in a Python context. I use VBS to kill these processes,the VBS cannot kill these either. > 2) I can't quite see from this traceback where the problem > arises. Have you snipped the traceback at all, or was that > all there was? Can you narrow the thing down to a short > snippet of code which I'm likely to be able to run independently, > please? import wmi from time import sleep c = wmi.WMI () process_watcher = c.Win32_Process.watch_for("creation") while True: new_process = process_watcher() if new_process.Caption == 'notepad.exe': print "start killing.." sleep(5) result = new_process.terminate() print "killed" We must start the notepad.exe manually, then (1) kill the notepad.exe by this code. (2)we kill the notepad.exe before this code manually. Both will result in errors. From tjreedy at udel.edu Fri Jul 25 17:53:22 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Jul 2008 17:53:22 -0400 Subject: Calling external program from within python In-Reply-To: <296ec449-831e-4f1f-9082-5ad4991dfc04@i20g2000prf.googlegroups.com> References: <6eu684F91muhU1@mid.uni-berlin.de> <042e46cf-8ee8-4dd0-bc2b-716d588f8e83@o40g2000prn.googlegroups.com> <296ec449-831e-4f1f-9082-5ad4991dfc04@i20g2000prf.googlegroups.com> Message-ID: Michael Tobis wrote: > For some reason os.popen is deprecated in favor of the more verbose > subprocess.Popen, but this will work for a while. As explained in http://www.python.org/dev/peps/pep-0324/ subprocess consolidated replaced several modules and functions (popen*, system, spawn*, ???)with better security, exception handling, and flexibility. The deprecated modules are gone in 3.0, so the OP might want to start with subprocess now. From ethan at stoneleaf.us Tue Jul 8 13:34:04 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 08 Jul 2008 09:34:04 -0800 Subject: numeric emulation and __pos__ In-Reply-To: <92e3ea9f-5745-4072-9d09-7c14fd335828@f36g2000hsa.googlegroups.com> References: <92e3ea9f-5745-4072-9d09-7c14fd335828@f36g2000hsa.googlegroups.com> Message-ID: <4873A50C.5090003@stoneleaf.us> Mark Dickinson wrote: > On Jul 8, 12:12 am, Ethan Furman wrote: > >>1) Any reason to support the less common operators? >> i.e. <<, >>, &, ^, | > > No reason to support any of these for a nonintegral > nonbinary type, as far as I can see. > >>2) What, exactly, does .__pos__() do? An example would help, too. > > Very little: it implements the unary + operator, which > for most numeric types is a no-op: > >>>>+5.0 > > 5.0 Anybody have an example of when the unary + actually does something? Besides the below Decimal example. I'm curious under what circumstances it would be useful for more than just completeness (although completeness for it's own sake is important, IMO). > So you could safely implement it as: > > def __pos__(self): > return self > > By the way, have you met the Decimal type? It also > keeps track of significant zeros. For example: > >>>>from decimal import Decimal >>>>Decimal('1.95') + Decimal('2.05') > > Decimal("4.00") Significant zeroes is not quite the same as significant digits (although Decimal may support that too, I haven't studied it). The difference being, for example, the following: >>> from decimal import Decimal >>> first = Decimal("3.14") >>> second = Decimal("5.2") >>> first * second Decimal("16.328") >>> from measure import Measure >>> third = Measure("3.14") >>> fourth = Measure("5.2") >>> third * fourth Measure("16") In other words, any calculated value cannot be more accurate than the least accurate input (5.2 in the case above, which hase two significant digits). > (Note that the output includes the extra zeros...) > Interestingly, in Decimal the __pos__ operation isn't a no-op: > it rounds a Decimal to the current context, and it also > (mistakenly, in my opinion) changes -0.0 to 0.0: > > >>>>+Decimal('-0.0') > > Decimal("0.0") > >>>>+Decimal('123456789123456789123456789123456789') > > Decimal("1.234567891234567891234567891E+35") > > Mark -- Ethan From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 3 11:26:59 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 03 Jul 2008 17:26:59 +0200 Subject: Write a file - beginner's question In-Reply-To: References: Message-ID: <486cefb7$0$6040$426a74cc@news.free.fr> Ben Keshet a ?crit : > I have a probably simple beginner's question - > > I have a script that I am currently able to print its output. instead, > i want to write it into a file - I tried different versions of write() > but might have gotten the syntax wrong. The syntax is: fileobj.write(something) Now since you don't say exactly what you tried *and what you got*, we can't help much more here. > the variable I want to write is > a line from a file I am reading: > > "... > f = open('receptor.mol2', 'r') > line = f.readline()[:-1] If you want to strip the newline characters, you'd better use line.strip() or line.lstrip() > while '@ATOM' not in line: > line = f.readline()[:-1] > #print line Also, there are simpler ways to iterate over a file: f = open('somefile.txt') for line in f: if '@ATOM' in line: break print line.lstrip() f.close() > print random_mol2 > ..." > > e.g. I want to write to a file all the lines in 'receptor.mol2' up to > the string "@ATOM" (one after the other). Can anyone please > advice? The simplest solution for a unix-like command-line program would be to redirect the standard out to this file, ie: # python myprog.py > destfile.txt But this may not fit your needs !-) The other simplest solution is to open the destination file in write (or append) mode and write to it: source = open('somefile.txt') dest = open('otherfile.txt', 'w') for line in source: if '@ATOM' in line: break # we don't strip here, since write doesn't append a newline dest.write(line) source.close() dest.close() > On a related note - how do I read and write to a file that is not in the > same directory? Give the full absolute or relative path. > e.g how do I provide a pathway to an open command? source = open('/full/absolute/path/to/my/file.txt') Note that the exact syntax for a path depends on your os (but the os.path module can take care of most specificities). The above example is for a posix system. On Windows, you'll probably have something like: source = open('C:/full/absolute/path/to/my/file.txt') HTH From fredrik at pythonware.com Thu Jul 24 14:05:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 20:05:31 +0200 Subject: instance comparison In-Reply-To: References: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> <4888879a$0$1043$426a74cc@news.free.fr> Message-ID: King skrev: > The the class is not subclass of another one. Problem still persist. > The code is pretty huge and I am trying to post the information as > clear as possible. feel free to *add* stuff to the following example until it breaks, if that's easier: >>> class Spam: ... def __init__(self, label): ... self.label = label ... def __str__(self): ... return self.label ... >>> a = Spam("an object") >>> a <__main__.Spam instance at 0xb7e8faac> >>> print a an object >>> b = Spam("an object") >>> b <__main__.Spam instance at 0xb7e8fb6c> >>> print b an object >>> a == b False >>> a is b False >>> str(a) == str(b) True From Russ.Paielli at gmail.com Thu Jul 31 01:31:51 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 30 Jul 2008 22:31:51 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> Message-ID: On Jul 30, 9:27 pm, Erik Max Francis wrote: > Russ P. wrote: > > I don't know if you can read minds, but you seem to have a lot of > > trouble reading words. > > > Can you read "it would be nice to be able to write ..."? Can you > > understand what it means? Can you understand that it does *not* mean, > > "one *should* be able to write ..."? > > You're sure going on about a distinction without a difference for a guy > who childishly likes to call other people names. A reasonable person > would have long ago moved on instead of blaming others for not > immediately intuiting your thoughts, rather than straightforwardly > reading your words. Which, by the way, includes at least three people > other than myself. > > But I'll bet the mindless namecalling is really working out for you. > Go, team, go! You earned the "childish name calling" by acting like a child -- with your petty little game of trying to show that I don't understand a basic concept in Python. As I said, your initial misunderstanding, while silly, was at least forgivable. But your insistence on repeating it time after time is not. It is truly pathetic. From dusan.smitran at gmail.com Tue Jul 22 07:28:05 2008 From: dusan.smitran at gmail.com (dusans) Date: Tue, 22 Jul 2008 04:28:05 -0700 (PDT) Subject: Converting List of String to Integer References: Message-ID: <45493256-eaff-40e5-8414-59e7ce1b347c@m73g2000hsh.googlegroups.com> >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] >>> [map(int, i) for i in a] [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] On Jul 21, 9:06?pm, Samir wrote: > Hi Everyone, > > I am relatively new to Python so please forgive me for what seems like > a basic question. > > Assume that I have a list, a, composed of nested lists with string > representations of integers, such that > > a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > > I would like to convert this to a similar list, b, where the values > are represented by integers, such as > > b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > I have unsuccessfully tried the following code: > > n = [] > for k in a: > ? ? n.append([int(v) for v in k]) > print n > > Does anyone know what I am doing wrong? > > Thanks in advance. > > Samir From duncan.booth at invalid.invalid Thu Jul 17 17:02:42 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jul 2008 21:02:42 GMT Subject: x, = y (???) References: Message-ID: kj wrote: > I still don't get it. If we write > > y = 'Y' > x, = y > > what's the difference now between x and y? And if there's no > difference, what's the point of performing such "unpacking"? None whatsoever when the string has only one character, but with 2 characters it becomes an obfuscated way of checking that there was only one character: >>> x, = 'a' >>> x, = 'ab' Traceback (most recent call last): File "", line 1, in x, = 'ab' ValueError: too many values to unpack From fredrik at pythonware.com Mon Jul 21 11:04:08 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 17:04:08 +0200 Subject: Safe guard .pyc files In-Reply-To: References: Message-ID: King wrote: > After google a lot I didn't find any way to safe guard .pyc files from > decompilation. There's no bullet-proof way to do that (the interpreter needs the bytecodes to be able to run your program, so unless you create your own Python runtime, someone could always run your program with an instrumented stock interpreter, and get the code from there. If you build your own runtime, they'll just instrument your runtime instead, which might be a little more work, but not much for someone who knows how to do such things.) Possible solutions: - implement portions of your application as a web service - hardware dongles (hackers can usually get around them without too much work, but they work pretty well for some applications / markets.) - use an obfuscator, e.g. http://bitboost.com/#other or http://www.lysator.liu.se/~astrand/projects/pyobfuscate/ From rotlaus at gmail.com Tue Jul 8 02:27:06 2008 From: rotlaus at gmail.com (Rotlaus) Date: Mon, 7 Jul 2008 23:27:06 -0700 (PDT) Subject: extended setattr() References: Message-ID: On 7 Jul., 08:01, Rotlaus wrote: > 2 weeks ago i asked for a etended getattr() which worked really fine, > but now i would love to have a extendedsetattr() as well. I've tried the following, but it doesn't work: class A(object): def __init__(self): self.B = B() class B(object): def __init__(self): self.C = C('foo') class C(object): def __init__(self, txt=''): self.txt = txt def ext_setattr(obj, attr, val): for subattr in attr.split("."): obj = getattr(obj, subattr) obj = val >>> import test >>> a = A() Traceback (most recent call last): File "", line 1, in NameError: name 'A' is not defined >>> a = test.A() >>> a.B.C.txt 'foo' >>> ext_setattr(a, 'B.C.txt', 'bar') >>> a.B.C.txt 'foo' What am i doing wrong? From cricket.keith at gmail.com Wed Jul 2 17:26:41 2008 From: cricket.keith at gmail.com (Keith Nation) Date: Wed, 2 Jul 2008 16:26:41 -0500 Subject: Queue/Priority Needed Message-ID: <21935b370807021426l11f1fa0ayc52593cc184869b3@mail.gmail.com> I'm still very new to python, and I have a question about how to prioritize jobs in a queue. Currently, I have a simple script that does the following: job1 = [1, 'Task1', 'v03', '-start', 'Bonnie'] job2 = [2, 'Task2', 'v01', '-start', 'Billy'] job3 = [3, 'Task3', 'v01', '-start', 'Bob'] jobsequence = (job1, job2, job3) for job in jobsequence: jnam=job[1] jop=job[3] jver=job[2] jreq=job[4] jpatch=job[5] jid=jnam+'/'+jver cmdline= /home/user/program/start '+' '+jop+' -proj '+jnam+' -dir '+'/home/user/programdata/'+jnam+'/'+jver; os.popen2(cmdline,mode='t',bufsize=-1) x=0 delay=5 while os.path.exists(jid+'/log.pid'): time.sleep(60*delay) x=x+1 print 'Job Complete' What I would like to do is populate the job listings interactively (using input lines) and be able to change priority on uncompleted jobs still in the queue, and add jobs to the queue. I appreciate any help you folks can offer. Keith Nation -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sun Jul 20 01:18:31 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 19 Jul 2008 22:18:31 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> <945275e9-8923-479c-8eec-258bd68063c0@z6g2000pre.googlegroups.com> <4881FE02.3000203@gmail.com> Message-ID: <99a8d3a0-e58e-4129-ba5a-8f0eac193f8e@a2g2000prm.googlegroups.com> On Jul 20, 11:14 am, Andrew Freeman wrote: > John Machin wrote: > (4) I highly doubt that this code was actually to be used in an > interactive session, The offending code is a nonsense wherever it is used. > the False/True output was truncated intentionally, What meaning are you attaching to "truncated"? > it's an obvious, but superfluous output (unless you were to rely on this > by attaching it to a variable which might lead to sorting issues). > > I put together a generic matcher that returns either a list of True data > (if the input is a list or tuple) or a boolean value: > > def match(ex, var): > "ex is the regular expression to match for, var the iterable or > string to return a list of matching items or a boolean value respectively." > ex = re.compile(ex).match You lose clarity by rebinding ex like that, and you gain nothing. > if isinstance(var, (list, tuple)): > return filter(ex, var) > else: > return bool(ex(var)) > > I believe this is fairly clean and succinct code, it would help my > learning immensely if you feel there is a more succinct, generic way of > writing this function. You have created a function which does two quite different things depending on whether one of the arguments is one of only two of the many kinds of iterables and which has a rather generic (match what?) and misleading (something which filters matches is called "match"??) name. The loss of clarity and ease of understanding caused by the readers having to find the code for the function so that they can puzzle through it means that the most succinct, generic and *recommended* way of writing this function would be not to write it at all. Write a function which returns a MatchObject. In the unlikely event that that anyone really wants to put bools in a list and sort them, then they can wrap bool() around it. Give it a meaningful name e.g. match_LRM. You want to check if a single variable refers to a valid LRM string? Use match_LRM(the_variable). Nice and clear. You want to filter out of some iterable all the occurrences of valid LRM strings? Use filter (whose name indicates its task) or a generator or list comprehension ... what [x for x in some_iterable if match_LRM(x)] does should be screamingly obvious i.e. have less chance than filter of needing a trip to the manual. HTH, John From Samnsparky at gmail.com Sun Jul 13 12:20:40 2008 From: Samnsparky at gmail.com (Sparky) Date: Sun, 13 Jul 2008 09:20:40 -0700 (PDT) Subject: wxPython Tab Message-ID: Is there a way to get wxPython to change the visible tab in a notebook (like I have tab 1 open but the computer will automatically change to tab 2)? Thanks, Sam From Lie.1296 at gmail.com Sat Jul 26 06:23:52 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 26 Jul 2008 03:23:52 -0700 (PDT) Subject: xml.dom's weirdness? References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> Message-ID: On Jul 26, 2:29?pm, Fredrik Lundh wrote: > Lie wrote: > > Why this generates AttributeError, then not? > > > Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) > > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> import xml > >>>> xml.dom > > Traceback (most recent call last): > > ? File "", line 1, in > > AttributeError: 'module' object has no attribute 'dom' > >>>> xml.dom > > > > this is what I get, on both Windows and Linux: > > ?>>> import xml > ?>>> xml.dom > Traceback (most recent call last): > ? ?File "", line 1, in > AttributeError: 'module' object has no attribute 'dom' > ?>>> xml.dom > Traceback (most recent call last): > ? ?File "", line 1, in > AttributeError: 'module' object has no attribute 'dom' > > That was what I would have expected. The submodules shouldn't get imported unless explicitly imported with import xml.dom, but what I see right now in front of me... I wouldn't have believed such thing if this isn't happening right under my eyes. Doing several dir(xml) revealed that xml.dom and xml.parsers appeared only after doing xml.dom and getting AttributeError After further testing, I found that it also happens with xml.parsers, but not xml.sax nor xml.etree, odd thing. And I tried PIL modules, the oddities doesn't happen. Then I tested the email module, the same thing happened: Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import email >>> dir(email) ['Charset', 'Encoders', 'Errors', 'FeedParser', 'Generator', 'Header', 'Iterators', 'LazyImporter', 'MIMEAudio', 'MIMEBase', 'MIMEImage', 'MIMEMessage', 'MIMEMultipart', 'MIMENonMultipart', 'MIMEText', 'Message', 'Parser', 'Utils', '_LOWERNAMES', '_MIMENAMES', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__path__', '__version__', '_name', 'base64MIME', 'email', 'importer', 'message_from_file', 'message_from_string', 'mime', 'quopriMIME', 'sys'] >>> email.parser Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'parser' >>> dir(email) ['Charset', 'Encoders', 'Errors', 'FeedParser', 'Generator', 'Header', 'Iterators', 'LazyImporter', 'MIMEAudio', 'MIMEBase', 'MIMEImage', 'MIMEMessage', 'MIMEMultipart', 'MIMENonMultipart', 'MIMEText', 'Message', 'Parser', 'Utils', '_LOWERNAMES', '_MIMENAMES', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__path__', '__version__', '_name', '_parseaddr', 'base64MIME', 'base64mime', 'charset', 'email', 'encoders', 'errors', 'importer', 'iterators', 'message', 'message_from_file', 'message_from_string', 'mime', 'quopriMIME', 'quoprimime', 'sys', 'utils'] >>> It seems python (or my version of python, which is the one that shipped with Ubuntu) mysteriously imported several modules's submodules in a (seemingly) random, yet consistent manner after an error occurred (as far as now, it seems ANY error would trigger the mysterious submodule import). I got even more head scratching when I see this: Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ac Traceback (most recent call last): File "", line 1, in NameError: name 'ac' is not defined >>> import xml >>> dir(xml) ['_MINIMUM_XMLPLUS_VERSION', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__path__', '__version__', 'dom', 'parsers'] >>> The triggering errors happened BEFORE I imported a module, yet later module import would also import submodules If you have any idea what black magic is happening in my computer right now, I'd appreciate it. From elessar at nienna.org Mon Jul 21 11:03:52 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Tue, 22 Jul 2008 00:03:52 +0900 Subject: sending input to an embedded application In-Reply-To: References: Message-ID: <4884A558.2000209@nienna.org> mefyl wrote: > Uwe Schmitt wrote: >> On 12 Jul., 09:08, George Oliver wrote: >>> What I would like to do is take a program and embed it or put it >>> within a Python-run GUI, using the GUI just to capture and send input >>> to the application, and display the ouput. >> Which interface does your interpreter provide ? Just commandline or >> can you access by other methods ? >> >> http://sourceforge.net/projects/pexpect/ might help you >> > > Although Pexpect looks more advanced and complete, you might want to take a > look at popen* modules. It enables you to easily run a subprocess, feed him > data on stdin, retrieve output from stdout/stderr, and wait for its > completion. > > http://docs.python.org/lib/module-popen2.html > I believe the subprocess module is the recommended module to use now. -Matt From elessar at nienna.org Thu Jul 3 17:05:53 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Thu, 03 Jul 2008 15:05:53 -0600 Subject: Testing for an empty list In-Reply-To: <18268092.post@talk.nabble.com> References: <18268092.post@talk.nabble.com> Message-ID: <486D3F31.30202@nienna.org> Alexnb wrote: > Okay this is a simple question I just don't know how. If I have a list, say: > > funList = [] > > and after a while something possible should have been appended to it, but > wasn't. How can I test if that list is empty. if not funList: do_something() -Matt From michele.simionato at gmail.com Thu Jul 24 04:37:37 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 24 Jul 2008 01:37:37 -0700 (PDT) Subject: parameterized classes References: Message-ID: <1bbb53aa-eff0-4c03-a868-606396b6bbd6@y21g2000hsf.googlegroups.com> John Tantalo wrote: > I really wish I could create a class whose instances were classes that > subclassed BaseRequestHandler. Is this possible, or is there a better > way than my approach here? Or am I crazy? You may use type: type('MuSubclass', (Base, ), dict(a1=1, a2=2, ...)) From pavlovevidence at gmail.com Sat Jul 12 13:42:11 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 12 Jul 2008 10:42:11 -0700 (PDT) Subject: why is "self" used in OO-Python? References: Message-ID: <39b8817b-5297-486b-92df-7a900fcc2a35@x35g2000hsb.googlegroups.com> On Jul 12, 12:32 pm, ssecorp wrote: > I first learned about OO from Java. > > I much prefer to program in Python though. > > However I am consufed about 2 things. Short answer is, "Java isn't the only way OOP." Longer answers follow. > 1. Why do I have to pass self into every method in a class? Since I am > always doing why cant this be automated or abstracted away? > Are the instances where I won't pass self? > I imagine there is some tradeoff involved otherwise it would have been > done away with. This is pretty simple: it was judged to be significantly more readable if you mark class variables explicitly. That is, when you see something like "self.var" you instantly know it's an attribute of the object and not a local or global variable. That you sometimes see Java and (more often) C++ guidelines that recommend always using "this" for accessing class members shows that it's somewhat helpful to keep them visually distinct from other variables. I think it's a minor point, really, that people make a pretty big deal over. > 2. self.item instead of getters and setters. I thought one of the main > purposes of OO was encapsulation. Just as an aside: the usage of getters and setters probably does more to thwart encapsulation than to protect it, in practice. You see, it doesn't matter whether you access a member directly, or through getters and setters: you're still accessing the member. Getters and setters don't encapsulate your data one bit. All they do is to add a bunch of mostly unnecessary boilerplate. OTOH, many people add getters and setters recklessly, based on the above misconception. Not only are they exposing internal details by doing this, they're also giving the user a blessing to use them. The practical advantage getters and setters have in Java is that, if your class implementation changes and you no longer wish for something that was once a single variable to be that way anymore, you can change your underlying implementation without changing the interface. That advantage does not exist in Python, however, since in Python one can do the same thing with properties. > Doesn't messing with internal object- > representations break this? > I see how the getters and setters could be just visual clutter and you > have to add them to every class so it is annoying a bit in the same > way as self described above. > However I feel like I want getters and setters when I write classes, > not sure of the advantages/disadvantages though. > Only looking at the documentation of a Python-class, will internal > representations be provided? > > If I have a class: > > class Stack(object): > def __init__(self, *items): > self.stack = list(items) > > def append(self, item): > self.stack.append(item) > > def pop(self): > return self.stack.pop() > > I can get to see the stack with var.stack but then why even implement > append when I could do self.stack.append(x) etc. > That way you could do away with OO completely. So why let people > access the main attribute but not let them manipulate it? > Makes more sense to draw the line to not access any attributes at all > no? Much of what you're arguing is only true if you accept it as a given that data hiding is important. The designers of Python don't really think it is, and that's why they don't have it. Carl Banks From mva.led at gmail.com Wed Jul 9 12:09:55 2008 From: mva.led at gmail.com (Manuel Vazquez Acosta) Date: Wed, 09 Jul 2008 12:09:55 -0400 Subject: Determining when a file has finished copying In-Reply-To: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> Message-ID: <4874E2D3.4050707@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 This seems a synchronization problem. A scenario description could clear things up so we can help: Program W (The workflow) copies file F to directory B Program D (the dog) polls directory B to find is there's any new file F In this scenario, program D does not know whether F has been fully copied, but W does. Solution: Create a custom lock mechanism. Program W writes a file D/F.lock to indicate file F is not complete, it's removed when F is fully copied. I program W crashes in mid-copy both F and F.lock are kept so program D does not bother to process F. Recovery from the crash in W would another issue to tackle down. Best regards, Manuel. writeson wrote: > Hi all, > > I'm writing some code that monitors a directory for the appearance of > files from a workflow. When those files appear I write a command file > to a device that tells the device how to process the file. The > appearance of the command file triggers the device to grab the > original file. My problem is I don't want to write the command file to > the device until the original file from the workflow has been copied > completely. Since these files are large, my program has a good chance > of scanning the directory while they are mid-copy, so I need to > determine which files are finished being copied and which are still > mid-copy. > > I haven't seen anything on Google talking about this, and I don't see > an obvious way of doing this using the os.stat() method on the > filepath. Anyone have any ideas about how I might accomplish this? > > Thanks in advance! > Doug > -- > http://mail.python.org/mailman/listinfo/python-list > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkh04skACgkQI2zpkmcEAhi0eQCgsVqg51fWiwi47jxqtbR8Gz2U UukAoKm15UAm3KpEyjhsIGQ+68rq8WuU =UFHi -----END PGP SIGNATURE----- From nick at craig-wood.com Wed Jul 2 08:32:58 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 02 Jul 2008 07:32:58 -0500 Subject: Why is recursion so slow? References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Message-ID: Rich Harkins wrote: > Nick Craig-Wood wrote: > [snip] > > By definition any function in a functional language will > > always produce the same result if given the same arguments, so you can > > memoize any function. > > > > Ah, so that's why time.time() seems to be stuck... ;) ;-) As Bruno noted I should have said "pure functional language" above. As for how you deal with IO in a pure functional language, well, either you make it impure (eg Erlang or Lisp) - functions can have side effects, or you do other complicated things like monads in Haskell! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From castironpi at gmail.com Sun Jul 27 01:02:07 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 26 Jul 2008 22:02:07 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> Message-ID: <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> On Jul 24, 11:04?pm, Tim Roberts wrote: > castironpi wrote: > > >Compiling a program is different than running it. ?A JIT compiler is a > >kind of compiler and it makes a compilation step. ?I am saying that > >Python is not a compiler and in order to implement JIT, it would have > >to change that fact. > > And I'm saying you are wrong. ?There is NOTHING inherent in Python that > dictates that it be either compiled or interpreted. ?That is simply an > implementation decision. ?The CPython implementation happens to interpret. > The IronPython implementation compiles the intermediate language to native > machine language. > > >> of Python that uses .NET. ?In that case, the code *IS* JIT compiled to > >> assembly when the program starts. > > >But still not the user's code, only the interpreter, which is running > >in assembly already anyway in CPython. > > In CPython, yes. ?In IronPython, no; the user's code is compiled into > machine language. ?Both of them are "Python". > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. In CPython yes. In IronPython yes: the parts that are compiled into machine code are the interpreter, *not user's code*. Without that step, the interpreter would be running on an interpreter, but that doesn't get the user's statement 'a= b+ 1' into registers-- it gets 'push, push, add, pop' into registers. From mishok13 at gmail.com Wed Jul 9 09:20:24 2008 From: mishok13 at gmail.com (Andrii V. Mishkovskyi) Date: Wed, 9 Jul 2008 16:20:24 +0300 Subject: Returning the positions of a list that are non-zero In-Reply-To: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> References: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> Message-ID: <192840a00807090620s578ff6f9u9af8db40327f5640@mail.gmail.com> 2008/7/9 Benjamin Goudey : > I have a very large list of integers representing data needed for a > histogram that I'm going to plot using pylab. However, most of these > values (85%-95%) are zero and I would like to remove them to reduce > the amount of memory I'm using and save time when it comes to plotting > the data. To do this, I'm trying to find the best way to remove all of > the zero values and produce a list of indices of where the non-zero > values used to be. > > For example, if my original list is [0,0,1,2,1,0,0] I would like to > produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices > of where the non-zero values used to be). Removing non-zero values is > very easy but determining the indicies is where I'm having difficulty. > > Thanks in advance for any help >>> l = [0, 0, 1, 2, 1, 0, 0] >>> zip(*[(item, index) for (index, item) in enumerate(l) if item != 0]) [(1, 2, 1), (2, 3, 4)] > -- > http://mail.python.org/mailman/listinfo/python-list > -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. From kyosohma at gmail.com Sat Jul 26 20:48:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sat, 26 Jul 2008 17:48:13 -0700 (PDT) Subject: wx.Timer not working References: <7a2a1c54-6d74-475c-9566-4d94cb5b5962@a3g2000prm.googlegroups.com> Message-ID: On Jul 26, 5:22?pm, 5lvqbw... at sneakemail.com wrote: > On Jul 26, 3:13?pm, Mike Driscoll wrote: > > > > > On Jul 26, 2:33?pm, 5lvqbw... at sneakemail.com wrote: > > > > Windows XP SP3 > > > Python 2.5 > > > wx.version() = '2.8.1.1 (msw-unicode)' > > > ------ > > > I have written the following *simplest* implementation of wx.timer I > > > can think of. ?No workie. ? I want an exception, a print statement, or > > > something. > > > > The wxpython demos all work, but for some reason this isn't. ?The > > > demos are simple and straghtforward, so I think I understand how it > > > should work. ?Clues please? ?I've tried variations of ID's, SetOwners, > > > using and redefining Notify(), Bind, Connect, etc. ?In the cases where > > > the interpreter doesn't complain about passed argument types, the > > > callback function is never called. > > > > import wx > > > > class MyFrame(wx.Frame): > > > ? ? ? ? def __init__(self, parent, id, title): > > > ? ? ? ? ? ? ? ? wx.Frame.__init__(self, parent, id, ? ? title, pos=(100, 100)) > > > > ? ? ? ? ? ? ? ? timer = wx.Timer(self, -1) > > > ? ? ? ? ? ? ? ? self.Bind(wx.EVT_TIMER, self.OnTick, timer) > > > ? ? ? ? ? ? ? ? timer.Start(100) > > > > ? ? ? ? def OnTick(self, event): > > > ? ? ? ? ? ? ? ? print 'Hi. Bye.' > > > ? ? ? ? ? ? ? ? 1/0 #<-- should crash as evidence callback is being called > > > > class MyApp(wx.App): > > > ? ? ? ? def OnInit(self): > > > ? ? ? ? ? ? ? ? frame1 = MyFrame(None, wx.ID_ANY, "This is a test") > > > ? ? ? ? ? ? ? ? frame1.Show(True) > > > ? ? ? ? ? ? ? ? return True > > > > app ? ? = MyApp(0) > > > app.MainLoop() > > > > Thanks for any advice!! > > > > Michael > > > I'm not seeing anything either. Please post this to the wxPython > > user's group for additional help: > > >http://www.wxpython.org/maillist.php > > > Mike > > I think I figured it out. ?By looking at the wxTimer example here:http://wiki.wxpython.org/AnotherTutorial#head-420329f7c159d81cb03a6dd... > > My code created a temporary timer object and did not make it a class > member. ?When I changed it to be a class member with self.timer, then > it worked. > > thanks > Michael Ah...I didn't even think about that. I noticed I had self.timer in my code, but I didn't realize it was required. Sorry I wasn't of more help. Still, you can learn a lot from the wxPython user's group just by reading other people's posts. Mike From benjamin.kaplan at case.edu Wed Jul 2 23:10:17 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 2 Jul 2008 23:10:17 -0400 Subject: wxPython: How can I get window's HANDLE in wxPython. In-Reply-To: References: Message-ID: On Wed, Jul 2, 2008 at 9:40 PM, Leo Lee wrote: > I need a window's handle to be passed to external c++. > Thanks in advance > Try posting this to the wxPython-users mailing list. You'll probably get better answers there. http://www.wxpython.org/maillist.php > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From max at alcyone.com Wed Jul 30 02:09:16 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 23:09:16 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> Message-ID: Carl Banks wrote: > On Jul 30, 1:15 am, "Russ P." wrote: >> All this discussion about "if x" has me wondering. I use it all the >> time because a fully explicit test just seems redundant. But maybe it >> does have some value in terms of readability and type checking. After >> all, it is possible to forget whether something is a number or a list. > > IMO, the only time I think "if x" is really dangerous is if you are > using "if x" instead of "if x is None" to distinguish between None and > a type that can have false values. Well, that would be an exceptionally bad way to test for None-ness, since None is false. The test would never succeed. >> Having said that, it would sure be nice to be able to write >> >> if myList is not empty: >> >> instead of >> >> if len(myList) != 0: > > I can agree with this. I'm getting this sneaking suspicion that you guys are all putting us on. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The doors of Heaven and Hell are adjacent and identical. -- Nikos Kazantzakis From __peter__ at web.de Mon Jul 7 16:04:52 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 07 Jul 2008 22:04:52 +0200 Subject: do a sed / awk filter with python tools (at least as fast) References: Message-ID: Mathieu Prevot wrote: > I use in a bourne shell script the following filter: > > sed '/watch?v=/! d;s/.*v=//;s/\(.\{11\}\).*/\1/' \ > | sort | uniq | awk 'ORS=" "{print $1}' > > that give me all sets of 11 characters that follows the "watch?v=" > motif. I would like to do it in python on stdout from a > subprocess.Popen instance, using python tools rather than sed awk etc. > How can I do this ? Can I expect something as fast ? You should either do it in Python , e. g.: def process(lines): candidates = (line.rstrip().partition("/watch?v=") for line in lines) matches = (c[:11] for a, b, c in candidates if len(c) >= 11) print " ".join(sorted(set(matches))) if __name__ == "__main__": import sys process(sys.stdin) or invoke your shell script via subprocess.Popen(). Invoking a python script via subprocess doesn't make sense IMHO. Peter From kyosohma at gmail.com Wed Jul 16 15:40:58 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 16 Jul 2008 12:40:58 -0700 (PDT) Subject: New to Python - Accessing Lotus Notes References: Message-ID: On Jul 16, 2:11?pm, KDawg44 wrote: > Hi, > > We have a Lotus Notes Database that tracks time spent on projects. > What I would like to do is develop a Time Tracker in Python that > communicates with the server. ?This would pull projects in and allow a > use to start a timer as he/she works on a given project. ?The user > would then be able to commit this back to the database (thus, > preventing them from having to go to the calendar view and pick the > project and enter the hours). > > As another potential feature, I would like the user to be able to > create projects in the app and track time and then when a project > exists in the database, it would retroactively add those hours (users > cannot create their own projects and sometimes managers take some time > to actually get a project in the system). ?Lasty, the user could run a > report by date to get their hours on each project. > > Anyway, long story short, how can I communicate with Lotus Notes to > accomplish these tasks? ?Lotus Notes 7. > > Thank you for your help. ?I am very new to Python and am hoping to > learn a lot from this project so I can incorporate Python into my > daily tasks. ?Also, forgive my rant as I figured out some of my specs > as I typed this. > > Thanks again. > > Kevin Use Google...it is very cool. Here are some links I found: http://mail.python.org/pipermail/python-list/2005-May/323756.html http://www.velocityreviews.com/forums/t350942-python-and-lotus-notes.html HTH Mike From russblau at hotmail.com Fri Jul 18 10:04:29 2008 From: russblau at hotmail.com (Russell Blau) Date: Fri, 18 Jul 2008 10:04:29 -0400 Subject: Regular expression help References: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> Message-ID: wrote in message news:187a9118-97fb-41fc-87f2-d24c4d7522fb at w1g2000prk.googlegroups.com... > I am new to Python, with a background in scientific computing. I'm > trying to write a script that will take a file with lines like > > c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647 > 3pv=0 > > extract the values of afrac and etot and plot them. ... > What is being stored in energy is '<_sre.SRE_Match object at > 0x2a955e4ed0>', not '-11.020107'. Why? because the re.match() method returns a match object, as documented at http://www.python.org/doc/current/lib/match-objects.html But this looks like a problem where regular expressions are overkill. Assuming all your lines are formatted as in the example above (every value you are interested in contains an equals sign and is surrounded by spaces), you could do this: values = {} for expression in line.split(" "): if "=" in expression: name, val = expression.split("=") values[name] = val I'd wager that this will run a fair bit faster than any regex-based solution. Then you just use values['afrac'] and values['etot'] when you need them. And when you get to be a really hard-core Pythonista, you could write the whole routine above in one line, but this seems clearer. ;-) Russ From wuwei23 at gmail.com Thu Jul 24 06:03:09 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 24 Jul 2008 03:03:09 -0700 (PDT) Subject: Confounded by Python objects References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> Message-ID: <645148ca-9c52-44d7-a75a-b6c61c3ffb26@j33g2000pri.googlegroups.com> On Jul 24, 7:45 pm, "boblat... at googlemail.com" wrote: > class Channel: > name = '' > sample = [] > > def __init__(self, name): > self.name = name > > def append(self, time, value): > self.sample.append((time, value)) > self.diag() > > def diag(self): > print (self.name, self.sample) Okay, the problem is you're appending to a _class_ attribute, not to an instance attribute. If you change your class definition to this, it should work: class Channel: def __init__(self, name): self.name = name self.sample = [] That will provide each instance with its own version of the sample attribute. The 'self.name = name' in the __init__ for your original code binds a new attribute to the instance, whereas 'self.sample.append(...' in the class's append was appending to the class attribute instead. Hope this helps. - alex23 From mail at timgolden.me.uk Thu Jul 10 12:13:54 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 10 Jul 2008 17:13:54 +0100 Subject: Local User Control In-Reply-To: References: Message-ID: <48763542.8050304@timgolden.me.uk> Sparky wrote: > On Jul 10, 9:58 am, Tim Golden wrote: >> Sparky wrote: >>> I don't know how feasible this is, but is it possible to have users >>> log in to access a local database file in such a way that allows the >>> program to know what user name and password they logged in with? This >>> would involve separate user names and passwords for each user. >> Well, this is a question which is crying out for some >> context. Are you talking about an existing database >> on an existing platform? If so, which one? Are you >> talking about a database youo're thinking of building? >> If so, the answer's probably yes but only you can >> know. Are you talking about something else altogether? >> >> TJG > > Thanks for the timely response. This would be a database that I am > building myself. The question comes down to is there a feasible way to > verify a user's user name and password from inside that database. > Obviously the file would be encrypted, but if there is going to be > more than one user using it I suppose there would be a separate file > for a log-in. I am just asking for some guidance on how this would > theoretically be implemented. Maybe someone else on the list has a clearer idea than I do, but at this distance from an implementation, all I can say is: yes, I'm sure you can achieve some kind of user authentication. After all, lots of other products already do. Or is your proposed db very different? TJG From Nikolaus at rath.org Fri Jul 18 06:03:22 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Fri, 18 Jul 2008 12:03:22 +0200 Subject: Protecting instance variables Message-ID: <87zlof5x1x.fsf@nokile.rath.org> Hello, I am really surprised that I am asking this question on the mailing list, but I really couldn't find it on python.org/doc. Why is there no proper way to protect an instance variable from access in derived classes? I can perfectly understand the philosophy behind not protecting them from access in external code ("protection by convention"), but isn't it a major design flaw that when designing a derived class I first have to study the base classes source code? Otherwise I may always accidentally overwrite an instance variable used by the base class... Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From paul.hankin at gmail.com Wed Jul 9 15:49:41 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 9 Jul 2008 12:49:41 -0700 (PDT) Subject: Anyone happen to have optimization hints for this loop? References: <43111321-2cc1-4a5e-9189-744131555841@26g2000hsk.googlegroups.com> Message-ID: <1471d37a-d89a-4856-a67c-3e599270f3bf@34g2000hsf.googlegroups.com> On Jul 9, 5:04?pm, dp_pearce wrote: > count = 0 > dmntString = "" > for z in range(0, Z): > ? ? for y in range(0, Y): > ? ? ? ? for x in range(0, X): > ? ? ? ? ? ? fraction = domainVa[count] > ? ? ? ? ? ? dmntString += " ?" > ? ? ? ? ? ? dmntString += fraction > ? ? ? ? ? ? count = count + 1 > ? ? ? ? dmntString += "\n" > ? ? dmntString += "\n" > dmntString += "\n***\n > > dmntFile ? ? = open(dmntFilename, 'wt') > dmntFile.write(dmntString) > dmntFile.close() > Can anyone see a way of speeding this loop up? I'd consider writing it like this: def dmntGenerator(): count = 0 for z in xrange(Z): for y in xrange(Y): for x in xrange(X): yield ' ' yield domainVa[count] count += 1 yield '\n' yield '\n' yield '\n***\n' You can make the string using ''.join: dmntString = ''.join(dmntGenerator()) But if you don't need the string, just write straight to the file: for part in dmntGenerator(): dmntFile.write(part) This is likely to be a lot faster as no large string is produced. -- Paul Hankin From deets at nospam.web.de Tue Jul 22 03:02:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 09:02:38 +0200 Subject: Web Page Construction in Python In-Reply-To: References: Message-ID: <6elf0eF7k1pvU1@mid.uni-berlin.de> SUBHABRATA schrieb: > Dear Group, > I am getting some questions on doing Web Pages in Python. > I have some interactive codes in python for which I like to make web > pages. > I am trying to use kid. > Kid I learnt, and is easy, too. > My questions are: > i) Am I going correct? > ii) Is there any language other than kid? > iii) The worked out examples of kid are not opening properly, is there > any other URL where I can see them. > iv) Can cgi scripting be done with kid? > If any one can spend time on my questions. I suggest you take a look at TurboGears. It's a web-framework that uses KID (or genshi, which is extremely similar) to render pages, and makes web-development considerably easier. http://www.turbogears.org/ Diez From sjmachin at lexicon.net Mon Jul 7 20:48:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 7 Jul 2008 17:48:15 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <6deq2uF21vo2U1@mid.uni-berlin.de> <9b841be4-cd9c-4782-8498-55f053cdbb71@x41g2000hsb.googlegroups.com> Message-ID: On Jul 8, 2:51 am, Henning Thornblad wrote: > When trying to find an alternative way of solving my problem i found > that running this script: > > #!/usr/bin/env python > > import re > > row="" > for a in range(156000): > row+="a" > print "How many, dude?" > print re.search('/[^ "=]*',row) (the / has moved) > > wouldn't take even a second (The re.search part of course) > > This is for me very strange since this, > in theory, is the same problem as before. In theory. In practice, it is the same problem *iff* you start at the end of the text and work backwards. Your original pattern can be characterised as X*Y, where X and Y are character classes; your new one is YX*. You are asking each to search a text that contains many Xs and no Ys. The second pattern will cause a naive search engine to examine each character in the text (is it a Y?) as a candidate for the start of a successful match; each test fails, and the whole expedition has cost O(N). OTOH, the first pattern will start at offset 0, cheerfully cruising past all those lovely Xs, but failing (no Y) at the end of the text. It will then think that it's been too greedy, reduce the matched span of X* from N characters to N-1, fail to find Y, N-2, fail, ... so that's O(N) just for the first trial starting from offset 0. Being naive, it will try again starting from offset 1, 2, 3, ... an O(N**2) process. If Y were instead something more complicated, it would be worse than O(N**2). If you were to tell us what you are actually trying to do, we could probably help you with a faster method. BTW, if the text is 'aaa///bbb///ccc', your original search will find 'aaa///bbb///'; if you want it to find 'aaa/', the pattern should be: '[^ "=/]*/' Cheers, John From henrik at chamalulu.com Tue Jul 1 18:47:20 2008 From: henrik at chamalulu.com (chamalulu) Date: Tue, 1 Jul 2008 15:47:20 -0700 (PDT) Subject: Attribute reference design References: <6cvlk4F3s90U1@mid.uni-berlin.de> Message-ID: On Jul 1, 11:24 pm, "Diez B. Roggisch" wrote: > chamalulu schrieb: > > > Hello. > > I think I'm aware of how attribute access is resolved in python. When > > referencing a class instance attribute which is not defined in the > > scope of the instance, Python looks for a class attribute with the > > same name. (For assignment or deletion this is not the case, > > thankfully.) > > I've been trying to understand why? What is the reason behind, or > > practical purpose of, this design decision? Anyone, please enlighten > > me. > > How else would you resolve methods which are of course defined on the > class but invoked through the instance? > Yes, of course... You're right. Didn't think of that. Thank you. I'll go stand in the corner. :) I think I haven't got this bound/unbound stuff through my head yet. If I dir() a class instance I see the methods right there. Are they not bound to the class instance at instanciation (and as such be attributes of the class instance)? /Henrik From frank at chagford.com Tue Jul 22 11:28:24 2008 From: frank at chagford.com (Frank Millman) Date: Tue, 22 Jul 2008 08:28:24 -0700 (PDT) Subject: Is this a valid use of 'import'? References: Message-ID: <70869cae-ba4f-46c7-9def-c3e6175c3275@m45g2000hsb.googlegroups.com> On Jul 22, 5:22?pm, Tim Golden wrote: > Frank Millman wrote: > > In this particular case, when it is executed, it does a whole lot > > more. It reads in some parameters, establishes a socket connection, > > starts a thread, and starts monitoring the socket using select.select. > > It also exposes some functions that disguise the complexity of reading > > from and writing to the socket. > > This is not, in general, a good idea, no matter how appealing! > There is some subtle stuff going on within the chain of imports, > and firing off a new thread is quite likely to confuse it in > nasty ways later on. Less attractive though it may be, you're > better off having a "startup" function or whatever and calling > that: > > import Utils.client > Utils.client.startup () > > TJG Makes sense. Thanks, Tim. Frank From rajanikanth at gmail.com Tue Jul 8 18:16:21 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Tue, 8 Jul 2008 15:16:21 -0700 Subject: (silly?) speed comparisons In-Reply-To: References: Message-ID: <84bdef3c0807081516g7872d1d8x2ecb448fd1fa900c@mail.gmail.com> Try using a list instead of a vector for the C++ version. Raj On Tue, Jul 8, 2008 at 3:06 PM, mk wrote: > Out of curiosity I decided to make some speed comparisons of the same > algorithm in Python and C++. Moving slices of lists of strings around seemed > like a good test case. > > Python code: > > def move_slice(list_arg, start, stop, dest): > frag = list_arg[start:stop] > if dest > stop: > idx = dest - (stop - start) > else: > idx = dest > del list_arg[start:stop] > list_arg[idx:idx] = frag > return list_arg > > b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] > >>>> import timeit >>>> t = timeit.Timer("move_slice.move_slice(move_slice.b, 4, 6, 7)", "import >>>> move_slice") >>>> t.timeit() > 3.879252810063849 > > (Python 2.5, Windows) > > Implementing the same algorithm in C++: > > #include > #include > #include > > using namespace std; > > vector move_slice(vector vec, int start, int stop, int dest) > { > int idx = stop - start; > vector frag; > > // copy a fragment of vector > for (idx = start; idx < stop; idx++) > frag.push_back(vec.at(idx)); > if( dest > stop) > idx = dest - (stop - start); > else > idx = dest; > // delete the corresponding fragment of orig vector > vec.erase( vec.begin() + start, vec.begin() + stop); > > // insert the frag in proper position > vec.insert( vec.begin() + idx, frag.begin(), frag.end()); > > return vec; > } > > > int main(int argc, char* argv) > { > vector slice; > string u = "abcdefghij"; > int pos; > for (pos = 0; pos < u.length(); pos++) > slice.push_back(u.substr(pos,1)); > > int i; > for (i = 0; i<1000000; i++) > move_slice(slice, 4, 6, 7); > > } > > Now this is my first take at vectors in C++, so it's entirely possible that > an experienced coder would implement it in more efficient way. Still, > vectors of strings seemed like a fair choice - after all, Python version is > operating on similarly versatile objects. > > But I was still rather surprised to see that C++ version took 15% longer to > execute! > > (vector, 4, 6, 7) > $ time slice > > > real 0m4.478s > user 0m0.015s > sys 0m0.031s > > Compiler: MinGW32/gcc 3.4.5, with -O2 optimization (not cygwin's gcc, which > for some reason seems to produce sluggish code). > > > When I changed moving the slice closer to the end of the list / vector, > Python version executed even faster: > >>>> t = timeit.Timer("move_slice.move_slice(move_slice.b, 6, 7, 7)", "import >>>> move_slice") >>>> t.timeit() > 1.609766883779912 > > C++: > > (vector, 6, 7, 7) > $ time slice.exe > > > real 0m3.786s > user 0m0.015s > sys 0m0.015s > > Now C++ version took over twice the time to execute in comparison to Python > time! > > > Am I comparing apples to oranges? Should the implementations be different? > Or does the MinGW compiler simply suck? > > Note: it appears that speed of Python lists falls down quickly the closer to > the list beginning one deletes or inserts elements. C++ vectors do not seem > to be as heavily position-dependent. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From deets at nospam.web.de Tue Jul 29 03:35:41 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jul 2008 09:35:41 +0200 Subject: Python COM In-Reply-To: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> References: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> Message-ID: <6f7vieFa8u2cU1@mid.uni-berlin.de> birdprince at gmail.com schrieb: > I have implemented a COM in C++,buy i don't know how to use this COM > in python. > For example: the COM's ProgID is "MyCOM1.AdvMethod".this COM have two > interfaces,the default interface's name is IAdvMethod,the second > interface's name is IBasicMethod. > How do i use those interfaces in python.Thank you very much,please > answer my question in code. http://starship.python.net/crew/theller/comtypes/ Diez From alan.isaac at gmail.com Tue Jul 22 14:19:34 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Tue, 22 Jul 2008 18:19:34 GMT Subject: sys.stderr.write returns string length in Python 3 Message-ID: Is this new behavior intentional? :: >>> sys.stderr.write("thisisatest\n") thisisatest 12 Here is the reason for it: >>> help(sys.stderr.write) Help on method write in module io: write(self, s: str) method of io.TextIOWrapper instance Thank you, Alan Isaac From JO3chiang at gmail.com Tue Jul 8 03:02:59 2008 From: JO3chiang at gmail.com (jo3c) Date: Tue, 8 Jul 2008 00:02:59 -0700 (PDT) Subject: windows active directory ldap output encoding Message-ID: Hi.. Im trying to get some information out of a windows sever 2003 chinese active directory system so let's say encoding is probably big5 or utf-8 what im doing is simliar to ldapsearch in shell with my python script using python ldap module the result is not the correct encoding.. i've look many places and tried many different encoding on the top of the script #coding=big5 etc.. below is the wrong encoding output .. any help will be much appreciated.. *** ldap://2134.localhost.com:389 - SimpleLDAPObject.set_option ((17, 3),{}) CN=?,OU=2134,DC=localhost,DC=com {'accountExpires': ['9223372036854775807'], 'badPasswordTime': ['128566014672343750'], 'badPwdCount': ['0'], 'cn': ['\xe6\xb1\x9f\xe6\x9f\x8f\xe5\xa3\x95'], 'codePage': ['0'], 'company': ['\xe8\x8f\xaf\xe8\x81\xaf\xe7\x94\x9f \xe7\x89\xa9\xe7\xa7\x91\xe6\x8a\x80'], 'countryCode': ['0'], 'department': ['\xe7\x94\x9f\xe7\x89\xa9\xe7\xa7\x91\xe6\x8a \x80\xe8\x99\x95'], 'displayName': ['\xe6\xb1\x9f\xe6\x9f\x8f\xe5\xa3\x95'], 'distinguishedName': ['CN=\xe6\xb1\x9f\xe6\x9f\x8f \xe5\xa3\x95,OU=300\xe7\xa7\x91\xe6\x8a \x80\xe8\x99\x95,DC=localhost,DC=com'], 'givenName': ['\xe6\x9f\x8f\xe5\xa3\x95'], 'homeMDB': ['CN=\xe4\xbf\xa1\xe7\xae\xb1\xe5\x84\xb2\xe5\xad \x98\xe5\x8d\x80 (MAIL),CN=\xe9\xa0\x90\xe8\xa8\xad\xe5\x84\xb2\xe5\xad \x98\xe7\xbe\xa4\xe7\xb5\x84,CN=InformationStore,CN=MAIL,CN=Servers,CN= \xe9\xa0\x90\xe8\xa8\xad\xe7\xb3\xbb\xe7\xb5\xb1\xe7\xae \xa1\xe7\x90\x86\xe7\xbe\xa4\xe7\xb5\x84,CN=Administrative Groups,CN=localhost,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=localhost,DC=com'], 'homeMTA': ['CN=Microsoft MTA,CN=MAIL,CN=Servers,CN= \xe9\xa0\x90\xe8\xa8\xad\xe7\xb3\xbb\xe7\xb5\xb1\xe7\xae \xa1\xe7\x90\x86\xe7\xbe\xa4\xe7\xb5\x84,CN=Administrative Groups,CN=localhost,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=localhost,DC=com'], 'instanceType': ['4'], 'lastLogoff': ['0'], 'lastLogon': ['128598965066718750'], 'legacyExchangeDN': ['/o=localhost/ou=ExchangAdmin/cn=Recipients/ cn=joechiang'], 'logonCount': ['33'], 'mDBUseDefaults': ['TRUE'], 'mail': ['joechiang at localhost.com'], 'mailNickname': ['joechiang'], 'memberOf': ['CN=AllHQStaff,CN=Users,DC=localhost,DC=com'], 'msExchALObjectVersion': ['60'], 'msExchHomeServerName': ['/o=localhost/ou=ExchangAdmin/ cn=Configuration/cn=Servers/cn=MAIL'], 'msExchMailboxGuid': ['2\x04\x116^\xfc%J\x87yi\xbdj^\x1bl'], 'msExchMailboxSecurityDescriptor': ['\x01\x00\x04\x80x \x00\x00\x00\x94\x00\x00\x00\x00\x00\x00\x00\x14\x00\x00\x00\x04\x00d \x00\x01\x00\x00\x00\x00\x02\x14\x00\x03\x00\x02\x00\x01\x01\x00\x00\x00\x00\x00\x05\n \x00\x00\x00a\x00n\x00x\x00/\x00C\x00N\x00=\x00C\x00o\x00n\x00f\x00i \x00g\x00u\x00r\x00a\x00t\x00i\x00o\x00n \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x05\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00\xd6\xb2i \x1a^\xa7P\xcb\xday \x88\xa9\xf4\x01\x00\x00\x01\x05\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00\xd6\xb2i \x1a^\xa7P\xcb\xday\x88\xa9\xf4\x01\x00\x00'], 'msExchPoliciesIncluded': ['{C96E41C5-C5D5-411B-8672-1A3B6602437F}, {3B6813EC-CE89-42BA-9442-D87D4AA30DBC}', '{C96E41C5-C5D5-411B-8672-1A3B6602437F}, {26491CFC-9E50-4857-861B-0CB8DF22B5D7}'], 'msExchUserAccountControl': ['0'], 'name': ['\xe6\xb1\x9f\xe6\x9f\x8f\xe5\xa3\x95'], 'objectCategory': ['CN=Person,CN=Schema,CN=Configuration,DC=localhost,DC=com'], 'objectClass': ['top', 'person', 'organizationalPerson', 'user'], 'objectGUID': ['\x13\xfa\xc2\xbb\x9e\xee|C\x9d\xa8_\xea]\xef \xc6\x90'], 'objectSid': ['\x01\x05\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00\xd6\xb2i\x1a^\xa7P \xcb\xday\x88\xa9u\x0c\x00\x00'], 'primaryGroupID': ['513'], 'proxyAddresses': ['X400:c=TW;a= ;p=localhost;o=Exchange;s=joechiang;', 'SMTP:joechiang at localhost.com'], 'pwdLastSet': ['128587670396562500'], 'sAMAccountName': ['joechiang'], 'sAMAccountType': ['805306368'], 'showInAddressBook': ['CN=\xe5\x85\xa8\xe5\x9f\x9f\xe9\x80\x9a \xe8\xa8\x8a\xe6\xb8\x85\xe5\x96\xae,CN=All Global Address Lists,CN=Address Lists Container,CN=localhost,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=localhost,DC=com', 'CN=\xe7\x87\x9f\xe9\x81\x8b\xe8\x99\x95,CN=All Address Lists,CN=Address Lists Container,CN=localhost,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=localhost,DC=com', 'CN=\xe7\x94\x9f\xe7\x89\xa9\xe7\xa7\x91\xe6\x8a \x80\xe8\x99\x95,CN=All Address Lists,CN=Address Lists Container,CN=localhost,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=localhost,DC=com', 'CN=\xe6\x89\x80\xe6\x9c\x89\xe4\xbd\xbf \xe7\x94\xa8\xe8\x80\x85,CN=All Address Lists,CN=Address Lists Container,CN=localhost,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=localhost,DC=com'], 'sn': ['\xe6\xb1\x9f'], 'textEncodedORAddress': ['c=TW;a= ;p=localhost;o=Exchange;s=joechiang;'], 'uSNChanged': ['22943844'], 'uSNCreated': ['21991450'], 'userAccountControl': ['66048'], 'userPrincipalName': ['joe at localhost.com'], 'whenChanged': ['20080624074423.0Z'], 'whenCreated': ['20071205035154.0Z']} None From socyl at 987jk.com.invalid Tue Jul 29 09:27:53 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 13:27:53 +0000 (UTC) Subject: backspace problems Message-ID: If I'm in the python interactive interpreter, I get a beep when I hit the backspace key. I must confess, though, that my terminal is "complicated", to put it mildly: I work on a Mac running Leopard; I open a Terminal session, and through it I ssh to an Ubuntu server; on this server I connect to a permanently-running GNU screen session, which has several multiplexed windows going, all running zsh; it is in this convoluted environment that I run the python interactive interpreter.[*] I've determined that the problem occurs only within the GNU screen session. GNU screen is one of the coolest Unix programs ever, one that literally changed the way I work, is there's no way I'll stop using it. So I need to figure out how to fix this. How can I determine the character that the python session is receiving when I hit the backspace key, and how can I tell it to handle it as a backward-delete character? TIA! kynn [*] Actually, it gets worse. My .zshrc file (which gets executed whenever an interactive shell is started) runs the command bindkey '^[[3~' backward-delete-char because, otherwise my regular zsh interaction would not handle the backspace key properly. But the problem I described above occurs whether this command is executed or not. -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From s0suk3 at gmail.com Mon Jul 28 04:47:12 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Mon, 28 Jul 2008 01:47:12 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> <6385b0a8-f7f3-4dc3-91be-e6f158ffb439@a1g2000hsb.googlegroups.com> Message-ID: <13c15de6-2e28-4896-a6ab-67572a27c001@y21g2000hsf.googlegroups.com> On Jul 28, 1:55 am, Lawrence D'Oliveiro wrote: > In message > , > > > > s0s... at gmail.com wrote: > > On Jul 27, 10:55 pm, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: > >> In message > >> <6385b0a8-f7f3-4dc3-91be-e6f158ffb... at a1g2000hsb.googlegroups.com>, > > >> s0s... at gmail.com wrote: > >> > On Jul 26, 6:47 pm, Lawrence D'Oliveiro >> > central.gen.new_zealand> wrote: > >> >> In message > >> >> <024ace13-f72f-4093-bcc9-f8a339c32... at v1g2000pra.googlegroups.com>, > > >> >> s0s... at gmail.com wrote: > >> >> > On Jul 24, 5:01 am, Lawrence D'Oliveiro >> >> > central.gen.new_zealand> wrote: > > >> >> >> In message > > <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, > > > > >> >> >> Jordan wrote: > > >> >> >> > Except when it comes to Classes. I added some classes to code > >> >> >> > that had previously just been functions, and you know what I did > >> >> >> > - or rather, forgot to do? Put in the 'self'. In front of some of > >> >> >> > the variable accesses, but more noticably, at the start of *every > >> >> >> > single method argument list.* > > >> >> >> The reason is quite simple. Python is not truly an > >> >> >> "object-oriented" language. It's sufficiently close to fool those > >> >> >> accustomed to OO ways of doing things, but it doesn't force you to > >> >> >> do things that way. You still have the choice. An implicit "self" > >> >> >> would take away that choice. > > >> >> > By that logic, C++ is not OO. > > >> >> Yes it is, because it has "this". > > >> > You mean the keyword "this"? It's just a feature. How does that make a > >> > difference on being or not being OO? > > >> Because it was one of the things the OP was complaining about (see > >> above). > > > Wrong. > > Reread what the OP said. Stop quoting only portions of my posts that lead to misinterpretation of them. Next time you quote, be sure to quote this (which I also mentioned in the previous post): What the OP complains about has no relevance on what makes a language OO or not. Do you believe otherwise? From INVALID at EXAMPLE.COM Sun Jul 13 12:54:39 2008 From: INVALID at EXAMPLE.COM (INVALID at EXAMPLE.COM) Date: Sun, 13 Jul 2008 16:54:39 +0000 Subject: spam References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <1bc1ddbb-fbfc-4e0c-8337-71d2dd301e5d@z66g2000hsc.googlegroups.com> Message-ID: rickman wrote: >I love the way that people who plonk others feel the need to inform >everyone of it. That ranks up there with, "I know what you are, but >what am I?" It is a matter of basic politeness and common courtesy. Without the plonk, the killfiled poster is left hanging in the wind, wasting his time writing responses that will never be read. If you were talking with a blind man, would you silently creep out of the room leaving him talking to the walls, or would you be polite and excuse yourself before leaving? From Michael.Coll-Barth at VerizonWireless.com Mon Jul 21 12:12:12 2008 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Mon, 21 Jul 2008 12:12:12 -0400 Subject: Python Written in C? In-Reply-To: References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> Message-ID: <20080721162454.9EB5D1E4008@bag.python.org> > > From: mk > Wrong! Real programmers can program using only Touring machine (and > something having to do with post for some reason). I'm sure our > brilliant OP[1] could program in both. Ah, now we can really got OT. My favorite Touring machine is a Jaguar ( with the pronounced 'U' in there ). Oh, you meant "Turing"; . Sorry, I just couldn't resist after the tortured route this thread has taken. The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From Graham.Dumpleton at gmail.com Mon Jul 21 20:18:24 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Mon, 21 Jul 2008 17:18:24 -0700 (PDT) Subject: Problem with Python Server Pages (PSP) References: <9766b993-03e6-4b75-92a2-06244c41e51c@a1g2000hsb.googlegroups.com> Message-ID: <8ce2ffdd-0fb3-4f5f-bde8-1598f9b231bc@i20g2000prf.googlegroups.com> On Jul 21, 9:42?pm, barun.sah... at gmail.com wrote: > Hi, > > I am facing a very basic problem with PSP. I have installedmod_python > (in fedora Core 1), added the lines required for loading Python > modules and handling PSP pages. I have created a hello.psp page. But > when I try to view this hello.psp page, all Python code are getting > displayed. > > The said page is stored at /var/www/html/psp/hello.psp. I guess this > is some configuration problem with Apache, but not able to figure out > the exact problem. I have tried putting those configuration lines for > psp in both httpd.conf and python.conf files. But still it is not > working. > > The Python module (mod_python) is getting loaded. Because when I > telnet to my server, I can find that in the headers. > > These are the versions of the softwares: > Apache: 2.0.47 > Python: 2.2.3mod_python: 3.0.3 > > Thnaks for all your suggestions. What is the Apache configuration snippet you are using to enable mod_python and PSP file handling? Graham From keith.hughitt at gmail.com Wed Jul 16 11:29:26 2008 From: keith.hughitt at gmail.com (Keith Hughitt) Date: Wed, 16 Jul 2008 08:29:26 -0700 (PDT) Subject: Angle brackets in command-line arguments? References: <52f1cde3-6240-46b0-8b03-478454e87688@b1g2000hsg.googlegroups.com> Message-ID: <16827dd4-4621-43d1-b5ee-ab9340f54a96@m36g2000hse.googlegroups.com> On Jul 16, 11:16?am, Gary Herron wrote: > Keith Hughitt wrote: > > Hi all, > > > I am using someone else's script which expects input in the form of: > > > ? ? ?./script.py arg2 > > > I was wondering if the angle-brackets here have a special meaning? It > > seems like > > they specify an input and output stream to use in place of the > > console. I could not > > find anything in the python manual or Python in a Nut-shell though. > > > Anyone know? > > > Thanks, > > Keith > > -- > >http://mail.python.org/mailman/listinfo/python-list > > In most Unix/Linux and related OS shells, ?the angled brackets *do* > specify input and output streams as you surmise. ?However, they are > *not* seen by the script ?as command line arguments. ?(And they are > *not* brackets, and do not need to be matched. ) > > For any command, > ? cmd < file > redirects the contents of file to cmd's standard input, which in Python > is accessed by reading from sys.stdin (use input or raw_input or > sys.stdin.read...) > > Also for any command, > ? cmd > file > redirects the output of cmd to the named file. ?In Python this can be > accessed using print, sys.stdout.write, ... > > Anything written to sys.stderr will not be caught by the ">" > redirection, ans so will probably end up on the screen instead of in file. > > ?Also various shells will provide similar functionality using a variety > of similar syntaxes: ?<<, >>, >&, and |, and so on. > > Gary Herron Thanks all for the quick response. I should have known it was shell- related. I haven't ever had to use this kind of redirection before, mostly just the single-bracket version to feed the contents of a file into some command. The reason it was causing me concern in the first place was that I was trying to execute a python script from Apache Ant, and it was failing. It turned out that when I escaped the angle brackets in Ant, they were there-after treated as normal command-line arguments, so when the script was then executed, it just had some additional values in sys.argv. I ended up getting around the issue by creating a small bash-script which simply wraps input in angle brackets and then executes the python script itself. That way I didn't have to escape anything in in Ant, and things worked well. Thanks everyone for taking the time to explain things to me. I really appreciate the help :) Take care, Keith From ojeeves at gmail.com Wed Jul 2 08:33:14 2008 From: ojeeves at gmail.com (oj) Date: Wed, 2 Jul 2008 05:33:14 -0700 (PDT) Subject: Email Validation with domain References: Message-ID: <9d6f2e4f-099b-404d-a8db-c87ab15062d6@79g2000hsk.googlegroups.com> On Jul 2, 12:41?pm, Sallu wrote: > Hi All, ? import re > msg=raw_input('Enter the email : ') > > def validateEmail(email): > > ? ? ? ? #if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9] > {1,3})(\\]?)$", email) != None: > ? ? ? ? if re.match("^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$", > email) != None: > ? ? ? ? ? ? ? ? print 'Valis' > ? ? ? ? else: > ? ? ? ? ? ? ? ? print 'not' > > validateEmail(msg) ?i wrote a script above it works fine but it does > not check for valid domain like .com .org .in > how to validate with domain Don't try and check that the TLD (.com .org etc.) is valid with a regular expression. Just don't. Especially now that the rules about domain names are now being relaxed and there is no possible way of you predicating what all the new TLDs will be. Validating that that the e-mail address is in a valid form, and validating the domain is valid are two separate things. If you want to validate the domain, do a DNS lookup on the domain or some such. I don't think there are standard modules to provide this functionality included with python. You could try using the socket module, and reading up on the relevant protocols, or making calls to external programs. From carroll at nospam-tjc.com Thu Jul 17 04:01:26 2008 From: carroll at nospam-tjc.com (Terry Carroll) Date: Thu, 17 Jul 2008 01:01:26 -0700 Subject: How to process a very large (4Gb) tarfile from python? Message-ID: I am trying to do something with a very large tarfile from within Python, and am running into memory constraints. The tarfile in question is a 4-gigabyte datafile from freedb.org, http://ftp.freedb.org/pub/freedb/ , and has about 2.5 million members in it. Here's a simple toy program that just goes through and counts the number of members in the tarfile, printing a status message every N records (N=10,000 for the smaller file; N=100,000 for the larger). I'm finding that memory usage goes through the roof, simply iterating over the tarfile. I'm using over 2G when I'm barely halfway through the file. This surprises me; I'd expect the memory associated with each iteration to be released at the end of the iteration; but something's obviously building up. On one system, this ends with a MemoryError exception. On another system, it just hangs, bringing the system to its knees, to the point that it takes a minute or so to do simple task switching. Any suggestions to process this beast? I suppose I could just untar the file, and process 2.5 million individual files, but I'm thinking I'd rather process it directly if that's possible. Here's the toy code. (One explanation about the "import tarfilex as tarfile" statement. I'm running Activestate Python 2.5.0, and the tarfile.py module of that vintage was buggy, to the point that it couldn't read these files at all. I brought down the most recent tarfile.py from http://svn.python.org/view/python/trunk/Lib/tarfile.py and saved it as tarfilex.py. It works, at least until I start processing some very large files, anyway.) import tarfilex as tarfile import os, time SOURCEDIR = "F:/Installs/FreeDB/" smallfile = "freedb-update-20080601-20080708.tar" # 63M file smallint = 10000 bigfile = "freedb-complete-20080708.tar" # 4,329M file bigiTnt = 100000 TARFILENAME, INTERVAL = smallfile, smallint # TARFILENAME, INTERVAL = bigfile, bigint def filetype(filename): return os.path.splitext(filename)[1] def memusage(units="M"): import win32process current_process = win32process.GetCurrentProcess() memory_info = win32process.GetProcessMemoryInfo(current_process) bytes = 1 Kbytes = 1024*bytes Mbytes = 1024*Kbytes Gbytes = 1024*Mbytes unitfactors = {'B':1, 'K':Kbytes, 'M':Mbytes, 'G':Gbytes} return memory_info["WorkingSetSize"]//unitfactors[units] def opentar(filename): modes = {".tar":"r", ".gz":"r:gz", ".bz2":"r:bz2"} openmode = modes[filetype(filename)] openedfile = tarfile.open(filename, openmode) return openedfile TFPATH=SOURCEDIR+'/'+TARFILENAME assert os.path.exists(TFPATH) assert tarfile.is_tarfile(TFPATH) tf = opentar(TFPATH) count = 0 print "%s memory: %sM count: %s (starting)" % (time.asctime(), memusage(), count) for tarinfo in tf: count += 1 if count % INTERVAL == 0: print "%s memory: %sM count: %s" % (time.asctime(), memusage(), count) print "%s memory: %sM count: %s (completed)" % (time.asctime(), memusage(), count) Results with the smaller (63M) file: Thu Jul 17 00:18:21 2008 memory: 4M count: 0 (starting) Thu Jul 17 00:18:23 2008 memory: 18M count: 10000 Thu Jul 17 00:18:26 2008 memory: 32M count: 20000 Thu Jul 17 00:18:28 2008 memory: 46M count: 30000 Thu Jul 17 00:18:30 2008 memory: 55M count: 36128 (completed) Results with the larger (4.3G) file: Thu Jul 17 00:18:47 2008 memory: 4M count: 0 (starting) Thu Jul 17 00:19:40 2008 memory: 146M count: 100000 Thu Jul 17 00:20:41 2008 memory: 289M count: 200000 Thu Jul 17 00:21:41 2008 memory: 432M count: 300000 Thu Jul 17 00:22:42 2008 memory: 574M count: 400000 Thu Jul 17 00:23:47 2008 memory: 717M count: 500000 Thu Jul 17 00:24:49 2008 memory: 860M count: 600000 Thu Jul 17 00:25:51 2008 memory: 1002M count: 700000 Thu Jul 17 00:26:54 2008 memory: 1145M count: 800000 Thu Jul 17 00:27:59 2008 memory: 1288M count: 900000 Thu Jul 17 00:29:03 2008 memory: 1430M count: 1000000 Thu Jul 17 00:30:07 2008 memory: 1573M count: 1100000 Thu Jul 17 00:31:11 2008 memory: 1716M count: 1200000 Thu Jul 17 00:32:15 2008 memory: 1859M count: 1300000 Thu Jul 17 00:33:23 2008 memory: 2001M count: 1400000 Traceback (most recent call last): File "C:\test\freedb\tardemo.py", line 40, in for tarinfo in tf: File "C:\test\freedb\tarfilex.py", line 2406, in next tarinfo = self.tarfile.next() File "C:\test\freedb\tarfilex.py", line 2311, in next tarinfo = self.tarinfo.fromtarfile(self) File "C:\test\freedb\tarfilex.py", line 1235, in fromtarfile obj = cls.frombuf(buf) File "C:\test\freedb\tarfilex.py", line 1193, in frombuf if chksum not in calc_chksums(buf): File "C:\test\freedb\tarfilex.py", line 261, in calc_chksums unsigned_chksum = 256 + sum(struct.unpack("148B", buf[:148]) + struct.unpack("356B", buf[156:512])) MemoryError From drakonik at gmail.com Tue Jul 15 09:13:02 2008 From: drakonik at gmail.com (Nick Dumas) Date: Tue, 15 Jul 2008 09:13:02 -0400 Subject: Suggestion: Python global scope In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 The function of the global keyword is to 'push' local variables to the global scope. If you want to 'import' a variable into a local scope, pass the variable to your function/method as an argument. Anonymous Bastard wrote: > I've been tossing this idea in my mind for some time now: > > In Python, declaring a variable using the global statement automatically > makes it available in all subsequent scopes. > > But to me, it makes more sense to use the global statement to 'import' a > variable from the global scope into the current scope. For instance: > > [code] > global X > X = 1 > > def P(): > X = 2 > print X > global X > print X > > print X > P() > print X > [code] > > Currently, this will print 1, 2, 2 and 2. But if global would be limited > to current scope, it would print 1, 2, 1, 1. > > 'X = 2' would work on the local version of X, 'global X' will 'import' > the global X into the local scope, so any actions on X would reference > the global X, rather than previous X. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkh8ol4ACgkQLMI5fndAv9ieGwCgi51Vs45tgj3mbom0BeM/nBzL XwsAnjRZr9An617xXyiWp9AVBv3FQ3+z =EFee -----END PGP SIGNATURE----- From socyl at 987jk.com.invalid Wed Jul 30 16:41:48 2008 From: socyl at 987jk.com.invalid (kj) Date: Wed, 30 Jul 2008 20:41:48 +0000 (UTC) Subject: how to split text into lines? Message-ID: In Perl, one can break a chunk of text into an array of lines while preserving the trailing line-termination sequence in each line, if any, by splitting the text on the regular expression /^/: DB<1> x split(/^/, "foo\nbar\nbaz") 0 'foo ' 1 'bar ' 2 'baz' But nothing like this seems to work in Python: >>> re.split('^', 'foo\nbar\nbaz') ['foo\nbar\nbaz'] (One gets the same result if one adds the re.MULTILINE flag to the re.split call.) What's the Python idiom for splitting text into lines, preserving the end-of-line sequence in each line? -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From fredrik at pythonware.com Sun Jul 20 09:29:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jul 2008 15:29:15 +0200 Subject: Rotating a cube In-Reply-To: <4881BBCF.2060905@preisshare.net> References: <3d47df08-9734-4e0f-96ad-37da445b4faf@34g2000hsh.googlegroups.com> <8156f68a-3f65-4fca-a725-2e0c4240abd1@v21g2000pro.googlegroups.com> <4881BBCF.2060905@preisshare.net> Message-ID: David Lyon wrote: > But is the question about display graphics ? > > ie rotating a cube using a python framework ? > > With something like python and OpenGL ? or Python and PovRay... or > perphaps python and imagemagick ? can you name one graphics framework that represents a cube as "x + 4*y + 16*z" ? From cokofreedom at gmail.com Thu Jul 24 11:07:34 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 24 Jul 2008 08:07:34 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <40449826-c71d-4c6e-8b74-13069269e5da@z6g2000pre.googlegroups.com> <488896bf$0$3493$426a74cc@news.free.fr> <3d56ad67-bcd7-4840-979a-8648292afcff@j7g2000prm.googlegroups.com> Message-ID: <402c3712-f9bc-4605-b559-33b5adf9c530@b1g2000hsg.googlegroups.com> > > My words aren't as clear as they should be. I mean that Python lets > *you* do something without documenting, or rather stating to use a > better term, that your intention is the non-obvious one. I'm not > saying that Python itself lacks documentation for its own behaviour; > I'm saying it should force you to make your intentions clear and > visible to someone reading your code when you want to do something non- > obvious. > I take it you are relating to the need for less comments within the code as the idea is the Python code itself is readable? Or are you saying that when someone does a clever trick it should be documented better? I'm a little confused as what you mean by no-documenting? I always add doc-strings to modules I will be using heavily as well as a README with them. But that isn't different from programming in other languages and using comments. (Do you mean something like JavaDoc?) From keith.hughitt at gmail.com Wed Jul 9 10:04:04 2008 From: keith.hughitt at gmail.com (Keith Hughitt) Date: Wed, 9 Jul 2008 07:04:04 -0700 (PDT) Subject: Allow tab completion when inputing filepath? Message-ID: Hi all, I've been looking around on the web for a way to do this, but so far have not come across anything for this particular application. I have found some ways to enable tab completion for program-related commands, but not for system filepaths. This would be nice to have when prompting the user to enter a file/directory location. Any suggestions? Thanks, Keith From bruno.desthuilliers at gmail.com Wed Jul 9 16:22:15 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 9 Jul 2008 13:22:15 -0700 (PDT) Subject: Anyone happen to have optimization hints for this loop? References: <43111321-2cc1-4a5e-9189-744131555841@26g2000hsk.googlegroups.com> Message-ID: <7f6c348f-3d49-4483-a3cc-7d4b8eb863a4@27g2000hsf.googlegroups.com> On 9 juil, 18:04, dp_pearce wrote: > I have some code that takes data from an Access database and processes > it into text files for another application. At the moment, I am using > a number of loops that are pretty slow. I am not a hugely experienced > python user so I would like to know if I am doing anything > particularly wrong or that can be hugely improved through the use of > another method. > > Currently, all of the values that are to be written to file are pulled > from the database and into a list called "domainVa". These values > represent 3D data and need to be written to text files using line > breaks to seperate 'layers'. I am currently looping through the list > and appending a string, which I then write to file. This list can > regularly contain upwards of half a million values... > > count = 0 > dmntString = "" > for z in range(0, Z): > for y in range(0, Y): > for x in range(0, X): > fraction = domainVa[count] > dmntString += " " > dmntString += fraction > count = count + 1 > dmntString += "\n" > dmntString += "\n" > dmntString += "\n***\n > > dmntFile = open(dmntFilename, 'wt') > dmntFile.write(dmntString) > dmntFile.close() > > I have found that it is currently taking ~3 seconds to build the > string but ~1 second to write the string to file, which seems wrong (I > would normally guess the CPU/Memory would out perform disc writing > speeds). Not necessarily - when the dataset becomes too big and your process has eaten all available RAM, your OS starts swapping, and then it's getting worse than disk IO. IOW, for large datasets (for a definition of 'large' depending on the available resources), you're sometimes better doing direct disk access - which BTW are usually buffered by the OS. > Can anyone see a way of speeding this loop up? Perhaps by changing the > data format? Almost everyone told you to use a list and str.join()... Which used to be a sound advice wrt/ both performances and readability, but nowadays "only" makes your code more readable (and pythonic...) : bruno at bibi ~ $ python Python 2.5.1 (r251:54863, Apr 6 2008, 17:20:35) [GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from timeit import Timer >>> def dostr(): ... s = '' ... for i in xrange(10000): ... s += ' ' + str(i) ... >>> def dolist(): ... s = [] ... for i in xrange(10000): ... s.append(str(i)) ... s = ' '.join(s) ... >>> tstr = Timer("dostr", "from __main__ import dostr") >>> tlist = Timer("dolist", "from __main__ import dolist") >>> tlist.timeit(10000000) 1.4280490875244141 >>> tstr.timeit(10000000) 1.4347598552703857 >>> The list + str.join version is only marginaly faster... But you should consider this solution even if doesn't that change much to perfs - readabilty counts, too// > Is it wrong to append a string and write once, or should > hold a file open and write at each instance? Is it really a matter of one XOR the other ? Perhaps you should try a midway solution, ie building not-too-big chunks as lists, and writing them to the (opened file) ? This would avoids possible swap and reduce disk IO. I suggest you try this approach with different list-size / write ratios, using the timeit module (and eventually the "top" program on unix or it's equivalent if you're on another platform to check memory/CPU usage) to find out which ratio works best for a representative sample of your input data. That's at least what I'd do... HTH From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 2 04:34:46 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Jul 2008 10:34:46 +0200 Subject: How to make a function associated with a class? In-Reply-To: <0d9c534b-8720-4363-b3e5-eb546dd3637c@8g2000hse.googlegroups.com> References: <69e26f9b-2f00-4318-9bc5-6aa94e141bca@59g2000hsb.googlegroups.com> <4d7cf477-e791-4122-bc20-0dbd1a16bc12@j22g2000hsf.googlegroups.com> <0d9c534b-8720-4363-b3e5-eb546dd3637c@8g2000hse.googlegroups.com> Message-ID: <486b3da1$0$6039$426a34cc@news.free.fr> Kurda Yon a ?crit : > On Jul 1, 5:01 pm, "bruno.desthuilli... at gmail.com" > wrote: >> On 1 juil, 22:43, Kurda Yon wrote: >> >> >> >>> Hi, >>> I have a class called "vector". And I would like to define a function >>> "dot" which would return a dot product of any two "vectors". I want >>> to call this function as follow: dot(x,y). >>> Well, I can define a functions "dot" outside the class and it works >>> exactly as I want. However, the problem is that this function is not >>> associated with the class (like methods a method of the class). >>> For example, if I call "x.calc()" or "y.calc()", python will execute >>> different methods if "x" and "y" belongs to different classes. I want >>> to have the same with my "dot" function. I.e. I want it calculates the >>> dot product ONLY IF the both arguments of that function belong to the >>> "vector" class. >>> Is it possible? >> You don't need to make dot() a method of your Vector class to have >> this behaviour, and making it a method of the Vector class isn't >> enough to have this behaviour. >> >> The simplest solution would be: >> >> class Vector(object): >> def dot(self, other): >> if not isinstance(other, type(self)): >> raise TypeError("can only calculate the dot product of two >> vectors") >> # do the job here and return what's appropriate >> >> Now since it's a binary operator, you might as well implement it as >> such: >> >> class Vector(object): >> def __mul__(self, other): >> if not isinstance(other, type(self)): >> raise TypeError("can only calculate the dot product of two >> vectors") >> # do the job here and return what's appropriate >> >> Then use it as doproduct = vector1 * vector2 >> >> HTH > > As far as I understood, In the first case, you gave, I need to call > the function as follows "x.dot(y)". In the second case I need to call > the function as follows "x*y". But I want to call the function as > follows "dot(x,y)". I tought you could figure it out by yourself from the above examples. > By the way, "type(self)" returns the name of the class to which the > "self" belongs? Nope, it returns the class object (for new-style classes at least). > Does "instance" return "true" if the first argument belongs to the > class whose name Python's classes are objects. type() returns a class object (or a type object for old-style classes IIRC), and isinstance() takes a class or style object (or a tuple of class / type objects) as second argument. > is given in the second argument? isinstance() is documented, you know ? As well as type() FWIW. What about first looking up the fine manual, then come back if there's something you have problem with ?-) From wtanksleyjr at gmail.com Tue Jul 22 17:07:37 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Tue, 22 Jul 2008 14:07:37 -0700 (PDT) Subject: Bidirectional Generators Message-ID: <8e2cf6b7-4b5f-4701-8a4c-bc779ed7305c@m45g2000hsb.googlegroups.com> Okay, I'm almost finished with my first bidirectional generator. By "almost finished" I mean both that it's almost working, and that I'm almost about to replace it with a class that works a bit more like what I currently understand. Surely some other people have worked with this feature... Are there any pages that discuss how it's been useful? No, I don't want to see an implementation of coroutines. I get that one already. :-) -Wm From peter.bulychev at gmail.com Tue Jul 1 14:31:15 2008 From: peter.bulychev at gmail.com (Peter Bulychev) Date: Tue, 1 Jul 2008 22:31:15 +0400 Subject: convert unicode characters to visibly similar ascii characters Message-ID: Hello. I want to convert unicode character into ascii one. The method ".encode('ASCII') " can convert only those unicode characters, which fit into 0..128 range. But there are still lots of characters beyond this range, which can be manually converted to some visibly similar ascii characters. For instance, there are several quotation marks in unicode, which can be converted into ascii quotation mark. Can this conversion be performed in automatic manner? After googling I've only found that there exists Unicode database, which stores human-readable information on notation of all unicode characters ( ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt). And there also exists the Python adapter for this database ( http://docs.python.org/lib/module-unicodedata.html). Using this database I can do something like `if notation.find('QUOTATION')!=-1:\n\treturn "'"`. I believe there is more elegant way. Am I right? Thanks. -- Best regards, Peter Bulychev. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Sun Jul 20 23:51:59 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 20 Jul 2008 20:51:59 -0700 (PDT) Subject: Python Written in C? References: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> Message-ID: On Jul 20, 10:05?pm, Stephen Johnson wrote: > > Carry bits? Who worries about carry bits when you have > > unlimited precision arithmetic? You want cool? > > THIS is cool: > > > j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2])) > > % xyz[1]**(k-1))/xyz[1]**(k-2) > > You call that "cool." I call it "unreadable." Ok, but not in the sense that something like Scheme is unreadable as this is nothing but algebra (albeit complicaed). > > -Steve Johnson From notnorwegian at yahoo.se Sat Jul 12 17:35:58 2008 From: notnorwegian at yahoo.se (maestro) Date: Sat, 12 Jul 2008 14:35:58 -0700 (PDT) Subject: Why is there no GUI-tools like this for Windows? Message-ID: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> http://www.youtube.com/watch?v=PXpwC1o5AcI I have done some GUI-programming for windows with Python but the Tkinter interface sucked and while it is the only one I tried I got the impression they are all the same. It's amazing how retarded a lot of the stuff programmers do is. Watcing that video, that is how it should be. I can just do the layout with my mouse and then there is a program that writes the code for me. GUI-programming is hard for no reason. One good program then forever easy... Is there not something like this for Python/Windows? Is the Linux one only for ruby or for any language? Oh well im switching to Linux anyway and mostly write webapps but still... From craig.pastro at gmail.com Thu Jul 10 13:32:52 2008 From: craig.pastro at gmail.com (craig75) Date: Thu, 10 Jul 2008 10:32:52 -0700 (PDT) Subject: Idiomatic Python to convert list to dict References: <7ec9405c-4e6f-491d-84b2-c81152302b13@79g2000hsk.googlegroups.com> Message-ID: <89d99e55-4a26-4d76-813a-debcf8ff9901@s50g2000hsb.googlegroups.com> On Jul 10, 10:06?am, James Fassett wrote: > Hi all, > > Simple question really on a best practice. I want to avoid adding > duplicates to a list. > > my_list = ['a', 'b', 'c', 'd', 'e'] > dup_map = {} > for item in my_list: > ? ? dup_map[item] = True > > # ... sometime later > > for complex_dict in large_list: > ? ? if complex_dict["char"] not in dup_map: > ? ? ? ? my_list.append(complex_dict["char"]) > ? ? ? ? dup_map[complex_dict["char"]] = True > > For the first part (generating the duplicate map) is there a more > idiomatic Python method for flipping the list into a dict? > > Is there a better way to achieve the overall objective (as hinted at > by the above algorithm)? > > Thanks in advance for any tips. > > James. The dictionary seems like overkill here because, if I understand correctly, the only value associated with a key is "True". So in that case just remove all the code related to the dictionary (and complex_dict) and you end up with my_list = ['a', 'b', 'c', 'd', 'e'] # ... sometime later for char in large_list: if char not in my_list: my_list.append(char) However, as Diez suggests, use a set: my_list = set(['a', 'b', 'c', 'd', 'e']) # ... sometime later for char in large_list: my_list.add(char) # will not add duplicates From ojeeves at gmail.com Fri Jul 25 11:13:55 2008 From: ojeeves at gmail.com (oj) Date: Fri, 25 Jul 2008 08:13:55 -0700 (PDT) Subject: Calling external program from within python References: <6eu684F91muhU1@mid.uni-berlin.de> <6eu75mF92mqcU1@mid.uni-berlin.de> Message-ID: On Jul 25, 3:44?pm, "Diez B. Roggisch" wrote: > Because usually if a program *prompts* the user to enter input (and that > was what I read from the OP's post), one has to deal with pseudo > terminals, not with stdin/out. How does the program writing some text before taking input change how it takes input? If it runs in a terminal and takes input from the user via keyboard, as in the user types a response and presses enter, it's most likely using stdin, in which case subprocess would be perfect. Perhaps that OP can clarify how the tcal program takes input? From bignose+hates-spam at benfinney.id.au Mon Jul 28 20:44:39 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 29 Jul 2008 10:44:39 +1000 Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> <488e3520$0$16766$426a74cc@news.free.fr> Message-ID: <87myk1iknc.fsf@benfinney.id.au> Bruno Desthuilliers writes: > Boy, I don't know who you think you're talking to, but you're > obviously out of luck here. I'm 41, married, our son is now a > teenager, I have an happy social life, quite a lot of work, and no > time to waste in the streets. And FWIW, name-calling won't buy you > much here. It has, at least, long ago bought him a place in my kill-file. Seeing your side of the conversation, I can only confirm that decision as correct. -- \ ?bash awk grep perl sed, df du, du-du du-du, vi troff su fsck | `\ rm * halt LART LART LART!? ?The Swedish BOFH, | _o__) alt.sysadmin.recovery | Ben Finney From basti.wiesner at gmx.net Thu Jul 10 12:58:06 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Thu, 10 Jul 2008 18:58:06 +0200 Subject: plugins using cvs/distutils? References: Message-ID: Deacon : > Hi. I have an open-source application development environment that I > would like to enable an automated package download system for (like > downloadable plugins), using sourceforge as its repository. My > software will have a menu-based popup window, that will list the > packages (Applications) available through the project distribution > page. If a user selects a package from this window, it should be > automatically retrieved and installed by the development environment. > My software already has a system for automatically recognizing and > deploying new packages, so I'm only asking for help with distribution > logistics, I think. > > I'm thinking that I will use the built-in ftplib to list and retrieve > the files (but I'm not sure yet where to look), and then the distutils > should probably be used in a standardized manner to actually install > the packages, right? I've established a CVS, but I'm not aware of any > built-in-python tools for managing the CVS, and I would rather not add > any new user-has-to-download-dependencies for this. Is there an easier > or alternative advisable approach? I have a linux box, should I be > using it to build all of the platform versions? Any advice would be > much appreciated, this is my first distribution project > (sourceforge.net/projects/spade). I'd use setuptools entrypoints. This takes the task of plugin discovery from you, as this is done by setuptools, and allows you to utilize pypi/easy_install for plugin distribution. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From guillermo.listas at googlemail.com Mon Jul 28 09:39:04 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Mon, 28 Jul 2008 06:39:04 -0700 (PDT) Subject: Getting python 2.4 dll Message-ID: Hi there, Is it possible to get a 2.4 dll of python for Windows easily? I need it to use python as scripting language for Vim. Regards, Guillermo From mrkafk at gmail.com Wed Jul 9 10:56:02 2008 From: mrkafk at gmail.com (mk) Date: Wed, 09 Jul 2008 16:56:02 +0200 Subject: (silly?) speed comparisons In-Reply-To: <200807091447.34094.maric@aristote.info> References: <84bdef3c0807081516g7872d1d8x2ecb448fd1fa900c@mail.gmail.com> <200807091447.34094.maric@aristote.info> Message-ID: P.S. Java 1.6 rocks - I wrote equivalent version using ArrayList and it executed in 0.7s. From subhabrata.iisc at hotmail.com Fri Jul 18 06:06:35 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Fri, 18 Jul 2008 03:06:35 -0700 (PDT) Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> Message-ID: Thanx Peter, I would change my variables next time I would post. And obviously, thanx for your solution. I am reviewing it, I was also trying out some solutions. Best Regards, Subhabrata. Peter Otten wrote: > SUBHABRATA wrote: > > > I am trying the following code line: > > def try2(n): > user_line = raw_input("PRINT A STRING:") > user_words = user_line.split() > my_line = "God Godess Heaven Sky" > for word in user_words: > pos = my_line.find(word) > if pos >- 1: > first_char = my_line[pos] > print first_char > elif pos < 0: > missing_word = word > print "It is not found" > print missing_word > else: > print "Error" > s = first_char + " " + missing_word > print s > > try2(1) > > Do you recognise your code? With that jumpstart you should find the error in > no time ;) > > > Here, if I put a string like: > > Petrol Helium Heaven Sky > > In s it is giving me S Helium > > But I am looking for an output of a5 and a6 concatenating all its > > values not the last ones. Can you suggest me any help? Am I missing > > any minor point? > > Yes, use meaningful variables. They won't make your code magically correct > but will make it a lot easier to pinpoint mistakes and false assumptions -- > for you and others. > > Peter From JordanNealBerg at gmail.com Thu Jul 10 00:34:55 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Wed, 9 Jul 2008 21:34:55 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: Message-ID: <5b9065a5-a98d-4a97-8f07-e3a0c12b80a8@i76g2000hsf.googlegroups.com> I was actually just going through an example to show what was happening each step of the way and noticed the overflow!!! bah, stupid tricks tricks tricks!!! The problem is def the overflow, I notice that I start to get negative numbers in the C version, which makes me think that the & 0xffffffff trick won't work (because it will never evaluate to negative in python, right?) Seeing that the problem is the overflow and the bitwise operations returning a negative, does anyone have any suggestions...I will look more into C bitwise tricks in the meantime haha. And in terms of what this is doing in a poker hand evaluator: http://www.suffecool.net/poker/evaluator.html (an evaluator using some nice tricks to evaluate for flushes, straights, and highcard with LU tables then binary search for the rest) then http://senzee.blogspot.com/2006/06/some-perfect-hash.html (does the same thing, but uses perfect hashing instead of a binary search) the function I am having issues with comes up in the hashing algorithm :) From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 11:04:50 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 17:04:50 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <87zlo747gv.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> Message-ID: <4888b609$0$27463$426a74cc@news.free.fr> Torsten Bronger a ?crit : > Hall?chen! > > Bruno Desthuilliers writes: > >> Torsten Bronger a ?crit : >> >>> Bruno Desthuilliers writes: >>> >>>> [...] >>>> >>>> How would you handle this case with an implicit 'self' : >>>> >>>> class Foo(object): >>>> pass >>>> >>>> def bar(self): >>>> print self >>>> >>>> Foo.bar = bar >>> Just like this. However, the compiler could add "self" to >>> non-decorated methods which are defined within "class". >> What's defined within classes are plain functions. It's actually >> the lookup mechanism that wraps them into methods (and manage to >> insert the current instance as first argument). > > And why does this make the implicit insertion of "self" difficult? Did I say such a thing ? Call me pedantic if you want, but I find it easier to understand how something works when using the appropriate terms, that's all. > I could easily write a preprocessor which does it after all. A source-code-preprocessor based solution wouldn't do IMHO. But that was not the point. The point is that a working solution would require to handle "functions-or-else" defined within a class statement as a special case, which obviously makes thing more compl[ex|icated]. Now as far as I'm concerned, as long as such a solution 1/ doesn't impose any restriction wrt/ current features of Python's object model and 2/ doesn't make any of the currently used "metaprogramming" idioms more difficult, I just wouldn't care. From mrkafk at gmail.com Thu Jul 17 11:05:57 2008 From: mrkafk at gmail.com (mk) Date: Thu, 17 Jul 2008 17:05:57 +0200 Subject: storing references instead of copies in a dictionary In-Reply-To: References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: > def f2(arg): > return "f2 "+arg > > def f1(arg): > return "f1 "+arg > > a={"1":"f1","2":"f2"} > print [eval(x[1])(x[0]) for x in a.items()] > def f2(arg): > return "New f2 "+arg > print [eval(x[1])(x[0]) for x in a.items()] Neat trick, if probably dangerous in some circumstances. Anyway, thanks, I didn't think of that. > Don't know if this is any use to you.. At least I learned something. :-) From jwkenne at attglobal.net Tue Jul 22 15:54:05 2008 From: jwkenne at attglobal.net (John W Kennedy) Date: Tue, 22 Jul 2008 15:54:05 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: <48863add$0$5013$607ed4bc@cv.net> Martin Gregorie wrote: > I used Algol 60 on an Elliott 503 and the ICL 1900 series back when it was > a current language. The term "thunking" did not appear in either compiler > manual nor in any Algol 60 language definition I've seen. It doesn't have to; Algol 60 thunks are not part of the language. However, practical implementation of Algol 60 call by name means that thunks are created by every Algol 60 compiler, and the word "thunk" was coined in 1961 to designate them. > A60 could pass > values by name or value and procedures by name. That was it. Call by name > is what is now referred to as reference passing. Either you misunderstood (because in many simple cases the semantics of call-by-reference and call-by-name cannot be distinguished) or the compiler you used implemented non-standard Algol (which was fairly common in compilers meant for day-to-day practical work). Algol call-by-name was a unique form that subsequent language designers have recoiled from in horror. (Historically, "call-by-name" has sometimes been used in non-Algol contexts to mean "call-by-reference".) > Algol 60 did not have 'functions'. It had procedures which could be > declared to return values or not. A procedure that returned a value was > equivalent to a function but the term 'function' was not used. This is simply wrong. You are accurately describing the language syntax, which used (as PL/I does) the keyword "procedure" for both functions and subroutines, but Algol documentation nevertheless referred to "functions". > Similarly > it did not have a mechanism for declaring anonymous procedures. That, like > the incorporation of machine code inserts, would have been a > compiler-specific extension, so it is a terminological mistake to refer to > it without specifying the implementing compiler. Standards-conforming Algol compilers had a limited ability to create de-facto anonymous functions in the call-by-name implementation. -- John W. Kennedy "Information is light. Information, in itself, about anything, is light." -- Tom Stoppard. "Night and Day" From mail at timgolden.me.uk Tue Jul 29 04:33:39 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 29 Jul 2008 09:33:39 +0100 Subject: Questions on 64 bit versions of Python (Thank-you!) In-Reply-To: <1217307763.13376.1265835765@webmail.messagingengine.com> References: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> <488cbeeb$0$17104$9b622d9e@news.freenet.de> <1217307763.13376.1265835765@webmail.messagingengine.com> Message-ID: <488ED5E3.9090607@timgolden.me.uk> python at bdurham.com wrote: > Thanks for everyone's feedback - excellent detail - all my questions > have been answered. > > BTW: Roel was correct that I got confused over the AMD and Intel naming > conventions regarding the 64 bit versions of Python for Windows. (I > missed that nuance that the Intel build refered to the Itanium vs. the > standard off-the-rack 64 bit version of Intel's 586/686 CPU) Frankly, I'm very glad you did get confused: I've learnt more about the various 64-bit architectures in this thread than I ever thought I'd need to know :) TJG From josiah.carlson at gmail.com Thu Jul 10 14:30:11 2008 From: josiah.carlson at gmail.com (Josiah Carlson) Date: Thu, 10 Jul 2008 11:30:11 -0700 (PDT) Subject: Doubts about how implementing asynchronous timeouts through a heap References: <80430d47-aac5-4123-8835-0591faf0baed@34g2000hsf.googlegroups.com> Message-ID: <156ca6dc-2120-4107-9cc5-a05088ae1c63@27g2000hsf.googlegroups.com> On Jul 9, 4:13?am, "Giampaolo Rodola'" wrote: > Hi, > I'm trying to implement an asynchronous scheduler for asyncore to call > functions at a later time without blocking the main loop. > The logic behind it consists in: > > - adding the scheduled functions into a heapified list > - calling a "scheduler" function at every loop which checks the > scheduled functions due to expire soonest > > Note that, by using a heap, the first element of the list is always > supposed to be the one with the lower timeout. > Here's the code I wrote: > > <--- snippet ---> > import heapq > import time > import sys > > delayed_map = [] > > class delayed_call: > ? ? """Calls a function at a later time. > > ? ? The instance returned is an object that can be used to cancel the > ? ? scheduled call, by calling its cancel() method. > ? ? It also may be rescheduled by calling delay() or reset()} methods. > ? ? """ > > ? ? def __init__(self, delay, target, *args, **kwargs): > ? ? ? ? """ > ? ? ? ? - delay: the number of seconds to wait > ? ? ? ? - target: the callable object to call later > ? ? ? ? - args: the arguments to call it with > ? ? ? ? - kwargs: the keyword arguments to call it with > ? ? ? ? """ > ? ? ? ? assert callable(target), "%s is not callable" %target > ? ? ? ? assert sys.maxint >= delay >= 0, "%s is not greater than or > equal " \ > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"to 0 seconds" % (delay) > ? ? ? ? self.__delay = delay > ? ? ? ? self.__target = target > ? ? ? ? self.__args = args > ? ? ? ? self.__kwargs = kwargs > ? ? ? ? # seconds from the epoch at which to call the function > ? ? ? ? self.timeout = time.time() + self.__delay > ? ? ? ? self.cancelled = False > ? ? ? ? heapq.heappush(delayed_map, self) > > ? ? def __le__(self, other): > ? ? ? ? return self.timeout <= other.timeout > > ? ? def active(self): > ? ? ? ? """Return True if this scheduler has not been cancelled.""" > ? ? ? ? return not self.cancelled > > ? ? def call(self): > ? ? ? ? """Call this scheduled function.""" > ? ? ? ? self.__target(*self.__args, **self.__kwargs) > > ? ? def reset(self): > ? ? ? ? """Reschedule this call resetting the current countdown.""" > ? ? ? ? assert not self.cancelled, "Already cancelled" > ? ? ? ? self.timeout = time.time() + self.__delay > ? ? ? ? if delayed_map[0] is self: > ? ? ? ? ? ? heapq.heapify(delayed_map) > > ? ? def delay(self, seconds): > ? ? ? ? """Reschedule this call for a later time.""" > ? ? ? ? assert not self.cancelled, "Already cancelled." > ? ? ? ? assert sys.maxint >= seconds >= 0, "%s is not greater than or > equal " \ > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"to 0 seconds" %(seconds) > ? ? ? ? self.__delay = seconds > ? ? ? ? self.reset() > > ? ? def cancel(self): > ? ? ? ? """Unschedule this call.""" > ? ? ? ? assert not self.cancelled, "Already cancelled" > ? ? ? ? del self.__target, self.__args, self.__kwargs > ? ? ? ? if self in delayed_map: > ? ? ? ? ? ? if delayed_map[0] is self: > ? ? ? ? ? ? ? ? delayed_map.remove(self) > ? ? ? ? ? ? ? ? heapq.heapify(delayed_map) > ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? delayed_map.remove(self) > ? ? ? ? self.cancelled = True > > def fun(arg): > ? ? print arg > > a = delayed_call(0.6, fun, '0.6') > b = delayed_call(0.5, fun, '0.5') > c = delayed_call(0.4, fun, '0.4') > d = delayed_call(0.3, fun, '0.3') > e = delayed_call(0.2, fun, '0.2') > f = delayed_call(0.1, fun, '0.1') > > while delayed_map: > ? ? now = time.time() > ? ? while delayed_map and now >= delayed_map[0].timeout: > ? ? ? ? delayed = heapq.heappop(delayed_map) > ? ? ? ? try: > ? ? ? ? ? ? delayed.call() > ? ? ? ? finally: > ? ? ? ? ? ? if not delayed.cancelled: > ? ? ? ? ? ? ? ? delayed.cancel() > ? ? time.sleep(0.01) > > > Here comes the questions. > Since that the timeouts of the scheduled functions contained in the > list can change when I reset() or cancel() them I don't know exactly > *when* the list needs to be heapified(). > By doing some tests I came to the conclusion that I need the heapify() > the list only when the function I reset() or cancel() is the *first of > the list* but I'm not absolutely sure about it. > When do you think it would be necessary calling heapify()? > I wrote a short test suite which tests the code above and I didn't > notice strange behaviors but since that I don't know much about the > logic behind heaps I'd need some help. > Thanks a lot in advance. > > --- Giampaolohttp://code.google.com/p/pyftpdlib/ According to a quick scan, there is some inefficiencies with your code. In particular, you don't need to re-heapify if the item you need to remove is the first item; you only need to heappop(). In any case, if the Python standard library heapq module supported non- lists as containers, then the pair heap implementation I wrote a couple years ago would be perfect for this particular task. Because of the rewriting of heapq in C, without a bit of monkeypatching, we can't re-use that implementation (which offered insert/remove of arbitrary entries in the heap in O(logn) time, which is significantly faster than the O(n) time of your implementation). What I'm thinking is that we should add a pair heap implementation to the heapq module (which can cache the pure Python functions if it needs to use them), which would then allow us to use that (and others to use it generally), add scheduling, etc. Regardless, it's a 2.7/3.1 feature, so it's ok if we take it slow. - Josiah From animator333 at gmail.com Thu Jul 24 04:50:06 2008 From: animator333 at gmail.com (King) Date: Thu, 24 Jul 2008 01:50:06 -0700 (PDT) Subject: instance comparison Message-ID: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> I am facing a problem where I am really confused about it. I am trying to compare to instances using: if inst1 == inst2 These instances have a overridden method __str__ which returns same string. The condition result is true although they are different instances. If I use: if id(inst1) == id(inst2) The results is false. What's happening here? If I am trying to store this pair in a set where other instances are already stored, but it's not storing it. Although I am sure that there is no pair already stored of same but even if Set is comparing by using string return by __str__ method then it won't. How do I solve this? Is this mean when you have overridden __str__ method then it comapre with results of __str__ or else it will comapre whether they are the same instances? From bignose+hates-spam at benfinney.id.au Mon Jul 7 21:13:59 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 08 Jul 2008 11:13:59 +1000 Subject: Python Agile Software Development Tools Screencasts References: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> <87lk0dwbys.fsf@benfinney.id.au> <87hcb1w6gl.fsf@benfinney.id.au> Message-ID: <87abgtw52g.fsf@benfinney.id.au> Robert Kern writes: > Ben Finney wrote: > > Okay. Where would the public link to those files be? > > > > If I need to "log in" just to download it, that's a needless barrier > > that's going to turn me away too. > > Yes, you do need to log in. Thanks. > If you don't want to do it, that's fine. I certainly don't care. No problem. I hope the OP, who wanted people to see his videos, does care enough to put them somewhere people can get them without needless barriers. -- \ ?Money is always to be found when men are to be sent to the | `\ frontiers to be destroyed: when the object is to preserve them, | _o__) it is no longer so.? ?Voltaire, _Dictionnaire Philosophique_ | Ben Finney From fredrik at pythonware.com Sat Jul 26 07:03:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Jul 2008 13:03:15 +0200 Subject: xml.dom's weirdness? In-Reply-To: References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> Message-ID: Lie wrote: > If you have any idea what black magic is happening in my computer > right now, I'd appreciate it. command completion? (no ubuntu within reach right now, so I cannot check how they've set it up). try starting python with the "-v" option, so you can see exactly when the import occurs. From deets at nospam.web.de Thu Jul 31 10:39:40 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 16:39:40 +0200 Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> <6fe0scFaus40U1@mid.uni-berlin.de> Message-ID: <6fe17mFaus40U2@mid.uni-berlin.de> Diez B. Roggisch wrote: > squishywaffle at gmail.com wrote: > >>> Ctypes is a since python2.5 built-in module that allows to declare >>> interfaces to C-libraries in pure python. You declare datatypes and >>> function prototypes, load a DLL/SO and then happily work with it. No C, >>> no compiler, no refcounts, no nothing. >>> >>> And you can pass python-functions as callbacks. >> >> The first sentence (and some really crummy licensing restrictions >> imposed by the library distributor) alone here excludes this as a >> valid option for this particular case, I definitely need Python 2.4 >> support. > > How much more liberal can it get than MIT-licensed? > > """ > to deal in the Software without restriction, including > without limitation the rights to use, copy, modify, merge, publish, > distribute, sublicense, and/or sell copies of the Software, and to > permit persons to whom the Software is furnished to do so, subject to > the following conditions: > """ Sorry, missed the paragraph """ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. """ Still, AFAIK MIT is pretty liberal. Diez From sorsorday at gmail.com Sun Jul 27 20:35:08 2008 From: sorsorday at gmail.com (Herman) Date: Sun, 27 Jul 2008 17:35:08 -0700 Subject: Where is the correct round() method? Use math.ceil Message-ID: <98aab64d0807271735w111f6ec7w81c9e65f99744199@mail.gmail.com> > > Where is the correct round() method? > Hello, > > I need a round function that _always_ rounds to the higher integer if > the argument is equidistant between two integers. In Python 3.0, this > is not the advertised behavior of the built-in function round() as > seen below: > > >>> round(0.5) > 0 > >>> round(1.5) > 2 > >>> round(2.5) > 2 > > > I would think this is a common need, but I cannot find a function in > the Python library to do it. I wrote my own, but did I miss such a > method in my search of the Python library? > > Thanks Use ceil in the math module: import math math.ceil(number) -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcus at internetnowasp.net Sun Jul 13 22:57:10 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Mon, 14 Jul 2008 10:57:10 +0800 Subject: Malaysia python user group Message-ID: <487AC086.3010600@internetnowasp.net> Hi, I am thinking of promoting Python for the local developers here in Malaysia, via Universities , seminars etc . Is there already a user group here in Malaysia? Any pointers would help. Marcus. From ppearson at nowhere.invalid Tue Jul 8 00:01:05 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 8 Jul 2008 04:01:05 GMT Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> <6ddj74F21uhjU1@mid.individual.net> <4cv8k5-dsg.ln1@rama.nodalpoint> Message-ID: <6dg740F2b1mkU1@mid.individual.net> On Mon, 07 Jul 2008 10:05:56 +0200, TP wrote: > TP wrote: > >> So, the python print command *can* interpret these 4-character as a single >> character. It would be odd if there were no possibility to do the same >> thing when the characters are (i) stored in a python variable > > Sorry, it works when using variables. Try for example: > > col="[0;31m" > esc="\033" > colreset="[0m" > print esc + col + "foobar" + esc + colreset I don't understand exactly what you mean by "Sorry", but let me direct your attention to the fact that the "interpretation" step about which we're talking happens during the parsing of the string literal (i.e., while the statement esc="\033" is processed), not during the execution of the print statement. To prove this assertion, simply print len(esc). You will see that esc is a single character long. -- To email me, substitute nowhere->spamcop, invalid->net. From mdboldin at gmail.com Wed Jul 30 15:14:31 2008 From: mdboldin at gmail.com (mmm) Date: Wed, 30 Jul 2008 12:14:31 -0700 (PDT) Subject: undo a dictionary References: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> Message-ID: <192b4786-85b2-43d3-bb7c-b5716068ff12@56g2000hsm.googlegroups.com> > > And for that matter a way to create a > > dictionary from a set of variables (local or global). > > You have to be more specific: there are {} displays and dict(args) call > and other methods. ?Read the manual. My desire is to take a set of data items in an alpha-numeric range and oput them into a dictionary i.e., x1=1 x2=20 x3=33 to yield the dictionary { 'x1':1, 'x2':20, 'x3':33 } without having to type in as above but instead invoke a function maybe with syntax of dd=make_dict('x1--x99') From kylotan at gmail.com Fri Jul 18 06:23:39 2008 From: kylotan at gmail.com (Ben Sizer) Date: Fri, 18 Jul 2008 03:23:39 -0700 (PDT) Subject: Best Python packages? References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> Message-ID: <17861f55-8ad1-4703-ad22-838675f2afc4@w1g2000prk.googlegroups.com> On Jul 16, 3:31?pm, Fredrik Lundh wrote: > Ben Sizer wrote: > > make my development a lot easier. > > Knowing what kind of development you do might help, of course. ?Some > libraries are excellent in some contexts and suck badly in others... Sure. Mostly I'm just interested in what's out there though. In C++ you have Boost which everybody knows are a source of high quality libraries, covering a fairly wide set of applications. Obviously that's more low-level and less application specific, and the Python standard libs do pretty much everything that is in Boost, but it's that sort of peer-reviewed and widely-applicable list that I'd like to see. I (attempt to) use TurboGears for web development and that depends on a whole bunch of libraries - SQLObject, PyProtocols, RuleDispatch, SimpleJson, FormEncode, etc - and I would never have heard of these if TurboGears' exposure of its internals wasn't so common. Some of these are web-specific but some are not. And I'd never know to look for them specificially, because in many cases it wouldn't occur to me that they exist. (eg. Object-Relational Mappers like SQLObject may be obvious if you come from certain areas of IT, but I'd never heard of them before I started with TurboGears.) For what it's worth, my main areas of interest are gaming, multimedia, and web development. But I just like to hear about anything that people might use which makes their life a lot easier and which perhaps is not application specific - like ORMs or something similar. > Looking at things that larger projects and distributions use can also be > a good idea. ?For example, if you're doing scientific stuff, go directly > to enthought.com. ?If you're doing web stuff, look at the libraries big > Django applications use. ?Etc. Sadly, I know just as little about what major applications are out there as I do about what libraries are out there! -- Ben Sizer From aljosa.mohorovic at gmail.com Thu Jul 31 11:42:46 2008 From: aljosa.mohorovic at gmail.com (Aljosa Mohorovic) Date: Thu, 31 Jul 2008 08:42:46 -0700 (PDT) Subject: current week / weeks in year - best practice References: <6fdur9Fb0nvuU1@mid.uni-berlin.de> Message-ID: <2ac30ca6-554a-4b40-bdb8-a61f2311ab24@l42g2000hsc.googlegroups.com> On Jul 31, 3:58 pm, "Diez B. Roggisch" wrote: > Instead of datetime.now() use date.today(), which removes a lot of > boilerplate. > > int(date.today().strftime("%W")) > > Apart from that, I think it's the way to go. what if i know current context week = 20 (example), what would be the best way to get datetime objects for first and last day of current context week? by "current context week" i don't mean current week for current year but current week when program is iterating all weeks in year. Aljosa From atulskulkarni at gmail.com Thu Jul 24 11:34:40 2008 From: atulskulkarni at gmail.com (Atul.) Date: Thu, 24 Jul 2008 08:34:40 -0700 (PDT) Subject: Encoding for Devanagari Script. Message-ID: Hello All, I wanted to know what encoding should I use to open the files with Devanagari characters. I was thinking of UTF-8 but was not sure, any leads on this? Anyone used it earlier? Thanks in Advance. Regards, Atul. From fredrik at pythonware.com Tue Jul 22 15:08:32 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 21:08:32 +0200 Subject: software engineering foundations? In-Reply-To: <18566.11394.326317.821553@montanaro-dyndns-org.local> References: <18566.11394.326317.821553@montanaro-dyndns-org.local> Message-ID: skip at pobox.com wrote: > Sorry for the off-topic-ish post. My son (a fairly junior sysadmin type) > mentioned to me today that he was looking for online courses for Perl. (I > don't hold that against him. Perl is still a lingua franca in the sysadmin > realm.) In my work I have from time-to-time had to pick up and maintain > scripts (generally shell/Python stuff) which non-professional programmers > have written. It's never what you would call a "pleasant" task. > > There are software construction skills which are entirely distinct from the > language in which you are programming. We can tout object-oriented, > structured programming, test-driven development or other software > engineering techniques, but there is a body of knowledge out there which is > orthogonal to the language in which the code is written. People who are not > professional programmers often lack those skills and their code shows it. just get McDonnell's "Code Complete": http://www.cc2e.com/ From nclbndk759 at googlemail.com Fri Jul 18 10:40:02 2008 From: nclbndk759 at googlemail.com (nclbndk759 at googlemail.com) Date: Fri, 18 Jul 2008 07:40:02 -0700 (PDT) Subject: Regular expression help References: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> Message-ID: <8a5492e9-15a6-458e-90b1-c25b5bf4a318@i20g2000prf.googlegroups.com> On Jul 18, 3:35?pm, Nick Dumas wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > I think you're over-complicating this. I'm assuming that you're going to > do a line graph of some sorta, and each new line of the file contains a > new set of data. > > The problem you mentioned with your regex returning a match object > rather than a string is because you're simply using a re function that > doesn't return strings. re.findall() is what you want. That being said, > here is working code to mine data from your file. > > [code] > line = 'c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 > mad=-3.597647 3pv=0' > > energypat = r'\betot=(-?\d*?[.]\d*)' > > #Note: To change the data grabbed from the line, you can change the > #'etot' to 'afrac' or 'emad' or anything that doesn't contain a regex > #special character. > > energypat = re.compile(energypat) > > re.findall(energypat, line)# returns a STRING containing '-12.020107' > > [/code] > > This returns a string, which is easy enough to convert to an int. After > that, you can datapoints.append() to your heart's content. Good luck > with your work. > > > > nclbndk... at googlemail.com wrote: > > Hello, > > > I am new to Python, with a background in scientific computing. I'm > > trying to write a script that will take a file with lines like > > > c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647 > > 3pv=0 > > > extract the values of afrac and etot and plot them. I'm really > > struggling with getting the values of efrac and etot. So far I have > > come up with (small snippet of script just to get the energy, etot): > > > def get_data_points(filename): > > ? ? file = open(filename,'r') > > ? ? data_points = [] > > ? ? while 1: > > ? ? ? ? line = file.readline() > > ? ? ? ? if not line: break > > ? ? ? ? energy = get_total_energy(line) > > ? ? ? ? data_points.append(energy) > > ? ? return data_points > > > def get_total_energy(line): > > ? ? rawstr = r"""(?P.*?)=(?P.*?)\s""" > > ? ? p = re.compile(rawstr) > > ? ? return p.match(line,5) > > > What is being stored in energy is '<_sre.SRE_Match object at > > 0x2a955e4ed0>', not '-11.020107'. Why? I've been struggling with > > regular expressions for two days now, with no luck. Could someone > > please put me out of my misery and give me a clue as to what's going > > on? Apologies if it's blindingly obvious or if this question has been > > asked and answered before. > > > Thanks, > > > Nicole > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (MingW32) > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > iEYEARECAAYFAkiAqiAACgkQLMI5fndAv9h7HgCfU6a7v1nE5iLYcUPbXhC6sfU7 > mpkAn1Q/DyOI4Zo7QJhF9zqfqCq6boXv > =L2VZ > -----END PGP SIGNATURE----- Thanks guys :-) From lxz3002 at yahoo.com.cn Wed Jul 16 22:10:16 2008 From: lxz3002 at yahoo.com.cn (Leo Lee) Date: Thu, 17 Jul 2008 10:10:16 +0800 Subject: wxPython: How can I get window's HANDLE in wxPython. References: Message-ID: Thank you , Mike. "Mike Driscoll" ??????:ad849714-c6a9-4308-a997-d6d1d43a915b at t54g2000hsg.googlegroups.com... On Jul 2, 8:40 pm, "Leo Lee" wrote: > I need a window's handle to be passed to external c++. > Thanks in advance Are you talking about a wxPython wx.Window object or an external window handle? If the latter, then I recommend asking about that on the PyWin32 user's group. Otherwise, follow Paul's suggestion. Mike From victorsubervi at gmail.com Tue Jul 15 08:41:03 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 15 Jul 2008 14:41:03 +0200 Subject: Type Problem Message-ID: <4dc0cfea0807150541p43e3c3eco749f02dc712d9ff0@mail.gmail.com> Hi; Forgive multiple posts in one day: online very infrequently Why am I getting this error? import os dir_dict = {6:36, 5:26, 4:22, 3:18, 2:14, 1:12} cur_dir = os.getcwd() dirs = os.path.split(cur_dir) len = len(dirs) type(len(dirs)) Traceback (most recent call last): File "", line 1, in type(len(dirs)) TypeError: 'int' object is not callable Forgot to bring it with me, but type(len) gives me an intelligent response. TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From eliben at gmail.com Thu Jul 10 13:40:35 2008 From: eliben at gmail.com (eliben) Date: Thu, 10 Jul 2008 10:40:35 -0700 (PDT) Subject: using Python's AST generator for other languages Message-ID: Hello, I'm building a parser in Python, and while pondering on the design of my ASTs had the idea to see what Python uses. I quickly got to the compiler.ast module, and understood it's automatically generated. So I went to the source, ast.txt and tools/compiler/astgen.py, where I was this unexpected message: """Generate ast module from specification This script generates the ast module from a simple specification, which makes it easy to accomodate changes in the grammar. This approach would be quite reasonable if the grammar changed often. Instead, it is rather complex to generate the appropriate code. And the Node interface has changed more often than the grammar. """ Now, to me the design of the AST in Python looks quite elegant, especially from the point of view of the AST's user (using Visitors to walk the AST). And astgen.py looks like a nice approach to generate tons of boilerplate code. So, my questions: 1) Is the compiler.ast module really employed during the compilation of Python into .pyc files ? 2) What is the meaning of the comment in astgen.py ? Are the Python maintainers unhappy with the design of the AST ? 3) What other approach would be recommended to generate a very detailed AST hierarchy, if the one in astgen.py is dissapointing ? Thanks in advance Eli From cwitts at gmail.com Thu Jul 31 02:59:50 2008 From: cwitts at gmail.com (Chris) Date: Wed, 30 Jul 2008 23:59:50 -0700 (PDT) Subject: how to split text into lines? References: Message-ID: <7ed81072-aaf1-4e06-98b5-e6fa94268cbd@r66g2000hsg.googlegroups.com> On Jul 31, 7:26?am, alex23 wrote: > kj wrote: > > Sorry, I should have googled this first. ?I just found splitlines()... > > > Still, for my own edification, is there a way to achieve the same > > effect using re.split? > > re.split(os.linesep, ) works the same as .splitlines() > > Neither retain the EOL for each line, though. The only way I'm aware > of is to re-add it: > > [s+os.linesep for s in re.split(os.linesep, )] > > Was that what you were after? or what about 'string'.splitlines(True) as that retains newline characters. ;) From otr2 at tuningchannel.de Mon Jul 21 07:56:26 2008 From: otr2 at tuningchannel.de (otr2 at tuningchannel.de) Date: Mon, 21 Jul 2008 04:56:26 -0700 (PDT) Subject: Python Embedding Thread Message-ID: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> Hi :) I want to run Python in my app. That works still fine. But my app supports now Threads and I would like to know what to do, that it runs without problems. PyGILState_Release and PyGILState_Ensure should solve the problem right? Where do I have to put this two commands around? between each Command that increase, decrease a reference? Currently, this is a small code-snippet that represents the part of the code-execution: PyObject *f_globals=NULL, *f_locals=NULL, *mod=NULL, *rv=NULL; mod = PyImport_ImportModule("__main__"); if (!mod) return; f_globals = PyModule_GetDict(mod); f_locals = PyDict_New(); PyDict_Update(f_locals, f_globals); if (!f_locals) { Py_DECREF(mod); PyErr_Print(); return; } rv = PyRun_String( , Py_file_input, f_locals, f_locals); if (!rv) PyErr_Print(); Py_XDECREF(rv); Py_DECREF(mod); Py_DECREF(f_locals); Py_DECREF(f_locals); Thanks a lot for your help :) From timaranz at gmail.com Thu Jul 10 00:32:38 2008 From: timaranz at gmail.com (Tim Mitchell) Date: Thu, 10 Jul 2008 16:32:38 +1200 Subject: python scalability Message-ID: <487590E6.7020004@gmail.com> Hi All, I work on a desktop application that has been developed using python and GTK (see www.leapfrog3d.com). We have around 150k lines of python code (and 200k+ lines of C). We also have a new project manager with a C# background who has deep concerns about the scalability of python as our code base continues to grow and we are looking at introducing more products. I am looking for examples of other people like us (who write desktop apps in python) with code bases of a similar size who I can point to (and even better talk to) to help convince him that python is scalable to 300+ lines of code and beyond. I have looked at the python success stories page and haven't come up with anyone quite like us. One of my project managers questions is: "Are we the only company in the world with this kind and size of project?" I want to say no, but am having trouble convincing myself, let alone him. If you are involved in this kind of thing please get in touch with me. Thanks, Tim From Russ.Paielli at gmail.com Sat Jul 26 15:48:33 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 26 Jul 2008 12:48:33 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> Message-ID: <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> > If, as I wrote, you permit the omission of "self" in method signatures > defined within class definitions, then you could still insist on > instance attribute qualification using "self" - exactly as one would > when writing Java according to certain style guidelines. I'm not sure exactly what people mean here by allowing "self" to be "omitted" in method signatures. If it is omitted, then it seems to me that a place holder would be needed to the interpreter that the first argument is not just another name for "self." In an earlier post on this thread (don't feel like looking it up at the moment), someone suggested that member data could be accessed using simply ".member". I think he might be on to something. The dot is a minimal indicator that the data is a class member rather than just local. However, a placeholder is still needed in the signature. So why not allow something like this?: class MyClass: def func( , xxx, yyy): .xxx = xxx local = .yyy The "self" argument is replaced with nothing, but a comma is used as a placeholder. From segfaulthunter at gmail.com Mon Jul 14 18:53:12 2008 From: segfaulthunter at gmail.com (name) Date: Mon, 14 Jul 2008 15:53:12 -0700 (PDT) Subject: Why is there no GUI-tools like this for Windows? References: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> Message-ID: <6b3ee6bd-c83f-4d24-9ed1-4aeb1a39275b@w7g2000hsa.googlegroups.com> It seems the video is showing glade, which is also available for wx under the name wxglade, I do not know whether it's available for Windows. I think it should work because it itself is written in Python. I personally prefer to code my GUI myself, so I can do looping stuff with it, but that is just me. From thomas.troeger.ext at siemens.com Fri Jul 25 05:00:44 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Fri, 25 Jul 2008 11:00:44 +0200 Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: Lawrence D'Oliveiro wrote: > Specified by whom? The most common setting these days is 4 columns. Where? I've randomly seen code snipplets that indent using spaces or, worse, tabstop != 8, but most code I've come across uses tabstop width 8, which is how it was meant to be from the beginning of time. Unfortunately, for many people it's hard to understand that a tabstop is not the same as indenting with spaces, but I think this is leading too far and will end in a dogmatic discussion like the `ViM vs. Emacs' war. Anyways, if you claim tabstop 4 is most widely used I'd like to see some kind of a reference for that since it contradicts not only my experience. Finally, I'd like to throw in this one from the Linux kernel sources, from `Documentation/CodingStyle: ------------------------------------------------------------------------ Chapter 1: Indentation Tabs are 8 characters, and thus indentations are also 8 characters. There are heretic movements that try to make indentations 4 (or even 2!) characters deep, and that is akin to trying to define the value of PI to be 3. [...] Now, some people will claim that having 8-character indentations makes the code move too far to the right, and makes it hard to read on a 80-character terminal screen. The answer to that is that if you need more than 3 levels of indentation, you're screwed anyway, and should fix your program. In short, 8-char indents make things easier to read, and have the added benefit of warning you when you're nesting your functions too deep. Heed that warning. ------------------------------------------------------------------------ From Tribulations at Paralleles.invalid Sun Jul 6 17:42:26 2008 From: Tribulations at Paralleles.invalid (TP) Date: Sun, 06 Jul 2008 23:42:26 +0200 Subject: interpretation of special characters in Python Message-ID: <3rq7k5-lqf.ln1@rama.nodalpoint> Hi everybody, I am new to Python, I try to understand how Python treats special characters. For example, if I execute the following line in a shell console, I obtain a colored string: $ python -c "print '\033[30;44m foo \033[0m'" So, it works. Some time ago, I have made a lot of shell variables with all possible colors (with shell functions executed each time I launch a new shell). For example: $ echo -e $esc$ColorBlackOnDarkblue foo $esc$ColorReset gives the same result than the python command above. To know the corresponding non-interpreted characters, I can use the -n option of echo: $ echo -n $esc$ColorBlackOnDarkblue foo $esc$ColorReset \033[30;44m foo \033[0m So, it is exactly the string above, as expected. My problem arises when it comes to get these shell variables ( $esc, $ColorBlackOnDarkblue, $ColorReset) in a Python script, with os.environ, in the following 5-line script: import os Color = os.environ['ColorBlackOnDarkblue'] ColorReset = os.environ['ColorReset'] Esc = os.environ['esc'] print '%s%s%s%s%s' % (Esc, Color, " foo ", Esc, ColorReset) Run this script color.py, but after having defined these shell variables in a shell: $ export esc="\033" $ export ColorBlackOnDarkblue="[30;44m" $ export ColorReset="[0m" When I execute the Python script, I do not obtain any special character interpretation in Python: $ python color.py \033[30;44m foo \033[0m Why? What is the problem? Is there any solution? I really want to get my shell color variables. Thanks a lot -- TP (Tribulations Parall?les) "Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert). From stefan_ml at behnel.de Fri Jul 11 01:36:19 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 11 Jul 2008 07:36:19 +0200 Subject: Bypassing WebFilter security In-Reply-To: <563968a1-3cc3-4009-beca-d5d367d4ccff@k13g2000hse.googlegroups.com> References: <563968a1-3cc3-4009-beca-d5d367d4ccff@k13g2000hse.googlegroups.com> Message-ID: <4876F153.2020406@behnel.de> pranav wrote: > I am working in an organization, which is using a very strict > webcontent filter management suite. Due to this i am unable to > download any exe file, or surf web (even the necessary downloads from > sourceforgenet are blocked). I was wondering, if python could be of > any help. Say i have a python script, and i pass the URL of > downloadable file, and it just downloads the file for me. Nice try. Can I talk to your employer for a minute? :) Honestly, the language doesn't make any difference here, and there isn't much you can do unless you control both sides, i.e. the server and the client. But I would suggest you actually talk to your employer yourself to see if there's an official way to get what you want. Stefan From gherron at islandtraining.com Thu Jul 17 12:45:01 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 17 Jul 2008 09:45:01 -0700 Subject: properly delete item during "for item in..." In-Reply-To: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> References: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> Message-ID: <487F770D.8070405@islandtraining.com> Ratko wrote: > Say you have something like this: > > for item in myList: > del item > > Would this actually delete the item from the list or just decrement > the reference counter because the item in myList is not associated > with name "item" anymore (but still is with myList[itemIndex])? In > other words, is "item" a temporary reference to myList[itemIndex] or > is it actually that reference that myList has stored? > The 'del' statement does not delete an object, it deletes a reference to an object. In this case, the variable item is deleted from the scope, and the referred-to object will have its reference counter decremented by 1. (But, as you surmise, not to zero, because the list will still reference it.) You could remove the object from the list with del myList[i] if you knew i. HOWEVER, don't do that while looping through the list! Changing a list's length will interact badly with the for loop's indexing through the list, causing the loop to mis the element following the deleted item. Gary Herron > I am not sure if this question even makes any sense anymore. I've been > using python for years and never had any problems (and I don't now > either) but now that I had to revisit c++/STL, I had to deal about > these issues and was wondering how python does it. > > Thanks, > Ratko > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Sat Jul 12 01:10:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 01:10:52 -0400 Subject: Python 3.0 and removal of the 'string' module In-Reply-To: <87skugotpw.fsf@benfinney.id.au> References: <87wsjtqiyo.fsf@benfinney.id.au> <87iqvdq6qz.fsf@benfinney.id.au> <487706b7$0$9695$9b622d9e@news.freenet.de> <87abgorgiv.fsf@benfinney.id.au> <76f1bf48-b05f-472b-9bfc-cf59dd2a97ca@m45g2000hsb.googlegroups.com> <87skugotpw.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > So, in summary, despite the appearance of the "Python 3.0" page on the > wiki, there's really no single clearing-house source of Python 3.0 > information that is maintained. The interested party needs to know a > half-dozen different resources to find out what's changing, and none > of the resources seems to attempt to be a single point of entry for > the interested party. The problem in this respect, as I hinted before, is that nothing gets added or changed unless someone (or ones) volunteers to write a complete patch (code + tests + doc as appropriate) and, usually, someone (or ones) reviews and applies the patch. And once it is in, it is there for anyone to look at. At this point, the changes Guido most cared about have pretty much been done as far as I know, subject to bug fixes and a few tweaks. Other things that might go in are things he will allow but does not care too much about. The process is looser than I imagine it would be in a compamy where the project manager (or someone) hires people and directs them to work on specific items. From animator333 at gmail.com Thu Jul 24 05:53:15 2008 From: animator333 at gmail.com (King) Date: Thu, 24 Jul 2008 02:53:15 -0700 (PDT) Subject: instance comparison References: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> Message-ID: The only methods I do have in class is __init__ and __str__. How ever inst1 and inst2 is coming from a dictionary where I stored them with a unique id. inst1 = stored[id] inst2 = stored[id] Is this makes a difference? I will rip down the piece of code giving me problem and post. From bearophileHUGS at lycos.com Fri Jul 11 19:10:09 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 11 Jul 2008 16:10:09 -0700 (PDT) Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: Denis Kasak: > spam = ['a', 'n', 'n', 'a'] > eggs = spam[:] > if spam.reverse() == eggs: > print "Palindrome" An alternative version: >>> txt = "anna" >>> txt == txt[::-1] True >>> txt = "annabella" >>> txt == txt[::-1] False Bye, bearophile From tjreedy at udel.edu Sat Jul 26 00:06:05 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 00:06:05 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> Message-ID: Paul Boddie wrote: > On 25 Jul, 22:37, Terry Reedy wrote: >> Kay Schluehr wrote: >>> This isn't the problem Jordan tries to address. It's really just about >>> `self` in the argument signature of f, not about its omission in the >>> body. >> That is not at all how I read him, so I will let him respond if he >> wishes. The main problem moving a function from module scope to class >> scope is prefixing the proper variables. Adding a param name, whether >> 'self', 's', 'this', or whatever, is trivial and hardly worth the ink. > > He wrote the following of relevance: > > "I added some classes to code that had previously just been functions, > and you know what I did - or rather, forgot to do? Put in the 'self'. > In front of some of the variable accesses, but more noticably, at the > start of *every single method argument list.*" > > And rounding off with this on the subject: > > "The problem is that the explicit requirement to have self at the > start > of every method is something that should be shipped off to the > implicit category." There is no requirement to have 'self' in the parameter list. It can be 's', 'this', 'me', 'yo'(Spanish for I), or 'cls' (for class methods), or any other identifier in whatever language. In 3.0, identifiers are not restricted to ascii but can be any unicode 'word' as defined in the manual. So the proposal would have to be that the compiler scan the function body and decide which dotted name prefix is the one to be implicitly added. Have fun writing the discovery algorithm. However, I think this is pretty silly. Just write the name you want. Or the proposal would have to be that 'self' is mandatory for all programmers in all languages. I think *that* would be pernicious. People are now free to write the more compact 's.sum = s.a + s.b + s.c' if they want instead of the 'self' version. And again, not everyone writes in English. tjr From robert.rawlins at thinkbluemedia.co.uk Sun Jul 20 06:33:07 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Sun, 20 Jul 2008 11:33:07 +0100 Subject: __del__ methods In-Reply-To: <87hcalxvx0.fsf@benfinney.id.au> References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> <87hcalxvx0.fsf@benfinney.id.au> Message-ID: <007d01c8ea54$0067e360$0137aa20$@rawlins@thinkbluemedia.co.uk> > In Python 2.x, "classic" classes (which are not part of the unified > type hierarchy) are deprecated, and exist only for backward > compatibility with old code. > > You need to create "new-style" classes > by inheriting from some > class that is part of the unified type hierarchy; if there is no > obvious candidate, 'object' is the recommended choice. Thanks Ben, This isn?t something I'd seen before (god that makes me feel stupid). I've always based my code off the odd example that's dotted around and hadn?t ever done any proper reading on these new type classes. I've done a little reading this morning and really love a great deal of the concepts, I'll be upgrading my app to this spec in the next few days. Robert From bj_666 at gmx.net Tue Jul 1 05:10:06 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Jul 2008 09:10:06 GMT Subject: how to judge urllib.Request is finished? References: Message-ID: <6cuajeF3e7podU1@mid.uni-berlin.de> On Tue, 01 Jul 2008 15:16:03 +0800, oyster wrote: > currently I am using > [code] > req=urllib2.Request(url) > data='' > if '' not in data: > fd=urllib2.urlopen(req) > data=fd.read() > time.sleep(10) > time.sleep(10) > blahblah > [/code] That looks very strange. Why the ``if`` and the `sleep()`\s? The ``if`` condition is always true, so it's completely unnecessary. The `read()` call is blocking, that means it returns iff the complete data is read. So there's no need to wait or to check if all is read. If there's a problem with the connection an exception should be raised by `urllib2`. Ciao, Marc 'BlackJack' Rintsch From waldemar.rymarkiewicz at gmail.com Thu Jul 24 04:02:18 2008 From: waldemar.rymarkiewicz at gmail.com (waldek) Date: Thu, 24 Jul 2008 01:02:18 -0700 (PDT) Subject: python.exe crash and ctypes use References: <6eou4dF82ehaU1@mid.individual.net> Message-ID: <89572ec1-fad8-4b42-a2da-73c62d469ee5@m36g2000hse.googlegroups.com> On Jul 23, 4:39 pm, Thomas Heller wrote: > waldek schrieb: > > > > > Hi, > > > I have module A.py and B.dll which exports C functions by cdecl_ > > > In A.py I pass callback (py callable) to dll. Next, thread inside dll > > simply calls my callback (in a loop). After few secs I got crash of > > python.exe. > > > How to debug it? > > > I'm using winxp and py 2.5.2 > > > =========================== > > def mycallback(data, size) > > return 0 > > > CBFUNC = CFUNCTYPE(c_int,POINTER(c_int), c_int) > > dll = cdll.mydll > > > if dll.RegisterCallback(CBFUNC(mycallback)) != 0: > > print "Error." > > =========================== > > You need the callback function instance - what the CBFUNC(mycallback) > call returns - alive as long as some C code is calling it. > If you don't sooner or later the Python garbage collector will > free it since it seems to be no longer used. ctypes does NOT keep > the callback function alive itself. > > Thomas In fact ctypes does not keep references to callback passed directly to dll. Now it works. Thanks Thomas. Waldek From cjw at ncf.ca Tue Jul 29 18:29:23 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Tue, 29 Jul 2008 18:29:23 -0400 Subject: static variables in Python? In-Reply-To: References: Message-ID: <488F99C3.1000501@ncf.ca> kj wrote: > In Larry Bates writes: > >> kj wrote: >>> Yet another noob question... >>> >>> Is there a way to mimic C's static variables in Python? Or something >>> like it? The idea is to equip a given function with a set of >>> constants that belong only to it, so as not to clutter the global >>> namespace with variables that are not needed elsewhere. >>> >>> For example, in Perl one can define a function foo like this >>> >>> *foo = do { >>> my $x = expensive_call(); >>> sub { >>> return do_stuff_with( $x, @_ ); >>> } >>> }; >>> >>> In this case, foo is defined by assigning to it a closure that has >>> an associated variable, $x, in its scope. >>> >>> Is there an equivalent in Python? >>> >>> Thanks! >>> >>> kynn > > >> First names in Python are just that, names that point to objects. Those objects >> can contain any type of information including other objects. They are NOT >> buckets where things are stored. > >> 1) Names (variables in Perl/C) defined within a Python function are placed in >> its local namespace. They are not visible in the global namespace. > >> 2) Yes you can have a local name point to a global. This is often used in >> classes with attributes because looking up local is somewhat quicker than >> looking up the class attribute. > >> def foo(): >> x = expensive_call >> return do_stuff_with(x()) > > Maybe I'm missing your point, the goal is to have a "runtime > constant" associated with the function. In the your definition of > foo, expensive_call gets called every time that foo gets called; > this is what I'm trying to avoid! > > Maybe it's easier to see what I mean with JavaScript: > > function foo() { > if (foo.x === undefined) foo.x = expensive_call(); > return do_stuff_with(foo.x); > } > > Here, expensive_call is called only once (assuming it never returns > undefined). > > OK, I guess that in Python the only way to do what I want to do is > with objects... > > kynn You might consider using a singleton class. Colin W. From max at alcyone.com Thu Jul 17 15:19:29 2008 From: max at alcyone.com (Erik Max Francis) Date: Thu, 17 Jul 2008 12:19:29 -0700 Subject: x, = y (???) In-Reply-To: References: Message-ID: kj wrote: > I just came across an assignment of the form > > x, = y > > where y is a string (in case it matters). > > 1. What's the meaning of the comma in the LHS of the assignment? > 2. How could I have found this out on my own? > > (Regarding (2) above, I consulted the index of several Python > reference books but I could not find the answer to (1). I hope to > find a better Python reference!) It's unpacking a 1-tuple: (x,) = y The parentheses here are not necessary and are sometimes left out. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The United States, while they wish for war with no nation, will buy peace with none. -- James Madison From ddasilva at umd.edu Wed Jul 30 02:03:04 2008 From: ddasilva at umd.edu (Daniel da Silva) Date: Wed, 30 Jul 2008 02:03:04 -0400 Subject: Overloaded Functions In-Reply-To: <12f9fcac-501b-4eba-8068-24dca22a94b5@m36g2000hse.googlegroups.com> References: <3070b5ff-0914-4109-841a-ee622e4105a5@27g2000hsf.googlegroups.com> <12f9fcac-501b-4eba-8068-24dca22a94b5@m36g2000hse.googlegroups.com> Message-ID: <8d9ec3dd0807292303g5508c554g14439644debc549e@mail.gmail.com> With a little hacking, you might be able to do something like this: @overload("f", (int, int, str)) def f1(x, y, z): pass @overload("f", (str, str)) def f2(x, y): pass The way I would typically do method overloading would be as follows (this has been tested): class Person: def __init__(*args): argTypes = tuple(map(type,args)) methods = { (str,int) : Person.initAllInfo, (str,) : Person.initOnlyName, } methods[argTypes[1:]](*args) # ........................ def initAllInfo(self, name, age): self.name = name self.age = age def initOnlyName(self, name): self.name = name self.age = 100 With this overload-dictionary approach, it may be possible to elegantly implement the overloading decorator I described at the top of this email. I hoped this helped. Daniel On Tue, Jul 29, 2008 at 12:05 PM, Tim Henderson wrote: > Yes i am aware of that but I want the code to be self documenting, so > the intent is clear. I actually have an implementation using that > style which you suggest. I would like cleaner style, like the one i > suggested in my first post. > > Cheers > Tim Henderson > -- > http://mail.python.org/mailman/listinfo/python-list > From dingo_1980 at yahoo.com Tue Jul 1 00:33:11 2008 From: dingo_1980 at yahoo.com (dingo_1980) Date: Mon, 30 Jun 2008 21:33:11 -0700 (PDT) Subject: Are the following supported in scipy.sparse Message-ID: <7f324b8e-e1f9-466e-b6f2-fde8d5f11494@a70g2000hsh.googlegroups.com> I wanted to know if scipy.sparse support or will support the following functions which are available in scipy.linalg or scipy or numpy: Inverse Cholesky SVD multiply power append eig concatenate Thanks... From peter.anderson at internode.on.net Tue Jul 15 09:50:12 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Tue, 15 Jul 2008 23:50:12 +1000 Subject: Python internals Message-ID: <008ca729$0$20313$c3e8da3@news.astraweb.com> Hi! I am slowly teaching myself Python. I was reading David Beazley's excellent book "Python - Essential Reference"; in particular about variables. Let me quote: "Python is a dynamically typed language in which names can represent values of different types during the execution of a program. In fact the names used in the program are really just labels for various quantities and objects. The assignment operator simply creates an association between a name and a value. This is different from C, for example, in which a name (variable) represents a fixed size and location in memory..." As an old mainframe programmer, I understand the way C does things with variable but this text got me wondering how Python handles this "association" between variable name and value at the lower level. Is it like a fifo list? If there is any Python guru that can help I would be most interested in your thoughts. Regards, Peter -- Peter Anderson There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things -- Niccolo Machiavelli, The Prince, ch. 6 From wuwei23 at gmail.com Wed Jul 23 09:19:59 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 23 Jul 2008 06:19:59 -0700 (PDT) Subject: os.walk question References: <79b8d5e1-709f-4a4f-957d-8acbee20018b@c2g2000pra.googlegroups.com> Message-ID: On Jul 23, 10:26?pm, Fredrik Lundh wrote: > ? ? ?random.choice(filter(os.path.isfile, glob.glob("/*"))) > > isn't that bad, though. I'll agree to that. From bgporter at acm.org Wed Jul 30 14:03:16 2008 From: bgporter at acm.org (Brett g Porter) Date: Wed, 30 Jul 2008 14:03:16 -0400 Subject: Reasoning behind 'self' parameter in classes? In-Reply-To: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> Message-ID: <4890ACE4.4060703@acm.org> Robert Dailey wrote: > This is an example of a response I'm looking for: > "The self parameter is required because the parser is a bit old and > needs to know the exact object you're referencing" > > This is _not_ an example of what I'm looking for: > "Specifying self is a great mysterious thing that we should never > question. Do not question the language! The language is mighty! Don't > bring C++ to Python!" > Fredrik Lundh has written a very clear explanation of this at http://effbot.org/pyfaq/why-must-self-be-used-explicitly-in-method-definitions-and-calls.htm (or http://bit.ly/3EUiCf if you don't feel like stitching that URL back together...) From jazle at nospam.log.web.id Tue Jul 22 22:15:44 2008 From: jazle at nospam.log.web.id (Jaimy Azle) Date: Wed, 23 Jul 2008 09:15:44 +0700 Subject: Python Embedding Thread References: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> <87bf413d-eb98-47c0-8466-237c45fd1a0e@e53g2000hsa.googlegroups.com> <5081c3df-cb66-443b-ac71-be9661ae057d@27g2000hsf.googlegroups.com> Message-ID: wrote: > I fixed the code. This code snippet runs in a seperate thread: > > > PyObject *dict=NULL; > PyGILState_STATE state = PyGILState_Ensure(); > dict = CreateMyGlobalDictionary(); > > PyRun_String(, Py_file_input, dict, dict); > > ReleaseGlobalDictionary(dict); > > But it still does not work... :-/ Have you initialize interpreter with PyEval_InitThreads? look at http://www.python.org/doc/1.5.2/api/threads.html for more information. Oh, btw... I did use python in a bit different scenario than you've described. Since you attempt to run different script per-host thread, you might need python multiple interpreter support, I suggest you take a look mod_python implementation. Salam, -Jaimy. From bruno.desthuilliers at gmail.com Fri Jul 18 08:13:17 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 18 Jul 2008 05:13:17 -0700 (PDT) Subject: storing references instead of copies in a dictionary References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: <87150e65-907d-485a-90be-f4ad441415fd@y22g2000prd.googlegroups.com> On 17 juil, 15:56, mk wrote: > Calvin Spealman wrote: > > To your actual problem... Why do you wanna do this anyway? If you want > > to change the function in the dictionary, why don't you simply define > > the functions you'll want to use, and change the one you have bound to > > the key in the dictionary when you want to change it? In other words, > > define them all at once, and then just d['1'] = new_f1. What is wrong > > with that? > > Well, basically nothing except I need to remember I have to do that. > > Suppose one does that frequently in a program. It becomes tedious. I > think I will define some helper function then: > > >>> def helper(fundict, newfun): > ... fundict[newfun.func_name] = newfun > ... > > _If_ there were some shorter and still "proper" way to do it, I'd use > it. You're halfway there. from functools import partial callbacks = {} register_callback = partial(helper, callbacks) @register_callback def f1(arg): print "f1", arg callbacks['f1']('ok') @register_callback def f1(arg): print "new f1", arg callbacks['f1']('ok') From Scott.Daniels at Acm.Org Tue Jul 22 21:36:39 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 22 Jul 2008 18:36:39 -0700 Subject: Python Written in C? In-Reply-To: References: <143349c3-b0e9-49d8-9426-8b030b23d2c9@l42g2000hsc.googlegroups.com> Message-ID: <1uKdnTtUhIQHFRvVnZ2dnUVZ_q_inZ2d@pdx.net> Erik Max Francis wrote: > Ethan Furman wrote: > >> Iain King wrote: >>> The story of a Real Programmer: >>> http://www.pbm.com/~lindahl/mel.html >>> Iain >> >> Wow. Awesome story. > > If my google-fu is up to snuff, these are "screenshots" (scans of > printouts) of the actual blackjack game in operation: > > http://wps.com/projects/LGP-21/Software/LGP30-Blackjack1.jpg > http://wps.com/projects/LGP-21/Software/LGP30-Blackjack2.jpg > > and here's a scan of a printout of some "source code" (machine language): > > http://wps.com/projects/LGP-21/Software/CrapGame.tiff > The high school I went to had an LGP-30, and I learned to program on it. Rumor had it that a student from two years before me used to work late in the lab, and allow the janitors to play blackjack, and it is further rumored that he made a bit of money leaning on the transfer control button. --Scott David Daniels Scott.Daniels at Acm.Org From s0suk3 at gmail.com Wed Jul 23 23:22:31 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Wed, 23 Jul 2008 20:22:31 -0700 (PDT) Subject: Autocompletion and Interactive Tables in a Python IDE References: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Message-ID: <66184e22-13e0-43fe-a6c4-21b1edee7267@i20g2000prf.googlegroups.com> On Jul 23, 4:28 pm, Anthony wrote: > Hi, I'm a FoxPro programmer, but I want to learn python before it's > too late. I do a lot of statistical programming, so I import SPSS > into python. In my opinion, the best features of Visual FoxPro 9.0 > were: > a) Intellisense (tells you what classes/methods are available and what > variables go into a function) > b) Code Completion (guesses your code after four letters) > c) Data-Orientation; multiple data sessions can be open, data can be > viewed easily > > Python's IDLE has only half of the first of these features. I did a > lot of searching and found the PyDev extensions for Eclipse's Python > IDE, and found that they've got Intellisense. I'm still missing b and > c, and am getting extremely frustrated programming so slowly.. > > So two questions: > Is there any package, gui, IDE, anything that will do FoxPro-style > code completion? If it works in Eclipse, even better.. > I can't find a good screenshot, but here's a better description: > You type "BROW" and it pops up a window that says "BROWSE" ..at this > point if you hit enter it completes the word.. > > and > > How can I view open SPSS data in one of the Python GUIs? Again, > Eclipse would be the preference. > Here's an example of how I'd like to browse the data:http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=... > I don't want to have to switch back and forth between Python and SPSS > while I'm programming; I just want to stay in one of them.. > > What can I do? I feel extremely inefficient when I don't have these > three features.. > You're looking at it the wrong way. A programming language's strength is not the availability if IDEs that exist for it. It might be a bit convenient, depending on the circumstances, but it is, by no means, what makes a language a good language, because it's actually not a property of the language itself. And if you're new to any programming language in particular, that's actually the lesser of the things you should be worrying about. However, when you become more experienced and need to be more productive, that might be problem. It's a shame that there aren't as much IDEs for Python as there are for, e.g., Java or C++. I usually use Komodo. Then there's the one you mentioned, Eclipse. You'll probably get more replies mentioning a lot of others, but what I think I should point out is that you seem to be overrating the importance of it. Sebastian From deets at nospam.web.de Mon Jul 21 14:55:12 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 21 Jul 2008 20:55:12 +0200 Subject: scanf in python In-Reply-To: <4884be5e$0$19722$426a74cc@news.free.fr> References: <4884be5e$0$19722$426a74cc@news.free.fr> Message-ID: <6ek4cgF7hq4vU1@mid.uni-berlin.de> AMD schrieb: > Hello, > > I often need to parse strings which contain a mix of characters, > integers and floats, the C-language scanf function is very practical for > this purpose. > I've been looking for such a feature and I have been quite surprised to > find that it has been discussed as far back as 2001 but never > implemented. The recommended approach seems to be to use split and then > atoi or atof or to use regex and then atoi and atof. Both approaches > seem to be a lot less natural and much more cumbersome than scanf. If > python already has a % string operator that behaves like printf, why not > implement either a %% or << string operator to behave like scanf, use > could be like the followng: > > a, b, c = "%d %f %5c" %% "1 2.0 abcde" > > or > > a, b, c = "%d %f %5c" << "1 2.0 abcde" > > %% is closer to the % operator > > << seems more intuitive to me > > either of this methods seems to me much simpler than: > > lst = "1 2;0 abcde".split() > a = int(lst[0]) > b = float(lst[1]) > c = lst[2] > > or even worse when using regular expressions to parse such simple input. > > I like python because it is concise and easy to read and I really think > it could use such an operator. > > I know this has been discussed before and many times, but all previous > threads I found seem to be dead and I would like to invite further > investigation of this topic. I'm pretty certain python won't grow an additional operator for this. Yet you are free to create a scanf-implementation as 3rd-party-module. IMHO the usability of the approach is very limited though. First of all, the need to capture more than one input token is *very* seldom - nearly all commandline-tools I know that do require interactive user-input (like the linux kernel config tool) do so by providing either line-by-line value entry (including defaults, something you can't do with your approach), or even dialog-centric value entry with curses. So - I doubt you will gather much momentum on this. Good luck though. Diez From tjreedy at udel.edu Fri Jul 25 17:05:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Jul 2008 17:05:27 -0400 Subject: Execution speed question In-Reply-To: <4889a36f$1@news2-rz-ap.ethz.ch> References: <4889a36f$1@news2-rz-ap.ethz.ch> Message-ID: Suresh Pillai wrote: > I am performing simulations on networks (graphs). I have a question on > speed of execution (assuming very ample memory for now). I simplify the > details of my simulation below, as the question I ask applies more > generally than my specific case. I would greatly appreciate general > feedback in terms of computing and of course considerations specific to > implementation in Python. > > The nodes in my network may be ON or OFF. The network starts off with > all nodes in the OFF state. I loop through the nodes. For each node > that is OFF, I consider some probability of it turning ON based on the > states of its neighbours. I MUST GO THROUGH ALL NODES BEFORE DECIDING > WHICH ONES TO TURN ON. If the nodes do not have to be processed in any particular order, then you could keep them either in a dict, with the value being either On or Off (True,False)(plus connection data) or a pair of sets, one for On and one for Off. The advantage of the dict is that the items would be fixed and only their values would change, but you needlessly scan through On items. The advantage of the set pair is that you only scan through Off items but have to move some from Off to On. I will not guess which would be faster over a complete run, or how this will compare with using lists. tjr From bignose+hates-spam at benfinney.id.au Fri Jul 11 04:06:48 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 11 Jul 2008 18:06:48 +1000 Subject: Python 3.0 and removal of the 'string' module References: <87wsjtqiyo.fsf@benfinney.id.au> <87iqvdq6qz.fsf@benfinney.id.au> <487706b7$0$9695$9b622d9e@news.freenet.de> Message-ID: <87abgorgiv.fsf@benfinney.id.au> "Martin v. L?wis" writes: > > This is rather disappointing. Is that entire page suspect? > > All documentation about Python 3 is suspect until Python 3 gets > actually released (nobody can say for sure how the release will > look like in all details). Is there a better information source, then, for the current state of what's expected in Python 3.0? -- \ ?Somebody told me how frightening it was how much topsoil we | `\ are losing each year, but I told that story around the campfire | _o__) and nobody got scared.? ?Jack Handey | Ben Finney From dikkie at nospam.org Wed Jul 2 14:21:20 2008 From: dikkie at nospam.org (Dikkie Dik) Date: Wed, 02 Jul 2008 20:21:20 +0200 Subject: Discover Islam - The Fastest Growing Religion in the World ! In-Reply-To: <9d3ed65e-335c-4d45-8374-505ae7d434b1@p25g2000hsf.googlegroups.com> References: <9d3ed65e-335c-4d45-8374-505ae7d434b1@p25g2000hsf.googlegroups.com> Message-ID: <486bc722$0$23180$bf4948fe@news.tele2.nl> If it so fast growing, I'd rather wait for a stable release... LOL From sneuberger at mitre.org Mon Jul 21 09:14:53 2008 From: sneuberger at mitre.org (Neuberger, Sheldon N.) Date: Mon, 21 Jul 2008 09:14:53 -0400 Subject: ntlm authentication Message-ID: <7B3D44209E8C944288889D4132FEC4125B98D8@IMCSRV6.MITRE.ORG> Is there any way to make urllib2 handle NTLM authentication? Sheldon Neuberger -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris.hulan at gmail.com Tue Jul 8 13:41:36 2008 From: chris.hulan at gmail.com (Chris Hulan) Date: Tue, 8 Jul 2008 10:41:36 -0700 (PDT) Subject: How to make python scripts .py executable, not bring up editor References: Message-ID: On Jul 7, 5:56 pm, korean_dave wrote: > From command Prompt, i type in a script, "tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? sounds like you need to adjust the file association so .py files are associated with python.exe From workitharder at gmail.com Mon Jul 28 14:03:10 2008 From: workitharder at gmail.com (bukzor) Date: Mon, 28 Jul 2008 11:03:10 -0700 (PDT) Subject: Easier way to get the "here" path? References: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> <649bb102-51aa-4781-ad40-3762e59db626@56g2000hsm.googlegroups.com> Message-ID: <53f12f73-74da-4ac4-ac9d-8981da3d9ca6@34g2000hsf.googlegroups.com> On Jul 28, 10:34?am, bukzor wrote: > On Jul 26, 9:19?am, Andrew wrote: > > > > > bukzor wrote: > > >>>> from os.path import abspath, realpath > > >>>> realpath(path.__file__.rstrip("c")) > > > > '/home/bgolemon/python/symlinks/path.py' > > > >>>> realpath(abspath(path.__file__.rstrip("c"))) > > > > '/home/bgolemon/python/symlinks/symlinks/path.py' > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > I find it interesting that I get something different: > > > In [1]: import path > > path.pyc > > > In [2]: path.__file__ > > Out[2]: 'path.pyc' > > > In [3]: path.__file__.rstrip("c") > > Out[3]: 'path.py' > > > In [4]: from os.path import abspath, realpath > > > In [5]: realpath(path.__file__.rstrip("c")) > > Out[5]: '/home/andrew/sym/sym/path.py' > > > In [6]: realpath(abspath(path.__file__.rstrip("c"))) > > Out[6]: '/home/andrew/sym/sym/path.py' > > > I get the same thing for realpath() and realpath(abspath()) > > It seems to me you can just use: > > > In [1]: import path > > path.pyc > > > In [2]: from os.path import abspath > > > In [3]: realpath(path.__file__.rstrip("c")) > > Out[3]: '/home/andrew/sym/sym/path.py' > > > By the way, I am in /home/andrew/sym and path is symlinked from > > /home/andrew/sym/sym/path.py to /home/andrew/sym/path.py > > > -- > > Andrew > > As you can see above, I get the wrong think if I do that. It's very > strange that we're getting different things. I'm using python 2.4, > maybe it was updated in 2.5? After doing a little testing, it seems that realpath was in fact improved between 2.4 and 2.5. I need to stick with 2.4, so the abspath() call is still necessary for me. Regardless, the answer to my question is that there's no good built-in way to do this. Even the code above fails for some cases (say the symlink is named just "c"), making the problem non-trivial. To me, this is a failure of python's "batteries included". Is this worthy of a PEP? I'd like to add something like "__absfile__" or maybe "os.path.absolute_script_path()". Sample implementation: def scriptpath(): from inspect import currentframe file = currentframe().f_back.f_locals.get('__file__', None) if file.endswith(".pyc"): file = file.rstrip("c") from os.path import realpath, abspath return realpath(abspath(file)) Testing: ~/python>ls -l foo.py* c sym/* lrwxrwxrwx 1 bgolemon asic 10 Jul 28 10:46 c -> sym/ bar.py* lrwxrwxrwx 1 bgolemon asic 10 Jul 28 10:38 foo.py -> sym/ bar.py* -rw-rw-r-- 1 bgolemon asic 149 Jul 28 10:57 foo.pyc -rwxrwx--- 1 bgolemon asic 76 Jul 28 10:53 sym/bar.py* -rw-rw-r-- 1 bgolemon asic 149 Jul 28 10:58 sym/bar.pyc ~/python>cat sym/bar.py #!/usr/bin/env python from scriptpath import scriptpath print scriptpath() ~/python>./c /home/bgolemon/python/sym/bar.py ~/python>./sym/bar.py /home/bgolemon/python/sym/bar.py ~/python>./foo.py /home/bgolemon/python/sym/bar.py ~/python>python >>> import foo /home/bgolemon/python/sym/bar.py ~/python>cd sym/ ~/python/sym>python >>> import bar /home/bgolemon/python/sym/bar.py --Buck From bignose+hates-spam at benfinney.id.au Wed Jul 9 07:12:25 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 09 Jul 2008 21:12:25 +1000 Subject: mock with inheritance References: <87df8aea-a7e4-4e30-9384-960b0a8cfc89@27g2000hsf.googlegroups.com> Message-ID: <873amjux9i.fsf@benfinney.id.au> lidiriel writes: > But i don't know how to mock the class Component. Note that Component > provide the attribut env. I prefer to use the MiniMock framework . You don't need to specify what interface the mock object has. Its Mock objects will allow *any* attribute access, method or otherwise, and simply report what was done. You can then check that report to see if it matches what you expect; the author suggests that the existing standard-library 'doctest' module is ideal for such checking. -- \ ?It is the mark of an educated mind to be able to entertain a | `\ thought without accepting it.? ?Aristotle | _o__) | Ben Finney From larry.bates at websafe.com` Thu Jul 10 12:03:10 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 10 Jul 2008 11:03:10 -0500 Subject: Loading just in time In-Reply-To: References: Message-ID: D'Arcy J.M. Cain wrote: > I am trying to create a utility module that only loads functions when > they are first called rather than loading everything. I have a bunch > of files in my utility directory with individual methods and for each I > have lines like this in __init__.py: > > def calc_tax(*arg, **name): > from calc_tax import calc_tax as _func_ > calc_tax = _func_ > return _func_(*arg, **name) > > This works the first time I call utility.calc_tax but if I call it > again I get a "TypeError: 'module' object is not callable" error. Is > there any way to do what I want or do I have to put everything back > into a single file. Of course, I can simply change all my calls to > utility.calc_tax.calc_tax(...) but I have a lot of code to change if I > do that. > > Thanks. > You are stuck in a futile battle called "premature optimization". I would suggest that you stop worrying about any performance you would gain from doing something like this. Python has been "highly" optimized to handle imports in a very efficient way. Just put your functions in a file and import them. from myfunctions import calc_tax, ... Then you don't have to preface the function name with the module name. -Larry From JordanNealBerg at gmail.com Wed Jul 9 23:56:59 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Wed, 9 Jul 2008 20:56:59 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) Message-ID: I am trying to rewrite some C source code for a poker hand evaluator in Python. Putting aside all of the comments such as just using the C code, or using SWIG, etc. I have been having problems with my Python code not responding the same way as the C version. C verison: unsigned find_fast(unsigned u) { unsigned a, b, r; u += 0xe91aaa35; u ^= u >> 16; u += u << 8; u ^= u >> 4; b = (u >> 8) & 0x1ff; a = (u + (u << 2)) >> 19; r = a ^ hash_adjust[b]; return r; } my version (Python, hopefully ;)): def find_fast(u): u += 0xe91aaa35 u ^= u >> 16 u += u << 8 u ^= u >> 4 b = (u >> 8) & 0x1ff a = (u + (u << 2)) >> 19 r = a ^ hash_adjust[b] return r As far as I understand the unsigned instructions in C just increase amount of bytes the int can hold, and Python automatically converts to longs which have infinite size when necessary, so I am not sure why I am getting different results. I assume that I am missing something fairly simple here, so help a n00b out if you can :) Thanks in advance, jnb From tjreedy at udel.edu Tue Jul 29 15:28:45 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 15:28:45 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87tze9qeyw.fsf@nokile.rath.org> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <488D5B2C.10808@gmail.com> <488e6af8$0$20692$426a74cc@news.free.fr> <87tze9qeyw.fsf@nokile.rath.org> Message-ID: Nikolaus Rath wrote: > Bruno Desthuilliers writes: >> Nikolaus Rath a ?crit : >>> Thats true. But out of curiosity: why is changing the interpreter such >>> a bad thing? (If we suppose for now that the change itself is a good >>> idea). >> Because it would very seriously break a *lot* of code ? > > Well, Python 3 will break lots of code anyway, won't it? Each code breaking change was evaluated as a cost against the long-term net benefits. Many are removals that were announced years ago and which will not break code written with an eye to the future. An example is the removal of 'apply', which was replace with '*iterable' years ago. Some proposed changes, were rejected only because they would break too much code, or because automatic fixed would not be easy. For these reasons, the core Python syntax is pretty much untouched. Attribute lookup is part of core syntax. From samwyse at gmail.com Mon Jul 14 16:46:12 2008 From: samwyse at gmail.com (samwyse) Date: Mon, 14 Jul 2008 13:46:12 -0700 (PDT) Subject: Problems Returning an HTTP 200 Ok Message References: <1cf880cc-2036-42dc-8217-d52a714c1710@a70g2000hsh.googlegroups.com> <9bc65e72-be16-4f73-9dfb-6ddeaae34c21@m73g2000hsh.googlegroups.com> <8596af5b-fd0a-413e-8051-62d650e9a153@8g2000hse.googlegroups.com> Message-ID: <8e0527eb-3af1-428f-bfc2-5c1809c33274@t54g2000hsg.googlegroups.com> On Jul 11, 3:46?am, "Gabriel Genellina" wrote: > As Guy Davidson has already pointed out, this is a problem in the meter ? > TCP implementation, and you should ask the vendor to fix it. That would have been me, not Guy. From omer at no-log.org Wed Jul 2 06:35:04 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Wed, 2 Jul 2008 12:35:04 +0200 Subject: Attribute reference design In-Reply-To: <486ABB01.1040904@islandtraining.com> References: <486ABB01.1040904@islandtraining.com> Message-ID: <200807021235.04262.omer@no-log.org> Le Wednesday 02 July 2008 01:17:21 Gary Herron, vous avez ?crit?: > chamalulu wrote: > > On Jul 1, 11:24 pm, "Diez B. Roggisch" wrote: > >> chamalulu schrieb: > >>> Hello. > >>> I think I'm aware of how attribute access is resolved in python. When > >>> referencing a class instance attribute which is not defined in the > >>> scope of the instance, Python looks for a class attribute with the > >>> same name. (For assignment or deletion this is not the case, > >>> thankfully.) > >>> I've been trying to understand why? What is the reason behind, or > >>> practical purpose of, this design decision? Anyone, please enlighten > >>> me. > >> > >> How else would you resolve methods which are of course defined on the > >> class but invoked through the instance? > > > > Yes, of course... You're right. > > Didn't think of that. > > Thank you. I'll go stand in the corner. :) > > No need. Also, you can define a class attribute (C++ might call it a > static attribute) and access it transparently through an instance. > > class C: > aClassAttribute = 123 > def __init__(self, ...): > ... > > c = C() > ... do something with c.aClassAttribute ... > Be very careful with that, as it looks like C++ or similar other OO languages, but python handles it in a strange way if you assign a value to such an attribute. It took me a long time to understand what happens here: class Foo (object) : bar = 0 foo = Foo() print '(1) Foo.bar: %d' % Foo.bar print '(1) foo.bar: %d' % foo.bar Foo.bar += 1 print '(2) Foo.bar: %d' % Foo.bar print '(2) foo.bar: %d' % foo.bar foo.bar += 1 print '(3) Foo.bar: %d' % Foo.bar print '(3) foo.bar: %d' % foo.bar here's the output: (1) Foo.bar: 0 (1) foo.bar: 0 (2) Foo.bar: 1 (2) foo.bar: 1 (3) Foo.bar: 1 # hey dude, where is my bar ? (3) foo.bar: 2 In the third case, you might expect foo.bar += 1 to just increment Foo.bar, but actually it doesn't. I first thought it was a bug, but it's not. When you write foo.bar += 1 (equivalent to foo.bar = foo.bar + 1), python first looks for a bar attribute, finds it in the class members, and then creates an instance member with the result. Things would be different with a mutable type implementing the += operator. I discovered this in a middle of a project and it was hard to track all these assignments in my code to correct them, so I'd suggest to always access class members through the class instead of the instance, unless you have no choice or know exactly what you are doing. -- C?dric Lucantis From steve at REMOVE-THIS-cybersource.com.au Mon Jul 28 20:15:08 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 00:15:08 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> Message-ID: <009e5c8d$0$20313$c3e8da3@news.astraweb.com> On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: > On Jul 28, 10:00 am, Steven D'Aprano cybersource.com.au> wrote: >> Cutting to the crux of the discussion... >> >> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: >> > I want something where "if x" will do but a simple explicit test >> > won't. >> >> Explicit tests aren't simple unless you know what type x is. If x could >> be of any type, you can't write a simple test. Does x have a length? Is >> it a number? Maybe it's a fixed-length circular length, and the length >> is non-zero even when it's empty? Who knows? How many cases do you need >> to consider? > > Use case, please. I'm asking for code, not arguments. Please give me a > piece of code where you can write "if x" that works but a simple > explicit test won't. I gave you a piece of code, actual code from one of my own projects. If you wouldn't accept that evidence then, why would you accept it now? It isn't that explicit tests will fail, it is that explicit tests are more work for no benefit. You keep talking about "simple explicit tests", but it seems to me that you're missing something absolutely fundamental: "if x" is simpler than "if x!=0" and significantly simpler than "if len (x)!=0". Even if you discount the evidence of the character lengths (4 versus 7 versus 12) just use the dis module to see what those expressions are compiled into. Or use timeit to see the execution speed. So I'm not really sure what your point is. Yes, for vast amounts of code, there's no *need* to write "if x". If x is always a number, you can replace it with "if x != 0" and it will still work. Big deal. I never said differently. But if I don't care what type x is, why should I write code that cares what type x is? All you're doing is writing an expression that does more work than it needs to. Although the amount of work is trivial for built-ins, it's still more than necessary. But provided x is always the right sort of duck, your code will work. It will be longer, more verbose, slower, fail in unexpected ways if x is an unexpected type, and it goes against the spirit of duck-typing, but it will work. -- Steven From castironpi at gmail.com Mon Jul 28 23:57:02 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 28 Jul 2008 20:57:02 -0700 (PDT) Subject: derivative in numpy References: Message-ID: <45321c72-795e-47d8-86be-d64c2864d60c@l64g2000hse.googlegroups.com> On Jul 28, 5:34?pm, knielse... at gmail.com wrote: > Hi, > > I am looking to do a simple derivative. I would expect such a function > to be available in numpy, but can't find it. I have written my own, > but just curious if anybody knows of such function in numpy. > > Cheers, > ?Kim I presume you are taking the numerical derivative, not the symbolic one. From casey.mcginty at gmail.com Sun Jul 20 23:39:20 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Sun, 20 Jul 2008 17:39:20 -1000 Subject: Python Written in C? In-Reply-To: References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> Message-ID: On Sun, Jul 20, 2008 at 5:06 PM, Grant Edwards wrote: > On 2008-07-21, Dan Upton wrote: > > Using punch-cards and paper-tape. Real programmers can edit > their programs with a pointy stick and some home-made > sticky-tape. > > Doesn't everyone know that REAL programmers use butterflies. http://xkcd.com/378/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From LEnglish5 at cox.net Tue Jul 15 09:29:18 2008 From: LEnglish5 at cox.net (Lawson English) Date: Tue, 15 Jul 2008 06:29:18 -0700 Subject: [ANN} Daily pyogp coders meeting (PYthon Open Grid Protocols for virtual worlds) Message-ID: pyogp is a Python-based virtual worlds test harness and client library being developed by Linden Lab, makers of Second Life, and members of the SL Architecture Working Group, in order to test the Open Grid Protocols that were used in the recent "proof of concept" demo by IBM and Linden Lab, that allowed avatars to teleport from one virtual world (Second Life) to another (Open Simulator) using standardized interoperability protocols. http://www.informationweek.com/news/personal_tech/virtualworlds/showArticle.jhtml?articleID=208803274 A daily meeting within Second Life has been setup for pyogp coders and designers to meet, as described in the announcement below. This is the transcript of the first meeting: http://wiki.secondlife.com/wiki/Pyogp/Chat_Logs/Daily_Meeting/14_jul_2008 The pyogp meetings are open to any "resident" of Second Life, and any Python person (or design expert) with a desire to contribute to the process is certainly welcome. In World Meetings We're going to start having daily meetings at "infinity is full of stars" in the Levenhall simulator in Second Life at 9:30AM SLT (Pacific Coast Time) each day. These meetings are for the PyOGP coders to meet and discuss design, process and status. In the near term, these are likely to be "somewhat beefy" meetings where design issues are discussed and differences hammered out. In the longer term, these will hopefully be more "Agile Stand-Up" style meetings where we discuss: a. what we've done in the last 24 hours, b. what we're going to do in the next 24 and c. what we're blocked on. what PyOGP Coders Meeting who PyOGP l33t C0d3rZ where "infinity is full of stars" @ http://slurl.com/secondlife/Levenhall/91/208/22 when 9:30AM SLT / 12:30PM Eastern Time / 5:30PM GMT / 6:30PM Central European Time why for PyOGP contributors to hash out architecture, design, test and deploy issues IRC: irc://irc.freenode.com/#pyogp Mailing list: https://lists.secondlife.com/cgi-bin/mailman/listinfo/pyogp wiki: http://wiki.secondlife.com/wiki/Pyogp From jiri.zahradil at gmail.com Tue Jul 29 10:26:38 2008 From: jiri.zahradil at gmail.com (jiri.zahradil at gmail.com) Date: Tue, 29 Jul 2008 07:26:38 -0700 (PDT) Subject: block/lambda References: <0406eb4f-8dec-4ce2-b506-8e597de2958d@56g2000hsm.googlegroups.com> Message-ID: <0b6a5dff-dae5-4cd8-9dfd-18737c4a8746@f36g2000hsa.googlegroups.com> > 2. Will it be possible in Python 3.0 to do the following: > > >>> def dotimes(n, callable): > > ? ? ? ? for i in range(n): callable() > > >>> def block(): > > ? ? ? ? nonlocal i > ? ? ? ? for j in range(i): > ? ? ? ? ? ? ? ? print j, > ? ? ? ? print dotimes seems ok and what is wrong with that function "block"? You do not need to specify that i is "nonlocal", global i will be used. >>> i=10 >>> def block(): for j in range(i): print j, print >>> block() 0 1 2 3 4 5 6 7 8 9 Jiri From alexnbryan at gmail.com Wed Jul 16 16:22:49 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 13:22:49 -0700 (PDT) Subject: py2exe issues with pictures and icons In-Reply-To: <18495626.post@talk.nabble.com> References: <18493908.post@talk.nabble.com> <18495626.post@talk.nabble.com> Message-ID: <18495836.post@talk.nabble.com> Alexnb wrote: > > > > Mike Driscoll wrote: >> >> On Jul 16, 1:37?pm, Alexnb wrote: >>> Hello >>> >>> I am sure most of you are familiar with py2exe. I am having a bit of a >>> problem. See the program has a few pictures involved and the .ico it >>> uses >>> for the windows. However, the pictures are stored in the same directory >>> as >>> the source, something like: C:\Docs and settings\me\My >>> docs\python\program. >>> When I run the program for the interpreter, just as a .py, everything >>> works >>> just as it should. However, when I compile the main source as an .exe, >>> and >>> say let a friend try the program. It fails because it is missing the >>> .ico. >>> The catch, is I don't want to have it have to installed, at least at >>> this >>> point, I want it to be able to just run. So how can I make it just run >>> from >>> any computer with the files not being in the immediate directory. If >>> that is >>> not possible, how can I put them in the immediate directory and still >>> make >>> it work. Because that directory may change a lot so the path will >>> change. >>> >>> Just a few questions. I hope someone out there can help me out! >>> -- >>> View this message in >>> context:http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp1849390... >>> Sent from the Python - python-list mailing list archive at Nabble.com. >> >> >> Put the part of the code that needs the ico file(s) into a try/except >> block. You could also try reading the py2exe wiki and tutorials. This >> one looks like it has relevant data: >> >> http://www.py2exe.org/index.cgi/CustomIcons >> >> Mike >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > Well, that may solve the icon problem. But what about getting pictures in > there? > > Okay, the icon fix didn't really fix it, what it did was make the .exe have the icon as the little picture for the shortcut, but it isn't really a shortcut. Whatever. But, I went and ran it on another computer and this was the error log it created right off the bat. Traceback (most recent call last): File "The GUI.py", line 696, in File "Tkinter.pyc", line 1515, in wm_iconbitmap _tkinter.TclError: bitmap "C:\Documents and Settings\Alex\My Documents\PYTHON\DictionaryApp\Windows.ico" not defined -- View this message in context: http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp18493908p18495836.html Sent from the Python - python-list mailing list archive at Nabble.com. From nagle at animats.com Sat Jul 5 00:23:19 2008 From: nagle at animats.com (John Nagle) Date: Fri, 04 Jul 2008 21:23:19 -0700 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: <486ef34e$0$17156$742ec2ed@news.sonic.net> Henning_Thornblad wrote: > What can be the cause of the large difference between re.search and > grep? > > This script takes about 5 min to run on my computer: > #!/usr/bin/env python > import re > > row="" > for a in range(156000): > row+="a" > print re.search('[^ "=]*/',row) > > > While doing a simple grep: > grep '[^ "=]*/' input (input contains 156.000 a in > one row) > doesn't even take a second. > > Is this a bug in python? > > Thanks... > Henning Thornblad You're recompiling the regular expression on each use. Use "re.compile" before the loop to do it once. John Nagle From cwitts at gmail.com Wed Jul 9 09:29:09 2008 From: cwitts at gmail.com (Chris) Date: Wed, 9 Jul 2008 06:29:09 -0700 (PDT) Subject: Returning the positions of a list that are non-zero References: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> Message-ID: <51b454d7-2300-4f56-b596-d899551f810d@i76g2000hsf.googlegroups.com> On Jul 9, 7:48?am, "Rajanikanth Jammalamadaka" wrote: > Try this: > > >>> li=[0,0,1,2,1,0,0] > >>> li > > [0, 0, 1, 2, 1, 0, 0]>>> [i for i in range(len(li)) if li[i] != 0] > > [2, 3, 4] > > Cheers, > > Raj > > > > On Tue, Jul 8, 2008 at 10:26 PM, Benjamin Goudey wrote: > > I have a very large list of integers representing data needed for a > > histogram that I'm going to plot using pylab. However, most of these > > values (85%-95%) are zero and I would like to remove them to reduce > > the amount of memory I'm using and save time when it comes to plotting > > the data. To do this, I'm trying to find the best way to remove all of > > the zero values and produce a list of indices of where the non-zero > > values used to be. > > > For example, if my original list is [0,0,1,2,1,0,0] I would like to > > produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices > > of where the non-zero values used to be). Removing non-zero values is > > very easy but determining the indicies is where I'm having difficulty. > > > Thanks in advance for any help > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > "For him who has conquered the mind, the mind is the best of friends; > but for one who has failed to do so, his very mind will be the > greatest enemy." > > Rajanikanth That's a waste >>> li=[0,0,1,2,1,0,0] >>> [i for i in li if i] That's all you need. :) From anthony.hw.kong at gmail.com Mon Jul 14 22:48:20 2008 From: anthony.hw.kong at gmail.com (AK@SYD) Date: Mon, 14 Jul 2008 19:48:20 -0700 (PDT) Subject: How to write a custom tracer/profiler? Message-ID: <28ee2efb-6c8a-4884-8d25-4b91fb73ebb2@f63g2000hsf.googlegroups.com> Hi, all, Just wanna look for some suggestions on how to appoarch this problem... I have some code ("main logic") which has a dependency on a library. Let's call it DS. ("data source"). The main logic will issue a number of calls to the DS in order to get the data it needs and then carry out some calculations. I want to have a non-intrusive way to find out all the DS data requested by the main logic. One thing to note, the DS is a big, messy bit of code. So putting logger everywhere within DS and main logic is not a reliably, satisfactory solution. I have thought about using somehting like aspect. But seems to me there is no mature, widely-used aspect lib out there. Another idea is: let's roll a custom tracer/profiler. Whenever any method/attributes in the DS package are called, the return values will be logged. I have taken a quick look at profile.py in python 2.4, It seems sys module will pass a frames to the profile class. Can I access the return value of a function via these frame objects? Cheers, Anthony From fredrik at pythonware.com Mon Jul 21 10:07:59 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 16:07:59 +0200 Subject: error In-Reply-To: <0b48f3b2-0927-4745-97ce-6ee2bc8bcbe0@m73g2000hsh.googlegroups.com> References: <5f4395d7-9f5c-45c3-b137-655e5c618b8c@8g2000hse.googlegroups.com> <0b48f3b2-0927-4745-97ce-6ee2bc8bcbe0@m73g2000hsh.googlegroups.com> Message-ID: Anish Chapagain wrote: > hi thank's i probably missed the b.pack() but it's till the window is > not closed and error message of Windows Appear what does that error message say? From cyril.bazin at info.unicaen.fr Tue Jul 15 17:42:21 2008 From: cyril.bazin at info.unicaen.fr (Cyril Bazin) Date: Tue, 15 Jul 2008 23:42:21 +0200 Subject: Problem with MySQLdb and mod_python Message-ID: Hi, I installed an apache server with mod_python. I have got a problem with the mysql connection of my python script. In fact I tried this file : --------------------------------- import os os.environ["PYTHON_EGG_CACHE"] = "/tmp" import MySQLdb from mod_python import apache def test(req): db=MySQLdb.connect(user="xxx",passwd="xxx",host="xxx.xxx",db="xxx") c = db.cursor() requete = "SELECT * FROM document" nbRows = c.execute(requete) req.write("Result : %s"%repr(nbRows)) return apache.OK --------------------------------- But it seems, after many tests, that the script stops at the instruction : "c.execute(requete)" The script works if I am logged on the server as "root" or "www". I use : --------------------------------- Python 2.4.4 (#1, Oct 23 2006, 13:58:00) [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb >>> MySQLdb.__version__ '1.2.2' >>> import mod_python >>> mod_python.version '3.3.1' --------------------------------- If someone has any information that can help me... Thanks in advance, Cyril BAZIN From mercado949 at gmail.com Fri Jul 18 20:50:22 2008 From: mercado949 at gmail.com (mercado mercado) Date: Fri, 18 Jul 2008 20:50:22 -0400 Subject: Importing different versions of a module In-Reply-To: <48811064.5010603@hughes.net> References: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> <48811064.5010603@hughes.net> Message-ID: <8b51e78c0807181750x66fd0372y82367245630e921f@mail.gmail.com> Thanks norseman for the reply. You're right that I didn't like it though. :-) Also note that my original question has to do with importing modules from different locations. If all I had to do was use different paths within the script (e.g. for sending to os.path.join or whatever), then I could just put those in a config file. That's not a problem... -------------- next part -------------- An HTML attachment was scrubbed... URL: From mdboldin at gmail.com Wed Jul 30 10:51:43 2008 From: mdboldin at gmail.com (mmm) Date: Wed, 30 Jul 2008 07:51:43 -0700 (PDT) Subject: undo a dictionary Message-ID: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> I found code to undo a dictionary association. def undict(dd, name_space=globals()): for key, value in dd.items(): exec "%s = %s" % (key, repr(value)) in name_space So if i run >>> dx= { 'a':1, 'b': 'B'} >>> undict(dx) I get >>> print A, B 1 B Here, a=1 and b='B' This works well enough for simple tasks and I understand the role of globals() as the default names space, but creating local variables is a problem. Also having no output arguemtns to undict() seems counterintuitive. Also, the function fails if the key has spaces or operand characters (-,$,/,%). Finally I know I will have cases where not clearing (del(a,b)) each key-value pair might create problems in a loop. So I wonder if anyone has more elegant code to do the task that is basically the opposite of creating a dictionary from a set of globally assigned variables. And for that matter a way to create a dictionary from a set of variables (local or global). Note I am not simply doing and undoing dict(zip(keys,values)) From tjreedy at udel.edu Sun Jul 6 15:58:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 06 Jul 2008 15:58:43 -0400 Subject: re.search much slower then grep on some regular expressions In-Reply-To: References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Sebastian "lunar" Wiesner wrote: > I completely agree. I'd just believe, that the combination of some finite > state machine for "classic" expressions with some backtracking code is > terribly hard to implement. But I'm not an expert in this, probably some > libraries out there already do this. In this case, it'd be time to give > pythons re engine a more sophisticated implementation ;) One thing to remember in making comparisons is that Python moved to its own implementation to support unicode as well as extended ascii (bytes in 3.0). Does grep do that? Has pcre, which Python once used, been upgraded to do that? From mrkafk at gmail.com Wed Jul 2 12:01:33 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Wed, 02 Jul 2008 18:01:33 +0200 Subject: Importing modules in embedded Python In-Reply-To: References: Message-ID: OK I found the answer in yet another Google search, right after I gave up and posted here - turns out in order to import dynamically linked modules, one has to pass -E argument to the linker. > Exception exceptions.ImportError: > '/usr/lib/python2.4/lib-dynload/timemodule.so: undefined symbol: > PyModule_AddObject' in 'garbage collection' ignored > Fatal Python error: unexpected exception during garbage collection > Aborted From rw at smsnet.pl Sun Jul 20 07:30:09 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Sun, 20 Jul 2008 13:30:09 +0200 Subject: Help Tracing urllib2 Error, Please? References: <263aa5e2-f620-4d17-b95d-bd0b81f934a6@8g2000hse.googlegroups.com> Message-ID: <877ibgkd32.fsf@merkury.smsnet.pl> Larry Hale writes: > Since it seems I have a "unique" problem, I wonder if anyone could > point me in the general/right direction for tracking down the issue > and resolving it myself. > > See my prior post @ http://groups.google.com/group/comp.lang.python/browse_thread/thread/44775994a6b55161?hl=en# > for more info. (Python 2.5.2 on Win XP 64 ==>> Squid Proxy requiring > Authentication ==>> Internet not working.) > > I've looked the urllib2 source over, but am having trouble following > it. As previously mentioned, urllib2 initiates the request, Squid > replies "407 error" that auth's required, and then urllib2 just stops, > throwing error 407. > > Any though(s) on what to check out? > > It's frustrating (to say the least) that it seems so many are > successfully accomplishing this task, and all's working perfectly for > them, but I'm failing miserably. > > Would any quotes viewed in the HTTP traffic help? (Wireshark shows > all! :) I don't even know what other info could help. > > Any info to get about Squid's configuration that might make it "non > standard" in a way that could cause my problem? Any question(s) I > should ask my Net Admin to relay info to you all? Maybe Squid is configured to not allow sending authentication directly in URI. Or maybe there is only digest scheme allowed. Try this: def getopener(proxy=None, digest=False): opener = urllib2.build_opener(urllib2.HTTPHandler) if proxy: passwd_mgr = urllib2.HTTPPasswordMgr() passwd_mgr.add_password(None, 'http://localhost:3128', 'user', 'password') if digest: proxy_support = urllib2.ProxyDigestAuthHandler(passwd_mgr) else: proxy_support = urllib2.ProxyBasicAuthHandler(passwd_mgr) opener.add_handler(proxy_support) return opener def fetchurl(url, opener): f = opener.open(url) data = f.read() f.close() return data print fetchurl('http://www.python.org', getopener('127.0.0.1:3128')) print fetchurl('http://www.python.org', getopener('127.0.0.1:3128', digest=True)) HTH, Rob From bruno.desthuilliers at gmail.com Wed Jul 2 13:35:26 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 2 Jul 2008 10:35:26 -0700 (PDT) Subject: Trouble using pinckle References: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> <1ijgp2r.1j1k5xwwbtiwcN%pdorange@pas-de-pub-merci.mac.com> <486ba8a4$0$11957$426a74cc@news.free.fr> Message-ID: <386f827f-1cc0-4d87-842e-29d9d04cf4f3@z72g2000hsb.googlegroups.com> On 2 juil, 18:40, C?dric Lucantis wrote: > > > I'll also try the dictionnary method. > > > My final idea was that a dictionnary would be perhaps simple in the > > > future to save/load as XML and a parser. > > XML ? What a strange idea ? > > Why is it so strange ? It was kind of joke. But only kind of... > Many softs have their config in xml, and the xml.* > modules are not that hard to use. It makes sense if you have a lot of config > entries with nested sections. Lightweight solutions like json or yaml comes to mind here... From vshankar0 at gmail.com Sat Jul 19 15:10:31 2008 From: vshankar0 at gmail.com (Venky K Shankar) Date: Sun, 20 Jul 2008 00:40:31 +0530 Subject: How do you check if a program/process is running using python? In-Reply-To: References: Message-ID: <200807200040.32190.vshankar0@gmail.com> On Sunday 20 July 2008 12:08:49 am Lamonte Harris wrote: > How do you check if a program or process is running when using python? > What I want to do is have an infinite loop to check if a program is running > or not and send data to my web server to check yes or no. Is this > possible? If so how? you can execute OS system call. here i execute ps -ef and grep the required process name (or you can grep by pid on that particular column using awk) import os os.system("ps -ef | grep -v grep | grep ") in my system it gives result 0 if the process is running >>> a = os.system("ps -ef | grep -v grep | grep python") root 8749 5331 0 Jul19 pts/1 00:00:00 python >>> a 0 else gives non 0 : >>> a = os.system("ps -ef | grep -v grep | grep python123") >>> a 256 you can check this inside while True: I am sure there should be a far better solution that this in python. -Venky From vlastimil.brom at gmail.com Tue Jul 1 07:11:12 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 1 Jul 2008 13:11:12 +0200 Subject: How make regex that means "contains regex#1 but NOT regex#2" ?? In-Reply-To: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> References: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> Message-ID: <9fdb569a0807010411u2da4ea5xbec69b5b695605d9@mail.gmail.com> 2008/7/1, seberino at spawar.navy.mil : > > I'm looking over the docs for the re module and can't find how to > "NOT" an entire regex. > > For example..... > > How make regex that means "contains regex#1 but NOT regex#2" ? > > Chris > > -- > http://mail.python.org/mailman/listinfo/python-list > Maybe I'm missing something, but the negative lookahead seems to do roughly that (at least for simpler cases); the usual form is the check the text after the match, but it can also be used at the beginning of the pattern. ie. (?!regex#2)regex#1 e.g. the following should search for "words" discarding some very frequent ones; the important part seems to be keeping the excluding regexp2 compatible with the matching regex#1. (?!\b(?:an?|the|is|are|of|in|to|and)\b)\b\w+\b (without the checks for word boundaries \b, this pattern would also exclude "words" only partly containing the stopwords) regards vbr -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick at craig-wood.com Mon Jul 28 06:35:27 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 28 Jul 2008 05:35:27 -0500 Subject: ctypes - unloading implicitly loaded dlls References: Message-ID: pigmartian wrote: > I'm writing a program that uses functionality from two different sets of > cdlls which reside in two different directories, call them 'libA.dll' > and 'libB.dll'. Although I don't directly use it, both directories > contain a dll with the same name, although they aren't in fact > identical. Call them, "libC.dll". However, the c-functions I call from > the clls I do use seem to implicitly use "libC.dll". The problem that > occurs after I load one dll and call functions in it, when I try to load > the second dll I get windows errors because the second dll tries to call > a function in its version of libC.dll, but it finds the version meant > for libB.dll, which doesn't contain that function. > > Oy, I hope some sample code makes it clearer: > > def demo(): > > A = ctypes.cdll.LoadLibrary('/path1/libA.dll') > A.foo() # implicitly uses '/path1/libC.dll' > > _ctypes.FreeLibrary(A._handle) > > # CRASH! > B = ctypes.cdll.LoadLibrary('/path2/libB.dll') > # "The procedure entry point some_func could not be located > # in the dynamic link library libC.dll.": > > # libB.dll wants to use code from '/path2/libC.dll', but > # instead it finds '/path1/libC.dll' already loaded > # in memory, which doesn't > # contain the function call it wants. > > > Assuming my understanding of things is correct, then I believe what I > need to do is to remove /path1/libC.dll from memory before I try loading > libB.dll, but I haven't found any way of doing that. Can anyone offer > my some suggestions? Or, am I S.O.L.? You could try loading C explicitly with ctypes.LoadLibrary() before loading A, then you'll have a handle to unload it before you load B. I think I'd probably split the code into two or three processes though. Perhaps use http://pypi.python.org/pypi/processing to communicate between them. That should get you out of DLL Hell! (Don't load any of the DLLs before you start the worker processes off.) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From snowballz.game at gmail.com Fri Jul 18 19:05:44 2008 From: snowballz.game at gmail.com (Michael Lubker) Date: Fri, 18 Jul 2008 18:05:44 -0500 Subject: Any Game Developers here? In-Reply-To: <4A235BC6-5E46-4402-AF2D-BA3DBC175517@gmail.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> <4A235BC6-5E46-4402-AF2D-BA3DBC175517@gmail.com> Message-ID: <76b841590807181605r106995d2k98486993a4eaccc4@mail.gmail.com> I'm interested in general... I know about PyGame and Pyglet, and have used both. We're currently using Python-Ogre. In the end, I am looking to find people interested in my project ( see http://youtube.com/watch?v=E0QQ9JuclxE ), but I also want to find people experienced with Python in general, not just one library. (though of course I know that's not too likely) Aren't you one of the Escort Wing developers? :) Thanks Michael On Fri, Jul 18, 2008 at 5:13 PM, Stephen Johnson wrote: > I use the Pyglet library to make games. You want to look at the pyglet and > pygame mailing lists, not this one. Use Google. > In my opinion, PyGame is clunky and Pyglet is elegant, simple, and > comprehensive. PyGame has more examples available, but Pyglet has great > documentation and enough examples to answer any questions you might have. > Both have active communities. > > -Steve Johnson > On Jul 18, 2008, at 5:38 PM, Michael Lubker wrote: > > Any people that use Python as the predominant language for their game > development here? > > ~Michael > -- > http://mail.python.org/mailman/listinfo/python-list > > -- ~ "The world hates change, yet it is the only thing that has brought progress." ~ Charles Kettering http://snowballz.joey101.net From timothywayne.cook at gmail.com Sun Jul 6 08:52:11 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Sun, 06 Jul 2008 09:52:11 -0300 Subject: Hands-on HTML Table Parser/Matrix? In-Reply-To: References: Message-ID: <1215348731.2873.734.camel@localhost.localdomain> There are couple of HTML examples using Pyparsing here: http://pyparsing.wikispaces.com/Examples --Tim On Sun, 2008-07-06 at 14:40 +0200, robert wrote: > Often I want to extract some web table contents. Formats are > mostly static, simple text & numbers in it, other tags to be > stripped off. So a simple & fast approach would be ok. > > What of the different modules around is most easy to use, stable, > up-to-date, iterator access or best matrix-access (without need > for callback functions,classes.. for basic tasks)? > > > Robert > -- > http://mail.python.org/mailman/listinfo/python-list -- Timothy Cook, MSc Health Informatics Research & Development Services LinkedIn Profile:http://www.linkedin.com/in/timothywaynecook Skype ID == timothy.cook ************************************************************** *You may get my Public GPG key from popular keyservers or * *from this link http://timothywayne.cook.googlepages.com/home* ************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From fredrik at pythonware.com Wed Jul 23 16:43:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 22:43:31 +0200 Subject: Raw Strings (I Think) In-Reply-To: References: Message-ID: Lanny wrote: >> No, it doesn't. Instead of guessing what the cause might be, please show >> us your code and show us the error message you're getting, so that we can >> determine what the cause really is. > > Ok, sorry. Heres my code: > > import glob > import random > import os > > songs = glob.glob('C:\###\###\###\*.mp3') > pick = random.choice(songs) > os.system(pick) > > And yes, I know there are better ways of randomly selecting > a .mp3 file to play but I don't care. my guess is that the real problem is that you get back filenames with spaces in them, which gets treated as multiple arguments by os.system. using os.startfile will fix this: >>> import glob, os, random >>> file = random.choice(glob.glob("\\music\\*.mp3")) >>> file '\\music\\Madrugada - Grit - 05 - Seven Seconds.mp3' >>> print file \music\Madrugada - Grit - 05 - Seven Seconds.mp3 >>> os.system(file) '\music\Madrugada' is not recognized as an internal or external command, operable program or batch file. 1 >>> os.startfile(file) ... music starts playing ... From bj_666 at gmx.net Fri Jul 18 05:46:11 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Jul 2008 09:46:11 GMT Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> Message-ID: <6eb733F67cpfU2@mid.uni-berlin.de> On Fri, 18 Jul 2008 01:31:59 -0700, SUBHABRATA wrote: > def try2(n): > a1=raw_input("PRINT A STRING:") > a2=a1.split() > a3="God Godess Heaven Sky" > for x in a2: > a4=a3.find(x) > if a4>-1: > a5=a3[a4] > print a5 > elif a4<0: > a6=x > print "It is not found" > print a6 > else: > print "Error" > s=a5+" "+a6 > print s > > Here, if I put a string like: > Petrol Helium Heaven Sky > In s it is giving me S Helium > But I am looking for an output of a5 and a6 concatenating all its > values not the last ones. Can you suggest me any help? Am I missing > any minor point? Maybe you should describe what the input looks like and what output you want to have and how the input and output are connected. In words, not in not very clear code with "numbered names". That's a silly idea and makes understanding the code very hard. Please use meaningful names! Ciao, Marc 'BlackJack' Rintsch From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 08:51:20 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 14:51:20 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <40449826-c71d-4c6e-8b74-13069269e5da@z6g2000pre.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <40449826-c71d-4c6e-8b74-13069269e5da@z6g2000pre.googlegroups.com> Message-ID: <488896bf$0$3493$426a74cc@news.free.fr> Jordan a ?crit : > OK, it seems my original reply to Bruno got lost in the Aether > (apologies therefore if a paraphrased "quantum duplicate" of this > message is eventually forthcoming.) > > Torsten has adequately responded to his second point, Not MHO, by far. > so I need only > replicated what I said for the first. > >> Please get your facts, the behaviour *is* actually fully documented: > > I have the facts. I know full well the behaviour is documented Then why do you write, let me quote: """ (snip) coding __eq__ (snip) buys you nothing from the != operator. != isn't (by default) a synonym for the negation of == (unlike in, say, every other language ever); not only will Python let you make them mean different things, without documenting this fact - it actively encourages you to do so. """ >- it > was pointed out at the time of the original discussion. Documenting a > confusing, unintuitive design decision (whether its in a programming > language, an end user GUI app or anything in between) doesn't justify > it. I was not commenting on the actual design choice, just stating that it is actually documented. > To attack a strawman: "foolanguage uses the bar IO library; printing > to stdout takes about 10 mins on the average machine. But thats ok, > because look, its documented right here." And you're talking about strawman ??? Come on, you obviously can tell the difference between a one-line statement and your above strawman argument, don't you ? Please understand that I'm not arguing about this particular design choice (and FWIW, I'd mostly agree on the point that having a != b different from not (a == b) is actually a wart). I'm just correcting your statement about the behaviour of __eq__ / __ne__ not being documented, which is obviously false. (snip) From rajanikanth at gmail.com Wed Jul 9 01:48:26 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Tue, 8 Jul 2008 22:48:26 -0700 Subject: Returning the positions of a list that are non-zero In-Reply-To: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> References: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> Message-ID: <84bdef3c0807082248u4714fe35xcff80d4288185eff@mail.gmail.com> Try this: >>> li=[0,0,1,2,1,0,0] >>> li [0, 0, 1, 2, 1, 0, 0] >>> [i for i in range(len(li)) if li[i] != 0] [2, 3, 4] Cheers, Raj On Tue, Jul 8, 2008 at 10:26 PM, Benjamin Goudey wrote: > I have a very large list of integers representing data needed for a > histogram that I'm going to plot using pylab. However, most of these > values (85%-95%) are zero and I would like to remove them to reduce > the amount of memory I'm using and save time when it comes to plotting > the data. To do this, I'm trying to find the best way to remove all of > the zero values and produce a list of indices of where the non-zero > values used to be. > > For example, if my original list is [0,0,1,2,1,0,0] I would like to > produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices > of where the non-zero values used to be). Removing non-zero values is > very easy but determining the indicies is where I'm having difficulty. > > Thanks in advance for any help > -- > http://mail.python.org/mailman/listinfo/python-list > -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From jamitwidme at gmail.com Wed Jul 2 10:09:05 2008 From: jamitwidme at gmail.com (jamitwidme at gmail.com) Date: Wed, 2 Jul 2008 07:09:05 -0700 (PDT) Subject: Pyro: ProtocolError('connection failed') Message-ID: Hello everyone Can someone help me fix this problem? I am using an example from Pyro(Python Remote Object) website directly. It is the last example from http://pyro.sourceforge.net/manual/8-example.htm I have two computers to run Server and Client. ############################################ server.py import Pyro.naming import Pyro.core from Pyro.errors import PyroError,NamingError ###### testclass Pyro object class testclass(Pyro.core.ObjBase): def mul(s, arg1, arg2): return arg1*arg2 def add(s, arg1, arg2): return arg1+arg2 def sub(s, arg1, arg2): return arg1-arg2 def div(s, arg1, arg2): return arg1/arg2 ###### main server program def main(): Pyro.core.initServer() daemon = Pyro.core.Daemon() # locate the NS locator = Pyro.naming.NameServerLocator() print 'searching for Name Server...' ns = locator.getNS(host='drizzle.des.hep.uiuc.edu', port=9090) daemon.useNameServer(ns) # connect a new object implementation (first unregister previous one) try: # 'test' is the name by which our object will be known to the outside world ns.unregister('test') except NamingError: pass # connect new object implementation daemon.connect(testclass(),'test') # enter the server loop. print 'Server object "test" ready.' daemon.requestLoop() if __name__=="__main__": main() ################################### ################################### client.py import Pyro.naming, Pyro.core from Pyro.errors import NamingError # locate the NS locator = Pyro.naming.NameServerLocator() print 'Searching Name Server...', ns = locator.getNS(host='drizzle.des.hep.uiuc.edu',port=9090) # resolve the Pyro object print 'finding object' try: URI=ns.resolve('test') print 'URI:',URI except NamingError,x: print 'Couldn\'t find object, name server says:',x raise SystemExit # create a proxy for the Pyro object, and return that test = Pyro.core.getProxyForURI(URI) print test.mul(111,9) print test.add(100,222) print test.sub(222,100) print test.div(2.0,9.0) print test.mul('*',10) print test.add('String1','String2') ####################################### It does not matter which computer Pyro NameServer is located. When Server and Client are in a same computer, it works perfectly fine. But whenever Server and Client run in different computers, I get a following error message. ######################################## Pyro Client Initialized. Using Pyro V3.7 Searching Name Server... finding object URI: PYRO://127.0.0.1:7888/7f000001193649ab6a89d5592bc843bb Traceback (most recent call last): File "client.py", line 22, in print test.mul(111,9) File "/usr/local/lib/python2.5/site-packages/Pyro/core.py", line 390, in __call__ return self.__send(self.__name, args, kwargs) File "/usr/local/lib/python2.5/site-packages/Pyro/core.py", line 467, in _invokePYRO self.adapter.bindToURI(self.URI) File "/usr/local/lib/python2.5/site-packages/Pyro/protocol.py", line 255, in bindToURI raise ProtocolError('connection failed') Pyro.errors.ProtocolError: connection failed ######################################## Thanks a lot. From max at alcyone.com Tue Jul 29 16:11:57 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 13:11:57 -0700 Subject: iterating "by twos" In-Reply-To: <70a172ac-0491-4918-9c74-6a577f35068a@d45g2000hsc.googlegroups.com> References: <70a172ac-0491-4918-9c74-6a577f35068a@d45g2000hsc.googlegroups.com> Message-ID: giltay at gmail.com wrote: > On Jul 29, 1:36 pm, kj wrote: >> Is there a special pythonic idiom for iterating over a list (or >> tuple) two elements at a time? > > I use this one a lot: > > for x, y in zip(a, a[1:]): > frob(x, y) It doesn't work: >>> a = range(10) >>> [(x, y) for x, y in zip(a, a[1:])] [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)] What you meant was this: >>> [(x, y) for x, y in zip(a[::2], a[1::2])] [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] but this creates three sublists through slicing and zip. The use of islice and izip is better, particularly if the list that's being iterated over is large. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Tell me the truth / I'll take it like a man -- Chante Moore From duncan.booth at invalid.invalid Sat Jul 19 16:39:34 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Jul 2008 20:39:34 GMT Subject: create instance attributes for every method argument References: <4780837f-a5bc-4071-94d3-28e2f206163e@k30g2000hse.googlegroups.com> Message-ID: Berco Beute wrote: > I remember reading somewhere how to create an instance attribute for > every method argument, but although Google is my friend, I can't seem > to find it. This could likely be done way more elegant: > >========================= > class Test(object): > > def __init__(self, a, b, c, d, e, f): > self.a = a > self.b = b > self.c = c > self.d = d >========================= > > 2B You *could* do something like this: >>> class Test(object): def __init__(self, a, b, c, d, e, f): self.update(locals()) def update(self, adict): for k in adict: if k != 'self': setattr(self, k, adict[k]) >>> c = Test(1, 2, 3, 4, 5, 6) >>> c.__dict__ {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'f': 6} >>> but to be honest, your original is much clearer as it expresses the intention without any obfuscation and as soon as you want to do anything more than simply copying all arguments you'll want to do the assignments individually anyway. From __peter__ at web.de Mon Jul 7 09:31:31 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 07 Jul 2008 15:31:31 +0200 Subject: python mysteriously halts References: <13a33043-21d1-40c0-a938-6e905d958064@m3g2000hsc.googlegroups.com> Message-ID: Todd wrote: > I ran a python script last night which connects to a matlab automation > server via DCOM (using win32com). I expected to see the results when > I came in this morning. But apparently, not long after I left, python > stopped. I hit enter in the console, and it started again. I scoured > the handful of lines of code to see if there was any kind of input > statement put there by accident but couldn't find one. Furthermore, > I've run this code many times without it pausing. It's still possible > I've done something boneheaded, but I'm wondering if there is another > reason (e.g. a pause in the win32com module, some kind of timeout > feature if the system is idle, etc.). thank you You could start your debugging process by hitting Control-C instead of and study the traceback. Peter From lars at gustaebel.de Thu Jul 17 16:21:34 2008 From: lars at gustaebel.de (Lars =?iso-8859-1?Q?Gust=E4bel?=) Date: Thu, 17 Jul 2008 22:21:34 +0200 Subject: How to process a very large (4Gb) tarfile from python? In-Reply-To: References: <0e96241d-60a3-44fd-967a-394904ad5b34@e39g2000hsf.googlegroups.com> <4nqu74p3mmmdmf9pn7125voe6itko8d31k@4ax.com> Message-ID: <20080717202134.GA7617@axis.g33x.de> On Thu, Jul 17, 2008 at 10:39:23AM -0700, Uwe Schmitt wrote: > On 17 Jul., 17:55, Terry Carroll wrote: > > On Thu, 17 Jul 2008 06:14:45 -0700 (PDT), Uwe Schmitt > > > > wrote: > > >I had a look at tarfile.py in my current Python 2.5 installations > > >lib path. The iterator caches TarInfo objects in a list > > >tf.members . If you only want to iterate and you ?are not interested > > >in more functionallity, you could use "tf.members=[]" inside > > >your loop. This is a dirty hack ! > > > > Thanks, Uwe. ?That works fine for me. ?It now reads through all 2.5 > > million members, in about 30 minutes, never going above a 4M working > > set. > > Maybe we should post this issue to python-dev mailing list. > Parsing large tar-files is not uncommon. This issue is known and was fixed for Python 3.0, see http://bugs.python.org/issue2058. -- Lars Gust?bel lars at gustaebel.de Es gen?gt nicht nur, keine Gedanken zu haben, man mu? auch unf?hig sein, sie auszudr?cken. (anonym) From callen314 at gmail.com Wed Jul 16 18:20:04 2008 From: callen314 at gmail.com (Craig Allen) Date: Wed, 16 Jul 2008 15:20:04 -0700 (PDT) Subject: singletons Message-ID: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Hey, forgive me for just diving in, but I have a question I was thinking of asking on another list but it really is a general question so let me ask it here. It's about how to approach making singletons. Background: I've been programming in python seriously for about a year now, maybe a little longer depending how you count, and the system I am making is sophisticated enough that I've had to enter into a few idioms which were beyond my knowledge of python, and I had to do quick research and test my ideas with test code (which of course can miss subtle problems). Otoh, I have decades of programming experience now and wasn't totally without footing. I think I have a solution I like for creating something to act as a singleton but I'm curious what other's think. I have several classes in our system which need to act like singletons, they are libraries of data classifications, and other such libraries of configurations for the system which need to be global. The first thing I found searching for singleton, early in this project, trying to be a good citizen and find a decent idiom from the python community itself, knowing someone had mentioned "singleton" and "python" together at some point, was a recommendation to do this: (option 1) class TehLibrary(object): __single = None def __init__(self): if (TehLibrary.__single): raise AlreadyExistsException # or whatever This sucks because that means creation of the object has to be in a try block as a matter of course, something I promptly hid in a factory function, but still. But the way this worked made me realize that the Class itself is a full fledged object, quite instance-like from my C++ addled (I love you C++) perspective and it's single. If I can store that instance, I can make a class that shares member at the class level. The class doesn't even have to be a singleton exactly. (option 2) Therefore option two is a family of options where class level members can be used to share whatever needs to be shared, though strictly the class is not a singleton since multiple instances are created which merely share the data that should be single (say a big dictionary of configuration information the class manages). (option 3) I still wanted actual singletons and realized that since I had to create a factory function even in option 1, that I could use module level variables to control the behavior of those factories, which led me to realize I'm basically just using the module itself as a singleton. And this is sort of where I have arrived... when I import the modules it runs code to build up it's basic services, much like an object construction. It only runs once no matter how many times it's imported. When client code asks for the library that should be a singleton, it gets a singleton which has been stored in a module level variable. Anyone have any comments? Is there anything wrong, evil, or ugly about using a module this way, or am I correct to think that actually, this is a common approach in python. Is it pythonic? From nicolas.pourcelot at gmail.com Fri Jul 18 06:03:53 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Fri, 18 Jul 2008 03:03:53 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> Message-ID: <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> On 18 juil, 11:30, Peter Otten <__pete... at web.de> wrote: > nicolas.pource... at gmail.com wrote: > > Hi, > > > I want to test if an object IS in a list (identity and not equality > > test). > > I can if course write something like this : > > > test = False > > myobject = MyCustomClass(*args, **kw) > > for element in mylist: > > ? ? if element is myobject: > > ? ? ? ? test = True > > ? ? ? ? break > > > and I can even write a isinlist(elt, mylist) function. > > > But most of the time, when I need some basic feature in python, I > > discover later it is in fact already implemented. ;-) > > > So, is there already something like that in python ? > > I tried to write : > > 'element is in mylist' > > but this appeared to be incorrect syntax... > > There is no "is in" operator in Python, but you can write your test more > concisely as > > any(myobject is element for element in mylist) > > > Thanks a lot However, any() is only available if python version is >= 2.5, but I may define a any() function on initialisation, if python version < 2.5 I think something like >>> id(myobject) in (id(element) for element in mylist) would also work, also it's not so readable, and maybe not so fast (?)... An "is in" operator would be nice... > > PS: Btw, how is set element comparison implemented ? My first > > impression was that 'a' and 'b' members are considered equal if and > > only if hash(a) == hash(b), but I was obviously wrong : > >>>> class A(object): > > ... def __eq__(self,y): > > ... return False > > ... def __hash__(self): > > ... return 5 > > ... > >>>> a=A();b=A() > >>>> a==b > > False > >>>> hash(b)==hash(a) > > True > >>>> b in set([a]) > > False > >>>> S=set([a]) > >>>> S.difference([b]) > > set([<__main__.A object at 0xb7a91dac>]) > > > So there is some equality check also, maybe only if '__eq__' is > > implemented ? > > In general equality is determined by __eq__() or __cmp__(). By default > object equality checks for identity. > > Some containers (like the built-in set and dict) assume that a==b implies > hash(a) == hash(b). > > Peter So, precisely, you mean that if hash(a) != hash(b), a and b are considered distinct, and else [ie. if hash(a) == hash(b)], a and b are the same if and only if a == b ? From stodge at gmail.com Wed Jul 9 14:53:28 2008 From: stodge at gmail.com (Stodge) Date: Wed, 9 Jul 2008 11:53:28 -0700 (PDT) Subject: Boost Python - C++ class' private static data blown away before accessing in Python? References: <8b864486-9283-4991-a3cd-3c59c309959a@56g2000hsm.googlegroups.com> Message-ID: <69f5feb2-afbb-4353-b5ee-1bfbf4d8bf6e@z72g2000hsb.googlegroups.com> Oops - I didn't see my post so I thought something had gone wrong and reposted. Apologies for the multiple posts. On Jul 9, 11:57?am, Stodge wrote: > Could it be a boundary problem? The static data is initialised by the > application. The problem arises when the python module tries to access > it. > > On Jul 5, 11:14?pm, Giuseppe Ottaviano wrote: > > > > In Python, I retrive an Entity from the EntityList: > > > > elist = EntityList() > > > elist.append(Entity()) > > > elist.append(Entity()) > > > > entity = elist.get_at(0) > > > > entity.foo() > > > > But it crashes inside foo() as the private static data is empty; or > > > rather the string array is empty. I know before that point that the > > > private static data is valid when accessed earlier by the C++ code as > > > the program works fine. It just won't work from Python, so somehow the > > > private static data has been blown away but I can't work out where or > > > why. > > > Probably it is a problem of lifetime. What is the signature of append? ? > > Who deletes the appended Entity in C++ code? > > If append takes a raw pointer, Boost.Python copies the pointer but ? > > destroys the Entity object because it is a temporary and its reference ? > > count went to zero. So the pointer in the list is referring to a ? > > destroyed object, which results in undefined behaviour. > > > Did you have a look at the lifetime policies of Boost.Python? The ? > > simplest way to workaround the problem is using const reference ? > > arguments, and always use value semantics. If it can result in a ? > > performance penalty, another simple way is using shared_ptr's, which ? > > have their own reference count (different from the one in CPython ? > > lib), but Boost.Python does the magic to make them work together. > > > HTH, > > Giuseppe From bulg at ngs.ru Sun Jul 13 06:05:49 2008 From: bulg at ngs.ru (Yosifov Pavel) Date: Sun, 13 Jul 2008 03:05:49 -0700 (PDT) Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> Message-ID: <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> On 13 ???, 14:12, Peter Otten <__pete... at web.de> wrote: > Yosifov Pavel wrote: > > Whats is the way to clone "independent" iterator? I can't use tee(), > > because I don't know how many "independent" iterators I need. copy and > > deepcopy doesn't work... > > There is no general way. For "short" sequences you can store the items in a > list which is also the worst-case behaviour of tee(). > > What are you trying to do? > > Peter I try to generate iterators (iterator of iterators). Peter, you are right! Thank you. For example, it's possible to use something like this: def cloneiter( it ): """return (clonable,clone)""" return tee(it) and usage: clonable,seq1 = cloneiter(seq) ...iter over seq1... then clone again: clonable,seq2 = cloneiter(clonable) ...iter over seq2... Or in class: class ReIter: def __init__( self, it ): self._it = it def __iter__( self ): self._it,ret = tee(self._it) return ret and usage: ri = ReIter(seq) ...iter over ri... ...again iter over ri... ...and again... But I think (I'm sure!) it's deficiency of Python iterators! They are not very good... --Pavel From walter at livinglogic.de Thu Jul 3 07:37:23 2008 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Thu, 03 Jul 2008 13:37:23 +0200 Subject: ANN: XML builder for Python In-Reply-To: <486C5D63.5030407@behnel.de> References: <486C5CA1.3080105@behnel.de> <486C5D63.5030407@behnel.de> Message-ID: <486CB9F3.3020902@livinglogic.de> Stefan Behnel wrote: > Stefan Behnel wrote: >> Jonas Galvez wrote: >>> Not sure if it's been done before, but still... >> Obviously ;) >> >> http://codespeak.net/lxml/tutorial.html#the-e-factory >> >> ... and tons of other tools that generate XML, check PyPI. > > Although it might be the first time I see the with statement "misused" for > this. :) XIST has been using with blocks since version 3.0. Take a look at: http://www.livinglogic.de/Python/xist/Examples.html from __future__ import with_statement from ll.xist import xsc from ll.xist.ns import html, xml, meta with xsc.Frag() as node: +xml.XML() +html.DocTypeXHTML10transitional() with html.html(): with html.head(): +meta.contenttype() +html.title("Example page") with html.body(): +html.h1("Welcome to the example page") with html.p(): +xsc.Text("This example page has a link to the ") +html.a("Python home page", href="http://www.python.org/") +xsc.Text(".") print node.conv().bytes(encoding="us-ascii") Servus, Walter From mensanator at aol.com Wed Jul 2 18:05:19 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 2 Jul 2008 15:05:19 -0700 (PDT) Subject: internet porn References: <620da533-6fe0-4dd0-bda1-c40e322a8fda@a1g2000hsb.googlegroups.com> Message-ID: <3a3fb630-b7a6-403a-a414-b6ed0d7988d7@59g2000hsb.googlegroups.com> On Jul 2, 4:42?pm, NewsChann... at gmail.com wrote: > Hello, WNBC is looking to interview someone who is addicted to > internet porn for our 11pm newscast, if you are interested or > availbale we can also disguse your identity. > Call 212-664-2731 And don't be put off by the heavy breathing. > or email wnbc.newsd... at nbcuni.com > Thanks From fredrik at pythonware.com Thu Jul 24 16:16:18 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 22:16:18 +0200 Subject: need help with introducing more traffic In-Reply-To: References: <632875.28836.qm@web51808.mail.re2.yahoo.com> <6es0m9F8mehmU1@mid.uni-berlin.de> Message-ID: Fredrik Lundh wrote: > "load testing" other people's sites are known as something else, of course. message.replace(" are ", " is ") # do'h! (when do we get the ability to edit our c.l.python messages for, say, 30 minutes after they're posted? ;-) From robert.rawlins at thinkbluemedia.co.uk Thu Jul 24 12:30:02 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 24 Jul 2008 17:30:02 +0100 Subject: Gracefull application exit. In-Reply-To: <4888AB7C.5040003@timgolden.me.uk> References: <00ba01c8eda7$2e61ecb0$8b25c610$@rawlins@thinkbluemedia.co.uk> <4888AB7C.5040003@timgolden.me.uk> Message-ID: <00d701c8edaa$860ea8b0$922bfa10$@rawlins@thinkbluemedia.co.uk> > but mind the caveats: Thanks Tim, the main caveat which worries me is the fact that it doesn't get called when being killed by SIGTERM. When I look at implementing the application as Daemon will cause complications. The implementation looks nice and is certainly the way I would like to go, but unless it'll work when killed by sigterm it likely won't be for me. Thanks Tim, if you're aware of any other methods then give me a shout. Rob From cmbrannon at cox.net Wed Jul 23 02:55:15 2008 From: cmbrannon at cox.net (Chris Brannon) Date: Wed, 23 Jul 2008 01:55:15 -0500 Subject: Proper way to query user and group database on a Unix host? References: Message-ID: <87d4l5ozsc.fsf@cox.net> Mike MacCana writes: > Hi folks, > > What's the proper way to query the passwd and group database on a Unix > host? Use the pwd and grp modules, respectively. > ## Get the full group database entry, leave just the user list, > ## and split the list on comma > groupname=users > groupsusers = commands.getoutput('getent group '+groupname).split(':',-1)[3].split(',') Instead, do this: import grp groupname = 'users' groupusers = grp.getgrnam(groupname)[3] print 'The group named "users" contains:' for username in groupusers: print username The functions from the grp and pwd modules return tuples. The docs describe their formats. Hope this helps, -- Chris From circularfunc at gmail.com Thu Jul 10 16:46:44 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 10 Jul 2008 13:46:44 -0700 (PDT) Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: >>> def mod(x,y): return x.append(y) >>> mod([1,2],3) >>> k=[1,2,3] >>> k [1, 2, 3] >>> l = mod(k,4) >>> l >>> k [1, 2, 3, 4] >>> l >>> k==l False >>> mod(k,5) >>> k [1, 2, 3, 4, 5] >>> mod(l,4) Traceback (most recent call last): File "", line 1, in mod(l,4) File "", line 2, in mod return x.append(y) AttributeError: 'NoneType' object has no attribute 'append' >>> l >>> l=k >>> l [1, 2, 3, 4, 5] >>> i=mod(k,1) >>> i >>> same stuff but i dont find this intuitive. From python at rgbaz.eu Sat Jul 12 18:58:59 2008 From: python at rgbaz.eu (Python.Arno) Date: Sun, 13 Jul 2008 00:58:59 +0200 Subject: like py2exe, but on a mac In-Reply-To: <18424336.post@talk.nabble.com> References: <18424336.post@talk.nabble.com> Message-ID: On 13 jul 2008, at 00:39, Alexnb wrote: > > Hi All > > I am wondering what I can do to turn a python app (.py) into a mac OSX > applicaiton (.app). Just like py2exe does. i use these: http://undefined.org/python/py2app.html http://effbot.org/pyfaq/how-do-i-create-a-pyc-file.htm > But I am also wondering since in > your applications folder on macs it usually doesn't have an actual > folder > for each app. Rather an icon. so for firefox, you just see the icon. > Unlike > windows where you have a folder with everything, and the actual > program is > in it. where is all the application info stored? just in the .app? apps on OSX are also folder, yet with the reserved .app extension the OS then presents this as an app (right click on an app and choose 'Show package content') py2app creates all that for you > Finally > whether or not there is an app like py2exe for mac, is there a way > to skip > the middle man and turn it straight into a .dmg with the app inside? > -- a dmg is a disk image, similar to iso on windows you can create an empty one with Disk Utility then drop everything in it's NOT an installer > cheers Arno From gordon at panix.com Wed Jul 23 14:55:34 2008 From: gordon at panix.com (John Gordon) Date: Wed, 23 Jul 2008 18:55:34 +0000 (UTC) Subject: Inserting cookies into a web session Message-ID: I'm developing a web application that needs a semi-persistent way to store information. I've looked at some options such as writing entries to a database table or creating small textfiles, but I'm not thrilled with anything I've come up with so far. Then a coworker suggested that I could just insert a cookie into the current session, which would store whatever information I wanted. This seems like a really good solution. That's what cookies are *for*, right? But I've never worked with cookies before. Is there a Python package for handling cookies? And are there any back-end requirements? I assume you would have to be running a webserver that supports sessions. Do you also have to be running some sort of web container or servlet engine? Thanks for any suggestions. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From tjreedy at udel.edu Thu Jul 24 21:01:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jul 2008 21:01:58 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87zlo747gv.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> Message-ID: Torsten Bronger wrote: > Hall?chen! > And why does this make the implicit insertion of "self" difficult? > I could easily write a preprocessor which does it after all. class C(): def f(): a = 3 Inserting self into the arg list is trivial. Mindlessly deciding correctly whether or not to insert 'self.' before 'a' is impossible when 'a' could ambiguously be either an attribute of self or a local variable of f. Or do you and/or Jordan plan to abolish local variables for methods? tjr From jeremy at 54oaks.com Thu Jul 3 11:52:12 2008 From: jeremy at 54oaks.com (Jeremy Link) Date: Thu, 3 Jul 2008 08:52:12 -0700 Subject: better way to search the Python archive Message-ID: <00e901c8dd24$c3301ad0$8101a8c0@bocaron> Just an FYI out to folks that want a better way to search the Python archive. I've been using MarkMail (www.markmail.org ) to search the archives and it works MUCH better than the Google archive. It is a free hosting of all sorts of GNU/open source mailing lists (registration NOT required or even available). -------------- next part -------------- An HTML attachment was scrubbed... URL: From maric at aristote.info Wed Jul 30 10:50:00 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 30 Jul 2008 16:50:00 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <25f024b4-1b0c-4265-bc30-24431ebbe079@z72g2000hsb.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <25f024b4-1b0c-4265-bc30-24431ebbe079@z72g2000hsb.googlegroups.com> Message-ID: <200807301650.01377.maric@aristote.info> Le Wednesday 30 July 2008 15:31:28 giltay at gmail.com, vous avez ?crit?: > > > class Signal: > > > ? ? [...] > > > ? ? def dc_offset(self, amount): > > > ? ? ? ? if amount == 0: > > > ? ? ? ? ? ? return > > > ? ? ? ? self.samples = [sample + amount for sample in self.samples] > > > > This function is also wrong assuming that because amount compare to zero, > > it can be added to sample. > > Not quite. ?I'm assuming that if amount equals 0, then amount is some > scalar. ?In fact, only if that comparison fails will I get my > exception: since [] != 0, it will then try to add sample + [], which > will raise TypeError. > > > If you want to make type checking just check the type or convert your > > parameter to an int, but the test "== 0" is of no help here. > > I'm not going for type checking here because I want Signal to support > int and float samples (and numpy.int16, &c.). Ok, but the fact that amount == 0 passes, doesn't ensure you didn't a programming error, this add just some relative robustness (protect you from passing an empty list). And a reader would probably not see your intention here (he already expect a scalar due to the name of the variable). This is exactly the problem ABC is intended to solve. Without ABC, to explicitly ensure amount is a scalar, just doing a int(amount) or int(abs(amount)) if you want to deal with complex numbers too, at the begining of the function is a common idiom. -- _____________ Maric Michaud From martin at v.loewis.de Fri Jul 11 03:04:35 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 11 Jul 2008 09:04:35 +0200 Subject: error with configure (svn 64857) In-Reply-To: References: <487681e9$0$9745$9b622d9e@news.freenet.de> Message-ID: <48770603$0$9695$9b622d9e@news.freenet.de> > Thank you Martin. How can I remove -lgcc_s and use the Intel equivalent ? I'm not so sure that there is anything wrong in configure. configure doesn't pass -lgcc_s to icc; instead, icc is making this up on its own. So I would guess you need to get libgcc_s onto you system in a way that the linker finds it. Else you need to read the icc documentation (but I'm fairly sure that icc is *required* to link with libgcc_s, for interoperability with gcc-compiled binaries). I'm somewhat puzzled that the wchar_t test is the one where it crashes; this test comes fairly late, and configure has run multiple compiler invocations before that. Can you build any binaries at all with your icc installation? Regards, Martin From disappearedng at gmail.com Sat Jul 5 04:31:33 2008 From: disappearedng at gmail.com (disappearedng at gmail.com) Date: Sat, 5 Jul 2008 01:31:33 -0700 (PDT) Subject: Not necessarily related to python Web Crawlers Message-ID: Hi Does anyone here have a good recommendation for an open source crawler that I could get my hands on? It doesn't have to be python based. I am interested in learning how crawling works. I think python based crawlers will ensure a high degree of flexibility but at the same time I am also torn between looking for open source crawlers in python vs C ++ because the latter is much more efficient(or so I heard. I will be crawling on very cheap hardware.) I am definitely open to suggestions. Thx From lanclos at ucolick.org Wed Jul 16 19:09:11 2008 From: lanclos at ucolick.org (Kyle Lanclos) Date: Wed, 16 Jul 2008 16:09:11 -0700 Subject: Manually prompting garbage collection Message-ID: <20080716230911.GD22400@monkey.ucolick.org> I've done a lot of web searching, a fair bit of C-source reading, and quite a lot of miscellaneous head scratching, and I find that I am not necessarily closer to an ideal solution. I have a Python/C interface layer that essentially does the following: Py_XDECREF (some_callback); closeService (some_service); return; The problem, of course, is that way back in my Python layer, I have Objects that are poised to be de-allocated due to the Py_XDECREF call above; those Objects have __del__ () methods that invoke calls to the service that is about to be closed in the second line above. I want to modify the above sequence to manually prompt Python's garbage collection routine(s) to take over (performance is not an issue here), similar to the following: Py_XDECREF (some_callback); PyCollect_Garbage (); closeService (some_service); return; Is that possible? I can work around this with additional convoluted tracking of the services in the C layer, but the problem would disappear entirely if the garbage collection could be explicitly invoked. I suspect the likely workaround would involve returning from the above C function, letting Whatever happen a few times, and only invoking the real closeServce () after I've returned to the C layer. To wit: Py_XDECREF (some_callback); markForClosure (some_service); return; (( ...time passes in Python-space, and a C function is invoked... )) if ( servicesNeedClosing ()) { closeServices (); } return; I would prefer, however, an explicit solution, as the above workaround continues to rely on the assumption that garbage collection occurs magically at some point when I'm not paying attention. Solutions I've read about, and/or attempted, and am not wholly interested in hearing more about: 1. Don't use __del__ methods. I'm using __del__ methods, which are otherwise doing the right thing in non-sequence-sensitive situations, so this option is off the table. 2. Don't assume that __del__ methods will be invoked in a timely fashion. I'm not making this assumption, but rather, I would like to *explicitly* assert that garbage collection has occurred. 3. Use the gc module (or PyGC_Collect). These appear to only address situations with circular references, which are not my problem-- the Py_XDECREF call makes the right thing happen, it's just that the garbage collection happens *after* the service has been properly closed. I've tried inserting calls to PyGC_Collect (including an invocation of "while (PyGC_Collect() > 0)") with no change in behavior. Suggestions are welcome. Cheers, --Kyle From jyoung79 at kc.rr.com Wed Jul 30 09:10:44 2008 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Wed, 30 Jul 2008 8:10:44 -0500 Subject: elementtree and rounding questions Message-ID: <27976748.917531217423445156.JavaMail.root@hrndva-web18-z02> Thank you very much Gabriel and Stefan for your help! I really appreciate the excellent examples you've shared which is helping me understand how all this works. Again, thank you for taking the time to help me with this. Jay From bj_666 at gmx.net Fri Jul 18 11:41:43 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Jul 2008 15:41:43 GMT Subject: Regular expression help References: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> Message-ID: <6ebrtnF67cpfU3@mid.uni-berlin.de> On Fri, 18 Jul 2008 10:04:29 -0400, Russell Blau wrote: > values = {} > for expression in line.split(" "): > if "=" in expression: > name, val = expression.split("=") > values[name] = val > [?] > > And when you get to be a really hard-core Pythonista, you could write > the whole routine above in one line, but this seems clearer. ;-) I know it's a matter of taste but I think the one liner is still clear (enough):: values = dict(s.split('=') for s in line.split() if '=' in s) Ciao, Marc 'BlackJack' Rintsch From upton at virginia.edu Mon Jul 21 14:28:05 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 21 Jul 2008 14:28:05 -0400 Subject: automating python programs In-Reply-To: References: Message-ID: <5504f9ac0807211128p3b94b4c2tb8f454ef54f50a27@mail.gmail.com> On Mon, Jul 21, 2008 at 2:12 PM, Zach Hobesh wrote: > Hi, > > I'm trying to figure out how to run a python program on a schedule, maybe > every half an hour... Is this possible? > > Thanks! > > -Zach > > -- > http://mail.python.org/mailman/listinfo/python-list > On Linux, man cron. From keshet1 at umbc.edu Tue Jul 8 20:08:29 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Tue, 08 Jul 2008 20:08:29 -0400 Subject: a simple 'for' question Message-ID: <4874017D.2000401@umbc.edu> Hi fans, I want to use a 'for' iteration to manipulate files in a set of folders, something like: folders= ['1A28','1A6W','56Y7'] for x in folders: print x # print the current folder f = open('my/path/way/x/my_file.txt', 'r') ... where 'x' in the pathway should iterate over '1A28','1A6W','56Y7'. How should I identify 'x' in the pathway line as the same x that is iterating over 'folders'? I am getting the following error: Traceback (most recent call last): File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Linux\Dock_method_validation\myscripts\test_for.py", line 5, in f = open('c:/Linux/Dock_method_validation/x/receptor.mol2', 'r') IOError: [Errno 2] No such file or directory: 'c:/Linux/Dock_method_validation/x/receptor.mol2' I tired several variations: %x, 'x', "x", etc. all gave me similar errors. Thanks for your help, BK From sjmachin at lexicon.net Sat Jul 19 16:12:14 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 19 Jul 2008 13:12:14 -0700 (PDT) Subject: regex doubts References: <532965.570.qm@web54502.mail.re2.yahoo.com> Message-ID: <504d473e-375a-4111-ae2e-c06aaa37b096@p25g2000pri.googlegroups.com> On Jul 20, 5:04 am, Fredrik Lundh wrote: > Mr SZ wrote: > > I am taking a string as an input from the user and it should only > > contain the chars:L , M or R > > > I tried the folllowing in kodos but they are still not perfect: > > > [^A-K,^N-Q,^S-Z,^0-9] > > [L][M][R] > > [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > > > For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. > > try "[LRM]+$" (an L or an R or an M, one or more times, all the way to > the end of the string). Ummm ... with the default flag settings, shouldn't that be \Z instead of $ ? From frank at chagford.com Tue Jul 22 11:12:06 2008 From: frank at chagford.com (Frank Millman) Date: Tue, 22 Jul 2008 08:12:06 -0700 (PDT) Subject: Is this a valid use of 'import'? Message-ID: Hi all I am familiar enough with the normal use of 'import'. However, I have found a use for it which seems effective, but I have not seen it used like this before, so I am not sure if there are any downsides. I know that when a module is imported the first time, it is 'executed'. This normally entails setting up constants, classes, functions, etc, that you want to make available to the importer. In this particular case, when it is executed, it does a whole lot more. It reads in some parameters, establishes a socket connection, starts a thread, and starts monitoring the socket using select.select. It also exposes some functions that disguise the complexity of reading from and writing to the socket. This enables me to write a 'client' program that look like this - --------------------------- from Utils.client import * connect(userid='frank',pwd='') cust = getRecord( company='chagford',table='ArCustomers', column='CustNo',value='A001') print cust close() --------------------------- As you can see, it makes writing a client program very easy. Are there any problems with this approach? Frank Millman From binjured at gmail.com Tue Jul 1 09:44:53 2008 From: binjured at gmail.com (Tom Davis) Date: Tue, 1 Jul 2008 06:44:53 -0700 (PDT) Subject: Looping-related Memory Leak References: <94312edc-babb-4c1b-8db1-233404aa4a02@i76g2000hsf.googlegroups.com> <0abf2145-231c-4189-a8ca-b1f327a735dd@a1g2000hsb.googlegroups.com> <1e36866c-4a94-40b6-9780-81e104286862@d1g2000hsg.googlegroups.com> Message-ID: <5fcaf13f-5fc1-44bc-befe-e8763e3fef60@d1g2000hsg.googlegroups.com> On Jun 30, 3:12 pm, Marc 'BlackJack' Rintsch wrote: > On Mon, 30 Jun 2008 10:55:00 -0700, Tom Davis wrote: > > To me, this seems illogical. I can understand that the GC is > > reluctant to reclaim objects that have many connections to other > > objects and so forth, but once those objects' scopes are gone, why > > doesn't it force a reclaim? For instance, I can use timeit to create > > an object instance, run a method of it, then `del` the variable used > > to store the instance, but each loop thereafter continues to require > > more memory and take more time. 1000 runs may take .27 usec/pass > > whereas 100000 takes 2 usec/pass (Average). > > `del` just removes the name and one reference to that object. Objects are > only deleted when there's no reference to them anymore. Your example > sounds like you keep references to objects somehow that are accumulating. > Maybe by accident. Any class level bound mutables or mutable default > values in functions in that source code? Would be my first guess. > > Ciao, > Marc 'BlackJack' Rintsch Marc, Thanks for the tips. A quick confirmation: I took "class level bound mutables" to mean something like: Class A(object): SOME_MUTABLE = [1,2] ... And "mutable default values" to mean: ... def a(self, arg=[1,2]): ... If this is correct, I have none of these. I understand your point about the references, but in my `timeit` example the statement is as simple as this: import MyClass a = MyClass() del a So, yes, it would seem that object references are piling up and not being removed. This is entirely by accident. Is there some kind of list somewhere that says "If your class has any of these attributes (mutable defaults, class-level mutables, etc.) it may not be properly dereferenced:"? My obvious hack around this is to only do X loops at a time and make a cron to run the script over and over until all the files have been processed, but I'd much prefer to make the code run as intended. I ran a test overnight last night and found that at first a few documents were handled per second, but when I woke up it had slowed down so much that it took over an hour to process a single document! The RAM usage went from 20mb at the start to over 300mb when it should actually never use more than about 20mb because everything is handled with local variables and new objects are instantiated for each document. This is a serious problem. Thanks, Tom From wuwei23 at gmail.com Thu Jul 17 07:30:07 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 17 Jul 2008 04:30:07 -0700 (PDT) Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> <0T56p3tmInifNv8%stesch@parsec.no-spoon.de> Message-ID: <33bbf8d8-f5b9-430b-9c47-06a6fa4477ee@w7g2000hsa.googlegroups.com> On Jul 17, 6:04 pm, Fredrik Lundh wrote: > Django's 0.91 release in early 1996 While I totally agree with position, I'm pretty sure you mean 2006 here :) From motoom at xs4all.nl Sat Jul 19 20:41:24 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Sun, 20 Jul 2008 02:41:24 +0200 Subject: Change PC to Win or Windows In-Reply-To: <6tednSAkCcl50x_VnZ2dnUVZ_oPinZ2d@earthlink.com> References: <6eeir8F6itbqU1@mid.individual.net> <6tednSAkCcl50x_VnZ2dnUVZ_oPinZ2d@earthlink.com> Message-ID: <200807200241.24695.motoom@xs4all.nl> On Saturday 19 July 2008 22:30:29 Dennis Lee Bieber wrote: > I still wonder who came up with the Commodore PET -- Personal > Electronic Transactor... yeesh... But the "Personal" was already in play > way back then. Probably Chuck Peddle, Jack Tramiel or Leonard Tramiel. For your amusement: http://en.wikipedia.org/wiki/PET_2001 Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From musiccomposition at gmail.com Mon Jul 21 22:43:13 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 21 Jul 2008 19:43:13 -0700 (PDT) Subject: Python Embedding Thread References: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> Message-ID: <87bf413d-eb98-47c0-8466-237c45fd1a0e@e53g2000hsa.googlegroups.com> On Jul 21, 6:56?am, o... at tuningchannel.de wrote: > Hi :) > > I want to run Python in my app. That works still fine. But my app > supports now Threads and I would like to know what to do, that it runs > without problems. > > PyGILState_Release and PyGILState_Ensure should solve the problem > right? Where do I have to put this two commands around? between each > Command that increase, decrease a reference? Two threads should not be running through the Python VM concurrently in the same process. The GIL has to be held *any* time you use the Python API. When you want to release the GIL (to process something in C), use PY_BEGIN_ALLOW_THREADS and PY_END_ALLOW_THREADS around the places where threads can run. > > Currently, this is a small code-snippet that represents the part of > the code-execution: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? PyObject *f_globals=NULL, *f_locals=NULL, *mod=NULL, *rv=NULL; > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? mod = PyImport_ImportModule("__main__"); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (!mod) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? return; > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? f_globals = PyModule_GetDict(mod); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? f_locals = PyDict_New(); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? PyDict_Update(f_locals, f_globals); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (!f_locals) { > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Py_DECREF(mod); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? PyErr_Print(); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? return; > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? } > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? rv = PyRun_String( ? ? ?, Py_file_input, f_locals, > f_locals); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (!rv) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? PyErr_Print(); > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Py_XDECREF(rv); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Py_DECREF(mod); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Py_DECREF(f_locals); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Py_DECREF(f_locals); > > Thanks a lot for your help :) From ethan at stoneleaf.us Wed Jul 9 19:54:05 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 09 Jul 2008 15:54:05 -0800 Subject: Determining when a file has finished copying In-Reply-To: References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> Message-ID: <48754F9D.1000306@stoneleaf.us> writeson wrote: > Guys, > > Thanks for your replies, they are helpful. I should have included in > my initial question that I don't have as much control over the program > that writes (pgm-W) as I'd like. Otherwise, the write to a different > filename and then rename solution would work great. There's no way to > tell from the os.stat() methods to tell when the file is finished > being copied? I ran some test programs, one of which continously > copies big files from one directory to another, and another that > continously does a glob.glob("*.pdf") on those files and looks at the > st_atime and st_mtime parts of the return value of os.stat(filename). >>From that experiment it looks like st_atime and st_mtime equal each > other until the file has finished being copied. Nothing in the > documentation about st_atime or st_mtime leads me to think this is > true, it's just my observations about the two test programs I've > described. > > Any thoughts? Thanks! > Doug The solution my team has used is to monitor the file size. If the file has stopped growing for x amount of time (we use 45 seconds) the file is done copying. Not elegant, but it works. -- Ethan From tjreedy at udel.edu Fri Jul 11 01:09:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 Jul 2008 01:09:34 -0400 Subject: Python 3.0 and removal of the 'string' module In-Reply-To: <87wsjtqiyo.fsf@benfinney.id.au> References: <87wsjtqiyo.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Howdy all, > > The Python wiki page states on its page for Python 3.0 > , in the section for > "Standard Library Changes" > , > that the 'string' module is to be removed. > > It references PEP 4 , > which has nothing to say about the status of the 'string' module. > > Further, the 'string' module has existing functionality (the Template > class, the character sets 'whitespace' etc.) that, to my knowledge, > has no replacement in Python 3.0. > > Can anyone see a reason to believe the above wiki page's statement > about the 'string' module being removed? More to the point, can anyone > see a reason why that statement should remain on that page? Removing string and moving the functionality elsewhere was considered, but... IDLE 3.0b1 >>> import string >>> dir(string) ['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'maketrans', 'octdigits', 'printable', 'punctuation', 'whitespace'] Feel free to edit the wiki. From elessar at nienna.org Thu Jul 3 15:02:08 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Thu, 03 Jul 2008 13:02:08 -0600 Subject: Write a file - beginner's question In-Reply-To: <8d278055-29be-46f1-8a6b-044838bd4b00@p25g2000pri.googlegroups.com> References: <486cefb7$0$6040$426a74cc@news.free.fr> <8d278055-29be-46f1-8a6b-044838bd4b00@p25g2000pri.googlegroups.com> Message-ID: <486D2230.2000600@nienna.org> Callie Bertsche wrote: > I have a closely related note. How do I write to a relative path with > python? Example, > source = open('/../../directory/subdirectory/file.extension') > > What am I missing? > -- > http://mail.python.org/mailman/listinfo/python-list > Leave off the beginning slash. -Matt From Phillip.Ross.Taylor at gmail.com Thu Jul 24 06:52:57 2008 From: Phillip.Ross.Taylor at gmail.com (Philluminati) Date: Thu, 24 Jul 2008 03:52:57 -0700 (PDT) Subject: Working with ctypes and char** data type Message-ID: <14b44a64-ec58-4ff2-abce-1cc44557e4e4@27g2000hsf.googlegroups.com> I'm a bit of a python newbie and I need to wrap a C library. I can initialise the library using CDLL('mcclient.so') and I can call functions correctly inside the library but I need to invoke one function which has this function definition: char ** CAPAPI McSearch(HMCLINK Handle, short nSearchType, short nNoSelect, char **pSelect, short nNoWhere, char **pWhere, char **pData, int iTimeout); For **pSelect I want to pass in an array of char points, which in C would be declared as char *pData[] = { "ADDR", "POSTCODE" }; Can someone tell me how use pointers + char pointers together in python with ctypes please? Thank you Phill From aaa at bbb.it Thu Jul 31 16:11:08 2008 From: aaa at bbb.it (Fred Mangusta) Date: Thu, 31 Jul 2008 21:11:08 +0100 Subject: Case tagging and python In-Reply-To: <1cdb154c-da87-47a8-9e6d-66597a107480@x35g2000hsb.googlegroups.com> References: <1cdb154c-da87-47a8-9e6d-66597a107480@x35g2000hsb.googlegroups.com> Message-ID: Hi, I came up with the following procedure ALLCAPS = "|ALLCAPS" NOCAPS = "|NOCAPS" MIDCAPS = "|MIDCAPS" CAPS = "|CAPS" DIGIT = "|DIGIT" def test_case(w): w_out = '' if w.isalpha(): #se la virgola non ci entra if w.isupper(): w_out = w.lower() + ALLCAPS return w_out elif w.islower(): w_out = w + NOCAPS return w_out else: m = re.match("^[A-Z]",w) if m: w_out = w.lower() + CAPS #notsure about this.. return w_out else: w_out = w.lower() + MIDCAPS return w_out elif w.isdigit(): w_out = w + DIGIT return w_out Called in here: #========================= lines = 0 for s in file: lines += 1 if lines % 1000 == 0: print '%d lines' % lines #sent = sent.replace(",","") sent = s.split() #split string by spaces for w in sent: wout= test_case(w) #========================== But I don't know if I'm doing something sensible? Moreover: - test_case has problems, cause whenever It finds some punctuation character attached to some word, doesn't tag it. I was thinking of cleaning the line of the punctuation before using split on it (see commented row) but I don't know if I have to call that replace() once for every punctuation char? -Is there a way to reprint the tagged text in a file including punctuation? -Is my test_case a good start? Would you use regular expressions? Thanks very much! F. From durumdara at gmail.com Mon Jul 28 04:27:43 2008 From: durumdara at gmail.com (durumdara at gmail.com) Date: Mon, 28 Jul 2008 10:27:43 +0200 Subject: Callback Python procedure from Delphi DLL Message-ID: Hi! I have a component, and a tool in Delphi. I wanna call it from Python. I can implement all things I need into a Delphi generated DLL. It is ok, I can use this DLL from Python, but the DLL procedure needs a callback procedure to return the partially output, and needs a python passed variable to check terminate/abort signal. For example: procedure ProcessFiles(InputFiles : string; CallBackProc: ????????????????????????); export; begin .... CallBackProc(ProcessedFiles, Percentage, NeedToAbort); if NeedToAbort then Exit; .... end; def CallBackProc(ProcessedFiles, Percentage, NeedToAbort): ... But I don't know, how to call back this procedure, and how to pass variables. The other way is a ActiveX. This time I don't load the DLL, I only construct the Delphi based Com Object, and I start the process. But in this way I also don't know how to implement the callback, because the main code uses callback events, and I need to use too... Thanks for every usable help! dd From Nikolaus at rath.org Mon Jul 28 06:13:18 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 28 Jul 2008 12:13:18 +0200 Subject: os.symlink() References: <6f5ik2F9t9b5U1@mid.uni-berlin.de> Message-ID: <87abg2s4e9.fsf@nokile.rath.org> "Diez B. Roggisch" writes: > Nikolaus Rath wrote: > >> Hello, >> >>>From `pydoc os`: >> >> symlink(...) >> symlink(src, dst) >> >> Create a symbolic link pointing to src named dst. >> >> >> Is there any reason why this is so deliberately confusing? Why is the >> target of the symlink, the think where it points *to*, called the >> `src`? It seems to me that the names of the parameters should be >> reversed. > > I used the command the other day, and didn't feel the slightest confusion. > > To me, the process of creating a symlink is like a "virtual copy". > Which the above parameter names reflect perfectly. Is this interpretation really widespread? I couldn't find any other sources using it. On the other hand: >From ln(2): ,---- | SYNOPSIS | ln [OPTION]... [-T] TARGET LINK_NAME (1st form) | | DESCRIPTION | In the 1st form, create a link to TARGET with the name LINK_NAME. `---- >From Wikipedia: ,---- | A symbolic link merely contains a text string that is interpreted and | followed by the operating system as a path to another file or | directory. It is a file on its own and can exist independently of its | target. If a symbolic link is deleted, its target remains unaffected. | If the target is moved, renamed or deleted, any symbolic link that | used to point to it continues to exist but now points to a | non-existing file. `---- Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From diordna at gmail.com Fri Jul 18 15:43:14 2008 From: diordna at gmail.com (Stephen Johnson) Date: Fri, 18 Jul 2008 15:43:14 -0400 Subject: Distributing Python App In-Reply-To: <072bf39b-d700-482e-ab59-36840e21e83e@a70g2000hsh.googlegroups.com> References: <072bf39b-d700-482e-ab59-36840e21e83e@a70g2000hsh.googlegroups.com> Message-ID: Look up py2app and py2exe, for OS X and Windows, respectively. They are extensively documented and easy to use. On Jul 18, 2008, at 3:35 PM, KDawg44 wrote: > Hi, > > I am very new to Python but find it very interesting (from what I know > of it) and am considering writing an application. However, I have a > question regarding distribution of the app once it is done. Is there > a way to package everything a user needs to run the app or will they > have to install Python their machine? This is probably an obvious > question but most development I do is for administrative tasks on > servers and such, not usually development of an app for someone else. > > Thanks for your help. > > Kevin > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Jul 9 06:09:01 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 09 Jul 2008 12:09:01 +0200 Subject: delete lines References: <35d53620-16c7-4c2c-b904-04dbab6bc91a@z66g2000hsc.googlegroups.com> Message-ID: antar2 wrote: > I am new in python and I have the following problem: > > Suppose I have a list with words of which I want to remove each time > the words in the lines below item1 and above item2: > f = re.compile("item\[1\]\:") > g = re.compile("item\[2\]\:") > for i, line in enumerate(list1): > ????????????????f_match = f.search(line) > ????????????????g_match = g.search(line) > ????????????????if f_match: > ????????????????????????if g_match: > ????????????????????????????????if list1[i] > f_match: > ????????????????????????????????????????if list1[i] < g_match: > ????????????????????????????????????????????????del list1[i] > > > But this does not work > > If someone can help me, thanks! I see two problems with your code: - You are altering the list while you iterate over it. Don't do that, it'll cause Python to skip items, and the result is usually a mess. Make a new list instead. - You don't keep track of whether you are between "item1" and "item2". A simple flag will help here. A working example: inlist = """item1 a b item2 c d item3 e f item4 g h item1 i j item2 k l item3 m n item4 o p """.splitlines() print inlist outlist = [] between = False for item in inlist: if between: if item == "item2": between = False outlist.append(item) else: outlist.append(item) if item == "item1": between = True print outlist Peter From deets at nospam.web.de Tue Jul 22 05:26:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 11:26:47 +0200 Subject: Hello,who can help me! References: <163330b8-8d0d-44c4-baf7-450bd42f8402@c65g2000hsa.googlegroups.com> Message-ID: <6elngkF7mgmfU1@mid.uni-berlin.de> birdprince at gmail.com wrote: > I have implemented a C++ COM,which contains two interface in one > coclass. > when i use this COM in python: > dll=win32com.client.Dispatch("XXXXX") > then i can only call default interface's method,but can't call non > default interface's method. > who can tell me how to call non default interface's method. > thank you very much! > you can send the answer to my mailbox:birdprince at hotmail.com AFAIK win32com only supports IDispatch-based interfaces, not custom interfaces. Diez From torriem at gmail.com Mon Jul 28 05:02:45 2008 From: torriem at gmail.com (Michael Torrie) Date: Mon, 28 Jul 2008 03:02:45 -0600 Subject: Attack a sacred Python Cow In-Reply-To: <87proysbpn.fsf@nokile.rath.org> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <488D5B2C.10808@gmail.com> <87proysbpn.fsf@nokile.rath.org> Message-ID: <488D8B35.7090203@gmail.com> Nikolaus Rath wrote: > Thats true. But out of curiosity: why is changing the interpreter such > a bad thing? (If we suppose for now that the change itself is a good > idea). Round and round and round we go. Because by doing as you suggest you'd be altering the internal consistency of how python deals with objects, particularly function objects. By keeping all functions as function objects, we're able to provide a consistent view of things both to the programmer and the interpreter. If we break this consistency then we're saying, well this is always a function, except in this case, and except in this case, when it's dealt with specially. This does not fit at all with python's established mantras. In python, "def" does only one thing: it creates a function object and binds it to a name. That's it! Making what def does context-sensitive seems pretty silly to me, and without any real benefit. As said before, adding attributes after the fact that are functions is a chore, because those functions can't be unit tested, and can't be clearly read and understood by other programmers. From wuwei23 at gmail.com Tue Jul 22 01:18:37 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 21 Jul 2008 22:18:37 -0700 (PDT) Subject: string[i:j:k] References: Message-ID: <4a9a4cf3-9ef4-4d9e-b714-bbf62b7c1917@v1g2000pra.googlegroups.com> On Jul 22, 3:10?pm, konstantin wrote: > some_string[i:j:k] > What does it mean? i = start position, j = end position, k = step size >>> s = "ABABABABABABAB" >>> s[0:6:2] 'AAA' >>> s = "ABCABCABCABCABC" >>> s[0:6:3] 'AA' Hope this helps. - alex23 From adityashukla1983 at gmail.com Thu Jul 24 16:06:08 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Thu, 24 Jul 2008 15:06:08 -0500 Subject: Reading a file Message-ID: <73045cca0807241306h370166ebwdd1b12227cef43c2@mail.gmail.com> I have a text file whose contents are like this:- jd|fj|dnv|jd|0.33|c:\\windows\\win32 shcbsbs|nscsjsj|0.93|hsbcjsnc I am trying to read the file like this:- >>> x = open("c:\\a.txt","r") >>> x.read() the result that i get is ike this:- 'jd|fj|dnv|jd|0.33|c:\\\\windows\\\\win32\nshcbsbs|nscsjsj|0.93|hsbcjsnc\n' My doubt is how can i read the file as it is? ie my output should be d|fj|dnv|jd|0.33|c:\\windows\\win32 shcbsbs|nscsjsj|0.93|hsbcjsnc Thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Fri Jul 25 00:38:45 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 25 Jul 2008 16:38:45 +1200 Subject: os.walk question References: Message-ID: In message , Fredrik Lundh wrote: > Lanny wrote: > >> How would one make a list of the files in the top directory >> using os.walk. >> >> I need to pick a random file from said list. > > if you want a list of files from a single directory, use listdir, not > walk: > > >>> import os, random > >>> random.choice(os.listdir("/")) > 'python25' Won't that return any subdirectories as well as files? From stefan_ml at behnel.de Fri Jul 18 02:58:57 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 18 Jul 2008 08:58:57 +0200 Subject: wholesale n i k e [...] In-Reply-To: References: Message-ID: <48803f31$0$6614$9b4e6d93@newsspool2.arcor-online.net> hyh_david at hotmail.com wrote: > [incomplete babbling removed] I guess this guy meant the "whole snake", but messed up his keyboard. Stefan From lew at lewscanon.com Sun Jul 13 00:05:51 2008 From: lew at lewscanon.com (Lew) Date: Sun, 13 Jul 2008 00:05:51 -0400 Subject: spam <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> In-Reply-To: <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> Message-ID: WDC wrote: > BTW I reported it, yo should too. To whom did you report it, so that we may also report it there? -- Lew From casey.mcginty at gmail.com Fri Jul 25 20:13:35 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Fri, 25 Jul 2008 14:13:35 -1000 Subject: DBUS/HAL Manager Interface Help Message-ID: Can someone explain to me why this sample code does not work? I am trying to test if a device exists. ---------------- dbus_test.py -------------------------- import dbus bus = dbus.SystemBus() proxy = bus.get_object( 'org.freedesktop.Hal', '/org/freedesktop/Hal/Manager' ) manager = dbus.Interface( proxy, 'org.freedesktop.Hal.Manager' ) some_dev = manager.GetAllDevices()[0] print "Calling DeviceExists on '%s'" % some_dev print manager.DeviceExists( some_dev ) ------------------- output ------------------------------ $ python dbus_test.py Calling DeviceExists on '/org/freedesktop/Hal/devices/platform_bluetooth' Traceback (most recent call last): File "dbus_test.py", line 9, in print manager.DeviceExists( some_dev ) File "/var/lib/python-support/python2.5/dbus/proxies.py", line 140, in __call__ **keywords) File "/var/lib/python-support/python2.5/dbus/connection.py", line 607, in call_blocking message, timeout) dbus.exceptions.DBusException: org.freedesktop.Hal.SyntaxError: There is a syntax error in the invocation of the method Manager.DeviceExists -------------- next part -------------- An HTML attachment was scrubbed... URL: From Nikolaus at rath.org Thu Jul 31 10:46:28 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Thu, 31 Jul 2008 16:46:28 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> Message-ID: <87tze6862j.fsf@nokile.rath.org> Maric Michaud writes: >> > Can someone explain to me the difference between a type and a class? >> >> If your confusion is of a more general nature I suggest reading the >> introduction of `Design Patterns' (ISBN-10: 0201633612), under >> `Specifying Object Interfaces'. >> >> In short: A type denotes a certain interface, i.e. a set of signatures, >> whereas a class tells us how an object is implemented (like a >> blueprint). A class can have many types if it implements all their >> interfaces, and different classes can have the same type if they share a >> common interface. The following example should clarify matters: >> > > Of course, this is what a type means in certain literature about OO > (java-ish), but this absolutely not what type means in Python. Types > are a family of object with a certain status, and they're type is > "type", conventionnaly named a metatype in standard OO. [...] Hmm. Now you have said a lot about Python objects and their type, but you still haven't said what a type actually is (in Python) and in what way it is different from a class. Or did I miss something? Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From dullrich at sprynet.com Mon Jul 28 11:58:22 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 28 Jul 2008 10:58:22 -0500 Subject: multiple inheritance and __getattr__ References: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> Message-ID: In article <488ddc51$0$41654$4fafbaef at reader4.news.tin.it>, "Enrico" <4564 at 755189.45> wrote: > Hi there, > I have the following situation (I tryed to minimize the code to concentrate > on the issue): > > >>> class A(object): > def __getattr__(self, name): > print 'A.__getattr__' > if name == 'a': return 1 > raise AttributeError('%s not found in A' % name) > > >>> class B(object): > def __getattr__(self, name): > print 'B.__getattr__' > if name == 'b': return 1 > raise AttributeError('%s not found in B' % name) > > Both classes have a __getattr__ method. > Now I want to have a class that inherits from both so I write: > > >>> class C(B,A): > pass > > The problem arise when I try something like this: > >>> c=C() > >>> c.a > A.__getattr__ > 1 > >>> c.b > A.__getattr__ > > Traceback (most recent call last): > File "", line 1, in > c.b > File "", line 5, in __getattr__ > raise AttributeError('%s not found in A' % name) > AttributeError: b not found in A > > I was expecting, after a fail in A.__getattr__, a call to the __getattr__ > method of B but it seems that after A.__getattr__ fails the exception stops > the flow. So, if I did understand well, B.__getattr__ will be never called > "automatically". I don't know if this has a reason, if it is a design choice > or what else, any explanation is welcome. Well, it's simply the way it works. When you say C(A, B) then A is searched first for a given attribute and if A has no such attribute then B is searched. If you really want to do something like this then yes, you have to do something as below. I suspect that the people who feel expert enough to talk about what you should and shouldn't want are going to say that you shouldn't want something like this - with things set up the way you have them you really can't tell what's going to happen with c.__getattr__ unless you look at all the code in all the subclasses. > Since A and B are not written by me I can only work on C. The solution that > comes to my mind is to define a __getattr__ also in C and write something > like: > > >>> class C(A,B): > def __getattr__(self, name): > try: > return A.__getattr__(self, name) > except AttributeError: > return B.__getattr__(self, name) > > >>> c=C() > >>> c.a > A.__getattr__ > 1 > >>> c.b > A.__getattr__ > B.__getattr__ > 1 > > A better solution is welcome. > Many thanks, Enrico -- David C. Ullrich From __peter__ at web.de Fri Jul 18 15:56:29 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 21:56:29 +0200 Subject: Trickiness with unittesting References: Message-ID: arockstar at gmail.com wrote: > Basically, I'm trying to implement a setUp() and TearDown() for a > python TestSuite (as opposed to an individual test within the suite). > > Sort of. > > I have a few different test suites (call them SuiteA, SuiteB,...). For > one of the test suites (SuiteA), I need to execute a bit of code (say > startFoo()) before the first test in SuiteA runs, and once when the > last test of SuiteA finishes (endFoo()). > > Making this even trickier is that the testing framework combines the > different suites (SuiteA, SuiteB) as well as individual tests into > master test suite which my testrunner then runs. > > Also complicating matters is the fact that the testing framework can > run an *individual* test from any TestSuite: in that case, if I'm > running SuiteA.test1, I'd want to call startFoo() and endFoo() as > well. > > I could use a global variable as a flag and see if it's been set > during the setUp() method of the test cases (which would allow me to > call startFoo() once when tests from SuiteA are run from the master > suite), but that doesn't help me with calling endFoo() when the tests > from SuiteA finish. Plus, it's not very elegant. > > So: > Given a master test suite comprised of a bunch of different tests from > different suites, I need to call startFoo() before tests from SuiteA > are run, and stopFoo() after all the tests from SuiteA have finished > running. Here's a glorified version of you global flag idea: class Nested(object): def __init__(self, start, end): self.level = 0 self._start = start self._end = end def start(self): if self.level == 0: self._start() self.level += 1 def end(self): assert self.level > 0 self.level -= 1 if self.level == 0: self._end() def start_foo(): print "start foo" def end_foo(): print "end foo" foo = Nested(start_foo, end_foo) print "--- 1 ---" foo.start() print "--- 2 ---" foo.start() print "--- 3 ---" foo.end() print "--- 4 ---" foo.end() print "--- 5 ---" Peter From shandy.b at gmail.com Wed Jul 2 01:43:18 2008 From: shandy.b at gmail.com (shandy.b at gmail.com) Date: Tue, 1 Jul 2008 22:43:18 -0700 (PDT) Subject: Python and timezones Message-ID: I'm trying to write some code to deal with world timezones, and I'm getting a strange result. America/Iqaluit should not be showing up in UTC+00:00, but it is. Can anyone see what's wrong with this code? import time from datetime import datetime import os import pytz def getZoneNamesOnThisComputer(): for i in pytz.all_timezones: if os.path.exists( os.path.join('/tmp/usr/share/zoneinfo/', i)): yield i def getZonesGroupedByOffset(): '''return a dict of all the zone names , grouped by their offset eg: {'-0400': ['America/Blanc-Sablon', 'Etc/GMT+4'], '+0000': ['America/Iqaluit', 'Etc/GMT', 'Europe/Belfast', 'GB', 'GMT'], ... } ''' Y,M,D,h,m,s = time.localtime()[:6] zonesGroupedByOffset = {} for name in getZoneNamesOnThisComputer(): tz = pytz.timezone(name) now = datetime(Y,M,D,h,m,s, tzinfo=tz) # strfime returns a string like "-0800" or "+0430" or "0000" offsetKey = now.strftime('%z') if not zonesGroupedByOffset.has_key(offsetKey): zonesGroupedByOffset[offsetKey] = [] zonesGroupedByOffset[offsetKey].append(name) return zonesGroupedByOffset z = getZonesGroupedByOffset() print z['+0000'] # Why is America/Iqaluit showing up here??? From larry.bates at websafe.com` Wed Jul 9 16:43:08 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 09 Jul 2008 15:43:08 -0500 Subject: User-defined exception: "global name 'TestRunError' is not defined" In-Reply-To: References: Message-ID: jmike at alum.mit.edu wrote: > I'm using some legacy code that has a user-defined exception in it. > > The top level program includes this line > > from TestRunError import * > > It also imports several other modules. These other modules do not > explicitly import TestRunError. TestRunError is raised in various > places throughout the modules. > > There are a few cases where something goes wrong with the program and > I get this error: > > FATAL ERROR: global name 'TestRunError' is not defined > > I realize this is kind of a silly question to ask in the general sense > without showing more of the code, but does anyone have any suggestions > as to the most likely causes of this error coming up? Could it be > something like an error happening where it is not explicitly in a try > block, or an error happening while I'm already in an except block, or > something like that? > > Thanks, > --JMike Please post the entire traceback and we might actually be able to help. The traceback will show a line number where it failed, you can look to see what is going on at the time. It is more likely a scoping issue where TestRunError isn't defined in the scope where the exception is being raised. -Larry From semanticist at gmail.com Wed Jul 30 22:47:04 2008 From: semanticist at gmail.com (Miles) Date: Wed, 30 Jul 2008 22:47:04 -0400 Subject: overriding file.readline: "an integer is required" In-Reply-To: References: Message-ID: On Wed, Jul 30, 2008 at 5:52 PM, kj wrote: > I know that I could rewrite the method like this: > > def readline(self, size=None): > if size == None: > line = self.file.readline() > else: > line = self.file.readline(size) > # etc., etc. > > ...but this seems to me exceptionally awkward. (Actually, it's worse > than awkward: it fails to complain when the overriding method is > called with the argument None. IMO, the method should have been possible to call with None in the first place (like str.split and list.sort), and it's not incorrect for your method to allow it. > It would be better to test for the > number of arguments passed to the function, but I can't figure out > how to do this either.) You could of course do: def readline(self, *args): line = self.file.readline(*args) # etc., etc. But this has its drawbacks. -Miles From ldo at geek-central.gen.new_zealand Sat Jul 26 19:47:30 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 27 Jul 2008 11:47:30 +1200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> Message-ID: In message <024ace13-f72f-4093-bcc9-f8a339c324e2 at v1g2000pra.googlegroups.com>, s0suk3 at gmail.com wrote: > On Jul 24, 5:01 am, Lawrence D'Oliveiro central.gen.new_zealand> wrote: > >> In message >> <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, >> Jordan wrote: >> >> > Except when it comes to Classes. I added some classes to code that had >> > previously just been functions, and you know what I did - or rather, >> > forgot to do? Put in the 'self'. In front of some of the variable >> > accesses, but more noticably, at the start of *every single method >> > argument list.* >> >> The reason is quite simple. Python is not truly an "object-oriented" >> language. It's sufficiently close to fool those accustomed to OO ways of >> doing things, but it doesn't force you to do things that way. You still >> have the choice. An implicit "self" would take away that choice. > > By that logic, C++ is not OO. Yes it is, because it has "this". From gerthwd at rose-hulman.edu Thu Jul 17 15:58:33 2008 From: gerthwd at rose-hulman.edu (Gerth, William D) Date: Thu, 17 Jul 2008 15:58:33 -0400 Subject: XML Parsing: Expat Error Message-ID: <0FF698F7C0354F42987734704458117F015DD7F0@EVS3.rose-hulman.edu> Hey all, I'm simply trying to get my feet wet with XML parsing, and I tried to just do something simple with ElementTree, just throw the XML tags from a file into a list. The code is as follows (and may be wrong): import glob import xml.etree.ElementTree as ET tree = ET.parse('nameofFilehere').getroot() list = [] for branch in tree: this = {} for child in branch.getchildren(): this[child.tag] = child.text list.append(this) Every time I run the program, I get this error: Traceback (most recent call last): File "nameofFilehere", line 4, in coords = ET.parse('nameofFilehere').getroot() File "C:\Program Files\Python25\Lib\xml\etree\ElementTree.py", line 862, in parse tree.parse(source, parser) File "C:\Program Files\Python25\Lib\xml\etree\ElementTree.py", line 587, in parse self._root = parser.close() File "C:\Program Files\Python25\Lib\xml\etree\ElementTree.py", line 1254, in close self._parser.Parse("", 1) # end of data xml.parsers.expat.ExpatError: no element found: line 3, column 0 What can I do to fix this, if anything? My overall goal has been to simply get the text of the XML document into a text file, but even that has failed (I get naught but gibberish), so any help would be appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mrkafk at gmail.com Sun Jul 20 08:42:09 2008 From: mrkafk at gmail.com (mk) Date: Sun, 20 Jul 2008 14:42:09 +0200 Subject: getting with statement to deal with various exceptions Message-ID: Hello, I'm trying to learn how with statement can be used to avoid writing: prepare() try: something_that_can_raise_SomeException() except SomeException, err: deal_with_SomeException finally: tear_it_down() Verbose, not very readable. OK, "with" to the rescue? Let's take a textbook example from PEP: with open('/etc/passwd', 'r') as f: BLOCK Well, great, it's neat that "with" closes the file after BLOCK has finished execution, but what if the file isn't there and attempt to open it raises IOException? I'd like to be able to catch it precisely to avoid writing verbose try: .. except: .. finally: .. blocks which as I understand has been much of the rationale behind creating "with" statement in the first place. "with" statement only allows easy dealing with prepare() and tear_it_down(). When I try to get it to deal with exceptions that might happen, it becomes more complicated: class FileContextManager: def __enter__(self, filename, mode): f = open(filename, mode) return f def __exit__(self, etype, evalue, etraceback): print "etype", etype, "evalue", evalue, "etraceback", etraceback >>> with FileContextManager("somefile", "r") as f: a = f.readlines() Traceback (most recent call last): File "", line 1, in with FileContextManager("somefile", "r") as f: TypeError: this constructor takes no arguments Bummer. Plus, no documentation I've read (on effbot, in PEP 343, etc) says how to deal with the exception happening in __enter__ method of context manager, which is precisely what I'd like to do. This is only natural, isn't it? When e.g. reading the file, preparation phase is typically checking if it can be opened in the first place. So it falls into __enter__ method of context manager. "with" limited only to successful execution of a_statement from "with a_statement" seems like limited benefit to me. I'd like to be able to write smth like class FileContextManager: def __enter__(self, filename, mode): f = open(filename, mode) return f def __except__(IOError, err): do_this print err def __except__(RuntimeError, err): do_that print "something bad happened", err def __exit__(self, etype, evalue, etraceback): print "etype", etype, "evalue", evalue, "etraceback", etraceback __exit__ deals with exceptions happening in the BLOCK below "with" statement, not with exceptions raised in "a_statement", when executing with a_statement as var: BLOCK In the above way "with" would give me the benefit of more terse, but still understandable and efficient code. Well, I can always do this: try: with open("somefile.txt") as txtfile: for line in txtfile: print line except IOError: print "No such file." No such file. But that's just ugly, nested too many times (flat is better than nested, right?) and not all that more readable. From mrkafk at gmail.com Wed Jul 2 12:46:23 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Wed, 02 Jul 2008 18:46:23 +0200 Subject: Bloody signal handling (in embedded Python code) In-Reply-To: References: Message-ID: Right, I didn't realize before that Python interpreter has its own signal handling routines. Now I am able to handle signals in Python code, but it still barfs on exit: import time import signal import sys def userBreak(sigNum, execFrame): print "Interrupted,,," sys.exit(sigNum) def terminateRun(sigNum, execFrame): print "SIGTERM received, terminating." sys.exit(sigNum) def test(): time.sleep(1) print "success" time.sleep(90) if __name__ == "__main__": signal.signal(signal.SIGTERM, terminateRun) signal.signal(signal.SIGINT, userBreak) test() The error: ./test success ( pressing Ctrl-C ) Interrupted,,, Exception exceptions.SystemExit: 2 in 'garbage collection' ignored Fatal Python error: unexpected exception during garbage collection Aborted So the real question is - how to exit cleanly from embedded Python code? From shahmed at sfwmd.gov Thu Jul 10 15:35:33 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Thu, 10 Jul 2008 15:35:33 -0400 Subject: parsing incoming emails Message-ID: HI, I am working on a project where I need to parse incoming emails (Microsoft outlook) with a specific subject into an excel file or a Microsoft access table. I am using python for my GIS works but not sure how I can use python script here to work with Microsoft outlook email. Any help or idea is highly appreciated. Thanks SA -------------- next part -------------- An HTML attachment was scrubbed... URL: From niklas.norrthon at hotmail.com Tue Jul 22 02:32:06 2008 From: niklas.norrthon at hotmail.com (Niklas Norrthon) Date: Mon, 21 Jul 2008 23:32:06 -0700 (PDT) Subject: formatting list -> comma separated (slightly different) References: Message-ID: On 9 Juli, 22:25, Michiel Overtoom wrote: > Paul & Robert wrote... > > d = ["soep", "reeds", "ook"] > >print ', '.join(d) > > soep, reeds, ook > > I occasionally have a need for printing lists of items too, but in the form: > "Butter, Cheese, Nuts and Bolts". ?The last separator is the word 'and' > instead of the comma. The clearest I could come up with in Python is below. > I wonder if there is a more pythonic solution for this problem. ?Maybe > something recursive? [snip] > def pretty(f): > ? ? if len(f)==0: return '' > ? ? if len(f)==1: return f[0] > ? ? sepwithcommas=f[:-1] > ? ? sepwithand=f[-1] > ? ? s=', '.join(sepwithcommas) > ? ? if sepwithand: > ? ? ? ? s+=' and '+sepwithand > ? ? return s def pretty(names): return ' and '.join(', '.join(names).rsplit(', ', 1)) > friends=['Anne','Bob','Chris','Debbie','Eve','Fred'] print pretty(friends) From mensanator at aol.com Fri Jul 18 20:58:24 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 18 Jul 2008 17:58:24 -0700 (PDT) Subject: new itertools functions in Python 2.6 References: <4dd80ff2-5fda-405a-a637-08c985ff8add@e53g2000hsa.googlegroups.com> <498a38d4-10b5-4824-8401-5ebb510fcfa8@y38g2000hsy.googlegroups.com> <49e8f7eb-b4c6-4a51-af0d-54a257fcc353@x41g2000hsb.googlegroups.com> Message-ID: <5032701a-5a82-4dfe-9899-a180ed50a274@c65g2000hsa.googlegroups.com> On Jul 16, 5:05 am, Mark Dickinson wrote: > On Jul 16, 7:20 am, Mensanator wrote: > > > > > ## Combinations with replacement > > > > ## ----------------------------- > > > > ## aaa aab aac aad aae abb abc abd abe acc acd ace > > > > ## add ade aee bbb bbc bbd bbe bcc bcd bce bdd bde > > > > ## bee ccc ccd cce cdd cde cee ddd dde dee eee > > > > ## > > > > ## actual words: 35 (m+n-1)!/(n!(m-1)!) words: 35 > >>> for x in combinations(range(7), 4): > ... x = [-1] + list(x) + [7] > ... print ''.join(c*(x[i+1]-x[i]-1) for i, c in enumerate('abcde')) > > Generalization left as an exercise for the reader. First part of exercise: figure out what's going on. ##[-1, 0, 1, 2, 3, 7] ['', '', '', '', 'eee'] eee ##[-1, 0, 1, 2, 4, 7] ['', '', '', 'd', 'ee'] dee ##[-1, 0, 1, 2, 5, 7] ['', '', '', 'dd', 'e'] dde ##[-1, 0, 1, 2, 6, 7] ['', '', '', 'ddd', ''] ddd ##[-1, 0, 1, 3, 4, 7] ['', '', 'c', '', 'ee'] cee ##[-1, 0, 1, 3, 5, 7] ['', '', 'c', 'd', 'e'] cde ##[-1, 0, 1, 3, 6, 7] ['', '', 'c', 'dd', ''] cdd ##[-1, 0, 1, 4, 5, 7] ['', '', 'cc', '', 'e'] cce ##[-1, 0, 1, 4, 6, 7] ['', '', 'cc', 'd', ''] ccd ##[-1, 0, 1, 5, 6, 7] ['', '', 'ccc', '', ''] ccc ## Damn, that's clever ## empty strings disappear when joined Here's what I came with for a generalization. s = 'abcde' m = len(s) n = 3 mn1 = m+n-1 m1 = m-1 p = [tuple(''.join(c*(q[i+1]-q[i]-1) for i, c in enumerate(s))) \ for q in [[t for t in chain.from_iterable(([-1],r,[mn1]))] \ for r in combinations(range(mn1), m1)]] I used the tuple() to give output consistent with the itertools functions. Combinations with replacement [26 letters 4 at a time] version 2 (Mark Dickinson) ------------------------------------------------------- actual words: 23751 (m+n-1)!/(n!(m-1)!) words: 23751 0.828000068665 seconds Drat, that's not very impressive. And here I thought using chain.from_iterable was a nice touch. Not much better than my version. p = [i for i in ifilter(lambda x: list(x)==sorted(x),product(s,repeat=n))] Combinations with replacement [26 letters 4 at a time] (using ifilter(product)) ------------------------------------------------------- actual words: 23751 (m+n-1)!/(n!(m-1)!) words: 23751 0.84299993515 seconds Maybe all the time saved not iterating through the entire Cartesian Product is lost to the overhead of all that list and string manipulation. Makes me wish they had done this function directly in itertools. Even the full Cartesian Product is faster despite being almost 20 times larger: Permutations with replacement [26 letters 4 at a time] (using product) ------------------------------------------------------- 0.453000068665 seconds for 456976 words Not to mention my goofy ooloop6 program (which certainly isn't a replacement for itertools since it only works with a single sorted iterable). Combinations with replacement [26 letters 4 at a time] original nested for loop ------------------------------------------------------- 0.18700003624 seconds for 23751 words Permutations with replacement [26 letters 4 at a time] original nested for loop ------------------------------------------------------- 0.344000101089 seconds for 456976 words So, maybe there simply ISN'T a GOOD way to do Combinations With Replacement. Thanks anyway. > > Mark From mail at timgolden.me.uk Wed Jul 16 03:29:45 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 08:29:45 +0100 Subject: About wmi In-Reply-To: <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> Message-ID: <487DA369.5080607@timgolden.me.uk> patrol wrote: >> http://timgolden.me.uk/wmi-project/wmi.py > > It cannot work either. Oh well. It was only a quick fix! I'll try to get some kind of non-ASCII edition of Windows to test against. As I understand it, the situation is that some WMI exception (ie coming from the underlying WMI/COM subsystem) results in an error message which contains non-ASCII characters. Just so I'm not chasing red herrings, could you paste the output from the following code, please? import wmi # use the version linked above c = wmi.WMI ("non-existent computer") # # Should give a traceback here for the DCOM # error, not a UnicodeDecodeError. # Thanks TJG From malaclypse2 at gmail.com Fri Jul 11 15:20:01 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 11 Jul 2008 15:20:01 -0400 Subject: Filechooser issues In-Reply-To: <576590.26999.qm@web54501.mail.re2.yahoo.com> References: <576590.26999.qm@web54501.mail.re2.yahoo.com> Message-ID: <16651e80807111220h19e9bd76u94f88afc09f10ad0@mail.gmail.com> On Fri, Jul 11, 2008 at 3:09 PM, Mr SZ wrote: > ff = gtk.FileFilter.add_pixbuf_formats() > The documentation doesn't say anything about an argument to be passed: > http://www.pygtk.org/docs/pygtk/class-gtkfilefilter.html#method-gtkfilefilter--add-pixbuf-formats I don't know anything about gtk or its python bindings. That being said, the reference page seems to say you need to do this: ff = gtk.FileFilter() #Create a file filter object ff.add_pixbuf_formats() #Tell the object what to filter for -- Jerry From is_this at visible.com Thu Jul 31 13:02:53 2008 From: is_this at visible.com (Bruce Frederiksen) Date: Thu, 31 Jul 2008 17:02:53 +0000 Subject: problem when reading file References: Message-ID: <4ad40$4891f03d$18607848$1746@KNOLOGY.NET> On Thu, 31 Jul 2008 23:44:33 +1000, shrimpy wrote: > hi every one, i am new to python, > and coz i want to write a handy command for my linux machine, to find > a word in all the files which are under the current folder. > > the code is half done, but when i run it, it complain, and i don`t know why??? > > can anyone help me have a look at it? > > > here is the message it complain > ======================================= > file is : qt_plugins_3.3rc > > Traceback (most recent call last): > File "./python_script/svn_grep.py", line 34, in > searPatten(file,'are','no') > File "./python_script/svn_grep.py", line 8, in searPatten > openFile = open(file, 'r') > IOError: [Errno 2] No such file or directory: 'qt_plugins_3.3rc' > > > here are the code i wrote > ---------------------------------------------------------------code begin > > > for root, dirs, files in os.walk(os.getcwd()): > for file in files: > print "=======================================" > print "file is : " + file + "\n" > searPatten(file,'are','no') > > ---------------------------------------------------------------code end Try changing that last line to: searPatten(os.path.join(root, file), 'are', 'no') You'll have to import os.path too... From mensanator at aol.com Sat Jul 12 15:28:06 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 12 Jul 2008 12:28:06 -0700 (PDT) Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: On Jul 12, 2:18?pm, Terry Reedy wrote: > Peter Otten wrote: > > Denis Kasak wrote: > > >> Basically, it reverses the list in place, so it modifies the list which > >> called it. It does not return a /new/ list which is a reversed version > >> of the original, as you expected it to. Since it doesn't return anything > >> explicitly, Python makes it return None. Hence, the comparison you are > >> doing is between the original list and a None, which is False, naturally. > >> Try this: > > >> spam = ['a', 'n', 'n', 'a'] > >> eggs = spam[:] > >> if spam.reverse() == eggs: > >> ? ? print "Palindrome" > > > Your explanation is correct, but your example code compares None to > > ['a', 'n', 'n', 'a'] and therefore won't print "Palindrome", either. > > I don't know if this was posted yet, It hasn't. and here's why: IDLE 2.6b1 >>> seq=['a','n','n','a'] >>> seq.reversed() Traceback (most recent call last): File "", line 1, in seq.reversed() AttributeError: 'list' object has no attribute 'reversed' > but 'seq.reversed() == seq' is the > simple way to test for 'palindomeness'. Not in 2.x. From mail at microcorp.co.za Tue Jul 8 03:51:17 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 8 Jul 2008 09:51:17 +0200 Subject: Cross Compiler for Python? Message-ID: <001001c8e0d2$3604d720$0d00a8c0@hendrik> Jorgen Grahn wrote: >This is a special case of a more general, non-Python problem which you >will have to address if you want to build an industrial controller. > >If your target has no C compiler[1], you have to set up a cross-compiling >environment. I'd be surprised if the eBox doesn't come with >documentation covering this. The eBox comes with a non free (both as in beer and speech) distribution, without even a root password, and tied to the mac address in the hardware so that it can only run on a specific box. So we (the local distributor and us) are trying to put together something free and useful. I think what they are doing is of dubious legality, but instead of fighting it, we are simply ignoring it. If there was any documentation, I certaintly did not see it. > >If there are special procedures and requirements for cross-compiling >Python (someone else indicated there are), I guess the Python >installation notes must cover this in a general way. > The python readme tells you how to install on the same box - I have not found anything that tells me how to do a cross compile, which is the reason I started this thread... >/Jorgen > >[1] Or even if it has one. It is much more convenient to build in your >normal work environment where you have plenty of disk, CPU and RAM, >a good text editor, version control, Perl ... So far, I have sternly resisted getting involved with Perl, and I hope to die before I have to wrap my head around it. - Hendrik From Xue.Huichao at gmail.com Thu Jul 17 05:19:46 2008 From: Xue.Huichao at gmail.com (Bighead) Date: Thu, 17 Jul 2008 02:19:46 -0700 (PDT) Subject: common elements between list of lists and lists References: <2724c6f8-d75d-4fc2-ac8f-310f4f622aae@p25g2000hsf.googlegroups.com> Message-ID: On Jul 17, 4:30 pm, antar2 wrote: > Hello, > > I am a beginner in python. > following program prints the second element in list of lists 4 for the > first elements in list 4 that are common with the elements in list 5 > > list4 = [['1', 'a'],['4', 'd'],['8', 'g']] > list5 = ['1', '2', '3'] > > for j in list4: > for k in list5: > if j[0] == k: > print j[1] > > Result: a > > I would like to do the same thing starting with following lists, where > the numbers in list 5 are without ''. Is there a way to convert > integers in a list to integers in '' ? This is based on a situation > where I want to find common numbers between a list and a list of lists > where the numbers in the list are without '' and the numbers in the > list of lists are with '' > > list4 = [['1', 'a'],['4', 'd'],['8', 'g']] > list5 = [1, 2, 3] > > This might be a stupid question, but anyway, thanks for your answer > It is not my first post on this site. In some way it is not possible > to react on the messages that I receive to thank the persons that > react. Anyway, thanks a lot By "integer without ''" you mean integers not embraced by single quotes, right? Actually, '1' is a string, not an integer. If you want to normalize the first elements of all the lists in list4, just use int() to convert them. That is: list4 = [['1', 'a'],['4', 'd'],['8', 'g']] list5 = ['1', '2', '3'] set5 = set(map(int, list5)) list4 = [[int(i[0]), i[1]] for i in list4] for j in list4: if j[0] in set5: print j[1] You can have a try :) From chrisspen at gmail.com Thu Jul 31 00:35:55 2008 From: chrisspen at gmail.com (Chris) Date: Wed, 30 Jul 2008 21:35:55 -0700 (PDT) Subject: Executing Python From Perl Message-ID: <5720e913-e3ce-4ea5-a0a4-b92e53e89682@59g2000hsb.googlegroups.com> I have an old application that has an embedded Perl interpreter exposing an API. However, all the code I have needs to use the API is in Python. What's the easiest way access my Python code from inside Perl? The closest thing I've found is the Inline::Python module (http://search.cpan.org/~neilw/Inline-Python-0.22/Python.pod), but it seems to have died about 6 years ago. From fredrik at pythonware.com Mon Jul 21 03:10:21 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 09:10:21 +0200 Subject: Python Written in C? In-Reply-To: <48841799.5020808@gmail.com> References: <48841799.5020808@gmail.com> Message-ID: Michael Torrie wrote: > giveitawhril2008 at gmail.com wrote: >> I'm not dissing Python, here. Just noting that, if it is written in C, >> that throws a curve at me in trying to balance the value of learning >> Python vs. some other major language. > > Definitely one of the most non-sequitor statements I have ever heard. > Actually your entire post doesn't make much sense. Maybe you are a > brother bot to castropini? or that perl troll making another attempt to add noise to this newsgroup? I'm a bit surprised that he managed to generate this many replies, really. From sk8in_zombi at yahoo.com.au Fri Jul 18 10:27:10 2008 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Fri, 18 Jul 2008 07:27:10 -0700 (PDT) Subject: Help with decorators Message-ID: <947605.33489.qm@web54507.mail.re2.yahoo.com> Hi, I'm using decos for the first time.I want to check the input and then call a function in a class. I'm pasting the code: ??? def check_input_sanity(self,rover_input): ??? ??? '''Check the input from client''' ??? ??? def _check(fn): ??? ??? ??? def _inner(rover_input): ??? ??? ??? ??? if rover_input[0].upper().replace('L','').replace('R').replace('M') == '' and rover_input[1].upper() in ['N','S','E','W']: ??? ??? ??? ??? ??? print 'Input is sane'??? ??? ??? ??? ??? ??? fn() ??? ??? ??? ??? return _inner ??? ??? return _check??? ??? ??? ??? ??? ??? ?? ??? @check_input_sanity([self.origorient,self.direction_str,self.init_loc]) ??? def tell_coord_from_path(self): ??? ??? '''Gives the final co-ordinate and the direction untill it falls off/reaches.''' ??? ??? pdir = self.origorient #Present direction here the vars : self.origorient,self.direction_str,self.init_loc are the ones I would like to check for sanity. But I get an error: Traceback (most recent call last): ? File "tw.py", line 5, in ??? import sys,os,robo ? File "C:\Python25\thought\robo.py", line 30, in ??? class robo_actions(robo): ? File "C:\Python25\thought\robo.py", line 58, in robo_actions ??? @check_input_sanity([self.origorient,self.direction_str,self.init_loc]) NameError: name 'self' is not defined Why is this so? aren't they to be referred to by self with in a class as they are attributes of the object ? " life isn't heavy enough,it flies away and floats far above action" Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: From robnhood007 at yahoo.com Thu Jul 17 14:45:25 2008 From: robnhood007 at yahoo.com (robnhood00) Date: Thu, 17 Jul 2008 11:45:25 -0700 (PDT) Subject: Need Python Programmer (preferentially in Los Angeles) References: Message-ID: Fair enough. All details of the project will be disclosed so a proper bid can be put in place. I just need an experienced Python Programmer and I'll put you in direct contact with the client and I won't even take a referral fee. I just want the project completed. Thanks again, Rob On Jul 16, 6:01?am, Scott David Daniels wrote: > robnhood00 wrote: > > I need apythonprogrammer that can integrate graphics into an > > existingpythonapplication. ?The application is a basic application > > and the job should be pretty easy for an experiencedPython > > programmer. ?Los Angeles programmer is preferred but this can > > obviously be done from anywhere. > > Please contact me at robnhood... at yahoo.com is you can help me. > > Thank you. > > I get worried when I hear people tell me that a job they don't know > how to do "should be pretty easy," but at least it is better than > "should only take a week." ?What I'd rather hear is, "seems like it > is a simple job." > > Beware of customers who know something will take little effort > without being able to characterize that effort. > > --Scott David Daniels > Scott.Dani... at Acm.Org From larry.bates at websafe.com` Sat Jul 12 15:18:34 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 12 Jul 2008 14:18:34 -0500 Subject: Beginner Question : Iterators and zip In-Reply-To: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> References: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> Message-ID: <4qCdnURK6q4XnuTVnZ2dnUVZ_vzinZ2d@comcast.com> moogyd at yahoo.co.uk wrote: > Hi group, > > I have a basic question on the zip built in function. > > I am writing a simple text file comparison script, that compares line > by line and character by character. The output is the original file, > with an X in place of any characters that are different. > > I have managed a solution for a fixed (3) number of files, but I want > a solution of any number of input files. > > The outline of my solution: > > for vec in zip(vec_list[0],vec_list[1],vec_list[2]): > res = '' > for entry in zip(vec[0],vec[1],vec[2]): > if len(set(entry)) > 1: > res = res+'X' > else: > res = res+entry[0] > outfile.write(res) > > So vec is a tuple containing a line from each file, and then entry is > a tuple containg a character from each line. > > 2 questions > 1) What is the general solution. Using zip in this way looks wrong. Is > there another function that does what I want > 2) I am using set to remove any repeated characters. Is there a > "better" way ? > > Any other comments/suggestions appreciated. > > Thanks, > > Steven > > > > > You should take a look at Python's difflib library. I probably already does what you are attempting to "re-invent". -Larry From mrkafk at gmail.com Mon Jul 21 12:12:54 2008 From: mrkafk at gmail.com (mk) Date: Mon, 21 Jul 2008 18:12:54 +0200 Subject: Python Written in C? In-Reply-To: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> Message-ID: > Who cares what language a language is written in as long as you can be > productive - which you certainly can be in Python. Seriously, though, would there be any advantage in re-implementing Python in e.g. C++? Not that current implementation is bad, anything but, but if you're not careful, the fact that lists are implemented as C arrays can bite your rear from time to time (it recently bit mine while using lxml). Suppose C++ re-implementation used some other data structure (like linked list, possibly with twists like having an array containing pointers to 1st linked list elements to speed lookups up), which would be a bit slower on average perhaps, but it would behave better re deletion? From ojeeves at gmail.com Fri Jul 18 12:29:10 2008 From: ojeeves at gmail.com (oj) Date: Fri, 18 Jul 2008 09:29:10 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> Message-ID: <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> > > > Why not just use * instead of + like: > > > if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of > > string; $ means end of string > > ? ?print "Invalid" > > > This will *only* print invalid when there is a character other than L, > > R, or M or a empty string. > > Sorry, forget the beginning and ending markers, I just tried it out, it > doesn't work. > use this instead: > > if re.search(r'[^LRM]*', var): > ? ?print "Invalid" No, that's broken. That searches for any number of invalid characters. Even 0, so it ALWAYS matches, no matter what string you give it. My regex worked in the first place, you're complicating it needlessly. The presence of one invalid character makes the string invalid, so why not just search for one? Similarly, there's no need to stick in the beginning and end markers - you're not trying to match the entire string, just find part of it that is invalid. However, I think the sets solution by Scott David Daniels is the most elegant method put forward. From spython01 at gmail.com Tue Jul 22 17:56:45 2008 From: spython01 at gmail.com (Samir) Date: Tue, 22 Jul 2008 14:56:45 -0700 (PDT) Subject: Iterating Through List or Tuple References: Message-ID: <422bf0e3-da8c-42bf-b6da-67111dc8fb2a@2g2000hsn.googlegroups.com> Fredrik, Marc, Larry -- Thank you all for your very fast and informative replies. I had not come across "itertools" in my search. This group is a great resource. Samir From gcmartijn at gmail.com Sat Jul 26 08:54:14 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Sat, 26 Jul 2008 05:54:14 -0700 (PDT) Subject: re.findall(a patern,'function(dsf sdf sdf)') References: <8fc6d72a-cfc5-4e9d-af56-a009a464c6bb@27g2000hsf.googlegroups.com> <2dd5c418-f532-4f50-923e-057a10f01fdd@79g2000hsk.googlegroups.com> Message-ID: <47a011c8-c672-4dd2-b33a-3dde8733770c@l42g2000hsc.googlegroups.com> On 26 jul, 14:25, Fredrik Lundh wrote: > gcmart... at gmail.com wrote: > > - For me its hard to learn the re , I will try to search again at > > google for examples and do some copy past things. > > this might be useful when figuring out how RE:s work: > > ? ? ?http://kodos.sourceforge.net/ > > also, don't forget the following guideline: > > ? ? "Some people, when confronted with a problem, think 'I know, > ? ? I'll use regular expressions.' ? Now they have two problems." > > some advice: > > - Keep the RE:s simple. ?You can often simplify things a lot by doing > multiple searches, or even by applying a second RE on the results from > the first. ?In this case, you could use one RE to search for BlaObject, > and then use another one to extract the first argument. > > - Ordinary string methods (e.g. find, partition, split) are often a very > capable alternative (in combination with simple RE:s). ?In your case, > for JavaScript code that's as regular as the one in your example, you > can split the string on "BlaObject(" and then use partition to strip off > the first argument. > > - only use RE:s to read specialized file formats if you know exactly > what you're doing; there's often a ready-made library that does it much > better. > > - The regular expression machinery is not a parser. ?You cannot handle > all possible syntaxes with it, so don't even try. > > Thanks for the info, I will download that program later so I can build a re (i hope) Because I can't wait for that re, I have made a non re solution what is working for now. for a in bla.split(): if a.find('BlaObject')<>-1: print a[11:].replace("'","").replace('"',"").replace(",","") (I know this is not the best way, but it helps me for now) From ggpolo at gmail.com Mon Jul 28 18:38:24 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 28 Jul 2008 19:38:24 -0300 Subject: Is it allowed to use function results as default arguments ? In-Reply-To: <488E2BF1.8020003@gmail.com> References: <488E2BF1.8020003@gmail.com> Message-ID: On Mon, Jul 28, 2008 at 5:28 PM, Stef Mientki wrote: > hello, > > I've a perfect working procedure, > at least as far I've tested it it works perfect. > > But I was just experimenting with inspect, > and saw that the default argument was not parsed correctly. > > So I wonder if this is allowed: > > def Get_Relative_Path ( target, base=os.curdir ) : > ... > > As inspect returns the following: > > (['target', 'base'], None, None, ('.',)) Are you referring to the last item in the tuple above ? It is merely listing the default values, it is not associating target to '.'. What else would the tuple be if there is just base with a default value ? > > thanks, > Stef Mientki > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From rNOSPAMon at flownet.com Fri Jul 4 03:17:14 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Fri, 04 Jul 2008 00:17:14 -0700 Subject: Parsing MIME-encoded data in an HTTP request References: <4834df8f-2cf8-434c-8c95-ff53024766c8@p25g2000hsf.googlegroups.com> Message-ID: In article <4834df8f-2cf8-434c-8c95-ff53024766c8 at p25g2000hsf.googlegroups.com>, s0suk3 at gmail.com wrote: > On Jul 3, 3:59 pm, Ron Garret wrote: > > I'm writing a little HTTP server and need to parse request content that > > is mime-encoded. All the MIME routines in the Python standard library > > seem to have been subsumed into the email package, which makes this > > operation a little awkward. > > To deal with messages of that kind, I've seen modules such as > 'rfc822', and 'mimetools' (which apparently builds itself from > 'rfc822', so it might be more complete). There's also 'mimetypes', in > case you need to deal with file extensions and their corresponding > MIME media type. >From the mimetools docs: "Deprecated since release 2.3. The email package should be used in preference to the module. This module is present only to maintain backward compatibility." > > > It seems I have to do the following: > > > > 1. Extract the content-length header from the HTTP request and use that > > to read the payload. > > > > 2. Stick some artificial-looking headers onto the beginning of this > > payload to make it look like an email message (including the > > content-type and content-transfer-encoding headers) > > > > 3. Parse the resulting string into a email message > > > > Email? Why does an HTTP server need to build an email message? It shouldn't. That's my whole point. But see the docs excerpt above. > I remember doing things like that some time ago when building an HTTP > server myself (http://code.google.com/p/sws-d/). Incidentally, I > resisted the urge to use much of the Python's library facilities (most > things are done manually; am I a knucklehead or what!? :). You might > wanna take a look to get some ideas. I'd much prefer not to reinvent this particular wheel. rg From semanticist at gmail.com Wed Jul 30 23:21:15 2008 From: semanticist at gmail.com (Miles) Date: Wed, 30 Jul 2008 23:21:15 -0400 Subject: Optimizing size of very large dictionaries In-Reply-To: <1217464179.31710.1266222419@webmail.messagingengine.com> References: <1217464179.31710.1266222419@webmail.messagingengine.com> Message-ID: On Wed, Jul 30, 2008 at 8:29 PM, wrote: > Background: I'm trying to identify duplicate records in very large text > based transaction logs. I'm detecting duplicate records by creating a SHA1 > checksum of each record and using this checksum as a dictionary key. This > works great except for several files whose size is such that their > associated checksum dictionaries are too big for my workstation's 2G of RAM. What are the values of this dictionary? You can save memory by representing the checksums as long integers, if you're currently using strings. -Miles From Bill at SynectixLtd.com Fri Jul 11 04:18:12 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Fri, 11 Jul 2008 09:18:12 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: "Tim Golden" wrote in message news:mailman.256.1215697841.20628.python-list at python.org... > Bill Davy wrote: >> I'm not sure OL2003 can read news. I think perhaps some later OL can >> (added tot he View menu, perhaps?). So I use OL Express to read news. >> The OL with which I wish to communicate is: >> >> Application name Outlook >> Version 11.0 >> Build 8217 >> Product ID 70141-700-0350904-56905 >> Language English (United States) >> Application Path C:\Program Files\Microsoft Office\OFFICE11\ >> System Language English (United Kingdom) >> Mail Support Not Available >> Current folder Inbox >> Current item Not Available > > Where did you get to with this, Bill? I wasn't sure if no news > was good news or whether you'd gone a different way, or > were still trying things... > > TJG Hi Tim, Well, at 5pm last Friday I posted: " I kept looking and thought I was saved when I found Receipe 10.16 in the Python Cookbook but .... I changed the following: self.oOutlookApp = Dispatch("Outlook.Application") #self.oOutlookApp = gencache.EnsureDispatch("Outlook.Application") Because gencache failed and I hade run makepy last week (I only get one day a week to look at this). Then the following failed because (as I found) olFolderContacts is not in any of constants' dictionaries. ofContacts = onMAPI.GetDefaultFolder(constants.olFolderContacts) So, sadly, I shall have to put this aside for another week and get on with some work. Any thoughts would be gratefully accepted. TIA, Bill " and since then have been busy with work, and my other job, and the garden. Now I am back looking at this (and using WInUSB to talk to a Maxim 3421E etc etc but that's another story). So any help today will be much appreciated. Rgds, Bill From sjmachin at lexicon.net Mon Jul 28 20:35:00 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 28 Jul 2008 17:35:00 -0700 (PDT) Subject: seemingly simple list indexing problem References: <488E4170.2020804@islandtraining.com> Message-ID: <83dc4629-7a34-4721-a0fa-d97589c3f571@u12g2000prd.googlegroups.com> Guilherme Polo wrote: > It wasn't supposed to be the fastest solution, also, he didn't mention > duplicated items. He didn't need to. He explicitly said "list" (which permits duplicates) and didn't mention a self-imposed uniqueness constraint. From alexnbryan at gmail.com Fri Jul 11 01:56:10 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Fri, 11 Jul 2008 00:56:10 -0500 Subject: Simple question, how do you tell how many items in a list? Message-ID: <268ac2770807102256o4f41e784q79a0caf849c046b4@mail.gmail.com> I am just wondering how you get an integer value for how many items there are in a list, preferably w/o a for loop. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stesch at no-spoon.de Wed Jul 16 23:41:11 2008 From: stesch at no-spoon.de (Stefan Scholl) Date: Thu, 17 Jul 2008 05:41:11 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> Message-ID: <0T56p3tmInifNv8%stesch@parsec.no-spoon.de> Fredrik Lundh wrote: > Stefan Scholl wrote: > >> Django isn't ready. > > That's a remarkably ignorant statement. The 1.0 release will be in September. -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ From steve at REMOVE-THIS-cybersource.com.au Sun Jul 27 18:54:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Jul 2008 22:54:41 GMT Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <7eabe5a6-357a-4255-a958-0804959ce844@a6g2000prm.googlegroups.com> Message-ID: <009cf838$0$20302$c3e8da3@news.astraweb.com> On Sun, 27 Jul 2008 12:33:16 -0700, Russ P. wrote: > On Jul 27, 1:19 am, Steven D'Aprano cybersource.com.au> wrote: >> On Sat, 26 Jul 2008 17:14:46 -0700, Russ P. wrote: > >> > You take the name down to a single letter. As I suggested in an >> > earlier post on this thread, why not take it down to zero letters? >> >> The question isn't "why not", but "why". The status quo works well as >> it is, even if it isn't perfect. Prove that implicit self is a good >> idea -- or at least prove that it is an idea worth considering. >> >> "I don't like typing self" doesn't convince me. The same argument could >> be made typing parentheses, colons, commas, etc. We could end up with >> something like this: >> >> class Foo base >> def method x y z >> .args = list x y z >> >> That's not necessarily wrong, but it's not Python. > > And what does that have to do with my suggestion? Absolutely nothing. Not at all. You're suggesting a change to Python's syntax. I've suggested a couple more changes to Python syntax. I don't intend them to be taken seriously, but only to illustrate a point that syntax defines how a language is written. You want to change that. > It's a red herring that you seem to be using to obscure the fact that > you have no rational argument to make. I don't have to make a rational argument for keeping the status quo. That status quo just *is*. You want people to change, you need to convince them that such a change is not just "not bad" but a serious advantage, enough to make up for all the work required to implement it. I'm listening. Tell me why removing self if not merely harmless, but actively better. [...] >> By "better" do you mean "uglier"? If so, I agree with you. If not, then >> I disagree that it is better. > > You seem to be freaked out by an empty argument. Actually, it bothers me > a bit too, which is why I suggested that a period could be used as the > first argument to indicate that, like Clint Eastwood in The Good, the > Bad, and the Ugly, "self" had no name here. Well there you go now. How should we *talk* about this piece of code? Try writing a comment or docstring, or even sitting down with a fellow programmer and discussing it. What do you call this implicit Object With No Name? def fun( , cat): .cat = cat # assumes that the Object With No Name has foo versus def fun(self, cat): self.cat = cat # assumes that self has foo Before you suggest that people will continue to call the first argument "self" but just not write it down anywhere, I suggest that's a terrible idea and one which will confuse a lot of people. "Where's this 'self' defined? I can't find it anywhere!" A slightly better suggestion is "the instance", but that fails here: class C(object): def method(, other): assert isinstance(other, C) .cat = other # assumes that the instance has foo # er, that is to say, the implicit instance, # not the other instance The ability to talk easily about the code is invaluable. Implicit self makes it harder to talk about the code. [...] >> Even uglier than the first. Convince me there's a benefit. > > Actually, I think it's elegant. And I'll bet that if Guido had suggested > it, you would think it was beautiful. Oh please. I think the syntax for ternary if is ugly, and Guido came up with that, and it doesn't even use punctuation. > Why force a name to be used when none is needed? But a name is needed. class Foo(base1, base2, base3): def meth(self, arg): super(Foo, self).meth(arg) print self try: value = _cache[self] except KeyError: value = some_long_calculation(self) How do you pass self to arbitrary functions without a name? -- Steven From dthole at gmail.com Wed Jul 2 09:21:34 2008 From: dthole at gmail.com (TheDarkTrumpet) Date: Wed, 2 Jul 2008 06:21:34 -0700 (PDT) Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> <87vdzpmxv3.fsf@internal.daycos.com> Message-ID: Another thing I'd like to add on this subject. I agree with others here that having logic in the view isn't really a bad thing. I used to think it did, but now I don't think it does as much. I feel that when you're separating out the view, you're giving really non-programmers the ability to actually do the content. That doesn't mean that non-programmers can't learn very very basic programming logic. Take, for example, the Django code. The Django template system is a very watered down version of a language. It supports very basic stuff, and I feel that really anyone can pick up on it. By totally separating out the logic, and using tags, you're adding a lot of overhead in my opinion. It's another file that needs to be included, and the logic of how it's displayed on the page is then split a bit - between the developer and the designer. If the designer feels that they want only 5 products to show on one page, they should be able to change it. THis is how I feel on the whole idea anyways. From waldemar.rymarkiewicz at gmail.com Fri Jul 25 04:06:32 2008 From: waldemar.rymarkiewicz at gmail.com (waldek) Date: Fri, 25 Jul 2008 01:06:32 -0700 (PDT) Subject: ctypes and reading value under pointer passed as param of a callback References: <6erjpeF88slmU1@mid.individual.net> Message-ID: On Jul 24, 5:01 pm, Thomas Heller wrote: > waldekschrieb: > > > Hi, > > > I'm using C dll with py module and wanna read value (buffer of bytes) > > returned in py callback as parameter passed to dll function. > > The callback receives a pointer instance. You can dereference the pointer > to read individual bytes in this way: > print data[0], data[5], data[42] > or use slicing to read a bunch of bytes: > print data[0:42] > > So, you probably want something like this: > > > -------------------------------------------------- > > def mycallback(data, size): > > # how to read data buffer here ? > > print data[:size] > > > return 0 > > > cbfunc = CFUNCTYPE(c_int, POINTER(c_uint8), c_int) > > > mydll = cdll.somedll > > mdll.foo(cbfunct) > > --------------------------------------------------------------- > > > Question: How to get bytes from the buffer passed to mycallback ??? > > Let's assume that the buffer consist of 4 bytes 4 bytes 8 bytes. > > > I tried unpack("ii8s", data[0]) and nothing. I tried different ctypes > > passed to callback and nothing. > > Thomas Cool, works fine now. ... and how to convert a list of bytes to py string or int ?? i.e data[:4] -> py int data[4:8] -> py int data[8:] -> py strng I tried unpack and unpack_from but the buff should be an string or buffer not a list of bytes as data is. any suggestions? From toby at tobiah.org Wed Jul 30 15:42:42 2008 From: toby at tobiah.org (Tobiah) Date: Wed, 30 Jul 2008 12:42:42 -0700 Subject: How do I include a shell variable in my script? References: Message-ID: On Tue, 29 Jul 2008 07:53:53 -0700, laredotornado wrote: > Hi, > > I'm running a Python script on a Solaris 9 machine, invoking the > Python script from ksh, if that matters. There is an enviornment > variable, $JAVA_HOME, that I would like to include in my script, > replacing "/path/to/java/home'" with the value of $JAVA_HOME. > > java_home='/path/to/java/home' > > How do I do this? If I need to pass a command line argument, so be > it, but I figure there is a more direct way to get the value. > > Thanks, - Dave import os java_home = os.environ['JAVA_HOME'] ** Posted from http://www.teranews.com ** From stefan_ml at behnel.de Tue Jul 29 16:26:41 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 29 Jul 2008 22:26:41 +0200 Subject: SWIG and char* newb questions :) In-Reply-To: <7ec26fb6-3d6a-4e1b-b2c9-a0a254780153@26g2000hsk.googlegroups.com> References: <7ec26fb6-3d6a-4e1b-b2c9-a0a254780153@26g2000hsk.googlegroups.com> Message-ID: <488f7d01$0$1071$9b4e6d93@newsspool3.arcor-online.net> code_berzerker wrote: > Hi i'm relatively new to Python and my C/C++ knowledge is near to > None. Having said that I feel justified to ask stupid questions :) Have you considered using Cython? It's almost Python, but it compiles to C code for a Python extension module and even lets you call C functions directly from your code. http://cython.org/ Stefan From google at mrabarnett.plus.com Sun Jul 13 20:14:23 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 13 Jul 2008 17:14:23 -0700 (PDT) Subject: Using Groups inside Braces with Regular Expressions References: <10284e46-1601-4269-a1a0-ef3831e9f85c@z66g2000hsc.googlegroups.com> Message-ID: <87e2b1a0-e732-42d3-aa94-061dcd81d35c@z72g2000hsb.googlegroups.com> On Jul 14, 12:05?am, Chris wrote: > I'm trying to delimit ?sentences in a block of text by defining the > end-of-sentence marker as a period followed by a space followed by an > uppercase letter or end-of-string. > > I'd imagine the regex for that would look something like: > [^(?:[A-Z]|$)]\.\s+(?=[A-Z]|$) > > However, Python keeps giving me an "unbalanced parenthesis" error for > the [^] part. If this isn't valid regex syntax, how else would I match > a block of text that doesn't the delimiter pattern? > What is the [^(?:[A-Z]|$)] part meant to be doing? Is it meant to be matching everything up to the end of the sentence? [...] is a character class, so Python is parsing the character class as: [^(?:[A-Z]|$)] ^^^^^^^^^^ From wiggly at wiggly.org Thu Jul 31 07:21:55 2008 From: wiggly at wiggly.org (Nigel Rantor) Date: Thu, 31 Jul 2008 12:21:55 +0100 Subject: Terminate a python script from linux shell / bash script In-Reply-To: References: Message-ID: <4891A053.1080003@wiggly.org> Gros Bedo wrote: > Thank you guys for your help. My problem is that I project to use this command to terminate a script when uninstalling the software, so I can't store the PID. This command will be integrated in the spec file of the RPM package. Here's the script I'll use, it may help someone else: > > #!/bin/sh > # PYTHON SCRIPT PROCESS KILLER by GBO v0.1 > # This script will look for all the lines containing $SOFTWARENAME in the process list, and close them > > SOFTWARENAME='yoursoftware' #This is case insensitive > JOBPRESENT=$(ps -ef | grep -i $SOFTWARENAME | grep -v grep) > echo $JOBPRESENT > ps -ef | grep -i $SOFTWARENAME | grep -v grep | awk '{print $2}' | xargs kill If you have a long running process you wish to be able to kill at a later date the normal way of doing it would be for the script itself to write it's own PID to a file that you can then inspect from a different process and use to kill it. So, my_daemon.py might shove its PID into /var/run/my_daemon.pid And later my_daemon_killer.py (or indeed my_daemon_killer.sh) would read the PID out of /var/run/my_daemon.pid and pass that to a kill command. Using ps/grep in the way you're trying to do is always going to be inexact and people will not thank you for killing processes they wanted running. n From bronger at physik.rwth-aachen.de Sat Jul 26 11:22:55 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 26 Jul 2008 17:22:55 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <2b74a8a8-e1fe-4ddd-862d-033d77f57535@a70g2000hsh.googlegroups.com> Message-ID: <874p6cacvk.fsf@physik.rwth-aachen.de> Hall?chen! Kay Schluehr writes: > On 26 Jul., 09:45, Torsten Bronger > wrote: >> >> Terry Reedy writes: >> >>> [...] >>> >>> Or the proposal would have to be that 'self' is mandatory for >>> all programmers in all languages. I think *that* would be >>> pernicious. People are now free to write the more compact 's.sum >>> = s.a + s.b + s.c' if they want instead of the 'self' version. >>> And again, not everyone writes in English. >> >> Of course, "self" would have to become a reserved word. > > ?? > > This is an extra requirement. Why do you want to make 'self' a > keyword? How could one determine which other identifier must be inserted into the method's signature? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From nightdreams143 at gmail.com Sat Jul 26 04:50:05 2008 From: nightdreams143 at gmail.com (Enjoy) Date: Sat, 26 Jul 2008 01:50:05 -0700 (PDT) Subject: Just click and Enjoy the latest Shreya and Asin Message-ID: Just click and Enjoy the latest Shreya and Asin SEXY photes also your favorite Heroines............... ############################ http://lovegroup341.blogspot.com/ ############################# ENJOY each moments From laiyijia at yahoo.ca Mon Jul 28 09:27:31 2008 From: laiyijia at yahoo.ca (Harry) Date: Mon, 28 Jul 2008 13:27:31 -0000 Subject: Python FTP - NameError: name 'mydpa' is not defined Message-ID: Hi there. I am trying to download a file(sn.last) from a public FTP server with the following code: from ftplib import FTP ftp=FTP('tgftp.nws.noaa.gov') ftp.login() ftp.cwd('SL.us008001/DF.of/DC.radar/DS.81dpr/SI.kbuf') ftp.retrbinar('RETR sn.last', open(mydpa,'wb').write) ftp.quit() but got an error message, which I think is normal: Traceback (most recent call last): File "", line 1, in ftp.retrbinary('RETR sn.last', open(mydpa,'wb').write) NameError: name 'mydpa' is not defined I don't know much about python, but just try to use the code to download data. I don't know where the file will be saved to. Is the mydata a file name or a folder name? where will it be saved to even if it's working? Please help be fixed the problem step by step? I am using 2.5.2 by the way. I really appreciate your help. Thanks. From pythonnutter at gmail.com Sat Jul 19 23:33:36 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Sun, 20 Jul 2008 13:33:36 +1000 Subject: Any Game Developers here? In-Reply-To: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: I used to use PyGame but the horrible delay waiting for OS X binaries put me off. I now use Pyglet extensively, and combine Pyglet + Rabbyt to get amazing sprite handling speeds. Pyglet/Rabbyt make use of OpenGL which comes installed on all the major systems out there. PyGame requires the installation of the SDL library to work so is a lot larger installation requirement. There are two books I know of currently in print on game programming, both use PyGame as it was out first. One book is horrible and only worth for cleaning yourself up after you use the bathroom. The second is really well written (The L express game programming book) and highly recommended if you need to get some basic game design and programming under your belt in Python. That said its stupidly easy to port examples to work on Pyglet/Rabbyt so you won't do yourself a dis-service if you want to buy the book but want to develop later in Pyglet/Rabbyt. Cheers, PN P.S. Since you've likely found Pyglet and PyGame already, the only other reference URL you need is for Rabbyt so go here for that: http://matthewmarshall.org/projects/rabbyt/ 2008/7/19 Michael Lubker : > Any people that use Python as the predominant language for their game > development here? > > ~Michael > -- > http://mail.python.org/mailman/listinfo/python-list > From alexnbryan at gmail.com Thu Jul 17 03:07:40 2008 From: alexnbryan at gmail.com (Alexnb) Date: Thu, 17 Jul 2008 00:07:40 -0700 (PDT) Subject: Getting a unknown word out of a list with no spaces Message-ID: <18502758.post@talk.nabble.com> Hello Lets say I have a string: --a href="/browse/brick"--brick--/a-- The -- needs to be replaced with < or > where applicable. and I want the "brick" out of that string (the second brick that is). How can I get just the "brick" out of that string? -- View this message in context: http://www.nabble.com/Getting-a-unknown-word-out-of-a-list-with-no-spaces-tp18502758p18502758.html Sent from the Python - python-list mailing list archive at Nabble.com. From larry.bates at websafe.com` Thu Jul 3 16:14:36 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 03 Jul 2008 15:14:36 -0500 Subject: Instance Names In-Reply-To: References: Message-ID: Tim Cook wrote: > On Thu, 2008-07-03 at 14:20 -0500, Larry Bates wrote: > >> I suspect there is some "misunderstanding" here. Why exactly do you think you >> need to have your instances named with [] characters in them? >> > > I often misunderstand. :-) > > But, I am implementing specifications in Python that are already > implemented in other languages. > > http://www.openehr.org/releases/1.0.1/roadmap.html > > These specifications say that an archetype node id consists of > identifiers like [at0000] and [at0001]. Now these are valid URIs and > the associated query language (AQL) used by other services will send > queries with those characters in them. > > For example: > FROM EHR [ehr_id/value=$ehrUid] CONTAINS COMPOSITION > [openEHR-EHR-COMPOSITION.encounter.v1] > CONTAINS OBSERVATION obs [openEHR-EHR-OBSERVATION.blood_pressure.v1] > WHERE > obs/data[at0001]/events[at0006]/data[at0003]/items[at0004]/value/value >> = 140 > > Since I am also using Zope3 it would be easier on me to name the > instances with those characters. > > But my fall back is to set at0000.__name__='[at0000]' and manipulate the > query to match __name__ instead of the actual instance ID. > > Thoughts? > > --Tim > > > If these will be class attributes, I believe you can use setattr() setattr('[at0000]') = ... obj = getattr(self, '[at0000]') -Larry From giltay at gmail.com Wed Jul 30 09:31:28 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Wed, 30 Jul 2008 06:31:28 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <2ac250ee-131d-44a3-9b0a-f2fb34758147@c65g2000hsa.googlegroups.com> Message-ID: <25f024b4-1b0c-4265-bc30-24431ebbe079@z72g2000hsb.googlegroups.com> On Jul 30, 5:09?am, Maric Michaud wrote: > Le Tuesday 29 July 2008 23:48:31 gil... at gmail.com, vous avez ?crit?: > > def print_members(iterable): > > ? ? if not iterable: > > ? ? ? ? print '' > > ? ? ? ? return > > ? ? print '' > > ? ? for item in iterable: > > ? ? ? ? print '%s' % item > > ? ? print '' > > But iterables can have no notion of emptiness too : > > >>>[25]: print_members((e for e in range(0))) > > > Ack! Maybe I meant "container" rather than "iterable". Or maybe I'd be wrong on that count, too. Other people have come up with better examples, so I won't try to fix my hasty code (although I'll keep that in mind if I have to write a custom XML writer). > > class Signal: > > ? ? [...] > > ? ? def dc_offset(self, amount): > > ? ? ? ? if amount == 0: > > ? ? ? ? ? ? return > > ? ? ? ? self.samples = [sample + amount for sample in self.samples] > > This function is also wrong assuming that because amount compare to zero, it > can be added to sample. Not quite. I'm assuming that if amount equals 0, then amount is some scalar. In fact, only if that comparison fails will I get my exception: since [] != 0, it will then try to add sample + [], which will raise TypeError. > If you want to make type checking just check the type or convert your > parameter to an int, but the test "== 0" is of no help here. I'm not going for type checking here because I want Signal to support int and float samples (and numpy.int16, &c.). > The only valuable point I see for this idiom is to make more explicit I am > testing a numerical value. That's one of the reasons I wrote it that way. Signal has other methods that take lists (like mix and envelope), which I could get confused with the ones that take scalars (offset and change volume). Cheers, Geoff G-T From israelu at elbit.co.il Tue Jul 29 06:04:58 2008 From: israelu at elbit.co.il (iu2) Date: Tue, 29 Jul 2008 03:04:58 -0700 (PDT) Subject: block/lambda References: <0406eb4f-8dec-4ce2-b506-8e597de2958d@56g2000hsm.googlegroups.com> Message-ID: On Jul 29, 9:36?am, Duncan Booth wrote: > iu2 wrote: > > Is it possible to grant Python another syntactic mark, similar to > > triple quotes, that will actually make the enclosed code a compiled > > code, or an anonymous function? > > Yes, the syntactic mark you are looking for is 'def'. > > Your example becomes: > > >>> def dotimes(n, callable): > > ? ? ? ? for i in range(n): callable(i) > > >>> def block(i): > > ? ? ? ? for j in range(i): > ? ? ? ? ? ? ? ? print j, > ? ? ? ? print > > >>> dotimes(5, block) > > 0 > 0 1 > 0 1 2 > 0 1 2 3 > > The only thing you asked for that this doesn't do is make 'block' > anonymous, but actually that is a good thing. > > -- > Duncan Boothhttp://kupuguy.blogspot.com Ok, I've got 2 questions about it: 1. Can you please explain why it is a good thing? 2. Will it be possible in Python 3.0 to do the following: >>> def dotimes(n, callable): for i in range(n): callable() >>> def block(): nonlocal i for j in range(i): print j, print Thanks From vlastimil.brom at gmail.com Sat Jul 26 16:13:46 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sat, 26 Jul 2008 22:13:46 +0200 Subject: wx.Timer not working In-Reply-To: <7a2a1c54-6d74-475c-9566-4d94cb5b5962@a3g2000prm.googlegroups.com> References: <7a2a1c54-6d74-475c-9566-4d94cb5b5962@a3g2000prm.googlegroups.com> Message-ID: <9fdb569a0807261313h7dc90182h8da9b7fff58d7cc6@mail.gmail.com> 2008/7/26 <5lvqbwl02 at sneakemail.com> > Windows XP SP3 > Python 2.5 > wx.version() = '2.8.1.1 (msw-unicode)' > ------ > I have written the following *simplest* implementation of wx.timer I > can think of. No workie. I want an exception, a print statement, or > something. > > The wxpython demos all work, but for some reason this isn't. The > demos are simple and straghtforward, so I think I understand how it > should work. Clues please? I've tried variations of ID's, SetOwners, > using and redefining Notify(), Bind, Connect, etc. In the cases where > the interpreter doesn't complain about passed argument types, the > callback function is never called. > > > import wx > > class MyFrame(wx.Frame): > def __init__(self, parent, id, title): > wx.Frame.__init__(self, parent, id, title, pos=(100, > 100)) > > timer = wx.Timer(self, -1) > self.Bind(wx.EVT_TIMER, self.OnTick, timer) > timer.Start(100) > > def OnTick(self, event): > print 'Hi. Bye.' > 1/0 #<-- should crash as evidence callback is being called > > class MyApp(wx.App): > def OnInit(self): > frame1 = MyFrame(None, wx.ID_ANY, "This is a test") > frame1.Show(True) > return True > > app = MyApp(0) > app.MainLoop() > > > Thanks for any advice!! > > Michael > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, not exactly sure, but compared to the demo, it seems to be a binding problem; Using "self.timer" instead of "timer" in the __init__ section and self.Bind(wx.EVT_TIMER, self.OnTick) instead of self.Bind(wx.EVT_TIMER, self.OnTick, timer) seems to work; HTH, Vlasta -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun Jul 27 04:19:17 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Jul 2008 08:19:17 GMT Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <009c2b11$0$20302$c3e8da3@news.astraweb.com> On Sat, 26 Jul 2008 17:14:46 -0700, Russ P. wrote: > On Jul 26, 2:25 pm, Terry Reedy >> There is a lot of code you have not seen. Really. In informal code I >> use 's' and 'o' for 'self' and 'other'. I don't usually post such >> because it is not considered polite. So you have seen a biased sample >> of the universe. > > You take the name down to a single letter. As I suggested in an earlier > post on this thread, why not take it down to zero letters? The question isn't "why not", but "why". The status quo works well as it is, even if it isn't perfect. Prove that implicit self is a good idea -- or at least prove that it is an idea worth considering. "I don't like typing self" doesn't convince me. The same argument could be made typing parentheses, colons, commas, etc. We could end up with something like this: class Foo base def method x y z .args = list x y z That's not necessarily wrong, but it's not Python. It's not enough to show that a change "isn't bad" -- you have to show that it is actively good. Why should Python make any changes to the current explicit self without a clear and solid reason to change? > You could if Python accepted something like > > class Whatever: > > def fun( , cat): > > .cat = cat > > This is even better than the single-character name, By "better" do you mean "uglier"? If so, I agree with you. If not, then I disagree that it is better. > not only because it > is shorter, but also because there is no question that you are referring > to "self." No need to look back at the method signature to verify that. "Don't need to look at the method signature" is not an argument in favour of implicit self. You don't need to look at the method signature when you're using an explicit self either. What happens with class-methods? With the cls (or if you prefer klass) convention, it is simple to tell what object I am referring to. Now I have to go back to the method signature to see if it is a class method or instance method, instead of just looking at the explicit name. > For those who don't like the way the empty first argument looks, maybe > something like this could be allowed: > > def fun( ., cat): Even uglier than the first. Convince me there's a benefit. -- Steven From iainking at gmail.com Tue Jul 8 09:54:33 2008 From: iainking at gmail.com (Iain King) Date: Tue, 8 Jul 2008 06:54:33 -0700 (PDT) Subject: How to make python scripts .py executable, not bring up editor References: Message-ID: On Jul 7, 10:56?pm, korean_dave wrote: > From command Prompt, i type in a script, ?"tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? find a .py file in windows explorer. Right click it->Open With- >Choose Program... Now find your python.exe file (should be in c:\python24), select it, and tick the box that says "Always use the selected program" Iain From norseman at hughes.net Fri Jul 18 17:51:32 2008 From: norseman at hughes.net (norseman) Date: Fri, 18 Jul 2008 14:51:32 -0700 Subject: Importing different versions of a module In-Reply-To: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> References: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> Message-ID: <48811064.5010603@hughes.net> mercado mercado wrote: > I have two versions of a script on my machine. One version is for new > development and the other version is a production version. This script > imports a module from a different directory, and this module again has two > versions (a development version and a production version). What I want is > for the development script to import the development module, and the > production script to import the production module, without making any > changes to the code in the script. > > For example, suppose the development script is in ~/dev/rss.py, and the > production script is in ~/prod/rss.py. I want the dev version to import > /usr/lib/python2.5/site-packages/lib_dev/parse.py, and the prod version to > import usr/lib/python2.5/site-packages/lib_prod/parse.py. > > My first instinct was to place a .pth file in ~/dev that points to > /usr/lib/python2.5/site-packages/lib_dev, and a .pth file in ~/prod that > points to /usr/lib/python2.5/site-packages/lib_prod, but it seems that > site.py doesn't look at .pth files in the current working directory. My > next attempt was to create a symbolic link in ~/dev called parse.py, > pointing to /usr/lib/python2.5/site-packages/lib_dev/parse.py, and a > symbolic link in ~/prod called parse.py, pointing to > /usr/lib/python2.5/site-packages/lib_prod/parse.py, but that didn't work > either. > > Can anybody suggest a way to achieve my goal? Thanks in advance. > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list ========================================================== Yes, but you may not like it. I do what you do. Prod and devel subdirs. I store the paths in a var at the top of my programs. I change it(them) when the program graduates. example: #!/usr/local.... . . DvlpPATH=...... #usually a full hardcoded path ending with a '/' #FnlPATH=..... . . PATH2USE=DvlpPATH #which gets changed to FnlPATH when graduating # I keep the DvlpPATH until I'm positive I'm not # going to send it back to school x= os.open(PATH2USE+"pgm_or_file.ext", 'r+b') and so forth If the there is a need, I'll hardcode to a branch point and create sub branch vars as needed and chain as needed. company_one + accounting + payables + vendors + inventory + shelf + vendors + real_property + locations company_two + (same as above) you get the idea YES! You do have to change the code. But in one place only once you are correctly set. Steve norseman at hughesnet From mail at timgolden.me.uk Mon Jul 14 07:18:53 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 14 Jul 2008 12:18:53 +0100 Subject: About wmi In-Reply-To: <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> Message-ID: <487B361D.1070503@timgolden.me.uk> Larry Bates wrote: > patrol wrote: >> I want to prevent some process from running. The code is in the >> following. I encounter some unexpected troubles. >> Probelm1: This program cannot terminate "scrcons.exe" and >> "FNPLicensingService.exe",which are system processes. >> Problem2:After a while, this program will abort by error >> File "C:\Python25\lib\wmi.py", line 397, in __call__ >> handle_com_error (error_info) >> File "C:\Python25\lib\wmi.py", line 190, in handle_com_error raise >> x_wmi, "\n".join (exception_string) >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position >> 14: ordinal not in range(128) [... snip code ...] > You should probably post this to comp.python.windows. Tim Golden > (author of WMI interface) monitors that list religously (thanks Tim). Actually, I follow this one pretty much, too. I've just been a bit busy these last few days. And still am, so this answer will be short :) 1) I'm not sure if WMI can be forced to close down system processes, but if it can it's probably by means of specifying one or more privileges when you connect. Try looking in the WMI newsgroups for a more general (non-Python) answer to this and I'll happily explain how to apply it in a Python context. 2) I can't quite see from this traceback where the problem arises. Have you snipped the traceback at all, or was that all there was? Can you narrow the thing down to a short snippet of code which I'm likely to be able to run independently, please? Sorry for the haste. TJG From maric at aristote.info Mon Jul 28 14:30:34 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 28 Jul 2008 20:30:34 +0200 Subject: Where is the correct round() method? Use math.ceil In-Reply-To: <98aab64d0807271735w111f6ec7w81c9e65f99744199@mail.gmail.com> References: <98aab64d0807271735w111f6ec7w81c9e65f99744199@mail.gmail.com> Message-ID: <200807282030.34568.maric@aristote.info> Le Monday 28 July 2008 02:35:08 Herman, vous avez ?crit?: > Where is the correct round() method? > Hello, > > I need a round function that _always_ rounds to the higher integer if > the argument is equidistant between two integers. In Python 3.0, this > is not the advertised behavior of the built-in function round() as > > seen below: > >>> round(0.5) > > 0 > > >>> round(1.5) > > 2 > > >>> round(2.5) > > 2 Hmm, I don't have the same result in python2.6, I suspect it's a floating point precision problem, try just to type "0.5" in the console to see the exact representation of this value on your system, it may be just over or just down by a small quantity. On mine with 2.6 this typically give : >>>[26]: 0.5 ...[26]: 0.5 >>>[27]: 0.49 ...[27]: 0.48999999999999999 >>>[29]: 0.51 ...[29]: 0.51000000000000001 >>>[28]: 1.1 ...[28]: 1.1000000000000001 >>>[35]: round(0.5) ...[35]: 1.0 -- _____________ Maric Michaud From kris at FreeBSD.org Thu Jul 10 06:21:31 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Thu, 10 Jul 2008 12:21:31 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <750f823a-f9de-4f81-9eb3-7c7b39237c90@y38g2000hsy.googlegroups.com> Message-ID: <4875E2AB.3020902@FreeBSD.org> John Machin wrote: > Uh-huh ... try this, then: > > http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ > > You could use this to find the "Str" cases and the prefixes of the > "re" cases (which seem to be no more complicated than 'foo.*bar.*zot') > and use something slower like Python's re to search the remainder of > the line for 'bar.*zot'. If it was just strings, then sure...with regexps it might be possible to make it work, but it doesn't sound particularly maintainable. I will stick with my shell script until python gets a regexp engine of equivalent performance. Kris From pavlovevidence at gmail.com Tue Jul 29 13:42:50 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 10:42:50 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> On Jul 29, 11:12 am, Matthew Fitzgibbons wrote: > Carl Banks wrote: > > On Jul 28, 8:15 pm, Steven D'Aprano > cybersource.com.au> wrote: > >> On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: > >>> On Jul 28, 10:00 am, Steven D'Aprano >>> cybersource.com.au> wrote: > >>>> Cutting to the crux of the discussion... > >>>> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: > >>>>> I want something where "if x" will do but a simple explicit test > >>>>> won't. > >>>> Explicit tests aren't simple unless you know what type x is. If x could > >>>> be of any type, you can't write a simple test. Does x have a length? Is > >>>> it a number? Maybe it's a fixed-length circular length, and the length > >>>> is non-zero even when it's empty? Who knows? How many cases do you need > >>>> to consider? > >>> Use case, please. I'm asking for code, not arguments. Please give me a > >>> piece of code where you can write "if x" that works but a simple > >>> explicit test won't. > >> I gave you a piece of code, actual code from one of my own projects. If > >> you wouldn't accept that evidence then, why would you accept it now? > > > I would accept as "evidence" something that satisfies my criteria, > > which your example did not: it could have easily (and more robustly) > > been written with a simple explicit test. I am looking for one that > > can't. > > > You keep bringing up this notion of "more complex with no benefit", > > which I'm simply not interested in talking about that at this time, > > and I won't respond to any of your points. I am seeking the answer to > > one question: whether "if x" can usefully do something a simple > > explicit test can't. Everyone already knows that "if x" requires > > fewer keystrokes and parses to fewer nodes. > > > Carl Banks > > -- > >http://mail.python.org/mailman/listinfo/python-list > > My use case involves a DAG of filters that pass data (of a variety of > types--filters just pass on data types they don't understand) between > them. I can also drop out of the filter chain at any point, using > critera determined by the filters. These criteria, you guessed it, are > bound to __nonzero__ in the filter and I determine whether or not to > continue through the graph using "if x". You can't code explicit tests > if you don't know what the tests even are beforehand. Also, I wanted to > support builtins (ints and lists in particular) because they can be > meaningful inputs to filters. Finally, as I add more filters and data > types, I don't want to go back and mess with the code that decides > whether or not to break out of the graph. Much like in Steven D'Aprano's example, still the only actual code snippet I've seen, it seems that this can easily be done with a simple explicit test by having all no-advance filters return None and testing with "if x is not None". So it doesn't pass my criterion of being not replaceable with simple explicit test. Maybe that's not workable for some reason. Perhaps if you'd post a code example that shows this, rather than just talking about it, you might be more persuasive. Carl Banks From deets at nospam.web.de Mon Jul 28 08:16:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 14:16:06 +0200 Subject: Module clarification References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> Message-ID: <6f5rm7F89muqU1@mid.uni-berlin.de> Hussein B wrote: > Hi. > I'm a Java guy and I'm playing around Python these days... > In Java, we organize our classes into packages and then jarring the > packages into JAR files. > What are modules in Python? > What is the equivalent of modules in Java? Read the docs: http://docs.python.org/tut/node8.html And read about eggs, the jars of python: http://peak.telecommunity.com/DevCenter/PythonEggs Diez From ptmcg at austin.rr.com Tue Jul 1 23:02:24 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 1 Jul 2008 20:02:24 -0700 (PDT) Subject: pyparsing problem References: Message-ID: On Jul 1, 8:02?am, name wrote: > Hi, > > I try to parse a file with pyparsing and get this output: > > ? ? ['generic', 'host-01', 'host alias xyz', '10.0.0.1'] > ? ? - alias: host alias xyz > ? ? - host_name: ['host-01'] > ? ? - ip_address: ['10.0.0.1'] > ? ? - use: ['generic'] > > ? ? > ? ? ? generic > ? ? ? host-01 > ? ? ? host alias xyz > ? ? ? 10.0.0.1 > ? ? > > ? ? ['generic', 'host-01', 'host alias xyz', '10.0.0.1'] > > ? ? finished > > What I don't understand is why I get the line > > ? ? generic > > and not > > ? ? generic > > as there is an associated name in the dump() output. > > Thank you very much in advance for any clue or help you could > provide. > > The code: > --------- > > #!/usr/bin/env python > > from pyparsing import * > > sample = """ > define host{ > ? use ? ? ? ? ? ? ? ? ? generic > ? host_name ? ? ? ? ? ? host-01 > ? alias ? ? ? ? ? ? ? ? host alias xyz > ? address ? ? ? ? ? ? ? ? ? ? ? 10.0.0.1} > > """ > > # define tokens > LBRACE,RBRACE = map(Suppress, '{}') > ipAddress = Combine(Word(nums) + ('.' + Word(nums))*3) > useTemplate = oneOf('generic user') > > # define grammar > > deviceName = Word(alphanums+'-') > hostDef = Literal('define').suppress() + Literal('host').suppress() > useLine = Suppress('use') + useTemplate + Suppress(SkipTo(lineEnd)) > host_nameLine = Suppress('host_name') + deviceName + Suppress(SkipTo > (lineEnd)) > aliasLine = Suppress('alias') + SkipTo(lineEnd) > aliasLine.setParseAction(lambda x: ' '.join(x[0].split())) > ip_addressLine = Suppress('address') + ipAddress > > use = useLine.setResultsName('use') > host_name = host_nameLine.setResultsName('host_name') > alias = aliasLine.setResultsName('alias') > ip_address = ip_addressLine.setResultsName('ip_address') > > host_stmt = (use + host_name + alias + ip_address) > host = hostDef + LBRACE + host_stmt ?+ RBRACE > > test_file = OneOrMore(host) + stringEnd > > # test > x = test_file.parseString(sample) > print x.dump() > print > print x.asXML('Hosts') > print > print x.asList() > print > > print 'finished' Try downloading the latest pyparsing.py file from the SourceForge SVN repository. This bug should be fixed in the latest version. -- Paul From ldo at geek-central.gen.new_zealand Thu Jul 24 06:01:23 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 24 Jul 2008 22:01:23 +1200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: In message <52404933-ce08-4dc1-a558-935bbbae779b at r35g2000prm.googlegroups.com>, Jordan wrote: > Except when it comes to Classes. I added some classes to code that had > previously just been functions, and you know what I did - or rather, > forgot to do? Put in the 'self'. In front of some of the variable > accesses, but more noticably, at the start of *every single method > argument list.* The reason is quite simple. Python is not truly an "object-oriented" language. It's sufficiently close to fool those accustomed to OO ways of doing things, but it doesn't force you to do things that way. You still have the choice. An implicit "self" would take away that choice. From sn.oo.py.9027 at gmail.com Mon Jul 14 04:18:51 2008 From: sn.oo.py.9027 at gmail.com (John Mechaniks) Date: Mon, 14 Jul 2008 01:18:51 -0700 (PDT) Subject: subprocess module Message-ID: <2e7f0504-cc1c-4cb6-b2d0-b67b004eca7d@x41g2000hsb.googlegroups.com> from subprocess import call call(['ls', '-l']) How do I get the result (not the exit status of the command) of "ls - l" into a variable? From comp.ogz at gmail.com Thu Jul 24 10:54:50 2008 From: comp.ogz at gmail.com (Oguz Yarimtepe) Date: Thu, 24 Jul 2008 17:54:50 +0300 Subject: pci card adjusting Message-ID: <20831c740807240754o407c7383h462e01fecb8364c0@mail.gmail.com> Hi all, I need to adjust the dimming property of my video card. There is currently a written application called nvclock but it is not supporting my card right now. So i need to implement the requiered register jobs on the card. This is already done to a degree in C. But i don't want to dive in to the C code right now. I prefer Python so may i implement such a feature by Python? Is there any library that i can use inside Python to get or set some register values of my pci card. Some memory stuff might be necessarry, i dont know yet how to implement the dim feature for my card. But till i observe the code, pmc smartdim offset, smartdim mask and shift amount is used for such a thing. These are vendor spesific values and lets imagine i have these values now. What is the next movement or any suggestions about this issue? -- O?uz Yar?mtepe www.loopbacking.info From bruno.desthuilliers at gmail.com Mon Jul 14 12:40:51 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 14 Jul 2008 09:40:51 -0700 (PDT) Subject: while var, but var ==16 != true References: <8c2cd9ff-bec2-4844-82a8-8ce02df5663e@w7g2000hsa.googlegroups.com> Message-ID: <689d495a-af00-4af6-86ce-b20861ef42f3@f36g2000hsa.googlegroups.com> On 14 juil, 07:32, Tim Roberts wrote: (snip) > Everything has a boolean value in > Python. 0, None, False, '' (empty string), [] (empty list), () (empty > tuple), and {} (empty dictionary) all have a False value. Everything else > has a True value. Unless the author of the class specified it otherwise (implementing the appropriate __magic_method__). From bronger at physik.rwth-aachen.de Thu Jul 17 08:26:44 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 17 Jul 2008 14:26:44 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> Message-ID: <87lk00d7cr.fsf@physik.rwth-aachen.de> Hall?chen! bruno.desthuilliers at gmail.com writes: > On 16 juil, 10:35, Stefan Scholl wrote: > >> Dave U. Random wrote: >> >>> http://snipr.com/PracticalDjango >> >> June 2008 is a bit too early. Django isn't ready. > > Oh, really ? Too bad. But, wait... If Django isn't ready, what's > that framework I've been using for almost three years now, then > ??? Before writing sarcastic comments, reading the thread would be really polite. As far as versioning is concerned, Django's policy is that "1.0" equals "API is frozen". And I consider publishing a book four months before the API is polished bad timing, too. Especially because Django is exquisitely documented on its webpage, so there is no urgent need for it. I thought about buying a Django book, too. I'm happy to have delayed it, for the same reason Stefan mentioned. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From ggpolo at gmail.com Wed Jul 30 18:48:47 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 30 Jul 2008 19:48:47 -0300 Subject: Tkinter- Possibly a basic question In-Reply-To: <59dee72b-3fb6-414b-ab49-33cab8f9c9e8@26g2000hsk.googlegroups.com> References: <59dee72b-3fb6-414b-ab49-33cab8f9c9e8@26g2000hsk.googlegroups.com> Message-ID: On Wed, Jul 30, 2008 at 6:33 PM, wrote: > I hate to do this, but I've thoroughly exhausted google search. Yes, > it's that pesky root window and I have tried withdraw to no avail. I'm > assuming this is because of the methods I'm using. I guess my question > is two-fold. > 1) How do I get rid of that window? You don't. > 2) Any comments in general? I am just learning python (and coding with > classes), so I'm sure there are things I should pound into my head > before I learn bad habits. > > Here's the code. It will eventually be a voltage measurement using an > Arduino board. Just a simple plot for now. > > import Tkinter, time > > ... > > if __name__ == "__main__": > root = Tkinter.Tk() > root.withdraw() > > #create main window > a = App(root) > a.title('Plot') > > #create a sample data range for testing > #data ranges from x=0, y=0 to x=10, y=5 > data = [] > for i in range(1000): > data.append( (float(i)/1000*10,float(i)/1000*5) ) > > a.plot_data(data) > > #loop until destroy > a.mainloop() > Before anything.. root withdraw works here but I wouldn't do it anyway. There are several solutions to this actually, I will list some, and none involve withdrawing the root window. The first thing you could do is change App to not inherit from Toplevel, instead change it to inherit object at max and pass the root object to it (to act as the parent for menu and other things). The drawback here is that you will have to change several lines, those that involve menu creation for example and this a.title and a.mainloop. The second option is to not create the root there, instead, make App inherit Tk. I rarely see people doing this, but it works too. Here you won't need to store the parent in an instance attribute, given it is always accessible through self.master since you are subclassing Tk. Another option is to make App subclass Frame instead of Toplevel, so you don't create an unecessary window. But if it is really a window, it doesn't make much sense to inherit Frame, so we are back at the first proposed solution. -- -- Guilherme H. Polo Goncalves From david.lyon at preisshare.net Tue Jul 15 09:38:42 2008 From: david.lyon at preisshare.net (David Lyon) Date: Tue, 15 Jul 2008 23:38:42 +1000 Subject: AW: Python embedding question. In-Reply-To: References: <487C8E1C.7050600@preisshare.net> Message-ID: <487CA862.2000400@preisshare.net> Troeger, Thomas (ext) wrote: > Thanks for your answer. The plattform is x86, so basically it's a PC > with a compact flash drive. The problem is that the compact flash is > rather limited in speed and size (there is other stuff on it too). > Oh ok. Well just keep in mind that 4GB of flash memory can be bought in China for about 5 euros. Since programming time is pretty expensive you need to do your sums about where you want to spend the time/money. >>> Or is there a method to have gzipped modules that are unzipped on >>> > the > >>> fly into memory when they're accessed? That would be even better. >>> >> Yes - also possible. >> > > That sounds promising, is there a link you can give? Or do I have to > modify the module loading code for this, i.e. the interpreter? http://squashfs.sourceforge.net/ > I think > that wouldn't be too much of a problem if I understand where Python > loads modules; I haven't checked the Python source yet for that one, and > searching for Python and zip or similar always yields tons of links that > use the Python zip or tar module :) > Python modules are byte compiled. You can usually cut out a lot/some of space by removing the source (.py) and leaving the compile (.pyc) modules. There is usually a lib or a sitelib directory. You could try cleaning that out of unwanted modules. My advice would be to simply buy higher capacity flash memory.... Regards David -------------- next part -------------- An HTML attachment was scrubbed... URL: From ivan at datasyncorp.com Wed Jul 2 16:39:48 2008 From: ivan at datasyncorp.com (Ivan Ven Osdel) Date: Wed, 2 Jul 2008 15:39:48 -0500 (CDT) Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: <4400a687-f424-45ba-93f5-e096913f52a9@s21g2000prm.googlegroups.com> Message-ID: <562513320.877251215031188320.JavaMail.root@saturn.datasyncintra.net> Not really, I have just worked with them more. ----- Original Message ----- From: "Ali Servet D?nmez" To: python-list at python.org Sent: Wednesday, July 2, 2008 1:15:04 PM GMT -06:00 US/Canada Central Subject: Re: Freesoftware for auto/intelligent code completing in Python On Jul 2, 7:55?pm, Ivan Ven Osdel wrote: > The free Python editors/IDEs really do need work as far as code completion goes but I am hopeful. > > IMO Stani's Python Editor comes closest by providing some code sense through a combination of history and doc strings for Python built-ins. Where it falls short is the ability to scan doc strings for your own code and non built-in modules in the Python path. Python already has the ground work in place to accomplish something similar to VS's XML commenting/intellisense system. With a Python interpretor you can type help(myModule) and get the doc string documentation. So I imagine implementing code sense for code being developed as well as non built-in modules would just be a matter of finding the appropriate module at the right time and piping the output of help([module]) to a popup window. > > If your willing to help work on something like that I suggest contacting Stani directlyhttp://pythonide.stani.be/or creating a plugin for Geanyhttp://geany.uvena.de/ > > Ivan Ven Osdel > Software Engineerhttp://www.datasyncsuite.com/ > > ----- Original Message ----- > From: "Ali Servet D?nmez" > To: python-l... at python.org > Sent: Wednesday, July 2, 2008 3:33:59 AM GMT -06:00 US/Canada Central > Subject: Re: Freesoftware for auto/intelligent code completing in Python > > On Jul 1, 12:15?am, Fuzzyman wrote: > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > I don't want to be so mean here, but how hard it could be be writing a > > > freesoftware which would automatically/intelligently auto complete > > > Python code? (I mean something that really does the job, like > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > name it, but just don't give me PyDev please...) > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > missing here? > > > > Could someone please point me out something that I'm really missing > > > which is already present in the wild, otherwise I'd like discuss with > > > whoever is willing to help me to get this thing done. I made my mind > > > and I could volunteer to make this happen as thesis project for my > > > incoming graduation in the next year. > > > > Regards you all, > > > Ali Servet D?nmez > > > Vim, Emacs, Wing, Komodo, ... more? > > > Yeah, I guess you're missing something. :-) > > > Michael Foordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > I've checkout Wing IDE's license and it doesnt' seem to be a > freesoftware; am I wrong? > > Ivan, thanks for your reply. I am curious how come you're suggesting me those two, but not others. Is there a good/particular reason for that? From motoom at xs4all.nl Thu Jul 10 16:13:53 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Thu, 10 Jul 2008 22:13:53 +0200 Subject: parsing incoming emails Message-ID: <2.2.32.20080710201353.01167514@pop.xs4all.nl> Ahmed wrote... > I am working on a project where I need to parse incoming emails > (Microsoft outlook) I'm not sure if you are able to bypass Outlook (and have Python fetch the mail itself using poplib), but if you are, the following code might be useful. I use this to pry apart emails which might contain multiple MIME parts. from email.Parser import Parser from rfc822 import parseaddr import poplib import smtplib popserver="pop.site.com" popuser="user at site.com" poppassword="secret" # split a message into an header- and body part def separate(msg): if isinstance(msg,str): msg=msg.split('\n') emptyline=msg.index('') return msg[:emptyline],msg[emptyline+1:] # return a certain headerline from the headers def headerline(header,tag="From: "): for h in header: if h.startswith(tag): return h[len(tag)+1:] return "" # enumerate recursively the contents of a MIME message # remember the first text/plain and text/html part(s) that is found # also remember if any other parts were found (like attachments) # def enummimeparts(msg,extract,level=1,verbose=False): m=Parser().parsestr(msg) if m.is_multipart(): if verbose: print '\t'*level,'multipart' for part in m.get_payload(): enummimeparts(part.as_string(),extract,level+1,verbose) else: t=m.get_content_type() if verbose: print '\t'*level,t if t=="text/plain": if not "text/plain" in extract: headers,body=separate(m.as_string()) extract["text/plain"]='\n'.join(body) else: extract["others"]=True elif t=="text/html": if not "text/html" in extract: headers,body=separate(m.as_string()) extract["text/html"]='\n'.join(body) else: extract["others"]=True else: extract["others"]=True # extract the first 'text/plain' and 'text/html' mime-parts from a message def extracttext(msg): extract={} enummimeparts(msg,extract) return extract.get("text/plain",None),extract.get("text/html",None),extract.get("ot hers",False) def processmessage(msgnr): # get a message from the POP server, extract the parts response,lines,bytes=pop.retr(msgnr) msg='\n'.join(lines) headers,body=separate(lines) name,fromaddress=parseaddr(headerline(headers,"From:")) subject=headerline(headers,"Subject:") logging.info(subject+" ("+fromaddress+")") (plain,html,others)=extracttext(msg) # prefer flat text; if not present in the message, fallback to HTML content (if any) texttoprocess="" if plain: texttoprocess=plain elif html: texttoprocess=html # now do something useful with the text processtext(texttoprocess) # delete message from pop server after processing pop.dele(msgnr) # connect to the pop server and process all messages logging.info("Checking pop server '%s', user '%s'" % (popserver,popuser)) pop=poplib.POP3(popserver) pop.user(popuser) pop.pass_(poppassword) stat=pop.stat() if stat[0]: for n in range(stat[0]): processmessage(n+1) pop.quit() -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From larry.bates at websafe.com` Wed Jul 16 22:27:50 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 16 Jul 2008 21:27:50 -0500 Subject: py2exe issues with pictures and icons In-Reply-To: References: Message-ID: Alexnb wrote: > Hello > > I am sure most of you are familiar with py2exe. I am having a bit of a > problem. See the program has a few pictures involved and the .ico it uses > for the windows. However, the pictures are stored in the same directory as > the source, something like: C:\Docs and settings\me\My docs\python\program. > When I run the program for the interpreter, just as a .py, everything works > just as it should. However, when I compile the main source as an .exe, and > say let a friend try the program. It fails because it is missing the .ico. > The catch, is I don't want to have it have to installed, at least at this > point, I want it to be able to just run. So how can I make it just run from > any computer with the files not being in the immediate directory. If that is > not possible, how can I put them in the immediate directory and still make > it work. Because that directory may change a lot so the path will change. > > Just a few questions. I hope someone out there can help me out! Windows can't read minds. The icon's/pictures have to either be in the same directory as the .exe or the .exe has to have a way to find them in another folder (e.g. via .ini config file). Takw a few minutes and go to: http://jrsoftware.org/isinfo.php It is a free Windows installer that I use to take py2exe, icons, pictures, .ini files, documentation, etc and wrap it all up into a nice, neat package that can be distributed as a single .exe. It will take a couple of hours, but it will be hours well spent (especially if you think you will do this more than once). Larry From kyosohma at gmail.com Sun Jul 13 19:30:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sun, 13 Jul 2008 16:30:25 -0700 (PDT) Subject: wxPython code giving strange errors. References: <01694ab5-7b5e-4e57-8b86-bf89b0beec82@m44g2000hsc.googlegroups.com> Message-ID: On Jul 13, 10:18?am, teh_sAbEr wrote: > I'm busy trying to learn wxPython, and i'm trying to run the following > piece of code (its from the wxPyWiki tutorial): > > import wx > > ID_ABOUT = 101 > ID_EXIT = 110 > > class MainWindow(wx.Frame): > ? ? def __init__(self,parent,id,title): > ? ? ? ? wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) > ? ? ? ? self.control = wx.TextCtrl(self,1,style=wx.TE_MULTILINE) > ? ? ? ? self.CreateStatusBar() > > ? ? ? ? filemenu = wx.Menu() > ? ? ? ? filemenu.Append(ID_ABOUT,"&About"," Information about this > program.") > ? ? ? ? filemenu.AppendSeparator() > ? ? ? ? filemenu.Append(ID_EXIT,"E&xit"," Terminate the program.") > > ? ? ? ? menuBar = wx.MenuBar() > ? ? ? ? menuBar.Append(filemenu,"&File") > ? ? ? ? self.SetMenuBar(menuBar) > ? ? ? ? self.Show(True) > > app = wx.PySimpleApp() > frame = MainWindow(None, -1, "Sample editor") > app.MainLoop() > > Simple enough, but every single time I try to run it IDLE gives me > this instead of the app I was hoping for: > > Traceback (most recent call last): > ? File "C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap > \Python Stuff\Batch Picture Converter\main.py", line 24, in > ? ? frame = MainWindow(None, -1, "Sample editor") > ? File "C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap > \Python Stuff\Batch Picture Converter\main.py", line 9, in __init__ > ? ? wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) > ? File "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx > \_windows.py", line 501, in __init__ > ? ? _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, > **kwargs)) > PyNoAppError: The wx.App object must be created first! > > As far as I can tell, the wx.App object IS being created first. I > suspect a race condition of some sort here, but can anyone shed some > light on this? This code works "as is" on Windows XP. However, I have gotten this error when trying to run it from IDLE and I've heard that that can happen in other Tkinter-based IDEs. Try running it from the command line and I'll bet you won't get that error. Also, there's a great wxPython user's group you can join from the official website: www.wxpython.org Mike From jadamwilson2 at gmail.com Tue Jul 22 22:06:50 2008 From: jadamwilson2 at gmail.com (jadamwil) Date: Tue, 22 Jul 2008 19:06:50 -0700 (PDT) Subject: fromfile error on windows, not mac References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> <9650a33b-40b5-46a7-a05e-5b059117891f@b1g2000hsg.googlegroups.com> <185cc290-18a5-4572-9fda-fa0bb785c831@z72g2000hsb.googlegroups.com> Message-ID: <8b6b03d3-089a-4157-b425-54040e8620c8@d1g2000hsg.googlegroups.com> On Jul 22, 8:35?am, jadamwil wrote: > On Jul 22, 2:05?am, Uwe Schmitt > wrote: > > > > > jadamwil schrieb: > > > > Hello, > > > I am using the numpy fromfile function to read binary data from a file > > > on disk. The problem is that the program runs fine on a Mac, but gives > > > an error or warning onwindowswhen trying to read the data. I use it > > > like this: > > > > Signal = zeros((N, 16), dtype=float32) > > > for sample in range(0, N): > > > ? # this function gets the next position in the file to seek to > > > ? s = getFilePos(sample) > > > > ? # go to the correct location in the file; this IS checked to make > > > sure it is within the file > > > ? mFile.seek(s) > > > > ? # read the 16 float32 values from the file > > > ? D = fromfile(mFile, dtype=numpy.float32, 16) > > > > ? # save D in Signal > > > ? Signal[sample, :] = D > > > > This will fail when sample is ~4. If I change the range to (5,N), > > > skipping the "bad" file location, it will run fine for a few samples, > > > and then give another error. The message it gives is: > > > "16 items requested but only 7 read" > > > > So D is a 7x1 vector, and the program dies when it tries to assign D > > > to the slice of Signal ("ValueError: shape mismatch: objects cannot be > > > broadcast to a single shape"). > > > > Onwindows, the Python version is 2.5.2, and the most recent numpy and > > > scipy are being used as well. I tried using Enthought, but it gave > > > this error as well, in addition to a c runtime error whenever I > > > imported scipy (which is another post topic...). > > > > Any ideas on what might be causing this? Is there a way to debug the > > > fromfile function? And, remember, this works perfectly on a Mac. Would > > > compiling everything (python, scipy, numpy) potentially solve this? > > > Did you open the file in binary mode ? > > > Greetings, Uwe > > Yes I did. Would that make a difference between a mac andwindows? > Thanks Uwe, Thanks for the suggestion. I passed "rb" to the open file command, not 'rb' which made a difference. I thought it opened in binary, but it did not, and it seems windows is not as good unix for dealing with this situation. Adam From rkmr.em at gmail.com Mon Jul 28 09:02:48 2008 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Mon, 28 Jul 2008 06:02:48 -0700 Subject: write unsigned integer 32 bits to socket In-Reply-To: <9_KdnfSDZ9xHIRDVnZ2dnUVZ_gCdnZ2d@pdx.net> References: <9_KdnfSDZ9xHIRDVnZ2dnUVZ_gCdnZ2d@pdx.net> Message-ID: On Mon, Jul 28, 2008 at 5:45 AM, Scott David Daniels wrote: > Alan Franzoni wrote: >> >> Michael Torrie was kind enough to say: >> >>> Of course any time you send coherent numbers over the network, I highly >>> recommend you use what's called network byte order.... I'm sure python >>> has some convention in the struct module for dealing with this. >> >> Not in the struct module; such functions are available in the socket >> module, and should be employed indeed. > > Please don't pass this misinformation along. > > In the struct module document, see the section on the initial character: > Character Byte order Size and alignment > @ native native > = native standard > < little-endian standard > > big-endian standard > ! network (= big-endian) standard > and notes @ is the default. >>>> print struct.pack('>>> print struct.pack('>lh', 3,4) >>>> print struct.pack('lh', 3,4) >>>> print struct.pack('!lh', 3,4) thanks for clarifying, and just to make sure, i am using '!' format from the struct package... i had this even in my previous email.... what am doing below is fine right? this is short >>> struct.pack('!h',3) '\x00\x03' this is integer >>> struct.pack('!i',3) '\x00\x00\x00\x03' this is long >>> struct.pack('!l',3) '\x00\x00\x00\x03' From marcus at internetnowasp.net Mon Jul 21 12:14:42 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Tue, 22 Jul 2008 00:14:42 +0800 Subject: Python Written in C? In-Reply-To: References: Message-ID: <4884B5F2.5020102@internetnowasp.net> Hi everyone, Yes, python is written in C. Maybe the original poster is looking for "ultimate" language and thus finds it uncomfortable that python should be written in C and not python itself. Actually it doesnt matter if IronPython is written in C# and Python in C. Each programming language is like a tool to the programmer and no, C is not outdate, its just a language with a much higher learning curve and its best left to do stuffs requiring drivers or optimized algorithms and other embedded stuffs that is usable by other languages. What do you think C# is written in? C# ? You see how flawed this logic is. Anyway, good luck on your search. But why look for "ultimate" language, when the core difference is the "programmmer" him/herself. In the hands of an skilled programmer, any language could accomplish much and then there is an issue with "time". I would cringe to do in C what i do in python nowadays, and i have like 14 years of C/C++ programming background. Someone wrote bittorrent in python and today its Utorrent written in C/C++ that is "cool", you see that doesnt mean that the next guy wrote write it in python would not beat the cool factor, its a matter of design, look, feel and ....its all about the programmer. Like they say in racing, its the driver not the car. From __peter__ at web.de Sat Jul 19 16:38:38 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 19 Jul 2008 22:38:38 +0200 Subject: create instance attributes for every method argument References: <4780837f-a5bc-4071-94d3-28e2f206163e@k30g2000hse.googlegroups.com> Message-ID: Berco Beute wrote: > I remember reading somewhere how to create an instance attribute for > every method argument, but although Google is my friend, I can't seem > to find it. This could likely be done way more elegant: > > ========================= > class Test(object): > > def __init__(self, a, b, c, d, e, f): > self.a = a > self.b = b > self.c = c > self.d = d > ========================= http://code.activestate.com/recipes/280381/ Personally, I prefer to spell it out like you did above. Peter From urizev at gmail.com Thu Jul 3 18:58:01 2008 From: urizev at gmail.com (Urizev) Date: Fri, 4 Jul 2008 00:58:01 +0200 Subject: Singleton implementation problems Message-ID: Hi everyone I have developed the singleton implementation. However I have found a strange behaviour when using from different files. The code is attached. Executing main new MySet object No singleton instance New singleton: <__main__.Singleton instance at 0x2b98be474a70> new MySet object There is a singlenton instance new Member new MySet object No singleton instance New singleton: new Member new MySet object There is a singlenton instance new Member new MySet object There is a singlenton instance I do not know why, but it creates two instances of the singleton. Does anybody know why? Regards -------------- next part -------------- A non-text attachment was scrubbed... Name: member.py Type: text/x-python Size: 175 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: myset.py Type: text/x-python Size: 1466 bytes Desc: not available URL: From ldo at geek-central.gen.new_zealand Thu Jul 17 01:31:37 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 17 Jul 2008 17:31:37 +1200 Subject: fork after creating temporary file using NamedTemporaryFile References: <0435315d-7b7d-4587-bc8c-000e3f2644a2@z72g2000hsb.googlegroups.com> Message-ID: In message , Sebastian "lunar" Wiesner wrote: > Relying on the destructor is *always* a bad idea, you should always > close files explicitly! There shouldn't be any problem with files opened read-only. From alexnbryan at gmail.com Thu Jul 17 01:38:05 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 22:38:05 -0700 (PDT) Subject: Need help getting BeautifulSoup contents Message-ID: <18501881.post@talk.nabble.com> The trick to this one is that the html looks something like this:
american, a href="/browse/blue" linkindex="12" set="yes">blue brick churn cottage cream " My question is I want everything inside, the contents of each ad the regular text of the . I know I can do like a.contents, but it only gives me the first one, in this case being "blue". I want the contents of each of those and the regular contents of the . P.S. notice the things inbetween the Message-ID: <74c92ee2-7b89-4579-b25a-a68262e2fee7@a70g2000hsh.googlegroups.com> On Jul 21, 10:17 am, "??" wrote: > Howdy, > > I'm confused about the motivation of releasing python2.6 and python3.0 > at the *same* time. IMO, 2.6 should be compatible with 2.5 while 3.0 > is new style python. Currenly, most python projects works fine in 2.5. > When 3.0 becomes final release, those projects will be gradually moved > to 3.0. But even without the intermediate version 2.6, project > transformation with be smooth enough, and then 2.5, 2.6 will be > replaced by 3.0. I will not spend any time on studying 2.6. So why > does python development team put many efforts on 2.6? What is the role > of 2.6? > > Best regards, > > -- > ShenLei 2.6 is meant to be a continuation of the 2.x line of Python, to support a gradual move of larger projects over to the Python 3.x series. The idea is that as Python 3.x will cause some major and minor changes to the basics of Python as we currently know it, trying to move everyone straight away will be problematic. Therefore the point is there will be a 2.7, 2.8 and so forth until there is almost no difference between the 2.x and 3.x at which time most users will have moved to the 3.x series and the 2.x can be discontinued. I will program larger projects in 2.5 for a while and then perhaps look to move it to 2.6 and 2.7, I won't touch the 3.x series until it is the common choice, much as a lot of people still program in 2.3/4. From binjured at gmail.com Tue Jul 1 09:50:49 2008 From: binjured at gmail.com (Tom Davis) Date: Tue, 1 Jul 2008 06:50:49 -0700 (PDT) Subject: Looping-related Memory Leak References: <94312edc-babb-4c1b-8db1-233404aa4a02@i76g2000hsf.googlegroups.com> <0abf2145-231c-4189-a8ca-b1f327a735dd@a1g2000hsb.googlegroups.com> <1e36866c-4a94-40b6-9780-81e104286862@d1g2000hsg.googlegroups.com> Message-ID: <186a7a16-2f3c-4e52-a280-c615cd320126@f63g2000hsf.googlegroups.com> On Jun 30, 8:24?pm, Carl Banks wrote: > On Jun 30, 1:55 pm, Tom Davis wrote: > > > > > On Jun 26, 5:38 am, Carl Banks wrote: > > > > On Jun 26, 5:19 am, Tom Davis wrote: > > > > > I am having a problem where a long-running function will cause a > > > > memory leak / balloon for reasons I cannot figure out. ?Essentially, I > > > > loop through a directory of pickled files, load them, and run some > > > > other functions on them. ?In every case, each function uses only local > > > > variables and I even made sure to use `del` on each variable at the > > > > end of the loop. ?However, as the loop progresses the amount of memory > > > > used steadily increases. > > > > Do you happen to be using a single Unpickler instance? ?If so, change > > > it to use a different instance each time. ?(If you just use the module- > > > level load function you are already using a different instance each > > > time.) > > > > Unpicklers hold a reference to everything they've seen, which prevents > > > objects it unpickles from being garbage collected until it is > > > collected itself. > > > > Carl Banks > > > Carl, > > > Yes, I was using the module-level unpickler. ?I changed it with little > > effect. ?I guess perhaps this is my misunderstanding of how GC works. > > For instance, if I have `a = Obj()` and run `a.some_method()` which > > generates a highly-nested local variable that cannot be easily garbage > > collected, it was my assumption that either (1) completing the method > > call or (2) deleting the object instance itself would automatically > > destroy any variables used by said method. ?This does not appear to be > > the case, however. ?Even when a variable/object's scope is destroyed, > > it would seem t hat variables/objects created within that scope cannot > > always be reclaimed, depending on their complexity. > > > To me, this seems illogical. ?I can understand that the GC is > > reluctant to reclaim objects that have many connections to other > > objects and so forth, but once those objects' scopes are gone, why > > doesn't it force a reclaim? > > Are your objects involved in circular references, and do you have any > objects with a __del__ method? ?Normally objects are reclaimed when > the reference count goes to zero, but if there are cycles then the > reference count never reaches zero, and they remain alive until the > generational garbage collector makes a pass to break the cycle. > However, the generational collector doesn't break cycles that involve > objects with a __del__method. There are some circular references, but these are produced by objects created by BeautifulSoup. I try to decompose all of them, but if there's one part of the code to blame it's almost certainly this. I have no objects with __del__ methods, at least none that I wrote. > Are you calling any C extensions that might be failing to decref an > object? ?There could be a memory leak. Perhaps. Yet another thing to look into. > Are you keeping a reference around somewhere. ?For example, appending > results to a list, and the result keeps a reference to all of your > unpickled data for some reason. No. > You know, we can throw out all these scenarios, but these suggestions > are just common pitfalls. ?If it doesn't look like one of these > things, you're going to have to do your own legwork to help isolate > what's causing the behavior. ?Then if needed you can come back to us > with more detailed information. > > Start with your original function, and slowly remove functionality > from it until the bad behavior goes away. ?That will give you a clue > what's causing it. I realize this and thank you folks for your patience. I thought perhaps there was something simple I was overlooking, but in this case it would seem that there are dozens of things outside of my direct control that could be causing this, most likely from third-party libraries I am using. I will continue to try to debug this on my own and see if I can figure anything out. Memory leaks and failing GC and so forth are all new concerns for me. Thanks Again, Tom From siona at chiark.greenend.org.uk Thu Jul 10 08:37:37 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 10 Jul 2008 13:37:37 +0100 (BST) Subject: User-defined exception: "global name 'TestRunError' is not defined" References: Message-ID: In article , wrote: >I'm using some legacy code that has a user-defined exception in it. > >The top level program includes this line > >from TestRunError import * > >It also imports several other modules. These other modules do not >explicitly import TestRunError. TestRunError is raised in various >places throughout the modules. The import line imports TestRunError into the "global" namespeace of the top level program module *only*. It is not magically propogated to the other modules imported -- if they want to use TestRunError themselves, they have to import it, otherwise this happens: >FATAL ERROR: global name 'TestRunError' is not defined >I realize this is kind of a silly question to ask in the general sense >without showing more of the code, but does anyone have any suggestions >as to the most likely causes of this error coming up? The cause is whoever wrote the legacy code not understanding how to program in Python. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From cokofreedom at gmail.com Thu Jul 10 02:53:05 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 9 Jul 2008 23:53:05 -0700 (PDT) Subject: You, spare time and SyntaxError References: Message-ID: <8731210e-34cf-4aa7-9a6e-66edce00d157@x35g2000hsb.googlegroups.com> > > just... great !-) > Thanks :) From larry.bates at websafe.com` Mon Jul 21 12:54:25 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 11:54:25 -0500 Subject: how to create GUI dynamically In-Reply-To: <84f144db-0d6c-44d5-a1ef-6e7778304c2a@r66g2000hsg.googlegroups.com> References: <84f144db-0d6c-44d5-a1ef-6e7778304c2a@r66g2000hsg.googlegroups.com> Message-ID: hitechpundir at gmail.com wrote: > Hi; > > i m working on a project where i need run time creation of GUI. > > i have some no. of entities for which i want checkboxes in front of > them which can be checked/ unchecked by user. > > But the problem is that the number and name of entities is not fixed > and it depends on the file which is used as input. > > So is there any way to tackle this problem. > > By the way ; i use Boa constructor (zope editor) for GUI now. > > regards > pawan pundir All the GUI tookits (Tkinter, wxWindows, QT) allow you to build the GUI dynamically. -Larry From bgeddy at home.havin.a.break Thu Jul 17 20:36:44 2008 From: bgeddy at home.havin.a.break (bgeddy) Date: Fri, 18 Jul 2008 01:36:44 +0100 Subject: storing references instead of copies in a dictionary In-Reply-To: References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: bgeddy wrote: > castironpi wrote: >> On Jul 17, 10:05 am, mk wrote: >>>> def f2(arg): >>>> return "f2 "+arg >>>> def f1(arg): >>>> return "f1 "+arg >>>> a={"1":"f1","2":"f2"} >>>> print [eval(x[1])(x[0]) for x in a.items()] >>>> def f2(arg): >>>> return "New f2 "+arg >>>> print [eval(x[1])(x[0]) for x in a.items()] >>> Neat trick, if probably dangerous in some circumstances. Anyway, thanks, >>> I didn't think of that. >>> >>>> Don't know if this is any use to you.. >>> At least I learned something. :-) >> >> You want consistent access to a changing variable. Wrap it in an >> object: >> >>>>> a= Blank( ) >>>>> a.ref= 'X' >>>>> a.ref >> 'X' >>>>> b= a >>>>> b.ref >> 'X' >>>>> a.ref= 'Y' >>>>> b.ref >> 'Y' >> > My "old fashioned" programing paradigms think of this in terms of > "pointers", a throw back to my schooling in 'C'. I find this general > form of problem to be common across languages and in some ways hard to > express in python. The whole idea of labels bound to objects is quite > alien to traditional terminology. I find one of the main attractions of > python is this new mindset that the language makes you adopt - a > different set of tools are at hand for the old school programmer. > > castironpi - please give an example of what you are thinking as I find > this interesting. preferably post some brief example code. castironpi - please forgive the double post but my newsreader didn't display your code correctly.. Doh !! Anyway - a nice way of addressing the problem. However the OP's post revolved around having a rewritable set of "labels" - which could be recorded at one time and when re referenced the new definitions of those labels would be used. For example a "collection" (list,dictionary,tuple) could be made of these "labels" and then the underlying code accessed by the labels changed. If the code was now ran indirectly by referencing the list then the new code would be ran. These building blocks are how parsers are built and the basis of language. I can see how you form two ways of addressing the variable but can't figure how this fits the original problem. Please elaborate for my ignorance. EdH. From fuzzyman at gmail.com Sat Jul 19 16:07:49 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sat, 19 Jul 2008 13:07:49 -0700 (PDT) Subject: win32api not found? References: Message-ID: On Jul 19, 8:45?pm, Michiel Overtoom wrote: > On Saturday 19 July 2008 21:13:04 Lamonte Harris wrote: > > > Where can I get the win32api module? I been searching all day on google and > > nothing, i installed > >https://sourceforge.net/project/showfiles.php?group_id=78018which requires > > win32api and its not found... > If you have successfully installed the pywin32 extensions then you *will* be able to import win32api. What happens if you start the Python interactive interpreter and enter 'import win32api' ? Michael Foord http://www.ironpythoninaction.com/ > What are the actions you do and the commands you give, and what is the precise > error you get? > > Greetings, > > -- > "The ability of the OSS process to collect and harness > the collective IQ of thousands of individuals across > the Internet is simply amazing." - Vinod Vallopillilhttp://www.catb.org/~esr/halloween/halloween4.html From littlesweetmelon at gmail.com Mon Jul 21 04:17:00 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Mon, 21 Jul 2008 16:17:00 +0800 Subject: What is the role of python2.6 and C++? Message-ID: Howdy, I'm confused about the motivation of releasing python2.6 and python3.0 at the *same* time. IMO, 2.6 should be compatible with 2.5 while 3.0 is new style python. Currenly, most python projects works fine in 2.5. When 3.0 becomes final release, those projects will be gradually moved to 3.0. But even without the intermediate version 2.6, project transformation with be smooth enough, and then 2.5, 2.6 will be replaced by 3.0. I will not spend any time on studying 2.6. So why does python development team put many efforts on 2.6? What is the role of 2.6? Another question is about the future of C++. I am a C++ programmer. Since I studied python, most of my projects becomes written in python because of the better and simpler OOP representation. As a supplement, I use python C extension for computational extensive jobs. Therefore, for a relatively long time, I do not use C++ any more... Anyone is same to me? What is your attitude to the role of C++ in the age of python? Best regards, -- ShenLei From circularfunc at gmail.com Sat Jul 12 12:20:58 2008 From: circularfunc at gmail.com (ssecorp) Date: Sat, 12 Jul 2008 09:20:58 -0700 (PDT) Subject: Why is this blowing the stack, thought it was tail-recursive... Message-ID: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> def fib(n): def fibt(a, b, n): if n <= 1: return b else: return fibt(b, a + b, n - 1) if n == 0: return 0 else: return fibt(0, 1, n); and can memoization speed up this even more? tesintg with memoization doesnt really say anything because it is so fast it is instant anyway. (the classic easy-redable exponential fib-function can obv be helped enormously with memoization though.) From p0q0b0d at gmail.com Wed Jul 9 02:37:20 2008 From: p0q0b0d at gmail.com (|e0) Date: Wed, 9 Jul 2008 08:37:20 +0200 Subject: Newbie question Message-ID: <3b1e6f480807082337l419fd40ax91eaf13e0701c5b3@mail.gmail.com> Hi list, i'm running Ubuntu Hardy Desktop and i've installed Tim Golden WMI. However importing wmi module i have this error: >>> import wmi Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/site-packages/wmi.py", line 141, in from win32com.client import GetObject, Dispatch ImportError: cannot import name GetObject I can import win32com.client without problems. Do i need to install any extra package? On win i suppose i need win32 extensions, but on linux? Thank you! -- Regards, Leonardo From randall at tnr.cc Sat Jul 26 20:58:38 2008 From: randall at tnr.cc (Randall Smith) Date: Sat, 26 Jul 2008 19:58:38 -0500 Subject: bundling python with application Message-ID: I'd like to bundle Python with my app, which will be targeted at Linux, Windows and Mac. Discussions I've found about this tend to lead to py2exe, freeze, etc, but I'd like to do something rather simple and am seeking advice. What I'd like to do is just copy the standard libraries and executable(s) and adjust the paths in the environment variables. The libraries and executable(s) would reside in the same directory with the application so that you could run the application without needing to install it. The directory might look like this: $ ls start-app.sh app_lib/ python_lib/ python_bin/ start-app.sh would look like this: #!/bin/sh PATH="python_bin:$PATH" PYTHON_HOME="./python_lib" python app_lib/start.py Of course, there would be a start-app.bat for Windows. The PATH is altered to make sure the right python interpreter is found and PYTHON_HOME makes sure the right (local) libraries are found. Can this be done? Randall From benjamin.kaplan at case.edu Tue Jul 15 16:39:31 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 15 Jul 2008 16:39:31 -0400 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: On Tue, Jul 15, 2008 at 4:10 PM, wrote: > I need to know if I'm running on 32bit or 64bit ... so far I haven't > come up with how to get this info via python. sys.platform returns > what python was built on ... but not what the current system is. > > I thought platform.uname() or just platform.processor() would have > done it, but python returns an empty string on windows. Any ideas? > > Thanks, Ken > -- platform.architecture() should have it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sat Jul 26 18:58:16 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 26 Jul 2008 15:58:16 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> Message-ID: <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> On Jul 26, 5:07?pm, Terry Reedy wrote: > Whether or not one should write 'if x' or 'if x != 0' [typo corrected] > depends on whether one means the general 'if x is any non-null object > for which bool(x) == True' or the specific 'if x is anything other than > numeric zero'. ?The two are not equivalent. ?Ditto for the length example. Can you think of any use cases for the former? And I mean something where it can't be boiled down to a simple explicit test for the sorts of arguments you're expecting; something that really takes advantage of the "all objects are either true or false" paradigm. The best thing I can come up with out of my mind is cases where you want to check for zero or an empty sequence, and you want to accept None as an alternative negative as well. But that's pretty weak. The use case of simply passing something to a function that accepts any boolean doesn't count. For instance, I could write: def nand(a,b): return not (a and b) And then I could use it like this, even if x is an interger and y a string: if nand(x,y): But that doesn't buy much since I could just pass in the explicit tests like this: if nand(x!=0,y!=""): Carl Banks From desothier at yahoo.com Fri Jul 18 08:33:57 2008 From: desothier at yahoo.com (antar2) Date: Fri, 18 Jul 2008 05:33:57 -0700 (PDT) Subject: substitution of list elements Message-ID: <247ab26d-ba98-42cc-bf6e-738b4b32a70c@q28g2000prh.googlegroups.com> I want to replace each first element in list 5 that is equal to the first element of the list of lists4 by the fourth element. I wrote following code that does not work: list4 = [['1', 'a', 'b', 'c'], ['2', 'd', 't', 'e'], ['8', 'g', 'q', 'f']] list5 = ['1', '2', '3'] for j in list4: for k in list5: if j[0] == k: k = j[3] print list5 Wanted result: ['c', 'e', '3'] thanks! From larry.bates at websafe.com` Sun Jul 13 21:55:49 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 13 Jul 2008 20:55:49 -0500 Subject: How to package a logging.config file? In-Reply-To: References: Message-ID: Matthew Wilson wrote: > I'm working on a package that uses the standard library logging module > along with a .cfg file. > > In my code, I use > logging.config.fileConfig('/home/matt/mypackage/matt.cfg') to load in > the logging config file. > > However, it seems really obvious to me that this won't work when I share > this package with others. > > I can't figure out what path to use when I load my .cfg file. > > Any ideas? > > Matt Normally you put the logging configuration file in the path where you put the program that you will be sharing (quite often with no path at all). -Larry From david.lyon at preisshare.net Sat Jul 19 06:02:55 2008 From: david.lyon at preisshare.net (David Lyon) Date: Sat, 19 Jul 2008 20:02:55 +1000 Subject: Rotating a cube In-Reply-To: <8156f68a-3f65-4fca-a725-2e0c4240abd1@v21g2000pro.googlegroups.com> References: <3d47df08-9734-4e0f-96ad-37da445b4faf@34g2000hsh.googlegroups.com> <8156f68a-3f65-4fca-a725-2e0c4240abd1@v21g2000pro.googlegroups.com> Message-ID: <4881BBCF.2060905@preisshare.net> Lie wrote: > On Jul 17, 3:11 pm, J-Burns wrote: > >> On Jul 17, 12:53 pm, Fredrik Lundh wrote: >> >> >>> J-Burns wrote: >>> >>>> Is there a built in Python function for this? >>>> >>> for answering questions that have nothing to do with programming, and >>> looks quite a bit like homework? don't think they've added that one yet. >>> >>> maybe you should look for a geometry newsgroup/forum? >>> >>> >>> >> I meant to ask how would you do this in Python... :S >> > > The same as you do it in any other languages. This question is marked > correctly as having no relationship to python whatsoever. You'd get a > better answer if you asked in mathematics/geometry group, many > mathematician are adept programmer as well. > - But is the question about display graphics ? ie rotating a cube using a python framework ? With something like python and OpenGL ? or Python and PovRay... or perphaps python and imagemagick ? If so... i would have thought he should be able to ask that question here.... David -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Sat Jul 26 22:38:26 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 27 Jul 2008 02:38:26 GMT Subject: pixel colour on screen References: <22940391-cf14-4022-8b00-8d7974590072@e39g2000hsf.googlegroups.com> Message-ID: <6pnn84t2uvmg5akolipt493773oddv1a3u@4ax.com> chris wrote: >On Jun 30, 4:37?am, Tim Roberts wrote: >> cjstut... at hotmail.com wrote: >> >> >Could anyone help me, I'm a python noob and need some help. im trying >> >to find some code that will, given ascreenco-ordinate, will give me >> >thecolourof thatpixelin RGB. i have found a lot about getting the >> >pixelcolourfrom a picture file with a given co-ordinate, but is it >> >possible to do it from the wholescreenoutput regardless what >> >application the selectedpixelis in? >> >> Which operating system? ?If you are on Windows, and you have pywin32 >> loaded. you can use the Windows APIs GetDC and GetPixel. > >i have ubuntu hardy. does that help? Then you will have to use a GUI library of some kind: wx, or Qt, or tkinter. The answer depends on which GUI library you decide to use. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From python at rcn.com Mon Jul 21 18:20:39 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 21 Jul 2008 15:20:39 -0700 (PDT) Subject: persistent deque (continued) References: <4c985e86-c0c4-4cb3-b7ce-f8e105b7f85d@y21g2000hsf.googlegroups.com> Message-ID: <4126ceeb-128e-4aa1-af95-31648d42eade@i24g2000prf.googlegroups.com> On Jul 21, 12:08?pm, castironpi wrote: > Some time ago, I was asking about the feasibility of a persistent > deque, a double-ended queue. > > It runs into the typical space allocation problems. ? Try starting with a dict-based implementation of a double-ended queue ( http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259179 ) and then replace the dict with a shelf. Presto, you've got a persistent deque. Raymond From asd at pittle.org Wed Jul 2 04:33:59 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Wed, 2 Jul 2008 01:33:59 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> Message-ID: <9ad840e1-e12f-4125-8537-4bad2ef77f51@w5g2000prd.googlegroups.com> On Jul 1, 12:15?am, Fuzzyman wrote: > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > > I don't want to be so mean here, but how hard it could be be writing a > > freesoftware which would automatically/intelligently auto complete > > Python code? (I mean something that really does the job, like > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > name it, but just don't give me PyDev please...) > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > even a brand new huge all-fancy IDE, I don't care, but what am I > > missing here? > > > Could someone please point me out something that I'm really missing > > which is already present in the wild, otherwise I'd like discuss with > > whoever is willing to help me to get this thing done. I made my mind > > and I could volunteer to make this happen as thesis project for my > > incoming graduation in the next year. > > > Regards you all, > > Ali Servet D?nmez > > Vim, Emacs, Wing, Komodo, ... more? > > Yeah, I guess you're missing something. :-) > > Michael Foordhttp://www.ironpythoninaction.com/http://www.trypython.org/ I've checkout Wing IDE's license and it doesnt' seem to be a freesoftware; am I wrong? From eddie at holyrood.ed.ac.uk Fri Jul 18 06:46:53 2008 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 18 Jul 2008 10:46:53 +0000 (UTC) Subject: trying to match a string References: Message-ID: arnimavidyarthy at gmail.com writes: >Hi, >Hi, >I am taking a string as an input from the user and it should only >contain the chars:L , M or R >I tried the folllowing in kodos but they are still not perfect: >[^A-K,^N-Q,^S-Z,^0-9] >[L][M][R] >[LRM]?L?[LRM]? etc but they do not exactly meet what I need. >For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. >regards, >SZ >The string may or may not have all the three chars. >>> var = 'LRLRLRNL' >>> residue = var.replace('L','').replace('R','').replace('M','') >>> if residue != '': ... print 'Invalid characters in input',residue ... Invalid characters in input N From wesbrooks at gmail.com Tue Jul 1 11:38:23 2008 From: wesbrooks at gmail.com (Wesley Brooks) Date: Tue, 1 Jul 2008 16:38:23 +0100 Subject: Error from zipfile Message-ID: Dear Users, I'm having a problem when trying to move script from Linux to Windows. A zipfile opperation is failing with the message: "BadZipFile: File is not a zip file" I have a simple scripts that reads a zip file in the same way as any other file into a string, then sends it across to a network where it is saved as perusual into a file, then read in and processed by zipfile. I've tried adding the flag to allow 64 bit and even using uncompressed zip files. Niether fixes the problem. The zip file and contents were created on linux. To be certain that was not the issue I have emptied the zip file, created a new one, opend all the files in wordpad and saved them, then put the contents into the new file. Still no joy. Any help would be greatly appreciated. On linux I'm running python 2.5 and on windows it is 2.4. Thanks, Wesley Brooks. From rw at smsnet.pl Tue Jul 8 16:01:07 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Tue, 08 Jul 2008 22:01:07 +0200 Subject: Logging to zero or more destinations References: Message-ID: <87r6a4du2k.fsf@merkury.smsnet.pl> samwyse writes: > In the Python 2.5 Library Reference, section 14.5.3 (Logging to > multiple destinations), an example is given of logging to both a file > and the console. This is done by using logging.basicConfig() to > configure a log file, and then calling > logging.getLogger('').addHandler(console) to add the console. > > However, in section 14.5.4 (Sending and receiving logging events > across a network), a call is made to > rootLogger.addHandler(socketHandler), and later it is stated that "On > the client side, nothing is printed on the console". > > Finally, back in section 14.5.2 (Basic example), it's stated that "by > default, the root logger is configured to only handle messages with a > severity of WARNING or above. The message format is also a > configuration default, as is the output destination of the messages - > sys.stderr." > > The only way that I can see for all three statements to be consistent > is that the root logger starts with an empty list of handlers, and > doesn't instantiate a default handler until either > logging.basicConfig() is called, That is correct. > or the first time that a message is > logged. That is not correct. The list of handlers is empty until `basicConfig` or explicit `addHandler` is called. > This would also seem to imply that there's no way to use an > empty handler list (say, if you want to suppress all logging), because > the root handler will instantiate a handler for you. Is this correct? No. Consider this: >>> import logging >>> logging.root.warning('error message') No handlers could be found for logger "root" >>> logging.root.warning('error message') Note only one warning message. > P.S. I tried researching this further by myself, but the logging > module doesn't come with source (apparently it's written in C?) and I > don't have the time to find and download the source to my laptop. Hmmm... that's strange. It is a pure Python package. $ ls /usr/lib/python2.5/logging/ config.py config.pyc handlers.py handlers.pyc __init__.py __init__.pyc HTH, Rob From tjreedy at udel.edu Thu Jul 31 23:42:00 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 31 Jul 2008 23:42:00 -0400 Subject: Decoding an attachment In-Reply-To: References: Message-ID: robinsiebler at gmail.com wrote: > I figured out how to save an e-mail message as a text file, but I'm > not sure how to decode the encoded part as I am not sure how much I > need to include to decode it properly. Here is what a message looks > like: The email.parser and email.message modules will do this for you. But understanding the parts will help you use them properly. I am 99% sure of the following comments. > > > Received: from INGESTOR2SQA ([10.220.83.198]) by sqaserver300 with > Microsoft SMTPSVC(6.0.3790.0); > Thu, 31 Jul 2008 12:10:26 -0700 > mime-version: 1.0 > from: "AVDN Ingestor" > to: sqatest at ictvsys.pvt > date: 31 Jul 2008 17:53:40 +0000 > subject: Upload Status for test > content-type: multipart/mixed; This says multiple mime parts of mixed types boundary=--boundary_2_09ab8836- > ff06-41a6-94d6-59258539bf88 This is the boundary between parts > Return-Path: sqatest at ictvsys.pvt > Message-ID: > X-OriginalArrivalTime: 31 Jul 2008 19:10:26.0125 (UTC) > FILETIME=[16D08FD0:01C8F341] > > blank lines separate header from body > ----boundary_2_09ab8836-ff06-41a6-94d6-59258539bf88 This is the boundary specified above, with '--' prepended > content-type: text/plain; charset=us-ascii > content-transfer-encoding: quoted-printable This is header of first part > Blank separates part header from part boundary > For additional information, please see attachment. This is first (and last) list of first, plain text part > ----boundary_2_09ab8836-ff06-41a6-94d6-59258539bf88 This is boundary ending first part and starting second part > content-type: text/xml; name=status.xml; charset=utf-8 > content-transfer-encoding: base64 > content-disposition: attachment This is 2nd part header, specifying base64 coding, which is one of the two that email.message knows about. > Blank separating header and payload > PGF2ZG5fcG5tIHZlcnNpb249IjEuMSIgc2VuZGVyPSJhdmRud2VzdGRjMSIgZG9jbnVtYmVy > PSJvaHV0bHBxeXptM25xd3lrYm9wd3pwdTUiIHN0YXR1cz0ic3VjY2Vzc2Z1bCI+PGNvbnRh > Y3QgcGhvbmU9IjQwOC05MzEtOTIzMiIgZW1haWw9Im0uY2hhbkBhdm5ldHdvcmtzLmNvbSIg > Lz48YXNzZXRzdGF0ZSBwcm92aWRlcmlkPSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJjZjcw > NDcwNWFjIiBmaWxlbmFtZT0iXHZpZGVvXGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2NfYWMz > XzAxLmpwZyIgbm90aWZpY2F0aW9uPSIxMjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJpZD0i > U1FBIiBhc3NldGlkPSJhY2YxZTNkNmViY2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRlb1xm > b29cYm91Z2UwMDMuMzIwXzI0MF9udHNjX2FjM18wMy5qcGciIG5vdGlmaWNhdGlvbj0iMTIw > IiAvPjxhc3NldHN0YXRlIHByb3ZpZGVyaWQ9IlNRQSIgYXNzZXRpZD0iYWNmMWUzZDZlYmNm > NzA0NzA1YWMiIGZpbGVuYW1lPSJcdmlkZW9cZm9vXGJvdWdlMDAzLjMyMF8yNDBfbnRzY19h > YzNfMDQuanBnIiBub3RpZmljYXRpb249IjEyMCIgLz48YXNzZXRzdGF0ZSBwcm92aWRlcmlk > PSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJjZjcwNDcwNWFjIiBmaWxlbmFtZT0iXHZpZGVv > XGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2NfYWMzXzAyLmpwZyIgbm90aWZpY2F0aW9uPSIx > MjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJpZD0iU1FBIiBhc3NldGlkPSJhY2YxZTNkNmVi > Y2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRlb1xmb29cYm91Z2UwMDMuMzIwXzI0MF9udHNj > X2FjMy5qcGciIG5vdGlmaWNhdGlvbj0iMTIwIiAvPjxhc3NldHN0YXRlIHByb3ZpZGVyaWQ9 > IlNRQSIgYXNzZXRpZD0iYWNmMWUzZDZlYmNmNzA0NzA1YWMiIGZpbGVuYW1lPSJcdmlkZW9c > Zm9vXGJvdWdlMDAzLjMyMF8yNDBfbnRzY19hYzNfMDguanBnIiBub3RpZmljYXRpb249IjEy > MCIgLz48YXNzZXRzdGF0ZSBwcm92aWRlcmlkPSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJj > ZjcwNDcwNWFjIiBmaWxlbmFtZT0iXHZpZGVvXGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2Nf > YWMzXzA3LmpwZyIgbm90aWZpY2F0aW9uPSIxMjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJp > ZD0iU1FBIiBhc3NldGlkPSJhY2YxZTNkNmViY2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRl > b1xmb29cYm91Z2UwMDMuMzIwXzI0MF9udHNjX2FjM18wNi5qcGciIG5vdGlmaWNhdGlvbj0i > MTIwIiAvPjxhc3NldHN0YXRlIHByb3ZpZGVyaWQ9IlNRQSIgYXNzZXRpZD0iYWNmMWUzZDZl > YmNmNzA0NzA1YWMiIGZpbGVuYW1lPSJcdmlkZW9cZm9vXGJvdWdlMDAzLjMyMF8yNDBfbnRz > Y19hYzNfMDUuanBnIiBub3RpZmljYXRpb249IjEyMCIgLz48YXNzZXRzdGF0ZSBwcm92aWRl > cmlkPSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJjZjcwNDcwNWFjIiBmaWxlbmFtZT0iXHZp > ZGVvXGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2NfYWMzXzA5LmpwZyIgbm90aWZpY2F0aW9u > PSIxMjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJpZD0iU1FBIiBhc3NldGlkPSJhY2YxZTNk > NmViY2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRlb1xmb29cYm91Z2UwMDMuMzIwXzI0MF9u > dHNjX2FjMy50cyIgbm90aWZpY2F0aW9uPSIxMjAiIC8+PC9hdmRuX3BubT4= end of payload, lines in between go to base64 module > ----boundary_2_09ab8836-ff06-41a6-94d6-59258539bf88-- End of part 2 and mime body #I believe s = message_as_string m = email.parser.message_from_string(s) # email.message.Message object p = m.get_payload(1,True) # should give you the 2nd part as a message with the body base64-decoded q = p.get_payload() # utf-8 encoded xml string # I recommend trying out other Message methods # In particular, you want to be able to retrieve the subfields of content_type and I don't know exactly how. Terry Jan Reedy From ndbecker2 at gmail.com Fri Jul 11 15:24:13 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 11 Jul 2008 15:24:13 -0400 Subject: decorator to prevent adding attributes to class? References: <98c6e83e-4a54-49ce-a32e-f03f5ab97f28@k13g2000hse.googlegroups.com> <48778CA2.2000402@jouy.inra.fr> Message-ID: Robert Bossy wrote: > class Foo(Freezeable): > def __init__(self): > self.bar = 42 > self.freeze() # ok, we set all variables, no more from here > > > x = Foo() > print x.bar > x.bar = -42 > print x.bar > x.baz = "OMG! A typo!" > Pretty nice, but unfortunately the subclass has to remember to call freeze in it's init. Too bad that can't be automated. From r_e_s_01 at ZZZyahoo.com Thu Jul 10 20:46:00 2008 From: r_e_s_01 at ZZZyahoo.com (r.e.s.) Date: Thu, 10 Jul 2008 17:46:00 -0700 Subject: Can this program be shortened? Measuring program-length? References: <7Rtdk.16747$N87.3559@nlpi068.nbdc.sbc.com> <2ed6de5b-bf2f-4e3d-94af-c8e6c6a28f95@s50g2000hsb.googlegroups.com> Message-ID: wrote ... > "r.e.s." wrote: >> Can the following program be shortened? ... >> >> def h(n,m): >> E=n, >> while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n >> return n >> h(9,9) >> > > Some ideas... > > # h is your version > def h(n,m): > E=n, > while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n > return n > > def g(n,m): > E=n, > while E*m:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n > return n > > def f(n,m): > E=n, > while E*m:n=h(n+1,m-1);E=(E[0]>0)*(E[0]-1,)*n+E[1:] > return n > > def e(n,m): > E=[n] > while E*m:n=h(n+1,m-1);E[:1]=(E[0]>0)*[E[0]-1]*n > return n > > # some tests > print h(1,1), h(2,1), h(0,2) > print g(1,1), g(2,1), g(0,2) > print f(1,1), f(2,1), f(0,2) > print e(1,1), e(2,1), e(0,2) Very instructive! Thank you for the "step-by-step". From martin at v.loewis.de Wed Jul 23 13:08:55 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 23 Jul 2008 19:08:55 +0200 Subject: interpreter vs. compiled In-Reply-To: References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> Message-ID: <488765A7.7030400@v.loewis.de> >> Oh. How is the stack represented? > > As usual, as successive locations in memory. > I have the impression that CPython uses the same stack C does. Actually, it doesn't (at least not for the evaluation stack). In CPython, when a Python function starts, the maximum depth of the evaluation stack is known, but it depends on the specific function (of course). So Python needs to allocate an array for the evaluation stack with known size, but can't do so on the C stack (at least not portably), since you can't allocate dynamically-sized array as a local variable in C. So instead, pymalloc is used to allocate the evaluation stack, and it is part of the frame object (so the entire frame object is allocated in one chunk, and then split up into local variables and evaluation stack. > While conceptually, CPython may put objects on the stack, I am pretty > sure it actually stacks references (C pointers) to objects in heap memory. Correct. >> Does it keep track of which stack >> positions (TOS, TOS1, etc.) are in what registers? > > I am sure they are not in registers, just normal memory. Correct. As discussed above, they are located on the heap (making Python's frame stack a spaghetti stack). Regards, Martin From mnordhoff at mattnordhoff.com Fri Jul 25 20:52:19 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sat, 26 Jul 2008 00:52:19 +0000 Subject: SimpleJson is slow .... is there any C Compiled version ? In-Reply-To: References: Message-ID: <488A7543.2090205@mattnordhoff.com> sanket wrote: > Hello All, > > I have created an API which fetches some data from the database. > I am using simplejson to encode it and return it back. > > Now the problem is that, this API is being called for millions of > times in a sequence. > I ran a profiler and saw that most of the time is consumed in encoding > my database results in to json. > So I was just wondering is there any C compiled version of simplejson > is available? > or any help regarding this issue would be appreciated. > > Thank you, > Sanket simplejson is not the only JSON library out there. For example, there's python-cjson, which is written entirely in C: There's also an enhanced version of it: I think simplejson has some small, optional C bits that will improve performance if you compile them. Also, be aware that I think simplejson is being integrated into the stdlib in Python 2.6. Also, simplejson and python-cjson might not be entirely compatible: there's one character that one escapes and the other doesn't, or something. -- From magnus.lycka at gmail.com Wed Jul 23 14:07:57 2008 From: magnus.lycka at gmail.com (magnus.lycka at gmail.com) Date: Wed, 23 Jul 2008 11:07:57 -0700 (PDT) Subject: Segv in mmap.move() Message-ID: Does anyone recognize this little Python crasher? I'll file a bug report unless someone notices it as an already documented bug. I found some open mmap bugs, but it wasn't obvious to me that this problem was one of those... Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import mmap >>> data = mmap.mmap(-1, 1) >>> data.move(1,1,-1) Segmenteringsfel (core dumped) I first noticed the problem under Windows in 2.5.1. From ojeeves at gmail.com Wed Jul 2 10:01:16 2008 From: ojeeves at gmail.com (oj) Date: Wed, 2 Jul 2008 07:01:16 -0700 (PDT) Subject: simple UnZip References: <5b915a0e-a227-460f-8273-ecc01b800884@2g2000hsn.googlegroups.com> Message-ID: On Jul 2, 2:39?pm, noydb wrote: > Can someone help me with this script, which I found posted elsewhere? > I'm trying to figure out what is going on here so that I can alter it > for my needs, but the lack of descriptive names is making it > difficult. ?And, the script doesn't quite do anything worthwhile -- it > unzips one file from a zipfile, not all files in a zipfile. > > *** > import zipfile, os, sys, glob > > os.chdir("C:\\Temp") > zips = glob.glob('*.zip') > > for fzip in zips: > ? ? if zipfile.is_zipfile(fzip): > ? ? ? ? print fzip," is a zip" > ? ? ? ? z = zipfile.ZipFile(fzip,'r') > ? ? ? ? lstName = z.namelist() > ? ? ? ? sHgt = lstName[0] > ? ? ? ? print "Unpacking",sHgt > ? ? ? ? hgt = z.read(sHgt) > ? ? ? ? fHgt = open(sHgt,'wb') > ? ? ? ? fHgt.write(hgt) > ? ? ? ? # fHgt.flush > ? ? ? ? fHgt.close > print "Finished" > *** > > I changed it somewhat to > &&& > import zipfile, os, sys > > event_zip = ("C:\\Temp\\data4event.zip") > > z = zipfile.ZipFile(event_zip, 'r') > > zList = z.namelist() > > for zItem in zList: > ? ? print "Unpacking",zItem > ? ? zRead = z.read(zItem) > ? ? z1File = open(zItem,'wb') > ? ? z1File.write(zRead) > ? ? z1File.close > print "Finished" > &&& > > This works, but I want to be able to specify a different output > location. > > The scenario is that the zip file will always be the same (gets copied > over daily), but it needs to be unzipped to a specific different > directory. > > Can anyone help? > > Thanks! Firstly, I'd recommend just reading the documentation for the zipfile module, it's fairly straight forwards. To write the files to a different location, just change this line: z1File = open(zItem,'wb') This is where you're opening a file to write to. Try something like: z1File = open( os.path.join(output_dir, zItem), 'wb') to write the files into the path specified in output_dir. You don't even have to save the files with the same names they have in the zipfile; you don't have to save the files at all. In one project I'm working on, I just read files from a zip file into memory and process them there. From fred.sells at adventistcare.org Tue Jul 15 12:50:24 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Tue, 15 Jul 2008 12:50:24 -0400 Subject: need ldap windows binary and/or installation help In-Reply-To: <487B361D.1070503@timgolden.me.uk> Message-ID: <0A53725C4A497848A7B3A0874B259831011B09A1@acesxch01.ADVENTISTCORP.NET> I'm running python 2.5 (or 2.4) in an XP environment. I downloaded and installed the .dll's from OpenLDAP-2.4.8+OpenSSL-0.9.8g-Win32.zip and copied the .dll's in c:/windows/system32 as instructed now I get this error. Is there anyway to avoid building the python_ldap binaries? Apart from being lazy, I've got a secure system policy issue if I start compiling apps. I could give up and just start running in linux, but my xp environment is much friendlier to develop in. I've googled a lot, but all the links I've found talk to Unix or to compiling from source. Even if I build from source, will the mingw compiler mentioned in most posts produce something that is compatible with "Python was built with Visual Studio 2003". c:\all>easy_install python_ldap Searching for python-ldap Reading http://pypi.python.org/simple/python_ldap/ Reading http://pypi.python.org/simple/python-ldap/ Reading http://python-ldap.sourceforge.net/ Reading http://python-ldap.sourceforge.net/download.shtml Reading http://sourceforge.net/project/showfiles.php?group_id=2072&package_id=2011 Best match: python-ldap 2.3.5 Downloading http://downloads.sourceforge.net/python-ldap/python-ldap-2.3.5.tar.gz?modtime=1215364319&big_mirror=0 Processing python-ldap-2.3.5.tar.gz Running python-ldap-2.3.5\setup.py -q bdist_egg --dist-dir c:\documents and settings\frsells\local settings\temp\easy_install-uczq5i\python-ld extra_compile_args: extra_objects: include_dirs: /usr/local/openldap-2.3/include /usr/include/sasl library_dirs: /usr/local/openldap-2.3/lib libs: ldap_r lber sasl2 ssl crypto file Lib\ldap.py (for module ldap) not found file Lib\ldap\schema.py (for module ldap.schema) not found warning: no files found matching 'Makefile' warning: no files found matching 'Modules\LICENSE' file Lib\ldap.py (for module ldap) not found file Lib\ldap\schema.py (for module ldap.schema) not found file Lib\ldap.py (for module ldap) not found file Lib\ldap\schema.py (for module ldap.schema) not found error: Setup script exited with error: Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. Visual Studio 2003 was not found on this system. If you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py. --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From konstantin.selivanov at gmail.com Tue Jul 22 03:39:12 2008 From: konstantin.selivanov at gmail.com (konstantin) Date: Tue, 22 Jul 2008 00:39:12 -0700 (PDT) Subject: string[i:j:k] References: <4a9a4cf3-9ef4-4d9e-b714-bbf62b7c1917@v1g2000pra.googlegroups.com> <811e72db-a8bc-475a-b32a-38a9b6922600@k30g2000hse.googlegroups.com> Message-ID: <947e9bfd-a172-4b8b-abf2-c4391f0da709@z66g2000hsc.googlegroups.com> Now it's clear. Thanks. From paul at boddie.org.uk Tue Jul 29 11:58:49 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 29 Jul 2008 08:58:49 -0700 (PDT) Subject: DB access without object-relation mapping? References: Message-ID: On 29 Jul, 17:20, kj wrote: > > ?So what's the > standard Python way to send SQL directly to a Postgres database > and get back results? Take a look at this page: http://wiki.python.org/moin/DatabaseInterfaces I've used psycopg2 and pyPgSQL successfully, although pg_proboscis looks very interesting, too. Paul From mdw at distorted.org.uk Sun Jul 6 17:36:36 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Sun, 6 Jul 2008 21:36:36 +0000 (UTC) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Sebastian "lunar" Wiesner wrote: > # perl -e '("a" x 100000) =~ /^(ab?)*$/;' > zsh: segmentation fault perl -e '("a" x 100000) =~ /^(ab?)*$/;' (Did you really run that as root?) > It'd be interesting to know, how CL-PPCRE performs here (I don't know this > library). Stack overflow condition. :-( -- [mdw] From dieter at handshake.de Fri Jul 4 00:20:13 2008 From: dieter at handshake.de (Dieter Maurer) Date: Fri, 4 Jul 2008 06:20:13 +0200 Subject: Nested generator caveat Message-ID: <18541.42237.847192.691004@gargle.gargle.HOWL> I met the following surprising behaviour >>> def gen0(): ... for i in range(3): ... def gen1(): ... yield i ... yield i, gen1() ... >>> for i,g in gen0(): print i, g.next() ... 0 0 1 1 2 2 >>> for i,g in list(gen0()): print i, g.next() ... 0 2 1 2 2 2 If this is not a bug, it is at least quite confusing. The apparent reason is that the free variables in nested generator definitions are not bound (to a value) at invocation time but only at access time. Almost surely, the same applies to all locally defined functions with free variables. This would mean that locally defined functions with free variables are very risky in generators. -- Dieter From ivan at datasyncorp.com Mon Jul 14 17:48:55 2008 From: ivan at datasyncorp.com (Ivan Ven Osdel) Date: Mon, 14 Jul 2008 16:48:55 -0500 (CDT) Subject: Using Python To Launch Python In-Reply-To: <1197830015.1651011216072000480.JavaMail.root@saturn.datasyncintra.net> Message-ID: <338494552.1651151216072135866.JavaMail.root@saturn.datasyncintra.net> >Hello All, > I have a situation where I can count on a Python installation being >available on a system, but I can't count on it being a version of >Python needed by my application. Since my application has it's own >version of Python installed with it how should I use the system Python >to launch the version of Python that launches my Application. Yes, >this is a convoluted process, but not all Pythons are built the >same :) > >Right now I am leaning towards using exec to start a new process, but >I thought I would check to see if anyone else has had the need to >perform a task similar to this one. >AHA Simplest case: >>> import os >>> os.system("/path/to/your/python app.py") Obviously things can be shortened by adding to the PATH. Ivan Ven Osdel Software Engineer http://datasyncsuite.com From tjreedy at udel.edu Tue Jul 15 16:16:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Jul 2008 16:16:41 -0400 Subject: Simplify Code In-Reply-To: <4dc0cfea0807150537w1361ccabq75039886600ce9f8@mail.gmail.com> References: <4dc0cfea0807150537w1361ccabq75039886600ce9f8@mail.gmail.com> Message-ID: Victor Subervi wrote: > I set the following variables: > # Headers are kept in order to determine nesting of chapters > # They are labeled according to font size > h36 = '' > h26 = '' > h22 = '' > h18 = '' > h14 = '' > h12 = '' > header_sizes = [36, 26, 22, 18, 14, 12] > # Size is the font size of the header > size = 0 > > I write code that grabs the size var. > Then I have the following very laborious spaghetti code: > > if size == 36: > h36 = line > h26 = '' > h22 = '' > h18 = '' > h14 = '' > h12 = '' > elif size == 26: > h26 = line > h22 = '' > h18 = '' > h14 = '' > h12 = '' > elif size == 22: > h22 = line > h18 = '' > h14 = '' > h12 = '' > elif size == 18: > h18 = line > h14 = '' > h12 = '' > elif size == 14: > h14 = line > h12 = '' > elif size == 12: > h12 = line > else: > # THROW ERROR! Multiple elifs indicate a possible use for dicts. Untested possibility header_sizes = [36, 26, 22, 18, 14, 12] header_num = len(header_sizes) header_blank = ['']*header_num # makes resetting headers much easier! header_dexes = dict(zip(header_sizes, range(header_num))) hearders = header_blank[0:] #initialize # You can now change header_sizes length and contents # and others will be built to match .. def adjust_headers(size, line): dex = header_dexes[size] headers[dex] = line headers[dex+1:] = header_blank[dex+1:] Terry Jan Reedy From motoom at xs4all.nl Wed Jul 9 16:25:33 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Wed, 09 Jul 2008 22:25:33 +0200 Subject: formatting list -> comma separated (slightly different) Message-ID: <2.2.32.20080709202533.01137964@pop.xs4all.nl> Paul & Robert wrote... > d = ["soep", "reeds", "ook"] >print ', '.join(d) > soep, reeds, ook I occasionally have a need for printing lists of items too, but in the form: "Butter, Cheese, Nuts and Bolts". The last separator is the word 'and' instead of the comma. The clearest I could come up with in Python is below. I wonder if there is a more pythonic solution for this problem. Maybe something recursive? Greetings, ''' Formatting a sequence of items such that they are separated by commas, except the last item, which is separated by the word 'and'. Used for making lists of dates and items more human-readable in generated emails and webpages. For example: Four friends have a dinner: Anne, Bob, Chris and Debbie Three friends have a dinner: Anne, Bob and Chris Two friends have a dinner: Anne and Bob One friend has a dinner: Anne No friend has a dinner: ['Anne','Bob','Chris','Debbie'] -> "Anne, Bob, Chris and Debbie" ['Bob','Chris','Debbie'] -> "Bob, Chris and Debbie" ['Chris','Debbie'] -> "Chris and Debbie" ['Debbie'] -> "Debbie" [] -> "" ''' def pretty(f): if len(f)==0: return '' if len(f)==1: return f[0] sepwithcommas=f[:-1] sepwithand=f[-1] s=', '.join(sepwithcommas) if sepwithand: s+=' and '+sepwithand return s friends=['Anne','Bob','Chris','Debbie','Eve','Fred'] while True: print friends,'->',pretty(friends) if friends: friends.pop(0) else: break -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From deets at nospam.web.de Sun Jul 27 17:35:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2008 23:35:06 +0200 Subject: with statement for two files In-Reply-To: <08d72316-15f1-45dd-b1f7-7b8ee06efef5@e39g2000hsf.googlegroups.com> References: <08d72316-15f1-45dd-b1f7-7b8ee06efef5@e39g2000hsf.googlegroups.com> Message-ID: <6f480aF9r4s5U1@mid.uni-berlin.de> braver schrieb: > Can open two files in a with statement: > > with open(src) as readin, open(dst,"w") as writin: # WRONG: comma > doesn't work > ... > > -- so that you have transactional safety for two file descriptors? > The comma syntax doesn't work, but is there a way, except for > > with open(src) as readin: > with open(dst,"w) as writin: > ... I'm not aware of any pre-defined context manager which does that. But you can write your own context manager to do that, even a generalized combinator for taking two managers and create one, like this: with context_creator(open, [src], open, [dst, "w"]) as readin, writin: ... A fundamental problem though would be that the semantics become difficult. If closing the "outer" file fails, it's impossible to "rollback" the inner one. So I think it really is better to use the nested with, which makes it crystal clear that the inner block might succeed independently from the outer one. Diez From nicolas.pourcelot at gmail.com Fri Jul 18 07:39:40 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Fri, 18 Jul 2008 04:39:40 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: <88704e81-8208-4785-a725-8dcde080225f@z16g2000prn.googlegroups.com> On 18 juil, 12:26, Peter Otten <__pete... at web.de> wrote: > nicolas.pource... at gmail.com wrote: > > I think something like > >>>> id(myobject) in (id(element) for element in mylist) > > would also work, also it's not so readable, and maybe not so fast > > (?)... > > > An "is in" operator would be nice... > > And rarely used. Probably even less than the (also missing) > > < in, | in, you-name-it > > operators... > Maybe, but imho >>> myobject is in mylist is highly readable, when >>> myobject < in mylist is not. From tjreedy at udel.edu Wed Jul 2 20:27:19 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 02 Jul 2008 20:27:19 -0400 Subject: wrong md5 checksum In-Reply-To: <486be45d$0$859$ba4acef3@news.orange.fr> References: <486a16ef$0$885$ba4acef3@news.orange.fr> <486a5316$0$864$ba4acef3@news.orange.fr> <2-CdnaVu6892xvfVnZ2dnUVZ_gGdnZ2d@supernews.com> <486be45d$0$859$ba4acef3@news.orange.fr> Message-ID: kkwweett wrote: > >> >> A. an error in the software that computed the value for the web page, >> B. a transcription error in putting the checksum on the web page, >> C. accidental corruption of the file, or >> D. a deliberate attempt to substitute a file with a similar MD5 sum. >> > > It seems that the answer is probably B. But, according to the release > website manager, a mystery remains : > > http://mail.python.org/pipermail/python-3000/2008-July/014281.html Marcin Kowalczyk pointed out in a follow-up to the above that the replacement of 'a5' with 'b1' could have been part of a global search/replace that would have been correct everywhere else on the page. Thus case C. Barry remembers doing some such. Lesson. Take care with blind global replacements. From nicolas.pourcelot at gmail.com Sat Jul 19 16:13:40 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Sat, 19 Jul 2008 13:13:40 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> <6ebshqF67cpfU4@mid.uni-berlin.de> Message-ID: <5d6b8066-c941-4f0c-abea-20baed33b4ab@l64g2000hse.googlegroups.com> On 18 juil, 17:52, Marc 'BlackJack' Rintsch wrote: > On Fri, 18 Jul 2008 07:39:38 -0700, nicolas.pourcelot wrote: > > So, I use something like this in 'sheet.objects.__setattr__(self, > > name, value)': > > if type(value) == Polygon: > > ? ? for edge in value.edges: > > ? ? ? ? if edge is_in sheet.objects.__dict__.itervalues(): > > ? ? ? ? ? ? object.__setattr__(self, self.__new_name(), edge) > > > Ok, I suppose it's confused, but it's difficult to sum up. ;-) > > You are setting attributes with computed names? ?How do you access them? > Always with `gettattr()` or via the `__dict__`? ?If the answer is yes, why > don't you put the objects the into a dictionary instead of the extra > redirection of an objects `__dict__`? > Yes, I may subclass dict, and change its __getitem__ and __setitem__ methods, instead of changing objets __setattr__ and __getattr__... But I prefer >>> sheet.objects.A = Point(0, 0) than >>> sheet.objects["A"] = Point(0, 0) > Oh and the `type()` test smells like you are implementing polymorphism > in a way that should be replaced by OOP techniques. I wrote 'type' here by mistake, but I used 'isinstance' in my code. ;-) > If you make Point immutable you might be able to drop the "must not be referenced twice" requirement. Yes, but unfortunately I can't (or it would require complete redesign...) From Bill at SynectixLtd.com Sat Jul 12 10:14:06 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Sat, 12 Jul 2008 15:14:06 +0100 Subject: ..\..\Python-2.5.2\Include\pyport.h(117) : fatal error C1189: #error : "Python needs a typedef for Py_ssize_t in pyport.h." Message-ID: <2Y2dnWAl9dSwIeXVnZ2dnUVZ8u-dnZ2d@bt.com> When I try and compile using VS2003 for Release. Compiles fine for Debug. In a hurry (should be gardening). Any solution? TIA Bill From asmodai at in-nomine.org Fri Jul 4 01:31:14 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 4 Jul 2008 07:31:14 +0200 Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: References: Message-ID: <20080704053113.GJ34192@nexus.in-nomine.org> -On [20080630 23:51], Ali Servet D?nmez (asd at pittle.org) wrote: >This could be an extension, a plugin, an Emacs mode, a new editor or >even a brand new huge all-fancy IDE, I don't care, but what am I >missing here? Vim's omnicomplete (CTRL-X CTRL-O). See :help omnifunc within vim. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Don't always think in a straight line... From omer at no-log.org Wed Jul 2 12:40:03 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Wed, 2 Jul 2008 18:40:03 +0200 Subject: Trouble using pinckle In-Reply-To: <486ba8a4$0$11957$426a74cc@news.free.fr> References: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> <1ijgp2r.1j1k5xwwbtiwcN%pdorange@pas-de-pub-merci.mac.com> <486ba8a4$0$11957$426a74cc@news.free.fr> Message-ID: <200807021840.03888.omer@no-log.org> > > I'll also try the dictionnary method. > > My final idea was that a dictionnary would be perhaps simple in the > > future to save/load as XML and a parser. > XML ? What a strange idea ? Why is it so strange ? Many softs have their config in xml, and the xml.* modules are not that hard to use. It makes sense if you have a lot of config entries with nested sections. > > On a more global perspective, what are the best method to implement a > > simple config file with pyhton. > > Well... Python does have a couple of config-related packages, starting > with the one in the stdlib. You may want to find out if any of these > packages fits your needs before reinventing the wheel ? Right, ConfigParser should do the trick for simpler things. -- C?dric Lucantis From bedouglas at earthlink.net Sun Jul 20 21:43:03 2008 From: bedouglas at earthlink.net (bruce) Date: Sun, 20 Jul 2008 18:43:03 -0700 Subject: db question Message-ID: <229701c8ead3$1e9eecf0$0301a8c0@tmesa.com> Hi... simple test mysql cmd - select * from foo where dog like "%small%"; sql ="""select * from foo where dog like "%%%s%%" """ c.execute(sql, (var,)) the above doesn't work, and I can't seem to figure out how to display/print out the sql as i't actually been excuted, so I can see where the issue is. i've tried to "/" escape, as well as a few other things, now of which shed any light on the issue. haven't found any information via google either. the above works if i have something like sql="""select * from foo where dog=%s""" c.execute(sql,(var,)) so.. any help/pointers on what i've screwed up/missed would be helpful. thanks From alexnbryan at gmail.com Thu Jul 31 15:51:49 2008 From: alexnbryan at gmail.com (Alexnb) Date: Thu, 31 Jul 2008 12:51:49 -0700 (PDT) Subject: simple problem with lists I am just forgetting Message-ID: <18762181.post@talk.nabble.com> Lets say we have this list: funlist = ['a', 'b', 'c'] and lets say I do this: if funlist[4]: print funlist[4] I will get the exception "list index out of range" How can I test if the list item is empty without getting that exception? -- View this message in context: http://www.nabble.com/simple-problem-with-lists-I-am-just-forgetting-tp18762181p18762181.html Sent from the Python - python-list mailing list archive at Nabble.com. From d3vvnull at gmail.com Sun Jul 20 15:53:46 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Sun, 20 Jul 2008 14:53:46 -0500 Subject: question In-Reply-To: References: Message-ID: <170543c70807201253r5af5b54bv7e00a63aa7dc43fd@mail.gmail.com> I think the question was: why does anyone still use perl when Python is clearly the better language? On Sun, Jul 20, 2008 at 2:17 PM, Paddy wrote: > On Jul 20, 6:39 pm, wrote: > > Nobody any sensible answers. Too complicated I suppose! > > The sensible question was? > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From vaibhav4947 at gmail.com Mon Jul 7 02:10:51 2008 From: vaibhav4947 at gmail.com (vaibhav pol) Date: Mon, 7 Jul 2008 11:40:51 +0530 Subject: error in SimpleXMLRPCServer Message-ID: <18a05b120807062310m47d3def4k972c7d9af1fca421@mail.gmail.com> hi, I create a SimpleXMLRPCServer script which execute the command on server and return the result. code is below accessList=( 'test.org' ) class Server(SimpleXMLRPCServer.SimpleXMLRPCServer): def __init__(self,*args): SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self,(args[0],args[1])) def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) SimpleXMLRPCServer.SimpleXMLRPCServer.server_bind(self) def verify_request(self,request, client_address): if client_address[0] in accessList: return 1 else: return 0 class xmlrpc_registers: def __init__(self): self.python_string = string def clientfun(self,argument): try: cmd = argument (stdin,stdout,stderr)=popen3(cmd) stdin.close() value2=stdout.read() value3=stderr.read() stdout.close() stderr.close() output = {"stdout":value2,"stderr": value3} return output if __name__ == "__main__": if (len(sys.argv) == 3): try : servername=sys.argv[1] portnumber=int(sys.argv[2]) server = Server(servername,portnumber) server.register_instance(xmlrpc_registers()) server.serve_forever() except Exception,e: print "Root service is shutting down .." print str(e) else: print "Please provide <\"hostname or ip\"> <\"portnumber\">" this server side code i run in background using nohup from client when i call function it execute fine but after some time when i call it gives following error and server program killed. please help -------------- next part -------------- An HTML attachment was scrubbed... URL: From mrkafk at gmail.com Wed Jul 23 08:10:22 2008 From: mrkafk at gmail.com (mk) Date: Wed, 23 Jul 2008 14:10:22 +0200 Subject: Python Written in C? In-Reply-To: <6ejutcF6vgp3U4@mid.uni-berlin.de> References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > An operation that most people avoid because of the penalty of "shifting > down" all elements after the deleted one. Pythonistas tend to build new > lists without unwanted elements instead. Which is exactly what I have done with my big lxml.etree, from which I needed to delete some elements: constructed a new tree only with elements I wanted. Sure, that works. There _is_ a minor side effect: nearly doubling memory usage while the operation lasts. 99% of the time it's not a problem, sure. > I can't even remember when I > deleted something from a list in the past. Still, doesn't that strike you as.. workaround? I half-got used to it, but it would still be nice not to (practically) have to use it. Enough whining. Gonna eat my quiche and do my Python. :-) From pavlovevidence at gmail.com Tue Jul 29 17:27:48 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 14:27:48 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: On Jul 29, 3:43 pm, "Heiko Wundram" wrote: > Am 29.07.2008, 18:30 Uhr, schrieb Carl Banks : > > > On Jul 29, 5:15 am, Heiko Wundram wrote: > >> I can't dig up a simple example from code I wrote quickly, but because > >> of the > >> fact that explicit comparisons always hamper polymorphism > > > I'm not going to take your word for it. Do you have code that > > demonstrates how "if x" improves polymorphism relative to simple > > explicit tests? > > As I wrote in the second reply email I sent, check out my integer set > recipe on ASPN (and to save you the search: http://code.activestate.com/recipes/466286/). Couple points: 1. Any container type that returns a length that isn't exactly the number of elements in it is broken. 2. The need for __nonzero__ in this case depends on a limitation in the language. 3. On the other hand, I will concede that sometimes calculating len is a lot more expensive than determining emptiness, and at a basic level it's important to avoid these costs. You have found a practical use case for __nonzero__. However, I'd like to point out the contrasting example of numpy arrays. For numpy arrays, "if x" fails (it raises an exception) but "if len(x)!=0" succeeds. The only sane advice for dealing with nonconformant classes like numpy arrays or your interger set is to be wary of nonconformances and don't expect polymorphism to work all the time. So I guess I'll concede that in the occasional cases with nonconformant classes the "if x" might help increase polymorphism a little. (BTW: here's another little thing to think about: the "if x" is useful here only because there isn't an explicit way to test emptiness without len.) Carl Banks From michael at stroeder.com Thu Jul 24 02:49:33 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 24 Jul 2008 08:49:33 +0200 Subject: Inserting cookies into a web session In-Reply-To: References: Message-ID: John Gordon wrote: > I'm developing a web application that needs a semi-persistent way to > store information. > > I've looked at some options such as writing entries to a database table > or creating small textfiles, but I'm not thrilled with anything I've come > up with so far. What's the problem? > Then a coworker suggested that I could just insert a cookie into the > current session, which would store whatever information I wanted. This > seems like a really good solution. That's what cookies are *for*, right? Before using cookies keep in mind that the cookies returned by the browser are not trustworthy! You have to validate the values each time. > But I've never worked with cookies before. Is there a Python package for > handling cookies? http://docs.python.org/lib/module-Cookie.html > And are there any back-end requirements? No. > I assume you > would have to be running a webserver that supports sessions. You can do this all within your web application. > Do you also > have to be running some sort of web container or servlet engine? No. Ciao, Michael. From JordanNealBerg at gmail.com Tue Jul 15 15:36:05 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Tue, 15 Jul 2008 12:36:05 -0700 (PDT) Subject: graphing lifelines References: Message-ID: There are several different modules for graphing in Python which you can find easily by searching, but to my knowledge none of them will simply take in a set of tuples and turn them into what you want, although I am sure that it is certainly possible to program a app that could do that for you... If you can't/don't want to program such an app and you don't have many data points, you could probably just cook one up using Photoshop/GIMP/ MSPaint, or whatnot (although clearly I could understand not wanting to do that for 100's of points)... sounds like an interesting project an auto lifeline maker that takes in data points...hmm From carbonimax at gmail.com Tue Jul 8 08:56:46 2008 From: carbonimax at gmail.com (Carbonimax) Date: Tue, 8 Jul 2008 05:56:46 -0700 (PDT) Subject: py2exe, PyQT, QtWebKit and jpeg problem References: Message-ID: <3eead611-60be-4ccd-bc9b-d62ef3b74578@8g2000hse.googlegroups.com> On Jun 29, 4:14 pm, yang.zenggu... at gmail.com wrote: > On 6?20?, ??11?04?, Carbonimax wrote: > > > hello > > > I have a problem with py2exe and QtWebKit : > > I make a program with a QtWebKit view. > > If I launch the .py directly, all images (jpg, png) are displayed but > > if I compile it with py2exe I have only png images. No jpg ! > > No error message, nothing. > > > Have you a solution ? Thank you. > > I have the same problem with you. I find a way to fix it: > 1. Copy Qt plugins to the directory: $YOUR_DIST_PATH/PyQt4/plugins; > 2. Copy qt.conf to youar dist directory; > 3. Edit qt.conf, change Prefix to $YOUR_DIST_PATH/PyQt4 > > Orit It work, thank you :) From jgardner at jonathangardner.net Thu Jul 17 16:02:57 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 17 Jul 2008 13:02:57 -0700 (PDT) Subject: x, = y (???) References: Message-ID: On Jul 17, 12:55?pm, kj wrote: > I still don't get it. ?If we write > > ? y ?= 'Y' > ? x, = y > > what's the difference now between x and y? ?And if there's no > difference, what's the point of performing such "unpacking"? > Try: y = "abc" x, = y You were unpacking y into ('Y',) From mensanator at aol.com Mon Jul 21 01:16:39 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 20 Jul 2008 22:16:39 -0700 (PDT) Subject: Python Written in C? References: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> Message-ID: <02065923-76b6-4b4e-a1a0-19ee8ac49c04@59g2000hsb.googlegroups.com> On Jul 20, 11:08?pm, "Dan Upton" wrote: > On Sun, Jul 20, 2008 at 11:51 PM, Mensanator wrote: > > On Jul 20, 10:05?pm, Stephen Johnson wrote: > >> > Carry bits? Who worries about carry bits when you have > >> > unlimited precision arithmetic? You want cool? > >> > THIS is cool: > > >> > j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2])) > >> > % xyz[1]**(k-1))/xyz[1]**(k-2) > > >> You call that "cool." I call it "unreadable." > > > Ok, but not in the sense that something like > > Scheme is unreadable as this is nothing but > > algebra (albeit complicaed). > > Scheme doesn't *have* to be unreadable... any more unreadable than any > other language when poorly documented/formatted, anyway. When I needed to whip up a variation on Ulam's Spiral recently, I went and got the Scheme version I wrote 4 years ago when I briefly toyed with Scheme and thought I'd just translate the plotting part to Python. Couldn't make any sense of it and ended up doing the Python version with Turtle Graphics. From karthikbalaguru79 at gmail.com Tue Jul 22 09:27:19 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Tue, 22 Jul 2008 06:27:19 -0700 (PDT) Subject: tkinter for my python program !! Message-ID: Hi, One of my python program needs tkinter to be installed to run successfully. I am using Redhat 9.0 and hence tried installing by copying the tkinter-2.2.2-36.i386.rpm alone from the CD 3 to my pc. But, it is not getting installed and is failing by throwing the below errors. Should i need to configure / install any specific files for resolving this issue ? [root at localhost karthik]# rpm -ivh tkinter-2.2.2-26.i386.rpm warning: tkinter-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key ID db42a 60e error: Failed dependencies: libtcl8.3.so is needed by tkinter-2.2.2-26.i386 libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 libtk8.3.so is needed by tkinter-2.2.2-26.i386 Any ideas ? Thx in advans, Karthik Balaguru From sjmachin at lexicon.net Sun Jul 13 21:13:11 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 13 Jul 2008 18:13:11 -0700 (PDT) Subject: Using Groups inside Braces with Regular Expressions References: <10284e46-1601-4269-a1a0-ef3831e9f85c@z66g2000hsc.googlegroups.com> Message-ID: <5428c947-56bd-4ab5-bfdd-2797b031d3f7@27g2000hsf.googlegroups.com> On Jul 14, 9:05 am, Chris wrote: Misleading subject. [] brackets or "square brackets" {} braces or "curly brackets" () parentheses or "round brackets" > I'm trying to delimit sentences in a block of text by defining the > end-of-sentence marker as a period followed by a space followed by an > uppercase letter or end-of-string. ... which has at least two problems: (1) You are insisting on at least one space between the period and the end-of-string (this can be overcome, see later). (2) Periods are often dropped in after abbreviations and contractions e.g. "Mr. Geo. Smith". You will get three "sentences" out of that. > > I'd imagine the regex for that would look something like: > [^(?:[A-Z]|$)]\.\s+(?=[A-Z]|$) > > However, Python keeps giving me an "unbalanced parenthesis" error for > the [^] part. It's nice to know that Python is consistent with its error messages. > If this isn't valid regex syntax, If? It definitely isn't valid syntax. The brackets should delimit a character class. You are trying to cram a somewhat complicated expression into a character class, or you should be using parentheses. However it's a bit hard to determine what you really meant that part of the pattern to achieve. > how else would I match > a block of text that doesn't the delimiter pattern? Start from the top down: A sentence is: anything (with some qualifications) followed by (but not including): a period followed by either 1 or more whitespaces then a capital letter or 0 or more whitespaces then end-of-string So something like this might do the trick: >>> sep = re.compile(r'\.(?:\s+(?=[A-Z])|\s*(?=\Z))') >>> sep.split('Hello. Mr. Chris X\nis here.\nIP addr 1.2.3.4. ') ['Hello', 'Mr', 'Chris X\nis here', 'IP addr 1.2.3.4', ''] From praveen.sunsetpoint at gmail.com Thu Jul 3 01:38:11 2008 From: praveen.sunsetpoint at gmail.com (Sallu) Date: Wed, 2 Jul 2008 22:38:11 -0700 (PDT) Subject: Email Validation with domain References: <873ams770b.fsf@benfinney.id.au> Message-ID: On Jul 2, 6:25?pm, Ben Finney wrote: > Sallu writes: > > validateEmail(msg) ?i wrote a script above it works fine > > Actually, no. It rejects a great many email addresses that are valid. > > > but it does not check for valid domain like .com .org .in how to > > validate with domain > > To validate a domain for delivery of email, check with the DNS by > requesting the A or MX record for that domain. > > To validate an email address, check with the mail server for that > domain by sending a message to the address. > > Neither of them should be "validated" by a regular expression. > > Please refer to RFC 3696 > described as "Recommended techniques for applications checking or > manipulating domain and other internet names". > > -- > ?\ ? ? ? ??Pinky, are you pondering what I'm pondering?? ?Wuh, I think | > ? `\ ? so, Brain, but wouldn't anything lose its flavor on the bedpost | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? overnight?? ?_Pinky and The Brain_ | > Ben Finney Thank you to all of you and clearing my idea.. From larudwer at freenet.de Fri Jul 25 11:52:11 2008 From: larudwer at freenet.de (Rüdiger Werner) Date: Fri, 25 Jul 2008 17:52:11 +0200 Subject: Python base distribution come with a validating XML parser? References: <4205c679-4a0e-41d6-8311-2e033b7b5e0d@j7g2000prm.googlegroups.com> Message-ID: > Hi, > > Basic XML questions, > > I have a .xml file I want to validate against a .xsd file... > > Does the Python base distribution come with a validating XML parser? > > I want to make sure the elements in my xml file vs. the elements > defined in my xsd are a match. > > I could parse both XML and xsd elements to lists and compare the > lists, but I imagine the validation process can do this too... > > Some of this is basic stuff - just a link to a site or doc is > sufficient. > > Thanks. I think you are looking for lxml http://codespeak.net/lxml/ From steve at REMOVE-THIS-cybersource.com.au Tue Jul 29 19:39:06 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 23:39:06 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> Message-ID: <009fa593$0$20313$c3e8da3@news.astraweb.com> On Tue, 29 Jul 2008 21:15:12 +0100, Matthew Woodcraft wrote: > Steven D'Aprano wrote: >> "if x" is completely type agnostic. You can pass an object of any type >> to it, and it will work. (Excluding objects with buggy methods, >> naturally.) > > There are many circumstances where if a parameter is None I'd rather get > an exception than have the code carry on with the 'empty container' > branch (and silently give me a meaningless result). Sure. The way I'd handle that is test for None at the start of the function, and raise an error there, rather than deal with it at some arbitrary part of the function body. -- Steven From trentm at activestate.com Mon Jul 28 12:55:49 2008 From: trentm at activestate.com (Trent Mick) Date: Mon, 28 Jul 2008 09:55:49 -0700 Subject: ActiveState Code (the new Python Cookbook) has been launched In-Reply-To: References: Message-ID: <488DFA15.9080407@activestate.com> Nick Craig-Wood wrote: > Trent Mick wrote: >> I happy to announce that ActiveState Code has been taken out of beta. >> This is the new site replacing the ASPN Cookbooks -- in particular the >> Python Cookbook. >> >> http://code.activestate.com/ > > Looks great and much faster than the old site! Thanks! > Mind telling us how it is implemented? I'm guessing python/django by > the url and the fact that you have python stuff on your home pages but > I could be wrong! Yup, it is a Django-based site -- a pleasure to work with, that. Using django-tagging, django-template-utils & universal feedparser (for hooking in Atom content for News section on home page), django-voting, python-markdown2 (for rendering comments, discussion/descriptions), recaptcha-client (for feedback when not logged in), pygments (for syntax coloring). I've just submitted the site to http://www.djangosites.org/ I hope to do some blog posts about some parts of the site soon and release the small re-usable "feedback" app I've put together for getting feedback on the site. Cheers, Trent -- Trent Mick trentm at activestate.com From fredrik at pythonware.com Wed Jul 23 08:19:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 14:19:06 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: <216dcee8-ad3d-4ae1-ac4a-4f4819775c7e@d1g2000hsg.googlegroups.com> References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> <216dcee8-ad3d-4ae1-ac4a-4f4819775c7e@d1g2000hsg.googlegroups.com> Message-ID: Ben Sizer wrote: > You should put the extern block around the #include call > rather than individual functions, as surely the C calling convention > should apply to everything within. Hello? Python's include files are C++ safe. I even posted a complete compiler session to show that I'm not making that up. From sjmachin at lexicon.net Fri Jul 18 07:10:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 18 Jul 2008 04:10:44 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> Message-ID: On Jul 18, 9:05 pm, oj wrote: > On Jul 18, 11:33 am, arnimavidyar... at gmail.com wrote: > > > > > Hi, > > > Hi, > > > I am taking a string as an input from the user and it should only > > contain the chars:L , M or R > > > I tried the folllowing in kodos but they are still not perfect: > > > [^A-K,^N-Q,^S-Z,^0-9] > > [L][M][R] > > [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > > > For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. > > > regards, > > SZ > > > The string may or may not have all the three chars. > > With regular expressions, [^LRM] matches a character that isn't L, R > or M. So: > > import re > > var = "LRLRLRLNR" > > if re.search(r'[^LRM]', var): > print "Invalid" Fails if var refers to the empty string. From jake at vapourforge.com Thu Jul 10 01:06:11 2008 From: jake at vapourforge.com (Jake Anderson) Date: Thu, 10 Jul 2008 15:06:11 +1000 Subject: python scalability In-Reply-To: <487590E6.7020004@gmail.com> References: <487590E6.7020004@gmail.com> Message-ID: <487598C3.9080306@vapourforge.com> Tim Mitchell wrote: > Hi All, > > I work on a desktop application that has been developed using python > and GTK (see www.leapfrog3d.com). We have around 150k lines of python > code (and 200k+ lines of C). We also have a new project manager with > a C# background who has deep concerns about the scalability of python > as our code base continues to grow and we are looking at introducing > more products. I am looking for examples of other people like us (who > write desktop apps in python) with code bases of a similar size who I > can point to (and even better talk to) to help convince him that > python is scalable to 300+ lines of code and beyond. I have looked at > the python success stories page and haven't come up with anyone quite > like us. One of my project managers questions is: "Are we the only > company in the world with this kind and size of project?" > I want to say no, but am having trouble convincing myself, let alone him. > > If you are involved in this kind of thing please get in touch with me. > > Thanks, > Tim > -- > http://mail.python.org/mailman/listinfo/python-list It'd be 1500k lines of C if not for the 150k of python ;-> From fredrik at pythonware.com Wed Jul 16 04:57:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 10:57:52 +0200 Subject: reading one byte from stdin In-Reply-To: <40DC41E9-DBFA-45F3-B155-92785AA9490B@fastsoft.com> References: <40DC41E9-DBFA-45F3-B155-92785AA9490B@fastsoft.com> Message-ID: Mark McDuff wrote: > I'm trying to read one byte from stdin, without the newline. > > If I try something like: > >>> import os, sys > >>> os.read(sys.stdin.fileno(),1) > > I can input a character, but then I have to press enter, which leaves a > newline character in the stdin buffer and requires two keypresses. Is > there any way to read only one keypress in a simple manner (i.e. no > curses)? in addition to the cookbook article Diez posted, there's also a FAQ entry about this: http://effbot.org/pyfaq/how-do-i-get-a-single-keypress-at-a-time.htm From robert.rawlins at thinkbluemedia.co.uk Fri Jul 18 12:12:39 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Fri, 18 Jul 2008 17:12:39 +0100 Subject: Unusual Exception Behaviour In-Reply-To: <1e6def2a-9c44-419e-a450-5fe596c5e3c0@j1g2000prb.googlegroups.com> References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> <8904.90077804333$1216313689@news.gmane.org> <006001c8e831$5c1487b0$143d9710$@rawlins@thinkbluemedia.co.uk> <1214.94685668058$1216317006@news.gmane.org> <1e6def2a-9c44-419e-a450-5fe596c5e3c0@j1g2000prb.googlegroups.com> Message-ID: <002901c8e8f1$1a00c6c0$4e025440$@rawlins@thinkbluemedia.co.uk> > The logging configuration functionality provided by fileConfig is all- > or-nothing, i.e. it does not support incremental configuration. > > Do you know if any libraries you depend on use fileConfig? > > If you use programmatic configuration only, and don't use fileConfig > at all, does everything work as expected? Vinay, I changed this over to programmatic configuration this afternoon and it works just great, all the logging I require, and my exceptions get thrown. :-D I have no idea if any of the librarys I use work from a file config, I'm certainly not aware of them doing so. This is really quite frustrating as I'd much rather use a conf file than work this programmatically. I get the feeling that it's because in the config file I was not attaching any handlers to the root logger, but I don't know. Robert From hv at tbz-pariv.de Wed Jul 2 09:24:47 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Wed, 02 Jul 2008 15:24:47 +0200 Subject: Scripting SAP GUI (Windows) In-Reply-To: <6d15tpFaec4U1@mid.individual.net> References: <6d15tpFaec4U1@mid.individual.net> Message-ID: <6d1dsvFb31rU2@mid.individual.net> I just got this link in a german newsgroup: http://pywinauto.openqa.org/ Seems to be what I was looking for. Nevertheless feedback still welcome. Thomas Guettler schrieb: > Hi, > > I need to script SAP GUI running on MS-Windows: > > Open SAP GUI window, if it is not already open, and then batch input > some keystrokes. > > The following solutions were found by google: > > - autohotkey: not preferred, since it has an own programming > language. This will slow down development. > - pyHook > - user pywin32 and SetWindowsHookEx > > I develop with python since seven years, but only on linux. > > Any hints? > > -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From basti.wiesner at gmx.net Sat Jul 5 19:26:05 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sun, 06 Jul 2008 01:26:05 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <9cae59d9-ead4-45bc-a980-2ac2e1616f9b@p25g2000hsf.googlegroups.com> Message-ID: Terry Reedy : > Mark Dickinson wrote: >> On Jul 5, 1:54 pm, Carl Banks wrote: > >> Part of the problem is a lack of agreement on what >> 'regular expression' means. > > Twenty years ago, there was. Calling a extended re-derived grammar > expression like Perl's a 'regular-expression' is a bit like calling a > Hummer a 'car' -- perhaps to hide its gas-guzzling behavior. Yet, to many programmers the Hummer is not only just a car, its _the_ car. Everything else is just silly, bloody old posix crap ;) (meaning, that pcres are often seen as true regular expressions, and everything else is referred to as "being somehow restricted") -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From ki4yjl at gmail.com Sat Jul 12 12:17:31 2008 From: ki4yjl at gmail.com (WDC) Date: Sat, 12 Jul 2008 09:17:31 -0700 (PDT) Subject: spam <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> Message-ID: <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> On Jul 11, 7:21?pm, Nobody Here wrote: > rickman wrote: > > spam > > No fucking shit, Sherlock, why double the volume by pointing out the obvious? Calm down you all. BTW I reported it, yo should too. From davidreynon at gmail.com Mon Jul 7 17:56:23 2008 From: davidreynon at gmail.com (korean_dave) Date: Mon, 7 Jul 2008 14:56:23 -0700 (PDT) Subject: How to make python scripts .py executable, not bring up editor Message-ID: >From command Prompt, i type in a script, "tryme.py". This, instead, brings up PythonWin editor and Interactive Window. Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) How do I make it so that the script runs? From basti.wiesner at gmx.net Sat Jul 5 04:12:05 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sat, 05 Jul 2008 10:12:05 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Paddy : > On Jul 4, 1:36?pm, Peter Otten <__pete... at web.de> wrote: >> Henning_Thornblad wrote: >> > What can be the cause of the large difference between re.search and >> > grep? >> >> grep uses a smarter algorithm ;) >> >> >> >> > This script takes about 5 min to run on my computer: >> > #!/usr/bin/env python >> > import re >> >> > row="" >> > for a in range(156000): >> > row+="a" >> > print re.search('[^ "=]*/',row) >> >> > While doing a simple grep: >> > grep '[^ "=]*/' input ? ? ? ? ? ? ? ? ?(input contains 156.000 a in >> > one row) >> > doesn't even take a second. >> >> > Is this a bug in python? >> >> You could call this a performance bug, but it's not common enough in real >> code to get the necessary brain cycles from the core developers. >> So you can either write a patch yourself or use a workaround. >> >> re.search('[^ "=]*/', row) if "/" in row else None >> >> might be good enough. >> >> Peter > > It is not a smarter algorithm that is used in grep. Python RE's have > more capabilities than grep RE's which need a slower, more complex > algorithm. FWIW, grep itself can confirm this statement. The following command roughly takes as long as Python's re.search: # grep -P '[^ "=]*/' input -P tells grep to use real perl-compatible regular expressions. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From mrkafk at gmail.com Thu Jul 17 13:10:47 2008 From: mrkafk at gmail.com (mk) Date: Thu, 17 Jul 2008 19:10:47 +0200 Subject: Unusual Exception Behaviour In-Reply-To: <8904.90077804333$1216313689@news.gmane.org> References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> <8904.90077804333$1216313689@news.gmane.org> Message-ID: > http://linux.byexamples.com/archives/365/python-convey-the-exception-traceba > ck-into-log-file/ >> if __name__=="__main__": >> try: >> main() >> except: >> print "Trigger Exception, traceback info forward to log file." >> traceback.print_exc(file=open("errlog.txt","a")) >> sys.exit(1) >> > > I've just given this solution a shot but I still seem to get the same > result, it suddenly starts dumping the log data to the command line, and > nothing gets printed in error.txt apart from the keyboard interrupt from > when I kill the application. That's seriously weird. What's your Python version and platform? On my Windows and Linux machines, with more recent Python versions the above trick works flawlessly. Check your environment, namely PYTHON* variables. There may be something causing this behaviour. Unset them. Check the first line of your scripts. If you're calling wrong Python interpreter (there may be more than one in the system for some reason), this may cause it. You could also try setting up PYTHONINSPECT environment variable or run the python interpreter with -i option before program filename, which drops you into an interactive shell upon exception or termination of a program. > For some reason the exceptions don't seem to be raised properly so obviously > aren't being caught at this higher level. > > So confusing. This behavior is seriously unusual for Python. Maybe you have some old / buggy version? From sjmachin at lexicon.net Tue Jul 1 17:49:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 1 Jul 2008 14:49:28 -0700 (PDT) Subject: Error from zipfile References: Message-ID: <0ee648ae-25d3-4c51-8b40-ba2f88612e4c@q27g2000prf.googlegroups.com> On Jul 2, 1:38 am, "Wesley Brooks" wrote: > Dear Users, > > I'm having a problem when trying to move script from Linux to Windows. > A zipfile opperation is failing with the message: > > "BadZipFile: File is not a zip file" > > I have a simple scripts that reads a zip file in the same way as any > other file into a string, then sends it across to a network where it > is saved as perusual into a file, then read in and processed by > zipfile. If "saved as per usual" means something like open('foo.zip', 'w').write(the_string) then this is highly likely to be your problem. Use 'wb'. Get into the habit of using the 'b' flag on binary files in your scripts (whether reading or writing) and they'll be much more portable. Something to check: on the Linux side, do wc -l foo.zip (that option's 'L'.lower()) to get the number of pseudo-lines in your zip file, and compare the sizes of the file on Linux and Windows. What do you see? HTH, John From wbsoft at xs4all.nl Sat Jul 19 16:18:46 2008 From: wbsoft at xs4all.nl (Wilbert Berendsen) Date: Sat, 19 Jul 2008 22:18:46 +0200 Subject: Determining when a file has finished copying In-Reply-To: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> Message-ID: <200807192218.46396.wbsoft@xs4all.nl> You could also copy to a different name on the same disk, and when the copying has been finished just 'move' (mv) the file to the filename the other application expects. E.g. QMail works this way, writing incoming mails in folders. Met vriendelijke groet, Wilbert Berendsen -- http://www.wilbertberendsen.nl/ "You must be the change you wish to see in the world." -- Mahatma Gandhi From sjmachin at lexicon.net Sun Jul 20 17:12:10 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 Jul 2008 14:12:10 -0700 (PDT) Subject: regex doubts References: <532965.570.qm@web54502.mail.re2.yahoo.com> <504d473e-375a-4111-ae2e-c06aaa37b096@p25g2000pri.googlegroups.com> Message-ID: On Jul 21, 12:30 am, Fredrik Lundh wrote: > John Machin wrote: > >> try "[LRM]+$" (an L or an R or an M, one or more times, all the way to > >> the end of the string). > > > Ummm ... with the default flag settings, shouldn't that be \Z instead > > of $ ? > > Why? The OP was reading input from a user; whether he gets a trailing > newline or not depends on the input method, and $ does the right thing > for all normal input methods. The goal as far as I can tell was to produce a pattern that matched one (maybe zero) or more instances of 'L', 'R', or 'M', and no other characters. >>> bool(re.match(r'[LRM]+\Z', 'MRL\n')) False >>> bool(re.match(r'[LRM]+$', 'MRL\n')) True >>> '\n' is an "other character". Perhaps you could explain what you mean by "$ does the right thing". From kw at codebykevin.com Tue Jul 8 13:41:43 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 08 Jul 2008 13:41:43 -0400 Subject: system tray for Tk In-Reply-To: References: Message-ID: <4873A6D7.308@codebykevin.com> Oguz Yarimtepe wrote: > Hi, > > Is there any binding that i can use for my python-tk application that > will show an icon at the system tray when the application runs which > will be able to be change during the process? > See http://wiki.tcl.tk/4090 for some ideas. This will require installing some Tcl/Tk packages, but they can probably be called easily enough from Python. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From socyl at 987jk.com.invalid Thu Jul 17 15:55:59 2008 From: socyl at 987jk.com.invalid (kj) Date: Thu, 17 Jul 2008 19:55:59 +0000 (UTC) Subject: x, = y (???) References: Message-ID: In Erik Max Francis writes: >kj wrote: >> I just came across an assignment of the form >> >> x, = y >> >> where y is a string (in case it matters). >> >> 1. What's the meaning of the comma in the LHS of the assignment? >It's unpacking a 1-tuple: > (x,) = y >The parentheses here are not necessary and are sometimes left out. I still don't get it. If we write y = 'Y' x, = y what's the difference now between x and y? And if there's no difference, what's the point of performing such "unpacking"? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From deets at nospam.web.de Wed Jul 2 14:49:16 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Jul 2008 20:49:16 +0200 Subject: Most efficient way to get pixelcolors of an image? In-Reply-To: <2c4e285c-f355-4e09-bd67-6de5656dc6c9@m36g2000hse.googlegroups.com> References: <2c4e285c-f355-4e09-bd67-6de5656dc6c9@m36g2000hse.googlegroups.com> Message-ID: <6d20tcFf205U1@mid.uni-berlin.de> defn noob schrieb: > i want to process a large number of images and store their respective > pixels in a matrix. > > what is the mostt efficient way of opening and checking them? > i doubt pygame is made for this purpose :) Au contaraire, it is. http://www.pygame.org/docs/ref/pixelarray.html Diez From ppearson at nowhere.invalid Mon Jul 7 11:29:57 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 7 Jul 2008 15:29:57 GMT Subject: Confused yet again: Very Newbie Question References: <13be8c54-3fa9-4a37-a0e6-45bb019bff7e@a1g2000hsb.googlegroups.com> <593b44b7-9a0a-4665-9926-19890d29eabe@2g2000hsn.googlegroups.com> Message-ID: <6der3lF25815U1@mid.individual.net> On Mon, 7 Jul 2008 05:41:22 -0700 (PDT), mcl wrote: [snip] > My use of classes is because I want two classes one for global > variables and one for global functions. One of the many lovely things about programming in the Python style is that very few things need to be global. When you make something global, you're in effect saying that it has no particular connection to anything else. If it has a connection to something else, then it should probably be combined into an object with that something else. -- To email me, substitute nowhere->spamcop, invalid->net. From asma61 at dsl.pipex.com Mon Jul 21 18:53:36 2008 From: asma61 at dsl.pipex.com (DaveM) Date: Mon, 21 Jul 2008 23:53:36 +0100 Subject: Python Written in C? References: Message-ID: On Mon, 21 Jul 2008 03:18:01 +0200, Michiel Overtoom wrote: >Many major text/word processing programs (Emacs, vi, MS-Word) are also >written in C. I thought Emacs was written in Lisp. DaveM From news at prodata.co.uk Tue Jul 1 09:43:52 2008 From: news at prodata.co.uk (John Dann) Date: Tue, 01 Jul 2008 14:43:52 +0100 Subject: Scope and program structure problems References: <486a210f$0$15472$426a34cc@news.free.fr> Message-ID: <2kck641lali2uenplo8rhp3l9qks3idl03@4ax.com> Many thanks for the repsonse - much appreciated. And sorry - yes I was probably compounding two separate issues here - the GUI one and the variable scope one. Maybe the wxPython list would be the best place to ask more about the GUI side of things. Then actually I can simplify my remaining question quite a lot - I know you've partly answered this already but let me just rephrase this: It must be commonplace to first use a variable or object within one function in a module and then want to use it again - perhaps still with the same value as in the first function - in a second function. So what's the recommended Python way round this? If I was using .Net then I'd be declaring the variables/objects explicitly and could set their scope according to how/where they were declared. But if the Python way is not to declare vars before use then this must create some problems for cross-function use. So it is best to declare such vars at the module level (ie outside of a function) and set eg to Null/None or to assign them with a keyword such as global or static (assuming that concept applies in Python) at first use inside a function or what? JGD From patf at well.com Mon Jul 28 18:33:29 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 15:33:29 -0700 (PDT) Subject: Download excel file from web? References: <6f6vhlFa7anrU1@mid.uni-berlin.de> Message-ID: On Jul 28, 3:29?pm, "Diez B. Roggisch" wrote: > p... at well.com schrieb: > > > > > On Jul 28, 3:00 pm, "p... at well.com" wrote: > >> Hi - experienced programmer but this is my first Python program. > > >> This URL will retrieve an excel spreadsheet containing (that day's) > >> msci stock index returns. > > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > >> Want to write python to download and save the file. > > >> So far I've arrived at this: > > >> [quote] > >> # import pdb > >> import urllib2 > >> from win32com.client import Dispatch > > >> xlApp = Dispatch("Excel.Application") > > >> # test 1 > >> # xlApp.Workbooks.Add() > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > >> # xlBook = xlApp.ActiveWorkbook > >> # xlBook.SaveAs(Filename='C:\\test.xls') > > >> # pdb.set_trace() > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> excel? > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> +25%2C+2008&export=Excel_IEIPerfRegional') > >> # test 2 - returns check = False > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > >> indexperf/excel? > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > >> xlApp = response.fp > >> print(response.fp.name) > >> print(xlApp.name) > >> xlApp.write > >> xlApp.Close > >> [/quote] > > > Woops hit Send when I wanted Preview. ?Looks like the html [quote] tag > > doesn't work from groups.google.com (nice). > > > Anway, in test 1 above, I determined how to instantiate an excel > > object; put some stuff in it; then save to disk. > > > So, in theory, I'm retrieving my excel spreadsheet with > > > response = urllib2.urlopen() > > > Except what then do I do with this? > > > Well for one read some of the urllib2 documentation and found the > > Request class with the method has_data() on it. ?It returns False. > > Hmm that's not encouraging. > > > I supposed the trick to understand what urllib2.urlopen is returning > > to me; rummage around in there; and hopefully find my excel file. > > > I use pdb to debug. ?This is interesting: > > > (Pdb) dir(response) > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > > 'code', ' > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > > 'readline', ' > > readlines', 'url'] > > (Pdb) > > > I suppose the members with __*_ are methods; and the names without the > > underbars are attributes (variables) (?). > > No, these are the names of all attributes and methods. read is a method, > for example. right - I got it backwards. > > > Or maybe this isn't at all the right direction to take (maybe there > > are much better modules to do this stuff). ?Would be happy to learn if > > that's the case (and if that gets the job done for me). > > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty > clear on this: > > """ > This function returns a file-like object with two additional methods: > """ > > And then for file-like objects: > > http://docs.python.org/lib/bltin-file-objects.html > > """ > read( ? [size]) > ? ? ?Read at most size bytes from the file (less if the read hits EOF > before obtaining size bytes). If the size argument is negative or > omitted, read all data until EOF is reached. The bytes are returned as a > string object. An empty string is returned when EOF is encountered > immediately. (For certain files, like ttys, it makes sense to continue > reading after an EOF is hit.) Note that this method may call the > underlying C function fread() more than once in an effort to acquire as > close to size bytes as possible. Also note that when in non-blocking > mode, less data than what was requested may be returned, even if no size > parameter was given. > """ > > Diez Just stumbled upon .read: response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ excel? priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul +25%2C+2008&export=Excel_IEIPerfRegional').read Now the question is: what to do with this? I'll look at the documentation that you point to. thanx - pat From mccredie at gmail.com Mon Jul 14 18:00:32 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 14 Jul 2008 15:00:32 -0700 (PDT) Subject: Bug when using with_statement with exec Message-ID: I think I'm going to create a new issue in Pythons issue database, but I wanted to run it by the news group first. See if I can get any useful feed back. The following session demonstrates the issue: Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> exec "def foo():\n return 0" # no ending newline works fine >>> foo() 0 >>> exec "def foo():\n return 1\n" # with an ending newline works fine >>> foo() 1 >>> from __future__ import with_statement >>> exec "def foo():\n return 2\n" # with an ending newline works fine >>> foo() 2 >>> exec "def foo():\n return 3" # without an ending new line... breaks Traceback (most recent call last): File "", line 1, in File "", line 2 return 3 ^ SyntaxError: invalid syntax If I create a function by using exec on a string and _don't_ end the string with a new-line it will work just fine unless I "from __future__ import with_statement". I can imagine that it is probably a good practice to always end function body's with a new-line, but the requirement should be consistent and the syntax error text could be a _little_ more descriptive (and flag something other than the 2nd to last character). Note that you don't need to be in the interpreter to reproduce this issue. I searched python's issue database and didn't see anything similar to this. If there is already an issue related to this, please point me to it... or better yet, let me know how you found it. Matt From castironpi at gmail.com Thu Jul 24 13:34:40 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 24 Jul 2008 10:34:40 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> Message-ID: <24197170-ac41-4cec-8056-6b0ffbb3483d@x29g2000prd.googlegroups.com> On Jul 24, 11:49?am, "Sebastian \"lunar\" Wiesner" wrote: > Torsten Bronger : > > > > > Hall?chen! > > > Bruno Desthuilliers writes: > > >> Torsten Bronger a ?crit : > > >>> Bruno Desthuilliers writes: > > >>>> [...] > > >>>> How would you handle this case with an implicit 'self' : > > >>>> class Foo(object): > >>>> ? ?pass > > >>>> def bar(self): > >>>> ? ?print self > > >>>> Foo.bar = bar > > >>> Just like this. ?However, the compiler could add "self" to > >>> non-decorated methods which are defined within "class". > > >> What's defined within classes are plain functions. It's actually > >> the lookup mechanism that wraps them into methods (and manage to > >> insert the current instance as first argument). > > > And why does this make the implicit insertion of "self" difficult? > > I could easily write a preprocessor which does it after all. > > Who said, that it would be "difficult"? ?He just corrected your statement > about definitions inside a class, and did not make any assumption about > making "self" implicit. > > I'd assume, that making self implicit wouldn't be that difficult to assume. > But does the fact, that it could easily be done, alone mean, that it > _should_ be done? ?The explicit "self" was a design decision, that can't > really be judged by technical arguments from implementation side. ?Its a > discussion about design from a programmers point of view ... > > -- > Freedom is always the freedom of dissenters. > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? (Rosa Luxemburg) I don't think you can infer from 'explicit is better than implicit' that 'the more explicit the better'. For instance, we don't use: python.callbyvalue.foo( bar, 1, 2 ) python.callbyref.foo2( bar, x, y ) or further: foo( byref bar, byval 1, byval 2 ) foo2( byref bar, byref x, byref x ) though some languages do. Python doesn't do that much implicity, like copying, with the exception of copying strings, which some string functions do, such as lower, replace, strip. (Does slicing return a new string?) What is the most surprisingly implicit behavior in Python? What is the most explicit? From joemystery123 at gmail.com Mon Jul 14 22:08:26 2008 From: joemystery123 at gmail.com (joe shoemaker) Date: Mon, 14 Jul 2008 22:08:26 -0400 Subject: Python pack and unpack question Message-ID: <372de840807141908y501d04baxccc09701d439e555@mail.gmail.com> If you have the following: data = unpack('>L', sock.recv(4)) Does this line of code means that incoming data is big endian and unpack it to endianess of local machine? If local machine is little endian, then big endian is automatically converted to little endian format? thank you. From larry.bates at websafe.com` Wed Jul 16 22:19:53 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 16 Jul 2008 21:19:53 -0500 Subject: Framework recommendations for web service? In-Reply-To: References: Message-ID: Phillip B Oldham wrote: > We're looking at the next phase of development for our webapp, and the > main focus will be to move the core from the app to a web service so > other systems can use the data we've gathered (we're thinking along > the lines of the XML API of Highrise from 37Signals). > > Its possible that we'll extend the service to allow access via vanilla > XML, JSON, and YAML at some point, however we've decided to use > Facebook's Thrift for connectivity initially to support as many techs > as possible and also because our web interface for the app is written > in PHP. > > As we're extracting the core we'll be translating it to Python to make > use of the wealth of well-structured libraries and hopefully make the > project shorter. However, we've hit a snag in choosing a framework > around which to rebuild the service. > > It seems the more popular frameworks (django, turbogears) are all > focused on providing web content. Since our core will be using thrift > to communicate, we don't need templating, feeds, admin pages (django), > or ajax (turbogears). > > What we *do* need is a lightweight, simple framework that will allow > us to create a RESTful interface and throw code together fast. We'll > probably go with SQLObject (unless we can extract the ORM from django > - lazy evaluation would be very useful), and we're just looking for > something fast and light to sit between that and the thrift interfaces > we'll create. > > So, can anyone suggest a lightweight python framework which just does > the essentials? You want thin and fast with little cruft and a focus on interfaces, look at Twisted. -Larry From max at alcyone.com Wed Jul 30 02:36:20 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 23:36:20 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> Message-ID: Russ P. wrote: > On Jul 29, 11:09 pm, Erik Max Francis wrote: > >> I'm getting this sneaking suspicion that you guys are all putting us on. > > As I said in an earlier post, I realize that this would only work if > there were only one copy of "empty" (as there is only one copy of > "None"). I don't know off hand if that is feasible or not. It's only feasible if you change what `is` means for this one bizarre use case, which isn't a good idea. > You reply reeks of the kind of pedantic snobbishness that makes me > sick. Well, if understanding what the `is` operator means is pedantic snobbishness, then hey, go right ahead. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The doors of Heaven and Hell are adjacent and identical. -- Nikos Kazantzakis From mva.led at gmail.com Thu Jul 10 13:20:48 2008 From: mva.led at gmail.com (Manuel Vazquez Acosta) Date: Thu, 10 Jul 2008 13:20:48 -0400 Subject: Determining when a file has finished copying In-Reply-To: <20080710014412.GA29399@cskk.homeip.net> References: <20080710014412.GA29399@cskk.homeip.net> Message-ID: <487644F0.9070906@gmail.com> Cameron Simpson wrote: > On 09Jul2008 15:54, Ethan Furman wrote: >> The solution my team has used is to monitor the file size. If the file >> has stopped growing for x amount of time (we use 45 seconds) the file is >> done copying. Not elegant, but it works. > > If you know that files appear in sequence (a single serial upload > process, not multiple uploaders) you can augument this with a check > that an additional file has started to upload, ergo the current file > has finished. Of course, only you can decide if this might be relied upon. > > Cheers, Hum, what about the last file in the sequence? I think polling file's size maybe a good indicator, as Ethan proposed. Best regards, Manuel. From larry.bates at websafe.com` Tue Jul 15 14:46:14 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 13:46:14 -0500 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: Victor Noagbodji wrote: > Hello, > > what's the difference between these two statement? And which one should one use? > if name ... Will be false if: name is an integer == 0 name is a float == 0 name is an empty string name is an empty list name is an empty dictionary There are others, but you get the idea. If name is not None: Is false only if name is not None but will be true for all the others. -Larry From jr9445 at ATT.COM Tue Jul 1 11:06:49 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Tue, 1 Jul 2008 10:06:49 -0500 Subject: How make regex that means "contains regex#1 but NOT regex#2" ?? In-Reply-To: References: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Reedick, Andrew > Sent: Tuesday, July 01, 2008 10:07 AM > To: seberino at spawar.navy.mil; python-list at python.org > Subject: RE: How make regex that means "contains regex#1 but NOT > regex#2" ?? > > Match 'foo.*bar', except when 'not' appears between foo and bar. > > > import re > > s = 'fooAAABBBbar' > print "Should match:", s > m = re.match(r'(foo(.(?!not))*bar)', s); > if m: > print m.groups() > > print > > s = 'fooAAAnotBBBbar' > print "Should not match:", s > m = re.match(r'(foo(.(?!not))*bar)', s); > if m: > print m.groups() > > > == Output == > Should match: fooAAABBBbar > ('fooAAABBBbar', 'B') > > Should not match: fooAAAnotBBBbar > Fixed a bug with 'foonotbar'. Conceptually it breaks down into: First_half_of_Regex#1(not Regex#2)(any_char_Not_followed_by_Regex#2)*Second_half_of_Regex#1 However, if possible, I would make it a two pass regex. Match on Regex#1, throw away any matches that then match on Regex#2. A two pass is faster and easier to code and understand. Easy to understand == less chance of a bug. If you're worried about performance, then a) a complicated regex may or may not be faster than two simple regexes, and b) if you're passing that much data through a regex, you're probably I/O bound anyway. import re ss = ('foobar', 'fooAAABBBbar', 'fooAAAnotBBBbar', 'fooAAAnotbar', 'foonotBBBbar', 'foonotbar') for s in ss: print s, m = re.match(r'(foo(?!not)(?:.(?!not))*bar)', s); if m: print m.groups() else: print == output == foobar ('foobar',) fooAAABBBbar ('fooAAABBBbar',) fooAAAnotBBBbar fooAAAnotbar foonotBBBbar foonotbar ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA621 From robert.kern at gmail.com Mon Jul 7 19:59:48 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 07 Jul 2008 18:59:48 -0500 Subject: complex representation In-Reply-To: References: Message-ID: DSM wrote: > From the nothing-is-so-trivial-it's-not-worth-a-usenet-post file: > > Shouldn't the default representation of complex numbers be like that of > floats? That is, have a decimal point? > > >>> 1 > 1 > >>> 1.0 > 1.0 > >>> 1j > 1j > >>> 1.0j > 1j > >>> 1.0+1.0j > (1+1j) > > > In the relevant bit of floatobject.c, there's a comment explaining that > 1.0 isn't accidental: > > /* Subroutine for float_repr and float_print. > We want float numbers to be recognizable as such, > i.e., they should contain a decimal point or an exponent. > However, %g may print the number as an integer; > in such cases, we append ".0" to the string. */ > > ISTM the same reasoning applies equally to complex numbers. Not necessarily. The reason that having floats always have a decimal point is desirable is to ensure roundtripping through eval(repr(x)). The j is sufficient for complexes. There are no complex integers to confuse it with. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From Russ.Paielli at gmail.com Wed Jul 30 03:18:48 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 30 Jul 2008 00:18:48 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> Message-ID: <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> On Jul 30, 12:03 am, Heiko Wundram wrote: > Am Mittwoch, 30. Juli 2008 08:30:48 schrieb Russ P.: > > > On Jul 29, 11:09 pm, Erik Max Francis wrote: > > > I'm getting this sneaking suspicion that you guys are all putting us on. > > > As I said in an earlier post, I realize that this would only work if > > there were only one copy of "empty" (as there is only one copy of > > "None"). I don't know off hand if that is feasible or not. > > > You reply reeks of the kind of pedantic snobbishness that makes me > > sick. > > I can understand (and pretty much sympathise) that you get this kind of reply, > simply because the point you and Carl Banks (formulated somewhat differently) > put up has been answered again and again (in this thread), and I can only > repeat it once more: > > __nonzero__(), i.e. the "cast" to boolean, is THE WAY to test whether a > container is empty or not. Like this design decision, or don't like it, but > the discussion is not going to go anywhere unless you concede that there is a > (very explicit!) way to test for non-emptiness of a container already, and > you're currently simply discussing about adding/using syntactic sugar > (different means of expressing the test) to suit your own personal taste > better. Anyway, check the documentation for __nonzero__(): if the object > doesn't implement that, but implements __len__(), the interpreter "replaces" > the __nonzero__() test by __len__()>0, so I guess someone in the design > department must've seen it logical for the truth value of a container to > express the test "len(x)>0" at some point in time to make this interpretation > for the truth value of a container. > > There cannot be an argument about missing/misplaced functionality (that's what > you make it sound like), if the functionality for doing what you want to do > is there and you simply don't like the syntax, which I can somewhat relate to > because style is a personal thing, even though I don't see either points made > by you or Carl Banks, because implicit casting to bool is so common in pretty > much every programming language to test for "truth" of an object, and IMHO > it's completely logical to extend that idea to containers to mean > empty/non-empty. > > Eric Max Francis tried to explain why your syntactic "enhancement" would come > at a much greater price than its worth, and he's absolutely right in that, as > it's an abuse of the "is" operator, but again, that's a somewhat different > point. It changes nothing about the fact that all this discussion centers > around something that is a non-point, but simply a matter of personal taste. > > -- > Heiko Wundram Oh, Lordy. I understand perfectly well how boolean tests, __len__, and __nonzero__ work in Python. It's very basic stuff. You can quit patronizing me (and Carl too, I'm sure). The point that you seem to be missing, or refuse to acknowledge for some reason, is that "if x" can be mistakenly applied to any object when the programmer thinks that x is a list -- and the programmer will receive no feedback on the error. I have made errors like that, and I could have saved some time had I used an "empty" method that only applies to a list or other sequence. Is that an important issue? I don't know. I'm not claiming it is. But you cannot just sweep it away as nothing. From vinay_sajip at yahoo.co.uk Sun Jul 20 09:51:36 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Sun, 20 Jul 2008 06:51:36 -0700 (PDT) Subject: Unusual Exception Behaviour References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> <8904.90077804333$1216313689@news.gmane.org> <006001c8e831$5c1487b0$143d9710$@rawlins@thinkbluemedia.co.uk> <1214.94685668058$1216317006@news.gmane.org> <1e6def2a-9c44-419e-a450-5fe596c5e3c0@j1g2000prb.googlegroups.com> Message-ID: <1317c3ed-1bfe-4fc2-b2f2-9dba13a28b04@m3g2000hsc.googlegroups.com> On Jul 18, 5:12 pm, "Robert Rawlins" wrote: > > This is really quite frustrating as I'd much rather use a conf file than > work this programmatically. I get the feeling that it's because in the > config file I was not attaching any handlers to the root logger, but I don't > know. > There's no reason why not having a handler for the root logger would cause any particular problem. For example, the following script: #- start of logconftest.py ------------------ import logging, logging.config logging.config.fileConfig("log.conf") app_logger = logging.getLogger("application") sa_logger = logging.getLogger("sqlalchemy") loggers = [app_logger, sa_logger] def func1(): raise Exception("Exception from func1") def func2(): raise TypeError("TypeError from func2") def func3(): raise ValueError("ValueError from func3") funcs = [func1, func2, func3] for x in range(10): try: f = funcs[x % 3] f() except Exception, e: loggers[x % 2].exception("%d. Problem in %s", x, f.__name__) #- end of logconftest.py -------------------- together with the following configuration file (almost the same as yours): ;-- start of log.conf ----------------------- [loggers] keys=root,application,sqlalchemy [handlers] keys=hand01,hand03 [formatters] keys=form01 [logger_root] level=DEBUG handlers= [logger_application] level=DEBUG handlers=hand01 qualname=application [logger_sqlalchemy] level=DEBUG handlers=hand03 qualname=sqlalchemy [handler_hand01] class=handlers.RotatingFileHandler level=DEBUG formatter=form01 args=('application.log', 'a', 800000, 5) [handler_hand03] class=handlers.RotatingFileHandler level=DEBUG formatter=form01 args=('sqlalchemy.log', 'a', 800000, 5) [formatter_form01] format=%(asctime)s %(filename)s %(lineno)d %(levelname)-8s %(message)s datefmt= class=logging.Formatter ;-- end of log.conf ------------------------- gives the following output: -- start of application.log ----------------- 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 0. Problem in func1 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 11, in func1 raise Exception("Exception from func1") Exception: Exception from func1 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 2. Problem in func3 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 17, in func3 raise ValueError("ValueError from func3") ValueError: ValueError from func3 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 4. Problem in func2 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 14, in func2 raise TypeError("TypeError from func2") TypeError: TypeError from func2 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 6. Problem in func1 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 11, in func1 raise Exception("Exception from func1") Exception: Exception from func1 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 8. Problem in func3 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 17, in func3 raise ValueError("ValueError from func3") ValueError: ValueError from func3 -- end of application.log ------------------- -- start of sqlalchemy.log ------------------ 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 1. Problem in func2 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 14, in func2 raise TypeError("TypeError from func2") TypeError: TypeError from func2 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 3. Problem in func1 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 11, in func1 raise Exception("Exception from func1") Exception: Exception from func1 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 5. Problem in func3 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 17, in func3 raise ValueError("ValueError from func3") ValueError: ValueError from func3 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 7. Problem in func2 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 14, in func2 raise TypeError("TypeError from func2") TypeError: TypeError from func2 2008-07-20 14:47:05,625 logconftest.py 26 ERROR 9. Problem in func1 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 11, in func1 raise Exception("Exception from func1") Exception: Exception from func1 -- end of sqlalchemy.log -------------------- which is, from a quick scan, the expected result - all the expected exceptions are thrown. Note the absence of any handlers on the root logger. Regards, Vinay Sajip From roy at panix.com Thu Jul 3 22:26:57 2008 From: roy at panix.com (Roy Smith) Date: Thu, 03 Jul 2008 22:26:57 -0400 Subject: Testing for an empty list References: <18268092.post@talk.nabble.com> Message-ID: In article , claird at lairds.us (Cameron Laird) wrote: > In article , > Matthew Fitzgibbons wrote: > >Alexnb wrote: > >> Okay this is a simple question I just don't know how. If I have a list, > >> say: > >> > >> funList = [] > >> > >> and after a while something possible should have been appended to it, but > >> wasn't. How can I test if that list is empty. > > > >if not funList: > > do_something() > . > . > . > It's also perfectly legitimate--and arguably even more > precise--to write > > if funList == []: > do_something() Any of these will be true for an empty list and false for a non-empty list: not funList len(funList) == 0 funList == [] Where they differ is how they behave for values of funList which are not lists. For example, if you did funList = (), then the first two would be true and the last one false. If you did funList = 0, the first and last would be true, and the middle one would raise an exception. The point is that if you're *sure* the item in question is going to be a list, then any of them are pretty much as good as any other. If it's a parameter that's being passed into a routine, so you can't be sure what type it is, then you should be thinking a little harder about how flexible you want to be. From g.threepwood at gmail.com Thu Jul 17 17:48:45 2008 From: g.threepwood at gmail.com (C Martin) Date: Thu, 17 Jul 2008 14:48:45 -0700 (PDT) Subject: Using Tcl extensions with Python? Message-ID: <6f09cdf7-1156-4f41-af5f-c8e5b99eab2d@b1g2000hsg.googlegroups.com> How do you setup a Tcl extension to be accessible through Python? I understand that I'll have to use native Tcl calls to use it (tk.call() etc), but I can't figure out where to put the files or how to initialize them so I can call them. The package I would like to use is TkPNG: http://www.muonics.com/FreeStuff/TkPNG/ Thanks. From gnuarm at gmail.com Fri Jul 11 13:12:44 2008 From: gnuarm at gmail.com (rickman) Date: Fri, 11 Jul 2008 10:12:44 -0700 (PDT) Subject: spam References: <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> Message-ID: <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> spam From hyh_david at hotmail.com Thu Jul 17 15:18:15 2008 From: hyh_david at hotmail.com (hyh_david at hotmail.com) Date: Thu, 17 Jul 2008 12:18:15 -0700 (PDT) Subject: wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal Message-ID: paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal ... From rogerkolsson at yahoo.co.uk Sun Jul 27 05:02:46 2008 From: rogerkolsson at yahoo.co.uk (rogerkolsson at yahoo.co.uk) Date: Sun, 27 Jul 2008 02:02:46 -0700 (PDT) Subject: Rifle & Ammunition Retail Store - Sportsman, Wildlife and Outdoor Supply Message-ID: Giuen Interpose & Outright Company ? Huntingrifle, Ammunition, Optics, Navigation ? Surplus Rifle Sale ? Pre-Owned Rifles ? Precision Rifle - Pistol A New Generation Outright Company begun in 2008 the funding for a battlefield data link that projected data onto a computer screen inside for example vehicles and inside the tanks. A system mated up with vehicle sets permanent to the base top-of-the-line included in the Inter-Vehicle Information System, a simple system for trading data, it presented the crew with a comprehensive overview of the battlefield, and converted hard-won reconnaissance information into general knowledge in a matter of seconds. No longer was data on a developing engagement limited to a harried and distracted unit commander. Now sergants knew everything the colonel did, and information was still the most valuable commodity known to man. The funding for that equipment on the agent exchange management for the obvious reason that it was too expensive to transport it all back and forth was yet not in harbour to the full at the end of 2007, however it still crapped out in a hurry to bring great benefit for the coming. Machines that did things at the bidding of others, to be thrown away when convenient and mass produce of such systems is neither anymore the mission he would welcome anywhere at all, this is a system that could work in helicopters with skilled computers in the modern age as well. He might have some position in the expanding unit government, security or intelligence, probably, with a comfortable office and a sizable stipend, able finally to settle down in peace and safety. However it takes to make a successful launch, and anyway with the newest variant of the system which meet the proper protective measures with a computerized database, divisions aided as always. Perhaps, it didn?t really matter. Conditions was good enough that such a person would be spotted. They will make their moves to continue their missions full of assurance to all. Their first mission briefing to request for support was just now getting started in a big way in advance of the main force in traditional working relationship on national defense and allied parnerships more substantial. The security detatchment made official was expect for the information in detailed reports and heading more precise the exact performance of every subsystem. Exactly what they?d been designed to do can neverthless be fully briefed in other than character and integrity at this time on industry routinely produced all manner of specialized products most for strategic partnership respectfully request information. Hummer H2 2004 at Dealership in Sweden Giuen Holding Ltd. Int. Call: +46 (0) 705474830 Hollywood NetBook ? Shopping Astore Sports http://astore.amazon.com/entertainmens-20 International Yatcht Trade http://www.rapidsellers.com/molsson3/ Janine Cabriore Powertriumph www.rapidsellers.com/molsson3/contact.asp Giuen Holding Ltd.? Export & Import Public Form http://publishing.yudu.com/Freedom/Akx6s/G1public/ Munifus Landmark Estate ? Prospect: http://publishing.yudu.com/Freedom/Ak8i8/DevelopmentProject/ Giuen Interpose & Outright Company ? Security ? Hunting - Equipment http://www.impactguns.com/cgi-bin/affiliates/clickthru.cgi?id=Outright From larry.bates at websafe.com` Mon Jul 14 21:04:14 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 14 Jul 2008 20:04:14 -0500 Subject: Method behavior for user-created class instances In-Reply-To: <42433fcd-fcdc-4f42-a427-c28241734b7c@z66g2000hsc.googlegroups.com> References: <42433fcd-fcdc-4f42-a427-c28241734b7c@z66g2000hsc.googlegroups.com> Message-ID: crazychimp132 at gmail.com wrote: > Greetings. > > I am looking for a way to achieve method behavior for a class I > created. That is, it has a __call__ method, so can be called like a > function. But I also want it to be treated as a method when it appears > in a class body. > > Eg. > > class foo: > def __call__(self, inst): pass > > class bar: > meth = foo() > > such that bar().meth() will not raise an exception for too few > arguments (because the inst argument in foo.__call__ is implicitly set > to the bar instance). I know this has to do with writing the __get__ > method of foo, but I am wondering if there is perhaps some class I can > just inherit from to get the proper __get__, which behaves identically > to that of regular Python functions. The need for this arises out of > the implementation of a function decorator as a class. > > Thanks. While it is not clear "why" you would want this, I believe this works. If not, take a look at staticmethods or classmethods, they might work for you. >>> class foo(object): ... def __call__(self, inst): ... print "foo.__call__", inst ... >>> class bar: ... def __init__(self): ... self.foo = foo() ... self.meth = self.foo.__call__ ... >>> b = bar() >>> b.meth(1) foo.__call__ 1 -Larry From jonas at codeazur.com.br Thu Jul 3 22:30:22 2008 From: jonas at codeazur.com.br (Jonas Galvez) Date: Thu, 3 Jul 2008 23:30:22 -0300 Subject: ANN: XML builder for Python In-Reply-To: <486D48BF.3050007@livinglogic.de> References: <486C5CA1.3080105@behnel.de> <486C5D63.5030407@behnel.de> <486D22CF.3000505@behnel.de> <486D48BF.3050007@livinglogic.de> Message-ID: <10df03a30807031930h2b71eb9bu811fc92c8e366037@mail.gmail.com> Walter D?rwald wrote: > Of course the node constructor could append the > node to the currently active element. However there > might be cases where you want to do something else > with the newly created node, so always appending the > node is IMHO the wrong thing. Unless you're using it as a templating engine of sorts, much like Ruby's builder used in Rails. Which is exactly what I'm trying to get at. I don't want to store the tree in any way or be able to modify it afterwards, I just want to generate the XML as the block is executed. Using ElementTree as suggested previously might be a good solution if you want to preserve what you've generated, tho. --Jonas Galvez From martin at v.loewis.de Fri Jul 4 16:49:58 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 04 Jul 2008 22:49:58 +0200 Subject: Can't get Python for Windows to run In-Reply-To: References: <486E4125.5080201@timgolden.me.uk> Message-ID: <486e8cf6$0$5679$9b622d9e@news.freenet.de> > Is it worth flagging as an issue somewhere the fact that the pywin > installer assumes a particular structure for the start menu No. This is the first time in several years that this was reported, and chances that this gets fixed in the upcoming years are very low, unless a patch gets contributed. (IOW, I couldn't care less about implementing it myself, and find installers annoying that ask too many questions). In any case, try installing with msiexec /i 'ProgramMenuFolder=C:\Documents and Settings\All Users\StartMenu\Programs\Programming' or some such. Regards, Martin From xng at xs4all.nl Mon Jul 21 10:11:03 2008 From: xng at xs4all.nl (Martin P. Hellwig) Date: Mon, 21 Jul 2008 16:11:03 +0200 Subject: Python Written in C? In-Reply-To: <488473b7$0$3470$426a74cc@news.free.fr> References: <488473b7$0$3470$426a74cc@news.free.fr> Message-ID: <488498f0$0$15075$e4fe514c@dreader28.news.xs4all.nl> Bruno Desthuilliers wrote: > giveitawhril2008 at gmail.com a ?crit : > (snip clueless nonsense) > > Surely a troll... No one on earth can be *that* clueless. I disagree he has upper management written all over him. -- mph From mmaccana at au1.ibm.com Wed Jul 23 01:47:18 2008 From: mmaccana at au1.ibm.com (Mike MacCana) Date: Wed, 23 Jul 2008 15:47:18 +1000 Subject: Proper way to query user and group database on a Unix host? Message-ID: <1216792038.7380.7.camel@mmaccana-laptop> Hi folks, What's the proper way to query the passwd and group database on a Unix host? I'd like to fetch the users in a group (obviously from name services), but my many varied searches can't find any reference of someone ever looking up users on a Unix system, just NT. Weird, I know. Currently I'm calling the getent command, which works well enough, but surely there's a more Pythonic method of looking up OS user and group data ... ## Get the full group database entry, leave just the user list, and split the list on comma groupname=users groupsusers = commands.getoutput('getent group '+groupname).split(':',-1)[3].split(',') Cheers, Mike ________________________________________________ Mike MacCana Technical Specialist Australia Linux and Virtualisation Services IBM Global Services Level 14, 60 City Rd Southgate Vic 3000 Phone: +61-3-8656-2138 Fax: +61-3-?8656-2423 Email: mmaccana at au1.ibm.com From mail at timgolden.me.uk Tue Jul 22 04:09:19 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 22 Jul 2008 09:09:19 +0100 Subject: Missing sqlite3.h Error when Building Debug Python -- Windows Vista In-Reply-To: References: <048b8df4-8468-47a1-ae15-d84ca9d43e0a@y38g2000hsy.googlegroups.com> Message-ID: <488595AF.1070205@timgolden.me.uk> Bev in TX wrote: > Thanks for letting me know about this. I installed Subversion and > tried to make the build work like that, but it fails. [... snip problems ...] I'm afraid I'm not using VS 2005, nor Vista, nor 64-bit, so I hope someone else can help. If you don't get any take-up here try the python-win32 list; there may be people there who don't follow this (rather higher volume) list. TJG From davideyork at gmail.com Fri Jul 25 20:34:09 2008 From: davideyork at gmail.com (David York) Date: Fri, 25 Jul 2008 17:34:09 -0700 Subject: Porting python to C++ Message-ID: <38c9cdb10807251734v3a827aaah86c379ebda92bc9a@mail.gmail.com> Hello, I'm a longtime lurker of python-list, python-C++ and a couple of others. I have a commercial project being prototyped in Python, brought to a very fine level of completion and which needs to be ported to C++. I would like to outsource this project - does anybody have any experience with Python -> C++ porting that could give advice? Does anybody have any experience with outsourcing such projects? Any experience (or being redirected to a more appropriate forum) would be greatly appreciated. I'm currently thinking about breaking the program down into pieces inside unit tests then taking care of them via rentacoder.com but having no experience I don't know if this idea is good or not. David -------------- next part -------------- An HTML attachment was scrubbed... URL: From elessar at nienna.org Thu Jul 31 13:59:11 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Thu, 31 Jul 2008 11:59:11 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <00a121b4$0$20313$c3e8da3@news.astraweb.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <00a121b4$0$20313$c3e8da3@news.astraweb.com> Message-ID: <4891FD6F.8090604@nienna.org> Steven D'Aprano wrote: > On Wed, 30 Jul 2008 09:23:05 -0600, Matthew Fitzgibbons wrote: > >> If you're expecting a list (and only a list) >> then your point makes sense. 'if x' can get you into trouble if you >> _don't_ want its polymorphism. > > "if x" is hardly unique in that way. If you're expecting a list, and only > a list, "len(x) != 0" will get you in trouble if somebody passes a string > or a dictionary. I don't see any reason why we should single out "if x" > as dangerous in the face of invalid types. With the exception of the "is" > and "is not" operators, nothing in Python is guaranteed to work with any > imaginable object. Even print can fail, if the object's __str__ method > raises an exception. > > >> Although, if my function is expecting a list, my preference is to do: >> >> if not isinstance(x, list): >> raise SomeMeaningfulException() >> # do stuff with the list >> >> I put my type checking at the top of the function, so readers can >> reference it easily. > > And thus you break duck-typing and upset anybody who wants to pass a > sequence that doesn't inherit directly from list. > > There are other (and arguably better, although more labour-intensive) > techniques for defensive programming that don't break duck-typing. You > can google for Look Before You Leap and Easier To Ask Forgiveness Than > Permission for more information. Alex Martelli has a fine recipe in the > Python Cookbook -- search for the recipe "Checking if an object has the > necessary attributes". > > But in a nutshell, here's a toy example: > > def spam(seq): > try: > seq.append > seq.extend > seq[0] = seq[0] > except Exception: > raise TypeError("argument isn't sufficiently sequence-like") > # No exceptions expected from here on > seq.append(seq[0]) > seq.extend([1,2,3]) > seq[0] = "spam" > > > > Yes, I know it breaks duck typing, which is why I do it only very rarely, and never with e.g. sequence types. If I use ifinstance for type checking, it's because I need some _very_ specific class, almost always one that I wrote. My more usual use case for ifinstance is to figure out how to handle a particular object using introspection. That said, your example is still helpful. It's a good approach, and I should use it more often. Although I'd also lean toward hasattr and iscallable and ordinary ifs instead of the try ... except where possible. Depending on what you put in the try ... except, you risk masking legit exceptions. Ahhh, Programing. Where no rule of thumb seems to last five minutes. -Matt From malaclypse2 at gmail.com Tue Jul 29 11:05:31 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 29 Jul 2008 11:05:31 -0400 Subject: How do I include a shell variable in my script? In-Reply-To: References: Message-ID: <16651e80807290805j11ac4d31v11c7658c7d29b90d@mail.gmail.com> On Tue, Jul 29, 2008 at 10:53 AM, laredotornado wrote: > Hi, > > I'm running a Python script on a Solaris 9 machine, invoking the > Python script from ksh, if that matters. There is an enviornment > variable, $JAVA_HOME, that I would like to include in my script, > replacing "/path/to/java/home'" with the value of $JAVA_HOME. > > java_home='/path/to/java/home' import os java_home = os.environ['JAVA_HOME'] -- Jerry From siona at chiark.greenend.org.uk Wed Jul 9 11:44:48 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 09 Jul 2008 16:44:48 +0100 (BST) Subject: numeric emulation and __pos__ References: <92e3ea9f-5745-4072-9d09-7c14fd335828@f36g2000hsa.googlegroups.com> Message-ID: Ethan Furman wrote: >Anybody have an example of when the unary + actually does something? I've seen it (jokingly) used to implement a prefix increment operator. I'm not going to repeat the details in case somebody decides it's serious code. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From animator333 at gmail.com Sun Jul 27 09:14:48 2008 From: animator333 at gmail.com (King) Date: Sun, 27 Jul 2008 06:14:48 -0700 (PDT) Subject: Read .txt file like .py file Message-ID: <90f13013-bb20-4224-ac58-02947f3f9358@i24g2000prf.googlegroups.com> I have a text file and contents are: Help=""" Code is written by xteam. """ value = 0.0 How do I read this file like python syntax. What I mean is first readline operation should return complete declaration of 'Help' variable. If I evaluate this string then it should create a 'Help' variable with it's value. May be something related to 'parsing' would help but I don't know much. From bdesth.quelquechose at free.quelquepart.fr Sun Jul 27 14:07:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Jul 2008 20:07:35 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <874p6f5m5u.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <32e12408-fc9f-4eb4-8b9d-fb7fa69bd2fc@f36g2000hsa.googlegroups.com> <87zlo7y2wn.fsf@physik.rwth-aachen.de> <48889a72$0$25165$426a74cc@news.free.fr> <874p6f5m5u.fsf@physik.rwth-aachen.de> Message-ID: <488cd55e$0$21184$426a34cc@news.free.fr> Torsten Bronger a ?crit : > Hall?chen! > > Bruno Desthuilliers writes: > >> Torsten Bronger a ?crit : (snip) >>> One could surely find ways to realise this. However, the design >>> goal should be: Make the frequent case simple, and the rare case >>> possible. >> Given the (more and more prominent) use of decorators, metaclasses >> and other meta-programming techniques in Python, I'm not sure the >> cases where you really need access to Python's object model inners >> are that "rare". Not in my code at least. > > What does "not rare" mean for you? More than once a week. From ptmcg at austin.rr.com Sat Jul 12 08:46:03 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 12 Jul 2008 05:46:03 -0700 (PDT) Subject: Changing self: if self is a tree how to set to a different self References: Message-ID: <0101e32d-bba2-4821-aaf4-97944c9d8f3a@f63g2000hsf.googlegroups.com> On Jul 12, 6:18?am, Bart Kastermans wrote: > This uses the function: > > def NoneOr (tree, mem_function, *arguments): > ? ? """ if tree is not None then tree.mem_function (arguments). """ > ? ? if tree == None: > ? ? ? ? return None > ? ? else: > ? ? ? ? return getattr (tree, mem_function) (*arguments) > > Bart This code reads wrongly to me on a couple of levels. First, I think the general computing consensus is that if-then-else is more readable/ logical if you assert the positive condition for the then-part, and put the alternative condition in the else-part. My impression is that the non-None-ness of tree is actually the positive assertion, as in: if tree != None: return getattr(tree, mem_function)(*arguments) else: return None Next, the more Pythonic test for None-ness is most clearly written as: if tree is not None: as there is only one None, and the identity "is not" check is simpler/ faster for Python to execute (and possibly - and more importantly - also simpler for readers to follow, as this reads more like a continuous sentence instead of a mixture of prose and mathematical notations). One might even suggest you could further abbreviate this test to: if tree: and get the same behavior. I would quibble with that, however, that this merely exploits a side-effect of Python, in which None values are always False, and *most* non-None values are True. But Python also interprets many non-None values as False, such as 0, or empty containers, such as lists, tuples, dicts, and strings. In fact, your tree class sounds like a structured container to me, and it would be reasonable to assume that you might implement __nonzero__ (pre-Python 2.6) or __bool__ (Python 2.6 and later) in your class to return False for an empty tree, which would still be a valid and not-None tree. You should be able to invoke methods on an empty tree just as one can call "".upper(). So for this case, I would stick with the more explicit "if tree is not None". Another Pythonicity is that methods will *always* return a value, even if you do not write a return statement - and that value is None. So if you assert the tree-not-None as the if condition, you don't even need the else part. You could just write: def NoneOr (tree, mem_function, *arguments): """ if tree is not None then tree.mem_function (arguments). """ if tree is not None: return getattr(tree, mem_function)(*arguments) Surprisingly, this actually reads almost verbatim from your doc string! So I would guess that this implementation is probably closest to your original intent for this method. Still, for explicitness'- sake, you might want to keep the else-part, just to make your intent clear and spelled-out. (Complaining about the presence or absence of this bit of code goes beyond "persnickety"...) Note that the original code is perfectly valid Python, and will run just as efficiently as any of my alternative suggestions, which is why I enclosed my comments in 'persnickety' (http:// dictionary.reference.com/browse/persnickety) tags. -- Paul From squishywaffle at gmail.com Thu Jul 31 11:27:14 2008 From: squishywaffle at gmail.com (squishywaffle at gmail.com) Date: Thu, 31 Jul 2008 08:27:14 -0700 (PDT) Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> <6fe0scFaus40U1@mid.uni-berlin.de> <6bc8bc07-eab0-4303-b8a4-c9470f96038d@c65g2000hsa.googlegroups.com> <6fe1n2Faus40U3@mid.uni-berlin.de> Message-ID: On Jul 31, 10:47?am, "Diez B. Roggisch" wrote: > I take the freedom to do so as I see fit - this is usenet... Fine, then keep beating a dead horse by replying to this thread with things that do nobody any good. It seems like there are a lot better way to waste time, though. The Python/C API can get me back further without reliance on third- party libraries than ctypes. It also isn't subject to the quirks that ctypes is on platforms other than Windows (the target application runs on Windows, Mac, and eventually Linux once the original distributor has drivers for the device). I'm not even sure ctypes could load the lib/driver the distributor packaged. So really, I appreciate the option in ctypes, it's good stuff. But it's not for this project. Once again, the original question stands for anyone who has experience with the Python/C API callbacks. From lanny at freshells.ch Thu Jul 24 11:02:00 2008 From: lanny at freshells.ch (Lanny) Date: Thu, 24 Jul 2008 08:02:00 -0700 Subject: Raw Strings (I Think) Message-ID: I've used glob.glob to get a list of files in a directory and now I want to use os.system to execute one of those files, the problem is that python automatically puts a escape charater infront of the back slashes so the os.system gets X:\\####\\####\\ and is useless, I think I need to convert my string to a raw string but I don't know how. -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- From malaclypse2 at gmail.com Wed Jul 23 15:26:52 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 23 Jul 2008 15:26:52 -0400 Subject: Using variables across modules In-Reply-To: References: <855136ce-6c70-40ac-a462-dc0bbfa1fc3a@b2g2000prf.googlegroups.com> <121c5161-9485-4d6a-a447-9f9dd4227bac@d77g2000hsb.googlegroups.com> Message-ID: <16651e80807231226v5efded9cwcf4b23c185cc88de@mail.gmail.com> On Wed, Jul 23, 2008 at 3:06 PM, Aaron Scott wrote: > ... which is what I was expecting, but not what I want. Obviously, > each import is creating its own instance of the variable. What I need > is a way to change myvar from within "bar.py" so that PrintVar() > returns the new value, even though it's in a different module. That's what happens when you do "from variables import *", it creates those names in the local namespace. If you just import the module, then you can do what you want. For example: ---variables.py--- myvar = 5 print myvar ---foo.py--- import variables def PrintVar(): print variables.myvar ---bar.py--- import variables, foo print variables.myvar variables.myvar = 2 print variables.myvar foo.PrintVar() ---output from running bar.py--- 5 5 2 2 For more on how the import statement works, see the library reference (http://docs.python.org/ref/import.html), or maybe this article on the various ways you can import things and the differences between them (http://effbot.org/zone/import-confusion.htm) -- Jerry From arockstar at gmail.com Fri Jul 18 15:17:33 2008 From: arockstar at gmail.com (arockstar at gmail.com) Date: Fri, 18 Jul 2008 12:17:33 -0700 (PDT) Subject: Trickiness with unittesting Message-ID: Basically, I'm trying to implement a setUp() and TearDown() for a python TestSuite (as opposed to an individual test within the suite). Sort of. I have a few different test suites (call them SuiteA, SuiteB,...). For one of the test suites (SuiteA), I need to execute a bit of code (say startFoo()) before the first test in SuiteA runs, and once when the last test of SuiteA finishes (endFoo()). Making this even trickier is that the testing framework combines the different suites (SuiteA, SuiteB) as well as individual tests into master test suite which my testrunner then runs. Also complicating matters is the fact that the testing framework can run an *individual* test from any TestSuite: in that case, if I'm running SuiteA.test1, I'd want to call startFoo() and endFoo() as well. I could use a global variable as a flag and see if it's been set during the setUp() method of the test cases (which would allow me to call startFoo() once when tests from SuiteA are run from the master suite), but that doesn't help me with calling endFoo() when the tests from SuiteA finish. Plus, it's not very elegant. So: Given a master test suite comprised of a bunch of different tests from different suites, I need to call startFoo() before tests from SuiteA are run, and stopFoo() after all the tests from SuiteA have finished running. From deets at nospam.web.de Sun Jul 27 10:57:14 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2008 16:57:14 +0200 Subject: Rant (was Re: x*x if x>10 In-Reply-To: <6f3g8rF9gfj0U1@mid.uni-berlin.de> References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3g8rF9gfj0U1@mid.uni-berlin.de> Message-ID: <6f3gmaF9moqsU1@mid.uni-berlin.de> Marc 'BlackJack' Rintsch schrieb: > On Sun, 27 Jul 2008 16:41:19 +0200, Diez B. Roggisch wrote: > >> DaveM schrieb: >>> Getting back to the >>> list concatenation, I finally found the itertools.chain command which >>> is the most compact and fastest (or second fastest by a trivial amount, >>> I can't remember which). Along the way, I must have tried/used half a >>> dozen methods, ...which brings me back my initial PERL comment. There's >>> more than one way to do it in Python, too. >> Any non-trivial task has that property. I don't know enough perl to have >> an example ready that shows something that python has only one way of >> doing and perl has several. >> >> But I *do* know that taking the python zen literally is fruitless. > > I think it should be taken more literally than the wrong reduction to > "there should be only one way". People tend to forget "obvious" and > "preferably" all the time. Good point. The OP found the obvious way of extending. I wonder what his reasons were to abandon it. Diez From tjreedy at udel.edu Thu Jul 24 21:02:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jul 2008 21:02:48 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <20b5e80c-ba2a-4cd0-9a6a-beeef6134839@r35g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <1de235af-4245-41aa-9091-bb7b112f4ce5@n33g2000pri.googlegroups.com> <20b5e80c-ba2a-4cd0-9a6a-beeef6134839@r35g2000prm.googlegroups.com> Message-ID: Jordan wrote: > I wish in retrospect I'd had the time, patience and focus to edit the > initial post to make it more measured and less inflammatory, because > its clear the tone I will ignore that. > detracts from the argument I'm making, which I feel still stands. class C(): def f(): a = 3 You made a complaint and an incomplete proposal identical to what others have proposed. But here is where the idea always sinks. Suppose as you propose 'self' is added to the arg list. How is a mindless algorithm to decide whether to change a to 'self.a' to make it an attribute or leave it alone as a local variable? Or would you abolish local vars from methods (which would slow them down)? As near as I can see, any concrete detailed implementable proposal would be a more major change in Python or its implementation than 'down-with-self'ers usually admit. If the argument you refer to is instead that 'Explicit is better than Implicit' is a bit overused and inadequate as a technical response, then I agree. But excuse me for being unsure ;-). Terry Jan Reedy From paddy3118 at googlemail.com Fri Jul 4 12:40:47 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 4 Jul 2008 09:40:47 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> On Jul 4, 1:36?pm, Peter Otten <__pete... at web.de> wrote: > Henning_Thornblad wrote: > > What can be the cause of the large difference between re.search and > > grep? > > grep uses a smarter algorithm ;) > > > > > This script takes about 5 min to run on my computer: > > #!/usr/bin/env python > > import re > > > row="" > > for a in range(156000): > > ? ? row+="a" > > print re.search('[^ "=]*/',row) > > > While doing a simple grep: > > grep '[^ "=]*/' input ? ? ? ? ? ? ? ? ?(input contains 156.000 a in > > one row) > > doesn't even take a second. > > > Is this a bug in python? > > You could call this a performance bug, but it's not common enough in real > code to get the necessary brain cycles from the core developers. > So you can either write a patch yourself or use a workaround. > > re.search('[^ "=]*/', row) if "/" in row else None > > might be good enough. > > Peter It is not a smarter algorithm that is used in grep. Python RE's have more capabilities than grep RE's which need a slower, more complex algorithm. You could argue that if the costly RE features are not used then maybe simpler, faster algorithms should be automatically swapped in but .... - Paddy. From kyosohma at gmail.com Mon Jul 7 10:34:56 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 7 Jul 2008 07:34:56 -0700 (PDT) Subject: Hi there! I need what is probably a very basic lesson in events.... References: <4d5a5286-f4cf-480e-9432-b4b337f7c145@x35g2000hsb.googlegroups.com> Message-ID: <8fca22ab-67ad-4dbb-b92c-d5412a8eba2f@m44g2000hsc.googlegroups.com> On Jul 6, 8:18?am, furby wrote: > I am teaching myself Python... I'm nowhere near even intermediate > level yet, so treat me like an idiot. I am using Boa Constructor on > Ubuntu 8.04 if that helps. Here is what I have right now : > > I am plying with reading a URL (An RSS feed to be exact) and > displaying it inside a HTMLWindow. I have that part working - It shows > the title as a link and displays the description next to it. What I > want to do is trap the mouseclick on the link and use that to grab > just the text that is on the site. Right now, if I click on it, the > HTML window control takes me to the site and doesn't really show the > site very well, since it doesn't seem to do CSS. That's okay - I just > want to display the text.... How do I trap the mouse clicking on the > link? > > I know that HTMLwindow has a "OnLinkClicked" event - I can see it in > the docs for that control. But it seems that Boa Constructor doesn't > expose that event in it's frame designer.... How do I code a event > that fires off instead of the default event? > > I don't know if I am being clear enough, so if not just tell me what I > should say... Liek I said, I am a newbie right now. I think you just need to override that method (OnLinkClicked) in the class you use to subclass the HtmlWindow widget. Something like this: class MyCustomDlg(wx.Frame): def __init__(self, parent, title, icon, pos): wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(400,400)) x,y = pos self.SetPosition((x+30, y+30)) self.SetIcon(icon) html = wxHTML(self) class wxHTML(wx.html.HtmlWindow): def OnLinkClicked(self, link): # do something here pass However, for wxPython questions, it's best to post to the wxPython user's group. They are very knowledgeable there. http://wxpython.org/maillist.php Hope that helps. ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From Russ.Paielli at gmail.com Wed Jul 30 01:15:30 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 22:15:30 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: On Jul 29, 9:52 pm, Carl Banks wrote: > On Jul 29, 11:17 pm, Terry Reedy wrote: > > > > > Carl Banks wrote: > > >> As I wrote in the second reply email I sent, check out my integer set > > >> recipe on ASPN (and to save you the search: http://code.activestate.com/recipes/466286/). > > > > Couple points: > > > > 1. Any container type that returns a length that isn't exactly the > > > number of elements in it is broken. > > > 2. The need for __nonzero__ in this case depends on a limitation in > > > the language. > > > 3. On the other hand, I will concede that sometimes calculating len is > > > a lot more expensive than determining emptiness, and at a basic level > > > it's important to avoid these costs. You have found a practical use > > > case for __nonzero__. > > > I thought of another one: testing whether an iterator is 'empty' (will > > raise StopIteration on the next next() (3.0) call) or not. As virtual > > collections, iterators generally have neither __len__ or __bool__. But > > __bool__ (but only __bool__) can be added to any iterator by wrapping it > > with something like the following 3.0 code (not tested): > > > class look_ahead_it(): > > def __init__(self, iterable): > > self.it = iter(iterable) > > self.fill_next() > > > def __iter__(self): > > return self > > def __next__(self): > > tem = self.next > > if tem is self.empty: > > raise StopIteration > > else: > > self.fill_next() > > return tem > > > empty = object() > > def fill_next(self) > > try: > > self.next = next(self.it) > > except StopIteration: > > self.next = self.empty > > > def __bool__(self): > > return self.next is not self.empty > > Iterators are funny: if there's any reason you should not use "if x" > it's because of them. Built-in iterators are always true, so if > you're writing a function that accepts an iterable you should never > use the "if x" to test whether it's empty, because it fails for a > whole class of iterables. > > However, given that that wart exists, your example does work for "if > x" and not with "if len(x)!=0". > > Then again, it really only works to accommodate faulty code, because > no code that expects an iterable should be using that test in the > first place. (Unless you wrap every iterable as soon as you get it, > but then you're not bound to use __nonzero__.) > > Carl Banks All this discussion about "if x" has me wondering. I use it all the time because a fully explicit test just seems redundant. But maybe it does have some value in terms of readability and type checking. After all, it is possible to forget whether something is a number or a list. Having said that, it would sure be nice to be able to write if myList is not empty: instead of if len(myList) != 0: From wuwei23 at gmail.com Thu Jul 31 01:26:04 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 30 Jul 2008 22:26:04 -0700 (PDT) Subject: how to split text into lines? References: Message-ID: kj wrote: > Sorry, I should have googled this first. ?I just found splitlines()... > > Still, for my own edification, is there a way to achieve the same > effect using re.split? re.split(os.linesep, ) works the same as .splitlines() Neither retain the EOL for each line, though. The only way I'm aware of is to re-add it: [s+os.linesep for s in re.split(os.linesep, )] Was that what you were after? From zapwireDASHgroups at yahoo.com Mon Jul 14 21:33:18 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Mon, 14 Jul 2008 18:33:18 -0700 Subject: One step up from str.split() Message-ID: I normally use str.split() for simple splitting of command line arguments, but I would like to support, e.g., long file names which-- under windows -- are typically provided as simple quoted string. E.g., myapp --dosomething --loadthis "my file name.fil" ...and I'd like to get back a list wherein ListEntry[3]="my file name.fil" , but just running str.split() on the above string creates: >>> ListEntry='myapp --dosomething --loadthis "my file name.fil"' >>> ListEntry.split() ['myapp', '--dosomething', '--loadthis', '"my', 'file', 'name.fil"'] Is there an easy way to provide just this one small additional feature (keeping quoted names as a single entry) rather than going to a full-blown command-line argument parsing tool? Even regular expressions seem like they'd probably be overkill here? Or no? Thanks, ---Joel From basti.wiesner at gmx.net Thu Jul 24 06:02:15 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Thu, 24 Jul 2008 12:02:15 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: Jordan : > # Blog code, not tested > class A(): > def __eq__(self, obj): > return True > a = A() > b = [] > assert a == b > assert not (a != b) > > The second assertion fails. Why? Because coding __eq__, the most > obvious way to make a class have equality based comparisons, buys you > nothing from the != operator. != isn't (by default) a synonym for the > negation of == (unlike in, say, every other language ever); This is just plain wrong for at least C# and C++. C# wants you to explicitly overload "!=", if you have overloaded "==", C++ complains about "!=" not being defined for class A. If you had derived A from a another class in C++, the compiler would happily use the operator from the base class instead of doing silly aliasing of "!=" to "! ==" ... > The sad thing is there are plenty of smart Python programmers who will > justify all kinds of idiocy in the name of their holy crusade against > the implict. > > If there was one change I could make to Python, it would be to get > that damn line out of the Zen. Fortunately, Python isn't designed according to your ideas, and won't change, so consider your posting a waste of time. If feeling like bringing such old "issues" up again next time, spend your time learning another programming language, as you would obviously not get happy with Python anyway ... -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From mgi820 at motorola.com Tue Jul 1 12:46:43 2008 From: mgi820 at motorola.com (Gary Duzan) Date: Tue, 1 Jul 2008 16:46:43 +0000 (UTC) Subject: dynamically load from module import xxx References: Message-ID: In article , Neal Becker wrote: >What is a good way to emulate: > >from module import xxx >where 'module' is a dynamically generated string? > >__import__ ('modulename', fromlist=['xxx']) > >seems to be what I want, but then it seems 'xxx' is not placed in globals() >(which makes me wonder, what exactly did fromlist do?) You might want to read what "help(__import__)" tells you. It sounds like what you want is: mynamespace['xxx'] = __import__('modulename.xxx', fromlist=['xxx']) Seems a bit weird to me, but that's the way it is, and I'm sure there is a reason for it. Good luck. Gary Duzan Motorola H&NM From stefan_ml at behnel.de Sun Jul 13 11:47:49 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 13 Jul 2008 17:47:49 +0200 Subject: SAX XML Parse Python error message In-Reply-To: References: Message-ID: <487A23A5.7000905@behnel.de> goldtech wrote: > My first attempt at SAX, but have an error message I need help with. Just in case you prefer writing readable code over debugging SAX code into existence, try lxml. http://codespeak.net/lxml/ Here is a presentation you might find interesting. http://codespeak.net/lxml/s5/lxml-ep2008.html Stefan From kylefarthing at msn.com Sun Jul 6 05:21:29 2008 From: kylefarthing at msn.com (kylefarthing at msn.com) Date: Sun, 6 Jul 2008 02:21:29 -0700 (PDT) Subject: Discover Islam - The Fastest Growing Religion in the World ! References: <9d3ed65e-335c-4d45-8374-505ae7d434b1@p25g2000hsf.googlegroups.com> Message-ID: On Jul 1, 4:51?pm, ah wrote: > Correct your information about Islam > , > The Misunderstood Religion > > ? When you are ready_ you can enter this place!!! > ?http://sultan.org all u muslim liers get your facts stright According to the Carnegie Endowment for International Peace, the World Christian Database as of 2007 estimated the six fastest growing religions of the world to be Islam (1.84%), the Bah?'? Faith (1.7%), Sikhism (1.62%), Jainism (1.57%), Hinduism (1.52%), and Christianity (1.32%). High birth rates were cited as the reason for the growth. [13] From enleverlesX.XmcX at XmclaveauX.com Sat Jul 5 17:14:15 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 5 Jul 2008 23:14:15 +0200 Subject: pythoncom InternetExplorer.Application don't work in vista || firefox pythoncom ? In-Reply-To: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> References: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> Message-ID: <486fe5cc$0$926$ba4acef3@news.orange.fr> Hi! Your code run OK for me (Vista Ultimate). This other version run also OK : def webbrowser(url=None): import win32com.client, time ie=win32com.client.Dispatch('InternetExplorer.Application') while ie.Busy==True: time.sleep(0.125) ie.Top = 0 ie.Left = 0 ie.Height = 400 ie.Width = 400 ie.AddressBar = False ie.MenuBar = False ie.Resizable = False ie.StatusBar = False ie.ToolBar = False ie.Visible = 1 return ie w = webbrowser() w.Navigate('http://www.google.nl') @-salutations -- Michel Claveau From exarkun at divmod.com Tue Jul 29 14:28:02 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 29 Jul 2008 14:28:02 -0400 Subject: [unittest] Run setUp only once In-Reply-To: <87y73kpnk1.fsf@nokile.rath.org> Message-ID: <20080729182802.29191.2001258936.divmod.quotient.8313@ohm> On Tue, 29 Jul 2008 20:12:14 +0200, Nikolaus Rath wrote: >Jean-Paul Calderone writes: >> On Tue, 29 Jul 2008 19:26:09 +0200, Nikolaus Rath wrote: >>>Jean-Paul Calderone writes: >>>> On Tue, 29 Jul 2008 16:35:55 +0200, Nikolaus Rath wrote: >>>>>Hello, >>>>> >>>>>I have a number of conceptually separate tests that nevertheless need >>>>>a common, complicated and expensive setup. >>>>> >>>>>Unfortunately, unittest runs the setUp method once for each defined >>>>>test, even if they're part of the same class as in >>>>> >>>>>class TwoTests(unittest.TestCase): >>>>> def setUp(self): >>>>> # do something very time consuming >>>>> >>>>> def testOneThing(self): >>>>> >>>>> >>>>> def testADifferentThing(self): >>>>> >>>>> >>>>>which would call setUp twice. >>>>> >>>>> >>>>>Is there any way to avoid this, without packing all the unrelated >>>>>tests into one big function? >>>>> >>>> >>>> class TwoTests(unittest.TestCase): >>>> setUpResult = None >>>> >>>> def setUp(self): >>>> if self.setUpResult is None: >>>> self.setUpResult = computeIt() >>>> >>>> ... >>>> >>>> There are plenty of variations on this pattern. >>> >>> >>>But at least this variation doesn't work, because unittest apparently >>>also creates two separate TwoTests instances for the two tests. Isn't >>>there some way to convince unittest to reuse the same instance instead >>>of trying to solve the problem in the test code itself? >>> >> >> Eh sorry, you're right, the above is broken. `setUpResult` should be >> a class attribute instead of an instance attribute. > >Yeah, well, I guess that would work. But to me this looks really more >like a nasty hack.. isn't there a proper solution? > How is it a nasty hack? It's a straight-forward implementation of shared state, which is what you said you wanted. If you prefer, you could keep the state somewhere else - like by applying a memoizer to `computeIt? and just calling it unconditionally in `setUp?. Jean-Paul From patf at well.com Mon Jul 28 18:43:20 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 15:43:20 -0700 (PDT) Subject: Download excel file from web? References: <6f6vhlFa7anrU1@mid.uni-berlin.de> Message-ID: <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> On Jul 28, 3:33?pm, "p... at well.com" wrote: > On Jul 28, 3:29?pm, "Diez B. Roggisch" wrote: > > > > > p... at well.com schrieb: > > > > On Jul 28, 3:00 pm, "p... at well.com" wrote: > > >> Hi - experienced programmer but this is my first Python program. > > > >> This URL will retrieve an excel spreadsheet containing (that day's) > > >> msci stock index returns. > > > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > > >> Want to write python to download and save the file. > > > >> So far I've arrived at this: > > > >> [quote] > > >> # import pdb > > >> import urllib2 > > >> from win32com.client import Dispatch > > > >> xlApp = Dispatch("Excel.Application") > > > >> # test 1 > > >> # xlApp.Workbooks.Add() > > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > > >> # xlBook = xlApp.ActiveWorkbook > > >> # xlBook.SaveAs(Filename='C:\\test.xls') > > > >> # pdb.set_trace() > > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > > >> excel? > > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > >> +25%2C+2008&export=Excel_IEIPerfRegional') > > >> # test 2 - returns check = False > > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > > >> indexperf/excel? > > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > > >> xlApp = response.fp > > >> print(response.fp.name) > > >> print(xlApp.name) > > >> xlApp.write > > >> xlApp.Close > > >> [/quote] > > > > Woops hit Send when I wanted Preview. ?Looks like the html [quote] tag > > > doesn't work from groups.google.com (nice). > > > > Anway, in test 1 above, I determined how to instantiate an excel > > > object; put some stuff in it; then save to disk. > > > > So, in theory, I'm retrieving my excel spreadsheet with > > > > response = urllib2.urlopen() > > > > Except what then do I do with this? > > > > Well for one read some of the urllib2 documentation and found the > > > Request class with the method has_data() on it. ?It returns False. > > > Hmm that's not encouraging. > > > > I supposed the trick to understand what urllib2.urlopen is returning > > > to me; rummage around in there; and hopefully find my excel file. > > > > I use pdb to debug. ?This is interesting: > > > > (Pdb) dir(response) > > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > > > 'code', ' > > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > > > 'readline', ' > > > readlines', 'url'] > > > (Pdb) > > > > I suppose the members with __*_ are methods; and the names without the > > > underbars are attributes (variables) (?). > > > No, these are the names of all attributes and methods. read is a method, > > for example. > > right - I got it backwards. > > > > > > > > Or maybe this isn't at all the right direction to take (maybe there > > > are much better modules to do this stuff). ?Would be happy to learn if > > > that's the case (and if that gets the job done for me). > > > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty > > clear on this: > > > """ > > This function returns a file-like object with two additional methods: > > """ > > > And then for file-like objects: > > >http://docs.python.org/lib/bltin-file-objects.html > > > """ > > read( ? [size]) > > ? ? ?Read at most size bytes from the file (less if the read hits EOF > > before obtaining size bytes). If the size argument is negative or > > omitted, read all data until EOF is reached. The bytes are returned as a > > string object. An empty string is returned when EOF is encountered > > immediately. (For certain files, like ttys, it makes sense to continue > > reading after an EOF is hit.) Note that this method may call the > > underlying C function fread() more than once in an effort to acquire as > > close to size bytes as possible. Also note that when in non-blocking > > mode, less data than what was requested may be returned, even if no size > > parameter was given. > > """ > > > Diez > > Just stumbled upon .read: > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > excel? > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > +25%2C+2008&export=Excel_IEIPerfRegional').read > > Now the question is: what to do with this? ?I'll look at the > documentation that you point to. > > thanx - pat Or rather (next iteration): response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ excel? priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) The file is generally something like 26 KB so specifying 1,000,000 seems like a good idea (first approximation). And then when I do: print(response) I get a whole lot of garbage (and some non-garbage), so I know I'm onto something. When I read the .read documentation further, it says that read() has returned the data as a string object. Now - how do I convince Python that the string object is in fact an excel file - and save it to disk? pat From martin at v.loewis.de Mon Jul 7 16:36:19 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 07 Jul 2008 22:36:19 +0200 Subject: Memory error while saving dictionary of size 65000X50 using pickle In-Reply-To: <43b21f62-edb6-4e37-89b8-f2460fdc36b3@25g2000hsx.googlegroups.com> References: <43b21f62-edb6-4e37-89b8-f2460fdc36b3@25g2000hsx.googlegroups.com> Message-ID: <48727e43$0$20740$9b622d9e@news.freenet.de> Nagu wrote: > I am trying to save a dictionary of size 65000X50 to a local file and > I get the memory error problem. What do you mean by this size specification? When I interpreter X as multiplication, I can't see a problem: the code import pickle d = {} for i in xrange(65000*50): d[i]=i print "Starting dump" s = pickle.dumps(d) works just fine for me. Can you please modify it so that it does cause a problem? Regards, Martin From mnordhoff at mattnordhoff.com Mon Jul 7 09:17:09 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 07 Jul 2008 13:17:09 +0000 Subject: I am looking for svn library(module) In-Reply-To: <6e1097a0-2a99-4885-a1ef-0684af5aa6a1@d1g2000hsg.googlegroups.com> References: <6e1097a0-2a99-4885-a1ef-0684af5aa6a1@d1g2000hsg.googlegroups.com> Message-ID: <48721755.4050507@mattnordhoff.com> sniipe at gmail.com wrote: > Hi, > > I am looking fo svn library(module) which is used in the svn- > mailer(http://opensource.perlig.de/svnmailer/) project. Does anybody > know where can I find it(download url)? This is information which I > received from python error: > > from svn import core as svn_core > ImportError: No module named svn > > Best regards Those would be the bindings that come with Subversion. They're covered at the end of ./INSTALL in the source tree (which just points you to ./subversion/bindings/swig/INSTALL). If you installed svn with a package manager, there's probably a package for them (e.g. python-subversion on Ubuntu). -- From tjreedy at udel.edu Sat Jul 12 15:46:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 15:46:49 -0400 Subject: Confused In-Reply-To: <4878DC07.9000302@gmail.com> References: <000001c8e417$c2b5bc50$0a01a8c0@HOMEPC> <4878DC07.9000302@gmail.com> Message-ID: Michael Torrie wrote: > eric.butteriss wrote: >> Please tell me why may mail is being returned. The message says I >> have been blacklisted...for what reason? I never open mail that I >> know is not expected and I never send junk or spam. I am trying to >> send important info to my cousin. > > Now I'm confused. Is the python mailing list blacklisting you? Unless > this is a python-related thing, I doubt you'll find anyone here who can > help. I think the OP is another spammer. Who would email a cousin via a language email list? This was probably sent to multiple lists. From s0suk3 at gmail.com Thu Jul 3 23:50:45 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Thu, 3 Jul 2008 20:50:45 -0700 (PDT) Subject: Parsing MIME-encoded data in an HTTP request References: Message-ID: <4834df8f-2cf8-434c-8c95-ff53024766c8@p25g2000hsf.googlegroups.com> On Jul 3, 3:59 pm, Ron Garret wrote: > I'm writing a little HTTP server and need to parse request content that > is mime-encoded. All the MIME routines in the Python standard library > seem to have been subsumed into the email package, which makes this > operation a little awkward. To deal with messages of that kind, I've seen modules such as 'rfc822', and 'mimetools' (which apparently builds itself from 'rfc822', so it might be more complete). There's also 'mimetypes', in case you need to deal with file extensions and their corresponding MIME media type. > It seems I have to do the following: > > 1. Extract the content-length header from the HTTP request and use that > to read the payload. > > 2. Stick some artificial-looking headers onto the beginning of this > payload to make it look like an email message (including the > content-type and content-transfer-encoding headers) > > 3. Parse the resulting string into a email message > Email? Why does an HTTP server need to build an email message? I remember doing things like that some time ago when building an HTTP server myself (http://code.google.com/p/sws-d/). Incidentally, I resisted the urge to use much of the Python's library facilities (most things are done manually; am I a knucklehead or what!? :). You might wanna take a look to get some ideas. Sebastian From kay.schluehr at gmx.net Sat Jul 12 09:35:56 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 12 Jul 2008 06:35:56 -0700 (PDT) Subject: Changing self: if self is a tree how to set to a different self References: Message-ID: On 10 Jul., 15:19, Bart Kastermans wrote: > I am playing with some trees. In one of the procedures I wrote > for this I am trying to change self to a different tree. A tree > here has four members (val/type/left/right). I found that self = SS > does not work; I have to write self.val = SS.val and the same for > the other members (as shown below). Is there a better way to do this? > > In the below self is part of a parse tree, F is the parse tree of a > function f with argument x. If a node in the parse tree is labelled > f, we should replace it by the parse tree for the function f, F, with > the remainder of the tree substituted for the input variable for the > function f, here x. > > def elimF (self): > if self.val == "f": > SS = F.copy () > SS.subst ('x', self.left) > self.val = SS.val # from here: set self to be SS > self.type = SS.type > self.left = SS.left > self.right = SS.right # completed: set self to be SS > > if self.left != None: # iterate onward, inf recursion if f > # appears. Would need a check in > # real version > self.left.elimF () > if self.right != None: > self.right.elimF () > > Best, > Bart Since it is acting on a tree why doesn't the code substitute self in its parent by SS? That's the natural perspective if one considers a tree as a linked structure and inserts and deletes nodes within this structure. From 2007 at jmunch.dk Mon Jul 28 19:19:00 2008 From: 2007 at jmunch.dk (Anders J. Munch) Date: Tue, 29 Jul 2008 01:19:00 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <009dcc93$0$20313$c3e8da3@news.astraweb.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> Message-ID: <488e4d2d$0$5967$ba624c82@nntp06.dk.telia.net> Steven D'Aprano wrote: > On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: > >> I want something where "if x" will do but a simple explicit test won't. > > Explicit tests aren't simple unless you know what type x is. If you don't even know a duck-type for x, you have no business invoking any methods on that object. If you do know a duck-type for x, then you also know which explicit test to perform. > Explicit tests are not necessarily simple for custom classes. Testing for > emptiness could be arbitrarily complex. That's why we have __nonzero__, > so you don't have to fill your code with complex expressions like (say) > > if len(x.method()[x.attribute]) > -1 > > Instead you write it once, in the __nonzero__ method, and never need to > think about it again. Okay, so you have this interesting object property that you often need to test for, so you wrap the code for the test up in a method, because that way you only need to write the complex formula once. I'm with you so far. But then you decide to name the method "__nonzero__", instead of some nice descriptive name? What's up with that? This is the kind of code I would write: class C: def attribute_is_nonnegative(self): return len(self.method()[self.attribute]) > -1 ... c = get_a_C() if c.attribute_is_nonnegative(): ... Now suppose you were reading these last few lines and got to wondering if get_a_C might ever return None. The answer is obviously no. get_a_C must always return a C object or something compatible. If not, it's a bug and an AttributeError will ensue. The code tells you that. By giving the method a name the intent of the test is perfectly documented. In comparison, I gather you would write something like this: class C: def __nonzero__(self): return len(self.method()[self.attribute]) > -1 ... c = get_a_C() if c: ... Again, the question is, can get_a_C return None? Well that's hard to say really. It could be that "if c" is intended to test for None. Or it could be intended to call C.__nonzero__. Or it could be cleverly intended to test not-None and C.__nonzero__ at the same time. It may be impossible to discern the writer's true intent. Even if we find out that C.__nonzero__ is called, what was it that __nonzero__ did again? Did it test for the queue being non-empty? Did it test for the queue being not-full? Did it test whether for the consumer thread is running? Did it test for if there are any threads blocked on the queue? Better dig up the class C documentation and find out, because there is no single obvious interpretation of what is means for an object to evaluate to true. "if x" is simple to type, but not so simple to read. "if x.namedPredicate()" is harder to type, but easier to read. I prefer the latter because code is read more often than it is written. regards, Anders From timothy.grant at gmail.com Fri Jul 25 02:32:40 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Thu, 24 Jul 2008 23:32:40 -0700 Subject: Function editing with Vim throws IndentError In-Reply-To: References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: On Thu, Jul 24, 2008 at 9:32 PM, Lawrence D'Oliveiro wrote: > In message > , > Matimus > wrote: > > > On Jul 24, 2:54 am, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: > >> In message > >> , > >> > >> Matimus wrote: > >> > That isn't the standard. With that setup tabs will show up as 4 > >> > spaces, and still confuse you. > >> > >> Why should that be confusing? The most common tab-stop setting is 4 > >> columns. > > > > A tab character is specified as 8 spaces. > > Specified by whom? The most common setting these days is 4 columns. > -- > http://mail.python.org/mailman/listinfo/python-list > A tab-stop has historically been 8 spaces. Most terminals, printers and other devices understand the tab as 8 characters. Smart editors have made it easy to make tabs APPEAR as four spaces, but they are almost universally interpreted elsewhere as 8 characters. http://en.wikipedia.org/wiki/Tab_key -- Stand Fast, tjg. [Timothy Grant] -------------- next part -------------- An HTML attachment was scrubbed... URL: From torainLight at gmail.com Thu Jul 24 20:42:54 2008 From: torainLight at gmail.com (satoru) Date: Thu, 24 Jul 2008 17:42:54 -0700 (PDT) Subject: Confounded by Python objects References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> Message-ID: <5ddae1dd-c7dd-4f04-84f6-ad71c3282c92@j7g2000prm.googlegroups.com> On Jul 24, 6:10?pm, "boblat... at googlemail.com" wrote: > On Jul 24, 11:59 am, Fredrik Lundh wrote: > > > tip: if you're not 100% sure why you would want to put an attribute > > on the class level, don't do it. > > The reason I did it was sort of C++ish (that's where I come from): I > somehow wanted a list of attributes on the class level. More for > readibility than anything elase, really. > > > hope this helps! > > Yup, did the trick. Thanks! > robert yes, i thought your code is kind of static, so it didn't work for a dynamic language like python. in python, you don't have to say "static" to make an variable a class variable, so the "name" and "sample" you kind of "declared" is indeed class variables. you may wonder why then the two instaces of "Channel" has different names, that's because you assign to name in "__init__" and make it an instance variable that shared the name "name" with a class variable. As to "sample", it never get assigned to and when you say "append" the class variable is changed in place. hope my explaination helps. From david at boddie.org.uk Sun Jul 20 08:18:03 2008 From: david at boddie.org.uk (David Boddie) Date: Sun, 20 Jul 2008 14:18:03 +0200 Subject: Genetic programming: pygene, pygp, AST, or (gasp) Lisp? References: <7bfb3c41-b08b-49dc-9711-6e39a4667db2@b1g2000hsg.googlegroups.com> Message-ID: On Sunday 20 July 2008 09:52, John Ladasky wrote: > Is there a way to interface Lisp to Python, so that I can do all the > interface programming in the language I already know best -- and just > do the genetic parts in Lisp? I haven't seen exception handling in > Lisp, a feature I've come to love in Python. Since it is fairly easy > for a randomly-generated program to generate illegal output (I already > know this from my initial experiments in Python), I don't think I can > live without exception handling. Just searching the Web for Python and Lisp yielded some interesting projects: http://www.biostat.wisc.edu/~annis/creations/PyLisp/ http://www.livelogix.net/logix/ I've no idea if they're really that relevant to your problem, but they might lead somewhere useful. David From semanticist at gmail.com Sun Jul 20 03:18:55 2008 From: semanticist at gmail.com (Miles) Date: Sun, 20 Jul 2008 03:18:55 -0400 Subject: MethodChain In-Reply-To: <6efv5cF6uhc3U1@mid.uni-berlin.de> References: <6eej10F6k7g3U2@mid.uni-berlin.de> <342b5431-5ead-4827-8bdd-ab2cd50c2acc@i76g2000hsf.googlegroups.com> <6efv5cF6uhc3U1@mid.uni-berlin.de> Message-ID: On Sun, Jul 20, 2008 at 1:01 AM, Marc 'BlackJack' Rintsch wrote: > The methods are a problem IMHO. You can't add an own method/function with > the name `fire()` or `toFunction()`. `MethodChain` has to know all > functions/methods in advance. You can add the methods of whole classes at > once and there are over 300 pre-added, this begs for name clashes. Name clashes aren't an issue, since MethodChain doesn't apply any special meaning to the method names it knows; the limitation is because JavaScript doesn't allow you to modify property lookup behavior. And since we can make the chain object callable, we don't need "fire" or "toFunction" methods. ########### from functools import partial class MethodChain(object): # The implementation of this could be cleaner. I would prefer # chain.foo() to return a new object instead of modifying chain. # But this is easier to write and closer to the JavaScript implementation. def __init__(self): self._methodname = None self._chain = [] def __getattr__(self, methodname): assert self._methodname is None self._methodname = methodname return self def __call__(self, *args, **kwargs): if self._methodname is None: assert len(args) == 1 and not kwargs result = args[0] for method in self._chain: result = getattr(result, method[0])(*method[1], **method[2]) return result else: self._chain.append((self._methodname, args, kwargs)) self._methodname = None return self def compose(*callables): def composition(arg): result = arg for callable in callables: # or should that be reversed(callables)? to be mathematically # accurate, yes, probably; however, it also makes sense to # specify the callables in the order they'll be applied result = callable(result) return result return composition chain = MethodChain().lower().replace('ello,', 'ey').title().split() print chain('HELLO, world') func = compose(chain, partial(map, lambda s: s+'!'), ' '.join) print func('HELLO, world') ########### -Miles From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 10 12:45:42 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 10 Jul 2008 18:45:42 +0200 Subject: Smal question In-Reply-To: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> References: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> Message-ID: <48763c7f$0$9609$426a74cc@news.free.fr> Hans M?ller a ?crit : > Hello group, > > I have some scripts sharing some common functions. > So what I'd like to have is a modern include. > Of course python does not have (with good reasons) no include statement. > But I'm too lazy to create a module which has to be installed into the > interpreter for some functions I need to share in a project. What do you mean "installed in the interpreter" ? From wuwei23 at gmail.com Wed Jul 23 07:48:36 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 23 Jul 2008 04:48:36 -0700 (PDT) Subject: os.walk question References: Message-ID: <79b8d5e1-709f-4a4f-957d-8acbee20018b@c2g2000pra.googlegroups.com> On Jul 23, 5:22?pm, Fredrik Lundh wrote: > if you want a list of files from a single directory, use listdir, not walk: > > ? ? ? >>> import os, random > ? ? ? >>> random.choice(os.listdir("/")) > ? ? ? 'python25' This will include folders as well, though, which isn't what the OP asked for. >>> import os, random >>> root = "/" >>> random.choice([f for f in os.listdir(root) if os.path.isfile(os.path.join(root, f))]) 'initrd.img' It just seems clunky compared to os.walk :) From jcn-france1972 at pobox.com Sun Jul 6 21:10:20 2008 From: jcn-france1972 at pobox.com (Jean-Claude Neveu) Date: Sun, 06 Jul 2008 18:10:20 -0700 Subject: Using poplib to parse headers - Thank You All! In-Reply-To: References: Message-ID: Tim Roberts wrote: >You've received some very confusing advice in this thread. Alex had the >right answer, but I want to expand it a bit. > >[...] > >poplib.retr gives you a string. You need to hand that string to the email >module, and you do that using "email.message_from_string". This is just to thank Tim, Alex, and everyone who posted for their help in getting this to work. It's been more than a month since you answered my question and I've been having to focus on other things. Last week, I finally got back to this task and your answers helped me get it working. To save time for future people who might have the same question, I'm posting a basic script for reading mail from a POP server and passing the email message to the Python email library for parsing. I'm new to Python (but experienced in other languages) so please feel free to tell me if any of my syntax is clumsy, or if I did something the difficult way when Python has an easier or more efficient way to do it. I hope this will be useful for the archives. # import getpass, poplib, email # Set up the connection to the POP server popconnection = poplib.POP3('mail.blah.com') popconnection.user('user-name-goes-here') popconnection.pass_('password-goes-here') # Find out how many messages are waiting numMessages = len(popconnection.list()[1]) # Iterate through the messages for i in range(numMessages): # retr will be called three times for each email message in the j loop below. # # The first call will return a string telling you how many bytes (i.e., octets) # are in the message. The string will look like this: OK octets # (where is the total number of bytes in the message). # # The second call will return a list containing the elements of the message. # # The third call will return an integer containing the total number of # bytes in the message for j in popconnection.retr(i+1): # We are interested only in the contents of the list. And we need to put the # list contents into a string, because that is what message_from_string expects. # We must also be sure to put a line break at the end of the substring that # represents each list element, as message_from_string relies on line breaks # to parse the email message. The k loop below builds the string from the list. if type(j) == list: numElements = len(j) outString = "" for k in range(numElements): outString += j[k] outString += '\n' message = email.message_from_string(outString) # Now that we have got the contents of the email into an email object, we can # access the logical elements of the email at will, in any order. The call to # get_payload() is to retrieve the body of the message. print message['Subject'] print message['From'] print message.get_payload() # Strictly speaking, all we need to do on quitting is to disconnect, but in some # applications it would be a good idea to delete the email from the server. popconnection.quit() From hyh_david at hotmail.com Thu Jul 17 15:17:26 2008 From: hyh_david at hotmail.com (hyh_david at hotmail.com) Date: Thu, 17 Jul 2008 12:17:26 -0700 (PDT) Subject: wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal Message-ID: paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal ... From __peter__ at web.de Sat Jul 5 02:01:06 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 05 Jul 2008 08:01:06 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Paddy wrote: > It is not a smarter algorithm that is used in grep. Python RE's have > more capabilities than grep RE's which need a slower, more complex > algorithm. So you're saying the Python algo is alternatively gifted... Peter From bronger at physik.rwth-aachen.de Sat Jul 19 09:10:15 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 19 Jul 2008 15:10:15 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> <87lk00d7cr.fsf@physik.rwth-aachen.de> <4881e41d$0$10421$426a34cc@news.free.fr> Message-ID: <87prpam348.fsf@physik.rwth-aachen.de> Hall?chen! Bruno Desthuilliers writes: > Torsten Bronger a ?crit : > >> bruno.desthuilliers at gmail.com writes: >> >>> On 16 juil, 10:35, Stefan Scholl wrote: >>> >>>> Dave U. Random wrote: >>>> >>>>> http://snipr.com/PracticalDjango >>>> >>>> June 2008 is a bit too early. Django isn't ready. >>> >>> Oh, really ? Too bad. But, wait... If Django isn't ready, what's >>> that framework I've been using for almost three years now, then >>> ??? >> >> Before writing sarcastic comments, reading the thread would be >> really polite. > > You may not have notice, but applied to a piece of software, > "ready" is usually understood as "ready for production use". Which > Django is, and has been for years now. Yes, so Stefan used the wrong English word. The rest of the thread had already revealed it when you made your statement. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From hdante at gmail.com Tue Jul 29 22:37:50 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Tue, 29 Jul 2008 19:37:50 -0700 (PDT) Subject: Parsing VHDL with python, where to start. References: <31888260-86a9-46b0-b0a4-79f7852f256a@k30g2000hse.googlegroups.com> <50129a5b-b2f3-48a8-9ff6-1ac27918f4d4@r66g2000hsg.googlegroups.com> Message-ID: On Jul 29, 11:23?pm, Henrique Dante de Almeida wrote: > On Jul 28, 6:49?pm, Svenn Are Bjerkem > wrote: > > > > > Hi again, > > > when I get far enough to parse the VHDL (which is not currently the > > fact, but I have to look at the work coming up downstream) I will have > > to put it into an internal data structure and then write some classes > > to handle the MVC between whatever data I have and the PyQt4 widget > > that is going to show the block diagram. I own the book "Rapig GUI > > Programming with Python and Qt" by Mark Summerfield and try to read up > > on the PyQt way of doing things as I try to make a plan for my > > application. I have been looking for possible data structures with > > google just to find out that most of the ideas are stored in > > proceedings or to conferences or ieee papers not generally available > > to me. Is anybody experienced with designing data structures willing > > to share some ideas with me? Since I am using the open-source version > > of PyQt4, any information will eventually be available to public (if > > the app pass the planning stage) if that makes helping out any > > easier: :-) There is already an app called Qucs that is running in > > Qt-3 and being ported to Qt-4 that is written in C++, but I don't know > > how wise it is to just reverse-engineering C++ classes and translate > > them into python classes. > > > -- > > Svenn > > ?Don't mix the parsing code with Qt. They're independent. Qt should be > used mostly for the model and the view. The controller should be > completelly decoupled from the model and the view. If you need to wrap > the controller in some Qt object, first write the controller without > Qt, then wrap it in the Qt object. Considering that you need a full > parser for VHDL, my option would be to take the VHDL grammar: > > ?http://tams-www.informatik.uni-hamburg.de/vhdl/tools/grammar/vhdl93-b... > > ?and port it to a LR(1) or LALR parser that emits python code. See: > > ?http://en.wikipedia.org/wiki/Comparison_of_parser_generators > > ?Then, add action code to the grammar that you wrote, so that it > builds a tree representing the parsed file. I think SableCC seems to be the best choice: http://www.mare.ee/indrek/sablecc/ From gnewsg at gmail.com Sun Jul 13 11:17:07 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sun, 13 Jul 2008 08:17:07 -0700 (PDT) Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> Message-ID: On 13 Lug, 11:35, Duncan Booth wrote: > "Giampaolo Rodola'" wrote: > > Having said that I'd like to understand if there are cases where > > deleting or moving an element of the heap, causes heappop() to return > > an element which is not the smallest one. > > Yes, of course there are: any time you delete element 0 of the heap you can > do that. > > >>> heap = [0, 2, 1, 4, 5, 6, 7, 8, 9] > >>> heapify(heap) > >>> heap > > [0, 2, 1, 4, 5, 6, 7, 8, 9] > > >>> del heap[0] > >>> heappop(heap) > 2 > > By definition, element 0 is always the smallest but the next two elements > could be in any order. If you delete an element other than 0 then the next > pop won't be guaranteed to work. > > If you delete an element other than 0 the very next pop will work, but the > heap conditions won't necessarily be restored so subsequent elements may > come out in the wrong order. A simple example: > > >>> heap = [0, 1, 3, 4, 2, 5] > >>> heapify(heap) > >>> heap > [0, 1, 3, 4, 2, 5] > >>> del heap[1] > >>> heappop(heap), heappop(heap), heappop(heap) > > (0, 3, 2) Thanks, that's what I wanted to know. I understand that heapq is not that efficient to implement timeouts as I thought at first. It would have been perfect if there were functions to remove arbitrary elements withouth needing to re-heapify() the heap every time. Thanks for your help anyway. --- Giampaolo http://code.google.com/p/pyftpdlib/ From lists at nanl.de Wed Jul 9 14:02:56 2008 From: lists at nanl.de (Mirko Vogt) Date: Wed, 09 Jul 2008 20:02:56 +0200 Subject: socket-module: different behaviour on windows / unix when a timeout is set Message-ID: <4874FD50.1070404@nanl.de> Hey, it seems that the socket-module behaves differently on unix / windows when a timeout is set. Here an example: # test.py import socket sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print 'trying to connect...' sock.connect(('127.0.0.1',9999)) print 'connected!' # executed on windows >C:\Python25\python.exe test.py trying to connect... Traceback (most recent call last): File "test.py", line 4, in sock.connect(('127.0.0.1',9999)) File "", line 1, in connect socket.error: (10061, 'Connection refused') > # executed on linux $ python test.py trying to connect... Traceback (most recent call last): File "test.py", line 4, in sock.connect(('127.0.0.1',9999)) File "", line 1, in connect socket.error: (111, 'Connection refused') $ Even if the error-codes are different both raise an socket.error with the message 'Connection refused' - good so far. Now I will change the code slightly - to be precise I set a timeout on the socket: # test.py import socket sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.settimeout(3.0) # <---------------------------------------------------------- print 'trying to connect...' sock.connect(('127.0.0.1',9999)) print 'connected!' # executed on linux $ python test.py trying to connect... Traceback (most recent call last): File "test.py", line 5, in sock.connect(('127.0.0.1',9999)) File "", line 1, in connect socket.error: (111, 'Connection refused') $ # executed on windows >C:\Python25\python.exe test.py trying to connect... connected! > The code executed by python running on windows does *not* raise the exception anymore. The Linux does as expected. Is that behaviour common or even documented? Found nothing. It took me lot's of time to figure this out, because there was no exception which was raised when testing for open / ports. When I try to read from the socket (e.g. on port 9999 on which nothing runs) I get a timeout after the via settimeou() specified value. Thanks in advance, Mirko From mensanator at aol.com Thu Jul 3 23:27:16 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 3 Jul 2008 20:27:16 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> <7db52b03-7a8a-40c4-b3cb-f6dccd273b90@59g2000hsb.googlegroups.com> <45ce2acc-e4b5-4762-8daa-b67a78b02411@w7g2000hsa.googlegroups.com> Message-ID: <5b9a9fda-f736-4f72-b878-16008097f13f@34g2000hsf.googlegroups.com> On Jul 3, 9:09?pm, George Sakkis wrote: > On Jul 3, 7:51 pm, Mensanator wrote: > > > On Jul 3, 6:24 pm, George Sakkis wrote: > > > > Taking into account 2.6 too (we're not talking about only 3.0 here), > > > probably not much less than those who even know what is gmpy, let > > > alone dismiss a beta Python release because their obscure pet module > > > is not available yet. > > > That was just an example. When you consider ALL the pet > > modules like PIL, Numpy, Win32, etc., that's a lot, isn't it. > > A few points: > - The OP acknowledged he's a newbie, and as a newbie he'll probably > spend some time getting used to the language and the standard library > before jumping to the dozens 3rd party packages. > - I am sure many Python users are productive without ever touching an > external package; that is after all the point of "batteries included". > - Even if they do have external dependencies, chances are that they > are pure Python modules, which typically work without modification on > new 2.x versions. Yes, these points are valid, although I think mine are valid also. But there's no point in any further arguing. > > > I was just trying to be helpful (I admit I often sound > > negative when I'm not trying to be). > > Well, something like "Until then, such solutions are worthless, i.e., > of no value" is too strong, subjective and biased to be really > helpful. I was trying NOT to imply "broken" or "doesn't do anything useful". I guess I'll have to try to be less succinct. > > George From misceverything at gmail.com Sun Jul 20 12:05:12 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Sun, 20 Jul 2008 09:05:12 -0700 (PDT) Subject: Web Server References: Message-ID: <1dc5311f-6243-41d4-b5da-78183c9668e4@m44g2000hsc.googlegroups.com> Thanks, Fredrik - that definitely works. Now to get a little greedy - is there something along those lines that is a bit more secure (i.e. allows HTTPS, possibly with authentication)? Basically something that you would feel more comfortable opening up to the Internet.. From fredrik at pythonware.com Tue Jul 22 13:21:00 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 19:21:00 +0200 Subject: Importing different versions of a module In-Reply-To: <8b51e78c0807221005k4ead9652i721a030c592273af@mail.gmail.com> References: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> <48811064.5010603@hughes.net> <8b51e78c0807181750x66fd0372y82367245630e921f@mail.gmail.com> <4884FC33.2090006@hughes.net> <8b51e78c0807221005k4ead9652i721a030c592273af@mail.gmail.com> Message-ID: mercado mercado wrote: > It seems that you can specify the name of the module to be imported at > runtime using the following syntax: > > X = __import__('X') > > (from http://effbot.org/zone/import-confusion.htm) > > Of course, I would rather specify the path to the module at runtime, not > the module name itself, but at least this is a start... additional approaches can be found here: http://effbot.org/zone/import-string.htm also see my other reply to you in this thread. From robert.kern at gmail.com Tue Jul 29 18:01:19 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 29 Jul 2008 17:01:19 -0500 Subject: Swap memory in Python ? - three questions In-Reply-To: References: <642068.13334.qm@web55102.mail.re4.yahoo.com> Message-ID: Terry Reedy wrote: > > Robert LaMarca wrote: >> Hi, >> I am using numpy and wish to create very large arrays. My system is >> AMD 64 x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a >> 15 GB swap drive. >> The command I have been trying to use is; >> g=numpy.ones([1000,1000,1000],numpy.int32) >> >> This returns a memory error. A smaller array ([500,500,500]) worked >> fine.. Two smaller arrays again crashed the system. >> >> So... I did the math. a 1000x1000x1000 array at 32 bits should be >> around 4gb RAM... Obviously larger than RAM, but much smaller than the >> swap drive. >> >> 1. So... does Numpy have a really lot of overhead? Or is my system >> just not somehow getting to make use of the 15gb swap area. 2. Is >> there a way I can access the swap area, or direct numpy to do so? Or >> do I have to write out my own numpy cache system... 3. How difficult >> is it to use data compression internally on numpy arrays? > > I do not know what numpy does, but constant arrays only need to store > the dimensions and the constant value and have a getitem method that > returns that constant value for any valid index. This is at most a few > hundred bytes regardless of the dimensions. Presumably, he's using numpy.ones() as an example of creating a large array, not because he actually needs an array full of 1s. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From paul at boddie.org.uk Wed Jul 30 11:43:58 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 30 Jul 2008 08:43:58 -0700 (PDT) Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: Message-ID: <2a703a46-75bc-4228-95d1-05a4e6030b40@f63g2000hsf.googlegroups.com> On 30 Jul, 16:32, Simon Willison wrote: > I'm having a horrible time trying to get xml.dom.pulldom to consume a > UTF8 encoded XML file. Here's what I've tried so far: > > >>> xml_utf8 = """ > > Simon\xe2\x80\x99s XML nightmare > """>>> from xml.dom import pulldom > >>> parser = pulldom.parseString(xml_utf8) > >>> parser.next() > > ('START_DOCUMENT', )>>> parser.next() > > ('START_ELEMENT', )>>> parser.next() > > ... > UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in > position 21: ordinal not in range(128) I can't reproduce this on Python 2.3.6 or 2.4.4 on RHEL 4. Instead, I get the usual... ('CHARACTERS', ) And I can get the content of the text node as a proper Unicode object. [...] > Is it possible to consume utf8 or unicode using xml.dom.pulldom or > should I try something else? Yes, it is possible, at least in Python 2.3.6 and 2.4.4 configured with --enable-unicode=ucs4 (which is what Red Hat does and expects). Paul P.S. You shouldn't try and pass Unicode to the parser, since XML parsing in its entirety deals with byte sequences and character encodings, although I suppose that there's some kind of character- based (ie. Unicode value-based) parsing method defined somewhere by some committee or other. From animator333 at gmail.com Fri Jul 25 04:10:52 2008 From: animator333 at gmail.com (King) Date: Fri, 25 Jul 2008 01:10:52 -0700 (PDT) Subject: 2d graphics - what module to use? References: Message-ID: <5519ca3a-bef6-4673-981a-fb327425cfee@w39g2000prb.googlegroups.com> Use python's default GUI tkinter's drawing functions or you can use wxPython GUI kit or you can use pyopengl. If you are only interested to draw sin waves or math functions that you should give try to matlab at www.mathworks.com From s0suk3 at gmail.com Sun Jul 27 00:46:31 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Sat, 26 Jul 2008 21:46:31 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> Message-ID: <6385b0a8-f7f3-4dc3-91be-e6f158ffb439@a1g2000hsb.googlegroups.com> On Jul 26, 6:47 pm, Lawrence D'Oliveiro wrote: > In message > <024ace13-f72f-4093-bcc9-f8a339c32... at v1g2000pra.googlegroups.com>, > > > > s0s... at gmail.com wrote: > > On Jul 24, 5:01 am, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: > > >> In message > >> <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, > >> Jordan wrote: > > >> > Except when it comes to Classes. I added some classes to code that had > >> > previously just been functions, and you know what I did - or rather, > >> > forgot to do? Put in the 'self'. In front of some of the variable > >> > accesses, but more noticably, at the start of *every single method > >> > argument list.* > > >> The reason is quite simple. Python is not truly an "object-oriented" > >> language. It's sufficiently close to fool those accustomed to OO ways of > >> doing things, but it doesn't force you to do things that way. You still > >> have the choice. An implicit "self" would take away that choice. > > > By that logic, C++ is not OO. > > Yes it is, because it has "this". You mean the keyword "this"? It's just a feature. How does that make a difference on being or not being OO? (It's true that C++ has more OO features than Python, like private/ public members, virtual methods, etc. But I don't see how a trivial feature like an additional keyword makes a difference.) From patf at well.com Mon Jul 28 19:04:37 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 16:04:37 -0700 (PDT) Subject: Download excel file from web? References: <6f6vhlFa7anrU1@mid.uni-berlin.de> <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> Message-ID: <19fa0bb2-e101-47c9-84d4-1bf05d08ba39@b2g2000prf.googlegroups.com> On Jul 28, 3:52?pm, "Guilherme Polo" wrote: > On Mon, Jul 28, 2008 at 7:43 PM, p... at well.com wrote: > > On Jul 28, 3:33 pm, "p... at well.com" wrote: > >> On Jul 28, 3:29 pm, "Diez B. Roggisch" wrote: > > >> > p... at well.com schrieb: > > >> > > On Jul 28, 3:00 pm, "p... at well.com" wrote: > >> > >> Hi - experienced programmer but this is my first Python program. > > >> > >> This URL will retrieve an excel spreadsheet containing (that day's) > >> > >> msci stock index returns. > > >> > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > >> > >> Want to write python to download and save the file. > > >> > >> So far I've arrived at this: > > >> > >> [quote] > >> > >> # import pdb > >> > >> import urllib2 > >> > >> from win32com.client import Dispatch > > >> > >> xlApp = Dispatch("Excel.Application") > > >> > >> # test 1 > >> > >> # xlApp.Workbooks.Add() > >> > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > >> > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > >> > >> # xlBook = xlApp.ActiveWorkbook > >> > >> # xlBook.SaveAs(Filename='C:\\test.xls') > > >> > >> # pdb.set_trace() > >> > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > >> excel? > >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> +25%2C+2008&export=Excel_IEIPerfRegional') > >> > >> # test 2 - returns check = False > >> > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > >> > >> indexperf/excel? > >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > >> > >> xlApp = response.fp > >> > >> print(response.fp.name) > >> > >> print(xlApp.name) > >> > >> xlApp.write > >> > >> xlApp.Close > >> > >> [/quote] > > >> > > Woops hit Send when I wanted Preview. ?Looks like the html [quote] tag > >> > > doesn't work from groups.google.com (nice). > > >> > > Anway, in test 1 above, I determined how to instantiate an excel > >> > > object; put some stuff in it; then save to disk. > > >> > > So, in theory, I'm retrieving my excel spreadsheet with > > >> > > response = urllib2.urlopen() > > >> > > Except what then do I do with this? > > >> > > Well for one read some of the urllib2 documentation and found the > >> > > Request class with the method has_data() on it. ?It returns False. > >> > > Hmm that's not encouraging. > > >> > > I supposed the trick to understand what urllib2.urlopen is returning > >> > > to me; rummage around in there; and hopefully find my excel file. > > >> > > I use pdb to debug. ?This is interesting: > > >> > > (Pdb) dir(response) > >> > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > >> > > 'code', ' > >> > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > >> > > 'readline', ' > >> > > readlines', 'url'] > >> > > (Pdb) > > >> > > I suppose the members with __*_ are methods; and the names without the > >> > > underbars are attributes (variables) (?). > > >> > No, these are the names of all attributes and methods. read is a method, > >> > for example. > > >> right - I got it backwards. > > >> > > Or maybe this isn't at all the right direction to take (maybe there > >> > > are much better modules to do this stuff). ?Would be happy to learn if > >> > > that's the case (and if that gets the job done for me). > > >> > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty > >> > clear on this: > > >> > """ > >> > This function returns a file-like object with two additional methods: > >> > """ > > >> > And then for file-like objects: > > >> >http://docs.python.org/lib/bltin-file-objects.html > > >> > """ > >> > read( ? [size]) > >> > ? ? ?Read at most size bytes from the file (less if the read hits EOF > >> > before obtaining size bytes). If the size argument is negative or > >> > omitted, read all data until EOF is reached. The bytes are returned as a > >> > string object. An empty string is returned when EOF is encountered > >> > immediately. (For certain files, like ttys, it makes sense to continue > >> > reading after an EOF is hit.) Note that this method may call the > >> > underlying C function fread() more than once in an effort to acquire as > >> > close to size bytes as possible. Also note that when in non-blocking > >> > mode, less data than what was requested may be returned, even if no size > >> > parameter was given. > >> > """ > > >> > Diez > > >> Just stumbled upon .read: > > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> excel? > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> +25%2C+2008&export=Excel_IEIPerfRegional').read > > >> Now the question is: what to do with this? ?I'll look at the > >> documentation that you point to. > > >> thanx - pat > > > Or rather (next iteration): > > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > > excel? > > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > > The file is generally something like 26 KB so specifying 1,000,000 > > seems like a good idea (first approximation). > > > And then when I do: > > > print(response) > > > I get a whole lot of garbage (and some non-garbage), so I know I'm > > onto something. > > > When I read the .read documentation further, it says that read() has > > returned the data as a string object. ?Now - how do I convince Python > > that the string object is in fact an excel file - and save it to disk? > > You don't need to convince Python, just write it to a file. > More reading for you:http://docs.python.org/tut/node9.html > > > pat > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves OK: response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ excel? priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) # print(response) f = open("c:\\msci.xls",'w') f.write(response) OK this makes the file, and there's a c:\msci.xls in place and it's about the right size. But whether I make the second param to open 'w' or 'wb', when I try to open msci.xls from the Windows file explorer, excel tells me that the file is corrupted. pat From carsten.haese at gmail.com Wed Jul 23 16:48:36 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Wed, 23 Jul 2008 16:48:36 -0400 Subject: Raw Strings (I Think) In-Reply-To: References: Message-ID: Lanny wrote: >> No, it doesn't. Instead of guessing what the cause might be, please show >> us your code and show us the error message you're getting, so that we can >> determine what the cause really is. > > Ok, sorry. Heres my code: > [...] And the error message you're getting is...? -- Carsten Haese http://informixdb.sourceforge.net From tjreedy at udel.edu Tue Jul 22 13:26:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2008 13:26:15 -0400 Subject: Is this a valid use of 'import'? In-Reply-To: References: Message-ID: Frank Millman wrote: > I know that when a module is imported the first time, it is > 'executed'. This normally entails setting up constants, classes, > functions, etc, that you want to make available to the importer. And every time thereafter, the module code is not executed*. So module code should only be code you want executed exactly once, on first import, and never again. > In this particular case, when it is executed, it does a whole lot > more. It reads in some parameters, establishes a socket connection, > starts a thread, and starts monitoring the socket using select.select. > It also exposes some functions that disguise the complexity of reading > from and writing to the socket. What if you want to open another connection, because you want a second, or because you closed the first (to help the server while the client does something else) or because the connection got dropped because the server timed it out or because of network congestion or whatever? tjr *Python2 has a built-in reload function, but in 3.0 it is removed because it almost never did what people wanted or expected and thus lead to surprising bugs. You can delete a module from sys.modules and re-import it, but the module object and those it created will not disappear as long as there are other references to them. From miki.tebeka at gmail.com Fri Jul 4 00:20:41 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 3 Jul 2008 21:20:41 -0700 (PDT) Subject: running python from cmd.exe References: Message-ID: Hello, > I can't seem to get python to run my scripts using the command: python > .py > > If I type python the interpreter runs as I sorted out the Path property, > > I'm afraid I don't know much about this kind of thing as I'm a science > student who needs some Python not a programmer! Can you be more specific about the error you get? Say you have a script hw.py that contains one line: print "Hello Python" and you run python hw.py What is the error you get? HTH, -- Miki http://pythonwise.blogspot.com From pavlovevidence at gmail.com Wed Jul 30 00:17:24 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 21:17:24 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> Message-ID: <7f4a3d37-e551-4e21-b660-3618016cb67b@z6g2000pre.googlegroups.com> On Jul 29, 10:23 pm, Erik Max Francis wrote: > Carl Banks wrote: > > Bzzt. "if len(x)!=0" is a simple explicit that would work for this > > class and all built-in containers. (Or should--Steven D'Aprano's > > objections notwithstanding, any reasonable container type should > > support this invariant. From a language design standpoint, an "empty" > > builtin could have been created to simplify this even more, but since > > there isn't one len(x)!=0 will have to do.) > > That you choose not to test for non-emptiness doesn't change the fact > that it's already a builtin part of the language that is supported by > all fundamental types and is overridable by anyone writing a custom > type. Use it or don't use it, but it's an example of precisely what you > were asking for that is both practical and already in widespread use. That's not what I was asking for. I was asking for a use case for "if x" that can't be replaced by a simple explicit test. Your example didn't satisfy that. Carl Banks From apardon at forel.vub.ac.be Tue Jul 1 07:46:39 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 1 Jul 2008 11:46:39 GMT Subject: Why is recursion so slow? References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Message-ID: On 2008-06-29, slix wrote: > Recursion is awesome for writing some functions, like searching trees > etc but wow how can it be THAT much slower for computing fibonacci- > numbers? Try the following recursive function: def fib(n): def gfib(a, b , n): if n == 0: return a else: return gfib(b, a + b, n - 1) return gfib(0, 1, n) -- Antoon Pardon From tjreedy at udel.edu Wed Jul 9 13:42:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 09 Jul 2008 13:42:14 -0400 Subject: Anyone happen to have optimization hints for this loop? In-Reply-To: <6dk4v0F311k1U1@mid.uni-berlin.de> References: <32fd142e-b198-430e-888b-01aee4e63ac0@c65g2000hsa.googlegroups.com> <6dk4v0F311k1U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > dp_pearce wrote: >> >> count = 0 >> dmntString = "" >> for z in range(0, Z): >> for y in range(0, Y): >> for x in range(0, X): >> fraction = domainVa[count] >> dmntString += " " >> dmntString += fraction Minor point, just construct " "+domain[count] all at once >> count = count + 1 >> dmntString += "\n" >> dmntString += "\n" >> dmntString += "\n***\n >> >> dmntFile = open(dmntFilename, 'wt') >> dmntFile.write(dmntString) >> dmntFile.close() >> >> I have found that it is currently taking ~3 seconds to build the >> string but ~1 second to write the string to file, which seems wrong (I >> would normally guess the CPU/Memory would out perform disc writing >> speeds). >> >> Can anyone see a way of speeding this loop up? Perhaps by changing the >> data format? Is it wrong to append a string and write once, or should >> hold a file open and write at each instance? > > Don't use in-place adding to concatenate strings. It might lead to > quadaratic behavior. Semantically, repeated extension of an immutable is inherently quadratic. And it is for strings in Python until 2.6 or possibly 2.5 (not sure), when more sophisticated code was added because people kept falling into this trap. But since the more sophisticated code 'cheats' by mutating the immutable (with an algorithm similar to list.extend),I am pretty sure it will only be used when there is only one reference to the string and the extension is with +=, so that the extension can reliably be done in-place without changing semantics. Thus, Python programmers should still learn the following. > Use the "".join()-idiom instead: (Or upgrade) > > dmntStrings = [] > .... > dmntStrings.append("\n") > .... > dmntFile.write("".join(dmntStrings)) Note that the minor point above will cut the number of things to be joined nearly in half. tjr From tjreedy at udel.edu Thu Jul 10 15:52:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jul 2008 15:52:08 -0400 Subject: parsing incoming emails In-Reply-To: References: Message-ID: > I am working on a project where I need to parse incoming emails > (Microsoft outlook) with a specific subject into an excel file or a > Microsoft access table. You should be able to give Outlook a rule to call a program (your Python one) when the subject matches whatever. From Python, use the mail module to parse and the windows extensions to access Excel and perhaps Access. There should also be a DBapi extension for accessing Access through sql. Search c.l.p archives, the web, or wait for others to post. From deets at nospam.web.de Mon Jul 28 18:29:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jul 2008 00:29:09 +0200 Subject: Download excel file from web? In-Reply-To: References: Message-ID: <6f6vhlFa7anrU1@mid.uni-berlin.de> patf at well.com schrieb: > On Jul 28, 3:00 pm, "p... at well.com" wrote: >> Hi - experienced programmer but this is my first Python program. >> >> This URL will retrieve an excel spreadsheet containing (that day's) >> msci stock index returns. >> >> http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... >> >> Want to write python to download and save the file. >> >> So far I've arrived at this: >> >> [quote] >> # import pdb >> import urllib2 >> from win32com.client import Dispatch >> >> xlApp = Dispatch("Excel.Application") >> >> # test 1 >> # xlApp.Workbooks.Add() >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' >> # xlBook = xlApp.ActiveWorkbook >> # xlBook.SaveAs(Filename='C:\\test.xls') >> >> # pdb.set_trace() >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ >> excel? >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> +25%2C+2008&export=Excel_IEIPerfRegional') >> # test 2 - returns check = False >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ >> indexperf/excel? >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() >> >> xlApp = response.fp >> print(response.fp.name) >> print(xlApp.name) >> xlApp.write >> xlApp.Close >> [/quote] > > Woops hit Send when I wanted Preview. Looks like the html [quote] tag > doesn't work from groups.google.com (nice). > > Anway, in test 1 above, I determined how to instantiate an excel > object; put some stuff in it; then save to disk. > > So, in theory, I'm retrieving my excel spreadsheet with > > response = urllib2.urlopen() > > Except what then do I do with this? > > Well for one read some of the urllib2 documentation and found the > Request class with the method has_data() on it. It returns False. > Hmm that's not encouraging. > > I supposed the trick to understand what urllib2.urlopen is returning > to me; rummage around in there; and hopefully find my excel file. > > I use pdb to debug. This is interesting: > > (Pdb) dir(response) > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > 'code', ' > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > 'readline', ' > readlines', 'url'] > (Pdb) > > I suppose the members with __*_ are methods; and the names without the > underbars are attributes (variables) (?). No, these are the names of all attributes and methods. read is a method, for example. > Or maybe this isn't at all the right direction to take (maybe there > are much better modules to do this stuff). Would be happy to learn if > that's the case (and if that gets the job done for me). The docs (http://docs.python.org/lib/module-urllib2.html) are pretty clear on this: """ This function returns a file-like object with two additional methods: """ And then for file-like objects: http://docs.python.org/lib/bltin-file-objects.html """ read( [size]) Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread() more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. """ Diez From p0q0b0d at gmail.com Wed Jul 9 03:19:45 2008 From: p0q0b0d at gmail.com (|e0) Date: Wed, 9 Jul 2008 09:19:45 +0200 Subject: Newbie question In-Reply-To: References: <3b1e6f480807082337l419fd40ax91eaf13e0701c5b3@mail.gmail.com> Message-ID: <3b1e6f480807090019p1d9ed0ev7a950d026424f826@mail.gmail.com> So, i can't use wmi module on linux? On Wed, Jul 9, 2008 at 9:14 AM, Lamonte Harris wrote: > I think the win32 module is only for windows. > From wuwei23 at gmail.com Fri Jul 25 10:43:17 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 25 Jul 2008 07:43:17 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <579f9d5b-8984-425d-8d4f-b2ed0be8eaba@o40g2000prn.googlegroups.com> <6c809cef-3549-4887-85c2-9110a2858a9b@y22g2000prd.googlegroups.com> Message-ID: On Jul 25, 9:49?pm, Lie wrote: > These two statements contradicts each other, > implying an implicit Zen: "Foolish consistency is the hobgoblin's > little minds", it is OK to break the rules sometimes. "A foolish consistency is _the_ hobgoblin of little minds." (Ralph Waldo Emerson, although the emphasis is mine) I do like your version, though :) From bj_666 at gmx.net Sun Jul 20 16:27:07 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Jul 2008 20:27:07 GMT Subject: question References: Message-ID: <6ehlcrF6uhc3U4@mid.uni-berlin.de> On Sun, 20 Jul 2008 18:39:52 +0100, Perl_Wizard wrote: > Nobody any sensible answers. Too complicated I suppose! I've often been asked that, i'd be able to buy me a mars bar! Ciao, Marc 'BlackJack' Rintsch From larry.bates at websafe.com` Mon Jul 21 23:59:15 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 22:59:15 -0500 Subject: Python Written in C? In-Reply-To: References: Message-ID: Grant Edwards wrote: > On 2008-07-22, Larry Bates wrote: > >> You talk about "writing it in assembly language for each MPU >> chip". Actually it is even better than that. We now have >> these modern inventions, called compilers that do that type of >> work for us. They translate high level instructions, not >> into assembler but into machine language. > > Actually, all of the compilers I'm familiar with (gcc and a > handful of cross compilers for various microprocessors) > translate from high-level languages (e.g. C, C++) into > assembly, which is then assembled into relocatable object > files, which are then linked/loaded to produce machine > language. > I just learned something I did not know. I was under the impression that they translated directly to machine code without ever actually generating Assembler text files. Seems like a waste to generate the text and turn around run that through the assembler, but what do I know. I guess that way the compiler can have pluggable assembler back-ends. -Larry From mnordhoff at mattnordhoff.com Tue Jul 1 03:12:22 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Tue, 01 Jul 2008 07:12:22 +0000 Subject: Are the following supported in scipy.sparse In-Reply-To: <7f324b8e-e1f9-466e-b6f2-fde8d5f11494@a70g2000hsh.googlegroups.com> References: <7f324b8e-e1f9-466e-b6f2-fde8d5f11494@a70g2000hsh.googlegroups.com> Message-ID: <4869D8D6.3010602@mattnordhoff.com> dingo_1980 wrote: > I wanted to know if scipy.sparse support or will support the following > functions which are available in scipy.linalg or scipy or numpy: > > Inverse > Cholesky > SVD > multiply > power > append > eig > concatenate > > Thanks... You should probably ask on a SciPy mailing list. -- From cheapkobe at sina.com Fri Jul 18 01:16:23 2008 From: cheapkobe at sina.com (14789) Date: Thu, 17 Jul 2008 22:16:23 -0700 (PDT) Subject: wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal Message-ID: <8be58a85-04e1-4617-8ba7-1d10b09b83a3@a3g2000prm.googlegroups.com> wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal From jordanrastrick at gmail.com Thu Jul 24 01:46:38 2008 From: jordanrastrick at gmail.com (Jordan) Date: Wed, 23 Jul 2008 22:46:38 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: On Jul 24, 3:41?pm, Jordan wrote: > Hi everyone, > > I'm a big Python fan who used to be involved semi regularly in > comp.lang.python (lots of lurking, occasional posting) but kind of > trailed off a bit. I just wrote a frustration inspired rant on my > blog, and I thought it was relevant enough as a wider issue to the > Python community to post here for your discussion and consideration. > > This is not flamebait. I love Python, and I'm not out to antagonise > the community. I also realise that one of the issues I raise is way > too ingrained to be changed now. I'd just like to share my thinking on > a misstep in Python's guiding principles that has done more harm than > good IMO. So anyway, here's the post. > > I've become utterly convinced that at least one criticism leveled at > my favourite overall programming language, Python, is utterly true and > fair. After quite a while away from writing Python code, I started > last night on a whim to knock up some code for a prototype of an idea > I once had. It's going swimmingly; the Python Image Library, which I'd > never used before, seems quick, intuitive, and with the all the > features I need for this project. As for Python itself, well, my heart > still belongs to whitespace delimitation. All the basics of Python > coding are there in my mind like I never stopped using them, or like > I've been programming in this language for 10 years. > > Except when it comes to Classes. I added some classes to code that had > previously just been functions, and you know what I did - or rather, > forgot to do? Put in the 'self'. In front of some of the variable > accesses, but more noticably, at the start of *every single method > argument list.* This cannot be any longer blamed as a hangover from > Java - I've written a ton more code, more recently in Python than in > Java or any other OO language. What's more, every time I go back to > Python after a break of more than about a week or so, I start making > this 'mistake' again. The perennial justification for this 'feature' > of the language? That old Python favourite, "Explicit is better than > implicit." > > I'm sorry, but EXPLICIT IS NOT NECESSARILY BETTER THAN IMPLICIT. > Assembler is explicit FFS. Intuitive, clever, dependable, expected, > well-designed *implicit* behaviour is one of the chief reasons why I > use a high level language. Implicitly garbage collect old objects for > me? Yes, please! > > I was once bitten by a Python wart I felt was bad enough to raise and > spend some effort advocating change for on comp.lang.python (never got > around to doing a PEP; partly laziness, partly young and inexperienced > enough to be intimidated at the thought. Still am, perhaps.) > > The following doesn't work as any sane, reasonable person would > expect: > > # Blog code, not tested > class A(): > ? def __eq__(self, obj): > ? ? return True > a = A() > b = [] > assert a == b > assert not (a != b) > > The second assertion fails. Why? Because coding __eq__, the most > obvious way to make a class have equality based comparisons, buys you > nothing from the != operator. != isn't (by default) a synonym for the > negation of == (unlike in, say, every other language ever); not only > will Python let you make them mean different things, without > documenting this fact - it actively encourages you to do so. > > There were a disturbingly high number of people defending this > (including one quite renowned Pythonista, think it might have been > Effbot). Some had the temerity to fall back on "Explicit is better > than implict: if you want != to work, you should damn well code > __ne__!" > > Why, for heaven's sake, should I have to, when in 99.99% of use cases > (and of those 0.01% instances quoted in the argument at the time only > one struck me as remotely compelling) every programmer is going to > want __ne__ to be the logical negation of __eq__? Why, dear Python, > are you making me write evil Java-style language power reducing > boilerplate to do the thing you should be doing yourself anyway? > What's more, every programmer is going to unconciously expect it to > work this way, and be as utterly as mystified as me when it fails to > do so. Don't tell me to RTFM and don't tell me to be explicit. I'll > repeat myself - if I wanted to be explicit, I'd be using C and > managing my own memory thank you very much. Better yet, I'd explicitly > and graphically swear - swear in frustration at this entrenched design > philosophy madness that afflicts my favourite language. > > I think the real problem with the explicit is better than implicit, > though, is that while you can see the underlying truth its trying to > get at (which is perhaps better expressed by Ruby's more equivocal, > less dependable, but more useful Principle of Least Surprise), in its > stated form its actually kind of meanginless and is used mainly in > defence of warts - no, we'll call them for what they are, a language > design *bugs*. > > You see, the problem is, there's no such thing of explict in > programming. Its not a question of not doing things implicitly; its a > question of doing the most sensible thing implicitly. For example this > python code: > > some_obj.some_meth(some_arg1, some_arg2) > > is implicitly equivalent to > > SomeClass.some_meth(some_obj, some_arg1, some_arg2) > > which in turn gives us self as a reference to some_obj, and Python's > OO model merrily pretends its the same as Java's when in fact is a > smarter version that just superficially looks the same. > > The problem is that the explicit requirement to have self at the start > of every method is something that should be shipped off to the > implicit category. You should have to be explicit, yes - explicit when > you want the *other* behaviour, of self *not* being an argument, > because thats the more unusual, less likely case. > > Likewise, > > a != b > > is implicitly equivalent to something like calling this function (may > not be correct, its a while since I was heavily involved in this > issue): > > def equal(a, b): > ? if hasattr(a, "__ne__"): return a.__ne__(b) > ? if hasattr(b, "__ne__"): return b.__ne__(a) > ? if hasattr(a, "__cmp__"): return not (a.__cmp__(b) == 0) > ? if hasattr(b, "__cmp__"): return not (b.__cmp__(a) == 0) > ? return not (a is b) > > There's absolutely nothing explicit about this. I wasn't arguing for > making behaviour implicit; I was arguing for changing the stupid > implict behaviour to something more sensible and less surprising. > > The sad thing is there are plenty of smart Python programmers who will > justify all kinds of idiocy in the name of their holy crusade against > the implict. > > If there was one change I could make to Python, it would be to get > that damn line out of the Zen. P.S. Forgive the typos, it was blogged in extreme haste and then only quickly proofread and edited before posting here. Hopefully the point I'm making is not diminshed by your reduced respect for me as a result of my carelessness :-) From lemcoe9 at bellsouth.net Fri Jul 18 17:47:39 2008 From: lemcoe9 at bellsouth.net (David M Lemcoe Jr.) Date: Fri, 18 Jul 2008 21:47:39 +0000 (UTC) Subject: Any Game Developers here? References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: Hello Michael, > Any people that use Python as the predominant language for their game > development here? > > ~Michael > Well, I make little CLI games that are extremely basic and have no actual graphics, but i'm sure a few people actually use them in video games. David From tonal at promsoft.ru Thu Jul 17 03:32:35 2008 From: tonal at promsoft.ru (Alexandr N Zamaraev) Date: Thu, 17 Jul 2008 14:32:35 +0700 Subject: Getting a unknown word out of a list with no spaces In-Reply-To: <18502758.post@talk.nabble.com> References: <18502758.post@talk.nabble.com> Message-ID: <487EF593.5060505@promsoft.ru> >>> s = '--a href="/browse/brick"--brick--/a--' >>> s '--a href="/browse/brick"--brick--/a--' >>> ''.join('<%s>' % l if i % 2 == 1 else l for i, l in enumerate(s.split('--'))) 'brick' From nicolas.pourcelot at gmail.com Sun Jul 20 14:33:06 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Sun, 20 Jul 2008 11:33:06 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> <6ebshqF67cpfU4@mid.uni-berlin.de> <5d6b8066-c941-4f0c-abea-20baed33b4ab@l64g2000hse.googlegroups.com> <569da8b8-df8a-4115-a952-5d8c2d9744e0@i20g2000prf.googlegroups.com> Message-ID: <46c2153d-fef6-45b5-91af-9ecb359e6a2b@2g2000hsn.googlegroups.com> > (1) You are searching through lists to find float objects by identity, > not by value ???? From callen314 at gmail.com Wed Jul 16 21:25:15 2008 From: callen314 at gmail.com (Craig Allen) Date: Wed, 16 Jul 2008 18:25:15 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Message-ID: I don't intend to do much subclassing of this, but of course, I'd rather not second guess the future and it's not hard to imagine we will come to some point that we need to do just that. Thanks for the ideas about repairing option one, which I'd given up, though the ideal is still that tl = TehLibrary() would always return the same object. -craig On Jul 16, 2:00 pm, castironpi wrote: > On Jul 16, 5:20 pm, Craig Allen wrote: > > > > > Hey, forgive me for just diving in, but I have a question I was > > thinking of asking on another list but it really is a general question > > so let me ask it here. It's about how to approach making singletons. > > Background: I've been programming in python seriously for about a year > > now, maybe a little longer depending how you count, and the system I > > am making is sophisticated enough that I've had to enter into a few > > idioms which were beyond my knowledge of python, and I had to do quick > > research and test my ideas with test code (which of course can miss > > subtle problems). Otoh, I have decades of programming experience now > > and wasn't totally without footing. I think I have a solution I like > > for creating something to act as a singleton but I'm curious what > > other's think. > > > I have several classes in our system which need to act like > > singletons, they are libraries of data classifications, and other such > > libraries of configurations for the system which need to be global. > > > The first thing I found searching for singleton, early in this > > project, trying to be a good citizen and find a decent idiom from the > > python community itself, knowing someone had mentioned "singleton" and > > "python" together at some point, was a recommendation to do this: > > > (option 1) > > > class TehLibrary(object): > > __single = None > > def __init__(self): > > if (TehLibrary.__single): > > raise AlreadyExistsException # or whatever > > > This sucks because that means creation of the object has to be in a > > try block as a matter of course, something I promptly hid in a factory > > function, but still. > > > But the way this worked made me realize that the Class itself is a > > full fledged object, quite instance-like from my C++ addled (I love > > you C++) perspective and it's single. If I can store that instance, I > > can make a class that shares member at the class level. The class > > doesn't even have to be a singleton exactly. > > > (option 2) > > Therefore option two is a family of options where class level members > > can be used to share whatever needs to be shared, though strictly the > > class is not a singleton since multiple instances are created which > > merely share the data that should be single (say a big dictionary of > > configuration information the class manages). > > > (option 3) > > I still wanted actual singletons and realized that since I had to > > create a factory function even in option 1, that I could use module > > level variables to control the behavior of those factories, which led > > me to realize I'm basically just using the module itself as a > > singleton. And this is sort of where I have arrived... when I import > > the modules it runs code to build up it's basic services, much like an > > object construction. It only runs once no matter how many times it's > > imported. When client code asks for the library that should be a > > singleton, it gets a singleton which has been stored in a module level > > variable. > > > Anyone have any comments? Is there anything wrong, evil, or ugly > > about using a module this way, or am I correct to think that actually, > > this is a common approach in python. > > > Is it pythonic? > > In option 1, you could use the __new__ method, and return the existing > instance if there is one, or, I believe, call __init__ on the > superclass. Alternatively, define your own 'create' method with the > @classmethod decorator, instantiate with ClassA.create( ), and return > any existing instance from there. The catch is you need to rely on > the discipline of not using the default instantiation syntax. > > In option 2, you would have to wrap the functions with the > @staticmethod decorator, and all instance methods would act on the > same object. > > Each of these have different consequences for inheritance, if that is > on the horizon in your project. From sri_annauni at yahoo.co.in Thu Jul 3 00:55:44 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Thu, 3 Jul 2008 10:25:44 +0530 (IST) Subject: How to pickle bound methods Message-ID: <573056.8255.qm@web7910.mail.in.yahoo.com> Peter, Could you please explain?the code breifly?? I am not getting what it does. Thanks, Srini? ----- Original Message ---- From: Peter Otten <__peter__ at web.de> To: python-list at python.org Sent: Wednesday, 2 July, 2008 12:53:19 PM Subject: Re: How to pickle bound methods srinivasan srinivas wrote: > I would like?to know how to pickle a bound method?? $ cat pickle_method.py import copy_reg import new def make_instancemethod(inst, methodname): ? ? return getattr(inst, methodname) def pickle_instancemethod(method): ? ? return make_instancemethod, (method.im_self, method.im_func.__name__) copy_reg.pickle(new.instancemethod, pickle_instancemethod, make_instancemethod) if __name__ == "__main__": ? ? import pickle ? ? class A(object): ? ? ? ? def __init__(self, who): ? ? ? ? ? ? self.who = who ? ? ? ? def alpha(self): ? ? ? ? ? ? print "Hello,", self.who ? ? FILENAME = "method.pickle" ? ? import sys ? ? args = sys.argv[1:] ? ? if args: ? ? ? ? a = A(args[0]) ? ? ? ? m = a.alpha ? ? ? ? pickle.dump(m, open(FILENAME, "wb")) ? ? else: ? ? ? ? m = pickle.load(open(FILENAME, "rb")) ? ? ? ? m() $ python pickle_method.py world $ python pickle_method.py Hello, world $ python pickle_method.py Srini $ python pickle_method.py Hello, Srini Peter -- http://mail.python.org/mailman/listinfo/python-list Share files, take polls, and make new friends - all under one roof. Go to http://in.promos.yahoo.com/groups/ From Chris.Rathman at gmail.com Tue Jul 22 01:43:24 2008 From: Chris.Rathman at gmail.com (Chris Rathman) Date: Mon, 21 Jul 2008 22:43:24 -0700 (PDT) Subject: proliferation of computer languages References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> Message-ID: <40429b65-23a0-489b-b5fd-ae6b8eee607d@t54g2000hsg.googlegroups.com> I can't say that I see any particular point to the essay. But I did want to point out that Oz should not be considered part of the ML family. Aside from not being statically typed - a very central tenet to ML, Oz is much more part of the Logic family of languages (Mercury, Prolog, etc...). On Jul 18, 12:17 pm, "xah... at gmail.com" wrote: > Today, i took sometime to list some major or talked-about langs that > arose in recent years. > > ML Family: > > * Oz?J. Concurrent. Multiparadigm. > * Alice?J. Concurrent, ML derivative. Saarland University, Germany. > * OCaml?J > * F#?J. Microsoft's functional lang. From peter.anderson at internode.on.net Wed Jul 16 02:39:25 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Wed, 16 Jul 2008 16:39:25 +1000 Subject: Python internals In-Reply-To: <87hcaq7pja.fsf@benfinney.id.au> References: <008ca729$0$20313$c3e8da3@news.astraweb.com> <87hcaq7pja.fsf@benfinney.id.au> Message-ID: <008d93af$0$20327$c3e8da3@news.astraweb.com> Ben Finney wrote: > Larry Bates writes: > > The term "pointer" carries much extra baggage for a programmer > thinking of C (as the original poster is)... Thanks everyone! Just a quick correction - "as the original poster is" is a bit of a jump that does not reflect my original question. I DO understand how C and other programming languages handle variables internally (the bits of actual memory reserved, etc. etc.) and that's why I asked the question in the first place. If Python doesn't do it like C and the others then what mechanism does it use - it's the sort of issue that helps me understand how the language is interacting with the underlying operating system/hardware. By way of background, in my ancient working days I looked after mainframe systems written in COBOL and Natural (and some assembler which I never had to support personally but my staff did). I found that most programmers write bad code because they don't understand what the machine is doing with their code. Probably doesn't matter any more but old habits die hard! ;-) Regards, Peter -- Peter Anderson There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things -- Niccolo Machiavelli, The Prince, ch. 6 From straton at lampsacos.demon.co.uk Fri Jul 11 07:42:58 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 11 Jul 2008 12:42:58 +0100 Subject: PIL: Transparent PNGs and im.paste: ValueError: bad transparency mask In-Reply-To: References: Message-ID: Durand wrote: > I posted this too soon. Converting the images to png with image magick's convert did the trick...However, I'm still not sure why I need to convert the images in the first place. Are there different types of PNGs? http://en.wikipedia.org/wiki/Portable_Network_Graphics#Transparency_of_image From gherron at islandtraining.com Mon Jul 7 18:02:15 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 07 Jul 2008 15:02:15 -0700 Subject: "in"consistency? In-Reply-To: References: Message-ID: <48729267.1060104@islandtraining.com> Nick Dumas wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > [1,2] in [1,2,3] checks to see if the list [1,2] is an item in [1,2,3]. > Because the list [1,2,3] only contains the integers 1,2,3, the code > returns a False. Try "[1,2] in [[1,2],[2,3]]" > The inconsistency goes deeper than that. For instance, the type of a value returned by the indexing operation: Indexing a string returns a string (of length 1 of course), while indexing a list does not (necessarily) return a list. Conclusion: They are different types supporting different operations. Given all the obvious differences (mutability, sorting and other methods, types of individual elements), I'd say there are more differences than similarities, even though, as sequences, they both support a small subset of similar operations. Gary Herron > David C. Ullrich wrote: > >> Luckily I tried it before saying no, that's >> not how "in" works: >> >> >>>>> 'ab' in 'abc' >>>>> >> True >> >>>>> [1,2] in [1,2,3] >>>>> >> False >> >> Is there a reason for the inconsistency? I would >> have thought "in" would check for elements of a >> sequence, regardless of what sort of sequence it was... >> >> > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (MingW32) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iEYEARECAAYFAkhyiwEACgkQLMI5fndAv9jbiwCeKMXrAclILJMPro5VuSRgdkvB > cGkAn1igcjFWRQJSwEDOxpk3spzceZGa > =iq8L > -----END PGP SIGNATURE----- > -- > http://mail.python.org/mailman/listinfo/python-list > From Dogzilla1000 at gmail.com Tue Jul 8 12:44:21 2008 From: Dogzilla1000 at gmail.com (Dogzilla1000 at gmail.com) Date: Tue, 8 Jul 2008 09:44:21 -0700 (PDT) Subject: problem with Tkinter after installing Python 2.5.2 on UBUNTU Message-ID: <83df18ac-e39c-4a1d-95a0-53886d873ea8@s50g2000hsb.googlegroups.com> I just installed Python 2.5.2 on UBUNTU Linux. It seems to work, however I don't seem to have access Tkinter. This is the result of "import Tkinter": Python 2.5.2 (r252:60911, Jul 7 2008, 12:39:49) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Tkinter Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.5/lib-tk/Tkinter.py", line 38, in import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter >>> What do I need to do to configure Python for Tk? From tjreedy at udel.edu Sat Jul 26 18:24:04 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 18:24:04 -0400 Subject: os.walk question In-Reply-To: <92da89760807261310r39df1109j4cf7133d8144508b@mail.gmail.com> References: <92da89760807261310r39df1109j4cf7133d8144508b@mail.gmail.com> Message-ID: Eric Wertman wrote: > I do this, mabye a no-no? It is a roundabout way to do multiple assignment: > import os > for root,dirs,files in os.walk(dir) : break root,dirs,files = os.walk(dir).next #2.x root,dirs,files = next(os.walk(dir))#3.x From deets at nospam.web.de Mon Jul 28 17:39:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 23:39:19 +0200 Subject: Proxy server? In-Reply-To: References: <6f5rteF89muqU2@mid.uni-berlin.de> Message-ID: <6f6sk7Fa4tf5U1@mid.uni-berlin.de> Gary schrieb: > "Diez B. Roggisch" wrote in message > news:6f5rteF89muqU2 at mid.uni-berlin.de... >> Gary wrote: > >> For what? > > A non-transparent proxy, for anonymity purposes only. You can't make any TCP/IP communication run through a proxy, unless it's transparent. HTTP (and maybe FTP, I personally don't know) have that built-in, and of course anything that builds upon them (SOAP, XMLRPC). But e.g. CORBA or bittorrent or .... don't support that. You can try and install TOR or use it. It is a transparent proxy: http://wiki.noreply.org/noreply/TheOnionRouter/TransparentProxy Diez From norseman at hughes.net Thu Jul 10 13:03:01 2008 From: norseman at hughes.net (norseman) Date: Thu, 10 Jul 2008 10:03:01 -0700 Subject: variable question In-Reply-To: <01da01c8e1fb$7615a4f0$a701a8c0@office.ipglobal.net> References: <01da01c8e1fb$7615a4f0$a701a8c0@office.ipglobal.net> Message-ID: <487640C5.5030604@hughes.net> Support Desk wrote: > I am trying to assign a variable using an if / else statement like so: > > > > If condition1: > > Variable = something > > If condition2: > > Variable = something else > > Do stuff with variable. > > > > But the variable assignment doesn't survive outside the if statement. Is > there any better way to assign variables using an if statement or exception > so I don't have to write two almost identical if statements. This is > probably a dumb question. > > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list =================================== Is this test in a def? If in-line there should be no problem if Var is done as this: var= ' ' test= '2' if test == '1': var= 'choice 1' elif test == '2': var= 'choice 2' elif test == '3': var= 'default' #endif #do something with var print var ----------------- if inside a def: var= 0 def xxx(): global var var += 1 # whatever, if var was set to text, do text things #possible other commands #enddef # somewhere below in 'main' (runtime portion of code) xxx() print var #use var, etc. etc. ----------------- It is ALWAYS good form to prime a var before using. Steve norseman at hughes.net From semanticist at gmail.com Thu Jul 31 18:58:24 2008 From: semanticist at gmail.com (Miles) Date: Thu, 31 Jul 2008 18:58:24 -0400 Subject: Difference between type and class In-Reply-To: <87fxpq7x41.fsf@nokile.rath.org> References: <87myjy2vc6.fsf@nokile.rath.org> <87r69a85ek.fsf@nokile.rath.org> <87fxpq7x41.fsf@nokile.rath.org> Message-ID: On Thu, Jul 31, 2008 at 1:59 PM, Nikolaus Rath wrote: > If it is just a matter of different rendering, what's the reason for > doing it like that? Wouldn't it be more consistent and straightforward > to denote builtin types as classes as well? Yes, and in Python 3, it will be so: >>> class myint(int): pass ... >>> int >>> myint The reason the distinction is made currently is that before Python 2.2, "types" were built-in (or C extension) classes, and "classes" were Python classes; it was not possible to subclass built-in types. That "classic" style of classes are still supported in Python 2.2 and above (but not in Python 3), by not inheriting from object or any other built-in. However, for new-style classes, the only distinction is in the repr. >>> class classic: pass ... >>> class newstyle(object): pass ... >>> type(classic) >>> type(classic()) >>> classic.__class__ Traceback (most recent call last): File "", line 1, in AttributeError: class classic has no attribute '__class__' >>> classic().__class__ >>> >>> type(newstyle) >>> type(newstyle()) Further reading: http://www.python.org/download/releases/2.2.3/descrintro/ http://svn.python.org/view?rev=23331&view=rev http://bugs.python.org/issue2565 -Miles From jonas at codeazur.com.br Wed Jul 2 20:16:28 2008 From: jonas at codeazur.com.br (Jonas Galvez) Date: Wed, 2 Jul 2008 21:16:28 -0300 Subject: ANN: XML builder for Python Message-ID: <10df03a30807021716v33518930g951e903c2529ef82@mail.gmail.com> Not sure if it's been done before, but still... from __future__ import with_statement from xmlbuilder import builder, element xml = builder(version="1.0", encoding="utf-8") with xml.feed(xmlns='http://www.w3.org/2005/Atom'): xml.title('Example Feed') xml.link(None, href='http://example.org/') xml.updated('2003-12-13T18:30:02Z') with xml.author: xml.name('John Doe') xml.id('urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6') with xml.entry: xml.title('Atom-Powered Robots Run Amok') xml.link(None, href='http://example.org/2003/12/13/atom03') xml.id('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a') xml.updated('2003-12-13T18:30:02Z') xml.summary('Some text.') print xml Will produce: Example Feed 2003-12-13T18:30:02Z John Doe urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6 Atom-Powered Robots Run Amok urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a 2003-12-13T18:30:02Z Some text. http://github.com/galvez/gae-rest/tree/258066f5e1a32c999e04a9313943fdfa8e64edd9/xmlbuilder.py --Jonas Galvez From alexnbryan at gmail.com Sat Jul 5 07:15:41 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Sat, 5 Jul 2008 06:15:41 -0500 Subject: Margins in the Tkinter Text widget Message-ID: <10942F2C-5D83-4A14-8777-F2B1449E65BC@gmail.com> Okay, so i am trying to have some sort of formatting going on in a textbox, and I need left margins. I see that there are two, one for the first line and th other for every line but that line. My program gives a word and a list of definitions for the word. So my question is how can I make the it repeat itself. Like I want to have something formatted like this: word: definiton1 definition2 word2: defintion12 definition22 and so on. So I don't really understand how to keep like redoing the margins I guess. Would love some help! From sun_tong_001 at users.sourceforge.net Sat Jul 5 18:06:27 2008 From: sun_tong_001 at users.sourceforge.net (* Tong *) Date: Sat, 05 Jul 2008 17:06:27 -0500 Subject: perl + python tutorial available for download References: <86c4090b-ed0b-4249-b3ee-517c94328741@z32g2000prh.googlegroups.com> Message-ID: On Tue, 01 Jul 2008 12:02:24 +0000, Ben Bullock wrote: > I'm a big fan of code samples - most of my code starts as other people's > code samples. What I think is missing, Xah, is that the actual result. I.e, showing that "you can do this" only covers less than half of the tutorial, showing what the result is is more important. From basti.wiesner at gmx.net Sun Jul 6 14:33:42 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sun, 06 Jul 2008 20:33:42 +0200 Subject: Problem with subprocess.Popen wget within a thread References: Message-ID: Mathieu Prevot : > it seems the script (A) finishes before the downloading ends, and the > (B) version doesn't (wanted behavior) ... this is unexpected. What > happens ? "readlines" blocks, until the pipe is closed, which usually happens, if the process dies. On the other hand, spawned processes are usually asynchronous, you have to explicitly _wait_ for them. And you're not waiting for it in example A. Anyway, the _proper_ way to wait for a child process is ... guess what ... the "wait" method of the Popen object ;) -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From casey.mcginty at gmail.com Tue Jul 29 19:07:40 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Tue, 29 Jul 2008 13:07:40 -1000 Subject: How can I check nbr of cores of computer? In-Reply-To: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> Message-ID: On Tue, Jul 29, 2008 at 12:53 PM, defn noob wrote: > How can I check how many cores my computer has? > Is it possible to do this in a Python-app? > -- > http://mail.python.org/mailman/listinfo/python-list > You can use the HAL interface from the DBUS module. See also the gnome-device-manager app which lists all the HAL devices. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Wed Jul 9 11:55:16 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 9 Jul 2008 08:55:16 -0700 (PDT) Subject: Regular Expressions Quick Question References: Message-ID: <5d82ad48-5ffc-44db-a3bd-3773fe7c8709@l64g2000hse.googlegroups.com> On Jul 9, 2:24?am, "Rajanikanth Jammalamadaka" wrote: > hi! > > Try this: > > >>> lis=['t','tes','test','testing'] > >>> [elem for elem in lis if re.compile("^te").search(elem)] > > ['tes', 'test', 'testing'] > > Cheers, > > Raj > > > > > > On Wed, Jul 9, 2008 at 12:13 AM, Lamonte Harris wrote: > > Alright, basically I have a list of words in a file and I load each word > > from each line into the array. ?Then basically the question is how do I > > check if the input word matches multiple words in the list. > > > Say someone input "test", how could I check if that word matches these list > > of words: > > > test > > testing > > tested > > > Out of the list of > > > Hello > > blah > > example > > test > > ested > > tested > > testing > > > I want it to loop then check if the input word I used starts any of the > > words in the list so if I typed 'tes' > > > Then: > > > test > > testing > > testing > > > would be appended to a new array. > > > I'm unsure how to do this in python. > > > Thanks in advanced. > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > "For him who has conquered the mind, the mind is the best of friends; > but for one who has failed to do so, his very mind will be the > greatest enemy." > > Rajanikanth- Hide quoted text - > > - Show quoted text - Give the built-in string functions a try before resorting to the re howitzers: >>> lis=['t','tes','test','testing'] >>> [elem for elem in lis if elem.startswith("te")] ['tes', 'test', 'testing'] -- Paul From dwahli at gmail.com Fri Jul 4 07:21:25 2008 From: dwahli at gmail.com (dwahli at gmail.com) Date: Fri, 4 Jul 2008 04:21:25 -0700 (PDT) Subject: Bug in re.findall? References: Message-ID: <9a34cb6a-4d18-4ab6-8ddd-f44fd450a4e4@m45g2000hsb.googlegroups.com> On Jul 4, 12:33?pm, Marcin Krol wrote: > Hello everyone, > > Is there a bug in re.findall in Python 2.4? See: > > subnetlist="192.168.100.0 , 192.168.101.0" > ipre=re.compile("([0-9]{1,3}\.){3}[0-9]{1,3}") > > ?>>> ipre.findall(subnetlist) > > ['100.', '101.'] > > But: > > a=ipre.finditer(subnetlist) > > ?>>> a.next().group() > '192.168.100.0' > ?>>> a.next().group() > '192.168.101.0' > ?>>> a.next().group() > Traceback (most recent call last): > ? ?File "", line 1, in ? > StopIteration > > Also: > > ?>>> ipre.search(subnetlist).group() > '192.168.100.0' > > Is this a bug or am I doing smth wrong? Look strange but match the Python documentation for re.findall: "If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group" you must use this RE for your example to match what you expect: ipre=re.compile("(?:[0-9]{1,3}\.){3}[0-9]{1,3}") but using re.finditer is IMHO better. Cheer, Dom From bmassel at descartes.com Tue Jul 15 15:51:41 2008 From: bmassel at descartes.com (Brock Massel) Date: Tue, 15 Jul 2008 15:51:41 -0400 Subject: graphing lifelines In-Reply-To: References: Message-ID: <78CC970856BCB3468058B65560DA97D003E7643D@XPOCSCA.corp.descartes.com> Google this: "drawing graphs with dot" dotguide.pdf Look at page ~40ff. Perhaps a simple script to generate graphviz input. Then let those excellent tools do the heavy lifting. -----Original Message----- From: python-list-bounces+bmassel=descartes.com at python.org [mailto:python-list-bounces+bmassel=descartes.com at python.org] On Behalf Of E. J. Gold is the Hi-Tech Shaman Sent: Tuesday, July 15, 2008 14:57 To: python-list at python.org Subject: graphing lifelines (crossposted to sci.math) I'm looking for a tool which will take a dataset of tuples indicating the year of birth and death of a person: (1872, 1950, "Sri Aurobindo") (1821, 1910, "Mary Baker Eddy") (1831, 1891, "HP. Blavatksy") And graph them out, in bars, annotating them with the person's name. A simple spreadsheet would've worked, but they seem to start from zero. Thus, I would only be able to indicate the span of life (by subtracting death year from birth year). -- http://mail.python.org/mailman/listinfo/python-list From adityashukla1983 at gmail.com Wed Jul 23 17:02:18 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Wed, 23 Jul 2008 16:02:18 -0500 Subject: Taking the floating point distances and plotting histogram Message-ID: <73045cca0807231402m1c439414s516e5409a704506f@mail.gmail.com> Hello folks:- I have a program whose output is stored in a text file , say test.txt eg. 0\9\10\11|0.50|c:\windows\apppatch/AcLayers.dll 0\9\10\11|0.50|c:\windows\apppatch/AcRedir.dll 0\9\10|0.66|c:\windows\apppatch/AcSpecfc.dll 0\9|0.83|c:\windows\apppatch/iebrshim.dll After reading this text file i need to extract the float point values from each line ie , 0.50,0.50,0.66.0.83 respectively in this case, till the end of the file is reached and then i need to plot a histogram based on these values . Please provide any hints on how to do this. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Nikolaus at rath.org Tue Jul 29 10:35:55 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Tue, 29 Jul 2008 16:35:55 +0200 Subject: [unittest] Run setUp only once Message-ID: <877ib4rc50.fsf@nokile.rath.org> Hello, I have a number of conceptually separate tests that nevertheless need a common, complicated and expensive setup. Unfortunately, unittest runs the setUp method once for each defined test, even if they're part of the same class as in class TwoTests(unittest.TestCase): def setUp(self): # do something very time consuming def testOneThing(self): def testADifferentThing(self): which would call setUp twice. Is there any way to avoid this, without packing all the unrelated tests into one big function? Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From ldo at geek-central.gen.new_zealand Mon Jul 21 05:15:24 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 21 Jul 2008 21:15:24 +1200 Subject: atan2 weirdness References: <3b3ce28f-55d0-4db4-8eac-df0a9d1bc558@o40g2000prn.googlegroups.com> Message-ID: In message , Carsten Haese wrote: > Since pi is close to 3 ... "Biblical pi" = 3. From mail at timgolden.me.uk Tue Jul 15 12:07:10 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Jul 2008 17:07:10 +0100 Subject: How can I save command prompt screen In-Reply-To: <401698.26103.qm@web44903.mail.sp1.yahoo.com> References: <401698.26103.qm@web44903.mail.sp1.yahoo.com> Message-ID: <487CCB2E.30501@timgolden.me.uk> Ty hensons wrote: > how can i save my command prompt screen? (Trying to be helpful here...) What do mean by "save" and what do you mean by "command prompt screen"? And, especially, what platform are you running on? TJG From paddy3118 at googlemail.com Wed Jul 23 15:56:35 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 23 Jul 2008 12:56:35 -0700 (PDT) Subject: Doubt References: Message-ID: <8c8592be-3bb2-4ee6-9f90-cd374233ba05@w7g2000hsa.googlegroups.com> On Jul 23, 3:51?pm, ???????? wrote: > Friends > > I am a Perl programmer new to Python. I have a small doubt. > How to convert the perl notation > $a = ""; expression in Python ? > > How to represent the loop > for ($a = $b; $a<=$c;$a++){ > > } in Python > > Jagan > Linguist This might help you generally: http://wiki.python.org/moin/PerlPhrasebook - Paddy. From marcus at internetnowasp.net Sat Jul 26 22:23:06 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Sun, 27 Jul 2008 10:23:06 +0800 Subject: Attack a sacred Python Cow In-Reply-To: <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <488BDC0A.50403@internetnowasp.net> Well after reading some of these posts on "sacred python cow" on the "self" , i would generally feel that most programmers who started with C++/Java would find it odd. And its true, i agree completely there should not be a need to put "self" into every single member function. If you were writing an application and one of your classes adds the same variable to each of its member function you would do away with it too. What could be done instead is :- 1. python should hardcode the keyword "self". So whenever this keyword is used, it would automatically implied that it is referring to a class scope variable. This would be similar to how the "this" keyword is used in C++. 2. Omit self from the parameter. class Abc : def DoSomething (a,b,c) : # class variable self.somevar = a self.someblar = b self.somec = c somevar = a * b # local variable Russ P. wrote: > On Jul 26, 2:25 pm, Terry Reedy > >> There is a lot of code you have not seen. Really. In informal code I >> use 's' and 'o' for 'self' and 'other'. I don't usually post such >> because it is not considered polite. So you have seen a biased sample >> of the universe. >> > > You take the name down to a single letter. As I suggested in an > earlier post on this thread, why not take it down to zero letters? You > could if Python accepted something like > > class Whatever: > > def fun( , cat): > > .cat = cat > > This is even better than the single-character name, not only because > it is shorter, but also because there is no question that you are > referring to "self." No need to look back at the method signature to > verify that. > > For those who don't like the way the empty first argument looks, maybe > something like this could be allowed: > > def fun( ., cat): > > -- > http://mail.python.org/mailman/listinfo/python-list > > From zondo42 at googlemail.com Fri Jul 11 17:20:41 2008 From: zondo42 at googlemail.com (Glenn Hutchings) Date: Fri, 11 Jul 2008 22:20:41 +0100 Subject: Graphics References: Message-ID: vanam writes: > hi all > i am new to python programming a beginner. I Came to know from the > groups that "How to think like a computer scientist" is preferable for > begineers. i just looking through that i came to one section where a > sample program for generation of graphics is present.i tried to copy > the same script to the interpreter and it is showing an error i want > to know whether is there anything that has to be installed in addition > to python 2.5 > below is the program > from gasp import * > begin_graphics() > Circle((200, 200), 60) > Line((100, 400), (580, 200)) > Box((400, 350), 120, 100) > end_graphics() You're probably getting an ImportError from the 'from gasp...' line. You need to grab and install the GASP package from https://launchpad.net/gasp. Glenn From durand1 at gmail.com Thu Jul 10 16:31:43 2008 From: durand1 at gmail.com (Durand) Date: Thu, 10 Jul 2008 21:31:43 +0100 Subject: PIL: Transparent PNGs and im.paste: ValueError: bad transparency mask Message-ID: Hi! I'm trying to paste a png with a transparent layer into an image using "image.paste(tesla,(20,10), tesla)" but I'm getting this error: ValueError: bad transparency mask I have used im.paste(image,box,image) sucessfully before to paste an image with transparency, however, it doesn't seem to work for this particular image. How would I change the image so that it doesn't give me this error? The image is http://img293.imageshack.us/img293/1434/teslahv5.png Thanks in advance! From Russ.Paielli at gmail.com Mon Jul 28 00:42:37 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 21:42:37 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> Message-ID: <7360bd9a-4ff6-4e75-821c-eabc88ee6258@u6g2000prc.googlegroups.com> On Jul 27, 8:58 pm, castironpi wrote: > On Jul 27, 2:39 pm, Bruno Desthuilliers > > wrote: > > Derek Martin a ?crit : > > > It's bad programming, but the world is full of bad programmers, and we > > > don't always have the choice not to use their code. Isn't one of > > > Python's goals to minimize opportunities for bad programming? > > > Nope. That's Java's goal. Python's goals are to maximize opportunities > > for good programming, which is quite different. Oh, gosh, that is so clever. What a bunch of crap. > +1 QOTW Do you realize what an insult that is to everyone else who has posted here in the past week? From sjmachin at lexicon.net Sat Jul 19 17:07:10 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 19 Jul 2008 14:07:10 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> <945275e9-8923-479c-8eec-258bd68063c0@z6g2000pre.googlegroups.com> <4881FE02.3000203@gmail.com> Message-ID: On Jul 20, 5:00 am, Andrew Freeman wrote: > Andrew Freeman wrote: > > John Machin wrote: > >> A couple of points: > >> (1) Instead of search(r'^blahblah', ...) use match(r'blahblah', ...) > >> (2) You need to choose your end-anchor correctly; your pattern is > >> permitting a newline at the end: > > I forgot to change search to match. This should be better: > > def match(var): > if re.match(r'[LRM]*\Z', var): > return True > else: > return False A bit wordy ... if blahblah: return True else: return False can in total generality be replaced by: return blahblah > > I was also thinking if you had a list of these items needing to be > verified you could use this: You could, but I suggest you don't use it in a job interview :-) > >>> l = ['LLMMRR', '00thLL', 'L', '\n'] (1) Don't use 'L'.lower() as a name; it slows down reading as people need to fire up their mental parser to distinguish it from the result of 3 - 2 > >>> out = [] > >>> map(lambda i: match(i)==False or out.append(i), l) (2) Read PEP 8 (3) blahblah == False ==> not blahblah (4) You didn't show the output from map() i.e. something like [None, True, None, True] (5) or out.append(...) is a baroque use of a side-effect, and is quite unnecessary. If you feel inexorably drawn to following the map way, read up on the filter and reduce functions. Otherwise learn about list comprehensions and generators. > >>> print out > ['LLMMRR', 'L'] > Consider this: >>> import re >>> alist = ['LLMMRR', '00thLL', 'L', '\n'] >>> zeroplusLRM = re.compile(r'[LRM]*\Z').match >>> filter(zeroplusLRM, alist) ['LLMMRR', 'L'] >>> [x for x in alist if zeroplusLRM(x)] ['LLMMRR', 'L'] >>> Cheers, John From anjalinapriya at gmail.com Wed Jul 30 04:13:51 2008 From: anjalinapriya at gmail.com (sexy) Date: Wed, 30 Jul 2008 01:13:51 -0700 (PDT) Subject: play boy sex videos Message-ID: <7eaac699-2a1d-4c41-a86f-4cb1ae5b4c0f@q5g2000prf.googlegroups.com> play boy sex videos ** SEXY GIRLS HOT SEXY PICTURES AND NUDE VIDEO'S ** ^ Sexy boobs ^^ New Fresh Girls ^^ Nude Sexy Stores ^ **sex galexcy and more ****************************************************** http://www.funnywworld.com http://www.funnywworld.com http://www.funnywworld.com http://www.funnywworld.com ******************************************************* From kay.schluehr at gmx.net Fri Jul 11 17:14:47 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 11 Jul 2008 14:14:47 -0700 (PDT) Subject: ANN: P4D 1.1 References: Message-ID: <13bc226c-e096-4739-a7c5-8f8e1db0c4f5@a70g2000hsh.googlegroups.com> On 11 Jul., 15:25, Fuzzyman wrote: > On Jul 11, 10:09 am, Kay Schluehr wrote: > > > P4D = E4X style embedded DSL for Python but without E and X. > > > For more information see: > > >http://pypi.python.org/pypi/P4D/1.1-py2.5 > > That looks a lot like YAML. Any reason to use it over YAML? > > Michael Foordhttp://www.ironpythoninaction.com/ I considered an embedded YAML DSL for Python a long time ago but YAML and Python are not orthogonal. For instance YAML specifies syntax for lists and dictionaries and also data sections which can be expressed easily as triple quoted strings in Python. Embedding YAML is a bit excessive. Syntactically P4D is inspired by SLiP http://slip.sourceforge.net/ and I'd say it is mostly Python extened by SLiP + extra syntax for element filters and attribute access which was kept from E4X. Why an embedded DSL and not an external one? I don't want to argue about this but just say that you need to feel the difference. Check out the package and start editing P4D elements on the console prompt. It's just like a Python feature... Notice that there was a showstopper in the initial release I announced. It has been corrected here: http://pypi.python.org/pypi/P4D/1.1.1-py2.5 From grante at visi.com Tue Jul 15 15:49:19 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 15 Jul 2008 14:49:19 -0500 Subject: Testing for connection to a website References: Message-ID: On 2008-07-15, Alexnb wrote: > Okay, I already made this post, but it kinda got lost. No, it didn't get lost. Your question was answered and you didn't like the answer. > So anyway I need to figure out how to test if the user is able > to connect to a specific website. Last time I got pointed to > the urllib2 page, but if I do urlopen() and and am not > connected, the program stops. How long did you wait? Depending on what/how/where the network is broken, it make take a minute or two for the connection attempt to fail. You may not like it, but that's how TCP works. You're concerned with TCP connections, so you're going to have to live with it. > So I don't know if that was what you guys wanted me to do, Yes it was what we advised you to do. > but I don't think so, you guys are smarter than that. So, how > can I test for connection to a website. Like we told you: 1) Open a connection using urllib or urllib2. 2) The attempt will either fail or succeed. 3) Proceed accordingly. -- Grant Edwards grante Yow! HUGH BEAUMONT died at in 1982!! visi.com From deets at nospam.web.de Tue Jul 22 09:29:40 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 15:29:40 +0200 Subject: DB Pool References: <40f3a61b-8c37-4e26-90f6-02de760ce00e@c58g2000hsc.googlegroups.com> Message-ID: <6em5o2F7r22oU1@mid.uni-berlin.de> bcurtu wrote: > Hi, > > I use MySQLdb lib to access my DB, because I want to opttimize my sql > queries. The application I'm working on has quite a few traffic load, > so I want to minimize the time of creating/destroying cursors: > > My typical code is sth like: > > cursor=con.cursor() > cursor.execute(sql) > all= cursor.fetchall() > cursor.close() > > So, the question is... how can I minimize this cost? I was thinking on > Connection Pools, but I didn't find any good documentation or sample. > Any idea? What has the above (getting *cursors* from a given connection) to do with connection-pooling? I'm not sure what the actual costs of creating a cursor are (might well be that these are neglibel) but why don't you stop closing the cursor and just re-use it? Connection pooling is of course useful - frameworks such as SQLAlchemy and SQLObject do that for you, if used proper. Diez From mensanator at aol.com Tue Jul 15 13:42:03 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 15 Jul 2008 10:42:03 -0700 (PDT) Subject: isPrime works but UnBoundLocalError when mapping on list References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> <487CD564.5020008@hughes.net> Message-ID: <2d8e4a25-f29e-46b5-a580-ff5663ff29d6@34g2000hsf.googlegroups.com> On Jul 15, 12:28?pm, "Andreas Tawn" wrote: > >defn noob wrote: > >> isPrime works when just calling a nbr but not when iterating on a > >> list, why? adding x=1 makes it work though but why do I have to add > >> it? > >> Is there a cleaner way to do it? > > >> def isPrime(nbr): > >> ? ? for x in range(2, nbr + 1): > >> ? ? ? ? if nbr % x == 0: > >> ? ? ? ? ? ? break > >> ? ? if x == nbr: > >> ? ? ? ? return True > >> ? ? else: > >> ? ? ? ? return False > > >>>>> [isPrime(y) for y in range(11)] > > >> Traceback (most recent call last): > >> ? File "", line 1, in > >> ? ? [isPrime(y) for y in range(11)] > >> ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > >> ? ? if x == nbr: > >> UnboundLocalError: local variable 'x' referenced before assignment > > >>>>> map(isPrime, range(100)) > > >> Traceback (most recent call last): > >> ? File "", line 1, in > >> ? ? map(isPrime, range(100)) > >> ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > >> ? ? if x == nbr: > >> UnboundLocalError: local variable 'x' referenced before assignment > >>>>> isPrime(10) > >> False > >>>>> isPrime(11) > >> True > > >> adding x=1 makes it work though: > > >> def isPrime(nbr): > >> ? ? x=1 > >> ? ? for x in range(2, nbr + 1): > >> ? ? ? ? if nbr % x == 0: > >> ? ? ? ? ? ? break > >> ? ? if x == nbr: > >> ? ? ? ? return True > >> ? ? else: > >> ? ? ? ? return False > > >>>>> [isPrime(y) for y in range(11)] > >> [False, True, True, True, False, True, False, True, False, False, > >> False] > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > >======================================== > >Yep - "local variable 'x' referenced before assignment" is correct. > >You state: for x in range... but x doesn't exist until initialized. > > ? To save a loop, initialize x=2 (the minimum value) and loop executes > > ? on pass one. > >In a straight 'C' program > > ? ( ?for (x=1, x=(nbr+1), x++) ?etc... ?) > > ? the x is initialized and forceably incremented. > > ? seems Python does not auto initialize but does auto increment. > > I think a better explanation is that in your original function, x only > existed while the for loop was running. The for loop never ran. > As soon as execution hit the break statement, It never hit the break statement, the first call from [isPrime(y) for y in range(11)] attempted to do for x in range(2,1). > x ceased to exist. Something has to exist before it can cease to exist. > When you attempted to reference it > in the next line, Python has no variable called x so it complains that x > hasn't been initialised. Right conlusion but false premise. > > A more idiomatic way to write it... > > def isPrime(nbr): > ? ? if nbr <= 1: > ? ? ? ? return False > ? ? for x in xrange(2, nbr+1): > ? ? ? ? if not nbr % x: > ? ? ? ? ? ? return x == nbr > > Cheers, > > Drea From python7946 at gmail.com Wed Jul 2 08:05:39 2008 From: python7946 at gmail.com (Jim Brown) Date: Wed, 2 Jul 2008 20:05:39 +0800 Subject: How to modify the data in a binary file? Message-ID: <21563db10807020505p11561ce2k31d36f2731342c78@mail.gmail.com> Hi all, I'm a Python newbie, so please pardon me if my question may look a little silly. :) I want to modify a binary file p.data (which has some C-style "short" integers -- 16-bit integers) in such a way: The bit m and bit n of every "short int" si in the file are set to 1, and the left bits in si are not affected. I.e, for the first short int in the file, I think the code would be: import os f = os.open("/root/p.data", os.O_RDWR) str = os.read(f, 2) #assume the short int in str is 0x0102, and I want to change it to 0x8182 (changing bit7 and bit15 to 1). #how to change the str into a short int variable si?? ??? si = (si & ~0x8080) | 0x8080 # how to change the si to a two-byte str? ??? os.lseek(f, 0, 0); os.write(f, si) os.close(f) Thanks a lot! -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick at craig-wood.com Mon Jul 28 10:35:28 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 28 Jul 2008 09:35:28 -0500 Subject: ActiveState Code (the new Python Cookbook) has been launched References: Message-ID: Trent Mick wrote: > I happy to announce that ActiveState Code has been taken out of beta. > This is the new site replacing the ASPN Cookbooks -- in particular the > Python Cookbook. > > http://code.activestate.com/ Looks great and much faster than the old site! Mind telling us how it is implemented? I'm guessing python/django by the url and the fact that you have python stuff on your home pages but I could be wrong! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From tcfg at sina.com Wed Jul 16 21:50:37 2008 From: tcfg at sina.com (tcfg at sina.com) Date: Wed, 16 Jul 2008 18:50:37 -0700 (PDT) Subject: how to debug python's extend module written in c/c++ on windows Message-ID: <64d771b2-fbc8-4b6a-9725-3dc5063c5328@p25g2000hsf.googlegroups.com> dear all: I have searched the debug informations of many python's IDE, but I cannot find the method about debuging the extend module written in Visual studio 2008 on windows. The wingIDE tell me that we can debug the extend module on linux, but cannot on windows. and using wingdbstub.py we can embed python into other's source code but not extending. Who can tell me the skills, I appreciate! best regards fang 2008.07.17 From Graham.Dumpleton at gmail.com Mon Jul 21 20:11:15 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Mon, 21 Jul 2008 17:11:15 -0700 (PDT) Subject: Error importing modules with mod_python References: Message-ID: On Jul 22, 3:30?am, Aaron Scott wrote: > I've installedmod_python, and everything seems to be working, but it > fails when I try to import another file into the file that's actually > producing the output. I have these lines at the top of index.py: > > frommod_pythonimport apache > from storylab import * > > ... and in the directory where index.py resides (/htdocs/python/), I > have a directory called "storylab". Inside that directory is > __init__.py. When I try to execute /htdocs/python/index.py, I get the > following error: > > --- > > MOD_PYTHONERROR > ProcessId: ? ? ?828 > Interpreter: ? ?'localhost' > ServerName: ? ? 'localhost' > DocumentRoot: ? 'C:/htdocs' > URI: ? ? ? ? ? ?'/python/index.py' > Location: ? ? ? None > Directory: ? ? ?'C:/htdocs/python/' > Filename: ? ? ? 'C:/htdocs/python/index.py' > PathInfo: ? ? ? '' > Phase: ? ? ? ? ?'PythonHandler' > Handler: ? ? ? ?'index' > > Traceback (most recent call last): > > ? File "C:\Python25\lib\site-packages\mod_python\importer.py", line > 1537, in HandlerDispatch > ? ? default=default_handler, arg=req, silent=hlist.silent) > > ? File "C:\Python25\lib\site-packages\mod_python\importer.py", line > 1202, in _process_target > ? ? module = import_module(module_name, path=path) > > ? File "C:\Python25\lib\site-packages\mod_python\importer.py", line > 296, in import_module > ? ? log, import_path) > > ? File "C:\Python25\lib\site-packages\mod_python\importer.py", line > 680, in import_module > ? ? execfile(file, module.__dict__) > > ? File "C:\htdocs\python\index.py", line 2, in > ? ? from storylab import * > > ImportError: No module named storylab > > --- > > What am I doing wrong? Any insight would be greatly appreciated. You can't put Python packages in same directory as handler scripts managed by mod_python. See documentation for import_module() in: http://www.modpython.org/live/current/doc-html/pyapi-apmeth.html Graham From mail at timgolden.me.uk Fri Jul 11 05:09:50 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 11 Jul 2008 10:09:50 +0100 Subject: importing .dll in a python file In-Reply-To: <4dfaeb7b-8e7e-4f0b-80a8-ed24ed1c46d3@x35g2000hsb.googlegroups.com> References: <4dfaeb7b-8e7e-4f0b-80a8-ed24ed1c46d3@x35g2000hsb.googlegroups.com> Message-ID: <4877235E.80708@timgolden.me.uk> moijes12 wrote: > I need to use a .dll from a python script.I have installed pywin.But > in the program ,which is like: > > import dllName > > I get : > > Import Error : DLL not found > > Please suggest a solution! Well, the short answer is: use the ctypes module. The longer answer is: read around the subject a bit before you expect Python to import an arbitrary DLL and then give up when it doesn't :) TJG From sjmachin at lexicon.net Wed Jul 16 18:33:55 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 16 Jul 2008 15:33:55 -0700 (PDT) Subject: python's YENC.DECODE -> weird output References: <0807160233556.16Jul08$rookswood@suburbian.com> Message-ID: On Jul 16, 11:33 pm, John Savage wrote: > I save posts from a midi music newsgroup, some are encoded with > yenc encoding. This gave me an opportunity to try out the decoders > in Python. The UU decoder works okay, but my YENC effort gives > results unexpected: > > import yenc, sys > > fd1=open(sys.argv[1],'r') > #yenc.encode(sys.argv[1],"outfile.yenc",bytes=0) > yenc.decode(sys.argv[1],"outfile.mid",bytes=0,crc_in='') > > I confirmed that yenc.decode exactly reverses yenc.encode, BUT the > encoding itself seems to differ from the USENET standard. That is, > when I decode USENET files the result isn't a valid music file. > (I did try both with and w/o the headers.) > > Maybe it uses a different character set? I can't quite put my > finger on what might be happening. What I can say is that the > yenc coding from the newsgroup article, when viewed with Linux > 'more', displays roughly 10% of its characters as a question mark, > whereas when I give Python's yenc.encode a binary music file and > view its output using 'more', it displays about 90% of the output > as a question mark. > > Any ideas? 1. It isn't "Python's yenc". Consider directing your question to whoever (if anyone) is maintaining whichever third-party module you are talking about. 2. Consider using a tool that will display what is going on in characters and hex e.g. http://linux.about.com/library/cmd/blcmdl1_hexdump.htm From Nikolaus at rath.org Thu Jul 31 06:37:13 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Thu, 31 Jul 2008 12:37:13 +0200 Subject: Difference between type and class Message-ID: <87myjy2vc6.fsf@nokile.rath.org> Hello, Can someone explain to me the difference between a type and a class? After reading http://www.cafepy.com/article/python_types_and_objects/ it seems to me that classes and types are actually the same thing: - both are instances of a metaclass, and the same metaclass ('type') can instantiate both classes and types. - both can be instantiated and yield an "ordinary" object - I can even inherit from a type and get a class So why does Python distinguish between e.g. the type 'int' and the class 'myclass'? Why can't I say that 'int' is a class and 'myclass' is a type? I hope I have managed to get across the point of my confusion... Thanks in advance, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From hyh_david at hotmail.com Thu Jul 17 15:19:00 2008 From: hyh_david at hotmail.com (hyh_david at hotmail.com) Date: Thu, 17 Jul 2008 12:19:00 -0700 (PDT) Subject: wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal Message-ID: <66dc049d-d057-48a3-b109-8d18ec7042c0@i36g2000prf.googlegroups.com> paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal ... From rupole at hotmail.com Thu Jul 31 23:22:27 2008 From: rupole at hotmail.com (Roger Upole) Date: Thu, 31 Jul 2008 23:22:27 -0400 Subject: win32com ChartObject pythonwin vs idle References: <670b57b7-d48e-44c0-abd0-b6772d23688d@79g2000hsk.googlegroups.com> Message-ID: "sterling" wrote in message news:670b57b7-d48e-44c0-abd0-b6772d23688d at 79g2000hsk.googlegroups.com... > I'm curious as to why the difference between IDLE and pythonWin when > using win32com. > opening an excel file, i've attempted to grab the chart information > out of the file. > > commands like co = ChartObjects(1) works in pythonWin but doesn't > work in IDLE. > > however, on both co = chartobjects(1) works just fine. > > The same goes other things like SeriesCollection()/ > seriescollection(1),seriescollection(2)..., Close()/close > > Is there any way to fix it such that IDLE works with ChartObject() > too? I'd really like to be able to use ChartObject().Count() (there > doesn't seem to be an equivalent chartobject.count) > > Thanks. This was probably due to a conflict with the way IDLE sets the locale. Bug report here: http://sourceforge.net/tracker/index.php?func=detail&aid=2006053&group_id=78018&atid=551954 This is fixed in build 212, just released today. Roger From perl_wizard at manx.net Sat Jul 19 05:27:28 2008 From: perl_wizard at manx.net (perl_wizard at manx.net) Date: 19 Jul 2008 10:27:28 +0100 Subject: Question Message-ID: <200807190927.CQP26713@manxnetsf02.manx.net> Why is Perl so much better than python? From M.Busetto at isac.cnr.it Wed Jul 23 03:25:39 2008 From: M.Busetto at isac.cnr.it (maurizio) Date: Wed, 23 Jul 2008 09:25:39 +0200 Subject: maximum value in a column of file Message-ID: <4886DCF3.10107@isac.cnr.it> which is the best way for the calculation of the maximum value in a column of a file? From bignose+hates-spam at benfinney.id.au Sat Jul 12 22:32:06 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 13 Jul 2008 12:32:06 +1000 Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> Message-ID: <87skuems49.fsf@benfinney.id.au> ssecorp writes: > Is this correct use of exceptions? to raise an indexerror and add my > own string insetad of just letting it raise a IndexError by itself > and "blaming" it on list.pop? > > class Stack(object): > def __init__(self, *items): > self.stack = list(items) If you are passing a sequence conceptually, then it's more Pythonic to pass it as a sequence explicitly:: def __init__(self, items): """ Call with e.g. Stack(["foo", "bar"]) """ self.stack = list(items) > def pop(self): > try: > return self.stack.pop() > except: > raise IndexError, "pop from empty stack" Don't use this form of 'raise', it's deprecated. Instead, create the exception instance with the arguments:: raise IndexError("pop from empty stack") Don't use a bare 'except'; you will thereby catch *all* exceptions in the 'try' block, masking errors you did not expect to handle, making debugging unnecessarily difficult. Instead, always be explicit about *which* exceptions you're handling here. Don't catch the exception only to raise a new one; the context of the original exception is lost. If all you want to do is have a different message, modify the existing exception instance's args and re-raise it. try: return self.stack.pop() except IndexError, exc: exc.args = ["pop from empty stack"] raise -- \ ?Experience is that marvelous thing that enables you to | `\ recognize a mistake when you make it again.? ?Franklin P. Jones | _o__) | Ben Finney From sjmachin at lexicon.net Fri Jul 18 19:43:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 18 Jul 2008 16:43:35 -0700 (PDT) Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> <3db7c643-56ca-4d6e-99eb-16176e1a2e88@d19g2000prm.googlegroups.com> <7b2d0e3b-0ee4-4f1b-90d5-90eae9f258a0@u6g2000prc.googlegroups.com> Message-ID: <3dd3ce99-e75b-4d5c-84dc-7854abd9d0e1@w8g2000prd.googlegroups.com> On Jul 18, 11:42 pm, ptn wrote: [snip] > Remember C, where i, j, > k are indices, p, q, r are pointers, s, t are strings and x, y, z are > integers. Only by convention (even-K&R-v1 C required explicit declarations almost everywhere), and x etc being used for integers is news to me ... perhaps you were thinking of m and n. The only language I remember that had implicit typing was FORTRAN (GOD is real, but JESUS is an integer). From python at rcn.com Thu Jul 31 03:21:24 2008 From: python at rcn.com (Raymond Hettinger) Date: Thu, 31 Jul 2008 00:21:24 -0700 (PDT) Subject: Optimizing size of very large dictionaries References: <1217464179.31710.1266222419@webmail.messagingengine.com> Message-ID: <45a2a32e-eb88-4eab-a4de-718896c3dbbb@b2g2000prf.googlegroups.com> > > Are there any techniques I can use to strip a dictionary data > > structure down to the smallest memory overhead possible? Sure. You can build your own version of a dict using UserDict.DictMixin. The underlying structure can be as space efficient as you want. FWIW, dictionaries automatically become more space efficient at largers sizes (50,000+ records). The size quadrupling strategy falls back to just doubling whenever a dict gets two thirds full. > > Background: I'm trying to identify duplicate records in very > > large text based transaction logs. I'm detecting duplicate > > records by creating a SHA1 checksum of each record and using this > > checksum as a dictionary key. This works great except for several > > files whose size is such that their associated checksum > > dictionaries are too big for my workstation's 2G of RAM. Tons of memory can be saved by not storing the contents of the record. Just make an initial pass to identify the digest values of possible duplicates. The use a set to identify actual dups but only store the records for those whose digest is a possible duplicate: bag = collections.defaultdict(int) for record in logs: bag[sha1(record).digest()] += 1 possible_dups = set() while bag: hashval, cnt = bag.popitem() if cnt > 1: possible_dups.add(hashvalue) seen = set() for record in logs: if record in seen: print 'Duplicate:', record elif sha1(record).digest() in possible_dups: seen.add(record) Raymond P.S. If the log entries are one liners, maybe it would be better to use the operating system's sort/uniq filters. From patf at well.com Tue Jul 29 00:47:16 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 21:47:16 -0700 (PDT) Subject: Download excel file from web? References: <6f6vhlFa7anrU1@mid.uni-berlin.de> <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> <19fa0bb2-e101-47c9-84d4-1bf05d08ba39@b2g2000prf.googlegroups.com> Message-ID: On Jul 28, 6:05?pm, "Guilherme Polo" wrote: > On Mon, Jul 28, 2008 at 9:39 PM, MRAB wrote: > > On Jul 29, 12:41 am, "p... at well.com" wrote: > >> On Jul 28, 4:20 pm, "Guilherme Polo" wrote: > > >> > On Mon, Jul 28, 2008 at 8:04 PM, p... at well.com wrote: > >> > > On Jul 28, 3:52 pm, "Guilherme Polo" wrote: > >> > >> On Mon, Jul 28, 2008 at 7:43 PM, p... at well.com wrote: > >> > >> > On Jul 28, 3:33 pm, "p... at well.com" wrote: > >> > >> >> On Jul 28, 3:29 pm, "Diez B. Roggisch" wrote: > > >> > >> >> > p... at well.com schrieb: > > >> > >> >> > > On Jul 28, 3:00 pm, "p... at well.com" wrote: > >> > >> >> > >> Hi - experienced programmer but this is my first Python program. > > >> > >> >> > >> This URL will retrieve an excel spreadsheet containing (that day's) > >> > >> >> > >> msci stock index returns. > > >> > >> >> > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > >> > >> >> > >> Want to write python to download and save the file. > > >> > >> >> > >> So far I've arrived at this: > > >> > >> >> > >> [quote] > >> > >> >> > >> # import pdb > >> > >> >> > >> import urllib2 > >> > >> >> > >> from win32com.client import Dispatch > > >> > >> >> > >> xlApp = Dispatch("Excel.Application") > > >> > >> >> > >> # test 1 > >> > >> >> > >> # xlApp.Workbooks.Add() > >> > >> >> > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > >> > >> >> > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > >> > >> >> > >> # xlBook = xlApp.ActiveWorkbook > >> > >> >> > >> # xlBook.SaveAs(Filename='C:\\test.xls') > > >> > >> >> > >> # pdb.set_trace() > >> > >> >> > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > >> >> > >> excel? > >> > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional') > >> > >> >> > >> # test 2 - returns check = False > >> > >> >> > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > >> > >> >> > >> indexperf/excel? > >> > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > >> > >> >> > >> xlApp = response.fp > >> > >> >> > >> print(response.fp.name) > >> > >> >> > >> print(xlApp.name) > >> > >> >> > >> xlApp.write > >> > >> >> > >> xlApp.Close > >> > >> >> > >> [/quote] > > >> > >> >> > > Woops hit Send when I wanted Preview. ?Looks like the html [quote] tag > >> > >> >> > > doesn't work from groups.google.com (nice). > > >> > >> >> > > Anway, in test 1 above, I determined how to instantiate an excel > >> > >> >> > > object; put some stuff in it; then save to disk. > > >> > >> >> > > So, in theory, I'm retrieving my excel spreadsheet with > > >> > >> >> > > response = urllib2.urlopen() > > >> > >> >> > > Except what then do I do with this? > > >> > >> >> > > Well for one read some of the urllib2 documentation and found the > >> > >> >> > > Request class with the method has_data() on it. ?It returns False. > >> > >> >> > > Hmm that's not encouraging. > > >> > >> >> > > I supposed the trick to understand what urllib2.urlopen is returning > >> > >> >> > > to me; rummage around in there; and hopefully find my excel file. > > >> > >> >> > > I use pdb to debug. ?This is interesting: > > >> > >> >> > > (Pdb) dir(response) > >> > >> >> > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > >> > >> >> > > 'code', ' > >> > >> >> > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > >> > >> >> > > 'readline', ' > >> > >> >> > > readlines', 'url'] > >> > >> >> > > (Pdb) > > >> > >> >> > > I suppose the members with __*_ are methods; and the names without the > >> > >> >> > > underbars are attributes (variables) (?). > > >> > >> >> > No, these are the names of all attributes and methods. read is a method, > >> > >> >> > for example. > > >> > >> >> right - I got it backwards. > > >> > >> >> > > Or maybe this isn't at all the right direction to take (maybe there > >> > >> >> > > are much better modules to do this stuff). ?Would be happy to learn if > >> > >> >> > > that's the case (and if that gets the job done for me). > > >> > >> >> > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty > >> > >> >> > clear on this: > > >> > >> >> > """ > >> > >> >> > This function returns a file-like object with two additional methods: > >> > >> >> > """ > > >> > >> >> > And then for file-like objects: > > >> > >> >> >http://docs.python.org/lib/bltin-file-objects.html > > >> > >> >> > """ > >> > >> >> > read( ? [size]) > >> > >> >> > ? ? ?Read at most size bytes from the file (less if the read hits EOF > >> > >> >> > before obtaining size bytes). If the size argument is negative or > >> > >> >> > omitted, read all data until EOF is reached. The bytes are returned as a > >> > >> >> > string object. An empty string is returned when EOF is encountered > >> > >> >> > immediately. (For certain files, like ttys, it makes sense to continue > >> > >> >> > reading after an EOF is hit.) Note that this method may call the > >> > >> >> > underlying C function fread() more than once in an effort to acquire as > >> > >> >> > close to size bytes as possible. Also note that when in non-blocking > >> > >> >> > mode, less data than what was requested may be returned, even if no size > >> > >> >> > parameter was given. > >> > >> >> > """ > > >> > >> >> > Diez > > >> > >> >> Just stumbled upon .read: > > >> > >> >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > >> >> excel? > >> > >> >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> >> +25%2C+2008&export=Excel_IEIPerfRegional').read > > >> > >> >> Now the question is: what to do with this? ?I'll look at the > >> > >> >> documentation that you point to. > > >> > >> >> thanx - pat > > >> > >> > Or rather (next iteration): > > >> > >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > >> > excel? > >> > >> > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > >> > >> > The file is generally something like 26 KB so specifying 1,000,000 > >> > >> > seems like a good idea (first approximation). > > >> > >> > And then when I do: > > >> > >> > print(response) > > >> > >> > I get a whole lot of garbage (and some non-garbage), so I know I'm > >> > >> > onto something. > > >> > >> > When I read the .read documentation further, it says that read() has > >> > >> > returned the data as a string object. ?Now - how do I convince Python > >> > >> > that the string object is in fact an excel file - and save it to disk? > > >> > >> You don't need to convince Python, just write it to a file. > >> > >> More reading for you:http://docs.python.org/tut/node9.html > > >> > >> > pat > >> > >> > -- > >> > >> >http://mail.python.org/mailman/listinfo/python-list > > >> > >> -- > >> > >> -- Guilherme H. Polo Goncalves > > >> > > OK: > > >> > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > > excel? > >> > > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > >> > > # print(response) > >> > > f = open("c:\\msci.xls",'w') > >> > > f.write(response) > > >> > I would initially change that to: > > >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&...) > > >> > f = open("c:\\msci.xls", "wb") > >> > for line in response: > >> > ? ? f.write(line) > >> > f.close() > > >> > and then.. > > >> > > OK this makes the file, and there's a c:\msci.xls in place and it's > >> > > about the right size. But whether I make the second param to open 'w' > >> > > or 'wb', when I try to open msci.xls from the Windows file explorer, > >> > > excel tells me that the file is corrupted. > > >> > try it. > > >> > > pat > >> > > -- > >> > >http://mail.python.org/mailman/listinfo/python-list > > >> > -- > >> > -- Guilherme H. Polo Goncalves > > >> A simple f.write(response) does work (click on a single row in Excel > >> and you get a single row). > > >> But I can see that what you recommend Guilherme is probably safer - > >> thanx. > > >> pat > > > If response contains a string then: > > Did you notice I removed the read(...) part ? > > > for line in response: > > ? ?f.write(line) > > > will actually be writing the string one character at a time! > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves Actually no I didn't Guilherme (although I'll take it out now). Would leaving the in urllib2.urlopen().read() imply, as MRAB would seem to indicate, that the following for loop would act byte-by-byte? And if so, how? Even with the .read() in, it was very fast. But it looks like it won't hurt (and very possibly helps) to take it out. pat From Scott.Daniels at Acm.Org Sat Jul 12 15:20:33 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 12 Jul 2008 12:20:33 -0700 Subject: Why is this blowing the stack, thought it was tail-recursive... In-Reply-To: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> References: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> Message-ID: <_MadnaFbKtwVnOTVnZ2dnUVZ_jydnZ2d@pdx.net> ssecorp wrote: > and can memoization speed up this even more? .... Generators get you to an even clearer Fibonacci expression. def _Fibonacci_gen(): a, b = 1, 0 while True: a += b yield a b += a yield b Here's how to use it to avoid redundant comutation: _next_entry = _Fibonacci_gen().next _sofar = [] def fib(n): while len(_sofar) <= n: _sofar.append(_next_entry()) return _sofar[n] --Scott David Daniels Scott.Daniels at Acm.Org From arsyed at gmail.com Thu Jul 24 05:00:15 2008 From: arsyed at gmail.com (arsyed) Date: Thu, 24 Jul 2008 05:00:15 -0400 Subject: Autocompletion and Interactive Tables in a Python IDE In-Reply-To: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> References: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Message-ID: <9a2cc7a70807240200h455cf49cm99bbd5227f2312fc@mail.gmail.com> On Wed, Jul 23, 2008 at 5:28 PM, Anthony wrote: > Hi, I'm a FoxPro programmer, but I want to learn python before it's > too late. I do a lot of statistical programming, so I import SPSS > into python. In my opinion, the best features of Visual FoxPro 9.0 > were: > a) Intellisense (tells you what classes/methods are available and what > variables go into a function) > b) Code Completion (guesses your code after four letters) > c) Data-Orientation; multiple data sessions can be open, data can be > viewed easily > > Python's IDLE has only half of the first of these features. I did a > lot of searching and found the PyDev extensions for Eclipse's Python > IDE, and found that they've got Intellisense. I'm still missing b and > c, and am getting extremely frustrated programming so slowly.. > > So two questions: > Is there any package, gui, IDE, anything that will do FoxPro-style > code completion? If it works in Eclipse, even better.. > I can't find a good screenshot, but here's a better description: > You type "BROW" and it pops up a window that says "BROWSE" ..at this > point if you hit enter it completes the word.. > > and > > How can I view open SPSS data in one of the Python GUIs? Again, > Eclipse would be the preference. > Here's an example of how I'd like to browse the data: > http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=vfptoolkit_figure02.tif > I don't want to have to switch back and forth between Python and SPSS > while I'm programming; I just want to stay in one of them.. > > What can I do? I feel extremely inefficient when I don't have these > three features.. > I don't know of any python IDE that provides the data orientation feature, but there may be an Eclipse plugin for that sort of thing. Otherwise, if you're on windows, check out PyScripter, which is free: http://mmm-experts.com/Products.aspx?ProductId=4 and WingIDE which is quite nice and cross-platform (not free, though): http://www.wingware.com/ I use Vim, which is worth learning IMHO, but somewhat difficult to get started with especially if you're coming from FoxPro. From circularfunc at yahoo.se Sat Jul 5 05:07:04 2008 From: circularfunc at yahoo.se (defn noob) Date: Sat, 5 Jul 2008 02:07:04 -0700 (PDT) Subject: Not necessarily related to python Web Crawlers References: Message-ID: just crawling is supereasy. its how to index and search that is hard. just start at yahoo.com, scrape out all the links and then for every site visit every link. i wrote a crawler in 15 lines of code. but then it all it did was visit the sites, not indexing them or anything. you could write a faster one in C++ probably but if you are new to it doing it in python will let you experiment and learn faster. some links: http://infolab.stanford.edu/~backrub/google.html http://www-csli.stanford.edu/~hinrich/information-retrieval-book.html http://www.example-code.com/python/pythonspider.asp http://www.example-code.com/python/spider_simpleCrawler.asp From samwyse at gmail.com Tue Jul 8 08:59:02 2008 From: samwyse at gmail.com (samwyse) Date: Tue, 8 Jul 2008 05:59:02 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> On Jul 4, 6:43?am, Henning_Thornblad wrote: > What can be the cause of the large difference between re.search and > grep? > While doing a simple grep: > grep '[^ "=]*/' input ? ? ? ? ? ? ? ? ?(input contains 156.000 a in > one row) > doesn't even take a second. > > Is this a bug in python? You might want to look at Plex. http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/ "Another advantage of Plex is that it compiles all of the regular expressions into a single DFA. Once that's done, the input can be processed in a time proportional to the number of characters to be scanned, and independent of the number or complexity of the regular expressions. Python's existing regular expression matchers do not have this property. " I haven't tested this, but I think it would do what you want: from Plex import * lexicon = Lexicon([ (Rep(AnyBut(' "='))+Str('/'), TEXT), (AnyBut('\n'), IGNORE), ]) filename = "my_file.txt" f = open(filename, "r") scanner = Scanner(lexicon, f, filename) while 1: token = scanner.read() print token if token[0] is None: break From steve at REMOVE-THIS-cybersource.com.au Mon Jul 28 10:07:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Jul 2008 14:07:44 GMT Subject: QOTW [was Re: Attack a sacred Python Cow] References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> <7360bd9a-4ff6-4e75-821c-eabc88ee6258@u6g2000prc.googlegroups.com> Message-ID: <009dce32$0$20313$c3e8da3@news.astraweb.com> On Sun, 27 Jul 2008 21:42:37 -0700, Russ P. wrote: >> +1 QOTW > > Do you realize what an insult that is to everyone else who has posted > here in the past week? Actually I don't. I hadn't realised that when a person believes that somebody has made an especially clever, witty, insightful or fun remark, that's actually a put-down of all the other people whose remarks weren't quite as clever, witty, insightful or fun. But now that I've had this pointed out to me, why, I see insults everywhere! Tonight, my wife said to me that she liked my new shirt, so I replied "What's the matter, you think my trousers are ugly?" -- Steven From bignose+hates-spam at benfinney.id.au Sun Jul 20 06:48:50 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 20 Jul 2008 20:48:50 +1000 Subject: __del__ methods References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> <87hcalxvx0.fsf@benfinney.id.au> Message-ID: <87prp8x23x.fsf@benfinney.id.au> "Robert Rawlins" writes: > This isn?t something I'd seen before (god that makes me feel stupid). No need to feel stupid, unless you've had the opportunity to learn and passed it by. > I've always based my code off the odd example that's dotted around Time to fix that, then, with some documentation , and by working through the Python tutorial . -- \ ?I was married by a judge. I should have asked for a jury.? | `\ ?Groucho Marx | _o__) | Ben Finney From fredrik at pythonware.com Tue Jul 15 14:52:22 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2008 20:52:22 +0200 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: Victor Noagbodji wrote: > what's the difference between these two statement? one checks if the given object is not None, the other checks if it's a true value: http://docs.python.org/ref/Booleans.html#Booleans > And which one should one use? depends on what you want to test for, of course. From kyosohma at gmail.com Mon Jul 14 09:12:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 14 Jul 2008 06:12:25 -0700 (PDT) Subject: a module.pth question References: Message-ID: On Jul 14, 6:26?am, oyster wrote: > My py24 is installed in h:\python24 > I installed pyglet(http://pyglet.org/) in > H:\pure_pylib\Multimedia\pyglet-1.0\, if I do > [code]>>> import sys > >>> sys.path.append(r'H:\pure_pylib\Multimedia\pyglet-1.0') > >>> import pyglet > > [/code] > it is ok. > > but if I created h:\pure_pylib\pyglet.pth file, which containts > [code] > Multimedia\pyglet-1.0 > [/code] > > then > [code]>>> import sys > >>> sys.path.append(r'h:\pure_pylib') > >>> import pyglet > > Traceback (most recent call last): > ? File "", line 1, in ? > ImportError: No module named pyglet > > [/code] > > what is wrong with it? and How to fix it? thanks in advance I looked in my easy_install.pth and it looks like it should be: .\Multimedia\pyglet-1.0 But I don't really see any reason not to do it the way you were earlier with the full path name. Besides, you should be able to install pyglet to your site-packages folder. Or you could use buildout if you're just testing modules and you don't want to screw up your namespace. Mike From gherron at islandtraining.com Thu Jul 31 12:16:16 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 31 Jul 2008 09:16:16 -0700 Subject: How smart is the Python interpreter? In-Reply-To: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> References: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> Message-ID: <4891E550.7010106@islandtraining.com> ssecorp wrote: > def str_sort(string): > s = "" > for a in sorted(string): > s+=a > return s > > > if i instead do: > > def str_sort(string): > s = "" > so = sorted(string) > for a in so: > s+=a > return s > > > will that be faster or the interpreter can figure out that it only has > to do sorted(string) once? or that kind of cleverness is usually > reserved for compilers and not interpreters? > -- > http://mail.python.org/mailman/listinfo/python-list > The 'for' statement is only executed once of course. It's the body of the 'for' which is executed multiple times. So in both pieces of code, the 'sorted' is only executed once, and the returned string is bound to a name in the second but not the first. However, you are worrying about optimizing the wrong things here. The 's+=a' line has terrible (quadratic) performance. Instead use the string method 'join' which has linear performance. def str_sort(string): return "".join(sorted(string)) No for loop, no inefficient accumulation. Gary Herron From nick83ola at gmail.com Tue Jul 1 02:57:39 2008 From: nick83ola at gmail.com (nickooooola) Date: Mon, 30 Jun 2008 23:57:39 -0700 (PDT) Subject: Implementing an 8 bit fixed point register Message-ID: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> Hello to all I'm about to write a simulator for a microcontroller in python (why python? because I love it!!!) but I have a problem. The registry of this processor are all 8 bit long (and 10 bit for some other strange register) and I need to simulate the fixed point behaviour of the register, and to access the single bit. f.x. (this is a pseudo python session, only for understanding) >>> reg1 = fixed_int(8) >>> reg2 = fixed_int(10) >>> reg1[0].set() or >>> reg1[0] = 1 # or True? how to rapresent a binary bit >>> reg1[0] 1 >>> reg1[1] 0 >>> reg1[9] >>> reg2 = 0x7FE # in binary 11111111110 , or 11 bit long >>> reg2 0x7FE #or 1111111110, the memorization truncate the upper bits ( or perhaps generate an exception?) >>> reg2 += 0x02 #the result is 10000000000, again not contained in 10 bit >>> reg2 0x00 # truncated again >>> myprocessor.flags['z'] 1 # or True? Z flag indicated an overflow in arithmetic operations Is possibile to do so in python? thanks From alexnbryan at gmail.com Thu Jul 3 04:51:56 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Thu, 3 Jul 2008 03:51:56 -0500 Subject: Creating an .exe with Tkinter involved Message-ID: <1BB24C28-FCDF-4FC5-84CA-D79EAD477FCA@gmail.com> I know this is possible so someone out there should be able to help me! Okay, I have a program that uses Tkinter, and BeautifulSoup. I don't think it should be a problem. I want to create an exe of it. I have py2exe but I don't really know how to work it. I read their tutorial thing and did a setup that looked something like this: from distutils.core import setup import py2exe setup(console['myFunProgram.py']) (isn't really called myFunProgram) This seems terribly wrong however because... it isn't a console app. So I am wondering if anyone can show me how or point me in the right direction to a place where I can learn how to do this. I would appreciate it! From jordanrastrick at gmail.com Fri Jul 25 22:49:57 2008 From: jordanrastrick at gmail.com (Jordan) Date: Fri, 25 Jul 2008 19:49:57 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> Message-ID: <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> Well this discussion is chugging along merrily now under its own steam, but as the OP I should probably clarify a few things about my own views since people continue to respond to them (and are in some cases misunderstanding me.) I *like* explicit self for instance variable access. There are arguments for and against, and my personal opinion is that the arguments for are stronger. Local variables and instance variables should be explicitly differentiated somehow, for the sake of readability. Python's approach works. I slightly prefer Ruby's @, because I think the brevity is a net win for something so commonplace (is it less readable? Maybe. is "def" less readable than "define"? I don't know - I think about 10 seconds of coding in Python or Ruby is enough for you to be able to instantly grok def. Likewise, @. The argument is more aesthetic IMO - how many perl-style/1337speak pu|\| (tu at t10n m at r|<$ can you stand?) I have come to dislike explicit self in method argument lists. Sure, there are reasons. I don't think they're at all strong enough. I'm definitely against the != behaviour, and maybe will get around to actually PEPing it. The point I was trying to make originally was that applying any mantra dogmatically, including Explicit is better than implicit, can lead to bad results. Perhaps having Practicality beats purity is enough of a reminder of that fact for the Python community :-) From pavlovevidence at gmail.com Thu Jul 31 23:56:33 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 31 Jul 2008 20:56:33 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> Message-ID: <6813ac09-18f9-4950-bef6-91d4dfcdb577@k13g2000hse.googlegroups.com> On Jul 30, 10:05 pm, Erik Max Francis wrote: > Russ P. wrote: > > On Jul 30, 1:07 am, Erik Max Francis wrote: > >> Russ P. wrote: > >>> Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > >>> __nonzero__ work in Python. It's very basic stuff. You can quit > >>> patronizing me (and Carl too, I'm sure). > >> You suggested a syntax for testing non-emptiness (`x is not empty`) > >> which indicated a profound misunderstanding of what the `is` operator does. > > >> You then acknowledged that there might be a problem because of the > >> implication if the `is` operator and weren't sure whether it would work > >> or not: > > > Oh, my. I wrote something like, "It would sure be nice to be able to > > write > > > if x is not empty: > > > because it reads like natural language. Immediately after I posted it, > > I thought, "oh, I'll bet some idiot takes that as a serious proposal." > > Sure enough, some idiot did just that almost immediately. > > Yes, all people are idiots for reading what you wrote, reading your > later realization that it was wrong, and taking both at face value. > I'll be sure never to make that mistake again! I thought it was obvious that he was paraphrasing. I also think that, among the people who took it literally, those who are not an ass would have accepted his explanation that he was paraphrasing it and moved on, rather than rubbing it in. If you recall, I agreed with his statement. Would you like to claim that I don't understand the fundamentals of Python? Carl Banks From tjreedy at udel.edu Mon Jul 7 01:53:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 07 Jul 2008 01:53:02 -0400 Subject: Very weird bug! In-Reply-To: <1c1c343a-dd63-454a-8e29-a5c70281ad90@c58g2000hsc.googlegroups.com> References: <1c1c343a-dd63-454a-8e29-a5c70281ad90@c58g2000hsc.googlegroups.com> Message-ID: ssecorp wrote: > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > wtf was this in the middle!? > >>>> def build(a,b): > return a+b > >>>> build(5,4) > (5, 4) I have exactly the same build on Windows and get the expected 9. Try it again. From jorjun at gmail.com Thu Jul 10 08:13:16 2008 From: jorjun at gmail.com (jorjun) Date: Thu, 10 Jul 2008 05:13:16 -0700 (PDT) Subject: Automatic keyword argument source change? Message-ID: <8caa4111-52af-4df8-9bbf-7261835ef53a@34g2000hsf.googlegroups.com> Anyone know of a Python source code utility PSU, to automatically add keyword arguments to method calls that don't have them? : BEFORE def get_total(books, binders, hinges): return (binders.total + hinges.total - books.cost) def print_total(): print get_total(novels, covers, brackets) AFTER .... def print_total(): -- print get_total(novels, covers, brackets) ++ print get_total(books=novels, binders=covers, hinges=brackets) From grflanagan at gmail.com Thu Jul 3 03:29:12 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Thu, 03 Jul 2008 09:29:12 +0200 Subject: ANN: XML builder for Python In-Reply-To: <10df03a30807021716v33518930g951e903c2529ef82@mail.gmail.com> References: <10df03a30807021716v33518930g951e903c2529ef82@mail.gmail.com> Message-ID: Jonas Galvez wrote: > Not sure if it's been done before, but still... > > from __future__ import with_statement > from xmlbuilder import builder, element > > xml = builder(version="1.0", encoding="utf-8") > with xml.feed(xmlns='http://www.w3.org/2005/Atom'): > xml.title('Example Feed') > xml.link(None, href='http://example.org/') > xml.updated('2003-12-13T18:30:02Z') > with xml.author: > xml.name('John Doe') > xml.id('urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6') > with xml.entry: > xml.title('Atom-Powered Robots Run Amok') > xml.link(None, href='http://example.org/2003/12/13/atom03') > xml.id('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a') > xml.updated('2003-12-13T18:30:02Z') > xml.summary('Some text.') > print xml > > Will produce: > > > > Example Feed > > 2003-12-13T18:30:02Z > > John Doe > > urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6 > > Atom-Powered Robots Run Amok > > urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a > 2003-12-13T18:30:02Z > Some text. > > > > http://github.com/galvez/gae-rest/tree/258066f5e1a32c999e04a9313943fdfa8e64edd9/xmlbuilder.py > > --Jonas Galvez > -- > http://mail.python.org/mailman/listinfo/python-list > Nice! Here's a version that uses elementtree: 8<---------------------------------------------------- from __future__ import with_statement from xml.etree import ElementTree as ET class element(object): def __init__(self, name, parent): self.parent = parent self.element = ET.SubElement(parent, name) def __str__(self): return ET.tostring(self.parent) def __getattr__(self, name): return element(name, self.parent) def __getitem__(self, name): return element(name, self.parent) def __enter__(self): self.parent = self.element return self def __exit__(self, type, value, tb): pass def __call__(self, value='', **kargs): self.element.text = value self.element.attrib = kargs return self class builder(element): def __init__(self, version, encoding): self.parent = ET.Element('root') if __name__ == "__main__": xml = builder(version="1.0", encoding="utf-8") with xml.feed(xmlns='http://www.w3.org/2005/Atom') as feed: feed.title('Example Feed') feed.link(href='http://example.org/') feed.updated('2003-12-13T18:30:02Z') with feed.author as author: author.name('John Doe') feed.id('urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6') with feed.entry as entry: entry.title('Atom-Powered Robots Run Amok', class_='l') entry.link(href='http://example.org/2003/12/13/atom03') entry.id('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a') entry.updated('2003-12-13T18:30:02Z') entry.summary('Some text.') with feed.entry as entry: entry.title('2') entry.link(href='2') entry.id('2') entry.updated('2') entry.summary('2') print xml 8<---------------------------------------------------- From tjreedy at udel.edu Sun Jul 27 13:17:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 13:17:30 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <009c29cc$0$20302$c3e8da3@news.astraweb.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c29cc$0$20302$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Sun, 27 Jul 2008 10:23:06 +0800, Marcus.CM wrote: > >> Well after reading some of these posts on "sacred python cow" on the >> "self" , i would generally feel that most programmers who started with >> C++/Java would find it odd. > > You know, there are some programmers who haven't started with C++ or Java. Like my teenager, who is only 1 of many kids learning Python as a first algorithm language. If not now, eventually, I expect a majority of Python programmers to *not* be C++/Java graduates. tjr From smalladi at gmail.com Thu Jul 10 14:35:59 2008 From: smalladi at gmail.com (Sashi) Date: Thu, 10 Jul 2008 11:35:59 -0700 (PDT) Subject: Elisp Lesson on file processing (make downloadable copy of a website) References: Message-ID: <7095dc5e-3008-45b8-8665-e746bff84dd6@m36g2000hse.googlegroups.com> On Jul 6, 4:05 am, "xah... at gmail.com" wrote: > In this week i wrote a emacs program and tutorial that does archiving > a website for offline reading. > (Seehttp://xahlee.org/emacs/make_download_copy.html) Why not use wget or curl? From noreply at yahoo.com Tue Jul 1 05:20:26 2008 From: noreply at yahoo.com (Kirk) Date: 1 Jul 2008 09:20:26 GMT Subject: Freeze problem with Regular Expression References: <6cf614F3f8ocoU1@mid.individual.net> <0e1a9726-cc1d-4bd2-b0ba-b2bcc1c27ee8@f24g2000prh.googlegroups.com> <6cs9rtF3g9fsvU1@mid.individual.net> <08a8164c-fb82-4265-a84e-c0ccd92a01db@a32g2000prf.googlegroups.com> Message-ID: <6cub6qF3g9fsvU2@mid.individual.net> On Mon, 30 Jun 2008 13:43:22 -0700, John Machin wrote: >> I reply here to all of you about such point: that's not important, >> although I appreciate very much your suggestions! My point was >> 'something that works in Perl, has problems in Python'. > > It *is* important; our point was 'you didn't define "works", and it was ok... > near-impossible (without transcribing your regex into verbose mode) to > guess at what you suppose it might do sometimes'. fine: it's supposed to terminate! :-) Do you think that hanging is an *admissible* behavior? Couldn't we learn something from Perl implementation? This is my point. Bye -- Kirk From bdesth.quelquechose at free.quelquepart.fr Sun Jul 27 15:39:26 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Jul 2008 21:39:26 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> Message-ID: <488ceae5$0$11227$426a34cc@news.free.fr> Derek Martin a ?crit : > On Sun, Jul 27, 2008 at 08:19:17AM +0000, Steven D'Aprano wrote: >>> You take the name down to a single letter. As I suggested in an earlier >>> post on this thread, why not take it down to zero letters? >> The question isn't "why not", but "why". The status quo works well as it >> is, even if it isn't perfect. Prove that implicit self is a good idea -- >> or at least prove that it is an idea worth considering. > > Come on, this sounds like a schoolyard argument. This comes down to a > matter of style, and as such, is impossible to prove. It's largely a > question of individual preference. > > That said, the argument in favor is rather simple: > > 1. This is an extremely common idiom in Python > 2. It is completely unnecessary, and the language does not suffer for > making it implicit > 3. Making it implicit reduces typing, reduces opportunities for > mistakes, and arguably increases consistency. "arguably", indeed, cf below. > As for the latter part of #3, self (or some other variable) is > required in the parameter list of object methods, It's actually the parameter list of the *function* that is used as the implementation of a method. Not quite the same thing. And then, consistency mandates that the target object of the method is part of the parameter list of the *function*, since that's how you make objects availables to a function. > however when the > method is *called*, it is omitted. Certainly not. You need to lookup the corresponding attribute *on a given object* to get the method. Whether you write some_object.some_method() or some_function(some_object) you still need to explicitely mention some_object. > It is implied, supplied by Python. Neither. The target object is passed to the function by the method object, which is itself returned by the __get__ method of function objects, which is one possible application of the more general descriptor protocol (the same protocol that is used for computed attributes). IOW, there's nothing specific to 'methods' here, just the use of two general features (functions and the descriptor protocol). FWIW, you can write your own callable, and write it so it behave just like a function here: import types class MyCallable(object): def __call__(self, obj): print "calling %s with %s" % (self, obj) def __get__(self, instance, cls): return types.MethodType(self.__call__, instance, cls) class Foo(object): bar = MyCallable() print Foo.bar f = Foo() f.bar() > Thus when an object method is called, it must be called with one fewer > arguments than those which are defined. This can be confusing, > especially to new programmers. This is confusing as long as you insist on saying that what you "def"ined is a method - which is not the case. > It can also be argued that it makes the code less ugly, though again, > that's a matter of preference. > >> It's not enough to show that a change "isn't bad" -- you have to show >> that it is actively good. > > But he did... he pointed out that *it saves work*, without actually > being bad. Benefit, without drawback. Sounds good to me! > >> "Don't need to look at the method signature" is not an argument in favour >> of implicit self. > > Yes, actually, it is. It isn't, since there's no "method signature" to look at !-) > If there is a well-defined feature of Python > which provides access to the object within itself, The point is that you don't get access to the object "within itself". You get access to an object *within a function*. The fact that a function is defined within a class statement doesn't imply any "magic", it just creates a function object, bind it to a name, and make that object an attribute of the class. You have the very same result by defining the function outside the class statement and binding it within the class statement, by defining the function outside the class and binding it to the class outside the class statement, by binding the name to a lambda within the class statement etc... > then the > opportunities for mistakes when someone decides to use something else > are lessened. > >> You don't need to look at the method signature when you're using an >> explicit self either. > > That isn't necessarily true. If you're using someone else's code, and > they didn't use "self" -- or worse yet, if they chose this variable's > name randomly throughout their classes -- then you may well need to > look back to see what was used. > > It's bad programming, but the world is full of bad programmers, and we > don't always have the choice not to use their code. Isn't one of > Python's goals to minimize opportunities for bad programming? Nope. That's Java's goal. Python's goals are to maximize opportunities for good programming, which is quite different. > Providing a keyword equivalent to self and removing the need to name > it in object methods is one way to do that. It's also a way to make Python more complicated than it needs to be. At least with the current state, you define your functions the same way regardless of how they are defined, and the implementation is (relatively) easy to explain. Special-casing functions definition that happens within a class statement would only introduce a special case. Then you'd have to explain why you need to specify the target object in the function's parameters when the function is defined outside the class but not when it's defined within the class. IOW : there's one arguably good reason to drop the target object from functions used as methods implementation, which is to make Python looks more like Java, and there's at least two good reason to keep it the way it is, which are simplicity (no special case) and consistency (no special case). Anyway, the BDFL has the final word, and it looks like he's not going to change anything here - but anyone is free to propose a PEP, isn't it ? From israelu at elbit.co.il Tue Jul 15 16:12:28 2008 From: israelu at elbit.co.il (iu2) Date: Tue, 15 Jul 2008 13:12:28 -0700 (PDT) Subject: bad recursion, still works References: <7bf2bad5-d6b6-4929-a520-a82b7bb49916@34g2000hsf.googlegroups.com> Message-ID: <5be12739-7896-4112-9307-53897af4f691@f63g2000hsf.googlegroups.com> On Jul 15, 9:30?pm, mdshe... at gmail.com wrote: > On Jul 15, 2:59?pm, iu2 wrote: > > > > > Hi, > > > I wrote this wrong recursive function that flattens a list: > > > def flatten(lst, acc=[]): > > ? ? #print 'acc =', acc, 'lst =', lst > > ? ? if type(lst) != list: > > ? ? ? ? acc.append(lst) > > ? ? else: > > ? ? ? ? for item in lst: > > ? ? ? ? ? ? flatten(item) > > ? ? return acc > > > a = [1, 2, [3, 4, 5], [6, [7, 8, [9, 10], 11], 12], 13, 14] > > b = flatten(a) > > print b > > > I was amazed to realize that it flattens the list alright. Why? 'acc' > > should be an empty list on each invocation of flatten, but is seems to > > accumulate anyway... > > When you say acc=[] in the function declaration, it binds acc to a > particular list object, rather than to a concept of an empty list. > Thus, all operations being performed on acc are being performed on the > same list. If, after the sample code you provided, were to call > > c = flatten([15,16,17,[18,19]]) > print c > > you would get back the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, > 13, 14, 15, 16, 17, 18, 19]. > > Mark Sherry I still don't understand: In each recursive call to flatten, acc should be bound to a new [], shouldn't it? Why does the binding happen only on the first call to flatten? From scottpig1 at comcast.net Sun Jul 27 20:45:48 2008 From: scottpig1 at comcast.net (pigmartian) Date: Sun, 27 Jul 2008 20:45:48 -0400 Subject: Where is the correct round() method? In-Reply-To: References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> Message-ID: it could be that 3.0 is using "banker's rounding" --- rounding to the even digit. the idea behind it behind it being to reduce error accumulation when working with large sets of values. > Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo > CPU". What system are you on? > > > It could be that 2.5 is really 2.49999... which would round down to 2, > but on any modern CPU (using IEEE floating point), 2.5 should be > representable exactly. > > From bj_666 at gmx.net Fri Jul 18 17:15:15 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Jul 2008 21:15:15 GMT Subject: how to avoid line return when using python -c 'print "foo"' References: <63d7l5-72p.ln1@rama.nodalpoint> Message-ID: <6ecff3F67cpfU6@mid.uni-berlin.de> On Fri, 18 Jul 2008 23:04:06 +0200, TP wrote: > All my problem is in the title. > If I try: > > $ python -c 'print "foo",' > > It does not change anything, surely because the line return is added > by "python -c". It is added by the interpreter at exit time. The interpreter tries to be smart here deciding for you that the last printed line before program exit should end in a newline. Use `sys.write()` instead of ``print``. Ciao, Marc 'BlackJack' Rintsch From tonal at promsoft.ru Thu Jul 17 04:45:48 2008 From: tonal at promsoft.ru (Alexandr N Zamaraev) Date: Thu, 17 Jul 2008 15:45:48 +0700 Subject: common elements between list of lists and lists In-Reply-To: <2724c6f8-d75d-4fc2-ac8f-310f4f622aae@p25g2000hsf.googlegroups.com> References: <2724c6f8-d75d-4fc2-ac8f-310f4f622aae@p25g2000hsf.googlegroups.com> Message-ID: <487F06BC.4000202@promsoft.ru> >>> list4 = [['1', 'a'],['4', 'd'],['8', 'g']] >>> list5 = [1, 2, 3] >>> set5 = set(list5) >>> [x for n, x in list4 if int(n) in set5] ['a'] From fredrik at pythonware.com Wed Jul 23 05:44:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 11:44:50 +0200 Subject: maximum value in a column of file In-Reply-To: <4886F4CD.8010704@isac.cnr.it> References: <4886DCF3.10107@isac.cnr.it> <4886F4CD.8010704@isac.cnr.it> Message-ID: maurizio wrote: > i tryed to use the module max of numpy, > the problem is that i don't know how to put the column of the file in an > array. > (i'm new in phyton). > anyway if you think there is a better way..... What kind of file is it? Did you pick numpy because you want to do matrix operations (beyond just finding a maximum value), or was it just the first thing you stumbled upon when researching the problem? A simple pattern for finding the maximum value in a file, using only plain Python code, is: max_value = ... some very small value ... for line in file: value = ... extract value from line ... if value > max_value: max_value = value If it's not obvious what "some very small value" is, given the range of data you're working with, you can do max_value = None for line in file: value = ... extract value from line ... if max_value is None or value > max_value: max_value = value instead (this leaves max_value set to None if the file is empty) A more experienced Python hacker might write def get_all_values(file): for line in file: value = ... extract value from line ... yield value ... max_value = max(get_all_values(file)) instead. But this still leaves us with the problem of extracting the value. The best way to do that depends on the kind of files you're working with; for fixed-format text files, you could use string slicing and int/float for conversion (e.g. "value = float(line[10:20])", see the tutorial for details); for other text formats, you could use split/partition or regular expressions, or maybe an existing module (such as "csv"); for binary formats, there's a large number of existing tools. And if you really want to use numpy for other reasons than just getting a maximum value from a column, there's plenty of stuff in NumPy and SciPy (http://www.scipy.org/) that might be useful. So, in other words, I guess we still need more info. From tjreedy at udel.edu Thu Jul 17 21:47:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jul 2008 21:47:30 -0400 Subject: interpreter vs. compiled In-Reply-To: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> Message-ID: castironpi wrote: > On Jul 17, 5:37 pm, I V wrote: > > > Oh. How is the stack represented? As usual, as successive locations in memory. I have the impression that CPython uses the same stack C does. While conceptually, CPython may put objects on the stack, I am pretty sure it actually stacks references (C pointers) to objects in heap memory. > Does it keep track of which stack > positions (TOS, TOS1, etc.) are in what registers? I am sure they are not in registers, just normal memory. The C code that implements bytecodes to act on stack values will use registers just like any other C code. So using registers for the stack would get in the way. Of course, the C code might load pointers on the stack into address registers when actually needed. But this depends on the address scheme of a particular processor and how the C code is compiled to its object code. > Does stack manipulation consume processor cycles? Of course. For much more, you should peruse the CPython source. From andymac at bullseye.apana.org.au Thu Jul 10 06:15:11 2008 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 10 Jul 2008 21:15:11 +1100 Subject: Retrieving BSTR * from a DLL In-Reply-To: <500e422d-5868-4a2b-a213-7d4d13a51d23@j22g2000hsf.googlegroups.com> References: <500e422d-5868-4a2b-a213-7d4d13a51d23@j22g2000hsf.googlegroups.com> Message-ID: <4875E12F.8090401@bullseye.andymac.org> mzdude wrote: > I need to interface with a windows DLL that has the following > signature > > extern "C" void Foo( BSTR in, BSTR *out ) > > Code so far > >>>> from ctypes import * >>>> import comtypes >>>> LPBSTR = POINTER(comtypes.BSTR) >>>> >>>> hdl = windll.MyDll.Foo >>>> hdl.rettype = None >>>> hdl.argtypes = [comtypes.BSTR, LPBSTR] >>>> >>>> inStr = comtypes.BSTR(u'Some Silly String') >>>> out = comtypes.BSTR out = comtypes.BSTR() >>>> hdl(inStr,byref(out)) > > Traceback (most recent call last): > File "", line 1, in > hdl(inStr,byref(out)) > TypeError: byref() argument must be a ctypes instance, not > '_ctypes.SimpleType' comtypes.BSTR is a type; the type error makes clear you need an instance, as above. > Also tried the following > >>>> out = comtypes.BSTR(u'') >>>> p = pointer(out) >>>> hdl(inStr,p) > > Traceback (most recent call last): > File "", line 1, in > hdl(inStr,p) > ValueError: Procedure probably called with too many arguments (8 bytes > in excess) This likely indicates that the DLL is using the C calling convention and not the stdcall calling convention. Use CDLL rather than WinDLL to load the DLL. You might like to join the ctypes-users mailing list at sourceforge. -- ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From timr at probo.com Fri Jul 18 02:18:07 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 18 Jul 2008 06:18:07 GMT Subject: % sign in python? References: Message-ID: <48d08494p4jnhkrhgidmgppg1aostmurvn@4ax.com> Steven Howe wrote: >Terry Reedy wrote: >> >> korean_dave wrote: >>> What does this operator do? Specifically in this context >>> >>> test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) > >I thought, in this contexted, it was mapping operator. What?? Python does not have a "mapping operator". It has a "map" function, but no equivalent operator. % is either the string formatting operator (when the left-hand operand is a string) or the modulo operator (when the left-hand operand is a number). -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dariusz.malec at gmail.com Thu Jul 24 15:28:24 2008 From: dariusz.malec at gmail.com (Dariusz Malec) Date: Thu, 24 Jul 2008 21:28:24 +0200 Subject: curses problem References: Message-ID: forgot to post the code. Server does not allow to post attachments. The code is here http://www.kos.wsiz.rzeszow.pl/~dmalec/src.zip -- Dariusz Malec http://www.kos.wsiz.rzeszow.pl JID:dmalec at jabber.kos.wsiz.rzeszow.pl From q2w3qw14 at gmail.com Sun Jul 27 22:46:36 2008 From: q2w3qw14 at gmail.com (Sera Jackson) Date: Sun, 27 Jul 2008 19:46:36 -0700 (PDT) Subject: I love "shelf" BUT Message-ID: ok, I know its an over discussed topic. Althought I understand why it is there I cant constantly see it in my argument list in parenthesis. can someone give me an insight of the cons of a syntax like this: class Class: def self.method(arguments): etc, etc In other words def method(self, arg1, arg2 ,argN) becomes-> def self.method(arg1, arg2 ,argN) From richard at pyweek.org Sat Jul 19 00:50:15 2008 From: richard at pyweek.org (richard at pyweek.org) Date: Sat, 19 Jul 2008 14:50:15 +1000 Subject: Python game programming challenge, NUMBER 7, in September! Message-ID: <200807191450.16148.richard@pyweek.org> The date for the SEVENTH bi-annual PyWeek challenge has been set: Sunday 7th September to Sunday 14th September (00:00UTC to 00:00UTC). http://pyweek.org/ The PyWeek challenge invites entrants to write a game in one week from scratch either as an individual or in a team. Entries must be developed in Python, during the challenge, and must incorporate some theme chosen at the start of the challenge. REGISTRATION IS NOT YET OPEN -- In order to reduce the number of unnecessary registrations, we will open the challenge for registration one month before the start date. See the competition timetable and rules: http://www.pyweek.org/ PLANNING FOR THE CHALLENGE -- Make sure you have working versions of the libraries you're going to use. The rules page has a list of libraries and other resources. Make sure you know how to build an MD5 sum for your submission. See the challenge help page for more information. Make sure you can build packages to submit as your final submission (if you're going to use py2exe, make sure you know how to use it and that it works). If you don't have access to Linux, Windows or a Mac to test on, contact friends, family or other competitors to find someone who is able to test for you. -- Visit the PyWeek website: http://www.pyweek.org/ From animator333 at gmail.com Mon Jul 28 05:39:30 2008 From: animator333 at gmail.com (King) Date: Mon, 28 Jul 2008 02:39:30 -0700 (PDT) Subject: Read .txt file like .py file References: <90f13013-bb20-4224-ac58-02947f3f9358@i24g2000prf.googlegroups.com> <488c77ee$0$29452$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <389d95bf-15c7-44bb-a317-16854e1a0631@v13g2000pro.googlegroups.com> Well, I have a look to into compiler module and gave it a try using compiler.parseFile and compiler.walk but I haven't got what I need here. From james at reggieband.com Fri Jul 11 06:00:47 2008 From: james at reggieband.com (James Fassett) Date: Fri, 11 Jul 2008 03:00:47 -0700 (PDT) Subject: Moving to functional programming Message-ID: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> Hi all, Had a simple problem that turned into an interesting solution and I thought I would share it here. I had a list of tuples that I needed to get the first value from and generate a list. tuple_list = ( ('John', 'Doe'), ('Mark', 'Mason'), ('Jeff', 'Stevens'), ('Bat', 'Man') ) # what I'd do in C or other procedural languages result_list = [] for item in tuple_list: result_list.append(item[0]) # the first Pythonic attempt using comprehensions result_list = [x[0] for x in tuple_list] # the final functional way [result_list, _] = zip(*tuple_list) I really like how Python allows me to do what I feel is the most natural solution (for a seasoned procedural programmer) while allowing a satisfying path towards a more functional approach. Cheers, James From steve at REMOVE-THIS-cybersource.com.au Mon Jul 28 10:11:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Jul 2008 14:11:12 GMT Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <488d86e2$1@news2-rz-ap.ethz.ch> <488dc3eb$1@news2-rz-ap.ethz.ch> Message-ID: <009dcf02$0$20313$c3e8da3@news.astraweb.com> On Mon, 28 Jul 2008 15:04:43 +0200, Suresh Pillai wrote: > I could of course use the old trick of using a dictionary with 'None' > values and then using iterkeys(). But I thought sets were supposed to > replace this. So maybe I should be asking a more basic question: is > there any way to iterate over the items in a set other than converting > to a list or using the pop() method. Yes, just do it. >>> for i in set([1,2,3]): ... print i ... 1 2 3 -- Steven From martin at v.loewis.de Sun Jul 27 14:31:07 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 27 Jul 2008 20:31:07 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: References: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> Message-ID: <488cbeeb$0$17104$9b622d9e@news.freenet.de> > - AMD64 (or x86-64 or x64 or EMT64 or Intel64) is a 64-bit instruction > set from AMD which is an extension to the i386 instruction set, and runs > 32-bit (and 16-bit) i386-code natively. But, and this is important, > despite the name the instruction set is also used by Intel (though they > call it EMT64 and made a few minor changes). Indeed, there are (unfortunately) many names for the architecture. Originally, AMD called it x86-64, and later renamed it to AMD64. Intel originally implemented it under the name EM64T (for Extended Memory 64 Technology), and now calls the architecture Intel 64. Microsoft (apparently not wanting to take sides) calls it x64. I personally believe that whoever invents a technology also gets to name it, so I encourage use of the name AMD gives it (which is AMD64). That's why the Python installer has that label in its name. Regards, Martin From Russ.Paielli at gmail.com Sat Jul 26 17:16:42 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 26 Jul 2008 14:16:42 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> Message-ID: <370a7975-cc00-4c15-b095-7c942d8084ed@i24g2000prf.googlegroups.com> > > So why not allow something like this?: > > > class MyClass: > > > def func( , xxx, yyy): > > > .xxx = xxx > > > local = .yyy > > > The "self" argument is replaced with nothing, but a comma is used as a > > placeholder. > > (+1) but why retain the leading comma in > the argument list? As I said, the leading comma is a place holder. Without it, the interpreter would have no way of knowing that the first argument is not just another name for "self." We need to maintain compatibility with existing Python rules. If we were designing a new language, we could omit the "self" argument in the signature, and allow either ".xxx" or "self.xxx," at the programmers discretion (i.e., let "self" be the standard name, like "this" in C++). From list-ener at strank.info Thu Jul 31 05:53:34 2008 From: list-ener at strank.info (Stefan Rank) Date: Thu, 31 Jul 2008 11:53:34 +0200 Subject: working pylint anyone? In-Reply-To: <6fdf17Fb2bboU1@mid.uni-berlin.de> References: <6fdf17Fb2bboU1@mid.uni-berlin.de> Message-ID: <48918B9E.9020403@strank.info> on 31.07.2008 11:29 Diez B. Roggisch said the following: > > The packaged version of pylint (0.13.2) fails with this error (last line): > > > So - anybody out here having an actually working pylint config and can tell > me what versions work together? I've become pretty dependend on it to be > honest... Three installations of pylint 0.14.0 that I have access to from here: pylint.bat 0.14.0, astng 0.17.2, common 0.27.0 Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] pylint 0.14.0, astng 0.17.2, common 0.31.0 Python 2.5.2 (r252:60911, Jul 23 2008, 00:17:15) [GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] pylint 0.14.0, astng 0.17.2, common 0.27.0 Python 2.5.1 (r251:54863, Jul 11 2007, 15:07:18) [GCC 3.3.5 (Debian 1:3.3.5-13)] All of them installed using good old setup.py (times 3). easy_install does not work as you noted. Hope that helps. cheers, stefan From karthikbalaguru79 at gmail.com Thu Jul 24 05:08:31 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Thu, 24 Jul 2008 02:08:31 -0700 (PDT) Subject: Requires a character ... !! Message-ID: Hi, I am new to python . I am face few problems related with python and iam trying to resolve it. The below is the error that i get when i invoke my application by giving the necessary input file. [root at localhost hello]# Analyzer hello_input Loading debug info: hello_input Traceback (most recent call last): File "/usr/local/SDK/host/bin/Analyzer", line 694, in ? app.dbg.readObjectInfo(elf) File "/usr/local/SDK/host/bin/debugprocessor.py", line 427, in readObjectInfo self.privateProcessorDwarfTree.readProcessorDwarfTree(filename) File "/usr/local/SDK/bin/debugprocessor.py", line 314, in readDwarfTree if "DW_OP_reg" in value: TypeError: 'in ' requires character as left operand Is this related with the version conflicts ? Should i need to configure any environment variables or change some source code. Any ideas ? Thx in advans, Karthik Balaguru From fredrik at pythonware.com Mon Jul 21 10:19:23 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 16:19:23 +0200 Subject: imported module no longer available In-Reply-To: <8496caf30807210656y3d8467eer83a953e7c37e556c@mail.gmail.com> References: <8496caf30807210656y3d8467eer83a953e7c37e556c@mail.gmail.com> Message-ID: Jeff Dyke wrote: > I've come across an error that i'm not yet able to create a test case > for but wanted to get see if someone could shed light on this. > > I have imported a module at the top of my file with > import mymodulename > > this module is used many times in the current file successfully, but > then I attempt to use it one more time and get: UnboundLocalError: > local variable 'mymodulename' referenced before assignment Let me guess: you've done def myfunc(): print mymodulename import mymodulename or something similar? Getting an exception in this case is the excepted behaviour; the reason being that a variable in a block only belongs to a single scope. for the entire block. For details, see: http://docs.python.org/ref/naming.html Especially this section: "If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can lead to errors when a name is used within a block before it is bound. This rule is subtle. Python lacks declarations and allows name binding operations to occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations." To fix this, mark the name as global: def myfunc(): global mymodulename # I mean the global name! print mymodulename import mymodulename From code at pizzashack.org Mon Jul 21 16:45:31 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 21 Jul 2008 16:45:31 -0400 Subject: Change PC to Win or Windows In-Reply-To: <82873ccd-9667-4dfa-9ec4-a9ac7c672aa7@w1g2000prk.googlegroups.com> References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> <82873ccd-9667-4dfa-9ec4-a9ac7c672aa7@w1g2000prk.googlegroups.com> Message-ID: <20080721204531.GE8793@dragontoe.org> On Mon, Jul 21, 2008 at 12:32:00PM -0700, Lie wrote: > > The term "PC" is commonly used in English, in the United States > > and other English speaking countries, to mean a computer running > > Microsoft Windows. > > As far as I am aware, they're like that because most people aren't > even aware that there are other OSes than Microsoft Windows. You are missing two points. The first one: It doesn't matter what the reasons are for the terminology to be common. It only matters that it IS common. It is; and it is therefore "correct" in the sense that it conveys a meaning to the overwhelming majority of English speakers, which is the intended one. As for the question of whether or not it is appropriate to refer to Windows installations as "PC", it's as simple as that. It is, by definition (via common usage). That is what this thread is about. > The reason why the world hasn't evolved to the two predictable cases > ("all kinds of microcomputers" or "IBM-PC and clones"), is what I'll > explain below. Your explanation is irrelevant to the argument of whether or not the term PC is an inappropriate term to describe a Windows installation, which is what this thread is about. That is the premise put forth by the OP, and that is the notion to which I am responding. It simply is not wrong or inappropriate in any sense; it is in fact correct, regardless of how the meaning or usage resulted, and regardless of any ADDITIONAL meanings the term may have. For what it's worth, your explanation is also WRONG; the term PC began to be popularly used in the United States to describe Intel-based Microsoft machines when there was a proliferation of other kinds of personal computers available to consumers. When it was first used this way, the IBM PC was *NOT* the most popular personal computer... the Commodore 64 was. It dates from a time when the Commodore VIC-20 and C64, Atari 400 and 800, Timex Sinclair, and other computers were all very popluar home machines. The term probably originated primarily because IBM chose to name their computer the IBM PC, and because of Americans' predeliction to abbreviate everything that's more than 2 syllables. ;-) > > It wasn't something that Apple started; it's been used this way > > in increasingly common usage for at least 20 years, although > > exactly what combination of hardware and software was being > > refered to as a "PC" has evolved over that timeframe. > > Apple popularizes the term by explicit marketing, And here is the last point you are missing: Apple does no such thing. They are only using a term in a way that has previously been popularized by the computer industry as a whole, and its market (i.e. consumers, predominantly American consumers historically) for *DECADES*. If I'm not mistaken, their ad campaign mentioning PCs is less than 10 years old (though I can't quickly find any references as to the date). The popularization of the term PC to refer to Intel-compatible machines running Microsoft OSes PREDATES APPLE'S AD CAMPAIGN BY OVER 10 YEARS. Therefore none of your points are valid or relevant, as to the question of whether the usage of the term "PC" to describe windows builds of Python is appropriate. Can we return to the subject of Python now? -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jkugler at bigfoot.com Thu Jul 10 15:01:51 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Thu, 10 Jul 2008 11:01:51 -0800 Subject: Problems Returning an HTTP 200 Ok Message References: <1cf880cc-2036-42dc-8217-d52a714c1710@a70g2000hsh.googlegroups.com> Message-ID: Guy Davidson wrote: > Hi Folks, > > I'm having some issues with an small socket based server I'm writing, > and I was hoping I could get some help. > > My code (attached below) us supposed to read an HTTP Post message > coming from a power meter, parse it, and return a proper HTTP 200 Ok > message. The problem is that the socket fails to send the entire > message as one message, creating a fragmented message which the power > meter then fails to read and accept. > > Is there any way to force the socket to send the entire message at > once? Am I doing anything wrong? Is there an easier way to implement > this functionality? I don't have a solution to the problem presented, per se, but you might have an easier time implementing this if you use SimpleHTTPServer or CGIHTTPServer modules. This will take care of all the socket listening, and a lot of other low-level details. Hope that helps! j From duncan.booth at invalid.invalid Thu Jul 17 16:58:44 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jul 2008 20:58:44 GMT Subject: decorating a method in multiple child classes References: Message-ID: 1x7y2z9 at gmail.com wrote: > I wish to decorate all of the CX.func() in the same way. One way to > do this is to add a decorator to each of the derived classes. But > this is tedious and involves modifying multiple files. > > Is there a way to modify the parent class and have the same effect? > Or some other way neater than the above? > Use a metaclass. >>> def decorate(f): print "decorating", f return f >>> class meta(type): def __init__(self, name, bases, dictionary): if 'func' in dictionary: dictionary['func'] = decorate(dictionary['func']) type.__init__(self, name, bases, dictionary) >>> class P(object): __metaclass__ = meta >>> class C1(P): def func(self): pass decorating >>> From bj_666 at gmx.net Tue Jul 1 16:50:34 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Jul 2008 20:50:34 GMT Subject: Please check my understanding... References: Message-ID: <6cvjkqF9eaU2@mid.uni-berlin.de> On Tue, 01 Jul 2008 12:35:01 -0700, Tobiah wrote: > list.append([1,2]) will add the two element list as the next > element of the list. > > list.extend([1,2]) is equivalent to list = list + [1, 2] > and the result is that each element of the added list > becomes it's own new element in the original list. It's not 100% equivalent because `list.extend()` mutates the original list while ``+`` creates a new list object: In [8]: a = [1, 2, 3] In [9]: b = a In [10]: b.extend([4, 5]) In [11]: b Out[11]: [1, 2, 3, 4, 5] In [12]: a Out[12]: [1, 2, 3, 4, 5] In [13]: b = b + [6, 7] In [14]: b Out[14]: [1, 2, 3, 4, 5, 6, 7] In [15]: a Out[15]: [1, 2, 3, 4, 5] > Is that the only difference? > > From the manual: > > s.extend(x) | same as s[len(s):len(s)] = x > > But: (python 2.5.2) > >>>> a > [1, 2, 3] >>>> a[len(a):len(a)] = 4 > Traceback (most recent call last): > File "", line 1, in > TypeError: can only assign an iterable >>>> Have you tried `extend()` with the same value? In [15]: a Out[15]: [1, 2, 3, 4, 5] In [16]: a.extend(6) --------------------------------------------------------------------------- Traceback (most recent call last) /home/bj/ in () : 'int' object is not iterable See, both ways need something iterable. Ciao, Marc 'BlackJack' Rintsch From mrkafk at gmail.com Tue Jul 1 12:07:49 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Tue, 01 Jul 2008 18:07:49 +0200 Subject: Embedding Python In-Reply-To: References: Message-ID: Carsten Haese wrote: > python_code is a C string containing the raw bytes from your pyc file. > Casting that to a PyObject pointer will not magically transform it into > a Python code object. well yeah, I kind of didn't think that through.. A pyc file contains the following: > > 1) An 8 byte header containing a magic number. > 2) A "marshal" serialization of the code object. > > So, in order to transform those contents into a code object, you need to > skip the 8 byte header and an unmarshal the rest. Basically, replace the > line above with something like this: > > codeobj = PyMarshal_ReadObjectFromString(python_code+8, size-8); > mainobj = PyImport_ExecCodeModule("multiply", codeobj); > > where codeobj is of type (PyObject *). > > Once that works, add magic number checking and exception handling to taste. Thanks. That's exactly what I was looking for. From zapwireDASHgroups at yahoo.com Tue Jul 15 19:28:54 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Tue, 15 Jul 2008 16:28:54 -0700 Subject: One step up from str.split() References: Message-ID: "Sion Arrowsmith" wrote in message news:Tiv*wYYhs at news.chiark.greenend.org.uk... > What's wrong with sys.argv ? Mainly that it doesn't exist. :-) The example was slightly contrived -- I'm really dealing with commands interactively entered within a program in response to raw_input(), although the format of the commands is meant to be consistent with command-line usage. (A real command, for instance, would be something like this: load "my firmware file.bin" .) I ended up using shlex.strip() -- works great! ---Joel From thomas.troeger.ext at siemens.com Thu Jul 17 06:22:20 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Thu, 17 Jul 2008 12:22:20 +0200 Subject: Python embedding question. References: Message-ID: Jan Claeys wrote: > I'd say that PyGame could be a solution. > > Or otherwise you could do your own audio/graphics programming (you don't > tell us which OS you use, but there exist python modules that allow you > to do barebones graphics & sound programming on linux...). Yes, I'm using a very small Linux system with busybox, running from a compact flash drive. I'll investigate PyGame, it sounds as if it is a good candidate :P Thanks so far, Thomas. From circularfunc at yahoo.se Thu Jul 3 11:02:59 2008 From: circularfunc at yahoo.se (defn noob) Date: Thu, 3 Jul 2008 08:02:59 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: <938b7b06-33db-4f0d-89cc-4ce52c9cf0b3@25g2000hsx.googlegroups.com> Message-ID: <3531f0b9-7c83-4e8b-bd67-adbce5c85518@k37g2000hsf.googlegroups.com> On Jul 3, 5:02?pm, Chris wrote: > On Jul 3, 4:11?pm, defn noob wrote: > > > i unzipped and put the folder in site-packages. when i run setup.py > > install nothing happens. > > > when i do import pp from shell it complains it doesnt exist. > > > isnt placing the folder in site-packages enough? > > > these setup.py-files often dont work but normally it still works. > > "python setup.py install" windows...i run setup.py install From denis.kasak2718281828 at gmail.com Fri Jul 11 18:34:42 2008 From: denis.kasak2718281828 at gmail.com (Denis Kasak) Date: Sat, 12 Jul 2008 00:34:42 +0200 Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: On Sat, Jul 12, 2008 at 12:22 AM, kdt wrote: > Hi all, > > Can someone please explain to me why the following evaluates as false? > >>>>list=['a','n','n','a'] >>>>list==list.reverse() >>>>False > > I'm stumped :s Read the documentation on list.reverse(). Basically, it reverses the list in place, so it modifies the list which called it. It does not return a /new/ list which is a reversed version of the original, as you expected it to. Since it doesn't return anything explicitly, Python makes it return None. Hence, the comparison you are doing is between the original list and a None, which is False, naturally. Try this: spam = ['a', 'n', 'n', 'a'] eggs = spam[:] if spam.reverse() == eggs: print "Palindrome" Also, 'list' is a really bad name for a list, since this is the name of the builtin type object for the list type. -- Denis Kasak From ptmcg at austin.rr.com Thu Jul 31 19:15:13 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 31 Jul 2008 16:15:13 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> <7360bd9a-4ff6-4e75-821c-eabc88ee6258@u6g2000prc.googlegroups.com> Message-ID: On Jul 28, 12:15?pm, Kay Schluehr wrote: > On 28 Jul., 06:42, "Russ P." wrote: > > > > > > > On Jul 27, 8:58 pm, castironpi wrote: > > > > On Jul 27, 2:39 pm, Bruno Desthuilliers > > > > wrote: > > > > Derek Martin a ?crit : > > > > > It's bad programming, but the world is full of bad programmers, and we > > > > > don't always have the choice not to use their code. ?Isn't one of > > > > > Python's goals to minimize opportunities for bad programming? > > > > > Nope. That's Java's goal. Python's goals are to maximize opportunities > > > > for good programming, which is quite different. > > > Oh, gosh, that is so clever. What a bunch of crap. > > > > +1 QOTW > > > Do you realize what an insult that is to everyone else who has posted > > here in the past week? > > Nothing glues a community together so well as a common enemy. Or even > better: two enemies i.e. Perl and Java in Pythons case. On the other > hand, some enemies have to be ignored or declared to be not an enemy > ( Ruby ), although oneself is clearly an enemy for them. The same > antisymmetry holds for Python and Java. Java is an enemy for Python > but Python is not worth for Java to be an enemy as long as it can be > ignored. C++ and Java are enemies for each other. Same holds for Java > and C#.- Hide quoted text - > > - Show quoted text - Help... being... sucked into... black hole... inside a... Klein... bottle... From dbpokorny at gmail.com Tue Jul 1 17:50:40 2008 From: dbpokorny at gmail.com (dbpokorny at gmail.com) Date: Tue, 1 Jul 2008 14:50:40 -0700 (PDT) Subject: How to make a function associated with a class? References: <69e26f9b-2f00-4318-9bc5-6aa94e141bca@59g2000hsb.googlegroups.com> Message-ID: On Jul 1, 1:43 pm, Kurda Yon wrote: > Hi, > > I have a class called "vector". And I would like to define a function > "dot" which would return a dot product of any two "vectors". I want > to call this function as follow: dot(x,y). > > Well, I can define a functions "dot" outside the class and it works > exactly as I want. However, the problem is that this function is not > associated with the class (like methods a method of the class). > > For example, if I call "x.calc()" or "y.calc()", python will execute > different methods if "x" and "y" belongs to different classes. I want > to have the same with my "dot" function. I.e. I want it calculates the > dot product ONLY IF the both arguments of that function belong to the > "vector" class. > > Is it possible? > > Thank you in advance. It sounds like you are talking about data-directed programming (see http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-17.html#%_sec_2.4.3). Basically you have two options: def dot(x,y): if isinstance(x,Vector) and isintance(y,Vector): ... raise TypeError("...") which quickly breaks down in a mess of if-then clauses when you want to expand the dot function to handle other datatypes, or you create a table and populate it with entries like this dispatch_table[('dot','Vector','Vector')] = Vector.dot # this has to be declared @staticmethod in class Vector dispatch_table[('dot','str','str')] = operator.add # borrowed from PHP dispatch_table[('mul',Matrix,Matrix)] = Matrix.mul You now have to write something like this (this isn't even valid Python code, but hopefully you get the idea) def generic_function(name): def exec_generic_function(*args): f = dispatch_table.get((name, *(type(arg).__name__ for arg in args)),None) if f == None: raise TypeError('...') return f(*args) return exec_generic_function dot = generic_function('dot') # NB: (a, *b) means (a,) + b until the generalized *-unpacking syntax is accepted This is essentially a translation into Python of the content of the link. Neither of these options are great (and the latter is marginal at best) if you care about performance (but maybe it will all become C anyway so you don't care). If you want to do it the Python way, use __mul__. Cheers, David From sjmachin at lexicon.net Thu Jul 31 04:43:58 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 31 Jul 2008 01:43:58 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Message-ID: On Jul 31, 12:58?am, william tanksley wrote: > Thank you for the response. Here's some more info, including a little > that you didn't ask me for but which might be useful. > > John Machin wrote: > > william tanksley wrote: > > > To ask another way: how do I convert from a file:// URL to a local > > > path in a standard way, so that filepaths from two different sources > > > will work the same way in a dictionary? > > > The problems occur when the filenames have non-ascii characters in > > > them -- I suspect that the URLs are having some encoding placed on > > > them that Python's decoder doesn't know about. > > # track_id = url2pathname(urlparse(track_id).path) > > print repr(track_id) > > parse_result = urlparse(track_id).path > > print repr(parse_result) > > track_id_replacement = url2pathname(parse_result) > > print repr(track_id_replacement) > > The "important" value here is track_id_replacement; it contains the > data that's throwing me. It appears that some UTF-8 characters are > being read as multiple bytes by ElementTree rather than being decoded > into Unicode. Appearances can be deceptive. You present no evidence. > Could this be a bug in ElementTree's Unicode support? It could, yes, but the probability is extremely low. > If > so, can I work around it? > > Here's one example. The others are similar -- they have the same > things that look like problems to me. > > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" > > Note some problems here: Where? > > 1. This isn't Unicode; it's missing the u"" (I printed using repr). > 2. It's got the UTF-8 bytes there in the middle. > > I tried doing track_id.encode("utf-8"), but it doesn't seem to make > any difference at all. > > Of course, my ultimate goal is to compare the track_id to the track_id > I get from iTunes' COM interface, including hashing to the same value > for dict lookups. > > > and copy/paste the results into your next posting. > > In addition to the above results, *WHAT* results? I don't see any repr() output, just your interpretation of what you think you saw! From max at alcyone.com Wed Jul 30 23:03:03 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Jul 2008 20:03:03 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > The reason I wrote that "it would be nice to be able to write" > > if x is not empty: > > is that it reads naturally. It was not an actual proposal, and the > fact that you took it as such was *your* mistake. ... > Now read carefully: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! Let > me repeat that for you: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! > Did you get that, idiot? So people who can read words but not minds are idiots. Go get 'em, tiger! -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis If you turned right / You turned left / Or if you just walked out ahead -- Anggun From jmcmonagle at velseis.com.au Tue Jul 22 02:05:46 2008 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Tue, 22 Jul 2008 16:05:46 +1000 Subject: string[i:j:k] In-Reply-To: <811e72db-a8bc-475a-b32a-38a9b6922600@k30g2000hse.googlegroups.com> References: <4a9a4cf3-9ef4-4d9e-b714-bbf62b7c1917@v1g2000pra.googlegroups.com> <811e72db-a8bc-475a-b32a-38a9b6922600@k30g2000hse.googlegroups.com> Message-ID: <488578BA.5050703@velseis.com.au> konstantin wrote: > > Thanks! > It seems that negative step leads in reverse direction. > But logic isn't completely clear for me. >>>> s = '123456789' >>>> s[::-2] > '97531' > > but >>>> s[:-1:-2] > '' > though I expected something like '8642' > What did i missed? > > -- You need to *start* at the second from last index: s[-2::-2] Regards, John From cwitts at gmail.com Thu Jul 3 11:02:00 2008 From: cwitts at gmail.com (Chris) Date: Thu, 3 Jul 2008 08:02:00 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: Message-ID: <938b7b06-33db-4f0d-89cc-4ce52c9cf0b3@25g2000hsx.googlegroups.com> On Jul 3, 4:11?pm, defn noob wrote: > i unzipped and put the folder in site-packages. when i run setup.py > install nothing happens. > > when i do import pp from shell it complains it doesnt exist. > > isnt placing the folder in site-packages enough? > > these setup.py-files often dont work but normally it still works. "python setup.py install" From dullrich at sprynet.com Tue Jul 1 13:25:35 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 01 Jul 2008 12:25:35 -0500 Subject: ask for a RE pattern to match TABLE in html References: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> <62f752f3-d840-42de-a414-0d56d15d7c5a@w4g2000prd.googlegroups.com> <87bb8346-6498-4e51-b065-88d915dcff0d@p39g2000prm.googlegroups.com> Message-ID: In article <87bb8346-6498-4e51-b065-88d915dcff0d at p39g2000prm.googlegroups.com>, Jonathan Gardner wrote: > On Jun 27, 10:32?am, "David C. Ullrich" wrote: > > (ii) The regexes in languages like Python and Perl include > > features that are not part of the formal CS notion of > > "regular expression". Do they include something that > > does allow parsing nested delimiters properly? > > > > In perl, there are some pretty wild extensions to the regex syntax, > features that make it much more than a regular expression engine. > > Yes, it is possible to match parentheses and other nested structures > (such as HTML), and the regex to do so isn't incredibly difficult. > Note that Python doesn't support this extension. Huh. My evidently misinformed impression was that the regexes in P and P were essentially equivalent. (I hope nobody takes that as a complaint...) > See http://www.perl.com/pub/a/2003/08/21/perlcookbook.html -- David C. Ullrich From Nikolaus at rath.org Tue Jul 29 13:26:09 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Tue, 29 Jul 2008 19:26:09 +0200 Subject: [unittest] Run setUp only once References: Message-ID: <871w1cr49a.fsf@nokile.rath.org> Jean-Paul Calderone writes: > On Tue, 29 Jul 2008 16:35:55 +0200, Nikolaus Rath wrote: >>Hello, >> >>I have a number of conceptually separate tests that nevertheless need >>a common, complicated and expensive setup. >> >>Unfortunately, unittest runs the setUp method once for each defined >>test, even if they're part of the same class as in >> >>class TwoTests(unittest.TestCase): >> def setUp(self): >> # do something very time consuming >> >> def testOneThing(self): >> >> >> def testADifferentThing(self): >> >> >>which would call setUp twice. >> >> >>Is there any way to avoid this, without packing all the unrelated >>tests into one big function? >> > > class TwoTests(unittest.TestCase): > setUpResult = None > > def setUp(self): > if self.setUpResult is None: > self.setUpResult = computeIt() > > ... > > There are plenty of variations on this pattern. But at least this variation doesn't work, because unittest apparently also creates two separate TwoTests instances for the two tests. Isn't there some way to convince unittest to reuse the same instance instead of trying to solve the problem in the test code itself? Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From iainking at gmail.com Wed Jul 2 10:11:51 2008 From: iainking at gmail.com (Iain King) Date: Wed, 2 Jul 2008 07:11:51 -0700 (PDT) Subject: Win32.client, DAO.DBEngine and exceeding the file sharing count lock Message-ID: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> Hi. I'm using the win32 module to access an Access database, but I'm running into the File Sharing lock count as in http://support.microsoft.com/kb/815281 The solution I'd like to use is the one where you can temporarily override the setting using (if we were in VB): DAO.DBEngine.SetOption dbmaxlocksperfile,15000 Can I do this in win32com? I've been using ADO, not DAO, but I have to confess to not knowing exactly what the difference is. I set up my recordset thusly: rs = win32com.client.Dispatch(r'ADODB.Recordset') can I jigger it to increase it's max locks? Iain From prasanths89 at gmail.com Mon Jul 21 21:50:58 2008 From: prasanths89 at gmail.com (Prasanth) Date: Mon, 21 Jul 2008 18:50:58 -0700 (PDT) Subject: Pinging a machine from python References: <0abad6b7-87bc-42d2-88ee-1f2ed40aa07f@w1g2000prd.googlegroups.com> Message-ID: <85a9e54a-e12a-446c-972f-d4e9c398d5ce@p25g2000pri.googlegroups.com> On May 26, 5:21?am, Zerge wrote: > On May 25, 11:13 am, Prasanth wrote: > > > I tried pinging a machine from python using socket programming but > > could not do it. Is there any module which we can use to ping the > > machine < like net::ping in perl> or can you give me simple program. > > Import OS > ip=192.168.1.1 > pingtext="ping "+ip+" -n 1" > pingresult=os.popen(pingtext).readlines() > > "OS" gives you access to the command line of the operating system. Thanks for the solution guys. But the above program is giving the output as : If we print pingresult it is giving the output as : ['\r\n', 'Pinging 0.168.1.1 with 32 bytes of data:\r\n', '\r\n', 'Request timed out.\r\n', '\r\n', 'Ping statistics for 0.168.1.1:\r \n', ' Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),\r\n'] my requirement is IP address and whether the machine is pinging or not. we should not display the above output. However we can do it by using regular expression or there is any other way. Please suggest. Thanks, Prasanth. From castironpi at gmail.com Sun Jul 27 00:59:08 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 26 Jul 2008 21:59:08 -0700 (PDT) Subject: persistent deque (continued) References: <4c985e86-c0c4-4cb3-b7ce-f8e105b7f85d@y21g2000hsf.googlegroups.com> <4126ceeb-128e-4aa1-af95-31648d42eade@i24g2000prf.googlegroups.com> Message-ID: <90422c5b-0688-408d-a342-411bf5c86a9f@34g2000hsh.googlegroups.com> On Jul 21, 5:20?pm, Raymond Hettinger wrote: > On Jul 21, 12:08?pm, castironpi wrote: > > > Some time ago, I was asking about the feasibility of a persistent > > deque, a double-ended queue. > > > It runs into the typical space allocation problems. ? > > Try starting with a dict-based implementation of a double-ended queue > (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259179) > and then replace the dict with a shelf. ?Presto, you've got a > persistent deque. > > Raymond We have the cookbook recipe Raymond brings up, and an automatic pickler that inhahe brought up in May. I've initiated the approach to the solution I have in mind, but the dilemma comes early and isn't pleasant. I can either (i) recompile the whole interpreter, replacing malloc with a custom function that allocates from disk; or (ii) duplicate every class I want to be persistable, making every change to the allocations by hand. Disk-resident objects can clearly not contain references to any objects not on disk (arguably at finalization-stage only), and references to ones that are need to be wrapped by offset, and 'made live' at initialization-time, so that references to the mapped file resume succeeding after termination and restart--- the mapped memory segment won't be the same from run to run. Further, if I can't hijack the existing arena-pool model native in Python, it would take writing a dedicated memory manager. Assuming the whole memory isn't moved to disk, which is feasible, the usage would look like this, to ensure that 'disk-resident' objects don't refer to 'live' ones. listA= perst( [ perst( 0 ), perst( 1 ), perst( "abc" ) ] ) to create the list [ 0, 1, "abc" ]. Modifications, e.g. append "def", would look like this: listA.append( perst( "def" ) ) and would execute the addition directly to mapped memory. The memory file would then have five objects: 0, 1, "abc", "def", and this list. It is not clear that normal assignments would still work, self.b= c, even for disk-resident c, since on a later run, 'self.b' would refer to a different place in memory. It might take either trapping updates to self.__dict__, or something deeper at the level of the ast and Assm't statements. Or an extra level of indirection in accessing it. >>> self.b The indirection would consist of an offset-finder and a delegation layer. >>> self.b.append( perst( set( ) ) ) It would first have to look-up 'self.b', as opposed to accessing it directly by memory address. What I want from the group is to know if I've assessed the options for a model of persistence accurately. Or if I haven't depicted what I'm going for clearly. It seems enormous and if it is this hard, I doubt I'll produce anything other than a few correct persistent types. From Russ.Paielli at gmail.com Thu Jul 17 01:20:12 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 16 Jul 2008 22:20:12 -0700 (PDT) Subject: Best Python packages? References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> Message-ID: <0e63942e-e84f-45c3-9e78-1c67860d760b@p25g2000hsf.googlegroups.com> On Jul 16, 7:16 am, Ben Sizer wrote: > Although the standard library in Python is great, there are > undoubtedly some great packages available from 3rd parties, and I've > encountered a few almost by accident. However, I don't know how a user > would become aware of many of these.http://pypi.python.org/pypi/ > presumably lists most of the decent ones, but there's a lot there and > little indication as to quality or popularity - great if you know > exactly what you need, but not so great for just browsing. I'd love to > have some way of finding out what hidden gems are out there in the > Python world which could make my development a lot easier. Any > suggestions? > > -- > Ben Sizer One good place to look is The Python Papers, "a free e-journal, including industry and academic articles" at http://pythonpapers.org/ The current issue (vol. 3, issue 1) has an article that I wrote called, "An Efficient Scalar Package in Python." If you do engineering or scientific computing with Python, and you wish to avoid unit errors without slowing down your production runs, then I suggest take a look at this package. You can download it and its user's guide at http://RussP.us/scalar.htm . From karthikbalaguru79 at gmail.com Thu Jul 24 00:58:51 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Wed, 23 Jul 2008 21:58:51 -0700 (PDT) Subject: tkinter for my python program !! References: <6em5snF7r22oU3@mid.uni-berlin.de> <63ff0b6f-8c75-4172-b836-8497870544ca@s50g2000hsb.googlegroups.com> <6em86gF7q9djU1@mid.uni-berlin.de> <81554f58-cc9c-4649-afdd-45656ab0bf64@b2g2000prf.googlegroups.com> Message-ID: On Jul 23, 11:38 pm, David wrote: > > Further, finally when i invoke the python program by > > giving the necessary input file, i get the following > > errors . > > Does it have any relation with the python version installed ? > > yes > > > I am using Redhat 9.0 > > You may want to install a current Linux distro. I got the info from this usenet group. Thx for that info. The problem got resolved after including 'from __future__ import generators' in the beginning of the file. Karthik Balaguru From mail at timgolden.me.uk Wed Jul 2 10:29:28 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 02 Jul 2008 15:29:28 +0100 Subject: Win32.client, DAO.DBEngine and exceeding the file sharing count lock In-Reply-To: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> References: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> Message-ID: <486B90C8.6030801@timgolden.me.uk> Iain King wrote: > Hi. I'm using the win32 module to access an Access database, but I'm > running into the File Sharing lock count as in http://support.microsoft.com/kb/815281 > The solution I'd like to use is the one where you can temporarily > override the setting using (if we were in VB): > > DAO.DBEngine.SetOption dbmaxlocksperfile,15000 Really hurried answer: import win32com.client dao = win32com.client.gencache.EnsureDispatch ("DAO.DBEngine.36") dao.SetOption (Option=win32com.client.constants.dbMaxLocksPerFile, Value=15000) TJG From fredrik at pythonware.com Wed Jul 23 16:04:24 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 22:04:24 +0200 Subject: lxml, comparing nodes In-Reply-To: References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> Message-ID: code_berzerker wrote: >> Your requirements for a single Element are simple enough to write it in three >> to five lines of Python code (depending on your definition of equality). >> Checking this equality recursively is another two to three lines. Not complex >> enough to be considered a wheel in the first place. > > Forgive my ignorance as I am new to both Python and lxml ;) off the top of my head (untested): >>> def equal(a, b): ... if a.tag != b.tag or a.attrib != b.attrib: ... return False ... if a.text != b.text or a.tail != b.tail: ... return False ... if len(a) != len(b): ... return False ... if any(not equal(a, b) for a, b in zip(a, b)): ... return False ... return True this should work for arbitrary ET implementations (lxmk, xml.etree, ET, etc). tweak as necessary. From alexnbryan at gmail.com Thu Jul 3 16:58:26 2008 From: alexnbryan at gmail.com (Alexnb) Date: Thu, 3 Jul 2008 13:58:26 -0700 (PDT) Subject: Testing for an empty list Message-ID: <18268092.post@talk.nabble.com> Okay this is a simple question I just don't know how. If I have a list, say: funList = [] and after a while something possible should have been appended to it, but wasn't. How can I test if that list is empty. -- View this message in context: http://www.nabble.com/Testing-for-an-empty-list-tp18268092p18268092.html Sent from the Python - python-list mailing list archive at Nabble.com. From john.goodleaf at gmail.com Thu Jul 31 19:23:49 2008 From: john.goodleaf at gmail.com (john.goodleaf) Date: Thu, 31 Jul 2008 16:23:49 -0700 (PDT) Subject: Problem with pyodbc, Python? Message-ID: I've just built pyodbc 2.0.58 against freetds and unixodbc. When I attempt to invoke it, either from the test script or from the interpreter, I get: ImportError: build/lib.linux-x86_64-2.5/pyodbc.so: undefined symbol: PyUnicodeUCS2_Resize I'm not quite sure how to go about troubleshooting this. More info: Build is on opensuse 11.0, intel x86_64 from Python 2.5.2. I've also tried a custom built (i.e. not the SuSE package) Python with the same result. Yes, I have the Python-dev package installed. I had this working on this very machine when I was running Mandriva but I recently, overly whimsically, decided to try opensuse. Near as I can figure, something about how Python or supporting libraries are built is different between the two distros but I'm not sure how to go about fixing things. Any thoughts? J From kinokunya at gmail.com Mon Jul 14 02:22:20 2008 From: kinokunya at gmail.com (Kinokunya) Date: Sun, 13 Jul 2008 23:22:20 -0700 (PDT) Subject: Need help in writing up a Python Syntax checker Message-ID: Hi guys, My group and I will be working on our final year project, the scope to do a program/web-based application similar areas of functionalities like the PyLint and PyChecker; a Python syntax checker. We have no Python background, equipped only with some knowledge of Java and Dot net. We did some research on PyLint and found out that there are 2 common modules that PyLint & PyChecker are using, namely logilab-astng and logilab-common. I'm not really sure what these 2 modules are for. Quoted from the offical site, The aim of this module (logilab-astng) is to provide a common base representation of python source code We're not really sure what they meant by common base representation of source codes. Does that mean logilab-astng is somewhat like a repository/library of Python syntax API so that we can easily 'call' these module to aid in syntax checking? My group and I were considering of using Java as a basis for this project, but if these 2 modules were really the repositories for Python syntax codes then we are restricted to using Python to make full use of the above mentioned dependencies. Our current stand was to use Jython as it is able to support Java as well as the .PY files inside logilab-astng and logilab-common, but having no knowledge in Python, we're unable to make out whatever was in the 2 above modules, was was unable to find user support forums/ communities for Logilab related stuff. You insights are greatly appreciated. Windows platform (XP & vista) Python (If need be, we will install the latest official version of it) Jython 2.2.1 (Latest version) Server: Apache Tomcat 2.2 (Should we require one for the project) From iainking at gmail.com Fri Jul 25 10:07:34 2008 From: iainking at gmail.com (Iain King) Date: Fri, 25 Jul 2008 07:07:34 -0700 (PDT) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> Message-ID: <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> On Jul 25, 1:46 pm, Iain King wrote: > On Jul 25, 10:57 am, Suresh Pillai wrote: > > > > > I am performing simulations on networks (graphs). I have a question on > > speed of execution (assuming very ample memory for now). I simplify the > > details of my simulation below, as the question I ask applies more > > generally than my specific case. I would greatly appreciate general > > feedback in terms of computing and of course considerations specific to > > implementation in Python. > > > The nodes in my network may be ON or OFF. The network starts off with > > all nodes in the OFF state. I loop through the nodes. For each node > > that is OFF, I consider some probability of it turning ON based on the > > states of its neighbours. I MUST GO THROUGH ALL NODES BEFORE DECIDING > > WHICH ONES TO TURN ON. > > > So my question is whether it is faster to > > > 1. loop through a list of ALL nodes and check for OFF nodes using ifs > > > or to > > > 2. loop through a container of OFF nodes and remove from this when they > > turn ON > > or 3. build a new list every iteration intead of deleting from the old > one: > > while processing: > new_off_list = [] > for x in off_list: > if goes_on(x): > on_list.append(x) > else: > new_off_list.append(x) > off_list = new_off_list > generation += 1 > > Iain I was curious to what extent the different methods varied in time, so I checked it out. Here there are three procedures: test_every which matches your (1), destructive which matches your (2), and constructive which is (3) as I've outlined above. On varying the size of the dataset I get this (probability a node goes on = 50%): Length of initial list: 100000 Test every: 1.16085492357 Destructive: 2.592310272 Constructive: 0.850312458886 Length of initial list: 200000 Test every: 2.48013843287 Destructive: 9.20894689718 Constructive: 1.73562198439 Length of initial list: 400000 Test every: 5.00652267447 Destructive: 44.9696004134 Constructive: 3.51687329373 Length of initial list: 800000 Test every: 9.67657648655 Destructive: 220.57583941 Constructive: 7.06614485537 and changing the probability that a nodes goes on (dataset size = 200000): Probability goes on: 1/2 Test every: 2.24765364513 Destructive: 9.28801971614 Constructive: 1.62770773816 Probability goes on: 1/4 Test every: 4.77387350904 Destructive: 13.4432467571 Constructive: 3.45467140006 Probability goes on: 1/8 Test every: 11.0514899721 Destructive: 18.4026878278 Constructive: 6.86778036177 Probability goes on: 1/16 Test every: 22.5896021593 Destructive: 25.7784044083 Constructive: 13.8631404605 Probability goes on: 1/32 Test every: 49.7667941179 Destructive: 39.3652502735 Constructive: 27.2527219598 Probability goes on: 1/64 Test every: 91.0523955153 Destructive: 65.7747103963 Constructive: 54.4087322936 Code: import random from timeit import Timer SIZE = 100000 MAX = 2 def goes_on(x): global MAX return random.randint(1,MAX) == 1 def test_every(): global SIZE print "Test every:", nodes = range(SIZE) is_on = [False for x in xrange(SIZE)] count = SIZE while count: for i,x in enumerate(nodes): if not is_on[i] and goes_on(x): is_on[i] = True count -= 1 def destructive(): global SIZE print "Destructive:", off_list = range(SIZE) on_list = [] count = SIZE while count: for i in xrange(len(off_list)-1, -1, -1): x = off_list[i] if goes_on(x): on_list.append(x) del(off_list[i]) count -= 1 def constructive(): global SIZE print "Constructive:", off_list = range(SIZE) on_list = [] count = SIZE while count: new_off_list = [] for x in off_list: if goes_on(x): on_list.append(x) count -= 1 else: new_off_list.append(x) off_list = new_off_list #SIZE = 200000 while True: print "Length of initial list:", SIZE #print "Probability goes on: 1/%d" % MAX print Timer("test_every()", "from __main__ import test_every").timeit(1) print Timer("destructive()", "from __main__ import destructive").timeit(1) print Timer("constructive()", "from __main__ import constructive").timeit(1) print SIZE *= 2 #MAX *= 2 Conclusions: On size, (2) really doesn't like bigger datasets, taking exponentially longer as it increases, while (1) and (3) happily increase linearly. (3) is faster. On probability it's (1) who's the loser, while (2) and (3) are happy. (3) is once again faster. I think (2)'s poor performance is being amplified by how python handles lists and list deletions; the effect may be stymied in other languages, or by using other data constructs in python (like a dictionary or a user made list class). If you were short on memory then (2) would have an advantage, but as it is, (3) is the clear winner. I'm a fan of list comprehensions, and it feels like they could be nice here, but since we are making two lists at once here I don't see how to... anyone see how to use them (or 'map' if you want to be old school)? Iain From tjreedy at udel.edu Tue Jul 22 14:20:20 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2008 14:20:20 -0400 Subject: CPython VM internals - Wiki page Message-ID: Various people have asked on c.l.p about documentation of CPython's virtual machine internals. The usual answers have been to see the dis module doc for bytecodes and 'read the code' for more. Jakob Sievers did so and posted his notes, with additions from Martin v. L?wis, as http://wiki.python.org/moin/CPythonVmInternals From cokofreedom at gmail.com Mon Jul 7 06:00:13 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 7 Jul 2008 03:00:13 -0700 (PDT) Subject: yo... References: Message-ID: <1a767250-c2e6-4a07-8650-84b79bf628af@26g2000hsk.googlegroups.com> On Jul 7, 11:55 am, "A.T.Hofkamp" wrote: > On 2008-07-07, abhishek wrote: > > > hey guys...me nu 2 python yo...help me...by da way...jus joined > > in....thanks > > Ask a specific question and you may get an answer. > > If you want an answer from me, it helps *a lot* if you write full english > sentences (starting with a capital letter and ending with a single '.') rather > than the short-hand you seem to favor. (It costs me a lot of effort to > decipher). > > Sincerely, > Albert Considering I speak English as a first language, it is still rather difficult to understand you. However welcome to Python and this Google Group. If you have questions in the future, feel free to ask them. Though you might want to use less Text-style lingo as many of the users here are not first-language English speakers. From tommy.nordgren at comhem.se Wed Jul 23 09:25:52 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Wed, 23 Jul 2008 15:25:52 +0200 Subject: fromfile error on windows, not mac In-Reply-To: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> Message-ID: <611B728A-16C6-4033-B4E3-1AC4183A28F0@comhem.se> One question : Did you remember to open the file in binary mode? This MUST be done on windows. On 22 jul 2008, at 06.36, jadamwil wrote: > Hello, > I am using the numpy fromfile function to read binary data from a file > on disk. The problem is that the program runs fine on a Mac, but gives > an error or warning on windows when trying to read the data. I use it > like this: > > Signal = zeros((N, 16), dtype=float32) > for sample in range(0, N): > # this function gets the next position in the file to seek to > s = getFilePos(sample) > > # go to the correct location in the file; this IS checked to make > sure it is within the file > mFile.seek(s) > > # read the 16 float32 values from the file > D = fromfile(mFile, dtype=numpy.float32, 16) > > # save D in Signal > Signal[sample, :] = D > > This will fail when sample is ~4. If I change the range to (5,N), > skipping the "bad" file location, it will run fine for a few samples, > and then give another error. The message it gives is: > "16 items requested but only 7 read" > > So D is a 7x1 vector, and the program dies when it tries to assign D > to the slice of Signal ("ValueError: shape mismatch: objects cannot be > broadcast to a single shape"). > > On windows, the Python version is 2.5.2, and the most recent numpy and > scipy are being used as well. I tried using Enthought, but it gave > this error as well, in addition to a c runtime error whenever I > imported scipy (which is another post topic...). > > Any ideas on what might be causing this? Is there a way to debug the > fromfile function? And, remember, this works perfectly on a Mac. Would > compiling everything (python, scipy, numpy) potentially solve this? > > Thanks! > -- > http://mail.python.org/mailman/listinfo/python-list ---------------------------------- Skinheads are so tired of immigration, that they are going to move to a country that don't accept immigrants! Tommy Nordgren tommy.nordgren at comhem.se From gcmartijn at gmail.com Sun Jul 6 06:06:06 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Sun, 6 Jul 2008 03:06:06 -0700 (PDT) Subject: pythoncom InternetExplorer.Application don't work in vista || firefox pythoncom ? References: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> Message-ID: On 5 jul, 15:27, Terry Reedy wrote: > gcmart... at gmail.com wrote: > > H! > > > I using a script that opens a internet page in a small window (what I > > can control) > > In XP everything was working fine, but now I'm using Vista with IE7 > > and this is what happends now: > > > First a small window opens at the postion x0 y0 (like I want) but then > > IE thinks "Hey lets open a other main window too". > > And that window opens the url 'http://www.google.nl' > > Perhaps on XP you changed the IE homepage to about:blank. ?On your Vista > machine, it is set to Google, perhaps by the manufacturer (for a fee). > Try changing it. Nope when its about:blank I get that google page (because I say that in the script) From rridge at csclub.uwaterloo.ca Fri Jul 11 18:23:55 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Fri, 11 Jul 2008 18:23:55 -0400 Subject: Loading just in time References: Message-ID: D'Arcy J.M. Cain wrote: >def calc_tax(*arg, **name): > from calc_tax import calc_tax as _func_ > calc_tax = _func_ > return _func_(*arg, **name) This should do what you want: def calc_tax(*arg, **name): global calc_tax from calc_tax import calc_tax return calc_tax(*arg, **name) I suspect though that the cost of importing a lot of little modules won't be as bad as you might think. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From wuwei23 at gmail.com Mon Jul 28 23:44:04 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 28 Jul 2008 20:44:04 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> Message-ID: <466157f1-adcb-45f6-8c2d-b3c245a6ce8d@p31g2000prf.googlegroups.com> On Jul 29, 4:46?am, "Russ P." wrote: > As I said, I could write a pre-processor myself to > implement it in less than a day. So WHY DON'T YOU WRITE IT ALREADY? If you're meeting so much resistance to your idea, why not scratch your own damn itch and just do it? Or doesn't that afford you as many chances to insult others while feeling smugly superior? From marcus at internetnowasp.net Sat Jul 12 22:11:43 2008 From: marcus at internetnowasp.net (Marcus Low) Date: Sun, 13 Jul 2008 10:11:43 +0800 Subject: Someone enlightened me Message-ID: <4879645F.3070504@internetnowasp.net> Opps here is the mail again, incase my formatting is lost, can someone explain to me why this code behaves differently when "lister" and "self.lister" is swap remarked. class abc : # remark this later and unremark "self.lister" lister = [] def __init__ (self, val): #self.lister = [] self.lister.append(val) globallist = [] def test () : global l for x in range(10) : o = abc(x) globallist.append(o) o = "" for i in globallist : print i.lister test() From ptmcg at austin.rr.com Wed Jul 9 10:37:54 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 9 Jul 2008 07:37:54 -0700 (PDT) Subject: Returning the positions of a list that are non-zero References: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> Message-ID: <3aaf581d-eec7-4b20-a75c-f5ff6829e10a@2g2000hsn.googlegroups.com> On Jul 9, 12:26?am, Benjamin Goudey wrote: > I have a very large list of integers representing data needed for a > histogram that I'm going to plot using pylab. However, most of these > values (85%-95%) are zero and I would like to remove them to reduce > the amount of memory I'm using and save time when it comes to plotting > the data. To do this, I'm trying to find the best way to remove all of > the zero values and produce a list of indices of where the non-zero > values used to be. > > For example, if my original list is [0,0,1,2,1,0,0] I would like to > produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices > of where the non-zero values used to be). Removing non-zero values is > very easy but determining the indicies is where I'm having difficulty. > >>> sparse_data = [0, 0, 1, 2, 1, 0, 0] >>> values,locns = zip(*[ (x,i) for i,x in enumerate(sparse_data) if x ]) >>> print values (1, 2, 1) >>> print locns (2, 3, 4) >>> -- Paul From gherron at islandtraining.com Mon Jul 28 13:46:18 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 28 Jul 2008 10:46:18 -0700 Subject: python lists and newline character In-Reply-To: <053101c8f0d7$ebd7c340$a601a8c0@office.ipglobal.net> References: <053101c8f0d7$ebd7c340$a601a8c0@office.ipglobal.net> Message-ID: <488E05EA.80800@islandtraining.com> Support Desk wrote: > > Hello all, > > I am using os.popen to get a list returned of vpopmail > users, something like this > > > > x = os.popen('/home/vpopmail/bin/vuserinfo -n -D mydomain.com).readlines() > > > > x returns a list, of usernames, and I am trying to append the > usernames with the domain like so > > > > for line in x: > > print line + ?@? + domain > > > > but instead of getting > > > > user at domain.com > > > > im getting a newline character like: > > user > > @domain.com > > User > > @comain.com > > User2 > > @domain.com > > > > > > Is there some way I can get this list without the newline characters > being added. or somehow remove the newline characters. Any help would > be appreciated. > The problem has nothing to do with lists. The readlines() function returns each line *with* its newline. To strip it off, use line.strip() Gary Herron > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From doug.farrell at gmail.com Wed Jul 9 14:48:59 2008 From: doug.farrell at gmail.com (writeson) Date: Wed, 9 Jul 2008 11:48:59 -0700 (PDT) Subject: Determining when a file has finished copying References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> Message-ID: Guys, Thanks for your replies, they are helpful. I should have included in my initial question that I don't have as much control over the program that writes (pgm-W) as I'd like. Otherwise, the write to a different filename and then rename solution would work great. There's no way to tell from the os.stat() methods to tell when the file is finished being copied? I ran some test programs, one of which continously copies big files from one directory to another, and another that continously does a glob.glob("*.pdf") on those files and looks at the st_atime and st_mtime parts of the return value of os.stat(filename). >From that experiment it looks like st_atime and st_mtime equal each other until the file has finished being copied. Nothing in the documentation about st_atime or st_mtime leads me to think this is true, it's just my observations about the two test programs I've described. Any thoughts? Thanks! Doug From notontheweb at noisp.com Sat Jul 26 19:17:15 2008 From: notontheweb at noisp.com (Jive Dadson) Date: Sat, 26 Jul 2008 23:17:15 GMT Subject: urllib and login with passwords In-Reply-To: References: Message-ID: <%fOik.344229$tY4.283186@fe06.news.easynews.com> Thanks, Rob! Some of that is beyond my maturity level, but I'll try to figure it out. If anyone has specific info on about how YouTube does it, I would appreciate the info. From martin at v.loewis.de Wed Jul 23 12:24:28 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 23 Jul 2008 18:24:28 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: References: Message-ID: <48875B3C.2030900@v.loewis.de> > 1>application.obj : error LNK2031: unable to generate p/invoke for > "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@$$J0YMXH at Z); > calling convention missing in metadata The main problem here is the __clrcall hint: apparently, you are using Managed C++ resp. C++/CLI, i.e. the Microsoft .NET Framework for C++. Don't do that. Instead, make sure that your project targets native Intel x86 code; then compile your code either as C or C++ (your choice). To integrate Python into managed C++ would require a lot of experience, and it may well not be possible. Regards, Martin From 4vinoth at gmail.com Wed Jul 30 10:17:43 2008 From: 4vinoth at gmail.com (:-)) Date: Wed, 30 Jul 2008 07:17:43 -0700 (PDT) Subject: New CMS in Python Message-ID: HI I am Glad to announce you that I am creating New CMS for Python. I'll post it after Python 3 release. Currently I only the Developer/Team Lead/Project Lead/Organization :) It would be Very lightweight Fast Easy to Use Ajax Enabled new?? Done. Please send me how U expect your new CMS would be? Cheers Vinoth From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 2 05:05:27 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Jul 2008 11:05:27 +0200 Subject: Problem with a for loop and a list In-Reply-To: References: Message-ID: <486b44d2$0$15038$426a74cc@news.free.fr> Alexnb a ?crit : > I am not sure what is going on here. Here is the code that is being run: > > def getWords(self): > self.n=0 > for entry in self.listBuffer: > self.wordList[self.n] = entry.get() > self.n=self.n+1 > print self.wordList def get_words(self): self.word_list = [e.get() for e in self.list_buffer] > This is the "listBuffer" that you see: > > self.listBuffer=[self.e1, self.e2, self.e3, self.e4, > self.e5, self.e6, self.e7, self.e8, > self.e9, self.e10, self.e11, > self.e12, self.e13, self.e14] What a fantastic naming scheme. So easy to read, understand and maintain. Congratulation, you just won the right to read "How to write unmaintainable code": http://mindprod.com/jgloss/unmain.html From steve at REMOVE-THIS-cybersource.com.au Sun Jul 13 02:56:20 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 13 Jul 2008 01:56:20 -0500 Subject: Why is this blowing the stack, thought it was tail-recursive... References: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> Message-ID: On Sat, 12 Jul 2008 19:25:18 -0400, Terry Reedy wrote: > ssecorp wrote: >> def fib(n): >> def fibt(a, b, n): >> if n <= 1: >> return b >> else: >> return fibt(b, a + b, n - 1) >> if n == 0: >> return 0 >> else: >> return fibt(0, 1, n); >> >> and can memoization speed up this even more? tesintg with memoization >> doesnt really say anything because it is so fast it is instant anyway. > > Except for the fact that a+b gets slower as a and b get bigger, this > would already be linear time in n. Memoization (here by means of a > linear list) only helps if the list is preserved and one makes repeated > requests for various fib values. > > I am just curious what input you tried that blew the stack? It had to > be pretty large. No, not really. Try it for yourself: on my system, I get RuntimeError: maximum recursion depth exceeded with fib(999). fib(999) is a large number, with 208 digits, but not that large: 268638100244853593861467272021429239676166093189869523401 231759976179817002478816893383696544833565641918278561614 433563129766736422103503246348504103776803673341511728991 69723197082763985615764450078474174626L -- Steven From paul at boddie.org.uk Tue Jul 29 12:21:04 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 29 Jul 2008 09:21:04 -0700 (PDT) Subject: Build tool for Python References: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Message-ID: On 29 Jul, 17:08, Hussein B wrote: > Apache Ant is the de facto building tool for Java (whether JSE, JEE > and JME) application. > With Ant you can do what ever you want: compile, generate docs, > generate code, packing, deploy, connecting to remote servers and every > thing. > Do we have such a tool for Python projects? There are quite a few similar tools here: http://wiki.python.org/moin/ConfigurationAndBuildTools Having looked at a few such tools recently, I found myself considering using plain old make for automating various non-compilation-related activities, but then again, plain Python is actually very good for automation if you get into the right mindset. Consequently, I've just written a bunch of functions which run programs, test outputs and potentially feed those outputs to other programs. Where most of the available generic tools seem to frustrate is in their support of the often necessary but complicated behaviour required to minimise the amount of unnecessary work performed, through frameworks which seem to obscure the nature of the work itself. I do understand that it can be awkward to work out which object files need recompiling due to changes in source files, for example, and that one doesn't want to see the logic involved reproduced all over the place, but I do wonder whether the machinery around such matters isn't sometimes more complicated in these tools as soon as one strays outside the common cases. It seems to me that some common build-related primitives implemented as functions combined with plain Python would be a good enough combination for a lot of tasks in this domain. Paul From bignose+hates-spam at benfinney.id.au Fri Jul 11 20:19:20 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 12 Jul 2008 10:19:20 +1000 Subject: Loading just in time References: Message-ID: <87k5fsosxj.fsf@benfinney.id.au> Ross Ridge writes: > D'Arcy J.M. Cain wrote: > >def calc_tax(*arg, **name): > > from calc_tax import calc_tax as _func_ > > calc_tax = _func_ > > return _func_(*arg, **name) > > This should do what you want: > > def calc_tax(*arg, **name): > global calc_tax > from calc_tax import calc_tax > return calc_tax(*arg, **name) > > I suspect though that the cost of importing a lot of little modules > won't be as bad as you might think. The performance cost isn't the only consideration. Importing modules at arbitrary places scattered through the code imposes a maintenance burden on any reader of the code. For this reason, PEP 8 requires conformant code to have imports in a standard location in the module: - Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. Imports should be grouped in the following order: 1. standard library imports 2. related third party imports 3. local application/library specific imports You should put a blank line between each group of imports. Put any relevant __all__ specification after the imports. This doesn't contradict the use of many small modules, but please, keep them imported according to PEP 8. -- \ ?People always ask me, ?Where were you when Kennedy was shot?? | `\ Well, I don't have an alibi.? ?Emo Philips | _o__) | Ben Finney From ewertman at gmail.com Sat Jul 26 15:58:51 2008 From: ewertman at gmail.com (Eric Wertman) Date: Sat, 26 Jul 2008 15:58:51 -0400 Subject: Execution speed question In-Reply-To: <4889a36f$1@news2-rz-ap.ethz.ch> References: <4889a36f$1@news2-rz-ap.ethz.ch> Message-ID: <92da89760807261258m5233145dr912c0d129c1c2045@mail.gmail.com> > The number of nodes is very large: millions for sure, maybe tens > of millions. If considering (2), take note of my BOLD text above, which > means I can't remove nodes as I iterate through them in the main loop. Since your use of 'node' is pretty vague and I don't have a good sense of what tests you are running and how long they would take, I'm only speculating, but a single loop might be the wrong way to go about that. If you are going to be frequently running tests and switching nodes on/off, have you considered a separate set of processes to do both? For example: A set of some number of "tester" threads, that loop through and test, recording thier results (somewhere). You could then have a separate loop that runs every so often, checks all the current test values, and runs through the nodes once, switching them on or off. I know it's not exactly what you asked, but depending on what your nodes are exactly, you can avoid a lot of other problems down the road. What if your single loop dies or gets hung on a test? With a separate approach, you'll have a lot more resilience too.. if there's some problem with a single tester or node, it won't keep the rest of the program from continuing to function. From gerard.blais at gmail.com Wed Jul 9 07:40:59 2008 From: gerard.blais at gmail.com (Gerry) Date: Wed, 9 Jul 2008 04:40:59 -0700 (PDT) Subject: How to make python scripts .py executable, not bring up editor References: <7a34ceb4-4f2e-4c79-aeb2-587235cab19d@z72g2000hsb.googlegroups.com> Message-ID: <12faab2c-1fdd-4858-8c61-d57548076aa6@e39g2000hsf.googlegroups.com> And if you've gotten this far, why not take the next step: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/476204 and just type tryme (as opposed to tryme.py) Gerry From Eric_Dexter at msn.com Mon Jul 14 10:56:47 2008 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Mon, 14 Jul 2008 07:56:47 -0700 (PDT) Subject: new python podcast Message-ID: http://www.podango.com/tag/python I just started to play with this and I wanted to know if there is any interest in this sort of thing now that the last (maybe I should say most proliffic) python podcaster has stopped being active.. I would also be intrested in knowing if there is a particular bit rate that people are after... first episode is an intro to the panda python setup.. mostly from the manual.. From eric.butteriss at wanadoo.fr Sat Jul 12 08:06:37 2008 From: eric.butteriss at wanadoo.fr (eric.butteriss) Date: Sat, 12 Jul 2008 14:06:37 +0200 Subject: Confused Message-ID: <000001c8e417$c2b5bc50$0a01a8c0@HOMEPC> Please tell me why may mail is being returned. The message says I have been blacklisted...for what reason? I never open mail that I know is not expected and I never send junk or spam. I am trying to send important info to my cousin. Thank you in anticipation E Butteriss -------------- next part -------------- An HTML attachment was scrubbed... URL: From cokofreedom at gmail.com Wed Jul 9 07:10:59 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 9 Jul 2008 04:10:59 -0700 (PDT) Subject: a simple 'for' question References: Message-ID: On Jul 9, 2:08 am, Ben Keshet wrote: > Hi fans, > > I want to use a 'for' iteration to manipulate files in a set of folders, > something like: > > folders= ['1A28','1A6W','56Y7'] > for x in folders: > print x # print the current folder > f = open('my/path/way/x/my_file.txt', 'r') > ... > > where 'x' in the pathway should iterate over '1A28','1A6W','56Y7'. How > should I identify 'x' in the pathway line as the same x that is > iterating over 'folders'? > > I am getting the following error: > > Traceback (most recent call last): > File > "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Linux\Dock_method_validation\myscripts\test_for.py", line 5, > in > f = open('c:/Linux/Dock_method_validation/x/receptor.mol2', 'r') > IOError: [Errno 2] No such file or directory: > 'c:/Linux/Dock_method_validation/x/receptor.mol2' > > I tired several variations: %x, 'x', "x", etc. all gave me similar errors. > > Thanks for your help, > BK >>> folders = ["a", "b", "c"] >>> for item in folders: print item file = open("my/path/way/" + item + "/my_file.txt", "r") From gagsl-py2 at yahoo.com.ar Mon Jul 28 07:05:48 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 Jul 2008 08:05:48 -0300 Subject: Raw Strings (I Think) References: Message-ID: En Thu, 24 Jul 2008 12:02:00 -0300, Lanny escribi?: > I've used glob.glob to get a list of files in a directory > and now I want to use os.system to execute one of > those files, the problem is that python automatically > puts a escape charater infront of the back slashes > so the os.system gets X:\\####\\####\\ and is useless, > I think I need to convert my string to a raw string but > I don't know how. Those \\ represent a SINGLE character. That is, they LOOK duplicated in code and when you use repr(...) but it's actually a single backslash: >>> path = "X:\\abc" >>> path 'X:\\abc' >>> print path X:\abc >>> len(path) 6 Probably you have another issue - please post a short but complete failing code... -- Gabriel Genellina From straton at lampsacos.demon.co.uk Mon Jul 28 19:22:40 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Tue, 29 Jul 2008 00:22:40 +0100 Subject: derivative in numpy In-Reply-To: References: Message-ID: Ken Starks wrote: > knielsen73 at gmail.com wrote: >> Hi, >> >> I am looking to do a simple derivative. I would expect such a function >> to be available in numpy, but can't find it. I have written my own, >> but just curious if anybody knows of such function in numpy. >> >> Cheers, >> Kim > numpy and much more are wrapped together in 'sage' and you should get > the functionality you need there. > > For a review, see: > > http://vnoel.wordpress.com/2008/05/03/bye-matlab-hello-python-thanks-sage/ Sorry, the review isn't very useful. for something more focused on your request, see: http://www.sagemath.org/doc/tut/node13.html From tjreedy at udel.edu Wed Jul 2 20:40:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 02 Jul 2008 20:40:52 -0400 Subject: Generating list of possible configurations In-Reply-To: References: Message-ID: Mensanator wrote: > On Jul 2, 4:53 pm, "bjorklund.e... at gmail.com" > wrote: >> After this I tried figuring out a function that would generate the >> different possible configurations, but I couldn't quite wrap my head >> around it... > Lookup "Cartesian Product". > >> Any pointers as to how one would go about >> solving something like this would be greatly appreciated. > > for a in [True,False]: > for b in [True,False]: > for c in [1,2,3,4]: > print 'combined settings:',a,'\t',b,'\t',c This has been added to itertools at least for 2.6/3.0 >>> import itertools as it >>> for prod in it.product((True,False), (True,False), (1,2,3,4)): print(prod) # or run test (True, True, 1) (True, True, 2) (True, True, 3) (True, True, 4) (True, False, 1) (True, False, 2) (True, False, 3) (True, False, 4) (False, True, 1) (False, True, 2) (False, True, 3) (False, True, 4) (False, False, 1) (False, False, 2) (False, False, 3) (False, False, 4) The sequences of sequences can, of course, be a variable: >>> options = ((True,False), (True,False), (1,2,3,4)) >>> for prod in it.product(*options): print(prod) does the same thing. So you can change 'options' without changing the test runner. tjr From ldo at geek-central.gen.new_zealand Mon Jul 21 05:13:39 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 21 Jul 2008 21:13:39 +1200 Subject: Python Written in C? References: Message-ID: In message , Michiel Overtoom wrote: > Many major text/word processing programs (Emacs, vi, MS-Word) are also > written in C. Does that mean you should do all your text processing in C? How else would you implement a Boyer-Moore algorithm? From rocksportrocker at googlemail.com Tue Jul 22 08:46:42 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Tue, 22 Jul 2008 05:46:42 -0700 (PDT) Subject: Python embedding question (2). References: Message-ID: On 22 Jul., 14:07, Thomas Troeger wrote: > Carl Banks wrote: > > On Jul 17, 9:57 am, Thomas Troeger > > wrote: > >>> I'd say that PyGame could be a solution. > >>> Or otherwise you could do your own audio/graphics programming (you don't > >>> tell us which OS you use, but there exist python modules that allow you > >>> to do barebones graphics & sound programming on linux...). > > Pyglet runs on top of OpenGL, which might have performance problems on > > an embedded device, if OpenGL or Mesa is even supported. ?If it's > > supported, I suspect performance will be adequate for 2D drawing. ?It > > almost certainly is the lightest solution you can find. > > > Carl Banks > > I've managed to put together a small pyGame program, it runs smoothly > and seems to be exactly what I wanted. It's fast! Even with 100 moving > objects it still runs so fast that I can consider using Python/pyGame > for the whole project. > > There are still some questions left which I haven't found out by myself, > so maybe someone here can answer them: > > - I can't see how to create more sophisticated text output, it seems the > built in font render facilities are limited to simple strings. Is that > true? I'd need a way to at least render multiline text with paragraphs > and bidirectionality, like pango does it. Is there a way to integrate > pango support into pyGame? I'd prefer marked up text display with text > properties ... > - Is there some way to reserve screen areas so they are excluded from a > blit, or do I have to manage stuff like this myself? I am thinking about > several graphic layers where each layer is painted on top of the next > layer, for example to draw a gui in front of a background image. > - There seems to be support for video overlay, i.e. is it possible to > have an external program paint an image from a camera into a portion of > the screen while pyGame is running? > > Maybe this is the wrong list to ask, so please forgive the question but > direct me to somewhere better. > > Cheers, > Thomas. Maybe http://sourceforge.net/projects/pygameui/ helps you, at least the source code. Greetings, Uwe From larzluv at hotmail.com Fri Jul 18 14:43:26 2008 From: larzluv at hotmail.com (Larry Hale) Date: Fri, 18 Jul 2008 11:43:26 -0700 (PDT) Subject: Python Behind a Squid Corporate Proxy on Windows References: <7b541a3b-846f-496a-aee1-d5719217e011@m45g2000hsb.googlegroups.com> <821d7616-3faa-4dae-a988-18caf4f8598a@8g2000hse.googlegroups.com> <84c473ed-6993-481a-b789-35851242895b@f1g2000prb.googlegroups.com> Message-ID: Thank you so much for the reply, but alas: I get the same results. (urllib2 makes the initial request, Squid replies "Error 407: Proxy Authentication Required", which urllib2 dutifully fails on/raises said error...) I do appreciate your time, though! :) -Larry On Jul 18, 3:08?am, Chris wrote: > On Jul 17, 6:40?pm, Larry Hale wrote: > > > Err, the line above should be: > > > proxy_handler = urllib2.ProxyHandler( { "http": "http:// > > myusername:passw... at webfilter.xyz.local:3128" } ) > > > (Sorry! ?:) > > some old code I wrote to download public domain info for our company, > also through a squid proxy and this still works for me > > import urllib2, urllib > > proxy = urllib2.ProxyHandler({'http': 'http:// > username:password at proxy_url:proxy_port'}) > auth = urllib2.HTTPBasicAuthHandler() > opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) > urllib2.install_opener(opener) > > conn = urllib2.urlopen('http://python.org') > return_str = conn.read() > > fp = open('python.html','w').write(return_str) From PengYu.UT at gmail.com Thu Jul 24 13:48:05 2008 From: PengYu.UT at gmail.com (Peng Yu) Date: Thu, 24 Jul 2008 10:48:05 -0700 (PDT) Subject: Is there a metacharacter to match transitions between any two of a set of non intersected char classes? Message-ID: Hi, '\b' only match the boundary between alphanumerical char and nonalphanumerical char. I'm wonder if there is a generic metacharacter to match the boundary between any non intersected char set defined in regex and its complement. For example, I have a few non intersected char sets [a-zA-Z_0-9], [:] and [\s], and lets call the new metacharactor \m. r"abc\m" would be the same as r"abc\b" r"abc:\m' would match "abc:" in r"abc:xy" but not "abc::xy" r"a \m" (with one space) would match "a " (with one space) in "a abc" but not "a abc" (with two spaces). I would like that I have the flexibility to define more non intersected char sets, while I don't want change the regex that I have written. Thanks, Peng From asd at pittle.org Sun Jul 6 07:10:50 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Sun, 6 Jul 2008 04:10:50 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: Message-ID: <8ad14f1d-f10b-4a1c-b66a-67ce987def88@m36g2000hse.googlegroups.com> On Jul 4, 7:31?am, Jeroen Ruigrok van der Werven wrote: > -On [20080630 23:51], Ali Servet D?nmez (a... at pittle.org) wrote: > > >This could be an extension, a plugin, an Emacs mode, a new editor or > >even a brand new huge all-fancy IDE, I don't care, but what am I > >missing here? > > Vim's omnicomplete (CTRL-X CTRL-O). > > See :help omnifunc within vim. > > -- > Jeroen Ruigrok van der Werven / asmodai > ????? ?????? ??? ?? ??????http://www.in-nomine.org/|http://www.rangaku.org/| GPG: 2EAC625B > Don't always think in a straight line... Jeroen, your advice might be *the solution* to the problem; but I'm not really into using Vi(m). Thank your very much anyway! From kyosohma at gmail.com Thu Jul 31 09:05:51 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 31 Jul 2008 06:05:51 -0700 (PDT) Subject: working pylint anyone? References: <6fdf17Fb2bboU1@mid.uni-berlin.de> Message-ID: On Jul 31, 4:29?am, "Diez B. Roggisch" wrote: > Hi, > > until yesterday I was a happy user of pylint. Then I upgraded to ubuntu > hardy heron - and the trouble began. > > The packaged version of pylint (0.13.2) fails with this error (last line): > > logilab.common.configuration.UnsupportedAction: callback > > The same error happens if I use > > easy_install-2.5http://release.ingeniweb.com/third-party-dist/logilab.installer-0.1.tgz > > as found on the net. Using easy_install pylint misses logilab-common & > astng, installing these additionally (easy_install) creates two eggs - but > unfortunately, the don't actually create a namespace-package logilab, > instead either one of them is picked up depending on installation order. > > Then I tried the source releases - no luck either, either they produce the > same error or something similar. > > I tried looking into the MLs - the last posts are from around 2006, so I > refrained from actually subscribing. > > So - anybody out here having an actually working pylint config and can tell > me what versions work together? I've become pretty dependend on it to be > honest... > > Diez For future reference, I found this installer package helpful in getting PyLint and its dependencies to all install correctly: http://tarekziade.wordpress.com/2008/02/20/pylint-installation-made-easier/ http://pypi.python.org/pypi/logilab.pylintinstaller I used it on Windows, but it should (theoretically) work on Linux just as well. Mike From heikki at osafoundation.org Thu Jul 24 01:33:19 2008 From: heikki at osafoundation.org (Heikki Toivonen) Date: Wed, 23 Jul 2008 22:33:19 -0700 Subject: Undocumented Python 2.6 change: Py_None vs NULL when C implementation raises exception In-Reply-To: <4887b13a$0$7677$9b622d9e@news.freenet.de> References: <4887b13a$0$7677$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > Heikki Toivonen wrote: >> I tracked this down to the C code incorrectly returning Py_None when it >> should have returned NULL. Changing the C code to return NULL made it >> behave correctly in 2.6. > > Can you please be specific what function you are talking about? Perhaps it wasn't clear that I was referring to the C code in an extension, M2Crypto. I assumed that this affected all extension code like this, which is why I didn't mention the actual lines. It appears from Fredrik's comment that this might not be just a 2.6 issue, but that this problem has cropped up in the past as well more or less randomly. >> I don't know how common a mistake it is to return Py_None when NULL >> should have been returned, but it might be worth a note in the list of >> changes for 2.6 that this behavior changed, don't you think? > > Perhaps. OTOH, perhaps the change is completely erroneous. In that case, > rather than documenting it, it should be reverted. > > Unfortunately, as you keep the specific issue secret, none of this will > happen, as we have no clue what you are talking about. I don't know what change in Python caused the change in M2Crypto behavior. I can only point you to the change I made in M2Crypto if you are interested: http://viewcvs.osafoundation.org/m2crypto/trunk/SWIG/_pkcs7.i?rev=531&r1=611&r2=531 If you revert that change and run the M2Crypto unit tests you will see the single error in the tests. > I'm sure there are tons of silent changes, in this release, all past > releases, and all future releases, not only in Python, but in any > software. Given that there is a long document showing the changes in each Python release, I would hope all intended changes of significance would be listed. Of course mistakes can happen, which was why I posted in the first place. I have no plans to track down the exact change in Python code that caused this. There does not seem to be much point, since according to Fredrik this seems to be an area that is practically undefined and the M2Crypto code was clearly buggy. -- Heikki Toivonen From ddasilva at umd.edu Wed Jul 30 00:30:37 2008 From: ddasilva at umd.edu (Daniel da Silva) Date: Wed, 30 Jul 2008 00:30:37 -0400 Subject: static variables in Python? In-Reply-To: References: Message-ID: <8d9ec3dd0807292130p7452e54eoba116d2f346d9b70@mail.gmail.com> This is the solution I suggest. It is fairly trivial, and works by introducing the "self.static" namespace for a class's static variables, in contrast to "self" for the class's instance variables. ----------------------------------- class Static(object): pass personStatic = Static() class Person: static = personStatic def __init__(self, name, age): self.name = name self.age = age def setVersion(self, version): self.static.version = version def getVersion(self): return self.static.version ----------------------------------- Daniel On Tue, Jul 29, 2008 at 4:40 PM, kj wrote: > > > Yet another noob question... > > Is there a way to mimic C's static variables in Python? Or something > like it? The idea is to equip a given function with a set of > constants that belong only to it, so as not to clutter the global > namespace with variables that are not needed elsewhere. > > For example, in Perl one can define a function foo like this > > *foo = do { > my $x = expensive_call(); > sub { > return do_stuff_with( $x, @_ ); > } > }; > > In this case, foo is defined by assigning to it a closure that has > an associated variable, $x, in its scope. > > Is there an equivalent in Python? > > Thanks! > > kynn > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. > -- > http://mail.python.org/mailman/listinfo/python-list > From elessar at nienna.org Sat Jul 26 00:43:45 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 25 Jul 2008 22:43:45 -0600 Subject: Attack a sacred Python Cow In-Reply-To: <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> Message-ID: <488AAB81.5070603@nienna.org> Jordan wrote: > Well this discussion is chugging along merrily now under its own > steam, but as the OP I should probably clarify a few things about my > own views since people continue to respond to them (and are in some > cases misunderstanding me.) > > I *like* explicit self for instance variable access. There are > arguments for and against, and my personal opinion is that the > arguments for are stronger. Local variables and instance variables > should be explicitly differentiated somehow, for the sake of > readability. Python's approach works. I slightly prefer Ruby's @, > because I think the brevity is a net win for something so commonplace > (is it less readable? Maybe. is "def" less readable than "define"? I > don't know - I think about 10 seconds of coding in Python or Ruby is > enough for you to be able to instantly grok def. Likewise, @. The > argument is more aesthetic IMO - how many perl-style/1337speak pu|\| > (tu at t10n m at r|<$ can you stand?) > > I have come to dislike explicit self in method argument lists. Sure, > there are reasons. I don't think they're at all strong enough. > > I'm definitely against the != behaviour, and maybe will get around to > actually PEPing it. > > The point I was trying to make originally was that applying any mantra > dogmatically, including Explicit is better than implicit, can lead to > bad results. Perhaps having Practicality beats purity is enough of a > reminder of that fact for the Python community :-) > -- > http://mail.python.org/mailman/listinfo/python-list > Having followed this entire discussion, I don't think that explicit vs. implicit is really the issue. Your own examples, self in the arg list and __ne__ not being the negation of __eq__ by default, seem to contradict your premise that explicit is dogmatically favored over implicit. Keep in mind that another core principle of Python is "don't make the user type it if they don't have to." As you yourself admit, there are very compelling reasons to make the user type self in every method argument list, one of which being yet another Python principle, readability. Therefore, explicit self didn't come through dogmatic adherence to explicit over implicit, but through careful consideration. As for !=, it seems like there is a technical reason for the behavior. Remember, there is no default __ne__ method, so the behavior you want would have to live in the interpreter. If __ne__ isn't defined, it would have to try to call __eq__ and negate the result. Is there any other lookup that is treated this way? It seems like a kludge to add this special type of behavior for one case that doesn't seem to bother most people anyway. So really, this is about a couple annoyances you've found in a language you otherwise like. And it seems like both can be addressed pretty easily. PyLint, for example, already checks that self is the first argument of methods. And since it has a plugin system, I'm sure you could add a check for __ne__ if __eq__ is defined. You can turn off the checks you don't care about and bind it to a key combo in your text editor. Those annoying little errors will be exposed very quickly. -Matt From deets at nospam.web.de Tue Jul 29 11:11:28 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jul 2008 17:11:28 +0200 Subject: Build tool for Python References: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Message-ID: <6f8qb5Fafh42U2@mid.uni-berlin.de> Hussein B wrote: > Hi. > Apache Ant is the de facto building tool for Java (whether JSE, JEE > and JME) application. > With Ant you can do what ever you want: compile, generate docs, > generate code, packing, deploy, connecting to remote servers and every > thing. > Do we have such a tool for Python projects? distutils and setuptools are used to create distributions of python-packages, potentially compiling e.g. C or pyrex-sources, and you can hook into them to create e.g. api-docs. Diez From fredrik at pythonware.com Tue Jul 22 15:34:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 21:34:51 +0200 Subject: software engineering foundations? In-Reply-To: References: <18566.11394.326317.821553@montanaro-dyndns-org.local> Message-ID: Fredrik Lundh wrote: > just get McDonnell's "Code Complete": > > http://www.cc2e.com/ McConnell, that is. McConnell. sorry. From fabiofz at gmail.com Sat Jul 5 07:34:56 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Sat, 5 Jul 2008 08:34:56 -0300 Subject: pydev and psycopg2 - weird behaviour In-Reply-To: <486e7bfc@news.alcatel.com> References: <486e7bfc@news.alcatel.com> Message-ID: Hi Ross, Usually that happens when some module contains too much runtime information and the static analysis cannot get it... You can probably fix that by adding 'psycopg2' to the list of builtin modules... See http://fabioz.com/pydev/manual_101_interpreter.html for information on how to configure that (look for forced builtins). Cheers, Fabio On 7/4/08, RossGK wrote: > > > I've been using pydev for a short while successfully, and Django with > postgresql as well. psycopg2 is part of that behind the scenes I would > imagine, to make django work. > > Now I'm trying to use psycopg2 in a non-Django program, I'm seeing some > weird behaviour > > My "import psycopg2" is tagged in pyDev (eclipse) as "Unresolved Import: > psycopg2" > > But when I run my code anyway, I seem to connect to the postgresql DB okay. > If I remove the import, and try it, it fails. > > So it seems to use it, but thinks it's unresolved. Any idea what's going > on there? > > Just to be sure it's installed right, I reinstalled with no change. I also > opened a python shell (cmd window in winXP environment) and on the command > line issued a psycopg2 connect request which succeeds as well. So it mostly > seems to be an erroneous report from pydev that it can't resolve psycopg2 > when it apparently can? > > Your input appreciated... > > Ross. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From circularfunc at yahoo.se Thu Jul 3 14:00:20 2008 From: circularfunc at yahoo.se (defn noob) Date: Thu, 3 Jul 2008 11:00:20 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: <6d4bfmFp3aoU1@mid.uni-berlin.de> <0f6f795d-8041-463e-8e98-9d830ca3fc5b@l42g2000hsc.googlegroups.com> Message-ID: <64c5634a-f8af-4de6-a337-be83c59aed3b@m44g2000hsc.googlegroups.com> and yes it is parallel python. and windows vista. and the python GUI shell. From rotlaus at gmail.com Mon Jul 7 02:01:45 2008 From: rotlaus at gmail.com (Rotlaus) Date: Sun, 6 Jul 2008 23:01:45 -0700 (PDT) Subject: extended setattr() Message-ID: 2 weeks ago i asked for a etended getattr() which worked really fine, but now i would love to have a extended setattr() as well. Lets assume i have some classes: class A(object): def __init__(self): self.B = B() class B(object): def __init__(self): self.C = C() class C(object): def __init__(self, foo='', bar=''): self.foo = foo self.bar = bar and now i wanna do something like this: a=A() ext_setattr(a, 'B.C', ('a', 'b')) Is this possible? It would also be nice if the attributes would be created if they not exist, always implying that objectname==objecttype. Kind regards, Andre From M.Busetto at isac.cnr.it Wed Jul 23 05:07:25 2008 From: M.Busetto at isac.cnr.it (maurizio) Date: Wed, 23 Jul 2008 11:07:25 +0200 Subject: maximum value in a column of file In-Reply-To: References: <4886DCF3.10107@isac.cnr.it> Message-ID: <4886F4CD.8010704@isac.cnr.it> i tryed to use the module max of numpy, the problem is that i don't know how to put the column of the file in an array. (i'm new in phyton). anyway if you think there is a better way..... Fredrik Lundh wrote: >
maurizio > wrote: > >> which is the best way for the calculation of the maximum value in >> a column of a file? > > what approach have you tried, and what happened when you tried it? > > > > >
From tjreedy at udel.edu Fri Jul 18 03:45:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Jul 2008 03:45:58 -0400 Subject: % sign in python? In-Reply-To: <48d08494p4jnhkrhgidmgppg1aostmurvn@4ax.com> References: <48d08494p4jnhkrhgidmgppg1aostmurvn@4ax.com> Message-ID: Tim Roberts wrote: > Steven Howe wrote: > >> Terry Reedy wrote: >>> korean_dave wrote: >>>> What does this operator do? Specifically in this context >>>> >>>> test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) >> I thought, in this contexted, it was mapping operator. You miss clipped. I never wrote that. Please be careful, especially about attributing mis-information. > What?? > > Python does not have a "mapping operator". It has a "map" function, but no > equivalent operator. > > % is either the string formatting operator (when the left-hand operand is a > string) or the modulo operator (when the left-hand operand is a number). Which I learned 10 years ago. What I did write was a pre-announcement of a Python symbol glossary, which I just finished a first draft of. And now to bed ;-) From enleverlesX.XmcX at XmclaveauX.com Thu Jul 3 16:20:43 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Thu, 3 Jul 2008 22:20:43 +0200 Subject: PIL(Py Image lib), show() not showing picture... In-Reply-To: <84a8f15a-594f-4e02-aa89-b70932eae420@59g2000hsb.googlegroups.com> References: <84a8f15a-594f-4e02-aa89-b70932eae420@59g2000hsb.googlegroups.com> Message-ID: <486d366d$0$879$ba4acef3@news.orange.fr> Hi! Which OS? On Vista, you MUST reconfig the "aper?u images et t?l?copies" (in french ; sorry, I don't know the english translation). @-salutations Michel Claveau From fredrik at pythonware.com Mon Jul 21 08:14:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 14:14:15 +0200 Subject: simple question about dictionaries In-Reply-To: <8aedc744-f432-4a4a-a6e4-2bb714caf720@x35g2000hsb.googlegroups.com> References: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> <8aedc744-f432-4a4a-a6e4-2bb714caf720@x35g2000hsb.googlegroups.com> Message-ID: Jeff wrote: > throw KeyError('%s not found' % str(val)) "throw"? and shouldn't that be a ValueError? ;-) From tcfg at sina.com Thu Jul 17 02:18:45 2008 From: tcfg at sina.com (tcfg at sina.com) Date: Wed, 16 Jul 2008 23:18:45 -0700 (PDT) Subject: how to debug python's extend module written in c/c++ on windows References: <64d771b2-fbc8-4b6a-9725-3dc5063c5328@p25g2000hsf.googlegroups.com> <6e83v4F5pfg0U1@mid.uni-berlin.de> Message-ID: dear Diez: I need step into c function in extending module(DLL) when debugging the script. and I want Single-step debugging the extend module itself, but python script Launched The whole process. best regards fang From workitharder at gmail.com Sat Jul 12 23:03:17 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 12 Jul 2008 20:03:17 -0700 (PDT) Subject: Someone enlightened me References: Message-ID: <1724abf3-232a-4ffd-893d-fb0ee81e59e8@z72g2000hsb.googlegroups.com> On Jul 12, 7:08 pm, Marcus Low wrote: > Can someone explain to me, why the behaviour below is different when u > remark "lister" and unremark "self.lister"? > > #-------------------------------------------------------------- > class abc : > # remark this later and unremark "self.lister" > lister = [] > > def __init__ (self, val): > #self.lister = [] > self.lister.append(val) > > #-------------------------------------------------------------- > globallist = [] > #-------------------------------------------------------------- > def test () : > global l > for x in range(10) : > o = abc(x) > globallist.append(o) > o = "" > > for i in globallist : > print i.lister > > #-------------------------------------------------------------- > test() > #-------------------------------------------------------------- The way it's written, you're appending to a list associated with the class itself, which is created only once, then printing out that list 10 times. After you uncomment and comment the specified lines (this is the usual term, rather than "remark"), you are using a list that is associated with the actual object, then printing out the 10 different lists. Hope that's clear enough. --Buck From fredrik at pythonware.com Wed Jul 23 16:25:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 22:25:11 +0200 Subject: Raw Strings (I Think) In-Reply-To: References: Message-ID: Lanny wrote: > I've used glob.glob to get a list of files in a directory > and now I want to use os.system to execute one of > those files, the problem is that python automatically > puts a escape charater infront of the back slashes > so the os.system gets X:\\####\\####\\ and is useless, No, it doesn't. The backslash doubling only happens when you "echo" a variable to the terminal in interactive mode. If you want to know that the string really contains, use "print". Here's an example: >>> import glob >>> files = glob.glob("\\bin\\ls.exe") >>> files ['\\bin\\ls.exe'] >>> files[0] '\\bin\\ls.exe' >>> print files[0] \bin\ls.exe >>> import os >>> os.system(files[0]) Demo Makefile.pre.in Parser Doc Misc Python Grammar Modules README Include Objects RISCOS LICENSE PC Tools Lib PCbuild configure Mac PCbuild8 configure.in Btw, if you want to pass arguments to the program, you might want to use the "subprocess" module instead, since it handles escaping and quoting for you all by itself: >>> import subprocess >>> subprocess.call([files[0], "-l"]) total 479 drwxr-xr-x 26 1006 everyone 0 Oct 14 2006 Demo drwxr-xr-x 33 1006 everyone 0 Oct 14 2006 Doc drwxr-xr-x 6 1006 everyone 0 Oct 14 2006 Grammar ... There's also a function called "os.startfile", which can be used to "open" an arbitrary file (in the same as if you'd double-click on it in the explorer). > I think I need to convert my string to a raw string but > I don't know how. Raw strings are an alternate syntax for adding string literals to your source code, and has nothing to do with output. From adityashukla1983 at gmail.com Thu Jul 24 16:41:59 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Thu, 24 Jul 2008 15:41:59 -0500 Subject: Reading a file Message-ID: <73045cca0807241341x4c1e6b2cs3aab64be7df6e406@mail.gmail.com> Thanks a lot guys , i got it now. Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From laredotornado at zipmail.com Wed Jul 30 12:28:07 2008 From: laredotornado at zipmail.com (laredotornado) Date: Wed, 30 Jul 2008 09:28:07 -0700 (PDT) Subject: Syntax error in my script Message-ID: Hi, This might be more relevant for another group, but since this is a Python script, thought I'd start here. I'm trying to write a WLST script for WebLogic 9.2. I coped one directly from WebLogic's site (http://e-docs.bea.com/wls/docs90/config_scripting/ using_WLST.html#1078952), but I'm getting errors. Specifically, I'm getting $HOSTNAME:"$PWD"->sh run_setup_cluster.sh Initializing WebLogic Scripting Tool (WLST) ... Welcome to WebLogic Server Administration Scripting Shell Type help() for help on available commands Problem invoking WLST - Traceback (innermost last): (no code object) at line 0 File "/export/third-party/etsbea/home/etsbea/tests/npsconfig/ createcluster.py", line 2 from javax.management import * ^ SyntaxError: invalid syntax Below is my script. I know nothing about Python but cutting and pasting from BEA's site isn't cutting it. ============Begin createcluster.py file======================= from java.util import * from javax.management import * import javax.management.Attribute print 'starting the script .... ' connect('system','weblogic','t3://localhost:7001') clusters = "NPSCONFIG_GUI_Cluster" ms1 = {'managed1':7019:8020,'managed2':7020:8021} clustHM = HashMap() edit() startEdit() for c in clusters: print 'creating cluster '+c clu = create(c,'Cluster') clustHM.put(c,clu) cd('Clusters/' + c) set('MulticastAddress', '237.0.0.101') set('MulticastPort', 9200) set('WeblogicPluginEnabled', 'true') cd('..\..') clus1 = clustHM.get(clusters[0]) for m, lp, ssl_lp in ms1.items(): managedServer = create(m,'Server') print 'creating managed server '+m managedServer.setListenAddress('10.61.6.134') managedServer.setListenPort(lp) managedServer.setEnabled(0) cd('SSL/cgServer') managedServer.setEnabled(1) managedServer.setListenPort(ssl_lp) managedServer.setCluster(clus1) save() activate(block="true") disconnect() print 'End of script ...' exit() ==============End cretaecluster.py file======================= From duncan.booth at invalid.invalid Fri Jul 11 13:18:53 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Jul 2008 17:18:53 GMT Subject: strip() using strings instead of chars References: Message-ID: Christoph Zwerschke wrote: > In Python programs, you will quite frequently find code like the > following for removing a certain prefix from a string: > > if url.startswith('http://'): > url = url[7:] If I came across this code I'd want to know why they weren't using urlparse.urlsplit()... > > Similarly for stripping suffixes: > > if filename.endswith('.html'): > filename = filename[:-5] ... and I'd want to know why os.path.splitext() wasn't appropriate here. > > My problem with this is that it's cumbersome and error prone to count > the number of chars of the prefix or suffix. If you want to change it > from 'http://' to 'https://', you must not forget to change the 7 to 8. > If you write len('http://') instead of the 7, you see this is actually > a DRY problem. > > Things get even worse if you have several prefixes to consider: > > if url.startswith('http://'): > url = url[7:] > elif url.startswith('https://'): > url = url[8:] > > You can't take use of url.startswith(('http://', 'https://')) here. > No you can't, so you definitely want to be parsing the URL properly. I can't actually think of a use for stripping off the scheme without either saving it somewhere or doing further parsing of the url. From dear.jay.logan at gmail.com Sun Jul 27 17:49:01 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Sun, 27 Jul 2008 14:49:01 -0700 (PDT) Subject: Where is the correct round() method? Message-ID: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> Hello, I need a round function that _always_ rounds to the higher integer if the argument is equidistant between two integers. In Python 3.0, this is not the advertised behavior of the built-in function round() as seen below: >>> round(0.5) 0 >>> round(1.5) 2 >>> round(2.5) 2 I would think this is a common need, but I cannot find a function in the Python library to do it. I wrote my own, but did I miss such a method in my search of the Python library? Thanks From elessar at nienna.org Tue Jul 29 18:42:59 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Tue, 29 Jul 2008 16:42:59 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> Message-ID: <488F9CF3.6050301@nienna.org> Carl Banks wrote: > On Jul 29, 11:12 am, Matthew Fitzgibbons wrote: >> Carl Banks wrote: >>> On Jul 28, 8:15 pm, Steven D'Aprano >> cybersource.com.au> wrote: >>>> On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: >>>>> On Jul 28, 10:00 am, Steven D'Aprano >>>> cybersource.com.au> wrote: >>>>>> Cutting to the crux of the discussion... >>>>>> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: >>>>>>> I want something where "if x" will do but a simple explicit test >>>>>>> won't. >>>>>> Explicit tests aren't simple unless you know what type x is. If x could >>>>>> be of any type, you can't write a simple test. Does x have a length? Is >>>>>> it a number? Maybe it's a fixed-length circular length, and the length >>>>>> is non-zero even when it's empty? Who knows? How many cases do you need >>>>>> to consider? >>>>> Use case, please. I'm asking for code, not arguments. Please give me a >>>>> piece of code where you can write "if x" that works but a simple >>>>> explicit test won't. >>>> I gave you a piece of code, actual code from one of my own projects. If >>>> you wouldn't accept that evidence then, why would you accept it now? >>> I would accept as "evidence" something that satisfies my criteria, >>> which your example did not: it could have easily (and more robustly) >>> been written with a simple explicit test. I am looking for one that >>> can't. >>> You keep bringing up this notion of "more complex with no benefit", >>> which I'm simply not interested in talking about that at this time, >>> and I won't respond to any of your points. I am seeking the answer to >>> one question: whether "if x" can usefully do something a simple >>> explicit test can't. Everyone already knows that "if x" requires >>> fewer keystrokes and parses to fewer nodes. >>> Carl Banks >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> My use case involves a DAG of filters that pass data (of a variety of >> types--filters just pass on data types they don't understand) between >> them. I can also drop out of the filter chain at any point, using >> critera determined by the filters. These criteria, you guessed it, are >> bound to __nonzero__ in the filter and I determine whether or not to >> continue through the graph using "if x". You can't code explicit tests >> if you don't know what the tests even are beforehand. Also, I wanted to >> support builtins (ints and lists in particular) because they can be >> meaningful inputs to filters. Finally, as I add more filters and data >> types, I don't want to go back and mess with the code that decides >> whether or not to break out of the graph. > > Much like in Steven D'Aprano's example, still the only actual code > snippet I've seen, it seems that this can easily be done with a simple > explicit test by having all no-advance filters return None and testing > with "if x is not None". So it doesn't pass my criterion of being not > replaceable with simple explicit test. > > Maybe that's not workable for some reason. Perhaps if you'd post a > code example that shows this, rather than just talking about it, you > might be more persuasive. > > > Carl Banks > -- > http://mail.python.org/mailman/listinfo/python-list > The no-advance filters have to return the object because I don't just forget about it; I evaluate whether I pass it to the next filter or drop it in a completely different queue for use in the next stage of the operation. True means 'I'm ready to move on to the next stage,' False means 'Do the filter thing some more.' Furthermore, the argument that I should just change my API to make a 'simple test' work is not very convincing. The natural, obvious way for a filter to work is to pass through the data it operates on; why on Earth would it return None? I want to DO something with the data. In this case, make a decision about where to pass the data next. In Java, to accomplish this I would have to do lots of introspection and value checking (adding more any time I came up with a new kind of input), or make a new kind of interface that gives me a method so I can do a 'simple test' (including wrappers for ints and arrays and anything else I decide to pass in down the road). But Python supports duck typing and gives me a handy __nonzero__ method; I can rebind __nonzero__ in my filters for my own classes, and ints and lists are handled how I want them to be by default. So why jump through hoops instead of just using 'if x'? I don't have any postable code (it's in a half way state and I haven't touched it for a while), but I'll see if I can't find the time to bang something up to give you the gist. -Matt From varun.consit at gmail.com Tue Jul 1 09:35:25 2008 From: varun.consit at gmail.com (varun chadha) Date: Tue, 1 Jul 2008 06:35:25 -0700 (PDT) Subject: connecting to DBMS Message-ID: <669fe460-77bf-4e53-9f05-1237f2147b10@j1g2000prb.googlegroups.com> i am a newbie to python and is working on an application which needs to connect to the database. can anyone guide me through the DBMS that i can use and the module to connect to it. currently i have MySQL installed using the link on the python.org site but is unable to connect to it through python. pls specify the link to the tutorials which can guide to connect and execute my query. hopes u understood what i meant to say. thanks in advance From jonas.esp at googlemail.com Mon Jul 14 04:01:25 2008 From: jonas.esp at googlemail.com (Kless) Date: Mon, 14 Jul 2008 01:01:25 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> Message-ID: But in my dictionary both keys and values are unique. On Jul 14, 7:34?am, Dennis Lee Bieber wrote: > On Sun, 13 Jul 2008 16:21:11 -0700 (PDT), Kless > declaimed the following in comp.lang.python: > > > I need a dictionary where get the result from a 'key' (on left), but > > also from a 'value' (on right), how to get it? > > > I know that dictionaries aren't bidirectional, but is there any way > > without use two dictionaries? > > ? ? ? ? Just out of curiosity... What do you expect to have returned from... > > aDict = { "one" : "two", > ? ? ? ? ? ? ? ? "three" : "four", > ? ? ? ? ? ? ? ? "What?" : "two" ? ? } > > when looking for the value "two"? > > ? ? ? ? In a dictionary, the /keys/ are unique... but the /values/ can be > duplicates. From fredrik at pythonware.com Mon Jul 21 08:54:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 14:54:52 +0200 Subject: How to install simplejson on WinXP In-Reply-To: References: Message-ID: lookon wrote: > I am new to python and had difficulty in installing simplejson on > WinXP...Could anyone help me? Thanks what did you try, and what happened when you tried that? From mattheww at chiark.greenend.org.uk Tue Jul 29 21:52:31 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 30 Jul 2008 02:52:31 +0100 (BST) Subject: Boolean tests References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <87y73kg70u.fsf@benfinney.id.au> <009fa67c$0$20313$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >Anders wrote: >> "But then you decide to name the method "__nonzero__", instead of some >> nice descriptive name?" > That suggests to me that Anders imagined that __nonzero__ is something I > just made up, instead of a standard Python method. What does it suggest > to you? That he thinks using __nonzero__ like this decreases readability. He also wrote > In comparison, I gather you would write something like this: > class C: > def __nonzero__(self): > return len(self.method()[self.attribute]) > -1 > ... > c = get_a_C() > if c: > ... If he had imagined that __nonzero__ was something you just made up, the second-last line there would have read if c.__nonzero__() -M- From timothy.grant at gmail.com Tue Jul 15 20:53:09 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Tue, 15 Jul 2008 17:53:09 -0700 Subject: Testing for connection to a website In-Reply-To: <18476597.post@talk.nabble.com> References: <18473382.post@talk.nabble.com> <18476597.post@talk.nabble.com> Message-ID: On Tue, Jul 15, 2008 at 3:48 PM, Alexnb wrote: > > > > Alexnb wrote: > > > > Okay, I already made this post, but it kinda got lost. So anyway I need > to > > figure out how to test if the user is able to connect to a specific > > website. Last time I got pointed to the urllib2 page, but if I do > > urlopen() and and am not connected, the program stops. So I don't know if > > that was what you guys wanted me to do, but I don't think so, you guys > are > > smarter than that. So, how can I test for connection to a website. > > > > Just for anyone looking this up later here is code that works :) > > from urllib2 import * > import urllib2 > e = '' > > req = urllib2.Request('http://www.dictionary.com') > try: > response = urlopen(req) > > except HTTPError, e: > print e.code > except URLError, e: > print e.reason > > if e == '': > print "good to go" > -- > View this message in context: > http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p18476597.html > Sent from the Python - python-list mailing list archive at Nabble.com. > > -- > http://mail.python.org/mailman/listinfo/python-list > I'm glad to see you found the old post and implemented the code suggested there. -- Stand Fast, tjg. [Timothy Grant] -------------- next part -------------- An HTML attachment was scrubbed... URL: From shandy.b at gmail.com Thu Jul 3 21:19:58 2008 From: shandy.b at gmail.com (shandy.b at gmail.com) Date: Thu, 3 Jul 2008 18:19:58 -0700 (PDT) Subject: Python and timezones References: <66de1777-ab65-4708-904b-3e511409a662@m36g2000hse.googlegroups.com> Message-ID: I found a solution: http://groups.google.com/group/comp.lang.python/browse_thread/thread/aea64448eaca4778/250e908652e2646d If I use datetime.now(tz=tz) instead of datetime(Y,M,D,h,m,s, tzinfo=tz), it works. On Jul 3, 4:18?pm, "shand... at gmail.com" wrote: > Nah, it's got to be something more than that. ?A bunch of them are > screwed up. ?It's showing America/Saskatchewan as UTC-06:59. > > I think there's something wrong with my code. ?I've put it up at a > pastebin so that it's easier to read. > > http://pastebin.ca/1061776 > > On Jul 2, 11:22?am, Mensanator wrote: > > > On Jul 2, 12:43?am, "shand... at gmail.com" wrote: > > > > I'm trying to write some code to deal with world timezones, and I'm > > > getting a strange result. ?America/Iqaluit should not be showing up in > > > UTC+00:00, but it is. ?Can anyone see what's wrong with this code? > > > > import time > > > from datetime import datetime > > > import os > > > import pytz > > > > def getZoneNamesOnThisComputer(): > > > ? ? for i in pytz.all_timezones: > > > ? ? ? ? if os.path.exists( os.path.join('/tmp/usr/share/zoneinfo/', > > > i)): > > > ? ? ? ? ? ? yield i > > > > def getZonesGroupedByOffset(): > > > ? ? '''return a dict of all the zone names , grouped by their offset > > > ? ? eg: > > > ? ? {'-0400': ['America/Blanc-Sablon', 'Etc/GMT+4'], > > > ? ? ?'+0000': ['America/Iqaluit', 'Etc/GMT', 'Europe/Belfast', 'GB', > > > 'GMT'], > > > ? ? ?... > > > ? ? } > > > ? ? ''' > > > ? ? Y,M,D,h,m,s = time.localtime()[:6] > > > > ? ? zonesGroupedByOffset = {} > > > > ? ? for name in getZoneNamesOnThisComputer(): > > > ? ? ? ? tz = pytz.timezone(name) > > > ? ? ? ? now = datetime(Y,M,D,h,m,s, tzinfo=tz) > > > ? ? ? ? # strfime returns a string like "-0800" or "+0430" or "0000" > > > ? ? ? ? offsetKey = now.strftime('%z') > > > ? ? ? ? if not zonesGroupedByOffset.has_key(offsetKey): > > > ? ? ? ? ? ? zonesGroupedByOffset[offsetKey] = [] > > > ? ? ? ? zonesGroupedByOffset[offsetKey].append(name) > > > ? ? return zonesGroupedByOffset > > > > z = getZonesGroupedByOffset() > > > print z['+0000'] > > > > # Why is America/Iqaluit showing up here??? > > > The database contains an error. Shit happens, deal with it. > > From dream.andy at yahoo.com Fri Jul 25 23:47:10 2008 From: dream.andy at yahoo.com (Andy Peter) Date: Fri, 25 Jul 2008 20:47:10 -0700 (PDT) Subject: Exposure Your Google Groups in our FREE Advertising Board ! Message-ID: Exposure Your Google Groups in our FREE Advertising Board ! http://you.forumgogo.com/forum-7045-1.html Free Advertising Board in you.forumgogo.com (FREE AD EXPOSURES! ) http://you.forumgogo.com/forum-6637-1.html Your Forums and Community (Freebies, Games, Chat Room, Funny Stuff, General Discussion etc) http://you.forumgogo.com . From emen999 at gmail.com Fri Jul 25 06:05:00 2008 From: emen999 at gmail.com (code_berzerker) Date: Fri, 25 Jul 2008 03:05:00 -0700 (PDT) Subject: lxml, comparing nodes References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> <6c91a4da-6443-4570-8dd3-01c4ec169bf3@t54g2000hsg.googlegroups.com> <4888ad28$0$9491$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <4613042f-ed70-4cfa-8de9-a92b4df32923@k36g2000pri.googlegroups.com> > If document order doesn't matter, try sorting the elements of each level in > the two documents by some arbitrary deterministic key, such as (tag name, > text, attr count, whatever), and then compare them in order, instead of trying > to find matches in multiple passes. itertools.groupby() might be your friend here. I think that sorting multiple times by each attribute will cost more than I've managed to do: from lxml import etree from collections import deque import string, re, time def xmlEqual(xmlStr1, xmlStr2): et1 = etree.XML(xmlStr1) et2 = etree.XML(xmlStr2) let1 = [x for x in et1.iter()] let2 = [x for x in et2.iter()] if len(let1) != len(let2): return False while let1: el = let1.pop(0) foundEl = findMatchingElem(el, let2) if foundEl is None: return False let2.remove(foundEl) return True def findMatchingElem(el, eList): for elem in eList: if elemsEqual(el, elem): return elem return None def elemsEqual(el1, el2): if el1.tag != el2.tag or el1.attrib != el2.attrib: return False # no requirement for text checking for now #if el1.text != el2.text or el1.tail != el2.tail: #return False path1 = el1.getroottree().getpath(el1) path2 = el2.getroottree().getpath(el2) idxRE = re.compile(r"(\[\d*\])") path1 = idxRE.sub("", path1) path2 = idxRE.sub("", path2) if path1 != path2: return False return True Notice that if documents are in exact same order, each element is compared only once! From grante at visi.com Tue Jul 1 14:14:54 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 01 Jul 2008 13:14:54 -0500 Subject: How to use gnu readline library in program? References: Message-ID: <6e-dnXtxRu6D6ffVnZ2dnUVZ_sPinZ2d@posted.visi> >> What I want to do is replace sys.stdin.readline() with >> something that will provide the user with line editing and >> history recall. In other languages, one uses the Gnu readline >> library to do that, but my reading of the Python library >> documentation is that's not what the Python readline module is >> for. Am I wrong? > > Here's a simple example: > > import readline > > for s in "alpha beta gamma".split(): > readline.add_history(s) > > candidates = "red yellow pink blue black".split() > > def completer(word, index): > matches = [c for c in candidates if c.startswith(word)] > try: > return matches[index] + " " > except IndexError: > pass > > > readline.set_completer(completer) > readline.parse_and_bind("tab: complete") > > while 1: > print raw_input("$ ") Ah, thanks. It was far too simple. What I was looking for was simply: import readline then replace sys.stdin.readline() with raw_input() > You may also consider using the cmd module. I'll have to keep the cmd module in mind for other applications (where the user is entering commands). Rather than commands, the user of this application is entering data that changes little (if any) from one line to the next, so raw_input() is exactly what I needed. -- Grant Edwards grante Yow! I'm young ... I'm at HEALTHY ... I can HIKE visi.com THRU CAPT GROGAN'S LUMBAR REGIONS! From glman74 at gmail.com Sun Jul 27 05:51:40 2008 From: glman74 at gmail.com (glman74 at gmail.com) Date: Sun, 27 Jul 2008 02:51:40 -0700 (PDT) Subject: Iterating through 2 files simultaneously Message-ID: <7ae96aff-c1a7-4763-8db7-ff23766296df@u6g2000prc.googlegroups.com> Hi folks, I am trying to tee off both stdout and stderr from a process run through Popen. As a test, I am first trying to print the output below: from subprocess import Popen,PIPE ... p1 = Popen(['cvs', 'update'], stdout=PIPE, stderr=PIPE) for (l1, l2) in zip(p1.stdout, p1.stderr): print '-->' + l1, print '-->' + l2, This doesn't work - probably because I cannot iterate through the pipes this way. I am new to Python, and I'd appreciate it if you could please explain why this doesn't work and/or suggest an alternate way to redirect stdout and stderr to a common place. My objective is for my code to print out stdout/stderr messages and at the same time redirect them to a log file. Thanks Mahesh From basti.wiesner at gmx.net Tue Jul 15 13:46:09 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Tue, 15 Jul 2008 19:46:09 +0200 Subject: Is it legal to rebuild Python.exe to include Version property tab? References: Message-ID: ward.david at comcast.net : > My company distributes a COM object that can be license and userd by > our customers. Some of my company's internal application also use the > COM object. However, for internal applications, instead of licensing > the COM object, we just make the application registered as "friendly". > We accomplish this be including various information in the "version" > property tab of the calling EXE. > > In my case, the calling EXE is Python.exe. So, my question is, can we > rebuild Python.exe to include the various "version" information? Is > this allowed under the Python licensing agreement? Though being not a lawyer, I'd say "yes". Afair version metadata for windows executables is passed as compiler options, so you wouldn't even have to change the sources. Paragraph 2 of the PSF (the python license) grants you an explicit right to "reproduce, [...], prepare derivative works (and) distribute" Python, and there's no other paragraph saying "don't touch version information". Still, not sure paragraph 3 would affect distributors: "In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python." Looks like you have to add a document describing your changes to the modified distribution, but that shouldn't be showstopper ;) -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From tjreedy at udel.edu Sat Jul 12 19:25:18 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 19:25:18 -0400 Subject: Why is this blowing the stack, thought it was tail-recursive... In-Reply-To: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> References: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> Message-ID: ssecorp wrote: > def fib(n): > def fibt(a, b, n): > if n <= 1: > return b > else: > return fibt(b, a + b, n - 1) > if n == 0: > return 0 > else: > return fibt(0, 1, n); > > and can memoization speed up this even more? tesintg with memoization > doesnt really say anything because it is so fast it is instant anyway. Except for the fact that a+b gets slower as a and b get bigger, this would already be linear time in n. Memoization (here by means of a linear list) only helps if the list is preserved and one makes repeated requests for various fib values. I am just curious what input you tried that blew the stack? It had to be pretty large. The stack problem, by the way, is one reason linear induction is usually written in Python with iteration syntax instead of recursion syntax. Another is the extra simplicity. def fib(n): a,b = 1,0 while n: a,b,n = b, a+b, n-1 return b A third is the ease of conversion to a (space-efficient) generator function. def fib_gen() a,b = 1,0 while True: yield b a,b = b, a+b The generator it produces can be used, for instance, to fill a list (linear memo) 'on demand'. A model that leads to the linear algorithm (as opposed to the double recursion derived from Fibonacci's rabbit model) is as follows: A population consists of juveniles and adults. In one period, juveniles become adults (which never die) and adults birth (or bud off) one juvenile. (Yeast are somewhat like this.) At time 0, we start with 1 juvenile and 0 adults. How many adults are there at time n? Terry Jan Reedy From fredrik at pythonware.com Wed Jul 16 11:10:14 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 17:10:14 +0200 Subject: Angle brackets in command-line arguments? In-Reply-To: <52f1cde3-6240-46b0-8b03-478454e87688@b1g2000hsg.googlegroups.com> References: <52f1cde3-6240-46b0-8b03-478454e87688@b1g2000hsg.googlegroups.com> Message-ID: Keith Hughitt wrote: > I am using someone else's script which expects input in the form of: > > ./script.py arg2 is a common notation for "replace with argument value", so it could be that they're just expecting you to type: ./script.py arg1 arg2 Alternatively, they meant ./script.py arg2 in which case arg1 and arg2 are filenames. This is most commonly used with tools that process textfiles in some way. In the latter case, you can try the script simply by running: ./script.py and then typing the input to the terminal (use control-D on Unix or control-Z on Windows to terminate). Do the instructions use more meaningful names than "arg1" and "arg2"? From maphew at gmail.com Sat Jul 5 02:29:31 2008 From: maphew at gmail.com (maphew) Date: Fri, 4 Jul 2008 23:29:31 -0700 (PDT) Subject: install py2exe in vista References: <98aab64d0806211028i57bdc3e3kfaf2cf3b97e351e2@mail.gmail.com> Message-ID: <924c20f6-df19-449d-80ec-e69c9c8a6359@t54g2000hsg.googlegroups.com> SOLVED: right-click on the install program and "Run as administrator" solution courtesy of http://support.esri.com/index.cfm?fa=knowledgebase.techarticles.articleShow&d=34538 On Jun 22, 11:34?am, jim-on-linux wrote: > On Saturday 21 June 2008 13:28, Herman wrote: > > > ?I want to install it in > > vista >l#>, but i get this message in the process: > >couldnotcreate...py2exe-py2.5 > > I forwarded your question but you may want to ask again > at the link below. > > py2exe-us... at lists.sourceforge.net > > jim-on-linuxhttp://inqvista.com > > > > > I press 'OK', then.. > >couldnotset key value python 2.5 py2exe-0.6.8 > > > I press 'OK' again, then... > >couldnotset key value > > c:\Python25\Removepy2exe.exe" -u > > "c:\python25\py2exe-wininst.log > > > The installation goes on and do something, run some > > postinstall script. > > > I thought it should be ok, but i fail even creating > > a simple hello word exe. I get this message after i > > run python setup.py install: running install > > running build > > running install_egg_info > > Writing > > c:\Python25\Lib\site-packages\UNKNOWN-0.0.0-py2.5-eg > >g-info > > > No output is created. > > > Can I anyone help me with this? > > > > >ost&p=631985>- Hide quoted text - > > - Show quoted text - From stefan_ml at behnel.de Wed Jul 23 02:05:47 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 23 Jul 2008 08:05:47 +0200 Subject: xpathEval fails for large files In-Reply-To: References: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> <48864b0d$0$9494$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <4886ca3b$0$18828$9b4e6d93@newsspool2.arcor-online.net> Kanch wrote: > Original file was 18MB, and contained 288328 element attributes for > the particular path. You didn't say how many elements there are in total, but I wouldn't expect that to be a problem, unless you have very little free memory (say, way below 256MB). I just tried with lxml 2.1 and a 40MB XML file with 300 000 elements and it lets the whole Python interpreter take up some 140MB of memory in total. Looping over all elements by calling "list(root.iter())" takes a bit more than one second on my laptop. That suggests that /any/ solution involving lxml (or cElementTree) will do just fine for you. > I wonder whether for loop will cause a problem in iterating for 288328 > times. You are heavily underestimating the power of the Python here. Stefan From paul at boddie.org.uk Mon Jul 28 11:51:04 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 28 Jul 2008 08:51:04 -0700 (PDT) Subject: xml.dom's weirdness? References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> <488C3645.8060304@behnel.de> <488c75ee$0$29448$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <913ac597-6be3-4394-b3a6-79a2ac06d3c3@34g2000hsf.googlegroups.com> On 28 Jul, 16:15, Sion Arrowsmith wrote: > Stefan Behnel wrote: > >Blame Ubuntu/Debian. > > I'd be wary about including Debian in that blame. Using 4.0 here, > with a 2.4.4 default and a 2.5.0 straight from the package: [...] I can imagine that some of the Python Eggs magic could quite easily inflate the number of files opened when doing imports. Information on things like the state of site-packages, .pth files, the length of PYTHONPATH and so on should surely accompany the numbers before fingers are pointed. Paul From enleverlesX.XmcX at XmclaveauX.com Tue Jul 29 07:19:47 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Tue, 29 Jul 2008 13:19:47 +0200 Subject: Python COM In-Reply-To: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> References: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> Message-ID: <488eff34$0$869$ba4acef3@news.orange.fr> Hi! Example, with Pywin32: import win32com.client moncom = win32com.client.Dispatch('MyCOM1.AdvMethod') moncom.IAdvMethod(... See Pywin32 here: http://sourceforge.net/projects/pywin32/ @-salutations Michel Claveau From hobesh at gmail.com Mon Jul 28 16:41:31 2008 From: hobesh at gmail.com (Zach Hobesh) Date: Mon, 28 Jul 2008 13:41:31 -0700 Subject: Running python scripts in a VB program Message-ID: Does anyone have any clue on how to embed python scripts in a visual basic windows app? Additionally, does anybody else feel like Visual Basic is ridiculously confusing? Any help is appreciated. Thanks, -Zach -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Sun Jul 20 20:11:34 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 20 Jul 2008 17:11:34 -0700 (PDT) Subject: Python Written in C? References: Message-ID: On Jul 20, 5:50?pm, giveitawhril2... at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. Python is for people who want to program, not REAL WORLD programmers. > > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language C isn't a high level language, that's part of its problem. > which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > > I'm not dissing Python, here. Yes, you are. > Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. Then go learn C, nobody's stopping you. From Vern.Muhr at gmail.com Mon Jul 28 18:58:38 2008 From: Vern.Muhr at gmail.com (VernM) Date: Mon, 28 Jul 2008 15:58:38 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <8287c9c5-d6bb-4f67-9dec-00bc59bcb546@q28g2000prh.googlegroups.com> On Jul 20, 3:50?pm, giveitawhril2... at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. Thank you giveitawhril2...!! I haven't had so much fun reading a thead in years. Hilarious!!!! From steve at holdenweb.com Tue Jul 29 11:32:26 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 29 Jul 2008 11:32:26 -0400 Subject: Public Pythn Classs, September 9, 2008 Message-ID: <488F380A.4070105@holdenweb.com> Holden Web is please to announce its third public "Introduction to Python" class, near Washington DC, from September 9-11. Further details are available from http://holdenweb.com/py/training/ We are also interested in adding to our course repertoire. If you have ideas for suitable one-day classes please visit http://holdenweb.blogspot.com/2008/07/one-day-python-classes.html and leave a comment on that page. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From ldo at geek-central.gen.new_zealand Mon Jul 28 02:55:56 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 28 Jul 2008 18:55:56 +1200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> <6385b0a8-f7f3-4dc3-91be-e6f158ffb439@a1g2000hsb.googlegroups.com> Message-ID: In message , s0suk3 at gmail.com wrote: > On Jul 27, 10:55 pm, Lawrence D'Oliveiro central.gen.new_zealand> wrote: >> In message >> <6385b0a8-f7f3-4dc3-91be-e6f158ffb... at a1g2000hsb.googlegroups.com>, >> >> >> >> s0s... at gmail.com wrote: >> > On Jul 26, 6:47 pm, Lawrence D'Oliveiro > > central.gen.new_zealand> wrote: >> >> In message >> >> <024ace13-f72f-4093-bcc9-f8a339c32... at v1g2000pra.googlegroups.com>, >> >> >> s0s... at gmail.com wrote: >> >> > On Jul 24, 5:01 am, Lawrence D'Oliveiro > >> > central.gen.new_zealand> wrote: >> >> >> >> In message >> >> >> <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, >> >> >> Jordan wrote: >> >> >> >> > Except when it comes to Classes. I added some classes to code >> >> >> > that had previously just been functions, and you know what I did >> >> >> > - or rather, forgot to do? Put in the 'self'. In front of some of >> >> >> > the variable accesses, but more noticably, at the start of *every >> >> >> > single method argument list.* >> >> >> >> The reason is quite simple. Python is not truly an >> >> >> "object-oriented" language. It's sufficiently close to fool those >> >> >> accustomed to OO ways of doing things, but it doesn't force you to >> >> >> do things that way. You still have the choice. An implicit "self" >> >> >> would take away that choice. >> >> >> > By that logic, C++ is not OO. >> >> >> Yes it is, because it has "this". >> >> > You mean the keyword "this"? It's just a feature. How does that make a >> > difference on being or not being OO? >> >> Because it was one of the things the OP was complaining about (see >> above). > > Wrong. Reread what the OP said. From crazychimp132 at gmail.com Mon Jul 14 19:24:27 2008 From: crazychimp132 at gmail.com (crazychimp132 at gmail.com) Date: Mon, 14 Jul 2008 16:24:27 -0700 (PDT) Subject: Method behavior for user-created class instances Message-ID: <42433fcd-fcdc-4f42-a427-c28241734b7c@z66g2000hsc.googlegroups.com> Greetings. I am looking for a way to achieve method behavior for a class I created. That is, it has a __call__ method, so can be called like a function. But I also want it to be treated as a method when it appears in a class body. Eg. class foo: def __call__(self, inst): pass class bar: meth = foo() such that bar().meth() will not raise an exception for too few arguments (because the inst argument in foo.__call__ is implicitly set to the bar instance). I know this has to do with writing the __get__ method of foo, but I am wondering if there is perhaps some class I can just inherit from to get the proper __get__, which behaves identically to that of regular Python functions. The need for this arises out of the implementation of a function decorator as a class. Thanks. From larry.bates at websafe.com` Mon Jul 14 00:29:41 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 13 Jul 2008 23:29:41 -0500 Subject: About wmi In-Reply-To: <51cb0fe0-58f2-4f56-a59e-59986177f3d5@c65g2000hsa.googlegroups.com> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <51cb0fe0-58f2-4f56-a59e-59986177f3d5@c65g2000hsa.googlegroups.com> Message-ID: patrol wrote: > On 7?13?, ??10?26?, Larry Bates wrote: >> patrol wrote: >>> I want to prevent some process from running. The code is in the >>> following. I encounter some unexpected troubles. >>> Probelm1: This program cannot terminate "scrcons.exe" and >>> "FNPLicensingService.exe",which are system processes. >>> Problem2:After a while, this program will abort by error >>> File "C:\Python25\lib\wmi.py", line 397, in __call__ >>> handle_com_error (error_info) >>> File "C:\Python25\lib\wmi.py", line 190, in handle_com_error raise >>> x_wmi, "\n".join (exception_string) >>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position >>> 14: ordinal not in range(128) >>> ---------------------------------------------------- >>> code----------------------------------------------------------------------------------- >>> # -*- coding:utf-8 -*- >>> import pythoncom >>> import wmi >>> import threading >>> import time >>> from xml.dom.minidom import parse, parseString >>> class Info (threading.Thread): >>> def __init__ (self): >>> threading.Thread.__init__ (self) >>> def run (self): >>> print 'In Another Thread...' >>> pythoncom.CoInitialize () >>> dom1 = parse('processTerminateList.xml') >>> config_element = dom1.getElementsByTagName("processTerminateList") >>> [0] >>> servers = config_element.getElementsByTagName("processName") >>> try: >>> c = wmi.WMI () >>> for process in c.Win32_Process (): >>> for server in servers: >>> if process.name == getText(server.childNodes): >>> process.Terminate() >>> print process.name >>> process_watcher = c.Win32_Process.watch_for("creation") >>> while True: >>> new_process = process_watcher() >>> name = new_process.Caption >>> print name >>> for server in servers: >>> if name == getText(server.childNodes): >>> new_process.Terminate() >>> finally: >>> pythoncom.CoUninitialize () >>> def getText(nodelist): >>> rc = "" >>> for node in nodelist: >>> if node.nodeType == node.TEXT_NODE: >>> rc = rc + node.data >>> return rc >>> if __name__ == '__main__': >>> Info().start() >>> ------------------------------------------------------ >>> processTerminateList.xml------------------------------------------------------------------------ >>> >>> >>> scrcons.exe >>> TXPlatform.exe >>> mdm.exe >>> FNPLicensingService.exe >>> notepad.exe >>> uedit32.exe >>> >> You should probably post this to comp.python.windows. Tim Golden (author of WMI >> interface) monitors that list religously (thanks Tim). >> >> -Larry- ??????? - >> >> - ??????? - > > I cannot find comp.python.windows.What's the URL? http://news.gmane.org/gmane.comp.python.windows/cutoff=7565 -Larry From malaclypse2 at gmail.com Wed Jul 9 15:33:50 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 9 Jul 2008 15:33:50 -0400 Subject: formatting list -> comma separated In-Reply-To: <48750e4f$0$15106$e4fe514c@dreader27.news.xs4all.nl> References: <48750e4f$0$15106$e4fe514c@dreader27.news.xs4all.nl> Message-ID: <16651e80807091233p3d297d80p93a1e45d17fb23e9@mail.gmail.com> On Wed, Jul 9, 2008 at 3:23 PM, Robert wrote: > given d: > d = ["soep", "reeds", "ook"] > > I want it to print like > soep, reeds, ook use the join() method of strings, like this: >>> d = ["soep", "reeds", "ook"] >>> ', '.join(d) 'soep, reeds, ook' >>> d = [] >>> ', '.join(d) '' >>> -- Jerry From lanny at freshells.ch Thu Jul 24 11:24:38 2008 From: lanny at freshells.ch (Lanny) Date: Thu, 24 Jul 2008 08:24:38 -0700 Subject: Raw Strings (I Think) References: Message-ID: > No, it doesn't. Instead of guessing what the cause might be, please show > us your code and show us the error message you're getting, so that we can > determine what the cause really is. Ok, sorry. Heres my code: import glob import random import os songs = glob.glob('C:\###\###\###\*.mp3') pick = random.choice(songs) os.system(pick) And yes, I know there are better ways of randomly selecting a .mp3 file to play but I don't care. -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- From deets at nospam.web.de Mon Jul 7 07:53:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 07 Jul 2008 13:53:31 +0200 Subject: Is there a good way to implement file updating? such as lock, update, reload... References: <2ebcf7f9-a8d9-403f-a05a-f26a9ca420b0@x41g2000hsb.googlegroups.com> Message-ID: <6deef6F271g5U1@mid.uni-berlin.de> Evan wrote: > Hello - > > My script use a DB file which is written by XML, and the user load > this DB file (XML tree in memory), and then do some updating about > this tree, such as delete element, generate new element or move > element. > > The thing is, my script is a cmd based program (based on module > "cmd"), and there are many users would use this script at same time, > in a shell style prompt (module "cmd"), so I want to implement a > updating after a user update the XML tree, it such as a "signal > console", so that all the user can keep same DB, or other user can > see update a few seconds later. > > What I did is, create a new file calling "db_change", and put a number > "1" in file, and then update the real "DB" file (by change uid to lock > file), other user to check this file and then re-load XML file, but I > do not think it is a good idea, the performance is not good. > > I would like to know if you could help on this matter, I hope I can > get inspiration/example from you guys. Start using a proper database. And get rid of the XML. If you need it for output/exchange purposes, generate it from the DB. Diez From kalaiarasanq at gmail.com Wed Jul 2 11:36:33 2008 From: kalaiarasanq at gmail.com (kali) Date: Wed, 2 Jul 2008 08:36:33 -0700 (PDT) Subject: Woman on Top Sex Position - The Sexiest Mattress Move ... Message-ID: <940ba25c-297e-4e68-8fc5-fee646b708b4@s33g2000pri.googlegroups.com> Woman on Top Sex Position - The Sexiest Mattress Move ... Top 10 Sex Stories of 2006 For your end-of-the-year sexual entertainment, my picks for the Top 10 Sex Stories of 2006:. 10. The Larry Wachowski Story ... click him in poen viset. ************************************* htt://mountanbikes.blogspot.com/ ************************************* From hubaghdadi at gmail.com Mon Jul 28 10:03:48 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Mon, 28 Jul 2008 07:03:48 -0700 (PDT) Subject: Module clarification References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> <896c547e-9fa1-4f84-8c9b-53a96e70246c@y21g2000hsf.googlegroups.com> <00c033b9-1b5a-4165-abec-4ff6119298a5@z66g2000hsc.googlegroups.com> Message-ID: On Jul 28, 8:11 am, Duncan Booth wrote: > Hussein B wrote: > > If I have a couple of modules, is there a way to package them? or > > there is no such a thing in Python? > > It sounds rather as though you haven't yet gone through the Python > tutorial. You really should read it, even if you just skim through it to > see what topics are covered. The tutorial explains both modules and > packages:http://docs.python.org/tut/node8.html > > What it doesn't cover is that you can import modules or packages directly > from a zip file. > > Then read about eggs. > > -- > Duncan Boothhttp://kupuguy.blogspot.com I'm reading "Learning Python, 3rd Edition" What do you think about it? From nodrogbrown at gmail.com Fri Jul 4 04:15:30 2008 From: nodrogbrown at gmail.com (gordon) Date: Fri, 4 Jul 2008 01:15:30 -0700 (PDT) Subject: compatible image type Message-ID: hi in my application a file selection by user returns a pathname string like F:/images/png/my.png or F:/docs/text/somedoc.txt ....etc. I can get the extension using extn=string.split(os.path.basename(pathname),'.' )[1] then later on i want to create a Photoimage using ImageTk.PhotoImage(file=pathname) and display it on a canvas. the extn can be anything ..even zip or bat ,doc whatever depending on user selection...I want to put someway to raise an error message to the user if he selects a file with extension not of a compatible image type for PhotoImage.How should i do this? should i check 'extn' to a list of compatible image type extensions(something like [''jpg','jpeg','png','gif'...] ) or is there a better way? gordon From comp.ogz at gmail.com Tue Jul 8 01:10:28 2008 From: comp.ogz at gmail.com (Oguz Yarimtepe) Date: Tue, 8 Jul 2008 08:10:28 +0300 Subject: Tk overrideredirect problem Message-ID: <20831c740807072210m3c3e66c0j42f7e9bbd87f70fc@mail.gmail.com> Hi, At my GUI application i am catching a key press action. The code is working if i don't enable the overrideredirect. When i comment out the overriderect part i can see the picture but i am not able to catch the key presses. It seems like the GUI is stucked. But i want to have windowless appereance that is just the picture itself. Also a working application that will catch my key presses. So how can i fix it? Here is the code part related with my question: from Tkinter import * from Xlib import * import Image #PIL import ImageTk #PIL self.root = Tk() #self.root.overrideredirect(1) self.root.title("Status") self.root.bind('', self.action) dsp = display.Display() self.screen = dsp.screen().root self.screen.grab_key(self.actionkey, X.AnyModifier, 1,X.GrabModeAsync, X.GrabModeAsync) # we tell the X server we want to catch keyPress event self.screen.change_attributes(event_mask = X.KeyPressMask) def action(self,event): #print event.keycode if event.keycode == self.actionkey: self.showImage() def showImage(self,imageName="w_on_b_on.jpg"): print imageName im = Image.open(imageName) xlocation = 440 ylocation = 640 width = im.size[0]+20 height = im.size[1]+20 newgeometry = str(width)+"x"+str(height)+"+"+str(xlocation)+"+"+str(ylocation) self.root.geometry(newgeometry) self.root.protocol('WM_DELETE_WINDOW', self.doExit) # add 20 to account for border defined in create_image self.canvas = Canvas(self.root, height=im.size[1]+20, width=im.size[0]+20) self.canvas.pack(side=LEFT,fill=BOTH,expand=1) photo = ImageTk.PhotoImage(im) item = self.canvas.create_image(10,10,anchor=NW, image=photo) self.counter += 1 #self.canvas.update() mainloop() I didn't check the code below, the whole working one is here: http://rafb.net/p/SvqqjH64.html I pasted it to give an idea. -- O?uz Yar?mtepe From __peter__ at web.de Sat Jul 5 02:06:26 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 05 Jul 2008 08:06:26 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: Filipe Fernandes wrote: > but why would you say this particular > regex isn't common enough in real code? As Carl says, it's not just the regex, it's the the combination with a long line that exposes the re library's weakness. Peter From animator333 at gmail.com Fri Jul 18 06:56:11 2008 From: animator333 at gmail.com (King) Date: Fri, 18 Jul 2008 03:56:11 -0700 (PDT) Subject: sub typing built in type with common attributes. Am I right? References: <4d9c4b74-9c28-4b98-afe7-9eb774655c3a@v21g2000pro.googlegroups.com> <98c3de7d-f167-48f9-9736-b09938d96b92@f40g2000pri.googlegroups.com> Message-ID: <6849e509-9132-4628-8cbb-af818e5b6762@q28g2000prh.googlegroups.com> Thanks Michaud, You have actually solved an another problem by 'make_subtype_with_attr' function. What actually I am trying to do here is to create custom types using built in types to use in my application. For example , float2, float3, color, vector, point, normal, matrix etc. The reason being creating as individual subtypes is because each subtypes has it's own set of functions as well as common functions and attributes defined in 'Attribute' class. Although I won't be doing any math using subtypes like multiply a color by another color or add a float and a color. One of the important function that every subtype has is to print itself in a special format. For 'color' it would be : 'type' + 'name' + ' = color('+color[0]+', '+color[2]+', '+color[2]+');' Result: color myColor = color(0.5, 0.1, 1.0); I hope this will make things more clearer. If you do have any suggestions then please send it across. Prashant From ldo at geek-central.gen.new_zealand Fri Jul 25 00:32:59 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 25 Jul 2008 16:32:59 +1200 Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: In message , Matimus wrote: > On Jul 24, 2:54?am, Lawrence D'Oliveiro central.gen.new_zealand> wrote: >> In message >> , >> >> Matimus wrote: >> > That isn't the standard. With that setup tabs will show up as 4 >> > spaces, and still confuse you. >> >> Why should that be confusing? The most common tab-stop setting is 4 >> columns. > > A tab character is specified as 8 spaces. Specified by whom? The most common setting these days is 4 columns. From ptmcg at austin.rr.com Sun Jul 20 01:42:04 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 19 Jul 2008 22:42:04 -0700 (PDT) Subject: MethodChain References: <6eej10F6k7g3U2@mid.uni-berlin.de> <342b5431-5ead-4827-8bdd-ab2cd50c2acc@i76g2000hsf.googlegroups.com> <6efv5cF6uhc3U1@mid.uni-berlin.de> Message-ID: On Jul 20, 12:01?am, Marc 'BlackJack' Rintsch wrote: > The methods are a problem IMHO. ?You can't add an own method/function with > the name `fire()` or `toFunction()`. ?`MethodChain` has to know all > functions/methods in advance. ?You can add the methods of whole classes at > once and there are over 300 pre-added, this begs for name clashes. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch If you shift the syntax just a bit, instead of writing a.b.c, pass a, b, and c as the args to a MethodChain object. Here's a rough stab at the problem: class MethodChain(object): def __init__(self, *fns): self.fns = fns[:] def __call__(self,*args): if self.fns: for f in self.fns: args = (f(*args),) return args[0] def dncase(s): return s.lower() def upcase(s): return s.upper() def stripVowels(s): return "".join( c for c in s if c not in "aeiou" ) def selectItems(items,s): return "".join(c for i,c in enumerate(s) if i in items) from functools import partial chn = MethodChain( dncase, stripVowels, upcase, partial(selectItems,(0,2)) ) print chn("FoO Bar") -- Paul From alexnbryan at gmail.com Sat Jul 12 19:01:00 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sat, 12 Jul 2008 16:01:00 -0700 (PDT) Subject: like py2exe, but on a mac In-Reply-To: References: <18424336.post@talk.nabble.com> Message-ID: <18424499.post@talk.nabble.com> Python.Arno wrote: > > > On 13 jul 2008, at 00:39, Alexnb wrote: > >> >> Hi All >> >> I am wondering what I can do to turn a python app (.py) into a mac OSX >> applicaiton (.app). Just like py2exe does. > > i use these: > http://undefined.org/python/py2app.html > http://effbot.org/pyfaq/how-do-i-create-a-pyc-file.htm > >> But I am also wondering since in >> your applications folder on macs it usually doesn't have an actual >> folder >> for each app. Rather an icon. so for firefox, you just see the icon. >> Unlike >> windows where you have a folder with everything, and the actual >> program is >> in it. where is all the application info stored? just in the .app? > > apps on OSX are also folder, yet with the reserved .app extension > the OS then presents this as an app (right click on an app and choose > 'Show package content') > > py2app creates all that for you > > >> Finally >> whether or not there is an app like py2exe for mac, is there a way >> to skip >> the middle man and turn it straight into a .dmg with the app inside? >> -- > > a dmg is a disk image, similar to iso on windows > you can create an empty one with Disk Utility then drop everything in > it's NOT an installer > >> > cheers > Arno > -- > http://mail.python.org/mailman/listinfo/python-list > > Okay, well thank you very much for your help you answered all my questions :) -- View this message in context: http://www.nabble.com/like-py2exe%2C-but-on-a-mac-tp18424336p18424499.html Sent from the Python - python-list mailing list archive at Nabble.com. From moijes12 at gmail.com Mon Jul 14 00:03:08 2008 From: moijes12 at gmail.com (moijes12) Date: Sun, 13 Jul 2008 21:03:08 -0700 (PDT) Subject: importing from .pyd Message-ID: <3d66daeb-d45a-46be-bd4d-34a2225683d1@2g2000hsn.googlegroups.com> hi there is a .pyd file present in the same folder as the script abc.py by the name foo.pyd .I don't have foo.py .In the script abc.py I try import foo Error i get is ImportError: DLL load failed: The specified module could not be found. I have tried placing .pyd under C:\python25\DLLs but it didn't work.I have also given the path for foo.pyd in PYTHONPATH.but i still recieve the same error. Please suggest a solution moijes12 From kyosohma at gmail.com Thu Jul 3 14:37:52 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 3 Jul 2008 11:37:52 -0700 (PDT) Subject: manipulating movie files with Python References: Message-ID: <61fdcc89-8c1b-4446-8c1b-3a68f1a86689@2g2000hsn.googlegroups.com> On Jul 3, 12:15?pm, Tim Grove wrote: > I would like to write a python script which could take a movie file name > (avi, mov, mpg) along with a start and stop time as parameters, and > return to me a ?new movie file just containing that section of the > original which I'm interested in. Is there a Python library which could > already perform such magic? Thanks for any suggestions. > > Best regards, > Tim You might check these out: http://pymedia.org/ http://www.unixuser.org/~euske/vnc2swf/pyvnc2swf.html Mike From cokofreedom at gmail.com Fri Jul 25 04:38:30 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Fri, 25 Jul 2008 01:38:30 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> Message-ID: <5d3729f0-6e5d-4e3f-b4ed-e25f8ebc655f@q5g2000prf.googlegroups.com> > > By that logic, C++ is not OO. By that logic, Ruby is not OO. By that > logic, I know of only one OO language: Java :) > > The fact that a language doesn't force you to do object-oriented > programming doesn't mean that it's not object-oriented. In other > words, your words are nonsense. > No, what it means is that it might support OO but doesn't have to, it isn't the only way to code. Supporting and Being OO are very different. From akineko at gmail.com Sat Jul 5 08:11:48 2008 From: akineko at gmail.com (akineko) Date: Sat, 5 Jul 2008 05:11:48 -0700 (PDT) Subject: Python XML-RPC Server with clientside Javascript References: Message-ID: <7d589fd8-2877-4427-84a6-d5e999172305@d77g2000hsb.googlegroups.com> Hello Paul, Thank you very much for your prompt and clear answer. I didn't know the "same origin" javascript security policy (as I'm not familiar with javascript). After reading the description of the "same origin" javascript policy, I think you are absolutely correct. The security policy does make sense. However, if that is the case, it seems I have only two options to make my project work: (1) Place my XML-CGI services under a web server so that both HTML page and RPC services are coming from the same origin (2) Expand Python DocXMLRPCServer, which renders a HTML page, to implement my own HTML page from it I wanted to run the program as a standalone one (no external web server required). Therefore, (2) seems the only option I have to make it work. Anyway, thank you for solving my days-long question. Best regards, Aki Niimura On Jul 5, 3:39 am, paul wrote: > > I'd think this has nothing to do with CGI vs. "free-standing", the > client couldn't tell the difference anyway. > It looks like you're running in the "same origin" javascript security > restriction enforced by the browser. That is, the origin of your > javascript is file://... and you're trying to accesshttp://localhost:8765. This is not allowed. > > hth > Paul From grante at visi.com Tue Jul 15 15:05:11 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 15 Jul 2008 14:05:11 -0500 Subject: Testing for Internet Connection References: <18460572.post@talk.nabble.com> <1216113021.24038.0@proxy02.news.clara.net> Message-ID: On 2008-07-15, norseman wrote: > Process: > copy/paste into afile > slide lines left to create proper indent values > save > python afile > > I get same as Grant > > > If one does a copy/paste into interactive Python, it does fail. > (Lots of indent error messages. After all, it is Python :) I'm always a bit conflicted about how to post code snippets. IMO, the posting is a lot more readable if the code is indented to offset it from the prose, but it does make more work for anybody who wants to run the example. -- Grant Edwards grante Yow! Did I SELL OUT yet?? at visi.com From bignose+hates-spam at benfinney.id.au Wed Jul 16 04:47:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jul 2008 18:47:38 +1000 Subject: How can i use a variable without define it ? References: Message-ID: <87k5fm2p1x.fsf@benfinney.id.au> zhw writes: > How can i use a variable without define it ? What do you mean by "use"? That's so vague I can think of many possible interpretations. What do you mean by "variable"? That term carries a lot of baggage that doesn't apply in Python. Can you give a small, complete example that demonstrates the issue you're trying to solve? -- \ ?The face of a child can say it all, especially the mouth part | `\ of the face.? ?Jack Handey | _o__) | Ben Finney From stanc at al.com.au Mon Jul 7 00:12:48 2008 From: stanc at al.com.au (Astan Chee) Date: Mon, 07 Jul 2008 14:12:48 +1000 Subject: VNC capture in python Message-ID: <487197C0.1090006@al.com.au> Hi, I was wondering if I can do a capture of a VNC screen in python. Kinda like this http://search.cpan.org/~lbrocard/Net-VNC-0.35/lib/Net/VNC.pm but without opening a VNC window or doing a screen capture. Thanks for any suggestions -- "Formulations of number theory: Complete, Consistent, Non-trivial. Choose two." Animal Logic http://www.animallogic.com Please think of the environment before printing this email. This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. From pavlovevidence at gmail.com Thu Jul 31 23:44:20 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 31 Jul 2008 20:44:20 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> Message-ID: <5a0b303a-8324-4eeb-a975-397371bf2875@b1g2000hsg.googlegroups.com> On Jul 31, 12:13 am, Ethan Furman wrote: > Carl Banks wrote: > > So I stand by the point I was trying to make: for your average day-to- > > day programming, the main benefit of "if x" is to save keystrokes. It > > doesn't help your code become more polymophic in practice. A little > > more polymorphic, yes. A lot, no. > > Hmmm... well, I see your point. Unfortunately, even though it feels > incorrect to me, I do not (yet) have the breadth and depth of Python > experience to come up with an example that would display such exquisite > polymorphism. It also seems to me that such an example would be > non-trivial in nature. Wrong on both counts. Let me give you a hint. Take integers and lists. Count how many methods the two types have in common. By my reckoning, they are: __add__, __iadd__, __mul__, _imul__, __str__, __repr__, and __nonzero__. Also there are __getattribute__ and __setattr__, but lists and ints share no common attributes. I don't think ints have any at all aside from the special methods. What this means is: any code that can work for both ints and lists must use only these methods (this is not quite correct, but mostly is). That eliminates probably 99.9% of code right off the bat. Then you have to consider that some code that does use only these attributes does something useful only for either ints or lists, not both. Take this simple example: def foil(a,b,c,d): return a*b + a*d + b*c + b*d This code works if a and c are both ints, or are both lists (while b and d would have to be ints). It does something useful for ints and other numeric types, but does it do anything useful for lists? Third, there are cases where you have code that works for both ints and lists, that does do something useful for both, but it makes no sense to apply "if x" to it. def print_if_true(x): if x: print x This little piece of code might actually come in handy here and there, but would it end up being used for numeric types a whole lot? It seems like if you have an empty list you might reasonably want to print nothing at all, but when you have a zero integer you usually want to print the zero. (However, you might reasonably want to print some object unless it's None. You could then use this one function to handle that case as well as the case with empty lists, instead of defining two functions, like so: print_if_not_empty(x): if len(x)!=0: print x print_if_not_None(x): if x is not None: print x But wait! What if you had a value that could be either an integer or None? You can't use the "if x" variant because x could be False. So you'd have to define the "if x is not None" variant anyway. I might use the "if x" variant in throwaway scripts, but for anything production I would prefer the explicit variants, partially because, as shown above, even when "if x" does rear it's polymoprhic head, it doesn't necessarily buy you much. Nevertheless, I think this is probably the best example of the enhanced polymorphism of "if x" yet. I'm kind of surprised no one came up with it.) In general, the ability to take advantage of "if x" polymorphism across numeric, container, and other types depends on the something/ nothing dichotomy to be applicable. Something versus nothing is a useless concept most of the time, but occasionally finds use in human interaction cases such as printing. So there you have it. This is why I didn't expect anyone to come up with a good example: you just don't have a lot to work with. Carl Banks From tjreedy at udel.edu Tue Jul 29 15:11:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 15:11:53 -0400 Subject: block/lambda In-Reply-To: References: <0406eb4f-8dec-4ce2-b506-8e597de2958d@56g2000hsm.googlegroups.com> Message-ID: iu2 wrote: > On Jul 29, 9:36 am, Duncan Booth wrote: >> Your example becomes: >> >>>>> def dotimes(n, callable): >> for i in range(n): callable(i) >> >>>>> def block(i): >> for j in range(i): >> print j, >> print >> >>>>> dotimes(5, block) >> 0 >> 0 1 >> 0 1 2 >> 0 1 2 3 >> >> The only thing you asked for that this doesn't do is make 'block' >> anonymous, but actually that is a good thing. > > Ok, I've got 2 questions about it: > > 1. Can you please explain why it is a good thing? All functions defined with lambda expressions get the pseudoname ''. All functions defined with def get the name you give it, which is typically unique within some scope. The representation of a function, whether intentionally printed or printed as part of a traceback, is more meaningful with a specific name than a general name. > 2. Will it be possible in Python 3.0 to do the following: > >>>> def dotimes(n, callable): > for i in range(n): callable() > >>>> def block(): > nonlocal i > for j in range(i): > print j, > print If you indent block so it is a nested function, yes. But the nonlocal declaration is not needed unless you rebind 'i' from within the nested function, which block does not do. tjr From bdesth.quelquechose at free.quelquepart.fr Mon Jul 28 07:17:32 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Jul 2008 13:17:32 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: <488dc6c2$0$24366$426a34cc@news.free.fr> Russ P. a ?crit : > On Jul 27, 12:39 pm, Bruno Desthuilliers > wrote: >> Derek Martin a ?crit : >> >> >> >>> On Sun, Jul 27, 2008 at 08:19:17AM +0000, Steven D'Aprano wrote: >>>>> You take the name down to a single letter. As I suggested in an earlier >>>>> post on this thread, why not take it down to zero letters? >>>> The question isn't "why not", but "why". The status quo works well as it >>>> is, even if it isn't perfect. Prove that implicit self is a good idea -- >>>> or at least prove that it is an idea worth considering. >>> Come on, this sounds like a schoolyard argument. This comes down to a >>> matter of style, and as such, is impossible to prove. It's largely a >>> question of individual preference. >>> That said, the argument in favor is rather simple: >>> 1. This is an extremely common idiom in Python >>> 2. It is completely unnecessary, and the language does not suffer for >>> making it implicit >>> 3. Making it implicit reduces typing, reduces opportunities for >>> mistakes, and arguably increases consistency. >> "arguably", indeed, cf below. >> >>> As for the latter part of #3, self (or some other variable) is >>> required in the parameter list of object methods, >> It's actually the parameter list of the *function* that is used as the >> implementation of a method. Not quite the same thing. And then, >> consistency mandates that the target object of the method is part of the >> parameter list of the *function*, since that's how you make objects >> availables to a function. >> >>> however when the >>> method is *called*, it is omitted. >> Certainly not. You need to lookup the corresponding attribute *on a >> given object* to get the method. Whether you write >> >> some_object.some_method() >> >> or >> >> some_function(some_object) >> >> you still need to explicitely mention some_object. >> >>> It is implied, supplied by Python. >> Neither. The target object is passed to the function by the method >> object, which is itself returned by the __get__ method of function >> objects, which is one possible application of the more general >> descriptor protocol (the same protocol that is used for computed >> attributes). IOW, there's nothing specific to 'methods' here, just the >> use of two general features (functions and the descriptor protocol). >> FWIW, you can write your own callable, and write it so it behave just >> like a function here: >> >> import types >> >> class MyCallable(object): >> def __call__(self, obj): >> print "calling %s with %s" % (self, obj) >> def __get__(self, instance, cls): >> return types.MethodType(self.__call__, instance, cls) >> >> class Foo(object): >> bar = MyCallable() >> >> print Foo.bar >> f = Foo() >> f.bar() >> >>> Thus when an object method is called, it must be called with one fewer >>> arguments than those which are defined. This can be confusing, >>> especially to new programmers. >> This is confusing as long as you insist on saying that what you >> "def"ined is a method - which is not the case. >> >>> It can also be argued that it makes the code less ugly, though again, >>> that's a matter of preference. >>>> It's not enough to show that a change "isn't bad" -- you have to show >>>> that it is actively good. >>> But he did... he pointed out that *it saves work*, without actually >>> being bad. Benefit, without drawback. Sounds good to me! >>>> "Don't need to look at the method signature" is not an argument in favour >>>> of implicit self. >>> Yes, actually, it is. >> It isn't, since there's no "method signature" to look at !-) >> >>> If there is a well-defined feature of Python >>> which provides access to the object within itself, >> The point is that you don't get access to the object "within itself". >> You get access to an object *within a function*. >> >> The fact that a function is defined within a class statement doesn't >> imply any "magic", it just creates a function object, bind it to a name, >> and make that object an attribute of the class. You have the very same >> result by defining the function outside the class statement and binding >> it within the class statement, by defining the function outside the >> class and binding it to the class outside the class statement, by >> binding the name to a lambda within the class statement etc... >> >>> then the >>> opportunities for mistakes when someone decides to use something else >>> are lessened. >>>> You don't need to look at the method signature when you're using an >>>> explicit self either. >>> That isn't necessarily true. If you're using someone else's code, and >>> they didn't use "self" -- or worse yet, if they chose this variable's >>> name randomly throughout their classes -- then you may well need to >>> look back to see what was used. >>> It's bad programming, but the world is full of bad programmers, and we >>> don't always have the choice not to use their code. Isn't one of >>> Python's goals to minimize opportunities for bad programming? >> Nope. That's Java's goal. Python's goals are to maximize opportunities >> for good programming, which is quite different. >> >>> Providing a keyword equivalent to self and removing the need to name >>> it in object methods is one way to do that. >> It's also a way to make Python more complicated than it needs to be. At >> least with the current state, you define your functions the same way >> regardless of how they are defined, and the implementation is >> (relatively) easy to explain. Special-casing functions definition that >> happens within a class statement would only introduce a special case. >> Then you'd have to explain why you need to specify the target object in >> the function's parameters when the function is defined outside the class >> but not when it's defined within the class. >> >> IOW : there's one arguably good reason to drop the target object from >> functions used as methods implementation, which is to make Python looks >> more like Java, and there's at least two good reason to keep it the way >> it is, which are simplicity (no special case) and consistency (no >> special case). >> >> Anyway, the BDFL has the final word, and it looks like he's not going to >> change anything here - but anyone is free to propose a PEP, isn't it ? > > The issue here has nothing to do with the inner workings of the Python > interpreter. Oh yes, really ??? > The issue is whether an arbitrary name such as "self" > needs to be supplied by the programmer. > > Neither I nor the person to whom you replied to here (as far as I can > tell) is suggesting that Python adopt the syntax of Java or C++, in > which member data or functions can be accessed the same as local > variables. Any suggestion otherwise is a red herring. I didn't talk about the implicit self/this reference in methods, but about java/C++/PHP/etc method signatures vs python's *functions* signature. > All I am suggesting is that the programmer have the option of > replacing "self.member" with simply ".member", since the word "self" > is arbitrary and unnecessary. It is arbitrary, indeed. And FWIW, you can use any other (legal) arbitrary identifier you like. But if you still assert it is unnecessary, then either you didn't read the above explanation of how and why the whole thing works in Python, or you didn't understand it. > Otherwise, everything would work > *EXACTLY* the same as it does now. This would be a shallow syntactical > change with no effect on the inner workings of Python, but it could > significantly unclutter code in many instances. > > The fact that you seem to think it would change the inner functioning > of Python just shows that you don't understand the proposal. The fact that you seem to think it would *not* change the inner working of Python just shows that you don't understand how Python works. We're not going very far with such arguments. Sorry but I perfectly understood the proposition, and explained why this would require changes to how Python actually implements methods. From omer at no-log.org Wed Jul 2 08:15:38 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Wed, 2 Jul 2008 14:15:38 +0200 Subject: How to modify the data in a binary file? In-Reply-To: <21563db10807020505p11561ce2k31d36f2731342c78@mail.gmail.com> References: <21563db10807020505p11561ce2k31d36f2731342c78@mail.gmail.com> Message-ID: <200807021415.38666.omer@no-log.org> Le Wednesday 02 July 2008 14:05:39 Jim Brown, vous avez ?crit?: > Hi all, I'm a Python newbie, so please pardon me if my question may look a > little silly. :) > > I want to modify a binary file p.data (which has some C-style "short" > integers -- 16-bit integers) in such a way: > The bit m and bit n of every "short int" si in the file are set to 1, and > the left bits in si are not affected. > > I.e, for the first short int in the file, I think the code would be: > > import os > f = os.open("/root/p.data", os.O_RDWR) > str = os.read(f, 2) > > #assume the short int in str is 0x0102, and I want to change it to 0x8182 > (changing bit7 and bit15 to 1). > #how to change the str into a short int variable si?? > ??? > > si = (si & ~0x8080) | 0x8080 > You can either do it by hand by splitting your string in chars and getting the bytes values with ord (described here: http://docs.python.org/lib/built-in-funcs.html) : byte0 = ord(s[0]) byte1 = ord(s[1]) si = (byte0 << 8) | byte1 # or maybe the inverse ? or use the struct module: http://docs.python.org/lib/module-struct.html -- C?dric Lucantis From norseman at hughes.net Wed Jul 23 21:40:53 2008 From: norseman at hughes.net (norseman) Date: Wed, 23 Jul 2008 18:40:53 -0700 Subject: Broken examples Message-ID: <4887DDA5.1010707@hughes.net> I'm only talking about IPC related. I have googled, yahooed, and so forth for several months now. ALL examples I've come across have failed including those pertinent in the Python doc area. Outline: cd somedir ls -1 *.xls >thislist #ls hyphen one python process.py (yes - ls can go here if wanted. easier to edit outside) open thislist loop until done start excel (or scalc) have it open file have it save file as a .csv (or .dbf) close excell (or scalc) Would seem to be a trivial exercise. Starting Excel or any other executable in system path works fine. popen3 opens whatever and reports no errors. r,w,and e all check as being created. r,w,e= os.popen3('ls -l') print r.read() # works as expected ALL attempts to send instructions to Excel or scalc FAIL COMPLETELY. Actually, any attempt to communicate with a 'Point'n'Click' program fails without errors being cited. They don't use redirectable command line interfaces (like piping between programs) do they? :) Trying to use the examples I have found that supposedly setup IPC's of one type or another have all failed with errors that point to things that make no sense in the first place. Before you post a code example or a link to one be kind enough to run it yourself first. You may get a surprise. The OOo examples do not work. Not even when switching my system to their version. One problem they have is asking a general user to change to places the user has no place being and then to work there without permissions. I guess somebody insists on doing all their work with root clearance down in the middle of the vendor's tree. I don't think that's a healthy way to do things, do you? In OOo in particular, using their version of VBA one can create the macro and even port it to python. If one found the correct Microsoft suite docs I suspect that same could be done there too. But that doesn't activate it from a python control. As for setting the macro to run at startup, well... maybe I had other uses in mind today???? Besides the moment I change it, coworker in other room is going to decide to... :) Let's stick to Microsoft Office and OpenSource products for now. My final goal will require specific conversations with a commercial vendor. I would like those spread sheets working though. Thanks Steve norseman at hughes.net From naude.jaco at gmail.com Wed Jul 23 05:58:42 2008 From: naude.jaco at gmail.com (Jaco Naude) Date: Wed, 23 Jul 2008 02:58:42 -0700 (PDT) Subject: Undefined calling conventions in Python.h References: Message-ID: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> On Jul 23, 9:59?am, Fredrik Lundh wrote: > Jaco Naude wrote: > > 1>application.obj : error LNK2031: unable to generate p/invoke for > > "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@$$J0YMXH at Z); > > calling convention missing in metadata > > 1>frmPythonInterface.obj : error LNK2031: unable to generate p/invoke > > for "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@$$J0YMXH at Z); > > calling convention missing in metadata > > > I'm probably missing something but I can't find any calling convention > > details in Python.h or the other headers included in this file. > > the precence of name mangling indicates that your compiler doesn't > understand that Python's a C library, and therefore uses C calling > conventions. ?have you managed to override the defaults in some odd > way? > > good point. I agree that the problem is probably due to name mangling. I'm not sure how its possible to tell the application that the DLL is a C dll? I've looked at the DLL using Dependency Walker and the functions in the DLL are clean (Thus no name mangling used). How do I tell Visual C++ that the DLL is a C dll? I thought it should be in Python.h but this line appears at the top of the file: /* Since this is a "meta-include" file, no #ifdef __cplusplus / extern "C" { */ Thanks for the help Jaco From dariusz.malec at gmail.com Thu Jul 24 15:26:42 2008 From: dariusz.malec at gmail.com (Dariusz Malec) Date: Thu, 24 Jul 2008 21:26:42 +0200 Subject: curses problem Message-ID: Hi, I'm very new to python and to curses but i guess someone can help me understand the problem: I wrote a little application (attachment) and the problem is when I resize the terminal the sub-window (log window) gets wrong size (rows) and when restoring previous terminal size the window row size does not change at all. Is there some kind of method to set directly window size in python curses? I'm using mvwin() method to set the windows new position but the problem is the size. -- Dariusz Malec http://www.kos.wsiz.rzeszow.pl JID:dmalec at jabber.kos.wsiz.rzeszow.pl From robin at alldunn.com Mon Jul 21 01:44:44 2008 From: robin at alldunn.com (Robin Dunn) Date: Sun, 20 Jul 2008 22:44:44 -0700 Subject: ANNOUNCE: wxPython 2.8.8.1 Message-ID: <4884224C.8080603@alldunn.com> Announcing ---------- The 2.8.8.1 release of wxPython is now available for download at http://wxpython.org/download.php. This is a minor bugfix release with several fixes for problems discovered in the 2.8.8.0 release. Source code is available, as well as binaries for Python 2.3, 2.4 and 2.5, for Windows and Mac, as well some packages for various Linux distributions. A summary of changes is listed below and also at http://wxpython.org/recentchanges.php. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit Microsoft Windows, most Linux or other Unix-like systems using GTK2, and Mac OS X 10.3+, in most cases the native widgets are used on each platform to provide a 100% native look and feel for the application. Changes in 2.8.8.1 ------------------ wx.richtext: Added wrappers for the RichTextPrinting and RichTextPrintout classes. Make it easier to replace the check box images used in the CheckListCtrlMixin class. Fixed bug in wx.ScrolledWindow when child focus events caused unneccessary or incorrect scrolling. Fixed a bug in wx.GridBagSizer where hidden items were not ignored in part of the layout algorithm. Several other bugs also fixed. Added builds for Ubuntu Hardy (8.04) -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From Bill at SynectixLtd.com Fri Jul 4 12:00:38 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Fri, 4 Jul 2008 17:00:38 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: "Bill Davy" wrote in message news:lPmdnYSbNrM6sPPVnZ2dneKdnZydnZ2d at bt.com... > "Tim Golden" wrote in message > news:mailman.61.1215177888.20628.python-list at python.org... >> Bill Davy wrote: >>> I am trying to edit Contacts in Outlook. This is so I can transfer >>> numbers from my address book which is an Excel spreadsheet to my mobile >>> phone. I came across the following snippet of code >> >> --- hey! that looks familiar :) >> >>> which enabled me to the contacts at least list. I had to root around to >>> discover CdoDefaultFolderContacts (though it was guessable; how could I >>> enumerate win32com.client.constants?). >> >> Well that bit's easy: win32com.client.constants is a small class with >> a __dicts__ attribute (note the "s") which is a list of dictionaries, one >> per generated library. So you can do something like this: >> >> >> import win32com.client >> >> outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") >> outlook_constants = win32com.client.constants.__dicts__[0] >> >> for k, v in outlook_constants.items (): >> print k, "=>", v >> >> >> >>> I now want to work through the Contacts in Outlook patching in data from >>> my spreadsheet, and also making new contacts where there is an entry in >>> my spreadsheet which has not gone into Contacts already. >> >> OK. >> >>> Where can I find the API? >> >> I recommend: >> >> http://msdn.microsoft.com/en-us/library/ms526861.aspx >> >> and >> >> http://www.outlookcode.com/article.aspx?id=20 >> >> and >> >> http://www.cdolive.com/cdo10.htm >> >> TJG > > > Brilliant. But I was a bit disappointed by one experiment. In MSDN I > found "Exploring the Outlook Object Model". That suggested: > Outlook | Tools | Macros | VB Editor | View | Object Browser > > There I found ContactItems and reckoned I was onto a winner, but found > that a "message" from the ContactFolder might have Subject but it did not > have a FullName. Also, if Python crashed, it left Outlook complaing that > someone was accessing it but had disappeaared so Outlook has to be > restarted each time. > > But you have suggested some more things to look at so thanks. I have had > a quick look but have not so far even found "Subject" as a member/property > of a message/contact. I shall keep looking. > > Rgds, > Bill > I kept looking and thought I was saved when I found Receipe 10.16 in the Python Cookbook but .... I changed the following: self.oOutlookApp = Dispatch("Outlook.Application") #self.oOutlookApp = gencache.EnsureDispatch("Outlook.Application") Because gencache failed and I hade run makepy last week (I only get one day a week to look at this). Then the following failed because (as I found) olFolderContacts is not in any of constants' dictionaries. ofContacts = onMAPI.GetDefaultFolder(constants.olFolderContacts) So, sadly, I shall have to put this aside for another week and get on with some work. Any thoughts would be gratefully accepted. TIA, Bill From andre at descombes.info Sat Jul 19 11:54:15 2008 From: andre at descombes.info (=?ISO-8859-1?Q?Andr=E9_Michel_Descombes?=) Date: Sat, 19 Jul 2008 17:54:15 +0200 Subject: scanf in python Message-ID: Hello, I often need to parse strings which contain a mix of characters, integers and floats, the C-language scanf function is very practical for this purpose. I've been looking for such a feature and I have been quite surprised to find that it has been discussed as far back as 2001 but never implemented. The recommended approach seems to be to use split and then atoi or atof or to use regex and then atoi and atof. Both approaches seem to be a lot less natural and much more cumbersome than scanf. If python already has a % string operator that behaves like printf, why not implement either a %% or << string operator to behave like scanf, use could be like the followng: a, b, c = "%d %f %5c" %% "1 2.0 abcde" or a, b, c = "%d %f %5c" << "1 2.0 abcde" %% is closer to the % operator << seems more intuitive either of this methods seems to me much simpler than: lst = "1 2;0 abcde".split() a = int(lst[0]) b = float(lst[1]) c = lst[2] or even worse when using regular expressions to parse such simple input. I like python because it is concise and easy to read and I really think it could use such an operator. I know this has been discussed before and many times, but all previous threads I found seem to be dead and I would like to invite further investigation of this topic. Best Regards, Andr? M. Descombes -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sat Jul 26 00:27:06 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 00:27:06 -0400 Subject: print doesn't respect file inheritance? In-Reply-To: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> References: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> Message-ID: bukzor wrote: > I was trying to change the behaviour of print (tee all output to a > temp file) by inheriting from file and overwriting sys.stdout, but it > looks like print uses C-level stuff to do its writes which bypasses > the python object/inhertiance system. It looks like I need to use > composition instead of inheritance, but thought this was strange > enough to note. > > $python -V > Python 2.5 > > """A short demo script""" > class notafile(file): > def __init__(self, *args, **kwargs): > readonly = ['closed', '__class__', 'encoding', 'mode', 'name', > 'newlines', 'softspace'] > file.__init__(self, *args, **kwargs) > for attr in dir(file): > if attr in readonly: continue > setattr(self, attr, None) Drop the __init__ and give notafile a .write method. Composition version inheritance is not the the real issue. >>> class nf(object): def write(s): print(s) print(s) >>> print >>nf(), 'testing' testing testing Now change nf.write to put the copy where you want it. tjr From basti.wiesner at gmx.net Thu Jul 24 09:11:49 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Thu, 24 Jul 2008 15:11:49 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> Message-ID: Jordan : >> Fortunately, Python isn't designed according to your ideas, and won't >> change, so consider your posting a waste of time. ?If feeling like >> bringing such old "issues" up again next time, spend your time learning >> another programming language, as you would obviously not get happy with >> Python anyway ... > > OK, if that's your response, that's sad. Of course, I try to learn new > languages all the time. Python is still IMO the best. If the attitude > in the community in response to feedback/criticism has gone from > "maybe you've got a point" to "your a lunatic, we'll never change", > well, only Python will suffer in the long term. I don't really mind, what you think about my response. Python will suffer from it as little as it will suffer from your complaints: These things will not change, whatever any of us says about them. So this discussion unlikely to produce any new insight, especially because this as been discussed over and over again in the past, without any effect on Python. Let's just drop this, and if you want to complain next time, just complain about something, that is really worth being complained about, like for instance old and outdated modules in the standard library, or real showstoppers in Python (e.g. the GIL). -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From alia_khouri at yahoo.com Wed Jul 16 01:34:42 2008 From: alia_khouri at yahoo.com (Alia Khouri) Date: Tue, 15 Jul 2008 22:34:42 -0700 (PDT) Subject: snippet to update local (bazaar, mercurial, svn) versioned source Message-ID: Here's a very simple snippet I use to automatically keep my versioned sources fresh.. Posted here in case it may be of use to anybody... #!/usr/local/bin/python import os, sys src = '/Users/ak/Code/src' # utility functions join, isdir, listdir = os.path.join, os.path.isdir def run(cmd): print cmd os.system(cmd) ops = { '.bzr': ['bzr pull', 'bzr update'], '.hg': ['hg pull', 'hg update'], '.svn': ['svn update'] } for folder in os.listdir(src): target = os.path.join(src,folder) if os.path.isdir(target): internal = os.listdir(target) for f in internal: if f in ops: print os.chdir(target) cmds = ops[f] print print target, '-->', for cmd in cmds: run(cmd) From sjmachin at lexicon.net Thu Jul 24 07:12:18 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 24 Jul 2008 04:12:18 -0700 (PDT) Subject: Requires a character ... !! References: Message-ID: On Jul 24, 7:23 pm, Ulrich Eckhardt wrote: > karthikbalaguru wrote: > > [root at localhost hello]# Analyzer hello_input > > ^^^^^^^^^^^^^^ > This is often a bad idea. Anyhow, that has nothing to do with Python. > > > Loading debug info: hello_input > > Traceback (most recent call last): > > File "/usr/local/SDK/host/bin/Analyzer", line 694, in ? > > app.dbg.readObjectInfo(elf) > > File "/usr/local/SDK/host/bin/debugprocessor.py", line 427, in > > readObjectInfo > > self.privateProcessorDwarfTree.readProcessorDwarfTree(filename) > > File "/usr/local/SDK/bin/debugprocessor.py", line 314, in > > readDwarfTree > > if "DW_OP_reg" in value: > > TypeError: 'in ' requires character as left operand > > > Is this related with the version conflicts ? > > Which version conflict? Sorry, but my crystal ball is getting a new polish > today, so I can't see the actual code that causes the error. I suggest that > you reduce your code to the smallest possible piece of code that still > shows the error and post it here, otherwise nobody will be able to help > you. You don't need a crystal ball; you just need to have been reading this group/list for the last day or so --- the OP is trying to use Python 2.2 on some *.py that are obviously written for a later version, refuses to contemplate upgrading, and starts a new thread every time he gets a syntax error. From callie.m.bradley at gmail.com Thu Jul 3 14:45:30 2008 From: callie.m.bradley at gmail.com (Callie Bertsche) Date: Thu, 3 Jul 2008 11:45:30 -0700 (PDT) Subject: Write a file - beginner's question References: <486cefb7$0$6040$426a74cc@news.free.fr> Message-ID: <8d278055-29be-46f1-8a6b-044838bd4b00@p25g2000pri.googlegroups.com> I have a closely related note. How do I write to a relative path with python? Example, source = open('/../../directory/subdirectory/file.extension') What am I missing? From gcmartijn at gmail.com Sat Jul 26 08:01:29 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Sat, 26 Jul 2008 05:01:29 -0700 (PDT) Subject: re.findall(a patern,'function(dsf sdf sdf)') References: <8fc6d72a-cfc5-4e9d-af56-a009a464c6bb@27g2000hsf.googlegroups.com> Message-ID: <2dd5c418-f532-4f50-923e-057a10f01fdd@79g2000hsk.googlegroups.com> > In short, the regular expression you used doesn't seem to be an effort > to solve the problem. In other words, you haven't read the regular > expression docs:http://docs.python.org/lib/module-re.html. In other > words, it's useless to talk with you until then. > Its a combination - I don't understand english very good (yet) - For me its hard to learn the re , I will try to search again at google for examples and do some copy past things. From __peter__ at web.de Tue Jul 1 11:58:33 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Jul 2008 17:58:33 +0200 Subject: How to use gnu readline library in program? References: Message-ID: Grant Edwards wrote: > I'm trying to figure out how to use the gnu readline library so > that when my program is prompting the user for input there is > line editing and history support. > > I've read and re-read the documentation for the "readline" > module in the standard library and I still can't figure out how > to use the module or even if the module is intended to do what > I want. The example code all seems to be about on how to > modify the behavior of an interactive Python interpreter > session so you have things like auto-completion of Python > identifiers. > > What I want to do is replace sys.stdin.readline() with > something that will provide the user with line editing and > history recall. In other languages, one uses the Gnu readline > library to do that, but my reading of the Python library > documentation is that's not what the Python readline module is > for. Am I wrong? Here's a simple example: import readline for s in "alpha beta gamma".split(): readline.add_history(s) candidates = "red yellow pink blue black".split() def completer(word, index): matches = [c for c in candidates if c.startswith(word)] try: return matches[index] + " " except IndexError: pass readline.set_completer(completer) readline.parse_and_bind("tab: complete") while 1: print raw_input("$ ") You may also consider using the cmd module. Peter From bblais at bryant.edu Wed Jul 30 11:12:37 2008 From: bblais at bryant.edu (Brian Blais) Date: Wed, 30 Jul 2008 11:12:37 -0400 Subject: Pointers/References in Python? In-Reply-To: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> References: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Message-ID: <80F2428C-C66D-4D3C-9FB1-3B7432B30057@bryant.edu> On Jul 30, 2008, at 10:46 , boblatest at googlemail.com wrote: > Of course I can just build those lists naively by creating copies of > the original list and then sorting them according to my wishes. But > that would create huge memory overhead. If the list itself is not memory intensive, but only the objects, then you shouldn't have to worry. For example, In [1]:big_object=[0.0]*int(1e7) # about 40 meg In [2]:big_object2=[0.0]*int(1e7) # another 40 meg In [3]:list1=[big_object,big_object2] # maybe a few bytes more, but no copy In [4]:list2=[big_object2,big_object] # maybe a few bytes more, but no copy after this, my python process takes about 80 meg. names like big_object are just names, and they reference an object in memory. if you say a=big_object, you are saying that the name "a" should also reference that same object. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From jenn.duerr at gmail.com Wed Jul 2 09:39:51 2008 From: jenn.duerr at gmail.com (noydb) Date: Wed, 2 Jul 2008 06:39:51 -0700 (PDT) Subject: simple UnZip Message-ID: <5b915a0e-a227-460f-8273-ecc01b800884@2g2000hsn.googlegroups.com> Can someone help me with this script, which I found posted elsewhere? I'm trying to figure out what is going on here so that I can alter it for my needs, but the lack of descriptive names is making it difficult. And, the script doesn't quite do anything worthwhile -- it unzips one file from a zipfile, not all files in a zipfile. *** import zipfile, os, sys, glob os.chdir("C:\\Temp") zips = glob.glob('*.zip') for fzip in zips: if zipfile.is_zipfile(fzip): print fzip," is a zip" z = zipfile.ZipFile(fzip,'r') lstName = z.namelist() sHgt = lstName[0] print "Unpacking",sHgt hgt = z.read(sHgt) fHgt = open(sHgt,'wb') fHgt.write(hgt) # fHgt.flush fHgt.close print "Finished" *** I changed it somewhat to &&& import zipfile, os, sys event_zip = ("C:\\Temp\\data4event.zip") z = zipfile.ZipFile(event_zip, 'r') zList = z.namelist() for zItem in zList: print "Unpacking",zItem zRead = z.read(zItem) z1File = open(zItem,'wb') z1File.write(zRead) z1File.close print "Finished" &&& This works, but I want to be able to specify a different output location. The scenario is that the zip file will always be the same (gets copied over daily), but it needs to be unzipped to a specific different directory. Can anyone help? Thanks! From wtanksleyjr at gmail.com Wed Jul 30 20:33:24 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Wed, 30 Jul 2008 17:33:24 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Message-ID: <4ae2518f-10c0-49f2-b5d7-a75993b0a67d@z66g2000hsc.googlegroups.com> "Jerry Hill" wrote: > On Wed, Jul 30, 2008 at 2:27 PM, william tanksley wrote: > > Awesome... Thank you! I had my mental model of Python turned around > > backwards. That's an odd feeling. Okay, so you decode to go from raw > > byes into a given encoding, and you encode to go from a given encoding > > to raw bytes. Not what I thought it was, but that's cool, makes sense. > That's not quite right. ?Decoding takes a byte string that is already > in a particular encoding and transforms it to unicode. ?Unicode isn't > a encoding of it's own. ?Decoding takes a unicode string (which > doesn't have any encoding associated with it), and gives you back a > sequence of bytes in a particular encoding. Okay, this is useful. Thank you for straightening out my mental model. It makes sense to define strings as just naturally Unicode... and anything else is in some ways not really a string, although it's something that might have many of the same methods. I guess this mental model is being implemented more thoroughly in Py3K... Anyhow, it makes sense. I'm still puzzled why I'm getting some non-Unicode out of an ElementTree's text, though. > Jerry -Wm From tjreedy at udel.edu Sat Jul 26 17:19:59 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 17:19:59 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87ljzpt3lv.fsf@nokile.rath.org> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> <87ljzpt3lv.fsf@nokile.rath.org> Message-ID: Nikolaus Rath wrote: > > I think you misunderstood him. I did, but addressed the below in another post. > What he wants is to write > > class foo: > def bar(arg): > self.whatever = arg + 1 > > instead of > > class foo: > def bar(self, arg) > self.whatever = arg + 1 > > so 'self' should *automatically* only be inserted in the function > declaration, and *manually* be typed for attributes. which means making 'self' a keyword just so it can be omitted. Silly and pernicious. tjr From jonas.esp at googlemail.com Sun Jul 20 11:19:37 2008 From: jonas.esp at googlemail.com (Kless) Date: Sun, 20 Jul 2008 08:19:37 -0700 (PDT) Subject: Passing keywords Message-ID: <73285f0c-da54-4c43-b83e-27c3e1b26951@2g2000hsn.googlegroups.com> I've a constructor with several values that must be used by any functions: --------------- class foo: def __init__(self, foo1, foo2, foon): self.__check(foo1=foo1, foo2=foo2, foon=foon) self.__check2(foo1=foo1, foo2=foo2, foon=foon) def __check(self, foo1, foo2, foon): ... def __check2(self, foo1, foo2, foon): ... --------------- How simplify all that? I could use the next but I don't think... --------------- def __check(self, **keywords): --------------- From robert.rawlins at thinkbluemedia.co.uk Mon Jul 21 04:46:51 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Mon, 21 Jul 2008 09:46:51 +0100 Subject: Odd math related issue. Message-ID: <00bb01c8eb0e$51face80$f5f06b80$@rawlins@thinkbluemedia.co.uk> Guys, I've got what seems to me to be a totally illogical math issue here which I can't figure out. Take a look at the following code: self.__logger.info("%i / %i" % (bytes_transferred, self.__sessions[path].total_bytes)) percentage = bytes_transferred / self.__sessions[path].total_bytes * 100 self.__logger.info("%i" % percentage) Seems fairly straight forward, you would think. It takes two values and calculates the percentage of one from the other, however, percentage always comes back as '0' for some reason, look at this log output. 2008-07-21 08:39:05,465 manager.py 78 INFO 290112 / 442435 2008-07-21 08:39:05,466 manager.py 80 INFO 0 Any suggestions as to why this might be the case? I'm sure it's something dumb but I can't spot it. Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Wed Jul 9 22:20:41 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 9 Jul 2008 19:20:41 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <750f823a-f9de-4f81-9eb3-7c7b39237c90@y38g2000hsy.googlegroups.com> Message-ID: On Jul 9, 10:06 pm, Kris Kennaway wrote: > John Machin wrote: > >> Hmm, unfortunately it's still orders of magnitude slower than grep in my > >> own application that involves matching lots of strings and regexps > >> against large files (I killed it after 400 seconds, compared to 1.5 for > >> grep), and that's leaving aside the much longer compilation time (over a > >> minute). If the matching was fast then I could possibly pickle the > >> lexer though (but it's not). > > > Can you give us some examples of the kinds of patterns that you are > > using in practice and are slow using Python re? > > Trivial stuff like: > > (Str('error in pkg_delete'), ('mtree', 'mtree')), > (Str('filesystem was touched prior to .make install'), > ('mtree', 'mtree')), > (Str('list of extra files and directories'), ('mtree', 'mtree')), > (Str('list of files present before this port was installed'), > ('mtree', 'mtree')), > (Str('list of filesystem changes from before and after'), > ('mtree', 'mtree')), > > (re('Configuration .* not supported'), ('arch', 'arch')), > > (re('(configure: error:|Script.*configure.*failed > unexpectedly|script.*failed: here are the contents of)'), > ('configure_error', 'configure')), > ... > > There are about 150 of them and I want to find which is the first match > in a text file that ranges from a few KB up to 512MB in size. > > > How large is "large"? > > > What kind of text? > > It's compiler/build output. > > > Instead of grep, you might like to try nrgrep ... google("nrgrep > > Navarro Raffinot"): PDF paper about it on Citeseer (if it's up), > > postscript paper and C source findable from Gonzalo Navarro's home- > > page. > > Thanks, looks interesting but I don't think it is the best fit here. I > would like to avoid spawning hundreds of processes to process each file > (since I have tens of thousands of them to process). > Uh-huh ... try this, then: http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ You could use this to find the "Str" cases and the prefixes of the "re" cases (which seem to be no more complicated than 'foo.*bar.*zot') and use something slower like Python's re to search the remainder of the line for 'bar.*zot'. Cheers, John From bborcic at gmail.com Fri Jul 25 10:10:21 2008 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 25 Jul 2008 16:10:21 +0200 Subject: 2d graphics - what module to use? In-Reply-To: References: Message-ID: Pierre Dagenais wrote: > What is the easiest way to draw to a window? I'd like to draw something > like sine waves from a mathematical equation. > Newbie to python. > -- > http://mail.python.org/mailman/listinfo/python-list > For very simple things, the standard module turtle might be your best bet. BB From noagbodjivictor at gmail.com Tue Jul 15 14:37:05 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Tue, 15 Jul 2008 14:37:05 -0400 Subject: 'if name is not None:' v. 'if name:' Message-ID: Hello, what's the difference between these two statement? And which one should one use? -- NOAGBODJI Paul Victor From stef.mientki at gmail.com Wed Jul 23 06:35:54 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 23 Jul 2008 12:35:54 +0200 Subject: Is this possible .... In-Reply-To: References: Message-ID: <4887098A.8040009@gmail.com> thanks Paul, your solution works very well. cheers, Stef Paul Hankin wrote: > On Jul 23, 9:58 am, Stef Mientki wrote: > > .... > You could use version() instead of module.version(), and just > declare 'version' in one place. Presumably you already have a module > for getting the metadata out of one of your modules; perhaps it could > go in there? > > def version(module): > return getattr(module, 'Version_Text')[0][0] > > -- > Paul Hankin > From jcd at sdf.lonestar.org Thu Jul 10 11:47:05 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 10 Jul 2008 11:47:05 -0400 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <1343fa73-fd32-46c3-8a75-0efc85b2660e@a70g2000hsh.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <1343fa73-fd32-46c3-8a75-0efc85b2660e@a70g2000hsh.googlegroups.com> Message-ID: <1215704825.11618.6.camel@aalcdl07.lib.unc.edu> On Wed, 2008-07-09 at 12:29 -0700, samwyse wrote: > On Jul 8, 11:01 am, Kris Kennaway wrote: > > samwyse wrote: > > > > You might want to look at Plex. > > >http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/ > > > > > "Another advantage of Plex is that it compiles all of the regular > > > expressions into a single DFA. Once that's done, the input can be > > > processed in a time proportional to the number of characters to be > > > scanned, and independent of the number or complexity of the regular > > > expressions. Python's existing regular expression matchers do not have > > > this property. " > > > Hmm, unfortunately it's still orders of magnitude slower than grep in my > > own application that involves matching lots of strings and regexps > > against large files (I killed it after 400 seconds, compared to 1.5 for > > grep), and that's leaving aside the much longer compilation time (over a > > minute). If the matching was fast then I could possibly pickle the > > lexer though (but it's not). > > That's funny, the compilation is almost instantaneous for me. > However, I just tested it to several files, the first containing > 4875*'a', the rest each twice the size of the previous. And you're > right, for each doubling of the file size, the match take four times > as long, meaning O(n^2). 156000*'a' would probably take 8 hours. > Here are my results: > > compile_lexicon() took 0.0236021580595 secs > test('file-0.txt') took 24.8322969831 secs > test('file-1.txt') took 99.3956799681 secs > test('file-2.txt') took 398.349623132 secs Sounds like a good strategy would be to find the smallest chunk of the file that matches can't cross, and iterate your search on units of those chunks. For example, if none of your regexes cross line boundaries, search each line of the file individually. That may help turn around the speed degradation you're seeing. Cheers, Cliff From __peter__ at web.de Fri Jul 18 12:19:51 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 18:19:51 +0200 Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> Message-ID: nicolas.pourcelot at gmail.com wrote: >> What is your (concrete) use case, by the way? > > > > I try to make it simple (there is almost 25000 lines of code...) > I have a sheet with geometrical objects (points, lines, polygons, > etc.) > The sheet have an object manager. > > So, to simplify : > >>>> sheet.objects.A = Point(0, 0) >>>> sheet.objects.B = Point(0, 2) >>>> sheet.objects.C = Middle(A, B) > > Then we have : > >>>> sheet.objects.A == sheet.objects.B > True > > since have and B have the same coordinates. > But of course A and B objects are not same python objects. > In certain cases, some geometrical objects are automatically > referenced in the sheet, without being defined by the user. > (Edges for polygons, for example...) > But they must not be referenced twice. So if the edge of the polygon > is already referenced (because the polygon uses an already referenced > object for its construction...), it must not be referenced again. > However, if there is an object, which accidentally have the same > coordinates, it must be referenced with a different name. > > So, I use something like this in 'sheet.objects.__setattr__(self, > name, value)': > if type(value) == Polygon: > for edge in value.edges: > if edge is_in sheet.objects.__dict__.itervalues(): > object.__setattr__(self, self.__new_name(), edge) > > Ok, I suppose it's confused, but it's difficult to sum up. ;-) I won't pretend I understand ;) If you make Point immutable you might be able to drop the "must not be referenced twice" requirement. Peter From mensanator at aol.com Sat Jul 26 22:04:02 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 26 Jul 2008 19:04:02 -0700 (PDT) Subject: Insert string into string References: <56ff99b9-b4d4-4077-8de1-97a771ac526a@k13g2000hse.googlegroups.com> Message-ID: <486aa16d-0cd5-4f26-86e3-9574998bdf5b@x35g2000hsb.googlegroups.com> On Jul 26, 6:32?pm, Mensanator wrote: > On Jul 26, 4:40?pm, "Francesco Pietra" wrote: > > > > > > > I am posting ex novo as it became confusing to me. I take the > > opportunity to ask advice for a second problem. > > > FIRST PROBLEM > > For file xxx.pdb, insert letter "A" into each line that starts with > > "ATOM". "A" should be inserted at position 22, i.e., one space after > > "LEU", leaving all other characters at the same position as in the > > original example: > > > ATOM ? ? ?1 ?N ? LEU ? ? 1 ? ? 146.615 ?40.494 103.776 ?1.00 73.04 ? ? ? 1SG ? 2 > > > In all lines starting with "ATOM", "LEU" is constant as to position > > only (18-20), i.e., "LEU" may be replaced by > > three different uppercase letters. Therefore, the most direct > > indication would be position 22. If specifying line starting with > > "ATOM" makes complication, forget about that as most lines begin with > > "ATOM" so that hand correction will be easy. > > > Script > > f = open("xxx.pdb", "w") > > import sys > > > for line in sys.stdin: > > ? ? line = line[:22] + "A" + line[23:] > > ? ? sys.stdout.write(line) > > > destroys the xxxx.pdb file and python exits witha non zero exit status. > > > The same occurs with script > > > f = open("hASIC1a.B99990003.pdb", "w") > > f.write(' line = line[:22] + "A" + line[23:]') > > f.close() > > > I must have misunderstood the suggestion I received on previous posting. > > ____________________________________ > > SECOND PROBLEM > > File xxx.pdb above has 426 lines stating with "ATOM", this serial > > number occupying positions 7-11, right justified (Thus 1, as in the > > line example above, means first line). A second, similar file yyy.pdb > > has to be concatenated to xxx.pdb. Before that it should be added of > > "A" as above and renumbered at position 7-11, starting from 428 (there > > is an intermediate line to add). How should a script look like for > > this string insertion into string with recursive +1? > > > Thanks > > francesco > > I don't know why you're using stdin if you're reading from a file. > > Also, the serial number isn't 7-11, it's 6-10 (remember to > count from 0, so character 1 is position 0, etc.) > > fx = open('xxx.pdb','r') # first input file > fy = open('yyy.pdb','r') # second input file > fz = open('zzz.pdb','w') # output file (to be created) > > for xline in fx: ? ? ? ? # read input one line at a time > ? if len(xline) >= 80: ? # don't process invalid lines > ? ? line_index = int(xline[7:12]) # keep track of this Forgot to fix this after I discovered your error. S/b int(xline[6:11]) > ? ? if xline[:4]=='ATOM': > ? ? ? fz.write(xline[:22] + 'A' + xline[23:]) > ? ? else: > ? ? ? fz.write(xline) > > fx.close() # done with first file > > fz.write('the extra line \n') > line_index += 1 ? ? ? ? ? ? ? # don't forget to count it > > for yline in fy: ? ? ? ? ? ? ?# read second file > ? if len(yline) >= 80: ? ? ? ?# again, valid only > ? ? line_index += 1 ? ? ? ? ? # ignore serial number, use > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? # ? where we left off from > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? # ? from first file > ? ? if yline[:4]=='ATOM': > ? ? ? # note use of .rjust(5) to creat new serial number > ? ? ? fz.write(yline[:6] + \ > ? ? ? ? ? ? ? ?str(line_index).rjust(5) + \ > ? ? ? ? ? ? ? ?yline[11:22] + 'A' + yline[23:]) > ? ? else: > ? ? ? fz.write(yline[:6] + \ > ? ? ? ? ? ? ? ?str(line_index).rjust(5) + yline[11:]) > > fy.close() # done with second file > > fz.close() # done with output file From inhahe at gmail.com Sun Jul 6 03:04:02 2008 From: inhahe at gmail.com (inhahe) Date: Sun, 6 Jul 2008 03:04:02 -0400 Subject: The Yield statement References: Message-ID: "Alex Bryan" wrote in message news:mailman.1009.1214865088.1044.python-list at python.org... > Okay, so i don't really understand the Yield thing and i know it is > useful. I've read a few things about it but it is all programming jargon > and so basically it is hard for me to understand. So can anyone give me a > description or link me to a site that has a good definition and/or > examples of it? If you could I would really appreciate it. Really short answer: def f(): yield 1 yield 2 yield 3 for x in f(): print x, # should print 1 2 3 def f(): for x in xrange(10): yield x for x in f(): print x, # should print 0 1 2 3 4 5 6 7 8 9 note that this won't work; def f(): for x in xrange(10): for y in xrange(10): yield (x,y) yield just doesn't work right with multiple levels of loops. i had to discover that the hard way. From sjmachin at lexicon.net Mon Jul 14 04:08:24 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 14 Jul 2008 01:08:24 -0700 (PDT) Subject: while var, but var ==16 != true References: <8c2cd9ff-bec2-4844-82a8-8ce02df5663e@w7g2000hsa.googlegroups.com> Message-ID: <8c98aa5d-12f4-43ea-af1f-ddf5e88f900e@k37g2000hsf.googlegroups.com> On Jul 14, 3:32?pm, Tim Roberts wrote: > maestro wrote: > > >why does this work? ?"while p" = "while p != 0" ? 1 is True and 0 is > >false in python but other numbers have no boolean value so why doesnt > >it abort. > > Because your statement is incorrect. ?Everything has a boolean value in > Python. ?0, None, False, '' (empty string), [] (empty list), () (empty > tuple), and {} (empty dictionary) all have a False value. ?Everything else > has a True value. Not quite; for example: >>> bool(set()) False >>> According to section 5.10 of the Reference Manual: """ In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. """ ... and for the definition for what a user-written class needs to do, see section 3.4.1: """ __nonzero__( self) Called to implement truth value testing, and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1. When this method is not defined, __len__() is called, if it is defined (see below). If a class defines neither __len__() nor __nonzero__(), all its instances are considered true. """ Cheers, John From aahz at pythoncraft.com Wed Jul 9 23:40:40 2008 From: aahz at pythoncraft.com (Aahz) Date: 9 Jul 2008 20:40:40 -0700 Subject: Python equivalent of call/cc? References: Message-ID: In article , The Pythonista wrote: > >Yesterday, I was hacking around a bit, trying to figure out how to >implement the semantics of call/cc in Python. Specifically, I wanted to >translate this Scheme code to equivalent Python: > >#### > >(define theContinuation #f) > > (define (test) > (let ((i 0)) > (call/cc (lambda (k) (set! theContinuation k))) > (set! i (+ i 1)) > i)) > > (test) > (theContinuation) > (theContinuation) > Python relies on mutables to do this: class holder: pass def call(): x = holder() x.counter = 0 def cc(): x.counter += 1 return x.counter return cc foo = call() print foo() print foo() print foo() -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From mrkafk at gmail.com Thu Jul 17 12:28:02 2008 From: mrkafk at gmail.com (mk) Date: Thu, 17 Jul 2008 18:28:02 +0200 Subject: Unusual Exception Behaviour In-Reply-To: <21965.9065748148$1216310669@news.gmane.org> References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> Message-ID: Robert Rawlins wrote: > I certainly like that implementation for logging the exceptions, however, at > the moment I don't even know where the exceptions are occurring, or what > type they are, could I still use this method to log any and all exceptions > raised in the application? Sure. I'm a little confused as to how I can modify that > implementation to do so. Remember, Google is your friend, here's the crux of the method without the fancy schmancy sugar coating: http://linux.byexamples.com/archives/365/python-convey-the-exception-traceback-into-log-file/ if __name__=="__main__": try: main() except: print "Trigger Exception, traceback info forward to log file." traceback.print_exc(file=open("errlog.txt","a")) sys.exit(1) This will obviously capture every exception happening in the main() function. The drawback of this method is that you cannot capture the error message / object accompanying the exception, as you normally can do while capturing specific exception: >>> import sys >>> import traceback >>> def anindextoofar(alist): print alist[10] >>> shortlist=range(1,10) >>> >>> try: anindextoofar(shortlist) except IndexError, err: print err traceback.print_exc(file=sys.stdout) list index out of range Traceback (most recent call last): File "", line 2, in File "", line 2, in anindextoofar IndexError: list index out of range From kurdayon at yahoo.com Tue Jul 1 16:43:45 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Tue, 1 Jul 2008 13:43:45 -0700 (PDT) Subject: How to make a function associated with a class? Message-ID: <69e26f9b-2f00-4318-9bc5-6aa94e141bca@59g2000hsb.googlegroups.com> Hi, I have a class called "vector". And I would like to define a function "dot" which would return a dot product of any two "vectors". I want to call this function as follow: dot(x,y). Well, I can define a functions "dot" outside the class and it works exactly as I want. However, the problem is that this function is not associated with the class (like methods a method of the class). For example, if I call "x.calc()" or "y.calc()", python will execute different methods if "x" and "y" belongs to different classes. I want to have the same with my "dot" function. I.e. I want it calculates the dot product ONLY IF the both arguments of that function belong to the "vector" class. Is it possible? Thank you in advance. From pavlovevidence at gmail.com Thu Jul 31 22:36:48 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 31 Jul 2008 19:36:48 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: <9f4b1c12-d010-45f6-91ee-d490e2f850dc@79g2000hsk.googlegroups.com> On Jul 31, 1:27 pm, "Chris Mellon" wrote: > I'm really not sure where you're going with this or what you're trying > to prove. "if x" is a duck-type test for a boolean value. Obviously if > you know the type and want a more *specific* test, then you can use an > explicit one. Any time you don't know or don't care about a more > specific type than "something which probably is boolean true", or any > time where you know the boolean semantics of the type and want to drop > some typing, you can use "if x". The more specific test is what you'd > use if you want more specific results. What's complicated about this > idea? Many people trumpet that "if x" makes your code more polymorphic whenever this comes up--in fact you just repeated the claim--without ever considering how rarely this more extensive polymorphism comes up in practice. I was calling them out to say "prove to me that it actually happens". I believe it's very rare not to know enough about the expected type that explicit tests won't work. We've uncovered a few examples of it in this thread, but IMO we haven't uncovered any sort of broad, wide- ranging use cases. Carl Banks From henrik at chamalulu.com Tue Jul 1 17:20:11 2008 From: henrik at chamalulu.com (chamalulu) Date: Tue, 1 Jul 2008 14:20:11 -0700 (PDT) Subject: Attribute reference design Message-ID: Hello. I think I'm aware of how attribute access is resolved in python. When referencing a class instance attribute which is not defined in the scope of the instance, Python looks for a class attribute with the same name. (For assignment or deletion this is not the case, thankfully.) I've been trying to understand why? What is the reason behind, or practical purpose of, this design decision? Anyone, please enlighten me. /Henrik From gagsl-py2 at yahoo.com.ar Wed Jul 30 21:07:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 22:07:31 -0300 Subject: undo a dictionary References: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> <192b4786-85b2-43d3-bb7c-b5716068ff12@56g2000hsm.googlegroups.com> Message-ID: En Wed, 30 Jul 2008 16:14:31 -0300, mmm escribi?: >> > And for that matter a way to create a >> > dictionary from a set of variables (local or global). >> >> You have to be more specific: there are {} displays and dict(args) call >> and other methods. ?Read the manual. > > My desire is to take a set of data items in an alpha-numeric range and > oput them into a dictionary > > i.e., > x1=1 > x2=20 > x3=33 > > to yield the dictionary > > { 'x1':1, 'x2':20, 'x3':33 } > > without having to type in as above but instead invoke a function dict(x1=1, x2=20, x3=33) does the same thing. Or, do you mean you already have those names and values, perhaps mixed with a lot more names, and want to extract only those starting with "x" and following with a number? result = {} for name, value in vars(): # or locals().items(), or globals().items(), or vars(some_module) if name[0]=='x' and name[1:].isdigit(): result[name] = value -- Gabriel Genellina From wtanksleyjr at gmail.com Thu Jul 31 17:44:51 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Thu, 31 Jul 2008 14:44:51 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> <4609709f-dc0f-47cc-905e-1552a02ec3b6@r15g2000prd.googlegroups.com> <416f2710-1295-4d8b-a356-98fd9e9a56ad@j7g2000prm.googlegroups.com> Message-ID: John Machin wrote: > william tanksley wrote: > Let's try again: Cool. Sorry for the misunderstanding. Thank you for helping again! Postscript: your request to print the actual data did the trick. I'm including the rest of my reply just to provide context, but the answer was the the Unicode was actually embedded in the URL, encoded as distinct bytes. Thus, it *had* to be url-decoded and then UTF-8 decoded, in that order, in order to recover the original filename. So the problem was indeed purely in my head -- I should have looked at the original data (unfortunately, I was fooled by looking at the song title, which is the same thing but with the raw UTF-8 bytes instead of the URL escape codes). > >> track_id = url2pathname(urlparse(track_id).path) > >> print repr(track_id) > >> parse_result = urlparse(track_id).path > >> print repr(parse_result) > >> track_id_replacement = url2pathname(parse_result) > >> print repr(track_id_replacement) > > The "important" value here is track_id_replacement; it contains the > > data that's throwing me. It appears that some UTF-8 characters are > > being read as multiple bytes by ElementTree rather than being decoded > > into Unicode. > > Here's one example. The others are similar -- they have the same > > things that look like problems to me. > > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" > ROTFL! I thought the Buffett thing was a Windows filename! What I was > expecting was THREE lots of repr() output, and I'm quite unused to > seeing repr() output with quotes around it instead of apostrophes; how > did you achieve that? I don't know -- but I got it again when I printed out the original version. My *guess* would be that this is what repr prints when asked to print a byte string (but I don't know how to confirm that). Alternately, the fact that I'm running these inside SPE might be changing some defaults. I'm not sure. You're right that single quotes are expected -- and I'd expect a preceding u, since they're supposed to be Unicode. I dunno what's going on. > So you're saying that track_id_replacement contains utf8 characters. > It is obtained by track_id_replacement = url2pathname(parse_result). > You don't show us what is in parse_result. url2pathname() is nothing > to do with ElementTree. urlparse() is nothing to do with ElementTree. > You have provided no evidence that ElementTree is doing what you > accuse it of. Okay. Here's the evidence... Or something. Looking at this I begin to see why things work the way they do. It's utterly bizzare, quite frankly. > Please try again. Backtrack in your code to where you are pulling the > url out of an element. Do print repr(some_element.some_attribute). > Show us. Okay, the repr of the string that comes out of the .text attribute is: "file://localhost/C:/Documents%20and%20Settings/TanksleyJrW/My %20Documents/My%20Music/iTunes/iTunes%20Music/Podcasts/Brian %20Preston's%20_Money%20Guy_%20Blog%20and%20Pod/Buffett%20Time%20- %20Annual%20Shareholders%C2%A0L.mp3" Looking at the XML, and THIS TIME actually looking at the correct attribute (I was looking at the title before) I see... surprise! That's the correct data. So all of the mysteries are solved (except for my Python's doublequotes, but who cares), and ElementTree is entirely vindicated. -Wm From larry.bates at websafe.com` Tue Jul 15 15:41:55 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 14:41:55 -0500 Subject: logging via SocketHandler and TCPserver In-Reply-To: <87tzerndq9.fsf@merkury.smsnet.pl> References: <81929250-449b-4686-acf3-dcc0095e341a@d1g2000hsg.googlegroups.com> <87tzerndq9.fsf@merkury.smsnet.pl> Message-ID: Rob Wolfe wrote: > Larry Bates writes: > >> Can multiple applications send SocketHandler logging records to the >> same socket server on the same port simultaneously? > > Of course they can. Server can accept requests from many clients. > You have used `SocketServer.ThreadingTCPServer`. That server for example > handles every request in a different thread. > >> If so, then I understand your answer completely and will go >> in that direction. I guess I was trying to not use up >> bandwidth/CPU cycles on the applications that weren't being actively >> monitored by just not having the socket server connected to them. >> >> I think you may be a 'little to close' to the (excellent) application >> you have written to understand the steep learning curve that I see. >> You know the saying, "Brain surgery is easy to a brain surgeon". I >> should point out that I'm no newbie. I've used PIL, ReportLab, >> BeautifulSoup, Mechanize, Win32 extensions, ElementTree and a whole >> host of other modules with less difficulty. Please don't take this as >> anything more than an observation on my part. From what I see, you >> have written (and generously donated) an extremely powerful library >> and it is greatly appreciated. It is most likely just me. > > Well, I know what you mean. I had troubles to understand that library > either. Logging docs are quite good as a reference, but there is lack > of a good introductory tutorial. Now when I know `logging` I can't live > without it, but the start wasn't easy. > I shouldn't say it here, but I found helpful docs to the similar > library in Java. ;) > http://logging.apache.org/log4j/1.2/manual.html > > There are many differences (e.g. Appenders vs Handlers), but the rule > is the same. > >> As far as the book is concerned, I guess I'd purchase the only copy ;-). > > "The Art of Logging" - four volumes. ;-) > > Regards, > Rob Five volumes if you add in "Logging within Frameworks (Django, TurboGears, and Pylons" ;-). Now on to UnitTesting (I use a home-grown method), Twisted, and other things I can't seem to find time to get my brain around... -Larry From blake.anderton at gmail.com Fri Jul 25 20:19:36 2008 From: blake.anderton at gmail.com (BAnderton) Date: Fri, 25 Jul 2008 17:19:36 -0700 (PDT) Subject: How to close all python-opened file identifiers? Message-ID: Greetings from beautiful Tucson, Arizona. Question: Is there a way in Python to determine what all file identifiers have been opened by Python, and to close them all? Why I ask: I learned Python after cutting my programming teeth on Matlab, where you get a list of all open file identifiers (that is, those opened from a particular Matlab session) with "fopen('all')" and close them with "fclose('all')". In my 4 years of experience with Python, I haven't yet come across an equivalent means of doing this in Python. I understand that this problem can be prevented by making sure a "fid.close()" exists for every "open"; I need this however for a file-permissions troubleshooting problem. Extra info on this specific problem: In my program, python (through subprocess) launched a text editor on a text file, and I can't seem to save the text file through that editor (I get a "this document is in use by another application and cannot be accessed" error from the editor [wordpad on winXp]). The text file in question is modified by my program prior to its loading into the launched editor. Although I can't find unmatched "open" and "fid.close()" statements, I'd like to implement a check for open file identifiers before launching the editor. Thanks very much in advance for your time and any help you can provide. From mnordhoff at mattnordhoff.com Mon Jul 7 13:06:00 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 07 Jul 2008 17:06:00 +0000 Subject: Confused yet again: Very Newbie Question In-Reply-To: <16651e80807070654j12d55802yf3950e2375bbe67d@mail.gmail.com> References: <16651e80807070654j12d55802yf3950e2375bbe67d@mail.gmail.com> Message-ID: <48724CF8.6030009@mattnordhoff.com> Jerry Hill wrote: > On Mon, Jul 7, 2008 at 7:30 AM, mcl wrote: >> I did not think you had to make the distinction between 'byvar' and >> 'byref' as in Basic. > > Python does not use "call by value" or "call by reference" semantics. > Instead, python's model is "call by object". See this writeup for > some details: http://effbot.org/zone/call-by-object.htm Ah-ha! That's the article I've been trying to find! I can never remember "effbot"'s name. Thanks! -- From thudfoo at opensuse.us Mon Jul 28 11:23:36 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Mon, 28 Jul 2008 08:23:36 -0700 Subject: QOTW [was Re: Attack a sacred Python Cow] In-Reply-To: <009dce32$0$20313$c3e8da3@news.astraweb.com> References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> <7360bd9a-4ff6-4e75-821c-eabc88ee6258@u6g2000prc.googlegroups.com> <009dce32$0$20313$c3e8da3@news.astraweb.com> Message-ID: <3d881a310807280823h46ec1d40yfd9eac1ca2791bfd@mail.gmail.com> On 28 Jul 2008 14:07:44 GMT, Steven D'Aprano wrote: > On Sun, 27 Jul 2008 21:42:37 -0700, Russ P. wrote: > > >> +1 QOTW > > > > Do you realize what an insult that is to everyone else who has posted > > here in the past week? > > Actually I don't. I hadn't realised that when a person believes that > somebody has made an especially clever, witty, insightful or fun remark, > that's actually a put-down of all the other people whose remarks weren't > quite as clever, witty, insightful or fun. > > But now that I've had this pointed out to me, why, I see insults > everywhere! Tonight, my wife said to me that she liked my new shirt, so I > replied "What's the matter, you think my trousers are ugly?" > > > -- > Steven > It is difficult to not offend the insult-sensitive. From russandheather at gmail.com Sat Jul 19 01:45:32 2008 From: russandheather at gmail.com (Russell Warren) Date: Fri, 18 Jul 2008 22:45:32 -0700 (PDT) Subject: "proper"/best way to hack SimpleXmlRpcServer to support datetime? Message-ID: <7e2bab15-d655-4741-974f-d5dfa2bea9f8@m36g2000hse.googlegroups.com> I'm running python 2.5.1 and it seems that SimpleXmlRpcServer is not setup to support the base datetime module in the same way xmlrpclib has been with "use_datetime". I see that someone (Virgil Dupras) has recently submitted a fix to address this, but I don't want to patch my python distro. I want to work around it until the real upgrade comes. I have a klugey workaround I can just drop in my program that does the trick, but I'm curious if there is a better way? I have not done that many monkey patches. I'm also of course interested in someone telling me I don't need to patch this and I'm just blind to the correct way. My monkey patch is below... ### HACK HACK HACK ### ## Patching SimpleXmlRpcServer to support datetime (just like xmlrpclib does) from SimpleXMLRPCServer import xmlrpclib as _xmlrpclib _old_loads = _xmlrpclib.loads def _new_loads(*args, **kwargs): kwargs["use_datetime"] = True return _old_loads(*args, **kwargs) _xmlrpclib.loads = _new_loads ### ENDHACK ENDHACK ### That works, but are there any better, slicker, more pythonic, more robust, more interesting, or just plain more fun ways to do it? From malaclypse2 at gmail.com Wed Jul 23 11:55:27 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 23 Jul 2008 11:55:27 -0400 Subject: Get dict value but not as reference. In-Reply-To: <4357936148771237039@unknownmsgid> References: <4357936148771237039@unknownmsgid> Message-ID: <16651e80807230855l745bba66u4c506e9fab5b38fa@mail.gmail.com> On Wed, Jul 23, 2008 at 11:49 AM, Robert Rawlins wrote: > I have a dictionary, and I want to get one of the values from it, but rather > than returning it as a reference I want to actually detach/remove the > element from the dictionary. Like so: Use the pop() method of the dictionary, like this: >>> my_dict = {'a': 'Item A', 'b': 'Item B', 'c': 'Item C'} >>> my_dict.pop('a') 'Item A' >>> my_dict {'c': 'Item C', 'b': 'Item B'} >>> -- Jerry From fredrik at pythonware.com Wed Jul 23 03:22:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 09:22:38 +0200 Subject: os.walk question In-Reply-To: References: Message-ID: Lanny wrote: > How would one make a list of the files in the top directory > using os.walk. > > I need to pick a random file from said list. if you want a list of files from a single directory, use listdir, not walk: >>> import os, random >>> random.choice(os.listdir("/")) 'python25' From babacity4 at gmail.com Thu Jul 24 16:55:04 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:55:04 -0700 (PDT) Subject: www spankwire com - Amazing porn video collection Message-ID: www spankwire com . >>>>>>>>>>Best Collection of Spankwire Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE www spankwire VIDEOS<<<<<<<<<<< . www spankwire com From dominic.rice at gmail.com Fri Jul 4 05:38:35 2008 From: dominic.rice at gmail.com (Dominic Rice) Date: Fri, 04 Jul 2008 10:38:35 +0100 Subject: running python from cmd.exe References: Message-ID: Dominic Rice wrote: > Miki wrote: >> Hello, >> >>> I can't seem to get python to run my scripts using the command: python >>> .py >>> >>> If I type python the interpreter runs as I sorted out the Path property, >>> >>> I'm afraid I don't know much about this kind of thing as I'm a science >>> student who needs some Python not a programmer! >> Can you be more specific about the error you get? >> >> Say you have a script hw.py that contains one line: >> print "Hello Python" >> >> and you run >> python hw.py >> >> What is the error you get? >> >> HTH, >> -- >> Miki >> http://pythonwise.blogspot.com >> > Sure, I get: > > can't open file .py: [errorno 2]No such file or directory. > > Now if I've noticed that if I change directory to (for instance) > \Python25 where the script is the command runs fine.(?) Oh I just noticed you specified hw.py, in that case just to clarify it would be can't open file hw.py: [errorno 2]No such file or directory From sn.oo.py.9027 at gmail.com Mon Jul 14 12:41:15 2008 From: sn.oo.py.9027 at gmail.com (John Mechaniks) Date: Mon, 14 Jul 2008 09:41:15 -0700 (PDT) Subject: subprocess module References: <2e7f0504-cc1c-4cb6-b2d0-b67b004eca7d@x41g2000hsb.googlegroups.com> <39622612-5e43-45b4-800a-69277c2e2987@79g2000hsk.googlegroups.com> Message-ID: <83c5472c-935d-4eda-ad98-dbb6dd02222a@l64g2000hse.googlegroups.com> On Jul 14, 7:44?pm, Peter Otten <__pete... at web.de> wrote: > John Mechaniks wrote: > > On Jul 14, 12:34?pm, Peter Otten <__pete... at web.de> wrote: > >> John Mechaniks wrote: > >> > from subprocess import call > >> > call(['ls', '-l']) > > >> > How do I get the result (not the exit status of the command) of "ls - > >> > l" into a variable? > > >> output = subprocess.Popen(["ls", "-l"], > >> stdout=subprocess.PIPE).stdout.read() > > What difference does the following code makes? What are the advantages > > of the above method over this one? > > output = subprocess.Popen(['ls', '-l'], > > stdout=subprocess.PIPE).communicate()[0] > > Hm, I chose it because it looks cleaner. Looking into the source > Popen.communicate() seems to do the following: > > output = p._fo_read_no_intr(p.stdout) ? > p.wait() ? ? ? ? ? ? > > So there are two differences in this case > > - communicate() waits for the subprocess to terminate. > - stdout.read() is retried if an EINTR occurs (Not sure when this would > happen). > > > Also could someone show an example of using the optional input > > argument for communicate() > > http://blog.doughellmann.com/2007/07/pymotw-subprocess.html > > I didn't read it myself, but Doug Hellmann's articles are usually quite > good. > > Peter Thanks Peter From boblatest at yahoo.com Sat Jul 26 14:54:22 2008 From: boblatest at yahoo.com (Robert Latest) Date: 26 Jul 2008 18:54:22 GMT Subject: Confounded by Python objects References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> <5ddae1dd-c7dd-4f04-84f6-ad71c3282c92@j7g2000prm.googlegroups.com> Message-ID: <6f1a6uF9ctsmU1@mid.uni-berlin.de> satoru wrote: > As to "sample", it never get assigned to and when you say "append" the > class variable is changed in place. > hope my explaination helps. Sure does, thanks a lot. Here's an interesting side note: After fixing my "Channel" thingy the whole project behaved as expected. But there was an interesting hitch. The main part revolves around another class, "Sequence", which has a list of Channels as attribute. I was curious about the performance of my script, because eventually this construct is supposed to handle megabytes of data. So I wrote a simple loop that creates a new Sequence, fills all the Channels with data, and repeats. Interistingly, the first couple of dozens iterations went satisfactorily quickly (took about 1 second total), but after a hundred or so times it got really slow -- like a couple of seconds per iteration. Playing around with the code, not really knowing what to do, I found that in the "Sequence" class I had again erroneously declared a class-level attribute -- rather harmlessly, just a string, that got assigned to once in each iteration on object creation. After I had deleted that, the loop went blindingly fast without slowing down. What's the mechanics behind this behavior? robert From fredrik at pythonware.com Wed Jul 16 20:24:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 02:24:25 +0200 Subject: Manually prompting garbage collection In-Reply-To: <20080716235656.GE22400@monkey.ucolick.org> References: <20080716230911.GD22400@monkey.ucolick.org> <20080716235656.GE22400@monkey.ucolick.org> Message-ID: Kyle Lanclos wrote: > The DECREF decrements the reference count, but does not immediately prompt > garbage collection when the reference count drops to zero; that garbage > collection does not appear to occur until I return from the particular C > function I am in the middle of executing. Yeah, but what do you expect that garbage collection pass to result in? What objects do you want to get rid of? Do these objects have direct references to a resource that you're explicitly destroying from your C code? Why? > Ideally, I want to explicitly prompt garbage collection in the middle > of a C function, without first returning to the larger Python > interpreter. PyGC_Collect() does exactly that, so if that doesn't solve your problem, the only way to fix is this is to go back to the drawing board (and even if it would fix this, it's a good idea to get back to the drawing board anyway; Python's not C++, and code that relies on destructors to fire in a specific order, or before a specific event, is bound to fail sooner or later.) From tjreedy at udel.edu Thu Jul 17 17:19:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jul 2008 17:19:08 -0400 Subject: unpacking with default values In-Reply-To: <6a105194-a248-4ee6-be01-5aef9e5bb648@e53g2000hsa.googlegroups.com> References: <335e7a21-e35e-41ee-9f92-fd4c2f6bf166@f36g2000hsa.googlegroups.com> <6a105194-a248-4ee6-be01-5aef9e5bb648@e53g2000hsa.googlegroups.com> Message-ID: McA wrote: > Do you know the "protocol" used by python while unpacking? > Is it a direct assingnment? Or iterating? In CPython, at least, both, just as with normal unpack and multiple assignment. The iterable is unpacked into pieces by iterating (with knowledge of the number of targets and which is the catchall). The targets are then directly bound. >>> from dis import dis # first standard assignment >>> dis(compile("a,b,c = range(3)", '','single')) 1 0 LOAD_NAME 0 (range) 3 LOAD_CONST 0 (3) 6 CALL_FUNCTION 1 9 UNPACK_SEQUENCE 3 12 STORE_NAME 1 (a) 15 STORE_NAME 2 (b) 18 STORE_NAME 3 (c) 21 LOAD_CONST 1 (None) 24 RETURN_VALUE # now starred assignment >>> dis(compile("a,b,*c = range(3)", '','single')) 1 0 LOAD_NAME 0 (range) 3 LOAD_CONST 0 (3) 6 CALL_FUNCTION 1 9 UNPACK_EX 2 12 STORE_NAME 1 (a) 15 STORE_NAME 2 (b) 18 STORE_NAME 3 (c) 21 LOAD_CONST 1 (None) 24 RETURN_VALUE The only difference is UNPACK_EX (tended) instead of UNPACK_SEQUENCE. Tne UNPACK_EX code is not yet in the dis module documentation. But a little reverse engineering reveals the parameter meaning: a,*b,c and *a,b,c give parameters 257 and 512 instead of 2. Separating 2,257,512 into bytes gives 0,2; 1,1; 2,0. a,*b and *a,b give 1, 256 or 0,1; 1,0. The two bytes are the number of targets after and before the starred target. Terry Jan Reedy From tn.pablo at gmail.com Mon Jul 21 09:12:30 2008 From: tn.pablo at gmail.com (ptn) Date: Mon, 21 Jul 2008 06:12:30 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <0537f970-6a87-42f8-872c-6a48fd2211a6@e53g2000hsa.googlegroups.com> On Jul 20, 5:50?pm, giveitawhril2... at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. Sounds like you program only because someone's paying you. Any programmer who says that C is outdated and not real *is* outdated and not real. Not used anymore? Mmmmm I wonder, have you heard of something called "Linux"? The open source Unix-like system? Or perhaps you are familiar with "Apache"? Does "GNOME" ring any bells to you? "Vim"? "Git"? You got some serious research to do, STFW. From fredrik at pythonware.com Wed Jul 23 03:07:27 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 09:07:27 +0200 Subject: sys.stderr.write returns string length in Python 3 In-Reply-To: References: <43ab2eb4-31ec-4574-ab54-4467fa89d187@27g2000hsf.googlegroups.com> Message-ID: Alan G Isaac wrote: > Can you give me an example of using the returned value? it's for consistency with stream objects that support raw I/O (as described in the PEP). when using buffered I/O, you can ignore it. From stephan at transvection.de Tue Jul 1 08:06:41 2008 From: stephan at transvection.de (Stephan Diehl) Date: Tue, 01 Jul 2008 14:06:41 +0200 Subject: PyPy questions In-Reply-To: References: Message-ID: Allen schrieb: > I read the website of some information about PyPy, and how a translator > translates the RPython code to C/CLI/Java/etc to be compiled to a native > executable or something like that. Would it be possible, in PyPy, to > write such an extension that could easily be compiled to native code > from Python code? Is this functionality planned in a future release of > it? Also, how is the source distributed (If I opt to use it I will end > up compiling it on a system without an initial python install (a scratch > linux system)), so does the source include the generated C code? > > B. Vanderburg II these kind of questions are better asked on pypy-dev. Anyway, at the moment you need a working python installation in order to run the pypy chain. I have to admit that I didn't understand your question, but you should read the pypy documentation on codespeak.net as it will probably answer all of your questions. Alternativly, you might want to join the #pypy channel on freenode Stephan From fredrik at pythonware.com Wed Jul 16 10:14:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 16:14:35 +0200 Subject: Regular expression In-Reply-To: References: Message-ID: Beema shafreen wrote: > How do I write a regular expression for this kind of sequences > > >gi|158028609|gb|ABW08583.1| CG8385-PF, isoform F [Drosophila melanogaster] > MGNVFANLFKGLFGKKEMRILMVGLDAAGKTTILYKLKLGEIVTTIPTIGFNVETVE line.split("|") ? it's a bit hard to come up with a working RE with only a single sample; what are the constraints for the different fields? is the last part free form text or something else, etc. have you googled for existing implementations of the format you're using? From enleverlesX.XmcX at XmclaveauX.com Sat Jul 5 16:57:40 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 5 Jul 2008 22:57:40 +0200 Subject: Python with Ecmascript In-Reply-To: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> Message-ID: <486fe241$0$867$ba4acef3@news.orange.fr> Hi! Ecmascript (Jscript) is Active-Scripting compliant. With PyWin32, you can : - call JScript functions (with parameters) - define pieces of code (& run it) Another way, is to drive Internet-Explorer (via COM). You can set the IE-Windows as invisible, and connect the motor of execution (of JScript). Then, you can : - call JScript functions, with parameters et return ; variables, but also array (<=> lists) - connect to JScripts's objects (for read/write) - write new functions in JScript - etc. @-salutations Michel Claveau From cs at zip.com.au Thu Jul 10 18:37:53 2008 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 11 Jul 2008 08:37:53 +1000 Subject: Determining when a file has finished copying In-Reply-To: <487644F0.9070906@gmail.com> Message-ID: <20080710223753.GA14055@cskk.homeip.net> On 10Jul2008 13:20, Manuel Vazquez Acosta wrote: | Cameron Simpson wrote: | > On 09Jul2008 15:54, Ethan Furman wrote: | >> The solution my team has used is to monitor the file size. If the file | >> has stopped growing for x amount of time (we use 45 seconds) the file is | >> done copying. Not elegant, but it works. | > | > If you know that files appear in sequence (a single serial upload | > process, not multiple uploaders) you can augument this with a check | > that an additional file has started to upload, ergo the current file | > has finished. Of course, only you can decide if this might be relied upon. | | Hum, what about the last file in the sequence? | I think polling file's size maybe a good indicator, as Ethan proposed. Hence the word "augument". It may let you short circuit the time delay, if a new file appears. Obviously it's not enough on its own. -- Cameron Simpson DoD#743 From babacity4 at gmail.com Thu Jul 24 16:51:50 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:51:50 -0700 (PDT) Subject: sextv1 player - Amazing porn video collection Message-ID: <2adc914d-0115-4cc0-8e67-058d9cf9b072@v39g2000pro.googlegroups.com> sextv1 player . >>>>>>>>>>Best Collection of Sextv1 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE sextv1 player VIDEOS<<<<<<<<<<< . sextv1 player From deets at nospam.web.de Mon Jul 28 09:31:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 15:31:26 +0200 Subject: ctypes and how to copy data passed to callback References: <2059b8a4-7651-4c3c-afbf-44caa8605c64@m3g2000hsc.googlegroups.com> Message-ID: <6f603fFa1lhcU1@mid.uni-berlin.de> waldek wrote: > Hi, > > I'm trying to handle data passed to Py Callback which is called from > C dll. Callback passes data to another thread using Queue module and > there the data are printed out. > > If data is printed out in a callback itself it's ok. If I put on > queue and next get from queue in another thread script prints some > trash. Looks like the data is released when callback returned. I tired > to make d = copy.deepcopy(data), but it does not work - I got nothing. > Any idea why it's happening ? > > --------------------- main thread -------- > def callback(data, size): > myqueue.put((data, size)) > > mydll = cdll.MyDLL > cbproto = CFUNCTYPE(c_int, POINTER(c_char), c_int) > mycallback = cbproto(callback) > > mydll.RegisterCallback(mycallback) > > ---------------------------------- thread listener > ---------------------- > > while True: > data, size = myqueue.get() > print "***", data[:size] > > ------------------------------------------------------------------------------ You need to allocate e.g. a bytebuffer using ctypes and then copy the memory area you get passed into that buffer. Otherwise I presume whoever invokes the callback releases the originaly memory block after the callback terminated. Diez From deets at nospam.web.de Sun Jul 27 08:20:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2008 14:20:09 +0200 Subject: bundling python with application In-Reply-To: References: Message-ID: <6f37fqF97ndoU1@mid.uni-berlin.de> Randall Smith schrieb: > I'd like to bundle Python with my app, which will be targeted at Linux, > Windows and Mac. Discussions I've found about this tend to lead to > py2exe, freeze, etc, but I'd like to do something rather simple and am > seeking advice. > > What I'd like to do is just copy the standard libraries and > executable(s) and adjust the paths in the environment variables. The > libraries and executable(s) would reside in the same directory with the > application so that you could run the application without needing to > install it. The directory might look like this: > > $ ls > > start-app.sh > app_lib/ > python_lib/ > python_bin/ > > > start-app.sh would look like this: > > #!/bin/sh > > PATH="python_bin:$PATH" PYTHON_HOME="./python_lib" python app_lib/start.py > > Of course, there would be a start-app.bat for Windows. > > The PATH is altered to make sure the right python interpreter is found > and PYTHON_HOME makes sure the right (local) libraries are found. > > Can this be done? It might be doable (virtualenv shows it works, you might consider taking a look into it), but I would advise against it. py2exe and py2app for example do a great job to provide a way to distribute software in a way the respective target OS (and their users) are expecting it. For example, OSX uses so-called "application bundles" which py2app (guess where the name comes from...) produces for you. Not using them might cripple you, because e.g. GUI-stuff isn't working properly (or will show an arbitrary icon in the dock, instead of one you chose). Why do you insist on re-inventing a wheel that's rolling fine? Diez From gnewsg at gmail.com Sun Jul 13 22:16:47 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sun, 13 Jul 2008 19:16:47 -0700 (PDT) Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> <487a3c0d$0$32256$9b622d9e@news.freenet.de> Message-ID: <18f16069-aab6-495d-86e2-3080421e52db@79g2000hsk.googlegroups.com> On 13 Lug, 22:35, Miles wrote: > On Sun, Jul 13, 2008 at 3:05 PM, Giampaolo Rodola' wrote: > > On 13 Lug, 19:31, "Martin v. L?wis" wrote: > >> > I understand that heapq is not that efficient to implement timeouts as > >> > I thought at first. > >> > It would have been perfect if there were functions to remove arbitrary > >> > elements withouth needing to re-heapify() the heap every time. > > >> It is efficient for that - you just need to use it correctly. > > >> To remove the nth element from a heap, replace it with the last element, > >> and then _siftup that element: > > >> The time complexity for that operation is O(log(len(heap))). > > The problem is that in order to remove an arbitrary element from a > heap, you usually have to do an O(n) linear search in order to find it > first, since you can't know ahead of time which index an arbitrary > element is at. ?(You can, actually, but only if your heap > implementation somehow notifies the elements of their new index when > it moves them in the heap, which the Python heapq module doesn't do, > so you'd have to write your own heap implementation.) > > > And if instead of removing an element I'd want to change its value? > > E.g.: > > > ?>>> heap = [0, 2, 1, 4, 5, 6, 7, 8, 9] > > ?>>> heapify(heap) > > ?>>> heap > > ?[0, 2, 1, 4, 5, 6, 7, 8, 9] > > ?>>> heap[4] = 12 > > Don't do that; you must first remove the element and then reinsert it. > > -Miles That seems to be slower than re-heapifying() the heap. The code I used (which is probably wrong): def reset(self): """Reschedule this call resetting the current countdown.""" assert not self.cancelled, "Already cancelled" self.timeout = time.time() + self.__delay n = heap.index(self) if n == len(heap) - 1: heap.pop() else: heap[n] = heap.pop() heapq._siftup(heap, n) heapq.heappush(heap, self) Moreover I have the feeling that doing such thing requires a different code whether the new value I use as replacement is lower or higher in comparison to the older one. Am I right? --- Giampaolo http://code.google.com/p/pyftpdlib/ From exarkun at divmod.com Tue Jul 29 13:32:34 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 29 Jul 2008 13:32:34 -0400 Subject: [unittest] Run setUp only once In-Reply-To: <871w1cr49a.fsf@nokile.rath.org> Message-ID: <20080729173234.29191.503309096.divmod.quotient.8288@ohm> On Tue, 29 Jul 2008 19:26:09 +0200, Nikolaus Rath wrote: >Jean-Paul Calderone writes: >> On Tue, 29 Jul 2008 16:35:55 +0200, Nikolaus Rath wrote: >>>Hello, >>> >>>I have a number of conceptually separate tests that nevertheless need >>>a common, complicated and expensive setup. >>> >>>Unfortunately, unittest runs the setUp method once for each defined >>>test, even if they're part of the same class as in >>> >>>class TwoTests(unittest.TestCase): >>> def setUp(self): >>> # do something very time consuming >>> >>> def testOneThing(self): >>> >>> >>> def testADifferentThing(self): >>> >>> >>>which would call setUp twice. >>> >>> >>>Is there any way to avoid this, without packing all the unrelated >>>tests into one big function? >>> >> >> class TwoTests(unittest.TestCase): >> setUpResult = None >> >> def setUp(self): >> if self.setUpResult is None: >> self.setUpResult = computeIt() >> >> ... >> >> There are plenty of variations on this pattern. > > >But at least this variation doesn't work, because unittest apparently >also creates two separate TwoTests instances for the two tests. Isn't >there some way to convince unittest to reuse the same instance instead >of trying to solve the problem in the test code itself? > Eh sorry, you're right, the above is broken. `setUpResult` should be a class attribute instead of an instance attribute. Jean-Paul From robert.rawlins at thinkbluemedia.co.uk Tue Jul 8 08:22:31 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 8 Jul 2008 13:22:31 +0100 Subject: No Exceptions Message-ID: <002901c8e0f5$52a47ca0$f7ed75e0$@rawlins@thinkbluemedia.co.uk> Morning Guys, This morning I've been having a strange issue where my application doesn't appear to raise any exceptions. Even when manually placing code in the application which raises an exception explicitly like: Raise Exception, "This is a test exception" The application doesn't appear to throw it, it will fail to execute any code in the block following the exception but does not throw any exceptions to the command prompt. Any ideas what might be causing this? I've just sent another support request to this list about logging configuration, could the two issues be related? Thank you, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Thu Jul 17 01:27:42 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 17 Jul 2008 17:27:42 +1200 Subject: Problem with MySQLdb and mod_python References: Message-ID: In message , Cyril Bazin wrote: > But it seems, after many tests, that the script stops at the > instruction : "c.execute(requete)" What's the error message? This should be in Apache's error_log file. From pavlovevidence at gmail.com Wed Jul 30 00:52:52 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 21:52:52 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: On Jul 29, 11:17 pm, Terry Reedy wrote: > Carl Banks wrote: > >> As I wrote in the second reply email I sent, check out my integer set > >> recipe on ASPN (and to save you the search: http://code.activestate.com/recipes/466286/). > > > Couple points: > > > 1. Any container type that returns a length that isn't exactly the > > number of elements in it is broken. > > 2. The need for __nonzero__ in this case depends on a limitation in > > the language. > > 3. On the other hand, I will concede that sometimes calculating len is > > a lot more expensive than determining emptiness, and at a basic level > > it's important to avoid these costs. You have found a practical use > > case for __nonzero__. > > I thought of another one: testing whether an iterator is 'empty' (will > raise StopIteration on the next next() (3.0) call) or not. As virtual > collections, iterators generally have neither __len__ or __bool__. But > __bool__ (but only __bool__) can be added to any iterator by wrapping it > with something like the following 3.0 code (not tested): > > class look_ahead_it(): > def __init__(self, iterable): > self.it = iter(iterable) > self.fill_next() > > def __iter__(self): > return self > def __next__(self): > tem = self.next > if tem is self.empty: > raise StopIteration > else: > self.fill_next() > return tem > > empty = object() > def fill_next(self) > try: > self.next = next(self.it) > except StopIteration: > self.next = self.empty > > def __bool__(self): > return self.next is not self.empty Iterators are funny: if there's any reason you should not use "if x" it's because of them. Built-in iterators are always true, so if you're writing a function that accepts an iterable you should never use the "if x" to test whether it's empty, because it fails for a whole class of iterables. However, given that that wart exists, your example does work for "if x" and not with "if len(x)!=0". Then again, it really only works to accommodate faulty code, because no code that expects an iterable should be using that test in the first place. (Unless you wrap every iterable as soon as you get it, but then you're not bound to use __nonzero__.) Carl Banks From paul at boddie.org.uk Sat Jul 26 20:39:43 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 26 Jul 2008 17:39:43 -0700 (PDT) Subject: Pwnie awards References: Message-ID: On 27 Jul, 02:03, a... at pythoncraft.com (Aahz) wrote: > Boy, am I glad we're not listed: > > http://pwnie-awards.org/2008/awards.html An amusing mention, though: 2008-03-03: Core sends proof-of-concept code written in Python. 2008-03-05: Vendor asks for compiler tools required to use the PoC code. 2008-03-05: Core sends a link to http://www.python.org http://pwnie-awards.org/2008/awards.html#lamestvendor Paul From dullrich at sprynet.com Tue Jul 8 11:54:13 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 08 Jul 2008 10:54:13 -0500 Subject: "in"consistency? References: Message-ID: In article , Nick Dumas wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > [1,2] in [1,2,3] checks to see if the list [1,2] is an item in [1,2,3]. > Because the list [1,2,3] only contains the integers 1,2,3, the code > returns a False. Try "[1,2] in [[1,2],[2,3]]" Thanks. I understand how it works for lists and why - I was wondering why it's not the same for strings. > David C. Ullrich wrote: > > Luckily I tried it before saying no, that's > > not how "in" works: > > > >>>> 'ab' in 'abc' > > True > >>>> [1,2] in [1,2,3] > > False > > > > Is there a reason for the inconsistency? I would > > have thought "in" would check for elements of a > > sequence, regardless of what sort of sequence it was... > > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (MingW32) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iEYEARECAAYFAkhyiwEACgkQLMI5fndAv9jbiwCeKMXrAclILJMPro5VuSRgdkvB > cGkAn1igcjFWRQJSwEDOxpk3spzceZGa > =iq8L > -----END PGP SIGNATURE----- -- David C. Ullrich From bignose+hates-spam at benfinney.id.au Wed Jul 2 06:57:00 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 02 Jul 2008 20:57:00 +1000 Subject: beginner's questions - manipulating text files References: <486ABACE.9050103@umbc.edu> Message-ID: <87k5g47dvn.fsf@benfinney.id.au> C?dric Lucantis writes: > Le Wednesday 02 July 2008 01:16:30 Ben Keshet, vous avez ?crit?: > > I am trying to write a script that will search for the second and > > third appearance of the symbol '@' in a file, will read a random > > line between them, and write the line into a new file. > > If the file you're reading is not too big, you can use > file.readlines() which read all the files and returns its content as > a list of lines. Better is to iterate over the file object, getting a line each time. This works regardless of the size of the file, because it doesn't attempt to read the entirety of a large file in at once. > text.find('@') will return the position of the first occurence of > '@', or a negative value if not found. If one is interested only in *whether* text is contained within a string (and is uninterested in its position), the 'in' operator returns a boolean value. Untried code: import random separator = "@" interesting_lines = [] input_file = open("foo.txt") seen_separator_count = 0 for line in input_file: if separator in line: # Count this separator, but don't keep the line. seen_separator_count += 1 continue if seen_separator_count == 2: # We have seen exactly two lines with separators, # so we're interested in the current line. interesting_lines.append(line) if seen_separator_count >= 3: # After seeing three lines with separators, stop reading. break chosen_line = random.choice(interesting_lines) output_file = open("bar.txt", 'w') output_file.write(chosen_line) -- \ ?Smoking cures weight problems. Eventually.? ?Steven Wright | `\ | _o__) | Ben Finney From deanfamily11 at verizon.net Tue Jul 1 15:26:12 2008 From: deanfamily11 at verizon.net (Brandon) Date: Tue, 01 Jul 2008 19:26:12 GMT Subject: Convert string to char array References: <0%uak.283$4a3.73@trnddc04> <4670347e-2531-4449-a171-e352e1053864@r66g2000hsg.googlegroups.com> Message-ID: Thank you both for your help. "Mike Kent" wrote in message news:4670347e-2531-4449-a171-e352e1053864 at r66g2000hsg.googlegroups.com... On Jul 1, 2:49 pm, "Brandon" wrote: > How do I convert a string to a char array? I am doing this so I can edit > the string received from an sql query so I can remove unnecessary > characters. Answering your specific question: Python 2.5.1 (r251:54863, Mar 31 2008, 11:09:52) [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> s = 'hello' >>> l = list(s) >>> l ['h', 'e', 'l', 'l', 'o'] >>> But more generally, you might want to read up on the string methods available to you, such as replace(): http://docs.python.org/lib/string-methods.html From alexnbryan at gmail.com Wed Jul 16 17:50:05 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 14:50:05 -0700 (PDT) Subject: Having trouble with some lists in BeautifulSoup Message-ID: <18497409.post@talk.nabble.com> Okay, what I want to do with this code is to got to thesaurus.reference.com and then search for a word and get the syns for it. Now, I can get the syns, but they are still in html form and some are hyperlinks. But I can't get the contents out. I am not that familiar with BeautifulSoup. So if anyone wants to look over this code(if you run it, it will make a lot more sense) and maybe help me out. side note: if you run it, a list object will print and what I am after is the part that starts:
american... Heres the code: import urllib from BeautifulSoup import BeautifulSoup class defSyn: def __init__(self, word): self.word = word def get_syn(term): soup = BeautifulSoup(urllib.urlopen('http://thesaurus.reference.com/search?q=%s' % term)) balls = soup.findAll('table', {'width': '100%'}) print soup.prettify() for tabs in soup.findAll('table', {'width': '100%'}): yield tabs.findAll('td', {'colspan': '2'}) self.mainList = list(get_syn(self.word)) print self.mainList[2] if You have any further questions I would be happy to answer. -- View this message in context: http://www.nabble.com/Having-trouble-with-some-lists-in-BeautifulSoup-tp18497409p18497409.html Sent from the Python - python-list mailing list archive at Nabble.com. From castironpi at gmail.com Sun Jul 27 23:58:15 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 27 Jul 2008 20:58:15 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> On Jul 27, 2:39?pm, Bruno Desthuilliers wrote: > Derek Martin a ?crit : > > It's bad programming, but the world is full of bad programmers, and we > > don't always have the choice not to use their code. ?Isn't one of > > Python's goals to minimize opportunities for bad programming? > > Nope. That's Java's goal. Python's goals are to maximize opportunities > for good programming, which is quite different. +1 QOTW From ggpolo at gmail.com Mon Jul 28 18:33:38 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 28 Jul 2008 19:33:38 -0300 Subject: seemingly simple list indexing problem In-Reply-To: <488E4170.2020804@islandtraining.com> References: <488E4170.2020804@islandtraining.com> Message-ID: On Mon, Jul 28, 2008 at 7:00 PM, Gary Herron wrote: > Guilherme Polo wrote: >> >> On Mon, Jul 28, 2008 at 6:24 PM, Ervan Ensis >> wrote: >> >>> >>> My programming skills are pretty rusty and I'm just learning Python so >>> this >>> problem is giving me trouble. >>> >>> I have a list like [108, 58, 68]. I want to return the sorted indices of >>> these items in the same order as the original list. So I should return >>> [2, >>> 0, 1] >>> >> >> You could simply do this: >> >> a = [108, 58, 68] >> b = sorted(a) >> [b.index(c) for c in a] >> > > Yuck. Slow, and it fails if duplicate list elements exist. It wasn't supposed to be the fastest solution, also, he didn't mention duplicated items. > > Also... This looks like a beginners programming assignment. Let's let > him try it himself. We can offer help rather than full solutions if he has > specific Python questions. > > > > > >> >>> >>> For a list that's already in order, I'll just return the indices, i.e. >>> [56, >>> 66, 76] should return [0, 1, 2] >>> >>> Any help would be appreciated. >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> >> >> >> > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From wolfram.hinderer at googlemail.com Thu Jul 10 17:59:13 2008 From: wolfram.hinderer at googlemail.com (wolfram.hinderer at googlemail.com) Date: Thu, 10 Jul 2008 14:59:13 -0700 (PDT) Subject: Can this program be shortened? Measuring program-length? References: <7Rtdk.16747$N87.3559@nlpi068.nbdc.sbc.com> Message-ID: <2ed6de5b-bf2f-4e3d-94af-c8e6c6a28f95@s50g2000hsb.googlegroups.com> On 10 Jul., 21:57, "r.e.s." wrote: > Can the following program be shortened? ... > > def h(n,m): > E=n, > while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n > return n > h(9,9) > Some ideas... # h is your version def h(n,m): E=n, while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n return n def g(n,m): E=n, while E*m:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n return n def f(n,m): E=n, while E*m:n=h(n+1,m-1);E=(E[0]>0)*(E[0]-1,)*n+E[1:] return n def e(n,m): E=[n] while E*m:n=h(n+1,m-1);E[:1]=(E[0]>0)*[E[0]-1]*n return n # some tests print h(1,1), h(2,1), h(0,2) print g(1,1), g(2,1), g(0,2) print f(1,1), f(2,1), f(0,2) print e(1,1), e(2,1), e(0,2) From kotecha.ravi at googlemail.com Mon Jul 21 17:05:02 2008 From: kotecha.ravi at googlemail.com (Ravi Kotecha) Date: Mon, 21 Jul 2008 14:05:02 -0700 (PDT) Subject: Getting the name of a variable which was used as a function parameter. References: <9e2e64db-d594-408d-9418-b17133f23204@27g2000hsf.googlegroups.com> <6ekbg0F6vgp3U5@mid.uni-berlin.de> Message-ID: <9c24ced1-4a0b-4e04-9ce2-1d730e3d8dd7@d77g2000hsb.googlegroups.com> Of course I wouldn't, it is a total hack, mostly useless but fun. I tried to do it after someone in #python efnet said it was impossible! On Jul 21, 9:56?pm, Marc 'BlackJack' Rintsch wrote: > On Mon, 21 Jul 2008 09:01:10 -0700, Ravi Kotecha wrote: > > I thought this was pretty cool and since I spent 30 mins or so > > goggling before giving up and figuring out myself I thought I'd share > > it with you. > > >>>> def a(a): > > ... ? ? for k,v in sys._getframe(1).f_locals.items(): > > ... ? ? ? ? if id(v) == id(a): > > ... ? ? ? ? ? ? print k > > ... > > >>>> hello = 123 > > >>>> a(hello) > > hello > > > ## pretty cool. > > Or ugly hack. ?Beauty lies in the eye of the beer holder? > > > It's totally useless but I wanted to do it for logging purposes. > > Don't use such things in production code, please. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch From arsyed at gmail.com Tue Jul 22 05:56:32 2008 From: arsyed at gmail.com (arsyed) Date: Tue, 22 Jul 2008 05:56:32 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: <9a2cc7a70807220256k543365d3y3f4832239d955bac@mail.gmail.com> On Tue, Jul 22, 2008 at 5:21 AM, Martin Gregorie wrote: > On Tue, 24 Jun 2008 18:42:15 -0400, John W Kennedy wrote: > >> David Combs wrote: >>> passing >>> *unnamed* functions as args (could Algol 60 also do something like that, >>> via something it maybe termed a "thunk") >> >> No, the "thunks" were necessary at the machine-language level to >> /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. >> > Are you sure about that? > > The first time I ran across the term "thunking" was when Windows 3 > introduced the Win32S shim and hence the need to switch addressing between > 16 bit and 32 bit modes across call interfaces. That was called "thunking" > by Microsoft and even they would surely admit it was a kludge. > > I used Algol 60 on an Elliott 503 and the ICL 1900 series back when it was > a current language. The term "thunking" did not appear in either compiler > manual nor in any Algol 60 language definition I've seen. A60 could pass > values by name or value and procedures by name. That was it. Call by name > is what is now referred to as reference passing. > On Tue, Jul 22, 2008 at 5:21 AM, Martin Gregorie wrote: > On Tue, 24 Jun 2008 18:42:15 -0400, John W Kennedy wrote: > >> David Combs wrote: >>> passing >>> *unnamed* functions as args (could Algol 60 also do something like that, >>> via something it maybe termed a "thunk") >> >> No, the "thunks" were necessary at the machine-language level to >> /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. >> > Are you sure about that? > > The first time I ran across the term "thunking" was when Windows 3 > introduced the Win32S shim and hence the need to switch addressing between > 16 bit and 32 bit modes across call interfaces. That was called "thunking" > by Microsoft and even they would surely admit it was a kludge. > > I used Algol 60 on an Elliott 503 and the ICL 1900 series back when it was > a current language. The term "thunking" did not appear in either compiler > manual nor in any Algol 60 language definition I've seen. A60 could pass > values by name or value and procedures by name. That was it. Call by name > is what is now referred to as reference passing. > Thunk has more than one meaning. The ALGOL 60 usage predates Windows obviously. Also, call-by-name is distinct from call-by-reference. See: http://en.wikipedia.org/wiki/Evaluation_strategy And, for fun with call-by-name: http://en.wikipedia.org/wiki/Jensen%27s_Device http://en.wikipedia.org/wiki/Man_or_boy_test From rNOSPAMon at flownet.com Fri Jul 4 18:30:30 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Fri, 04 Jul 2008 15:30:30 -0700 Subject: Parsing MIME-encoded data in an HTTP request References: <3a11k5-al7.ln1@nb2.stroeder.com> Message-ID: In article <3a11k5-al7.ln1 at nb2.stroeder.com>, Michael Str?der wrote: > Ron Garret wrote: > > I'm writing a little HTTP server and need to parse request content that > > is mime-encoded. All the MIME routines in the Python standard library > > seem to have been subsumed into the email package, which makes this > > operation a little awkward. > > How about using cgi.parse_multipart()? > > Ciao, Michael. Unfortunately cgi.parse_multipart doesn't handle nested multiparts, which the requests I'm getting have. You have to use a FieldStorage object to do that, and that only works if you're actually in a cgi environment, which I am not. The server responds to these requests directly. Anyway, thanks for the idea. rg From mail at timgolden.me.uk Mon Jul 28 11:56:58 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 28 Jul 2008 16:56:58 +0100 Subject: Encoding for Devanagari Script. In-Reply-To: References: Message-ID: <488DEC4A.2040603@timgolden.me.uk> Atul. wrote: > Hi Fredrik and Terry, > > Well I got this on IDLE I think I have done something wrong. > >>>> import codecs >>>> f = open("C:\Documents and Settings\admin\My Documents\corpus\dainaikAikya collected by sushant.txt","r", "utf_8") > > Traceback (most recent call last): > File "", line 1, in > f = open("C:\Documents and Settings\admin\My Documents\corpus > \dainaikAikya collected by sushant.txt","r", "utf_8") > TypeError: an integer is required > > PS: the above code I wrote using the information from the Library > Reference pdf section 4.8 "Codecs". Something wrong I am doing? Please > do let me know. Only slightly. You're importing the codecs module but you're not using it. So you're *actually* using the built-in open function, which doesn't have an encoding parameter. It does have a third param which is to do with the buffer size. Just change your code to use codecs.open ("...") and, I suggest, either use raw strings for your filename (r"c:\docume...") or use the other kind of slash ("c:/documen..."). Otherwise you might run into some problems. TJG From thomas.troeger.ext at siemens.com Thu Jul 31 09:16:38 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Thu, 31 Jul 2008 15:16:38 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> <873alq9r2q.fsf@nokile.rath.org> Message-ID: > That would imply that I cannot create instances of a type, only of > a class that implements the type, wouldn't it? > > But Python denotes 'int' as a type *and* I can instantiate it. Now I start getting confused also ;-) >>> a=5 >>> a.__class__ >>> a.__class__.__class__ >>> dir(a) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] I think in Python everything is implemented as a class which makes sense. AFAIK you can implement a certain interface in a custom class and it behaves like, for example, a builtin integer. But I guess one of the gurus can clarify this matter with an appropriate URL ;-) From robert.rawlins at thinkbluemedia.co.uk Tue Jul 8 08:18:15 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 8 Jul 2008 13:18:15 +0100 Subject: Logger Configuration Message-ID: <001d01c8e0f4$b2c0c900$18425b00$@rawlins@thinkbluemedia.co.uk> Hello guys, I've attached an example of my logging configuration file for you to look at. The problem I'm experiencing is that the log files are not rotating as I would expect them to, they just keep growing and growing. Can you see any reason for this to happen? This is the first time I've used a config file and not just configured the logger programmatically. Thanks guys, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: logging.conf Type: application/octet-stream Size: 391 bytes Desc: not available URL: From steven at REMOVE.THIS.cybersource.com.au Mon Jul 28 21:12:46 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 01:12:46 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <488e4d2d$0$5967$ba624c82@nntp06.dk.telia.net> <009e5e66$0$20313$c3e8da3@news.astraweb.com> Message-ID: On Tue, 29 Jul 2008 00:23:02 +0000, Steven D'Aprano wrote: > Dude. Dude. Just... learn some Python before you embarrass yourself > further. I'm sorry Anders, that was a needlessly harsh thing for me to say. I apologize for the unpleasant tone. Still, __nonzero__ is a fundamental part of Python's behaviour. You should learn about it. -- Steven From gary at byoteki.com Sat Jul 26 14:57:30 2008 From: gary at byoteki.com (Gary Josack) Date: Sat, 26 Jul 2008 14:57:30 -0400 Subject: Simple Path issues In-Reply-To: <7bef6df9-45d6-4ef6-b802-1dd201ec66e3@k30g2000hse.googlegroups.com> References: <7bef6df9-45d6-4ef6-b802-1dd201ec66e3@k30g2000hse.googlegroups.com> Message-ID: <488B739A.5070603@byoteki.com> Brett Ritter wrote: > New to Python, and I have some questions on how to best set up a basic > development environment, particular relating to path issues. > > Note: I am not root on my development box (which is some flavor of > BSD) > > Where should I develop my own modules so as to refer to them in the > standard way. I.E. I want: > import proj > > to work regardless of my current working directory, and to function as > if "proj" were a core or third-party module. > > I saw that I can set PYTHONPATH, but that seems sub-prime. I noted > that in installing pysqlite (the local installation of python is 2.4) > that I had it install in a lib under my home dir...should I use that > locale? > > What is the command to tell me what directories python is checking in? > > While I'm at it, what is the best (read: standard) locale to stick my > test cases? same dir as my project? A subdir? > > Thanks in advance > -- > http://mail.python.org/mailman/listinfo/python-list > sys.path is a list that will tell you where python is looking. You can append to this in your scripts to have python look in a specific directory for your own modules. Thanks, Gary M. Josack From ojeeves at gmail.com Tue Jul 1 09:13:57 2008 From: ojeeves at gmail.com (oj) Date: Tue, 1 Jul 2008 06:13:57 -0700 (PDT) Subject: recursive import Message-ID: <54205cc0-8fc6-41f3-86bc-1f88b911bc62@f36g2000hsa.googlegroups.com> Hi, I'm just toying around with some ideas at the moment. Is there an easy and safe way to recursivly import all modules under a particular namespace? Say, I had modules: foo foo.bar foo.bar.baz foo.baz bar bar.baz I want to import all the modules in the foo namespace, so the first four modules in that list. Other then having those modules explicitly import their children, or explicitly importing them all from where I want to use them, can I do this? Should I do this? The idea is that function decorates 'register' functions in those modules, so they become available without having to have a list of all the modules that contain them, and without all the modules necessarily needing to know about each other. From norseman at hughes.net Wed Jul 16 13:28:46 2008 From: norseman at hughes.net (norseman) Date: Wed, 16 Jul 2008 10:28:46 -0700 Subject: how can i save my command prompt screen? Message-ID: <487E2FCE.6070508@hughes.net> Ty hensons wrote: > how can i save my command prompt screen? ============================================== That by itself leaves lots of questions. Taken literally to be the "box" then: In Microsoft use the "Print Screen" followed by mspaint and Edit/paste (Or SHIFT-PrintScreen if whole screen showed up, I forget which it is. One does just the box that is hot while the other gets all) In Unix use xwd. See man xwd and xwud. Also man convert with box open and text you want for show'n'tell visible xwd>screen_1.xwd (click in box of choice) to view results: xwud Vanam wrote... > I want to know whether is there anything that has > to be installed in addition to python 2.5 > > from gasp import * You have to install the 'gasp' package too. https://launchpad.net/gasp-code/stable-0.1.x/0.1.1 -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From bruno.desthuilliers at gmail.com Tue Jul 1 16:46:48 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Tue, 1 Jul 2008 13:46:48 -0700 (PDT) Subject: Please check my understanding... References: Message-ID: <3e82eab6-6df1-4a16-83d8-96a22ad247cf@k37g2000hsf.googlegroups.com> On 1 juil, 21:35, Tobiah wrote: > list.append([1,2]) will add the two element list as the next > element of the list. list.append(obj) will add obj as the last element of list, whatever type(obj) is. > list.extend([1,2]) is equivalent to list = list + [1, 2] Not quite. The second statement rebinds the name list (a very bad name BTW but anyway...) to a new list object composed of elements of the list object previously bound to the name list and the elements of the anonymous list object [1, 2], while the first expression modifies the original list object in place. The results will compare equal (same type, same content), but won't be identical (not the same object). A better definition for list.extend(iterable) is that it is equivalent to: for item in iterable: list.append(item) The difference is important if list is bound to other names. A couple examples: a = [1, 2, 3} b = a # b and a points to the same list object b is a => True a.append(4) print b => [1, 2, 3, 4] b.extend([5, 6]) print a => [1, 2, 3, 4, 5, 6] a = a + [7, 8] print b => [1, 2, 3, 4, 5, 6] print a => [1, 2, 3, 4, 5, 6, 7, 8] a is b => False def func1(lst): lst.extend([9, 10]) print lst def func2(lst): lst = lst + [11, 12] print lst func1(a) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print a => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] func2(a) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] print a => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > Is that the only difference? cf above. > From the manual: > > s.extend(x) | same as s[len(s):len(s)] = x > > But: (python 2.5.2) > > >>> a > [1, 2, 3] > >>> a[len(a):len(a)] = 4 > > Traceback (most recent call last): > File "", line 1, in > TypeError: can only assign an iterable And if you try with extend, you'll also have a TypeError: a.extend(4) => Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not iterable list.extend expects an iterable, and so does slice assignment. You want: a[len(a):len(a)] = [4] > > Also, what is the difference between list[x:x] and list[x]? The first expression refers to the *sublist* starting at x and ending one element before x. Of course, if x == x, then it refers to an empty list !-) >>> a[3:3] [] >>> a[1:3] [2, 3] >>> a[0:2] [1, 2] >>> a[0:1] [1] >>> The second expression refers to the *element* at index x. HTH From mnordhoff at mattnordhoff.com Sun Jul 6 21:19:58 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 07 Jul 2008 01:19:58 +0000 Subject: mirroring files and data via http In-Reply-To: References: Message-ID: <48716F3E.3020509@mattnordhoff.com> Steve Potter wrote: > I'm working on a project to create a central administration interface > for several websites located on different physical servers. > > You can think of the websites as a blog type application. My > administration application will be used to create new blog posts with > associated media (images, etc..) > > So I am thinking to setting up a script on each of the sites to "phone > home" once per day and download any new posts and media files. > > I am thinking of transmitting the post data in an xml format that > could then be decoded an recorded into the database on the slave > site. Are there any easy ways to encode a python dictionary to and > from xml? > > For the media files I am thinking that the administration interface > would also provide an xml file with a list of all of the media files > required along with an http path to retrieve them and a checksum of > some sort to verify that they were downloaded correctly. > > Basically I am trying to figure out if anything already exists to > perform some of these functions or if I have to make them from > scratch. I know none of it should be too hard, but I hate to re- > invent the wheel. > > Thanks, > > Steven Potter It sounds like JSON would be perfect for this. For working with it in Python, the simplejson module is popular: -- From jcd at sdf.lonestar.org Tue Jul 15 14:48:18 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 15 Jul 2008 14:48:18 -0400 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: <1216147698.27311.12.camel@aalcdl07.lib.unc.edu> On Tue, 2008-07-15 at 14:37 -0400, Victor Noagbodji wrote: > Hello, > > what's the difference between these two statement? And which one should one use? > Aside: Please include all relevant information in the *body* of your post, not just the subject header. The two statements in question are: if name is not None: and if name: The difference? name='' if name is not None: print "name is not None." if name: print "name is." Give it a whirl. Cheers, Cliff From bdesth.quelquechose at free.quelquepart.fr Sun Jul 27 14:37:30 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Jul 2008 20:37:30 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> <5d3729f0-6e5d-4e3f-b4ed-e25f8ebc655f@q5g2000prf.googlegroups.com> <43d32584-e762-4578-82d9-0d4395bb4138@k36g2000pri.googlegroups.com> Message-ID: <488cdc61$0$7006$426a74cc@news.free.fr> Lawrence D'Oliveiro a ?crit : > In message > <43d32584-e762-4578-82d9-0d4395bb4138 at k36g2000pri.googlegroups.com>, > s0suk3 at gmail.com wrote: > >> "Support OO but it doesn't have to"? That sounds like saying that in >> some Python implementations you'll be able to use OO, but that you >> just might bump into a Python distribution ... > > Change "distribution" to "program" and you're on the right track. Since just everything that can be bound to a name is actually an object, I don't see how you could do anything in Python without using objects. Now if what you meant is that nothing in Python forces you into designing your program the OO way, then Java is not an OOPL neither (never seen a Java program where you have classes with only static methods and classes with only public attributes - IOW, functions and structs ?). From fetchinson at googlemail.com Sat Jul 5 17:40:12 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 5 Jul 2008 14:40:12 -0700 Subject: Python with Ecmascript In-Reply-To: <486fe241$0$867$ba4acef3@news.orange.fr> References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <486fe241$0$867$ba4acef3@news.orange.fr> Message-ID: > Ecmascript (Jscript) is Active-Scripting compliant. > With PyWin32, you can : > - call JScript functions (with parameters) > - define pieces of code (& run it) > > Another way, is to drive Internet-Explorer (via COM). You can set the > IE-Windows as invisible, and connect the motor of execution (of > JScript). Then, you can : > - call JScript functions, with parameters et return ; variables, but > also array (<=> lists) > - connect to JScripts's objects (for read/write) > - write new functions in JScript > - etc. Is there a way to do similar things on linux? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From socyl at 987jk.com.invalid Fri Jul 18 11:49:49 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 18 Jul 2008 15:49:49 +0000 (UTC) Subject: x, = y (???) References: Message-ID: In Matthew Woodcraft writes: >kj wrote: >> I still don't get it. If we write >> >> y = 'Y' >> x, = y >> >> what's the difference now between x and y? And if there's no >> difference, what's the point of performing such "unpacking"? >If y really is is a string, I think it's likely that the line you came >across was a typo. OK, this is the best explanation I've seen for the code I'm talking about. This code may be found at: http://norvig.com/sudo.py in the definition of the function eliminate. Here's the fragment: elif len(values[s]) == 1: ## If there is only one value (d2) left in square, remove it from peers d2, = values[s] Now, in the assignment, values[s] *is* a string of length 1. So this assignment appears to me entirely equivalent (in its ultimate effect) to the more straightforward d2 = values[s] ...but, since I'm a noob, I thought I'd ask :-) Thanks! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From invalid at nowhere.invalid.org Tue Jul 15 05:09:54 2008 From: invalid at nowhere.invalid.org (Alex Marandon) Date: Tue, 15 Jul 2008 10:09:54 +0100 Subject: Testing for Internet Connection In-Reply-To: References: Message-ID: <1216113021.24038.0@proxy02.news.clara.net> Alexnb wrote: > I am wondering, is there a simple way to test for Internet connection? If > not, what is the hard way :p Trying to fetch the homepage from a few major websites (Yahoo, Google, etc.)? If all of them are failing, it's very likely that the connection is down. You can use urllib2 [1] to accomplish that. [1] From moijes12 at gmail.com Fri Jul 11 04:23:07 2008 From: moijes12 at gmail.com (moijes12) Date: Fri, 11 Jul 2008 01:23:07 -0700 (PDT) Subject: importing .dll in a python file Message-ID: <4dfaeb7b-8e7e-4f0b-80a8-ed24ed1c46d3@x35g2000hsb.googlegroups.com> Hi I need to use a .dll from a python script.I have installed pywin.But in the program ,which is like: import dllName I get : Import Error : DLL not found Please suggest a solution! From arnimavidyarthy at gmail.com Fri Jul 18 11:01:56 2008 From: arnimavidyarthy at gmail.com (arni) Date: Fri, 18 Jul 2008 08:01:56 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> Message-ID: <292d640d-1c84-4f7c-8b57-1db23e53aeff@f1g2000prb.googlegroups.com> On Jul 18, 7:51?pm, Andrew Freeman wrote: > Andrew Freeman wrote: > > oj wrote: > >> On Jul 18, 12:10 pm, John Machin wrote: > > >>> On Jul 18, 9:05 pm, oj wrote: > > >>>> On Jul 18, 11:33 am, arnimavidyar... at gmail.com wrote: > > >>>>> Hi, > >>>>> ? ? ? ? Hi, > >>>>> ? ? ? ? I am taking a string as an input from the user and it > >>>>> should only > >>>>> contain the chars:L , M or R > >>>>> ? ? ? ? I tried the folllowing in kodos but they are still not > >>>>> perfect: > >>>>> ? ? ? ? [^A-K,^N-Q,^S-Z,^0-9] > >>>>> [L][M][R] > >>>>> [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > >>>>> ? ? ? ? For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' > >>>>> .like that. > >>>>> ? ? ? ? regards, > >>>>> SZ > >>>>> ? ? ? ? The string may or may not have all the three chars. > > >>>> With regular expressions, [^LRM] matches a character that isn't L, R > >>>> or M. So: > >>>> ? ? ? import re > >>>> ? ? ? var = "LRLRLRLNR" > >>>> ? ? ? if re.search(r'[^LRM]', var): > >>>> ? ? print "Invalid" > > >>> Fails if var refers to the empty string. > > >> No it doesn't, it succeeds if var is an empty string. An empty string > >> doesn't contain characters that are not L, R or M. > > >> The OP doesn't specify whether an empty string is valid or not. My > >> interpretation was that an empty string would be valid. > > > Why not just use * instead of + like: > > > if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of > > string; $ means end of string > > ? ?print "Invalid" > > > This will *only* print invalid when there is a character other than L, > > R, or M or a empty string. > > Sorry, forget the beginning and ending markers, I just tried it out, it > doesn't work. > use this instead: > > if re.search(r'[^LRM]*', var): > ? ?print "Invalid" I was using kodos to check the regex.I should have used the IDE instead.Thanks a lot again. From robert.rawlins at thinkbluemedia.co.uk Wed Jul 16 07:38:50 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Wed, 16 Jul 2008 12:38:50 +0100 Subject: Logging in __del__() In-Reply-To: References: <17056.2125546441$1216121658@news.gmane.org> Message-ID: <011001c8e738$8483bcb0$8d8b3610$@rawlins@thinkbluemedia.co.uk> Hi Vinay, > Python uses reference counting with a cycle detector, but the > detector's behaviour is different if there are finalizers (__del__) - > see > > http://www.python.org/doc/ext/refcounts.html > Thank you for the link, that certainly explains a great deal. So, am I right to assume that python will still handle its garbage disposal if I implement __del__(), it just handles circular references in a slightly different way, but to the same effect. Right? Cheers, Robert From xkenneth at gmail.com Mon Jul 7 17:39:36 2008 From: xkenneth at gmail.com (xkenneth) Date: Mon, 7 Jul 2008 14:39:36 -0700 (PDT) Subject: Emacs/Python Essentials? Message-ID: What does everyone consider essential for emacs python dev? Regards, Ken From moneymakecash2 at gmail.com Thu Jul 24 13:18:28 2008 From: moneymakecash2 at gmail.com (MERLIN) Date: Thu, 24 Jul 2008 10:18:28 -0700 (PDT) Subject: Free Online Trading Courses - Online Trading Academy - Stock Trading ... Message-ID: <32d526d4-785b-4f3b-b8f7-cbaf907d7f08@v39g2000pro.googlegroups.com> Free Online Trading Courses - Online Trading Academy - Stock Trading ... ____________________ http://dayonlinetrading.blogspot.com _________________ From stefan_ml at behnel.de Thu Jul 31 01:59:28 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 31 Jul 2008 07:59:28 +0200 Subject: Unicode characters, XML/RSS In-Reply-To: <832add51-92e1-4420-9279-5b503b453869@u6g2000prc.googlegroups.com> References: <832add51-92e1-4420-9279-5b503b453869@u6g2000prc.googlegroups.com> Message-ID: <489154C0.3060401@behnel.de> Adam W. wrote: > File "C:\Python25\lib\xml\sax\expatreader.py", line 207, in feed > self._parser.Parse(data, isFinal) > File "C:\Users\Adam\Desktop\Rev3 DL\XMLWorkspace.py", line 51, in > characters > self.data.append(string) > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in > position 236: ordinal not in range(128) You seem to be doing an implicit conversion from a unicode string to a byte string, maybe by concatenating ('+' operator) strings of different types or by writing it out into a file (or printing it, or ...) - I don't know what self.data is or does, since you didn't provide any code. Stefan From siona at chiark.greenend.org.uk Mon Jul 28 10:15:54 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 28 Jul 2008 15:15:54 +0100 (BST) Subject: xml.dom's weirdness? References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> <488C3645.8060304@behnel.de> <488c75ee$0$29448$9b4e6d93@newsspool4.arcor-online.net> Message-ID: Stefan Behnel wrote: >Using my system Python (2.5.1 on Ubunutu Gutsy): > > $ strace -e open python -c '' 2>&1 | wc -l > 551 > $ strace -e open python -c '<><<' 2>&1 | wc -l > 4631 > >Using a self-built Python I have lying around: > > $ strace -e open python2.3 -c '' 2>&1 | wc -l > 210 > $ strace -e open python2.3 -c '<><<' 2>&1 | wc -l > 214 > > $ strace -e open python2.6 -c '' 2>&1 | wc -l > 138 > $ strace -e open python2.6 -c '<><<' 2>&1 | wc -l > 142 > >Blame Ubuntu/Debian. I'd be wary about including Debian in that blame. Using 4.0 here, with a 2.4.4 default and a 2.5.0 straight from the package: $ strace -e open python -c '' 2>&1 | wc -l 171 $ strace -e open python -c '<><<' 2>&1 | wc -l 175 $ strace -e open python2.5 -c '' 2>&1 | wc -l 105 $ strace -e open python2.5 -c '<><<' 2>&1 | wc -l 109 -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From sjmachin at lexicon.net Tue Jul 1 20:29:52 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 1 Jul 2008 17:29:52 -0700 (PDT) Subject: convert unicode characters to visibly similar ascii characters References: <17d4c282-8606-4d29-9e71-d34f5e6d13bb@m44g2000hsc.googlegroups.com> Message-ID: On Jul 2, 9:55 am, Jim wrote: > Peter Bulychev wrote: > > I want to convert unicode character into ascii one. > > You have to make some arbitrary choices of what to translate. Based > on some materials on effbot's site, and a recipe, I made > ftp://alan.smcvt.edu/hefferon/unicode2ascii.py > which has at least some of what you are looking for. > $ grep HYPHEN unicode2ascii.py > u'\N{SOFT HYPHEN}':u'-', > u'\N{HYPHEN}':u'-', > u'\N{NON-BREAKING HYPHEN}':u'-', > u'\N{SOFT HYPHEN}': '-', > No doubt I have some terrible gaffes and some things missing. > Corrections appreciated. Comments on the above grep output: 1. You have SOFT HYPHEN twice, mapping it to u'-' and '-' 2. The idea of a soft hyphen is as a hint to a hyphenator about where to insert a hyphen if one is necessary and the hyphenator is suspected of acting cluelessly without the hint. IMHO, asciification should substitute u'', not u'-'. 3. Read PEP 8. s/:/: / Cheers, John From martinnorth at westnet.com.au Fri Jul 11 21:02:54 2008 From: martinnorth at westnet.com.au (martinnorth) Date: Sat, 12 Jul 2008 11:02:54 +1000 Subject: MySQLdb will only import for root In-Reply-To: <6dothnF3lqqmU1@mid.uni-berlin.de> References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> <6dothnF3lqqmU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > martinnorth schrieb: >> Hi, >> >> I am running Python and MySQL on Ubuntu and have installed MySQLdb. If >> I try to import MySQLdb I get the following error: >> >> ActivePython 2.5.2.2 (ActiveState Software Inc.) based on >> Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08) >> [GCC 3.3.1 (SuSE Linux)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import MySQLdb >> Traceback (most recent call last): >> File "", line 1, in >> ImportError: No module named MySQLdb >> >> But if I lrun python as the root user it imports fine. Can anyone >> suggest what might be wrong with the installation? Or is there nothing >> wrong? I haven't seen any examples that mentioned being root to import >> a module. > > Try importing sys and printing out sys.path both with a "normal" account > and the root-account, to see if there are any differences. And of course > make sure both actually use the same interpreter. > > Beyond that, you are right: there is no root-only-importing. > > Diez Now that I look at, it appears it might not be the same interpreter. When running python as root I get: Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. Which is completely different from when I'm a normal user (see original post). And yes, sys.path is different. Being somewhat new to python and linux, how would I go about fixing this? How do I get a normal user to run the same interpreter? Is it to do with my PATH? Martin From ojeeves at gmail.com Wed Jul 2 08:55:34 2008 From: ojeeves at gmail.com (oj) Date: Wed, 2 Jul 2008 05:55:34 -0700 (PDT) Subject: n00bie wants advice. References: <8757c630-0518-4351-a319-124ced0ac92c@w4g2000prd.googlegroups.com> Message-ID: <08fa3c12-07bf-467f-a098-c4c3b373a1a3@y38g2000hsy.googlegroups.com> On Jul 2, 7:25?am, bsag... at gmail.com wrote: > This simple script writes html color codes that can be viewed in a > browser. ?I used short form hex codes (fff or 000, etc) and my list > has only six hex numbers otherwise the results get rather large. I > invite criticism as to whether my code is "pythonic". Are there other > ways to generate the hex combos besides the nested "for" loops? Thanks > in advance, Bill > > list = ['3','6','9','b','d','f'] > > s = '\n' > > for a in list: > ? ? ? ? for b in list: > ? ? ? ? ? ? ? ? for c in list: > ? ? ? ? ? ? ? ? ? ? ? ? s += '

'+ a + b + c +'

> \n' > > s += '' > > f = open('c:/x/test.htm', 'w') > f.write(s) > f.close() You could write the loop like this: for red, green, blue in [(r, g, b) for r in list for g in list for b in list]: s += blah blah blah but, arguably, that isn't easier to read or understand. It's a matter of taste, I guess. As has already been mentioned, list is not a good name, because it is already used. Also, personally, I find it easier to read strings that aren't constructed with concatenation, but using pythons string formatting gubbins: '

' % (red, green, blue) Again, I think this is mostly personal preference. From deets at nospam.web.de Wed Jul 2 16:56:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Jul 2008 22:56:44 +0200 Subject: Run interpreter in emacs? In-Reply-To: References: Message-ID: <6d28ccFftk4U1@mid.uni-berlin.de> defn noob schrieb: > Can I run the python interpreter from with in Emacs? Yes, the python-mode supports that. Make sure to install the proper one http://www.emacswiki.org/cgi-bin/wiki/PythonMode > Do i have to change anything then? or is it by default? it already > syntax-highlights python-files. See above for docs. Diez From noagbodjivictor at gmail.com Tue Jul 15 15:44:25 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Tue, 15 Jul 2008 15:44:25 -0400 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: >>what's the difference between these two statement? >one checks if the given object is not None, the other checks if it's a true value: >http://docs.python.org/ref/Booleans.html#Booleans >>And which one should one use? >depends on what you want to test for, of course. > > Well that's exactly why I'm asking. Since None returns False in if statements. Why do people use if name is not None: instead of simply writing if not name? -- NOAGBODJI Paul Victor From amdescombes at gmail.com Mon Jul 21 12:50:29 2008 From: amdescombes at gmail.com (AMD) Date: Mon, 21 Jul 2008 18:50:29 +0200 Subject: scanf in python Message-ID: <4884be5e$0$19722$426a74cc@news.free.fr> Hello, I often need to parse strings which contain a mix of characters, integers and floats, the C-language scanf function is very practical for this purpose. I've been looking for such a feature and I have been quite surprised to find that it has been discussed as far back as 2001 but never implemented. The recommended approach seems to be to use split and then atoi or atof or to use regex and then atoi and atof. Both approaches seem to be a lot less natural and much more cumbersome than scanf. If python already has a % string operator that behaves like printf, why not implement either a %% or << string operator to behave like scanf, use could be like the followng: a, b, c = "%d %f %5c" %% "1 2.0 abcde" or a, b, c = "%d %f %5c" << "1 2.0 abcde" %% is closer to the % operator << seems more intuitive to me either of this methods seems to me much simpler than: lst = "1 2;0 abcde".split() a = int(lst[0]) b = float(lst[1]) c = lst[2] or even worse when using regular expressions to parse such simple input. I like python because it is concise and easy to read and I really think it could use such an operator. I know this has been discussed before and many times, but all previous threads I found seem to be dead and I would like to invite further investigation of this topic. Cheers, Andr? M. Descombes From larry.bates at websafe.com` Mon Jul 28 13:26:03 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 28 Jul 2008 12:26:03 -0500 Subject: Suggestions for creating a PDF table In-Reply-To: References: Message-ID: Kirk Strauser wrote: > Short question: > > Is there a good library for generating HTML-style tables with the equivalent > of colspans, automatically sized columns, etc. that can render directly to > PDF? > > Longer question: > > I'm re-doing a big chunk of locally-written code. I have a > report-generating function that takes a list of lists of lists as input and > returns either a PDF, an HTML table, or an Excel spreadsheet as requested. > For example, input might look like: > > makereport('html', > headers=['Invoice number', 'Customer', 'Price'], > data=[ > [['123', 'John Doe', '$50.00'], > ['Ordered on 2008-01-01 via the website']], > [['124', 'Peter Bilt', '$25.99'], > ['Mail via African swallow']] > ]) > > This would result in HTML like: > > > > > > > > > > > > > > > > > > > > > > > >
Invoice numberCustomerPrice
123John Doe$50.00
Ordered on 2008-01-01 via the website
124Peter Bilt$25.99
Mail via African swallow
> > Note particularly how the explanatory notes for each invoice are similar in > appearance to the "primary" report lines they're associated with. > > Now, I have a similar transformation to PDF via pdflatex. This works fairly > well but requires a bunch of temp files and subprocesses, and I've never > been 100% happy with the LaTeX output (you have to calculate your own > column widths, for instance). Since I plan to re-write this anyway, I'd > like to find a more widely used library if one was available. > > ReportLab seemed *almost* perfect, except that it doesn't support colspans. > As I hope I demonstrated in the example, most of our reports depend on that > ability. > > So, again, any thoughts on a PDF generator that can generate tables with the > same kind of flexibility as HTML? It does support the equivalent of colspans. See page 75 of the userguide manual. -Larry From mrkafk at gmail.com Fri Jul 11 13:02:15 2008 From: mrkafk at gmail.com (mk) Date: Fri, 11 Jul 2008 19:02:15 +0200 Subject: Using SWIG to build C++ extension Message-ID: Hello, I'm having terrible problems building C++ extension to Python 2.4 using SWIG. I'd appreciate if somebody knowledgeable at the subject took a look at it. swig-1.3.29, g++ (GCC) 4.1.1 20070105 (Red Hat 4.1.1-52). I used following commands to build C++ extension: # swig -c++ -python edit_distance.i # c++ -c edit_distance.c edit_distance_wrap.cxx edit_distance.cpp -I. -I/usr/include/python2.4 Linux RH (9.156.44.105) root ~/tmp # c++ -c edit_distance.c edit_distance_wrap.cxx edit_distance.cpp -I. -I/usr/include/python2.4 c++: edit_distance.cpp: No such file or directory edit_distance_wrap.cxx: In function ?PyObject* _wrap_edit_distance(PyObject*, PyObject*)?: edit_distance_wrap.cxx:2579: error: ?string? was not declared in this scope edit_distance_wrap.cxx:2579: error: ?arg1? was not declared in this scope edit_distance_wrap.cxx:2580: error: ?arg2? was not declared in this scope edit_distance_wrap.cxx:2597: error: expected type-specifier before ?string? edit_distance_wrap.cxx:2597: error: expected `>' before ?string? edit_distance_wrap.cxx:2597: error: expected `(' before ?string? edit_distance_wrap.cxx:2597: error: expected primary-expression before ?>? token edit_distance_wrap.cxx:2597: error: expected `)' before ?;? token edit_distance_wrap.cxx:2605: error: expected type-specifier before ?string? edit_distance_wrap.cxx:2605: error: expected `>' before ?string? edit_distance_wrap.cxx:2605: error: expected `(' before ?string? edit_distance_wrap.cxx:2605: error: expected primary-expression before ?>? token edit_distance_wrap.cxx:2605: error: expected `)' before ?;? token What's weird is that I _did_ use std:: namespace prefix carefully in the code: #include #include #include const unsigned int cost_del = 1; const unsigned int cost_ins = 1; const unsigned int cost_sub = 1; unsigned int edit_distance( std::string& s1, std::string& s2 ) { const size_t len1 = s1.length(), len2 = s2.length(); std::vector > d(len1 + 1, std::vector(len2 + 1)); for(int i = 1; i <= len1; ++i) for(int j = 1; j <= len2; ++j) d[i][j] = std::min(d[i - 1][j] + 1, std::min(d[i][j - 1] + 1, d[i - 1][j - 1] + (s1[i - 1] == s2[j - 1] ? 0 : 1))); return d[len1][len2]; } Ok, anyway I fixed it in the generated code (edit_distance_wrap.cxx). It compiled to .o file fine then. It linked to _edit_distance.so as well: # c++ -shared edit_distance_wrap.o -o _edit_distance.so But now I get import error in Python! Linux RH root ~/tmp # python Python 2.4.3 (#1, Dec 11 2006, 11:38:52) [GCC 4.1.1 20061130 (Red Hat 4.1.1-43)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import edit_distance Traceback (most recent call last): File "", line 1, in ? File "edit_distance.py", line 5, in ? import _edit_distance ImportError: ./_edit_distance.so: undefined symbol: _Z13edit_distanceRSsS_ What did I do to deserve this? :-) edit_distance.i file just in case: %module edit_distance %{ #include "edit_distance.h" %} extern unsigned int edit_distance(string& s1, string& s2); From vinay_sajip at yahoo.co.uk Fri Jul 18 11:07:26 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 18 Jul 2008 08:07:26 -0700 (PDT) Subject: Unusual Exception Behaviour References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> <8904.90077804333$1216313689@news.gmane.org> <006001c8e831$5c1487b0$143d9710$@rawlins@thinkbluemedia.co.uk> <1214.94685668058$1216317006@news.gmane.org> Message-ID: <1e6def2a-9c44-419e-a450-5fe596c5e3c0@j1g2000prb.googlegroups.com> On Jul 18, 12:03 pm, "Robert Rawlins" wrote: > > Yeah it's got me a little bemused to be honest, I've tried playing around > with configuration options this morning and not been able to achieve > anything that works properly. > The logging configuration functionality provided by fileConfig is all- or-nothing, i.e. it does not support incremental configuration. Do you know if any libraries you depend on use fileConfig? If you use programmatic configuration only, and don't use fileConfig at all, does everything work as expected? Regards, Vinay Sajip From mtobis at gmail.com Fri Jul 25 12:23:38 2008 From: mtobis at gmail.com (Michael Tobis) Date: Fri, 25 Jul 2008 09:23:38 -0700 (PDT) Subject: Calling external program from within python References: <6eu684F91muhU1@mid.uni-berlin.de> <042e46cf-8ee8-4dd0-bc2b-716d588f8e83@o40g2000prn.googlegroups.com> Message-ID: <296ec449-831e-4f1f-9082-5ad4991dfc04@i20g2000prf.googlegroups.com> These answers are too elaborate and abstract for the question. Emmanouil, Here is a program "myprog" which takes input and writes output to a file. It happens to be python but it could be anything. ##### #!/usr/bin/env python a = int(raw_input("enter thing 1 ")) b = int(raw_input("enter thing 2 ")) c = raw_input("enter output file name ") f = open(c,"w") f.write("answer is %s\n" % str(a + b)) f.close() ##### Here is python code which runs that program ##### import os f = os.popen("/path/to/myprog","w") f.write("3\n4\noutputname\n") #can also do three separate writes if that is more convenient f.close() ##### For some reason os.popen is deprecated in favor of the more verbose subprocess.Popen, but this will work for a while. Here is an even simpler approach that will take you a long way. This should be very easy to understand. ##### import os params = open("temp","w") params.write("3\n") params.write("4\n") params.write("outputname2\n") params.close() os.system("/path/to/myprog < temp") ##### If you want python to pick up the stdout of your program as well look into popen2. Try basing your solution on those and if you have any problems let us know what they are. In most cases such as you describe these will work. mt From 5lvqbwl02 at sneakemail.com Wed Jul 30 16:05:24 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Wed, 30 Jul 2008 13:05:24 -0700 (PDT) Subject: static variables in Python? References: Message-ID: <413b5eb3-27fd-40a3-962f-027ca1ad7b39@o40g2000prn.googlegroups.com> kj wrote: > Yet another noob question... > > Is there a way to mimic C's static variables in Python? Or something > like it? The idea is to equip a given function with a set of > constants that belong only to it, so as not to clutter the global > namespace with variables that are not needed elsewhere. > > For example, in Perl one can define a function foo like this > > *foo = do { > my $x = expensive_call(); > sub { > return do_stuff_with( $x, @_ ); > } > }; > > In this case, foo is defined by assigning to it a closure that has > an associated variable, $x, in its scope. > > Is there an equivalent in Python? > I found the following link addressing this problem several different ways. My favorite (trickiest) way is using decorators... http://www.daniweb.com/code/snippet501.html From __peter__ at web.de Sat Jul 12 02:19:13 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Jul 2008 08:19:13 +0200 Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: Denis Kasak wrote: > Basically, it reverses the list in place, so it modifies the list which > called it. It does not return a /new/ list which is a reversed version > of the original, as you expected it to. Since it doesn't return anything > explicitly, Python makes it return None. Hence, the comparison you are > doing is between the original list and a None, which is False, naturally. > Try this: > > spam = ['a', 'n', 'n', 'a'] > eggs = spam[:] > if spam.reverse() == eggs: > print "Palindrome" Your explanation is correct, but your example code compares None to ['a', 'n', 'n', 'a'] and therefore won't print "Palindrome", either. Peter From tjreedy at udel.edu Tue Jul 22 13:58:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2008 13:58:27 -0400 Subject: Question about admin rights and IDLE In-Reply-To: References: Message-ID: Murphy.MarkS at epamail.epa.gov wrote: > Hi All, > > Apologies in advance for a potentially redundant posting -- I sent a > similar question to the help box yesterday. > > I have a Geographic Info System (GIS) user that is having problems > editing with Python IDLE on a WindowsXP machine unless she has admin > rights. I had initially thought there might be a place where you can > change the 'user rights' settings in Python, but wasn't able to find it. > So, I did a fresh install of Python 2.5.1 and told it to be available to > all users during the install process. The problem is that IDLE still > seems to be available only to the person who has admin rights on a given > machine. Can anybody make sense of this and help me fix it? I have both 2.5.2 and 3.0b2 loaded for all users on stock xp with all upgrades. I put /Python25 and /Python30 under Program Files instead of C:. As normal non-admin user, I can edit files in ./misc (added by me) under either, or in ./Lib/site-packages/my_package or, of course, under My Documents. You did not specify the 'problems'. If it is saving (which is required to run a file), then perhaps your user is trying to save in an admin-only directory. If IDLE is not running at all, perhaps you have some special government security mods. Perhaps changing install location would help. Also, does 'fresh install' mean uninstall first? This is not normally required, but you are not in a normal situation ;-). Or perhaps you are running into somthing connected with this warning: **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** Perhaps you are getting silent blockage. Related to the above, there can only be one IDLE process running on the machine at one time. If somehow one were being started on the admin account, for instance .... . Terry Jan Reedy PS. Unless you have good reason not too, consider installing 2.5.2 instead with its many bug fixes. From darcy at druid.net Thu Jul 10 10:45:30 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 10 Jul 2008 10:45:30 -0400 Subject: Loading just in time Message-ID: <20080710104530.bcfc8aa8.darcy@druid.net> I am trying to create a utility module that only loads functions when they are first called rather than loading everything. I have a bunch of files in my utility directory with individual methods and for each I have lines like this in __init__.py: def calc_tax(*arg, **name): from calc_tax import calc_tax as _func_ calc_tax = _func_ return _func_(*arg, **name) This works the first time I call utility.calc_tax but if I call it again I get a "TypeError: 'module' object is not callable" error. Is there any way to do what I want or do I have to put everything back into a single file. Of course, I can simply change all my calls to utility.calc_tax.calc_tax(...) but I have a lot of code to change if I do that. Thanks. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From stefan_ml at behnel.de Sat Jul 12 01:55:12 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 12 Jul 2008 07:55:12 +0200 Subject: Help with using findAll() in BeautifulSoup In-Reply-To: References: Message-ID: <48784741$0$6606$9b4e6d93@newsspool2.arcor-online.net> Alexnb wrote: > Okay, I am not sure if there is a better way of doing this than findAll() but > that is how I am doing it right now. Consider using lxml.html and lxml.cssselect. http://codespeak.net/lxml/ > I am making an app that screen scapes > dictionary.com for definitions. Do they have a policy for doing that? > noun > >
> verb >
> > I want to be able to do like findAll('span', {'class': 'pg'}), but tell me > how many
things are after it, or before the next so I know how many > defintions it has. You didn't say where the "span" is in the HTML code, but lxml.cssselect should get you pretty close to what you want. If your tables are descendants of the "span"s, a selector like: "span.pg table" might work. There's also a CSS syntax for siblings. Stefan From stochashtic at yahoo.ca Fri Jul 25 10:39:56 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 25 Jul 2008 16:39:56 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> Message-ID: <4889e5bc$1@news2-rz-ap.ethz.ch> That's a good comparison for the general question I posed. Thanks. Although I do believe lists are less than ideal here and a different data structure should be used. To be more specific to my case: As mentioned in my original post, I also have the specific condition that one does not know which nodes to turn ON until after all the probabilities are calculated (lets say we take the top m for example). In this case, the second and third will perform worse as the second one will require a remove from the list after the fact and the third will require another loop through the nodes to build the new list. From roy at panix.com Sat Jul 12 21:33:13 2008 From: roy at panix.com (Roy Smith) Date: Sat, 12 Jul 2008 21:33:13 -0400 Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> <85c3da91-9f2f-4d19-ba98-dfdc99b1e1e3@79g2000hsk.googlegroups.com> Message-ID: ssecorp wrote: > i dont get what you mean, if i dont do anything python will raise an > indexerror so it is an indexerror. You wrote: > > > ? ? def pop(self): > > > ? ? ? ? try: > > > ? ? ? ? ? ? return self.queue.pop(0) > > > ? ? ? ? except: > > > ? ? ? ? ? ? raise IndexError, "pop from empty queue" You are assuming that the only possible exception that can be thrown by "return self.queue.pop(0)" is IndexError. Maybe, maybe not. I gave you one example of how something else could be thrown -- a typo in your code leading to a NameError. Maybe even something more exotic like MemoryError? The defensive thing to do is catch exactly the exception you expect to happen. In this case, that means IndexError. From mmcduff at fastsoft.com Wed Jul 16 01:39:38 2008 From: mmcduff at fastsoft.com (Mark McDuff) Date: Tue, 15 Jul 2008 22:39:38 -0700 Subject: reading one byte from stdin Message-ID: <40DC41E9-DBFA-45F3-B155-92785AA9490B@fastsoft.com> I'm trying to read one byte from stdin, without the newline. If I try something like: >>> import os, sys >>> os.read(sys.stdin.fileno(),1) I can input a character, but then I have to press enter, which leaves a newline character in the stdin buffer and requires two keypresses. Is there any way to read only one keypress in a simple manner (i.e. no curses)? From PengYu.UT at gmail.com Tue Jul 22 18:33:04 2008 From: PengYu.UT at gmail.com (Peng Yu) Date: Tue, 22 Jul 2008 15:33:04 -0700 (PDT) Subject: How to match word boundary? Message-ID: <94c0d7d1-5263-45f6-a75d-a9751b3785f9@d45g2000hsc.googlegroups.com> Hi, I use r"\ba\b" to match "a". However, I can not use "\ba::\b" to match "a::b". I would like to match "a::" in "a::b", but not in "a:: b". That is, the character after "::" should be a alphanumeric character. Could you let me know how to do it and why "\b" would not work? Thanks, Peng From chiendarret at gmail.com Sat Jul 26 06:42:40 2008 From: chiendarret at gmail.com (Francesco Pietra) Date: Sat, 26 Jul 2008 12:42:40 +0200 Subject: Insert character at a fixed position of lines In-Reply-To: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> Message-ID: I am still at the stone age, using scripts (e.g., to insert a string after a string) of the type f = open("xxx.pdb", "r") for line in f: print line if "H16Z POPC" in line: print "TER" f.close() That is, I have to learn about modules. In your scripts I am lost about the filename for the pdb file to modify, francesco On Sat, Jul 26, 2008 at 11:35 AM, Lie wrote: > On Jul 26, 2:41 pm, "Francesco Pietra" wrote: >> How to insert letter "A" on each line (of a very long list of lines) >> at position 22, i.e., one space after "LEU", leaving all other >> characters at the same position as in the original example: >> >> ATOM 1 N LEU 1 146.615 40.494 103.776 1.00 73.04 1SG 2 >> >> In all lines"ATOM" is constant as to both position and string, while >> "LEU" is constant as to position only, i.e., "LEU" may be replaced by >> three different uppercase letters. Therefore, the most direct >> indication would be position 22. >> >> Should the script introduce blank lines, no problem. That I know how >> to correct with a subsequent script. >> >> Thanks >> chiendarret > > If you want to leave the rest of the strings as-is (i.e. the letter A > overwrites whatever on position 22), Peter's code need to be modified > a little: > line = line[:22] + " " + line[23:] > -- > http://mail.python.org/mailman/listinfo/python-list > -- Dr Francesco Pietra Professor of Chemistry Accademia Lucchese di Scienze, Lettere e Arti, founded in 1594 Palazzo Ducale 55100 Lucca (Italy) e-mail chiendarret at gmail.com From __peter__ at web.de Wed Jul 9 10:42:05 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 09 Jul 2008 16:42:05 +0200 Subject: Relative Package Import References: Message-ID: Thomas wrote: > Robert Hancock wrote: >> mypackage/ >> __init__.py >> push/ >> __init__.py >> dest.py >> feed/ >> __init__py >> subject.py >> >> In subject.py I have >> from ..push import dest > > There is no such thing as relative package imports. See > http://www.python.org/doc/essays/packages.html Unless you are using Python 1.5 the following document is a bit more relevant: http://www.python.org/dev/peps/pep-0328/ Peter From Ralf.Schaa at gmail.com Sun Jul 13 04:59:35 2008 From: Ralf.Schaa at gmail.com (Ralf.Schaa at gmail.com) Date: Sun, 13 Jul 2008 01:59:35 -0700 (PDT) Subject: matplotlib: is there something like DISLIN's "call newpag" ? Message-ID: Hi there, hope somebody here can help me out: is there a command in matplotlib which resembles DISLIN's "CALL NEWPAG" ? I am trying to make multiple plots on several pages, all stored in one ps (or pdf) document. Cheers -Ralf From iainking at gmail.com Fri Jul 25 08:46:56 2008 From: iainking at gmail.com (Iain King) Date: Fri, 25 Jul 2008 05:46:56 -0700 (PDT) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> Message-ID: <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> On Jul 25, 10:57 am, Suresh Pillai wrote: > I am performing simulations on networks (graphs). I have a question on > speed of execution (assuming very ample memory for now). I simplify the > details of my simulation below, as the question I ask applies more > generally than my specific case. I would greatly appreciate general > feedback in terms of computing and of course considerations specific to > implementation in Python. > > The nodes in my network may be ON or OFF. The network starts off with > all nodes in the OFF state. I loop through the nodes. For each node > that is OFF, I consider some probability of it turning ON based on the > states of its neighbours. I MUST GO THROUGH ALL NODES BEFORE DECIDING > WHICH ONES TO TURN ON. > > So my question is whether it is faster to > > 1. loop through a list of ALL nodes and check for OFF nodes using ifs > > or to > > 2. loop through a container of OFF nodes and remove from this when they > turn ON or 3. build a new list every iteration intead of deleting from the old one: while processing: new_off_list = [] for x in off_list: if goes_on(x): on_list.append(x) else: new_off_list.append(x) off_list = new_off_list generation += 1 Iain From misceverything at gmail.com Sun Jul 20 11:48:40 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Sun, 20 Jul 2008 08:48:40 -0700 (PDT) Subject: Run as Service Message-ID: <09c0bfa9-c86b-4153-ba91-cb9bf2e85e2a@k30g2000hse.googlegroups.com> I have, in the past, used SRVANY to run a Python app as a Windows service. However, now I am interested in distributing my scripts and want to make it as painless for the end user as possible (hands-off is best :). How can you go about running a Python app as a Windows service without SRVANY? From castironpi at gmail.com Wed Jul 30 22:26:05 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 30 Jul 2008 19:26:05 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> <29a131a5-d813-407a-b774-6f90b7f8f3e3@w1g2000prk.googlegroups.com> Message-ID: <8f058531-8c1b-4654-a205-9bec0281b830@k37g2000hsf.googlegroups.com> On Jul 30, 1:50?am, Carl Banks wrote: > On Jul 30, 1:58 am, "Russ P." wrote: > > > > > On Jul 29, 10:33 pm, Carl Banks wrote: > > > > On Jul 30, 1:15 am, "Russ P." wrote: > > > > Having said that, it would sure be nice to be able to write > > > > > if myList is not empty: > > > > > instead of > > > > > if len(myList) != 0: > > > > I can agree with this. > > > But I guess that could only work if there were only one empty list > > that represents all empty lists (as there is only one actual "None"). > > I don't know if that makes sense or not. > > I mean in general. ?I wouldn't spell it like that. ?I would prefer if > empty(x), with an __empty__ method. ?(And support __nonzero__ aka > __bool__ dropped completely.) > > Carl Banks An __empty__ method could return True for my social life, ha ha. Does __nonzero__ just mean __nonempty__? From ldo at geek-central.gen.new_zealand Thu Jul 24 05:54:03 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 24 Jul 2008 21:54:03 +1200 Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: In message , Matimus wrote: > That isn't the standard. With that setup tabs will show up as 4 > spaces, and still confuse you. Why should that be confusing? The most common tab-stop setting is 4 columns. From Samnsparky at gmail.com Sun Jul 13 22:51:16 2008 From: Samnsparky at gmail.com (Sparky) Date: Sun, 13 Jul 2008 19:51:16 -0700 (PDT) Subject: wxPython Tab References: <75018ae6-6d8c-4962-9fd0-aedb52ad626f@k30g2000hse.googlegroups.com> Message-ID: <9a360a73-fa6b-4559-929d-909bc83430f3@34g2000hsf.googlegroups.com> On Jul 13, 10:32?am, Uwe Schmitt wrote: > On Jul 13, 6:20?pm, Sparky wrote: > > > Is there a way to get wxPython to change the visible tab in a notebook > > (like I have tab 1 open but the computer will automatically change to > > tab 2)? > > > Thanks, > > Sam > > look athttp://docs.wxwidgets.org/stable/wx_wxnotebook.html#wxnotebooksetpage... > > greetings, uwe Works like a charm. Thanks! Sam From sunp1028 at gmail.com Fri Jul 18 03:18:52 2008 From: sunp1028 at gmail.com (patrol) Date: Fri, 18 Jul 2008 00:18:52 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> <487E1AD4.9020509@timgolden.me.uk> <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> <3d1db021-6766-4d5d-9105-fdd81e27b671@26g2000hsk.googlegroups.com> Message-ID: On 7?17?, ??4?22?, Tim Golden wrote: > patrol wrote: > > I will try to modify the wmi.py ,however I'm a novice.It will take a > > long time. You can give it up temporarily. If you don't mind ,can you > > tell me where needs modifying and how? Just unicode? Or Other? > > OK. Thanks for your patience on this one, Patrol. What I propose > to do is to dig into the pywin32 sources to determine what's going > on when the error messages are fetched. Then I'll be better placed > to decide what to do when they come out. On the surface, the current > module should be handling things correctly; but I've obviously missed > an encode/decode somewhere. > > If I can think of an (even hackish) workaround for you in the meantime, > I'll let you know. Until then... > > TJG Thanks for Tim's help. Patrol From castironpi at gmail.com Thu Jul 17 18:08:17 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 17 Jul 2008 15:08:17 -0700 (PDT) Subject: interpreter vs. compiled Message-ID: I'm curious about some of the details of the internals of the Python interpreter: I understand C from a hardware perspective. x= y+ 1; Move value from place y into a register Add 1 to the value in the register Move the addition's result to place x The Python disassembly is baffling though. >>> y= 3 >>> dis.dis('x=y+1') 0 SETUP_LOOP 31037 (to 31040) 3 STORE_SLICE+3 4 <49> What are SETUP_LOOP and STORE_SLICE? What are these instructions? From socyl at 987jk.com.invalid Wed Jul 30 17:52:26 2008 From: socyl at 987jk.com.invalid (kj) Date: Wed, 30 Jul 2008 21:52:26 +0000 (UTC) Subject: overriding file.readline: "an integer is required" Message-ID: I'm trying to subclass file, overriding the readline method. The new method definition begins with def readline(self, size=None): line = self.file.readline(size) # etc., etc. ...where the self.file attribute is a regular file object. This works fine if I invoke the new method with an integer argument, but if I invoke it without arguments, I get the error TypeError: an integer is required ...which I suppose comes from the call to self.file.readline(None). I know that I could rewrite the method like this: def readline(self, size=None): if size == None: line = self.file.readline() else: line = self.file.readline(size) # etc., etc. ...but this seems to me exceptionally awkward. (Actually, it's worse than awkward: it fails to complain when the overriding method is called with the argument None. It would be better to test for the number of arguments passed to the function, but I can't figure out how to do this either.) Is there a better idiom? TIA! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From mdboldin at gmail.com Thu Jul 31 11:29:39 2008 From: mdboldin at gmail.com (mmm) Date: Thu, 31 Jul 2008 08:29:39 -0700 (PDT) Subject: undo a dictionary References: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> <192b4786-85b2-43d3-bb7c-b5716068ff12@56g2000hsm.googlegroups.com> Message-ID: Gabriel, I meant the latter, so this helps > Or, do you mean you already have those names and values, perhaps mixed ? > with a lot more names, and want to extract only those starting with "x" ? > and following with a number? > > result = {} > for name, value in vars(): # or locals().items(), or globals().items(), or ? > vars(some_module) > ? ?if name[0]=='x' and name[1:].isdigit(): > ? ? ?result[name] = value But I got an error with 'for name, value in vars():' RuntimeError: dictionary changed size during iteration I think globals() has the same problem, but globals.items() works. I will need to read the docs to learn why '.items()' works but the changing global dictionary problem makes sense. I assume I need to use a non dynamic created list. Sometimes I get the error about 'too many variables to unpack' (can not consistently repeat the error however) In any event, thanks for the suggestions, everyone. Using a blank class for unpacking the dictionary makes the most sense, for safety sake. So you know the general issue is I want to switch between using dictionaries for storing data items and simple variable names for writing equations/formulas, So (a) and (b) below are preferred to (c) for readability (a) straight forward equation y = b0 + b1*Age + b2*Size (b) Class version y = b0 + b1*x.Age + b2*x.Size (c) Dictionary version y = b0 + b1*dd.get('Age') + b2*dd.get('Size') From asma61 at dsl.pipex.com Sun Jul 27 10:17:51 2008 From: asma61 at dsl.pipex.com (DaveM) Date: Sun, 27 Jul 2008 15:17:51 +0100 Subject: Rant (was Re: x*x if x>10 Message-ID: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> On Sun, 27 Jul 2008 05:24:36 -0700 (PDT), alex23 wrote: >On Jul 27, 10:13?pm, ssecorp wrote: >> I have seen somewhere that you can write something like: >> x*x if x>10 >> but exactly that doesn't work and I can't get any variation to work. >It's called a ternary operator. The format is: > My question is I want everything inside, the contents of each ad the regular text of the " My question is I want everything inside, the contents of each ad the regular text of the
american, a href="/browse/blue" linkindex="12" set="yes">blue brick churn cottage cream " My question is I want everything inside, the contents of each ad the regular text of the . I know I can do like a.contents, but it only gives me the first one, in this case being "blue". I want the contents of each of those and the regular contents of the . P.S. notice the things inbetween the tags, I need those too :( Can anyone help? -- View this message in context: http://www.nabble.com/Need-help-getting-BeautifulSoup-contents-tp18501881p18501881.html Sent from the Python - python-list mailing list archive at Nabble.com. From dusan.smitran at gmail.com Thu Jul 17 04:14:52 2008 From: dusan.smitran at gmail.com (dusans) Date: Thu, 17 Jul 2008 01:14:52 -0700 (PDT) Subject: Need help getting BeautifulSoup contents References: Message-ID: <3b6240a5-3f2a-4c44-8944-34079d8e990a@e39g2000hsf.googlegroups.com> I dont quite understand what u want. U should paste the html here http://pastebin.com/ also provide the result that u want. If u dont take the time to write what u wont, nobody will take the time to help u On Jul 17, 7:38?am, Alexnb wrote: > The trick to this one is that the html looks something like this: > > > american, > a href="/browse/blue" linkindex="12" set="yes">blue brick churn cottage > cream " > > My question is I want everything inside, the contents of each ? ad the > regular text of the . > I know I can do like a.contents, but it only gives me the first one, in this > case being "blue". I want the contents of each of those and the regular > contents of the . > > P.S. notice the things inbetween the > Can anyone help? > > -- > View this message in context:http://www.nabble.com/Need-help-getting-BeautifulSoup-contents-tp1850... > Sent from the Python - python-list mailing list archive at Nabble.com. From chrisspen at gmail.com Sun Jul 13 19:05:13 2008 From: chrisspen at gmail.com (Chris) Date: Sun, 13 Jul 2008 16:05:13 -0700 (PDT) Subject: Using Groups inside Braces with Regular Expressions Message-ID: <10284e46-1601-4269-a1a0-ef3831e9f85c@z66g2000hsc.googlegroups.com> I'm trying to delimit sentences in a block of text by defining the end-of-sentence marker as a period followed by a space followed by an uppercase letter or end-of-string. I'd imagine the regex for that would look something like: [^(?:[A-Z]|$)]\.\s+(?=[A-Z]|$) However, Python keeps giving me an "unbalanced parenthesis" error for the [^] part. If this isn't valid regex syntax, how else would I match a block of text that doesn't the delimiter pattern? Thanks, Chris From fredrik at pythonware.com Tue Jul 15 06:49:49 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2008 12:49:49 +0200 Subject: screencapture with PIL question In-Reply-To: <8e9ca866-4f14-4dd6-a784-a76630d8d812@x35g2000hsb.googlegroups.com> References: <8e9ca866-4f14-4dd6-a784-a76630d8d812@x35g2000hsb.googlegroups.com> Message-ID: greg wrote: > I am able to use the PIL module to capture a screen or specific > window. My problem is when capturing a window (on windows XP) I can > only capture the "visible" portion of the window. Is there any way to > capture the entire window? specifically the scrolled portion of a > window that is not visible on the screen. If we're talking arbitrary applications, that portion doesn't necessarily exist other than as a collection of data structures deep inside the application. To fix this, your captura program needs to take repeated screenshots, adjust the view between every shot, and then stitch them together. See Gabriel's post for a link to a nice automation tool for Windows. There are also various browser screenshot tools around that might work in your case (I think I've seen Python code for that somewhere, but cannot find it right now). Google can probably help. From hat at se-162.se.wtb.tue.nl Wed Jul 2 03:56:03 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 02 Jul 2008 09:56:03 +0200 Subject: n00bie wants advice. References: <8757c630-0518-4351-a319-124ced0ac92c@w4g2000prd.googlegroups.com> Message-ID: On 2008-07-02, bsagert at gmail.com wrote: > This simple script writes html color codes that can be viewed in a > browser. I used short form hex codes (fff or 000, etc) and my list > has only six hex numbers otherwise the results get rather large. I > invite criticism as to whether my code is "pythonic". Are there other > ways to generate the hex combos besides the nested "for" loops? Thanks > in advance, Bill ok. variable names of 1 letter are very bad. Use more meaningful names like 'red' 'green' etc. 'list' is better, but also a name reserved by Python, so change that too. Indenting is normally 4 spaces in Python You can see "a + b +c" twice, compute it once, and assign it to a intermediate variable Use string formatting for better readability. In this case, you could also open the file earlier, and write all strings directly to file instead of first creating a string in memory Otherways of creating the colour code permutations: In this case, this is most Pythonic imho. You could write a list comprehension of even a recursive function, but I think it wouldn't increase readability. Albert > list = ['3','6','9','b','d','f'] > > s = '\n' > > for a in list: > for b in list: > for c in list: > s += '

'+ a + b + c +'

> \n' > > s += '' > > f = open('c:/x/test.htm', 'w') > f.write(s) > f.close() From stefan_ml at behnel.de Fri Jul 25 07:02:09 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 25 Jul 2008 13:02:09 +0200 Subject: lxml, comparing nodes In-Reply-To: <4613042f-ed70-4cfa-8de9-a92b4df32923@k36g2000pri.googlegroups.com> References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> <6c91a4da-6443-4570-8dd3-01c4ec169bf3@t54g2000hsg.googlegroups.com> <4888ad28$0$9491$9b4e6d93@newsspool3.arcor-online.net> <4613042f-ed70-4cfa-8de9-a92b4df32923@k36g2000pri.googlegroups.com> Message-ID: <4889B2B1.5030204@behnel.de> code_berzerker wrote: >> If document order doesn't matter, try sorting the elements of each level in >> the two documents by some arbitrary deterministic key, such as (tag name, >> text, attr count, whatever), and then compare them in order, instead of trying >> to find matches in multiple passes. itertools.groupby() might be your friend here. > > I think that sorting multiple times by each attribute will cost more > than I've managed to do: [...] > let1 = [x for x in et1.iter()] > let2 = [x for x in et2.iter()] > [...] > while let1: > el = let1.pop(0) > foundEl = findMatchingElem(el, let2) > if foundEl is None: > return False > let2.remove(foundEl) > return True > > def findMatchingElem(el, eList): > for elem in eList: > if elemsEqual(el, elem): > return elem > return None [...] > Notice that if documents are in exact same order, each element is > compared only once! Not in your code. Stefan From tdelaney at avaya.com Mon Jul 21 21:01:17 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 22 Jul 2008 09:01:17 +0800 Subject: Python Written in C? In-Reply-To: Message-ID: Fredrik Lundh wrote: > rynt wrote: > >> You're either --- >> A. A Troll >> B. A young, immature programmer trying to show off or >> C. A total idiot. > > you forgot the "All of the above" choice. I read it as an inclusive "or". Tim Delaney From bearophileHUGS at lycos.com Sat Jul 19 16:57:33 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 19 Jul 2008 13:57:33 -0700 (PDT) Subject: MethodChain References: <6eej10F6k7g3U2@mid.uni-berlin.de> Message-ID: <342b5431-5ead-4827-8bdd-ab2cd50c2acc@i76g2000hsf.googlegroups.com> Marc 'BlackJack' Rintsch: > What's called `MethodChain` there seems to be function composition in > functional languages. Maybe `functools` could grow a `compose()` function. To me it looks like a quite more "refined" thing, it's an object, it has some special methods, etc. I think it's not too much difficult to implement it with Python. Bye, bearophile From Russ.Paielli at gmail.com Sun Jul 27 15:33:16 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 12:33:16 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> Message-ID: <7eabe5a6-357a-4255-a958-0804959ce844@a6g2000prm.googlegroups.com> On Jul 27, 1:19 am, Steven D'Aprano wrote: > On Sat, 26 Jul 2008 17:14:46 -0700, Russ P. wrote: > > You take the name down to a single letter. As I suggested in an earlier > > post on this thread, why not take it down to zero letters? > > The question isn't "why not", but "why". The status quo works well as it > is, even if it isn't perfect. Prove that implicit self is a good idea -- > or at least prove that it is an idea worth considering. > > "I don't like typing self" doesn't convince me. The same argument could > be made typing parentheses, colons, commas, etc. We could end up with > something like this: > > class Foo base > def method x y z > .args = list x y z > > That's not necessarily wrong, but it's not Python. And what does that have to do with my suggestion? Absolutely nothing. It's a red herring that you seem to be using to obscure the fact that you have no rational argument to make. By the way, according to your "reasoning," Python 2.5 was *not* Python when 2.1 was the latest version. But now it is! Yes, Python has actually changed, yet remained Python. What a concept! > It's not enough to show that a change "isn't bad" -- you have to show > that it is actively good. Why should Python make any changes to the > current explicit self without a clear and solid reason to change? > > > You could if Python accepted something like > > > class Whatever: > > > def fun( , cat): > > > .cat = cat > > > This is even better than the single-character name, > > By "better" do you mean "uglier"? If so, I agree with you. If not, then I > disagree that it is better. You seem to be freaked out by an empty argument. Actually, it bothers me a bit too, which is why I suggested that a period could be used as the first argument to indicate that, like Clint Eastwood in The Good, the Bad, and the Ugly, "self" had no name here. > > not only because it > > is shorter, but also because there is no question that you are referring > > to "self." No need to look back at the method signature to verify that. > > "Don't need to look at the method signature" is not an argument in favour > of implicit self. You don't need to look at the method signature when > you're using an explicit self either. Actually, you do. The name "self" could be used for any argument -- or even for a local variable. No good programmer would do such a thing, of course, but not all programmers are good programmers (and not all Python programmers read the stern admonitions against such practices on this forum). And if you are reviewing critical code, you had darn well better verify that "self" is the first argument. With my proposal, you would not need to do that. Is that a major advantage? No. But it is a minor advantage. And it is perfectly logical. Am I suggesting that unnamed first arguments should always be used? No, of course not. But I am saying that in some cases it can unclutter and simplify the code. > What happens with class-methods? With the cls (or if you prefer klass) > convention, it is simple to tell what object I am referring to. Now I > have to go back to the method signature to see if it is a class method or > instance method, instead of just looking at the explicit name. Bzzzzt. Wrong again. The exact same convention could apply there. And the same benefits apply: less clutter and no need to keep the name of the first argument in your head when reading the code. > > For those who don't like the way the empty first argument looks, maybe > > something like this could be allowed: > > > def fun( ., cat): > > Even uglier than the first. Convince me there's a benefit. Actually, I think it's elegant. And I'll bet that if Guido had suggested it, you would think it was beautiful. Why force a name to be used when none is needed? Think about lambda functions. From mrkafk at gmail.com Mon Jul 21 12:03:08 2008 From: mrkafk at gmail.com (mk) Date: Mon, 21 Jul 2008 18:03:08 +0200 Subject: Python Written in C? In-Reply-To: References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> Message-ID: Grant Edwards wrote: > Using punch-cards and paper-tape. Real programmers can edit > their programs with a pointy stick and some home-made > sticky-tape. Wrong! Real programmers can program using only Touring machine (and something having to do with post for some reason). I'm sure our brilliant OP[1] could program in both. [1] Troll, really. Don't feed the troll. I wouldn't have posted about him because that only adds to the noise. oops. From nagle at animats.com Tue Jul 29 02:08:32 2008 From: nagle at animats.com (John Nagle) Date: Mon, 28 Jul 2008 23:08:32 -0700 Subject: block/lambda In-Reply-To: <0406eb4f-8dec-4ce2-b506-8e597de2958d@56g2000hsm.googlegroups.com> References: <0406eb4f-8dec-4ce2-b506-8e597de2958d@56g2000hsm.googlegroups.com> Message-ID: <488eaf61$0$17164$742ec2ed@news.sonic.net> iu2 wrote: > Hi, > > Playing with imitating lambdas and ruby blocks in Python, I came up > with a very simple construct, for example: > > import compiler Python supports nested functions. You don't have to use a lambda form just to get a local function. Just write an ordinary nested def within another def. John Nagle From dinov at exchange.microsoft.com Fri Jul 25 11:32:11 2008 From: dinov at exchange.microsoft.com (Dino Viehland) Date: Fri, 25 Jul 2008 08:32:11 -0700 Subject: Questions on 64 bit versions of Python In-Reply-To: References: <1216966424.4685.1265275245@webmail.messagingengine.com> <4889AC5E.8090909@egenix.com> Message-ID: <7AD436E4270DD54A94238001769C2227012C935C06F4@DF-GRTDANE-MSG.exchange.corp.microsoft.com> The end result of that is on a 32-bit machine IronPython runs in a 32-bit process and on a 64-bit machine it runs in a 64-bit process. -----Original Message----- From: python-list-bounces+dinov=microsoft.com at python.org [mailto:python-list-bounces+dinov=microsoft.com at python.org] On Behalf Of Mike Driscoll Sent: Friday, July 25, 2008 5:58 AM To: python-list at python.org Subject: Re: Questions on 64 bit versions of Python On Jul 25, 5:52 am, Fredrik Lundh wrote: > M.-A. Lemburg wrote: > >> 4. Is there a stable version of IronPython compiled under a 64 bit > >> version of .NET? Anyone have experience with such a beast? > > > Can't comment on that one. > > Should that matter? Isn't IronPython pure CLR? > > IronPython is written in C# and runs in/with the CLR, if that's what you mean. Well, IronPython one works with the CLR and is equivalent to Python 2.4, whereas IronPython 2 works with the DLR and is equivalent to Python 2.5 Mike -- http://mail.python.org/mailman/listinfo/python-list From modelnine at modelnine.org Tue Jul 29 07:13:23 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Tue, 29 Jul 2008 13:13:23 +0200 Subject: SWIG and char* newb questions :) In-Reply-To: <7ec26fb6-3d6a-4e1b-b2c9-a0a254780153@26g2000hsk.googlegroups.com> References: <7ec26fb6-3d6a-4e1b-b2c9-a0a254780153@26g2000hsk.googlegroups.com> Message-ID: <200807291313.24134.modelnine@modelnine.org> Am Dienstag, 29. Juli 2008 12:51:36 schrieb code_berzerker: > Ok now more seriously. I have question refering to char* used as > function parameters to return values. I have read SWIG manual to find > best way to overcome that, but there are many warnings about memory > leaks and stuff, so I feel confused. > > Ok to put it more simply: how to safely define a variable in Python > and have it modified by C/C++ function? At least for strings, this won't work. Python strings are immutable (and Python optimizes some things based on this knowledge), and as such you can pass a Python string(-object) into a C/C++ function and retrieve its value there as a const (!) char* using the PyString_*-API (I have no idea how this is encapsulated in SWIG), but cannot/should not modify it (a const_cast<> is almost always a sign of bad programming, anyway). The only real choice you have is to have your wrapper return a new string object, created using one of the PyString_FromString[AndSize] functions. Check the Python C-API documentation for more info on this. Anyway, on a different note, I personally have always found it simpler to not use SWIG to generate C extensions for Python, but to use the Python C-API directly. Hope this helps! -- Heiko Wundram From deets at nospam.web.de Wed Jul 16 03:04:37 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Jul 2008 09:04:37 +0200 Subject: reading one byte from stdin In-Reply-To: References: Message-ID: <6e5ksbF5c5a4U1@mid.uni-berlin.de> Mark McDuff schrieb: > I'm trying to read one byte from stdin, without the newline. > > If I try something like: > >>> import os, sys > >>> os.read(sys.stdin.fileno(),1) > > I can input a character, but then I have to press enter, which leaves a > newline character in the stdin buffer and requires two keypresses. Is > there any way to read only one keypress in a simple manner (i.e. no > curses)? Depending on your OS, yes. Under *nix, you need to set the terminal to RAW-mode. This recipe claims to be OS-agnostinc: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 Diez From dominic.rice at gmail.com Fri Jul 4 17:38:21 2008 From: dominic.rice at gmail.com (Dominic Rice) Date: Fri, 04 Jul 2008 22:38:21 +0100 Subject: running python from cmd.exe References: Message-ID: Chris Hulan wrote: > On Jul 4, 5:38 am, Dominic Rice wrote: >> Dominic Rice wrote: >>> Miki wrote: >>>> Hello, >>>>> I can't seem to get python to run my scripts using the command: python >>>>> .py >>>>> If I type python the interpreter runs as I sorted out the Path property, >>>>> I'm afraid I don't know much about this kind of thing as I'm a science >>>>> student who needs some Python not a programmer! >>>> Can you be more specific about the error you get? >>>> Say you have a script hw.py that contains one line: >>>> print "Hello Python" >>>> and you run >>>> python hw.py >>>> What is the error you get? >>>> HTH, >>>> -- >>>> Miki >>>> http://pythonwise.blogspot.com >>> Sure, I get: >>> can't open file .py: [errorno 2]No such file or directory. >>> Now if I've noticed that if I change directory to (for instance) >>> \Python25 where the script is the command runs fine.(?) >> Oh I just noticed you specified hw.py, in that case just to clarify it >> would be can't open file hw.py: [errorno 2]No such file or directory > > When you run a script, are you in the directory where the script is > located? when it works yes! Does it have to be the case then? I assumed that there was a default folder (eg \Python25) that the python command would look for the file in, I take it this is not the case then? From bj_666 at gmx.net Thu Jul 17 00:14:50 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Jul 2008 04:14:50 GMT Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> <0T56p3tmInifNv8%stesch@parsec.no-spoon.de> Message-ID: <6e7v9qF5q74kU1@mid.uni-berlin.de> On Thu, 17 Jul 2008 05:41:11 +0200, Stefan Scholl wrote: > Fredrik Lundh wrote: >> Stefan Scholl wrote: >> >>> Django isn't ready. >> >> That's a remarkably ignorant statement. > > The 1.0 release will be in September. So what? It's not the version number that matters but features and stability. It's not uncommon in open source projects to have very usable software with a version number below 1.0. Ciao, Marc 'BlackJack' Rintsch From fetchinson at googlemail.com Fri Jul 11 02:42:39 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 10 Jul 2008 23:42:39 -0700 Subject: Bypassing WebFilter security In-Reply-To: <4876F153.2020406@behnel.de> References: <563968a1-3cc3-4009-beca-d5d367d4ccff@k13g2000hse.googlegroups.com> <4876F153.2020406@behnel.de> Message-ID: >> I am working in an organization, which is using a very strict >> webcontent filter management suite. Due to this i am unable to >> download any exe file, or surf web (even the necessary downloads from >> sourceforgenet are blocked). I was wondering, if python could be of >> any help. Say i have a python script, and i pass the URL of >> downloadable file, and it just downloads the file for me. > > Nice try. Can I talk to your employer for a minute? :) > > Honestly, the language doesn't make any difference here, and there isn't > much > you can do unless you control both sides, i.e. the server and the client. > But > I would suggest you actually talk to your employer yourself to see if > there's > an official way to get what you want. Yes, the language itself doesn't matter as long as you go through the web. But if I were you I would use an ssh client to ssh to a remote machine on which I have an account, download the file there to that machine and scp it to the local machine. Assuming of course port 21 is not blocked. In fact, this is something I do regularly for similar reasons :) Good luck, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From paul at boddie.org.uk Fri Jul 25 18:32:44 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 25 Jul 2008 15:32:44 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> Message-ID: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> On 25 Jul, 22:37, Terry Reedy wrote: > Kay Schluehr wrote: > > > > This isn't the problem Jordan tries to address. It's really just about > > `self` in the argument signature of f, not about its omission in the > > body. > > That is not at all how I read him, so I will let him respond if he > wishes. The main problem moving a function from module scope to class > scope is prefixing the proper variables. Adding a param name, whether > 'self', 's', 'this', or whatever, is trivial and hardly worth the ink. He wrote the following of relevance: "I added some classes to code that had previously just been functions, and you know what I did - or rather, forgot to do? Put in the 'self'. In front of some of the variable accesses, but more noticably, at the start of *every single method argument list.*" And rounding off with this on the subject: "The problem is that the explicit requirement to have self at the start of every method is something that should be shipped off to the implicit category." I guess the desire is to have Java-like behaviour: when defining a method, which must typically be done in the class definition in Java (unless they've enhanced that area in the past few years), you never write a "this" parameter in the method signature, but you are free to qualify instance attribute accesses with "this". Personally, I liked the Modula-3-inspired requirement for "self" in Python, but I can see how a reminder of what it is in every method signature (defined within a class) might be regarded as overly explicit. Paul From execrable at gmail.com Wed Jul 23 22:40:38 2008 From: execrable at gmail.com (B) Date: Wed, 23 Jul 2008 19:40:38 -0700 Subject: os.walk question In-Reply-To: References: Message-ID: Lanny wrote: > How would one make a list of the files in the top directory > using os.walk. > > I need to pick a random file from said list. > > Thanks. > > > > > -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- > how about: import os x = os.walk('/') (root,dirs,files) = x.next() 'files' should contain a list of filenames. From zondo42 at googlemail.com Fri Jul 25 13:13:10 2008 From: zondo42 at googlemail.com (Glenn Hutchings) Date: Fri, 25 Jul 2008 18:13:10 +0100 Subject: calling source command within python References: Message-ID: Jie writes: > i'm having trouble executing os.system('source .bashrc') command > within python, it always says that source not found and stuff. Any > clue? There's no 'source' program; it's a shell builtin. Even if there was, it almost certainly wouldn't do what you want. The .bashrc file is supposed to contain settings applying to the current shell, and os.system() runs in a subshell, so the settings will only affect that shell. If you're doing this to set environment variables, try modifying os.environ instead. Glenn From wuwei23 at gmail.com Thu Jul 24 08:40:16 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 24 Jul 2008 05:40:16 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> Message-ID: <1de235af-4245-41aa-9091-bb7b112f4ce5@n33g2000pri.googlegroups.com> On Jul 24, 8:21?pm, Jordan wrote: > If the attitude > in the community in response to feedback/criticism has gone from > "maybe you've got a point" to "your a lunatic, we'll never change", > well, only Python will suffer in the long term. Personally, I think it has more to do with statements like "there are plenty of smart Python programmers who will justify all kinds of idiocy in the name of their holy crusade" than with your position. You don't begin a discussion by discrediting anyone who might disagree with you as some kind of religious bigot while simultaneously holding that you are the only sane voice speaking. From darcy at druid.net Sat Jul 26 10:36:30 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 26 Jul 2008 10:36:30 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87k5f8afjl.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> Message-ID: <20080726103630.04297f88.darcy@druid.net> On Sat, 26 Jul 2008 16:25:18 +0200 Torsten Bronger wrote: > > Isn't this a showstopper all by itself? > > Yes. But I've seen no code that uses some other word. Emacs' > syntax highlighting even treats it as reserved. So I think that > other counter-arguments are stronger. > > The in my opinion strongest one is that automatic insertion of > "self" would make Python less verbose but more complicated. Well, if we are arguing over which reason to not change it is more important than I would say that we are in "violent agreement." :-) -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From __peter__ at web.de Mon Jul 7 04:10:14 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 07 Jul 2008 10:10:14 +0200 Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> <6ddj74F21uhjU1@mid.individual.net> Message-ID: Peter Pearson wrote: > On Sun, 06 Jul 2008 23:42:26 +0200, TP > wrote: >> >> $ python -c "print '\033[30;44m foo \033[0m'" > [writes an escape sequence to stdout] > >> $ echo -e $esc$ColorBlackOnDarkblue foo $esc$ColorReset > [also writes an escape sequence to stdout] > >> $ echo -n $esc$ColorBlackOnDarkblue foo $esc$ColorReset >> \033[30;44m foo \033[0m > > [snip, shuffle] >> $ export esc="\033" >> $ export ColorBlackOnDarkblue="[30;44m" >> $ export ColorReset="[0m" >> >> import os >> Color = os.environ['ColorBlackOnDarkblue'] >> ColorReset = os.environ['ColorReset'] >> Esc = os.environ['esc'] >> print '%s%s%s%s%s' % (Esc, Color, " foo ", Esc, ColorReset) > [snip] >> $ python color.py >> \033[30;44m foo \033[0m > > The string "\033" is 4 characters long. Your shell variable > "esc" is 4 characters long. Your Python program prints > those four characters. You want it to re-interpret those 4 > characters into a single escape character. > > One of this group's regular participants can (I hope) tell > us three breathtakingly elegant ways to do that. I'm sorry > I can't. > > When you run echo, it recognizes the 4-character "esc" as a > convention for representing a single character, and performs > the re-interpretation for you. When you tell python > "print '\033[30;44m foo \033[0m'", python interprets > the "\033" as a single character. Peter Pearson's explanation is spot-on. You get the 4-character sequence instead of the escape code chr(27). $ export esc="\033" $ python Python 2.5.1 (r251:54863, Mar 7 2008, 03:39:23) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ["esc"] '\\033' >>> print _ \033 If you want to interpret "\\033" as "\033" you have to perform the conversion explicitly. Fortunately there already is an encoding that understands these escape sequences for characters: >>> esc = os.environ["esc"].decode("string-escape") >>> esc '\x1b' >>> print "%s[30;44malles so schoen bunt hier%s[0m" % (esc, esc) alles so schoen bunt hier Peter From simon at simonwillison.net Wed Jul 30 10:32:16 2008 From: simon at simonwillison.net (Simon Willison) Date: Wed, 30 Jul 2008 07:32:16 -0700 (PDT) Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? Message-ID: I'm having a horrible time trying to get xml.dom.pulldom to consume a UTF8 encoded XML file. Here's what I've tried so far: >>> xml_utf8 = """ Simon\xe2\x80\x99s XML nightmare """ >>> from xml.dom import pulldom >>> parser = pulldom.parseString(xml_utf8) >>> parser.next() ('START_DOCUMENT', ) >>> parser.next() ('START_ELEMENT', ) >>> parser.next() ... UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 21: ordinal not in range(128) xml.dom.minidom can handle the string just fine: >>> from xml.dom import minidom >>> dom = minidom.parseString(xml_utf8) >>> dom.toxml() u'Simon\u2019s XML nightmare' If I pass a unicode string to pulldom instead of a utf8 encoded bytestring it still breaks: >>> xml_unicode = u'Simon\u2019s XML nightmare' >>> parser = pulldom.parseString(xml_unicode) ... /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ xml/dom/pulldom.py in parseString(string, parser) 346 347 bufsize = len(string) --> 348 buf = StringIO(string) 349 if not parser: 350 parser = xml.sax.make_parser() UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 32: ordinal not in range(128) Is it possible to consume utf8 or unicode using xml.dom.pulldom or should I try something else? Thanks, Simon Willison From sjmachin at lexicon.net Thu Jul 17 08:29:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 17 Jul 2008 05:29:44 -0700 (PDT) Subject: storing references instead of copies in a dictionary References: Message-ID: <4eec55f0-91a0-4635-bf0c-a4c4573bf81e@p25g2000hsf.googlegroups.com> On Jul 17, 9:45 pm, mk wrote: > Hello everyone, > > I'm storing functions in a dictionary (this is basically for cooking up > my own fancy schmancy callback scheme, mainly for learning purpose): > > >>> def f2(arg): > ... return "f2 " + arg > ... > >>> > >>> def f1(arg): > ... return "f1" + arg > ... > > >>> a={'1': f1, '2': f2} > >>> > >>> [ x[1](x[0]) for x in a.items() ] > ['f11', 'f2 2'] > > Well, neat. Except if I change function definitions now, old functions > are called. And rightly: > > {'1': , '2': } > >>> f1 > > >>> > >>> def f1(arg): > ... return "NEW f1 " + arg > ... > >>> f1 > > > The address of function f1 has obviously changed on redefinition. I wouldn't put it like that. You have created a new function, with a different address to the original function, and bound the name "f1" to that new function. The address of the old function is still stored in the dictionary. A function (or any other object) can have 0, 1, or many names: >>> def foo(): ... print "The function formerly known as foo" ... >>> fred = foo # 2 names >>> del foo # back to one name >>> fred() The function formerly known as foo >>> L = [fred] >>> del fred # 0 names >>> L[0]() # You can't keep a good function down ... The function formerly known as foo >>> > Of course, I can basically update the dictionary with a new function > definition. Uh-huh ... > > But I wonder, is there not a way _in general_ to specifically store > references to functions/variables/first-class objects instead of copies > in a dictionary? Yup, and that's what happens all the time, unless you explicitly make a copy ... some objects have a copy method, sequences can be copied by taking a full slice (seq_copy = seq[:]), otherwise read up on the copy module. From fredrik at pythonware.com Sat Jul 26 07:45:55 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Jul 2008 13:45:55 +0200 Subject: Insert character at a fixed position of lines In-Reply-To: References: Message-ID: Francesco Pietra wrote: > How to insert letter "A" on each line (of a very long list of lines) > at position 22, i.e., one space after "LEU", leaving all other > characters at the same position as in the original example: > > > ATOM 1 N LEU 1 146.615 40.494 103.776 1.00 73.04 1SG 2 > > In all lines"ATOM" is constant as to both position and string, while > "LEU" is constant as to position only, i.e., "LEU" may be replaced by > three different uppercase letters. Therefore, the most direct > indication would be position 22. you may find the fileinput module helpful, combined with the tips you've already gotten in this thread. reference: http://docs.python.org/lib/module-fileinput.html examples: http://effbot.org/librarybook/fileinput.htm http://blog.doughellmann.com/2007/03/pymotw-fileinput.html From fetchinson at googlemail.com Sun Jul 6 03:13:01 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sun, 6 Jul 2008 00:13:01 -0700 Subject: Python with Ecmascript In-Reply-To: <48706543$1$860$ba4acef3@news.orange.fr> References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <486fe241$0$867$ba4acef3@news.orange.fr> <48706543$1$860$ba4acef3@news.orange.fr> Message-ID: >> Is there a way to do similar things on linux? > > I think no. Because these tech use COM. And COM don't exist under xxnux. > But: > - look if XPCOM, or dBus) can help you > - search with the word "MOZLAB", who work a solution (plugin) for > drive Firefox, from an external software. Wow, mozlab is amazing! Thanks, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From larry.bates at websafe.com` Mon Jul 14 22:19:23 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 14 Jul 2008 21:19:23 -0500 Subject: One step up from str.split() In-Reply-To: References: Message-ID: Joel Koltner wrote: > I normally use str.split() for simple splitting of command line arguments, but > I would like to support, e.g., long file names which-- under windows -- are > typically provided as simple quoted string. E.g., > > myapp --dosomething --loadthis "my file name.fil" > > ...and I'd like to get back a list wherein ListEntry[3]="my file name.fil" , > but just running str.split() on the above string creates: > >>>> ListEntry='myapp --dosomething --loadthis "my file name.fil"' >>>> ListEntry.split() > ['myapp', '--dosomething', '--loadthis', '"my', 'file', 'name.fil"'] > > Is there an easy way to provide just this one small additional feature > (keeping quoted names as a single entry) rather than going to a full-blown > command-line argument parsing tool? Even regular expressions seem like they'd > probably be overkill here? Or no? > > Thanks, > ---Joel > > Sounds like it is time to look at getopt Library module. I handles these types of args lines. -Larry From sri_annauni at yahoo.co.in Wed Jul 2 06:32:44 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Wed, 2 Jul 2008 16:02:44 +0530 (IST) Subject: How to identify whether a function is module scoped function or static method of a class by using its fully qualified name Message-ID: <534745.21348.qm@web7906.mail.in.yahoo.com> Thanks, Srini Best Jokes, Best Friends, Best Food and more. Go to http://in.promos.yahoo.com/groups/bestofyahoo/ From news at prodata.co.uk Sat Jul 12 05:30:00 2008 From: news at prodata.co.uk (John Dann) Date: Sat, 12 Jul 2008 10:30:00 +0100 Subject: How to create a timer/scheduler in Python? Message-ID: <0stg74t0eksmnfsslukn5m7f9s4rbub8kt@4ax.com> I need what I'd call (in .Net) a timer, ie I need to run a function eg every 2 seconds - it doesn't need to be millisec accurate but it would be nice if it wasn't eg every 4 seconds or something. Rather surprisingly, Core Python (Chun) doesn't seem to index 'timer' or 'scheduler', which leaves me wondering whether this is an aspect of Python that isn't perhaps widely used? Looking around on the net I can see references to a thread timer, but I'm not really looking to start any new threads (I just want part of the GUI to update every 2 secs) and don't want to get into that sort of complication while still just learning Python. Is there really no simple timer/scheduler function available in Python? From dear.jay.logan at gmail.com Sun Jul 27 20:52:09 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Sun, 27 Jul 2008 17:52:09 -0700 (PDT) Subject: Where is the correct round() method? References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> Message-ID: <90d24864-c67a-4594-b121-d0760f9e145b@m45g2000hsb.googlegroups.com> On Jul 27, 8:45?pm, pigmartian wrote: > it could be that 3.0 is using "banker's rounding" --- rounding to the > even digit. ?the idea behind it behind it being to reduce error > accumulation when working with large sets of values. > > > Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo > > CPU". ?What system are you on? > > > It could be that 2.5 is really 2.49999... which would round down to 2, > > but on any modern CPU (using IEEE floating point), 2.5 should be > > representable exactly. > > That's exactly what's happening, pigmartian. Thank you for explaining the reasoning behind this change. So am I relegated to building my own round() function that behaves like the original function? Or did they move the functionality to a new method somewhere for backwards-compatibility? From luismgz at gmail.com Mon Jul 21 15:12:39 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 21 Jul 2008 12:12:39 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <5e098db8-38f0-42ac-9cb7-9eada66f9a00@z72g2000hsb.googlegroups.com> Let's say you want to build a house... You can use pre-built bricks and stack them together to build your walls, or you can cook your own bricks out of clay because hey! clay is the real thing.... not those ready-made bricks that anyone can use! In the end, you'll have a truly original house but you would have spent 5 years instead of 6 months. The question is: Is it worth it? Bceause you can use pre-built bricks instead and, after applying stucco, nobody will notice you used bricks instead of your own in house-original-cooked bricks. Ok, making your own bricks give you more control over the final result and the way you work with them, but after building two or three houses, you realize it is very cumbersome and time consuming, and not really practical for a "real world" builder... Although making your own bricks could make sense if instead of being a house builder, you are a bricks vendor. It is the same with programming languages: If you are planning to write the next operating system, or a database management system to be used in mission critical applications by millions of users, or perhaps a 3D graphics application, you'd better use C. Fort anything else, boy, don't lose your time. Use Python, get the job done with the least delay and have fun. My two cents... Luis On 20 jul, 19:50, giveitawhril2... at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > > So I was suspecting the Python compiler or interpreter is written in a From rNOSPAMon at flownet.com Fri Jul 4 18:37:12 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Fri, 04 Jul 2008 15:37:12 -0700 Subject: Parsing MIME-encoded data in an HTTP request References: <3a11k5-al7.ln1@nb2.stroeder.com> Message-ID: In article , Ron Garret wrote: > In article <3a11k5-al7.ln1 at nb2.stroeder.com>, > Michael Str?der wrote: > > > Ron Garret wrote: > > > I'm writing a little HTTP server and need to parse request content that > > > is mime-encoded. All the MIME routines in the Python standard library > > > seem to have been subsumed into the email package, which makes this > > > operation a little awkward. > > > > How about using cgi.parse_multipart()? > > > > Ciao, Michael. > > Unfortunately cgi.parse_multipart doesn't handle nested multiparts, > which the requests I'm getting have. You have to use a FieldStorage > object to do that, and that only works if you're actually in a cgi > environment, which I am not. The server responds to these requests > directly. > > Anyway, thanks for the idea. > > rg Hm, it actually seems to work if I manually pass in the outerboundary parameter and environ={'REQUEST_METHOD':'POST'} That seems like the Right Answer. Woohoo! Thanks Michael! rg From boblatest at googlemail.com Wed Jul 30 10:46:37 2008 From: boblatest at googlemail.com (boblatest at googlemail.com) Date: Wed, 30 Jul 2008 07:46:37 -0700 (PDT) Subject: Pointers/References in Python? Message-ID: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Hello, I have a long list of memory-heavy objects that I would like to access in differently sorted order. Let's say I'd like to have lists called by_date or by_size that I can use to access the objects in the specified order. Of course I can just build those lists naively by creating copies of the original list and then sorting them according to my wishes. But that would create huge memory overhead. Of course I could use lists of indices into the "master" list, just as in C I'd create lists or arrays of pointers into the original data. Is there a clever Python way to do this, or should I just use lists of indices? I know there is a thing called "shallow copy" that has something to do with not duplicating memory content but I don't understand the concept. Maybe that's what would help here, too. Thanks, robert From tjreedy at udel.edu Mon Jul 14 14:17:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Jul 2008 14:17:49 -0400 Subject: Moving to functional programming In-Reply-To: <6daf86f6-0a96-4811-90c4-2bc6ccbff9fb@x41g2000hsb.googlegroups.com> References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> <6daf86f6-0a96-4811-90c4-2bc6ccbff9fb@x41g2000hsb.googlegroups.com> Message-ID: James Fassett wrote: ... >> robust and efficient than the list comprehension. > > I don't know the internals of how the Python interpreter treats list > comprehensions and zip but it seems reasonable to assume an extra list > is created for the zip approach. Minor times differences between this and that way of writing things tend to be version and even system dependent. In 3.0, for instance, zip produces an iterator, not a list. So it will be faster. On the other hand, list comprehensions will be a bit slower to fix what many, including Guido, consider to be a slight design bug. From mail at timgolden.me.uk Mon Jul 7 12:16:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 07 Jul 2008 17:16:03 +0100 Subject: how to recognize IE window already opened using win32com extension In-Reply-To: <203fdfe3-78d6-4b08-a64f-a031df9cacc1@s50g2000hsb.googlegroups.com> References: <203fdfe3-78d6-4b08-a64f-a031df9cacc1@s50g2000hsb.googlegroups.com> Message-ID: <48724143.7040905@timgolden.me.uk> korean_dave wrote: > How do I use the win32com API to manipulate IE windows ALREADY open? > > ie = Dispatch("InternetExplorer.Application") opens a new window. > > But I'd like to be able to find, of windows already open, a specific > window (with a specified property, matching url, etc.) I have this strange feeling of deja vu. Is there some sort of "opening IE windows with Python" conference going on somewhere? Have a look at Roger Upole's answer from the other day: http://mail.python.org/pipermail/python-win32/2008-June/007796.html TJG From timothy.grant at gmail.com Sat Jul 19 01:18:25 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Fri, 18 Jul 2008 22:18:25 -0700 Subject: Change PC to Win or Windows In-Reply-To: <48812807.3000100@v.loewis.de> References: <48812807.3000100@v.loewis.de> Message-ID: On Fri, Jul 18, 2008 at 4:32 PM, "Martin v. L?wis" wrote: > > Calling Windows PC seems to be something that Apple did so they would > > not have to directly mention Windows. Could all the places that say PC > > that are not referring to Personal Computers in general be changed to > > Win or Windows. > > That's bikeshedding. If the name stops you from building your own > binaries, you should use prebuilt binaries, or read the documentation. > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list > Thank you for introducing me to a fabulous new word. Had to look it up, but I like it. -- Stand Fast, tjg. [Timothy Grant] -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Fri Jul 25 12:17:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 25 Jul 2008 18:17:44 +0200 Subject: Calling external program from within python In-Reply-To: <042e46cf-8ee8-4dd0-bc2b-716d588f8e83@o40g2000prn.googlegroups.com> References: <6eu684F91muhU1@mid.uni-berlin.de> <042e46cf-8ee8-4dd0-bc2b-716d588f8e83@o40g2000prn.googlegroups.com> Message-ID: <6eucl8F90apnU2@mid.uni-berlin.de> Mike Driscoll schrieb: > On Jul 25, 9:28 am, "Diez B. Roggisch" wrote: >> Mike Driscoll schrieb: >> >>> On Jul 25, 7:56 am, Emmanouil Angelakis >>> wrote: >>>> Hi, >>>> I am tryiong to do something obviously trivial such as: >>>> I have a c program called "tsys2list" that when it is ran it asks the user to give the value of "tcal" which is a variable. I want to call the "tsys2list" from within a pyrthon script lets call it "gamma.py" >>>but<<< I want to pass the value of "tcal" to th eprogram automatically and not by interacting with the keyboard. >>>> How do I do that? >>>> thanks i advance! >>>> manolis >>> There are probably many ways to do this. I would recommend checking >>> out the subprocess module and see if it does what you want. >> This will only work if the program can be fully controlled by >> commandline arguments. If interaction is required, the OP might consider >> using pexpect. >> >>> Or you >>> could learn a little Tkinter or wxPython and use that to get the >>> user's variable. Or you could even do it via the command line using >>> the "raw_input" command. >> I fail to see how *gathering* input (regardless of the method) solves >> the problem of *passing* input to a subprocess. >> >> Diez > > My understanding of the OP's request was that "tsys2list" was a custom > script of some sort that gathered info from the user, so I wanted to > know why he didn't just skip calling it and write something in Tkinter > or wxPython or even via the CLI instead. > > I'm probably just not understanding something. The program is doing some work, and needs to be told what actually to do. It does so by asking the user, sure. But then it *works*. I think that's pretty clear from """ I have a c program called "tsys2list" that when it is ran it asks the user to give the value of "tcal" which is a variable. I want to call the "tsys2list" from within a pyrthon script lets call it "gamma.py" >>>but<<< I want to pass the value of "tcal" to th eprogram automatically and not by interacting with the keyboard. """ So replacing it with something that asks the same questions leaves us with the work undone... Diez From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 2 12:11:22 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Jul 2008 18:11:22 +0200 Subject: Trouble using pinckle In-Reply-To: <1ijgp2r.1j1k5xwwbtiwcN%pdorange@pas-de-pub-merci.mac.com> References: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> <1ijgp2r.1j1k5xwwbtiwcN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <486ba8a4$0$11957$426a74cc@news.free.fr> Pierre-Alain Dorange a ?crit : > C?dric Lucantis wrote: > >> Here self is only a local variable and its meaning is only a convention. So >> assigning it to a new value won't change the object itself (and is not a good >> idea as it may be confusing for the reader). > > Thanks, i was thinking about something like that. > (snip) > I try the staticmethod, it works fine. Very helpful. > > But i don't like it very much, it seems 'complicated' (python was > supposed to be simple). Try doing the same thing in C++ !-) > I'll also try the dictionnary method. > My final idea was that a dictionnary would be perhaps simple in the > future to save/load as XML and a parser. XML ? What a strange idea ? > But perhaps i'm wrong with my vision of python. > > On a more global perspective, what are the best method to implement a > simple config file with pyhton. Well... Python does have a couple of config-related packages, starting with the one in the stdlib. You may want to find out if any of these packages fits your needs before reinventing the wheel ? > Assuming i finally want to made a bundle > app for Mac, Windows and perhaps Linux. > I develop on Mac, and on this platform the config fil (preferences) have > to be stored in a special directory : ~/Library/Preferences, no problem. > But on other platform that's not the same directory and perhaps i would > also faced to permissions issues... Yeps. Portability sometimes has a cost. I can't help you wrt/ Windows, but on unix the convention is to save user's prefs in a .yourprogram file (or directory) in the user's home directory. > But first is there a way to determine on which platfrom the python > script is running ? the os package is your friend. From pavlovevidence at gmail.com Mon Jul 7 17:04:49 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 7 Jul 2008 14:04:49 -0700 (PDT) Subject: Dynamically Changing the Base Class References: <6d60c362-ba17-4414-babd-2cc254526bca@c58g2000hsc.googlegroups.com> Message-ID: <68bba759-864e-4943-9f1e-f19b99408ef7@l64g2000hse.googlegroups.com> On Jul 7, 9:31 am, "Adam C." wrote: > We have a situation where we want a Swig-generated Python class to > have a different base (not object). It doesn't appear that we can > coerce Swig into generating the class we want at present (but we are > still enquiring). > > Is it possible to dynamically change the base class to something else? > Initial experiments appear to show it is not: > -------------------------------- snip -------------------------------->>> class Foo(object): > > pass > > >>> class Foozle(object): > > pass > > >>> Foozle.__bases__ = (Foo,) > > Traceback (most recent call last): > File "", line 1, in > Foozle.__bases__ = (Foo,) > TypeError: __bases__ assignment: 'Foo' deallocator differs from > 'object' > -------------------------------- snip -------------------------------- > > Is there a solution I am missing? > > Thanks in advance. You get the same effect as subclassing by using multiple inheritance. Suppose your SWIG class called Foo to have a base class of Base. You could instead call the SWIG class _Foo, and define Foo as a Python class like this: class Foo(_Foo,Base): pass If you do that, the resulting class will behave exactly as if _Foo were a subclass of base (apart from some introspection methods and edge cases). You can see that this is so if you look at the MRO: Foo, _Foo, Base, object Which is the same MRO that would occur if _Foo derived from Base directly. The drawback (which is also a drawback to the hypothetical base reassignment) is that Foo's __init__ method won't call Base's. The only way you can make SWIG __init__ call it's superclass's __init__ is apparently a patch. Carl Banks From tom.machinski at gmail.com Mon Jul 21 18:29:27 2008 From: tom.machinski at gmail.com (Tom Machinski) Date: Mon, 21 Jul 2008 15:29:27 -0700 Subject: Getting clear error messages with a Python templating system? Message-ID: Hi there, I'm developing web applications in Python, so I use a templating system to produce HTML. We're dealing with heavy traffic here, so my original choice was the fast and efficient Cheetah. The main problem is that Cheetah doesn't provide clear error messages. Even in the best cases, you only get some indication of the nature of the error ("TypeError: 'str' object is not callable") but you can't see the code where the error occurs. You can't even know the approximate region of the template code where the problem originates. So I tried another templating system, the newer and equally efficient Mako. Again, same problem. It should be noted that both Cheetah and Mako compile themselves to an intermediary Python file. This Python file is what's actually running, so that's where the error originates. This is very efficient, but also severely hinders debugging (see below for example of what a very simple error on a very short Mako template generates). So my question is: is there any way to get clear error messages with a Python templating system? I welcome both suggestion on how to get those with Cheetah (or Mako), and suggestions about alternative templating systems that provide better error messages. Thanks, Tom ----- # foo.mako: hello ${data} >>> print mako.template.Template(filename="foo.mako").render(data="world") hello world >>> print mako.template.Template(filename="foo.mako").render(dataerr="world") Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/site-packages/Mako-0.1.10-py2.5.egg/mako/template.py", line 114, in render return runtime._render(self, self.callable_, args, data) File "/usr/lib/python2.5/site-packages/Mako-0.1.10-py2.5.egg/mako/runtime.py", line 287, in _render _render_context(template, callable_, context, *args, **_kwargs_for_callable(callable_, data)) File "/usr/lib/python2.5/site-packages/Mako-0.1.10-py2.5.egg/mako/runtime.py", line 304, in _render_context _exec_template(inherit, lclcontext, args=args, kwargs=kwargs) File "/usr/lib/python2.5/site-packages/Mako-0.1.10-py2.5.egg/mako/runtime.py", line 337, in _exec_template callable_(context, *args, **kwargs) File "foo_mako", line 19, in render_body File "/usr/lib/python2.5/site-packages/Mako-0.1.10-py2.5.egg/mako/runtime.py", line 91, in __str__ raise NameError("Undefined") NameError: Undefined -------------- next part -------------- An HTML attachment was scrubbed... URL: From anishchapagain at gmail.com Mon Jul 21 09:11:50 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Mon, 21 Jul 2008 06:11:50 -0700 (PDT) Subject: error References: <5f4395d7-9f5c-45c3-b137-655e5c618b8c@8g2000hse.googlegroups.com> Message-ID: <0b48f3b2-0927-4745-97ce-6ee2bc8bcbe0@m73g2000hsh.googlegroups.com> On Jul 21, 1:47?pm, Fredrik Lundh wrote: > Anish Chapagain wrote: > > from Tkinter import * > > root=Tk() > > f=Frame(root,height=200,width=200) > > b=Button(f,text="quit",command=f.quit) > > f.pack() > > root.mainloop() > > > -------------------------------------------------- > > from Tkinter import * > > import sys > > root=Tk() > > f=Frame(root,height=200,width=200) > > b=Button(f,text="quit",command=sys.exit) > > f.pack() > > root.mainloop() > > > I am wondering that why the button after clikcing is not closing the > > window..please any suggestion.. > > i tries command=f.quit, sys.quit also.. > > if there is something i'm missing please help > > Assuming you accidentally left out the line where you're displaying the > button (e.g. "b.pack()"), both your samples work when running this from > the command line. > > Are you perhaps running this code from inside IDLE? ?IDLE is itself > written in Tkinter, and it doesn't always shut down the Tkinter > subsystem properly. > > ... and I have to admit that I don't know what the currently recommended > workaround is -- you'll find plenty of documentation on the net that > just says "don't do that" (run Tkinter programs from within IDLE, that > is), but surely someone should have fixed that issue by now?. > > - Hide quoted text - > > - Show quoted text - hi thank's i probably missed the b.pack() but it's till the window is not closed and error message of Windows Appear From fredrik at pythonware.com Wed Jul 23 15:45:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 21:45:52 +0200 Subject: Undocumented Python 2.6 change: Py_None vs NULL when C implementation raises exception In-Reply-To: References: Message-ID: Heikki Toivonen wrote: > I was debugging M2Crypto function written in C which changed behavior > between Python 2.6 and earlier Python versions. In an error condition > the function was supposed to raise exception type A, but with 2.6 it > raised type B, and further, there was no string value for the exception. > > I tracked this down to the C code incorrectly returning Py_None when it > should have returned NULL. Changing the C code to return NULL made it > behave correctly in 2.6. > > I don't know how common a mistake it is to return Py_None when NULL > should have been returned, but it might be worth a note in the list of > changes for 2.6 that this behavior changed, don't you think? the behaviour when setting the exception status without returning NULL has never been well-defined; it pretty much depends on what kind of error checking the code that runs later happens to use. (this has been an entertaining source of obscure errors over the years; code that uses PyErr_Clear may mask errors, and code that uses PyErr_Occurred to check if something went wrong might raise the wrong error, often at an unexpected location). From hubaghdadi at gmail.com Mon Jul 28 04:54:11 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Mon, 28 Jul 2008 01:54:11 -0700 (PDT) Subject: Module clarification Message-ID: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> Hi. I'm a Java guy and I'm playing around Python these days... In Java, we organize our classes into packages and then jarring the packages into JAR files. What are modules in Python? What is the equivalent of modules in Java? Please correct me if I'm wrong: I saved my Python code under the file Wow.py Wow.py is now a module and I can use it in other Python code: import Wow Thanks. From sunp1028 at gmail.com Wed Jul 16 11:54:02 2008 From: sunp1028 at gmail.com (patrol) Date: Wed, 16 Jul 2008 08:54:02 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> Message-ID: On 7?16?, ??10?39?, Tim Golden wrote: > patrol wrote: > > The errors are in the following: > > > Traceback (most recent call last): > > File "D:\My Documents\code\python\wmi\test.py", line 5, in > > c = wmi.WMI ("non-existent computer") > > File "C:\Python25\lib\wmi.py", line 1199, in connect > > handle_com_error (error_info) > > File "C:\Python25\lib\wmi.py", line 184, in handle_com_error > > exception_string = [u"%s - %s" % (hex (hresult_code), > > hresult_name)] > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > > 4: ordinal not in range(128) > > OK, I'm trying to set up a Virtual PC so I can install > a non-English XP. But would you mind running the > following code for me, please, so I can get a handle > on what's coming back: > > > import pythoncom > import win32com.client > > try: > win32com.client.GetObject ("winmgmts://blahblah") > except pythoncom.com_error, info: > for i in info: > print repr (i) > > > > Thanks > TJG -2147023174 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3' None None ---------------------------------------------------------------------- import pythoncom import win32com.client try: win32com.client.GetObject ("winmgmts://blahblah") except pythoncom.com_error, info: for i in info: print i -2147023174 RPC ??????? None None ------------------------------------------------------------------------- >>> a="RPC ???????" >>> a 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3' >>> ------------------------------------------------------------------------- Patrol From hat at se-162.se.wtb.tue.nl Thu Jul 10 02:24:51 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 10 Jul 2008 08:24:51 +0200 Subject: socket-module: different behaviour on windows / unix when a timeout is set References: Message-ID: On 2008-07-09, Mirko Vogt wrote: > Is that behaviour common or even documented? Found nothing. Second sentence in the socket module documentation: Note: Some behavior may be platform dependent, since calls are made to the operating system socket APIs. So yes, what you found is probably how it should behave. Albert From andre at descombes.info Sun Jul 20 10:11:56 2008 From: andre at descombes.info (=?ISO-8859-1?Q?Andr=E9_Michel_Descombes?=) Date: Sun, 20 Jul 2008 16:11:56 +0200 Subject: scanf equivalent in python Message-ID: Hello, I often need to parse strings which contain a mix of characters, integers and floats, the C-language scanf function is very practical for this purpose. I've been looking for such a feature and I have been quite surprised to find that it has been discussed as far back as 2001 but never implemented. The recommended approach seems to be to use split and then atoi or atof or to use regex and then atoi and atof. Both approaches seem to be a lot less natural and much more cumbersome than scanf. If python already has a % string operator that behaves like printf, why not implement either a %% or << string operator to behave like scanf, use could be like the followng: a, b, c = "%d %f %5c" %% "1 2.0 abcde" or a, b, c = "%d %f %5c" << "1 2.0 abcde" %% is closer to the % operator << seems more intuitive to me either of this methods seems to me much simpler than: lst = "1 2;0 abcde".split() a = int(lst[0]) b = float(lst[1]) c = lst[2] or even worse when using regular expressions to parse such simple input. I like python because it is concise and easy to read and I really think it could use such an operator. I know this has been discussed before and many times, but all previous threads I found seem to be dead and I would like to invite further investigation of this topic. Cheers, Andr? M. Descombes -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.desthuilliers at gmail.com Tue Jul 1 16:53:24 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Tue, 1 Jul 2008 13:53:24 -0700 (PDT) Subject: Why is recursion so slow? References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Message-ID: On 1 juil, 22:46, Nick Craig-Wood wrote: (snip) > By definition any function in a functional language will > always produce the same result if given the same arguments, This is only true for pure functional languages. I know you know it, but someone might think it also applies to unpure FPLs like Common Lisp. (snip) From torriem at gmail.com Mon Jul 28 01:37:48 2008 From: torriem at gmail.com (Michael Torrie) Date: Sun, 27 Jul 2008 23:37:48 -0600 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <488D5B2C.10808@gmail.com> Colin J. Williams wrote: >> >> def fun( ., cat): >> > I don't see the need for the comma in fun. It (the entire first variable!) is needed because a method object is constructed from a normal function object: def method(self,a,b): pass class MyClass(object): pass MyClass.testmethod=method That's precisely the same as if you'd defined method inside of the class to begin with. A function becomes a method when the lookup procedure in the instance object looks up the attribute and returns (from what I understand) essentially a closure that binds the instance to the first variable of the function. The result is known as a bound method, which is a callable object: >>> instance=MyClass() >>> instance.testmethod > How would this work if there was not first parameter at all? In short, unlike what most of the implicit self advocates are saying, it's not just a simple change to the python parser to do this. It would require a change in the interpreter itself and how it deals with classes. From rocksportrocker at googlemail.com Sat Jul 12 06:39:12 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Sat, 12 Jul 2008 03:39:12 -0700 (PDT) Subject: How to create a timer/scheduler in Python? References: <0stg74t0eksmnfsslukn5m7f9s4rbub8kt@4ax.com> Message-ID: <90d09691-1c43-4618-bbb7-a8c04496752f@k37g2000hsf.googlegroups.com> On 12 Jul., 11:30, John Dann wrote: > I need what I'd call (in .Net) a timer, ie I need to run a function eg > every 2 seconds - it doesn't need to be millisec accurate but it would > be nice if it wasn't eg every 4 seconds or something. > > Rather surprisingly, Core Python (Chun) doesn't seem to index 'timer' > or 'scheduler', which leaves me wondering whether this is an aspect of > Python that isn't perhaps widely used? > > Looking around on the net I can see references to a thread timer, but > I'm not really looking to start any new threads (I just want part of > the GUI to update every 2 secs) and don't want to get into that sort > of complication while still just learning Python. > > Is there really no simple timer/scheduler function available in > Python? The usual way is to use threads. Depending on you GUI lib there may exist replacements for threads, eg wxPython. As most (all ?) GUIs have some event handling mechanisms they should be able to schedule tasks and process them in the background. By the way: Using threads in Python is quite simple, even if you are a novice. Greetings, Uwe From max at alcyone.com Tue Jul 22 17:13:34 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 22 Jul 2008 14:13:34 -0700 Subject: Python Written in C? In-Reply-To: References: <143349c3-b0e9-49d8-9426-8b030b23d2c9@l42g2000hsc.googlegroups.com> Message-ID: Ethan Furman wrote: > Iain King wrote: >> On Jul 21, 6:58 am, "Krishnakant Mane" wrote: >> >>> First off all c# is absolute rubbish waist of time. if I need to >>> learn it then I better lern java or pythonfor that matter. and by the >>> way what is a "real programmer?" >> >> The story of a Real Programmer: >> >> http://www.pbm.com/~lindahl/mel.html >> >> Iain > > Wow. Awesome story. If my google-fu is up to snuff, these are "screenshots" (scans of printouts) of the actual blackjack game in operation: http://wps.com/projects/LGP-21/Software/LGP30-Blackjack1.jpg http://wps.com/projects/LGP-21/Software/LGP30-Blackjack2.jpg and here's a scan of a printout of some "source code" (machine language): http://wps.com/projects/LGP-21/Software/CrapGame.tiff -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis In time of war the devil makes more room in hell. -- (a German proverb) From bearophileHUGS at lycos.com Thu Jul 31 07:13:35 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 31 Jul 2008 04:13:35 -0700 (PDT) Subject: Case tagging and python References: Message-ID: <1cdb154c-da87-47a8-9e6d-66597a107480@x35g2000hsb.googlegroups.com> Fred Mangusta: > Could I use the join function to reform the string? You can write a function to split the words, for example taking in account the points too, etc. > And, regarding the casetest() function, what do you suggest to do? Python strings have isupper, islower, istitle methods, they may be enough for your purposes. > -open input file > -open output file > -get line of text > -split line into words > -for each word > -tag = checkCase(word) > -newword = lowercase(word) + append(tag) > rejoin words into line > write line into output file It seems good. To join the words of a line there's str.join. Now you can write a function that splits lines, and another to check the case, then you can show them to us. Yet, I don't see how much use can have your output file :-) Bye, bearophile From arslanburney at gmail.com Thu Jul 17 02:50:25 2008 From: arslanburney at gmail.com (J-Burns) Date: Wed, 16 Jul 2008 23:50:25 -0700 (PDT) Subject: Rotating a cube Message-ID: Hello. Need some help here. I have a 4*4 cube. So the equation of the cube becoming: x + 4*y + 16*z Now i want to rotate this cube 90 degrees anticlockwise( a right rotation). How can i do that? The rotation must take place with the axis of rotation being the straight line through the center of the cube and perpendicular to the "xz-plane." The axis are aligned in this fashion: y | | |________ x / / z Moreover, also tell me how to perform a rotation with the axis of rotation being the straight line through the center of the cube and perpendicular to the "yz-plane." Essentially, I need the equations of the lines after the rotation has been done in both cases. Is there a built in Python function for this? From r.grimm at science-computing.de Fri Jul 18 02:52:13 2008 From: r.grimm at science-computing.de (r.grimm at science-computing.de) Date: Thu, 17 Jul 2008 23:52:13 -0700 (PDT) Subject: None in comparison Message-ID: <549f01d2-1d15-4b0d-9440-a9402c0449ff@b2g2000prf.googlegroups.com> Hello, I'm a little confused about None in comparison. >>> id ( None ) 3086100672L >>> id ( 1 ) 134541104 >>> None < 1 True >>> I thought, the id of the object is the last comparison criterion. Therefore, None must be greater then 1. Where is the behaviour of the comparison defined?. In the __cmp__ of int. Or in the global cmp Function? Thanks in advance Rainer From bdesth.quelquechose at free.quelquepart.fr Sun Jul 27 14:27:11 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Jul 2008 20:27:11 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <488cd9f5$0$14746$426a74cc@news.free.fr> Russ P. a ?crit : > On Jul 26, 11:22 pm, Terry Reedy wrote: >> Russ P. wrote: >>> On Jul 26, 2:25 pm, Terry Reedy >>>> There is a lot of code you have not seen. Really. In informal code I >>>> use 's' and 'o' for 'self' and 'other'. I don't usually post such >>>> because it is not considered polite. So you have seen a biased sample >>>> of the universe. >>> You take the name down to a single letter. As I suggested in an >>> earlier post on this thread, why not take it down to zero letters? >> Because 1 letter is legal now, while no letters (already proposed and >> rejected) is a major change and breakage of current simplicity and >> consistency for zero functional benefit. > > Sorry, but I fail to see how it is a "major change." It only applies > to the first argument of a class member function, There's nothing like a "class member function" in Python. From kyosohma at gmail.com Thu Jul 3 10:35:10 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 3 Jul 2008 07:35:10 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: Message-ID: On Jul 3, 9:11?am, defn noob wrote: > i unzipped and put the folder in site-packages. when i run setup.py > install nothing happens. > > when i do import pp from shell it complains it doesnt exist. What is "pp"? Parallel Python? > > isnt placing the folder in site-packages enough? Usually. Sometimes you have to add the package to the Path too though. > > these setup.py-files often dont work but normally it still works. I rarely have any trouble with them on Windows, although the troublesome ones do exist. Mike From semanticist at gmail.com Sun Jul 13 16:40:30 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 16:40:30 -0400 Subject: heapq question In-Reply-To: References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> Message-ID: On Sun, Jul 13, 2008 at 4:16 PM, Duncan Booth wrote: > "Giampaolo Rodola'" wrote: >> I understand that heapq is not that efficient to implement timeouts as >> I thought at first. >> It would have been perfect if there were functions to remove arbitrary >> elements withouth needing to re-heapify() the heap every time. >> > There could be suitable functions, but there aren't any. > ... > Bottom line though is that heaps aren't really suitable for timeouts. I would argue that heaps in general are ideally suited for timeouts; it's just that the Python heapq implementation is lacking if you ever need to cancel a timeout before it expires. -Miles From cokofreedom at gmail.com Thu Jul 24 11:04:44 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 24 Jul 2008 08:04:44 -0700 (PDT) Subject: New to Python, familiar with Perl - Seeking info sources References: <18c8fc73-8ff9-4640-a020-de0be4b76ca4@z72g2000hsb.googlegroups.com> Message-ID: On Jul 24, 3:53 pm, Brett Ritter wrote: > After many years happily coding Perl, I'm looking to expand my > horizons. [no flames please, I'm pretty aware of Perl's strengths and > weaknesses and I'm just here to learn more, not to enter religious > debates]. > > I've gone through some of the online tutorials and I'll be browsing > the reference before starting the "code a lot" phase. > > My question is: What are the best sources to learn best practices or > get the answers to questions? Are there any good sources to tell me > what Perl habits are good/bad in the Python paradigm? What about > common packages that will change my life? (I do a lot of web work, > but also a lot of DB reporting) I'm also working as a Java developer > primarily, so I'm glad to see that Jython has been resurrected, but > I'm focusing on vanilla Python for the moment. > > As examples: PerlMonks has been my info source. The Perl Best > Practices and Higher Order Perl books have been my tutors into better > coding practices. CPAN has my life easy, giving me access to the DBI, > Class::DBI (and its successors), HTML::FillInForm, > Data::FormValidator, CGI::Application, and Text::CSV::Simple modules > that are staples of my coding. The (occasionally complete) Perl > Advent calendars have proven to be a good source to learn about > helpful modules that I might not otherwise stumble across. > > (I've encountered Django, but I'm getting my fill of "frameworks" from > Java for the moment, so I'm looking for lightweight pieces at the > moment) > > My (admittedly brief) searches here and on google didn't lead me to > any particular spots of concentrated Python info, and most of the Perl/ > Python stuff is either a smug attack by one camp on the other or a > rant about the behavior of an obscure feature between the two. > > Any recommendations? Thanks in advance. Best start is a quick read of DiveIntoPython that provides a nice account of how to work with Python, and relates to coming from a programming background. I also keep this List on my bookmarks, as well as the python library (http://docs.python.org//lib/). The ActiveState Python Cookbook (http://aspn.activestate.com/ASPN/ Python/Cookbook/) generally has a lot of useful code snippets worth using. Zen of Python (http://www.python.org/dev/peps/pep-0020/) shows the idea of Python and (http://www.python.org/dev/peps/pep-0008/) is the Style Guidelines for Python code. I haven't worked with the web and Python much yet so maybe someone else can help you there. Welcome :) From kanchana.senevirathna at gmail.com Tue Jul 22 05:00:41 2008 From: kanchana.senevirathna at gmail.com (Kanchana) Date: Tue, 22 Jul 2008 02:00:41 -0700 (PDT) Subject: xpathEval fails for large files Message-ID: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> Hi, I tried to extract some data with xpathEval. Path contain more than 100,000 elements. doc = libxml2.parseFile("test.xml") ctxt = doc.xpathNewContext() result = ctxt.xpathEval('//src_ref/@editions') doc.freeDoc() ctxt.xpathFreeContext() this will stuck in following line and will result in high usage of CPU. result = ctxt.xpathEval('//src_ref/@editions') Any suggestions to resolve this. Is there any better alternative to handle large documents? Kanch From fredrik at pythonware.com Wed Jul 16 17:23:48 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 23:23:48 +0200 Subject: how to match whole word In-Reply-To: <31b6a6c2-e152-418d-b5a1-477dc3dd15aa@s50g2000hsb.googlegroups.com> References: <97461ec5-151a-4527-a5fa-c5da07941e46@l42g2000hsc.googlegroups.com> <31b6a6c2-e152-418d-b5a1-477dc3dd15aa@s50g2000hsb.googlegroups.com> Message-ID: John S wrote: > Not sure why you picked \A and \Z -- they are only useful if you are > using the re.M flag. Well, they're aliases for ^ and $ in "normal" mode, at least for strings that don't end with a newline. > re.I is the same as re.IGNORECASE. More than one option may be OR'ed > together. There's no such thing as "re.O" in Python. I can understand > where you get the idea, as there is an 'o' modifier for REs in Perl. His code did opts.ignore_case and re.I or 0 which is the same as "re.I if opts.ignore_case else 0" in Python 2.5, where 0 is a zero and not an O. From JordanNealBerg at gmail.com Thu Jul 10 16:47:02 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Thu, 10 Jul 2008 13:47:02 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: <8feab8ce-1e09-4438-b00a-3b31956c56af@k37g2000hsf.googlegroups.com> <5c521979-aaf0-4b4b-9673-671a978d050a@j22g2000hsf.googlegroups.com> <3hqc74lhdkdqrjb20h34k6ab65g2hc8ucp@4ax.com> Message-ID: Well, that about wraps this up...MRAB was 100% correct, that solution worked...not sure how I managed to mess it up when I tried it early. Based on the incoming values of u here is the code with the minimal number of maskings: def findit(u): mask = 0xffffffff u += 0xe91aaa35 u ^= u >> 16 u = (u + (u << 8)) & mask u ^= u >> 4 b = (u >> 8) & 0x1ff a = (u + (u << 2) & mask) >> 19 r = a ^ hash_adjust[b] return r Thanks for your help all! From lie.1296 at gmail.com Sat Jul 26 19:26:04 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 27 Jul 2008 06:26:04 +0700 Subject: Insert character at a fixed position of lines In-Reply-To: References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> Message-ID: <1217114764.6402.5.camel@lieryan-laptop> On Sat, 2008-07-26 at 17:47 +0200, Francesco Pietra wrote: > Sorry to come again for the same problem. On commanding: > > $ python script.py 2>&1 | tee fileout.pdb > > nothing occurred (fileout.pdb was zero byte). The script reads: > > f = open("xxx.pdb", "w") > f.write('line = line[:22] + "A" + line[23:]') > f.close() > > File xxx.pdb is opened by the command: when I forgot the single quote > ' after [23:] the error answer was: > SynthaxError: EOL while scanning single-quoted string. > > Thanks > francesco I'd expect fileout.pdb to be zero bytes, what you have piped to tee fileout.pdb is the stdout of your script, i.e. whatever you "print". Since you "print"ed nothing, nothing is written to fileout.pdb You'd find your written material in the file referenced by f, i.e. "xxx.pdb". Btw, if you do f.write('line = line[:22] + "A" + line[23:]'), you'd output exactly that, and not inserting the 23rd character, you'd want to do this instead: f.write(?line = line[:22] + "A" + line[23:]) > On Sat, Jul 26, 2008 at 1:10 PM, Lie wrote: > > On Jul 26, 5:42 pm, "Francesco Pietra" wrote: > >> I am still at the stone age, using scripts (e.g., to insert a string > >> after a string) of the type > >> > >> f = open("xxx.pdb", "r") > >> for line in f: > >> print line > >> if "H16Z POPC" in line: > >> print "TER" > >> f.close() > >> > >> That is, I have to learn about modules. In your scripts I am lost > >> about the filename for the pdb file to modify, > > > > In Python, stdin and stdout (as provided by the sys module) is a file- > > like object, i.e. it have similar behavior as regular files you opened > > with open(). stdin is a read-only file, while stdout is a write-only > > file. You already know how to make read-only file, f = open("xxx.pdb", > > "r"), to make it writable, you've got to use 'w' as the mode: f = > > open("xxx.pdb", "w") > > > > After that you can do this: > > f.write('some string') > > > > > >> francesco > >> > >> > >> > >> On Sat, Jul 26, 2008 at 11:35 AM, Lie wrote: > >> > On Jul 26, 2:41 pm, "Francesco Pietra" wrote: > >> >> How to insert letter "A" on each line (of a very long list of lines) > >> >> at position 22, i.e., one space after "LEU", leaving all other > >> >> characters at the same position as in the original example: > >> > >> >> ATOM 1 N LEU 1 146.615 40.494 103.776 1.00 73.04 1SG 2 > >> > >> >> In all lines"ATOM" is constant as to both position and string, while > >> >> "LEU" is constant as to position only, i.e., "LEU" may be replaced by > >> >> three different uppercase letters. Therefore, the most direct > >> >> indication would be position 22. > >> > >> >> Should the script introduce blank lines, no problem. That I know how > >> >> to correct with a subsequent script. > >> > >> >> Thanks > >> >> chiendarret > >> > >> > If you want to leave the rest of the strings as-is (i.e. the letter A > >> > overwrites whatever on position 22), Peter's code need to be modified > >> > a little: > >> > line = line[:22] + " " + line[23:] > >> > -- > >> >http://mail.python.org/mailman/listinfo/python-list > >> > >> -- > >> Dr Francesco Pietra > >> Professor of Chemistry > >> Accademia Lucchese di Scienze, Lettere e Arti, founded in 1594 > >> Palazzo Ducale > >> 55100 Lucca (Italy) > >> e-mail chiendar... at gmail.com > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > From stefan_ml at behnel.de Thu Jul 24 12:26:16 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 24 Jul 2008 18:26:16 +0200 Subject: lxml, comparing nodes In-Reply-To: <6c91a4da-6443-4570-8dd3-01c4ec169bf3@t54g2000hsg.googlegroups.com> References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> <6c91a4da-6443-4570-8dd3-01c4ec169bf3@t54g2000hsg.googlegroups.com> Message-ID: <4888ad28$0$9491$9b4e6d93@newsspool3.arcor-online.net> code_berzerker wrote: > Thanks for help. Thats inspiring, tho not exactly what I need, coz > ignoring document order is requirement (ignoring changes in order of > different siblings of the same type, etc). I plan to try something > like that: > > def xmlCmp(xmlStr1, xmlStr2): > et1 = etree.XML(xmlStr1) > et2 = etree.XML(xmlStr2) > > queue = [] > tmpq = deque([et1]) > tmpq2 = deque([et2]) > > while tmpq: > el = tmpq.popleft() > tmpq.extend(el) > queue.append(el.tag) > > while queue: > el = queue.pop() > foundEl = findMatchingElem(el, et2) > if foundEl: > et1.remove(el) > tmpq2.remove(foundEl) > else: > return False > > if len(tmpq2) == 0: > return True > else: > return False If document order doesn't matter, try sorting the elements of each level in the two documents by some arbitrary deterministic key, such as (tag name, text, attr count, whatever), and then compare them in order, instead of trying to find matches in multiple passes. itertools.groupby() might be your friend here. Stefan From bsagert at gmail.com Wed Jul 9 19:39:24 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Wed, 9 Jul 2008 16:39:24 -0700 (PDT) Subject: Python and decimal character entities over 128. Message-ID: <95e7a2c4-0027-45e6-ace6-f0b414a0fd1c@34g2000hsh.googlegroups.com> Some web feeds use decimal character entities that seem to confuse Python (or me). For example, the string "doesn't" may be coded as "doesn’t" which should produce a right leaning apostrophe. Python hates decimal entities beyond 128 so it chokes unless you do something like string.encode('utf-8'). Even then, what should have been a right-leaning apostrophe ends up as "???". The following script does just that. Look for the string "The Canuck iPhone: Apple doesn? ??t care" after running it. # coding: UTF-8 import feedparser s = '' d = feedparser.parse('http://feeds.feedburner.com/Mathewingramcom/ work') title = d.feed.title link = d.feed.link for i in range(0,4): title = d.entries[i].title link = d.entries[i].link s += title +'\n' + link + '\n' f = open('c:/x/test.txt', 'w') f.write(s.encode('utf-8')) f.close() This useless script is adapted from a "useful" script. Its only purpose is to ask the Python community how I can deal with decimal entities > 128. Thanks in advance, Bill From thomas.troeger.ext at siemens.com Thu Jul 31 07:32:39 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Thu, 31 Jul 2008 13:32:39 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> Message-ID: > Can someone explain to me the difference between a type and a class? If your confusion is of a more general nature I suggest reading the introduction of `Design Patterns' (ISBN-10: 0201633612), under `Specifying Object Interfaces'. In short: A type denotes a certain interface, i.e. a set of signatures, whereas a class tells us how an object is implemented (like a blueprint). A class can have many types if it implements all their interfaces, and different classes can have the same type if they share a common interface. The following example should clarify matters: class A: def bar(self): print "A" class B: def bar(self): print "B" class C: def bla(self): print "C" def foo(x): x.bar() you can call foo with instances of both A and B, because both classes share a common type, namely the type that has a `bar' method), but not with an instance of C because it has no method `bar'. Btw, this example shows the use of duck typing (http://en.wikipedia.org/wiki/Duck_typing). HTH, Thomas. From jeffrey at fro.man Thu Jul 10 10:30:37 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 10 Jul 2008 07:30:37 -0700 Subject: python scalability References: Message-ID: Tim Mitchell wrote: > One of my project managers questions is: "Are we the only company in the > world with this kind and size of project?" I can't provide a bigger success story personally (my largest project is currently about 15k lines of code, eminently manageable by one person.) But Google comes to mind. Just a feeling I get from quotes like: "Python is big at Google ... being used for everything from build tools to managing ads." -- Guido Van Rossum http://www.artima.com/weblogs/viewpost.jsp?thread=143947 "When programming in python, one should design for scalability. If you design properly, the you should be able to just throw more machines at the problem and your app should scale fine." -- Greg Stein's PyCON keynote, paraphrased by Matt Harrison http://panela.blog-city.com/python_at_google_greg_stein__sdforum.htm Maybe that's not exactly the sort of scalability you're referring to, but certainly Goolge is colossal in its deployment. I have a hard time imagining that scalability based on "N lines of code" is going to be any better in any other language. Jeffrey From bj_666 at gmx.net Thu Jul 10 00:55:45 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Jul 2008 04:55:45 GMT Subject: Manipulating bitsets in struct References: Message-ID: <6dlj2hF35ua2U1@mid.uni-berlin.de> On Wed, 09 Jul 2008 20:04:24 -0400, Allen wrote: > I'm using Python to do some simple network programming, and found the > struct module very useful for such things, but is there a way to easily > manipulate bitsets such as a 16 bit word being split into 4 parts like 2 > bits, 1 bit, 4 bits, and 9 bits? > > Perhaps something like: > > struct.pack('!h(2:1:4:9)',2,0,1,100) Take a look at Construct_ instead of `struct`. .. _Construct: http://construct.wikispaces.com/ Ciao, Marc 'BlackJack' Rintsch From michael at stroeder.com Fri Jul 4 03:49:55 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 04 Jul 2008 09:49:55 +0200 Subject: Parsing MIME-encoded data in an HTTP request In-Reply-To: References: Message-ID: <3a11k5-al7.ln1@nb2.stroeder.com> Ron Garret wrote: > I'm writing a little HTTP server and need to parse request content that > is mime-encoded. All the MIME routines in the Python standard library > seem to have been subsumed into the email package, which makes this > operation a little awkward. How about using cgi.parse_multipart()? Ciao, Michael. From andreas.tawn at ubisoft.com Wed Jul 16 08:24:19 2008 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Wed, 16 Jul 2008 14:24:19 +0200 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: <487DDEE9.8060305@timgolden.me.uk> References: <8AEDA5E3386EA742B8C24C95FF0C758004623111@PDC-MAIL3.ubisoft.org> <487DDEE9.8060305@timgolden.me.uk> Message-ID: <8AEDA5E3386EA742B8C24C95FF0C7580046232B6@PDC-MAIL3.ubisoft.org> > Andreas Tawn wrote: > > Terry Reedy wrote: > >> Wrong. > > Thank you. > > > >> For loop variables continue after the loop exits. This is > >> intentional. > > I never knew that and I can't find reference to it in the docs. > > Interesting starting point. It never occurred to me > that they might not. (So I didn't look for anything > in the docs when they did :) ). > > TJG I don't have experience of too many other languages, but in C++ (and I guess C)... for (int i=0; i<10; ++i) { doStuff(i); } doStuff(i); // Error int i; for (i=0; i<10;++i) { doStuff(i); } doStuff(i); // No error That's the behaviour I was expecting. Is the Python behaviour just a happy side effect of the target list assignment or specific design decision? Cheers, Drea From babacity4 at gmail.com Thu Jul 24 16:54:51 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:54:51 -0700 (PDT) Subject: www Spankwire - Amazing porn video collection Message-ID: <06ee6164-9e2f-446a-9d4e-3826b61b94f3@j1g2000prb.googlegroups.com> www spankwire . >>>>>>>>>>Best Collection of Spankwire Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE www spankwire VIDEOS<<<<<<<<<<< . www spankwire From xahlee at gmail.com Tue Jul 22 21:44:02 2008 From: xahlee at gmail.com (xahlee at gmail.com) Date: Tue, 22 Jul 2008 18:44:02 -0700 (PDT) Subject: proliferation of computer languages References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> Message-ID: <637ca9de-75d6-48e4-b6fd-0bd36020c209@c65g2000hsa.googlegroups.com> over the past 5 years there are some negative remarks on me or my posts. I have almost never responded to any of them. Here i want to clarify a few things. ? I seldomly write off-topic posts. For example, any argument about netiquette, i consider off-topic, including defense such as what i'm doing now. But in recent years i gradually relaxed my stringent self- imposed rules in my posting habit. (See ?Aloofness vs Approable? http://xahlee.org/UnixResource_dir/writ/aloof_vs_approachable.html ) ? many says i'm posting off topic posts. In recent years they start to say i'm posting tangentially relevant posts. That's not correct. In fact, there are huge number of blatantly off-topics posts by regulars that spawn off from threads, happens regularly. The topics vary anywhere from discussing politics, law, licenses, free speech, math education, yapping on happenings of celebrity programers, and including rampant flamewars and accusations among themselves. (see ? ?Old School Netiquette? http://xahlee.org/UnixResource_dir/writ/os_netiquette.html ) ? Some people says that i don't participate in discussion, and this is part of the reason they think i'm a so-called ?troll?. Actually i do, and read every reply to my post, as well have replied to technical questions other posted. Most reply to my posts are attacks or trivial (of few sentences) i don't consider worthy to reply. A few, maybe 10% replies to my controvial posts, i consider having some value. But if i don't have opinion on what they remarked, i don't reply. Also, if all i wanted to say is ?thanks?, i tend to avoid posting such trivial posts too. (i used to reply by personal email in such cases, I still do sometimes now, but today that can be considered intrusive.) (see ? ?Philosophies of Netiquette? http://xahlee.org/UnixResource_dir/writ/phil_netiquette.html , ) In newsgroups which i feel i'm more part of the community, i do reply more often. (e.g. in the dot com years (~1999) i'm much more active in comp.lang.perl.misc including asking technical questions; during 2005-2006 while i was learning python, did somewhat frequent posts to comp.lang.python; in this year in comp.lang.lisp, i frequently replied and argued more freely. But in this year, also very active in gnu.emacs.help, most of my posts there just answered tech questions) ? Most newsgroup tech geekers consider cross-posting wrong. I consider the taboo of this convention being a major contribution to the redundant creation of new languages, and foster the hostile faction nature of programing language communities we see. (see ? ?Cross-posting & Language Factions? http://xahlee.org/Netiquette_dir/cross-post.html ) ? There's a lot rumors that says i post prodigiously. Actually, when i'm active, i post only about 1 or 2 posts per week, in the past 10 years. (See the ?Aloofness vs Approachble? article cited above. Note that, last time i checked, the stat given by poster's profile at groups.google.com is actually erroneous. I think it counts all replies or multiply cross posts) ? Many say i repeatedly post old essays i wrote that are published on my website. The total number of times i've done that is perhaps 4 or absoletly less than than 10, since the 12 years of using newsgroup started in 1996. The first of such ?repeat? must be sometimes after 2004. The interval of a ?repeat? happens is at least half a year, more likely 1 or 2 years. Also, the repeat does not happen more than once. (to be absolutely correct, possibly there is 1 essay that are posted at a max of 3 times) I ?repeat? a essay i've written because i think the issue is important, the situation has not changed, and i consider it worth to be said again. When appropriate, i incorporate information from the discussion into by my essay, with proper credits. (this esp has happened in my Python tutorial, emacs lisp tutorial, java tutorial, various classical literature on my site) Actually, most accusations about me falls apart if one just take 10 min to check the facts. ? When i used my google email account to post, as opposed to my older google account xah at xahlee.org, often people accuse me of ?changing identity to avoid killfile?. This is just one of their ways these people drivel. I don't really give a fuck i'm kill filed or not kill filed. People change emails all the time. In the past 10 years of using newsgroups, i've only used xah at xahlee.org and xahlee at gmail.com . And before 2000, i had few other emails before i registered the domain xahlee.org. I rather stick with xah at xahlee.org, but the re-login to different google accounts with several of their services is becoming a pain. See, for example, this post this month: http://groups.google.com/group/Google-Accounts-API/browse_thread/thread/a179b4fd348900aa?tvc=2 Also, whenever i had a new webhosting provider, people dig it up and accuse me of changing IP to troll. (this happens more frequently in the past, say before 2003, i think that the knowledge of digging up IP is now considered lame even amoneg these stupid tech geekers) My site xahlee.org has changed web hosting about every 2 years for variety of reasons. For a few years it was hosted free on the math educational site that used to be mathforum.org of Swathmore edu. (For some detail of my website hosting and history, see: ? ?Web Hosting Compared: 2006-01? http://xahlee.org/Periodic_dosage_dir/t1/webhosting.html A little trivia: before i had xahlee.org in 2000, my site was hosted at best.com/~xah starting in 1996. Some very very old sites still link to that. ) The only time that my change of web hoster has anything to do with my posting, is in 2006 someone harrassed me to have my web hosting kick me off due to my controversial postings in comp.lang.* groups. I have written a detailed account about it on my website. you can easily find the url by web search ?xah, dreamhost, harrassment?. (for the record, any ban, or harrasment on me, i keep a record as truthful as possile. Most of these bans, kicks, or fights happens in just aboun every online forum, inworld game groups, irc chat groups, ...etc where the participants are almost all males. Typically, they are not unlike highschool boys brawling things out. If the issue effected me or pissed me in some serious way, i publish it on my website. The keeping record is very tedious. For example, in newsgroups you might want to save all the messages in a thread this happened. In online forums, blogs, social networking sites, where posts can be deleted or modified easily, it's more tedious to keep a history of the site (e.g. screenshots), and to keep a manual written log of what happened when. Similarly, in irc, you have to save the chat, manage the chat logs, adding comment on what happened where with what chat log, finding out people's real identities if proper, etc. (as a example, i've been ban'd in freenode.com's #emacs irc chat since 2006. See ? ?Emacs Irc Channel Ban on Xah Lee? http://xahlee.org/emacs/xah_ban_emacs_irc.html . I have a bunch of irc chat logs when i'm banned. I always save the chat log when someone ban me unjustly. But it's quite time consuming to organize them and write about them.)) (as another example of ban, in about 2 months ago i was ban'd in Wikipedia. I was editing 3 article related to Tibet, of which i consider my edit very proper. But, in my opinion, it's too much againt Western's popular beliefs. I wrote detailed argument about my edit in my Wikipedia's personal talk page. The Wikipedia fuckheads not only ban'd me, but subsequently ban'd me in editing my pesonal Wikipedia page too, and blatantly deleted the detailed reason that i defended my edit. The incident is here, bottom: http://en.wikipedia.org/wiki/User_talk:P0lyglut the writing where i defended my edit, is here: http://en.wikipedia.org/w/index.php?title=User_talk:P0lyglut&diff=prev&oldid=215672906 Wikipedia these days is a huge organization (ranked top 10 of all sites), and part of the good thing is that they have some rules and regulations that prevents the fuckheads powers struggle too much, in that they have 1-month ban, with record of history, and in general has ways to further one's case to judgement. However, it's still subject to a lot tech geekers or other cartel of vested interest in keeping some article to the way they liked. I do consider Wikipedia one of the most important site and in fact part of my life, but these days i avoid ?contributing?. (e.g. i have now over 4000 links to Wikipedia articles from my site. I estimate, that for each link i've made, there are maybe 10 more article i've read. See for example: ? ?Links To Wikipedia from XahLee.org? http://xahlee.org/wikipedia_links.html , ? ?Generate a Web Links Report with Emacs Lisp? http://xahlee.org/emacs/elisp_link_report.html , ? ?Encyclopedia, My Experiences? http://xahlee.org/Periodic_dosage_dir/encyclopedia.html ? ?Lispers and Wikipedia? http://xahlee.org/emacs/lispers_n_wikipedia.html ) ) ----------------- I've been actively using online forums since 1991 in CompuServe and AppleLink days. I've seen my share of flames, netiquette arguments, etc. (the medium include: newsgroup, mailing list, web forum, irc, communities inside massive multi-player online games) I've been banned now and then in places. (in one case, legally definable harrassment, which happened and perhapss well-known at the time in comp.lang.* groups few years ago) From what i see, the banning, heated accusations and quarrels, are mostly exhibition of male nature and political struggle, not unlike political struggles that happens in society at large, such as in academia, corporations, goverment orgs, between corporations, between nations. Some say ?why can't you be normal?? It is true i tend to discuss controversial topics and with non- conformal attitude. I have my reasons and you could say it's just a personality. However, ?being not normal? is not a reason to accuse. There are philosophers, unorthodox, dissenters, free thinkers, flag bunners, protesters, traitor/founder, homosexuals ... many are persecuted, considered a crime, in the past, and some are now considered national or international heros. Btw, this post is not some kinda formal defense to some formal accusations. Newsgroups has always been a very contentious and argumentive medium, and perhaps far more wortheless with relatively little readership and impact on society than tech geeking regulars like to think. People in fact like newsgroups that way. I don't feel necessary to respond to morons. This post is just one of my post i feels like writing. You guys to whatever it is that you do. PS as i have detailed, i have my own moral ethics in posting. Most posts and opinions are just too stupid, igonrant, for me to consider replying. If you really belived that some of my opinion or posts are wrong, contain bad advice, or wrong fact, then do post, as i do read every reply it shows up in groups.google.com. And, whatever is your opinion, i would recommend you spend 30 minutes to write your reply. (as i do spend 1 to even 6 hours in most of my newsgroup posts as explained in detail in one of the above cited article) Also, if the subject is unconventional and you see i put forth my opinion forcefully, i suggest you take 30 minutes, to think, do research, about it before you reply. Also, if prefer to reply to those who post with real names. Again, i don't consider this is some serious issue, or that my opinions and beliefs and behaviors are always correct. It's just another newsgroup day. Do whatever it is that you do. Xah ? http://xahlee.org/ ? From bignose+hates-spam at benfinney.id.au Thu Jul 10 19:50:31 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 11 Jul 2008 09:50:31 +1000 Subject: Python and decimal character entities over 128. References: <95e7a2c4-0027-45e6-ace6-f0b414a0fd1c@34g2000hsh.googlegroups.com> Message-ID: <87vdzds3i0.fsf@benfinney.id.au> I don't have an answer for why Python might be mis-handling the data, but wanted to make a factual correction: bsagert at gmail.com writes: > Some web feeds use decimal character entities that seem to confuse > Python (or me). For example, the string "doesn't" may be coded as > "doesn’t" which should produce a right leaning apostrophe. That character isn't a "right leaning apostrophe"; it has nothing to do with apostrophes. It is the character called "right single quotation mark" in and in Unicode (code point U+2019). It's a typographical error to use a quotation mark as an apostrophe. Use the apostrophe character (U+0027) where an apostrophe is intended, and quotation mark characters where those are intended. This is directed, of course, at the person generating that output. -- \ ?If you go to a costume party at your boss's house, wouldn't | `\ you think a good costume would be to dress up like the boss's | _o__) wife? Trust me, it's not.? ?Jack Handey | Ben Finney From fredrik at pythonware.com Wed Jul 23 08:02:24 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 14:02:24 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> Message-ID: Jaco Naude wrote: > That said, let me double check something which might be causing > problems since you will be familiar with this. Which Python.h file do > you include when including the DLL in your programs? The one in the > source distribution of the one in the installation distribution? I've > been including the one in the installation distribution all along. > When I try to include the one in the source distribution it gets up to > the point where it looks for the following include: > > #include "pyconfig.h" > > This file is not in the same directory as the Python.h file in the > source distribution. Because of this I just used Python.h in the > installation distribution. that's just two copies of the same file, as far as I know. the "pyconfig.h" file contains platform-specific information; it's generated from pyconfig.h.in on Unix-style systems, and copied from the PC directory on Windows. From nagle at animats.com Tue Jul 22 14:48:25 2008 From: nagle at animats.com (John Nagle) Date: Tue, 22 Jul 2008 11:48:25 -0700 Subject: CPython VM internals - Wiki page In-Reply-To: References: Message-ID: <48862716$0$17157$742ec2ed@news.sonic.net> Terry Reedy wrote: > Various people have asked on c.l.p about documentation of CPython's > virtual machine internals. The usual answers have been to see the dis > module doc for bytecodes and 'read the code' for more. Jakob Sievers > did so and posted his notes, with additions from Martin v. L?wis, as > > http://wiki.python.org/moin/CPythonVmInternals That's interesting. It's dumber than I thought. All temporaries on the stack are "boxed" as PyObjects. That's simple and portable, but slow. John Nagle From pavlovevidence at gmail.com Sat Jul 26 04:19:05 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 26 Jul 2008 01:19:05 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: On Jul 24, 1:41?am, Jordan wrote: > Except when it comes to Classes. I added some classes to code that had > previously just been functions, and you know what I did - or rather, > forgot to do? Put in the 'self'. In front of some of the variable > accesses, but more noticably, at the start of *every single method > argument list.* This cannot be any longer blamed as a hangover from > Java - I've written a ton more code, more recently in Python than in > Java or any other OO language. What's more, every time I go back to > Python after a break of more than about a week or so, I start making > this 'mistake' again. The perennial justification for this 'feature' > of the language? That old Python favourite, "Explicit is better than > implicit." I'm sure some people use that argument, but in my observations the more common justification for explicit self is that makes code easier to read, by making it obvious that something is a class attribute instead of a local or global variable. Your claim is that self makes code a lot harder to write, but you've disregarded the viewpoint of the reader altogether. You probably are aware that there is another Zen that says "Readability Counts". Would you also suggest that Zen needs to be done away with? > If there was one change I could make to Python, it would be to get > that damn line out of the Zen. Personally, I think you've applied it to things that it wasn't really intended for. It's mostly applies to things like language syntax, type conversions, and other semantics. For instance in Perl there are cases where you can omit quotes around strings; that'd be a major no- no in Python. Or how about this: a = 1 # a is an integer a += "hello" # oops, now it's a string Let me suggest that such things are a Very Bad Idea and so that line is better left in place. Carl Banks From patf at well.com Mon Jul 28 18:07:20 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 15:07:20 -0700 (PDT) Subject: Download excel file from web? References: Message-ID: On Jul 28, 3:00?pm, "p... at well.com" wrote: > Hi - experienced programmer but this is my first Python program. > > This URL will retrieve an excel spreadsheet containing (that day's) > msci stock index returns. > > http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > Want to write python to download and save the file. > > So far I've arrived at this: > > [quote] > # import pdb > import urllib2 > from win32com.client import Dispatch > > xlApp = Dispatch("Excel.Application") > > # test 1 > # xlApp.Workbooks.Add() > # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > # xlBook = xlApp.ActiveWorkbook > # xlBook.SaveAs(Filename='C:\\test.xls') > > # pdb.set_trace() > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > excel? > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > +25%2C+2008&export=Excel_IEIPerfRegional') > # test 2 - returns check = False > check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > indexperf/excel? > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > xlApp = response.fp > print(response.fp.name) > print(xlApp.name) > xlApp.write > xlApp.Close > [/quote] Woops hit Send when I wanted Preview. Looks like the html [quote] tag doesn't work from groups.google.com (nice). Anway, in test 1 above, I determined how to instantiate an excel object; put some stuff in it; then save to disk. So, in theory, I'm retrieving my excel spreadsheet with response = urllib2.urlopen() Except what then do I do with this? Well for one read some of the urllib2 documentation and found the Request class with the method has_data() on it. It returns False. Hmm that's not encouraging. I supposed the trick to understand what urllib2.urlopen is returning to me; rummage around in there; and hopefully find my excel file. I use pdb to debug. This is interesting: (Pdb) dir(response) ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', 'code', ' fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', 'readline', ' readlines', 'url'] (Pdb) I suppose the members with __*_ are methods; and the names without the underbars are attributes (variables) (?). Or maybe this isn't at all the right direction to take (maybe there are much better modules to do this stuff). Would be happy to learn if that's the case (and if that gets the job done for me). pat From paddy3118 at googlemail.com Sat Jul 5 12:42:34 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 5 Jul 2008 09:42:34 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <9cae59d9-ead4-45bc-a980-2ac2e1616f9b@p25g2000hsf.googlegroups.com> Message-ID: <887bdcaa-7d90-4bf7-81b8-bd70dbe11e31@l64g2000hse.googlegroups.com> On Jul 5, 4:13?pm, Mark Dickinson wrote: > It seems like an appropriate moment to point out *this* paper: > > http://swtch.com/~rsc/regexp/regexp1.html > That's the one! Thanks Mark. - Paddy. From robert.rawlins at thinkbluemedia.co.uk Thu Jul 17 13:47:13 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 17 Jul 2008 18:47:13 +0100 Subject: Unusual Exception Behaviour In-Reply-To: <006001c8e831$5c1487b0$143d9710$@rawlins@thinkbluemedia.co.uk> References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> <8904.90077804333$1216313689@news.gmane.org> <006001c8e831$5c1487b0$143d9710$@rawlins@thinkbluemedia.co.uk> Message-ID: <007001c8e835$252a2990$6f7e7cb0$@rawlins@thinkbluemedia.co.uk> >> That's seriously weird. What's your Python version and platform? On my >> Windows and Linux machines, with more recent Python versions the above >> trick works flawlessly. >> >> Check your environment, namely PYTHON* variables. There may be >> something causing this behaviour. Unset them. >> >> Check the first line of your scripts. If you're calling wrong Python >> interpreter (there may be more than one in the system for some >> reason), this may cause it. >> >> You could also try setting up PYTHONINSPECT environment variable or >> run the python interpreter with -i option before program filename, >> which drops you into an interactive shell upon exception or >> termination of a program. >> >> This behavior is seriously unusual for Python. Maybe you have some old >> / buggy version? > > Thanks for that MK. I'm using Debian with Python 2.5 from the stable apt repository, installed > but a couple of days ago. I'll be sure to look into those other elements you suggested also. > > I'm not sure if it bares any resemblance but this application runs a gobject mainloop and uses > > dbus quite extensively. > > Don't think this might have something to do with the way I have my loggers configured do you? > > For some reason it sits in my mind that this issue started when I moved my logging > > > > > > > configuration from programmatic into a config file, I can't be totally sure of that though. > > I've attached the config file that I use, does it all look ok to you? I wonder if the way I've > not added any handles/formatters to my root logger might be causing beef? > > This is certainly a strange one. Ok, Just to add a little interest, when I comment out the configuration line for my logging, like so: #logging.config.fileConfig("/myapp/configuration/logging.conf") It appears to throw the exceptions as normal :-) :-s Sounds as if it's a conflict with my logging configuration, I wonder what though. From siona at chiark.greenend.org.uk Tue Jul 15 10:21:13 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 15 Jul 2008 15:21:13 +0100 (BST) Subject: One step up from str.split() References: Message-ID: Joel Koltner wrote: >I normally use str.split() for simple splitting of command line arguments, but >I would like to support, e.g., long file names which-- under windows -- are >typically provided as simple quoted string. E.g., > >myapp --dosomething --loadthis "my file name.fil" > >...and I'd like to get back a list wherein ListEntry[3]="my file name.fil" , > [ ... ] Hang on, let's back up here a second. You want a command line like >myapp --dosomething --loadthis "my file name.fil" to be available as ['--dosomething', '--loadthis', 'my file name.fil'] ? What's wrong with sys.argv ? -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From google at mrabarnett.plus.com Tue Jul 15 18:11:43 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 15 Jul 2008 15:11:43 -0700 (PDT) Subject: Python internals References: <008ca729$0$20313$c3e8da3@news.astraweb.com> Message-ID: On Jul 15, 2:50?pm, Peter Anderson wrote: > Hi! ?I am slowly teaching myself Python. ?I was reading David Beazley's > excellent book "Python - Essential Reference"; in particular about > variables. ?Let me quote: > > "Python is a dynamically typed language in which names can represent > values of different types during the execution of a program. In fact the > names used in the program are really just labels for various quantities > and objects. The assignment operator simply creates an association > between a name and a value. This is different from C, for example, in > which a name (variable) represents a fixed size and location in memory..." > > As an old mainframe programmer, I understand the way C does things with > variable but this text got me wondering how Python handles this > "association" between variable name and value at the lower level. ?Is it > like a fifo list? > > If there is any Python guru that can help I would be most interested in > your thoughts. > They're stored in a dictionary (hash table), called a "dict" in Python, the name being the key and the value being a reference to the actual value. The CPython implementation is written in C (hence the name) and implements references with pointers. From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 10 07:47:48 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 10 Jul 2008 13:47:48 +0200 Subject: FOSS projects exhibiting clean/good OOP? In-Reply-To: <1fdb9220-4ddd-4633-b5bd-91fbfc91453d@z66g2000hsc.googlegroups.com> References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> <1fdb9220-4ddd-4633-b5bd-91fbfc91453d@z66g2000hsc.googlegroups.com> Message-ID: <4875f6af$0$26425$426a74cc@news.free.fr> Phillip B Oldham a ?crit : > On Jul 9, 9:26 pm, "bruno.desthuilli... at gmail.com" > wrote: >> This is somewhat subjective... Some would say that Python's object >> model is fundamentally broken and crappy (not MHO, needless to say) >> that Python + "solid OO principles" is antinomic !-) > > Really? Would you happen to be able to provide any further information > on that? Well... Some people seems to think that an object model with no language-enforced access restriction, no implicit 'self' reference and the necessity to explicitely declare 'self' as first argument of methods is broken. You'll also find a couple guys complaining about Python not forcing you to put everything into classes, ? la Java. From duncan.booth at invalid.invalid Sat Jul 12 14:15:28 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jul 2008 18:15:28 GMT Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> Message-ID: "Giampaolo Rodola'" wrote: > > My question is the following: is it safe to avoid to re-heapify() a > heap when I remove or move an element which is not the first one? > Example: > >>>> from heapq import * >>>> heap = [2,4,6,7,1,2,3] >>>> heapify(heap) >>>> del heap[4] >>>> # Am I forced to heapify() the heap here? > > Thanks in advance. No, it is not safe to avoid re-heapifying. After you call heapify the list is ordered such that for any 'n' in the range 1..len(heap)//2 it is the case that heap[n-1] <= heap[2*n-1] and when heap[2*n] exists heap[n-1] <= heap[2*n]. So: >>> heap = [0, 100, 1, 101, 102, 2, 3] >>> heapify(heap) >>> heap [0, 100, 1, 101, 102, 2, 3] >>> del(heap[4]) >>> heap [0, 100, 1, 101, 2, 3] >>> heapify(heap) >>> heap [0, 2, 1, 101, 100, 3] after deleting heap[4] it is no longer the case that heap[1] >= heap[4] as the old heap[5] was a child of heap[2] not of heap[1]. From basti.wiesner at gmx.net Sat Jul 5 06:44:05 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sat, 05 Jul 2008 12:44:05 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Carl Banks : > On Jul 5, 4:12 am, "Sebastian \"lunar\" Wiesner" > wrote: >> Paddy : >> >> >> >> > On Jul 4, 1:36 pm, Peter Otten <__pete... at web.de> wrote: >> >> Henning_Thornblad wrote: >> >> > What can be the cause of the large difference between re.search and >> >> > grep? >> >> >> grep uses a smarter algorithm ;) >> >> >> > This script takes about 5 min to run on my computer: >> >> > #!/usr/bin/env python >> >> > import re >> >> >> > row="" >> >> > for a in range(156000): >> >> > row+="a" >> >> > print re.search('[^ "=]*/',row) >> >> >> > While doing a simple grep: >> >> > grep '[^ "=]*/' input (input contains 156.000 a in >> >> > one row) >> >> > doesn't even take a second. >> >> >> > Is this a bug in python? >> >> >> You could call this a performance bug, but it's not common enough in >> >> real code to get the necessary brain cycles from the core developers. >> >> So you can either write a patch yourself or use a workaround. >> >> >> re.search('[^ "=]*/', row) if "/" in row else None >> >> >> might be good enough. >> >> >> Peter >> >> > It is not a smarter algorithm that is used in grep. Python RE's have >> > more capabilities than grep RE's which need a slower, more complex >> > algorithm. >> >> FWIW, grep itself can confirm this statement. The following command >> roughly takes as long as Python's re.search: >> >> # grep -P '[^ "=]*/' input >> >> -P tells grep to use real perl-compatible regular expressions. > > This confirms that a particular engine might not be optimized for it, > but it's not necessarily a reflection that the engine is more complex. My posting wasn't intended to reflect the differences in complexity between normal GNU grep expressions (which are basically extended POSIX expressions) and perl-compatible expressions. The latter just _are_ more complex, having additional features like look aheads or non-greedy qualifiers. I just wanted to illustrate, that the speed of the given search is somehow related to the complexity of the engine. Btw, other pcre implementation are as slow as Python or "grep -P". I tried a sample C++-code using pcre++ (a wrapper around libpcre) and saw it running equally long. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From mccredie at gmail.com Tue Jul 1 16:23:54 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 1 Jul 2008 13:23:54 -0700 (PDT) Subject: Please check my understanding... References: Message-ID: On Jul 1, 12:35?pm, Tobiah wrote: > list.append([1,2]) will add the two element list as the next > element of the list. > > list.extend([1,2]) is equivalent to list = list + [1, 2] > and the result is that each element of the added list > becomes it's own new element in the original list. > > Is that the only difference? > > From the manual: > > s.extend(x) ?| ?same as s[len(s):len(s)] = x > > But: (python 2.5.2) > > >>> a > [1, 2, 3] > >>> a[len(a):len(a)] = 4 > > Traceback (most recent call last): > ? File "", line 1, in > TypeError: can only assign an iterable > > > > Also, what is the difference between list[x:x] and list[x]? > > >>> a[3:3] = [4] > >>> a > > [1, 2, 3, 4] > ** Posted fromhttp://www.teranews.com** In this example: > s.extend(x) | same as s[len(s):len(s)] = x x _must_ be iterable. As the error states, `4` is not iterable. the s[start:stop] notation is called slicing: >>> x = range(10) >>> x[0] 0 >>> x[1] 1 >>> x[0:1] [0] >>> x[0:2] [0, 1] >>> x[0:3] [0, 1, 2] >>> x[1:3] [1, 2] >>> x[5:-1] [5, 6, 7, 8] >>> x[5:] [5, 6, 7, 8, 9] In general `x[len(x):len(x)] = seq` is a stupid way to extend a list, just use .extend or +=. Matt From winter at biotec.tu-dresden.de Mon Jul 28 12:15:19 2008 From: winter at biotec.tu-dresden.de (Christof Winter) Date: Mon, 28 Jul 2008 18:15:19 +0200 Subject: SOAPpy WSDL problem: namespace of schema and import match error In-Reply-To: <6f5lirF9vmv1U1@mid.dfncis.de> References: <6f5lirF9vmv1U1@mid.dfncis.de> Message-ID: <6f69knFa1adaU1@mid.dfncis.de> Christof Winter wrote, On 28.07.2008 12:32: > I am trying to use a webservice with SOAPpy: > > import SOAPpy > intact_wsdl = "http://www.ebi.ac.uk/intact/binary-search-ws/binarysearch?wsdl" > intact_serv = SOAPpy.WSDL.Proxy(intact_wsdl) [...] > My question: > - Is there a problem with the WSDL file being not valid? I just figured out that this could indeed be true. The WSDL document contains an XML Schema import that probably should be an XML Schema include: "The import element is used to add multiple schemas with different target namespace to a document." http://www.w3schools.com/schema/el_import.asp "The include element is used to add multiple schemas with the same target namespace to a document." http://www.w3schools.com/schema/el_include.asp Maybe I should post this to comp.text.xml Christof From tjreedy at udel.edu Fri Jul 18 18:15:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Jul 2008 18:15:48 -0400 Subject: round function error??? In-Reply-To: References: Message-ID: Anthony wrote: > Isn't this a mistake??? > >>>> round(3499.349439034,44) > 3499.3494390340002 >>>> round(_,2) > 3499.3499999999999 >>>> round(_,1) > 3499.4000000000001 > > My Python 2.5.1 spat that out.. No, round() return binary floats that, in general, cannot represent decimal floats exactly. Formatted printing gives what you expect. >>> '%8.2f' % x ' 3499.35' From fredrik at pythonware.com Sun Jul 20 14:30:28 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jul 2008 20:30:28 +0200 Subject: Web Server In-Reply-To: <1dc5311f-6243-41d4-b5da-78183c9668e4@m44g2000hsc.googlegroups.com> References: <1dc5311f-6243-41d4-b5da-78183c9668e4@m44g2000hsc.googlegroups.com> Message-ID: misceverything at gmail.com wrote: > Thanks, Fredrik - that definitely works. Now to get a little greedy - > is there something along those lines that is a bit more secure (i.e. > allows HTTPS, possibly with authentication)? Basically something that > you would feel more comfortable opening up to the Internet.. open up to whom? I'm not sure I like the combination of "windows app" and "opened up to the internet", really... but assuming that you're aware of the issues involved, and want a light-weight HTTP server for Windows, this one's pretty nice: http://www.aprelium.com/abyssws/ there's also apache, of course, and a bunch of others, including several Python solutions (more or less pre-packaged). but the "open up" part still sounds a bit risky. maybe you could turn things around, and let the application "push" data to your server instead? From dstromberglists at gmail.com Sat Jul 26 15:15:40 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Sat, 26 Jul 2008 19:15:40 GMT Subject: Stripping parts of a path References: Message-ID: On Sat, 26 Jul 2008 08:59:15 -0300, Tim Cook wrote: > Hi All, > > I just ran into an issue with the rstrip method when using it on path > strings. > > When executing a function I have a need to strip off a portion of the > current working directory and add on a path to a log file. Initially > this worked great but then I added a branch in SVN which caused the path > to contain 'LNCCWorkshop'. The rstrip() then began removing the > characters 'shop' leaving an incorrect path to the log file. When I > hard coded this path it worked okay but then did the same thing later in > the file when I needed to point to a database. The code worked fine with > a different path. Here are some code fragments. > > logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/ at_build_errors.log' > > this worked when the path was: > /home/tim/ref_impl_python/TRUNK/oship/src/oship/atbldr > > the code above returns: > /home/tim/ref_impl_python/TRUNK/oship/log/at_build_errors.log > > but when I tried a branches version that has the path: > /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/src/oship/atbldr > > it SHOULD return: > /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/log/ at_build_errors.log > > but I get: > /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/ at_build_errors.log > > logfile=os.getcwd() > print logfile is correct; but when I add the .rstrip('src/oship/atbldr') > it also strips the 'shop' off of LNCCWorkshop and returns > /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/ at_build_errors.log > > I had two other people looking at this as we did troubleshooting and we > could not determine the cause. It is repeatable with this path name. In > resolution I renamed the branch to just LNCC and it works fine. > > Thoughts? > > Tim Is this the Tim Cook I worked with at UCI? Anyway, I think the os.path module might have something for you. As a little bonus, it should produce code that works well with other operating systems, and should deal gracefully with repeated slashes. From callen314 at gmail.com Thu Jul 31 21:27:36 2008 From: callen314 at gmail.com (Craig Allen) Date: Thu, 31 Jul 2008 18:27:36 -0700 (PDT) Subject: when does the GIL really block? Message-ID: I have followed the GIL debate in python for some time. I don't want to get into the regular debate about if it should be gotten rid of (though I am curious about the status of that for Python 3)... personally I think I can do multi-threaded programming well, but I also see the benefits of a multiprocess approach. I'm not so egotistical that I don't realize perhaps my mt programming has not been "right" (though it worked and was debuggable) or more likely that doing it right I have avoided even trying some things people want mt programming to do... i.e. to do mt programming right you start to use queues a lot, inter-thread asynchronous, non-blocking, communication, which is essentially the multi-process approach, using IPC (except that the threads can see the same memory when, in your special case, you know that's ok. Given something like a reader-writer lock, this can have benefits... but again, whatever. My question is that given this problem, years ago before I started writing in python I wrote some short programs in python which could, in fact, busy both my CPUs. In retrospect I assume I did not have code in my run function that causes a GIL lock... so I have done this again. I start two threads... I use gkrellm to watch my processors (dual processor machine). If I merely print a number... both CPUS are getting 90% simultaneous loads. If I increment a counter and print it too, the same, and if I create a small list and sort it, the same. I did not expect this... I expected to see one processor pegged at around 100%, which should sometimes switch to the other processor. Granted, the same program in C/C++ would peg both processors at 100%... but given that the overhead in the interpreter cannot explain the extra usage, I assume the code in my thread's run functions is actually executing non-serially. I assume this is because what I am doing does not require the GIL to be locked for a significant part of the time my code is running... what code could I put in my run function to see the behavior I expected? What code could I put there to take advantage of the possibility that really the GIL is not locked enough to cause actual serialization of the threads... anyone care to explain? From rocksportrocker at googlemail.com Tue Jul 1 06:56:25 2008 From: rocksportrocker at googlemail.com (rocksportrocker) Date: Tue, 1 Jul 2008 03:56:25 -0700 (PDT) Subject: problem with exec and locals() Message-ID: <95f07476-e3c8-45e4-82b3-0e48c9188f8e@79g2000hsk.googlegroups.com> Hi, the following code does not work until I ommit the "a=0" statement. def test(): exec "a=3" in locals() print a a=0 test() print raises: UnboundLocalError: local variable 'a' referenced before assignment Can anybody explain what is going wrong here ? Greetings, Uwe From phil at freehackers.org Wed Jul 30 07:24:15 2008 From: phil at freehackers.org (BlueBird) Date: Wed, 30 Jul 2008 04:24:15 -0700 (PDT) Subject: Continuous integration for Python projects References: <6f8pelFafh42U1@mid.uni-berlin.de> Message-ID: <551e5dcc-bc22-4a23-9adf-f13a05c1e9cf@z66g2000hsc.googlegroups.com> On Jul 29, 4:56?pm, "Diez B. Roggisch" wrote: > Hussein B wrote: > > Hi. > > Please correct my if I'm wrong but it seems to me that the major > > continuous integration servers (Hudson, CruiseControl, TeamCity ..) > > don't support Python based application. > > It seems they mainly support Java, .NET and Ruby. > > Can I use one of the previous listed servers for Python project? > > Hudson can, and AFAIK CC as well - they only invoke shell-scripts (at least > hudson does, and CC you can convince doing that using ANT) > I have CC almost running here with python tests and there is no technical problem in front. You must package your test scripts so that they exit with something different than 0 in case of failure, and then just use the Exec runner of CC to run them. From bj_666 at gmx.net Sun Jul 13 04:41:37 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Jul 2008 08:41:37 GMT Subject: Problems with curses References: Message-ID: <6dtte1F49rsiU1@mid.uni-berlin.de> On Sat, 12 Jul 2008 20:49:56 -0400, Clay Hobbs wrote: > Unfortunately, the error message isn't very helpful. But it would be helpful to tell it. If you get exceptions, always copy'n'paste the traceback here. People might know what the exception means and share their wisdom. Ciao, Marc 'BlackJack' Rintsch From iainking at gmail.com Thu Jul 3 05:01:08 2008 From: iainking at gmail.com (Iain King) Date: Thu, 3 Jul 2008 02:01:08 -0700 (PDT) Subject: Win32.client, DAO.DBEngine and exceeding the file sharing count lock References: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> <9ab0cc2d-5a7e-40ca-a4da-084347f147cd@m36g2000hse.googlegroups.com> <486BAA56.4070303@timgolden.me.uk> Message-ID: <45054c4a-e673-4e0e-9569-232dfa8ee12d@k13g2000hse.googlegroups.com> On Jul 2, 8:13?pm, Tim Golden wrote: > In case it helps, there's a recipe just shown up > on the Python Cookbook which at least illustrates > DAO use: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/572165 > > TJG On Jul 2, 6:30 pm, "M.-A. Lemburg" wrote: > You could try to use the Access ODBC driver and access the database > that way via mxODBC. That would be faster as well: > > http://www.microsoft.com/technet/prodtechnol/windows2000serv/technolo... > (scroll down to table 7.1) > > Apart from that option and if you are really in need for larger > transactions, I'd suggest that you move to SQL Server for processing > (if you can). Access is not really made for heavy-lifting and big > transactions. Thanks for the help. I'll check those out, in case there's a performance gain to be had, but I found that ADO can in fact do exactly what I want; on the comments of the page I previously linked to which said ADO couldn't was a posting which refuted some of the OP's claims; ADO can set some options on it's open connection, including Max Locks Per Record. My code now looks like this: self._connection.Open(self._DSN) if MAX_LOCKS != None: self._connection.Properties("Jet OLEDB:Max Locks Per File").Value = MAX_LOCKS rs = win32com.client.Dispatch(r'ADODB.Recordset') N.B. I'm writing tools software for a 3rd party app which uses an Access db as it's output format, so I'm locked in. No way to switch to SQL server. Thanks both! Iain From alexnbryan at gmail.com Thu Jul 17 01:37:39 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 22:37:39 -0700 (PDT) Subject: Need help getting BeautifulSoup contents Message-ID: <18501881.post@talk.nabble.com> The trick to this one is that the html looks something like this:
american, a href="/browse/blue" linkindex="12" set="yes">blue brick churn cottage cream " My question is I want everything inside, the contents of each ad the regular text of the . I know I can do like a.contents, but it only gives me the first one, in this case being "blue". I want the contents of each of those and the regular contents of the . P.S. notice the things inbetween the tags, I need those too :( Can anyone help? -- View this message in context: http://www.nabble.com/Need-help-getting-BeautifulSoup-contents-tp18501881p18501881.html Sent from the Python - python-list mailing list archive at Nabble.com. From steve at REMOVE-THIS-cybersource.com.au Wed Jul 30 23:29:28 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Jul 2008 03:29:28 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <00a121b4$0$20313$c3e8da3@news.astraweb.com> Message-ID: <00a12d08$0$20313$c3e8da3@news.astraweb.com> On Thu, 31 Jul 2008 02:41:08 +0000, Steven D'Aprano wrote: > On Wed, 30 Jul 2008 09:23:05 -0600, Matthew Fitzgibbons wrote: ... >> Although, if my function is expecting a list, my preference is to do: >> >> if not isinstance(x, list): >> raise SomeMeaningfulException() >> # do stuff with the list >> >> I put my type checking at the top of the function, so readers can >> reference it easily. > > And thus you break duck-typing and upset anybody who wants to pass a > sequence that doesn't inherit directly from list. Correction: delete "directly" from the above. -- Steven From claird at lairds.us Wed Jul 30 20:55:52 2008 From: claird at lairds.us (Cameron Laird) Date: Thu, 31 Jul 2008 00:55:52 +0000 Subject: Is there a such Python module ? References: Message-ID: In article , Matthew Fitzgibbons wrote: >Johny wrote: >> Is there a Python module that can help with reading SMS message from a >> mobile phone? >> Or is there an example how to read SMS message using a program written >> in Python,C, or any other language? >> Thank you very much for help >> L. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > >There is a Python distro for Symbian, if your phone is running that. You >can do things like send/receive SMS messages, control the camera, etc. >http://wiki.opensource.nokia.com/projects/PyS60. Can't speak to anything >else. Cellular handsets are consumer devices; their notion of "standardization" is ENTIRELY different from the way most of Pythonia behaves. So, yes, there are all sorts of resources of Nokia devices. Gammu is also likely to interest you, depending on your hardware. There are still other solutions specific to Motorola, ..., although Python's presence and compatibility declines steeply when you leave Nokia and/or Gammu. From __peter__ at web.de Sat Jul 12 04:26:46 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Jul 2008 10:26:46 +0200 Subject: variable question References: <6f02608a-2b2e-478d-a153-d10bbfb58981@c58g2000hsc.googlegroups.com> <48782d93$0$20780$9b622d9e@news.freenet.de> <98553eaa-a435-488f-9f14-831d858ac800@m45g2000hsb.googlegroups.com> Message-ID: happy wrote: > I think its better to leave the "teach kiddies" tutoring opportunity > for the python experts out there. If you know how to make some simple scripts that do something that kids find interesting and are able to convey your enthusiasm, you are better suited to teach than any expert who tortures them with explanations of how a variable is not a name is not a pointer. Peter From Russ.Paielli at gmail.com Wed Jul 30 00:36:45 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 21:36:45 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> <466157f1-adcb-45f6-8c2d-b3c245a6ce8d@p31g2000prf.googlegroups.com> <47a24fed-6822-4767-aad3-07a72ddc3a1a@m73g2000hsh.googlegroups.com> <7a090a5e-c103-4182-b8d9-c1c0c4819696@y38g2000hsy.googlegroups.com> Message-ID: <90f35a30-3fea-43f1-bda8-74960412aa75@q28g2000prh.googlegroups.com> On Jul 29, 2:27 am, Iain King wrote: > On Jul 29, 5:33 am, "Russ P." wrote: > > > > > On Jul 28, 8:44 pm, alex23 wrote: > > > > On Jul 29, 4:46 am, "Russ P." wrote: > > > > > As I said, I could write a pre-processor myself to > > > > implement it in less than a day. > > > > So WHY DON'T YOU WRITE IT ALREADY? > > > I'm working on something else right now if you don't mind, but I'll > > get to it in good time. > > > Conceptually, the matter is simple. All I need to do is to grab the > > first formal argument of each def, then search for occurrences of any > > word in the body of the def that starts with a dot, and insert that > > first argument in front of it. > > > I expect the "hard" part will be breaking up the body of the def into > > "words." I could just split each line on white space, except for > > situations like > > > x+=.zzz > > > So I need to account for the fact that operators do not need to be > > surrounded by spaces. That's the hardest part I can think of off the > > top of my head. > > > Maybe I'll encounter an insurmountable problem and realize that the > > idea can't work in general. If so, then so be it. Certainly, no one on > > this thread has anticipated such a problem. Had someone pointed out an > > actual technical problem with the idea, I would have gladly thanked > > them. But I got a load of irrelevant crap instead, not to mention > > being addressed as "boy." > > > > If you're meeting so much resistance to your idea, why not scratch > > > your own damn itch and just do it? > > > > Or doesn't that afford you as many chances to insult others while > > > feeling smugly superior? > > > This coming from a guy who insulted my reading comprehension ability > > -- when he was the one who was wrong! > > Are you actually this stupid? I mean, you were entertaining while you > were mouthing of and insulting your betters, but now you're gonna > complain the second anyone insults you (and I mean, 'boy' - what an > insult!). Never mind that you're never gonna get off your ass to > write a PEP, which would be rejected on language design grounds anyway > (as demonstrated by alex23's link - the one you aren't > comprehending). The most irritating thing is that I like the idea of > being able to use '.x = 10' type notation (and have been for a long > time), but the person arguing for it is an insufferable buffoon who's > too dense to understand a cogent argument, never mind make one. So > great, thanks, the chances of this (or a VB 'with'-like 'using' > keyword) ever making it into the language get smaller every time you > fire up your keyboard. Nice work. > > Iain > > p.s. am looking forward to your post whining about the invalid reasons > your PEP got rejected, in the slim hope you actually write one. +1 POTW Thanks for the gentle prod! I'm on it -- well, soon anyway. I have to consciously avoid thinking about this post whenever I consume a beverage! From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 9 07:52:45 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 09 Jul 2008 13:52:45 +0200 Subject: a simple 'for' question In-Reply-To: References: <4874017D.2000401@umbc.edu> <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> <487437E6.8010609@umbc.edu> Message-ID: <4874a65e$0$11358$426a74cc@news.free.fr> Tim Cook a ?crit : > On Wed, 2008-07-09 at 00:00 -0400, Ben Keshet wrote: >> oops, my mistake, actually it didn't work... >> when I tried: >> for x in folders: >> print x # print the current folder >> filename='Folder/%s/myfile.txt' %x >> f=open(filename,'r') >> >> it says: IOError: [Errno 2] No such file or directory: >> 'Folder/1/myfile.txt' >> > > I believe it's because x is the position marker what you want instead is > the contents of folders at x; therefore folders[x] Nope. Python's for loops iterate over elements, not over indices. Here, the following code: folders= ['1A28','1A6W','56Y7'] for x in folders: print x filename='Folder/%s/myfile.txt' %x print filename yields: 1A28 Folder/1A28/myfile.txt 1A6W Folder/1A6W/myfile.txt 56Y7 Folder/56Y7/myfile.txt IOW: the problem is elsewhere. From larry.bates at websafe.com` Wed Jul 9 16:49:02 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 09 Jul 2008 15:49:02 -0500 Subject: Determining when a file has finished copying In-Reply-To: References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> Message-ID: writeson wrote: > Guys, > > Thanks for your replies, they are helpful. I should have included in > my initial question that I don't have as much control over the program > that writes (pgm-W) as I'd like. Otherwise, the write to a different > filename and then rename solution would work great. There's no way to > tell from the os.stat() methods to tell when the file is finished > being copied? I ran some test programs, one of which continously > copies big files from one directory to another, and another that > continously does a glob.glob("*.pdf") on those files and looks at the > st_atime and st_mtime parts of the return value of os.stat(filename). > From that experiment it looks like st_atime and st_mtime equal each > other until the file has finished being copied. Nothing in the > documentation about st_atime or st_mtime leads me to think this is > true, it's just my observations about the two test programs I've > described. > > Any thoughts? Thanks! > Doug I guess the problem is "What is the definition of 'finished copying'?". There is no explicit operating system command that says "I'm done copying to this file and I won't add anything on to the end of it". If I could not control the sending application, I would make an estimation of how long the longest file could possibly take to copy, double it and then only look at files where the st_ctime was at least that far in the past. What you suggest could work as well. -Larry From Samnsparky at gmail.com Tue Jul 15 13:20:49 2008 From: Samnsparky at gmail.com (Sparky) Date: Tue, 15 Jul 2008 10:20:49 -0700 (PDT) Subject: File Locking Forced? Newbie question. Message-ID: <216e2396-65f6-4281-b3c5-754ceb07f3eb@m36g2000hse.googlegroups.com> Hello! I am writing some software that will have many users accessing the same file resource at once for reading purposes only. I am programming on (Ubuntu) Linux and my question is in Windows, can I have it so that the same file can be open in read mode by more than one person or could Window's file locking system get in the way? Thanks, Sam From workitharder at gmail.com Mon Jul 14 00:12:21 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 13 Jul 2008 21:12:21 -0700 (PDT) Subject: socket.connect() hangs in SYN_SENT state. References: <804bccb2-42c7-42e9-8f50-7a780d3438fd@j22g2000hsf.googlegroups.com> Message-ID: On Jul 13, 6:31 pm, Miles wrote: > On Sun, Jul 13, 2008 at 8:35 PM, bukzor wrote: > > The problem only manifests about 1 in 20 runs. Below there's code for > > a client that shows the problem 100% of the time. > > > The two URL's that I seem to be "confused" about point to the same IP. > > Maybe this will make it clear: > > > PING bukzor.hopto.org (75.61.84.249) 56(84) bytes of data. > > 64 bytes from adsl-75-61-84-249.dsl.pltn13.sbcglobal.net > > (75.61.84.249): icmp_seq=1 ttl=255 time=1.68 ms > > For me, buzkor.hopto.org resolves to 69.65.19.125, which I hope > explains why I thought you were confused, and increases my own > suspicion that DNS settings are to blame. I let the script run for > about five minutes without it failing. > > Does your luck change if you use "localhost" or a numeric IP address > in the ServerProxy URL? > > -Miles It seems to work fairly perfectly If i use localhost or even my LAN IP address, but starts to fail if I go beyond that. You said you ran it for five minuts without error. Did it error out after that? If you can't reproduce it, that would indicate something else. From keshet1 at umbc.edu Tue Jul 1 19:16:30 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Tue, 01 Jul 2008 19:16:30 -0400 Subject: beginner's questions - manipulating text files Message-ID: <486ABACE.9050103@umbc.edu> Hi, I am a very beginner Python programmer with limited programming experience overall. I am trying to write a script that will search for the second and third appearance of the symbol '@' in a file, will read a random line between them, and write the line into a new file. So far I was only able to open the file using 'open', but I am not sure how to proceed. I tried to read it line by line using 'readline' but was not sure how to manipulate the text the way I need to. Could anyone please give me |a basic guidance as for what functions may be useful for my purpose? (e.g how to search for a string '@' in a text? how to identify its location? how to choose a random number in a defined range? how to read that line number from a text file? etc.)| || |Any help will be much appreciated (please remember that I am a super beginner).| || |Thanks.| || | | -------------- next part -------------- An HTML attachment was scrubbed... URL: From keith.hughitt at gmail.com Fri Jul 11 14:42:37 2008 From: keith.hughitt at gmail.com (Keith Hughitt) Date: Fri, 11 Jul 2008 11:42:37 -0700 (PDT) Subject: Converting from local -> UTC Message-ID: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> Hi, I am having a little trouble figuring out how to convert a python datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would like to create a UTC date so that when I send it to MySQL (which treats all dates at local dates by default), it will already have incorporated the proper UTC offset. I've tried looking through the docs http://python.active-venture.com/lib/datetime-datetime.html), but have not had any luck. Does anyone have any suggestions? Any help would be greatly appreciated. Thanks, Keith From vshankar0 at gmail.com Thu Jul 17 07:54:20 2008 From: vshankar0 at gmail.com (Venky Shankar) Date: Thu, 17 Jul 2008 17:24:20 +0530 Subject: Testing for connection to a website In-Reply-To: References: Message-ID: ping the universal DNS ? (4.2.2.2) -Venky On Wed, Jul 16, 2008 at 1:17 AM, Jordan wrote: > On Jul 15, 3:43 pm, Alexnb wrote: > > Okay, I already made this post, but it kinda got lost. So anyway I need > to > > figure out how to test if the user is able to connect to a specific > website. > > Last time I got pointed to the urllib2 page, but if I do urlopen() and > and > > am not connected, the program stops. So I don't know if that was what you > > guys wanted me to do, but I don't think so, you guys are smarter than > that. > > So, how can I test for connection to a website. > > -- > > View this message in context: > http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p... > > Sent from the Python - python-list mailing list archive at Nabble.com. > > Ping it? ~_^ > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.franzoni.blahblah at example.com.invalid Wed Jul 30 13:26:37 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Wed, 30 Jul 2008 17:26:37 GMT Subject: Syntax error in my script References: Message-ID: laredotornado was kind enough to say: [cut] Indentation counts in Python. You're probably doing something wrong with whitespace/tab/carriage return. -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From samwyse at gmail.com Mon Jul 14 16:45:21 2008 From: samwyse at gmail.com (samwyse) Date: Mon, 14 Jul 2008 13:45:21 -0700 (PDT) Subject: Problems Returning an HTTP 200 Ok Message References: <1cf880cc-2036-42dc-8217-d52a714c1710@a70g2000hsh.googlegroups.com> <9bc65e72-be16-4f73-9dfb-6ddeaae34c21@m73g2000hsh.googlegroups.com> <8596af5b-fd0a-413e-8051-62d650e9a153@8g2000hse.googlegroups.com> Message-ID: On Jul 10, 4:10?pm, Guy Davidson wrote: > I try to send the following message, using the socket.send() command: > > 'HTTP/1.1 200 OK\r\nDate: Thu, 10 July 2008 14:07:50 GMT\r\nServer: > Apache/2.2.8 (Fedora)\r\nX-Powered-By: PHP/5.2.4\r\nContent-Length: 4\r > \nConnection: close\r\nContent-Type: text/html; charset=UTF-8\r\n\r > \n[0]\n' > > However, when I snoop on the packets in wireshark, here's what I see: > > HTTP/1.1 200 Ok: > > HTTP/1.1 200 OK > Date: Wed, 09 July 2008 14:55:50 GMT > Server: Apache/2.2.8 (Fedora) > X-Powered-By: > > Continuation or non-HTTP traffic: > > PHP/5.2.4 > Content-Length: 4 > Connection: close > Content-Type: text/html; charset=UTF-8 > > [0] > > It splits into two packages, which the meter can't read, and the > communication breaks down there. OK, it looks like a single TCP segment is being sent by you (which is consistent with only one socket.send() command being needed), but something along the way to the meter is using an MTU (Maximum Transmission Unit) of about 100 bytes, producing two IP datagrams. How many hops are there between the PC and the meter? Are you sniffing on the same subnet as the PC, the meter, or somewhere in between? MTU is normally set to about 1500 (and MSS is generally MTU-40), but you can generally change these values. You should be able to set the do-not-fragment flag on your IP packets, but that may cause them to get dropped instead of sent. You could also try setting a smaller ICP MSS (Maximum Segment Size), which the meter might be able to assemble, even if it can't handle fragmented IP datagrams. Try http://www.cisco.com/en/US/tech/tk870/tk877/tk880/technologies_tech_note09186a008011a218.shtml#prob_desc for more help. You really need to get a networking guru involved if you want to go down this path. I used to be one, but that was years ago. Or, you can take Gabriel Genellina's advice and try coding smaller responses. From frankrentef at yahoo.com Thu Jul 24 11:13:26 2008 From: frankrentef at yahoo.com (frankrentef) Date: Thu, 24 Jul 2008 08:13:26 -0700 (PDT) Subject: Python / PAMIE References: Message-ID: <9e077ec9-9a07-4a3a-b5dc-bfd593162350@8g2000hse.googlegroups.com> On Jul 24, 10:07?am, Tim Golden wrote: > frankrentef wrote: > > Can someone help with a PAMIE issue? ?I'm new to Python / PAMIE and > > they seem like great tools but to be honest I'm finding that no > > responses to questions can be found (Experts Exchange, etc.) ?I'm > > hoping this will be the place. > > > I tried to duplicate the authors "ie.writeScript" function shown at > > >http://showmedo.com/videos/video?name=pythonMarchettiPamie3&fromSerie... > > I'd rather you posted the code you've tried. > I'm not too keen on viewing a video just to get > hold of a piece of code, and in any case that > would only show me what the author's done. > > We need to see what you've done, and what the > traceback was. Would you mind posting some code, > please? > > Thanks > > TJG THNX for your response. Based on the authors code it's very simple. from cPAMIE import PAMIE ie=PAMIE () #ie.navigate ("google.com") #ie.linkClick #ie.textBoxSet #ie.writeScript ie.navigate ('https://login.yahoo.com/config/mail?.intl=us') #ie.scriptWrite () ie.scriptWrite() Below is the error I get... File "C:\Python24\lib\site-packages\cPAMIE.py", line 1837, in scriptWrite nameProp = getattr(x,"nameProp") File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 500, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: .nameProp From sunp1028 at gmail.com Wed Jul 16 08:28:54 2008 From: sunp1028 at gmail.com (patrol) Date: Wed, 16 Jul 2008 05:28:54 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> Message-ID: On 7?16?, ??3?29?, Tim Golden wrote: > patrol wrote: > >>http://timgolden.me.uk/wmi-project/wmi.py > > > It cannot work either. > > Oh well. It was only a quick fix! I'll try > to get some kind of non-ASCII edition of Windows > to test against. As I understand it, the situation > is that some WMI exception (ie coming from the > underlying WMI/COM subsystem) results in an error > message which contains non-ASCII characters. > > Just so I'm not chasing red herrings, could you > paste the output from the following code, please? > > > import wmi # use the version linked above > > c = wmi.WMI ("non-existent computer") > > # > # Should give a traceback here for the DCOM > # error, not a UnicodeDecodeError. > # > > > Thanks > > TJG The errors are in the following: Traceback (most recent call last): File "D:\My Documents\code\python\wmi\test.py", line 5, in c = wmi.WMI ("non-existent computer") File "C:\Python25\lib\wmi.py", line 1199, in connect handle_com_error (error_info) File "C:\Python25\lib\wmi.py", line 184, in handle_com_error exception_string = [u"%s - %s" % (hex (hresult_code), hresult_name)] UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 4: ordinal not in range(128) Patrol From tjreedy at udel.edu Tue Jul 8 15:25:47 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 08 Jul 2008 15:25:47 -0400 Subject: "in"consistency? In-Reply-To: <871c6735-f2d2-4cd0-811d-0cd774d55bdd@m45g2000hsb.googlegroups.com> References: <871c6735-f2d2-4cd0-811d-0cd774d55bdd@m45g2000hsb.googlegroups.com> Message-ID: castironpi wrote: > Strings are not containers. Library Reference/Built-in Types/Sequence Types says "Strings contain Unicode characters." Perhaps you have a different notion of contain/container. I prefer 'collection' to 'container' since 'container' tends to imply an exclusiveness that is not true. Byte/character sequences *are* different from tuples, lists, sets, dicts, etc, in the following sense: members of the latter collection classes must exist first before being added to the collection (non-exclusively). Members of the former do not. (In CPython, at least, they do not). So I consider them to (reiterable) *virtual* sequence collections that can produce subsequences on demand, So I partially agree with you in that byte/char sequences are a different sub-category. > Another container type: > > Python 3.0b1 on win32 >>>> {0} in {0,1} > False And similarly, (0,) not in (0,1), [0] not in [0,1], {0:None} not in {0:None,1:None). These are all general manifest collection types that can contain any Python object, and which could contain a sub-collection even if they do not. Terry Jan Reedy From tjreedy at udel.edu Sun Jul 27 21:32:06 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 21:32:06 -0400 Subject: Where is the correct round() method? In-Reply-To: <488D0BC0.3080701@islandtraining.com> References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> <488D0BC0.3080701@islandtraining.com> Message-ID: Gary Herron wrote: > josh logan wrote: >> I need a round function that _always_ rounds to the higher integer if >> the argument is equidistant between two integers. In Python 3.0, this >> is not the advertised behavior of the built-in function round() as >> seen below: >>>>> round(2.5) >>>>> >> 2 > Huh? > >>> round(2.5) > 3.0 As the OP said, PY 3.0, where statisticians' unbiased round to even was explicitly adopted. (I think before it was maybe left to the C library?) >> I would think this is a common need, If you need any particular rounding for legal/finance-rule reasons, you probably need the decimal module, which has several rounding modes and other features catering to money calculation rules. For general data analysis with floats, round to even is better. tjr From ethan at stoneleaf.us Tue Jul 15 14:11:15 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 15 Jul 2008 10:11:15 -0800 Subject: MySQL Insert In-Reply-To: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> References: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> Message-ID: <487CE843.2080704@stoneleaf.us> maestroQC wrote: > Hi, > > Its one of those days. I cannot solve this. Any help would be greatly > appreciated! > When I execute this: > > class Db(object): > def insertAccount(self, date, accountNumber, description, > openingBalance): > dec = decimal.Decimal(openingBalance) > db = MySQLdb.connect(host="localhost", user="dumb", > passwd="dumber", db="rdc") > cursor = db.cursor() > cursor.execute("INSERT INTO es_accounts (dateCreated, > accountNumber, description, openingBalance) VALUES (%s, %s, %s, %d)", > (date, accountNumber, description, dec)) > > I get this error: > Traceback (most recent call last): > File "main.py", line 59, in > main() > File "main.py", line 40, in main > dbObj.insertAccount(dateTo, item[0], item[1], item[8]) > File "C:\projects\workspace\INYR_ES_0.1\src\db.py", line 19, in > insertAccount > cursor.execute("INSERT INTO es_accounts (dateCreated, > accountNumber, description, openingBalance) VALUES (%s, %s, %s > , %d)", (date, accountNumber, description, dec)) > File "c:\python25\lib\site-packages\MySQLdb\cursors.py", line 151, > in execute > query = query % db.literal(args) > TypeError: int argument required > > My table is defined as: > CREATE TABLE es_accounts ( > id int(6) not null auto_increment, > dateCreated date DEFAULT '0000-00-00', > accountNumber int(6) not null, > description varchar(255) not null, > openingBalance decimal(15,8) NOT NULL DEFAULT 0.00000000, > primary key (id) > ); > > TIA The problem is your %d in Values, and then using a Decimal type to feed it. Depending on the type of your openingBalance field, you may want to change the %d to %s, or change dec to int(dec), or change the %d to %f and change dec to float(dec). My experience with the Decimal type is limited, so there may be other options as well. ~Ethan From deets at nospam.web.de Wed Jul 16 03:05:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Jul 2008 09:05:58 +0200 Subject: Redirecting stdout to another script In-Reply-To: References: Message-ID: <6e5kusF5c5a4U2@mid.uni-berlin.de> Richard Sim?es schrieb: > Hopefully, this explanation will sufficiently clear despite the lack > of code. > > I wrote a python script that takes data via stdin, does stuff with the > data, and outputs the result to stdout. A friend wrote a perl script > that opens a pipe to my script, feeds it data, and then accepts the > result. The problem here is that the python script's outputting the > result to stdout via print statements isn't doing what we expected: my > friend's perl script isn't getting the result back via the pipe. > > Is there is simple solution for this problem? Whose script needs to be > modified? That of your friend, if he is the one invoking you. Because the invoking script is the one responsible for connecting the pipes properly. Diez From larry.bates at websafe.com` Thu Jul 10 11:47:38 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 10 Jul 2008 10:47:38 -0500 Subject: python scalability In-Reply-To: References: Message-ID: Tim Mitchell wrote: > Hi All, > > I work on a desktop application that has been developed using python and > GTK (see www.leapfrog3d.com). We have around 150k lines of python code > (and 200k+ lines of C). We also have a new project manager with a C# > background who has deep concerns about the scalability of python as our > code base continues to grow and we are looking at introducing more > products. I am looking for examples of other people like us (who write > desktop apps in python) with code bases of a similar size who I can > point to (and even better talk to) to help convince him that python is > scalable to 300+ lines of code and beyond. I have looked at the python > success stories page and haven't come up with anyone quite like us. One > of my project managers questions is: "Are we the only company in the > world with this kind and size of project?" > I want to say no, but am having trouble convincing myself, let alone him. > > If you are involved in this kind of thing please get in touch with me. > > Thanks, > Tim It is not clear what "scalability" means to a desktop application? When maximum calculation speeds are required, you can drop into C libraries from Python with ease. If this is about making use of multiple cores on a machine this link (http://wiki.python.org/moin/ParallelProcessing) covers most of the solutions that can be implementing in Python. Another poster has suggested that you would need 1500K lines of C to replace 300K lines of Python (and he may be being generous to C). Projects are about more than raw speed: maintainability, speed of adding features, etc. Python wins those races in most situations. I'm sure that hand coded assembler would run fastest of all, but little application software is written that way these days. -Larry From tn.pablo at gmail.com Tue Jul 22 17:02:57 2008 From: tn.pablo at gmail.com (ptn) Date: Tue, 22 Jul 2008 14:02:57 -0700 (PDT) Subject: Function editing with Vim throws IndentError Message-ID: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Hi everybody, I have a weird problem. Say I have a .py file with some functions in it, like this: # (...) def foo(): print("bar") When I open it and add a line to one of the functions, # (...) def foo(): troz = "bar" print(troz) I get the following traceback from the interpreter: Traceback (most recent call last): File "SOMEWHERE/example.py", line ?? troz = "bar" ^ IndentationError: unindent does not match any outer indentation level And so I'm forced to rewrite the function entirely just to add the new line. I thought that my problem was the w option from formatoptions, so I changed my .vimrc file to this: augroup filetype autocmd BufNewFile,BufRead *.txt set filetype=human augroup END autocmd FileType human setlocal formatoptions+=ta2w autocmd FileType lisp,scheme,python,c,java,vim setlocal formatoptions-=ta2w But the problem didn't go away. I don't think this has anything to do with the tabs and spaces, because I have them set up like this: set tabstop=4 shiftwidth=4 expandtab which is the standard way to handle them. The scripts I load are: qbuf, TagList, indent/python.vim and a reduced version of the standard python.vim Could someone provide some pointers? Thanks, Pablo Torres N. From Ming.YIN at murex.com Fri Jul 11 06:31:35 2008 From: Ming.YIN at murex.com (YIN Ming) Date: Fri, 11 Jul 2008 18:31:35 +0800 Subject: recommended gcc versions for python2.5 compilation on Solarissparc/x86, AIX, Linux In-Reply-To: <20080711095456.GW68329@nexus.in-nomine.org> References: <9347F3EEF61FC542A7D9211A42CD7E6387E071@dolphin.sg.murex.com> <20080711095456.GW68329@nexus.in-nomine.org> Message-ID: <200807111031.m6BAVRGh012217@mail.m> Dear Jeroen, Thanks so much for your help. :) Best regards, Yin Ming -----Original Message----- From: Jeroen Ruigrok van der Werven [mailto:asmodai at in-nomine.org] Sent: Friday, July 11, 2008 5:55 PM To: YIN Ming Cc: python-list at python.org; LEGRAND Mathieu Subject: Re: recommended gcc versions for python2.5 compilation on Solarissparc/x86, AIX, Linux -On [20080711 06:18], YIN Ming (Ming.YIN at murex.com) wrote: >2. use new version of gcc (rather than odd version) See http://www.in-nomine.org/2008/04/11/python-26a2-execution-times-with-various-compilers/ that I wrote a while ago. Basically for Python GCC 3.4.6 outperformed the newer GCCs. So do not automatically assume that newer is better. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B The weak can never forgive. Forgiveness is the attribute of the strong... -------------------------------------------------------- This e-mail contains information for the intended recipient only. It may contain proprietary material or confidential information. If you are not the intended recipient you are not authorised to distribute, copy or use this e-mail or any attachment to it. Murex cannot guarantee that it is virus free and accepts no responsibility for any loss or damage arising from its use. If you have received this e-mail in error please notify immediately the sender and delete the original email received, any attachments and all copies from your system. From code at pizzashack.org Sun Jul 27 15:59:26 2008 From: code at pizzashack.org (Derek Martin) Date: Sun, 27 Jul 2008 15:59:26 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <009c2b11$0$20302$c3e8da3@news.astraweb.com> References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> Message-ID: <20080727195926.GF7373@dragontoe.org> On Sun, Jul 27, 2008 at 08:19:17AM +0000, Steven D'Aprano wrote: > > You take the name down to a single letter. As I suggested in an earlier > > post on this thread, why not take it down to zero letters? > > The question isn't "why not", but "why". The status quo works well as it > is, even if it isn't perfect. Prove that implicit self is a good idea -- > or at least prove that it is an idea worth considering. Come on, this sounds like a schoolyard argument. This comes down to a matter of style, and as such, is impossible to prove. It's largely a question of individual preference. That said, the argument in favor is rather simple: 1. This is an extremely common idiom in Python 2. It is completely unnecessary, and the language does not suffer for making it implicit 3. Making it implicit reduces typing, reduces opportunities for mistakes, and arguably increases consistency. As for the latter part of #3, self (or some other variable) is required in the parameter list of object methods, however when the method is *called*, it is omitted. It is implied, supplied by Python. Thus when an object method is called, it must be called with one fewer arguments than those which are defined. This can be confusing, especially to new programmers. It can also be argued that it makes the code less ugly, though again, that's a matter of preference. > It's not enough to show that a change "isn't bad" -- you have to show > that it is actively good. But he did... he pointed out that *it saves work*, without actually being bad. Benefit, without drawback. Sounds good to me! > "Don't need to look at the method signature" is not an argument in favour > of implicit self. Yes, actually, it is. If there is a well-defined feature of Python which provides access to the object within itself, then the opportunities for mistakes when someone decides to use something else are lessened. > You don't need to look at the method signature when you're using an > explicit self either. That isn't necessarily true. If you're using someone else's code, and they didn't use "self" -- or worse yet, if they chose this variable's name randomly throughout their classes -- then you may well need to look back to see what was used. It's bad programming, but the world is full of bad programmers, and we don't always have the choice not to use their code. Isn't one of Python's goals to minimize opportunities for bad programming? Providing a keyword equivalent to self and removing the need to name it in object methods is one way to do that. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From iainking at gmail.com Sat Jul 19 04:52:56 2008 From: iainking at gmail.com (Iain King) Date: Sat, 19 Jul 2008 01:52:56 -0700 (PDT) Subject: Best Python packages? References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> <17861f55-8ad1-4703-ad22-838675f2afc4@w1g2000prk.googlegroups.com> <48819E2D.10903@behnel.de> Message-ID: On Jul 19, 8:56 am, Stefan Behnel wrote: > Iain King wrote: > > Well, if you're looking for a list of excellent 3rd party Python > > libraries, then I can give you the ones I like and use a lot: > [...] > > BeautifulSoup : for real-world (i.e. not-at-all-recommendation- > > compliant) HTML processing > > You forgot lxml.html, which is much faster, more memory friendly and more > feature-rich than BS. > > Stefan Never heard of it :) Iain From mwilson at the-wire.com Tue Jul 1 08:47:18 2008 From: mwilson at the-wire.com (Mel) Date: Tue, 01 Jul 2008 08:47:18 -0400 Subject: Implementing an 8 bit fixed point register References: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> Message-ID: nickooooola wrote: > Hello to all > I'm about to write a simulator for a microcontroller in python > (why python? because I love it!!!) [...] > The registry of this processor are all 8 bit long (and 10 bit for some > other strange register) > and I need to simulate the fixed point behaviour of the register, > and to access the single bit. > > f.x. (this is a pseudo python session, only for understanding) > >>>> reg1 = fixed_int(8) >>>> reg2 = fixed_int(10) >>>> reg1[0].set() > or >>>> reg1[0] = 1 # or True? how to rapresent a binary bit >>>> reg1[0] > 1 >>>> reg1[1] > 0 >>>> reg1[9] > >>>> reg2 = 0x7FE # in binary 11111111110 , or 11 bit long >>>> reg2 > 0x7FE > #or 1111111110, the memorization truncate the upper bits ( or perhaps > generate an exception?) >>>> reg2 += 0x02 #the result is 10000000000, again not contained in 10 bit >>>> reg2 > 0x00 > # truncated again >>>> myprocessor.flags['z'] > 1 > # or True? Z flag indicated an overflow in arithmetic operations > > Is possibile to do so in python? I did this for a PIC, and generally just used brute force, e.g. temp = reg2 + 0x02 reg2 = temp & 0xFF if temp & 0x100: flags |= CARRY_MASK else: flags &= ~CARRY_MASK if temp & 0xFF: flags &= ~ZERO_MASK else: flags |= ZERO_MASK Since it was a PIC, and there were only a half-dozen arithmetic/logical operations, the code stayed in this form. With something bigger, it would have been attractive to wrap these operations up in a class, as you suggest.. (just a sketch) .. class fixed_register (object): def __init__ (self, size, val=0): self.mask = ~(-1 << size) self.ovfmask = 1 << size self.val = val & self.mask with appropriate __add__, __sub__, etc. Perhaps __getitem__, __setitem__ to manipulate bits. Good Luck, Mel. From musiccomposition at gmail.com Fri Jul 11 08:28:56 2008 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 11 Jul 2008 05:28:56 -0700 (PDT) Subject: using Python's AST generator for other languages References: <6d31532b-9946-42a3-a20b-56c403a388b2@l42g2000hsc.googlegroups.com> Message-ID: On Jul 11, 12:27 am, eliben wrote: > > > 2) What is the meaning of the comment in astgen.py ? Are the Python > > > maintainers unhappy with the design of the AST ?3 > > > Node, I think, is talking about a node in the parse tree. (AST is > > generated from another parse tree.) See PEP 339 for details. > > > > Thanks, PEP 339 clarified a lot to me. I wonder, though, at the need > for two Python compilation frameworks in the same code base. While > CPython uses the flow described in PEP 339 (parsing to an AST > generated from ASDL), the compiler module of the standard library > takes a different approach, with a custom AST description syntax in > ast.txt > Why aren't the two methods unified. I.e. can't the compiler.ast module > be also generated from ASDL, and provide a more unified interface to > the real thing ? You are correct on all points and this is one of the main reasons that the compiler package is going away in 3.0. > > Eli From jmcmonagle at velseis.com.au Tue Jul 8 21:02:08 2008 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Wed, 09 Jul 2008 11:02:08 +1000 Subject: a simple 'for' question In-Reply-To: <4874017D.2000401@umbc.edu> References: <4874017D.2000401@umbc.edu> Message-ID: <48740E10.7020400@velseis.com.au> Ben Keshet wrote: > Hi fans, > > I want to use a 'for' iteration to manipulate files in a set of folders, > something like: > > folders= ['1A28','1A6W','56Y7'] > for x in folders: > print x # print the current folder > f = open('my/path/way/x/my_file.txt', 'r') > ... > Use os.path.join import os folders = ['1A2B', '1A6W', '56Y7'] for x in folders: f = open(os.path.join('my/path/way', x, 'my_file.txt'), 'r') From fuzzyman at gmail.com Tue Jul 29 05:09:07 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Tue, 29 Jul 2008 02:09:07 -0700 (PDT) Subject: ironpython, exception in mscorlib when reading .py file from network share References: <6dfb578a-17ff-434d-a071-646ed3ef2b03@z72g2000hsb.googlegroups.com> Message-ID: <15144d50-319d-48ce-bd16-0ead4226dd08@f63g2000hsf.googlegroups.com> On Jul 29, 9:34?am, mindmind wrote: > Hello, > > I have a ironpython 1.1.1.0 host in my c# app, and When doing a > ? engine.ExecuteFile(file); > i often get the error below, when "file" is on a network share : > (winXp client , windows ??? server) > > 21-07-2008 12:47:28 : Traceback (most recent call last): > 21-07-2008 12:47:28 : ? File c:\sandbox\xxx.cs > 21-07-2008 12:47:28 : ? File c:\sandboxx\yyy.cs > 21-07-2008 12:47:28 : ? File mscorlib, line unknown, in ReadAllBytes > 21-07-2008 12:47:28 : ? File mscorlib, line unknown, in Read > 21-07-2008 12:47:28 : ? File mscorlib, line unknown, in ReadCore > 21-07-2008 12:47:28 : ? File mscorlib, line unknown, in WinIOError > 21-07-2008 12:47:28 : IOError: The specified network name is no longer > available. > 21-07-2008 12:47:28 : > > Exception is caught before first line in python is executed. > > Other parts of the program is also accessing the network (for copying > files etc), and never fails, > so networks connection is "ok" (maybe not perfect, but at least > present.) > > Is the ExecuteFile reading the contents of the .py file differently > than a "copy" primitive is (other timeout/retry values) ? > > Does anyone have any ideas of how to setup windows , ironpython host > or .NET lib differently, to stop it doing this ? Fallback solution is > to copy file locally before execution, but I would rather fix this. > > thx I don't know the answer - I do know that .NET permissions issues and accessing network resources are a bit 'weird'. You're likely to get an answer if you ask on the IronPython mailing list. Michael Foord -- http://www.ironpythoninaction.com/ From mcmurtri at dslextreme.com Sun Jul 13 03:22:52 2008 From: mcmurtri at dslextreme.com (Kevin McMurtrie) Date: Sun, 13 Jul 2008 00:22:52 -0700 Subject: spam <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> Message-ID: In article , Lew wrote: > WDC wrote: > > BTW I reported it, yo should too. > > To whom did you report it, so that we may also report it there? Google does not accept spam complaints. Go ahead, try it. That's why they've been the #1 Usenet spamming tool for years now. What you're seeing is the spam slowly expanding into the software development groups. uk.railway is probably a random group added to confuse spam filters. Some groups, like rec.photo.digital, have been getting hundreds of Google spams a day for about a year. Ask your news service for a Google UDP (Usenet Death Penalty) or configure your reader to drop everything with "googlegroups.com" in the Message-ID. http://improve-usenet.org/ -- I will not see your reply if you use Google. From anonymous at anonymitaet-im-inter.net Mon Jul 14 00:08:54 2008 From: anonymous at anonymitaet-im-inter.net (Dave U. Random) Date: Mon, 14 Jul 2008 06:08:54 +0200 (CEST) Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) Message-ID: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> http://snipr.com/PracticalDjango From sjmachin at lexicon.net Wed Jul 2 18:29:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 2 Jul 2008 15:29:28 -0700 (PDT) Subject: Sorting two dimentional array by column? References: Message-ID: On Jul 3, 7:35 am, Tobiah wrote: > > Imagine an excel spreadsheet. I can choose > > a column and sort the records based on the items > > in that column. I would like to do the same > > thing with a large two dimensional array. > > What would be the fastest way (in computation time) > > to accomplish this? > > Now that I think about the problem more, I really want > to sort an array of dictionaries according one of the > keys of each. Could I use: > > array.sort(key = something) > > Where something looks at the proper item in the > current row? I can't quite visualize how to pull > the item out of the dictionary. Manual sez: """key specifies a function of one argument that is used to extract a comparison key from each list element: "key=str.lower" """ Assuming that "sort an array of dictionaries according one of the keys of each" means "sort an array of dictionaries according to the value stored for one of the keys of each". If the dict key were a constant, you could do: array.sort(key=lambda adict: adict['the_constant_key']) However you want the current row, and sort wants a 1-arg key function ... to stick with the key= caper you'll need to curry the extra arg. So (Python 2.5 onwards): # do this once import functools def dict_extract(adict, akey): return adict[akey] # do this each time you want to sort current_row_key = whatever() sort_key_func = functools.partial(dict_extract, akey=current_row_key) array.sort(key=sort_key_func) Alternatively, use the decorate-sort-undecorate procedure: temp = [(d[current_row_key], d) for d in array] temp.sort() array[:] = [tup[1] for tup in temp] HTH, John From bruno.desthuilliers at gmail.com Wed Jul 9 16:44:31 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 9 Jul 2008 13:44:31 -0700 (PDT) Subject: You, spare time and SyntaxError References: Message-ID: On 9 juil, 16:56, cokofree... at gmail.com wrote: > def ine(you): > yourself = "what?" > go = list("something"), list("anything") > be = "something" > please = be, yourself > yourself = "great" > for good in yourself: > if you is good: > good in you > please.add(more, good) > else: > def inition(lacks, clarity): > if clarity not in you: > please.remove(everything and go) > for bad in yourself: > list(bad) if bad else (ignore, yourself) > try: > (to, escape, your, fate, but) > except (Exception), son: > if bad in (you, son): > (you is bad, son), so > finally: > if bad in you: > lie, cheat, steal, be, bad > else: > print you, "is", yourself > you is good and yourself is not bad > please, go > > ine("Everyone") just... great !-) From alif016 at gmail.com Mon Jul 7 23:27:02 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Mon, 07 Jul 2008 22:27:02 -0500 Subject: Python Agile Software Development Tools Screencasts In-Reply-To: <8763rhw0vv.fsf@benfinney.id.au> References: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> <87lk0dwbys.fsf@benfinney.id.au> <87hcb1w6gl.fsf@benfinney.id.au> <87abgtw52g.fsf@benfinney.id.au> <8763rhw0vv.fsf@benfinney.id.au> Message-ID: <4872DE86.4030508@gmail.com> Ben Finney wrote: > Andrew Freeman writes: > >> http://videos1.showmedo.com/ShowMeDos/2910000.flv >> > > Which leads one to wonder why they don't just present that URL for > download instead of behind a "log in" gate. And how long that will be > possible before they break it ? presumably the site admins put that > barrier there for a reason. > It appears that the url would be difficult to change; it appears to be mapped to a database: http://showmedo.com/videos/video?name=2910000&fromSeriesID=291 notice the "name" is the same in this URL and the flv. -- Andrew From mail at timgolden.me.uk Fri Jul 11 11:04:35 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 11 Jul 2008 16:04:35 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) In-Reply-To: References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: <48777683.2080804@timgolden.me.uk> Bill Davy wrote: > Traceback (most recent call last): > File "H:/Personal/OutlookIF1/t2.py", line 18, in > outlook = win32com.client.gencache.EnsureDispatch > ("Outlook.Application") > File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line > 536, in EnsureDispatch > mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], > bForDemand=bForDemand) > File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line > 393, in EnsureModule > module = GetModuleForTypelib(typelibCLSID, lcid, major, minor) > File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line > 262, in GetModuleForTypelib > AddModuleToCache(typelibCLSID, lcid, major, minor) > File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line > 554, in AddModuleToCache > dict = mod.CLSIDToClassMap > AttributeError: 'module' object has no attribute 'CLSIDToClassMap' Just in case, could you delete the contents of your gen_py directory (probably in %TEMP%\gen_py) TJG From siona at chiark.greenend.org.uk Tue Jul 29 12:26:31 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 29 Jul 2008 17:26:31 +0100 (BST) Subject: Continuous integration for Python projects References: <6f8pelFafh42U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >Hussein B wrote: >> Please correct my if I'm wrong but it seems to me that the major >> continuous integration servers (Hudson, CruiseControl, TeamCity ..) >> don't support Python based application. >> It seems they mainly support Java, .NET and Ruby. >> Can I use one of the previous listed servers for Python project? >Hudson can, and AFAIK CC as well - they only invoke shell-scripts (at least >hudson does, and CC you can convince doing that using ANT) You can definitely set up CruiseControl to handle Python, but don't ask me for details as it was a couple of years and a change of job ago. I seem to remember it being easier when CC was driving make, but we had makefiles in any case for building the extension modules needed -- writing a makefile from scratch might be a bit much. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From dp_pearce at hotmail.com Tue Jul 15 11:24:55 2008 From: dp_pearce at hotmail.com (dp_pearce) Date: Tue, 15 Jul 2008 08:24:55 -0700 (PDT) Subject: Zipping files Message-ID: Hi all, I have come across an error while using zipfile and I can't seem to find somewhere that explains the problem. My script needs to be able to take text files from one drive and add them to zip files on another drive. The following seems to work just fine. import zipfile # write test file in working directory directory folder = "J:/" filename = "testing.txt" fullpath = folder+filename fout = open(fullpath, 'wt') fout.write(str1) fout.close() # Add text file to zip file on same drive zFolder = "J:/" zFilename = "testing.zip" zFullpath = zFolder+zFilename zout = zipfile.ZipFile(zFullpath, "w") zout.write(fullpath) zout.close() print fullpath, "successfully added to", zFullpath However, if I change the drive letters to anything other than the drive from which the Python script is saved (e.g. run script from J: but zip to C:), I get the following warning: Traceback (most recent call last): File "J:/test.py", line 18, in zout = zipfile.ZipFile(zFullpath, "w") File "C:\Python25\lib\zipfile.py", line 339, in __init__ self.fp = open(file, modeDict[mode]) IOError: [Errno 13] Permission denied: 'C:/testing.zip' Can anyopne shed some light on what I am missing here? If it has any relevance to the permissions part of the error, I am currently using Windows machines. Thanks in advance for your time. Dan From jadamwilson2 at gmail.com Tue Jul 22 00:36:38 2008 From: jadamwilson2 at gmail.com (jadamwil) Date: Mon, 21 Jul 2008 21:36:38 -0700 (PDT) Subject: fromfile error on windows, not mac Message-ID: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> Hello, I am using the numpy fromfile function to read binary data from a file on disk. The problem is that the program runs fine on a Mac, but gives an error or warning on windows when trying to read the data. I use it like this: Signal = zeros((N, 16), dtype=float32) for sample in range(0, N): # this function gets the next position in the file to seek to s = getFilePos(sample) # go to the correct location in the file; this IS checked to make sure it is within the file mFile.seek(s) # read the 16 float32 values from the file D = fromfile(mFile, dtype=numpy.float32, 16) # save D in Signal Signal[sample, :] = D This will fail when sample is ~4. If I change the range to (5,N), skipping the "bad" file location, it will run fine for a few samples, and then give another error. The message it gives is: "16 items requested but only 7 read" So D is a 7x1 vector, and the program dies when it tries to assign D to the slice of Signal ("ValueError: shape mismatch: objects cannot be broadcast to a single shape"). On windows, the Python version is 2.5.2, and the most recent numpy and scipy are being used as well. I tried using Enthought, but it gave this error as well, in addition to a c runtime error whenever I imported scipy (which is another post topic...). Any ideas on what might be causing this? Is there a way to debug the fromfile function? And, remember, this works perfectly on a Mac. Would compiling everything (python, scipy, numpy) potentially solve this? Thanks! From lanny at freshells.ch Thu Jul 24 11:56:44 2008 From: lanny at freshells.ch (Lanny) Date: Thu, 24 Jul 2008 08:56:44 -0700 Subject: Raw Strings (I Think) References: Message-ID: > my guess is that the real problem is that you get back filenames with > spaces in them, which gets treated as multiple arguments by os.system. > > using os.startfile will fix this: > > >>> import glob, os, random > >>> file = random.choice(glob.glob("\\music\\*.mp3")) > >>> file > '\\music\\Madrugada - Grit - 05 - Seven Seconds.mp3' > >>> print file > \music\Madrugada - Grit - 05 - Seven Seconds.mp3 > >>> os.system(file) > '\music\Madrugada' is not recognized as an internal or external command, > operable program or batch file. > 1 > >>> os.startfile(file) > ... music starts playing ... > > Thanks I just switched the startfile for system and it worked like a charm Thanks -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- From keshet1 at umbc.edu Thu Jul 3 11:02:20 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Thu, 03 Jul 2008 11:02:20 -0400 Subject: Write a file - beginner's question Message-ID: <486CE9FC.3090204@umbc.edu> I have a probably simple beginner's question - I have a script that I am currently able to print its output. instead, i want to write it into a file - I tried different versions of write() but might have gotten the syntax wrong. the variable I want to write is a line from a file I am reading: "... f = open('receptor.mol2', 'r') line = f.readline()[:-1] while '@ATOM' not in line: line = f.readline()[:-1] #print line print random_mol2 ..." e.g. I want to write to a file all the lines in 'receptor.mol2' up to the string "@ATOM" (one after the other). Can anyone please advice? On a related note - how do I read and write to a file that is not in the same directory? e.g how do I provide a pathway to an open command? Please remember that I am a very beginner in Python and programming - Thank you. From jaganadhg at gmail.com Thu Jul 24 01:57:51 2008 From: jaganadhg at gmail.com (=?UTF-8?B?4LSc4LSX4LSo4LWN4LSo4LS+4LSl4LWN?=) Date: Wed, 23 Jul 2008 22:57:51 -0700 (PDT) Subject: Doubt References: Message-ID: On Jul 24, 1:13 am, Fredrik Lundh wrote: > ???????? wrote: > > I am a Perl programmer new to Python. I have a small doubt. > > I suspect you mean "question", not "doubt". It's not quite the same thing. > > > How to convert the perl notation > > $a = ""; expression in Python ? > Thank you for all to giving suggestions . With regards Jaganadh G > > How to represent the loop > > for ($a = $b; $a<=$c;$a++){ > > } in Python > > Start here: > > http://www.lucasmanual.com/mywiki/PerlPythonPhrasebook > > and then read either of these (preferably both): > > http://www.swaroopch.com/byteofpython/ > http://docs.python.org/tut/ > > From ojeeves at gmail.com Mon Jul 14 11:37:54 2008 From: ojeeves at gmail.com (oj) Date: Mon, 14 Jul 2008 08:37:54 -0700 (PDT) Subject: Do we have perl's Data::Dumper equivalent in Python?? References: Message-ID: On Jul 14, 11:41?am, srinivasan srinivas wrote: > Thanks, > Srini > > ? ? ? Bollywood, fun, friendship, sports and more. You name it, we have it onhttp://in.promos.yahoo.com/groups/bestofyahoo/ You might have more luck asking for help if you explained what Perl's Data::Dumper actually does, instead of expecting people to either just know, or to go and look it up. In particular, what functionality of Data::Dumper is it you are looking for? For a user friendly representation of a python data structure, look at pprint: http://docs.python.org/lib/module-pprint.html For a string representing a data structure that can be eval'd to get the structure back again, look at the built-in repr() -Oli From rowen at cesmail.net Tue Jul 29 15:28:12 2008 From: rowen at cesmail.net (Russell E. Owen) Date: Tue, 29 Jul 2008 12:28:12 -0700 Subject: like py2exe, but on a mac References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> Message-ID: In article , Tommy Nordgren wrote: > On 28 jul 2008, at 03.59, William McBrine wrote: > > > On Sun, 13 Jul 2008 00:58:59 +0200, Python.Arno wrote: > > > >> http://undefined.org/python/py2app.html > > > > py2app bundles Python itself into the app, right? I wonder, is there > > no > > way to create an app bundle that relies on the existing installation > > of > > Python, since OS X already comes with Python? I have a tiny little > > program (~20k) that I'd like to make into an app bundle, if only to > > suppress the console window, and I'd rather not lump in the whole > > Python > > interpreter if I can avoid it. > > > There is Platypus, a general open source program to wrap a script > in an Macintosh (GUI) It's an interesting application, but... I tried it to bundle a script that puts up a standard Tkinter file save dialog box and I found that the dialog box was not in front -- I had to switch applications to get to it. Still, it looks useful for fully faceless applications; unlike py2applet the text to stdout shows up in a log window. -- Russell From michael at stroeder.com Tue Jul 8 04:52:13 2008 From: michael at stroeder.com (=?UTF-8?B?TWljaGFlbCBTdHLDtmRlcg==?=) Date: Tue, 08 Jul 2008 10:52:13 +0200 Subject: windows active directory ldap output encoding In-Reply-To: References: Message-ID: jo3c wrote: > Im trying to get some information out of a windows sever 2003 chinese > active directory system > so let's say encoding is probably big5 or utf-8 The Unicode encoding of LDAP attributes with syntax Directory String is always UTF-8 (e.g. attributes 'cn', 'sn', 'givenName' or 'displayName'). > what im doing is simliar to ldapsearch in shell with my python script > using python ldap module > > the result is not the correct encoding.. What exactly did you expect? > 'cn': ['\xe6\xb1\x9f\xe6\x9f\x8f\xe5\xa3\x95'], >>> unicode('\xe6\xb1\x9f\xe6\x9f\x8f\xe5\xa3\x95','utf-8') u'\u6c5f\u67cf\u58d5' I cannot tell whether this Unicode string of length 3 is correct since I cannot read Chinese and I probably don't have the necessary fonts installed. At least it decodes as UTF-8 which is correct at the LDAP level. > 'displayName': ['\xe6\xb1\x9f\xe6\x9f\x8f\xe5\xa3\x95'], >>> unicode('\xe6\xb1\x9f\xe6\x9f\x8f\xe5\xa3\x95','utf-8') u'\u6c5f\u67cf\u58d5' Maybe you should provide the original Unicode string (e.g. in Python syntax) and tell us how you store that into your AD server. Note that the tools used to maintain AD are also part of the game. Ciao, Michael. From bj_666 at gmx.net Tue Jul 15 11:39:39 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Jul 2008 15:39:39 GMT Subject: String flags - redundant? References: Message-ID: <6e3ulrF527ucU1@mid.uni-berlin.de> On Tue, 15 Jul 2008 18:14:15 +0300, Alexandru Palade wrote: > I'm rather a Python newbie, so I've put myself a question. Are these two > statements (performance-wise) equal? > > r""" Text """ > and > """ Text """ > > I mean using the raw flag speeds up things because the interpreter > doesn't need to look after escape sequences? Or it's rather optimized? > I'm asking you this because I want to know how my """-style comments > should be written in order not to affect the performance. *Please* stop worrying about the speed of the compilation here. If you have doubts about speed then measure and find the bottlenecks in your code and iff you find hotspots *then* try to optimize. But only iff the program is *to slow*, not when it's fast enough anyway. In that case you should always favor more readable code above speed. > And another short question... Are there any flags to specify variables > intercalation in a string? I mean "I have x apples", how can i specify > for the interpreter to substitute x with it's value? (in case *x* is a > variable). And if this flag exists is it better to use "I have " + x + " > apples" or the above mentioned way? Maybe you should work through the tutorial in the Python documentation. Ciao, Marc 'BlackJack' Rintsch From sjdevnull at yahoo.com Sun Jul 6 03:07:32 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Sun, 6 Jul 2008 00:07:32 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <9cae59d9-ead4-45bc-a980-2ac2e1616f9b@p25g2000hsf.googlegroups.com> Message-ID: <1fed692b-099a-4a66-a26d-c937b5c610c8@f63g2000hsf.googlegroups.com> On Jul 5, 11:13 am, Mark Dickinson wrote: > Apparently, grep and Tcl convert a regex to a finite state machine. ... > But not all PCREs can be converted to a finite state machine ... > Part of the problem is a lack of agreement on what > 'regular expression' means. Strictly speaking, PCREs aren't > regular expressions at all, for some values of the term > 'regular expression'. See > > http://en.wikipedia.org/wiki/Regular_expression Formally, there's no lack of agreement that I'm aware of. Anyone formally defining it will use something along the lines of what wikipedia specifies (with "Regular expressions in this sense can express the regular languages, exactly the class of languages accepted by finite state automata."). Colloquially it's used to mean "any text- matching scheme that looks vaguely like sed/grep regexes". PCREs are certainly not "real" regular expressions, but they are colloquially. From deets at nospam.web.de Thu Jul 24 05:47:24 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 Jul 2008 11:47:24 +0200 Subject: Requires a character ... !! References: Message-ID: <6er1fdF8cqfvU1@mid.uni-berlin.de> > Thx for that info. I understand. > The requirements state that it needs Python 2.2, But i wonder > how that program has been implemented using Python 2.3 features. > Anyhow, this has to be resolved and i need your help. > > Kindly let me know a trick to make to resolve > the 'in' operator related problem by using Python 2.2. You obviously don't understand and it appears that it's time to resort to somewhat more explicit clue-batting: YOU ARE UNDER A WRONG IMPRESSION THAT YOUR SOFTWARE REQUIRES PYTHON 2.2. YOU HAVE BEEN TOLD THAT NUMEROUS TIMES. SO PLEASE - STOP USING PYTHON 2.2 FOR IT. WHOEVER TOLD YOU THAT IT IS NEEDED WAS ****WROOOOONG****** Now did that get through? Given your record here, I think I have to repeat... STOP USING PYTHON 2.2. NOW! Diez From diordna at gmail.com Sun Jul 20 23:05:54 2008 From: diordna at gmail.com (Stephen Johnson) Date: Sun, 20 Jul 2008 23:05:54 -0400 Subject: Python Written in C? In-Reply-To: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> References: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> Message-ID: <81FB1292-CE2E-49DB-AEF9-72F4D7866AD6@gmail.com> > Carry bits? Who worries about carry bits when you have > unlimited precision arithmetic? You want cool? > THIS is cool: > > j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2])) > % xyz[1]**(k-1))/xyz[1]**(k-2) You call that "cool." I call it "unreadable." -Steve Johnson From arsyed at gmail.com Sun Jul 20 18:09:19 2008 From: arsyed at gmail.com (arsyed) Date: Sun, 20 Jul 2008 18:09:19 -0400 Subject: examples of pipe usage? In-Reply-To: <5aab8bb6-0d56-475d-85c2-ced908e29412@x36g2000prg.googlegroups.com> References: <5aab8bb6-0d56-475d-85c2-ced908e29412@x36g2000prg.googlegroups.com> Message-ID: <9a2cc7a70807201509g5a41f6b9sb563bafcbdab5aa5@mail.gmail.com> On Sun, Jul 20, 2008 at 5:27 PM, Sean McIlroy wrote: > hola > > i'd like to control another interpreter from idle. i don't have any > experience using unix but i think a "pipe" is what i need. am i right > about this? can anybody point me to a simple example of using a pipe > (if that's the right thing) for this kind of task? thanks if you can > help. > > Take a look at the URL below which has a bunch of examples of using the subprocess module to interact with other processes. http://blog.doughellmann.com/2007/07/pymotw-subprocess.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From joshdw4 at gmail.com Thu Jul 31 07:15:04 2008 From: joshdw4 at gmail.com (joshdw4 at gmail.com) Date: Thu, 31 Jul 2008 04:15:04 -0700 (PDT) Subject: Tkinter- Possibly a basic question References: <59dee72b-3fb6-414b-ab49-33cab8f9c9e8@26g2000hsk.googlegroups.com> Message-ID: <75d21498-8bb7-43ac-842f-f4b6f2b0d179@m45g2000hsb.googlegroups.com> On Jul 30, 6:48?pm, "Guilherme Polo" wrote: > On Wed, Jul 30, 2008 at 6:33 PM, ? wrote: > >... > > ... > > The second option is to not create the root there, instead, make App > inherit Tk. I rarely see people doing this, but it works too. Here you > won't need to store the parent in an instance attribute, given it is > always accessible through self.master since you are subclassing Tk. > > ... > > -- > -- Guilherme H. Polo Goncalves Excellent, this one was easy enough for me to understand/implement and it worked. Thanks for the help. From pythonnutter at gmail.com Sat Jul 19 23:36:03 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Sun, 20 Jul 2008 13:36:03 +1000 Subject: Any Game Developers here? In-Reply-To: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: PS. To see some real games developed under pressure/time constraints in Python you should visit PyWeek to see what individuals and teams can create in only a weeks time! http://pyweek.org/ 2008/7/19 Michael Lubker : > Any people that use Python as the predominant language for their game > development here? > > ~Michael > -- > http://mail.python.org/mailman/listinfo/python-list > From anishchapagain at gmail.com Tue Jul 22 05:34:55 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Tue, 22 Jul 2008 02:34:55 -0700 (PDT) Subject: regarding SWIG Message-ID: <12e21dec-b269-4c34-9492-98424d207397@w7g2000hsa.googlegroups.com> Hi.. I'm new to SWIG and need to create Wrapper for C code, so, I have installed the SWIG already but doesnot know how to run it for generating Interface file... My C code is in message.c so what do i need to do the first step..uisng SWIG..i read the documentation but cannot grasp creating interface file. thank's anish From cwitts at gmail.com Wed Jul 23 04:51:45 2008 From: cwitts at gmail.com (Chris) Date: Wed, 23 Jul 2008 01:51:45 -0700 (PDT) Subject: maximum value in a column of file References: Message-ID: On Jul 23, 9:25?am, maurizio wrote: > ?which is the best way for the calculation of the maximum value in a > ? ? column of a file? oddly enough >>> help(max) Help on built-in function max in module __builtin__: max(...) max(iterable[, key=func]) -> value max(a, b, c, ...[, key=func]) -> value With a single iterable argument, return its largest item. With two or more arguments, return the largest argument. From castironpi at gmail.com Wed Jul 23 12:38:56 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 23 Jul 2008 09:38:56 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> Message-ID: <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> On Jul 22, 11:38?pm, Tim Roberts wrote: > castironpi wrote: > > >You're saying the VM can't compile code. ?That makes sense, it's not a > >compiler. > > I wouldn't say "can't". ?The current CPython VM does not compile code. ?It > COULD. ?The C#/.NET VM does. ?IronPython, for example, is an implementation > of Python that uses .NET. ?In that case, the code *IS* JIT compiled to > assembly when the program starts. > > >Do I understand correctly that JIT does compile to native > >code in some cases? > > VMs that use JIT do, yes. > > >But that's not the only thing that stops python > >from precompiling to assembly directly. ?GNU doesn't come with > >Python. > > Do you mean Linux? > > >What sorts of minimal information would be necessary to take > >from the GNU libs for the user's specific processor, (the one they're > >downloading their version of Python for), to move Python to the > >further step of outputting the machine code? > > I don't know why you think GNU has anything to do with this. ?There's > nothing that prevents the Python run-time from JIT compiling the code. > IronPython does this. ?CPython does not. ?It's an implementation decision. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. Compiling a program is different than running it. A JIT compiler is a kind of compiler and it makes a compilation step. I am saying that Python is not a compiler and in order to implement JIT, it would have to change that fact. > of Python that uses .NET. In that case, the code *IS* JIT compiled to > assembly when the program starts. But still not the user's code, only the interpreter, which is running in assembly already anyway in CPython. From fredrik at pythonware.com Tue Jul 22 16:41:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 22:41:56 +0200 Subject: software engineering foundations? In-Reply-To: <776bfd4d-a9c7-42f7-936f-967f58e7362d@59g2000hsb.googlegroups.com> References: <776bfd4d-a9c7-42f7-936f-967f58e7362d@59g2000hsb.googlegroups.com> Message-ID: Paddy wrote: > This course is an intensive introduction to basic software development > practices for scientists and engineers that can reduce the time they > spend programming by 20-25%. Judging from the table of contents and a quick sampling of a few lectures, that's mostly about programming (with a strong Python flavour), and the material about the engineering process is pretty simplistic, I'd say. On the other hand, the bibliography does have the following to say about the book I recommended: In short, it is everything I wished someone had told me before I started my first full-time programming job. so I guess it's not all that bad ;-) From amdescombes at gmail.com Sat Jul 26 07:33:09 2008 From: amdescombes at gmail.com (AMD) Date: Sat, 26 Jul 2008 13:33:09 +0200 Subject: scanf in python In-Reply-To: References: <4884be5e$0$19722$426a74cc@news.free.fr> <6ek4cgF7hq4vU1@mid.uni-berlin.de> <4884e77a$0$29405$426a74cc@news.free.fr> <4889ae4a$0$3726$426a74cc@news.free.fr> Message-ID: <488b0b7c$0$9616$426a74cc@news.free.fr> Thanks Fredrik, very nice examples. Andr? > AMD wrote: > >>> For reading delimited fields in Python, you can use .split string >>> method. > >> Yes, that is what I use right now, but I still have to do the >> conversion to integers, floats, dates as several separate steps. What >> is nice about the scanf function is that it is all done on the same >> step. Exactly like when you use % to format a string and you pass it a >> dictionary, it does all the conversions to string for you. > > You're confusing surface syntax with processing steps. If you want to > do things on one line, just add a suitable helper to take care of the > processing. E.g. for whitespace-separated data: > > >>> def scan(s, *types): > ... return tuple(f(v) for (f, v) in zip(types, s.split())) > ... > >>> scan("1 2 3", int, int, float) > (1, 2, 3.0) > > This has the additional advantage that it works with any data type that > provides a way to convert from string to that type, not just a small > number of built-in types. And you can even pass in your own local > helper, of course: > > >>> def myfactory(n): > ... return int(n) * "!" > ... > >>> scan("1 2 3", int, float, myfactory) > (1, 2.0, '!!!') > > If you're reading multiple columns of the same type, you might as well > inline the whole thing: > > data = map(int, line.split()) > > For other formats, replace the split with slicing or a regexp. Or use a > ready-made module; there's hardly every any reason to read standard CSV > files by hand when you can just do "import csv", for example. > > Also note that function *creation* is relatively cheap in Python, and > since "def" is an executable statement, you can create them pretty much > anywhere; if you find that need a helper somewhere in your code, just > put it there. The following is a perfectly valid pattern: > > def myfunc(...): > > def myhelper(...): > ... > > myhelper(...) > myhelper(...) > > for line in open(file): > myhelper(...) > > (I'd say knowing when and how to abstract things away into a local > helper is an important step towards full Python fluency -- that is, the > point where you're able to pack "a lot of action in a small amount of > clear code" most of the time.) > > > From pavlovevidence at gmail.com Sun Jul 20 21:00:07 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 20 Jul 2008 18:00:07 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <4ffdeab2-7422-4e08-8acb-e97d6b28cfef@m44g2000hsc.googlegroups.com> On Jul 20, 6:50?pm, giveitawhril2... at gmail.com wrote: > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. I somehow doubt the Python community will feel much of a loss if you decide to learn some other language. Carl Banks From modelnine at modelnine.org Wed Jul 30 03:49:34 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Wed, 30 Jul 2008 09:49:34 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> Message-ID: <200807300949.35060.modelnine@modelnine.org> Am Mittwoch, 30. Juli 2008 09:18:48 schrieb Russ P.: > Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > __nonzero__ work in Python. It's very basic stuff. You can quit > patronizing me (and Carl too, I'm sure). I'll stop repeating what the current state is (which might sound like I'm patronizing, but that's not the real intent actually, I'm just trying to get the discussion straight with what is fact, namely that there already exists an explicit way which doesn't seem to be recognized by some people here) if you agree to my point that we're not talking about a problem with Python, but about a personal stylistic issue with the language design. That's just what I said in my last mail: I can concede that you, personally, have an issue with the current state, but for me and seemingly also for a majority of people who have posted in this thread, that's a non-issue. > The point that you seem to be missing, or refuse to acknowledge for > some reason, is that "if x" can be mistakenly applied to any object > when the programmer thinks that x is a list -- and the programmer will > receive no feedback on the error. > > I have made errors like that, and I could have saved some time had I > used an "empty" method that only applies to a list or other sequence. For me, I've never had this kind of problem, simply because if I test for the truth value of something, I'm going to do something with it later on, and as soon as I'm doing something with it, I'll see whether the object supports the interface I want it to support (and get an error there if the object doesn't support the basic notions of a sequence type, for example, i.e. __iter__()). Testing for truth is IMHO not doing something with an object, and as such I'm more than happy that it's "foolproof". This is one thing that I personally find attractive about Python's way of duck-typing. But, if you personally have been bitten by this, give an example, and I'm sure that we can start discussing from there. I've already given an example why the explicit test for length is less polymorphic than the explicit test for truth of a container elsewhere as a proof for the point I'm trying to make. -- Heiko Wundram From gagsl-py2 at yahoo.com.ar Tue Jul 15 00:16:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 01:16:23 -0300 Subject: Problems Returning an HTTP 200 Ok Message References: <1cf880cc-2036-42dc-8217-d52a714c1710@a70g2000hsh.googlegroups.com> <9bc65e72-be16-4f73-9dfb-6ddeaae34c21@m73g2000hsh.googlegroups.com> <8596af5b-fd0a-413e-8051-62d650e9a153@8g2000hse.googlegroups.com> <8e0527eb-3af1-428f-bfc2-5c1809c33274@t54g2000hsg.googlegroups.com> Message-ID: En Mon, 14 Jul 2008 17:46:12 -0300, samwyse escribi?: > On Jul 11, 3:46?am, "Gabriel Genellina" > wrote: > >> As Guy Davidson has already pointed out, this is a problem in the meter > That would have been me, not Guy. Indeed, sorry the misattribution! -- Gabriel Genellina From john.hanks0 at gmail.com Fri Jul 25 15:36:44 2008 From: john.hanks0 at gmail.com (John Hanks) Date: Fri, 25 Jul 2008 15:36:44 -0400 Subject: Quesion on class.attributes assignment Message-ID: Hi, I am reading a python program now but I just cannot understand how the values of class attributes are assigned and changed. Here is the original code url: http://agolb.blogspot.com/2006/01/sudoku-solver-in-python.html Here I am concerned is how attribute matrix.rows is changed. Through pdb debugging, I can see in line 97, once "self.solutions = set((val,))" is executed, cell.row and matrix.rows will be updated. But I did not see any assignment codes here. How could this change happen then? Thanks a lot! John # http://agolb.blogspot.com/2006/01/sudoku-solver-in-python.html #!/usr/bin/env python # # sudoku-solver version 3 # # Some ideas ripped-off from: # http://www.linuxjournal.com/article/8729 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440542 # Pavol solver in # http://groups.google.com/group/comp.lang.python/browse_thread/thread/5087890f4c5e770d # # Copyright 2005 Ago, # But you are free to copy, reuse, modify and distribute the code as you see fit from copy import deepcopy class DeadEnd(Exception): pass class Matrix: def __init__(self, input): self.rows = [[] for i in range(9)] self.cols = [[] for i in range(9)] self.submatrices = [[] for i in range(9)] self.cells = [Cell(i,self) for i in range(81)] self.subdiagonals = [self.rows[i][j+i%3] for i in range(9) for j in [0,3,6]] input = [s not in '-*' and int(s) or 0 for s in input if s in '0123456789-*'] for cell,val in zip(self.cells, input): if val: cell.setSolution(val) def solve(self): #Brute-force solver self.solveByReduction() lensols=[(len(c.solutions),c.index) for c in self.cells if not c.solved] if not lensols: return True unsolved = min(lensols)[1] solutions = list(self.cells[unsolved].solutions) for s in solutions: tmpmatrix = deepcopy(self) try: tmpmatrix.cells[unsolved].setSolution(s) if tmpmatrix.solve(): self.update(tmpmatrix) return True except DeadEnd: pass def solveByReduction(self): while True: self.changed = False for c in self.cells: c.solve() for c in self.subdiagonals: c.skim() if not self.changed: break def update(self, m): self.rows, self.cols, self.submatrices, self.cells, self.subdiagonals=\ m.rows, m.cols, m.submatrices, m.cells, m.subdiagonals def __str__(self): return "\n".join(str([c for c in row ])[1:-1] for row in self.rows) class Cell: def __init__(self, index, matrix): self.solved = False self.matrix = matrix self.index = index self.row = matrix.rows[index/9] self.col = matrix.cols[index%9] self.submatrix = matrix.submatrices[((index/9)/3)*3+(index%9)/3] self.row.append(self) self.col.append(self) self.submatrix.append(self) self.solutions = set(range(1,10)) def solve(self): if self.solved: return if len(self.solutions) == 1: self.setSolution(self.solutions.pop()) else: sol = set() for cells in [self.row, self.col, self.submatrix]: otherSolutions = self.cells2sols(cells, self) sol |= (self.solutions - otherSolutions) if len(sol) > 1: raise DeadEnd() if sol: self.setSolution(sol.pop()) def skim(self): submatrix = set(self.submatrix) for r in (set(self.row), set(self.col)): subset1 = submatrix - r subset2 = r - submatrix solsNotIn1 = set(range(1,10)) - self.cells2sols(subset2) solsNotIn2 = set(range(1,10)) - self.cells2sols(subset1) for c in subset1: c.delSolutions(solsNotIn1) for c in subset2: c.delSolutions(solsNotIn2) def setSolution(self, val): self.solved = True self.solutions = set((val,)) self.matrix.changed = True for other in self.row+self.col+self.submatrix: if other is self: continue if other.solutions == self.solutions: raise DeadEnd() other.delSolutions(self.solutions) def delSolutions(self, val): if not self.solved and val & self.solutions: self.solutions -= val self.matrix.changed = True if not self.solutions: raise DeadEnd() def __repr__(self): return str(self.solved and list(self.solutions)[0] or list(self.solutions)) @staticmethod def cells2sols(cells, exclude=None): return set(s for c in cells for s in c.solutions if c is not exclude) if __name__ == "__main__": input =''' 1,0,0,0,0,0,0,0,2 0,9,0,4,0,0,0,5,0 0,0,6,0,0,0,7,0,0 0,5,0,9,0,3,0,0,0 0,0,0,0,7,0,0,0,0 0,0,0,8,5,0,0,4,0 7,0,0,0,0,0,6,0,0 0,3,0,0,0,9,0,8,0 0,0,2,0,0,0,0,0,1 ''' matrix = Matrix(input) matrix.solve() print matrix -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: AgolB.py URL: From mail at timgolden.me.uk Fri Jul 4 09:24:36 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 04 Jul 2008 14:24:36 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) In-Reply-To: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: <486E2494.3080905@timgolden.me.uk> Bill Davy wrote: > I am trying to edit Contacts in Outlook. This is so I can transfer numbers > from my address book which is an Excel spreadsheet to my mobile phone. I > came across the following snippet of code --- hey! that looks familiar :) > which enabled me to the contacts > at least list. I had to root around to discover CdoDefaultFolderContacts > (though it was guessable; how could I enumerate win32com.client.constants?). Well that bit's easy: win32com.client.constants is a small class with a __dicts__ attribute (note the "s") which is a list of dictionaries, one per generated library. So you can do something like this: import win32com.client outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") outlook_constants = win32com.client.constants.__dicts__[0] for k, v in outlook_constants.items (): print k, "=>", v > I now want to work through the Contacts in Outlook patching in data from my > spreadsheet, and also making new contacts where there is an entry in my > spreadsheet which has not gone into Contacts already. OK. > Where can I find the API? I recommend: http://msdn.microsoft.com/en-us/library/ms526861.aspx and http://www.outlookcode.com/article.aspx?id=20 and http://www.cdolive.com/cdo10.htm TJG From deets at nospam.web.de Thu Jul 17 07:31:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 17 Jul 2008 13:31:13 +0200 Subject: Good HTML Parser References: Message-ID: <6e8otlF5k4pgU1@mid.uni-berlin.de> Chris wrote: > Can anyone recommend a good HTML/XHTML parser, similar to > HTMLParser.HTMLParser or htmllib.HTMLParser, but able to intelligently > know that certain tags, like
, are implicitly closed? I need to > iterate through the entire DOM, building up a DOM path, but the stdlib > parsers aren't calling handle_endtag() for any implicitly closed tags. > I looked at BeautifulSoup, but it only seems to work by first parsing > the entire document, then allowing you to query the document > afterwards. I need something like a SAX parser. This isn't possible. Your own example of arbitrarily closeable Tags needs context that just a SAX-like parser can't provide. I suggest you use BeautifulSoup, and if you must create your own event-generation around that which you can attach consumers to. Diez From bignose+hates-spam at benfinney.id.au Thu Jul 10 23:30:06 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 11 Jul 2008 13:30:06 +1000 Subject: paypal wholesale men jordans 17 (paypal accept)(www super-saler com References: <5d746374-d2a0-411e-bf60-87256a219b7c@m44g2000hsc.googlegroups.com> Message-ID: <87skuhqerl.fsf@benfinney.id.au> WDC writes: > On Jul 10, 10:33?pm, 128 wrote: [?] > > Is that spam i spy? It is, clearly. Please don't make the problem worse by repeating the entire thing. -- \ ?I got fired from my job the other day. They said my | `\ personality was weird. ? That's okay, I have four more.? | _o__) ?Bug-Eyed Earl, _Red Meat_ | Ben Finney From bj_666 at gmx.net Mon Jul 7 11:12:30 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Jul 2008 15:12:30 GMT Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: <6deq2uF21vo2U1@mid.uni-berlin.de> On Mon, 07 Jul 2008 16:44:22 +0200, Sebastian \"lunar\" Wiesner wrote: > Mark Wooding : > >> Sebastian "lunar" Wiesner wrote: >> >>> # perl -e '("a" x 100000) =~ /^(ab?)*$/;' >>> zsh: segmentation fault perl -e '("a" x 100000) =~ /^(ab?)*$/;' >> >> (Did you really run that as root?) > > How come, that you think so? The '#' is usually the prompt of root accounts while ordinary users get a '$'. Ciao, Marc 'BlackJack' Rintsch From sunp1028 at gmail.com Mon Jul 14 22:22:01 2008 From: sunp1028 at gmail.com (patrol) Date: Mon, 14 Jul 2008 19:22:01 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> Message-ID: Situation (1): result = new_process.terminate() TypeError: 'int' object is not callable Situation (2): result = new_process.terminate() File "C:\Python25\lib\wmi.py", line 494, in __getattr__ handle_com_error (error_info) File "C:\Python25\lib\wmi.py", line 190, in handle_com_error raise x_wmi, "\n".join (exception_string) UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 14: ordinal not in range(128) BTW, My windows' languange is Chinese. From torainLight at gmail.com Sun Jul 13 08:35:01 2008 From: torainLight at gmail.com (satoru) Date: Sun, 13 Jul 2008 05:35:01 -0700 (PDT) Subject: why is "self" used in OO-Python? References: Message-ID: <9c766948-5d96-44ac-b0d9-9e99b702359c@z66g2000hsc.googlegroups.com> On Jul 13, 12:32?am, ssecorp wrote: > I first learned about OO from Java. > > I much prefer to program in Python though. > > However I am consufed about 2 things. > > 1. Why do I have to pass self into every method in a class? Since I am > always doing why cant this be automated or abstracted away? > Are the instances where I won't pass self? > I imagine there is some tradeoff involved otherwise it would have been > done away with. > > 2. self.item instead of getters and setters. I thought one of the main > purposes of OO was encapsulation. Doesn't messing with internal object- > representations break this? > I see how the getters and setters could be just visual clutter and you > have to add them to every class so it is annoying a bit in the same > way as self described above. > However I feel like I want getters and setters when I write classes, > not sure of the advantages/disadvantages though. > Only looking at the documentation of a Python-class, will internal > representations be provided? > > If I have a class: > > class Stack(object): > ? ? def __init__(self, *items): > ? ? ? ? self.stack = list(items) > > ? ? def append(self, item): > ? ? ? ? self.stack.append(item) > > ? ? def pop(self): > ? ? ? ? return self.stack.pop() > > I can get to see the stack with var.stack but then why even implement > append when I could do self.stack.append(x) etc. > That way you could do away with OO completely. So why let people > access the main attribute but not let them manipulate it? > Makes more sense to draw the line to not access any attributes at all > no? i think the following article may be helpful to you. "Introduction to OOP with Python" http://www.voidspace.org.uk/python/articles/OOP.shtml#id34 From fredrik at pythonware.com Wed Jul 23 03:47:10 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 09:47:10 +0200 Subject: mean of arobase in python In-Reply-To: <7c49f36f0807230033k40722abfwdb28c34d3d88a32a@mail.gmail.com> References: <7c49f36f0807230033k40722abfwdb28c34d3d88a32a@mail.gmail.com> Message-ID: Guilhem Faure wrote: > What means @ in python ? usually called "at sign" in english. > In this script for exemple (this script return an error in my konsole...) > > @f1(arg) > @f2 > def func(): pass > > I see several script where used this symbol but I can't understand. in your example, "f1(arg)" and "f2" are decorators. the above is equivalent to writing def func(): pass func = f1(arg)(f2(func)) that is, define a function, and then pass it to the function "f2", and then to the function that's returned by calling "f1(arg)". the final value of the "func" variable is whatever the decorators returned. the decorator functions (f2 and whatever f1(arg) returns) can manipulate the function being defined, or even replace it with something else. specification: http://www.python.org/dev/peps/pep-0318/ some (semi-advanced) articles: http://www.ibm.com/developerworks/linux/library/l-cpdecor.html http://www.phyast.pitt.edu/~micheles/python/documentation.html From tjreedy at udel.edu Fri Jul 18 17:57:13 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Jul 2008 17:57:13 -0400 Subject: Core Dump - Segmentation Fault -Newbie In-Reply-To: <8ba4373d-3d97-4e9a-a15e-723f6818c757@k36g2000pri.googlegroups.com> References: <8ba4373d-3d97-4e9a-a15e-723f6818c757@k36g2000pri.googlegroups.com> Message-ID: johnericaturnbull at yahoo.com wrote: > Hi - I am very new to python. I get this random core dump and am > looking for a good way to catch the error. I know the function my core > dump occurs. Is there any error catching/handling that I could use in > python? When posting such questions, please supply Python version, system info, and usually code. If you wrote a function in Python that seg faulted, congratulations, its hard (but not impossible) to do ;-). Post it. If you (or someone else) wrote a C function that seg faulted while calling the Python api, well that is much easier. Post it or bug the author. If you (or someone else) wrote a C function that seg faulted in normal C code, well that's easy. Most likely a bad pointer. tjr From bearophileHUGS at lycos.com Wed Jul 30 12:32:25 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 30 Jul 2008 09:32:25 -0700 (PDT) Subject: Non Continuous Subsequences Message-ID: This post is not about practical stuff, so if you have little time, you may ignore it. This is a task of the rosettacode.org site: http://www.rosettacode.org/wiki/Non_Continuous_Subsequences A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence. The task is to enumerate all non-continuous subsequences for a given sequence. Translating the Scheme code to Python was easy (and I think this is quite more readable than the Scheme version): def ncsub(seq, s=0): if seq: x = seq[:1] xs = seq[1:] p2 = s % 2 p1 = not p2 return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2) else: return [[]] if s >= 3 else [] Output: >>> ncsub(range(1, 4)) [[1, 3]] >>> ncsub(range(1, 5)) [[1, 2, 4], [1, 3, 4], [1, 3], [1, 4], [2, 4]] >>> ncsub(range(1, 6)) [[1, 2, 3, 5], [1, 2, 4, 5], [1, 2, 4], [1, 2, 5], [1, 3, 4, 5], [1, 3, 4], [1, 3, 5], [1, 3], [1, 4, 5], [1, 4], [1, 5], [2, 3, 5], [2, 4, 5], [2, 4], [2, 5], [3, 5]] To test its speed I use this: from sys import argv def ncsub(seq, s=0): if seq: x = seq[:1] xs = seq[1:] p2 = s % 2 p1 = not p2 return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2) else: return [[]] if s >= 3 else [] import psyco; psyco.bind(ncsub) print len( ncsub(range(1, int(argv[1]))) ) On a 2 GHz CPU it needs 6.4s with n=20 (the output contains 524_097 sublists!), and 7.8s without Psyco, so I think the speed isn't bad. With the libs I have written for D, translating the Python code is not difficult (with n=20 it runs in 3.72s with the last DMD compiler): import d.all; T[][] ncsub(T)(T[] seq, int s=0) { if (seq.length) { T[] xs = seq[1..$]; int p2 = s % 2; int p1 = !p2; return map((T[] ys){return seq[0]~ys;}, ncsub(xs, s+p1)) ~ ncsub(xs, s+p2); } else return s >= 3 ? [DA!(T)] : null; } void main() { foreach (m; xrange(4, 7)) putr(ncsub(range(1, m))); } But with normal D the program is short enough anyway (but a slower to run (4.7s with n=20) and faster to compile, about 0.1s with full optimizations and about 0.07s without): import std.stdio: writefln; T[][] ncsub(T)(T[] seq, int s=0) { if (seq.length) { T[][] aux; foreach (ys; ncsub(seq[1..$], s + !(s % 2))) aux ~= seq[0] ~ ys; return aux ~ ncsub(seq[1..$], s + s % 2); } else return s >= 3 ? [new T[0]] : null; } void main() { writefln(ncsub([1, 2, 3])); writefln(ncsub([1, 2, 3, 4])); writefln(ncsub([1, 2, 3, 4, 5])); } The Scheme version is eager, it comes from the first Haskell version, that I think is lazy. In Python the management of lazy iterables feels almost bolted-on compared to Haskell, for example in Haskell lazy iterables don't exhaust like in Python (because they are immutable), and while you create a lazy list you can refer to the items already created. But in many cases you can create a lazy code in Python too, even if that may be harder. So I have tried to create a lazy version for Python, hoping to speed up the code avoiding the creation and joining of most/all sublists, but I have failed so far (once I have created a lazy Python version, I can probably create a short lazy version in D too, my D libs contain most of itertools module too). In my failed attempts I have used chain() to join the sublists, islice() to slice their items, and iter() to make the management more uniform when the input seq is a Python list instead of an xrange, etc. The: if seq: can be replaced by something like: try: x = seq2.next() except StopIteration: ... else: ... If you have some time to waste you may suggest me how to write a lazy version in Python :-) Bye, bearophile From israelu at elbit.co.il Tue Jul 29 02:49:55 2008 From: israelu at elbit.co.il (iu2) Date: Mon, 28 Jul 2008 23:49:55 -0700 (PDT) Subject: seemingly simple list indexing problem References: <1ad9234a-6bba-48ce-ad40-ea0aeabce492@79g2000hsk.googlegroups.com> Message-ID: On Jul 29, 2:26?am, John Krukoff wrote: > On Mon, 2008-07-28 at 16:00 -0700, iu2 wrote: > > On Jul 29, 12:10 am, John Krukoff wrote: > > > On Mon, 2008-07-28 at 16:24 -0500, Ervan Ensis wrote: > > > > My programming skills are pretty rusty and I'm just learning Python so > > > > this problem is giving me trouble. > > > > > I have a list like [108, 58, 68]. ?I want to return the sorted indices > > > > of these items in the same order as the original list. ?So I should > > > > return [2, 0, 1] > > > > > For a list that's already in order, I'll just return the indices, i.e. > > > > [56, 66, 76] should return [0, 1, 2] > > > > > Any help would be appreciated. > > > > > -- > > > >http://mail.python.org/mailman/listinfo/python-list > > > > If your lists aren't so large that memory is an issue, this might be a > > > good place for a variation of decorate, sort, undecorate. > > > > >>> listToSort = [ 108, 58, 68 ] > > > >>> decorated = [ ( data, index ) for index, data in > > > > enumerate( listToSort ) ]>>> decorated > > > > [(108, 0), (58, 1), (68, 2)]>>> result = [ None, ] * len( listToSort ) > > > >>> for sortedIndex, ( ignoredValue, originalIndex ) in > > > > enumerate( sorted( decorated ) ): > > > ... ? ? result[ originalIndex ] = sortedIndex > > > ...>>> result > > > > [2, 0, 1] > > > > -- > > > John Krukoff > > > Land Title Guarantee Company > > > Inspired by your idea and the above one, here is another try: > > > >>> a0 = [108, 58, 68, 108, 58] > > >>> a1 = [(x, y) for x, y in enumerate(a0)] > > You know this line is a no-op, right? > > > >>> a1 > > [(0, 108), (1, 58), (2, 68), (3, 108), (4, 58)] > > >>> a2 = sorted(a1, lambda x, y: cmp(x[1], y[1])) > > If you're going to do the unpacking here for the sort, just use > enumerate directly. Since this is a simple case, should use the key > parameter instead of the cmp parameter for speed. Can also use the > operator module to avoid a bit of lambda overhead: > > >>> import operator > >>> a2 = sorted( enumerate( a0 ), key = operator.itemgetter( 1 ) ) > > >>> a2 > > [(1, 58), (4, 58), (2, 68), (0, 108), (3, 108)] > > >>> a3 = [a2.index(x) for x in a1] > > >>> a3 > > [3, 0, 2, 4, 1] > > > The idea is to make each item unique (by making it a tuple), and then > > apply the naive solution. > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Using index is still kinda evil, due to the exponential time required > since you're rescanning half the list (on average) to find each index > value. > > -- > John Krukoff > Land Title Guarantee Company- Hide quoted text - > > - Show quoted text - Well, a dictionary can replace the index search helper_dict = dict(zip(a2, xrange(len(a2)))) >>> helper_dict {(1, 58): 0, (4, 58): 1, (3, 108): 4, (2, 68): 2, (0, 108): 3} a3 = [helper_dict[x] for x in a1] >>> a3 [3, 0, 2, 4, 1] The performance now should be n*log(n) From p0q0b0d at gmail.com Wed Jul 9 08:52:18 2008 From: p0q0b0d at gmail.com (|e0) Date: Wed, 9 Jul 2008 14:52:18 +0200 Subject: Newbie question In-Reply-To: References: <3b1e6f480807082337l419fd40ax91eaf13e0701c5b3@mail.gmail.com> Message-ID: <3b1e6f480807090552m51be62a9tbb76085504e5d4e3@mail.gmail.com> I did not mean to use WMI on linux, but query win machines *from* linux. Thank you for your clarifications - Leonardo On Wed, Jul 9, 2008 at 11:04 AM, A.T.Hofkamp wrote: > Welcome to the world outside MS. > > Many python modules don't actually do anything than passing on calls to an > existing underlying library. They are cheap to make, and make it possible to > use the functionality of the library from a Python program. The down-side is, > as you have discovered, that you need the underlying library to make it work. > > So, the answer is no, you cannot use wmi under a non-MS OS. (But what did you > expect, given that wmi means WINDOWS Management Instrumentation?) No doubt > there are also open source variants of this package, however, I am not familiar > with them, so I cannot help you. > > > Albert From timr at probo.com Thu Jul 31 02:17:59 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 31 Jul 2008 06:17:59 GMT Subject: interpreter vs. compiled References: <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> Message-ID: <4rl294duo83eujnq6tjbk215mavpl87o9r@4ax.com> castironpi wrote: > >In C, we have: > >int x, y; >x= 10; >y= x+ 1; > >It translates as, roughly: >> >8000 .data >7996 ffffffff #x >7992 ffffffff #y >7988 .end data >7984 loadi reg0 7996 >7980 loadi reg1 7992 >7976 loadi reg2 10 >7972 loadi reg3 1 >7968 storv reg2 reg0 >7964 add reg0 reg1 reg2 >7960 storv reg3 reg1 I don't recognize that assembly language. Is that another intermediate language? >You are telling me that the same thing happens in IronPython. Yes, the same process happens. >By the >time the instruction pointer gets to 'x= 10', the next 7 instructions >are the ones shown here compiled from C. I most certainly did NOT say that, as you well know. Different C compilers produce different instruction sequences for a given chunk of code. Indeed, a single C compiler will produce different instruction sequences based on the different command-line options. It's unreasonable to expect a Python compiler to produce exactly the same code as a C compiler. However, that does disqualify the Python processor as a "compiler". >CMIIW, but the CPython implementation -does- -not-. And again, I never said that it did. CPython is an interpreter. the user's code is never translated into machine language. >My point is, CPython takes more than seven steps. My question is, >does IronPython? So, if compiler B isn't as good at optimization as compiler A, does that mean in your mind that compiler B is not a "compiler"? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From torriem at gmail.com Mon Jul 21 00:50:40 2008 From: torriem at gmail.com (Michael Torrie) Date: Sun, 20 Jul 2008 22:50:40 -0600 Subject: Python Written in C? In-Reply-To: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> References: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> Message-ID: <488415A0.10107@gmail.com> Mensanator wrote: > On Jul 20, 7:37?pm, Roy Smith wrote: >> In article >> , >> >> ?Mensanator wrote: >>> C isn't a high level language, that's part of its problem. >> C is the highest level assembler language > > Isn't that like bragging about being the smartest > kid on the short bus? > >> I've ever used. ?And I've used a >> few. ?It really is cool that you can add two 32-bit integers and not have >> to worry about all those carry bits. > > Carry bits? Who worries about carry bits when you have > unlimited precision arithmetic? You want cool? Perhaps you missed the wonderful humor in Roy's post. It was rather brilliant. Sorry you missed it. From paul.hankin at gmail.com Wed Jul 23 05:11:17 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 23 Jul 2008 02:11:17 -0700 (PDT) Subject: Is this possible .... References: Message-ID: On Jul 23, 9:58?am, Stef Mientki wrote: > hello, > > I'm looking for a way to remove duplicate code. > The problem is this: > In all my modules I've version information, > containing version information, date, author, testconditions etc, > something like this: > > Version_Text = [ > [ 0.2, '10-02-2008', 'Stef Mientki', > 'Test Conditions:', (1,2), > _(0, """ > ? ?- scaling and offset is set for each individual signal > ? ?- Time history window for 1 signal with min/max display > ? ?- set attributes for all signals at once > """) ], > > [ 0.1, '04-11-2007', 'Stef Mientki', > 'Test Conditions:', (1,), > """ > ? ? - orginal release > """ ] > ] > > Now I've made modules that can generate docs, a library manager, etc, > and that even in different languages. > > But for the simple case I would like to have a simple function, which > just displays the version number. > So in each module, there is a function: > > def version () : > ? return ( version_text [0] [0] ) > > But is there a way to avoid the placing of this function "version" in > each module, > and still use a simple call like: > ? .version() You could use version() instead of module.version(), and just declare 'version' in one place. Presumably you already have a module for getting the metadata out of one of your modules; perhaps it could go in there? def version(module): return getattr(module, 'Version_Text')[0][0] -- Paul Hankin From bignose+hates-spam at benfinney.id.au Tue Jul 29 19:14:56 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 30 Jul 2008 09:14:56 +1000 Subject: DB access without object-relation mapping? References: Message-ID: <87tze8ffkf.fsf@benfinney.id.au> kj writes: > The word on the street is to use something like SQLAlchemy for > database access in Python, but my experience in the past with > packages that perform automated SQL generation has been awful, so I > always return to lighter-weight solutions that allow me to write my > own SQL. Using SQLAlchemy, you *can* write your own SQL (with its 'text' query type to feed explicit SQL text on the connection); you just don't *need* to for the majority of simple and not-so-simple cases. I've been using SQLAlchemy for some time and have found its combination of "make the simple cases simple" and "allow full control when needed" to be close to ideal. I can use exactly the same interface to leverage the SQL generation for mundane tasks and to craft custom weird SQL that I need. Combine that with active, level-headed maintenance, and comprehensive documentation, and I don't even need to consider using the ORM layer :-) -- \ ?Know what I hate most? Rhetorical questions.? ?Henry N. Camp | `\ | _o__) | Ben Finney From rparimi at gmail.com Wed Jul 9 19:32:28 2008 From: rparimi at gmail.com (rparimi at gmail.com) Date: Wed, 9 Jul 2008 16:32:28 -0700 (PDT) Subject: redirecting output of process to a file using subprocess.Popen() Message-ID: <515ad1dd-15b0-4f7a-8ea2-87e0bb0cb47e@f36g2000hsa.googlegroups.com> I am trying to redirect stderr of a process to a temporary file and then read back the contents of the file, all in the same python script. As a simple exercise, I launched /bin/ls but this doesn't work: #!/usr/bin/python import subprocess as proc import tempfile name = tempfile.NamedTemporaryFile(mode='w+b') print 'name is '+ name.name cmd = [] cmd.append('/bin/ls') cmd.append('-l') cmd.append('/tmp') p = proc.Popen(cmd, stdout=name, stderr=proc.STDOUT, close_fds=True) while True: ret = p.poll() if (ret is not None): output = name.readlines() print 'out = ', output break $python sub.py name is /tmp/tmpjz4NJY out = [] I tried calling flush() on the file object but this didn't help either. Tried closing and re-opening the file, but closing the file object results in it getting deleted. Can the above be made to work by using tempfiles? thanks From fredrik at pythonware.com Mon Jul 21 10:10:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 16:10:35 +0200 Subject: Odd math related issue. In-Reply-To: <6472d2d2-1f0e-44af-8bdb-b7e475080e26@v28g2000pro.googlegroups.com> References: <43332.3139710867$1216630189@news.gmane.org> <48847F5D.9080509@sellerengine.com> <6472d2d2-1f0e-44af-8bdb-b7e475080e26@v28g2000pro.googlegroups.com> Message-ID: sahasranaman wrote: > Use 2.0 / 3 * 100 to solve this. Why make things look bigger? you mean that a.0 / 3 * 100 works in your Python version? that's interesting. (maybe you should at least skim the the thread before you jump in?) From mathieu.prevot at gmail.com Sun Jul 6 14:05:56 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Sun, 6 Jul 2008 20:05:56 +0200 Subject: Problem with subprocess.Popen wget within a thread Message-ID: <3e473cc60807061105n6cdd67ffw5044b8abe7a0725a@mail.gmail.com> Hi it seems the script (A) finishes before the downloading ends, and the (B) version doesn't (wanted behavior) ... this is unexpected. What happens ? (A) ============================================ class vid(threading.Thread): def __init__(self): threading.Thread.__init__(self) def download(self): self.cmd = 'wget ftp://ftp.freebsd.org/pub/FreeBSD/releases/i386/ISO-IMAGES/7.0/7.0-RELEASE-i386-bootonly.iso' self.child = subprocess.Popen(self.cmd.split()) def run(self): self.download() def main(): w = vid() w.start() w.join() (B) ============================================ class vid(threading.Thread): def __init__(self): threading.Thread.__init__(self) def download(self): self.cmd = 'wget ftp://ftp.freebsd.org/pub/FreeBSD/releases/i386/ISO-IMAGES/7.0/7.0-RELEASE-i386-bootonly.iso' self.child = subprocess.Popen(self.cmd.split(), stderr=subprocess.PIPE) def run(self): self.download() self.child.stderr.readlines() def main(): w = vid() w.start() w.join() ============================================ From jayjaygibbs at hotmail.co.uk Sun Jul 6 22:33:27 2008 From: jayjaygibbs at hotmail.co.uk (jayjaygibbs at hotmail.co.uk) Date: Sun, 6 Jul 2008 19:33:27 -0700 (PDT) Subject: GUI Programming by hand not code with Python Code Message-ID: <7003b665-3227-47a7-ab06-1a486f87939a@a1g2000hsb.googlegroups.com> Is their a program that lets you design a GUI by hand (like gambas) not by code (like wxpython) but the commands are in python? A program similar to gambas or vb Gambas with python code instead of gambas code would be perfect. Thanks in advance From david.lyon at preisshare.net Sat Jul 19 08:37:15 2008 From: david.lyon at preisshare.net (David Lyon) Date: Sat, 19 Jul 2008 22:37:15 +1000 Subject: Help with displaying images in CherryPy Message-ID: <4881DFFB.5060306@preisshare.net> Hi all, I have a very simple question about configuration under CherryPy - it is such a simple one but I have been struggling to find an answer for a few days. All I want is a sample configuration file that will allow me to display a page with a jpeg on it. Whilst there are some examples in the CherryPy examples, they are mixed with so many other concepts that it is difficult for me (a newbie) to figure it out. None actually show me where to put image files. This really should only take a few minutes for somebody who has done this in CherryPy before and I would certainly appreciate the assistance because it doesn't seem covered in any documentation that i could find. Regards David From gh at ghaering.de Wed Jul 23 04:19:24 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 23 Jul 2008 10:19:24 +0200 Subject: How do I compare files? In-Reply-To: <1216769247.18962.7.camel@generator> References: <1216769247.18962.7.camel@generator> Message-ID: Clay Hobbs wrote: > I am making a program that (with urllib) that downloads two jpeg files > and, if they are different, displays the new one. I need to find a way > to compare two files in Python. How is this done? There's a module in the standard library called filecmp ;-) -- Gerhard From fredrik at pythonware.com Thu Jul 24 06:13:01 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 12:13:01 +0200 Subject: instance comparison In-Reply-To: References: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> Message-ID: King wrote: > The only methods I do have in class is __init__ and __str__. > How ever inst1 and inst2 is coming from a dictionary where I stored > them with a unique id. > > inst1 = stored[id] > inst2 = stored[id] > > Is this makes a difference? unlikely (well, if that's the literal code, both variables will point to the same variable, but I guess that's not what you meant). > I will rip down the piece of code giving me problem and post. please do. and don't be surprised if you find the problem while doing so ;-) From socyl at 987jk.com.invalid Tue Jul 29 17:13:36 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 21:13:36 +0000 (UTC) Subject: Where is the documentation for psycopg2? References: Message-ID: In Matthew Woodcraft writes: >kj wrote: >> Hi. I can't find any documentation for psycopg2. >> >> I'm a noob, so I'm sure I'm just not looking in the right place... >> >> Anybody know where it is? >For basic use, psycopg2 follows the dbapi, which is described in >http://www.python.org/dev/peps/pep-0249/ >Additional features are described in doc/extensions.rst in the psycopg2 >tarball. >This leaves a gap for documentation of the basic features which the >dbapi doesn't nail down (in particular, connecting to a database in the >first place). I don't think there is any proper documentation covering >this, but the scripts in examples/ (particularly simple.py) should make >it reasonably clear. That's very helpful. I would have never found it on my own. Thanks! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From gros_bedo at hotmail.com Wed Jul 9 19:07:03 2008 From: gros_bedo at hotmail.com (Gros Bedo) Date: Thu, 10 Jul 2008 01:07:03 +0200 Subject: Freesoftware for auto/intelligent code completing in Python Message-ID: Hello, Ali I totally support you, neither I couldn't find any really working code completion for python in a free software, and it's really a mess, at least on Linux. On Windows, there is PyScripter (http://pyscripter.googlepages.com/), but it is based on Delphi, and as such it's not portable. But it's a free software (even if I couldn't find the sources, they say you can download them). It is said to be working on Linux via Wine, so if you really need a code completion tool you could give it a try. _________________________________________________________________ T?l?chargez gratuitement des ?motic?nes pour pimenter vos conversations Messenger http://specials.fr.msn.com/femmes/amour/emoticonesLove.aspx From marcus at internetnowasp.net Sat Jul 12 22:14:15 2008 From: marcus at internetnowasp.net (Marcus Low) Date: Sun, 13 Jul 2008 10:14:15 +0800 Subject: Someone enlightened me In-Reply-To: <4879645F.3070504@internetnowasp.net> References: <4879645F.3070504@internetnowasp.net> Message-ID: <487964F7.8000908@internetnowasp.net> Duh, Ok here is the file again ...attached. I give up doing this via the email editor. Sorry! new to the mailing list. Marcus Marcus Low wrote: > Opps here is the mail again, incase my formatting is lost, can someone > explain to me why this code behaves differently when "lister" and > "self.lister" is swap remarked. > > > class abc : > # remark this later and unremark "self.lister" > lister = [] > def __init__ (self, val): > #self.lister = [] > self.lister.append(val) > globallist = [] > > def test () : > > global l > for x in range(10) : > o = abc(x) globallist.append(o) o > = "" > for i in globallist : > print i.lister > test() > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: k.txt URL: From cokofreedom at gmail.com Wed Jul 9 07:08:30 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 9 Jul 2008 04:08:30 -0700 (PDT) Subject: Impossible to change methods with special names of instances of new-style classes? References: Message-ID: > > My question is: did something about the way the special method names are > implemented change for new-style classes? > >>> class old: pass >>> class new(object): pass >>> testone = old() >>> testone.__call__ = lambda : 33 >>> testone() 33 >>> testtwo = new() >>> testtwo.__call__ = lambda : 33 >>> testtwo() Traceback (most recent call last): File "", line 1, in testtwo() TypeError: 'new' object is not callable >>> old.__call__ Traceback (most recent call last): File "", line 1, in old.__call__ AttributeError: class old has no attribute '__call__' >>> new.__call__ >>> testone.__call__ at 0x00C35EB0> >>> testtwo.__call__ at 0x00C35B70> >>> dir(testtwo) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] >>> dir(testone) ['__call__', '__doc__', '__module__'] >>> dir(new) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] >>> dir(old) ['__doc__', '__module__'] I don't see __call__ in either class structures, but for new style classes it is a wrapper and for old it is nothing. Not sure if that helps, but this is rather over my head. From greg at cosc.canterbury.ac.nz Tue Jul 29 00:32:51 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 29 Jul 2008 16:32:51 +1200 Subject: with statement for two files In-Reply-To: <6f6cfdFa22kkU1@mid.uni-berlin.de> References: <08d72316-15f1-45dd-b1f7-7b8ee06efef5@e39g2000hsf.googlegroups.com> <7xsktuvusj.fsf@ruckus.brouhaha.com> <6f6cfdFa22kkU1@mid.uni-berlin.de> Message-ID: <6f7l86Fa9d5lU2@mid.individual.net> Diez B. Roggisch wrote: > Paul Rubin wrote: > > > use contextlib.nexted(). > > You mean contextlib.nested I guess. Although "nexted" is an intriguing-sounding word. I wonder what it could mean? -- Greg From fuzzyman at gmail.com Thu Jul 3 13:38:31 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 3 Jul 2008 10:38:31 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> <9ad840e1-e12f-4125-8537-4bad2ef77f51@w5g2000prd.googlegroups.com> Message-ID: <6b1e8a6c-4d21-488d-a8b9-74388f1f5c43@m45g2000hsb.googlegroups.com> On Jul 2, 9:33?am, Ali Servet D?nmez wrote: > On Jul 1, 12:15?am, Fuzzyman wrote: > > > > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > I don't want to be so mean here, but how hard it could be be writing a > > > freesoftware which would automatically/intelligently auto complete > > > Python code? (I mean something that really does the job, like > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > name it, but just don't give me PyDev please...) > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > missing here? > > > > Could someone please point me out something that I'm really missing > > > which is already present in the wild, otherwise I'd like discuss with > > > whoever is willing to help me to get this thing done. I made my mind > > > and I could volunteer to make this happen as thesis project for my > > > incoming graduation in the next year. > > > > Regards you all, > > > Ali Servet D?nmez > > > Vim, Emacs, Wing, Komodo, ... more? > > > Yeah, I guess you're missing something. :-) > > > MichaelFoordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > I've checkout Wing IDE's license and it doesnt' seem to be a > freesoftware; am I wrong? Wing 101 is free. The software is good enough though that it is worth supporting its development by paying for it. Michael Foord -- http://www.ironpythoninaction.com/ http://www.trypython.org/ From three3q at arcor.de Mon Jul 7 18:59:49 2008 From: three3q at arcor.de (three3q) Date: Tue, 08 Jul 2008 00:59:49 +0200 Subject: sage vs enthought for sci computing In-Reply-To: References: <677e7819-e09e-43d3-8368-5864f91002be@34g2000hsh.googlegroups.com> Message-ID: <48729fe9$0$7550$9b4e6d93@newsspool1.arcor-online.net> Hi, >> If my goal >> is to replace matlab (we do signal processing and stats on >> physiological data, with a lot of visualization), would sage or >> enthought get me going quicker? Pylab. > At the moment I switched totally to Python, Me too, porting scripts was easy. Dan From alexnbryan at gmail.com Thu Jul 17 01:35:29 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 22:35:29 -0700 (PDT) Subject: Need help getting BeautifulSoup contents Message-ID: <18501881.post@talk.nabble.com> The trick to this one is that the html looks something like this:
american, /browse/blue blue , /browse/brick brick , brie, cheddar, cheshire, /browse/churn churn , /browse/cottage cottage , /browse/cream cream , dunlop, and it goes on . I know I can do like a.contents, but it only gives me the first one, in this case being "blue". I want the contents of each of those and the regular contents of the . Can anyone help? -- View this message in context: http://www.nabble.com/Need-help-getting-BeautifulSoup-contents-tp18501881p18501881.html Sent from the Python - python-list mailing list archive at Nabble.com. From fredrik at pythonware.com Mon Jul 21 08:30:44 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 14:30:44 +0200 Subject: Odd math related issue. In-Reply-To: <48847F5D.9080509@sellerengine.com> References: <43332.3139710867$1216630189@news.gmane.org> <48847F5D.9080509@sellerengine.com> Message-ID: Alexandru Palade wrote: > However, you should be carefully because using an %i modifier for a > what-should-be a float value truncates the value in a way you may not > expect. > > What I mean is that if you have sent 2 out of 3 bytes, the math will be > 200/3 which with the %i modifier will print 66, rather than 66.6 (or at > least 67 which is closer - have a look at the round() function). My suggested workaround doesn't use floats. As for rounding, that's more of a usability issue -- seeing the download process getting stuck at 100% can be rather frustrating for the poor user. Better truncate towards zero. > Another thing, you could have just added a dot after the constant in > order to promote the expression to be evaluated as float. As in > percentage = bytes_transferred / /self/.__sessions[path].total_bytes > * 100. > (notice the last dot) Did you try that? >>> 2 / 3 * 100. 0.0 You can fix this with parentheses, but I usually recommend an explicit "cast" instead, to make it obvious what you're doing: result = float(a) / b From duncan.booth at invalid.invalid Sat Jul 19 10:01:59 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Jul 2008 14:01:59 GMT Subject: __del__ methods References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> Message-ID: "Robert Rawlins" wrote: > I've just recently (in the past week) started using the __del__ method > to log class instance destruction so I can keep a track of when > objects are created and destroyed, in order to help me trace and fix > memory leaks. That sounds like an appropriate use for __del__: it won't matter that it may not be called when your app exits. > > Are you saying that on the adverse side to this, __del__ may in fact > be the CAUSE of a memory leak within my application? Yes, but there is an easy work-around. If you want to track destruction of objects of type C then don't add a __del__ method to the C objects. Instead create a separate class which does nothing but track it's own desctruction and reference that from the class which may be leaking. >>> class Track(object): def __init__(self, parent): self.parentid = id(parent) self.parenttype = type(parent).__name__ def __del__(self): print "Destroyed <%s object at %s>" % (self.parenttype, self.parentid) >>> class C(object): def __init__(self): self._track = Track(self) >>> a = C() >>> b = C() >>> a.b = b >>> b.a = a >>> del a >>> del b >>> gc.collect() Destroyed Destroyed 19 > If this is the case and __del__ creates such a vulnerability within > the application, and apparently isn't all that reliable anyway, why is > it still part of the python platform? > Because it does have a very few cases where it is useful. Tracking memory leaks may be one. However you should also consider that __del__ only lets you log when objects are destroyed. Using weak references may be a more useful option as it will let you track which objects are not being destroyed: you can easily keep a dictionary of weak references to all existing objects of interest. Check its length periodically to see whether objects are being leaked and then inspect the objects themselves to see which ones have leaked. You can use gc.get_referrers() to find everything that references a particular objects and gradually trace backwards until you find the problem reference (it is tricky though as any code which does this needs to ignore its own references to the object in question). From fredrik at pythonware.com Thu Jul 24 04:13:27 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 10:13:27 +0200 Subject: parameterized classes In-Reply-To: References: Message-ID: John Tantalo wrote: > Is there is a better way to create parameterized classes than defining > and returning a class in a closure? I ask because I want to create > arbitrary BaseRequestHandler subclasses that delegate line handling to a > given line handler, as in this example: Oh, now I get it. Maybe. Wouldn't it be easier to just use subclassing for parametrization: class LineRequestHandler(StreamRequestHandler): ... self.handle_line(line) ... class SomeLineHandler(LineRequestHandler): def handle_line(self, line): print "I got a line: %s" % line Alternatively, note that the SocketServer framework doesn't require the request handler baseclass to actually be a class; it works with any factory object that takes the same three arguments and returns an handler instance. You can use a plain function closure as a factory, if you prefer that. From ojeeves at gmail.com Thu Jul 31 07:29:45 2008 From: ojeeves at gmail.com (oj) Date: Thu, 31 Jul 2008 04:29:45 -0700 (PDT) Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> Message-ID: <12072cbe-139a-430f-81aa-b64bc31b43e5@e39g2000hsf.googlegroups.com> On Jul 31, 11:37?am, Nikolaus Rath wrote: > So why does Python distinguish between e.g. the type 'int' and the > class 'myclass'? Why can't I say that 'int' is a class and 'myclass' > is a type? I might be wrong here, but I think the point is that there is no distinction. A class (lets call it SomeClass for this example) is an object of type 'type', and an instance of a class is an object of type 'SomeClass'. So int is a type, but if you have an int variable, its type is int. Same for your classes. This is, ignoring old style classes. Make sure all your classes inherit from object to get new style classes. From roy at panix.com Sat Jul 26 21:25:09 2008 From: roy at panix.com (Roy Smith) Date: Sat, 26 Jul 2008 21:25:09 -0400 Subject: Insert string into string References: Message-ID: In article , "Francesco Pietra" wrote: > I am posting ex novo as it became confusing to me. I take the > opportunity to ask advice for a second problem. > > FIRST PROBLEM > For file xxx.pdb, insert letter "A" into each line that starts with > "ATOM". "A" should be inserted at position 22, i.e., one space after > "LEU", leaving all other characters at the same position as in the > original example: > > > ATOM 1 N LEU 1 146.615 40.494 103.776 1.00 73.04 1SG > 2 > > In all lines starting with "ATOM", "LEU" is constant as to position > only (18-20), i.e., "LEU" may be replaced by > three different uppercase letters. Therefore, the most direct > indication would be position 22. If specifying line starting with > "ATOM" makes complication, forget about that as most lines begin with > "ATOM" so that hand correction will be easy. > > Script > f = open("xxx.pdb", "w") > import sys > > for line in sys.stdin: > line = line[:22] + "A" + line[23:] > sys.stdout.write(line) You're opening "xxx.pdb" for writing, but then not writing to it. You're writing to stdout. BTW, you might want to take a look at http://biopython.org. From carsten.haese at gmail.com Tue Jul 1 09:41:28 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Tue, 01 Jul 2008 09:41:28 -0400 Subject: Embedding Python In-Reply-To: References: Message-ID: Marcin Krol wrote: > Hello everyone, > > I'm trying to embed Python interpreter in C code, but in a specific way: > loading compiled bytecode into a memory location and executing it (don't > ask why, complicated reasons). > > PyImport_ExecCodeModule seems like obvious candidate, docs say: > > "Given a module name (possibly of the form package.module) and a code > object read from a Python bytecode file or obtained from the built-in > function compile(), load the module." > [...] > mainobj = PyImport_ExecCodeModule("multiply", (PyObject *) > python_code); > [...] python_code is a C string containing the raw bytes from your pyc file. Casting that to a PyObject pointer will not magically transform it into a Python code object. A pyc file contains the following: 1) An 8 byte header containing a magic number. 2) A "marshal" serialization of the code object. So, in order to transform those contents into a code object, you need to skip the 8 byte header and an unmarshal the rest. Basically, replace the line above with something like this: codeobj = PyMarshal_ReadObjectFromString(python_code+8, size-8); mainobj = PyImport_ExecCodeModule("multiply", codeobj); where codeobj is of type (PyObject *). Once that works, add magic number checking and exception handling to taste. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From circularfunc at gmail.com Sat Jul 12 12:32:12 2008 From: circularfunc at gmail.com (ssecorp) Date: Sat, 12 Jul 2008 09:32:12 -0700 (PDT) Subject: why is "self" used in OO-Python? Message-ID: I first learned about OO from Java. I much prefer to program in Python though. However I am consufed about 2 things. 1. Why do I have to pass self into every method in a class? Since I am always doing why cant this be automated or abstracted away? Are the instances where I won't pass self? I imagine there is some tradeoff involved otherwise it would have been done away with. 2. self.item instead of getters and setters. I thought one of the main purposes of OO was encapsulation. Doesn't messing with internal object- representations break this? I see how the getters and setters could be just visual clutter and you have to add them to every class so it is annoying a bit in the same way as self described above. However I feel like I want getters and setters when I write classes, not sure of the advantages/disadvantages though. Only looking at the documentation of a Python-class, will internal representations be provided? If I have a class: class Stack(object): def __init__(self, *items): self.stack = list(items) def append(self, item): self.stack.append(item) def pop(self): return self.stack.pop() I can get to see the stack with var.stack but then why even implement append when I could do self.stack.append(x) etc. That way you could do away with OO completely. So why let people access the main attribute but not let them manipulate it? Makes more sense to draw the line to not access any attributes at all no? From jordanrastrick at gmail.com Thu Jul 24 11:17:36 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 08:17:36 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <87abg7pe16.fsf@benfinney.id.au> Message-ID: <78446ee7-b035-49a8-ac73-46895391543d@o40g2000prn.googlegroups.com> > > You're not a lunatic. > > We, and Python itself, change quite readily. > > Neither of those mean your ideas in this instance have merit. You're right, these premises don't lead to this conclusion. Neither do they lead to its negation, of course. As it happens, you're wrong on both counts. I do in fact suffer from a mental illness and have spent a week in a psych ward, so am a lunatic by some reasonable definitions. Python readily changes in some regards, but not in others. Of course, a great many things of worth have this as one of their essential qualities. Pithy replies are fun. > Thanks for your opinion. I disagree strongly: I think its influence is > nicely balanced by the other important principles that are also > followed. This isn't just being clever, there's substance here. A clearly stated opposing position, with a decent if somewhat short justification. I think you're right insofar as you go - that if someone really sits down, and thinks clearly about all the Pythonic principles, as a whole, and in detail, then the net result in the shaping their thinking will be positive more often than not. Perhaps we're just looking at an instance of a wider problem - smart people boil good ideas down into short slogans, which are nice and memorable and somewhat helpful, but can lead to bad consequences when lots of others start overusing or misunderstanding them. From bj_666 at gmx.net Tue Jul 1 11:45:23 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Jul 2008 15:45:23 GMT Subject: Error from zipfile References: Message-ID: <6cv1oiF9eaU1@mid.uni-berlin.de> On Tue, 01 Jul 2008 16:38:23 +0100, Wesley Brooks wrote: > Dear Users, > > I'm having a problem when trying to move script from Linux to Windows. > A zipfile opperation is failing with the message: > > "BadZipFile: File is not a zip file" > > I have a simple scripts that reads a zip file in the same way as any > other file into a string, then sends it across to a network where it > is saved as perusual into a file, [?] Are you sure you read and save the file in binary mode, especially on windows!? Ciao, Marc 'BlackJack' Rintsch From amnorvend at gmail.com Fri Jul 18 14:31:20 2008 From: amnorvend at gmail.com (Jason Baker) Date: Fri, 18 Jul 2008 11:31:20 -0700 (PDT) Subject: __del__ methods Message-ID: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> I have a class that I need to do some finalization on when it dies. I know I can use the __del__ method, but I seem to recall that it impedes garbage collection. Is this the case? (keep in mind that my code aims to be compatible with python 2.3 to python 2.5) From motoom at xs4all.nl Tue Jul 15 10:02:11 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Tue, 15 Jul 2008 16:02:11 +0200 Subject: Simplify Code Message-ID: <2.2.32.20080715140211.00d47cb0@pop.xs4all.nl> Victor wrote... ># del is used to determine if should reset the lower header values to '' >del = 0 Apart from many other things that spring to mind, I already see an obvious flaw: 'del' is a keyword, or a 'reserved word' in Python. It is used to remove variables from the namespace. Tip: Use some other name as a variable, eg. 'deletethisone'. Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From deets at nospam.web.de Fri Jul 11 07:59:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 11 Jul 2008 13:59:27 +0200 Subject: MySQLdb will only import for root In-Reply-To: <85d26ae4-757f-494c-bf7e-412323e26b8a@x41g2000hsb.googlegroups.com> References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> <6dothnF3lqqmU1@mid.uni-berlin.de> <85d26ae4-757f-494c-bf7e-412323e26b8a@x41g2000hsb.googlegroups.com> Message-ID: <6dp092F3mhbaU1@mid.uni-berlin.de> Jeff schrieb: > Is it possible the module was installed with priviledges set too > strict? Perhaps the interpreter cannot see the module when it is run > from a normal user account. Possible - certainly. Yet unrealistic, because usually root access is *required* to system-wide install a package - thus the normal install processes ensure proper rights. Diez From kay.schluehr at gmx.net Wed Jul 9 16:53:26 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 9 Jul 2008 13:53:26 -0700 (PDT) Subject: Relative Package Import References: Message-ID: On 8 Jul., 21:09, Peter Otten <__pete... at web.de> wrote: > Robert Hancock wrote: > > mypackage/ > > __init__.py > > push/ > > __init__.py > > dest.py > > feed/ > > __init__py > > subject.py > > > In subject.py I have > > from ..push import dest > > > But i receive the error: > > Caught exception importing module subject: > > File "/usr/local/python/lib/python2.5/site-packages/pychecker/ > > checker.py", line 621, in setupMainCode() > > module = imp.load_module(self.moduleName, file, filename, smt) > > File "subject.py", line 1, in () > > from ..feed import dest > > ValueError: Attempted relative import in non-package > > > What am I missing? > > When you run subject as a file > > pychecker mypackage/feed/subject.py > > subject.py is regarded as a standalone script, not as part of a package. Try > > pychecker mypackage.feed.subject > > instead to invoke the module via the standard import mechanism. > > Peter Since when are Python modules not regarded as standalone scripts but as a "part of a package"? The only indication that there is some duality and that it is relevant at all are those relative imports that came in with Python 2.5. As it seems this feature is justified by the artificial semantic differences it produces. From ericdfirst at gmail.com Thu Jul 24 10:23:33 2008 From: ericdfirst at gmail.com (Eric First) Date: Thu, 24 Jul 2008 09:23:33 -0500 Subject: Wrapping std::set in boost::python Message-ID: <349c44440807240723i56e28823q587e7c0a7e63658d@mail.gmail.com> Has anybody wrapped std::set using boost::python? I'm trying to find the best way to do this. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From animator333 at yahoo.com Wed Jul 16 10:53:13 2008 From: animator333 at yahoo.com (Prashant Saxena) Date: Wed, 16 Jul 2008 07:53:13 -0700 (PDT) Subject: Custom 'Float' class. Am I right here? Message-ID: <552799.63120.qm@web33404.mail.mud.yahoo.com> import sys class Float(float): """ Custom float datatype with addtional attributes. """ def __new__(self, value=0.0, #default value name='', # string range=(0.0, 1.0) # tuple ) try: self.name = name self.range = range self.pos = (1, 1) return float.__new__(self, value) except: print ('Invalid value : Float = %s %s' % (str(value), sys.exc_info()[:2])) def setpos(self, value): self.pos = value def getpos(self): return self.pos*2.0 p = property(getpos, setpos) myFloat = Float(0.23) print myFloat.pos I am trying to create a custom 'float' datatype by subtyping default 'float'. There are few things I would like to know here: 1. How to make 'name' & 'range' only readable attributes. 2. The property 'p' is not working as it has to. What's wrong here? 3. I would be heavily instancing this class, and I won't be creating any new attribute on instance. Is there any way to optimize? __slots__? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From jtanis at mdchs.org Sun Jul 20 17:20:17 2008 From: jtanis at mdchs.org (James Tanis) Date: Sun, 20 Jul 2008 17:20:17 -0400 Subject: Web Server In-Reply-To: Message-ID: "Fredrik Lundh" wrote: > there's also apache, of course, and a bunch of others, including several > Python solutions (more or less pre-packaged). but the "open up" part > still sounds a bit risky. maybe you could turn things around, and let > the application "push" data to your server instead? Either way requires an open port, otherwise there's no way to negotiate new clients. If your in a closed environment that's not a concern, you could just define what clients to push to and when, but it sounds like he wants something a bit more dynamic. -- James Tanis Technical Coordinator Monsignor Donovan Catholic High School e: jtanis at mdchs.org From bj_666 at gmx.net Thu Jul 10 01:07:21 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Jul 2008 05:07:21 GMT Subject: Python and decimal character entities over 128. References: <95e7a2c4-0027-45e6-ace6-f0b414a0fd1c@34g2000hsh.googlegroups.com> Message-ID: <6dljo8F35ua2U2@mid.uni-berlin.de> On Wed, 09 Jul 2008 16:39:24 -0700, bsagert wrote: > Some web feeds use decimal character entities that seem to confuse > Python (or me). I guess they confuse you. Python is fine. > For example, the string "doesn't" may be coded as "doesn’t" which > should produce a right leaning apostrophe. Python hates decimal entities > beyond 128 so it chokes unless you do something like > string.encode('utf-8'). Python doesn't hate nor chokes on these entities. It just refuses to guess which encoding you want, if you try to write *unicode* objects into a file. Files contain byte values not characters. > Even then, what should have been a right-leaning apostrophe ends up as > "???". The following script does just that. Look for the string "The > Canuck iPhone: Apple doesn? ??t care" after running it. Then you didn't tell the application you used to look at the result, that the text is UTF-8 encoded. I guess you are using Windows and the application expects cp1252 encoded text because an UTF-8 encoded apostrophe looks like '???' in cp1252. Choose the encoding you want the result to have and anything is fine. Unless you stumble over a feed using characters which can't be encoded in the encoding of your choice. That's why UTF-8 might have been a good idea. Ciao, Marc 'BlackJack' Rintsch From tjreedy at udel.edu Thu Jul 10 01:49:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jul 2008 01:49:41 -0400 Subject: variable question In-Reply-To: <01da01c8e1fb$7615a4f0$a701a8c0@office.ipglobal.net> References: <01da01c8e1fb$7615a4f0$a701a8c0@office.ipglobal.net> Message-ID: Support Desk wrote: > I am trying to assign a variable using an if / else statement like so: > If condition1: Variable = something > If condition2: Variable = something else > Do stuff with variable. > But the variable assignment doesn?t survive outside the if statement. When things do not work as you expect, post minimal actual code that does not work, what happened, and if not obvious, what you expected different. From rcdailey at gmail.com Wed Jul 30 16:12:19 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 30 Jul 2008 15:12:19 -0500 Subject: Reasoning behind 'self' parameter in classes? In-Reply-To: References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> <4890ACE4.4060703@acm.org> <496954360807301227h1dea050eg735314beb0b5ff16@mail.gmail.com> Message-ID: <496954360807301312vd528870vccec29cf3f2f09d3@mail.gmail.com> On Wed, Jul 30, 2008 at 2:48 PM, Patrick Mullen wrote: > Well, the linked thread gives many reasons, but as mentioned it is a > flamewar thread. Philosophically python is not an "object oriented" > language per say, it has an object system, a not bolted on one I might add, > but it doesn't force developers to use that methodology. You can be > functional or procedural if you'd rather. Following this philosophy, when > methods were designed, they were merely functions that got passed an > instance as the first argument. The parser followed this design choice. As > far as I understand it, the underlying method object is not different from a > function argument, thus it cannot have any magic arguments built in. The > only magic involved is the fact that the object, when calling a method, will > pass its instance as the first argument. > > I don't believe there is any chance of this changing in python 3, python 4 > is anyone's guess... > > This does allow some good things that come for free, like adding methods > later, or changing functions into methods or methods into functions. If you > start out developing a class, but feel a class is too bulky, you can delete > the "class" line, dedent the methods, and have a set of functions instead > for free. Or, if you have functions that are set up to take instances as > their first argument already, you can bundle them up into a class very > easily. > > If by "hack" you mean using features already available in the language to > accomplish things, that kind of is what it is, and that's kind of what > python is about. New syntax for a new feature is uncommon, but it happens. > New syntax that breaks old code is very uncommon, and is only now coming out > in python 3. And the biggest change in python 3 is to eliminate added > syntax, such as print being a statement, and make the code reuse more python > features rather than have every feature exist as an island. Print being a > function, for instance, lets you use the same syntax for it that you use for > other functions, making everything clearer and more unified. A common thing > programmers might do when upgrading their code is to turn print statements > into better logging functions - if print was a function in the first place > this would be an easier task. > > Eliminating self doesn't accomplish much, and changes of this nature just > don't get done without a good reason. It takes away something that might be > annoying, but doesn't add anything. The benefits of changing have to be > significant for a code change to break the existing syntax. Many people are > upset even about some of the changes in python 3, that the benefits don't > outweight the cost of change, and most of those changes are less damaging > than playing around with the self businss would be :) > > So no, self not a mysterious thing that we should never question. Self is > an understood thing that has been questioned very often (weekly, monthly) > for many many years - there are not enough good reasons to bother with > changing it, and there enough good reasons for it that it's best to keep it. > This is quite possibly the best explanation yet. Thank you very much for this. You bring much insight into the feature. You see, a lot of people I've worked with have complained about the 'self' parameter. While this has never bothered me personally, other people find it a "flaw in the language". I often argue with my coworkers that Python is better than Ruby (This is of course opinionated and biased), but sometimes I find I cannot defend python when I need to, and in the argument of 'self' I find that to be one of those situations. Anyway, I appreciate everyone taking the time to explain this to me. I'm sure you guys are at the point of copy/paste of your responses on these topics :) They're far too frequent it seems. In any case, I still appreciate the responses. This topic can die now, I would hate to see it continue and another flame war to start. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexnbryan at gmail.com Wed Jul 2 04:21:58 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 2 Jul 2008 01:21:58 -0700 (PDT) Subject: Problem with a for loop and a list In-Reply-To: References: <18232298.post@talk.nabble.com> Message-ID: <18232528.post@talk.nabble.com> well okay, so what can I do? A.T.Hofkamp-3 wrote: > > On 2008-07-02, Alexnb wrote: >> I have no idea what "list assignment index out of range means?!?! > > You are assigning a value to a non-existing list element, as in > >>>> x = [1] >>>> x[2] = 4 > Traceback (most recent call last): > File "", line 1, in ? > IndexError: list assignment index out of range > > > Albert > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Problem-with-a-for-loop-and-a-list-tp18232298p18232528.html Sent from the Python - python-list mailing list archive at Nabble.com. From bignose+hates-spam at benfinney.id.au Thu Jul 24 10:12:05 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 25 Jul 2008 00:12:05 +1000 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> Message-ID: <87abg7pe16.fsf@benfinney.id.au> Jordan writes: > If the attitude in the community in response to feedback/criticism > has gone from "maybe you've got a point" to "your a lunatic, we'll > never change", well, only Python will suffer in the long term. You're not a lunatic. We, and Python itself, change quite readily. Neither of those mean your ideas in this instance have merit. -- \ ?Pinky, are you pondering what I'm pondering?? ?Well, I think | `\ so, Brain, but do I really need two tongues?? ?_Pinky and The | _o__) Brain_ | Ben Finney From sean_mcilroy at yahoo.com Sun Jul 20 17:27:35 2008 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: Sun, 20 Jul 2008 14:27:35 -0700 (PDT) Subject: examples of pipe usage? Message-ID: <5aab8bb6-0d56-475d-85c2-ced908e29412@x36g2000prg.googlegroups.com> hola i'd like to control another interpreter from idle. i don't have any experience using unix but i think a "pipe" is what i need. am i right about this? can anybody point me to a simple example of using a pipe (if that's the right thing) for this kind of task? thanks if you can help. peace stm From starsareblueandfaraway at gmail.com Thu Jul 17 13:32:13 2008 From: starsareblueandfaraway at gmail.com (Roy H. Han) Date: Thu, 17 Jul 2008 13:32:13 -0400 Subject: property getter with more than 1 argument? In-Reply-To: References: Message-ID: <6a5569ec0807171032n5f0f666evcab326fdf6300683@mail.gmail.com> I don't understand what you're trying to do here. On Thu, Jul 17, 2008 at 10:57 AM, mk wrote: > > It seems like getter is defined in such way that it passes only 'self': > > > class FunDict(dict): > def __init__(self): > self.fundict = dict() > > def fget(self, fun): > return fundict[fun.func_name] > > def fset(self, newfun): > self.fundict[newfun.func_name] = newfun > > newfun = property (fget, fset) > > >>>> a=FunDict() >>>> >>>> a.newfun=f1 >>>> >>>> a.newfun('f1') > > Traceback (most recent call last): > File "", line 1, in > a.newfun('f1') > TypeError: fget() takes exactly 2 arguments (1 given) > > > > Is it possible to pass more than one argument to fget function? > > I know: I can define a function with property name ('newfun' in the example) > and call it with more arguments. But then I do not get the benefits of > setter and property in general! > > -- > http://mail.python.org/mailman/listinfo/python-list > From arsyed at gmail.com Sun Jul 20 17:06:32 2008 From: arsyed at gmail.com (arsyed) Date: Sun, 20 Jul 2008 17:06:32 -0400 Subject: matplotlib: Plotting a graph against time In-Reply-To: <4249053c-d350-445a-977f-04799bb236cb@t54g2000hsg.googlegroups.com> References: <293e05cf-3a50-40e3-961c-926cafe14762@e53g2000hsa.googlegroups.com> <4249053c-d350-445a-977f-04799bb236cb@t54g2000hsg.googlegroups.com> Message-ID: <9a2cc7a70807201406r4e06980am1b4c90db72c317eb@mail.gmail.com> On Sun, Jul 20, 2008 at 9:57 AM, Durand wrote: > Oooh, this is almost what I want but I'm not really sure how I'd > incorporate this into real dates... > If I have a list of dates like ['2008-07-18 14:36:53.494013', > '2008-07-20 14:37:01.508990', '2008-07-28 14:49:26.183256'], how would > I convert it to a format that pylab can understand? When I tried > type(datetime.now()) it gave me datetime.datetime whereas the objects > in this list are strings...Am I doing something wrong here? > -- > http://mail.python.org/mailman/listinfo/python-list > To convert strings to date, you can use datetime.strptime but it doesn't seem to handle fractional seconds. I usually opt for the dateutil module [1]: import dateutil, pylab datestrings = ['2008-07-18 14:36:53.494013','2008-07-20 14:37:01.508990', '2008-07-28 14:49:26.183256'] dates = [dateutil.parser.parse(s) for s in datestrings] pylab.plot_date(pylab.date2num(dates), values, linestyle='-') where values is the list of corresponding y-values. [1] http://labix.org/python-dateutil -------------- next part -------------- An HTML attachment was scrubbed... URL: From mrkafk at gmail.com Tue Jul 1 12:11:02 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Tue, 01 Jul 2008 18:11:02 +0200 Subject: Embedding Python In-Reply-To: References: Message-ID: Hello everyone, In the meantime I managed to work out another solution, mainly thanks to reading the source code of some OSS projects. I post it here so somebody else looking for solution to this problem had the example available: ----cut---- #include #include #include #include #include static FILE *read_module(const char *cpathname, long mtime) { FILE *fp; long magic; long pyc_mtime; fp = fopen (cpathname, "rb"); if (fp == NULL) return NULL; magic = PyMarshal_ReadLongFromFile (fp); if (magic != PyImport_GetMagicNumber()) { fclose(fp); return NULL; } pyc_mtime = PyMarshal_ReadLongFromFile (fp); if (mtime && pyc_mtime != mtime) { fclose(fp); return NULL; } return fp; } int main(int argc, char **argv) { int size; Py_Initialize(); PyCodeObject *mainobj, *pycode; PyObject *result, *mainmodule, *maindict; mainmodule = PyImport_AddModule("__main__"); maindict = PyModule_GetDict(mainmodule); FILE *f = read_module("multiply.pyc", 0L); pycode = (PyCodeObject *) PyMarshal_ReadObjectFromFile(f); printf("pointer: %d\n", pycode); PyEval_EvalCode(pycode, maindict, maindict); Py_Finalize(); } ----cut---- From cwitts at gmail.com Wed Jul 2 10:03:56 2008 From: cwitts at gmail.com (Chris) Date: Wed, 2 Jul 2008 07:03:56 -0700 (PDT) Subject: simple UnZip References: <5b915a0e-a227-460f-8273-ecc01b800884@2g2000hsn.googlegroups.com> Message-ID: On Jul 2, 3:39?pm, noydb wrote: > Can someone help me with this script, which I found posted elsewhere? > I'm trying to figure out what is going on here so that I can alter it > for my needs, but the lack of descriptive names is making it > difficult. ?And, the script doesn't quite do anything worthwhile -- it > unzips one file from a zipfile, not all files in a zipfile. > > *** > import zipfile, os, sys, glob > > os.chdir("C:\\Temp") > zips = glob.glob('*.zip') > > for fzip in zips: > ? ? if zipfile.is_zipfile(fzip): > ? ? ? ? print fzip," is a zip" > ? ? ? ? z = zipfile.ZipFile(fzip,'r') > ? ? ? ? lstName = z.namelist() > ? ? ? ? sHgt = lstName[0] > ? ? ? ? print "Unpacking",sHgt > ? ? ? ? hgt = z.read(sHgt) > ? ? ? ? fHgt = open(sHgt,'wb') > ? ? ? ? fHgt.write(hgt) > ? ? ? ? # fHgt.flush > ? ? ? ? fHgt.close > print "Finished" > *** > > I changed it somewhat to > &&& > import zipfile, os, sys > > event_zip = ("C:\\Temp\\data4event.zip") > > z = zipfile.ZipFile(event_zip, 'r') > > zList = z.namelist() > > for zItem in zList: > ? ? print "Unpacking",zItem > ? ? zRead = z.read(zItem) > ? ? z1File = open(zItem,'wb') > ? ? z1File.write(zRead) > ? ? z1File.close > print "Finished" > &&& > > This works, but I want to be able to specify a different output > location. > > The scenario is that the zip file will always be the same (gets copied > over daily), but it needs to be unzipped to a specific different > directory. > > Can anyone help? > > Thanks! Well, how is the output directory different ? Is it just a timestamp like 'YYYYMMDD' that obviously changes every day or is it named after the file used ? If it is timestamp style you can do import zipfile, os, sys, time folder_name = time.strftime("%Y%m%d", time.localtime(time.time())) event_zip = ("C:\\Temp\\data4event.zip") z = zipfile.ZipFile(event_zip, 'r') zList = z.namelist() for zItem in zList: print "Unpacking",zItem zRead = z.read(zItem) z1File = open(os.path.join(folder_name, zItem),'wb') z1File.write(zRead) z1File.close print "Finished" That will create a folder in your current working directory with the name of todays date and unzip it there. This is just one example route. From grflanagan at gmail.com Thu Jul 31 06:47:30 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Thu, 31 Jul 2008 12:47:30 +0200 Subject: ANN: Google custom search engine for Python In-Reply-To: References: Message-ID: <48919842.1020502@gmail.com> Gerard flanagan wrote: > What is it? > ----------- > > A Google custom search engine which targets only the following sites: > > + `The Hazel Tree `__ > + `The Python standard library docs `__ > + `The Python wiki `__ > + `Python Package Index `__ > > Where can I access it? > ---------------------- > > The home page of the search engine is here: > > http://www.google.com/coop/cse?cx=002031040340806163079:nkigkp_irqk > > As well as accessing it from its home page, you can link to it from your > own web sites, or add it as a gadget to your Google home page (if you > have one) - see the above link for details. > > No ads > ------ > > `The Hazel Tree `__ is a not-for-profit site > and no ads will appear in the search results. > > Using refinements > ----------------- > > To refine the search to any of the individual sites, you can specify a > refinement using the following labels: stdlib, wiki, pypi, thehazeltree > > So, to just search the python wiki, you would do: > > somesearchterm more:wiki > > and similarly: > > somesearchterm more:stdlib > somesearchterm more:pypi > somesearchterm more:thehazeltree > > About http://thehazeltree.org > ----------------------------- > > `The Hazel Tree `__ is a collection of popular > Python texts that I have converted to reStructuredText and put together > using `Sphinx `__. It's in a publishable state, > but not as polished as I'd like, and since I'll be mostly offline for > the next month it will have to remain as it is for the present. However, > the search engine is ready now and the clock is ticking on its > subscription (one year, renewal depending on success of site), so if > it's useful to anyone, it's all yours (and a link back to > http://thehazeltree.org would be appreciated). > > Cheers, > > G. > > -- > http://mail.python.org/mailman/listinfo/python-list > Added http://code.activestate.com/recipes/ (refinement name is `aspn`) G. From tjreedy at udel.edu Mon Jul 7 21:46:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 07 Jul 2008 21:46:48 -0400 Subject: complex representation In-Reply-To: References: Message-ID: DSM wrote: > ISTM the same reasoning applies equally to complex numbers. My interest > arose because of what I think is a bug in pypy's complex printing: > > > Python 2.4.1 (pypy 1.0.0 build 56124) on linux2 > Type "help", "copyright", "credits" or "license" for more information. > ``RPython: we use it so you don't have to'' > >>>> (1.1+1.1j)**200 > (240733537691613523198532543387690598400L+236495565429619338248192Lj) > > > This strangeness comes about because a hack used to recover cpython's > behaviour fails at large values. (x.real == floor(x.real), so it > decides the value's an integer, and returns the repr of int(x.real).) > It's trivial to fix but I think cpython's behaviour is slightly odd > here, and the real and imaginary parts of the complex repr should be > identical to those of the underlying floats. CPython 2.4, 2.5, and 3.0 on WinXP (and hence I presume 2.6) produce (with a trivial variation) >>> (1.1+1.1j)**200 (2.407335376916204e+38+2.3649556542962612e+23j) That Pypy disagrees in the 14th digit is a bit odd, but I suspect a C math library difference. Unless they are actually calculating 40 digits exactly, the extra digits should be filled with 0s if they want integers. Take that, and whatever you think is strange, up with them. From diordna at gmail.com Fri Jul 18 20:52:52 2008 From: diordna at gmail.com (Stephen Johnson) Date: Fri, 18 Jul 2008 20:52:52 -0400 Subject: Any Game Developers here? In-Reply-To: <76b841590807181605r106995d2k98486993a4eaccc4@mail.gmail.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> <4A235BC6-5E46-4402-AF2D-BA3DBC175517@gmail.com> <76b841590807181605r106995d2k98486993a4eaccc4@mail.gmail.com> Message-ID: <9B960401-8D79-44BC-B4A5-4BE2BD1869BC@gmail.com> Yes, I wrote the music, the GUI, and bits of code here and there.. Will Hogben is working on EW 2 for Freeverse right now. But that was in BlitzMax, and I'm in greener pastures now, working on my demo for PyOhio. -Steve Johnson On Jul 18, 2008, at 7:05 PM, Michael Lubker wrote: > I'm interested in general... I know about PyGame and Pyglet, and have > used both. We're currently using Python-Ogre. In the end, I am looking > to find people interested in my project ( see > http://youtube.com/watch?v=E0QQ9JuclxE ), but I also want to find > people experienced with Python in general, not just one library. > (though of course I know that's not too likely) > > Aren't you one of the Escort Wing developers? :) > > Thanks > Michael > > On Fri, Jul 18, 2008 at 5:13 PM, Stephen Johnson > wrote: >> I use the Pyglet library to make games. You want to look at the >> pyglet and >> pygame mailing lists, not this one. Use Google. >> In my opinion, PyGame is clunky and Pyglet is elegant, simple, and >> comprehensive. PyGame has more examples available, but Pyglet has >> great >> documentation and enough examples to answer any questions you might >> have. >> Both have active communities. >> >> -Steve Johnson >> On Jul 18, 2008, at 5:38 PM, Michael Lubker wrote: >> >> Any people that use Python as the predominant language for their game >> development here? >> >> ~Michael >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > > > -- > ~ "The world hates change, yet it is the only thing that has brought > progress." ~ Charles Kettering > > http://snowballz.joey101.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Tue Jul 15 07:42:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2008 13:42:37 +0200 Subject: Logging in __del__() In-Reply-To: <17056.2125546441$1216121658@news.gmane.org> References: <17056.2125546441$1216121658@news.gmane.org> Message-ID: Robert Rawlins wrote: > I then get the following exception thrown when running my code: When the application is running, or when it is shutting down? > Traceback (most recent call last): > File "/usr/lib/python2.5/logging/handlers.py", line 73, in emit > if self.shouldRollover(record): > File "/usr/lib/python2.5/logging/handlers.py", line 147, in shouldRollover > self.stream.seek(0, 2) #due to non-posix-compliant Windows feature > ValueError: I/O operation on closed file > > Does anyone have any ideas as to what I?m doing wrong here? Is this a > known issue which has a neat little work around? Python makes no guarantees that it will tear down your objects before it tears down the library's objects (or the library itself). See e.g. http://www.python.org/doc/essays/cleanup/ (old and probably somewhat outdated, but you get the idea) I'd just put a try/except around it, and ignore any exceptions that may occur. From mensanator at aol.com Wed Jul 16 02:20:58 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 15 Jul 2008 23:20:58 -0700 (PDT) Subject: new itertools functions in Python 2.6 References: <4dd80ff2-5fda-405a-a637-08c985ff8add@e53g2000hsa.googlegroups.com> <498a38d4-10b5-4824-8401-5ebb510fcfa8@y38g2000hsy.googlegroups.com> Message-ID: On Jul 15, 1:44 am, Raymond Hettinger wrote: > On Jul 14, 1:26 pm, Mensanator wrote: > > > ## Combinations with replacement > > ## ----------------------------- > > ## aaa aab aac aad aae abb abc abd abe acc acd ace > > ## add ade aee bbb bbc bbd bbe bcc bcd bce bdd bde > > ## bee ccc ccd cce cdd cde cee ddd dde dee eee > > ## > > ## actual words: 35 (m+n-1)!/(n!(m-1)!) words: 35 > > > Although it works, it's somewhat slow as we have to iterate > > over the entire Cartesian Product and the filter list(x)==sorted(x) > > has got to be expensive (it's slower than the nested loop algorithm). > > > Is there a better way to get Combinations With Replacement > > using itertools? > > There may a technique to start with the combinations without > replacement and then grow the result by repeating elements: Great idea, I had only considered making a sub=set. It never occured to me to try and make a super=set. Thanks for the suggestions, they've given me some ideas to try. > > result = set(combinations('abcde', 3)) > # transform 'ab ac ad ae bc bd be cd ce de' into 'aab abb aac > acc ...' > for c in combinations('abcde', 2): > # transform 'ab' --> 'aab abb' > for i in range(2): > result.add(c[:i] + c[i]*1 + c[i:]) > for c in combinations('abcde', 1): > for i in range(1): > # 'a' --> 'aaa' > result.add(c[:i] + c[i]*2 + c[i:]) > > If you generalize the above, it may solve the problem using itertools > as a starting point. > > Alternatively, it's not too hard to transform the pure python version > given in the docs to one that supports combinations with replacement: I was trying to avoid that kind of solution. ifilter(product()) is exactly the kind of thing I'm looking for, just wondering if there's a better way, using a different combination of functions. > > def combinations_with_replacement(iterable, r): > pool = tuple(iterable) > n = len(pool) > indices = [0] * r > yield tuple(pool[i] for i in indices) > while 1: > for i in reversed(range(r)): > if indices[i] != n - 1: > break > else: > return > indices[i] += 1 > for j in range(i+1, r): > indices[j] = indices[j-1] > yield tuple(pool[i] for i in indices) > > Raymond From fredrik at pythonware.com Mon Jul 21 04:55:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 10:55:56 +0200 Subject: What is the role of python2.6 and C++? In-Reply-To: <74c92ee2-7b89-4579-b25a-a68262e2fee7@a70g2000hsh.googlegroups.com> References: <74c92ee2-7b89-4579-b25a-a68262e2fee7@a70g2000hsh.googlegroups.com> Message-ID: cokofreedom at gmail.com wrote: > 2.6 is meant to be a continuation of the 2.x line of Python, to > support a gradual move of larger projects over to the Python 3.x > series. note that Python also has a tradition of releasing X.6 and (X+1).0 at the same time: http://mail.python.org/pipermail/python-announce-list/2000-September/000513.html http://mail.python.org/pipermail/python-list/2000-September/051263.html From paul at boddie.org.uk Sat Jul 26 14:22:59 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 26 Jul 2008 11:22:59 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> Message-ID: On 26 Jul, 06:06, Terry Reedy wrote: > Paul Boddie wrote: > > "The problem is that the explicit requirement to have self at the > > start of every method is something that should be shipped off to the > > implicit category." Here, I presume that the author meant "at the start of every method signature". > There is no requirement to have 'self' in the parameter list. It can be > 's', 'this', 'me', 'yo'(Spanish for I), or 'cls' (for class methods), or > any other identifier in whatever language. But Jordan apparently wanted to omit that parameter. The omission of all mentions of "self" could be regarded as a bonus, but it's a non- trivial goal. > In 3.0, identifiers are not restricted to ascii but can be any unicode > 'word' as defined in the manual. > > So the proposal would have to be that the compiler scan the function > body and decide which dotted name prefix is the one to be implicitly > added. Have fun writing the discovery algorithm. However, I think this > is pretty silly. Just write the name you want. If, as I wrote, you permit the omission of "self" in method signatures defined within class definitions, then you could still insist on instance attribute qualification using "self" - exactly as one would when writing Java according to certain style guidelines. Paul From circularfunc at yahoo.se Thu Jul 3 10:11:09 2008 From: circularfunc at yahoo.se (defn noob) Date: Thu, 3 Jul 2008 07:11:09 -0700 (PDT) Subject: site-packages, unzipepd there but import fails Message-ID: i unzipped and put the folder in site-packages. when i run setup.py install nothing happens. when i do import pp from shell it complains it doesnt exist. isnt placing the folder in site-packages enough? these setup.py-files often dont work but normally it still works. From george.trojan at noaa.gov Tue Jul 29 13:58:05 2008 From: george.trojan at noaa.gov (George Trojan) Date: Tue, 29 Jul 2008 17:58:05 +0000 Subject: iterating "by twos" In-Reply-To: References: Message-ID: kj wrote: > Is there a special pythonic idiom for iterating over a list (or > tuple) two elements at a time? > > I mean, other than > > for i in range(0, len(a), 2): > frobnicate(a[i], a[i+1]) > > ? > > I think I once saw something like > > for (x, y) in forgotten_expression_using(a): > frobnicate(x, y) > > Or maybe I just dreamt it! :) > > Thanks! I saw the same thing, forgot where though. But I put it in my library. Here it is: # x.py import itertools def pairs(seq): is1 = itertools.islice(iter(seq), 0, None, 2) is2 = itertools.islice(iter(seq), 1, None, 2) return itertools.izip(is1, is2) s = range(9) for x, y in pairs(s): print x, y dilbert at trojan> python x.py 0 1 2 3 4 5 6 7 From toby at tobiah.org Thu Jul 24 14:46:49 2008 From: toby at tobiah.org (Tobiah) Date: Thu, 24 Jul 2008 11:46:49 -0700 Subject: Doubt References: <8c8592be-3bb2-4ee6-9f90-cd374233ba05@w7g2000hsa.googlegroups.com> Message-ID: >> How to convert the perl notation >> $a = ""; expression in Python ? a = "" >> How to represent the loop >> for ($a = $b; $a<=$c;$a++){ >> >> } in Python for a in range(b, c + 1): do_something() ** Posted from http://www.teranews.com ** From wuwei23 at gmail.com Sat Jul 26 23:02:54 2008 From: wuwei23 at gmail.com (alex23) Date: Sat, 26 Jul 2008 20:02:54 -0700 (PDT) Subject: Insert character at a fixed position of lines References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> <7895c8b2-fa01-483c-8ba9-d90975ea688d@o40g2000prn.googlegroups.com> Message-ID: <8b0f4fe2-d8ab-4230-9032-ccd02878d349@v39g2000pro.googlegroups.com> Ugh, and in pointing our your inaccurate code I posted my own: > >>> f = open('dummy.txt','w') > >>> f.write(line = 'this doesn't work') > > File "", line 1 > f.write(line = 'this doesn't work') > ^ > SyntaxError: invalid syntax That should be: >>> f.write(line = "this doesn't work") Traceback (most recent call last): File "", line 1, in TypeError: write() takes no keyword arguments Sorry about that :) From ironfroggy at gmail.com Thu Jul 17 08:34:13 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Thu, 17 Jul 2008 08:34:13 -0400 Subject: Instance In-Reply-To: <120cea3a-33a9-49ec-8932-7cef2e5aef17@25g2000hsx.googlegroups.com> References: <120cea3a-33a9-49ec-8932-7cef2e5aef17@25g2000hsx.googlegroups.com> Message-ID: <76fd5acf0807170534y3aa2a8fft96b1c8a7a7a57f65@mail.gmail.com> On Thu, Jul 17, 2008 at 2:56 AM, karthikbalaguru wrote: > Hi, > > I am new to python. I am trying to use the python files given to me > for bringing up a setup. > I get the following error while trying to use a python file - > AttributeError : Classroom instance has no attribute 'desk_offset' > > How to resolve this ? > Should i need to define desk_offset to zero in the python file ? > > Any ideas .. This means you did something like this: class Foo: def __init__(self): self.bar = 10 f = Foo() print f.quu ... AttributeError : Foo instance has no attribute 'quu' See? You tried to use an attribute that simply doesn't exist. Look in the traceback for where you used the desk_offset attribute, and figure out why you thought the object had such an attribute and why it does not. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From bronger at physik.rwth-aachen.de Thu Jul 24 06:47:36 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 24 Jul 2008 12:47:36 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <32e12408-fc9f-4eb4-8b9d-fb7fa69bd2fc@f36g2000hsa.googlegroups.com> Message-ID: <87zlo7y2wn.fsf@physik.rwth-aachen.de> Hall?chen! Kay Schluehr writes: > On 24 Jul., 11:40, Torsten Bronger > wrote: >> >> Bruno Desthuilliers writes: >> >>> [...] >>> >>> How would you handle this case with an implicit 'self' : >>> >>> class Foo(object): >>> pass >>> >>> def bar(self): >>> print self >>> >>> Foo.bar = bar >> >> Just like this. However, the compiler could add "self" to >> non-decorated methods which are defined within "class". > > And $self2, $self3, ... to the object methods of nested classes > and $cls2, $cls3, ... to the classmethods of those classes...? One could surely find ways to realise this. However, the design goal should be: Make the frequent case simple, and the rare case possible. (Actually, I'm -0 on this anyway because I forget "self" very seldomly, and you would still have ".self" all over the place.) Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From clay at lakeserv.net Sun Jul 13 09:22:01 2008 From: clay at lakeserv.net (Clay Hobbs) Date: Sun, 13 Jul 2008 09:22:01 -0400 Subject: Problems with curses Message-ID: <1215955321.19541.3.camel@generator> > On Sat, 12 Jul 2008 20:49:56 -0400, Clay Hobbs wrote: > > > Unfortunately, the error message isn't very helpful. > > But it would be helpful to tell it. If you get exceptions, always > copy'n'paste the traceback here. People might know what the exception > means and share their wisdom. Here is the error message: Traceback (most recent call last): File "./text_adventure.py", line 25, in curses.wrapper(main) File "/usr/lib/python2.5/curses/wrapper.py", line 44, in wrapper return func(stdscr, *args, **kwds) File "./text_adventure.py", line 19, in main stdscr.scroll(3) _curses.error: scroll() returned ERR -- Ratfink From tjreedy at udel.edu Sun Jul 13 14:00:32 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 13 Jul 2008 14:00:32 -0400 Subject: Functional/Best? In-Reply-To: <1215956345.3028.10.camel@localhost.localdomain> References: <1215956345.3028.10.camel@localhost.localdomain> Message-ID: Tim Cook wrote: > I guess I can classify my application(s) as more procedural than > anything else. But I have a question about the best way to handle > something in Python. > > When given a mapping of keywords, I want to call a function based on a > certain keyword found when parsing a text file. The mapping looks like > this: > > definClassMap={'SECTION':'bldSection','COMPOSITION':'bldComposition','OBSERVATION':'bldObservation','ITEM_TREE':'bldItemTree'} > > So if the text file contains 'ITEM_TREE' I want to call bldItemTree > which creates an instance of the class ItemTree. > > I currently use an if ..., elif ... construct. > Is there a better, more efficient, more Pythonic way of doing this? Yes. Create a mapping of keywords to function objects rather than to function names! def bldSection(): ... def bldItemTree(): class_map={ 'SECTION':bldSection, 'COMPOSITION':bldComposition, 'OBSERVATION':bldObservation, 'ITEM_TREE':bldItemTree, # trailing comma allows easy additions } for word in parselist: try; class_map[word]() except KeyError: tjr From coolman.guron at gmail.com Thu Jul 31 11:40:03 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Thu, 31 Jul 2008 08:40:03 -0700 (PDT) Subject: Newbie Python questions References: <12p2941fee0nnimqmraqt9cm1vml7ra2kt@4ax.com> Message-ID: <706f52bb-c206-4021-9a2f-2e52f6e3429b@u6g2000prc.googlegroups.com> One great open source GUI package that you left out is GTK ie. pygtk. i cant compare it with wx as i have never used it but isay its much better than QT. Anyway for ur q if u want to compair qt n wx. QT should be faster coz it has a better documentation. and welcome to the python family! kind regards binaryjesus On Jul 31, 12:10 pm, Tim Roberts wrote: > LessPaul wrote: > > >...My > >question is in regard to GUI platforms. My primary target would be > >Windows, but I would also like be able to support Linux and Mac > >versions if possible. I'm also interested in using a system that also > >has support for pure C++ applications. As such, and after reading many > >web pages regarding Python GUIs, I believe I have the candidates > >narrowed down to pyQT and wxPython. > > >The first question -- how steep is the curve to become proficient with > >the above GUI packages? > > There is so much personal preference here that it is extremely hard to give > any guidance. If you have done any Windows programming at all, so that you > are familiar with the event-driven programming model, then I don't think > you would see that much difference in learning curve. The two packages are > more alike than they are different -- the various APIs are just spelled > differently. > > I happen to be a big wxPython fan. I learn best by example, and wxPython > has a 44,000-line demo suite with 167 source files that demonstrates > virtually every class it includes. > > >Since there appears to be no commercial licencing fee for wxWidgets/ > >wxPython, the last question is what do I gain from going QT over wx? > >I've seen great applications written with both (on my computer I have > >the wxPython Digsby and the pyQT apps "Mnemosyne" and "Anki". All seem > >to be solid. > > Yep. Personal preference. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. From circularfunc at yahoo.se Tue Jul 15 12:26:55 2008 From: circularfunc at yahoo.se (defn noob) Date: Tue, 15 Jul 2008 09:26:55 -0700 (PDT) Subject: isPrime works but UnBoundLocalError when mapping on list Message-ID: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> isPrime works when just calling a nbr but not when iterating on a list, why? adding x=1 makes it work though but why do I have to add it? Is there a cleaner way to do it? def isPrime(nbr): for x in range(2, nbr + 1): if nbr % x == 0: break if x == nbr: return True else: return False >>> [isPrime(y) for y in range(11)] Traceback (most recent call last): File "", line 1, in [isPrime(y) for y in range(11)] File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime if x == nbr: UnboundLocalError: local variable 'x' referenced before assignment >>> map(isPrime, range(100)) Traceback (most recent call last): File "", line 1, in map(isPrime, range(100)) File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime if x == nbr: UnboundLocalError: local variable 'x' referenced before assignment >>> isPrime(10) False >>> isPrime(11) True adding x=1 makes it work though: def isPrime(nbr): x=1 for x in range(2, nbr + 1): if nbr % x == 0: break if x == nbr: return True else: return False >>> [isPrime(y) for y in range(11)] [False, True, True, True, False, True, False, True, False, False, False] From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 2 04:47:02 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Jul 2008 10:47:02 +0200 Subject: Mako vs. Cheetah? In-Reply-To: References: <4862f57c$0$11621$607ed4bc@cv.net> <4863bf9c$0$14081$c3e8da3@news.astraweb.com> Message-ID: <486b4081$0$13874$426a74cc@news.free.fr> Maric Michaud a ?crit : > Le Saturday 28 June 2008 06:30:50 Tim Roberts, vous avez ?crit : >> Others really like the TAL scheme in Zope. >> For my taste, TAL just requires too much non-essential syntax; it >> interferes with the reading of the page. >> >> So, the folks who like TAL can go ahead and be productive with TAL, and >> I'll keep on being productive with Cheetah. > > Yes, TAL is a bit more hard and require some added learning, but tal templates > are very powerful and well structured, and they have a real advantage over > all other templating system, they are valid xhtml, So are Kid and Genshi, and they are way less verbose than TAL. And FWIW making Django's templating system xhtml compliant mostly requires redefining a couple constants to replace {% %} with and {{ }} with ${ }. From __peter__ at web.de Wed Jul 2 07:45:41 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Jul 2008 13:45:41 +0200 Subject: How to pickle bound methods References: Message-ID: srinivasan srinivas wrote: (Please don't top-post) > It works will for instance and class methods. But it doesn't work for > static methods. Can you tel me how to pickle static methods as well?? For static methods pickling is not so easy because these don't carry information about the class they belong to. What are you trying to do? Peter From duane.kaufman at gmail.com Mon Jul 21 11:51:04 2008 From: duane.kaufman at gmail.com (TheSeeker) Date: Mon, 21 Jul 2008 08:51:04 -0700 (PDT) Subject: how to create GUI dynamically References: <84f144db-0d6c-44d5-a1ef-6e7778304c2a@r66g2000hsg.googlegroups.com> Message-ID: On Jul 21, 8:19 am, hitechpun... at gmail.com wrote: > Hi; > > i m working on a project where i need run time creation of GUI. > > i have some no. of entities for which i want checkboxes in front of > them which can be checked/ unchecked by user. > > But the problem is that the number and name of entities is not fixed > and it depends on the file which is used as input. > > So is there any way to tackle this problem. > > By the way ; i use Boa constructor (zope editor) for GUI now. > > regards > pawan pundir Hi, Boa constructor can be used for the main part of the application, but you'll probably need to 'roll your own' builder of the dynamic portion (which isn't very hard). A wonderful list for these kinds of questions is: https://lists.sourceforge.net/lists/listinfo/boa-constructor-users Duane From gcmartijn at gmail.com Mon Jul 7 13:27:43 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Mon, 7 Jul 2008 10:27:43 -0700 (PDT) Subject: pythoncom InternetExplorer.Application don't work in vista || firefox pythoncom ? References: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> <486fe5cc$0$926$ba4acef3@news.orange.fr> <29c70427-07f2-43ae-b742-86af4431edd8@34g2000hsh.googlegroups.com> <48714f2f$0$897$ba4acef3@news.orange.fr> Message-ID: On 6 jul, 16:00, "M?ta-MCI \(MVP\)" wrote: > Hmmmm... ?I have a similary problem, in another circumstances. > It's often a problem of configuration of IE (for news customers). ?But, > it is not easy, because IE has many parameters. > > Good luck! > > Michel Claveau IE have many options, you say that the code is working so I was hoping that you could answer these questions: - Is your tabbed browsing on ? - Do you use the default 'securiy' settings ? - Do you use by privacy option: Medium ? - The advanced options are to much to ask here :( Greetings, GCMartijn From norseman at hughes.net Thu Jul 3 20:16:33 2008 From: norseman at hughes.net (norseman) Date: Thu, 03 Jul 2008 17:16:33 -0700 Subject: How to bypass Windows 'cooking' the I/O? (One more time, please) Message-ID: <486D6BE1.3000501@hughes.net> I know I saw the answer recently, as in since February '08, but I can't re-find it. :( I tried the mail archives and such and my own collections but the piece I saw still eludes me. Problem: (sos=same old s...) Microsoft insists the world work it's way even when the Microsoft way was proven wrong decades ago. In this case it's (still) 'cooking' the writes even with 'rwb' and O_RDWR|O_BINARY in (proper respective) use. Specific: python created and inspected binary file ends: 00460: 0D 1A (this is correct) after a write os.lseek(target, -1, 2) os.write(target,record) the expected result would be: 00460: 0D 20 .....data bytes.... 1A BUT I get: 00460: 20 .... data bytes... 1A It is one byte off!!! And the 0D has to be there. Signifies the end of the header. Same python program runs as expected in Linux. Maybe because that's where it was written?! :) What I seek is the way to slap Microsoft up side the head and make it work correctly. OK, well, at least in this situation. Note: Things like this justify Python implementers bypassing OS calls (data fetch, data write) and using the BIOS direct. Remember, the CPU understands bit patterns only. It has no comprehension of 'text', 'program', 'number', 'pointer', blah blah blah.... All that is totally beyond it's understanding. A given bit pattern means 'do that'. The CPU is 100% binary. Memory, storage and the rest is just bits-on, bits-off. Patterns. Proper binary I/O is mandatory for the machine to function. Anyway - if whoever mentioned the flags and such to 'over ride' Microsoft's BS would re-send that piece I would be very appreciative. Steve norseman at hughes.net From motoom at xs4all.nl Tue Jul 15 10:42:31 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Tue, 15 Jul 2008 16:42:31 +0200 Subject: Is it legal to rebuild Python.exe to include Version property tab? Message-ID: <2.2.32.20080715144231.012aacdc@pop.xs4all.nl> Ward wrote... > Can we rebuild Python.exe to include the various "version" > information? Why rebuild it? You can use a resource editor tool to add/edit/delete the VERSIONINFO from any Windows executable, including Python.exe ;-) Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From circularfunc at gmail.com Sun Jul 6 14:45:54 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 6 Jul 2008 11:45:54 -0700 (PDT) Subject: how are strings immutable in python? Message-ID: >>> h = "aja baja" >>> h += 'e' >>> h 'aja bajae' >>> From afriere at yahoo.co.uk Tue Jul 22 21:39:22 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 22 Jul 2008 18:39:22 -0700 (PDT) Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: <76e68c88-a720-464b-96f4-95e744468bd7@k37g2000hsf.googlegroups.com> On Jul 23, 7:02 am, ptn wrote: > Hi everybody, > > I have a weird problem. Say I have a .py file with some functions in > it, like this: > > # (...) > def foo(): > print("bar") > > When I open it and add a line to one of the functions, > > # (...) > def foo(): > troz = "bar" > print(troz) > > I get the following traceback from the interpreter: > > Traceback (most recent call last): > File "SOMEWHERE/example.py", line ?? > troz = "bar" > ^ > IndentationError: unindent does not match any outer indentation > level > > And so I'm forced to rewrite the function entirely just to add the new > line. > > I thought that my problem was the w option from formatoptions, so I > changed my .vimrc file to this: > > augroup filetype > autocmd BufNewFile,BufRead *.txt set filetype=human > augroup END > autocmd FileType human setlocal formatoptions+=ta2w > autocmd FileType lisp,scheme,python,c,java,vim setlocal > formatoptions-=ta2w > > But the problem didn't go away. It doesn't look like those formatoptions would be called when the filetype is python. Or am I missing something? > I don't think this has anything to do > with the tabs and spaces, because I have them set up like this: > > set tabstop=4 shiftwidth=4 expandtab > > which is the standard way to handle them. Did you actually search for tabs (/\t)? If the file was orginally edited without expandtabs and later expandtabs was used this is exactly the sort of problem you would encounter. Also you don't need to set tabstop if you in- and de-dented using [ctrl]-[t] and [ctrl]-[d] in insert mode, and '>>' and '<<' in command mode. > > The scripts I load are: qbuf, TagList, indent/python.vim and a reduced > version of the standard python.vim > > Could someone provide some pointers? > > Thanks, > > Pablo Torres N. From gnewsg at gmail.com Thu Jul 31 16:39:22 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 31 Jul 2008 13:39:22 -0700 (PDT) Subject: Questions about asyncore References: <5d30aad5-cad7-4e47-aa83-277202c70ae2@z72g2000hsb.googlegroups.com> <6db7042c-02bb-42ef-b578-3811d8f427f5@m36g2000hse.googlegroups.com> <4903018c-feac-40fb-81fc-002dfc430f84@z66g2000hsc.googlegroups.com> <85bd837a-62e3-455d-8bec-3d778231bfc5@i76g2000hsf.googlegroups.com> Message-ID: On 31 Lug, 08:30, Frank Millman wrote: > On Jul 30, 7:50 pm, "Giampaolo Rodola'" wrote: > > > On 30 Lug, 09:49, Frank Millman wrote: > > Thanks again, Giampaolo, your input is really appreciated. > > > > > I pretty much have the same overview I had before. > > As far as I can tell the only reason you want to use a thread is when > > you have to do something which requires a consistent amount of time to > > complete so that the asyncore loop gets blocked. > > The question is: is there anything like that in your code? > > If the answer is no then you don't need to use threads. > > Maybe you are just not used to the asynchronous approach where "wait > > for server to respond" or "wait for the response to be complete" > > doesn't mean that YOU have to wait. > > It means that when a specific condition occurs (e.g. some data is > > received) a certain method of the framework you're using will be > > called and then it will be up to you deciding what do to. > > Maybe I am not being clear enough on my side. > > I (hope I) understand the power of asnyc. I have written the server to > use async techniques, and when I get around to writing the full-blown > client, that will also use async techniques. > > However, at this stage, all I want to do is write something quick and > dirty to check that the server is behaving as intended. I want to > throw some messages at it, more or less at random, and check the > responses. I found it much easier to do this with asyncore.loop > running in a separate thread. I don't know why you find more convenient running asyncore.loop in a separate thread but if your purpose is writing a test suite in which a client checks responses sent by server I *would not* recommend using asyncore. The common way to do that is starting the server into setUp() method and shut it down in tearDown(). Every test consists in a client which uses the socket module to connect() to the server, send() something and recv() the response. That's all. pyftpdlib, which consists of an asyncore-based FTP server, has a test suite behaving exactly like that. Try to take a look and see if it could fit your purposes: http://code.google.com/p/pyftpdlib/source/browse/tags/release-0.4.0/test/test_ftpd.py > To send a message from the main thread, I append it to a list called > self.sendData. In asyncore.dispatcher, writable() returns True if the > list contains anything, and handle_write() pops the message off the > list and sends it. > > To receive messages, readable() always return True, and handle_read() > breaks up the input into individual messages and appends them to a > list called self.recvData. When the main thread is waiting for a > response, it simply loops until self.recvData contains something. > > To do this asynchronously, for every test I would have to define the > detailed interaction between client and server, and write methods to > be called from within handle_read(). It could be done, but it would be > much more tedious. > > Does this make sense? Now I see why you find it more tedious, in fact I wouldn't use that kind of approach in the test suite. Anyway, I still don't understand why running asyncore.loop into a thread could make any difference. --- Giampaolo http://code.google.com/p/pyftpdlib/ From bignose+hates-spam at benfinney.id.au Sat Jul 26 00:07:52 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 26 Jul 2008 14:07:52 +1000 Subject: binding names doesn't affect the bound objects (was: print doesn't respect file inheritance?) References: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> Message-ID: <8763qtmgo7.fsf@benfinney.id.au> bukzor writes: > I was trying to change the behaviour of print (tee all output to a > temp file) by inheriting from file and overwriting sys.stdout That's not what your code does, though. > def main(): > n = notafile('/dev/stdout', "w") Creates a new instance of the 'notafile' class; the '=' operator then binds that instance to the name 'n'. > import sys Imports a module, and binds the module to the name 'sys'. This includes, usually, the module attribute named by 'sys.stdout'. > sys.stdout = n Re-binds the name 'sys.stdout' to the object already referenced by the name 'n'. No objects are changed by this; only bindings of names to objects. > print "Testing: 1, 2, 3..." Doesn't rely at all on the name 'sys.stdout', so isn't affected by all the binding of names above. In other words, you can't change the object used by the 'print' statement only by re-binding names (which is *all* that is done by the '=' operator). You can, however, specify which file 'print' should use . -- \ ?When I wake up in the morning, I just can't get started until | `\ I've had that first, piping hot pot of coffee. Oh, I've tried | _o__) other enemas...? ?Emo Philips | Ben Finney From iainking at gmail.com Wed Jul 2 10:54:50 2008 From: iainking at gmail.com (Iain King) Date: Wed, 2 Jul 2008 07:54:50 -0700 (PDT) Subject: Win32.client, DAO.DBEngine and exceeding the file sharing count lock References: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> Message-ID: <9ab0cc2d-5a7e-40ca-a4da-084347f147cd@m36g2000hse.googlegroups.com> On Jul 2, 3:29?pm, Tim Golden wrote: > Iain King wrote: > > Hi. ?I'm using the win32 module to access an Access database, but I'm > > running into the File Sharing lock count as inhttp://support.microsoft.com/kb/815281 > > The solution I'd like to use is the one where you can temporarily > > override the setting using (if we were in VB): > > > DAO.DBEngine.SetOption dbmaxlocksperfile,15000 > > Really hurried answer: > > > import win32com.client > > dao = win32com.client.gencache.EnsureDispatch ("DAO.DBEngine.36") > dao.SetOption (Option=win32com.client.constants.dbMaxLocksPerFile, Value=15000) > > > TJG Thanks. I found this: http://blogs.msdn.com/michkap/archive/2007/07/13/3849288.aspx which outlines some difference between DAO and ADO, including: "Capability to set and change Jet options without making registry changes (works in DAO through DBEngine.GetOption and DBEngine.SetOption, fails in ADO, which has no such analogue)." Now, I'm pretty sure I tried to use DAO before and failed to get it to work, but maybe you could look at my code and suggest the DAO equivalent? --- self._connection = win32com.client.Dispatch(r'ADODB.Connection') self._DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE='+dbfile+';' self._connection.Open(self._DSN) rs = win32com.client.Dispatch(r'ADODB.Recordset') query = 'SELECT '+field+' FROM '+self.__TABLE rs.Open(query, self._connection, 1, 3) while not rs.EOF: v = function(rs.Fields.Item(0).Value) if v != RETAIN_VALUE: rs.Fields.Item(0).Value = v rs.MoveNext() rs.Close() --- aTdHvAaNnKcSe, Iain From Samnsparky at gmail.com Thu Jul 10 12:08:03 2008 From: Samnsparky at gmail.com (Sparky) Date: Thu, 10 Jul 2008 09:08:03 -0700 (PDT) Subject: Local User Control References: Message-ID: On Jul 10, 9:58?am, Tim Golden wrote: > Sparky wrote: > > I don't know how feasible this is, but is it possible to have users > > log in to access a local database file in such a way that allows the > > program to know what user name and password they logged in with? This > > would involve separate user names and passwords for each user. > > Well, this is a question which is crying out for some > context. Are you talking about an existing database > on an existing platform? If so, which one? Are you > talking about a database youo're thinking of building? > If so, the answer's probably yes but only you can > know. Are you talking about something else altogether? > > TJG Thanks for the timely response. This would be a database that I am building myself. The question comes down to is there a feasible way to verify a user's user name and password from inside that database. Obviously the file would be encrypted, but if there is going to be more than one user using it I suppose there would be a separate file for a log-in. I am just asking for some guidance on how this would theoretically be implemented. Thanks again, Sam From rw at smsnet.pl Tue Jul 15 15:34:22 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Tue, 15 Jul 2008 21:34:22 +0200 Subject: logging via SocketHandler and TCPserver References: <81929250-449b-4686-acf3-dcc0095e341a@d1g2000hsg.googlegroups.com> Message-ID: <87tzerndq9.fsf@merkury.smsnet.pl> Larry Bates writes: > Can multiple applications send SocketHandler logging records to the > same socket server on the same port simultaneously? Of course they can. Server can accept requests from many clients. You have used `SocketServer.ThreadingTCPServer`. That server for example handles every request in a different thread. > If so, then I understand your answer completely and will go > in that direction. I guess I was trying to not use up > bandwidth/CPU cycles on the applications that weren't being actively > monitored by just not having the socket server connected to them. > > I think you may be a 'little to close' to the (excellent) application > you have written to understand the steep learning curve that I see. > You know the saying, "Brain surgery is easy to a brain surgeon". I > should point out that I'm no newbie. I've used PIL, ReportLab, > BeautifulSoup, Mechanize, Win32 extensions, ElementTree and a whole > host of other modules with less difficulty. Please don't take this as > anything more than an observation on my part. From what I see, you > have written (and generously donated) an extremely powerful library > and it is greatly appreciated. It is most likely just me. Well, I know what you mean. I had troubles to understand that library either. Logging docs are quite good as a reference, but there is lack of a good introductory tutorial. Now when I know `logging` I can't live without it, but the start wasn't easy. I shouldn't say it here, but I found helpful docs to the similar library in Java. ;) http://logging.apache.org/log4j/1.2/manual.html There are many differences (e.g. Appenders vs Handlers), but the rule is the same. > As far as the book is concerned, I guess I'd purchase the only copy ;-). "The Art of Logging" - four volumes. ;-) Regards, Rob From bignose+hates-spam at benfinney.id.au Thu Jul 10 19:38:48 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 11 Jul 2008 09:38:48 +1000 Subject: Loading just in time References: Message-ID: <87zlops41j.fsf@benfinney.id.au> "D'Arcy J.M. Cain" writes: > Performance optimization wasn't really my goal here. What I was > looking for was the ability to spread the functions around different > files to manage them better from a proggrammer's POV. Why not do that, then? Your functions should be organised into conceptually sensible module groupings. -- \ ?My doctor told me to stop having intimate dinners for four. | `\ Unless there are three other people.? ?Orson Welles | _o__) | Ben Finney From bdesth.quelquechose at free.quelquepart.fr Mon Jul 28 18:58:09 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 29 Jul 2008 00:58:09 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <488D5B2C.10808@gmail.com> Message-ID: <488e6af8$0$20692$426a74cc@news.free.fr> Nikolaus Rath a ?crit : > Michael Torrie writes: (snip) >> In short, unlike what most of the implicit self advocates are >> saying, it's not just a simple change to the python parser to do >> this. It would require a change in the interpreter itself and how it >> deals with classes. > > > Thats true. But out of curiosity: why is changing the interpreter such > a bad thing? (If we suppose for now that the change itself is a good > idea). Because it would very seriously break a *lot* of code ? From bruno.desthuilliers at gmail.com Thu Jul 17 08:13:23 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 17 Jul 2008 05:13:23 -0700 (PDT) Subject: How can i use a variable without define it ? References: <87k5fm2p1x.fsf@benfinney.id.au> <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> Message-ID: <67dda03d-0d90-47ee-920b-2706a4779f15@x41g2000hsb.googlegroups.com> On 16 juil, 11:06, zhw wrote: > On 7?16?, ??4?47?, Ben Finney > wrote: > > > > > zhw writes: > > > How can i use a variable without define it ? > > > What do you mean by "use"? That's so vague I can think of many > > possible interpretations. > > > What do you mean by "variable"? That term carries a lot of baggage > > that doesn't apply in Python. > > > Can you give a small, complete example that demonstrates the issue > > you're trying to solve? > > > -- > > \ ?The face of a child can say it all, especially the mouth part | > > `\ of the face.? ?Jack Handey | > > _o__) | > > Ben Finney > > Thank you! Sorry for my poor english! > > Here is a example that I want to complete:>>> import sys, new > >>> context={"name":"david", "sex":"male"} > >>> sys.modules["foo"] = new.module("foo") > >>> import foo > >>> for attr in context: > > setattr(foo, attr, context[attr]) > > >>> def bar(): > > # here is a error > # import * only allowed at module level > from foo import * > print name, sex > > >>> bar() Looks like a major WTF to me. What's wrong with: class Person(object): def __init__(self, name, sex): self.name = name self.sex = sex def bar(self): print self.name, self.sex p = Person("david", "male") p.bar() From patf at well.com Mon Jul 28 18:00:42 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 15:00:42 -0700 (PDT) Subject: Download excel file from web? Message-ID: Hi - experienced programmer but this is my first Python program. This URL will retrieve an excel spreadsheet containing (that day's) msci stock index returns. http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul+25%2C+2008&export=Excel_IEIPerfRegional Want to write python to download and save the file. So far I've arrived at this: [quote] # import pdb import urllib2 from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") # test 1 # xlApp.Workbooks.Add() # xlApp.ActiveSheet.Cells(1,1).Value = 'A' # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' # xlBook = xlApp.ActiveWorkbook # xlBook.SaveAs(Filename='C:\\test.xls') # pdb.set_trace() response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ excel? priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul +25%2C+2008&export=Excel_IEIPerfRegional') # test 2 - returns check = False check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ indexperf/excel? priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul +25%2C+2008&export=Excel_IEIPerfRegional').has_data() xlApp = response.fp print(response.fp.name) print(xlApp.name) xlApp.write xlApp.Close [/quote] From alokkat at gmail.com Tue Jul 8 21:07:06 2008 From: alokkat at gmail.com (Alok Kumar) Date: Tue, 8 Jul 2008 21:07:06 -0400 Subject: Python HTTPS Bus Error Message-ID: Hi, Can someone help me what to look for fixing Bus error. I must mention that I am working in embedded environment and it does have selective installation of python I am getting following error from client when it is trying to talk with server over *HTTPS*. HTTP works fine. *Alignment trap: python2.5 (1030) PC=0x4058a738 Instr=0xe5902004 Address=0x000001* *35 FSR 0x001* *Bus error* Server throws SSL handshake failure error. It will be great if someone can throw any pointers. Regards Alok -------------- next part -------------- An HTML attachment was scrubbed... URL: From gary at byoteki.com Mon Jul 28 20:59:26 2008 From: gary at byoteki.com (Gary Josack) Date: Mon, 28 Jul 2008 20:59:26 -0400 Subject: python lists and newline character In-Reply-To: <488E05EA.80800@islandtraining.com> References: <053101c8f0d7$ebd7c340$a601a8c0@office.ipglobal.net> <488E05EA.80800@islandtraining.com> Message-ID: <488E6B6E.2060505@byoteki.com> Gary Herron wrote: > Support Desk wrote: >> >> Hello all, >> >> I am using os.popen to get a list returned of vpopmail >> users, something like this >> >> >> >> x = os.popen('/home/vpopmail/bin/vuserinfo -n -D >> mydomain.com).readlines() >> >> >> >> x returns a list, of usernames, and I am trying to append the >> usernames with the domain like so >> >> >> >> for line in x: >> >> print line + ?@? + domain >> >> >> >> but instead of getting >> >> >> >> user at domain.com >> >> >> >> im getting a newline character like: >> >> user >> >> @domain.com >> >> User >> >> @comain.com >> >> User2 >> >> @domain.com >> >> >> >> >> >> Is there some way I can get this list without the newline characters >> being added. or somehow remove the newline characters. Any help would >> be appreciated. >> > > The problem has nothing to do with lists. The readlines() function > returns each line *with* its newline. To strip it off, use line.strip() > > Gary Herron > >> ------------------------------------------------------------------------ >> >> -- >> http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list Also os.popen is deprecated. You should probably learn subprocess. Thanks, Gary M. Josack From tjreedy at udel.edu Sun Jul 27 17:26:24 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 17:26:24 -0400 Subject: Rant (was Re: x*x if x>10 In-Reply-To: References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3qjoF9n3cpU1@mid.uni-berlin.de> Message-ID: DaveM wrote: > On Sun, 27 Jul 2008 19:46:32 +0200, "Diez B. Roggisch" > wrote: >> As a rule of thumb, don't return objects you didn't create inside a >> function from scratch. Unless its job is specifically to get/fetch an object (reference thereto) from someplace the caller cannot or should not access. But then it should probably not mutate the object before returning the reference. > > I wish I'd had that advice when I started learning python. It would have > saved me no end of grief. I wish I had seen this 'rule' before too. From robert.kern at gmail.com Wed Jul 23 21:18:32 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 23 Jul 2008 20:18:32 -0500 Subject: fill in 3D array In-Reply-To: <3180f972-f2d4-43ff-81de-bcdd0a2ef906@59g2000hsb.googlegroups.com> References: <3180f972-f2d4-43ff-81de-bcdd0a2ef906@59g2000hsb.googlegroups.com> Message-ID: knielsen73 at gmail.com wrote: > Hi, > > I am a python newbie, trying to convert my IDL scripts to python. I am > kind of stuck at the moment. I am reading in a 1-D data file with 2000 > data points. I need to put them in a 3-D array with size [10,10,20]. I > have defined the field array as arr = zeros((10,10,20)) but don't know > how to read the data into the array. I assume that you are using numpy. Use numpy.fromfile() and the .reshape() method. Assuming that your file is ASCII with numbers separated by whitespace: import numpy arr = numpy.fromfile(thefilename, sep=' ').reshape((10,10,20)) There is no need, in this case, to create an array before reading the data. > Also, I need to extract a slice of a 3-D array and tried a = > array_name(:,:,20) but that didn't work. Python uses [] brackets for indexing, not (). arr[:,:,20] -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ki4yjl at gmail.com Fri Jul 11 12:59:03 2008 From: ki4yjl at gmail.com (WDC) Date: Fri, 11 Jul 2008 09:59:03 -0700 (PDT) Subject: Using the Random Module. Message-ID: I am currently learning, and loving, Python and have a question about random(). Right now, what I have to do to get a whole number and not a decimal using random.random() is this: >>>random.random() 0.84765728501856734 >>>_ * 10**17 84765728501856734.0 Is there a better way to do that besides doing this: >>>random.randint(00000000000000000, 99999999999999999) 09657398671238769 Thanks for your time. David From alif016 at gmail.com Fri Jul 18 22:04:36 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Fri, 18 Jul 2008 21:04:36 -0500 Subject: trying to match a string In-Reply-To: <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> Message-ID: <48814BB4.700@gmail.com> oj wrote: >>> Why not just use * instead of + like: >>> >>> if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of >>> string; $ means end of string >>> print "Invalid" >>> >>> This will *only* print invalid when there is a character other than L, >>> R, or M or a empty string. >>> >> Sorry, forget the beginning and ending markers, I just tried it out, it >> doesn't work. >> use this instead: >> >> if re.search(r'[^LRM]*', var): >> print "Invalid" >> > > No, that's broken. > > That searches for any number of invalid characters. Even 0, so it > ALWAYS matches, no matter what string you give it. > > My regex worked in the first place, you're complicating it needlessly. > The presence of one invalid character makes the string invalid, so why > not just search for one? Similarly, there's no need to stick in the > beginning and end markers - you're not trying to match the entire > string, just find part of it that is invalid. > > However, I think the sets solution by Scott David Daniels is the most > elegant method put forward. > -- > http://mail.python.org/mailman/listinfo/python-list > I see your point after rereading the question, he only wants to match L R and M let me revise it please: To show if valid: if re.search(r'^[LRM]*$', 'LM'): print 'Valid' To show if invalid, if re.search(r'^[^LRM]*$', '0'): print 'Inalid' Example session: >>> import re >>> def match(var): >>> if re.search(r'^[LRM]*$', var): ....... print 'Valid' ....... else: ....... print 'Invalid' >>> >>> eg = 'LRLRLRLRLM' >>> match(eg) Valid >>> fg = 'LRLRLRNL' >>> match(fg) Invalid -- Andrew From stodge at gmail.com Fri Jul 4 12:18:33 2008 From: stodge at gmail.com (Stodge) Date: Fri, 4 Jul 2008 09:18:33 -0700 (PDT) Subject: Boost Python - C++ class' private static data blown away before accessing in Python? Message-ID: I've exposed a C++ class to Python using Boost Python. The class, let's say it's called Entity, contains private static data, which is an array of strings. Though I think it implements it using MFC's CPtrArray. I've also exposed a public function from Entity - let's say it's called foo. This function accesses the private static data (the string array). I have multiple instances of Entity stored in a custom C++ container, which is also exposed to Python as class EntityList. In Python, I retrive an Entity from the EntityList: elist = EntityList() elist.append(Entity()) elist.append(Entity()) entity = elist.get_at(0) entity.foo() But it crashes inside foo() as the private static data is empty; or rather the string array is empty. I know before that point that the private static data is valid when accessed earlier by the C++ code as the program works fine. It just won't work from Python, so somehow the private static data has been blown away but I can't work out where or why. The static data is setup at initialisation - my Python code is only called long after initialisation is complete. I added a static dump() function to the Entity class that dumps the string array, and even if I just do the following in Python: Entity.dump() in Python, the private static data is empty. Doing the same from C++ works fine. Weird. I know this is an impossible question to ask, but can anyone think of something obvious I need to look into? Thanks From gcmartijn at gmail.com Sat Jul 5 04:12:04 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Sat, 5 Jul 2008 01:12:04 -0700 (PDT) Subject: pythoncom InternetExplorer.Application don't work in vista || firefox pythoncom ? Message-ID: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> H! I using a script that opens a internet page in a small window (what I can control) In XP everything was working fine, but now I'm using Vista with IE7 and this is what happends now: First a small window opens at the postion x0 y0 (like I want) but then IE thinks "Hey lets open a other main window too". And that window opens the url 'http://www.google.nl' It seems that I can't control/use my first window anymore, and that IE7/vista is forcing to open it in a big new window. The code below is what I'm using. def webbrowser(url=None): import pythoncom from win32com.client import Dispatch ie = pythoncom.CoCreateInstance("InternetExplorer.Application", None,pythoncom.CLSCTX_SERVER,pythoncom.IID_IDispatch) ie = Dispatch(ie) ie.Top = 0.0 ie.Left = 0.0 ie.Height = 400 ie.Width = 400 ie.AddressBar = False ie.MenuBar = False ie.Resizable = False ie.StatusBar = False ie.ToolBar = False ie.Visible = 1 return ie w = webbrowser() w.Navigate('http://www.google.nl') -- ow and why can't I find a pythoncom.CoCreateInstance.FireFox example ? Thanks for helping. From sjmachin at lexicon.net Sun Jul 13 19:15:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 13 Jul 2008 16:15:47 -0700 (PDT) Subject: Mutually referencing imports -- impossible? References: Message-ID: <4ce90db0-3ed3-4525-b1a3-a59851b37d30@f63g2000hsf.googlegroups.com> On Jul 14, 3:55 am, Matthew Wilson wrote: > I started off with a module that defined a class Vehicle, and then > subclasses Car and Motorcycle. > > In the Car class, for some bizarre reason, I instantiated a Motorcycle. > Please pretend that this can't be avoided for now. > > Meanwhile, my Motorcycle class instantiated a Car as well. > > Then I moved the Car and Motorcycle classes into separate files. Each > imported the Vehicle module. > > Then I discovered that my Car module failed because the global > Motorcycle wasn't defined. The same problem happened in my Motorcycle > module. Car and Motorcycle can't both import each other. And they should not import each other. > > In the beginning, when all three (Vehicle, Car, and Motorcycle) were > defined in the same file, everything worked fine. You seem to have a strange notion of "worked fine". > > I don't know how to split them out in separate files now though and I > really wish I could because the single file is enormous. What is making a file with 3 classes "enormous"?? What is "enormous"? > > Any ideas? *WRONG WAY* *GO BACK* Your structure is not only bizarre, it is also (sticking with only 1 letter of the alphabet) a Byzantine, baroque, and broken concept. Asking us to "pretend that this can't be avoided for now" is asking us to aid and abet you in creating a meaningless and unmaintainable monster. Consider adding Truck and Bus subclasses. Will each subclass instantiate the other 3??? You should be able to add or remove a subclass without having to modify all other subclasses. The only rational solution is not to have the subclasses refer to each other. Tell us *why* you think you need to have Car refer to Motorcycle and vice versa, and we should be able to help you find a way out. Cheers, John From deets at nospam.web.de Fri Jul 25 10:28:20 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 25 Jul 2008 16:28:20 +0200 Subject: Calling external program from within python In-Reply-To: References: Message-ID: <6eu684F91muhU1@mid.uni-berlin.de> Mike Driscoll schrieb: > On Jul 25, 7:56 am, Emmanouil Angelakis > wrote: >> Hi, >> >> I am tryiong to do something obviously trivial such as: >> I have a c program called "tsys2list" that when it is ran it asks the user to give the value of "tcal" which is a variable. I want to call the "tsys2list" from within a pyrthon script lets call it "gamma.py" >>>but<<< I want to pass the value of "tcal" to th eprogram automatically and not by interacting with the keyboard. >> >> How do I do that? >> >> thanks i advance! >> manolis > > There are probably many ways to do this. I would recommend checking > out the subprocess module and see if it does what you want. This will only work if the program can be fully controlled by commandline arguments. If interaction is required, the OP might consider using pexpect. > Or you > could learn a little Tkinter or wxPython and use that to get the > user's variable. Or you could even do it via the command line using > the "raw_input" command. I fail to see how *gathering* input (regardless of the method) solves the problem of *passing* input to a subprocess. Diez From modelnine at modelnine.org Wed Jul 30 03:03:49 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Wed, 30 Jul 2008 09:03:49 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> Message-ID: <200807300903.49378.modelnine@modelnine.org> Am Mittwoch, 30. Juli 2008 08:30:48 schrieb Russ P.: > On Jul 29, 11:09 pm, Erik Max Francis wrote: > > I'm getting this sneaking suspicion that you guys are all putting us on. > > As I said in an earlier post, I realize that this would only work if > there were only one copy of "empty" (as there is only one copy of > "None"). I don't know off hand if that is feasible or not. > > You reply reeks of the kind of pedantic snobbishness that makes me > sick. I can understand (and pretty much sympathise) that you get this kind of reply, simply because the point you and Carl Banks (formulated somewhat differently) put up has been answered again and again (in this thread), and I can only repeat it once more: __nonzero__(), i.e. the "cast" to boolean, is THE WAY to test whether a container is empty or not. Like this design decision, or don't like it, but the discussion is not going to go anywhere unless you concede that there is a (very explicit!) way to test for non-emptiness of a container already, and you're currently simply discussing about adding/using syntactic sugar (different means of expressing the test) to suit your own personal taste better. Anyway, check the documentation for __nonzero__(): if the object doesn't implement that, but implements __len__(), the interpreter "replaces" the __nonzero__() test by __len__()>0, so I guess someone in the design department must've seen it logical for the truth value of a container to express the test "len(x)>0" at some point in time to make this interpretation for the truth value of a container. There cannot be an argument about missing/misplaced functionality (that's what you make it sound like), if the functionality for doing what you want to do is there and you simply don't like the syntax, which I can somewhat relate to because style is a personal thing, even though I don't see either points made by you or Carl Banks, because implicit casting to bool is so common in pretty much every programming language to test for "truth" of an object, and IMHO it's completely logical to extend that idea to containers to mean empty/non-empty. Eric Max Francis tried to explain why your syntactic "enhancement" would come at a much greater price than its worth, and he's absolutely right in that, as it's an abuse of the "is" operator, but again, that's a somewhat different point. It changes nothing about the fact that all this discussion centers around something that is a non-point, but simply a matter of personal taste. -- Heiko Wundram From fredrik at pythonware.com Wed Jul 23 07:10:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 13:10:38 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> Message-ID: Jaco Naude wrote: > What Visual C++ is doing is that it is looking for mangled names since > it does not know the DLL contains C functions. I've managed to work > around this by declaring the Python functions as follows before using > them in the C++ application side: > > extern "C" > { > void Py_Initialize(void); > } > > This seems to work and the C++ application side is not looking for > mangled names any more. Is this the right way of doing it? It seems > unnecessary to have to declare each Python function you want to use > using the extern "C" way as shown above. Eh, are you saying that you're not including the Python.h file? Because it does exactly that, for each and every public function in the C API. > It is probably more of a C++ question it turns out, but I would think > that someone in the Python group would use the Python DLL in C++. The > documentation also suggest that there is no extra work needed when > using C++ rather than C. Oh, but I do that all the time, without doing any extra work. Both embedding Python in C++ programs and existing it with C++ extensions. And I'm definitely not alone. Here's an actual session, using the version of Visual Studio I happen to have on this machine (2003, I think) from the command line: > more test.cc #include "Python.h" #include main() { Py_Initialize(); PyRun_SimpleString("print 'hello'\n"); Py_Finalize(); std::cout << "world\n"; } > cl cl -EHsc -MD -I \python25\include test.cc \python25\libs\python25.lib Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80x86 Copyright (C) Microsoft Corporation 1984-2002. All rights reserved. ... > test hello world If you cannot get the same console program to work in your compiler setup, something's wrong with your configuration. From fredrik at pythonware.com Sat Jul 19 15:04:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 19 Jul 2008 21:04:06 +0200 Subject: regex doubts In-Reply-To: <532965.570.qm@web54502.mail.re2.yahoo.com> References: <532965.570.qm@web54502.mail.re2.yahoo.com> Message-ID: Mr SZ wrote: > I am taking a string as an input from the user and it should only > contain the chars:L , M or R > > I tried the folllowing in kodos but they are still not perfect: > > [^A-K,^N-Q,^S-Z,^0-9] > [L][M][R] > [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > > For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. try "[LRM]+$" (an L or an R or an M, one or more times, all the way to the end of the string). From fredrik at pythonware.com Sun Jul 20 11:48:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jul 2008 17:48:58 +0200 Subject: Web Server In-Reply-To: References: Message-ID: misceverything at gmail.com wrote: > As part of a Python app I wrote recently (for Windows), I would like > to give the option of an HTTP (HTTPS if possible, but not necessary) > front end, which would then call some existing python scripts. My > question is - I know I can write a simple HTTP server in Python, but > if there's something simple already out there, I'd prefer to just use > that. Basically all I need is a simple (i.e. preferably a single > executable) web server that can serve up my content - the only thing I > want the user to be able to configure is the port the web server > listens on (or ports if HTTPS also), and the location of the HTML > files... thanks in advance for your help. import SimpleHTTPServer ? sample code here: http://effbot.org/librarybook/simplehttpserver.htm From asmodai at in-nomine.org Thu Jul 10 13:50:45 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 10 Jul 2008 19:50:45 +0200 Subject: Fwd: [ANN] Babel 0.9.3 released Message-ID: <20080710175045.GR68329@nexus.in-nomine.org> ----- Forwarded message from Christopher Lenz ----- From: Christopher Lenz To: python-babel at googlegroups.com Cc: cldr-users at unicode.org Subject: [ANN] Babel 0.9.3 released Date: Thu, 10 Jul 2008 11:26:23 +0200 X-Mailer: Apple Mail (2.926) Babel 0.9.3 - Jul 9, 2007 ========================= We're proud to present the latest release of the Babel: 0.9.3. Babel is a Python library that provides an integrated collection of utilities that assist with internationalizing and localizing Python applications (in particular web-based applications.) This release contains a number of bugfixes over the 0.9.2 release. You can download the new release here: Please don't hesitate to report any issues you may find with this release: For questions, comments and user discussions, please use the Babel mailing list: What's New: ----------- * Fixed invalid message extraction methods causing an UnboundLocalError. * Extraction method specification can now use a dot instead of the colon to separate module and function name (ticket #105). * Fixed message catalog compilation for locales with more than two plural forms (ticket #95). * Fixed compilation of message catalogs for locales with more than two plural forms where the translations were empty (ticket #97). * The stripping of the comment tags in comments is optional now and is done for each line in a comment. * Added a JavaScript message extractor. * Updated to CLDR 1.6. * Fixed timezone calculations when formatting datetime and time values. * Added a `get_plural` function into the plurals module that returns the correct plural forms for a locale as tuple. * Added support for alias definitions in the CLDR data files, meaning that the chance for items missing in certain locales should be greatly reduced (ticket #68). Acknowledgments ---------------- A big thank you to everyone who tried Babel and provided feedback, reported bugs, and/or contributed patches! Cheers, Chris -- Christopher Lenz cmlenz at gmx.de http://www.cmlenz.net/ ----- End forwarded message ----- -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B No man is good enough to govern another man without the other's consent... From bignose+hates-spam at benfinney.id.au Tue Jul 29 19:27:00 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 30 Jul 2008 09:27:00 +1000 Subject: static variables in Python? References: Message-ID: <87prowff0b.fsf@benfinney.id.au> kj writes: > Is there a way to mimic C's static variables in Python? Or something > like it? A "static variable" in C is one that has access limited to the scope in which it is declared. Python approaches the same issue through namespaces: a name binding made at a class or module level is accessible only via specification of the class or module namespace. > The idea is to equip a given function with a set of constants that > belong only to it, so as not to clutter the global namespace with > variables that are not needed elsewhere. Python functions have local name bindings by default . Python doesn't have "variables" in the sense of boxes containing values, so it doesn't have "constants" in the sense of boxes that don't change. Instead, Python has names bound to objects like sticky notes. A name can later be re-bound to some other object. What use case are you trying to address? It seems that the normal use of local function names and class attributes would serve your described requirements. -- \ ?It is hard to believe that a man is telling the truth when you | `\ know that you would lie if you were in his place.? ?Henry L. | _o__) Mencken | Ben Finney From vinay_sajip at yahoo.co.uk Tue Jul 15 09:56:15 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 15 Jul 2008 06:56:15 -0700 (PDT) Subject: Logging in __del__() References: <17056.2125546441$1216121658@news.gmane.org> Message-ID: On Jul 15, 1:51 pm, "Robert Rawlins" wrote: > > Am I right in thinking that Python destroys instances of classes when it > deems they are no longer needed? I shouldn't have to explicitly delete the > classes, right? Python uses reference counting with a cycle detector, but the detector's behaviour is different if there are finalizers (__del__) - see http://www.python.org/doc/ext/refcounts.html Regards, Vinay Sajip From goldfita at gmail.com Mon Jul 7 11:22:12 2008 From: goldfita at gmail.com (goldfita at gmail.com) Date: Mon, 7 Jul 2008 08:22:12 -0700 (PDT) Subject: python mysteriously halts References: <13a33043-21d1-40c0-a938-6e905d958064@m3g2000hsc.googlegroups.com> Message-ID: On Jul 7, 10:17?am, Tim Golden wrote: > Todd wrote: > > I ran a python script last night which connects to a matlab automation > > server via DCOM (using win32com). ?I expected to see the results when > > I came in this morning. ?But apparently, not long after I left, python > > stopped. ?I hit enter in the console, and it started again. > > Symptomatically, at least, this can be caused by someone starting to > select (with the mouse) an area of the screen: the process will pause > until is pressed, which copies the area to the clipboard. This > only happens with a console window, but it sounds like that's what > you had running. > > TJG That might be it, although I don't recall doing that. Fortunately/ unfortunately, it happened a few times, but it seems to have stopped now. From gptutorsx at gmail.com Wed Jul 23 03:33:00 2008 From: gptutorsx at gmail.com (smartx) Date: Wed, 23 Jul 2008 00:33:00 -0700 (PDT) Subject: game programming Message-ID: <8890c74b-e92c-4dfd-9a3a-4399f83a42c2@x35g2000hsb.googlegroups.com> Game programming became as a box of art and science, the box contains a lot of arts, musics, sounds, graphics,scenario, math, ai and physics ...etc. great department, great skills, great tips, also you can observe your source is the internet that has a lot of articles a lot of great sites like gamedev.net, gameinstitute.com, gametutorials.com. all of these encourage you to be a professional game programmer, for me I love it so much, it's important to love something, because this will help you to develop yourself in this domain, I hope for all the best wishes in game development's journey. Best wishes for all, smartx gptutors.com From mwilson at the-wire.com Tue Jul 1 09:15:27 2008 From: mwilson at the-wire.com (Mel) Date: Tue, 01 Jul 2008 09:15:27 -0400 Subject: problem with exec and locals() References: <95f07476-e3c8-45e4-82b3-0e48c9188f8e@79g2000hsk.googlegroups.com> Message-ID: rocksportrocker wrote: > > Hi, > > the following code does not work until I ommit the "a=0" statement. > > > def test(): > exec "a=3" in locals() > print a > a=0 > > test() > > print raises: > UnboundLocalError: local variable 'a' referenced before > assignment > > Can anybody explain what is going wrong here ? AFAIK, local variables are implemented rather like __slots__ in new-style classes. This is a very valuable efficiency measure, but it can cause this kind of trouble. Without `a=0`, the bytecode compiler makes no slot for a, and dis.dis shows the following bytecode for test: >>> dis.dis (test) 2 0 LOAD_CONST 1 ('a=3') 3 LOAD_NAME 0 (locals) 6 CALL_FUNCTION 0 9 DUP_TOP 10 EXEC_STMT 3 11 LOAD_NAME 1 (a) 14 PRINT_ITEM 15 PRINT_NEWLINE 16 LOAD_CONST 0 (None) 19 RETURN_VALUE At address 11, LOAD_NAME 1(a) gets the value that was set by exec. With a=0, the code is >>> dis.dis(test2) 2 0 LOAD_CONST 1 ('a=4') 3 LOAD_NAME 0 (locals) 6 CALL_FUNCTION 0 9 DUP_TOP 10 EXEC_STMT 3 11 LOAD_FAST 0 (a) 14 PRINT_ITEM 15 PRINT_NEWLINE 4 16 LOAD_CONST 2 (0) 19 STORE_FAST 0 (a) 22 LOAD_CONST 0 (None) 25 RETURN_VALUE and here, the value of a is found in slot 0 via LOAD_FAST. Slot 0 is used because a=0 forced a to be a local variable. Apparently, exec in locals() knows nothing about slots (because locals() is the only dictionary in the universe where slots would be involved ? -- perhaps not, but close). Mel. From dominic.rice at gmail.com Fri Jul 4 20:10:37 2008 From: dominic.rice at gmail.com (Dominic Rice) Date: Sat, 05 Jul 2008 01:10:37 +0100 Subject: running python from cmd.exe References: Message-ID: John Machin wrote: > On Jul 5, 7:38 am, Dominic Rice wrote: >> Chris Hulan wrote: >>> On Jul 4, 5:38 am, Dominic Rice wrote: >>>> Dominic Rice wrote: >>>>> Miki wrote: >>>>>> Hello, >>>>>>> I can't seem to get python to run my scripts using the command: python >>>>>>> .py >>>>>>> If I type python the interpreter runs as I sorted out the Path property, >>>>>>> I'm afraid I don't know much about this kind of thing as I'm a science >>>>>>> student who needs some Python not a programmer! >>>>>> Can you be more specific about the error you get? >>>>>> Say you have a script hw.py that contains one line: >>>>>> print "Hello Python" >>>>>> and you run >>>>>> python hw.py >>>>>> What is the error you get? >>>>>> HTH, >>>>>> -- >>>>>> Miki >>>>>> http://pythonwise.blogspot.com >>>>> Sure, I get: >>>>> can't open file .py: [errorno 2]No such file or directory. >>>>> Now if I've noticed that if I change directory to (for instance) >>>>> \Python25 where the script is the command runs fine.(?) >>>> Oh I just noticed you specified hw.py, in that case just to clarify it >>>> would be can't open file hw.py: [errorno 2]No such file or directory >>> When you run a script, are you in the directory where the script is >>> located? >> when it works yes! Does it have to be the case then? I assumed that >> there was a default folder (eg \Python25) that the python command would >> look for the file in, I take it this is not the case then? > > The default folder *is* the "current" folder, i.e. "the directory that > you are in". If you want to run a script in another folder, you > specify the path to that script. This is usual in Windows command-line > operation, not special to Python. > > By the way, storing your own files in the same folder structure as a > software package (e.g. \Python25) is not a good idea. Keep them > somewhere else e.g. a separate folder for each significantly different > project, a folder for commonly useful stuff, and a junk folder for > mucking about trying things out. Then when e.g. you upgrade to Python > 2.6 the possibility of drama is reduced. > > HTH, > John seems like very good advice, many thanks! From mail at timgolden.me.uk Wed Jul 16 15:20:29 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 20:20:29 +0100 Subject: About wmi In-Reply-To: <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> <487E1AD4.9020509@timgolden.me.uk> <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> Message-ID: <487E49FD.7050005@timgolden.me.uk> patrol wrote: > On 7?17?, ??12?16?, Tim Golden wrote: >> Assuming that the error comes back in the sys.stdout encoding, the following version *should* work ok. I still haven't got a non-English set up to test it on, but it certainly does return a Unicode error message. >> >> http://timgolden.me.uk/wmi-project/wmi.py >> >> The usual test case, if you wouldn't mind: >> >> >> import wmi >> >> wmi.WMI ("non-existent computer") >> >> >> >> should give a (language-specific) error message, not an UnicodeDecodeError >> >> TJG > -------------------------------------------------------------------------------------- >>>> import wmi >>>> wmi.WMI('non-existent computer') > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\wmi.py", line 1199, in connect > handle_com_error (error_info) > File "C:\Python25\lib\wmi.py", line 184, in handle_com_error > exception_string = [u"%s - %s" % (hex (hresult_code), > hresult_name)] > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > 4: ordinal > not in range(128) > -------------------------------------------------------------------------------------- > yup,error_info contains the Chinese encoded string. All of the Simple > Chinese Windows use the CP936.Every Chinese word utilizes two > bytes.Maybe you can fix this bug by modifying handle_com_error. Can you confirm that that last bit of code was run with the version of wmi.py currently at: http://timgolden.me.uk/wmi-project/wmi.py That version should already be decoding the string correctly. TJG From jiri.zahradil at gmail.com Mon Jul 7 03:23:33 2008 From: jiri.zahradil at gmail.com (jiri.zahradil at gmail.com) Date: Mon, 7 Jul 2008 00:23:33 -0700 (PDT) Subject: Python with Ecmascript References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <8ek074tia4l47tcfo6tqfo9huv2hb68hkt@4ax.com> <7eaf458d-b355-4112-a947-b2b7fe0d1f8d@s50g2000hsb.googlegroups.com> Message-ID: On 7 ?ec, 08:21, alex23 wrote: > On Jul 7, 12:31 am, "jiri.zahra... at gmail.com" > > wrote: > > I personally does not like COM solution. I prefer some simple library > > but may be it is just a hope. > > Have you looked at the module 'python-spidermonkey'? It apparently > "allows for the implementation of Javascript classes, objects and > functions in Python, as well as the evaluation and calling of > Javascript scripts and functions". > > http://code.google.com/p/python-spidermonkey/ I have looked at it. It seems to be not fully working version, but I have not check it properly because the project homepage says "windows version is forthcoming". At this time I am considering using some command line interpreter (maybe jsdb, http://www.jsdb.org/, based on spidermonkey) Idea is to save script code to file and let it run by interpreter and then parse the results. Problem is that this approach has very limited access to variables and objects exposed to javascript (they needs to be serialized before script run, script cannot call python functions etc) and also retrieving results is not straigtforward. Still looking for better solution ... JZ From alan.isaac at gmail.com Tue Jul 22 23:13:37 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Wed, 23 Jul 2008 03:13:37 GMT Subject: sys.stderr.write returns string length in Python 3 In-Reply-To: <43ab2eb4-31ec-4574-ab54-4467fa89d187@27g2000hsf.googlegroups.com> References: <43ab2eb4-31ec-4574-ab54-4467fa89d187@27g2000hsf.googlegroups.com> Message-ID: Benjamin wrote: > http://www.python.org/dev/peps/pep-3116/. Thanks. Can you give me an example of using the returned value? Alan From elessar at nienna.org Wed Jul 30 12:25:58 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Wed, 30 Jul 2008 10:25:58 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> Message-ID: <48909616.6050004@nienna.org> Carl Banks wrote: > On Jul 29, 6:42 pm, Matthew Fitzgibbons wrote: >> Carl Banks wrote: >>> Much like in Steven D'Aprano's example, still the only actual code >>> snippet I've seen, it seems that this can easily be done with a simple >>> explicit test by having all no-advance filters return None and testing >>> with "if x is not None". So it doesn't pass my criterion of being not >>> replaceable with simple explicit test. >>> Maybe that's not workable for some reason. Perhaps if you'd post a >>> code example that shows this, rather than just talking about it, you >>> might be more persuasive. >>> Carl Banks >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> The no-advance filters have to return the object because I don't just >> forget about it; I evaluate whether I pass it to the next filter or drop >> it in a completely different queue for use in the next stage of the >> operation. True means 'I'm ready to move on to the next stage,' False >> means 'Do the filter thing some more.' > > I think I see what you're saying, and yeah I guess that could really > take advantage of polymorphism between very different types. > >> Furthermore, the argument that I should just change my API to make a >> 'simple test' work is not very convincing. > > I wasn't suggesting you change it: I was trying to ascertain whether > it would have suffered much if you had written it with explicit tests > in the first place, or if Python didn't even have magical booleans. Yes it would have suffered. I chose the implementation I did because it made the most sense to me and was the most flexible (a key requirement). Instead of cobbling together my own way, I used the way that Python gave me. Python doesn't have magic booleans. They are instead a very well-defined language mechanism that isn't perfect for every circumstance, but is pretty good for the most part. I wanted to do meaningful boolean tests on various objects, so I used the mechanism that my language gave me. > >> The natural, obvious way for >> a filter to work is to pass through the data it operates on; why on >> Earth would it return None? I want to DO something with the data. In >> this case, make a decision about where to pass the data next. > > If you don't mind me asking: what do you do actually DO with a zero or > empty list? Depends on exactly what the next stage is. Typically, zeros and empty lists are not meaningful for the next stage, so they get dropped then if they make it through. I don't want to restrict what gets passed through, though, because I could end up with several meaningful data types, making a simple test again impossible. So I pass everything through and let the next stage decide. > >> In Java, >> to accomplish this I would have to do lots of introspection and value >> checking (adding more any time I came up with a new kind of input), or >> make a new kind of interface that gives me a method so I can do a >> 'simple test' (including wrappers for ints and arrays and anything else >> I decide to pass in down the road). But Python supports duck typing and >> gives me a handy __nonzero__ method; I can rebind __nonzero__ in my >> filters for my own classes, and ints and lists are handled how I want >> them to be by default. So why jump through hoops instead of just using >> 'if x'? > > Ah, so it's just happens to work. Still, just happening to work > works. (shrug) Nonono. The point you seem to be missing is that 'if x' is very well defined. There is nothing magic or arbitrary about what it does. It works here and elsewhere because Python (a) chooses good default behavior (its treatment of lists and ints, etc) and (b) gives you a way, __nonzero__, to change the behavior to suit your needs. > >> I don't have any postable code (it's in a half way state and I haven't >> touched it for a while), but I'll see if I can't find the time to bang >> something up to give you the gist. > > I wouldn't bother at this point. I was looking to see if someone > could come up with something to disprove my belief on the polymorphic > uselessness of "if x" relative to explicit tests, and if (as I > anticipated) they did not, I could claim that "if x" is really just a > glorified keystroke saver. But I now realize that the failure of this > bunch doesn't prove anything. I don't think most people even realize > why answering the question I asked would demonstrate the usefulness of > "if x". Of course you don't _need_ to have 'if x'; after all, REAL programmers code in machine language. The whole point of a high-level language is to make life easier. Python is very dynamic and allows duck typing so that you can use these tools to do clever things that would otherwise be very difficult. It even gives you a handy polymorphic mechanism to do boolean tests, which my example illustrates. You asked for a use case for a polymorphic 'if x' that can't be easily replaced by a simple test. I gave one. Then you asked for a code sample, but now have dismissed my sample as not compelling without having seen it. But here it is anyway (attached). It's pretty rough since I just threw it together. I'm sure there are mistakes. I also dropped the DAG, where all the queueing and decision making is handled in the actual program. The filters and data are arbitrary but should illustrate the setup. You care about line 66. Again, the same thing could be accomplished in various ways; but keep in mind that data could be _anything_, so you can't easily rewrite line 66. > > Your example isn't exactly the smoking gun I was looking for, but I > guess we'll have to admit that at least one usage will suffer for not > having it. > > > Carl Banks > -- > http://mail.python.org/mailman/listinfo/python-list > So you hypothesized that you can easily rewrite any 'if x' as a simple, explicit test. I produced an example that shows this cannot be done; therefore your hypothesis is not correct. For most cases, you can come up with a simple test, even if it's not the best way to implement you problem. But other times, the poylmorphic, duck typing behavior of 'if x' allows you to make your problem much easier, in a way a simple test can't. To deny this fact is to deny to power of dynamic languages in general. -Matt -------------- next part -------------- A non-text attachment was scrubbed... Name: filterex.py Type: text/x-python Size: 4647 bytes Desc: not available URL: From bj_666 at gmx.net Sat Jul 19 12:28:16 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Jul 2008 16:28:16 GMT Subject: MethodChain References: Message-ID: <6eej10F6k7g3U2@mid.uni-berlin.de> On Sat, 19 Jul 2008 08:55:23 -0700, bearophileHUGS wrote: > Found from Reddit, it's for e ECMA(Java)Script, but something similar > may be useful for Python too: > > http://jsclass.jcoglan.com/methodchain.html > http://blog.jcoglan.com/2008/07/16/where-did-all-my-code-go-using-ojay-chains-to-express-yourself-clearly/ What's called `MethodChain` there seems to be function composition in functional languages. Maybe `functools` could grow a `compose()` function. Ciao, Marc 'BlackJack' Rintsch From svenn.bjerkem at googlemail.com Tue Jul 29 13:54:54 2008 From: svenn.bjerkem at googlemail.com (Svenn Are Bjerkem) Date: Tue, 29 Jul 2008 10:54:54 -0700 (PDT) Subject: Parsing VHDL with python, where to start. References: <31888260-86a9-46b0-b0a4-79f7852f256a@k30g2000hse.googlegroups.com> <488F33E9.8090004@ericsson.com> Message-ID: <4e02f7d1-b342-4413-be4b-525f273e0d5f@56g2000hsm.googlegroups.com> On Jul 29, 5:14 pm, Wolfgang Grafen wrote: > For me it is not very clear what you intend to do. After years of > parsing parts of VHDL from time to time the rapid parsing way for me is > using regular expressions instead of one of the parser frame works > because of following reasons: > > - It is hard for me to understand those frameworks > - They are very slow > - It is too much work for me to bring them up to work in a sensible way > - Compared with regular expression matching they usually need a lot of > extra work. I agree with frameworks being difficult to understand and that is why I also have been using regular expressions in tcl to parse spice netlists before. Now I want to parse spice, vhdl and also maybe verilog. I think I will end up with regular expressions unless I get a grip on SimpleParse. The rationale for the whole project has been to finally be able to view spice and specially vhdl code for projects I work on. This has been something I have wanted to have for years, without having the ressources to complete it. There are commercial tools available, but I was looking for something more open/free that could be maintained independently of what tools I have at work. > PyQt as a widget framework is not useful until here, but of course you > could display your results in arbitrary graphical ways with PyQt, if you > rally need to. You should know, printing out an ASCII or XML > representation is so much more easy and quicker to code so I always > prefer that. There are even editors/visualizers ready to display XML... PyQt4 doesn't help me parse my sources, but it helps me visualise them. I did something in tcl/tk to get hierarchical spice netlists into a tree structure, but extending that app was too much hassle. PyQt4 offers a lot of functionality once the threshold of learning it has been passed. It also installs nicely on windows and most linux distributions offer it ready to install. And I like Qt. -- Svenn From zapwireDASHgroups at yahoo.com Mon Jul 14 22:24:54 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Mon, 14 Jul 2008 19:24:54 -0700 Subject: One step up from str.split() References: <2f7e2895-e1ee-4113-a6bf-a3a15235f27c@w7g2000hsa.googlegroups.com> Message-ID: Thanks Matt, that looks like just what I want! From gros_bedo at hotmail.com Sun Jul 13 14:59:04 2008 From: gros_bedo at hotmail.com (Gros Bedo) Date: Sun, 13 Jul 2008 20:59:04 +0200 Subject: Terminate a python script from linux shell / bash script Message-ID: Thank you guys for your help. My problem is that I project to use this command to terminate a script when uninstalling the software, so I can't store the PID. This command will be integrated in the spec file of the RPM package. Here's the script I'll use, it may help someone else: #!/bin/sh # PYTHON SCRIPT PROCESS KILLER by GBO v0.1 # This script will look for all the lines containing $SOFTWARENAME in the process list, and close them SOFTWARENAME='yoursoftware' #This is case insensitive JOBPRESENT=$(ps -ef | grep -i $SOFTWARENAME | grep -v grep) echo $JOBPRESENT ps -ef | grep -i $SOFTWARENAME | grep -v grep | awk '{print $2}' | xargs kill _________________________________________________________________ Pendant tout l'?t?, consultez vos emails Hotmail sur votre mobile ! http://www.messengersurvotremobile.com/?d=hotmail From Nikolaus at rath.org Mon Jul 28 03:26:02 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 28 Jul 2008 09:26:02 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> <490769a4-2a48-41dc-a069-2cc003b332a2@b1g2000hsg.googlegroups.com> Message-ID: <87tzeasc51.fsf@nokile.rath.org> castironpi writes: >> I think you misunderstood him. What he wants is to write >> >> class foo: >> ? ?def bar(arg): >> ? ? ? ?self.whatever = arg + 1 >> >> instead of >> >> class foo: >> ? ?def bar(self, arg) >> ? ? ? ?self.whatever = arg + 1 >> >> so 'self' should *automatically* only be inserted in the function >> declaration, and *manually* be typed for attributes. >> > > There's a further advantage: > > class A: > def get_auxclass( self, b, c ): > class B: > def auxmeth( self2, d, e ): > #here, ... > return B In auxmeth, self would refer to the B instance. In get_auxclass, it would refer to the A instance. If you wanted to access the A instance in auxmeth, you'd have to use class A: def get_auxclass(b, c ): a_inst = self class B: def auxmeth(d, e ): self # the B instance a_inst # the A instance return B This seems pretty natural to me (innermost scope takes precedence), and AFAIR this is also how it is done in Java. Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From fredrik at pythonware.com Sat Jul 26 08:25:49 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Jul 2008 14:25:49 +0200 Subject: re.findall(a patern,'function(dsf sdf sdf)') In-Reply-To: <2dd5c418-f532-4f50-923e-057a10f01fdd@79g2000hsk.googlegroups.com> References: <8fc6d72a-cfc5-4e9d-af56-a009a464c6bb@27g2000hsf.googlegroups.com> <2dd5c418-f532-4f50-923e-057a10f01fdd@79g2000hsk.googlegroups.com> Message-ID: gcmartijn at gmail.com wrote: > - For me its hard to learn the re , I will try to search again at > google for examples and do some copy past things. this might be useful when figuring out how RE:s work: http://kodos.sourceforge.net/ also, don't forget the following guideline: "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." some advice: - Keep the RE:s simple. You can often simplify things a lot by doing multiple searches, or even by applying a second RE on the results from the first. In this case, you could use one RE to search for BlaObject, and then use another one to extract the first argument. - Ordinary string methods (e.g. find, partition, split) are often a very capable alternative (in combination with simple RE:s). In your case, for JavaScript code that's as regular as the one in your example, you can split the string on "BlaObject(" and then use partition to strip off the first argument. - only use RE:s to read specialized file formats if you know exactly what you're doing; there's often a ready-made library that does it much better. - The regular expression machinery is not a parser. You cannot handle all possible syntaxes with it, so don't even try. From toby at tobiah.org Wed Jul 2 17:25:49 2008 From: toby at tobiah.org (Tobiah) Date: Wed, 02 Jul 2008 14:25:49 -0700 Subject: Sorting two dimentional array by column? Message-ID: Imagine an excel spreadsheet. I can choose a column and sort the records based on the items in that column. I would like to do the same thing with a large two dimensional array. What would be the fastest way (in computation time) to accomplish this? This seems similar to a recent sorting thread, but with that one, the 'master' table was sequential integers. This array would be filled with arbitrary data. Thanks ** Posted from http://www.teranews.com ** From nagle at animats.com Tue Jul 22 12:07:18 2008 From: nagle at animats.com (John Nagle) Date: Tue, 22 Jul 2008 09:07:18 -0700 Subject: DB Pool In-Reply-To: <40f3a61b-8c37-4e26-90f6-02de760ce00e@c58g2000hsc.googlegroups.com> References: <40f3a61b-8c37-4e26-90f6-02de760ce00e@c58g2000hsc.googlegroups.com> Message-ID: <48860153$0$17207$742ec2ed@news.sonic.net> bcurtu wrote: > Hi, > > I use MySQLdb lib to access my DB, because I want to optimize my SQL > queries. The application I'm working on has quite a few traffic load, > so I want to minimize the time of creating/destroying cursors: > > My typical code is sth like: > > cursor=con.cursor() > cursor.execute(sql) > all= cursor.fetchall() > cursor.close() > > So, the question is... how can I minimize this cost? I was thinking on > Connection Pools, but I didn't find any good documentation or sample. > Any idea? Creating and destroying MySQLdb cursors is cheap, because it doesn't really do anything. MySQL doesn't actually support cursors; you can only do one thing at a time per connection, and thus you can only have one cursor per connection. So cursor creation is a dummy operation for MySQLdb. Creating connections to the database is more expensive, and it helps to reuse those. There was once something called the "pool module" for doing this ("http://dustman.net/andy/python/Pool") but it's a dead link now. This is usually an issue only in multithreaded programs. Also, it's OK to have multiple connections open to the database from multiple threads, until you have so many that the database server starts to run out of resources. John Nagle From Scott.Daniels at Acm.Org Wed Jul 23 00:32:00 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 22 Jul 2008 21:32:00 -0700 Subject: Question about inheritence In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Catherine Heathcote wrote: > >> If I create a new class inherited from another with a constructor, what >> happens with the new class's constructer? > Python doesn't really have constructors; when you create an object, > Python first creates the object and then calls the __init__ method, if > available To elaborate a bit on Fredrik's response, there is a sense in which Python has constructors, but, to the extent it does, a constructor is the __new__, __init__ pair. For immutables, everything happens in __new__, for mutables, most things happen in the __init__ chain. --Scott David Daniels Scott.Daniels at Acm.Org From stefan_ml at behnel.de Sun Jul 27 04:48:05 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 27 Jul 2008 10:48:05 +0200 Subject: xml.dom's weirdness? In-Reply-To: <1c837e71-a191-4495-8ec8-0126003ba9c6@n33g2000pri.googlegroups.com> References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> <1c837e71-a191-4495-8ec8-0126003ba9c6@n33g2000pri.googlegroups.com> Message-ID: <488C3645.8060304@behnel.de> Lie wrote: > Question: Is there a way to list loaded modules, including those that > aren't in my namespace? such as sys.modules? Modules are not unloaded automatically just because you do not use them yourselves. If the module is imported for whatever reason by whatever other module, it stays alive until it's no longer referenced (including the reference in sys.modules). Stefan From alexnbryan at gmail.com Tue Jul 15 18:48:15 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 15 Jul 2008 15:48:15 -0700 (PDT) Subject: Testing for connection to a website In-Reply-To: <18473382.post@talk.nabble.com> References: <18473382.post@talk.nabble.com> Message-ID: <18476597.post@talk.nabble.com> Alexnb wrote: > > Okay, I already made this post, but it kinda got lost. So anyway I need to > figure out how to test if the user is able to connect to a specific > website. Last time I got pointed to the urllib2 page, but if I do > urlopen() and and am not connected, the program stops. So I don't know if > that was what you guys wanted me to do, but I don't think so, you guys are > smarter than that. So, how can I test for connection to a website. > Just for anyone looking this up later here is code that works :) from urllib2 import * import urllib2 e = '' req = urllib2.Request('http://www.dictionary.com') try: response = urlopen(req) except HTTPError, e: print e.code except URLError, e: print e.reason if e == '': print "good to go" -- View this message in context: http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p18476597.html Sent from the Python - python-list mailing list archive at Nabble.com. From nagle at animats.com Fri Jul 18 01:28:06 2008 From: nagle at animats.com (John Nagle) Date: Thu, 17 Jul 2008 22:28:06 -0700 Subject: Problem with MySQLdb and mod_python In-Reply-To: References: Message-ID: <48802594$0$17225$742ec2ed@news.sonic.net> Cyril Bazin wrote: > Thanks for your reply > > The apache log contains lines like : > > [Tue Jul 15 23:31:01 2008] [notice] mod_python (pid=11836, > interpreter='www.toto.fr'): Importing module > '/usr/local/apache2/htdocs/intranet/courrier/test.py' > [Tue Jul 15 23:31:02 2008] [notice] child pid 11836 exit signal > Segmentation fault (11) > [Tue Jul 15 23:31:19 2008] [notice] mod_python (pid=11764, > interpreter='www.toto.fr'): Importing module > '/usr/local/apache2/htdocs/intranet/courrier/test.py' > [Tue Jul 15 23:31:19 2008] [notice] child pid 11764 exit signal > Segmentation fault (11) > > I think the problem comes from the MySQLdb module. > If I can't find another solution, I think I will downgrade the MySQLdb > version to 1.2.1 Sounds like version hell. mod_python and MySQLdb have to be compiled with exactly the same compiler for this to work. mod_python is usually troublesome. Python doesn't really have quite enough isolation to run multiple unrelated instances reliably. We use FCGI, which has the isolation of CGI but doesn't reload the application for every transaction. Also, it's easier to debug if CPython is crashing. John Nagle From jim.hefferon at gmail.com Wed Jul 2 12:42:00 2008 From: jim.hefferon at gmail.com (Jim) Date: Wed, 2 Jul 2008 09:42:00 -0700 (PDT) Subject: convert unicode characters to visibly similar ascii characters References: <17d4c282-8606-4d29-9e71-d34f5e6d13bb@m44g2000hsc.googlegroups.com> Message-ID: On Jul 1, 8:42 pm, Jim wrote: > On Jul 1, 8:29 pm, John Machin wrote: > > Comments on the above grep output: > > 1. You have SOFT HYPHEN twice, mapping it to u'-' and '-' > > Hmph. I'll correct that. Thanks. Well, maybe not. I forgot that I got the by-hand conversions from three different sources and that's why that character appears in two different places. (I thought that listing all cases for each source was less confusing. Arguable, for sure.) > 2. The idea of a soft hyphen is as a hint to a hyphenator about where > > to insert a hyphen if one is necessary and the hyphenator is suspected > > of acting cluelessly without the hint. IMHO, asciification should > > substitute u'', not u'-'. > > Thanks also here. I'll think about it. Googling "soft hyphen" showed me that the question is not perfectly clear-- some people seem to have very elaborate opinions on the topic-- but I've gone with your suggestion. Thank you. Again, I'd appreciate additional corrections. Not do I only speak ASCII :-( but I admit to entering the data while watching a basketball game, so no doubt there are some real blunders. Thanks, Jim From elessar at nienna.org Thu Jul 31 16:28:26 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Thu, 31 Jul 2008 14:28:26 -0600 Subject: Hobbyist - Python vs. other languages In-Reply-To: References: Message-ID: <4892206A.4000007@nienna.org> fprintf wrote: > I have been playing with computers since I first learned to program > moving shapes on an Atari 800XL in BASIC. After many years of dabbling > in programming languages as a hobbyist (I am not a computer scientist > or other IT professional), I have never found a way to stick with a > language far enough to do anything useful. I learn all about loops > and data structures and functions/methods etc. but never get to create > a program that will do anything of value that I can't more easily do > via freeware. Well, except the slot car timing system I wrote in C++ > for Linux many moons ago. > > Honestly Python seems like a breath of fresh air and possibly a way to > get back to my BASIC roots, you know, programming just for the fun of > it. > > Since I don't have a specific problem to solve, besides > Pythonchallenge (which I found very cryptic), and Project Euler (which > I found beyond my mathematics skills), is there a place to go for > increasingly difficult problems to solve? I have followed a number of > the recommended online tutorials that contain a logical progression of > problems and yet they all end at the point where a person has enough > knowledge of the syntax, but not really enough to do anything. > -- > http://mail.python.org/mailman/listinfo/python-list > My situation's a bit different because I code for a living, but I also code sometimes for the heck of it. I come up with small, hobby projects one of two ways. (1) There's a whole lot of comp sci stuff out there that I don't know. So when I come across a new concept, pattern, etc., I write a little implementation. E.g., one day I was reading about how someone used memoization in a certain problem (don't remember what), so I thought "I bet I could do that as a decorator." So I did. (2) If you have some simple task, write a program to do it (even if there's a program out there already). E.g., I recently took a trip to Japan and decided to learn the kana before going. I found a website to help me learn them, then implemented my own version in Python for the heck of it. If you just examine the things you do with a computer, and challenge yourself "I bet I can do that in 100 lines of Python," I think you'll find no shortage of projects. -Matt From piyush.subscription at gmail.com Tue Jul 29 00:17:13 2008 From: piyush.subscription at gmail.com (Piyush Anonymous) Date: Tue, 29 Jul 2008 09:47:13 +0530 Subject: Dynamically adding methods to a class... Message-ID: <19ac19520807282117y4c34ed22n3bcb9c6cf7d198b8@mail.gmail.com> class MyObject: def __init__(self, name): self.name = name def do_this_default(self): print "default do_this implementation for %s" % self.name def custom_do_this(): #method to be added print "custom do_this implementation for %s" % self.name def funcToMethod(func,clas,method_name=None): """Adds func to class so it is an accessible method; use method_name to specify the name to be used for calling the method. The new method is accessible to any instance immediately.""" import new method = new.instancemethod(func,None,clas) print method if not method_name: method_name=func.__name__ clas.__dict__[method_name]=func myobj = MyObject('myobj1') funcToMethod(custom_do_this,MyObject) #trying 2 add method to class not instance print myobj.custom_do_this() --- Error I am getting; TypeError: custom_do_this() takes no arguments (1 given) Why am I getting it? Also how can I do this in new style class (inherited from 'object')? -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at hope.cz Fri Jul 25 14:37:20 2008 From: python at hope.cz (Johny) Date: Fri, 25 Jul 2008 11:37:20 -0700 (PDT) Subject: Python program as daemon? Message-ID: <8bb6bd1a-cd85-4b7a-8fc9-844f3794bca0@c58g2000hsc.googlegroups.com> Is it possible to run a Python program as daemon? Thanks From tjreedy at udel.edu Wed Jul 16 19:51:37 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 Jul 2008 19:51:37 -0400 Subject: python's YENC.DECODE -> weird output In-Reply-To: <0807160233556.16Jul08$rookswood@suburbian.com> References: <0807160233556.16Jul08$rookswood@suburbian.com> Message-ID: John Savage wrote: > I save posts from a midi music newsgroup, some are encoded with > yenc encoding. This gave me an opportunity to try out the decoders > in Python. The UU decoder works okay, but my YENC effort gives > results unexpected: > > import yenc, sys > > fd1=open(sys.argv[1],'r') > #yenc.encode(sys.argv[1],"outfile.yenc",bytes=0) > yenc.decode(sys.argv[1],"outfile.mid",bytes=0,crc_in='') > > I confirmed that yenc.decode exactly reverses yenc.encode, BUT the > encoding itself seems to differ from the USENET standard. I do not believe that there really is a yenc standard. I have noticed that the yenc decoder in Mozilla Thunderbird never decodes posts from certain posters (and hence certain encoders) whereas uu decoding only sporadically fails. From stodge at gmail.com Wed Jul 9 11:44:27 2008 From: stodge at gmail.com (Stodge) Date: Wed, 9 Jul 2008 08:44:27 -0700 (PDT) Subject: Boost Python - C++ class' private static data blown away before accessing in Python? References: Message-ID: <99b74b4f-935d-44e7-a578-99b8ae71ef60@34g2000hsf.googlegroups.com> I wonder if it's a DLL boundary problem. On Jul 5, 11:14?pm, Giuseppe Ottaviano wrote: > > In Python, I retrive an Entity from the EntityList: > > > elist = EntityList() > > elist.append(Entity()) > > elist.append(Entity()) > > > entity = elist.get_at(0) > > > entity.foo() > > > But it crashes inside foo() as the private static data is empty; or > > rather the string array is empty. I know before that point that the > > private static data is valid when accessed earlier by the C++ code as > > the program works fine. It just won't work from Python, so somehow the > > private static data has been blown away but I can't work out where or > > why. > > Probably it is a problem of lifetime. What is the signature of append? ? > Who deletes the appended Entity in C++ code? > If append takes a raw pointer, Boost.Python copies the pointer but ? > destroys the Entity object because it is a temporary and its reference ? > count went to zero. So the pointer in the list is referring to a ? > destroyed object, which results in undefined behaviour. > > Did you have a look at the lifetime policies of Boost.Python? The ? > simplest way to workaround the problem is using const reference ? > arguments, and always use value semantics. If it can result in a ? > performance penalty, another simple way is using shared_ptr's, which ? > have their own reference count (different from the one in CPython ? > lib), but Boost.Python does the magic to make them work together. > > HTH, > Giuseppe From stefan_ml at behnel.de Wed Jul 30 02:25:53 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 30 Jul 2008 08:25:53 +0200 Subject: elementtree and rounding questions In-Reply-To: References: Message-ID: <48900971$0$11730$9b4e6d93@newsspool1.arcor-online.net> jyoung79 at kc.rr.com wrote: > ============================================================ > > > > > > > > > > ============================================================ You can exploit the structure: the Elements you are looking for do not have children, but they do have a "name" attribute. declarations = [ fontData for fontData in root.getiterator('fontData') if fontData.get("name") ] This gives you a list of all "fontData" Elements that declare a font name. The one you want is the last one, i.e. declarations[-1]. You can also do font_names = [ fontData.get("name") for fontData in root.getiterator('fontData') if fontData.get("name") ] or something like that. And if you only want the fontData Elements that appear in the template Elements, try findall instead of getiterator: tree.findall("//template//fontData") ("//" means: descend into the subtree, while "/" would mean: look only at the direct children). > f = root.getiterator('fonts') > n = f[-1].getiterator('fontData') You should not rely on ET returning a list from ".getiterator()", so avoid using f[-1] here. > fntList = [] > f = root.getiterator('fonts') > n = f[-1].find('fontData') > for i in n: > fntList.append(i.get('name')) > > print fntList > ============================================================ > > This code just gave me ['Courier']. Now if I change 'find' to 'findall' then I'll get [None, 'Helvetica']. Not exactly sure what exactly that's doing. The first value (None) comes from the "fontData" Element that does not have a "name" attibute. The path expression "fontData" means: find all children that are named "fontData". As above, what you want is ".//fontData". Stefan From naude.jaco at gmail.com Wed Jul 23 08:22:19 2008 From: naude.jaco at gmail.com (Jaco Naude) Date: Wed, 23 Jul 2008 05:22:19 -0700 (PDT) Subject: Undefined calling conventions in Python.h References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> <216dcee8-ad3d-4ae1-ac4a-4f4819775c7e@d1g2000hsg.googlegroups.com> Message-ID: On Jul 23, 2:08?pm, Ben Sizer wrote: > On Jul 23, 11:43?am, Jaco Naude wrote: > > > What Visual C++ is doing is that it is looking for mangled names since > > it does not know the DLL contains C functions. I've managed to work > > around this by declaring the Python functions as follows before using > > them in the C++ application side: > > > extern "C" > > { > > ? ? void Py_Initialize(void); > > > } > > You should put the extern block around the #include call > rather than individual functions, as surely the C calling convention > should apply to everything within. > > > It is probably more of a C++ question it turns out, but I would think > > that someone in the Python group would use the Python DLL in C++. > > More of a Visual C++ question specifically, since the __clrcall prefix > is a MS specific extension (http://msdn.microsoft.com/en-us/library/ > ec7sfckb(VS.80).aspx). If you're not using managed code in your app, > disable it in the project/build options. If you are, then perhaps you > just need to specify that you're not with this DLL, though I've never > had to deal with anything like that myself. > > -- > Ben Sizer Fredrik, thanks for the help. I'm not sure why but it seems to work now even if I don't include the extern "C" command. It also works with both Python.h files (after I copied pyconfig.h from the PC folder). So it seems like everything is working now. Ben, Thanks for the reply. Good suggestion to place the extern "C" around the include. I will remember that. It turns out that it works without that as well in the end. As for the question on managed code: My application do use managed code. I've been able to turn this off when I created the Python DLL and it seems to work. Thanks for all the help, All the best Jaco From socyl at 987jk.com.invalid Tue Jul 29 16:22:16 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 20:22:16 +0000 (UTC) Subject: iterating "by twos" References: Message-ID: Thanks for all the replies. I learned a lot! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From deets at nospam.web.de Tue Jul 29 18:46:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 30 Jul 2008 00:46:30 +0200 Subject: Python: SPREE HELP (willing to pay someone) In-Reply-To: References: <25fb9200-9be5-456f-b711-804a830b3297@m44g2000hsc.googlegroups.com> Message-ID: <6f9ku6Fahtg6U1@mid.uni-berlin.de> > I cannot help but wonder if this is spam meant to drive traffic to the > site. If yes, you just managed to increase its visibility by quoting the whole post including the post. Diez From castironpi at gmail.com Wed Jul 30 22:29:58 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 30 Jul 2008 19:29:58 -0700 (PDT) Subject: undo a dictionary References: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> <192b4786-85b2-43d3-bb7c-b5716068ff12@56g2000hsm.googlegroups.com> Message-ID: On Jul 30, 8:07?pm, "Gabriel Genellina" wrote: > En Wed, 30 Jul 2008 16:14:31 -0300, mmm escribi : > > > > >> > And for that matter a way to create a > >> > dictionary from a set of variables (local or global). > > >> You have to be more specific: there are {} displays and dict(args) call > >> and other methods. ?Read the manual. > > > My desire is to take a set of data items in an alpha-numeric range and > > oput them into a dictionary > > > i.e., > > x1=1 > > x2=20 > > x3=33 > > > to yield ?the dictionary > > > { 'x1':1, 'x2':20, 'x3':33 } > > > without having to type in as above but instead invoke a function > > dict(x1=1, x2=20, x3=33) does the same thing. > > Or, do you mean you already have those names and values, perhaps mixed ? > with a lot more names, and want to extract only those starting with "x" ? > and following with a number? > > result = {} > for name, value in vars(): # or locals().items(), or globals().items(), or ? > vars(some_module) > ? ?if name[0]=='x' and name[1:].isdigit(): > ? ? ?result[name] = value > > -- > Gabriel Genellina You can also use a blank class instance, and update its __dict__ member with the dictionary you design. >>> class A: pass ... >>> d= { 'x1': 0, 'x2': set( ) } >>> A.__dict__ {'__module__': '__main__', '__doc__': None} >>> A.__dict__.update( d ) >>> A.__dict__ {'x2': set([]), '__module__': '__main__', 'x1': 0, '__doc__': None} >>> A.x1 0 >>> A.x2 set([]) >>> I agree that locals( ) shouldn't necessarily be read-only, and I believe it would extend the power of Python if it weren't. From martin at v.loewis.de Fri Jul 11 03:07:35 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 11 Jul 2008 09:07:35 +0200 Subject: Python 3.0 and removal of the 'string' module In-Reply-To: <87iqvdq6qz.fsf@benfinney.id.au> References: <87wsjtqiyo.fsf@benfinney.id.au> <87iqvdq6qz.fsf@benfinney.id.au> Message-ID: <487706b7$0$9695$9b622d9e@news.freenet.de> > This is rather disappointing. Is that entire page suspect? All documentation about Python 3 is suspect until Python 3 gets actually released (nobody can say for sure how the release will look like in all details). Wiki pages, traditionally, are always suspect for incorrect or outdated information, IMO. It's in the nature of Wikis. Regards, Martin From torriem at gmail.com Sat Jul 12 12:29:59 2008 From: torriem at gmail.com (Michael Torrie) Date: Sat, 12 Jul 2008 10:29:59 -0600 Subject: Confused In-Reply-To: <000001c8e417$c2b5bc50$0a01a8c0@HOMEPC> References: <000001c8e417$c2b5bc50$0a01a8c0@HOMEPC> Message-ID: <4878DC07.9000302@gmail.com> eric.butteriss wrote: > Please tell me why may mail is being returned. The message says I > have been blacklisted...for what reason? I never open mail that I > know is not expected and I never send junk or spam. I am trying to > send important info to my cousin. Now I'm confused. Is the python mailing list blacklisting you? Unless this is a python-related thing, I doubt you'll find anyone here who can help. From hat at se-162.se.wtb.tue.nl Thu Jul 10 02:39:39 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 10 Jul 2008 08:39:39 +0200 Subject: TypeError, I know why but not how!? References: <03cbb0d2-6a0c-4b86-a75e-b73c5677acc7@c65g2000hsa.googlegroups.com> Message-ID: On 2008-07-10, ssecorp wrote: > > def validate(placed): > student = round(random.random()*401) > if student in placed: > validate(placed) > else: > placed.append(student) > return student, placed > > def pair(incompatibles, placed): > student1, placed = validate(placed) > student2, placed = validate(placed) > pair1 = (student1,student2) > pair2 = (student2,student1) > if (pair1 or pair2) in incompatibles: > placed.remove(student1) > placed.remove(student2) > pair(incompatibles, placed) > else: > return pair1, placed > > def generateList(dormlist,incompatibles, placed, rooms): > if len(dormlist) < (rooms + 1): > room, placed = pair(incompatibles, placed) > dormlist.append(room) > generateList(dormlist,incompatibles,placed,rooms) > else: > return dormlist In each of the above functions, the 'if' part has no 'return', while the 'else' part has. You should add a 'return' statement at every exit from the function. If you don't expect the program to get at some point, you should add a check like raise ValueError("This shouldn't happen") you'd be surprised how often 'impossible' things do happen (and writing such a statement costs less than a minute, and saves you many hours debugging). Some people so as far as demanding that there is exactly 1 return statement, namely at the bottom of the function. While I don't favor that approach, it may help you in always returning a value. BTW: For performance and readability, you may want to replace your direct recursion with iterations. Albert From jaywgraves at gmail.com Mon Jul 7 09:16:28 2008 From: jaywgraves at gmail.com (jay graves) Date: Mon, 7 Jul 2008 06:16:28 -0700 (PDT) Subject: I am looking for svn library(module) References: <6e1097a0-2a99-4885-a1ef-0684af5aa6a1@d1g2000hsg.googlegroups.com> Message-ID: <566b1cc4-79aa-4b05-8129-a1bed2baed61@l64g2000hse.googlegroups.com> On Jul 7, 7:49?am, sni... at gmail.com wrote: > Hi, > I am looking fo svn library(module) which is used in the svn- > mailer(http://opensource.perlig.de/svnmailer/) project. Does anybody > know where can I find it(download url)? This is information which I > received from python error: > from svn import core as svn_core > ImportError: No module named svn > Best regards I believe that it is the python binding provided by Subversion. You didn't say what platform you are on or what version of SVN you are using so I can't point you any closer than: http://subversion.tigris.org/ HTH ... Jay Graves From ldo at geek-central.gen.new_zealand Fri Jul 25 00:36:47 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 25 Jul 2008 16:36:47 +1200 Subject: Broken examples References: Message-ID: In message , norseman wrote: > Lawrence D'Oliveiro wrote: > >> In message , norseman >> wrote: >> >>> The OOo examples do not work. >> >> I have done OOo scripting in Python. What exactly does not work? > > soffice "-accept=socket,host=localhost,port=2002;urp;" & > sleep 9 > > ./python ./zhw.py I've never tried that. I've run Python scripts from the "Tools/Macros/Run Macro..." dialog. From noZ.spamZ at ZZ.ZsvpZ.com Tue Jul 29 18:30:14 2008 From: noZ.spamZ at ZZ.ZsvpZ.com (Michel Claveau - NoSpam SVP ; merci) Date: Wed, 30 Jul 2008 00:30:14 +0200 Subject: Python COM In-Reply-To: <6f8dgfFabuohU1@mid.uni-berlin.de> References: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> <488eff34$0$869$ba4acef3@news.orange.fr> <6f8dgfFabuohU1@mid.uni-berlin.de> Message-ID: <488f9c24$1$12756$426a74cc@news.free.fr> Re! Pywin32 can use dynamic COM server (without tlb). Therefore, I prefer to wait the return from birdprince... @-salutations -- Michel Claveau From Lie.1296 at gmail.com Sat Jul 26 06:48:18 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 26 Jul 2008 03:48:18 -0700 (PDT) Subject: re.findall(a patern,'function(dsf sdf sdf)') References: <8fc6d72a-cfc5-4e9d-af56-a009a464c6bb@27g2000hsf.googlegroups.com> Message-ID: On Jul 26, 5:03?pm, gcmart... at gmail.com wrote: > H! > > First I have some random string below. > > bla = """ ? ? ? ? ? ? ? ? """ > > Now I'm trying to get each BlaObject with the first (variable) > function argument > First of all, since you're dealing with Javascript, which is case- sensitive, Blaobject and BlaObject means different thing, if the dummy code is real, it'd have raised a name not found error. > And I can say that this isn't working > for a in re.findall(r'([BlaObject ])(.*)([)] *)',bla): > ? ? print a Of course that doesn't work, you've put BlaObject in a square bracket (character class notation), which means the re module would search for _a single letter_ that exist inside the square bracket. Then you do a '.*', a greedy match-all, something that you generally don't want to do. Next is the '[)] *', a character class containing only a single character is the same as the character itself, and the zero-or-more- repetition (*) is applied to the white space after the character class, not to the character class itself. In short, the regular expression you used doesn't seem to be an effort to solve the problem. In other words, you haven't read the regular expression docs: http://docs.python.org/lib/module-re.html . In other words, it's useless to talk with you until then. (snip) From rkmr.em at gmail.com Sun Jul 27 22:26:09 2008 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Sun, 27 Jul 2008 19:26:09 -0700 Subject: write unsigned integer 32 bits to socket In-Reply-To: References: Message-ID: On Sun, Jul 27, 2008 at 7:17 PM, Larry Bates wrote: > rkmr.em at gmail.com wrote: >> On Sun, Jul 27, 2008 at 7:01 PM, Larry Bates >> wrote: >>> rkmr.em at gmail.com wrote: >>>> i want to send unsigned 32 bit integer to socket, and looking for >>>> something equivalent to this method... >>>> >>>> http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt() >>>> >>>> is there such method / library available in python?! >>> >>> You will need to use struct module to build the 4 byte value and then >>> send >>> it. >>> >>> Something like (not tested): >>> >>> import struct >>> us32bit = struct.pack("I", value) >>> s.send(us32bit) >> >> thanks a lot!!! >> >> just to make sure if I want 32 bit or 4 bytes then should I use the >> short or integer or long? >> >> this is short >>>>> >>>>> struct.pack('!h',3) >> >> '\x00\x03' >> >> this is integer >>>>> >>>>> struct.pack('!i',3) >> >> '\x00\x00\x00\x03' >> >> this is long >>>>> >>>>> struct.pack('!l',3) >> >> '\x00\x00\x00\x03' > > Short is 16 bits, Integer is 32 bits, long is 64 bits (as I read and have > found). thanks a lot!!! re-read it again!!! from the struct doc! Standard size and alignment are as follows: no alignment is required for any type (so you have to use pad bytes); short is 2 bytes; int and long are 4 bytes; long long (__int64 on Windows) is 8 bytes; float and double are 32-bit and 64-bit IEEE floating point numbers, respectively. From dickinsm at gmail.com Fri Jul 18 18:05:46 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 18 Jul 2008 15:05:46 -0700 (PDT) Subject: round function error??? References: Message-ID: <2da2f5f1-7ff2-46d7-a768-f0817e414615@f36g2000hsa.googlegroups.com> On Jul 18, 10:17?pm, Anthony wrote: > Isn't this a mistake??? Which 'this'? That is, what were you expecting? If you're objecting to the fact that the second result produces 3499.3499999999999 instead of 3499.35, then no, that's not a mistake; see http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate for more information. But I'm guessing that you're questioning the fact that a value that's apparently *less* than 3499.35 is rounded up to 3499.4, rather than down to 3499.3. ? Then yes, I'd agree that's less than ideal, though I don't consider it a particularly serious bug. It's been on my list of things to fix for a while. (See http://bugs.python.org/issue1869 ). Contributions welcome! Mark From paul at boddie.org.uk Thu Jul 24 11:46:29 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 24 Jul 2008 08:46:29 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: On 24 Jul, 12:02, "Sebastian \"lunar\" Wiesner" wrote: > > Fortunately, Python isn't designed according to your ideas, and won't > change, so consider your posting a waste of time. This is the kind of petty response that serves only to shut down discussion that might actually lead to genuine attempts to remedy issues (or "warts") with Python. Although the tone of the complaint was badly chosen, it is always worth jumping over the fence and considering whether things could be made better. Without complaints being aired, how do you expect any advances around things like the "old and outdated modules in the standard library, or real showstoppers in Python (e.g. the GIL)" that you mention elsewhere? > If feeling like bringing such old "issues" up again next time, spend > your time learning another programming language, as you would > obviously not get happy with Python anyway ... Such a constructive response that is! Instead, I think it is interesting to consider why methods still require an explicit "self" parameter - something which has been discussed previously - and whether there might be a case for omitting it from the signature - perhaps in a variant of Python - in methods which are defined within class definitions (as opposed to those assigned to classes later). Indeed, there's scope for experimentation with Python variants, just to investigate whether certain features added to CPython can be considered essential, and which features might be considered of marginal benefit. I recall that some features (eg. lexical scoping and closures) were eventually added to Python partly to remedy issues with lambda definitions, but also because the lack of such features was cited repeatedly by proponents of other languages. In such a climate, it can be easier to "meet the challenge" and implement features to silence the critics rather than to insist that they are of marginal benefit (although it's interesting to note this in a thread where improvement suggestions are deemed "a waste of time" - I suppose the community is now more resistant to suggestions from "unofficial" sources). A review of such language "enhancement" decisions would be interesting, but since one shouldn't expect this from the CPython implementers, I feel that it is the role of others to do so in their own experiments. Of course, such experiments are often derided as "lesser Pythons" or misunderstood, but that's another unfortunate trait exhibited by parts of the Python community. Paul From peter.anderson at internode.on.net Tue Jul 15 09:54:46 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Tue, 15 Jul 2008 23:54:46 +1000 Subject: Python internals question Message-ID: <487CAC26.9050904@internode.on.net> Hi! I am slowly teaching myself Python. I was reading David Beazley's excellent book "Python - Essential Reference"; in particular about variables. Let me quote: "Python is a dynamically typed language in which names can represent values of different types during the execution of a program. In fact the names used in the program are really just labels for various quantities and objects. The assignment operator simply creates an association between a name and a value. This is different from C, for example, in which a name (variable) represents a fixed size and location in memory..." As an old mainframe programmer, I understand the way C does things with variable but this text got me wondering how Python handles this "association" between variable name and value at the lower level. Is it like a fifo list? If there is any Python guru that can help I would be most interested in your thoughts. Regards, Peter -- Peter Anderson There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things ? Niccolo Machiavelli, /The Prince/, ch. 6 From laredotornado at zipmail.com Tue Jul 29 10:53:53 2008 From: laredotornado at zipmail.com (laredotornado) Date: Tue, 29 Jul 2008 07:53:53 -0700 (PDT) Subject: How do I include a shell variable in my script? Message-ID: Hi, I'm running a Python script on a Solaris 9 machine, invoking the Python script from ksh, if that matters. There is an enviornment variable, $JAVA_HOME, that I would like to include in my script, replacing "/path/to/java/home'" with the value of $JAVA_HOME. java_home='/path/to/java/home' How do I do this? If I need to pass a command line argument, so be it, but I figure there is a more direct way to get the value. Thanks, - Dave From arkanes at gmail.com Thu Jul 31 13:27:41 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 31 Jul 2008 12:27:41 -0500 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: <4866bea60807311027g521a00e7i9bfe0ce2776863bb@mail.gmail.com> On Tue, Jul 29, 2008 at 3:37 AM, Carl Banks wrote: > On Jul 28, 8:15 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: >> > On Jul 28, 10:00 am, Steven D'Aprano > > cybersource.com.au> wrote: >> >> Cutting to the crux of the discussion... >> >> >> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: >> >> > I want something where "if x" will do but a simple explicit test >> >> > won't. >> >> >> Explicit tests aren't simple unless you know what type x is. If x could >> >> be of any type, you can't write a simple test. Does x have a length? Is >> >> it a number? Maybe it's a fixed-length circular length, and the length >> >> is non-zero even when it's empty? Who knows? How many cases do you need >> >> to consider? >> >> > Use case, please. I'm asking for code, not arguments. Please give me a >> > piece of code where you can write "if x" that works but a simple >> > explicit test won't. >> >> I gave you a piece of code, actual code from one of my own projects. If >> you wouldn't accept that evidence then, why would you accept it now? > > I would accept as "evidence" something that satisfies my criteria, > which your example did not: it could have easily (and more robustly) > been written with a simple explicit test. I am looking for one that > can't. > > You keep bringing up this notion of "more complex with no benefit", > which I'm simply not interested in talking about that at this time, > and I won't respond to any of your points. I am seeking the answer to > one question: whether "if x" can usefully do something a simple > explicit test can't. Everyone already knows that "if x" requires > fewer keystrokes and parses to fewer nodes. > I'm really not sure where you're going with this or what you're trying to prove. "if x" is a duck-type test for a boolean value. Obviously if you know the type and want a more *specific* test, then you can use an explicit one. Any time you don't know or don't care about a more specific type than "something which probably is boolean true", or any time where you know the boolean semantics of the type and want to drop some typing, you can use "if x". The more specific test is what you'd use if you want more specific results. What's complicated about this idea? From pavlovevidence at gmail.com Thu Jul 17 02:46:36 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 16 Jul 2008 23:46:36 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Message-ID: On Jul 16, 6:20?pm, Craig Allen wrote: > Anyone have any comments? ?Is there anything wrong, evil, or ugly > about using a module this way, or am I correct to think that actually, > this is a common approach in python. > > Is it pythonic? The one drawback to this is that it could require lots of globals definitions. Whereas in a regular class you could do this: def something(self): self.var = 1 self.max = 10 using a module as a singleton you'd be doing this: def something(): global var global max var = 1 max = 10 If you have a lot of "attributes" of your module to redefine, I'd suggest taking steps to avoid globals. The most straightforward way is to define a self variable in your module that is bound to the module itself, and access all "attributes" through that. The following code should suffice (though it may not work in some corner cases): self = sys.modules[__name__] So then you could rewrite the something method like so: def something(): self.var = 1 self.max = 10 [Another possibility, and this is what I do, is to use a function decorator that passes the module in as the first argument. I have reasons for doing it but it doesn't do anything the above method does. It would be used like this: @modmethod def something(self): self.var = 1 self.max = 10 ] Carl Banks From RonV at Nospam.com Sat Jul 12 12:08:02 2008 From: RonV at Nospam.com (RV) Date: Sat, 12 Jul 2008 12:08:02 -0400 Subject: Can anyone suggest a date peocedure... References: Message-ID: <7flh74peqavr4uvogmoo7ergas1hcjsvjs@4ax.com> On Thu, 10 Jul 2008 20:04:27 -0400, RV wrote: Gary, Larry, Michiel , Thanks very much, your helpful info has enabled me to get past a learning bump. Ron From alexnbryan at gmail.com Tue Jul 15 13:49:32 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 15 Jul 2008 10:49:32 -0700 (PDT) Subject: Testing for Internet Connection In-Reply-To: <1216113021.24038.0@proxy02.news.clara.net> References: <18460572.post@talk.nabble.com> <1216113021.24038.0@proxy02.news.clara.net> Message-ID: <18471183.post@talk.nabble.com> Alex Marandon-3 wrote: > > Alexnb wrote: >> I am wondering, is there a simple way to test for Internet connection? If >> not, what is the hard way :p > > Trying to fetch the homepage from a few major websites (Yahoo, Google, > etc.)? If all of them are failing, it's very likely that the connection > is down. You can use urllib2 [1] to accomplish that. > > [1] > -- > http://mail.python.org/mailman/listinfo/python-list > > What exactly do you think will work? I am not sure what you think I should do? If I use urlopen("http://www.google.com") and I am not connected, I am not going to get an exception, the program will fail. -- View this message in context: http://www.nabble.com/Testing-for-Internet-Connection-tp18460572p18471183.html Sent from the Python - python-list mailing list archive at Nabble.com. From cmake-bounces at cmake.org Thu Jul 24 18:43:34 2008 From: cmake-bounces at cmake.org (cmake-bounces at cmake.org) Date: Thu, 24 Jul 2008 18:43:34 -0400 Subject: Your message to CMake awaits moderator approval Message-ID: Your mail to 'CMake' with the subject Status Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. If you would like to cancel this posting, please visit the following URL: http://www.cmake.org/mailman/confirm/cmake/42b7f3960ed3942796005bcc10ef862779cd7985 From frankrentef at yahoo.com Tue Jul 29 14:30:44 2008 From: frankrentef at yahoo.com (frankrentef) Date: Tue, 29 Jul 2008 11:30:44 -0700 (PDT) Subject: Python / PAMIE - scriptWrite Function References: Message-ID: <5562e1cc-21a9-4740-a5d9-8bec67e7d32a@34g2000hsh.googlegroups.com> On Jul 29, 1:26?pm, frankrentef wrote: > In using PAMIE 2.0 specifically the "scripWrite" function I'm getting > the following error... > > File "C:\Python23\Lib\site-packages\win32com\client\dynamic.py", line > 489, in _getattr_ > > further states... > > raise AttributeError, "%s.%s" % (self._username_, attr) > > Help... :) Further messages found are: C:\Python23\lib\site-packages\win32com\client\dynamic.py:476: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up debug_attr_print("Getting property Id 0x%x from OLE object" % retEntry.dispid) From deets at nospam.web.de Wed Jul 9 06:53:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Jul 2008 12:53:19 +0200 Subject: start reading from certain line References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> Message-ID: <6djjmfF2tamgU1@mid.uni-berlin.de> antar2 wrote: > I am a starter in python and would like to write a program that reads > lines starting with a line that contains a certain word. > For example the program starts reading the program when a line is > encountered that contains 'item 1' > > > The weather is nice > Item 1 > We will go to the seaside > ... > > Only the lines coming after Item 1 should be read Start reading each line, and skip them until your criterion matches. Like this: def line_skipper(predicate, line_iterable): for line in line_iterable: if predicate(line): break for line in line_iterable: yield line Diez From anonymous at anonymous.com Mon Jul 14 08:51:06 2008 From: anonymous at anonymous.com (anonymous) Date: Mon, 14 Jul 2008 12:51:06 GMT Subject: Python beginner, unicode encode/decode Q Message-ID: <487B4BC5.7FA8FFF9@anonymous.com> 1 Objective to write little programs to help me learn German. See code after numbered comments. //Thanks in advance for any direction or suggestions. tk 2 Want keyboard answer input, for example: answer_str = raw_input(' Enter answer > ') Herr ?? [ I keyboard in the following characters Herr ?? ] print answer_str Output on screen is > Herr ?? 3 history 1 and 2 code run interactively under Debian Linux Python 2.4 and interactively under windows98, first edition IDLE, Python 2.3.5 and it works. 4 history 3 and 4 code run from within a .py file produce different output from example in book. 5 want to operate under Debian Linux but because the program failed under Linux when I tried to run the code from a file in Linux Python, I thougt I should fire up the win98 Idle/python program and try it to see if ran there but it failed, too from within a file. 6 The sample code is from page 108-109 of: "Python for Dummies" It says in the book: "Python's file objects and StringIO objects don't support raw Unicode; the usual workaround is to encode Unicode as UTF-8 before saving it to a file or stringIO object. The sample code from the book is French as indicate here but trying German produces the same result. 7 I have searched the net under all the keywords but this is as close as I get to accomplishing my task. I suspect I may not be understanding: StringIO objects don't support raw Unicode, but I don't know. #_*_ coding: utf-8 _*_ # code run under linux debian interactively from a terminal and works print " u'Libert\u00e9' " # y = raw_input('Enter >') commented out y = u'Lbert\u00e9' y.encode('utf-8') q = y.encode('utf-8') q.decode('utf-8') print q.decode('utf-8') history 1 works and here is the screen copy of interactive >>> y = raw_input ('>') >Libert\xc3\xa9 >>> q = 'Libert\xc3\xa9' >>> q.decode('utf-8') u'Libert\xe9' >>> print q Libert? >>> [ screen output is next line ] Lbert? history 2 # code run under win98, first edition, within IDLE interactively and succeeded in produce correct results. # y = raw_input('Enter >') commented out y = u'Lbert\u00e9' y.encode('utf-8') q = y.encode('utf-8') q.decode('utf-8') print q.decode('utf-8') history 1 works and here is the screen copy of interactive >>> y = raw_input ('>') >Libert\xc3\xa9 >>> q = 'Libert\xc3\xa9' >>> q.decode('utf-8') u'Libert\xe9' >>> print q Libert? >>> [ screen output is next line ] Lbert? # history 3 # this code is run from within idle on win98 and inside a python file. # The code DOES NOT produce the proper outout. #_*_ coding: utf-8 _*_ # print "u'Libert\u00e9'" printed to screen y = raw_input('Enter >') # y = u'Lbert\u00e9' commented out y.encode('utf-8') q = y.encode('utf-8') q.decode('utf-8') print q.decode('utf-8') # output is on the lines below was produced on the screen after run enter u'Libert\u00e9' on screen to copy into into y string Enter >u'Libert\u00e9' u'Libert\u00e9' The code DOES NOT produce Libert? but instead produce u'Libert\u00e9' # history 4 # this code is run from within terminal on Debian linux inside a python file. # The code does not produce proper outout but produces the same output as run on # windows. #_*_ coding: utf-8 _*_ print "u'Libert\u00e9'" printed to screen y = raw_input('Enter >') # y = u'Lbert\u00e9' commented out y.encode('utf-8') q = y.encode('utf-8') q.decode('utf-8') print q.decode('utf-8') # output is on the lines below was produced on the screen after run enter u'Libert\u00e9' on screen to copy into into y string Enter >u'Libert\u00e9' u'Libert\u00e9' The code DID NOT produce Libert? but instead produce u'Libert\u00e9' From paddy3118 at googlemail.com Sun Jul 20 15:17:57 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 20 Jul 2008 12:17:57 -0700 (PDT) Subject: question References: Message-ID: On Jul 20, 6:39?pm, wrote: > Nobody any sensible answers. Too complicated I suppose! The sensible question was? From xkenneth at gmail.com Mon Jul 7 17:38:28 2008 From: xkenneth at gmail.com (xkenneth) Date: Mon, 7 Jul 2008 14:38:28 -0700 (PDT) Subject: Standard Equation Description Language? Message-ID: <1cd1baf2-9816-4ac1-91ea-90f148167549@t54g2000hsg.googlegroups.com> Does anyone know of a standard inter-language syntax for describing scientific/mathematical equations? Preferably something with parsers in multiple libraries. Regards, Kenneth Miller From michele.simionato at gmail.com Thu Jul 10 07:54:45 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 10 Jul 2008 04:54:45 -0700 (PDT) Subject: FOSS projects exhibiting clean/good OOP? References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> Message-ID: <5c3e8cf2-ffae-4930-8f2f-d8bc081518c0@56g2000hsm.googlegroups.com> On Jul 9, 4:38?pm, Phillip B Oldham wrote: > I'm wondering whether anyone can offer suggestions on FOSS projects/ > apps which exhibit solid OO principles, clean code, good inline > documentation, and sound design principles? > > I'm devoting some time to reviewing other people's code to advance my > skills. Its good to review bad code (of which I have more than enough > examples) as well as good, but I'm lacking in finding good examples. > > Projects of varying sizes would be great. I vote for the doctest module in the standard library. From mattheww at chiark.greenend.org.uk Tue Jul 29 16:25:44 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 29 Jul 2008 21:25:44 +0100 (BST) Subject: Boolean tests References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8d <87y73kg70u.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > No, he retracted the *insult* and restated the *advice* as a distinct > statement. I think it's quite worthwhile to help people see the > difference. Ben, it was quite clear from Anders' post that he knows about __nonzero__ . That's why the so-called advice is insulting. The original phrasing was just the icing on the cake. -M- From ironfroggy at gmail.com Thu Jul 17 08:35:30 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Thu, 17 Jul 2008 08:35:30 -0400 Subject: Getting a unknown word out of a list with no spaces In-Reply-To: <18502758.post@talk.nabble.com> References: <18502758.post@talk.nabble.com> Message-ID: <76fd5acf0807170535s63ea3d41m8b42850671a9dad6@mail.gmail.com> BeautifulSoup. You need a good html parsing, not some one-shot code to handle one tiny unflexable pattern. On Thu, Jul 17, 2008 at 3:07 AM, Alexnb wrote: > > Hello > > Lets say I have a string: > > --a href="/browse/brick"--brick--/a-- > > The -- needs to be replaced with < or > where applicable. > > and I want the "brick" out of that string (the second brick that is). How > can I get just the "brick" out of that string? > -- > View this message in context: http://www.nabble.com/Getting-a-unknown-word-out-of-a-list-with-no-spaces-tp18502758p18502758.html > Sent from the Python - python-list mailing list archive at Nabble.com. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From rocksportrocker at googlemail.com Tue Jul 15 06:26:10 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Tue, 15 Jul 2008 03:26:10 -0700 (PDT) Subject: Python embedding question. References: <45f657a0-315f-421e-8d69-1c5b24e23887@k37g2000hsf.googlegroups.com> Message-ID: <5e0e47aa-a7bc-4e43-98cd-07fc0f6fe454@l42g2000hsc.googlegroups.com> On 15 Jul., 12:14, Thomas Troeger wrote: > Kay Schluehr wrote: > > On 15 Jul., 11:51, Thomas Troeger > > wrote: > > >> I've really looked at a lot of places but haven't found a suitable > >> solutions yet, so I'm asking here in hope that someone has experience > >> with that topic. > > > Which solutions did you rule out? > > - Python + Qt, because it's definitely overkill for my plans. I only > need simple graphics and some sound, no widgets. Basically I'm looking > for something really lightweight that has methods for drawing graphic > primitives and renders fonts -- no complicated widgets, windows, > scrollbars and the like. And, for example, the Qt library is a real > heavyweight with approx. 10 MB for qt-3.3.8 alone. > > - The same holds for cairo/pango, I've written a test program (in C, I > must say) that has dynamic links to 10 libraries that are all like 250kb > in size. That's a lot for a small embedded device. > Did you try pygame ? I think it has a small footprint. Greetings, Uwe From bignose+hates-spam at benfinney.id.au Thu Jul 24 11:09:54 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 25 Jul 2008 01:09:54 +1000 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <579f9d5b-8984-425d-8d4f-b2ed0be8eaba@o40g2000prn.googlegroups.com> Message-ID: <871w1jpbct.fsf@benfinney.id.au> Jordan writes: > Explicit is actually kinda annoying a lot of the time Yes. It is also very helpful for those who will later try to understand, interface with, debug, modify, or otherwise work with the code (including, in a great many cases, the original author of that code). The great boost that EIBTI grants to maintainability trumps, in my view, the annoyance felt by some at the time of writing the code. -- \ ?An eye for an eye would make the whole world blind.? ?Mahatma | `\ Gandhi | _o__) | Ben Finney From maric at aristote.info Wed Jul 30 11:54:27 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 30 Jul 2008 17:54:27 +0200 Subject: Standard module for parsing emails? In-Reply-To: References: Message-ID: <200807301754.28054.maric@aristote.info> Le Wednesday 30 July 2008 17:15:07 Phillip B Oldham, vous avez ?crit?: > If there isn't a standard library for parsing emails, is there one for > connecting to a pop/imap resource and reading the mailbox? > -- > http://mail.python.org/mailman/listinfo/python-list There are both shipped with python, email module and poplib, both very well documented in the official doc (with examples and all). email module is rather easy to use, and really powerful, but you'l need to manage yourself the many ways email clients compose a message, and broken php webmails that doesn't respect RFCs (notably about encoding)... -- _____________ Maric Michaud From mtobis at gmail.com Sat Jul 19 22:43:35 2008 From: mtobis at gmail.com (Michael Tobis) Date: Sat, 19 Jul 2008 19:43:35 -0700 (PDT) Subject: Not entirely serious: recursive lambda? Message-ID: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> I came across the "japh" concept today and decided to do one of my own, obviously, interpreting the 'p' somewhat loosely, http://en.wikipedia.org/wiki/JAPH but I'm not entirely satisfied with it: #### # japh, for certain values of 'p' f=lambda(r,N):N and f((" acdefijlmnopqrstuv"[N%19]+r,N/19))or(r,N) print f( ("",reduce(lambda c,m:c*95+''.join(map(chr,range(32,127))).index(m), "!b)'1Mgh0z+fYQ]g::i^<&y~g)cnE-d=K&{GMNQ1gx+ooY<~L##N'X]P2<@XYXwX3z", 0)))[0] #### it bothers me that there are two statements. (In case you are wondering what they do, it's all essentially about changing from base 95 to base 19. It's based loosely on this fine, simple recipe by Drew Perttula which I have found to be useful on several occasions: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 ) Anyway, I'd much prefer an even uglier japh like this: # does not work print (lambda(r,N):N and $$$$((" acdefijlmnopqrstuv"[N%19]+r,N/ 19))or(r,N))( ("",reduce(lambda c,m:c*95+''.join(map(chr,range(32,127))).index(m), "!b)'1Mgh0z+fYQ]g::i^<&y~g)cnE-d=K&{GMNQ1gx+ooY<~L##N'X]P2<@XYXwX3z", 0)))[0] but what would $$$$ be for an unnamed function to call itself? I realize that lambda is something of an orphan and was arguably a bad idea for anything besides obfuscation, but obfuscation is exactly my purpose here. Can a lambda call itself without giving itself a name? Google was not my friend on this one, and I suspect there is no answer. Relax, I am not going to submit a PEP about it. mt From castironpi at gmail.com Wed Jul 9 21:01:30 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 9 Jul 2008 18:01:30 -0700 (PDT) Subject: "in"consistency? References: <871c6735-f2d2-4cd0-811d-0cd774d55bdd@m45g2000hsb.googlegroups.com> Message-ID: On Jul 8, 2:25?pm, Terry Reedy wrote: > castironpi wrote: > > Strings are not containers. > > Library Reference/Built-in Types/Sequence Types says > "Strings contain Unicode characters." > Perhaps you have a different notion of contain/container. > > I prefer 'collection' to 'container' since 'container' tends to imply an > exclusiveness that is not true. ?Byte/character sequences *are* > different from tuples, lists, sets, dicts, etc, in the following sense: > members of the latter collection classes must exist first before being > added to the collection (non-exclusively). ?Members of the former do > not. ?(In CPython, at least, they do not). ?So I consider them to > (reiterable) *virtual* sequence collections that can produce > subsequences on demand, > > So I partially agree with you in that byte/char sequences are a > different sub-category. > > > Another container type: > > > Python 3.0b1 on win32 > >>>> {0} in {0,1} > > False > > And similarly, (0,) not in (0,1), [0] not in [0,1], {0:None} not in > {0:None,1:None). ?These are all general manifest collection types that > can contain any Python object, and which could contain a sub-collection > even if they do not. > > Terry Jan Reedy Under that definition, "a" in "abc" is clearly well-defined. I construe "abc" to "contain Unicode characters", specifically, "a", "b", and "c". But "ab" is not a Unicode character. "Contain" is still a good word for what strings "do", to the extent that they "do" anything at all. The fact that they contain a uniform data-type permits the extension of "in" to subset/substring testing. Compare to an imaginary "set of ints" data type: >>> a= setofints( [ 0, 1, 2 ] ) Then, the semantics of >>> b= setofints( [ 0, 1 ] ) >>> b in a True are consistent and predictable. Correct me if I'm wrong. From Russ.Paielli at gmail.com Wed Jul 30 01:58:28 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 22:58:28 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> Message-ID: <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> On Jul 29, 10:33 pm, Carl Banks wrote: > On Jul 30, 1:15 am, "Russ P." wrote: > > Having said that, it would sure be nice to be able to write > > > if myList is not empty: > > > instead of > > > if len(myList) != 0: > > I can agree with this. But I guess that could only work if there were only one empty list that represents all empty lists (as there is only one actual "None"). I don't know if that makes sense or not. From notnorwegian at yahoo.se Sun Jul 13 23:03:38 2008 From: notnorwegian at yahoo.se (maestro) Date: Sun, 13 Jul 2008 20:03:38 -0700 (PDT) Subject: while var, but var ==16 != true Message-ID: <8c2cd9ff-bec2-4844-82a8-8ce02df5663e@w7g2000hsa.googlegroups.com> why does this work? "while p" = "while p != 0" ? 1 is True and 0 is false in python but other numbers have no boolean value so why doesnt it abort. >>> p=16 >>> p 16 >>> while p: print p p -= 1 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 >>> i can also do: >>> k=[] >>> while k: k.pop() >>> k=[1,2,3] >>> while k: k.pop() 3 2 1 >>> so obv while var means while not empty or why not zero but it isnt something youd guess unless youd beeen shown it. From adamc55 at gmail.com Mon Jul 7 09:31:57 2008 From: adamc55 at gmail.com (Adam C.) Date: Mon, 7 Jul 2008 06:31:57 -0700 (PDT) Subject: Dynamically Changing the Base Class Message-ID: <6d60c362-ba17-4414-babd-2cc254526bca@c58g2000hsc.googlegroups.com> We have a situation where we want a Swig-generated Python class to have a different base (not object). It doesn't appear that we can coerce Swig into generating the class we want at present (but we are still enquiring). Is it possible to dynamically change the base class to something else? Initial experiments appear to show it is not: -------------------------------- snip -------------------------------- >>> class Foo(object): pass >>> class Foozle(object): pass >>> Foozle.__bases__ = (Foo,) Traceback (most recent call last): File "", line 1, in Foozle.__bases__ = (Foo,) TypeError: __bases__ assignment: 'Foo' deallocator differs from 'object' -------------------------------- snip -------------------------------- Is there a solution I am missing? Thanks in advance. From rw at smsnet.pl Tue Jul 8 15:43:28 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Tue, 08 Jul 2008 21:43:28 +0200 Subject: Logger Configuration References: Message-ID: <87vdzgduvz.fsf@merkury.smsnet.pl> "Robert Rawlins" writes: > Hello guys, > > > > I?ve attached an example of my logging configuration file for you to look at. > The problem I?m experiencing is that the log files are not rotating as I would > expect them to, they just keep growing and growing. > > > > Can you see any reason for this to happen? This is the first time I?ve used a > config file and not just configured the logger programmatically. I think that you should use integers instead of strings in that line: args=('/logs/application.log', 'a', '800000', '5') so it would look like this: args=('/logs/application.log', 'a', 800000, 5) HTH, Rob From norseman at hughes.net Mon Jul 7 21:00:16 2008 From: norseman at hughes.net (norseman) Date: Mon, 07 Jul 2008 18:00:16 -0700 Subject: How to make python scripts .py executable, not bring up editor In-Reply-To: References: Message-ID: <4872BC20.3080702@hughes.net> korean_dave wrote: >>From command Prompt, i type in a script, "tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? > -- > http://mail.python.org/mailman/listinfo/python-list > ====================================== I get tired of Microsoft jerking me around too. Rather than spend hours trying to undo somebody's reorganizing my system preferences I just ignore them completely. py tryme is how I do it. py.bat is a file placed in a directory listed in PATH in autoexec.bat. Edit autoexec.bat to include directory you put it in and reboot system or it won't find it. something like: PATH=.;c:\py-stuff;[anything already listed] Don't forget the semicolons. The . (period) up front means look here first. here being where ever you are when you issued the command. (The pRESENT wORKING dIRECTORY :-) The c:\py-stuff (fix to suit yourself and make sure it exists) is where you can put your efforts to be called at your leisure. Your .py files you write and use. Even the py.bat can go there. (Short note: Microsoft usually does look in pwd first. But good form dictates being specific.) contents of py.bat: ======================== rem name: py.bat @echo off c:\Python24\python %f.py make it fit your path rem end of file ======================== This way - you get what you expect, when you expect it, & nothing else. Yeah - dumb, but it works! I have one similar for each of my compilers. They contain the whole command line switches stuff as well as things like remove old stuff before trying to over write with new since MS can be temperamental about that. Easiest way in the world to give it the finger and make it behave. Steve norseman at hughes.ney From simon.peverett at gmail.com Mon Jul 14 08:31:03 2008 From: simon.peverett at gmail.com (Impotent Verse) Date: Mon, 14 Jul 2008 05:31:03 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> Message-ID: <378b8499-4b1b-4eda-bb13-91bf59c77bfc@a70g2000hsh.googlegroups.com> If keys and values are unique you could do this... -------------- # Left : Right roman = { "One" : "I", "Two" : "II", "Three" : "III", "Four" : "IV", "Five" : "V", "Six" : "VI", "Seven" : "VII", "Eight" : "VIII", "Nine" : "IX", "Ten" : "X" } left, right = zip( *roman.items() ) left = list(left) right = list(right) print left[ right.index("VIII") ] -------------- ... result is "Eight". Hmmm! zip returns tuples, which need to be turned into lists to do much with. Maybe not the best solution in this case. Verse. From magnusschuster at yahoo.com Tue Jul 29 12:13:51 2008 From: magnusschuster at yahoo.com (Magnus Schuster) Date: Tue, 29 Jul 2008 09:13:51 -0700 (PDT) Subject: proxy class and __add__ method Message-ID: <18715799.post@talk.nabble.com> Hello, I have written the following small proxy class which I expect to pass all function calls to the 'original' object: --- BEGIN --- class proxy(object): def __init__( self, subject ): self.__subject = subject def __getattr__( self, name ): return getattr( self.__subject, name ) prx_i=proxy(1) print hasattr(prx_i,'__add__') j=prx_i.__add__(1) k=prx_i+1 --- END --- Actually the "hasattr(prx_i,'__add__')" returns "True" as expected, and "j=prx_i.__add__(1)" sets j=2. But "k=prx_i+1" raises a : unsupported operand type(s) for +: 'proxy' and 'int'. How is this addition different from the previous line "j=..."? And how can I modify the proxy class so that all methods are passed on, which are not explicitly overloaded? Regards, Magnus -- View this message in context: http://www.nabble.com/proxy-class-and-__add__-method-tp18715799p18715799.html Sent from the Python - python-list mailing list archive at Nabble.com. From diordna at gmail.com Tue Jul 22 11:27:56 2008 From: diordna at gmail.com (Stephen Johnson) Date: Tue, 22 Jul 2008 11:27:56 -0400 Subject: convert list of lists to list In-Reply-To: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> References: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> Message-ID: <370A5418-B09B-4ED4-B3DE-FCBFF7564AB1@gmail.com> list_A = [['klas*', '*', '*'], ['mooi*', '*', '*', '*'], ['koe'], ['arm*', '*', '*(haar)'], ['groei*', '*', '*', '*', '*']] list_B = [] for inner_list in list_A: #join elements of list into a string with separator ' ' list_B.append(' '.join(inner_list)) print list_B Output: ['klas* * *', 'mooi* * * *', 'koe', 'arm* * *(haar)', 'groei* * * * *'] -Steve Johnson On Jul 22, 2008, at 11:10 AM, antar2 wrote: > Is there a way to convert list_of_listsA to list_of_listsB, where one > list in listof lists A is one element of listB? > > list_of_listsA: > [['klas*', '*', '*'], > ['mooi*', '*', '*', '*'], > ['koe'], > ['arm*', '*', '*(haar)'], > ['groei*', '*', '*', '*', '*']] > > listB: > ['klas* * *', 'mooi* * * *, 'koe', 'arm* * * (haar)', 'groei* * * * > *'] > > Thankx! > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.rawlins at thinkbluemedia.co.uk Sat Jul 19 10:46:34 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Sat, 19 Jul 2008 15:46:34 +0100 Subject: __del__ methods In-Reply-To: References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> Message-ID: <016a01c8e9ae$3de4b840$b9ae28c0$@rawlins@thinkbluemedia.co.uk> Hi Duncan, > That sounds like an appropriate use for __del__: it won't matter that it > may not be called when your app exits. Ok, well that's good to know. :-) > Yes, but there is an easy work-around. If you want to track destruction of > objects of type C then don't add a __del__ method to the C objects. Instead > create a separate class which does nothing but track it's own desctruction > and reference that from the class which may be leaking. > > >>> class Track(object): > def __init__(self, parent): > self.parentid = id(parent) > self.parenttype = type(parent).__name__ > def __del__(self): > print "Destroyed <%s object at %s>" % (self.parenttype, > self.parentid) > > > >>> class C(object): > def __init__(self): > self._track = Track(self) > I like this idea, I can definitely see the benefits to working with this concept. One things I will take this quick opportunity to ask, even though it's a little OT: What is the benefit of extending the base 'object' class? What does that give me that en empty, non subclassed object doesn't? > However you should also consider that __del__ only lets you log when > objects are destroyed. Using weak references may be a more useful option as > it will let you track which objects are not being destroyed: you can easily > keep a dictionary of weak references to all existing objects of interest. > Check its length periodically to see whether objects are being leaked and > then inspect the objects themselves to see which ones have leaked. > > You can use gc.get_referrers() to find everything that references a > particular objects and gradually trace backwards until you find the problem > reference (it is tricky though as any code which does this needs to ignore > its own references to the object in question). Yes, that's a very nice concept and like you say gives you quite a nice visual reference of what objects are and aren't being destroyed. Cheers Duncan, Robert From sk8in_zombi at yahoo.com.au Fri Jul 18 06:05:20 2008 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Fri, 18 Jul 2008 03:05:20 -0700 (PDT) Subject: regex doubts Message-ID: <532965.570.qm@web54502.mail.re2.yahoo.com> Hi, I am taking a string as an input from the user and it should only contain the chars:L , M or R I tried the folllowing in kodos but they are still not perfect: [^A-K,^N-Q,^S-Z,^0-9] [L][M][R] [LRM]?L?[LRM]? etc but they do not exactly meet what I need. For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. regards, SZ The string may or may not have all the three chars. " life isn't heavy enough,it flies away and floats far above action" Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.tawn at ubisoft.com Wed Jul 16 05:04:09 2008 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Wed, 16 Jul 2008 11:04:09 +0200 Subject: isPrime works but UnBoundLocalError when mapping on list Message-ID: <8AEDA5E3386EA742B8C24C95FF0C758004623111@PDC-MAIL3.ubisoft.org> Terry Reedy wrote: >Wrong. Thank you. >For loop variables continue after the loop exits. This is >intentional. I never knew that and I can't find reference to it in the docs. Can you help me with the reasons for it? Drea From timr at probo.com Mon Jul 14 01:32:29 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 14 Jul 2008 05:32:29 GMT Subject: while var, but var ==16 != true References: <8c2cd9ff-bec2-4844-82a8-8ce02df5663e@w7g2000hsa.googlegroups.com> Message-ID: maestro wrote: > >why does this work? "while p" = "while p != 0" ? 1 is True and 0 is >false in python but other numbers have no boolean value so why doesnt >it abort. Because your statement is incorrect. Everything has a boolean value in Python. 0, None, False, '' (empty string), [] (empty list), () (empty tuple), and {} (empty dictionary) all have a False value. Everything else has a True value. Python didn't even have a boolean type (True and False) until rather recently (2.2?). This is a very handy feature, and it's one of the things I love about Python. >so obv while var means while not empty or why not zero but it isnt >something youd guess unless youd beeen shown it. It's clearly stated in the documentation. I don't know how you concluded that True and False were the only boolean values. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From asd at pittle.org Thu Jul 3 16:17:04 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Thu, 3 Jul 2008 13:17:04 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: Message-ID: <905975ec-70e0-48ef-9611-a8309170620a@w1g2000prd.googlegroups.com> On Jul 2, 10:39?pm, Ivan Ven Osdel wrote: > Not really, I have just worked with them more. > > ----- Original Message ----- > From: "Ali Servet D?nmez" > To: python-l... at python.org > Sent: Wednesday, July 2, 2008 1:15:04 PM GMT -06:00 US/Canada Central > Subject: Re: Freesoftware for auto/intelligent code completing in Python > > On Jul 2, 7:55?pm, Ivan Ven Osdel wrote: > > The free Python editors/IDEs really do need work as far as code completion goes but I am hopeful. > > > IMO Stani's Python Editor comes closest by providing some code sense through a combination of history and doc strings for Python built-ins. Where it falls short is the ability to scan doc strings for your own code and non built-in modules in the Python path. Python already has the ground work in place to accomplish something similar to VS's XML commenting/intellisense system. With a Python interpretor you can type help(myModule) and get the doc string documentation. So I imagine implementing code sense for code being developed as well as non built-in modules would just be a matter of finding the appropriate module at the right time and piping the output of help([module]) to a popup window. > > > If your willing to help work on something like that I suggest contacting Stani directlyhttp://pythonide.stani.be/orcreating a plugin for Geanyhttp://geany.uvena.de/ > > > Ivan Ven Osdel > > Software Engineerhttp://www.datasyncsuite.com/ > > > ----- Original Message ----- > > From: "Ali Servet D?nmez" > > To: python-l... at python.org > > Sent: Wednesday, July 2, 2008 3:33:59 AM GMT -06:00 US/Canada Central > > Subject: Re: Freesoftware for auto/intelligent code completing in Python > > > On Jul 1, 12:15?am, Fuzzyman wrote: > > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > > I don't want to be so mean here, but how hard it could be be writing a > > > > freesoftware which would automatically/intelligently auto complete > > > > Python code? (I mean something that really does the job, like > > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > > name it, but just don't give me PyDev please...) > > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > > missing here? > > > > > Could someone please point me out something that I'm really missing > > > > which is already present in the wild, otherwise I'd like discuss with > > > > whoever is willing to help me to get this thing done. I made my mind > > > > and I could volunteer to make this happen as thesis project for my > > > > incoming graduation in the next year. > > > > > Regards you all, > > > > Ali Servet D?nmez > > > > Vim, Emacs, Wing, Komodo, ... more? > > > > Yeah, I guess you're missing something. :-) > > > > Michael Foordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > > I've checkout Wing IDE's license and it doesnt' seem to be a > > freesoftware; am I wrong? > > Ivan, thanks for your reply. I am curious how come you're suggesting > me those two, but not others. Is there a good/particular reason for > that? > > I see, thank you! I'll certainly keep that in mind. From toby at tobiah.org Wed Jul 2 18:22:34 2008 From: toby at tobiah.org (Tobiah) Date: Wed, 02 Jul 2008 15:22:34 -0700 Subject: Sorting two dimentional array by column? References: Message-ID: >> Imagine an excel spreadsheet. I can choose >> a column and sort the records based on the items >> in that column. I would like to do the same >> thing with a large two dimensional array. >> What would be the fastest way (in computation time) >> to accomplish this? > > Now that I think about the problem more, I really want > to sort an array of dictionaries according one of the > keys of each. Could I use: > > array.sort(key = something) > > Where something looks at the proper item in the > current row? I can't quite visualize how to pull > the item out of the dictionary. Sorry to reply to myself so many times, but I have come up with the answer: from operator import itemgetter thing = [ {'animal': 'duck', 'tool': 'pond'}, {'animal': 'dog', 'tool': 'bone'}, {'animal': 'bear', 'tool': 'hive'} ] get = itemgetter('animal') thing.sort(key = get) print thing ***************************************** [ {'tool': 'hive', 'animal': 'bear'}, {'tool': 'bone', 'animal': 'dog'}, {'tool': 'pond', 'animal': 'duck'} ] ** Posted from http://www.teranews.com ** From vlastimil.brom at gmail.com Fri Jul 11 02:22:51 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 11 Jul 2008 08:22:51 +0200 Subject: Simple question, how do you tell how many items in a list? In-Reply-To: <268ac2770807102256o4f41e784q79a0caf849c046b4@mail.gmail.com> References: <268ac2770807102256o4f41e784q79a0caf849c046b4@mail.gmail.com> Message-ID: <9fdb569a0807102322r7723848dt8e192545a513282e@mail.gmail.com> 2008/7/11, Alex Bryan : > > I am just wondering how you get an integer value for how many items there > are in a list, preferably w/o a for loop. > > -- > http://mail.python.org/mailman/listinfo/python-list > Use len >>> len([1,2,3]) 3 >>> vbr -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at gmail.com Mon Jul 21 07:44:44 2008 From: cwitts at gmail.com (Chris) Date: Mon, 21 Jul 2008 04:44:44 -0700 (PDT) Subject: howto check is function capable of obtaining **kwargs? References: Message-ID: On Jul 21, 1:20?pm, dmitrey wrote: > hi all, > howto check is function capable of obtaining **kwargs? > > i.e. I have some funcs like > def myfunc(a,b,c,...):... > > some like > def myfunc(a,b,c,...,*args):... > > some like > def myfunc(a,b,c,...,*args, **kwargs):... > > some like > def myfunc(a,b,c,...,zz=zz0):... > > So I need to know is the given function capable of handling zz > parameter, for example the call > myfunc(a,b,c,...,zz=4,...) > > Thank you in advance, D. >>> def f(a, b=1, c={}, *args, **kwargs): pass >>> inspect.getargspec(f) (['a', 'b', 'c'], 'args', 'kwargs', (1, {})) >>> print inspect.getargspec.__doc__ Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. Hope that helps. Chris From basti.wiesner at gmx.net Mon Jul 7 10:44:22 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Mon, 07 Jul 2008 16:44:22 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Mark Wooding : > Sebastian "lunar" Wiesner wrote: > >> # perl -e '("a" x 100000) =~ /^(ab?)*$/;' >> zsh: segmentation fault perl -e '("a" x 100000) =~ /^(ab?)*$/;' > > (Did you really run that as root?) How come, that you think so? -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From norseman at hughes.net Tue Jul 22 20:30:08 2008 From: norseman at hughes.net (norseman) Date: Tue, 22 Jul 2008 17:30:08 -0700 Subject: How do I compare files? In-Reply-To: References: <1216769247.18962.7.camel@generator> Message-ID: <48867B90.90406@hughes.net> Timothy Grant wrote: > On Tue, Jul 22, 2008 at 4:27 PM, Clay Hobbs wrote: > >> I am making a program that (with urllib) that downloads two jpeg files >> and, if they are different, displays the new one. I need to find a way >> to compare two files in Python. How is this done? >> >> -- Ratfink >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > I'd start with file sizes. > > If that's not enough you might look at the md5 library and check the md5 > values for the files. > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list =================================== If you are on a Unix platform: man cmp man identify man display (ImageMagick) gimp If you use mc (MidnightCommander) the F3 key can help. Jef Poskanzer's package has tools too. If you are on a Microsoft platform: you needs lots money. :) CorelDraw is available for under $100.00 American Steve norseman at hughes.net From jmike at alum.mit.edu Wed Jul 9 13:39:48 2008 From: jmike at alum.mit.edu (jmike at alum.mit.edu) Date: Wed, 9 Jul 2008 10:39:48 -0700 (PDT) Subject: User-defined exception: "global name 'TestRunError' is not defined" Message-ID: I'm using some legacy code that has a user-defined exception in it. The top level program includes this line from TestRunError import * It also imports several other modules. These other modules do not explicitly import TestRunError. TestRunError is raised in various places throughout the modules. There are a few cases where something goes wrong with the program and I get this error: FATAL ERROR: global name 'TestRunError' is not defined I realize this is kind of a silly question to ask in the general sense without showing more of the code, but does anyone have any suggestions as to the most likely causes of this error coming up? Could it be something like an error happening where it is not explicitly in a try block, or an error happening while I'm already in an except block, or something like that? Thanks, --JMike From fredrik at pythonware.com Mon Jul 21 04:01:04 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 10:01:04 +0200 Subject: regex doubts In-Reply-To: References: <532965.570.qm@web54502.mail.re2.yahoo.com> <504d473e-375a-4111-ae2e-c06aaa37b096@p25g2000pri.googlegroups.com> Message-ID: >> Perhaps you could explain what you mean by "$ does the right thing". > > wtf is wrong with you? (I mean, you do know under what circumstances $ matches a newline character when used without modifiers, right? So why do you keep behaving like a reddit commenter?) From motoom at xs4all.nl Tue Jul 22 21:26:50 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Wed, 23 Jul 2008 03:26:50 +0200 Subject: Python Written in C? Message-ID: <2.2.32.20080723012650.012742b8@pop.xs4all.nl> giveitawhril2008 wrote... > I think someone should write a compiler, "Revenge of BASIC." Your remark made an immediate association with me with the following soundtrack: http://www.empire-of-the-claw.com/files/Empire%20of%20The%20Claw%20-%20Tranc e%20of%20the%2080's%20Arcade.mp3 "A creature for my amusement" Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From Tribulations at Paralleles.invalid Mon Jul 7 01:25:34 2008 From: Tribulations at Paralleles.invalid (TP) Date: Mon, 07 Jul 2008 07:25:34 +0200 Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> Message-ID: Dennis Lee Bieber wrote: > Off-hand, I'd probably try first with: > > csi = "\033[" > > and then define your > > colorblackondarkblue = $csi"30;44m" Thanks for your answer. I have tried this slight modification, but it does not change anything on my terminal. -- TP (Tribulations Parall?les) "Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert). From fabiofz at gmail.com Sun Jul 27 17:29:02 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Sun, 27 Jul 2008 18:29:02 -0300 Subject: Autocompletion and Interactive Tables in a Python IDE In-Reply-To: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> References: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Message-ID: > a) Intellisense (tells you what classes/methods are available and what > variables go into a function) > b) Code Completion (guesses your code after four letters) > c) Data-Orientation; multiple data sessions can be open, data can be > viewed easily > > Python's IDLE has only half of the first of these features. I did a > lot of searching and found the PyDev extensions for Eclipse's Python > IDE, and found that they've got Intellisense. I'm still missing b and > c, and am getting extremely frustrated programming so slowly.. Hi Anthony, Actually, Pydev (both open source and Pydev Extensions) provide 'a' and 'b' -- if it's not showing to you, it may be that the pythonpath is not correctly configured (see http://fabioz.com/pydev/manual_101_root.html for instructions on how to configure it). As for 'c', I'm sure there's more than one plugin that can give that to you within Eclipse (search google for eclipse database plugins) -- I haven't used any of those, so, I can't really comment on them. Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeffrey at fro.man Tue Jul 15 15:50:50 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Tue, 15 Jul 2008 12:50:50 -0700 Subject: 'if name is not None:' v. 'if name:' References: Message-ID: Victor Noagbodji wrote: > Why do people use if name is not None: instead of simply > writing if not name? To differentiate from the case where name == '', or some other non-None false value. So the question is, do you want to test for identity with None, or for truth in general? Jeffrey From wuwei23 at gmail.com Tue Jul 29 08:39:58 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 29 Jul 2008 05:39:58 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> Message-ID: On Jul 29, 2:21?pm, castironpi wrote: > On Jul 28, 5:58?pm, Fuzzyman wrote: > > Well - in IronPython user code gets compiled to in memory assemblies > > which can be JIT'ed. > > I don't believe so. Uh, you're questioning someone who is not only co-author of a book on IronPython, but also a developer on one of the first IronPython-based commercial applications. I know authorship isn't always a guarantee of correctness, but what experience do you have with IronPython that makes you so unwilling to accept the opinion of someone with substantial knowledge of the subject? From andrewthommo at gmail.com Fri Jul 11 23:24:02 2008 From: andrewthommo at gmail.com (Andrew Thompson) Date: Fri, 11 Jul 2008 20:24:02 -0700 (PDT) Subject: paypal wholesale men jordans 17 (paypal accept)(www super-saler com References: <5d746374-d2a0-411e-bf60-87256a219b7c@m44g2000hsc.googlegroups.com> <87skuhqerl.fsf@benfinney.id.au> Message-ID: <8557ccba-9ad1-4f83-9069-e02b80ccdefe@f63g2000hsf.googlegroups.com> On Jul 12, 1:18?pm, Kevin McMurtrie wrote: ... > I strongly recommend dropping all articles with "googlegroups.com" in > the Message-ID. ? I strongly recommend setting follow-ups in inane, multi-posted, spam based threads. F-U set to cam.misc, since I do not read it, and do not care too much to see any replies. -- Andrew Thompson http://pscode.org/ From digitig at gmail.com Mon Jul 7 10:47:39 2008 From: digitig at gmail.com (Tim Rowe) Date: Mon, 7 Jul 2008 15:47:39 +0100 Subject: Can't get Python for Windows to run In-Reply-To: <486e8cf6$0$5679$9b622d9e@news.freenet.de> References: <486E4125.5080201@timgolden.me.uk> <486e8cf6$0$5679$9b622d9e@news.freenet.de> Message-ID: 2008/7/4 "Martin v. L?wis" : > and find installers annoying that ask too many questions So do I, but not as annoying as installers that do the Wrong Thing because they didn't ask! ;-) Still, it's your call. > In any case, try installing with > > msiexec /i 'ProgramMenuFolder=C:\Documents and Settings\All > Users\StartMenu\Programs\Programming' Thanks, that looks like just what I need. -- Tim Rowe From castironpi at gmail.com Mon Jul 21 14:37:43 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 21 Jul 2008 11:37:43 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> Message-ID: <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> On Jul 18, 2:13?pm, Dan wrote: > On Jul 18, 2:17 pm, castironpi wrote: > > > > > On Jul 17, 11:39 pm, Kay Schluehr wrote: > > > > On 18 Jul., 01:15, castironpi wrote: > > > > > On Jul 17, 5:37 pm, I V wrote: > > > > > > On Thu, 17 Jul 2008 15:08:17 -0700, castironpi wrote: > > > > > > The Python disassembly is baffling though. > > > > > > >>>> y= 3 > > > > > >>>> dis.dis('x=y+1') > > > > > > You can't disassemble strings of python source (well, you can, but, as > > > > > you've seen, the results are not meaningful). You need to compile the > > > > > source first: > > > > > > >>> code = compile('y=x+1','-', 'single') > > > > > >>> dis.dis(code) > > > > > > ? 1 ? ? ? ? ? 0 LOAD_NAME ? ? ? ? ? ? ? ?0 (x) > > > > > ? ? ? ? ? ? ? 3 LOAD_CONST ? ? ? ? ? ? ? 0 (1) > > > > > ? ? ? ? ? ? ? 6 BINARY_ADD > > > > > ? ? ? ? ? ? ? 7 STORE_NAME ? ? ? ? ? ? ? 1 (y) > > > > > ? ? ? ? ? ? ?10 LOAD_CONST ? ? ? ? ? ? ? 1 (None) > > > > > ? ? ? ? ? ? ?13 RETURN_VALUE > > > > > > You may well find these byte codes more meaningful. Note that there is a > > > > > list of opcodes athttp://docs.python.org/lib/bytecodes.html > > > > > Oh. ?How is the stack represented? > > > > As a pointer to a pointer of PyObject structs. > > > > > Does it keep track of which stack > > > > positions (TOS, TOS1, etc.) are in what registers? ?Does stack > > > > manipulation consume processor cycles? > > > > Python does not store values in registers. It stores locals in arrays > > > and accesses them by position ( you can see the positional index in > > > the disassembly right after the opcode name ) and globals / object > > > attributes in dicts. > > > > For more information you might just download the source distribution > > > and look for src/Python/ceval.c. This file contains the main > > > interpreter loop. > > > Ah, found it. ?The parts that are making sense are: > > > register PyObject **stack_pointer; > > #define TOP() ? ? ? ? ? (stack_pointer[-1]) > > #define BASIC_POP() ? ? (*--stack_pointer) > > > ...(line 1159)... > > w = POP(); > > v = TOP(); > > if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { > > ? ? ? ? /* INLINE: int + int */ > > ? ? ? ? register long a, b, i; > > ? ? ? ? a = PyInt_AS_LONG(v); > > ? ? ? ? b = PyInt_AS_LONG(w); > > ? ? ? ? i = a + b; > > ? ? ? ? if ((i^a) < 0 && (i^b) < 0) > > ? ? ? ? ? ? ? ? goto slow_add; > > ? ? ? ? x = PyInt_FromLong(i); > > > ... Which is more than I was picturing was involved. ?I understand it > > is also specific to CPython. ?Thanks for the pointer to the code. > > > My basic question was, what is the difference between compilers and > > interpreters, and why are interpreters slow? ?I'm looking at some of > > the answer right now in "case BINARY_ADD:". > > The basic difference between a (traditional) compiler and an > interpreter is that a compiler emits (assembly) code for a specific > machine. Therefore it must know the specifics of the machine (how many > registers, memory addressing modes, etc), whereas interpreters > normally define themselves by their conceptual state, that is, a > virtual machine. The instructions (bytecode) of the virtual machine > are generally more high-level than real machine instructions, and the > semantics of the bytecode are implemented by the interpreter, usually > in a sort-of high level language like C. This means the interpreter > can run without detailed knowledge of the machine as long as a C > compiler exists. However, the trade off is that the interpreter > semantics are not optimized for that machine. > > This all gets a little more hairy when you start talking about JITs, > runtime optimizations, and the like. For a real in-depth look at the > general topic of interpretation and virtual machines, I'd recommend > Virtual Machines by Smith and Nair (ISBN:1-55860910-5). > > -Dan You're saying the VM can't compile code. That makes sense, it's not a compiler. Do I understand correctly that JIT does compile to native code in some cases? Python: x= y+ 1 Python VM: push, push, add, store Assembly: load, load, add, store Except, the assembly doesn't contain the type-checking that PyInt_AS_LONG does. But that's not the only thing that stops python from precompiling to assembly directly. GNU doesn't come with Python. What sorts of minimal information would be necessary to take from the GNU libs for the user's specific processor, (the one they're downloading their version of Python for), to move Python to the further step of outputting the machine code? From konstantin.selivanov at gmail.com Tue Jul 22 01:10:02 2008 From: konstantin.selivanov at gmail.com (konstantin) Date: Mon, 21 Jul 2008 22:10:02 -0700 (PDT) Subject: string[i:j:k] Message-ID: Hello, I'm not a newbie in python, but recently faced a problem in simple expression: some_string[i:j:k] What does it mean? I believe this grammar (http://docs.python.org/ref/ slicings.html) describes the syntax. But I can't grasp it. Thanks! From david at abbottdavid.com Mon Jul 14 21:04:39 2008 From: david at abbottdavid.com (David) Date: Mon, 14 Jul 2008 21:04:39 -0400 Subject: Python Tiddlywiki class In-Reply-To: References: Message-ID: <487BF7A7.5050602@abbottdavid.com> CracKPod wrote: > Hello, I wrote a Python class to interact with the TiddlyWiki. In case > you are interested you can find it on my blog: > > http://crackpod.bplaced.net/ > > CracKPod > -- > http://mail.python.org/mailman/listinfo/python-list > > > Thank you :) -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From arsyed at gmail.com Fri Jul 25 05:36:55 2008 From: arsyed at gmail.com (arsyed) Date: Fri, 25 Jul 2008 05:36:55 -0400 Subject: 2d graphics - what module to use? In-Reply-To: References: Message-ID: <9a2cc7a70807250236u7e7cfdfaxe326cc1f4bb41cef@mail.gmail.com> On Fri, Jul 25, 2008 at 2:13 AM, Pierre Dagenais wrote: > What is the easiest way to draw to a window? I'd like to draw something > like sine waves from a mathematical equation. > Newbie to python. > -- > http://mail.python.org/mailman/listinfo/python-list > I'd recommend matplotlib: http://matplotlib.sourceforge.net/ Also see the "GUI" and "Plotting" sections on this page: http://wiki.python.org/moin/UsefulModules From mensanator at aol.com Tue Jul 15 14:30:14 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 15 Jul 2008 11:30:14 -0700 (PDT) Subject: isPrime works but UnBoundLocalError when mapping on list References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> <8a07445a-3ca8-4373-9312-cea8db83ec5c@l64g2000hse.googlegroups.com> <9f3c45f1-9cb2-46c1-838b-716180061956@e39g2000hsf.googlegroups.com> Message-ID: On Jul 15, 12:36?pm, defn noob wrote: > On Jul 15, 7:28?pm, Mensanator wrote: > > > > > > > On Jul 15, 11:26?am, defn noob wrote: > > > > isPrime works when just calling a nbr but not when iterating on a > > > list, why? adding x=1 makes it work though but why do I have to add > > > it? > > > Is there a cleaner way to do it? > > > > def isPrime(nbr): > > > ? ? for x in range(2, nbr + 1): > > > ? ? ? ? if nbr % x == 0: > > > ? ? ? ? ? ? break > > > ? ? if x == nbr: > > > ? ? ? ? return True > > > ? ? else: > > > ? ? ? ? return False > > > > >>> [isPrime(y) for y in range(11)] > > > > Traceback (most recent call last): > > > ? File "", line 1, in > > > ? ? [isPrime(y) for y in range(11)] > > > ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > > > ? ? if x == nbr: > > > UnboundLocalError: local variable 'x' referenced before assignment > > > > >>> map(isPrime, range(100)) > > > > Traceback (most recent call last): > > > ? File "", line 1, in > > > ? ? map(isPrime, range(100)) > > > ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > > > ? ? if x == nbr: > > > UnboundLocalError: local variable 'x' referenced before assignment>>> isPrime(10) > > > False > > > >>> isPrime(11) > > > > True > > > > adding x=1 makes it work though: > > > > def isPrime(nbr): > > > ? ? x=1 > > > ? ? for x in range(2, nbr + 1): > > > ? ? ? ? if nbr % x == 0: > > > ? ? ? ? ? ? break > > > ? ? if x == nbr: > > > ? ? ? ? return True > > > ? ? else: > > > ? ? ? ? return False > > > > >>> [isPrime(y) for y in range(11)] > > > > [False, True, True, True, False, True, False, True, False, False, > > > False] > > > No, it doesn't. You are falsely reporting that 1 is prime. > > > And instead of making the fake variable x, shouldn't you > > instead test that nbr+1 is greater than 2? Or call it with > > range(3,11) instead of range(11)? x isn't initialized > > because if nbr+1 is <=2, the for loop has an invalid range > > and doesn't even execute. > > def isPrime(nbr): > ? ? for x in range(2, nbr + 1): > ? ? ? ? if nbr % x == 0: > ? ? ? ? ? ? break > ? ? if x == nbr: > ? ? ? ? return True > ? ? else: > ? ? ? ? return False > > this works for all primes, if i want to not include 1 i just do if > nbr<=1 return false > > you are answering the wrong question. No, I also mentioned the for loop having an invalid range, which is why your original failed. Pointing out that 1 isn't prime was a bonus. > > anyway here is a clear one: > def isPrime(nbr): > ? ? if nbr < 2: > ? ? ? ? return False > ? ? for x in range(2, nbr + 1): > ? ? ? ? if nbr % x == 0: > ? ? ? ? ? ? return nbr == x I suppose you're not interested in knowing you don't have to test anything higher than the square root of the number. From workitharder at gmail.com Sun Jul 13 02:04:23 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 12 Jul 2008 23:04:23 -0700 (PDT) Subject: filtering keyword arguments References: <633d6159-7803-4d9b-8f16-2a4a0a197a86@t54g2000hsg.googlegroups.com> Message-ID: On Jul 12, 8:44 pm, Amir wrote: > How do you filter keyword arguments before passing them to a function? > > For example: > > def f(x=1): return x > > def g(a, **kwargs): print a, f(**kwargs) > > In [5]: g(1, x=3) > 1 3 > > In [6]: g(1, x=3, y=4) > TypeError: f() got an unexpected keyword argument 'y' > > Is there a way to do something like: > > def g(a, **kwargs): print a, f(filter_rules(f, **kwargs)) > > so only {'x': 3} is passed to f? > > I was hoping for a pythonic way of doing what in Mathematica is done > by FilterRules: > > http://reference.wolfram.com/mathematica/ref/FilterRules.html Here it is as a decorator: def filter_arguments(func): def func2(*args, **kwargs): import inspect arglist, vararg, kwarg, defaults = inspect.getargspec(func) for k in kwargs.copy(): if k not in arglist: del kwargs[k] return func(*args, **kwargs) return func2 @filter_arguments def func(a=1, b=2): return a+b print func() print func(c=3) print func(a=3,b=4) From bruno.42.desthuilliers at websiteburo.invalid Mon Jul 7 04:52:19 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 07 Jul 2008 10:52:19 +0200 Subject: Validation in plone In-Reply-To: <3d02ab9e-6f81-4b56-b6ef-786e8e6f070a@m44g2000hsc.googlegroups.com> References: <3d02ab9e-6f81-4b56-b6ef-786e8e6f070a@m44g2000hsc.googlegroups.com> Message-ID: <4871d920$0$11997$426a74cc@news.free.fr> Sallu a ?crit : > Hi all and one, > How to do server side validation in plone? Wrong place for Plone related questions. Try the Plone mailing list. From steve at REMOVE-THIS-cybersource.com.au Wed Jul 30 22:54:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Jul 2008 02:54:41 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <00a124e1$0$20313$c3e8da3@news.astraweb.com> On Wed, 30 Jul 2008 20:55:03 +0100, Matthew Woodcraft wrote: > On the other hand, iterators provide a clear example of problems with > "if x": __nonzero__ for iterators (in general) returns True even if they > are 'empty'. How do you propose telling whether an iterator is empty? That's a generic problem with any sort of lazy function. You don't know if it has finished unless you try grabbing data from it. > For example, this function (which attempts to avoid making an expensive > call when not necessary) is buggy, but easy to write if you've been > taught that "if x" will work with any kind of object. > > def frob(widgets, power): > if widgets: > frobber = Frobber(power) # expensive call > for widget in widgets: > frobber.frob(widget) AFAIK there's no great solution to this problem. It's inherent in the way lazy functions work. Certainly you can't replace the call to "if widgets" with "if len(widgets)", because iterators don't have a length. However, there is a good (but not great) solution: def frob(widgets, power): widgets = iter(widgets) # in case widgets is a sequence try: first = widgets.next() except StopIteration: # empty iterator, nothing to do return None frobber = Frobber(power) # expensive call frobber.frob(widget) for widget in widgets: frobber.frob(widget) -- Steven From ervan.ensis at gmail.com Mon Jul 28 17:24:43 2008 From: ervan.ensis at gmail.com (Ervan Ensis) Date: Mon, 28 Jul 2008 16:24:43 -0500 Subject: seemingly simple list indexing problem Message-ID: My programming skills are pretty rusty and I'm just learning Python so this problem is giving me trouble. I have a list like [108, 58, 68]. I want to return the sorted indices of these items in the same order as the original list. So I should return [2, 0, 1] For a list that's already in order, I'll just return the indices, i.e. [56, 66, 76] should return [0, 1, 2] Any help would be appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Wed Jul 30 14:20:15 2008 From: nagle at animats.com (John Nagle) Date: Wed, 30 Jul 2008 11:20:15 -0700 Subject: Reasoning behind 'self' parameter in classes? In-Reply-To: References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> Message-ID: <4890ac61$0$17215$742ec2ed@news.sonic.net> Matthew Fitzgibbons wrote: > Robert Dailey wrote: >> I've always been curious (more so than annoyed) as to why one must >> explicitly specify a "self" parameter for member functions in a class >> in Python. This seems very "C" like to me, since to do object oriented >> programming in C you must devote one parameter to the object itself. >> In a higher order language like Python, I would not have expected (and >> thus am rather surprised) that this pattern would apply. Is there any >> particular reason why 'self' parameters must be specified explicitly? >> I am curious to understand the philosophy and design behind this. Think about the implications of a language without real declarations and it will come to you. John Nagle Animats From larry.bates at websafe.com` Fri Jul 4 09:21:47 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Fri, 04 Jul 2008 08:21:47 -0500 Subject: compatible image type In-Reply-To: References: Message-ID: gordon wrote: > hi > in my application a file selection by user returns a pathname string > like F:/images/png/my.png or F:/docs/text/somedoc.txt ....etc. > I can get the extension using > extn=string.split(os.path.basename(pathname),'.' )[1] > > then later on i want to create a Photoimage using > > ImageTk.PhotoImage(file=pathname) and display it on a canvas. > > the extn can be anything ..even zip or bat ,doc whatever depending on > user selection...I want to put someway to raise an error message to > the user if he selects a file with extension not of a compatible image > type for PhotoImage.How should i do this? should i check 'extn' to a > list of compatible image type extensions(something like > [''jpg','jpeg','png','gif'...] ) or is there a better way? > > gordon You do know that there is a method for getting extensions easily? extn = os.path.splitext(pathname)[1] Note: It does include the '.' separator (e.g. it returns .txt) but that's easy to handle. If you just catch the exception (as Mark suggested), you don't even have to look at the extension. -Larry From sthembilengidi at gmail.com Mon Jul 21 10:44:05 2008 From: sthembilengidi at gmail.com (Amie) Date: Mon, 21 Jul 2008 07:44:05 -0700 (PDT) Subject: Website Creation using Python Message-ID: Afternoon, I would like some help on how to create a website using the python programming language. I've tried using enamel, but had some problems because I could not create html tables and intergrating it with python, like you use it when coding in php. Any help would be appreciated. Thanks From gherron at islandtraining.com Wed Jul 16 01:29:20 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 15 Jul 2008 22:29:20 -0700 Subject: how to match whole word In-Reply-To: References: Message-ID: <487D8730.60802@islandtraining.com> Peng Yu wrote: > Hi, > > The following code snippet is from /usr/bin/rpl. I would like the it > to match a word, for example, "abc" in ":abc:". But the current one > would not match "abc" in ":abc:". I tried to modify it myself. Would > you please let me know what is the corrected way to do it? > > Thanks, > Peng > > if opts.whole_words: > regex = re.compile(r"(?:(?<=\s)|^)" + re.escape(old_str) + r"(?=\s| > $)", > opts.ignore_case and re.I or 0) > -- > http://mail.python.org/mailman/listinfo/python-list > The regular expression "\w+" will match (what might be your definition of) a word, and in particular will match abc in :abc:. Regular expressions have lots of other special \-sequences that might be worth your while to read about: http://docs.python.org/lib/re-syntax.html Gary Herron From wuwei23 at gmail.com Mon Jul 28 05:52:23 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 28 Jul 2008 02:52:23 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> <6a5506b1-632e-4bf6-b0ce-4d51d1751aa9@i24g2000prf.googlegroups.com> <8b4b11c3-e306-4fe7-82d1-0a948c725f2f@r15g2000prd.googlegroups.com> <239a084f-b73d-4c20-aaaf-bbd05d452638@a2g2000prm.googlegroups.com> <8f675d65-e302-4428-a4bc-f494b230cb59@w1g2000prk.googlegroups.com> <744c27d4-e166-4b3a-9c2c-d4bf1a207fb8@a2g2000prm.googlegroups.com> Message-ID: <553e2d69-7ac7-4b27-bd09-4c35548ce5ec@a3g2000prm.googlegroups.com> On Jul 28, 3:07 pm, "Russ P." wrote: > What was "suggested in rejected" on the thread you pointed me to was > not what I suggested. Not even close. Get it, genius? *sigh* Clearly I don't have better things to do right now than waste my time. You wrote: > So why not allow something like this?: > class MyClass: > def func( , xxx, yyy): > .xxx = xxx > local = .yyy > The "self" argument is replaced with nothing, but a comma is used as a > placeholder. Philip Eby suggested in the thread I linked to: > def .aMethod(arg1, arg2): > return .otherMethod(arg1*2+arg2) > In other words, 'self' here is uniformly replaced by an empty string. So you honestly see no similarity between your suggestion and the latter? Or do you seriously think that placing an errant comma in the argument list is somehow substantively different from placing a period before the function name? Or are you trying to say that '"self" argument is replaced with nothing' is in no way the same suggestion as "'self' here is uniformly replaced by an empty string"? And do you -really- believe that Guido's rejection reasons of * "you're proposing to hide a fundamental truth in Python, that methods are "just" functions whose first argument can be supplied using syntactic sugar" * "that's a lot of new syntax for no gain in readability. You just need to get your head around the fundamental truth" ...somehow don't apply to your suggestion? Did you even read the thread? From drobinow at gmail.com Thu Jul 3 21:25:31 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Thu, 3 Jul 2008 18:25:31 -0700 (PDT) Subject: Copyright issues for an application developed using django, python and mySQL References: <1f23a9fd-33a0-4a06-9733-241c8fd450d2@w4g2000prd.googlegroups.com> Message-ID: <13318ff0-196b-4430-86f3-4839d7859be7@x41g2000hsb.googlegroups.com> On Jul 3, 8:33?pm, Nagu wrote: > ... > How do I go about addressing the copyright and licensing issues? (I do > not know if licensing is the right word here). > > Please advice. > > Thank you, > Nagu I suggest you take the advice of random idiots on a python mailing list. From squishywaffle at gmail.com Thu Jul 31 10:15:20 2008 From: squishywaffle at gmail.com (squishywaffle at gmail.com) Date: Thu, 31 Jul 2008 07:15:20 -0700 (PDT) Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> Message-ID: <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> > Ctypes is a since python2.5 built-in module that allows to declare > interfaces to C-libraries in pure python. You declare datatypes and > function prototypes, load a DLL/SO and then happily work with it. No C, no > compiler, no refcounts, no nothing. > > And you can pass python-functions as callbacks. The first sentence (and some really crummy licensing restrictions imposed by the library distributor) alone here excludes this as a valid option for this particular case, I definitely need Python 2.4 support. So the question comes back around to being how is this same desired behavior duplicated in the Python/C API? From deets at nospam.web.de Thu Jul 17 01:34:22 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 17 Jul 2008 07:34:22 +0200 Subject: how to debug python's extend module written in c/c++ on windows In-Reply-To: <64d771b2-fbc8-4b6a-9725-3dc5063c5328@p25g2000hsf.googlegroups.com> References: <64d771b2-fbc8-4b6a-9725-3dc5063c5328@p25g2000hsf.googlegroups.com> Message-ID: <6e83v4F5pfg0U1@mid.uni-berlin.de> tcfg at sina.com schrieb: > dear all: > > I have searched the debug informations of many python's IDE, but I > cannot find the method about debuging the extend module written in > Visual studio 2008 on windows. > The wingIDE tell me that we can debug the extend module on linux, but > cannot on windows. and using wingdbstub.py we can embed python into > other's source code but not extending. > Who can tell me the skills, I appreciate! I use plain gdb (aka the C-debugger) for this purpose. Create a small test-script that exposes the error you want to debug, and then start the python interpreter in the debugger. Set breakpoints, or watch backtraces. I can't comment on how that works on VS08 though - but it shouldn't be to hard. Diez From neridaj at gmail.com Tue Jul 1 01:33:44 2008 From: neridaj at gmail.com (neridaj at gmail.com) Date: Mon, 30 Jun 2008 22:33:44 -0700 (PDT) Subject: ImportError: No module named _md5 Message-ID: Hello, Does anyone know how to fix this error when trying to build MySQL- python-1.2.2: python setup.py build Traceback (most recent call last): File "setup.py", line 5, in import ez_setup; ez_setup.use_setuptools() File "/Users/jasonnerida/Downloads/MySQL-python-1.2.2/ez_setup.py", line 83, in use_setuptools egg = download_setuptools(version, download_base, to_dir, download_delay) File "/Users/jasonnerida/Downloads/MySQL-python-1.2.2/ez_setup.py", line 111, in download_setuptools import urllib2, shutil File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/ lib/python2.5/urllib2.py", line 91, in import hashlib File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/ lib/python2.5/hashlib.py", line 133, in md5 = __get_builtin_constructor('md5') File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/ lib/python2.5/hashlib.py", line 60, in __get_builtin_constructor import _md5 ImportError: No module named _md5 I then tried installing py25-hashlib via macports, which never completes: sudo port install py25-hashlib Password: Waiting for lock on /opt/local/var/macports/build/ _opt_local_var_macports_sources_rsync.macports.org_release_ports_python_py25- hashlib/work/.macports.py25-hashlib.state Do I need to completely reinstall python? I'm using 2.5.2 which shipped with Leopard. Thanks for any help, Jason From sukkopera at gmail.com Fri Jul 18 09:00:42 2008 From: sukkopera at gmail.com (sukkopera at gmail.com) Date: Fri, 18 Jul 2008 06:00:42 -0700 (PDT) Subject: Unexpected default arguments behaviour (Maybe bug?) References: <4f29ccf6-4daf-4e8e-8735-96cffd8a882e@t54g2000hsg.googlegroups.com> <475185e0-360a-452b-8d22-33ffc243b8a0@z66g2000hsc.googlegroups.com> <98fdc845-cb62-4e7b-891c-dfc75d741a2f@z66g2000hsc.googlegroups.com> Message-ID: On 18 Lug, 13:23, "Sebastian \"lunar\" Wiesner" wrote: > It _is_ the correct thing. ?Evaluation of default parameters at "declaration > time" and not at invocation is truely a language feature, not a bug. > > You'll find your bug report being closed quickly. It has ;). I had totally missed the tutorial section where it is stated, which actually even has an example quite close to the one I provided. Sorry for the waste of time. Giorgio From larry.bates at websafe.com` Tue Jul 29 16:57:27 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 29 Jul 2008 15:57:27 -0500 Subject: static variables in Python? In-Reply-To: References: Message-ID: kj wrote: > Yet another noob question... > > Is there a way to mimic C's static variables in Python? Or something > like it? The idea is to equip a given function with a set of > constants that belong only to it, so as not to clutter the global > namespace with variables that are not needed elsewhere. > > For example, in Perl one can define a function foo like this > > *foo = do { > my $x = expensive_call(); > sub { > return do_stuff_with( $x, @_ ); > } > }; > > In this case, foo is defined by assigning to it a closure that has > an associated variable, $x, in its scope. > > Is there an equivalent in Python? > > Thanks! > > kynn First names in Python are just that, names that point to objects. Those objects can contain any type of information including other objects. They are NOT buckets where things are stored. 1) Names (variables in Perl/C) defined within a Python function are placed in its local namespace. They are not visible in the global namespace. 2) Yes you can have a local name point to a global. This is often used in classes with attributes because looking up local is somewhat quicker than looking up the class attribute. def foo(): x = expensive_call return do_stuff_with(x()) In this particular case it doesn't really help. It would be more useful in something like: class foo(object): def __init__(self, initialvalue = 0) self.currentvalue = initialvalue def longloopingmethod(self, listtosum): currentvalue = self.currentvalue for v in listtosum: currentvalue += v BTW - There are BETTER ways to sum a list, so this is just an example. -Larry From jason at tishler.net Wed Jul 30 15:30:21 2008 From: jason at tishler.net (Jason Tishler) Date: Wed, 30 Jul 2008 15:30:21 -0400 Subject: SVN access with pysvn under Cygwin (Installation problems) In-Reply-To: <69da0a81-bf73-46cb-a762-b017a53e6ddf@e39g2000hsf.googlegroups.com> References: <69da0a81-bf73-46cb-a762-b017a53e6ddf@e39g2000hsf.googlegroups.com> Message-ID: <20080730193021.GA3888@tishler.net> Andy, On Wed, Jul 30, 2008 at 07:46:32AM -0700, Andy Dingley wrote: > Trying to install the pysvn module I'm running into problems getting > it to work under Cygwin. Works fine from a Windows command prompt, > with both the svn_cmd.py example and my own Python code. Under Cygwin > though I just get import failures. pysvn/__init__.py seems to be > invoked happily enough, but then fails when it tries to import > _pysvn_2_5.pyd > > $ python svn_cmd.py > Traceback (most recent call last): > File "svn_cmd.py", line 10, in > import pysvn > File "/usr/lib/python2.5/pysvn/__init__.py", line 104, in > import _pysvn_2_5 > ImportError: No module named _pysvn_2_5 > > Is there some trick to getting .pyd to work under Cygwin? You need to build (and install) pysvn under Cygwin. The pre-built Windows version will not work under Cygwin. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From timr at probo.com Fri Jul 25 00:04:33 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 25 Jul 2008 04:04:33 GMT Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> Message-ID: castironpi wrote: > >Compiling a program is different than running it. A JIT compiler is a >kind of compiler and it makes a compilation step. I am saying that >Python is not a compiler and in order to implement JIT, it would have >to change that fact. And I'm saying you are wrong. There is NOTHING inherent in Python that dictates that it be either compiled or interpreted. That is simply an implementation decision. The CPython implementation happens to interpret. The IronPython implementation compiles the intermediate language to native machine language. >> of Python that uses .NET. In that case, the code *IS* JIT compiled to >> assembly when the program starts. > >But still not the user's code, only the interpreter, which is running >in assembly already anyway in CPython. In CPython, yes. In IronPython, no; the user's code is compiled into machine language. Both of them are "Python". -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bj_666 at gmx.net Mon Jul 21 16:56:32 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Jul 2008 20:56:32 GMT Subject: Getting the name of a variable which was used as a function parameter. References: <9e2e64db-d594-408d-9418-b17133f23204@27g2000hsf.googlegroups.com> Message-ID: <6ekbg0F6vgp3U5@mid.uni-berlin.de> On Mon, 21 Jul 2008 09:01:10 -0700, Ravi Kotecha wrote: > I thought this was pretty cool and since I spent 30 mins or so > goggling before giving up and figuring out myself I thought I'd share > it with you. > >>>> def a(a): > ... for k,v in sys._getframe(1).f_locals.items(): > ... if id(v) == id(a): > ... print k > ... > >>>> hello = 123 > >>>> a(hello) > hello > > ## pretty cool. Or ugly hack. Beauty lies in the eye of the beer holder? > It's totally useless but I wanted to do it for logging purposes. Don't use such things in production code, please. Ciao, Marc 'BlackJack' Rintsch From deets at nospam.web.de Tue Jul 29 10:56:16 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jul 2008 16:56:16 +0200 Subject: Continuous integration for Python projects References: Message-ID: <6f8pelFafh42U1@mid.uni-berlin.de> Hussein B wrote: > Hi. > Please correct my if I'm wrong but it seems to me that the major > continuous integration servers (Hudson, CruiseControl, TeamCity ..) > don't support Python based application. > It seems they mainly support Java, .NET and Ruby. > Can I use one of the previous listed servers for Python project? Hudson can, and AFAIK CC as well - they only invoke shell-scripts (at least hudson does, and CC you can convince doing that using ANT) So go ahead and use them - shouldn't be much (more) effort than for java projects. Diez From dp_pearce at hotmail.com Tue Jul 15 10:10:34 2008 From: dp_pearce at hotmail.com (dp_pearce) Date: Tue, 15 Jul 2008 07:10:34 -0700 (PDT) Subject: Anyone happen to have optimization hints for this loop? References: <43111321-2cc1-4a5e-9189-744131555841@26g2000hsk.googlegroups.com> <7f6c348f-3d49-4483-a3cc-7d4b8eb863a4@27g2000hsf.googlegroups.com> Message-ID: <5d9afe6f-9055-465a-8991-803ca63b7fed@27g2000hsf.googlegroups.com> Thank you so much for all your advice. I have learnt a lot. In the end, the solution was perhaps self evident. Why try and build a huge string AND THEN write it to file when you can just write it to file? Writing this much data directly to file completed in ~1.5 seconds instead of the 3-4 seconds that any of the .join methods produced. Interestingly, I found that my tests agreed with Bruno. There wasn't a huge change in speed between a lot of the other methods, other than them looking a lot tidier. Again, many thanks. Dan From atulskulkarni at gmail.com Mon Jul 28 11:48:38 2008 From: atulskulkarni at gmail.com (Atul.) Date: Mon, 28 Jul 2008 08:48:38 -0700 (PDT) Subject: Encoding for Devanagari Script. References: Message-ID: Hi Fredrik and Terry, Well I got this on IDLE I think I have done something wrong. >>> import codecs >>> f = open("C:\Documents and Settings\admin\My Documents\corpus\dainaikAikya collected by sushant.txt","r", "utf_8") Traceback (most recent call last): File "", line 1, in f = open("C:\Documents and Settings\admin\My Documents\corpus \dainaikAikya collected by sushant.txt","r", "utf_8") TypeError: an integer is required after that I tried the read binary mode and tried reading the firt 32 bytes and this is what I got. >>> f = open("C:\Documents and Settings\\admin\\My Documents\\corpus\\dainaikAikya collected by sushant.txt","rb") >>> f.read(32) '\xef\xbb\xbf\xe0\xa4\xa8\xe0\xa4\xb5\xe0\xa5\x80 \xe0\xa4\xa6\xe0\xa4\xbf\xe0\xa4\xb2\xe0\xa5\x8d \xe0\xa4\xb2\xe0\xa5\x80,' Now based on my knowledge of Unicode I think this is a utf-8 file (the first 3 bytes \xef\xbb\xbf), please correct me if I am wrong. How do I read this? Atul. PS: the above code I wrote using the information from the Library Reference pdf section 4.8 "Codecs". Something wrong I am doing? Please do let me know. On Jul 25, 6:21?am, Terry Reedy wrote: > Atul. wrote: > > Hello All, > > > I wanted to know what encoding should I use to open the files with > >Devanagaricharacters. I was thinking of UTF-8 but was not sure, any > > leads on this? Anyone used it earlier? > > You cannot hurt your machine by giving that a try. > > This is a general comment for all beginners. ?Before posting, open the > interactive interpreter (or IDLE) and try something(s). ?If the result > puzzles you, copy and paste into a post. ?Or if more appropriate, open > the Python manuals and search a bit, or try a search engine. From mrkafk at gmail.com Mon Jul 21 13:49:36 2008 From: mrkafk at gmail.com (mk) Date: Mon, 21 Jul 2008 19:49:36 +0200 Subject: Seriously, though, about LLVM In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > mk wrote: > >> This project has gained some publicity. There's IronPython, right, so >> has anybody thought about implementing Python using LLVM as backend, >> as it seems not out of question at all? > > you mean like: > > http://llvm.org/ProjectsWithLLVM/#pypy > > ? No, I don't mean "Python written in Python", with whatever backend. From tjreedy at udel.edu Wed Jul 9 13:44:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 09 Jul 2008 13:44:31 -0400 Subject: Openine unicode files In-Reply-To: <92793.41064.qm@web27403.mail.ukl.yahoo.com> References: <92793.41064.qm@web27403.mail.ukl.yahoo.com> Message-ID: Noorhan Abbas wrote: > Hello, > I wonder if someone can advise me on how to open unicode utf-8 files > without using the codecs library . I am trying to use the codecs.open() > from within Google Appengine but it is not working. When posting about something 'not working', post at least a line of code and the resulting exception traceback, if there is one, or a printing of the erroneous value, if that instead is the problem. From mefyl at lrde.epita.fr Sat Jul 12 08:16:22 2008 From: mefyl at lrde.epita.fr (mefyl) Date: Sat, 12 Jul 2008 14:16:22 +0200 Subject: sending input to an embedded application References: Message-ID: Uwe Schmitt wrote: > On 12 Jul., 09:08, George Oliver wrote: >> What I would like to do is take a program and embed it or put it >> within a Python-run GUI, using the GUI just to capture and send input >> to the application, and display the ouput. > > Which interface does your interpreter provide ? Just commandline or > can you access by other methods ? > > http://sourceforge.net/projects/pexpect/ might help you > Although Pexpect looks more advanced and complete, you might want to take a look at popen* modules. It enables you to easily run a subprocess, feed him data on stdin, retrieve output from stdout/stderr, and wait for its completion. http://docs.python.org/lib/module-popen2.html -- mefyl R&D engineer at Gostai - http://www.gostai.com To understand recursion, you must first understand recursion. From stochashtic at yahoo.ca Fri Jul 25 05:57:03 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 25 Jul 2008 11:57:03 +0200 Subject: Execution speed question Message-ID: <4889a36f$1@news2-rz-ap.ethz.ch> I am performing simulations on networks (graphs). I have a question on speed of execution (assuming very ample memory for now). I simplify the details of my simulation below, as the question I ask applies more generally than my specific case. I would greatly appreciate general feedback in terms of computing and of course considerations specific to implementation in Python. The nodes in my network may be ON or OFF. The network starts off with all nodes in the OFF state. I loop through the nodes. For each node that is OFF, I consider some probability of it turning ON based on the states of its neighbours. I MUST GO THROUGH ALL NODES BEFORE DECIDING WHICH ONES TO TURN ON. So my question is whether it is faster to 1. loop through a list of ALL nodes and check for OFF nodes using ifs or to 2. loop through a container of OFF nodes and remove from this when they turn ON The second would result in looping through less nodes, especially as the simulation progresses, but how does the cost of removal compare with cheap ifs and would the extra memory usage affect performance. I an appreciate that the cost of the if check, the number of nodes, and the type of container I use will come into the answer. In my case, the ifs are cheap boolean queries (whether the node is ON or OFF). The number of nodes is very large: millions for sure, maybe tens of millions. If considering (2), take note of my BOLD text above, which means I can't remove nodes as I iterate through them in the main loop. I naturally started coding with (2), but couldn't decide on the best data structure for python. A set seemed ideal for speedy removal, but then I can't iterate through them with out popping. An ordered list? Some creative solution with numpy arrays? There is also the complication that since we are in interpreted python, what is theoretically the best data structure may not in reality be optimal unless it is a default system object or coded externally in a compiled module. Of course, I will start experimenting to see what the execution difference is, but I would appreciate some suggestions from others re which is best and also on best data structure for (2). I'm not a newbie, so you can get technical with me python-wise and algorithm wise. I realise it is a 'basic' question, but it is something that I have always wondered about (cheap ifs versus extra structure) and with the number of nodes I am considering, it actually becomes an issue. Many Thanks, Suresh From rmanocha at gmail.com Tue Jul 22 08:01:59 2008 From: rmanocha at gmail.com (Rishabh Manocha) Date: Tue, 22 Jul 2008 17:31:59 +0530 Subject: Converting List of String to Integer In-Reply-To: <45493256-eaff-40e5-8414-59e7ce1b347c@m73g2000hsh.googlegroups.com> References: <45493256-eaff-40e5-8414-59e7ce1b347c@m73g2000hsh.googlegroups.com> Message-ID: <65b679260807220501j77246cdcp642c2814492a8d21@mail.gmail.com> Just to throw my hat in the ring, this is another way you can do this: [(lambda x : [int(ii) for ii in x])(y) for y in a] However, I do think dusans way is more elegant. Best, R On Tue, Jul 22, 2008 at 4:58 PM, dusans wrote: > >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > >>> [map(int, i) for i in a] > [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > On Jul 21, 9:06 pm, Samir wrote: > > Hi Everyone, > > > > I am relatively new to Python so please forgive me for what seems like > > a basic question. > > > > Assume that I have a list, a, composed of nested lists with string > > representations of integers, such that > > > > a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > > > > I would like to convert this to a similar list, b, where the values > > are represented by integers, such as > > > > b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > > > I have unsuccessfully tried the following code: > > > > n = [] > > for k in a: > > n.append([int(v) for v in k]) > > print n > > > > Does anyone know what I am doing wrong? > > > > Thanks in advance. > > > > Samir > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From amdescombes at gmail.com Tue Jul 22 15:00:38 2008 From: amdescombes at gmail.com (AMD) Date: Tue, 22 Jul 2008 21:00:38 +0200 Subject: scanf in python In-Reply-To: References: <4884be5e$0$19722$426a74cc@news.free.fr> <488568f6$0$6120$426a74cc@news.free.fr> Message-ID: <48862e5a$0$13865$426a74cc@news.free.fr> > AMD wrote: > >> I had seen this pure python implementation, but it is not as fast or >> as elegant as would be an implementation written in C directly within >> python with no need for import. > > maybe you should wait with disparaging comments about how Python is not > what you want it to be until you've learned the language? > > > Hello Fredrik, I didn't think my comment would offend anyone, I'm sorry if it did. I have been developping in Python for about 5 years, my company uses Python as a scripting language for all of its products. We use Jython for our server products. I think I know it pretty well by now. So I think I have earned the right to try to suggest improvements to the language or at least intelligent discussion of new features without need for offensive comments, don't you think? Andr? From gnewsg at gmail.com Sat Jul 12 15:05:01 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sat, 12 Jul 2008 12:05:01 -0700 (PDT) Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> Message-ID: <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> On 12 Lug, 20:15, Duncan Booth wrote: > "Giampaolo Rodola'" wrote: > > > My question is the following: is it safe to avoid to re-heapify() a > > heap when I remove or move an element which is not the first one? > > Example: > > >>>> from heapq import * > >>>> heap = [2,4,6,7,1,2,3] > >>>> heapify(heap) > >>>> del heap[4] > >>>> # Am I forced to heapify() the heap here? > > > Thanks in advance. > > No, it is not safe to avoid re-heapifying. > > After you call heapify the list is ordered such that for any 'n' in the > range 1..len(heap)//2 it is the case that heap[n-1] <= heap[2*n-1] and when > heap[2*n] exists heap[n-1] <= heap[2*n]. > > So: > > >>> heap = [0, 100, 1, 101, 102, 2, 3] > >>> heapify(heap) > >>> heap > > [0, 100, 1, 101, 102, 2, 3]>>> del(heap[4]) > >>> heap > > [0, 100, 1, 101, 2, 3]>>> heapify(heap) > >>> heap > > [0, 2, 1, 101, 100, 3] > > after deleting heap[4] it is no longer the case that heap[1] >= heap[4] as > the old heap[5] was a child of heap[2] not of heap[1]. Even if I avoid to re-heapify() it seems that the first element returned by heappop() is always the smaller one. >>> heap = [0, 100, 1, 101, 102, 2, 3] >>> heapify(heap) >>> heap [0, 100, 1, 101, 102, 2, 3] >>> del heap[4] >>> heap [0, 100, 1, 101, 2, 3] >>> heappop(heap) 0 >>> heappop(heap) 1 >>> heappop(heap) 2 >>> heappop(heap) 3 >>> heappop(heap) 100 >>> heappop(heap) 101 >>> heappop(heap) Traceback (most recent call last): File "", line 1, in IndexError: index out of range >>> That would be ok for me, as long as heappop() always returns the smallest item. Having said that I'd like to understand if there are cases where deleting or moving an element of the heap, causes heappop() to return an element which is not the smallest one. --- Giampaolo http://code.google.com/p/pyftpdlib/ From circularfunc at gmail.com Thu Jul 3 16:40:13 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 3 Jul 2008 13:40:13 -0700 (PDT) Subject: PIL(Py Image lib), show() not showing picture... References: <84a8f15a-594f-4e02-aa89-b70932eae420@59g2000hsb.googlegroups.com> <486d366d$0$879$ba4acef3@news.orange.fr> Message-ID: <09525702-bf03-437b-8fe1-e85a9759a711@2g2000hsn.googlegroups.com> On Jul 3, 10:20?pm, "M?ta-MCI \(MVP\)" wrote: > Hi! > > Which OS? ? On Vista, you MUST reconfig the "aper?u images et > t?l?copies" (in french ; sorry, I don't know the english translation). > > @-salutations > > Michel Claveau thumbnail images and faxes? and how do i do that? i must do it in windows or in the python library? From python at lists.wgwh.ch Wed Jul 16 11:01:08 2008 From: python at lists.wgwh.ch (Oli Schacher) Date: Wed, 16 Jul 2008 17:01:08 +0200 Subject: poplib 100% cpu usage Message-ID: <487E0D34.4060401@lists.wgwh.ch> Hi all I wrote a multithreaded script that polls mails from several pop/imap accounts. To fetch the messages I'm using the getmail classes ( http://pyropus.ca/software/getmail/ ) , those classes use the poplib for the real pop transaction. When I run my script for a few hours cpu usage goes up to 100%, sometimes even 104% according to 'top' :-) This made our test machine freeze once. First I thought I maybe didn't stop my threads correctly after polling an account but I attached a remote debugger and it showed that threads are stopped ok and that the cpu gets eaten in poplib in the function "_getline" which states in the description: ---snip--- # Internal: return one line from the server, stripping CRLF. # This is where all the CPU time of this module is consumed. # Raise error_proto('-ERR EOF') if the connection is closed. def _getline(self): ---snip--- So for testing purposes I changed this function and added: time.sleep(0.0001) (googling about similar problems with cpu usage yields this time.sleep() trick) It now looks ok, cpu usage is at about 30% with a few spikes to 80-90%. Of course I don't feel cozy about changing a standard library as the changes will be overwritten by python upgrades. Did someone else from the list hit a similar problem and maybe has a better solution? Thanks for your hints. Best regards, Oli Schacher From ldo at geek-central.gen.new_zealand Fri Jul 25 00:33:51 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 25 Jul 2008 16:33:51 +1200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <8233fbfb-ad9b-43ef-b722-9738ef129d0b@q5g2000prf.googlegroups.com> Message-ID: In message <8233fbfb-ad9b-43ef-b722-9738ef129d0b at q5g2000prf.googlegroups.com>, Jordan wrote: > On Jul 24, 8:01?pm, Lawrence D'Oliveiro central.gen.new_zealand> wrote: > >> In message >> <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, >> Jordan wrote: >> >> > Except when it comes to Classes. I added some classes to code that had >> > previously just been functions, and you know what I did - or rather, >> > forgot to do? Put in the 'self'. In front of some of the variable >> > accesses, but more noticably, at the start of *every single method >> > argument list.* >> >> The reason is quite simple. Python is not truly an "object-oriented" >> language. It's sufficiently close to fool those accustomed to OO ways of >> doing things, but it doesn't force you to do things that way. You still >> have the choice. An implicit "self" would take away that choice. > > You could still explicitly request non-implicit self on a method by > method basis. That would mean making OO the default. Which Python doesn't do. From tjreedy at udel.edu Mon Jul 7 16:45:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 07 Jul 2008 16:45:58 -0400 Subject: Confused yet again: Very Newbie Question In-Reply-To: <13be8c54-3fa9-4a37-a0e6-45bb019bff7e@a1g2000hsb.googlegroups.com> References: <13be8c54-3fa9-4a37-a0e6-45bb019bff7e@a1g2000hsb.googlegroups.com> Message-ID: Jeff wrote: > When you call c3.createJoe(c1.fred), you are passing a copy of the > value stored in c1.fred to your function. Python passes function > parameters by value. These statements are both wrong. Function argument objects or objects derived therefrom are bound to function parameter names. One could say that Python calls by cross-namespace assignment. No copying is done, anymore than with assignment statements. It returns objects the same way if there is a target to receive them. > The function will not destructively modify its arguments; If the argument is mutable and the function calls a mutation method of the object, it is mutated. tjr From larry.bates at websafe.com` Tue Jul 22 17:52:50 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 22 Jul 2008 16:52:50 -0500 Subject: Iterating Through List or Tuple In-Reply-To: References: Message-ID: Samir wrote: > Is there a way to loop or iterate through a list/tuple in such a way > that when you reach the end, you start over at the beginning? For > example, suppose I define a list "daysOfWeek" such that: > >>>> daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] > > If today is Sunday, I can set the variable "day" to today by: > >>>> i = iter(daysOfWeek) >>>> day = i.next() >>>> print day > sunday > > If I want to find out the day of the week 2 days from now, then this > code works ok: > >>>> for x in xrange(2): day = i.next() > >>>> print day > tuesday > > However, when extending my range beyond the number of items in the > list, I receive an error. For example, if I want to find out the day > of the week 11 days from today, I get this: > >>>> for x in xrange(11): day = i.next() > > > Traceback (most recent call last): > File "", line 1, in > for x in xrange(11): day = i.next() > StopIteration > > Is there a way to easily loop through a list or tuple (and starting > over at the beginning when reaching the end) without having to resort > to an "if" or "while" statement? > > (My question concerns the more general use of lists and tuples, not > necessarily determining days of the week. I know about using "import > datetime" and "from calendar import weekday" but thought that using > the days of the week would best illustrate my problem.) > > As always, thanks in advance. > > Samir >>> import itertools >>> i = itertools.cycle(daysOfWeek) >>> i.next() 'sunday' >>> i.next() 'monday' . . . >>> i.next() 'saturday' >>> i.next() 'sunday' -Larry From lepto.python at gmail.com Mon Jul 14 07:26:49 2008 From: lepto.python at gmail.com (oyster) Date: Mon, 14 Jul 2008 19:26:49 +0800 Subject: a module.pth question Message-ID: <6a4f17690807140426m1d8d6544ye60a5bd560863389@mail.gmail.com> My py24 is installed in h:\python24 I installed pyglet(http://pyglet.org/) in H:\pure_pylib\Multimedia\pyglet-1.0\, if I do [code] >>> import sys >>> sys.path.append(r'H:\pure_pylib\Multimedia\pyglet-1.0') >>> import pyglet [/code] it is ok. but if I created h:\pure_pylib\pyglet.pth file, which containts [code] Multimedia\pyglet-1.0 [/code] then [code] >>> import sys >>> sys.path.append(r'h:\pure_pylib') >>> import pyglet Traceback (most recent call last): File "", line 1, in ? ImportError: No module named pyglet >>> [/code] what is wrong with it? and How to fix it? thanks in advance From ki4yjl at gmail.com Sun Jul 13 19:37:11 2008 From: ki4yjl at gmail.com (WDC) Date: Sun, 13 Jul 2008 16:37:11 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> Message-ID: <7769c9aa-5084-4e71-9699-fd9949e51352@x41g2000hsb.googlegroups.com> On Jul 13, 4:21 pm, Kless wrote: > I need a dictionary where get the result from a 'key' (on left), but > also from a 'value' (on right), how to get it? > > I know that dictionaries aren't bidirectional, but is there any way > without use two dictionaries? > > Thanks in advance! You want to print the key as well as the value? From __peter__ at web.de Sat Jul 12 02:24:04 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Jul 2008 08:24:04 +0200 Subject: MySQLdb will only import for root References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> <6dothnF3lqqmU1@mid.uni-berlin.de> Message-ID: martinnorth wrote: > Diez B. Roggisch wrote: >> martinnorth schrieb: >>> Hi, >>> >>> I am running Python and MySQL on Ubuntu and have installed MySQLdb. If >>> I try to import MySQLdb I get the following error: >>> >>> ActivePython 2.5.2.2 (ActiveState Software Inc.) based on >>> Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08) >>> [GCC 3.3.1 (SuSE Linux)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> import MySQLdb >>> Traceback (most recent call last): >>> File "", line 1, in >>> ImportError: No module named MySQLdb >>> >>> But if I lrun python as the root user it imports fine. Can anyone >>> suggest what might be wrong with the installation? Or is there nothing >>> wrong? I haven't seen any examples that mentioned being root to import >>> a module. >> >> Try importing sys and printing out sys.path both with a "normal" account >> and the root-account, to see if there are any differences. And of course >> make sure both actually use the same interpreter. >> >> Beyond that, you are right: there is no root-only-importing. >> >> Diez > > Now that I look at, it appears it might not be the same interpreter. > When running python as root I get: > > Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > Which is completely different from when I'm a normal user (see original > post). And yes, sys.path is different. > > Being somewhat new to python and linux, how would I go about fixing > this? How do I get a normal user to run the same interpreter? Is it to > do with my PATH? Yes, you can either invoke the standard interpreter explicitly with $ /usr/bin/python or remove /the/path/to/activestate/python from your PATH. (If you were just experimenting and don't really need ActiveState I recommend that you remove it completely) Peter From tommy.nordgren at comhem.se Mon Jul 28 15:09:10 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Mon, 28 Jul 2008 21:09:10 +0200 Subject: like py2exe, but on a mac In-Reply-To: <_7ojk.253$wS4.85@trnddc03> References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> <_7ojk.253$wS4.85@trnddc03> Message-ID: On 28 jul 2008, at 20.22, William McBrine wrote: > On Mon, 28 Jul 2008 19:51:26 +0200, Tommy Nordgren wrote: > >> There is Platypus, a general open source program to wrap a script >> in an Macintosh (GUI) Application. > > Thanks. I tried Platypus, and it's close to what I want. But I still > can't seem to get rid of the small "Console" window that pops up > behind > my Tkinter app. > > -- > 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on > -- > http://mail.python.org/mailman/listinfo/python-list Try setting the Output popup menu to 'None' ------ What is a woman that you forsake her, and the hearth fire and the home acre, to go with the old grey Widow Maker. --Kipling, harp song of the Dane women Tommy Nordgren tommy.nordgren at comhem.se From mdw at distorted.org.uk Sun Jul 6 12:03:02 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Sun, 6 Jul 2008 16:03:02 +0000 (UTC) Subject: Nested generator caveat References: Message-ID: Dieter Maurer wrote: > I met the following surprising behaviour [code moved until later...] > The apparent reason is that the free variables in nested generator > definitions are not bound (to a value) at invocation time but only at > access time. No. This is about the difference between binding and assignment. Unfortunately, Python doesn't have explicit syntax for doing the former. Here's what's actually going on in your generator. >>>> def gen0(): > ... for i in range(3): > ... def gen1(): > ... yield i > ... yield i, gen1() The function gen0 contains a yield statement; it's therefore a generator. It contains an assignment to a variable i (in this case, it's implicit in the `for' loop). So, on entry to the code, a fresh location is allocated, and the variable i is bound to it. The function gen1 contains a yield statement too, so it's also a generator. It contains a free reference to a variable i, so it shares the binding in the outer scope. Here's the important part: the for loop works by assigning to the location named by i each time through. It doesn't rebind i to a fresh location. So each time you kick gen1, it produces the current value of i at that time. So... >>>> for i,g in gen0(): print i, g.next() > 0 0 > 1 1 > 2 2 Here, the for loop in gen0 is suspended each iteration while we do some printing. So the variable i (in gen0) still matches the value yielded by gen0. But... >>>> for i,g in list(gen0()): print i, g.next() > 0 2 > 1 2 > 2 2 Here, gen0 has finished all of its iterations before we start kicking any of the returned generators. So the value of i in gen0 is 2 (the last element of range(3)). > Almost surely, the same applies to all locally defined functions > with free variables. > This would mean that locally defined functions with free > variables are very risky in generators. It means that you must be careful about the difference between binding and assignment when dealing with closures of whatever kind. Here's an example without involving nested generators. def gen(): for i in xrange(3): yield lambda: i for f in gen(): print f() for f in list(gen()): print f() To fix the problem, you need to arrange for something to actually rebind a variable around your inner generator on each iteration through. Since Python doesn't have any mechanism for controlling variable binding other than defining functions, that's what you'll have to do. def genfix(): for i in xrange(3): def bind(i): def geninner(): yield i return geninner() yield i, bind(i) shows the general pattern, but since a generator has the syntactic form of a function anyway, we can fold the two together. def genfix2(): for i in xrange(3): def geninner(i): yield i yield i, geninner(i) Yes, this is cumbersome. A `let' statement would help a lot. Or macros. ;-) -- [mdw] From joan.pallares at gmail.com Fri Jul 18 12:39:30 2008 From: joan.pallares at gmail.com (=?ISO-8859-1?Q?Joan_Pallar=E8s?=) Date: Fri, 18 Jul 2008 18:39:30 +0200 Subject: Backtracking problem Message-ID: Hi, In my first message in the list I'm going to ask you to solve this problem or at least help me to solve it by myself: We have a list a couples created this way: *parejas = [(1, 'a'), (1, 'b'), (1, 'c'), (1, 'd'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c'), (3, 'd')]* We want to get all te possible combinations in an ordered way. Good combinations examples are: *1a,2b,3c 1a,2b,3d 1b,2a,3c* As you note, the numbers or characters cannont be repeated. The objective is to get one possible combination and if the user wants another possible combination he can get it. And if he wants to get bak the previous combiantion is also has to be possible. That's way I said to *get all possible combinations in an ordered way. * I made a Backtracking algorithm and I get the first result, but I'm not able to get the following result. Any help? My code, just in case it helps you: *parejas = [(1, 'a'), (1, 'b'), (1, 'c'), (1, 'd'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c'), (3, 'd')] print parejas listasCorrectas = [] lista = [] def numerosDiferentes(lista): numeros = [] letras = [] for numero,letra in lista: numeros.append(numero) letras.append(letra) if len(numeros) == len(set(numeros)) and len(letras) == len(set(letras)): return True return False def backTracking(parejas,lista): if len(lista) == 3 and numerosDiferentes(lista): listasCorrectas.append(lista) print 'LISTA CORRECTA',lista return if len(lista) < 2: lista.append(parejas[0]) print lista backTracking(parejas[1:],lista) while(not numerosDiferentes(lista) and len(lista)>1): lista = lista[:-1] lista.append(parejas[0]) print lista backTracking(parejas[1:],lista) backTracking(parejas,lista)* -------------- next part -------------- An HTML attachment was scrubbed... URL: From dstromberglists at gmail.com Thu Jul 10 00:25:53 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Thu, 10 Jul 2008 04:25:53 GMT Subject: error when porting C code to Python (bitwise manipulation) References: Message-ID: On Wed, 09 Jul 2008 20:56:59 -0700, Jordan wrote: > I am trying to rewrite some C source code for a poker hand evaluator in > Python. Putting aside all of the comments such as just using the C > code, or using SWIG, etc. I have been having problems with my Python > code not responding the same way as the C version. > > C verison: > > unsigned find_fast(unsigned u) > { > unsigned a, b, r; > u += 0xe91aaa35; > u ^= u >> 16; > u += u << 8; > u ^= u >> 4; > b = (u >> 8) & 0x1ff; > a = (u + (u << 2)) >> 19; > r = a ^ hash_adjust[b]; > return r; > } > > > my version (Python, hopefully ;)): > > def find_fast(u): > u += 0xe91aaa35 > u ^= u >> 16 > u += u << 8 > u ^= u >> 4 > b = (u >> 8) & 0x1ff > a = (u + (u << 2)) >> 19 > r = a ^ hash_adjust[b] > return r > > > As far as I understand the unsigned instructions in C just increase > amount of bytes the int can hold, and Python automatically converts to > longs which have infinite size when necessary, so I am not sure why I am > getting different results. > > I assume that I am missing something fairly simple here, so help a n00b > out if you can :) > > Thanks in advance, > > jnb What business does a poker hand evaluator have doing that kind of bitwise arithmetic? One problem with C is not the language itself, but the culture of using bitwise tricks where they aren't really necessary. Anyway, I believe in C unsigned bitwise arithmetic, when overflowing an integer will simply throw away the bits that are "too big". So if python is converting to a long when overflowing, that would cause a different result right there. You could try throwing in "&= 0xffffffff" all over the place if the C code was written for a 32 bit unsigned int. unsigned int will usually be 32 or 64 bits these days. If it's a 64 bit unsigned int in C, it'd be "&= 0xffffffffffffffff". From dickinsm at gmail.com Sun Jul 20 10:56:26 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 20 Jul 2008 07:56:26 -0700 (PDT) Subject: round function error??? References: <2da2f5f1-7ff2-46d7-a768-f0817e414615@f36g2000hsa.googlegroups.com> Message-ID: On Jul 19, 12:20?am, John Machin wrote: > On Jul 19, 8:05 am, Mark Dickinson wrote: > > for more information. ?But I'm guessing that you're > > questioning the fact that a value that's apparently > > *less* than 3499.35 is rounded up to 3499.4, rather > > than down to 3499.3. ?? > > "apparently" being the operative word. Well, it's not just an apparent problem: the closest floating-point number to 3499.35 really *is* less than 3499.35. A nice way to check this is using the new fractions module in 2.6, which allows exact conversions of floats and Decimals into rational numbers: Python 2.6b2+ (trunk:65155, Jul 20 2008, 15:39:46) [GCC 4.0.1 (Apple Inc. build 5484)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from decimal import Decimal >>> from fractions import Fraction >>> x = 3499.35 >>> y = Decimal('3499.35') >>> Fraction.from_float(x) Fraction(7695152029315891, 2199023255552) >>> Fraction.from_decimal(y) Fraction(69987, 20) [54933 refs] >>> Fraction.from_float(x) < Fraction.from_decimal(y) True Mark From wolfgang.grafen at ericsson.com Tue Jul 29 11:14:49 2008 From: wolfgang.grafen at ericsson.com (Wolfgang Grafen) Date: Tue, 29 Jul 2008 17:14:49 +0200 Subject: Parsing VHDL with python, where to start. In-Reply-To: References: <31888260-86a9-46b0-b0a4-79f7852f256a@k30g2000hse.googlegroups.com> Message-ID: <488F33E9.8090004@ericsson.com> Svenn Are Bjerkem schrieb: > Hi again, > > when I get far enough to parse the VHDL (which is not currently the > fact, but I have to look at the work coming up downstream) I will have > to put it into an internal data structure and then write some classes > to handle the MVC between whatever data I have and the PyQt4 widget > that is going to show the block diagram. I own the book "Rapig GUI > Programming with Python and Qt" by Mark Summerfield and try to read up > on the PyQt way of doing things as I try to make a plan for my > application. I have been looking for possible data structures with > google just to find out that most of the ideas are stored in > proceedings or to conferences or ieee papers not generally available > to me. Is anybody experienced with designing data structures willing > to share some ideas with me? Since I am using the open-source version > of PyQt4, any information will eventually be available to public (if > the app pass the planning stage) if that makes helping out any > easier: :-) There is already an app called Qucs that is running in > Qt-3 and being ported to Qt-4 that is written in C++, but I don't know > how wise it is to just reverse-engineering C++ classes and translate > them into python classes. For me it is not very clear what you intend to do. After years of parsing parts of VHDL from time to time the rapid parsing way for me is using regular expressions instead of one of the parser frame works because of following reasons: - It is hard for me to understand those frameworks - They are very slow - It is too much work for me to bring them up to work in a sensible way - Compared with regular expression matching they usually need a lot of extra work. Regular expressions work very well once the validation of the VHDL code was done by one of the commercial compilers. Once you can rely on the code that it is valid VHDL - Parse it with a regular expression for simple VHDL structures or - Extract a structure first and analyse that with a set of regular expressions The result can be stored into a combination of lists and dictionaries, dependend on the problem. For processing with other tools the results could be stored into XML structures. PyQt as a widget framework is not useful until here, but of course you could display your results in arbitrary graphical ways with PyQt, if you rally need to. You should know, printing out an ASCII or XML representation is so much more easy and quicker to code so I always prefer that. There are even editors/visualizers ready to display XML... Best regards Wolfgang From gagsl-py2 at yahoo.com.ar Tue Jul 15 00:26:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 01:26:03 -0300 Subject: a module.pth question References: <6a4f17690807140426m1d8d6544ye60a5bd560863389@mail.gmail.com> Message-ID: En Mon, 14 Jul 2008 08:26:49 -0300, oyster escribi?: > My py24 is installed in h:\python24 > I installed pyglet(http://pyglet.org/) in > H:\pure_pylib\Multimedia\pyglet-1.0\, if I do > [code] >>>> import sys >>>> sys.path.append(r'H:\pure_pylib\Multimedia\pyglet-1.0') >>>> import pyglet > [/code] > it is ok. > > but if I created h:\pure_pylib\pyglet.pth file, which containts > [code] > Multimedia\pyglet-1.0 > [/code] > > then > [code] >>>> import sys >>>> sys.path.append(r'h:\pure_pylib') >>>> import pyglet > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named pyglet .pth files are searched only when Python starts (specifically: when the site.py script is executed). If you later add a directory containing a .pth file, it is *not* processed. Put your .pth files inside a directory *already* in the search path - see http://docs.python.org/lib/module-site.html -- Gabriel Genellina From skip at pobox.com Tue Jul 22 21:09:26 2008 From: skip at pobox.com (Skip Montanaro) Date: Wed, 23 Jul 2008 01:09:26 +0000 (UTC) Subject: software engineering foundations? References: <18566.11394.326317.821553@montanaro-dyndns-org.local> Message-ID: > just get McConnell's "Code Complete": > > http://www.cc2e.com/ Thanks Fredrik. It looks interesting. I just bought a copy online and will skim it myself before passing it along to Chris. Skip From ldo at geek-central.gen.new_zealand Sat Jul 26 19:45:39 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 27 Jul 2008 11:45:39 +1200 Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: In message , Thomas Troeger wrote: > Finally, I'd like to throw in this one from the Linux kernel sources, > from `Documentation/CodingStyle: > > ------------------------------------------------------------------------ > > Chapter 1: Indentation > > Tabs are 8 characters, and thus indentations are also 8 characters. > There are heretic movements that try to make indentations 4 (or even 2!) > characters deep, and that is akin to trying to define the value of PI to > be 3. > > [...] > > Now, some people will claim that having 8-character indentations makes > the code move too far to the right, and makes it hard to read on a > 80-character terminal screen. The answer to that is that if you need > more than 3 levels of indentation, you're screwed anyway, and should fix > your program. Which is, of course, a load of nonsense. From szrRE at szromanMO.comVE Tue Jul 22 18:14:41 2008 From: szrRE at szromanMO.comVE (szr) Date: Tue, 22 Jul 2008 15:14:41 -0700 Subject: proliferation of computer languages References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> <40429b65-23a0-489b-b5fd-ae6b8eee607d@t54g2000hsg.googlegroups.com> Message-ID: Grant Edwards wrote: > On 2008-07-22, szr wrote: >> J?rgen Exner wrote: >>> Chris Rathman wrote: >>> >>>> I can't say that I see any particular point to the essay. >>> >>> You must be new here. There never is any particular point to >>> Xah Lee's rantings except to cross-post borderline topics to >>> borderline relevant NGs and then lay back and enjoy the >>> ensuing slaughter. >> >> Admittedly, I'm not all too familiar with his postings, but on >> a general note, isn't it possible that someone else might not >> see it the same as you do? I really didn't see anything really >> sinister about the posting or it's content. > > That's the, uh, "beauty" of Xah Lee's posts. There's enough > "there" there to suck people into what they think is going to > be a conversation. But it's not really a conversation. He > doesn't really read (or doesn't comprehend) responses to his > posts and will just continue to ramble on in a somewhat > insulting, half-rational stream of utterly opaque metaphors > that he thinks makes him sound deeply philosphical. It has > been theorized that he's an AI project. So, some dark government experiment gone horribly wrong? >> It may very well be someone attempting to create a >> conversation, someone who may not be generally well received a >> lot of the time I gather. > > Quite a few people here in c.l.p put forth a a lot of effort > (for Usenet, anyway) trying to have a reasonable exchange with > xah lee, but it seems to be pointless. He's a perpetual critic > who looks down his nose at everything and thinks he could do > everything better than everybody else (not that he has actually > ever _done_ anything, AFAICT). That's good to know. >> Also, if have such a distaste for his postings, you are free >> to ignore them as well. That said, I am all for alerting >> someone of something which may be a complete waste of their >> time, > > It's not a waste of your time if you find him entertaining, but > I wouldn't expect any actual conversation where he reads and > understands your replies and responds to them in a rational > manner. Yeah I wasn't really aware it was that bad. >> but in this case it feels like you are projecting your >> own dislike for the OP. Unless the OP really is deserving of >> such branding (in which case I'd stand corrected), I don't >> think it is reason enough to tell others not to read of his >> work just because you aren't particularly fond of it. >> >> Perhaps citing an actual example illustrating a reason to >> avoid him like the plague would of helped :-) > > google groups should be able to find you plenty of examples > both here and in perl groups. Thank you for filling in some voids. -- szr From frankrentef at yahoo.com Tue Jul 29 14:26:28 2008 From: frankrentef at yahoo.com (frankrentef) Date: Tue, 29 Jul 2008 11:26:28 -0700 (PDT) Subject: Python / PAMIE - scriptWrite Function Message-ID: In using PAMIE 2.0 specifically the "scripWrite" function I'm getting the following error... File "C:\Python23\Lib\site-packages\win32com\client\dynamic.py", line 489, in _getattr_ further states... raise AttributeError, "%s.%s" % (self._username_, attr) Help... :) From martin at v.loewis.de Mon Jul 28 17:06:04 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Mon, 28 Jul 2008 23:06:04 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: <5Gojk.254$wS4.153@trnddc03> References: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> <488cbeeb$0$17104$9b622d9e@news.freenet.de> <5Gojk.254$wS4.153@trnddc03> Message-ID: <488E34BC.4060005@v.loewis.de> > I hadn't heard "Intel 64" before. That's a bit nervy, isn't it? Plus it > seems to conflict with their own use of "IA-64" (Intel Architecture 64) > for the Itanium (vs. "IA-32" for traditional x86). Indeed. Microsoft Installer has an architecture string for the MSI file; "Intel64" there means Itanium (and AMD64 can be denoted by either "AMD64" or "x64"). This was from a time when Intel still told people that the future of 64-bit computing is in Itanium (and architecturally, I still think this would have been the right choice). Regards, Martin From quekshuy at gmail.com Thu Jul 3 13:51:19 2008 From: quekshuy at gmail.com (Quek) Date: Thu, 3 Jul 2008 10:51:19 -0700 (PDT) Subject: Times where one would use new style classes vs classic classes References: <6700e4ba-8573-44da-b75a-3b3e5ba1fd9b@i36g2000prf.googlegroups.com> <486c7ba7$0$10446$426a74cc@news.free.fr> Message-ID: <75aa3baa-f495-4d51-bf48-185ad966fe5d@u6g2000prc.googlegroups.com> On Jul 3, 3:11?pm, Bruno Desthuilliers wrote: > Quek a ?crit : > > > Hi all, > > > I'm reallynewto Python and I've been reading up some texts on older > > versions of Python (2.2 to be specific). > > > The text briefly mentionednewstyleand classic classes. > > > I'd really like to know in the current context of Python 2.5, besides > > in the cases of multi-inheritance, where would I usenewstyle > > classes? > > Everywhere you don't have to support compat with ages-old versions of > Python. MI is not the main point of newstyle classes (FWIW, you can do > MI with old-styleclasses too), they have quite a lot more to offer. > Consider "classic" classes as a legacy feature, period. Thanks everyone. From norseman at hughes.net Thu Jul 17 15:04:43 2008 From: norseman at hughes.net (norseman) Date: Thu, 17 Jul 2008 12:04:43 -0700 Subject: Rotating a cube In-Reply-To: References: Message-ID: <487F97CB.10404@hughes.net> J-Burns wrote: > Hello. Need some help here. I have a 4*4 cube. So the equation of the > cube becoming: > > x + 4*y + 16*z > > Now i want to rotate this cube 90 degrees anticlockwise( a right > rotation). How can i do that? The rotation must take place with the > axis of rotation being the straight line through the center of the > cube and perpendicular to the "xz-plane." The axis are aligned in this > fashion: > > y > | > | > |________ x > / > / > z > > Moreover, also tell me how to perform a rotation with the axis of > rotation being the straight line through the center of the cube and > perpendicular to the "yz-plane." > > Essentially, I need the equations of the lines after the rotation has > been done in both cases. > Is there a built in Python function for this? > -- > http://mail.python.org/mailman/listinfo/python-list > ====================================== OH-Boy! 1) a regular cube is dimensioned having three mutually perpendicular axis, each of same length. The 4x4 would be for a plane. 2) Clockwise IS Angles Right. (Rotate to right.) Normal Angles Right would put zero at +Y, 90 at +X as viewed from +Z. Norman Angles Right would put zero at +Z, 90 at +Y as viewed from +X. Normal Angles Right would put zero at +Z, 90 at -X as viewed from +Y. (there are six faces, finish the defs for the rest.) 3) Normally all rotations are defined as pivoting about the 0,0,0 point. To use center of a plane or other pivot point is to add offsets. 4) Sequence of rotations controls final spatial orientation. As for finding a cube handling graphic in the standard package download, I did not. Somebody else can answer if there is a full blown Python vector graphic package. At a minimum you need to define a: rotational routine that handles N 3D points as a single bundle. The usual routines consider each rotation as being about a single axis. It computes all N corners each time. translation routine that moves N 3D points as a single bundle along a single 3D vector. It computes all N corners each time. scaler routine that expands/contracts the relative distances between the N 3D points using vectors from the computed 3D center. It computes all N corners each time. Some pre-/post routines to put things together to get the desired effects. If N=0 (the nothing) there is nothing to do. If N=1 (the point) there is no rotation or scale. If N>1 (the line,plane,box,sphere,torus,etc.) then use all three. (a sphere can be computed as three points of an isosceles triangle in which the third side can equal the other two. The points then are used to create a circle (ellipse) which is rotated about the third side. In case it isn't obvious - the perpendicular bisector of the third side is the center of the sphere. To track a point on a sphere is simply to use 4 points. 0,1,2 are triangle and 3 is the point. Do your thing on all 4, use 0,1,2 to remake sphere and 3 will be right place.) The Chemical Rubber Company's Handbook of Physics and Chemistry is a good starting point for the equations. Johnny, George, Willie and I also used a few Celestial Mechanics books from the Library when we wrote those in assembly in the long ago and far away. (back in the '60s on the other side of the continent.) Sorry, but the punch cards disappeared long ago and access to CAD programs deletes my need to re-write them. Steve norseman at hughes.net From wjmtrade003 at gmail.com Fri Jul 18 13:17:55 2008 From: wjmtrade003 at gmail.com (avan) Date: Fri, 18 Jul 2008 10:17:55 -0700 (PDT) Subject: accept paypal,www.wjmtrade.com sell adidas35 jordan af1 bape puma Message-ID: <5009fd51-e24d-4b34-8307-ba1ddb7f1490@u12g2000prd.googlegroups.com> We are manufacturer/wholesaler for branded sport shoes and clothings, supplying 3A quality product with reasonable price, such as series of : Jordan 1-22 Air force one (AF1),Dunks, air max 95,97,2003,2004,2005,tn shox TL/TL2/TL3, R4/R5, monster, turbo, NZ bape shoes,adidas ,Timberlands etc. t-shirt, hoody, jeans,bag, watch etc. 1) high quality. All the Shoes we offer are of the grade AAA. Packing: original box with retro cards tags 2) safety. We have a lot of experience to pass the custom inspection. 3) fast shipment. We have agreement with some international express Corporation, the shoes will be sent out within 24 hours after we receive your Payment. You will receive the shoes within 5-7 days. 4) lowest Price. We can give you competitive price based on equal conditions in china. 5) We are very serious business man.hope do the long term business with you! please kindly visite our website: www.wjmtrade.com msn: wjmtrade at hotmail.com email: wjmtrade at gmail.com From fredrik at pythonware.com Wed Jul 16 05:16:28 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 11:16:28 +0200 Subject: Testing for connection to a website In-Reply-To: <18476597.post@talk.nabble.com> References: <18473382.post@talk.nabble.com> <18476597.post@talk.nabble.com> Message-ID: Alexnb wrote: > e = '' > try: > ... > except HTTPError, e: > print e.code > except URLError, e: > print e.reason > > if e == '': > print "good to go" footnote: here's a better way to test if an exception was raised or not: try: ... except HTTPError, e: print e.code except URLError, e: print e.reason else: print "good to go" From h.goebel at goebel-consult.de Wed Jul 30 03:48:52 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Wed, 30 Jul 2008 09:48:52 +0200 Subject: Using McMillan Installer, PyInstall or py2exe cross-platform? In-Reply-To: <6e1492db-6868-4554-9b85-96c1717b6b6a@s50g2000hsb.googlegroups.com> References: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> <487d100a$0$7538$9b4e6d93@newsspool1.arcor-online.net> <6e1492db-6868-4554-9b85-96c1717b6b6a@s50g2000hsb.googlegroups.com> Message-ID: <48901ce5$0$20699$9b4e6d93@newsspool4.arcor-online.net> Paul Boddie schrieb: > On 15 Jul, 23:00, Hartmut Goebel wrote: >> I started working on cross-pyinstall today. > > Let us know how you get on! In theory, one should be able to build > Python (and derived works) using the mingw32 libraries and a suitable > cross-compiler on platforms other than Windows, but I've never > bothered to do so myself. Pyinstaller trunk is now able to build exe for Windows on Linux/Unix. This includes only the "bundling" of scripts and modules into an exe, not compiling anything. -- Sch?nen Gru? - Regards Hartmut Goebel Goebel Consult Spezialist f?r IT-Sicherheit in komplexen Umgebungen http://www.goebel-consult.de From frank at chagford.com Thu Jul 31 02:30:16 2008 From: frank at chagford.com (Frank Millman) Date: Wed, 30 Jul 2008 23:30:16 -0700 (PDT) Subject: Questions about asyncore References: <5d30aad5-cad7-4e47-aa83-277202c70ae2@z72g2000hsb.googlegroups.com> <6db7042c-02bb-42ef-b578-3811d8f427f5@m36g2000hse.googlegroups.com> <4903018c-feac-40fb-81fc-002dfc430f84@z66g2000hsc.googlegroups.com> Message-ID: <85bd837a-62e3-455d-8bec-3d778231bfc5@i76g2000hsf.googlegroups.com> On Jul 30, 7:50?pm, "Giampaolo Rodola'" wrote: > On 30 Lug, 09:49, Frank Millman wrote: > Thanks again, Giampaolo, your input is really appreciated. > > I pretty much have the same overview I had before. > As far as I can tell the only reason you want to use a thread is when > you have to do something which requires a consistent amount of time to > complete so that the asyncore loop gets blocked. > The question is: is there anything like that in your code? > If the answer is no then you don't need to use threads. > Maybe you are just not used to the asynchronous approach where "wait > for server to respond" or "wait for the response to be complete" > doesn't mean that YOU have to wait. > It means that when a specific condition occurs (e.g. some data is > received) a certain method of the framework you're using will be > called and then it will be up to you deciding what do to. Maybe I am not being clear enough on my side. I (hope I) understand the power of asnyc. I have written the server to use async techniques, and when I get around to writing the full-blown client, that will also use async techniques. However, at this stage, all I want to do is write something quick and dirty to check that the server is behaving as intended. I want to throw some messages at it, more or less at random, and check the responses. I found it much easier to do this with asyncore.loop running in a separate thread. To send a message from the main thread, I append it to a list called self.sendData. In asyncore.dispatcher, writable() returns True if the list contains anything, and handle_write() pops the message off the list and sends it. To receive messages, readable() always return True, and handle_read() breaks up the input into individual messages and appends them to a list called self.recvData. When the main thread is waiting for a response, it simply loops until self.recvData contains something. To do this asynchronously, for every test I would have to define the detailed interaction between client and server, and write methods to be called from within handle_read(). It could be done, but it would be much more tedious. Does this make sense? Frank From alif016 at gmail.com Mon Jul 7 21:53:15 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Mon, 07 Jul 2008 20:53:15 -0500 Subject: Python Agile Software Development Tools Screencasts In-Reply-To: <87abgtw52g.fsf@benfinney.id.au> References: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> <87lk0dwbys.fsf@benfinney.id.au> <87hcb1w6gl.fsf@benfinney.id.au> <87abgtw52g.fsf@benfinney.id.au> Message-ID: <4872C88B.4080307@gmail.com> Ben Finney wrote: > Robert Kern writes: > > >> Ben Finney wrote: >> >>> Okay. Where would the public link to those files be? >>> >>> If I need to "log in" just to download it, that's a needless barrier >>> that's going to turn me away too. >>> >> Yes, you do need to log in. >> > > Thanks. > > >> If you don't want to do it, that's fine. I certainly don't care. >> > > No problem. > > I hope the OP, who wanted people to see his videos, does care enough > to put them somewhere people can get them without needless barriers. > > The URL for the flv is: http://videos1.showmedo.com/ShowMeDos/2910000.flv I hope the presenter doesn't mind, but it is quite simple to discover using open source tools like firebug. As for playing back flvs with free software, there is Gnash -- an open source flash player -- http://www.gnu.org/software/gnash/ -- Andrew From Bill at SynectixLtd.com Fri Jul 4 10:03:19 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Fri, 4 Jul 2008 15:03:19 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: "Tim Golden" wrote in message news:mailman.61.1215177888.20628.python-list at python.org... > Bill Davy wrote: >> I am trying to edit Contacts in Outlook. This is so I can transfer >> numbers from my address book which is an Excel spreadsheet to my mobile >> phone. I came across the following snippet of code > > --- hey! that looks familiar :) > >> which enabled me to the contacts at least list. I had to root around to >> discover CdoDefaultFolderContacts (though it was guessable; how could I >> enumerate win32com.client.constants?). > > Well that bit's easy: win32com.client.constants is a small class with > a __dicts__ attribute (note the "s") which is a list of dictionaries, one > per generated library. So you can do something like this: > > > import win32com.client > > outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") > outlook_constants = win32com.client.constants.__dicts__[0] > > for k, v in outlook_constants.items (): > print k, "=>", v > > > >> I now want to work through the Contacts in Outlook patching in data from >> my spreadsheet, and also making new contacts where there is an entry in >> my spreadsheet which has not gone into Contacts already. > > OK. > >> Where can I find the API? > > I recommend: > > http://msdn.microsoft.com/en-us/library/ms526861.aspx > > and > > http://www.outlookcode.com/article.aspx?id=20 > > and > > http://www.cdolive.com/cdo10.htm > > TJG Brilliant. But I was a bit disappointed by one experiment. In MSDN I found "Exploring the Outlook Object Model". That suggested: Outlook | Tools | Macros | VB Editor | View | Object Browser There I found ContactItems and reckoned I was onto a winner, but found that a "message" from the ContactFolder might have Subject but it did not have a FullName. Also, if Python crashed, it left Outlook complaing that someone was accessing it but had disappeaared so Outlook has to be restarted each time. But you have suggested some more things to look at so thanks. I have had a quick look but have not so far even found "Subject" as a member/property of a message/contact. I shall keep looking. Rgds, Bill From manuel.dipl at gmail.com Mon Jul 14 14:46:43 2008 From: manuel.dipl at gmail.com (manu) Date: Mon, 14 Jul 2008 11:46:43 -0700 (PDT) Subject: trying to use sax for a very basic first xml parser References: <6ff86003-a3e8-4c5b-9276-1cd3c7f0ffa7@56g2000hsm.googlegroups.com> <3a7148a9-b95d-4e95-b3b7-492e0d016ab8@f36g2000hsa.googlegroups.com> Message-ID: On Jul 14, 8:14?pm, Miki wrote: > Python is using an external library for SAX (expat IIRC). > I *guess* the Python that comes with Blender don't have this library. > I don't know... I didnt install any external libraries for sax. I think python comes with a standard sax library. And before I had python installed Blender said at startup: "Compiled with Python version 2.5. Checking for installed Python... No installed Python found. Some scripts will not run. Continuing happily" After installing Python 2.5.2 it now says: "Compiled with Python version 2.5. Checking for installed Python... got it!" So I think it is using the installed Python. Could it be that I have to install the same python version Blender was compiled with? From tjreedy at udel.edu Tue Jul 1 18:08:16 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 01 Jul 2008 18:08:16 -0400 Subject: Implementing an 8 bit fixed point register In-Reply-To: References: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> Message-ID: Grant Edwards wrote: > On 2008-07-01, Terry Reedy wrote: >> >> nickooooola wrote: >>> Hello to all >>> I'm about to write a simulator for a microcontroller in python >>> (why python? because I love it!!!) >>> >>> but I have a problem. >>> >>> The registry of this processor are all 8 bit long (and 10 bit for some >>> other strange register) >>> and I need to simulate the fixed point behaviour of the register, >>> and to access the single bit. >> In Python3, I would use a (mutable) bytearray. >> >> IDLE 3.0b1 >>>>> reg1 = bytearray((0,)*8) # or *10 for 10 bits >>>>> reg1 >> bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00') >>>>> reg1[1]=1 >>>>> reg1[1] >> 1 >>>>> tuple(reg1) >> (0, 1, 0, 0, 0, 0, 0, 0) >> >> A bytearray subclass could enforce that all 'bits' (stored as bytes) are >> 0 or 1, have a customized representation to your taste, and add methods >> like .flipall(). > > It seems like implementing ALU operations on such arrays would > be a lot more work than implementing bit-indexing on a type > derived on a more "integer" like base. I'm pretty fuzzy on how > one sub-classes basic things like integers, so maybe I'm all > wet, and adding __getitem__ and __setitem__ to an integer type > isn't even possible. If one only wants bit operations, then the array approach is easy. If one only wants int arithmetic and all-bits logic, then int approach is easy. OP did not completely specify needs. The problem with the int approach is that ints are immutable. Therefore, if one wants to subclass int to hide the bit masking for the bit operations, one must override *every* operation one might use, including all arithmetic and all-bits logic, even when the int operation gives the correct answer other than the class of the result. class bits(int): ... def __add__(self,other): return bit(self+other) ... If one does not, a,b = bits(1),bits(2) c = a+b #c is now an int, not a bits So there is a tendency to not subclass and instead either leave the extra functionality unmasked in repeated code or to put it in functions instead. setters = (1,2,4,8,16,32,64, ..., 2147483648)# slightly pseudocode unsetters = (~1,~2,~4,...~2147483648) # ditto def bitset(n, bit): return n | setters[bit] def bitunset(n,bit): return n & unsetters[bit] thus not getting the nice reg[n] functionality, nor an easy display of individual bits without callings *another* function. One the other hand, with mutable arrays, setting bits is a mutation and so no override of __setitem__ is required unless one wants to be fancy and enforce setting to 0 or 1. It is a trade-off. Terry Jan Reedy From michele.simionato at gmail.com Sun Jul 27 00:58:29 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 26 Jul 2008 21:58:29 -0700 (PDT) Subject: How to close all python-opened file identifiers? References: Message-ID: <4b2ee8eb-e9e1-4338-b099-5355854d063f@i76g2000hsf.googlegroups.com> On Jul 26, 2:19?am, BAnderton wrote: ?Although I > can't find unmatched "open" and "fid.close()" statements, I'd like to > implement a check for open file identifiers before launching the > editor. So you need a debug tool to track down the opened files. How about that: # assume Python 2.5 from __future__ import with_statement import __builtin__ orig_file = __builtin__.file # you could do the same for open class ChattyFile(file): opened = [] def __init__(self, *args, **kw): super(ChattyFile, self).__init__(*args, **kw) self.opened.append(self) print 'opened %s' % self def close(self): super(ChattyFile, self).close() self.opened.remove(self) print 'closed %s' % self class ContextManager(object): def __init__(self): self.opened = ChattyFile.opened def __enter__(self): __builtin__.file = ChattyFile def __exit__(self, *exc_info): __builtin__.file = orig_file chattyfile = ContextManager() with chattyfile: f = file('x.txt', 'w') f.write('hello') f.close() file('x.txt') print chattyfile.opened gives: $ python chattyfile.py opened closed opened [] Warning: I did not test this more than you see. Notice also that overriding the builtins is fine for debugging purposes (it is perhaps the only good use case for this feature, together with testing, for mock objects). You are expected to use it as follows: from chattyfile import chattyfile from mylibrary import main with chattyfile: main() and all calls to 'file' will be tracked down. Since 'open' is basically an alias for 'file' (they were exactly the same in Python 2.4) you could also track 'open' in the same way. If you are using Python 2.4 you can use the same trick, but in a less clean way, using a try ..finally instead of the context manager. Michele Simionato From s0suk3 at gmail.com Wed Jul 16 06:55:10 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Wed, 16 Jul 2008 03:55:10 -0700 (PDT) Subject: Modify a string's value References: <8c7245ed-2341-4283-988c-8a8adf3e58fd@56g2000hsm.googlegroups.com> <87k5fm4ecl.fsf@benfinney.id.au> Message-ID: On Jul 15, 11:55 pm, Ben Finney wrote: > s0s... at gmail.com writes: > > I just came across this unusual situation where I'd like to modify a > > string passed to a function > > Again: Why? The normal way to do this is to create a new string and > return that. > Yes, usually, but that won't work in this case (look at my previous post around the 'cin >> line' line). This is what I came up with: class StreamLineBuffer: def __init__(self): self.buf = "" def __rrshift__(self, stream): self.buf = stream.readline() def __str__(self): return self.buf cin = sys.stdin buf = StreamLineBuffer() cin >> buf line = str(buf) Works like a charm :) From basti.wiesner at gmx.net Thu Jul 24 12:49:16 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Thu, 24 Jul 2008 18:49:16 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> Message-ID: Torsten Bronger : > Hall?chen! > > Bruno Desthuilliers writes: > >> Torsten Bronger a ?crit : >> >>> Bruno Desthuilliers writes: >>> >>>> [...] >>>> >>>> How would you handle this case with an implicit 'self' : >>>> >>>> class Foo(object): >>>> pass >>>> >>>> def bar(self): >>>> print self >>>> >>>> Foo.bar = bar >>> >>> Just like this. However, the compiler could add "self" to >>> non-decorated methods which are defined within "class". >> >> What's defined within classes are plain functions. It's actually >> the lookup mechanism that wraps them into methods (and manage to >> insert the current instance as first argument). > > And why does this make the implicit insertion of "self" difficult? > I could easily write a preprocessor which does it after all. Who said, that it would be "difficult"? He just corrected your statement about definitions inside a class, and did not make any assumption about making "self" implicit. I'd assume, that making self implicit wouldn't be that difficult to assume. But does the fact, that it could easily be done, alone mean, that it _should_ be done? The explicit "self" was a design decision, that can't really be judged by technical arguments from implementation side. Its a discussion about design from a programmers point of view ... -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From wilson.t.thompson at gmail.com Sat Jul 5 02:24:08 2008 From: wilson.t.thompson at gmail.com (wilson) Date: Fri, 4 Jul 2008 23:24:08 -0700 (PDT) Subject: how to get selected filename in FileSelectBox Message-ID: hi i am using tix FileSelectBox in my application .I want to get the selected filename as a string i do this as follows fselectbox=FileSelectBox(someframe) fselectbox.__setitem__("dir",join(fselectbox.cget("dir"),"..")) fselectbox.pack(side=LEFT) ... selectedfile=fselectbox.selection.cget("value") fselectbox.selection.selection_clear() print "file=",selectedfile i did these by going thru the docs in tix ,actually i couldn't find an example so i am not sure if this is the right way..it does print the filename but i want to know if this is the way..Can someone comment? Wilson From samwyse at gmail.com Tue Jul 8 08:26:01 2008 From: samwyse at gmail.com (samwyse) Date: Tue, 8 Jul 2008 05:26:01 -0700 (PDT) Subject: Logging to zero or more destinations Message-ID: In the Python 2.5 Library Reference, section 14.5.3 (Logging to multiple destinations), an example is given of logging to both a file and the console. This is done by using logging.basicConfig() to configure a log file, and then calling logging.getLogger('').addHandler(console) to add the console. However, in section 14.5.4 (Sending and receiving logging events across a network), a call is made to rootLogger.addHandler(socketHandler), and later it is stated that "On the client side, nothing is printed on the console". Finally, back in section 14.5.2 (Basic example), it's stated that "by default, the root logger is configured to only handle messages with a severity of WARNING or above. The message format is also a configuration default, as is the output destination of the messages - sys.stderr." The only way that I can see for all three statements to be consistent is that the root logger starts with an empty list of handlers, and doesn't instantiate a default handler until either logging.basicConfig() is called, or the first time that a message is logged. This would also seem to imply that there's no way to use an empty handler list (say, if you want to suppress all logging), because the root handler will instantiate a handler for you. Is this correct? P.S. I tried researching this further by myself, but the logging module doesn't come with source (apparently it's written in C?) and I don't have the time to find and download the source to my laptop. Thanks! From code at pizzashack.org Fri Jul 18 17:41:59 2008 From: code at pizzashack.org (Derek Martin) Date: Fri, 18 Jul 2008 17:41:59 -0400 Subject: Multiple variable control in for loops. Doable in Python? In-Reply-To: <20080718212832.GA1994@dragontoe.org> References: <28efa6970807181221o67c90575w690464f1442dc47d@mail.gmail.com> <20080718212832.GA1994@dragontoe.org> Message-ID: <20080718214159.GA3043@dragontoe.org> On Fri, Jul 18, 2008 at 05:28:32PM -0400, Derek Martin wrote: > def control(i, j): > print i,j > if not (i < 5 or j < 10): Rather, if not (i < 5 and j < 10): > return > else: > control(some_increment_function(i), other_increment_function(j)) -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From fredrik at pythonware.com Wed Jul 23 03:19:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 09:19:58 +0200 Subject: How to replace the values with keys ? In-Reply-To: <92df0f7c0807222130n382edf5di8c7124690f3dffa7@mail.gmail.com> References: <92df0f7c0807222130n382edf5di8c7124690f3dffa7@mail.gmail.com> Message-ID: "Graps Graps" wrote: > Text2 is a python dictionary containing data as > > {0: 'a', 1: 'b', 2: 'c'...} > > now I want the data in text1 to be replaced with the keys, say like > > 0 1 > 0 2 > 0 3 > 0 6 > 1 2... so on.. someone asked a very similar question not long ago, so maybe you're really supposed to figure this out yourself. I'm sure your teacher won't kill you if you ask for a hint. (if you asked me for a hint, I'd tell you to look for questions about dictionaries in the mailing list archives). From wuwei23 at gmail.com Wed Jul 23 09:16:50 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 23 Jul 2008 06:16:50 -0700 (PDT) Subject: os.walk question References: Message-ID: On Jul 23, 10:11?pm, Larry Bates wrote: > import glob > random.choice([f for f in glob.glob(root, "*")]) glob.glob only accepts one argument though, did you mean root + "*"? It also returns folders as well as files, though, and the list comprehension is not necessary given it returns a list itself. From theller at python.net Wed Jul 23 10:39:29 2008 From: theller at python.net (Thomas Heller) Date: Wed, 23 Jul 2008 16:39:29 +0200 Subject: python.exe crash and ctypes use In-Reply-To: References: Message-ID: <6eou4dF82ehaU1@mid.individual.net> waldek schrieb: > Hi, > > I have module A.py and B.dll which exports C functions by cdecl_ > > In A.py I pass callback (py callable) to dll. Next, thread inside dll > simply calls my callback (in a loop). After few secs I got crash of > python.exe. > > How to debug it? > > I'm using winxp and py 2.5.2 > > > =========================== > def mycallback(data, size) > return 0 > > CBFUNC = CFUNCTYPE(c_int,POINTER(c_int), c_int) > dll = cdll.mydll > > if dll.RegisterCallback(CBFUNC(mycallback)) != 0: > print "Error." > =========================== You need the callback function instance - what the CBFUNC(mycallback) call returns - alive as long as some C code is calling it. If you don't sooner or later the Python garbage collector will free it since it seems to be no longer used. ctypes does NOT keep the callback function alive itself. Thomas From ddasilva at umd.edu Wed Jul 30 01:08:26 2008 From: ddasilva at umd.edu (Daniel da Silva) Date: Wed, 30 Jul 2008 01:08:26 -0400 Subject: iterating "by twos" In-Reply-To: References: Message-ID: <8d9ec3dd0807292208p3ff225bs49a9ca5c748a0360@mail.gmail.com> The following method is similar to the others provided, but yields an index value as well (similar to the enumerate(iterable) function). This is useful in some (but not all) situations. If the iterable object's iterator returns an even number of items then you're fine; otherwise it will throw away the last item because it doesn't have a full pair to return. ------------------------- import itertools def enumeratePairs(x): it = iter(x) for i in itertools.count(): p = it.next() q = it.next() yield i, (p,q) raise StopIteration -------------------------- >>> for v in enumeratePairs("hello i am daniel"): ... print v ... (0, ('h', 'e')) (1, ('l', 'l')) (2, ('o', ' ')) (3, ('i', ' ')) (4, ('a', 'm')) (5, (' ', 'd')) (6, ('a', 'n')) (7, ('i', 'e')) ------------------------------- On Tue, Jul 29, 2008 at 1:36 PM, kj wrote: > > > > Is there a special pythonic idiom for iterating over a list (or > tuple) two elements at a time? > > I mean, other than > > for i in range(0, len(a), 2): > frobnicate(a[i], a[i+1]) > > ? > > I think I once saw something like > > for (x, y) in forgotten_expression_using(a): > frobnicate(x, y) > > Or maybe I just dreamt it! :) > > Thanks! > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. > -- > http://mail.python.org/mailman/listinfo/python-list > From misceverything at gmail.com Wed Jul 23 19:30:17 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Wed, 23 Jul 2008 16:30:17 -0700 (PDT) Subject: Run as Service References: <09c0bfa9-c86b-4153-ba91-cb9bf2e85e2a@k30g2000hse.googlegroups.com> Message-ID: <7c79c170-a92b-42d5-9362-5c3370118b59@m73g2000hsh.googlegroups.com> Jay/Larry - Thanks for the suggestions! From gherron at islandtraining.com Wed Jul 9 11:43:58 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 09 Jul 2008 08:43:58 -0700 Subject: Opening Unicode files In-Reply-To: <636110.21350.qm@web27405.mail.ukl.yahoo.com> References: <636110.21350.qm@web27405.mail.ukl.yahoo.com> Message-ID: <4874DCBE.6000902@islandtraining.com> Noorhan Abbas wrote: > Hello, > I wonder if you don't mind helping me out in this problem. I have been > developing a tool in python that opens some unicode files, reading > them and processing the data. It is working fine. When I started to > write a cgi module that does the same thing for google > appengine(actually it is using the same files that I used befoer), I > get an error: > > f = codecs.open (FileName , 'rU', 'utf-8') > > It says that the above functions takes 3 arguments but 4 were given. Truly? I ran that line and found it works perfectly. What version of python are you using (I used 2.5.1). What OS? (That should not matter, however you should tell us anyway.) Are you sure your codecs is the Python module imported normally. (You may have to show us all your code.) With no code and a careful look at your error message, here's my guess: That error message is what you get when you call an instance's method with the wrong number of arguments. (And in that case the extra argument it's referring to is the instance itself begin passed in as the first (self) parameter.) I believe your codecs value is no longer the imported module, but rather some instance object you've assigned into it: codecs = ...something overwriting the module object ... Gary Herron > I wonder if I need to do something before using the codecs library > from within the cgi module?! > > Thank you very much for your help, > Nora > > ------------------------------------------------------------------------ > Not happy with your email address? > Get the one you really want > - millions of new email addresses available now at Yahoo! > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From Perl_Wizard at manx.net Sun Jul 20 13:39:52 2008 From: Perl_Wizard at manx.net (Perl_Wizard at manx.net) Date: Sun, 20 Jul 2008 18:39:52 +0100 (BST) Subject: question Message-ID: <200807201739.CQT04024@manxnetsf02.manx.net> Nobody any sensible answers. Too complicated I suppose! From Nikolaus at rath.org Mon Jul 28 06:23:21 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 28 Jul 2008 12:23:21 +0200 Subject: Protecting instance variables References: <6eb9iaF6779oU1@mid.uni-berlin.de> Message-ID: <877ib6s3xi.fsf@nokile.rath.org> Hi, Sorry for replying so late. Your MUA apparently messes up the References:, so I saw you reply only now and by coincidence. "Diez B. Roggisch" writes: > Nikolaus Rath schrieb: >> Hello, >> >> I am really surprised that I am asking this question on the mailing >> list, but I really couldn't find it on python.org/doc. >> >> Why is there no proper way to protect an instance variable from access >> in derived classes? >> >> I can perfectly understand the philosophy behind not protecting them >> from access in external code ("protection by convention"), but isn't >> it a major design flaw that when designing a derived class I first >> have to study the base classes source code? Otherwise I may always >> accidentally overwrite an instance variable used by the base class... > > Here we go again... > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/188467d724b48b32/ > > To directly answer your question: that's what the __ (double > underscore) name mangling is for. I understand that it is desirable not to completely hide instance variables. But it seems silly to me that I should generally prefix almost all my instance variables with two underscores. I am not so much concerned about data hiding, but about not accidentally overwriting a variable of the class I'm inheriting from. And, unless I misunderstood something, this is only possible if I'm prefixing them with __. How is this problem solved in practice? I probably don't have a representative sample, but in the libraries that I have been using so far, there were a lot of undocumented (in the sense of: not being part of the public API) instance variables not prefixed with __. I have therefore started to first grep the source of all base classes whenever I introduce a new variable in my derived class. Is that really the way it's supposed to be? What if one of the base classes introduces a new variable at a later point? Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From martin at v.loewis.de Mon Jul 7 00:53:47 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 07 Jul 2008 06:53:47 +0200 Subject: how are strings immutable in python? In-Reply-To: <337db7c6-0fc9-465e-b780-322c3a5cf8da@y38g2000hsy.googlegroups.com> References: <337db7c6-0fc9-465e-b780-322c3a5cf8da@y38g2000hsy.googlegroups.com> Message-ID: <4871a15c$0$23475$9b622d9e@news.freenet.de> > so why would you ever want mutability? > > > seems very counterintuitive and unreliable. For lists, mutability is fairly natural. Suppose you have a function f that copies some items from one list to another. You write it as def f(src, dst): for x in src: if condition(x): dst.append(x) If dst was immutable, an .append method could not be defined (since it modifies the list itself), so you would have to write dst = dst + [x] However, that would only modify the local variable dst in the function f - the parameter of the caller of f would not get modified. The same holds for many other operations on lists. You can pass very complex data structures around (lists of lists of dictionaries etc), and have functions modify the lists, rather than creating new ones. For example, to change a two-dimensional matrix (which is a list of lists), you can write M[10][11] = 3.14 whereas with immutable lists, you would have to write M_10_new = M[10][:11] + [3.14] + [M10][12:] M = M[:10] + [M_10_new] + M[11:] HTH, Martin From mattheww at chiark.greenend.org.uk Thu Jul 31 12:51:31 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 31 Jul 2008 17:51:31 +0100 (BST) Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> Message-ID: >> Ctypes is a since python2.5 built-in module that allows to declare >> interfaces to C-libraries in pure python. You declare datatypes and >> function prototypes, load a DLL/SO and then happily work with it. No C, no >> compiler, no refcounts, no nothing. >> >> And you can pass python-functions as callbacks. squishywaffle at gmail.com wrote: > The first sentence (and some really crummy licensing restrictions > imposed by the library distributor) alone here excludes this as a > valid option for this particular case, I definitely need Python 2.4 > support. Perhaps all is not lost: ctypes works from Python 2.3 up. That first sentence is saying that since Python 2.5 it has been included in the standard Python distribution, but you can still download it separately. -M- From python at rcn.com Tue Jul 15 02:44:56 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 14 Jul 2008 23:44:56 -0700 (PDT) Subject: new itertools functions in Python 2.6 References: <4dd80ff2-5fda-405a-a637-08c985ff8add@e53g2000hsa.googlegroups.com> Message-ID: <498a38d4-10b5-4824-8401-5ebb510fcfa8@y38g2000hsy.googlegroups.com> On Jul 14, 1:26?pm, Mensanator wrote: > ## ?Combinations with replacement > ## ?----------------------------- > ## ?aaa aab aac aad aae abb abc abd abe acc acd ace > ## ?add ade aee bbb bbc bbd bbe bcc bcd bce bdd bde > ## ?bee ccc ccd cce cdd cde cee ddd dde dee eee > ## > ## ?actual words: 35 ? ?(m+n-1)!/(n!(m-1)!) words: 35 > > Although it works, it's somewhat slow as we have to iterate > over the entire Cartesian Product and the filter list(x)==sorted(x) > has got to be expensive (it's slower than the nested loop algorithm). > > Is there a better way to get Combinations With Replacement > using itertools? There may a technique to start with the combinations without replacement and then grow the result by repeating elements: result = set(combinations('abcde', 3)) # transform 'ab ac ad ae bc bd be cd ce de' into 'aab abb aac acc ...' for c in combinations('abcde', 2): # transform 'ab' --> 'aab abb' for i in range(2): result.add(c[:i] + c[i]*1 + c[i:]) for c in combinations('abcde', 1): for i in range(1): # 'a' --> 'aaa' result.add(c[:i] + c[i]*2 + c[i:]) If you generalize the above, it may solve the problem using itertools as a starting point. Alternatively, it's not too hard to transform the pure python version given in the docs to one that supports combinations with replacement: def combinations_with_replacement(iterable, r): pool = tuple(iterable) n = len(pool) indices = [0] * r yield tuple(pool[i] for i in indices) while 1: for i in reversed(range(r)): if indices[i] != n - 1: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] yield tuple(pool[i] for i in indices) Raymond From kirk at strauser.com Mon Jul 28 12:14:19 2008 From: kirk at strauser.com (Kirk Strauser) Date: Mon, 28 Jul 2008 11:14:19 -0500 Subject: Suggestions for creating a PDF table Message-ID: Short question: Is there a good library for generating HTML-style tables with the equivalent of colspans, automatically sized columns, etc. that can render directly to PDF? Longer question: I'm re-doing a big chunk of locally-written code. I have a report-generating function that takes a list of lists of lists as input and returns either a PDF, an HTML table, or an Excel spreadsheet as requested. For example, input might look like: makereport('html', headers=['Invoice number', 'Customer', 'Price'], data=[ [['123', 'John Doe', '$50.00'], ['Ordered on 2008-01-01 via the website']], [['124', 'Peter Bilt', '$25.99'], ['Mail via African swallow']] ]) This would result in HTML like:
Invoice number Customer Price
123 John Doe $50.00
Ordered on 2008-01-01 via the website
124 Peter Bilt $25.99
Mail via African swallow
Note particularly how the explanatory notes for each invoice are similar in appearance to the "primary" report lines they're associated with. Now, I have a similar transformation to PDF via pdflatex. This works fairly well but requires a bunch of temp files and subprocesses, and I've never been 100% happy with the LaTeX output (you have to calculate your own column widths, for instance). Since I plan to re-write this anyway, I'd like to find a more widely used library if one was available. ReportLab seemed *almost* perfect, except that it doesn't support colspans. As I hope I demonstrated in the example, most of our reports depend on that ability. So, again, any thoughts on a PDF generator that can generate tables with the same kind of flexibility as HTML? -- Kirk Strauser From tjreedy at udel.edu Wed Jul 30 11:14:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jul 2008 11:14:28 -0400 Subject: Is it allowed to use function results as default arguments ? In-Reply-To: References: Message-ID: fred.haab wrote: > Well, others have answered the question, but I thought I'd throw in > that it would be more pythonic to do something like: > > def Get_Relative_Path(target, base = None): > if base is None: > base = os.curdir > ... Since os.curdir is a constant, this is nonesensical. One only needs the dummy default when one wants an expression re-evaluated with each call. From clay at lakeserv.net Wed Jul 23 16:07:08 2008 From: clay at lakeserv.net (Clay Hobbs) Date: Wed, 23 Jul 2008 16:07:08 -0400 Subject: PyOpenGL Tutorial? Message-ID: <1216843629.18962.16.camel@generator> I need a tutorial for PyOpenGL (specifically, to be used with wxPython). I searched with Google and didn't find one. Does anybody know where one is? -- Ratfink From leonhard.vogt at gmx.ch Wed Jul 30 16:58:20 2008 From: leonhard.vogt at gmx.ch (Leonhard Vogt) Date: Wed, 30 Jul 2008 22:58:20 +0200 Subject: How can I check nbr of cores of computer? In-Reply-To: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> Message-ID: defn noob schrieb: > How can I check how many cores my computer has? > Is it possible to do this in a Python-app? processing (http://pyprocessing.berlios.de/) has an utility function processing.cpuCount(). Leo From fredrik at pythonware.com Thu Jul 24 03:53:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 09:53:31 +0200 Subject: parameterized classes In-Reply-To: References: Message-ID: John Tantalo wrote: > I really wish I could create a class whose instances were classes that > subclassed BaseRequestHandler. Is this possible, or is there a better > way than my approach here? Or am I crazy? no you so much as your code. unfortunately, it fails the "decipher in allocated time slot" test, though, so I hope someone else will have time to untangle it for you. > And I may be dense, so if there is an easier way to stream sockets as > line streams, please let me know. I honestly don't think it should be > this difficult to implement a socket handler this simple. there's a StreamRequestHandler class in SocketServer that buffered streams via the rfile and wfile attributes. From deets at nospam.web.de Tue Jul 22 09:32:10 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 15:32:10 +0200 Subject: tkinter for my python program !! References: Message-ID: <6em5snF7r22oU3@mid.uni-berlin.de> karthikbalaguru wrote: > Hi, > > One of my python program needs tkinter to be installed to run > successfully. > I am using Redhat 9.0 and hence tried installing by copying the > tkinter-2.2.2-36.i386.rpm > alone from the CD 3 to my pc. But, it is not getting installed and is > failing by throwing > the below errors. Should i need to configure / install any specific > files for resolving this issue ? > > [root at localhost karthik]# rpm -ivh tkinter-2.2.2-26.i386.rpm > warning: tkinter-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, > key ID db42a > 60e > error: Failed dependencies: > libtcl8.3.so is needed by tkinter-2.2.2-26.i386 > libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 > libtk8.3.so is needed by tkinter-2.2.2-26.i386 > > Any ideas ? Yes: you should consider reading error-messages. What does error: Failed dependencies: libtcl8.3.so is needed by tkinter-2.2.2-26.i386 libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 libtk8.3.so is needed by tkinter-2.2.2-26.i386 look like for you? Small hint: if you install something that depends on something else, you need to .... the missing dependency first. Fill in the dots... Diez From elessar at nienna.org Fri Jul 25 11:22:06 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 25 Jul 2008 09:22:06 -0600 Subject: Execution speed question In-Reply-To: <4889e5bc$1@news2-rz-ap.ethz.ch> References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> <4889e5bc$1@news2-rz-ap.ethz.ch> Message-ID: <4889EF9E.5050602@nienna.org> Suresh Pillai wrote: > That's a good comparison for the general question I posed. Thanks. > Although I do believe lists are less than ideal here and a different data > structure should be used. > > To be more specific to my case: > As mentioned in my original post, I also have the specific condition that > one does not know which nodes to turn ON until after all the > probabilities are calculated (lets say we take the top m for example). > In this case, the second and third will perform worse as the second one > will require a remove from the list after the fact and the third will > require another loop through the nodes to build the new list. > -- > http://mail.python.org/mailman/listinfo/python-list > It seems like the probability calculation applies to all three equally, and can therefore be ignored for the simulations. You said that your algorithm must be a two-stage process: (A) calculate the probabilities then (B) turn on some nodes. Iain's simulations assume (A) is already done. He just addressed the performance of (B). Part (A) is invariant for all his simulations, because your requirement forces it to be. As for different data structures, it largely depends on how you need to access the data. If you don't need to index the data, just loop through it, you might try a linked list. The performance hit in (2) is coming from the list del; using a linked list would make the removal constant rather than O(n), and may even execute faster than (3) as well. -Matt From wuwei23 at gmail.com Sun Jul 27 08:24:36 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 27 Jul 2008 05:24:36 -0700 (PDT) Subject: x*x if x>10 References: <59b5d431-8218-4a07-a9d7-5357f1c474f8@f36g2000hsa.googlegroups.com> Message-ID: On Jul 27, 10:13?pm, ssecorp wrote: > I have seen somewhere that you can write something like: > > x*x if x>10 > > but exactly that doesn't work and I can't get any variation to work. It's called a ternary operator. The format is:
american, /browse/blue blue , /browse/brick brick , brie, cheddar, cheshire, /browse/churn churn , /browse/cottage cottage , /browse/cream cream , dunlop, and it goes on . I know I can do like a.contents, but it only gives me the first one, in this case being "blue". I want the contents of each of those and the regular contents of the . Can anyone help? -- View this message in context: http://www.nabble.com/Need-help-getting-BeautifulSoup-contents-tp18501881p18501881.html Sent from the Python - python-list mailing list archive at Nabble.com. From bierbaum at vierfalt.com Thu Jul 10 17:12:36 2008 From: bierbaum at vierfalt.com (Simon Bierbaum) Date: Thu, 10 Jul 2008 23:12:36 +0200 Subject: handling unexpected exceptions in pdb In-Reply-To: References: Message-ID: Am 10.07.2008 um 20:52 schrieb R. Bernstein: > Simon Bierbaum writes: > >> Hi all, >> >> I'm in an interactive session in pdb, debugging my code using >> pdb.runcall. Somewhere, an exception is raised and lands uncaught on >> stdout. Is there any way of picking up this exception and at least >> read the full message, or even accessing its stack trace to determine >> where exactly within the one line I just executed it was raised? This >> is where I'm stuck: >> >>> /usr/local/apache2/bin/Model/Database.py(287)disconnect() >> (Pdb) n >> FlushError: FlushErr...perly.",) >>> /usr/local/apache2/bin/Model/Database.py(287)disconnect() >> (Pdb) import sys >> (Pdb) sys.last_traceback >> *** AttributeError: 'module' object has no attribute 'last_traceback' >> >> Thanks, Simon > > I think basically you want runcall to be wrapped in a try block. So > in pdb.py > instead of: > > def runcall(*args, **kwds): > return Pdb().runcall(*args, **kwds) > > > Change with: > > def runcall(*args, **kwds): > p=Pdb() > try: > return p.runcall(*args, **kwds) > except: > traceback.print_exc() > print "Uncaught exception. Entering post mortem debugging" > t = sys.exc_info()[2] > p.interaction(t.tb_frame,t) > print "Post mortem debugger finished." > return None > > Code like this appears near the bottom of the pdb.py file. If that > works, you may want to file a bug Python report to change pdb. Also > note that one may want to do the same thing on run() and runeval() > > But also if this does what you want, please file a feature request > to pydb: > http://sourceforge.net/tracker/?func=add&group_id=61395&atid=497162 > > and I'll probably make it happen in the next release. > > This is the first time I've heard of anyone using runcall. My app is called from mod_python with the PythonEnablePdb option set to On, which makes mod_python call my handler function not directly, but wrapped into a pdb.runcall(). I figure I might not be the first one to use runcall under these circumstances ;-) I'll definitely give your hack a try, thank you for your help! Cheers, Simon From paul at boddie.org.uk Wed Jul 30 13:54:17 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 30 Jul 2008 10:54:17 -0700 (PDT) Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: <2a703a46-75bc-4228-95d1-05a4e6030b40@f63g2000hsf.googlegroups.com> <26c2fe8e-d464-44f0-8e57-3b8e82248691@x35g2000hsb.googlegroups.com> Message-ID: On 30 Jul, 19:23, Peter Otten <__pete... at web.de> wrote: > > I'm on Kubuntu 7.10 and see the same error as Simon. The problem is in the > minidom.CharacterData class which has the following method > > ? ? def __repr__(self): > ? ? ? ? data = self.data > ? ? ? ? if len(data) > 10: > ? ? ? ? ? ? dotdotdot = "..." > ? ? ? ? else: > ? ? ? ? ? ? dotdotdot = "" > ? ? ? ? return "" % ( > ? ? ? ? ? ? self.__class__.__name__, data[0:10], dotdotdot) > > The data attribute is a unicode instance... Who wants to be first to submit a patch? ;-) Paul From Scott.Daniels at Acm.Org Wed Jul 23 00:06:47 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 22 Jul 2008 21:06:47 -0700 Subject: fromfile error on windows, not mac In-Reply-To: <185cc290-18a5-4572-9fda-fa0bb785c831@z72g2000hsb.googlegroups.com> References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> <9650a33b-40b5-46a7-a05e-5b059117891f@b1g2000hsg.googlegroups.com> <185cc290-18a5-4572-9fda-fa0bb785c831@z72g2000hsb.googlegroups.com> Message-ID: <56Sdncz234dVNhvVnZ2dnUVZ_oLinZ2d@pdx.net> jadamwil wrote: > On Jul 22, 2:05 am, Uwe Schmitt > wrote: >> jadamwil schrieb: >> >> >> >>> Hello, >>> I am using the numpy fromfile function to read binary data from a file >>> on disk. The problem is that the program runs fine on a Mac, but gives >>> an error or warning on windows when trying to read the data. I use it >>> like this: >>> Signal = zeros((N, 16), dtype=float32) >>> for sample in range(0, N): >>> # this function gets the next position in the file to seek to >>> s = getFilePos(sample) >>> # go to the correct location in the file; this IS checked to make >>> sure it is within the file >>> mFile.seek(s) >>> # read the 16 float32 values from the file >>> D = fromfile(mFile, dtype=numpy.float32, 16) >>> # save D in Signal >>> Signal[sample, :] = D >>> This will fail when sample is ~4. If I change the range to (5,N), >>> skipping the "bad" file location, it will run fine for a few samples, >>> and then give another error. The message it gives is: >>> "16 items requested but only 7 read" >>> So D is a 7x1 vector, and the program dies when it tries to assign D >>> to the slice of Signal ("ValueError: shape mismatch: objects cannot be >>> broadcast to a single shape"). >>> On windows, the Python version is 2.5.2, and the most recent numpy and >>> scipy are being used as well. I tried using Enthought, but it gave >>> this error as well, in addition to a c runtime error whenever I >>> imported scipy (which is another post topic...). >>> Any ideas on what might be causing this? Is there a way to debug the >>> fromfile function? And, remember, this works perfectly on a Mac. Would >>> compiling everything (python, scipy, numpy) potentially solve this? >> Did you open the file in binary mode ? >> >> Greetings, Uwe > > Yes I did. Would that make a difference between a mac and windows? > Thanks In a word, yes. the values for bytes that have issues are 10 and 13. --Scott David Daniels Scott.Daniels at Acm.Org From boblatest at googlemail.com Thu Jul 24 06:10:49 2008 From: boblatest at googlemail.com (boblatest at googlemail.com) Date: Thu, 24 Jul 2008 03:10:49 -0700 (PDT) Subject: Confounded by Python objects References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> Message-ID: On Jul 24, 11:59 am, Fredrik Lundh wrote: > tip: if you're not 100% sure why you would want to put an attribute > on the class level, don't do it. The reason I did it was sort of C++ish (that's where I come from): I somehow wanted a list of attributes on the class level. More for readibility than anything elase, really. > hope this helps! Yup, did the trick. Thanks! robert From miki.tebeka at gmail.com Mon Jul 14 14:14:46 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 14 Jul 2008 11:14:46 -0700 (PDT) Subject: trying to use sax for a very basic first xml parser References: <6ff86003-a3e8-4c5b-9276-1cd3c7f0ffa7@56g2000hsm.googlegroups.com> Message-ID: <3a7148a9-b95d-4e95-b3b7-492e0d016ab8@f36g2000hsa.googlegroups.com> Hello, > but when I copy the script into blender and run it I get: > > [code]Compiled with Python version 2.5. > Checking for installed Python... got it! > Traceback (most recent call last): > ? File "Text", line 27, in > ? File "H:\Python25\lib\xml\sax\__init__.py", line 93, in make_parser > ? ? raise SAXReaderNotAvailable("No parsers found", None) > xml.sax._exceptions.SAXReaderNotAvailable: No parsers found[/code] Python is using an external library for SAX (expat IIRC). I *guess* the Python that comes with Blender don't have this library. > Its probably a stupid question but thanks anyway! He who asks is a fool for five minutes, but he who does not ask remains a fool forever. - Chinese Proverb HTH, -- Miki http://pythonwise.blogspot.com From koen at asemic.org Tue Jul 1 07:10:05 2008 From: koen at asemic.org (Koen Vossen) Date: 01 Jul 2008 11:10:05 GMT Subject: Disabling the magic "last expression" _ variable Message-ID: <486a108d$0$14358$e4fe514c@news.xs4all.nl> A project I'm currently working on uses Turbogears as a framework. I'd like to interact with it using the tg-admin shell. We also use gettext's _() function for internationalization. Now, this function is overwritten in interactive mode, which causes annoying exceptions. Is it possible to disable this behavior? From aquil.abdullah at gmail.com Mon Jul 14 17:01:04 2008 From: aquil.abdullah at gmail.com (aha) Date: Mon, 14 Jul 2008 14:01:04 -0700 (PDT) Subject: Using Python To Launch Python Message-ID: Hello All, I have a situation where I can count on a Python installation being available on a system, but I can't count on it being a version of Python needed by my application. Since my application has it's own version of Python installed with it how should I use the system Python to launch the version of Python that launches my Application. Yes, this is a convoluted process, but not all Pythons are built the same :) Right now I am leaning towards using exec to start a new process, but I thought I would check to see if anyone else has had the need to perform a task similar to this one. AHA From __peter__ at web.de Fri Jul 11 04:08:58 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jul 2008 10:08:58 +0200 Subject: problem with exec and locals() References: <95f07476-e3c8-45e4-82b3-0e48c9188f8e@79g2000hsk.googlegroups.com> <2fc55416-76c7-48c8-8f49-64c10c5daeda@w7g2000hsa.googlegroups.com> Message-ID: Uwe Schmitt wrote: >> Apparently, exec in locals() knows nothing about slots (because locals() >> is the only dictionary in the universe where slots would be involved ? -- >> perhaps not, but close). >> >> Mel. > > Thanks for your answer. I wonder if this is a bug, or did I miss > something in the docs ??? Hm, the documentation has an explicit warning: http://docs.python.org/lib/built-in-funcs.html#l2h-47 """ locals( ) Update and return a dictionary representing the current local symbol table. Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. """ By the way, the local namespace is affected if you don't provide it explicitly: >>> def f(): ... exec "a=42" ... print a ... a = "whatever" ... >>> f() 42 Peter From ppearson at nowhere.invalid Sat Jul 5 00:08:59 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 5 Jul 2008 04:08:59 GMT Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: <6d8aeqF1cgfsU1@mid.individual.net> On Fri, 4 Jul 2008 20:34:03 -0700 (PDT), Carl Banks wrote: > On Jul 4, 4:43 pm, "Filipe Fernandes" wrote: >> On Fri, Jul 4, 2008 at 8:36 AM, Peter Otten <__pete... at web.de> wrote: >> > Henning_Thornblad wrote: >> >> >> This script takes about 5 min to run on my computer: >> >> #!/usr/bin/env python >> >> import re >> >> >> row="" >> >> for a in range(156000): >> >> row+="a" >> >> print re.search('[^ "=]*/',row) [snip] >> >> Is this a bug in python? > > This behavior is showing that you're getting n-squared performance; > the regexp seems to be checking 156000*(156000-1)/2 substrings for a > match. I did this: $ python -m timeit -s "import re" "re.search( '[^13]*x', 900*'a' )" 100 loops, best of 3: 16.7 msec per loop for values of 900 ranging from 300 to 1000, and the time taken per loop was indeed quadratic. -- To email me, substitute nowhere->spamcop, invalid->net. From paddy3118 at googlemail.com Sat Jul 5 03:31:24 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 5 Jul 2008 00:31:24 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: <8d2a078c-ccb4-4e09-a802-b35886207e50@56g2000hsm.googlegroups.com> On Jul 5, 7:01?am, Peter Otten <__pete... at web.de> wrote: > Paddy wrote: > > It is not a smarter algorithm that is used in grep. Python RE's have > > more capabilities than grep RE's which need a slower, more complex > > algorithm. > > So you're saying the Python algo is alternatively gifted... > > Peter The following isn't the article I read on regexp types and their speed differences but it does give info on regexp engine types: http://books.google.co.uk/books?id=GX3w_18-JegC&pg=PA145&lpg=PA145&dq=%2Bregex+%2Bspeed+%2Bgrep+%2Btcl+&source=web&ots=PHljNqeuJZ&sig=CyBCOZYsyZaJTMfj2Br53if46Bc&hl=en&sa=X&oi=book_result&resnum=3&ct=result#PPA145,M1 - Paddy. From ldo at geek-central.gen.new_zealand Mon Jul 28 00:00:39 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 28 Jul 2008 16:00:39 +1200 Subject: Python program as daemon? References: <8bb6bd1a-cd85-4b7a-8fc9-844f3794bca0@c58g2000hsc.googlegroups.com> <13866da4-01ed-4330-8297-8bdecce1393a@x35g2000hsb.googlegroups.com> Message-ID: In message <13866da4-01ed-4330-8297-8bdecce1393a at x35g2000hsb.googlegroups.com>, sturlamolden wrote: > Basically it forks twice ... What's the advantage of forking twice over forking once and calling setsid? From vinay_sajip at yahoo.co.uk Mon Jul 14 09:25:19 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Mon, 14 Jul 2008 06:25:19 -0700 (PDT) Subject: How to package a logging.config file? References: Message-ID: <0a5713d6-8337-44a3-8347-012814345dd8@79g2000hsk.googlegroups.com> On Jul 14, 1:21 am, Matthew Wilson wrote: > I'm working on a package that uses the standard libraryloggingmodule > along with a .cfg file. > > In my code, I uselogging.config.fileConfig('/home/matt/mypackage/matt.cfg') to load in > theloggingconfig file. > > However, it seems really obvious to me that this won't work when I share > this package with others. > > I can't figure out what path to use when I load my .cfg file. > > Any ideas? > > Matt Is your package a library or an application? If it's a library, you should avoid configuring logging using a config file - this is because logging configuration is process-wide, and if multiple libraries use fileConfig to configure their logging, you may get unexpected results. If it's an application, then Larry's advice is good. Regards, Vinay Sajip From hat at se-162.se.wtb.tue.nl Tue Jul 1 03:34:13 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 01 Jul 2008 09:34:13 +0200 Subject: How make regex that means "contains regex#1 but NOT regex#2" ?? References: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> Message-ID: On 2008-07-01, seberino at spawar.navy.mil wrote: > I'm looking over the docs for the re module and can't find how to > "NOT" an entire regex. (?! R) > How make regex that means "contains regex#1 but NOT regex#2" ? (\1|(?!\2)) should do what you want. Albert From jeffober at gmail.com Tue Jul 22 08:42:32 2008 From: jeffober at gmail.com (Jeff) Date: Tue, 22 Jul 2008 05:42:32 -0700 (PDT) Subject: simple question about dictionaries References: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> <8aedc744-f432-4a4a-a6e4-2bb714caf720@x35g2000hsb.googlegroups.com> Message-ID: <051bfa54-fd66-4a01-978d-3a05e4527c38@34g2000hsf.googlegroups.com> On Jul 21, 8:14?am, Fredrik Lundh wrote: > Jeff wrote: > > ? throw KeyError('%s not found' % str(val)) > > "throw"? ?and shouldn't that be a ValueError? ;-) > > Whoops. Been working in too many different languages at the same time :). From gherron at islandtraining.com Sun Jul 13 11:23:28 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 13 Jul 2008 08:23:28 -0700 Subject: Someone enlightened me In-Reply-To: <4879645F.3070504@internetnowasp.net> References: <4879645F.3070504@internetnowasp.net> Message-ID: <487A1DF0.70503@islandtraining.com> Marcus Low wrote: > Opps here is the mail again, incase my formatting is lost, can someone > explain to me why this code behaves differently when "lister" and > "self.lister" is swap remarked. > > > class abc : > # remark this later and unremark "self.lister" > lister = [] > def __init__ (self, val): > #self.lister = [] > self.lister.append(val) > globallist = [] > > def test () : > > global l > for x in range(10) : > o = abc(x) globallist.append(o) o > = "" > for i in globallist : > print i.lister > test() > > -- > http://mail.python.org/mailman/listinfo/python-list It's a Python scoping rule: If a variable is assigned to anywhere within a function, it is assumed to be local *everywhere* within that function. See the faq for more: http://www.python.org/doc/faq/programming/#what-are-the-rules-for-local-and-global-variables-in-python Gary Herron From Donald at dontdoithere.com Sun Jul 13 11:17:39 2008 From: Donald at dontdoithere.com (donald) Date: Sun, 13 Jul 2008 08:17:39 -0700 Subject: spam <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> In-Reply-To: <487a0d4d$0$90272$14726298@news.sunsite.dk> References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> <487a0d4d$0$90272$14726298@news.sunsite.dk> Message-ID: Arne Vajh?j wrote: >> >> Google does not accept spam complaints. Go ahead, try it. That's why >> they've been the #1 Usenet spamming tool for years now. What you're >> seeing is the spam slowly expanding into the software development >> groups. uk.railway is probably a random group added to confuse spam >> filters. Some groups, like rec.photo.digital, have been getting >> hundreds of Google spams a day for about a year. >> >> Ask your news service for a Google UDP (Usenet Death Penalty) or >> configure your reader to drop everything with "googlegroups.com" in >> the Message-ID. > > Some real users do use GG. This is true, however there are acceptable losses. donald > > Arne From ethan at stoneleaf.us Tue Jul 15 14:27:11 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 15 Jul 2008 10:27:11 -0800 Subject: MySQL Insert In-Reply-To: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> References: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> Message-ID: <487CEBFF.2070003@stoneleaf.us> maestroQC wrote: > Hi, > > Its one of those days. I cannot solve this. Any help would be greatly > appreciated! > When I execute this: > > class Db(object): > def insertAccount(self, date, accountNumber, description, > openingBalance): > dec = decimal.Decimal(openingBalance) > db = MySQLdb.connect(host="localhost", user="dumb", > passwd="dumber", db="rdc") > cursor = db.cursor() > cursor.execute("INSERT INTO es_accounts (dateCreated, > accountNumber, description, openingBalance) VALUES (%s, %s, %s, %d)", > (date, accountNumber, description, dec)) > > I get this error: > Traceback (most recent call last): > File "main.py", line 59, in > main() > File "main.py", line 40, in main > dbObj.insertAccount(dateTo, item[0], item[1], item[8]) > File "C:\projects\workspace\INYR_ES_0.1\src\db.py", line 19, in > insertAccount > cursor.execute("INSERT INTO es_accounts (dateCreated, > accountNumber, description, openingBalance) VALUES (%s, %s, %s > , %d)", (date, accountNumber, description, dec)) > File "c:\python25\lib\site-packages\MySQLdb\cursors.py", line 151, > in execute > query = query % db.literal(args) > TypeError: int argument required > > My table is defined as: > CREATE TABLE es_accounts ( > id int(6) not null auto_increment, > dateCreated date DEFAULT '0000-00-00', > accountNumber int(6) not null, > description varchar(255) not null, > openingBalance decimal(15,8) NOT NULL DEFAULT 0.00000000, > primary key (id) > ); > > TIA How embarassing. My previous post is not correct in it's explanation, unless there is some way to tell Decimal not to allow int coercion... --> from decimal import Decimal --> n10_25 = Decimal('10.25') --> n10_25 Decimal("10.25") --> "%d" % n10_25 '10' About the only thing it had even partially right is not using %d, as it will truncate the fractional part of your opening balance. As far as why you are getting that error, I now have no idea, and I apologize for any confusion created by my error. ~Ethan From russblau at hotmail.com Tue Jul 15 15:50:09 2008 From: russblau at hotmail.com (Russell Blau) Date: Tue, 15 Jul 2008 15:50:09 -0400 Subject: 'if name is not None:' v. 'if name:' References: Message-ID: "Victor Noagbodji" wrote in message news:fdd6be670807151244v6d63e5baj7e316a4ce861ac80 at mail.gmail.com... > > Well that's exactly why I'm asking. Since None returns False in if > statements. Why do people use if name is not None: instead of simply > writing if not name? > Because '' is a string value that is treated as false. If name=='', then "if name:" will be false, but "if name is not None:" will be true. Which one to use depends entirely on how you want to treat empty strings. For all other (string) values of name, the two statements will give the same results. Russ From steve at REMOVE-THIS-cybersource.com.au Sat Jul 26 08:24:28 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Jul 2008 12:24:28 GMT Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> Message-ID: <009b130f$0$20313$c3e8da3@news.astraweb.com> On Sat, 26 Jul 2008 11:08:12 +0200, Nikolaus Rath wrote: > Terry Reedy writes: ... >> Because you must prefix self attributes with 'self.'. If you do not use >> any attributes of the instance of the class you are making the function >> an instance method of, then it is not really an instance method and >> need not and I would say should not be masqueraded as one. If the >> function is a static method, then it should be labeled as one and no >> 'self' is not needed and auto insertion would be a mistake. In brief, I >> assume the OP wants 'self' inserted in the body because inserting it >> only in the parameter list and never using it in the body is either >> silly or wrong. > > > I think you misunderstood him. What he wants is to write > > > class foo: > def bar(arg): > self.whatever = arg + 1 > > > instead of > > class foo: > def bar(self, arg) > self.whatever = arg + 1 > > > so 'self' should *automatically* only be inserted in the function > declaration, and *manually* be typed for attributes. That idea might have worked many years ago, but not now. The problem is, what happens here? class Foo(object): def foo(self, arg): self.whatever = arg + 1 @classmethod def cfoo(cls, arg): cls.whatever = arg - 1 @staticmethod def sfoo(arg): print arg How does the compiler know to insert "self" into the argument list for foo, "cls" into that of cfoo, but do nothing for sfoo? Decorators can transform methods in arbitrarily complex ways using the Descriptor protocol. -- Steven From xushunttr2 at yahoo.cn Tue Jul 1 06:52:32 2008 From: xushunttr2 at yahoo.cn (jinole) Date: Tue, 1 Jul 2008 03:52:32 -0700 (PDT) Subject: Create a sex site Message-ID: <6b749394-46a9-4966-8000-bb6b6d33a68a@l28g2000prd.googlegroups.com> Asian porn sites! Not the best, only better. To join our team, we do together.URL: http://www.loioi.com From dullrich at sprynet.com Mon Jul 7 16:59:10 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 07 Jul 2008 15:59:10 -0500 Subject: caseless dict - questions References: <77798300-820f-4175-a9cb-aef639d42a32@m45g2000hsb.googlegroups.com> Message-ID: In article <77798300-820f-4175-a9cb-aef639d42a32 at m45g2000hsb.googlegroups.com>, Phoe6 wrote: > I have a requirement for using caseless dict. I searched the web for > many different implementations and found one snippet which was > implemented in minimal and useful way. > > ############# > import UserDict > > class CaseInsensitiveDict(dict, UserDict.DictMixin): > def __init__(self, *args, **kwargs): > self.orig = {} > super(CaseInsensitiveDict, self).__init__(*args, **kwargs) > def items(self): > keys = dict.keys(self) > values = dict.values(self) This items() can't be what anyone would want items to be for a "caseless dict". > return [(self.orig[k],v) for k in keys for v in values] > def __setitem__(self, k, v): > hash_val = hash(k.lower()) > self.orig[hash_val] = k > dict.__setitem__(self, hash_val, v) > def __getitem__(self, k): > return dict.__getitem__(self, hash(k.lower())) > > > obj = CaseInsensitiveDict() > obj['Name'] = 'senthil' > print obj > print obj.items() > > obj1 = {} > obj1['Name'] = 'senthil' > print obj1 > print obj1.items() > ########### > [ors at goofy python]$ python cid1.py > {15034981: 'senthil'} > [('Name', 'senthil')] > {'Name': 'senthil'} > [('Name', 'senthil')] > > --- > The difference between the Caselessdict and {} is that when called as > the object, the Caselessdict() is giving me the internal > representation. > obj = CaseInsensitiveDict() > obj['Name'] = 'senthil' > print obj > gives: {15034981: 'senthil'} > > obj1 = {} > obj1['Name'] = 'senthil' > print obj1 > Correctly gives {'Name': 'senthil'} > > What changes should I make to CaseInsensitiveDict ( written above), so > that its instance gives the actual dictionary instead of its internal > representation. > Constructing a dictionary and returning from __init__ method did not > work. It's not entirely clear to me what you want: Since this is supposed to be a "caseless" dict, I imagine that if you say d['Name'] = 'first value' d['name'] = 'new value' then d['Name'] should now be 'new value'. Fine. Now in that case exactly what do you want to see when you print d? Do you want to see {'name':'new value'} or {'name':'new value', 'Name': 'newvalue'}? > TIA, > Senthil -- David C. Ullrich From mail at timgolden.me.uk Thu Jul 10 04:17:51 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 10 Jul 2008 09:17:51 +0100 Subject: Allow tab completion when inputing filepath? In-Reply-To: <08e60124-51c1-40c1-bffe-52c22ff310db@l64g2000hse.googlegroups.com> References: <08e60124-51c1-40c1-bffe-52c22ff310db@l64g2000hse.googlegroups.com> Message-ID: <4875C5AF.60702@timgolden.me.uk> Keith Hughitt wrote: > On Jul 9, 10:18 am, Tim Golden wrote: >> Keith Hughitt wrote: >>> I've been looking around on the web for a way to do this, but so far >>> have not come across anything for this particular application. I have >>> found some ways to enable tab completion for program-related commands, >>> but not for system filepaths. This would be nice to have when >>> prompting the user to enter a file/directory location. >> What platform are you on? And what kind of display? >> (Console / GUI / wxPython / Qt / Web...) >> >> TJG > > Hi TJG, > > Currently Unix/Console. Although I don't have any plans at the moment > to add a GUI, it would be great if a cross-platform solution existed. Ah. Not my area then, I'm afraid :( I mostly do Windows stuff. However, I don't remember ever coming across a standard way of doing this, although it shouldn't be too hard to roll your own. TJG From enleverlesX.XmcX at XmclaveauX.com Sun Jul 6 19:00:53 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Mon, 7 Jul 2008 01:00:53 +0200 Subject: pythoncom InternetExplorer.Application don't work in vista || firefox pythoncom ? In-Reply-To: <29c70427-07f2-43ae-b742-86af4431edd8@34g2000hsh.googlegroups.com> References: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> <486fe5cc$0$926$ba4acef3@news.orange.fr> <29c70427-07f2-43ae-b742-86af4431edd8@34g2000hsh.googlegroups.com> Message-ID: <48714f2f$0$897$ba4acef3@news.orange.fr> Hmmmm... I have a similary problem, in another circumstances. It's often a problem of configuration of IE (for news customers). But, it is not easy, because IE has many parameters. Good luck! Michel Claveau From kyosohma at gmail.com Sat Jul 26 18:13:37 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sat, 26 Jul 2008 15:13:37 -0700 (PDT) Subject: wx.Timer not working References: <7a2a1c54-6d74-475c-9566-4d94cb5b5962@a3g2000prm.googlegroups.com> Message-ID: On Jul 26, 2:33?pm, 5lvqbw... at sneakemail.com wrote: > Windows XP SP3 > Python 2.5 > wx.version() = '2.8.1.1 (msw-unicode)' > ------ > I have written the following *simplest* implementation of wx.timer I > can think of. ?No workie. ? I want an exception, a print statement, or > something. > > The wxpython demos all work, but for some reason this isn't. ?The > demos are simple and straghtforward, so I think I understand how it > should work. ?Clues please? ?I've tried variations of ID's, SetOwners, > using and redefining Notify(), Bind, Connect, etc. ?In the cases where > the interpreter doesn't complain about passed argument types, the > callback function is never called. > > import wx > > class MyFrame(wx.Frame): > ? ? ? ? def __init__(self, parent, id, title): > ? ? ? ? ? ? ? ? wx.Frame.__init__(self, parent, id, ? ? title, pos=(100, 100)) > > ? ? ? ? ? ? ? ? timer = wx.Timer(self, -1) > ? ? ? ? ? ? ? ? self.Bind(wx.EVT_TIMER, self.OnTick, timer) > ? ? ? ? ? ? ? ? timer.Start(100) > > ? ? ? ? def OnTick(self, event): > ? ? ? ? ? ? ? ? print 'Hi. Bye.' > ? ? ? ? ? ? ? ? 1/0 #<-- should crash as evidence callback is being called > > class MyApp(wx.App): > ? ? ? ? def OnInit(self): > ? ? ? ? ? ? ? ? frame1 = MyFrame(None, wx.ID_ANY, "This is a test") > ? ? ? ? ? ? ? ? frame1.Show(True) > ? ? ? ? ? ? ? ? return True > > app ? ? = MyApp(0) > app.MainLoop() > > Thanks for any advice!! > > Michael I'm not seeing anything either. Please post this to the wxPython user's group for additional help: http://www.wxpython.org/maillist.php Mike From grante at visi.com Wed Jul 23 09:52:05 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 23 Jul 2008 08:52:05 -0500 Subject: Python Written in C? References: Message-ID: On 2008-07-23, mk wrote: >> Actually, all of the compilers I'm familiar with (gcc and a >> handful of cross compilers for various microprocessors) >> translate from high-level languages (e.g. C, C++) into >> assembly, which is then assembled into relocatable object >> files, which are then linked/loaded to produce machine >> language. > > Doesn't g++ translate C++ into C and then compile C? No. > Last I heard, most C++ compilers were doing that. A decade or two ago there were some C++ front-ends that did that, but I don't think it's common in modern C++ compilers. -- Grant Edwards grante Yow! Oh, I get it!! at "The BEACH goes on", huh, visi.com SONNY?? From timr at probo.com Sun Jul 20 23:44:03 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 21 Jul 2008 03:44:03 GMT Subject: % sign in python? References: <48d08494p4jnhkrhgidmgppg1aostmurvn@4ax.com> Message-ID: <7c188491si65q4gsnj63vbf87n0h1sb8j3@4ax.com> Terry Reedy wrote: > >Tim Roberts wrote: >> Steven Howe wrote: >> >>> Terry Reedy wrote: >>>> korean_dave wrote: >>>>> What does this operator do? Specifically in this context >>>>> >>>>> test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) >>> >>> I thought, in this contexted, it was mapping operator. > >You miss clipped. I never wrote that. Please be careful, especially >about attributing mis-information. If you count the > signs, you'll see that I correctly attributed the question to korean_dave, and the answer to Steve Howe. Steve's reply contained your name, but there was no text from you in my post. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From larry.bates at websafe.com` Mon Jul 28 11:45:13 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 28 Jul 2008 10:45:13 -0500 Subject: We programming In-Reply-To: References: Message-ID: <6uadnZFLhJMQdBDVnZ2dnUVZ_rrinZ2d@comcast.com> srinivasan srinivas wrote: > Hi, > Could someone suggest me better python modules for developing web programming related projects like web-pages download and uopload?? > Thanks, > Srini > > > Explore your hobbies and interests. Go to http://in.promos.yahoo.com/groups/ urllib, urllib2, httplib All depends on what you want to do with them. -Larry From gagsl-py2 at yahoo.com.ar Wed Jul 30 00:38:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 01:38:12 -0300 Subject: RTF Parsing References: <4dc0cfea0807290608v3e89a5c6m7dc0ca70fd064a00@mail.gmail.com> Message-ID: En Tue, 29 Jul 2008 10:08:21 -0300, Victor Subervi escribi?: > Hi; > I have this code: > def a(): > chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', > '\\yz'] > rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like the > Beast? Who can wage war against him?\par' The \ is an escape character inside string literals. '\n' contains a *single* character and it's the same as chr(10). '\f0' is two characters long, not three. You have two alternatives: a) double each \ (because \\ is interpreted as a single backslash): rtf_markup = 'viewkind4\\uc1\\pard\\nowidctlpar\\qc...' b) use raw strings - that is, prefix each string literal with a small r: rtf_markup = r'viewkind4\uc1\pard\nowidctlpar...' See the tutorial http://docs.python.org/tut/node5.html#SECTION005120000000000000000 and the gory details at http://docs.python.org/ref/strings.html -- Gabriel Genellina From bearophileHUGS at lycos.com Mon Jul 28 06:28:05 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 28 Jul 2008 03:28:05 -0700 (PDT) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <488d7d43$1@news2-rz-ap.ethz.ch> Message-ID: <41b03ed3-c515-48c7-9546-84a8bf9178bd@l42g2000hsc.googlegroups.com> Suresh Pillai: > Or 4, since the order of my nodes doesn't matter: swap the node to be > deleted with the last node in the list and then remove the last node of > the list. This is the fastest to date, if using native structures, for > low number nodes being deleted per cycle (def if only deleting one). Using Psyco this suggestion may lead to code as fast as it gets in Python :-) Bye, bearophile From asmodai at in-nomine.org Wed Jul 9 08:18:48 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 9 Jul 2008 14:18:48 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <4874A9C9.7020804@FreeBSD.org> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <750f823a-f9de-4f81-9eb3-7c7b39237c90@y38g2000hsy.googlegroups.com> <4874A9C9.7020804@FreeBSD.org> Message-ID: <20080709121848.GO26006@nexus.in-nomine.org> -On [20080709 14:08], Kris Kennaway (kris at FreeBSD.org) wrote: >It's compiler/build output. Sounds like the FreeBSD ports build cluster. :) Kris, have you tried a PGO build of Python with your specific usage? I cannot guarantee it will significantly speed things up though. Also, a while ago I did tests with various GCC compilers and their effect on Python running time as well as Intel's cc. Intel won on (nearly) all accounts, meaning it was faster overall. >From the top of my mind: GCC 4.1.x was faster than GCC 4.2.x. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Beware of the fury of the patient man... From timr at probo.com Fri Jul 4 01:31:56 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 04 Jul 2008 05:31:56 GMT Subject: Required items in a form References: <45yak.331$Ae3.313@trnddc05> Message-ID: "Brandon" wrote: > >What I'm trying to do is essentially force a user to fill in required items >in a form, which will be saved to a database. How can I get it so that once >the user clicks "OK" on the dialog box, it transfers control back to the >form, and not save the empty fields into the database? What do you mean by "transfers control back to the form"? A form doesn't have any code, and so can't "control" anything. Now, it is certainly possible to define an onSubmit handler in the
header, then write a Javascript function that validates the input. If the function returns false, the submit won't happen. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mail at timgolden.me.uk Wed Jul 16 10:01:58 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 15:01:58 +0100 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: <487DFF56.7010405@timgolden.me.uk> Fredrik Lundh wrote: > Ken Hartling wrote: > > > Thanks .. but I want to find out if the system is "running on 64bit" > > even when the interpreter is a 32-bit build executable ("what python > > was built on"). platform.architecture() and platform() in general > > seems to only be looking at the build executable > > You can pass in an arbitrary binary to architecture(), so I guess you > could use this on some suitable thing under "/bin" on a Unix box. This > doesn't work on Windows, though. > > In this message, > > http://mail.python.org/pipermail/python-list/2005-June/326158.html > > Thomas Heller suggests using ctypes to call the Windows API directly; so > something like this could work: > > >>> import ctypes, sys > >>> i = ctypes.c_int() > >>> kernel32 = ctypes.windll.kernel32 > >>> process = kernel32.GetCurrentProcess() > >>> kernel32.IsWow64Process(process, ctypes.byref(i)) > 1 > >>> is64bit = (i.value != 0) > >>> is64bit > False This is included in the latest pywin32-211 as well: import win32process print win32process.IsWow64Process () TJG From bearophileHUGS at lycos.com Fri Jul 11 06:36:45 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 11 Jul 2008 03:36:45 -0700 (PDT) Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> Message-ID: <3ebed664-a6ba-4e30-acc5-f7d5edb25e32@56g2000hsm.googlegroups.com> James Fassett: > # the first Pythonic attempt using comprehensions > result_list = [x[0] for x in tuple_list] > > # the final functional way > [result_list, _] = zip(*tuple_list) > > I really like how Python allows me to do what I feel is the most > natural solution (for a seasoned procedural programmer) while allowing > a satisfying path towards a more functional approach. The list comprehension is quite more readable to me, so I suggest you to use it. It's probably the default way to do it in Python. If you want functional code this is another way (I have not tested the relative performance but it may be quick): >>> tuple_list = ( ... ('John', 'Doe'), ... ('Mark', 'Mason'), ... ('Jeff', 'Stevens'), ... ('Bat', 'Man') ... ) >>> from operator import itemgetter >>> map(itemgetter(0), tuple_list) ['John', 'Mark', 'Jeff', 'Bat'] Bye, bearophile From google at mrabarnett.plus.com Thu Jul 24 21:40:41 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 24 Jul 2008 18:40:41 -0700 (PDT) Subject: Is there a metacharacter to match transitions between any two of a set of non intersected char classes? References: Message-ID: <2ada0734-9193-45ef-ad08-1ac9fdcd8fcd@a21g2000prf.googlegroups.com> On Jul 24, 6:48?pm, Peng Yu wrote: > Hi, > > '\b' only match the boundary between alphanumerical char and > nonalphanumerical char. I'm wonder if there is a generic metacharacter > to match the boundary between any non intersected char set defined in > regex and its complement. > > For example, I have a few non intersected char sets [a-zA-Z_0-9], [:] > and [\s], and lets call the new metacharactor \m. > > r"abc\m" would be the same as r"abc\b" > r"abc:\m' would match "abc:" in r"abc:xy" but not "abc::xy" > r"a \m" (with one space) would match "a " (with one space) in "a abc" > but not "a ?abc" (with two spaces). > > I would like that I have the flexibility to define more non > intersected char sets, while I don't want change the regex that I have > written. > Interesting idea. It could be added, but how much demand is there for it? From gagsl-py2 at yahoo.com.ar Thu Jul 17 19:26:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 17 Jul 2008 20:26:11 -0300 Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> <41d4ffc7-7fd5-4202-92ea-132c7d4f5cd4@s50g2000hsb.googlegroups.com> Message-ID: En Wed, 16 Jul 2008 15:00:50 -0300, Keith Hughitt escribi?: > Thanks Gabriel! > > That helps clear things up for me. The above method works very well. I > only have one remaining question: > How can I pass a datetime object to MySQL?' > > So far, what I've been doing is building the query as a string, for > example: > > query = "INSERT INTO image VALUES(%d, %d, %s, '%s')" % (id, meas, > date, 'jpg') > cursor.execute(query) That's not a good idea, in general (among other problems: what if any text contains a quote? ever heard of "sql injection"?). Use this form instead: query = "INSERT INTO image VALUES(%s, %s, %s, %s)" cursor.execute(query, (id, meas, date, 'jpg')) Note that I used %s everywhere (it's just a placeholder, not a format) and the execute method receives two arguments, the second being a tuple containing the desired values. -- Gabriel Genellina From jordanrastrick at gmail.com Thu Jul 24 06:21:20 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 03:21:20 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> > This is just plain wrong for at least C# and C++. ?C# wants you to > explicitly overload "!=", if you have overloaded "==", While this is as inconvenient as Python at least it doesn't catch you unawares. C# 1 (or maybe 0.5), Python 0. > C++ complains > about "!=" not being defined for class A. ? See above. C++ 1, Python 0. So in showing my clearly hyperbolic comment was technically incorrect (something I could have told you myself), you have merely shown that two languages I find vastly inferior to Python overall are actually better than it in this case. > Fortunately, Python isn't designed according to your ideas, and won't > change, so consider your posting a waste of time. ?If feeling like bringing > such old "issues" up again next time, spend your time learning another > programming language, as you would obviously not get happy with Python > anyway ... OK, if that's your response, that's sad. Of course, I try to learn new languages all the time. Python is still IMO the best. If the attitude in the community in response to feedback/criticism has gone from "maybe you've got a point" to "your a lunatic, we'll never change", well, only Python will suffer in the long term. From WookieTim at gmail.com Mon Jul 7 11:28:34 2008 From: WookieTim at gmail.com (furby) Date: Mon, 7 Jul 2008 08:28:34 -0700 (PDT) Subject: Hi there! I need what is probably a very basic lesson in events.... References: <4d5a5286-f4cf-480e-9432-b4b337f7c145@x35g2000hsb.googlegroups.com> <8fca22ab-67ad-4dbb-b92c-d5412a8eba2f@m44g2000hsc.googlegroups.com> Message-ID: On Jul 7, 10:34?am, Mike Driscoll wrote: > On Jul 6, 8:18?am, furby wrote: > > > > > I am teaching myself Python... I'm nowhere near even intermediate > > level yet, so treat me like an idiot. I am using Boa Constructor on > > Ubuntu 8.04 if that helps. Here is what I have right now : > > > I am plying with reading a URL (An RSS feed to be exact) and > > displaying it inside a HTMLWindow. I have that part working - It shows > > the title as a link and displays the description next to it. What I > > want to do is trap the mouseclick on the link and use that to grab > > just the text that is on the site. Right now, if I click on it, the > > HTML window control takes me to the site and doesn't really show the > > site very well, since it doesn't seem to do CSS. That's okay - I just > > want to display the text.... How do I trap the mouse clicking on the > > link? > > > I know that HTMLwindow has a "OnLinkClicked" event - I can see it in > > the docs for that control. But it seems that Boa Constructor doesn't > > expose that event in it's frame designer.... How do I code a event > > that fires off instead of the default event? > > > I don't know if I am being clear enough, so if not just tell me what I > > should say... Liek I said, I am a newbie right now. > > I think you just need to override that method (OnLinkClicked) in the > class you use to subclass the HtmlWindow widget. Something like this: > > > class MyCustomDlg(wx.Frame): > It sounds eminently reasonable. I'll try it tonight when I get home and let you know if it works! > ? ? def __init__(self, parent, title, icon, pos): > > ? ? ? ? wx.Frame.__init__(self, parent, wx.ID_ANY, title, > size=(400,400)) > > ? ? ? ? x,y = pos > ? ? ? ? self.SetPosition((x+30, y+30)) > > ? ? ? ? self.SetIcon(icon) > ? ? ? ? html = wxHTML(self) > > class wxHTML(wx.html.HtmlWindow): > ? ? ?def OnLinkClicked(self, link): > ? ? ? ? ?# do something here > ? ? ? ? ?pass > > > However, for wxPython questions, it's best to post to the wxPython > user's group. They are very knowledgeable there.http://wxpython.org/maillist.php > > Hope that helps. > > ------------------- > Mike Driscoll > > Blog: ?http://blog.pythonlibrary.org > Python Extension Building Network: ? ?http://www.pythonlibrary.org From Nikolaus at rath.org Tue Jul 29 04:20:07 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Tue, 29 Jul 2008 10:20:07 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <488D5B2C.10808@gmail.com> <488e6af8$0$20692$426a74cc@news.free.fr> Message-ID: <87tze9qeyw.fsf@nokile.rath.org> Bruno Desthuilliers writes: > Nikolaus Rath a ?crit : >> Michael Torrie writes: > > (snip) > >>> In short, unlike what most of the implicit self advocates are >>> saying, it's not just a simple change to the python parser to do >>> this. It would require a change in the interpreter itself and how it >>> deals with classes. >> >> >> Thats true. But out of curiosity: why is changing the interpreter such >> a bad thing? (If we suppose for now that the change itself is a good >> idea). > > Because it would very seriously break a *lot* of code ? Well, Python 3 will break lots of code anyway, won't it? Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From gherron at islandtraining.com Tue Jul 29 00:17:55 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 28 Jul 2008 21:17:55 -0700 Subject: exec(code) not allowing import on top level? In-Reply-To: References: Message-ID: <488E99F3.9040608@islandtraining.com> Peter Teuben wrote: > > if I define a simple string code, with the following contents: > > import math > def foo(x): > return math.sqrt(x) What? You have not told us something important here. First, that code won't fail because it does not even execute the function foo -- it just defines it. Second, if I exend your string with one more line "foo(123)" to actually execute the code, it still works as expected. So let's try this again... and this time please please also show us the full text of the error message. Gary Herron > > and i run it using exec(code) in python, math is not known. But when I > recode the string as: > > def foo(x): > import math > return math.sqrt(x) > > it works fine. That seemed like an inconsistency, since it works > fine otherwise, as expected. It's easy to work around, but > just odd to find this out. > > thanks > > peter > -- > http://mail.python.org/mailman/listinfo/python-list From martin at v.loewis.de Fri Jul 4 02:36:56 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 04 Jul 2008 08:36:56 +0200 Subject: problem parsing utf-8 encoded xml - minidom In-Reply-To: References: Message-ID: <486dc508$0$23431$9b622d9e@news.freenet.de> > The parser is failing on this line: > > Heinrich K?ufner, Norbert Nedopil, Heinz Sch?och (Hrsg.). mrcb245-c> If it is literally this line, it's no surprise: there must not be a line break between the slash and the closing element name. However, since you are getting the error in a different column, it's indeed more likely that there is a problem with the encoding. Given that the Python UTF-8 codec refuses the data, most likely, the data is *not* encoded in UTF-8 (but perhaps in Latin-1). If so, you need to prefix the XML document with a proper XML declaration, such as Alternatively, make sure that the file is really encoded in UTF-8. Regards, Martin From rocksportrocker at googlemail.com Fri Jul 18 02:41:50 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 17 Jul 2008 23:41:50 -0700 (PDT) Subject: How to process a very large (4Gb) tarfile from python? References: <0e96241d-60a3-44fd-967a-394904ad5b34@e39g2000hsf.googlegroups.com> <4nqu74p3mmmdmf9pn7125voe6itko8d31k@4ax.com> Message-ID: <1fe948fd-63a3-48ef-b5a8-84f0e4dd48a2@y22g2000prd.googlegroups.com> On 17 Jul., 22:21, Lars Gust?bel wrote: > > > Maybe we should post this issue to python-dev mailing list. > > Parsing large tar-files is not uncommon. > > This issue is known and was fixed for Python 3.0, seehttp://bugs.python.org/issue2058. The proposed patch does not avoid caching the previous values of the iterator, it just reduces the size of each cached object. It would be nice to be able to avoid caching on demand, which would make iteration independent of the size of the tar file. Greetings Uwe From mail at timgolden.me.uk Wed Jul 16 11:59:16 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 16:59:16 +0100 Subject: About wmi In-Reply-To: References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> Message-ID: <487E1AD4.9020509@timgolden.me.uk> patrol wrote: > -2147023174 > 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3' > None > None > > ---------------------------------------------------------------------- > import pythoncom > import win32com.client > > > try: > win32com.client.GetObject ("winmgmts://blahblah") > except pythoncom.com_error, info: > for i in info: > print i > > -2147023174 > RPC ??????? > None > None > ------------------------------------------------------------------------- >>>> a="RPC ???????" >>>> a > 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3' > ------------------------------------------------------------------------- > Patrol Brilliant. Thanks, Patrol. So the error message comes back encoded. Can you confirm what your console encoding is, please? The following script should confirm: import os, sys print sys.stdout.encoding os.system ("chcp") TJG From code at pizzashack.org Mon Jul 14 17:24:54 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 14 Jul 2008 17:24:54 -0400 Subject: Using Python To Launch Python In-Reply-To: References: Message-ID: <20080714212454.GE16010@dragontoe.org> On Mon, Jul 14, 2008 at 02:01:04PM -0700, aha wrote: > Since my application has it's own version of Python installed with > it how should I use the system Python to launch the version of > Python that launches my Application. Yes, this is a convoluted > process, but not all Pythons are built the same :) /usr/local/bin/$APPNAME: #!/bin/sh INSTALLPATH= PATH=$INSTALLPATH/bin:$PATH exec $INSTALLPATH/bin/python $APPNAME "$@" Doesn't get much simpler than that. :) You can certainly do the equivalent in Python... there's not much difference. Slightly less typing in bourne/bash shell, I guess... -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From dinov at exchange.microsoft.com Wed Jul 30 01:12:32 2008 From: dinov at exchange.microsoft.com (Dino Viehland) Date: Tue, 29 Jul 2008 22:12:32 -0700 Subject: interpreter vs. compiled In-Reply-To: References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> Message-ID: <7AD436E4270DD54A94238001769C2227012C9376BA46@DF-GRTDANE-MSG.exchange.corp.microsoft.com> IronPython doesn't have an interpreter loop and therefore has no POP / TOP / etc... Instead what IronPython has is a method call Int32Ops.Add which looks like: public static object Add(Int32 x, Int32 y) { long result = (long) x + y; if (Int32.MinValue <= result && result <= Int32.MaxValue) { return Microsoft.Scripting.Runtime.RuntimeHelpers.Int32ToObject((Int32)(result)); } return BigIntegerOps.Add((BigInteger)x, (BigInteger)y); } This is the implementation of int.__add__. Note that calling int.__add__ can actually return NotImplemented and that's handled by the method binder looking at the strong typing defined on Add's signature here - and then automatically generating the NotImplemented result when the arguments aren't ints. So that's why you don't see that here even though it's the full implementation of int.__add__. Ok, next if you define a function like: def adder(a, b): return a + b this turns into a .NET method, which will get JITed, which in C# would look something like like: static object adder(object a, object b) { return $addSite.Invoke(a, b) } where $addSite is a dynamically updated call site. $addSite knows that it's performing addition and knows how to do nothing other than update the call site the 1st time it's invoked. $addSite is local to the function so if you define another function doing addition it'll have its own site instance. So the 1st thing the call site does is a call back into the IronPython runtime which starts looking at a & b to figure out what to do. Python defines that as try __add__, maybe try __radd__, handle coercion, etc... So we go looking through finding the __add__ method - if that can return NotImplemented then we find the __radd__ method, etc... In this case we're just adding two integers and we know that the implementation of Add() won't return NotImplemented - so there's no need to call __radd__. We know we don't have to worry about NotImplemented because the Add method doesn't have the .NET attribute indicating it can return NotImplemented. At this point we need to do two things. We need to generate the test which is going to see if future arguments are applicable to what we just figured out and then we need to generate the code which is actually going to handle this. That gets combined together into the new call site delegate and it'll look something like: static void CallSiteStub(CallSite site, object a, object b) { if (a != null && a.GetType() == typeof(int) && b != null && b.GetType() == typeof(int)) { return IntOps.Add((int)a, (int)b); } return site.UpdateBindingAndInvoke(a, b); } That gets compiled down as a lightweight dynamic method which also gets JITed. The next time through the call site's Invoke body will be this method and things will go really fast if we have int's again. Also notice this is looking an awful lot like the inlined/fast-path(?) code dealing with int's that you quoted. If everything was awesome (currently it's not for a couple of reasons) the JIT would even inline the IntOps.Add call and it'd probably be near identical. And everything would be running native on the CPU. So that's how 2 + 2 works... Finally if it's a user type then we'd generate a more complicated test like (and getting more and more pseudo code to keep things simple): if (PythonOps.CheckTypeVersion(a, 42) && PythonOps.CheckTypeVersion(b, 42)) { return $callSite.Invoke(__cachedAddSlot__.__get__(a), b); } Here $callSite is another stub which will handle doing optimal dispatch to whatever __add__.__get__ will return. It could be a Python type, it could be a user defined function, it could be the Python built-in sum function, etc... so that's the reason for the extra dynamic dispatch. So in summary: everything is compiled to IL. At runtime we have lots of stubs all over the place which do the work to figure out the dynamic operation and then cache the result of that calculation. Also what I've just described is how IronPython 2.0 works. IronPython 1.0 is basically the same but mostly w/o the stubs and where we use stub methods they're much less sophisticated. Also, IronPython is open source - www.codeplex.com/IronPython -----Original Message----- From: python-list-bounces+dinov=microsoft.com at python.org [mailto:python-list-bounces+dinov=microsoft.com at python.org] On Behalf Of castironpi Sent: Tuesday, July 29, 2008 9:20 PM To: python-list at python.org Subject: Re: interpreter vs. compiled On Jul 29, 7:39 am, alex23 wrote: > On Jul 29, 2:21 pm, castironpi wrote: > > > On Jul 28, 5:58 pm, Fuzzyman wrote: > > > Well - in IronPython user code gets compiled to in memory assemblies > > > which can be JIT'ed. > > > I don't believe so. > > Uh, you're questioning someone who is not only co-author of a book on > IronPython, but also a developer on one of the first IronPython-based > commercial applications. > > I know authorship isn't always a guarantee of correctness, but what > experience do you have with IronPython that makes you so unwilling to > accept the opinion of someone with substantial knowledge of the > subject? None, no experience, no authority, only the stated premises & classifications, which I am generally tending to misinterpret. I'm overstepping my bounds and trying to do it politely. (Some might call it learning, which yes, though uncustomary, *requires questioning authorities*, or reinventing.) Evidently, I have a "fundamental misunderstanding of the compilation process", which I'm trying to correct by stating what I believe. I'm trying to elaborate, and I'm meeting with increasingly much detail. So, perhaps I'll learn something out of this. Until then... What I know I have is two conflicting, contradictory, inconsistent beliefs. Maybe I've spent too much time in Python to imagine how a dynamic language can compile. This is from 7/22/08, same author: > I wouldn't say "can't". The current CPython VM does not compile > code. It COULD. The C#/.NET VM does. Three big claims here that I breezed right over and didn't believe. > It COULD. I'm evidently assuming that if it could, it would. > The current CPython VM does not compile code. Therefore it couldn't, or the assumption is wrong. Tim says it is. And the glaring one-- WHY NOT? Why doesn't CPython do it? >From 7/18/08, own author: >> #define TOP() (stack_pointer[-1]) #define BASIC_POP() (*--stack_pointer) ...(line 1159)... w = POP(); v = TOP(); if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { /* INLINE: int + int */ register long a, b, i; a = PyInt_AS_LONG(v); b = PyInt_AS_LONG(w); i = a + b; << I am imagining that every Python implementation has something like it. If IronPython does not, in particular, not have the 'POP(); TOP();' sequence, then it isn't running on a stack machine. Is the IronPython code open source, and can someone link to it? I'm not wading through it from scratch. What does it have instead? Does dynamic typing still work? If you're bluffing, bluff harder; I call. If you're not, I apologize; teach me something. If you can ask better, teach me that too. -- http://mail.python.org/mailman/listinfo/python-list From bulg at ngs.ru Sun Jul 13 21:51:19 2008 From: bulg at ngs.ru (Yosifov Pavel) Date: Sun, 13 Jul 2008 18:51:19 -0700 (PDT) Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> Message-ID: > Well, I think Python's iterators, especially the generators, are beautiful. > More importantly, I think there is no general way to make iterators > copyable, regardless of the programming language. The problem is that most > of the useful ones depend on external state. > > Peter Hmm, but tee() de facto do it (clone iterator) and ignore side-effects of iterator ("external" state). And tee() create independent **internal** state of iterator (current position). But **external** state - is headache of programmer. So, iterator/generator have to be method for copy itself (the tee() implementation) or be "re- startable". Why not? Concrete problem was to generate iterators (iterator of slices). It was solved with ReIter. --Best regards, --pavel From __peter__ at web.de Tue Jul 29 07:48:39 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Jul 2008 13:48:39 +0200 Subject: exec(code) not allowing import on top level? References: Message-ID: Peter Teuben wrote: > > if I define a simple string code, with the following contents: > > import math > def foo(x): > return math.sqrt(x) The import math statement puts 'math' in the local namespace, and foo looks it up in the global namespace. This can only work when these namespaces are the same: >>> code = """ ... import math ... def foo(x): ... return math.sqrt(x) ... print foo(2) ... """ >>> exec code in {} 1.41421356237 >>> exec code in {}, {} Traceback (most recent call last): File "", line 1, in File "", line 5, in File "", line 4, in foo NameError: global name 'math' is not defined You could argue that Python should always look into the local namespace and then fall back to the global namespace but that would be fruitless extra work in most cases. I think it can only hapen with exec/eval, and as you have seen in the other responses even there it works on the module level because -- tada! >>> globals() is locals() True > and i run it using exec(code) in python, math is not known. But when I > recode the string as: > > def foo(x): > import math > return math.sqrt(x) Here Python "guesses" that math is a local variable and that guess is correct. If you wrote import math def foo(x): return math.sqrt(x) math = 42 Python would still guess that math is a local name and you would end up with a runtime exception. Peter From rw at smsnet.pl Wed Jul 9 15:56:46 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 09 Jul 2008 21:56:46 +0200 Subject: FOSS projects exhibiting clean/good OOP? References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> Message-ID: <87iqve25mp.fsf@merkury.smsnet.pl> Phillip B Oldham writes: > I'm wondering whether anyone can offer suggestions on FOSS projects/ > apps which exhibit solid OO principles, clean code, good inline > documentation, and sound design principles? > > I'm devoting some time to reviewing other people's code to advance my > skills. Its good to review bad code (of which I have more than enough > examples) as well as good, but I'm lacking in finding good examples. > > Projects of varying sizes would be great. IMHO these projects are examples of very interesting and clean design: docutils: http://docutils.sourceforge.net/docs/dev/hacking.html trac: http://trac.edgewall.org/wiki/TracDev/ComponentArchitecture In both of them code is not just clean, it is a work of art. ;) HTH, Rob From Russ.Paielli at gmail.com Wed Jul 30 22:36:53 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 30 Jul 2008 19:36:53 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> Message-ID: <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> On Jul 30, 7:05 pm, Erik Max Francis wrote: > Russ P. wrote: > > On Jul 30, 1:07 am, Erik Max Francis wrote: > >> Russ P. wrote: > >>> Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > >>> __nonzero__ work in Python. It's very basic stuff. You can quit > >>> patronizing me (and Carl too, I'm sure). > >> You suggested a syntax for testing non-emptiness (`x is not empty`) > >> which indicated a profound misunderstanding of what the `is` operator does. > > >> You then acknowledged that there might be a problem because of the > >> implication if the `is` operator and weren't sure whether it would work > >> or not: > > > Oh, my. I wrote something like, "It would sure be nice to be able to > > write > > > if x is not empty: > > > because it reads like natural language. Immediately after I posted it, > > I thought, "oh, I'll bet some idiot takes that as a serious proposal." > > Sure enough, some idiot did just that almost immediately. > > Yes, all people are idiots for reading what you wrote, reading your > later realization that it was wrong, and taking both at face value. > I'll be sure never to make that mistake again! > > > And he is > > still patronizing me for it. > > No, I'm not patronizing you for your initial misstatement. I'm mocking > you for your pathetic and transparent attempt to backpedal away from it. > Just give it up, already. > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis > Drifting from woman-who-tries misconstrued / Shifting to woman-wise > -- Lamya The reason I wrote that "it would be nice to be able to write" if x is not empty: is that it reads naturally. It was not an actual proposal, and the fact that you took it as such was *your* mistake. I can understand your misunderstanding one time, but you have now repeated it three times, despite my (unnecessary) explanations. One more time, and you graduate from idiot to moron. Having said that, the syntax I wrote *could* conceivably work IF all empty lists pointed to one empty list, just as all values set to None actually point to the same None. That is possible, but probably not a good idea. Now read carefully: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! Let me repeat that for you: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! Did you get that, idiot? From tjreedy at udel.edu Fri Jul 11 15:06:11 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 Jul 2008 15:06:11 -0400 Subject: Moving to functional programming In-Reply-To: <3ebed664-a6ba-4e30-acc5-f7d5edb25e32@56g2000hsm.googlegroups.com> References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> <3ebed664-a6ba-4e30-acc5-f7d5edb25e32@56g2000hsm.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > James Fassett: >> # the first Pythonic attempt using comprehensions >> result_list = [x[0] for x in tuple_list] This has the virtue of working for tuples of any length and doing the minimal work required. >> # the final functional way >> [result_list, _] = zip(*tuple_list) This requires the tuples in tuple_list to be of length 2. It also produces a second list that is then tossed away. > The list comprehension is quite more readable to me, so I suggest you > to use it. It's probably the default way to do it in Python. It also has two virtues that the non-equivalent alternative lacks. > If you want functional code this is another way (I have not tested the > relative performance but it may be quick): > >>>> tuple_list = ( > ... ('John', 'Doe'), > ... ('Mark', 'Mason'), > ... ('Jeff', 'Stevens'), > ... ('Bat', 'Man') > ... ) >>>> from operator import itemgetter >>>> map(itemgetter(0), tuple_list) > ['John', 'Mark', 'Jeff', 'Bat'] This again makes just one list from tuples of any length. Some of the other alternatives in another post do minimal work but only work with pairs. tjr From marek.rocki at wp.pl Fri Jul 4 11:19:01 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Fri, 4 Jul 2008 08:19:01 -0700 (PDT) Subject: Javascript - Python RSA encryption interoperability References: Message-ID: <79934f50-2208-4e68-8d61-1fd33d34a468@a1g2000hsb.googlegroups.com> Evren Esat Ozkan napisa?(a): > Hello, > > I'm trying to encrypt a string with RSA. But it needs to be compitable > with Dave's JavaScript RSA implementation*. I'm already read and tried > lots of different things about RSA and RSA in Python. But could not > produce the same result with the javascript library. > > My experiments could be seen at: http://dpaste.com/hold/60741/ > > * JavaScript RSA Library: http://www.ohdave.com/rsa/ > > Python libraries which I tried; > * PyCrtypo: http://www.amk.ca/python/code/crypto.html > * rsa library from http://www.stuvel.eu/rsa > > How could I create the same results with the JS library in Python. > > > Any help would be appreciated > > Evren, It seems that this Javascript is doing weird things to its input, namely processing it in reverse. Try encrypting ciphertext[::-1] instead of just ciphertext. public_modulus_hex = '9F2E..snip..4BC7' public_exponent_hex = '10001' public_modulus = int(public_modulus_hex, 16) public_exponent = int(public_exponent_hex, 16) def encrypt(plaintext_text): # Beware, plaintext must be short enough to fit in a single block! plaintext = int(plaintext_text.encode('hex'), 16) ciphertext = pow(plaintext, public_exponent, public_modulus) return '%X' % ciphertext # return hex representation print encrypt('12345') print encrypt('12345'[::-1]) # Will return the value compatible with JS output Regards, Marek From larry.bates at websafe.com` Fri Jul 25 07:30:33 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Fri, 25 Jul 2008 06:30:33 -0500 Subject: object persistency, store instances relationship externally In-Reply-To: <3183af12-4b1e-4bd1-8d21-b9fc2b421008@v1g2000pra.googlegroups.com> References: <3183af12-4b1e-4bd1-8d21-b9fc2b421008@v1g2000pra.googlegroups.com> Message-ID: <2dqdnXc7zqT2JBTVnZ2dnUVZ_umdnZ2d@comcast.com> King wrote: > This is a new test for object persistency. I am trying to store the > relationship between instances externally. > It's not working as expected. May be I am doing it in wrong way. Any > suggestions? > > > import shelve > > class attrib(object): > pass > > class node(object): > def __init__(self): > self.a = attrib() > self.b = attrib() > self.c = attrib() > self.d = attrib() > > a = node() > #store pair relationship. This relationship is created at run time. > lst = [[a.a, a.b], [a.c, a.d]] > #Write objects into file > shelf = shelve.open('shelve_test_01.txt', writeback=True) > shelf['node'] = a > shelf['lst'] = lst > shelf.sync() > shelf.close() > > > #Read objects from file > shelf = shelve.open('shelve_test_01.txt', 'r') > a = shelf['node'] > lst = shelf['lst'] > print a.a, a.b, a.c, a.d > #lst does not contains the relationship of object 'a''s attributes, > instead it's creating new instances > #of 'attrib' class > print lst > You may want to take a look at Zope's ZODB. -Larry From RyanSmithEE at gmail.com Thu Jul 17 14:47:14 2008 From: RyanSmithEE at gmail.com (Ryan Smith) Date: Thu, 17 Jul 2008 11:47:14 -0700 (PDT) Subject: Rotating a cube References: <3d47df08-9734-4e0f-96ad-37da445b4faf@34g2000hsh.googlegroups.com> Message-ID: <58b8339f-658e-432d-9231-3509a04f422b@s21g2000prm.googlegroups.com> Have you taken the time to solve the problem for the 2D case? I can't say my code is correct or even good python, but this was my attempt at the 2D case, maybe it will give you some ideas. http://code.google.com/p/rs-wxpython-nooberdev/source/browse/rectangle.py For the rest of c.l.p, criticism is welcome :-) Regards, Ryan On Jul 17, 2:11 am, J-Burns wrote: > On Jul 17, 12:53 pm, Fredrik Lundh wrote: > > > J-Burns wrote: > > > Is there a built in Python function for this? > > > for answering questions that have nothing to do with programming, and > > looks quite a bit like homework? don't think they've added that one yet. > > > maybe you should look for a geometry newsgroup/forum? > > > > > I meant to ask how would you do this in Python... :S From mangaboy001 at gmail.com Tue Jul 1 06:15:45 2008 From: mangaboy001 at gmail.com (mangaboy001) Date: Tue, 1 Jul 2008 03:15:45 -0700 (PDT) Subject: Naruto 407, One Piece 506, Bleach 329 Hot manga Download Message-ID: <062683aa-ff14-43f9-818d-a3a623b0e051@u36g2000prf.googlegroups.com> Naruto 407, One Piece 506, Bleach 329 Hot manga Download The hottest mangas and the latest chapters Manga news, Most popular mangas, Latest mangas, Latest chapters http://english1.isoshu.com/?recommid=1023 http://emanga1.isoshu.com/?recommid=1023 A New Wonderful Manga: Maken-ki! http://english1.isoshu.com/search/Maken-ki/all-1?recommid=1023 Hi, my friends!!! Have you read the manga named Maken-ki? This manga series is as nice as To-Love-ru!!! The illustrator is Hiromitsu Takeda and his girls are incredibly gorgeous. The story is described as an "ecchi love comedy with battle action." Oyama Takeshi happily enrolls in a co-ed school that didn't required any entrance exams and has hostels to book... Only to find out that there's more to the school than he thought! It is very good that Takeda-san likes to draw his girls with very big eyes. Have only read a bit so far but many of the girls have an item called "Maken" - each are different and have varying powers when used in battle. And as with all good school girl battles, their clothes easily explode. And there are characters for folks who like loli's too. Maken Ki has been an entertaining read so far and look forward to more!!! I am sure that you must be love it at the first glance!!! http://english1.isoshu.com/search/Maken-ki/all-1?recommid=1023 From wuwei23 at gmail.com Thu Jul 24 13:03:35 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 24 Jul 2008 10:03:35 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> Message-ID: <73ba661a-9d3b-4e53-b233-fd1b21dc9f6d@a2g2000prm.googlegroups.com> On Jul 25, 1:39 am, Torsten Bronger wrote: > I could easily write a preprocessor which does it after all. Have you considered actually doing so? That might resolve the whole issue, if a tool exists for those who want implicit self. After all, if -you- have the itch... Perhaps you could leverage off of EasyExtend? "EasyExtend (EE) is a preprocessor generator and metaprogramming framework written in pure Python and integrated with CPython. The main purpose of EasyExtend is the creation of extension languages i.e. adding custom syntax and semantics to Python." http://www.fiber-space.de/EasyExtend/doc/EE.html From tjreedy at udel.edu Tue Jul 15 17:00:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Jul 2008 17:00:48 -0400 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: <8AEDA5E3386EA742B8C24C95FF0C758004622F93@PDC-MAIL3.ubisoft.org> References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> <487CD564.5020008@hughes.net> <8AEDA5E3386EA742B8C24C95FF0C758004622F93@PDC-MAIL3.ubisoft.org> Message-ID: Andreas Tawn wrote: > I think a better explanation is that in your original function, x only > existed while the for loop was running. As soon as execution hit the > break statement, x ceased to exist. Wrong. For loop variables continue after the loop exits. This is intentional. Mensanator gave the correct explanation (loop never enters for nbr==1). From bruno.42.desthuilliers at websiteburo.invalid Fri Jul 4 08:29:56 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 04 Jul 2008 14:29:56 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: <486e17b2$0$12609$426a74cc@news.free.fr> Henning_Thornblad a ?crit : > What can be the cause of the large difference between re.search and > grep? > > This script takes about 5 min to run on my computer: > #!/usr/bin/env python > import re > > row="" > for a in range(156000): > row+="a" > print re.search('[^ "=]*/',row) > > > While doing a simple grep: > grep '[^ "=]*/' input (input contains 156.000 a in > one row) > doesn't even take a second. > > Is this a bug in python? Please re-read carefully your python code. Don't you think there's a subtle difference between reading a file and buildin 156000 string objects ? From scottpig1 at comcast.net Tue Jul 29 21:38:01 2008 From: scottpig1 at comcast.net (pigmartian) Date: Tue, 29 Jul 2008 21:38:01 -0400 Subject: static variables in Python? In-Reply-To: <115a132d-7edd-4b07-ba4f-7855577992d1@x41g2000hsb.googlegroups.com> References: <115a132d-7edd-4b07-ba4f-7855577992d1@x41g2000hsb.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > kj: >> OK, I guess that in Python the only way to do what I want to do >> is with objects... > > There are other ways, like assigning the value out of the function, > because Python functions too are objects: > ... > But I suggest you to use a class in this situation, it's often the way > that will keep your code more bug-free, and more readable by near- > casual readers too. Python philosophy asks you to write readable code > instead of clever code when possible, this is a difference from Perl, > I presume. > > Bye, > bearophile Here's a solution using decorators, I like it, but I'm biased: def staticAttrs(**kwds): """ Adds attributes to a function, akin to c-style "static" variables """ def _decorator(fcn): for k in kwds: setattr(fcn, k, kwds[k]) return fcn return _decorator @staticAttrs(n=0) def rememberCalls(): """ >>> rememberCalls() 0 >>> rememberCalls() 1 >>> rememberCalls() 2 """ print rememberCalls.n rememberCalls.n += 1 ~Scott From motoom at xs4all.nl Thu Jul 10 20:26:42 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Fri, 11 Jul 2008 02:26:42 +0200 Subject: Can anyone suggest a date peocedure... In-Reply-To: References: Message-ID: <3B32695E-249A-4D4A-B69D-F1A0E5A85474@xs4all.nl> Ron wrote: > Now all I need to know is how to > plug the date into the datetime object from a string. You could use simple string manipulation: >>> import datetime >>> a="20081031" >>> d=datetime.date(int(a[0:4]),int(a[4:6]),int(a[6:8])) >>> d datetime.date(2008, 10, 31) >>> print d 2008-10-31 Greetings, From robert.rawlins at thinkbluemedia.co.uk Sat Jul 19 05:43:54 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Sat, 19 Jul 2008 10:43:54 +0100 Subject: __del__ methods In-Reply-To: References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> Message-ID: <010101c8e983$f785ae60$e6910b20$@rawlins@thinkbluemedia.co.uk> > Yes. > > "Objects that have __del__() methods and are part of a reference cycle > cause the entire reference cycle to be uncollectable, including > objects not necessarily in the cycle but reachable only from it. > Python doesn't collect such cycles automatically because, in general, > it isn't possible for Python to guess a safe order in which to run the > __del__() methods." > > The uncollectable objects are stored in gc.garbage and will not be > freed until their reference cycles are broken and they are removed > from that list. Ok, guys, I've just recently (in the past week) started using the __del__ method to log class instance destruction so I can keep a track of when objects are created and destroyed, in order to help me trace and fix memory leaks. Are you saying that on the adverse side to this, __del__ may in fact be the CAUSE of a memory leak within my application? If this is the case and __del__ creates such a vulnerability within the application, and apparently isn't all that reliable anyway, why is it still part of the python platform? Cheers, Robert From sjmachin at lexicon.net Sun Jul 20 20:43:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 Jul 2008 17:43:46 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <41d4aa44-253b-42f6-8c02-4eec4eaf6647@w39g2000prb.googlegroups.com> On Jul 21, 8:50 am, giveitawhril2... at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Why do that, when gcc has a code generator for just about every MPU chip out there? > Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# A bit of a non sequitur .... and C# is available on how many different MPU chips? > and Python is > akin to Visual Basic > or something: a specialty language > ....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. ? > > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! Nobody wants to use C any more? > So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. It should be sublimely irrelevant to most people learning LanguageX what language LanguageX is written in. Some other implementations of Python: PyPy (written in Python), Jython (written in Java) and IronPython (written in C#). From Graham.Dumpleton at gmail.com Wed Jul 23 08:50:25 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Wed, 23 Jul 2008 05:50:25 -0700 (PDT) Subject: Python Embedding Thread References: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> <87bf413d-eb98-47c0-8466-237c45fd1a0e@e53g2000hsa.googlegroups.com> <5081c3df-cb66-443b-ac71-be9661ae057d@27g2000hsf.googlegroups.com> Message-ID: On Jul 23, 12:15?pm, "Jaimy Azle" wrote: > wrote: > > I fixed the code. This code snippet runs in a seperate thread: > > > PyObject *dict=NULL; > > PyGILState_STATE state = PyGILState_Ensure(); > > dict = CreateMyGlobalDictionary(); > > > PyRun_String(, Py_file_input, dict, dict); > > > ReleaseGlobalDictionary(dict); > > > But it still does not work... :-/ > > Have you initialize interpreter with PyEval_InitThreads? look athttp://www.python.org/doc/1.5.2/api/threads.htmlfor more information. > > Oh, btw... I did use python in a bit different scenario than you've > described. Since you attempt to run different script per-host thread, you > might need python multiple interpreter support, I suggest you take a lookmod_pythonimplementation. Please don't look at mod_python. Current versions of mod_python don't use Python simplified GIL APIs correctly. http://issues.apache.org/jira/browse/MODPYTHON-217 Look at mod_wsgi instead, it is closer to the mark, although still has some not quite cruft in there to workaround mistakes in mod_python for case where mod_python and mod_wsgi are being loaded together. :-( Graham From fredrik at pythonware.com Wed Jul 16 16:24:22 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 22:24:22 +0200 Subject: For_loops hurt my brain. In-Reply-To: <4874c21f-befa-4e9f-a99d-486cc9c9b5b8@d77g2000hsb.googlegroups.com> References: <4874c21f-befa-4e9f-a99d-486cc9c9b5b8@d77g2000hsb.googlegroups.com> Message-ID: bsagert at gmail.com wrote: > This script uses a simple for loop to zip some files. However I am > repeating code that cries out for a nested loop. Cries out for a *function*, I'd say. > My two lists of files_to_be_zipped (spare and seekfacts) are of > uneven length so I can't seem to decipher the "for_logic". > I would appreciate any help. > import zipfile > import os > spare = [ > 'c:/spare/huge.fm3', > 'c:/spare/huge.wk3' > ] > seekfacts = [ > 'c:/seekfacts/bookmark.html', > 'c:/seekfacts/index.htm', > 'c:/seekfacts/seek.css', > 'c:/seekfacts/seek.js' > ] def zipit(outfile, file_list): zFile = zipfile.ZipFile(zips[0], 'w') for file in file_list: zFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) zFile.close() zipit("c:/spare.zip", spare) zipit("c:/seekfacts.zip", seekfacts) From drakonik at gmail.com Sun Jul 13 15:30:14 2008 From: drakonik at gmail.com (Nick Dumas) Date: Sun, 13 Jul 2008 15:30:14 -0400 Subject: Newbie Threading Question In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I'm not an expert on Python threading, so don't take my word as low, however, I believe that there's no need for a list of systems which support it because the Python virtual machine handles it. Thus, any system which supports Python (or at least Python versions with threading) will support Python threading. Again, I don't know a lot about this, but it would make sense. Sparky wrote: > It seems strange, but I can't find a list of operating systems which > support / don't support threading in Python. Can anyone point me in > the right direction? > > Thanks, > Sam -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkh6V8YACgkQLMI5fndAv9hVKgCePbrN4nwbsdZXNfIcnm3cXac5 5kUAnR0OeNB0gjsksRD2W5gcZ8c0pby0 =p3U+ -----END PGP SIGNATURE----- From dullrich at sprynet.com Fri Jul 11 12:20:53 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 11 Jul 2008 11:20:53 -0500 Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: In article , ssecorp wrote: > >>> def mod(x,y): > return x.append(y) > > >>> mod([1,2],3) > >>> k=[1,2,3] > >>> k > [1, 2, 3] > >>> l = mod(k,4) > >>> l > >>> k > [1, 2, 3, 4] > >>> l > >>> k==l > False > >>> mod(k,5) > >>> k > [1, 2, 3, 4, 5] > >>> mod(l,4) > > Traceback (most recent call last): > File "", line 1, in > mod(l,4) > File "", line 2, in mod > return x.append(y) > AttributeError: 'NoneType' object has no attribute 'append' > >>> l > >>> l=k > >>> l > [1, 2, 3, 4, 5] > >>> i=mod(k,1) > >>> i > >>> > > same stuff but i dont find this intuitive. You need to read the docs. AList.append(x) does _not_ return AList with x appended. In fact it returns None, because it wants to be a "procedure" that doesn't return anything at all, but there is no such thing in Python; functions and methods that do not explicitly contain a "return" statement return None. So when you say "return x.append(a)" you're saying "return None", which explains the rest of it. You noticed that the second line of > >>> l = mod(k,4) > >>> l didn't print anything? That's because the first line set l to None. If you'd typed "print l" instead of just "l" you would have seen >>> l = mod(k,4) >>> l >>> None -- David C. Ullrich From robert.rawlins at thinkbluemedia.co.uk Sun Jul 20 06:56:58 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Sun, 20 Jul 2008 11:56:58 +0100 Subject: __del__ methods In-Reply-To: <87prp8x23x.fsf@benfinney.id.au> References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> <87hcalxvx0.fsf@benfinney.id.au> <87prp8x23x.fsf@benfinney.id.au> Message-ID: <007e01c8ea57$57225020$0566f060$@rawlins@thinkbluemedia.co.uk> > Time to fix that, then, with some documentation > , and by working through the Python > tutorial . Thanks Ben, I'll be sure to read through these. I also read through this http://www.geocities.com/foetsch/python/new_style_classes.htm earlier this morning which was also a nice little resource. Just about all of it makes sense at the moment, apart from the new constructor types which are constructors at a class level opposed to at instance level. I found this a little confusing but who knows. Presumably this is where you would deal with setting things which exist in every instance of a class, and properties that can vary from instance to instance go into the standard __init_(), have I got that right? Cheers Ben, Robert From gagsl-py2 at yahoo.com.ar Fri Jul 11 05:45:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Jul 2008 06:45:45 -0300 Subject: Trying to learn References: <8763rcrejw.fsf@benfinney.id.au> Message-ID: En Fri, 11 Jul 2008 05:49:23 -0300, Ben Finney escribi?: > luster123 writes: > >> Can someone please teach me the basics of Python and Pygame? > > Yes, you can do it. > > > > Also you can find other resources in the Python wiki: -- Gabriel Genellina From ldo at geek-central.gen.new_zealand Mon Jul 28 00:02:02 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 28 Jul 2008 16:02:02 +1200 Subject: How to find processes from Python References: <9f04931c-867b-4ff3-820c-3f8d0bfd2618@e53g2000hsa.googlegroups.com> Message-ID: In message <9f04931c-867b-4ff3-820c-3f8d0bfd2618 at e53g2000hsa.googlegroups.com>, Johny wrote: > Is there a way how to find out running processes?E.g. how many > Appache's processes are running? Under Linux, every process has a procfs directory /proc/, where is the process ID. In here you will find all kinds of interesting information about the process command line, what files it has open, its environment, its memory usage etc. From ldo at geek-central.gen.new_zealand Mon Jul 21 05:32:04 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 21 Jul 2008 21:32:04 +1200 Subject: db question References: Message-ID: In message , Dennis Lee Bieber wrote: > On Sun, 20 Jul 2008 18:43:03 -0700, "bruce" > declaimed the following in comp.lang.python: >> >> mysql cmd - select * from foo where dog like "%small%"; >> >> sql ="""select * from foo where dog like "%%%s%%" """ >> c.execute(sql, (var,)) > > The execute statement is responsible quoting your literals, so the > final statement you end up submitting looks like: > > select * from foo where dog like ""%"xxx"%"" > > or some variant thereof. > > Anything parameterized with %s must be a complete term! > > Try: > > sql = "select * from foo where dog like %s" > c.execute(sql, ("%" + var + "%",) ) > > IOW: you need to massage the variable search term to include the > wildcard % FIRST, then let MySQLdb substitute it (with surrounding > quotes and escapes) into the SQL. More general, less pitfall-prone solution: select * from foo where dog like %s" % SQLString("%" + EscapeSQLWild("small") + "%") where SQLString and EscapeSQLWild are defined as in . From ivan at datasyncorp.com Wed Jul 16 14:45:38 2008 From: ivan at datasyncorp.com (Ivan Ven Osdel) Date: Wed, 16 Jul 2008 13:45:38 -0500 (CDT) Subject: Framework recommendations for web service? In-Reply-To: <1561508290.1827571216233656023.JavaMail.root@saturn.datasyncintra.net> Message-ID: <2002101011.1828051216233938686.JavaMail.root@saturn.datasyncintra.net> >I don't think RESTful interfaces are built in but I know people have succesfully built RESTful apps on top of CherryPy. Also plans >for REST in CherryPy 3 look promising. Here is a post I ran across from one of the contributers. >"Hey there, >CherryPy 3 is currently under brainstorming before being first draft. There some feature we do want such as the ability to change >the URL dispatching at will depending on what is required for a given application. > >One dispatching rule I do want is the one based on HTTP verbs. So it might take a few months to get there but eventually it will be >a built-in :) > >- Sylvain" My apologies, it appears that post was from 2006! -- Ivan Ven Osdel Senior Software Engineer http://datasyncsuite.com From tjreedy at udel.edu Tue Jul 29 23:17:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 23:17:49 -0400 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: Carl Banks wrote: >> As I wrote in the second reply email I sent, check out my integer set >> recipe on ASPN (and to save you the search: http://code.activestate.com/recipes/466286/). > > Couple points: > > 1. Any container type that returns a length that isn't exactly the > number of elements in it is broken. > 2. The need for __nonzero__ in this case depends on a limitation in > the language. > 3. On the other hand, I will concede that sometimes calculating len is > a lot more expensive than determining emptiness, and at a basic level > it's important to avoid these costs. You have found a practical use > case for __nonzero__. I thought of another one: testing whether an iterator is 'empty' (will raise StopIteration on the next next() (3.0) call) or not. As virtual collections, iterators generally have neither __len__ or __bool__. But __bool__ (but only __bool__) can be added to any iterator by wrapping it with something like the following 3.0 code (not tested): class look_ahead_it(): def __init__(self, iterable): self.it = iter(iterable) self.fill_next() def __iter__(self): return self def __next__(self): tem = self.next if tem is self.empty: raise StopIteration else: self.fill_next() return tem empty = object() def fill_next(self) try: self.next = next(self.it) except StopIteration: self.next = self.empty def __bool__(self): return self.next is not self.empty From nagle at animats.com Fri Jul 25 14:24:13 2008 From: nagle at animats.com (John Nagle) Date: Fri, 25 Jul 2008 11:24:13 -0700 Subject: interpreter vs. compiled In-Reply-To: References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> Message-ID: <488a15ed$0$17181$742ec2ed@news.sonic.net> Tim Roberts wrote: > And I'm saying you are wrong. There is NOTHING inherent in Python that > dictates that it be either compiled or interpreted. That is simply an > implementation decision. The CPython implementation happens to interpret. > The IronPython implementation compiles the intermediate language to native > machine language. Well, actually there are some Python language features which make static compilation to machine code difficult. PyPy and Shed Skin have to impose some restrictions on dynamism to make efficient compilation feasible. The big problem is "hidden dynamism", where the code looks static, but at run time, some external piece of code replaces a function or adds an unexpected attribute to what looked like a simple object or function in the defining module. In CPython, everything is a general object internally, and all the names are resolved over and over again at run time by dictionary lookup. This is simple, but there's a sizable speed penalty. John Nagle From deets at nospam.web.de Fri Jul 25 10:44:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 25 Jul 2008 16:44:06 +0200 Subject: Calling external program from within python In-Reply-To: References: <6eu684F91muhU1@mid.uni-berlin.de> Message-ID: <6eu75mF92mqcU1@mid.uni-berlin.de> Grant Edwards schrieb: > On 2008-07-25, Diez B. Roggisch wrote: > >>> There are probably many ways to do this. I would recommend >>> checking out the subprocess module and see if it does what you >>> want. >> This will only work if the program can be fully controlled by >> commandline arguments. > > Why do you say that? You can interact with programs via > stdin/stdout using the subprocess module. Because usually if a program *prompts* the user to enter input (and that was what I read from the OP's post), one has to deal with pseudo terminals, not with stdin/out. >> If interaction is required, the OP might consider using >> pexpect. > > Pexpect is a good option, but it's just an automation layer on > top of the same facilities that subprocess provides. AFAIK it's more than that. I'm not an expert on pseudo terminals, but AFAIK setting using module pty isn't possible using subprocess. Diez From ndbecker2 at gmail.com Fri Jul 11 11:29:55 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 11 Jul 2008 11:29:55 -0400 Subject: decorator to prevent adding attributes to class? Message-ID: After spending the morning debugging where I had misspelled the name of an attribute (thus adding a new attr instead of updating an existing one), I would like a way to decorate a class so that attributes cannot be (easily) added. I guess class decorators are not available yet (pep 3129), but probably inheritance can be used. Can anyone suggest an implementation? From alan.franzoni.blahblah at example.com.invalid Mon Jul 28 12:01:41 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Mon, 28 Jul 2008 16:01:41 GMT Subject: write unsigned integer 32 bits to socket References: <9_KdnfSDZ9xHIRDVnZ2dnUVZ_gCdnZ2d@pdx.net> Message-ID: Scott David Daniels was kind enough to say: > Alan Franzoni wrote: > Please don't pass this misinformation along. > > In the struct module document, see the section on the initial character: > Character Byte order Size and alignment > @ native native > = native standard > < little-endian standard > > big-endian standard > ! network (= big-endian) standard Sure, that's is one way to do it... but I was answering Micheal Torrie, who said: > htonl() call, and then when pulling it off the wire on the other end >you'd use ntohl(). If you don't then you will have problems when the htonl() and ntohl() are available in Python in the socket module, so: 1) i was just pointing the OP to the right place where to find such functions 2) they work just the same way, hence I can't see why the "struct" way should be the preferred one while the "socket" way should be misinformation :P Bye! -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From execrable at gmail.com Wed Jul 23 23:02:03 2008 From: execrable at gmail.com (B) Date: Wed, 23 Jul 2008 20:02:03 -0700 Subject: Recursion Performance Question Message-ID: Hey I found some (VERY) old C++ code of mine that recursively built a tree of the desktop window handles (on windows) using: (they are stored in an STL vector) void FWL(HWND hwnd, int nFlag) // Recursive Function { hwnd = GetWindow(hwnd, nFlag); if(hwnd == NULL) return; AddWnd(hwnd); nLevel++; FWL(hwnd, GW_CHILD); nLevel--; FWL(hwnd, GW_HWNDNEXT); return; } int FillWindowList(bool bReset) // Build Window List { WLI wli; if(bReset) ResetWindowList(); nLevel = 0; FWL(ui.hWnd, GW_HWNDFIRST); return nCount; } Now the interface on this program is really ugly (i hate UI coding), so I was thinking about re-writing it in python to use PyQt for an easy GUI. So far I have (they are stored in a 'tree' class): # pass in window handle and parent node def gwl(node, hwnd): if hwnd: yield node, hwnd for nd, wnd in Wnd.gwl(node.children[-1], GetWindow(hwnd, GW_CHILD)): yield nd, wnd for nd, wnd in Wnd.gwl(node, GetWindow(hwnd, GW_HWNDNEXT)): yield nd, wnd def generateTree(self): t = time.clock() if self is not None: self.children = [] for nd, wnd in Wnd.gwl(self, GetWindow(self.hwnd, GW_CHILD)): nd.addChild(wnd) Now it works, but it runs quite slow (compared to the c++ app). I changed gwl from strait recursion to use a generator and that helped, but it still takes 0.5-1.0 seconds to populate the tree. What I'm wondering is am I doing it in a really inefficient way, or is it just python? The second problem is reseting the list. In C++ I would use the STL Vector's clear() method. In python, I can't think of a good way to free all the nodes, so there is a large memory leak. I can post more of the code if it's unclear, I just didn't want to write a really long post. From iainking at gmail.com Thu Jul 31 05:06:56 2008 From: iainking at gmail.com (Iain King) Date: Thu, 31 Jul 2008 02:06:56 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> <024f39e3-4a24-489f-812f-38977e468075@o40g2000prn.googlegroups.com> Message-ID: On Jul 31, 7:08 am, "Russ P." wrote: > On Jul 30, 10:43 pm, Erik Max Francis wrote: > > > > > Russ P. wrote: > > > On Jul 30, 9:27 pm, Erik Max Francis wrote: > > >> You're sure going on about a distinction without a difference for a guy > > >> who childishly likes to call other people names. A reasonable person > > >> would have long ago moved on instead of blaming others for not > > >> immediately intuiting your thoughts, rather than straightforwardly > > >> reading your words. Which, by the way, includes at least three people > > >> other than myself. > > > >> But I'll bet the mindless namecalling is really working out for you. > > >> Go, team, go! > > > > You earned the "childish name calling" by acting like a child -- with > > > your petty little game of trying to show that I don't understand a > > > basic concept in Python. As I said, your initial misunderstanding, > > > while silly, was at least forgivable. But your insistence on repeating > > > it time after time is not. It is truly pathetic. > > > Sis, boom, rah rah rah! > > > You're kind of skipping over the point where three other people had the > > same misunderstanding about your original statement and correction, so > > Another whopper, but who's counting? > > > maybe the reader is not the problem but rather the writer, but hey, > > don't let that get in the way of a good public shitfit. > > > You're winning! > > And you're a professional of some sort? Man, I can't even imagine > working in an environment with people like you. I guess I'm pretty > lucky to work with real professionals who don't play petty little > games like the one you played here -- and are still playing. Go ahead, > have the last word, loser -- then get lost. You understand this is usenet, right? Where we can all read the entire thread? So trying to spin the situation just doesn't work? Just checking... Iain From dickinsm at gmail.com Sat Jul 5 11:13:36 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 5 Jul 2008 08:13:36 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: <9cae59d9-ead4-45bc-a980-2ac2e1616f9b@p25g2000hsf.googlegroups.com> On Jul 5, 1:54?pm, Carl Banks wrote: > I don't think you've illustrated that at all. ?What you've illustrated > is that one implementation of regexp optimizes something that another > doesn't. ?It might be due to differences in complexity; it might not. > (Maybe there's something about PCREs that precludes the optimization > that the default grep uses, but I'd be inclined to think not.) It seems like an appropriate moment to point out *this* paper: http://swtch.com/~rsc/regexp/regexp1.html Apparently, grep and Tcl convert a regex to a finite state machine. Matching is then *very* fast: essentially linear time in the length of the string being matched, even in the worst case. Though it is possible for the size of the finite state machine to grow exponentially with the size of the regex. But not all PCREs can be converted to a finite state machine, so Perl, Python, etc. use a backtracking approach, which has exponential running time in the worst case. In particular, it's not possible to use a finite state machine to represent a regular expression that contains backreferences. Part of the problem is a lack of agreement on what 'regular expression' means. Strictly speaking, PCREs aren't regular expressions at all, for some values of the term 'regular expression'. See http://en.wikipedia.org/wiki/Regular_expression Mark From mensanator at aol.com Thu Jul 3 19:51:52 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 3 Jul 2008 16:51:52 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> <7db52b03-7a8a-40c4-b3cb-f6dccd273b90@59g2000hsb.googlegroups.com> Message-ID: <45ce2acc-e4b5-4762-8daa-b67a78b02411@w7g2000hsa.googlegroups.com> On Jul 3, 6:24?pm, George Sakkis wrote: > On Jul 3, 5:49?pm, Mensanator wrote: > > > On Jul 3, 2:52?pm, Terry Reedy wrote: > > > > Worthless to you, worthwhile to me. ? > > > The OP's opinion is the only one that matters. > > I bet the OP doesn't know (or care) what gmpy is. But he'll care if he tries to use something specific to 2.6 and it fails and he doesn't know why. > > > What do you suppose > > is the percentage of posts on this newsgroup by those using 3.0? > > Taking into account 2.6 too (we're not talking about only 3.0 here), > probably not much less than those who even know what is gmpy, let > alone dismiss a beta Python release because their obscure pet module > is not available yet. That was just an example. When you consider ALL the pet modules like PIL, Numpy, Win32, etc., that's a lot, isn't it. > You will probably sound less negative if you refrain from projecting > your own very specialized needs to those of the average pythonista. Funny how you don't complain when Mr. Reedy projects HIS specialized needs to the average pythonista. I was just trying to be helpful (I admit I often sound negative when I'm not trying to be). > > George From cwitts at gmail.com Fri Jul 18 04:08:25 2008 From: cwitts at gmail.com (Chris) Date: Fri, 18 Jul 2008 01:08:25 -0700 (PDT) Subject: Python Behind a Squid Corporate Proxy on Windows References: <7b541a3b-846f-496a-aee1-d5719217e011@m45g2000hsb.googlegroups.com> <821d7616-3faa-4dae-a988-18caf4f8598a@8g2000hse.googlegroups.com> Message-ID: <84c473ed-6993-481a-b789-35851242895b@f1g2000prb.googlegroups.com> On Jul 17, 6:40?pm, Larry Hale wrote: > Err, the line above should be: > > proxy_handler = urllib2.ProxyHandler( { "http": "http:// > myusername:passw... at webfilter.xyz.local:3128" } ) > > (Sorry! ?:) some old code I wrote to download public domain info for our company, also through a squid proxy and this still works for me import urllib2, urllib proxy = urllib2.ProxyHandler({'http': 'http:// username:password at proxy_url:proxy_port'}) auth = urllib2.HTTPBasicAuthHandler() opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) urllib2.install_opener(opener) conn = urllib2.urlopen('http://python.org') return_str = conn.read() fp = open('python.html','w').write(return_str) From tjreedy at udel.edu Wed Jul 16 19:56:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 Jul 2008 19:56:02 -0400 Subject: Custom 'Float' class. Am I right here? In-Reply-To: <552799.63120.qm@web33404.mail.mud.yahoo.com> References: <552799.63120.qm@web33404.mail.mud.yahoo.com> Message-ID: Prashant Saxena wrote: > import sys > > class Float(float): > """ > Custom float datatype with addtional attributes. > """ > > def __new__(self, > value=0.0, #default value > name='', # string > & nbsp; range=(0.0, 1.0) # tuple > ) > > try: > self.name = name > self.range = range > self.pos = (1, 1) > return float.__new__(self, value) > except: > print ('Invalid value : Float = %s %s' % (str(value), > sys.exc_info()[:2])) > > > def setpos(self, value): > self.pos = value > def getpos(self): > return self.pos*2.0 > p = property(getpos, setpos) > > myFloat = Float(0.23) > print myFloat.pos > > I am trying to create a custom 'float' datatype by subtyping default > 'float'. There are few things I would like to know here: > > 1. How to make 'name' & 'range' only readable attributes. A property with a working get and set that raises an exception. > 2. The property 'p' is not working as it has to. What's wrong here? Don't know. > 3. I would be heavily instancing this class, and I won't be creating any > new attribute on instance. Is there any way to optimize? __slots__? I believe this is what slots is for. From samwyse at gmail.com Thu Jul 10 14:46:31 2008 From: samwyse at gmail.com (samwyse) Date: Thu, 10 Jul 2008 11:46:31 -0700 (PDT) Subject: Loading just in time References: Message-ID: On Jul 10, 9:45?am, "D'Arcy J.M. Cain" wrote: > I am trying to create a utility module that only loads functions when > they are first called rather than loading everything. ?I have a bunch > of files in my utility directory with individual methods and for each I > have lines like this in __init__.py: > > def calc_tax(*arg, **name): > ? ? from calc_tax import calc_tax as _func_ > ? ? calc_tax = _func_ > ? ? return _func_(*arg, **name) This doesn't do what you think. The line "calc_tax = _func_" is probably modifying a local variable that is then thrown away. I've got a slightly different (simpler) version to illustrate: === main.py === def calc_tax(*arg, **name): from calc_tax import calc_tax as _func_ #global calc_tax calc_tax = _func_ print '_func_ is', repr(_func_) print 'calc_tax is', repr(calc_tax) return _func_(*arg, **name) print 'before: calc_tax is', repr(calc_tax) result = calc_tax() print 'after: calc_tax is', repr(calc_tax) === calc_tax.py === def calc_tax(*arg, **name): return 42 === end of files === Running main.py gives this: before: calc_tax is _func_ is calc_tax is after: calc_tax is Note that the value of calc_test is the same in the first and last lines. If you uncomment the line "#global calc_tax" and run it again, you get this: before: calc_tax is _func_ is calc_tax is after: calc_tax is Interestingly, neither version gives me a TypeError, no matter how many times I call calc_tax. (BTW, you might want to look up Memoization; it's very similar to what you want to do, and might give you a way to more efficiently code things.) From arkanes at gmail.com Thu Jul 31 13:39:50 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 31 Jul 2008 12:39:50 -0500 Subject: Function References In-Reply-To: References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> <6fe0scFaus40U1@mid.uni-berlin.de> <6bc8bc07-eab0-4303-b8a4-c9470f96038d@c65g2000hsa.googlegroups.com> <6fe1n2Faus40U3@mid.uni-berlin.de> Message-ID: <4866bea60807311039h7f8d62bcv31b8299bb100a264@mail.gmail.com> On Thu, Jul 31, 2008 at 10:27 AM, squishywaffle at gmail.com wrote: > On Jul 31, 10:47 am, "Diez B. Roggisch" wrote: >> I take the freedom to do so as I see fit - this is usenet... > > Fine, then keep beating a dead horse by replying to this thread with > things that do nobody any good. It seems like there are a lot better > way to waste time, though. > > The Python/C API can get me back further without reliance on third- > party libraries than ctypes. It also isn't subject to the quirks that > ctypes is on platforms other than Windows (the target application runs > on Windows, Mac, and eventually Linux once the original distributor > has drivers for the device). I'm not even sure ctypes could load the > lib/driver the distributor packaged. > Ctypes works fine on many platforms. Since you didn't even know about ctypes until you were told about it, don't you think it's a little premature to be speculating about problems you haven't actually experienced? > So really, I appreciate the option in ctypes, it's good stuff. But > it's not for this project. > It's actually perfectly suited, but you're (I'm assuming) and adult and can make your own decisions... > Once again, the original question stands for anyone who has experience > with the Python/C API callbacks. > -- If you know how to write a callback in C, you know how to do it with Python/C. It's not real flexible if the callback API you're using doesn't include user data, and it looks like it doesn't. Ctypes can generate dynamic thunks and therefore will let you use any Python object as a callback. It's a lot more flexible and it's a lot easier to not write your own thunk generation in C. From HeinTest at web.de Thu Jul 10 10:55:00 2008 From: HeinTest at web.de (=?ISO-8859-1?Q?Hans_M=FCller?=) Date: Thu, 10 Jul 2008 16:55:00 +0200 Subject: Smal question Message-ID: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> Hello group, I have some scripts sharing some common functions. So what I'd like to have is a modern include. Of course python does not have (with good reasons) no include statement. But I'm too lazy to create a module which has to be installed into the interpreter for some functions I need to share in a project. Is there any idea to do this ? Thanks a lot Hans From sukkopera at gmail.com Mon Jul 14 05:41:23 2008 From: sukkopera at gmail.com (sukkopera at gmail.com) Date: Mon, 14 Jul 2008 02:41:23 -0700 (PDT) Subject: subprocess module References: <2e7f0504-cc1c-4cb6-b2d0-b67b004eca7d@x41g2000hsb.googlegroups.com> Message-ID: <88a36645-851d-4c72-9095-796dfe1d94c9@k30g2000hse.googlegroups.com> On 14 Lug, 10:34, Peter Otten <__pete... at web.de> wrote: > John Mechaniks wrote: > > from subprocess import call > > call(['ls', '-l']) > > > How do I get the result (not the exit status of the command) of "ls - > > l" into a variable? > > output = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE).stdout.read() > > Peter Correct, but I would rather use Python's os.listdir() and/or os.stat(). Executing a simple ls running a subprocess is overkill. From larry.bates at websafe.com` Sun Jul 13 10:26:02 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 13 Jul 2008 09:26:02 -0500 Subject: About wmi In-Reply-To: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> Message-ID: <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> patrol wrote: > I want to prevent some process from running. The code is in the > following. I encounter some unexpected troubles. > Probelm1: This program cannot terminate "scrcons.exe" and > "FNPLicensingService.exe",which are system processes. > Problem2:After a while, this program will abort by error > File "C:\Python25\lib\wmi.py", line 397, in __call__ > handle_com_error (error_info) > File "C:\Python25\lib\wmi.py", line 190, in handle_com_error raise > x_wmi, "\n".join (exception_string) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > 14: ordinal not in range(128) > > > ---------------------------------------------------- > code---------------------------------------------------------------------------------- > # -*- coding:utf-8 -*- > import pythoncom > import wmi > import threading > import time > from xml.dom.minidom import parse, parseString > > class Info (threading.Thread): > def __init__ (self): > threading.Thread.__init__ (self) > def run (self): > print 'In Another Thread...' > pythoncom.CoInitialize () > dom1 = parse('processTerminateList.xml') > config_element = dom1.getElementsByTagName("processTerminateList") > [0] > servers = config_element.getElementsByTagName("processName") > try: > c = wmi.WMI () > for process in c.Win32_Process (): > for server in servers: > if process.name == getText(server.childNodes): > process.Terminate() > print process.name > process_watcher = c.Win32_Process.watch_for("creation") > while True: > new_process = process_watcher() > name = new_process.Caption > print name > for server in servers: > if name == getText(server.childNodes): > new_process.Terminate() > finally: > pythoncom.CoUninitialize () > def getText(nodelist): > rc = "" > for node in nodelist: > if node.nodeType == node.TEXT_NODE: > rc = rc + node.data > return rc > > if __name__ == '__main__': > Info().start() > ------------------------------------------------------ > processTerminateList.xml----------------------------------------------------------------------- > > > scrcons.exe > TXPlatform.exe > mdm.exe > FNPLicensingService.exe > notepad.exe > uedit32.exe > You should probably post this to comp.python.windows. Tim Golden (author of WMI interface) monitors that list religously (thanks Tim). -Larry From info at egenix.com Mon Jul 21 09:25:40 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Mon, 21 Jul 2008 15:25:40 +0200 Subject: ANN: eGenix EuroPython 2008 Presentations & Videos Message-ID: <48848E54.70408@egenix.com> ________________________________________________________________________ eGenix EuroPython 2008 Presentations & Videos ________________________________________________________________________ We have uploaded our EuroPython 2008 presentations to our website. Learn the concepts behind the Python DB-API and how to design large-scale applications. This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/EuroPython-2008-Presentations.html ________________________________________________________________________ INTRODUCTION The EuroPython Conference is the one of the premier conferences for Python & Zope users and developers. This year it was being held from the 7th to 9th July in Vilnius, Lithuania. eGenix was one of the founding members of the EuroPython conference team and played a major role in organizing the first EuroPython conference in the year 2002. Since then we have attended every EuroPython conference to meet up face-to-face with the people from the Python & Zope communities and have given regular talks at these conferences. ________________________________________________________________________ TALKS AT EUROPYTHON 2008 We gave the following two talks at the conference. The presentations are available for viewing and download from our Presentations and Talks section: http://www.egenix.com/library/presentations/ As special feature, we have added talk videos in addition to providing the slide PDFs. You can view the talks online if you have the Adobe Flash Player 8 or later installed. * Using the Python Database API The Python Database API (DB-API) is a specification of a module interface that allows interfacing from Python to a relational database. The talk gives a high-level introduction to the concepts used in the Python DB-API and relational databases in general. Connection, cursors and transactions are discussed, and their use in Python database applications is explained. * Designing Large-Scale Applications in Python Python is widely and somewhat inaccurately referred to as a scripting language. While Python is an ideal platform for small scripting tasks, it does in fact cover all the concepts needed for large scale object oriented application development. However, complex applications bring different challenges. This talk draws on eGenix' many years experience with large scale application development using Python as central implementation language and provides a cookbook approach to many of the the problems you face when designing and organizing complex application frameworks. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 21 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From robert.kern at gmail.com Mon Jul 21 19:48:21 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 21 Jul 2008 18:48:21 -0500 Subject: scanf in python In-Reply-To: <4884be5e$0$19722$426a74cc@news.free.fr> References: <4884be5e$0$19722$426a74cc@news.free.fr> Message-ID: AMD wrote: > Hello, > > I often need to parse strings which contain a mix of characters, > integers and floats, the C-language scanf function is very practical for > this purpose. > I've been looking for such a feature and I have been quite surprised to > find that it has been discussed as far back as 2001 but never > implemented. The second Google hit is a pure Python implementation of scanf. http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From waldemar.rymarkiewicz at gmail.com Tue Jul 29 06:05:14 2008 From: waldemar.rymarkiewicz at gmail.com (waldek) Date: Tue, 29 Jul 2008 03:05:14 -0700 (PDT) Subject: ctypes and how to copy data passed to callback References: <2059b8a4-7651-4c3c-afbf-44caa8605c64@m3g2000hsc.googlegroups.com> <6f61s7Fa0pq9U1@mid.individual.net> Message-ID: On Jul 28, 4:03 pm, Thomas Heller wrote: > waldek schrieb: > > > > > Hi, > > > I'm trying to handle data passed to Py Callback which is called from > > C dll. Callback passes data to another thread using Queue module and > > there the data are printed out. > > > If data is printed out in a callback itself it's ok. If I put on > > queue and next get from queue in another thread script prints some > > trash. Looks like the data is released when callback returned. I tired > > to make d = copy.deepcopy(data), but it does not work - I got nothing. > > Any idea why it's happening ? > > > --------------------- main thread -------- > > def callback(data, size): > > myqueue.put((data, size)) > > > mydll = cdll.MyDLL > > cbproto = CFUNCTYPE(c_int, POINTER(c_char), c_int) > > mycallback = cbproto(callback) > > > mydll.RegisterCallback(mycallback) > > > ---------------------------------- thread listener > > ---------------------- > > > while True: > > data, size = myqueue.get() > > print "***", data[:size] > > > ------------------------------------------------------------------------------ > > I guess your code would work if you change it in this way: > > > def callback(data, size): > > myqueue.put(data[:size]) > > while True: > > data = myqueue.get() > > print "***", data > > Thomas Both solutions work fine. The secon is nicer :) Thanks From wuwei23 at gmail.com Wed Jul 30 00:32:30 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 29 Jul 2008 21:32:30 -0700 (PDT) Subject: Native Code vs. Python code for modules References: Message-ID: On Jul 30, 1:56?pm, koblas wrote: > Ruby has been getting pummeled for the last year or more on the > performance subject. ?They've been working hard at improving it. ?From > my arm chair perspective Python is sitting on it's laurels and not > taking this as seriously as it probably should. Well, the snarky response is most Python developers are too busy working on actual real world projects :) A more measured response would be that it's so easy to integrate Python with C that most developers would prefer to profile their own code and implement bottleneck code in C where appropriate. >?In general it's > possible to make many comments that swirl around religion and > approach, one of the things that I've noticed is that wile Python has > a much more disciplined developer community they're not using this for > the greater good. I guess it all depends on what you define by "greater good". If you mean "faster performance", then maybe not, although it definitely seems to be -one- aspect being addressed by the PyPy project, at least. For me, "greater good" == "makes my life as a developer easier", and from that definition I've nothing but admiration for the community as a whole. > This got me to think, why does python have "pickle" and "cPickle"? Because sometimes you want something to be fast, but other times you want a pure Python version that's easy to extend. > To that end why would somebody write big try catch blocks to see if > modules exist and if they exist alias their names. Because it's the established approach, they're run through once during importing, and it doesn't require modifying the language to achieve it. >?Wouldn't it be > better if there was a way that if I have an "interface compatible" > native (aka C) module that has better performance that there could be > a way that python would give it preference. Shouldn't that -always- be decided by the developer? I don't want to rely on magic behaviour based on what is installed in the runtime environment by an end user... > ? import random(version=1.2, lang=c) > or > ? import random(version=1.2, lang=py) I don't see the gain over sticking with an established convention, like pickle and cPickle. > ? import random ? ? # ?use the latest version in the "fastest" code (C > given preference) I personally have a preference for predictable behaviour over idealised optimisation. All of this, of course, is personal preference; please don't take me for a jihadi :) - alex23 From tjreedy at udel.edu Fri Jul 18 22:12:45 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Jul 2008 22:12:45 -0400 Subject: Change in Decimal repr in Python 2.6 In-Reply-To: References: Message-ID: Karen Tracey wrote: > I noticed when trying out Python's 2.6b2 release that the repr of > Decimal has changed since 2.5. On 2.5: > > Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import decimal > >>> decimal.Decimal(7) > Decimal("7") > >>> > > double quotes were used whereas on 2.6b2: > > Python 2.6b2 (r26b2:65082, Jul 18 2008, 13:36:54) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import decimal > >>> decimal.Decimal(7) > Decimal('7') > >>> > > single quotes are used. Searching around I see this was done in r60773 > with the log message: > > Fix decimal repr which should have used single quotes like other reprs. > > but I can't find any discussion other than that. > > My problem is this breaks a bunch of doctests that were written assuming > the prior repr. I can't just update the tests to assume the new single > quotes because they are for code that is supposed to run on everything > back to Python 2.3. > > So my question: > > Is this backwards-incompatible change really necessary and could it be > reconsidered? > If it's here to stay, is there some straightforward why that I am > unaware of to construct tests that use Decimal repr but will work > correctly on Python 2.3-2.6? > > Also, if this is not the right list for this question please let me know > where would be more appropriate and I will go there. If answers here do not satisfy, the pydev list would be the place to request that this change be put off until 3.0, when changes that break are more permissible. I do not remember any discussion of this issue. You can also post there via news.gmane.org/g.c.python.devel (the mail to news gateway). From wuwei23 at gmail.com Thu Jul 24 12:34:37 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 24 Jul 2008 09:34:37 -0700 (PDT) Subject: New to Python, familiar with Perl - Seeking info sources References: <18c8fc73-8ff9-4640-a020-de0be4b76ca4@z72g2000hsb.googlegroups.com> Message-ID: <8397b80b-80d5-4470-9605-1c0340cf1c53@r35g2000prm.googlegroups.com> On Jul 24, 11:53 pm, Brett Ritter wrote: > My question is: What are the best sources to learn best practices or > Are there any good sources to tell me > what Perl habits are good/bad in the Python paradigm? I've never used Perl myself, so I can't comment on the quality, but this document was recommended earlier this week: http://wiki.python.org/moin/PerlPhrasebook > What about > common packages that will change my life? (I do a lot of web work, > but also a lot of DB reporting) If you're not anti-ORM, I highly recommend checking out SQLAlchemy. It's not part of the standard lib, but it's an amazing tool: http://www.sqlalchemy.org/ > The (occasionally complete) Perl > Advent calendars have proven to be a good source to learn about > helpful modules that I might not otherwise stumble across. You might appreciate Doug Hellman's Python Module of the Week blog: http://www.doughellmann.com/projects/PyMOTW/ > (I've encountered Django, but I'm getting my fill of "frameworks" from > Java for the moment, so I'm looking for lightweight pieces at the > moment) The Web Services Gateway Interface (WSGI) was designed to promote the building of web applications using interchangeable middleware. It's definitely worth having an understanding of if you plan on developing web apps in Python: http://www.wsgi.org/wsgi/ If you're wanting to avoid the larger frameworks, check out CherryPy, it's a thing of beauty: http://www.cherrypy.org/ From hackingkk at gmail.com Mon Jul 21 01:58:40 2008 From: hackingkk at gmail.com (Krishnakant Mane) Date: Mon, 21 Jul 2008 11:28:40 +0530 Subject: Python Written in C? In-Reply-To: References: Message-ID: <8d3752f20807202258w2a4167e4hd40b56b12c0c74fc@mail.gmail.com> On 21/07/2008, giveitawhril2008 at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > Are you a PH.d researcher In the first place why do you want to make an issue of "what an x language is compiled in " and if that' is what you are researching in, then sorry to say you don't seam to have a mindset needed for researcher. > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > First off all c# is absolute rubbish waist of time. if I need to learn it then I better lern java or pythonfor that matter. and by the way what is a "real programmer?" I never knew that there are robots who program vertually and a "real programmer ". What do you think I am a spam bot who is writing a "vertual program " every day? first give me your defination for real programmer. > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > what! no one is using c? I want to know what people use to write device drivers? I am such a fool I really never new that people use c# to create device drivers for hardware and for creating firmware. I admit my stupidity that I never knew that c# is "real programming language ". and what is "your programming language?"python is a free and open source programming language and does not belong to one person. > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. My request and strong recommendation to you is "don't learn python, because you don't deserve to. " I am not saying for dissing you, i know you are "real programmer ". but you seam to have a typical mindset which the rubbish microsoft has inculcated in many programmers, aa sorry "real programmers " line you. I don't think there is any point saying "vvb kind of " some thing is great and python is rubbish. every language has its value and vb is not a language in the first place. python is made with a view that it is usefull for all purposes and it has been so far successful and I don't really care why it is done in c as long as it does the work. happy hacking. Krishnakant. > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Fri Jul 25 10:51:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 16:51:42 +0200 Subject: Execution speed question In-Reply-To: <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> Message-ID: Iain King wrote: > I think (2)'s poor performance is being amplified by how python > handles lists and list deletions; the effect may be stymied in other > languages Delete is O(n) (or "O(n/2) on average", if you prefer), while append is amortized O(1). Unless I'm missing something, your example keeps going until it's flagged *all* nodes as "on", which, obviously, kills performance for the first version as the probability goes down. The OP's question was about a single pass (but he did mention "as the simulation progresses", so I guess it's fair to test a complete simulation.) Btw, if the nodes can be enumerated, I'd probably do something like: node_list = ... get list of nodes ... random.shuffle(node_list) start = 0 end = len(node_list) step = end / MAX while start < end: for i in xrange(start, start + step): ... switch on node_list[i] ... ... do whatever you want to do after a step ... # prepare for next simulation step start += step step = max((len(node_list) - start) / MAX, 1) which is near O(n) overall, and mostly constant wrt. the probability for each pass (where the probability is 1:MAX). Might need some tuning; tweak as necessary. From JordanNealBerg at gmail.com Thu Jul 10 04:47:54 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Thu, 10 Jul 2008 01:47:54 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: Message-ID: <48435624-6422-4d27-be4f-476b3b949ecb@c58g2000hsc.googlegroups.com> Well, I have figured out something that works: def findit(u): u += 0xe91aaa35 u1 = ~(0xffffffff - u) ^ u >> 16 u1 += ((u1 << 8) & 0xffffffff) u1 ^= (u1 & 0xffffffff) >> 4 b = (u1 >> 8) & 0x1ff a = (u1 + (u1 << 2) & 0xffffffff) >> 19 r = int(a) ^ hash_adjust[int(b)] return r I feel like this cannot possibly be the best way of doing this, but it does work!!!! haha If anyone would care to share a more elegant solution, that would be great :) From amheiserbush at yahoo.com.au Thu Jul 31 17:09:12 2008 From: amheiserbush at yahoo.com.au (James Calivar) Date: Thu, 31 Jul 2008 14:09:12 -0700 (PDT) Subject: Newbie having issues with threads Message-ID: <6f262ce0-0b03-4891-9d43-f83398500e5d@a2g2000prm.googlegroups.com> I'm a newbie trying to write a script that uses threads. I'm right now a little bit stuck in understanding why the code snippet I wrote doesn't seem to be entering the function defined in the start_new_thread() call. If I run it as is (the threaded version), the output is: UA_1 configuring... UA_1 halting.. But if I comment out the line w/ the thread and just call the function directly, everything seems to work OK: UA_1 configuring... UA_1 executing... UA_1 halting... Can anyone tell me why the thread doesn't seem to invoke the function "execute()"? I'm running Python 2.4.3. Here is my code: =========== import thread class Test(object): def __init__(self, instanceID): self.instanceID = instanceID def configure(self): print self.instanceID + " configuring..." def execute(self): print self.instanceID + " executing..." def halt(self): print self.instanceID + " halting..." if __name__ == "__main__": """usage: sipp_auto [options]""" ua1 = Test("UA_1") ua1.configure() #ua1.execute() thread.start_new_thread(ua1.execute, ()) ua1.halt() =========== Thanks, James From mal at egenix.com Fri Jul 18 11:48:19 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 18 Jul 2008 17:48:19 +0200 Subject: Converting from local -> UTC In-Reply-To: <_L2dnRlm9sNmkB3VnZ2dnUVZ_j2dnZ2d@earthlink.com> References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> <41d4ffc7-7fd5-4202-92ea-132c7d4f5cd4@s50g2000hsb.googlegroups.com> <_L2dnRlm9sNmkB3VnZ2dnUVZ_j2dnZ2d@earthlink.com> Message-ID: <4880BB43.4050209@egenix.com> On 2008-07-18 05:28, Dennis Lee Bieber wrote: > On Thu, 17 Jul 2008 20:26:11 -0300, "Gabriel Genellina" > declaimed the following in comp.lang.python: > > >> Note that I used %s everywhere (it's just a placeholder, not a format) and > > > > Unfortunately, in the case of MySQLdb... It is both -- maybe that > will change once MySQLdb gives up compatibility with MySQL 4.x by > incorporating usage of prepared statements in place of a Python % > interpolation. > > It has to be %s as the adapter first converts to string, escapes, > and quotes the arguments; regardless of native datatype they are strings > when put into the SQL statement... If you prefer a different parameter style, you could use mxODBC and the MySQL ODBC drivers. You'd then write: query = "INSERT INTO image VALUES(?, ?, ?, ?)" and avoid any confusion due to the parameter style looking a lot like the Python string formatting markers (for obvious reasons, since that's what the MySQLdb module uses internally). -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 18 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From ggpolo at gmail.com Sat Jul 12 17:52:56 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sat, 12 Jul 2008 18:52:56 -0300 Subject: Why is there no GUI-tools like this for Windows? In-Reply-To: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> References: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> Message-ID: On Sat, Jul 12, 2008 at 6:35 PM, maestro wrote: > http://www.youtube.com/watch?v=PXpwC1o5AcI > > I have done some GUI-programming for windows with Python but the > Tkinter interface sucked and while it is the only one I tried I got > the impression they are all the same. > > It's amazing how retarded a lot of the stuff programmers do is. > Watcing that video, that is how it should be. > > I can just do the layout with my mouse and then there is a program > that writes the code for me. There are several programs that allow you to that, there is one not really nice for tkinter, GUI Builder, there are glade and gazpacho for gtk, Qt Designer for qt, wxglade and xrc (and others) for wxwidgets. There are probably others for each of the toolkits I described on the previous sentence, but those are the most well known (or not known at all in case of GUI Builder for tkinter). > GUI-programming is hard for no reason. One good program then forever > easy... > > Is there not something like this for Python/Windows? Is the Linux one > only for ruby or for any language? All the examples I mentioned previously works both in Linux and Windows. Also, they tend to not be language dependent either, they tend to save the user interface description to some format like XML, which you can then use independently of language (as long as your language has a lib for reading its format and doing proper processing). > > Oh well im switching to Linux anyway and mostly write webapps but > still... > -- > http://mail.python.org/mailman/listinfo/python-list > Note: I didn't watch the video, if it presents something totally unrelated to my answer, my bad then. -- -- Guilherme H. Polo Goncalves From Graham.Dumpleton at gmail.com Wed Jul 23 09:18:27 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Wed, 23 Jul 2008 06:18:27 -0700 (PDT) Subject: Problem with Python Server Pages (PSP) References: <9766b993-03e6-4b75-92a2-06244c41e51c@a1g2000hsb.googlegroups.com> <8ce2ffdd-0fb3-4f5f-bde8-1598f9b231bc@i20g2000prf.googlegroups.com> Message-ID: <53b1f015-edc8-4225-aeab-1082e07c57c3@j33g2000pri.googlegroups.com> On Jul 22, 1:54?pm, barun.sah... at gmail.com wrote: > On Jul 22, 5:18?am, Graham Dumpleton > wrote: > > > > > On Jul 21, 9:42?pm, barun.sah... at gmail.com wrote: > > > > Hi, > > > > I am facing a very basic problem with PSP. I have installedmod_python > > > (in fedora Core 1), added the lines required for loading Python > > > modules and handling PSP pages. I have created a hello.psp page. But > > > when I try to view this hello.psp page, all Python code are getting > > > displayed. > > > > The said page is stored at /var/www/html/psp/hello.psp. I guess this > > > is some configuration problem with Apache, but not able to figure out > > > the exact problem. I have tried putting those configuration lines for > > > psp in both httpd.conf and python.conf files. But still it is not > > > working. > > > > The Python module (mod_python) is getting loaded. Because when I > > > telnet to my server, I can find that in the headers. > > > > These are the versions of the softwares: > > > Apache: 2.0.47 > > > Python: 2.2.3mod_python: 3.0.3 > > > > Thnaks for all your suggestions. > > > What is the Apache configuration snippet you are using to enable > >mod_pythonand PSP file handling? > > > Graham- Hide quoted text - > > > - Show quoted text - > > Hi Graham, > > The configuration used in httpd.conf file looks like: > > ? ? AddHandler .psp .psp_ > ? ? PythonHandler modules/python > ? ? PythonDebug On > Go read the documentation properly. http://www.modpython.org/live/current/doc-html/hand-psp.html What is PythonHandler set to? Graham From sconnoll at lowes.com Fri Jul 18 15:14:47 2008 From: sconnoll at lowes.com (sconnoll at lowes.com) Date: Fri, 18 Jul 2008 12:14:47 -0700 (PDT) Subject: bsddb - help needed with btflags values for Python Message-ID: import bsddb bsddb.btopen(file, flag='c', mode=438, btflags=0, cachesize=None, maxkeypage=None, minkeypage=None, pgsize=None, lorder=None) Can anyone help me with the values to use for btflags? I'd like to tell the database manager that I want to allow duplicate values. The ORACLE Berkeley documentation addresses C (not Python), so I can't find the approprate btflags values documented for Python anywhere. Help!!!!......and thanks in advance. Sean From jmcmonagle at velseis.com.au Wed Jul 2 04:33:25 2008 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Wed, 02 Jul 2008 18:33:25 +1000 Subject: Problem with a for loop and a list In-Reply-To: <18232528.post@talk.nabble.com> References: <18232298.post@talk.nabble.com> <18232528.post@talk.nabble.com> Message-ID: <486B3D55.4070109@velseis.com.au> Alexnb wrote: > well okay, so what can I do? > > > Firstly, stop top posting. Replies to a thread "flow" better if bottom posted. Secondly, it sounds like you want to build a list of the results from your entry.get() calls. Try this: self.wordList = [] def getWords(self): for entry in self.listBuffer: self.wordList.append(entry.get()) print self.wordList From alexnbryan at gmail.com Tue Jul 15 11:39:31 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 15 Jul 2008 08:39:31 -0700 (PDT) Subject: Testing for Internet Connection In-Reply-To: <87bq0z8lym.fsf@benfinney.id.au> References: <18460572.post@talk.nabble.com> <87bq0z8lym.fsf@benfinney.id.au> Message-ID: <18468350.post@talk.nabble.com> Ben Finney-2 wrote: > > Alexnb writes: > >> I am wondering, is there a simple way to test for Internet >> connection? If not, what is the hard way :p > > Refine the question: What do you mean by "internet"? It isn't a single > entity. > > Do you mean "some particular internet host responding on a particular > network port"? > > If you can define exactly what you mean by "internet connection", the > test for it becomes correspondingly easier. > > -- > \ ?Why should I care about posterity? What's posterity ever done | > `\ for me?? ?Groucho Marx | > _o__) | > Ben Finney > -- > http://mail.python.org/mailman/listinfo/python-list > Well, really I just need to figure out if I am able to connect to one site. That site is dictionary.com. -- View this message in context: http://www.nabble.com/Testing-for-Internet-Connection-tp18460572p18468350.html Sent from the Python - python-list mailing list archive at Nabble.com. From piet at cs.uu.nl Thu Jul 10 16:50:06 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 10 Jul 2008 22:50:06 +0200 Subject: Terminate a python script from linux shell / bash script References: Message-ID: >>>>> Gros Bedo (GB) wrote: >GB> Yes I've seen that each python script calls its own instance of >GB> Python. But how to know which is the good one in bash ? Is there a >GB> command that gets the parameters of process, so I could use grep to >GB> select the one containing the name of my script ? The ps command will usually give you a list of the running processes with their argument, but using that is suboptimal. I suppose you start the process in the background, like: python myscript &. When you start the python script in bash (or any other process for that matter) in the background you can get the process id (pid) with $! (immediately after starting the process). Later on you can use this to kill the process: python myscript myargs & savepid=$! later: kill $savepid That is much better than trying to grep through the ps output. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From tjreedy at udel.edu Tue Jul 15 16:48:16 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Jul 2008 16:48:16 -0400 Subject: Python internals In-Reply-To: <008ca729$0$20313$c3e8da3@news.astraweb.com> References: <008ca729$0$20313$c3e8da3@news.astraweb.com> Message-ID: Peter Anderson wrote: > Hi! I am slowly teaching myself Python. I was reading David Beazley's > excellent book "Python - Essential Reference"; in particular about > variables. Let me quote: > > "Python is a dynamically typed language in which names can represent > values of different types during the execution of a program. In fact the > names used in the program are really just labels for various quantities > and objects. The assignment operator simply creates an association > between a name and a value. This is different from C, for example, in > which a name (variable) represents a fixed size and location in memory..." > > As an old mainframe programmer, I understand the way C does things with > variable but this text got me wondering how Python handles this > "association" between variable name and value at the lower level. Is it > like a fifo list? No. Names are associated with (references to) objects in a namespace. The details are implementation specific. For CPython, the references are addresses stored in an array. If the set of names is dynamic, names are converted to indexes by hashing during execution and the array of references is expanded before it gets full. If the set of names is static, as is usual for the local namespace of functions, an optimization converts the names to indexes (in a constant length array) during compilation. (On function startup, slots corresponding to non-parameter local vars are, I expect, initialized to invalid reference values to detect 'use before assignment' bugs.) Terry Jan Reedy From phillip.oldham at gmail.com Wed Jul 16 12:43:45 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Wed, 16 Jul 2008 09:43:45 -0700 (PDT) Subject: Framework recommendations for web service? Message-ID: We're looking at the next phase of development for our webapp, and the main focus will be to move the core from the app to a web service so other systems can use the data we've gathered (we're thinking along the lines of the XML API of Highrise from 37Signals). Its possible that we'll extend the service to allow access via vanilla XML, JSON, and YAML at some point, however we've decided to use Facebook's Thrift for connectivity initially to support as many techs as possible and also because our web interface for the app is written in PHP. As we're extracting the core we'll be translating it to Python to make use of the wealth of well-structured libraries and hopefully make the project shorter. However, we've hit a snag in choosing a framework around which to rebuild the service. It seems the more popular frameworks (django, turbogears) are all focused on providing web content. Since our core will be using thrift to communicate, we don't need templating, feeds, admin pages (django), or ajax (turbogears). What we *do* need is a lightweight, simple framework that will allow us to create a RESTful interface and throw code together fast. We'll probably go with SQLObject (unless we can extract the ORM from django - lazy evaluation would be very useful), and we're just looking for something fast and light to sit between that and the thrift interfaces we'll create. So, can anyone suggest a lightweight python framework which just does the essentials? From python at rcn.com Fri Jul 4 00:40:27 2008 From: python at rcn.com (Raymond Hettinger) Date: Thu, 3 Jul 2008 21:40:27 -0700 (PDT) Subject: Nested generator caveat References: Message-ID: <6cfa41bf-9eb8-414f-976d-f5bcd70d6f64@u12g2000prd.googlegroups.com> On Jul 3, 9:20?pm, "Dieter Maurer" wrote: > The apparent reason is that the free variables in > nested generator definitions are not bound (to a value) at invocation > time but only at access time. That's what it is supposed to do. Welcome to a dynamic language. Raymond From Graham.Dumpleton at gmail.com Fri Jul 18 09:17:00 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Fri, 18 Jul 2008 06:17:00 -0700 (PDT) Subject: https in pylons References: Message-ID: <75acf330-16d5-4130-8a2c-0dba39478cb7@u36g2000pro.googlegroups.com> On Jul 18, 9:50?pm, sni... at gmail.com wrote: > Hello, > > I have a question about framework pylons - how to run(in paster) > webpages over https? Is it possible, or not? If Paste server that is uses doesn't already support HTTPS, then run Pylons under Apache/mod_wsgi, or just run Pylons with Paste server behind Apache/mod_proxy. In other words, use Apache to handle the HTTPS side of things. Graham From deets at nospam.web.de Mon Jul 28 04:53:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 10:53:31 +0200 Subject: Callback Python procedure from Delphi DLL References: Message-ID: <6f5fqcF9vgcaU1@mid.uni-berlin.de> durumdara at gmail.com wrote: > Hi! > > I have a component, and a tool in Delphi. > I wanna call it from Python. > > I can implement all things I need into a Delphi generated DLL. > It is ok, I can use this DLL from Python, but the DLL procedure needs a > callback procedure to return the partially output, and needs a python > passed variable to check terminate/abort signal. > > For example: > procedure ProcessFiles(InputFiles : string; CallBackProc: > ????????????????????????); export; > begin > .... > CallBackProc(ProcessedFiles, Percentage, NeedToAbort); > if NeedToAbort then Exit; > .... > end; > > > def CallBackProc(ProcessedFiles, Percentage, NeedToAbort): > ... > > But I don't know, how to call back this procedure, and how to pass > variables. > > The other way is a ActiveX. > This time I don't load the DLL, I only construct the Delphi based Com > Object, and I start the process. > > But in this way I also don't know how to implement the callback, because > the main code uses callback events, and I need to use too... > > Thanks for every usable help! ctypes allows to create callbacks. See the module-docs. Diez From Scott.Daniels at Acm.Org Thu Jul 10 23:24:38 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 10 Jul 2008 20:24:38 -0700 Subject: Loading just in time In-Reply-To: References: Message-ID: <0PmdnTvMhPidTevVnZ2dnUVZ_uLinZ2d@pdx.net> D'Arcy J.M. Cain wrote: > I am trying to create a utility module that only loads functions when > they are first called rather than loading everything. I have a bunch > of files in my utility directory with individual methods and for each I > have lines like this in __init__.py: > > def calc_tax(*arg, **name): > from calc_tax import calc_tax as _func_ > calc_tax = _func_ > return _func_(*arg, **name) > ... Well, you may well be "mired in premature optimization," but you _could_ do the following (you'll need to evaluate whether it addresses your issues). def calc_tax(*arg, **kwargs): from calc_tax import calc_tax globals()['calc_tax'] = calc_tax return calc_tax(*arg, **kwargs) But if you are terrifyingly clever, (or have enough motive*), you can define a function, '_remote', So that your __init__.py contains: ... _remote('some_tax') _remote('other', 'frogs') ... * The pythonic "enough motive" is how redundant your "__init__.py" looks. The "DRY" (Don't Repeat Yourself) principle comes into effect. The more your source looks like boilerplate, the more you should itch to replace the boilerplate. --Scott David Daniels Scott.Daniels at Acm.Org From rtw at freenet.co.uk Sat Jul 26 11:29:18 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 26 Jul 2008 10:29:18 -0500 Subject: Questions on 64 bit versions of Python References: <488aec52$0$21481$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote in news:488aec52$0$21481$9b622d9e at news.freenet.de in comp.lang.python: >> The end result of that is on a 32-bit machine IronPython runs in a >> 32-bit process and on a 64-bit machine it runs in a 64-bit process. > > > That's probably not exactly true (although I haven't checked). > > When you start a .NET .exe program, the operating system needs to > decide whether to create a 32-bit or a 64-bit process (assuming the > processor supports 64-bit mode). > > The Microsoft .NET commercial framework uses the PE architecture of the Whats the "Commercial framework" ? I've only come accross 3, the standard 32 bit one and 2 64 bit variants. > executable to make that decision (or, rather, it doesn't decide at all, > but the underlying OS decides). The C# compiler (more specifically, the > assembly linker) offers a choice of setting the .NET architecture to > Itanium, AMD64, x86, or "any"; people use typically "any". This "any" > choice is implemented by setting the PE architecture to "any", and then > indicating to the .NET run-time that any other architecture would be > fine as well. > > As a consequence, an architecture-any executable launches as a 32-bit > process on a 64-bit system. I just tested, I built a default C# forms app using the "AnyCPU" option and it ran as a 64 bit app (no *32 in Task Manager), this is on XP64. I have though installed the AMD64 version of the 2.0 framework and AFAICT neither windows update or the Visual Studio installer will install that by default, you have to go get it your self. > To have the executable launch as 64-bit > code, you must tell csc.exe to create an AMD64 binary (say), which > then means that the binary won't launch on a 32-bit system. I haven't > checked, but my guess is that IronPython uses architecture-any > executables (unless you adjust the build process). I just started ipy.exe the 1.1 and 2.0B1, both ran as 64 bit processes IronPython 1.1 (1.1) on .NET 2.0.50727.1433 Copyright (c) Microsoft Corporation. All rights reserved. >>> I don't know what happens if you have both 32 bit and 64 bit versions of the framwork installed (presumably with slightly different minor version numbers) as I uninstalled the 32 bit version before I installed the AMD64 version. Rob. -- http://www.victim-prime.dsl.pipex.com/ From wmcbrine at users.sf.net Wed Jul 30 14:48:28 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Wed, 30 Jul 2008 18:48:28 GMT Subject: like py2exe, but on a mac References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> <341kk.407$aA5.312@trnddc05> Message-ID: <0I2kk.565$rb5.429@trnddc04> On Wed, 30 Jul 2008 16:57:35 +0000, I wrote: > [bundlebuidler] does put in a version-specific #! line, but if I change > that to #!/usr/bin/env python, the app still works, and it seems to me > that it will work for any version of Python on OS 10.4, 10.5, and maybe > 10.3. Then again, I see now that it has more hardwired paths in the "Python" binary. Bah. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From duncan.booth at invalid.invalid Wed Jul 9 17:06:08 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jul 2008 21:06:08 GMT Subject: formatting list -> comma separated (slightly different) References: Message-ID: Michiel Overtoom wrote: > I occasionally have a need for printing lists of items too, but in the > form: "Butter, Cheese, Nuts and Bolts". The last separator is the > word 'and' instead of the comma. The clearest I could come up with in > Python is below. I wonder if there is a more pythonic solution for > this problem. Maybe something recursive? >>> from itertools import chain, repeat >>> def across(*iterables): iterables = map(iter, iterables) while 1: for it in iterables: yield it.next() >>> friends=['Anne','Bob','Chris','Debbie','Eve','Fred'] >>> ''.join(across(friends, chain(repeat(', ', len(friends)-2), [' and ']))) 'Anne, Bob, Chris, Debbie, Eve and Fred' I feel there ought to be an easier way of alternating between iterators but if there is I can't think of it offhand. Also it breaks down unless you have at least two friends. This version is a bit messy but seems to work reliably for any number of friends: >>> for i in range(len(friends)+1): f = friends[:i] print ' and '.join(s for s in [', '.join(f[:-1]), ''.join(f[-1:])] if s) Anne Anne and Bob Anne, Bob and Chris Anne, Bob, Chris and Debbie Anne, Bob, Chris, Debbie and Eve Anne, Bob, Chris, Debbie, Eve and Fred Of course neither works cleanly if you give it an iterator rather than a list. This is a bit longer but does work without knowing the length of the iterator in advance (and you could save a couple of lines by concatenating the adjacent yields): >>> def commaand(it): it = iter(it) yield it.next() n = it.next() for nxt in it: yield ', ' yield n n = nxt yield ' and ' yield n >>> for i in range(len(friends)+1): f = friends[:i] print ''.join(commaand(f)) Anne Anne and Bob Anne, Bob and Chris Anne, Bob, Chris and Debbie Anne, Bob, Chris, Debbie and Eve Anne, Bob, Chris, Debbie, Eve and Fred From bignose+hates-spam at benfinney.id.au Thu Jul 3 21:27:28 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 04 Jul 2008 11:27:28 +1000 Subject: Copyright issues for an application developed using django, python and mySQL References: <1f23a9fd-33a0-4a06-9733-241c8fd450d2@w4g2000prd.googlegroups.com> Message-ID: <87iqvm30cf.fsf@benfinney.id.au> Nagu writes: > I made a small recommendation engine for our company using python, > django, and mySQL. My supervisor and the senior management are > worried about the copyright and licensing issues. It's good that they're raising these concerns and making sure. > They want to find out the details on how to go about start using it, > like quoting python/django/ mySQL specifically on the bottom of the > web page or some other thing. You should read the licenses for these products (they're not long), and retain a lawyer to give an educated opinion addressing the specific concerns your managers have. > How do I go about addressing the copyright and licensing issues? (I > do not know if licensing is the right word here). Start with finding out exactly what those concerns are, gather the license terms of the works you're using, and consult a copyright lawyer. In parallel, you can read the license texts yourself and understand them to satisfy yourself about what the terms allow and require. However, that understanding is good only for making decisions that affect yourself; for making decisions that affect the company, your managers should get expert legal opinion. > Please advice. Hope that helps. -- \ ?I was gratified to be able to answer promptly and I did. I | `\ said I didn't know.? ?Mark Twain, _Life on the Mississippi_ | _o__) | Ben Finney From mitchell.peabody at gmail.com Wed Jul 16 18:37:00 2008 From: mitchell.peabody at gmail.com (mizhi) Date: Wed, 16 Jul 2008 15:37:00 -0700 (PDT) Subject: For_loops hurt my brain. References: <4874c21f-befa-4e9f-a99d-486cc9c9b5b8@d77g2000hsb.googlegroups.com> Message-ID: Other possibility, combining Dan and Fredrik's posts: import zipfile import os zips = { 'c:/spare.zip': ['c:/spare/huge.fm3', 'c:/spare/huge.wk3'], 'c:/seekfacts.zip': ['c:/seekfacts/bookmark.html', 'c:/seekfacts/ index.htm', 'c:/seekfacts/seek.css', 'c:/seekfacts/seek.js'] }; def zipdir(zFile, files): for f in files: zFile.write(f, os.path.basename(f), zipfile.ZIP_DEFLATED); def zipit(zipfilename, files): zFile = zipfile.ZipFile(zipfilename, 'w'); zipdir(zFile, files); zFile.close(); for zipfilename,files in zips.items(): zipit(zipfilename, files); From wegraps at gmail.com Wed Jul 23 00:30:43 2008 From: wegraps at gmail.com (Graps Graps) Date: Wed, 23 Jul 2008 10:00:43 +0530 Subject: How to replace the values with keys ? Message-ID: <92df0f7c0807222130n382edf5di8c7124690f3dffa7@mail.gmail.com> Hi all, I am a newbie to python... I have two text files text1 and text2. Text1 is a tabbed separated file, say like a b a c a d a g b c b d b h c d c h... and so on.. Text2 is a python dictionary containing data as {0: 'a', 1: 'b', 2: 'c'...} now I want the data in text1 to be replaced with the keys, say like 0 1 0 2 0 3 0 6 1 2... so on.. Is there some way I could do it in python? I tried import aDict import re infile = open('text1.txt','rw') outfile = open('text3.txt','w') def replace_words(infile, aDict): rc=re.compile('|'.join(map(re.escape, aDict))) def translate(match): return aDict[match.group(0)] return rc.sub(translate, infile) outfile = replace_words(infile,aDict) I am thrown with: Traceback (most recent call last): File "", line 1, in File "", line 2, in replace_words TypeError: argument 2 to map() must support iteration I imported text2.txt , containing python dictionary as aDict.py. I want the replaced values in a separate file text3.txt. Thanking in advance.., GraPs -------------- next part -------------- An HTML attachment was scrubbed... URL: From rowen at cesmail.net Tue Jul 29 15:24:49 2008 From: rowen at cesmail.net (Russell E. Owen) Date: Tue, 29 Jul 2008 12:24:49 -0700 Subject: like py2exe, but on a mac References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> Message-ID: In article <5K9jk.278$rb5.198 at trnddc04>, William McBrine wrote: > On Sun, 13 Jul 2008 00:58:59 +0200, Python.Arno wrote: > > > http://undefined.org/python/py2app.html > > py2app bundles Python itself into the app, right? I wonder, is there no > way to create an app bundle that relies on the existing installation of > Python, since OS X already comes with Python? I have a tiny little > program (~20k) that I'd like to make into an app bundle, if only to > suppress the console window, and I'd rather not lump in the whole Python > interpreter if I can avoid it. That is exactly what py2app does by default if you run py2app with the system python. If you run py2app with a non-system python then that python is bundled with the application. Note that different versions of MacOS X have different versions of system python. So if your application needs any 3rd party packages then including python with the app will allow it work with more versions of MacOS X. -- Russell From rocksportrocker at googlemail.com Sat Jul 12 06:44:37 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Sat, 12 Jul 2008 03:44:37 -0700 (PDT) Subject: sending input to an embedded application References: Message-ID: On 12 Jul., 09:08, George Oliver wrote: > hi, I'm a novice programmer trying to better define a hobby project > I'm thinking of. > > What I would like to do is take a program and embed it or put it > within a Python-run GUI, using the GUI just to capture and send input > to the application, and display the ouput. > > Specifically I want to use a Python module such as wxPython, pygame or > pyglet to build the UI, capture key presses, and then send a string to > the program, an interactive fiction interpreter; the reason for this > is that the interpreter on its own doesn't have the capability to > recognize certain key presses on the keyboard. I thought that writing > a middle layer rather than a brand new interpreter would be easier for > someone of my skill level. > > The interpreter would send its output to the Python GUI. The GUI then > would be as light/translucent as possible, just accepting input, > sending it to the interpreter, and displaying the output as if you > were just running the interpreter by itself. > > As I don't really know the issues involved, I'm hoping someone can > point me in the right direction. Do people 'frame' programs with > something like wxPython or pygame and use the frame to capture and > pass along input, and receive and display the output? > > thanks, George Which interface does your interpreter provide ? Just commandline or can you access by other methods ? http://sourceforge.net/projects/pexpect/ might help you Greetings, Uwe From jwahlmann at gmail.com Fri Jul 18 14:43:26 2008 From: jwahlmann at gmail.com (jwahlmann at gmail.com) Date: Fri, 18 Jul 2008 11:43:26 -0700 (PDT) Subject: Weird Python startup behavior between different drives on PowerPC platform Message-ID: <616d9012-5b71-43c7-9141-bc4b37072642@y22g2000prd.googlegroups.com> I'm experiencing some strange behavior when starting up python on a Debian-based PowerPC platform. Normally, I operate from this platform with a root file system on an IDE flash drive (/dev/hda1). However, I'm trying to get my system to run with root on a mechanical SATA drive (/dev/sda1). Both are installed on a PowerPC board via a PMC daughter board. When running off the flash drive, the Python interpreter loads and runs just fine. However, when running from SATA, the interpreter seems to have problems with importing things like site, os, etc. I've played around with PYTHONHOME to no effect. I even went as far as setting PYTHONHOME to some off the wall location (so no stdlibs will load) and invoking Python as: host$ PYTHONHOME=/tmp python -d -v -S # installing zipimport hook import zipimport # builtin # installed zipimport hook Python 2.4.4 (#2, Apr 5 2007, 19:01:44) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 >>> i=0 File "", line 1 i=0 ^ SyntaxError: invalid syntax >>> You'll note that doing something as simple as setting "i=0" results in a syntax error. If I run the same thing on the IDE flash drive, it works: host$ PYTHONHOME=/tmp python -d -v -S # installing zipimport hook import zipimport # builtin # installed zipimport hook Python 2.4.4 (#2, Apr 5 2007, 19:01:44) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 >>> i=0 >>> Any ideas?! What could possibly cause a difference of operation between running from a IDE flash drive (/dev/hda1) vs. SATA (/dev/ sda1)? Other than toggling hda1 vs. sda1 in /etc/fstab, the filesystems are being built identically. Could it be that shared libraries aren't being loaded correctly or fast enough off the SATA drive vs. flash? Shooting in the dark here... Thanks, Jon Wahlmann From alexnbryan at gmail.com Thu Jul 17 03:50:59 2008 From: alexnbryan at gmail.com (Alexnb) Date: Thu, 17 Jul 2008 00:50:59 -0700 (PDT) Subject: Getting a unknown word out of a list with no spaces In-Reply-To: <487EF7D9.8010400@promsoft.ru> References: <18502758.post@talk.nabble.com> <487EF593.5060505@promsoft.ru> <18503144.post@talk.nabble.com> <487EF7D9.8010400@promsoft.ru> Message-ID: <18503367.post@talk.nabble.com> Alexandr N Zamaraev wrote: > > Alexnb wrote: >>>>>> s = '--a href="/browse/brick"--brick--/a--' >>>>>> s >>> '--a href="/browse/brick"--brick--/a--' >>>>>> ''.join('<%s>' % l if i % 2 == 1 else l for i, l in >>> enumerate(s.split('--'))) >>> ' /browse/brick brick ' >> >> I'm sorry, I don't think I was being clear. I replaced the <'s with -- so >> it >> would post online w/o actually making a link. I just need to know how to >> get >> the "brick" out. > 1) if string really '--a href="/browse/brick"--brick--/a--' > >>> s.split('--', 3)[2] > brick > 2) if string ' /browse/brick brick ' > >>> s.split('>', 1)[1].split('<')[0] > brick > -- > http://mail.python.org/mailman/listinfo/python-list > > Excellent! it works. But I have one more question. How can I test to see if the first character of a string is what I want, for example, how can I test to see if the first char of a string is "<"? -- View this message in context: http://www.nabble.com/Getting-a-unknown-word-out-of-a-list-with-no-spaces-tp18502758p18503367.html Sent from the Python - python-list mailing list archive at Nabble.com. From asd at pittle.org Thu Jul 10 05:16:12 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Thu, 10 Jul 2008 02:16:12 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: Message-ID: <2320fe46-9e4d-483c-bbe5-4d8741951ffd@2g2000hsn.googlegroups.com> On Jul 10, 1:07?am, Gros Bedo wrote: > Hello, > Ali I totally support you, neither I couldn't find any really working code completion for python in a free software, and it's really a mess, at least on Linux. > > On Windows, there is PyScripter (http://pyscripter.googlepages.com/), but it is based on Delphi, and as such it's not portable. But it's a free software (even if I couldn't find the sources, they say you can download them). > > It is said to be working on Linux via Wine, so if you really need a code completion tool you could give it a try. > _________________________________________________________________ > T?l?chargez gratuitement des ?motic?nes pour pimenter vos conversations Messengerhttp://specials.fr.msn.com/femmes/amour/emoticonesLove.aspx Thanks. From theller at python.net Thu Jul 24 11:03:59 2008 From: theller at python.net (Thomas Heller) Date: Thu, 24 Jul 2008 17:03:59 +0200 Subject: Working with ctypes and char** data type In-Reply-To: <14b44a64-ec58-4ff2-abce-1cc44557e4e4@27g2000hsf.googlegroups.com> References: <14b44a64-ec58-4ff2-abce-1cc44557e4e4@27g2000hsf.googlegroups.com> Message-ID: <6erju5F88slmU2@mid.individual.net> Philluminati schrieb: > I'm a bit of a python newbie and I need to wrap a C library. > > I can initialise the library using CDLL('mcclient.so') > > and I can call functions correctly inside the library but I need to > invoke one function which has this function definition: > > char ** CAPAPI McSearch(HMCLINK Handle, > short nSearchType, > short nNoSelect, > char **pSelect, > short nNoWhere, > char **pWhere, > char **pData, > int iTimeout); > > For **pSelect I want to pass in an array of char points, which in C > would be declared as > > char *pData[] = { "ADDR", "POSTCODE" }; > > Can someone tell me how use pointers + char pointers together in > python with ctypes please? # create an array that holds two pointers to 'char *', and fill it with data: pData = (c_char_p * 2)() pData[0] = "ADDR" pData[1] = "POSTCODE" # Another way: pData = (c_char_p * 2)("ADDR", "POSTCODE") Thomas From code at pizzashack.org Mon Jul 21 12:12:41 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 21 Jul 2008 12:12:41 -0400 Subject: Change PC to Win or Windows In-Reply-To: References: Message-ID: <20080721161241.GA8793@dragontoe.org> On Fri, Jul 18, 2008 at 10:34:41PM -0700, Dennis Lee Bieber wrote: > On Fri, 18 Jul 2008 19:14:43 -0400, Derek Martin > declaimed the following in comp.lang.python: > > > On Fri, Jul 18, 2008 at 03:46:13PM -0700, Joel Teichroeb wrote: > > > Calling Windows PC seems to be something that Apple did so they would > > > not have to directly mention Windows. > > > > Actually it's something IBM did when they created the IBM PC. Of > > Bah... PC was short for Personal Computer... I'm well aware... congratulations on completely missing the point. I was describing how the term PC has become synonimous with Windows machines. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From motoom at xs4all.nl Mon Jul 14 12:30:26 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Mon, 14 Jul 2008 18:30:26 +0200 Subject: Determining when a file has finished copying Message-ID: <2.2.32.20080714163026.01217970@pop.xs4all.nl> Ethan wrote: > One more option may be to attempt to rename > the file -- if it's still open for copying, that will fail; > success indicates the copy is done. Caveat -- this is dependent on the operating system! Windows will indeed not allow you to rename or delete a file that's still open for writing by another process, at least not when the file is on a local NTFS filesystem, but don't count on this on Unix or networked filesystems. There you can easily rename, move or delete a filename from a directory whilst other processes still write to it. After all, a directory is nothing else than a list of filenames which map to certain inodes. Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From sjmachin at lexicon.net Sat Jul 19 01:32:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 18 Jul 2008 22:32:15 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> Message-ID: <945275e9-8923-479c-8eec-258bd68063c0@z6g2000pre.googlegroups.com> On Jul 19, 12:04 pm, Andrew Freeman wrote: > To show if valid: > > if re.search(r'^[LRM]*$', 'LM'): > print 'Valid' > A couple of points: (1) Instead of search(r'^blahblah', ...) use match(r'blahblah', ...) (2) You need to choose your end-anchor correctly; your pattern is permitting a newline at the end: >>> re.search(r'^[LRM]*$', 'LM\n') <_sre.SRE_Match object at 0x00B9E528> >>> From steve at REMOVE-THIS-cybersource.com.au Sun Jul 27 05:14:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Jul 2008 09:14:26 GMT Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> Message-ID: <009c37fd$0$20302$c3e8da3@news.astraweb.com> On Sat, 26 Jul 2008 15:58:16 -0700, Carl Banks wrote: > On Jul 26, 5:07?pm, Terry Reedy wrote: >> Whether or not one should write 'if x' or 'if x != 0' [typo corrected] >> depends on whether one means the general 'if x is any non-null object >> for which bool(x) == True' or the specific 'if x is anything other than >> numeric zero'. ?The two are not equivalent. ?Ditto for the length >> example. > > Can you think of any use cases for the former? And I mean something > where it can't be boiled down to a simple explicit test for the sorts of > arguments you're expecting; something that really takes advantage of the > "all objects are either true or false" paradigm. But why do you need the explicit test? What benefit do you get from if len(alist) != 0 instead of the simpler and faster "if alist" ? If you need to know that alist is actually a list, isinstance() is the function you want; and if you want to know that it has a length, hasattr(alist, '__len__') is better. (Or call len() in a try...except block.) Either way, testing the length is zero explicitly gains you nothing, and risks failure for any sequence types that might distinguish between an empty sequence and a length of zero. > The best thing I can come up with out of my mind is cases where you want > to check for zero or an empty sequence, and you want to accept None as > an alternative negative as well. But that's pretty weak. You might find it pretty weak, but I find it a wonderful, powerful feature. I recently wrote a method that sequentially calls one function after another with the same argument, looking for the first function that claims a match by returning a non-false result. It looked something like this: def match(arg, *functions): for func in functions: if func(arg): return func I wanted the function itself, not the result of calling the function. I didn't care what the result was, only that it was something (indicates a match) or nothing (no match). In one application, the functions might return integers or floats; in another they might return strings. In a third, they might return re match objects or None. I don't need to care, because my code doesn't make any assumptions about the type of the result. -- Steven From python at bdurham.com Wed Jul 30 20:29:39 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 30 Jul 2008 20:29:39 -0400 Subject: Optimizing size of very large dictionaries Message-ID: <1217464179.31710.1266222419@webmail.messagingengine.com> Are there any techniques I can use to strip a dictionary data structure down to the smallest memory overhead possible? I'm working on a project where my available RAM is limited to 2G and I would like to use very large dictionaries vs. a traditional database. Background: I'm trying to identify duplicate records in very large text based transaction logs. I'm detecting duplicate records by creating a SHA1 checksum of each record and using this checksum as a dictionary key. This works great except for several files whose size is such that their associated checksum dictionaries are too big for my workstation's 2G of RAM. Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From larry.bates at websafe.com` Wed Jul 9 20:27:17 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 09 Jul 2008 19:27:17 -0500 Subject: Manipulating bitsets in struct In-Reply-To: References: Message-ID: Allen wrote: > I'm using Python to do some simple network programming, and found the > struct module very useful for such things, but is there a way to easily > manipulate bitsets such as a 16 bit word being split into 4 parts like 2 > bits, 1 bit, 4 bits, and 9 bits? > > Perhaps something like: > > struct.pack('!h(2:1:4:9)',2,0,1,100) > > > Brian Vanderburg II > > > > > Just 'or' them together after shifting to the left the appropriate number of bits. -Larry From henryar2 at gmail.com Fri Jul 11 11:38:47 2008 From: henryar2 at gmail.com (Henry Read) Date: Fri, 11 Jul 2008 23:38:47 +0800 Subject: Editra Message-ID: Editra is a multi-platform text editor with an implementation that focuses on creating an easy to use interface and features that aid in code development. Currently it supports syntax highlighting and variety of other useful features for over 60 programming languages. Editra is freely available under the terms of the wxWindows Licence. Currently the project is in the alpha development phase but test builds of "stable" points are available for download and trial as Windows and Mac OSX(Universal) binaries, currently other Unix and Linux based systems will have to install from source using the included setup script. Please feel free give it a try and to report bugs and request features. *Editra*.org | News It is a good editor for Python, also it is small.It can also support auto completion with Python modules. It is suitable for Python beginners. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dominic.rice at gmail.com Fri Jul 4 05:37:20 2008 From: dominic.rice at gmail.com (Dominic Rice) Date: Fri, 04 Jul 2008 10:37:20 +0100 Subject: running python from cmd.exe References: Message-ID: Miki wrote: > Hello, > >> I can't seem to get python to run my scripts using the command: python >> .py >> >> If I type python the interpreter runs as I sorted out the Path property, >> >> I'm afraid I don't know much about this kind of thing as I'm a science >> student who needs some Python not a programmer! > Can you be more specific about the error you get? > > Say you have a script hw.py that contains one line: > print "Hello Python" > > and you run > python hw.py > > What is the error you get? > > HTH, > -- > Miki > http://pythonwise.blogspot.com > Sure, I get: can't open file .py: [errorno 2]No such file or directory. Now if I've noticed that if I change directory to (for instance) \Python25 where the script is the command runs fine.(?) From bronger at physik.rwth-aachen.de Thu Jul 24 11:36:45 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 24 Jul 2008 17:36:45 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <32e12408-fc9f-4eb4-8b9d-fb7fa69bd2fc@f36g2000hsa.googlegroups.com> <87zlo7y2wn.fsf@physik.rwth-aachen.de> <48889a72$0$25165$426a74cc@news.free.fr> Message-ID: <874p6f5m5u.fsf@physik.rwth-aachen.de> Hall?chen! Bruno Desthuilliers writes: > Torsten Bronger a ?crit : > >> Kay Schluehr writes: >> >>> On 24 Jul., 11:40, Torsten Bronger >>> wrote: >>> >>>> [...] Just like this. However, the compiler could add "self" >>>> to non-decorated methods which are defined within "class". >>> >>> And $self2, $self3, ... to the object methods of nested classes >>> and $cls2, $cls3, ... to the classmethods of those classes...? >> >> One could surely find ways to realise this. However, the design >> goal should be: Make the frequent case simple, and the rare case >> possible. > > Given the (more and more prominent) use of decorators, metaclasses > and other meta-programming techniques in Python, I'm not sure the > cases where you really need access to Python's object model inners > are that "rare". Not in my code at least. What does "not rare" mean for you? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From bruno.desthuilliers at gmail.com Fri Jul 4 16:07:23 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 4 Jul 2008 13:07:23 -0700 (PDT) Subject: Getting a path from a file object References: <3c500ce7-c697-44e9-9f13-f65edc509e1c@a32g2000prf.googlegroups.com> Message-ID: <1e813aba-292a-49fa-8bb4-3f90269402ff@34g2000hsh.googlegroups.com> On 4 juil, 20:37, Andrew Fong wrote: > Newbie question: > > Let's say I open a new file for writing in a certain path. How do I > get that path back? > > Example: > > >>> f = open('/some/path/file.ext') > >>> some_function(f) > > '/some/path/file.ext' > > Does some_function(f) already exist? Nope. But: > And if not, how would I define > it? Not sure it's worth defining a function: def some_function(f): return f.name > -- Andrew From bj_666 at gmx.net Sat Jul 12 09:36:22 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Jul 2008 13:36:22 GMT Subject: How to create a timer/scheduler in Python? References: <0stg74t0eksmnfsslukn5m7f9s4rbub8kt@4ax.com> Message-ID: <6drqamF3sqd5U1@mid.uni-berlin.de> On Sat, 12 Jul 2008 10:30:00 +0100, John Dann wrote: > Looking around on the net I can see references to a thread timer, but > I'm not really looking to start any new threads (I just want part of > the GUI to update every 2 secs) and don't want to get into that sort > of complication while still just learning Python. Look into the GUI toolkit because that's typically something solved with functions from the specific toolkit. > Is there really no simple timer/scheduler function available in > Python? You can do that quite easily with threads but almost all GUI toolkits don't like it if you access the GUI from multiple threads. Ciao, Marc 'BlackJack' Rintsch From no at spam.no Sun Jul 13 11:25:03 2008 From: no at spam.no (Thin Myrna) Date: Sun, 13 Jul 2008 17:25:03 +0200 Subject: wxPython code giving strange errors. References: <01694ab5-7b5e-4e57-8b86-bf89b0beec82@m44g2000hsc.googlegroups.com> Message-ID: <487a1e4e$0$12126$3b214f66@aconews.univie.ac.at> teh_sAbEr wrote: > I'm busy trying to learn wxPython, and i'm trying to run the following > piece of code (its from the wxPyWiki tutorial): > > import wx > > ID_ABOUT = 101 > ID_EXIT = 110 > > class MainWindow(wx.Frame): > def __init__(self,parent,id,title): > wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) > self.control = wx.TextCtrl(self,1,style=wx.TE_MULTILINE) > self.CreateStatusBar() > > filemenu = wx.Menu() > filemenu.Append(ID_ABOUT,"&About"," Information about this > program.") > filemenu.AppendSeparator() > filemenu.Append(ID_EXIT,"E&xit"," Terminate the program.") > > menuBar = wx.MenuBar() > menuBar.Append(filemenu,"&File") > self.SetMenuBar(menuBar) > self.Show(True) > > app = wx.PySimpleApp() > frame = MainWindow(None, -1, "Sample editor") > app.MainLoop() > > Simple enough, but every single time I try to run it IDLE gives me > this instead of the app I was hoping for: > > Traceback (most recent call last): > File "C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap > \Python Stuff\Batch Picture Converter\main.py", line 24, in > frame = MainWindow(None, -1, "Sample editor") > File "C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap > \Python Stuff\Batch Picture Converter\main.py", line 9, in __init__ > wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) > File "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx > \_windows.py", line 501, in __init__ > _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, > **kwargs)) > PyNoAppError: The wx.App object must be created first! > > As far as I can tell, the wx.App object IS being created first. I > suspect a race condition of some sort here, but can anyone shed some > light on this? The main frame has to be created by the app itself, e.g. like so: class App(wx.App): def OnInit(self): self._frame = MainFrame( None, -1, _APP_CAPTION) self._frame.Show( True) self.SetTopWindow( self._frame) return True def Run(): app = App() app.MainLoop() if __name__ == '__main__': Run() HTH Thin From fredrik at pythonware.com Wed Jul 23 03:59:48 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 09:59:48 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: References: Message-ID: Jaco Naude wrote: > 1>application.obj : error LNK2031: unable to generate p/invoke for > "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@$$J0YMXH at Z); > calling convention missing in metadata > 1>frmPythonInterface.obj : error LNK2031: unable to generate p/invoke > for "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@$$J0YMXH at Z); > calling convention missing in metadata > > I'm probably missing something but I can't find any calling convention > details in Python.h or the other headers included in this file. the precence of name mangling indicates that your compiler doesn't understand that Python's a C library, and therefore uses C calling conventions. have you managed to override the defaults in some odd way? From mwilson at the-wire.com Mon Jul 7 20:41:20 2008 From: mwilson at the-wire.com (Mel) Date: Mon, 07 Jul 2008 20:41:20 -0400 Subject: "in"consistency? References: <87vdzhwf1v.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > "David C. Ullrich" writes: > >> >>> 'ab' in 'abc' >> True >> >>> [1,2] in [1,2,3] >> False > > > >> Is there a reason for the inconsistency? > > Probably. The special behaviour of string types was changed in Python > 2.3, according to that document. As it stands, you'd get [1,2] in [1,2,3] == False [1,2] in [1, [1,2], 3] == True This could be a good thing. Mel. > From lanclos at ucolick.org Wed Jul 16 21:46:08 2008 From: lanclos at ucolick.org (Kyle Lanclos) Date: Wed, 16 Jul 2008 18:46:08 -0700 Subject: Manually prompting garbage collection In-Reply-To: References: <20080716230911.GD22400@monkey.ucolick.org> <20080716235656.GE22400@monkey.ucolick.org> Message-ID: <20080717014608.GA28610@monkey.ucolick.org> Fredrik Lundh wrote: > Yeah, but what do you expect that garbage collection pass to result in? Basically, I want to toss the objects before I close the service that they depend on. > PyGC_Collect() does exactly that, so if that doesn't solve your problem, > the only way to fix is this is to go back to the drawing board (and even > if it would fix this, it's a good idea to get back to the drawing board > anyway; Python's not C++, and code that relies on destructors to fire in > a specific order, or before a specific event, is bound to fail sooner or > later.) I suspect that this is the root of the answer to my question-- if I can't rely on triggering the collection in a specific sequence, I'll need to implement my workaround. Your time and attention is greatly appreciated-- --Kyle From __peter__ at web.de Sun Jul 27 02:41:54 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 27 Jul 2008 08:41:54 +0200 Subject: Insert string into string References: <56ff99b9-b4d4-4077-8de1-97a771ac526a@k13g2000hse.googlegroups.com> Message-ID: Mensanator wrote: > I don't know why you're using stdin if you're reading from a file. >From Francesco's initial post in his previous thread I inferred that he had a script like f = open("xxx.pdb") for line in f: # process line print line and was calling it python script.py >outfile My hope was that import sys for line in sys.stdin: # process line sys.stdout.write(line) invoked as python script.py outfile would be an improvement as it avoids hardcoding the filename, but instead chaos ensued... Francesco: Mensanator's script looks like you can take it "as is". If you want to use Python to do other interesting things I highly recommend that you work your way through a tutorial of your choice. This will make subsequent trial-and-error much more fun. Following Roy's suggestion I also had a brief look at Biopython's PDB parser which has the advantage that it "understands" the file format. Unfortunately it is probably too complex for you to use at this point of your career as a pythonista ;) By the way, are you trying to modify the chain ID? Biopython locates that at position 21, so take this as a reminder that indices in Python start at 0, i. e. line[21] gives you the 22nd character in the line. Peter From __peter__ at web.de Sun Jul 6 14:57:00 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 06 Jul 2008 20:57:00 +0200 Subject: how are strings immutable in python? References: Message-ID: ssecorp wrote: >>>> h = "aja baja" >>>> h += 'e' >>>> h > 'aja bajae' >>>> The inplace-add operator doesn't mutate the lvalue, it just rebinds it: >>> a = b = "foo" >>> id(a) 47643036142016 >>> a += "bar" >>> id(a), a (47643036142064, 'foobar') >>> id(b), b (47643036142016, 'foo') Peter From motoom at xs4all.nl Sat Jul 12 06:09:11 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Sat, 12 Jul 2008 12:09:11 +0200 Subject: Help with BeautifulSoup Message-ID: <2.2.32.20080712100911.01141b64@pop.xs4all.nl> Alex wrote... > >Okay, heres the general idea of the html I have to work with: > >
> noun > >
>
>
> verb >
>
>
> > >Okay, I left off some stuff. I wish you didn't, or at least provided an URL where I can get the page which you are trying to parse. Now I don't have a valid testcase to tinker with. And maybe you can also show your code which you already came up with. > I can easily get the tables but it is the span's than I am having trouble with. I can't see any SPAN tags in the example you provided. Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From roy at panix.com Sat Jul 12 20:32:53 2008 From: roy at panix.com (Roy Smith) Date: Sat, 12 Jul 2008 20:32:53 -0400 Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> Message-ID: In article <3b78898b-6131-4137-9c1d-64deaf460ee6 at p25g2000hsf.googlegroups.com>, ssecorp wrote: > Is this correct use of exceptions? to raise an indexerror and add my > own string insetad of just letting it raise a IndexError by itself and > "blaming" it on list.pop? > > class Stack(object): > def __init__(self, *items): > self.stack = list(items) > > def push(self, item): > self.stack.append(item) > > def pop(self): > try: > return self.stack.pop() > except: > raise IndexError, "pop from empty stack" > > class Queue(object): > def __init__(self, *items): > self.queue = list(items) > > def append(self, item): > self.queue.append(item) > > def pop(self): > try: > return self.queue.pop(0) > except: > raise IndexError, "pop from empty queue" I think you would do better defining a new exception, PopError, or something like that. Then you can write code which specifically catches that and do something with it. It's also not a good idea to catch all exceptions. Catch the most specific thing you can. Consider something like: try: kew.pop(0) except: raise IndexError, "pop from empty kew" When I run it, it prints, "IndexError: pop from empty kew". The problem is, the *real* error is "NameError: name 'kew' is not defined". By catching all exceptions, I've masked a programming error by turning the NameError into an IndexError. From norseman at hughes.net Tue Jul 15 12:50:44 2008 From: norseman at hughes.net (norseman) Date: Tue, 15 Jul 2008 09:50:44 -0700 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> Message-ID: <487CD564.5020008@hughes.net> defn noob wrote: > isPrime works when just calling a nbr but not when iterating on a > list, why? adding x=1 makes it work though but why do I have to add > it? > Is there a cleaner way to do it? > > > def isPrime(nbr): > for x in range(2, nbr + 1): > if nbr % x == 0: > break > if x == nbr: > return True > else: > return False > >>>> [isPrime(y) for y in range(11)] > > Traceback (most recent call last): > File "", line 1, in > [isPrime(y) for y in range(11)] > File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > if x == nbr: > UnboundLocalError: local variable 'x' referenced before assignment > > >>>> map(isPrime, range(100)) > > Traceback (most recent call last): > File "", line 1, in > map(isPrime, range(100)) > File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > if x == nbr: > UnboundLocalError: local variable 'x' referenced before assignment >>>> isPrime(10) > False >>>> isPrime(11) > True > > > > adding x=1 makes it work though: > > def isPrime(nbr): > x=1 > for x in range(2, nbr + 1): > if nbr % x == 0: > break > if x == nbr: > return True > else: > return False > > >>>> [isPrime(y) for y in range(11)] > [False, True, True, True, False, True, False, True, False, False, > False] > -- > http://mail.python.org/mailman/listinfo/python-list > ======================================== Yep - "local variable 'x' referenced before assignment" is correct. You state: for x in range... but x doesn't exist until initialized. To save a loop, initialize x=2 (the minimum value) and loop executes on pass one. In a straight 'C' program ( for (x=1, x=(nbr+1), x++) etc... ) the x is initialized and forceably incremented. seems Python does not auto initialize but does auto increment. Steve norseman at hughes.net From ki4yjl at gmail.com Sun Jul 20 17:05:16 2008 From: ki4yjl at gmail.com (WDC) Date: Sun, 20 Jul 2008 14:05:16 -0700 (PDT) Subject: Testing out NewsProxy Message-ID: Please excuse this post, but I am seeing if NewsProxy actually filters out Google Groups or not. From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 3 11:09:45 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 03 Jul 2008 17:09:45 +0200 Subject: site-packages, unzipepd there but import fails In-Reply-To: References: Message-ID: <486cebad$0$15999$426a34cc@news.free.fr> defn noob a ?crit : > i unzipped what ? > and put the folder which folder > in site-packages. which one ? (remember that if you have more than one Python installation on your machine, you'll have more than one site-packages too). > when i run setup.py > install nothing happens. Well... usually, setup.py install takes care of putting the appropriate things at the appropriate place for your system, so you don't have to "put the folder in site-packages" by yourself. > when i do import pp from shell Which shell ? The Python shell ? A bash shell ? > it complains it doesnt exist. > > isnt placing the folder in site-packages enough? > move "the folder" from site-packages to somewhere else, cd to "the folder", then run python setup.py install (with appropriate permissions of course). And if you have more than one python install on your system, make sure the one you're using for running setup.py is the right one. > these setup.py-files often dont work Python-version confusion issues set aside, I've never had any problem with a setup.py so far (for 'so far' == since I've started using Python some height years ago). But I admit I never tried to copy "the folder" into site-packages *then* run setup.py install from there... From sjmachin at lexicon.net Thu Jul 10 07:28:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 10 Jul 2008 04:28:35 -0700 (PDT) Subject: TypeError, I know why but not how!? References: <03cbb0d2-6a0c-4b86-a75e-b73c5677acc7@c65g2000hsa.googlegroups.com> Message-ID: On Jul 10, 12:07 pm, ssecorp wrote: > pair1 = (student1,student2) > pair2 = (student2,student1) > if (pair1 or pair2) in incompatibles: Apart from the problems that others have mentioned, the above statement is NOT doing what you think it is. (pair1 or pair2) will always produce pair1, because pair1, a tuple of length 2, cannot be false. So the statement is equivalent to: if pair1 in incompatibles: What you want is: if pair1 in incompatibles or pair2 in incompatibles: Cheers, John From stefan_ml at behnel.de Sat Jul 19 03:56:29 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 19 Jul 2008 09:56:29 +0200 Subject: Best Python packages? In-Reply-To: References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> <17861f55-8ad1-4703-ad22-838675f2afc4@w1g2000prk.googlegroups.com> Message-ID: <48819E2D.10903@behnel.de> Iain King wrote: > Well, if you're looking for a list of excellent 3rd party Python > libraries, then I can give you the ones I like and use a lot: [...] > BeautifulSoup : for real-world (i.e. not-at-all-recommendation- > compliant) HTML processing You forgot lxml.html, which is much faster, more memory friendly and more feature-rich than BS. Stefan From alexandre.Fayolle at logilab.fr Thu Jul 31 07:34:39 2008 From: alexandre.Fayolle at logilab.fr (alexandre.Fayolle@logilab.Fr) Date: Thu, 31 Jul 2008 04:34:39 -0700 (PDT) Subject: working pylint anyone? References: <6fdf17Fb2bboU1@mid.uni-berlin.de> Message-ID: <8a08b59f-f7f0-4706-84c9-19f0460f09ef@k30g2000hse.googlegroups.com> On Jul 31, 11:29?am, "Diez B. Roggisch" wrote: > Hi, > > until yesterday I was a happy user of pylint. Then I upgraded to ubuntu > hardy heron - and the trouble began. > > The packaged version of pylint (0.13.2) fails with this error (last line): > > logilab.common.configuration.UnsupportedAction: callback This is a bug in the pylint package in Ubuntu, which has a wrong versioned dependency on python-logilab-common. You should report this bug to ubuntu using the reportbug command. Which version of python-logilab-common and python-logilab-astng are installed on your machine ? > The same error happens if I use > > easy_install-2.5http://release.ingeniweb.com/third-party-dist/logilab.installer-0.1.tgz > > as found on the net. Using easy_install pylint misses logilab-common & > astng, installing these additionally (easy_install) creates two eggs - but > unfortunately, the don't actually create a namespace-package logilab, > instead either one of them is picked up depending on installation order. > > Then I tried the source releases - no luck either, either they produce the > same error or something similar. You are probably picking up the system installation of logilab-common when you do this. > I tried looking into the MLs - the last posts are from around 2006, so I > refrained from actually subscribing. I don't know where you checked, but there is some traffic on the mailing list, and questions generally get answered :-) (http://lists.logilab.org/pipermail/python-projects/ is the correct place) > So - anybody out here having an actually working pylint config and can tell > me what versions work together? I've become pretty dependend on it to be > honest... pylint 0.14.0 should work fine with logilab-common 0.33.0 and astng 0.17.2 Our Debian packages state that it should even work with logilab-common >= 0.22.0 and astng >= 0.17.1 (although to be perfectly honnest, I'm not sure that we have tested pylint with logilab-common 0.22.0, so we could be the ones who introduced the bug in the Ubuntu package). Hope this helps, -- Alexandre Fayolle LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services Informatique scientifique: http://www.logilab.fr/science From narutocanada at gmail.com Sun Jul 20 00:12:59 2008 From: narutocanada at gmail.com (narutocanada at gmail.com) Date: Sat, 19 Jul 2008 21:12:59 -0700 (PDT) Subject: atan2 weirdness Message-ID: <3b3ce28f-55d0-4db4-8eac-df0a9d1bc558@o40g2000prn.googlegroups.com> hi atan2 is supposed to return the angle to x-axis when given y and x, I suppose if I take [x,y] to one full circle, I should get 0-360 degree back---- but no, I get 3 full revolutions! maybe my understanding is wrong. from math import * def f(ang): a=ang if a>360: a-=360 if a>360: a-=360 if a<0: a+=360 if a<0: a+=360 return round(a) for i in range(0,360): t=2*pi*i/360.0 print i,f(atan2(sin(t),cos(t))*180.0) 0 0.0 1 3.0 2 6.0 3 9.0 4 13.0 5 16.0 6 19.0 7 22.0 8 25.0 9 28.0 10 31.0 11 35.0 12 38.0 13 41.0 14 44.0 15 47.0 16 50.0 17 53.0 18 57.0 19 60.0 20 63.0 21 66.0 22 69.0 23 72.0 24 75.0 25 79.0 26 82.0 27 85.0 28 88.0 29 91.0 30 94.0 31 97.0 32 101.0 33 104.0 34 107.0 35 110.0 36 113.0 37 116.0 38 119.0 39 123.0 40 126.0 41 129.0 42 132.0 43 135.0 44 138.0 45 141.0 46 145.0 47 148.0 48 151.0 49 154.0 50 157.0 51 160.0 52 163.0 53 167.0 54 170.0 55 173.0 56 176.0 57 179.0 58 182.0 59 185.0 60 188.0 61 192.0 62 195.0 63 198.0 64 201.0 65 204.0 66 207.0 67 210.0 68 214.0 69 217.0 70 220.0 71 223.0 72 226.0 73 229.0 74 232.0 75 236.0 76 239.0 77 242.0 78 245.0 79 248.0 80 251.0 81 254.0 82 258.0 83 261.0 84 264.0 85 267.0 86 270.0 87 273.0 88 276.0 89 280.0 90 283.0 91 286.0 92 289.0 93 292.0 94 295.0 95 298.0 96 302.0 97 305.0 98 308.0 99 311.0 100 314.0 101 317.0 102 320.0 103 324.0 104 327.0 105 330.0 106 333.0 107 336.0 108 339.0 109 342.0 110 346.0 111 349.0 112 352.0 113 355.0 114 358.0 115 1.0 116 4.0 117 8.0 118 11.0 119 14.0 120 17.0 121 20.0 122 23.0 123 26.0 124 30.0 125 33.0 126 36.0 127 39.0 128 42.0 129 45.0 130 48.0 131 52.0 132 55.0 133 58.0 134 61.0 135 64.0 136 67.0 137 70.0 138 74.0 139 77.0 140 80.0 141 83.0 142 86.0 143 89.0 144 92.0 145 96.0 146 99.0 147 102.0 148 105.0 149 108.0 150 111.0 151 114.0 152 118.0 153 121.0 154 124.0 155 127.0 156 130.0 157 133.0 158 136.0 159 140.0 160 143.0 161 146.0 162 149.0 163 152.0 164 155.0 165 158.0 166 162.0 167 165.0 168 168.0 169 171.0 170 174.0 171 177.0 172 180.0 173 183.0 174 187.0 175 190.0 176 193.0 177 196.0 178 199.0 179 202.0 180 205.0 181 158.0 182 161.0 183 164.0 184 167.0 185 170.0 186 173.0 187 177.0 188 180.0 189 183.0 190 186.0 191 189.0 192 192.0 193 195.0 194 198.0 195 202.0 196 205.0 197 208.0 198 211.0 199 214.0 200 217.0 201 220.0 202 224.0 203 227.0 204 230.0 205 233.0 206 236.0 207 239.0 208 242.0 209 246.0 210 249.0 211 252.0 212 255.0 213 258.0 214 261.0 215 264.0 216 268.0 217 271.0 218 274.0 219 277.0 220 280.0 221 283.0 222 286.0 223 290.0 224 293.0 225 296.0 226 299.0 227 302.0 228 305.0 229 308.0 230 312.0 231 315.0 232 318.0 233 321.0 234 324.0 235 327.0 236 330.0 237 334.0 238 337.0 239 340.0 240 343.0 241 346.0 242 349.0 243 352.0 244 356.0 245 359.0 246 2.0 247 5.0 248 8.0 249 11.0 250 14.0 251 18.0 252 21.0 253 24.0 254 27.0 255 30.0 256 33.0 257 36.0 258 40.0 259 43.0 260 46.0 261 49.0 262 52.0 263 55.0 264 58.0 265 62.0 266 65.0 267 68.0 268 71.0 269 74.0 270 77.0 271 80.0 272 84.0 273 87.0 274 90.0 275 93.0 276 96.0 277 99.0 278 102.0 279 106.0 280 109.0 281 112.0 282 115.0 283 118.0 284 121.0 285 124.0 286 128.0 287 131.0 288 134.0 289 137.0 290 140.0 291 143.0 292 146.0 293 150.0 294 153.0 295 156.0 296 159.0 297 162.0 298 165.0 299 168.0 300 172.0 301 175.0 302 178.0 303 181.0 304 184.0 305 187.0 306 190.0 307 193.0 308 197.0 309 200.0 310 203.0 311 206.0 312 209.0 313 212.0 314 215.0 315 219.0 316 222.0 317 225.0 318 228.0 319 231.0 320 234.0 321 237.0 322 241.0 323 244.0 324 247.0 325 250.0 326 253.0 327 256.0 328 259.0 329 263.0 330 266.0 331 269.0 332 272.0 333 275.0 334 278.0 335 281.0 336 285.0 337 288.0 338 291.0 339 294.0 340 297.0 341 300.0 342 303.0 343 307.0 344 310.0 345 313.0 346 316.0 347 319.0 348 322.0 349 325.0 350 329.0 351 332.0 352 335.0 353 338.0 354 341.0 355 344.0 356 347.0 357 351.0 358 354.0 359 357.0 From larry.bates at websafe.com` Thu Jul 10 20:21:52 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 10 Jul 2008 19:21:52 -0500 Subject: Can anyone suggest a date peocedure... In-Reply-To: References: Message-ID: RV wrote: > On Thu, 10 Jul 2008 13:39:29 -0700, Gary Herron > wrote: > > >> The datetime module has what you need. >> >> It has methods (with examples) on building a datetime object from a >> string, and it has a object named timedelta, and the ability to subtract >> a timedelta from a time. >> >> For instance, the time right now and the time exactly one day ago: >> >>>>> from datetime import * >>>>> datetime.today() >> datetime.datetime(2008, 7, 10, 13, 38, 48, 279539) >>>>> datetime.today()-timedelta(1) >> datetime.datetime(2008, 7, 9, 13, 38, 50, 939580) >> >> >> Gary Herron > > Thanks Gary! This works great. Now all I need to know is how to > plug the date into the datetime object from a string. > > Ron > I really shouldn't do this until you have put forth at least a little effort... Type the following into the Python interpreter: >>>import datetime >>>help(datetime.datetime.strptime) Help on built-in function strptime: strptime(...) string, format -> new datetime parsed from a string (like time.strptime()). Note: Looking in Python manual or Googling for time.strptime (to get proper format for YYYYMMDD) dstr = "20070710" dt = datetime.datetime.strptime(dstr, "%Y%m%d") >>>dt datetime.datetime(2008, 7, 10, 0, 0) -Larry From toby at tobiah.org Thu Jul 10 15:03:06 2008 From: toby at tobiah.org (Tobiah) Date: Thu, 10 Jul 2008 12:03:06 -0700 Subject: sort(cmp=func) References: Message-ID: On Wed, 09 Jul 2008 20:58:32 -0700, Daniel Fetchinson wrote: >> I have a list of objects that generate code. Some >> of them depend on others being listed first, to >> satisfy dependencies of others. >> >> I wrote a cmp function something like this: >> >> def dep_cmp(ob1, ob2): >> >> if ob1.name in ob2.deps: >> return -1 >> else: >> return 1 >> >> I also tried returning 0 when there were no dependency >> relationships between the objects. >> >> This failed, because every object was not compared with >> ever other. I imagine that this is because sort assumes >> that if a > b and b > c, then a > c. In my case, this >> isn't really true. If a is not dependent on b, and >> b is not dependent on c, that doesn't mean that a is not >> dependent on c. >> >> Is there a better way? > > It's only meaningful to talk about sorting if your particular > definition of "<" is transitive. I.e. a < b and b < c should imply a < > c. If this is not satisfied, it doesn't make sense to sort according > to your "<" definition. It's just not a well-defined operation and no > trick will make it work. There is a meaningful relationship here however. Basically, some items must precede some other items. There are more than one correct orders however. Here was my eventual solution. I had to compare each item with each other item, swapping on failed dependencies. Recursion simplified this greatly: def dep_sort(tables): for this_index in range(len(tables)): this_table = tables[this_index] for prev_index in range(this_index): prev_table = tables[prev_index] if this_table.name in prev_table.deps: tables[prev_index] = this_table tables[this_index] = prev_table dep_sort(tables) return ** Posted from http://www.teranews.com ** From robert.kern at gmail.com Wed Jul 9 22:17:02 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 09 Jul 2008 21:17:02 -0500 Subject: TypeError, I know why but not how!? In-Reply-To: <03cbb0d2-6a0c-4b86-a75e-b73c5677acc7@c65g2000hsa.googlegroups.com> References: <03cbb0d2-6a0c-4b86-a75e-b73c5677acc7@c65g2000hsa.googlegroups.com> Message-ID: ssecorp wrote: > Im looking into PvsNP: > http://www.claymath.org/millennium/P_vs_NP/ > so I thought I'd write the program just to get a feel for it. > > > But I run into a problem. Why does it all the sudden return None? I > mean I know why the program aborts but I dont understand why the None > is generated all the sudden. Hitting recursion depth isn't reported > with that error. def validate(placed): student = round(random.random()*401) if student in placed: # You need to explicitly return, here: return validate(placed) else: placed.append(student) return student, placed -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From maric at aristote.info Wed Jul 30 05:09:01 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 30 Jul 2008 11:09:01 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <2ac250ee-131d-44a3-9b0a-f2fb34758147@c65g2000hsa.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <2ac250ee-131d-44a3-9b0a-f2fb34758147@c65g2000hsa.googlegroups.com> Message-ID: <200807301109.02110.maric@aristote.info> Le Tuesday 29 July 2008 23:48:31 giltay at gmail.com, vous avez ?crit?: > Here's a function, print_members. ?It's just something that takes some > iterable and prints its members in XML. ?It's special-cased so that an > empty iterable gets an empty tag. ?(This is a bit of a trivial > example, I admit; the point is that the empty iterable is a special > case.) > > def print_members(iterable): > ? ? if not iterable: > ? ? ? ? print '' > ? ? ? ? return > ? ? print '' > ? ? for item in iterable: > ? ? ? ? print '%s' % item > ? ? print '' > > ... > So print_members can work on iterables that have no len(), and handle > the special case of an empty iterable, as long as __nonzero__ is > implemented. > But iterables can have no notion of emptiness too : >>>[25]: print_members((e for e in range(0))) Your function is just wrong assuming that, it should be written : >>>[31]: def print_members(iterable): print '' print '%s' % item print empty and '/>' or '' ....: ....: >>>[40]: print_members((e for e in range(0))) >>>[41]: print_members((e for e in range(1))) 0 > Counterexample: > > While "if x" works well in some circumstances, I don't like using it > for purely numeric types. ?For instance, I have a mutable Signal class > for doing some basic DSP. ?Among other things, I can apply a DC offset > to the signal (it just adds the offset to all the samples). ?I have a > special case for an offset of 0 so I don't have to loop through all > the samples (I also have a two-pass remove_offset method that > subtracts the average; if it's already properly centred, I can skip a > step). > > class Signal: > ? ? [...] > ? ? def dc_offset(self, amount): > ? ? ? ? if amount == 0: > ? ? ? ? ? ? return > ? ? ? ? self.samples = [sample + amount for sample in self.samples] This function is also wrong assuming that because amount compare to zero, it can be added to sample. If you want to make type checking just check the type or convert your parameter to an int, but the test "== 0" is of no help here. The only valuable point I see for this idiom is to make more explicit I am testing a numerical value. But your example is a good objection to this, with well chosen name, ie. amount, it's quite clear "if not amount :" is testing the zero value of a numerical value. -- _____________ Maric Michaud From peter.bulychev at gmail.com Wed Jul 2 10:27:46 2008 From: peter.bulychev at gmail.com (Peter Bulychev) Date: Wed, 2 Jul 2008 18:27:46 +0400 Subject: convert unicode characters to visibly similar ascii characters In-Reply-To: <040bbdba-169b-4340-aa76-a7d2d0954346@34g2000hsf.googlegroups.com> References: <040bbdba-169b-4340-aa76-a7d2d0954346@34g2000hsf.googlegroups.com> Message-ID: Thank you. That is exactly what I was looking for. 2008/7/2 Jim : > Peter Bulychev wrote: > > I want to convert unicode character into ascii one. > You have to make some arbitrary choices of what to translate. Based > on some materials on effbot's site, and a recipe, I made > ftp://alan.smcvt.edu/hefferon/unicode2ascii.py > which has at least some of what you are looking for. > $ grep HYPHEN unicode2ascii.py > u'\N{SOFT HYPHEN}':u'-', > u'\N{HYPHEN}':u'-', > u'\N{NON-BREAKING HYPHEN}':u'-', > u'\N{SOFT HYPHEN}': '-', > No doubt I have some terrible gaffes and some things missing. > Corrections appreciated. > > Jim > -- > http://mail.python.org/mailman/listinfo/python-list > -- Best regards, Peter Bulychev. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jordanrastrick at gmail.com Thu Jul 24 10:07:02 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 07:07:02 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <1de235af-4245-41aa-9091-bb7b112f4ce5@n33g2000pri.googlegroups.com> Message-ID: <20b5e80c-ba2a-4cd0-9a6a-beeef6134839@r35g2000prm.googlegroups.com> > Personally, I think it has more to do with statements like "there are > plenty of smart Python programmers who will > justify all kinds of idiocy in the name of their holy crusade" than > with your position. You don't begin a discussion by discrediting > anyone who might disagree with you as some kind of religious bigot > while simultaneously holding that you are the only sane voice > speaking. I didn't set out to discredit anyone who might disagree with me; in fact I didn't in anyway try to pre-empt any person who might disagree with my thesis. I merely stated an observation - I have in the past seen seemingly intelligent people take silly stands in the name of Explicit is greater than Implicit (not just on comp.lang.python, and not just concerning != or self). I wish in retrospect I'd had the time, patience and focus to edit the initial post to make it more measured and less inflammatory, because its clear the tone detracts from the argument I'm making, which I feel still stands. So if you wish, ignore the specifics of the frustration that inspired me and consider only the thrust of what I'm saying: "Explicit is better than Implict" considered harmful. Discuss. From alexandre.Fayolle at logilab.fr Thu Jul 31 10:09:52 2008 From: alexandre.Fayolle at logilab.fr (alexandre.Fayolle@logilab.Fr) Date: Thu, 31 Jul 2008 07:09:52 -0700 (PDT) Subject: working pylint anyone? References: <6fdf17Fb2bboU1@mid.uni-berlin.de> <8a08b59f-f7f0-4706-84c9-19f0460f09ef@k30g2000hse.googlegroups.com> <6fdq70Fb1t79U1@mid.uni-berlin.de> Message-ID: <8ffa9c09-4538-459e-b81c-2f437113dfa4@x35g2000hsb.googlegroups.com> On Jul 31, 2:39?pm, "Diez B. Roggisch" wrote: > > Which version of python-logilab-common and python-logilab-astng are > > installed on your machine ? > > By now, pylint 0.14 with logilab.common 0.27 and astng 0.17.2 > > I was able to track down the problem as being related to a custom init-hook. > > See the attached .pylintrc + hook. They don't actually *do* anything (or, > the hook that is), but confuse pylint to spit out the reported error. Maybe > you can track down the real reason for the error? Congratulation ! you've found a pylint bug (or more likely a logilab- common bug in our wrapper of optparse/optik) :-/ I have added it to our tracker (http://www.logilab.org/ticket/5677) and it should be fixed in the next release of pylint or logilab-common. > > I don't know where you checked, but there is some traffic on the > > mailing list, > > and questions generally get answered :-) > > On the website, I found this link: > > http://www.logilab.org/mailinglist/850 > > through the search. Ouch, this is actually a nasty bug on our site. I'm going to see what I can do about it. In the meantime, you may consider subscribing directly from http://lists.logilab.org/mailman/listinfo/python-projects -- Alexandre Fayolle LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services Informatique scientifique: http://www.logilab.fr/science From python at hope.cz Wed Jul 30 12:22:51 2008 From: python at hope.cz (Johny) Date: Wed, 30 Jul 2008 09:22:51 -0700 (PDT) Subject: Is there a such Python module ? Message-ID: Is there a Python module that can help with reading SMS message from a mobile phone? Or is there an example how to read SMS message using a program written in Python,C, or any other language? Thank you very much for help L. From gagsl-py2 at yahoo.com.ar Wed Jul 30 00:56:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 01:56:28 -0300 Subject: Defunct when using subprocess.Popen References: <6D3D064BBC122445A4577CE1895FA06501755913@afsegbgex1.af.se> Message-ID: En Tue, 29 Jul 2008 10:04:46 -0300, Gordon Maria escribi?: > I'm running a GUI in python which is able to launch a separate python > process > that will run forever. In rare cases I will want to kill the launched > process. > Every time I do so, I end up with the process as defunct. Can anybody > help me > clean it up in a nice way? > > On request from GUI I do the following: > os.kill(process.pid,9) > > FYI, it is all running on Linux. You should call os.waitpid() after killing the child process, to let the OS free the resources allocated to it. -- Gabriel Genellina From george.sakkis at gmail.com Mon Jul 7 10:11:57 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 7 Jul 2008 07:11:57 -0700 (PDT) Subject: Dynamically Changing the Base Class References: <6d60c362-ba17-4414-babd-2cc254526bca@c58g2000hsc.googlegroups.com> Message-ID: On Jul 7, 9:31?am, "Adam C." wrote: > We have a situation where we want a Swig-generated Python class to > have a different base (not object). It doesn't appear that we can > coerce Swig into generating the class we want at present (but we are > still enquiring). > > Is it possible to dynamically change the base class to something else? > Initial experiments appear to show it is not: > -------------------------------- snip -------------------------------->>> class Foo(object): > > ? ? ? ? pass > > >>> class Foozle(object): > > ? ? ? ? pass > > >>> Foozle.__bases__ = (Foo,) > > Traceback (most recent call last): > ? File "", line 1, in > ? ? Foozle.__bases__ = (Foo,) > TypeError: __bases__ assignment: 'Foo' deallocator differs from > 'object' > -------------------------------- snip -------------------------------- > > Is there a solution I am missing? > > Thanks in advance. Supposedly it should (usually) work, there's a 6 year old patch for this (http://bugs.python.org/issue635933). Check if Swig can generate old-style classes (i.e. not inheriting from object) since __bases__ assignment works for them. HTH, George From larry.bates at websafe.com` Tue Jul 22 14:16:15 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 22 Jul 2008 13:16:15 -0500 Subject: Authentication for XML-RPC Calls In-Reply-To: <3e4258ac-40d8-485d-ba65-39d343b9561d@2g2000hsn.googlegroups.com> References: <3e4258ac-40d8-485d-ba65-39d343b9561d@2g2000hsn.googlegroups.com> Message-ID: whitemice wrote: > The only documentation regarding doing authentication for XML-RPC I > can find is - > > "Both the HTTP and HTTPS transports support the URL syntax extension > for HTTP Basic Authentication: http://user:pass at host:port/path. The > user:pass portion will be base64-encoded as an HTTP `Authorization' > header, and sent to the remote server as part of the connection > process when invoking an XML-RPC method. You only need to use this if > the remote server requires a Basic Authentication user and password." > > - from http://docs.python.org/lib/module-xmlrpclib.html > > Is this really the only way to do authentication for XML-RPC calls? > > Like this: > server = xmlrpclib.Server('http://adam:fred123 at localhost/zidestore/so/ > adam/' > > This works, but is pretty ugly. Is there no way to setup the > authentication through properties (like in most XML-RPC bindings), > like: > > server = xmlrpclib.Server('http://localhost/zidestore/so/adam/' > server.Username = 'adam' > server.Password = 'fred123' Just write a little factory class that does it for you: import urlparse class myauth(object): def __init__(self, scheme = None, domain = None, path = None): self.scheme = scheme self.domain = domain self.path = path self.Username = None self.Password = None def __str__(self): for attr in ['scheme', 'domain', 'path', 'Username', 'Password']: if getattr(self, attr) is None: raise ValueError('No %s attribute value given' % attr) url=urlparse.urlunsplit((self.scheme, '%s:%s@%s' % (self.Username, self.Password, self.domain), self.path, '', '')) return url if __name__ == "__main__": auth = auth = myauth(scheme = 'http', domain = 'localhost', path='/zidestore/so/adam/') auth.Username = 'adam' auth.Password = 'fred123' print auth In program auth = myauth(scheme = 'http', domain = 'localhost', path = '/zidestore/so/adam') auth.Username = 'adam' auth.Password = 'fred123' print auth 'http://adam:fred123 at docs.python.org/params;/lib/module-xmlrpclib.html' >>> -Larry From jwkenne at attglobal.net Tue Jul 22 15:57:21 2008 From: jwkenne at attglobal.net (John W Kennedy) Date: Tue, 22 Jul 2008 15:57:21 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: <48863ba1$0$5000$607ed4bc@cv.net> Rob Warnock wrote: > Thunks were something used by Algol 60 > *compiler writers* in the code generated by their compilers to > implement the semantics of Algol 60 call-by-name, but were not > visible to users at all [except that they allowed call-by-name > to "work right"]. ...unless you were a system programmer and had to write Algol-friendly assembler. -- John W. Kennedy "Give up vows and dogmas, and fixed things, and you may grow like That. ...you may come to think a blow bad, because it hurts, and not because it humiliates. You may come to think murder wrong, because it is violent, and not because it is unjust." -- G. K. Chesterton. "The Ball and the Cross" From Maria.Gordon at afconsult.com Tue Jul 29 09:04:46 2008 From: Maria.Gordon at afconsult.com (Gordon Maria) Date: Tue, 29 Jul 2008 15:04:46 +0200 Subject: Defunct when using subprocess.Popen Message-ID: <6D3D064BBC122445A4577CE1895FA06501755913@afsegbgex1.af.se> An HTML attachment was scrubbed... URL: From francofuji at gmail.com Wed Jul 9 14:56:27 2008 From: francofuji at gmail.com (Francisco Perez) Date: Wed, 9 Jul 2008 14:56:27 -0400 Subject: About Google App Engine Message-ID: <30fdaa240807091156o2540b1ccpfd22f4e36fbf98d1@mail.gmail.com> Hello every body: Recently the Google boy's announce their last toy: Google App Engine, a really great idea. Although the GAE site have documentations and guides, i think it not covers the some of the best practices when we really build a web site. I mean layers, design patterns, etc. In the link bellow [1] we can find a completelly functional Ads site. And the best thing is that for all tht people like me that are not too good in english, the site has a Help (Ayuda) that explains the Maiking Of (Como se Hizo) of de site. There is a great explanation in spanish of MVC patterns and hot apply it building a web site. Check it. [1] http://bazar.appspot.com From babacity2 at gmail.com Thu Jul 24 16:57:18 2008 From: babacity2 at gmail.com (babacity2 at gmail.com) Date: Thu, 24 Jul 2008 13:57:18 -0700 (PDT) Subject: Shown on efukt com - Amazing porn video collection Message-ID: shown on efukt com . >>>>>>>>>>Best Collection of Efukt Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE shown on efukt com VIDEOS<<<<<<<<<<< . shown on efukt com From castironpi at gmail.com Tue Jul 29 23:28:48 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 29 Jul 2008 20:28:48 -0700 (PDT) Subject: static variables in Python? References: <115a132d-7edd-4b07-ba4f-7855577992d1@x41g2000hsb.googlegroups.com> Message-ID: On Jul 29, 8:38?pm, pigmartian wrote: > bearophileH... at lycos.com wrote: > > kj: > >> OK, I guess that in Python the only way to do what I want to do > >> is with objects... > > > There are other ways, like assigning the value out of the function, > > because Python functions too are objects: > > ... > > But I suggest you to use a class in this situation, it's often the way > > that will keep your code more bug-free, and more readable by near- > > casual readers too. Python philosophy asks you to write readable code > > instead of clever code when possible, this is a difference from Perl, > > I presume. > > > Bye, > > bearophile > > Here's a solution using decorators, I like it, but I'm biased: > > def staticAttrs(**kwds): > ? ? ? ? """ > ? ? ? ? Adds attributes to a function, akin to c-style > ? ? ? ? "static" variables > ? ? ? ? """ > > ? ? ? ? def _decorator(fcn): > ? ? ? ? ? ? ? ? for k in kwds: > ? ? ? ? ? ? ? ? ? ? ? ? setattr(fcn, k, kwds[k]) > ? ? ? ? ? ? ? ? return fcn > ? ? ? ? return _decorator > > @staticAttrs(n=0) > def rememberCalls(): > ? ? ? ? """ > ? ? ? ? >>> rememberCalls() > ? ? ? ? 0 > ? ? ? ? >>> rememberCalls() > ? ? ? ? 1 > ? ? ? ? >>> rememberCalls() > ? ? ? ? 2 > ? ? ? ? """ > ? ? ? ? print rememberCalls.n > ? ? ? ? rememberCalls.n += 1 > > ~Scott I like it too. It also thought of (implementation not shown): @has_locals def rememberCalls( self ): self.val= 0 self.ref= object( ) where self is preserved between calls and is an instance of a custom class, possibly empty. If you want more than one, but still preserved: rememberCallsA= has_locals( rememberCalls ) rememberCallsB= has_locals( rememberCalls ) You might want to make self a small and lightweight dict-only object: @has_locals def rememberCalls( dic ): dic['val']= 0 dic['ref']= object( ) From exarkun at divmod.com Tue Jul 29 10:47:53 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 29 Jul 2008 10:47:53 -0400 Subject: block/lambda In-Reply-To: <0b6a5dff-dae5-4cd8-9dfd-18737c4a8746@f36g2000hsa.googlegroups.com> Message-ID: <20080729144753.29191.615503627.divmod.quotient.8219@ohm> On Tue, 29 Jul 2008 07:26:38 -0700 (PDT), "jiri.zahradil at gmail.com" wrote: > >> 2. Will it be possible in Python 3.0 to do the following: >> >> >>> def dotimes(n, callable): >> >> for i in range(n): callable() >> >> >>> def block(): >> >> nonlocal i >> for j in range(i): >> print j, >> print > >dotimes seems ok and what is wrong with that function "block"? You do >not need to specify that i is "nonlocal", global i will be used. > >>>> i=10 >>>> def block(): > for j in range(i): > print j, > print >>>> block() >0 1 2 3 4 5 6 7 8 9 > Python doesn't have dynamic scoping. >>> def dotimes(n, callable): ... for i in range(n): ... callable() ... >>> def block(): ... for j in range(i): ... print j, ... print ... >>> def f(): ... dotimes(5, block) ... >>> f() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in f File "", line 3, in dotimes File "", line 2, in block NameError: global name 'i' is not defined >>> The "nonlocal" keyword in Python 3 won't do this, either. It's for referencing names in outer lexical scopes, not outer dynamic scopes. Jean-Paul From usenet at solar-empire.de Tue Jul 29 09:26:55 2008 From: usenet at solar-empire.de (Marc Christiansen) Date: Tue, 29 Jul 2008 15:26:55 +0200 Subject: Swap memory in Python ? - three questions References: Message-ID: Robert LaMarca wrote: > Hi, > > I am using numpy and wish to create very large arrays. My system is > AMD 64 x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a > 15 GB swap drive. > > The command I have been trying to use is; > g=numpy.ones([1000,1000,1000],numpy.int32) > > This returns a memory error. Works for me on AMD64x2, 2GB RAM, 3GB swap. With much paging of course ;) Process size of python 4019508kB. > A smaller array ([500,500,500]) worked fine.. About 0.5GB.. no surprise. > Two smaller arrays again crashed the system. Crash as in "computer reboots"? Strange. And you say, that two [500, 500, 500] arrays are two much? > So... I did the math. a 1000x1000x1000 array at 32 bits should be > around 4gb RAM... Obviously larger than RAM, but much smaller than the > swap drive. Sounds like either your kernel or python are not 64bit. For the kernel, have a look at /proc/meminfo, which value you get for VmallocTotal. I have VmallocTotal: 34359738367 kB. For python, check sys.maxint. If it's 2147483647, then you have a 32bit python. Mine says 9223372036854775807. > 1. So... does Numpy have a really lot of overhead? Or is my system > just not somehow getting to make use of the 15gb swap area. No. Yes. > 2. Is there a way I can access the swap area, or direct numpy to do > so? Or do I have to write out my own numpy cache system... > 3. How difficult is it to use data compression internally on numpy > arrays? 2 + 3: Should not be necessary. I just tried a 32bit python on my 64bit system, using Numeric instead of numpy (don't have a 32bit numpy ready): g=Numeric.zeros([1000,1000,1000],Numeric.Int32) Traceback (most recent call last): File "", line 1, in MemoryError: can't allocate memory for array g=Numeric.zeros([1000,1000,500],Numeric.Int32) succeeds. So it looks like you have a 32bit kernel. Marc From ptmcg at austin.rr.com Thu Jul 31 18:58:01 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 31 Jul 2008 15:58:01 -0700 (PDT) Subject: find and replace with regular expressions References: Message-ID: <8160cc86-d0bd-444a-bc93-da732c76e3bb@c65g2000hsa.googlegroups.com> On Jul 31, 3:07?pm, chrispoliq... at gmail.com wrote: > > middle_abbr = re.compile('[A-Za-z0-9]\.[A-Za-z0-9]\.') > When defining re's with string literals, it is good practice to use the raw string literal format (precede with an 'r'): middle_abbr = re.compile(r'[A-Za-z0-9]\.[A-Za-z0-9]\.') What abbreviations have numeric digits in them? I hope your input string doesn't include something like this: For a good approximation of pi, use 3.1. -- Paul From stochashtic at yahoo.ca Mon Jul 28 03:40:19 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 28 Jul 2008 09:40:19 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> <4889e5bc$1@news2-rz-ap.ethz.ch> <331bd56e-e446-4b08-bf72-be7482051f32@y22g2000prd.googlegroups.com> Message-ID: <488d77e3$1@news2-rz-ap.ethz.ch> On Fri, 25 Jul 2008 08:08:57 -0700, Iain King wrote: > On Jul 25, 3:39 pm, Suresh Pillai wrote: >> That's a good comparison for the general question I posed. Thanks. >> Although I do believe lists are less than ideal here and a different >> data structure should be used. >> >> To be more specific to my case: >> As mentioned in my original post, I also have the specific condition >> that one does not know which nodes to turn ON until after all the >> probabilities are calculated (lets say we take the top m for example). >> In this case, the second and third will perform worse as the second one >> will require a remove from the list after the fact and the third will >> require another loop through the nodes to build the new list. > > So you need to loops through twice regardless? i.e. loop once to gather > data on off nodes, do some calculation to work out what to turn on, then > loop again to turn on the relevant nodes? If so, then I think the > functions above remain the same, becoming the 2nd loop. Every iteration > you do a first loop over the off_nodes (or them all for (1)) to gather > the data on them, perform your calculation, and then perform one of the > above functions (minus the setup code at the begining; basically > starting at the 'for') as a second loop, with the goes_on function now > returning a value based on the calculation (rather than the calculation > itself as I had it). Performance should be similar. > > Iain If do I settle on an explicit loop to remove the nodes turned ON, then I realised this weekend that I could do this in the next iteration of the simulation (first loop above) and save some iteration overhead (the if checking will still be there of course). And thanks for pointing out that constructing a new list, for long lists, is faster than simple removal. It's obvious but I never really thought of it; good tip. From marcus at internetnowasp.net Sat Jul 12 22:08:22 2008 From: marcus at internetnowasp.net (Marcus Low) Date: Sun, 13 Jul 2008 10:08:22 +0800 Subject: Someone enlightened me Message-ID: <48796396.9090805@internetnowasp.net> Can someone explain to me, why the behaviour below is different when u remark "lister" and unremark "self.lister"? #-------------------------------------------------------------- class abc : # remark this later and unremark "self.lister" lister = [] def __init__ (self, val): #self.lister = [] self.lister.append(val) #-------------------------------------------------------------- globallist = [] #-------------------------------------------------------------- def test () : global l for x in range(10) : o = abc(x) globallist.append(o) o = "" for i in globallist : print i.lister #-------------------------------------------------------------- test() #-------------------------------------------------------------- From jstrickler at gmail.com Wed Jul 16 16:59:51 2008 From: jstrickler at gmail.com (John S) Date: Wed, 16 Jul 2008 13:59:51 -0700 (PDT) Subject: how to match whole word References: <97461ec5-151a-4527-a5fa-c5da07941e46@l42g2000hsc.googlegroups.com> Message-ID: <31b6a6c2-e152-418d-b5a1-477dc3dd15aa@s50g2000hsb.googlegroups.com> On Jul 16, 9:38 am, Peng Yu wrote: > On Jul 15, 10:29 pm, Gary Herron wrote: > > > > > Peng Yu wrote: > > > Hi, > > > > The following code snippet is from /usr/bin/rpl. I would like the it > > > to match a word, for example, "abc" in ":abc:". But the current one > > > would not match "abc" in ":abc:". I tried to modify it myself. Would > > > you please let me know what is the corrected way to do it? > > > > Thanks, > > > Peng > > > > if opts.whole_words: > > > regex = re.compile(r"(?:(?<=\s)|^)" + re.escape(old_str) + r"(?=\s| > > > $)", > > > opts.ignore_case and re.I or 0) > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > The regular expression "\w+" will match (what might be your definition > > of) a word, and in particular will match abc in :abc:. Regular > > expressions have lots of other special \-sequences that might be worth > > your while to read about: http://docs.python.org/lib/re-syntax.html > > > Gary Herron > > I didn't read the docs and tried the following code. > > regex = re.compile(r"\A" + re.escape(old_str) + r"\Z", > opts.ignore_case and re.I or 0) > > But I'm not sure why it is not working. > > Thanks, > Peng Not sure why you picked \A and \Z -- they are only useful if you are using the re.M flag. What you want is \b -- match word boundary, on either side of your word: regex = re.compile(r"\b" + re.escape(old_str) + r"\b",re.I) re.I is the same as re.IGNORECASE. More than one option may be OR'ed together. There's no such thing as "re.O" in Python. I can understand where you get the idea, as there is an 'o' modifier for REs in Perl. To summarize, \A and \Z match the beginning and end of a STRING, while \b matches the beginning or end of a WORD. -- john From modelnine at modelnine.org Tue Jul 29 05:15:05 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Tue, 29 Jul 2008 11:15:05 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: <200807291115.05701.modelnine@modelnine.org> Am Dienstag, 29. Juli 2008 10:37:45 schrieb Carl Banks: > You keep bringing up this notion of "more complex with no benefit", > which I'm simply not interested in talking about that at this time, > and I won't respond to any of your points. I am seeking the answer to > one question: whether "if x" can usefully do something a simple > explicit test can't. Everyone already knows that "if x" requires > fewer keystrokes and parses to fewer nodes. Yes, there are quite a lot of use cases. Think of a polymorphic function, where the input can be any object that implements the iterator protocol (concerning base types, I'm thinking of strings, tuples, lists, dicts and sets here, which are all iterable and yield a chain of singular values) and you want to check whether the iterable object is empty or not for special-casing that. "if x" uses the special interface method __nonzero__() if that's implemented (which all of the above types implement as returning True iff the container yields at least one value when iterated over, i.e., it isn't empty), and falls back to a test for __len__() != 0, otherwise x is considered to be true. Now, explicitly comparing x against the five "empty" values of the container types I specified above would be broken design in such a function: when I implement a container class myself, which implements the __iter__() and __nonzero__() methods, I can directly use it with the polymorphic function I wrote, and the special case for an empty container will work out of the box. In the case of explicit comparisons, I have to modify the polymorphic function to accept my container type in addition to those it already processes to be able to special-case the empty container for my type. I can't dig up a simple example from code I wrote quickly, but because of the fact that explicit comparisons always hamper polymorphism (which might not be needed initially, but you never know what comes up later, thinking of reusability of components), I personally always stick to the idiom "if x" rather than comparing it to an empty value, even when I'm sure that the type of x is a singular type. Additionally, IMHO "if x" is so much more readable than "if x != ". Just my 2 (euro)cents. -- Heiko Wundram From bsagert at gmail.com Wed Jul 16 13:42:18 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Wed, 16 Jul 2008 10:42:18 -0700 (PDT) Subject: For_loops hurt my brain. Message-ID: <4874c21f-befa-4e9f-a99d-486cc9c9b5b8@d77g2000hsb.googlegroups.com> This script uses a simple for loop to zip some files. However I am repeating code that cries out for a nested loop. My two lists of files_to_be_zipped (spare and seekfacts) are of uneven length so I can't seem to decipher the "for_logic". I would appreciate any help. Thanks, Bill import zipfile import os zips = [ 'c:/spare.zip', 'c:/seekfacts.zip' ] spare = [ 'c:/spare/huge.fm3', 'c:/spare/huge.wk3' ] seekfacts = [ 'c:/seekfacts/bookmark.html', 'c:/seekfacts/index.htm', 'c:/seekfacts/seek.css', 'c:/seekfacts/seek.js' ] zFile = zipfile.ZipFile(zips[0], 'w') for files in spare: zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED) zFile.close() zFile = zipfile.ZipFile(zips[1], 'w') for files in seekfacts: zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED) zFile.close() From draeath.spamtrap at gmail.com Thu Jul 24 22:26:09 2008 From: draeath.spamtrap at gmail.com (draeath) Date: Fri, 25 Jul 2008 02:26:09 GMT Subject: Your message to CMake awaits moderator approval References: Message-ID: On Thu, 24 Jul 2008 18:43:34 -0400, cmake-bounces wrote: > Your mail to 'CMake' with the subject > > Status > > Is being held until the list moderator can review it for approval. > > The reason it is being held: > > Post by non-member to a members-only list > > Either the message will get posted to the list, or you will receive > notification of the moderator's decision. If you would like to cancel > this posting, please visit the following URL: > > Should this be showing up in a usenet group? From stefan_ml at behnel.de Fri Jul 11 01:31:41 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 11 Jul 2008 07:31:41 +0200 Subject: B-Soup: broken iterator, tag a keyword? In-Reply-To: <413d8bc0-6156-4502-93c1-8c8790128f56@d45g2000hsc.googlegroups.com> References: <413d8bc0-6156-4502-93c1-8c8790128f56@d45g2000hsc.googlegroups.com> Message-ID: <4876F03D.40407@behnel.de> Hi, Brendan wrote: > I have the following using Beautiful Soup: > > soup = BeautifulSoup(data) > tags = soup.findAll(href=re.compile("/MER_FRS_L2_Canada/MER_FRS_\S > +gz")) > for tag in tags: > print tag['href'] > print tag.parent.nextSibling.string > print tag.parent.nextSibling.nextSibling.string > print tag.parent.nextSibling.nextSibling.nextSibling.string > print > tag.parent.nextSibling.nextSibling.nextSibling.nextSibling.contents[0].string It's pretty impossible that the problem is the name "tag" here. But since you didn't state what the actual problem is, let me suggest not to parse markup with regular expressions in general (which BS does). Use a real XML/HTML parser for that. lxml will work just fine (and it also has a nicer API). http://codespeak.net/lxml/ Stefan From rridge at csclub.uwaterloo.ca Thu Jul 31 04:24:48 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Thu, 31 Jul 2008 04:24:48 -0400 Subject: Change PC to Win or Windows References: Message-ID: Dennis Lee Bieber wrote: > It gets even worse... No Windows-based "PC" has ever used the >"PowerPC" processor -- which had been a staple of the Macintosh before >they went Intel... Actually the were personal computers sold using PowerPC processors that ran Windows NT. I even remember seeing one that had ISA slots. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From jkugler at bigfoot.com Tue Jul 1 14:25:48 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Tue, 01 Jul 2008 10:25:48 -0800 Subject: Classes for processing/parsing Wiki Markup text References: <170543c70807010931x16938234n9df68ee3c6d0319a@mail.gmail.com> Message-ID: Michael Mabin wrote: > Does anyone know if there are any generally available classes for parsing > various wiki markup formats? Several here: http://pypi.python.org/pypi?%3Aaction=search&term=wiki&submit=search I'm sure you could find a good one, and add your own markup if needed. j From gh at ghaering.de Mon Jul 28 07:01:58 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 28 Jul 2008 13:01:58 +0200 Subject: Google Group: architectgurus In-Reply-To: References: Message-ID: Dear Guru, Sudhakar Chavali wrote: > Hi > > I have created a group called architectgurus (http://groups.google.com/ > group/architectgurus) or architectgurus at googlegroups.com . > Irrespective of technology, vendor, domain I will be discussing and > share my thoughts in homogenous and harmonious way. If you are > interested *even you* can join and contribute your thoughts in this > group. My intention doing these activities is to spread the knowledge > and thoughts across the globe. What? even me? That's really nice of you. -- Gerhard From bulg at ngs.ru Mon Jul 14 03:25:15 2008 From: bulg at ngs.ru (Yosifov Pavel) Date: Mon, 14 Jul 2008 00:25:15 -0700 (PDT) Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> <6e0564F4bvr4U2@mid.uni-berlin.de> Message-ID: <1ca3ddf2-7d41-44ae-8b5a-80d7be7b88eb@f36g2000hsa.googlegroups.com> > `tee()` doesn't copy the iterator or its internal state but just caches > it's results, so you can iterate over them again. That makes only sense > if you expect to use the two iterators in a way they don't get much out of > sync. If your usage pattern is "consume iterator 1 fully, and then > re-iterate with iterator 2" `tee()` has no advantage over building a list > of all results of the original iterator and iterate over that twice. > `tee()` would be building this list anyway. It's interesting and a concrete answer. Thanks a lot. > Because it's often not possible without generating a list with all > results, and the advantage of a low memory footprint is lost. > > Ciao, > Marc 'BlackJack' Rintsch Seems like "monada". But I think is possible to determine when there is a bounded external state (side-effects) or not, may be is needed some new class-protocol for it... or something else. Or another way: iterators may be re-iterable always, but if programmer need to point to the extra- (external) state, he has to raise some a special exception in __iter)) method... OK, it's only fantasies about language design :-) --pavel From sjmachin at lexicon.net Fri Jul 18 02:32:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 17 Jul 2008 23:32:47 -0700 (PDT) Subject: storing references instead of copies in a dictionary References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> <7c26ca26-be96-4e8c-8eb5-e43bd78e4e70@v21g2000pro.googlegroups.com> Message-ID: <374d1d4f-e958-455c-8e60-048c55bc493f@q28g2000prh.googlegroups.com> On Jul 18, 4:26?pm, castironpi wrote: > I delicately ask for an example in natural language and daily life in > which we change what object a name refers to, her, him, it, ... i.e. any pronoun From phil.lemelin at gmail.com Fri Jul 18 08:38:03 2008 From: phil.lemelin at gmail.com (phil lemelin) Date: Fri, 18 Jul 2008 08:38:03 -0400 Subject: Question regarding os.write() and write() method of a file descriptor Message-ID: Good Day python users, I have a question regarding os.write and the write method of a file descriptor object. My python was written on linux, under python 2.4 and I've recently migrated to python 2.5. My problem came from a pipe I used to to open and write to using : fd = os.open("myfifo","w+") os.write(fd,'some boring stuff\n') os.close(fd) I'm pretty sure that it worked on a previous version of python and linux but, on my mandriva 2008, running python 2.5, I get the following exception : os.write(fd,'some boring stuff\n') exceptions.TypeError: an integer is required Now, I solved my problem by changing my code to the following : fd open("myfifo","w+") fd.write("some less boring stuff\n") fd.close() I still cant explain why it works with the file descriptor method and i'm seeking an explanation. Please, forgive me if it's a dumb question, but i'm just trying to get better at python. I hope someone will take time to help me out. -- Philippe-Alexandre Lemelin -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Jul 24 05:20:05 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 11:20:05 +0200 Subject: Requires a character ... !! In-Reply-To: References: Message-ID: karthikbalaguru wrote: > I am new to python . I am face few problems related with > python and iam trying to resolve it. > > The below is the error that i get when i invoke my application by > giving > the necessary input file. > > [root at localhost hello]# Analyzer hello_input > Loading debug info: hello_input > Traceback (most recent call last): > File "/usr/local/SDK/host/bin/Analyzer", line 694, in ? > app.dbg.readObjectInfo(elf) > File "/usr/local/SDK/host/bin/debugprocessor.py", line 427, in > readObjectInfo > self.privateProcessorDwarfTree.readProcessorDwarfTree(filename) > File "/usr/local/SDK/bin/debugprocessor.py", line 314, in > readDwarfTree > if "DW_OP_reg" in value: > TypeError: 'in ' requires character as left operand > > Is this related with the version conflicts ? > Should i need to configure any environment variables or change some > source code. You should run the code on a Python version that supports the features your code is using. Support for arbitrary strings on the left side of the "in" operator was added in Python 2.3, which was released in 2003. What software is this? If you've written it yourself, make sure to use only features supported by the Python version you're actually using. If it's written by someone else, please read the requirements section for the software you're using, and follow the instructions in there. (hasn't people been telling you this about a hundred times before in this forum? or was that some other guy who also kept insisting on running some program on a python version it didn't support?) From fouff at fouff.com Thu Jul 3 05:34:16 2008 From: fouff at fouff.com (Fouff) Date: Thu, 03 Jul 2008 11:34:16 +0200 Subject: Creating an .exe with Tkinter involved In-Reply-To: References: Message-ID: Alex Bryan a ?crit : > I know this is possible so someone out there should be able to help me! > Okay, I have a program that uses Tkinter, and BeautifulSoup. I don't > think it should be a problem. I want to create an exe of it. I have > py2exe but I don't really know how to work it. I read their tutorial > thing and did a setup that looked something like this: > > from distutils.core import setup > import py2exe > > setup(console['myFunProgram.py']) > > (isn't really called myFunProgram) > > This seems terribly wrong however because... it isn't a console app. So > I am wondering if anyone can show me how or point me in the right > direction to a place where I can learn how to do this. I would > appreciate it! Hi. If your program isn't a concole one, maybe should you rename it .pyw and then in your setup.py file, replace the line > setup(console['myFunProgram.py']) by this one setup(windows=["myFunProgram.pyw"]) I use it under MS windows (I don't know if it is your case too). You will find more informations here http://www.py2exe.org/index.cgi/ListOfOptions and more generally at http://www.py2exe.org/ Fouff From bearophileHUGS at lycos.com Thu Jul 31 13:43:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 31 Jul 2008 10:43:11 -0700 (PDT) Subject: Non Continuous Subsequences References: <9e5a3$4891e9f5$18607848$1746@KNOLOGY.NET> Message-ID: <3e475fac-4ce6-41da-8f7c-1c013756656b@25g2000hsx.googlegroups.com> Bruce Frederiksen: Your solution is a bit different from what I was thinking about (I was thinking about a generator function, with yield), but it works. This line: > return itertools.chain( > itertools.imap(lambda ys: x + ys, ncsub(xs, s + p1)), > ncsub(xs, s + p2)) Can be written in a simpler way: return chain((x + ys for ys in ncsub(xs, s + p1)), ncsub(xs, s + p2)) I'll think more about all this, bye and thank you, bearophile From mariano.mara at gmail.com Thu Jul 3 00:37:15 2008 From: mariano.mara at gmail.com (Mariano Mara) Date: Thu, 03 Jul 2008 01:37:15 -0300 Subject: Queue/Priority Needed In-Reply-To: <21935b370807021426l11f1fa0ayc52593cc184869b3@mail.gmail.com> References: <21935b370807021426l11f1fa0ayc52593cc184869b3@mail.gmail.com> Message-ID: <486C577B.5010809@gmail.com> Keith Nation wrote: > I'm still very new to python, and I have a question about how to > prioritize jobs in a queue. > You can use the python 2.6 priority queue implementation: $ python Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import heapq >>> import Queue >>> >>> class PriorityQueue(Queue.Queue): ... """Variant of Queue that retrieves open entries in ... priority order (lowest first). ... Entries are typically tuples of the form: (priority number, ... data) ... This class can be found at: Python-2.6a3/Lib/Queue.py ... """ ... maxsize = 0 ... def _init(self, maxsize): ... self.queue = [] ... def _qsize(self, len=len): ... return len(self.queue) ... def _put(self, item, heappush=heapq.heappush): ... heappush(self.queue, item) ... def _get(self, heappop=heapq.heappop): ... return heappop(self.queue) ... >>> class example(object): ... def __init__(self, p1, p2, p3, p4): ... self.p1 = p1 ... self.p2 = p2 ... self.p3 = p3 ... self.p4 = p4 ... >>> pq = PriorityQueue() >>> ex = example('Task1', 'v03', '-start', 'Bonnie') >>> pq.put((1, ex)) >>> ex = example('Task3', 'v01', '-start', 'Bob') >>> pq.put((3, ex)) >>> ex = example('Task2', 'v01', '-start', 'Billy') >>> pq.put((2, ex)) >>> pr, ex = pq.get() # prints task 1 >>> print ex.p1, ex.p2, ex.p3, ex.p4 Task1 v03 -start Bonnie >>> pr, ex = pq.get() # prints task 2 >>> print ex.p1, ex.p2, ex.p3, ex.p4 Task2 v01 -start Billy From ethan at stoneleaf.us Mon Jul 7 19:12:27 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 07 Jul 2008 15:12:27 -0800 Subject: numeric emulation and __pos__ Message-ID: <4872A2DB.4090609@stoneleaf.us> Greetings, List! I'm working on a numeric data type for measured values that will keep track of and limit results to the number of significant digits originally defined for the values in question. I am doing this primarily because I enjoy playing with numbers, and also to get some experience with unit testing. At this point I have the __init__ portion finished, and am starting on the various operator functions. Questions for the group: 1) Any reason to support the less common operators? i.e. <<, >>, &, ^, | 2) What, exactly, does .__pos__() do? An example would help, too. Thanks for the feedback. -- Ethan From fredrik at pythonware.com Fri Jul 25 07:50:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 13:50:25 +0200 Subject: Automatically loading and initialising objects from a plugins directory In-Reply-To: <4889B888.8000600@ecs.soton.ac.uk> References: <488607BC.3040204@ecs.soton.ac.uk> <4889B888.8000600@ecs.soton.ac.uk> Message-ID: Dave Challis wrote: > I'll have a look into metaclasses too, haven't stumbled upon those yet > at all. It's a potentially brain-exploding topic, though, so if the above solution works for you, you might want to leave it at that ;-) But very briefly, a metaclass is a something that's responsible for creating a class, much like an ordinary class is responsible for creating an object. When Python executes the following statement, class Spam: attrib = 1 def func(self): pass # <-- end of class statement it will create a new scope for the class content, execute the class body, and then, when it reaches the end, call the "metaclass" to create the actual class object. The metaclass is given the requested name ("Spam" in this case), any base classes, and a dictionary containing everything from the class scope ("attrib" and "func", in this case). The thing that's returned is assigned to the "Spam" variable. The default metaclass ("type") just creates an ordinary class object, but if you replace that with your own metaclas, you can completely override that behaviour, or just extend it (e.g. by registering the subclasses in a common registry). Like, say, this: registry = [] # list of subclasses class Plugin(object): class __metaclass__(type): def __init__(cls, name, bases, dict): type.__init__(name, bases, dict) registry.append((name, cls)) class SpamPlugin(Plugin): pass class BaconPlugin(Plugin): pass for name, cls in registry: if cls is not Plugin: print name, cls Here, the presence of an inner __metaclass__ class (which is a subclass of "type") causes Python's class machinery to use that class instead of "type" when creating class objects for Plugin or any subclass thereof. The extra code in the __init__ method just all plugins to a list. For more on this, see e.g. http://www.python.org/download/releases/2.2/descrintro/#metaclasses From dullrich at sprynet.com Wed Jul 9 13:22:47 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Wed, 09 Jul 2008 12:22:47 -0500 Subject: "in"consistency? References: Message-ID: In article , Terry Reedy wrote: > David C. Ullrich wrote: > > In article , > > Terry Reedy wrote: > > >>> Is there a reason for the inconsistency? I would > >>> have thought "in" would check for elements of a > >>> sequence, regardless of what sort of sequence it was... > >> It is not an inconsistency but an extension corresponding to the > >> limitation of what an string element can be. > > > > It's an inconsistency. That doesn't mean it's a bad thing or that > > I want my money back. It may well be a reasonable inconsistency - > > strings _can_ work that way while it's clear lists had better not. > > But it's an inconsistency. > > To decisively argue 'inconsistency' as factual or not, versus us having > divergent opinions, you would have to supply a technical definition ;-) > The math definition of 'leading to a contradiction' in the sense of > being able to prove False is True, does not seem to apply here. > > However, > a) In common English, 'in' and 'contains', applied to strings of > characters (text), is understood as applying to substrings that appear > in the text. This is also true of many other programming languages. > 'Dictionary' contains 'diction'. This is even the basis of various word > games. > b) Python otherwise allows operators to vary in meaning for different > classes. > > In any case, back to your original question: the extension of meaning, > 'inconsistent' or not, was deliberated and adopted on the basis that the > usefulness of the extension would outweigh the confusion wrought by the > class-specific nature of the extension. (In other words, threads such > as this *were* anticipated ;-) I wasn't saying that the fact that the behavior of "in" for strings is inconsistent with the behavior for lists was a bad thing - I was just asking about the reason for it. (I also wasn't claiming that it was inconsistent with the common English usage of "in"...) People have pointed out that "in" for strings _can_ work that way, while (of course) "in" for lists had better not. That's fine. > Terry Jan Reedy -- David C. Ullrich From fetchinson at googlemail.com Wed Jul 9 23:58:32 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 9 Jul 2008 20:58:32 -0700 Subject: sort(cmp=func) In-Reply-To: References: Message-ID: > I have a list of objects that generate code. Some > of them depend on others being listed first, to > satisfy dependencies of others. > > I wrote a cmp function something like this: > > def dep_cmp(ob1, ob2): > > if ob1.name in ob2.deps: > return -1 > else: > return 1 > > I also tried returning 0 when there were no dependency > relationships between the objects. > > This failed, because every object was not compared with > ever other. I imagine that this is because sort assumes > that if a > b and b > c, then a > c. In my case, this > isn't really true. If a is not dependent on b, and > b is not dependent on c, that doesn't mean that a is not > dependent on c. > > Is there a better way? It's only meaningful to talk about sorting if your particular definition of "<" is transitive. I.e. a < b and b < c should imply a < c. If this is not satisfied, it doesn't make sense to sort according to your "<" definition. It's just not a well-defined operation and no trick will make it work. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From workitharder at gmail.com Sun Jul 13 14:32:22 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 13 Jul 2008 11:32:22 -0700 (PDT) Subject: socket.connect() hangs in SYN_SENT state. References: Message-ID: <804bccb2-42c7-42e9-8f50-7a780d3438fd@j22g2000hsf.googlegroups.com> On Jul 13, 1:14?am, Miles wrote: > On Sat, Jul 12, 2008 at 11:23 PM, bukzor wrote: > > I'm connecting to an apache2 process on the same machine, > > for testing. When looking at netstat, the socket is in the SYN_SENT > > state, like this: > > > $netstat -a -tcp > > tcp ? ? ? ?0 ? ? ?0 *:www ? ? ? ? ? ? ? ? ? *:* LISTEN ? ? ?7635/apache2 > > tcp ? ? ? ?0 ? ? ?1 bukzor:38234 ? ? ? ? ? ?adsl-75-61-84-249.d:www SYN_SENT ? ?9139/python > > > Anyone know a general reason this might happen? Even better, a way to > > fix it? > > That socket connection is to a remote machine, not the same one. ?Your > test code works fine for me. ?The "hang then crash" (and I'm assuming > "crash" here means an uncaught exception) just means that your packets > are being silently ignored by whatever machine you're actually > attempting to connect to. It's possible that your machine has odd DNS > settings causing buzkor.hopto.org to resolve to the wrong address. > > -Miles I'm connecting to my machine through the internet, and the resolved URL of my router is what you're seeing above. If you run the code above you'll see what I mean. Thanks tho, --Buck From mrkafk at gmail.com Sun Jul 13 12:55:11 2008 From: mrkafk at gmail.com (mk) Date: Sun, 13 Jul 2008 18:55:11 +0200 Subject: Magic? In-Reply-To: References: Message-ID: > However, it appears that somehow this object prints the value of 's' > attribute without me setting any specific methods to do that: > > >>> astr = lstr('abcdef') > >>> astr > 'abcdef' > >>> astr.swapcase() > 'ABCDEF' Correction: it doesn't really get the value from _s attribute: >>> astr = lstr('abcdef') >>> astr.s 'abcdef' >>> astr.s='xyzzy' >>> astr 'abcdef' >>> astr.s 'xyzzy' So my updated question is where does this lstr() instance keep the original value ('abcdef')? It obviously has smth to do with inheriting after str class, but I don't get the details of the mechanism. From mathieu.prevot at gmail.com Mon Jul 7 13:32:31 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Mon, 7 Jul 2008 19:32:31 +0200 Subject: do a sed / awk filter with python tools (at least as fast) Message-ID: <3e473cc60807071032s47afd4eap42adb5c1bddc0171@mail.gmail.com> Hi, I use in a bourne shell script the following filter: sed '/watch?v=/! d;s/.*v=//;s/\(.\{11\}\).*/\1/' \ | sort | uniq | awk 'ORS=" "{print $1}' that give me all sets of 11 characters that follows the "watch?v=" motif. I would like to do it in python on stdout from a subprocess.Popen instance, using python tools rather than sed awk etc. How can I do this ? Can I expect something as fast ? Thanks, Mathieu From comp.ogz at gmail.com Thu Jul 3 10:40:06 2008 From: comp.ogz at gmail.com (Oguz Yarimtepe) Date: Thu, 3 Jul 2008 17:40:06 +0300 Subject: detection of unplugged cable In-Reply-To: <20831c740807022158l38648a61l4966d11fae20297d@mail.gmail.com> References: <20831c740807022158l38648a61l4966d11fae20297d@mail.gmail.com> Message-ID: <20831c740807030740k16f90c1fx78a4649ca70c18ea@mail.gmail.com> Ok here is the exact problem. I have both S-Video, HDMI and VGA out at my machine. I tried to clone the LCD display to HDMI out but it worked only when i disable the LCD and send the display to HDMI. So when the HDMI cable is unplugged i want to revert the process and enable the LCD. I need to detect this signal or whatever it is. I tried with xrandr by thinking that when i used the --output LMDS --off i will see "LMDS disconnect" at the output but it was not true. So i should find a better way. Any idea? I am using Ubuntu Hardy with an Intel VGA card. -- O?uz Yar?mtepe From siddhantgoel at gmail.com Sun Jul 20 05:42:44 2008 From: siddhantgoel at gmail.com (Siddhant) Date: Sun, 20 Jul 2008 02:42:44 -0700 (PDT) Subject: Problems with curses References: Message-ID: On Jul 13, 6:22?pm, Clay Hobbs wrote: > > On Sat, 12 Jul 2008 20:49:56 -0400, Clay Hobbs wrote: > > > > ? ? ? Unfortunately, the error message isn't very helpful. > > > But it would be helpful to tell it. ?If you get exceptions, always > > copy'n'paste the traceback here. ?People might know what the exception > > means and share their wisdom. > > Here is the error message: > > Traceback (most recent call last): > ? File "./text_adventure.py", line 25, in > ? ? curses.wrapper(main) > ? File "/usr/lib/python2.5/curses/wrapper.py", line 44, in wrapper > ? ? return func(stdscr, *args, **kwds) > ? File "./text_adventure.py", line 19, in main > ? ? stdscr.scroll(3) > _curses.error: scroll() returned ERR > > -- Ratfink You need to put a stdscr.scrollok(True) in the beginning. That should avoid the exception. -Siddhant From alex.gaynor at gmail.com Sun Jul 13 01:33:20 2008 From: alex.gaynor at gmail.com (alex.gaynor at gmail.com) Date: Sat, 12 Jul 2008 22:33:20 -0700 (PDT) Subject: filtering keyword arguments References: <633d6159-7803-4d9b-8f16-2a4a0a197a86@t54g2000hsg.googlegroups.com> Message-ID: On Jul 12, 10:44?pm, Amir wrote: > How do you filter keyword arguments before passing them to a function? > > For example: > > def f(x=1): return x > > def g(a, **kwargs): print a, f(**kwargs) > > In [5]: g(1, x=3) > 1 3 > > In [6]: g(1, x=3, y=4) > TypeError: f() got an unexpected keyword argument 'y' > > Is there a way to do something like: > > def g(a, **kwargs): print a, f(filter_rules(f, **kwargs)) > > so only {'x': 3} is passed to f? > > I was hoping for a pythonic way of doing what in Mathematica is done > by FilterRules: > > http://reference.wolfram.com/mathematica/ref/FilterRules.html Sure, you could do: def call_with_relevant_args(func, kwargs): kwargs = dict([(k, v) for k, v in kwargs.iteritems() if k in func.func_code.co_varnames]) return func(**kwargs) From russblau at hotmail.com Wed Jul 30 17:55:03 2008 From: russblau at hotmail.com (Russell Blau) Date: Wed, 30 Jul 2008 17:55:03 -0400 Subject: Tkinter- Possibly a basic question References: <59dee72b-3fb6-414b-ab49-33cab8f9c9e8@26g2000hsk.googlegroups.com> Message-ID: wrote in message news:59dee72b-3fb6-414b-ab49-33cab8f9c9e8 at 26g2000hsk.googlegroups.com... >I hate to do this, but I've thoroughly exhausted google search. Yes, > it's that pesky root window and I have tried withdraw to no avail. I'm > assuming this is because of the methods I'm using. I guess my question > is two-fold. > 1) How do I get rid of that window? > 2) Any comments in general? I am just learning python (and coding with > classes), so I'm sure there are things I should pound into my head > before I learn bad habits. At the risk of overlooking something obvious, why don't you make your App class a subclass of Tkinter.Frame instead of Tkinter.Toplevel, and just pack it into the root window instead of worrying about how to get rid of the root window? Just delete "root.withdraw()" and then add "a.pack()" before "a.mainloop()". Russ From duncan.booth at invalid.invalid Sat Jul 19 12:10:06 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Jul 2008 16:10:06 GMT Subject: __del__ methods References: Message-ID: "Robert Rawlins" wrote: > I like this idea, I can definitely see the benefits to working with > this concept. One things I will take this quick opportunity to ask, > even though it's a little OT: > > What is the benefit of extending the base 'object' class? What does > that give me that en empty, non subclassed object doesn't? > Habit: certain things (such as properties) don't work properly with old-style classes, so it is good practice always to use new-style classes and that way you won't forget to do it when it really does matter. >> You can use gc.get_referrers() to find everything that references a >> particular objects and gradually trace backwards until you find the > problem >> reference (it is tricky though as any code which does this needs to >> ignore > >> its own references to the object in question). > > Yes, that's a very nice concept and like you say gives you quite a > nice visual reference of what objects are and aren't being destroyed. > See http://groups.google.co.uk/group/comp.lang.python/browse_thread/thread/394ba5b48f83ebfb/237dc92f3629dd9a#237dc92f3629dd9a for the code (although I seem to remember that there are some problems with that code so caveat emptor). From gagsl-py2 at yahoo.com.ar Fri Jul 11 04:46:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Jul 2008 05:46:31 -0300 Subject: Problems Returning an HTTP 200 Ok Message References: <1cf880cc-2036-42dc-8217-d52a714c1710@a70g2000hsh.googlegroups.com> <9bc65e72-be16-4f73-9dfb-6ddeaae34c21@m73g2000hsh.googlegroups.com> <8596af5b-fd0a-413e-8051-62d650e9a153@8g2000hse.googlegroups.com> Message-ID: En Thu, 10 Jul 2008 18:10:46 -0300, Guy Davidson escribi?: > On Jul 10, 12:38?pm, samwyse wrote: >> On Jul 10, 1:50?pm, Guy Davidson wrote: >> >> > My code (attached below) us supposed to read an HTTP Post message >> > coming from a power meter, parse it, and return a proper HTTP 200 Ok >> > message. The problem is that the socket fails to send the entire >> > message as one message, creating a fragmented message which the power >> > meter then fails to read and accept. >> >> From your description, I get the feeling that your power meter has a >> broken network stack, and you're trying to program around it. ?You >> need to repair the meter. > > The meter sends HTTP Post messages, and expects, as a reply, an HTTP > 200/Ok message. > > I try to send the following message, using the socket.send() command: > > 'HTTP/1.1 200 OK\r\nDate: Thu, 10 July 2008 14:07:50 GMT\r\nServer: > Apache/2.2.8 (Fedora)\r\nX-Powered-By: PHP/5.2.4\r\nContent-Length: 4\r > \nConnection: close\r\nContent-Type: text/html; charset=UTF-8\r\n\r > \n[0]\n' > > However, when I snoop on the packets in wireshark, here's what I see: > > HTTP/1.1 200 Ok: > > HTTP/1.1 200 OK > Date: Wed, 09 July 2008 14:55:50 GMT > Server: Apache/2.2.8 (Fedora) > X-Powered-By: > > Continuation or non-HTTP traffic: > > PHP/5.2.4 > Content-Length: 4 > Connection: close > Content-Type: text/html; charset=UTF-8 > > [0] > > It splits into two packages, which the meter can't read, and the > communication breaks down there. > > Any ideas? As Guy Davidson has already pointed out, this is a problem in the meter TCP implementation, and you should ask the vendor to fix it. (Anyway, looks like "somewhere" there is a buffer size of 100 bytes or so, very small). As a workaround, try to shorten your HTTP response; I guess the Server and X-Powered-By headers are not required; the Date probably isn't either; and if all your responses are like "[0]" a simple "Content-Type: text/plain" may suffice (the meter might just ignore it, anyway). -- Gabriel Genellina From hyugaricdeau at gmail.com Tue Jul 22 09:55:23 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Tue, 22 Jul 2008 06:55:23 -0700 (PDT) Subject: regarding SWIG References: <12e21dec-b269-4c34-9492-98424d207397@w7g2000hsa.googlegroups.com> Message-ID: On Jul 22, 5:34?am, Anish Chapagain wrote: > Hi.. > I'm new to SWIG and need to create Wrapper for C code, > so, I have installed the SWIG already but doesnot know how to run it > for generating Interface file... > My C code is in message.c so what do i need to do the first > step..uisng SWIG..i read the documentation but cannot grasp creating > interface file. > > thank's anish Not sure where you're having trouble. I can understand if there's a language barrier, but I think that the introductory SWIG documentation is pretty darn straightforward, even if you just look at the code, so I don't think there's anything that could be said here that's any more clear, as far as the basics are concerned. You'd have to explain exactly what it is you're stuck on. From straton at lampsacos.demon.co.uk Mon Jul 14 04:44:34 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Mon, 14 Jul 2008 09:44:34 +0100 Subject: Dictionary bidirectional In-Reply-To: References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: > On Sun, 13 Jul 2008 16:21:11 -0700 (PDT), Kless > declaimed the following in comp.lang.python: > >> I need a dictionary where get the result from a 'key' (on left), but >> also from a 'value' (on right), how to get it? >> >> I know that dictionaries aren't bidirectional, but is there any way >> without use two dictionaries? >> > Just out of curiosity... What do you expect to have returned from... > > aDict = { "one" : "two", > "three" : "four", > "What?" : "two" } > > when looking for the value "two"? > > In a dictionary, the /keys/ are unique... but the /values/ can be > duplicates. I wonder if anyone has implemented an 'equivalence class' class (for finite sets) based on this. Obviously the relation defined by k1~k2 iff D[k1] == D[k2] does partition the set of all keys as an equivalence class. So ... as a kind of inverse you could return a set, a subset of the keys. How you would get a canonical representative of that set is a different matter, of course. Unless, as in the OP's case, it is a singleton set. It would seem more efficient to do this when a key-value pair is added or removed from the original dictionary rather than iterating over all the keys each time you used it. From scott.pigman at gmail.com Sun Jul 27 07:47:33 2008 From: scott.pigman at gmail.com (Scott Pigman) Date: Sun, 27 Jul 2008 07:47:33 -0400 Subject: ctypes - unloading implicitly loaded dlls Message-ID: <14db0f2c0807270447t46b0acf2yf3814d97d9c7f03c@mail.gmail.com> Here's what I'm struggling with (as best as I can understand it): I'm writing a program that uses functionality from two different sets of cdlls which reside in two different directories, call them 'libA.dll' and 'libB.dll'. Although I don't directly use it, both directories contain a dll with the same name, although they aren't in fact identical. Call them, "libC.dll". However, the c-functions I call from the clls I do use seem to implicitly use "libC.dll". The problem that occurs is that after I load one dll and call functions in it, when I try to load the second dll I get windows errors because the second dll tries to call a function in its version of libC.dll, but it finds the version meant for libB.dll, which doesn't contain that function. Oy, I hope some sample code makes it clearer: def demo(): A = ctypes.cdll.LoadLibrary('/path1/libA.dll') A.foo() # implicitly uses '/path1/libC.dll' _ctypes.FreeLibrary(A._handle) # CRASH! "The procedure entry point some_func could not be located # in the dynamic link library libC.dll.": B = ctypes.cdll.LoadLibrary('/path2/libB.dll') # libB.dll wants to use code from '/path2/libC.dll', but # instead it finds '/path1/libC.dll' already loaded # in memory, which doesn't # contain the function call it wants. Assuming my understanding of things is correct, then I believe what I need to do is to remove /path1/libC.dll from memory before I try loading libB.dll, but I haven't found any way of doing that. Can anyone offer my some suggestions? Notes: * the two sets of dlls are supplied by a vendor for working with its COTS packages; I don't have any control over the dll names used or the code therein. * If I leave out the call to A.foo(), then I don't crash, but if I leave out the FreeLibrary call as well then I do crash. * I've tried manipulating the PATH before loading the dlls, to no effect. * I've tried del'ing A and running gc.collect() before loading B. -------------- next part -------------- An HTML attachment was scrubbed... URL: From benkasminbullock at gmail.com Tue Jul 1 08:02:24 2008 From: benkasminbullock at gmail.com (Ben Bullock) Date: Tue, 1 Jul 2008 12:02:24 +0000 (UTC) Subject: perl + python tutorial available for download References: <86c4090b-ed0b-4249-b3ee-517c94328741@z32g2000prh.googlegroups.com> Message-ID: On Mon, 30 Jun 2008 17:44:13 +0000, J?rgen Exner wrote: > Xah wrote: >>my perl and python tutorial >> >>http://xahlee.org/perl-python/index.html >> >>is now available for download for offline reading. > > Why anyone would have the idea to mix two different langauges in one > tutorial is beyond me. It's an interesting idea to present two or more languages in parallel - it would assist someone going "sideways" from one language to another. > And calling that web page a tutorial is a large stretch of imagination. > It is a random collection of primitve code samples, organized roughly by > area. No learning goals, no explanation of concepts, ... I'm a big fan of code samples - most of my code starts as other people's code samples. > Apparently you changed your ID to escape all the filters you have been a > permanent guest to. This 'tutorial' confirms that this is the best place > for you. So back you go again. I'm not interested in Xah Lee's tutorials enough to check whether they're any good or not, but he does have some interesting things to say about Emacs. From pavlovevidence at gmail.com Mon Jul 28 02:45:26 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 27 Jul 2008 23:45:26 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> Message-ID: <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> On Jul 27, 5:14 am, Steven D'Aprano wrote: > On Sat, 26 Jul 2008 15:58:16 -0700, Carl Banks wrote: > > On Jul 26, 5:07 pm, Terry Reedy wrote: > >> Whether or not one should write 'if x' or 'if x != 0' [typo corrected] > >> depends on whether one means the general 'if x is any non-null object > >> for which bool(x) == True' or the specific 'if x is anything other than > >> numeric zero'. The two are not equivalent. Ditto for the length > >> example. > > > Can you think of any use cases for the former? And I mean something > > where it can't be boiled down to a simple explicit test for the sorts of > > arguments you're expecting; something that really takes advantage of the > > "all objects are either true or false" paradigm. > > But why do you need the explicit test? I asked you first, buddy. [snip attempt to reverse argument] > > The best thing I can come up with out of my mind is cases where you want > > to check for zero or an empty sequence, and you want to accept None as > > an alternative negative as well. But that's pretty weak. > > You might find it pretty weak, but I find it a wonderful, powerful > feature. Powerful? You've got to be kidding me. If I have a function create_object(name) where one creates an anonymous object by passing an empty string, behold! now I can also create an anonymous object by passing None. You call that powerful? I call it simple convenience, and not something that we'd suffer much for for not having. But it's still the one thing I can think of that can't be replaced by a simple explicit test. > I recently wrote a method that sequentially calls one function after > another with the same argument, looking for the first function that > claims a match by returning a non-false result. It looked something like > this: > > def match(arg, *functions): > for func in functions: > if func(arg): > return func > > I wanted the function itself, not the result of calling the function. I > didn't care what the result was, only that it was something (indicates a > match) or nothing (no match). In one application, the functions might > return integers or floats; in another they might return strings. In a > third, they might return re match objects or None. I don't need to care, > because my code doesn't make any assumptions about the type of the result. Couldn't you write the function to return None on no match, then test if func(arg) is None? That way would seem a lot more natural to me. As an added bonus, you don't have to return some sort of wrapped object if suddenly you decide that you want to match a zero. Sorry, can't give it credit for the use case I was asking for. I want something where "if x" will do but a simple explicit test won't. Carl Bannks From Lie.1296 at gmail.com Wed Jul 16 08:44:28 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 16 Jul 2008 05:44:28 -0700 (PDT) Subject: Why is this blowing the stack, thought it was tail-recursive... References: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> Message-ID: On Jul 13, 8:44?pm, Fuzzyman wrote: > On Jul 13, 7:56?am, Steven D'Aprano > > > cybersource.com.au> wrote: > > On Sat, 12 Jul 2008 19:25:18 -0400, Terry Reedy wrote: > > > ssecorp wrote: > > >> def fib(n): > > >> ? ? def fibt(a, b, n): > > >> ? ? ? ? if n <= 1: > > >> ? ? ? ? ? ? return b > > >> ? ? ? ? else: > > >> ? ? ? ? ? ? return fibt(b, a + b, n - 1) > > >> ? ? if n == 0: > > >> ? ? ? ? return 0 > > >> ? ? else: > > >> ? ? ? ? return fibt(0, 1, n); > > > >> and can memoization speed up this even more? tesintg with memoization > > >> doesnt really say anything because it is so fast it is instant anyway. > > > > Except for the fact that a+b gets slower as a and b get bigger, this > > > would already be linear time in n. ?Memoization (here by means of a > > > linear list) only helps if the list is preserved and one makes repeated > > > requests for various fib values. > > > > I am just curious what input you tried that blew the stack? ?It had to > > > be pretty large. > > > No, not really. Try it for yourself: on my system, I get RuntimeError: > > maximum recursion depth exceeded with fib(999). > > > fib(999) is a large number, with 208 digits, but not that large: > > > 268638100244853593861467272021429239676166093189869523401 > > 231759976179817002478816893383696544833565641918278561614 > > 433563129766736422103503246348504103776803673341511728991 > > 69723197082763985615764450078474174626L > > > -- > > Steven > > The default CPython recursion limit is 1000 - so hitting it with an > input of 999 is not that surprising... > > You can set a higher limit with sys.setrecursionlimit(...) Though that would be a kludge, not a fix. Using iteration or generator expression is better. From jeffober at gmail.com Tue Jul 8 07:41:27 2008 From: jeffober at gmail.com (Jeff) Date: Tue, 8 Jul 2008 04:41:27 -0700 (PDT) Subject: Emacs/Python Essentials? References: Message-ID: I just use Python mode. For Django work, there is a Django mode as well. Cedet is helpful, too. From fredrik at pythonware.com Tue Jul 22 18:45:36 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 00:45:36 +0200 Subject: How to match word boundary? In-Reply-To: <94c0d7d1-5263-45f6-a75d-a9751b3785f9@d45g2000hsc.googlegroups.com> References: <94c0d7d1-5263-45f6-a75d-a9751b3785f9@d45g2000hsc.googlegroups.com> Message-ID: Peng Yu wrote: > I would like to match "a::" in "a::b", but not in "a:: b". That is, > the character after "::" should be a alphanumeric character. sounds like a look-ahead assertion is what you need: >>> import re >>> re.match("\w::(?=\w)", "a::b") <_sre.SRE_Match object at 0x01442138> >>> _.group() 'a::' >>> re.match("\w::(?=\w)", "a:: b") >>> From darcy at druid.net Mon Jul 28 14:19:48 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Mon, 28 Jul 2008 14:19:48 -0400 Subject: We programming In-Reply-To: <488E0956.8070002@internetnowasp.net> References: <789038.29418.qm@web7906.mail.in.yahoo.com> <488E0956.8070002@internetnowasp.net> Message-ID: <20080728141948.03ada692.darcy@druid.net> On Tue, 29 Jul 2008 02:00:54 +0800 "Marcus.CM" wrote: > I hope this doesnt invite flames.....but for webpages i suggest stick > with php... Oh, come on. You're just asking for it. :-) [Turns flame thrower to low setting] OK, here is why I don't like PHP. When I am creating dynamic web content, chances are that it is part of a larger system. I may have command line utilities, server software and cron jobs all working on the same (usually database backed) systems. As a result it is really convenient to be able to reuse modules. Python gives me that quite easily. PHP, not so much. I am not going to write a server in PHP, for example. I also don't much care for PHP as a language anyway but that's actually a secondary consideration. I'll go put on my flame-retardent underwear now. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From stef.mientki at gmail.com Sat Jul 26 13:43:56 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 26 Jul 2008 19:43:56 +0200 Subject: how to upload files to "google code" filesection ? Message-ID: <488B625C.4060400@gmail.com> hello, In a program I want to download (updated) files from google code (not the svn section). I could find a python script to upload files, but not for downloading. Anyone has a hint or a solution ? thanks, Stef Mientki From __peter__ at web.de Thu Jul 24 11:27:38 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 Jul 2008 17:27:38 +0200 Subject: repr(string) References: Message-ID: Peter Otten wrote: > You could also use a csv file with a single row. Err, I meant column, but a row would also work. Your choice. Peter From thomas.troeger.ext at siemens.com Tue Jul 22 08:07:23 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Tue, 22 Jul 2008 14:07:23 +0200 Subject: Python embedding question (2). References: Message-ID: Carl Banks wrote: > On Jul 17, 9:57 am, Thomas Troeger > wrote: >>> I'd say that PyGame could be a solution. >>> Or otherwise you could do your own audio/graphics programming (you don't >>> tell us which OS you use, but there exist python modules that allow you >>> to do barebones graphics & sound programming on linux...). > Pyglet runs on top of OpenGL, which might have performance problems on > an embedded device, if OpenGL or Mesa is even supported. If it's > supported, I suspect performance will be adequate for 2D drawing. It > almost certainly is the lightest solution you can find. > > > Carl Banks I've managed to put together a small pyGame program, it runs smoothly and seems to be exactly what I wanted. It's fast! Even with 100 moving objects it still runs so fast that I can consider using Python/pyGame for the whole project. There are still some questions left which I haven't found out by myself, so maybe someone here can answer them: - I can't see how to create more sophisticated text output, it seems the built in font render facilities are limited to simple strings. Is that true? I'd need a way to at least render multiline text with paragraphs and bidirectionality, like pango does it. Is there a way to integrate pango support into pyGame? I'd prefer marked up text display with text properties ... - Is there some way to reserve screen areas so they are excluded from a blit, or do I have to manage stuff like this myself? I am thinking about several graphic layers where each layer is painted on top of the next layer, for example to draw a gui in front of a background image. - There seems to be support for video overlay, i.e. is it possible to have an external program paint an image from a camera into a portion of the screen while pyGame is running? Maybe this is the wrong list to ask, so please forgive the question but direct me to somewhere better. Cheers, Thomas. From robert.rawlins at thinkbluemedia.co.uk Mon Jul 28 10:16:48 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Mon, 28 Jul 2008 15:16:48 +0100 Subject: GUID Generation Message-ID: <019c01c8f0bc$92b56b20$b8204160$@rawlins@thinkbluemedia.co.uk> Chaps, I've been looking at the following recipe for generating a GUID http://code.activestate.com/recipes/163604/ however I note that its about 6 years old. Has python since adopted an internal module for GUID generation? Or is this 3rd part module still the best option? Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From koblas at gmail.com Tue Jul 29 23:56:31 2008 From: koblas at gmail.com (koblas) Date: Tue, 29 Jul 2008 20:56:31 -0700 (PDT) Subject: Native Code vs. Python code for modules Message-ID: Ruby has been getting pummeled for the last year or more on the performance subject. They've been working hard at improving it. From my arm chair perspective Python is sitting on it's laurels and not taking this as seriously as it probably should. In general it's possible to make many comments that swirl around religion and approach, one of the things that I've noticed is that wile Python has a much more disciplined developer community they're not using this for the greater good. Specifically, in looking at a benchmark that was posted, python was an order of magnitude (20 secs vs. 1 sec) slower than ruby. In investigating the performance bottleneck is the random module. This got me to think, why does python have "pickle" and "cPickle"? Comes down to lowest common denominator, or the inability for somebody to write an optimized package that can mimic a python package. To that end why would somebody write big try catch blocks to see if modules exist and if they exist alias their names. Wouldn't it be better if there was a way that if I have an "interface compatible" native (aka C) module that has better performance that there could be a way that python would give it preference. e.g. import random(version=1.2, lang=c) or import random(version=1.2, lang=py) # use the python version by default or import random # use the latest version in the "fastest" code (C given preference) where there could be a nice set of "standard" key value pairs that could provide addtional hints as to what language and version of a library was to be used. From 5lvqbwl02 at sneakemail.com Sat Jul 26 15:33:40 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Sat, 26 Jul 2008 12:33:40 -0700 (PDT) Subject: wx.Timer not working Message-ID: <7a2a1c54-6d74-475c-9566-4d94cb5b5962@a3g2000prm.googlegroups.com> Windows XP SP3 Python 2.5 wx.version() = '2.8.1.1 (msw-unicode)' ------ I have written the following *simplest* implementation of wx.timer I can think of. No workie. I want an exception, a print statement, or something. The wxpython demos all work, but for some reason this isn't. The demos are simple and straghtforward, so I think I understand how it should work. Clues please? I've tried variations of ID's, SetOwners, using and redefining Notify(), Bind, Connect, etc. In the cases where the interpreter doesn't complain about passed argument types, the callback function is never called. import wx class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, pos=(100, 100)) timer = wx.Timer(self, -1) self.Bind(wx.EVT_TIMER, self.OnTick, timer) timer.Start(100) def OnTick(self, event): print 'Hi. Bye.' 1/0 #<-- should crash as evidence callback is being called class MyApp(wx.App): def OnInit(self): frame1 = MyFrame(None, wx.ID_ANY, "This is a test") frame1.Show(True) return True app = MyApp(0) app.MainLoop() Thanks for any advice!! Michael From norseman at hughes.net Mon Jul 7 16:41:24 2008 From: norseman at hughes.net (norseman) Date: Mon, 07 Jul 2008 13:41:24 -0700 Subject: Cross Compiler for Python? In-Reply-To: <000901c8e009$dbd29e40$0d00a8c0@hendrik> References: <000901c8e009$dbd29e40$0d00a8c0@hendrik> Message-ID: <48727F74.9000708@hughes.net> I think I should have not used the 'reply' button but rather sent it back through the python-list at ... So here here goes. =============== Hendrik van Rooyen wrote: > Up to now, I have been innocently using the vanilla python > that comes with the Linux distribution (Suse in my case). > > For the past few days, I have been playing with a little > device called an eBox - it is basically a 486 with 128Mb > memory, and a 1Gig pcmcia flash drive. > > We want to try to use this as an industrial controller, so > I want to load python onto it. > > So I downloaded the sources, and got them into the box, > over its ethernet connection. > > Then I got stymied - the configure script will not run, > because the "distribution" has no C compiler - it is > basically a kernel, and Busybox, with precious little else. > > So I googled, and I found mobile python, and portable python, > both aimed at windows. - no good to me. > > Adding "embedded" to the Google string is also useless, > as it basically brings up instances of embedding the > interpreter into another app, not for small processors. > > So how does one do a compile of python on one machine > aimed at another one? - All I want is a vanilla installation > with the stuff in all the usual places. And just to make matters > interesting, the two Linux boxes I have available are both > 64 bit dual core animals, one Intel, one AMD... > > I don't need much more than the interpreter, sys, os, sockets > and ctypes. > > Alternatively, where can one find a set of binaries for > 32 bit Linux? > > Looking for some sane advice please. > > - Hendrik > > -- > http://mail.python.org/mailman/listinfo/python-list > ================================================== In case all else fails: This is not a cookbook answer, but: 1) gnu's gcc will compile to 16,32 or 64 bit intel architectures OK, the 32 bit version compiles to 16 or 32 & the 64 should. The 64 will run 32 bit programs, including the 32 bit gcc. chgroot can be (messy but) useful to maintain separation. 2) info gcc and look for compiler directives then info nasm and look for directives same for the linker I'm not specific because I use Slackware and different distros can use different modules. You may have an assembler with a different name. Switches can be different and so forth. On Slackware the installpkg (for tarballs already compiled) records the locations of where things go in /var/log/packages. I have to assume other distros have something similar since these are used to remove things later. Can we say 'updates'? If not you will need to wade through the .configure and Makefiles to root out what happens to get 'vanilla' locations. Like I said, it's not cookbook, but it will get you there and you will gain quite an insight into Linux. While the path may not be well marked in Linux, there usually is one. Sorry I don't have a more straight forward approach. Steve norseman at hughes.net From mail at timgolden.me.uk Tue Jul 15 13:01:25 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Jul 2008 18:01:25 +0100 Subject: need ldap windows binary and/or installation help In-Reply-To: <0A53725C4A497848A7B3A0874B259831011B09A1@acesxch01.ADVENTISTCORP.NET> References: <0A53725C4A497848A7B3A0874B259831011B09A1@acesxch01.ADVENTISTCORP.NET> Message-ID: <487CD7E5.5020805@timgolden.me.uk> Sells, Fred wrote: > I'm running python 2.5 (or 2.4) in an XP environment. > > I downloaded and installed the .dll's from OpenLDAP-2.4.8+OpenSSL-0.9.8g-Win32.zip and copied the .dll's in c:/windows/system32 as instructed > > now I get this error. Is there anyway to avoid building the python_ldap binaries? Apart from being lazy, I've got a secure system policy issue if I start compiling apps. I could give up and just start running in linux, but my xp environment is much friendlier to develop in. I've googled a lot, but all the links I've found talk to Unix or to compiling from source. Disclaimer. I know nothing about python-ldap. I simply Googled for it and came to: http://python-ldap.sourceforge.net/download.shtml which led me to http://www.osuch.org/python-ldap from which I downloaded and ran the .msi http://www.osuch.org/python-ldap-2.3.5.win32-py2.5.msi and Bob was at that point my uncle. Was there some obstacle to your doing this? (It wasn't clear whether some policy required you to compile from source). TJG From kris at FreeBSD.org Wed Jul 9 15:46:50 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Wed, 09 Jul 2008 21:46:50 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <1343fa73-fd32-46c3-8a75-0efc85b2660e@a70g2000hsh.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <1343fa73-fd32-46c3-8a75-0efc85b2660e@a70g2000hsh.googlegroups.com> Message-ID: <487515AA.3070407@FreeBSD.org> samwyse wrote: > On Jul 8, 11:01 am, Kris Kennaway wrote: >> samwyse wrote: > >>> You might want to look at Plex. >>> http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/ >>> "Another advantage of Plex is that it compiles all of the regular >>> expressions into a single DFA. Once that's done, the input can be >>> processed in a time proportional to the number of characters to be >>> scanned, and independent of the number or complexity of the regular >>> expressions. Python's existing regular expression matchers do not have >>> this property. " > >> Hmm, unfortunately it's still orders of magnitude slower than grep in my >> own application that involves matching lots of strings and regexps >> against large files (I killed it after 400 seconds, compared to 1.5 for >> grep), and that's leaving aside the much longer compilation time (over a >> minute). If the matching was fast then I could possibly pickle the >> lexer though (but it's not). > > That's funny, the compilation is almost instantaneous for me. My lexicon was quite a bit bigger, containing about 150 strings and regexps. > However, I just tested it to several files, the first containing > 4875*'a', the rest each twice the size of the previous. And you're > right, for each doubling of the file size, the match take four times > as long, meaning O(n^2). 156000*'a' would probably take 8 hours. > Here are my results: The docs say it is supposed to be linear in the file size ;-) ;-( Kris From fredrik at pythonware.com Thu Jul 24 05:24:17 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 11:24:17 +0200 Subject: instance comparison In-Reply-To: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> References: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> Message-ID: King wrote: > Is this mean when you have overridden __str__ method then it comapre > with results of __str__ or else it will comapre whether they are the > same instances? Comparisons uses __cmp__ or the rich comparison set; see http://docs.python.org/ref/customization.html for details. Sets and dictionaries, also relies on hashing (the __hash__ method, also described on the linked page). The __str__ method only affects printing and conversion to string. From kris at FreeBSD.org Thu Jul 10 18:49:34 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Fri, 11 Jul 2008 00:49:34 +0200 Subject: multithreading in python ??? In-Reply-To: <486CAC9B.9000902@shopzeus.com> References: <674A912AA405814397CED58601AC8E251554964241@BLRKECMBX05.ad.infosys.com> <486CAC9B.9000902@shopzeus.com> Message-ID: <487691FE.7040903@FreeBSD.org> Laszlo Nagy wrote: > Abhishek Asthana wrote: >> >> Hi all , >> >> I have large set of data computation and I want to break it into >> small batches and assign it to different threads .I am implementing it >> in python only. Kindly help what all libraries should I refer to >> implement the multithreading in python. >> > You should not do this. Python can handle multiple threads but they > always use the same processor. (at least in CPython.) In order to take > advantage of multiple processors, use different processes. Only partly true. Threads executing in the python interpreter are serialized and only run on a single CPU at a time. Depending on what modules you use they may be able to operate independently on multiple CPUs. The term to research is "GIL" (Global Interpreter Lock). There are many webpages discussing it, and the alternative strategies you can use. Kris From vinay_sajip at yahoo.co.uk Tue Jul 15 09:45:50 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 15 Jul 2008 06:45:50 -0700 (PDT) Subject: logging via SocketHandler and TCPserver References: <81929250-449b-4686-acf3-dcc0095e341a@d1g2000hsg.googlegroups.com> Message-ID: On Jul 14, 11:16 pm, Larry Bates wrote: > Vinay, > > Thanks for your detailed explanation, but IMHO your suggested solution is almost > the opposite (right idea wrong direction) of what I'm looking for. Hypothetical > setup: > > application1 - SocketHandlerloggingturned on > application2 - SocketHandlerloggingturned on > application3 - SocketHandlerloggingturned on > . > . > . > applicationN > > monitoring app - ThreadingTCPServer target that Allows user to connect to ANY > running application and to view the real-time log messages. After monitoring, > it should be able to disconnect and connect to another application... The > clients (application1..N) never stop sending and don't ever send anything short > to disconnect themselves from the monitoring application. The disconnect/ > reconnect is done at the monitoring app end based on input from the user. I > think each one would beloggingto a different port, but I never really quite > got that far. Perhaps there is some other way that I'm missing. It seems like > this is something that might be able to be "generalized" into a robust > monitoring application for an arbitrary number of asynchronously running > applications. > > Each application's real-time log might be reached by clicking on a tab, menu, etc. Here's how I see it: the socket server listens, and receives logging events from numerous applications in real time. If the server is configured to monitor app1, then it quietly discards (or doesn't show in the UI) all events from other apps - it only collects/shows events from app1. When you click on a tab/menu/whatever to switch to monitoring app2, then this information is used to tell the server to discard (or not show) events from all apps except app2. You would of course need to ensure the communication between UI thread and server thread were done in a thread-safe manner. > As to the difficulty, I might just have a mental block but two modules that I've > had a real hard time getting my mind wrapped around is yourLoggingand Twisted. > They both have a multitude of options/ways to be used and not very many working > examples to work from. Might be a chance to make some money on a book. If it > was full of examples, I'd purchase it. > But there are numerous examples in the logging docs - the script you quoted as having put together after several hours of Googling is pretty much the same as the (working) version in the logging docs! If you have reviewed the logging docs and find them lacking examples, please provide more detail about the kind of examples you think are missing. And I can't speak for Twisted, but it does a lot more than logging - and I don't think there's enough complexity in Python logging to warrant a paid-for book. (No doubt people will tell me if they disagree!) Best regards, Vinay Sajip From arnimavidyarthy at gmail.com Fri Jul 18 07:04:34 2008 From: arnimavidyarthy at gmail.com (arni) Date: Fri, 18 Jul 2008 04:04:34 -0700 (PDT) Subject: trying to match a string References: Message-ID: <4b33b3b5-d87d-4333-948d-73f07c33c111@a3g2000prm.googlegroups.com> On Jul 18, 3:46?pm, ed... at holyrood.ed.ac.uk (Eddie Corns) wrote: > arnimavidyar... at gmail.com writes: > >Hi, > >Hi, > >I am taking a string as an input from the user and it should only > >contain the chars:L , M or R > >I tried the folllowing in kodos but they are still not perfect: > >[^A-K,^N-Q,^S-Z,^0-9] > >[L][M][R] > >[LRM]?L?[LRM]? etc but they do not exactly meet what I need. > >For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. > >regards, > >SZ > >The string may or may not have all the three chars. > >>> var ? ? = 'LRLRLRNL' > >>> residue = var.replace('L','').replace('R','').replace('M','') > >>> if residue != '': > > ... ? print 'Invalid characters in input',residue > ... > Invalid characters in input N That was quick.Thanks.Never thought it that angle :( From bearophileHUGS at lycos.com Thu Jul 31 21:56:45 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 31 Jul 2008 18:56:45 -0700 (PDT) Subject: Non Continuous Subsequences References: <650df4ae-2f63-4428-b780-3f7045164690@p25g2000hsf.googlegroups.com> Message-ID: <1d074ab3-e703-4741-be14-26c52af457ca@27g2000hsf.googlegroups.com> Kay Schluehr: >[Yes, I have too much time...] Thank you for your code. If you allow me to, I may put some code derived from yours back into the rosettacode.org site. >Here is an evil imperative, non-recursive generator: I like imperative, non-recursive code :-) If you count the number of items of the results, you find the sequence A002662: www.research.att.com/~njas/sequences/A002662 The series grows as: lambda n: sum(C(n, k) for k in xrange(3, n+1)) I have modified your code a little, here and there, so I can show it again. Here are some timings. Note: n = 19 => result = 261_972 subs n = 21 => result = 1_048_365 subs Timings, seconds, best of 3: N=19 N=21 v1: 2.51 17.88 v2: 0.63 3.58 v3: 2.47 10.65 v4: 0.61 3.55 v5: 0.84 5.45 v6: 0.64 2.67 v7: 0.58 3.07 v8: 0.44 1.83 v9: 0.07 0.21 v10: 2.22 9.58 v9 computes the 67_108_512 subs of n=27 in 14.54 s. The versions: v1) original eager Python+Psyco version v2) eager Python+Psyco version v3) lazy Python version v4) eager Python+Psyco version plus optimization v5) eager D version with my libs v6) lazy D version with my libs v7) eager D version without my libs plus optimization v8) lazy D version without my libs v9) lazy D version without my libs, no allocations 10) lazy Python version, no allocations Used DMD compiler V.1.033 with: -O -release -inline Python 2.5.2, Psyco 1.5.2. Some comments: - The current Python GC manages memory more efficienty than the current default D GC. This is a known issue, D is a much younger language, and there are various different situations (not just regarding its GC) where it's slower (for example regarding I/O, associative arrays, etc). - Being compiled, and having a very light iteration protocol, D is much faster in the lazy version. Avoiding to allocate new memory reduces total time a lot. - In D when n is small the eager version is faster, but things change with n is large, because this time the allocation time and the cache misses start to dominate. - The Python version doesn't improve much when you know much long the result is, while the D version improves significantly. This because the list append in Python is much more efficient than in D. Python is a much more refined language, and despite D supposed to be a fast compiled "to the metal" system language, it's often not faster. For example Python dicts are often faster than D AAs. D is currently in quick development so its data structures and many details aren't optimized. Python is much older and its data structures are well optized, lot of smart people has made them fast. - If you avoid memory allocation in D you can generally go quite fast. - Comparing different languages like this is useful for D, because it's young, and doing such comparisons I have found many performance problems in it, sometimes they have even being discussed, understood, addressed. - In D another possible output is an uint (integer not signed always 32 bits), where the bits = 1 are the items in the current subset. This may be fast enough. Bye, bearophile ------------------------- THE CODE: # 1) original eager Python+Psyco version from sys import argv def ncsub(seq, s=0): if seq: x = seq[:1] xs = seq[1:] p2 = s % 2 p1 = not p2 return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2) else: return [[]] if s >= 3 else [] import psyco; psyco.bind(ncsub) n = 10 if len(argv) < 2 else int(argv[1]) print len( ncsub(range(1, n)) ) ------------------------- # 2) eager Python+Psyco version from sys import argv def ncsub(seq): n = len(seq) res = [] for i in xrange(1, 2 ** n): S = [] nc = False for j in xrange(n + 1): k = i >> j if k == 0: if nc: res.append(S) break elif k % 2: S.append(seq[j]) elif S: nc = True return res import psyco; psyco.bind(ncsub) n = 10 if len(argv) < 2 else int(argv[1]) print len( ncsub(range(1, n)) ) ------------------------- # 3) lazy Python version # Psyco not used because makes it slower from sys import argv def leniter(iterator): nelements = 0 for _ in iterator: nelements += 1 return nelements def ncsub(seq): n = len(seq) for i in xrange(1, 2 ** n): S = [] nc = False for j in xrange(n + 1): k = i >> j if k == 0: if nc: yield S break elif k % 2: S.append(seq[j]) elif S: nc = True n = 10 if len(argv) < 2 else int(argv[1]) print leniter( ncsub(range(1, n)) ) ------------------------- # 4) eager Python+Psyco version plus optimization def C(n, k): result = 1 for d in xrange(1, k+1): result *= n n -= 1 result /= d return result # www.research.att.com/~njas/sequences/A002662 nsubs = lambda n: sum(C(n, k) for k in xrange(3, n+1)) def ncsub(seq): n = len(seq) result = [None] * nsubs(n) pos = 0 for i in xrange(1, 2 ** n): S = [] nc = False for j in xrange(n + 1): k = i >> j if k == 0: if nc: result[pos] = S pos += 1 break elif k % 2: S.append(seq[j]) elif S: nc = True return result from sys import argv import psyco; psyco.full() n = 10 if len(argv) < 2 else int(argv[1]) print len( ncsub(range(1, n)) ) ------------------------- // 5) eager D version with my libs // all the D code is generic (templated) import d.all, std.conv; T[][] ncsub(T)(T[] seq) { int n = len(seq); T[][] result; auto R = xrange(n + 1); foreach (i; xrange(1, 1 << n)) { T[] S; bool nc = false; foreach (j; R) { int k = i >> j; if (k == 0) { if (nc) result ~= S; break; } else if (k % 2) S ~= seq[j]; else if (S.length) nc = true; } } return result; } void main(string[] args) { int n = args.length == 2 ? toInt(args[1]) : 10; putr( len( ncsub(range(1, n)) ) ); } ------------------------- // 6) lazy D version with my libs import d.all, std.conv; struct Ncsub(T) { T[] seq; void generator() { int n = len(seq); foreach (i; xrange(1, 1 << n)) { T[] S; bool nc = false; foreach (j; xrange(n + 1)) { int k = i >> j; if (k == 0) { if (nc) yield(S); break; } else if (k % 2) S ~= seq[j]; else if (S.length) nc = true; } } } mixin Generator!(T[]); } void main(string[] args) { int n = args.length == 2 ? toInt(args[1]) : 10; putr( len( Ncsub!(int)(range(1, n)) ) ); } ------------------------- // 7) eager D version without my libs plus optimization import std.stdio: putr = writefln; import std.conv: toInt; long C(long n, long k) { long result = 1; for (long d = 1; d < k+1; d++) { result *= n; n--; result /= d; } return result; } long nsubs(long n) { // www.research.att.com/~njas/sequences/A002662 long tot = 0; for (int k = 3; k <= n; k++) tot += C(n, k); return tot; } T[][] ncsub(T)(T[] seq) { auto result = new T[][nsubs(seq.length)]; int pos; for (int i = 1; i < (1 << seq.length); i++) { T[] S; bool nc = false; for (int j; j < seq.length + 1; j++) { int k = i >> j; if (k == 0) { if (nc) result[pos++] = S; break; } else if (k % 2) S ~= seq[j]; else if (S.length) nc = true; } } return result; } void main(string[] args) { int n = args.length == 2 ? toInt(args[1]) : 10; auto range = new int[n - 1]; foreach (i, ref el; range) el = i + 1; putr( ncsub(range).length ); } ------------------------- // 8) lazy D version without my libs import std.conv: toInt; import std.stdio: putr = writefln; struct Ncsub(T) { T[] seq; int opApply(int delegate(ref int[]) dg) { int result, n = seq.length; OUTER: for (int i = 1; i < (1 << seq.length); i++) { T[] S; bool nc = false; for (int j; j < seq.length + 1; j++) { int k = i >> j; if (k == 0) { if (nc) { result = dg(S); if (result) break OUTER; } break; } else if (k % 2) S ~= seq[j]; else if (S.length) nc = true; } } return result; } } void main(string[] args) { int n = args.length == 2 ? toInt(args[1]) : 10; auto range = new int[n - 1]; foreach (i, ref el; range) el = i + 1; int count; foreach (sub; Ncsub!(int)(range)) count++; putr(count); } ------------------------- // 9) lazy D version without my libs, no allocations // the slicing S[0..len_S] doesn't copy memory import std.conv: toInt; import std.stdio: putr = writefln; struct Ncsub(T) { T[] seq; int opApply(int delegate(ref int[]) dg) { int result, n = seq.length; auto S = new int[n]; OUTER: for (int i = 1; i < (1 << seq.length); i++) { int len_S; bool nc = false; for (int j; j < seq.length + 1; j++) { int k = i >> j; if (k == 0) { if (nc) { T[] auxS = S[0 .. len_S]; result = dg(auxS); if (result) break OUTER; } break; } else if (k % 2) S[len_S++] = seq[j]; else if (len_S) nc = true; } } return result; } } void main(string[] args) { int n = args.length == 2 ? toInt(args[1]) : 10; auto range = new int[n - 1]; foreach (i, ref el; range) el = i + 1; int count; foreach (sub; Ncsub!(int)(range)) count++; putr(count); } ------------------------- # 10) lazy Python version, no allocations from sys import argv def leniter(iterator): nelements = 0 for _ in iterator: nelements += 1 return nelements def ncsub(seq, S): n = len(seq) for i in xrange(1, 2 ** n): lenS = 0 nc = False for j in xrange(n + 1): k = i >> j if k == 0: if nc: yield lenS break elif k % 2: S[lenS] = seq[j] lenS += 1 elif lenS: nc = True n = 10 if len(argv) < 2 else int(argv[1]) s = [None] * (n-1) print leniter( ncsub(range(1, n), s) ) ------------------------- From clay at lakeserv.net Wed Jul 23 11:00:32 2008 From: clay at lakeserv.net (Clay Hobbs) Date: Wed, 23 Jul 2008 11:00:32 -0400 Subject: How do I compare files? In-Reply-To: References: Message-ID: <1216825232.18962.11.camel@generator> On Tue, 2008-07-22 at 17:29 -0700, Matimus wrote: > On Jul 22, 4:27pm, Clay Hobbs wrote: > > I am making a program that (with urllib) that downloads two jpeg files > > and, if they are different, displays the new one. I need to find a way > > to compare two files in Python. How is this done? > > > > -- Ratfink > > Do you just want to check to see if they are the same? Or do you > actually want to know what the differences are? > > import urllib > > data1 = urllib.urlopen("http://url.of.jpg1").read() > data2 = urllib.urlopen("http://url.of.jpg2").read() > > if data1 == data2: > print "they are the same" > I just wanted to see if they are different. The code I was using that didn't work was almost the same, except that the lines that download the files didn't end in .read(). Thank you for your help -- Ratfink From areyoulookon at gmail.com Mon Jul 21 07:32:57 2008 From: areyoulookon at gmail.com (lookon) Date: Mon, 21 Jul 2008 04:32:57 -0700 (PDT) Subject: How to install simplejson on WinXP Message-ID: I am new to python and had difficulty in installing simplejson on WinXP...Could anyone help me? Thanks From fredrik at pythonware.com Sun Jul 20 09:43:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jul 2008 15:43:53 +0200 Subject: Not entirely serious: recursive lambda? In-Reply-To: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> References: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> Message-ID: Michael Tobis wrote: > I realize that lambda is something of an orphan and was arguably a bad > idea for anything besides obfuscation, but obfuscation is exactly my > purpose here. Can a lambda call itself without giving itself a name? > Google was not my friend on this one, and I suspect there is no > answer. Relax, I am not going to submit a PEP about it. gerson kurz' writings on lambdaization might be helpful (or not): http://www.p-nand-q.com/python/lambdaizing_quicksort.html http://www.p-nand-q.com/python/stupid_lambda_tricks.html From Bill at SynectixLtd.com Fri Jul 11 09:48:13 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Fri, 11 Jul 2008 14:48:13 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: "Tim Golden" wrote in message news:mailman.325.1215781777.20628.python-list at python.org... > Bill Davy wrote: >> and since then have been busy with work, and my other job, and the >> garden. > > Aha! So you're English, are you? Looks like you're in the West Country. > Weather map suggests you're not short of rain over there :) > >> Now I am back looking at this (and using WInUSB to talk to a Maxim 3421E >> etc etc but that's another story). So any help today will be much >> appreciated. >> Rgds, > > Can't remember what the particular obstacles were you > were facing, but this runs OK on my setup - > Python 2.5.2 / pywin32 211 / Outlook 2003: > > > import os, sys > import win32com.client > constants = win32com.client.constants > > def items (contacts): > items = contacts.Items > item = items.GetFirst () > while item: > yield item > item = items.GetNext () > > # > # Add whatever fields you like from: > # http://msdn.microsoft.com/en-us/library/aa210907(office.11).aspx > # > FIELDS = ['FullName', 'CompanyName', 'Email1Address'] > > outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") > ns = outlook.GetNamespace ("MAPI") > for contact in items (ns.GetDefaultFolder (constants.olFolderContacts)): > if contact.Class == constants.olContact: > print contact > for field in FIELDS: > print " ", field, "=>", getattr (contact, field, "") > > > > Hope that helps. > TJG jUST IN CASE,. i CUT'NPASTED THE PROGRAM: import os, sys import win32com.client constants = win32com.client.constants def items (contacts): items = contacts.Items item = items.GetFirst () while item: yield item item = items.GetNext () # # Add whatever fields you like from: # http://msdn.microsoft.com/en-us/library/aa210907(office.11).aspx # FIELDS = ['FullName', 'CompanyName', 'Email1Address'] outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") ns = outlook.GetNamespace ("MAPI") for contact in items (ns.GetDefaultFolder (constants.olFolderContacts)): if contact.Class == constants.olContact: print contact for field in FIELDS: print " ", field, "=>", getattr (contact, field, "") --------------------------------------------------------------------------------------------------- And then I ran it: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.2.2 >>> ================================ RESTART >>> ================================ >>> Traceback (most recent call last): File "H:/Personal/OutlookIF1/t2.py", line 18, in outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 536, in EnsureDispatch mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], bForDemand=bForDemand) File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 393, in EnsureModule module = GetModuleForTypelib(typelibCLSID, lcid, major, minor) File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 262, in GetModuleForTypelib AddModuleToCache(typelibCLSID, lcid, major, minor) File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 554, in AddModuleToCache dict = mod.CLSIDToClassMap AttributeError: 'module' object has no attribute 'CLSIDToClassMap' >>> ------------------------------------------------------------------------------------------------- Outlook is running fine. This is how the fucntion where the failure occurs begins: def AddModuleToCache(typelibclsid, lcid, major, minor, verbose = 1, bFlushNow = not is_readonly): """Add a newly generated file to the cache dictionary. """ fname = GetGeneratedFileName(typelibclsid, lcid, major, minor) mod = _GetModule(fname) # if mod._in_gencache_ is already true, then we are reloading this # module - this doesn't mean anything special though! mod._in_gencache_ = 1 dict = mod.CLSIDToClassMap info = str(typelibclsid), lcid, major, minor for clsid, cls in dict.items(): clsidToTypelib[clsid] = info ----------------------------------------------------------------------------------------------- Yes, we have suffiicient rain but the gaden needed it. I am about to become the proud tenant of half an allotment. Still, this time last year we had floods. TIA, Bill From gagsl-py2 at yahoo.com.ar Fri Jul 11 03:41:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Jul 2008 04:41:22 -0300 Subject: socket-module: different behaviour on windows / unix when a timeout is set References: <4874FD50.1070404@nanl.de> Message-ID: En Wed, 09 Jul 2008 15:02:56 -0300, Mirko Vogt escribi?: > it seems that the socket-module behaves differently on unix / windows > when a timeout is set. [...] > Now I will change the code slightly - to be precise I set a timeout on > the socket: > > > # test.py > > import socket > sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) > sock.settimeout(3.0) # <----- > print 'trying to connect...' > sock.connect(('127.0.0.1',9999)) > print 'connected!' > > > # executed on linux > > $ python test.py > trying to connect... > Traceback (most recent call last): > File "test.py", line 5, in > sock.connect(('127.0.0.1',9999)) > File "", line 1, in connect > socket.error: (111, 'Connection refused') > $ > > > # executed on windows > >> C:\Python25\python.exe test.py > trying to connect... > connected! Which Python version? Which Windows version? I've tried 2.3.4, 2.4.4, 2.5.1 and 3.0a4, all on WinXP SP2, and in all cases I got an exception (details differ between versions). In no case I could make the connection succeed when nobody was listening at port 9999, as expected. -- Gabriel Genellina From fredrik at pythonware.com Wed Jul 16 09:01:27 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 15:01:27 +0200 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: <8AEDA5E3386EA742B8C24C95FF0C7580046232B6@PDC-MAIL3.ubisoft.org> References: <8AEDA5E3386EA742B8C24C95FF0C758004623111@PDC-MAIL3.ubisoft.org> <487DDEE9.8060305@timgolden.me.uk> <8AEDA5E3386EA742B8C24C95FF0C7580046232B6@PDC-MAIL3.ubisoft.org> Message-ID: Andreas Tawn wrote: > I don't have experience of too many other languages, but in C++ (and I > guess C)... That's invalid C (you cannot declare variables in the "for" statement itself, at least not in C89). And back in the old days, some C++ compilers did in fact leak declarations from "for" loops, and others didn't... > Is the Python behaviour just a happy side effect of the target list > assignment or specific design decision? I'd say it all follows from the fact that Python doesn't have variable declarations; if you want to stick to the principle that variables can introduced simply by assigning to them, you cannot introduce new blocks nilly-willy. So none of the basic structural elements do that; variables introduced inside an "if" statement or a "for-in" statement are no different from variables introduced outside them. And intro- ducing a new block only for the loop variables would be confusing and rather impractical, given how fundamental looping over sequences and iterables are in Python. (the discussions about loop variables in list comprehensions and generator expressions are a bit different; they're expressions, not statements, and shouldn't really do assignments as a side effect, any more than function calls should leak parameter names into the calling scope...) From teebes at gmail.com Tue Jul 1 14:51:29 2008 From: teebes at gmail.com (teebes) Date: Tue, 1 Jul 2008 11:51:29 -0700 (PDT) Subject: connecting to DBMS References: <669fe460-77bf-4e53-9f05-1237f2147b10@j1g2000prb.googlegroups.com> Message-ID: <6c1e5903-e21f-4aac-a802-d4b18259ccd4@z72g2000hsb.googlegroups.com> On Jul 1, 9:35?am, varun chadha wrote: > i am a newbie to python and is working on an application which needs > to connect to the database. can anyone guide me through the DBMS that > i can use and the module to connect to it. currently i have MySQL > installed using the link on the python.org site but is unable to > connect to it through python. pls specify the link ?to the tutorials > which can guide to connect and execute my query. hopes u understood > what i meant to say. > thanks in advance mysql-python is probably your best bet for MySQL databases http://sourceforge.net/projects/mysql-python/ As far as tutorials are concerned, the presentation linked in this page is very good, given by the creator of the interface Andy Dustman: http://bogdan.org.ua/2007/09/07/mysql-python-good-mysqldb-tutorial-examples.html (scroll down to page 7 for the stuff on MySQL). - Teebes From vshankar0 at gmail.com Sat Jul 19 06:06:30 2008 From: vshankar0 at gmail.com (Venky K Shankar) Date: Sat, 19 Jul 2008 15:36:30 +0530 Subject: Question In-Reply-To: References: Message-ID: <200807191536.30757.vshankar0@gmail.com> On Saturday 19 July 2008 03:14:20 pm Peter Otten wrote: > perl_wizard at manx.net wrote: > > Why is Perl so much better than python? > > Because you have the video: > > http://mail.python.org/pipermail/python-list/2004-March/253370.html >> what about this ? i feel python's better :) >> http://www.monstersandcritics.com/people/news/article_1339060.php > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From countryone77 at yahoo.com Sat Jul 19 08:19:50 2008 From: countryone77 at yahoo.com (Bev in TX) Date: Sat, 19 Jul 2008 05:19:50 -0700 (PDT) Subject: Missing sqlite3.h Error when Building Debug Python -- Windows Vista Message-ID: <048b8df4-8468-47a1-ae15-d84ca9d43e0a@y38g2000hsy.googlegroups.com> I am a complete newbie at building Python. I am trying to build it under MS Windows Vista (64-bit AMD) with MS VS2005. I'm doing that because I need debug libraries, which I did not see in the standard distribution. I downloaded the source and found the MSVS8 solution/project files. However, when I tried to build it I got the following error: ...\python-2.5.2\modules\_sqlite\connection.h(33) : fatal error C1083: Cannot open include file: 'sqlite3.h': No such file or directory I searched on the web, and at one place it said I would just need to download sqlite3.h from sqlite.org. I looked around there, but I could not find the source for sqlite 3.3.4. I went back and reread the PCbuild8\readme.txt file, and it mentions using the following command to download the sqlite: svn export http://svn.python.org/projects/external/sqlite-source-3.3.4 Do I really need to get the whole thing, or will just sqlite3.h resolve the build problem. As far as I know, I don't really need sqlite. If I do need to execute that svn command, how do I execute that under MS Windows? Or is there some other way in which to circumvent this error? Thanks, Bev in TX From gary at byoteki.com Fri Jul 25 23:26:21 2008 From: gary at byoteki.com (Gary Josack) Date: Fri, 25 Jul 2008 23:26:21 -0400 Subject: How to find processes from Python In-Reply-To: <20080726022330.GA25922@cskk.homeip.net> References: <20080726022330.GA25922@cskk.homeip.net> Message-ID: <488A995D.2000101@byoteki.com> Cameron Simpson wrote: > On 25Jul2008 11:34, Johny wrote: > | Is there a way how to find out running processes?E.g. how many > | Appache's processes are running? > > See the popen function and use the "ps" system command. > Use of the popen functions is generally discouraged since being deprecated for the subprocess module. Look at the subprocess module which will allow you to run processes and capture the output. The docstrings have good examples for how to use it. From thomas.troeger.ext at siemens.com Fri Jul 4 07:48:07 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Fri, 04 Jul 2008 13:48:07 +0200 Subject: Static Class Initialization Question. Message-ID: Hello, I have a class that looks like this: class A(object): def __init__(self, a=0, b=1): self.a, self.b=a, b def __str__(self): return "%s(%d,%d)" % (type(a).__name__, self.a, self.b) I want to have a list of such classes instantiated automatically on startup of my program. My current (most probably clumsy) implementation looks like this: bla=[A(x[0], x[1]) for x in ((1, 2), (3, 4))] giving the following: >>> map(str, bla) ['A(1,2)', 'A(3,4)'] Is there a better way to construct a list of such classes? Basically what I want is something similar to the following C example: struct { int a; int b; } bla[]={ {1, 2}, {3, 4} }; Regards, T. From ptmcg at austin.rr.com Thu Jul 31 23:46:23 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 31 Jul 2008 20:46:23 -0700 (PDT) Subject: Genital Hair Removal References: Message-ID: <036d2619-cc7b-41bb-8481-381ee8afa108@s50g2000hsb.googlegroups.com> On Jul 31, 10:40?pm, "dr.jonver" wrote: > Genital Hair Removal http://misspelled_words_in_URLs_are_funny.blogspot.com/2008/07/genital-hair-removal.html Python provides the del command, as in: del self.genital_hair If "Genital Hair" is an element in a list, you can remove it using: items.remove("Genital Hair") Be careful though, you should not modify a sequence while iterating over it. -- Paul From adamc55 at gmail.com Mon Jul 7 14:08:56 2008 From: adamc55 at gmail.com (Adam C.) Date: Mon, 7 Jul 2008 11:08:56 -0700 (PDT) Subject: Dynamically Changing the Base Class References: <6d60c362-ba17-4414-babd-2cc254526bca@c58g2000hsc.googlegroups.com> Message-ID: On Jul 7, 9:11?am, George Sakkis wrote: > On Jul 7, 9:31?am, "Adam C." wrote: > > > > > We have a situation where we want a Swig-generated Python class to > > have a different base (not object). It doesn't appear that we can > > coerce Swig into generating the class we want at present (but we are > > still enquiring). > > > Is it possible to dynamically change the base class to something else? > > Initial experiments appear to show it is not: > > -------------------------------- snip -------------------------------->>> class Foo(object): > > > ? ? ? ? pass > > > >>> class Foozle(object): > > > ? ? ? ? pass > > > >>> Foozle.__bases__ = (Foo,) > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? ? Foozle.__bases__ = (Foo,) > > TypeError: __bases__ assignment: 'Foo' deallocator differs from > > 'object' > > -------------------------------- snip -------------------------------- > > > Is there a solution I am missing? > > > Thanks in advance. > > Supposedly it should (usually) work, there's a 6 year old patch for > this (http://bugs.python.org/issue635933). Check if Swig can generate > old-style classes (i.e. not inheriting from object) since __bases__ > assignment works for them. > > HTH, > George Thanks. I think we would want new-style classes, and 6-year-old patches strike me as maybe a little out of the desired path... so this really just doesn't work in modern Python? From digitig at gmail.com Fri Jul 4 11:19:34 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 4 Jul 2008 16:19:34 +0100 Subject: Can't get Python for Windows to run Message-ID: I have Python 2.5 working just fine on my system. I've tried downloading and installing the MS Windows Python extensions, but can't get pythonw.exe (that's the windows executable, right?) to do anything. I double-click it, nothing happens. I run it from a command prompt, it just returns me to the command prompt. The only possible clue I have is that the installation process produced the error message: "Can't install shortcuts - 'C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Python 2.5' is not a folder" That's right, it isn't a folder -- the relevant folder would have been C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Programming\\Python 2.5' but the installer never gave me the chance to choose that. That woudn't stop me running Pythonw directly from the folder in which it's installed, though, would it? -- Tim Rowe From john.tantalo at gmail.com Thu Jul 24 03:29:51 2008 From: john.tantalo at gmail.com (John Tantalo) Date: Thu, 24 Jul 2008 00:29:51 -0700 Subject: parameterized classes Message-ID: Is there is a better way to create parameterized classes than defining and returning a class in a closure? I ask because I want to create arbitrary BaseRequestHandler subclasses that delegate line handling to a given line handler, as in this example: from SocketServer import * class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass def LineRequestHandler(handler): class __LineRequestHandler(BaseRequestHandler): def handle(self): for line in self.lines(): handler.handle(line) def lines(self): line = self.line() while line: yield line line = self.line() def line(self): parts = [] while not parts or parts[-1] and not parts[-1][-1] == "\n": parts.append(self.request.recv(2**10)) if parts: return ''.join(parts)[0:-1] return __LineRequestHandler class SomeLineHandler: def handle(self, line): print "I got a line: %s" % line if __name__ == '__main__': s = ThreadingTCPServer(("", 2005), LineRequestHandler(SomeLineHandler())) s.serve_forever() I really wish I could create a class whose instances were classes that subclassed BaseRequestHandler. Is this possible, or is there a better way than my approach here? Or am I crazy? And I may be dense, so if there is an easier way to stream sockets as line streams, please let me know. I honestly don't think it should be this difficult to implement a socket handler this simple. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rgbaz.eu Tue Jul 1 08:30:04 2008 From: python at rgbaz.eu (Python.Arno) Date: Tue, 1 Jul 2008 14:30:04 +0200 Subject: raw_input into Tkinter ? In-Reply-To: <634e2b50-45ba-4b93-89b4-0afd739adaf3@z66g2000hsc.googlegroups.com> References: <634e2b50-45ba-4b93-89b4-0afd739adaf3@z66g2000hsc.googlegroups.com> Message-ID: On 30 jun 2008, at 18:55, jamitwidme at gmail.com wrote: > Is there any way to type into a Tkinter frame window? > I want to use raw_input() within a Tkinter frame. > -- > http://mail.python.org/mailman/listinfo/python-list > > You could use the Tkinter.Entry option from dialog windows... http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm gr Arno From rjagodic at gmail.com Thu Jul 17 12:27:27 2008 From: rjagodic at gmail.com (Ratko) Date: Thu, 17 Jul 2008 09:27:27 -0700 (PDT) Subject: properly delete item during "for item in..." Message-ID: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> Say you have something like this: for item in myList: del item Would this actually delete the item from the list or just decrement the reference counter because the item in myList is not associated with name "item" anymore (but still is with myList[itemIndex])? In other words, is "item" a temporary reference to myList[itemIndex] or is it actually that reference that myList has stored? I am not sure if this question even makes any sense anymore. I've been using python for years and never had any problems (and I don't now either) but now that I had to revisit c++/STL, I had to deal about these issues and was wondering how python does it. Thanks, Ratko From samwyse at gmail.com Wed Jul 9 11:07:39 2008 From: samwyse at gmail.com (samwyse) Date: Wed, 9 Jul 2008 08:07:39 -0700 (PDT) Subject: Logging to zero or more destinations References: <87r6a4du2k.fsf@merkury.smsnet.pl> Message-ID: On Jul 8, 3:01?pm, Rob Wolfe wrote: > samwyse writes: > > P.S. ?I tried researching this further by myself, but the logging > > module doesn't come with source (apparently it's written in C?) and I > > don't have the time to find and download the source to my laptop. > > Hmmm... that's strange. It is a pure Python package. > > $ ls /usr/lib/python2.5/logging/ > config.py ?config.pyc ?handlers.py ?handlers.pyc ?__init__.py ?__init__.pyc > > HTH, > Rob Oops, my bad. I was using IDLE and tried the "Open Module..." command on logging, not logging.something. From paul.hankin at gmail.com Sun Jul 13 18:29:56 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sun, 13 Jul 2008 15:29:56 -0700 (PDT) Subject: Functional/Best? References: <1215956345.3028.10.camel@localhost.localdomain> Message-ID: On Jul 13, 7:00?pm, Terry Reedy wrote: > Tim Cook wrote: > > I guess I can classify my application(s) as more procedural than > > anything else. ?But I have a question about the best way to handle > > something in Python. > > > When given a mapping of keywords, I want to call a function based on a > > certain keyword found when parsing a text file. ?The mapping looks like > > this: > > > definClassMap={'SECTION':'bldSection','COMPOSITION':'bldComposition','OBSER VATION':'bldObservation','ITEM_TREE':'bldItemTree'} > > > So if the text file contains 'ITEM_TREE' ?I want to call bldItemTree > > which creates an instance of the class ItemTree. ? > > > I currently use an if ..., elif ... construct. > > Is there a better, more efficient, more Pythonic way of doing this? > > Yes. Create a mapping of keywords to function objects rather than to > function names! > > def bldSection(): > ... > def bldItemTree(): > > class_map={ > ? ?'SECTION':bldSection, > ? ?'COMPOSITION':bldComposition, > ? ?'OBSERVATION':bldObservation, > ? ?'ITEM_TREE':bldItemTree, # trailing comma allows easy additions > > } > > for word in parselist: > ? ?try; > ? ? ?class_map[word]() > ? ?except KeyError: > ? ? ? A nice variant of this, which minimizes repetition, is to group all the factory methods together into a class, naming them the same as the keyword... class Builder(object): def SECTION(self): ... def COMPOSITION(self): ... def OBSERVATION(self): ... def ITEM_TREE(self): ... builder = Builder() for word in parse_list: item = getattr(builder, word)() ... -- Paul Hankin From max at alcyone.com Tue Jul 29 22:23:10 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 19:23:10 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> Message-ID: Carl Banks wrote: > Bzzt. "if len(x)!=0" is a simple explicit that would work for this > class and all built-in containers. (Or should--Steven D'Aprano's > objections notwithstanding, any reasonable container type should > support this invariant. From a language design standpoint, an "empty" > builtin could have been created to simplify this even more, but since > there isn't one len(x)!=0 will have to do.) That you choose not to test for non-emptiness doesn't change the fact that it's already a builtin part of the language that is supported by all fundamental types and is overridable by anyone writing a custom type. Use it or don't use it, but it's an example of precisely what you were asking for that is both practical and already in widespread use. > Now, you guys keep whining "But what if you don't know what kind of > object you're expecting?!!" It's a fair question, and my belief is > that, in practice, this almost never happens. Duck typing happens > between numeric types often, and between container types often, but > almost never between both numeric and container types. Their usages > are simply too different. What should a custom type return as its length to pass your non-emptiness test if it's a custom sequence class that is an infinite generator? It's non-empty, but doesn't have a length. You test for non-emptiness by Boolean comparison, not by testing its length. > So I present another question to you: Give me an useful, non-trivial, > example of some code that where x could be either a numeric or > container type. That would be the first step to finding a > counterexample. (The next step would be to show that it's useful to > use "if x" in such a context.) Well, asked and answered, but it apparently wasn't good enough, so I doubt anyone's going to enjoy playing your game much further. You're asking for an example of something that demonstrates a use case that's _already used by all the builtin types_, so eh, have fun drawing imaginary lines in the sand. > Once again, I'm invoking the contraint against simply using x in a > boolean context, or passing x to a function expecting a boolean > doesn't count, since in those cases x can be set to the result of the > explicit test. Next answer you're just add another constraint, so I suspect the only one enjoying this word game is you. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Love is the selfishness of two persons. -- Antoine de la Salle From duncan.booth at invalid.invalid Tue Jul 29 03:36:40 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Jul 2008 07:36:40 GMT Subject: block/lambda References: <0406eb4f-8dec-4ce2-b506-8e597de2958d@56g2000hsm.googlegroups.com> Message-ID: iu2 wrote: > Is it possible to grant Python another syntactic mark, similar to > triple quotes, that will actually make the enclosed code a compiled > code, or an anonymous function? > Yes, the syntactic mark you are looking for is 'def'. Your example becomes: >>> def dotimes(n, callable): for i in range(n): callable(i) >>> def block(i): for j in range(i): print j, print >>> dotimes(5, block) 0 0 1 0 1 2 0 1 2 3 The only thing you asked for that this doesn't do is make 'block' anonymous, but actually that is a good thing. -- Duncan Booth http://kupuguy.blogspot.com From deets at nospam.web.de Wed Jul 30 09:10:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 30 Jul 2008 15:10:19 +0200 Subject: Standard module for parsing emails? References: Message-ID: <6fb7k3Faok8fU1@mid.uni-berlin.de> Phillip B Oldham wrote: > Is there a standard library for parsing emails that can cope with the > different way email clients quote? AFAIK not - as unfortunately that's something the user can configure, and thus no atrocity is unimaginable. Hard to write a module for that... All you can try is to apply a heuristic like "if there are lines all starting with a certain prefix that contains non-alphanumeric characters". But then if the user configures to quote using XX you're doomed... Diez From bronger at physik.rwth-aachen.de Sat Jul 26 08:40:00 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 26 Jul 2008 14:40:00 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> <009b130f$0$20313$c3e8da3@news.astraweb.com> Message-ID: <87wsj8akf3.fsf@physik.rwth-aachen.de> Hall?chen! Steven D'Aprano writes: > On Sat, 26 Jul 2008 11:08:12 +0200, Nikolaus Rath wrote: > >> [...] >> >> so 'self' should *automatically* only be inserted in the function >> declaration, and *manually* be typed for attributes. > > > That idea might have worked many years ago, but not now. The > problem is, what happens here? > > class Foo(object): > def foo(self, arg): > self.whatever = arg + 1 > @classmethod > def cfoo(cls, arg): > cls.whatever = arg - 1 > @staticmethod > def sfoo(arg): > print arg See . It is only added to non-decorated methods within a class. This implies that you can switch this mechanism off with a noop decorator. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From animator333 at gmail.com Thu Jul 24 13:53:38 2008 From: animator333 at gmail.com (King) Date: Thu, 24 Jul 2008 10:53:38 -0700 (PDT) Subject: instance comparison References: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> <4888879a$0$1043$426a74cc@news.free.fr> Message-ID: No, The the class is not subclass of another one. Problem still persist. The code is pretty huge and I am trying to post the information as clear as possible. From jdscript at gmail.com Sat Jul 12 03:49:48 2008 From: jdscript at gmail.com (happy) Date: Sat, 12 Jul 2008 00:49:48 -0700 (PDT) Subject: variable question References: <6f02608a-2b2e-478d-a153-d10bbfb58981@c58g2000hsc.googlegroups.com> <48782d93$0$20780$9b622d9e@news.freenet.de> Message-ID: <98553eaa-a435-488f-9f14-831d858ac800@m45g2000hsb.googlegroups.com> On Jul 12, 8:05?am, Robert Lehmann wrote: > On Fri, 11 Jul 2008 20:13:04 -0700, happy wrote: > > Can a variable be considered the simplest of the data structures. I am > > tutoring some kids about basics of programming using python. Not an > > expert in computer sciences, but am a python enthusiast. > > Why do you need this additional layer of indirection? Just explain the > real simple data structures ? la "look, kids, a string is a chain of > characters which are bytes actually. etc. here>". Although explaining encodings is an *important* thing (which > many programmers still get wrong), it might be second priority to kids > and you might just want to say "a string is text" and jump into higher- > order data structures. > > > I wanted to know if it is correct to say a variable is a data structure, > > it has a name and a value. > > Not at all. This sounds a lot like an explanation for variables in other > languages (such as C, where the value also has a type). In Python, we use > to speak of "names," not variables. They are more like name tags you can > put on objects -- or you don't. Depending on the age/interest of your > students, I'd insert an explanation about references, reference counting > and garbage collection here (they usually find that quite understandable > and it paves the way for The Real Stuff, even though you might argue that > the refcounting gc is a CPython detail and might become obsolete with > PyPy's rise ). > > The important thing is really that Python's approach of references is > nearly orthogonal to the common approach of variables. In other > languages, variables are (as you described above) containers (a bucket, > really!) in your memory where you can put stuff into. Assignment is > usually a copy or pointer operation. > Python does not care at all about your memory. You have abstract objects > (incidentally saved in your memory, okay) with names being one mechanism > to reference them. Here, assignment is always a "put the left-hand side > name tag onto the right-hand side object". > > > Put a stack of variables in a special data > > structure called a dictionary where the each name associates to a value. > > If in a data structure, one uses numbers starting from 0 to describe the > > name, it becomes a list and ?so forth.... > > First off, you really put objects in your data structures. Names are a > one-way mapping -- the object does not know which name tags are assigned > to it. > > Your explanation of dictionaries and lists sounds a little bit upside- > down (not the mapping name->value or number->value makes it a dict or > list -- the data structure makes it a mapping with this and that > behaviour). > > HTH, > > -- > Robert "Stargaming" Lehmann Thanks for the reply. I think its better to leave the "teach kiddies" tutoring opportunity for the python experts out there. Would "python experts" have an appetite for newbies and "kiddies"? Only time will tell... I must really focus on learning the language better. "Look kids, you will learn it when you grow up... Now get out of here..." From babacity4 at gmail.com Thu Jul 24 16:50:32 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:50:32 -0700 (PDT) Subject: www sextv1 pl - Amazing porn video collection Message-ID: <87a018bf-0bfe-4c53-9c0a-63979a49e7bb@w1g2000prk.googlegroups.com> www sextv1 pl . >>>>>>>>>>Best Collection of Sextv1 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE www sextv1 pl VIDEOS<<<<<<<<<<< . www sextv1 pl From Ming.YIN at murex.com Fri Jul 11 00:02:25 2008 From: Ming.YIN at murex.com (YIN Ming) Date: Fri, 11 Jul 2008 12:02:25 +0800 Subject: recommended gcc versions for python2.5 compilation on Solaris sparc/x86, AIX, Linux Message-ID: <9347F3EEF61FC542A7D9211A42CD7E6387E071@dolphin.sg.murex.com> Dear All, We are going to compile python2.5.1 with gcc on various platforms, including Solaris8(sparc), Solaris10(x86), AIX and Linux. Just want to check if there are recommended gcc versions for these platforms. We aim to: 1. use a single version of gcc for all platforms 2. use new version of gcc (rather than odd version) Thanks and best regards, Yin Ming -------------------------------------------------------- This e-mail contains information for the intended recipient only. It may contain proprietary material or confidential information. If you are not the intended recipient you are not authorised to distribute, copy or use this e-mail or any attachment to it. Murex cannot guarantee that it is virus free and accepts no responsibility for any loss or damage arising from its use. If you have received this e-mail in error please notify immediately the sender and delete the original email received, any attachments and all copies from your system. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Mon Jul 21 12:06:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 21 Jul 2008 17:06:03 +0100 Subject: Python Written in C? In-Reply-To: References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> Message-ID: <4884B3EB.4090001@timgolden.me.uk> mk wrote: > Grant Edwards wrote: > >> Using punch-cards and paper-tape. Real programmers can edit >> their programs with a pointy stick and some home-made >> sticky-tape. > > Wrong! Real programmers can program using only Touring machine Is that some kind of bicycle? TJG From teh.saber at gmail.com Sun Jul 13 11:18:55 2008 From: teh.saber at gmail.com (teh_sAbEr) Date: Sun, 13 Jul 2008 08:18:55 -0700 (PDT) Subject: wxPython code giving strange errors. Message-ID: <01694ab5-7b5e-4e57-8b86-bf89b0beec82@m44g2000hsc.googlegroups.com> I'm busy trying to learn wxPython, and i'm trying to run the following piece of code (its from the wxPyWiki tutorial): import wx ID_ABOUT = 101 ID_EXIT = 110 class MainWindow(wx.Frame): def __init__(self,parent,id,title): wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) self.control = wx.TextCtrl(self,1,style=wx.TE_MULTILINE) self.CreateStatusBar() filemenu = wx.Menu() filemenu.Append(ID_ABOUT,"&About"," Information about this program.") filemenu.AppendSeparator() filemenu.Append(ID_EXIT,"E&xit"," Terminate the program.") menuBar = wx.MenuBar() menuBar.Append(filemenu,"&File") self.SetMenuBar(menuBar) self.Show(True) app = wx.PySimpleApp() frame = MainWindow(None, -1, "Sample editor") app.MainLoop() Simple enough, but every single time I try to run it IDLE gives me this instead of the app I was hoping for: Traceback (most recent call last): File "C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap \Python Stuff\Batch Picture Converter\main.py", line 24, in frame = MainWindow(None, -1, "Sample editor") File "C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap \Python Stuff\Batch Picture Converter\main.py", line 9, in __init__ wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) File "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx \_windows.py", line 501, in __init__ _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs)) PyNoAppError: The wx.App object must be created first! As far as I can tell, the wx.App object IS being created first. I suspect a race condition of some sort here, but can anyone shed some light on this? From karthikbalaguru79 at gmail.com Tue Jul 22 05:06:14 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Tue, 22 Jul 2008 02:06:14 -0700 (PDT) Subject: Instance References: <120cea3a-33a9-49ec-8932-7cef2e5aef17@25g2000hsx.googlegroups.com> Message-ID: On Jul 17, 5:34 pm, "Calvin Spealman" wrote: > On Thu, Jul 17, 2008 at 2:56 AM, karthikbalaguru > > wrote: > > Hi, > > > I am new to python. I am trying to use the python files given to me > > for bringing up a setup. > > I get the following error while trying to use a python file - > > AttributeError : Classroom instance has no attribute 'desk_offset' > > > How to resolve this ? > > Should i need to define desk_offset to zero in the python file ? > > > Any ideas .. > > This means you did something like this: > > class Foo: > def __init__(self): > self.bar = 10 > > f = Foo() > print f.quu > ... > AttributeError : Foo instance has no attribute 'quu' > > See? You tried to use an attribute that simply doesn't exist. Look in > the traceback for where you used the desk_offset attribute, and figure > out why you thought the object had such an attribute and why it does > not. > Thx!! Your ideas were useful. I read some basic lessons on python and that were also very helpful in solving the problem. Thx , Karthik Balaguru From jadamwilson2 at gmail.com Tue Jul 22 09:35:50 2008 From: jadamwilson2 at gmail.com (jadamwil) Date: Tue, 22 Jul 2008 06:35:50 -0700 (PDT) Subject: fromfile error on windows, not mac References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> <9650a33b-40b5-46a7-a05e-5b059117891f@b1g2000hsg.googlegroups.com> Message-ID: <185cc290-18a5-4572-9fda-fa0bb785c831@z72g2000hsb.googlegroups.com> On Jul 22, 2:05?am, Uwe Schmitt wrote: > jadamwil schrieb: > > > > > Hello, > > I am using the numpy fromfile function to read binary data from a file > > on disk. The problem is that the program runs fine on a Mac, but gives > > an error or warning on windows when trying to read the data. I use it > > like this: > > > Signal = zeros((N, 16), dtype=float32) > > for sample in range(0, N): > > ? # this function gets the next position in the file to seek to > > ? s = getFilePos(sample) > > > ? # go to the correct location in the file; this IS checked to make > > sure it is within the file > > ? mFile.seek(s) > > > ? # read the 16 float32 values from the file > > ? D = fromfile(mFile, dtype=numpy.float32, 16) > > > ? # save D in Signal > > ? Signal[sample, :] = D > > > This will fail when sample is ~4. If I change the range to (5,N), > > skipping the "bad" file location, it will run fine for a few samples, > > and then give another error. The message it gives is: > > "16 items requested but only 7 read" > > > So D is a 7x1 vector, and the program dies when it tries to assign D > > to the slice of Signal ("ValueError: shape mismatch: objects cannot be > > broadcast to a single shape"). > > > On windows, the Python version is 2.5.2, and the most recent numpy and > > scipy are being used as well. I tried using Enthought, but it gave > > this error as well, in addition to a c runtime error whenever I > > imported scipy (which is another post topic...). > > > Any ideas on what might be causing this? Is there a way to debug the > > fromfile function? And, remember, this works perfectly on a Mac. Would > > compiling everything (python, scipy, numpy) potentially solve this? > > Did you open the file in binary mode ? > > Greetings, Uwe Yes I did. Would that make a difference between a mac and windows? Thanks From victorsubervi at gmail.com Tue Jul 29 12:47:48 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 29 Jul 2008 18:47:48 +0200 Subject: Windows Interpreter In-Reply-To: <488F1DB3.4010608@timgolden.me.uk> References: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> <488F1745.4020705@timgolden.me.uk> <4dc0cfea0807290626p4b05376en49ccb18f0e1eb4bb@mail.gmail.com> <488F1DB3.4010608@timgolden.me.uk> Message-ID: <4dc0cfea0807290947n5d5ebf6fw8d358c49bad8cd57@mail.gmail.com> I?ll try that. Back online in a week. Victor On 7/29/08, Tim Golden wrote: > > Victor Subervi wrote: > >> def a(): >> chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', >> '\\yz'] >> rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like the >> Beast? Who can wage war against him?\par' >> for char in chars: >> c = '(?<=' + char + ')' >> test = re.search(c, rtf_markup) >> try: >> junk = test.group(0) >> print char >> except: >> pass >> >> Now, I can paste that entire fn in linux. But in windows I have to paste >> it line_by_line. Pain in butt! And it indents automatically. How change that >> behavior. >> > > Well, I'm not really sure what to say. I've just copied that > whole section with drag-mouse, Ctrl-C. I then opened a new > interpreter window (effectively, Start > Run > python) and > right-clicked over the window. At this point, the lines I > copied were copied in and the function accepted by the > interpreter. > > I do have QuickEdit on by default in all by console windows, > but the only difference I expect that to make is that you'd > otherwise have to use the window's System Menu (Alt-Space, > Edit, Paste). > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From diordna at gmail.com Sat Jul 19 00:29:10 2008 From: diordna at gmail.com (Stephen Johnson) Date: Sat, 19 Jul 2008 00:29:10 -0400 Subject: Any Game Developers here? In-Reply-To: <76b841590807181951p10159677n881d2bdadf4f69fc@mail.gmail.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> <4A235BC6-5E46-4402-AF2D-BA3DBC175517@gmail.com> <76b841590807181605r106995d2k98486993a4eaccc4@mail.gmail.com> <9B960401-8D79-44BC-B4A5-4BE2BD1869BC@gmail.com> <76b841590807181951p10159677n881d2bdadf4f69fc@mail.gmail.com> Message-ID: <104129B8-51F4-45DF-86B0-84597CA8D76E@gmail.com> Yes, I will put the demo up on my web site (www.steveasleep.com) with fully commented source code and will probably spend a couple more months on it making it into a proper game. -Steve Johnson On Jul 18, 2008, at 10:51 PM, Michael Lubker wrote: > PyOhio sounds fun... I've been wanting to get some sort of Barcamp or > GameJam running where I live (in Austin, so you'd think there would be > people interested) but no-one will bite. :/ > > Escort Wing was a fun project... I did a few mods for EW1. > > Will you release this demo anywhere? Just curious. > > Thanks > Michael > > On Fri, Jul 18, 2008 at 7:52 PM, Stephen Johnson > wrote: >> Yes, I wrote the music, the GUI, and bits of code here and there.. >> Will >> Hogben is working on EW 2 for Freeverse right now. But that was in >> BlitzMax, >> and I'm in greener pastures now, working on my demo for PyOhio. >> -Steve Johnson >> On Jul 18, 2008, at 7:05 PM, Michael Lubker wrote: >> >> I'm interested in general... I know about PyGame and Pyglet, and have >> used both. We're currently using Python-Ogre. In the end, I am >> looking >> to find people interested in my project ( see >> http://youtube.com/watch?v=E0QQ9JuclxE ), but I also want to find >> people experienced with Python in general, not just one library. >> (though of course I know that's not too likely) >> >> Aren't you one of the Escort Wing developers? :) >> >> Thanks >> Michael >> >> On Fri, Jul 18, 2008 at 5:13 PM, Stephen Johnson >> wrote: >> >> I use the Pyglet library to make games. You want to look at the >> pyglet and >> >> pygame mailing lists, not this one. Use Google. >> >> In my opinion, PyGame is clunky and Pyglet is elegant, simple, and >> >> comprehensive. PyGame has more examples available, but Pyglet has >> great >> >> documentation and enough examples to answer any questions you might >> have. >> >> Both have active communities. >> >> -Steve Johnson >> >> On Jul 18, 2008, at 5:38 PM, Michael Lubker wrote: >> >> Any people that use Python as the predominant language for their game >> >> development here? >> >> ~Michael >> >> -- >> >> http://mail.python.org/mailman/listinfo/python-list >> >> >> >> >> >> -- >> ~ "The world hates change, yet it is the only thing that has brought >> progress." ~ Charles Kettering >> >> http://snowballz.joey101.net >> >> > > > > -- > ~ "The world hates change, yet it is the only thing that has brought > progress." ~ Charles Kettering > > http://snowballz.joey101.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From thermostat at gmail.com Wed Jul 16 14:00:05 2008 From: thermostat at gmail.com (Dan) Date: Wed, 16 Jul 2008 11:00:05 -0700 (PDT) Subject: For_loops hurt my brain. References: <4874c21f-befa-4e9f-a99d-486cc9c9b5b8@d77g2000hsb.googlegroups.com> Message-ID: <2b90e4bd-2797-4be3-8a82-ef7b66493c48@d45g2000hsc.googlegroups.com> On Jul 16, 1:42 pm, bsag... at gmail.com wrote: > This script uses a simple for loop to zip some files. However I am > repeating code that cries out for a nested loop. My two lists of > files_to_be_zipped (spare and seekfacts) are of uneven length so I > can't seem to decipher the "for_logic". I would appreciate any help. > Thanks, Bill > > import zipfile > import os > > zips = [ > 'c:/spare.zip', > 'c:/seekfacts.zip' > ] > spare = [ > 'c:/spare/huge.fm3', > 'c:/spare/huge.wk3' > ] > seekfacts = [ > 'c:/seekfacts/bookmark.html', > 'c:/seekfacts/index.htm', > 'c:/seekfacts/seek.css', > 'c:/seekfacts/seek.js' > ] > > zFile = zipfile.ZipFile(zips[0], 'w') > for files in spare: > zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED) > zFile.close() > > zFile = zipfile.ZipFile(zips[1], 'w') > for files in seekfacts: > zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED) > zFile.close() I would do something like this: # UNTESTED import zipfile import os zip_dict = { 'spare' : ['c:/spare.zip', 'c:/seekfacts.zip'], 'seekfacts' : [ 'c:/seekfacts/bookmark.html', 'c:/seekfacts/index.htm', 'c:/seekfacts/seek.css', 'c:/seekfacts/seek.js' ] } for key,value in zip_dict.items(): zFile = zipfile.ZipFile("c:/%s.zip" % key, 'w') for fname in value: zFile.write(fname, os.path.basename(files), zipfile.ZIP_DEFLATED) zFile.close() # End untested code. This implicitly maps thing with the key foo to the zip file c:/ foo.zip, but if you want to be more general, I would suggest thinking about making a class. -Dan From sajmikins at gmail.com Mon Jul 28 17:56:24 2008 From: sajmikins at gmail.com (Simon Forman) Date: Mon, 28 Jul 2008 14:56:24 -0700 (PDT) Subject: Is it allowed to use function results as default arguments ? References: Message-ID: <936daef1-5ffb-4496-b67f-b68d82d021d4@z11g2000prl.googlegroups.com> On Jul 28, 1:28?pm, Stef Mientki wrote: > hello, > > I've a perfect working procedure, > at least as far I've tested it it works perfect. > > But I was just experimenting with inspect, > and saw that the default argument was not parsed correctly. > > So I wonder if this is allowed: > > def Get_Relative_Path ( target, base=os.curdir ) : > ? ... > > As inspect returns the following: > > (['target', 'base'], None, None, ('.',)) > > thanks, > Stef Mientki os.curdir is '.' on many platforms. What did you expect inspect to show? |>>> import os |>>> os.curdir '.' From bruno.42.desthuilliers at websiteburo.invalid Fri Jul 4 06:26:32 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 04 Jul 2008 12:26:32 +0200 Subject: Newbie, list has no attribute iteritems In-Reply-To: <12caa75c-455a-4ab3-a9c3-4bd191b6965d@k13g2000hse.googlegroups.com> References: <12caa75c-455a-4ab3-a9c3-4bd191b6965d@k13g2000hse.googlegroups.com> Message-ID: <486dfac7$0$3624$426a74cc@news.free.fr> rabad a ?crit : > Hi, > I've created a custom filter based on HTMLParser, with the following > source: > >(snip) > But when I use it, it gives me the following error message: > ERROR Processor exception: AttributeError: 'list' object has no > attribute 'iteritems' (snip) > File "d:\esp\lib\python2.3\processors\DocDumpF.py", line 178, in > __html_attrs > _attrs = ' %s' % (' '.join([('%s="%s"' % (k,v)) for k,v in > attrs.iteritems() > ])) > > Anybody knows why it says attrs is not a list element? Actually, what the traceback says is that 1/ attrs is a list object 2/ list objects have no attribute named iteritems If you assumed it was a dict, then it's probably time to re-read HTMLParser's doc. Else if you assumed list had an iteritems method, then it's probably time to re-read the Python's tutorial !-) IIRC, HTMLParser represents attributes as a list of (attrname, value) pairs. If so (please check it out), your method should be rewritten as return ' %s' % (' '.join(('%s="%s"') % attr for attr in attrs) As a side note: __double_leading_undescores is probably a bit extrem. The convention for implementation attributes is _single_leading_underscore. From ericdfirst at gmail.com Wed Jul 23 13:09:35 2008 From: ericdfirst at gmail.com (Eric First) Date: Wed, 23 Jul 2008 12:09:35 -0500 Subject: Wrapping std::set in Boost::Python Message-ID: <349c44440807231009g4908787ekdcbc930595781647@mail.gmail.com> All: Has anybody had success at wrapping std::set using Boost::Python? Any ideas, snippets of code, etc... would be very helpful. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwahler at gmail.com Thu Jul 10 00:13:31 2008 From: dwahler at gmail.com (David Wahler) Date: Wed, 9 Jul 2008 23:13:31 -0500 Subject: sort(cmp=func) In-Reply-To: References: Message-ID: On Wed, Jul 9, 2008 at 10:58 PM, Daniel Fetchinson wrote: > > > I have a list of objects that generate code. Some > > of them depend on others being listed first, to > > satisfy dependencies of others. > > > > I wrote a cmp function something like this: > > > > def dep_cmp(ob1, ob2): > > > > if ob1.name in ob2.deps: > > return -1 > > else: > > return 1 > > > > I also tried returning 0 when there were no dependency > > relationships between the objects. > > > > This failed, because every object was not compared with > > ever other. I imagine that this is because sort assumes > > that if a > b and b > c, then a > c. In my case, this > > isn't really true. If a is not dependent on b, and > > b is not dependent on c, that doesn't mean that a is not > > dependent on c. > > > > Is there a better way? > > It's only meaningful to talk about sorting if your particular > definition of "<" is transitive. I.e. a < b and b < c should imply a < > c. If this is not satisfied, it doesn't make sense to sort according > to your "<" definition. It's just not a well-defined operation and no > trick will make it work. > Presumably what the OP really wants is to sort using the transitive closure of dep_cmp, which is a topological sort. http://en.wikipedia.org/wiki/Topological_sorting has details and a linear-time algorithm. -- David From max at alcyone.com Tue Jul 29 16:12:48 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 13:12:48 -0700 Subject: iterating "by twos" In-Reply-To: References: <70a172ac-0491-4918-9c74-6a577f35068a@d45g2000hsc.googlegroups.com> Message-ID: giltay at gmail.com wrote: > Whoops, I misread the original post. That would be: > > for x, y in zip(a[::2], a[1::2]): > frob(x, y) > > ... which I don't use a lot. Sorry, posted before I saw your reply. Still, you're building three sublists in order to just iterate over them. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Tell me the truth / I'll take it like a man -- Chante Moore From goldtech at worldpost.com Sun Jul 13 17:00:04 2008 From: goldtech at worldpost.com (goldtech) Date: Sun, 13 Jul 2008 14:00:04 -0700 (PDT) Subject: SAX XML Parse Python error message References: <487A23A5.7000905@behnel.de> Message-ID: I would be grateful for support with the code I cited. It's not long and fairly standard. I'm sure my error(s) would be glaring to more experienced coders. I appreciated the "heads-up" about other options but I would be grateful for help getting this code to run. Thanks On Jul 13, 11:47 am, Stefan Behnel wrote: > goldtech wrote: > > My first attempt at SAX, but have an error message I need help with. > > Just in case you prefer writing readable code over debugging SAX code into > existence, try lxml. > > http://codespeak.net/lxml/ > > Here is a presentation you might find interesting. > > http://codespeak.net/lxml/s5/lxml-ep2008.html > > Stefan From tn.pablo at gmail.com Tue Jul 22 09:27:13 2008 From: tn.pablo at gmail.com (ptn) Date: Tue, 22 Jul 2008 06:27:13 -0700 (PDT) Subject: Converting List of String to Integer References: Message-ID: > n = [] > for k in a: > ? ? n.append([int(v) for v in k]) > print n > > Does anyone know what I am doing wrong? > > Thanks in advance. > > Samir Use extend instead of append: * Append -> add the one item to the end of the list * Extend -> add the list of items to the end of the list From larzluv at hotmail.com Sat Jul 19 19:08:27 2008 From: larzluv at hotmail.com (Larry Hale) Date: Sat, 19 Jul 2008 16:08:27 -0700 (PDT) Subject: Help Tracing urllib2 Error, Please? Message-ID: <263aa5e2-f620-4d17-b95d-bd0b81f934a6@8g2000hse.googlegroups.com> Since it seems I have a "unique" problem, I wonder if anyone could point me in the general/right direction for tracking down the issue and resolving it myself. See my prior post @ http://groups.google.com/group/comp.lang.python/browse_thread/thread/44775994a6b55161?hl=en# for more info. (Python 2.5.2 on Win XP 64 ==>> Squid Proxy requiring Authentication ==>> Internet not working.) I've looked the urllib2 source over, but am having trouble following it. As previously mentioned, urllib2 initiates the request, Squid replies "407 error" that auth's required, and then urllib2 just stops, throwing error 407. Any though(s) on what to check out? It's frustrating (to say the least) that it seems so many are successfully accomplishing this task, and all's working perfectly for them, but I'm failing miserably. Would any quotes viewed in the HTTP traffic help? (Wireshark shows all! :) I don't even know what other info could help. Any info to get about Squid's configuration that might make it "non standard" in a way that could cause my problem? Any question(s) I should ask my Net Admin to relay info to you all? As always, any/all help greatly appreciated. Thanks! :) -Larry From modelnine at modelnine.org Wed Jul 30 08:22:34 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Wed, 30 Jul 2008 14:22:34 +0200 Subject: Proxy server? In-Reply-To: References: <6f6sk7Fa4tf5U1@mid.uni-berlin.de> Message-ID: <200807301422.34853.modelnine@modelnine.org> Am Mittwoch, 30. Juli 2008 13:48:08 schrieb Gary: > "Diez B. Roggisch" wrote in message > news:6f6sk7Fa4tf5U1 at mid.uni-berlin.de... > > > Gary schrieb: > > > "Diez B. Roggisch" wrote in message > > > news:6f5rteF89muqU2 at mid.uni-berlin.de... > > > > You can't make any TCP/IP communication run through a proxy, unless it's > > transparent. > > Thanks for all the info. This is not entirely true. There are libc-plugins (i.e. LD_PRELOAD hacks) which use SOCKS (which is a generic proxying protocol for [TCP/]IP) to redirect all locally originating TCP/IP traffic _which is managed through the socket interface of the libc_ in the application that you applied the LD_PRELOAD hack to through a specified SOCKS-proxy (this should capture pretty much everything, except for communication originating in the *nix-kernel itself). I seem to recall that something similar exists for WinSock, but I wouldn't know for sure. Check the web for documentation on setting up a SOCKS proxy, and for the respective libc-plugins or WinSock SOCKS "hack". If you cannot make the user use SOCKS through a means like this (in which case there has to be no application support) or by instructing a specific application to use a SOCKS proxy directly (which all browsers can out of the box AFAIK), and you don't have the possibility to put yourself somewhere in the middle by means of a transparent proxy (i.e., a firewall applicance which does this; I seem to recall that there was some FreeBSD-based software which basically did just this kind of transparent proxying for a network), you're out of luck, just like Diez said. -- Heiko Wundram From RonVick at Nospam.com Thu Jul 10 16:21:16 2008 From: RonVick at Nospam.com (RLV) Date: Thu, 10 Jul 2008 16:21:16 -0400 Subject: Can anyone suggest a date peocedure... Message-ID: I'd like to find a simple... (I'm a simple person) procedure to subtract a numerical number from a six char date string YYYYMMDD and then convert back to a new date string. I'm sure there's a way to do it, but the date modules haven't been much help. TIA Ron From google at mrabarnett.plus.com Wed Jul 2 11:25:42 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 2 Jul 2008 08:25:42 -0700 (PDT) Subject: simple UnZip References: <5b915a0e-a227-460f-8273-ecc01b800884@2g2000hsn.googlegroups.com> Message-ID: On Jul 2, 3:07?pm, C?dric Lucantis wrote: > Le Wednesday 02 July 2008 15:39:51 noydb, vous avez ?crit?: > > > > > Can someone help me with this script, which I found posted elsewhere? > > I'm trying to figure out what is going on here so that I can alter it > > for my needs, but the lack of descriptive names is making it > > difficult. ?And, the script doesn't quite do anything worthwhile -- it > > unzips one file from a zipfile, not all files in a zipfile. > > > *** > > import zipfile, os, sys, glob > > > os.chdir("C:\\Temp") > > zips = glob.glob('*.zip') > > > for fzip in zips: > > ? ? if zipfile.is_zipfile(fzip): > > ? ? ? ? print fzip," is a zip" > > ? ? ? ? z = zipfile.ZipFile(fzip,'r') > > ? ? ? ? lstName = z.namelist() > > ? ? ? ? sHgt = lstName[0] > > ? ? ? ? print "Unpacking",sHgt > > ? ? ? ? hgt = z.read(sHgt) > > ? ? ? ? fHgt = open(sHgt,'wb') > > ? ? ? ? fHgt.write(hgt) > > ? ? ? ? # fHgt.flush > > ? ? ? ? fHgt.close > > print "Finished" > > *** > > > I changed it somewhat to > > &&& > > import zipfile, os, sys > > > event_zip = ("C:\\Temp\\data4event.zip") > > > z = zipfile.ZipFile(event_zip, 'r') > > > zList = z.namelist() > > > for zItem in zList: > > ? ? print "Unpacking",zItem > > ? ? zRead = z.read(zItem) > > ? ? z1File = open(zItem,'wb') > > ? ? z1File.write(zRead) > > ? ? z1File.close It's not actually closing the file. It should be: z1File.close() > > namelist() returns a list of relative file names, so you can just put them > anywhere you want with: > > zlFile = open(os.path.join(DESTDIR, zItem), 'wb') > > or change the current directory, but the first way should be preferred. > > > print "Finished" > > &&& > > > This works, but I want to be able to specify a different output > > location. > > -- > C?dric Lucantis From andreas.mock at web.de Tue Jul 15 08:27:33 2008 From: andreas.mock at web.de (McA) Date: Tue, 15 Jul 2008 05:27:33 -0700 (PDT) Subject: Logging to different addressees Message-ID: <8df30038-86c1-4376-b046-a50f2bcf0a2b@s50g2000hsb.googlegroups.com> Hi all, I need a recommendation. I would to like to use the logging module to create log messages the following way: a) Every log message does go to a admin sink. b) The logging of special messages should go to the admin sink AND to a sink specifically for a certain addressee. c) I don't want to write the log message to two different loggers for that purpose. I would like to do it this way: common_logger.log('bla') -> message to admin sink certain_logger.log('something' -> message to admin sink and addressee- sink d) Filtering and debug level should work as expected. I could I achieve this in a elegant way? Best regards Andreas Mock From ptmcg at austin.rr.com Thu Jul 31 19:05:21 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 31 Jul 2008 16:05:21 -0700 (PDT) Subject: simple problem with lists I am just forgetting References: Message-ID: On Jul 31, 2:51?pm, Alexnb wrote: > Lets say we have this list: > > funlist = ['a', 'b', 'c'] > > and lets say I do this: > > if funlist[4]: > ? ? print funlist[4] > > I will get the exception "list index out of range" > > How can I test if the list item is empty without getting that exception? Try using a slice. Slices are ignorant of list index validity. funlist = list("abc") # too lazy to type ['a', 'b', 'c'] if funlist[4:]: print funlist[4] Voila! No exception! -- Paul From deets at nospam.web.de Thu Jul 31 07:57:28 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 13:57:28 +0200 Subject: How smart is the Python interpreter? References: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> Message-ID: <6fdnnhFb5flqU1@mid.uni-berlin.de> ssecorp wrote: > def str_sort(string): > s = "" > for a in sorted(string): > s+=a > return s > > > if i instead do: > > def str_sort(string): > s = "" > so = sorted(string) > for a in so: > s+=a > return s > > > will that be faster or the interpreter can figure out that it only has > to do sorted(string) once? or that kind of cleverness is usually > reserved for compilers and not interpreters? There isn't much cleverness involved here - why on earth should one execute the sorted(string) several times? The for in construct will evaluate the of course only once. Diez From digitig at gmail.com Fri Jul 4 13:11:14 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 4 Jul 2008 18:11:14 +0100 Subject: Can't get Python for Windows to run In-Reply-To: <486E4125.5080201@timgolden.me.uk> References: <486E4125.5080201@timgolden.me.uk> Message-ID: 2008/7/4 Tim Golden : > Ummm. That's the Python interpreter but without a window so > (unhelpfully, from your point of view) it's doing exactly the > right thing. > > I assume you were trying to run the PythonWin Python > interpreter and dev env? On my system, that's: > > C:\Python25\Lib\site-packages\pythonwin\Pythonwin.exe Ah! Something that would have been blindingly obvious had it successfully installed the shortcuts, but something I would never have worked out as it was! Many thanks. Is it worth flagging as an issue somewhere the fact that the pywin installer assumes a particular structure for the start menu, and fails to install shortcuts if it doesn't find that structure? I'm used to programs asking me where they want to put the shortcuts, and creating folders if they don't find them (creating *without* asking would, of course, a Hostile Act). -- Tim Rowe From Tribulations at Paralleles.invalid Tue Jul 8 01:21:49 2008 From: Tribulations at Paralleles.invalid (TP) Date: Tue, 08 Jul 2008 07:21:49 +0200 Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> <6ddj74F21uhjU1@mid.individual.net> <4cv8k5-dsg.ln1@rama.nodalpoint> <6dg740F2b1mkU1@mid.individual.net> Message-ID: Peter Pearson wrote: > I don't understand exactly what you mean by "Sorry" I means: please forgive me for having said that it does not work with variables, because it is completely false. Thanks one more time Julien -- TP (Tribulations Parall?les) "Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert). From aaron.hildebrandt at gmail.com Wed Jul 23 17:19:34 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 23 Jul 2008 14:19:34 -0700 (PDT) Subject: Using variables across modules References: <855136ce-6c70-40ac-a462-dc0bbfa1fc3a@b2g2000prf.googlegroups.com> Message-ID: > first read this to learn how objects and variables work in Python: > > ? ? ?http://effbot.org/zone/python-objects.htm > > and then read this to learn how from-import works, and when you're > supposed to use it: > > ? ? ?http://effbot.org/zone/import-confusion.htm > > hope this helps! > Awesome. After reading those two pages, I was able to correct the code and get things up and running. Thanks! Aaron From Russ.Paielli at gmail.com Sun Jul 27 02:26:28 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 26 Jul 2008 23:26:28 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> Message-ID: <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> On Jul 26, 11:18 pm, Terry Reedy wrote: > Colin J. Williams wrote: > > Russ P. wrote: > >> class MyClass: > > >> def func( , xxx, yyy): > > >> .xxx = xxx > > >> local = .yyy > > The use of '.' has been suggested before and rejected. Where and why? From emen999 at gmail.com Tue Jul 29 08:51:49 2008 From: emen999 at gmail.com (code_berzerker) Date: Tue, 29 Jul 2008 05:51:49 -0700 (PDT) Subject: SWIG and char* newb questions :) References: <7ec26fb6-3d6a-4e1b-b2c9-a0a254780153@26g2000hsk.googlegroups.com> Message-ID: Ok I think I got it: PyObject* myFuncXXX(char* p_1, int p_2, char* p_3, int p_4) { int res; char _host[255] = ""; int _port; res = funcXXX(p_1, p_2, p_3, p_4, _host, &_port); PyObject* res1 = PyInt_FromLong(res); PyObject* res2 = PyString_FromStringAndSize(_host, strlen(_host)); PyObject* res3 = PyInt_FromLong(_port); PyObject* resTuple = PyTuple_New(3); PyTuple_SetItem(resTuple, 0, res1); PyTuple_SetItem(resTuple, 1, res2); PyTuple_SetItem(resTuple, 2, res3); return resTuple; } It seems to work when I put it into swig's "*.i" file. me proud of me.self :D From jaycx2.3.calrobert at spamgourmet.com.remove Sun Jul 20 13:36:21 2008 From: jaycx2.3.calrobert at spamgourmet.com.remove (Robert Maas,) Date: Sun, 20 Jul 2008 10:36:21 -0700 Subject: The Importance of Terminology's Quality References: <48617847$0$5021$607ed4bc@cv.net> <486ae06b$0$5011$607ed4bc@cv.net> Message-ID: > >> ... the "thunks" were necessary at the machine-language level to > >> /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. > > Ah, thanks for the clarification. Is that info in the appropriate > > WikiPedia page? If not, maybe you would edit it in? > From: John W Kennedy > It is explained s.v. "thunk", which is referenced from "ALGOL > 60". The ALGOL "pass-by-name" argument/parameter matching was > perhaps the most extreme example ever of a language feature that > was "elegant" but insane. What it meant, in effect, was that, > unless otherwise marked, every argument was passed as two closures, > one that returned a fresh evaluation of the expression given as the > argument, which was called every time the parameter was read, and > one that set the argument to a new value, which was called every > time the parameter was set. Wow! All these years when I occasionally heard of a "thunk" I never was told, until now, what it really meant. Thanks for the info!! Followup question #1: I assume these are lexical closures in the environment of the point of the call, right? Followup question #2: For simple arithmetic expressions, I can possibly understand how the UPDATE closure might be implemeted (expressed in Lisp to make the intent clear): Call form: MyFunction(X+2); GET closure: (+ closedX 2) UPDATE closure: (lambda (newval) (setf closedX (- newval 2)) Thus from inside MyFunction where formal parameter Arg1 is bound to actual parameter X+2, after doing Arg1 := 7; X will have the value 5 so that calling Arg1 will return 7 as expected, right? But if the actual argument is something complicated, especially if it makes a nested function call, how can that possibly be implemented? Given an arbitrary expression that calls some external function, how can assigning a value to that expression make sufficient changes in the runtime environment such that subsequently evaluating that expression will yield the expected value i.e. the value that had been assigned? Or is the default of passing two closures (GET and UPDATE) *only* if the actual-argument expression is simple enough that it's invertible, and in complicated cases only a GET closure is passed (or the UPDATE closure is simply a signal of a runtime error that you're not allowed to assign a value to a complicated expression)? IMO the "right" way to pass parameters that can be modified is to use "locatatives" as in the Lisp Machine. That converts the idea of a "place" (as used by SETF in Common Lisp) into a "first class citizen" which can be passed around and stored etc., compared to a SETF place which is merely a compiletime-macro trick to convert place-references in source code into direct calls to the appropriate accessor just above the place followed by specialized SETter call to do the act. A hack to emulate a locative in CL would be to pass a closure where the code to find the object directly containing the place, and any parameters needed to find that place, and the function needed to perform the act. Then the called function would need to know it's going to get such a thunk-like closure, but since it's expecting to modify one of its parameters anyway, that's reasonable. Sketch of implementation (two special cases): (defun make-thunk-cadr (topptr) (let* ((midptr (cdr topptr)) (getclo (make-getter-closure :PARENT midptr :GETTERFN #'car :PARMS nil)) (setclo (make-setter-closure :PARENT midptr :SETTERFN #'rplaca :PARMS nil))) (make-thunk getclo setclo)) (defun make-thunk-aref1 (topptr arrindex1) (let ((getclo (make-getter-closure :PARENT topptr :GETTERFN #'aref1 :PARMS (list arrindex1))) (setclo (make-setter-closure :PARENT midptr :SETTERFN #'setaref1 :PARMS (list arrindex1)))) (make-thunk getclo setclo)) (defun swap (thunk1 thunk2) (prog (tmp) (setq tmp (thunk-get thunk1)) (thunk-set thunk1 (thunk-get thunk2)) (thunk-set thunk2 tmp))) ;Definitions of make-getter-closure make-setter-closure make-thunk ; thunk-get thunk-set not shown because they depend on whether ; closures and thunks are implemented via tagged assoc lists or ; DEFSTRUCT structures or CLOS objects or whatever. But I made the ; call to the constructors explicit enough that it should be obvious ; what components are inside each type of object. Note that with ; CLOS objects, this could all be condensed to have a single CLOS ; object which is the thunk which has two methods GET and SET, no ; need to make closures for get and set separately, templates for ; those closures are made automatically when the CLOS class is ; defined, and closures are generated from those templates whenever ; a new CLOS thunk-object is made. Thus: ; ... (make-CLOS-thunk :PARENT topptr :GETTERFN #'aref1 :SETTERFN #'setaref1 ; :PARMS (list arrindex1)) ... ;Example that should actually work: (format t " arr: ~S~% ixs: ~S~%" arr ixs) arr: #'(3 5 7 11 13)) ixs: (2 4) (setq arr #'(3 5 7 11 13)) (setq ixs (list 2 4)) (setq thunkcadr (make-thunk-cadr ixs)) ;Locative to the 4 in ixs (setq thunkaref (make-thunk-aref1 arr (thunk-get thunkcadr))) ;Locative to the 11 in the array (swap thunkcadr thunkaref) (format t " arr: ~S~% ixs: ~S~%" arr ixs) arr: #'(3 5 7 4 13)) ixs: (2 11) I haven't implemented this. I'm just specifying what the behaviour should be and giving a sketch how it ought to be easily doable in Common Lisp. And I'm not going to implement it because I have no use for this way of coding, at least not currently or in the foreseeable future. Generally my abstract data type is at a higher level where the caller doesn't know that a single place is going to need to be SETFed, so there's no point in getting a locative to work with. Instead there's some *kind* of update to do, and parameters to that *kind* of update; what really happens internally (one or more SETFs, or alternately re-build anything that changed and share what didn't change) doesn't need to be known by the caller. All the caller needs to know is generically whether the update is in-place or non-destructive. (If it's non-destructive, then the new edition of the data structure is one of the return values. If it's in-place, then there's no need to bother with setq of the new value, because my structures always have a header cell that has a tag for the intentional datatype, and that header cell always points to either the in-place-modified object or the latest-edition-of-object.) I'd rather program in "paranoid" mode than in "risk shoot foot" mode. The CAR of each ADT object is a keyword identifying the intentional type of that object, and every function that operates on that intentional type first checks if the parameter really does have the expected CAR, just to make sure I didn't copy&paste some inappropriate function name in my code. Yeah, it takes extra CPU cycles to do that checking on every calls, but it sure saves me from shooting myself in the foot and having to spend an hour to find out how I did it before I can fix it. TMI = Too Much Information (actually YMMV, some readers might like it) MTMI = More of Too Much Information EMTMI = Even More of Too Much Information (only newbies need read) Credits to Babylon Five for the "I spy" game in the cargo hold. I spy something that starts with the letter B. Boxes! I spy something that starts with the letter M. More boxes! From akathorn at gmail.com Mon Jul 14 10:01:07 2008 From: akathorn at gmail.com (Akathorn Greyhat) Date: Mon, 14 Jul 2008 15:01:07 +0100 Subject: Dictionary bidirectional In-Reply-To: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> Message-ID: This is a better version of the class that I sen't you, now it raises a KeyError when you try to insert a value that is already in ############################ class MyCoolDictionary(dict): def __init__(self, *args, **kargs): dict.__init__(self, *args, **kargs) def __setitem__(self, *args, **kargs): for i in dictio.values(): if args[0]==i or args[1]==i: raise KeyError, 'Value already exists' dict.__setitem__(self, *args, **kargs) def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: keys=[] for i in dictio.keys(): if dictio[i]==item: keys.append(i) if not keys: raise KeyError, 'Can\'t found key or value "' + str(item) + '"' return keys ############################ Feel free to change anything you want or need Regards, Akathorn Greyhat 2008/7/14 Kless : > I need a dictionary where get the result from a 'key' (on left), but > also from a 'value' (on right), how to get it? > > I know that dictionaries aren't bidirectional, but is there any way > without use two dictionaries? > > > Thanks in advance! > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stesch at no-spoon.de Wed Jul 16 04:35:07 2008 From: stesch at no-spoon.de (Stefan Scholl) Date: Wed, 16 Jul 2008 10:35:07 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> Message-ID: <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> Dave U. Random wrote: > http://snipr.com/PracticalDjango June 2008 is a bit too early. Django isn't ready. -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ From cartercc at gmail.com Tue Jul 22 15:56:39 2008 From: cartercc at gmail.com (cartercc) Date: Tue, 22 Jul 2008 12:56:39 -0700 (PDT) Subject: proliferation of computer languages References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> Message-ID: On Jul 18, 1:17 pm, "xah... at gmail.com" wrote: > Today, i took sometime to list some major or talked-about langs that > arose in recent years. You missed PowerShell and ActionScript. Languages are just tools. It may have escaped your notice, but it's a remarkable fact that no two languages are alike! It's not the language that we should focus on, but the task at hand. Personally, I feel that we can gain a lot more by studying the different kinds of problems we can solve by computing and relate the language to the job, rather than learning a language and then trying to find a fit with a particular class of problems. If you look at TIOBE and the like, you will note that the top four language categories (Java/JavaScript, C/C++, Basic, and Perl/Python/ Ruby) account for around eighty percent of the language usage (not counting PHP), and all the other languages quickly fall off. No. 13 on the TIOBE rating was PL/SQL at 0.073 percent. If you read the employment ads (Dice, etc.) the percentage is even greater for the big languages. To me, this indicates that we have several mainstream languages that account for the vast majority of work and a vast number of task specific languages for special purposes. CC From __peter__ at web.de Fri Jul 4 07:24:53 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Jul 2008 13:24:53 +0200 Subject: Bug in re.findall? References: Message-ID: Marcin Krol wrote: > Hello everyone, > > Is there a bug in re.findall in Python 2.4? See: > > subnetlist="192.168.100.0 , 192.168.101.0" > ipre=re.compile("([0-9]{1,3}\.){3}[0-9]{1,3}") > > >>> ipre.findall(subnetlist) > > ['100.', '101.'] > > > But: > > a=ipre.finditer(subnetlist) > > >>> a.next().group() > '192.168.100.0' > >>> a.next().group() > '192.168.101.0' > >>> a.next().group() > Traceback (most recent call last): > File "", line 1, in ? > StopIteration > > Also: > > >>> ipre.search(subnetlist).group() > '192.168.100.0' > > Is this a bug or am I doing smth wrong? >From the doc: """ findall( pattern, string[, flags]) Return a list of all non-overlapping matches of pattern in string. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. """ So findall()'s behaviour changes depending on the number of explicit groups None: [m.group() for m in re.finditer(...)] One: [m.group(1) for m in re.finditer(...)] More than one: [m.groups() for m in re.finditer(...)] all in accordance with the documentation. Peter From mrkafk at gmail.com Wed Jul 2 12:08:41 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Wed, 02 Jul 2008 18:08:41 +0200 Subject: Bloody signal handling (in embedded Python code) Message-ID: Hello everyone, And now for something completely different: signal handling sometimes works, sometimes it doesn't. When I embed following code, it works: count = 0 def test(): global count while True: count += 1 if (count % 100000 == 0): print count if __name__ == "__main__": test() It nicely does what signal handler function tells it to do and exits. However, when I embed this code, it segfaults on receiving the signal: import time def test(): time.sleep(1) print "success" time.sleep(90) if __name__ == "__main__": test() Does it have something to do with the fact that the program receiving the signal sleeps? The C code of segfaulting program: #include #include #include #include #include #include void userbreak(int sig) { Py_Finalize(); printf("Interrupted..\n"); exit(sig); } void terminaterun(int sig) { Py_Finalize(); printf("Received SIGTERM. Terminating.\n"); exit(sig); } int main(int argc, char **argv) { Py_Initialize(); PyObject *pyCode, *mainmodule, *maindict; mainmodule = PyImport_AddModule("__main__"); maindict = PyModule_GetDict(mainmodule); unsigned int size = 326; unsigned char python_code[] = { 0x63,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00, 0x40,0x00,0x00,0x00,0x73,0x2E,0x00,0x00,0x00,0x64, 0x00,0x00,0x6B,0x00,0x00,0x5A,0x00,0x00,0x64,0x01, 0x00,0x84,0x00,0x00,0x5A,0x01,0x00,0x65,0x02,0x00, 0x64,0x02,0x00,0x6A,0x02,0x00,0x6F,0x0B,0x00,0x01, 0x65,0x01,0x00,0x83,0x00,0x00,0x01,0x6E,0x01,0x00, 0x01,0x64,0x00,0x00,0x53,0x28,0x03,0x00,0x00,0x00, 0x4E,0x63,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x02,0x00,0x00,0x00,0x43,0x00,0x00,0x00,0x73,0x23, 0x00,0x00,0x00,0x74,0x00,0x00,0x69,0x01,0x00,0x64, 0x01,0x00,0x83,0x01,0x00,0x01,0x64,0x02,0x00,0x47, 0x48,0x74,0x00,0x00,0x69,0x01,0x00,0x64,0x03,0x00, 0x83,0x01,0x00,0x01,0x64,0x00,0x00,0x53,0x28,0x04, 0x00,0x00,0x00,0x4E,0x69,0x01,0x00,0x00,0x00,0x74, 0x07,0x00,0x00,0x00,0x73,0x75,0x63,0x63,0x65,0x73, 0x73,0x69,0x5A,0x00,0x00,0x00,0x28,0x02,0x00,0x00, 0x00,0x74,0x04,0x00,0x00,0x00,0x74,0x69,0x6D,0x65, 0x74,0x05,0x00,0x00,0x00,0x73,0x6C,0x65,0x65,0x70, 0x28,0x00,0x00,0x00,0x00,0x28,0x00,0x00,0x00,0x00, 0x28,0x00,0x00,0x00,0x00,0x74,0x07,0x00,0x00,0x00, 0x74,0x65,0x73,0x74,0x2E,0x70,0x79,0x74,0x04,0x00, 0x00,0x00,0x74,0x65,0x73,0x74,0x05,0x00,0x00,0x00, 0x73,0x06,0x00,0x00,0x00,0x00,0x01,0x0D,0x01,0x05, 0x01,0x74,0x08,0x00,0x00,0x00,0x5F,0x5F,0x6D,0x61, 0x69,0x6E,0x5F,0x5F,0x28,0x03,0x00,0x00,0x00,0x52, 0x01,0x00,0x00,0x00,0x52,0x04,0x00,0x00,0x00,0x74, 0x08,0x00,0x00,0x00,0x5F,0x5F,0x6E,0x61,0x6D,0x65, 0x5F,0x5F,0x28,0x02,0x00,0x00,0x00,0x52,0x04,0x00, 0x00,0x00,0x52,0x01,0x00,0x00,0x00,0x28,0x00,0x00, 0x00,0x00,0x28,0x00,0x00,0x00,0x00,0x52,0x03,0x00, 0x00,0x00,0x74,0x01,0x00,0x00,0x00,0x3F,0x03,0x00, 0x00,0x00,0x73,0x06,0x00,0x00,0x00,0x09,0x02,0x09, 0x05,0x0D,0x01 }; pyCode = PyMarshal_ReadObjectFromString((PyObject *) python_code, size); (void) signal(SIGINT, userbreak); (void) signal(SIGTERM, terminaterun); PyEval_EvalCode(pyCode, maindict, maindict); Py_Finalize(); } From Russ.Paielli at gmail.com Wed Jul 30 02:47:21 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 23:47:21 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> <6d906dd5-bf5a-44d5-a5a8-3875027f6b91@v26g2000prm.googlegroups.com> Message-ID: <0f0b03c9-794b-430b-88ab-18a68505109e@a21g2000prf.googlegroups.com> On Jul 29, 11:36 pm, Erik Max Francis wrote: > Russ P. wrote: > > Come to think of it, shouldn't the list type have an "isempty" method? > > Or does it? > > Yes. It's written: > > if not aList: > ... As you know, that is not quite exactly the same thing. An "isempty" method would fail if aList were an integer, and such failure might be desirable if someone mistakenly had aList pointing to an integer. From rcdailey at gmail.com Wed Jul 30 15:27:55 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 30 Jul 2008 14:27:55 -0500 Subject: Reasoning behind 'self' parameter in classes? In-Reply-To: <4890ACE4.4060703@acm.org> References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> <4890ACE4.4060703@acm.org> Message-ID: <496954360807301227h1dea050eg735314beb0b5ff16@mail.gmail.com> On Wed, Jul 30, 2008 at 1:03 PM, Brett g Porter wrote: > Robert Dailey wrote: > > This is an example of a response I'm looking for: >> "The self parameter is required because the parser is a bit old and needs >> to know the exact object you're referencing" >> >> This is _not_ an example of what I'm looking for: >> "Specifying self is a great mysterious thing that we should never >> question. Do not question the language! The language is mighty! Don't bring >> C++ to Python!" >> >> > Fredrik Lundh has written a very clear explanation of this at > http://effbot.org/pyfaq/why-must-self-be-used-explicitly-in-method-definitions-and-calls.htm > > (or http://bit.ly/3EUiCf if you don't feel like stitching that URL back > together...) > This sounds like an article of opinion. He's not really given any reasons other than "Well, it makes this easier or look better". True that declarations are the determining factor in C/C++, however I was thinking of more or less an implied 'self'. For example: # Consider this normal syntax: class MyFoo: def DoFoo( self ): self._member = 6 # Elimintating 'self' in the parameter list should still work as far as the # interpreter is concerned, since 'self' in this case now acts like 'this' # in C++. The below code should be equivalent. class MyFoo: def DoFoo(): self._member = 6 Given the code samples above, is there any technical reason why this cannot be done? Thanks for the input guys, and thanks more over for keeping this easy-going. -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Sun Jul 27 14:10:33 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 27 Jul 2008 11:10:33 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> <87ljzpt3lv.fsf@nokile.rath.org> Message-ID: <826f6075-40ff-4da0-a178-b53d90ab3096@z66g2000hsc.googlegroups.com> On Jul 27, 2:56?am, Nikolaus Rath wrote: > Terry Reedy writes: > >> What he wants is to write > > > ?> class foo: > >> ? ?def bar(arg): > >> ? ? ? ?self.whatever = arg + 1 > > >> instead of > > >> class foo: > >> ? ?def bar(self, arg) > >> ? ? ? ?self.whatever = arg + 1 > > >> so 'self' should *automatically* only be inserted in the function > >> declaration, and *manually* be typed for attributes. > > > which means making 'self' a keyword just so it can be omitted. Silly > > and pernicious. > > Well, I guess that's more a matter of personal preference. I would go > for it immediately (and also try rename it to '@' at the same time). > > Best, > > ? ?-Nikolaus > > -- > ??It is not worth an intelligent man's time to be in the majority. > ? By definition, there are already enough people to do that.? > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?-J.H. Hardy Hardy has an interesting claim. OT. He has omitted a couple of lemmas, which aren't true. 1: There are enough people to be in the majority. 2: It is not worthwhile to be in the majority. 3: There is no majority of worthwhile timespending. 4: There is no majority of intelligent men. 5: Being in the majority takes time. It is worth some intelligent men's time to be in the majority; the majority of intelligent men are intelligent men, and are in the majority of intelligent men. Perhaps it is merely not worth their time to be. From mrkafk at gmail.com Wed Jul 2 11:44:18 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Wed, 02 Jul 2008 17:44:18 +0200 Subject: Importing modules in embedded Python Message-ID: Hello everyone, I can embed Python interpreter in C code now, but now there's another problem, importing modules in Python code doesn't work: Exception exceptions.ImportError: '/usr/lib/python2.4/lib-dynload/timemodule.so: undefined symbol: PyModule_AddObject' in 'garbage collection' ignored Fatal Python error: unexpected exception during garbage collection Aborted The (autogenerated) C code: ---cut--- #include #include #include #include #include #include void userbreak(int sig) { Py_Finalize(); printf("Interrupted..\n"); exit(sig); } void terminaterun(int sig) { Py_Finalize(); printf("Received SIGTERM. Terminating.\n"); exit(sig); } int main(int argc, char **argv) { Py_Initialize(); PyObject *pyCode, *mainmodule, *maindict; mainmodule = PyImport_AddModule("__main__"); maindict = PyModule_GetDict(mainmodule); unsigned int size = 272; unsigned char python_code[] = { 0x63,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00, 0x40,0x00,0x00,0x00,0x73,0x16,0x00,0x00,0x00,0x64, 0x00,0x00,0x6B,0x00,0x00,0x5A,0x00,0x00,0x64,0x01, 0x00,0x84,0x00,0x00,0x5A,0x01,0x00,0x64,0x00,0x00, 0x53,0x28,0x02,0x00,0x00,0x00,0x4E,0x63,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00, 0x43,0x00,0x00,0x00,0x73,0x23,0x00,0x00,0x00,0x74, 0x00,0x00,0x69,0x01,0x00,0x64,0x01,0x00,0x83,0x01, 0x00,0x01,0x64,0x02,0x00,0x47,0x48,0x74,0x00,0x00, 0x69,0x01,0x00,0x64,0x03,0x00,0x83,0x01,0x00,0x01, 0x64,0x00,0x00,0x53,0x28,0x04,0x00,0x00,0x00,0x4E, 0x69,0x01,0x00,0x00,0x00,0x74,0x07,0x00,0x00,0x00, 0x73,0x75,0x63,0x63,0x65,0x73,0x73,0x69,0x5A,0x00, 0x00,0x00,0x28,0x02,0x00,0x00,0x00,0x74,0x04,0x00, 0x00,0x00,0x74,0x69,0x6D,0x65,0x74,0x05,0x00,0x00, 0x00,0x73,0x6C,0x65,0x65,0x70,0x28,0x00,0x00,0x00, 0x00,0x28,0x00,0x00,0x00,0x00,0x28,0x00,0x00,0x00, 0x00,0x74,0x07,0x00,0x00,0x00,0x74,0x65,0x73,0x74, 0x2E,0x70,0x79,0x74,0x04,0x00,0x00,0x00,0x74,0x65, 0x73,0x74,0x04,0x00,0x00,0x00,0x73,0x06,0x00,0x00, 0x00,0x00,0x01,0x0D,0x01,0x05,0x01,0x28,0x02,0x00, 0x00,0x00,0x52,0x01,0x00,0x00,0x00,0x52,0x04,0x00, 0x00,0x00,0x28,0x02,0x00,0x00,0x00,0x52,0x04,0x00, 0x00,0x00,0x52,0x01,0x00,0x00,0x00,0x28,0x00,0x00, 0x00,0x00,0x28,0x00,0x00,0x00,0x00,0x52,0x03,0x00, 0x00,0x00,0x74,0x01,0x00,0x00,0x00,0x3F,0x02,0x00, 0x00,0x00,0x73,0x02,0x00,0x00,0x00,0x09,0x02 }; pyCode = PyMarshal_ReadObjectFromString((PyObject *) python_code, size); (void) signal(SIGINT, userbreak); (void) signal(SIGTERM, terminaterun); PyEval_EvalCode(pyCode, maindict, maindict); Py_Finalize(); } ---cut--- The Python code: import time def test(): time.sleep(1) print "success" time.sleep(90) How do I manage to get modules imported? Anybody? From paddy3118 at googlemail.com Sun Jul 20 02:54:33 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 19 Jul 2008 23:54:33 -0700 (PDT) Subject: Question References: Message-ID: <2e60b845-58fa-416e-ac41-fac9f7e872bf@s50g2000hsb.googlegroups.com> On Jul 19, 10:27?am, perl_wiz... at manx.net wrote: > Why is Perl so much better than python? Coz its endorsed by: Chernobble valve controls. Barings Bank. The society of the Mortgage Brokers of America. The Bush Disaster relief fund for the Southern States. And, of course, is the tool of choice when looking for weapons of mass destruction in Iraq. - Paddy. From com.lewscanon at lew Tue Jul 22 09:54:06 2008 From: com.lewscanon at lew (Lew) Date: Tue, 22 Jul 2008 09:54:06 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: Rob Warnock wrote: > Martin Gregorie wrote: > +--------------- > | John W Kennedy wrote: > | > No, the "thunks" were necessary at the machine-language level to > | > /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. > | > | Are you sure about that? > +--------------- > > I don't know if John is, but *I* am! ;-} At this point we are so far off topic for clj.programmer, but still impinging on functional programming issues with the discussion of closures, et al., that I respectfully request that you all exclude clj.programmer from followups to this thread. (f-u set to comp.lang.functional) -- Lew From deets at nospam.web.de Thu Jul 31 08:39:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 14:39:50 +0200 Subject: working pylint anyone? References: <6fdf17Fb2bboU1@mid.uni-berlin.de> <8a08b59f-f7f0-4706-84c9-19f0460f09ef@k30g2000hse.googlegroups.com> Message-ID: <6fdq70Fb1t79U1@mid.uni-berlin.de> > Which version of python-logilab-common and python-logilab-astng are > installed on your machine ? By now, pylint 0.14 with logilab.common 0.27 and astng 0.17.2 I was able to track down the problem as being related to a custom init-hook. See the attached .pylintrc + hook. They don't actually *do* anything (or, the hook that is), but confuse pylint to spit out the reported error. Maybe you can track down the real reason for the error? > > I don't know where you checked, but there is some traffic on the > mailing list, > and questions generally get answered :-) On the website, I found this link: http://www.logilab.org/mailinglist/850 through the search. Diez -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: .pylint_init_hook.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: .pylintrc URL: From tjreedy at udel.edu Sat Jul 12 16:32:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 16:32:25 -0400 Subject: Weird lambda rebinding/reassignment without me doing it In-Reply-To: References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Thu, 10 Jul 2008 14:09:16 -0400, Terry Reedy wrote: > >>>>>>> g = lambda x:validate(x) >> This is doubly diseased. >> >> First, never write a 'name = lambda...' statement since it is equivalent >> to a def statement except that the resulting function object lacks a >> proper .funcname attribute. > > Using lambda in this way is no more "diseased" than aliasing any other > object. In the context of giving advice to a confused beginner, I disagree. He must learn def statements. Lambda expressions are optional. > It's a matter of personal preference not to bind a lambda to a > name. Functions, whether created by lambda or def, are first class > objects, and as such there's nothing wrong with binding them to names. When I brought this up on pydev, in the context of a style guide addition, about 9 of 10 respondants agreed that this should be discouraged. Alex Martelli reported his experience that this construction more often leads people to the useless wrapping of function calls, such as the OP posted, than the def statement equivalent does. One of the major reasons people give for wanting lambda expressions kept in Python and for using them is that they do not want to have to think up a name for short expressions. If such a person then turns around and binds the resulting function object to a name, then that rationale disappears. Over the years, people have written on c.l.p about 'lambdas' as if they were a separate class of objects somehow different from def objects (and not just an expression). I believe writing and reading both 'name = lambda ...' and 'def name(...' engenders and reinforces this delusion, especially for beginners. > Admittedly, the lack of a func_name attribute can sometimes make > tracebacks harder to understand, especially if you've got many bound > lambdas. Is saving two keystrokes worth that disadvantage, and the confusions mentioned above? To me, no. Hence my advice. Terry Jan Reedy From tbourden at doc.ic.ac.uk Sun Jul 27 14:26:39 2008 From: tbourden at doc.ic.ac.uk (Themistoklis Bourdenas) Date: Sun, 27 Jul 2008 19:26:39 +0100 Subject: method decorators and more on decorators Message-ID: <7fd737460807271126m3dbdea8cv4dbd8c9058d4faea@mail.gmail.com> Hi, is there any possible way to get the class or class name inside a method decorator? For example in the code sample below: def decorate(func): print type(func) return func class myclass: @decorate def foo(self): pass The output of this program will be the type of the supplied func in decorate, i.e. method foo. However, the type is function foo, a free function, not an instance method myclass.foo. On a related note, as the actual instance method of myclass is not foo but decorate(foo), why are they called method decorators? This does not decorate methods, they decorate functions and eventually the decorated functions become methods. The name method decorator sounds a bit misleading to me. So returning to my original question is there any way I can get the class inside decorate()? I guess there is not, but just asking to make sure. Speaking of decorators I'd also like to ask on the pending class decorators that should be coming in a following version of the language. Are they going to be in 2.6 or just 3.0? In the following example: def class_decorate(cls): print 'class_decorate' return cls def decorate(func): print 'decorate' return func @class_decorate class myclass: @decorate def foo(self): pass what will be the correct output? class_decorate decorate or decorate class_decorate In essence what is the order of application of class decorators compared to the function decorators of their methods? I couldn't find any mention of that issue in any of the PEPs. I guess it would be the latter, following the behavior of metaclasses, but better be certain than speculate :) Cheers, Themis -------------- next part -------------- An HTML attachment was scrubbed... URL: From digetl.try at gmail.com Sat Jul 26 06:01:11 2008 From: digetl.try at gmail.com (raja) Date: Sat, 26 Jul 2008 03:01:11 -0700 (PDT) Subject: EZ Recipe & Menu Costing Message-ID: <7edfbf9c-2c5b-4e0c-b767-3b835788d1c6@x29g2000prd.googlegroups.com> Customized Excel Workbook to Cost All Your Recipes & Menu Items http://food-drinks.page.tl/ From semanticist at gmail.com Sun Jul 13 22:29:27 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 22:29:27 -0400 Subject: socket.connect() hangs in SYN_SENT state. In-Reply-To: References: Message-ID: On Sat, Jul 12, 2008 at 11:23 PM, bukzor wrote: > Anyone know a general reason this might happen? Even better, a way to > fix it? Another reason that a socket can hang in the SYN_SENT state (besides trying to connect to an unreachable host without getting an ICMP destination-unreachable message in response): if the server's listen queue is full, it will silently ignore SYN packets until there is room in the queue. Sorry again about the "bukzor" vs. "buzkor" thing. I don't know what's causing your problem (and it's probably not a DNS issue after all) but it's more likely to be a server issue than a client one. Maybe your client has an unusually low socket timeout for some reason, though; does increasing it (with socket.setdefaulttimeout) help? Mine seems to default to about 75 seconds. If you can't work out the root cause, but it only happens every once in a while, you could try changing your client code to catch the socket exception and retry a limited number of times. -Miles From sniipe at gmail.com Mon Jul 7 08:49:09 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Mon, 7 Jul 2008 05:49:09 -0700 (PDT) Subject: I am looking for svn library(module) Message-ID: <6e1097a0-2a99-4885-a1ef-0684af5aa6a1@d1g2000hsg.googlegroups.com> Hi, I am looking fo svn library(module) which is used in the svn- mailer(http://opensource.perlig.de/svnmailer/) project. Does anybody know where can I find it(download url)? This is information which I received from python error: from svn import core as svn_core ImportError: No module named svn Best regards From moogyd at yahoo.co.uk Mon Jul 14 10:46:35 2008 From: moogyd at yahoo.co.uk (moogyd at yahoo.co.uk) Date: Mon, 14 Jul 2008 07:46:35 -0700 (PDT) Subject: Beginner Question : Iterators and zip References: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> <0ea30e6f-fcf4-4f39-a091-10b2a2178efd@l64g2000hse.googlegroups.com> Message-ID: <090ad4d5-761a-49b2-8927-3949bad9578b@m44g2000hsc.googlegroups.com> On 13 Jul, 19:49, Terry Reedy wrote: > moo... at yahoo.co.uk wrote: > > What is this *lis operation called? I am having trouble finding any > > reference to it in the python docs or the book learning python. > > One might call this argument unpacking, but > Language Manual / Expressions / Primaries / Calls > simply calls it *expression syntax. > "If the syntax *expression appears in the function call, expression must > evaluate to a sequence. Elements from this sequence are treated as if > they were additional positional arguments; if there are positional > arguments x1,...,*xN* , and expression evaluates to a sequence > y1,...,*yM*, this is equivalent to a call with M+N positional arguments > x1,...,*xN*,*y1*,...,*yM*." > > See Compound Statements / Function definitions for the mirror syntax in > definitions. > > tjr Thanks, It's starting to make sense :-) Steven From giveitawhril2008 at gmail.com Mon Jul 21 20:42:44 2008 From: giveitawhril2008 at gmail.com (giveitawhril2008 at gmail.com) Date: Mon, 21 Jul 2008 17:42:44 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <38394a86-80d0-4c19-84c6-12b5390aed9d@z72g2000hsb.googlegroups.com> On Jul 20, 9:18 pm, Michiel Overtoom wrote: . > > Many major text/word processing programs (Emacs, vi, MS-Word) are also > written in C. Does that mean you should do all your text processing in C? Well, actually, as a COBOL geezer I should not complain about Python. Rumor had it that the COMPUTE statement in COBOL invoked FORTRAN arithmetic modules. Yes, real programmers DO write in FORTRAN! Frankly, I say screw not only object-oriented programming but structured programming as well. I think someone should write a compiler, "Revenge of BASIC." It would have good old REMs, FOR...TO...NEXTs, GOSUBS, GOTOs, etc. Standard libraries of subroutines, and/or Copy Libraries of source code, could handle switching to new screens or forms, placement of objects, alteration of characteristics of all these, detection of mouse and keyboard actions, graphics, sound, placement of HTML code, EVERYTHING! If anyone wants to write this compiler, they should probably do it in Python. Make it open source, of course. I'm waiting! From fredrik at pythonware.com Sat Jul 26 03:29:54 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Jul 2008 09:29:54 +0200 Subject: xml.dom's weirdness? In-Reply-To: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> Message-ID: Lie wrote: > Why this generates AttributeError, then not? > > Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import xml >>>> xml.dom > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'dom' >>>> xml.dom > this is what I get, on both Windows and Linux: >>> import xml >>> xml.dom Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'dom' >>> xml.dom Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'dom' From __peter__ at web.de Mon Jul 14 04:34:05 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 14 Jul 2008 10:34:05 +0200 Subject: subprocess module References: <2e7f0504-cc1c-4cb6-b2d0-b67b004eca7d@x41g2000hsb.googlegroups.com> Message-ID: John Mechaniks wrote: > from subprocess import call > call(['ls', '-l']) > > How do I get the result (not the exit status of the command) of "ls - > l" into a variable? output = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE).stdout.read() Peter From deets at nospam.web.de Mon Jul 28 02:58:42 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 08:58:42 +0200 Subject: Python program as daemon? In-Reply-To: References: <8bb6bd1a-cd85-4b7a-8fc9-844f3794bca0@c58g2000hsc.googlegroups.com> <13866da4-01ed-4330-8297-8bdecce1393a@x35g2000hsb.googlegroups.com> Message-ID: <6f5913F9qs32U1@mid.uni-berlin.de> Lawrence D'Oliveiro schrieb: > In message > <13866da4-01ed-4330-8297-8bdecce1393a at x35g2000hsb.googlegroups.com>, > sturlamolden wrote: > >> Basically it forks twice ... > > What's the advantage of forking twice over forking once and calling setsid? http://code.activestate.com/recipes/278731/ See the comments. Diez From mensanator at aol.com Sat Jul 26 19:32:15 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 26 Jul 2008 16:32:15 -0700 (PDT) Subject: Insert string into string References: Message-ID: <56ff99b9-b4d4-4077-8de1-97a771ac526a@k13g2000hse.googlegroups.com> On Jul 26, 4:40?pm, "Francesco Pietra" wrote: > I am posting ex novo as it became confusing to me. I take the > opportunity to ask advice for a second problem. > > FIRST PROBLEM > For file xxx.pdb, insert letter "A" into each line that starts with > "ATOM". "A" should be inserted at position 22, i.e., one space after > "LEU", leaving all other characters at the same position as in the > original example: > > ATOM ? ? ?1 ?N ? LEU ? ? 1 ? ? 146.615 ?40.494 103.776 ?1.00 73.04 ? ? ? 1SG ? 2 > > In all lines starting with "ATOM", "LEU" is constant as to position > only (18-20), i.e., "LEU" may be replaced by > three different uppercase letters. Therefore, the most direct > indication would be position 22. If specifying line starting with > "ATOM" makes complication, forget about that as most lines begin with > "ATOM" so that hand correction will be easy. > > Script > f = open("xxx.pdb", "w") > import sys > > for line in sys.stdin: > ? ? line = line[:22] + "A" + line[23:] > ? ? sys.stdout.write(line) > > destroys the xxxx.pdb file and python exits witha non zero exit status. > > The same occurs with script > > f = open("hASIC1a.B99990003.pdb", "w") > f.write(' line = line[:22] + "A" + line[23:]') > f.close() > > I must have misunderstood the suggestion I received on previous posting. > ____________________________________ > SECOND PROBLEM > File xxx.pdb above has 426 lines stating with "ATOM", this serial > number occupying positions 7-11, right justified (Thus 1, as in the > line example above, means first line). A second, similar file yyy.pdb > has to be concatenated to xxx.pdb. Before that it should be added of > "A" as above and renumbered at position 7-11, starting from 428 (there > is an intermediate line to add). How should a script look like for > this string insertion into string with recursive +1? > > Thanks > francesco I don't know why you're using stdin if you're reading from a file. Also, the serial number isn't 7-11, it's 6-10 (remember to count from 0, so character 1 is position 0, etc.) fx = open('xxx.pdb','r') # first input file fy = open('yyy.pdb','r') # second input file fz = open('zzz.pdb','w') # output file (to be created) for xline in fx: # read input one line at a time if len(xline) >= 80: # don't process invalid lines line_index = int(xline[7:12]) # keep track of this if xline[:4]=='ATOM': fz.write(xline[:22] + 'A' + xline[23:]) else: fz.write(xline) fx.close() # done with first file fz.write('the extra line \n') line_index += 1 # don't forget to count it for yline in fy: # read second file if len(yline) >= 80: # again, valid only line_index += 1 # ignore serial number, use # where we left off from # from first file if yline[:4]=='ATOM': # note use of .rjust(5) to creat new serial number fz.write(yline[:6] + \ str(line_index).rjust(5) + \ yline[11:22] + 'A' + yline[23:]) else: fz.write(yline[:6] + \ str(line_index).rjust(5) + yline[11:]) fy.close() # done with second file fz.close() # done with output file From rocksportrocker at googlemail.com Thu Jul 17 09:14:45 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 17 Jul 2008 06:14:45 -0700 (PDT) Subject: How to process a very large (4Gb) tarfile from python? References: Message-ID: <0e96241d-60a3-44fd-967a-394904ad5b34@e39g2000hsf.googlegroups.com> On 17 Jul., 10:01, Terry Carroll wrote: > I am trying to do something with a very large tarfile from within > Python, and am running into memory constraints. ?The tarfile in > question is a 4-gigabyte datafile from freedb.org,http://ftp.freedb.org/pub/freedb/, and has about 2.5 million members > in it. > > Here's a simple toy program that just goes through and counts the > number of members in the tarfile, printing a status message every N > records (N=10,000 for the smaller file; N=100,000 for the larger). > > I'm finding that memory usage goes through the roof, simply iterating > over the tarfile. ?I'm using over 2G when I'm barely halfway through > the file. This surprises me; I'd expect the memory associated with > each iteration to be released at the end of the iteration; but > something's obviously building up. > > On one system, this ends with a MemoryError exception. ?On another > system, it just hangs, bringing the system to its knees, to the point > that it takes a minute or so to do simple task switching. > > Any suggestions to process this beast? ?I suppose I could just untar > the file, and process 2.5 million individual files, but I'm thinking > I'd rather process it directly if that's possible. > > Here's the toy code. ?(One explanation about the "import tarfilex as > tarfile" statement. I'm running Activestate Python 2.5.0, and the > tarfile.py module of that vintage was buggy, to the point that it > couldn't read these files at all. ?I brought down the most recent > tarfile.py fromhttp://svn.python.org/view/python/trunk/Lib/tarfile.py > and saved it as tarfilex.py. ?It works, at least until I start > processing some very large files, anyway.) > > import tarfilex as tarfile > import os, time > SOURCEDIR = "F:/Installs/FreeDB/" > smallfile = "freedb-update-20080601-20080708.tar" # 63M file > smallint = 10000 > bigfile ? = "freedb-complete-20080708.tar" ?# 4,329M file > bigiTnt = 100000 > > TARFILENAME, INTERVAL = smallfile, smallint > # TARFILENAME, INTERVAL = bigfile, bigint > > def filetype(filename): > ? ? return os.path.splitext(filename)[1] > > def memusage(units="M"): > ? ? import win32process > ? ? current_process = win32process.GetCurrentProcess() > ? ? memory_info = win32process.GetProcessMemoryInfo(current_process) > ? ? bytes = 1 > ? ? Kbytes = 1024*bytes > ? ? Mbytes = 1024*Kbytes > ? ? Gbytes = 1024*Mbytes > ? ? unitfactors = {'B':1, 'K':Kbytes, 'M':Mbytes, 'G':Gbytes} > ? ? return memory_info["WorkingSetSize"]//unitfactors[units] > > def opentar(filename): > ? ? modes = {".tar":"r", ".gz":"r:gz", ".bz2":"r:bz2"} > ? ? openmode = modes[filetype(filename)] > ? ? openedfile = tarfile.open(filename, openmode) > ? ? return openedfile > > TFPATH=SOURCEDIR+'/'+TARFILENAME > assert os.path.exists(TFPATH) > assert tarfile.is_tarfile(TFPATH) > tf = opentar(TFPATH) > count = 0 > print "%s memory: %sM count: %s (starting)" % (time.asctime(), > memusage(), count) > for tarinfo in tf: > ? ? count += 1 > ? ? if count % INTERVAL == 0: > ? ? ? ? print "%s memory: %sM count: %s" % (time.asctime(), > memusage(), count) > print "%s memory: %sM count: %s (completed)" % (time.asctime(), > memusage(), count) > > Results with the smaller (63M) file: > > Thu Jul 17 00:18:21 2008 memory: 4M count: 0 (starting) > Thu Jul 17 00:18:23 2008 memory: 18M count: 10000 > Thu Jul 17 00:18:26 2008 memory: 32M count: 20000 > Thu Jul 17 00:18:28 2008 memory: 46M count: 30000 > Thu Jul 17 00:18:30 2008 memory: 55M count: 36128 (completed) > > Results with the larger (4.3G) file: > > Thu Jul 17 00:18:47 2008 memory: 4M count: 0 (starting) > Thu Jul 17 00:19:40 2008 memory: 146M count: 100000 > Thu Jul 17 00:20:41 2008 memory: 289M count: 200000 > Thu Jul 17 00:21:41 2008 memory: 432M count: 300000 > Thu Jul 17 00:22:42 2008 memory: 574M count: 400000 > Thu Jul 17 00:23:47 2008 memory: 717M count: 500000 > Thu Jul 17 00:24:49 2008 memory: 860M count: 600000 > Thu Jul 17 00:25:51 2008 memory: 1002M count: 700000 > Thu Jul 17 00:26:54 2008 memory: 1145M count: 800000 > Thu Jul 17 00:27:59 2008 memory: 1288M count: 900000 > Thu Jul 17 00:29:03 2008 memory: 1430M count: 1000000 > Thu Jul 17 00:30:07 2008 memory: 1573M count: 1100000 > Thu Jul 17 00:31:11 2008 memory: 1716M count: 1200000 > Thu Jul 17 00:32:15 2008 memory: 1859M count: 1300000 > Thu Jul 17 00:33:23 2008 memory: 2001M count: 1400000 > Traceback (most recent call last): > ? File "C:\test\freedb\tardemo.py", line 40, in > ? ? for tarinfo in tf: > ? File "C:\test\freedb\tarfilex.py", line 2406, in next > ? ? tarinfo = self.tarfile.next() > ? File "C:\test\freedb\tarfilex.py", line 2311, in next > ? ? tarinfo = self.tarinfo.fromtarfile(self) > ? File "C:\test\freedb\tarfilex.py", line 1235, in fromtarfile > ? ? obj = cls.frombuf(buf) > ? File "C:\test\freedb\tarfilex.py", line 1193, in frombuf > ? ? if chksum not in calc_chksums(buf): > ? File "C:\test\freedb\tarfilex.py", line 261, in calc_chksums > ? ? unsigned_chksum = 256 + sum(struct.unpack("148B", buf[:148]) + > struct.unpack("356B", buf[156:512])) > MemoryError I had a look at tarfile.py in my current Python 2.5 installations lib path. The iterator caches TarInfo objects in a list tf.members . If you only want to iterate and you are not interested in more functionallity, you could use "tf.members=[]" inside your loop. This is a dirty hack ! Greetings, Uwe From FongAndrew at gmail.com Fri Jul 4 14:37:37 2008 From: FongAndrew at gmail.com (Andrew Fong) Date: Fri, 4 Jul 2008 11:37:37 -0700 (PDT) Subject: Getting a path from a file object Message-ID: <3c500ce7-c697-44e9-9f13-f65edc509e1c@a32g2000prf.googlegroups.com> Newbie question: Let's say I open a new file for writing in a certain path. How do I get that path back? Example: >>> f = open('/some/path/file.ext') >>> some_function(f) '/some/path/file.ext' Does some_function(f) already exist? And if not, how would I define it? -- Andrew From lamciuloeng at gmail.com Mon Jul 14 09:40:45 2008 From: lamciuloeng at gmail.com (CL (Ciu Loeng) Lam) Date: Mon, 14 Jul 2008 21:40:45 +0800 Subject: Turbogear installing error. Message-ID: HI,there: I get the errors below when installing the Turebogear,could anyone help me ? Thanks in advance. error: Not a recognized archive type: c:\docume~1\admini~1\locals~1\ temp\easy_in stall-y2znne\PasteScript-1.6.3.tar.gz -------------- next part -------------- An HTML attachment was scrubbed... URL: From maestroQC at gmail.com Tue Jul 15 11:06:21 2008 From: maestroQC at gmail.com (maestroQC) Date: Tue, 15 Jul 2008 08:06:21 -0700 (PDT) Subject: MySQL Insert Message-ID: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> Hi, Its one of those days. I cannot solve this. Any help would be greatly appreciated! When I execute this: class Db(object): def insertAccount(self, date, accountNumber, description, openingBalance): dec = decimal.Decimal(openingBalance) db = MySQLdb.connect(host="localhost", user="dumb", passwd="dumber", db="rdc") cursor = db.cursor() cursor.execute("INSERT INTO es_accounts (dateCreated, accountNumber, description, openingBalance) VALUES (%s, %s, %s, %d)", (date, accountNumber, description, dec)) I get this error: Traceback (most recent call last): File "main.py", line 59, in main() File "main.py", line 40, in main dbObj.insertAccount(dateTo, item[0], item[1], item[8]) File "C:\projects\workspace\INYR_ES_0.1\src\db.py", line 19, in insertAccount cursor.execute("INSERT INTO es_accounts (dateCreated, accountNumber, description, openingBalance) VALUES (%s, %s, %s , %d)", (date, accountNumber, description, dec)) File "c:\python25\lib\site-packages\MySQLdb\cursors.py", line 151, in execute query = query % db.literal(args) TypeError: int argument required My table is defined as: CREATE TABLE es_accounts ( id int(6) not null auto_increment, dateCreated date DEFAULT '0000-00-00', accountNumber int(6) not null, description varchar(255) not null, openingBalance decimal(15,8) NOT NULL DEFAULT 0.00000000, primary key (id) ); TIA From gherron at islandtraining.com Mon Jul 28 18:58:37 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 28 Jul 2008 15:58:37 -0700 Subject: derivative in numpy In-Reply-To: References: Message-ID: <488E4F1D.3060908@islandtraining.com> knielsen73 at gmail.com wrote: > Hi, > > I am looking to do a simple derivative. I would expect such a function > to be available in numpy, but can't find it. I have written my own, > but just curious if anybody knows of such function in numpy. > Derivatives are a property of functions. Since numpy provides representations of arrays not functions, how would you expect this to work? To be more concrete, what you you expect the derivative of [ [ 1 2 ] [ 3 4 ] ] to be? Or do you have in mind some array representation of the coefficients of a function of some pre-defined type - like a polynomial? Gary Herron > Cheers, > Kim > -- > http://mail.python.org/mailman/listinfo/python-list > From waldemar.osuch at gmail.com Sun Jul 13 17:30:41 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Sun, 13 Jul 2008 14:30:41 -0700 (PDT) Subject: SAX XML Parse Python error message References: <487A23A5.7000905@behnel.de> Message-ID: <1c87a4e2-7c66-4ced-8622-b6eebc8664bb@i76g2000hsf.googlegroups.com> On Jul 13, 3:00 pm, goldtech wrote: > I would be grateful for support with the code I cited. It's not long > and fairly standard. I'm sure my error(s) would be glaring to more > experienced coders. I appreciated the "heads-up" about other options > but I would be grateful for help getting this code to run. Thanks Initialize self.coodinates in the __init__ or indent the "print self.description, str(self.coordinates)" one more level. You have to remember that "endElement" is being called on the end of every element. In your case it is called by but the parser did not see yet. In "def characters" you should be collecting the "ch" in a buffer. It may be called multiple times for the same element. Something like "self.description += ch" would do for starters. Also you do not need to convert self.coordinates to string before printing, it is already a string and even if it was not "print" would convert it for you. That's it for now :-) Others may spot more issues with your code or my response. On the positive side I really liked how you asked the question. There was a short runnable example and traceback. Waldemar From MDiPierro at cs.depaul.edu Wed Jul 16 18:56:21 2008 From: MDiPierro at cs.depaul.edu (Massimo Di Pierro) Date: Wed, 16 Jul 2008 17:56:21 -0500 Subject: Framework recommendations for web service? Message-ID: <8355B44C-7BA9-4E36-B804-F8E0CF0B137E@cs.depaul.edu> web2py (not to be confused with web.py although both of them are excellent) comes with XMLRPC, XML, JSON and RSS API. You can find an XMLRPC example here: http://mdp.cti.depaul.edu/examples/default/examples#xmlrpc_examples The web2py source (including the optional web based interface) fits in 1.3MBytes. Massimo > Phillip B Oldham wrote: > > So, can anyone suggest a lightweight python framework which just does > > the essentials? > > web.py is pretty slim (not to be confused with web2py). > > Pylons isn't very large, depending on what you call "essential." -------------- next part -------------- An HTML attachment was scrubbed... URL: From semanticist at gmail.com Fri Jul 18 20:44:52 2008 From: semanticist at gmail.com (Miles) Date: Fri, 18 Jul 2008 20:44:52 -0400 Subject: __del__ methods In-Reply-To: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> Message-ID: On Fri, Jul 18, 2008 at 2:31 PM, Jason Baker wrote: > I have a class that I need to do some finalization on when it dies. I > know I can use the __del__ method, but I seem to recall that it > impedes garbage collection. Is this the case? Yes. "Objects that have __del__() methods and are part of a reference cycle cause the entire reference cycle to be uncollectable, including objects not necessarily in the cycle but reachable only from it. Python doesn't collect such cycles automatically because, in general, it isn't possible for Python to guess a safe order in which to run the __del__() methods." The uncollectable objects are stored in gc.garbage and will not be freed until their reference cycles are broken and they are removed from that list. http://docs.python.org/lib/module-gc.html -Miles From tjreedy at udel.edu Tue Jul 29 16:03:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 16:03:43 -0400 Subject: Build tool for Python In-Reply-To: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> References: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Message-ID: Hussein B wrote: > Hi. > Apache Ant is the de facto building tool for Java (whether JSE, JEE > and JME) application. > With Ant you can do what ever you want: compile, generate docs, > generate code, packing, deploy, connecting to remote servers and every > thing. > Do we have such a tool for Python projects? Also see thread Continuous integration for Python projects and mention of buildbot. From circularfunc at gmail.com Thu Jul 10 16:40:12 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 10 Jul 2008 13:40:12 -0700 (PDT) Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: ty very good answer. i know i shouldn't use lambda like that, i never do i was just playing around there and then this happened which i thought was weird. On Jul 10, 8:09?pm, Terry Reedy wrote: > David C. Ullrich wrote: > > In article > > <02ff4326-7b07-4ae6-8607-f58ea6180... at z72g2000hsb.googlegroups.com>, > > ?ssecorp wrote: > > >> I am never redefining the or reassigning the list when using validate > >> but since it spits the modified list back out that somehow means that > >> the modified list is part of the environment and not the old one. > >> i thought what happend inside a function stays inside a function > >> meaning what comes out is independent of what comes in. > >> Meaning if I want the list I send as a parameter to the function I > >> have to do x = func(x) and not just func(x) and x is magically what > >> comes out of func(). > > > A function cannot modify the value of a global variable > > Yes it can. > ?>>> a=[] > ?>>> def f(): > ? ? ? ? a.append('yes I can') > > ?>>> f() > ?>>> a > ['yes I can'] > > > (unless it specifies "global"). It doesn't reassign anything. > > The statement 'global a' would allow f to *rebind* the global *name* > 'a'. ?The word 'variable' should almost not be used in discussing Python > since it is often unclear whether it refers to a name (or collection > slot) or an object bound thereto. > > > But in the functions below you're not reassigning a variable, > > you're _modifiying_ an object. A function _can_ modify an > > object you pass to it: > > It can modify any mutable object it can access. > > >> Doesnt Python have closure or that isnt what this is about? > > Python does have closures. ?This is not about that. > > >> def validate(placed): > >> ? ? student = round(random.random()*401) > >> ? ? if student in placed: > >> ? ? ? ? return validate(placed) > >> ? ? else: > >> ? ? ? ? placed.append(student) > >> ? ? ? ? return student, placed > > Delete this. It is redundant with the below. > > >> def val(placed): > >> ? ? student = round(random.random()*401) > >> ? ? if student in placed: > >> ? ? ? ? return validate(placed) > >> ? ? else: > >> ? ? ? ? placed.append(student) > >> ? ? ? ? return student > > I believe this is equivalent to > > def addval(placed): > ? ?while True: > ? ? ?student = round(random.random()*401) > ? ? ?if student not in placed: > ? ? ? ?break > ? ?placed.append(student) > ? ?return student > > While this avoids the indefinite recursion depth problem, it does not > avoid the indefinite time problem. ?Use random.shuffle, or write your > own version if doing this for practice. ?Also consider removing the > return statement unless you actually directly use the added value. ?It > is easier to remember that addval mutates 'placed' without the return. > > >>>>> g = lambda x:validate(x) > > This is doubly diseased. > > First, never write a 'name = lambda...' statement since it is equivalent > to a def statement except that the resulting function object lacks a > proper .funcname attribute. ?The above only trivially abbreviates > ? ?def g(x): return validate(x) > by 3 characters. ?Another reason is that the lambda form somehow more > often tricks people into the next mistake . > > Second, never write a function (with either def or lambda) that simply > returns a function of the argument(s). ?The wrapping does nothing! ?This > is a waste of time and space for both you and the interpreter. ?The > above is functionally equivalent to > ? ?g = validate > and if you want that, you could name the function 'g' when you define it. > > >>>>> l=[] > > In some fonts, 'l' and '1' are nearly identical; please use something > else for public code, which you made this to be by posting it;-) > > >>>>> for x in range(1,10): > >> ? ? ? ?g(l) > > As said, the 'g' wrapper is useless. > ? ? ? ? addval(l) > > Hope this helps. > > Terry Jan Reedy From tjreedy at udel.edu Sat Jul 26 17:49:17 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 17:49:17 -0400 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> Message-ID: Paul Boddie wrote: > On 26 Jul, 06:06, Terry Reedy wrote: >> Paul Boddie wrote: >>> "The problem is that the explicit requirement to have self at the >>> start of every method is something that should be shipped off to the >>> implicit category." > > Here, I presume that the author meant "at the start of every method > signature". > >> There is no requirement to have 'self' in the parameter list. It can be >> 's', 'this', 'me', 'yo'(Spanish for I), or 'cls' (for class methods), or >> any other identifier in whatever language. > > But Jordan apparently wanted to omit that parameter. The omission of > all mentions of "self" could be regarded as a bonus, but it's a non- > trivial goal. Reword. There is no requirement to name the instance anything in particular. Thus there is no requirement at present that the first parameter, which gives the name of the instance, be anything in particular. >> In 3.0, identifiers are not restricted to ascii but can be any unicode >> 'word' as defined in the manual. >> >> So the proposal would have to be that the compiler scan the function >> body and decide which dotted name prefix is the one to be implicitly >> added. Have fun writing the discovery algorithm. However, I think this >> is pretty silly. Just write the name you want. > > If, as I wrote, you permit the omission of "self" in method signatures > defined within class definitions, then you could still insist on > instance attribute qualification using "self" - exactly as one would > when writing Java according to certain style guidelines. Which is what I said in the first sentence of my next paragraph, which you clipped. "Or the proposal would have to be that 'self' is mandatory for all programmers in all languages." To clarify " ... that 'self' be the mandatory instance name for all Python programmers regardless of inclination or the natural language they otherwise use as a basis for identifiers." In sum, if the instance name is omitted from the parameter list, it must either be discovered or mandated, and def statements in direct class scope have to be treated differently from def statements elsewhere. Terry Jan Reedy From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 17:10:15 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 23:10:15 +0200 Subject: Neat way to get rid of [" "] in sys.argv[n:] returns In-Reply-To: References: Message-ID: <4888efae$0$5589$426a74cc@news.free.fr> korean_dave a ?crit : > so, i code this: > ----------------------------- > #!/usr/bin/python > > import sys > import os > > for param in os.environ.keys(): > print "%20s %s" % (param,os.environ[param]) > > print(os.environ['PATH']) > > print(sys.argv[1:]) > -------------------------- > and then when i type in --> > > python test.py "testparameter" > > I get this output: > > ------------- > ['testparameter'] > ---------------- > > Is there a way to neatly, in one call to the parameter, to get rid of > the [' and '] without bothering to replace() '[ with "" and replace() > '] with ''? exact-but-useless-answer: print sys.argv[1] to-the-point-answer: print " ".join(sys.argv[1:]) and-if-I-may-ask: - do you understand why you get these "[' ']" ? From amdescombes at gmail.com Mon Jul 21 15:45:52 2008 From: amdescombes at gmail.com (AMD) Date: Mon, 21 Jul 2008 21:45:52 +0200 Subject: scanf in python In-Reply-To: <6ek4cgF7hq4vU1@mid.uni-berlin.de> References: <4884be5e$0$19722$426a74cc@news.free.fr> <6ek4cgF7hq4vU1@mid.uni-berlin.de> Message-ID: <4884e77a$0$29405$426a74cc@news.free.fr> > > I'm pretty certain python won't grow an additional operator for this. > Yet you are free to create a scanf-implementation as 3rd-party-module. > > IMHO the usability of the approach is very limited though. First of all, > the need to capture more than one input token is *very* seldom - nearly > all commandline-tools I know that do require interactive user-input > (like the linux kernel config tool) do so by providing either > line-by-line value entry (including defaults, something you can't do > with your approach), or even dialog-centric value entry with curses. > > So - I doubt you will gather much momentum on this. Good luck though. > > > Diez Actually it is quite common, it is used for processing of files not for reading parameters. You can use it whenever you need to read a simple csv file or fixed format file which contains many lines with several fields per line. The advantage of the approach is that it combines the parsing and conversion of the fields into one operation. Another advantage of using simple formatting strings is that it allows for easy translation of these lines, just like you have with the % operator for output. I don't see why python can have an operator for output but it can't have one for input, it's just not symmetrical. I don?t see why you can't use this method for line-by-line value entry, just add \n between your %s or %d. The method is quite versatile and much simpler than regular expressions plus conversion afterwards. Andr? From pyth0nc0d3r at gmail.com Sat Jul 19 14:38:49 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Sat, 19 Jul 2008 13:38:49 -0500 Subject: How do you check if a program/process is running using python? Message-ID: How do you check if a program or process is running when using python? What I want to do is have an infinite loop to check if a program is running or not and send data to my web server to check yes or no. Is this possible? If so how? -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick83ola at gmail.com Tue Jul 1 11:26:29 2008 From: nick83ola at gmail.com (nickooooola) Date: Tue, 1 Jul 2008 08:26:29 -0700 (PDT) Subject: Implementing an 8 bit fixed point register References: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> Message-ID: <72cb8cf8-a73d-4405-a347-197cb3d61c23@26g2000hsk.googlegroups.com> Thanks to all for the responses! to MEl: I also want to build a pic simulator, but I want to do this as "python for big project" learning exercise, I have used python in the past only for small script and now I want to use it for something more "big". do you have some code to share? myhdl seems interesting, I think that I can take a blick on its source code...I think that must have something like the 8 bit register class that I need somewhere I try what you people have said, and if it turns to be something useful, I report it to the community. Nicola Ps excuse me for my english... From jstrickler at gmail.com Fri Jul 18 12:28:42 2008 From: jstrickler at gmail.com (John S) Date: Fri, 18 Jul 2008 09:28:42 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> Message-ID: On Jul 18, 7:51 am, Andrew Freeman wrote: > Andrew Freeman wrote: > > oj wrote: > >> On Jul 18, 12:10 pm, John Machin wrote: > > >>> On Jul 18, 9:05 pm, oj wrote: > > >>>> On Jul 18, 11:33 am, arnimavidyar... at gmail.com wrote: > > >>>>> Hi, > >>>>> Hi, > >>>>> I am taking a string as an input from the user and it > >>>>> should only > >>>>> contain the chars:L , M or R > >>>>> I tried the folllowing in kodos but they are still not > >>>>> perfect: > >>>>> [^A-K,^N-Q,^S-Z,^0-9] > >>>>> [L][M][R] > >>>>> [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > >>>>> For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' > >>>>> .like that. > >>>>> regards, > >>>>> SZ > >>>>> The string may or may not have all the three chars. > > >>>> With regular expressions, [^LRM] matches a character that isn't L, R > >>>> or M. So: > >>>> import re > >>>> var = "LRLRLRLNR" > >>>> if re.search(r'[^LRM]', var): > >>>> print "Invalid" > > >>> Fails if var refers to the empty string. > > >> No it doesn't, it succeeds if var is an empty string. An empty string > >> doesn't contain characters that are not L, R or M. > > >> The OP doesn't specify whether an empty string is valid or not. My > >> interpretation was that an empty string would be valid. > > > Why not just use * instead of + like: > > > if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of > > string; $ means end of string > > print "Invalid" > > > This will *only* print invalid when there is a character other than L, > > R, or M or a empty string. > > Sorry, forget the beginning and ending markers, I just tried it out, it > doesn't work. > use this instead: > > if re.search(r'[^LRM]*', var): > print "Invalid" This won't work -- every string in the universe contains 0 or more characters which are not 'L', 'R', or 'M'. That is, the regular expression X* could match the empty string, which can be found in all strings. From Caseyweb at gmail.com Fri Jul 11 19:46:41 2008 From: Caseyweb at gmail.com (Casey) Date: Fri, 11 Jul 2008 16:46:41 -0700 (PDT) Subject: Perfect hashing for Py References: Message-ID: <666edc45-098a-4894-99eb-8367d5f3edb4@k30g2000hse.googlegroups.com> On Jul 11, 8:01?am, bearophileH... at lycos.com wrote: > Following links from this thread:http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > I have found this perfect hash (minimal too) implementation:http://burtleburtle.net/bob/hash/perfect.html > > I have already translated part of it to D, and it seems to work well > enough. As discussed in the PyConDue, I think this may be used in > frozenset (and frozendict) to build a (minimal too?) perfect hash on > the fly, to allow (hopefully) faster retrieval of items that don't > change. > That code is C and I think it's public domain, so if experiments show > it gives enough speed up, it may be added to CPython 2.6/3. > > Bye, > bearophile It would be interesting to see if such an algorithm could actually provide any significant performance improvements for the size of sets that I suspect are most often used in practice. The chance of a hash collision for a good 32-bit general is fairly low even for a set of 1,000,000 unique elements, which seems to me to be a pretty large memory-based set. Compare that with the cost of determining a perfect hash (O(n**2)?). From my perspective, a perfect hash would certainly be a welcome addition to the Python library or even as an optional algorithm supporting hash-based collections. From deets at nospam.web.de Tue Jul 22 10:11:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 16:11:31 +0200 Subject: tkinter for my python program !! References: <6em5snF7r22oU3@mid.uni-berlin.de> <63ff0b6f-8c75-4172-b836-8497870544ca@s50g2000hsb.googlegroups.com> Message-ID: <6em86gF7q9djU1@mid.uni-berlin.de> karthikbalaguru wrote: > On Jul 22, 6:32 pm, "Diez B. Roggisch" wrote: >> karthikbalaguru wrote: >> > Hi, >> >> > One of my python program needs tkinter to be installed to run >> > successfully. >> > I am using Redhat 9.0 and hence tried installing by copying the >> > tkinter-2.2.2-36.i386.rpm >> > alone from the CD 3 to my pc. But, it is not getting installed and is >> > failing by throwing >> > the below errors. Should i need to configure / install any specific >> > files for resolving this issue ? >> >> > [root at localhost karthik]# rpm -ivh tkinter-2.2.2-26.i386.rpm >> > warning: tkinter-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, >> > key ID db42a >> > 60e >> > error: Failed dependencies: >> > libtcl8.3.so is needed by tkinter-2.2.2-26.i386 >> > libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 >> > libtk8.3.so is needed by tkinter-2.2.2-26.i386 >> >> > Any ideas ? >> >> Yes: you should consider reading error-messages. What does >> >> error: Failed dependencies: >> libtcl8.3.so is needed by tkinter-2.2.2-26.i386 >> libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 >> libtk8.3.so is needed by tkinter-2.2.2-26.i386 >> >> look like for you? >> >> Small hint: if you install something that depends on something else, you >> need to .... the missing dependency first. Fill in the dots... >> > > I find that it needs python-2.2.2-26.i386 and hence i tried installing > python and i > land here :( :( > > [root at localhost karthik]# rpm -ivh python-2.2.2-26.i386.rpm > warning: python-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key > ID db42a60e > error: Failed dependencies: > libdb-4.0.so is needed by python-2.2.2-26.i386 > python < 2.4.3-18.fc6 conflicts with python- > devel-2.4.3-18.fc6.i386 > [root at localhost karthik]# > > > I find that python 2.4.3-18.fc6 is being used by many of applications. > But, the program i am trying to run needs python-2.2.2-26. > So, how to resolve this issue ? Are you *sure* it requires python2.2? If yes, why can't fedora install several python versions together? Ubuntu for sure can. But Python2.2 is *ancient* - you might need to compile it yourself. Diez From dfnsonfsduifb at gmx.de Mon Jul 21 09:26:18 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Mon, 21 Jul 2008 15:26:18 +0200 Subject: Python Written in C? In-Reply-To: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> References: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> Message-ID: Mensanator schrieb: > You want cool? > THIS is cool: > > j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2])) > % xyz[1]**(k-1))/xyz[1]**(k-2) You call it cool, I call it NameError: name 'invert' is not defined. Regards, Johannes -- "Wer etwas kritisiert muss es noch lange nicht selber besser k?nnen. Es reicht zu wissen, da? andere es besser k?nnen und andere es auch besser machen um einen Vergleich zu bringen." - Wolfgang Gerber in de.sci.electronics <47fa8447$0$11545$9b622d9e at news.freenet.de> From spandanagella at gmail.com Thu Jul 3 02:52:45 2008 From: spandanagella at gmail.com (spandana g) Date: Thu, 3 Jul 2008 14:52:45 +0800 Subject: HTTP request error with urlopen Message-ID: Hello , I have written a code to get the page source of the google search page .. this is working for other urls. I have this problem with import re from urllib2 import urlopen string='http://www.google.com/search?num=20&hl=en&q=ipod&btnG=Search' file_source=file("google_source.txt",'w') file_source.write(urlopen(string).read()) page_content=file_source.readlines() Traceback (most recent call last) : File "C:/Python25/google.py", line 5,in file_source.write(urlopen(string).read()) File "C:\Python25\lib\urllib2.py", line 124 , in urlopen return__opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 387 , in open response =meth(req, response) File "C:\Python25\lib\urllib2.py", line 498 , in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 425, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 360, in __call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 506, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: Forbidden Actually urlopen is working for google labs sets page but not for the google.com and even I have same problem with wikipedia . Please let me know .. If any one of have any idea about this . Thank You, Spandana. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gherron at islandtraining.com Wed Jul 30 18:10:36 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 30 Jul 2008 15:10:36 -0700 Subject: overriding file.readline: "an integer is required" In-Reply-To: References: Message-ID: <4890E6DC.8080504@islandtraining.com> kj wrote: > I'm trying to subclass file, overriding the readline method. The > new method definition begins with > > def readline(self, size=None): > line = self.file.readline(size) > # etc., etc. > > ...where the self.file attribute is a regular file object. > > This works fine if I invoke the new method with an integer argument, > but if I invoke it without arguments, I get the error > > TypeError: an integer is required > > ...which I suppose comes from the call to self.file.readline(None). > > I know that I could rewrite the method like this: > > def readline(self, size=None): > if size == None: > line = self.file.readline() > else: > line = self.file.readline(size) > # etc., etc. > > ...but this seems to me exceptionally awkward. (Actually, it's worse > than awkward: it fails to complain when the overriding method is > called with the argument None. It would be better to test for the > number of arguments passed to the function, but I can't figure out > how to do this either.) > > Is there a better idiom? > Since the manual implies that negative values have no effect, try this: def readline(self, size=-1): line = self.file.readline(size) # etc., etc. I tested this (just barely), and it seems to work as you wish. Gary Herron > TIA! > > Kynn > From fredrik at pythonware.com Thu Jul 24 03:48:03 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 09:48:03 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: Jordan wrote: > Except when it comes to Classes. I added some classes to code that had > previously just been functions, and you know what I did - or rather, > forgot to do? Put in the 'self'. In front of some of the variable > accesses, but more noticably, at the start of *every single method > argument list.* This cannot be any longer blamed as a hangover from > Java - I've written a ton more code, more recently in Python than in > Java or any other OO language. What's more, every time I go back to > Python after a break of more than about a week or so, I start making > this 'mistake' again. The perennial justification for this 'feature' > of the language? That old Python favourite, "Explicit is better than > implicit." Do you seriously think that Python is designed by mindless application of a set of humorous and somewhat self-deprecating observations posted to a newsgroup a number of years ago? From pdorange at pas-de-pub-merci.mac.com Wed Jul 30 03:04:56 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Wed, 30 Jul 2008 09:04:56 +0200 Subject: Python embedding question (2). References: Message-ID: <1ikuf8r.1s2a5ex11pfrveN%pdorange@pas-de-pub-merci.mac.com> Thomas Troeger wrote: > I've managed to put together a small pyGame program, it runs smoothly > and seems to be exactly what I wanted. It's fast! Even with 100 moving > objects it still runs so fast that I can consider using Python/pyGame > for the whole project. > > There are still some questions left which I haven't found out by myself, > so maybe someone here can answer them: > > - I can't see how to create more sophisticated text output, it seems the > built in font render facilities are limited to simple strings. Is that > true? Yes, for my part i start to make a (small) library myself for my little game in development (simple). Supporting bidirectionnal in such a case is not a big deal, but markups will be not trivial (but python has tools to parse text, this can help). Also have a look at somme gui library for pygame : It seems PGU is one of the most used. > - Is there some way to reserve screen areas so they are excluded from a > blit, or do I have to manage stuff like this myself? You can blit any rectangle it's trivial. for example group.draw render the sprites in it, into the surface given, this surface can be the screen or any other "virtual surface". You just have to render this "virtual" on screen whn done. You can also used the more sophisticate "dirty rect" (group.RenderUdates) or even better group.LayeredUpdates. I start with but a can not make all things work properly at that time. > I am thinking about > several graphic layers where each layer is painted on top of the next > layer, for example to draw a gui in front of a background image. For this is simply create sprite groups (one per layer) and than call group render (group.draw) in the order i need. Easy and efficient. > - There seems to be support for video overlay, i.e. is it possible to > have an external program paint an image from a camera into a portion of > the screen while pyGame is running? Don't know... -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From babacity4 at gmail.com Thu Jul 24 16:51:21 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:51:21 -0700 (PDT) Subject: sextv1 net - Amazing porn video collection Message-ID: <2ed8b9cd-466f-4589-8310-b906523c7e48@b30g2000prf.googlegroups.com> sextv1 net . >>>>>>>>>>Best Collection of Sextv1 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE sextv1 net VIDEOS<<<<<<<<<<< . sextv1 net From mccredie at gmail.com Tue Jul 22 20:29:16 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 22 Jul 2008 17:29:16 -0700 (PDT) Subject: How do I compare files? References: Message-ID: On Jul 22, 4:27?pm, Clay Hobbs wrote: > I am making a program that (with urllib) that downloads two jpeg files > and, if they are different, displays the new one. ?I need to find a way > to compare two files in Python. ?How is this done? > > -- Ratfink Do you just want to check to see if they are the same? Or do you actually want to know what the differences are? import urllib data1 = urllib.urlopen("http://url.of.jpg1").read() data2 = urllib.urlopen("http://url.of.jpg2").read() if data1 == data2: print "they are the same" Doing a regular text diff won't tell you much. You could use PIL and do all sorts of image manipulation though. You might generate an image of the difference between each pixel. Something like this: import Image import ImageChops import urllib data1 = urllib.urlopen("http://url.of.jpg1").read() data2 = urllib.urlopen("http://url.of.jpg2").read() im1 = Image.fromstring(data1) im2 = Image.fromstring(data2) result = ImageChops.difference(im1, im2) result.save("result_image.jpg") Read up on PIL: http://www.pythonware.com/library/pil/handbook/index.htm Matt From wmcbrine at users.sf.net Mon Jul 28 14:22:50 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Mon, 28 Jul 2008 18:22:50 GMT Subject: like py2exe, but on a mac References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> Message-ID: <_7ojk.253$wS4.85@trnddc03> On Mon, 28 Jul 2008 19:51:26 +0200, Tommy Nordgren wrote: > There is Platypus, a general open source program to wrap a script > in an Macintosh (GUI) Application. Thanks. I tried Platypus, and it's close to what I want. But I still can't seem to get rid of the small "Console" window that pops up behind my Tkinter app. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From murugesan550 at gmail.com Thu Jul 24 23:27:49 2008 From: murugesan550 at gmail.com (muruges) Date: Thu, 24 Jul 2008 20:27:49 -0700 (PDT) Subject: .............................on line jobs........................................ Message-ID: <6f37bd72-02fb-46c2-9b67-2515fd93a424@v26g2000prm.googlegroups.com> we are selecting you for this online jobs. For more information see this website in this.............................. we are selecting you for this online jobs. For more information see this website in this.............................. Details .................. Name of the job.........................Online job.......................... Nature of work...........................Like data entry.......................... Qualification required........................good knowledge in computer Basics Earnings................More then Rs=1000 per day......................Earnings depends on your work............................. FOR MORE DETAILS: WWW.Bigconstructions5.blogspot.com From christopher.saunter at durham.ac.uk Wed Jul 23 07:03:13 2008 From: christopher.saunter at durham.ac.uk (c d saunter) Date: Wed, 23 Jul 2008 11:03:13 +0000 (UTC) Subject: Parsing VHDL with python, where to start. References: Message-ID: Svenn Are Bjerkem (svenn.bjerkem at googlemail.com) wrote: : Hi, : I am in the need to write an application for PyQt to visualise the : structure of a VHDL project I am working on. Looking for a sensible : way to parse VHDL files and putting them into a data structure that : PyQt can represent as a tree (or whatever the MVC is supporting) : through search engines does not give me many hints. From what I know, : VHDL is not a very easy language to parse. There seems to be a parser : for perl available, but I do not know if it is wise to use a perl : module as a template for writing something similar in python. Hi Sven, How much of VHDL are you looking to parse? Are you just looking at files intended for synthesis, or at simulation/testbench files as well? I wrote a basic parser a few years ago for automatically stringing modules together, but it was very limited in scope. I thought VHDL was quite simple to parse, it's very rigid. Having written a basic one I realised I'd coded myself into a dead-end as you say. Maybe not so simple after all... :-) If I started again I'd use pyparsing: http://pyparsing.wikispaces.com/ Looks like someone is already there in part: http://pyparsing.wikispaces.com/message/view/home/103973 Regards, Chris : My initial idea is to start simple and extend features in my : application, but I fear that I may start off with wrong ideas how to : parse and then code myself into a dead-end requiring myself to rewrite : the whole application in order to get any further. I would start : finding definitions of entities and the instantiations of these and : build a tree from a set of external vhdl files stored in a file : hierarchy. If somebody have a starting point where to get going with a : task like this, I would be happy to know. : -- : kind regards, : Svenn From JordanNealBerg at gmail.com Mon Jul 14 20:39:14 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Mon, 14 Jul 2008 17:39:14 -0700 (PDT) Subject: Python ver of System.arraycopy() in Java Message-ID: <6041eb3a-6e32-44cb-a442-5cf3ac9b4d9d@59g2000hsb.googlegroups.com> I could seem to find a built in function that would serve the purpose of System.arraycopy() in java. I was able to accomplish it with something like this: def arraycopy(source, sourcepos, dest, destpos, numelem): dest[destpos:destpos+numelem] = source[sourcepos:sourcepos +numelem] is there a built in version, or better way of doing this... From tim.arnold at sas.com Wed Jul 30 12:41:38 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Wed, 30 Jul 2008 12:41:38 -0400 Subject: Build tool for Python References: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Message-ID: "Terry Reedy" wrote in message news:mailman.868.1217361931.922.python-list at python.org... > > > Hussein B wrote: >> Hi. >> Apache Ant is the de facto building tool for Java (whether JSE, JEE >> and JME) application. >> With Ant you can do what ever you want: compile, generate docs, >> generate code, packing, deploy, connecting to remote servers and every >> thing. >> Do we have such a tool for Python projects? > > Also see thread Continuous integration for Python projects and mention of > buildbot. Surprised no one has mentioned SCons, http://www.scons.org/ I've used it a bit and found it pretty good, out of the box. --Tim Arnold From is_this at visible.com Thu Jul 31 12:36:05 2008 From: is_this at visible.com (Bruce Frederiksen) Date: Thu, 31 Jul 2008 16:36:05 +0000 Subject: Non Continuous Subsequences References: Message-ID: <9e5a3$4891e9f5$18607848$1746@KNOLOGY.NET> On Wed, 30 Jul 2008 09:32:25 -0700, bearophileHUGS wrote: > This post is not about practical stuff, so if you have little time, > you may ignore it. > > This is a task of the rosettacode.org site: > http://www.rosettacode.org/wiki/Non_Continuous_Subsequences > > A subsequence contains some subset of the elements of this sequence, > in the same order. A continuous subsequence is one in which no > elements are missing between the first and last elements of the > subsequence. The task is to enumerate all non-continuous subsequences > for a given sequence. > > Translating the Scheme code to Python was easy (and I think this is > quite more readable than the Scheme version): > > def ncsub(seq, s=0): > if seq: > x = seq[:1] > xs = seq[1:] > p2 = s % 2 > p1 = not p2 > return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + > p2) > else: > return [[]] if s >= 3 else [] > > Output: > >>>> ncsub(range(1, 4)) > [[1, 3]] >>>> ncsub(range(1, 5)) > [[1, 2, 4], [1, 3, 4], [1, 3], [1, 4], [2, 4]] >>>> ncsub(range(1, 6)) > [[1, 2, 3, 5], [1, 2, 4, 5], [1, 2, 4], [1, 2, 5], [1, 3, 4, 5], [1, > 3, 4], [1, 3, 5], [1, 3], [1, 4, 5], [1, 4], [1, 5], [2, 3, 5], [2, 4, > 5], [2, 4], [2, 5], [3, 5]] > > > > But in many cases you can create a lazy code in Python too, even if > that may be harder. So I have tried to create a lazy version for > Python, hoping to speed up the code avoiding the creation and joining > of most/all sublists, but I have failed so far (once I have created a > lazy Python version, I can probably create a short lazy version in D > too, my D libs contain most of itertools module too). > > In my failed attempts I have used chain() to join the sublists, > islice() to slice their items, and iter() to make the management more > uniform when the input seq is a Python list instead of an xrange, etc. Try this: import itertools def ncsub(seq, s = 0): if seq: x = seq[:1] xs = seq[1:] p2 = s % 2 p1 = 1 - p2 return itertools.chain( itertools.imap(lambda ys: x + ys, ncsub(xs, s + p1)), ncsub(xs, s + p2)) else: return [[]] if s >= 3 else [] >>> ncsub(range(1, 4)) >>> list(ncsub(range(1, 4))) [[1, 3]] >>> list(ncsub(range(1, 5))) [[1, 2, 4], [1, 3, 4], [1, 3], [1, 4], [2, 4]] >>> list(ncsub(range(1, 6))) [[1, 2, 3, 5], [1, 2, 4, 5], [1, 2, 4], [1, 2, 5], [1, 3, 4, 5], [1, 3, 4], [1, 3, 5], [1, 3], [1, 4, 5], [1, 4], [1, 5], [2, 3, 5], [2, 4, 5], [2, 4], [2, 5], [3, 5]] From shalupov at diverse.org.ru Thu Jul 31 08:11:34 2008 From: shalupov at diverse.org.ru (Leonid Shalupov) Date: Thu, 31 Jul 2008 16:11:34 +0400 Subject: Continuous integration for Python projects In-Reply-To: References: Message-ID: <4891ABF6.3090906@diverse.org.ru> Hello, Hussein B wrote: > Please correct my if I'm wrong but it seems to me that the major > continuous integration servers (Hudson, CruiseControl, TeamCity ..) > don't support Python based application. > It seems they mainly support Java, .NET and Ruby. > Can I use one of the previous listed servers for Python project? You can use TeamCity. Build and test your project with command-line runner and make sure you've installed modules for reporting tests to TeamCity. http://www.jetbrains.net/confluence/display/TW/Python+Unit+Test+Reporting -- Leonid. From max at alcyone.com Wed Jul 30 02:06:32 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 23:06:32 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <68448887-4736-4af9-9f27-837bb5312cbd@o40g2000prn.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> <7f4a3d37-e551-4e21-b660-3618016cb67b@z6g2000pre.googlegroups.com> <68448887-4736-4af9-9f27-837bb5312cbd@o40g2000prn.googlegroups.com> Message-ID: Carl Banks wrote: > Bull. This is a request, that, if satisfied, would prove that "if x" > is more polymorphic than a simple explicit test. I posed the question > precisely to see if anyone could come up with a use case that shows > this benefit of "if x". Except you're the only one who's not convinced of it, and it's your test, and your rules. So who cares? >> "if x" _is_ a completely simple >> test. Simpler, in fact, than the ones you were advocating. > > It's not explicit. It's not explicit enough for you, yes, that much is obvious. Contests that rely on mind-reading aren't too much fun for anyone involved. > I've explained why I doubt that it helps polymorphism that much: you > almost never see code for which an integer and list both work, so > having the ability to spell a test the same way for both types isn't > useful. If you claim that "if x" does help polymorphism, please tell > me what's wrong with the above analysis. It helps polymorphism for types other that (say) numerics and sequences. There are plenty of container objects for which an "is this non-empty?" test is far simpler a "how many objects are in this container?" test, and several examples have already been given -- as in, O(1) vs. O(n) complexity or worse. You've seem to have even acknowledged this, but are still insisting on continuing the challenge. You're drawing an artificial line in the sand to compare length computation to a more specialized non-emptiness test. (And, as I've pointed out, what happens if you're dealing with a sequence type that _doesn't_ have a length? Then certainly `len(x) != 0` is nonsensical.) Perhaps in the particular use case you're thinking of (numeric types vs. container types), there aren't any good examples. But who cares? Polymorphism applies in more than just this one special case. You're setting up a challenge that isn't very interesting, and which is rigged so that no one can win because you're the one who. So, what's the point? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Can I be your friend / 'Till the end -- India Arie From wmcbrine at users.sf.net Sun Jul 27 21:59:29 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Mon, 28 Jul 2008 01:59:29 GMT Subject: like py2exe, but on a mac References: <18424336.post@talk.nabble.com> Message-ID: <5K9jk.278$rb5.198@trnddc04> On Sun, 13 Jul 2008 00:58:59 +0200, Python.Arno wrote: > http://undefined.org/python/py2app.html py2app bundles Python itself into the app, right? I wonder, is there no way to create an app bundle that relies on the existing installation of Python, since OS X already comes with Python? I have a tiny little program (~20k) that I'd like to make into an app bundle, if only to suppress the console window, and I'd rather not lump in the whole Python interpreter if I can avoid it. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From niklas.norrthon at hotmail.com Wed Jul 23 18:44:02 2008 From: niklas.norrthon at hotmail.com (Niklas Norrthon) Date: Wed, 23 Jul 2008 15:44:02 -0700 (PDT) Subject: Request Help Debugging Program References: <898dfe7a-4133-4337-8243-f4936b8a8092@8g2000hse.googlegroups.com> Message-ID: <864f60ea-39fb-40a6-b3f3-18fc019e193b@m44g2000hsc.googlegroups.com> On 24 Juli, 00:30, Samir wrote: > from math import sqrt > > def findSumOfDivisor(n): [...] > ? ? return sum(divisor) ? ? ? ? ? ? ? ?# return the sum of the > divisors > for i in range(2,10): ? ? ? ? ? ? ? ? ?# loop through integers 2 > through 9 [...] > ? ? ? ? sum = findSumOfDivisor(i) ? ? ?# then find the sum of its divisors [...] > Traceback (most recent call last): > ? File "pe_prob021.py", line 19, in > ? ? sum = findSumOfDivisor(i) ? ? ?# then find the sum of its divisors > ? File "pe_prob021.py", line 12, in findSumOfDivisor > ? ? return sum(divisor) ? ? ? ? ? ? ? ?# return the sum of the > divisors > TypeError: 'int' object is not callable > 'int' object is not callable... hmmm... >>> 42() Traceback (most recent call last): File "", line 1, in 42() TypeError: 'int' object is not callable >>> divisor = 1 >>> sum = 42 >>> sum(divisor) Traceback (most recent call last): File "", line 1, in sum(divisor) TypeError: 'int' object is not callable That must be it. No debugging, just reading the error message and the code... From fred.sells at adventistcare.org Tue Jul 15 15:16:34 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Tue, 15 Jul 2008 15:16:34 -0400 Subject: need ldap windows binary and/or installation help In-Reply-To: Message-ID: <0A53725C4A497848A7B3A0874B259831011B09A4@acesxch01.ADVENTISTCORP.NET> well, duh ;) as my granny used to say "If it had been a snake it would a bit ya". I could probably come up with some lame excuse why I didn't see the msi on osuch.org, but it would be lame and an excuse. anyway. Thanks! > -----Original Message----- > From: python-list-bounces+frsells=adventistcare.org at python.org > [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On > Behalf Of Michael Str?der > Sent: Tuesday, July 15, 2008 2:46 PM > To: python-list at python.org > Subject: Re: need ldap windows binary and/or installation help > > > Tim Golden wrote: > > Sells, Fred wrote: > >> I'm running python 2.5 (or 2.4) in an XP environment. > >> I downloaded and installed the .dll's from > >> OpenLDAP-2.4.8+OpenSSL-0.9.8g-Win32.zip and copied the .dll's in > >> c:/windows/system32 as instructed > >> now I get this error. Is there anyway to avoid building the > >> python_ldap binaries? > > > > Disclaimer. I know nothing about python-ldap. I simply > > Googled for it and came to: > > http://python-ldap.sourceforge.net/download.shtml > > which led me to > > http://www.osuch.org/python-ldap > > from which I downloaded and ran the .msi > > http://www.osuch.org/python-ldap-2.3.5.win32-py2.5.msi > > and Bob was at that point my uncle. > > When reading the original posting I wondered how to make > python-ldap's > web pages even more clear. Thanks that you pointed out that > it seems not > necessary. :-) > > Ciao, Michael. > -- > http://mail.python.org/mailman/listinfo/python-list > From sbcook at gmail.com Tue Jul 29 20:01:35 2008 From: sbcook at gmail.com (SteveC) Date: Tue, 29 Jul 2008 17:01:35 -0700 (PDT) Subject: POP3 - Using poplib only shows the first few hundred messages in the mailbox References: <503aa944-bbf6-4d86-bd98-b58adcd5a2bd@y22g2000prd.googlegroups.com> Message-ID: On Jul 25, 6:07?pm, MRAB wrote: > On Jul 25, 1:18?pm, SteveC wrote: > > > Hello, > > > I am trying to use POP3_SSL class of thepoplibmodule to read email > > from my gmail account. ?I can connect just fine using the example herehttp://www.python.org/doc/lib/pop3-example.html > > > import getpass,poplib > > > M =poplib.POP3('localhost') > > M.user(getpass.getuser()) > > M.pass_(getpass.getpass()) > > numMessages = len(M.list()[1]) > > for i in range(numMessages): > > ? ? for j in M.retr(i+1)[1]: > > ? ? ? ? print j > > > That is the above sample code from the python doc. ?While everything > > works fine, the problem is that when I use the list() function it only > > returns about 400 messages starting from the beginning of my inbox. ?I > > have probably 10,000 emails in my gmail account. ?I don't see any pop3 > > object functions to "move" around the inbox or anything of the like. > > > Could someone point me in the right direction? ?I'm sure there must be > > something simple I am missing. > > That's a lot of emails! :-) > > I had a quick look atpoplib.py and I couldn't see any limit in the > code itself. Perhaps it's the gmail server that's doing it. Can you > retrieve the later messages, eg have you tried M.retr(500)? If you can > then you could just try retrieving messages beyond what M.list() says > until it says there's no such message. Nothing changes when I retrieve the messages it first provides me. What baffles me is I see tons of examples online doing the same thing: http://python.about.com/od/simplerscripts/ss/backup_gmail_3.htm I'm not sure if it could be just a gmail thing either, because then it would seem that this would be a problem with any pop email client. From martin at v.loewis.de Wed Jul 16 01:43:40 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 16 Jul 2008 07:43:40 +0200 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: <487D8A8C.7080307@v.loewis.de> >> I need to know if I'm running on 32bit or 64bit ... so far I haven't >> come up with how to get this info via python. sys.platform returns >> what python was built on ... but not what the current system is. >> >> I thought platform.uname() or just platform.processor() would have >> done it, but python returns an empty string on windows. Any ideas? >> > >>>> import sys >>>> hex(sys.maxint) > '0x7fffffff' I don't think that will satisfy the OP. Apparently, he wants to find out that the system is "running on 64bit" even when the interpreter is a 32-bit build executable ("what python was built on"). I don't think Python supports querying that information in general (i.e. "is the microprocessor supporting a 64-bit address space, even if the current process, and perhaps the current operating system only uses a 32-bit address space?") It is possible to answer that question with Python in a platform-specific manner, but the answer is more difficult than a single yes/no: - is the processor capable of executing 64-bit code? - is the operating system kernel operating the processor in 64-bit mode? - does the operating system support 64-bit user-space applications? (in some OSX and Solaris releases, the answer to this question was no, even though the answer to the previous question was yes, IIRC) - does the Python binary support 64-bit mode? - is the Python binary running in 64-bit mode? (again, this may vary from the previous question, in case of fat (universal) binaries) Whether any of these questions are of interest, and which of them the OP wanted to ask, I don't know. Regards, Martin From bj_666 at gmx.net Mon Jul 14 01:06:12 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 14 Jul 2008 05:06:12 GMT Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> Message-ID: <6e0564F4bvr4U2@mid.uni-berlin.de> On Sun, 13 Jul 2008 18:51:19 -0700, Yosifov Pavel wrote: >> Well, I think Python's iterators, especially the generators, are beautiful. >> More importantly, I think there is no general way to make iterators >> copyable, regardless of the programming language. The problem is that most >> of the useful ones depend on external state. > > Hmm, but tee() de facto do it (clone iterator) and ignore side-effects > of iterator ("external" state). And tee() create independent > **internal** state of iterator (current position). `tee()` doesn't copy the iterator or its internal state but just caches it's results, so you can iterate over them again. That makes only sense if you expect to use the two iterators in a way they don't get much out of sync. If your usage pattern is "consume iterator 1 fully, and then re-iterate with iterator 2" `tee()` has no advantage over building a list of all results of the original iterator and iterate over that twice. `tee()` would be building this list anyway. > But **external** state - is headache of programmer. So, > iterator/generator have to be method for copy itself (the tee() > implementation) or be "re- startable". Why not? Because it's often not possible without generating a list with all results, and the advantage of a low memory footprint is lost. Ciao, Marc 'BlackJack' Rintsch From lotrpy at gmail.com Wed Jul 2 19:36:48 2008 From: lotrpy at gmail.com (lotrpy) Date: Wed, 2 Jul 2008 16:36:48 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: Message-ID: <4b2f5f71-5f82-4dd8-b58c-9723f72504e5@v26g2000prm.googlegroups.com> On 7?1?, ??5?46?, Ali Servet D?nmez wrote: > I don't want to be so mean here, but how hard it could be be writing a > freesoftware which would automatically/intelligently auto complete > Python code? (I mean something that really does the job, like > Microsoft's Visual Studio or Sun's NetBeans or something else, you > name it, but just don't give me PyDev please...) > > This could be an extension, a plugin, an Emacs mode, a new editor or > even a brand new huge all-fancy IDE, I don't care, but what am I > missing here? > > Could someone please point me out something that I'm really missing > which is already present in the wild, otherwise I'd like discuss with > whoever is willing to help me to get this thing done. I made my mind > and I could volunteer to make this happen as thesis project for my > incoming graduation in the next year. > > Regards you all, > Ali Servet D?nmez ulipad clearly deserves a look. good lucky :) http://code.google.com/p/ulipad/ From bearophileHUGS at lycos.com Sun Jul 20 07:08:01 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 20 Jul 2008 04:08:01 -0700 (PDT) Subject: Not entirely serious: recursive lambda? References: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> Message-ID: Kay Schluehr: > Sure, use a fixed point combinator. I've just added this recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/576366 Does it work? Bye, bearophile From duncan.booth at invalid.invalid Mon Jul 21 13:59:22 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Jul 2008 17:59:22 GMT Subject: Almost keywords References: <30d1a9c0-331f-4263-9775-a1e639082769@m44g2000hsc.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > A possible way to avoid such bugs is to turn all those names like > "list", "map", "filter", "self", etc into keywords. But this may have > some disadvantages (well, I think I'd like to have "self" as keyword, > seen how all Python books strong suggest to not use a name different > from "self"). I'm not convinced by making 'self' a keyword. Forcing the first argument of a method to be named 'self' fails for many reasons (e.g. classmethod/staticmethod) so I don't really see a benefit to making it special in any way. For the other names though, this would have the advantage of allowing the compiler to optimise access to builtins which should provide a slight speed improvement and I think would also make life easier for some implementations (especially things like 'locals()'). A half-way house would be to generate a warning for any use of a name which masks one of the reserved builtins, but only optimise lookups in scopes where no such masking is seen by the compiler: this would prevent you overriding builtins by injecting a name into the global namespace from outside a module but not otherwise break existing code. Of course any of this would break some existing code and therefore isn't going to happen. From kmtracey at gmail.com Sat Jul 26 09:48:14 2008 From: kmtracey at gmail.com (Karen Tracey) Date: Sat, 26 Jul 2008 09:48:14 -0400 Subject: Stripping parts of a path In-Reply-To: <1217073555.2771.41.camel@localhost.localdomain> References: <1217073555.2771.41.camel@localhost.localdomain> Message-ID: On Sat, Jul 26, 2008 at 7:59 AM, Tim Cook wrote: > Hi All, > > I just ran into an issue with the rstrip method when using it on path > strings. > > When executing a function I have a need to strip off a portion of the > current working directory and add on a path to a log file. Initially > this worked great but then I added a branch in SVN which caused the path > to contain 'LNCCWorkshop'. The rstrip() then began removing the > characters 'shop' leaving an incorrect path to the log file. When I > hard coded this path it worked okay but then did the same thing later in > the file when I needed to point to a database. The code worked fine with > a different path. Here are some code fragments. > > > logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/at_build_errors.log' > > this worked when the path was: > /home/tim/ref_impl_python/TRUNK/oship/src/oship/atbldr > > the code above returns: > /home/tim/ref_impl_python/TRUNK/oship/log/at_build_errors.log > > but when I tried a branches version that has the path: > /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/src/oship/atbldr > > it SHOULD return: > > /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/log/at_build_errors.log > > but I get: > /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log > > logfile=os.getcwd() > print logfile is correct; but when I add the .rstrip('src/oship/atbldr') > it also strips the 'shop' off of LNCCWorkshop and returns > /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log > > I had two other people looking at this as we did troubleshooting and we > could not determine the cause. It is repeatable with this path name. > In resolution I renamed the branch to just LNCC and it works fine. > > Thoughts? > I think rstrip does not do what you think it does. From: http://docs.python.org/lib/string-methods.html "The chars argument is not a suffix; rather, all combinations of its values are stripped" Thus, since the characters p,o,h, and s are all in the argument you supplied to rstrip, they are removed, then stripping is stopped at the k because that is not in the chars arg you supplied. To do what you really want I think you need to use rfind/rindex to locate the last occurrence of the substring and then truncate the string yourself. Karen -------------- next part -------------- An HTML attachment was scrubbed... URL: From goldtech at worldpost.com Sun Jul 13 18:17:12 2008 From: goldtech at worldpost.com (goldtech) Date: Sun, 13 Jul 2008 15:17:12 -0700 (PDT) Subject: SAX XML Parse Python error message References: <487A23A5.7000905@behnel.de> <1c87a4e2-7c66-4ced-8622-b6eebc8664bb@i76g2000hsf.googlegroups.com> Message-ID: <4a19c059-0999-47fa-8ca2-c55b5d09c106@l42g2000hsc.googlegroups.com> On Jul 13, 5:30 pm, Waldemar Osuch wrote: > On Jul 13, 3:00 pm, goldtech wrote: > > > I would be grateful for support with the code I cited. It's not long > > and fairly standard. I'm sure my error(s) would be glaring to more > > experienced coders. I appreciated the "heads-up" about other options > > but I would be grateful for help getting this code to run. Thanks > > Initialize self.coodinates in the __init__ > or indent the "print self.description, str(self.coordinates)" > one more level. > You have to remember that "endElement" is being called on the end > of every element. In your case it is called by but > the parser did not see yet. > > In "def characters" you should be collecting the "ch" in a buffer. > It may be called multiple times for the same element. > Something like "self.description += ch" would do for starters. > > Also you do not need to convert self.coordinates to string before > printing, it is already a string and even if it was not "print" > would convert it for you. > > That's it for now :-) Others may spot more issues with > your code or my response. > On the positive side I really liked how you asked > the question. There was a short runnable example and traceback. > > Waldemar Putting the print statements were they won't cause trouble and using ...+= ch (vs. only =) in the character section fixed it: ... def endElement(self, name): ... if name == 'description': self.isdescriptionElement= 0 print self.description if name == 'coordinates': self.iscoordinatesElement = 0 print self.coordinates ... I need to read your answer again carefully - I don't know if what I did is best - but it seemed to fix it. Thank you for the clear and cogent answer. Lee G. From simon at brunningonline.net Sun Jul 6 09:12:32 2008 From: simon at brunningonline.net (Simon Brunning) Date: Sun, 6 Jul 2008 14:12:32 +0100 Subject: Recursive wildcard file search In-Reply-To: References: <496954360807031353n4f91f691recb330f7350cbf70@mail.gmail.com> Message-ID: <8c7f10c60807060612o39622188ld75d2bb0794394a8@mail.gmail.com> 2008/7/4 Gerhard H?ring : > Robert Dailey wrote: >> Is there a way to perform a recursive file search using wildcards in >> python 3.0b1? [...] > > glob.glob() or glob.iglob(). glob's not recursive AFAIK. This recipe probably still works under Pythion 3K, though: -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From aaron.hildebrandt at gmail.com Wed Jul 23 14:34:32 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 23 Jul 2008 11:34:32 -0700 (PDT) Subject: Using variables across modules Message-ID: <855136ce-6c70-40ac-a462-dc0bbfa1fc3a@b2g2000prf.googlegroups.com> I'm having some trouble understanding how Python handles variables across multiple modules. I've dug through the documentation, but I still find myself at a loss. When you import a module, are you creating an instance of the variables within? For instance, if I have one file, "variables.py", which contains "myvar = 0", and I import it into both "foo.py" and "bar.py" with the line "from variables import *", and then set myvar in "foo.py" and "bar.py" to different values, will each file have a different value for myvar? If so, how can I ensure that a change to myvar in "bar.py" is reflected by "foo.py"? Or am I completely off base? From bj_666 at gmx.net Mon Jul 21 04:26:45 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Jul 2008 08:26:45 GMT Subject: What is the role of python2.6 and C++? References: Message-ID: <6eivi5F6vgp3U1@mid.uni-berlin.de> On Mon, 21 Jul 2008 16:17:00 +0800, ?? wrote: > I'm confused about the motivation of releasing python2.6 and python3.0 > at the *same* time. IMO, 2.6 should be compatible with 2.5 while 3.0 > is new style python. That's how it is. 2.6 is backwards compatible with 2.5. > [?] But even without the intermediate version 2.6, project transformation > with be smooth enough, and then 2.5, 2.6 will be replaced by 3.0. I will > not spend any time on studying 2.6. So why does python development team > put many efforts on 2.6? What is the role of 2.6? It's a version that makes the transition smoother. You really should take that "detour" via 2.6. There should be some of the changes from 3.0 in 2.6 that don't mess with backwards compatibility, and a script that tries to automate the conversion from 2.6 to 3.0. This spares a lot of work when porting to 3.0. Ciao, Marc 'BlackJack' Rintsch From roy at panix.com Sun Jul 20 20:37:23 2008 From: roy at panix.com (Roy Smith) Date: Sun, 20 Jul 2008 20:37:23 -0400 Subject: Python Written in C? References: Message-ID: In article , Mensanator wrote: > C isn't a high level language, that's part of its problem. C is the highest level assembler language I've ever used. And I've used a few. It really is cool that you can add two 32-bit integers and not have to worry about all those carry bits. From xahlee at gmail.com Fri Jul 11 02:32:27 2008 From: xahlee at gmail.com (xahlee at gmail.com) Date: Thu, 10 Jul 2008 23:32:27 -0700 (PDT) Subject: Elisp Lesson on file processing (make downloadable copy of a website) References: <7095dc5e-3008-45b8-8665-e746bff84dd6@m36g2000hse.googlegroups.com> Message-ID: <0219b84b-d524-4b3e-9031-ac399be322da@m3g2000hsc.googlegroups.com> Xah Lee wrote: ? ... emacs program and tutorial that does archiving a website for offline reading. (See http://xahlee.org/emacs/make_download_copy.html ) ? Sashi wrote: ?Why not use wget or curl?? The Emacs lisp program makes a archive of parts of website you own, so that readers of your website can click download to read it offline. For wget and curl, i have some tips here: http://xahlee.org/UnixResource_dir/unix_tips.html Xah ? http://xahlee.org/ ? From bearophileHUGS at lycos.com Wed Jul 16 12:10:44 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 16 Jul 2008 09:10:44 -0700 (PDT) Subject: Regular expression References: Message-ID: <47610734-5b49-4fd2-98ce-70976c257d14@d77g2000hsb.googlegroups.com> On Jul 16, 4:14 pm, Fredrik Lundh wrote: > Beema shafreen wrote: > > How do I write a regular expression for this kind of sequences > > > >gi|158028609|gb|ABW08583.1| CG8385-PF, isoform F [Drosophila melanogaster] > > MGNVFANLFKGLFGKKEMRILMVGLDAAGKTTILYKLKLGEIVTTIPTIGFNVETVE > > line.split("|") ? > > it's a bit hard to come up with a working RE with only a single sample; > what are the constraints for the different fields? is the last part > free form text or something else, etc. > > have you googled for existing implementations of the format you're using? That'a a fasta file, so for the header line this is enough: [part.strip() for part in line.split("|")] But better is to use the biopython libs that already perform all such things better. Bye, bearophile From wuwei23 at gmail.com Thu Jul 31 01:49:14 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 30 Jul 2008 22:49:14 -0700 (PDT) Subject: Insert character at a fixed position of lines References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> <7895c8b2-fa01-483c-8ba9-d90975ea688d@o40g2000prn.googlegroups.com> <8b0f4fe2-d8ab-4230-9032-ccd02878d349@v39g2000pro.googlegroups.com> Message-ID: <3ff98b50-ec9b-40d2-a9a5-235926fa1c9e@w39g2000prb.googlegroups.com> On Jul 30, 10:43?pm, Lie wrote: > Lessons learned, should test codes even if you thought it seemed > trivial. And I learned I should always make sure to cut&paste the right example :) From henrik at chamalulu.com Wed Jul 2 05:40:57 2008 From: henrik at chamalulu.com (chamalulu) Date: Wed, 2 Jul 2008 02:40:57 -0700 (PDT) Subject: Attribute reference design References: <6cvlk4F3s90U1@mid.uni-berlin.de> <486b38b6$0$7210$426a74cc@news.free.fr> Message-ID: <787ce82d-4e39-4c34-b91f-bbabd8c3bf14@f63g2000hsf.googlegroups.com> On Jul 2, 10:13 am, Bruno Desthuilliers wrote: > Nope. The wrapping happens at lookup time, thru the descriptor protocol > (the same thing that gives support for properties). Aha, I should read up on that. > Help on built-in function dir in module __builtin__: So, the dir function is a little more helpful than I thaught. I checked instance.__dict__ now instead of dir(instance). No methods. It's getting clearer. Thank you. I think you've provided me with a good reason for class instances to delegate attribute references to the class if class instance doesn't contain the attribute. Diez, Gary, Bruno; Thanks for your help. /Henrik From kyosohma at gmail.com Thu Jul 3 09:40:37 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 3 Jul 2008 06:40:37 -0700 (PDT) Subject: wxPython: How can I get window's HANDLE in wxPython. References: Message-ID: On Jul 2, 8:40?pm, "Leo Lee" wrote: > I need a window's handle to be passed to external c++. > Thanks in advance Are you talking about a wxPython wx.Window object or an external window handle? If the latter, then I recommend asking about that on the PyWin32 user's group. Otherwise, follow Paul's suggestion. Mike From ladasky at my-deja.com Sun Jul 20 03:52:13 2008 From: ladasky at my-deja.com (John Ladasky) Date: Sun, 20 Jul 2008 00:52:13 -0700 (PDT) Subject: Genetic programming: pygene, pygp, AST, or (gasp) Lisp? Message-ID: <7bfb3c41-b08b-49dc-9711-6e39a4667db2@b1g2000hsg.googlegroups.com> Hi folks, I've played around with neural nets for a while. I wrote my own slow, pure-Python NN package. I knew that there were Python NN packages out there -- but I couldn't really understand their features and documentation at first, not without some hands-on experience. I haven't yet solved any interesting problems with NN, but I learned a lot about both NN and about Python along the way. One of the unpleasant things I learned about NN was their propensity for becoming trapped in local minima. I also learned about overfitting, wasting many hours of CPU time in the process. In short, simple neural nets have disappointed me. I have now asked myself: wouldn't it be cool if, when you ceased to make progress on an optimization algorithm, you could divide your data set with an "if" statement, which would evolve a useful dividing line through your data set -- and then, develop divergent solutions to explain each subset better? In mathematical terms: Round 1 of evolutionary programming leads to a single, but sub-optimal solution, probably a solution in a local minimum: b = f(a) Round 2 would start by elaborating the solution of round 1, adding a condition that is initially meaningless: if disc(a) < c: b = f1(a) else: b = f2(a) Initially, f1() = f2() = the original f(). Therefore, the output of the starting state of round 2 will be identical to the output of the final state of round 1, regardless of the initial state of the discriminant function, disc(). But then, f1(), f2(), and disc() will all be permitted to evolve. This may provide a chance to "pop out" of the local minimum, without sacrificing any of the progress made in defining the solution of round 1. Of course, f(), f1(), f2(), and disc() could be complex functions. They would best be described with parse trees, which I've just discovered (I'm not formally trained in computer science). Some reading has led me to conclude that what I'm proposing is basically genetic programming. http://en.wikipedia.org/wiki/Genetic_programming I've tried my hand at this already in Python. I have devised a code tree class, which functions as a parse tree for functions and also handles multiple-line statements. I've tried cobbling together program strings from code trees, and then using the exec() function to run them. This is all very cool, but I'm finding it VERY cumbersome! As with neural nets, I know that there are genetic programming packages offered for Python: http://www.freenet.org.nz/python/pygene/ http://sourceforge.net/projects/pygp/ But I can't really understand what they do -- both of these packages are, alas, minimally documented. Is anyone out there using either of these? I can't tell whether they will implement algorithms of the type I've described here. Specifically, I don't know if conditional statements are included in their repertoire. Also, Pygene SEEMS to have a bent toward Boolean logic. I'm working with analog data, and I want complex, nonlinear functions. So, as with neural nets, shall I once again proceed on my own? There is apparently a layer in the Python interpreter at which code is represented as an abstract syntax tree (AST). http://docs.python.org/lib/ast.html Why not do genetic programming directly on Python code? Maybe my code tree data structure is redundant to something which already exists? But apparently Python's "_ast" module offers only one-way access -- it will generate an AST from a piece of code, but you can't modify an AST, and turn it back into executable code? I would definitely need this latter feature. ALTERNATELY -- and I don't mention this to start a flame war -- in pondering this problem I've noticed the frightening fact that Lisp seems set up to handle genetic programming by design. The s- expression syntax IS essentially a parse tree. Now, I've spent a few hours with Lisp so far, and I can't make it do much of anything -- but I DO see how Lisp could be helpful. Still, I'm reluctant to pursue a language I don't know, and which I'm finding much harder to grasp than any language I've tried before. Is there a way to interface Lisp to Python, so that I can do all the interface programming in the language I already know best -- and just do the genetic parts in Lisp? I haven't seen exception handling in Lisp, a feature I've come to love in Python. Since it is fairly easy for a randomly-generated program to generate illegal output (I already know this from my initial experiments in Python), I don't think I can live without exception handling. I also think that Python has a higher-level understanding of a variable's "type" or an object's "class" than Lisp does -- if I'm hacking at a parse tree and I want to minimize syntax errors, I need to know more than the fact that an element in an expression is an atom or a list. Producing human-readable code from my genetic programming search would be a great bonus -- and for me, at this moment, this seems to mean Algol-style syntax. (Sigh.) But it's not a requirement. Thanks for your advice! From cokofreedom at gmail.com Mon Jul 14 03:16:17 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 14 Jul 2008 00:16:17 -0700 (PDT) Subject: Beginner Question : Iterators and zip References: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> Message-ID: > > zip(*vec_list) will zip together all entries in vec_list > Do be aware that zip stops on the shortest iterable. So if vec[1] is > shorter than vec[0] and matches otherwise, your output line will be > truncated. Or if vec[1] is longer and vec[0] matches as far as it goes, > there will be no signal either. > Do note that from Python 3.0 there is another form of zip that will read until all lists are exhausted, with the other being filled up with a settable default value. Very useful! From circularfunc at gmail.com Sun Jul 27 08:13:36 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 27 Jul 2008 05:13:36 -0700 (PDT) Subject: x*x if x>10 Message-ID: <59b5d431-8218-4a07-a9d7-5357f1c474f8@f36g2000hsa.googlegroups.com> I have seen somewhere that you can write something like: x*x if x>10 but exactly that doesn't work and I can't get any variation to work. it is possible to nest with an else too. how do you write it? and also, is it idiomatic? doesn't seem to add functionality, just another way of doing the same thing which is quite unpythonic but I remember reading it was added because it helped simplify the expression of a certain type of operation. From bulg at ngs.ru Sun Jul 13 02:53:46 2008 From: bulg at ngs.ru (Yosifov Pavel) Date: Sat, 12 Jul 2008 23:53:46 -0700 (PDT) Subject: iterator clone Message-ID: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> Whats is the way to clone "independent" iterator? I can't use tee(), because I don't know how many "independent" iterators I need. copy and deepcopy doesn't work... --pavel From carsten.haese at gmail.com Wed Jul 23 16:15:48 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Wed, 23 Jul 2008 16:15:48 -0400 Subject: Raw Strings (I Think) In-Reply-To: References: Message-ID: Lanny wrote: > I've used glob.glob to get a list of files in a directory > and now I want to use os.system to execute one of > those files, the problem is that python automatically > puts a escape charater infront of the back slashes No, it doesn't. Instead of guessing what the cause might be, please show us your code and show us the error message you're getting, so that we can determine what the cause really is. -- Carsten Haese http://informixdb.sourceforge.net From hiursvapsisnowhere at gmail.com Wed Jul 23 08:31:04 2008 From: hiursvapsisnowhere at gmail.com (SvaPs) Date: Wed, 23 Jul 2008 05:31:04 -0700 (PDT) Subject: How to replace the values with keys ? References: <92df0f7c0807222130n382edf5di8c7124690f3dffa7@mail.gmail.com> Message-ID: <4c61674b-c81e-427a-a916-4aafbd645b7c@u12g2000prd.googlegroups.com> Hi all.., I tried with this.. def multiple_replace(text,adict): rx=re.compile('|'.join(map(re.escape,adict))) def one_xlat(match): return adict[match.group(0)] return rx.sub(one_xlat,text) print multiple_replace(text,adict) I am thrown with a error: Traceback (most recent call last): File "", line 1, in File "", line 2, in multiple_replace TypeError: argument 2 to map() must support iteration I would be grateful for any comments.. Thankin in advance' GraPs. Fredrik Lundh wrote: > "Graps Graps" wrote: > > > Text2 is a python dictionary containing data as > > > > {0: 'a', 1: 'b', 2: 'c'...} > > > > now I want the data in text1 to be replaced with the keys, say like > > > > 0 1 > > 0 2 > > 0 3 > > 0 6 > > 1 2... so on.. > > someone asked a very similar question not long ago, so maybe you're > really supposed to figure this out yourself. I'm sure your teacher > won't kill you if you ask for a hint. > > (if you asked me for a hint, I'd tell you to look for questions about > dictionaries in the mailing list archives). > > From Russ.Paielli at gmail.com Mon Jul 28 00:35:08 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 21:35:08 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> <6a5506b1-632e-4bf6-b0ce-4d51d1751aa9@i24g2000prf.googlegroups.com> <8b4b11c3-e306-4fe7-82d1-0a948c725f2f@r15g2000prd.googlegroups.com> <239a084f-b73d-4c20-aaaf-bbd05d452638@a2g2000prm.googlegroups.com> Message-ID: On Jul 27, 8:38 pm, alex23 wrote: > On Jul 28, 4:59 am, "Russ P." wrote: > > > On Jul 27, 3:11 am, alex23 wrote: > > > > On Jul 27, 4:26 pm, "Russ P." wrote: > > > > > On Jul 26, 11:18 pm, Terry Reedy wrote: > > > > > The use of '.' has been suggested before and rejected. > > > > > Where and why? > > > > Google is your friend:http://mail.python.org/pipermail/python-3000/2006-April/000793.html > > > What Guido rejected there is most certainly *not* > > what I suggested. I agree with Guido on that one. > > Orly? > > Ian Bicking wrote: "I propose that the self argument be removed from > > method definitions." > > Philip Eby suggested: > > > def .aMethod(arg1, arg2): > > return .otherMethod(arg1*2+arg2) > > Guido shot them all down by stating: > > > [Y]ou're proposing to hide a > > fundamental truth in Python, that methods are "just" functions whose > > first argument can be supplied using syntactic sugar > > Any more reading comprehension we can do for you? Dude, I agree with Guido completely on this one. You seem to be clueless about the issue here. You're the one with the reading comprehension problem. Please quit wasting my time with your irrelevant crap. From manuhack at gmail.com Wed Jul 23 16:09:28 2008 From: manuhack at gmail.com (Manu Hack) Date: Wed, 23 Jul 2008 16:09:28 -0400 Subject: fromfile error on windows, not mac In-Reply-To: References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> Message-ID: <50af02ed0807231309p2f7b1333sf45f96a9f082d8f0@mail.gmail.com> On Wed, Jul 23, 2008 at 3:37 PM, jadamwil wrote: > I found the problem: I thought it was opening in binary mode on BOTH > windows and the mac, but on windows I passed "rb" with double quotes, > not 'rb' with single quotes to the open file function. Changing it to > 'rb' fixed it. > > by the way, anyone could explain why changing to single quote makes a difference? >>> "rb" == 'rb' True -------------- next part -------------- An HTML attachment was scrubbed... URL: From adamtaunowilliams at gmail.com Tue Jul 22 13:31:03 2008 From: adamtaunowilliams at gmail.com (whitemice) Date: Tue, 22 Jul 2008 10:31:03 -0700 (PDT) Subject: Authentication for XML-RPC Calls Message-ID: <3e4258ac-40d8-485d-ba65-39d343b9561d@2g2000hsn.googlegroups.com> The only documentation regarding doing authentication for XML-RPC I can find is - "Both the HTTP and HTTPS transports support the URL syntax extension for HTTP Basic Authentication: http://user:pass at host:port/path. The user:pass portion will be base64-encoded as an HTTP `Authorization' header, and sent to the remote server as part of the connection process when invoking an XML-RPC method. You only need to use this if the remote server requires a Basic Authentication user and password." - from http://docs.python.org/lib/module-xmlrpclib.html Is this really the only way to do authentication for XML-RPC calls? Like this: server = xmlrpclib.Server('http://adam:fred123 at localhost/zidestore/so/ adam/' This works, but is pretty ugly. Is there no way to setup the authentication through properties (like in most XML-RPC bindings), like: server = xmlrpclib.Server('http://localhost/zidestore/so/adam/' server.Username = 'adam' server.Password = 'fred123' From fredrik at pythonware.com Wed Jul 23 17:11:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 23:11:11 +0200 Subject: Taking the floating point distances and plotting histogram In-Reply-To: <73045cca0807231402m1c439414s516e5409a704506f@mail.gmail.com> References: <73045cca0807231402m1c439414s516e5409a704506f@mail.gmail.com> Message-ID: aditya shukla wrote: > I have a program whose output is stored in a text file , say test.txt > eg. > 0\9\10\11|0.50|c:\windows\apppatch/AcLayers.dll > 0\9\10\11|0.50|c:\windows\apppatch/AcRedir.dll > 0\9\10|0.66|c:\windows\apppatch/AcSpecfc.dll > 0\9|0.83|c:\windows\apppatch/iebrshim.dll > > After reading this text file i need to extract the float point values > from each line ie , 0.50,0.50,0.66.0.83 respectively > in this case, till the end of the file is reached and then i need to > plot a histogram based on these values . Extracting is easy; you can do something like data = [] for line in open("test.txt"): line = line.split("|") data.append(float(line[1])) (or maybe use the csv module with a custom separator) Plotting is a bit different -- there are many ways to do that, depending on where and how you want to display that histogram (on a website, in a window on your machine, in a PDF file, ...), but most solutions require additional libraries. Here's one such library: http://matplotlib.sourceforge.net/ From dstromberglists at gmail.com Wed Jul 9 02:46:09 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Wed, 09 Jul 2008 06:46:09 GMT Subject: how to remove oldest files up to a limit efficiently References: <1eb168ac-fc63-4724-8604-45e995a06b51@s50g2000hsb.googlegroups.com> Message-ID: On Tue, 08 Jul 2008 15:18:23 -0700, linuxnow at gmail.com wrote: > I need to mantain a filesystem where I'll keep only the most recently > used (MRU) files; least recently used ones (LRU) have to be removed to > leave space for newer ones. The filesystem in question is a clustered fs > (glusterfs) which is very slow on "find" operations. To add complexity > there are more than 10^6 files in 2 levels: 16? dirs with equally > distributed number of files inside. > > My first idea was to "os.walk" the filesystem, find oldest files and > remove them until I reach the threshold. But find proves to be too slow. > > My second thought was to run find -atime several times to remove the > oldest ones, and repeat the process with most recent atime until > threshold is reached. Again, this needs several walks through the fs. > > Then I thought about tmpwatch, but it needs, as find, a date to start > removing. > > The ideal way is to keep a sorted list if files by atime, probably in a > cache, something like updatedb. > This list could be also be built based only on the diratime of the first > level of dirs, seek them in order and so on, but it still seems > expensive to get his first level of dir sorted. > > Any suggestions of how to do it effectively? os.walk once. Build a list of all files in memory. Sort them by whatever time you prefer - you can get times from os.stat. Then figure out how many you need to delete from one end of your list, and delete them. If the filesystem is especially slow (or the directories especially large), you might cluster the files to delete into groups by the directories they're contained in, and cd to those directories prior to removing them. From jeffrey at fro.man Fri Jul 11 11:23:24 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Fri, 11 Jul 2008 08:23:24 -0700 Subject: read file into list of lists References: <48775fee$0$928$ba4acef3@news.orange.fr> Message-ID: Laurent Rahuel wrote that antar2 wrote: >> following text for example should be considered as a list of lists (3 >> columns and 3 rows), so that when I make the print statement list[0] >> [0], that the word pear appears >> >> >> pear noun singular >> books nouns plural >> table noun singular File objects are themselves iterable, returning one line per iteration. So a simple approach is: >>> table = [line.split() for line in open('sentences.txt')] >>> table[0][0] 'pear' Jeffrey From banuchandar46 at gmail.com Sat Jul 19 18:35:30 2008 From: banuchandar46 at gmail.com (Prabhu) Date: Sat, 19 Jul 2008 15:35:30 -0700 (PDT) Subject: Free online computer studies Message-ID: <4fee65d8-e4c5-4d51-abce-89d813e30b61@v1g2000pra.googlegroups.com> Free online computer studies super visualize study get all courses,hurry up limited offer http://vijaydollars.blogspot.com/ http://friendfinder.com/go/g981367 http://amigos.com/go/g981367 From kylotan at gmail.com Wed Jul 23 08:08:58 2008 From: kylotan at gmail.com (Ben Sizer) Date: Wed, 23 Jul 2008 05:08:58 -0700 (PDT) Subject: Undefined calling conventions in Python.h References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> Message-ID: <216dcee8-ad3d-4ae1-ac4a-4f4819775c7e@d1g2000hsg.googlegroups.com> On Jul 23, 11:43?am, Jaco Naude wrote: > What Visual C++ is doing is that it is looking for mangled names since > it does not know the DLL contains C functions. I've managed to work > around this by declaring the Python functions as follows before using > them in the C++ application side: > > extern "C" > { > ? ? void Py_Initialize(void); > > } You should put the extern block around the #include call rather than individual functions, as surely the C calling convention should apply to everything within. > It is probably more of a C++ question it turns out, but I would think > that someone in the Python group would use the Python DLL in C++. More of a Visual C++ question specifically, since the __clrcall prefix is a MS specific extension (http://msdn.microsoft.com/en-us/library/ ec7sfckb(VS.80).aspx). If you're not using managed code in your app, disable it in the project/build options. If you are, then perhaps you just need to specify that you're not with this DLL, though I've never had to deal with anything like that myself. -- Ben Sizer From Russ.Paielli at gmail.com Sun Jul 27 14:59:05 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 11:59:05 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> <6a5506b1-632e-4bf6-b0ce-4d51d1751aa9@i24g2000prf.googlegroups.com> Message-ID: <8b4b11c3-e306-4fe7-82d1-0a948c725f2f@r15g2000prd.googlegroups.com> On Jul 27, 3:11 am, alex23 wrote: > On Jul 27, 4:26 pm, "Russ P." wrote: > > > On Jul 26, 11:18 pm, Terry Reedy wrote: > > > The use of '.' has been suggested before and rejected. > > > Where and why? > > Google is your friend:http://mail.python.org/pipermail/python-3000/2006-April/000793.html What Guido rejected there is most certainly *not* what I suggested. I agree with Guido on that one. From Russ.Paielli at gmail.com Mon Jul 28 00:27:19 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 21:27:19 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: On Jul 27, 6:21 pm, Terry Reedy wrote: > Russ P. wrote: > > On Jul 27, 12:39 pm, Bruno Desthuilliers > > All I am suggesting is that the programmer have the option of > > replacing "self.member" with simply ".member", since the word "self" > > is arbitrary and unnecessary. > > I presume you are proposing the opposite also, that ".member" would > internally be expanded to "self.member". > > As I said before, that, or something near like it (it is hard to exactly > compare underspecified proposals) has be suggested and rejected, even if > someone gave you not the exact reference. For one thing, as Guido > noted, a single . can be hard to see and easy to miss, depending on > one's eyesight, environmental lighting, and exact display medium, > including font. > > I suspect Guido's other reasons have been covered, but I do not want > misquote him. I will leave you to search the pydev list archives. > > > Otherwise, everything would work *EXACTLY* the same as it does now. > > If I understand you, that would mean that .attribute would raise > NameError: name 'self' is not defined > if used anywhere where 'self' was not defined. After thinking about this a bit more, let me try to be more specific. Forget about the empty first argument and the "." for the first argument. Just let the first argument be "self" or anything the programmer chooses. No change there. If access is needed to "self.var", let it be accessable as either "self.var" or simply ".var". Ditto for "self.method()", which would be accessible as ".method()". In other words, wherever ".var" appears, let it be interpreted as ".var". If the first argument is "self", then it should be equivalent to "self.var". If the first argument is "snafu", then ".var" should be equivalent to "snafu.var". I can't think of any technical problem with this proposal, but I may be overlooking something. If so, please let me know. This proposal should be relatively easy to implement, and it would reduce code clutter significantly. (I could probably write a pre- processor to implement myself it in less than a day.) From fredrik at pythonware.com Thu Jul 24 17:20:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 23:20:52 +0200 Subject: Neat way to get rid of [" "] in sys.argv[n:] returns In-Reply-To: References: Message-ID: korean_dave wrote: > python test.py "testparameter" > > I get this output: > > ------------- > ['testparameter'] > ---------------- > > Is there a way to neatly, in one call to the parameter, to get rid of > the [' and '] without bothering to replace() '[ with "" and replace() > '] with ''? Since you're using slicing instead of indexing, you're printing a list, not a single string. There is no '[ or ]' in the string itself, and no need to replace it with anything. To print just that string, do print sys.argv[1] # fetch item instead of print sys.argv[1:] # slice list I suggest working through a tutorial or two. Pay special attention to the difference between an object's value and the various ways that value can be output. From joe at goldthwaites.com Thu Jul 3 12:00:52 2008 From: joe at goldthwaites.com (Joe Goldthwaite) Date: Thu, 3 Jul 2008 09:00:52 -0700 Subject: SQLite and Python 2.4 In-Reply-To: Message-ID: <200807031600.m63G0tJ6023817@vm-mailout1.fpw.ch> Thanks Guilherme. That helped. I guess I was thinking that pysqlite would automatically come with some version of sqlite. The fact that it doesn't is what was causing me to get the strange results. I downloaded the Windows version of the SQLite3.dll. I didn't know where to put it so I first put it in its own directory and tried to register it. That didn't work so I just moved it to the pysqlite directory in site-packages. That did the trick. It took way longer than I thought to figure out how this stuff worked. Here's an example putting it all together. It's Windows specific but only for the part that finds where the cookies.sqlite file is. Maybe it will save someone else the time. import ConfigParser from pysqlite2 import dbapi2 as sqlite import os def GetFirefoxCookies(domain, d): """This function gets all FireFox 3 cookies for the passed in domain and adds them to the dict object""" # Get the Firefox data path FireFoxPath = os.environ['AppData'] + '\Mozilla\Firefox' # use the FireFoxPath to load up the profies.ini file iniFileName = r'%s%s' % (FireFoxPath, r'\profiles.ini') # use the ConfigParser module to load in the contents of the ini file parser = ConfigParser.ConfigParser() parser.read(iniFileName) # I'm just getting the path from the [Profile0] section since this code # is only running on my system. For a production system, you'd probably # want to look for the section with "default=1". path = parser.get('Profile0','Path') # with all that, we can finally find the cookies.sqlite file dbfile = '%s\%s\%s' % (FireFoxPath, path.replace('/','\\'), 'cookies.sqlite') # Next create an sqlite connection object and load up the cookies table conn = sqlite.connect(dbfile) # get a cursor object c = conn.cursor() # get the name and cookie values c.execute("SELECT name, value FROM moz_cookies WHERE host = '%s'" % domain) # loop through the cookies and add their key and values to the # dictionary. for row in c.fetchall(): d[row[0].encode('utf-8')] = row[1].encode('utf-8') if __name__ == '__main__': domain = 'localhost' cookiedict = {} GetFirefoxCookies(domain, cookiedict) print cookiedict -----Original Message----- From: Guilherme Polo [mailto:ggpolo at gmail.com] Sent: Tuesday, July 01, 2008 6:15 PM To: joe at goldthwaites.com; python-list at python.org Subject: Re: SQLite and Python 2.4 On Tue, Jul 1, 2008 at 9:51 PM, Joe Goldthwaite wrote: > I'm confused. (Not a new experience). I've got a web application running > under Zope. I use the Wing IDE for testing and debugging. When trying to > recreate problems that come up on the web, I wrote some little routines that > pull my cookies out of the Firefox cookies.txt file into my code. That way, > I'm working with all the same options under Wing that my app uses when > running under Zope. > > That's worked great until I upgraded to Firefox 3. Firefox 3 moved their > cookies from cookies.txt to cookies.sqlite. I haven't worked with SQLite at > all so I started searching for examples and found this; > > import sqlite3 > conn = sqlite3.connect('test.db') > c = conn.cursor() > rows = c.execute('SELECT * from somefile') > > Looks simple enough but I can't get it to work. Here are my questions; > > 1. How do you get sqlite3 for Python 2.4? I can't find it anywhere. You need sqlite itself (www.sqlite.org) and bindings, pysqlite 2 (http://oss.itsystementwicklung.de/trac/pysqlite/) or aspw (http://code.google.com/p/apsw/) > > 2. If sqlite3 is only for Python 2.5, does sqlite2 work the same way? > You are confused, yes. The sqlite3 package that comes with python2.5 is actually pysqlite2, which interfaces with sqlite3. Also, sqlite3 and sqlite2 files format are not compatible. > 3. Looking at the cookies.sqlite file, I see some text right at the top > "SQLite format 3". Does that mean that I need to use sqlite3? Yes > > I kind of got the above example using pysqlite2.4.1 for python 2.4. I get > through the part where I create the connection object but the resulting > object doesn't have a cursor method. I thought that maybe it wasn't > recognizing the cookies.sqlite file as a SQLite database so I tried the same > code giving it a junk text file instead and it behaved the same way. Since > I didn't get an error message, I'm thinking that I've got the wrong version > for the Firefox cookies.sqlite file. > > I don't have a clue as to where else to look to trace it down. I'm hoping > that someone here is more familiar with it and can give me some pointers. > > Thanks, > > Joe Goldthwaite > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From weizhonghua.ati at gmail.com Wed Jul 16 06:00:38 2008 From: weizhonghua.ati at gmail.com (zhw) Date: Wed, 16 Jul 2008 03:00:38 -0700 (PDT) Subject: How can i use a variable without define it ? References: <87k5fm2p1x.fsf@benfinney.id.au> <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> <87fxqa2mu0.fsf@benfinney.id.au> Message-ID: <5dd91053-d239-4ff1-b693-d6afedf6bf24@x35g2000hsb.googlegroups.com> On 7?16?, ??5?35?, Ben Finney wrote: > zhw writes: > > Here is a example that I want to complete: > > >>> import sys, new > > >>> context={"name":"david", "sex":"male"} > > Here you have a set of values addressible by name. > > > >>> sys.modules["foo"] = new.module("foo") > > Why do you believe you need to create a module object? > > > >>> import foo > > >>> for attr in context: > > setattr(foo, attr, context[attr]) > > This doesn't appear to get you anything that isn't already available > with the 'context' mapping. > > > >>> def bar(): > > # here is a error > > # import * only allowed at module level > > from foo import * > > print name, sex > > You can simply do: > > >>> context = {'name': "david", 'sex': "male"} > >>> def bar(): > ... print context['name'], context['sex'] > ... > >>> bar() > david male > > Or, more flexible and more explicit: > > >>> foo = {'name': "david", 'sex': "male"} > >>> def bar(context): > ... print context['name'], context['sex'] > ... > >>> bar(foo) > david male > > What problem are you trying to solve? I an sorry, I can't tell you. If you can't give a solution, just ignore it! From mccredie at gmail.com Wed Jul 16 18:10:01 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 16 Jul 2008 15:10:01 -0700 (PDT) Subject: One step up from str.split() References: Message-ID: <0aa3b82e-9caa-4f02-8578-831300f53ebe@y21g2000hsf.googlegroups.com> On Jul 15, 4:28?pm, "Joel Koltner" wrote: > "Sion Arrowsmith" wrote in message > > news:Tiv*wYYhs at news.chiark.greenend.org.uk... > > > What's wrong with sys.argv ? > > Mainly that it doesn't exist. ?:-) ?The example was slightly contrived -- I'm > really dealing with commands interactively entered within a program in > response to raw_input(), although the format of the commands is meant to be > consistent with command-line usage. ?(A real command, for instance, would be > something like this: load "my firmware file.bin" .) > > I ended up using shlex.strip() -- works great! > > ---Joel Then... better yet... check out the cmd module (you can still use shlex if you like). [code] import cmd class MyCmd(cmd.Cmd): def do_blah(self, args): """Sing a song about bla""" print >>self.stdout, "bla bla bla" def do_foo(self, args): """Prints out the args""" print >>self.stdout, repr(args) def do_quit(self, args): """exit the command interpreter""" print >>self.stdout, "bye bye" return True do_exit = do_q = do_quit if __name__ == "__main__": MyCmd().cmdloop() [/code] When run, you will get a "(cmd)" prompt: (Cmd) help Documented commands (type help ): ======================================== blah exit foo q quit Undocumented commands: ====================== help (Cmd) help blah Sing a song about bla (Cmd) help exit exit the command interpreter (Cmd) help foo Prints out the args (Cmd) qu *** Unknown syntax: qu (Cmd) quit bye bye Documentation here: http://docs.python.org/lib/module-cmd.html Matt From darcy at druid.net Thu Jul 10 12:13:45 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 10 Jul 2008 12:13:45 -0400 Subject: Loading just in time In-Reply-To: References: Message-ID: <20080710121345.60d4fa02.darcy@druid.net> On Thu, 10 Jul 2008 11:03:10 -0500 Larry Bates wrote: > D'Arcy J.M. Cain wrote: > > def calc_tax(*arg, **name): > > from calc_tax import calc_tax as _func_ > > calc_tax = _func_ > > return _func_(*arg, **name) > You are stuck in a futile battle called "premature optimization". I would I thought that I might be. > suggest that you stop worrying about any performance you would gain from doing > something like this. Python has been "highly" optimized to handle imports in a > very efficient way. Just put your functions in a file and import them. Performance optimization wasn't really my goal here. What I was looking for was the ability to spread the functions around different files to manage them better from a proggrammer's POV. Oh well. I guess I will just combine them all again. At least I found some dead code, duplicate functions and just plain bad code doing this little exercise. :-) -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From fredrik at pythonware.com Tue Jul 22 12:54:01 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 18:54:01 +0200 Subject: Question about inheritence In-Reply-To: References: Message-ID: Catherine Heathcote wrote: > If I create a new class inherited from another with a constructor, what > happens with the new class's constructer? assuming that you mean "is it called or not?": Python doesn't really have constructors; when you create an object, Python first creates the object and then calls the __init__ method, if available that method is an ordinary method, and behaves like all other methods: if you override it, your version is used. if you don't, the other one is used. >>> class Parent: ... def __init__(self): ... print "init parent" ... >>> class Child(Parent): ... pass ... >>> o = Child() init parent >>> class Child(Parent): ... def __init__(self): ... print "init child" ... >>> o = Child() init child if you want to override the parent's init method, but still use its functionality, you can add an explicit call to the method: >>> class Child(Parent): ... def __init__(self): ... Parent.__init__(self) ... print "init child" ... >>> o = Child() init parent init child since it's an ordinary method call, you don't have to initialize the parent the first thing you do. you can also pass in any arguments you want (including arguments passed to the child constructor): >>> class OtherChild(OtherParent): ... def __init__(self, a, b, c): ... self.c = c ... OtherParent.__init__(self, a + b) ... there's even a common pattern for passing along *all* arguments, no matter what they are: >>> class OtherChild(OtherParent): ... def __init__(self, *args, **kwargs): ... # do something here ... OtherParent.__init__(self, *args, **kwargs) ... # do something else here ... instead of explicitly naming the baseclass, you can use the "super" method to automatically look up the parent class, but this only works if the parent class inherits from "object" or a subclass thereof: >>> class Parent(object): ... def __init__(self): ... print "init parent" ... >>> class Child(Parent): ... def __init__(self): ... super(Child, self).__init__() ... print "init child" ... >>> o = Child() init parent init child hope this helps! From nicolas.pourcelot at gmail.com Fri Jul 18 05:09:57 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Fri, 18 Jul 2008 02:09:57 -0700 (PDT) Subject: checking if an object IS in a list Message-ID: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> Hi, I want to test if an object IS in a list (identity and not equality test). I can if course write something like this : test = False myobject = MyCustomClass(*args, **kw) for element in mylist: if element is myobject: test = True break and I can even write a isinlist(elt, mylist) function. But most of the time, when I need some basic feature in python, I discover later it is in fact already implemented. ;-) So, is there already something like that in python ? I tried to write : 'element is in mylist' but this appeared to be incorrect syntax... All objects involved all have an '__eq__' method. Thanks, N. P. PS: Btw, how is set element comparison implemented ? My first impression was that 'a' and 'b' members are considered equal if and only if hash(a) == hash(b), but I was obviously wrong : >>> class A(object): ... def __eq__(self,y): ... return False ... def __hash__(self): ... return 5 ... >>> a=A();b=A() >>> a==b False >>> hash(b)==hash(a) True >>> b in set([a]) False >>> S=set([a]) >>> S.difference([b]) set([<__main__.A object at 0xb7a91dac>]) So there is some equality check also, maybe only if '__eq__' is implemented ? From linuxnow at gmail.com Tue Jul 8 18:18:23 2008 From: linuxnow at gmail.com (linuxnow at gmail.com) Date: Tue, 8 Jul 2008 15:18:23 -0700 (PDT) Subject: how to remove oldest files up to a limit efficiently Message-ID: <1eb168ac-fc63-4724-8604-45e995a06b51@s50g2000hsb.googlegroups.com> I need to mantain a filesystem where I'll keep only the most recently used (MRU) files; least recently used ones (LRU) have to be removed to leave space for newer ones. The filesystem in question is a clustered fs (glusterfs) which is very slow on "find" operations. To add complexity there are more than 10^6 files in 2 levels: 16? dirs with equally distributed number of files inside. My first idea was to "os.walk" the filesystem, find oldest files and remove them until I reach the threshold. But find proves to be too slow. My second thought was to run find -atime several times to remove the oldest ones, and repeat the process with most recent atime until threshold is reached. Again, this needs several walks through the fs. Then I thought about tmpwatch, but it needs, as find, a date to start removing. The ideal way is to keep a sorted list if files by atime, probably in a cache, something like updatedb. This list could be also be built based only on the diratime of the first level of dirs, seek them in order and so on, but it still seems expensive to get his first level of dir sorted. Any suggestions of how to do it effectively? From basti.wiesner at gmx.net Wed Jul 16 16:23:45 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Wed, 16 Jul 2008 22:23:45 +0200 Subject: Is there any component-oriented (non-MVC) web framework available for Python? References: <5fdd1388-bb1e-4a59-8fd1-2aa1ce7fa6e0@79g2000hsk.googlegroups.com> Message-ID: Alis : > Is there any component-oriented (non-MVC) web framework available for > Python? > > That is something like Apache Wicket, Tapestry or JSF, but I need it > to be in Python. Zope [1] might be worth trying. [1] http://www.zope.org -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From cs at zip.com.au Fri Jul 25 22:23:30 2008 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 26 Jul 2008 12:23:30 +1000 Subject: How to find processes from Python In-Reply-To: <9f04931c-867b-4ff3-820c-3f8d0bfd2618@e53g2000hsa.googlegroups.com> Message-ID: <20080726022330.GA25922@cskk.homeip.net> On 25Jul2008 11:34, Johny wrote: | Is there a way how to find out running processes?E.g. how many | Appache's processes are running? See the popen function and use the "ps" system command. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ When asked what would I most want to try before doing it, I said Death. - Michael Burton, michaelb at compnews.co.uk From pavlovevidence at gmail.com Wed Jul 30 22:00:18 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 30 Jul 2008 19:00:18 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> Message-ID: On Jul 30, 4:49 am, Ethan Furman wrote: > Carl Banks wrote: > > On Jul 29, 6:42 pm, Matthew Fitzgibbons wrote: > >> I don't have any postable code (it's in a half way state and I haven't > >> touched it for a while), but I'll see if I can't find the time to bang > >> something up to give you the gist. > > > I wouldn't bother at this point. I was looking to see if someone > > could come up with something to disprove my belief on the polymorphic > > uselessness of "if x" relative to explicit tests, and if (as I > > anticipated) they did not, I could claim that "if x" is really just a > > glorified keystroke saver. But I now realize that the failure of this > > bunch doesn't prove anything. I don't think most people even realize > > why answering the question I asked would demonstrate the usefulness of > > "if x". > > > Your example isn't exactly the smoking gun I was looking for, but I > > guess we'll have to admit that at least one usage will suffer for not > > having it. > > > Carl Banks > > Even for those that did realize, and in fact hoped that that is what you > were attempting to accomplish, I was not attempting to accomplish what you think I was. I was looking for it, but I didn't want to see it. I didn't expect to see it. I wanted to show that "if x" doesn't have the polymorphic advantage people mindlessly claim it does by posing the challenge and having people fail to meet it, and for the most part the examples that met the challenge were for minor usages. Ok, someone wrote a filter that truly benefits from polymorphism of "if x" against very different types, but really, these use cases aren't all that common. It's not like it's an everyday thing for you to write "if x" instead of "if x!=0", and that it actually saves you from having to rewrite the condition because later you decided to use a list. So I stand by the point I was trying to make: for your average day-to- day programming, the main benefit of "if x" is to save keystrokes. It doesn't help your code become more polymophic in practice. A little more polymorphic, yes. A lot, no. > it was still quite frustrating to see you > ignoring all the non-code, yet perfectly valid examples of why "if x" > was not only valid, but the most pythonic[1] way to get the task done. Pfft. The usage of "if x" might be Pythonic, but I think the best way is the way Java does it. > I think it would have been a better discussion if you had responded with > reasons why, and not just parroted the "show me the code!" line over and > over and over and ... It seemed as if you thought you were the > professor, impatiently trying to teach a class full of idiots by playing > the devil's advocate. I wasn't playing Devil's advocate, I was playing the Devil. That's why I did that. Sorry if it irritated people but I wasn't about to those things distract me. > I was sure hoping someone would get the actual > code example and post it, partly because I enjoy learning, but mostly > because it would (hopefully) shut you up and move the conversation > along. In fact, somebody did post some code about a custom matrix > class, where __len__ was useless, and still you kept on with... pah. I admit it! I downplay even successful examples because I just don't like implicit booleans. What can I say, I'm an optimist. I didn't see any custom matrix class, BTW. The only code I saw was Steven D'Aprano filter which he still apparently expects me to take his word for it that the alternative I proposed won't work, and Terry Reedy's empty-enabled iterator. Oh, also Heiko Wundram's integer set. > It's late, so before I say something stupid I'll finish this. My last > thought on the matter -- up until this thread I had looked forward to > your posts, Carl. I think you did more damage than good to yourself > with this stunt. Sorry, but I must go on a crusade every once in awhile, whatever damage it may cause my esteem. It's in my nature. Carl Banks From ethan at stoneleaf.us Thu Jul 10 11:34:35 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 10 Jul 2008 07:34:35 -0800 Subject: a simple 'for' question In-Reply-To: References: <4874017D.2000401@umbc.edu> <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> <487437E6.8010609@umbc.edu> <1215599630.2873.965.camel@localhost.localdomain> <48749F60.7030106@umbc.edu> Message-ID: <48762C0B.60407@stoneleaf.us> Tim Roberts wrote: > Ethan Furman wrote: > > >>Ben Keshet wrote: >> >>>it didn't help. it reads the pathway "as is" (see errors for both >>>tries). It looks like it had the write pathway the first time, but >>>could not find it because it searched in the path/way instead of in the >>>path\way. thanks for trying. >> >>The form of slash ('\' vs '/') is irrelevant to Python. At least on >>Windows. >> >> >>>folders= ['1','2','3'] >>>for x in folders: >>> print x # print the current folder >>> filename='Folder/%s/myfile.txt' %[x] >> >> ^- brackets not needed > > > More than that, the brackets are CAUSING this problem. The "%" formatting > operator expects to find either a single item, or a tuple containing > multiple items. It does NOT look for a generic iterator. In this case, > the %s will use the whole list as its parameter. Python converts the list > to string, and the string representation of that one-item list is ['1']. You are, of course, correct -- the brackets are causing the displayed problem below. But judging from the thread so far, there are actually multiple problems going on here, of which the brackets are only this one part. It looks like the OP also lacks understanding regarding absolute and relative path names, as well as (possibly) not knowing where his script/interpreter is running from. > > >>> f=open(filename,'r') >>> >>>gives: IOError: [Errno 2] No such file or directory: >>>"Folder/['1']/myfile.txt" > > > Just like that. > > >>As far as the Python question of string substitution, "%s" % var is an >>appropriate way. > > > Right. From jim.hefferon at gmail.com Tue Jul 1 20:42:41 2008 From: jim.hefferon at gmail.com (Jim) Date: Tue, 1 Jul 2008 17:42:41 -0700 (PDT) Subject: convert unicode characters to visibly similar ascii characters References: <17d4c282-8606-4d29-9e71-d34f5e6d13bb@m44g2000hsc.googlegroups.com> Message-ID: On Jul 1, 8:29 pm, John Machin wrote: > On Jul 2, 9:55 am, Jim wrote: > > Comments on the above grep output: > 1. You have SOFT HYPHEN twice, mapping it to u'-' and '-' Hmph. I'll correct that. Thanks. > 2. The idea of a soft hyphen is as a hint to a hyphenator about where > to insert a hyphen if one is necessary and the hyphenator is suspected > of acting cluelessly without the hint. IMHO, asciification should > substitute u'', not u'-'. Thanks also here. I'll think about it. > 3. Read PEP 8. s/:/: / I don't like the spacing in 8, personally. Thanks, Jim From chiendarret at gmail.com Sat Jul 26 11:47:52 2008 From: chiendarret at gmail.com (Francesco Pietra) Date: Sat, 26 Jul 2008 17:47:52 +0200 Subject: Insert character at a fixed position of lines In-Reply-To: <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> Message-ID: Sorry to come again for the same problem. On commanding: $ python script.py 2>&1 | tee fileout.pdb nothing occurred (fileout.pdb was zero byte). The script reads: f = open("xxx.pdb", "w") f.write('line = line[:22] + "A" + line[23:]') f.close() File xxx.pdb is opened by the command: when I forgot the single quote ' after [23:] the error answer was: SynthaxError: EOL while scanning single-quoted string. Thanks francesco On Sat, Jul 26, 2008 at 1:10 PM, Lie wrote: > On Jul 26, 5:42 pm, "Francesco Pietra" wrote: >> I am still at the stone age, using scripts (e.g., to insert a string >> after a string) of the type >> >> f = open("xxx.pdb", "r") >> for line in f: >> print line >> if "H16Z POPC" in line: >> print "TER" >> f.close() >> >> That is, I have to learn about modules. In your scripts I am lost >> about the filename for the pdb file to modify, > > In Python, stdin and stdout (as provided by the sys module) is a file- > like object, i.e. it have similar behavior as regular files you opened > with open(). stdin is a read-only file, while stdout is a write-only > file. You already know how to make read-only file, f = open("xxx.pdb", > "r"), to make it writable, you've got to use 'w' as the mode: f = > open("xxx.pdb", "w") > > After that you can do this: > f.write('some string') > > >> francesco >> >> >> >> On Sat, Jul 26, 2008 at 11:35 AM, Lie wrote: >> > On Jul 26, 2:41 pm, "Francesco Pietra" wrote: >> >> How to insert letter "A" on each line (of a very long list of lines) >> >> at position 22, i.e., one space after "LEU", leaving all other >> >> characters at the same position as in the original example: >> >> >> ATOM 1 N LEU 1 146.615 40.494 103.776 1.00 73.04 1SG 2 >> >> >> In all lines"ATOM" is constant as to both position and string, while >> >> "LEU" is constant as to position only, i.e., "LEU" may be replaced by >> >> three different uppercase letters. Therefore, the most direct >> >> indication would be position 22. >> >> >> Should the script introduce blank lines, no problem. That I know how >> >> to correct with a subsequent script. >> >> >> Thanks >> >> chiendarret >> >> > If you want to leave the rest of the strings as-is (i.e. the letter A >> > overwrites whatever on position 22), Peter's code need to be modified >> > a little: >> > line = line[:22] + " " + line[23:] >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> -- >> Dr Francesco Pietra >> Professor of Chemistry >> Accademia Lucchese di Scienze, Lettere e Arti, founded in 1594 >> Palazzo Ducale >> 55100 Lucca (Italy) >> e-mail chiendar... at gmail.com > > -- > http://mail.python.org/mailman/listinfo/python-list > From wmcbrine at users.sf.net Mon Jul 28 20:39:17 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Tue, 29 Jul 2008 00:39:17 GMT Subject: like py2exe, but on a mac References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> <_7ojk.253$wS4.85@trnddc03> <488E1B93.1060408@codebykevin.com> Message-ID: On Mon, 28 Jul 2008 15:18:43 -0400, Kevin Walzer wrote: > Add this call to your Python script somewhere (modify as needed): > > try: > self.tk.call('console', 'hide') > except TclError: > pass Ah, yes! Thanks. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From dickinsm at gmail.com Tue Jul 8 09:55:26 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 8 Jul 2008 06:55:26 -0700 (PDT) Subject: numeric emulation and __pos__ References: Message-ID: <92e3ea9f-5745-4072-9d09-7c14fd335828@f36g2000hsa.googlegroups.com> On Jul 8, 12:12?am, Ethan Furman wrote: > 1) Any reason to support the less common operators? > ? ? ? ? i.e. <<, >>, &, ^, | No reason to support any of these for a nonintegral nonbinary type, as far as I can see. > 2) What, exactly, does .__pos__() do? ?An example would help, too. > Very little: it implements the unary + operator, which for most numeric types is a no-op: >>> +5.0 5.0 So you could safely implement it as: def __pos__(self): return self By the way, have you met the Decimal type? It also keeps track of significant zeros. For example: >>> from decimal import Decimal >>> Decimal('1.95') + Decimal('2.05') Decimal("4.00") (Note that the output includes the extra zeros...) Interestingly, in Decimal the __pos__ operation isn't a no-op: it rounds a Decimal to the current context, and it also (mistakenly, in my opinion) changes -0.0 to 0.0: >>> +Decimal('-0.0') Decimal("0.0") >>> +Decimal('123456789123456789123456789123456789') Decimal("1.234567891234567891234567891E+35") Mark From gherron at islandtraining.com Mon Jul 28 18:00:16 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 28 Jul 2008 15:00:16 -0700 Subject: seemingly simple list indexing problem In-Reply-To: References: Message-ID: <488E4170.2020804@islandtraining.com> Guilherme Polo wrote: > On Mon, Jul 28, 2008 at 6:24 PM, Ervan Ensis wrote: > >> My programming skills are pretty rusty and I'm just learning Python so this >> problem is giving me trouble. >> >> I have a list like [108, 58, 68]. I want to return the sorted indices of >> these items in the same order as the original list. So I should return [2, >> 0, 1] >> > > You could simply do this: > > a = [108, 58, 68] > b = sorted(a) > [b.index(c) for c in a] > Yuck. Slow, and it fails if duplicate list elements exist. Also... This looks like a beginners programming assignment. Let's let him try it himself. We can offer help rather than full solutions if he has specific Python questions. > >> For a list that's already in order, I'll just return the indices, i.e. [56, >> 66, 76] should return [0, 1, 2] >> >> Any help would be appreciated. >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > > > From thomas.bugzilla at gmx.net Thu Jul 10 08:11:46 2008 From: thomas.bugzilla at gmx.net (Thomas) Date: Thu, 10 Jul 2008 14:11:46 +0200 Subject: Relative Package Import In-Reply-To: References: Message-ID: Peter Otten wrote: > Thomas wrote: > >> Robert Hancock wrote: >>> mypackage/ >>> __init__.py >>> push/ >>> __init__.py >>> dest.py >>> feed/ >>> __init__py >>> subject.py >>> >>> In subject.py I have >>> from ..push import dest >> There is no such thing as relative package imports. See >> http://www.python.org/doc/essays/packages.html > > Unless you are using Python 1.5 the following document is a bit more > relevant: > > http://www.python.org/dev/peps/pep-0328/ Oups, thanks for the pointer. I thought the old doc was still valid... (gee, there should be forward references). Thomas From swiftone at swiftone.org Sat Jul 26 15:38:14 2008 From: swiftone at swiftone.org (Brett Ritter) Date: Sat, 26 Jul 2008 12:38:14 -0700 (PDT) Subject: Simple Path issues References: <7bef6df9-45d6-4ef6-b802-1dd201ec66e3@k30g2000hse.googlegroups.com> Message-ID: <6093d9df-d68d-43e7-90d4-44f964529299@m3g2000hsc.googlegroups.com> On Jul 26, 2:57?pm, Gary Josack wrote: > sys.path is a list that will tell you where python is looking. You can > append to this in your scripts to have python look in a specific > directory for your own modules. I can, but that is almost certainly not the standard way to develop a module. I see nothing in sys.path that I have write permissions to. Is altering my PYTHONPATH the normal way to develop (under the assumption that later users will install in their conventional python search path)? From fredrik at pythonware.com Wed Jul 23 16:13:32 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 22:13:32 +0200 Subject: Doubt In-Reply-To: References: Message-ID: ???????? wrote: > I am a Perl programmer new to Python. I have a small doubt. I suspect you mean "question", not "doubt". It's not quite the same thing. > How to convert the perl notation > $a = ""; expression in Python ? > > How to represent the loop > for ($a = $b; $a<=$c;$a++){ > } in Python Start here: http://www.lucasmanual.com/mywiki/PerlPythonPhrasebook and then read either of these (preferably both): http://www.swaroopch.com/byteofpython/ http://docs.python.org/tut/ From ldo at geek-central.gen.new_zealand Sun Jul 27 23:55:10 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 28 Jul 2008 15:55:10 +1200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> <6385b0a8-f7f3-4dc3-91be-e6f158ffb439@a1g2000hsb.googlegroups.com> Message-ID: In message <6385b0a8-f7f3-4dc3-91be-e6f158ffb439 at a1g2000hsb.googlegroups.com>, s0suk3 at gmail.com wrote: > On Jul 26, 6:47 pm, Lawrence D'Oliveiro central.gen.new_zealand> wrote: >> In message >> <024ace13-f72f-4093-bcc9-f8a339c32... at v1g2000pra.googlegroups.com>, >> >> s0s... at gmail.com wrote: >> > On Jul 24, 5:01 am, Lawrence D'Oliveiro > > central.gen.new_zealand> wrote: >> >> >> In message >> >> <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, >> >> Jordan wrote: >> >> >> > Except when it comes to Classes. I added some classes to code that >> >> > had previously just been functions, and you know what I did - or >> >> > rather, forgot to do? Put in the 'self'. In front of some of the >> >> > variable accesses, but more noticably, at the start of *every single >> >> > method argument list.* >> >> >> The reason is quite simple. Python is not truly an "object-oriented" >> >> language. It's sufficiently close to fool those accustomed to OO ways >> >> of doing things, but it doesn't force you to do things that way. You >> >> still have the choice. An implicit "self" would take away that choice. >> >> > By that logic, C++ is not OO. >> >> Yes it is, because it has "this". > > You mean the keyword "this"? It's just a feature. How does that make a > difference on being or not being OO? Because it was one of the things the OP was complaining about (see above). From hv at tbz-pariv.de Wed Jul 2 07:08:40 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Wed, 02 Jul 2008 13:08:40 +0200 Subject: Scripting SAP GUI (Windows) Message-ID: <6d15tpFaec4U1@mid.individual.net> Hi, I need to script SAP GUI running on MS-Windows: Open SAP GUI window, if it is not already open, and then batch input some keystrokes. The following solutions were found by google: - autohotkey: not preferred, since it has an own programming language. This will slow down development. - pyHook - user pywin32 and SetWindowsHookEx I develop with python since seven years, but only on linux. Any hints? -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From workitharder at gmail.com Sun Jul 13 20:39:01 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 13 Jul 2008 17:39:01 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> Message-ID: <792048c1-5e18-4a2c-925d-a1c932d18a91@j22g2000hsf.googlegroups.com> On Jul 13, 4:21 pm, Kless wrote: > I need a dictionary where get the result from a 'key' (on left), but > also from a 'value' (on right), how to get it? > > I know that dictionaries aren't bidirectional, but is there any way > without use two dictionaries? > > Thanks in advance! You need to use two dictionaries. Here's a class that someone's written that wraps it up into a single dict-like object for you: http://www.faqts.com/knowledge_base/view.phtml/aid/4376 From tn.pablo at gmail.com Fri Jul 18 09:42:07 2008 From: tn.pablo at gmail.com (ptn) Date: Fri, 18 Jul 2008 06:42:07 -0700 (PDT) Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> <3db7c643-56ca-4d6e-99eb-16176e1a2e88@d19g2000prm.googlegroups.com> Message-ID: <7b2d0e3b-0ee4-4f1b-90d5-90eae9f258a0@u6g2000prc.googlegroups.com> On Jul 18, 5:40?am, SUBHABRATA wrote: > Hi Peter,Peter Otten wrote: > > SUBHABRATA wrote: > > > > Thanx Peter, > > > I would change my variables next time I would post. > > > No, you should use meaningful variable names when you write your code no > > matter whether you plan to post it or not. > > Good You are teaching me something good in life. Thanx. > > > > And obviously, > > > thanx for your solution. I am reviewing it, I was also trying out some > > > solutions. > > > You misunderstood. I did not modify your code other than changing the > > variable names. My hope was that with this modification any errors sprang > > to you eye... > > I was seeing that. > I am almost near the solution. You can also try some hands if you > feel. > Best Regards, > Subhabrata. > > > > > Peter > > A couple more things on variable naming and coding style: - You used "a{digit}" to name variables of different types (a4 was an int, a2 was a list and the rest were strings). Remember C, where i, j, k are indices, p, q, r are pointers, s, t are strings and x, y, z are integers. For unimportant variables, you can skip long descriptive names, so long you don't use a confusing one. - You violated your own naming conventions. Why did you choose to use s to name that last string? Use descriptive names and stick to your own style. - You use whitespace weirdly (like in a4>-1 or a4=a3.find). Try reading PEP8 (http://www.python.org/dev/peps/pep-0008/), the Style Guide for Python Code. As for your code, you need to find where it is that missing_word and first_char are being updated, and assign to s before that happens. From Abhishek_Asthana01 at infosys.com Thu Jul 3 05:46:08 2008 From: Abhishek_Asthana01 at infosys.com (Abhishek Asthana) Date: Thu, 3 Jul 2008 15:16:08 +0530 Subject: multithreading in python ??? Message-ID: <674A912AA405814397CED58601AC8E251554964241@BLRKECMBX05.ad.infosys.com> Hi all , I have large set of data computation and I want to break it into small batches and assign it to different threads .I am implementing it in python only. Kindly help what all libraries should I refer to implement the multithreading in python. Thanks , Abhishek **************** CAUTION - Disclaimer ***************** This e-mail contains PRIVILEGED AND CONFIDENTIAL INFORMATION intended solely for the use of the addressee(s). If you are not the intended recipient, please notify the sender by e-mail and delete the original message. Further, you are not to copy, disclose, or distribute this e-mail or its contents to any other person and any such actions are unlawful. This e-mail may contain viruses. Infosys has taken every reasonable precaution to minimize this risk, but is not liable for any damage you may sustain as a result of any virus in this e-mail. You should carry out your own virus checks before opening the e-mail or attachment. Infosys reserves the right to monitor and review the content of all messages sent to or from this e-mail address. Messages sent to or from this e-mail address may be stored on the Infosys e-mail system. ***INFOSYS******** End of Disclaimer ********INFOSYS*** -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 10 06:35:57 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 10 Jul 2008 12:35:57 +0200 Subject: FOSS projects exhibiting clean/good OOP? In-Reply-To: <3bd416cf-6989-44fb-961d-658032231356@m73g2000hsh.googlegroups.com> References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> <3bd416cf-6989-44fb-961d-658032231356@m73g2000hsh.googlegroups.com> Message-ID: <4875e5d8$0$16991$426a34cc@news.free.fr> Phillip B Oldham a ?crit : > Thanks all - lots to go through there! :D > > I'd heard previously that Trac was a nice example, or rather its core > was, but I'd also heard that there were lots of problems with it and > that they were redeveloping it from scratch? Trac's plugin system is interesting, yes, but there were indeed quite a couple gotchas last time I used it (about 2 years ago). From asmodai at in-nomine.org Fri Jul 11 05:54:56 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 11 Jul 2008 11:54:56 +0200 Subject: recommended gcc versions for python2.5 compilation on Solaris sparc/x86, AIX, Linux In-Reply-To: <9347F3EEF61FC542A7D9211A42CD7E6387E071@dolphin.sg.murex.com> References: <9347F3EEF61FC542A7D9211A42CD7E6387E071@dolphin.sg.murex.com> Message-ID: <20080711095456.GW68329@nexus.in-nomine.org> -On [20080711 06:18], YIN Ming (Ming.YIN at murex.com) wrote: >2. use new version of gcc (rather than odd version) See http://www.in-nomine.org/2008/04/11/python-26a2-execution-times-with-various-compilers/ that I wrote a while ago. Basically for Python GCC 3.4.6 outperformed the newer GCCs. So do not automatically assume that newer is better. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B The weak can never forgive. Forgiveness is the attribute of the strong... From mal at egenix.com Thu Jul 17 18:01:57 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 18 Jul 2008 00:01:57 +0200 Subject: Converting from local -> UTC In-Reply-To: <44GdnYNOD4ZCM-LVnZ2dnUVZ_gydnZ2d@earthlink.com> References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> <41d4ffc7-7fd5-4202-92ea-132c7d4f5cd4@s50g2000hsb.googlegroups.com> <44GdnYNOD4ZCM-LVnZ2dnUVZ_gydnZ2d@earthlink.com> Message-ID: <487FC155.30604@egenix.com> On 2008-07-17 22:43, Dennis Lee Bieber wrote: > On Thu, 17 Jul 2008 19:55:44 +0200, "M.-A. Lemburg" > declaimed the following in comp.lang.python: > > >> Use binding parameters and it should work: >> >> query = "INSERT INTO image VALUES(%d, %d, %s, '%s')" > > If this is MySQLdb interface: > > query = "INSERT INTO image VALUES(%s, %s, %s, '%s')" > > ... only %s is valid; all values have been converted to escaped/quoted > string before getting to the substitution. Right. I forgot to replace the %d's with %s's. The line should read: query = "INSERT INTO image VALUES(%s, %s, %s, %s)" -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 17 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From stefan_ml at behnel.de Thu Jul 3 01:02:27 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 03 Jul 2008 07:02:27 +0200 Subject: ANN: XML builder for Python In-Reply-To: <486C5CA1.3080105@behnel.de> References: <486C5CA1.3080105@behnel.de> Message-ID: <486C5D63.5030407@behnel.de> Stefan Behnel wrote: > Jonas Galvez wrote: >> Not sure if it's been done before, but still... > > Obviously ;) > > http://codespeak.net/lxml/tutorial.html#the-e-factory > > ... and tons of other tools that generate XML, check PyPI. Although it might be the first time I see the with statement "misused" for this. :) Stefan From fred.haab at gmail.com Tue Jul 29 23:43:55 2008 From: fred.haab at gmail.com (fred.haab) Date: Tue, 29 Jul 2008 20:43:55 -0700 (PDT) Subject: Is it allowed to use function results as default arguments ? References: Message-ID: Well, others have answered the question, but I thought I'd throw in that it would be more pythonic to do something like: def Get_Relative_Path(target, base = None): if base is None: base = os.curdir ... From ebgssth at gmail.com Wed Jul 9 19:16:34 2008 From: ebgssth at gmail.com (js) Date: Thu, 10 Jul 2008 08:16:34 +0900 Subject: Py_BuildValue for char **? Message-ID: Hi, I'm writing a wrapper module of C API. To make a C struct data avaiable to Python, I need to map C struct into a PyObject. I'm thinking that I use a tuple or dict to represent the struct but a problem is one of the members of the struct is char **, which is not supported by Py_BuildValue. Is there any idiomatic way of mapping char ** to Python? Any suggestions, pointers would be appreciated. From jaing08 at gmail.com Wed Jul 2 23:05:06 2008 From: jaing08 at gmail.com (Devil) Date: Thu, 3 Jul 2008 08:35:06 +0530 Subject: Need help on Python File write operation..... Message-ID: <7a2a9cc40807022005h2218c55fxb2fa3bf801281d9a@mail.gmail.com> Hi, I am stuck at below mention point. I am not able to find any way of doing it in python. I have google enough to find any sample code but unsuccessful. Plz help. I am trying to write a file of size (user specified size) so that it will pops(remove) the oldest line written (data item) to make room for newest line (data item ) when max size is reached. I also want to see data update while program running (some thing like flush() because file size some time is very huge... so need to check the data copying to file) Data written in file is a string (array of data of variable length ) ended by '\n'. Do help me as it is very urgent for me. Thanks in advance. Regards, jaing -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Sat Jul 19 11:39:00 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Jul 2008 15:39:00 GMT Subject: Question References: Message-ID: <6eeg4kF6k7g3U1@mid.uni-berlin.de> On Sat, 19 Jul 2008 10:27:28 +0100, perl_wizard wrote: > Why is Perl so much better than python? You are so much better than python? Ciao, Marc 'BlackJack' Rintsch From musiccomposition at gmail.com Tue Jul 22 23:06:10 2008 From: musiccomposition at gmail.com (Benjamin) Date: Tue, 22 Jul 2008 20:06:10 -0700 (PDT) Subject: Is this a valid use of 'import'? References: Message-ID: On Jul 22, 12:26?pm, Terry Reedy wrote: > > *Python2 has a built-in reload function, but in 3.0 it is removed > because it almost never did what people wanted or expected and thus lead > to surprising bugs. ?You can delete a module from sys.modules and > re-import it, but the module object and those it created will not > disappear as long as there are other references to them. It's not gone. It's been moved to imp. From phil at riverbankcomputing.com Sat Jul 5 12:09:28 2008 From: phil at riverbankcomputing.com (Phil Thompson) Date: Sat, 05 Jul 2008 17:09:28 +0100 Subject: Python with Ecmascript In-Reply-To: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> Message-ID: On Sat, 5 Jul 2008 06:28:42 -0700 (PDT), "jiri.zahradil at gmail.com" wrote: > Hello, > > for my Python application (Windows platform) to be standards > compliant, I need to embbed Ecmascript(Javascript) interpreter - I > need to execute plugins written in this language. Which engine is > suitable for Python, I have found bunch of them. Any recomendations > are welcome. > > To be more specific, I think that plugins will be pretty simple, they > will be used to manipulate my class-based datamodel, no special > libraries dependencies ... therefore I prefer some rather simple > solution ... PyQt includes a Javascript interpreter. You can expose Python objects and properties as Javascript objects and properties. Phil From stefan_ml at behnel.de Thu Jul 31 13:59:39 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 31 Jul 2008 19:59:39 +0200 Subject: Python parsing iTunes XML/COM In-Reply-To: <5f3a28f9-5918-4d5a-857b-3fbe2af3b196@u12g2000prd.googlegroups.com> References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> <4ae2518f-10c0-49f2-b5d7-a75993b0a67d@z66g2000hsc.googlegroups.com> <48915761$0$11736$9b4e6d93@newsspool1.arcor-online.net> <5f3a28f9-5918-4d5a-857b-3fbe2af3b196@u12g2000prd.googlegroups.com> Message-ID: <4891fd8a$0$20708$9b4e6d93@newsspool4.arcor-online.net> william tanksley wrote: > I didn't > pass a string. I passed a file. It didn't error out; instead, it > produced bytestring-encoded output (not Unicode). >From my experience (and from the source code I have seen so far), ElementTree does not return UTF-8 encoded strings at the API level. Can you produce any evidence for your claims? Some code and an XML file that together produce the result you are talking about? From what you have written so far, it seems far more likely to me that your code is messed up than that you found a bug in ElementTree. Stefan From bgeddy at home.havin.a.break Thu Jul 17 20:16:17 2008 From: bgeddy at home.havin.a.break (bgeddy) Date: Fri, 18 Jul 2008 01:16:17 +0100 Subject: storing references instead of copies in a dictionary In-Reply-To: References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: castironpi wrote: > On Jul 17, 10:05 am, mk wrote: >>> def f2(arg): >>> return "f2 "+arg >>> def f1(arg): >>> return "f1 "+arg >>> a={"1":"f1","2":"f2"} >>> print [eval(x[1])(x[0]) for x in a.items()] >>> def f2(arg): >>> return "New f2 "+arg >>> print [eval(x[1])(x[0]) for x in a.items()] >> Neat trick, if probably dangerous in some circumstances. Anyway, thanks, >> I didn't think of that. >> >>> Don't know if this is any use to you.. >> At least I learned something. :-) > > You want consistent access to a changing variable. Wrap it in an > object: > >>>> a= Blank( ) >>>> a.ref= 'X' >>>> a.ref > 'X' >>>> b= a >>>> b.ref > 'X' >>>> a.ref= 'Y' >>>> b.ref > 'Y' > My "old fashioned" programing paradigms think of this in terms of "pointers", a throw back to my schooling in 'C'. I find this general form of problem to be common across languages and in some ways hard to express in python. The whole idea of labels bound to objects is quite alien to traditional terminology. I find one of the main attractions of python is this new mindset that the language makes you adopt - a different set of tools are at hand for the old school programmer. castironpi - please give an example of what you are thinking as I find this interesting. preferably post some brief example code. From mal at egenix.com Fri Jul 25 06:35:10 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 25 Jul 2008 12:35:10 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: <1216966424.4685.1265275245@webmail.messagingengine.com> References: <1216966424.4685.1265275245@webmail.messagingengine.com> Message-ID: <4889AC5E.8090909@egenix.com> On 2008-07-25 08:13, python at bdurham.com wrote: > Background: I'm going to be processing some raw transaction logs that > are 30G in size. As part of this processing I may need to create some > very large dictionary structures. I will be running my scripts on a > version of Windows 2003 Server Enterprise Edition that supports 16G of > RAM. Yes, I could use a database in place of dictionaries, but I'm > looking for maximum performance. > > The following page lists two 64 bit versions of Python for Windows: > http://www.python.org/download/releases/2.5.2/ > > For Win64-Itanium users: python-2.5.2.ia64.msi > For Win64-AMD64 users: python-2.5.2.amd64.msi > > 1. It looks like the 64 bit versions of Python for Windows are CPU > vendor specific, eg. it doesn't look like there's a single, universal > executable for Windows 64 bit platforms. Is this true? Yes. But then Intel Itanium is being phased out anyway and the AMD64 build works on both Intel and AMD processors. > 2. Are there limitations to the using the 64 bit versions of Python? I > seem to remember reading that many 3rd party modules (especially Windows > OS specific modules) may not be compatible with the 64 bit versions of > Python for Windows. True. The extensions usually need to be recompiled and possibly also updated to support 64-bit architectures. The win32 tools are available on 64-bit Windows - if that's what you mean with "Windows OS specific modules". > 3. If I wanted to run a 64 bit version of Python under Linux, would I > need to recompile from source on 64 bit version of Linux or do 64 bit > versions of Linux automatically ship with 64 bit versions of Python? > (Any recommendations on a flavor of 64 bit of Linux for the Intel > architecture would be appreciated) Yes, 64-bit Linux versions ship with 64-bit builds of Python. Any recent Linux distro should work just fine. > 4. Is there a stable version of IronPython compiled under a 64 bit > version of .NET? Anyone have experience with such a beast? Can't comment on that one. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 25 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From comp.ogz at gmail.com Thu Jul 3 00:58:59 2008 From: comp.ogz at gmail.com (Oguz Yarimtepe) Date: Thu, 3 Jul 2008 07:58:59 +0300 Subject: detection of unplugged cable In-Reply-To: References: Message-ID: <20831c740807022158l38648a61l4966d11fae20297d@mail.gmail.com> On Thu, Jul 3, 2008 at 7:33 AM, Dennis Lee Bieber wrote: > On Wed, 2 Jul 2008 13:32:59 +0300, "Oguz Yarimtepe" > declaimed the following in comp.lang.python: > I'd be willing to bet that S-video outputs do NOT have feed-back to > the video driver as they only carry chroma and luminance signals. And > what is DMI? a low-resolution HDMI or a typo for DVI? > It is a DVI output. sorry for the typo. > For those connectors that do carry feedback, it is no doubt > something buried deep in the guts of the OS and video card drivers. > > Also, consider that, for example, my monitor has four inputs: VGA, > DVI, S-Video, and I believe plain old composite. I can have four devices > (two computers, a dvd-player, and a VCR, say) and switch between them. > What would your program do if the detected cable is not the one that is > displayed at the time? > -- It is a display switcher working in a simple way. I couldn't manage to clone my dvi output, i had to switch of lvds and set the output to dvi. When the cable is unplugged i planned to switch the lvds output on. -- O?uz Yar?mtepe From doug.farrell at gmail.com Wed Jul 9 11:52:04 2008 From: doug.farrell at gmail.com (writeson) Date: Wed, 9 Jul 2008 08:52:04 -0700 (PDT) Subject: Determining when a file has finished copying Message-ID: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> Hi all, I'm writing some code that monitors a directory for the appearance of files from a workflow. When those files appear I write a command file to a device that tells the device how to process the file. The appearance of the command file triggers the device to grab the original file. My problem is I don't want to write the command file to the device until the original file from the workflow has been copied completely. Since these files are large, my program has a good chance of scanning the directory while they are mid-copy, so I need to determine which files are finished being copied and which are still mid-copy. I haven't seen anything on Google talking about this, and I don't see an obvious way of doing this using the os.stat() method on the filepath. Anyone have any ideas about how I might accomplish this? Thanks in advance! Doug From sjmachin at lexicon.net Sun Jul 20 17:38:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 Jul 2008 14:38:28 -0700 (PDT) Subject: round function error??? References: <2da2f5f1-7ff2-46d7-a768-f0817e414615@f36g2000hsa.googlegroups.com> Message-ID: <4f1c4b26-ac4c-4079-adc3-3b978263ff22@b2g2000prf.googlegroups.com> On Jul 21, 12:56 am, Mark Dickinson wrote: > On Jul 19, 12:20 am, John Machin wrote: > > > On Jul 19, 8:05 am, Mark Dickinson wrote: > > > for more information. But I'm guessing that you're > > > questioning the fact that a value that's apparently > > > *less* than 3499.35 is rounded up to 3499.4, rather > > > than down to 3499.3. ? > > > "apparently" being the operative word. > > Well, it's not just an apparent problem: the closest > floating-point number to 3499.35 really *is* less than > 3499.35. I'm well aware of that. My point is that I hope that you weren't planning on changing that behaviour in an unannounced unstaged manner. From mrkafk at gmail.com Tue Jul 8 18:06:21 2008 From: mrkafk at gmail.com (mk) Date: Wed, 09 Jul 2008 00:06:21 +0200 Subject: (silly?) speed comparisons Message-ID: Out of curiosity I decided to make some speed comparisons of the same algorithm in Python and C++. Moving slices of lists of strings around seemed like a good test case. Python code: def move_slice(list_arg, start, stop, dest): frag = list_arg[start:stop] if dest > stop: idx = dest - (stop - start) else: idx = dest del list_arg[start:stop] list_arg[idx:idx] = frag return list_arg b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] >>> import timeit >>> t = timeit.Timer("move_slice.move_slice(move_slice.b, 4, 6, 7)", "import move_slice") >>> t.timeit() 3.879252810063849 (Python 2.5, Windows) Implementing the same algorithm in C++: #include #include #include using namespace std; vector move_slice(vector vec, int start, int stop, int dest) { int idx = stop - start; vector frag; // copy a fragment of vector for (idx = start; idx < stop; idx++) frag.push_back(vec.at(idx)); if( dest > stop) idx = dest - (stop - start); else idx = dest; // delete the corresponding fragment of orig vector vec.erase( vec.begin() + start, vec.begin() + stop); // insert the frag in proper position vec.insert( vec.begin() + idx, frag.begin(), frag.end()); return vec; } int main(int argc, char* argv) { vector slice; string u = "abcdefghij"; int pos; for (pos = 0; pos < u.length(); pos++) slice.push_back(u.substr(pos,1)); int i; for (i = 0; i<1000000; i++) move_slice(slice, 4, 6, 7); } Now this is my first take at vectors in C++, so it's entirely possible that an experienced coder would implement it in more efficient way. Still, vectors of strings seemed like a fair choice - after all, Python version is operating on similarly versatile objects. But I was still rather surprised to see that C++ version took 15% longer to execute! (vector, 4, 6, 7) $ time slice real 0m4.478s user 0m0.015s sys 0m0.031s Compiler: MinGW32/gcc 3.4.5, with -O2 optimization (not cygwin's gcc, which for some reason seems to produce sluggish code). When I changed moving the slice closer to the end of the list / vector, Python version executed even faster: >>> t = timeit.Timer("move_slice.move_slice(move_slice.b, 6, 7, 7)", "import move_slice") >>> t.timeit() 1.609766883779912 C++: (vector, 6, 7, 7) $ time slice.exe real 0m3.786s user 0m0.015s sys 0m0.015s Now C++ version took over twice the time to execute in comparison to Python time! Am I comparing apples to oranges? Should the implementations be different? Or does the MinGW compiler simply suck? Note: it appears that speed of Python lists falls down quickly the closer to the list beginning one deletes or inserts elements. C++ vectors do not seem to be as heavily position-dependent. From maestroQC at gmail.com Tue Jul 15 15:14:19 2008 From: maestroQC at gmail.com (maestroQC) Date: Tue, 15 Jul 2008 12:14:19 -0700 (PDT) Subject: MySQL Insert References: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> Message-ID: <41160444-1483-4aba-b1a5-2ceb4e343ee0@l42g2000hsc.googlegroups.com> Thanks for the information. However I must stick to decimal since I'm dealing with monetary values. I loose the decimals with int and float has only supports one decimal place. I tried as you suggested to use the %s instead of the %d to no avail. From ddasilva at umd.edu Wed Jul 30 19:36:21 2008 From: ddasilva at umd.edu (Daniel da Silva) Date: Wed, 30 Jul 2008 19:36:21 -0400 Subject: How can I check nbr of cores of computer? In-Reply-To: <8d9ec3dd0807301635g7997da2bxed2a022ebbec59aa@mail.gmail.com> References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> <4890acd6$0$17215$742ec2ed@news.sonic.net> <5504f9ac0807301116i3907b46l383ed0dd683edfd1@mail.gmail.com> <8d9ec3dd0807301635g7997da2bxed2a022ebbec59aa@mail.gmail.com> Message-ID: <8d9ec3dd0807301636x562bc20fy98ac053d2e8d46df@mail.gmail.com> Single line using /proc/cpuinfo: numprocs = [ int(line.strip()[-1]) for line in open('/proc/cpuinfo', 'r') if \ line.startswith('processor') ][-1] + 1 On Wed, Jul 30, 2008 at 2:16 PM, Dan Upton wrote: > > On Wed, Jul 30, 2008 at 2:22 PM, John Nagle wrote: > > defn noob wrote: > >> > >> How can I check how many cores my computer has? > >> Is it possible to do this in a Python-app? > > > > Why do you care? Python can't use more than one of them at > > a time anyway. > > Per Python process, but you might fork multiple processes and want to > know how many cores there are to know how many to fork, and which > cores to pin them to. (I don't know if there's a direct way in Python > to force it to a certain core, so I instead just wrote an extension to > interface with sched_setaffinity on Linux.) > > On Linux, an almost assuredly non-ideal way to find out the number of > cores is to read /proc/cpuinfo and look for the highest-numbered > "processor: " line (and add 1). > -- > http://mail.python.org/mailman/listinfo/python-list From duncan-news at grisby.org Mon Jul 14 04:42:48 2008 From: duncan-news at grisby.org (Duncan Grisby) Date: Mon, 14 Jul 2008 08:42:48 GMT Subject: Does omniORBpy 3.2 supports DII? References: Message-ID: In article , Ilan wrote: >My apologies if this is not the correct forum for thses quiestions, by >I'm rather new to python+CORBA > >Has anyone used omniORBpy as CORBA implementation? are there any >drawbacks? As omniORBpy's author, I'm biased, so I'll let other people answer that... >Does omniORBpy 3.2 supports the Dynamic Invocation Interface? No, it doesn't. You can use Python's normal dynamic features to build dynamic requests, though. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From rparimi at gmail.com Tue Jul 15 10:15:54 2008 From: rparimi at gmail.com (rparimi at gmail.com) Date: Tue, 15 Jul 2008 07:15:54 -0700 (PDT) Subject: fork after creating temporary file using NamedTemporaryFile Message-ID: <0435315d-7b7d-4587-bc8c-000e3f2644a2@z72g2000hsb.googlegroups.com> Hello pythoners, When I create temporary file using the tempfile module, and forkI) later on in my program, I always see errors when the program exits. Is this because the child process deletes temp file? Here's a stripped down version of my script that exhibits this problem: #!/usr/bin/python import os import tempfile import sys cmd = [] cmd.append('/bin/ls') cmd.append('-l') cmd.append('/tmp') foo = tempfile.NamedTemporaryFile(mode='w+b') pid = os.fork() if pid: print 'I am parent' else: print 'I am child' sys.exit(0) $ python sub.py I am child I am parent Exception exceptions.OSError: (2, 'No such file or directory', '/tmp/ tmp-mZTPq') in ', mode 'w+b' at 0xb7d2a578>> ignored How can these warnings be avoided? I tried to catch this exception using try/except but it didn't work. thanks! From elessar at nienna.org Tue Jul 29 11:12:29 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Tue, 29 Jul 2008 09:12:29 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: <488F335D.8050901@nienna.org> Carl Banks wrote: > On Jul 28, 8:15 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: >>> On Jul 28, 10:00 am, Steven D'Aprano >> cybersource.com.au> wrote: >>>> Cutting to the crux of the discussion... >>>> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: >>>>> I want something where "if x" will do but a simple explicit test >>>>> won't. >>>> Explicit tests aren't simple unless you know what type x is. If x could >>>> be of any type, you can't write a simple test. Does x have a length? Is >>>> it a number? Maybe it's a fixed-length circular length, and the length >>>> is non-zero even when it's empty? Who knows? How many cases do you need >>>> to consider? >>> Use case, please. I'm asking for code, not arguments. Please give me a >>> piece of code where you can write "if x" that works but a simple >>> explicit test won't. >> I gave you a piece of code, actual code from one of my own projects. If >> you wouldn't accept that evidence then, why would you accept it now? > > I would accept as "evidence" something that satisfies my criteria, > which your example did not: it could have easily (and more robustly) > been written with a simple explicit test. I am looking for one that > can't. > > You keep bringing up this notion of "more complex with no benefit", > which I'm simply not interested in talking about that at this time, > and I won't respond to any of your points. I am seeking the answer to > one question: whether "if x" can usefully do something a simple > explicit test can't. Everyone already knows that "if x" requires > fewer keystrokes and parses to fewer nodes. > > > Carl Banks > -- > http://mail.python.org/mailman/listinfo/python-list > My use case involves a DAG of filters that pass data (of a variety of types--filters just pass on data types they don't understand) between them. I can also drop out of the filter chain at any point, using critera determined by the filters. These criteria, you guessed it, are bound to __nonzero__ in the filter and I determine whether or not to continue through the graph using "if x". You can't code explicit tests if you don't know what the tests even are beforehand. Also, I wanted to support builtins (ints and lists in particular) because they can be meaningful inputs to filters. Finally, as I add more filters and data types, I don't want to go back and mess with the code that decides whether or not to break out of the graph. -Matt From basti.wiesner at gmx.net Tue Jul 1 16:47:18 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Tue, 01 Jul 2008 22:47:18 +0200 Subject: raw_input into Tkinter ? References: <634e2b50-45ba-4b93-89b4-0afd739adaf3@z66g2000hsc.googlegroups.com> <9571b5b0-7b18-4045-a912-6635a6e86500@l42g2000hsc.googlegroups.com> Message-ID: Matimus : > On Jun 30, 9:55?am, jamitwi... at gmail.com wrote: >> Is there any way to type into a Tkinter frame window? >> I want to use raw_input() within a Tkinter frame. > > `raw_input(prompt)` just calls `sys.stdout.write(prompt)` and returns > `sys.stdin.readline()`. It does more like providing readline support, if readline is loaded. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From castironpi at gmail.com Wed Jul 23 12:42:29 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 23 Jul 2008 09:42:29 -0700 (PDT) Subject: Python Written in C? References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> <6eosgtF7u58sU1@mid.uni-berlin.de> Message-ID: <537c58c3-d74c-41dd-8571-26cfbb415178@34g2000hsh.googlegroups.com> On Jul 23, 9:11?am, Marc 'BlackJack' Rintsch wrote: > On Wed, 23 Jul 2008 14:10:22 +0200, mk wrote: > > Marc 'BlackJack' Rintsch wrote: > >> I can't even remember when I deleted something from a list in the past. > > > Still, doesn't that strike you as.. workaround? > > No, I find it actually safer; I don't have to care where modifications of > the list might be seen elsewhere in the program. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch a[:]= newlist and a= newlist have two completely different effects, and one is just as safe as 'del'. Besides, del isn't safe to be seen elsewhere in the program in other threads, if they aren't locking the GIL. From Lie.1296 at gmail.com Mon Jul 21 17:47:31 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 21 Jul 2008 14:47:31 -0700 (PDT) Subject: Change PC to Win or Windows References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> <82873ccd-9667-4dfa-9ec4-a9ac7c672aa7@w1g2000prk.googlegroups.com> Message-ID: <0f3272c1-b1a7-4aef-9e4a-0f03af823a2d@z11g2000prl.googlegroups.com> On Mon, 2008-07-21 at 16:45 -0400, Derek Martin wrote: > On Mon, Jul 21, 2008 at 12:32:00PM -0700, Lie wrote: > > > The term "PC" is commonly used in English, in the United States > > > and other English speaking countries, to mean a computer running > > > Microsoft Windows. > > > > As far as I am aware, they're like that because most people aren't > > even aware that there are other OSes than Microsoft Windows. > > You are missing two points. > > The first one: It doesn't matter what the reasons are for the > terminology to be common. It only matters that it IS common. It is; > and it is therefore "correct" in the sense that it conveys a meaning > to the overwhelming majority of English speakers, which is the > intended one. > True, it doesn't actually matters, but it is a proof that it is technically incorrect to apply PC JUST to Windows-based PC. It is arguable whether the term should only be exclusively to IBM-PC or whether the term should be expanded to include its clones. But I'm against on using it just to refer Windows-based PC exclusively, since it is neither Microsoft's marketing term nor a literal meaning conveyed in the term. > As for the question of whether or not it is appropriate to refer to > Windows installations as "PC", it's as simple as that. It is, by > definition (via common usage). That is what this thread is about. > Common usage isn't always correct. For example, a physicist would not use weight when he meant mass. Although in daily use he might not care much, but in technical environment doing so would embarrass him. In this analogy, I consider download page for a software source code to be a technical area. > The reason why the world hasn't evolved to the two predictable cases > > ("all kinds of microcomputers" or "IBM-PC and clones"), is what I'll > > explain below. > > Your explanation is irrelevant to the argument of whether or not the > term PC is an inappropriate term to describe a Windows installation, > which is what this thread is about. That is the premise put forth by > the OP, and that is the notion to which I am responding. It simply is > not wrong or inappropriate in any sense; it is in fact correct, > regardless of how the meaning or usage resulted, and regardless of any > ADDITIONAL meanings the term may have. > > For what it's worth, your explanation is also WRONG; the term PC > began to be popularly used in the United States to describe > Intel-based Microsoft machines when there was a proliferation of other > kinds of personal computers available to consumers. When it was first > used this way, the IBM PC was *NOT* the most popular personal computer... > the Commodore 64 was. > True, but PC is IBM's marketing term, thus it originally belongs to them. Nevertheless, it is NOT Window's marketing term and the literal meaning of Personal Computer is in no way means Windows-based computers ONLY. > It dates from a time when the Commodore VIC-20 > and C64, Atari 400 and 800, Timex Sinclair, and other computers were > all very popluar home machines. But they aren't called PC, why? Because IBM hasn't invented the term. Nowadays, they might be called as PC or not depending on which side are you in: "PC as IBM-PC" or "PC as personal computer" (note the lower case) > The term probably originated primarily because IBM chose to name their > computer the IBM PC, and because of Americans' predeliction to > abbreviate everything that's more than 2 syllables. ;-) > > > > It wasn't something that Apple started; it's been used this way > > > in increasingly common usage for at least 20 years, although > > > exactly what combination of hardware and software was being > > > refered to as a "PC" has evolved over that timeframe. > > > > Apple popularizes the term by explicit marketing, > > And here is the last point you are missing: Apple does no such > thing. They did, by using the term PC to refer to other computers. IF they have used the term "Regular PC", noone would have complained, it's just like an apple farmer advertising his "Super Apples" and calls other apples "Regular Apples", there would be nothing wrong about it. But there is this specific apple farmer who advertised his apple as "Orange" and calls other apples as "Apples", which makes a problem since "Orange" is just a different variants of apple, and is still an apple. This kind of advertising Apple (the computer company) used is misleading, since it implied that their PC is not a PC. > They are only using a term in a way that has previously been > popularized by the computer industry as a whole, and its market (i.e. > consumers, predominantly American consumers historically) for > *DECADES*. > If I'm not mistaken, their ad campaign mentioning PCs is > less than 10 years old (though I can't quickly find any references as > to the date). The popularization of the term PC to refer to > Intel-compatible machines running Microsoft OSes PREDATES APPLE'S AD > CAMPAIGN BY OVER 10 YEARS. When did I say that Apple was the first one to start the term's misuse? Apple's is only making the term's misuse more widespread, nevertheless they might be the largest computer company that tried to _actively_ spread its misuse by persistently using the term in their ads in that manner. But even without Apple, yes, it is true that the misuse would still get widespread, simply because of Microsoft's dominance. > Therefore none of your points are valid or relevant, as to the > question of whether the usage of the term "PC" to describe windows > builds of Python is appropriate. > Because you are missing all the points. > Can we return to the subject of Python now? yes, in short, don't use PCBuild to refer Windows-only build. PCBuild should contain a universal build that is compatible with all platforms a PC is usually based on (i.e. it shouldn't exist except if such thing is possible). From socyl at 987jk.com.invalid Wed Jul 30 16:45:57 2008 From: socyl at 987jk.com.invalid (kj) Date: Wed, 30 Jul 2008 20:45:57 +0000 (UTC) Subject: how to split text into lines? References: Message-ID: In kj writes: >In Perl, one can break a chunk of text into an array of lines while >preserving the trailing line-termination sequence in each line, if >any, by splitting the text on the regular expression /^/: > DB<1> x split(/^/, "foo\nbar\nbaz") >0 'foo >' >1 'bar >' >2 'baz' >But nothing like this seems to work in Python: >>>> re.split('^', 'foo\nbar\nbaz') >['foo\nbar\nbaz'] >(One gets the same result if one adds the re.MULTILINE flag to the >re.split call.) >What's the Python idiom for splitting text into lines, preserving >the end-of-line sequence in each line? Sorry, I should have googled this first. I just found splitlines()... Still, for my own edification, is there a way to achieve the same effect using re.split? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From circularfunc at yahoo.se Wed Jul 2 17:11:52 2008 From: circularfunc at yahoo.se (defn noob) Date: Wed, 2 Jul 2008 14:11:52 -0700 (PDT) Subject: Run interpreter in emacs? References: <6d28ccFftk4U1@mid.uni-berlin.de> Message-ID: <9817b8df-a6bb-4392-86a9-66c2807bec31@z72g2000hsb.googlegroups.com> thanks but i dont quite understand the load-path, add to the load path. the loadpath has a lot of variables. so where i should i place the python-mode folder and should i then add that directory to the loadpath? From deets at nospam.web.de Mon Jul 28 05:41:20 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 11:41:20 +0200 Subject: os.symlink() References: Message-ID: <6f5ik2F9t9b5U1@mid.uni-berlin.de> Nikolaus Rath wrote: > Hello, > >>From `pydoc os`: > > symlink(...) > symlink(src, dst) > > Create a symbolic link pointing to src named dst. > > > Is there any reason why this is so deliberately confusing? Why is the > target of the symlink, the think where it points *to*, called the > `src`? It seems to me that the names of the parameters should be > reversed. I used the command the other day, and didn't feel the slightest confusion. To me, the process of creating a symlink is like a "virtual copy". Which the above parameter names reflect perfectly. Diez From josef.moellers at fujitsu-siemens.com Tue Jul 22 05:56:41 2008 From: josef.moellers at fujitsu-siemens.com (Josef Moellers) Date: Tue, 22 Jul 2008 11:56:41 +0200 Subject: The Importance of Terminology's Quality In-Reply-To: References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: Martin Gregorie wrote: > Are you sure about that? > I used Algol 60 on an Elliott 503 and the ICL 1900 series back when it was > a current language. The term "thunking" did not appear in either compiler > manual nor in any Algol 60 language definition I've seen. A60 could pass > values by name or value and procedures by name. That was it. Call by name > is what is now referred to as reference passing. Are you sure about that? ;-) AFAIK "Call by name" is *not* the same as passing an argument by reference. With "call by name" you can implement this wonderful thing called "Jensen's Device", which you cannot do when you pass parameters by reference! Josef -- These are my personal views and not those of Fujitsu Siemens Computers! Josef M?llers (Pinguinpfleger bei FSC) If failure had no penalty success would not be a prize (T. Pratchett) Company Details: http://www.fujitsu-siemens.com/imprint.html From bulg at ngs.ru Tue Jul 15 22:54:30 2008 From: bulg at ngs.ru (Yosifov Pavel) Date: Tue, 15 Jul 2008 19:54:30 -0700 (PDT) Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> <7348c0dc-028d-4f89-9d63-b1247fb6807c@m44g2000hsc.googlegroups.com> Message-ID: Kay, can you show example of such generator? ReIter, for example, work with usual generators. But for "big" iterator, I think is no any good solutions. IMHO we can discern 2 types of iterators: re-startable (based on internal Python objects) and not re-startable (with an external state, side- effects)... Best regards, Pavel From iainking at gmail.com Mon Jul 21 05:25:24 2008 From: iainking at gmail.com (Iain King) Date: Mon, 21 Jul 2008 02:25:24 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <143349c3-b0e9-49d8-9426-8b030b23d2c9@l42g2000hsc.googlegroups.com> On Jul 21, 6:58?am, "Krishnakant Mane" wrote: > > First off all c# is absolute rubbish waist of time. ?if I need to > learn it then I better lern java or pythonfor that matter. ?and by the > way what is a "real programmer?" The story of a Real Programmer: http://www.pbm.com/~lindahl/mel.html Iain From bruno.desthuilliers at gmail.com Wed Jul 9 16:26:27 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 9 Jul 2008 13:26:27 -0700 (PDT) Subject: FOSS projects exhibiting clean/good OOP? References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> Message-ID: <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> On 9 juil, 16:38, Phillip B Oldham wrote: > I'm wondering whether anyone can offer suggestions on FOSS projects/ > apps which exhibit solid OO principles, clean code, good inline > documentation, and sound design principles? This is somewhat subjective... Some would say that Python's object model is fundamentally broken and crappy (not MHO, needless to say) that Python + "solid OO principles" is antinomic !-) More seriously: > I'm devoting some time to reviewing other people's code to advance my > skills. Its good to review bad code (of which I have more than enough > examples) as well as good, but I'm lacking in finding good examples. > > Projects of varying sizes would be great. I'd recommand at least FormEncode and SQLAlchemy. From ojeeves at gmail.com Wed Jul 16 08:14:33 2008 From: ojeeves at gmail.com (oj) Date: Wed, 16 Jul 2008 05:14:33 -0700 (PDT) Subject: bad recursion, still works References: mailman.112.1216164093.922.python-list@python.org <20cba7ab-72d2-4c7b-8f3f-48f39eaf9625@m3g2000hsc.googlegroups.com> Message-ID: On Jul 16, 1:09?pm, Jeff wrote: > On Jul 15, 7:21?pm, Michael Torrie wrote: > > > iu2 wrote: > > > I still don't understand: In each recursive call to flatten, acc > > > should be bound to a new [], shouldn't it? Why does the binding happen > > > only on the first call to flatten? > > > Nope. ?In each new call it's (re)bound to the same original list, which > > you've added to as your function continues--it's mutable. ?Default > > variables that are bound to mutable objects are one of the big caveats > > that is mentioned in the FAQ. > > Is this avoidable by using a call to list() in the definition instead? No. Probably what you'd want to do, is something like this: def func(arg1, arg2=None): if arg2 is None: arg2 = list() ... So you create a list at runtime if arg2 has its default value. From nagle at animats.com Fri Jul 18 19:29:43 2008 From: nagle at animats.com (John Nagle) Date: Fri, 18 Jul 2008 16:29:43 -0700 Subject: Having trouble with some lists in BeautifulSoup In-Reply-To: References: Message-ID: <48812316$0$17149$742ec2ed@news.sonic.net> Alexnb wrote: > Okay, what I want to do with this code is to got to thesaurus.reference.com > and then search for a word and get the syns for it. Now, I can get the syns, > but they are still in html form and some are hyperlinks. But I can't get the > contents out. I am not that familiar with BeautifulSoup. So if anyone wants > to look over this code(if you run it, it will make a lot more sense) and > maybe help me out. The thesaurus site may become annoyed if you overdo this. However, it's not hard to do. Search the output for an "a" tag with class "noline", then extract the text content of the "a" tag. The BeautifulSoup manual will tell you how. If you want raw thesaurus data you can use freely, see "http://wordnet.princeton.edu". John Nagle From dullrich at sprynet.com Fri Jul 11 12:15:19 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 11 Jul 2008 11:15:19 -0500 Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: In article , Terry Reedy wrote: > David C. Ullrich wrote: > > In article > > <02ff4326-7b07-4ae6-8607-f58ea61802ef at z72g2000hsb.googlegroups.com>, > > ssecorp wrote: > > > >> I am never redefining the or reassigning the list when using validate > >> but since it spits the modified list back out that somehow means that > >> the modified list is part of the environment and not the old one. > >> i thought what happend inside a function stays inside a function > >> meaning what comes out is independent of what comes in. > >> Meaning if I want the list I send as a parameter to the function I > >> have to do x = func(x) and not just func(x) and x is magically what > >> comes out of func(). > > > > A function cannot modify the value of a global variable > > Yes it can. > >>> a=[] > >>> def f(): > a.append('yes I can') > > >>> f() > >>> a > ['yes I can'] > > > (unless it specifies "global"). It doesn't reassign anything. > > The statement 'global a' would allow f to *rebind* the global *name* > 'a'. Aargh. That's exactly what I meant, sorry. > The word 'variable' should almost not be used in discussing Python > since it is often unclear whether it refers to a name (or collection > slot) or an object bound thereto. Indeed. Which is exactly why I included those snippets of code that you snipped, one of which does exactly what your snippet above does... you're probably right, "variable" is a bad idea, and "modify the value of a variable" is a very bad idea. The code doesn't "modify the value of the variable" in the sense that the value of the variable is a certain object, and after the function call the value is the same object. It does "modify the value of the variable" in the sense that the object which is the value of the variable has been modified. There's a problem here. Please note that this is not a criticism, and I don't really know what anyone could do about the problem. The problem is that if the reader is not accustomed to thinking explicitly about what's going on under the hood when code is executed he's going to have a hard time understanding the difference between "assigning a value to a variable" and "binding a name to an object". Once I realized that dicts rule everything this became clear to me, but for some time the discussions I saw on all this made no sense to me. Which is why I think it's a good idea to include examples illustrating what can and cannot be done, which is why I did that. I tend to suspect that the OP is at least as confused on the subtlties as I was back then (evidence below). > > But in the functions below you're not reassigning a variable, > > you're _modifiying_ an object. A function _can_ modify an > > object you pass to it: > > It can modify any mutable object it can access. > > >> Doesnt Python have closure or that isnt what this is about? > > Python does have closures. This is not about that. This is why I suspect what I say I suspect. He's thought that the word "closure" meant something like "local scope"... > >> def validate(placed): > >> student = round(random.random()*401) > >> if student in placed: > >> return validate(placed) > >> else: > >> placed.append(student) > >> return student, placed > > Delete this. It is redundant with the below. > > >> def val(placed): > >> student = round(random.random()*401) > >> if student in placed: > >> return validate(placed) > >> else: > >> placed.append(student) > >> return student > > I believe this is equivalent to > > def addval(placed): > while True: > student = round(random.random()*401) > if student not in placed: > break > placed.append(student) > return student > > While this avoids the indefinite recursion depth problem, it does not > avoid the indefinite time problem. Use random.shuffle, or write your > own version if doing this for practice. Also consider removing the > return statement unless you actually directly use the added value. It > is easier to remember that addval mutates 'placed' without the return. > > >>>>> g = lambda x:validate(x) > > This is doubly diseased. > > First, never write a 'name = lambda...' statement since it is equivalent > to a def statement except that the resulting function object lacks a > proper .funcname attribute. The above only trivially abbreviates > def g(x): return validate(x) > by 3 characters. Another reason is that the lambda form somehow more > often tricks people into the next mistake . > > Second, never write a function (with either def or lambda) that simply > returns a function of the argument(s). The wrapping does nothing! This > is a waste of time and space for both you and the interpreter. The > above is functionally equivalent to > g = validate > and if you want that, you could name the function 'g' when you define it. > > >>>>> l=[] > In some fonts, 'l' and '1' are nearly identical; please use something > else for public code, which you made this to be by posting it;-) > > >>>>> for x in range(1,10): > >> g(l) > As said, the 'g' wrapper is useless. > addval(l) > > Hope this helps. > > Terry Jan Reedy -- David C. Ullrich From alokkat at gmail.com Thu Jul 10 21:20:21 2008 From: alokkat at gmail.com (Alok Kumar) Date: Thu, 10 Jul 2008 21:20:21 -0400 Subject: Basic Question about Python WebServer File handling Message-ID: Hi, I need to have a python webserver which can handle Get request from the clients and upload the *files* from 4 different directories. Can someone please point me what to exactly look for. Thanks you very much for this great help. Regards Alok Kumar -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Thu Jul 10 14:34:44 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jul 2008 14:34:44 -0400 Subject: Smal question In-Reply-To: <48763c7f$0$9609$426a74cc@news.free.fr> References: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> <48763c7f$0$9609$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Hans M?ller a ?crit : >> Hello group, >> >> I have some scripts sharing some common functions. >> So what I'd like to have is a modern include. >> Of course python does not have (with good reasons) no include statement. >> But I'm too lazy to create a module which has to be installed into the >> interpreter for some functions I need to share in a project. > > What do you mean "installed in the interpreter" ? He probably meant either compiled into the interpreter or installed in the interpreter directory, not knowing that one can import from the project directory, and that the project directory gets added to the front of sys.path (as '.'). From Russ.Paielli at gmail.com Sun Jul 27 18:11:13 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 15:11:13 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: On Jul 27, 12:39 pm, Bruno Desthuilliers wrote: > Derek Martin a ?crit : > > > > > On Sun, Jul 27, 2008 at 08:19:17AM +0000, Steven D'Aprano wrote: > >>> You take the name down to a single letter. As I suggested in an earlier > >>> post on this thread, why not take it down to zero letters? > >> The question isn't "why not", but "why". The status quo works well as it > >> is, even if it isn't perfect. Prove that implicit self is a good idea -- > >> or at least prove that it is an idea worth considering. > > > Come on, this sounds like a schoolyard argument. This comes down to a > > matter of style, and as such, is impossible to prove. It's largely a > > question of individual preference. > > > That said, the argument in favor is rather simple: > > > 1. This is an extremely common idiom in Python > > 2. It is completely unnecessary, and the language does not suffer for > > making it implicit > > 3. Making it implicit reduces typing, reduces opportunities for > > mistakes, and arguably increases consistency. > > "arguably", indeed, cf below. > > > As for the latter part of #3, self (or some other variable) is > > required in the parameter list of object methods, > > It's actually the parameter list of the *function* that is used as the > implementation of a method. Not quite the same thing. And then, > consistency mandates that the target object of the method is part of the > parameter list of the *function*, since that's how you make objects > availables to a function. > > > however when the > > method is *called*, it is omitted. > > Certainly not. You need to lookup the corresponding attribute *on a > given object* to get the method. Whether you write > > some_object.some_method() > > or > > some_function(some_object) > > you still need to explicitely mention some_object. > > > It is implied, supplied by Python. > > Neither. The target object is passed to the function by the method > object, which is itself returned by the __get__ method of function > objects, which is one possible application of the more general > descriptor protocol (the same protocol that is used for computed > attributes). IOW, there's nothing specific to 'methods' here, just the > use of two general features (functions and the descriptor protocol). > FWIW, you can write your own callable, and write it so it behave just > like a function here: > > import types > > class MyCallable(object): > def __call__(self, obj): > print "calling %s with %s" % (self, obj) > def __get__(self, instance, cls): > return types.MethodType(self.__call__, instance, cls) > > class Foo(object): > bar = MyCallable() > > print Foo.bar > f = Foo() > f.bar() > > > Thus when an object method is called, it must be called with one fewer > > arguments than those which are defined. This can be confusing, > > especially to new programmers. > > This is confusing as long as you insist on saying that what you > "def"ined is a method - which is not the case. > > > It can also be argued that it makes the code less ugly, though again, > > that's a matter of preference. > > >> It's not enough to show that a change "isn't bad" -- you have to show > >> that it is actively good. > > > But he did... he pointed out that *it saves work*, without actually > > being bad. Benefit, without drawback. Sounds good to me! > > >> "Don't need to look at the method signature" is not an argument in favour > >> of implicit self. > > > Yes, actually, it is. > > It isn't, since there's no "method signature" to look at !-) > > > If there is a well-defined feature of Python > > which provides access to the object within itself, > > The point is that you don't get access to the object "within itself". > You get access to an object *within a function*. > > The fact that a function is defined within a class statement doesn't > imply any "magic", it just creates a function object, bind it to a name, > and make that object an attribute of the class. You have the very same > result by defining the function outside the class statement and binding > it within the class statement, by defining the function outside the > class and binding it to the class outside the class statement, by > binding the name to a lambda within the class statement etc... > > > then the > > opportunities for mistakes when someone decides to use something else > > are lessened. > > >> You don't need to look at the method signature when you're using an > >> explicit self either. > > > That isn't necessarily true. If you're using someone else's code, and > > they didn't use "self" -- or worse yet, if they chose this variable's > > name randomly throughout their classes -- then you may well need to > > look back to see what was used. > > > It's bad programming, but the world is full of bad programmers, and we > > don't always have the choice not to use their code. Isn't one of > > Python's goals to minimize opportunities for bad programming? > > Nope. That's Java's goal. Python's goals are to maximize opportunities > for good programming, which is quite different. > > > Providing a keyword equivalent to self and removing the need to name > > it in object methods is one way to do that. > > It's also a way to make Python more complicated than it needs to be. At > least with the current state, you define your functions the same way > regardless of how they are defined, and the implementation is > (relatively) easy to explain. Special-casing functions definition that > happens within a class statement would only introduce a special case. > Then you'd have to explain why you need to specify the target object in > the function's parameters when the function is defined outside the class > but not when it's defined within the class. > > IOW : there's one arguably good reason to drop the target object from > functions used as methods implementation, which is to make Python looks > more like Java, and there's at least two good reason to keep it the way > it is, which are simplicity (no special case) and consistency (no > special case). > > Anyway, the BDFL has the final word, and it looks like he's not going to > change anything here - but anyone is free to propose a PEP, isn't it ? The issue here has nothing to do with the inner workings of the Python interpreter. The issue is whether an arbitrary name such as "self" needs to be supplied by the programmer. Neither I nor the person to whom you replied to here (as far as I can tell) is suggesting that Python adopt the syntax of Java or C++, in which member data or functions can be accessed the same as local variables. Any suggestion otherwise is a red herring. All I am suggesting is that the programmer have the option of replacing "self.member" with simply ".member", since the word "self" is arbitrary and unnecessary. Otherwise, everything would work *EXACTLY* the same as it does now. This would be a shallow syntactical change with no effect on the inner workings of Python, but it could significantly unclutter code in many instances. The fact that you seem to think it would change the inner functioning of Python just shows that you don't understand the proposal. From dickinsm at gmail.com Wed Jul 16 06:05:38 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 16 Jul 2008 03:05:38 -0700 (PDT) Subject: new itertools functions in Python 2.6 References: <4dd80ff2-5fda-405a-a637-08c985ff8add@e53g2000hsa.googlegroups.com> <498a38d4-10b5-4824-8401-5ebb510fcfa8@y38g2000hsy.googlegroups.com> Message-ID: <49e8f7eb-b4c6-4a51-af0d-54a257fcc353@x41g2000hsb.googlegroups.com> On Jul 16, 7:20?am, Mensanator wrote: > > > ## ?Combinations with replacement > > > ## ?----------------------------- > > > ## ?aaa aab aac aad aae abb abc abd abe acc acd ace > > > ## ?add ade aee bbb bbc bbd bbe bcc bcd bce bdd bde > > > ## ?bee ccc ccd cce cdd cde cee ddd dde dee eee > > > ## > > > ## ?actual words: 35 ? ?(m+n-1)!/(n!(m-1)!) words: 35 >>> for x in combinations(range(7), 4): ... x = [-1] + list(x) + [7] ... print ''.join(c*(x[i+1]-x[i]-1) for i, c in enumerate('abcde')) ... eee dee dde ddd cee cde cdd cce ccd ccc bee bde bdd bce bcd bcc bbe bbd bbc bbb aee ade add ace acd acc abe abd abc abb aae aad aac aab aaa Generalization left as an exercise for the reader. Mark From darcy at druid.net Sat Jul 26 10:08:09 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 26 Jul 2008 10:08:09 -0400 Subject: binding names doesn't affect the bound objects (was: print doesn't respect file inheritance?) In-Reply-To: <8763qtmgo7.fsf@benfinney.id.au> References: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> <8763qtmgo7.fsf@benfinney.id.au> Message-ID: <20080726100809.02fcca24.darcy@druid.net> On Sat, 26 Jul 2008 14:07:52 +1000 Ben Finney wrote: > > sys.stdout = n > > Re-binds the name 'sys.stdout' to the object already referenced by the > name 'n'. No objects are changed by this; only bindings of names to > objects. I do agree that the object formerly known as sys.stdout hasn't changed. > > print "Testing: 1, 2, 3..." > > Doesn't rely at all on the name 'sys.stdout', so isn't affected by all > the binding of names above. Hmm. Are you saying that the following doesn't work? $ python >>> f = open("test", "w") >>> import sys >>> sys.stdout = f >>> print "test message" >>> sys.exit(0) $ cat test test message > In other words, you can't change the object used by the 'print' > statement only by re-binding names (which is *all* that is done by the > '=' operator). Apparently I can. > You can, however, specify which file 'print' should use > . Which contains this statement. "Standard output is defined as the file object named stdout in the built-in module sys." I suppose that there might be some ambiguity there but the proof, as they say, is in the pudding. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From alif016 at gmail.com Sat Jul 26 12:19:45 2008 From: alif016 at gmail.com (Andrew) Date: Sat, 26 Jul 2008 11:19:45 -0500 Subject: Easier way to get the "here" path? In-Reply-To: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> References: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> Message-ID: <488B4EA1.6050506@gmail.com> bukzor wrote: >>>> from os.path import abspath, realpath >>>> realpath(path.__file__.rstrip("c")) >>>> > '/home/bgolemon/python/symlinks/path.py' > >>>> realpath(abspath(path.__file__.rstrip("c"))) >>>> > '/home/bgolemon/python/symlinks/symlinks/path.py' > -- > http://mail.python.org/mailman/listinfo/python-list > I find it interesting that I get something different: In [1]: import path path.pyc In [2]: path.__file__ Out[2]: 'path.pyc' In [3]: path.__file__.rstrip("c") Out[3]: 'path.py' In [4]: from os.path import abspath, realpath In [5]: realpath(path.__file__.rstrip("c")) Out[5]: '/home/andrew/sym/sym/path.py' In [6]: realpath(abspath(path.__file__.rstrip("c"))) Out[6]: '/home/andrew/sym/sym/path.py' I get the same thing for realpath() and realpath(abspath()) It seems to me you can just use: In [1]: import path path.pyc In [2]: from os.path import abspath In [3]: realpath(path.__file__.rstrip("c")) Out[3]: '/home/andrew/sym/sym/path.py' By the way, I am in /home/andrew/sym and path is symlinked from /home/andrew/sym/sym/path.py to /home/andrew/sym/path.py -- Andrew From girish.cfc at gmail.com Thu Jul 24 03:15:54 2008 From: girish.cfc at gmail.com (Girish) Date: Thu, 24 Jul 2008 00:15:54 -0700 (PDT) Subject: EXCEL API Message-ID: <8279561b-05b7-4935-9ded-def5663b4f93@y21g2000hsf.googlegroups.com> Hello, Does any one have a sample piece of code to search for a keyword in Excel sheet? if so plz post it.. Thanks, Girish.. From Xue.Huichao at gmail.com Mon Jul 14 21:03:40 2008 From: Xue.Huichao at gmail.com (Bighead) Date: Mon, 14 Jul 2008 18:03:40 -0700 (PDT) Subject: About the slot declaration decorator in PyQt4 References: Message-ID: <8486b24e-4d80-4bc2-85b7-db6b6519915f@m45g2000hsb.googlegroups.com> On Jul 15, 2:04 am, "Sebastian \"lunar\" Wiesner" wrote: > Bighead : > > > I remember when I did UI Design in PyQt4 for the first time, I found a > > manual. In it, no "connect" was used. Instead, an OO approach is > > applied, new UI classes inherit from old ones, and all the slot > > functions are automatically connected to some signals, using a > > decorator. In the __init__ function of our newly written class, > > "connect" is not invoked. > > > I like this style... > > > Unfortunately, I cannot find that manual now.... So anyone have read > > something like that before? If so, could you tell me where can I find > > that manual please? Thank you :) > > I guess, you're referring to QtCore.pyqtSignature and > QtCore.QMetaObject.connectSlotsByName. > > Seehttp://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#t... > > Especially "3.7.3 Connecting Slots By Name" > > Hih > > -- > Freedom is always the freedom of dissenters. > (Rosa Luxemburg) Oh yes, that's it! connectSlotsByName. That is the reason I though Qt was easy to use. This will be much easier :) Thank you very much. From http Mon Jul 28 12:27:08 2008 From: http (Paul Rubin) Date: 28 Jul 2008 09:27:08 -0700 Subject: with statement for two files References: <08d72316-15f1-45dd-b1f7-7b8ee06efef5@e39g2000hsf.googlegroups.com> Message-ID: <7xsktuvusj.fsf@ruckus.brouhaha.com> braver writes: > with open(src) as readin, open(dst,"w") as writin: # WRONG: comma > doesn't work > ... > -- so that you have transactional safety for two file descriptors? use contextlib.nexted(). From johnroth1 at gmail.com Sun Jul 13 15:30:23 2008 From: johnroth1 at gmail.com (John Roth) Date: Sun, 13 Jul 2008 12:30:23 -0700 (PDT) Subject: Mutually referencing imports -- impossible? References: Message-ID: <2e6bcb14-1db7-413b-afa7-62a11c9e33e4@26g2000hsk.googlegroups.com> On Jul 13, 11:55?am, Matthew Wilson wrote: > I started off with a module that defined a class Vehicle, and then > subclasses Car and Motorcycle. > > In the Car class, ?for some bizarre reason, I instantiated a Motorcycle. > Please pretend that this can't be avoided for now. > > Meanwhile, my Motorcycle class instantiated a Car as well. > > Then I moved the Car and Motorcycle classes into separate files. ?Each > imported the Vehicle module. > > Then I discovered that my Car module failed because the global > Motorcycle wasn't defined. ?The same problem happened in my Motorcycle > module. ?Car and Motorcycle can't both import each other. > > In the beginning, when all three (Vehicle, Car, and Motorcycle) were > defined in the same file, everything worked fine. > > I don't know how to split them out in separate files now though and I > really wish I could because the single file is enormous. > > Any ideas? > > Matt While it's possible for circular imports to work, it's very dangerous: it's not always possible to tell what went wrong without tracking down the process of the import step by step. There are more productive ways of banging your head against the wall and going insane. In your situation, it might be a whole lot easier to extract a common superclass that both of your classes could inherit from. John Roth From spandanagella at gmail.com Thu Jul 3 22:14:05 2008 From: spandanagella at gmail.com (spandana g) Date: Fri, 4 Jul 2008 10:14:05 +0800 Subject: HTTP request error with urlopen In-Reply-To: References: Message-ID: Hello , I have written a code to get the page source of the google search page .. this is working for other urls. I have this problem with import re from urllib2 import urlopen string='http://www.google.com/search?num=20&hl=en&q=ipod&btnG=Search' file_source=file("google_source.txt",'w') file_source.write(urlopen(string).read()) page_content=file_source.readlines() Traceback (most recent call last) : File "C:/Python25/google.py", line 5,in file_source.write(urlopen(string).read()) File "C:\Python25\lib\urllib2.py", line 124 , in urlopen return__opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 387 , in open response =meth(req, response) File "C:\Python25\lib\urllib2.py", line 498 , in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 425, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 360, in __call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 506, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: Forbidden Actually urlopen is working for google labs sets page but not for the google.com and even I have same problem with wikipedia . Please let me know .. If any one of have any idea about this . Thank You, Spandana. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chrispoliquin at gmail.com Thu Jul 31 16:07:16 2008 From: chrispoliquin at gmail.com (chrispoliquin at gmail.com) Date: Thu, 31 Jul 2008 13:07:16 -0700 (PDT) Subject: find and replace with regular expressions Message-ID: I am using regular expressions to search a string (always full sentences, maybe more than one sentence) for common abbreviations and remove the periods. I need to break the string into different sentences but split('.') doesn't solve the whole problem because of possible periods in the middle of a sentence. So I have... ---------------- import re middle_abbr = re.compile('[A-Za-z0-9]\.[A-Za-z0-9]\.') # this will find abbreviations like e.g. or i.e. in the middle of a sentence. # then I want to remove the periods. ---------------- I want to keep the ie or eg but just take out the periods. Any ideas? Of course newString = middle_abbr.sub('',txt) where txt is the string will take out the entire abbreviation with the alphanumeric characters included. From mva.led at gmail.com Mon Jul 21 01:15:45 2008 From: mva.led at gmail.com (Manuel Vazquez Acosta) Date: Mon, 21 Jul 2008 01:15:45 -0400 Subject: Python Written in C? Message-ID: <48841B81.3000704@gmail.com> I think your mixing things up. Even modern C compiler are mostly written in some other high level language. See GCC, for instance: it's mostly written in C. Many languages are made for build other major systems: * C was made in order to ease the build of Unix * Ada was made in order to ease the build of Air Traffic Control Systems. * and so on... On the other hand, Python's language features are, in a way, orthogonal to those of the underlying language in which Python *may* be implemented (take a look at PyPy: http://en.wikipedia.org/wiki/PyPy). I mean, I really don't care how Python mappings are implemented in C. What I care about is that I think in terms of (key, value) mappings, regardless of how lookups, insertions, deletions, and so are made internally. In C, I would have to resort to implement a hash table or so. Let's summarize: Python is a *new* language. C was the option to make it happen, there are others. Manuel. giveitawhril2008 at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. > -- > http://mail.python.org/mailman/listinfo/python-list > From timr at probo.com Thu Jul 31 03:10:14 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 31 Jul 2008 07:10:14 GMT Subject: Newbie Python questions References: Message-ID: <12p2941fee0nnimqmraqt9cm1vml7ra2kt@4ax.com> LessPaul wrote: > >...My >question is in regard to GUI platforms. My primary target would be >Windows, but I would also like be able to support Linux and Mac >versions if possible. I'm also interested in using a system that also >has support for pure C++ applications. As such, and after reading many >web pages regarding Python GUIs, I believe I have the candidates >narrowed down to pyQT and wxPython. > >The first question -- how steep is the curve to become proficient with >the above GUI packages? There is so much personal preference here that it is extremely hard to give any guidance. If you have done any Windows programming at all, so that you are familiar with the event-driven programming model, then I don't think you would see that much difference in learning curve. The two packages are more alike than they are different -- the various APIs are just spelled differently. I happen to be a big wxPython fan. I learn best by example, and wxPython has a 44,000-line demo suite with 167 source files that demonstrates virtually every class it includes. >Since there appears to be no commercial licencing fee for wxWidgets/ >wxPython, the last question is what do I gain from going QT over wx? >I've seen great applications written with both (on my computer I have >the wxPython Digsby and the pyQT apps "Mnemosyne" and "Anki". All seem >to be solid. Yep. Personal preference. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From fredrik at pythonware.com Tue Jul 15 07:04:17 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2008 13:04:17 +0200 Subject: SAX XML Parse Python error message In-Reply-To: References: <487A23A5.7000905@behnel.de> Message-ID: goldtech wrote: > I would be grateful for support with the code I cited. It's not long > and fairly standard. I'm sure my error(s) would be glaring to more > experienced coders. I appreciated the "heads-up" about other options > but I would be grateful for help getting this code to run. Thanks For comparison, here's how an experienced Python programmer might prefer to write your code: import xml.etree.cElementTree as ET description = None # most recently seen description for event, elem in ET.parse("somefile.xml"): if elem.tag == "description": description = elem.text elif elem.tag == "coordinates": print description.strip(), elem.text.strip() You may want to ask yourself why you prefer to struggle with obsolete, error-prone, and slow technology when there are more efficient tools available in Python's standard library. (the lxml library that Stefan linked to is a superset of xml.etree, in case you want more XML features). From dsc at ecs.soton.ac.uk Tue Jul 22 07:09:08 2008 From: dsc at ecs.soton.ac.uk (Dave Challis) Date: Tue, 22 Jul 2008 12:09:08 +0100 Subject: Automatically loading and initialising objects from a plugins directory Message-ID: <4885BFD4.9070502@ecs.soton.ac.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I'm trying to write some code which: 1. Finds all modules in a plugin directory 2. Imports those modules 3. Creates an instance of each object defined in the module (each module will contain exactly 1 object, which is a subclass of 'Plugin') The closest I've come so far is with something like: In plugin.py: # taken from http://docs.python.org/lib/built-in-funcs.html def my_import(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod def import_plugins(): mods = [] for filename in os.listdir('/plugins'): if filename.endswith('.py'): name = os.path.splitext(filename)[0] mods.append(my_import('plugins.' + name)) return mods class Plugin(object): pass In plugins/exampleplugin.py: class ExamplePlugin(Plugin): def __init__(self): pass Calling import_plugins() then gives me a list containing references to modules. How can I loop through that list and create an instance of whatever object was defined within the module? (In this case I'd want to construct an instance of ExamplePlugin) Thanks in advance, Dave - -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ( Dave Challis ) ><> ____dsc at ecs.soton.ac.uk_______________________(___________________________ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFIhb/Uv26GZvAVVFERAsGaAJ9KwtFI9yXdk2gBGxy0/bjCd5318wCgsiV9 m14BZSvxqZ1EP0OvaXBZoaw= =TYlD -----END PGP SIGNATURE----- From keith.hughitt at gmail.com Wed Jul 9 15:53:52 2008 From: keith.hughitt at gmail.com (Keith Hughitt) Date: Wed, 9 Jul 2008 12:53:52 -0700 (PDT) Subject: Allow tab completion when inputing filepath? References: Message-ID: <08e60124-51c1-40c1-bffe-52c22ff310db@l64g2000hse.googlegroups.com> On Jul 9, 10:18?am, Tim Golden wrote: > Keith Hughitt wrote: > > I've been looking around on the web for a way to do this, but so far > > have not come across anything for this particular application. I have > > found some ways to enable tab completion for program-related commands, > > but not for system filepaths. This would be nice to have when > > prompting the user to enter a file/directory location. > > What platform are you on? And what kind of display? > (Console / GUI / wxPython / Qt / Web...) > > TJG Hi TJG, Currently Unix/Console. Although I don't have any plans at the moment to add a GUI, it would be great if a cross-platform solution existed. Keith From ptmcg at austin.rr.com Sun Jul 20 01:11:55 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 19 Jul 2008 22:11:55 -0700 (PDT) Subject: Not entirely serious: recursive lambda? References: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> Message-ID: <3eb2d018-3230-49bf-840d-3650b614b016@8g2000hse.googlegroups.com> On Jul 19, 11:49?pm, Miles wrote: > On Sat, Jul 19, 2008 at 10:43 PM, Michael Tobis wrote: > > Can a lambda call itself without giving itself a name? > > Kind of. ?There's a couple ways I know of. > > The functional way, which involves the lambda receiving itself as an argument: > > (lambda f: f(10, f))(lambda n, f: n and (sys.stdout.write("%d\n" % n) > or f(n-1,f))) > > The stack frame examination way: > > import sys, inspect, new > (lambda:sys.stdout.write('recurse\n') or > new.function(inspect.currentframe().f_code, globals())())() > > The functional way is probably harder to grok unless you've studied > lambda calculus or had experience with "real" functional languages (I > haven't). ?For fun, try throwing a Y combinator in there. > > -Miles Here is Michael Tobis's original program, using the functional approach: print (lambda f:f(("",reduce(lambda c,m:c*95+''.join(map(chr,range(32,127))).index(m), "!b)'1Mgh0z+fYQ]g::i^<&y~g)cnE-d=K&{GMNQ1gx +ooY<~L##N'X]P2<@XYXwX3z", 0),f)))(lambda (r,N,f):N and f((" acdefijlmnopqrstuv"[N%19]+r,N/ 19,f))or(r,N,f))[0] Tr?s assombri! (according to Babelfish...). -- Paul From mail at timgolden.me.uk Tue Jul 15 12:18:53 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Jul 2008 17:18:53 +0100 Subject: About wmi In-Reply-To: References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> Message-ID: <487CCDED.2090705@timgolden.me.uk> patrol wrote: > Situation (2): > result = new_process.terminate() > File "C:\Python25\lib\wmi.py", line 494, in __getattr__ > handle_com_error (error_info) > File "C:\Python25\lib\wmi.py", line 190, in handle_com_error > raise x_wmi, "\n".join (exception_string) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > 14: ordinal > not in range(128) > > BTW, My windows' languange is Chinese. Well that looks embarrassingly like a complete lack of unicode-awareness in the wmi module. Would you mind trying this version: http://timgolden.me.uk/wmi-project/wmi.py which is a copy of the svn trunk to see if that improves the UnicodeDecode error, please? I'll try to get an install of a non-English edition of Windows but, as you might imagine, I normally run the UK version so don't hit these kind of issue myself. TJG From sk8in_zombi at yahoo.com.au Fri Jul 11 15:09:25 2008 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Fri, 11 Jul 2008 12:09:25 -0700 (PDT) Subject: Filechooser issues Message-ID: <576590.26999.qm@web54501.mail.re2.yahoo.com> Hi, I am using a gtk.filechooser dialog to open and save files.How do I add a filter so that only images are filtered ?I did something like this: ??? def get_save_filename(self): ??? ??????? filename = None ??????? chooser = gtk.FileChooserDialog("Save File...", self.window, ??????????????????????????????????????? gtk.FILE_CHOOSER_ACTION_SAVE, ??????????????????????????????????????? (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, ???????????????????????????????????????? gtk.STOCK_SAVE, gtk.RESPONSE_OK)) ??? ff = gtk.FileFilter.add_pixbuf_formats() ??????? chooser.add_filter(ff) ??????? response = chooser.run() ??????? if response == gtk.RESPONSE_OK: filename = chooser.get_filename() ??????? chooser.destroy() ??????? ??????? return filename Now I get an error when I add ff or a filefilter .The error is : Traceback (most recent call last): ? File "tutorial.py", line 91, in on_save_as_menu_item_activate ??? filename = self.get_save_filename() ? File "tutorial.py", line 231, in get_save_filename ??? ff = gtk.FileFilter.add_pixbuf_formats() TypeError: descriptor 'add_pixbuf_formats' of 'gtk.FileFilter' object needs an argument The documentation doesn't say anything about an argument to be passed: http://www.pygtk.org/docs/pygtk/class-gtkfilefilter.html#method-gtkfilefilter--add-pixbuf-formats Regards, SZ " life isn't heavy enough,it flies away and floats far above action" Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: From nicolas.pourcelot at gmail.com Mon Jul 21 04:58:17 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Mon, 21 Jul 2008 01:58:17 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> <6ebshqF67cpfU4@mid.uni-berlin.de> <5d6b8066-c941-4f0c-abea-20baed33b4ab@l64g2000hse.googlegroups.com> <6eg02pF6uhc3U2@mid.uni-berlin.de> Message-ID: <94b55395-f89e-4dda-828b-505dacdabeb4@l64g2000hse.googlegroups.com> On 20 juil, 07:17, Marc 'BlackJack' Rintsch wrote: > On Sat, 19 Jul 2008 13:13:40 -0700, nicolas.pourcelot wrote: > > On 18 juil, 17:52, Marc 'BlackJack' Rintsch wrote: > >> On Fri, 18 Jul 2008 07:39:38 -0700, nicolas.pourcelot wrote: > >> > So, I use something like this in 'sheet.objects.__setattr__(self, > >> > name, value)': > >> > if type(value) == Polygon: > >> > ? ? for edge in value.edges: > >> > ? ? ? ? if edge is_in sheet.objects.__dict__.itervalues(): > >> > ? ? ? ? ? ? object.__setattr__(self, self.__new_name(), edge) > > >> > Ok, I suppose it's confused, but it's difficult to sum up. ;-) > > >> You are setting attributes with computed names? ?How do you access them? > >> Always with `gettattr()` or via the `__dict__`? ?If the answer is yes, why > >> don't you put the objects the into a dictionary instead of the extra > >> redirection of an objects `__dict__`? > > > Yes, I may subclass dict, and change its __getitem__ and __setitem__ > > methods, instead of changing objets __setattr__ and __getattr__... But > > I prefer > >>>> sheet.objects.A = Point(0, 0) > > than > >>>> sheet.objects["A"] = Point(0, 0) > > But with computed names isn't the difference more like > > setattr(sheet.objects, name, Point(0, 0)) > vs. > sheet.objects[name] = Point(0, 0) > > and > > getattr(sheet.objects, name) > vs. > sheet.objects[name] > > Or do you really have ``sheet.objects.A`` in your code, in the hope that > an attribute named 'A' exists? > > >> Oh and the `type()` test smells like you are implementing polymorphism > >> in a way that should be replaced by OOP techniques. > > > I wrote 'type' here by mistake, but I used 'isinstance' in my code. ;-) > > Doesn't change the "code smell". ?OOP approach would be a method on the > geometric objects that know what to do instead of a type test to decide > what to do with each type of geometric object. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch Thank you for your advises, it's very interesting to have an external point of view. No, I have not anything like 'sheet.objects.A' in the library code, but I use then the library in different programs where things like sheet.objects.A sometimes occur. However, since it is not so frequent, I may indeed subclass dict, and change __getitem__, __setitem__ and __delitem__, and then redirect __getattr__, __setattr__, __delattr__ to previous methods... This would not break library external API, and it may speed-up a little internal stuff. I'm not very expert in OOP ; imho it's largely a mean and not a goal. On one hand, 'a method on the geometric objects that know what to do' would require them to contain some code concerning the object manager... I don't like that very much. On the other hand, object manager should not rely on object's implementation... I will think about that. Thank you all of you for your answers. I'm sorry I may not have time to reply further, it was interesting :-) (even if it's a bit difficult for me to write clearly in english ;-)) From casevh at gmail.com Sat Jul 5 15:04:51 2008 From: casevh at gmail.com (casevh) Date: Sat, 5 Jul 2008 12:04:51 -0700 (PDT) Subject: conflict between multiple installs of python (linux) References: <6bd22c06-a1e6-4247-9aff-2d0b29b1ec5e@d1g2000hsg.googlegroups.com> Message-ID: <6993e25b-7f81-4584-9c28-b5565cda7fcc@a70g2000hsh.googlegroups.com> On Jul 5, 11:09?am, david wrote: > You learn something new every day: > > On my ubuntu, update-manager is supposed to use the python2.5 > installed on /usr/bin. Well, I had subsequently installed a whole > bunch of stuff in /usr/local (/usr/local/bin/python and /usr/local/lib/ > python2.5 etc), which I have happily been using for development for a > year. I had thought that the two pythons were completely independent. > > Well, I was wrong. When /usr/bin/python2.5 runs, *by default*, it > adds /usr/local/lib/python2.5 to its sys path - and apparently there > are things in /usr/local which are inconsistent with those at /usr > (not suprising). > > I have fixed the problem - but I had to modify the actual update- > manager .py file itself. At the beginning, I set the sys.path in > python *explicitly* to not include the /usr/local stuff. > > But this is clearly a kludge. My question: how do I keep the Ubuntu > python stuff at /usr/bin/python2.5 from adding /usr/local/lib/ > python2.5 to the import search path in a clean and global way? I > really want both pythons completely isolated from one another! > > Thankyou. Python's path is build by site.py. In the file /usr/lib/python2.5/ site.py, look for the line "prefixes.insert(0, '/usr/local')" and comment it out. That should do it. casevh From notontheweb at noisp.com Sat Jul 26 13:52:51 2008 From: notontheweb at noisp.com (Jive Dadson) Date: Sat, 26 Jul 2008 17:52:51 GMT Subject: urllib and login with passwords Message-ID: Hey folks! There are various web pages that I would like to read using urllib, but they require login with passwords. Can anyone tell me how to find out how to do that, both in general and specifically for YouTube.com. Thankee. From mrkafk at gmail.com Thu Jul 17 10:57:08 2008 From: mrkafk at gmail.com (mk) Date: Thu, 17 Jul 2008 16:57:08 +0200 Subject: property getter with more than 1 argument? Message-ID: It seems like getter is defined in such way that it passes only 'self': class FunDict(dict): def __init__(self): self.fundict = dict() def fget(self, fun): return fundict[fun.func_name] def fset(self, newfun): self.fundict[newfun.func_name] = newfun newfun = property (fget, fset) >>> a=FunDict() >>> >>> a.newfun=f1 >>> >>> a.newfun('f1') Traceback (most recent call last): File "", line 1, in a.newfun('f1') TypeError: fget() takes exactly 2 arguments (1 given) Is it possible to pass more than one argument to fget function? I know: I can define a function with property name ('newfun' in the example) and call it with more arguments. But then I do not get the benefits of setter and property in general! From deets at nospam.web.de Fri Jul 11 05:59:55 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 11 Jul 2008 11:59:55 +0200 Subject: Question about: GUI Builder for Tkinter and call to C/C++ code In-Reply-To: References: Message-ID: <6dop8uF3lhrqU1@mid.uni-berlin.de> pauladospublicidad schrieb: > First I'll introduce myself. I normally programm in C/C++ and Java. > Sometimes I have to mix them (normally using C/C++ in java, because in > java is easier to make portable graphic user interfaces). However to > use C/C++ code in java is really complex and difficult. > > Not too much time ago, I discover python. I had think to use it for > developing portable graphic user intefaces, that will call my C/C++ > code / libraries / programs. > > I had thought to use tkinter for making the GUIs, for portability and > for not installing anything more than python. It's to say, for not > adding more packages because I'm new in python and I don't now too > much about install new packages. > > I have seen that for wxpython there is gui builders (such as boa) but > for tkinter I have not found anyon. I would like to know if anyone > knows a GUI Builder for tkinter in order to develop my GUI's > graphically and in a easier way. AFAIK there is none, at least not usable with python. However, back when I did tk, I found it easy and clear enough (especially with the powerful layout managemnt) to hand-craft the GUI. > Apart from this, I would like to call my C/C++ code / modulles / > applications from python. I have read that python is implemented > normally in C, so is easy to add new modules from C. I would like to > find any tutorial / manual / link for dummies in order to make this > (call my C code from python). There are various options, depending on if you are real about using C, or if you are more into C++. If you *can*, you should IMHO rely on a C-API (potentially layering a C++-lib). Then you can use the since python2.5 build-in ctypes-module to access any DLL/shared library you like. For extending and embedding, see the official docs: http://docs.python.org/ext/ext.html For C++ wrappers, there are several available: - SWIG - Boost::Python - SIP (used to wrap the great Qt gui toolkit) I can personally recommend the latter, others MMV. > Another solution could be to call the GUI made in python from C/C++ > code, but I'm sure this would be more complex. You don't want this, no. It's possible, but needlessly complex. HTH, Diez From mrkafk at gmail.com Mon Jul 21 12:06:45 2008 From: mrkafk at gmail.com (mk) Date: Mon, 21 Jul 2008 18:06:45 +0200 Subject: Seriously, though, about LLVM Message-ID: http://llvm.org/ This project has gained some publicity. There's IronPython, right, so has anybody thought about implementing Python using LLVM as backend, as it seems not out of question at all? From bourdenas at gmail.com Mon Jul 28 14:10:05 2008 From: bourdenas at gmail.com (Themis Bourdenas) Date: Mon, 28 Jul 2008 19:10:05 +0100 Subject: Module clarification In-Reply-To: <488E0887.6070803@internetnowasp.net> References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> <488E0887.6070803@internetnowasp.net> Message-ID: <7fd737460807281110y36a1e9dfk63ea7d692d9f8cb7@mail.gmail.com> I would recommend dive into python. Its available free online (just google it) and it tries to teach you python, not programming which unfortunately many books try to do. It assumes that you already have some experience with C++ or Java and contradicts python syntax/semantics to those languages. Very useful and fast if you already know how to program. Cheers, Themis On Mon, Jul 28, 2008 at 6:57 PM, Marcus.CM wrote: > Hi Hussein, > > Basically a module is a FILE and is considered as a singleton model. Yes ur > wow.py assumption is correct. > I recommend getting Mark Lutz Learning Python book to get you started. > > Marcus.CM > > > Hussein B wrote: > >> Hi. >> I'm a Java guy and I'm playing around Python these days... >> In Java, we organize our classes into packages and then jarring the >> packages into JAR files. >> What are modules in Python? >> What is the equivalent of modules in Java? >> Please correct me if I'm wrong: >> I saved my Python code under the file Wow.py >> Wow.py is now a module and I can use it in other Python code: >> import Wow >> >> Thanks. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> >> > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Fri Jul 18 15:10:33 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Jul 2008 19:10:33 GMT Subject: __del__ methods References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> Message-ID: <6ec859F67cpfU5@mid.uni-berlin.de> On Fri, 18 Jul 2008 11:31:20 -0700, Jason Baker wrote: > I have a class that I need to do some finalization on when it dies. I > know I can use the __del__ method, but I seem to recall that it > impedes garbage collection. Is this the case? `__del__()` is not a deterministic destructor. So forget about reliable automatic clean up. Do it yourself with an explicit call to a `close()` method or something like that. Ciao, Marc 'BlackJack' Rintsch From timr at probo.com Sun Jul 6 01:02:13 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 06 Jul 2008 05:02:13 GMT Subject: Python with Ecmascript References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> Message-ID: <8ek074tia4l47tcfo6tqfo9huv2hb68hkt@4ax.com> "jiri.zahradil at gmail.com" wrote: > >for my Python application (Windows platform) to be standards >compliant, I need to embbed Ecmascript(Javascript) interpreter - I >need to execute plugins written in this language. What standard are you hoping to comply with? I mean, what kind of a program is this? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mensanator at aol.com Mon Jul 14 16:26:19 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 14 Jul 2008 13:26:19 -0700 (PDT) Subject: new itertools functions in Python 2.6 Message-ID: <4dd80ff2-5fda-405a-a637-08c985ff8add@e53g2000hsa.googlegroups.com> With the new functions added to itertools in Python 2.6, I can finally get rid of this monstrosity: def ooloop6(a, n, perm=True, repl=True): if (not repl) and (n>len(a)): return r0 = range(n) r1 = r0[1:] if perm and repl: # ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) e = ''.join(["p = [''.join((",v,")) ",f,"]"]) exec e return p if (not perm) and repl: # ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) i = ' and '.join(['(c%s>=c%s)' % (j,j-1) for j in r1]) e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"]) exec e return p if perm and (not repl): # ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) i = ' and '.join([' and '.join(['(c%s!=c%s)' % (j,k) for k in range(j)]) for j in r1]) e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"]) exec e return p if (not perm) and (not repl): # ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) i = ' and '.join(['(c%s>c%s)' % (j,j-1) for j in r1]) e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"]) exec e return p If I use a single iterable with the repeat option, the Carteisan Product will give me Permutaions With Replacement. from itertools import * from math import factorial as fac s = 'abcde' m = len(s) n = 3 print 'For %d letters (%s) taken %d at a time:' % (m,s,n) print '========================================' ### Permutations with replacement m**n ### print 'Permutations with replacement' print '-----------------------------' p = [i for i in product('abcde',repeat=3)] for i in p: print ''.join(i), print print print 'actual words: %d m**n words: %d' % (len(p),m**n) print ## For 5 letters (abcde) taken 3 at a time: ## ======================================== ## Permutations with replacement ## ----------------------------- ## aaa aab aac aad aae aba abb abc abd abe aca acb ## acc acd ace ada adb adc add ade aea aeb aec aed ## aee baa bab bac bad bae bba bbb bbc bbd bbe bca ## bcb bcc bcd bce bda bdb bdc bdd bde bea beb bec ## bed bee caa cab cac cad cae cba cbb cbc cbd cbe ## cca ccb ccc ccd cce cda cdb cdc cdd cde cea ceb ## cec ced cee daa dab dac dad dae dba dbb dbc dbd ## dbe dca dcb dcc dcd dce dda ddb ddc ddd dde dea ## deb dec ded dee eaa eab eac ead eae eba ebb ebc ## ebd ebe eca ecb ecc ecd ece eda edb edc edd ede ## eea eeb eec eed eee ## ## actual words: 125 m**n words: 125 So what does "permutaions" mean in itertools? It actually means Permutions Without Replacement. ### Permutations without replacement m!/(m-n)! ### print 'Permutations without replacement' print '--------------------------------' p = [i for i in permutations('abcde',3)] for i in p: print ''.join(i), print print print 'actual words: %d m!/(m-n)! words: %d' % (len(p),fac(m)/fac(m- n)) print ## Permutations without replacement ## -------------------------------- ## abc abd abe acb acd ace adb adc ade aeb aec aed ## bac bad bae bca bcd bce bda bdc bde bea bec bed ## cab cad cae cba cbd cbe cda cdb cde cea ceb ced ## dab dac dae dba dbc dbe dca dcb dce dea deb dec ## eab eac ead eba ebc ebd eca ecb ecd eda edb edc ## ## actual words: 60 m!/(m-n)! words: 60 Not surprisingly, "combinations" actually means Combinations Without Replacement. ### Combinations without replacement m!/(n!(m-n)!) ### print 'Combinations without replacement' print '--------------------------------' p = [i for i in combinations('abcde',3)] for i in p: print ''.join(i), print print print 'actual words: %d m!/(n!(m-n)!) words: %d' % (len(p),fac(m)/ (fac(n)*factorial(m-n))) print ## Combinations without replacement ## -------------------------------- ## abc abd abe acd ace ade bcd bce bde cde ## ## actual words: 10 m!/(n!(m-n)!) words: 10 Hmm...that's only three subsets of the Cartesian Product. No Combinations With Replacement. Although you can always filter the Cartesian Product to get a subset. # Combinations with replacement (m+n-1)!/(n!(m-1)!) # print 'Combinations with replacement' print '-----------------------------' p = [i for i in ifilter(lambda x: list(x)==sorted(x),product('abcde',repeat=3))] for i in p: print ''.join(i), print print print 'actual words: %d (m+n-1)!/(n!(m-1)!) words: %d' % (len(p),fac(m+n-1)/(fac(n)*fac(m-1))) print ## Combinations with replacement ## ----------------------------- ## aaa aab aac aad aae abb abc abd abe acc acd ace ## add ade aee bbb bbc bbd bbe bcc bcd bce bdd bde ## bee ccc ccd cce cdd cde cee ddd dde dee eee ## ## actual words: 35 (m+n-1)!/(n!(m-1)!) words: 35 Although it works, it's somewhat slow as we have to iterate over the entire Cartesian Product and the filter list(x)==sorted(x) has got to be expensive (it's slower than the nested loop algorithm). Is there a better way to get Combinations With Replacement using itertools? From kris at FreeBSD.org Mon Jul 7 15:27:43 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Mon, 07 Jul 2008 21:27:43 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: <48726E2F.5030503@FreeBSD.org> Paddy wrote: > On Jul 4, 1:36 pm, Peter Otten <__pete... at web.de> wrote: >> Henning_Thornblad wrote: >>> What can be the cause of the large difference between re.search and >>> grep? >> grep uses a smarter algorithm ;) >> >> >> >>> This script takes about 5 min to run on my computer: >>> #!/usr/bin/env python >>> import re >>> row="" >>> for a in range(156000): >>> row+="a" >>> print re.search('[^ "=]*/',row) >>> While doing a simple grep: >>> grep '[^ "=]*/' input (input contains 156.000 a in >>> one row) >>> doesn't even take a second. >>> Is this a bug in python? >> You could call this a performance bug, but it's not common enough in real >> code to get the necessary brain cycles from the core developers. >> So you can either write a patch yourself or use a workaround. >> >> re.search('[^ "=]*/', row) if "/" in row else None >> >> might be good enough. >> >> Peter > > It is not a smarter algorithm that is used in grep. Python RE's have > more capabilities than grep RE's which need a slower, more complex > algorithm. > You could argue that if the costly RE features are not used then maybe > simpler, faster algorithms should be automatically swapped in but .... I can and do :-) It's a major problem that regular expression parsing in python has exponential complexity when polynomial algorithms (for a subset of regexp expressions, e.g. excluding back-references) are well-known. It rules out using python for entire classes of applications where regexp parsing is on the critical path. Kris From rocksportrocker at googlemail.com Wed Jul 2 04:38:56 2008 From: rocksportrocker at googlemail.com (rocksportrocker) Date: Wed, 2 Jul 2008 01:38:56 -0700 (PDT) Subject: distutils - setup - lib problem Message-ID: <6138c75a-601e-4c44-b765-364cadb16098@l64g2000hse.googlegroups.com> Hi, I've got some problems with the following setup.py file. using "python setup.py install -f" it shows that wrap_ica.so is copied to /usr and not to ..../site-packages as I assumed. What am I doing wrong ? I'm using Python 2.4 on Debian Linux. ----------------------------------------------------- from distutils.core import setup import glob setup(name='py_ica', py_modules=['py_ica'], data_files=[(".", ["wrap_ica.so"]), ] ) ----------------------------------------------------- Greetings, Uwe From Russ.Paielli at gmail.com Sun Jul 27 02:47:05 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 26 Jul 2008 23:47:05 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: On Jul 26, 11:22 pm, Terry Reedy wrote: > Russ P. wrote: > > On Jul 26, 2:25 pm, Terry Reedy > >> There is a lot of code you have not seen. Really. In informal code I > >> use 's' and 'o' for 'self' and 'other'. I don't usually post such > >> because it is not considered polite. So you have seen a biased sample > >> of the universe. > > > You take the name down to a single letter. As I suggested in an > > earlier post on this thread, why not take it down to zero letters? > > Because 1 letter is legal now, while no letters (already proposed and > rejected) is a major change and breakage of current simplicity and > consistency for zero functional benefit. Sorry, but I fail to see how it is a "major change." It only applies to the first argument of a class member function, and the parser only needs to look for an empty argument or a period. Furthermore, it would break no working code. It may indeed have been "proposed and rejected," but it would be a nice way to clean up code in many areas, and as long as it cannot break any working code, I think it should be reconsidered. From motoom at xs4all.nl Tue Jul 15 10:06:48 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Tue, 15 Jul 2008 16:06:48 +0200 Subject: Type Problem Message-ID: <2.2.32.20080715140648.0125a124@pop.xs4all.nl> Victor wrote... >len = len(dirs) The function 'len' is a built-in function in Python. If you assign an integer to the name 'len', that will replace the function with an int. And you can't call an int. My suggestion: Do not use 'len' as a variable name. Use something else, like: directorycount=len(dirs) Greetings, >>> type(len) >>> print len("Victor") 6 >>> len=42 >>> type(len) >>> len("Victor") Traceback (most recent call last): File "", line 1, in len("Victor") TypeError: 'int' object is not callable -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From deets at nospam.web.de Wed Jul 2 15:09:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Jul 2008 21:09:44 +0200 Subject: Pyro: ProtocolError('connection failed') In-Reply-To: References: Message-ID: <6d223oFetjoU1@mid.uni-berlin.de> jamitwidme at gmail.com schrieb: > Hello everyone > Can someone help me fix this problem? > > I am using an example from Pyro(Python Remote Object) website > directly. > It is the last example from > http://pyro.sourceforge.net/manual/8-example.htm > > I have two computers to run Server and Client. > ############################################ > server.py > > import Pyro.naming > import Pyro.core > from Pyro.errors import PyroError,NamingError > > > ###### testclass Pyro object > > class testclass(Pyro.core.ObjBase): > def mul(s, arg1, arg2): return arg1*arg2 > def add(s, arg1, arg2): return arg1+arg2 > def sub(s, arg1, arg2): return arg1-arg2 > def div(s, arg1, arg2): return arg1/arg2 > > ###### main server program > > def main(): > Pyro.core.initServer() > daemon = Pyro.core.Daemon() > # locate the NS > locator = Pyro.naming.NameServerLocator() > print 'searching for Name Server...' > ns = locator.getNS(host='drizzle.des.hep.uiuc.edu', port=9090) > daemon.useNameServer(ns) > > # connect a new object implementation (first unregister > previous one) > try: > # 'test' is the name by which our object will be known > to the outside world > ns.unregister('test') > except NamingError: > pass > > # connect new object implementation > daemon.connect(testclass(),'test') > > # enter the server loop. > print 'Server object "test" ready.' > daemon.requestLoop() > > if __name__=="__main__": > main() > > ################################### > > ################################### > client.py > > import Pyro.naming, Pyro.core > from Pyro.errors import NamingError > > # locate the NS > locator = Pyro.naming.NameServerLocator() > print 'Searching Name Server...', > ns = locator.getNS(host='drizzle.des.hep.uiuc.edu',port=9090) > > # resolve the Pyro object > print 'finding object' > try: > URI=ns.resolve('test') > print 'URI:',URI > except NamingError,x: > print 'Couldn\'t find object, name server says:',x > raise SystemExit > > # create a proxy for the Pyro object, and return that > test = Pyro.core.getProxyForURI(URI) > > print test.mul(111,9) > print test.add(100,222) > print test.sub(222,100) > print test.div(2.0,9.0) > print test.mul('*',10) > print test.add('String1','String2') > ####################################### > > It does not matter which computer Pyro NameServer is located. > When Server and Client are in a same computer, it works perfectly > fine. > But whenever Server and Client run in different computers, I get a > following error message. > > > ######################################## > Pyro Client Initialized. Using Pyro V3.7 > Searching Name Server... finding object > URI: PYRO://127.0.0.1:7888/7f000001193649ab6a89d5592bc843bb > Traceback (most recent call last): > File "client.py", line 22, in > print test.mul(111,9) > File "/usr/local/lib/python2.5/site-packages/Pyro/core.py", line > 390, in __call__ > return self.__send(self.__name, args, kwargs) > File "/usr/local/lib/python2.5/site-packages/Pyro/core.py", line > 467, in _invokePYRO > self.adapter.bindToURI(self.URI) > File "/usr/local/lib/python2.5/site-packages/Pyro/protocol.py", line > 255, in bindToURI > raise ProtocolError('connection failed') > Pyro.errors.ProtocolError: connection failed > ######################################## > > Thanks a lot. THis is just a guess - but it seems that somehow you don't bind your pyro objects to the NIC's IP address, but to localhost (127.0.0.1) - which of course won't work. That never happened to me though, try and see the pyro docs on how to prevent/control to which IP a proxy is bound. Diez From alexandru.palade at sellerengine.com Mon Jul 21 08:21:49 2008 From: alexandru.palade at sellerengine.com (Alexandru Palade) Date: Mon, 21 Jul 2008 15:21:49 +0300 Subject: Odd math related issue. In-Reply-To: References: <43332.3139710867$1216630189@news.gmane.org> Message-ID: <48847F5D.9080509@sellerengine.com> However, you should be carefully because using an %i modifier for a what-should-be a float value truncates the value in a way you may not expect. What I mean is that if you have sent 2 out of 3 bytes, the math will be 200/3 which with the %i modifier will print 66, rather than 66.6 (or at least 67 which is closer - have a look at the round() function). Another thing, you could have just added a dot after the constant in order to promote the expression to be evaluated as float. As in percentage = bytes_transferred / /self/.__sessions[path].total_bytes * 100. (notice the last dot) Fredrik Lundh wrote: > Robert Rawlins wrote: > >> I?ve got what seems to me to be a totally illogical math issue here >> which I can?t figure out. Take a look at the following code: >> >> /self/.__logger.info(/"%i / %i"/ % (bytes_transferred, >> /self/.__sessions[path].total_bytes)) >> >> percentage = bytes_transferred / >> /self/.__sessions[path].total_bytes * 100 >> >> /self/.__logger.info(/"%i"/ % percentage) >> >> Seems fairly straight forward, you would think. It takes two values >> and calculates the percentage of one from the other, however, >> percentage always comes back as ?0? for some reason, look at this log >> output. > > if you divide two integers, you'll get an integer back (in Python 2.X, > at least). quick fix: > > percentage = bytes_transferred * 100 / total_bytes > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Mon Jul 21 18:04:45 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 21 Jul 2008 18:04:45 -0400 Subject: Python Written in C? In-Reply-To: References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> Message-ID: mk wrote: > Seriously, though, would there be any advantage in re-implementing > Python in e.g. C++? Considered and rejected by Guido and the CPython developer crew. Anyone who wants C++Python is free to make one, just as people have done JavePython (Jython), C#Python, (IonPython), PythonPython (PyPy), and compiled-CPython (multiple). > Not that current implementation is bad, anything but, but if you're not > careful, the fact that lists are implemented as C arrays can bite your > rear from time to time (it recently bit mine while using lxml). Suppose > C++ re-implementation used some other data structure (like linked list, > possibly with twists like having an array containing pointers to 1st > linked list elements to speed lookups up), which would be a bit slower > on average perhaps, but it would behave better re deletion? This is a data structure issue, not a language issue. The tradeoffs for practical implementation include code-length, code-complexity, code-fragility, and ease of cross-platform compilation as well as classical time and space issues. tjr From bignose+hates-spam at benfinney.id.au Fri Jul 4 03:12:49 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 04 Jul 2008 17:12:49 +1000 Subject: Singleton implementation problems References: Message-ID: <87abgy2kcu.fsf@benfinney.id.au> Peter Otten <__peter__ at web.de> writes: > The problem is the structure of your program. The myset module is > imported twice by Python, once as "myset" and once as "__main__". Yes, this is the problem. Each module imports the other. > Therefore you get two distinct MySet classes, and consequently two > distinct MySet.__instance class attributes. Are you sure? This goes against my understanding: that 'import foo' will not re-import a module that's already been imported, but will instead simply return the existing module. So, I think if one evaluated 'myset is __main__', you'd find they are exactly the same module under different names; and therefore that there is only *one* instance of 'MySet', again under two names. -- \ ?Science doesn't work by vote and it doesn't work by | `\ authority.? ?Richard Dawkins, _Big Mistake_ (The Guardian, | _o__) 2006-12-27) | Ben Finney From kyrie at uh.cu Wed Jul 9 06:06:44 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 09 Jul 2008 06:06:44 -0400 Subject: Returning the positions of a list that are non-zero In-Reply-To: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> References: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> Message-ID: <1215598004.48748db468ec1@comuh.uh.cu> This could work: l = [0,0,1,2,1,0,0] indexes, values = zip(*((index,value) for index,value in enumerate(l) if value != 0)) But I guess it would be a little less cryptic (and maybe a lot more efficient) if there were an unzip function instead of using the zip(*sequence) trick. I think a more readable way would be: indexes = [index for index,value in enumerate(l) if value != 0] values = [value for value in l if value != 0] Cheers. -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie Quoting Benjamin Goudey : > I have a very large list of integers representing data needed for a > histogram that I'm going to plot using pylab. However, most of these > values (85%-95%) are zero and I would like to remove them to reduce > the amount of memory I'm using and save time when it comes to plotting > the data. To do this, I'm trying to find the best way to remove all of > the zero values and produce a list of indices of where the non-zero > values used to be. > > For example, if my original list is [0,0,1,2,1,0,0] I would like to > produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices > of where the non-zero values used to be). Removing non-zero values is > very easy but determining the indicies is where I'm having difficulty. > > Thanks in advance for any help > -- > http://mail.python.org/mailman/listinfo/python-list > From stefan_ml at behnel.de Thu Jul 3 15:04:47 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 03 Jul 2008 21:04:47 +0200 Subject: ANN: XML builder for Python In-Reply-To: References: <486C5CA1.3080105@behnel.de> <486C5D63.5030407@behnel.de> Message-ID: <486D22CF.3000505@behnel.de> Hi, Walter D?rwald wrote: > XIST has been using with blocks since version 3.0. > > Take a look at: > http://www.livinglogic.de/Python/xist/Examples.html > > > from __future__ import with_statement > > from ll.xist import xsc > from ll.xist.ns import html, xml, meta > > with xsc.Frag() as node: > +xml.XML() > +html.DocTypeXHTML10transitional() > with html.html(): > with html.head(): > +meta.contenttype() > +html.title("Example page") > with html.body(): > +html.h1("Welcome to the example page") > with html.p(): > +xsc.Text("This example page has a link to the ") > +html.a("Python home page", href="http://www.python.org/") > +xsc.Text(".") > > print node.conv().bytes(encoding="us-ascii") Interesting. Is the "+" actually required? Are there other operators that make sense here? I do not see what "~" or "-" could mean. Or is it just a technical constraint? I'm asking because I consider adding such a syntax to lxml as a separate module. And I'd prefer copying an existing syntax over a (badly) home grown one. Stefan From karthikbalaguru79 at gmail.com Thu Jul 24 05:33:01 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Thu, 24 Jul 2008 02:33:01 -0700 (PDT) Subject: Requires a character ... !! References: Message-ID: On Jul 24, 2:20 pm, Fredrik Lundh wrote: > karthikbalaguru wrote: > > I am new to python . I am face few problems related with > > python and iam trying to resolve it. > > > The below is the error that i get when i invoke my application by > > giving > > the necessary input file. > > > [root at localhost hello]# Analyzer hello_input > > Loading debug info: hello_input > > Traceback (most recent call last): > > File "/usr/local/SDK/host/bin/Analyzer", line 694, in ? > > app.dbg.readObjectInfo(elf) > > File "/usr/local/SDK/host/bin/debugprocessor.py", line 427, in > > readObjectInfo > > self.privateProcessorDwarfTree.readProcessorDwarfTree(filename) > > File "/usr/local/SDK/bin/debugprocessor.py", line 314, in > > readDwarfTree > > if "DW_OP_reg" in value: > > TypeError: 'in ' requires character as left operand > > > Is this related with the version conflicts ? > > Should i need to configure any environment variables or change some > > source code. > > You should run the code on a Python version that supports the features > your code is using. Support for arbitrary strings on the left side of > the "in" operator was added in Python 2.3, which was released in 2003. > Thx for that info. I understand. The requirements state that it needs Python 2.2, But i wonder how that program has been implemented using Python 2.3 features. Anyhow, this has to be resolved and i need your help. Kindly let me know a trick to make to resolve the 'in' operator related problem by using Python 2.2. Thx in advans, Karthik Balaguru From bronger at physik.rwth-aachen.de Thu Jul 24 05:40:46 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 24 Jul 2008 11:40:46 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> Message-ID: <874p6fzkkh.fsf@physik.rwth-aachen.de> Hall?chen! Bruno Desthuilliers writes: > [...] > > How would you handle this case with an implicit 'self' : > > class Foo(object): > pass > > def bar(self): > print self > > Foo.bar = bar Just like this. However, the compiler could add "self" to non-decorated methods which are defined within "class". Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From AWasilenko at gmail.com Thu Jul 31 00:36:51 2008 From: AWasilenko at gmail.com (Adam W.) Date: Wed, 30 Jul 2008 21:36:51 -0700 (PDT) Subject: Unicode characters, XML/RSS Message-ID: <832add51-92e1-4420-9279-5b503b453869@u6g2000prc.googlegroups.com> So I wrote a little video podcast downloading script that checks a list of RSS feeds and downloads any new videos. Every once in a while it find a character that is out of the 128 range in the feed and my script blows up: Traceback (most recent call last): File "C:\Users\Adam\Desktop\Rev3 DL\Rev3.py", line 88, in mainloop() File "C:\Users\Adam\Desktop\Rev3 DL\Rev3.py", line 75, in mainloop update() File "C:\Users\Adam\Desktop\Rev3 DL\Rev3.py", line 69, in update couldhave = getshowlst(x[1],episodecnt) File "C:\Users\Adam\Desktop\Rev3 DL\Rev3.py", line 30, in getshowlst masterlist = XMLWorkspace.parsexml(url) File "C:\Users\Adam\Desktop\Rev3 DL\XMLWorkspace.py", line 54, in parsexml parse(url, FeedHandlerInst) File "C:\Python25\lib\xml\sax\__init__.py", line 33, in parse parser.parse(source) File "C:\Python25\lib\xml\sax\expatreader.py", line 107, in parse xmlreader.IncrementalParser.parse(self, source) File "C:\Python25\lib\xml\sax\xmlreader.py", line 123, in parse self.feed(buffer) File "C:\Python25\lib\xml\sax\expatreader.py", line 207, in feed self._parser.Parse(data, isFinal) File "C:\Users\Adam\Desktop\Rev3 DL\XMLWorkspace.py", line 51, in characters self.data.append(string) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 236: ordinal not in range(128) Now its my understanding that XML can contain upper Unicode characters as long as the encoding is specified, which it is (UTF-8). The feed validates every validator I've ran it through, every program I open it with seems to be ok with it, except my python script. Why? Here is the URL of the feed in question: http://revision3.com/winelibraryreserve/ My script is complaining of the fancy e in Mourv?dre At first glance I though it was the data.append(string) that was un accepting of the Unicode, but even if I put a return in the Character handler loop, it still breaks. What am I doing wrong? From Russ.Paielli at gmail.com Sat Jul 26 23:21:17 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 26 Jul 2008 20:21:17 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <517d1643-3ae1-442b-9764-6c1847065207@p10g2000prf.googlegroups.com> On Jul 26, 7:23 pm, "Marcus.CM" > 1. python should hardcode the keyword "self". So whenever this keyword > is used, it would automatically implied that it is > referring to a class scope variable. This would be similar to how the > "this" keyword is used in C++. > > 2. Omit self from the parameter. That might make sense if you're starting from scratch on a new language, but it is not compatible with Python as it is currently stands. Yes, it could have been put into 3.0, but it's way too late now for a change that drastic. Beyond that, I don't like the idea of being forced to use "self" in every case. Yes, C++ and Java standardized on "this," but it is implied and is usually not explicitly needed. From feliphil at gmx.net Thu Jul 10 10:42:17 2008 From: feliphil at gmx.net (Wolfgang Keller) Date: Thu, 10 Jul 2008 16:42:17 +0200 Subject: Does omniORBpy 3.2 supports DII? References: Message-ID: <20080710164217.da8448a3.feliphil@gmx.net> > My apologies if this is not the correct forum for thses quiestions, It's not the wrong place to ask, but you're more likely to get answers from the omniORB mailing lists: http://www.omniorb-support.com/mailman/listinfo Sincerely, Wolfgang From tjreedy at udel.edu Tue Jul 29 15:43:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 15:43:51 -0400 Subject: Swap memory in Python ? - three questions In-Reply-To: <642068.13334.qm@web55102.mail.re4.yahoo.com> References: <642068.13334.qm@web55102.mail.re4.yahoo.com> Message-ID: Robert LaMarca wrote: > Hi, > > I am using numpy and wish to create very large arrays. My system is AMD 64 x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a 15 GB swap drive. > > The command I have been trying to use is; > g=numpy.ones([1000,1000,1000],numpy.int32) > > This returns a memory error. > A smaller array ([500,500,500]) worked fine.. > Two smaller arrays again crashed the system. > > So... I did the math. a 1000x1000x1000 array at 32 bits should be around 4gb RAM... Obviously larger than RAM, but much smaller than the swap drive. > > 1. So... does Numpy have a really lot of overhead? Or is my system just not somehow getting to make use of the 15gb swap area. > 2. Is there a way I can access the swap area, or direct numpy to do so? Or do I have to write out my own numpy cache system... > 3. How difficult is it to use data compression internally on numpy arrays? I do not know what numpy does, but constant arrays only need to store the dimensions and the constant value and have a getitem method that returns that constant value for any valid index. This is at most a few hundred bytes regardless of the dimensions. From arsyed at gmail.com Wed Jul 30 01:21:39 2008 From: arsyed at gmail.com (arsyed) Date: Wed, 30 Jul 2008 01:21:39 -0400 Subject: Dynamically adding methods to a class... In-Reply-To: <19ac19520807282117y4c34ed22n3bcb9c6cf7d198b8@mail.gmail.com> References: <19ac19520807282117y4c34ed22n3bcb9c6cf7d198b8@mail.gmail.com> Message-ID: <9a2cc7a70807292221k4dfd72a0nce0ade86e7d222f7@mail.gmail.com> On Tue, Jul 29, 2008 at 12:17 AM, Piyush Anonymous wrote: > class MyObject: > def __init__(self, name): > self.name = name > > def do_this_default(self): > print "default do_this implementation for %s" % self.name > > def custom_do_this(): #method to be added > print "custom do_this implementation for %s" % self.name > > > def funcToMethod(func,clas,method_name=None): > """Adds func to class so it is an accessible method; use method_name to > specify the name to be used for calling the method. > The new method is accessible to any instance immediately.""" > import new > method = new.instancemethod(func,None,clas) > print method > if not method_name: method_name=func.__name__ > clas.__dict__[method_name]=func > > > myobj = MyObject('myobj1') > funcToMethod(custom_do_this,MyObject) #trying 2 add method to class not > instance > print myobj.custom_do_this() > > --- > Error I am getting; > TypeError: custom_do_this() takes no arguments (1 given) > > Why am I getting it? > If your method is going to be bound to an instance, then it needs the expected signature: the first parameter is always a reference to the instance ("self"). Change it to "custom_do_this(self)" and it should work. > Also how can I do this in new style class (inherited from 'object')? > > What did you try and how did it fail? This seems to work: def foo(self): print 'foo' class Bar(object): pass Bar.foobar = new.instancemethod(foo, None, Bar) b = Bar() b.foobar() > > > -- > http://mail.python.org/mailman/listinfo/python-list > From svenn.bjerkem at googlemail.com Thu Jul 24 02:32:10 2008 From: svenn.bjerkem at googlemail.com (Svenn Are Bjerkem) Date: Wed, 23 Jul 2008 23:32:10 -0700 (PDT) Subject: Parsing VHDL with python, where to start. References: Message-ID: <31888260-86a9-46b0-b0a4-79f7852f256a@k30g2000hse.googlegroups.com> On Jul 23, 1:03 pm, christopher.saun... at durham.ac.uk (c d saunter) wrote: > How much of VHDL are you looking to parse? Are you just looking at files > intended for synthesis, or at simulation/testbench files as well? As a start I want to parse VHDL which is going to be synthesised, and I am limiting myself to the entities and the structural component placement. I will drop the processes and the concurrent assignments even if that will mask important information. It is a design viewer tool, not a design tool that I am writing. Xilinx ISE do give me the opportunity to browse my synthesised netlist, but there is simply too much information. Later the app can be extended with more functionality, depends on my success with the initial problems that I have. > If I started again I'd use pyparsing:http://pyparsing.wikispaces.com/ > > Looks like someone is already there in part:http://pyparsing.wikispaces.com/message/view/home/103973 I also got a pointer to SimpleParse and now try to translate the parts of the VHDL BNF that I need into a definition that SimpleParse can understand. But looking at the BNF it is clear that VHDL is no easy language to parse, just as it is no easy language to do structural design in. -- Svenn From vinoliya341 at gmail.com Sat Jul 19 02:12:59 2008 From: vinoliya341 at gmail.com (hot rathi) Date: Fri, 18 Jul 2008 23:12:59 -0700 (PDT) Subject: Your win 10, 000$ in my groups Pls register your name and address in below of the website http://www.geocities.com/cathrina39 Message-ID: <3ee7dc1f-38d4-431d-a0b2-93c37e4e4dad@y22g2000prd.googlegroups.com> Your win 10,000$ in my groups Pls register your name and address in below of the website http://www.geocities.com/cathrina39 From bignose+hates-spam at benfinney.id.au Wed Jul 16 05:35:35 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jul 2008 19:35:35 +1000 Subject: How can i use a variable without define it ? References: <87k5fm2p1x.fsf@benfinney.id.au> <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> Message-ID: <87fxqa2mu0.fsf@benfinney.id.au> zhw writes: > Here is a example that I want to complete: > >>> import sys, new > >>> context={"name":"david", "sex":"male"} Here you have a set of values addressible by name. > >>> sys.modules["foo"] = new.module("foo") Why do you believe you need to create a module object? > >>> import foo > >>> for attr in context: > setattr(foo, attr, context[attr]) This doesn't appear to get you anything that isn't already available with the 'context' mapping. > >>> def bar(): > # here is a error > # import * only allowed at module level > from foo import * > print name, sex You can simply do: >>> context = {'name': "david", 'sex': "male"} >>> def bar(): ... print context['name'], context['sex'] ... >>> bar() david male Or, more flexible and more explicit: >>> foo = {'name': "david", 'sex': "male"} >>> def bar(context): ... print context['name'], context['sex'] ... >>> bar(foo) david male What problem are you trying to solve? -- \ ?The best mind-altering drug is truth.? ?Jane Wagner, via Lily | `\ Tomlin | _o__) | Ben Finney From straton at lampsacos.demon.co.uk Tue Jul 15 16:56:53 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Tue, 15 Jul 2008 21:56:53 +0100 Subject: Measure class, precision, significant digits, and divmod() In-Reply-To: References: Message-ID: Ethan Furman wrote: > Hey all. > > > As I have mentioned before, I am making this Measure class for two > reasons: experience with unit testing, I like playing with numbers, I > am unaware of anything like this having yet been done (okay, three > reasons ;). > > > Any and all feedback welcome, particularly from anyone who might > actually use the Measure class. ;) > > ~Ethan I have been following this thread with interest, because i am doing something similar, namely writing python to provide myself with experience with unit tests and i like playing with numbers. In my case the numbers are 'long rationals' (infinite precision) and will include both floats, the decimal type, extended 'decimals' -- i.e. possibly with a repeating expansion (or in any base) -- and finite continued fractions as derived classes. I also hope to deal with repeating continued fractions later. +++++++++++++++++++++++++++++++++++++++ My principal interest in your work, however, is in the use of unit tests as a pedagogical method of teaching programming, whether self-taught or taught by an instructor. The students would be taught how to __run__ a unit test-suite at as early an opportunity as possible. I can't see why an eleven or twelve year old should not be able to cope with it in hour one or two of a carefully structured course. What is needed for such an approach is a copy--in a public place--of your unit tests for all methods that are really part of the funtionality; together with blanked-out definitions for them (i.e just the first line, any in-code documentation, and 'pass' ). You would not include any 'internal' methods that are merely the way __you__ happened to achieve the result. The programming 'exercise' would then be for the students, or groups of students, to roll their own version until their code passed all the unit tests. From tim.tadh at gmail.com Tue Jul 29 11:25:34 2008 From: tim.tadh at gmail.com (Tim Henderson) Date: Tue, 29 Jul 2008 08:25:34 -0700 (PDT) Subject: DB access without object-relation mapping? References: Message-ID: On Jul 29, 11:20?am, kj wrote: > Python noob here. > > I want to write a script that creates and populates a simple Postgres > database. > > The word on the street is to use something like SQLAlchemy for > database access in Python, but my experience in the past with > packages that perform automated SQL generation has been awful, so > I always return to lighter-weight solutions that allow me to write > my own SQL. ?(E.g. when coding in Perl I've used Perl's DBI package > and drivers, rather than the likes of Class::DBI.) ?So what's the > standard Python way to send SQL directly to a Postgres database > and get back results? > > TIA! > > kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. Hi, I believe there are a couple of options but pyscopg, and PyGreSQL seem to be popular. Tim From thogiti at gmail.com Mon Jul 7 16:31:31 2008 From: thogiti at gmail.com (Nagu) Date: Mon, 7 Jul 2008 13:31:31 -0700 (PDT) Subject: Memory error while saving dictionary using pickle Message-ID: I am trying to save a dictionary of size 65000X50 to a local file and I get the memory error problem. How do I go about resolving this? Is there way to partition the pickle object and combine later if this is a problem due to limited resources (memory) on the machine (it is 32 bit machine Win XP, with 4GB RAM). Please advice. Thank you, Nagu Here is the detail description of the error: Traceback (most recent call last): File "", line 1, in s = pickle.dumps(itemsim) File "C:\Python25\lib\pickle.py", line 1366, in dumps Pickler(file, protocol).dump(obj) File "C:\Python25\lib\pickle.py", line 224, in dump self.save(obj) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "C:\Python25\lib\pickle.py", line 663, in _batch_setitems save(v) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 600, in save_list self._batch_appends(iter(obj)) File "C:\Python25\lib\pickle.py", line 615, in _batch_appends save(x) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 562, in save_tuple save(element) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 477, in save_float self.write(FLOAT + repr(obj) + '\n') MemoryError: out of memory From norseman at hughes.net Tue Jul 15 14:48:00 2008 From: norseman at hughes.net (norseman) Date: Tue, 15 Jul 2008 11:48:00 -0700 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> <8a07445a-3ca8-4373-9312-cea8db83ec5c@l64g2000hse.googlegroups.com> <9f3c45f1-9cb2-46c1-838b-716180061956@e39g2000hsf.googlegroups.com> Message-ID: <487CF0E0.7000807@hughes.net> Mensanator wrote: > On Jul 15, 12:36 pm, defn noob wrote: >> On Jul 15, 7:28 pm, Mensanator wrote: >> >> >> >> >> >>> On Jul 15, 11:26 am, defn noob wrote: >>>> isPrime works when just calling a nbr but not when iterating on a >>>> list, why? adding x=1 makes it work though but why do I have to add >>>> it? >>>> Is there a cleaner way to do it? >>>> def isPrime(nbr): >>>> for x in range(2, nbr + 1): >>>> if nbr % x == 0: >>>> break >>>> if x == nbr: >>>> return True >>>> else: >>>> return False >>>>>>> [isPrime(y) for y in range(11)] >>>> Traceback (most recent call last): >>>> File "", line 1, in >>>> [isPrime(y) for y in range(11)] >>>> File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime >>>> if x == nbr: >>>> UnboundLocalError: local variable 'x' referenced before assignment >>>>>>> map(isPrime, range(100)) >>>> Traceback (most recent call last): >>>> File "", line 1, in >>>> map(isPrime, range(100)) >>>> File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime >>>> if x == nbr: >>>> UnboundLocalError: local variable 'x' referenced before assignment>>> isPrime(10) >>>> False >>>>>>> isPrime(11) >>>> True >>>> adding x=1 makes it work though: >>>> def isPrime(nbr): >>>> x=1 >>>> for x in range(2, nbr + 1): >>>> if nbr % x == 0: >>>> break >>>> if x == nbr: >>>> return True >>>> else: >>>> return False >>>>>>> [isPrime(y) for y in range(11)] >>>> [False, True, True, True, False, True, False, True, False, False, >>>> False] >>> No, it doesn't. You are falsely reporting that 1 is prime. >>> And instead of making the fake variable x, shouldn't you >>> instead test that nbr+1 is greater than 2? Or call it with >>> range(3,11) instead of range(11)? x isn't initialized >>> because if nbr+1 is <=2, the for loop has an invalid range >>> and doesn't even execute. >> def isPrime(nbr): >> for x in range(2, nbr + 1): >> if nbr % x == 0: >> break >> if x == nbr: >> return True >> else: >> return False >> >> this works for all primes, if i want to not include 1 i just do if >> nbr<=1 return false >> >> you are answering the wrong question. > > No, I also mentioned the for loop having an invalid range, > which is why your original failed. > > Pointing out that 1 isn't prime was a bonus. > >> anyway here is a clear one: >> def isPrime(nbr): >> if nbr < 2: >> return False >> for x in range(2, nbr + 1): >> if nbr % x == 0: >> return nbr == x > > I suppose you're not interested in knowing you don't > have to test anything higher than the square root of > the number. > > -- > http://mail.python.org/mailman/listinfo/python-list > =========================== "don't...test...higher than the square root..." I wondered when that was going to show up. I too had a good math teacher. Steve norseman at hughes.net From fuzzyman at gmail.com Tue Jul 29 16:02:59 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Tue, 29 Jul 2008 13:02:59 -0700 (PDT) Subject: Questions on 64 bit versions of Python References: <488aec52$0$21481$9b622d9e@news.freenet.de> <488B570C.8070202@v.loewis.de> Message-ID: On Jul 26, 8:02?pm, Rob Williscroft wrote: > Martin v. L?wis wrote innews:488B570C.8070202 at v.loewis.dein > comp.lang.python: > > >> I just tested, I built a default C# forms app using the "AnyCPU" > >> option and it ran as a 64 bit app (no *32 in Task Manager), this is > >> on XP64. > > >> I have though installed the AMD64 version of the 2.0 framework and > >> AFAICT neither windows update or the Visual Studio installer > >> will install that by default, you have to go get it your self. > > > Interesting. I only tested this in .NET 1.1. Perhaps they have changed > > something since. How exactly did you launch the program? Does it change > > if you use Python's os.spawn* to launch it? > > If subprocess.call will do then I can report the same results, a > 64 bit process, using 32 bit CPython 2.5 to call it. > > Also if the programme (C#) is built with the 3.5 framework I > get the same results, however interestingly there is no 64 bit > build for the 3.5 framework (or at least I was unable to find one). > > Rob. > --http://www.victim-prime.dsl.pipex.com/ .NET 3.5 is a set of extension assemblies and does not change the underlying runtime - so there is probably no need for a separate 63 bit build for .NET 3.5. Michael Foord -- http://www.ironpythoninaction.com/ From bj_666 at gmx.net Sun Jul 20 01:17:14 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Jul 2008 05:17:14 GMT Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> <6ebshqF67cpfU4@mid.uni-berlin.de> <5d6b8066-c941-4f0c-abea-20baed33b4ab@l64g2000hse.googlegroups.com> Message-ID: <6eg02pF6uhc3U2@mid.uni-berlin.de> On Sat, 19 Jul 2008 13:13:40 -0700, nicolas.pourcelot wrote: > On 18 juil, 17:52, Marc 'BlackJack' Rintsch wrote: >> On Fri, 18 Jul 2008 07:39:38 -0700, nicolas.pourcelot wrote: >> > So, I use something like this in 'sheet.objects.__setattr__(self, >> > name, value)': >> > if type(value) == Polygon: >> > ? ? for edge in value.edges: >> > ? ? ? ? if edge is_in sheet.objects.__dict__.itervalues(): >> > ? ? ? ? ? ? object.__setattr__(self, self.__new_name(), edge) >> >> > Ok, I suppose it's confused, but it's difficult to sum up. ;-) >> >> You are setting attributes with computed names? ?How do you access them? >> Always with `gettattr()` or via the `__dict__`? ?If the answer is yes, why >> don't you put the objects the into a dictionary instead of the extra >> redirection of an objects `__dict__`? >> > > Yes, I may subclass dict, and change its __getitem__ and __setitem__ > methods, instead of changing objets __setattr__ and __getattr__... But > I prefer >>>> sheet.objects.A = Point(0, 0) > than >>>> sheet.objects["A"] = Point(0, 0) But with computed names isn't the difference more like setattr(sheet.objects, name, Point(0, 0)) vs. sheet.objects[name] = Point(0, 0) and getattr(sheet.objects, name) vs. sheet.objects[name] Or do you really have ``sheet.objects.A`` in your code, in the hope that an attribute named 'A' exists? >> Oh and the `type()` test smells like you are implementing polymorphism >> in a way that should be replaced by OOP techniques. > > I wrote 'type' here by mistake, but I used 'isinstance' in my code. ;-) Doesn't change the "code smell". OOP approach would be a method on the geometric objects that know what to do instead of a type test to decide what to do with each type of geometric object. Ciao, Marc 'BlackJack' Rintsch From upton at virginia.edu Wed Jul 30 14:16:32 2008 From: upton at virginia.edu (Dan Upton) Date: Wed, 30 Jul 2008 14:16:32 -0400 Subject: How can I check nbr of cores of computer? In-Reply-To: <4890acd6$0$17215$742ec2ed@news.sonic.net> References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> <4890acd6$0$17215$742ec2ed@news.sonic.net> Message-ID: <5504f9ac0807301116i3907b46l383ed0dd683edfd1@mail.gmail.com> On Wed, Jul 30, 2008 at 2:22 PM, John Nagle wrote: > defn noob wrote: >> >> How can I check how many cores my computer has? >> Is it possible to do this in a Python-app? > > Why do you care? Python can't use more than one of them at > a time anyway. Per Python process, but you might fork multiple processes and want to know how many cores there are to know how many to fork, and which cores to pin them to. (I don't know if there's a direct way in Python to force it to a certain core, so I instead just wrote an extension to interface with sched_setaffinity on Linux.) On Linux, an almost assuredly non-ideal way to find out the number of cores is to read /proc/cpuinfo and look for the highest-numbered "processor: " line (and add 1). From larzluv at hotmail.com Thu Jul 17 12:40:15 2008 From: larzluv at hotmail.com (Larry Hale) Date: Thu, 17 Jul 2008 09:40:15 -0700 (PDT) Subject: Python Behind a Squid Corporate Proxy on Windows References: <7b541a3b-846f-496a-aee1-d5719217e011@m45g2000hsb.googlegroups.com> Message-ID: <821d7616-3faa-4dae-a988-18caf4f8598a@8g2000hse.googlegroups.com> Err, the line above should be: proxy_handler = urllib2.ProxyHandler( { "http": "http:// myusername:password at webfilter.xyz.local:3128" } ) (Sorry! :) From bj_666 at gmx.net Fri Jul 4 05:50:50 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 Jul 2008 09:50:50 GMT Subject: compatible image type References: Message-ID: <6d6a3qF134f0U1@mid.uni-berlin.de> On Fri, 04 Jul 2008 01:15:30 -0700, gordon wrote: > then later on i want to create a Photoimage using > > ImageTk.PhotoImage(file=pathname) and display it on a canvas. > > the extn can be anything ..even zip or bat ,doc whatever depending on > user selection...I want to put someway to raise an error message to > the user if he selects a file with extension not of a compatible image > type for PhotoImage.How should i do this? should i check 'extn' to a > list of compatible image type extensions(something like > [''jpg','jpeg','png','gif'...] ) or is there a better way? Just catch the exception raised by `PhotoImage` if a non compatible file was selected!? Ciao, Marc 'BlackJack' Rintsch From fredrik at pythonware.com Wed Jul 23 08:35:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 14:35:11 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> <216dcee8-ad3d-4ae1-ac4a-4f4819775c7e@d1g2000hsg.googlegroups.com> Message-ID: Jaco Naude wrote: > Fredrik, thanks for the help. I'm not sure why but it seems to work > now even if I don't include the extern "C" command. It also works with > both Python.h files (after I copied pyconfig.h from the PC folder). So > it seems like everything is working now. As it's supposed to do. It's times like this that you really want to use a system that takes snapshots of every single revision of the files you work on, so you can see what exactly it was you had done when it didn't work (it's more often a "do'h" thing than a heisenbug ;-). (fwiw, I'm currently trying to track down a problem at a customer site when the entire Python application managed to remove itself during a test run; the program crashed with "zipimport: IOError" when they tried to use a part of the system that did some lazy imports, and when they tried to restart the program, neither the startup script nor the ZIP archive that contained the bulk of the application were anywhere to be seen. Other PY files in the same directory were left intact. Fully patched Windows XP, clean bill of health from a virus scanner. If anyone's ever experienced anything similar, let me know.) From cwitts at gmail.com Thu Jul 17 05:03:26 2008 From: cwitts at gmail.com (Chris) Date: Thu, 17 Jul 2008 02:03:26 -0700 (PDT) Subject: Remove some characters from a string References: <35cff1a6-74f6-4a68-b81e-71d8ff9c4633@a70g2000hsh.googlegroups.com> Message-ID: <1329a007-e4e3-442a-b546-a14a94410937@r66g2000hsg.googlegroups.com> On Jul 17, 10:13?am, Julien wrote: > Hi, > > I can't seem to find the right regular expression to achieve what I > want. I'd like to remove all characters from a string that are not > numbers, letters or underscores. > > For example: > > >>> magic_function('si_98%u^d at .as-*gf') > > str: 'si_98udasgf' > > Would you have any hint? > > Thanks a lot! > > Julien One quick and dirty way would be... import string safe_chars = string.ascii_letters + string.digits + '_' test_string = 'si_98%u^d at .as-*gf' ''.join([char if char in safe_chars else '' for char in test_string]) you could also use a translation table, see string.translate (the table it uses can be made with string.maketrans) From mattheww at chiark.greenend.org.uk Wed Jul 30 15:55:03 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 30 Jul 2008 20:55:03 +0100 (BST) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: Terry Reedy wrote: >Carl Banks wrote: >> That's not what I was asking for. I was asking for a use case for "if >> x" that can't be replaced by a simple explicit test. Your example >> didn't satisfy that. > But I believe my example of an iterator with __bool__ but not with > __len__ does. On the other hand, iterators provide a clear example of problems with "if x": __nonzero__ for iterators (in general) returns True even if they are 'empty'. For example, this function (which attempts to avoid making an expensive call when not necessary) is buggy, but easy to write if you've been taught that "if x" will work with any kind of object. def frob(widgets, power): if widgets: frobber = Frobber(power) # expensive call for widget in widgets: frobber.frob(widget) -M- From KDawg44 at gmail.com Wed Jul 16 15:11:28 2008 From: KDawg44 at gmail.com (KDawg44) Date: Wed, 16 Jul 2008 12:11:28 -0700 (PDT) Subject: New to Python - Accessing Lotus Notes Message-ID: Hi, We have a Lotus Notes Database that tracks time spent on projects. What I would like to do is develop a Time Tracker in Python that communicates with the server. This would pull projects in and allow a use to start a timer as he/she works on a given project. The user would then be able to commit this back to the database (thus, preventing them from having to go to the calendar view and pick the project and enter the hours). As another potential feature, I would like the user to be able to create projects in the app and track time and then when a project exists in the database, it would retroactively add those hours (users cannot create their own projects and sometimes managers take some time to actually get a project in the system). Lasty, the user could run a report by date to get their hours on each project. Anyway, long story short, how can I communicate with Lotus Notes to accomplish these tasks? Lotus Notes 7. Thank you for your help. I am very new to Python and am hoping to learn a lot from this project so I can incorporate Python into my daily tasks. Also, forgive my rant as I figured out some of my specs as I typed this. Thanks again. Kevin From d3vvnull at gmail.com Fri Jul 4 15:18:09 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 4 Jul 2008 14:18:09 -0500 Subject: Getting a path from a file object In-Reply-To: <3c500ce7-c697-44e9-9f13-f65edc509e1c@a32g2000prf.googlegroups.com> References: <3c500ce7-c697-44e9-9f13-f65edc509e1c@a32g2000prf.googlegroups.com> Message-ID: <170543c70807041218g6a8324e2k3d6fca321504a742@mail.gmail.com> f.name will return the path. But if you want to guarantee getting the absolute pathname use os.path.abspath >>> import os >>> os.path.abspath(f.name) '/some/path/file.ext' On Fri, Jul 4, 2008 at 1:37 PM, Andrew Fong wrote: > Newbie question: > > Let's say I open a new file for writing in a certain path. How do I > get that path back? > > Example: > > >>> f = open('/some/path/file.ext') > >>> some_function(f) > '/some/path/file.ext' > > Does some_function(f) already exist? And if not, how would I define > it? > > -- Andrew > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon Jul 28 01:32:13 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 28 Jul 2008 01:32:13 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <20080728033918.GG7373@dragontoe.org> References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <20080728033918.GG7373@dragontoe.org> Message-ID: Derek Martin wrote: > Furthermore, as you described, defining the function within the scope > of a class binds a name to the function and then makes it a method of > the class. Once that happens, *the function has become a method*. If you mean that a user-defined function object becomes a different class of object when bound to a class attribute name, that is wrong. Once a function, always a function. It may be called an 'instance method' but it is still a function. Any function object can be an attribute of multiple classes, without inheritance, or of none. When a function attribute is accessed via an instance of the class, it is *wrapped* with a bound method object that basically consists of references to the function and instance. When the 'bound method' is called, the instance is inserted in front of the other arguments to be matched with the first parameter. In 2.0, functions accessed through the class were rather uselessly wrapped as an 'unbound method', but those wrappers have been discarded in 3.0. > To be perfectly honest, the idea that an object method can be defined > outside the scope of an object (i.e. where the code has no reason to > have any knowledge of the object) seems kind of gross to me... I happen to like the simplicity that "def statements (and lambda expressions) create function objects." Period. ... > It does indeed -- it does more than imply. It states outright that > the function is defined within the namespace of that object, True. > and as such that it is inherently part of that object. False. That does not follow. Python objects generally exist independently of each other. Think of them as existing in a nameless dataspace if you want. Collection/container objects collect/contain references to their members, just as a club roster does, but they only metaphorically 'contain' their members. Any object can be a member of any number of collections, just as humans can join any number of clubs and groups. In mathematical set theory, membership is also non-exclusive. > So why should it need > to be explicitly told about the object of which it is already a part? Because it is not a 'part' of a class in the sense you seem to mean. What is true is that functions have a read-only reference to the global namespace of the module in which they are defined. But they do not have to be a member of that namespace. Terry Jan Reedy From george.sakkis at gmail.com Thu Jul 3 21:15:57 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 3 Jul 2008 18:15:57 -0700 (PDT) Subject: Singleton implementation problems References: Message-ID: <9ce89515-bb8a-455b-9f8c-ff95e9fb6265@c58g2000hsc.googlegroups.com> On Jul 3, 6:58 pm, Urizev wrote: > Hi everyone > > I have developed the singleton implementation. However I have found a > strange behaviour when using from different files. The code is > attached. > > Executing main > new MySet object > No singleton instance > New singleton: > <__main__.Singleton instance at 0x2b98be474a70> > new MySet object > There is a singlenton instance > new Member > new MySet object > No singleton instance > New singleton: > > new Member > new MySet object > There is a singlenton instance > new Member > new MySet object > There is a singlenton instance > > I do not know why, but it creates two instances of the singleton. Does > anybody know why? Because __init__() is called to initialize the state of an object *after* it has already been created. You should create a "new-style" class and define __new__() instead. Here's a working version: class Singleton(object): # new-style class def __new__(cls, *args, **kwds): # return the singleton (if already created) try: return cls.__dict__['__singleton'] except KeyError: # raised only the first time for a given class # create the singleton and store it to the class namespace singleton = object.__new__(cls, *args, **kwds) setattr(cls, '__singleton', singleton) return singleton class X(Singleton): def __init__(self, a): self.a = a assert X(1) is X(2) Note however that the classic Singleton pattern is usually frowned upon in Python; the preferred approach is to use (module level) globals. Also search for the "Borg pattern". George From ppearson at nowhere.invalid Mon Jul 7 00:09:08 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 7 Jul 2008 04:09:08 GMT Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> Message-ID: <6ddj74F21uhjU1@mid.individual.net> On Sun, 06 Jul 2008 23:42:26 +0200, TP wrote: > > $ python -c "print '\033[30;44m foo \033[0m'" [writes an escape sequence to stdout] > $ echo -e $esc$ColorBlackOnDarkblue foo $esc$ColorReset [also writes an escape sequence to stdout] > $ echo -n $esc$ColorBlackOnDarkblue foo $esc$ColorReset > \033[30;44m foo \033[0m [snip, shuffle] > $ export esc="\033" > $ export ColorBlackOnDarkblue="[30;44m" > $ export ColorReset="[0m" > > import os > Color = os.environ['ColorBlackOnDarkblue'] > ColorReset = os.environ['ColorReset'] > Esc = os.environ['esc'] > print '%s%s%s%s%s' % (Esc, Color, " foo ", Esc, ColorReset) [snip] > $ python color.py > \033[30;44m foo \033[0m The string "\033" is 4 characters long. Your shell variable "esc" is 4 characters long. Your Python program prints those four characters. You want it to re-interpret those 4 characters into a single escape character. One of this group's regular participants can (I hope) tell us three breathtakingly elegant ways to do that. I'm sorry I can't. When you run echo, it recognizes the 4-character "esc" as a convention for representing a single character, and performs the re-interpretation for you. When you tell python "print '\033[30;44m foo \033[0m'", python interprets the "\033" as a single character. -- To email me, substitute nowhere->spamcop, invalid->net. From circularfunc at yahoo.se Thu Jul 3 14:02:42 2008 From: circularfunc at yahoo.se (defn noob) Date: Thu, 3 Jul 2008 11:02:42 -0700 (PDT) Subject: manipulating movie files with Python References: Message-ID: <08cfeaab-33fc-4ae8-a502-6b2682d913b7@59g2000hsb.googlegroups.com> I would love the same thing. Dont know what you are doing but this might be relevant even if it is not what you are asking for: http://imdbpy.sourceforge.net/ library to take data from imdb. From gandalf at shopzeus.com Thu Jul 3 06:40:27 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 03 Jul 2008 12:40:27 +0200 Subject: multithreading in python ??? In-Reply-To: <674A912AA405814397CED58601AC8E251554964241@BLRKECMBX05.ad.infosys.com> References: <674A912AA405814397CED58601AC8E251554964241@BLRKECMBX05.ad.infosys.com> Message-ID: <486CAC9B.9000902@shopzeus.com> Abhishek Asthana wrote: > > Hi all , > > I have large set of data computation and I want to break it into > small batches and assign it to different threads .I am implementing it > in python only. Kindly help what all libraries should I refer to > implement the multithreading in python. > You should not do this. Python can handle multiple threads but they always use the same processor. (at least in CPython.) In order to take advantage of multiple processors, use different processes. L From mail at timgolden.me.uk Wed Jul 16 07:43:37 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 12:43:37 +0100 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: <8AEDA5E3386EA742B8C24C95FF0C758004623111@PDC-MAIL3.ubisoft.org> References: <8AEDA5E3386EA742B8C24C95FF0C758004623111@PDC-MAIL3.ubisoft.org> Message-ID: <487DDEE9.8060305@timgolden.me.uk> Andreas Tawn wrote: > Terry Reedy wrote: >> Wrong. > Thank you. > >> For loop variables continue after the loop exits. This is >> intentional. > I never knew that and I can't find reference to it in the docs. Interesting starting point. It never occurred to me that they might not. (So I didn't look for anything in the docs when they did :) ). TJG From ki4yjl at gmail.com Sat Jul 12 12:15:06 2008 From: ki4yjl at gmail.com (WDC) Date: Sat, 12 Jul 2008 09:15:06 -0700 (PDT) Subject: Using the Random Module. References: Message-ID: <63412f78-e3ba-4c68-9956-1b4562e59778@s50g2000hsb.googlegroups.com> On Jul 12, 10:06?am, Steven D'Aprano wrote: > On Fri, 11 Jul 2008 12:27:32 -0700, castironpi wrote: > > You want a random integer. ?Is there a range you want it in? > > > Past a certain point, you'll exceed the granularity of the random number > > generator, and some values in the range will never be generated. > > You might want to produce an unbounded random integer, where *every* > integer has a chance to be returned: > > def unbounded_randint(): > ? ? i = 0 > ? ? while True: > ? ? ? ? if random.random() < 0.5: > ? ? ? ? ? ? return i > ? ? ? ? i += 1 > > This returns 0 with probability 1/2, 1 with probability 1/4, 2 with > probability 1/8, etc. The probability distribution is centered close to > zero (the mode and median are both zero, and I'm too lazy to calculate > the mean) and it has an infinitely long tail. > > -- > Steven Thanks Steven. I like how that bit works. No range in particular. I was just wondering if there was a better way than what I had been doing. Thanks for help. From floris.bruynooghe at gmail.com Mon Jul 28 07:55:21 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Mon, 28 Jul 2008 04:55:21 -0700 (PDT) Subject: Module clarification References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> Message-ID: <896c547e-9fa1-4f84-8c9b-53a96e70246c@y21g2000hsf.googlegroups.com> On Jul 28, 9:54?am, Hussein B wrote: > Hi. > I'm a Java guy and I'm playing around Python these days... > In Java, we organize our classes into packages and then jarring the > packages into JAR files. > What are modules in Python? An importable or runable (i.e. script) collection of classes, functions, variables etc... > What is the equivalent of modules in Java? Don't know. Not even sure if it exists, but my Java is old and never been great. > Please correct me if I'm wrong: > I saved my Python code under the file ? Wow.py > Wow.py is now a module and I can use it in other Python code: > import Wow Indeed, you can now access things defined in Wow as Wow.foo Regards Floris From larry.bates at websafe.com` Wed Jul 9 12:09:07 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 09 Jul 2008 11:09:07 -0500 Subject: Determining when a file has finished copying In-Reply-To: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> Message-ID: writeson wrote: > Hi all, > > I'm writing some code that monitors a directory for the appearance of > files from a workflow. When those files appear I write a command file > to a device that tells the device how to process the file. The > appearance of the command file triggers the device to grab the > original file. My problem is I don't want to write the command file to > the device until the original file from the workflow has been copied > completely. Since these files are large, my program has a good chance > of scanning the directory while they are mid-copy, so I need to > determine which files are finished being copied and which are still > mid-copy. > > I haven't seen anything on Google talking about this, and I don't see > an obvious way of doing this using the os.stat() method on the > filepath. Anyone have any ideas about how I might accomplish this? > > Thanks in advance! > Doug The best way to do this is to have the program that copies the files copy them to a temporarily named file and rename it when it is completed. That way you know when it is done by scanning for files with a specific mask. If that is not possible you might be able to use pyinotify (http://pyinotify.sourceforge.net/) to watch for WRITE_CLOSE events on the directory and then process the files. -Larry From bearophileHUGS at lycos.com Wed Jul 30 11:10:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 30 Jul 2008 08:10:11 -0700 (PDT) Subject: Pointers/References in Python? References: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Message-ID: boblatest: > I have a long list of memory-heavy objects that I would like to access > in differently sorted order. Let's say I'd like to have lists called > by_date or by_size that I can use to access the objects in the > specified order. Just create a new list with a different sorting order, for example using: from operator import attrgetter by_date = sorted(input_data, key=attrgetter("date")) by_size = sorted(input_data, key=attrgetter("size")) Python doesn't copy by value by default, so you end having just a light list of references. To understand the situation better, there's a FAQ about how Python associates names to things. Bye, bearophile From larry.bates at websafe.com` Mon Jul 21 23:52:50 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 22:52:50 -0500 Subject: Website Creation using Python In-Reply-To: References: Message-ID: Amie wrote: > Afternoon, > > I would like some help on how to create a website using the python > programming language. > I've tried using enamel, but had some problems because I could not > create html tables and intergrating it with python, like you use it > when coding in php. > > Any help would be appreciated. > > Thanks Python is not PHP. Page generation is done differently. You might take a look at Django's web framework: http://www.djangoproject.com/ or http://pylonshq.com/ WARNING - Python web frameworks are MUCH more powerful than just using PHP to place some dynamic content on a web page. For many people, PHP will still be an easy to implement solution if your project isn't very complex. As the complexity grows, the need for additional power and flexibility grows also. -Larry From jonas.esp at googlemail.com Sun Jul 13 19:21:11 2008 From: jonas.esp at googlemail.com (Kless) Date: Sun, 13 Jul 2008 16:21:11 -0700 (PDT) Subject: Dictionary bidirectional Message-ID: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> I need a dictionary where get the result from a 'key' (on left), but also from a 'value' (on right), how to get it? I know that dictionaries aren't bidirectional, but is there any way without use two dictionaries? Thanks in advance! From d3vvnull at gmail.com Tue Jul 1 22:18:33 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Tue, 1 Jul 2008 21:18:33 -0500 Subject: Classes for processing/parsing Wiki Markup text In-Reply-To: References: <170543c70807010931x16938234n9df68ee3c6d0319a@mail.gmail.com> Message-ID: <170543c70807011918t2644fdd5mad09a6433d6e6f45@mail.gmail.com> Thanks! This looks like just what I need! :) On Tue, Jul 1, 2008 at 1:25 PM, Joshua Kugler wrote: > Michael Mabin wrote: > > > Does anyone know if there are any generally available classes for parsing > > various wiki markup formats? > > Several here: > > http://pypi.python.org/pypi?%3Aaction=search&term=wiki&submit=search > > I'm sure you could find a good one, and add your own markup if needed. > > j > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From code at pizzashack.org Fri Jul 18 17:28:32 2008 From: code at pizzashack.org (Derek Martin) Date: Fri, 18 Jul 2008 17:28:32 -0400 Subject: Multiple variable control in for loops. Doable in Python? In-Reply-To: <28efa6970807181221o67c90575w690464f1442dc47d@mail.gmail.com> References: <28efa6970807181221o67c90575w690464f1442dc47d@mail.gmail.com> Message-ID: <20080718212832.GA1994@dragontoe.org> On Fri, Jul 18, 2008 at 12:21:49PM -0700, mark floyd wrote: > I'm new to Python and have been doing work converting a few apps > from Perl to Python. I can not figure out the comparable Python > structures for multi-variable for loop control. [...] > I spent a good part of yesterday looking for a way to handle this > style for loop in Python and haven't been able to find an > appropriate way to handle this control style. One wonders why... :) > We have this style for loop all over the place and not being able to > find a similar structure in Python could be a problem. Any pointers > to a Python equivalent structure would be much appreciated Even if Python didn't offer a way to write a for loop in a similar fashion (someone else replied about that already), why should it be a problem? In general control structures can be rewritten as some other kind of control structure. For example, this does exactly what your for loop examples do: i = 0 j = 0 while i < 5 and j < 10: print i, j i += 1 j += 1 Though, this example is silly, as it will always terminate after the 5th iteration of the loop, and there is no need to have j being used as a control variable... it's termination condition will never be met. Though the example illustrates the techique, even if the example is bogus. Another way is to use functions to modify the values of i and j. Writing your loops this way, you can have as many control variables as you need, and your formula for incrementing those control variables can be as varied as complicated as you can imagine. def some_increment_function(i): # Do some complicated processing of i i = ... return i def other_incrjmental_function(j): # Do some complicated processing of j j = ... return j i = 0 j = 0 while i < 5 and j < 10: print i, j i = some_increment_function(i) j = other_increment_function(j) And of course, you could also replace the loop terminating conditions with functions that return a value which can be interpreted as a truth value. If you wanted to get really crazy, you could even code the control structure as a recursive function: def control(i, j): print i,j if not (i < 5 or j < 10): return else: control(some_increment_function(i), other_increment_function(j)) Should you really write control structures this way, generally? Absolutely not (unless you're writing LISP or Scheme :)). But the point is, even if a given language doesn't have a particular syntactic element that you're looking for, it's pretty much guaranteed to provide a way to do what you're trying to do. You just need to stop thinking about your problem in terms of a particular syntactic element, and start thinking about it in more general terms of what you are actually trying to accomplish, and apply whatever syntax (usually one of several) your language provides to do that. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From malaclypse2 at gmail.com Wed Jul 30 11:10:25 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 30 Jul 2008 11:10:25 -0400 Subject: Python parsing iTunes XML/COM In-Reply-To: <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Message-ID: <16651e80807300810l2ac2eba6tc5bb900e99a8dd@mail.gmail.com> On Wed, Jul 30, 2008 at 10:58 AM, william tanksley wrote: > Here's one example. The others are similar -- they have the same > things that look like problems to me. > > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" > > Note some problems here: > > 1. This isn't Unicode; it's missing the u"" (I printed using repr). > 2. It's got the UTF-8 bytes there in the middle. > > I tried doing track_id.encode("utf-8"), but it doesn't seem to make > any difference at all. I don't have anything to say about your iTunes problems, but encode() is the wrong method to turn a byte string into a unicode string. Instead, use decode(), like this: >>> track_id = "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" >>> utrack_id = track_id.decode('utf-8') >>> type(utrack_id) >>> print utrack_id Buffett Time - Annual Shareholders L.mp3 >>> print repr(utrack_id) u'Buffett Time - Annual Shareholders\xa0L.mp3' >>> -- Jerry From alif016 at gmail.com Fri Jul 18 11:18:13 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Fri, 18 Jul 2008 10:18:13 -0500 Subject: x, = y (???) In-Reply-To: References: Message-ID: <4880B435.8010200@gmail.com> kj wrote: > > I just came across an assignment of the form > > x, = y > > where y is a string (in case it matters). > > 1. What's the meaning of the comma in the LHS of the assignment? > 2. How could I have found this out on my own? > > (Regarding (2) above, I consulted the index of several Python > reference books but I could not find the answer to (1). I hope to > find a better Python reference!) > > TIA! > > kynn > Try this: >>> y = 'abc' >>> type(y) >>> type((y,)) >>> y = y, # y, is just short for (y,) you *have* to use a coma in 1 length tuples >>> y ('abc',) >>> type(y) >>> y[0] 'abc' >>> x, = y #same as x = y[0] OR more verbosely (x,) = (y,) >>> x 'abc' >>> type(x) Maybe that will hape you understand what the comma is for? From maric at aristote.info Thu Jul 31 11:31:44 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 31 Jul 2008 17:31:44 +0200 Subject: Difference between type and class In-Reply-To: <87r69a85ek.fsf@nokile.rath.org> References: <87myjy2vc6.fsf@nokile.rath.org> <87r69a85ek.fsf@nokile.rath.org> Message-ID: <200807311731.45441.maric@aristote.info> Le Thursday 31 July 2008 17:00:51 Nikolaus Rath, vous avez ?crit?: > > There are some confusion about the terms here. > > > > Classes are instances of type 'type', > > Could you please clarify what you mean with 'instance of type X'? I > guess you mean that 'y is an instance of type X' iif y is constructed > by instantiating X. Is that correct? > Correct, you can verify this with the isinstance builtin : >>>[1]: isinstance(int(), int) ...[1]: True >>>[2]: isinstance(int, object) ...[2]: True >>>[3]: isinstance(int, type) ...[3]: True >>>[4]: class A(object) : pass ...: >>>[5]: isinstance(A, type) ...[5]: True > > What the means is that int is not a user type but a > > builtin type, instances of int are not types (or classes) but common > > objects, so its nature is the same as any classes. > > > > The way it prints doesn't matter, it's just the __repr__ of any instance, > > and the default behavior for instances of type is to return '', > > but it can be easily customized. > > But 'int' is an instance of 'type' (the metaclass): > >>> int.__class__ > > > > so it should also return '' if that's the default behavior > of the 'type' metaclass. > The fact that a class is an instance of type, which it is always true, doesn't mean its metaclass is "type", it could be any subclass of type : >>>[6]: class A(object) : ...: class __metaclass__(type) : ...: def __repr__(self) : return "" ...: ...: >>>[7]: isinstance(A, type) ...[7]: True >>>[8]: A.__class__ ...[8]: >>>[9]: issubclass(A.__class__, type) ...[9]: True > I think that to get '' one would have to define a new > metaclass like this: > > def type_meta(type): > ? ? def __repr__(self) > ? ? ? ? ?return "" % self.__name__ > > and then one should have int.__class__ == type_meta. But obviously > that's not the case. Why? > > Moreover: > >>> class myint(int): > > ... ? ?pass > ... > > >>> myint.__class__ == int.__class__ > > True > *is* comparaison fits better here. > >>> int > > > > >>> myint > > > > despite int and myint having the same metaclass. So if the > representation is really defined in the 'type' metaclass, then > type.__repr__ has to make some kind of distinction between int and > myint, so they cannot be on absolute equal footing. You're right, type(int) is type, the way it renders differently is a detail of its implementation, you can do things with builtin types (written in C) you coudn't do in pure python, exactly as you couldn't write recursive types like 'object' and 'type'. -- _____________ Maric Michaud From jiri.zahradil at gmail.com Sun Jul 6 10:31:12 2008 From: jiri.zahradil at gmail.com (jiri.zahradil at gmail.com) Date: Sun, 6 Jul 2008 07:31:12 -0700 (PDT) Subject: Python with Ecmascript References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <8ek074tia4l47tcfo6tqfo9huv2hb68hkt@4ax.com> Message-ID: <7eaf458d-b355-4112-a947-b2b7fe0d1f8d@s50g2000hsb.googlegroups.com> On 6 ?ec, 07:02, Tim Roberts wrote: > "jiri.zahra... at gmail.com" wrote: > > >for my Python application (Windows platform) to be standards > >compliant, I need to embbed Ecmascript(Javascript) interpreter - I > >need to execute plugins written in this language. > > What standard are you hoping to comply with? I mean, what kind of a > program is this? > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. Thats for our speech recognition server - it should executed "tags" with Javascript code embbeded in some XML grammar format. I personally does not like COM solution. I prefer some simple library but may be it is just a hope. I will look to PyQT library and to Mozilla scripting engine, but I think that this one can get unnecessarily difficult. Does anyone work or use something similar? Jiri From dullrich at sprynet.com Thu Jul 24 11:12:39 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 24 Jul 2008 10:12:39 -0500 Subject: repr(string) References: Message-ID: In article , Fredrik Lundh wrote: > David C. Ullrich wrote: > > > I've been saving data in a file with one line per field. > > Now some of the fields may become multi-line strings... > > > > I was about to start escaping and unescaping linefeeds > > by hand, when I realized that repr() and eval() should > > do. Hence the question: If s is a string, is repr(s) > > guaranteed not to contain line breaks? > > yes. > > just keep in mind that using eval() on untrusted data isn't a very good > idea. Right. This data comes from me, gets put into a file and then read by me. Someone _could_ corrupt that file, but someone who could do that could more easily just throw the machine out the window... > -- David C. Ullrich From danielsb2 at hotmail.com Tue Jul 8 10:31:40 2008 From: danielsb2 at hotmail.com (Daniel de Sousa Barros) Date: Tue, 8 Jul 2008 11:31:40 -0300 Subject: Reportlab Image object opens filehandles Message-ID: Hi Mr Robin, I saw your post: http://mail.python.org/pipermail/python-list/2003-September/224781.html I'm trying to append more than 1000 images into one PDF report, but i get the IOError: Too many... know you a solution for it? Sorry by my english.... i'm brazilian and i'm learning english yet... -------------- next part -------------- An HTML attachment was scrubbed... URL: From cbc at unc.edu Mon Jul 14 09:02:44 2008 From: cbc at unc.edu (Chris Calloway) Date: Mon, 14 Jul 2008 09:02:44 -0400 Subject: BootCampArama Final Reminder Message-ID: <270C71C6-EB07-480E-86C1-C411EE2DD611@unc.edu> Final reminder, we're in the last two weeks of open registration for PyCamp, Plone Boot Camp, and Advanced Plone Boot Camp: http://trizpug.org/boot-camp/2008/ Registration is now open for: PyCamp: Python Boot Camp, August 4 - 8 Plone Boot Camp: Customizing Plone, July 28 - August 1 Advanced Plone Boot Camp: Plone 3 Techniques, August 4 - 7 All of these take place on the campus of the University of North Carolina at Chapel Hill in state of the art high tech classrooms, with free mass transit, low-cost accommodations with free wireless, and convenient dining options. Plone Boot Camp is taught by Joel Burton, twice chair of the Plone Foundation. Joel has logged more the 200 days at the head of Plone classrooms on four continents. See plonebootcamps.com for dozens of testimonials from Joel's students. PyCamp is taught by Chris Calloway, facilitator for TriZPUG and application analyst for the Southeast Coastal Ocean Observing System. Chris has developed PyCamp for over 1500 hours on behalf of Python user groups. Early bird registration runs through June 30. So register today! PyCamp is TriZPUG's Python Boot Camp, which takes a programmer familiar with basic programming concepts to the status of Python developer with one week of training. If you have previous scripting or programming experience and want to step into Python programming as quickly and painlessly as possible, this boot camp is for you. PyCamp is also the perfect follow-on to Plone Boot Camp: Customizing Plone the previous week. At Plone Boot Camp: Customizing Plone you will learn the essentials you need to build your Plone site and deploy it. This course is the most popular in the Plone world--for a good reason: it teaches you practical skills in a friendly, hands-on format. This bootcamp is aimed at: * people with HTML or web design experience * people with some or no Python experience * people with some or no Zope/Plone experience It covers using Plone, customizing, and deploying Plone sites. At Advanced Plone Boot Camp: Plone 3 Techniques you will learn to build a site using the best practices of Plone 3 as well as advance your skills in scripting and developing for Plone. The course covers the new technologies in Plone 3.0 and 3.1intended for site integrators and developers: our new portlet infrastructure, viewlets, versioning, and a friendly introduction to Zope 3 component architecture. Now, updated for Plone 3.1! The course is intended for people who have experience with the basics of Plone site development and HTML/CSS. It will cover what you need to know to take advantage of these new technologies in Plone 3. For more information contact: info at trizpug.org -- Sincerely, Chris Calloway http://www.secoora.org office: 332 Chapman Hall phone: (919) 599-3530 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From DWebre at dotd.la.gov Fri Jul 11 09:15:36 2008 From: DWebre at dotd.la.gov (DWebre at dotd.la.gov) Date: Fri, 11 Jul 2008 08:15:36 -0500 Subject: Pickle and wx.TextCtrl Message-ID: Trying to read a pickled filed and list contents. The attached program works using pprint, but I want to write to my frame. WriteText only produces half of the records. What is happening? (See attached file: ReadDB_b.py) D. J. Webre, Jr. PE & PLS Director of Engineering & Technical Support LA DOTD, Office of Public Works, Hurricane Flood Protection & Intermodal Transportation 8900 Jimmy Wedell Dr. Rm 215 Baton Rouge, LA 70807 http://www.dotd.louisiana.gov/sitemap.asp?ID=8 (225) 274-4339 e-mail: DJWebre at dotd.la.gov (225) 274-4322 Fac -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ReadDB_b.py Type: application/octet-stream Size: 1710 bytes Desc: not available URL: From kay.schluehr at gmx.net Tue Jul 15 04:11:05 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 15 Jul 2008 01:11:05 -0700 (PDT) Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> <7348c0dc-028d-4f89-9d63-b1247fb6807c@m44g2000hsc.googlegroups.com> Message-ID: On 15 Jul., 08:16, Yosifov Pavel wrote: > cloning of iterators in this manner is bad, more good is to use one, > single list(my_iter) instead of (seehttp://aquagnu.blogspot.com/2008/07/self-repair-iterator-in-python.html). This won't work for "big" iterators as mentioned by Peter Otten. With this recipe you can't even clone generator objects ( which are iterators ) that produce Fibonaccis in a lazy manner. Regards, Kay From babacity2 at gmail.com Thu Jul 24 16:58:07 2008 From: babacity2 at gmail.com (babacity2 at gmail.com) Date: Thu, 24 Jul 2008 13:58:07 -0700 (PDT) Subject: www efukt com - Amazing porn video collection Message-ID: <007227be-eec2-43ea-87bf-850af75062fa@w39g2000prb.googlegroups.com> www efukt com . >>>>>>>>>>Best Collection of Efukt Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE www efukt com VIDEOS<<<<<<<<<<< . www efukt com From ivan at datasyncorp.com Mon Jul 7 10:05:58 2008 From: ivan at datasyncorp.com (Ivan Ven Osdel) Date: Mon, 7 Jul 2008 09:05:58 -0500 (CDT) Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: Message-ID: <806987658.1043581215439558634.JavaMail.root@saturn.datasyncintra.net> >----- Original Message ----- >From: "Python Nutter" >To: "Ivan Ven Osdel" >Cc: python-list at python.org >Sent: Thursday, July 3, 2008 5:56:32 PM GMT -06:00 US/Canada Central >Subject: Re: Freesoftware for auto/intelligent code completing in Python > >If you guys can get your head out of IDE land, you'll find iPython >does a fantastic job at introspection and Auto-completion, you can >launch shell commands and editors and when done saving be back in the >iPython shell, save memory/variable space to disk so you can come back >the next day and continue off where you were. It puts IDEs to shame. > >If you can't get your Windows-centric IDE need eliminated, then Wing >IDE 101 will not auto-complete, its been deliberately disabled to >force students (hence 101) to memorize python/function names. > >Komodo Edit is a free download and will Auto-complete. >Cheers, >PN Thanks for the suggestion. I'll take a look at iPython today. Ivan From simon at brunningonline.net Wed Jul 23 04:31:49 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 23 Jul 2008 09:31:49 +0100 Subject: Strange problem .... In-Reply-To: <12fd8ef1-c7e0-470b-ba51-f946d8ea8e26@z6g2000pre.googlegroups.com> References: <12fd8ef1-c7e0-470b-ba51-f946d8ea8e26@z6g2000pre.googlegroups.com> Message-ID: <8c7f10c60807230131s35df199ele47fba527be25447@mail.gmail.com> 2008/7/23 karthikbalaguru : > I use Redhat 9.0, python-2.2.2-26, python-devel-2.2.2-26 and > db4-4.0.14-20. > > File "/usr/local/SDK/bin/../core/bin/processorlib.py", line 88 > yield ProcessorObjectInfo(child, self.pt) > ^ > SyntaxError: invalid syntax > > Is this error related with the version of python / python-devel that i > use . > Any ideas / tips ? Yup - generators (and hence the yield statement) were first introduced in Python 2.2, but in order to maintain backward compatibility, you'll need this line in any module using them: from __future__ import generators As of Python 2.3, this is no longer necessary, and I'd imagine that whatever you are running was targeted at a post 2.2 release. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From circularfunc at gmail.com Sat Jul 12 19:31:55 2008 From: circularfunc at gmail.com (ssecorp) Date: Sat, 12 Jul 2008 16:31:55 -0700 (PDT) Subject: Correct use of try,except and raise? Message-ID: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> Is this correct use of exceptions? to raise an indexerror and add my own string insetad of just letting it raise a IndexError by itself and "blaming" it on list.pop? class Stack(object): def __init__(self, *items): self.stack = list(items) def push(self, item): self.stack.append(item) def pop(self): try: return self.stack.pop() except: raise IndexError, "pop from empty stack" class Queue(object): def __init__(self, *items): self.queue = list(items) def append(self, item): self.queue.append(item) def pop(self): try: return self.queue.pop(0) except: raise IndexError, "pop from empty queue" From Nikolaus at rath.org Thu Jul 31 08:27:25 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Thu, 31 Jul 2008 14:27:25 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> Message-ID: <873alq9r2q.fsf@nokile.rath.org> Thomas Troeger writes: >> Can someone explain to me the difference between a type and a class? > > If your confusion is of a more general nature I suggest reading the > introduction of `Design Patterns' (ISBN-10: 0201633612), under > Specifying Object Interfaces'. > > In short: A type denotes a certain interface, i.e. a set of > signatures, whereas a class tells us how an object is implemented > (like a blueprint). A class can have many types if it implements all > their interfaces, and different classes can have the same type if they > share a common interface. The following example should clarify > matters: > > class A: > def bar(self): > print "A" > > class B: > def bar(self): > print "B" > > class C: > def bla(self): > print "C" > > def foo(x): > x.bar() > > you can call foo with instances of both A and B, because both classes > share a common type, namely the type that has a `bar' method), but not > with an instance of C because it has no method `bar'. Btw, this > example shows the use of duck typing > (http://en.wikipedia.org/wiki/Duck_typing). That would imply that I cannot create instances of a type, only of a class that implements the type, wouldn't it? But Python denotes 'int' as a type *and* I can instantiate it. Still confused, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From martin at v.loewis.de Thu Jul 10 00:33:05 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 10 Jul 2008 06:33:05 +0200 Subject: Py_BuildValue for char **? In-Reply-To: References: Message-ID: <48759101$0$9741$9b622d9e@news.freenet.de> > Is there any idiomatic way of mapping char ** to Python? My recommendation is to not use Py_BuildValue. Instead, use PyList_New, and then, in a loop, PyString_FromString/PyList_SetItem. Regards, Martin From duncan.booth at invalid.invalid Sat Jul 12 14:01:31 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jul 2008 18:01:31 GMT Subject: why is "self" used in OO-Python? References: Message-ID: ssecorp wrote: > 1. Why do I have to pass self into every method in a class? Since I am > always doing why cant this be automated or abstracted away? > Are the instances where I won't pass self? > I imagine there is some tradeoff involved otherwise it would have been > done away with. When you define a method in Java there is an implicit 'this' passed to the method. Python cannot tell when you define a function whether the function is going to be used as a function, an instance method, a class method, a static method or something else (or all of the above). Consider this: >>> class C: pass >>> def showme(*args, **kw): print args, kw >>> C.method = showme >>> C.staticmethod = staticmethod(showme) >>> C.classmethod = classmethod(showme) >>> showme(1,2,3) (1, 2, 3) {} >>> C().method(1,2,3) (<__main__.C instance at 0x00C4B580>, 1, 2, 3) {} >>> C().staticmethod(1,2,3) (1, 2, 3) {} >>> C().classmethod(1,2,3) (, 1, 2, 3) {} >>> The dynamic nature of Python means you can lift a method out of a class and re-use it in a different context or inject a function into a class as a method. There are two ways to handle this sort of code: javascript has an implied 'this' for everything whether a function or what passes for a method, Python makes it explicit. > 2. self.item instead of getters and setters. I thought one of the main > purposes of OO was encapsulation. Doesn't messing with internal object- > representations break this? That is correct. Some languages (e.g. Java) don't allow you to encapsulate attributes so you have to write getter and setter methods. If you expose an attribute in Java then you cannot later insert some code into the lookup or override the set without getting all users of your code to change the way they access the value. This is bad. Other languages (e.g. Python, C#) allow you to intercept the attribute lookup so you can change a plain attribute into a property without requiring the users of your class alter their source code. With C# I think they would still need to recompile their code so it may be more appropriate to avoid using public attributes if you are producing a class library for widespread reuse, but with Python there is no difference to the user of your class whether they are accessing an attribute or a property. Sadly a lot of Java programmers mistake the limitations of their language for rules of OO programming, and worse this has spread from Java into other languages where these restrictions no longer need apply. Your Stack class is a bad example: the stack attribute is purely internal so you wouldn't want to expose it as part of the public interface. Consider instead something like: class AddressBookEntry(object): def __init__(self, name, phone): self.name = name self.phone = phone @property def phone(self): return self._phone @property.setter def phone(self, number) validatephonenumber(number) # may throw an exception self._phone = number If later you want to add some processing to the name attribute it is easy, but putting in dummy property getter/setter methods before you need them would be pointless. From frank at chagford.com Wed Jul 30 03:49:36 2008 From: frank at chagford.com (Frank Millman) Date: Wed, 30 Jul 2008 00:49:36 -0700 (PDT) Subject: Questions about asyncore References: <5d30aad5-cad7-4e47-aa83-277202c70ae2@z72g2000hsb.googlegroups.com> Message-ID: <6db7042c-02bb-42ef-b578-3811d8f427f5@m36g2000hse.googlegroups.com> On Jul 29, 3:40?pm, "Giampaolo Rodola'" wrote: > On 29 Lug, 13:09, Frank Millman wrote: Thanks for the reply, Giampaolo. > > The benefit of asynchat is that it automatically handles the buffering > of both input and output. > Aside from set/found_terminator() the other two methods you could want > to look at are push() and push_with_producer(). > push() is a buffered version of asyncore.send(), push_with_producer() > accepts a data-producer object you can use in case you want to deal > with something other than strings (e.g. files, lists, generators, and > so on...). > I looked at push() and push_with_producer(). To be honest I don't fully understand why I would want to use them yet - I will have to go over them a few more times. However, my handle_write() method seems to be working ok and is not complicated, so I will stick with that for now. > > I'm not sure to understand but I doubt you have to use a thread. > If you "have to wait for the reply before continuing" just implement > this logic into handle_read() or found_terminator() method. > Maybe I am a bit slow, but I cannot figure out how to do this without adding a lot of complication. I will try to give a simple example. My server is a database server. It sits between the actual database and the client, and implements access control, automatic handling of foreign keys, etc. It accepts messages to read, update, and write data, and returns the results. For testing purposes, I want the client to send and receive messages such as the following (pseudocode) - -> Read Customer record with CustNo = 'A001'. <- Print data, check that it is correct. [1] -> Read customer's Branch record. <- Print data, check that it is correct. -> Update Customer record with new Branch code. [2] -> Read Branch code from Customer record. <- Print code, check that it has changed. -> Read customer's Branch record. <- Print data, check that it belongs to the new Branch. [1] Amongst other things, the server returns the id of the record [2] The update request uses the record id to identify which record to update These are just examples of the tests I might want to throw at the server. With my multi-threaded approach, the asyncore loop runs in the background, and in the foreground I can easily send any message I like and check the results. I cannot see how to implement this using handle_read() and found_terminator(). Maybe you can give a simple example of an alternative approach. Thanks Frank From jeffober at gmail.com Thu Jul 17 08:27:29 2008 From: jeffober at gmail.com (Jeff) Date: Thu, 17 Jul 2008 05:27:29 -0700 (PDT) Subject: bad recursion, still works References: <20cba7ab-72d2-4c7b-8f3f-48f39eaf9625@m3g2000hsc.googlegroups.com> Message-ID: <5ca91d8c-295e-412c-8bbc-7a0f9f4c8b46@27g2000hsf.googlegroups.com> Thanks, that made things very clear. I like that technique for adding memoization via the parameter. That is clever. It would be nice if there were a way to have multiple functions close over a shared local variable in Python, like let-binding in lisp. From deets at nospam.web.de Sun Jul 27 17:42:41 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2008 23:42:41 +0200 Subject: Rant (was Re: x*x if x>10 In-Reply-To: References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3qjoF9n3cpU1@mid.uni-berlin.de> Message-ID: <6f48ehF9p9bkU1@mid.uni-berlin.de> Terry Reedy schrieb: > > > DaveM wrote: >> On Sun, 27 Jul 2008 19:46:32 +0200, "Diez B. Roggisch" >> >> wrote: >>> As a rule of thumb, don't return objects you didn't create inside a >>> function from scratch. > > Unless its job is specifically to get/fetch an object (reference > thereto) from someplace the caller cannot or should not access. But > then it should probably not mutate the object before returning the > reference. I maybe should paraphrase "don't return objects you passed as arguments from a function". Of course there are exceptions to this rule - but these are few, the canonical being chained function calls like this: class Whatever(object): def do_something(self, arguments): .... return self Diez From Russ.Paielli at gmail.com Sat Jul 26 20:14:46 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 26 Jul 2008 17:14:46 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> Message-ID: <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> On Jul 26, 2:25 pm, Terry Reedy > There is a lot of code you have not seen. Really. In informal code I > use 's' and 'o' for 'self' and 'other'. I don't usually post such > because it is not considered polite. So you have seen a biased sample > of the universe. You take the name down to a single letter. As I suggested in an earlier post on this thread, why not take it down to zero letters? You could if Python accepted something like class Whatever: def fun( , cat): .cat = cat This is even better than the single-character name, not only because it is shorter, but also because there is no question that you are referring to "self." No need to look back at the method signature to verify that. For those who don't like the way the empty first argument looks, maybe something like this could be allowed: def fun( ., cat): From mccredie at gmail.com Tue Jul 15 16:00:52 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 15 Jul 2008 13:00:52 -0700 (PDT) Subject: 'if name is not None:' v. 'if name:' References: Message-ID: On Jul 15, 12:44?pm, "Victor Noagbodji" wrote: > >>what's the difference between these two statement? > >one checks if the given object is not None, the other checks if it's a true value: > >http://docs.python.org/ref/Booleans.html#Booleans > >>And which one should one use? > >depends on what you want to test for, of course. > > > > > Well that's exactly why I'm asking. Since None returns False in if > statements. Why do people use if name is not None: instead of simply > writing if not name? > > -- > NOAGBODJI Paul Victor 1. If you want to distinguish between None and something else that evaluates to False. 2. Speed, "is not" is checking identity of the objects. That can be (and usually is) much quicker than checking whether or not it evaluates to True. Checking the boolean value calls the "__nonzero__" method of an object. That method could be user defined and very complex. In general there are many cases where you use "None" as a placeholder (similar to NULL in C/C++). The best practice is to always compare identity with None. Matt From vuleetu at gmail.com Sun Jul 13 23:47:03 2008 From: vuleetu at gmail.com (Fisher) Date: Mon, 14 Jul 2008 11:47:03 +0800 Subject: Question about Stackless Python Message-ID: <004001c8e564$51fbb5c0$9600a8c0@WWW8D7149479C6> Hi, I have some question about Stackless Python. What is main tasklet? Usually we call stackless.run() to mainloop all the schedule tasklets. But if we just call sometaklet.channel.send(None) in main thread after all the necessary tasklets are created, what would happen? Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Fri Jul 4 01:40:32 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 04 Jul 2008 05:40:32 GMT Subject: How to bypass Windows 'cooking' the I/O? (One more time, please) References: Message-ID: norseman wrote: > >Problem: (sos=same old s...) Microsoft insists the world work it's way >even when the Microsoft way was proven wrong decades ago. In this case >it's (still) 'cooking' the writes even with 'rwb' and O_RDWR|O_BINARY in >(proper respective) use. No, it doesn't. Where did you get the idea that 'rwb' is a valid fopen mode? It's not. If you need to read and write an existing file, you want "r+b". C:\tmp>python Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('x.bat','r+b') >>> s = f.read() >>> s 'sed -e "s/[ \\t]*$//" -e "/^$/d" %1\rhow about that\r\n' >>> f.seek(-1,2) >>> f.write('xxx\r\n') >>> f.close() >>> f = open('x.bat','rb') >>> t = f.read() >>> t 'sed -e "s/[ \\t]*$//" -e "/^$/d" %1\rhow about that\rxxx\r\n' >>> >Same python program runs as expected in Linux. Maybe because that's >where it was written?! :) Perhaps your Linux C runtime library accepts the fopen mode 'rwb', but if it does, it's a non-standard extension. >What I seek is the way to slap Microsoft up side the head and make it >work correctly. OK, well, at least in this situation. It works correctly if you use it correctly. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From Russ.Paielli at gmail.com Wed Jul 30 19:22:19 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 30 Jul 2008 16:22:19 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> Message-ID: <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> On Jul 30, 1:07 am, Erik Max Francis wrote: > Russ P. wrote: > > Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > > __nonzero__ work in Python. It's very basic stuff. You can quit > > patronizing me (and Carl too, I'm sure). > > You suggested a syntax for testing non-emptiness (`x is not empty`) > which indicated a profound misunderstanding of what the `is` operator does. > > You then acknowledged that there might be a problem because of the > implication if the `is` operator and weren't sure whether it would work > or not: Oh, my. I wrote something like, "It would sure be nice to be able to write if x is not empty: because it reads like natural language. Immediately after I posted it, I thought, "oh, I'll bet some idiot takes that as a serious proposal." Sure enough, some idiot did just that almost immediately. And he is still patronizing me for it. Hey, dude, if you think I ever had any doubt about what "is" means in Python, you are simply wrong. Completely wrong. Can you get that through your thick skull? One of the problems with this site is that you have pedants who like to show off their knowledge of the Python language. I suspect that many of these people know little more than the rules of programming in Python. They are like someone who thinks he is a writer because he knows how to use Microsoft Word, or someone who thinks he is a chess expert because he knows the rules for moving the pieces. From tjreedy at udel.edu Fri Jul 11 14:53:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 Jul 2008 14:53:27 -0400 Subject: Simple question, how do you tell how many items in a list? In-Reply-To: <268ac2770807102256o4f41e784q79a0caf849c046b4@mail.gmail.com> References: <268ac2770807102256o4f41e784q79a0caf849c046b4@mail.gmail.com> Message-ID: Alex Bryan wrote: > I am just wondering how you get an integer value for how many items > there are in a list, preferably w/o a for loop. Read the library reference sections on built-in functions and classes. From mail at timgolden.me.uk Mon Jul 28 10:23:24 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 28 Jul 2008 15:23:24 +0100 Subject: GUID Generation In-Reply-To: <019c01c8f0bc$92b56b20$b8204160$@rawlins@thinkbluemedia.co.uk> References: <019c01c8f0bc$92b56b20$b8204160$@rawlins@thinkbluemedia.co.uk> Message-ID: <488DD65C.2040606@timgolden.me.uk> Robert Rawlins wrote: > I?ve been looking at the following recipe for generating a GUID > http://code.activestate.com/recipes/163604/ however I note that its > about 6 years old. Has python since adopted an internal module for GUID > generation? Or is this 3^rd part module still the best option? Not only is the answer, Yes: http://docs.python.org/lib/module-uuid.html but it's just featured as Doug Hellmann's module of the Week: http://blog.doughellmann.com/2008/07/pymotw-uuid.html TJG From circularfunc at yahoo.se Wed Jul 2 16:02:57 2008 From: circularfunc at yahoo.se (defn noob) Date: Wed, 2 Jul 2008 13:02:57 -0700 (PDT) Subject: Run interpreter in emacs? Message-ID: Can I run the python interpreter from with in Emacs? Do i have to change anything then? or is it by default? it already syntax-highlights python-files. From sleytr at gmail.com Fri Jul 4 09:36:32 2008 From: sleytr at gmail.com (Evren Esat Ozkan) Date: Fri, 4 Jul 2008 06:36:32 -0700 (PDT) Subject: Javascript - Python RSA encryption interoperability Message-ID: Hello, I'm trying to encrypt a string with RSA. But it needs to be compitable with Dave's JavaScript RSA implementation*. I'm already read and tried lots of different things about RSA and RSA in Python. But could not produce the same result with the javascript library. My experiments could be seen at: http://dpaste.com/hold/60741/ * JavaScript RSA Library: http://www.ohdave.com/rsa/ Python libraries which I tried; * PyCrtypo: http://www.amk.ca/python/code/crypto.html * rsa library from http://www.stuvel.eu/rsa How could I create the same results with the JS library in Python. Any help would be appreciated Evren, From mercado949 at gmail.com Wed Jul 23 18:14:30 2008 From: mercado949 at gmail.com (mercado mercado) Date: Wed, 23 Jul 2008 18:14:30 -0400 Subject: Importing different versions of a module Message-ID: <8b51e78c0807231514v47a3ab1ev28c816f3db714a27@mail.gmail.com> Thank you Fredrik. This is exactly what I was looking for. > cannot you just insert the appropriate directory in sys.path the first > thing you do in the scripts? e.g. > > import os, sys > > lib = "lib_dev" # change this for prod/rss.py > > sys.path.insert(0, > os.path.join( > os.path.dirname(os.__file__), "site-packages", lib > )) > > import parse # picks the right one -------------- next part -------------- An HTML attachment was scrubbed... URL: From livibetter at gmail.com Wed Jul 2 08:52:07 2008 From: livibetter at gmail.com (livibetter) Date: Wed, 2 Jul 2008 05:52:07 -0700 (PDT) Subject: Email Validation with domain References: <9d6f2e4f-099b-404d-a8db-c87ab15062d6@79g2000hsk.googlegroups.com> Message-ID: <1f5fe9e7-c3be-4076-93ac-5d10b99ef302@l28g2000prd.googlegroups.com> > If you want to validate the domain, do a DNS lookup on the domain or > some such. I don't think there are standard modules to provide this > functionality included with python. You could try using the socket > module, and reading up on the relevant protocols, or making calls to > external programs. I agreed. I made quick code for this. # Email address validator # # This module is in Public Domain # # This module was written for replying to # http://groups.google.com/group/comp.lang.python/browse_thread/thread/80d7d31bebc09190 # * It requires dnspython (http://www.dnspython.org/). # * It is a simple prototype. # * It would be slow if query mass email addresses, having cache mechanism # would be very helpful. # * It only checks hostname of email address. # # Author : Yu-Jie Lin # Creation Date: 2008-07-02T20:09:07+0800 import dns.resolver def CheckEmail(email): """This function directly extracts the hostname and query it""" email_parts = email.split('@') if len(email_parts) != 2: return False # Start querying try: answers = dns.resolver.query(email_parts[1], 'MX') except dns.resolver.NoAnswer: # This host doesn't have MX records return False except dns.resolver.NXDOMAIN: # No such hostname return False # Possible a valid hostname return True I also wrote a short blog post for this post and the code, if you are interested, you can read it at http://thetinybit.com/Blog/2008-07-02-2047-EmailHostnameCheck From thogiti at gmail.com Mon Jul 7 20:03:27 2008 From: thogiti at gmail.com (Nagu) Date: Mon, 7 Jul 2008 17:03:27 -0700 Subject: Memory error while saving dictionary of size 65000X50 using pickle Message-ID: <21da85430807071703t3d3df210le154070481a21343@mail.gmail.com> Thank you very much Martin. It worked like a charm. From sudhakar.koundinya at gmail.com Sun Jul 27 12:57:48 2008 From: sudhakar.koundinya at gmail.com (Sudhakar Chavali) Date: Sun, 27 Jul 2008 09:57:48 -0700 (PDT) Subject: Google Group: architectgurus Message-ID: Hi I have created a group called architectgurus (http://groups.google.com/ group/architectgurus) or architectgurus at googlegroups.com . Irrespective of technology, vendor, domain I will be discussing and share my thoughts in homogenous and harmonious way. If you are interested even you can join and contribute your thoughts in this group. My intention doing these activities is to spread the knowledge and thoughts across the globe. Best Regards Sudhakar Chavali From mensanator at aol.com Tue Jul 15 13:28:36 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 15 Jul 2008 10:28:36 -0700 (PDT) Subject: isPrime works but UnBoundLocalError when mapping on list References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> Message-ID: <8a07445a-3ca8-4373-9312-cea8db83ec5c@l64g2000hse.googlegroups.com> On Jul 15, 11:26?am, defn noob wrote: > isPrime works when just calling a nbr but not when iterating on a > list, why? adding x=1 makes it work though but why do I have to add > it? > Is there a cleaner way to do it? > > def isPrime(nbr): > ? ? for x in range(2, nbr + 1): > ? ? ? ? if nbr % x == 0: > ? ? ? ? ? ? break > ? ? if x == nbr: > ? ? ? ? return True > ? ? else: > ? ? ? ? return False > > >>> [isPrime(y) for y in range(11)] > > Traceback (most recent call last): > ? File "", line 1, in > ? ? [isPrime(y) for y in range(11)] > ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > ? ? if x == nbr: > UnboundLocalError: local variable 'x' referenced before assignment > > >>> map(isPrime, range(100)) > > Traceback (most recent call last): > ? File "", line 1, in > ? ? map(isPrime, range(100)) > ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > ? ? if x == nbr: > UnboundLocalError: local variable 'x' referenced before assignment>>> isPrime(10) > False > >>> isPrime(11) > > True > > adding x=1 makes it work though: > > def isPrime(nbr): > ? ? x=1 > ? ? for x in range(2, nbr + 1): > ? ? ? ? if nbr % x == 0: > ? ? ? ? ? ? break > ? ? if x == nbr: > ? ? ? ? return True > ? ? else: > ? ? ? ? return False > > >>> [isPrime(y) for y in range(11)] > > [False, True, True, True, False, True, False, True, False, False, > False] No, it doesn't. You are falsely reporting that 1 is prime. And instead of making the fake variable x, shouldn't you instead test that nbr+1 is greater than 2? Or call it with range(3,11) instead of range(11)? x isn't initialized because if nbr+1 is <=2, the for loop has an invalid range and doesn't even execute. From rookswood at suburbian.com.au Wed Jul 16 09:33:46 2008 From: rookswood at suburbian.com.au (John Savage) Date: Wed, 16 Jul 2008 13:33:46 +0000 (UTC) Subject: python's YENC.DECODE -> weird output Message-ID: <0807160233556.16Jul08$rookswood@suburbian.com> I save posts from a midi music newsgroup, some are encoded with yenc encoding. This gave me an opportunity to try out the decoders in Python. The UU decoder works okay, but my YENC effort gives results unexpected: import yenc, sys fd1=open(sys.argv[1],'r') #yenc.encode(sys.argv[1],"outfile.yenc",bytes=0) yenc.decode(sys.argv[1],"outfile.mid",bytes=0,crc_in='') I confirmed that yenc.decode exactly reverses yenc.encode, BUT the encoding itself seems to differ from the USENET standard. That is, when I decode USENET files the result isn't a valid music file. (I did try both with and w/o the headers.) Maybe it uses a different character set? I can't quite put my finger on what might be happening. What I can say is that the yenc coding from the newsgroup article, when viewed with Linux 'more', displays roughly 10% of its characters as a question mark, whereas when I give Python's yenc.encode a binary music file and view its output using 'more', it displays about 90% of the output as a question mark. Any ideas? -- John Savage (my news address is not valid for email) From fetchinson at googlemail.com Thu Jul 3 00:15:55 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 2 Jul 2008 21:15:55 -0700 Subject: Times where one would use new style classes vs classic classes In-Reply-To: <6700e4ba-8573-44da-b75a-3b3e5ba1fd9b@i36g2000prf.googlegroups.com> References: <6700e4ba-8573-44da-b75a-3b3e5ba1fd9b@i36g2000prf.googlegroups.com> Message-ID: > I'm really new to Python and I've been reading up some texts on older > versions of Python (2.2 to be specific). > > The text briefly mentioned new style and classic classes. > > I'd really like to know in the current context of Python 2.5, besides > in the cases of multi-inheritance, where would I use new style > classes? Is it a norm to use more new style classes even if I don't > have multi-inheritance in the industry, open source projects, etc > today? > > If this isn't the right place to ask these questions, could some one > point me somewhere more appropriate? As a general rule one always uses new style classes. In fact, in python 3.0 old style classes will cease to exist which fact alone justifies their abandonment from 2.x code too. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From fredrik at pythonware.com Mon Jul 21 04:52:33 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 10:52:33 +0200 Subject: Odd math related issue. In-Reply-To: <43332.3139710867$1216630189@news.gmane.org> References: <43332.3139710867$1216630189@news.gmane.org> Message-ID: Robert Rawlins wrote: > I?ve got what seems to me to be a totally illogical math issue here > which I can?t figure out. Take a look at the following code: > > /self/.__logger.info(/"%i / %i"/ % (bytes_transferred, > /self/.__sessions[path].total_bytes)) > > percentage = bytes_transferred / > /self/.__sessions[path].total_bytes * 100 > > /self/.__logger.info(/"%i"/ % percentage) > > Seems fairly straight forward, you would think. It takes two values and > calculates the percentage of one from the other, however, percentage > always comes back as ?0? for some reason, look at this log output. if you divide two integers, you'll get an integer back (in Python 2.X, at least). quick fix: percentage = bytes_transferred * 100 / total_bytes From samwyse at gmail.com Tue Jul 8 09:32:51 2008 From: samwyse at gmail.com (samwyse) Date: Tue, 8 Jul 2008 06:32:51 -0700 (PDT) Subject: numeric emulation and __pos__ References: Message-ID: <49875bd1-1b5a-4f37-ac29-f7f46fa43936@25g2000hsx.googlegroups.com> On Jul 7, 6:12?pm, Ethan Furman wrote: > Greetings, List! > > I'm working on a numeric data type for measured values that will keep > track of and limit results to the number of significant digits > originally defined for the values in question. > > I am doing this primarily because I enjoy playing with numbers, and also > to get some experience with unit testing. > > At this point I have the __init__ portion finished, and am starting on > the various operator functions. > > Questions for the group: > > 1) Any reason to support the less common operators? > ? ? ? ? i.e. <<, >>, &, ^, | > > 2) What, exactly, does .__pos__() do? ?An example would help, too. 1) Those make much less sense for non-integers. I'd say skip them. 2) It's an overridable no-op that implements the unary plus operator. Unary plus returns its value unchanged, as does __pos__. From jkrukoff at ltgc.com Mon Jul 28 18:13:00 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Mon, 28 Jul 2008 16:13:00 -0600 Subject: seemingly simple list indexing problem In-Reply-To: <488E4170.2020804@islandtraining.com> References: <488E4170.2020804@islandtraining.com> Message-ID: <1217283180.4123.101.camel@jmk> On Mon, 2008-07-28 at 15:00 -0700, Gary Herron wrote: > Guilherme Polo wrote: > > On Mon, Jul 28, 2008 at 6:24 PM, Ervan Ensis wrote: > > > >> My programming skills are pretty rusty and I'm just learning Python so this > >> problem is giving me trouble. > >> > >> I have a list like [108, 58, 68]. I want to return the sorted indices of > >> these items in the same order as the original list. So I should return [2, > >> 0, 1] > >> > > > > You could simply do this: > > > > a = [108, 58, 68] > > b = sorted(a) > > [b.index(c) for c in a] > > > > Yuck. Slow, and it fails if duplicate list elements exist. > > Also... This looks like a beginners programming assignment. Let's > let him try it himself. We can offer help rather than full solutions if > he has specific Python questions. > > > > > > > > >> For a list that's already in order, I'll just return the indices, i.e. [56, > >> 66, 76] should return [0, 1, 2] > >> > >> Any help would be appreciated. > >> > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > >> > >> > > > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list Sorry, problem was interesting to solve, so I may have jumped the gun. I do wonder why OP was asking for this though, as now that you mention it I can't think of a use case outside of a homework assignment. -- John Krukoff Land Title Guarantee Company From alif016 at gmail.com Sat Jul 26 12:46:45 2008 From: alif016 at gmail.com (Andrew) Date: Sat, 26 Jul 2008 11:46:45 -0500 Subject: Easier way to get the "here" path? In-Reply-To: <488B4A86.4010308@gmail.com> References: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> <488B4A86.4010308@gmail.com> Message-ID: <488B54F5.3090800@gmail.com> Andrew wrote: > bukzor wrote: >> I have to go into these convulsions to get the directory that the >> script is in whenever I need to use relative paths. I was wondering if >> you guys have a better way: >> ... >> > If you just need the current path (where it is executed) why not use > os.getcwd() > which returns a string of the absolute path to the module being executed. > > > $ echo "print __file__" > path.py > $ ipython > In [1]: import path > path.pyc > > In [2]: import os > > In [3]: os.path.join(os.getcwd(), path.__file__.rstrip("c")) > Out[3]: '/home/andrew/path.py' > -- > Andrew I was thinking of this in the module being imported, but now that I try, it doesn't work. It is still seeing itself from the symlink's position. This works, in the module being imported: $ less path.py from os.path import realpath here = realpath(__file__.rstrip("c")) $ python >>> import path >>> path.here '/home/andrew/sym/sym/path.py' -- Andrew From samwyse at gmail.com Wed Jul 9 11:03:39 2008 From: samwyse at gmail.com (samwyse) Date: Wed, 9 Jul 2008 08:03:39 -0700 (PDT) Subject: numeric emulation and __pos__ References: <92e3ea9f-5745-4072-9d09-7c14fd335828@f36g2000hsa.googlegroups.com> Message-ID: On Jul 8, 12:34?pm, Ethan Furman wrote: > Anybody have an example of when the unary + actually does something? > Besides the below Decimal example. ?I'm curious under what circumstances > it would be useful for more than just completeness (although > completeness for it's own sake is important, IMO). Well, as in Decimal, it would be a good operator to use for canonization. Let's say you implement complex numbers as an angle and radius. Then, unary plus could be used to normalize the angle to +/- Pi and the radius to a positive number (by inverting the angle). From alan.franzoni.blahblah at example.com.invalid Wed Jul 30 04:15:15 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Wed, 30 Jul 2008 08:15:15 GMT Subject: static variables in Python? References: Message-ID: <1wxwcddbkwzuy$.1urswtm09xu9q$.dlg@40tude.net> kj was kind enough to say: > In this case, foo is defined by assigning to it a closure that has > an associated variable, $x, in its scope. > > Is there an equivalent in Python? There've been plenty of answers, and I'm not absolutely sure about what you want... but closures are available in Python as well and you can use them, and by combining them through the partial module you can get a sort of closure factory: from functools import partial def getfunc(expensive_call, myfunc): val = expensive_call() f = partial(myfunc, val) return f you can then do something like that: >> f = getfunc(lambda: 1, lambda x,y:x*y) >> f(2) 6 -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From circularfunc at gmail.com Sun Jul 6 17:33:03 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 6 Jul 2008 14:33:03 -0700 (PDT) Subject: how are strings immutable in python? References: Message-ID: so if strings were mutable and i did a = b = "foo" and then did a += "bar" then a and b would be foobar? From Michael.Coll-Barth at VerizonWireless.com Mon Jul 21 12:57:53 2008 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Mon, 21 Jul 2008 12:57:53 -0400 Subject: Change PC to Win or Windows In-Reply-To: References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> Message-ID: <20080721171023.5CB321E4008@bag.python.org> > From: Derek Martin > The term "PC" is commonly used in > English, in the United States and other English speaking countries, to > mean a computer running Microsoft Windows. That isn't quite true. My kids are heading off to college and are in the market for laptops. The question they had for the salesman was if there was anything other than Vista available. I was so proud. His response was that they no longer bother with XP. Another customer suggested that they look at Apple and another customer suggested dual booting it with Ubuntu ( why not Fedora? ). I was shocked when I asked if either were in the field. Nope, a mechanic and doctor. While it might have been true that PCs were becoming synonymous with Windows boxes, I think that tide is heading back the other way. Particularly when I hear that the Apple boxes are becoming very popular as they work better with iPods and iPhones than does Windows. The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From mattheww at chiark.greenend.org.uk Thu Jul 31 17:01:48 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 31 Jul 2008 22:01:48 +0100 (BST) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <00a124e1$0$20313$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >On Wed, 30 Jul 2008 20:55:03 +0100, Matthew Woodcraft wrote: >> On the other hand, iterators provide a clear example of problems with >> "if x": __nonzero__ for iterators (in general) returns True even if they >> are 'empty'. > How do you propose telling whether an iterator is empty? > That's a generic problem with any sort of lazy function. You don't know > if it has finished unless you try grabbing data from it. Of course. The point is that if you tell people that "if x" is the standard way to check for emptiness, and also support a general principle along the lines of "write your function using the interfaces you expect, and call it using the object you have", you should expect to end up with bugs of this sort. >> For example, this function (which attempts to avoid making an expensive >> call when not necessary) is buggy, but easy to write if you've been >> taught that "if x" will work with any kind of object. >> >> def frob(widgets, power): >> if widgets: >> frobber = Frobber(power) # expensive call >> for widget in widgets: >> frobber.frob(widget) > AFAIK there's no great solution to this problem. It's inherent in the way > lazy functions work. Certainly you can't replace the call to "if widgets" > with "if len(widgets)", because iterators don't have a length. I'm not a fan of len() for testing emptiness. But it would have been better in this case, because it would have converted a hard-to-find performance bug into an obvious exception. >However, there is a good (but not great) solution: > >def frob(widgets, power): > widgets = iter(widgets) # in case widgets is a sequence > try: > first = widgets.next() > except StopIteration: > # empty iterator, nothing to do > return None > frobber = Frobber(power) # expensive call > frobber.frob(widget) > for widget in widgets: > frobber.frob(widget) I would use the following low-tech way: def frob(widgets, power): frobber = None for widget in widgets: if frobber is None: frobber = Frobber(power) frobber.frob(widget) -M- From M.Busetto at isac.cnr.it Wed Jul 23 06:20:06 2008 From: M.Busetto at isac.cnr.it (maurizio) Date: Wed, 23 Jul 2008 12:20:06 +0200 Subject: maximum value in a column of file In-Reply-To: References: <4886DCF3.10107@isac.cnr.it> <4886F4CD.8010704@isac.cnr.it> Message-ID: <488705D6.4090300@isac.cnr.it> thank you for your answer actually i've to do some statistics (maximum,minimum,mean,standard deviation,....) of a file of data in which each column is a particular type of data. (the file is a tab separated value). I was trying to do this by using python (usually i work with fortran or bash, but i'm learning python), that the reason why i tried to use numpy. Fredrik Lundh wrote: >
maurizio > wrote: > >> i tryed to use the module max of numpy, >> the problem is that i don't know how to put the column of the file in >> an array. >> (i'm new in phyton). >> anyway if you think there is a better way..... > > What kind of file is it? Did you pick numpy because you want to do > matrix operations (beyond just finding a maximum value), or was it > just the first thing you stumbled upon when researching the problem? > > A simple pattern for finding the maximum value in a file, using only > plain Python code, is: > > max_value = ... some very small value ... > for line in file: > value = ... extract value from line ... > if value > max_value: > max_value = value > > If it's not obvious what "some very small value" is, given the range > of data you're working with, you can do > > max_value = None > for line in file: > value = ... extract value from line ... > if max_value is None or value > max_value: > max_value = value > > instead (this leaves max_value set to None if the file is empty) > > A more experienced Python hacker might write > > def get_all_values(file): > for line in file: > value = ... extract value from line ... > yield value > > ... > > max_value = max(get_all_values(file)) > > instead. But this still leaves us with the problem of extracting the > value. The best way to do that depends on the kind of files you're > working with; for fixed-format text files, you could use string > slicing and int/float for conversion (e.g. "value = > float(line[10:20])", see the tutorial for details); for other text > formats, you could use split/partition or regular expressions, or > maybe an existing module (such as "csv"); for binary formats, there's > a large > number of existing tools. > > And if you really want to use numpy for other reasons than just > getting a maximum value from a column, there's plenty of stuff in > NumPy and SciPy (http://www.scipy.org/) that might be useful. > > So, in other words, I guess we still need more info. > > > > >
From r_e_s_01 at ZZZyahoo.com Thu Jul 10 15:57:51 2008 From: r_e_s_01 at ZZZyahoo.com (r.e.s.) Date: Thu, 10 Jul 2008 12:57:51 -0700 Subject: Can this program be shortened? Measuring program-length? Message-ID: <7Rtdk.16747$N87.3559@nlpi068.nbdc.sbc.com> Can the following program be shortened? ... def h(n,m): E=n, while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n return n h(9,9) Note: Although it halts eventually in principle, this program can't be expected to terminate on any machine in the universe, as it computes a number larger than Graham's number -- assuming Python is extended (if necessary?) to access unbounded storage. Besides using one-letter names and no unneeded whitespace, can something more be done to shorten it? ("Obfuscating" the code would be okay.) Also, I'm not really sure how best to measure a program's length, but this one is now 98 bytes long (or 102 bytes, depending on how newlines are handled). Is there a better measure of program-length? Thanks for any feedback. From norseman at hughes.net Thu Jul 24 13:14:24 2008 From: norseman at hughes.net (norseman) Date: Thu, 24 Jul 2008 10:14:24 -0700 Subject: Broken examples In-Reply-To: References: Message-ID: <4888B870.8090205@hughes.net> Lawrence D'Oliveiro wrote: > In message , norseman > wrote: > >> The OOo examples do not work. > > I have done OOo scripting in Python. What exactly does not work? > -- > http://mail.python.org/mailman/listinfo/python-list > ======================= file: z.scr ---------- #!/bin/bash cd /opt/openoffice.org2.0/program soffice "-accept=socket,host=localhost,port=2002;urp;" & sleep 9 ./python ./zhw.py echo "Did this Run?" # end of file --------- file: zhw.py --------- import uno # get the uno component context from the PyUNO runtime localContext = uno.getComponentContext() # create the UnoUrlResolver resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.b ridge.UnoUrlResolver", localContext ) # connect to the running office ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.Compo nentContext" ) smgr = ctx.ServiceManager # get the central desktop object desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx) # access the current writer document model = desktop.getCurrentComponent() # access the document's text property text = model.Text # create a cursor cursor = text.createTextCursor() # insert the text into the document text.insertString( cursor, "Hello World", 0 ) # Do a nasty thing before exiting the python process. In case the # last call is a oneway call (e.g. see idl-spec of insertString), # it must be forced out of the remote-bridge caches before python # exits the process. Otherwise, the oneway call may or may not reach # the target object. # I do this here by calling a cheap synchronous call (getPropertyValue). ctx.ServiceManager # end of file ------------ file: results ----------- SysOp(P):> sh z.scr Traceback (most recent call last): File "./zhw.py", line 20, in ? text = model.Text AttributeError: Text Did this Run? SysOp(P):> =============NO!!!!!! ----------------------- Haven't found any specific to scalc. The zhw contents is closest to working I have found to date. The z script was used to get to stated place and minimize typos. As results shows - I ran as root. As user it screams lots. (Permissions) The above is best effort so far. Others before it were even worse. If you have working code I would like to tryout your linkage (process). Before you send anything, can you use python to have scalc open a .xls and save it as a csv? I can get python to have scalc open a specific file and then point'n'click myself, but that isn't productive. I cannot get scalc to do a saveas instruction issued by a python program. I have no intentions of staying up all night pointing and clicking. Humans think, computers do the repetitive. Yes? Besides, it is far easier to train the computer than to train the ..... :) Any help is appreciated. Steve norseman at hughes.net From johnericaturnbull at yahoo.com Fri Jul 18 09:25:43 2008 From: johnericaturnbull at yahoo.com (johnericaturnbull at yahoo.com) Date: Fri, 18 Jul 2008 06:25:43 -0700 (PDT) Subject: Core Dump - Segmentation Fault -Newbie Message-ID: <8ba4373d-3d97-4e9a-a15e-723f6818c757@k36g2000pri.googlegroups.com> Hi - I am very new to python. I get this random core dump and am looking for a good way to catch the error. I know the function my core dump occurs. Is there any error catching/handling that I could use in python? From Tribulations at Paralleles.invalid Mon Jul 7 04:05:56 2008 From: Tribulations at Paralleles.invalid (TP) Date: Mon, 07 Jul 2008 10:05:56 +0200 Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> <6ddj74F21uhjU1@mid.individual.net> Message-ID: <4cv8k5-dsg.ln1@rama.nodalpoint> TP wrote: > So, the python print command *can* interpret these 4-character as a single > character. It would be odd if there were no possibility to do the same > thing when the characters are (i) stored in a python variable Sorry, it works when using variables. Try for example: col="[0;31m" esc="\033" colreset="[0m" print esc + col + "foobar" + esc + colreset -- TP (Tribulations Parall?les) "Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert). From __peter__ at web.de Wed Jul 2 03:23:19 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Jul 2008 09:23:19 +0200 Subject: How to pickle bound methods References: Message-ID: srinivasan srinivas wrote: > I would like?to know how to pickle a bound method?? $ cat pickle_method.py import copy_reg import new def make_instancemethod(inst, methodname): return getattr(inst, methodname) def pickle_instancemethod(method): return make_instancemethod, (method.im_self, method.im_func.__name__) copy_reg.pickle(new.instancemethod, pickle_instancemethod, make_instancemethod) if __name__ == "__main__": import pickle class A(object): def __init__(self, who): self.who = who def alpha(self): print "Hello,", self.who FILENAME = "method.pickle" import sys args = sys.argv[1:] if args: a = A(args[0]) m = a.alpha pickle.dump(m, open(FILENAME, "wb")) else: m = pickle.load(open(FILENAME, "rb")) m() $ python pickle_method.py world $ python pickle_method.py Hello, world $ python pickle_method.py Srini $ python pickle_method.py Hello, Srini Peter From clay at lakeserv.net Sat Jul 12 20:49:56 2008 From: clay at lakeserv.net (Clay Hobbs) Date: Sat, 12 Jul 2008 20:49:56 -0400 Subject: Problems with curses Message-ID: <1215910196.7852.7.camel@generator> I am making a text-based game similar to Zork with Python. I have decided to use the curses module, and have run into a problem. I want to scroll the commands and output up after a command is run instead of clearing the screen. But when I use std.scroll(), an exception is raised. Here is the program: #!/usr/bin/env python # text_adventure.py import curses import curses.wrapper def main(stdscr): curses.echo() stdscr.setscrreg(1, 24) score = 0 moves = 0 statusbar = stdscr.subwin(2, 80, 0, 0) statusbar.addstr(0, 0, 'Dingo'+' '*(58-len('Dingo'))+'Score: %03d Moves: %03d'%(score, moves), curses.A_REVERSE) stdscr.addstr(24, 0, '> ') x = stdscr.getstr(24, 2) x = str(x) stdscr.refresh() # stdscr.erase() stdscr.scroll(3) statusbar.erase() statusbar.addstr(0, 0, x+' '*(58-len(x))+'Score: %03d Moves: % 03d'%(score, moves), curses.A_REVERSE) stdscr.addstr(24, 0, '> ') stdscr.getstr(24, 2) curses.wrapper(main) Unfortunately, the error message isn't very helpful. I'm just hoping somebody out there knows curses and has the answer. -- Ratfink From s0suk3 at gmail.com Mon Jul 28 02:21:28 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Sun, 27 Jul 2008 23:21:28 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> <6385b0a8-f7f3-4dc3-91be-e6f158ffb439@a1g2000hsb.googlegroups.com> Message-ID: On Jul 27, 10:55 pm, Lawrence D'Oliveiro wrote: > In message > <6385b0a8-f7f3-4dc3-91be-e6f158ffb... at a1g2000hsb.googlegroups.com>, > > > > s0s... at gmail.com wrote: > > On Jul 26, 6:47 pm, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: > >> In message > >> <024ace13-f72f-4093-bcc9-f8a339c32... at v1g2000pra.googlegroups.com>, > > >> s0s... at gmail.com wrote: > >> > On Jul 24, 5:01 am, Lawrence D'Oliveiro >> > central.gen.new_zealand> wrote: > > >> >> In message > >> >> <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, > >> >> Jordan wrote: > > >> >> > Except when it comes to Classes. I added some classes to code that > >> >> > had previously just been functions, and you know what I did - or > >> >> > rather, forgot to do? Put in the 'self'. In front of some of the > >> >> > variable accesses, but more noticably, at the start of *every single > >> >> > method argument list.* > > >> >> The reason is quite simple. Python is not truly an "object-oriented" > >> >> language. It's sufficiently close to fool those accustomed to OO ways > >> >> of doing things, but it doesn't force you to do things that way. You > >> >> still have the choice. An implicit "self" would take away that choice. > > >> > By that logic, C++ is not OO. > > >> Yes it is, because it has "this". > > > You mean the keyword "this"? It's just a feature. How does that make a > > difference on being or not being OO? > > Because it was one of the things the OP was complaining about (see above). Wrong. What the OP complains about has no relevance on what makes a language OO or not. From ldo at geek-central.gen.new_zealand Thu Jul 24 06:08:10 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 24 Jul 2008 22:08:10 +1200 Subject: Broken examples References: Message-ID: In message , norseman wrote: > The OOo examples do not work. I have done OOo scripting in Python. What exactly does not work? From paul at boddie.org.uk Wed Jul 16 06:26:38 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 16 Jul 2008 03:26:38 -0700 (PDT) Subject: Using McMillan Installer, PyInstall or py2exe cross-platform? References: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> <487d100a$0$7538$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <6e1492db-6868-4554-9b85-96c1717b6b6a@s50g2000hsb.googlegroups.com> On 15 Jul, 23:00, Hartmut Goebel wrote: > > I started working on cross-pyinstall today. Let us know how you get on! In theory, one should be able to build Python (and derived works) using the mingw32 libraries and a suitable cross-compiler on platforms other than Windows, but I've never bothered to do so myself. Paul From ed.whyatt at gmail.com Wed Jul 16 11:42:50 2008 From: ed.whyatt at gmail.com (Whyatt) Date: Wed, 16 Jul 2008 08:42:50 -0700 (PDT) Subject: Setting Message Importance using SMTP Mail Message-ID: <33672217-148c-4c6a-96be-25ef88ba773f@k37g2000hsf.googlegroups.com> Hi all, I'm trying to create a message using SMTP Mail through Python with a message Importance of either 0 (Low) or 2 (High). If I do outer.Add_header('Importance', '0') it is ignored. If I do uter.Replace_header('Importance', '0') I get the error below. Traceback (most recent call last): File "#####", line 840, in outer.Replace_header('Importance', '0') AttributeError: MIMEMultipart instance has no attribute 'Replace_header' Can anyone provide any clues on the correct way of updating the Msg Importance header? Thanks in advance Ed From tjreedy at udel.edu Tue Jul 22 01:35:11 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2008 01:35:11 -0400 Subject: tail-rec decorator, well still blows the stack... In-Reply-To: References: Message-ID: ssecorp wrote: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 > > so I try it and when I run: > @Decorators.tail_recursion > def fibtr(n): > def fibt(a, b, n): > if n <= 1: > return b > else: > return fibt(b, a + b, n - 1) > if n == 0: > return 0 > else: > return fibt(0, 1, n); > > it still blows the stack. so what is the point? is it impossible to > get "real" tail-recursion in Python? As you have used it, the decorator wraps the *outer* non-recursive function which is just called once anyway. Useless. Try wrapping fibt instead. That said, this recipe significantly increases the running time by multiplying the number of function calls by about three. I do not regard it as removing the recursion, but, rather, as making it indirect (via two other calls) so as to remove the unneeded stack frames (and the space problem) in between recursive calls. Much simpler is the trivial rewrite with while to do 'in frame recursion', or iteration. This also removes the need for outer and inner function. rearrange fibt as def fibt(a,b,n): if n > 1: return fibt(b, a+b, n-1) else: return b and rewrite as def fibi(a,b,n): while n > 1: a,b,n = b,a+b,n-1 return b by directly binding the new arguments to the parameters. Move the initialization inside the function (and delete the outer wrapper) to get def fib(n): if n==0: return 0 else: a,b = 0,1 while n > 1: a,b,n = b,a+b,n-1 return b and even turn the induction back a step and simplify to def fib(n): a,b = 1,0 while n: a,b,n = b,a+b,n-1 return b Why do some people fight writing efficient beautiful code like this that works with Python's design to instead write less efficient and uglier code that works against Python's design? If you do not want function calls (and runtime name resolution), do not write them! Terry Jan Reedy From Robert.Bossy at jouy.inra.fr Fri Jul 11 12:38:58 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Fri, 11 Jul 2008 18:38:58 +0200 Subject: decorator to prevent adding attributes to class? In-Reply-To: <98c6e83e-4a54-49ce-a32e-f03f5ab97f28@k13g2000hse.googlegroups.com> References: <98c6e83e-4a54-49ce-a32e-f03f5ab97f28@k13g2000hse.googlegroups.com> Message-ID: <48778CA2.2000402@jouy.inra.fr> Michele Simionato wrote: > This article could give you same idea (it is doing the opposite, > warning you > if an attribute is overridden): > http://stacktrace.it/articoli/2008/06/i-pericoli-della-programmazione-con-i-mixin1/ > > There is also a recipe that does exactly what you want by means of a > metaclass: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158 > It is so short I can write it down here: > # requires Python 2.2+ > > def frozen(set): > "Raise an error when trying to set an undeclared name." > def set_attr(self,name,value): > if hasattr(self,name): > set(self,name,value) > else: > raise AttributeError("You cannot add attributes to %s" % > self) > return set_attr > > class Frozen(object): > """Subclasses of Frozen are frozen, i.e. it is impossibile to add > new attributes to them and their instances.""" > __setattr__=frozen(object.__setattr__) > class __metaclass__(type): > __setattr__=frozen(type.__setattr__) > I don't get it. Why use a metaclass? Wouldn't the following be the same, but easier to grasp: class Frozen(object): def __setattr__(self, name, value): if not hasattr(self, name): raise AttributeError, "cannot add attributes to %s" % self object.__setattr__(self, name, value) Btw, the main drawback with Frozen is that it will not allow to set any new attributes even inside __init__. Some people would advise to use __slots__: http://docs.python.org/ref/slots.html#l2h-222 Some other people would advise NOT to use __slots__: http://groups.google.com/group/comp.lang.python/msg/0f2e859b9c002b28 Personally, if I must absolutely, I'd go for explicitely freeze the object at the end of __init__: class Freezeable(object): def freeze(self): self._frozen = None def __setattr__(self, name, value): if hasattr(self, '_frozen') and not hasattr(self, name): raise AttributeError object.__setattr__(self, name, value) class Foo(Freezeable): def __init__(self): self.bar = 42 self.freeze() # ok, we set all variables, no more from here x = Foo() print x.bar x.bar = -42 print x.bar x.baz = "OMG! A typo!" Cheers, RB From pythonnutter at gmail.com Thu Jul 10 03:26:36 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Thu, 10 Jul 2008 17:26:36 +1000 Subject: ANN: Mac OS X versions of Rabbyt 0.81 - A fast 2D sprite engine using OpenGL Message-ID: Just a quick announcement, I have supplied PPC and Intel compiled eggs for the Rabbyt libary on Pypi http://pypi.python.org/pypi/Rabbyt/ Rabbyt-0.8.1-py2.5-macosx-10.3-ppc.egg (md5) Built on OS X 10.5.4 for PowerPC equipped Macs Rabbyt-0.8.1-py2.5-macosx-10.3-i386.egg (md5) Built on OS X 10.5.4 for Intel equipped Macs If you know anything about Rabbyt or want to run any of the Rabbyt + pyglet tutorials or demonstration programs, you can now easily install it onto your Mac. Cheers, PN From robert.rawlins at thinkbluemedia.co.uk Wed Jul 23 11:49:11 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Wed, 23 Jul 2008 16:49:11 +0100 Subject: Get dict value but not as reference. Message-ID: <007901c8ecdb$a67f9070$f37eb150$@rawlins@thinkbluemedia.co.uk> Guys, This feels like a strange question but it's not something I've done before, I'm sure it's quite simple. I have a dictionary, and I want to get one of the values from it, but rather than returning it as a reference I want to actually detach/remove the element from the dictionary. Like so: Def get_something(): Something = self.my_dict["keythatIwanttoredetach"] Return something I can then use something, however, it no longer exists in the dictionary. Sorry, I couldn't really explain this very well. How can I achieve this? Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From boaz at feldbaum.name Fri Jul 18 07:40:51 2008 From: boaz at feldbaum.name (Boaz Feldbaum) Date: Fri, 18 Jul 2008 14:40:51 +0300 Subject: How to register an extension DLL with python 2.5? Message-ID: Hello all, I wrote an extension dll in C++ using VS2005 to be used in windows platform. In pyhon 2.4 I used to copy my dll to the dlls sub-directory of python installation and import my dll and it worked fine. This doesn't work with python 2.5. I get the following when trying to import my dll: >>> import pywutil Traceback (most recent call last): File "", line 1, in ImportError: No module named pywutil >>> What should I do in 2.5 to be able to import my extension dll? Thanks a lot in advance, Boaz. From asd at pittle.org Wed Jul 2 14:15:04 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Wed, 2 Jul 2008 11:15:04 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: Message-ID: <4400a687-f424-45ba-93f5-e096913f52a9@s21g2000prm.googlegroups.com> On Jul 2, 7:55?pm, Ivan Ven Osdel wrote: > The free Python editors/IDEs really do need work as far as code completion goes but I am hopeful. > > IMO Stani's Python Editor comes closest by providing some code sense through a combination of history and doc strings for Python built-ins. Where it falls short is the ability to scan doc strings for your own code and non built-in modules in the Python path. Python already has the ground work in place to accomplish something similar to VS's XML commenting/intellisense system. With a Python interpretor you can type help(myModule) and get the doc string documentation. So I imagine implementing code sense for code being developed as well as non built-in modules would just be a matter of finding the appropriate module at the right time and piping the output of help([module]) to a popup window. > > If your willing to help work on something like that I suggest contacting Stani directlyhttp://pythonide.stani.be/or creating a plugin for Geanyhttp://geany.uvena.de/ > > Ivan Ven Osdel > Software Engineerhttp://www.datasyncsuite.com/ > > ----- Original Message ----- > From: "Ali Servet D?nmez" > To: python-l... at python.org > Sent: Wednesday, July 2, 2008 3:33:59 AM GMT -06:00 US/Canada Central > Subject: Re: Freesoftware for auto/intelligent code completing in Python > > On Jul 1, 12:15?am, Fuzzyman wrote: > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > I don't want to be so mean here, but how hard it could be be writing a > > > freesoftware which would automatically/intelligently auto complete > > > Python code? (I mean something that really does the job, like > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > name it, but just don't give me PyDev please...) > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > missing here? > > > > Could someone please point me out something that I'm really missing > > > which is already present in the wild, otherwise I'd like discuss with > > > whoever is willing to help me to get this thing done. I made my mind > > > and I could volunteer to make this happen as thesis project for my > > > incoming graduation in the next year. > > > > Regards you all, > > > Ali Servet D?nmez > > > Vim, Emacs, Wing, Komodo, ... more? > > > Yeah, I guess you're missing something. :-) > > > Michael Foordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > I've checkout Wing IDE's license and it doesnt' seem to be a > freesoftware; am I wrong? > > Ivan, thanks for your reply. I am curious how come you're suggesting me those two, but not others. Is there a good/particular reason for that? From brendandetracey at yahoo.com Thu Jul 10 08:05:49 2008 From: brendandetracey at yahoo.com (Brendan) Date: Thu, 10 Jul 2008 05:05:49 -0700 (PDT) Subject: B-Soup: broken iterator, tag a keyword? Message-ID: <413d8bc0-6156-4502-93c1-8c8790128f56@d45g2000hsc.googlegroups.com> Hi there, I have the following using Beautiful Soup: soup = BeautifulSoup(data) tags = soup.findAll(href=re.compile("/MER_FRS_L2_Canada/MER_FRS_\S +gz")) for tag in tags: print tag['href'] print tag.parent.nextSibling.string print tag.parent.nextSibling.nextSibling.string print tag.parent.nextSibling.nextSibling.nextSibling.string print tag.parent.nextSibling.nextSibling.nextSibling.nextSibling.contents[0].string For some reason I do not understand, using 'tag' as an iterator breaks the code. Can someone tell me why? reading dir(soup) did not illuminate me. Thanks From aspersieman at gmail.com Wed Jul 30 11:55:35 2008 From: aspersieman at gmail.com (Aspersieman) Date: Wed, 30 Jul 2008 17:55:35 +0200 Subject: Standard module for parsing emails? In-Reply-To: References: <6fb93eFap7j5U1@mid.individual.net> Message-ID: <48908EF7.7060301@gmail.com> Phillip B Oldham wrote: > If there isn't a standard library for parsing emails, is there one for > connecting to a pop/imap resource and reading the mailbox? > -- > http://mail.python.org/mailman/listinfo/python-list > > The search [1] yielded these results: 1) http://docs.python.org/lib/module-email.html 2) http://www.devshed.com/c/a/Python/Python-Email-Libraries-SMTP-and-Email-Parsing/ I have used the email module very successfully. Also you can try the following to connect to mailboxes: 1) poplib 2) smtplib For parsing the mails I would recommend pyparsing. [1] http://www.google.com/search?client=opera&rls=en&q=python+email&sourceid=opera&ie=utf-8&oe=utf-8 Regards Nicolaas -- The three things to remember about Llamas: 1) They are harmless 2) They are deadly 3) They are made of lava, and thus nice to cuddle. From sk8in_zombi at yahoo.com.au Fri Jul 11 12:16:05 2008 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Fri, 11 Jul 2008 09:16:05 -0700 (PDT) Subject: Simple Image Cropper Message-ID: <793799.70431.qm@web54501.mail.re2.yahoo.com> Hi, I am designing a simple image cropper which simply takes an image and use PIL to do the cropping.Now in order to do the cropping I simply draw a rectangle on the image by dragging the mouse over the image.I then use button press and button release events to find the mouse postition and send across the tuple to PIL? .Everything works fine but what I need is a way to show the user a dotted rectangle as he drags across the mouse as in every other standard image editor.I have learnt that using gnomecanvas will do that but given my time constraints and the lack of a tutorial on pygtk ,I used gtk.image + event box to do the above. Can someone point to using gnomecanvas in the following directions: 1.Load an image into the canvas from file as well as pixbuf. 2.Draw a dotted rectangle 3.Fire and capture mouse events 4.Use PIL I basically want to know about point 2. Also,will implementing cairo be easy on glade and pygtk? Regards, Abhishek " life isn't heavy enough,it flies away and floats far above action" Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: From maryam9646 at gmail.com Wed Jul 2 11:14:13 2008 From: maryam9646 at gmail.com (maryam9646 at gmail.com) Date: Wed, 2 Jul 2008 08:14:13 -0700 (PDT) Subject: free web design templates using free downloading Message-ID: <56b1ebf7-6ab2-4dfe-8210-eeac2d59e960@z24g2000prf.googlegroups.com> Success usually comes to those who are too busy to be looking for it Visit Mobiles & Computers?, http://www.mobilecomputers4all.blogspot.com/
Hi..Click me

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi..Click me

From ldo at geek-central.gen.new_zealand Thu Jul 24 06:03:26 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 24 Jul 2008 22:03:26 +1200 Subject: Confounded by Python objects References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> Message-ID: In message <33c9309a-9679-41f6-a777-2874aad1903a at z66g2000hsc.googlegroups.com>, boblatest at googlemail.com wrote: > class Channel: > name = '' > sample = [] These are class variables, not instance variables. Take them out, and ... > def __init__(self, name): > self.name = name ... add this line to the above function self.sample = [] From alan.franzoni.blahblah at example.com.invalid Thu Jul 31 04:44:08 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Thu, 31 Jul 2008 08:44:08 GMT Subject: Possible to have multiple loop variables? References: <5ff22b51-88e9-405c-aeb9-7b0abe9cf935@r66g2000hsg.googlegroups.com> Message-ID: <17l8ky2s9ntqz$.dn7j54skaf95$.dlg@40tude.net> laredotornado was kind enough to say: > How would I set up the ms1 array such that I can use three items per > object? Use tuples. But that should depend on which values make up the key for your mapping. E.g. ms1 = {('managed1':7019):8020, ('managed2':7020):8021} ms2 = {'managed1':(7019:8020), 'managed2':(7020:8021)} depending on what you want, and then iterate over such structure just like Marc suggested. Otherwise, you can create a custom class which returns three-tuples when iterated, in such case you can just extract m, lp, ssl_lp in the for cycle just like your example. -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From babacity4 at gmail.com Thu Jul 24 16:52:19 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:52:19 -0700 (PDT) Subject: free sextv1 tv - Amazing porn video collection Message-ID: free sextv1 tv . >>>>>>>>>>Best Collection of Sextv1 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE sextv1 tv VIDEOS<<<<<<<<<<< . free sextv1 tv From animator333 at gmail.com Fri Jul 25 13:05:14 2008 From: animator333 at gmail.com (King) Date: Fri, 25 Jul 2008 10:05:14 -0700 (PDT) Subject: object persistency, store instances relationship externally References: <3183af12-4b1e-4bd1-8d21-b9fc2b421008@v1g2000pra.googlegroups.com> Message-ID: Thanks Fredrik, It helped a lot and this is really an amazing this I have discovered today. :-)) From praveen.sunsetpoint at gmail.com Mon Jul 7 02:10:24 2008 From: praveen.sunsetpoint at gmail.com (Sallu) Date: Sun, 6 Jul 2008 23:10:24 -0700 (PDT) Subject: Validation in plone Message-ID: <3d02ab9e-6f81-4b56-b6ef-786e8e6f070a@m44g2000hsc.googlegroups.com> Hi all and one, How to do server side validation in plone? please help me its very urgent. i created a validator.py file where i wrote a script for 'special character are not allowed' and calling that script in movie.py its working fine by validators = ('splcharvalid',), and when i wrote another script for email validation and want to call in same field like validators = ('emailvalid',), and i am calling like this validators = ('splcharvalid',),('emailvalid',), but its not working even i wrote like this too validators = ('splcharvalid','emailvalid',), but its too not working.. could you please help mr to resolve this problem or may tell me another way to do validation in plone.. From ldo at geek-central.gen.new_zealand Sat Jul 26 19:43:09 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 27 Jul 2008 11:43:09 +1200 Subject: scanf in python References: <4884be5e$0$19722$426a74cc@news.free.fr> <6ek4cgF7hq4vU1@mid.uni-berlin.de> <4884e77a$0$29405$426a74cc@news.free.fr> <4889ae4a$0$3726$426a74cc@news.free.fr> Message-ID: In message <4889ae4a$0$3726$426a74cc at news.free.fr>, AMD wrote: >> In message <4884e77a$0$29405$426a74cc at news.free.fr>, AMD wrote: >> >>> Actually it is quite common, it is used for processing of files not for >>> reading parameters. You can use it whenever you need to read a simple >>> csv file or fixed format file which contains many lines with several >>> fields per line. >> >> I do that all the time, in Python and C++, but I've never felt the need >> for a scanf-type function. > > I agree scanf is not a must have function but rather a nice to have > function. I've never felt that scanf would be "nice" to have. Not in Python, not in C++. From norseman at hughes.net Wed Jul 9 12:59:32 2008 From: norseman at hughes.net (norseman) Date: Wed, 09 Jul 2008 09:59:32 -0700 Subject: start reading from certain line In-Reply-To: <1215601039.2873.972.camel@localhost.localdomain> References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> <1215601039.2873.972.camel@localhost.localdomain> Message-ID: <4874EE74.80801@hughes.net> Tim Cook wrote: > On Wed, 2008-07-09 at 03:30 -0700, antar2 wrote: >> I am a starter in python and would like to write a program that reads >> lines starting with a line that contains a certain word. >> For example the program starts reading the program when a line is >> encountered that contains 'item 1' >> >> >> The weather is nice >> Item 1 >> We will go to the seaside >> ... >> >> Only the lines coming after Item 1 should be read > > file=open(filename) > while True: > line=file.readline() > if not line: > break > > if 'Item 1' in line: > print line > > > HTH, > Tim > > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list ======================================================= I would use: readthem= 0 file=open(filename,'r') while readthem == 0: line=file.readline() if not line: break if 'Item 1' in line: readthem= 1 # print line # uncomment if 'Item 1' is to be printed while line: line= file.readline() print line # see note-1 below # end of segment The first while has lots of needed tests causing lots of bouncing about. May even need more tests to make sure it is right tag point. As in if 'Item 1' accidentally occurred in a line previous to intended one. The second while just buzzes on through. If the objective is to process from tag point on then processing code will be cleaner, easier to read in second while. note-1: in this form the line terminators in the file are also printed and then print attaches it's own EOL (newline). This gives a line double spacing effect, at least in Unix. Putting the comma at the end (print line,) will stop that. You will need to modify two lines if used. Which to use depends on you. Steve norseman at hughes.net From stochashtic at yahoo.ca Mon Jul 28 04:03:15 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 28 Jul 2008 10:03:15 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> Message-ID: <488d7d43$1@news2-rz-ap.ethz.ch> On Fri, 25 Jul 2008 05:46:56 -0700, Iain King wrote: > or 3. build a new list every iteration intead of deleting from the old > one: > > while processing: > new_off_list = [] > for x in off_list: > if goes_on(x): > on_list.append(x) > else: > new_off_list.append(x) > off_list = new_off_list > generation += 1 > > Iain Or 4, since the order of my nodes doesn't matter: swap the node to be deleted with the last node in the list and then remove the last node of the list. This is the fastest to date, if using native structures, for low number nodes being deleted per cycle (def if only deleting one). From __peter__ at web.de Fri Jul 11 07:53:09 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jul 2008 13:53:09 +0200 Subject: MySQLdb will only import for root References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> Message-ID: martinnorth wrote: > Hi, > > I am running Python and MySQL on Ubuntu and have installed MySQLdb. If I > try to import MySQLdb I get the following error: > > ActivePython 2.5.2.2 (ActiveState Software Inc.) based on > Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08) > [GCC 3.3.1 (SuSE Linux)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import MySQLdb > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named MySQLdb > > But if I lrun python as the root user it imports fine. Can anyone > suggest what might be wrong with the installation? Or is there nothing > wrong? I haven't seen any examples that mentioned being root to import a > module. You have probably installed two versions of Python. You can verify that by typing $ which python and $ sudo which python I suspect that root sees the python that comes with Ubuntu and that has MySQLdb installed while the normal user sees ActiveState's Python. Peter From callen314 at gmail.com Mon Jul 21 21:35:14 2008 From: callen314 at gmail.com (Craig Allen) Date: Mon, 21 Jul 2008 18:35:14 -0700 (PDT) Subject: Python Written in C? References: Message-ID: it's clear to me that the perfect language should exist a priori, coming to being causa sui. Having to actually implement a language is disgusting and unnatural. From __peter__ at web.de Wed Jul 9 02:17:03 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 09 Jul 2008 08:17:03 +0200 Subject: (silly?) speed comparisons References: Message-ID: mk wrote: > Now C++ version took over twice the time to execute in comparison to > Python time! > Am I comparing apples to oranges? Indeed. Where in Python you're passing references your C++ code produces copies of the vector. For starters you can change the function signature to void move_slice(vector& vec, int start, int stop, int dest) which should already give your C++ implementation a significant speed boost. Peter From weizhonghua.ati at gmail.com Wed Jul 16 05:06:56 2008 From: weizhonghua.ati at gmail.com (zhw) Date: Wed, 16 Jul 2008 02:06:56 -0700 (PDT) Subject: How can i use a variable without define it ? References: <87k5fm2p1x.fsf@benfinney.id.au> Message-ID: <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> On 7?16?, ??4?47?, Ben Finney wrote: > zhw writes: > > How can i use a variable without define it ? > > What do you mean by "use"? That's so vague I can think of many > possible interpretations. > > What do you mean by "variable"? That term carries a lot of baggage > that doesn't apply in Python. > > Can you give a small, complete example that demonstrates the issue > you're trying to solve? > > -- > \ ?The face of a child can say it all, especially the mouth part | > `\ of the face.? ?Jack Handey | > _o__) | > Ben Finney Thank you! Sorry for my poor english! Here is a example that I want to complete: >>> import sys, new >>> context={"name":"david", "sex":"male"} >>> sys.modules["foo"] = new.module("foo") >>> import foo >>> for attr in context: setattr(foo, attr, context[attr]) >>> def bar(): # here is a error # import * only allowed at module level from foo import * print name, sex >>> bar() From stef.mientki at gmail.com Tue Jul 29 03:43:26 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 29 Jul 2008 09:43:26 +0200 Subject: Is it allowed to use function results as default arguments ? In-Reply-To: References: <488E2BF1.8020003@gmail.com> Message-ID: <488ECA1E.8090706@gmail.com> Terry Reedy wrote: > To answer the subject line: > param= > will assign the result of the expression as the default argument > object for the parameter. > thanks Terry and others, brings me to one other question: I guess this function is only evaluated once, is that correct ? about os.curdir, I checked it, it's already a constant ;-) and because I use afterwards: os.path.abspath('.'') which is identical to os.path.getcwd() about '.' being the current directory, well I think windows was thrown at the market about 25 years ago, and since then we don't use '.' anymore ;-) cheers, Stef > tjr > > -- > http://mail.python.org/mailman/listinfo/python-list From jfabiani at yolo.com Tue Jul 22 09:54:09 2008 From: jfabiani at yolo.com (John Fabiani) Date: Tue, 22 Jul 2008 06:54:09 -0700 Subject: need thumbnail from video Message-ID: Hi, I need a py tool that will provide a thumbnail (bmp?) from a video (avi, wmv) that will be cross platform (linux, windows). Research has provided pymedia for Linux but I haven't found anything for windows. Hopefully, someone has had to do this in the past and knows what has to be done. Thanks in Advance, Johnf From phillip.oldham at gmail.com Thu Jul 10 05:25:26 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Thu, 10 Jul 2008 02:25:26 -0700 (PDT) Subject: FOSS projects exhibiting clean/good OOP? References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> Message-ID: <3bd416cf-6989-44fb-961d-658032231356@m73g2000hsh.googlegroups.com> Thanks all - lots to go through there! :D I'd heard previously that Trac was a nice example, or rather its core was, but I'd also heard that there were lots of problems with it and that they were redeveloping it from scratch? From omer at no-log.org Wed Jul 2 10:07:26 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Wed, 2 Jul 2008 16:07:26 +0200 Subject: simple UnZip In-Reply-To: <5b915a0e-a227-460f-8273-ecc01b800884@2g2000hsn.googlegroups.com> References: <5b915a0e-a227-460f-8273-ecc01b800884@2g2000hsn.googlegroups.com> Message-ID: <200807021607.26668.omer@no-log.org> Le Wednesday 02 July 2008 15:39:51 noydb, vous avez ?crit?: > Can someone help me with this script, which I found posted elsewhere? > I'm trying to figure out what is going on here so that I can alter it > for my needs, but the lack of descriptive names is making it > difficult. And, the script doesn't quite do anything worthwhile -- it > unzips one file from a zipfile, not all files in a zipfile. > > *** > import zipfile, os, sys, glob > > os.chdir("C:\\Temp") > zips = glob.glob('*.zip') > > for fzip in zips: > if zipfile.is_zipfile(fzip): > print fzip," is a zip" > z = zipfile.ZipFile(fzip,'r') > lstName = z.namelist() > sHgt = lstName[0] > print "Unpacking",sHgt > hgt = z.read(sHgt) > fHgt = open(sHgt,'wb') > fHgt.write(hgt) > # fHgt.flush > fHgt.close > print "Finished" > *** > > I changed it somewhat to > &&& > import zipfile, os, sys > > event_zip = ("C:\\Temp\\data4event.zip") > > z = zipfile.ZipFile(event_zip, 'r') > > zList = z.namelist() > > for zItem in zList: > print "Unpacking",zItem > zRead = z.read(zItem) > z1File = open(zItem,'wb') > z1File.write(zRead) > z1File.close namelist() returns a list of relative file names, so you can just put them anywhere you want with: zlFile = open(os.path.join(DESTDIR, zItem), 'wb') or change the current directory, but the first way should be preferred. > print "Finished" > &&& > > This works, but I want to be able to specify a different output > location. > -- C?dric Lucantis From lloyd at treleven.freeserve.co.uk Fri Jul 18 11:27:22 2008 From: lloyd at treleven.freeserve.co.uk (lloyd at treleven.freeserve.co.uk) Date: Fri, 18 Jul 2008 17:27:22 +0200 (CEST) Subject: Python evening class Message-ID: <33249062.1062901216394841974.JavaMail.www@wwinf3724> I am learning about python but I would like to attend and evening class at college as I find it hard to study at home. Does anyone know of such a class in London UK? From gnuarm at gmail.com Sun Jul 13 14:50:23 2008 From: gnuarm at gmail.com (rickman) Date: Sun, 13 Jul 2008 11:50:23 -0700 (PDT) Subject: spam References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> <487a0d4d$0$90272$14726298@news.sunsite.dk> Message-ID: <44d31c76-9909-46b1-943d-99e8bd363d8e@56g2000hsm.googlegroups.com> spam From wmcbrine at users.sf.net Fri Jul 4 23:28:32 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Sat, 05 Jul 2008 03:28:32 GMT Subject: Can't get Python for Windows to run References: Message-ID: On Fri, 04 Jul 2008 16:19:34 +0100, Tim Rowe wrote: > pythonw.exe (that's the windows executable, right?) python.exe and pythonw.exe are both Windows executables. There are no non- Windows executables in a Python for Windows package. python.exe is used for console apps or interactive sessions. pythonw.exe suppresses the console window. You use it to launch GUI apps that don't need a console. You can't use it for an interactive session, and it makes no sense to start it without also specifying a Python program to run. Python source files named with the ".pyw" extension are associated with pythonw.exe, while ".py" is associated with python.exe. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From pavlovevidence at gmail.com Fri Jul 4 23:34:03 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 4 Jul 2008 20:34:03 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: On Jul 4, 4:43 pm, "Filipe Fernandes" wrote: > On Fri, Jul 4, 2008 at 8:36 AM, Peter Otten <__pete... at web.de> wrote: > > Henning_Thornblad wrote: > > >> What can be the cause of the large difference between re.search and > >> grep? > > > grep uses a smarter algorithm ;) > > >> This script takes about 5 min to run on my computer: > >> #!/usr/bin/env python > >> import re > > >> row="" > >> for a in range(156000): > >> row+="a" > >> print re.search('[^ "=]*/',row) > > >> While doing a simple grep: > >> grep '[^ "=]*/' input (input contains 156.000 a in > >> one row) > >> doesn't even take a second. > > >> Is this a bug in python? > > > You could call this a performance bug, but it's not common enough in real > > code to get the necessary brain cycles from the core developers. > > So you can either write a patch yourself or use a workaround. > > > re.search('[^ "=]*/', row) if "/" in row else None > > > might be good enough. > > Wow... I'm rather surprised at how slow this is... using re.match > yields much quicker results, but of course it's not quite the same as > re.search > > Incidentally, if you add the '/' to "row" at the end of the string, > re.search returns instantly with a match object. This behavior is showing that you're getting n-squared performance; the regexp seems to be checking 156000*(156000-1)/2 substrings for a match. I don't think it's possible to avoid quadratic behavior in regexps in general, but clearly there are ways to optimize in some cases. I'm guessing that grep builds a table of locations of individual characters as it scans and, when the regexp exhausts the input, it tries to backtrack to the last slash it saw, except there wasn't one so it knows the regexp cannot be satisfied and it exits early. > @ Peter > I'm not versed enough in regex to tell if this is a bug or not > (although I suspect it is), I'm pretty sure it isn't: the regexp documentation makes no claims as to the performance of the regexp that I'm aware of. > but why would you say this particular > regex isn't common enough in real code? When re.search regexps start with things like [^...]* or .*, typically the excluded characters are a typically found frequently in the input. For example, the pattern .*hello.* could be used to find a line with hello in it, with the expectation that there are lots of newlines. But if there aren't any newlines the regexp wouldn't be very useful. Carl Banks From mattheww at chiark.greenend.org.uk Mon Jul 21 12:43:29 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 21 Jul 2008 17:43:29 +0100 (BST) Subject: Python Written in C? References: Message-ID: Roy Smith wrote: > C is the highest level assembler language I've ever used. And I've used a > few. It really is cool that you can add two 32-bit integers and not have > to worry about all those carry bits. I was ever so pleased when I found out that the LLVM people have learned this lesson from C. I look forward to the day when we can have similar treatment for all forms of error checking. Programming will be so much easier. -M- From stef.mientki at gmail.com Mon Jul 28 15:56:33 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 28 Jul 2008 21:56:33 +0200 Subject: how to upload files to "google code" filesection ? In-Reply-To: <63de76c2-349c-4371-8732-1681301c7ab0@a1g2000hsb.googlegroups.com> References: <7f6182a3-4504-4239-8239-673a7e4bfefd@s50g2000hsb.googlegroups.com> <63de76c2-349c-4371-8732-1681301c7ab0@a1g2000hsb.googlegroups.com> Message-ID: <488E2471.9050801@gmail.com> Mike Driscoll wrote: > Stef, > > >> Mike Driscoll wrote: >> >>> On Jul 26, 12:43 pm, Stef Mientki wrote: >>> >>>> hello, >>>> >>>> In a program I want to download (updated) files from google code (not >>>> the svn section). >>>> I could find a python script to upload files, >>>> but not for downloading. >>>> >>>> Anyone has a hint or a solution ? >>>> >>>> thanks, >>>> Stef Mientki >>>> >>> You should be able to use urllib to do that. The following link has a >>> recipe: >>> >>> http://code.activestate.com/recipes/496685/ >>> >> thanks Mike, >> >> I already found an even simpler solution (that works) >> >> filename, header = urllib.urlretrieve (url) >> >> >>> If you need to search Google Code, there's an API that appears to be >>> exposed through their gdata module. >>> >> Do you have perhaps a more specific link ? >> I saw the Google API's, but its'quit large / complex, so I couldnt find >> it there. >> >> cheers, >> Stef >> >> >>> Mike >>> > > I was looking at this page about Google Code Search: > http://code.google.com/apis/codesearch/ > > You should be able to use the API that's outlined there in conjunction > with the gdata module on this page: > > http://code.google.com/p/gdata-python-client/ > > thanks Mike, I'll take a look at those links. cheers, Stef > Mike > > -- > http://mail.python.org/mailman/listinfo/python-list > From max at alcyone.com Wed Jul 30 02:16:43 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 23:16:43 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > On Jul 29, 10:33 pm, Carl Banks wrote: >> On Jul 30, 1:15 am, "Russ P." wrote: > >>> Having said that, it would sure be nice to be able to write >>> if myList is not empty: >>> instead of >>> if len(myList) != 0: >> I can agree with this. > > But I guess that could only work if there were only one empty list > that represents all empty lists (as there is only one actual "None"). > I don't know if that makes sense or not. It really doesn't, since it presumably wouldn't apply to just list types. There are plenty of other sequence types: such as tuples, strings, or even arbitrary custom types. Emptiness is a test for the value of an object, not a test for whether it is identical to another object, so this is a very misleading of the `is` operator, bordering on abuse. This syntax would make far less sense than the existing Boolean test. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The doors of Heaven and Hell are adjacent and identical. -- Nikos Kazantzakis From mail at microcorp.co.za Mon Jul 7 09:31:15 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 7 Jul 2008 15:31:15 +0200 Subject: Cross Comiler for Python? Message-ID: <001001c8e036$e79ad940$0d00a8c0@hendrik> Diez wrote: >Look at the gumstix project, they do have a cross-compiled python in there. >You should be able to get an idea on how to do that yourself. > >It involves (or at least did back then) a bit of trickery as the >build-process of python uses the freshly created interpreter to pre-compile >modules. But it is possible. Thanks Diez will look at it. From mail at timgolden.me.uk Wed Jul 16 10:39:29 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 15:39:29 +0100 Subject: About wmi In-Reply-To: References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> Message-ID: <487E0821.3010808@timgolden.me.uk> patrol wrote: > The errors are in the following: > > Traceback (most recent call last): > File "D:\My Documents\code\python\wmi\test.py", line 5, in > c = wmi.WMI ("non-existent computer") > File "C:\Python25\lib\wmi.py", line 1199, in connect > handle_com_error (error_info) > File "C:\Python25\lib\wmi.py", line 184, in handle_com_error > exception_string = [u"%s - %s" % (hex (hresult_code), > hresult_name)] > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > 4: ordinal not in range(128) OK, I'm trying to set up a Virtual PC so I can install a non-English XP. But would you mind running the following code for me, please, so I can get a handle on what's coming back: import pythoncom import win32com.client try: win32com.client.GetObject ("winmgmts://blahblah") except pythoncom.com_error, info: for i in info: print repr (i) Thanks TJG From iainking at gmail.com Thu Jul 10 11:56:20 2008 From: iainking at gmail.com (Iain King) Date: Thu, 10 Jul 2008 08:56:20 -0700 (PDT) Subject: start reading from certain line References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> <1215601039.2873.972.camel@localhost.localdomain> <5de66f4b-b931-4618-b461-29a43e5a119d@25g2000hsx.googlegroups.com> Message-ID: On Jul 10, 4:54?pm, Iain King wrote: > On Jul 10, 2:45?pm, jstrick wrote: > > > Here's a simple way to do it with a minimum amount of loopiness (don't > > forget to use 'try-except' or 'with' in real life): > > > f = open("item1.txt") > > > for preline in f: > > ? ? if "Item 1" in preline: > > ? ? ? ? print preline, > > ? ? ? ? for goodline in f: > > ? ? ? ? ? ? # could put an end condition with a 'break' here > > ? ? ? ? ? ? print goodline, > > > f.close() > > No Ignore that From alif016 at gmail.com Sat Jul 19 21:14:08 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Sat, 19 Jul 2008 20:14:08 -0500 Subject: trying to match a string In-Reply-To: References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> <945275e9-8923-479c-8eec-258bd68063c0@z6g2000pre.googlegroups.com> <4881FE02.3000203@gmail.com> Message-ID: <48829160.4070800@gmail.com> John Machin wrote: > On Jul 20, 5:00 am, Andrew Freeman wrote: > >> Andrew Freeman wrote: >> >>> John Machin wrote: >>> >>>> A couple of points: >>>> (1) Instead of search(r'^blahblah', ...) use match(r'blahblah', ...) >>>> (2) You need to choose your end-anchor correctly; your pattern is >>>> permitting a newline at the end: >>>> >> I forgot to change search to match. This should be better: >> >> def match(var): >> if re.match(r'[LRM]*\Z', var): >> return True >> else: >> return False >> > > A bit wordy ... > > if blahblah: > return True > else: > return False > > can in total generality be replaced by: > > return blahblah > > > >> I was also thinking if you had a list of these items needing to be >> verified you could use this: >> > > You could, but I suggest you don't use it in a job interview :-) > > >> >>> l = ['LLMMRR', '00thLL', 'L', '\n'] >> > > (1) Don't use 'L'.lower() as a name; it slows down reading as people > need to fire up their mental parser to distinguish it from the result > of 3 - 2 > > >> >>> out = [] >> >>> map(lambda i: match(i)==False or out.append(i), l) >> > (2) Read PEP 8 > (3) blahblah == False ==> not blahblah > (4) You didn't show the output from map() i.e. something like [None, > True, None, True] > (5) or out.append(...) is a baroque use of a side-effect, and is quite > unnecessary. If you feel inexorably drawn to following the map way, > read up on the filter and reduce functions. Otherwise learn about list > comprehensions and generators. > > >> >>> print out >> ['LLMMRR', 'L'] >> >> > > Consider this: > > >>>> import re >>>> alist = ['LLMMRR', '00thLL', 'L', '\n'] >>>> zeroplusLRM = re.compile(r'[LRM]*\Z').match >>>> filter(zeroplusLRM, alist) >>>> > ['LLMMRR', 'L'] > >>>> [x for x in alist if zeroplusLRM(x)] >>>> > ['LLMMRR', 'L'] > Thank you for the pointers! (1) Depending on the typeface I totally agree, Courier New has a nearly indistinguishable 1 and l, I'm using Dejavu Sans Mono (Bitstream Vera based). I was just thinking of it as a generic variable name for some input. I'm fairly new to python and programming in general, it's more of a hobby. (2-3) This is actually the first time I've used map, maybe I should not give extra examples, I was actually using it as a learning tool for myself. I'm very thankful the mailing list has such skilled contributers, such as yourself, but I assume that it can't hurt to give working code, even though the style is less than perfect. (3) Personally I think map(lambda i: match(i)==False or out.append(i), l) is a little more readable than map(lambda i: not match(i) or out.append(i), l) even if "baroque", your use of filter is obviously much clearer than either. (4) I highly doubt that this code was actually to be used in an interactive session, the False/True output was truncated intentionally, it's an obvious, but superfluous output (unless you were to rely on this by attaching it to a variable which might lead to sorting issues). (5) Thank you very much, I've read of the filter and reduce functions, but haven't used them enough to recognize their usefulness. I did realize that a list comprehension would be useful, but wanted to try map() I put together a generic matcher that returns either a list of True data (if the input is a list or tuple) or a boolean value: def match(ex, var): "ex is the regular expression to match for, var the iterable or string to return a list of matching items or a boolean value respectively." ex = re.compile(ex).match if isinstance(var, (list, tuple)): return filter(ex, var) else: return bool(ex(var)) I believe this is fairly clean and succinct code, it would help my learning immensely if you feel there is a more succinct, generic way of writing this function. -- Andrew From vinay_sajip at yahoo.co.uk Tue Jul 15 19:21:52 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 15 Jul 2008 16:21:52 -0700 (PDT) Subject: Logging to different addressees References: <8df30038-86c1-4376-b046-a50f2bcf0a2b@s50g2000hsb.googlegroups.com> <7b829a76-ba2c-4cb7-b216-0c9c01e5cd02@f36g2000hsa.googlegroups.com> Message-ID: <4d3df1d9-339b-43b2-9f25-c792e9bf549c@k13g2000hse.googlegroups.com> On Jul 15, 5:17 pm, McA wrote: > > If you added the admin sink handler to the root logger, you're done. > > Isn't that the first thing above? What do you mean? I gave you a choice - to add the handler to the admin_logger OR the root logger. So I am saying here that if you added to the root logger (and not common_logger, assuming they're different), then there's nothing more to do... > > > Otherwise, you need to ensure that certain_logger is a child of > > common_logger. > > What I want to code is something like that. > a) I know thet this is a message for the admin only: > admin_logger.log('blabla') (admin_logger = root_logger =logging.get_logger("")) > > b) certain_logger.log('something' => log to the root/admin/-sink as > well as to the > certain-sink. > > Do I have to create a logger subclass where I do the multiplexing of > theloggingmessages? > I'm pretty sure I miss something. ;-) > No, the logging package is designed to allow flexibility of different events being logged to different destinations. There's no need to subclass Logger to achieve what you're asking for. The following script: # simple.py import logging admin_logger = logging.getLogger("") # The root logger addressee_logger = logging.getLogger("addressee") admin_sink = logging.FileHandler("admin.log", "w") addressee_sink = logging.FileHandler("addressee.log", "w") admin_logger.addHandler(admin_sink) addressee_logger.addHandler(addressee_sink) admin_logger.setLevel(logging.DEBUG) admin_logger.debug("This message appears in admin sink only.") addressee_logger.debug("This message appears in both admin sink and addressee sink." # - end of simple.py Generates the following results: ---------------------------------------------------------- admin.log ---------------------------------------------------------- This message appears in admin sink only. This message appears in both admin sink and addressee sink. ---------------------------------------------------------- addressee.log ---------------------------------------------------------- This message appears in both admin sink and addressee sink. Regards, Vinay Sajip From malaclypse2 at gmail.com Wed Jul 30 17:01:39 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 30 Jul 2008 17:01:39 -0400 Subject: Python parsing iTunes XML/COM In-Reply-To: References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Message-ID: <16651e80807301401ga381259u3f2833a35bea8e17@mail.gmail.com> On Wed, Jul 30, 2008 at 2:27 PM, william tanksley wrote: > Awesome... Thank you! I had my mental model of Python turned around > backwards. That's an odd feeling. Okay, so you decode to go from raw > byes into a given encoding, and you encode to go from a given encoding > to raw bytes. Not what I thought it was, but that's cool, makes sense. That's not quite right. Decoding takes a byte string that is already in a particular encoding and transforms it to unicode. Unicode isn't a encoding of it's own. Decoding takes a unicode string (which doesn't have any encoding associated with it), and gives you back a sequence of bytes in a particular encoding. This article isn't specific to Python, but it provides a good overview of unicode and character encodings that may be useful: http://www.joelonsoftware.com/articles/Unicode.html -- Jerry From james.b.looney at lmco.com Fri Jul 18 15:33:00 2008 From: james.b.looney at lmco.com (Looney, James B (N-ULA)) Date: Fri, 18 Jul 2008 13:33:00 -0600 Subject: Confused about error: invalid Python installation: unable to open ..../python2.4/config/Makefile Message-ID: I built and installed Python 2.4 on 12/12/2007. Recently, I tried installing python-ldap-2.3.4. The error I received was: error: invalid Python installation: unable to open /usr/local/openSource/architectureIndependent:/usr/local/openSource/IRIX 6/lib/python2.4/config/Makefile (No such file or directory) I figured out what I believe to be the origin of this string. When I ran configure to build/install Python, I used the following: ./configure --prefix=/usr/local/openSource/architectureIndependent --exec-prefix=/usr/local/openSource/IRIX6 --enable-shared --without-gcc --with-cxx=CC Somewhere along the lines, the prefix and exec-prefix strings were joined with a ':'. I just went searching around, and found that sys.prefix = '', and sys.exec_prefix="/usr/local/openSource/architectureIndependent:/usr/loca l/openSource/IRIX6" In past posts, I've found people referring to needing to install python-devel, and I have no idea why installing an additional package would help the installation of other packages. Does anyone have any thoughts as to why I'm getting the error? How about thoughts on why the prefix and exec-prefix strings were joined? Thanks, -James -------------- next part -------------- An HTML attachment was scrubbed... URL: From mnordhoff at mattnordhoff.com Mon Jul 7 04:23:18 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 07 Jul 2008 08:23:18 +0000 Subject: mirroring files and data via http In-Reply-To: <9a56e820-164f-4151-82f0-0bdf64c6a636@59g2000hsb.googlegroups.com> References: <9a56e820-164f-4151-82f0-0bdf64c6a636@59g2000hsb.googlegroups.com> Message-ID: <4871D276.2030600@mattnordhoff.com> Steve Potter wrote: > On Jul 6, 8:19 pm, Matt Nordhoff wrote: >> Steve Potter wrote: >>> I'm working on a project to create a central administration interface >>> for several websites located on different physical servers. >>> You can think of the websites as a blog type application. My >>> administration application will be used to create new blog posts with >>> associated media (images, etc..) >>> So I am thinking to setting up a script on each of the sites to "phone >>> home" once per day and download any new posts and media files. >>> I am thinking of transmitting the post data in an xml format that >>> could then be decoded an recorded into the database on the slave >>> site. Are there any easy ways to encode a python dictionary to and >>> from xml? >>> For the media files I am thinking that the administration interface >>> would also provide an xml file with a list of all of the media files >>> required along with an http path to retrieve them and a checksum of >>> some sort to verify that they were downloaded correctly. >>> Basically I am trying to figure out if anything already exists to >>> perform some of these functions or if I have to make them from >>> scratch. I know none of it should be too hard, but I hate to re- >>> invent the wheel. >>> Thanks, >>> Steven Potter >> It sounds like JSON would be perfect for this. For working with it in >> Python, the simplejson module is popular: >> >> >> -- > > Matt, > > You are correct JSON would be much easier to deal with than xml. That > takes care of several of the problems. > > Now it really just comes down to the file transfer from one server to > the other and a verification of some sort that the file transfer was > not corrupt. Is there a python module that takes care of file > downloads and verification? > > Thanks, > > Steve Not automatically, but this should be easy to do yourself. You could generate a simple JSON or plain text file listing URLs and hashes, and then use urllib or urllib2 to download them, and md5, sha1 or (in Python 2.5) hashlib to verify them. All of those modules are in the standard library. -- From sk8in_zombi at yahoo.com.au Fri Jul 11 16:55:32 2008 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Fri, 11 Jul 2008 13:55:32 -0700 (PDT) Subject: Adding a Cairo object into a vbox using pygtk Message-ID: <273437.63112.qm@web54507.mail.re2.yahoo.com> Hi , I am trying to attach a cairo object into a vbox.I can pack a textbox with the following code: ??? entry = gtk.Entry() ??? entry.set_max_length(50) ??? entry.connect("activate", self.enter_callback, entry) ??? entry.set_text("hello") ??? entry.insert_text(" world", len(entry.get_text())) ??? entry.select_region(0, len(entry.get_text())) ??? self.vbox.pack_start(entry, True, True, 0) ??? entry.show() but when I do the same for a cairo object I had created from the pycairo examples ,it wont. ??????? self.window = builder.get_object("mainwindow") ??????? self.vbox = builder.get_object("winvbox") ??? # connect signals ??????? builder.connect_signals(self) ??? .... ?? ??? self.cairorun(cairoshape) ??????? ??? def cairorun(self,Widget): ?? ??? widget = Widget() ??? self.vbox.pack_start(widget, True, True, 0) ??? widget.show() class cairoshape(framework.Screen): ??? def draw(self, cr, width, height): ??? image = cairo.ImageSurface.create_from_png ("image.png") ??? cr.set_source_surface (image, 0, 0) ??? cr.paint () and the framework.py from the examples: #! /usr/bin/env python import pygtk pygtk.require('2.0') import gtk, gobject, cairo # Create a GTK+ widget on which we will draw using Cairo class Screen(gtk.DrawingArea): ??? # Draw in response to an expose-event ??? __gsignals__ = { "expose-event": "override" } ??? # Handle the expose-event by drawing ??? def do_expose_event(self, event): ??????? # Create the cairo context ??????? cr = self.window.cairo_create() ??????? # Restrict Cairo to the exposed area; avoid extra work ??????? cr.rectangle(event.area.x, event.area.y, ??????????????? event.area.width, event.area.height) ??????? cr.clip() ??????? self.draw(cr, *self.window.get_size()) ??? def draw(self, cr, width, height): ??????? # Fill the background with gray ??????? cr.set_source_rgb(0.5, 0.5, 0.5) ??????? cr.rectangle(0, 0, width, height) ??????? cr.fill() # GTK mumbo-jumbo to show the widget in a window and quit when it's closed def run(Widget): ??? window = gtk.Window() ??? window.connect("delete-event", gtk.main_quit) ??? widget = Widget() ??? widget.show() ??? window.add(widget) ??? window.present() ??? gtk.main() if __name__ == "__main__": ??? run(Screen) In short,I can attach the cairo widget to a main window but I'm unable to pack it into a vbox. Regards, SZ " life isn't heavy enough,it flies away and floats far above action" Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: From sn.oo.py.9027 at gmail.com Mon Jul 14 06:05:56 2008 From: sn.oo.py.9027 at gmail.com (John Mechaniks) Date: Mon, 14 Jul 2008 03:05:56 -0700 (PDT) Subject: subprocess module References: <2e7f0504-cc1c-4cb6-b2d0-b67b004eca7d@x41g2000hsb.googlegroups.com> Message-ID: <39622612-5e43-45b4-800a-69277c2e2987@79g2000hsk.googlegroups.com> On Jul 14, 12:34?pm, Peter Otten <__pete... at web.de> wrote: > John Mechaniks wrote: > > from subprocess import call > > call(['ls', '-l']) > > > How do I get the result (not the exit status of the command) of "ls - > > l" into a variable? > > output = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE).stdout.read() > > Peter Thanks Peter. Just curious What difference does the following code makes? What are the advantages of the above method over this one? output = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE).communicate()[0] Also could someone show an example of using the optional input argument for communicate() From JordanNealBerg at gmail.com Thu Jul 10 00:42:58 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Wed, 9 Jul 2008 21:42:58 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: Message-ID: I realize I did a pretty bad job of explaining the problem. The problem is the python version is returning an r that is WAAAAY to big. Here is an example run through that function in each language: C: u starts at 1050 u += 0xe91aaa35; u is now -384127409 u ^= u >> 16; u is now -384153771 u += u << 8; u is now 56728661 u ^= u >> 4; u is now 56067472 b = (u >> 8) & 0x1ff; b is now 389 a = (u + (u << 2)) >> 19; a is now 534 r = a ^ hash_adjust[b]; r is now 6366 Python: u starts at 1050 u += 0xe91aaa35 u is now 3910839887L rut roh... From aoeui2008 at cox.net Sun Jul 20 20:58:56 2008 From: aoeui2008 at cox.net (Teiresias) Date: Sun, 20 Jul 2008 19:58:56 -0500 Subject: Python Written in C? References: Message-ID: <87mykcoxwv.fsf@cox.net> giveitawhril2008 at gmail.com writes: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? Well, yes, the interpreter and a handful of the core modules are written in C. However, most of Python -- especially the cool bits -- aren't written in C. They're written in ... Python! -- Teiresias From kyosohma at gmail.com Mon Jul 7 12:19:15 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 7 Jul 2008 09:19:15 -0700 (PDT) Subject: how to recognize IE window already opened using win32com extension References: <203fdfe3-78d6-4b08-a64f-a031df9cacc1@s50g2000hsb.googlegroups.com> Message-ID: <35175416-3e98-4151-a96e-a8a30def93c9@k13g2000hse.googlegroups.com> On Jul 7, 11:09?am, korean_dave wrote: > How do I use the win32com API to manipulate IE windows ALREADY open? > > ie = Dispatch("InternetExplorer.Application") opens a new window. > > But I'd like to be able to find, of windows already open, a specific > window (with a specified property, matching url, etc.) You'll probably want to re-post to the PyWin32 user's group, but in the mean time, here's one way to go about it. I use the following function: def windowEnumerationHandler(self, hwnd, resultList): ''' This is a handler to be passed to win32gui.EnumWindows() to generate a list of (window handle, window text) tuples. ''' resultList.append((hwnd, win32gui.GetWindowText(hwnd))) And call it like this: topWindows = [] win32gui.EnumWindows(self.windowEnumerationHandler, topWindows) Then you can use a for loop to iterate over the topWindows list to find the one with the correct title: for i in topWindows: if windowText in i[1]: # do something Notice that I use the win32gui module. Make sure you have the win32 modules installed or this won't work. Here's the link to PyWin32 group: http://mail.python.org/mailman/listinfo/python-win32 That should get you going...hopefully ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From bearophileHUGS at lycos.com Sat Jul 19 11:55:23 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 19 Jul 2008 08:55:23 -0700 (PDT) Subject: MethodChain Message-ID: Found from Reddit, it's for e ECMA(Java)Script, but something similar may be useful for Python too: http://jsclass.jcoglan.com/methodchain.html http://blog.jcoglan.com/2008/07/16/where-did-all-my-code-go-using-ojay-chains-to-express-yourself-clearly/ Bye, bearophile From matt at tplus1.com Sun Jul 13 13:55:04 2008 From: matt at tplus1.com (Matthew Wilson) Date: Sun, 13 Jul 2008 17:55:04 GMT Subject: Mutually referencing imports -- impossible? Message-ID: I started off with a module that defined a class Vehicle, and then subclasses Car and Motorcycle. In the Car class, for some bizarre reason, I instantiated a Motorcycle. Please pretend that this can't be avoided for now. Meanwhile, my Motorcycle class instantiated a Car as well. Then I moved the Car and Motorcycle classes into separate files. Each imported the Vehicle module. Then I discovered that my Car module failed because the global Motorcycle wasn't defined. The same problem happened in my Motorcycle module. Car and Motorcycle can't both import each other. In the beginning, when all three (Vehicle, Car, and Motorcycle) were defined in the same file, everything worked fine. I don't know how to split them out in separate files now though and I really wish I could because the single file is enormous. Any ideas? Matt From Lie.1296 at gmail.com Sat Jul 26 07:10:23 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 26 Jul 2008 04:10:23 -0700 (PDT) Subject: Insert character at a fixed position of lines References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> Message-ID: <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> On Jul 26, 5:42?pm, "Francesco Pietra" wrote: > I am still at the stone age, using scripts (e.g., to insert a string > after a string) of the type > > f = open("xxx.pdb", "r") > for line in f: > ? ?print line > ? ?if "H16Z POPC" in line: > ? ? ? ?print "TER" > f.close() > > That is, I have to learn about modules. In your scripts I am lost > about the filename for the pdb file to modify, In Python, stdin and stdout (as provided by the sys module) is a file- like object, i.e. it have similar behavior as regular files you opened with open(). stdin is a read-only file, while stdout is a write-only file. You already know how to make read-only file, f = open("xxx.pdb", "r"), to make it writable, you've got to use 'w' as the mode: f = open("xxx.pdb", "w") After that you can do this: f.write('some string') > francesco > > > > On Sat, Jul 26, 2008 at 11:35 AM, Lie wrote: > > On Jul 26, 2:41 pm, "Francesco Pietra" wrote: > >> How to insert letter "A" on each line (of a very long list of lines) > >> at position 22, i.e., one space after "LEU", leaving all other > >> characters at the same position as in the original example: > > >> ATOM ? ? ?1 ?N ? LEU ? ? 1 ? ? 146.615 ?40.494 103.776 ?1.00 73.04 ? ? ? 1SG ? 2 > > >> In all lines"ATOM" is constant as to both position and string, while > >> "LEU" is constant as to position only, i.e., "LEU" may be replaced by > >> three different uppercase letters. Therefore, the most direct > >> indication would be position 22. > > >> Should the script introduce blank lines, no problem. That I know how > >> to correct with a subsequent script. > > >> Thanks > >> chiendarret > > > If you want to leave the rest of the strings as-is (i.e. the letter A > > overwrites whatever on position 22), Peter's code need to be modified > > a little: > > line = line[:22] + " " + line[23:] > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Dr Francesco Pietra > Professor of Chemistry > Accademia Lucchese di Scienze, Lettere e Arti, founded in 1594 > Palazzo Ducale > 55100 Lucca (Italy) > e-mail chiendar... at gmail.com From bearophileHUGS at lycos.com Wed Jul 30 14:17:01 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 30 Jul 2008 11:17:01 -0700 (PDT) Subject: Reasoning behind 'self' parameter in classes? References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> Message-ID: <11adb25c-333f-4f1c-822f-0c770bb9418a@m44g2000hsc.googlegroups.com> Brett g Porter: > Fredrik Lundh has written a very clear explanation of this athttp://effbot.org/pyfaq/why-must-self-be-used-explicitly-in-method-de... Today lot of people know that Ruby exists, so such FAQ explanation must explain why Python doesn't use a shorter syntax like for example @foo to denote instance attributes (and maybe @@baz for the class attributes). Bye, bearophile From grumman at example.com Mon Jul 7 23:29:51 2008 From: grumman at example.com (Grumman) Date: Mon, 07 Jul 2008 23:29:51 -0400 Subject: How to make python scripts .py executable, not bring up editor In-Reply-To: References: Message-ID: korean_dave wrote: > From command Prompt, i type in a script, "tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? Start->My Computer->Properties->Advanced->Environment Variables in bottom pane "System Variables" add ";.py" to "PATHEXT" From dmitrey.kroshko at scipy.org Mon Jul 21 07:20:20 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Mon, 21 Jul 2008 04:20:20 -0700 (PDT) Subject: howto check is function capable of obtaining **kwargs? Message-ID: hi all, howto check is function capable of obtaining **kwargs? i.e. I have some funcs like def myfunc(a,b,c,...):... some like def myfunc(a,b,c,...,*args):... some like def myfunc(a,b,c,...,*args, **kwargs):... some like def myfunc(a,b,c,...,zz=zz0):... So I need to know is the given function capable of handling zz parameter, for example the call myfunc(a,b,c,...,zz=4,...) Thank you in advance, D. From usenetthrowaway at gmail.com Wed Jul 30 07:48:08 2008 From: usenetthrowaway at gmail.com (Gary) Date: Wed, 30 Jul 2008 12:48:08 +0100 Subject: Proxy server? References: <6f5rteF89muqU2@mid.uni-berlin.de> <6f6sk7Fa4tf5U1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote in message news:6f6sk7Fa4tf5U1 at mid.uni-berlin.de... > Gary schrieb: > > "Diez B. Roggisch" wrote in message > > news:6f5rteF89muqU2 at mid.uni-berlin.de... > You can't make any TCP/IP communication run through a proxy, unless it's > transparent. Thanks for all the info. I'm puzzled though that a such a transaction isn't possible by rewriting the headers. So client X connects to my PS, which passes on the data to the target but with the header changed to indicate the PS as the original source. The intended target responds to the PS, this is then resent to client X with the header modified so that the transaction appears transparent. So it's *effectively* transparent target>client but non-transparent client>target, if you see what I mean. Can you please explain why this wouldn't work? Thanks, Gary From python at barillari.org Tue Jul 8 17:56:45 2008 From: python at barillari.org (Joseph Barillari) Date: Tue, 08 Jul 2008 17:56:45 -0400 Subject: Impossible to change methods with special names of instances of new-style classes? Message-ID: <878wwcavky.fsf@bigbox.barillari.org> Hi python-list, I've just started using new-style classes and am a bit confused as to why I can't seem to alter methods with special names (__call__, etc.) of new-style class instances. In other words, I can do this: >>> class Z: ... pass ... >>> z = Z() >>> z.__call__ = lambda : 33 >>> z() 33 But apparently I can't do this: >>> class NZ(object): ... pass ... >>> nz = NZ() >>> nz.__call__ = lambda : 33 >>> nz() Traceback (most recent call last): File "", line 1, in TypeError: 'NZ' object is not callable I found this post from Bengt Richter three years ago which addressed a related problem: http://mail.python.org/pipermail/python-list/2005-July/332961.html >Apparently the issue, as stated implicitly or explicitly by most of >you, is that new-style class instances essentially defer their magic >methods to the class's static versions of same. This is good to know :) Actually, it's not just the "magic" methods. If you have an instance a of a newstyle class A, any attribute lookup a.attr will undergo the same search first to see if attr is a descriptor object, and if not, *then* to look in the instance attribute directory. But the descriptor search doesn't start in inst.__dict__, it goes through the chain of classes and base classes provided by type(inst).mro(), which starts in type(inst). And for our class A instance a, type(a) will be A, so the search for a.attr starts there. Same applies to a.__str__. This ensures that all instances of the same class will share the same methods. The way a method, which is just a class variable with a function as its value, gets to be a callable bound method, is the same as any attribute lookup looking for a descriptor with a __get__ method (which a function also has, for this purpose). If the descriptor doesn't have a __set__ method as well, then an instance attribute takes priority. If there is a __set__ method, and instance attribute can't shadow the attribute name, and the descriptor __get__ method takes precedence. Unshadowed, a method search looks something like cbm = ((base for base in type(inst).mro() if 'attr' in base.__dict__) .next().__dict__['attr'].__get__(inst, type(inst))) if this doesn't succeed and meet the __set__ vs shadowing logic, then you get the instance attribute per se. ...but if I understand correctly, this suggests that if the runtime can't find the attribute in the chain of classes and base classes, it will look in the instance dictionary. The behavior of NZ above suggests that it the runtime is _not_ doing that for __call__ as it would for a non-special name: >>> class NZ(object): ... pass ... >>> nz = NZ() >>> nz.f = lambda : 42 >>> nz.f() 42 My question is: did something about the way the special method names are implemented change for new-style classes? best, and thanks in advance, Joe From deets at nospam.web.de Thu Jul 31 09:59:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 15:59:56 +0200 Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> Message-ID: <6fdut5Fb0nvuU2@mid.uni-berlin.de> squishywaffle at gmail.com wrote: > Greetings, > > I'm trying to wrap a function in a C library as a compiled C Python > module. Everything is going great, but I've hit a snag. There's a > function in the form of this: > > First the typedef: > typedef void(*FPtr_DeviceMessageHandler) (const DeviceMessage, const > char*); > > Then the actual function prototype: > FPtr_DeviceMessageHandler > RegisterDeviceMessageHandler(FPtr_DeviceMessageHandler); > > Whenever this USB device I'm using generates a message, it's then sent > to that function whose reference you passed to > RegisterDeviceMessageHandler(). Here's an example: > > void testfunc() { > printf("test"); > } > ...on to main() > RegisterDeviceMessageHandler(&testfunc) > > So I've defined a similar function on my C module to do just this, > using the passed function reference to allow the device to send > messages to a Python function of the user's choice. I'm just not sure > how to do this, and the tutorials I've been digging through don't > offer any help. I've found some functions that look promising, but > can't figure out how to cast the function reference from Python into > something the C RegisterDevice... function can handle. Here's what > I've got: > > static PyObject * > Py1_RegisterDeviceMessageHandler(PyObject *self, PyObject *args) > { > PyObject *handle, *parsed; > > if(!PyArg_ParseTuple(args, "O", handle)) { > return NULL; > } > > parsed = PyMethod_Function(handle); > I1_RegisterDeviceMessageHandler(PyMethod_Function(handle)); > > Py_RETURN_TRUE; > } // end Py1_RegisterDeviceMessageHandler() > > This fails since PyMethod_Function returns a PyObject. Is there a way > to cast this to something generic? Casting to (void*) didn't seem to > work. > > Thanks in advance! May I suggest you move to ctypes for wrapping? It's easier, pure python and callbacks are already built-in. Diez From max at alcyone.com Wed Jul 30 03:55:43 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Jul 2008 00:55:43 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <0f0b03c9-794b-430b-88ab-18a68505109e@a21g2000prf.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> <6d906dd5-bf5a-44d5-a5a8-3875027f6b91@v26g2000prm.googlegroups.com> <0f0b03c9-794b-430b-88ab-18a68505109e@a21g2000prf.googlegroups.com> Message-ID: Russ P. wrote: > On Jul 29, 11:36 pm, Erik Max Francis wrote: >> Russ P. wrote: >>> Come to think of it, shouldn't the list type have an "isempty" method? >>> Or does it? >> Yes. It's written: >> >> if not aList: >> ... > > As you know, that is not quite exactly the same thing. An "isempty" > method would fail if aList were an integer, and such failure might be > desirable if someone mistakenly had aList pointing to an integer. If you're that concerned about what the type is, then you can do explicit typechecks. Those are discouraged precisely because of Python's dynamism. But knock yourself out. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The actor is not quite a human being -- but then, who is? -- George Sanders From geraint.williams at gmail.com Sun Jul 13 07:55:06 2008 From: geraint.williams at gmail.com (GHZ) Date: Sun, 13 Jul 2008 04:55:06 -0700 (PDT) Subject: Why is there no GUI-tools like this for Windows? References: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> Message-ID: There is http://www.codeplex.com/IronPythonStudio From dullrich at sprynet.com Tue Jul 8 11:53:13 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 08 Jul 2008 10:53:13 -0500 Subject: "in"consistency? References: <87vdzhwf1v.fsf@benfinney.id.au> Message-ID: In article , Mel wrote: > Ben Finney wrote: > > > "David C. Ullrich" writes: > > > >> >>> 'ab' in 'abc' > >> True > >> >>> [1,2] in [1,2,3] > >> False > > > > > > > >> Is there a reason for the inconsistency? > > > > Probably. The special behaviour of string types was changed in Python > > 2.3, according to that document. > > As it stands, you'd get > > [1,2] in [1,2,3] == False > > [1,2] in [1, [1,2], 3] == True > > > This could be a good thing. Oh, of course that's a good thing - changing "in" for lists to give True there would be awful. I was wondering why it _does_ work that way for strings. Maybe the answer is "because it can" - for strings the sort of possible problem you point out can't come up. > Mel. > > -- David C. Ullrich From castironpi at gmail.com Wed Jul 30 02:40:16 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 29 Jul 2008 23:40:16 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> Message-ID: <5be6b2bf-7bf3-42d7-9f31-5ccc886ec786@t54g2000hsg.googlegroups.com> I note that IronPython and Python's pickle.dumps do not return the same value. Perhaps this relates to the absence of interpreter loop. >>> p.dumps( { 'a': True, 'b': set( ) } ) IPy: '(dp0\nVb\np1\nc__builtin__\nset\np3\n((lp4\ntp5\nRp2\nsVa \np6\nI01\ns.' CPy: "(dp0\nS'a'\np1\nI01\nsS'b'\np2\nc__builtin__\nset \np3\n((lp4\ntp5\nRp6\ns." You make me think of a more elaborate example. for k in range( 100 ): i= j() g= h+ i e= f+ g c= d+ e a= b+ c Here, j creates a new class dynamically, and returns an instance of it. Addition is defined on it but the return type from it varies. If I read you correctly, IPy can leave hundreds of different addition stubs laying around at the end of the for-loop, each of which only gets executed once or twice, each of which was compiled for the exact combination of types it was called for. I might construe this to be a degenerate case, and the majority of times, you'll reexecute stubs enough to outweigh the length of time the compilation step takes. If you still do the bounds checking, it takes extra instructions (C doesn't), but operation switch-case BINARY_ADD, (PyInt_CheckExact(v) && PyInt_CheckExact(w)), and POP and TOP, are all handled by the selection of stubs from $addSite. I'm read from last April: >>> The most interesting cases to me are the 5 tests where CPython is more than 3x faster than IronPython and the other 5 tests where IronPython is more than 3x faster than CPython. CPython's strongest performance is in dictionaries with integer and string keys, list slicing, small tuples and code that actually throws and catches exceptions. IronPython's strongest performance is in calling builtin functions, if/then/else blocks, calling python functions, deep recursion, and try/except blocks that don't actually catch an exception. <<< http://lists.ironpython.com/pipermail/users-ironpython.com/2007-April/004773.html It's interesting that CPython can make those gains still by using a stack implementation. I'll observe that IronPython has the additional dependency of the full .NET runtime. (It was my point 7/18 about incorporating the GNU libs, that to compile to machine-native, as a JIT does, you need the instruction set of the machine.) Whereas, CPython can disregard them, having already been compiled for it. I think what I was looking for is that IronPython employs the .NET to compile to machine instructions, once it's known what the values of the variables are that are the operands. The trade-off is compilation time + type checks + stub look-up. What I want to know is, if __add__ performs an attribute look-up, is that optimized in any way, after the IP is already in compiled code? After all that, I don't feel so guilty about stepping on Tim's toes. On Jul 30, 12:12?am, Dino Viehland wrote: > IronPython doesn't have an interpreter loop and therefore has no POP / TOP / etc... ? Instead what IronPython has is a method call Int32Ops.Add which looks like: > > ? ? ? ? public static object Add(Int32 x, Int32 y) { > ? ? ? ? ? ? long result = (long) x + y; > ? ? ? ? ? ? if (Int32.MinValue <= result && result <= Int32.MaxValue) { > ? ? ? ? ? ? ? ? return Microsoft.Scripting.Runtime.RuntimeHelpers.Int32ToObject((Int32)(result)); > ? ? ? ? ? ? } > ? ? ? ? ? ? return BigIntegerOps.Add((BigInteger)x, (BigInteger)y); > ? ? ? ? } > > This is the implementation of int.__add__. ?Note that calling int.__add__ can actually return NotImplemented and that's handled by the method binder looking at the strong typing defined on Add's signature here - and then automatically generating the NotImplemented result when the arguments aren't ints. ?So that's why you don't see that here even though it's the full implementation of int.__add__. > > Ok, next if you define a function like: > > def adder(a, b): > ? ? ? ? return a + b > > this turns into a .NET method, which will get JITed, which in C# would look something like like: > > static object adder(object a, object b) { > ? ? return $addSite.Invoke(a, b) > > } > > where $addSite is a dynamically updated call site. > > $addSite knows that it's performing addition and knows how to do nothing other than update the call site the 1st time it's invoked. ?$addSite is local to the function so if you define another function doing addition it'll have its own site instance. > > So the 1st thing the call site does is a call back into the IronPython runtime which starts looking at a & b to figure out what to do. ?Python defines that as try __add__, maybe try __radd__, handle coercion, etc... ?So we go looking through finding the __add__ method - if that can return NotImplemented then we find the __radd__ method, etc... ?In this case we're just adding two integers and we know that the implementation of Add() won't return NotImplemented - so there's no need to call __radd__. ?We know we don't have to worry about NotImplemented because the Add method doesn't have the .NET attribute indicating it can return NotImplemented. > > At this point we need to do two things. ?We need to generate the test which is going to see if future arguments are applicable to what we just figured out and then we need to generate the code which is actually going to handle this. ?That gets combined together into the new call site delegate and it'll look something like: > > static void CallSiteStub(CallSite site, object a, object b) { > ? ? ? ? if (a != null && a.GetType() == typeof(int) && b != null && b.GetType() == typeof(int)) { > ? ? ? ? ? ? return IntOps.Add((int)a, (int)b); > ? ? ? ? } > ? ? ? ? return site.UpdateBindingAndInvoke(a, b); > > } > > That gets compiled down as a lightweight dynamic method which also gets JITed. ?The next time through the call site's Invoke body will be this method and things will go really fast if we have int's again. ?Also notice this is looking an awful lot like the inlined/fast-path(?) code dealing with int's that you quoted. ?If everything was awesome (currently it's not for a couple of reasons) the JIT would even inline the IntOps.Add call and it'd probably be near identical. ?And everything would be running native on the CPU. > > So that's how 2 + 2 works... ?Finally if it's a user type then we'd generate a more complicated test like (and getting more and more pseudo code to keep things simple): > > if (PythonOps.CheckTypeVersion(a, 42) && PythonOps.CheckTypeVersion(b, 42)) { > ? ? return $callSite.Invoke(__cachedAddSlot__.__get__(a), b); > > } > > Here $callSite is another stub which will handle doing optimal dispatch to whatever __add__.__get__ will return. ?It could be a Python type, it could be a user defined function, it could be the Python built-in sum function, etc... ?so that's the reason for the extra dynamic dispatch. > > So in summary: everything is compiled to IL. ?At runtime we have lots of stubs all over the place which do the work to figure out the dynamic operation and then cache the result of that calculation. > > Also what I've just described is how IronPython 2.0 works. ?IronPython 1.0 is basically the same but mostly w/o the stubs and where we use stub methods they're much less sophisticated. > > Also, IronPython is open source -www.codeplex.com/IronPython > > -----Original Message----- abriged: > This is from 7/22/08, same author: > > I wouldn't say "can't". ?The current CPython VM does not compile > > code. ?It COULD. ?The C#/.NET VM does. > > Three big claims here that I breezed right over and didn't believe. > > > It COULD. > > I'm evidently assuming that if it could, it would. > > > The current CPython VM does not compile code. > > Therefore it couldn't, or the assumption is wrong. ?Tim says it is. > And the glaring one-- > > WHY NOT? ?Why doesn't CPython do it? > > I am imagining that every Python implementation has something like > it. ?If IronPython does not, in particular, not have the 'POP(); > TOP();' sequence, then it isn't running on a stack machine. ?Is the > IronPython code open source, and can someone link to it? ?I'm not > wading through it from scratch. ?What does it have instead? ?Does > dynamic typing still work? From george.sakkis at gmail.com Thu Jul 3 22:09:54 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 3 Jul 2008 19:09:54 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> <7db52b03-7a8a-40c4-b3cb-f6dccd273b90@59g2000hsb.googlegroups.com> <45ce2acc-e4b5-4762-8daa-b67a78b02411@w7g2000hsa.googlegroups.com> Message-ID: On Jul 3, 7:51 pm, Mensanator wrote: > On Jul 3, 6:24 pm, George Sakkis wrote: > > > Taking into account 2.6 too (we're not talking about only 3.0 here), > > probably not much less than those who even know what is gmpy, let > > alone dismiss a beta Python release because their obscure pet module > > is not available yet. > > That was just an example. When you consider ALL the pet > modules like PIL, Numpy, Win32, etc., that's a lot, isn't it. A few points: - The OP acknowledged he's a newbie, and as a newbie he'll probably spend some time getting used to the language and the standard library before jumping to the dozens 3rd party packages. - I am sure many Python users are productive without ever touching an external package; that is after all the point of "batteries included". - Even if they do have external dependencies, chances are that they are pure Python modules, which typically work without modification on new 2.x versions. > I was just trying to be helpful (I admit I often sound > negative when I'm not trying to be). Well, something like "Until then, such solutions are worthless, i.e., of no value" is too strong, subjective and biased to be really helpful. George From fredrik at pythonware.com Mon Jul 21 16:55:14 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 22:55:14 +0200 Subject: Seriously, though, about LLVM In-Reply-To: References: Message-ID: mk wrote: >>> This project has gained some publicity. There's IronPython, right, so >>> has anybody thought about implementing Python using LLVM as backend, >>> as it seems not out of question at all? >> >> you mean like: >> >> http://llvm.org/ProjectsWithLLVM/#pypy >> >> ? > > No, I don't mean "Python written in Python", with whatever backend. so anyone attempting to write a Python implementation for the LLVM aren't allowed to use Python for the front-end? why not? From bj_666 at gmx.net Fri Jul 18 03:01:12 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Jul 2008 07:01:12 GMT Subject: None in comparison References: <549f01d2-1d15-4b0d-9440-a9402c0449ff@b2g2000prf.googlegroups.com> Message-ID: <6eatdoF67cpfU1@mid.uni-berlin.de> On Thu, 17 Jul 2008 23:52:13 -0700, r.grimm wrote: > Hello, > I'm a little confused about None in comparison. > >>>> id ( None ) > 3086100672L >>>> id ( 1 ) > 134541104 >>>> None < 1 > True >>>> > > I thought, the id of the object is the last comparison criterion. Obviously that expectation is false. The result of a comparison between different types, with no `__cmp__()` method that says otherwise, is a arbitrarily but consistent ordering by type. The language doesn't even guarantee that it must be consistent in different runs of the same program in the same interpreter, just within one run. So if you plan to rely on such implementation details, your program is broken. Ciao, Marc 'BlackJack' Rintsch From cyril.bazin at info.unicaen.fr Thu Jul 17 07:48:21 2008 From: cyril.bazin at info.unicaen.fr (Cyril Bazin) Date: Thu, 17 Jul 2008 13:48:21 +0200 Subject: Problem with MySQLdb and mod_python In-Reply-To: References: Message-ID: Thanks for your reply The apache log contains lines like : [Tue Jul 15 23:31:01 2008] [notice] mod_python (pid=11836, interpreter='www.toto.fr'): Importing module '/usr/local/apache2/htdocs/intranet/courrier/test.py' [Tue Jul 15 23:31:02 2008] [notice] child pid 11836 exit signal Segmentation fault (11) [Tue Jul 15 23:31:19 2008] [notice] mod_python (pid=11764, interpreter='www.toto.fr'): Importing module '/usr/local/apache2/htdocs/intranet/courrier/test.py' [Tue Jul 15 23:31:19 2008] [notice] child pid 11764 exit signal Segmentation fault (11) I think the problem comes from the MySQLdb module. If I can't find another solution, I think I will downgrade the MySQLdb version to 1.2.1 Cyril On Thu, Jul 17, 2008 at 7:27 AM, Lawrence D'Oliveiro wrote: > In message , Cyril Bazin > wrote: > >> But it seems, after many tests, that the script stops at the >> instruction : "c.execute(requete)" > > What's the error message? This should be in Apache's error_log file. > -- > http://mail.python.org/mailman/listinfo/python-list > From alexnbryan at gmail.com Wed Jul 16 14:37:35 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 11:37:35 -0700 (PDT) Subject: py2exe issues with pictures and icons Message-ID: <18493908.post@talk.nabble.com> Hello I am sure most of you are familiar with py2exe. I am having a bit of a problem. See the program has a few pictures involved and the .ico it uses for the windows. However, the pictures are stored in the same directory as the source, something like: C:\Docs and settings\me\My docs\python\program. When I run the program for the interpreter, just as a .py, everything works just as it should. However, when I compile the main source as an .exe, and say let a friend try the program. It fails because it is missing the .ico. The catch, is I don't want to have it have to installed, at least at this point, I want it to be able to just run. So how can I make it just run from any computer with the files not being in the immediate directory. If that is not possible, how can I put them in the immediate directory and still make it work. Because that directory may change a lot so the path will change. Just a few questions. I hope someone out there can help me out! -- View this message in context: http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp18493908p18493908.html Sent from the Python - python-list mailing list archive at Nabble.com. From musiccomposition at gmail.com Tue Jul 22 23:04:04 2008 From: musiccomposition at gmail.com (Benjamin) Date: Tue, 22 Jul 2008 20:04:04 -0700 (PDT) Subject: sys.stderr.write returns string length in Python 3 References: Message-ID: <43ab2eb4-31ec-4574-ab54-4467fa89d187@27g2000hsf.googlegroups.com> Alan G Isaac wrote: > Is this new behavior intentional? :: Yes, it's in the PEP http://www.python.org/dev/peps/pep-3116/. > > >>> sys.stderr.write("thisisatest\n") > thisisatest > 12 > > Here is the reason for it: > > >>> help(sys.stderr.write) > Help on method write in module io: > write(self, s: str) method of io.TextIOWrapper instance > > Thank you, > Alan Isaac From yanowitzmjy at yahoo.com Tue Jul 15 17:26:09 2008 From: yanowitzmjy at yahoo.com (Michael J. Yanowitz) Date: Tue, 15 Jul 2008 14:26:09 -0700 (PDT) Subject: Need Python Programmer (preferentially in Los Angeles) In-Reply-To: Message-ID: <594727.17052.qm@web58712.mail.re1.yahoo.com> Hello: I think I can do it but would like more details. I have been doing GUI work for years. I have been doin Python only for the last 2 and 1/2 years. The GUI work I have done there has been with TkInter and wxPython. Thanks: Michael Yanowitz --- On Tue, 7/15/08, robnhood00 wrote: > From: robnhood00 > Subject: Need Python Programmer (preferentially in Los Angeles) > To: python-list at python.org > Date: Tuesday, July 15, 2008, 4:54 PM > I need a python programmer that can integrate graphics into > an > existing python application. The application is a basic > application > and the job should be pretty easy for an experienced Python > programmer. Los Angeles programmer is preferred but this > can > obviously be done from anywhere. > Please contact me at robnhood007 at yahoo.com is you can help > me. > Thank you. > -- > http://mail.python.org/mailman/listinfo/python-list From bj_666 at gmx.net Wed Jul 30 14:02:20 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Jul 2008 18:02:20 GMT Subject: Possible to have multiple loop variables? References: <5ff22b51-88e9-405c-aeb9-7b0abe9cf935@r66g2000hsg.googlegroups.com> Message-ID: <6fbolbFaidktU1@mid.uni-berlin.de> On Wed, 30 Jul 2008 10:49:58 -0700, laredotornado wrote: > I don't know why I thought this would work, but I would like to have 3 > variables in my for loop per iteration. Those familiar will know that > this > > ms1 = {'managed1':7019:8020,'managed2':7020:8021} for m, lp, ssl_lp in > ms1.items(): > managedServer = create(m,'Server') > print 'creating managed server '+m > managedServer.setListenAddress('147.191.71.70') > managedServer.setListenPort(lp) > managedServer.setEnabled(0) > cd('SSL/cgServer') > managedServer.setEnabled(1) > managedServer.setListenPort(ssl_lp) > managedServer.setCluster(clus1) > > causes > > File "/export/third-party/etsbea/home/etsbea/tests/wlst/ > createcluster.py", line 9 > ms1 = {'managed1':7019:8020,'managed2':7020:8021} > ^ > SyntaxError: invalid syntax > > > How would I set up the ms1 array such that I can use three items per > object? `ms1` is a dictionary and not an array. You could use a tuple as value: In [5]: ms1 = {'managed1': (7019, 8020), 'managed2': (7020, 8021)} In [6]: for a, (b, c) in ms1.iteritems(): ...: print a, b, c ...: managed1 7019 8020 managed2 7020 8021 Ciao, Marc 'BlackJack' Rintsch From iainking at gmail.com Fri Jul 18 09:34:44 2008 From: iainking at gmail.com (Iain King) Date: Fri, 18 Jul 2008 06:34:44 -0700 (PDT) Subject: Best Python packages? References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> <17861f55-8ad1-4703-ad22-838675f2afc4@w1g2000prk.googlegroups.com> Message-ID: On Jul 18, 11:23?am, Ben Sizer wrote: > On Jul 16, 3:31?pm, Fredrik Lundh wrote: > > > Ben Sizer wrote: > > > make my development a lot easier. > > > Knowing what kind of development you do might help, of course. ?Some > > libraries are excellent in some contexts and suck badly in others... > > Sure. Mostly I'm just interested in what's out there though. In C++ > you have Boost which everybody knows are a source of high quality > libraries, covering a fairly wide set of applications. Obviously > that's more low-level and less application specific, and the Python > standard libs do pretty much everything that is in Boost, but it's > that sort of peer-reviewed and widely-applicable list that I'd like to > see. > > I (attempt to) use TurboGears for web development and that depends on > a whole bunch of libraries - SQLObject, PyProtocols, RuleDispatch, > SimpleJson, FormEncode, etc - and I would never have heard of these if > TurboGears' exposure of its internals wasn't so common. Some of these > are web-specific but some are not. And I'd never know to look for them > specificially, because in many cases it wouldn't occur to me that they > exist. (eg. Object-Relational Mappers like SQLObject may be obvious if > you come from certain areas of IT, but I'd never heard of them before > I started with TurboGears.) > > For what it's worth, my main areas of interest are gaming, multimedia, > and web development. But I just like to hear about anything that > people might use which makes their life a lot easier and which perhaps > is not application specific - like ORMs or something similar. > > > Looking at things that larger projects and distributions use can also be > > a good idea. ?For example, if you're doing scientific stuff, go directly > > to enthought.com. ?If you're doing web stuff, look at the libraries big > > Django applications use. ?Etc. > > Sadly, I know just as little about what major applications are out > there as I do about what libraries are out there! > > -- > Ben Sizer Well, if you're looking for a list of excellent 3rd party Python libraries, then I can give you the ones I like and use a lot: wxPython : powerful GUI library which generates native look & feel PIL : Imaging Library - if you need to manipulate bitmaps pyGame : SDL for python BeautifulSoup : for real-world (i.e. not-at-all-recommendation- compliant) HTML processing Iain From __peter__ at web.de Tue Jul 8 15:09:37 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Jul 2008 21:09:37 +0200 Subject: Relative Package Import References: Message-ID: Robert Hancock wrote: > mypackage/ > __init__.py > push/ > __init__.py > dest.py > feed/ > __init__py > subject.py > > In subject.py I have > from ..push import dest > > But i receive the error: > Caught exception importing module subject: > File "/usr/local/python/lib/python2.5/site-packages/pychecker/ > checker.py", line 621, in setupMainCode() > module = imp.load_module(self.moduleName, file, filename, smt) > File "subject.py", line 1, in () > from ..feed import dest > ValueError: Attempted relative import in non-package > > What am I missing? When you run subject as a file pychecker mypackage/feed/subject.py subject.py is regarded as a standalone script, not as part of a package. Try pychecker mypackage.feed.subject instead to invoke the module via the standard import mechanism. Peter From thisisspam0 at gmail.com Fri Jul 4 20:18:49 2008 From: thisisspam0 at gmail.com (thisisspam0 at gmail.com) Date: Fri, 4 Jul 2008 17:18:49 -0700 (PDT) Subject: http://vivalacuba.blogspot.com/ Message-ID: <70a28232-9657-4525-99e9-adc5f2befef1@e39g2000hsf.googlegroups.com> http://vivalacuba.blogspot.com/ From lie.1296 at gmail.com Tue Jul 22 09:19:05 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 22 Jul 2008 20:19:05 +0700 Subject: Change PC to Win or Windows In-Reply-To: <20080721225027.GF8793@dragontoe.org> References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> <82873ccd-9667-4dfa-9ec4-a9ac7c672aa7@w1g2000prk.googlegroups.com> <0f3272c1-b1a7-4aef-9e4a-0f03af823a2d@z11g2000prl.googlegroups.com> <20080721225027.GF8793@dragontoe.org> Message-ID: <1216732745.6470.46.camel@lieryan-laptop> On Mon, 2008-07-21 at 18:50 -0400, Derek Martin wrote: > On Mon, Jul 21, 2008 at 02:47:31PM -0700, Lie wrote: > > Common usage isn't always correct. > > Actually it is, inherently... When usage becomes common, the language > becomes redefined, and its correctness is therefore true by identity > (to borrow a mathematical term). The scholars complain for a while, > but eventually capitulate, and re-write the dictionary. Language > bends to its use by the people, not the other way around. Your > assumption is the opposite, and therefore all of your argument is > false. But until the dictionary is rewritten, it is incorrect usage. Since dictionary isn't rewritten unless (nearly) the whole world agrees with it, not all parts of the world used the term PC exclusively for Windows-based computer, in this part of the world specifically, PC is used for any desktop computers. Therefore your argument is false (at least: yet). > > For example, a physicist would not use weight when he meant mass. > > much, but in technical environment doing so would embarrass him. In > > this analogy, I consider download page for a software source code to > > be a technical area. > > Your analogy is still broken. The term "PC" has been used BY > TECHNCIAL PEOPLE, IN A TECHNICAL CONTEXT, to mean Microsoft on Intel, > FOR DECADES. ?Yes, and they are wrong on using it. So do some physicist, before the clear distinction is drawn explicitly between mass and weight. FOR DECADES, people used the term PC for all sorts of things, in the most technically correct usage, only IBM-branded home computers could be called a PC, since PC is ?officially their advertising term. However, since Personal Computer is a brand-neutral term (unlike iMac, Lifebook, etc), it have the tendency to be extended (by the people) to include other personally owned computers as well. The technically correct extension would be "PC is computers that is designed and marketed for personal possession and use", which means it doesn't matter what OS it is, what hardware it uses. A debate (or a long observation to the people) might be needed to determine whether that definition extension is acceptable, but the definition extension you mentioned: "PC is Windows-based computer" needs no debate, it is completely wrong and is a baseless misunderstanding. > + Authors of technical books, manuals, and other forms of > documentation have refered to them as PCs... for decades. > > + Educators in CS and EE at major universities have refer to them as > PCs, since at least as early as 1988 (when I started college). I'm sure they were mentioning IBM-PC and its clones, not mentioning Windows itself. (Well, it's true that IBM-PC and its clones is mostly Windows-based, but PC is a term for the combination of hardware and software that makes a personal computer, in the current incorrect usage, PC is Windows, a software.) > + Industry news publications such as Computer World have refered to > them as PCs, for decades. > > + There are even whole magazines dedicated to them! (PC Magazine, PC > Shopper, PC World, PC Gamer, etc.) They are dedicated to Microsoft > on Intel, and have existed (at least in some cases) long before > Apple started talking about PCs in their ads. Excuse me, those magazines (at least in this part of the world) also contain non-Microsoft articles. The fact that Windows articles is the dominant topic, is solely because most of their subscribers are Windows user, it is not as profitable to write about Linux and Mac and Unix. > All of this has been going on, essentially since there has been such > a thing as the IBM PC. I'm sorry, but you sir, are quite simply, > plainly, and completely, wrong. Compounded with misunderstanding, you sir, are very well ignorant. > With a catastrophic amount of > written documentation, written by technical people in the computer > industry over the last 20+ years, to prove it. > > > > > Apple popularizes the term by explicit marketing, > > > > > > And here is the last point you are missing: Apple does no such > > > thing. > > > > They did, by using the term PC to refer to other computers. > > APPLE CAN NOT POPULARIZE A TERM WHICH IS ALREADY POPULAR. Sure it catches the wave that has been going on for some time. And use it to their own advantage. I've mentioned that Apple could not be blamed so much for this, since with or without them, the term would become popular, although its meaning mightn't have been as twisted as nowadays. > > This kind of advertising Apple (the computer company) used is > > misleading, since it implied that their PC is not a PC. > > They haven't implied anything; they're stating it outright! Apple > sells personal computers, but they do not sell PCs. Apple's personal > computer is NOT a PC, and never was, and never will be. It's an > Apple. Apple's personal computer is NOT a PC? Aren't you contradicting yourself? Just like what Apple, you have just said: "I'm Apple, I'm a personal computer, but I'm not a personal computer." Completely nonsense. Last, probably my strongest argument: "If the folder has been called WinBuild/WindowsBuild, there is no need for arguments. PC as Windows is an arguable usage, Windows as Windows is not arguable." |||| |||| ____ / \ | 2c | \____/ _________ From pluskid at gmail.com Thu Jul 24 02:39:13 2008 From: pluskid at gmail.com (pluskid) Date: Wed, 23 Jul 2008 23:39:13 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: On Jul 24, 1:41?pm, Jordan wrote: > Hi everyone, > > I'm a big Python fan who used to be involved semi regularly in > comp.lang.python (lots of lurking, occasional posting) but kind of > trailed off a bit. I just wrote a frustration inspired rant on my > blog, and I thought it was relevant enough as a wider issue to the > Python community to post here for your discussion and consideration. > [...snip...] +1 for most of your opinion. I was also bitten by the __eq__/__ne__ problem this morning. :) From nagle at animats.com Thu Jul 31 11:44:19 2008 From: nagle at animats.com (John Nagle) Date: Thu, 31 Jul 2008 08:44:19 -0700 Subject: Swap memory in Python ? - three questions In-Reply-To: References: Message-ID: <4891d957$0$17213$742ec2ed@news.sonic.net> Robert LaMarca wrote: > Hi, > > I am using numpy and wish to create very large arrays. My system is AMD 64 > x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a 15 GB swap > drive. Does a full 64-bit version of CPython, one where all pointers and sizes are 64 bits, even exist? John Nagle From steve at REMOVE-THIS-cybersource.com.au Thu Jul 31 18:58:25 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Jul 2008 22:58:25 GMT Subject: How smart is the Python interpreter? References: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> Message-ID: <00a23efb$0$20313$c3e8da3@news.astraweb.com> On Thu, 31 Jul 2008 04:09:57 -0700, ssecorp wrote: > def str_sort(string): > s = "" > for a in sorted(string): > s+=a > return s > > > if i instead do: > > def str_sort(string): > s = "" > so = sorted(string) > for a in so: > s+=a > return s > > > will that be faster Oh dear. Premature optimization, the root of all (programming) evil. You can test which is faster by using the timeit module. In the interactive interpreter, define the two functions above with different names, and a string to supply as argument. Then call: from timeit import Timer t1 = Timer('str_sort1(s)', 'from __main__ import str_sort1, s') t2 = Timer('str_sort2(s)', 'from __main__ import str_sort2, s') t1.repeat(number=1000) t2.repeat(number=1000) I'll be hugely surprised if there was any meaningful difference. > or the interpreter can figure out that it only has > to do sorted(string) once? or that kind of cleverness is usually > reserved for compilers and not interpreters? Python uses a compiler. It doesn't do a lot of clever optimization, but it does some. In this case, no, it doesn't optimize your function, so technically the first may be a tiny bit faster. But, frankly, your function is so painfully inefficient, doing a lot of useless work, that you probably won't notice any real difference. The correct way to do what you have done above is ''.join(sorted(s)). Anything else is much slower. >>> def sort_str(s): ... ss = "" ... for c in sorted(s): ... ss += c ... return ss ... >>> s = "abcdefghijklmnopqrstuvwxyz"*100 >>> from timeit import Timer >>> t1 = Timer('"".join(sorted(s))', 'from __main__ import s') >>> t2 = Timer('sort_str(s)', 'from __main__ import sort_str, s') >>> t1.repeat(number=1000) [1.6792540550231934, 1.6882510185241699, 1.660383939743042] >>> t2.repeat(number=1000) [2.5500221252441406, 2.4761130809783936, 2.5888760089874268] -- Steven From circularfunc at gmail.com Mon Jul 21 23:06:44 2008 From: circularfunc at gmail.com (ssecorp) Date: Mon, 21 Jul 2008 20:06:44 -0700 (PDT) Subject: tail-rec decorator, well still blows the stack... References: Message-ID: I my function not proper tail-recursion? because this doesn't blow the stack: #!/usr/bin/env python2.4 # This program shows off a python decorator( # which implements tail call optimization. It # does this by throwing an exception if it is # it's own grandparent, and catching such # exceptions to recall the stack. import sys class TailRecurseException: def __init__(self, args, kwargs): self.args = args self.kwargs = kwargs def tail_call_optimized(g): """ This function decorates a function with tail call optimization. It does this by throwing an exception if it is it's own grandparent, and catching such exceptions to fake the tail call optimization. This function fails if the decorated function recurses in a non-tail context. """ def func(*args, **kwargs): f = sys._getframe() if f.f_back and f.f_back.f_back \ and f.f_back.f_back.f_code == f.f_code: raise TailRecurseException(args, kwargs) else: while 1: try: return g(*args, **kwargs) except TailRecurseException, e: args = e.args kwargs = e.kwargs func.__doc__ = g.__doc__ return func @tail_call_optimized def factorial(n, acc=1): "calculate a factorial" if n == 0: return acc return factorial(n-1, n*acc) print factorial(10000) # prints a big, big number, # but doesn't hit the recursion limit. @tail_call_optimized def fib(i, current = 0, next = 1): if i == 0: return current else: return fib(i - 1, next, current + next) print fib(10000) # also prints a big number, # but doesn't hit the recursion limit. From iainking at gmail.com Mon Jul 7 05:56:01 2008 From: iainking at gmail.com (Iain King) Date: Mon, 7 Jul 2008 02:56:01 -0700 (PDT) Subject: How to bypass Windows 'cooking' the I/O? (One more time, please) II References: Message-ID: On Jul 7, 10:18?am, Dennis Lee Bieber wrote: > On Mon, 07 Jul 2008 01:03:10 -0700, norseman > declaimed the following in comp.lang.python: > > > > > ?> Normal file I/O sequence: > > > ?> fp = open(target, 'wb') > > > ?> fp.seek(-1, 2) > > > ?> fp.write(record) > > > ? ?Except it doesn't do that in Windows. See below. > > ? ? ? ? I wouldn't expect that sequence to work on any system... The "w" > implies "create new file, or truncate existing file to 0-bytes, then > write data to it" -- with no seeking permitted. You must include the "+" > to do seeking, and if you want to retain the existing file contents you > probably need to open with "a+" ("a" for append). > > ? ? ? ? The rest of your situation I won't touch. Other than to wonder why > the situation hasn't hit any of the various database servers which must > be operating in binary mode, and perform lots of seeking... Surely > somewhere out someone else must have encountered a seek crossing an > apparent mark (which isn't a normal Windows sequence anyway -- > since Windows uses for EOL, I'd have expected to see a problem > if backing over a ) > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? ?wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ lol @ op not finding the answer to his question in the archives, then being answered again by someone who doesn't let his answer go in the archive. How useful. From arnimavidyarthy at gmail.com Fri Jul 18 06:33:50 2008 From: arnimavidyarthy at gmail.com (arnimavidyarthy at gmail.com) Date: Fri, 18 Jul 2008 03:33:50 -0700 (PDT) Subject: trying to match a string Message-ID: Hi, Hi, I am taking a string as an input from the user and it should only contain the chars:L , M or R I tried the folllowing in kodos but they are still not perfect: [^A-K,^N-Q,^S-Z,^0-9] [L][M][R] [LRM]?L?[LRM]? etc but they do not exactly meet what I need. For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. regards, SZ The string may or may not have all the three chars. From CracKPod at googlemail.com Mon Jul 14 17:37:08 2008 From: CracKPod at googlemail.com (CracKPod) Date: Mon, 14 Jul 2008 14:37:08 -0700 (PDT) Subject: Python Tiddlywiki class Message-ID: Hello, I wrote a Python class to interact with the TiddlyWiki. In case you are interested you can find it on my blog: http://crackpod.bplaced.net/ CracKPod From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 15:18:36 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 21:18:36 +0200 Subject: New to Python, familiar with Perl - Seeking info sources In-Reply-To: <18c8fc73-8ff9-4640-a020-de0be4b76ca4@z72g2000hsb.googlegroups.com> References: <18c8fc73-8ff9-4640-a020-de0be4b76ca4@z72g2000hsb.googlegroups.com> Message-ID: <4888d583$0$26943$426a74cc@news.free.fr> Brett Ritter a ?crit : > After many years happily coding Perl, I'm looking to expand my > horizons. [no flames please, I'm pretty aware of Perl's strengths and > weaknesses and I'm just here to learn more, not to enter religious > debates]. > > I've gone through some of the online tutorials and I'll be browsing > the reference before starting the "code a lot" phase. > > My question is: What are the best sources to learn best practices or > get the answers to questions? Are there any good sources to tell me > what Perl habits are good/bad in the Python paradigm? What about > common packages that will change my life? (I do a lot of web work, > but also a lot of DB reporting) wrt/ "best practices" and writing pythonic code, the best thing to do is probably to lurk here and post code snippets asking for code reviews (we just *love* that !-) Others already pointed you to useful readings like diveintopython. I'd like to add Fredrik Lundh (aka the effbot)'s excellent website to the list: http://effbot.org/ wrt/ packages, first take time to read the stdlib's package index - I've a couple time Reinvented The Square Wheel(tm) when a well-rounded one was just an import away. You'll also find useful resources on pypi (the Python's Package Index). > I'm also working as a Java developer > primarily, so I'm glad to see that Jython has been resurrected, but > I'm focusing on vanilla Python for the moment. > > As examples: PerlMonks has been my info source. The Perl Best > Practices and Higher Order Perl books have been my tutors into better > coding practices. This newsgroup, diveintopython, effbot.org... > CPAN has my life easy, Not quite close to CPAN, but the closest we actually have IMHO: pypi (for the package index) and easy_install. > giving me access to the DBI, > Class::DBI (and its successors), low-level : Python db-api hi-level : SQLAlchemy > HTML::FillInForm, Don't know what this one do... > Data::FormValidator, FormEncode > CGI::Application, cgi and wsgi... > and Text::CSV::Simple modules You probably want the csv package (in the stdlib). You may also want to have a look at templating engines like Mako or Genshi. > that are staples of my coding. The (occasionally complete) Perl > Advent calendars have proven to be a good source to learn about > helpful modules that I might not otherwise stumble across. python-announces ? > (I've encountered Django, but I'm getting my fill of "frameworks" from > Java for the moment, so I'm looking for lightweight pieces at the > moment) While not exactly lighweight by Python's standards, Django is certainly way lighter than the usual Java web framework. But Python is known to have more web frameworks than keywords, so you may find something lightweight enough for your taste - or of course write your own !-) From bob.martin at excite.com Thu Jul 31 04:46:52 2008 From: bob.martin at excite.com (Bob Martin) Date: Thu, 31 Jul 2008 08:46:52 GMT Subject: interpreter vs. compiled References: <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <4rl294duo83eujnq6tjbk215mavpl87o9r@4ax.com> Message-ID: <0_ekk.35361$E41.10772@text.news.virginmedia.com> in 76135 20080731 090911 Dennis Lee Bieber wrote: >On Thu, 31 Jul 2008 06:17:59 GMT, Tim Roberts declaimed >the following in comp.lang.python: > > >> And again, I never said that it did. CPython is an interpreter. the >> user's code is never translated into machine language. >> >Using that definition, the UCSD P-code Pascal and Java are also not >"compilers" -- all three create files containing instructions for a >non-hardware virtual machine. > >The only difference between Python, UCSD Pascal, and Java is that >Python foregoes the explicit "compiler" pass. > >BASIC (classical microcomputer implementations -- like the one M$ >supplied for TRS-80s) is an interpreter -- the pre-scan of the source >merely translated BASIC keywords into a byte index, not into opcodes for >any virtual machine. You are confusing languages with implementations, as I pointed out earlier. Java is a language. I have used at least 2 Java compilers, ie they compiled Java source to native machine language. From __peter__ at web.de Wed Jul 2 04:36:03 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Jul 2008 10:36:03 +0200 Subject: Problem with a for loop and a list References: Message-ID: Alexnb wrote: > > I am not sure what is going on here. Here is the code that is being run: > > def getWords(self): > self.n=0 The value of self.n only makes sense within the method, so you better use the local variable n instead of the instance attribute self.n > for entry in self.listBuffer: > self.wordList[self.n] = entry.get() > self.n=self.n+1 > > print self.wordList > > This is the "listBuffer" that you see: > > self.listBuffer=[self.e1, self.e2, self.e3, self.e4, > self.e5, self.e6, self.e7, self.e8, > self.e9, self.e10, self.e11, > self.e12, self.e13, self.e14] > > (side note, those are all tkinter entry widgets, and the get() function > gets the text) > > this is the error the interpreter is giving me when I run it: > > self.getWords() > File "C:/Documents and Settings/Alex/My > Documents/PYTHON/DictionaryApp/The > GUI.py", line 153, in getWords > self.wordList[self.n] = entry.get() > IndexError: list assignment index out of range > > I have no idea what "list assignment index out of range means?!?! As Albert explained this means that wordList is shorter than listBuffer. The most flexible remedy is to have wordList grow dynamically: def getWords(self): wordList = [] for entry in self.listBuffer: wordList.append(entry.get()) print wordList If for some reason you want to remember the values in wordList add self.wordList = wordList to the method (this is the same consideration as for self.n versus n). Peter From mimi.vx at gmail.com Thu Jul 3 07:00:19 2008 From: mimi.vx at gmail.com (mimi.vx) Date: Thu, 3 Jul 2008 04:00:19 -0700 (PDT) Subject: multithreading in python ??? References: <674A912AA405814397CED58601AC8E251554964241@BLRKECMBX05.ad.infosys.com> Message-ID: <9e0033c8-9292-486a-9c82-bb95f7026b23@k30g2000hse.googlegroups.com> On Jul 3, 12:40?pm, Laszlo Nagy wrote: > Abhishek Asthana wrote: > > > Hi all , > > > I ?have large set of data computation and I want to break it into > > small batches and assign it to different threads .I am implementing it > > in python only. Kindly help what all libraries should I refer to > > implement the multithreading in python. > > You should not do this. Python can handle multiple threads but they > always use the same processor. (at least in CPython.) In order to take > advantage of multiple processors, use different processes. > > ? L or use parallelpython module, very good in multi processor| multimachine prog. in python From grante at visi.com Tue Jul 15 14:28:51 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 15 Jul 2008 13:28:51 -0500 Subject: Testing for Internet Connection References: <18460572.post@talk.nabble.com> <1216113021.24038.0@proxy02.news.clara.net> Message-ID: On 2008-07-15, Alexnb wrote: > What exactly do you think will work? I am not sure what you > think I should do? If I use urlopen("http://www.google.com") > and I am not connected, I am not going to get an exception, > the program will fail. Bullshit. You get an exception. Here's my program: import urllib2 try: con = urllib2.urlopen("http://www.google.com/") data = con.read() print data except: print "failed" If I run it with no internet connection, I get this: $ python testit.py failed If I bring up the internet connection, then I get a bunch of HTML. -- Grant Edwards grante Yow! I'm ZIPPY the PINHEAD at and I'm totally committed visi.com to the festive mode. From fredrik at pythonware.com Thu Jul 24 16:05:00 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 22:05:00 +0200 Subject: need help with introducing more traffic In-Reply-To: <6es0m9F8mehmU1@mid.uni-berlin.de> References: <632875.28836.qm@web51808.mail.re2.yahoo.com> <6es0m9F8mehmU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> umm. are you saying that you run ruby-lang.org and want to write a >> stress tester in Python just for the fun of it, or are we missing >> something here... > > This: > > http://www.pylot.org/ > > Seems as if he *is* using various languages for fun... "load testing" other people's sites are known as something else, of course. From amnorvend at gmail.com Fri Jul 18 15:26:35 2008 From: amnorvend at gmail.com (Jason Baker) Date: Fri, 18 Jul 2008 12:26:35 -0700 (PDT) Subject: __del__ methods References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> <6ec859F67cpfU5@mid.uni-berlin.de> Message-ID: <17b5febd-602d-4d7e-9449-6cabf4d95e41@27g2000hsf.googlegroups.com> On Jul 18, 2:10?pm, Marc 'BlackJack' Rintsch wrote: > On Fri, 18 Jul 2008 11:31:20 -0700, Jason Baker wrote: > > I have a class that I need to do some finalization on when it dies. ?I > > know I can use the __del__ method, but I seem to recall that it > > impedes garbage collection. ?Is this the case? > > `__del__()` is not a deterministic destructor. ?So forget about reliable > automatic clean up. ?Do it yourself with an explicit call to a `close()` > method or something like that. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch I don't necessarily need deterministic cleanup. And I plan on doing something like a close() method as well. But I'd just like to make sure nothing slips between the cracks. :) From kkwweett at hotmail.fr Tue Jul 1 11:54:05 2008 From: kkwweett at hotmail.fr (kkwweett) Date: Tue, 01 Jul 2008 17:54:05 +0200 Subject: wrong md5 checksum In-Reply-To: <486a16ef$0$885$ba4acef3@news.orange.fr> References: <486a16ef$0$885$ba4acef3@news.orange.fr> Message-ID: <486a5316$0$864$ba4acef3@news.orange.fr> kkwweett a ?crit : > Hi, > > the download page (http://www.python.org/download/releases/3.0/) for > Python 3000 shows : > > 9119625244b17aa35ed94b655a2b2135 13491200 python-3.0b1.msi > > but I got > > 9119625244a57aa35ed94b655a2b2135 13491200 python-3.0b1.msi > > (44a57 rather than 44b17 ) > > with several md5 checkers ( MdChecker (http://getmd5checker.com/) or a C > prog I've written) Wrong md5 checksum even with Python2.5 : import md5 m=md5.new() message=open("python-3.0b1.msi","rb").read() m.update(message) m.hexdigest() Answer : '9119625244a57aa35ed94b655a2b2135' Does anyone know what can be done to decide wether the file is corrupted or the checksum given is wrong ? From Lie.1296 at gmail.com Wed Jul 30 08:43:02 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 30 Jul 2008 05:43:02 -0700 (PDT) Subject: Insert character at a fixed position of lines References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> <7895c8b2-fa01-483c-8ba9-d90975ea688d@o40g2000prn.googlegroups.com> <8b0f4fe2-d8ab-4230-9032-ccd02878d349@v39g2000pro.googlegroups.com> Message-ID: On Jul 27, 10:02?am, alex23 wrote: > Ugh, and in pointing our your inaccurate code I posted my own: > > > >>> f = open('dummy.txt','w') > > >>> f.write(line = 'this doesn't work') > > > ? File "", line 1 > > ? ? f.write(line = 'this doesn't work') > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?^ > > SyntaxError: invalid syntax > > That should be: > > >>> f.write(line = "this doesn't work") > > Traceback (most recent call last): > ? File "", line 1, in > TypeError: write() takes no keyword arguments > > Sorry about that :) Lessons learned, should test codes even if you thought it seemed trivial. From bignose+hates-spam at benfinney.id.au Tue Jul 1 10:30:45 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 02 Jul 2008 00:30:45 +1000 Subject: Disabling the magic "last expression" _ variable References: <486a108d$0$14358$e4fe514c@news.xs4all.nl> Message-ID: <87d4lxllre.fsf@benfinney.id.au> Peter Otten <__peter__ at web.de> writes: > >>> import sys > >>> def displayhook(result): > ... if result is not None: > ... __builtins__._last = result > ... print result > ... Better is to explicitly import the name '__builtin__' . The name '__builtins__' is an implementation detail not guaranteed to be present in any particular implementation. import __builtin__ import sys def displayhook(result): if result is not None: __builtin__._last = result print result -- \ ?If you continue running Windows, your system may become | `\ unstable.? ?Microsoft, Windows 95 error message | _o__) | Ben Finney From harald.luessen at gmx.de Thu Jul 10 16:04:49 2008 From: harald.luessen at gmx.de (Harald Luessen) Date: Thu, 10 Jul 2008 22:04:49 +0200 Subject: error when porting C code to Python (bitwise manipulation) References: <8feab8ce-1e09-4438-b00a-3b31956c56af@k37g2000hsf.googlegroups.com> <5c521979-aaf0-4b4b-9673-671a978d050a@j22g2000hsf.googlegroups.com> Message-ID: <3hqc74lhdkdqrjb20h34k6ab65g2hc8ucp@4ax.com> On Thu, 10 Jul 2008 Jordan wrote: >On Jul 10, 1:35?pm, MRAB wrote: >> On Jul 10, 4:56?am, Jordan wrote: >> >> >> >> > I am trying to rewrite some C source code for a poker hand evaluator >> > in Python. ?Putting aside all of the comments such as just using the C >> > code, or using SWIG, etc. ?I have been having problems with my Python >> > code not responding the same way as the C version. >> >> > C verison: >> >> > unsigned find_fast(unsigned u) >> > { >> > ? ? unsigned a, b, r; >> > ? ? u += 0xe91aaa35; >> > ? ? u ^= u >> 16; >> > ? ? u += u << 8; >> > ? ? u ^= u >> 4; >> > ? ? b ?= (u >> 8) & 0x1ff; >> > ? ? a ?= (u + (u << 2)) >> 19; >> > ? ? r ?= a ^ hash_adjust[b]; >> > ? ? return r; >> >> > } >> >> > my version (Python, hopefully ;)): >> >> > def find_fast(u): >> > ? ? u += 0xe91aaa35 >> > ? ? u ^= u >> 16 >> > ? ? u += u << 8 >> > ? ? u ^= u >> 4 >> > ? ? b ?= (u >> 8) & 0x1ff >> > ? ? a ?= (u + (u << 2)) >> 19 >> > ? ? r ?= a ^ hash_adjust[b] >> > ? ? return r >> >> > As far as I understand the unsigned instructions in C just increase >> > amount of bytes the int can hold, and Python automatically converts to >> > longs which have infinite size when necessary, so I am not sure why I >> > am getting different results. >> >> > I assume that I am missing something fairly simple here, so help a >> > n00b out if you can :) >> >> > Thanks in advance, >> >> > jnb >> >> You want to restrict the values to 32 bits. The result of + or << may >> exceed 32 bits, so you need to mask off the excess bits afterwards. >> >> def find_fast(u): >> ? ? mask = 0xffffffff >> ? ? u ?= (u + 0xe91aaa35) & mask >> ? ? u ^= u >> 16 >> ? ? u ?= (u + (u << 8)) & mask # can get away with only 1 mask here >> ? ? u ^= u >> 4 >> ? ? b ?= (u >> 8) & 0x1ff >> ? ? a ?= ((u + (u << 2)) & mask) >> 19 # can get away with only 1 mask >> here >> ? ? r ?= a ^ hash_adjust[b] >> ? ? return r >> >> HTH > >Well, I guess there are two problems....the masking and the fact the >in C it seems to for some reason overflow and become a negative >value....still not sure why it does it....So the code with just >masking doesn't work, you still need some sort of weird inversion like >the ~(0xFFFFFFFF - u).....weird > >anyone? In C unsigned can not be negative. Why do you believe the numbers are negative? If your debugger is telling you this thow away the debugger and use printf. If printf is telling you this then use the right format. printf("%u", u); // for unsigned int u printf("%lu", u); // for unsigned long u printf("%x", u); or printf("0x%08x", u); // to see u in hex Harald From fredrik at pythonware.com Wed Jul 16 03:36:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 09:36:13 +0200 Subject: Is there any library that can extract titles from PDFs? In-Reply-To: References: Message-ID: ZelluX wrote: > I want to write a script which will rename PDFs according to their > titles. I want to know if there is any library that can extract > titles(the first line of the PDF) from PDFs. Mathieu Fenniak's PyPdf should be able to do this: http://pybrary.net/pyPdf/ (but note that "the first line of the PDF" may not be the first thing that's rendered on the page, so don't expect such an approach to work for all files) From emrahayanoglu at gmail.com Fri Jul 11 06:58:35 2008 From: emrahayanoglu at gmail.com (hardemr) Date: Fri, 11 Jul 2008 03:58:35 -0700 (PDT) Subject: How to serialize and deserialize the objects into memory? Message-ID: <0a7ead85-2a38-41a8-98b8-59dede61f985@c58g2000hsc.googlegroups.com> Hello Everyone, I want to serialize and deserialize the objects into Memory not into file. How can i do that? Best Regards, From fredrik at pythonware.com Tue Jul 22 05:18:45 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 11:18:45 +0200 Subject: xpathEval fails for large files In-Reply-To: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> References: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> Message-ID: Kanchana wrote: > I tried to extract some data with xpathEval. Path contain more than > 100,000 elements. > > doc = libxml2.parseFile("test.xml") > ctxt = doc.xpathNewContext() > result = ctxt.xpathEval('//src_ref/@editions') > doc.freeDoc() > ctxt.xpathFreeContext() > > this will stuck in following line and will result in high usage of > CPU. > result = ctxt.xpathEval('//src_ref/@editions') > > Any suggestions to resolve this. what happens if you just search for "//src_ref"? what happens if you use libxml's command line tools to do the same search? > Is there any better alternative to handle large documents? the raw libxml2 API is pretty hopeless; there's a much nicer binding called lxml: http://codespeak.net/lxml/ but that won't help if the problem is with libxml2 itself, though (in case you probably should check with an appropriate libxml2 forum). there's also cElementTree (bundled with Python 2.5), but that has only limited xpath support in the current version. both lxml and other implementations of the ET API supports incremental tree parsing: http://effbot.org/zone/element-iterparse.htm which handles huge documents quite nicely, but requires you to write the search logic in Python: for event, elem in ET.iterparse("test.xml"): if elem.tag == "src_ref" and elem.get("editions"): ... process element ... elem.clear() From alexnbryan at gmail.com Mon Jul 7 16:31:11 2008 From: alexnbryan at gmail.com (Alexnb) Date: Mon, 7 Jul 2008 13:31:11 -0700 (PDT) Subject: Trouble with Tkinter text margins Message-ID: <18325944.post@talk.nabble.com> I am writing a program in which there is a textbox and in it the program auto inputs a series of words, and definitions for each word. I want to make it formatted nicely to where the word is indented, and the definitions indented even more. I don't even know how to make the margins work. I have read all the documentation but just need an example so that will help. But my bigger issue is that the way I have written it is like this: for entry in WordList: the definions go in. While that is very dumbed down, that is the gist. Meaning the words to be defined are in "wordlist" and for each entry it prints the entry and the definition. My problem is that I want the lmargin1 to be indented a little, and that will be the margin where the words are, and lmargin2 to be indented even further, and that will be where the definitions go. I want it to look like this: word: definition1 definition2 word2: definition1 and so on. So I need some help trying to figure out how to make this work with the for loop. -- View this message in context: http://www.nabble.com/Trouble-with-Tkinter-text-margins-tp18325944p18325944.html Sent from the Python - python-list mailing list archive at Nabble.com. From trentm at activestate.com Mon Jul 28 12:36:41 2008 From: trentm at activestate.com (Trent Mick) Date: Mon, 28 Jul 2008 09:36:41 -0700 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: <488D53AB.7090300@gmail.com> References: <487E2BCE.30108@hughes.net> <488A2E72.6030802@activestate.com> <488D53AB.7090300@gmail.com> Message-ID: <488DF599.7070904@activestate.com> Manuel Vazquez Acosta wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Just test for maxint value: > > from sys import maxint > if maxint >> 33: > print "more than 32 bits" # probably 64 > else: > print "32 bits" I believe that was already suggested in this thread. That test will just tell you if the Python *build* is 32-bit or 64-bit. If the answer is 32-bit, then that doesn't tell you if this is a 32-bit Python running on a 64-bit OS. Trent -- Trent Mick trentm at activestate.com From duncan.booth at invalid.invalid Sat Jul 19 14:01:21 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Jul 2008 18:01:21 GMT Subject: Change PC to Win or Windows References: <6eej73F6k7g3U3@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Sat, 19 Jul 2008 11:02:51 -0500, Grant Edwards wrote: > >> On 2008-07-19, Dennis Lee Bieber wrote: >> >>> Which term applied to the TRS-80, the Apple II, Altair even... >> >> Not that I remember. I had a homebrew S-100 bus system, worked >> with varioius Commodore machines, a few Apples, and some other >> CP/M systems. I never heard any of them called a 'PC'. My >> recollection is that 'PC' was a term that IBM coined. > > The C64 that still sits on my desk has a label on it saying > ???commodore 64 - personal computer???. > and I cut my programming teeth on a Sharp MZ80K personal computer. http://www.sharpmz.org/mz-80k/images/mz80kade1_1.jpg From mwilson at the-wire.com Sun Jul 6 16:36:13 2008 From: mwilson at the-wire.com (Mel) Date: Sun, 06 Jul 2008 16:36:13 -0400 Subject: how are strings immutable in python? References: Message-ID: ssecorp wrote: >>>> h = "aja baja" >>>> h += 'e' >>>> h > 'aja bajae' >>>> What Peter said, or, to put it another way: Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = b = "aja baja" >>> a += "e" >>> print a aja bajae >>> print b aja baja Mutability/immutability makes a difference in programs when different symbols (or container items) share a value. Mel. From pk.perl at gmail.com Wed Jul 2 07:24:10 2008 From: pk.perl at gmail.com (Prosenjit Kundu) Date: Wed, 02 Jul 2008 16:54:10 +0530 Subject: Scripting SAP GUI (Windows) In-Reply-To: <6d15tpFaec4U1@mid.individual.net> References: <6d15tpFaec4U1@mid.individual.net> Message-ID: <486B655A.8080408@gmail.com> First of all Linux is much better place. why you want to automate GUI with python. You can easily use QTP such GUI testing tools to automate your staff. But that does not mean I am saying the Python is bad in any way. Py and Perl are the two most good things in this world. py-py, Prosenjit Thomas Guettler wrote: > Hi, > > I need to script SAP GUI running on MS-Windows: > > Open SAP GUI window, if it is not already open, and then batch input > some keystrokes. > > The following solutions were found by google: > > - autohotkey: not preferred, since it has an own programming > language. This will slow down development. > - pyHook > - user pywin32 and SetWindowsHookEx > > I develop with python since seven years, but only on linux. > > Any hints? > > From Russ.Paielli at gmail.com Wed Jul 30 03:53:47 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 30 Jul 2008 00:53:47 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> Message-ID: <2da5350e-d74e-4760-b9b8-7cc9869dc607@n33g2000pri.googlegroups.com> On Jul 30, 12:49 am, Heiko Wundram wrote: > Am Mittwoch, 30. Juli 2008 09:18:48 schrieb Russ P.: > > > Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > > __nonzero__ work in Python. It's very basic stuff. You can quit > > patronizing me (and Carl too, I'm sure). > > I'll stop repeating what the current state is (which might sound like I'm > patronizing, but that's not the real intent actually, I'm just trying to get > the discussion straight with what is fact, namely that there already exists > an explicit way which doesn't seem to be recognized by some people here) if > you agree to my point that we're not talking about a problem with Python, but > about a personal stylistic issue with the language design. That's just what I > said in my last mail: I can concede that you, personally, have an issue with > the current state, but for me and seemingly also for a majority of people who > have posted in this thread, that's a non-issue. > > > The point that you seem to be missing, or refuse to acknowledge for > > some reason, is that "if x" can be mistakenly applied to any object > > when the programmer thinks that x is a list -- and the programmer will > > receive no feedback on the error. > > > I have made errors like that, and I could have saved some time had I > > used an "empty" method that only applies to a list or other sequence. > > For me, I've never had this kind of problem, simply because if I test for the > truth value of something, I'm going to do something with it later on, and as > soon as I'm doing something with it, I'll see whether the object supports the > interface I want it to support (and get an error there if the object doesn't > support the basic notions of a sequence type, for example, i.e. __iter__()). > Testing for truth is IMHO not doing something with an object, and as such I'm > more than happy that it's "foolproof". This is one thing that I personally > find attractive about Python's way of duck-typing. > > But, if you personally have been bitten by this, give an example, and I'm sure > that we can start discussing from there. I've already given an example why > the explicit test for length is less polymorphic than the explicit test for > truth of a container elsewhere as a proof for the point I'm trying to make. > > -- > Heiko Wundram Fair enough. I have no dog in this particular fight. I just think it wouldn't hurt to add an "isempty()" or "isnonempty()" method to the list type, and let people use it if they wish, or continue using "if x" if that's what they prefer. From alif016 at gmail.com Fri Jul 18 10:51:49 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Fri, 18 Jul 2008 09:51:49 -0500 Subject: trying to match a string In-Reply-To: <4880AD1A.6040707@gmail.com> References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> Message-ID: <4880AE05.2050005@gmail.com> Andrew Freeman wrote: > oj wrote: >> On Jul 18, 12:10 pm, John Machin wrote: >> >>> On Jul 18, 9:05 pm, oj wrote: >>> >>> >>> >>> >>>> On Jul 18, 11:33 am, arnimavidyar... at gmail.com wrote: >>>> >>>>> Hi, >>>>> Hi, >>>>> I am taking a string as an input from the user and it >>>>> should only >>>>> contain the chars:L , M or R >>>>> I tried the folllowing in kodos but they are still not >>>>> perfect: >>>>> [^A-K,^N-Q,^S-Z,^0-9] >>>>> [L][M][R] >>>>> [LRM]?L?[LRM]? etc but they do not exactly meet what I need. >>>>> For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' >>>>> .like that. >>>>> regards, >>>>> SZ >>>>> The string may or may not have all the three chars. >>>>> >>>> With regular expressions, [^LRM] matches a character that isn't L, R >>>> or M. So: >>>> import re >>>> var = "LRLRLRLNR" >>>> if re.search(r'[^LRM]', var): >>>> print "Invalid" >>>> >>> Fails if var refers to the empty string. >>> >> >> No it doesn't, it succeeds if var is an empty string. An empty string >> doesn't contain characters that are not L, R or M. >> >> The OP doesn't specify whether an empty string is valid or not. My >> interpretation was that an empty string would be valid. >> > Why not just use * instead of + like: > > if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of > string; $ means end of string > print "Invalid" > > This will *only* print invalid when there is a character other than L, > R, or M or a empty string. > Sorry, forget the beginning and ending markers, I just tried it out, it doesn't work. use this instead: if re.search(r'[^LRM]*', var): print "Invalid" From PengYu.UT at gmail.com Wed Jul 16 12:38:26 2008 From: PengYu.UT at gmail.com (Peng Yu) Date: Wed, 16 Jul 2008 09:38:26 -0700 (PDT) Subject: how to match whole word References: Message-ID: <97461ec5-151a-4527-a5fa-c5da07941e46@l42g2000hsc.googlegroups.com> On Jul 15, 10:29 pm, Gary Herron wrote: > Peng Yu wrote: > > Hi, > > > The following code snippet is from /usr/bin/rpl. I would like the it > > to match a word, for example, "abc" in ":abc:". But the current one > > would not match "abc" in ":abc:". I tried to modify it myself. Would > > you please let me know what is the corrected way to do it? > > > Thanks, > > Peng > > > if opts.whole_words: > > regex = re.compile(r"(?:(?<=\s)|^)" + re.escape(old_str) + r"(?=\s| > > $)", > > opts.ignore_case and re.I or 0) > > -- > >http://mail.python.org/mailman/listinfo/python-list > > The regular expression "\w+" will match (what might be your definition > of) a word, and in particular will match abc in :abc:. Regular > expressions have lots of other special \-sequences that might be worth > your while to read about: http://docs.python.org/lib/re-syntax.html > > Gary Herron I didn't read the docs and tried the following code. regex = re.compile(r"\A" + re.escape(old_str) + r"\Z", opts.ignore_case and re.I or 0) But I'm not sure why it is not working. Thanks, Peng From sukkopera at gmail.com Fri Jul 18 04:42:38 2008 From: sukkopera at gmail.com (sukkopera at gmail.com) Date: Fri, 18 Jul 2008 01:42:38 -0700 (PDT) Subject: Unexpected default arguments behaviour (Maybe bug?) References: <4f29ccf6-4daf-4e8e-8735-96cffd8a882e@t54g2000hsg.googlegroups.com> <475185e0-360a-452b-8d22-33ffc243b8a0@z66g2000hsc.googlegroups.com> <98fdc845-cb62-4e7b-891c-dfc75d741a2f@z66g2000hsc.googlegroups.com> Message-ID: <76c1fc77-ab6d-4d9e-a2eb-6d6a74c5bbcc@b2g2000prf.googlegroups.com> FYI, I have opened a bug on the official tracker: http://bugs.python.org/issue3403. From emen999 at gmail.com Wed Jul 23 13:06:03 2008 From: emen999 at gmail.com (code_berzerker) Date: Wed, 23 Jul 2008 10:06:03 -0700 (PDT) Subject: lxml, comparing nodes References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> Message-ID: On Jul 23, 6:29?pm, Stefan Behnel wrote: > Your requirements for a single Element are simple enough to write it in three > to five lines of Python code (depending on your definition of equality). > Checking this equality recursively is another two to three lines. Not complex > enough to be considered a wheel in the first place. Forgive my ignorance as I am new to both Python and lxml ;) From malaclypse2 at gmail.com Tue Jul 8 13:15:59 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 8 Jul 2008 13:15:59 -0400 Subject: problem with Tkinter after installing Python 2.5.2 on UBUNTU In-Reply-To: <83df18ac-e39c-4a1d-95a0-53886d873ea8@s50g2000hsb.googlegroups.com> References: <83df18ac-e39c-4a1d-95a0-53886d873ea8@s50g2000hsb.googlegroups.com> Message-ID: <16651e80807081015k104c686o1a6af8f71ba7a4db@mail.gmail.com> On Tue, Jul 8, 2008 at 12:44 PM, wrote: > I just installed Python 2.5.2 on UBUNTU Linux. It seems to work, > however I don't seem to have access Tkinter. This is the result of > "import Tkinter": I think ubuntu and debian both split Tkinter out of their main python packages. Try installing the python-tk package (via your favorite package manager, or from the command line 'sudo aptitude install python-tk') -- Jerry From tjreedy at udel.edu Fri Jul 4 04:37:04 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 04 Jul 2008 04:37:04 -0400 Subject: Singleton implementation problems In-Reply-To: <87abgy2kcu.fsf@benfinney.id.au> References: <87abgy2kcu.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Peter Otten <__peter__ at web.de> writes: > >> The problem is the structure of your program. The myset module is >> imported twice by Python, once as "myset" and once as "__main__". > > Yes, this is the problem. Each module imports the other. > >> Therefore you get two distinct MySet classes, and consequently two >> distinct MySet.__instance class attributes. > > Are you sure? This goes against my understanding: that 'import foo' > will not re-import a module that's already been imported, but will > instead simply return the existing module. Peter is correct that a module can only be imported once per *name*. In 3.0b1 temp.py ================= print(__name__) import temp print(__name__) from sys import modules as m print(m['__main__'] is m['temp']) produces ================== __main__ temp temp False __main__ False Duplicate imports under multiple names are a known problem, and this is not the only way to create such. But what can an interpreter do when it sees 'import x' other than check that 'x' is not already a key in sys.modules? Iterate through sys.modules (increasingly slow as the dict grows) and do what exactly? The semantics of 'import x' are to get sys.modules['x'] if it exists; otherwise 'initialize' module x according to what that means for the implementation and current state and mode of operation of the system. Modules are not required to have .__file__ attributes since they do not have to come from named files ;-). (And then the module is bound to 'x' in the importing namespace.) Terry Jan Reedy From motoom at xs4all.nl Fri Jul 11 14:15:39 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Fri, 11 Jul 2008 20:15:39 +0200 Subject: Using the Random Module. Message-ID: <2.2.32.20080711181539.01128274@pop.xs4all.nl> You wrote... >Is there a better way to do that besides doing this: > >>>>random.randint(00000000000000000, 99999999999999999) >09657398671238769 Maybe this? random.randint(0, 9e16) -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From bearophileHUGS at lycos.com Thu Jul 31 16:02:44 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 31 Jul 2008 13:02:44 -0700 (PDT) Subject: Hobbyist - Python vs. other languages References: Message-ID: <56c43c99-e525-4fad-9833-92359ce7e3da@y21g2000hsf.googlegroups.com> fprintf: > and yet they all end at the point where a person has enough > knowledge of the syntax, but not really enough to do anything. A programming language is a tool to solve problems, so first of all: do you have problems to solve? You can create some visualizations, some program with GUI, some networked code to download things and process them, etc. Another thing is that you probably have to learn beyond syntax, you can learn about GUIs, network protocols, PyGame, mathematics, some science, etc, they will give you both more things to learn (about the language too) and problems/ideas to solve. Bye, bearophile From mail at timgolden.me.uk Fri Jul 11 09:09:24 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 11 Jul 2008 14:09:24 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) In-Reply-To: References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: <48775B84.4040604@timgolden.me.uk> Bill Davy wrote: > and since then have been busy with work, and my other job, and the garden. Aha! So you're English, are you? Looks like you're in the West Country. Weather map suggests you're not short of rain over there :) > Now I am back looking at this (and using WInUSB to talk to a Maxim 3421E etc > etc but that's another story). So any help today will be much appreciated. > Rgds, Can't remember what the particular obstacles were you were facing, but this runs OK on my setup - Python 2.5.2 / pywin32 211 / Outlook 2003: import os, sys import win32com.client constants = win32com.client.constants def items (contacts): items = contacts.Items item = items.GetFirst () while item: yield item item = items.GetNext () # # Add whatever fields you like from: # http://msdn.microsoft.com/en-us/library/aa210907(office.11).aspx # FIELDS = ['FullName', 'CompanyName', 'Email1Address'] outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") ns = outlook.GetNamespace ("MAPI") for contact in items (ns.GetDefaultFolder (constants.olFolderContacts)): if contact.Class == constants.olContact: print contact for field in FIELDS: print " ", field, "=>", getattr (contact, field, "") Hope that helps. TJG From bignose+hates-spam at benfinney.id.au Wed Jul 16 03:34:10 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jul 2008 17:34:10 +1000 Subject: Python internals References: <008ca729$0$20313$c3e8da3@news.astraweb.com> <87hcaq7pja.fsf@benfinney.id.au> <008d93af$0$20327$c3e8da3@news.astraweb.com> Message-ID: <87wsjm2sgd.fsf@benfinney.id.au> Peter Anderson writes: > If Python doesn't do it like C and the others then what mechanism does > it use You've already been pointed to it, but here it is again: -- \ ?I may disagree with what you say, but I will defend to the | `\ death your right to mis-attribute this quote to Voltaire.? | _o__) ?Avram Grumer, rec.arts.sf.written, May 2000 | Ben Finney From stefan_ml at behnel.de Thu Jul 17 11:04:08 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 17 Jul 2008 17:04:08 +0200 Subject: Good HTML Parser In-Reply-To: References: Message-ID: <487f5f68$0$7543$9b4e6d93@newsspool1.arcor-online.net> Chris wrote: > Can anyone recommend a good HTML/XHTML parser, similar to > HTMLParser.HTMLParser or htmllib.HTMLParser, but able to intelligently > know that certain tags, like
, are implicitly closed? I need to > iterate through the entire DOM, building up a DOM path, but the stdlib > parsers aren't calling handle_endtag() for any implicitly closed tags. > I looked at BeautifulSoup, but it only seems to work by first parsing > the entire document, then allowing you to query the document > afterwards. I need something like a SAX parser. Try lxml.html. It's very memory friendly and extremely fast, so you may end up without any reason to use SAX anymore. http://codespeak.net/lxml/ Stefan From alif016 at gmail.com Sat Jul 26 12:02:14 2008 From: alif016 at gmail.com (Andrew) Date: Sat, 26 Jul 2008 11:02:14 -0500 Subject: Easier way to get the "here" path? In-Reply-To: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> References: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> Message-ID: <488B4A86.4010308@gmail.com> bukzor wrote: > I have to go into these convulsions to get the directory that the > script is in whenever I need to use relative paths. I was wondering if > you guys have a better way: > ... > If you just need the current path (where it is executed) why not use os.getcwd() which returns a string of the absolute path to the module being executed. $ echo "print __file__" > path.py $ ipython In [1]: import path path.pyc In [2]: import os In [3]: os.path.join(os.getcwd(), path.__file__.rstrip("c")) Out[3]: '/home/andrew/path.py' -- Andrew From deets at nospam.web.de Fri Jul 18 06:28:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 18 Jul 2008 12:28:19 +0200 Subject: Protecting instance variables In-Reply-To: References: Message-ID: <6eb9iaF6779oU1@mid.uni-berlin.de> Nikolaus Rath schrieb: > Hello, > > I am really surprised that I am asking this question on the mailing > list, but I really couldn't find it on python.org/doc. > > Why is there no proper way to protect an instance variable from access > in derived classes? > > I can perfectly understand the philosophy behind not protecting them > from access in external code ("protection by convention"), but isn't > it a major design flaw that when designing a derived class I first > have to study the base classes source code? Otherwise I may always > accidentally overwrite an instance variable used by the base class... Here we go again... http://groups.google.com/group/comp.lang.python/browse_thread/thread/188467d724b48b32/ To directly answer your question: that's what the __ (double underscore) name mangling is for. Diez From arne at vajhoej.dk Sun Jul 13 10:12:32 2008 From: arne at vajhoej.dk (=?UTF-8?B?QXJuZSBWYWpow7hq?=) Date: Sun, 13 Jul 2008 10:12:32 -0400 Subject: spam <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> In-Reply-To: References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> Message-ID: <487a0d4d$0$90272$14726298@news.sunsite.dk> Kevin McMurtrie wrote: > In article , > Lew wrote: >> WDC wrote: >>> BTW I reported it, yo should too. >> To whom did you report it, so that we may also report it there? > > Google does not accept spam complaints. Go ahead, try it. That's why > they've been the #1 Usenet spamming tool for years now. What you're > seeing is the spam slowly expanding into the software development > groups. uk.railway is probably a random group added to confuse spam > filters. Some groups, like rec.photo.digital, have been getting > hundreds of Google spams a day for about a year. > > Ask your news service for a Google UDP (Usenet Death Penalty) or > configure your reader to drop everything with "googlegroups.com" in the > Message-ID. Some real users do use GG. Arne From wuwei23 at gmail.com Tue Jul 22 09:00:49 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 22 Jul 2008 06:00:49 -0700 (PDT) Subject: Python embedding question (2). References: Message-ID: <4ed11a51-bc45-4660-bbd5-bfe468f66725@y21g2000hsf.googlegroups.com> On Jul 22, 10:07?pm, Thomas Troeger wrote: > Maybe this is the wrong list to ask, so please forgive the question but > direct me to somewhere better. http://groups.google.com/group/pygame-mirror-on-google-groups There are instructions on that page for joining the mailing list if Google Groups aren't your thing. From deets at nospam.web.de Tue Jul 29 12:20:17 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jul 2008 18:20:17 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <488d86e2$1@news2-rz-ap.ethz.ch> <488dc3eb$1@news2-rz-ap.ethz.ch> <488ddc3c$1@news2-rz-ap.ethz.ch> <488f3670$1@news2-rz-ap.ethz.ch> Message-ID: <6f8uc6FahulcU1@mid.uni-berlin.de> Suresh Pillai wrote: > On Mon, 28 Jul 2008 16:48:28 +0200, Suresh Pillai wrote: > >> Okay, please consider this my one absolutely stupid post for the year. >> I'd like to pretend it never happened but unfortunately the web doesn't >> allow that. Having never used sets, I unfort read something that lead >> to it, but ... > > Okay, got some sleep and what I meant to ask, although equally basic, but > not silly: > > For sets, I presume they are built on top of or like dicts, and there is > nothing crazy in the low level implementation so that I can be guaranteed > that if I don't alter the set, then the order, although arbitrary, will > be maintained in successive iterations over the contents? It is currently that way, but relying on it is certainly to be considered an implementation detail that might disappear without warning. Diez From jsanga at cox.net Wed Jul 23 21:14:09 2008 From: jsanga at cox.net (mzdude) Date: Wed, 23 Jul 2008 18:14:09 -0700 (PDT) Subject: Request Help Debugging Program References: <898dfe7a-4133-4337-8243-f4936b8a8092@8g2000hse.googlegroups.com> Message-ID: <9ba3340e-1048-4958-b988-d2a83559111d@d77g2000hsb.googlegroups.com> On Jul 23, 6:30?pm, Samir wrote: > Hi Everyone, > > > def findSumOfDivisor(n): > ? ? return sum(divisor) ? ? ? ? ? ? ? ?# fine using function sum() > > ? ? ? ? sum = findSumOfDivisor(i) ? ? ?# then find the sum of its divisors oops redefine what sum is. >>> x = [1,2] >>> sum(x) 3 >>> sum = 4 >>> sum(x) Traceback (most recent call last): File "", line 1, in sum(x) TypeError: 'int' object is not callable >>> From fredrik at pythonware.com Sun Jul 20 11:28:23 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jul 2008 17:28:23 +0200 Subject: Passing keywords In-Reply-To: <73285f0c-da54-4c43-b83e-27c3e1b26951@2g2000hsn.googlegroups.com> References: <73285f0c-da54-4c43-b83e-27c3e1b26951@2g2000hsn.googlegroups.com> Message-ID: Kless wrote: > I could use the next but I don't think... > > --------------- > def __check(self, **keywords): > --------------- don't think what? if you keep using the same variables in all submethods you call from a method inside the class, why not make them attributes? otherwise, using the **-form when *calling* the methods might work. you can use the **-form in the functions to ignore arguments that you're not interested in. self.__check(**kwargs) self.__check2(**kwargs) def __check(self, foo1, foo2, **extra): # use foo1 and foo2 here; ignore the rest etc. From gagsl-py2 at yahoo.com.ar Fri Jul 11 05:41:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Jul 2008 06:41:32 -0300 Subject: problem with exec and locals() References: <95f07476-e3c8-45e4-82b3-0e48c9188f8e@79g2000hsk.googlegroups.com> <2fc55416-76c7-48c8-8f49-64c10c5daeda@w7g2000hsa.googlegroups.com> Message-ID: En Fri, 11 Jul 2008 03:51:39 -0300, Uwe Schmitt escribi?: > On 1 Jul., 15:15, Mel wrote: >> rocksportrockerwrote: >> >> > the following code does not work until I ommit the "a=0" statement. >> >> > ? ?def test(): >> > ? ? ? ?exec "a=3" in locals() >> > ? ? ? ?print a >> > ? ? ? ?a=0 >> >> > ? ? test() >> >> > print raises: >> > ? ? ?UnboundLocalError: local variable 'a' referenced before >> > assignment >> >> > Can anybody explain what is going wrong here ? >> >> AFAIK, local variables are implemented rather like __slots__ in >> new-style >> classes. ?This is a very valuable efficiency measure, but it can cause >> this >> kind of trouble. ?Without `a=0`, the bytecode compiler makes no slot >> for a, > > Thanks for your answer. I wonder if this is a bug, or did I miss > something > in the docs ??? Read the warnings in the docs for the locals() builtin function: http://docs.python.org/lib/built-in-funcs.html#l2h-47 and the execfile function: http://docs.python.org/lib/built-in-funcs.html#l2h-26 -- Gabriel Genellina From ppearson at nowhere.invalid Tue Jul 1 12:31:39 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: Tue, 01 Jul 2008 11:31:39 -0500 Subject: wrong md5 checksum References: <486a16ef$0$885$ba4acef3@news.orange.fr> <486a5316$0$864$ba4acef3@news.orange.fr> Message-ID: <2-CdnaVu6892xvfVnZ2dnUVZ_gGdnZ2d@supernews.com> On Tue, 01 Jul 2008 17:54:05 +0200, kkwweett wrote: > kkwweett a ?crit : >> Hi, >> >> the download page (http://www.python.org/download/releases/3.0/) for >> Python 3000 shows : >> >> 9119625244b17aa35ed94b655a2b2135 13491200 python-3.0b1.msi >> >> but I got >> >> 9119625244a57aa35ed94b655a2b2135 13491200 python-3.0b1.msi >> >> (44a57 rather than 44b17 ) >> [snip] > Does anyone know what can be done to decide wether the file is corrupted > or the checksum given is wrong ? For what it's worth, md5sum (GNU coreutils) 5.93 agrees with your result. This interesting almost-agreement could result from A. an error in the software that computed the value for the web page, B. a transcription error in putting the checksum on the web page, C. accidental corruption of the file, or D. a deliberate attempt to substitute a file with a similar MD5 sum. Possibility C is unlikely, but would be the most exciting development in cryptology this year. If C turns out to be the explanation, I hope someone will make sure sci.crypt gets told. Possibility D would be awfully interesting, too. -- To email me, substitute nowhere->spamcop, invalid->net. From motoom at xs4all.nl Tue Jul 15 10:37:31 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Tue, 15 Jul 2008 16:37:31 +0200 Subject: Simplify Code Message-ID: <2.2.32.20080715143731.012ae780@pop.xs4all.nl> Victor wrote... ># Headers are kept in order to determine nesting of chapters ># They are labeled according to font size I'm not sure what you're trying to achieve (I can't divine it from your example code), but I suspect that a dictionary of sizes and header texts is somewhat more manegable than a slew of separate variables h12, h14, h16, h22, h36 etc... Maybe this gives an idea: # this could come from an input file or a parser source=( (18,"Hello"), (36,"Greetings"), # (11,"Boeh") , # uncomment to test this illegal size (36,"You too"), (12,"Bye"), ) # for each font size, remember the last seen header text headers={12:"", 14:"", 18:"", 22:"", 26:"", 36:""} # process the source, collect the header texts for (size,text) in source: if not size in headers: raise KeyError("%d is an illegal size. It must be one of %s" % (size,sorted(headers))) headers[size]=text # do something with the collected header texts for h in sorted(headers): print h,headers[h] Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From kris at FreeBSD.org Wed Jul 9 08:37:28 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Wed, 09 Jul 2008 14:37:28 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <20080709121848.GO26006@nexus.in-nomine.org> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <750f823a-f9de-4f81-9eb3-7c7b39237c90@y38g2000hsy.googlegroups.com> <4874A9C9.7020804@FreeBSD.org> <20080709121848.GO26006@nexus.in-nomine.org> Message-ID: <4874B108.9060205@FreeBSD.org> Jeroen Ruigrok van der Werven wrote: > -On [20080709 14:08], Kris Kennaway (kris at FreeBSD.org) wrote: >> It's compiler/build output. > > Sounds like the FreeBSD ports build cluster. :) Yes indeed! > Kris, have you tried a PGO build of Python with your specific usage? I > cannot guarantee it will significantly speed things up though. I am pretty sure the problem is algorithmic, not bad byte code :) If it was a matter of a few % then that is in the scope of compiler tweaks, but we're talking orders of magnitude. Kris > Also, a while ago I did tests with various GCC compilers and their effect on > Python running time as well as Intel's cc. Intel won on (nearly) all > accounts, meaning it was faster overall. > > From the top of my mind: GCC 4.1.x was faster than GCC 4.2.x. > From pyshib at googlemail.com Wed Jul 30 05:06:08 2008 From: pyshib at googlemail.com (pyshib at googlemail.com) Date: Wed, 30 Jul 2008 02:06:08 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> Message-ID: <8882ed70-2123-40a6-84a7-9fa170f1c384@k30g2000hse.googlegroups.com> If you want to convert the file names which use standard URL encoding (with %20 for space, etc) use: from urllib import unquote new_filename = unquote(filename) I have found this does not convert encoded characters of the form '&#CC;' so you may have to do that manually. I think these are just ascii encodings in hexadecimal. From linuxnow at gmail.com Wed Jul 9 18:21:09 2008 From: linuxnow at gmail.com (linuxnow at gmail.com) Date: Wed, 9 Jul 2008 15:21:09 -0700 (PDT) Subject: how to remove oldest files up to a limit efficiently References: <1eb168ac-fc63-4724-8604-45e995a06b51@s50g2000hsb.googlegroups.com> Message-ID: <01403c64-f282-4ed9-a624-5925089a297d@l64g2000hse.googlegroups.com> On Jul 9, 7:08?pm, Terry Reedy wrote: > Dan Stromberg wrote: > > On Tue, 08 Jul 2008 15:18:23 -0700, linux... at gmail.com wrote: > > >> I need to mantain a filesystem where I'll keep only the most recently > >> used (MRU) files; least recently used ones (LRU) have to be removed to > >> leave space for newer ones. The filesystem in question is a clustered fs > >> (glusterfs) which is very slow on "find" operations. To add complexity > >> there are more than 10^6 files in 2 levels: 16? dirs with equally > >> distributed number of files inside. > > >> Any suggestions of how to do it effectively? > > > os.walk once. > > > Build a list of all files in memory. > > > Sort them by whatever time you prefer - you can get times from os.stat. > > Since you do not need all 10**6 files sorted, you might also try the > heapq module. ?The entries into the heap would be (time, fileid) I'll look into it: probably sorting dirs by atime and adding the files inside to the heapq until I can remove enough of them would work very efficiently. Thanks Pau From andreas.mock at web.de Wed Jul 16 03:55:55 2008 From: andreas.mock at web.de (McA) Date: Wed, 16 Jul 2008 00:55:55 -0700 (PDT) Subject: Logging to different addressees References: <8df30038-86c1-4376-b046-a50f2bcf0a2b@s50g2000hsb.googlegroups.com> <7b829a76-ba2c-4cb7-b216-0c9c01e5cd02@f36g2000hsa.googlegroups.com> <4d3df1d9-339b-43b2-9f25-c792e9bf549c@k13g2000hse.googlegroups.com> Message-ID: <4e30c301-294c-4160-8cb8-c924aed00f71@f63g2000hsf.googlegroups.com> Hi Vinay, thank you for being so patient. On 16 Jul., 01:21, Vinay Sajip wrote: > On Jul 15, 5:17 pm, McA wrote: > > > > If you added the admin sink handler to the root logger, you're done. > > > Isn't that the first thing above? What do you mean? > > I gave you a choice - to add the handler to the admin_logger OR the > root logger. So I am saying here that if you added to the root logger > (and not common_logger, assuming they're different), then there's > nothing more to do... Reading the rest of your mail let me understand what you meant. > > # simple.py > import logging > > admin_logger = logging.getLogger("") # The root logger > addressee_logger = logging.getLogger("addressee") > > admin_sink = logging.FileHandler("admin.log", "w") > addressee_sink = logging.FileHandler("addressee.log", "w") > > admin_logger.addHandler(admin_sink) > addressee_logger.addHandler(addressee_sink) > > admin_logger.setLevel(logging.DEBUG) > > admin_logger.debug("This message appears in admin sink only.") > addressee_logger.debug("This message appears in both admin sink and > addressee sink." > Thank you for that snippet. That means, that the root-logger does inherit EVERY message (if it fits to the level and isn't filtered) and the inheritage chain is build by the chosen logger names, e.g. messages to logging.getLogger('tree.leave') would also show up in logging.getLogger('tree') automatically? If this is true, how can I avoid this "bubbling up" if I would like to? (You see, that's a new question, but I want to take the chance to get the answers from you personally ;-) Hope not to bother. Best regards Andreas Mock From mischneider1 at googlemail.com Wed Jul 23 12:45:22 2008 From: mischneider1 at googlemail.com (Michael Schneider) Date: 23 Jul 2008 16:45:22 GMT Subject: concatenate the elements in each list of a list of lists References: <72c425b7-d9c2-4a61-8b7f-075eae14e703@x41g2000hsb.googlegroups.com> Message-ID: <48876022$0$25953$6e1ede2f@read.cnntp.org> Am Wed, 23 Jul 2008 08:33:57 -0700 wrote antar2: > I already asked a similar question, but encounter problems with > python... > How can I concatenate the elements in each list of a list of lists > > list_of_listsA = > > [['klas*', '*', '*'], > ['mooi*', '*', '*', '*'], > ['arm*', '*', '*(haar)']] > > wanted result: > > list_of_listsA = > > [['klas* * *'] > ['mooi* * * *'] > ['arm* * *(haar)']] > > Thanks a lot ! Hello, maybe this will help: In [5]: list_of_listsA = [['klas*', '*', '*'], ['mooi*', '*', '*', '*'], ['arm*', '* ', '*(haar)']] In [6]: s = "" In [7]: print [[s.join(item)] for item in list_of_listsA] [['klas***'], ['mooi****'], ['arm** *(haar)']] regards Michael From richardlev at gmail.com Sat Jul 26 03:49:20 2008 From: richardlev at gmail.com (Richard Levasseur) Date: Sat, 26 Jul 2008 00:49:20 -0700 (PDT) Subject: SimpleJson is slow .... is there any C Compiled version ? References: Message-ID: <83a8a774-ddec-4137-9dbe-b6db3b4adfa2@p25g2000hsf.googlegroups.com> On Jul 25, 5:52?pm, Matt Nordhoff wrote: > Also, simplejson and python-cjson might not be entirely compatible: > there's one character that one escapes and the other doesn't, or something. > -- They also have different interface. simplejson uses load/loads/dump/ dumps, whereas cjson using encode/decode (its pretty simple to monkeypatch cjson with some lambda's so it has the same interface, though). Yeah, its frustrating that there are so many json encoders for python. Its a bit disappointing simplejson is going into the stdlib; i hope they rewrite it in C? http://blog.hill-street.net/?p=7 Has a good comparison of encoders. From kyosohma at gmail.com Wed Jul 23 16:11:00 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 23 Jul 2008 13:11:00 -0700 (PDT) Subject: Raw Strings (I Think) References: Message-ID: On Jul 24, 10:02?am, "Lanny" wrote: > I've used glob.glob to get a list of files in a directory > and now I want to use os.system to execute one of > those files, the problem is that python automatically > puts a escape charater infront of the back slashes > so the os.system gets X:\\####\\####\\ and is useless, > I think I need to convert my string to a raw string but > I don't know how. > > -- Posted on news://freenews.netfront.net - Complaints to n... at netfront.net -- This works fine for me on Windows XP. I did this: glob.glob(r'c:\test') which gave me something like this: ['c:\\test\\07-24TimeSheet.xls', 'c:\\test\\accts.CSV', 'c:\\test\ \Ataris Aqu\xe1ticos #2.txt', 'c:\\test\\changes.txt', 'c:\\test\ \change_g.txt', 'c:\\test\\config.ini', 'c:\\test\\County.txt', 'c:\ \test\\county1.txt', 'c:\\test\\ctypes-1.0.1.tar.gz', 'c:\\test\ \DAMNATUS_Soundtrack.zip', 'c:\\test\\doodad.1.12.3.doc', 'c:\\test\ \doodad.1.32.3.doc', 'c:\\test\\doodad.22.12.3.doc', 'c:\\test\ \emailMess.xml', 'c:\\test\\Eula.txt', 'c:\\test\\fasta.txt', 'c:\\test \\Funds.txt', 'c:\\test\\Funds2.txt', 'c:\\test\\Gmane.newsrc', 'c:\ \test\\groups.ini', 'c:\\test\\hammy.doc'] Now, if I use os.system like this, it works: os.system('notepad %s' % x[1]) This opens notepad with my *.csv file just fine. Windows XP, Python 2.5.2. Mike From fredrik at pythonware.com Tue Jul 22 05:10:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 11:10:51 +0200 Subject: proliferation of computer languages In-Reply-To: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> Message-ID: xahlee at gmail.com wrote: > There is a proliferation of computer languages today like never > before. "... today ... 1,700 special programming languages used to 'communicate' in over 700 application areas." -- Computer Software Issues, an American Mathematical Association Prospectus, July 1965. (as quoted in P. J. Landin's classic paper "The Next 700 Programming Languages" from March 1966). From happybrowndog at hotmail.com Sun Jul 13 04:19:41 2008 From: happybrowndog at hotmail.com (happybrowndog) Date: Sun, 13 Jul 2008 01:19:41 -0700 Subject: Building a Python app with Mozilla In-Reply-To: <4686CC45.9010405@sweetapp.com> References: <46867432.7060400@codebykevin.com> <4686CC45.9010405@sweetapp.com> Message-ID: Is that why Komodo is so damned slow???? Brian Quinlan wrote: > Kevin Walzer wrote: >> Komodo is not a Python application. It is a Mozilla application that >> supports Python development. Komodo is more akin to Thunderbird and >> Firefox than anything else; it uses the XUL framework for rendering >> widgets, if I'm not mistaken. If you want to build an application like >> Komodo, get a book on developing with the Mozilla framework (XUL, XPCOM, >> and all that) and look at that. Python has little to do with that. > > Most application logic in Komodo is implemented in Python, using the > PyXPCOM bindings. The UI is implemented using XUL and JavaScript. The > editor is Scintilla (C++). > > ../Komodo Edit.app/Contents/MacOS % find . -name "*.py" | xargs wc > ... > ... > 126392 456858 4949602 total > > This doesn't include the python code in the Python libraries themselves. > > Cheers, > Brian > > From workitharder at gmail.com Mon Jul 14 00:16:38 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 13 Jul 2008 21:16:38 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> <792048c1-5e18-4a2c-925d-a1c932d18a91@j22g2000hsf.googlegroups.com> <8923d0c5-29ce-495f-924a-6d9d2457138e@e39g2000hsf.googlegroups.com> Message-ID: On Jul 13, 6:53 pm, Larry Bates wrote: > bearophileH... at lycos.com wrote: > > bukzor: > >> You need to use two dictionaries. Here's a class that someone's > >> written that wraps it up into a single dict-like object for you: > >>http://www.faqts.com/knowledge_base/view.phtml/aid/4376 > > > It contains code like: > > > try: > > del self.data[item] > > except KeyError: > > pass > > > Exceptions are useful in python, but with dictionaries this is > > probably faster (and shorter), even if it may perform two lookups: > > > if item in self.data: > > del self.data[item] > > > Bye, > > bearophile > > The only case where it would be faster would be if most of the keys were NOT in > the dictionary (rather odd use case). Otherwise I believe you will find the > first way quicker as the exceptions are infrequent. > > -Larry /agree From M8R-yfto6h at mailinator.com Fri Jul 25 11:07:25 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Fri, 25 Jul 2008 08:07:25 -0700 Subject: ctypes and reading value under pointer passed as param of a callback References: <6erjpeF88slmU1@mid.individual.net> Message-ID: "waldek" wrote in message news:deaeba30-c160-4e55-9049-43af27e96217 at u12g2000prd.googlegroups.com... > On Jul 24, 5:01 pm, Thomas Heller wrote: >> waldekschrieb: >> >> > Hi, >> >> > I'm using C dll with py module and wanna read value (buffer of bytes) >> > returned in py callback as parameter passed to dll function. >> >> The callback receives a pointer instance. You can dereference the >> pointer >> to read individual bytes in this way: >> print data[0], data[5], data[42] >> or use slicing to read a bunch of bytes: >> print data[0:42] >> >> So, you probably want something like this: >> >> > -------------------------------------------------- >> > def mycallback(data, size): >> > # how to read data buffer here ? >> >> print data[:size] >> >> > return 0 >> >> > cbfunc = CFUNCTYPE(c_int, POINTER(c_uint8), c_int) >> >> > mydll = cdll.somedll >> > mdll.foo(cbfunct) >> > --------------------------------------------------------------- >> >> > Question: How to get bytes from the buffer passed to mycallback ??? >> > Let's assume that the buffer consist of 4 bytes 4 bytes 8 bytes. >> >> > I tried unpack("ii8s", data[0]) and nothing. I tried different ctypes >> > passed to callback and nothing. >> >> Thomas > > Cool, works fine now. > > ... and how to convert a list of bytes to py string or int ?? > > i.e > data[:4] -> py int > data[4:8] -> py int > data[8:] -> py strng > > I tried unpack and unpack_from but the buff should be an string or > buffer not a list of bytes as data is. > > any suggestions? Try: cbfunc = CFUNCTYPE(c_int, c_char_p, c_int) ctypes understands c_char_p as a null-terminated character string and will pass a string to your callback instead of a list of ints. --Mark From deets at nospam.web.de Tue Jul 1 17:24:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 Jul 2008 23:24:02 +0200 Subject: Attribute reference design In-Reply-To: References: Message-ID: <6cvlk4F3s90U1@mid.uni-berlin.de> chamalulu schrieb: > Hello. > I think I'm aware of how attribute access is resolved in python. When > referencing a class instance attribute which is not defined in the > scope of the instance, Python looks for a class attribute with the > same name. (For assignment or deletion this is not the case, > thankfully.) > I've been trying to understand why? What is the reason behind, or > practical purpose of, this design decision? Anyone, please enlighten > me. How else would you resolve methods which are of course defined on the class but invoked through the instance? Diez From mail at timgolden.me.uk Wed Jul 30 09:24:16 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 30 Jul 2008 14:24:16 +0100 Subject: variable expansion with sqlite In-Reply-To: References: <489059DC.5090501@timgolden.me.uk> Message-ID: <48906B80.5040705@timgolden.me.uk> Gerhard H?ring wrote: > My code would probably look very similar. Btw you don't need to use > list() on an iterable to pass to executemany(). pysqlite's executemany() > accepts anything iterable (so generators work fine, too). Thanks for that. My finger-memory told me to do that, possibly because some *other* dbapi interface only accepts lists. Can't quite remember. I'm usually all in favour of non-crystallised iterators. > Also, with SQLite you can just skip data type definitions like > VARCHAR(200). They're ignored anyway. Heh. Once again, finger memory forced me to put *something* in there. I've been developing Enterprise databases for too long :) TJG From dwahler at gmail.com Tue Jul 22 00:24:01 2008 From: dwahler at gmail.com (David Wahler) Date: Mon, 21 Jul 2008 23:24:01 -0500 Subject: tail-rec decorator, well still blows the stack... In-Reply-To: References: Message-ID: On Mon, Jul 21, 2008 at 10:01 PM, ssecorp wrote: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 > > so I try it and when I run: > @Decorators.tail_recursion > def fibtr(n): > def fibt(a, b, n): > if n <= 1: > return b > else: > return fibt(b, a + b, n - 1) > if n == 0: > return 0 > else: > return fibt(0, 1, n); > > it still blows the stack. so what is the point? is it impossible to > get "real" tail-recursion in Python? Python does not perform tail-call elimination, and there are currently no plans to make it do so. See http://mail.python.org/pipermail/python-dev/2004-July/046171.html and the ensuing discussion for an explanation. From Samnsparky at gmail.com Sun Jul 13 11:33:27 2008 From: Samnsparky at gmail.com (Sparky) Date: Sun, 13 Jul 2008 08:33:27 -0700 (PDT) Subject: Newbie Threading Question Message-ID: It seems strange, but I can't find a list of operating systems which support / don't support threading in Python. Can anyone point me in the right direction? Thanks, Sam From circularfunc at gmail.com Sun Jul 27 11:26:14 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 27 Jul 2008 08:26:14 -0700 (PDT) Subject: Rant (was Re: x*x if x>10 References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3g8rF9gfj0U1@mid.uni-berlin.de> <6f3gmaF9moqsU1@mid.uni-berlin.de> Message-ID: <552dcd4f-a821-4ac1-b588-b3727cff1679@m45g2000hsb.googlegroups.com> I might be misunderstanding OP but: a+b+c+d+e is simple way of concatenating 5 lists... as a function that takes any amount of lists and concatenates them: def concat(*args): c = [] for elem in args: c += elem return c don't know if extend is faster or slower or the same as + : def concat(*args): c = [] for elem in args: c.extend(elem) return c I don't know of a built-in. From __peter__ at web.de Fri Jul 4 01:56:16 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Jul 2008 07:56:16 +0200 Subject: Singleton implementation problems References: Message-ID: Urizev wrote: > Hi everyone > > I have developed the singleton implementation. However I have found a > strange behaviour when using from different files. The code is > attached. > > Executing main > New singleton: > <__main__.Singleton instance at 0x2b98be474a70> > New singleton: > > I do not know why, but it creates two instances of the singleton. Does > anybody know why? Do you see it now I snipped the irrelevant output? The problem is the structure of your program. The myset module is imported twice by Python, once as "myset" and once as "__main__". Therefore you get two distinct MySet classes, and consequently two distinct MySet.__instance class attributes. Move the if __name__ == "__main__": ... statements into a separate module, e. g. main.py: import myset import member if __name__ == "__main__": print "Executing main" set1 = myset.MySet() set2 = myset.MySet() mbr1 = member.Member() mbr2 = member.Member() mbr3 = member.Member() Now main.py and member.py share the same instance of the myset module and should work as expected. Peter From bdesth.quelquechose at free.quelquepart.fr Tue Jul 22 11:58:32 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 22 Jul 2008 17:58:32 +0200 Subject: convert list of lists to list In-Reply-To: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> References: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> Message-ID: <4886039a$0$4459$426a34cc@news.free.fr> antar2 a ?crit : > Is there a way to convert list_of_listsA to list_of_listsB, where one > list in listof lists A is one element of listB? > > list_of_listsA: > [['klas*', '*', '*'], > ['mooi*', '*', '*', '*'], > ['koe'], > ['arm*', '*', '*(haar)'], > ['groei*', '*', '*', '*', '*']] > > listB: > ['klas* * *', 'mooi* * * *, 'koe', 'arm* * * (haar)', 'groei* * * * > *'] Your example doesn't match your description. Assuming the example is correct and the description incorrect: listB = [' '.join(sublist) for sublist in list_of_listsA] NB : totally irrelevant, but your naming convention sucks big time IMHO. From stef.mientki at gmail.com Wed Jul 23 04:58:39 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 23 Jul 2008 10:58:39 +0200 Subject: Is this possible .... Message-ID: <4886F2BF.9060709@gmail.com> hello, I'm looking for a way to remove duplicate code. The problem is this: In all my modules I've version information, containing version information, date, author, testconditions etc, something like this: Version_Text = [ [ 0.2, '10-02-2008', 'Stef Mientki', 'Test Conditions:', (1,2), _(0, """ - scaling and offset is set for each individual signal - Time history window for 1 signal with min/max display - set attributes for all signals at once """) ], [ 0.1, '04-11-2007', 'Stef Mientki', 'Test Conditions:', (1,), """ - orginal release """ ] ] Now I've made modules that can generate docs, a library manager, etc, and that even in different languages. But for the simple case I would like to have a simple function, which just displays the version number. So in each module, there is a function: def version () : return ( version_text [0] [0] ) But is there a way to avoid the placing of this function "version" in each module, and still use a simple call like: .version() thanks, Stef Mientki From kyosohma at gmail.com Mon Jul 28 09:09:56 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 28 Jul 2008 06:09:56 -0700 (PDT) Subject: how to upload files to "google code" filesection ? References: Message-ID: <7f6182a3-4504-4239-8239-673a7e4bfefd@s50g2000hsb.googlegroups.com> On Jul 26, 12:43?pm, Stef Mientki wrote: > hello, > > In a program I want to download (updated) files from google code (not > the svn section). > I could find a python script to upload files, > but not for downloading. > > Anyone has a hint or a solution ? > > thanks, > Stef Mientki You should be able to use urllib to do that. The following link has a recipe: http://code.activestate.com/recipes/496685/ If you need to search Google Code, there's an API that appears to be exposed through their gdata module. Mike From nytrokiss at gmail.com Tue Jul 22 13:52:48 2008 From: nytrokiss at gmail.com (James Matthews) Date: Tue, 22 Jul 2008 10:52:48 -0700 Subject: Hello,who can help me! In-Reply-To: <6elngkF7mgmfU1@mid.uni-berlin.de> References: <163330b8-8d0d-44c4-baf7-450bd42f8402@c65g2000hsa.googlegroups.com> <6elngkF7mgmfU1@mid.uni-berlin.de> Message-ID: <8a6b8e350807221052x48c75f3elf4a3cb5f2e755c6e@mail.gmail.com> I would recommended on asking on the pywin32 mailing list. On Tue, Jul 22, 2008 at 2:26 AM, Diez B. Roggisch wrote: > birdprince at gmail.com wrote: > > > I have implemented a C++ COM,which contains two interface in one > > coclass. > > when i use this COM in python: > > dll=win32com.client.Dispatch("XXXXX") > > then i can only call default interface's method,but can't call non > > default interface's method. > > who can tell me how to call non default interface's method. > > thank you very much! > > you can send the answer to my mailbox:birdprince at hotmail.com > > AFAIK win32com only supports IDispatch-based interfaces, not custom > interfaces. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.jewelerslounge.com http://www.goldwatches.com/mens/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Wed Jul 2 12:18:30 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 02 Jul 2008 17:18:30 +0100 Subject: Win32.client, DAO.DBEngine and exceeding the file sharing count lock In-Reply-To: <9ab0cc2d-5a7e-40ca-a4da-084347f147cd@m36g2000hse.googlegroups.com> References: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> <9ab0cc2d-5a7e-40ca-a4da-084347f147cd@m36g2000hse.googlegroups.com> Message-ID: <486BAA56.4070303@timgolden.me.uk> Iain King wrote: > On Jul 2, 3:29 pm, Tim Golden wrote: >> Iain King wrote: >>> Hi. I'm using the win32 module to access an Access database, but I'm >>> running into the File Sharing lock count as inhttp://support.microsoft.com/kb/815281 >>> The solution I'd like to use is the one where you can temporarily >>> override the setting using (if we were in VB): >>> DAO.DBEngine.SetOption dbmaxlocksperfile,15000 >> Really hurried answer: >> >> >> import win32com.client >> >> dao = win32com.client.gencache.EnsureDispatch ("DAO.DBEngine.36") >> dao.SetOption (Option=win32com.client.constants.dbMaxLocksPerFile, Value=15000) >> >> >> TJG > > Thanks. I found this: http://blogs.msdn.com/michkap/archive/2007/07/13/3849288.aspx > which outlines some difference between DAO and ADO, including: > "Capability to set and change Jet options without making registry > changes (works in DAO through DBEngine.GetOption and > DBEngine.SetOption, fails in ADO, which has no such analogue)." > > Now, I'm pretty sure I tried to use DAO before and failed to get it to > work, but maybe you could look at my code and suggest the DAO > equivalent? I'm afraid I don't have the relevant experience myself. I'm sure I could muddle through a few web pages and work it out (but I'm sure you could, too!) Sorry TJG > aTdHvAaNnKcSe, PS - Like the .sig From fetchinson at googlemail.com Wed Jul 9 20:24:36 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 9 Jul 2008 17:24:36 -0700 Subject: FOSS projects exhibiting clean/good OOP? In-Reply-To: <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> Message-ID: >> I'm wondering whether anyone can offer suggestions on FOSS projects/ >> apps which exhibit solid OO principles, clean code, good inline >> documentation, and sound design principles? > > This is somewhat subjective... Some would say that Python's object > model is fundamentally broken and crappy (not MHO, needless to say) > that Python + "solid OO principles" is antinomic !-) > > More seriously: > >> I'm devoting some time to reviewing other people's code to advance my >> skills. Its good to review bad code (of which I have more than enough >> examples) as well as good, but I'm lacking in finding good examples. >> >> Projects of varying sizes would be great. > > I'd recommand at least FormEncode and SQLAlchemy. I'd object calling FormEncode a well-designed project. The classic dilemma has not been dealt with very well: should the software be uber-flexible and hence complex or more rigid but simple. Ideally, this dilemma is solved by being uber-flexible but the user (meaning developers using the code) experience is kept simple by hiding the complexity from developers who don't want to know about them but exposing it to advanced developers who do want to know about them. IMHO FormEncode is not a good example of this. But PIL definitely is! Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From rubbishemail at web.de Tue Jul 1 10:06:12 2008 From: rubbishemail at web.de (rubbishemail at web.de) Date: Tue, 1 Jul 2008 07:06:12 -0700 (PDT) Subject: frame grabber hardware References: Message-ID: <462e0151-04ec-4c40-810b-ceece2815d79@y38g2000hsy.googlegroups.com> > Do you mean something like this? > > Easy Cap Audio-Video Capturing Adapter http://www.youtube.com/watch?v=3AvT8JQ7NzI this would be suitable, if it had a documented driver, some sites said it could only be used with the included software. many bad comments, though: http://forums.ebay.com/db1/thread.jspa?threadID=2000392978&start=40 I found this library http://videocapture.sourceforge.net/ which may be useful to others I will probably go for a TWAIN enabled grabber like http://www.zarbeco.com/usb_videolink.htm and use twainmodule.sourceforge.net/ An alternative would be to use directshow, which seems to be supported by many cameras: http://directpython.sourceforge.net/index.html thanks for your input Daniel From leodp at yahoo.com Tue Jul 1 01:59:58 2008 From: leodp at yahoo.com (leodp) Date: Mon, 30 Jun 2008 22:59:58 -0700 (PDT) Subject: Getting sorting order References: <7cb9ebb7-e722-41e1-bdf2-693954a21b92@j22g2000hsf.googlegroups.com> Message-ID: > >>> x=zip(master,slave1,slave2) > >>> x.sort() > >>> master,slave1,slave2=zip(*x) > --Mark So nice is Python. Leo From bj_666 at gmx.net Fri Jul 18 11:52:26 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Jul 2008 15:52:26 GMT Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> Message-ID: <6ebshqF67cpfU4@mid.uni-berlin.de> On Fri, 18 Jul 2008 07:39:38 -0700, nicolas.pourcelot wrote: > So, I use something like this in 'sheet.objects.__setattr__(self, > name, value)': > if type(value) == Polygon: > for edge in value.edges: > if edge is_in sheet.objects.__dict__.itervalues(): > object.__setattr__(self, self.__new_name(), edge) > > Ok, I suppose it's confused, but it's difficult to sum up. ;-) You are setting attributes with computed names? How do you access them? Always with `gettattr()` or via the `__dict__`? If the answer is yes, why don't you put the objects the into a dictionary instead of the extra redirection of an objects `__dict__`? Oh and the `type()` test smells like you are implementing polymorphism in a way that should be replaced by OOP techniques. Ciao, Marc 'BlackJack' Rintsch From subhabrata.iisc at hotmail.com Fri Jul 18 04:31:59 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Fri, 18 Jul 2008 01:31:59 -0700 (PDT) Subject: Question on Joining of list Message-ID: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> Dear Group, I am trying the following code line: def try2(n): a1=raw_input("PRINT A STRING:") a2=a1.split() a3="God Godess Heaven Sky" for x in a2: a4=a3.find(x) if a4>-1: a5=a3[a4] print a5 elif a4<0: a6=x print "It is not found" print a6 else: print "Error" s=a5+" "+a6 print s Here, if I put a string like: Petrol Helium Heaven Sky In s it is giving me S Helium But I am looking for an output of a5 and a6 concatenating all its values not the last ones. Can you suggest me any help? Am I missing any minor point? Best Regards, Subhabrata. From casevh at gmail.com Tue Jul 8 23:41:41 2008 From: casevh at gmail.com (casevh) Date: Tue, 8 Jul 2008 20:41:41 -0700 (PDT) Subject: numeric emulation and __pos__ References: Message-ID: On Jul 7, 4:12?pm, Ethan Furman wrote: > Greetings, List! > > I'm working on a numeric data type for measured values that will keep > track of and limit results to the number of significant digits > originally defined for the values in question. > > I am doing this primarily because I enjoy playing with numbers, and also > to get some experience with unit testing. > > At this point I have the __init__ portion finished, and am starting on > the various operator functions. > > Questions for the group: > > 1) Any reason to support the less common operators? > ? ? ? ? i.e. <<, >>, &, ^, | Assuming you are working with decimal numbers, the &, ^, | may not be of any use for your application. The shift operators may be useful but there are two possible ways to define their behavior: 1) Multiplication or division by powers of 2. This mimics the common use of those operators as used with binary numbers. 2) Multiplication or division by powers of 10. > > 2) What, exactly, does .__pos__() do? ?An example would help, too. The unary + operator is frequently added for symmetry with -, however it is also used to force an existing number to match a new precision setting. For example, using the decimal module: >>> from decimal import * >>> t=Decimal('1.23456') >>> t Decimal("1.23456") >>> getcontext().prec = 5 >>> +t Decimal("1.2346") > > Thanks for the feedback. > -- > Ethan casevh From dstromberglists at gmail.com Thu Jul 24 20:55:06 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Fri, 25 Jul 2008 00:55:06 GMT Subject: curses problem References: Message-ID: On Thu, 24 Jul 2008 21:28:24 +0200, Dariusz Malec wrote: > forgot to post the code. Server does not allow to post attachments. The > code is here http://www.kos.wsiz.rzeszow.pl/~dmalec/src.zip You might google about SIGWINCH and see where that gets you. Of course, to my great disappointment, python programs that use signals become quite a bit more complex than they should because you have to restart interrupted system calls explicitly. Please, someone fix this! IMO, python functions and methods that could be be interrupted by a signal should restart themselves by default, and have an option to allow them to require themselves to be interrupted. Many Kernel programmers have negative perspectives on application programmers who don't bother this; python seems to have a significant culture of ignoring the issue. This makes me sad. I love python. I want it to do better. From martin at see_sig_for_address.invalid Tue Jul 22 05:21:50 2008 From: martin at see_sig_for_address.invalid (Martin Gregorie) Date: Tue, 22 Jul 2008 10:21:50 +0100 Subject: The Importance of Terminology's Quality References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: On Tue, 24 Jun 2008 18:42:15 -0400, John W Kennedy wrote: > David Combs wrote: >> passing >> *unnamed* functions as args (could Algol 60 also do something like that, >> via something it maybe termed a "thunk") > > No, the "thunks" were necessary at the machine-language level to > /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. > Are you sure about that? The first time I ran across the term "thunking" was when Windows 3 introduced the Win32S shim and hence the need to switch addressing between 16 bit and 32 bit modes across call interfaces. That was called "thunking" by Microsoft and even they would surely admit it was a kludge. I used Algol 60 on an Elliott 503 and the ICL 1900 series back when it was a current language. The term "thunking" did not appear in either compiler manual nor in any Algol 60 language definition I've seen. A60 could pass values by name or value and procedures by name. That was it. Call by name is what is now referred to as reference passing. I should also point out that Algol 60 was initially written as a means for communicating algorithms between people. Compiler implementations came later. In consequence the language did not define links to libraries or i/o methods. Both features were compiler specific - for instance the Elliott introduced 'input' and 'print' reserved words and syntax while the 1900 compilers used function calls. The Elliott approach was more readable. Algol 60 did not have 'functions'. It had procedures which could be declared to return values or not. A procedure that returned a value was equivalent to a function but the term 'function' was not used. Similarly it did not have a mechanism for declaring anonymous procedures. That, like the incorporation of machine code inserts, would have been a compiler-specific extension, so it is a terminological mistake to refer to it without specifying the implementing compiler. -- martin@ | Martin Gregorie gregorie. | org | Zappa fan & glider pilot From paul.hankin at gmail.com Mon Jul 7 17:22:47 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Mon, 7 Jul 2008 14:22:47 -0700 (PDT) Subject: The Yield statement References: <95354739-b4ba-47cb-b2c3-437365cc986b@z72g2000hsb.googlegroups.com> Message-ID: <1c979f9d-ba53-4af2-ad58-bcdcdc98778f@e53g2000hsa.googlegroups.com> On Jul 1, 12:45?am, Mensanator wrote: > Here's an example. > ... > def partition_generator(depth,width): > ? """creates all partions of a given depth,widtth (depth>=width) > ? depth objects in width bins such that each bin has at least 1 object > ? this function is a generator (does comb(depth-1,width-1) partitions) > > ? partition_generator(depth,width) > ? depth: ?total inverse rule 1 count (p of 2**p) > ? width: ?total inverse rule 2 count (q of 3**q) > ? sv: ? ? sequence vector (the partition) > ? returns sequence vector [sv] > ? """ > ? def move_col(c): > ? ? sv[c-1] += 1 > ? ? sv[c] -= 1 > ? def find_c(): > ? ? i = -1 > ? ? while i<0: > ? ? ? if sv[i]>1: > ? ? ? ? return i > ? ? ? i -= 1 > ? def rollover(c): > ? ? move_col(c) > ? ? sv[-1] = sv[c] > ? ? sv[c] = 1 > ? if depth ? ? print 'depth',depth,'must be >= to width',width > ? ? return ? ? ? ? ? ? ? ? ? ? ? # kills generator > ? max_element = depth - width + 1 > ? sv = [1 for i in range(width)] > ? sv[-1] = max_element > ? yield sv[:] ? ? ? ? ? ? ? ? ? ?# first partition > ? while sv[0] ? ? c = find_c() > ? ? if c < -1: > ? ? ? rollover(c) > ? ? ? yield sv[:] ? # must yield copy of sv, not sv > ? ? else: > ? ? ? move_col(c) > ? ? ? yield sv[:] It's just an example I know, but you can write this much more cleanly... def partitions(n, length): """Generate all sequences of positive numbers of the given length that sum to n.""" assert 0 < length <= n if length == 1: yield [n] return for i in xrange(1, n + 2 - length): for p in partitions(n - i, length - 1): yield [i] + p -- Paul Hankin From pavlovevidence at gmail.com Tue Jul 29 16:53:07 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 13:53:07 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> Message-ID: On Jul 29, 4:08 pm, Erik Max Francis wrote: > Carl Banks wrote: > > On Jul 29, 1:30 pm, Carl Banks wrote: > >> On Jul 29, 5:15 am, Heiko Wundram wrote: > > >>> I can't dig up a simple example from code I wrote quickly, but because of the > >>> fact that explicit comparisons always hamper polymorphism > >> I'm not going to take your word for it. Do you have code that > >> demonstrates how "if x" improves polymorphism relative to simple > >> explicit tests? > > > And, in case it wasn't obvious, the way to demonstrate that "if x" > > improves polymorphism relative to simple explicit tests would be > > posting an example where "if x" works but a simple explicit test > > doesn't. So don't accuse me of changing the question on you: it's the > > same question. > > It's pretty elementary, and people thought just describing the issue of > polymorphism and duck-typing was sufficient to explain it. Since it > apparently isn't: > > Let's say you come up with some kind of custom sequence class. You want > to act like any native sequence type (list, tuple, array, string, etc.) > in all reasonable ways (length testing, iteration, indexing, etc.) so > that it can be used in place of these things in code that doesn't > require explicit types. You know, standard polymorphism and duck-typing. > > So you want a test for whether your custom sequence isn't empty. To > create an "simple, explicit test" would be defined an `isntEmpty` method > that you can call, like so: > > if myObject.isntEmpty(): > # then do something > > However, this wouldn't be polymorphic since now someone would have to > call a "simple, explicit test" that doesn't exist on all the other > sequence-like objects. Therefore, you've broken polymorphism. > > The solution is to override the `__nonzero__` method so that you can use > Boolean testing, just like all the other sequence-like objects: > > if myObject: > # then do the same thing > > Now people who use your custom sequence type don't have to write special > code, and code written to deal with sequences using duck typing (which > is typically nearly all Python code) don't have to know anything special > about your custom sequence class. Bzzt. "if len(x)!=0" is a simple explicit that would work for this class and all built-in containers. (Or should--Steven D'Aprano's objections notwithstanding, any reasonable container type should support this invariant. From a language design standpoint, an "empty" builtin could have been created to simplify this even more, but since there isn't one len(x)!=0 will have to do.) Let me reframe the question to see if we can make some headway. The vast majority of true/false tests fit into one of the following four categories: 1. Testing the explicit result of a boolean operation (obviously) 2. Testing whether a numeric type is nonzero. 3. Testing whether a container type is empty. 4. Testing whether you have a (non-numeric, non-container) object of some sort, or None. There's a few other cases, but let's start with these to keep things simple and add other cases as necessary. We already know that cases 2, 3, and 4 can, individually, be converted to a simple explicit test (using x!=0, len(x)!=0, and x is not None, respectively). As long as you know which kind of object you're expecting, you can convert the implicit to an explicit test. Now, you guys keep whining "But what if you don't know what kind of object you're expecting?!!" It's a fair question, and my belief is that, in practice, this almost never happens. Duck typing happens between numeric types often, and between container types often, but almost never between both numeric and container types. Their usages are simply too different. So I present another question to you: Give me an useful, non-trivial, example of some code that where x could be either a numeric or container type. That would be the first step to finding a counterexample. (The next step would be to show that it's useful to use "if x" in such a context.) Once again, I'm invoking the contraint against simply using x in a boolean context, or passing x to a function expecting a boolean doesn't count, since in those cases x can be set to the result of the explicit test. So none of this: def nand(a,b): return not (a and b) Or anything trivial like this: def add(a,b): return a+b Carl Banks From castironpi at gmail.com Sun Jul 27 01:20:21 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 26 Jul 2008 22:20:21 -0700 (PDT) Subject: Insert character at a fixed position of lines References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> <7895c8b2-fa01-483c-8ba9-d90975ea688d@o40g2000prn.googlegroups.com> <8b0f4fe2-d8ab-4230-9032-ccd02878d349@v39g2000pro.googlegroups.com> Message-ID: On Jul 26, 10:02?pm, alex23 wrote: > Ugh, and in pointing our your inaccurate code I posted my own: > > > >>> f = open('dummy.txt','w') > > >>> f.write(line = 'this doesn't work') > > > ? File "", line 1 > > ? ? f.write(line = 'this doesn't work') > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?^ > > SyntaxError: invalid syntax > > That should be: > > >>> f.write(line = "this doesn't work") > > Traceback (most recent call last): > ? File "", line 1, in > TypeError: write() takes no keyword arguments > > Sorry about that :) This is close. import os size= os.path.getsize( 'test line_insertion.txt' ) f= open( 'test line_insertion.txt', 'r+' ) linelen= len( f.readline( ) ) f.seek( 20, os.SEEK_SET ) while f.tell( )< size: f.write( 'y' ) f.seek( linelen, os.SEEK_CUR ) f.flush( ) f.close( ) It assumes lines are a constant length (big assumption), and skips one line's length of characters starting from the 20th character. It repeats until current file position is past the original length of the file. From timr at probo.com Wed Jul 23 00:42:41 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 23 Jul 2008 04:42:41 GMT Subject: Python Written in C? References: Message-ID: Larry Bates wrote: > >I just learned something I did not know. I was under the impression that they >translated directly to machine code without ever actually generating Assembler >text files. Some do, some don't. It's an implementation chioce. gcc generates a text file and pipes it to gas. The __asm__ directive just adds strings to the assembler file. Visual C++ generates machine language. The compiler has to include an assembler for inline assembly. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ojeeves at gmail.com Mon Jul 21 07:08:05 2008 From: ojeeves at gmail.com (oj) Date: Mon, 21 Jul 2008 04:08:05 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> <7574170c-ea58-48a5-83b0-0cd909f07d06@k37g2000hsf.googlegroups.com> Message-ID: On Jul 21, 11:04?am, Fredrik Lundh wrote: > The drawback is that it's a lot easier to mess up the edge cases if you > do that (as this thread has shown). ?The small speedup you get in > typical cases is quickly offset by extra debugging/testing time (or, for > that matter, arguing with c.l.py:ers over more or less contrived ways to > interpret the original post). I disagree, from this thread, most of the erroneous solutions have been attempts to match the entire string. > Guess it's up to personal preferences for how to best help others. > Unless the OP explicitly asks for something else, I prefer to use simple > and straight-forward solutions with reasonable execution behaviour over > clever tricks or odd-ball solutions; it's not a JAPH contest, after all. [^LRM] *is* a simple and straight-forward regex - it isn't attempting to do any clever tricks or anything odd-ball. That said, I still think the sets solution is more elegant then the regex solutions. From grante at visi.com Mon Jul 28 10:18:03 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 28 Jul 2008 09:18:03 -0500 Subject: os.symlink() References: Message-ID: On 2008-07-28, Nikolaus Rath wrote: > Hello, > >>From `pydoc os`: > > symlink(...) > symlink(src, dst) > > Create a symbolic link pointing to src named dst. > > > Is there any reason why this is so deliberately confusing? Why is the > target of the symlink, the think where it points *to*, called the > `src`? It seems to me that the names of the parameters should be > reversed. I never looked at the names of the parameters. I just know that they're in the same order as they are when you do "ln -s" at a shell prompt. It's like you're copying a file (except the new one isn't really a copy, it's a link). -- Grant Edwards grante Yow! PEGGY FLEMMING is at stealing BASKET BALLS to visi.com feed the babies in VERMONT. From grflanagan at gmail.com Fri Jul 18 10:14:49 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Fri, 18 Jul 2008 16:14:49 +0200 Subject: Regular expression help In-Reply-To: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> References: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> Message-ID: nclbndk759 at googlemail.com wrote: > Hello, > > I am new to Python, with a background in scientific computing. I'm > trying to write a script that will take a file with lines like > > c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647 > 3pv=0 > > extract the values of afrac and etot and plot them. I'm really > struggling with getting the values of efrac and etot. So far I have > come up with (small snippet of script just to get the energy, etot): > > def get_data_points(filename): > file = open(filename,'r') > data_points = [] > while 1: > line = file.readline() > if not line: break > energy = get_total_energy(line) > data_points.append(energy) > return data_points > > def get_total_energy(line): > rawstr = r"""(?P.*?)=(?P.*?)\s""" > p = re.compile(rawstr) > return p.match(line,5) > > What is being stored in energy is '<_sre.SRE_Match object at > 0x2a955e4ed0>', not '-11.020107'. Why? 1. Consider using the 'split' method on each line rather than regexes 2. In your code you are compiling the regex for every line in the file, you should lift it out of the 'get_total-energy' function so that the compilation is only done once. 3. A Match object has a 'groups' function which is what you need to retrieve the data 4. Also look at the findall method: data = 'c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647 3pv=0 ' import re rx = re.compile(r'(\w+)=(\S+)') data = dict(rx.findall(data)) print data hth G. From circularfunc at gmail.com Sat Jul 12 15:59:20 2008 From: circularfunc at gmail.com (ssecorp) Date: Sat, 12 Jul 2008 12:59:20 -0700 (PDT) Subject: why is "self" used in OO-Python? References: Message-ID: On Jul 12, 8:44?pm, castironpi wrote: > On Jul 12, 1:01?pm, Duncan Booth wrote: > > > > > ssecorp wrote: > > > 1. Why do I have to pass self into every method in a class? Since I am > > > always doing why cant this be automated or abstracted away? > > > Are the instances where I won't pass self? > > > I imagine there is some tradeoff involved otherwise it would have been > > > done away with. > > > When you define a method in Java there is an implicit 'this' passed to the > > method. Python cannot tell when you define a function whether the function > > is going to be used as a function, an instance method, a class method, a > > static method or something else (or all of the above). Consider this: > > > The dynamic nature of Python means you can lift a method out of a class and > > re-use it in a different context or inject a function into a class as a > > method. There are two ways to handle this sort of code: javascript has an > > implied 'this' for everything whether a function or what passes for a > > method, Python makes it explicit. > > > > 2. self.item instead of getters and setters. I thought one of the main > > > purposes of OO was encapsulation. Doesn't messing with internal object- > > > representations break this? > > > That is correct. Some languages (e.g. Java) don't allow you to encapsulate > > attributes so you have to write getter and setter methods. If you expose an > > attribute in Java then you cannot later insert some code into the lookup or > > override the set without getting all users of your code to change the way > > they access the value. This is bad. > > > Other languages (e.g. Python, C#) allow you to intercept the attribute > > lookup so you can change a plain attribute into a property without > > requiring the users of your class alter their source code. With C# I > > think they would still need to recompile their code so it may be more > > appropriate to avoid using public attributes if you are producing a class > > library for widespread reuse, but with Python there is no difference to the > > user of your class whether they are accessing an attribute or a property. > > > Sadly a lot of Java programmers mistake the limitations of their language > > for rules of OO programming, and worse this has spread from Java into other > > languages where these restrictions no longer need apply. > > > Your Stack class is a bad example: the stack attribute is purely internal > > so you wouldn't want to expose it as part of the public interface. Consider > > instead something like: > > > class AddressBookEntry(object): > > ? ? def __init__(self, name, phone): > > ? ? ? ? self.name = name > > ? ? ? ? self.phone = phone > > > ? ? @property > > ? ? def phone(self): > > ? ? ? ? return self._phone > > > ? ? @property.setter > > ? ? def phone(self, number) > > ? ? ? ? validatephonenumber(number) # may throw an exception > > ? ? ? ? ? self._phone = number > > > If later you want to add some processing to the name attribute it is easy, > > but putting in dummy property getter/setter methods before you need them > > would be pointless. > > Part of the value of accessor methods appears when you're changing > class definitions, or changing classes, after you've already started > to use them-- the same interface with a different implementation. > > In the AddressBookEntry example, if you changed a pickled dictionary > to a shelf, you could reimplement the class and reprocess stored data > files, all without changing the code that uses the class-- especially > if there's a lot of it, or you don't know where it all is. > > Nothing stops you from using accessor methods to offer encapsulation, > and permit back-end changes later. ?But, nothing in Java stops you > from declaring class members public. > > Depending on your development process, data hiding may enforce > distribution of labor a little better, resulting in errors in Java > where Python relies only on discipline. ?If you're checking for value > validation, you can write a custom setter, regardless of language. > > Python doesn't break encapsulation; you do. > > In the Stack example, you have more options than you've mentioned. > Can you inherit from list directly? ?Can you delegate using > reflection? ?Are you studying this example specifically, or the class > model generally? ?If you're choosing a language, be careful that > stricter enforcement doesn't cause harder-to-find bugs. > > Useful link: Section 9.4 in the docs:http://docs.python.org/tut/node11.html ty for all the answers. Im not saying either is better Im just trying to fiugre out the philosophies behind each language and their respective pros and cons. and self is apparently not a reserved word so I could replace it with "blahaba". But basically Python trusts the programmer and relies on conventions rather than enforcements like Java does. From jiri.zahradil at gmail.com Sat Jul 5 09:28:42 2008 From: jiri.zahradil at gmail.com (jiri.zahradil at gmail.com) Date: Sat, 5 Jul 2008 06:28:42 -0700 (PDT) Subject: Python with Ecmascript Message-ID: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> Hello, for my Python application (Windows platform) to be standards compliant, I need to embbed Ecmascript(Javascript) interpreter - I need to execute plugins written in this language. Which engine is suitable for Python, I have found bunch of them. Any recomendations are welcome. To be more specific, I think that plugins will be pretty simple, they will be used to manipulate my class-based datamodel, no special libraries dependencies ... therefore I prefer some rather simple solution ... Jiri From tim.tadh at gmail.com Tue Jul 29 11:18:48 2008 From: tim.tadh at gmail.com (Tim Henderson) Date: Tue, 29 Jul 2008 08:18:48 -0700 (PDT) Subject: Overloaded Functions Message-ID: <3070b5ff-0914-4109-841a-ee622e4105a5@27g2000hsf.googlegroups.com> Hi, So this may have been asked before but i haven't found the answer by googling so far. My situation is this: I want this structure for my code: @overloaded def sign_auth(secret, salt, auth_normalized): return __sign_auth(saltedhash_bin(secret, salt), auth_normalized) @sign_auth.register(str, str) def sign_auth(secret_hash_normalized, auth_normalized): return __sign_auth(qcrypt.denormalize(secret_hash_normalized), auth_normalized) def __sign_auth(secret_hash_bin, auth_normalized): auth = qcrypt.denormalize(auth_normalized) aes = AES.new(secret_hash_bin, AES.MODE_CBC) plaintext = aes.decrypt(auth) ciphertext = qcrypt.normalize(xor_in_pi(plaintext)) if debug: print '\n------sign_auth------' print qcrypt.normalize(secret_hash_bin) print qcrypt.normalize(plaintext) print ciphertext print '-----sign_auth-------\n' return ciphertext I am using the overloading module from: http://svn.python.org/view/sandbox/trunk/overload/overloading.py?rev=43727&view=log However it doesn't actually support this functionality. Does any one know of a decorator that does this? It would be really nice to have a unified interface into the __sign_auth function for the two different use cases. Tim Henderson From pdorange at pas-de-pub-merci.mac.com Wed Jul 2 10:09:07 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Wed, 2 Jul 2008 16:09:07 +0200 Subject: Trouble using pinckle Message-ID: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> Hello, I'm new to python and i'm deelopping a small game with pygame. I got lot of fun with python. Trying to implement a config file to save user score and config. Reading doc and some tutorial about file handling i read about pickle, and yes it's very easy to implement. But i thought i miss something with the roots of python. I implement a Prefs class to handle config data and add it a load and save method. It works but when reading self, it OK inside the load function but outside the pref instance return to it's previus state... I don't really understand. Here's the test code : #!/usr/bin/env python import os, pickle kFileName='test.ini' class Prefs(): def __init__(self): self.test=1 self.zorglub='bonjour' def load(self): if os.path.exists(kFileName): try: print 'test %d (before)' % self.test f=open(kFileName,'r') self=pickle.load(f) f.close() print 'test %d (after)' % self.test except IOError: return 1 return 0 def save(self): f=open(kFileName,'w') pickle.dump(self,f) f.close() return 0 def main(): p=Prefs() p.load() print 'test %d (after load)' % p.test p.test+=1 print 'test %d (before save)' % p.test p.save() print '----------------------' if __name__ == '__main__': main() -- Pierre-Alain Dorange Vid?o, DV et QuickTime Clarus, the DogCow From babacity4 at gmail.com Thu Jul 24 16:52:04 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:52:04 -0700 (PDT) Subject: sextv1 tv com - Amazing porn video collection Message-ID: <301d6d18-833c-45d1-bd13-a2ea5b334fe8@z11g2000prl.googlegroups.com> sextv1 tv com . >>>>>>>>>>Best Collection of Sextv1 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE sextv1 tv com VIDEOS<<<<<<<<<<< . sextv1 tv com From darcy at druid.net Sat Jul 12 09:57:44 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 12 Jul 2008 09:57:44 -0400 Subject: Confused In-Reply-To: <000001c8e417$c2b5bc50$0a01a8c0@HOMEPC> References: <000001c8e417$c2b5bc50$0a01a8c0@HOMEPC> Message-ID: <20080712095744.f69818f8.darcy@druid.net> On Sat, 12 Jul 2008 14:06:37 +0200 "eric.butteriss" wrote: > Please tell me why may mail is being returned. The message says I have been blacklisted...for what reason? I never open mail that I know is not expected and I never send junk or spam. I am trying to send important info to my cousin. Well, the subject is accurate anyway. The problem is that sometimes error messages can be misleading. In this case the problem appears that you have arrived too late and the Internet is full. Please turn off your computer and go outside. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From PengYu.UT at gmail.com Tue Jul 15 23:40:31 2008 From: PengYu.UT at gmail.com (Peng Yu) Date: Tue, 15 Jul 2008 20:40:31 -0700 (PDT) Subject: how to match whole word Message-ID: Hi, The following code snippet is from /usr/bin/rpl. I would like the it to match a word, for example, "abc" in ":abc:". But the current one would not match "abc" in ":abc:". I tried to modify it myself. Would you please let me know what is the corrected way to do it? Thanks, Peng if opts.whole_words: regex = re.compile(r"(?:(?<=\s)|^)" + re.escape(old_str) + r"(?=\s| $)", opts.ignore_case and re.I or 0) From 5lvqbwl02 at sneakemail.com Sat Jul 26 18:22:11 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Sat, 26 Jul 2008 15:22:11 -0700 (PDT) Subject: wx.Timer not working References: <7a2a1c54-6d74-475c-9566-4d94cb5b5962@a3g2000prm.googlegroups.com> Message-ID: On Jul 26, 3:13?pm, Mike Driscoll wrote: > On Jul 26, 2:33?pm, 5lvqbw... at sneakemail.com wrote: > > > > > Windows XP SP3 > > Python 2.5 > > wx.version() = '2.8.1.1 (msw-unicode)' > > ------ > > I have written the following *simplest* implementation of wx.timer I > > can think of. ?No workie. ? I want an exception, a print statement, or > > something. > > > The wxpython demos all work, but for some reason this isn't. ?The > > demos are simple and straghtforward, so I think I understand how it > > should work. ?Clues please? ?I've tried variations of ID's, SetOwners, > > using and redefining Notify(), Bind, Connect, etc. ?In the cases where > > the interpreter doesn't complain about passed argument types, the > > callback function is never called. > > > import wx > > > class MyFrame(wx.Frame): > > ? ? ? ? def __init__(self, parent, id, title): > > ? ? ? ? ? ? ? ? wx.Frame.__init__(self, parent, id, ? ? title, pos=(100, 100)) > > > ? ? ? ? ? ? ? ? timer = wx.Timer(self, -1) > > ? ? ? ? ? ? ? ? self.Bind(wx.EVT_TIMER, self.OnTick, timer) > > ? ? ? ? ? ? ? ? timer.Start(100) > > > ? ? ? ? def OnTick(self, event): > > ? ? ? ? ? ? ? ? print 'Hi. Bye.' > > ? ? ? ? ? ? ? ? 1/0 #<-- should crash as evidence callback is being called > > > class MyApp(wx.App): > > ? ? ? ? def OnInit(self): > > ? ? ? ? ? ? ? ? frame1 = MyFrame(None, wx.ID_ANY, "This is a test") > > ? ? ? ? ? ? ? ? frame1.Show(True) > > ? ? ? ? ? ? ? ? return True > > > app ? ? = MyApp(0) > > app.MainLoop() > > > Thanks for any advice!! > > > Michael > > I'm not seeing anything either. Please post this to the wxPython > user's group for additional help: > > http://www.wxpython.org/maillist.php > > Mike I think I figured it out. By looking at the wxTimer example here: http://wiki.wxpython.org/AnotherTutorial#head-420329f7c159d81cb03a6dd226ddb822ea296c92 My code created a temporary timer object and did not make it a class member. When I changed it to be a class member with self.timer, then it worked. thanks Michael From karthikbalaguru79 at gmail.com Wed Jul 23 02:38:14 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Tue, 22 Jul 2008 23:38:14 -0700 (PDT) Subject: tkinter for my python program !! References: <6em5snF7r22oU3@mid.uni-berlin.de> <63ff0b6f-8c75-4172-b836-8497870544ca@s50g2000hsb.googlegroups.com> <6em86gF7q9djU1@mid.uni-berlin.de> Message-ID: <81554f58-cc9c-4649-afdd-45656ab0bf64@b2g2000prf.googlegroups.com> On Jul 22, 7:11 pm, "Diez B. Roggisch" wrote: > karthikbalaguru wrote: > > On Jul 22, 6:32 pm, "Diez B. Roggisch" wrote: > >> karthikbalaguru wrote: > >> > Hi, > > >> > One of my python program needs tkinter to be installed to run > >> > successfully. > >> > I am using Redhat 9.0 and hence tried installing by copying the > >> > tkinter-2.2.2-36.i386.rpm > >> > alone from the CD 3 to my pc. But, it is not getting installed and is > >> > failing by throwing > >> > the below errors. Should i need to configure / install any specific > >> > files for resolving this issue ? > > >> > [root at localhost karthik]# rpm -ivh tkinter-2.2.2-26.i386.rpm > >> > warning: tkinter-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, > >> > key ID db42a > >> > 60e > >> > error: Failed dependencies: > >> > libtcl8.3.so is needed by tkinter-2.2.2-26.i386 > >> > libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 > >> > libtk8.3.so is needed by tkinter-2.2.2-26.i386 > > >> > Any ideas ? > > >> Yes: you should consider reading error-messages. What does > > >> error: Failed dependencies: > >> libtcl8.3.so is needed by tkinter-2.2.2-26.i386 > >> libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 > >> libtk8.3.so is needed by tkinter-2.2.2-26.i386 > > >> look like for you? > > >> Small hint: if you install something that depends on something else, you > >> need to .... the missing dependency first. Fill in the dots... > > > I find that it needs python-2.2.2-26.i386 and hence i tried installing > > python and i > > land here :( :( > > > [root at localhost karthik]# rpm -ivh python-2.2.2-26.i386.rpm > > warning: python-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key > > ID db42a60e > > error: Failed dependencies: > > libdb-4.0.so is needed by python-2.2.2-26.i386 > > python < 2.4.3-18.fc6 conflicts with python- > > devel-2.4.3-18.fc6.i386 > > [root at localhost karthik]# > > > I find that python 2.4.3-18.fc6 is being used by many of applications. > > But, the program i am trying to run needs python-2.2.2-26. > > So, how to resolve this issue ? > > Are you *sure* it requires python2.2? If yes, why can't fedora install > several python versions together? Ubuntu for sure can. But Python2.2 is > *ancient* - you might need to compile it yourself. > I did the following to resolve the errors, many errors got resolved, but finally the python program is breaking with different error. I got the below errors when i invoked the python program - [root at localhost processor]# Analyzer The python module Tkinter is not installed properly. Tkinter is required for this program. Redhat 9 You need tkinter-2.2.2-26. This can be found on the Redhat install CD 3 $ rpm -i /mnt/cdrom/RedHat/RPMS/tkinter-2.2.2-26.i386.rpm When i tried to install tkinter, i got the below errors - [root at localhost karthik]# rpm -ivh tkinter-2.2.2-26.i386.rpm warning: tkinter-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key ID db42a60e error: Failed dependencies: libtcl8.3.so is needed by tkinter-2.2.2-26.i386 libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 libtk8.3.so is needed by tkinter-2.2.2-26.i386 To resolve the conflicts and bring up the python program. I did the following - I downloaded python-devel-2.2.2-26.i386.rpm & python-2.2.2-26.i386.rpm. [root at localhost karthik]# rpm -e --nodeps python- devel-2.4.3-18.fc6.i386 [root at localhost karthik]# rpm -e --nodeps python-2.4.3-18.fc6 [root at localhost karthik]# rpm -ivh python-devel-2.2.2-26.i386.rpm warning: python-devel-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key ID db42a60e Preparing... ########################################### [100%] 1:python-devel ########################################### [100%] [root at localhost karthik]# rpm -ivh python-2.2.2-26.i386.rpm warning: python-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key ID db42a60e error: Failed dependencies: libdb-4.0.so is needed by python-2.2.2-26.i386 To resolve the above dependency error , i downloaded db4-4.0.14-20.i386.rpm But, i got the below errors while installing - [root at localhost karthik]# rpm -ivh db4-4.0.14-20.i386.rpm warning: db4-4.0.14-20.i386.rpm: Header V3 DSA signature: NOKEY, key ID db42a60e Preparing... ########################################### [100%] package db4-4.3.29-9.fc6 (which is newer than db4-4.0.14-20) is already installed To resolve the above error i did the following - [root at localhost karthik]# rpm -e --nodeps db4-4.3.29-9.fc6.i386 [root at localhost karthik]# rpm -ivh db4-4.0.14-20.i386.rpm warning: db4-4.0.14-20.i386.rpm: Header V3 DSA signature: NOKEY, key ID db42a60e Preparing... ########################################### [100%] 1:db4 ########################################### [100%] Now, i did the python-2.2.2-26.i386 installation. [root at localhost karthik]# rpm -ivh python-2.2.2-26.i386.rpm warning: python-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key ID db42a60e Preparing... ########################################### [100%] 1:python ########################################### [100%] As you would have noticed i linux spitted warning messages during installations of various packages. But, i wonder why i get the warnings and will those warnings affect the working of python based programs ? Further, finally when i invoke the python program by giving the necessary input file, i get the following errors . Does it have any relation with the python version installed ? [root at localhost processor]# Analyzer processorcycle /usr/local/SDK/bin/../core/bin/processorlib.py:8 8: Warning: 'yield' will become a reserved keyword in the future Traceback (most recent call last): File "/usr/local/SDK/bin/Analyzer", line 48, in ? from debuglib import ProcessorInfo File "/usr/local/SDK/bin/../core/bin/processorlib.py", line 88 yield ProcessorObjectInfo(child, self.pt) ^ SyntaxError: invalid syntax Any ideas ? Thx in advans, Karthik Balaguru From kinokunya at gmail.com Mon Jul 14 22:17:49 2008 From: kinokunya at gmail.com (Kinokunya) Date: Mon, 14 Jul 2008 19:17:49 -0700 (PDT) Subject: Need help in writing up a Python Syntax checker References: <57817302-0aca-4cb5-9559-7af6b5bc9d4d@l42g2000hsc.googlegroups.com> Message-ID: <3cd37e84-73f3-4623-a09f-74a743e92b2e@m3g2000hsc.googlegroups.com> On Jul 14, 6:48 pm, Kay Schluehr wrote: > On 14 Jul., 08:22, Kinokunya wrote: > > > Hi guys, > > > My group and I will be working on our final year project, the scope to > > do a program/web-based application similar areas of functionalities > > like the PyLint and PyChecker; a Python syntax checker. We have no > > Python background, equipped only with some knowledge of Java and Dot > > net. > > Python doesn't need a syntax checker. Syntax is checked by the parser > and the parser is exposed to the user by means of the parser module. > What you probably mean are *semantical* checks which are typical for > compilers: e.g. whether names are used with prior assignments of > values that cause runtime exceptions. These issues are in fact covered > by PyLint and PyChecker. > > > We did some research on PyLint and found out that there are 2 common > > modules that PyLint & PyChecker are using, namely logilab-astng and > > logilab-common. I'm not really sure what these 2 modules are for. > > > Quoted from the offical site, > > > The aim of this module (logilab-astng) is to provide a common base > > representation of python source code > > > We're not really sure what they meant by common base representation of > > source codes. > > Just switch to \Scripts\ in your Vista installation > > and type `easy_install pylint`. This shall install PyLint in the > directory > > \lib\site-packages > > Additionally a pylint.bat file is placed in the \Scripts > \ directory. > > Type `pylint --help` and you get more information about the > functionality of PyLint. Thanks for replying Kay Schluehr, The topic of our project was to do a program/software similar to PyLint and PyChecker, and the project scope does not require us to compile the codes. I guess by that it means 'semantic' checks in this case. Does that means we can make use of the parser module as mentioned above for semantic syntax checking? Our situation now is that we are torn between the programming languages to go, Java, Jython or Python, with no definite direction to start off our development. Any pointers would be appreciated. Thank you. From bignose+hates-spam at benfinney.id.au Thu Jul 3 01:16:35 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 03 Jul 2008 15:16:35 +1000 Subject: Times where one would use new style classes vs classic classes References: <6700e4ba-8573-44da-b75a-3b3e5ba1fd9b@i36g2000prf.googlegroups.com> Message-ID: <87skur4kek.fsf@benfinney.id.au> Quek writes: > I'd really like to know in the current context of Python 2.5, > besides in the cases of multi-inheritance, where would I use new > style classes? Is it a norm to use more new style classes even if I > don't have multi-inheritance in the industry, open source projects, > etc today? Yes, it's the norm to use new-style classes. This makes one's classes part of the Python type hierarchy, allowing features such as 'super', 'property', etc. to work correctly. Use new-style classes for any new code you create. Old-style classes are deprecated in Python 2.5 (even earlier than that I believe), and will be removed in Python 3.0 . -- \ ?Good judgement comes from experience. Experience comes from | `\ bad judgement.? ?Frederick P. Brooks | _o__) | Ben Finney From mensanator at aol.com Sun Jul 27 11:34:59 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 27 Jul 2008 08:34:59 -0700 (PDT) Subject: Insert string into string References: <56ff99b9-b4d4-4077-8de1-97a771ac526a@k13g2000hse.googlegroups.com> Message-ID: <0b13960e-85a1-499f-872d-9e2b71987aad@26g2000hsk.googlegroups.com> On Jul 27, 1:41?am, Peter Otten <__pete... at web.de> wrote: > Mensanator wrote: > > I don't know why you're using stdin if you're reading from a file. > > From Francesco's initial post in his previous thread I inferred that he had > a script like > > f = open("xxx.pdb") > for line in f: > ? ? # process line > ? ? print line > > and was calling it > > python script.py >outfile > > My hope was that > > import sys > for line in sys.stdin: > ? ? # process line > ? ? sys.stdout.write(line) > > invoked as > > python script.py outfile > > would be an improvement as it avoids hardcoding the filename, but instead > chaos ensued... > > Francesco: Mensanator's script looks like you can take it "as is". Well, I didn't bother to insert the serial number into the extra line as the extra line wasn't given. Hopefully, it's obvious how to do that. > If you > want to use Python to do other interesting things I highly recommend that > you work your way through a tutorial of your choice. This will make > subsequent trial-and-error much more fun. > > Following Roy's suggestion I also had a brief look at Biopython's PDB parser > which has the advantage that it "understands" the file format. > Unfortunately it is probably too complex for you to use at this point of > your career as a pythonista ;) > > By the way, are you trying to modify the chain ID? Biopython locates that at > position 21, so take this as a reminder that indices in Python start at 0, > i. e. line[21] gives you the 22nd character in the line. > > Peter From thogiti at gmail.com Fri Jul 4 22:07:20 2008 From: thogiti at gmail.com (Nagu) Date: Fri, 4 Jul 2008 19:07:20 -0700 (PDT) Subject: Copyright issues for an application developed using django, python and mySQL References: <1f23a9fd-33a0-4a06-9733-241c8fd450d2@w4g2000prd.googlegroups.com> <87iqvm30cf.fsf@benfinney.id.au> Message-ID: Thank you for your explanations. On Jul 3, 6:27?pm, Ben Finney wrote: > Nagu writes: > > I made a small recommendation engine for our company using python, > > django, and mySQL. My supervisor and the senior management are > > worried about the copyright and licensing issues. > > It's good that they're raising these concerns and making sure. > > > They want to find out the details on how to go about start using it, > > like quoting python/django/ mySQL specifically on the bottom of the > > web page or some other thing. > > You should read the licenses for these products (they're not long), > and retain a lawyer to give an educated opinion addressing the > specific concerns your managers have. > > > How do I go about addressing the copyright and licensing issues? (I > > do not know if licensing is the right word here). > > Start with finding out exactly what those concerns are, gather the > license terms of the works you're using, and consult a copyright > lawyer. > > In parallel, you can read the license texts yourself and understand > them to satisfy yourself about what the terms allow and require. > However, that understanding is good only for making decisions that > affect yourself; for making decisions that affect the company, your > managers should get expert legal opinion. > > > Please advice. > > Hope that helps. > > -- > ?\ ? ? ? ? ?I was gratified to be able to answer promptly and I did. I | > ? `\ ? ? ? said I didn't know.? ?Mark Twain, _Life on the Mississippi_ | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| > Ben Finney From ethan at stoneleaf.us Thu Jul 10 16:37:42 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 10 Jul 2008 12:37:42 -0800 Subject: numeric emulation and the rich comparison operators Message-ID: <48767316.3060607@stoneleaf.us> Greetings, List! Still working on my Measure class, and my next question is... (drum roll please ;) What are the advantages of using __[eq|ne|lt|gt|le|ge]__ vs __cmp__? Thanks in advance! -- Ethan From casey.mcginty at gmail.com Thu Jul 10 16:18:41 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Thu, 10 Jul 2008 10:18:41 -1000 Subject: Unit Testing Techniques Message-ID: I'm familiar with the unittest module in Python, however I'm hoping someone can point me to some examples of more advanced usages of the framework. For example: 1. Using the framework to test a package with nested sub-packages and modules without having to hard code the location/name of each test module. 2. Testing class/methods that depend on file system directory structures, file data, or values read from system hardware. 3. Testing class/methods that require simulating functionality from imported modules. 4. Testing graphical interfaces and associated signal callback functions. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Russ.Paielli at gmail.com Mon Jul 28 02:00:51 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 23:00:51 -0700 (PDT) Subject: Attack a sacred Python Cow References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <20080728033918.GG7373@dragontoe.org> Message-ID: <3178aebe-88fd-483d-8068-b0a73e848a95@v1g2000pra.googlegroups.com> On Jul 27, 10:32 pm, Terry Reedy wrote: > Derek Martin wrote: > > Furthermore, as you described, defining the function within the scope > > of a class binds a name to the function and then makes it a method of > > the class. Once that happens, *the function has become a method*. > > If you mean that a user-defined function object becomes a different > class of object when bound to a class attribute name, that is wrong. > Once a function, always a function. It may be called an 'instance > method' but it is still a function. Any function object can be an > attribute of multiple classes, without inheritance, or of none. > > When a function attribute is accessed via an instance of the class, it > is *wrapped* with a bound method object that basically consists of > references to the function and instance. When the 'bound method' is > called, the instance is inserted in front of the other arguments to be > matched with the first parameter. > > In 2.0, functions accessed through the class were rather uselessly > wrapped as an 'unbound method', but those wrappers have been discarded > in 3.0. > > > To be perfectly honest, the idea that an object method can be defined > > outside the scope of an object (i.e. where the code has no reason to > > have any knowledge of the object) seems kind of gross to me... > > I happen to like the simplicity that "def statements (and lambda > expressions) create function objects." Period. > > ... > > > It does indeed -- it does more than imply. It states outright that > > the function is defined within the namespace of that object, > > True. > > > and as such that it is inherently part of that object. > > False. That does not follow. Python objects generally exist > independently of each other. Think of them as existing in a nameless > dataspace if you want. Collection/container objects collect/contain > references to their members, just as a club roster does, but they only > metaphorically 'contain' their members. Any object can be a member of > any number of collections, just as humans can join any number of clubs > and groups. In mathematical set theory, membership is also non-exclusive. > > > So why should it need > > to be explicitly told about the object of which it is already a part? > > Because it is not a 'part' of a class in the sense you seem to mean. > > What is true is that functions have a read-only reference to the global > namespace of the module in which they are defined. But they do not have > to be a member of that namespace. > > Terry Jan Reedy This whole discussion reminds me of discussions I saw on comp.lang.ada several years ago when I had a passing interest in Ada. My memory on this is a bit fuzzy, but IFIRC Ada 95 did not support standard OO "dot" syntax of the form myObject.myFunction(args) Instead, "myfunction" was just a "regular" function that took "myObject" and "args" as arguments. It was called as myFunction(myObject, args) It was put into the appropriate package or subpackage where it belonged rather than in a class definition. Namespaces were defined by a package hierarchy rather than by classes (which is actually more logical, but that's another topic). Well, so many people demanded the "dot" notation that it was finally implemented in Ada 2005. So now user can use the more familiar dot notation, but my understanding is that it is just "syntactic sugar" for the old notation. So when Python people go out of their way to point out that class "methods" in Python are implemented as regular functions, that seems fairly obvious to me -- but perhaps only because of my passing familiarity with Ada. From timothy.grant at gmail.com Tue Jul 22 19:49:18 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Tue, 22 Jul 2008 16:49:18 -0700 Subject: How do I compare files? In-Reply-To: <1216769247.18962.7.camel@generator> References: <1216769247.18962.7.camel@generator> Message-ID: On Tue, Jul 22, 2008 at 4:27 PM, Clay Hobbs wrote: > I am making a program that (with urllib) that downloads two jpeg files > and, if they are different, displays the new one. I need to find a way > to compare two files in Python. How is this done? > > -- Ratfink > > -- > http://mail.python.org/mailman/listinfo/python-list > I'd start with file sizes. If that's not enough you might look at the md5 library and check the md5 values for the files. -- Stand Fast, tjg. [Timothy Grant] -------------- next part -------------- An HTML attachment was scrubbed... URL: From upton at virginia.edu Mon Jul 21 00:08:13 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 21 Jul 2008 00:08:13 -0400 Subject: Python Written in C? In-Reply-To: References: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> Message-ID: <5504f9ac0807202108k764242f5i5c45b16f57dfe9aa@mail.gmail.com> On Sun, Jul 20, 2008 at 11:51 PM, Mensanator wrote: > On Jul 20, 10:05?pm, Stephen Johnson wrote: >> > Carry bits? Who worries about carry bits when you have >> > unlimited precision arithmetic? You want cool? >> > THIS is cool: >> >> > j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2])) >> > % xyz[1]**(k-1))/xyz[1]**(k-2) >> >> You call that "cool." I call it "unreadable." > > Ok, but not in the sense that something like > Scheme is unreadable as this is nothing but > algebra (albeit complicaed). > Scheme doesn't *have* to be unreadable... any more unreadable than any other language when poorly documented/formatted, anyway. From mail at timgolden.me.uk Fri Jul 4 11:26:29 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 04 Jul 2008 16:26:29 +0100 Subject: Can't get Python for Windows to run In-Reply-To: References: Message-ID: <486E4125.5080201@timgolden.me.uk> Tim Rowe wrote: > I have Python 2.5 working just fine on my system. > > I've tried downloading and installing the MS Windows Python > extensions, but can't get pythonw.exe (that's the windows executable, > right?) to do anything. I double-click it, nothing happens. I run it > from a command prompt, it just returns me to the command prompt. Ummm. That's the Python interpreter but without a window so (unhelpfully, from your point of view) it's doing exactly the right thing. I assume you were trying to run the PythonWin Python interpreter and dev env? On my system, that's: C:\Python25\Lib\site-packages\pythonwin\Pythonwin.exe HTH TJG From emfloyd2 at gmail.com Fri Jul 18 15:21:49 2008 From: emfloyd2 at gmail.com (mark floyd) Date: Fri, 18 Jul 2008 12:21:49 -0700 Subject: Multiple variable control in for loops. Doable in Python? Message-ID: <28efa6970807181221o67c90575w690464f1442dc47d@mail.gmail.com> I'm new to Python and have been doing work converting a few apps from Perl to Python. I can not figure out the comparable Python structures for multi-variable for loop control. Examples: # In Perl for($i = 0, j = 0; $i < I_MAX && $j < J_MAX; $i+=5, $j += 10) { ..... do something } // In Java class test { public static void main(String[] args){ int i = 0; int j = 1; for(i=1, j = 0; i<11 && j < 10; i++, j++){ System.out.println("I is: " + i); System.out.println("J is: " + j); } } } // In C #include int main() { int j = 0; int k = 0; for(j = 0, k = 0; j < 5 && k < 10; j++, k++) { printf("J = %d\n", j); printf("k = %d\n", k); } return 0; } I spent a good part of yesterday looking for a way to handle this style for loop in Python and haven't been able to find an appropriate way to handle this control style. We have this style for loop all over the place and not being able to find a similar structure in Python could be a problem. Any pointers to a Python equivalent structure would be much appreciated - Mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian at excess.org Tue Jul 15 23:59:25 2008 From: ian at excess.org (Ian Ward) Date: Tue, 15 Jul 2008 23:59:25 -0400 Subject: ANN: Urwid 0.9.8.3 - Console UI Library Message-ID: <487D721D.6010304@excess.org> Announcing Urwid 0.9.8.3 ------------------------ Urwid home page: http://excess.org/urwid/ Tarball: http://excess.org/urwid/urwid-0.9.8.3.tar.gz RSS: http://excess.org/feeds/tag/urwid/ About this release: =================== This is a maintenance release that fixes a memory leak and a canvas bug affecting Urwid 0.9.8, 0.9.8.1 and 0.9.8.2. New in this release: ==================== * Fixed a canvas cache memory leak affecting 0.9.8, 0.9.8.1 and 0.9.8.2 (found by John Goodfellow) * Fixed a canvas fill_attr() bug (found by Joern Koerner) About Urwid =========== Urwid is a console UI library for Python. It features fluid interface resizing, UTF-8 support, multiple text layouts, simple attribute markup, powerful scrolling list boxes and flexible interface design. Urwid is released under the GNU LGPL. From bierbaum at vierfalt.com Thu Jul 10 10:21:25 2008 From: bierbaum at vierfalt.com (Simon Bierbaum) Date: Thu, 10 Jul 2008 16:21:25 +0200 Subject: handling unexpected exceptions in pdb Message-ID: Hi all, I'm in an interactive session in pdb, debugging my code using pdb.runcall. Somewhere, an exception is raised and lands uncaught on stdout. Is there any way of picking up this exception and at least read the full message, or even accessing its stack trace to determine where exactly within the one line I just executed it was raised? This is where I'm stuck: > /usr/local/apache2/bin/Model/Database.py(287)disconnect() (Pdb) n FlushError: FlushErr...perly.",) > /usr/local/apache2/bin/Model/Database.py(287)disconnect() (Pdb) import sys (Pdb) sys.last_traceback *** AttributeError: 'module' object has no attribute 'last_traceback' Thanks, Simon From kjhishere at gmail.com Wed Jul 16 09:16:33 2008 From: kjhishere at gmail.com (Ken Hartling) Date: Wed, 16 Jul 2008 06:16:33 -0700 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: Thanks .. but I want to find out if the system is "running on 64bit" even when the interpreter is a 32-bit build executable ("what python was built on"). platform.architecture() and platform() in general seems to only be looking at the build executable and what it was built for on windows (sorry, I don't have a unix box available at the moment). platform.architecture() returns 32bit when on a windows 64bit box. Another recommendation was: import sys hex(sys.maxint) x = sys.maxint n = 1 while x: n += 1 x >>= 1 print n Unfortunately this too appears to be looking at the build executable ... on Windows 64 it returns '32'. Thanks for the suggestions, hopefully we'll come up with a winner. Ken On Tue, Jul 15, 2008 at 1:39 PM, Benjamin Kaplan wrote: > > > On Tue, Jul 15, 2008 at 4:10 PM, wrote: > >> I need to know if I'm running on 32bit or 64bit ... so far I haven't >> come up with how to get this info via python. sys.platform returns >> what python was built on ... but not what the current system is. >> >> I thought platform.uname() or just platform.processor() would have >> done it, but python returns an empty string on windows. Any ideas? >> >> Thanks, Ken >> -- > > > platform.architecture() should have it. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mathieu.prevot at ens.fr Fri Jul 11 06:43:04 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Fri, 11 Jul 2008 12:43:04 +0200 Subject: error with configure (svn 64857) In-Reply-To: <48770603$0$9695$9b622d9e@news.freenet.de> References: <487681e9$0$9745$9b622d9e@news.freenet.de> <48770603$0$9695$9b622d9e@news.freenet.de> Message-ID: <3e473cc60807110343s100b8866k1353b3e8e61049b7@mail.gmail.com> 2008/7/11 "Martin v. L?wis" : >> Thank you Martin. How can I remove -lgcc_s and use the Intel equivalent ? > > I'm not so sure that there is anything wrong in configure. configure > doesn't pass -lgcc_s to icc; instead, icc is making this up on its > own. So I would guess you need to get libgcc_s onto you system in a > way that the linker finds it. Else you need to read the icc > documentation (but I'm fairly sure that icc is *required* to link > with libgcc_s, for interoperability with gcc-compiled binaries). > > I'm somewhat puzzled that the wchar_t test is the one where it > crashes; this test comes fairly late, and configure has run multiple > compiler invocations before that. > > Can you build any binaries at all with your icc installation? Yes of course, I successfuly built and installed nmap, wget, so I thought there was something in the python configure process. If didn't investigate everything but I solved the problem by adding the "-static-libgcc" option: CFLAGS="-w -static-intel -static-libgcc" I think one should commit changes so configure can manage this. I can I want to help for further diagnosis or improvement. Also it seems -Wall will be deprecated, and usually we use -w: -w Control diagnostics, where is one of the following: 0 -- Display errors (same as -w) 1 -- Display warnings and errors (default) 2 -- Display remarks, warnings, and errors Cheers, Mathieu From d3vvnull at gmail.com Mon Jul 28 16:52:16 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Mon, 28 Jul 2008 15:52:16 -0500 Subject: Protecting instance variables In-Reply-To: <877ib6s3xi.fsf@nokile.rath.org> References: <6eb9iaF6779oU1@mid.uni-berlin.de> <877ib6s3xi.fsf@nokile.rath.org> Message-ID: <170543c70807281352w6858e7e0g51082b7b5b56611@mail.gmail.com> What about __setattr__()? On Mon, Jul 28, 2008 at 5:23 AM, Nikolaus Rath wrote: > Hi, > > Sorry for replying so late. Your MUA apparently messes up the > References:, so I saw you reply only now and by coincidence. > > "Diez B. Roggisch" writes: > > Nikolaus Rath schrieb: > >> Hello, > >> > >> I am really surprised that I am asking this question on the mailing > >> list, but I really couldn't find it on python.org/doc. > >> > >> Why is there no proper way to protect an instance variable from access > >> in derived classes? > >> > >> I can perfectly understand the philosophy behind not protecting them > >> from access in external code ("protection by convention"), but isn't > >> it a major design flaw that when designing a derived class I first > >> have to study the base classes source code? Otherwise I may always > >> accidentally overwrite an instance variable used by the base class... > > > > Here we go again... > > > > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/188467d724b48b32/ > > > > To directly answer your question: that's what the __ (double > > underscore) name mangling is for. > > > I understand that it is desirable not to completely hide instance > variables. But it seems silly to me that I should generally prefix > almost all my instance variables with two underscores. > > I am not so much concerned about data hiding, but about not > accidentally overwriting a variable of the class I'm inheriting from. > And, unless I misunderstood something, this is only possible if I'm > prefixing them with __. > > How is this problem solved in practice? I probably don't have a > representative sample, but in the libraries that I have been using so > far, there were a lot of undocumented (in the sense of: not being part > of the public API) instance variables not prefixed with __. I have > therefore started to first grep the source of all base classes > whenever I introduce a new variable in my derived class. Is that > really the way it's supposed to be? What if one of the base classes > introduces a new variable at a later point? > > > Best, > > -Nikolaus > > -- > ?It is not worth an intelligent man's time to be in the majority. > By definition, there are already enough people to do that.? > -J.H. Hardy > > PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From bsagert at gmail.com Wed Jul 2 02:25:53 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Tue, 1 Jul 2008 23:25:53 -0700 (PDT) Subject: n00bie wants advice. Message-ID: <8757c630-0518-4351-a319-124ced0ac92c@w4g2000prd.googlegroups.com> This simple script writes html color codes that can be viewed in a browser. I used short form hex codes (fff or 000, etc) and my list has only six hex numbers otherwise the results get rather large. I invite criticism as to whether my code is "pythonic". Are there other ways to generate the hex combos besides the nested "for" loops? Thanks in advance, Bill list = ['3','6','9','b','d','f'] s = '\n' for a in list: for b in list: for c in list: s += '

'+ a + b + c +'

\n' s += '' f = open('c:/x/test.htm', 'w') f.write(s) f.close() From tjreedy at udel.edu Thu Jul 10 14:29:32 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jul 2008 14:29:32 -0400 Subject: Changing self: if self is a tree how to set to a different self In-Reply-To: References: Message-ID: Bart Kastermans wrote: > I am playing with some trees. In one of the procedures I wrote > for this I am trying to change self to a different tree. A tree > here has four members (val/type/left/right). I found that self = SS > does not work; I have to write self.val = SS.val and the same for > the other members (as shown below). Is there a better way to do this? > > In the below self is part of a parse tree, F is the parse tree of a > function f with argument x. If a node in the parse tree is labelled > f, we should replace it by the parse tree for the function f, F, with > the remainder of the tree substituted for the input variable for the > function f, here x. > > def elimF (self): > if self.val == "f": > SS = F.copy () > SS.subst ('x', self.left) > self.val = SS.val # from here: set self to be SS > self.type = SS.type > self.left = SS.left > self.right = SS.right # completed: set self to be SS If you examine nodes from their parent, I believe you can do the substitution in one step. Something like: for slot,child in ( ('left',self.left), ('right',self.right) ): if child is not None: if child.val == 'f': setattr(self, slot, F.copy().subst('x', child.left)) child.elimF where .subst returns the modified tree. > > if self.left != None: # iterate onward, inf recursion if f > # appears. Would need a check in > # real version > self.left.elimF () > if self.right != None: > self.right.elimF () Terry Jan Reedy From sunp1028 at gmail.com Tue Jul 15 23:06:58 2008 From: sunp1028 at gmail.com (patrol) Date: Tue, 15 Jul 2008 20:06:58 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> Message-ID: <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> > http://timgolden.me.uk/wmi-project/wmi.py It cannot work either. > which is a copy of the svn trunk to see if that > improves the UnicodeDecode error, please? I'll > try to get an install of a non-English edition of > Windows but, as you might imagine, I normally run > the UK version so don't hit these kind of issue > myself. I expect you can test successfully at a non-English edition From sjmachin at lexicon.net Mon Jul 21 16:33:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 21 Jul 2008 13:33:01 -0700 (PDT) Subject: Converting List of String to Integer References: Message-ID: On Jul 22, 6:11 am, Samir wrote: [snip] > For some reason, the logic I posted seems to work ok while I'm using > the Python shell, but when used in my code, the program just hangs. > It never outputs the results. Below is the code in its entirety. Is > there a problem with my indendentation? > > a = n = [] > t = """ > 1 2 > 3 > 4 5 6 > 7 8 9 0 > """ > > d = t.split("\n") > > for x in range(1,len(d)-1): > a.append(d[x].split(" ")) > print a > > for k in a: > n.append([int(v) for v in k]) To see what is happening, insert some print statements, plus something to slow it down e.g. for k in a: print id(a), a print id(n), n n.append([int(v) for v in k]) raw_input('Hit Enter to continue ->') > > print n > From hat at se-162.se.wtb.tue.nl Mon Jul 7 05:49:57 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 07 Jul 2008 11:49:57 +0200 Subject: python beginner References: <1cd8ffae-62a7-4cfb-b3ab-61c7004841c9@8g2000hse.googlegroups.com> Message-ID: On 2008-07-07, cna wrote: > Hi all and one, > how may i learn python. is there any other website except python.org Yes, there are several millions web-sites, all across the world. They cover every possible topic you may and may not imagine. If you mean a website that tries to teach you about Python, the choice is slightly smaller. Did you look at the sites listed under "http://wiki.python.org/moin/BeginnersGuide"? If you find other useful sites, please add them. Sinceely, Albert From Russ.Paielli at gmail.com Wed Jul 30 23:24:38 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 30 Jul 2008 20:24:38 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> Message-ID: On Jul 30, 8:03 pm, Erik Max Francis wrote: > Russ P. wrote: > > The reason I wrote that "it would be nice to be able to write" > > > if x is not empty: > > > is that it reads naturally. It was not an actual proposal, and the > > fact that you took it as such was *your* mistake. > ... > > Now read carefully: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! Let > > me repeat that for you: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! > > Did you get that, idiot? > > So people who can read words but not minds are idiots. Go get 'em, tiger! I don't know if you can read minds, but you seem to have a lot of trouble reading words. Can you read "it would be nice to be able to write ..."? Can you understand what it means? Can you understand that it does *not* mean, "one *should* be able to write ..."? The really significant question here is why I waste my valuable time with pedants like you. From __peter__ at web.de Sat Jul 26 04:08:04 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 26 Jul 2008 10:08:04 +0200 Subject: Insert character at a fixed position of lines References: Message-ID: Francesco Pietra wrote: > How to insert letter "A" on each line (of a very long list of lines) > at position 22, i.e., one space after "LEU", leaving all other > characters at the same position as in the original example: > > > ATOM 1 N LEU 1 146.615 40.494 103.776 1.00 73.04 > 1SG 2 > > In all lines"ATOM" is constant as to both position and string, while > "LEU" is constant as to position only, i.e., "LEU" may be replaced by > three different uppercase letters. Therefore, the most direct > indication would be position 22. You insert a string into another one using slices line = line[:22] + " " + line[22:] (Python's strings are immutable, so you are not really modifying the old string but creating a new one) > Should the script introduce blank lines, no problem. That I know how > to correct with a subsequent script. You are probably printing lines read from a file. These lines already end with a newline, and print introduces a second one. Use the file's write() method instead of print to avoid that, e. g.: import sys for line in sys.stdin: line = line[:22] + " " + line[22:] sys.stdout.write(line) Peter From ldo at geek-central.gen.new_zealand Fri Jul 18 01:36:31 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 18 Jul 2008 17:36:31 +1200 Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> <41d4ffc7-7fd5-4202-92ea-132c7d4f5cd4@s50g2000hsb.googlegroups.com> Message-ID: In message , Gabriel Genellina wrote: > Note that I used %s everywhere (it's just a placeholder, not a format) ... >From /usr/lib64/python2.5/site-packages/MySQLdb/cursors.py, lines 150-151: if args is not None: query = query % db.literal(args) From tjreedy at udel.edu Wed Jul 30 13:22:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jul 2008 13:22:51 -0400 Subject: undo a dictionary In-Reply-To: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> References: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> Message-ID: mmm wrote: > I found code to undo a dictionary association. > > def undict(dd, name_space=globals()): > for key, value in dd.items(): > exec "%s = %s" % (key, repr(value)) in name_space You are not undoing anything. You are updating globals() from another dict. But why repr(value)? Without that, globals().update(dd) would work. In 2.6?/3.0, replace 'dd' with '{a:b for a,b in dd.items()} dd = { 'a':1, 'b': 'B'} globals().update({a:b for a,b in dd.items()}) print(a,b) # 1,B >>>> dx= { 'a':1, 'b': 'B'} >>>> undict(dx) > > I get >>>> print A, B > 1 B > > Here, a=1 and b='B' Don't fake interactive output. You would have to "print a,b". Above gives a NameError. > This works well enough for simple tasks and I understand the role of > globals() as the default names space, but creating local variables is > a problem. Within functions, yes. Just access the values in the dict. > Also having no output arguemtns to undict() seems > counterintuitive. In Python, this is standard for functions that mutate. > Also, the function fails if the key has spaces or > operand characters (-,$,/,%). Exec is tricky. Most people hardly ever use it. > Finally I know I will have cases where > not clearing (del(a,b)) each key-value pair might create problems in a > loop. You cannot mutate a dict while iterating through it. > So I wonder if anyone has more elegant code to do the task that is > basically the opposite of creating a dictionary from a set of > globally assigned variables. See above. > And for that matter a way to create a > dictionary from a set of variables (local or global). You have to be more specific: there are {} displays and dict(args) call and other methods. Read the manual. tjr From tommy.nordgren at comhem.se Sun Jul 13 13:02:54 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Sun, 13 Jul 2008 19:02:54 +0200 Subject: like py2exe, but on a mac In-Reply-To: <18424336.post@talk.nabble.com> References: <18424336.post@talk.nabble.com> Message-ID: <433B228E-A00F-4F7F-B2A6-8D4E6B42302A@comhem.se> On 13 jul 2008, at 00.39, Alexnb wrote: > > Hi All > > I am wondering what I can do to turn a python app (.py) into a mac OSX > applicaiton (.app). Just like py2exe does. But I am also wondering > since in > your applications folder on macs it usually doesn't have an actual > folder > for each app. Rather an icon. so for firefox, you just see the icon. > Unlike > windows where you have a folder with everything, and the actual > program is > in it. where is all the application info stored? just in the .app? > Finally > whether or not there is an app like py2exe for mac, is there a way > to skip > the middle man and turn it straight into a .dmg with the app inside? > -- > View this message in context: http://www.nabble.com/like-py2exe%2C-but-on-a-mac-tp18424336p18424336.html > Sent from the Python - python-list mailing list archive at Nabble.com. > > -- > http://mail.python.org/mailman/listinfo/python-list Platypus can bundle any script into an .app bundle. ----------------------------------- See the amazing new SF reel: Invasion of the man eating cucumbers from outer space. On congratulations for a fantastic parody, the producer replies : "What parody?" Tommy Nordgren tommy.nordgren at comhem.se From mbelzile at softimage.com Tue Jul 15 11:12:48 2008 From: mbelzile at softimage.com (=?iso-8859-1?Q?Marc-Andr=E9_Belzile?=) Date: Tue, 15 Jul 2008 11:12:48 -0400 Subject: installation error on linux 64 Message-ID: <0BCB4AE868D8934A8B3DCE3A58126A8902611161@tewk-mbpf3> Hi, I've compiled python 2.5.2 on red hat r4 and got this installation error: mtl-p1892:[Python-2.5.2] 1>make install ... Compiling /BuildViews/python252build/Python2.5.2.bin/lib/python2.5/test/test_module.py ... Compiling /BuildViews/python252build/Python2.5.2.bin/lib/python2.5/test/test_multibytecodec.py ... Sorry: UnicodeError: ("\\N escapes not supported (can't load unicodedata module)",) Compiling /BuildViews/python252build/Python2.5.2.bin/lib/python2.5/test/test_multibytecodec_support.py ... ... make: *** [libinstall] Error 1 Looks like I'm missing some codec. Any idea how I can fix that ? Thanks for your help. -mab -------------- next part -------------- An HTML attachment was scrubbed... URL: From Phillip.Ross.Taylor at gmail.com Fri Jul 25 09:30:14 2008 From: Phillip.Ross.Taylor at gmail.com (Philluminati) Date: Fri, 25 Jul 2008 06:30:14 -0700 (PDT) Subject: Working with ctypes and char** data type References: <14b44a64-ec58-4ff2-abce-1cc44557e4e4@27g2000hsf.googlegroups.com> <6erju5F88slmU2@mid.individual.net> Message-ID: <6ac2d2ef-a98d-4982-ad1a-7f444a5bf2b9@u12g2000prd.googlegroups.com> On Jul 24, 4:03?pm, Thomas Heller wrote: > Philluminati schrieb: > > > > > I'm a bit of a python newbie and I need to wrap a C library. > > > I can initialise the library using CDLL('mcclient.so') > > > and I can call functions correctly inside the library but I need to > > invoke one function which has this function definition: > > > char ** CAPAPI McSearch(HMCLINK Handle, > > ? ? ? ? ? ? ? ? ? ? ? ? short nSearchType, > > ? ? ? ? ? ? ? ? ? ? ? ? short nNoSelect, > > ? ? ? ? ? ? ? ? ? ? ? ? char **pSelect, > > ? ? ? ? ? ? ? ? ? ? ? ? short nNoWhere, > > ? ? ? ? ? ? ? ? ? ? ? ? char **pWhere, > > ? ? ? ? ? ? ? ? ? ? ? ? char **pData, > > ? ? ? ? ? ? ? ? ? ? ? ? int iTimeout); > > > For **pSelect I want to pass in an array of char points, which in C > > would be declared as > > > char *pData[] = { "ADDR", "POSTCODE" }; > > > Can someone tell me how use pointers + char pointers together in > > python with ctypes please? > > # create an array that holds two pointers to 'char *', and fill it with data: > pData = (c_char_p * 2)() > pData[0] = "ADDR" > pData[1] = "POSTCODE" > > # Another way: > pData = (c_char_p * 2)("ADDR", "POSTCODE") > > Thomas Thank you Thomas for your reply. I also got it working in a slightly less sophisticated manor like this: SelectType = c_char_p * 2 select = SelectType("ADDR", "POSTCODE") ptr = pointer(select) Anyway, thanks for taking the time to reply! Phill From tjreedy at udel.edu Thu Jul 10 02:21:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jul 2008 02:21:08 -0400 Subject: "in"consistency? In-Reply-To: References: <871c6735-f2d2-4cd0-811d-0cd774d55bdd@m45g2000hsb.googlegroups.com> Message-ID: castironpi wrote: > On Jul 8, 2:25 pm, Terry Reedy wrote: > Compare to an imaginary "set of ints" data type: > >>>> a= setofints( [ 0, 1, 2 ] ) > > Then, the semantics of > >>>> b= setofints( [ 0, 1 ] ) >>>> b in a > True > > are consistent and predictable. Correct me if I'm wrong. If you defined a subclass setofints of set with members restricted to being integers, so that [0,1] could not be a member, then you could (sensibly, in my opinion) override __contains__ to make the above work. On the other hand, 'b in a' as a synonym for 'b is a subset of a' is already available for general sets as b.issubset(a). So I would not do the work of subclassing just to abbreviate this call, but only if I wanted the membership guard. Also, the transition from 'int in setofints' to 'setofints in setofints' is not as smooth as the transition from 'length-1 string in string' to 'length-n string in string' because of the need to test and switch on whether the object tested is an int or setofints. Tuples and lists do not have a subsequence find or test method. However, if I wanted one (and I expect I will sometime), I would probably write a general function for sequence in sequence, without bothering with restricting sequence membership. Terry Jan Reedy From grante at visi.com Tue Jul 1 11:22:03 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 01 Jul 2008 10:22:03 -0500 Subject: How to use gnu readline library in program? Message-ID: I'm trying to figure out how to use the gnu readline library so that when my program is prompting the user for input there is line editing and history support. I've read and re-read the documentation for the "readline" module in the standard library and I still can't figure out how to use the module or even if the module is intended to do what I want. The example code all seems to be about on how to modify the behavior of an interactive Python interpreter session so you have things like auto-completion of Python identifiers. What I want to do is replace sys.stdin.readline() with something that will provide the user with line editing and history recall. In other languages, one uses the Gnu readline library to do that, but my reading of the Python library documentation is that's not what the Python readline module is for. Am I wrong? -- Grant Edwards grante Yow! On the road, ZIPPY at is a pinhead without a visi.com purpose, but never without a POINT. From MrJean1 at gmail.com Sat Jul 12 23:08:38 2008 From: MrJean1 at gmail.com (MrJean1) Date: Sat, 12 Jul 2008 20:08:38 -0700 (PDT) Subject: How to create a timer/scheduler in Python? References: <0stg74t0eksmnfsslukn5m7f9s4rbub8kt@4ax.com> Message-ID: <65766272-b3e3-462a-9fe3-456361732c97@m36g2000hse.googlegroups.com> There is a module called sched in the standard Python library /Jean Brouwers John Dann wrote: > I need what I'd call (in .Net) a timer, ie I need to run a function eg > every 2 seconds - it doesn't need to be millisec accurate but it would > be nice if it wasn't eg every 4 seconds or something. > > Rather surprisingly, Core Python (Chun) doesn't seem to index 'timer' > or 'scheduler', which leaves me wondering whether this is an aspect of > Python that isn't perhaps widely used? > > Looking around on the net I can see references to a thread timer, but > I'm not really looking to start any new threads (I just want part of > the GUI to update every 2 secs) and don't want to get into that sort > of complication while still just learning Python. > > Is there really no simple timer/scheduler function available in > Python? From squishywaffle at gmail.com Thu Jul 31 10:03:06 2008 From: squishywaffle at gmail.com (squishywaffle at gmail.com) Date: Thu, 31 Jul 2008 07:03:06 -0700 (PDT) Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> Message-ID: Hello Diez. > May I suggest you move to ctypes for wrapping? It's easier, pure python and > callbacks are already built-in. I'm pretty new to extending Python in C, I don't understand what you're saying. Are there any examples or a brief explanation/URL you could point me to? From victorsubervi at gmail.com Tue Jul 29 09:08:21 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 29 Jul 2008 15:08:21 +0200 Subject: RTF Parsing Message-ID: <4dc0cfea0807290608v3e89a5c6m7dc0ca70fd064a00@mail.gmail.com> Hi; I have this code: def a(): chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', '\\yz'] rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like the Beast? Who can wage war against him?\par' for char in chars: c = '(?<=' + char + ')' test = re.search(c, rtf_markup) try: junk = test.group(0) print char except: pass which gives this result: >>> a() \qc \b0 \i \u \b >>> which makes no sense at all. I expected this: >>> a() \qc \i >>> Why do I get more than that? Also, if I change this line thus: c = '(?<=' + char + ')[0 ]' I get this result: >>> a() \b >>> Why? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From krishnamurthi1921 at gmail.com Tue Jul 29 14:13:00 2008 From: krishnamurthi1921 at gmail.com (lakshmi) Date: Tue, 29 Jul 2008 11:13:00 -0700 (PDT) Subject: it is a computer langugage Message-ID: <533e5bb0-b76d-437d-aebc-a229c9a3357a@x29g2000prd.googlegroups.com> hai just click this a computer langugage www.insurances8blogspot From phillip.oldham at gmail.com Wed Jul 30 08:49:38 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Wed, 30 Jul 2008 05:49:38 -0700 (PDT) Subject: Standard module for parsing emails? Message-ID: Is there a standard library for parsing emails that can cope with the different way email clients quote? From babacity2 at gmail.com Thu Jul 24 16:56:54 2008 From: babacity2 at gmail.com (babacity2 at gmail.com) Date: Thu, 24 Jul 2008 13:56:54 -0700 (PDT) Subject: Peachy18 com - Amazing porn video collection Message-ID: peachy18 com . >>>>>>>>>>Best Collection of Peachy18 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE peachy18 com VIDEOS<<<<<<<<<<< . peachy18 com From jyoung79 at kc.rr.com Tue Jul 29 23:56:55 2008 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Tue, 29 Jul 2008 22:56:55 -0500 Subject: elementtree and rounding questions Message-ID: <8557669.817811217390216084.JavaMail.root@hrndva-web17-z02> Hi, Hoping that some of you won't mind taking a peek at my code and sharing your thoughts. I just started using the elementtree module yesterday to work with xml files. Here's an example of some xml code I might be parsing: ============================================================ ============================================================ What I'd like to do is get the attribute 'name' from the 2nd set 'fontData' tags. So what I'd end up with is ['Courier', 'Helvetica']. Here's the first lines of code I tested: ============================================================ from xml.etree import ElementTree as ET tree = ET.parse('/Users/jay/Desktop/test.txt') root = tree.getroot() fntList = [] f = root.getiterator('fonts') n = f[-1].getiterator('fontData') for i in n: i = i.get('name') if i != None: fntList.append(i) print fntList ============================================================ This gives me ['Courier', 'Helvetica'] which is what I'm wanting. If I'm understanding this correctly, it seems getiterator('fonts') will get both of the 2 sections of tags. Since I only want the second section, which is the last, I look at f[-1] and use the getiterator('fontData') in order to search through all the appropriate tags. Looks like getiterator also finds all nested tags as seen above when it grabbed both font names I was wanting. So I continued to experiment a bit and came up with this next: ============================================================ from xml.etree import ElementTree as ET tree = ET.parse('/Users/jay/Desktop/test.txt') root = tree.getroot() fntList = [] f = root.getiterator('fonts') n = f[-1].find('fontData') for i in n: fntList.append(i.get('name')) print fntList ============================================================ This code just gave me ['Courier']. Now if I change 'find' to 'findall' then I'll get [None, 'Helvetica']. Not exactly sure what exactly that's doing. Seems the 'findall' searches through the tags that aren't nested, but then just using 'find' found the first nested 'name'. Anyway, I'm hoping someone might tell me if the first example of code above is a decent way to parse xml files. I'm still new to Python and am looking for good code structure as well as accurate examples. -- One other question I had was about rounding floats. I was first looking at this syntax to round out to 6 decimal places if needed: >>> f = '508.5' >>> x = '%.6f' % (float(f)/72) >>> x '7.062500' However, in this instance I don't want the last 2 zeroes. So would it be better to do something like this: >> f = '508.5' >>> x = round(float(f)/72, 6) >>> x 7.0625 I've been reading a bit about some rounding bugs, but am really not that knowledgeable about the subject. Does anyone have a preference of how they like to round as well as the result they see? Thanks for looking at my questions. Jay From fredrik at pythonware.com Fri Jul 25 07:21:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 13:21:42 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> <216dcee8-ad3d-4ae1-ac4a-4f4819775c7e@d1g2000hsg.googlegroups.com> Message-ID: Ben Sizer wrote: > In theory, yeah. In practice, if his compiler was somehow not > respecting that, then a quicker fix is to enclose the #include than to > do individual prototypes. Admittedly that might obscure the problem > rather than solve it. Well, I'd say that the should in You should put the extern block around the #include call rather than individual functions, as surely the C calling convention should apply to everything within. makes it look way too much like "this is how you should use python.h" to be appropriate, given the earlier discussions in the thread, and that a casual inspection of the include files reveals that the included files contain exactly that thing. C compilers can be pretty stupid, indeed, but it's usually better to look for a solution that makes some sense (e.g. the wrong project settings) before blaming it all on deeper magic (it will look at this code if I put it here, but not if I put it there. hmm. must be a ley line over there. what if I add a comment?). From tjreedy at udel.edu Mon Jul 7 21:22:04 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 07 Jul 2008 21:22:04 -0400 Subject: "in"consistency? In-Reply-To: References: Message-ID: David C. Ullrich wrote: >>>> 'ab' in 'abc' > True 'a' in 'abc' works according to the standard meaning of o in collection. 'ab' in 'abc' could not work by that standard meaning because strings, as virtual sequences, only contain characters (length 1 strings). Among built-in collections, this limitation is unique to strings (and bytes, in 3.0). So in 2.3, 'in' was given a useful extension of meaning that is also unique to strings (and bytes). >>>> [1,2] in [1,2,3] > False [1,2] can be an member of tuples, lists, dicts and other general collections. [1,2] in collection therefore has that meaning, that it is a single element of collection. Extending the meaning would conflict with this basic meaning. > Is there a reason for the inconsistency? I would > have thought "in" would check for elements of a > sequence, regardless of what sort of sequence it was... It is not an inconsistency but an extension corresponding to the limitation of what an string element can be. Terry J. Reedy From mrkafk at gmail.com Tue Jul 1 05:36:53 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Tue, 01 Jul 2008 11:36:53 +0200 Subject: Embedding Python Message-ID: Hello everyone, I'm trying to embed Python interpreter in C code, but in a specific way: loading compiled bytecode into a memory location and executing it (don't ask why, complicated reasons). PyImport_ExecCodeModule seems like obvious candidate, docs say: "Given a module name (possibly of the form package.module) and a code object read from a Python bytecode file or obtained from the built-in function compile(), load the module." Code: ---cut--- #include #include #include #include #include int load_file(char *fname, unsigned char** result) { int size = 0; FILE *f = fopen(fname, "rb"); if (f == NULL) { *result = NULL; return -1; } fseek(f, 0, SEEK_END); size = ftell(f); *result = (unsigned char *) malloc(size+1); fseek(f, 0, SEEK_SET); size = fread(*result, sizeof(unsigned char), size, f); return size; } int main(int argc, char **argv) { int size; unsigned char *python_code; PyObject *mainobj; size = load_file("multiply.pyc", &python_code); Py_Initialize(); mainobj = PyImport_ExecCodeModule("multiply", (PyObject *) python_code); Py_Finalize(); } ---cut--- Compiling it following way works fine: ${CC} testit.c -g -o testit -I/usr/include/python2.4 -lpython2.4 -lm -lutil -lpthread -ldl -L/usr/lib/python2.4/config However, the damn thing crashes on this call: 33 mainobj = PyImport_ExecCodeModule("multiply", (PyObject *) python_code); (gdb) n Program received signal SIGSEGV, Segmentation fault. 0x0804e7f6 in PyImport_ExecCodeModuleEx () The .pyc file woks just fine in Python interpreter: >>> import multiply >>> multiply.multiply() The result of 12345 x 6789 : 83810205 83810205 >>> What I am doing wrong? Please help. From sysprv at gmail.com Mon Jul 7 08:39:10 2008 From: sysprv at gmail.com (sysprv) Date: Mon, 7 Jul 2008 05:39:10 -0700 (PDT) Subject: Python with Ecmascript References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <8ek074tia4l47tcfo6tqfo9huv2hb68hkt@4ax.com> <7eaf458d-b355-4112-a947-b2b7fe0d1f8d@s50g2000hsb.googlegroups.com> Message-ID: On Jul 7, 9:23?am, "jiri.zahra... at gmail.com" wrote: > On 7 ?ec, 08:21, alex23 wrote: > > > On Jul 7, 12:31 am, "jiri.zahra... at gmail.com" > > > wrote: > > > I personally does not like COM solution. I prefer some simple library > > > but may be it is just a hope. > > > Still looking for better solution ... > > JZ How about using Jython and Rhino [http://www.mozilla.org/rhino/] ? Could be worth your while, if you could live with coding for an older version of the Python spec. /sysprv From stef.mientki at gmail.com Mon Jul 28 14:40:42 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 28 Jul 2008 20:40:42 +0200 Subject: how to upload files to "google code" filesection ? In-Reply-To: <7f6182a3-4504-4239-8239-673a7e4bfefd@s50g2000hsb.googlegroups.com> References: <7f6182a3-4504-4239-8239-673a7e4bfefd@s50g2000hsb.googlegroups.com> Message-ID: <488E12AA.9090304@gmail.com> Mike Driscoll wrote: > On Jul 26, 12:43 pm, Stef Mientki wrote: > >> hello, >> >> In a program I want to download (updated) files from google code (not >> the svn section). >> I could find a python script to upload files, >> but not for downloading. >> >> Anyone has a hint or a solution ? >> >> thanks, >> Stef Mientki >> > > You should be able to use urllib to do that. The following link has a > recipe: > > http://code.activestate.com/recipes/496685/ > thanks Mike, I already found an even simpler solution (that works) filename, header = urllib.urlretrieve (url) > If you need to search Google Code, there's an API that appears to be > exposed through their gdata module. > Do you have perhaps a more specific link ? I saw the Google API's, but its'quit large / complex, so I couldnt find it there. cheers, Stef > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > From bdesth.quelquechose at free.quelquepart.fr Mon Jul 21 05:32:47 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 21 Jul 2008 11:32:47 +0200 Subject: Python Written in C? In-Reply-To: References: Message-ID: <488473b7$0$3470$426a74cc@news.free.fr> giveitawhril2008 at gmail.com a ?crit : (snip clueless nonsense) Surely a troll... No one on earth can be *that* clueless. From frankrentef at yahoo.com Thu Jul 24 10:04:50 2008 From: frankrentef at yahoo.com (frankrentef) Date: Thu, 24 Jul 2008 07:04:50 -0700 (PDT) Subject: Python / PAMIE Message-ID: Can someone help with a PAMIE issue? I'm new to Python / PAMIE and they seem like great tools but to be honest I'm finding that no responses to questions can be found (Experts Exchange, etc.) I'm hoping this will be the place. I tried to duplicate the authors "ie.writeScript" function shown at http://showmedo.com/videos/video?name=pythonMarchettiPamie3&fromSeriesID=25 I get "Attribute not found." I found one reference to where the command was written as "ie.scriptWrite" but that does not work either. I've emailed the author, Experts Exchange and other sites with ZERO responses. Can someone PLEASE assist? THNX From bignose+hates-spam at benfinney.id.au Wed Jul 16 08:16:41 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jul 2008 22:16:41 +1000 Subject: How can i use a variable without define it ? References: <87k5fm2p1x.fsf@benfinney.id.au> <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> <87fxqa2mu0.fsf@benfinney.id.au> <5dd91053-d239-4ff1-b693-d6afedf6bf24@x35g2000hsb.googlegroups.com> Message-ID: <87bq0y2fdi.fsf@benfinney.id.au> zhw writes: > On 7?16?, ??5?35?, Ben Finney > wrote: > > What problem are you trying to solve? > > I an sorry, I can't tell you. Perhaps I'm not being clear: What *programming* problem are you trying to solve? I ask because it seems you are focussed to much on some specific method, when it is very likely that your problem is better solved using different methods. > If you can't give a solution, just ignore it! I *did* give a solution. If that doesn't work for you, please tell us more about the problem so we can provide better solutions. -- \ ?Say what you will about the Ten Commandments, you must always | `\ come back to the pleasant fact that there are only ten of | _o__) them.? ?Henry L. Mencken | Ben Finney From asma61 at dsl.pipex.com Sun Jul 27 13:21:43 2008 From: asma61 at dsl.pipex.com (DaveM) Date: Sun, 27 Jul 2008 18:21:43 +0100 Subject: Rant (was Re: x*x if x>10 References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> Message-ID: On Sun, 27 Jul 2008 16:41:19 +0200, "Diez B. Roggisch" wrote: >You obviously aren't aware of the pitfalls regarding the mis-use of or >and and for this usage. Well, yes, I am (and the way around the problem), but as its never caught me out (so far), I hadn't considered it. >Can you tell us what you mean by "several names of one object"? You mean >this? > >a = range(10) >b = a > >id(a) == id(b) > > >? Passing references instead of values is an extremely important concept >of many languages, without it you would end up copying most of the time. OK. I've obviously been thinking about things the wrong way. In Forth you pass the memory address around, and presumably that's essentially what's happening when you pass a reference. The problem is, I get caught frequently in this situation: a = [1,2,3] def foo(x): do_something_with_x return x ... Then when I call foo(a), a gets changed. It just isn't the effect I expect from changing a local. DaveM From heikki at osafoundation.org Wed Jul 23 14:42:38 2008 From: heikki at osafoundation.org (Heikki Toivonen) Date: Wed, 23 Jul 2008 11:42:38 -0700 Subject: Undocumented Python 2.6 change: Py_None vs NULL when C implementation raises exception Message-ID: I was debugging M2Crypto function written in C which changed behavior between Python 2.6 and earlier Python versions. In an error condition the function was supposed to raise exception type A, but with 2.6 it raised type B, and further, there was no string value for the exception. I tracked this down to the C code incorrectly returning Py_None when it should have returned NULL. Changing the C code to return NULL made it behave correctly in 2.6. I don't know how common a mistake it is to return Py_None when NULL should have been returned, but it might be worth a note in the list of changes for 2.6 that this behavior changed, don't you think? -- Heikki Toivonen From fredrik at pythonware.com Wed Jul 16 09:20:23 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 15:20:23 +0200 Subject: bad recursion, still works In-Reply-To: <20cba7ab-72d2-4c7b-8f3f-48f39eaf9625@m3g2000hsc.googlegroups.com> References: <20cba7ab-72d2-4c7b-8f3f-48f39eaf9625@m3g2000hsc.googlegroups.com> Message-ID: Jeff wrote: > Is this avoidable by using a call to list() in the definition instead? No. Default values are *always* evaluated when, and only when, the "def" statement is executed; see: http://docs.python.org/ref/function.html Also note that "def" is an executable statement in Python, and that default arguments are evaluated in the "def" statement's environment. If you execute "def" multiple times, it'll create a new function object (with freshly calculated default values) each time. ::: The workaround is, as others have mentioned, to use a placeholder value instead of modifying the default value. None is a common value: def myfunc(value=None): if value is None: value = default() # go on an modify value If you need to handle arbitrary objects (including None), you can use a sentinel object: sentinel = object() def myfunc(value=sentinel): if value is sentinel: value = default() (in older code, written before "object" was introduced, you sometimes see things like "sentinel = ['placeholder']" used to create a non-false object with a unique identity; [] creates a new list every time it is evaluated.) ::: Finally, it should be noted that more advanced Python code often uses this mechanism to its advantage; for example, if you create a bunch of UI buttons in a loop, you might try something like: for i in range(10): def callback(): print "clicked button", i UI.Button("button %s" % i, callback) only to find that all callbacks print the same value (most likely 9, in this case). The reason for this is that Python's nested scopes bind to variables, not object values, so all callback instances will see the current (=last) value of the "i" variable. To fix this, use explicit binding: for i in range(10): def callback(i=i): print "clicked button", i UI.Button("button %s" % i, callback) The "i=i" part binds a local variable "i" to the *current* value of the outer variable "i". Two other uses are local caches/memoization; e.g. def calculate(a, b, c, memo={}): try: value = memo[a, b, c] # return already calculated value except KeyError: value = do calculation on a, b, c memo[a, b, c] = value # update the memo dictionary return value (this is especially nice for certain kinds of recursive algorithms) and, for highly optimized code, local rebinding of global names: def this_one_must_be_fast(x, sin=math.sin, cos=math.cos): ... Hope this helps more than it confuses. From misceverything at gmail.com Sun Jul 20 11:27:41 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Sun, 20 Jul 2008 08:27:41 -0700 (PDT) Subject: Web Server Message-ID: As part of a Python app I wrote recently (for Windows), I would like to give the option of an HTTP (HTTPS if possible, but not necessary) front end, which would then call some existing python scripts. My question is - I know I can write a simple HTTP server in Python, but if there's something simple already out there, I'd prefer to just use that. Basically all I need is a simple (i.e. preferably a single executable) web server that can serve up my content - the only thing I want the user to be able to configure is the port the web server listens on (or ports if HTTPS also), and the location of the HTML files... thanks in advance for your help. From fredrik at pythonware.com Wed Jul 23 03:13:04 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 09:13:04 +0200 Subject: Proper way to query user and group database on a Unix host? In-Reply-To: <1216792038.7380.7.camel@mmaccana-laptop> References: <1216792038.7380.7.camel@mmaccana-laptop> Message-ID: Mike MacCana wrote: > What's the proper way to query the passwd and group database on a Unix > host? > > I'd like to fetch the users in a group (obviously from name services), > but my many varied searches can't find any reference of someone ever > looking up users on a Unix system, just NT. Weird, I know. the relevant modules are "pwd", "spwd" and "grp"; see: http://docs.python.org/lib/unix.html From spandanagella at gmail.com Thu Jul 17 06:18:45 2008 From: spandanagella at gmail.com (spandana g) Date: Thu, 17 Jul 2008 18:18:45 +0800 Subject: Fwd: Hello In-Reply-To: References: Message-ID: Hello , Traceback (most recent call last): File "C:\Python25\hadi_yahoo.py", line 12, in file_source.write(urllib2.urlopen(req).read()) File "C:\Python25\lib\urllib2.py", line 124, in urlopen return _opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 387, in open response = meth(req, response) File "C:\Python25\lib\urllib2.py", line 498, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 425, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 506, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 999: Unable to process request at this time -- error 999 Previously i got the error which I have attached below when I use just urlopen . But now when I use this http request user_agent='Mozilla/3.0(compatible;MISE 5.5;Windows NT)' headers={'User-Agent':user_agent} req=urllib2.Request(url,None,headers) file_source.write(urllib2.urlopen(req).read() its still giving the error mentioned above .. Iam accessing the yahoo search engine .. link is "http://search.yahoo.com/search?n=20&p=ipod" I'm attaching the python file i have written just have a look and suggest me something that works for this query Thank You, Spandana. ---------- Forwarded message ---------- From: spandana g Date: Thu, Jul 3, 2008 at 2:52 PM Subject: HTTP request error with urlopen To: python-list at python.org Hello , I have written a code to get the page source of the google search page .. this is working for other urls. I have this problem with import re from urllib2 import urlopen string='http://www.google.com/search?num=20&hl=en&q=ipod&btnG=Search' file_source=file("google_source.txt",'w') file_source.write(urlopen(string).read()) page_content=file_source.readlines() Traceback (most recent call last) : File "C:/Python25/google.py", line 5,in file_source.write(urlopen(string).read()) File "C:\Python25\lib\urllib2.py", line 124 , in urlopen return__opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 387 , in open response =meth(req, response) File "C:\Python25\lib\urllib2.py", line 498 , in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 425, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 360, in __call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 506, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: Forbidden Actually urlopen is working for google labs sets page but not for the google.com and even I have same problem with wikipedia . Please let me know .. If any one of have any idea about this . Thank You, Spandana. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: hadi_yahoo.py URL: From adityashukla1983 at gmail.com Thu Jul 24 18:46:41 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Thu, 24 Jul 2008 17:46:41 -0500 Subject: file operations. Message-ID: <73045cca0807241546k3697a77cs999bad6d62867167@mail.gmail.com> Guys thanks for your previous help .I have a doubt again My text file is :- 0\9\10\11|0.50|c:\windows\apppatch/AcLayers.dll 0\9\10\11|0.50|c:\windows\apppatch/AcRedir.dll 0\9\10|0.66|c:\windows\apppatch/AcSpecfc.dll 0\9|0.83|c:\windows\apppatch/iebrshim.dll 0|0.92|c:\windows\apppatch/pcamain.sdb 0|0.92|c:\windows\apppatch/sysmain.sdb 0|0.93|c:\windows\apppatch/AcXtrnal.dll 0|0.97|c:\windows\apppatch/msimain.sdb 0|0.98|c:\windows\apppatch/AcRes.dll 0|0.98|c:\windows\apppatch/drvmain.sdb 0|0.98|c:\windows\apppatch/en-US/AcRes.dll.mui 0|0.99|c:\windows\apppatch/apihex86.dll 0|1.00|c:\windows\apppatch/AcGenral.dll now this is what happens >>> x=open("c:\\test2.txt","rb") >>> x.readline() '\n' ---? i am not able to understand why is new line character returned here >>> l =x.readline() >>> print l Also , because of this i am not able to extract the floating point values ie 0.50,0.50,0.66 respectively cause when i use the proposed solution given earlier data=[] for line in x: line=line.split("|") data.append(float(line[-2])) --> i am trying to get the floating point values from the back i receive this error message Traceback (most recent call last): File "", line 3, in d.append(float(line[-2])) IndexError: list index out of range Whereas the solution works well with the dummy text file which i have created which is a.txt jd|fj|dnv|jd|0.33|c:\\windows\\win32 shcbsbs|nscsjsj|0.93|hsbcjsnc x=open("a.txt","r") data=[] for line in x: line=line.split("|") data.append(float(line[-2])) print data 0.3300002,0.9300006 Please help me fix this problem Thanks in advance Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim_grove at sil.org Thu Jul 3 13:15:59 2008 From: tim_grove at sil.org (Tim Grove) Date: Thu, 03 Jul 2008 18:15:59 +0100 Subject: manipulating movie files with Python Message-ID: <486D094F.9000606@sil.org> I would like to write a python script which could take a movie file name (avi, mov, mpg) along with a start and stop time as parameters, and return to me a new movie file just containing that section of the original which I'm interested in. Is there a Python library which could already perform such magic? Thanks for any suggestions. Best regards, Tim From tjreedy at udel.edu Sun Jul 27 02:22:17 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 02:22:17 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > On Jul 26, 2:25 pm, Terry Reedy >> There is a lot of code you have not seen. Really. In informal code I >> use 's' and 'o' for 'self' and 'other'. I don't usually post such >> because it is not considered polite. So you have seen a biased sample >> of the universe. > > You take the name down to a single letter. As I suggested in an > earlier post on this thread, why not take it down to zero letters? Because 1 letter is legal now, while no letters (already proposed and rejected) is a major change and breakage of current simplicity and consistency for zero functional benefit. From grahn+nntp at snipabacken.se Mon Jul 7 13:43:16 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 7 Jul 2008 17:43:16 GMT Subject: The Yield statement References: Message-ID: On Sun, 6 Jul 2008 00:29:26 -0700, Mark Tolonen wrote: > > "inhahe" wrote in message > news:z6_bk.24960$AJ6.1423 at bignews8.bellsouth.net... ... >> note that this won't work; >> def f(): >> for x in xrange(10): >> for y in xrange(10): >> yield (x,y) >> >> yield just doesn't work right with multiple levels of loops. i had to >> discover that the hard way. > > Huh? Works fine: [...] Yes -- as is expected. Yield would be much less useful if it only work with strange restrictions on the structure of the function containing it. As far as I can tell, you can pick any function, stick zero or more yield statements into it, and it will work as expected: hit a yield, and you get another value for your sequence. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From peter.bulychev at gmail.com Tue Jul 1 14:54:29 2008 From: peter.bulychev at gmail.com (Peter Bulychev) Date: Tue, 1 Jul 2008 22:54:29 +0400 Subject: convert unicode characters to visibly similar ascii characters In-Reply-To: <486A7BB5.3000501@shopzeus.com> References: <486A7BB5.3000501@shopzeus.com> Message-ID: Thank you for you answer. If you only want this to work for a subset, please define that subset. Actually, I want to convert only punctuations (dots, commas, hyphens and so on). -- Best regards, Peter Bulychev. -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Mon Jul 14 18:32:33 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 14 Jul 2008 18:32:33 -0400 Subject: Bug when using with_statement with exec In-Reply-To: References: Message-ID: <16651e80807141532k391b452cmc5eb6deba38bbdbd@mail.gmail.com> On Mon, Jul 14, 2008 at 6:00 PM, Matimus wrote: > If I create a function by using exec on a string and _don't_ end the > string with a new-line it will work just fine unless I "from > __future__ import with_statement". [snip] > I searched python's issue database and didn't see anything similar to > this. If there is already an issue related to this, please point me to > it... or better yet, let me know how you found it. Possibly related to http://bugs.python.org/issue1184112, and/or http://bugs.python.org/issue501622? Since you asked, I found it by googling the words "python exec with newline". The second item was an email on Python-Dev with a similar bug and referencing an issue id. The comments on that issue led to the other one. -- Jerry From martin at v.loewis.de Mon Jul 7 18:55:16 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 08 Jul 2008 00:55:16 +0200 Subject: Memory error while saving dictionary of size 65000X50 using pickle In-Reply-To: References: Message-ID: <48729ed5$0$12966$9b622d9e@news.freenet.de> > I didn't have the problem with dumping as a string. When I tried to > save this object to a file, memory error pops up. That's not what the backtrace says. The backtrace says that the error occurs inside pickle.dumps() (and it is consistent with the functions being called, so it's plausible). > I am sorry for the mention of size for a dictionary. What I meant by > 65000X50 is that it has 65000 keys and each key has a list of 50 > tuples. [...] > > You exmple works just fine on my side. I can get the program import pickle d = {} for i in xrange(65000): d[i]=[(x,) for x in range(50)] print "Starting dump" s = pickle.dumps(d) to complete successfully, also, however, it consumes a lot of memory. I can reduce memory usage slightly by a) dumping directly to a file, and b) using cPickle instead of pickle i.e. import cPickle as pickle d = {} for i in xrange(65000): d[i]=[(x,) for x in range(50)] print "Starting dump" pickle.dump(d,open("/tmp/t.pickle","wb")) The memory consumed originates primarily from the need to determine shared references. If you are certain that no object sharing occurs in your graph, you can do import cPickle as pickle d = {} for i in xrange(65000): d[i]=[(x,) for x in range(50)] print "Starting dump" p = pickle.Pickler(open("/tmp/t.pickle","wb")) p.fast = True p.dump(d) With that, I see no additional memory usage, and pickling completes really fast. Regards, Martin From elessar at nienna.org Fri Jul 25 12:09:52 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 25 Jul 2008 10:09:52 -0600 Subject: Execution speed question In-Reply-To: <8c652342-fc15-43bc-bb6c-445e3ca7755f@u36g2000pro.googlegroups.com> References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> <4889e5bc$1@news2-rz-ap.ethz.ch> <8c652342-fc15-43bc-bb6c-445e3ca7755f@u36g2000pro.googlegroups.com> Message-ID: <4889FAD0.7010803@nienna.org> Iain King wrote: > On Jul 25, 4:22 pm, Matthew Fitzgibbons wrote: >> It seems like the probability calculation applies to all three equally, >> and can therefore be ignored for the simulations. > > The probability affects (1) more. My reasoning for this being: as > probability gets lower the number of times you have to loop over the > list increases. (1) always loops over the full list, but with each > successive iteration (2) and (3) are looping over smaller and smaller > lists. In the end this adds up, with (1) becoming slower than (2), > even though it starts out quicker. > > Iain > -- > http://mail.python.org/mailman/listinfo/python-list > I meant the _calculation_ of the probability affects all three equally, not the value itself. As your simulations show, different probabilities affect the algorithms differently; I'm talking about the algorithm to arrive at the probability value. -Matt From bearophileHUGS at lycos.com Sat Jul 5 09:29:08 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 5 Jul 2008 06:29:08 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Paddy: > You could argue that if the costly RE features are not used then maybe > simpler, faster algorithms should be automatically swapped in but .... Many Python implementations contains a TCL interpreter. TCL REs may be better than Python ones, so it can be interesting to benchmark the same RE with TCL, to see how much time it needs. If someone here knows TCL it may require to write just few lines of TCL code (used through tkinter, by direct call). Bye, bearophile From none at this.time Wed Jul 9 11:04:42 2008 From: none at this.time (The Pythonista) Date: Wed, 09 Jul 2008 11:04:42 -0400 Subject: Python equivalent of call/cc? Message-ID: Yesterday, I was hacking around a bit, trying to figure out how to implement the semantics of call/cc in Python. Specifically, I wanted to translate this Scheme code to equivalent Python: #### (define theContinuation #f) (define (test) (let ((i 0)) (call/cc (lambda (k) (set! theContinuation k))) (set! i (+ i 1)) i)) (test) (theContinuation) (theContinuation) #### Incidentally, those last three lines evaluate to 1, 2, and 3, respectively. The best Python translation I could come up with was something like this (targeted at Python 2.5): #### import inspect theContinuation = None def call_cc (f): f (inspect.currentframe().f_back) def invoke (c): exec c.f_code in c.f_globals, c.f_locals def test(): i = 0 call_cc (lambda k: globals().update({'theContinuation' : k })) i = i + 1 print i test() invoke (theContinuation) invoke (theContinuation) #### Now, this code is wrong on a number of levels [I am indeed aware of exactly how ugly that lambda is...], but, in particular, my continuations / stack frames don't seem to be resuming at the right point. I'd expect invoke (theContinuation) to restart on the line immediately following call_cc, but it does not. Not surprisingly, the output is also wrong. (I get 1, 1, and 1 rather than 1, 2, and 3.) Can anyone help me by, perhaps pointing out some silly error I made? Failing that, can someone show me a working implementation of call/cc (preferably based on some form of stack inspection)? Thanks! -- code.py: A blog about life, the universe, and Python http://pythonista.wordpress.com ** Posted from http://www.teranews.com ** From kotecha.ravi at googlemail.com Mon Jul 21 12:01:10 2008 From: kotecha.ravi at googlemail.com (Ravi Kotecha) Date: Mon, 21 Jul 2008 09:01:10 -0700 (PDT) Subject: Getting the name of a variable which was used as a function parameter. Message-ID: <9e2e64db-d594-408d-9418-b17133f23204@27g2000hsf.googlegroups.com> Hi guys, I thought this was pretty cool and since I spent 30 mins or so goggling before giving up and figuring out myself I thought I'd share it with you. >>> def a(a): ... for k,v in sys._getframe(1).f_locals.items(): ... if id(v) == id(a): ... print k ... >>> hello = 123 >>> a(hello) hello ## pretty cool. It's totally useless but I wanted to do it for logging purposes. It will still return weird results if you have two labels pointing to the same object but I'm not sure how to get around that, any ideas? Regards, Ravi Kotecha From steven at REMOVE.THIS.cybersource.com.au Tue Jul 29 05:27:41 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 09:27:41 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: On Tue, 29 Jul 2008 01:37:45 -0700, Carl Banks wrote: > On Jul 28, 8:15 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: >> > On Jul 28, 10:00 am, Steven D'Aprano > > cybersource.com.au> wrote: >> >> Cutting to the crux of the discussion... >> >> >> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: >> >> > I want something where "if x" will do but a simple explicit test >> >> > won't. >> >> >> Explicit tests aren't simple unless you know what type x is. If x >> >> could be of any type, you can't write a simple test. Does x have a >> >> length? Is it a number? Maybe it's a fixed-length circular length, >> >> and the length is non-zero even when it's empty? Who knows? How many >> >> cases do you need to consider? >> >> > Use case, please. I'm asking for code, not arguments. Please give >> > me a piece of code where you can write "if x" that works but a simple >> > explicit test won't. >> >> I gave you a piece of code, actual code from one of my own projects. If >> you wouldn't accept that evidence then, why would you accept it now? > > I would accept as "evidence" something that satisfies my criteria, which > your example did not: it could have easily (and more robustly) been > written with a simple explicit test. Only at the cost of completely ignoring the functional requirements and changing the API. In other words: you ignore my code, and invent your own imaginary code that does something completely different, then say that this imaginary code is better. And I question your assertion that a "simple explicit test" is more robust. Where's your evidence for that? > I am looking for one that can't. If you are writing code that needs to do the right thing with arbitrary types, then your so-called "simple explicit tests" simply can't work. If your code isn't expected to deal with arbitrary types, then you've got an excellent chance that it will work, because you know what types to expect. Until somebody passes a type that you didn't expect, and your code fails because it makes assumptions about the object. If you know that you only get lists, then "if len(x)!=0" is a perfectly good test (apart from being longer to type, harder to read, and slower to execute than "if x"). It will work so long as you only get objects where a length of zero is equivalent to being false. That's a good assumption to make, but it is an *unnecessary* assumption. Any reasonable object you get will know if it is false/nothing or true/something, so why make any assumptions? Just ask the object. It knows. > You keep bringing up this notion of "more complex with no benefit", > which I'm simply not interested in talking about that at this time, and > I won't respond to any of your points. Of course not. > I am seeking the answer to one > question: whether "if x" can usefully do something a simple explicit > test can't. "if x" is completely type agnostic. You can pass an object of any type to it, and it will work. (Excluding objects with buggy methods, naturally.) Try doing that with one of your so-called "simple explicit tests". -- Steven From __peter__ at web.de Thu Jul 3 04:44:54 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 Jul 2008 10:44:54 +0200 Subject: How to pickle bound methods References: Message-ID: srinivasan srinivas wrote: Please don't top-post. > No. It does not work. That's what I said. Try class A(object): @staticmethod def alpha(): print "Hello" alpha = A.alpha Peter From bignose+hates-spam at benfinney.id.au Wed Jul 2 09:25:24 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 02 Jul 2008 23:25:24 +1000 Subject: Email Validation with domain References: Message-ID: <873ams770b.fsf@benfinney.id.au> Sallu writes: > validateEmail(msg) i wrote a script above it works fine Actually, no. It rejects a great many email addresses that are valid. > but it does not check for valid domain like .com .org .in how to > validate with domain To validate a domain for delivery of email, check with the DNS by requesting the A or MX record for that domain. To validate an email address, check with the mail server for that domain by sending a message to the address. Neither of them should be "validated" by a regular expression. Please refer to RFC 3696 described as "Recommended techniques for applications checking or manipulating domain and other internet names". -- \ ?Pinky, are you pondering what I'm pondering?? ?Wuh, I think | `\ so, Brain, but wouldn't anything lose its flavor on the bedpost | _o__) overnight?? ?_Pinky and The Brain_ | Ben Finney From sublesi.try at gmail.com Sat Jul 26 11:32:23 2008 From: sublesi.try at gmail.com (lindi) Date: Sat, 26 Jul 2008 08:32:23 -0700 (PDT) Subject: Find Sofas Message-ID: <1edf7715-a312-40c8-8596-271c1d18df64@p10g2000prf.googlegroups.com> Huge Selections at Great Prices The Convenience of OneCart! http://good-furniture-care.page.tl/ From __peter__ at web.de Sat Jul 19 05:44:20 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 19 Jul 2008 11:44:20 +0200 Subject: Question References: Message-ID: perl_wizard at manx.net wrote: > Why is Perl so much better than python? Because you have the video: http://mail.python.org/pipermail/python-list/2004-March/253370.html From larry.bates at websafe.com` Tue Jul 8 20:01:26 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 08 Jul 2008 19:01:26 -0500 Subject: plugins using cvs/distutils? In-Reply-To: References: Message-ID: Deacon wrote: > Hi. I have an open-source application development environment that I > would like to enable an automated package download system for (like > downloadable plugins), using sourceforge as its repository. My > software will have a menu-based popup window, that will list the > packages (Applications) available through the project distribution > page. If a user selects a package from this window, it should be > automatically retrieved and installed by the development environment. > My software already has a system for automatically recognizing and > deploying new packages, so I'm only asking for help with distribution > logistics, I think. > > I'm thinking that I will use the built-in ftplib to list and retrieve > the files (but I'm not sure yet where to look), and then the distutils > should probably be used in a standardized manner to actually install > the packages, right? I've established a CVS, but I'm not aware of any > built-in-python tools for managing the CVS, and I would rather not add > any new user-has-to-download-dependencies for this. Is there an easier > or alternative advisable approach? I have a linux box, should I be > using it to build all of the platform versions? Any advice would be > much appreciated, this is my first distribution project > (sourceforge.net/projects/spade). > > Thanks a bunch, > > Deacon You might consider distributing as eggs and use setuptools/easyinstall to do this for you. -Larry http://peak.telecommunity.com/DevCenter/setuptools From teuben at verizon.net Mon Jul 28 23:26:45 2008 From: teuben at verizon.net (Peter Teuben) Date: Tue, 29 Jul 2008 03:26:45 GMT Subject: exec(code) not allowing import on top level? Message-ID: if I define a simple string code, with the following contents: import math def foo(x): return math.sqrt(x) and i run it using exec(code) in python, math is not known. But when I recode the string as: def foo(x): import math return math.sqrt(x) it works fine. That seemed like an inconsistency, since it works fine otherwise, as expected. It's easy to work around, but just odd to find this out. thanks peter From darcy at druid.net Sat Jul 26 10:11:13 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 26 Jul 2008 10:11:13 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87fxpxw0ku.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> Message-ID: <20080726101113.07d77b0a.darcy@druid.net> On Sat, 26 Jul 2008 09:45:21 +0200 Torsten Bronger wrote: > Of course, "self" would have to become a reserved word. You could > say that this may break some code, but I don't see much freedom Isn't this a showstopper all by itself? > removed from the language. After all, being a German, I still can't > write "F?r i in range(10)". ;-) Yes, this is why good languages try to limit the number of reserved words as much as possible. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From larry.bates at websafe.com` Wed Jul 23 08:11:26 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 23 Jul 2008 07:11:26 -0500 Subject: os.walk question In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Lanny wrote: > >> How would one make a list of the files in the top directory >> using os.walk. >> >> I need to pick a random file from said list. > > if you want a list of files from a single directory, use listdir, not walk: > > >>> import os, random > >>> random.choice(os.listdir("/")) > 'python25' > > > Or use glob. import glob random.choice([f for f in glob.glob(root, "*")]) -Larry From rhamph at gmail.com Wed Jul 30 13:54:51 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 30 Jul 2008 10:54:51 -0700 (PDT) Subject: proxy class and __add__ method References: <18715799.post@talk.nabble.com> Message-ID: <3d59a908-f585-4ff5-ad37-bb48579cc9cb@a21g2000prf.googlegroups.com> On Jul 29, 10:23?pm, "Gabriel Genellina" wrote: > En Tue, 29 Jul 2008 13:13:51 -0300, Magnus Schuster ? > escribi : > > > > > Hello, > > I have written the following small proxy class which I expect to pass all > > function calls to the 'original' object: > > > --- BEGIN --- > > class proxy(object): > > ? ? def __init__( self, subject ): > > ? ? ? ? self.__subject = subject > > ? ? def __getattr__( self, name ): > > ? ? ? ? return getattr( self.__subject, name ) > > > prx_i=proxy(1) > > print hasattr(prx_i,'__add__') > > j=prx_i.__add__(1) > > k=prx_i+1 > > --- END --- > > > Actually the "hasattr(prx_i,'__add__')" returns "True" as expected, and > > "j=prx_i.__add__(1)" sets j=2. > > > But "k=prx_i+1" raises a > > : unsupported operand type(s) for +: 'proxy' > > and 'int'. > > > How is this addition different from the previous line "j=..."? And how ? > > can I > > modify the proxy class so that all methods are passed on, which are not > > explicitly overloaded? > > __magic__ methods on new style classes are searched in the class, *not* in ? > the instance. prx_i+1 looks for __add__ in type(prx_i), that is, in the ? > proxy class. This much is true. > Try implementing a similar __getattr__ method in a metaclass. But I don't think they use __getattr__.. they bypass it. Effectively they catch the assignment to __add__ and cache it. You'll have to always define it in the class and have it be ineffectual in some cases. From elessar at nienna.org Sat Jul 26 00:47:28 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 25 Jul 2008 22:47:28 -0600 Subject: 2d graphics - what module to use? In-Reply-To: <5035d4cb-1976-47d5-8887-4e8381407a7b@m44g2000hsc.googlegroups.com> References: <5035d4cb-1976-47d5-8887-4e8381407a7b@m44g2000hsc.googlegroups.com> Message-ID: <488AAC60.8020903@nienna.org> sturlamolden wrote: > On Jul 25, 8:13 am, Pierre Dagenais wrote: >> What is the easiest way to draw to a window? I'd like to draw something >> like sine waves from a mathematical equation. >> Newbie to python. > > For mathematica equations, NumPy and matplotlib is probably the best > option. I prefer to embed matplotlib in wxPython. wxAgg is an > excellent backend. > > For more general 2D graphics, there are several options, including: > > - pygame (uses SDL) > - aggdraw module > - pycairo > - pyopengl > - wxPython's device context (ditto for other GUI libraries) > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > If you're using wx, there is also wx.lib.plot, which I found to be _much_ faster than matplotlib in my application, especially when resizing. -Matt From siona at chiark.greenend.org.uk Mon Jul 28 10:00:23 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 28 Jul 2008 15:00:23 +0100 (BST) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <488d86e2$1@news2-rz-ap.ethz.ch> <488dc3eb$1@news2-rz-ap.ethz.ch> Message-ID: Suresh Pillai wrote: > [ ... ] is >there any way to iterate over the items in a set other than converting to >a list or using the pop() method. Er, how about directly iterating over the set? -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From wtanksleyjr at gmail.com Tue Jul 29 15:42:07 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Tue, 29 Jul 2008 12:42:07 -0700 (PDT) Subject: iterating "by twos" References: Message-ID: kj wrote: > Is there a special pythonic idiom for iterating over a list (or > tuple) two elements at a time? I don't know of one, and I shouldn't be answering, but the following should work: def gulp_two(items): for i,j in zip(items[0::2], items[1::2]): yield (i,j) Let's see... >>> list(gulp_two(range(10))) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] Okay, it works. -Wm From kyosohma at gmail.com Fri Jul 18 16:21:33 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 18 Jul 2008 13:21:33 -0700 (PDT) Subject: Distributing Python App References: <072bf39b-d700-482e-ab59-36840e21e83e@a70g2000hsh.googlegroups.com> Message-ID: On Jul 18, 2:35?pm, KDawg44 wrote: > Hi, > > I am very new to Python but find it very interesting (from what I know > of it) and am considering writing an application. ?However, I have a > question regarding distribution of the app once it is done. ?Is there > a way to package everything a user needs to run the app or will they > have to install Python their machine? ?This is probably an obvious > question but most development I do is for administrative tasks on > servers and such, not usually development of an app for someone else. > > Thanks for your help. > > Kevin There is a variety of packaging programs. For Windows, you can use py2app and py2exe. I think the former can also be used for Mac and maybe Linux. If you are doing it on Windows, I would recommend packaging it with one of those and then using something like Inno Setup to create an installer. Mike From ggpolo at gmail.com Thu Jul 3 16:54:57 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 3 Jul 2008 17:54:57 -0300 Subject: controlling the windows In-Reply-To: <153e45a5-a161-4305-be6f-0fd56aee37e0@f1g2000prb.googlegroups.com> References: <153e45a5-a161-4305-be6f-0fd56aee37e0@f1g2000prb.googlegroups.com> Message-ID: On Thu, Jul 3, 2008 at 4:16 PM, varun chadha wrote: > i am developing an application using Tkinter where 'next' button > takes to another window and removes the first one from screen and > 'back' button bring me back to previous window and so on. > though i am able to move from one window to another but is unable to > remove the previous one from the screen. does anybody have a idea how > to do away with this problem. There are several solutions to this. You could just pack_forget the another window and pack a new one in its place. I have just prepared a simple Wizard, you can take a look at it here: http://code.google.com/p/python-ttk/wiki/ttkWizard and you will notice that it uses ttk. If you already use tk 8.5, and tkinter compiled against it, then ttk is available, otherwise you have to install tile or compile tkinter with tk 8.5 (python 2.6b1 includes tk 8.5.2 in the windows build). To use the ttk widgets you will need a wrapper and you will find one here: http://code.google.com/p/python-ttk/ > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From dwahler at gmail.com Tue Jul 22 00:39:58 2008 From: dwahler at gmail.com (David Wahler) Date: Mon, 21 Jul 2008 23:39:58 -0500 Subject: Time Complexity of String Operations In-Reply-To: References: Message-ID: On Mon, Jul 21, 2008 at 10:31 PM, youtoo wrote: > It has been extensively discussed the time complexity (quadratic) of > string concatenation (due to string's immutability). Actually, it is roughly linear, at least for reasonable string lengths: $ python -V Python 2.5.2 $ python -mtimeit -s "n=1000; a='#'*n" "a+a" 1000000 loops, best of 3: 1 usec per loop $ python -mtimeit -s "n=10000; a='#'*n" "a+a" 100000 loops, best of 3: 5.88 usec per loop $ python -mtimeit -s "n=100000; a='#'*n" "a+a" 10000 loops, best of 3: 59.8 usec per loop Repeatedly constructing a string by appending a constant number of characters at a time, however, is quadratic in the final string length (although VM optimizations may affect this). > But what is: > > == the time complexity of string indexing? Is it constant? Yes. > == the time complexity of string slicing? Is it O(K) with K the > slice's length? I suspect so, since the time is dominated by the time taken to copy the data into a new string object. > How are strings stored in Python? As arrays? As linked lists? Arrays; see Include/stringobject.h in the Python source distribution. -- David From fetchinson at googlemail.com Fri Jul 11 14:35:36 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Fri, 11 Jul 2008 11:35:36 -0700 Subject: Python with Ecmascript In-Reply-To: <7HMdk.14$6O4.10@trnddc06> References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <486fe241$0$867$ba4acef3@news.orange.fr> <7HMdk.14$6O4.10@trnddc06> Message-ID: >>>NJSModule? >>>http://en.wikipedia.org/wiki/NJS > >> This seems to be very good indeed. Just downloaded njs but the only >> njsmodule version I could find was for python 2.1. Does anyone have a >> recent copy? > > 1. You might ask here: > http://lists.njs-javascript.org/cgi-bin/mailman/listinfo/users > > 2. Did you try to compile it? > Is there anything obviously 2.5 incompatible? Well, so far I couldn't even compile njs (./configure complains about HOST setting or some such) so haven't looked at njsmodule yet. Thanks for the suggestions! Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From mva.led at gmail.com Mon Jul 28 01:05:47 2008 From: mva.led at gmail.com (Manuel Vazquez Acosta) Date: Mon, 28 Jul 2008 01:05:47 -0400 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: <488A2E72.6030802@activestate.com> References: <487E2BCE.30108@hughes.net> <488A2E72.6030802@activestate.com> Message-ID: <488D53AB.7090300@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Just test for maxint value: from sys import maxint if maxint >> 33: print "more than 32 bits" # probably 64 else: print "32 bits" Best regards, Manuel. Trent Mick wrote: > norseman wrote: >> >> > > I need to know if I'm running on 32bit or 64bit ... so far I haven't >> > > come up with how to get this info via python. sys.platform returns >> > > what python was built on ... but not what the current system is. >> > > >> > > I thought platform.uname() or just platform.processor() would have >> > > done it, but python returns an empty string on windows. Any ideas? > > If just for Windows I believe you can use the "PROCESSOR_ARCHITECTURE" > environment variable -- at least on NT-based Windows versions. > > Values are x86 (32-bit), IA64 (64-bit) and AMD64 (64-bit). > > Here is a "platinfo.py" module that might help if you need to do this > for other platforms: > > http://svn.openkomodo.com/openkomodo/view/openkomodo/trunk/util/platinfo.py > > > Cheers, > Trent > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkiNU6IACgkQI2zpkmcEAhi6sACgo1ZyGKCWtnBPLXr1EjgSq3V4 GEAAoL+zZStfGYaZxg/zYoUqk6UFa+oM =g+tz -----END PGP SIGNATURE----- From michele.simionato at gmail.com Thu Jul 10 09:10:35 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 10 Jul 2008 06:10:35 -0700 (PDT) Subject: python scalability References: Message-ID: <799d6ad1-8424-4b2a-96a6-6df9a24060d9@27g2000hsf.googlegroups.com> On Jul 10, 6:32?am, Tim Mitchell wrote: > Hi All, > > I work on a desktop application that has been developed using python and > GTK (seewww.leapfrog3d.com). ?We have around 150k lines of python code > (and 200k+ lines of C). We have bigger numbers than yours here (although not for a desktop application) and of course we have the problems of a large size application, but they have nothing to do with Python. The real problem are sociological, not language-related. Essentially, if a project takes 10+ years and 10+ people, with most of the people new, you have an issue, but this is independent from the language. Python is helping us at least because it is readable and the situation would be probably be worse with another language. But as I said the software development practices used are more important than the language in this context. From thomas.troeger.ext at siemens.com Thu Jul 17 09:57:51 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Thu, 17 Jul 2008 15:57:51 +0200 Subject: Python embedding question (2). References: Message-ID: > I'd say that PyGame could be a solution. > > Or otherwise you could do your own audio/graphics programming (you don't > tell us which OS you use, but there exist python modules that allow you > to do barebones graphics & sound programming on linux...). After some more reading I've stumbled over pyglet. Any experiences with it? It seems it does a lot of cool things, if anyone has used it more intensely I'd be happy to hear if the following things can be done: - Linux framebuffer (16, 24 bpp) display of 2d graphics with overlays (i.e. menues, contextual areas that pop up etc.). I don't have X on the embedded device, just the regular framebuffer. - alpha blending of several layers. - rendering of TTF fonts and unicode, for example display of arabic text (which renders from right to left) and mixed text support like in the unicode bidirectional algorithm. - hardware caching of bitmaps for faster graphics operations (needed for tool tips or similar tasks). I'll try to find that out myself (I'm pretty excited about the thing already ^^), but I'd be happy to hear of people who have used it already. Cheers, Thomas. From fredrik at pythonware.com Tue Jul 22 11:31:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 17:31:15 +0200 Subject: Is this a valid use of 'import'? In-Reply-To: References: Message-ID: Frank Millman wrote: > I know that when a module is imported the first time, it is > 'executed'. This normally entails setting up constants, classes, > functions, etc, that you want to make available to the importer. > > In this particular case, when it is executed, it does a whole lot > more. It reads in some parameters, establishes a socket connection, > starts a thread, and starts monitoring the socket using select.select. > It also exposes some functions that disguise the complexity of reading > from and writing to the socket. > > This enables me to write a 'client' program that look like this - > > --------------------------- > from Utils.client import * > > connect(userid='frank',pwd='') > cust = getRecord( > company='chagford',table='ArCustomers', > column='CustNo',value='A001') > print cust > close() > --------------------------- > > As you can see, it makes writing a client program very easy. > > Are there any problems with this approach? besides being fragile and not scalable and not thread-safe and incompatible with introspection tools and utterly surprising for people used to normal Python behaviour, and only marginally easier to write than, say: from Utils.client import Client c = Client() c.connect(userid='frank',pwd='') cust = c.getRecord( company='chagford',table='ArCustomers', column='CustNo',value='A001') print cust c.close() and some other problems that I cannot think of right now, you mean? From benjamin.kaplan at case.edu Sat Jul 26 23:07:24 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 26 Jul 2008 23:07:24 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <488BDC0A.50403@internetnowasp.net> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <488BDC0A.50403@internetnowasp.net> Message-ID: On Sat, Jul 26, 2008 at 10:23 PM, Marcus.CM wrote: > Well after reading some of these posts on "sacred python cow" on the "self" > , i would generally feel that most programmers > who started with C++/Java would find it odd. And its true, i agree > completely there should not be a need to put "self" into every single > member function. If you were writing an application and one of your classes > adds the same variable to each of its member function you would do away with > it too. > What could be done instead is :- > > 1. python should hardcode the keyword "self". So whenever this keyword is > used, it would automatically implied that it is > referring to a class scope variable. This would be similar to how the > "this" keyword is used in C++. > > 2. Omit self from the parameter. > > class Abc : > def DoSomething (a,b,c) : > # class variable > self.somevar = a > self.someblar = b > self.somec = c > somevar = a * b # local variable > > > So, what happens in this case, using your Abc class from before? def DoTheSameThing(abc, a, b, c) : abc.somevar = a abc.someblar = b abc.somec = c somevar = a * b Abc.DoSomething = DoTheSameThing Would methods defined this way never have access to the class instance? > > > Russ P. wrote: > >> On Jul 26, 2:25 pm, Terry Reedy >> >> >>> There is a lot of code you have not seen. Really. In informal code I >>> use 's' and 'o' for 'self' and 'other'. I don't usually post such >>> because it is not considered polite. So you have seen a biased sample >>> of the universe. >>> >>> >> >> You take the name down to a single letter. As I suggested in an >> earlier post on this thread, why not take it down to zero letters? You >> could if Python accepted something like >> >> class Whatever: >> >> def fun( , cat): >> >> .cat = cat >> >> This is even better than the single-character name, not only because >> it is shorter, but also because there is no question that you are >> referring to "self." No need to look back at the method signature to >> verify that. >> >> For those who don't like the way the empty first argument looks, maybe >> something like this could be allowed: >> >> def fun( ., cat): >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> >> > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alex.gaynor at gmail.com Tue Jul 29 22:12:15 2008 From: alex.gaynor at gmail.com (alex.gaynor at gmail.com) Date: Tue, 29 Jul 2008 19:12:15 -0700 (PDT) Subject: How can I check nbr of cores of computer? References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> <37e26af1-c6a7-4302-b93c-39164b222f26@34g2000hsf.googlegroups.com> Message-ID: On Jul 29, 7:44?pm, Mensanator wrote: > On Jul 29, 5:53?pm, defn noob wrote: > > > How can I check how many cores my computer has? > > Is it possible to do this in a Python-app? > > If you're using Windows, get PyWin32: > > win32api.GetSystemInfo > tuple = GetSystemInfo() > > Retrieves information about the current system. > > Win32 API References > > Search for GetSystemInfo at msdn, google or google groups. > > Return Value > The return value is a tuple of 9 values, > which corresponds to the Win32 SYSTEM_INFO structure. > The element names are: > dwOemId > dwPageSize > lpMinimumApplicationAddress > lpMaximumApplicationAddress > dwActiveProcessorMask > dwNumberOfProcessors > dwProcessorType > dwAllocationGranularity > (wProcessorLevel,wProcessorRevision) > > >>> import win32api > >>> win32api.GetSystemInfo() > > (0, 4096, 65536, 2147418111, 3L, 2, 586, 65536, (6, 3846)) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?processors This: http://pyprocessing.berlios.de/ has a method that returns CPU count. From robert.rawlins at thinkbluemedia.co.uk Thu Jul 17 12:52:05 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 17 Jul 2008 17:52:05 +0100 Subject: Unusual Exception Behaviour In-Reply-To: References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> Message-ID: <005b01c8e82d$71714480$5453cd80$@rawlins@thinkbluemedia.co.uk> Hi MK, >>Robert Rawlins wrote: >> >> I certainly like that implementation for logging the exceptions, however, at >> the moment I don't even know where the exceptions are occurring, or what >> type they are, could I still use this method to log any and all exceptions >> raised in the application? > Remember, Google is your friend, here's the crux of the method without > the fancy schmancy sugar coating: > > http://linux.byexamples.com/archives/365/python-convey-the-exception-traceba ck-into-log-file/ > > if __name__=="__main__": > try: > main() > except: > print "Trigger Exception, traceback info forward to log file." > traceback.print_exc(file=open("errlog.txt","a")) > sys.exit(1) > I've just given this solution a shot but I still seem to get the same result, it suddenly starts dumping the log data to the command line, and nothing gets printed in error.txt apart from the keyboard interrupt from when I kill the application. For some reason the exceptions don't seem to be raised properly so obviously aren't being caught at this higher level. So confusing. From mail at timgolden.me.uk Wed Jul 16 12:16:50 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 17:16:50 +0100 Subject: About wmi In-Reply-To: <487E1AD4.9020509@timgolden.me.uk> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> <487E1AD4.9020509@timgolden.me.uk> Message-ID: <487E1EF2.4090500@timgolden.me.uk> Assuming that the error comes back in the sys.stdout encoding, the following version *should* work ok. I still haven't got a non-English set up to test it on, but it certainly does return a Unicode error message. http://timgolden.me.uk/wmi-project/wmi.py The usual test case, if you wouldn't mind: import wmi wmi.WMI ("non-existent computer") should give a (language-specific) error message, not an UnicodeDecodeError TJG From mensanator at aol.com Sun Jul 20 22:31:23 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 20 Jul 2008 19:31:23 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> On Jul 20, 7:37?pm, Roy Smith wrote: > In article > , > > ?Mensanator wrote: > > C isn't a high level language, that's part of its problem. > > C is the highest level assembler language Isn't that like bragging about being the smartest kid on the short bus? > I've ever used. ?And I've used a > few. ?It really is cool that you can add two 32-bit integers and not have > to worry about all those carry bits. Carry bits? Who worries about carry bits when you have unlimited precision arithmetic? You want cool? THIS is cool: j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2])) % xyz[1]**(k-1))/xyz[1]**(k-2) From steve at REMOVE-THIS-cybersource.com.au Mon Jul 28 10:00:49 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Jul 2008 14:00:49 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> Message-ID: <009dcc93$0$20313$c3e8da3@news.astraweb.com> Cutting to the crux of the discussion... On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: > I want something where "if x" will do but a simple explicit test won't. Explicit tests aren't simple unless you know what type x is. If x could be of any type, you can't write a simple test. Does x have a length? Is it a number? Maybe it's a fixed-length circular length, and the length is non-zero even when it's empty? Who knows? How many cases do you need to consider? Explicit tests are not necessarily simple for custom classes. Testing for emptiness could be arbitrarily complex. That's why we have __nonzero__, so you don't have to fill your code with complex expressions like (say) if len(x.method()[x.attribute]) > -1 Instead you write it once, in the __nonzero__ method, and never need to think about it again. In general, you should write "if x" instead of an explicit test whenever you care whether or not x is something (true), as opposed to nothing (false), but you don't care what the type-specific definition of something vs. nothing actually is. To put it another way... using "if x" is just a form of duck-typing. Let the object decide itself whether it is something or nothing. -- Steven From jkugler at bigfoot.com Wed Jul 16 14:33:48 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Wed, 16 Jul 2008 10:33:48 -0800 Subject: Is re.findall guaranteed to be "in order?" References: Message-ID: Fredrik Lundh wrote: > Joshua Kugler wrote: > >> Experimenting has shown me that re.findall() will return a list with the >> matches in the order it found them. > > "in the order it found them" doesn't really say much, does it? ;-) > > "findall" and "finditer" both scans the string from left to right, and > will return matches in that order. > > (the documentation is a bit vague, so if you have the time, please add a > request for clarification to the bug tracker) Done. http://bugs.python.org/issue3384 j From dullrich at sprynet.com Mon Jul 7 17:19:33 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 07 Jul 2008 16:19:33 -0500 Subject: How to make a function associated with a class? References: <69e26f9b-2f00-4318-9bc5-6aa94e141bca@59g2000hsb.googlegroups.com> <4d7cf477-e791-4122-bc20-0dbd1a16bc12@j22g2000hsf.googlegroups.com> <0d9c534b-8720-4363-b3e5-eb546dd3637c@8g2000hse.googlegroups.com> Message-ID: In article <0d9c534b-8720-4363-b3e5-eb546dd3637c at 8g2000hse.googlegroups.com>, Kurda Yon wrote: > On Jul 1, 5:01 pm, "bruno.desthuilli... at gmail.com" > wrote: > > On 1 juil, 22:43, Kurda Yon wrote: > > > > > > > > > Hi, > > > > > I have a class called "vector". And I would like to define a function > > > "dot" which would return a dot product of any two "vectors". I want > > > to call this function as follow: dot(x,y). > > > > > Well, I can define a functions "dot" outside the class and it works > > > exactly as I want. However, the problem is that this function is not > > > associated with the class (like methods a method of the class). > > > > > For example, if I call "x.calc()" or "y.calc()", python will execute > > > different methods if "x" and "y" belongs to different classes. I want > > > to have the same with my "dot" function. I.e. I want it calculates the > > > dot product ONLY IF the both arguments of that function belong to the > > > "vector" class. > > > > > Is it possible? > > > > You don't need to make dot() a method of your Vector class to have > > this behaviour, and making it a method of the Vector class isn't > > enough to have this behaviour. > > > > The simplest solution would be: > > > > class Vector(object): > > def dot(self, other): > > if not isinstance(other, type(self)): > > raise TypeError("can only calculate the dot product of two > > vectors") > > # do the job here and return what's appropriate > > > > Now since it's a binary operator, you might as well implement it as > > such: > > > > class Vector(object): > > def __mul__(self, other): > > if not isinstance(other, type(self)): > > raise TypeError("can only calculate the dot product of two > > vectors") > > # do the job here and return what's appropriate > > > > Then use it as doproduct = vector1 * vector2 > > > > HTH > > As far as I understood, In the first case, you gave, I need to call > the function as follows "x.dot(y)". In the second case I need to call > the function as follows "x*y". But I want to call the function as > follows "dot(x,y)". You want to say dot(x,y), but to have the actual behavior determined by the class of which x and y are instances? You could do this: def dot(x,y): return x.dot(y) and now give Vector an appropriate dot(self, other) method. > By the way, "type(self)" returns the name of the class to which the > "self" belongs? > Does "instance" return "true" if the first argument belongs to the > class whose name is given in the second argument? -- David C. Ullrich From gagsl-py2 at yahoo.com.ar Tue Jul 15 01:25:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 02:25:29 -0300 Subject: how can I use exec with main module globals? References: Message-ID: En Sat, 12 Jul 2008 16:15:36 -0300, Akathorn Greyhat escribi?: > Hello, this is my first message in the group. Welcome! > I'm spanish so my english sometimes is really bad, sorry =( > > I have a problem and I hope someone has the answer. > > I'm trying to make an in-game python idle, it works great but the exec > statement can't access the main module globals but only the ones that are > inside the module in wich I defined the function. > > def execute(self, string): > exec(string, globals(), globals()) > > I realized that if I move the code to the main module, It works, but I > want > it to be inside another script. You have to pass in the namespace of the desired module - instead of globals. I'd use an explicit argument: def execute(self, string, namespace): # exec string in namespace # 2.5 exec(string, namespace) # 3.0 Use it this way: execute("a=1", target_module.__dict__) then target_module.a will be 1 -- Gabriel Genellina From arne at vajhoej.dk Sun Jul 13 13:01:13 2008 From: arne at vajhoej.dk (=?UTF-8?B?QXJuZSBWYWpow7hq?=) Date: Sun, 13 Jul 2008 13:01:13 -0400 Subject: spam <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> In-Reply-To: References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> <487a0d4d$0$90272$14726298@news.sunsite.dk> Message-ID: <487a34d5$0$90263$14726298@news.sunsite.dk> donald wrote: > Arne Vajh?j wrote: >>> >>> Google does not accept spam complaints. Go ahead, try it. That's >>> why they've been the #1 Usenet spamming tool for years now. What >>> you're seeing is the spam slowly expanding into the software >>> development groups. uk.railway is probably a random group added to >>> confuse spam filters. Some groups, like rec.photo.digital, have been >>> getting hundreds of Google spams a day for about a year. >>> >>> Ask your news service for a Google UDP (Usenet Death Penalty) or >>> configure your reader to drop everything with "googlegroups.com" in >>> the Message-ID. >> >> Some real users do use GG. > > This is true, however there are acceptable losses. Everybody is free to look at it that way. Arne From wuwei23 at gmail.com Thu Jul 17 19:27:13 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 17 Jul 2008 16:27:13 -0700 (PDT) Subject: x, = y (???) References: Message-ID: <869240fd-38ec-41ba-bd49-048a0693c253@s31g2000prg.googlegroups.com> On Jul 18, 8:01?am, DaveM wrote: > On Thu, 17 Jul 2008 17:32:30 -0400, Terry Reedy wrote: > > >>> *x, = [3] > > >>> x > >[3] > > What does *x signify? Mostly that Terry is using Python 3.0. See: http://www.python.org/dev/peps/pep-3132/ From q2w3qw14 at gmail.com Sun Jul 27 23:44:05 2008 From: q2w3qw14 at gmail.com (Sera Jackson) Date: Sun, 27 Jul 2008 20:44:05 -0700 (PDT) Subject: I love "shelf" BUT References: <1c2d28bb-06e8-4f02-a528-9d86f84366dd@n33g2000pri.googlegroups.com> Message-ID: On Jul 28, 6:25?am, alex23 wrote: > On Jul 28, 12:46?pm, Sera Jackson wrote: > > > ok, I know its an over discussed topic. Althought I understand why it > > is there I cant constantly see it in my argument list in parenthesis. > > > can someone give me an insight of the cons of a syntax like this: > > class Class: > > ? ? def self.method(arguments): > > ? ? ? ? etc, etc > > > In other words def method(self, arg1, arg2 ,argN) becomes-> ?def > > self.method(arg1, arg2 ,argN) > > Did you bother to check the group? You would've noticed it's being > discussed -right now-:http://groups.google.com/group/comp.lang.python/browse_frm/thread/a5f... > > And this -exact- suggestion has been turned down by Guido:http://mail.python.org/pipermail/python-3000/2006-April/000793.html alex thank you very much! I searched excessively python mailing list but unforurtunately I was using as query and I missed it, although I knew it should had been there. I mostly found threads insisting on a complete removal... And I sincerely apologise for missing the discussion here, I was tired digging python old mailing list. :D. Lot of thanks again, that's what I wanted to find, arguments against it, I was aware I wan not speaking of sth new. From ethan at stoneleaf.us Wed Jul 30 04:49:55 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 30 Jul 2008 00:49:55 -0800 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> Message-ID: <48902B33.3010205@stoneleaf.us> Carl Banks wrote: > On Jul 29, 6:42 pm, Matthew Fitzgibbons wrote: >> I don't have any postable code (it's in a half way state and I haven't >> touched it for a while), but I'll see if I can't find the time to bang >> something up to give you the gist. > > I wouldn't bother at this point. I was looking to see if someone > could come up with something to disprove my belief on the polymorphic > uselessness of "if x" relative to explicit tests, and if (as I > anticipated) they did not, I could claim that "if x" is really just a > glorified keystroke saver. But I now realize that the failure of this > bunch doesn't prove anything. I don't think most people even realize > why answering the question I asked would demonstrate the usefulness of > "if x". > > Your example isn't exactly the smoking gun I was looking for, but I > guess we'll have to admit that at least one usage will suffer for not > having it. > > Carl Banks Even for those that did realize, and in fact hoped that that is what you were attempting to accomplish, it was still quite frustrating to see you ignoring all the non-code, yet perfectly valid examples of why "if x" was not only valid, but the most pythonic[1] way to get the task done. I think it would have been a better discussion if you had responded with reasons why, and not just parroted the "show me the code!" line over and over and over and ... It seemed as if you thought you were the professor, impatiently trying to teach a class full of idiots by playing the devil's advocate. I was sure hoping someone would get the actual code example and post it, partly because I enjoy learning, but mostly because it would (hopefully) shut you up and move the conversation along. In fact, somebody did post some code about a custom matrix class, where __len__ was useless, and still you kept on with... pah. It's late, so before I say something stupid I'll finish this. My last thought on the matter -- up until this thread I had looked forward to your posts, Carl. I think you did more damage than good to yourself with this stunt. ~Ethan~ [1] by pythonic I mean using the features of the language that make sense. In this case, the __nonzero__ function to have the object in question tell us whether or not it's empty. This seems so basic (the __nonzero__ function, that is, and its purpose) -- do you really need code to prove it to yourself? From raghavendra.gv.vanam at gmail.com Thu Jul 10 08:00:39 2008 From: raghavendra.gv.vanam at gmail.com (vanam) Date: Thu, 10 Jul 2008 05:00:39 -0700 (PDT) Subject: Graphics Message-ID: hi all i am new to python programming a beginner. I Came to know from the groups that "How to think like a computer scientist" is preferable for begineers. i just looking through that i came to one section where a sample program for generation of graphics is present.i tried to copy the same script to the interpreter and it is showing an error i want to know whether is there anything that has to be installed in addition to python 2.5 below is the program from gasp import * begin_graphics() Circle((200, 200), 60) Line((100, 400), (580, 200)) Box((400, 350), 120, 100) end_graphics() From jonas.esp at googlemail.com Sat Jul 12 15:04:41 2008 From: jonas.esp at googlemail.com (Kless) Date: Sat, 12 Jul 2008 12:04:41 -0700 (PDT) Subject: SQLAlchmey - new data types for PostgreSQL Message-ID: It would be very interesting if the python community could to access since SQLAlchemy to more features of the PostgreSQL 8.3 RDBMS powerful, as are any new data types as: enumerated (ENUM) [1], XML [2], Universally Unique Identifiers (UUID) [3], and monetary [4]. For if anybody is interested on add them, see here: [5] [1] http://www.postgresql.org/docs/8.3/static/datatype-enum.html [2] http://www.postgresql.org/docs/8.3/static/datatype-xml.html [3] http://www.postgresql.org/docs/8.3/static/datatype-uuid.html [4] http://www.postgresql.org/docs/8.3/static/datatype-money.html [5] http://www.sqlalchemy.org/docs/05/sqlalchemy_databases_postgres.html http://www.sqlalchemy.org/trac/browser/sqlalchemy/trunk/lib/sqlalchemy/databases/postgres.py From sjmachin at lexicon.net Tue Jul 29 19:52:25 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 29 Jul 2008 16:52:25 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> Message-ID: <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> On Jul 30, 3:53 am, william tanksley wrote: > To ask another way: how do I convert from a file:// URL to a local > path in a standard way, so that filepaths from two different sources > will work the same way in a dictionary? > > Right now I'm using the following source: > > track_id = url2pathname(urlparse(track_id).path) > > url2pathname is from urllib; urlparse is from the urlparse module. > > The problems occur when the filenames have non-ascii characters in > them -- I suspect that the URLs are having some encoding placed on > them that Python's decoder doesn't know about. WHAT problems? WHAT non-ASCII characters?? Consider e.g. # track_id = url2pathname(urlparse(track_id).path) print repr(track_id) parse_result = urlparse(track_id).path print repr(parse_result) track_id_replacement = url2pathname(parse_result) print repr(track_id_replacement) and copy/paste the results into your next posting. From grante at visi.com Mon Jul 14 12:20:59 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 14 Jul 2008 11:20:59 -0500 Subject: Using McMillan Installer, PyInstall or py2exe cross-platform? References: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> Message-ID: On 2008-07-14, Hartmut Goebel wrote: > has anybody used McMillan Installer, PyInstall or py2exe cross-platform? I know that py2exe doesn't work "cross-platform". I'd be very surprised if the the others do. > I have a Windows partition with Python installed there, so > this would "only" required working on a different directory > and for a different OS. Since I'm working on Linux, it's awful > to boot Windows each time I want to build a new release. > > Any hint in this area? You can run Windows on a VM like Qemu and use that to build distribution packages. You still have to "boot windows", but at least you don't have to shut down Linux... -- Grant Edwards grante Yow! Here I am at the flea at market but nobody is buying visi.com my urine sample bottles ... From bj_666 at gmx.net Wed Jul 23 10:11:41 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 23 Jul 2008 14:11:41 GMT Subject: Python Written in C? References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> Message-ID: <6eosgtF7u58sU1@mid.uni-berlin.de> On Wed, 23 Jul 2008 14:10:22 +0200, mk wrote: > Marc 'BlackJack' Rintsch wrote: >> I can't even remember when I deleted something from a list in the past. > > Still, doesn't that strike you as.. workaround? No, I find it actually safer; I don't have to care where modifications of the list might be seen elsewhere in the program. Ciao, Marc 'BlackJack' Rintsch From mach.elf at gmail.com Wed Jul 2 18:07:12 2008 From: mach.elf at gmail.com (Pete Kirkham) Date: Wed, 2 Jul 2008 23:07:12 +0100 Subject: C++ or Python In-Reply-To: References: Message-ID: 2008/6/29 Dan Stromberg : > > On Sun, 29 Jun 2008 11:20:45 +0200, Sebastian \"lunar\" Wiesner wrote: > > > Dan Stromberg : > > > >> things like passing a method as a function parameter is a no-brainer > >> (requires extra syntax in java because of the cautious type system - > >> not sure about C++). > > > > C++ has function pointers and functors, therefore this is not really an > > issue with C++. > > Based on http://en.wikipedia.org/wiki/ > Function_object#Functors_in_C_and_C.2B.2B it looks like there's no > special syntax in the language core, but programs needing to pass an > object as though it were a function (for example) do need to add some > extra lines of code for each object needing such treatment. That's a slightly different case - creating a functor in C++ is more equivalent to making a Python object callable. Both require you to add a specially named method to the class - "__call__" or "operator()". The syntax for the pointer to the member function Bar of class Foo is "&Foo::Bar", which is the same as taking a pointer to anything else in C++. The standard C++ library also has functions which take a pointer to a member function and return a functor which can be used to call the member function on an instance. (Whether passing the pointer as an unbound method works correctly with functions which expect a reference to a functor is compiler dependent, so is discouraged in portable code) So it's quite easy to pass an unbound method in C++ - the only extra line of code is #include. The disadvantage is that member function pointers mostly behave like functors, except when they don't, so there's more cognitive load. What is a lot easier in Python is to pass a bound method as a first-class function - you just use "instance.method_name" - but in C++ there isn't a standard library function that takes an object reference and a member function pointer and returns a functor bound to that member. In the absence of automatic memory management, you have to ensure the instance lifecycle exceeds the functor lifecycle, and the standard library avoids making design decisions about lifecycles of objects it doesn't create. From grante at visi.com Tue Jul 29 11:46:14 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 29 Jul 2008 10:46:14 -0500 Subject: Is it allowed to use function results as default arguments ? References: <488E2BF1.8020003@gmail.com> Message-ID: On 2008-07-29, Stef Mientki wrote: > brings me to one other question: > I guess this function is only evaluated once, is that correct ? Yes. > about '.' being the current directory, well I think windows > was thrown at the market about 25 years ago, and since then we > don't use '.' anymore ;-) Who's "we"? I stull use "." as the current directory. -- Grant Edwards grante Yow! Mary Tyler Moore's at SEVENTH HUSBAND is wearing visi.com my DACRON TANK TOP in a cheap hotel in HONOLULU! From python at bdurham.com Fri Jul 25 02:13:44 2008 From: python at bdurham.com (python at bdurham.com) Date: Fri, 25 Jul 2008 02:13:44 -0400 Subject: Questions on 64 bit versions of Python Message-ID: <1216966424.4685.1265275245@webmail.messagingengine.com> Background: I'm going to be processing some raw transaction logs that are 30G in size. As part of this processing I may need to create some very large dictionary structures. I will be running my scripts on a version of Windows 2003 Server Enterprise Edition that supports 16G of RAM. Yes, I could use a database in place of dictionaries, but I'm looking for maximum performance. The following page lists two 64 bit versions of Python for Windows: http://www.python.org/download/releases/2.5.2/ For Win64-Itanium users: python-2.5.2.ia64.msi For Win64-AMD64 users: python-2.5.2.amd64.msi 1. It looks like the 64 bit versions of Python for Windows are CPU vendor specific, eg. it doesn't look like there's a single, universal executable for Windows 64 bit platforms. Is this true? 2. Are there limitations to the using the 64 bit versions of Python? I seem to remember reading that many 3rd party modules (especially Windows OS specific modules) may not be compatible with the 64 bit versions of Python for Windows. 3. If I wanted to run a 64 bit version of Python under Linux, would I need to recompile from source on 64 bit version of Linux or do 64 bit versions of Linux automatically ship with 64 bit versions of Python? (Any recommendations on a flavor of 64 bit of Linux for the Intel architecture would be appreciated) 4. Is there a stable version of IronPython compiled under a 64 bit version of .NET? Anyone have experience with such a beast? Thank you, Malcolm From mail at timgolden.me.uk Thu Jul 10 09:50:27 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 10 Jul 2008 14:50:27 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) In-Reply-To: References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: <487613A3.8020603@timgolden.me.uk> Bill Davy wrote: > I'm not sure OL2003 can read news. I think perhaps some later OL can (added > tot he View menu, perhaps?). So I use OL Express to read news. The OL with > which I wish to communicate is: > > Application name Outlook > Version 11.0 > Build 8217 > Product ID 70141-700-0350904-56905 > Language English (United States) > Application Path C:\Program Files\Microsoft Office\OFFICE11\ > System Language English (United Kingdom) > Mail Support Not Available > Current folder Inbox > Current item Not Available Where did you get to with this, Bill? I wasn't sure if no news was good news or whether you'd gone a different way, or were still trying things... TJG From fredrik at pythonware.com Thu Jul 17 05:09:24 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 11:09:24 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) In-Reply-To: <0T56pitfI5raNv8%stesch@parsec.no-spoon.de> References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> <0T56p3tmInifNv8%stesch@parsec.no-spoon.de> <6e7v9qF5q74kU1@mid.uni-berlin.de> <0T56pitfI5raNv8%stesch@parsec.no-spoon.de> Message-ID: Stefan Scholl wrote: > And by the way: The quote was changed by deleting something on > the same line: > > "June 2008 is a bit too early. Django isn't ready." > > vs. > > "Django isn't ready." Is this a language issue? That you meant to write "django 1.0 isn't done" (as in "completed; finished") but accidentally wrote "django isn't ready" (where "ready" is usually read as "completely prepared or in fit condition for immediate action or use")? (and the "stable release" and "much will change" stuff is pure FUD, of course. what competing project will I find if I google your name?) From mail at timgolden.me.uk Wed Jul 9 08:58:12 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 09 Jul 2008 13:58:12 +0100 Subject: Newbie question In-Reply-To: <3b1e6f480807090552m51be62a9tbb76085504e5d4e3@mail.gmail.com> References: <3b1e6f480807082337l419fd40ax91eaf13e0701c5b3@mail.gmail.com> <3b1e6f480807090552m51be62a9tbb76085504e5d4e3@mail.gmail.com> Message-ID: <4874B5E4.7000400@timgolden.me.uk> |e0 wrote: > I did not mean to use WMI on linux, but query win machines *from* linux. > Thank you for your clarifications In principle you ought to be able to use some kind of DCOM bridge (since WMI access if via COM/DCOM). I've no idea if anyone's attempted this or even if all the pieces are in place. If this won't fly, it should be simple enough to use one of the many, many RPC-ish mechanisms, whether all-Python or otherwise, to call into a WMI proxy service you could run on the chosen Windows boxes. TJG From maric at aristote.info Wed Jul 30 14:22:20 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 30 Jul 2008 20:22:20 +0200 Subject: Standard module for parsing emails? In-Reply-To: <6fbmilFanjibU1@mid.uni-berlin.de> References: <6fbmilFanjibU1@mid.uni-berlin.de> Message-ID: <200807302022.21390.maric@aristote.info> Le Wednesday 30 July 2008 19:25:31 Diez B. Roggisch, vous avez ?crit?: > Maric Michaud wrote: > > Le Wednesday 30 July 2008 17:55:35 Aspersieman, vous avez ?crit?: > >> For parsing the mails I would recommend pyparsing. > > > > Why ? email module is a great parser IMO. > > He talks about parsing the *content*, not the email envelope and possible > mime-body. Yes ? I don't know what the OP want to do with the content, but if it's just filtering the lines begining with a '>', pyparsing might be a bit overweighted. -- _____________ Maric Michaud From half.italian at gmail.com Wed Jul 23 15:22:42 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 23 Jul 2008 12:22:42 -0700 (PDT) Subject: Doubt References: Message-ID: On Jul 23, 7:51?am, ???????? wrote: > Friends > > I am a Perl programmer new to Python. I have a small doubt. > How to convert the perl notation > $a = ""; expression in Python ? > > How to represent the loop > for ($a = $b; $a<=$c;$a++){ > > } in Python > > Jagan > Linguist On most occasions you don't need to use the incrementing loop behavior. Lists are the main data structure comparable to an array, and you can iterate over them without using a counter. If you have: aList = [1, 2, 3] you can do for item in aList: print item Hope this helps. ~Sean From M8R-yfto6h at mailinator.com Mon Jul 21 10:09:13 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Mon, 21 Jul 2008 07:09:13 -0700 Subject: imported module no longer available References: Message-ID: <8qmdnYkOPPAVBRnVnZ2dnUVZ_rCdnZ2d@comcast.com> "Jeff Dyke" wrote in message news:mailman.406.1216648575.922.python-list at python.org... > I've come across an error that i'm not yet able to create a test case > for but wanted to get see if someone could shed light on this. > > I have imported a module at the top of my file with > import mymodulename > > this module is used many times in the current file successfully, but > then I attempt to use it one more time and get: UnboundLocalError: > local variable 'mymodulename' referenced before assignment > > if i add `print globals().keys()` right before the line where the > error occurs l see the module in the list (actual output, names > changed to protect the innocent) > ['HPADao', 'RDao', 'DriverBase', 'FKSUtility', 'PMDao', > 'mymodulename', 'IDriver', 'DriverTrack', 'HPPDao', 'setLogName', > 'HPDao', 'iparser', '__builtins__', '__file__', 'driver', '_LOGNAME', > 'sys', 'IClient', '__name__', 'copy', 'types', 'logging', 'iloader', > 'HPADao', '__doc__', 'PMDao', 'time', 'FormatLoad'] > Traceback (most recent call last): > File "testunbound.py", line 475, in > driver.getRData('0605', 22528) > File "testunbound.py", line 256, in getRData > print mymodulename > > the code that generates these two lines is: > print globals().keys() > print mymodulename > > I can solve this by placing > import mymodulename again in this method, but can't have that everywhere. > > I will try to come up with a generic reproduction of this issue, but > that might take some time. I've also seen this in the past with the > python builtin 'sys' > I did see a bug http://bugs.python.org/issue2378, which has very > similar behaviour, but is different. > > Python 2.5, ubuntu hardy > > Thanks for any insight, > Jeff That error will occur if somewhere in a function or method you accidently assign another value to a global variable, without declaring it with the global keyword first, even if it occurs later in the function. Example: import os print os.getcwd() def func(): print globals().keys() print os os=1 func() OUTPUT: c:\ ['__builtins__', '__file__', 'func', '__name__', 'os', '__doc__'] Traceback (most recent call last): File "C:\dev\python\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 414, in ImportFile exec codeObj in __main__.__dict__ File "", line 1, in File "test.py", line 10, in func() File "test.py", line 7, in func print os UnboundLocalError: local variable 'os' referenced before assignment Check in the function that caused the error to see if later in the code the module name is being used as a local variable. --Mark From norseman at hughes.net Tue Jul 15 14:43:18 2008 From: norseman at hughes.net (norseman) Date: Tue, 15 Jul 2008 11:43:18 -0700 Subject: Testing for Internet Connection In-Reply-To: References: <18460572.post@talk.nabble.com> <1216113021.24038.0@proxy02.news.clara.net> Message-ID: <487CEFC6.2080406@hughes.net> Grant Edwards wrote: > On 2008-07-15, Alexnb wrote: > >> What exactly do you think will work? I am not sure what you >> think I should do? If I use urlopen("http://www.google.com") >> and I am not connected, I am not going to get an exception, >> the program will fail. > > Bullshit. You get an exception. Here's my program: > > import urllib2 > try: > con = urllib2.urlopen("http://www.google.com/") > data = con.read() > print data > except: > print "failed" > > If I run it with no internet connection, I get this: > > $ python testit.py > failed > > If I bring up the internet connection, then I get a bunch of > HTML. > ============================= Yep -me two Process: copy/paste into afile slide lines left to create proper indent values save python afile I get same as Grant If one does a copy/paste into interactive Python, it does fail. (Lots of indent error messages. After all, it is Python :) Steve norseman at hughes.net From davidreynon at gmail.com Mon Jul 7 11:26:05 2008 From: davidreynon at gmail.com (korean_dave) Date: Mon, 7 Jul 2008 08:26:05 -0700 (PDT) Subject: win32com extension documentation/API Message-ID: <996ff65c-8611-483e-90d6-3cf73b9e1496@25g2000hsx.googlegroups.com> Hi. Where can i find the API for this extension? Sourceforge only has downloads. Python has stopped supporting the upkeep of the versions. Thanks. From robert.kern at gmail.com Mon Jul 28 18:56:08 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 28 Jul 2008 17:56:08 -0500 Subject: derivative in numpy In-Reply-To: References: Message-ID: knielsen73 at gmail.com wrote: > Hi, > > I am looking to do a simple derivative. I would expect such a function > to be available in numpy, but can't find it. I have written my own, > but just curious if anybody knows of such function in numpy. numpy.diff() handles the discrete difference. All you need to do is supply the scaling factor(s) to interpret it as a derivative. Again, numpy questions are best asked on the numpy mailing list. http://www.scipy.org/Mailing_Lists -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sjmachin at lexicon.net Mon Jul 7 18:30:08 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 7 Jul 2008 15:30:08 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <6deq2uF21vo2U1@mid.uni-berlin.de> <9b841be4-cd9c-4782-8498-55f053cdbb71@x41g2000hsb.googlegroups.com> Message-ID: <5ee3cbcd-22c1-41d9-97c6-b47655a04570@w7g2000hsa.googlegroups.com> On Jul 8, 2:51 am, Henning Thornblad wrote: > When trying to find an alternative way of solving my problem i found > that running this script: > > #!/usr/bin/env python > > import re > > row="" > for a in range(156000): > row+="a" > print "How many, dude?" > print re.search('/[^ "=]*',row) (the / has moved) > > wouldn't take even a second (The re.search part of course) > > This is for me very strange since this, > in theory, is the same problem as before. In theory. In practice, it is the same problem *iff* you start at the end of the text and work backwards. Your original pattern can be characterised as X*Y, where X and Y are character classes; your new one is YX*. You are asking each to search a text that contains many Xs and no Ys. The second pattern will cause a naive search engine to examine each character in the text (is it a Y?) as a candidate for the start of a successful match; each test fails, and the whole expedition has cost O(N). OTOH, the first pattern will start at offset 0, cheerfully cruising past all those lovely Xs, but failing (no Y) at the end of the text. It will then think that it's been too greedy, reduce the matched span of X* from N characters to N-1, fail to find Y, N-2, fail, ... so that's O(N**2) just for the first trial starting from offset 0. Being naive, it will try again starting from offset 1, 2, 3, ... an O(N**3) process. If you were to tell us what you are actually trying to do, we could probably help you with a faster method. BTW, if the text is 'aaa///bbb///ccc', your original search will find 'aaa///bbb///'; if you want it to find 'aaa/', the pattern should be: '[^ "=/]*/' Cheers, John From xahlee at gmail.com Sun Jul 6 04:05:09 2008 From: xahlee at gmail.com (xahlee at gmail.com) Date: Sun, 6 Jul 2008 01:05:09 -0700 (PDT) Subject: Elisp Lesson on file processing (make downloadable copy of a website) References: Message-ID: In this week i wrote a emacs program and tutorial that does archiving a website for offline reading. (See http://xahlee.org/emacs/make_download_copy.html ) In the process, i ran into a problem with the unix ?cp? utility. I've been a unix admin for Solaris during 1998-2004. Even the first time i learned about cp, i noticed some pecularity. But only today, i thought about it and wrote it out exactly what's going on. Here's a excerpt from my emacs tutorial above regarding the issue. ------------------ Copying a bunch of directories seems a trivial operation, but it actually took me a couple hours to arrive at the final code, due to the exact requirement of directory paths, and the unix ?cp? tool's lack of precision and flexibility. Originally, i thought the code would be something simple like several ?(shell-command (concat "cp -R " fromDir " " toDir))?, one for each source dir, where fromDir and toDir are full paths. However, it turns out the problem is slightly more complex. Suppose the source dir is ?/Users/xah/web/emacs? and dest dir is ?/ Users/xah/web/diklo/xahtut/emacs? and i want all branches under the source dir copied into the dest dir. If you do ?cp -R /Users/xah/web/emacs /Users/xah/web/diklo/xahtut/ emacs? with both xahtut and xahtut/emacs doesn't exist, then this error results: ?cp: /Users/xah/web/diklo/xahtut/emacs: No such file or directory?. If you do ?cp -R /Users/xah/web/emacs /Users/xah/web/diklo/xahtut/ emacs? with xahtut/emacs exists, then you got ?/Users/xah/web/diklo/ xahtut/emacs/emacs?, which is not what i want. If you do ?cp -R /Users/xah/web/emacs /Users/xah/web/diklo/xahtut? with xahtut doesn't exist, it results in all branches of emacs in xahtut, which is wrong. Only when you do ?cp -R /Users/xah/web/emacs /Users/xah/web/diklo/ xahtut? with xahtut exists, you get the correct result with the new dir ?/Users/xah/web/diklo/xahtut/emacs? having all branches of the original dir. So, the solution is to first create all the parent dirs of the dest dir, but without the dest dir node itself. Then, do a cp to the first parent of dest dir. Directories are abstractly a tree. Copying directories is like grafting a tree from one branch into another branch. To begin, we are given two spec: the source node and a destination node. The source node by definition is a existing node (i.e. existing dir or file), otherwise the copying won't make sense. However, the destination spec can be a node that doesn't exist, or its parents doesn't exist, or several levels of parents doesn't exist. When the destination spec has missing nodes, we can consider creating them as part of the grafting process, or we can consider it as a error. The unix ?cp? tool's behavior is mathematically inconsistent. When the destination node exist, the source node will become new children of destination node. When the destination node does not exist (but its parent exists), ?cp? will create the node, and copy only the children of the source node to it. When the destination node doesn't exist and its parent doesn't exist neither, then ?cp? considers it a error. --------------- Related readings: ? The Nature of the ?Unix Philosophy? http://xahlee.org/UnixResource_dir/writ/unix_phil.html Xah ? http://xahlee.org/ ? From ben at benfinney.id.au Thu Jul 10 21:59:27 2008 From: ben at benfinney.id.au (Ben Finney) Date: Fri, 11 Jul 2008 11:59:27 +1000 Subject: Python 3.0 and removal of the 'string' module Message-ID: <87wsjtqiyo.fsf@benfinney.id.au> Howdy all, The Python wiki page states on its page for Python 3.0 , in the section for "Standard Library Changes" , that the 'string' module is to be removed. It references PEP 4 , which has nothing to say about the status of the 'string' module. Further, the 'string' module has existing functionality (the Template class, the character sets 'whitespace' etc.) that, to my knowledge, has no replacement in Python 3.0. Can anyone see a reason to believe the above wiki page's statement about the 'string' module being removed? More to the point, can anyone see a reason why that statement should remain on that page? -- \ ?Ours is a world where people don't know what they want and are | `\ willing to go through hell to get it.? ?Donald Robert Perry | _o__) Marquis | Ben Finney From tjreedy at udel.edu Sat Jul 26 17:17:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 17:17:09 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87fxpxw0ku.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> Message-ID: Torsten Bronger wrote: > Hall?chen! > > Terry Reedy writes: > >> [...] >> >> Or the proposal would have to be that 'self' is mandatory for all >> programmers in all languages. I think *that* would be >> pernicious. People are now free to write the more compact 's.sum = >> s.a + s.b + s.c' if they want instead of the 'self' version. And >> again, not everyone writes in English. > > Of course, "self" would have to become a reserved word. You could > say that this may break some code, Will break. > but I don't see much freedom removed from the language. > After all, being a German, I still can't > write "F?r i in range(10)". ;-) But you can write 'for ubermenchen in range(10):' and in 3.0, with diacritics added. Would you really feel no loss of freedom if Guido make i0, i1, ... into keywords, which means they could not be used elsewhere, and mandated them as for loop index variables? From duncan.booth at invalid.invalid Mon Jul 28 09:11:22 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Jul 2008 13:11:22 GMT Subject: Module clarification References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> <896c547e-9fa1-4f84-8c9b-53a96e70246c@y21g2000hsf.googlegroups.com> <00c033b9-1b5a-4165-abec-4ff6119298a5@z66g2000hsc.googlegroups.com> Message-ID: Hussein B wrote: > If I have a couple of modules, is there a way to package them? or > there is no such a thing in Python? > > It sounds rather as though you haven't yet gone through the Python tutorial. You really should read it, even if you just skim through it to see what topics are covered. The tutorial explains both modules and packages: http://docs.python.org/tut/node8.html What it doesn't cover is that you can import modules or packages directly from a zip file. Then read about eggs. -- Duncan Booth http://kupuguy.blogspot.com From jazle at nospam.log.web.id Tue Jul 22 00:23:48 2008 From: jazle at nospam.log.web.id (Jaimy Azle) Date: Tue, 22 Jul 2008 11:23:48 +0700 Subject: Python Embedding Thread References: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> <87bf413d-eb98-47c0-8466-237c45fd1a0e@e53g2000hsa.googlegroups.com> Message-ID: "Benjamin" wrote: > Two threads should not be running through the Python VM concurrently > in the same process. The GIL has to be held *any* time you use the > Python API. When you want to release the GIL (to process something in > C), use PY_BEGIN_ALLOW_THREADS and > PY_END_ALLOW_THREADS around the > places where threads can run. I think he is trying to call python from thread, according to the documentation: "Beginning with version 2.3, threads can now take advantage of the PyGILState_*() functions to do all of the above automatically." - http://docs.python.org/api/threads.html I use it everywhere on my multithreaded server without problem. Salam, -Jaimy From Russ.Paielli at gmail.com Mon Jul 28 21:32:09 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jul 2008 18:32:09 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> <488e3520$0$16766$426a74cc@news.free.fr> <87myk1iknc.fsf@benfinney.id.au> Message-ID: <1d71bcce-2e82-4b8f-9ac6-f729fea634eb@z26g2000pre.googlegroups.com> On Jul 28, 5:44 pm, Ben Finney wrote: > Bruno Desthuilliers writes: > > Boy, I don't know who you think you're talking to, but you're > > obviously out of luck here. I'm 41, married, our son is now a > > teenager, I have an happy social life, quite a lot of work, and no > > time to waste in the streets. And FWIW, name-calling won't buy you > > much here. > > It has, at least, long ago bought him a place in my kill-file. Seeing > your side of the conversation, I can only confirm that decision as > correct. Now there's a classic reply from another comp.lang.python regular. All he needs is one side of the conversation to know what's going on! I'd really like to know where both of you guys find the time to spend here, because unless you type extremely fast, I figure it's about 10-20 hours per week every week. Sorry, but if you also have "quite a lot of work," I don't believe that leaves much time for a "happy social life." Each and every time I get involved in an extended discussion about Python here, I end up realizing that I've wasted a lot of time trying to reason with unreasonable people who are infatuated with Python and incapable of recognizing any deficiencies. I will thank you for one thing. By taking your best shot at my suggestion and coming up with nothing significant or relevant, you have given me confidence to go ahead with a PEP. I may just do it. If it is rejected, then so be it. Unlike you, they will have to give me a valid reason to reject it. From mattheww at chiark.greenend.org.uk Tue Jul 29 16:15:12 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 29 Jul 2008 21:15:12 +0100 (BST) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8d Message-ID: Steven D'Aprano wrote: > "if x" is completely type agnostic. You can pass an object of any type to > it, and it will work. (Excluding objects with buggy methods, naturally.) There are many circumstances where if a parameter is None I'd rather get an exception than have the code carry on with the 'empty container' branch (and silently give me a meaningless result). -M- From pavlovevidence at gmail.com Wed Jul 30 00:45:40 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 21:45:40 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> <7f4a3d37-e551-4e21-b660-3618016cb67b@z6g2000pre.googlegroups.com> Message-ID: <68448887-4736-4af9-9f27-837bb5312cbd@o40g2000prn.googlegroups.com> On Jul 30, 12:22 am, Erik Max Francis wrote: > Carl Banks wrote: > > That's not what I was asking for. I was asking for a use case for "if > > x" that can't be replaced by a simple explicit test. Your example > > didn't satisfy that. > > It's a completely artificial request. Bull. This is a request, that, if satisfied, would prove that "if x" is more polymorphic than a simple explicit test. I posed the question precisely to see if anyone could come up with a use case that shows this benefit of "if x". > "if x" _is_ a completely simple > test. Simpler, in fact, than the ones you were advocating. It's not explicit. Here's what we know for sure. 1. "if x" uses fewer keystrokes than an explicit test 2. "if x" creates fewer nodes in the parse tree than an explicit test 3. Couple minor things we somehow managed to uncover in this thread Is that it? Is that all the benefits of "if x"? This is what I want to establish. A bunch of people in this thread are crowing that it helps polymorphism, but I have only seen minor examples of it. I've explained why I doubt that it helps polymorphism that much: you almost never see code for which an integer and list both work, so having the ability to spell a test the same way for both types isn't useful. If you claim that "if x" does help polymorphism, please tell me what's wrong with the above analysis. Or just give me the use case I asked for. Carl Banks From jkrukoff at ltgc.com Mon Jul 28 18:10:13 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Mon, 28 Jul 2008 16:10:13 -0600 Subject: seemingly simple list indexing problem In-Reply-To: References: Message-ID: <1217283013.4123.98.camel@jmk> On Mon, 2008-07-28 at 16:24 -0500, Ervan Ensis wrote: > My programming skills are pretty rusty and I'm just learning Python so > this problem is giving me trouble. > > I have a list like [108, 58, 68]. I want to return the sorted indices > of these items in the same order as the original list. So I should > return [2, 0, 1] > > For a list that's already in order, I'll just return the indices, i.e. > [56, 66, 76] should return [0, 1, 2] > > Any help would be appreciated. > > -- > http://mail.python.org/mailman/listinfo/python-list If your lists aren't so large that memory is an issue, this might be a good place for a variation of decorate, sort, undecorate. >>> listToSort = [ 108, 58, 68 ] >>> decorated = [ ( data, index ) for index, data in enumerate( listToSort ) ] >>> decorated [(108, 0), (58, 1), (68, 2)] >>> result = [ None, ] * len( listToSort ) >>> for sortedIndex, ( ignoredValue, originalIndex ) in enumerate( sorted( decorated ) ): ... result[ originalIndex ] = sortedIndex ... >>> result [2, 0, 1] -- John Krukoff Land Title Guarantee Company From jordanrastrick at gmail.com Thu Jul 24 04:11:47 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 01:11:47 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> Of course not. I just think Explicit is better than Implicit is taken seriously by a large segment the Python community as a guiding principle, and overall its influence does more harm than good. Clearly self being in every argument list was a decision arrived at long before the Zen was ever coined. Its merely an example of what I feel is a shortcoming in the conventional 'pythonic' approach to thinking about problems. The reluctance to admit that the __eq__ behaviour is a poor design choice is further evidence; its something (unlike self) that quite conceivably could be changed, and should be changed, but its somehow seen (by certain people) as the way that Python should do things. From paul at subsignal.org Tue Jul 15 05:37:57 2008 From: paul at subsignal.org (paul) Date: Tue, 15 Jul 2008 11:37:57 +0200 Subject: FOSS projects exhibiting clean/good OOP? In-Reply-To: <3bd416cf-6989-44fb-961d-658032231356@m73g2000hsh.googlegroups.com> References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> <3bd416cf-6989-44fb-961d-658032231356@m73g2000hsh.googlegroups.com> Message-ID: Phillip B Oldham schrieb: > Thanks all - lots to go through there! :D > > I'd heard previously that Trac was a nice example, or rather its core > was, but I'd also heard that there were lots of problems with it and > that they were redeveloping it from scratch? They continually improve parts of it, but I don't know of any severe problems whatsoever. Yes people are moaning about lack of multi-project support but that was a design decision way back. From a programming POV, I highly recommend looking at the source. The component model looks simple but is very powerful. It's also a good example how code benefits from interfaces wrt. structuring and documentation. cheers Paul From fredrik at pythonware.com Wed Jul 16 09:55:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 15:55:13 +0200 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: Ken Hartling wrote: > Thanks .. but I want to find out if the system is "running on 64bit" > even when the interpreter is a 32-bit build executable ("what python > was built on"). platform.architecture() and platform() in general > seems to only be looking at the build executable You can pass in an arbitrary binary to architecture(), so I guess you could use this on some suitable thing under "/bin" on a Unix box. This doesn't work on Windows, though. In this message, http://mail.python.org/pipermail/python-list/2005-June/326158.html Thomas Heller suggests using ctypes to call the Windows API directly; so something like this could work: >>> import ctypes, sys >>> i = ctypes.c_int() >>> kernel32 = ctypes.windll.kernel32 >>> process = kernel32.GetCurrentProcess() >>> kernel32.IsWow64Process(process, ctypes.byref(i)) 1 >>> is64bit = (i.value != 0) >>> is64bit False (IsWow64Process returns a non-zero value if it manages to check the status, and sets the variable to a non-zero value if the process is running under WOW64. I only have 32-bit boxes here, so it's only partially tested). And yes, looks like official support for this might appear in 2.6: http://mail.python.org/pipermail/python-dev/2008-May/079022.html (in that thread, Mark Hammond suggests "'64 bit' in sys.version" as a workaround, but warns for false negatives). From siona at chiark.greenend.org.uk Wed Jul 30 09:07:06 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 30 Jul 2008 14:07:06 +0100 (BST) Subject: Build tool for Python References: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Message-ID: Hussein B wrote: >Apache Ant is the de facto building tool for Java (whether JSE, JEE >and JME) application. >With Ant you can do what ever you want: [ ... ] ... bash your head against your desk for hours trying to make sense of its classloader system, struggle for days on end trying to make it understand building anything outside the Java world, write piles of tedious and often boilerplate XML, wonder what happened to javac's ability to resolve dependencies to make this necessary ... Put it like this, my experience has lead me to regard Ant as a retrograde step compared to make. I can't understand why anyone would want to inflict such a thing on a Python project. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From __peter__ at web.de Fri Jul 18 08:21:55 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 14:21:55 +0200 Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: nicolas.pourcelot at gmail.com wrote: > On 18 juil, 13:13, Peter Otten <__pete... at web.de> wrote: >> nicolas.pource... at gmail.com wrote: >> > In fact, 'any(myobject is element for element in mylist)' is 2 times >> > slower than using a for loop, and 'id(myobject) in (id(element) for >> > element in mylist)' is 2.4 times slower. >> >> This is not a meaningful statement unless you at least qualify with the >> number of item that are actually checked. For sufficently long sequences >> both any() and the for loop take roughly the same amount of time over >> here. >> > > Sorry. I used short lists (a list of 20 floats) and the element > checked was not in the list. > (That was the case I usually deals with in my code.) What is your (concrete) use case, by the way? If you want efficiency you should use a dictionary instead of the list anyway: $ python -m timeit -s"d=dict((id(i), i) for i in range(1000)); x = 1000" "id(x) in d" 1000000 loops, best of 3: 0.275 usec per loop Peter From scottpig1 at comcast.net Sun Jul 27 20:54:26 2008 From: scottpig1 at comcast.net (pigmartian) Date: Sun, 27 Jul 2008 20:54:26 -0400 Subject: ctypes - unloading implicitly loaded dlls Message-ID: (my apologies if this is a repost, but it sure seems like the first attempt disappeared into the ether...) I'm writing a program that uses functionality from two different sets of cdlls which reside in two different directories, call them 'libA.dll' and 'libB.dll'. Although I don't directly use it, both directories contain a dll with the same name, although they aren't in fact identical. Call them, "libC.dll". However, the c-functions I call from the clls I do use seem to implicitly use "libC.dll". The problem that occurs after I load one dll and call functions in it, when I try to load the second dll I get windows errors because the second dll tries to call a function in its version of libC.dll, but it finds the version meant for libB.dll, which doesn't contain that function. Oy, I hope some sample code makes it clearer: def demo(): A = ctypes.cdll.LoadLibrary('/path1/libA.dll') A.foo() # implicitly uses '/path1/libC.dll' _ctypes.FreeLibrary(A._handle) # CRASH! B = ctypes.cdll.LoadLibrary('/path2/libB.dll') # "The procedure entry point some_func could not be located # in the dynamic link library libC.dll.": # libB.dll wants to use code from '/path2/libC.dll', but # instead it finds '/path1/libC.dll' already loaded # in memory, which doesn't # contain the function call it wants. Assuming my understanding of things is correct, then I believe what I need to do is to remove /path1/libC.dll from memory before I try loading libB.dll, but I haven't found any way of doing that. Can anyone offer my some suggestions? Or, am I S.O.L.? Notes: * the two sets of dlls are supplied by a vendor for working with its COTS packages; I don't have any control over the dll names used or the code therein. * If I leave out the call to A.foo(), then I don't crash, but if I leave out the FreeLibrary call as well then I do crash. * I've tried manipulating the PATH before loading the dlls, to no effect. * I've tried del'ing A and running gc.collect() before loading B. Thanks, Scott From jordanrastrick at gmail.com Thu Jul 24 06:24:31 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 03:24:31 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <8233fbfb-ad9b-43ef-b722-9738ef129d0b@q5g2000prf.googlegroups.com> On Jul 24, 8:01?pm, Lawrence D'Oliveiro wrote: > In message > <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, Jordan > wrote: > > > Except when it comes to Classes. I added some classes to code that had > > previously just been functions, and you know what I did - or rather, > > forgot to do? Put in the 'self'. In front of some of the variable > > accesses, but more noticably, at the start of *every single method > > argument list.* > > The reason is quite simple. Python is not truly an "object-oriented" > language. It's sufficiently close to fool those accustomed to OO ways of > doing things, but it doesn't force you to do things that way. You still > have the choice. An implicit "self" would take away that choice. You could still explicitly request non-implicit self on a method by method basis. From rharkins at nettrekker.com Tue Jul 1 17:13:19 2008 From: rharkins at nettrekker.com (Rich Harkins) Date: Tue, 01 Jul 2008 17:13:19 -0400 Subject: Why is recursion so slow? In-Reply-To: References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Message-ID: <486A9DEF.8030004@nettrekker.com> Nick Craig-Wood wrote: [snip] > By definition any function in a functional language will > always produce the same result if given the same arguments, so you can > memoize any function. > Ah, so that's why time.time() seems to be stuck... ;) Rich From abhishekatmanit at gmail.com Wed Jul 2 06:01:36 2008 From: abhishekatmanit at gmail.com (Abhishek Wadhava) Date: Wed, 2 Jul 2008 15:31:36 +0530 Subject: Using Bluetooth Module Message-ID: <6279b7260807020301q534d90f3k47a02079a32a9540@mail.gmail.com> Hi..!! I was thinking to perform bluetooth Communication with Python. So can any1 guide me from where to start...i mean any particular module or library for that, any documentations for that..etc etc... -------------- next part -------------- An HTML attachment was scrubbed... URL: From knielsen73 at gmail.com Wed Jul 23 21:06:50 2008 From: knielsen73 at gmail.com (knielsen73 at gmail.com) Date: Wed, 23 Jul 2008 18:06:50 -0700 (PDT) Subject: fill in 3D array Message-ID: <3180f972-f2d4-43ff-81de-bcdd0a2ef906@59g2000hsb.googlegroups.com> Hi, I am a python newbie, trying to convert my IDL scripts to python. I am kind of stuck at the moment. I am reading in a 1-D data file with 2000 data points. I need to put them in a 3-D array with size [10,10,20]. I have defined the field array as arr = zeros((10,10,20)) but don't know how to read the data into the array. Also, I need to extract a slice of a 3-D array and tried a = array_name(:,:,20) but that didn't work. Thanks, Kim From Nikolaus at rath.org Sat Jul 26 05:08:12 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Sat, 26 Jul 2008 11:08:12 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> Message-ID: <87ljzpt3lv.fsf@nokile.rath.org> Terry Reedy writes: > Nikolaus Rath wrote: >> Terry Reedy writes: >>> Torsten Bronger wrote: >>>> Hall?chen! >>> > And why does this make the implicit insertion of "self" difficult? >>>> I could easily write a preprocessor which does it after all. >>> class C(): >>> def f(): >>> a = 3 >>> >>> Inserting self into the arg list is trivial. Mindlessly deciding >>> correctly whether or not to insert 'self.' before 'a' is impossible >>> when 'a' could ambiguously be either an attribute of self or a local >>> variable of f. Or do you and/or Jordan plan to abolish local >>> variables for methods? >> >> Why do you think that 'self' should be inserted anywhere except in the >> arg list? AFAIU, the idea is to remove the need to write 'self' in the >> arg list, not to get rid of it entirely. > > Because you must prefix self attributes with 'self.'. If you do not > use any attributes of the instance of the class you are making the > function an instance method of, then it is not really an instance > method and need not and I would say should not be masqueraded as > one. If the function is a static method, then it should be labeled > as one and no 'self' is not needed and auto insertion would be a > mistake. In brief, I assume the OP wants 'self' inserted in the body > because inserting it only in the parameter list and never using it > in the body is either silly or wrong. I think you misunderstood him. What he wants is to write class foo: def bar(arg): self.whatever = arg + 1 instead of class foo: def bar(self, arg) self.whatever = arg + 1 so 'self' should *automatically* only be inserted in the function declaration, and *manually* be typed for attributes. Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From cjw at ncf.ca Fri Jul 25 08:12:59 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 25 Jul 2008 08:12:59 -0400 Subject: Autocompletion and Interactive Tables in a Python IDE In-Reply-To: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> References: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Message-ID: Anthony wrote: > Hi, I'm a FoxPro programmer, but I want to learn python before it's > too late. I do a lot of statistical programming, so I import SPSS > into python. In my opinion, the best features of Visual FoxPro 9.0 > were: > a) Intellisense (tells you what classes/methods are available and what > variables go into a function) > b) Code Completion (guesses your code after four letters) > c) Data-Orientation; multiple data sessions can be open, data can be > viewed easily > For Windows users, PyScripter provides a) and b). I don't understand what you are seeking with c). Colin W. From kyosohma at gmail.com Thu Jul 31 11:51:18 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 31 Jul 2008 08:51:18 -0700 (PDT) Subject: Newbie Python questions References: Message-ID: <2a30b583-16e2-41c2-a31a-3e66b1eb5dbc@x41g2000hsb.googlegroups.com> On Jul 29, 12:28?pm, LessPaul wrote: > I recently discovered Python and see it as a great language to use for > personal projects (and more). I made my living for over a decade as a > coder in C, C++, ADA, Fortran, and Assembly before moving to systems > engineering. > > I'm now retired, and would love to code again. I see Python as the > perfect language to get a good program working in a short time. My > question is in regard to GUI platforms. My primary target would be > Windows, but I would also like be able to support Linux and Mac > versions if possible. I'm also interested in using a system that also > has support for pure C++ applications. As such, and after reading many > web pages regarding Python GUIs, I believe I have the candidates > narrowed down to pyQT and wxPython. > > The first question -- how steep is the curve to become proficient with > the above GUI packages? If the answer is "not very" then there is no > need for the following questions as I can try both on for size to see > which I like best. However if it is a sizable investment in time, I'd > like to maximize my efforts and choose the one I'll end up using in > the end. > > The biggest hurdle I can see is the cost of the QT licence for > commercial software, though apparently it can be acquired for a > reasonable price via the BlackAdder package. Does purchasing the > BlackAdder also include the needed software support for C++ > development? Does the BlackAdder purchase also allow for licence of > standard C++ apps? > > Since there appears to be no commercial licencing fee for wxWidgets/ > wxPython, the last question is what do I gain from going QT over wx? > I've seen great applications written with both (on my computer I have > the wxPython Digsby and the pyQT apps "Mnemosyne" and "Anki". All seem > to be solid. Tim forgot to mention that the wxPython user's group is very helpful and fun. I don't know how the pyQT one is. You could try both toolkits just working on some toy projects before you work on anything commercial. Then they're both free! And you can find out which one better suits you. Mike From deets at nospam.web.de Fri Jul 11 07:07:04 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 11 Jul 2008 13:07:04 +0200 Subject: How to serialize and deserialize the objects into memory? In-Reply-To: <0a7ead85-2a38-41a8-98b8-59dede61f985@c58g2000hsc.googlegroups.com> References: <0a7ead85-2a38-41a8-98b8-59dede61f985@c58g2000hsc.googlegroups.com> Message-ID: <6dot6qF3m7fsU1@mid.uni-berlin.de> hardemr schrieb: > Hello Everyone, > > I want to serialize and deserialize the objects into Memory not into > file. How can i do that? Use pickle & module StringIO/cStringIO as file-to-memory-object. Diez From pavlovevidence at gmail.com Wed Jul 30 21:26:30 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 30 Jul 2008 18:26:30 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> <29a131a5-d813-407a-b774-6f90b7f8f3e3@w1g2000prk.googlegroups.com> Message-ID: <78ef923c-3065-4d9e-ad52-f94d91bee920@k13g2000hse.googlegroups.com> On Jul 30, 3:56 am, Erik Max Francis wrote: > Carl Banks wrote: > > I mean in general. I wouldn't spell it like that. I would prefer if > > empty(x), with an __empty__ method. (And support __nonzero__ aka > > __bool__ dropped completely.) > > So your argument is purely about style, then. You just wish it were > written differently. No, you misunderstand and/or misstate my position again. I realize I wasn't as clear as I could have been. First of all it's not my "argument": this is a tangent. There would be a built-in empty, which invokes __empty__, in the same way len invokes __len__. It would only be defined for container types. (Iterators could choose whether to define it and it would mean that the iterator is guaranteed stop on the next iteration. The iterator is free to read and store the item. If the iterator doesn't know whether it will stop, it must not define __empty__ or raise an exception in it.) It would become the One Obvious Way to test for emptiness. __nonzero__ would disappear and not be replaced with anything, and objects would not have implicit boolean conversion. Carl Banks From rocksportrocker at googlemail.com Tue Jul 22 03:05:48 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Tue, 22 Jul 2008 00:05:48 -0700 (PDT) Subject: fromfile error on windows, not mac References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> Message-ID: <9650a33b-40b5-46a7-a05e-5b059117891f@b1g2000hsg.googlegroups.com> jadamwil schrieb: > Hello, > I am using the numpy fromfile function to read binary data from a file > on disk. The problem is that the program runs fine on a Mac, but gives > an error or warning on windows when trying to read the data. I use it > like this: > > Signal = zeros((N, 16), dtype=float32) > for sample in range(0, N): > # this function gets the next position in the file to seek to > s = getFilePos(sample) > > # go to the correct location in the file; this IS checked to make > sure it is within the file > mFile.seek(s) > > # read the 16 float32 values from the file > D = fromfile(mFile, dtype=numpy.float32, 16) > > # save D in Signal > Signal[sample, :] = D > > This will fail when sample is ~4. If I change the range to (5,N), > skipping the "bad" file location, it will run fine for a few samples, > and then give another error. The message it gives is: > "16 items requested but only 7 read" > > So D is a 7x1 vector, and the program dies when it tries to assign D > to the slice of Signal ("ValueError: shape mismatch: objects cannot be > broadcast to a single shape"). > > On windows, the Python version is 2.5.2, and the most recent numpy and > scipy are being used as well. I tried using Enthought, but it gave > this error as well, in addition to a c runtime error whenever I > imported scipy (which is another post topic...). > > Any ideas on what might be causing this? Is there a way to debug the > fromfile function? And, remember, this works perfectly on a Mac. Would > compiling everything (python, scipy, numpy) potentially solve this? Did you open the file in binary mode ? Greetings, Uwe From snowballz.game at gmail.com Sun Jul 20 00:26:32 2008 From: snowballz.game at gmail.com (Michael Lubker) Date: Sat, 19 Jul 2008 23:26:32 -0500 Subject: Any Game Developers here? In-Reply-To: References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: <76b841590807192126r5ed40f55gc48ce7f9e1b423d2@mail.gmail.com> Rabbyt is developed by one of my colleagues. I'm currently using Python-Ogre and Anims (for 3D animation, broken off from Rabbyt by Matthew) for my game, SnowballZ. Thanks Michael On Sat, Jul 19, 2008 at 10:33 PM, Python Nutter wrote: > I used to use PyGame but the horrible delay waiting for OS X binaries > put me off. > > I now use Pyglet extensively, and combine Pyglet + Rabbyt to get > amazing sprite handling speeds. > > Pyglet/Rabbyt make use of OpenGL which comes installed on all the > major systems out there. > > PyGame requires the installation of the SDL library to work so is a > lot larger installation requirement. > > There are two books I know of currently in print on game programming, > both use PyGame as it was out first. One book is horrible and only > worth for cleaning yourself up after you use the bathroom. The second > is really well written (The L express game programming book) and > highly recommended if you need to get some basic game design and > programming under your belt in Python. > > That said its stupidly easy to port examples to work on Pyglet/Rabbyt > so you won't do yourself a dis-service if you want to buy the book but > want to develop later in Pyglet/Rabbyt. > > Cheers, > PN > > P.S. Since you've likely found Pyglet and PyGame already, the only > other reference URL you need is for Rabbyt so go here for that: > http://matthewmarshall.org/projects/rabbyt/ > > > 2008/7/19 Michael Lubker : >> Any people that use Python as the predominant language for their game >> development here? >> >> ~Michael >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > -- ~ "The world hates change, yet it is the only thing that has brought progress." ~ Charles Kettering http://snowballz.joey101.net From gherron at islandtraining.com Thu Jul 10 20:18:09 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 10 Jul 2008 17:18:09 -0700 Subject: Can anyone suggest a date peocedure... In-Reply-To: References: Message-ID: <4876A6C1.3010902@islandtraining.com> RV wrote: > On Thu, 10 Jul 2008 13:39:29 -0700, Gary Herron > wrote: > > > >> The datetime module has what you need. >> >> It has methods (with examples) on building a datetime object from a >> string, and it has a object named timedelta, and the ability to subtract >> a timedelta from a time. >> >> For instance, the time right now and the time exactly one day ago: >> >> >>>>> from datetime import * >>>>> datetime.today() >>>>> >> datetime.datetime(2008, 7, 10, 13, 38, 48, 279539) >> >>>>> datetime.today()-timedelta(1) >>>>> >> datetime.datetime(2008, 7, 9, 13, 38, 50, 939580) >> >> >> Gary Herron >> > > Thanks Gary! This works great. Now all I need to know is how to > plug the date into the datetime object from a string. > Use *strptime*( date_string, format) The format argument uses %-fields to describe how to pull data out of the date_string. It uses the same set of %-fields as the time modules strftime function Gary Herron > Ron > > -- > http://mail.python.org/mailman/listinfo/python-list > From larry.bates at websafe.com` Tue Jul 22 23:40:52 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 22 Jul 2008 22:40:52 -0500 Subject: Python Written in C? In-Reply-To: References: Message-ID: Grant Edwards wrote: > On 2008-07-22, Larry Bates wrote: >> Grant Edwards wrote: >>> On 2008-07-22, Larry Bates wrote: >>> >>>> You talk about "writing it in assembly language for each MPU >>>> chip". Actually it is even better than that. We now have >>>> these modern inventions, called compilers that do that type of >>>> work for us. They translate high level instructions, not >>>> into assembler but into machine language. >>> Actually, all of the compilers I'm familiar with (gcc and a >>> handful of cross compilers for various microprocessors) >>> translate from high-level languages (e.g. C, C++) into >>> assembly, which is then assembled into relocatable object >>> files, which are then linked/loaded to produce machine >>> language. >>> >> I just learned something I did not know. I was under the >> impression that they translated directly to machine code >> without ever actually generating Assembler text files. > > There may indeed be compilers that work that way. On Unix > systems (which is what I work with) compilers have > traditionally generated assembly language files. > >> Seems like a waste to generate the text and turn around run >> that through the assembler, but what do I know. I guess that >> way the compiler can have pluggable assembler back-ends. > > Since you probably need an assembler anyway, generating > assembly-language in the compiler prevents you from having to > duplicate a bunch of object-code-generation code in two places. > I'm not sure I understand what you mean here. The code generation phase of the top level compiler would have to generate assembler mnemonics instead of just generating machine coded directly. At that point it should be just as easy to generate machine code, unless you take advantage of macros, or other helpers provided in the assembly phase. My "compiler" work was way back on mainframes and the ones I worked with definitely didn't produce assembler then needed to be run through the assembler. They created likable objects directly. But that was over 30 years ago! All this may be a moot point, because assembler is just a mnemonic representations of machine language anyway. -Larry From asmodai at in-nomine.org Thu Jul 17 03:48:38 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 17 Jul 2008 09:48:38 +0200 Subject: Instance In-Reply-To: <120cea3a-33a9-49ec-8932-7cef2e5aef17@25g2000hsx.googlegroups.com> References: <120cea3a-33a9-49ec-8932-7cef2e5aef17@25g2000hsx.googlegroups.com> Message-ID: <20080717074838.GI83562@nexus.in-nomine.org> -On [20080717 09:01], karthikbalaguru (karthikbalaguru79 at gmail.com) wrote: >AttributeError : Classroom instance has no attribute 'desk_offset' You are using a Classroom instance and probably assigning something to the instance's variable/attribute 'desk_offset'. Except that the class Classroom has no self.desk_offset. So in your class definition you would need to add something to __init__() like: self.desk_offset = None # or 0 or... -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B A frightened mental vortex we will be, a Sun we seek, a Sun we flee... From gherron at islandtraining.com Tue Jul 22 02:25:10 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 21 Jul 2008 23:25:10 -0700 Subject: string[i:j:k] In-Reply-To: <811e72db-a8bc-475a-b32a-38a9b6922600@k30g2000hse.googlegroups.com> References: <4a9a4cf3-9ef4-4d9e-b714-bbf62b7c1917@v1g2000pra.googlegroups.com> <811e72db-a8bc-475a-b32a-38a9b6922600@k30g2000hse.googlegroups.com> Message-ID: <48857D46.2080905@islandtraining.com> konstantin wrote: > On Jul 22, 9:18 am, alex23 wrote: > >> On Jul 22, 3:10 pm, konstantin wrote: >> >> >>> some_string[i:j:k] >>> What does it mean? >>> >> i = start position, j = end position, k = step size >> >> >>>>> s = "ABABABABABABAB" >>>>> s[0:6:2] >>>>> >> 'AAA' >> >>>>> s = "ABCABCABCABCABC" >>>>> s[0:6:3] >>>>> >> 'AA' >> >> Hope this helps. >> >> - alex23 >> > > Thanks! > It seems that negative step leads in reverse direction. > But logic isn't completely clear for me. > >>>> s = '123456789' >>>> s[::-2] >>>> > '97531' > > but > >>>> s[:-1:-2] >>>> The slice s[:-1] means start at zero and go to n-1(where n-len(s)) (it does not mean start at zero and go to -1) So since the indexing is counting upward, the step size had better be positive. Thus: >>> s = '123456789' >>> s[:-1:2] '1357' >>> Gary Herron > '' > though I expected something like '8642' > What did i missed? > > -- > http://mail.python.org/mailman/listinfo/python-list > From remy.blank at pobox.com Tue Jul 8 14:39:37 2008 From: remy.blank at pobox.com (Remy Blank) Date: Tue, 08 Jul 2008 20:39:37 +0200 Subject: Relative Package Import In-Reply-To: References: Message-ID: Robert Hancock wrote: > mypackage/ > __init__.py > push/ > __init__.py > dest.py > feed/ > __init__py ^ Missing dot here? -----------| > In subject.py I have > from ..push import dest > > But i receive the error: > Caught exception importing module subject: > File "/usr/local/python/lib/python2.5/site-packages/pychecker/ > checker.py", line 621, in setupMainCode() > module = imp.load_module(self.moduleName, file, filename, smt) > File "subject.py", line 1, in () > from ..feed import dest This last line contradicts your statement above... -- Remy From google at mrabarnett.plus.com Mon Jul 28 11:41:55 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 28 Jul 2008 08:41:55 -0700 (PDT) Subject: Python FTP - NameError: name 'mydpa' is not defined References: Message-ID: On Jul 28, 2:27?pm, "Harry" wrote: > Hi there. I am trying to download a file(sn.last) from a public FTP > server with the following code: > > from ftplib import FTP > ftp=FTP('tgftp.nws.noaa.gov') > ftp.login() > ftp.cwd('SL.us008001/DF.of/DC.radar/DS.81dpr/SI.kbuf') > ftp.retrbinar('RETR sn.last', open(mydpa,'wb').write) open(mydpa,'wb') would open the file to which you're saving the data, but you haven't defined to mydpa, so Python will complain. > ftp.quit() > > but got an error message, which I think is normal: > > Traceback (most recent call last): > ? File "", line 1, in > ? ? ftp.retrbinary('RETR sn.last', open(mydpa,'wb').write) > NameError: name 'mydpa' is not defined Yep! > > I don't know much about python, but just try to use the code to > download data. I don't know where the file will be saved to. Is the > mydata a file name or a folder name? where will it be saved to even > if it's working? Please help be fixed the problem step by step? I am > using 2.5.2 by the way. > You need to tell it where to save the data by defining mydpa. > I really appreciate your help. Thanks. From nclbndk759 at googlemail.com Fri Jul 18 09:43:03 2008 From: nclbndk759 at googlemail.com (nclbndk759 at googlemail.com) Date: Fri, 18 Jul 2008 06:43:03 -0700 (PDT) Subject: Regular expression help Message-ID: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> Hello, I am new to Python, with a background in scientific computing. I'm trying to write a script that will take a file with lines like c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647 3pv=0 extract the values of afrac and etot and plot them. I'm really struggling with getting the values of efrac and etot. So far I have come up with (small snippet of script just to get the energy, etot): def get_data_points(filename): file = open(filename,'r') data_points = [] while 1: line = file.readline() if not line: break energy = get_total_energy(line) data_points.append(energy) return data_points def get_total_energy(line): rawstr = r"""(?P.*?)=(?P.*?)\s""" p = re.compile(rawstr) return p.match(line,5) What is being stored in energy is '<_sre.SRE_Match object at 0x2a955e4ed0>', not '-11.020107'. Why? I've been struggling with regular expressions for two days now, with no luck. Could someone please put me out of my misery and give me a clue as to what's going on? Apologies if it's blindingly obvious or if this question has been asked and answered before. Thanks, Nicole From romanticlover123 at gmail.com Sat Jul 19 00:35:04 2008 From: romanticlover123 at gmail.com (kick) Date: Fri, 18 Jul 2008 21:35:04 -0700 (PDT) Subject: hi this is very romantic actress photes Message-ID: <5a4d2a70-32d6-4078-9999-36777365fb3f@o40g2000prn.googlegroups.com> hi this is very romantic actress photes ******************************************************************************** http://lovegroup341.blogspot.com/ *********************************************************************** use this and enjoy each moments From dominic.rice at gmail.com Thu Jul 3 21:56:23 2008 From: dominic.rice at gmail.com (Dominic Rice) Date: Fri, 04 Jul 2008 02:56:23 +0100 Subject: running python from cmd.exe Message-ID: Hi, I can't seem to get python to run my scripts using the command: python .py If I type python the interpreter runs as I sorted out the Path property, I'm afraid I don't know much about this kind of thing as I'm a science student who needs some Python not a programmer! Thanks in advance From Lie.1296 at gmail.com Sun Jul 27 07:28:55 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 27 Jul 2008 04:28:55 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> Message-ID: On Jul 27, 2:48?am, "Russ P." wrote: > > If, as I wrote, you permit the omission of "self" in method signatures > > defined within class definitions, then you could still insist on > > instance attribute qualification using "self" - exactly as one would > > when writing Java according to certain style guidelines. > > I'm not sure exactly what people mean here by allowing "self" to be > "omitted" in method signatures. If it is omitted, then it seems to me > that a place holder would be needed to the interpreter that the first > argument is not just another name for "self." > > In an earlier post on this thread (don't feel like looking it up at > the moment), someone suggested that member data could be accessed > using simply ".member". I think he might be on to something. The dot > is a minimal indicator that the data is a class member rather than > just local. However, a placeholder is still needed in the signature. > > So why not allow something like this?: > > class MyClass: > > ? ? def func( , xxx, yyy): > Why not? Because that would make someone new to python scream in terror. > ? ? ? ? .xxx = xxx > > ? ? ? ? local = .yyy > OTOH, this might come as a handy syntax sugar, this is like With Statement in VB, although in VB, you have to state explicitly what you want to call implicitly when using something of the .methods. But I think implementing this might come with a heavy toll to the parser. > The "self" argument is replaced with nothing, but a comma is used as a > placeholder. From bgporter at acm.org Fri Jul 25 15:38:34 2008 From: bgporter at acm.org (Brett g Porter) Date: Fri, 25 Jul 2008 15:38:34 -0400 Subject: Python program as daemon? In-Reply-To: <8bb6bd1a-cd85-4b7a-8fc9-844f3794bca0@c58g2000hsc.googlegroups.com> References: <8bb6bd1a-cd85-4b7a-8fc9-844f3794bca0@c58g2000hsc.googlegroups.com> Message-ID: <488A2BBA.3060303@acm.org> Johny wrote: > Is it possible to run a Python program as daemon? Sure -- see http://code.activestate.com/recipes/66012/ for an example (and some useful stuff in the comments.) From tjreedy at udel.edu Wed Jul 9 13:08:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 09 Jul 2008 13:08:58 -0400 Subject: how to remove oldest files up to a limit efficiently In-Reply-To: References: <1eb168ac-fc63-4724-8604-45e995a06b51@s50g2000hsb.googlegroups.com> Message-ID: Dan Stromberg wrote: > On Tue, 08 Jul 2008 15:18:23 -0700, linuxnow at gmail.com wrote: > >> I need to mantain a filesystem where I'll keep only the most recently >> used (MRU) files; least recently used ones (LRU) have to be removed to >> leave space for newer ones. The filesystem in question is a clustered fs >> (glusterfs) which is very slow on "find" operations. To add complexity >> there are more than 10^6 files in 2 levels: 16? dirs with equally >> distributed number of files inside. > >> Any suggestions of how to do it effectively? > > os.walk once. > > Build a list of all files in memory. > > Sort them by whatever time you prefer - you can get times from os.stat. Since you do not need all 10**6 files sorted, you might also try the heapq module. The entries into the heap would be (time, fileid) From pdorange at pas-de-pub-merci.mac.com Thu Jul 3 08:15:52 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Thu, 3 Jul 2008 14:15:52 +0200 Subject: Trouble using pinckle References: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> <1ijgp2r.1j1k5xwwbtiwcN%pdorange@pas-de-pub-merci.mac.com> <486ba8a4$0$11957$426a74cc@news.free.fr> Message-ID: <1ijia9i.j7cls41raaazgN%pdorange@pas-de-pub-merci.mac.com> Bruno Desthuilliers wrote: > > I try the staticmethod, it works fine. Very helpful. > > > > But i don't like it very much, it seems 'complicated' (python was > > supposed to be simple). > > Try doing the same thing in C++ !-) OK ;-) I just ask myself what was the best method (according to python phylosophy). -- Pierre-Alain Dorange Vid?o, DV et QuickTime Clarus, the DogCow From Lie.1296 at gmail.com Sat Jul 26 11:41:04 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 26 Jul 2008 08:41:04 -0700 (PDT) Subject: print doesn't respect file inheritance? References: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> Message-ID: <6b8b16c2-1822-4e83-94a6-a9d3f98fddc7@k36g2000pri.googlegroups.com> On Jul 26, 8:50?am, bukzor wrote: > I was trying to change the behaviour of print (tee all output to a > temp file) by inheriting from file and overwriting sys.stdout, but it > looks like print uses C-level stuff ?to do its writes which bypasses > the python object/inhertiance system. It looks like I need to use > composition instead of inheritance, but thought this was strange > enough to note. > > $python -V > Python 2.5 > > """A short demo script""" > class notafile(file): > ? ? def __init__(self, *args, **kwargs): > ? ? ? ? readonly = ['closed', '__class__', 'encoding', 'mode', 'name', > 'newlines', 'softspace'] > ? ? ? ? file.__init__(self, *args, **kwargs) > ? ? ? ? for attr in dir(file): > ? ? ? ? ? ? if attr in readonly: continue > ? ? ? ? ? ? setattr(self, attr, None) > > def main(): > ? ? n = notafile('/dev/stdout', "w") > ? ? print vars(n) > > ? ? import sys > ? ? sys.stdout = n > ? ? print "Testing: 1, 2, 3..." > > output: > {'__str__': None, 'xreadlines': None, 'readlines': None, 'flush': > None, 'close': None, 'seek': None, '__init__': None, '__setattr__': > None, '__reduce_ex__': None, '__new__': None, 'readinto': None, > 'next': None, 'write': None, '__doc__': None, 'isatty': None, > 'truncate': None, 'read': None, '__reduce__': None, > '__getattribute__': None, '__iter__': None, 'readline': None, > 'fileno': None, 'writelines': None, 'tell': None, '__delattr__': None, > '__repr__': None, '__hash__': None} > Testing: 1, 2, 3... Use this: class fakefile(object): def __init__(self, writeto, transformer): self.target = writeto self.transform = transformer def write(self, s): s = self.transform(s) self.target.write(s) sys.stdout = fakefile(sys.stdout, lambda s: '"' + s + '"') Inheriting from file is not the best way to do it since there is a requirement that child class' interface must be compatible with the parent class' interface, since the file-like object you're creating must have extremely different interface than regular file, the best way is to use Duck Typing, i.e. write a class that have .write() method. From larry.bates at websafe.com` Tue Jul 15 23:07:54 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 22:07:54 -0500 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: David Lees wrote: > kjhishere at gmail.com wrote: >> I need to know if I'm running on 32bit or 64bit ... so far I haven't >> come up with how to get this info via python. sys.platform returns >> what python was built on ... but not what the current system is. >> >> I thought platform.uname() or just platform.processor() would have >> done it, but python returns an empty string on windows. Any ideas? >> >> Thanks, Ken > > On my windows box this works: > > >>> platform.architecture() > ('32bit', 'WindowsPE') > > > David On Fedora Core 5 64-bit here is what I see: >>> import platform >>> platform.architecture() ('64bit', 'ELF') -Larry From omer at no-log.org Wed Jul 2 06:43:36 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Wed, 2 Jul 2008 12:43:36 +0200 Subject: beginner's questions - manipulating text files In-Reply-To: <486ABACE.9050103@umbc.edu> References: <486ABACE.9050103@umbc.edu> Message-ID: <200807021243.37001.omer@no-log.org> Le Wednesday 02 July 2008 01:16:30 Ben Keshet, vous avez ?crit?: > Hi, > > I am a very beginner Python programmer with limited programming > experience overall. > > I am trying to write a script that will search for the second and third > appearance of the symbol '@' in a file, will read a random line between > them, and write the line into a new file. So far I was only able to open > the file using 'open', but I am not sure how to proceed. I tried to read > it line by line using 'readline' but was not sure how to manipulate the > text the way I need to. > If the file you're reading is not too big, you can use file.readlines() which read all the files and returns its content as a list of lines. > Could anyone please give me |a basic guidance as for what functions may > be useful for my purpose? (e.g how to search for a string '@' in a text? > how to identify its location? text.find('@') will return the position of the first occurence of '@', or a negative value if not found. > how to choose a random number in a defined > range? random.randrange(start, stop) > how to read that line number from a text file? etc.)| if you read the file with readlines(), just lines[lineno] you'll find more infos in the following sections: http://docs.python.org/lib/bltin-file-objects.html http://docs.python.org/lib/string-methods.html http://docs.python.org/lib/module-random.html -- C?dric Lucantis From deets at nospam.web.de Thu Jul 3 14:46:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jul 2008 20:46:47 +0200 Subject: imap4_SSL from behind a proxy server In-Reply-To: References: Message-ID: <6d4l4pFrogsU1@mid.uni-berlin.de> Dave schrieb: > First to admit I'm a newbie at Python, IMAP, or SSL. And it's been a > long time since I've posted anything to a Usenet group. But I've > spent countless hours spinning my wheels on this one, so I thought I'd > ask for help. > > I'm trying write some Python code to connect to Gmail from work, where > I need to direct all non-HTTP traffic through a proxy server. Can > anyone provide syntax which would redirect the imap4_SSL method > through a proxy server:port? I suspect there are some environment > variables which, when set, will do this very easily and elegantly. I > also suspect there is a really complicated way to 'wrap' the imap > classes so as to force requests to go through a proxy which, as a > newbie, I am trying to avoid. > > FYI, I'm currently running Python 2.5.2. via IDLE on Windows XP. But > when this project is done, I will move it to Linux. AFAIK that's simply not possible. Proxying that is not transparent is only (for practical matters, there might be esoteric protocols that do that as well) defined for HTTP. So "I need to direct all non-HTTP traffic through a proxy server." does not make much sense - at least to me. In other words: there is no such thing as general proxying, and thus no support in any library e.g. imaplib or such. Do you have an example of an application (e.g. mailclient or such) that *does* support the above scenario? Diez From bruno.desthuilliers at gmail.com Fri Jul 18 09:08:44 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 18 Jul 2008 06:08:44 -0700 (PDT) Subject: property getter with more than 1 argument? References: Message-ID: On 17 juil, 16:57, mk wrote: > It seems like getter is defined in such way that it passes only 'self': > > class FunDict(dict): > def __init__(self): > self.fundict = dict() What's the use of inheriting from dict here ??? > def fget(self, fun): wrong signature for a property.fget callback > return fundict[fun.func_name] > def fset(self, newfun): > self.fundict[newfun.func_name] = newfun > > newfun = property (fget, fset) > > >>> a=FunDict() > >>> > >>> a.newfun=f1 > >>> > >>> a.newfun('f1') Note that you're passing a string, when your (incorrect) getter expects a function object. > Traceback (most recent call last): > File "", line 1, in > a.newfun('f1') > TypeError: fget() takes exactly 2 arguments (1 given) > > Is it possible to pass more than one argument to fget function? Yes : call it directly !-) Or remember the old saying: """ Any software problem can be solved by adding another layer of indirection. Except, of course, the problem of too much indirection. """ Steve Bellovin of AT&T Labs Applied to your problem, it would mean making your getter return a closure that will take the func or func name and return the result of the lookup, ie: def fget(self): return lambda funcname: self.fundict[funcname] But anyway: this is still a typical case of arbitrary overcomplexification. A plain dict would be enough. Or, given the context (as exposed in an earlier post here), I'd suggest something like: class CallbacksRegister(object): def __init__(self, **kw): self._store = dict(**kw) def register(self, func, name=None): if name is None: name = func.__name__ self._store(name) = func return func def get(self, name, default=None): return self._store.get(name, default) def __getattr__(self, name): try: return self._store[name] except KeyError: raise AttributeError('%s object has no attribute '%s'" % (self, name) callbacks = CallbacksRegister() @callbacks.register def f1(arg): print "f1", arg callbacks.f1("yadda") callbacks.get('f1')('yadda') > I know: I can define a function with property name ('newfun' in the > example) and call it with more arguments. But then I do not get the > benefits of setter and property in general! The benefit of computed attributes (the property class being only one possible implementation) is to decouple interface (looks like an ordinary attribute) from implementation (is in fact computed). And the benefit from this decoupling is that you don't have to write getters/ setters until you really need them, since you can then turn a plain attribute into a computed one without breaking the interface. I fail to see what "benefits" you get from a property in your above snippet. From mcl.office at googlemail.com Mon Jul 7 07:30:33 2008 From: mcl.office at googlemail.com (mcl) Date: Mon, 7 Jul 2008 04:30:33 -0700 (PDT) Subject: Confused yet again: Very Newbie Question Message-ID: Why can I not the change the value of a variable in another class, when I have passed it via a parameter list. I am sure I am being stupid, but I thought passed objects were Read/ Write eg ------------------------------------------------------------ #!/usr/bin/python class one(): #my Global Vars fred = 'fred' class three(): def createJoe(self, myName): c1 = one() myName = 'Joe' #********************* Question why does this not change variable fred in 'class one' print 'Three(Local): ' + myName + ' Three(Global): ' + c1.fred def main(): c1 = one() c3 =three() c3.createJoe(c1.fred) if __name__ == '__main__' : main() Results: Three(Local): Joe Three(Global): fred 'fred' in 'class one' does not get changed to 'joe' in 'class three' 'createJoe', even though I have passed 'class one' 'fred' to 'createJoe' I hope this makes sense. I did not think you had to make the distinction between 'byvar' and 'byref' as in Basic. Thanks Richard From adityashukla1983 at gmail.com Fri Jul 25 14:50:05 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Fri, 25 Jul 2008 13:50:05 -0500 Subject: Histogram and \lambda parameter of the laplacian curve. Message-ID: <73045cca0807251150r15c2f9ebh24350482ab01190d@mail.gmail.com> Thanks everyone for your earlier help. I have to plot a histogram of values lets say [0.5,0.6,0.8,0.9].I guess the histogram would show an exponential decay ie, the laplacian curve. I need to find the \lambda parameter of this curve . So please tell me if it be done through http://matplotlib.sourceforge.net/and are there any other libraries which can be used. Thanks in advance. Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From Ilan.i18n at gmail.com Tue Jul 8 06:45:51 2008 From: Ilan.i18n at gmail.com (Ilan) Date: Tue, 8 Jul 2008 03:45:51 -0700 (PDT) Subject: Does omniORBpy 3.2 supports DII? Message-ID: Hello, My apologies if this is not the correct forum for thses quiestions, by I'm rather new to python+CORBA Has anyone used omniORBpy as CORBA implementation? are there any drawbacks? Does omniORBpy 3.2 supports the Dynamic Invocation Interface? Thanks. Ilan From gherron at islandtraining.com Mon Jul 28 00:34:24 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 27 Jul 2008 21:34:24 -0700 Subject: Where is the correct round() method? In-Reply-To: <90d24864-c67a-4594-b121-d0760f9e145b@m45g2000hsb.googlegroups.com> References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> <90d24864-c67a-4594-b121-d0760f9e145b@m45g2000hsb.googlegroups.com> Message-ID: <488D4C50.1030908@islandtraining.com> josh logan wrote: > On Jul 27, 8:45 pm, pigmartian wrote: > >> it could be that 3.0 is using "banker's rounding" --- rounding to the >> even digit. the idea behind it behind it being to reduce error >> accumulation when working with large sets of values. >> >> >>> Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo >>> CPU". What system are you on? >>> >>> It could be that 2.5 is really 2.49999... which would round down to 2, >>> but on any modern CPU (using IEEE floating point), 2.5 should be >>> representable exactly. >>> >> > > That's exactly what's happening, pigmartian. Thank you for explaining > the reasoning behind this change. > So am I relegated to building my own round() function that behaves > like the original function? Or did they move the functionality to a > new method somewhere for backwards-compatibility? > This will work as you wish: math.floor(x+0.5) Gary Herron > -- > http://mail.python.org/mailman/listinfo/python-list > From ggpolo at gmail.com Tue Jul 1 12:39:10 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 1 Jul 2008 13:39:10 -0300 Subject: dynamically load from module import xxx In-Reply-To: References: Message-ID: On Tue, Jul 1, 2008 at 12:55 PM, Neal Becker wrote: > Guilherme Polo wrote: > >> On Tue, Jul 1, 2008 at 12:11 PM, Neal Becker wrote: >>> What is a good way to emulate: >>> >>> from module import xxx >>> where 'module' is a dynamically generated string? >>> >>> __import__ ('modulename', fromlist=['xxx']) >>> >>> seems to be what I want, but then it seems 'xxx' is not placed in >>> globals() (which makes me wonder, what exactly did fromlist do?) >> >> fromlist is used for importing subpackages/submodules of the first arg >> of __import__. Since you are using "modulename", I'm guessing it is >> not a package, fromlist will do nothing for you. >> To solve your problem you could do getattr(__import__('modulename'), >> 'xxx'). > > This seems to be what I want, don't know if there is a simpler way: > > stuff =['A','B'] > module = __import__ (modulename) > for e in stuff: > globals().update({e : module.__dict__[e]}) > You could change that line to: globals()[e] = getattr(module, e) > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From jorgen.maillist at gmail.com Tue Jul 8 04:12:09 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Tue, 8 Jul 2008 10:12:09 +0200 Subject: Very weird bug! In-Reply-To: <1c7f6a82-bd0b-46bc-a6b7-23bf9f4b5ee3@m36g2000hse.googlegroups.com> References: <1c1c343a-dd63-454a-8e29-a5c70281ad90@c58g2000hsc.googlegroups.com> <1c7f6a82-bd0b-46bc-a6b7-23bf9f4b5ee3@m36g2000hse.googlegroups.com> Message-ID: <11e49df10807080112r6dd5e66ei22f9dde35cf0e365@mail.gmail.com> Maybe the interpreter remembered the values of some objects you used? If you type in the interpreter, the objects you create have a lifetime as long as the interpreter is active, which means it can get a state behaviour that otherwise is not present if you start a new interpreter instance. To be safe you should always try it with a script and run it from the commandline to get the same 'state' everytime your script runs. - Jorgen On Mon, Jul 7, 2008 at 7:36 PM, ssecorp wrote: > i know, idid try it again and it works as expected. but how the h*** > did it not work that one time? > -- > http://mail.python.org/mailman/listinfo/python-list > From bockman at virgilio.it Wed Jul 30 11:36:29 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Wed, 30 Jul 2008 08:36:29 -0700 (PDT) Subject: undo a dictionary References: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> Message-ID: <59548d6c-b30d-4dda-99e8-d2495000f4e1@d77g2000hsb.googlegroups.com> On 30 Lug, 16:51, mmm wrote: > I found code to undo a dictionary association. > > def undict(dd, name_space=globals()): > ? ? for key, value in dd.items(): > ? ? ? ? exec "%s = %s" % (key, repr(value)) in name_space > > So if i run > > >>> dx= { 'a':1, 'b': 'B'} > >>> undict(dx) > > I get>>> print A, B > > 1 B > > Here, ?a=1 and b='B' > > This works well enough for simple tasks and I understand the role of > globals() as the default names space, but creating local variables is > a problem. Also having no output arguemtns to undict() seems > counterintuitive. ?Also, the function fails if the key has spaces or > operand characters (-,$,/,%). ?Finally I know I will have cases where > not clearing (del(a,b)) each key-value pair might create problems in a > loop. > > So I wonder if anyone has more elegant code to do the task that is > basically the opposite of creating a dictionary from a set of > globally assigned variables. ?And for that matter a way to create a > dictionary from a set of variables (local or global). ?Note I am not > simply doing and ?undoing dict(zip(keys,values)) Maybe you can use objects as pseudo name spaces and do sommething like this: >>> class Scope(object): def dict(self): res = dict() for k, v in self.__dict__.items(): res[k] = v return res def undict(self, dict): for k,v in dict.items(): setattr(self, k, v ) >>> myscope = Scope() >>> myscope.undict(dict(A=1, B=2)) >>> myscope.A 1 >>> myscope.B 2 >>> myscope.dict() {'A': 1, 'B': 2} >>> Ciao ------ FB From larry.bates at websafe.com` Tue Jul 22 21:47:05 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 22 Jul 2008 20:47:05 -0500 Subject: How do I compare files? In-Reply-To: References: Message-ID: Clay Hobbs wrote: > I am making a program that (with urllib) that downloads two jpeg files > and, if they are different, displays the new one. I need to find a way > to compare two files in Python. How is this done? > > -- Ratfink > Use md5 to calculate checksum: import md5 md5file1 = md5.md5(open(filename1).read()).hexdigest() md5file2 = md5.md5(open(filename2).read()).hexdigest() if md5file1 != mdfile2: # # Do whatever you want # -Larry From Nikolaus at rath.org Mon Jul 28 03:35:16 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 28 Jul 2008 09:35:16 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <488D5B2C.10808@gmail.com> Message-ID: <87proysbpn.fsf@nokile.rath.org> Michael Torrie writes: > Colin J. Williams wrote: >>> >>> def fun( ., cat): >>> >> I don't see the need for the comma in fun. > > It (the entire first variable!) is needed because a method object is > constructed from a normal function object: > > def method(self,a,b): > pass > > class MyClass(object): > pass > > MyClass.testmethod=method > > That's precisely the same as if you'd defined method inside of the class > to begin with. A function becomes a method when the lookup procedure in > the instance object looks up the attribute and returns (from what I > understand) essentially a closure that binds the instance to the first > variable of the function. The result is known as a bound method, which > is a callable object: > >>>> instance=MyClass() > >>>> instance.testmethod > > > > > How would this work if there was not first parameter at all? > > In short, unlike what most of the implicit self advocates are > saying, it's not just a simple change to the python parser to do > this. It would require a change in the interpreter itself and how it > deals with classes. Thats true. But out of curiosity: why is changing the interpreter such a bad thing? (If we suppose for now that the change itself is a good idea). Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From ward.david at comcast.net Tue Jul 15 10:22:09 2008 From: ward.david at comcast.net (ward.david at comcast.net) Date: Tue, 15 Jul 2008 07:22:09 -0700 (PDT) Subject: Is it legal to rebuild Python.exe to include Version property tab? Message-ID: My company distributes a COM object that can be license and userd by our customers. Some of my company's internal application also use the COM object. However, for internal applications, instead of licensing the COM object, we just make the application registered as "friendly". We accomplish this be including various information in the "version" property tab of the calling EXE. In my case, the calling EXE is Python.exe. So, my question is, can we rebuild Python.exe to include the various "version" information? Is this allowed under the Python licensing agreement? From fuzzyman at gmail.com Sun Jul 13 09:44:00 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 13 Jul 2008 06:44:00 -0700 (PDT) Subject: Why is this blowing the stack, thought it was tail-recursive... References: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> Message-ID: On Jul 13, 7:56?am, Steven D'Aprano wrote: > On Sat, 12 Jul 2008 19:25:18 -0400, Terry Reedy wrote: > > ssecorp wrote: > >> def fib(n): > >> ? ? def fibt(a, b, n): > >> ? ? ? ? if n <= 1: > >> ? ? ? ? ? ? return b > >> ? ? ? ? else: > >> ? ? ? ? ? ? return fibt(b, a + b, n - 1) > >> ? ? if n == 0: > >> ? ? ? ? return 0 > >> ? ? else: > >> ? ? ? ? return fibt(0, 1, n); > > >> and can memoization speed up this even more? tesintg with memoization > >> doesnt really say anything because it is so fast it is instant anyway. > > > Except for the fact that a+b gets slower as a and b get bigger, this > > would already be linear time in n. ?Memoization (here by means of a > > linear list) only helps if the list is preserved and one makes repeated > > requests for various fib values. > > > I am just curious what input you tried that blew the stack? ?It had to > > be pretty large. > > No, not really. Try it for yourself: on my system, I get RuntimeError: > maximum recursion depth exceeded with fib(999). > > fib(999) is a large number, with 208 digits, but not that large: > > 268638100244853593861467272021429239676166093189869523401 > 231759976179817002478816893383696544833565641918278561614 > 433563129766736422103503246348504103776803673341511728991 > 69723197082763985615764450078474174626L > > -- > Steven The default CPython recursion limit is 1000 - so hitting it with an input of 999 is not that surprising... You can set a higher limit with sys.setrecursionlimit(...) Michael Foord http://www.ironpythoninaction.com/ From fredrik at pythonware.com Wed Jul 23 04:01:45 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 10:01:45 +0200 Subject: maximum value in a column of file In-Reply-To: <4886DCF3.10107@isac.cnr.it> References: <4886DCF3.10107@isac.cnr.it> Message-ID: maurizio wrote: > which is the best way for the calculation of the maximum value in a > column of a file? what approach have you tried, and what happened when you tried it? From google at mrabarnett.plus.com Sat Jul 26 12:26:23 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 26 Jul 2008 09:26:23 -0700 (PDT) Subject: Easier way to get the "here" path? References: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> Message-ID: <193ca421-7772-45cd-8fde-6ad594914732@p25g2000hsf.googlegroups.com> On Jul 25, 10:08?pm, bukzor wrote: > I have to go into these convulsions to get the directory that the > script is in whenever I need to use relative paths. I was wondering if > you guys have a better way: > > from os.path import dirname, realpath, abspath > here = dirname(realpath(abspath(__file__.rstrip("c")))) > > In particular, this takes care of the case of symlinked, compiled > scripts, which is fairly common at my workplace, and I imagine in many > *nix evironments. > > An illustration: > $echo "print __file__" > symlinks/path.py > $ln -s symlinks/path.py > $python>>> import path > path.py > >>> reload(path) > > path.pyc > >>> path.__file__ > 'path.pyc' > >>> path.__file__.rstrip("c") > 'path.py' > >>> from os.path import abspath, realpath > >>> realpath(path.__file__.rstrip("c")) > > '/home/bgolemon/python/symlinks/path.py'>>> realpath(abspath(path.__file__.rstrip("c"))) > > '/home/bgolemon/python/symlinks/symlinks/path.py' How about: import os import sys here = os.path.realpath(os.path.dirname(sys.argv[0])) It's a little clearer. :-) From s0suk3 at gmail.com Fri Jul 25 02:09:09 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Thu, 24 Jul 2008 23:09:09 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> On Jul 24, 5:01 am, Lawrence D'Oliveiro wrote: > In message > <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, Jordan > wrote: > > > Except when it comes to Classes. I added some classes to code that had > > previously just been functions, and you know what I did - or rather, > > forgot to do? Put in the 'self'. In front of some of the variable > > accesses, but more noticably, at the start of *every single method > > argument list.* > > The reason is quite simple. Python is not truly an "object-oriented" > language. It's sufficiently close to fool those accustomed to OO ways of > doing things, but it doesn't force you to do things that way. You still > have the choice. An implicit "self" would take away that choice. By that logic, C++ is not OO. By that logic, Ruby is not OO. By that logic, I know of only one OO language: Java :) The fact that a language doesn't force you to do object-oriented programming doesn't mean that it's not object-oriented. In other words, your words are nonsense. Sebastian From andreas.tawn at ubisoft.com Tue Jul 15 13:28:09 2008 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Tue, 15 Jul 2008 19:28:09 +0200 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: <487CD564.5020008@hughes.net> References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> <487CD564.5020008@hughes.net> Message-ID: <8AEDA5E3386EA742B8C24C95FF0C758004622F93@PDC-MAIL3.ubisoft.org> >defn noob wrote: >> isPrime works when just calling a nbr but not when iterating on a >> list, why? adding x=1 makes it work though but why do I have to add >> it? >> Is there a cleaner way to do it? >> >> >> def isPrime(nbr): >> for x in range(2, nbr + 1): >> if nbr % x == 0: >> break >> if x == nbr: >> return True >> else: >> return False >> >>>>> [isPrime(y) for y in range(11)] >> >> Traceback (most recent call last): >> File "", line 1, in >> [isPrime(y) for y in range(11)] >> File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime >> if x == nbr: >> UnboundLocalError: local variable 'x' referenced before assignment >> >> >>>>> map(isPrime, range(100)) >> >> Traceback (most recent call last): >> File "", line 1, in >> map(isPrime, range(100)) >> File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime >> if x == nbr: >> UnboundLocalError: local variable 'x' referenced before assignment >>>>> isPrime(10) >> False >>>>> isPrime(11) >> True >> >> >> >> adding x=1 makes it work though: >> >> def isPrime(nbr): >> x=1 >> for x in range(2, nbr + 1): >> if nbr % x == 0: >> break >> if x == nbr: >> return True >> else: >> return False >> >> >>>>> [isPrime(y) for y in range(11)] >> [False, True, True, True, False, True, False, True, False, False, >> False] >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > >======================================== >Yep - "local variable 'x' referenced before assignment" is correct. >You state: for x in range... but x doesn't exist until initialized. > To save a loop, initialize x=2 (the minimum value) and loop executes > on pass one. >In a straight 'C' program > ( for (x=1, x=(nbr+1), x++) etc... ) > the x is initialized and forceably incremented. > seems Python does not auto initialize but does auto increment. I think a better explanation is that in your original function, x only existed while the for loop was running. As soon as execution hit the break statement, x ceased to exist. When you attempted to reference it in the next line, Python has no variable called x so it complains that x hasn't been initialised. A more idiomatic way to write it... def isPrime(nbr): if nbr <= 1: return False for x in xrange(2, nbr+1): if not nbr % x: return x == nbr Cheers, Drea From randall at ymail.com Wed Jul 2 03:03:34 2008 From: randall at ymail.com (R W) Date: Wed, 2 Jul 2008 00:03:34 -0700 (PDT) Subject: extending auto_dict Message-ID: <694401.92884.qm@web46104.mail.sp1.yahoo.com> I'm using the excellent 'auto_dict' (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/537637) but I'd like to be able to extend it. Currently my program has class auto_dict(dict): def __getitem__(self, key): return self.setdefault(key, self.__class__()) daily=auto_dict() try: daily['today']['now'].append((1,2)) except AttributeError: daily['today']['now']=[(1,2)] Which works OK but I thought it would be easy to supply an 'append' method to the auto_dict class that would save me from having all those try/except blocks scattered through my code ie I could just say daily['today']['now'].append((1,2)) and the class would take care of catching the exception and assigning the list. I tried adding def append(self,item): self=[item] return self to the class definition but it doesnt actually assign the value. Can it be done this way? Some other way? Or am I stuck using the try/except blocks? (please CC me since I'm not subscribed to the list) Get the name you always wanted with the new y7mail email address. www.yahoo7.com.au/mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Jul 18 05:30:09 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 11:30:09 +0200 Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> Message-ID: nicolas.pourcelot at gmail.com wrote: > Hi, > > I want to test if an object IS in a list (identity and not equality > test). > I can if course write something like this : > > test = False > myobject = MyCustomClass(*args, **kw) > for element in mylist: > if element is myobject: > test = True > break > > and I can even write a isinlist(elt, mylist) function. > > But most of the time, when I need some basic feature in python, I > discover later it is in fact already implemented. ;-) > > So, is there already something like that in python ? > I tried to write : > 'element is in mylist' > but this appeared to be incorrect syntax... There is no "is in" operator in Python, but you can write your test more concisely as any(myobject is element for element in mylist) > PS: Btw, how is set element comparison implemented ? My first > impression was that 'a' and 'b' members are considered equal if and > only if hash(a) == hash(b), but I was obviously wrong : >>>> class A(object): > ... def __eq__(self,y): > ... return False > ... def __hash__(self): > ... return 5 > ... >>>> a=A();b=A() >>>> a==b > False >>>> hash(b)==hash(a) > True >>>> b in set([a]) > False >>>> S=set([a]) >>>> S.difference([b]) > set([<__main__.A object at 0xb7a91dac>]) > > So there is some equality check also, maybe only if '__eq__' is > implemented ? In general equality is determined by __eq__() or __cmp__(). By default object equality checks for identity. Some containers (like the built-in set and dict) assume that a==b implies hash(a) == hash(b). Peter From clay at lakeserv.net Tue Jul 22 19:27:27 2008 From: clay at lakeserv.net (Clay Hobbs) Date: Tue, 22 Jul 2008 19:27:27 -0400 Subject: How do I compare files? Message-ID: <1216769247.18962.7.camel@generator> I am making a program that (with urllib) that downloads two jpeg files and, if they are different, displays the new one. I need to find a way to compare two files in Python. How is this done? -- Ratfink From casey.mcginty at gmail.com Mon Jul 7 19:08:20 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Mon, 7 Jul 2008 13:08:20 -1000 Subject: Interest not met. In-Reply-To: <849453.75351.qm@web23404.mail.ird.yahoo.com> References: <849453.75351.qm@web23404.mail.ird.yahoo.com> Message-ID: On Thu, Jul 3, 2008 at 5:01 AM, david odey wrote: > I write to inform you that the reason I subscribed to this web page > is not been met. > > I want to be sent sample codes in programming languages especially > python and an email tutorial on C#. I will be happy if these demands > are met. > > Thanks in anticipation. > Haha. This is a joke, right? Funny. I will begin preparations for transportation and a fully fueled airplane for your escape. Please send me your location. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Wed Jul 23 08:55:49 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 14:55:49 +0200 Subject: maximum value in a column of file In-Reply-To: <488705D6.4090300@isac.cnr.it> References: <4886DCF3.10107@isac.cnr.it> <4886F4CD.8010704@isac.cnr.it> <488705D6.4090300@isac.cnr.it> Message-ID: maurizio wrote: > thank you for your answer > actually i've to do some statistics (maximum,minimum,mean,standard > deviation,....) of a file of data in which each column is a particular > type of data. (the file is a tab separated value). > I was trying to do this by using python (usually i work with fortran or > bash, but i'm learning python), that the reason why i tried to use numpy. As I implied, you can do all this in standard Python "by hand", but numpy/scipy can definitely make things easier. There's a dependency cost here (your program needs one or more extra libraries to work), but if that's no problem in your environment, I'd recommend that approach. The scipy add-on contains a bunch of things for file i/o; see http://www.scipy.org/doc/api_docs/SciPy.io.html for an overview. Since you're reading text files, the "array_import" module seems to be what you need: http://www.scipy.org/doc/api_docs/SciPy.io.array_import.html There are active user communities for both numpy and scipy that can help you sort out any remaining issues; for details, see: http://www.scipy.org/Mailing_Lists Hope this helps! From bignose+hates-spam at benfinney.id.au Mon Jul 7 18:44:59 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 08 Jul 2008 08:44:59 +1000 Subject: Python Agile Software Development Tools Screencasts References: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> Message-ID: <87lk0dwbys.fsf@benfinney.id.au> percious writes: > Hi All, > > I started a new series about python on showmedo. Please feel free to > take a look. I'd love to, but showmedo refuses to show presentations to me without installing non-free software. -- \ ?It takes a big man to cry, but it takes a bigger man to laugh | `\ at that man.? ?Jack Handey | _o__) | Ben Finney From trentm at activestate.com Fri Jul 11 13:41:00 2008 From: trentm at activestate.com (Trent Mick) Date: Fri, 11 Jul 2008 10:41:00 -0700 Subject: ActiveState Code: the new Python Cookbook site In-Reply-To: References: <4873F326.5010905@activestate.com> <4874698E.7000805@gmail.com> <4877053f$0$16181$5402220f@news.sunrise.ch> Message-ID: <48779B2C.1030308@activestate.com> Peter Otten wrote: > Thin Myrna wrote: > >> The old cookbook offered choices by category. Did you drop that feature? > > Looks like categories have become tags: > > http://code.activestate.com/recipes/tags/ Yes, that is correct. I should document the tag names to category mapping that I've used (mostly a straightforward "remove spaces and capitalization" thing). My hope is that allowing free form tagging and (importantly) multiple tags will allow for more interesting and useful grouping. However, there is value in there being good suggestions of common tags when adding tags. I need to add that to the recipe add form: http://code.activestate.com/recipes/add/ Trent -- Trent Mick trentm at activestate.com From tuckers4all911 at yahoo.co.uk Thu Jul 3 11:01:46 2008 From: tuckers4all911 at yahoo.co.uk (david odey) Date: Thu, 3 Jul 2008 15:01:46 +0000 (GMT) Subject: Interest not met. Message-ID: <849453.75351.qm@web23404.mail.ird.yahoo.com> I write to inform you that the reason I subscribed to this web page? is not been met. I want to be sent sample codes in programming languages especially?? python and an email tutorial on C#. I will be happy if these demands? are met. ?Thanks in anticipation. ALWAYS THERE FOR YOU __________________________________________________________ Not happy with your email address?. Get the one you really want - millions of new email addresses available now at Yahoo! http://uk.docs.yahoo.com/ymail/new.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From sk8in_zombi at yahoo.com.au Tue Jul 15 15:17:45 2008 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Tue, 15 Jul 2008 12:17:45 -0700 (PDT) Subject: Handling events using pycairo Message-ID: <936782.84072.qm@web54503.mail.re2.yahoo.com> Hi, I'm trying to create a rectangle when the user presses or releases the mouse over a cairo object.I'm using the eventBox to capture the mouse events. Now the problem is the shapes is beng drawn when I call it from the expose_event event handler and nothing happens when I call the same from the mouse release event handler. Here is my code : #!/usr/bin/env python import sys import cairo import gtk start = None #Starting co-ords stop = None #Ending co-ords box = None? #Tuple of co-ords for drawing rect ctx = None #Cairo Widget def button_press(widget, event, surface): ??? global start ??? start = (int(event.x),int(event.y)) def motion_notify(widget, event, surface): ??? pass def button_release(widget, event, surface): ??? global stop,ctx ??? ctx = None ??? ctx = widget.window.cairo_create() ??? ctx.set_source_surface(surface, 0,0) ??? ctx.paint() ??? print ctx ??? stop =? (int(event.x),int(event.y)) ??? box = (start[0],start[1]) ??? draw_dotrect(ctx,box) ??? print "Released" + str(box) def draw_dotrect(ctx,box): ??? ctx.set_source_rgba(0, 0, 0,0.5) ??? ctx.save() ??? ctx.new_path() ??? ctx.translate(3*20, 0) ??? square(ctx,box) ??? ctx.fill() ??? ctx.restore() ??? ctx.set_line_width(20 / 16) ??? ctx.set_tolerance(0.1) ??? ctx.set_line_join(cairo.LINE_JOIN_MITER) ??? ctx.set_dash([20/2.0, 20/2.0], 8) ??? ctx.save() ??? ctx.new_path() ??? ctx.set_source_rgb(0,0 ,0 ) ??? ctx.translate(3*20, 0) ??? square(ctx,box) ??? ctx.stroke_preserve() ??? ctx.restore() ??? def expose_event(widget, event, surface): ??? global ctx ??? ctx = widget.window.cairo_create() ??? ctx.set_source_surface(surface, 0,0) ??? ctx.paint() ??? ??? #draw_dotrect(ctx,(20,20)) # If called from here,it works ??? ??? def square(ctx,box): ??? ctx.move_to(0, 0) ??? ctx.rel_line_to(2*50, 0) ??? ctx.rel_line_to(0, 2*50) ??? ctx.rel_line_to(-2*50, 0) ??? ctx.close_path() ??? ??? if len(sys.argv) != 2: ??? ??? raise SystemExit('usage: png_view.py png_file') filename = sys.argv[1] surface = cairo.ImageSurface.create_from_png(filename) Width? = surface.get_width() Height = surface.get_height() win = gtk.Window() win.connect('destroy', gtk.main_quit) event_box = gtk.EventBox() win.add(event_box) drawingarea = gtk.DrawingArea() event_box.add(drawingarea) drawingarea.connect('expose_event', expose_event, surface) event_box.connect('button_press_event',button_press,surface) event_box.connect('button_release_event',button_release,surface) event_box.connect('motion_notify_event',motion_notify,surface) drawingarea.set_size_request(Width,Height) win.show_all() gtk.main() It doesn't throw me any error.I hardcoded the box to simplify things .??? I also create a new ctx in the release event handler else it throws an error:CAIRO_STATUS_SURFACE_FINISHED Any ideas why ? " life isn't heavy enough,it flies away and floats far above action" Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregvika at gmail.com Mon Jul 14 11:11:55 2008 From: gregvika at gmail.com (greg) Date: Mon, 14 Jul 2008 08:11:55 -0700 (PDT) Subject: screencapture with PIL question Message-ID: <8e9ca866-4f14-4dd6-a784-a76630d8d812@x35g2000hsb.googlegroups.com> I am able to use the PIL module to capture a screen or specific window. My problem is when capturing a window (on windows XP) I can only capture the "visible" portion of the window. Is there any way to capture the entire window? specifically the scrolled portion of a window that is not visible on the screen. Thanks for any help. From keshet1 at umbc.edu Wed Jul 9 07:22:08 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Wed, 09 Jul 2008 07:22:08 -0400 Subject: a simple 'for' question In-Reply-To: <1215599630.2873.965.camel@localhost.localdomain> References: <4874017D.2000401@umbc.edu> <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> <487437E6.8010609@umbc.edu> <1215599630.2873.965.camel@localhost.localdomain> Message-ID: <48749F60.7030106@umbc.edu> it didn't help. it reads the pathway "as is" (see errors for both tries). It looks like it had the write pathway the first time, but could not find it because it searched in the path/way instead of in the path\way. thanks for trying. folders= ['1','2','3'] for x in folders: print x # print the current folder filename='Folder/%s/myfile.txt' %[x] f=open(filename,'r') gives: IOError: [Errno 2] No such file or directory: "Folder/['1']/myfile.txt" Tim Cook wrote: > On Wed, 2008-07-09 at 00:00 -0400, Ben Keshet wrote: > >> oops, my mistake, actually it didn't work... >> when I tried: >> for x in folders: >> print x # print the current folder >> filename='Folder/%s/myfile.txt' %x >> f=open(filename,'r') >> >> it says: IOError: [Errno 2] No such file or directory: >> 'Folder/1/myfile.txt' >> >> > > I believe it's because x is the position marker what you want instead is > the contents of folders at x; therefore folders[x] > > HTH, > Tim > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Tue Jul 15 13:38:43 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Jul 2008 18:38:43 +0100 Subject: File Locking Forced? Newbie question. In-Reply-To: <216e2396-65f6-4281-b3c5-754ceb07f3eb@m36g2000hse.googlegroups.com> References: <216e2396-65f6-4281-b3c5-754ceb07f3eb@m36g2000hse.googlegroups.com> Message-ID: <487CE0A3.7060601@timgolden.me.uk> Sparky wrote: > Hello! I am writing some software that will have many users accessing > the same file resource at once for reading purposes only. I am > programming on (Ubuntu) Linux and my question is in Windows, can I > have it so that the same file can be open in read mode by more than > one person or could Window's file locking system get in the way? Assuming your question is: can processes A, B & C read from the same file at the same time, then: Yes. (You can try it out yourself fairly easily if you want. Just open a clutch of interpreter windows and do some open ("abc.txt", "r").read () stuff in each one). But I'm surprised you think that anything might get in the way of that. It would be a fairly limiting file system which prevented multiple simultaneous readers. TJG From gboutsioukis at gmail.com Tue Jul 29 20:19:21 2008 From: gboutsioukis at gmail.com (gbs) Date: Wed, 30 Jul 2008 00:19:21 +0000 (UTC) Subject: How can I check nbr of cores of computer? References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> Message-ID: On Tue, 29 Jul 2008 15:53:47 -0700, defn noob wrote: > How can I check how many cores my computer has? Is it possible to do > this in a Python-app? Well you can try the functions in the 'platform' module, although in my box(debian) nothing useful comes out. I don't think there's a simple & portable way, you probably have to find one specific to your platform . (if you are on linux, you can parse the output of 'cat /proc/cpuinfo') From sjmachin at lexicon.net Thu Jul 24 04:06:33 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 24 Jul 2008 01:06:33 -0700 (PDT) Subject: EXCEL API References: <8279561b-05b7-4935-9ded-def5663b4f93@y21g2000hsf.googlegroups.com> Message-ID: On Jul 24, 5:15?pm, Girish wrote in comp.lang.python: > Hello, > > Does any one have a sample piece of code to search for a keyword in > Excel sheet? if so plz post it.. > 8<--- xlkwsearch.py import xlrd, sys, glob def xlkwsearch(fname, query): book = xlrd.open_workbook(fname) for sheet in book.sheets(): for rowx in xrange(sheet.nrows): for colx in xrange(sheet.ncols): cell = sheet.cell(rowx, colx) if cell.ctype == xlrd.XL_CELL_TEXT and query in cell.value: yield fname, sheet.name, rowx, colx, cell.value if __name__ == '__main__': for fname in glob.glob(sys.argv[1]): for result in xlkwsearch(fname, sys.argv[2]): print result 8<--- Sample output: D:\junk>python xlkwsearch.py *search*.xls hello ('search_demo.xls', u'Sheet1', 0, 0, u'hello') ('search_demo.xls', u'Sheet1', 2, 6, u'hello world') D:\junk>python xlkwsearch.py *search*.xls world ('search_demo.xls', u'Sheet1', 1, 1, u'world') ('search_demo.xls', u'Sheet1', 2, 6, u'hello world') ('search_demo.xls', u'2nd Sheet', 0, 0, u'underworld') ('search_demo.xls', u'2nd Sheet', 0, 2, u'worldly') From timothywayne.cook at gmail.com Wed Jul 9 06:50:56 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Wed, 09 Jul 2008 07:50:56 -0300 Subject: start reading from certain line In-Reply-To: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> Message-ID: <1215600656.2873.970.camel@localhost.localdomain> On Wed, 2008-07-09 at 03:30 -0700, antar2 wrote: > I am a starter in python and would like to write a program that reads > lines starting with a line that contains a certain word. > For example the program starts reading the program when a line is > encountered that contains 'item 1' > > > The weather is nice > Item 1 > We will go to the seaside > ... > > Only the lines coming after Item 1 should be read file=open(filename) while True: line=file.readline() if not line: break if 'Item 1' in line: print line HTH, Tim -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From python at rcn.com Tue Jul 22 12:21:36 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 22 Jul 2008 09:21:36 -0700 (PDT) Subject: convert list of lists to list References: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> Message-ID: <947194bf-b885-4ca0-b75c-c0b99336d81f@25g2000hsx.googlegroups.com> On Jul 22, 8:25?am, Fredrik Lundh wrote: > if there's only one level of recursion, and the lists aren't too long, > you can simply do: > > ? ? ?sum(list_of_lists, []) > > (this has quadratic performance, so don't use it for large structures) For linear performance, you can use itertools: list(itertools.chain(*list_of_lists)) Raymond From gagsl-py2 at yahoo.com.ar Tue Jul 15 03:59:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 04:59:00 -0300 Subject: screencapture with PIL question References: <8e9ca866-4f14-4dd6-a784-a76630d8d812@x35g2000hsb.googlegroups.com> Message-ID: En Mon, 14 Jul 2008 12:11:55 -0300, greg escribi?: > I am able to use the PIL module to capture a screen or specific > window. My problem is when capturing a window (on windows XP) I can > only capture the "visible" portion of the window. Is there any way to > capture the entire window? specifically the scrolled portion of a > window that is not visible on the screen. Camtasia Studio -a commercial product- has a few ways to do that; one is to send many simulated mouse clicks to the window scroll bars, capturing the window contents in stripes. pywinauto would help on doing that from Python http://pywinauto.blogspot.com/ -- Gabriel Genellina From miki.tebeka at gmail.com Thu Jul 3 15:57:51 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 3 Jul 2008 12:57:51 -0700 (PDT) Subject: Spell suggest for locations References: Message-ID: <6d5cbf0a-e28f-4204-ab2e-4ca79ddbcb77@w8g2000prd.googlegroups.com> Hello, > I'm working on spell suggestions for a list of places(~10^6) e.g pizza > hut What data structure shall I use for max performance/efficiency? > > Typing pizza ?should yield something like > > pizza hut pizza corner<...<... > ... > ... > ... A trie? (http://en.wikipedia.org/wiki/Trie). Googling for "spell checker algorithm" yields many results. HTH, -- Miki http://pythonwise.blogspot.com From simon at simonwillison.net Wed Jul 30 12:17:45 2008 From: simon at simonwillison.net (Simon Willison) Date: Wed, 30 Jul 2008 09:17:45 -0700 (PDT) Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: <2a703a46-75bc-4228-95d1-05a4e6030b40@f63g2000hsf.googlegroups.com> Message-ID: On Jul 30, 4:59?pm, Simon Willison wrote: > I just tried it out on Python 2.4.2 on an Ubuntu machine and it worked > fine! I guess this must be an OS X Python bug. How absolutely > infuriating. Some very useful people in #python on Freenode pointed out that my bug occurs because I'm trying to display things interactively in the console. Saving to a variable instead fixes the problem. Thanks for your help, Simon From hubaghdadi at gmail.com Tue Jul 29 10:47:35 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Tue, 29 Jul 2008 07:47:35 -0700 (PDT) Subject: Continuous integration for Python projects Message-ID: Hi. Please correct my if I'm wrong but it seems to me that the major continuous integration servers (Hudson, CruiseControl, TeamCity ..) don't support Python based application. It seems they mainly support Java, .NET and Ruby. Can I use one of the previous listed servers for Python project? Thanks. From deets at nospam.web.de Mon Jul 28 13:02:35 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 19:02:35 +0200 Subject: with statement for two files References: <08d72316-15f1-45dd-b1f7-7b8ee06efef5@e39g2000hsf.googlegroups.com> <7xsktuvusj.fsf@ruckus.brouhaha.com> Message-ID: <6f6cfdFa22kkU1@mid.uni-berlin.de> Paul Rubin wrote: > braver writes: >> with open(src) as readin, open(dst,"w") as writin: # WRONG: comma >> doesn't work >> ... >> -- so that you have transactional safety for two file descriptors? > > use contextlib.nexted(). You mean contextlib.nested I guess. Didn't know about that module, cool! However, the fundamental problem stays: rolling back only works if the innermost context fails. Diez From kay.schluehr at gmx.net Mon Jul 28 13:15:50 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 28 Jul 2008 10:15:50 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> <7360bd9a-4ff6-4e75-821c-eabc88ee6258@u6g2000prc.googlegroups.com> Message-ID: On 28 Jul., 06:42, "Russ P." wrote: > On Jul 27, 8:58 pm, castironpi wrote: > > > On Jul 27, 2:39 pm, Bruno Desthuilliers > > > wrote: > > > Derek Martin a ?crit : > > > > It's bad programming, but the world is full of bad programmers, and we > > > > don't always have the choice not to use their code. Isn't one of > > > > Python's goals to minimize opportunities for bad programming? > > > > Nope. That's Java's goal. Python's goals are to maximize opportunities > > > for good programming, which is quite different. > > Oh, gosh, that is so clever. What a bunch of crap. > > > +1 QOTW > > Do you realize what an insult that is to everyone else who has posted > here in the past week? Nothing glues a community together so well as a common enemy. Or even better: two enemies i.e. Perl and Java in Pythons case. On the other hand, some enemies have to be ignored or declared to be not an enemy ( Ruby ), although oneself is clearly an enemy for them. The same antisymmetry holds for Python and Java. Java is an enemy for Python but Python is not worth for Java to be an enemy as long as it can be ignored. C++ and Java are enemies for each other. Same holds for Java and C#. From sureshku472 at gmail.com Wed Jul 2 11:17:47 2008 From: sureshku472 at gmail.com (sureshku472 at gmail.com) Date: Wed, 2 Jul 2008 08:17:47 -0700 (PDT) Subject: free sms all over the world & downloading free wallpaper ringtones Message-ID: <31aba42e-2ac1-45e0-a4fd-a7573ce6f0de@s21g2000prm.googlegroups.com> Success usually comes to those who are too busy to be looking for it Visit Mobiles & Computers?, http://www.mobilecomputers4all.blogspot.com/
Hi..Click me

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi..Click me

From peter.anderson at internode.on.net Mon Jul 21 01:14:32 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Mon, 21 Jul 2008 15:14:32 +1000 Subject: Python Written in C? Message-ID: <48841B38.4050900@internode.on.net> > Bah, new-fangled languages like Pascal... Real programmers write Fortran. Using punch-cards and paper-tape. Real programmers can edit their programs with a pointy stick and some home-made sticky-tape. -- Grant Edwards Reminds me of a funny story from my past working life. I had this fibre tipped pen, given to me as a freebie by some computer company. The pen had something like "Floppy Disk Pen" printed down the barrel. A colleague who was more into IT management than programming or hands-on support picked it up at a meeting and said something like - "That's interesting, what's it for?" Seeing an opportunity I replied "Its a new bit of technology that allows you to write directly to your floppy disks when you are away from your computer!" "What a great idea!" he replied in all seriousness! Maybe our friend could find one to code C# with! ;-) Peter -- Peter Anderson There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things ? Niccolo Machiavelli, /The Prince/, ch. 6 From thomas.troeger.ext at siemens.com Tue Jul 15 09:05:18 2008 From: thomas.troeger.ext at siemens.com (Troeger, Thomas (ext)) Date: Tue, 15 Jul 2008 15:05:18 +0200 Subject: AW: Python embedding question. In-Reply-To: <487C8E1C.7050600@preisshare.net> References: <487C8E1C.7050600@preisshare.net> Message-ID: Hi, > > I want to embed a Python application on a device with limited > > resources, esp. storage limitations. Is there a way to reduce the > > Python interpreter to a set of modules that's urgently needed? > Of course there is. What is the target platform ? Thanks for your answer. The plattform is x86, so basically it's a PC with a compact flash drive. The problem is that the compact flash is rather limited in speed and size (there is other stuff on it too). > > Or is there a method to have gzipped modules that are unzipped on the > > fly into memory when they're accessed? That would be even better. > Yes - also possible. That sounds promising, is there a link you can give? Or do I have to modify the module loading code for this, i.e. the interpreter? I think that wouldn't be too much of a problem if I understand where Python loads modules; I haven't checked the Python source yet for that one, and searching for Python and zip or similar always yields tons of links that use the Python zip or tar module :) > Regards > David Cheers, Thomas. From goldfita at signalsguru.net Mon Jul 7 11:26:28 2008 From: goldfita at signalsguru.net (Todd) Date: Mon, 7 Jul 2008 08:26:28 -0700 (PDT) Subject: python mysteriously halts References: <13a33043-21d1-40c0-a938-6e905d958064@m3g2000hsc.googlegroups.com> Message-ID: On Jul 7, 10:17?am, Tim Golden wrote: > Todd wrote: > > I ran a python script last night which connects to a matlab automation > > server via DCOM (using win32com). ?I expected to see the results when > > I came in this morning. ?But apparently, not long after I left, python > > stopped. ?I hit enter in the console, and it started again. > > Symptomatically, at least, this can be caused by someone starting to > select (with the mouse) an area of the screen: the process will pause > until is pressed, which copies the area to the clipboard. This > only happens with a console window, but it sounds like that's what > you had running. > > TJG That might be it, although I don't recall doing that. Fortunately/ unfortunately, it happened a few times, but it seems to have stopped now. From steve at REMOVE-THIS-cybersource.com.au Thu Jul 31 18:40:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Jul 2008 22:40:41 GMT Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> Message-ID: <00a23ad3$0$20313$c3e8da3@news.astraweb.com> On Thu, 31 Jul 2008 13:32:39 +0200, Thomas Troeger wrote: >> Can someone explain to me the difference between a type and a class? > > If your confusion is of a more general nature I suggest reading the > introduction of `Design Patterns' (ISBN-10: 0201633612), under > `Specifying Object Interfaces'. > > In short: A type denotes a certain interface, i.e. a set of signatures, > whereas a class tells us how an object is implemented (like a > blueprint). A class can have many types if it implements all their > interfaces, and different classes can have the same type if they share a > common interface. I fear you're introducing a rather complicated answer for a simple question. In Python, the simple answer is that built-in objects like int, float, str etc. are referred to as "types", and custom objects created using the class keyword are referred to as "classes". This is a historical distinction that will disappear in time. We can see that types and classes already have the same type in Python: >>> class Parrot(object): ... pass ... >>> type(Parrot) >>> type(str) > The following example should clarify matters: > > class A: > def bar(self): > print "A" Alas, you've chosen the worst-possible example to "clarify" matters, because old-style classic classes are *not* unified with types, and will disappear in the future: >>> class Old: # don't inherit from object ... pass ... >>> type(Old) So, to the Original Poster: In Python, new-style classes and types are the same, but it is traditional to refer to customer objects as "class" and built-in objects as "types". Old-style classes are different, but you are discouraged from using old-style classes unless you have a specific reason for needing them (e.g. backwards compatibility). -- Steven From timothywayne.cook at gmail.com Sat Jul 26 07:59:15 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Sat, 26 Jul 2008 08:59:15 -0300 Subject: Stripping parts of a path Message-ID: <1217073555.2771.41.camel@localhost.localdomain> Hi All, I just ran into an issue with the rstrip method when using it on path strings. When executing a function I have a need to strip off a portion of the current working directory and add on a path to a log file. Initially this worked great but then I added a branch in SVN which caused the path to contain 'LNCCWorkshop'. The rstrip() then began removing the characters 'shop' leaving an incorrect path to the log file. When I hard coded this path it worked okay but then did the same thing later in the file when I needed to point to a database. The code worked fine with a different path. Here are some code fragments. logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/at_build_errors.log' this worked when the path was: /home/tim/ref_impl_python/TRUNK/oship/src/oship/atbldr the code above returns: /home/tim/ref_impl_python/TRUNK/oship/log/at_build_errors.log but when I tried a branches version that has the path: /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/src/oship/atbldr it SHOULD return: /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/log/at_build_errors.log but I get: /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log logfile=os.getcwd() print logfile is correct; but when I add the .rstrip('src/oship/atbldr') it also strips the 'shop' off of LNCCWorkshop and returns /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log I had two other people looking at this as we did troubleshooting and we could not determine the cause. It is repeatable with this path name. In resolution I renamed the branch to just LNCC and it works fine. Thoughts? Tim -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. Home page: https://launchpad.net/oship/ Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From mrkafk at gmail.com Wed Jul 9 10:53:39 2008 From: mrkafk at gmail.com (mk) Date: Wed, 09 Jul 2008 16:53:39 +0200 Subject: (silly?) speed comparisons In-Reply-To: <200807091447.34094.maric@aristote.info> References: <84bdef3c0807081516g7872d1d8x2ecb448fd1fa900c@mail.gmail.com> <200807091447.34094.maric@aristote.info> Message-ID: Maric Michaud wrote: > Le Wednesday 09 July 2008 12:35:10 mk, vous avez ?crit : >> vector move_slice(vector& vec, int start, int stop, int >> dest) > > I guess the point is to make a vector of referene to string if you don't want > to copy string objects all around but just a word for an address each time. > > The signature should be : > vector move_slice(vector& vec, int start, int stop, int > dest) > > or > > vector move_slice(vector& vec, int start, int stop, int > dest) That matters too, but I just found, the main culprit was _returning the list instead of returning the reference to list_. The difference is staggering - some 25 sec vs 0.2 sec: $ time slice6 real 0m0.191s user 0m0.015s sys 0m0.030s #include #include #include using namespace std; list& move_slice(list& slist, int start, int stop, int dest) { int idx; if( dest > stop) idx = dest - (stop - start); else idx = dest; int i; list::iterator startiter; list::iterator enditer; list::iterator destiter; startiter = slist.begin(); destiter = slist.begin(); for (i = 0; i < start; i++) startiter++; enditer = startiter; for (i = start; i < stop; i++) enditer++; for (i = 0; i < dest; i++) destiter++; slist.splice(destiter, slist, startiter, enditer); /* cout << "frag " << endl; for (startiter = frag.begin(); startiter != frag.end(); startiter ++) cout << *startiter << " "; cout << endl;*/ /* cout << " after: "; for (startiter = slist.begin(); startiter != slist.end(); startiter++) cout << *startiter << " "; cout << endl;*/ return slist; } int main(int argc, char* argv) { list slice; string u = "abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij"; int pos; for (pos = 0; pos < u.length(); pos++) slice.push_back(new string(u)); int i; //for (i = 0; i<1000000; i++) /*list::iterator startiter; cout << "before: "; for (startiter = slice.begin(); startiter != slice.end(); startiter++) cout << *startiter << " "; cout << endl;*/ for (int i = 0; i<1000000; i++) move_slice(slice, 4, 6, 7); } From dullrich at sprynet.com Fri Jul 18 17:29:22 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 18 Jul 2008 16:29:22 -0500 Subject: wxPython code giving strange errors. References: <01694ab5-7b5e-4e57-8b86-bf89b0beec82@m44g2000hsc.googlegroups.com> Message-ID: In article , Mike Driscoll wrote: > On Jul 13, 10:18?am, teh_sAbEr wrote: > > I'm busy trying to learn wxPython, and i'm trying to run the following > > piece of code (its from the wxPyWiki tutorial): > > > > import wx > > [...] > > > > app = wx.PySimpleApp() > > frame = MainWindow(None, -1, "Sample editor") > > app.MainLoop() > >[...] > > This code works "as is" on Windows XP. However, I have gotten this > error when trying to run it from IDLE and I've heard that that can > happen in other Tkinter-based IDEs. So I've heard. Just for fun I tried running it in a wxPython-based shell - it worked fine. > Try running it from the command > line and I'll bet you won't get that error. > > Also, there's a great wxPython user's group you can join from the > official website: > > www.wxpython.org > > Mike -- David C. Ullrich From georgeoliverGO at gmail.com Sat Jul 12 03:08:09 2008 From: georgeoliverGO at gmail.com (George Oliver) Date: Sat, 12 Jul 2008 00:08:09 -0700 (PDT) Subject: sending input to an embedded application Message-ID: hi, I'm a novice programmer trying to better define a hobby project I'm thinking of. What I would like to do is take a program and embed it or put it within a Python-run GUI, using the GUI just to capture and send input to the application, and display the ouput. Specifically I want to use a Python module such as wxPython, pygame or pyglet to build the UI, capture key presses, and then send a string to the program, an interactive fiction interpreter; the reason for this is that the interpreter on its own doesn't have the capability to recognize certain key presses on the keyboard. I thought that writing a middle layer rather than a brand new interpreter would be easier for someone of my skill level. The interpreter would send its output to the Python GUI. The GUI then would be as light/translucent as possible, just accepting input, sending it to the interpreter, and displaying the output as if you were just running the interpreter by itself. As I don't really know the issues involved, I'm hoping someone can point me in the right direction. Do people 'frame' programs with something like wxPython or pygame and use the frame to capture and pass along input, and receive and display the output? thanks, George From Russ.Paielli at gmail.com Wed Jul 30 02:36:19 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 23:36:19 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> Message-ID: <6d906dd5-bf5a-44d5-a5a8-3875027f6b91@v26g2000prm.googlegroups.com> On Jul 29, 11:16 pm, Erik Max Francis wrote: > Russ P. wrote: > > On Jul 29, 10:33 pm, Carl Banks wrote: > >> On Jul 30, 1:15 am, "Russ P." wrote: > > >>> Having said that, it would sure be nice to be able to write > >>> if myList is not empty: > >>> instead of > >>> if len(myList) != 0: > >> I can agree with this. > > > But I guess that could only work if there were only one empty list > > that represents all empty lists (as there is only one actual "None"). > > I don't know if that makes sense or not. > > It really doesn't, since it presumably wouldn't apply to just list > types. There are plenty of other sequence types: such as tuples, > strings, or even arbitrary custom types. Emptiness is a test for the > value of an object, not a test for whether it is identical to another > object, so this is a very misleading of the `is` operator, bordering on > abuse. > > This syntax would make far less sense than the existing Boolean test. > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis > The doors of Heaven and Hell are adjacent and identical. > -- Nikos Kazantzakis Now that's more reasonable. Note that I said, "it would be nice to be able to write," not "this is how it should be done." Come to think of it, shouldn't the list type have an "isempty" method? Or does it? From johnroth1 at gmail.com Tue Jul 1 21:39:47 2008 From: johnroth1 at gmail.com (John Roth) Date: Tue, 1 Jul 2008 18:39:47 -0700 (PDT) Subject: How to make a function associated with a class? References: <69e26f9b-2f00-4318-9bc5-6aa94e141bca@59g2000hsb.googlegroups.com> Message-ID: On Jul 1, 2:43 pm, Kurda Yon wrote: > Hi, > > I have a class called "vector". And I would like to define a function > "dot" which would return a dot product of any two "vectors". I want > to call this function as follow: dot(x,y). > > Well, I can define a functions "dot" outside the class and it works > exactly as I want. However, the problem is that this function is not > associated with the class (like methods a method of the class). > > For example, if I call "x.calc()" or "y.calc()", python will execute > different methods if "x" and "y" belongs to different classes. I want > to have the same with my "dot" function. I.e. I want it calculates the > dot product ONLY IF the both arguments of that function belong to the > "vector" class. > > Is it possible? > > Thank you in advance. If I understand what you want, you could do it the same way most of the other functions are implemented. There's a function, and then each class which has the behavior has a private (actually a system) method that implements it. The general pattern is to get the class for the first operand, check to see if it has the implementation method, and call it if present. If it doesn't, get the class for the other operand, check and if it has the method call it with the operands reversed. Then if it isn't in either, you can look the actual implementation method up in a table. When all else fails, raise a type error. HTH John Roth From fredrik at pythonware.com Thu Jul 24 05:59:29 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 11:59:29 +0200 Subject: Confounded by Python objects In-Reply-To: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> Message-ID: boblatest at googlemail.com wrote: > take a look at the code snippet below. What I want to do is initialize > two separate Channel objects and put some data in them. However, > although two different objects are in fact created (as can be seen > from the different names they spit out with the "diag()" method), the > data in the "sample" member is the same although I stick different > values in. that's because you only have one sample object -- the one owned by the class object. since you're modifying that object in place (via the append method), your changes will be shared by all instances. python never copies attributes when it creates an instance; if you want a fresh object, you have to create it yourself. > class Channel: tip: if you're not 100% sure why you would want to put an attribute on the class level, don't do it. instead, just create all attributes inside the __init__ method: > def __init__(self, name): > self.name = name self.sample = [] # create fresh container for instance > def append(self, time, value): > self.sample.append((time, value)) > self.diag() > > def diag(self): > print (self.name, self.sample) hope this helps! From Pidgeot18 at verizon.invalid Tue Jul 22 22:29:16 2008 From: Pidgeot18 at verizon.invalid (Joshua Cranmer) Date: Wed, 23 Jul 2008 02:29:16 GMT Subject: OT: OT posts [was Re: proliferation of computer languages] In-Reply-To: <637ca9de-75d6-48e4-b6fd-0bd36020c209@c65g2000hsa.googlegroups.com> References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> <637ca9de-75d6-48e4-b6fd-0bd36020c209@c65g2000hsa.googlegroups.com> Message-ID: <0Iwhk.355$oU.209@trnddc07> xahlee at gmail.com wrote: > ? many says i'm posting off topic posts. In recent years they start to > say i'm posting tangentially relevant posts. That's not correct. In > fact, there are huge number of blatantly off-topics posts by regulars > that spawn off from threads, happens regularly. The topics vary > anywhere from discussing politics, law, licenses, free speech, math > education, yapping on happenings of celebrity programers, and > including rampant flamewars and accusations among themselves. There is a difference. Many of your claimant off-topic posts are buried in the end of threads, not at the explicit start of a thread. In those cases, I personally feel that not moving to another forum is trumped by the sake of continuity. Even then, it should be indicated as such by OT: in the subject, but it gets easy to forget it. Starting a thread that is OT does not have such continuity considerations, though. And realize that something is not on-topic merely because it's relevant to Java programmers. You can see people's responses to one of Roedy's threads as an example. > ? Most newsgroup tech geekers consider cross-posting wrong. I consider > the taboo of this convention being a major contribution to the > redundant creation of new languages, and foster the hostile faction > nature of programing language communities we see. X-Posting to groups as diverse as c.l.perl.misc, c.l.python, c.l.lisp, c.l.functional, and c.l.java.programmer (the last one especially, as it is not a functional language nor will it ever be) is generally a sign that you are not X-Posting in a germane fashion. Your original topic belongs in comp.programming or maybe (I can see a case for it) in c.l.functional, but not the other four groups. > I wrote detailed argument about my edit in > my Wikipedia's personal talk page. The Wikipedia fuckheads not only > ban'd me, "When in Rome, do as the Romans do." Fragrantly violating the established rules of an organization, especially after being reminded of these rules, is sufficient cause for disciplinary action. And you're entire post gets more and more OT every paragraph. I can in no good faith allow this to continue. Setting F-U header to take appropriate actions. -- Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth From simon at simonwillison.net Wed Jul 30 11:16:26 2008 From: simon at simonwillison.net (Simon Willison) Date: Wed, 30 Jul 2008 08:16:26 -0700 (PDT) Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: Message-ID: <16218185-7d69-411c-a219-31f2e4e8df9e@p25g2000hsf.googlegroups.com> Follow up question: what's the best way of incrementally consuming XML in Python that's character encoding aware? I have a very large file to consume but I'd rather not have to fall back to the raw SAX API. From p at ulmcnett.com Wed Jul 2 23:55:26 2008 From: p at ulmcnett.com (Paul McNett) Date: Wed, 02 Jul 2008 20:55:26 -0700 Subject: wxPython: How can I get window's HANDLE in wxPython. In-Reply-To: References: Message-ID: <486C4DAE.9050701@ulmcnett.com> Leo Lee wrote: > I need a window's handle to be passed to external c++. > Thanks in advance import wx help(wx.Window.GetHandle) """ GetHandle(*args, **kwargs) unbound wx._core.Window method GetHandle(self) -> long Returns the platform-specific handle (as a long integer) of the physical window. On wxMSW this is the win32 window handle, on wxGTK it is the XWindow ID, and on wxMac it is the ControlRef. """ Paul From salimfadhley at gmail.com Wed Jul 9 09:39:29 2008 From: salimfadhley at gmail.com (Salim Fadhley) Date: Wed, 9 Jul 2008 06:39:29 -0700 (PDT) Subject: Python / Windows process control Message-ID: <7b1097c5-7a8a-4bb8-b293-03d15aee98ed@m36g2000hse.googlegroups.com> Does anybody know of a python module which can do process management on Windows? The sort of thing that we might usually do with taskmgr.exe or process explorer? For example: * Kill a process by ID * Find out which process ID is locking an object in the filesystem * Find out all the IDs of a particular .exe file * Find all the details of a currently running process (e.g. given an ID tell me which files it uses, niceness, runtime) Thanks! Sal From emen999 at gmail.com Fri Jul 25 07:06:45 2008 From: emen999 at gmail.com (code_berzerker) Date: Fri, 25 Jul 2008 04:06:45 -0700 (PDT) Subject: lxml, comparing nodes References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> <6c91a4da-6443-4570-8dd3-01c4ec169bf3@t54g2000hsg.googlegroups.com> <4888ad28$0$9491$9b4e6d93@newsspool3.arcor-online.net> <4613042f-ed70-4cfa-8de9-a92b4df32923@k36g2000pri.googlegroups.com> <4889B2B1.5030204@behnel.de> Message-ID: > Not in your code. > > Stefan Not sure what you mean, but I tested and so far every document with the same order of elements had number of comparisons equal to number of nodes. From timr at probo.com Fri Jul 25 01:33:59 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 25 Jul 2008 05:33:59 GMT Subject: Broken examples References: Message-ID: norseman wrote: > >I'm only talking about IPC related. >I have googled, yahooed, and so forth for several months now. ALL >examples I've come across have failed including those pertinent in the >Python doc area. > >Outline: > cd somedir > ls -1 *.xls >thislist #ls hyphen one > python process.py > (yes - ls can go here if wanted. easier to edit outside) > open thislist > loop until done > start excel (or scalc) > have it open file > have it save file as a .csv (or .dbf) > close excell (or scalc) > >Would seem to be a trivial exercise. Excel is a COM-driven application. You have to drive it through the object model. import win32com.client excel = win32com.client.Dispatch( 'Excel.Application' ) xlCSV = 6 ... for nm in list_of_file_names: csv = os.path.splitext( nm )[0] + '.csv' wb = excel.Workbooks.Open( nm ) wb.SaveAs( csv, xlCSV ) wb.Close() If you want to watch the progress, add "excel.Visible=1" after the dispatch. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From kasterma at bart-kastermanss-macbook.local Sun Jul 13 06:32:12 2008 From: kasterma at bart-kastermanss-macbook.local (Bart Kastermans) Date: Sun, 13 Jul 2008 05:32:12 -0500 Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> <85c3da91-9f2f-4d19-ba98-dfdc99b1e1e3@79g2000hsk.googlegroups.com> Message-ID: Roy Smith writes: > ssecorp wrote: > >> i dont get what you mean, if i dont do anything python will raise an >> indexerror so it is an indexerror. > > You wrote: > >> > > ? ? def pop(self): >> > > ? ? ? ? try: >> > > ? ? ? ? ? ? return self.queue.pop(0) >> > > ? ? ? ? except: >> > > ? ? ? ? ? ? raise IndexError, "pop from empty queue" > > You are assuming that the only possible exception that can be thrown by > "return self.queue.pop(0)" is IndexError. Maybe, maybe not. I gave you > one example of how something else could be thrown -- a typo in your code > leading to a NameError. Maybe even something more exotic like MemoryError? > > The defensive thing to do is catch exactly the exception you expect to > happen. In this case, that means IndexError. And you do that by except IndexError: raise TheErrorYouNowWantToRaise And except IndexError, e: if you want access to the exception as well. From chiendarret at gmail.com Sat Jul 26 17:40:00 2008 From: chiendarret at gmail.com (Francesco Pietra) Date: Sat, 26 Jul 2008 23:40:00 +0200 Subject: Insert string into string Message-ID: I am posting ex novo as it became confusing to me. I take the opportunity to ask advice for a second problem. FIRST PROBLEM For file xxx.pdb, insert letter "A" into each line that starts with "ATOM". "A" should be inserted at position 22, i.e., one space after "LEU", leaving all other characters at the same position as in the original example: ATOM 1 N LEU 1 146.615 40.494 103.776 1.00 73.04 1SG 2 In all lines starting with "ATOM", "LEU" is constant as to position only (18-20), i.e., "LEU" may be replaced by three different uppercase letters. Therefore, the most direct indication would be position 22. If specifying line starting with "ATOM" makes complication, forget about that as most lines begin with "ATOM" so that hand correction will be easy. Script f = open("xxx.pdb", "w") import sys for line in sys.stdin: line = line[:22] + "A" + line[23:] sys.stdout.write(line) destroys the xxxx.pdb file and python exits witha non zero exit status. The same occurs with script f = open("hASIC1a.B99990003.pdb", "w") f.write(' line = line[:22] + "A" + line[23:]') f.close() I must have misunderstood the suggestion I received on previous posting. ____________________________________ SECOND PROBLEM File xxx.pdb above has 426 lines stating with "ATOM", this serial number occupying positions 7-11, right justified (Thus 1, as in the line example above, means first line). A second, similar file yyy.pdb has to be concatenated to xxx.pdb. Before that it should be added of "A" as above and renumbered at position 7-11, starting from 428 (there is an intermediate line to add). How should a script look like for this string insertion into string with recursive +1? Thanks francesco From paul.hankin at gmail.com Wed Jul 9 15:34:45 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 9 Jul 2008 12:34:45 -0700 (PDT) Subject: formatting list -> comma separated References: <48750e4f$0$15106$e4fe514c@dreader27.news.xs4all.nl> Message-ID: <3fe8c8a7-b47d-4d17-b4ba-5213ba389eb1@34g2000hsf.googlegroups.com> On Jul 9, 8:23?pm, "Robert" wrote: > given d: > > d = ["soep", "reeds", "ook"] > > I want it to print like > > soep, reeds, ook > > I've come up with : > > print ("%s"+", %s"*(len(d)-1)) % tuple(d) > > but this fails for d = [] > > any (pythonic) options for this? print ', '.join(d) -- Paul Hankin From adityashukla1983 at gmail.com Fri Jul 25 18:02:43 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Fri, 25 Jul 2008 17:02:43 -0500 Subject: Histogram of floating point values. Message-ID: <73045cca0807251502i58c6e83dt872c46a9e7bb6775@mail.gmail.com> Hello folks, I have a list say data=[0.99,0.98,0.98,0.98,0.97,0.93,0.92,0.92,0.83,0.66,0.50,0.50] i am trying to plot histogram of these values i have installed numpy and matplotlib and this is what i am doing* import numpy import pylab from numpy import * from pylab import * input_hist=array(data) pylab.hist(input_hist,bins=0.1) and this is the error that i am getting *(array([], dtype=int32), array([ 0.5]),
)* does this mean that i cannot plot a histogram of floating point values ? or is there a way around Thanks in advance Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From davidreynon at gmail.com Thu Jul 24 15:09:00 2008 From: davidreynon at gmail.com (korean_dave) Date: Thu, 24 Jul 2008 12:09:00 -0700 (PDT) Subject: readln() until EOF Message-ID: a = open("Thefile.txt","r") while ?????: result = a.readln() what do i put in ???? if i want to keep reading line by line until i reach the end of the file? I don't want to break the loop if there is a blank line, because there will be. Ex. of a file: map1 result1 map2 result 2 map3 result3 comments thanks... From alexnbryan at gmail.com Sat Jul 12 15:45:30 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sat, 12 Jul 2008 12:45:30 -0700 (PDT) Subject: Help with BeautifulSoup In-Reply-To: <2.2.32.20080712100911.01141b64@pop.xs4all.nl> References: <2.2.32.20080712100911.01141b64@pop.xs4all.nl> Message-ID: <18423003.post@talk.nabble.com> Michiel Overtoom wrote: > > Alex wrote... >> >>Okay, heres the general idea of the html I have to work with: >> >>
>> noun >>
>>
>>
>>
>> verb >>
>>
>>
>> >> >>Okay, I left off some stuff. > > I wish you didn't, or at least provided an URL where I can get the page > which you are trying to parse. Now I don't have a valid testcase to > tinker > with. And maybe you can also show your code which you already came up > with. > > >> I can easily get the tables but it is the span's than I am having trouble > with. > > I can't see any SPAN tags in the example you provided. > > Greetings, > > -- > "The ability of the OSS process to collect and harness > the collective IQ of thousands of individuals across > the Internet is simply amazing." - Vinod Vallopillil > http://www.catb.org/~esr/halloween/halloween4.html > > -- > http://mail.python.org/mailman/listinfo/python-list > > Oh, well sorry, I wrote the span tags, but they didn't show up. But it was around the noun. Here is the code I have to get the definitions alone: import urllib from BeautifulSoup import BeautifulSoup class defWord: def __init__(self, word): self.word = word def get_defs(term): soup = BeautifulSoup(urllib.urlopen('http://dictionary.reference.com/search?q=%s' % term)) for tabs in soup.findAll('table', {'class': 'luna-Ent'}): yield tabs.findAll('td')[-1].contents[0].string self.mainList = list(get_defs(self.word)) Theres a bit more to it, but it doesn't matter here, and so if you look I am using dictionary.com as the website. If you look at the html, the "" tags are where the type of the word is and that is what I need, in order. Or if I can figure out how many
tags are inbetween each "" tag, that too would work. If you need anything else, feel free to ask! -- View this message in context: http://www.nabble.com/Re%3A-Help-with-BeautifulSoup-tp18418004p18423003.html Sent from the Python - python-list mailing list archive at Nabble.com. From tjreedy at udel.edu Sat Jul 12 19:57:38 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 19:57:38 -0400 Subject: Beginner Question : Iterators and zip In-Reply-To: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> References: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> Message-ID: moogyd at yahoo.co.uk wrote: > Hi group, > > I have a basic question on the zip built in function. > > I am writing a simple text file comparison script, that compares line > by line and character by character. The output is the original file, > with an X in place of any characters that are different. > > I have managed a solution for a fixed (3) number of files, but I want > a solution of any number of input files. > > The outline of my solution: > > for vec in zip(vec_list[0],vec_list[1],vec_list[2]): > res = '' > for entry in zip(vec[0],vec[1],vec[2]): > if len(set(entry)) > 1: > res = res+'X' > else: > res = res+entry[0] > outfile.write(res) > > So vec is a tuple containing a line from each file, and then entry is > a tuple containg a character from each line. > > 2 questions > 1) What is the general solution. Using zip in this way looks wrong. Is > there another function that does what I want zip(*vec_list) will zip together all entries in vec_list Do be aware that zip stops on the shortest iterable. So if vec[1] is shorter than vec[0] and matches otherwise, your output line will be truncated. Or if vec[1] is longer and vec[0] matches as far as it goes, there will be no signal either. res=rex+whatever can be written as res+=whatever > 2) I am using set to remove any repeated characters. Is there a > "better" way ? I might have written a third loop to compare vec[0] to vec[1]..., but your set solution is easier and prettier. If speed is an issue, don't rebuild the output line char by char. Just change what is needed in a mutable copy. I like this better anyway. res = list(vec[0]) # if all ascii, in 3.0 use bytearray for n, entry in enumerate(zip(vec[0],vec[1],vec[2])): if len(set(entry)) > 1: res[n] = 'X' outfile.write(''.join(res)) # in 3.0, write(res) tjr From iainking at gmail.com Thu Jul 10 11:54:02 2008 From: iainking at gmail.com (Iain King) Date: Thu, 10 Jul 2008 08:54:02 -0700 (PDT) Subject: start reading from certain line References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> <1215601039.2873.972.camel@localhost.localdomain> Message-ID: <5de66f4b-b931-4618-b461-29a43e5a119d@25g2000hsx.googlegroups.com> On Jul 10, 2:45?pm, jstrick wrote: > Here's a simple way to do it with a minimum amount of loopiness (don't > forget to use 'try-except' or 'with' in real life): > > f = open("item1.txt") > > for preline in f: > ? ? if "Item 1" in preline: > ? ? ? ? print preline, > ? ? ? ? for goodline in f: > ? ? ? ? ? ? # could put an end condition with a 'break' here > ? ? ? ? ? ? print goodline, > > f.close() No From x at y.z Tue Jul 1 10:33:16 2008 From: x at y.z (name) Date: Tue, 1 Jul 2008 14:33:16 +0000 (UTC) Subject: pyparsing problem References: Message-ID: Paul McGuire wrote in news:be7af822-70d7-44fb-96fa- 78b490192334 at r66g2000hsg.googlegroups.com: > > Looks like this is a bug in asXML(). Note that if I reverse the use > and host_name strings in the input and in your grammar, I get this XML > output: > > > host-01 > generic > host alias xyz > 10.0.0.1 > > > Fortunately, you have provided a nice short test case, which should > allow me to track down the problem. > > Thanks, > -- Paul > You are welcome! And I would like to thank you for this outstanding tool! Thanks, Bernhard From castironpi at gmail.com Thu Jul 24 17:34:38 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 24 Jul 2008 14:34:38 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <579f9d5b-8984-425d-8d4f-b2ed0be8eaba@o40g2000prn.googlegroups.com> <4888cd25$0$15527$426a74cc@news.free.fr> Message-ID: <0baa0dfc-8c33-4659-9ae7-438a31f7dfa9@j1g2000prb.googlegroups.com> On Jul 24, 11:43?am, Bruno Desthuilliers wrote: > Jordan a ?crit : > > >> I don't really mind, what you think about my response. ?Python will suffer > >> from it as little as it will suffer from your complaints: ?These things > >> will not change, whatever any of us says about them. ?So this discussion > >> unlikely to produce any new insight, especially because this as been > >> discussed over and over again in the past, without any effect on Python. ? > > > You're right, of course. Because Python is in so many ways what I'm > > looking for in a language, I transform it in my mind to my own, > > personal ideal, close to the real existing language but with what I > > consider to be the imperfections removed. > > I guess you'll find a lot of us guilty here too - but do we really agree > on what we consider to be "imperfections" ?-) > > (snip) > > > I was trying not to change explicit self, or even != (which has a much > > better case.) I was trying to ask the community to reconsider a > > premise that the language is built around. Explicit is actually kinda > > annoying a lot of the time, viz., java. This is about social and > > philosophical adjustments, not technical ones. > > "explicit-is-etc" - just like the remaining of Python's zen - is a > general philosophy statement, not an absolute rule. Another quote states > that practicality beats purity. > > So yes, Python has warts, and one can't get away dogmatically quoting > Python's zen. Even if I'm sometimes myself guilty here, it's certainly > worth taking time to better address criticism, either by aknowledging > effective warts when someone points them out or by explaining (or > pointing to explanations of) the unusual parts of Python's design. > > Now since most of the times, criticisms expressed here fall in the > second category, we're happy to learn you'll now take appropriate action > here and help us keep c.l.py a newbie-friendly place !-) Something that is pure and explicit is a conflict of priorities with something that is practical and implicit. As with any rules, there are going to be times when the priorities in the Zen conflict with one another, and the Zen is silent on which combination ranks higher. Some people will hate you for using 'sf' instead of 'self'... but some hate you for spelling errors too. A temper lost is a flamewar earned. If you post two equivalent code snippets that both work, we can help you compare them. From tdelaney at avaya.com Sun Jul 6 21:00:20 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 7 Jul 2008 09:00:20 +0800 Subject: how are strings immutable in python? In-Reply-To: <337db7c6-0fc9-465e-b780-322c3a5cf8da@y38g2000hsy.googlegroups.com> Message-ID: ssecorp wrote: > so why would you ever want mutability? > > > seems very counterintuitive and unreliable. Because immutability imposes a lot of restrictions and performance characteristics that mutable objects don't have. For example, compare building up a list and a tuple element-by-element (using the most appropriate methods for each): a = [] b = () for i in range(10): a.append(i) b += (i,) The list can simply grow its memory space and assign the new element. OTOH, we need to create two new tuples each time (the one containing the new element, and the one which is a concatenation of the old elements plus the new element). The old tuple and the temporary tuple then get thrown away. Even if you optimise away the temporary 1-tuple (which python doesn't) the need to allocate a new tuple every time and copy the old elements to it results in much worse time and memory usage. There are optimisations that can be done if the compiler/runtime system can determine that there is only one reference to the immutable object (python now does this in some cases for string concatenation), but in general you cannot rely on this and have to assume that the worst case applies. Tim Delaney From cito at online.de Fri Jul 11 10:45:20 2008 From: cito at online.de (Christoph Zwerschke) Date: Fri, 11 Jul 2008 16:45:20 +0200 Subject: strip() using strings instead of chars In-Reply-To: <487751a6$0$29402$426a74cc@news.free.fr> References: <487751a6$0$29402$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers schrieb: > DRY/SPOT violation. Should be written as : > > prefix = 'http://' > if url.startswith(prefix): > url = url[len(prefix):] That was exactly my point. This formulation is a bit better, but it still violates DRY, because you need to type "prefix" two times. It is exactly this idiom that I see so often and that I wanted to simplify. Your suggestions work, but I somehow feel such a simple task should have a simpler formulation in Python, i.e. something like url = url.lstripstr(('http://', 'https://')) instead of for prefix in ('http://', 'https://'): if url.startswith(prefix): url = url[len(prefix):] break -- Christoph From bdesth.quelquechose at free.quelquepart.fr Mon Jul 28 18:50:52 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 29 Jul 2008 00:50:52 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: <488e6943$0$20692$426a74cc@news.free.fr> Derek Martin a ?crit : > On Sun, Jul 27, 2008 at 09:39:26PM +0200, Bruno Desthuilliers wrote: >>> As for the latter part of #3, self (or some other variable) is >>> required in the parameter list of object methods, >> It's actually the parameter list of the *function* that is used as the >> implementation of a method. Not quite the same thing. > > The idea that Python behaves this way is new to me. For example, the > tutorials make no mention of it: > > http://docs.python.org/tut/node11.html#SECTION0011300000000000000000 > > The Python reference manual has very little to say about classes, > indeed. If it's discussed there, it's buried somewhere I could not > easily find it. Yeps, most of the doc didn't really follow Python's evolutions alas. But it's still documented - I've learned all this from the doc. You'll find more details starting here: http://www.python.org/doc/newstyle/ and a couple more stuff in the language specs part of the doc: http://docs.python.org/ref/descriptors.html http://docs.python.org/ref/descriptor-invocation.html >> consistency mandates that the target object of the method is part of >> the parameter list of the *function*, since that's how you make >> objects availables to a function. > > Fair enough, but I submit that this distinction is abstruse, The distinction between class interface (the method call) and class implementation (the function called by the method) ? > and > poorly documented, This is certainly true. Patches to the doc are welcome. > and also generally not something the average > application developer should want to or have to care about... I don't know what's an "average application developper", but as an application developper myself, I feel I have to care about the implementation of my programs, just like I feel I have to care about knowing enough about the languages I use to use them properly. > it's of > interest primarily to computer scientists and language enthusiasts. > The language should prefer to hide such details from the people using > it. There I beg to disagree. Transparently exposing most of it's object model is a design choice, and is for a great part responsible for Python expressive power and flexibility. And all this is really part of the language - I mean, it's a public API, not an implementation detail. FWIW, I'm certainly not what you'd call a "computer scientist" (I left school at 16 and have absolutely no formal education in CS). Anyway: "the language" (IOW: the language's designer) made a different choice, and I'm very grateful he did. >>> however when the method is *called*, it is omitted. >> Certainly not. > > Seems not so certain to me... We disagree, even after your careful > explanation. You're of course (and hopefully) entitled the right to disagree !-) > See below. > >> You need to lookup the corresponding attribute *on a given object* >> to get the method. Whether you write >> >> some_object.some_method() >> >> or >> >> some_function(some_object) >> >> you still need to explicitely mention some_object. > > But these two constructs are conceptually DIFFERENT, Why so ? > whether or not > their implementation is the same or similar. The first says that > some_method is defined within the name space of some_object. The first says that you're sending the message "some_method" to some_object. Or, to express it in Python terminology, that you're looking up the name "some_method" on some_object, and try to call the object returned by the attribute lookup mechanism, whatever that object is (function, method, class or any other callable). Now saying that it implies that "some_method is defined within the name space of some_object" depends on the definitions of 'defined', 'within' and 'namespace' (more on this below). > The > second says that some_object is a parameter of some_function... Yes. It also say that some_function knows enough about some_object to accept it as a parameter (or at least that the developper that passed some_object to some_function thought / expected it would be the case). You know, the dotted notation ("obj.attrib") is, well, just a notation. It's by no mean necessary to OO. You could have a perfectly valid object system where the base notation is "some_message(some_object)" instead of being "some_object.some_message" - and FWIW, in Common Lisp - which BTW have one of the richer object systems around -, the syntax for method call is the same as the syntax for function call, IOW "(func_or_method_name object arg1 arg2 argN)". > Namespace != parameter!!!!!!!!! Functions parameters are part of the namespace of the function body. Please don't get me wrong : I'm not saying your point is moot, just suggesting another possible way to look at the whole thing. > To many people previously familiar with OO programming in other > languages (not just Java or C++), but not intimately familiar with > Python's implementation details, It's actually not an implementation detail - it's part of the language spec. > the first also implies that > some_method is inherently part of some_object, There again, I disagree. To me, it implies that some_object understands the 'some_method' message. Which is not the same thing. Ok, here's a possible implementation: # foo.py def foo(obj): return obj.__class__.__name__ # bar.py from foo import foo class Meta(type): def __new__(meta, name, bases, attribs): cls = type.__new__(meta, name, bases, attribs) old_getattr = getattr(cls, '__getattr__', None) def _getattr(self, attrname): if attrname == 'some_method': return lambda self=self: foo(self) elif callable(old_getattr): return old_getattr(self, attrname) else: raise AttributeError("blah blah") cls.__getattr__ = _getattr return cls # baaz.py import bar class Quux(object): __metaclass__ = bar.Meta class Baaz(object): def __init__(self): self._nix = Quux() def __getattr__(self, name): return getattr(self._nix, name) # main.py import baaz some_object = baaz.Baaz() Is 'some_method' "inherently part of" some_object here ? There isn't even an object named 'some_method' anywhere in the above code... (and no, don't tell me, I know: it's a very convoluted way to do a simple thing - but that's not that far from things you could find in real-life library code for not-so-simple things). > in which case > explicitly providing a parameter to pass in the object naturally seems > kind of crazy. The method can and should have implicit knowledge of > what object it has been made a part. The method does. Not the function. Here's a possible (and incomplete) Python implementation of the method type: class Method(object): def __init__(self, func, instance, cls): self.im_func = func self.im_self = instance self.im_class = cls def __call__(self, *args, **kw): if self.im_self: args = (self.im_self, ) + args return self.im_func(*args, **kw) elif isinstance(args[0], self.im_class): return self.im_func(*args, **kw) else: raise TypeError("blah blah") > Part of the point of using > objects is that they do have special knowledge of themselves... s/do/seem to/ > they > (generally) manipulate data that's part of the object. Conceptually, > the idea that an object's methods can be defined outside of the scope > of the object, s/object/class/ > and need to be told what object they are part > of/operating on is somewhat nonsensical... That's still how other OOPLs work, you know. But they hide the whole damn thing out and close the box, while Python exposes it all. And I can tell you from experience that it's a sound idea - this gives you full control about your object's behaviour. wrt/ functions being defined outside classes then used as part of the implementation of a class, I fail to see where is the problem - but I surely see how it can help avoiding quite a lot of boilerplate when wisely used. >>> Thus when an object method is called, it must be called with one fewer >>> arguments than those which are defined. This can be confusing, >>> especially to new programmers. >> This is confusing as long as you insist on saying that what you >> "def"ined is a method - which is not the case. > > I can see now the distinction, but please pardon my prior ignorance, > since the documentation says it IS the case, as I pointed out earlier. Yeps. Part of the problem is that OO terminology doesn't have any clear, unambiguous definition - so terms like 'method' can be used with somewhar different meanings. Most of Python's doc use the term 'method' for functions defined within class statements - and FWIW, that's usually what I do to. > Furthermore, as you described, defining the function within the scope > of a class binds a name to the function and then makes it a method of > the class. Once that happens, *the function has become a method*. The function doesn't "become" a method - it's __get__ method returns a method object, that itself wraps the object and the function (cf above snippet). What's get stored in the class __dict__ is really the function: >>> class Foo(object): ... def bar(self): ... print "bar(%s)" % self ... >>> Foo.__dict__['bar'] >>> Whether you bind the name within or outside of the class statement doesn't change anything. > To be perfectly honest, the idea that an object method can be defined > outside the scope of an object I assume you meant "outside the class statement's body" ? > (i.e. where the code has no reason to > have any knowledge of the object) Just any code "using" an object need to have at least some knowledge of this object, you know. Or do you mean that one should not pass message to any other object than self ? This seems like a pretty severe restriction to me - in fact, I fail to see how one could write any code that way !-) > seems kind of gross to me... another > Python wart. Nope. A *great* strength. > One which could occasionally be useful I suppose, More than "occasionaly". Lots of frameworks use that (usually in conjonction with metaclasses) to inject attributes (usually functions) into your objects. Have a look at how most Python ORM work. > but a > wart nonetheless. Your opinion. But then you wont probably like Python. May I suggest Ruby instead - it has a much more canonical object model ?-) Err, no, wait - while dynamically adding attributes / methods to objects / classes is possible but not that common in Python (outside frameworks and ORMs at least), it's close to a national sport in Ruby. Nope, you won't like Ruby neither... > This seems inherently not object-oriented at all, Because things happens outside a class statement ? Remember, it's *object* oriented, not class oriented. Classes are not part of the base definitions of OO, and just aren't necessary to OO (have a look at Self, Io, or Javascript). As far as I'm concerned, "object oriented" is defined by 1/ an object has an identity, a state and a behaviour 2/ objects communicate by sending messages to each others And that's all for the OO theory - everything else is (more or less) language-specific. As you can see, there's no mention of "class" here, and not even of "method". All you have is identity, state, behaviour and messages - IOW, high level concepts that can be (are are indeed) implemented in many different ways. > for reasons I've already stated. It also strikes me as a feature > designed to encourage bad programming practices. For which definition of "bad" ? Your views on what OO is are IMHO very restricted - I'd say, restricted to what the C++/Java/UML guys defined as "being OO". Anyway: you'd be surprised by the self (no pun) discipline of most Python programmers. Python let you do all kind of crazy things, but almost no one seems to get over the board. FWIW, if you find the idea of a "method" defined outside the class statement shocking, what about rebinding the class of an object at runtime ? You may not know it, but the class of an object is just another attribute, and nothing prevents you from rebinding it to any other object whenever you want !-) > Even discounting that, if Python had a keyword which referenced the > object of which a given peice of code was a part, e.g. self, then a > function written to be an object method could use this keyword *even > if it is defined outside of the scope of a class*. The self keyword, > once the function was bound to an object, would automatically refer to > the correct object. If the function were called outside of the > context of an object, then referencing self would result in an > exception. This could probably be implemented, but it would introduce additional complexity. As I already said somewhere in this thread, as far as I'm concerned, as long as it doesn't break any existing code and doesn't impose restrictions on what is actually possible, I wouldn't care that much - but I think it would be mostly a waste of time (IMHO etc). > You'll probably argue that this takes away your ability to define a > function and subsequently use it both as a stand-alone function and > also as a method. I could. FWIW, I've almost never had a need for such a construction yet, and I don't remember having seen such a thing anywhere. But anyway, to avoid breaking code, the modification would still have to take into account functions using an explicit self (or cls) in the function's signature. I'm afraid this would end up making a mess of something that was originally simple. > I'm OK with that -- while it might occasionally > be useful, I think if you feel the need to do this, it probably means > your program design is wrong/bad. More than likely what you really > needed was to define a class that had the function as a method, and > another class (or several) that inherits from the first. Not designing things the CanonicalUMLJavaMainstreamWay(tm) doesn't mean the design is wrong. Also, there are some problems that just can't be solved that way - or are overly (and uselessly) tedious to solve that way. Talking about design, you may not have noticed yet, but quite a lot of the OO design patterns are mostly workaround the lack of flexibility in Java and C++ (hint: how would you implement the decorator pattern in Python ?). And while we're at it, the GoF (IMHO one of the best books on OO design) lousily insists on composition/delegation being often a way better design than inheritance (which FWIW is what Python does with method calls being delegated to functions). > >> The point is that you don't get access to the object "within itself". >> You get access to an object *within a function*. > > Thus methods are not really methods at all, Please show me where you get access to the object "within itself" in any other OO language. Methods (for the usual acceptation of the term) are *not* "within" the instances. And they access instances thru a reference to it, reference that get injected into the code one way or another. Most languages make this implicit, Python makes it explicit. So what ? > which would seem to > suggest that Python's OO model is inherently broken (albeit by design, > and perhaps occasionally to good effect). Here again, you are being overly dogmatic IMHO. Being explicit, or just being different from mainstream, is not the same as being "broken". >> The fact that a function is defined within a class statement doesn't >> imply any "magic", > > It does indeed -- it does more than imply. It states outright that > the function is defined within the namespace of that object, s/object/class/ > and as > such that it is inherently part of that object. s/object/class/ > So why should it need > to be explicitly told about the object of which it is already a part? Because it's the simplest thing to do ?-) More seriously, methods are usually (in Python - always in most OOPLs) part of a class, not of it's instances - IOW, the same code is shared by all instances of a same class. And the language implementation needs to make the instance accessible to the method code one way or another. From this POV, Python doesn't behave differently - except that it choosed to expose the fact and make it part of the API. > It further does indeed imply, to hordes of programmers experienced > with OO programming in other languages, that as a member, property, > attribute, or what ever you care to call it, of the object, it should > have special knowledge about the object of which it is a part. class Foo(object): some_dict = dict() def __init__(self, some_int, some_list, some_string): self.int = some_int self.list = some_list self.string = some_string foo = Foo(42, range(3), "yadda") Where do you see that 42, range(3) and "yadda" have any knowledge of foo? Translate this to any other OOPLs and tell me if the answer is different. >> IOW : there's one arguably good reason to drop the target object from >> functions used as methods implementation, which is to make Python looks >> more like Java > > No, that's not the reason. I don't especially like Java, nor do I use > it. Sorry, I usually use 'Java' as a generic branding for the whole static struct-based class-oriented mindset - UML / C++ / Java / C# etc - by opposition to dynamic OOPLs. Anyway, in this particular case, it was not even what I meant, so please accept my apologies and s/Java/canonical/ in the above remark. > The reason is to make the object model behave more intuitively. I understand that having to specify the target object can seem disturbing, at least at first. Now once you know why, I personnaly find it more "intuitive" to not have different constructs for functions, methods, and functions-to-be-used-as-methods. I write functions, period. IOW: >> , and there's at least two good reason to keep it the way it is, >> which are simplicity (no special case) and consistency (no special >> case). > > Clearly a lot of people find that it is less simple TO USE. I would say it requires a bit more typing. Does that make it less simple to use ? I'm not sure. Am I biased here ? After many years of Python programming, I don't even notice typing 'self' in the argument list no more, so very probably: yes. > The point > of computers is to make hard things easier... if there is a task that > is annoying, or tedious, or repetitive, it should be done by code, not > humans. Which BTW is why I really enjoy having the possibility to modify a class at runtime - believe me, it can save quite a lot of boilerplate... > This is something that Python should do automatically for its > users. This point is debatable, indeed. Still, the only serious reason I see here is to make Python look more like most mainstream OOPLs, and while it may be a good idea - I'm not making any judgement on this - I can happily live with the current state of things as far as I'm concerned. Anyway, the decision doesn't belong to me. From aonaran at yahoo.com Mon Jul 7 19:38:44 2008 From: aonaran at yahoo.com (DSM) Date: Tue, 08 Jul 2008 00:38:44 +0100 Subject: complex representation Message-ID: From the nothing-is-so-trivial-it's-not-worth-a-usenet-post file: Shouldn't the default representation of complex numbers be like that of floats? That is, have a decimal point? >>> 1 1 >>> 1.0 1.0 >>> 1j 1j >>> 1.0j 1j >>> 1.0+1.0j (1+1j) In the relevant bit of floatobject.c, there's a comment explaining that 1.0 isn't accidental: /* Subroutine for float_repr and float_print. We want float numbers to be recognizable as such, i.e., they should contain a decimal point or an exponent. However, %g may print the number as an integer; in such cases, we append ".0" to the string. */ ISTM the same reasoning applies equally to complex numbers. My interest arose because of what I think is a bug in pypy's complex printing: Python 2.4.1 (pypy 1.0.0 build 56124) on linux2 Type "help", "copyright", "credits" or "license" for more information. ``RPython: we use it so you don't have to'' >>>> (1.1+1.1j)**200 (240733537691613523198532543387690598400L+236495565429619338248192Lj) This strangeness comes about because a hack used to recover cpython's behaviour fails at large values. (x.real == floor(x.real), so it decides the value's an integer, and returns the repr of int(x.real).) It's trivial to fix but I think cpython's behaviour is slightly odd here, and the real and imaginary parts of the complex repr should be identical to those of the underlying floats. Or is there some reason I'm missing that things are the way they are? From gcmartijn at gmail.com Sun Jul 6 06:07:59 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Sun, 6 Jul 2008 03:07:59 -0700 (PDT) Subject: pythoncom InternetExplorer.Application don't work in vista || firefox pythoncom ? References: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> <486fe5cc$0$926$ba4acef3@news.orange.fr> Message-ID: <29c70427-07f2-43ae-b742-86af4431edd8@34g2000hsh.googlegroups.com> On 5 jul, 14:14, "M?ta-MCI \(MVP\)" wrote: > Hi! > > Your code run OK for me (Vista Ultimate). > This other version run also OK : > > def webbrowser(url=None): > ? ? import win32com.client, time > > ? ? ie=win32com.client.Dispatch('InternetExplorer.Application') ? ? > ? ? while ie.Busy==True: > ? ? ? ? time.sleep(0.125) > ? ? ie.Top = 0 > ? ? ie.Left = 0 > ? ? ie.Height = 400 > ? ? ie.Width = 400 > ? ? ie.AddressBar = False > ? ? ie.MenuBar ?= False > ? ? ie.Resizable = False > ? ? ie.StatusBar = False > ? ? ie.ToolBar = False > ? ? ie.Visible = 1 > ? ? return ie > > w = webbrowser() > w.Navigate('http://www.google.nl') > > @-salutations > -- > Michel Claveau I use your script now but I'm still getting 2 windows I uploaded a screenshot how it looks. 1 at the background my window (but that is loading nothing) 1 at on top with the site http://www.google.nl (because that is in the script) http://img376.imageshack.us/img376/5506/capturess8.jpg From dullrich at sprynet.com Thu Jul 24 12:21:58 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 24 Jul 2008 11:21:58 -0500 Subject: repr(string) References: Message-ID: In article , Fredrik Lundh wrote: > David C. Ullrich skrev: > > >> just keep in mind that using eval() on untrusted data isn't a very good > >> idea. > > > > Right. This data comes from me, gets put into a file and then > > read by me. Someone _could_ corrupt that file, but someone who > > could do that could more easily just throw the machine out > > the window... > > and then your boss finds your program useful, and it's installed on a > shared server, and then the guys at the office in Eggkleiva wants a > copy, and then people start shipping save files via mail to keep things > synchronized, and then someone sets up a web service... ;-) Heh-heh. Good point, except that the idea that someone's going to find it useful is utterly implausible. Nobody but me has ever found a program I wrote useful. People think it's funny that I write little Python programs to do things I could just do in Excel or Open Office. (When I have some accounting/secretarial sort of thing to do doing it by hand in Python is one way to make it tolerably interesting. Easier to add new features - instead of trying to find an Excel way to do something like delete the smallest _two_ items in a list I just do it.) > -- David C. Ullrich From tjreedy at udel.edu Fri Jul 18 03:48:19 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Jul 2008 03:48:19 -0400 Subject: None in comparison In-Reply-To: <6eatdoF67cpfU1@mid.uni-berlin.de> References: <549f01d2-1d15-4b0d-9440-a9402c0449ff@b2g2000prf.googlegroups.com> <6eatdoF67cpfU1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Thu, 17 Jul 2008 23:52:13 -0700, r.grimm wrote: > >> Hello, >> I'm a little confused about None in comparison. >> >>>>> id ( None ) >> 3086100672L >>>>> id ( 1 ) >> 134541104 >>>>> None < 1 >> True >> I thought, the id of the object is the last comparison criterion. > > Obviously that expectation is false. The result of a comparison between > different types, with no `__cmp__()` method that says otherwise, is a > arbitrarily but consistent ordering by type. The language doesn't even > guarantee that it must be consistent in different runs of the same program > in the same interpreter, just within one run. > > So if you plan to rely on such implementation details, your program is > broken. And in 3.0 such arbitrary comparisons are gone. >>> None < 1 Traceback (most recent call last): File "", line 1, in None < 1 TypeError: unorderable types: NoneType() < int() From hat at se-162.se.wtb.tue.nl Wed Jul 2 04:15:47 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 02 Jul 2008 10:15:47 +0200 Subject: Problem with a for loop and a list References: Message-ID: On 2008-07-02, Alexnb wrote: > I have no idea what "list assignment index out of range means?!?! You are assigning a value to a non-existing list element, as in >>> x = [1] >>> x[2] = 4 Traceback (most recent call last): File "", line 1, in ? IndexError: list assignment index out of range Albert From goldtech at worldpost.com Fri Jul 25 09:53:32 2008 From: goldtech at worldpost.com (goldtech) Date: Fri, 25 Jul 2008 06:53:32 -0700 (PDT) Subject: Python base distribution come with a validating XML parser? Message-ID: <4205c679-4a0e-41d6-8311-2e033b7b5e0d@j7g2000prm.googlegroups.com> Hi, Basic XML questions, I have a .xml file I want to validate against a .xsd file... Does the Python base distribution come with a validating XML parser? I want to make sure the elements in my xml file vs. the elements defined in my xsd are a match. I could parse both XML and xsd elements to lists and compare the lists, but I imagine the validation process can do this too... Some of this is basic stuff - just a link to a site or doc is sufficient. Thanks. From semanticist at gmail.com Sun Jul 20 00:49:55 2008 From: semanticist at gmail.com (Miles) Date: Sun, 20 Jul 2008 00:49:55 -0400 Subject: Not entirely serious: recursive lambda? In-Reply-To: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> References: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> Message-ID: On Sat, Jul 19, 2008 at 10:43 PM, Michael Tobis wrote: > Can a lambda call itself without giving itself a name? Kind of. There's a couple ways I know of. The functional way, which involves the lambda receiving itself as an argument: (lambda f: f(10, f))(lambda n, f: n and (sys.stdout.write("%d\n" % n) or f(n-1,f))) The stack frame examination way: import sys, inspect, new (lambda:sys.stdout.write('recurse\n') or new.function(inspect.currentframe().f_code, globals())())() The functional way is probably harder to grok unless you've studied lambda calculus or had experience with "real" functional languages (I haven't). For fun, try throwing a Y combinator in there. -Miles From kandasamy.lakshmanan at gmail.com Sat Jul 26 02:44:01 2008 From: kandasamy.lakshmanan at gmail.com (abcd) Date: Fri, 25 Jul 2008 23:44:01 -0700 (PDT) Subject: u just click u get some dollars Message-ID: http://www.parttimejobsu.blogspot.com/ From aspersieman at gmail.com Fri Jul 4 02:58:58 2008 From: aspersieman at gmail.com (Aspersieman) Date: Fri, 04 Jul 2008 08:58:58 +0200 Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: <20080704053113.GJ34192@nexus.in-nomine.org> References: <20080704053113.GJ34192@nexus.in-nomine.org> Message-ID: <486DCA32.5000705@gmail.com> Jeroen Ruigrok van der Werven wrote: > -On [20080630 23:51], Ali Servet D?nmez (asd at pittle.org) wrote: > >> This could be an extension, a plugin, an Emacs mode, a new editor or >> even a brand new huge all-fancy IDE, I don't care, but what am I >> missing here? >> > > Vim's omnicomplete (CTRL-X CTRL-O). > > See :help omnifunc within vim. > > I find Vim with ctags, omnicomplete and calltip support the BEST I've tried so far. And I've tried many. Here's a tutorial on setting this up. http://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/ Regards Nicol -- The three things to remember about Llamas: 1) They are harmless 2) They are deadly 3) They are made of lava, and thus nice to cuddle. From timothywayne.cook at gmail.com Wed Jul 9 11:03:44 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Wed, 09 Jul 2008 12:03:44 -0300 Subject: FOSS projects exhibiting clean/good OOP? In-Reply-To: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> Message-ID: <1215615824.2873.978.camel@localhost.localdomain> On Wed, 2008-07-09 at 07:38 -0700, Phillip B Oldham wrote: > I'm wondering whether anyone can offer suggestions on FOSS projects/ > apps which exhibit solid OO principles, clean code, good inline > documentation, and sound design principles? > > I'm devoting some time to reviewing other people's code to advance my > skills. Its good to review bad code (of which I have more than enough > examples) as well as good, but I'm lacking in finding good examples. > > Projects of varying sizes would be great. Of course 'I think' mine matches that description. :-) In addition to the two links in the signature below where you can get a description and source code; there is an entry on Ohloh that says it is well documented code. http://www.ohloh.net/projects/oship I would appreciate your feedback. Cheers, Tim PS. The Launchpad and Ohloh repositories lag the openEHR SVN by several hours. -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. Home page: https://launchpad.net/oship/ Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From bbkolde at gmail.com Thu Jul 10 13:02:29 2008 From: bbkolde at gmail.com (Bhagwat Kolde) Date: Thu, 10 Jul 2008 22:32:29 +0530 Subject: installing any python module Message-ID: Hi all, What is the correct process of installing any external python module? Once we downloaded any python module, Q1) Where this module should be placed in python installation file structure? Q2) How to execute setup.py file? Thanks, Bhagwat -------------- next part -------------- An HTML attachment was scrubbed... URL: From naude.jaco at gmail.com Wed Jul 23 07:50:25 2008 From: naude.jaco at gmail.com (Jaco Naude) Date: Wed, 23 Jul 2008 04:50:25 -0700 (PDT) Subject: Undefined calling conventions in Python.h References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> Message-ID: On Jul 23, 1:10?pm, Fredrik Lundh wrote: > Jaco Naude wrote: > > What Visual C++ is doing is that it is looking for mangled names since > > it does not know the DLL contains C functions. I've managed to work > > around this by declaring the Python functions as follows before using > > them in the C++ application side: > > > extern "C" > > { > > ? ? void Py_Initialize(void); > > } > > > This seems to work and the C++ application side is not looking for > > mangled names any more. Is this the right way of doing it? It seems > > unnecessary to have to declare each Python function you want to use > > using the extern "C" way as shown above. > > Eh, are you saying that you're not including the Python.h file? ?Because > it does exactly that, for each and every public function in the C API. > > > It is probably more of a C++ question it turns out, but I would think > > that someone in the Python group would use the Python DLL in C++. The > > documentation also suggest that there is no extra work needed when > > using C++ rather than C. > > Oh, but I do that all the time, without doing any extra work. ?Both > embedding Python in C++ programs and existing it with C++ extensions. > And I'm definitely not alone. > > Here's an actual session, using the version of Visual Studio I happen to > have on this machine (2003, I think) from the command line: > > ?> more test.cc > > #include "Python.h" > #include > > main() > { > ? ? ?Py_Initialize(); > ? ? ?PyRun_SimpleString("print 'hello'\n"); > ? ? ?Py_Finalize(); > > ? ? ?std::cout << "world\n"; > > } > > ?> cl cl -EHsc -MD -I \python25\include test.cc \python25\libs\python25.lib > Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 > for 80x86 > Copyright (C) Microsoft Corporation 1984-2002. All rights reserved. > > ... > > ?> test > hello > world > > If you cannot get the same console program to work in your compiler > setup, something's wrong with your configuration. > > Ok that's probably good news, although it points out that there is something wrong with my configuration since that does not work. I would rather sort out the problem that having to defined each function with a extern "C" command. That said, let me double check something which might be causing problems since you will be familiar with this. Which Python.h file do you include when including the DLL in your programs? The one in the source distribution of the one in the installation distribution? I've been including the one in the installation distribution all along. When I try to include the one in the source distribution it gets up to the point where it looks for the following include: #include "pyconfig.h" This file is not in the same directory as the Python.h file in the source distribution. Because of this I just used Python.h in the installation distribution. Thanks again, Jaco From cwitts at gmail.com Wed Jul 23 12:42:06 2008 From: cwitts at gmail.com (Chris) Date: Wed, 23 Jul 2008 09:42:06 -0700 (PDT) Subject: concatenate the elements in each list of a list of lists References: <72c425b7-d9c2-4a61-8b7f-075eae14e703@x41g2000hsb.googlegroups.com> Message-ID: <82b5e735-88ee-45d2-a2fc-0346ed43341b@d77g2000hsb.googlegroups.com> On Jul 23, 5:33?pm, antar2 wrote: > I already asked a similar question, but encounter problems with > python... > How can I concatenate the elements in each list of a list of lists > > list_of_listsA = > > [['klas*', '*', '*'], > ['mooi*', '*', '*', '*'], > ['arm*', '*', '*(haar)']] > > wanted result: > > list_of_listsA = > > [['klas* * *'] > ['mooi* * * *'] > ['arm* * *(haar)']] > > Thanks a lot ! Nice and easy. :) >>> list_of_listsA = [['klas*', '*', '*'], ['mooi*', '*', '*', '*'], ['arm*', '*', '*(haar)']] >>> [' '.join(l) for l in list_of_listsA] ['klas* * *', 'mooi* * * *', 'arm* * *(haar)'] From socyl at 987jk.com.invalid Tue Jul 29 09:49:38 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 13:49:38 +0000 (UTC) Subject: backspace problems References: Message-ID: In kj writes: Please ignore my question. I found a general solution that works not only for the python interactive interpreter but also for all programs that have a readline-type interaction. This solution has nothing to do with Python, but if anyone's interested, it's here: http://www.macosxhints.com/article.php?story=20040930002324870&query=backspace%2Bdebian kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From torriem at gmail.com Tue Jul 15 19:21:14 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 15 Jul 2008 17:21:14 -0600 Subject: bad recursion, still works In-Reply-To: <5be12739-7896-4112-9307-53897af4f691@f63g2000hsf.googlegroups.com> References: <7bf2bad5-d6b6-4929-a520-a82b7bb49916@34g2000hsf.googlegroups.com> <5be12739-7896-4112-9307-53897af4f691@f63g2000hsf.googlegroups.com> Message-ID: <487D30EA.2060707@gmail.com> iu2 wrote: > I still don't understand: In each recursive call to flatten, acc > should be bound to a new [], shouldn't it? Why does the binding happen > only on the first call to flatten? Nope. In each new call it's (re)bound to the same original list, which you've added to as your function continues--it's mutable. Default variables that are bound to mutable objects are one of the big caveats that is mentioned in the FAQ. From bj_666 at gmx.net Wed Jul 16 11:07:53 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Jul 2008 15:07:53 GMT Subject: Angle brackets in command-line arguments? References: <52f1cde3-6240-46b0-8b03-478454e87688@b1g2000hsg.googlegroups.com> Message-ID: <6e6h69F5eajaU3@mid.uni-berlin.de> On Wed, 16 Jul 2008 07:53:56 -0700, Keith Hughitt wrote: > I am using someone else's script which expects input in the form of: > > ./script.py arg2 > > I was wondering if the angle-brackets here have a special meaning? It > seems like they specify an input and output stream to use in place of the > console. I could not find anything in the python manual or Python in a > Nut-shell though. > > Anyone know? That's not Python's business but the command shell's. Those characters are used for redirecting input and ouput from/to files in shells, so it should be covered in the documentation of the shell you are using. Including ways to protect the characters, so they reach the called program in arguments. Ciao, Marc 'BlackJack' Rintsch From fetchinson at googlemail.com Sat Jul 12 12:42:18 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 12 Jul 2008 09:42:18 -0700 Subject: Bypassing WebFilter security In-Reply-To: <25ff817d-2d0f-4806-b635-96e220d920f5@m44g2000hsc.googlegroups.com> References: <563968a1-3cc3-4009-beca-d5d367d4ccff@k13g2000hse.googlegroups.com> <4876F153.2020406@behnel.de> <25ff817d-2d0f-4806-b635-96e220d920f5@m44g2000hsc.googlegroups.com> Message-ID: >> >> I am working in an organization, which is using a very strict >> >> webcontent filter management suite. Due to this i am unable to >> >> download any exe file, or surf web (even the necessary downloads from >> >> sourceforgenet are blocked). I was wondering, if python could be of >> >> any help. Say i have a python script, and i pass the URL of >> >> downloadable file, and it just downloads the file for me. >> >> > Nice try. Can I talk to your employer for a minute? :) >> >> > Honestly, the language doesn't make any difference here, and there isn't >> > much >> > you can do unless you control both sides, i.e. the server and the >> > client. >> > But >> > I would suggest you actually talk to your employer yourself to see if >> > there's >> > an official way to get what you want. >> >> Yes, the language itself doesn't matter as long as you go through the >> web. But if I were you I would use an ssh client to ssh to a remote >> machine on which I have an account, download the file there to that >> machine and scp it to the local machine. Assuming of course port 21 is >> not blocked. >> >> In fact, this is something I do regularly for similar reasons :) >> >> Good luck, >> Daniel >> -- >> Psss, psss, put it down! -http://www.cafepress.com/putitdown > > Daniel, cool even i thought of the same thing, but you see, the > assumption has no use in my case! It is also blocked, Anyways, i will > talk to the system admins here. Thanks all Wait, port 21 is the *incoming* ssh port, when you use a client to ssh *out* you open a generic high port number. So that should work, you ssh out, download, go back to your local machine and scp out to get the file. On your local machine port 21 is not needed simply because you don't run an ssh server. Good luck, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From jordanrastrick at gmail.com Thu Jul 24 10:26:03 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 07:26:03 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> Message-ID: <579f9d5b-8984-425d-8d4f-b2ed0be8eaba@o40g2000prn.googlegroups.com> > I don't really mind, what you think about my response. ?Python will suffer > from it as little as it will suffer from your complaints: ?These things > will not change, whatever any of us says about them. ?So this discussion > unlikely to produce any new insight, especially because this as been > discussed over and over again in the past, without any effect on Python. ? You're right, of course. Because Python is in so many ways what I'm looking for in a language, I transform it in my mind to my own, personal ideal, close to the real existing language but with what I consider to be the imperfections removed. I'm not suggesting getting rid of explicit self, even in "Python 4000." Not because of the advantages it gives, which are some but don't outweigh the net loss in my ledger. It just wouldn't be Pythonic. I know its not a Pythonic thing to want. Thats my problem - because I have a largely Pythonic approach in some areas, it upsets me when there's a mismatch. So lets say I'm -1 for introducing it into a language and +0 for keeping it in Python now that its entrenched. If a lot of users keep bringing up something like this, well my attitude used to be the same as yours - "learn to love Python for what it is." Maybe > Let's just drop this, and if you want to complain next time, just complain > about something, that is really worth being complained about, like for > instance old and outdated modules in the standard library, or real > showstoppers in Python (e.g. the GIL). Its worth complaining about because I'm not just someone who has stumbled across Python after years of Java and PHP, and hasn't really grokked it, and has jumped on the net at once to start a flamewar. I'm someone who loves Python, uses it in preference to other languages, and have now returned to it after a bit of a break and its finally hit me over the head like a tonne of bricks "Hey, I can see exactly what all those internet trolls were talking about. This *is* a really annoying and silly state of affairs." I was trying not to change explicit self, or even != (which has a much better case.) I was trying to ask the community to reconsider a premise that the language is built around. Explicit is actually kinda annoying a lot of the time, viz., java. This is about social and philosophical adjustments, not technical ones. In reality? I'll just keep writing Python (hopefully enough so that explicit self become burned into muscle memory), and use other languages when necessary (no more C than I have to, looking forward to dabbling in Erlang soon, and one day overcoming the parentheses phobia enough to really tackle Lisp properly). When I'm old enough and wise enough, and have the time, energy and inclination, maybe I'll sit down and put a proper effort into designing and implementing a new language that bests suits my own particular style and needs. Just maybe it'll be good enough that smart people will rally to defend its design principles from people attacking them on the internet :-) From rajanikanth at gmail.com Tue Jul 8 20:55:52 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Tue, 8 Jul 2008 17:55:52 -0700 Subject: a simple 'for' question In-Reply-To: <48740BA8.5050605@hughes.net> References: <4874017D.2000401@umbc.edu> <84bdef3c0807081732q33b3bccdvc1d2c361d8c34d80@mail.gmail.com> <48740BA8.5050605@hughes.net> Message-ID: <84bdef3c0807081755v4407b84fl4339aaae2386e14d@mail.gmail.com> Thanks for correcting my typo norseman. Ben: I forgot a slash after the first string as norseman pointed out. Raj On Tue, Jul 8, 2008 at 5:51 PM, norseman wrote: > > Almost correct: There is a typo. Should read: > > for x in folders: > open('my/path/way/'+x+'/myfile.txt','r') > > > > > Rajanikanth Jammalamadaka wrote: >> >> Hi! >> >> Try this >> >> for x in folders: >> open('my/path/way'+x+'myfile.txt','r') >> >> Cheers, >> >> Raj >> >> On Tue, Jul 8, 2008 at 5:08 PM, Ben Keshet wrote: >>> >>> Hi fans, >>> >>> I want to use a 'for' iteration to manipulate files in a set of folders, >>> something like: >>> >>> folders= ['1A28','1A6W','56Y7'] >>> for x in folders: >>> print x # print the current folder >>> f = open('my/path/way/x/my_file.txt', 'r') >>> ... >>> >>> where 'x' in the pathway should iterate over '1A28','1A6W','56Y7'. How >>> should I identify 'x' in the pathway line as the same x that is iterating >>> over 'folders'? >>> >>> I am getting the following error: >>> >>> Traceback (most recent call last): >>> File >>> "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", >>> line 310, in RunScript >>> exec codeObject in __main__.__dict__ >>> File "C:\Linux\Dock_method_validation\myscripts\test_for.py", line 5, in >>> >>> f = open('c:/Linux/Dock_method_validation/x/receptor.mol2', 'r') >>> IOError: [Errno 2] No such file or directory: >>> 'c:/Linux/Dock_method_validation/x/receptor.mol2' >>> >>> I tired several variations: %x, 'x', "x", etc. all gave me similar >>> errors. >>> >>> Thanks for your help, >>> BK >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> >> > > -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From bignose+hates-spam at benfinney.id.au Fri Jul 11 02:23:16 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 11 Jul 2008 16:23:16 +1000 Subject: Python 3.0 and removal of the 'string' module References: <87wsjtqiyo.fsf@benfinney.id.au> Message-ID: <87iqvdq6qz.fsf@benfinney.id.au> Terry Reedy writes: > Ben Finney wrote: > > Can anyone see a reason to believe the above wiki page's statement > > about the 'string' module being removed? More to the point, can > > anyone see a reason why that statement should remain on that page? > > Removing string and moving the functionality elsewhere was considered, > but... [?] Thanks for the pointer. > Feel free to edit the wiki. Done. This is rather disappointing. Is that entire page suspect? It reads like a canonical list of things that will happen in Python 3000. What other long-obsolete information is there? I'm not about to go digging to find out. -- \ ?[T]he question of whether machines can think [?] is about as | `\ relevant as the question of whether submarines can swim.? | _o__) ?Edsger W. Dijkstra | Ben Finney From jkugler at bigfoot.com Mon Jul 28 15:22:19 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Mon, 28 Jul 2008 11:22:19 -0800 Subject: SimpleJson is slow .... is there any C Compiled version ? References: Message-ID: sanket wrote: > Hello All, > > I have created an API which fetches some data from the database. > I am using simplejson to encode it and return it back. > > Now the problem is that, this API is being called for millions of > times in a sequence. > I ran a profiler and saw that most of the time is consumed in encoding > my database results in to json. > So I was just wondering is there any C compiled version of simplejson > is available? > or any help regarding this issue would be appreciated. simplejson does have a C module. It is compiled automatically when installed. If you're installing on Windows, then it probably isn't getting compiled. j From patf at well.com Mon Jul 28 20:44:15 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 17:44:15 -0700 (PDT) Subject: Download excel file from web? References: <6f6vhlFa7anrU1@mid.uni-berlin.de> <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> <19fa0bb2-e101-47c9-84d4-1bf05d08ba39@b2g2000prf.googlegroups.com> Message-ID: On Jul 28, 5:39?pm, MRAB wrote: > On Jul 29, 12:41?am, "p... at well.com" wrote: > > > > > On Jul 28, 4:20?pm, "Guilherme Polo" wrote: > > > > On Mon, Jul 28, 2008 at 8:04 PM, p... at well.com wrote: > > > > On Jul 28, 3:52 pm, "Guilherme Polo" wrote: > > > >> On Mon, Jul 28, 2008 at 7:43 PM, p... at well.com wrote: > > > >> > On Jul 28, 3:33 pm, "p... at well.com" wrote: > > > >> >> On Jul 28, 3:29 pm, "Diez B. Roggisch" wrote: > > > > >> >> > p... at well.com schrieb: > > > > >> >> > > On Jul 28, 3:00 pm, "p... at well.com" wrote: > > > >> >> > >> Hi - experienced programmer but this is my first Python program. > > > > >> >> > >> This URL will retrieve an excel spreadsheet containing (that day's) > > > >> >> > >> msci stock index returns. > > > > >> >> > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > > > >> >> > >> Want to write python to download and save the file. > > > > >> >> > >> So far I've arrived at this: > > > > >> >> > >> [quote] > > > >> >> > >> # import pdb > > > >> >> > >> import urllib2 > > > >> >> > >> from win32com.client import Dispatch > > > > >> >> > >> xlApp = Dispatch("Excel.Application") > > > > >> >> > >> # test 1 > > > >> >> > >> # xlApp.Workbooks.Add() > > > >> >> > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > > > >> >> > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > > > >> >> > >> # xlBook = xlApp.ActiveWorkbook > > > >> >> > >> # xlBook.SaveAs(Filename='C:\\test.xls') > > > > >> >> > >> # pdb.set_trace() > > > >> >> > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > > > >> >> > >> excel? > > > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional') > > > >> >> > >> # test 2 - returns check = False > > > >> >> > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > > > >> >> > >> indexperf/excel? > > > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > > > >> >> > >> xlApp = response.fp > > > >> >> > >> print(response.fp.name) > > > >> >> > >> print(xlApp.name) > > > >> >> > >> xlApp.write > > > >> >> > >> xlApp.Close > > > >> >> > >> [/quote] > > > > >> >> > > Woops hit Send when I wanted Preview. ?Looks like the html [quote] tag > > > >> >> > > doesn't work from groups.google.com (nice). > > > > >> >> > > Anway, in test 1 above, I determined how to instantiate an excel > > > >> >> > > object; put some stuff in it; then save to disk. > > > > >> >> > > So, in theory, I'm retrieving my excel spreadsheet with > > > > >> >> > > response = urllib2.urlopen() > > > > >> >> > > Except what then do I do with this? > > > > >> >> > > Well for one read some of the urllib2 documentation and found the > > > >> >> > > Request class with the method has_data() on it. ?It returns False. > > > >> >> > > Hmm that's not encouraging. > > > > >> >> > > I supposed the trick to understand what urllib2.urlopen is returning > > > >> >> > > to me; rummage around in there; and hopefully find my excel file. > > > > >> >> > > I use pdb to debug. ?This is interesting: > > > > >> >> > > (Pdb) dir(response) > > > >> >> > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > > > >> >> > > 'code', ' > > > >> >> > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > > > >> >> > > 'readline', ' > > > >> >> > > readlines', 'url'] > > > >> >> > > (Pdb) > > > > >> >> > > I suppose the members with __*_ are methods; and the names without the > > > >> >> > > underbars are attributes (variables) (?). > > > > >> >> > No, these are the names of all attributes and methods. read is a method, > > > >> >> > for example. > > > > >> >> right - I got it backwards. > > > > >> >> > > Or maybe this isn't at all the right direction to take (maybe there > > > >> >> > > are much better modules to do this stuff). ?Would be happy to learn if > > > >> >> > > that's the case (and if that gets the job done for me). > > > > >> >> > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty > > > >> >> > clear on this: > > > > >> >> > """ > > > >> >> > This function returns a file-like object with two additional methods: > > > >> >> > """ > > > > >> >> > And then for file-like objects: > > > > >> >> >http://docs.python.org/lib/bltin-file-objects.html > > > > >> >> > """ > > > >> >> > read( ? [size]) > > > >> >> > ? ? ?Read at most size bytes from the file (less if the read hits EOF > > > >> >> > before obtaining size bytes). If the size argument is negative or > > > >> >> > omitted, read all data until EOF is reached. The bytes are returned as a > > > >> >> > string object. An empty string is returned when EOF is encountered > > > >> >> > immediately. (For certain files, like ttys, it makes sense to continue > > > >> >> > reading after an EOF is hit.) Note that this method may call the > > > >> >> > underlying C function fread() more than once in an effort to acquire as > > > >> >> > close to size bytes as possible. Also note that when in non-blocking > > > >> >> > mode, less data than what was requested may be returned, even if no size > > > >> >> > parameter was given. > > > >> >> > """ > > > > >> >> > Diez > > > > >> >> Just stumbled upon .read: > > > > >> >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > > > >> >> excel? > > > >> >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > > >> >> +25%2C+2008&export=Excel_IEIPerfRegional').read > > > > >> >> Now the question is: what to do with this? ?I'll look at the > > > >> >> documentation that you point to. > > > > >> >> thanx - pat > > > > >> > Or rather (next iteration): > > > > >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > > > >> > excel? > > > >> > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > > >> > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > > > >> > The file is generally something like 26 KB so specifying 1,000,000 > > > >> > seems like a good idea (first approximation). > > > > >> > And then when I do: > > > > >> > print(response) > > > > >> > I get a whole lot of garbage (and some non-garbage), so I know I'm > > > >> > onto something. > > > > >> > When I read the .read documentation further, it says that read() has > > > >> > returned the data as a string object. ?Now - how do I convince Python > > > >> > that the string object is in fact an excel file - and save it to disk? > > > > >> You don't need to convince Python, just write it to a file. > > > >> More reading for you:http://docs.python.org/tut/node9.html > > > > >> > pat > > > >> > -- > > > >> >http://mail.python.org/mailman/listinfo/python-list > > > > >> -- > > > >> -- Guilherme H. Polo Goncalves > > > > > OK: > > > > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > > > > excel? > > > > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > > > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > > > # print(response) > > > > f = open("c:\\msci.xls",'w') > > > > f.write(response) > > > > I would initially change that to: > > > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&...) > > > > f = open("c:\\msci.xls", "wb") > > > for line in response: > > > ? ? f.write(line) > > > f.close() > > > > and then.. > > > > > OK this makes the file, and there's a c:\msci.xls in place and it's > > > > about the right size. But whether I make the second param to open 'w' > > > > or 'wb', when I try to open msci.xls from the Windows file explorer, > > > > excel tells me that the file is corrupted. > > > > try it. > > > > > pat > > > > -- > > > >http://mail.python.org/mailman/listinfo/python-list > > > > -- > > > -- Guilherme H. Polo Goncalves > > > A simple f.write(response) does work (click on a single row in Excel > > and you get a single row). > > > But I can see that what you recommend Guilherme is probably safer - > > thanx. > > > pat > > If response contains a string then: > > for line in response: > ? ? f.write(line) > > will actually be writing the string one character at a time! Hmm. In this case, response was a string object. (that's what urllib2.urlopen().read() returns). My concern was with line ending characters (delimiters). I was thinking that if the string object doesn't contain line ending delimiters then maybe the for loop was better. Although that begs the question of how for line in reponse recognizes lines (as defined by line ending delimiters) in the first place. pat From timaranz at gmail.com Thu Jul 10 16:43:25 2008 From: timaranz at gmail.com (Tim Mitchell) Date: Fri, 11 Jul 2008 08:43:25 +1200 Subject: python scalability In-Reply-To: <799d6ad1-8424-4b2a-96a6-6df9a24060d9@27g2000hsf.googlegroups.com> References: Message-ID: <4876746D.3090003@gmail.com> Thanks for all the replies - they have all been helpful. On reflection I think our problems are probably design and people related. Cheers, Tim Michele Simionato wrote: > On Jul 10, 6:32 am, Tim Mitchell wrote: > >> Hi All, >> >> I work on a desktop application that has been developed using python and >> GTK (seewww.leapfrog3d.com). We have around 150k lines of python code >> (and 200k+ lines of C). >> > > We have bigger numbers than yours here (although not for a desktop > application) > and of course we have the problems of a large size application, but > they have > nothing to do with Python. The real problem are sociological, not > language-related. > Essentially, if a project takes 10+ years and 10+ people, with most of > the people > new, you have an issue, but this is independent from the language. > Python is helping > us at least because it is readable and the situation would be probably > be worse with > another language. But as I said the software development practices > used are more > important than the language in this context. > -- > http://mail.python.org/mailman/listinfo/python-list > From pruebauno at latinmail.com Wed Jul 30 10:30:29 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Wed, 30 Jul 2008 07:30:29 -0700 (PDT) Subject: Native Code vs. Python code for modules References: Message-ID: On Jul 29, 11:56 pm, koblas wrote: > better if there was a way that if I have an "interface compatible" > native (aka C) module that has better performance that there could be > a way that python would give it preference. > > e.g. > > import random(version=1.2, lang=c) > or > import random(version=1.2, lang=py) # use the python version by > default > or > import random # use the latest version in the "fastest" code (C > given preference) > > where there could be a nice set of "standard" key value pairs that > could provide addtional hints as to what language and version of a > library was to be used. I will only make a comment on automatic cModule importing. Some of what you are suggesting already happens (e.g. Elementree). In Python 3.0 more of the "legacy" modules (e.g. StringIO) should also work that way. I don't know what the current status for Pickle is because cPickle had some additional internal functionality not available in regular Pickle that Zope was dependent on. From sri_annauni at yahoo.co.in Mon Jul 28 03:33:43 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Mon, 28 Jul 2008 13:03:43 +0530 (IST) Subject: We programming Message-ID: <789038.29418.qm@web7906.mail.in.yahoo.com> Hi, Could someone?suggest?me better python modules for developing web programming related projects like web-pages download and uopload?? Thanks, Srini Explore your hobbies and interests. Go to http://in.promos.yahoo.com/groups/ From enleverlesX.XmcX at XmclaveauX.com Wed Jul 2 17:12:36 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Wed, 2 Jul 2008 23:12:36 +0200 Subject: Scripting SAP GUI (Windows) In-Reply-To: <6d15tpFaec4U1@mid.individual.net> References: <6d15tpFaec4U1@mid.individual.net> Message-ID: <486bf04d$0$843$ba4acef3@news.orange.fr> Hi! You can use Autoit. Bad "conception" language ; but many good tools, for identify windows, process, send keystrokes, emulate mouse, etc. (Autohotkey is make on Autoit 2 ; Autoit is actually in version 3). Good trick : Autoit-X is a COM server, with the most importants functions of Autoit (nor GUI) ; and Autoit-X can be driven from Python+PyWin32. *sorry for my bad english* Michel Claveau PS : http://www.autoitscript.com/autoit3/ (& look also forums) From timr at probo.com Fri Jul 25 01:59:54 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 25 Jul 2008 05:59:54 GMT Subject: pci card adjusting References: Message-ID: "Oguz Yarimtepe" wrote: > >I need to adjust the dimming property of my video card. There is >currently a written application called nvclock but it is not >supporting my card right now. So i need to implement the requiered >register jobs on the card. This is already done to a degree in C. But >i don't want to dive in to the C code right now. > >I prefer Python so may i implement such a feature by Python? Not easily, at least not without a helper DLL in C. And since the app won't be that large, you might as well just do it in C. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From grante at visi.com Tue Jul 22 14:17:10 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 22 Jul 2008 13:17:10 -0500 Subject: The Importance of Terminology's Quality References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: On 2008-07-22, Steve Schafer wrote: > On Tue, 22 Jul 2008 10:21:50 +0100, Martin Gregorie > wrote: > >>The first time I ran across the term "thunking" was when Windows 3 >>introduced the Win32S shim and hence the need to switch addressing between >>16 bit and 32 bit modes across call interfaces. That was called "thunking" >>by Microsoft and even they would surely admit it was a kludge. What?! Microsoft took a technical term and used it to mean something completely different than the widely used meaning? Never. > Win32s thunks are a completely different beast from the > original Algol 60 thunks. As far as I know, the first > published description of thunks was: > > Ingerman PZ (1961) Thunks: A way of compiling procedure statements with > some comments on procedure declarations, CACM 4:55-58. The Algol usage is certainly what we were taught back in the late 70's. I wasn't even aware that Microsoft had hijacked it to mean something else. -- Grant Edwards grante Yow! My polyvinyl cowboy at wallet was made in Hong visi.com Kong by Montgomery Clift! From aljosa.mohorovic at gmail.com Thu Jul 31 12:11:48 2008 From: aljosa.mohorovic at gmail.com (Aljosa Mohorovic) Date: Thu, 31 Jul 2008 09:11:48 -0700 (PDT) Subject: current week / weeks in year - best practice References: <6fdur9Fb0nvuU1@mid.uni-berlin.de> <2ac30ca6-554a-4b40-bdb8-a61f2311ab24@l42g2000hsc.googlegroups.com> Message-ID: On Jul 31, 5:42 pm, Aljosa Mohorovic wrote: > what if i know current context week = 20 (example), what would be the > best way to get datetime objects for first and last day of current > context week? > by "current context week" i don't mean current week for current year > but current week when program is iterating all weeks in year. if w = current context week and now is current datetime object this is how i calculate days: first_day = datetime.strptime("%s %s" % (now.year, str((w-1)*7)), "%Y %j") last_day = first_day + timedelta(days=6) any comments on this? Aljosa Mohorovic From straton at lampsacos.demon.co.uk Mon Jul 7 06:51:42 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Mon, 07 Jul 2008 11:51:42 +0100 Subject: python beginner In-Reply-To: <1cd8ffae-62a7-4cfb-b3ab-61c7004841c9@8g2000hse.googlegroups.com> References: <1cd8ffae-62a7-4cfb-b3ab-61c7004841c9@8g2000hse.googlegroups.com> Message-ID: cna wrote: > Hi all and one, > how may i learn python. is there any other website except python.org For several video series, follow the link from python.org to the ShowMeDo site. http://www.python.org/doc/av/5minutes/ From hv at tbz-pariv.de Wed Jul 30 09:36:46 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Wed, 30 Jul 2008 15:36:46 +0200 Subject: Standard module for parsing emails? In-Reply-To: References: Message-ID: <6fb93eFap7j5U1@mid.individual.net> Phillip B Oldham schrieb: > Is there a standard library for parsing emails that can cope with the > different way email clients quote? What do you mean with "quote" here? 1. Encode utf8/latin1 to ascii 2. Prefix of quoted text like your text above in my mail Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From jeff.dyke at gmail.com Mon Jul 21 12:31:12 2008 From: jeff.dyke at gmail.com (Jeff Dyke) Date: Mon, 21 Jul 2008 12:31:12 -0400 Subject: imported module no longer available In-Reply-To: <8496caf30807210928m27456a1ex747221ea829409a6@mail.gmail.com> References: <8496caf30807210656y3d8467eer83a953e7c37e556c@mail.gmail.com> <8496caf30807210928m27456a1ex747221ea829409a6@mail.gmail.com> Message-ID: <8496caf30807210931y27f5a198q195c9fb752eea5f3@mail.gmail.com> my apologies, to Fredrick, my response when solely to him. reply below, hopefully keeping thread intact. On Mon, Jul 21, 2008 at 12:28 PM, Jeff Dyke wrote: > On Mon, Jul 21, 2008 at 10:19 AM, Fredrik Lundh wrote: >> Jeff Dyke wrote: >> >>> I've come across an error that i'm not yet able to create a test case >>> for but wanted to get see if someone could shed light on this. >>> >>> I have imported a module at the top of my file with >>> import mymodulename >>> >>> this module is used many times in the current file successfully, but >>> then I attempt to use it one more time and get: UnboundLocalError: >>> local variable 'mymodulename' referenced before assignment >> >> Let me guess: you've done >> >> def myfunc(): >> print mymodulename >> import mymodulename > > actually no, the only things in that fucntion were. > print globals().keys() - i see it here > print mymodulename - it fails here. > > the `import mymodulename` statement is at the very top of the file. > > plus the processing that was attempted after. in fact in the calling > method i was able to execute print mymodulename and it printed the > expected python output. > >> >> or something similar? Getting an exception in this case is the excepted >> behaviour; the reason being that a variable in a block only belongs to a >> single scope. for the entire block. For details, see: >> >> http://docs.python.org/ref/naming.html >> >> Especially this section: >> >> "If a name binding operation occurs anywhere within a code block, all uses >> of the name within the block are treated as references to the current block. >> This can lead to errors when a name is used within a block before it is >> bound. This rule is subtle. Python lacks declarations and allows name >> binding operations to occur anywhere within a code block. The local >> variables of a code block can be determined by scanning the entire text of >> the block for name binding operations." >> >> To fix this, mark the name as global: >> >> def myfunc(): >> global mymodulename # I mean the global name! >> print mymodulename >> import mymodulename > > > So i went back to check that the name 'mymodulename' was not getting > overwritten by something else and the error went away. I've been > working on something else entirely for the past few hours and have > changed none of the code...and now it works. which is even more > troublesome then the error itself. > > Follow on question. If this name, mymodulename, was imported in some > other module.fucntion local to a function like > def anotherfunc(): > import mymodulename > > would that remove it from the globals() and save it to a locals() ? I > would assume the answer to be no. > > Thanks for you response. > Jeff > > >> >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > From ivan at datasyncorp.com Thu Jul 3 16:24:08 2008 From: ivan at datasyncorp.com (Ivan Ven Osdel) Date: Thu, 3 Jul 2008 15:24:08 -0500 (CDT) Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: <552487307.956521215116093518.JavaMail.root@saturn.datasyncintra.net> Message-ID: <1020285372.957161215116648910.JavaMail.root@saturn.datasyncintra.net> >From: "Fuzzyman" >To: python-list at python.org >Sent: Thursday, July 3, 2008 12:41:11 PM GMT -06:00 US/Canada Central >Subject: Re: Freesoftware for auto/intelligent code completing in Python > >On Jul 2, 9:33?am, Ali Servet D?nmez wrote: > On Jul 1, 12:15?am, Fuzzyman wrote: > > > > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > I don't want to be so mean here, but how hard it could be be writing a > > > freesoftware which would automatically/intelligently auto complete > > > Python code? (I mean something that really does the job, like > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > name it, but just don't give me PyDev please...) > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > missing here? > > > > Could someone please point me out something that I'm really missing > > > which is already present in the wild, otherwise I'd like discuss with > > > whoever is willing to help me to get this thing done. I made my mind > > > and I could volunteer to make this happen as thesis project for my > > > incoming graduation in the next year. > > > > Regards you all, > > > Ali Servet D?nmez > > > Vim, Emacs, Wing, Komodo, ... more? > > > Yeah, I guess you're missing something. :-) > > > MichaelFoordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > I've checkout Wing IDE's license and it doesnt' seem to be a > freesoftware; am I wrong? > > >Wing 101 is free. The software is good enough though that it is worth >supporting its development by paying for it. > >Michael Foord >-- >http://www.ironpythoninaction.com/ >http://www.trypython.org/ According to the site, Wings 101 doesn't support "Auto-completion for Python and extension modules" but I agree that Wings is worth it if he (or his company) can afford the license(s). If not then he should at least contribute time or money to one of the free (as in free speech, not free beer) alternatives. Ivan Ven Osdel http://www.datasyncsuite.com/ From g.threepwood at gmail.com Fri Jul 18 11:48:50 2008 From: g.threepwood at gmail.com (C Martin) Date: Fri, 18 Jul 2008 08:48:50 -0700 (PDT) Subject: Using Tcl extensions with Python? References: <6f09cdf7-1156-4f41-af5f-c8e5b99eab2d@b1g2000hsg.googlegroups.com> Message-ID: <50f3b23a-127f-429d-b86e-ca9bc163eb4b@i20g2000prf.googlegroups.com> On Jul 17, 5:18 pm, "Guilherme Polo" wrote: [snip] > And.. for tkpng specifically, you won't need tk.call to use it, you > just need to create your images using Tkinter.PhotoImage with a "png" > type. Thank you Guilherme, that's all great info. > Thomas Troeger wrote: > ARGH, Tcl!!! ;-) I know that's not the question, but do you know PIL > (http://www.pythonware.com/products/pil)? Yes, I know about PIL. However, I need use PNGs with a full alpha channel. PIL only seems support simple transparency, whereas TkPNG seems to work as expected with them. If I am incorrect in this, then please let me know how to use it! Thanks. From jeremy at 54oaks.com Wed Jul 2 18:38:50 2008 From: jeremy at 54oaks.com (Jeremy Link) Date: Wed, 2 Jul 2008 15:38:50 -0700 Subject: libffi and ARM support for Python Message-ID: <009101c8dc94$66bd9470$8101a8c0@bocaron> The latest version of libffi is supposed to support the ARM processor. Has anyone taken this and folded into Python v2.5.2 so that we have support for this? I've tried but have run into a few issues: 1. Needed to enable FFI_CLOSURES 2. Added FFI_TRAMPOLINE_SIZE (set it to 32, not sure what this should actually be) 3. still missing ffi_prep_closure (it is not defined in arm/ffi.c) Any ideas or added info would be appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at REMOVE.THIS.cybersource.com.au Tue Jul 29 04:32:19 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 08:32:19 GMT Subject: Is it allowed to use function results as default arguments ? References: <488E2BF1.8020003@gmail.com> Message-ID: On Tue, 29 Jul 2008 09:43:26 +0200, Stef Mientki wrote: > about '.' being the current directory, well I think windows was thrown > at the market about 25 years ago, and since then we don't use '.' > anymore ;-) No, even Windows uses '.' as the current directory -- at least XP does, I haven't tried Vista. However, old Classic Mac OS (pre OS-X) used ':' for the current directory, so dot isn't universal. -- Steven From mrkafk at gmail.com Thu Jul 17 10:51:02 2008 From: mrkafk at gmail.com (mk) Date: Thu, 17 Jul 2008 16:51:02 +0200 Subject: storing references instead of copies in a dictionary In-Reply-To: <19eba037-f7e2-4934-a03b-f1956db8e999@a1g2000hsb.googlegroups.com> References: <19eba037-f7e2-4934-a03b-f1956db8e999@a1g2000hsb.googlegroups.com> Message-ID: Uwe Schmitt wrote: > Python stores references in dictionaries and does not copy ! (unless > you explicitly use the copy module) ! > > In your case the entry in the dictionary is a reference to the same > object which f1 references, that is the object at 0xb7f0ba04. > > If you now say "f1=...:" then f1 references a new object > at 0xb7f0b994, and the entry in your dictionary still references > the "old" object at 0xb7f0ba04. Erm, I theoretically knews that, I guess I suffered temporary insanity when I wrote "copies" of objects. To me it seems that Python actually stores _labels_ referencing _objects_. Here, the problem was that the label in the dictionary led to the "old" object. > I do not know any method to automatically update your dictionary > as there is no possibility to overload the assignement operator "=". > But may be somebody can teach me a new trick :-) Theoretically I could define a class inheriting from dictionary and define a property with a setter (and getter). But I would still have to update the attribute manually, so plain dictionary is just as good. From aaron.hildebrandt at gmail.com Wed Jul 23 15:06:02 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 23 Jul 2008 12:06:02 -0700 (PDT) Subject: Using variables across modules References: <855136ce-6c70-40ac-a462-dc0bbfa1fc3a@b2g2000prf.googlegroups.com> <121c5161-9485-4d6a-a447-9f9dd4227bac@d77g2000hsb.googlegroups.com> Message-ID: > Just wirte test code ! variables.py: myvar = 5 print myvar foo.py: from variables import * def PrintVar(): print myvar bar.py: from variables import * from foo import * print myvar myvar = 2 print myvar PrintVar() "python bar.py" output: 5 5 2 5 ... which is what I was expecting, but not what I want. Obviously, each import is creating its own instance of the variable. What I need is a way to change myvar from within "bar.py" so that PrintVar() returns the new value, even though it's in a different module. From aahz at pythoncraft.com Mon Jul 21 00:03:57 2008 From: aahz at pythoncraft.com (Aahz) Date: 20 Jul 2008 21:03:57 -0700 Subject: Any Game Developers here? References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: In article , Python Nutter wrote: > >There are two books I know of currently in print on game programming, >both use PyGame as it was out first. One book is horrible and only >worth for cleaning yourself up after you use the bathroom. The second >is really well written (The L express game programming book) and >highly recommended if you need to get some basic game design and >programming under your belt in Python. Unfortunately, there are some serious bugs in the L-line book because the author doesn't really understand Python. (I know this because I was one of the tech editors.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From arslanburney at gmail.com Thu Jul 17 04:11:18 2008 From: arslanburney at gmail.com (J-Burns) Date: Thu, 17 Jul 2008 01:11:18 -0700 (PDT) Subject: Rotating a cube References: Message-ID: <3d47df08-9734-4e0f-96ad-37da445b4faf@34g2000hsh.googlegroups.com> On Jul 17, 12:53 pm, Fredrik Lundh wrote: > J-Burns wrote: > > Is there a built in Python function for this? > > for answering questions that have nothing to do with programming, and > looks quite a bit like homework? don't think they've added that one yet. > > maybe you should look for a geometry newsgroup/forum? > > I meant to ask how would you do this in Python... :S From cjw at ncf.ca Sat Jul 26 17:03:49 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 26 Jul 2008 17:03:49 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> Message-ID: <488B9135.3010308@ncf.ca> Russ P. wrote: >> If, as I wrote, you permit the omission of "self" in method signatures >> defined within class definitions, then you could still insist on >> instance attribute qualification using "self" - exactly as one would >> when writing Java according to certain style guidelines. > > I'm not sure exactly what people mean here by allowing "self" to be > "omitted" in method signatures. If it is omitted, then it seems to me > that a place holder would be needed to the interpreter that the first > argument is not just another name for "self." > > In an earlier post on this thread (don't feel like looking it up at > the moment), someone suggested that member data could be accessed > using simply ".member". I think he might be on to something. The dot > is a minimal indicator that the data is a class member rather than > just local. However, a placeholder is still needed in the signature. > > So why not allow something like this?: > > class MyClass: > > def func( , xxx, yyy): > > .xxx = xxx > > local = .yyy > > The "self" argument is replaced with nothing, but a comma is used as a > placeholder. > (+1) but why retain the leading comma in the argument list? Colin W. From jjbutler88 at gmail.com Sun Jul 13 13:22:16 2008 From: jjbutler88 at gmail.com (jjbutler88 at gmail.com) Date: Sun, 13 Jul 2008 10:22:16 -0700 (PDT) Subject: Socket problems Message-ID: I am trying to write a simple python IRC client, roughly following this guide: http://www.devshed.com/c/a/Python/Python-and-IRC/ I have written some code, which uses the same commands as the guide, but I get this error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/threading.py", line 486, in __bootstrap_inner self.run() File "pythonirc.py", line 31, in run self.sock.send('NICK %s\r\n') % self.nick AttributeError: send Here is my code so far: [code] #!/usr/bin/env python from socket import * from threading import Thread import sys class IRCBot(Thread): def __init__(self, host, room, nick, port=6667, ssl=0): Thread.__init__(self) self.host = host self.port = port self.ssl = ssl self.room = room self.nick = nick self.sock = socket(AF_INET, SOCK_STREAM) def run(self): print "Connecting..." try: self.sock.connect((self.host, self.port)) except: print "Could not connect to %s" % self.host sys.exit(1) if self.ssl: try: self.sock = ssl(self.sock) except: print "Server does not suport SSL" sys.exit(1) self.sock.send('NICK %s\r\n') % self.nick self.sock.send('USER PyIRC PyIRC PyIRC :Python IRC\r\n') self.sock.send('JOIN #%s\r\n') % self.room while True: data = self.sock.recv(4096) if data.find('PING') != -1: self.sock.send('PONG' + data.split()[1]+'\r\n') print data def close(self): self.sock.send('PART #%s\r\n') % self.room self.sock.send('QUIT\r\n') self.sock.shutdown(SHIT_RDWR) self.sock.close() IRCBot('irc.psych0tik.net','hbh', 'pythonircclient',6697,1).start() [/code] Anyone know why it might be doing this? Config problem? Thanks in advance, Jon From larzluv at hotmail.com Thu Jul 17 12:22:44 2008 From: larzluv at hotmail.com (Larry Hale) Date: Thu, 17 Jul 2008 09:22:44 -0700 (PDT) Subject: Python Behind a Squid Corporate Proxy on Windows Message-ID: <7b541a3b-846f-496a-aee1-d5719217e011@m45g2000hsb.googlegroups.com> Greetings, Pythonistas! My employer has a Squid Proxy between my Python programs and The Internet. I've searched high-and-low, and can only find examples online of how to do basic authentication to connect TO an external Web Server, but not how to go THROUGH a (corporate) Proxy, thus my question here. I've tried all sorts of permutations based on my findings, but (obviously) nothing's working for me. I've come across conflicting information, including that urllib2 can't/won't do what I'm needing, though this statement was a couple years old. I'm running Python 2.5 on Windows XP SP2 64-bit. The Proxy is Squid (don't know what version, but can find out if this is relevant). urllib2 grabs the Proxy info fine: 'http': 'http://webfilter.xyz.local: 3128' (.getproxies()). There's the obvious necessity of telling "something" my ID/pass *somehow*. An example of one iteration: ###################### import urllib2 proxy_handler = urllib2.ProxyHandler( { "http": "http:// myusername:@webfilter.xyz.local:3128" } ) opener = urllib2.build_opener( proxy_handler ) urllib2.install_opener( opener ) response = opener.open( "http://python.org" ) print response ###################### I've tried situations using HTTPPasswordMgrWithDefaultRealm and its add_password method, also to no avail. (Again, THIS sort of thing seems related to the -external- Web Server, _not_ going *through* a Proxy. 'Course, I could be wrong. But if I am, I couldn't get this to work, either. ;) I've looked at what's happening with Wireshark; Py/my program/urllib2 makes the initial page request, Proxy replies HTTP Error 407: Proxy Authentication Required, and Py/my program/urllib2 simply stops at that, reporting the message/error. Please forgive me; I've been programming in Python for a few years now, but never had to deal with Web Proxies. I *have* tried to RTFMs, but the "documentation" for non-basic stuffs with urllib2 is... uh... well, I'm sure ye olde pro's know... :) Cheers, and *any* help would be appreciated! -Larry From __peter__ at web.de Fri Jul 18 06:05:53 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 12:05:53 +0200 Subject: sub typing built in type with common attributes. Am I right? References: <4d9c4b74-9c28-4b98-afe7-9eb774655c3a@v21g2000pro.googlegroups.com> <98c3de7d-f167-48f9-9736-b09938d96b92@f40g2000pri.googlegroups.com> Message-ID: King wrote: > My mistake... > The correct __slots__ is like: > __slots__ = ['_Attribute_name', '_Attribute_type', '_Attribute_range', > 'label'] > > Could you please suggest an alternative or code improvement for the > matter. How about class AttributesMixin(object): """Warning: If you change name, type, or range of an existing object your computer will explode and you will have noone else to blame. """ def __init__(self, name=None, type=None, range=None, label=None): self.name = name self.type = type self.range = range self.label = label class Float(float, AttributesMixin): pass class Int(int, AttributesMixin): pass Now go and write something useful :-) Peter From keith.hughitt at gmail.com Wed Jul 16 14:00:50 2008 From: keith.hughitt at gmail.com (Keith Hughitt) Date: Wed, 16 Jul 2008 11:00:50 -0700 (PDT) Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> Message-ID: <41d4ffc7-7fd5-4202-92ea-132c7d4f5cd4@s50g2000hsb.googlegroups.com> Thanks Gabriel! That helps clear things up for me. The above method works very well. I only have one remaining question: How can I pass a datetime object to MySQL?' So far, what I've been doing is building the query as a string, for example: query = "INSERT INTO image VALUES(%d, %d, %s, '%s')" % (id, meas, date, 'jpg') cursor.execute(query) This works fine for regular datetime objects, which are passed as strings similar to: "2003-10-01 00:00:00." When incorporating a timezone, however, the resulting string is of the form "2003-10-01 00:00:00+00:00." Unfortunately, MySQL does not recognize the offset. I know you said you don't use MySQL, but how would you do something execute a similar query on the database you normally interface with? Thanks, Keith On Jul 15, 12:04?am, "Gabriel Genellina" wrote: > En Mon, 14 Jul 2008 12:06:30 -0300,KeithHughitt ? > escribi?: > > > > > On Jul 12, 12:52?am, "Gabriel Genellina" > > wrote: > >> En Fri, 11 Jul 2008 15:42:37 -0300,KeithHughitt ? > >> escribi?: > > >> > I am having a little trouble figuring out how to convert a python > >> > datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would > >> > like to create a UTC date so that when I send it to MySQL (which > >> > treats all dates at local dates by default), it will already have > >> > incorporated the proper UTC offset. I've tried looking through the > >> > docshttp://python.active-venture.com/lib/datetime-datetime.html), but > >> > have not had any luck. > > >> You have to use a "timezone aware" datetime object. If all you want is ? > >> to ? > >> store an UTC date, the tzinfo demo classes that you can find in the ? > >> Python ? > >> docs at may be enough. > > > Thanks for advice Gabriel. I downloaded the tzinfo demo class, saved > > it as > > UTC.py and imported it. I'm still not exactly sure how to use it > > though. It looks like > > the file already creates an instance of the UTC tzinfo class (line 20: > > "utc = UTC()"), > > however, when I try to test it out in the interpreter, it cannot be > > found. I'm new > > to python, and there is probably something obvious I'm missing, but do > > you have any ideas? > > The import statement in Python doesn't behave the same way as similar ? > statements in other languages - and it may be confusing you. I'll try to ? > explain it using this example. > You have: > - a *file* UTC.py, containing the source code for the *module* UTC. It ? > contains: > - a *class* definition (UTC) and > - an *instance* of that class, utc. > > --- begin UTC.py ---If you pass a "timezone aware" datetime object as a SQL parameter > class UTC(tzinfo): > ? ?... > utc = UTC() > ... > --- end UTC.py --- > > > Here is what I'm attempting: > > > ============ output begin ============= > > > Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) > > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> import datetime, UTC > > Here you have imported the *module* UTC. That is, the name UTC now refers ? > to a newly created module just loaded from the UTC.py file. > > >>>> t = datetime.datetime(2008, 7, 14, 00, 00, 00, UTC()) > > Traceback (most recent call last): > > ? File "", line 1, in > > TypeError: 'module' object is not callable > > The error comes from UTC(): UTC is a module, UTC() is attempting to "call" ? > it, and since modules are not callable objects, we get a TypeError. > > >>>> utc > > Traceback (most recent call last): > > ? File "", line 1, in > > NameError: name 'utc' is not defined > > The *only* name we have imported so far is UTC - the module. Lowercase utc ? > isn't defined. > > >>>> utc = UTC() > > Traceback (most recent call last): > > ? File "", line 1, in > > TypeError: 'module' object is not callable > > Same as above... > > Ok, how to solve it? We know that UTC refers to the *module* with the same ? > name. To get the *class* inside that module, use UTC.UTC - try again in ? > the interpreter. To create a new instance of that class, you can use ? > UTC.UTC(). To obtain the instance already created in the UTC module, use ? > UTC.utc > > **OR** > > Import those names explicitely: > > py> from UTC import UTC > > In this case the name UTC refers to the *class* inside the module. > In this particular example it may be confusing - both have the same name. ? > Another example from the standard library: the poplib module contains a ? > POP3 class, so after executing this line: > > py> from poplib import POP3 > > the name POP3 refers to that class. The poplib module itself isn't ? > directly available. > Back to the UTC module, you could use: > > py> from UTC import utc > > and now utc refers to the *instance* already created inside the module. ? > This last form may be the most convenient in your case: > > py> import datetime > py> from UTC import utc > py> print datetime.datetime(2008, 7, 14, 20, 30, 0, 0, utc) > 2008-07-14 20:30:00+00:00 > > -- > Gabriel Genellina From __peter__ at web.de Wed Jul 30 13:23:46 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 Jul 2008 19:23:46 +0200 Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: <2a703a46-75bc-4228-95d1-05a4e6030b40@f63g2000hsf.googlegroups.com> <26c2fe8e-d464-44f0-8e57-3b8e82248691@x35g2000hsb.googlegroups.com> Message-ID: Paul Boddie wrote: > On 30 Jul, 18:17, Simon Willison wrote: >> >> Some very useful people in #python on Freenode pointed out that my bug >> occurs because I'm trying to display things interactively in the >> console. Saving to a variable instead fixes the problem. > > What's strange about that is how the object is represented when > displayed: > > ('CHARACTERS', ) > > Here, there's no attempt made to encode \u2019 as an ASCII byte > sequence. Does the OS X version of Python do anything special with > string representations? I'm on Kubuntu 7.10 and see the same error as Simon. The problem is in the minidom.CharacterData class which has the following method def __repr__(self): data = self.data if len(data) > 10: dotdotdot = "..." else: dotdotdot = "" return "" % ( self.__class__.__name__, data[0:10], dotdotdot) The data attribute is a unicode instance... Peter From castironpi at gmail.com Sat Jul 12 14:44:40 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 12 Jul 2008 11:44:40 -0700 (PDT) Subject: why is "self" used in OO-Python? References: Message-ID: On Jul 12, 1:01?pm, Duncan Booth wrote: > ssecorp wrote: > > 1. Why do I have to pass self into every method in a class? Since I am > > always doing why cant this be automated or abstracted away? > > Are the instances where I won't pass self? > > I imagine there is some tradeoff involved otherwise it would have been > > done away with. > > When you define a method in Java there is an implicit 'this' passed to the > method. Python cannot tell when you define a function whether the function > is going to be used as a function, an instance method, a class method, a > static method or something else (or all of the above). Consider this: > > The dynamic nature of Python means you can lift a method out of a class and > re-use it in a different context or inject a function into a class as a > method. There are two ways to handle this sort of code: javascript has an > implied 'this' for everything whether a function or what passes for a > method, Python makes it explicit. > > > 2. self.item instead of getters and setters. I thought one of the main > > purposes of OO was encapsulation. Doesn't messing with internal object- > > representations break this? > > That is correct. Some languages (e.g. Java) don't allow you to encapsulate > attributes so you have to write getter and setter methods. If you expose an > attribute in Java then you cannot later insert some code into the lookup or > override the set without getting all users of your code to change the way > they access the value. This is bad. > > Other languages (e.g. Python, C#) allow you to intercept the attribute > lookup so you can change a plain attribute into a property without > requiring the users of your class alter their source code. With C# I > think they would still need to recompile their code so it may be more > appropriate to avoid using public attributes if you are producing a class > library for widespread reuse, but with Python there is no difference to the > user of your class whether they are accessing an attribute or a property. > > Sadly a lot of Java programmers mistake the limitations of their language > for rules of OO programming, and worse this has spread from Java into other > languages where these restrictions no longer need apply. > > Your Stack class is a bad example: the stack attribute is purely internal > so you wouldn't want to expose it as part of the public interface. Consider > instead something like: > > class AddressBookEntry(object): > ? ? def __init__(self, name, phone): > ? ? ? ? self.name = name > ? ? ? ? self.phone = phone > > ? ? @property > ? ? def phone(self): > ? ? ? ? return self._phone > > ? ? @property.setter > ? ? def phone(self, number) > ? ? ? ? validatephonenumber(number) # may throw an exception > ? ? ? ? ? self._phone = number > > If later you want to add some processing to the name attribute it is easy, > but putting in dummy property getter/setter methods before you need them > would be pointless. Part of the value of accessor methods appears when you're changing class definitions, or changing classes, after you've already started to use them-- the same interface with a different implementation. In the AddressBookEntry example, if you changed a pickled dictionary to a shelf, you could reimplement the class and reprocess stored data files, all without changing the code that uses the class-- especially if there's a lot of it, or you don't know where it all is. Nothing stops you from using accessor methods to offer encapsulation, and permit back-end changes later. But, nothing in Java stops you from declaring class members public. Depending on your development process, data hiding may enforce distribution of labor a little better, resulting in errors in Java where Python relies only on discipline. If you're checking for value validation, you can write a custom setter, regardless of language. Python doesn't break encapsulation; you do. In the Stack example, you have more options than you've mentioned. Can you inherit from list directly? Can you delegate using reflection? Are you studying this example specifically, or the class model generally? If you're choosing a language, be careful that stricter enforcement doesn't cause harder-to-find bugs. Useful link: Section 9.4 in the docs: http://docs.python.org/tut/node11.html From JordanNealBerg at gmail.com Thu Jul 10 13:52:53 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Thu, 10 Jul 2008 10:52:53 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: <8feab8ce-1e09-4438-b00a-3b31956c56af@k37g2000hsf.googlegroups.com> Message-ID: <5c521979-aaf0-4b4b-9673-671a978d050a@j22g2000hsf.googlegroups.com> On Jul 10, 1:35?pm, MRAB wrote: > On Jul 10, 4:56?am, Jordan wrote: > > > > > I am trying to rewrite some C source code for a poker hand evaluator > > in Python. ?Putting aside all of the comments such as just using the C > > code, or using SWIG, etc. ?I have been having problems with my Python > > code not responding the same way as the C version. > > > C verison: > > > unsigned find_fast(unsigned u) > > { > > ? ? unsigned a, b, r; > > ? ? u += 0xe91aaa35; > > ? ? u ^= u >> 16; > > ? ? u += u << 8; > > ? ? u ^= u >> 4; > > ? ? b ?= (u >> 8) & 0x1ff; > > ? ? a ?= (u + (u << 2)) >> 19; > > ? ? r ?= a ^ hash_adjust[b]; > > ? ? return r; > > > } > > > my version (Python, hopefully ;)): > > > def find_fast(u): > > ? ? u += 0xe91aaa35 > > ? ? u ^= u >> 16 > > ? ? u += u << 8 > > ? ? u ^= u >> 4 > > ? ? b ?= (u >> 8) & 0x1ff > > ? ? a ?= (u + (u << 2)) >> 19 > > ? ? r ?= a ^ hash_adjust[b] > > ? ? return r > > > As far as I understand the unsigned instructions in C just increase > > amount of bytes the int can hold, and Python automatically converts to > > longs which have infinite size when necessary, so I am not sure why I > > am getting different results. > > > I assume that I am missing something fairly simple here, so help a > > n00b out if you can :) > > > Thanks in advance, > > > jnb > > You want to restrict the values to 32 bits. The result of + or << may > exceed 32 bits, so you need to mask off the excess bits afterwards. > > def find_fast(u): > ? ? mask = 0xffffffff > ? ? u ?= (u + 0xe91aaa35) & mask > ? ? u ^= u >> 16 > ? ? u ?= (u + (u << 8)) & mask # can get away with only 1 mask here > ? ? u ^= u >> 4 > ? ? b ?= (u >> 8) & 0x1ff > ? ? a ?= ((u + (u << 2)) & mask) >> 19 # can get away with only 1 mask > here > ? ? r ?= a ^ hash_adjust[b] > ? ? return r > > HTH Well, I guess there are two problems....the masking and the fact the in C it seems to for some reason overflow and become a negative value....still not sure why it does it....So the code with just masking doesn't work, you still need some sort of weird inversion like the ~(0xFFFFFFFF - u).....weird anyone? haha From waldemar.rymarkiewicz at gmail.com Wed Jul 23 09:34:16 2008 From: waldemar.rymarkiewicz at gmail.com (waldek) Date: Wed, 23 Jul 2008 06:34:16 -0700 (PDT) Subject: python.exe crash and ctypes use Message-ID: Hi, I have module A.py and B.dll which exports C functions by cdecl_ In A.py I pass callback (py callable) to dll. Next, thread inside dll simply calls my callback (in a loop). After few secs I got crash of python.exe. How to debug it? I'm using winxp and py 2.5.2 =========================== def mycallback(data, size) return 0 CBFUNC = CFUNCTYPE(c_int,POINTER(c_int), c_int) dll = cdll.mydll if dll.RegisterCallback(CBFUNC(mycallback)) != 0: print "Error." =========================== From circularfunc at yahoo.se Tue Jul 29 18:53:47 2008 From: circularfunc at yahoo.se (defn noob) Date: Tue, 29 Jul 2008 15:53:47 -0700 (PDT) Subject: How can I check nbr of cores of computer? Message-ID: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> How can I check how many cores my computer has? Is it possible to do this in a Python-app? From niklas.norrthon at hotmail.com Wed Jul 23 16:21:04 2008 From: niklas.norrthon at hotmail.com (Niklas Norrthon) Date: Wed, 23 Jul 2008 13:21:04 -0700 (PDT) Subject: concatenate the elements in each list of a list of lists References: <72c425b7-d9c2-4a61-8b7f-075eae14e703@x41g2000hsb.googlegroups.com> Message-ID: <0494db0a-d58d-48dc-bea1-36c1997f5384@26g2000hsk.googlegroups.com> On 23 Juli, 17:33, antar2 wrote: > I already asked a similar question, but encounter problems with > python... > How can I concatenate the elements in each list of a list of lists > > list_of_listsA = > > [['klas*', '*', '*'], > ['mooi*', '*', '*', '*'], > ['arm*', '*', '*(haar)']] > > wanted result: > > list_of_listsA = > > [['klas* * *'] > ['mooi* * * *'] > ['arm* * *(haar)']] > > Thanks a lot ! wanted_result = [[item] for item in map(' '.join, list_of_listsA)] From tonal at promsoft.ru Thu Jul 17 03:42:17 2008 From: tonal at promsoft.ru (Alexandr N Zamaraev) Date: Thu, 17 Jul 2008 14:42:17 +0700 Subject: Getting a unknown word out of a list with no spaces In-Reply-To: <18503144.post@talk.nabble.com> References: <18502758.post@talk.nabble.com> <487EF593.5060505@promsoft.ru> <18503144.post@talk.nabble.com> Message-ID: <487EF7D9.8010400@promsoft.ru> Alexnb wrote: >>>>> s = '--a href="/browse/brick"--brick--/a--' >>>>> s >> '--a href="/browse/brick"--brick--/a--' >>>>> ''.join('<%s>' % l if i % 2 == 1 else l for i, l in >> enumerate(s.split('--'))) >> ' /browse/brick brick ' > > I'm sorry, I don't think I was being clear. I replaced the <'s with -- so it > would post online w/o actually making a link. I just need to know how to get > the "brick" out. 1) if string really '--a href="/browse/brick"--brick--/a--' >>> s.split('--', 3)[2] brick 2) if string 'brick' >>> s.split('>', 1)[1].split('<')[0] brick From wolfram.hinderer at googlemail.com Wed Jul 30 17:08:01 2008 From: wolfram.hinderer at googlemail.com (wolfram.hinderer at googlemail.com) Date: Wed, 30 Jul 2008 14:08:01 -0700 (PDT) Subject: seemingly simple list indexing problem References: <999589a9-e1bb-4a64-801c-74ce060bc0c6@i24g2000prf.googlegroups.com> Message-ID: On 29 Jul., 01:05, Raymond Hettinger wrote: > [Ervan Ensis] > > > I have a list like [108, 58, 68]. I want to return > > the sorted indices of these items in the same order > > as the original list. So I should return [2, 0, 1] > > One solution is to think of the list indexes > being sorted according the their corresponding > values in the input array: > > >>> s = [ 108, 58, 68 ] > >>> sorted(range(len(s)), key=s.__getitem__) > > [1, 2, 0] > To get the desired output you have to apply it twice: >>> sorted(range(len(s)), key=sorted(range(len(s)), key=s.__getitem__).__getitem__) [2, 0, 1] Wolfram From pladow at gmail.com Wed Jul 2 11:16:05 2008 From: pladow at gmail.com (Peter LaDow) Date: Wed, 2 Jul 2008 08:16:05 -0700 Subject: AttributeError with embedded Python Message-ID: <9e264e780807020816h35aacf74rb190f5990dc95850@mail.gmail.com> I posted this on c.l.p, but with the high level of traffic there, I thought I'd try to post here as well. I've embedded Python in an extension for a program we are using here at work. And I'm a bit stumped as to why I am getting an AttributeError only in the embedded Python. First, a bit of what I am doing. We use a simulator for a microprocessor we are using in our systems. Our simulator allows for extensions that can be loaded as shared libraries. Rather than code the entire extension in C/C++, I would like to make use of Python to script the extension. So, I first initialize Python (examples below leave out the error checking, but it is there): Py_Initialize(); And then I make sure the script directory is in the path with Py_GetPath() and PySys_SetPath(). Finally, I import the script (say it is in a local file 'script.py'): pName = PyString_FromString("script"); pModule = PyImport_Import(pName); Once the module is imported, I get objects to the functions in the script I want to call later, which I do with: pName = PyString_FromString("foo"); pFunc = PyObject_GetAttr(pModule, pName); Later, I come back and call the function: pResult = PyObject_CallObject(pFunc, NULL); And it always fails whenever I iterate of a list. Say for example my Python function is: def foo(): a = ['cat', 'window', 'defenstrate'] for x in a: print x, len(x) Now, the function runs, i.e. I see the output ("cat 3\nwindow 6\ndefenstrate 11\n"), but I always get the following error message: Traceback (most recent call last): File "./script.py", line 3, in foo for x in a: AttributeError: 'module' object has no attribute 'reset' Now, if I run this exact same script using Python standalone, i.e.: Python 2.3.4 (#1, Nov 20 2007, 15:18:15) [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import script >>> script.foo() cat 3 window 6 defenstrate 11 (I know, and old version of Python. But we are stuck with it because our processes require us to validate a newer version if we change.) This works great. What is the difference? Why does it work in one context but not the other? Thanks, Pete -- -- "To love for the sake of being loved is human; to love for the sake of loving is Angelic." -- Alphonse de Lamartine From mensanator at aol.com Sun Jul 6 22:47:21 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 6 Jul 2008 19:47:21 -0700 (PDT) Subject: can't start IDLE 2.6 in Windows Vista Message-ID: <2b7b982d-7a5e-487e-9b32-f9b6a27d09b2@f63g2000hsf.googlegroups.com> Python 2.6b1 installed ok on my XP laptop but not my Vista desktop. First I got a strange application log error: Activation context generation failed for "C:\Python\Dlls\_socket.pyd". Error in manifest or policy file "C:\Python26\DLLs\Microsoft.VC90.CRT.MANIFEST" on line 12. The value "..\msvcr90.dll" of attribute "name" in element "urn:schemas-microsoft-com:asm.v1^file" is invalid. Oddly, It IS valid. Poking around, I changed the name in the manifest from "..\msvcr90.dll" to "msvcr90.dll" and copied the .dll from the parent directory. This stopped the app;ication error log messages. In Googling around, I found the suggestion to do python lib\idlelib\idle.py -n which gives me this error: Traceback (most recent call last): File "lib\idlelib\idle.py", line 21, in idlelib.PyShell.main() File "C:\Python26\lib\idlelib\PyShell.py", line 1382, in main root = Tk(className="Idle") File "C:\Python26\lib\lib-tk\Tkinter.py", line 1647, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: Can't find a usable init.tcl in the following directories: C:/Python26/lib/tcl8.5 C:/lib/tcl8.5 C:/lib/tcl8.5 C:/library C:/ library C:/tcl8.5.2/library C:/tcl8.5.2/library And, just like the previous error, the file DOES exist Directory of C:\Python26\tcl\tcl8.5 06/12/2008 06:07 PM 24,808 init.tcl But I note that the suggested places it looked have a forward slash instead of a the backward slash used by Windows. Is this why the file can't be found? I would try changing it but can't figure out where to look. From jr9445 at ATT.COM Thu Jul 24 14:55:06 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 24 Jul 2008 13:55:06 -0500 Subject: New to Python, familiar with Perl - Seeking info sources In-Reply-To: <18c8fc73-8ff9-4640-a020-de0be4b76ca4@z72g2000hsb.googlegroups.com> References: <18c8fc73-8ff9-4640-a020-de0be4b76ca4@z72g2000hsb.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Brett Ritter > Sent: Thursday, July 24, 2008 9:54 AM > To: python-list at python.org > Subject: New to Python, familiar with Perl - Seeking info sources > > After many years happily coding Perl, I'm looking to expand my > horizons. [no flames please, I'm pretty aware of Perl's strengths and > weaknesses and I'm just here to learn more, not to enter religious > debates]. > > > Any recommendations? Thanks in advance. > I have a Perl background and have found the O'Reilly books to be useful. The Learning Python book (or whatever it's called) is good because it covers the paradigm shifts and potential gotchas that you won't even consider thinking about otherwise. Only downside is wading through the novice 'how to program' parts. The Cookbook is also good for getting 'standard' apps up and running quickly (meaning you know how to do it in Perl, and just need the equivalent Python syntax/paradigm.) The Python help can be very hit or miss. You're going to have _fun_ with the Python regex module. *twitch*winch*sputter* Generally speaking, there's a Python module to do just about everything you could do in Perl. The only gap I've found is in the win32com with a class in a .tlb file (works fine in Perl, fails in Python.) But someone on the python-win32 list posted a potential workaround which I need to test. The really spiffy part is that when I converted a few Perl scripts to Python, the Python scripts were a bit smaller. =O Python does less compile time type checking than Perl. And finally, this mailing list does produce useful, polite answers about syntax to theory, despite some noise. From duncan.booth at invalid.invalid Thu Jul 31 05:02:16 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Jul 2008 09:02:16 GMT Subject: interpreter vs. compiled References: <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> Message-ID: Terry Reedy wrote: > 1. Portability: The Microsoft C# JIT compiler runs under Windows .NET > on x86/amd64 and maybe it64 and what else? Just porting .NET to run > 0n Linux on the same processors was/is a bit task. Does MONO have a > JIT also? Technically there is no such thing as a Microsoft C# JIT compiler: the C# compiler targets IL and the JIT compilers convert IL to the native machine, but C# is just one of the frontend compilers you could use. Microsoft do JIT compilers for .Net Compact Framework that target ARM, MIPS, SHx and x86. The Mono JIT supports: s390, s390x (32 and 64 bits) Linux SPARC(32) Solaris, Linux PowerPC Linux, Mac OSX x86 Linux, FreeBSD, OpenBSD, NetBSD, Microsoft Windows, Solaris, OS X x86-64: AMD64 and EM64T (64 bit) Linux, Solaris IA64 Itanium2 (64 bit) Linux ARM: little and big endian Linux (both the old and the new ABI) Alpha Linux MIPS Linux HPPA Linux (from http://www.mono-project.com/Supported_Platforms) So I'd say .Net scores pretty highly on the portability stakes. (Although of course code written for .Net might not do so well). -- Duncan Booth http://kupuguy.blogspot.com From grante at visi.com Sun Jul 20 23:06:50 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 20 Jul 2008 22:06:50 -0500 Subject: Python Written in C? References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> Message-ID: On 2008-07-21, Dan Upton wrote: >>> REAL WORLD programmers who want to be generally useful go and >>> learn C#. >> >> No: Real programmers first eat a quiche and then return to >> their Pascal programming. > > Bah, new-fangled languages like Pascal... Real programmers > write Fortran. Using punch-cards and paper-tape. Real programmers can edit their programs with a pointy stick and some home-made sticky-tape. -- Grant Edwards grante Yow! While I'm in at LEVITTOWN I thought I'd visi.com like to see the NUCLEAR FAMILY!! From desothier at yahoo.com Fri Jul 11 09:15:10 2008 From: desothier at yahoo.com (antar2) Date: Fri, 11 Jul 2008 06:15:10 -0700 (PDT) Subject: read file into list of lists Message-ID: Hello, I can not find out how to read a file into a list of lists. I know how to split a text into a list sentences = line.split(\n) following text for example should be considered as a list of lists (3 columns and 3 rows), so that when I make the print statement list[0] [0], that the word pear appears pear noun singular books nouns plural table noun singular Can someone help me? Thanks From bdesth.quelquechose at free.quelquepart.fr Tue Jul 22 11:38:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 22 Jul 2008 17:38:35 +0200 Subject: simple question about dictionaries In-Reply-To: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> References: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> Message-ID: <4885feed$0$12032$426a74cc@news.free.fr> skazhy a ?crit : > hi, i am new to python, so i've a really simple question about > dictionaries. > if i have a dictionary and I make have an input after it (to input > numbers) can i get the key of value that was in input? What if many keys are associated with a same value, ie: d = {'a':100, 'b':200, 'c':100} > somehting like this: > dict = { "key1"=100,"key2"=200,"key3"=300} 1/ don't use 'dict' as an indentifier - this shadows the builtin dict type. 2/ the 'dict literal' syntax is: d = {'key1":100, "key2": 200, "key3":300} > a = input() > print 'the key of inputted value is', dict['a'] > > this syntax of course is wrong, but i hope you got the point.. Assuming you don't have duplicate values, you just need to build a reverse dictionnary, that is using values as keys and keys as values, then lookup this dictionnary. The first operation can be done in one single line. reversed_d = dict((value, key) for key, value in d.items()) From israelu at elbit.co.il Wed Jul 16 03:47:35 2008 From: israelu at elbit.co.il (iu2) Date: Wed, 16 Jul 2008 00:47:35 -0700 (PDT) Subject: bad recursion, still works References: <7bf2bad5-d6b6-4929-a520-a82b7bb49916@34g2000hsf.googlegroups.com> <5be12739-7896-4112-9307-53897af4f691@f63g2000hsf.googlegroups.com> Message-ID: On Jul 16, 2:21?am, Michael Torrie wrote: > iu2 wrote: > > I still don't understand: In each recursive call to flatten, acc > > should be bound to a new [], shouldn't it? Why does the binding happen > > only on the first call to flatten? > > Nope. ?In each new call it's (re)bound to the same original list, which > you've added to as your function continues--it's mutable. ?Default > variables that are bound to mutable objects are one of the big caveats > that is mentioned in the FAQ. Thanks guys, it's clear now From gnewsg at gmail.com Wed Jul 30 13:50:34 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Wed, 30 Jul 2008 10:50:34 -0700 (PDT) Subject: Questions about asyncore References: <5d30aad5-cad7-4e47-aa83-277202c70ae2@z72g2000hsb.googlegroups.com> <6db7042c-02bb-42ef-b578-3811d8f427f5@m36g2000hse.googlegroups.com> Message-ID: <4903018c-feac-40fb-81fc-002dfc430f84@z66g2000hsc.googlegroups.com> On 30 Lug, 09:49, Frank Millman wrote: > On Jul 29, 3:40 pm, "Giampaolo Rodola'" wrote: > > > On 29 Lug, 13:09, Frank Millman wrote: > > Thanks for the reply, Giampaolo. Glad to help. > > The benefit of asynchat is that it automatically handles the buffering > > of both input and output. > > Aside from set/found_terminator() the other two methods you could want > > to look at are push() and push_with_producer(). > > push() is a buffered version of asyncore.send(), push_with_producer() > > accepts a data-producer object you can use in case you want to deal > > with something other than strings (e.g. files, lists, generators, and > > so on...). > > I looked at push() and push_with_producer(). To be honest I don't > fully understand why I would want to use them yet - I will have to go > over them a few more times. However, my handle_write() method seems to > be working ok and is not complicated, so I will stick with that for > now. I don't know whether you need to use them. I've just introduced the benefits of asynchat over asyncore. If you're already ok with your handle_read() implementation you probably don't need anything different. > > I'm not sure to understand but I doubt you have to use a thread. > > If you "have to wait for the reply before continuing" just implement > > this logic into handle_read() or found_terminator() method. > > Maybe I am a bit slow Or maybe my English is not good enough to properly understand what you need (it wouldn't be the first time, after all... =)). > ...but I cannot figure out how to do this without > adding a lot of complication. I will try to give a simple example. > > My server is a database server. It sits between the actual database > and the client, and implements access control, automatic handling of > foreign keys, etc. It accepts messages to read, update, and write > data, and returns the results. > > For testing purposes, I want the client to send and receive messages > such as the following (pseudocode) - > > -> Read Customer record with CustNo = 'A001'. > <- Print data, check that it is correct. [1] > -> Read customer's Branch record. > <- Print data, check that it is correct. > -> Update Customer record with new Branch code. [2] > -> Read Branch code from Customer record. > <- Print code, check that it has changed. > -> Read customer's Branch record. > <- Print data, check that it belongs to the new Branch. > > [1] Amongst other things, the server returns the id of the record > [2] The update request uses the record id to identify which record to > update > > These are just examples of the tests I might want to throw at the > server. With my multi-threaded approach, the asyncore loop runs in the > background, and in the foreground I can easily send any message I like > and check the results. I cannot see how to implement this using > handle_read() and found_terminator(). > > Maybe you can give a simple example of an alternative approach. > > Thanks > > Frank I pretty much have the same overview I had before. As far as I can tell the only reason you want to use a thread is when you have to do something which requires a consistent amount of time to complete so that the asyncore loop gets blocked. The question is: is there anything like that in your code? If the answer is no then you don't need to use threads. Maybe you are just not used to the asynchronous approach where "wait for server to respond" or "wait for the response to be complete" doesn't mean that YOU have to wait. It means that when a specific condition occurs (e.g. some data is received) a certain method of the framework you're using will be called and then it will be up to you deciding what do to. For example, if you're supposed to do something when a string of 5 digits is received, overwrite the handle_read() method and check if that's happened. If not instead of waiting for it to happen just "pass" and wait for handle_read() to be called again. This way you don't do anything which blocks the asynchronous loop and every peer (clients, servers or both) you have in your list of watchable channels will be served. If my response hasn't helped you any further try to post some code so that me or someone else could see what exactly you're trying to do. Hope this helps, anyway. --- Giampaolo http://code.google.com/p/pyftpdlib From python at rcn.com Fri Jul 18 19:51:12 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 18 Jul 2008 16:51:12 -0700 (PDT) Subject: __del__ methods References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> Message-ID: <426ec150-6136-4c3f-a5bb-ed109285b5ac@p31g2000prf.googlegroups.com> On Jul 18, 11:31?am, Jason Baker wrote: > I have a class that I need to do some finalization on when it dies. ?I > know I can use the __del__ method, but I seem to recall that it > impedes garbage collection. ?Is this the case? FWIW, I know a good number of top notch Python programmers who have programmed happily for years without ever using __del__. There are ways to get it to work for you, but it may be the smart thing to pretend that you've never heard of it. Raymond From JordanNealBerg at gmail.com Tue Jul 15 15:47:49 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Tue, 15 Jul 2008 12:47:49 -0700 (PDT) Subject: Testing for connection to a website References: Message-ID: On Jul 15, 3:43?pm, Alexnb wrote: > Okay, I already made this post, but it kinda got lost. So anyway I need to > figure out how to test if the user is able to connect to a specific website. > Last time I got pointed to the urllib2 page, but if I do urlopen() and and > am not connected, the program stops. So I don't know if that was what you > guys wanted me to do, but I don't think so, you guys are smarter than that. > So, how can I test for connection to a website. > -- > View this message in context:http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p... > Sent from the Python - python-list mailing list archive at Nabble.com. Ping it? ~_^ From gherron at islandtraining.com Thu Jul 17 14:23:27 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 17 Jul 2008 11:23:27 -0700 Subject: unpacking with default values In-Reply-To: <6a105194-a248-4ee6-be01-5aef9e5bb648@e53g2000hsa.googlegroups.com> References: <335e7a21-e35e-41ee-9f92-fd4c2f6bf166@f36g2000hsa.googlegroups.com> <6a105194-a248-4ee6-be01-5aef9e5bb648@e53g2000hsa.googlegroups.com> Message-ID: <487F8E1F.7040800@islandtraining.com> McA wrote: > On 17 Jul., 18:33, Gary Herron wrote: > >> In Python 2.x, you can't do that directly, but you should be able to >> create a function that lengthens or shortens an input tuple of arguments >> to the correct length so you can do: >> >> a,c,b = fix(1,2) >> d,e,f = fix(1,2,3,4) >> >> However, the function won't know the length of the left hand side >> sequence, so it will have to be passed in as an extra parameter or hard >> coded. >> > > Hi Gary, > > thank you for the answer. > Do you know the "protocol" used by python while unpacking? > Is it a direct assingnment? Or iterating? > Both I think, but what do you mean by *direct* assignment? > Best regards > Andreas Mock > -- > http://mail.python.org/mailman/listinfo/python-list > It RHS of such an assignment can be any iterable (I think). Lets test: (The nice thing about an interactive Python session, it that it's really easy to test.) >>> L = [1,2,3] >>> a,b,c=L >>> a,b=L Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack >>> a,b,c,d=L Traceback (most recent call last): File "", line 1, in ValueError: need more than 3 values to unpack >>> G = (f for f in [1,2,3]) # A generator expression >>> a,b,c = G >>> G = (f for f in [1,2,3]) # A generator expression >>> a,b = G Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack >>> G = (f for f in [1,2,3]) # A generator expression >>> a,b,c,d = G Traceback (most recent call last): File "", line 1, in ValueError: need more than 3 values to unpack I'd call that direct assignment with values supplied by any iterable. Gary Herron From jstrick at mindspring.com Thu Jul 10 09:45:47 2008 From: jstrick at mindspring.com (jstrick) Date: Thu, 10 Jul 2008 06:45:47 -0700 (PDT) Subject: start reading from certain line References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> <1215601039.2873.972.camel@localhost.localdomain> Message-ID: Here's a simple way to do it with a minimum amount of loopiness (don't forget to use 'try-except' or 'with' in real life): f = open("item1.txt") for preline in f: if "Item 1" in preline: print preline, for goodline in f: # could put an end condition with a 'break' here print goodline, f.close() From pavlovevidence at gmail.com Tue Jul 29 13:30:43 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 10:30:43 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> On Jul 29, 5:15 am, Heiko Wundram wrote: > I can't dig up a simple example from code I wrote quickly, but because of the > fact that explicit comparisons always hamper polymorphism I'm not going to take your word for it. Do you have code that demonstrates how "if x" improves polymorphism relative to simple explicit tests? Carl Banks From deets at nospam.web.de Sun Jul 27 13:46:32 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2008 19:46:32 +0200 Subject: Rant (was Re: x*x if x>10 In-Reply-To: References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> Message-ID: <6f3qjoF9n3cpU1@mid.uni-berlin.de> > >> Can you tell us what you mean by "several names of one object"? You mean >> this? >> >> a = range(10) >> b = a >> >> id(a) == id(b) >> >> >> ? Passing references instead of values is an extremely important concept >> of many languages, without it you would end up copying most of the time. > > OK. I've obviously been thinking about things the wrong way. In Forth you > pass the memory address around, and presumably that's essentially what's > happening when you pass a reference. Pretty much, yes. And I for once can say that I've been caught by modifying e.g. stack-locals instead of heap-objects in C++ by accident. > The problem is, I get caught frequently > in this situation: > > a = [1,2,3] > > def foo(x): > do_something_with_x > return x > > ... > > Then when I call foo(a), a gets changed. It just isn't the effect I expect > from changing a local. It's the way things work - mutables are mutables. If you want them to be modified, use the module copy. As a rule of thumb, don't return objects you didn't create inside a function from scratch. Which is the exact reasoning for the list.sort method btw - returning None is supposed to make you aware of the in-place modification. Diez From deets at nospam.web.de Sun Jul 27 12:40:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2008 18:40:00 +0200 Subject: Rant (was Re: x*x if x>10 In-Reply-To: <1q5p845o2j9htp6vf44u6nqinucsr1numf@4ax.com> References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3g8rF9gfj0U1@mid.uni-berlin.de> <6f3gmaF9moqsU1@mid.uni-berlin.de> <1q5p845o2j9htp6vf44u6nqinucsr1numf@4ax.com> Message-ID: <6f3mn0F9ia4rU1@mid.uni-berlin.de> DaveM schrieb: > On Sun, 27 Jul 2008 16:57:14 +0200, "Diez B. Roggisch" > wrote: > >> Marc 'BlackJack' Rintsch schrieb: >>> On Sun, 27 Jul 2008 16:41:19 +0200, Diez B. Roggisch wrote: >>> >>>> DaveM schrieb: >>>>> Getting back to the list concatenation, I finally found the itertools.chain >>>>> command which is the most compact and fastest (or second fastest by a >>>>> trivial amount, I can't remember which). Along the way, I must have >>>>> tried/used half a dozen methods, ...which brings me back my initial PERL >>>>> comment. There's more than one way to do it in Python, too. > >>>> But I *do* know that taking the python zen literally is fruitless. > >>> I think it should be taken more literally than the wrong reduction to >>> "there should be only one way". People tend to forget "obvious" and >>> "preferably" all the time. > >> Good point. The OP found the obvious way of extending. I wonder what his >> reasons were to abandon it. > > You'll have guessed, I'm sure, that I'm not a professional programmer. This > was the third rewrite of a program to match candidate groups to examiners on > a three day course I run, necessitated on this occasion by a change in the > structure of the course. I originally learnt python as I wrote, and some of > the early code was ugly and verbose, so once the current rewrite was working > I took the opportunity to tidy the code up and document it (yes, I know, but > as I said, I'm an amateur). The list concatenation was an itch I couldn't > scratch: > > temp = [] > for value in sessexam.values(): > temp.extend(value) > c_exam = [name for name in set(temp)] #See what I mean about verbose? > c_exam.sort() > return c_exam > > Six lines just didn't feel like it ought to be the best way to do something > so simple. I liked the attempt below better, but was foolish enough to time > it, so that was the end of that. > > return sorted(list(set(reduce(lambda x, y: x+y, sessexam.values())))) > > The current version (below) is a compromise, but I still feel there _ought_ > to be a simple one word command to join multiple lists. > > a = list(set(itertools.chain(*sessexam.values()))) > a.sort() #As I write I'm wondering if I really need it sorted. Hmm... > return a You are aware that the above is much more than "concatenate a bunch of lists?" You want unique values & sorting, which are two additional requirements. I'd say 3 lines of code for three requirements is ok, so all = sum(sessexam.values(), []) unique = set(all) sorted_result = sorted(unique) And obviously there are more ways to skin *that* cat, some (as itertools.chain) being less memory intensive: a = sorted(set(itertools.chain(*sessexam.values()))) It's debatable if this one-liner is really the way to go, but I fail to see how you expect there to be a specialized builtin for this kind of task. Diez From casey.mcginty at gmail.com Sat Jul 26 20:36:04 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Sat, 26 Jul 2008 14:36:04 -1000 Subject: Pwnie awards In-Reply-To: References: Message-ID: One more award from award winner Tim Neshman ... http://www.thenewsh.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Wed Jul 2 15:13:51 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 02 Jul 2008 20:13:51 +0100 Subject: Win32.client, DAO.DBEngine and exceeding the file sharing count lock In-Reply-To: <486BAA56.4070303@timgolden.me.uk> References: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> <9ab0cc2d-5a7e-40ca-a4da-084347f147cd@m36g2000hse.googlegroups.com> <486BAA56.4070303@timgolden.me.uk> Message-ID: <486BD36F.1060301@timgolden.me.uk> In case it helps, there's a recipe just shown up on the Python Cookbook which at least illustrates DAO use: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/572165 TJG From mal at egenix.com Mon Jul 21 17:54:21 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 21 Jul 2008 23:54:21 +0200 Subject: persistent deque (continued) In-Reply-To: <4c985e86-c0c4-4cb3-b7ce-f8e105b7f85d@y21g2000hsf.googlegroups.com> References: <4c985e86-c0c4-4cb3-b7ce-f8e105b7f85d@y21g2000hsf.googlegroups.com> Message-ID: <4885058D.7090304@egenix.com> On 2008-07-21 21:08, castironpi wrote: > Some time ago, I was asking about the feasibility of a persistent > deque, a double-ended queue. You might want to have a look at mxBeeBase: http://www.egenix.com/products/python/mxBase/mxBeeBase/ Using the integer index you could probably write an on-disk dequeue. The B*Tree indexes available in mxBeeBase keep the indexes sorted, so you'd only have to keep incrementing the index as you add new values and keep a record of the highest and lowest index currently in use. Details are left as exercise for the interested reader ;-) > It runs into the typical space allocation problems. If you're storing > a pickle, you have to allocate and fragment the file you've opened, > since pickles can be variable-length strings; i.e. if the new data is > too long, blank out its entry, and grow the file. If you're storing a > data-type, you lose Python's dynamic-type advantages, as well as its > long integers, as they can be any length. If you change the object in > the deque, such as when using any mutable type, you have to update the > container too. > > Does anyone have any experience storing pickles (I am aware of the > similarities to shelf) to a database? > Can the file system facilitate the variable-length string problem? > How feasible is a length-of-length - length - data solution to the > unbounded integer problem? > Is there any alternative to completely re-pickling a large (say 1k > pickled) object you only change slightly? > What other issues are there? > Is a hybrid-storage type possible, that stores the contents of its > Python-allocated memory block to disk, including reference count, even > if it's a lot slower? The object could not contain any references to > objects not allocated on disk. > > A first approach is for the file to look like this: > > 00 data 01 data 02 > 01 data 03 data 04 > 02 data 05 data 06 > > Append would add: > > 03 data 07 data 08 > > AppendLeft would add: > > -01 data 09 data 0a > > Pop would remove 03, PopLeft would remove -01. You would need a > length-and-head index to make 'rotate' available. Remove would run a > worst-case risk of renumbering half of the indices stored, plus a > rotate. > -- > http://mail.python.org/mailman/listinfo/python-list -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 21 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From sanket.s.patel at gmail.com Fri Jul 25 23:04:19 2008 From: sanket.s.patel at gmail.com (sanket) Date: Fri, 25 Jul 2008 20:04:19 -0700 (PDT) Subject: SimpleJson is slow .... is there any C Compiled version ? References: Message-ID: <711d141b-fe46-437d-b7ca-e11f91c8217f@w1g2000prk.googlegroups.com> On Jul 25, 5:52?pm, Matt Nordhoff wrote: > sanket wrote: > > Hello All, > > > I have created an API which fetches some data from the database. > > I am using simplejson to encode it and return it back. > > > Now the problem is that, this API is being called for millions of > > times in a sequence. > > I ran a profiler and saw that most of the time is consumed in encoding > > my database results in to json. > > So I was just wondering is there any C compiled version of simplejson > > is available? > > or any help regarding this issue would be appreciated. > > > Thank you, > > Sanket > > simplejson is not the only JSON library out there. For example, there's > python-cjson, which is written entirely in C: > > > > There's also an enhanced version of it: > > > > I think simplejson has some small, optional C bits that will improve > performance if you compile them. > > Also, be aware that I think simplejson is being integrated into the > stdlib in Python 2.6. > > Also, simplejson and python-cjson might not be entirely compatible: > there's one character that one escapes and the other doesn't, or something. > -- Thanks Matt. I used cjson and it appears to be 5-6 times faster. Thank you, Sanket From fernandes.fd at gmail.com Fri Jul 4 16:43:11 2008 From: fernandes.fd at gmail.com (Filipe Fernandes) Date: Fri, 4 Jul 2008 16:43:11 -0400 Subject: re.search much slower then grep on some regular expressions In-Reply-To: References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: <11397a330807041343w6697db55p92bf53505ebab8b5@mail.gmail.com> On Fri, Jul 4, 2008 at 8:36 AM, Peter Otten <__peter__ at web.de> wrote: > Henning_Thornblad wrote: > >> What can be the cause of the large difference between re.search and >> grep? > > grep uses a smarter algorithm ;) > >> This script takes about 5 min to run on my computer: >> #!/usr/bin/env python >> import re >> >> row="" >> for a in range(156000): >> row+="a" >> print re.search('[^ "=]*/',row) >> >> >> While doing a simple grep: >> grep '[^ "=]*/' input (input contains 156.000 a in >> one row) >> doesn't even take a second. >> >> Is this a bug in python? > > You could call this a performance bug, but it's not common enough in real > code to get the necessary brain cycles from the core developers. > So you can either write a patch yourself or use a workaround. > > re.search('[^ "=]*/', row) if "/" in row else None > > might be good enough. > Wow... I'm rather surprised at how slow this is... using re.match yields much quicker results, but of course it's not quite the same as re.search Incidentally, if you add the '/' to "row" at the end of the string, re.search returns instantly with a match object. @ Peter I'm not versed enough in regex to tell if this is a bug or not (although I suspect it is), but why would you say this particular regex isn't common enough in real code? filipe From leo_365 at yahoo.com Fri Jul 25 02:58:24 2008 From: leo_365 at yahoo.com (leo davis) Date: Thu, 24 Jul 2008 23:58:24 -0700 (PDT) Subject: need help with introducing more traffic In-Reply-To: Message-ID: <853354.27263.qm@web51803.mail.re2.yahoo.com> Fredrik Lundh, ? I'm with you and my apologies for not making the scenario more clearer in my previous post.... [QUOTE]"load testing" other people's sites are known as something else, of course[QUOTE]- ? ?yes,that could cause a DoS and its lame....I certainly dont intend to do that,was just?checking whether the code was running alright on a random webserver and so if you did notice ran it with only '1(or 5)?thread/s which cant hurt...I have setup an intranet in my uni and thats where i plan to carry out the actual tests as part of my dissertation'. ? Yes,i am trying to write a code to stress test webservers,i know there r many free tools out there but looking for opensource codes so that i couls tweak them. ? Cheers ? ? --- On Fri, 7/25/08, Fredrik Lundh wrote: From: Fredrik Lundh Subject: Re: need help with introducing more traffic To: python-list at python.org Date: Friday, July 25, 2008, 1:46 AM Fredrik Lundh wrote: > "load testing" other people's sites are known as something else, of course. message.replace(" are ", " is ") # do'h! (when do we get the ability to edit our c.l.python messages for, say, 30 minutes after they're posted? ;-) -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From noorhanabbas at yahoo.co.uk Wed Jul 9 06:18:05 2008 From: noorhanabbas at yahoo.co.uk (Noorhan Abbas) Date: Wed, 9 Jul 2008 10:18:05 +0000 (GMT) Subject: Opening Unicode files Message-ID: <636110.21350.qm@web27405.mail.ukl.yahoo.com> Hello, I wonder if you don't mind helping me out in this problem. I have been developing a tool in python that opens some unicode files, reading them and processing the data. It is working fine. When I started to write a cgi module that does the same thing for google appengine(actually it is using the same files that I used befoer), I get an error: ? f = codecs.open (FileName , 'rU', 'utf-8') ? It says that the above functions takes 3 arguments but 4 were given.? I wonder if I need to do something before using the codecs library from within the cgi module?! ? Thank you very much for your help, Nora __________________________________________________________ Not happy with your email address?. Get the one you really want - millions of new email addresses available now at Yahoo! http://uk.docs.yahoo.com/ymail/new.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Tue Jul 29 00:21:31 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 28 Jul 2008 21:21:31 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> Message-ID: On Jul 28, 5:58?pm, Fuzzyman wrote: > On Jul 27, 6:02?am, castironpi wrote: > > > > > On Jul 24, 11:04?pm, Tim Roberts wrote: > > > > castironpi wrote: > > > > >Compiling a program is different than running it. ?A JIT compiler is a > > > >kind of compiler and it makes a compilation step. ?I am saying that > > > >Python is not a compiler and in order to implement JIT, it would have > > > >to change that fact. > > > > And I'm saying you are wrong. ?There is NOTHING inherent in Python that > > > dictates that it be either compiled or interpreted. ?That is simply an > > > implementation decision. ?The CPython implementation happens to interpret. > > > The IronPython implementation compiles the intermediate language to native > > > machine language. > > > > >> of Python that uses .NET. ?In that case, the code *IS* JIT compiled to > > > >> assembly when the program starts. > > > > >But still not the user's code, only the interpreter, which is running > > > >in assembly already anyway in CPython. > > > > In CPython, yes. ?In IronPython, no; the user's code is compiled into > > > machine language. ?Both of them are "Python". > > > -- > > > Tim Roberts, t... at probo.com > > > Providenza & Boekelheide, Inc. > > > In CPython yes. ?In IronPython yes: ?the parts that are compiled into > > machine code are the interpreter, *not user's code*. ?Without that > > step, the interpreter would be running on an interpreter, but that > > doesn't get the user's statement 'a= b+ 1' into registers-- it gets > > 'push, push, add, pop' into registers. > > Well - in IronPython user code gets compiled to in memory assemblies > which can be JIT'ed. > > Michael Foord > --http://www.ironpythoninaction.com/ I don't believe so. Take a sample interpreted language, to be compiled by a sample JIT. a= stack( ) a.push( 0 ) a.push( 2 ) a.push( 4 ) Bytecode output is: allocate var0 call STACK_CONSTRUCTOR initialize var0 return call METH0 var0 const 0 call METH0 var0 const 2 call METH0 var0 const 4 JIT output is assembly: reg0 malloc 4 setjmp jmp STACK_CONSTRUCTOR popjmpv reg1 setjmp reg1 0 jmp METH0 reg1 2 jmp METH0 reg1 4 jmp METH0 But when you compare the C code for 'x= y+ 1' to Python JIT code for 'x= y+ 1', there is no stack and no error checking. They're quite different. In a JIT language, Python runs in native assembly, output similar to CPython, theoretically. User's code -does- -not- -run-. It is moved in to and out of a stack by a program that is running, namely the interpreter, whether it came from C and a compiler, or .NEt, bytecode, and a JIT. From deets at nospam.web.de Sun Jul 27 10:41:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2008 16:41:19 +0200 Subject: Rant (was Re: x*x if x>10 In-Reply-To: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> Message-ID: <6f3fogF9jpidU1@mid.uni-berlin.de> DaveM schrieb: > On Sun, 27 Jul 2008 05:24:36 -0700 (PDT), alex23 wrote: > >> On Jul 27, 10:13 pm, ssecorp wrote: >>> I have seen somewhere that you can write something like: > >>> x*x if x>10 >>> but exactly that doesn't work and I can't get any variation to work. > >> It's called a ternary operator. The format is: >>
verb
Okay, I left off some stuff. But what I need to do is get what is inside each and then each
. But the key is that I need everything in the EXACT order that it would be in the html. I can easily get the tables but it is the span's than I am having trouble with. -- View this message in context: http://www.nabble.com/Help-with-BeautifulSoup-tp18416200p18416200.html Sent from the Python - python-list mailing list archive at Nabble.com. From emen999 at gmail.com Tue Jul 29 06:51:36 2008 From: emen999 at gmail.com (code_berzerker) Date: Tue, 29 Jul 2008 03:51:36 -0700 (PDT) Subject: SWIG and char* newb questions :) Message-ID: <7ec26fb6-3d6a-4e1b-b2c9-a0a254780153@26g2000hsk.googlegroups.com> Hi i'm relatively new to Python and my C/C++ knowledge is near to None. Having said that I feel justified to ask stupid questions :) Ok now more seriously. I have question refering to char* used as function parameters to return values. I have read SWIG manual to find best way to overcome that, but there are many warnings about memory leaks and stuff, so I feel confused. Ok to put it more simply: how to safely define a variable in Python and have it modified by C/C++ function? Even better would be a way to make a tuple of return value and out parameters, but thats probably a lot more work. Any hint will be appreciated! From patf at well.com Tue Jul 29 00:47:08 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 21:47:08 -0700 (PDT) Subject: Download excel file from web? References: <6f6vhlFa7anrU1@mid.uni-berlin.de> <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> <19fa0bb2-e101-47c9-84d4-1bf05d08ba39@b2g2000prf.googlegroups.com> Message-ID: On Jul 28, 6:05?pm, "Guilherme Polo" wrote: > On Mon, Jul 28, 2008 at 9:39 PM, MRAB wrote: > > On Jul 29, 12:41 am, "p... at well.com" wrote: > >> On Jul 28, 4:20 pm, "Guilherme Polo" wrote: > > >> > On Mon, Jul 28, 2008 at 8:04 PM, p... at well.com wrote: > >> > > On Jul 28, 3:52 pm, "Guilherme Polo" wrote: > >> > >> On Mon, Jul 28, 2008 at 7:43 PM, p... at well.com wrote: > >> > >> > On Jul 28, 3:33 pm, "p... at well.com" wrote: > >> > >> >> On Jul 28, 3:29 pm, "Diez B. Roggisch" wrote: > > >> > >> >> > p... at well.com schrieb: > > >> > >> >> > > On Jul 28, 3:00 pm, "p... at well.com" wrote: > >> > >> >> > >> Hi - experienced programmer but this is my first Python program. > > >> > >> >> > >> This URL will retrieve an excel spreadsheet containing (that day's) > >> > >> >> > >> msci stock index returns. > > >> > >> >> > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > >> > >> >> > >> Want to write python to download and save the file. > > >> > >> >> > >> So far I've arrived at this: > > >> > >> >> > >> [quote] > >> > >> >> > >> # import pdb > >> > >> >> > >> import urllib2 > >> > >> >> > >> from win32com.client import Dispatch > > >> > >> >> > >> xlApp = Dispatch("Excel.Application") > > >> > >> >> > >> # test 1 > >> > >> >> > >> # xlApp.Workbooks.Add() > >> > >> >> > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > >> > >> >> > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > >> > >> >> > >> # xlBook = xlApp.ActiveWorkbook > >> > >> >> > >> # xlBook.SaveAs(Filename='C:\\test.xls') > > >> > >> >> > >> # pdb.set_trace() > >> > >> >> > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > >> >> > >> excel? > >> > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional') > >> > >> >> > >> # test 2 - returns check = False > >> > >> >> > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > >> > >> >> > >> indexperf/excel? > >> > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > >> > >> >> > >> xlApp = response.fp > >> > >> >> > >> print(response.fp.name) > >> > >> >> > >> print(xlApp.name) > >> > >> >> > >> xlApp.write > >> > >> >> > >> xlApp.Close > >> > >> >> > >> [/quote] > > >> > >> >> > > Woops hit Send when I wanted Preview. ?Looks like the html [quote] tag > >> > >> >> > > doesn't work from groups.google.com (nice). > > >> > >> >> > > Anway, in test 1 above, I determined how to instantiate an excel > >> > >> >> > > object; put some stuff in it; then save to disk. > > >> > >> >> > > So, in theory, I'm retrieving my excel spreadsheet with > > >> > >> >> > > response = urllib2.urlopen() > > >> > >> >> > > Except what then do I do with this? > > >> > >> >> > > Well for one read some of the urllib2 documentation and found the > >> > >> >> > > Request class with the method has_data() on it. ?It returns False. > >> > >> >> > > Hmm that's not encouraging. > > >> > >> >> > > I supposed the trick to understand what urllib2.urlopen is returning > >> > >> >> > > to me; rummage around in there; and hopefully find my excel file. > > >> > >> >> > > I use pdb to debug. ?This is interesting: > > >> > >> >> > > (Pdb) dir(response) > >> > >> >> > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > >> > >> >> > > 'code', ' > >> > >> >> > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > >> > >> >> > > 'readline', ' > >> > >> >> > > readlines', 'url'] > >> > >> >> > > (Pdb) > > >> > >> >> > > I suppose the members with __*_ are methods; and the names without the > >> > >> >> > > underbars are attributes (variables) (?). > > >> > >> >> > No, these are the names of all attributes and methods. read is a method, > >> > >> >> > for example. > > >> > >> >> right - I got it backwards. > > >> > >> >> > > Or maybe this isn't at all the right direction to take (maybe there > >> > >> >> > > are much better modules to do this stuff). ?Would be happy to learn if > >> > >> >> > > that's the case (and if that gets the job done for me). > > >> > >> >> > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty > >> > >> >> > clear on this: > > >> > >> >> > """ > >> > >> >> > This function returns a file-like object with two additional methods: > >> > >> >> > """ > > >> > >> >> > And then for file-like objects: > > >> > >> >> >http://docs.python.org/lib/bltin-file-objects.html > > >> > >> >> > """ > >> > >> >> > read( ? [size]) > >> > >> >> > ? ? ?Read at most size bytes from the file (less if the read hits EOF > >> > >> >> > before obtaining size bytes). If the size argument is negative or > >> > >> >> > omitted, read all data until EOF is reached. The bytes are returned as a > >> > >> >> > string object. An empty string is returned when EOF is encountered > >> > >> >> > immediately. (For certain files, like ttys, it makes sense to continue > >> > >> >> > reading after an EOF is hit.) Note that this method may call the > >> > >> >> > underlying C function fread() more than once in an effort to acquire as > >> > >> >> > close to size bytes as possible. Also note that when in non-blocking > >> > >> >> > mode, less data than what was requested may be returned, even if no size > >> > >> >> > parameter was given. > >> > >> >> > """ > > >> > >> >> > Diez > > >> > >> >> Just stumbled upon .read: > > >> > >> >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > >> >> excel? > >> > >> >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> >> +25%2C+2008&export=Excel_IEIPerfRegional').read > > >> > >> >> Now the question is: what to do with this? ?I'll look at the > >> > >> >> documentation that you point to. > > >> > >> >> thanx - pat > > >> > >> > Or rather (next iteration): > > >> > >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > >> > excel? > >> > >> > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > >> > >> > The file is generally something like 26 KB so specifying 1,000,000 > >> > >> > seems like a good idea (first approximation). > > >> > >> > And then when I do: > > >> > >> > print(response) > > >> > >> > I get a whole lot of garbage (and some non-garbage), so I know I'm > >> > >> > onto something. > > >> > >> > When I read the .read documentation further, it says that read() has > >> > >> > returned the data as a string object. ?Now - how do I convince Python > >> > >> > that the string object is in fact an excel file - and save it to disk? > > >> > >> You don't need to convince Python, just write it to a file. > >> > >> More reading for you:http://docs.python.org/tut/node9.html > > >> > >> > pat > >> > >> > -- > >> > >> >http://mail.python.org/mailman/listinfo/python-list > > >> > >> -- > >> > >> -- Guilherme H. Polo Goncalves > > >> > > OK: > > >> > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > > excel? > >> > > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > >> > > # print(response) > >> > > f = open("c:\\msci.xls",'w') > >> > > f.write(response) > > >> > I would initially change that to: > > >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&...) > > >> > f = open("c:\\msci.xls", "wb") > >> > for line in response: > >> > ? ? f.write(line) > >> > f.close() > > >> > and then.. > > >> > > OK this makes the file, and there's a c:\msci.xls in place and it's > >> > > about the right size. But whether I make the second param to open 'w' > >> > > or 'wb', when I try to open msci.xls from the Windows file explorer, > >> > > excel tells me that the file is corrupted. > > >> > try it. > > >> > > pat > >> > > -- > >> > >http://mail.python.org/mailman/listinfo/python-list > > >> > -- > >> > -- Guilherme H. Polo Goncalves > > >> A simple f.write(response) does work (click on a single row in Excel > >> and you get a single row). > > >> But I can see that what you recommend Guilherme is probably safer - > >> thanx. > > >> pat > > > If response contains a string then: > > Did you notice I removed the read(...) part ? > > > for line in response: > > ? ?f.write(line) > > > will actually be writing the string one character at a time! > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves Actually no I didn't Guilherme (although I'll take it out now). Would leaving the in urllib2.urlopen().read() imply, as MRAB would seem to indicate, that the following for loop would act byte-by-byte? And if so, how? Even with the .read() in, it was very fast. But it looks like it won't hurt (and very possibly helps) to take it out. pat From tjreedy at udel.edu Sat Jul 12 15:43:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 15:43:03 -0400 Subject: Changing self: if self is a tree how to set to a different self In-Reply-To: References: Message-ID: Kay Schluehr wrote: > > > Since it is acting on a tree why doesn't the code substitute self in > its parent by SS? That's the natural perspective if one considers a > tree as a linked structure and inserts and deletes nodes within this > structure. I think you are suggesting the same thing I did: > If you examine nodes from their parent, I believe you can do the > > substitution in one step. Something like: > > > > for slot,child in ( ('left',self.left), ('right',self.right) ): > > if child is not None: > > if child.val == 'f': > > setattr(self, slot, F.copy().subst('x', child.left)) > > child.elimF > > > > where .subst returns the modified tree. Where F.copy is what was called 'SS'. If not, I don't understand. From fredrik at pythonware.com Thu Jul 24 11:59:39 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 17:59:39 +0200 Subject: Encoding for Devanagari Script. In-Reply-To: References: Message-ID: Atul. skrev: > I wanted to know what encoding should I use to open the files with > Devanagari characters. I was thinking of UTF-8 but was not sure, any > leads on this? Anyone used it earlier? Are we talking about existing files? If you don't know what encoding the files use, you could always try using the UTF-8 codec; it's very likely to complain if you're attempting to decode something that's isn't UTF-8. If that doesn't work, it's a bit trickier -- there are several ways to encode Unicode, and then there's ISCII as well. If you cannot sort it out, try running this: >>> f = open("myfile.txt", "rb") >>> f.read(32) on one of your files, and post the result, and chances are that someone will be able to identify the encoding. From wtanksleyjr at gmail.com Thu Jul 31 09:44:57 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Thu, 31 Jul 2008 06:44:57 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> <4ae2518f-10c0-49f2-b5d7-a75993b0a67d@z66g2000hsc.googlegroups.com> <48915761$0$11736$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <5f3a28f9-5918-4d5a-857b-3fbe2af3b196@u12g2000prd.googlegroups.com> Stefan Behnel wrote: > william tanksley wrote: > > Okay, my answer is that ElementTree (in Python 2.5) is simply > > deranged when it comes to Unicode. It assumes everything's ASCII. > It does not "assume" that. It *requires* byte strings to be ASCII. You can't encode Unicode into an ASCII string. (Well, except using UTF-7.) Bad requirement. > If it > didn't enforce that, how could it possibly know what encoding they were using, > i.e. what they were supposed to mean at all? Read the Python Zen, in the face > of ambiguity, ElementTree refuses the temptation to guess. Python 2.x does > exactly the same thing when it comes to implicit conversion between encoded > strings and Unicode strings. An XML file that begins with the string is NOT ascii. You don't have to guess what encoding it's in. It's UTF-8. If you error out when you hit an 8-bit character, you're not going to be able to process that file. I'm completely lost on why you're claiming otherwise. Furthermore, when ElementTree returns (from one of its .text elements) a string-of-bytes instead of a decoded Unicode string, it doesn't merely "resist the temptation to guess"; instead, it forces ME to guess. I've now had to hardcode "utf-8" into my program, when IT just bypassed and ignored an explicit instruction to use UTF-8. I hope and assume that iTunes will never switch from UTF-8 to UTF-32 -- if it does, my code breaks, and I'll probably have to switch away from ElementTree (I guess that since it requires ASCII it won't even pretend to handle more than 8 bits per character). > If you want to pass plain ASCII strings, you can either pass a byte string or > a Unicode string (that's a plain convenience feature). If you want to pass > anything that's not ASCII, you *must* pass a Unicode string. I don't care about strings. I've never passed ElementTree a string. I'm using a file, a file that's correctly encoded as UTF-8, and it returns some text elements that are raw bytes (undecoded). I have to manually decode them. > > Reference:http://codespeak.net/lxml/compatibility.html > > (Note that the lxml version also doesn't handle Unicode correctly; it > > errors when XML declares its encoding.) > It definitely does "handle Unicode correctly". Actually, this is my bad -- I misread the webpage. lxml appears to handle unicode strings with a declared encoding correctly: it errors out. That's quite reasonable when confronted with a contradiction. According to that page, however, the standard ElementTree library doesn't work that way -- it simply assumes that byte strings are ASCII. I'm going to back down on this one, though. I realize that this is a single paragraph on a third-party website, and it's not really trying to document the official ElementTree (it's trying to document its own version, lxml). So it might not be correct, or it might be overly ambiguous. It might also be talking ONLY about strings, to the exclusion of file input. I don't know, and I don't have the energy to debug it, especially since I can't "fix" anything about it even if something was wrong :-). So I revert to my former position: I don't know why those two lines have to be in that order for my code to work correctly; I don't even know why the "encode" line has to be there at all. When I was using the old Python XML library, I didn't have to worry about encoding or decoding; everything just worked. I really prefer ElementTree, and I'm glad I upgraded, but it really looks like encoding is a problem. > Let me guess, you tried passing > XML as a Unicode string into the parser, and your XML declared itself as > having a byte encoding (). How can that *not* be an error? I thought you just said "resist the temptation to guess"? I didn't pass a string. I passed a file. It didn't error out; instead, it produced bytestring-encoded output (not Unicode). > Stefan -Wm From bdesth.quelquechose at free.quelquepart.fr Sun Jul 27 14:04:27 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Jul 2008 20:04:27 +0200 Subject: Confounded by Python objects In-Reply-To: <009c464f$0$20302$c3e8da3@news.astraweb.com> References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> <5ddae1dd-c7dd-4f04-84f6-ad71c3282c92@j7g2000prm.googlegroups.com> <6f1a6uF9ctsmU1@mid.uni-berlin.de> <009c464f$0$20302$c3e8da3@news.astraweb.com> Message-ID: <488cd4a2$0$21184$426a34cc@news.free.fr> Steven D'Aprano a ?crit : > On Sat, 26 Jul 2008 18:54:22 +0000, Robert Latest wrote: > >> Here's an interesting side note: After fixing my "Channel" thingy the >> whole project behaved as expected. But there was an interesting hitch. >> The main part revolves around another class, "Sequence", which has a >> list of Channels as attribute. I was curious about the performance of my >> script, because eventually this construct is supposed to handle >> megabytes of data. So I wrote a simple loop that creates a new Sequence, >> fills all the Channels with data, and repeats. >> >> Interistingly, the first couple of dozens iterations went satisfactorily >> quickly (took about 1 second total), but after a hundred or so times it >> got really slow -- like a couple of seconds per iteration. >> >> Playing around with the code, not really knowing what to do, I found >> that in the "Sequence" class I had again erroneously declared a >> class-level attribute -- rather harmlessly, just a string, that got >> assigned to once in each iteration on object creation. >> >> After I had deleted that, the loop went blindingly fast without slowing >> down. >> >> What's the mechanics behind this behavior? > > Without actually seeing the code, it's difficult to be sure, but my guess > is that you were accidentally doing repeated string concatenation. This > can be very slow. > > In general, anything that looks like this: > > s = '' > for i in range(10000): # or any big number > s = s + 'another string' > > can be slow. Very slow. But this is way faster: s = '' for i in range(10000): # or any big number s += 'another string' (snip) > It's harder to stumble across the slow behaviour these days, as Python > 2.4 introduced an optimization that, under some circumstances, makes > string concatenation almost as fast as using join(). yeps : using augmented assignment (s =+ some_string) instead of concatenation and rebinding (s = s + some_string). > But be warned: join() > is still the recommended approach. Don't count on this optimization to > save you from slow code. > > If you want to see just how slow repeated concatenation is compared to > joining, try this: > > >>>> import timeit >>>> t1 = timeit.Timer('for i in xrange(1000): x=x+str(i)+"a"', 'x=""') >>>> t2 = timeit.Timer('"".join(str(i)+"a" for i in xrange(1000))', '') >>>> >>>> t1.repeat(number=30) > [0.8506159782409668, 0.80239105224609375, 0.73254203796386719] >>>> t2.repeat(number=30) > [0.052678108215332031, 0.052067995071411133, 0.052803993225097656] > > Concatenation is more than ten times slower in the example above, Not using augmented assignment: >>> from timeit import Timer >>> t1 = Timer('for i in xrange(1000): x+= str(i)+"a"', 'x=""') >>> t2 = Timer('"".join(str(i)+"a" for i in xrange(1000))', '') >>> t1.repeat(number=30) [0.07472991943359375, 0.064207077026367188, 0.064996957778930664] >>> t2.repeat(number=30) [0.071865081787109375, 0.061071872711181641, 0.06132817268371582] (snip) > And even worse: > >>>> t1.repeat(number=50) > [2.7190279960632324, 2.6910948753356934, 2.7089321613311768] >>>> t2.repeat(number=50) > [0.087616920471191406, 0.088094949722290039, 0.087819099426269531] > Not that worse here: >>> t1.repeat(number=50) [0.12305188179016113, 0.10764503479003906, 0.10605692863464355] >>> t2.repeat(number=50) [0.11200308799743652, 0.10315108299255371, 0.10278487205505371] >>> I'd still advise using the sep.join(seq) approach, but not because of performances. From george.sakkis at gmail.com Wed Jul 2 10:40:52 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 2 Jul 2008 07:40:52 -0700 (PDT) Subject: How to pickle bound methods References: Message-ID: <3fecf76b-5785-46ec-bf61-61a498d699d0@34g2000hsh.googlegroups.com> On Jul 2, 8:26 am, srinivasan srinivas wrote: > I am writing client-server program. The server will send a methodname and its arguments to a client. The client has to execute the method and return back the results. Are you aware of Pyro [1] ? Btw, you use the terminology backwards: the client calls a method on a remote server and the server executes it and returns back the results to the client. George [1] http://pyro.sourceforge.net/ From modelnine at modelnine.org Tue Jul 29 15:43:02 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Tue, 29 Jul 2008 20:43:02 +0100 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: Am 29.07.2008, 18:30 Uhr, schrieb Carl Banks : > On Jul 29, 5:15 am, Heiko Wundram wrote: >> I can't dig up a simple example from code I wrote quickly, but because >> of the >> fact that explicit comparisons always hamper polymorphism > > I'm not going to take your word for it. Do you have code that > demonstrates how "if x" improves polymorphism relative to simple > explicit tests? As I wrote in the second reply email I sent, check out my integer set recipe on ASPN (and to save you the search: http://code.activestate.com/recipes/466286/). To test whether the integer set is empty or not (in a polymorphic function which accepts any kind of sequence type), the explicit test would be, as you proposed elsewhere: len(x) > 0. This simply WILL NOT work with some sets of that respective type, because, as I documented for the __len__() method there: the return value of __len__() has to (had to?) be in the range 0 <= len < 2**31 (which I think means, as I tested and implemented it on i386, that the return value has to fit in an ssize_t platform type, but someone with more knowledge of the interpreter internals might be able to comment here; I'm not in the mood for checking this out now). Another reason why the test for __nonzero__() is beneficial, at least here: testing whether the set is empty or not is easy, because an empty set has no ranges, and a set with at least one element has at least one range (i.e., to test whether the set is non-empty, check whether the _ranges member, a list, is __nonzero__()); taking the len() of a set always means adding the size of the ranges together (even though this could of course be precomputed/cached, as the set type is immutable, but I'm not doing that in that recipe's code). So, adding things up: the interpretation of __nonzero__(), i.e. the direct "conversion" to bool, for container-types, implements THE means to test whether the container is empty or not. Insisting on not using it, because a "simple explicit" test is supposedly better, will prove to not work in those cases where the container type might not have a representable length (because of the constraints on the return value of __len__()), even though the container has an empty/non-empty state. I think this does make a very compelling use case for "if x" instead of "if len(x) > 0". --- Heiko. From subhabrata.iisc at hotmail.com Fri Jul 25 11:46:21 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Fri, 25 Jul 2008 08:46:21 -0700 (PDT) Subject: Question Regarding XML Message-ID: Dear Group, I have some queries regarding XML conversion of some .txt/.doc files. I am thinking to use Satine. Is it OK? But it seems to support Python2.3 but does it support 2.5, too? If any one can kindly let me know. Best Regards, Subhabrata. From basti.wiesner at gmx.net Mon Jul 7 10:47:14 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Mon, 07 Jul 2008 16:47:14 +0200 Subject: GUI Programming by hand not code with Python Code References: <7003b665-3227-47a7-ab06-1a486f87939a@a1g2000hsb.googlegroups.com> <85ab371e-9926-4bb3-bcd4-f441de7aa046@k30g2000hse.googlegroups.com> Message-ID: Jason Scheirer : > On Jul 6, 7:33?pm, jayjaygi... at hotmail.co.uk wrote: >> Is their a program that lets you design a GUI by hand (like gambas) >> not by code (like wxpython) but the commands are in python? >> >> A program similar to gambas or vb >> >> Gambas with python code instead of gambas code would be perfect. >> >> Thanks in advance > > Glade for GTK, wxGlade for wxPython. And the designer for Qt4 -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From johnroth1 at gmail.com Tue Jul 15 09:15:35 2008 From: johnroth1 at gmail.com (John Roth) Date: Tue, 15 Jul 2008 06:15:35 -0700 (PDT) Subject: Suggestion: Python global scope References: Message-ID: On Jul 15, 5:57?am, Anonymous Bastard wrote: > I've been tossing this idea in my mind for some time now: > > In Python, declaring a variable using the global statement automatically > makes it available in all subsequent scopes. > > But to me, it makes more sense to use the global statement to 'import' a > variable from the global scope into the current scope. For instance: > > [code] > global X > X = 1 > > def P(): > ? ? ?X = 2 > ? ? ?print X > ? ? ?global X > ? ? ?print X > > print X > P() > print X > [code] > > Currently, this will print 1, 2, 2 and 2. But if global would be limited > to current scope, it would print 1, 2, 1, 1. > > 'X = 2' would work on the local version of X, 'global X' will 'import' > the global X into the local scope, so any actions on X would reference > the global X, rather than previous X. I suppose it could be done, but I for one would be against it on several grounds. First, global operates somewhat as a declaration currently. Declarations are easier for most developers to understand than redefinitions of a variable on the fly. Second, following up the first point, it redefines a variable. While this is common practice, it's unfortunate since it leads to some amount of confusion. It also seems like it would be most useful in large, poorly structured methods, which is exactly the wrong way to go. Finally, as Gerhard Haring has said, it's backward incompatible, so the window for considering it has past: the 3.x series is pretty much frozen. John Roth From Bill at SynectixLtd.com Fri Jul 4 08:25:33 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Fri, 4 Jul 2008 13:25:33 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) Message-ID: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> I am trying to edit Contacts in Outlook. This is so I can transfer numbers from my address book which is an Excel spreadsheet to my mobile phone. I came across the following snippet of code which enabled me to the contacts at least list. I had to root around to discover CdoDefaultFolderContacts (though it was guessable; how could I enumerate win32com.client.constants?). I now want to work through the Contacts in Outlook patching in data from my spreadsheet, and also making new contacts where there is an entry in my spreadsheet which has not gone into Contacts already. Where can I find the API? I downloaded OutlookSpy but it is not clear to me that it can display the structure of the data, nor does it list methods for objects (a Contact, a Folder of Contacts) that I had hoped. TIA, Bill class Folder (object): def __init__ (self, folder): self._folder = folder def __getattr__ (self, attribute): return getattr (self._folder, attribute) def __iter__ (self): # # NB You *must* collect a reference to the # Messages collection here; otherwise GetFirst/Next # resets every time. # messages = self._folder.Messages message = messages.GetFirst () while message: yield message message = messages.GetNext () if __name__ == '__main__': import win32com.client session = win32com.client.gencache.EnsureDispatch ("MAPI.Session") constants = win32com.client.constants session.Logon ("Outlook") # # CdoDefaultFolderInbox # CdoDefaultFolderSentItems # CdoDefaultFolderContacts # contact_items = Folder (session.GetDefaultFolder (constants.CdoDefaultFolderContacts)) for message in contact_items: print message sys.exit(1) print message.Subject From bearophileHUGS at lycos.com Sun Jul 13 21:18:06 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 13 Jul 2008 18:18:06 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> <792048c1-5e18-4a2c-925d-a1c932d18a91@j22g2000hsf.googlegroups.com> Message-ID: <8923d0c5-29ce-495f-924a-6d9d2457138e@e39g2000hsf.googlegroups.com> bukzor: > You need to use two dictionaries. Here's a class that someone's > written that wraps it up into a single dict-like object for you: > http://www.faqts.com/knowledge_base/view.phtml/aid/4376 It contains code like: try: del self.data[item] except KeyError: pass Exceptions are useful in python, but with dictionaries this is probably faster (and shorter), even if it may perform two lookups: if item in self.data: del self.data[item] Bye, bearophile From rcdailey at gmail.com Thu Jul 3 16:53:37 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 3 Jul 2008 15:53:37 -0500 Subject: Recursive wildcard file search Message-ID: <496954360807031353n4f91f691recb330f7350cbf70@mail.gmail.com> Hi, Is there a way to perform a recursive file search using wildcards in python 3.0b1? For example, if I have: C:\foo\abc*xyz.* I want all files in C:\foo and all subfolders (recursively) of C:\foo that match the wildcard abc*xyz.* to be matched. In the end, I want a list of files that matched the search, as well as the directory they're located in. Help is appreciated. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From subhabrata.iisc at hotmail.com Fri Jul 18 06:40:15 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Fri, 18 Jul 2008 03:40:15 -0700 (PDT) Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> Message-ID: <3db7c643-56ca-4d6e-99eb-16176e1a2e88@d19g2000prm.googlegroups.com> Hi Peter, Peter Otten wrote: > SUBHABRATA wrote: > > > Thanx Peter, > > I would change my variables next time I would post. > > No, you should use meaningful variable names when you write your code no > matter whether you plan to post it or not. Good You are teaching me something good in life. Thanx. > > > And obviously, > > thanx for your solution. I am reviewing it, I was also trying out some > > solutions. > > You misunderstood. I did not modify your code other than changing the > variable names. My hope was that with this modification any errors sprang > to you eye... I was seeing that. I am almost near the solution. You can also try some hands if you feel. Best Regards, Subhabrata. > > Peter From ludovic.mercier at gmail.com Wed Jul 9 06:54:53 2008 From: ludovic.mercier at gmail.com (lidiriel) Date: Wed, 9 Jul 2008 03:54:53 -0700 (PDT) Subject: mock with inheritance Message-ID: <87df8aea-a7e4-4e30-9384-960b0a8cfc89@27g2000hsf.googlegroups.com> Hello, i would like use a mock object for testing one class and its methods: Here my class : class Foo(Component): def __init__(self): self._db = self.env.get_db() def foomethod(self, arg): ..... But i don't know how to mock the class Component. Note that Component provide the attribut env. I use Pyhton mock module (author Dave Kirby's ) or mock (author Michael Foord (fuzzyman)) but if you have a generic solution i will adapt it to my problem. Thanks by advance and sorry for my poor english. From carroll at nospam-tjc.com Thu Jul 17 11:55:06 2008 From: carroll at nospam-tjc.com (Terry Carroll) Date: Thu, 17 Jul 2008 08:55:06 -0700 Subject: How to process a very large (4Gb) tarfile from python? References: <0e96241d-60a3-44fd-967a-394904ad5b34@e39g2000hsf.googlegroups.com> Message-ID: <4nqu74p3mmmdmf9pn7125voe6itko8d31k@4ax.com> On Thu, 17 Jul 2008 06:14:45 -0700 (PDT), Uwe Schmitt wrote: >I had a look at tarfile.py in my current Python 2.5 installations >lib path. The iterator caches TarInfo objects in a list >tf.members . If you only want to iterate and you are not interested >in more functionallity, you could use "tf.members=[]" inside >your loop. This is a dirty hack ! Thanks, Uwe. That works fine for me. It now reads through all 2.5 million members, in about 30 minutes, never going above a 4M working set. From alif016 at gmail.com Mon Jul 21 19:00:23 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Mon, 21 Jul 2008 18:00:23 -0500 Subject: Converting List of String to Integer In-Reply-To: References: Message-ID: <48851507.5040907@gmail.com> Samir wrote: > On Jul 21, 6:15 pm, Andrew Freeman wrote: > >> Samir wrote: >> >>> On Jul 21, 3:20 pm, Gary Herron wrote: >>> >>>> Samir wrote: >>>> >>>>> Hi Everyone, >>>>> >>>>> I am relatively new to Python so please forgive me for what seems like >>>>> a basic question. >>>>> >>>>> Assume that I have a list, a, composed of nested lists with string >>>>> representations of integers, such that >>>>> >>>>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] >>>>> >>>>> I would like to convert this to a similar list, b, where the values >>>>> are represented by integers, such as >>>>> >>>>> b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] >>>>> >>>>> I have unsuccessfully tried the following code: >>>>> >>>>> n = [] >>>>> for k in a: >>>>> n.append([int(v) for v in k]) >>>>> print n >>>>> >>>>> Does anyone know what I am doing wrong? >>>>> >>>>> Thanks in advance. >>>>> >>>>> Samir >>>>> -- >>>>> http://mail.python.org/mailman/listinfo/python-list >>>>> >>>> You didn't tell us how it failed for you, so I can't guess what's wrong. >>>> >>>> However, your code works for me: >>>> >>>> >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] >>>> >>> n = [] >>>> >>> for k in a: >>>> ... n.append([int(v) for v in k]) >>>> ... >>>> >>> print n >>>> [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] >>>> >>>> (Although you seem to have confused variables b and n.) >>>> >>>> Gary Herron- Hide quoted text - >>>> >>>> - Show quoted text - >>>> >>> Hi Gary, >>> >>> Thanks for your quick response (and sorry about mixing up b and n). >>> For some reason, the logic I posted seems to work ok while I'm using >>> the Python shell, but when used in my code, the program just hangs. >>> It never outputs the results. Below is the code in its entirety. Is >>> there a problem with my indendentation? >>> >>> a = n = [] >>> t = """ >>> 1 2 >>> 3 >>> 4 5 6 >>> 7 8 9 0 >>> """ >>> >>> d = t.split("\n") >>> >>> for x in range(1,len(d)-1): >>> a.append(d[x].split(" ")) >>> print a >>> >>> for k in a: >>> n.append([int(v) for v in k]) >>> >>> print n >>> >>> Thanks again. >>> >>> Samir >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> I think this will work better, a sub-list comprehension of sorts: >> n = [[int(i) for i in k] for k in a] >> >> here is an ipython interactive session using it: >> In [1]: a = n = [] >> >> In [2]: t = """ >> ...: 1 2 >> ...: 3 >> ...: 4 5 6 >> ...: 7 8 9 0 >> ...: """ >> >> In [3]: >> >> In [4]: d = t.split("\n") >> >> In [5]: for x in range(1,len(d)-1): >> ...: a.append(d[x].split(" ")) >> ...: >> ...: >> >> In [6]: a >> Out[6]: [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] >> >> In [7]: n = [[int(i) for i in k] for k in a] >> >> In [8]: n >> Out[8]: [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] >> -- >> Andrew- Hide quoted text - >> >> - Show quoted text - >> > > Andrew, > > Thanks for the tip, though the syntax makes my head spin a bit in > trying to comprehend it. For my small list, I didn't notice a > discernible increase in speed, but I may have to try it with a larger > list size. > > Incidentally, I had never heard of iPython but from their web site, it > looks like an interesting tool. I'll have to check it out. > > Thanks. > > Samir > -- > http://mail.python.org/mailman/listinfo/python-list > If it helps look at this: n = [[int(i) for i in k] for k in a] like this: n = [] for k in a: for i in k: n.append(int(i)) It is more verbose and easier to read and they both do exactly the same thing! iPython is great, to install it you might try easy_install: http://peak.telecommunity.com/DevCenter/EasyInstall Then in a command line type: easy_install ipython Then, once it is complete, to use iPython type: ipython -- Andrew From larzluv at hotmail.com Fri Jul 18 14:43:41 2008 From: larzluv at hotmail.com (Larry Hale) Date: Fri, 18 Jul 2008 11:43:41 -0700 (PDT) Subject: Python Behind a Squid Corporate Proxy on Windows References: <7b541a3b-846f-496a-aee1-d5719217e011@m45g2000hsb.googlegroups.com> <821d7616-3faa-4dae-a988-18caf4f8598a@8g2000hse.googlegroups.com> <84c473ed-6993-481a-b789-35851242895b@f1g2000prb.googlegroups.com> Message-ID: Thank you so much for the reply, but alas: I get the same results. (urllib2 makes the initial request, Squid replies "Error 407: Proxy Authentication Required", which urllib2 dutifully fails on/raises said error...) I do appreciate your time, though! :) -Larry On Jul 18, 3:08?am, Chris wrote: > On Jul 17, 6:40?pm, Larry Hale wrote: > > > Err, the line above should be: > > > proxy_handler = urllib2.ProxyHandler( { "http": "http:// > > myusername:passw... at webfilter.xyz.local:3128" } ) > > > (Sorry! ?:) > > some old code I wrote to download public domain info for our company, > also through a squid proxy and this still works for me > > import urllib2, urllib > > proxy = urllib2.ProxyHandler({'http': 'http:// > username:password at proxy_url:proxy_port'}) > auth = urllib2.HTTPBasicAuthHandler() > opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) > urllib2.install_opener(opener) > > conn = urllib2.urlopen('http://python.org') > return_str = conn.read() > > fp = open('python.html','w').write(return_str) From mercado949 at gmail.com Thu Jul 17 19:14:56 2008 From: mercado949 at gmail.com (mercado mercado) Date: Thu, 17 Jul 2008 19:14:56 -0400 Subject: Importing different versions of a module Message-ID: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> I have two versions of a script on my machine. One version is for new development and the other version is a production version. This script imports a module from a different directory, and this module again has two versions (a development version and a production version). What I want is for the development script to import the development module, and the production script to import the production module, without making any changes to the code in the script. For example, suppose the development script is in ~/dev/rss.py, and the production script is in ~/prod/rss.py. I want the dev version to import /usr/lib/python2.5/site-packages/lib_dev/parse.py, and the prod version to import usr/lib/python2.5/site-packages/lib_prod/parse.py. My first instinct was to place a .pth file in ~/dev that points to /usr/lib/python2.5/site-packages/lib_dev, and a .pth file in ~/prod that points to /usr/lib/python2.5/site-packages/lib_prod, but it seems that site.py doesn't look at .pth files in the current working directory. My next attempt was to create a symbolic link in ~/dev called parse.py, pointing to /usr/lib/python2.5/site-packages/lib_dev/parse.py, and a symbolic link in ~/prod called parse.py, pointing to /usr/lib/python2.5/site-packages/lib_prod/parse.py, but that didn't work either. Can anybody suggest a way to achieve my goal? Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From babacity4 at gmail.com Thu Jul 24 16:51:09 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:51:09 -0700 (PDT) Subject: sextv1 tv - Amazing porn video collection Message-ID: <03e2be10-3838-46b4-963f-e1d1425a314a@y22g2000prd.googlegroups.com> sextv1 tv . >>>>>>>>>>Best Collection of Sextv1 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE sextv1 tv VIDEOS<<<<<<<<<<< . sextv1 tv From mensanator at aol.com Mon Jul 21 18:58:20 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 21 Jul 2008 15:58:20 -0700 (PDT) Subject: Python Written in C? References: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> Message-ID: <943d208b-35f6-4010-85de-fa034e12b5a8@m36g2000hse.googlegroups.com> On Jul 21, 8:26?am, Johannes Bauer wrote: > Mensanator schrieb: > > > You want cool? > > THIS is cool: > > > j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2])) > > % xyz[1]**(k-1))/xyz[1]**(k-2) > > You call it cool, I call it NameError: name 'invert' is not defined. It is when you do: from gmpy import * That single line wasn't the whole program. What's cool is that it IS a single line, that does answers with >50000 decimal digits without breaking a sweat. Sure, you can use GMP with C (and I've done it). But it's nothing like doing it in Python. > > Regards, > Johannes > > -- > "Wer etwas kritisiert muss es noch lange nicht selber besser k?nnen. Es > reicht zu wissen, da? andere es besser k?nnen und andere es auch > besser machen um einen Vergleich zu bringen." ? ? - ? ? Wolfgang Gerber > ? ? ? ?in de.sci.electronics <47fa8447$0$11545$9b622... at news.freenet.de> From tjreedy at udel.edu Sun Jul 27 02:18:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 02:18:56 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <488B9135.3010308@ncf.ca> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> Message-ID: Colin J. Williams wrote: > Russ P. wrote: >> class MyClass: >> >> def func( , xxx, yyy): >> >> .xxx = xxx >> >> local = .yyy The use of '.' has been suggested before and rejected. From Lie.1296 at gmail.com Sun Jul 27 01:04:48 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 26 Jul 2008 22:04:48 -0700 (PDT) Subject: xml.dom's weirdness? References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> Message-ID: <1c837e71-a191-4495-8ec8-0126003ba9c6@n33g2000pri.googlegroups.com> On Jul 26, 6:03?pm, Fredrik Lundh wrote: > Lie wrote: > > If you have any idea what black magic is happening in my computer > > right now, I'd appreciate it. > > command completion? ?(no ubuntu within reach right now, so I cannot > check how they've set it up). > > try starting python with the "-v" option, so you can see exactly when > the import occurs. > > I run python as: python -v &> pyth.log As I've predicted, they imported the modules when there is an Error, any Error, it seems. I have made a hypothesis that it seems that there is something wrong with the Error Handler, it seems that Python have leaked the modules the Error handler used to my session. Although I am unable to access the modules itself unless I imported those modules by myself, any sub- modules that is loaded by the Error Handler is already loaded, so in my session, those modules are merely rebound to a name in my namespace. Question: Is there a way to list loaded modules, including those that aren't in my namespace? Remarks: In another, possibly unrelated, possibly related case, every time I typed: "help(modules)" (to list all modules installed on the system) I've got an error, I've previously made a thread about this in c.l.py, but I don't really mind that much back then since listing installed modules aren't that important for me (I can lookup standardly installed modules in the internet and the number of 3rd party modules installed, I can count with the fingers from a hand). The thread was: http://groups.google.com/group/comp.lang.python/browse_thread/thread/e981edb45fb3854a/ This is an example of the terminal session me at my-computer:~$ python -v &> pyth.log be_nice = 100 doerror xml import xml xml.dom import email email.mime exit() Python doesn't emit the prompts >>> because they're redirected to pyth.log Here is the SUMMARY of pyth.log (the real one is very long, so I append it at the end) * Typed "python -v &> pyth.log" to terminal * Python imports many modules: zipimport, site, os, errno, posix, posixpath, stat, UserDict, copy_reg, types, _types, sitecustomize, apport_python_hook, warnings, linecache, encodings (# directory /usr/lib/python2.5/encodings), encodings (# precompiled from /usr/lib/python2.5/encodings/ __init__.pyc), codecs, _codecs, encodings.aliases, encodings.utf_8 * Standard Python Heading: Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. * I don't know what this is: dlopen("/usr/lib/python2.5/lib-dynload/ readline.so", 2); * Python imported readline module * Python prompt: I typed "be_nice = 100", no output * Python prompt: I typed "doerror" (since doerror is not defined, it raises NameError, I've tried many other errors, like arithmetic error, etc and they did similar thing), python response with loading a lot of modules: apport (# directory /usr/lib/python2.5/site-packages/apport), apport (# precompiled from /usr/lib/python2.5/site-packages/apport/ __init__.pyc), apport.report, subprocess, traceback, gc, time, select, fcntl, pickle, marshal, struct, _struct, re, sre_compile, _sre, sre_constants, sre_parse, binascii, cStringIO, tempfile, random, math, _random, thread, urllib, string, strop, socket, _socket, _ssl, urlparse, pwd, grp, fnmatch, glob, atexit, xml, xml.dom, xml.dom.domreg, xml.dom.minicompat, xml.dom.minidom, xml.dom.xmlbuilder, copy, xml.dom.NodeFilter, xml.parsers (# directory /usr/lib/python2.5/xml/parsers), xml.parsers (# precompiled from /usr/lib/python2.5/xml/parsers/ __init__.pyc), xml.parsers.expat, pyexpat, problem_report, zlib, base64, gzip, email, email.mime (# directory /usr/lib/python2.5/email/mime), email.mime (# precompiled from /usr/lib/python2.5/email/mime/ __init__.pyc), email.encoders, email.quopri, email.mime.multipart, email.mime.base, email.message, uu, email.charset, email.base64mime, email.utils, email._parseaddr, email.quoprimime, email.errors, email.iterators, email.mime.text, email.mime.nonmultipart, unittest, apport.fileutils, apport.packaging.impl, apt (# directory /usr/lib/python2.5/site-packages/apt), apt (# precompiled from /usr/lib/python2.5/site-packages/apt/ __init__.pyc), apt_pkg, apt.package, gettext, locale, _locale, operator, apt.cache, apt.progress, apt.cdrom, apport.packaging, shutil. Among these imports, there are lines like these interleaved (generally right before the import of the modules with the same name): dlopen("/usr/lib/python2.5/lib-dynload/time.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/select.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/fcntl.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/_struct.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/binascii.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/cStringIO.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/math.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/_random.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/strop.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/_socket.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/_ssl.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/grp.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/pyexpat.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/zlib.so", 2); dlopen("/usr/lib/python2.5/site-packages/apt_pkg.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/_locale.so", 2); dlopen("/usr/lib/python2.5/lib-dynload/operator.so", 2); * After those imports is the standard Python traceback (because of the doerror we made earlier) Traceback (most recent call last): File "", line 1, in NameError: name 'doerror' is not defined * The next few lines (edited[1] form the original, for viewing convenience): >>> xml Traceback (most recent call last): File "", line 1, in NameError: name 'xml' is not defined >>> import xml >>> xml.dom >>> import email >>> email.mime [1] Since this is a dump from IO redirection, the texts coming from stdin is absent, I inserted those stdin manually, so it looks more like terminal transcript, instead of IO redirection. * Python prompt - I typed "exit()", it displayed messages of it clearing itself and cleaning up the modules it have loaded TERMINAL TRANSCRIPT (the one already edited, to get the original, apply the diff far below): # installing zipimport hook import zipimport # builtin # installed zipimport hook # /usr/lib/python2.5/site.pyc matches /usr/lib/python2.5/site.py import site # precompiled from /usr/lib/python2.5/site.pyc # /usr/lib/python2.5/os.pyc matches /usr/lib/python2.5/os.py import os # precompiled from /usr/lib/python2.5/os.pyc import errno # builtin import posix # builtin # /usr/lib/python2.5/posixpath.pyc matches /usr/lib/python2.5/ posixpath.py import posixpath # precompiled from /usr/lib/python2.5/posixpath.pyc # /usr/lib/python2.5/stat.pyc matches /usr/lib/python2.5/stat.py import stat # precompiled from /usr/lib/python2.5/stat.pyc # /usr/lib/python2.5/UserDict.pyc matches /usr/lib/python2.5/ UserDict.py import UserDict # precompiled from /usr/lib/python2.5/UserDict.pyc # /usr/lib/python2.5/copy_reg.pyc matches /usr/lib/python2.5/ copy_reg.py import copy_reg # precompiled from /usr/lib/python2.5/copy_reg.pyc # /usr/lib/python2.5/types.pyc matches /usr/lib/python2.5/types.py import types # precompiled from /usr/lib/python2.5/types.pyc import _types # builtin # /usr/lib/python2.5/sitecustomize.pyc matches /usr/lib/python2.5/ sitecustomize.py import sitecustomize # precompiled from /usr/lib/python2.5/ sitecustomize.pyc # /usr/lib/python2.5/site-packages/apport_python_hook.pyc matches /usr/ lib/python2.5/site-packages/apport_python_hook.py import apport_python_hook # precompiled from /usr/lib/python2.5/site- packages/apport_python_hook.pyc # /usr/lib/python2.5/warnings.pyc matches /usr/lib/python2.5/ warnings.py import warnings # precompiled from /usr/lib/python2.5/warnings.pyc # /usr/lib/python2.5/linecache.pyc matches /usr/lib/python2.5/ linecache.py import linecache # precompiled from /usr/lib/python2.5/linecache.pyc import encodings # directory /usr/lib/python2.5/encodings # /usr/lib/python2.5/encodings/__init__.pyc matches /usr/lib/python2.5/ encodings/__init__.py import encodings # precompiled from /usr/lib/python2.5/encodings/ __init__.pyc # /usr/lib/python2.5/codecs.pyc matches /usr/lib/python2.5/codecs.py import codecs # precompiled from /usr/lib/python2.5/codecs.pyc import _codecs # builtin # /usr/lib/python2.5/encodings/aliases.pyc matches /usr/lib/python2.5/ encodings/aliases.py import encodings.aliases # precompiled from /usr/lib/python2.5/ encodings/aliases.pyc # /usr/lib/python2.5/encodings/utf_8.pyc matches /usr/lib/python2.5/ encodings/utf_8.py import encodings.utf_8 # precompiled from /usr/lib/python2.5/encodings/ utf_8.pyc Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. dlopen("/usr/lib/python2.5/lib-dynload/readline.so", 2); import readline # dynamically loaded from /usr/lib/python2.5/lib- dynload/readline.so >>> be_nice = 100 >>> doerror import apport # directory /usr/lib/python2.5/site-packages/apport # /usr/lib/python2.5/site-packages/apport/__init__.pyc matches /usr/ lib/python2.5/site-packages/apport/__init__.py import apport # precompiled from /usr/lib/python2.5/site-packages/ apport/__init__.pyc # /usr/lib/python2.5/site-packages/apport/report.pyc matches /usr/lib/ python2.5/site-packages/apport/report.py import apport.report # precompiled from /usr/lib/python2.5/site- packages/apport/report.pyc # /usr/lib/python2.5/subprocess.pyc matches /usr/lib/python2.5/ subprocess.py import subprocess # precompiled from /usr/lib/python2.5/subprocess.pyc # /usr/lib/python2.5/traceback.pyc matches /usr/lib/python2.5/ traceback.py import traceback # precompiled from /usr/lib/python2.5/traceback.pyc import gc # builtin dlopen("/usr/lib/python2.5/lib-dynload/time.so", 2); import time # dynamically loaded from /usr/lib/python2.5/lib-dynload/ time.so dlopen("/usr/lib/python2.5/lib-dynload/select.so", 2); import select # dynamically loaded from /usr/lib/python2.5/lib-dynload/ select.so dlopen("/usr/lib/python2.5/lib-dynload/fcntl.so", 2); import fcntl # dynamically loaded from /usr/lib/python2.5/lib-dynload/ fcntl.so # /usr/lib/python2.5/pickle.pyc matches /usr/lib/python2.5/pickle.py import pickle # precompiled from /usr/lib/python2.5/pickle.pyc import marshal # builtin # /usr/lib/python2.5/struct.pyc matches /usr/lib/python2.5/struct.py import struct # precompiled from /usr/lib/python2.5/struct.pyc dlopen("/usr/lib/python2.5/lib-dynload/_struct.so", 2); import _struct # dynamically loaded from /usr/lib/python2.5/lib- dynload/_struct.so # /usr/lib/python2.5/re.pyc matches /usr/lib/python2.5/re.py import re # precompiled from /usr/lib/python2.5/re.pyc # /usr/lib/python2.5/sre_compile.pyc matches /usr/lib/python2.5/ sre_compile.py import sre_compile # precompiled from /usr/lib/python2.5/ sre_compile.pyc import _sre # builtin # /usr/lib/python2.5/sre_constants.pyc matches /usr/lib/python2.5/ sre_constants.py import sre_constants # precompiled from /usr/lib/python2.5/ sre_constants.pyc # /usr/lib/python2.5/sre_parse.pyc matches /usr/lib/python2.5/ sre_parse.py import sre_parse # precompiled from /usr/lib/python2.5/sre_parse.pyc dlopen("/usr/lib/python2.5/lib-dynload/binascii.so", 2); import binascii # dynamically loaded from /usr/lib/python2.5/lib- dynload/binascii.so dlopen("/usr/lib/python2.5/lib-dynload/cStringIO.so", 2); import cStringIO # dynamically loaded from /usr/lib/python2.5/lib- dynload/cStringIO.so # /usr/lib/python2.5/tempfile.pyc matches /usr/lib/python2.5/ tempfile.py import tempfile # precompiled from /usr/lib/python2.5/tempfile.pyc # /usr/lib/python2.5/random.pyc matches /usr/lib/python2.5/random.py import random # precompiled from /usr/lib/python2.5/random.pyc dlopen("/usr/lib/python2.5/lib-dynload/math.so", 2); import math # dynamically loaded from /usr/lib/python2.5/lib-dynload/ math.so dlopen("/usr/lib/python2.5/lib-dynload/_random.so", 2); import _random # dynamically loaded from /usr/lib/python2.5/lib- dynload/_random.so import thread # builtin # /usr/lib/python2.5/urllib.pyc matches /usr/lib/python2.5/urllib.py import urllib # precompiled from /usr/lib/python2.5/urllib.pyc # /usr/lib/python2.5/string.pyc matches /usr/lib/python2.5/string.py import string # precompiled from /usr/lib/python2.5/string.pyc dlopen("/usr/lib/python2.5/lib-dynload/strop.so", 2); import strop # dynamically loaded from /usr/lib/python2.5/lib-dynload/ strop.so # /usr/lib/python2.5/socket.pyc matches /usr/lib/python2.5/socket.py import socket # precompiled from /usr/lib/python2.5/socket.pyc dlopen("/usr/lib/python2.5/lib-dynload/_socket.so", 2); import _socket # dynamically loaded from /usr/lib/python2.5/lib- dynload/_socket.so dlopen("/usr/lib/python2.5/lib-dynload/_ssl.so", 2); import _ssl # dynamically loaded from /usr/lib/python2.5/lib-dynload/ _ssl.so # /usr/lib/python2.5/urlparse.pyc matches /usr/lib/python2.5/ urlparse.py import urlparse # precompiled from /usr/lib/python2.5/urlparse.pyc import pwd # builtin dlopen("/usr/lib/python2.5/lib-dynload/grp.so", 2); import grp # dynamically loaded from /usr/lib/python2.5/lib-dynload/ grp.so # /usr/lib/python2.5/fnmatch.pyc matches /usr/lib/python2.5/fnmatch.py import fnmatch # precompiled from /usr/lib/python2.5/fnmatch.pyc # /usr/lib/python2.5/glob.pyc matches /usr/lib/python2.5/glob.py import glob # precompiled from /usr/lib/python2.5/glob.pyc # /usr/lib/python2.5/atexit.pyc matches /usr/lib/python2.5/atexit.py import atexit # precompiled from /usr/lib/python2.5/atexit.pyc import xml # directory /usr/lib/python2.5/xml # /usr/lib/python2.5/xml/__init__.pyc matches /usr/lib/python2.5/xml/ __init__.py import xml # precompiled from /usr/lib/python2.5/xml/__init__.pyc import xml.dom # directory /usr/lib/python2.5/xml/dom # /usr/lib/python2.5/xml/dom/__init__.pyc matches /usr/lib/python2.5/ xml/dom/__init__.py import xml.dom # precompiled from /usr/lib/python2.5/xml/dom/ __init__.pyc # /usr/lib/python2.5/xml/dom/domreg.pyc matches /usr/lib/python2.5/xml/ dom/domreg.py import xml.dom.domreg # precompiled from /usr/lib/python2.5/xml/dom/ domreg.pyc # /usr/lib/python2.5/xml/dom/minicompat.pyc matches /usr/lib/python2.5/ xml/dom/minicompat.py import xml.dom.minicompat # precompiled from /usr/lib/python2.5/xml/ dom/minicompat.pyc # /usr/lib/python2.5/xml/dom/minidom.pyc matches /usr/lib/python2.5/ xml/dom/minidom.py import xml.dom.minidom # precompiled from /usr/lib/python2.5/xml/dom/ minidom.pyc # /usr/lib/python2.5/xml/dom/xmlbuilder.pyc matches /usr/lib/python2.5/ xml/dom/xmlbuilder.py import xml.dom.xmlbuilder # precompiled from /usr/lib/python2.5/xml/ dom/xmlbuilder.pyc # /usr/lib/python2.5/copy.pyc matches /usr/lib/python2.5/copy.py import copy # precompiled from /usr/lib/python2.5/copy.pyc # /usr/lib/python2.5/xml/dom/NodeFilter.pyc matches /usr/lib/python2.5/ xml/dom/NodeFilter.py import xml.dom.NodeFilter # precompiled from /usr/lib/python2.5/xml/ dom/NodeFilter.pyc import xml.parsers # directory /usr/lib/python2.5/xml/parsers # /usr/lib/python2.5/xml/parsers/__init__.pyc matches /usr/lib/ python2.5/xml/parsers/__init__.py import xml.parsers # precompiled from /usr/lib/python2.5/xml/parsers/ __init__.pyc # /usr/lib/python2.5/xml/parsers/expat.pyc matches /usr/lib/python2.5/ xml/parsers/expat.py import xml.parsers.expat # precompiled from /usr/lib/python2.5/xml/ parsers/expat.pyc dlopen("/usr/lib/python2.5/lib-dynload/pyexpat.so", 2); import pyexpat # dynamically loaded from /usr/lib/python2.5/lib- dynload/pyexpat.so # /usr/lib/python2.5/site-packages/problem_report.pyc matches /usr/lib/ python2.5/site-packages/problem_report.py import problem_report # precompiled from /usr/lib/python2.5/site- packages/problem_report.pyc dlopen("/usr/lib/python2.5/lib-dynload/zlib.so", 2); import zlib # dynamically loaded from /usr/lib/python2.5/lib-dynload/ zlib.so # /usr/lib/python2.5/base64.pyc matches /usr/lib/python2.5/base64.py import base64 # precompiled from /usr/lib/python2.5/base64.pyc # /usr/lib/python2.5/gzip.pyc matches /usr/lib/python2.5/gzip.py import gzip # precompiled from /usr/lib/python2.5/gzip.pyc import email # directory /usr/lib/python2.5/email # /usr/lib/python2.5/email/__init__.pyc matches /usr/lib/python2.5/ email/__init__.py import email # precompiled from /usr/lib/python2.5/email/__init__.pyc import email.mime # directory /usr/lib/python2.5/email/mime # /usr/lib/python2.5/email/mime/__init__.pyc matches /usr/lib/ python2.5/email/mime/__init__.py import email.mime # precompiled from /usr/lib/python2.5/email/mime/ __init__.pyc # /usr/lib/python2.5/email/encoders.pyc matches /usr/lib/python2.5/ email/encoders.py import email.encoders # precompiled from /usr/lib/python2.5/email/ encoders.pyc # /usr/lib/python2.5/quopri.pyc matches /usr/lib/python2.5/quopri.py import quopri # precompiled from /usr/lib/python2.5/quopri.pyc # /usr/lib/python2.5/email/mime/multipart.pyc matches /usr/lib/ python2.5/email/mime/multipart.py import email.mime.multipart # precompiled from /usr/lib/python2.5/ email/mime/multipart.pyc # /usr/lib/python2.5/email/mime/base.pyc matches /usr/lib/python2.5/ email/mime/base.py import email.mime.base # precompiled from /usr/lib/python2.5/email/ mime/base.pyc # /usr/lib/python2.5/email/message.pyc matches /usr/lib/python2.5/ email/message.py import email.message # precompiled from /usr/lib/python2.5/email/ message.pyc # /usr/lib/python2.5/uu.pyc matches /usr/lib/python2.5/uu.py import uu # precompiled from /usr/lib/python2.5/uu.pyc # /usr/lib/python2.5/email/charset.pyc matches /usr/lib/python2.5/ email/charset.py import email.charset # precompiled from /usr/lib/python2.5/email/ charset.pyc # /usr/lib/python2.5/email/base64mime.pyc matches /usr/lib/python2.5/ email/base64mime.py import email.base64mime # precompiled from /usr/lib/python2.5/email/ base64mime.pyc # /usr/lib/python2.5/email/utils.pyc matches /usr/lib/python2.5/email/ utils.py import email.utils # precompiled from /usr/lib/python2.5/email/ utils.pyc # /usr/lib/python2.5/email/_parseaddr.pyc matches /usr/lib/python2.5/ email/_parseaddr.py import email._parseaddr # precompiled from /usr/lib/python2.5/email/ _parseaddr.pyc # /usr/lib/python2.5/email/quoprimime.pyc matches /usr/lib/python2.5/ email/quoprimime.py import email.quoprimime # precompiled from /usr/lib/python2.5/email/ quoprimime.pyc # /usr/lib/python2.5/email/errors.pyc matches /usr/lib/python2.5/email/ errors.py import email.errors # precompiled from /usr/lib/python2.5/email/ errors.pyc # /usr/lib/python2.5/email/iterators.pyc matches /usr/lib/python2.5/ email/iterators.py import email.iterators # precompiled from /usr/lib/python2.5/email/ iterators.pyc # /usr/lib/python2.5/email/mime/text.pyc matches /usr/lib/python2.5/ email/mime/text.py import email.mime.text # precompiled from /usr/lib/python2.5/email/ mime/text.pyc # /usr/lib/python2.5/email/mime/nonmultipart.pyc matches /usr/lib/ python2.5/email/mime/nonmultipart.py import email.mime.nonmultipart # precompiled from /usr/lib/python2.5/ email/mime/nonmultipart.pyc # /usr/lib/python2.5/unittest.pyc matches /usr/lib/python2.5/ unittest.py import unittest # precompiled from /usr/lib/python2.5/unittest.pyc # /usr/lib/python2.5/site-packages/apport/fileutils.pyc matches /usr/ lib/python2.5/site-packages/apport/fileutils.py import apport.fileutils # precompiled from /usr/lib/python2.5/site- packages/apport/fileutils.pyc # /usr/lib/python2.5/site-packages/apport/packaging_impl.pyc matches / usr/lib/python2.5/site-packages/apport/packaging_impl.py import apport.packaging_impl # precompiled from /usr/lib/python2.5/ site-packages/apport/packaging_impl.pyc import apt # directory /usr/lib/python2.5/site-packages/apt # /usr/lib/python2.5/site-packages/apt/__init__.pyc matches /usr/lib/ python2.5/site-packages/apt/__init__.py import apt # precompiled from /usr/lib/python2.5/site-packages/apt/ __init__.pyc dlopen("/usr/lib/python2.5/site-packages/apt_pkg.so", 2); import apt_pkg # dynamically loaded from /usr/lib/python2.5/site- packages/apt_pkg.so # /usr/lib/python2.5/site-packages/apt/package.pyc matches /usr/lib/ python2.5/site-packages/apt/package.py import apt.package # precompiled from /usr/lib/python2.5/site-packages/ apt/package.pyc # /usr/lib/python2.5/gettext.pyc matches /usr/lib/python2.5/gettext.py import gettext # precompiled from /usr/lib/python2.5/gettext.pyc # /usr/lib/python2.5/locale.pyc matches /usr/lib/python2.5/locale.py import locale # precompiled from /usr/lib/python2.5/locale.pyc dlopen("/usr/lib/python2.5/lib-dynload/_locale.so", 2); import _locale # dynamically loaded from /usr/lib/python2.5/lib- dynload/_locale.so dlopen("/usr/lib/python2.5/lib-dynload/operator.so", 2); import operator # dynamically loaded from /usr/lib/python2.5/lib- dynload/operator.so # /usr/lib/python2.5/site-packages/apt/cache.pyc matches /usr/lib/ python2.5/site-packages/apt/cache.py import apt.cache # precompiled from /usr/lib/python2.5/site-packages/ apt/cache.pyc # /usr/lib/python2.5/site-packages/apt/progress.pyc matches /usr/lib/ python2.5/site-packages/apt/progress.py import apt.progress # precompiled from /usr/lib/python2.5/site- packages/apt/progress.pyc # /usr/lib/python2.5/site-packages/apt/cdrom.pyc matches /usr/lib/ python2.5/site-packages/apt/cdrom.py import apt.cdrom # precompiled from /usr/lib/python2.5/site-packages/ apt/cdrom.pyc # /usr/lib/python2.5/site-packages/apport/packaging.pyc matches /usr/ lib/python2.5/site-packages/apport/packaging.py import apport.packaging # precompiled from /usr/lib/python2.5/site- packages/apport/packaging.pyc # /usr/lib/python2.5/shutil.pyc matches /usr/lib/python2.5/shutil.py import shutil # precompiled from /usr/lib/python2.5/shutil.pyc Traceback (most recent call last): File "", line 1, in NameError: name 'doerror' is not defined >>> xml Traceback (most recent call last): File "", line 1, in NameError: name 'xml' is not defined >>> import xml >>> xml.dom >>> import email >>> email.mime >>> exit() # clear __builtin__._ # clear sys.path # clear sys.argv # clear sys.ps1 # clear sys.ps2 # clear sys.exitfunc # clear sys.exc_type # clear sys.exc_value # clear sys.exc_traceback # clear sys.last_type # clear sys.last_value # clear sys.last_traceback # clear sys.path_hooks # clear sys.path_importer_cache # clear sys.meta_path # restore sys.stdin # restore sys.stdout # restore sys.stderr # cleanup __main__ # cleanup[1] apport # cleanup[1] zipimport # cleanup[1] quopri # cleanup[1] cStringIO # cleanup[1] apport.report # cleanup[1] math # cleanup[1] exceptions # cleanup[1] _locale # cleanup[1] sre_constants # cleanup[1] _codecs # cleanup[1] pwd # cleanup[1] _struct # cleanup[1] _types # cleanup[1] posix # cleanup[1] site # cleanup[1] problem_report # cleanup[1] pyexpat # cleanup[1] strop # cleanup[1] grp # cleanup[1] readline # cleanup[1] sitecustomize # cleanup[1] apport.packaging # cleanup[1] urlparse # cleanup[1] gzip # cleanup[1] signal # cleanup[1] apport.packaging_impl # cleanup[1] zlib # cleanup[1] apport.fileutils # cleanup[1] atexit # cleanup[1] unittest # cleanup[1] apport_python_hook # cleanup[1] shutil # cleanup[1] glob # cleanup[1] subprocess # cleanup[1] gc # cleanup[1] tempfile # cleanup[1] thread # cleanup[1] traceback # cleanup[1] fnmatch # cleanup[1] pickle # cleanup[1] marshal # cleanup[2] email.iterators # cleanup[2] random # cleanup[2] types # cleanup[2] email.mime # cleanup[2] xml # cleanup[2] struct # cleanup[2] base64 # cleanup[2] apt.cache # cleanup[2] pyexpat.errors # cleanup[2] apt_pkg # cleanup[2] encodings.utf_8 # cleanup[2] email.quoprimime # cleanup[2] email.mime.text # cleanup[2] email.encoders # cleanup[2] pyexpat.model # cleanup[2] locale # cleanup[2] email.charset # cleanup[2] xml.parsers.expat # cleanup[2] encodings # cleanup[2] urllib # cleanup[2] re # cleanup[2] email.mime.base # cleanup[2] email.errors # cleanup[2] email # cleanup[2] fcntl # cleanup[2] apt.progress # cleanup[2] UserDict # cleanup[2] codecs # cleanup[2] xml.dom.domreg # cleanup[2] socket # cleanup[2] xml.dom.xmlbuilder # cleanup[2] os # cleanup[2] _sre # cleanup[2] xml.parsers # cleanup[2] operator # cleanup[2] select # cleanup[2] posixpath # cleanup[2] errno # cleanup[2] _socket # cleanup[2] binascii # cleanup[2] email._parseaddr # cleanup[2] os.path # cleanup[2] apt.package # cleanup[2] xml.dom.NodeFilter # cleanup[2] email.utils # cleanup[2] copy # cleanup[2] apt.cdrom # cleanup[2] uu # cleanup[2] xml.dom.minidom # cleanup[2] apt # cleanup[2] encodings.aliases # cleanup[2] sre_parse # cleanup[2] copy_reg # cleanup[2] sre_compile # cleanup[2] _random # cleanup[2] email.message # cleanup[2] string # cleanup[2] email.mime.nonmultipart # cleanup[2] gettext # cleanup[2] xml.dom.minicompat # cleanup[2] stat # cleanup[2] _ssl # cleanup[2] warnings # cleanup[2] xml.dom # cleanup[2] email.base64mime # cleanup[2] email.mime.multipart # cleanup[2] linecache # cleanup[2] time # cleanup sys # cleanup __builtin__ # cleanup ints: 58 unfreed ints in 7 out of 17 blocks # cleanup floats: 33 unfreed floats in 2 out of 3 blocks 44,46c44 < >>> be_nice = 100 < >>> doerror < import apport # directory /usr/lib/python2.5/site-packages/apport --- > >>> >>> import apport # directory /usr/lib/python2.5/site-packages/apport 217,218c215 < >>> xml < Traceback (most recent call last): --- > >>> Traceback (most recent call last): 221,228c218,220 < >>> import xml < >>> xml.dom < < >>> import email < >>> email.mime < < >>> exit() < # clear __builtin__._ --- > >>> >>> > >>> >>> > >>> # clear __builtin__._ DIFF TO RAW TRANSCRIPT 44,46c44 < >>> be_nice = 100 < >>> doerror < import apport # directory /usr/lib/python2.5/site-packages/apport --- > >>> >>> import apport # directory /usr/lib/python2.5/site-packages/apport 217,218c215 < >>> xml < Traceback (most recent call last): --- > >>> Traceback (most recent call last): 221,228c218,220 < >>> import xml < >>> xml.dom < < >>> import email < >>> email.mime < < >>> exit() < # clear __builtin__._ --- > >>> >>> > >>> >>> > >>> # clear __builtin__._ From workitharder at gmail.com Fri Jul 25 17:08:01 2008 From: workitharder at gmail.com (bukzor) Date: Fri, 25 Jul 2008 14:08:01 -0700 (PDT) Subject: Easier way to get the "here" path? Message-ID: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> I have to go into these convulsions to get the directory that the script is in whenever I need to use relative paths. I was wondering if you guys have a better way: from os.path import dirname, realpath, abspath here = dirname(realpath(abspath(__file__.rstrip("c")))) In particular, this takes care of the case of symlinked, compiled scripts, which is fairly common at my workplace, and I imagine in many *nix evironments. An illustration: $echo "print __file__" > symlinks/path.py $ln -s symlinks/path.py $python >>> import path path.py >>> reload(path) path.pyc >>> path.__file__ 'path.pyc' >>> path.__file__.rstrip("c") 'path.py' >>> from os.path import abspath, realpath >>> realpath(path.__file__.rstrip("c")) '/home/bgolemon/python/symlinks/path.py' >>> realpath(abspath(path.__file__.rstrip("c"))) '/home/bgolemon/python/symlinks/symlinks/path.py' From aahz at pythoncraft.com Wed Jul 23 18:25:56 2008 From: aahz at pythoncraft.com (Aahz) Date: 23 Jul 2008 15:25:56 -0700 Subject: software engineering foundations? References: Message-ID: In article , wrote: > >There are software construction skills which are entirely distinct from the >language in which you are programming. We can tout object-oriented, >structured programming, test-driven development or other software >engineering techniques, but there is a body of knowledge out there which is >orthogonal to the language in which the code is written. People who are not >professional programmers often lack those skills and their code shows it. > >Are there any good online resources for this "software structure" axis? While this doesn't really directly address your question, I think that anyone who wants to do serious programming of any sort really should read _The Mythical Man-Month_ by Fred Brooks -- make sure to get the 25th anniversary edition. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From desothier at yahoo.com Thu Jul 17 04:30:47 2008 From: desothier at yahoo.com (antar2) Date: Thu, 17 Jul 2008 01:30:47 -0700 (PDT) Subject: common elements between list of lists and lists Message-ID: <2724c6f8-d75d-4fc2-ac8f-310f4f622aae@p25g2000hsf.googlegroups.com> Hello, I am a beginner in python. following program prints the second element in list of lists 4 for the first elements in list 4 that are common with the elements in list 5 list4 = [['1', 'a'],['4', 'd'],['8', 'g']] list5 = ['1', '2', '3'] for j in list4: for k in list5: if j[0] == k: print j[1] Result: a I would like to do the same thing starting with following lists, where the numbers in list 5 are without ''. Is there a way to convert integers in a list to integers in '' ? This is based on a situation where I want to find common numbers between a list and a list of lists where the numbers in the list are without '' and the numbers in the list of lists are with '' list4 = [['1', 'a'],['4', 'd'],['8', 'g']] list5 = [1, 2, 3] This might be a stupid question, but anyway, thanks for your answer It is not my first post on this site. In some way it is not possible to react on the messages that I receive to thank the persons that react. Anyway, thanks a lot From larry.bates at websafe.com` Tue Jul 15 10:21:29 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 09:21:29 -0500 Subject: logging via SocketHandler and TCPserver In-Reply-To: References: <81929250-449b-4686-acf3-dcc0095e341a@d1g2000hsg.googlegroups.com> Message-ID: Vinay Sajip wrote: > On Jul 14, 11:16 pm, Larry Bates wrote: >> Vinay, >> >> Thanks for your detailed explanation, but IMHO your suggested solution is almost >> the opposite (right idea wrong direction) of what I'm looking for. Hypothetical >> setup: >> >> application1 - SocketHandlerloggingturned on >> application2 - SocketHandlerloggingturned on >> application3 - SocketHandlerloggingturned on >> . >> . >> . >> applicationN >> >> monitoring app - ThreadingTCPServer target that Allows user to connect to ANY >> running application and to view the real-time log messages. After monitoring, >> it should be able to disconnect and connect to another application... The >> clients (application1..N) never stop sending and don't ever send anything short >> to disconnect themselves from the monitoring application. The disconnect/ >> reconnect is done at the monitoring app end based on input from the user. I >> think each one would beloggingto a different port, but I never really quite >> got that far. Perhaps there is some other way that I'm missing. It seems like >> this is something that might be able to be "generalized" into a robust >> monitoring application for an arbitrary number of asynchronously running >> applications. >> >> Each application's real-time log might be reached by clicking on a tab, menu, etc. > > Here's how I see it: the socket server listens, and receives logging > events from numerous applications in real time. If the server is > configured to monitor app1, then it quietly discards (or doesn't show > in the UI) all events from other apps - it only collects/shows events > from app1. When you click on a tab/menu/whatever to switch to > monitoring app2, then this information is used to tell the server to > discard (or not show) events from all apps except app2. You would of > course need to ensure the communication between UI thread and server > thread were done in a thread-safe manner. > >> As to the difficulty, I might just have a mental block but two modules that I've >> had a real hard time getting my mind wrapped around is yourLoggingand Twisted. >> They both have a multitude of options/ways to be used and not very many working >> examples to work from. Might be a chance to make some money on a book. If it >> was full of examples, I'd purchase it. >> > > But there are numerous examples in the logging docs - the script you > quoted as having put together after several hours of Googling is > pretty much the same as the (working) version in the logging docs! If > you have reviewed the logging docs and find them lacking examples, > please provide more detail about the kind of examples you think are > missing. And I can't speak for Twisted, but it does a lot more than > logging - and I don't think there's enough complexity in Python > logging to warrant a paid-for book. (No doubt people will tell me if > they disagree!) > > Best regards, > > Vinay Sajip Can multiple applications send SocketHandler logging records to the same socket server on the same port simultaneously? If so, then I understand your answer completely and will go in that direction. I guess I was trying to not use up bandwidth/CPU cycles on the applications that weren't being actively monitored by just not having the socket server connected to them. I think you may be a 'little to close' to the (excellent) application you have written to understand the steep learning curve that I see. You know the saying, "Brain surgery is easy to a brain surgeon". I should point out that I'm no newbie. I've used PIL, ReportLab, BeautifulSoup, Mechanize, Win32 extensions, ElementTree and a whole host of other modules with less difficulty. Please don't take this as anything more than an observation on my part. From what I see, you have written (and generously donated) an extremely powerful library and it is greatly appreciated. It is most likely just me. As far as the book is concerned, I guess I'd purchase the only copy ;-). I do appreciate your help very much. Regards, Larry From tjreedy at udel.edu Tue Jul 29 16:47:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 16:47:31 -0400 Subject: Python: SPREE HELP (willing to pay someone) In-Reply-To: <25fb9200-9be5-456f-b711-804a830b3297@m44g2000hsc.googlegroups.com> References: <25fb9200-9be5-456f-b711-804a830b3297@m44g2000hsc.googlegroups.com> Message-ID: TGD101 wrote: > I need someone who is able to install SPREE an open source program > see: http://www.askspree.de/ > > HOWEVER, here is the catch: It is on WINDOWS, but my server has > PYTHON..is there a miracle out there? If so please let me know what I > can do? Thank you. Since the site's 'Open Source' link to http:/project/askspree.de/ is dead, meaning there seems to be nothing to download and install, and since the question makes no sense, I cannot help but wonder if this is spam meant to drive traffic to the site. From dullrich at sprynet.com Thu Jul 10 12:12:15 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 10 Jul 2008 11:12:15 -0500 Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: In article <02ff4326-7b07-4ae6-8607-f58ea61802ef at z72g2000hsb.googlegroups.com>, ssecorp wrote: > I am never redefining the or reassigning the list when using validate > but since it spits the modified list back out that somehow means that > the modified list is part of the environment and not the old one. > i thought what happend inside a function stays inside a function > meaning what comes out is independent of what comes in. > Meaning if I want the list I send as a parameter to the function I > have to do x = func(x) and not just func(x) and x is magically what > comes out of func(). A function cannot modify the value of a global variable (unless it specifies "global"). It doesn't reassign anything. But in the functions below you're not reassigning a variable, you're _modifiying_ an object. A function _can_ modify an object you pass to it: >>> def DoesntReassign(x): ... x = 0 ... >>> def Modifies(x): ... x.append(0) ... >>> x=42 >>> DoesntReassign(x) >>> x 42 >>> x=[] >>> Modifies(x) >>> x [0] Hmm, look at this: >>> x=[] >>> id(x) 404296 >>> Modifies(x) >>> x [0] >>> id(x) 404296 'x' refers to exactly the same object before and after the call to Modifies. The function has _modified_ that object, but it hasn't redefined or reassigned anything. > Doesnt Python have closure or that isnt what this is about? > > > def validate(placed): > student = round(random.random()*401) > if student in placed: > return validate(placed) > else: > placed.append(student) > return student, placed > > def val(placed): > student = round(random.random()*401) > if student in placed: > return validate(placed) > else: > placed.append(student) > return student > > > > >>> g = lambda x:validate(x) > >>> l=[] > >>> for x in range(1,10): > g(l) > > > (141.0, [141.0]) > (19.0, [141.0, 19.0]) > (86.0, [141.0, 19.0, 86.0]) > (120.0, [141.0, 19.0, 86.0, 120.0]) > (76.0, [141.0, 19.0, 86.0, 120.0, 76.0]) > (262.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0]) > (234.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0]) > (74.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0]) > (325.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0, 325.0]) > >>> g = lambda x:val(x) > >>> l=[] > >>> for x in range(1,10): > g(l) > > > 183.0 > 33.0 > 315.0 > 244.0 > 308.0 > 168.0 > 146.0 > 378.0 > 297.0 > >>> -- David C. Ullrich From bj_666 at gmx.net Fri Jul 18 17:18:05 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Jul 2008 21:18:05 GMT Subject: __del__ methods References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> <6ec859F67cpfU5@mid.uni-berlin.de> <17b5febd-602d-4d7e-9449-6cabf4d95e41@27g2000hsf.googlegroups.com> Message-ID: <6ecfkdF67cpfU7@mid.uni-berlin.de> On Fri, 18 Jul 2008 12:26:35 -0700, Jason Baker wrote: > I don't necessarily need deterministic cleanup. And I plan on doing > something like a close() method as well. But I'd just like to make > sure nothing slips between the cracks. :) `__del__()` isn't guaranteed to be called *at all*, so can't make sure nothing slips between the cracks with it. Ciao, Marc 'BlackJack' Rintsch From bearophileHUGS at lycos.com Sat Jul 12 18:02:39 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 12 Jul 2008 15:02:39 -0700 (PDT) Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> Message-ID: Giampaolo Rodola': > Even if I avoid to re-heapify() it seems that the first element > returned by heappop() is always the smaller one. Yes, the heappop() function keeps the heap invariant, so it will keep giving you the smallest item. > I'd like to understand if there are cases where > deleting or moving an element of the heap, causes heappop() to return > an element which is not the smallest one. To be an heap it must keep its heap invariant true. The heap functions keep that invariant. Generally any time you move/delete an item yourself, you break the invariant, so you don't have an heap anymore and you need to re-heapify to restore the heap invariant :-) Bye, bearophile From hancock.robert at gmail.com Tue Jul 8 11:01:21 2008 From: hancock.robert at gmail.com (Robert Hancock) Date: Tue, 8 Jul 2008 08:01:21 -0700 (PDT) Subject: Relative Package Import Message-ID: mypackage/ __init__.py push/ __init__.py dest.py feed/ __init__py subject.py In subject.py I have from ..push import dest But i receive the error: Caught exception importing module subject: File "/usr/local/python/lib/python2.5/site-packages/pychecker/ checker.py", line 621, in setupMainCode() module = imp.load_module(self.moduleName, file, filename, smt) File "subject.py", line 1, in () from ..feed import dest ValueError: Attempted relative import in non-package What am I missing? From moijes12 at gmail.com Fri Jul 11 06:51:30 2008 From: moijes12 at gmail.com (moijes12) Date: Fri, 11 Jul 2008 03:51:30 -0700 (PDT) Subject: importing .dll in a python file References: <4dfaeb7b-8e7e-4f0b-80a8-ed24ed1c46d3@x35g2000hsb.googlegroups.com> Message-ID: <93f12156-e36e-41d4-9c37-524f5488e120@f36g2000hsa.googlegroups.com> On Jul 11, 2:09?pm, Tim Golden wrote: > moijes12 wrote: > > I need to use a .dll from a python script.I have installed pywin.But > > in the program ,which is like: > > > import dllName > > > I get : > > > Import Error : DLL not found > > > Please suggest a solution! > > Well, the short answer is: use the ctypes module. > > The longer answer is: read around the subject a > bit before you expect Python to import an arbitrary > DLL and then give up when it doesn't :) > > TJG Thanks a lot Tim. moijes12 From steve at REMOVE-THIS-cybersource.com.au Sat Jul 12 10:06:09 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 12 Jul 2008 09:06:09 -0500 Subject: Using the Random Module. References: Message-ID: On Fri, 11 Jul 2008 12:27:32 -0700, castironpi wrote: > You want a random integer. Is there a range you want it in? > > Past a certain point, you'll exceed the granularity of the random number > generator, and some values in the range will never be generated. You might want to produce an unbounded random integer, where *every* integer has a chance to be returned: def unbounded_randint(): i = 0 while True: if random.random() < 0.5: return i i += 1 This returns 0 with probability 1/2, 1 with probability 1/4, 2 with probability 1/8, etc. The probability distribution is centered close to zero (the mode and median are both zero, and I'm too lazy to calculate the mean) and it has an infinitely long tail. -- Steven From tjreedy at udel.edu Sun Jul 27 02:20:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 02:20:30 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87k5f88h2d.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f88h2d.fsf@physik.rwth-aachen.de> Message-ID: Torsten Bronger wrote: > No more than Python 3.0 breaks. This proposal would break 3.0 code without sufficient reason. From crazychimp132 at gmail.com Mon Jul 14 23:21:37 2008 From: crazychimp132 at gmail.com (crazychimp132 at gmail.com) Date: Mon, 14 Jul 2008 20:21:37 -0700 (PDT) Subject: Method behavior for user-created class instances References: <42433fcd-fcdc-4f42-a427-c28241734b7c@z66g2000hsc.googlegroups.com> Message-ID: On Jul 14, 9:04 pm, Larry Bates wrote: > crazychimp... at gmail.com wrote: > > Greetings. > > > I am looking for a way to achieve method behavior for a class I > > created. That is, it has a __call__ method, so can be called like a > > function. But I also want it to be treated as a method when it appears > > in a class body. > > > Eg. > > > class foo: > > def __call__(self, inst): pass > > > class bar: > > meth = foo() > > > such that bar().meth() will not raise an exception for too few > > arguments (because the inst argument in foo.__call__ is implicitly set > > to the bar instance). I know this has to do with writing the __get__ > > method of foo, but I am wondering if there is perhaps some class I can > > just inherit from to get the proper __get__, which behaves identically > > to that of regular Python functions. The need for this arises out of > > the implementation of a function decorator as a class. > > > Thanks. > > While it is not clear "why" you would want this, I believe this works. > If not, take a look at staticmethods or classmethods, they might work for you. > > >>> class foo(object): > ... def __call__(self, inst): > ... print "foo.__call__", inst > ... > > >>> class bar: > ... def __init__(self): > ... self.foo = foo() > ... self.meth = self.foo.__call__ > ... > >>> b = bar() > >>> b.meth(1) > foo.__call__ 1 > > -Larry This doesn't work for me. I have a class which is used to decorate functions, returning a callable object in the place of the original function. So, instances of this class must be able to be used anywhere a function would be used, and this means getting method behavior when it is used in a class body. A working implementation would be (in 3.0): from functools import partial from abc import ABCMeta, abstractmethod class method_behavior(metaclass = ABCMeta): def __get__(self, instance, owner): if instance is None: return self.__call__ return partial(self.__call__, instance) @abstractmethod def __call__(): pass Then, any decorator class can inherit from it: class foo(method_behavior): def __init__(self, func): self.func = func def __call__(self, *args, **kwds): print("calling decorated func") return self.func(*args, **kwds) Then, we can decorate a function with foo (via @foo) and it will work either inside a class body or outside, it works everywhere an undecorated function would work, eg.: @foo def bar(): print('bar') class baz: @foo def bar(self): print('bar') What I am asking is whether there is a way to directly inherit method behavior, instead of inexactly rewriting it as I did in method_behavior.__get__(). From martin at v.loewis.de Thu Jul 24 16:21:49 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 24 Jul 2008 22:21:49 +0200 Subject: Undocumented Python 2.6 change: Py_None vs NULL when C implementation raises exception In-Reply-To: References: <4887b13a$0$7677$9b622d9e@news.freenet.de> Message-ID: <4888E45D.7030406@v.loewis.de> > I have no plans to track down the exact change in Python code that > caused this. There does not seem to be much point, since according to > Fredrik this seems to be an area that is practically undefined and the > M2Crypto code was clearly buggy. I see, and I agree with Fredrik's analysis. It might actually be that there was *no* change in 2.6 causing this change in behavior, but just a difference in data returned in the actual application. E.g. if a PyInt_FromLong returns -1, the caller also needs to check for PyErr_Occurred, which would then detect an earlier exception. So it might be that if you have -1 in your data, you see the exception, but if you have -2 instead, you won't see it. Regards, Martin From bruno.desthuilliers at gmail.com Thu Jul 17 08:03:27 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 17 Jul 2008 05:03:27 -0700 (PDT) Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> Message-ID: On 16 juil, 10:35, Stefan Scholl wrote: > Dave U. Random wrote: > > >http://snipr.com/PracticalDjango > > June 2008 is a bit too early. Django isn't ready. Oh, really ? Too bad. But, wait... If Django isn't ready, what's that framework I've been using for almost three years now, then ??? From marcus at internetnowasp.net Mon Jul 28 13:57:27 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Tue, 29 Jul 2008 01:57:27 +0800 Subject: Module clarification In-Reply-To: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> Message-ID: <488E0887.6070803@internetnowasp.net> Hi Hussein, Basically a module is a FILE and is considered as a singleton model. Yes ur wow.py assumption is correct. I recommend getting Mark Lutz Learning Python book to get you started. Marcus.CM Hussein B wrote: > Hi. > I'm a Java guy and I'm playing around Python these days... > In Java, we organize our classes into packages and then jarring the > packages into JAR files. > What are modules in Python? > What is the equivalent of modules in Java? > Please correct me if I'm wrong: > I saved my Python code under the file Wow.py > Wow.py is now a module and I can use it in other Python code: > import Wow > > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > > From larry.bates at websafe.com` Sun Jul 27 22:17:22 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 27 Jul 2008 21:17:22 -0500 Subject: write unsigned integer 32 bits to socket In-Reply-To: References: Message-ID: rkmr.em at gmail.com wrote: > On Sun, Jul 27, 2008 at 7:01 PM, Larry Bates wrote: >> rkmr.em at gmail.com wrote: >>> i want to send unsigned 32 bit integer to socket, and looking for >>> something equivalent to this method... >>> http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt() >>> >>> is there such method / library available in python?! >> You will need to use struct module to build the 4 byte value and then send >> it. >> >> Something like (not tested): >> >> import struct >> us32bit = struct.pack("I", value) >> s.send(us32bit) > > thanks a lot!!! > > just to make sure if I want 32 bit or 4 bytes then should I use the > short or integer or long? > > this is short >>>> struct.pack('!h',3) > '\x00\x03' > > this is integer >>>> struct.pack('!i',3) > '\x00\x00\x00\x03' > > this is long >>>> struct.pack('!l',3) > '\x00\x00\x00\x03' Short is 16 bits, Integer is 32 bits, long is 64 bits (as I read and have found). -Larry From bearophileHUGS at lycos.com Wed Jul 30 14:35:26 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 30 Jul 2008 11:35:26 -0700 (PDT) Subject: Native Code vs. Python code for modules References: <4890aeb6$0$17192$742ec2ed@news.sonic.net> Message-ID: John Nagle: > Personally, I think the Shed Skin approach > is more promising. ShedSkin will probably have scaling problems: as the program size grows it may need too much time to infer all the types. The author has the strict policy of refusing any kind of type annotation, this make it unpractical. And, despite your interest in ShedSkin, so far very few people have given a hand actually developing SS (I think partially because ShedSkin Python sources aren't much hackable. This is very bad for an OpenSource project), so I think the author now has lost part of the will to develop this project (but probably we'll see one of two more versions). For me so far the most viable way to produce a faster Python system seems a version of CPython with Cython and something Psyco-like built- in (and a built-in compiler on Windows, like MinGW 4.2.1), maybe with some syntax support in the Python language, allowing to mix statically compiled Python code with dynamically compiled Python code in an easy way (as CLisp sometimes does). Bye, bearophile From mva.led at gmail.com Fri Jul 4 11:53:43 2008 From: mva.led at gmail.com (Manuel Vazquez Acosta) Date: Fri, 04 Jul 2008 11:53:43 -0400 Subject: A fix for OverflowError in 64bits platforms In-Reply-To: References: <486CE046.6080104@gmail.com> Message-ID: <486E4787.8090006@gmail.com> Terry Reedy wrote: > Manuel Vazquez Acosta wrote: >> Hi all, >> >> I'm debugging a Plone site in an AMD64 laptop. When I first tried to run >> Zope, I got this exception: > > In general, versions numbers for both Python and the app are helpful. > Python 2.4.5, Plone 2.5.5, Zope 2.9.8final >> OverflowError: signed integer is greater than maximum >> >> In the archives I encounter no solutions. > > Archives: Python? Zope? Plone? The three of them ;) > >> This is what I could find, so I share with you all: > > I hope you have/will report this to the appropriate place. > Well, not sure where to report to. According to your last comment, is an Archetypes' bug, isn't it? So it's best to report it there. >> >> I think the docstring should be appended with a "Note: On 64bits >> platform this raises an OverflowError blah blah..." > > Better to fix it ;-) Ok. Best regards, Manuel. From tom.machinski at gmail.com Mon Jul 21 19:22:15 2008 From: tom.machinski at gmail.com (Tom Machinski) Date: Mon, 21 Jul 2008 16:22:15 -0700 Subject: Python Written in C? In-Reply-To: References: Message-ID: On Mon, Jul 21, 2008 at 3:53 PM, DaveM wrote: > On Mon, 21 Jul 2008 03:18:01 +0200, Michiel Overtoom > wrote: > > > >Many major text/word processing programs (Emacs, vi, MS-Word) are also > >written in C. > > I thought Emacs was written in Lisp. Large parts of Emacs are indeed implemented in Emacs Lisp. There's are some core functions implemented in C. MS-Word, afaik, had very substantial parts written in Visual Basic. Tom > DaveM > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dp_pearce at hotmail.com Tue Jul 15 12:27:49 2008 From: dp_pearce at hotmail.com (dp_pearce) Date: Tue, 15 Jul 2008 09:27:49 -0700 (PDT) Subject: Zipping files References: Message-ID: <9400be29-9c00-4868-91a9-ae82ebfc6364@56g2000hsm.googlegroups.com> When I saw "Permission denied", this was my suspicion. And I think you are very right. I have just gone back and tried writing to a file outside of C:, in this case C:/output/, and it seems to work again. Would I be right in guessing there is no way around this? Dan From Lie.1296 at gmail.com Sun Jul 27 05:08:00 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 27 Jul 2008 02:08:00 -0700 (PDT) Subject: xml.dom's weirdness? References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> <1c837e71-a191-4495-8ec8-0126003ba9c6@n33g2000pri.googlegroups.com> <488C3645.8060304@behnel.de> Message-ID: On Jul 27, 3:48?pm, Stefan Behnel wrote: > Lie wrote: > > Question: Is there a way to list loaded modules, including those that > > aren't in my namespace? > > such as sys.modules? > > Modules are not unloaded automatically just because you do not use them > yourselves. I'm not surprised of that. > If the module is imported for whatever reason by whatever other > module, it stays alive until it's no longer referenced (including the > reference in sys.modules). I'm more concerned about the number of modules imported by making an error (from 30 on the startup to 187) and the side-effect of making an error, which makes modules such as xml.*/email.* that previously doesn't exist get imported out of the blue... this makes the effect that made me start the thread, a "command" that while getting NameError in the first call, gets a modules found on subsequent call, just because the Error Handler loaded it for you. I'm even more concerned by a few modules that got imported because of making the error, several of them isn't something that should be used by Error Handler (e.g. email.*, apt (seems to be related to Ubuntu's package manager of the same name), etc) I'm also concerned in that why Error handling is on python's level instead of built-in. PS: These concerns are based on the assumption that the offender is the "Error Handler", which I haven't proven completely, yet is the strongest candidate on why this odd behavior comes to be. From robert.kern at gmail.com Thu Jul 24 17:19:56 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 24 Jul 2008 16:19:56 -0500 Subject: need help with introducing more traffic In-Reply-To: References: <632875.28836.qm@web51808.mail.re2.yahoo.com> <6es0m9F8mehmU1@mid.uni-berlin.de> Message-ID: Fredrik Lundh wrote: > (when do we get the ability to edit our c.l.python messages for, say, 30 > minutes after they're posted? ;-) The IETF is waiting to borrow Guido's time machine for study before releasing the RFC for NNTTP (Network News Time Travel Protocol). Of course, if you have you get to borrow Guido's time machine, too, you can already comment on the RFC before the C's were R'ed. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ndbecker2 at gmail.com Thu Jul 10 11:10:33 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 10 Jul 2008 11:10:33 -0400 Subject: profiling question Message-ID: Just to confirm, the profiling numbers (from cProfile) do include time spent inside my own C functions that I import as modules? From circularfunc at gmail.com Tue Jul 22 02:15:32 2008 From: circularfunc at gmail.com (ssecorp) Date: Mon, 21 Jul 2008 23:15:32 -0700 (PDT) Subject: tail-rec decorator, well still blows the stack... References: Message-ID: <0c591e89-23ec-45ef-981f-a7927090f8cf@79g2000hsk.googlegroups.com> thanks i already have perfect iterative versions of fibonacci. def fib(n): a, b = 1, 0 while n: a, b, n = b, a+b, n-1 return b I know the example is not the way to write pythonic code, I was just learning about decorators and then I saw this example and tried it out. but thanks now i understand why it didn't work. From sri_annauni at yahoo.co.in Thu Jul 3 04:23:08 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Thu, 3 Jul 2008 13:53:08 +0530 (IST) Subject: How to pickle bound methods Message-ID: <248375.61171.qm@web7905.mail.in.yahoo.com> No. It does not work. def make_staticmethod(inst, methodname): ??? return getattr(inst, methodname) def pickle_function(method): ??? return make_staticmethod, (method.im_self, method.im_func.__name__) copy_reg.pickle(new.function, pickle_function, make_staticmethod) ----- Original Message ---- From: Peter Otten <__peter__ at web.de> To: python-list at python.org Sent: Thursday, 3 July, 2008 12:13:45 PM Subject: Re: How to pickle bound methods srinivasan srinivas wrote: Please don't top-post. > Could you please explain?the code breifly?? I am not getting what it does. >> import copy_reg >> import new >> >> def make_instancemethod(inst, methodname): >> ? ? return getattr(inst, methodname) >> >> def pickle_instancemethod(method): >> ? ? return make_instancemethod, (method.im_self, method.im_func.__name__) >> >> copy_reg.pickle(new.instancemethod, pickle_instancemethod, >> make_instancemethod) If you have a type that cannot be pickled because it is implemented in C you can make it "picklable" by registering it with the copy_reg.pickle() function. This function takes three arguments: 1 the type (here: new.instancemethod) 2 a function that takes an instance of the type. This returns a factory function and a tuple of the arguments this factory function needs to recreate the instance. 3 the factory function. In short the following must work, and out_method should do the same thing as in_method: factory, args = pickle_instancemethod(in_method) out_method = factory(*args) Now to your other problem, pickling static methods. The type of a static method is just new.function, the same as that of a global function. Global functions are already picklable, so the copy_reg mechanism doesn't kick in. Peter -- http://mail.python.org/mailman/listinfo/python-list Unlimited freedom, unlimited storage. Get it now, on http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/ From castironpi at gmail.com Fri Jul 18 02:26:24 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 17 Jul 2008 23:26:24 -0700 (PDT) Subject: storing references instead of copies in a dictionary References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: <7c26ca26-be96-4e8c-8eb5-e43bd78e4e70@v21g2000pro.googlegroups.com> On Jul 17, 7:36?pm, bgeddy wrote: > bgeddy wrote: > > castironpi wrote: > >> On Jul 17, 10:05 am, mk wrote: > >>>> def f2(arg): > >>>> ? ? return "f2 "+arg > >>>> def f1(arg): > >>>> ? ? return "f1 "+arg > >>>> a={"1":"f1","2":"f2"} > >>>> print [eval(x[1])(x[0]) for x in a.items()] > >>>> def f2(arg): > >>>> ? ? return "New f2 "+arg > >>>> print [eval(x[1])(x[0]) for x in a.items()] > >>> Neat trick, if probably dangerous in some circumstances. Anyway, thanks, > >>> I didn't think of that. > > >>>> Don't know if this is any use to you.. > >>> At least I learned something. :-) > > >> You want consistent access to a changing variable. ?Wrap it in an > >> object: > > >>>>> a= Blank( ) > >>>>> a.ref= 'X' > >>>>> a.ref > >> 'X' > >>>>> b= a > >>>>> b.ref > >> 'X' > >>>>> a.ref= 'Y' > >>>>> b.ref > >> 'Y' > > > My "old fashioned" programing paradigms think of this in terms of > > "pointers", a throw back to my schooling in 'C'. I find this general > > form of problem to be common across languages and in some ways hard to > > express in python. The whole idea of labels bound to objects is quite > > alien to traditional terminology. I find one of the main attractions of > > python is this new mindset that the language makes you adopt - a > > different set of tools are at hand for the old school programmer. > > > castironpi - please give an example of what you are thinking as I find > > this interesting. preferably post some brief example code. > > castironpi ?- please forgive the double post but my newsreader didn't > display your code correctly.. Doh !! Anyway - a nice way of addressing > the problem. However the OP's post revolved around having a rewritable > set of "labels" - which could be recorded at one time and when re > referenced the new definitions of those labels would be used. For > example a "collection" (list,dictionary,tuple) could be made of these > "labels" and then the underlying code accessed by the labels changed. If > the code was now ran indirectly by referencing the list then the new > code would be ran. These building blocks are how parsers are built and > the basis of language. > I can see how you form two ways of addressing the variable but can't > figure how this fits the original problem. Please elaborate for my > ignorance. > > EdH. In the OP's post, we have: def f1(): print 'f1' def f2(): print 'f2' funs= [ f1, f2 ] def f1(): print 'new f1' They wanted funs[ 0 ] to contain this new function / new definition too. Another language might permit: def funs[ 0 ](): print 'new f1' Python allows: def f1(): print 'new f1' funs[ 0 ]= f1 and @rebind( funs, 0 ) def f1(): print 'new f1' and @rebind_named( funs, 'funA' ) def f1(): print 'new f1' in the case funs was a dictionary or class or class instance. Functions remain to be first class objects; their definition syntax is merely restricted over normal assignments. To access "whatever 'f1' is pointing to right now", the only way is with eval, which you showed. Spealman's solution can accomplish redefinition, but only provided calling signature and closure, among others, don't change. If they do, you have to reassign those, too, and possibly more: >>> dir( f ) [snip] 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name' Roughly the same in 3.0. It's an option. > These building blocks are how parsers are built and > the basis of language. To address this, I observe altered references are easy for computers. Suppose: #--NOT PYTHON-- def f1(): print 'f1' 008902 f1: 0x008934 def f1(): print 'new f1' 008902 f1: 0x008938 'f1()' calls the function the address of which is stored at 008902 in each case: f1 (at 008934) in the first case, and new f1 (at 008938) in the second. Python eliminates that combination from the syntax, which strengthens object-name identity, at the cost of a slightly longer workaround (a.ref= f1) for keeping names but changing objects. In this sense, the only 'pointer' per se is the string name of an object, scoped by a namespace-- eval( 'f1', spaceA ). I delicately ask for an example in natural language and daily life in which we change what object a name refers to, or hold that Python conforms to natural language better than computer-native mutable pointers and references. From robert.rawlins at thinkbluemedia.co.uk Thu Jul 17 12:01:46 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 17 Jul 2008 17:01:46 +0100 Subject: Unusual Exception Behaviour In-Reply-To: References: <22681.110565509$1216308418@news.gmane.org> Message-ID: <004601c8e826$6a848490$3f8d8db0$@rawlins@thinkbluemedia.co.uk> Hi Mk, > Why not capture exceptions themselves to a log file? > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466332 Thanks for the reply mate, I appreciate you getting back to me so quickly. I certainly like that implementation for logging the exceptions, however, at the moment I don't even know where the exceptions are occurring, or what type they are, could I still use this method to log any and all exceptions raised in the application? I'm a little confused as to how I can modify that implementation to do so. Robert From misceverything at gmail.com Wed Jul 23 19:28:36 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Wed, 23 Jul 2008 16:28:36 -0700 (PDT) Subject: Web Server References: Message-ID: Thanks, guys..I think I am going to go the route Fredrik suggested. Thanks for all your help! From ggpolo at gmail.com Wed Jul 23 11:07:33 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 23 Jul 2008 12:07:33 -0300 Subject: Doubt In-Reply-To: References: Message-ID: On Wed, Jul 23, 2008 at 11:51 AM, ???????? wrote: > Friends > > I am a Perl programmer new to Python. I have a small doubt. > How to convert the perl notation > $a = ""; expression in Python ? a = "" > > How to represent the loop > for ($a = $b; $a<=$c;$a++){ > } in Python > for a in range(b, c + 1): pass > Jagan > Linguist > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From wtanksleyjr at gmail.com Mon Jul 28 19:42:46 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Mon, 28 Jul 2008 16:42:46 -0700 (PDT) Subject: Python parsing iTunes XML/COM Message-ID: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> I'm trying to convert the URLs contained in iTunes' XML file into a form comparable with the filenames returned by iTunes' COM interface. I'm writing a podcast sorter in Python; I'm using iTunes under Windows right now. iTunes' COM provides most of my data input and all of my mp3/aac editing capabilities; the one thing I can't access through COM is the Release Date, which is my primary sorting field. So I read everything in through COM, then read all the release dates from the iTunes XML file, then try to join the two together... But so far I have zero success. Is there _any_ way to match up tracks between iTunes COM and iTunes XML? I've spent far too much effort on this. I'm not stuck on using filenames, if that's a bad idea... But I haven't found anything else that works, and filenames seem like an obvious solution. -Wm From gh at ghaering.de Fri Jul 11 08:39:11 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 11 Jul 2008 14:39:11 +0200 Subject: How to serialize and deserialize the objects into memory? In-Reply-To: <0a7ead85-2a38-41a8-98b8-59dede61f985@c58g2000hsc.googlegroups.com> References: <0a7ead85-2a38-41a8-98b8-59dede61f985@c58g2000hsc.googlegroups.com> Message-ID: hardemr wrote: > Hello Everyone, > > I want to serialize and deserialize the objects into Memory not into > file. How can i do that? You want to serialize the objects, but only keep them in memory? That hardly makes any sense. Serialization is need if you want to store your objects in a file or if you want to communicate (via network) with other processes. -- Gerhard From bignose+hates-spam at benfinney.id.au Mon Jul 7 20:43:54 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 08 Jul 2008 10:43:54 +1000 Subject: Python Agile Software Development Tools Screencasts References: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> <87lk0dwbys.fsf@benfinney.id.au> Message-ID: <87hcb1w6gl.fsf@benfinney.id.au> Robert Kern writes: > Ben Finney wrote: > > percious writes: > > > >> I started a new series about python on showmedo. Please feel free > >> to take a look. > > > > I'd love to, but showmedo refuses to show presentations to me > > without installing non-free software. > > mplayer works just fine on the .flv's. Note that "works with mplayer" is not the same thing as "doesn't require non-free software"; many "works with mplayer" stories have the unspoken addendum of "... with these non-free codec libraries installed". But, not having the video files, I can't say whether that's the case in this instance. Okay. Where would the public link to those files be? If I need to "log in" just to download it, that's a needless barrier that's going to turn me away too. -- \ ?Don't worry about people stealing your ideas. If your ideas | `\ are any good, you'll have to ram them down people's throats.? | _o__) ?Howard Aiken | Ben Finney From mathieu.prevot at ens.fr Mon Jul 7 16:53:47 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Mon, 7 Jul 2008 22:53:47 +0200 Subject: do a sed / awk filter with python tools (at least as fast) In-Reply-To: References: Message-ID: <3e473cc60807071353t2b4c4c98pf01faeae244a7f60@mail.gmail.com> 2008/7/7 Peter Otten <__peter__ at web.de>: > Mathieu Prevot wrote: > >> I use in a bourne shell script the following filter: >> >> sed '/watch?v=/! d;s/.*v=//;s/\(.\{11\}\).*/\1/' \ >> | sort | uniq | awk 'ORS=" "{print $1}' >> >> that give me all sets of 11 characters that follows the "watch?v=" >> motif. I would like to do it in python on stdout from a >> subprocess.Popen instance, using python tools rather than sed awk etc. >> How can I do this ? Can I expect something as fast ? > > You should either do it in Python , e. g.: > > def process(lines): > candidates = (line.rstrip().partition("/watch?v=") for line in lines) > matches = (c[:11] for a, b, c in candidates if len(c) >= 11) > print " ".join(sorted(set(matches))) > > if __name__ == "__main__": > import sys > process(sys.stdin) > > or invoke your shell script via subprocess.Popen(). Invoking a python script > via subprocess doesn't make sense IMHO. :) Thanks. Mathieu From grante at visi.com Mon Jul 21 23:47:30 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 21 Jul 2008 22:47:30 -0500 Subject: Python Written in C? References: Message-ID: On 2008-07-22, Larry Bates wrote: > You talk about "writing it in assembly language for each MPU > chip". Actually it is even better than that. We now have > these modern inventions, called compilers that do that type of > work for us. They translate high level instructions, not > into assembler but into machine language. Actually, all of the compilers I'm familiar with (gcc and a handful of cross compilers for various microprocessors) translate from high-level languages (e.g. C, C++) into assembly, which is then assembled into relocatable object files, which are then linked/loaded to produce machine language. -- Grant Edwards grante Yow! "DARK SHADOWS" at is on!! Hey, I think visi.com the VAMPIRE forgot his UMBRELLA!! From dmitrey.kroshko at scipy.org Mon Jul 21 07:26:03 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Mon, 21 Jul 2008 04:26:03 -0700 (PDT) Subject: Genetic programming: pygene, pygp, AST, or (gasp) Lisp? References: <7bfb3c41-b08b-49dc-9711-6e39a4667db2@b1g2000hsg.googlegroups.com> Message-ID: <1ccf224d-096e-4afa-8bed-fce077e7f359@c65g2000hsa.googlegroups.com> also, you could look at the simple openopt example provided by GA "galileo" solver (connected to OO framework) http://projects.scipy.org/scipy/scikits/browser/trunk/openopt/scikits/openopt/examples/glp_1.py http://scipy.org/scipy/scikits/wiki/GLP Regards, D From alexnbryan at gmail.com Fri Jul 11 23:46:02 2008 From: alexnbryan at gmail.com (Alexnb) Date: Fri, 11 Jul 2008 20:46:02 -0700 (PDT) Subject: Help with using findAll() in BeautifulSoup Message-ID: <18415792.post@talk.nabble.com> Okay, I am not sure if there is a better way of doing this than findAll() but that is how I am doing it right now. I am making an app that screen scapes dictionary.com for definitions. However, I would like to have the type of the word for each definition. For example if def1 and def2 are noun defintions but def3 isn't: noun def1 def2 verb def3 Something like that. Now I can get the definitions just fine. But the problem comes when I want to get the type. I can get the types, but I don't know for what definitions they go with. So I can get noun and verb, but for all I know noun is def1, and verb is 2 and 3. I am wondering if there is a way to use findAll() but like stop once it hits a certain thing, or a way to do just that. for example, if I have noun
verb
I want to be able to do like findAll('span', {'class': 'pg'}), but tell me how many
things are after it, or before the next so I know how many defintions it has. Here is the code I am using(I used "cheese" because that is kinda my test word for everything in the app.): import urllib from BeautifulSoup import BeautifulSoup class defWord: def __init__(self, word): self.word = word def get_types(term): soup = BeautifulSoup(urllib.urlopen('http://dictionary.reference.com/search?q=%s' % term)) for tabs in soup.findAll('span', {'class': 'pg'}): yield tabs.contents[0].string self.mainList = list(get_types(self.word)) print self.mainList type = defWord("cheese") I don't know if this is really something anyone can help me fix or if I have to do it on my own. But I would love some help. -- View this message in context: http://www.nabble.com/Help-with-using-findAll%28%29-in-BeautifulSoup-tp18415792p18415792.html Sent from the Python - python-list mailing list archive at Nabble.com. From no-spam at no-spam-no-spam.invalid Sun Jul 6 10:42:04 2008 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sun, 06 Jul 2008 16:42:04 +0200 Subject: Hands-on HTML Table Parser/Matrix? In-Reply-To: References: Message-ID: Tim Cook wrote: > > On Sun, 2008-07-06 at 14:40 +0200, robert wrote: >> Often I want to extract some web table contents. Formats are >> mostly static, simple text & numbers in it, other tags to be >> stripped off. So a simple & fast approach would be ok. >> >> What of the different modules around is most easy to use, stable, >> up-to-date, iterator access or best matrix-access (without need >> for callback functions,classes.. for basic tasks)? >> > There are couple of HTML examples using Pyparsing here: > > http://pyparsing.wikispaces.com/Examples > > hm - nothing special with HTML tables. Meanwhile: I dislike "ClientTable" (file centric, too much parsing errors in real world). "TableParse" works. Very simple&fast 70-liner regexp->matrix and strip/clean/HTML-entities conversion. Fast success hands-on. Doesn't separate nested tables and such complexities consciously - but works though for simple hands-on tasks in real world. Robert From rocky at panix.com Thu Jul 10 14:52:42 2008 From: rocky at panix.com (R. Bernstein) Date: Thu, 10 Jul 2008 14:52:42 -0400 Subject: handling unexpected exceptions in pdb References: Message-ID: Simon Bierbaum writes: > Hi all, > > I'm in an interactive session in pdb, debugging my code using > pdb.runcall. Somewhere, an exception is raised and lands uncaught on > stdout. Is there any way of picking up this exception and at least > read the full message, or even accessing its stack trace to determine > where exactly within the one line I just executed it was raised? This > is where I'm stuck: > >> /usr/local/apache2/bin/Model/Database.py(287)disconnect() > (Pdb) n > FlushError: FlushErr...perly.",) >> /usr/local/apache2/bin/Model/Database.py(287)disconnect() > (Pdb) import sys > (Pdb) sys.last_traceback > *** AttributeError: 'module' object has no attribute 'last_traceback' > > Thanks, Simon I think basically you want runcall to be wrapped in a try block. So in pdb.py instead of: def runcall(*args, **kwds): return Pdb().runcall(*args, **kwds) Change with: def runcall(*args, **kwds): p=Pdb() try: return p.runcall(*args, **kwds) except: traceback.print_exc() print "Uncaught exception. Entering post mortem debugging" t = sys.exc_info()[2] p.interaction(t.tb_frame,t) print "Post mortem debugger finished." return None Code like this appears near the bottom of the pdb.py file. If that works, you may want to file a bug Python report to change pdb. Also note that one may want to do the same thing on run() and runeval() But also if this does what you want, please file a feature request to pydb: http://sourceforge.net/tracker/?func=add&group_id=61395&atid=497162 and I'll probably make it happen in the next release. This is the first time I've heard of anyone using runcall. From code at pizzashack.org Mon Jul 21 12:50:25 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 21 Jul 2008 12:50:25 -0400 Subject: Change PC to Win or Windows In-Reply-To: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> Message-ID: <20080721165025.GC8793@dragontoe.org> On Sat, Jul 19, 2008 at 02:56:07AM -0700, Lie wrote: > government, etc. IBM PC is one of the first computers that ordinary > people could possess, when IBM-clones appeared on the market, they're > referred as PCs too because they are Personal Computer, a computer > that is designed for personal use. Just to be clear, this statement is WRONG. PC-clones were so called because they were clones of the IBM-PC. The term is very specific to IBM-compatible hardware. http://en.wikipedia.org/wiki/Pc_clone IBM PC compatible computers are those generally similar to the original IBM PC, XT, and AT. Such computers used to be referred to as PC clones, or IBM clones since they almost exactly duplicated all the significant features of the PC, XT, or AT internal design, facilitated by various manufacturers' ability to legally reverse engineer the BIOS through cleanroom design. Wikipedia's article on the personal computer accurately reflects the multiple meanings of the term, and points out the common usage to mean a Windows box: http://en.wikipedia.org/wiki/Personal_computer Today a PC may be a desktop computer, a laptop computer or a tablet computer. The most common operating systems are Microsoft Windows, Mac OS X and Linux, while the most common microprocessors are x86 compatible CPUs. However, the term "PC" is often used only to refer to computers running Microsoft Windows. So please stop your whining and get used to the idea that THE REST OF THE WORLD uses PC to mean a Windows box. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From basti.wiesner at gmx.net Fri Jul 25 14:55:18 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Fri, 25 Jul 2008 20:55:18 +0200 Subject: Python program as daemon? References: <8bb6bd1a-cd85-4b7a-8fc9-844f3794bca0@c58g2000hsc.googlegroups.com> Message-ID: Johny : > Is it possible to run a Python program as daemon? You can write daemons in basically any language out there. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From stef.mientki at gmail.com Thu Jul 17 07:00:03 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 17 Jul 2008 13:00:03 +0200 Subject: Babelfish translation ... Message-ID: <487F2633.6000703@gmail.com> hello, I've build a translation tool, to translate all strings in a python source file. As a extra gadget I added translation through Babel Fish, using beautifulsoup. Although it works functionally, it can take lots of time waiting for the translation. What I basically do is, after selecting a new string to be translated: kwds = { 'trtext' : line_to_be_translated, 'lp' :'en_nl'} soup = BeautifulSoup (urlopen(url, urlencode ( kwds ) ) ) translation= soup.find ( 'div', style='padding:0.6em;' ).string self.Editor_Babel.SetLabel ( translation ) I'm using Python 2.5 and wxPython. Probably I should use a separate thread, but that's above my knowledge. I could also use a timer to check at regualr intervals when the translation is ready, but I've no idea how to implement that with the above code. thanks, Stef Mientki From matthieu.brucher at gmail.com Tue Jul 8 17:03:28 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Tue, 8 Jul 2008 23:03:28 +0200 Subject: sage vs enthought for sci computing In-Reply-To: <48729fe9$0$7550$9b4e6d93@newsspool1.arcor-online.net> References: <677e7819-e09e-43d3-8368-5864f91002be@34g2000hsh.googlegroups.com> <48729fe9$0$7550$9b4e6d93@newsspool1.arcor-online.net> Message-ID: 2008/7/8 three3q : > Hi, > >>> If my goal >>> is to replace matlab (we do signal processing and stats on >>> physiological data, with a lot of visualization), would sage or >>> enthought get me going quicker? > Pylab. Not a good idea, as pylab will be replaced by pyplot which only contains plot commands. The remaining will be left to numpy, and pylab does not have the same functions as numpy. My answer would be like Stuart's: a mix of Python, numpy, scipy and whatever scikit or additional numpy module I need, with ipython. That's if I want to do scientific computation. Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher From phillip.oldham at gmail.com Thu Jul 10 05:24:04 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Thu, 10 Jul 2008 02:24:04 -0700 (PDT) Subject: FOSS projects exhibiting clean/good OOP? References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> Message-ID: <1fdb9220-4ddd-4633-b5bd-91fbfc91453d@z66g2000hsc.googlegroups.com> On Jul 9, 9:26 pm, "bruno.desthuilli... at gmail.com" wrote: > This is somewhat subjective... Some would say that Python's object > model is fundamentally broken and crappy (not MHO, needless to say) > that Python + "solid OO principles" is antinomic !-) Really? Would you happen to be able to provide any further information on that? From deets at nospam.web.de Thu Jul 3 12:01:15 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 03 Jul 2008 18:01:15 +0200 Subject: site-packages, unzipepd there but import fails References: Message-ID: <6d4bfmFp3aoU1@mid.uni-berlin.de> defn noob wrote: > i unzipped and put the folder in site-packages. when i run setup.py > install nothing happens. Don't do that. Remove it from there. Put it somewhere else (temp), and use $ python setup.py install Look into site-packages afterwards, and see if it got placed there. Diez From michele.simionato at gmail.com Sat Jul 12 00:00:06 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 11 Jul 2008 21:00:06 -0700 (PDT) Subject: decorator to prevent adding attributes to class? References: <98c6e83e-4a54-49ce-a32e-f03f5ab97f28@k13g2000hse.googlegroups.com> <48778CA2.2000402@jouy.inra.fr> Message-ID: On Jul 11, 9:24?pm, Neal Becker wrote: > Robert Bossy wrote: > > class Foo(Freezeable): > > def __init__(self): > > self.bar = 42 > > self.freeze() # ok, we set all variables, no more from here > > > x = Foo() > > print x.bar > > x.bar = -42 > > print x.bar > > x.baz = "OMG! A typo!" > > Pretty nice, but unfortunately the subclass has to remember to call freeze > in it's init. ?Too bad that can't be automated. It can with a metaclass redefining the __call__ method to call freeze after instantation. But there would a lot of magic going on such a design. From desothier at yahoo.com Wed Jul 23 11:33:57 2008 From: desothier at yahoo.com (antar2) Date: Wed, 23 Jul 2008 08:33:57 -0700 (PDT) Subject: concatenate the elements in each list of a list of lists Message-ID: <72c425b7-d9c2-4a61-8b7f-075eae14e703@x41g2000hsb.googlegroups.com> I already asked a similar question, but encounter problems with python... How can I concatenate the elements in each list of a list of lists list_of_listsA = [['klas*', '*', '*'], ['mooi*', '*', '*', '*'], ['arm*', '*', '*(haar)']] wanted result: list_of_listsA = [['klas* * *'] ['mooi* * * *'] ['arm* * *(haar)']] Thanks a lot ! From basti.wiesner at gmx.net Sat Jul 12 10:16:28 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sat, 12 Jul 2008 16:16:28 +0200 Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> Message-ID: Gabriel Genellina : > En Fri, 11 Jul 2008 15:42:37 -0300, Keith Hughitt > escribi?: > >> I am having a little trouble figuring out how to convert a python >> datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would >> like to create a UTC date so that when I send it to MySQL (which >> treats all dates at local dates by default), it will already have >> incorporated the proper UTC offset. I've tried looking through the >> docs http://python.active-venture.com/lib/datetime-datetime.html), but >> have not had any luck. > > You have to use a "timezone aware" datetime object. If all you want is to > store an UTC date, the tzinfo demo classes that you can find in the Python > docs at may be enough. > A more complete implementation is at The python-dateutil package also provide classes to deal with timezone-aware datetime objects. See -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From Nikolaus at rath.org Sun Jul 27 03:56:43 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Sun, 27 Jul 2008 09:56:43 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> <87ljzpt3lv.fsf@nokile.rath.org> Message-ID: <871w1fu5dw.fsf@nokile.rath.org> Terry Reedy writes: >> What he wants is to write >> > > > class foo: >> def bar(arg): >> self.whatever = arg + 1 >> >> instead of >> >> class foo: >> def bar(self, arg) >> self.whatever = arg + 1 >> >> so 'self' should *automatically* only be inserted in the function >> declaration, and *manually* be typed for attributes. > > which means making 'self' a keyword just so it can be omitted. Silly > and pernicious. Well, I guess that's more a matter of personal preference. I would go for it immediately (and also try rename it to '@' at the same time). Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From bignose+hates-spam at benfinney.id.au Sat Jul 26 21:34:45 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 27 Jul 2008 11:34:45 +1000 Subject: binding names doesn't affect the bound objects References: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> <8763qtmgo7.fsf@benfinney.id.au> Message-ID: <87od4kkt3e.fsf@benfinney.id.au> "D'Arcy J.M. Cain" writes: > Hmm. Are you saying that the following doesn't work? > > $ python > >>> f = open("test", "w") > >>> import sys > >>> sys.stdout = f > >>> print "test message" > >>> sys.exit(0) > $ cat test > test message > > > In other words, you can't change the object used by the 'print' > > statement only by re-binding names (which is *all* that is done by > > the '=' operator). > > Apparently I can. I admit to not trying any of the above. I was explaining the behaviour reported by the original poster, without experimenting to see if I could reproduce the behaviour. Thanks for being more diligent. -- \ ?All persons, living and dead, are purely coincidental.? | `\ ?_Timequake_, Kurt Vonnegut | _o__) | Ben Finney From wtanksleyjr at gmail.com Wed Jul 30 10:58:36 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Wed, 30 Jul 2008 07:58:36 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> Message-ID: <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Thank you for the response. Here's some more info, including a little that you didn't ask me for but which might be useful. John Machin wrote: > william tanksley wrote: > > To ask another way: how do I convert from a file:// URL to a local > > path in a standard way, so that filepaths from two different sources > > will work the same way in a dictionary? > > The problems occur when the filenames have non-ascii characters in > > them -- I suspect that the URLs are having some encoding placed on > > them that Python's decoder doesn't know about. > # track_id = url2pathname(urlparse(track_id).path) > print repr(track_id) > parse_result = urlparse(track_id).path > print repr(parse_result) > track_id_replacement = url2pathname(parse_result) > print repr(track_id_replacement) The "important" value here is track_id_replacement; it contains the data that's throwing me. It appears that some UTF-8 characters are being read as multiple bytes by ElementTree rather than being decoded into Unicode. Could this be a bug in ElementTree's Unicode support? If so, can I work around it? Here's one example. The others are similar -- they have the same things that look like problems to me. "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" Note some problems here: 1. This isn't Unicode; it's missing the u"" (I printed using repr). 2. It's got the UTF-8 bytes there in the middle. I tried doing track_id.encode("utf-8"), but it doesn't seem to make any difference at all. Of course, my ultimate goal is to compare the track_id to the track_id I get from iTunes' COM interface, including hashing to the same value for dict lookups. > and copy/paste the results into your next posting. In addition to the above results, while trying to get more diagnostic printouts I got the following warning from Python: C:\projects\podcasts\podstrand\podcast.py:280: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal return track.databaseID == trackLocation The code that triggered this is as follows: if trackLocation in self.podcasts: track = self.podcasts[trackLocation] if trackRelease: track.release_date = trackRelease elif track.is_podcast: print "No release date:", repr(track.name) else: # For the sake of diagnostics, try to find the track. def track_has_location(track): return track.databaseID == trackLocation fillers = filter(track_has_location, self.fillers) if len(fillers): return disabled = filter(track_has_location, self.deferred) if len(disabled): return print "Location not known:", repr(trackLocation) -Wm From cheaplv at sina.com Fri Jul 18 01:35:52 2008 From: cheaplv at sina.com (cheaplv at sina.com) Date: Thu, 17 Jul 2008 22:35:52 -0700 (PDT) Subject: paypal wholesale men jordans 13 (paypal accept)(www goodsaler com Message-ID: <9436d005-27aa-4950-b184-c67a1c1fd78b@u12g2000prd.googlegroups.com> paypal wholesale men jordans (paypal accept)(www goodsaler com paypal wholesale men jordans 1 (paypal accept)(www goodsaler com paypal wholesale men jordans 2 (paypal accept)(www goodsaler com paypal wholesale men jordans 3 (paypal accept)(www goodsaler com paypal wholesale men jordans 4 (paypal accept)(www goodsaler com paypal wholesale men jordans 5 (paypal accept)(www goodsaler com paypal wholesale men jordans 6 (paypal accept)(www goodsaler com paypal wholesale men jordans 7 (paypal accept)(www goodsaler com paypal wholesale men jordans 8 (paypal accept)(www goodsaler com paypal wholesale men jordans 9 (paypal accept)(www goodsaler com paypal wholesale men jordans 10 (paypal accept)(www goodsaler com paypal wholesale men jordans 11 (paypal accept)(www goodsaler com paypal wholesale men jordans 12 (paypal accept)(www goodsaler com paypal wholesale men jordans 13 (paypal accept)(www goodsaler com paypal wholesale men jordans 14 (paypal accept)(www goodsaler com paypal wholesale men jordans 15 (paypal accept)(www goodsaler com paypal wholesale men jordans 16 (paypal accept)(www goodsaler com paypal wholesale men jordans 17 (paypal accept)(www goodsaler com paypal wholesale men jordans (paypal accept)(www goodsaler com paypal wholesale men jordans 1 (paypal accept)(www goodsaler com paypal wholesale men jordans 2 (paypal accept)(www goodsaler com paypal wholesale men jordans 3 (paypal accept)(www goodsaler com paypal wholesale men jordans 4 (paypal accept)(www goodsaler com paypal wholesale men jordans 5 (paypal accept)(www goodsaler com paypal wholesale men jordans 6 (paypal accept)(www goodsaler com paypal wholesale men jordans 7 (paypal accept)(www goodsaler com paypal wholesale men jordans 8 (paypal accept)(www goodsaler com paypal wholesale men jordans 9 (paypal accept)(www goodsaler com paypal wholesale men jordans 10 (paypal accept)(www goodsaler com paypal wholesale men jordans 11 (paypal accept)(www goodsaler com paypal wholesale men jordans 12 (paypal accept)(www goodsaler com paypal wholesale men jordans 13 (paypal accept)(www goodsaler com paypal wholesale men jordans 14 (paypal accept)(www goodsaler com paypal wholesale men jordans 15 (paypal accept)(www goodsaler com paypal wholesale men jordans 16 (paypal accept)(www goodsaler com paypal wholesale men jordans 17 (paypal accept)(www goodsaler com paypal wholesale men jordans (paypal accept)(www goodsaler com paypal wholesale men jordans 1 (paypal accept)(www goodsaler com paypal wholesale men jordans 2 (paypal accept)(www goodsaler com paypal wholesale men jordans 3 (paypal accept)(www goodsaler com paypal wholesale men jordans 4 (paypal accept)(www goodsaler com paypal wholesale men jordans 5 (paypal accept)(www goodsaler com paypal wholesale men jordans 6 (paypal accept)(www goodsaler com paypal wholesale men jordans 7 (paypal accept)(www goodsaler com paypal wholesale men jordans 8 (paypal accept)(www goodsaler com paypal wholesale men jordans 9 (paypal accept)(www goodsaler com paypal wholesale men jordans 10 (paypal accept)(www goodsaler com paypal wholesale men jordans 11 (paypal accept)(www goodsaler com paypal wholesale men jordans 12 (paypal accept)(www goodsaler com paypal wholesale men jordans 13 (paypal accept)(www goodsaler com paypal wholesale men jordans 14 (paypal accept)(www goodsaler com paypal wholesale men jordans 15 (paypal accept)(www goodsaler com paypal wholesale men jordans 16 (paypal accept)(www goodsaler com paypal wholesale men jordans 17 (paypal accept)(www goodsaler com From norseman at hughes.net Thu Jul 10 12:32:51 2008 From: norseman at hughes.net (norseman) Date: Thu, 10 Jul 2008 09:32:51 -0700 Subject: formatting list -> comma separated In-Reply-To: <48750e4f$0$15106$e4fe514c@dreader27.news.xs4all.nl> References: <48750e4f$0$15106$e4fe514c@dreader27.news.xs4all.nl> Message-ID: <487639B3.3020508@hughes.net> Robert wrote: > given d: > > d = ["soep", "reeds", "ook"] > > I want it to print like > > soep, reeds, ook > > I've come up with : > > print ("%s"+", %s"*(len(d)-1)) % tuple(d) > > but this fails for d = [] > > any (pythonic) options for this? > > Robert > > > > -- > http://mail.python.org/mailman/listinfo/python-list > ================================ the old fashion way would be: d = ["soep", "reeds", "ook"] if len(d) > 0: print ("%s"+", %s"*(len(d)-1)) % tuple(d) # if d= [] then print stmnt bypassed Steve norseman at hughes.net From sjmachin at lexicon.net Fri Jul 11 16:32:12 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 11 Jul 2008 13:32:12 -0700 (PDT) Subject: read file into list of lists References: <1388b868-aae9-4233-b3ec-a85ffc029283@56g2000hsm.googlegroups.com> Message-ID: On Jul 11, 11:35 pm, Paddy wrote: > On Jul 11, 2:15 pm, antar2 wrote: > > > > > Hello, > > > I can not find out how to read a file into a list of lists. I know how > > to split a text into a list > > > sentences = line.split(\n) > > > following text for example should be considered as a list of lists (3 > > columns and 3 rows), so that when I make the print statement list[0] > > [0], that the word pear appears > > > pear noun singular > > books nouns plural > > table noun singular > > > Can someone help me? > > > Thanks > > lofl = [line.strip().split() for line in the_opened_file] > >>> line = ' foo bar ' >>> line.strip().split() ['foo', 'bar'] >>> line.split() ['foo', 'bar'] From mattheww at chiark.greenend.org.uk Tue Jul 29 16:40:00 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 29 Jul 2008 21:40:00 +0100 (BST) Subject: Build tool for Python References: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Message-ID: Paul Boddie wrote: > I do understand that it can be awkward to work out which object files > need recompiling due to changes in source files, for example, and > that one doesn't want to see the logic involved reproduced all over > the place, but I do wonder whether the machinery around such matters > isn't sometimes more complicated in these tools as soon as one strays > outside the common cases. I think it often is. Tools like 'make' give you little declarative languages, and when things get a little bit complicated you end up wasting time working out how to fool it into doing what you want, when if only you could have direct access to its internals you could quite happily tell it explicitly. > It seems to me that some common build-related primitives implemented > as functions combined with plain Python would be a good enough > combination for a lot of tasks in this domain. I agree entirely; I've found this works well. I think there are three basic building blocks: - a way to invoke a compiler with suitable options (with some convenience support for describing project-wide default options and overriding them where appropriate); - a way to decide whether a file needs rebuilding (by comparing timestamps or stored hashes or whatever); - some kind of topological sort engine to work out what order to build things in. -M- From fredrik at pythonware.com Mon Jul 21 17:55:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 23:55:41 +0200 Subject: Importing different versions of a module In-Reply-To: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> References: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> Message-ID: mercado mercado wrote: > I have two versions of a script on my machine. One version is for new > development and the other version is a production version. This script > imports a module from a different directory, and this module again has > two versions (a development version and a production version). What I > want is for the development script to import the development module, and > the production script to import the production module, without making > any changes to the code in the script. if you already have two different versions of the script, what stops you from making changes to them? > For example, suppose the development script is in ~/dev/rss.py, and the > production script is in ~/prod/rss.py. I want the dev version to import > /usr/lib/python2.5/site-packages/lib_dev/parse.py, and the prod version > to import usr/lib/python2.5/site-packages/lib_prod/parse.py. cannot you just insert the appropriate directory in sys.path the first thing you do in the scripts? e.g. import os, sys lib = "lib_dev" # change this for prod/rss.py sys.path.insert(0, os.path.join( os.path.dirname(os.__file__), "site-packages", lib )) import parse # picks the right one From googler.1.webmaster at spamgourmet.com Tue Jul 22 02:43:07 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Mon, 21 Jul 2008 23:43:07 -0700 (PDT) Subject: Python Embedding Thread References: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> <87bf413d-eb98-47c0-8466-237c45fd1a0e@e53g2000hsa.googlegroups.com> Message-ID: <5081c3df-cb66-443b-ac71-be9661ae057d@27g2000hsf.googlegroups.com> Hi! Thank you very much for your answers. I have a menue with a script in it. So my app starts a new thread for each script. So I would like to run two scripts all the same time. Could someone give me a tip, what I have to set in my code? Thank you :) From rajanikanth at gmail.com Wed Jul 9 03:24:28 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Wed, 9 Jul 2008 00:24:28 -0700 Subject: Regular Expressions Quick Question In-Reply-To: References: Message-ID: <84bdef3c0807090024p3367981dq7e42ae0d4561ab81@mail.gmail.com> hi! Try this: >>> lis=['t','tes','test','testing'] >>> [elem for elem in lis if re.compile("^te").search(elem)] ['tes', 'test', 'testing'] Cheers, Raj On Wed, Jul 9, 2008 at 12:13 AM, Lamonte Harris wrote: > Alright, basically I have a list of words in a file and I load each word > from each line into the array. Then basically the question is how do I > check if the input word matches multiple words in the list. > > Say someone input "test", how could I check if that word matches these list > of words: > > test > testing > tested > > Out of the list of > > Hello > blah > example > test > ested > tested > testing > > I want it to loop then check if the input word I used starts any of the > words in the list so if I typed 'tes' > > Then: > > test > testing > testing > > would be appended to a new array. > > I'm unsure how to do this in python. > > Thanks in advanced. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From amdescombes at gmail.com Tue Jul 22 00:58:29 2008 From: amdescombes at gmail.com (AMD) Date: Tue, 22 Jul 2008 06:58:29 +0200 Subject: scanf in python In-Reply-To: References: <4884be5e$0$19722$426a74cc@news.free.fr> Message-ID: <488568f6$0$6120$426a74cc@news.free.fr> Robert Kern a ?crit : > AMD wrote: >> Hello, >> >> I often need to parse strings which contain a mix of characters, >> integers and floats, the C-language scanf function is very practical >> for this purpose. >> I've been looking for such a feature and I have been quite surprised >> to find that it has been discussed as far back as 2001 but never >> implemented. > > The second Google hit is a pure Python implementation of scanf. > > http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/ > Hi Robert, I had seen this pure python implementation, but it is not as fast or as elegant as would be an implementation written in C directly within python with no need for import. Cheers, Andr? From mccredie at gmail.com Tue Jul 22 11:27:07 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 22 Jul 2008 08:27:07 -0700 (PDT) Subject: Is this a valid use of 'import'? References: Message-ID: <3ed92b2e-a46f-41d9-a75c-c1ec74bb6137@f63g2000hsf.googlegroups.com> On Jul 22, 8:12?am, Frank Millman wrote: > Hi all > > I am familiar enough with the normal use of 'import'. However, I have > found a use for it which seems effective, but I have not seen it used > like this before, so I am not sure if there are any downsides. > > I know that when a module is imported the first time, it is > 'executed'. This normally entails setting up constants, classes, > functions, etc, that you want to make available to the importer. > > In this particular case, when it is executed, it does a whole lot > more. It reads in some parameters, establishes a socket connection, > starts a thread, and starts monitoring the socket using select.select. > It also exposes some functions that disguise the complexity of reading > from and writing to the socket. > > This enables me to write a 'client' program that look like this - > > --------------------------- > from Utils.client import * > > connect(userid='frank',pwd='') > cust = getRecord( > ? ? ? ? ? ? company='chagford',table='ArCustomers', > ? ? ? ? ? ? column='CustNo',value='A001') > print cust > close() > --------------------------- > > As you can see, it makes writing a client program very easy. > > Are there any problems with this approach? > > Frank Millman If it works for you that is great. That module however probably isn't very readable or easy to modify however. Also, you are hiding a lot of the complexity in a place where it isn't expected. Chances are it would be easy to do the same thing at the class level instead of the module level by putting all of that setup into the __init__ method of a class, which is the proper place to do that sort of thing. Making your code look something like this: from utils.client import Connection conn = Connection(userid='frank', pwd='') cust = conn.getRecord( company='chagford', table='ArCustomers', column='CustNo', value='A001' ) print cust conn.close() Without seeing your other code it is difficult to know what the issues might be. In general, this is what classes are for. Matt From fredrik at pythonware.com Thu Jul 24 11:42:46 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 17:42:46 +0200 Subject: need help with introducing more traffic In-Reply-To: <632875.28836.qm@web51808.mail.re2.yahoo.com> References: <632875.28836.qm@web51808.mail.re2.yahoo.com> Message-ID: leo davis skrev: > I found this code snippet(reference http://www.goldb.org) and wish to do > more with it than just send out a Http Get request.I would like to > introduce more traffic -say by downloading files,crawling through all > the links,logging in etc etc,and wish to see how the web server > reacts.I'm trying to stress the server to its limits....appreciate if > anyone could provide me code/ideas to inject into this. > the website -http://ftp.ruby-lang.org/pub/ruby/binaries/mswin32/ > selected as example has many downloads.i tried from urllib import umm. are you saying that you run ruby-lang.org and want to write a stress tester in Python just for the fun of it, or are we missing something here... From kasterma at bart-kastermanss-macbook.local Sun Jul 13 07:19:48 2008 From: kasterma at bart-kastermanss-macbook.local (Bart Kastermans) Date: Sun, 13 Jul 2008 06:19:48 -0500 Subject: Changing self: if self is a tree how to set to a different self References: <0101e32d-bba2-4821-aaf4-97944c9d8f3a@f63g2000hsf.googlegroups.com> Message-ID: Paul McGuire writes: > On Jul 12, 6:18?am, Bart Kastermans macbook.local> wrote: >> This uses the function: >> >> def NoneOr (tree, mem_function, *arguments): >> ? ? """ if tree is not None then tree.mem_function (arguments). """ >> ? ? if tree == None: >> ? ? ? ? return None >> ? ? else: >> ? ? ? ? return getattr (tree, mem_function) (*arguments) >> >> Bart > > First I want to say these comments are absolutely great. I *very* much appreciated getting them. This kind of analysis and thinking about code is exactly what I want to learn for myself; so this helped me a lot. From the many interesting thoughts I got from this there is only one that is a bit dissonant with me; it is the next paragraph. > This code reads wrongly to me on a couple of levels. First, I think > the general computing consensus is that if-then-else is more readable/ > logical if you assert the positive condition for the then-part, and > put the alternative condition in the else-part. My impression is that > the non-None-ness of tree is actually the positive assertion, as in: I had been experimenting with exactly this in some of my code. The choice seemed to be between (in the cases I had in front of me): 1) filter out the bad cases and deal with them, then have the code do the usual stuff, 2) set the conditions for being the usual case, then later deal with the bad stuff. I had been converging towards (1) as in def func (inputs): if inputs bad one way: deal with it if inputs bad another way: deal with it too take care of the generic remaining case case (2) would result in something like: def func (inputs): if inputs are not bad in any way: take care of the generic case elif in puts bad in one way: deal with it else: # bad in another way deal with it too Did I represent the case distinction as you had it in mind? I'll keep this more in mind when writing stuff and see how it works out. Better keep with "more readable", logically these are clearly equivalent. > > if tree != None: > return getattr(tree, mem_function)(*arguments) > else: > return None > > Next, the more Pythonic test for None-ness is most clearly written as: > > if tree is not None: > > as there is only one None, and the identity "is not" check is simpler/ > faster for Python to execute (and possibly - and more importantly - > also simpler for readers to follow, as this reads more like a > continuous sentence instead of a mixture of prose and mathematical > notations). > > One might even suggest you could further abbreviate this test to: > > if tree: > > and get the same behavior. I would quibble with that, however, that > this merely exploits a side-effect of Python, in which None values are > always False, and *most* non-None values are True. But Python also > interprets many non-None values as False, such as 0, or empty > containers, such as lists, tuples, dicts, and strings. In fact, your > tree class sounds like a structured container to me, and it would be > reasonable to assume that you might implement __nonzero__ (pre-Python > 2.6) or __bool__ (Python 2.6 and later) in your class to return False > for an empty tree, which would still be a valid and not-None tree. > You should be able to invoke methods on an empty tree just as one can > call "".upper(). So for this case, I would stick with the more > explicit "if tree is not None". > > Another Pythonicity is that methods will *always* return a value, even > if you do not write a return statement - and that value is None. So > if you assert the tree-not-None as the if condition, you don't even > need the else part. You could just write: > > def NoneOr (tree, mem_function, *arguments): > """ if tree is not None then tree.mem_function (arguments). > """ > if tree is not None: > return getattr(tree, mem_function)(*arguments) > > Surprisingly, this actually reads almost verbatim from your doc > string! So I would guess that this implementation is probably closest > to your original intent for this method. Still, for explicitness'- > sake, you might want to keep the else-part, just to make your intent > clear and spelled-out. (Complaining about the presence or absence of > this bit of code goes beyond "persnickety"...) > > > Note that the original code is perfectly valid Python, and will run > just as efficiently as any of my alternative suggestions, which is why > I enclosed my comments in 'persnickety' (http:// > dictionary.reference.com/browse/persnickety) tags. > > -- Paul From alokkat at gmail.com Thu Jul 3 18:18:35 2008 From: alokkat at gmail.com (Alok Kumar) Date: Thu, 3 Jul 2008 18:18:35 -0400 Subject: ImportError: No module named _md5 Message-ID: I am trying to move from python 2.4 to python 2.5.2. After compiling the python 2.5.2, I found it is throwing "ImportError: No module named _md5". I found this topic on the mailing list, but no solution to fix it. Can someone help me out. It will be highly appreciated. Regards Alok -------------- next part -------------- An HTML attachment was scrubbed... URL: From henning.vonbargen at arcor.de Tue Jul 29 03:00:43 2008 From: henning.vonbargen at arcor.de (henning.vonbargen at arcor.de) Date: Tue, 29 Jul 2008 00:00:43 -0700 (PDT) Subject: Importing different versions of a module References: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> <48811064.5010603@hughes.net> <8b51e78c0807181750x66fd0372y82367245630e921f@mail.gmail.com> <4884FC33.2090006@hughes.net> <8b51e78c0807221005k4ead9652i721a030c592273af@mail.gmail.com> Message-ID: Why not set up PYTHONPATH together with other environment variables in a shell script (bash, or CMD on Windows) and call that shell script instead of your Python script directly? This is probably the easiest and still a very powerful and generic solution for this kind of problem. We do it that way regardless of the programming language used. Henning From birdprince at gmail.com Tue Jul 29 03:19:20 2008 From: birdprince at gmail.com (birdprince at gmail.com) Date: Tue, 29 Jul 2008 00:19:20 -0700 (PDT) Subject: Python COM Message-ID: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> I have implemented a COM in C++,buy i don't know how to use this COM in python. For example: the COM's ProgID is "MyCOM1.AdvMethod".this COM have two interfaces,the default interface's name is IAdvMethod,the second interface's name is IBasicMethod. How do i use those interfaces in python.Thank you very much,please answer my question in code. From ethan at stoneleaf.us Tue Jul 8 18:54:37 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 08 Jul 2008 14:54:37 -0800 Subject: numeric emulation and __pos__ In-Reply-To: References: <92e3ea9f-5745-4072-9d09-7c14fd335828@f36g2000hsa.googlegroups.com> <4873A50C.5090003@stoneleaf.us> Message-ID: <4873F02D.5050600@stoneleaf.us> Terry Reedy wrote: > > > Ethan Furman wrote: > >> Anybody have an example of when the unary + actually does something? >> Besides the below Decimal example. I'm curious under what circumstances >> it would be useful for more than just completeness (although >> completeness for it's own sake is important, IMO). > > > All true operators and some built-in functions translate to special > method calls. > -x == x.__neg__() == type(x).__neg__(x) == x.__class__.__neg__(x) > > What should happen to '+x'? Raise SyntaxError? Ignore the '+'? Or > translate it to __pos__ in analogy with '-' and __neg__? Guido made the > third choice: partly for consistency perhaps, but also for the benefit > of user-written classes. Decimal started as user-contributed decimal.py. > > Does anything else use this hook? I don't know, but I do know that > there are periodic demands for *more* operators for user use. So I > expect it has been. > > tjr It definitely makes sense from that perspective. As I was reading the docs for numeric emulation I came across the unary + and wasn't sure what to make of it. I tried it out, and got exactly what I put in, for everything I tried. So I wondered if there were any situations where you would get something besides what you started with. Thanks to everyone for your comments and help. -- Ethan From alexnbryan at gmail.com Sat Jul 12 18:39:38 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sat, 12 Jul 2008 15:39:38 -0700 (PDT) Subject: like py2exe, but on a mac Message-ID: <18424336.post@talk.nabble.com> Hi All I am wondering what I can do to turn a python app (.py) into a mac OSX applicaiton (.app). Just like py2exe does. But I am also wondering since in your applications folder on macs it usually doesn't have an actual folder for each app. Rather an icon. so for firefox, you just see the icon. Unlike windows where you have a folder with everything, and the actual program is in it. where is all the application info stored? just in the .app? Finally whether or not there is an app like py2exe for mac, is there a way to skip the middle man and turn it straight into a .dmg with the app inside? -- View this message in context: http://www.nabble.com/like-py2exe%2C-but-on-a-mac-tp18424336p18424336.html Sent from the Python - python-list mailing list archive at Nabble.com. From larzluv at hotmail.com Fri Jul 18 14:43:57 2008 From: larzluv at hotmail.com (Larry Hale) Date: Fri, 18 Jul 2008 11:43:57 -0700 (PDT) Subject: Python Behind a Squid Corporate Proxy on Windows References: <7b541a3b-846f-496a-aee1-d5719217e011@m45g2000hsb.googlegroups.com> <821d7616-3faa-4dae-a988-18caf4f8598a@8g2000hse.googlegroups.com> <84c473ed-6993-481a-b789-35851242895b@f1g2000prb.googlegroups.com> Message-ID: Thank you so much for the reply, but alas: I get the same results. (urllib2 makes the initial request, Squid replies "Error 407: Proxy Authentication Required", which urllib2 dutifully fails on/raises said error...) I do appreciate your time, though! :) -Larry On Jul 18, 3:08?am, Chris wrote: > On Jul 17, 6:40?pm, Larry Hale wrote: > > > Err, the line above should be: > > > proxy_handler = urllib2.ProxyHandler( { "http": "http:// > > myusername:passw... at webfilter.xyz.local:3128" } ) > > > (Sorry! ?:) > > some old code I wrote to download public domain info for our company, > also through a squid proxy and this still works for me > > import urllib2, urllib > > proxy = urllib2.ProxyHandler({'http': 'http:// > username:password at proxy_url:proxy_port'}) > auth = urllib2.HTTPBasicAuthHandler() > opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) > urllib2.install_opener(opener) > > conn = urllib2.urlopen('http://python.org') > return_str = conn.read() > > fp = open('python.html','w').write(return_str) From norseman at hughes.net Thu Jul 10 20:03:21 2008 From: norseman at hughes.net (norseman) Date: Thu, 10 Jul 2008 17:03:21 -0700 Subject: Reportlab Image object opens filehandles In-Reply-To: References: <4873E0CC.9040306@hughes.net> Message-ID: <4876A349.7000600@hughes.net> Daniel de Sousa Barros wrote: > > ----- Original Message ----- From: "norseman" > To: "Daniel de Sousa Barros" > Cc: > Sent: Tuesday, July 08, 2008 6:49 PM > Subject: Re: Reportlab Image object opens filehandles > > >> >> Daniel de Sousa Barros wrote: >>> Hi Mr Robin, >>> >>> I saw your post: >>> http://mail.python.org/pipermail/python-list/2003-September/224781.html >>> >>> I'm trying to append more than 1000 images into one PDF report, but i >>> get the IOError: Too many... >>> >>> know you a solution for it? >>> >>> Sorry by my english.... i'm brazilian and i'm learning english yet... >>> >>> >>> ------------------------------------------------------------------------ >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> ==================== >> If you are using Microsoft: >> >> First reaction: Increase the system pagefile (virtual memory) size. >> >> Assuming lots of spare disk space you could change it to the 'on >> demand' or 'let system handle it' setting. I don't know about Vista >> but the rest top out about 4(or 2?)Gig per pagefile per disk. Forgot >> which. >> >> I don't know what imagery handling software you have, but if able, you >> could consider 1) resizing images to final printed paper display size >> and 2) make sure they are at or below 200dpi and jpeg in format before >> entering them into the report. >> >> If you are in Linux: >> >> see the man pages on mkswap and swapon. Use files for swapspace. Easy >> to create, easier to remove. Don't need to reconfigure hard drive. Can >> be on another mounted drive. Use AbiWord or OpenOffice to set up text >> pictures and all, print to file (will be a postscript) and use >> ghostview (gv) to check results then use ghostscript (gs) to convert >> to pdf. Final review in xpdf. ImageMagic's convert will do the image >> manipulations mentioned in last paragraph of Microsoft section and >> then some. All programs mentioned in the Linux section plus the >> operating system are free for the download. >> >> >> Steve >> norseman at hughes.net >> > ==================================================== > > I'm trying to generate de report using reportlab + PIL. > > This is the code: > > ------------------------------------------------------------------------------------------ > > for i in lista: > colab = Paragraph(i[0], style('1_b')) > imagem = Image(i[1]) #i tried lazy=2, but i get an error like this : > "_file" > imagem.drawHeight = 18*cm * imagem.drawHeight / imagem.drawWidth > imagem.drawWidth = 18*cm > story.append(imagem) > dados = [ > [colab, ''], > [imagem, ''] > ] > tabela = Table(dados, [19.3*cm, 0.01*cm], repeatRows=True) > tabela.hAlign = "LEFT" > story.append(tabela) > story.append(Spacer(0*cm, 1*cm)) > doc.build(story, onFirstPage = cabecalhoRetrato, > onLaterPages=cabecalhoRetrato) > ----------------------------------------------------------------------------------------------- > > > I only need to increase the virtual memory? How i do it? I'm using > windows xp. > > ================================================ Click Start/settings/control panel/system/advanced/settings(in \ performance area)/advanced/change set System managed size on click SET box to right of above line click positives (OK APPLY etc.) all way out, system will probably reboot what is 'cm' in your code? In my world it means centimeter. If you are trying to create full scale templates via raster methods you will probably need more than 'Mom's" email machine. Junior's whiz-bang game computer box probably won't work either. Even at 72dpi (72*72)*((18*2.54)*(18*2.54))*3 5184 *( 45.72 * 45.72) * 3 5184 * 2090.318 * 3 10,836,208 * 3 35,508,625.536 bytes per image 72dpi is normal for PDF/Postscript 5184 is dots per square inch 2090.318 is square inches per image 3 is one byte each, red,green,blue Add margins and offsets and space between and.... even without that, 35.5 million times 1000 = 35500 million or 35.5 Gigabytes !!!? In one file? Microsoft is going to have a problem with you. :) If that is what you are trying to do - reach me direct. I'll show you how. One of my photos takes 4 DVD's AFTER a 15 to 1 reduction in size. Can't find a calculator? 4*4.5*15 = 270Gigs uncompressed, more or less. Steve norseman at hughes.net From DWebre at dotd.la.gov Tue Jul 15 13:53:06 2008 From: DWebre at dotd.la.gov (DWebre at dotd.la.gov) Date: Tue, 15 Jul 2008 12:53:06 -0500 Subject: Pickle and wx.TextCtrl Message-ID: D. J. Webre, Jr. PE & PLS "Gabriel Genellina" python-list at python.org Sent by: cc python-list-bounc es Subject +djwebre=dotd.la. Re: Pickle and wx.TextCtrl gov at python.org 07/11/2008 10:51 PM Thanks for the response. En Fri, 11 Jul 2008 10:15:36 -0300, escribi?: > Trying to read a pickled file and list contents. > > The attached program works using pprint, but I want to write to my frame. > WriteText only produces half of the records. > What is happening? What do you mean by "only produces half of the records"? Write Text list records from "Assignment" to "Report" pprint list records from "Assignment" to "Report" and continues to "TaskWeek", about twice as many records Probably your problem has nothing to do with a TextCtrl - ensure you can save and load your data with a simple, console-based script, and only then write the GUI. The way you read the file is rather strange -mixing calls to readline and pickle.load- I'd write the data using pickle.dump calls *only* and then read it using pickle.load calls *only*. I used 13.1.7 Example of the Python Library Referencebut. Got an error message when I did not have the readline() statement. Additional ideas will be appreciated. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: graycol.gif Type: image/gif Size: 105 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: pic19718.gif Type: image/gif Size: 1255 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ecblank.gif Type: image/gif Size: 45 bytes Desc: not available URL: From nobby at invalid.invalid Fri Jul 11 19:21:08 2008 From: nobby at invalid.invalid (Nobody Here) Date: Fri, 11 Jul 2008 18:21:08 -0500 Subject: spam <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> Message-ID: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> rickman wrote: > spam No fucking shit, Sherlock, why double the volume by pointing out the obvious? From kay.schluehr at gmx.net Mon Jul 14 06:48:53 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 14 Jul 2008 03:48:53 -0700 (PDT) Subject: Need help in writing up a Python Syntax checker References: Message-ID: <57817302-0aca-4cb5-9559-7af6b5bc9d4d@l42g2000hsc.googlegroups.com> On 14 Jul., 08:22, Kinokunya wrote: > Hi guys, > > My group and I will be working on our final year project, the scope to > do a program/web-based application similar areas of functionalities > like the PyLint and PyChecker; a Python syntax checker. We have no > Python background, equipped only with some knowledge of Java and Dot > net. Python doesn't need a syntax checker. Syntax is checked by the parser and the parser is exposed to the user by means of the parser module. What you probably mean are *semantical* checks which are typical for compilers: e.g. whether names are used with prior assignments of values that cause runtime exceptions. These issues are in fact covered by PyLint and PyChecker. > We did some research on PyLint and found out that there are 2 common > modules that PyLint & PyChecker are using, namely logilab-astng and > logilab-common. I'm not really sure what these 2 modules are for. > > Quoted from the offical site, > > The aim of this module (logilab-astng) is to provide a common base > representation of python source code > > We're not really sure what they meant by common base representation of > source codes. Just switch to \Scripts\ in your Vista installation and type `easy_install pylint`. This shall install PyLint in the directory \lib\site-packages Additionally a pylint.bat file is placed in the \Scripts \ directory. Type `pylint --help` and you get more information about the functionality of PyLint. From linuxnow at gmail.com Wed Jul 9 18:19:41 2008 From: linuxnow at gmail.com (linuxnow at gmail.com) Date: Wed, 9 Jul 2008 15:19:41 -0700 (PDT) Subject: how to remove oldest files up to a limit efficiently References: <1eb168ac-fc63-4724-8604-45e995a06b51@s50g2000hsb.googlegroups.com> Message-ID: On Jul 9, 8:46?am, Dan Stromberg wrote: > On Tue, 08 Jul 2008 15:18:23 -0700, linux... at gmail.com wrote: > > I need to mantain a filesystem where I'll keep only the most recently > > used (MRU) files; least recently used ones (LRU) have to be removed to > > leave space for newer ones. The filesystem in question is a clustered fs > > (glusterfs) which is very slow on "find" operations. To add complexity > > there are more than 10^6 files in 2 levels: 16? dirs with equally > > distributed number of files inside. > > > My first idea was to "os.walk" the filesystem, find ?oldest files and > >removethem until I reach the threshold. But find proves to be too slow. > > > My second thought was to run find -atime several times toremovethe > > oldest ones, and repeat the process with most recent atime until > > threshold is reached. Again, this needs several walks through the fs. > > > Then I thought about tmpwatch, but it needs, as find, a date to start > > removing. > > > The ideal way is to keep a sorted list if files by atime, probably in a > > cache, something like updatedb. > > This list could be also be built based only on the diratime of the first > > level of dirs, seek them in order and so on, but it still seems > > expensive to get his first level of dir sorted. > > > Any suggestions of how to do it effectively? > os.walk once. > > Build a list of all files in memory. I was thinking of reuising updatedb but it does not contain atime. Reimplementing it seems overkill to only remove a few files regularily. Keeping this list easily would help a lot as old files would be always updated, the daily run (the one used to reupdate the db) would only add new ones which, in this case, are not interesting. > Sort them by whatever time you prefer - you can get times from os.stat. > > Then figure out how many you need to delete from one end of your list, > and delete them. > > If the filesystem is especially slow (or the directories especially > large), you might cluster the files to delete into groups by the > directories they're contained in, and cd to those directories prior to > removing them. 4096 dirs with equally distributed number of files inside. I'd probably play trick with diratime and then search inside in order and remove until threshold is reached, sorting seems too expensive, at the end this will run often and it should only need to remove a few tenths/ hundreths of files. From leo_365 at yahoo.com Wed Jul 23 06:23:59 2008 From: leo_365 at yahoo.com (leo davis) Date: Wed, 23 Jul 2008 03:23:59 -0700 (PDT) Subject: logging into a website using python Message-ID: <338837.60152.qm@web51802.mail.re2.yahoo.com> Hi, ? I''m trying achieve the following by running python programs -login to a website -automate filling up web forms ? So far I 've tried out the following codes: import cookielib, urllib, urllib2 login = 'cod45' password = 'mell' # Enable cookie support for urllib2 cookiejar = cookielib.CookieJar() urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) # Send login/password to the site and get the session cookie values = {'login':login, 'password':password } data = urllib.urlencode(values) request = urllib2.Request("https://student-webmail.surrey.ac.uk/webmail/", data) url = urlOpener.open(request)? # Our cookiejar automatically receives the cookies page = url.read(500000) # Make sure we are logged in by checking the presence of the cookie "id". # (which is the cookie containing the session identifier.) if not 'id' in [cookie.name for cookie in cookiejar]: ??? raise ValueError, "Login failed with login=%s, password=%s" % (login,password) print "We are logged in !" ? ? ***I get this error msg:Login failed with login?cod45' &? password ? ? Code 2: ? import urllib2 theurl = 'www.tek-tips.com' protocol = 'http://' username = 'ub007' password = 'with' passman = urllib2.HTTPPasswordMgrWithDefaultRealm() # this creates a password manager passman.add_password(None, theurl, username, password) # because we have put None at the start it will always # use this username/password combination for? urls # for which `theurl` is a super-url authhandler = urllib2.HTTPBasicAuthHandler(passman) # create the AuthHandler opener = urllib2.build_opener(authhandler) urllib2.install_opener(opener) # All calls to urllib2.urlopen will now use our handler # Make sure not to include the protocol in with the URL, or # HTTPPasswordMgrWithDefaultRealm will be very confused. # You must (of course) use it when fetching the page though. pagehandle = urllib2.urlopen(protocol + theurl) # authentication is now handled automatically for us the_page=pagehandle.read() print the_page ? **** This code prints out the html for? the home page ''www.tek-tips.com'.I was expecting it would log me in and take me to the members page.....What am i missing here? Why is it that the script doesnt attempt a login?Thanks in advance ? Cheers David -------------- next part -------------- An HTML attachment was scrubbed... URL: From max at alcyone.com Sun Jul 20 19:19:41 2008 From: max at alcyone.com (Erik Max Francis) Date: Sun, 20 Jul 2008 16:19:41 -0700 Subject: Python Written in C? In-Reply-To: References: Message-ID: giveitawhril2008 at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. Psst. What language do you think the primary implementations of C# is written in? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The actor is not quite a human being -- but then, who is? -- George Sanders From subhabrata.iisc at hotmail.com Tue Jul 22 02:25:15 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Mon, 21 Jul 2008 23:25:15 -0700 (PDT) Subject: Web Page Construction in Python Message-ID: Dear Group, I am getting some questions on doing Web Pages in Python. I have some interactive codes in python for which I like to make web pages. I am trying to use kid. Kid I learnt, and is easy, too. My questions are: i) Am I going correct? ii) Is there any language other than kid? iii) The worked out examples of kid are not opening properly, is there any other URL where I can see them. iv) Can cgi scripting be done with kid? If any one can spend time on my questions. Best Regards, Subhabrata. From comp.ogz at gmail.com Tue Jul 8 02:51:48 2008 From: comp.ogz at gmail.com (Oguz Yarimtepe) Date: Tue, 8 Jul 2008 09:51:48 +0300 Subject: system tray for Tk Message-ID: <20831c740807072351p9effd7dg598b5f16bffe4a9e@mail.gmail.com> Hi, Is there any binding that i can use for my python-tk application that will show an icon at the system tray when the application runs which will be able to be change during the process? -- O?uz Yar?mtepe From dingbat at codesmiths.com Wed Jul 30 10:46:32 2008 From: dingbat at codesmiths.com (Andy Dingley) Date: Wed, 30 Jul 2008 07:46:32 -0700 (PDT) Subject: SVN access with pysvn under Cygwin (Installation problems) Message-ID: <69da0a81-bf73-46cb-a762-b017a53e6ddf@e39g2000hsf.googlegroups.com> I'm building Python tools to wrap up access to our Subversion / SVN source control system. It's to run on my desktop (Cygwin under Windows XP) and then later under Redhat. Trying to install the pysvn module I'm running into problems getting it to work under Cygwin. Works fine from a Windows command prompt, with both the svn_cmd.py example and my own Python code. Under Cygwin though I just get import failures. pysvn/__init__.py seems to be invoked happily enough, but then fails when it tries to import _pysvn_2_5.pyd $ python svn_cmd.py Traceback (most recent call last): File "svn_cmd.py", line 10, in import pysvn File "/usr/lib/python2.5/pysvn/__init__.py", line 104, in import _pysvn_2_5 ImportError: No module named _pysvn_2_5 Is there some trick to getting .pyd to work under Cygwin? I've tried the obvious twiddling with environment variables (and regedit), but I'm just guessing blindly. Thanks for any assistance. From mccredie at gmail.com Tue Jul 22 12:35:58 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 22 Jul 2008 09:35:58 -0700 (PDT) Subject: Question about inheritence References: Message-ID: <26204bc2-a1f9-439c-aa0b-2d957ed81c5d@p25g2000hsf.googlegroups.com> On Jul 22, 9:26?am, Catherine Heathcote wrote: > If I create a new class inherited from another with a constructor, what > happens with the new class's constructer? > Thanks for your time. Nothing, unless you call it in your constructor. class Base(object): def __init__(self): print "Base constructor called" # without calling the base class constructor class C(Base): def __init__(self): print "C constructor called" # call the base class constructor using super class D(Base): def __init__(self): super(D, self).__init__() print "D constructor called" c = C() d = D() Matt From stefan_ml at behnel.de Sat Jul 19 15:09:25 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 19 Jul 2008 21:09:25 +0200 Subject: Question In-Reply-To: References: Message-ID: <48823be5$0$6563$9b4e6d93@newsspool3.arcor-online.net> perl_wizard at manx.net wrote: > Why is Perl so much better than python? Smart questions deserve smart answers: Yes. Stefan From wuwei23 at gmail.com Mon Jul 28 00:44:23 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 27 Jul 2008 21:44:23 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> <6a5506b1-632e-4bf6-b0ce-4d51d1751aa9@i24g2000prf.googlegroups.com> <8b4b11c3-e306-4fe7-82d1-0a948c725f2f@r15g2000prd.googlegroups.com> <239a084f-b73d-4c20-aaaf-bbd05d452638@a2g2000prm.googlegroups.com> Message-ID: <8f675d65-e302-4428-a4bc-f494b230cb59@w1g2000prk.googlegroups.com> > > > > On Jul 27, 4:26 pm, "Russ P." wrote: > > > > > Terry Reedy wrote: > > > > > > The use of '.' has been suggested before and rejected. > > > > > Where and why? > Dude, I agree with Guido completely on this one. You > seem to be clueless about the issue here. You're the > one with the reading comprehension problem. Please > quit wasting my time with your irrelevant crap. I pointed you at a thread -where it had been suggested and rejected-. And I'm the clueless one? I don't think I'm the one wasting anyone's time here, but fine. I've got far better things to do with my time than waste it talking to you. From deets at nospam.web.de Tue Jul 8 13:25:55 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 Jul 2008 19:25:55 +0200 Subject: extended setattr() References: <6dgfprF2ekq3U1@mid.uni-berlin.de> Message-ID: <6dhmahF2lhk6U1@mid.uni-berlin.de> Andre Adrian wrote: > Diez B. Roggisch nospam.web.de> writes: > >> > def ext_setattr(obj, attr, val): >> > for subattr in attr.split("."): >> > obj = getattr(obj, subattr) >> > obj = val >> > >> >>>> import test >> >>>> a = A() >> > Traceback (most recent call last): >> > File "", line 1, in >> > NameError: name 'A' is not defined >> >>>> a = test.A() >> >>>> a.B.C.txt >> > 'foo' >> >>>> ext_setattr(a, 'B.C.txt', 'bar') >> >>>> a.B.C.txt >> > 'foo' >> > >> > What am i doing wrong? >> >> obj = val won't work. > > Why is this so? Shouldn't it be the same? No, of course not! obj = val binds the object reffered to by val to the LOCAL name obj. That's python 101, make sure you get variables/names and scopes proper. >> You need to use a setattr(obj, name, val) >> on the last attribute-name. > > Ok, so this works: > > def ext_setattr(obj, attr, val): > attributes = attr.split('.') > for subattr in attributes[:-1]: > obj = getattr(obj, subattr) > setattr(obj, attributes[-1], val) Yep. Diez From sjmachin at lexicon.net Sun Jul 20 17:18:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 Jul 2008 14:18:34 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> <6ebshqF67cpfU4@mid.uni-berlin.de> <5d6b8066-c941-4f0c-abea-20baed33b4ab@l64g2000hse.googlegroups.com> <569da8b8-df8a-4115-a952-5d8c2d9744e0@i20g2000prf.googlegroups.com> <46c2153d-fef6-45b5-91af-9ecb359e6a2b@2g2000hsn.googlegroups.com> Message-ID: <141135ca-20fb-426e-a11f-bcd02aa01541@f40g2000pri.googlegroups.com> On Jul 21, 4:33 am, nicolas.pource... at gmail.com wrote: > > (1) You are searching through lists to find float objects by identity, > > not by value > > ???? You wrote """ I used short lists (a list of 20 floats) and the element checked was not in the list. (That was the case I usually deals with in my code.) """ From tavares at fe.up.pt Thu Jul 10 08:54:29 2008 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Thu, 10 Jul 2008 05:54:29 -0700 (PDT) Subject: Symposium "Image Processing and Data Visualization" within the SEECCM 2009, Greece - Announce & Call for Papers Message-ID: (Our apologies for cross-posting. We appreciate if you kindly distribute this information by your co- workers and colleagues.) *************************************************************************** Symposium ?Image Processing and Data Visualization? 2nd South-East European Conference on Computational Mechanics (SEECCM 2009) Island of Rhodes, Greece, 22-24 June 2009 http://www.seeccm2009.org (A special interest conference of the European Community on Computational Methods in Applied Sciences (ECCOMAS) and of the International Association for Computational Mechanics (IACM)) *************************************************************************** Dear Colleague, Within the 2nd South-East European Conference on Computational Mechanics (SEECCM 2009), to be held in Island of Rhodes, Greece, in 22-24 June 2009, we are organizing the Symposium ?Image Processing and Data Visualization?. The main goal of the Symposium ?Image Processing and Data Visualization? is to provide a platform for communications among specialists from complementary fields such as mechanics, computational vision, mathematics, physics, informatics, computer graphics, bio- medical-practice, psychology, clinicians and industry. Participants in this symposium should present and discuss their proposed methods in the corresponding fields that are related to the symposium topics and explore the translational potentials of this emerging technological field. Hence, this symposium should be an excellent opportunity to refine ideas for future work and to establish constructive cooperation. Due to your research activities in the related fields, we are pleased to invite you to submit your work and participate in the Symposium ?Image Processing and Data Visualization?. Topics of interest include (but are not restricted to): - Image Analysis; - Image Restoration, Compression, Segmentation and Description; - Object Tracking, Matching, Registration, Recognition and Reconstruction; - Visual Inspection; - 3D Vision; - Medical Imaging; - Data Processing, Modelling and Analysis; - Scientific Visualization; - Enhanced Visualization; - Human Computer Interaction; - Enhanced and Virtual Reality; - Simulation and Animation; - Software Development for Image Processing and Data Visualization; - Grid Computing in Image Processing and Data Visualization; - Applications of Image Processing and Data Visualization. Important dates and Instructions: - Deadline for submission one page abstract: 30 November 2008; - Authors notification: 31 December 2008; - Final contribution submission: 28 February 2009. - To submit your contribution, you should access the conference website at www.seeccm2009.org and select the Symposium ?Image Processing and Data Visualization? or send your file by email to the organizers (tavares at fe.up.pt, ceconst at stanford.edu). With kind regards, Yours sincerely, The Organizers, Jo?o Manuel R. S. Tavares (tavares at fe.up.pt) Faculty of Engineering of University of Porto, Porto, Portugal Christos E. Constantinou (ceconst at stanford.edu) Stanford University, USA From code at pizzashack.org Mon Jul 21 18:50:27 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 21 Jul 2008 18:50:27 -0400 Subject: Change PC to Win or Windows In-Reply-To: <0f3272c1-b1a7-4aef-9e4a-0f03af823a2d@z11g2000prl.googlegroups.com> References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> <82873ccd-9667-4dfa-9ec4-a9ac7c672aa7@w1g2000prk.googlegroups.com> <0f3272c1-b1a7-4aef-9e4a-0f03af823a2d@z11g2000prl.googlegroups.com> Message-ID: <20080721225027.GF8793@dragontoe.org> On Mon, Jul 21, 2008 at 02:47:31PM -0700, Lie wrote: > Common usage isn't always correct. Actually it is, inherently... When usage becomes common, the language becomes redefined, and its correctness is therefore true by identity (to borrow a mathematical term). The scholars complain for a while, but eventually capitulate, and re-write the dictionary. Language bends to its use by the people, not the other way around. Your assumption is the opposite, and therefore all of your argument is false. > For example, a physicist would not use weight when he meant mass. > much, but in technical environment doing so would embarrass him. In > this analogy, I consider download page for a software source code to > be a technical area. Your analogy is still broken. The term "PC" has been used BY TECHNCIAL PEOPLE, IN A TECHNICAL CONTEXT, to mean Microsoft on Intel, FOR DECADES. + Authors of technical books, manuals, and other forms of documentation have refered to them as PCs... for decades. + Educators in CS and EE at major universities have refer to them as PCs, since at least as early as 1988 (when I started college). + Industry news publications such as Computer World have refered to them as PCs, for decades. + There are even whole magazines dedicated to them! (PC Magazine, PC Shopper, PC World, PC Gamer, etc.) They are dedicated to Microsoft on Intel, and have existed (at least in some cases) long before Apple started talking about PCs in their ads. All of this has been going on, essentially since there has been such a thing as the IBM PC. I'm sorry, but you sir, are quite simply, plainly, and completely, wrong. With a catastrophic amount of written documentation, written by technical people in the computer industry over the last 20+ years, to prove it. > > > Apple popularizes the term by explicit marketing, > > > > And here is the last point you are missing: Apple does no such > > thing. > > They did, by using the term PC to refer to other computers. APPLE CAN NOT POPULARIZE A TERM WHICH IS ALREADY POPULAR. > This kind of advertising Apple (the computer company) used is > misleading, since it implied that their PC is not a PC. They haven't implied anything; they're stating it outright! Apple sells personal computers, but they do not sell PCs. Apple's personal computer is NOT a PC, and never was, and never will be. It's an Apple. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From swiftone at swiftone.org Mon Jul 28 09:48:46 2008 From: swiftone at swiftone.org (Brett Ritter) Date: Mon, 28 Jul 2008 06:48:46 -0700 (PDT) Subject: Module clarification References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> Message-ID: On Jul 28, 4:54?am, Hussein B wrote: > Hi. > I'm a Java guy and I'm playing around Python these days... > In Java, we organize our classes into packages and then jarring the > packages into JAR files. > What are modules in Python? > What is the equivalent of modules in Java? I'm new myself, coming from Perl and Java. Take my comments with the appropriate salt. Here's my understanding: 1) JARs are a bit of a Java oddity. The other languages I've worked with don't really combine their packaging method for transport with their packaging method of access. Put another way, you may get a zipfile or tarball of library files, but they aren't USED in that format, they are just transported in that format. You unzip them and use the compiled libraries directly. Java appears to be unusual there. I could be wrong (it's a big world), but such is my experience in the C and Perl worlds. 2) Java also dictates a single class per file (basically). Other languages do not have that restriction which leads to different collections. A file in Python (a module) may have several classes, or just one, or none. A package in Python is a directory containing modules (and possibly other packages) as well as a __init__.py file. This means that you cannot have the Java case of two packages offering the same fully qualified resource, because the namespace is tied to the filesystem (note you can alter this when importing the packages). 3) Java uses "import" to create a shortcut to the namespace, a convenience for the programmer that has little to no bearing on the execution of the code. Namespace is determined by the classloader. Python uses "import" to declare how a namespace is used by the code itself, which can be very significant, (For example, Java can access any fully qualified package without an import statement. Python cannot access any package until it has been made available by import.) Hope that helps and is remotely accurate. I'm sure someone will correct me if I'm wrong. From norseman at hughes.net Wed Jul 23 16:08:09 2008 From: norseman at hughes.net (norseman) Date: Wed, 23 Jul 2008 13:08:09 -0700 Subject: Importing different versions of a module Message-ID: <48878FA9.7020403@hughes.net> Mercado; Problem solved. The attached .zip file has the working example. It is modeled after my own uses in other languages. It's not quite as elegant as it should be but it does work and is both flexible and extendable. A word of caution: I run Linux. I make no promises about any of my code working on Microsoft. Fredrik's web links on __import__ was the first major door opener. The use of system environmentals took a ton of google time. Search that proved useful was "os enviro python'. Page two had a link to a google book. The Python Official Documentation does not make it clear as to how to use os.environ other than to note it's existence. The tutorial pretty much avoids it. Python docs, in general, seem to be for (and maybe by) persons writing less than one page of code per project. It does call itself a scripting language, but it is short in sight. Don't get me wrong, it is useful. Just that it doesn't seem to have originally been given a foundation for the scale of projects I see the questions coming in on. A more thorough search and use of regular dictionary terms would have been better. In python, 'global x' means for this file, not for the project as is normal. Anyway - Zip file has three files. .txt is test data. .py is sub or called module z (dot nothing) is program base put a copy of .txt and .py in each of two locations. something like: /tmp/scott to contain .txt and .py /tmp/scott/1 same in one or the other, but not both, make a change or two to the file(s) there. perhaps putting 6 'Z'z in a csv field of same size following the 12 in the last record. put z (no last name) in maybe your home dir. anywhere but in those two. fix the directories in both z files as needed, if needed. enter:> python z and check both the source(s) and the screen. in z change os.environ['ISTEST']='True' to ...'False' and rerun. There should be 'True' (or 'False') in the bottom of z's output and at the top of z.py's output. Any formatting changes and/or data changes should occur as expected. Do not think you have to use these 'as-is'. These are just concept proof. Actual real globals (project wide) are still the best but, well... perhaps in time. Gotta go to work; Steve norseman at hughes.net -------------- next part -------------- A non-text attachment was scrubbed... Name: test.zip Type: application/octet-stream Size: 2532 bytes Desc: not available URL: From bj_666 at gmx.net Tue Jul 22 17:49:42 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Jul 2008 21:49:42 GMT Subject: Iterating Through List or Tuple References: Message-ID: <6en2vlF7jml4U2@mid.uni-berlin.de> On Tue, 22 Jul 2008 14:43:10 -0700, Samir wrote: > Is there a way to loop or iterate through a list/tuple in such a way > that when you reach the end, you start over at the beginning? For > example, suppose I define a list "daysOfWeek" such that: > >>>> daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] > > If today is Sunday, I can set the variable "day" to today by: > >>>> i = iter(daysOfWeek) >>>> day = i.next() >>>> print day > sunday > > If I want to find out the day of the week 2 days from now, then this > code works ok: > >>>> for x in xrange(2): day = i.next() > >>>> print day > tuesday > > However, when extending my range beyond the number of items in the > list, I receive an error. For example, if I want to find out the day > of the week 11 days from today, I get this: > >>>> for x in xrange(11): day = i.next() > > > Traceback (most recent call last): > File "", line 1, in > for x in xrange(11): day = i.next() > StopIteration > > Is there a way to easily loop through a list or tuple (and starting > over at the beginning when reaching the end) without having to resort > to an "if" or "while" statement? For sequences: days_of_week[(today + offset) % len(days_of_week)] For iterables in general: `itertools.cycle()` Ciao, Marc 'BlackJack' Rintsch From sunp1028 at gmail.com Wed Jul 16 12:52:53 2008 From: sunp1028 at gmail.com (patrol) Date: Wed, 16 Jul 2008 09:52:53 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> <487E1AD4.9020509@timgolden.me.uk> Message-ID: <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> On 7?17?, ??12?16?, Tim Golden wrote: > Assuming that the error comes back in the sys.stdout encoding, the following version *should* work ok. I still haven't got a non-English set up to test it on, but it certainly does return a Unicode error message. > > http://timgolden.me.uk/wmi-project/wmi.py > > The usual test case, if you wouldn't mind: > > > import wmi > > wmi.WMI ("non-existent computer") > > > > should give a (language-specific) error message, not an UnicodeDecodeError > > TJG -------------------------------------------------------------------------------------- >>> import wmi >>> wmi.WMI('non-existent computer') Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\wmi.py", line 1199, in connect handle_com_error (error_info) File "C:\Python25\lib\wmi.py", line 184, in handle_com_error exception_string = [u"%s - %s" % (hex (hresult_code), hresult_name)] UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 4: ordinal not in range(128) -------------------------------------------------------------------------------------- yup,error_info contains the Chinese encoded string. All of the Simple Chinese Windows use the CP936.Every Chinese word utilizes two bytes.Maybe you can fix this bug by modifying handle_com_error. Patrol From castironpi at gmail.com Thu Jul 24 13:37:52 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 24 Jul 2008 10:37:52 -0700 (PDT) Subject: Python Written in C? References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> <6eosgtF7u58sU1@mid.uni-berlin.de> <537c58c3-d74c-41dd-8571-26cfbb415178@34g2000hsh.googlegroups.com> <6ep711F7u58sU2@mid.uni-berlin.de> Message-ID: <02635ba4-dbbd-4674-a1f7-b86f0f13dd4b@s21g2000prm.googlegroups.com> On Jul 23, 12:10?pm, Marc 'BlackJack' Rintsch wrote: > On Wed, 23 Jul 2008 09:42:29 -0700, castironpi wrote: > > On Jul 23, 9:11?am, Marc 'BlackJack' Rintsch wrote: > >> On Wed, 23 Jul 2008 14:10:22 +0200, mk wrote: > >> > Marc 'BlackJack' Rintsch wrote: > >> >> I can't even remember when I deleted something from a list in the past. > > >> > Still, doesn't that strike you as.. workaround? > > >> No, I find it actually safer; I don't have to care where modifications of > >> the list might be seen elsewhere in the program. > > >> Ciao, > >> ? ? ? ? Marc 'BlackJack' Rintsch > > > a[:]= newlist > > > and > > > a= newlist > > > have two completely different effects, and one is just as safe as > > 'del'. ?Besides, del isn't safe to be seen elsewhere in the program in > > other threads, if they aren't locking the GIL. > > As usual you are talking nonsense? > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch As usual you are taking flamebait! From levicc00123 at gmail.com Fri Jul 18 16:26:31 2008 From: levicc00123 at gmail.com (Levi Campbell) Date: Fri, 18 Jul 2008 13:26:31 -0700 (PDT) Subject: Writing a program under GNU/Linux for MS Windows. Message-ID: Hi, I'm trying to write a program for a friend of mine who uses windows but I use GNU/Linux. I know you can use mingw and link to the python dll, but is there a way to create a win32 service under Linux? From norseman at hughes.net Wed Jul 9 13:07:31 2008 From: norseman at hughes.net (norseman) Date: Wed, 09 Jul 2008 10:07:31 -0700 Subject: Determining when a file has finished copying In-Reply-To: <4874E2D3.4050707@gmail.com> References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> Message-ID: <4874F053.8060709@hughes.net> Also available: pgm-W copies/creates-fills whatever B/dummy when done, pgm-W renames B/dummy to B/F pgm-D only scouts for B/F and does it thing when found Steve norseman at hughes.net Manuel Vazquez Acosta wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > This seems a synchronization problem. A scenario description could clear > things up so we can help: > > Program W (The workflow) copies file F to directory B > Program D (the dog) polls directory B to find is there's any new file F > > In this scenario, program D does not know whether F has been fully > copied, but W does. > > Solution: > Create a custom lock mechanism. Program W writes a file D/F.lock to > indicate file F is not complete, it's removed when F is fully copied. > I program W crashes in mid-copy both F and F.lock are kept so program D > does not bother to process F. Recovery from the crash in W would another > issue to tackle down. > > Best regards, > Manuel. > > writeson wrote: >> Hi all, >> >> I'm writing some code that monitors a directory for the appearance of >> files from a workflow. When those files appear I write a command file >> to a device that tells the device how to process the file. The >> appearance of the command file triggers the device to grab the >> original file. My problem is I don't want to write the command file to >> the device until the original file from the workflow has been copied >> completely. Since these files are large, my program has a good chance >> of scanning the directory while they are mid-copy, so I need to >> determine which files are finished being copied and which are still >> mid-copy. >> >> I haven't seen anything on Google talking about this, and I don't see >> an obvious way of doing this using the os.stat() method on the >> filepath. Anyone have any ideas about how I might accomplish this? >> >> Thanks in advance! >> Doug >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (GNU/Linux) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iEYEARECAAYFAkh04skACgkQI2zpkmcEAhi0eQCgsVqg51fWiwi47jxqtbR8Gz2U > UukAoKm15UAm3KpEyjhsIGQ+68rq8WuU > =UFHi > -----END PGP SIGNATURE----- > -- > http://mail.python.org/mailman/listinfo/python-list > From stefan_ml at behnel.de Thu Jul 3 00:59:13 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 03 Jul 2008 06:59:13 +0200 Subject: ANN: XML builder for Python In-Reply-To: References: Message-ID: <486C5CA1.3080105@behnel.de> Jonas Galvez wrote: > Not sure if it's been done before, but still... Obviously ;) http://codespeak.net/lxml/tutorial.html#the-e-factory ... and tons of other tools that generate XML, check PyPI. Stefan From cyberco at gmail.com Mon Jul 21 07:53:12 2008 From: cyberco at gmail.com (Berco Beute) Date: Mon, 21 Jul 2008 04:53:12 -0700 (PDT) Subject: simple question about dictionaries References: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> Message-ID: <2c1ab8a0-ccbd-4c75-ae6d-d8e8000aa3df@r66g2000hsg.googlegroups.com> Sounds like a school assignment. Find the answer yourself here: http://diveintopython.org/toc/index.html You'll learn a lot more in the process. 2B From malaclypse2 at gmail.com Tue Jul 15 16:32:15 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 15 Jul 2008 16:32:15 -0400 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: <16651e80807151332o1a2b7446r651f515724a27e0@mail.gmail.com> On Tue, Jul 15, 2008 at 4:13 PM, Reedick, Andrew wrote: > If name is None: > Then name is NULL, nothing, nada, no object, no memory allocated, a > NULL pointer This is just plain untrue. If 'name is None' evaluates to true, then the variable 'name' is bound to the singleton value None. It has nothing to do with allocated memory or null pointers. All it means is that someplace along the line you did the equivalent of 'name = None' in your code. -- Jerry From torainLight at gmail.com Fri Jul 4 20:21:14 2008 From: torainLight at gmail.com (satoru) Date: Fri, 4 Jul 2008 17:21:14 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: <6d4bfmFp3aoU1@mid.uni-berlin.de> <0f6f795d-8041-463e-8e98-9d830ca3fc5b@l42g2000hsc.googlegroups.com> <45111722-3f2c-476d-8e7b-fd65cc5100a6@56g2000hsm.googlegroups.com> Message-ID: why don't you just download & excute the windown installer binary? On Jul 4, 2:47?am, defn noob wrote: > On Jul 3, 8:06?pm, "bruno.desthuilli... at gmail.com" > > wrote: > > On 3 juil, 18:51, defn noob wrote: > > > > well the reason i unzipped and placed it in site-packages was because > > > nothign happened when i ran setup.py(unzipped). > > > What do you mean, "running setup.py unzipped" ??? > > > The correct way to install a package is to: > > > - unzip (untar, whatever) the archive somewhere in your own directory > > - cd to the unzipped directory > > - *from there*, run python setup.py install > > yes, which i have done. > > the command row executes but nothing happens, no errors either. From elessar at nienna.org Wed Jul 30 12:52:35 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Wed, 30 Jul 2008 10:52:35 -0600 Subject: Reasoning behind 'self' parameter in classes? In-Reply-To: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> Message-ID: <48909C53.2060206@nienna.org> Robert Dailey wrote: > Hi, > > I want to point out first of all that I'm not as familiar with Python as > I should be, and for that reason I question a lot of things because I'm > mainly a C++ programmer and I'm used to certain conveniences. Having > said that... > > I've always been curious (more so than annoyed) as to why one must > explicitly specify a "self" parameter for member functions in a class in > Python. This seems very "C" like to me, since to do object oriented > programming in C you must devote one parameter to the object itself. In > a higher order language like Python, I would not have expected (and thus > am rather surprised) that this pattern would apply. Is there any > particular reason why 'self' parameters must be specified explicitly? I > am curious to understand the philosophy and design behind this. > > In Python 3 will there be any plans to eliminate this syntactic > artifact? As I said, it's not terribly annoying to me but it seems like > more of a hack than anything else. I would feel a bit better if I didn't > have to see it. I don't mean to start any syntax wars or anything, so I > hope everyone will keep an open mind and simply explain the design, > rather than defend it. I'm interested in only facts, and not opinions. > > This is an example of a response I'm looking for: > "The self parameter is required because the parser is a bit old and > needs to know the exact object you're referencing" > > This is _not_ an example of what I'm looking for: > "Specifying self is a great mysterious thing that we should never > question. Do not question the language! The language is mighty! Don't > bring C++ to Python!" > > I appreciate the community's time. > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list There was a massive thread "attack a sacred python cow" that brought up a lot of reasons why this is the case. If you can ignore the flames, you'll find some good info there. But it might not be wise to bring it up again a week after it happened last time. -Matt From drakonik at gmail.com Mon Jul 7 17:30:41 2008 From: drakonik at gmail.com (Nick Dumas) Date: Mon, 07 Jul 2008 17:30:41 -0400 Subject: "in"consistency? In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [1,2] in [1,2,3] checks to see if the list [1,2] is an item in [1,2,3]. Because the list [1,2,3] only contains the integers 1,2,3, the code returns a False. Try "[1,2] in [[1,2],[2,3]]" David C. Ullrich wrote: > Luckily I tried it before saying no, that's > not how "in" works: > >>>> 'ab' in 'abc' > True >>>> [1,2] in [1,2,3] > False > > Is there a reason for the inconsistency? I would > have thought "in" would check for elements of a > sequence, regardless of what sort of sequence it was... > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkhyiwEACgkQLMI5fndAv9jbiwCeKMXrAclILJMPro5VuSRgdkvB cGkAn1igcjFWRQJSwEDOxpk3spzceZGa =iq8L -----END PGP SIGNATURE----- From timothy.grant at gmail.com Tue Jul 22 18:11:29 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Tue, 22 Jul 2008 15:11:29 -0700 Subject: Function editing with Vim throws IndentError In-Reply-To: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: On Tue, Jul 22, 2008 at 2:02 PM, ptn wrote: > Hi everybody, > > I have a weird problem. Say I have a .py file with some functions in > it, like this: > > # (...) > def foo(): > print("bar") > > When I open it and add a line to one of the functions, > > # (...) > def foo(): > troz = "bar" > print(troz) > > I get the following traceback from the interpreter: > > Traceback (most recent call last): > File "SOMEWHERE/example.py", line ?? > troz = "bar" > ^ > IndentationError: unindent does not match any outer indentation > level > > And so I'm forced to rewrite the function entirely just to add the new > line. > > I thought that my problem was the w option from formatoptions, so I > changed my .vimrc file to this: > > augroup filetype > autocmd BufNewFile,BufRead *.txt set filetype=human > augroup END > autocmd FileType human setlocal formatoptions+=ta2w > autocmd FileType lisp,scheme,python,c,java,vim setlocal > formatoptions-=ta2w > > But the problem didn't go away. I don't think this has anything to > do > with the tabs and spaces, because I have them set up like this: > > set tabstop=4 shiftwidth=4 expandtab > > which is the standard way to handle them. > > The scripts I load are: qbuf, TagList, indent/python.vim and a reduced > version of the standard python.vim > > Could someone provide some pointers? > > Thanks, > > Pablo Torres N. > -- > http://mail.python.org/mailman/listinfo/python-list > Are you editing someone else's code? If you are, my guess is that the file uses tabs for indentation. You may want to do ":set list" within Vim to test that theory. That should show you what all the whitespace characters are. -- Stand Fast, tjg. [Timothy Grant] -------------- next part -------------- An HTML attachment was scrubbed... URL: From gherron at islandtraining.com Thu Jul 10 16:39:29 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 10 Jul 2008 13:39:29 -0700 Subject: Can anyone suggest a date peocedure... In-Reply-To: References: Message-ID: <48767381.9080303@islandtraining.com> RLV wrote: > I'd like to find a simple... (I'm a simple person) procedure to > subtract a numerical number from a six char date string > YYYYMMDD and then convert back to a new date string. > > I'm sure there's a way to do it, but the date modules haven't been > much help. > > TIA > Ron > > -- > http://mail.python.org/mailman/listinfo/python-list > The datetime module has what you need. It has methods (with examples) on building a datetime object from a string, and it has a object named timedelta, and the ability to subtract a timedelta from a time. For instance, the time right now and the time exactly one day ago: >>> from datetime import * >>> datetime.today() datetime.datetime(2008, 7, 10, 13, 38, 48, 279539) >>> datetime.today()-timedelta(1) datetime.datetime(2008, 7, 9, 13, 38, 50, 939580) Gary Herron From tjreedy at udel.edu Wed Jul 16 02:32:13 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 Jul 2008 02:32:13 -0400 Subject: Moving to functional programming In-Reply-To: <87vdz64j6j.fsf@benfinney.id.au> References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> <7xiqv68rrp.fsf@ruckus.brouhaha.com> <87vdz64j6j.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Paul Rubin writes: > >> I don't like square-bracket listcomps because they leak the index >> variables to the outside. > > According to PEP 289 , > this is an acknowledged wart that will be fixed in Python 3.0. Has been. IDLE 3.0b1 >>> a=[i for i in range(5)] >>> i Traceback (most recent call last): File "", line 1, in i NameError: name 'i' is not defined From giltay at gmail.com Tue Jul 29 15:42:19 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Tue, 29 Jul 2008 12:42:19 -0700 (PDT) Subject: iterating "by twos" References: <70a172ac-0491-4918-9c74-6a577f35068a@d45g2000hsc.googlegroups.com> Message-ID: On Jul 29, 2:36?pm, gil... at gmail.com wrote: > On Jul 29, 1:36?pm, kj wrote: > > > Is there a special pythonic idiom for iterating over a list (or > > tuple) two elements at a time? > > ? ? ?I use this one a lot: > > for x, y in zip(a, a[1:]): > ? ? frob(x, y) > > Geoff G-T Whoops, I misread the original post. That would be: for x, y in zip(a[::2], a[1::2]): frob(x, y) ... which I don't use a lot. >>> a = range(9) >>> for x, y in zip(a, a[1:]): ... print x, y ... 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 >>> for x, y in zip(a[::2], a[1::2]): ... print x, y ... 0 1 2 3 4 5 6 7 Geoff G-T From malaclypse2 at gmail.com Mon Jul 14 12:51:01 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 14 Jul 2008 12:51:01 -0400 Subject: Unicode confusion In-Reply-To: <1216053600.3028.59.camel@localhost.localdomain> References: <1216053600.3028.59.camel@localhost.localdomain> Message-ID: <16651e80807140951j1b4ecbfayb2f477a4bd000614@mail.gmail.com> On Mon, Jul 14, 2008 at 12:40 PM, Tim Cook wrote: > if I say units=unicode("?"). I get > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: > ordinal not in range(128) > > If I try x=unicode.decode(x,'utf-8'). I get > TypeError: descriptor 'decode' requires a 'unicode' object but received > a 'str' > > What is the correct way to interpret these symbols that come to me as a > string? Part of it depends on where you're getting them from. If they are in your source code, just define them like this: >>> units = u"?" >>> print units ? >>> print repr(units) u'\xb0' If they're coming from an external source, you have to know the encoding they're being sent in. Then you can decode them into unicode, like this: >>> units = "?" >>> unicode_units = units.decode('Latin-1') >>> print repr(unicode_units) u'\xb0' >>> print unicode_units ? -- Jerry From ptmcg at austin.rr.com Fri Jul 11 22:15:39 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 11 Jul 2008 19:15:39 -0700 (PDT) Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> <2a13cea6-5144-4f37-af8a-607601f923a9@79g2000hsk.googlegroups.com> Message-ID: <29434cc4-855e-4112-a234-f78cdd55205f@m73g2000hsh.googlegroups.com> On Jul 11, 6:20?pm, Mensanator wrote: > > Try this: > > > spam = ['a', 'n', 'n', 'a'] > > eggs = spam[:] > > if spam.reverse() == eggs: > > ? ? print "Palindrome" > > You could also do > > >>> spam = ['a','n','n','a'] > >>> if spam == [i for i in reversed(spam)]: > > ? ? ? ? print "Palindrome" > Or instead of this: [ i for i in generator_expression] just use the list constructor: list(generator_expression) -- Paul From sanket.s.patel at gmail.com Fri Jul 25 17:16:16 2008 From: sanket.s.patel at gmail.com (sanket) Date: Fri, 25 Jul 2008 14:16:16 -0700 (PDT) Subject: SimpleJson is slow .... is there any C Compiled version ? Message-ID: Hello All, I have created an API which fetches some data from the database. I am using simplejson to encode it and return it back. Now the problem is that, this API is being called for millions of times in a sequence. I ran a profiler and saw that most of the time is consumed in encoding my database results in to json. So I was just wondering is there any C compiled version of simplejson is available? or any help regarding this issue would be appreciated. Thank you, Sanket From Rakesh.Thakrar at microcom-it.com Thu Jul 31 09:51:28 2008 From: Rakesh.Thakrar at microcom-it.com (Rakesh Thakrar) Date: Thu, 31 Jul 2008 14:51:28 +0100 Subject: Python Contractor needed Message-ID: <17A5EF611D8AF34DA2E14B2354C9C3FE1EFAB1@ern-server-mail> Hi All, An opportunity for a talented Python Software Engineer has arisen to join a company which is currently going through a phase of rapid expansion. Candidates must have excellent software development skills to join an established team within this small company with offices in the U.K. and U.S. An ideal candidate will be familiar with Linux, have a passion for working with OpenSource software and a flair for creating innovative solutions to complex problems. The candidate will be a self motivated, flexible software engineer working within the existing I.T. Team. The day to day role will almost exclusively focus on new projects. Key elements of the role include l Work closely with the I.T. team and business managers to aid the design and implementation of a new web based application for our customers and data processing engine. l Work closely with the application design team to understand, agree, plan and develop the new application. l Assess software requirements and assist with the project planning stage. l Design, code and test various software elements in both Windows and Linux based environments. l Ability to train and mentor other members of the software development team. l Experience of working within a development team using source control and collaborative tools such as Subversion, CVS, Trac, etc. l Providing required documentation (specifications, test plans, processes, etc). This is a 6-12 month contract based near Portsmouth in Hampshire UK . Please do not hesitate to contact me for further information. Regards Rakesh ___________________ Rakesh Thakrar Manager Microcom Tel: 01923 851225 Mob: 079 7094 3227 Fax: 0845 389 2392 www.microcom-IT.com Beaumont Gate Shenley Hill Radlett Hertfordshire WD7 7AR Permanent and Contract IT Specialists ____________________________________ P SAVE A TREE - PLEASE DO NOT PRINT THIS EMAIL UNLESS YOU REALLY NEED TO. ************************************************************************ ************ The views expressed in this e-mail are not necessarily the views of European Recruitment Network Ltd, its directors, officers or employees make no representation or accept any liability for its accuracy or completeness unless expressly stated to the contrary. This e-mail, and any attachments are strictly confidential and intended for the addressee(s) only. The content may also contain legal, professional or other privileged information. Unless expressly stated to the contrary, no contracts may be concluded on behalf of European Recruitment Network Ltd by means of e-mail communication. You may report the matter by calling us on 0845 389 2322. Please ensure you have adequate virus protection before you open or detach any documents from this transmission. European Network Recruitment Ltd does not accept any liability for viruses. European Recruitment Network Ltd is registered in England: Company Number: 5651508. Registered Office: Greener House, 66-68 Haymarket, London, SW1Y 4RF ************************************************************************ ************ -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Jul 30 21:13:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 22:13:49 -0300 Subject: proxy class and __add__ method References: <18715799.post@talk.nabble.com> <3d59a908-f585-4ff5-ad37-bb48579cc9cb@a21g2000prf.googlegroups.com> Message-ID: En Wed, 30 Jul 2008 14:54:51 -0300, Rhamphoryncus escribi?: > On Jul 29, 10:23?pm, "Gabriel Genellina" > wrote: >> En Tue, 29 Jul 2008 13:13:51 -0300, Magnus Schuster ? >> escribi : >> >> > I have written the following small proxy class which I expect to pass >> all >> > function calls to the 'original' object: >> >> > --- BEGIN --- >> > class proxy(object): >> > ? ? def __init__( self, subject ): >> > ? ? ? ? self.__subject = subject >> > ? ? def __getattr__( self, name ): >> > ? ? ? ? return getattr( self.__subject, name ) >> >> > But "k=prx_i+1" raises a >> > : unsupported operand type(s) for +: >> 'proxy' >> > and 'int'. >> >> > How is this addition different from the previous line "j=..."? And >>> how ? >>> can I >>> modify the proxy class so that all methods are passed on, which are not >>> explicitly overloaded? >> >> Try implementing a similar __getattr__ method in a metaclass. > > But I don't think they use __getattr__.. they bypass it. Effectively > they catch the assignment to __add__ and cache it. You'll have to > always define it in the class and have it be ineffectual in some cases. Ouch, yes, thanks, I noticed the fact after some testing. -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Sun Jul 27 18:13:46 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Jul 2008 22:13:46 GMT Subject: Confounded by Python objects References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> <5ddae1dd-c7dd-4f04-84f6-ad71c3282c92@j7g2000prm.googlegroups.com> <6f1a6uF9ctsmU1@mid.uni-berlin.de> <009c464f$0$20302$c3e8da3@news.astraweb.com> <488cd4a2$0$21184$426a34cc@news.free.fr> Message-ID: <009ceea1$0$20302$c3e8da3@news.astraweb.com> On Sun, 27 Jul 2008 20:04:27 +0200, Bruno Desthuilliers wrote: >> In general, anything that looks like this: >> >> s = '' >> for i in range(10000): # or any big number >> s = s + 'another string' >> >> can be slow. Very slow. > > But this is way faster: > > s = '' > for i in range(10000): # or any big number > s += 'another string' Actually, no, for two reasons: (1) The optimizer works with both s = s+t and s += t, so your version is no faster than mine. (2) The optimization isn't part of the language. It only happens if you are using CPython versions better than 2.4, and even then not guaranteed. People forget that CPython isn't the language, it's just one implementation of the language, like Jython and IronPython. Relying on the optimization is relying on an implementation-specific trick. > yeps : using augmented assignment (s =+ some_string) instead of > concatenation and rebinding (s = s + some_string). Both are equally optimized. >>> timeit.Timer('s+=t', 's,t="xy"').repeat(number=100000) [0.027187108993530273, 0.026471138000488281, 0.027689933776855469] >>> timeit.Timer('s=s+t', 's,t="xy"').repeat(number=100000) [0.026300907135009766, 0.02638697624206543, 0.02637791633605957] But here's a version without it: >>> timeit.Timer('s=t+s', 's,t="xy"').repeat(number=100000) [2.1038830280303955, 2.1027638912200928, 2.1031770706176758] -- Steven From asma61 at dsl.pipex.com Sun Jul 27 15:29:39 2008 From: asma61 at dsl.pipex.com (DaveM) Date: Sun, 27 Jul 2008 20:29:39 +0100 Subject: Rant (was Re: x*x if x>10 References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3g8rF9gfj0U1@mid.uni-berlin.de> <6f3gmaF9moqsU1@mid.uni-berlin.de> <1q5p845o2j9htp6vf44u6nqinucsr1numf@4ax.com> Message-ID: On Sun, 27 Jul 2008 09:28:28 -0700, Gary Herron wrote: >> a = list(set(itertools.chain(*sessexam.values()))) >> a.sort() #As I write I'm wondering if I really need it sorted. Hmm... >> return a >Didn't someone already answer that. List addition and sum() both do >what you want. > > >>> A = [1,2,3] > >>> B = [4,5,6] > >>> C = [7,8,9] > > >>> A+B+C >[1, 2, 3, 4, 5, 6, 7, 8, 9] True, although unsuitable for my circumstance. > >>> sum([A,B,C], []) >[1, 2, 3, 4, 5, 6, 7, 8, 9] Ah. I had no luck with sum, but I hadn't realised it needed the "[]" term. I must read about it again. >It doesn't get any easier than that. Not only that, but it's exactly what I was after - and fastest, too, although speed isn't really an issue. Thank you. DaveM From salih84 at gmail.com Wed Jul 23 12:43:06 2008 From: salih84 at gmail.com (Eurotechzone) Date: Wed, 23 Jul 2008 09:43:06 -0700 (PDT) Subject: Europe's Best Computer Enthusiast Website, Eurotechzone is now Open! Message-ID: http://www.eurotechzone.com Catering to the computer enthusiasts from all over the world, Eurotechzone is Europe?s first multi-lingual website on hardware news&reviews. In this site you will find: ? The hottest news from IT Bussiness world ? The Reviews of the newest electronic components and PC hardwares. ? A dynamic community/forum to discuss IT subjects and technical issues. ? ?and more and more is awaiting for you in www.eurotechzone.com From lanclos at ucolick.org Wed Jul 16 19:56:56 2008 From: lanclos at ucolick.org (Kyle Lanclos) Date: Wed, 16 Jul 2008 16:56:56 -0700 Subject: Manually prompting garbage collection In-Reply-To: References: <20080716230911.GD22400@monkey.ucolick.org> Message-ID: <20080716235656.GE22400@monkey.ucolick.org> Fredrik Lundh wrote: > what magic do you expect the "manual garbage collection" to do here that > the DECREF doesn't already do? The DECREF decrements the reference count, but does not immediately prompt garbage collection when the reference count drops to zero; that garbage collection does not appear to occur until I return from the particular C function I am in the middle of executing. Ideally, I want to explicitly prompt garbage collection in the middle of a C function, without first returning to the larger Python interpreter. --Kyle From aquil.abdullah at gmail.com Tue Jul 15 10:42:32 2008 From: aquil.abdullah at gmail.com (Aquil H. Abdullah) Date: Tue, 15 Jul 2008 10:42:32 -0400 Subject: Using Python To Launch Python In-Reply-To: <23116d500807150741w157af9ffld1ace08a57896d71@mail.gmail.com> References: <20080714212454.GE16010@dragontoe.org> <23116d500807141440u402eed7du5e41d72bb0716c58@mail.gmail.com> <20080715003920.GF16010@dragontoe.org> <23116d500807150741w157af9ffld1ace08a57896d71@mail.gmail.com> Message-ID: <23116d500807150742n26de4d67p79d6b226e78d83f4@mail.gmail.com> Ahh, Win-BASH cool!!! On Tue, Jul 15, 2008 at 10:41 AM, Aquil H. Abdullah < aquil.abdullah at gmail.com> wrote: > Ack, .bat files! Yes, you are correct Windows does not ship with Python, > and there are ways to get bash (cygwin) on your Windoze system. I am > leaning towards a solution similar to your second suggestion as it will keep > me from having to distribute .bat files for one platform and .sh files for > another. Thank you for all of your suggestions. > > > On Mon, Jul 14, 2008 at 8:39 PM, Derek Martin wrote: > >> On Mon, Jul 14, 2008 at 05:40:43PM -0400, Aquil H. Abdullah wrote: >> > You've hit the proverbial nail with the hammer. The problem is that my >> > application needs to run under both the Linux and Windows OSs, so while >> I >> > would love to use a nice sh, csh, or bash shell script. My hands are >> tied >> > because Windows does not provide such wonderful shells. >> >> *Provides*, no... neither does it provide Python, for what that's >> worth. But you can certainly get it (bash): >> >> http://win-bash.sourceforge.net/ >> >> I suppose it's not worth installing just for this purpose though... >> But you can provide with your application a DoS batch file that does >> exactly the same thing (in addition to a shell script). The user >> would quite intuitively use whichever were appropriate, or follow your >> provided directions otherwise. Or, the equivalent in (hopefully >> OS-agnostic) Python: >> >> import os, sys >> >> # I believe this gets the name of the root in all major OSes >> def root_dir(path): >> if os.path.dirname(path) == path: >> return path >> return (root_dir(os.path.dirname(path))) >> >> appname = >> root = root_dir(os.getcwd()) >> install_path = os.path.join(root, "usr") >> bin_path = os.path.join(install_path, "bin") >> os.environ["PATH"] = bin_path + os.pathsep + os.environ["PATH"] >> python_path = os.path.join(bin_path, "python") >> args = sys.argv[1:] >> args.insert(0, os.path.join(bin_path, appname)) >> args.insert(0, python_path) >> args.insert(0, python_path) >> os.execv(python_path, args) >> >> >> >> > > > -- > Aquil H. Abdullah > aquil.abdullah at gmail.com > -- Aquil H. Abdullah aquil.abdullah at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From elessar at nienna.org Thu Jul 31 15:04:05 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Thu, 31 Jul 2008 13:04:05 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <00a121b4$0$20313$c3e8da3@news.astraweb.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <00a121b4$0$20313$c3e8da3@news.astraweb.com> Message-ID: <48920CA5.7050705@nienna.org> Steven D'Aprano wrote: > On Wed, 30 Jul 2008 09:23:05 -0600, Matthew Fitzgibbons wrote: > >> If you're expecting a list (and only a list) >> then your point makes sense. 'if x' can get you into trouble if you >> _don't_ want its polymorphism. > > "if x" is hardly unique in that way. If you're expecting a list, and only > a list, "len(x) != 0" will get you in trouble if somebody passes a string > or a dictionary. I don't see any reason why we should single out "if x" > as dangerous in the face of invalid types. With the exception of the "is" > and "is not" operators, nothing in Python is guaranteed to work with any > imaginable object. Even print can fail, if the object's __str__ method > raises an exception. Forgot respond to this point. I heartily agree. :) I singled out 'if x' only because that's the specific example under scrutiny. I think you and I are pretty much in agreement. -Matt From paul at subsignal.org Sat Jul 19 10:29:38 2008 From: paul at subsignal.org (paul) Date: Sat, 19 Jul 2008 16:29:38 +0200 Subject: Help with displaying images in CherryPy In-Reply-To: <4881DFFB.5060306@preisshare.net> References: <4881DFFB.5060306@preisshare.net> Message-ID: David Lyon schrieb: ... > All I want is a sample configuration file that will allow me to display > a page with a jpeg on it. .... > This really should only take a few minutes for somebody who has done > this in CherryPy before and I would certainly appreciate the assistance > because it doesn't seem covered in any documentation that i could find. Whats wrong with this page? http://www.cherrypy.org/wiki/StaticContent cheers Paul From sri_annauni at yahoo.co.in Wed Jul 2 07:14:29 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Wed, 2 Jul 2008 16:44:29 +0530 (IST) Subject: How to pickle bound methods Message-ID: <13944.78626.qm@web7913.mail.in.yahoo.com> HI Peter, It works will for instance and class methods. But it doesn't work for static methods. Can you tel me how to pickle static methods as well?? Thanks, Srini ----- Original Message ---- From: Peter Otten <__peter__ at web.de> To: python-list at python.org Sent: Wednesday, 2 July, 2008 12:53:19 PM Subject: Re: How to pickle bound methods srinivasan srinivas wrote: > I would like?to know how to pickle a bound method?? $ cat pickle_method.py import copy_reg import new def make_instancemethod(inst, methodname): ? ? return getattr(inst, methodname) def pickle_instancemethod(method): ? ? return make_instancemethod, (method.im_self, method.im_func.__name__) copy_reg.pickle(new.instancemethod, pickle_instancemethod, make_instancemethod) if __name__ == "__main__": ? ? import pickle ? ? class A(object): ? ? ? ? def __init__(self, who): ? ? ? ? ? ? self.who = who ? ? ? ? def alpha(self): ? ? ? ? ? ? print "Hello,", self.who ? ? FILENAME = "method.pickle" ? ? import sys ? ? args = sys.argv[1:] ? ? if args: ? ? ? ? a = A(args[0]) ? ? ? ? m = a.alpha ? ? ? ? pickle.dump(m, open(FILENAME, "wb")) ? ? else: ? ? ? ? m = pickle.load(open(FILENAME, "rb")) ? ? ? ? m() $ python pickle_method.py world $ python pickle_method.py Hello, world $ python pickle_method.py Srini $ python pickle_method.py Hello, Srini Peter -- http://mail.python.org/mailman/listinfo/python-list Bring your gang together. Do your thing. Find your favourite Yahoo! group at http://in.promos.yahoo.com/groups/ From guilhem.faure at gmail.com Wed Jul 23 03:33:07 2008 From: guilhem.faure at gmail.com (Guilhem Faure) Date: Wed, 23 Jul 2008 08:33:07 +0100 Subject: mean of arobase in python Message-ID: <7c49f36f0807230033k40722abfwdb28c34d3d88a32a@mail.gmail.com> Hello, What means @ in python ? In this script for exemple (this script return an error in my konsole...) @f1(arg) @f2 def func(): pass I see several script where used this symbol but I can't understand. G -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Tue Jul 29 13:59:25 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 10:59:25 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: <3a5fb076-c58a-45cf-80bb-e9fd4aab8276@v13g2000pro.googlegroups.com> On Jul 29, 5:27 am, Steven D'Aprano wrote: > On Tue, 29 Jul 2008 01:37:45 -0700, Carl Banks wrote: > > I would accept as "evidence" something that satisfies my criteria, which > > your example did not: it could have easily (and more robustly) been > > written with a simple explicit test. > > Only at the cost of completely ignoring the functional requirements and > changing the API. In other words: you ignore my code, and invent your own > imaginary code that does something completely different, then say that > this imaginary code is better. And, BTW, you keep making unsubstantiated assertions and keep expecting me to take them at face value. I'm really not going to take your word for it that your "functional requirements" would preclude the possibility of rewriting it as I said to, unless you provide details. Also, your third claim is false since it would have exactly the same behavior. Carl Banks From guilhem.faure at gmail.com Fri Jul 25 04:29:19 2008 From: guilhem.faure at gmail.com (Guilhem Faure) Date: Fri, 25 Jul 2008 10:29:19 +0200 Subject: 2d graphics - what module to use? In-Reply-To: <5519ca3a-bef6-4673-981a-fb327425cfee@w39g2000prb.googlegroups.com> References: <5519ca3a-bef6-4673-981a-fb327425cfee@w39g2000prb.googlegroups.com> Message-ID: <7c49f36f0807250129p4a5e892fie80d6661a12bcd8a@mail.gmail.com> You can try R cran also. Very powerfull and free. And with R you can use Rpy, a library R for python and can access to R function and R graph in a python script. Other mathematic library exist in python : Matplotlib for exemple. Summary : to draw graph easely in python : Rpy lib or Matplotlib. If you don't know R language (vectorial language) use Matplotlib. Adress : R site : http://cran.r-project.org/ Rpy lib for python : http://rpy.sourceforge.net/ Matplotlib for python : http://matplotlib.sourceforge.net/ On 7/25/08, King wrote: > > Use python's default GUI tkinter's drawing functions or you can use > wxPython GUI kit or you can use pyopengl. > If you are only interested to draw sin waves or math functions that > you should give try to matlab at www.mathworks.com > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Russ.Paielli at gmail.com Sun Jul 27 22:52:55 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 19:52:55 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <7eabe5a6-357a-4255-a958-0804959ce844@a6g2000prm.googlegroups.com> <009cf838$0$20302$c3e8da3@news.astraweb.com> Message-ID: On Jul 27, 3:54 pm, Steven D'Aprano wrote: > On Sun, 27 Jul 2008 12:33:16 -0700, Russ P. wrote: > > On Jul 27, 1:19 am, Steven D'Aprano > cybersource.com.au> wrote: > >> On Sat, 26 Jul 2008 17:14:46 -0700, Russ P. wrote: > > >> > You take the name down to a single letter. As I suggested in an > >> > earlier post on this thread, why not take it down to zero letters? > > >> The question isn't "why not", but "why". The status quo works well as > >> it is, even if it isn't perfect. Prove that implicit self is a good > >> idea -- or at least prove that it is an idea worth considering. > > >> "I don't like typing self" doesn't convince me. The same argument could > >> be made typing parentheses, colons, commas, etc. We could end up with > >> something like this: > > >> class Foo base > >> def method x y z > >> .args = list x y z > > >> That's not necessarily wrong, but it's not Python. > > > And what does that have to do with my suggestion? Absolutely nothing. > > Not at all. You're suggesting a change to Python's syntax. I've suggested > a couple more changes to Python syntax. I don't intend them to be taken > seriously, but only to illustrate a point that syntax defines how a > language is written. You want to change that. But the syntax change I am suggesting is trivial compared to the draconian examples you gave. > > It's a red herring that you seem to be using to obscure the fact that > > you have no rational argument to make. > > I don't have to make a rational argument for keeping the status quo. That > status quo just *is*. You want people to change, you need to convince > them that such a change is not just "not bad" but a serious advantage, > enough to make up for all the work required to implement it. > I'm listening. Tell me why removing self if not merely harmless, but > actively better. > > [...] I thought I did just that. I am very meticulous about the appearance of my code, and the less cluttered the better. That's one of the main reasons that I use Python. My suggestion would be relatively trivial to implement, yet it would dramatically reduce clutter. You may not agree, but I think the case is strong. > >> By "better" do you mean "uglier"? If so, I agree with you. If not, then > >> I disagree that it is better. > > > You seem to be freaked out by an empty argument. Actually, it bothers me > > a bit too, which is why I suggested that a period could be used as the > > first argument to indicate that, like Clint Eastwood in The Good, the > > Bad, and the Ugly, "self" had no name here. > > Well there you go now. How should we *talk* about this piece of code? Try > writing a comment or docstring, or even sitting down with a fellow > programmer and discussing it. What do you call this implicit Object With > No Name? How do Java and C++ programmers talk about the instance for which the method was called? I wasn't aware that that was a problem for them. > def fun( , cat): > .cat = cat # assumes that the Object With No Name has foo > > versus > > def fun(self, cat): > self.cat = cat # assumes that self has foo > > Before you suggest that people will continue to call the first argument > "self" but just not write it down anywhere, I suggest that's a terrible > idea and one which will confuse a lot of people. "Where's this 'self' > defined? I can't find it anywhere!" Any programmer who can't get past that point needs to find a new line of work -- such as moving furniture. > A slightly better suggestion is "the instance", but that fails here: > > class C(object): > def method(, other): > assert isinstance(other, C) > .cat = other # assumes that the instance has foo > # er, that is to say, the implicit instance, > # not the other instance > > The ability to talk easily about the code is invaluable. Implicit self > makes it harder to talk about the code. I can only imagine what you must think about lambda functions and list comprehensions. > [...] > > >> Even uglier than the first. Convince me there's a benefit. > > > Actually, I think it's elegant. And I'll bet that if Guido had suggested > > it, you would think it was beautiful. > > Oh please. I think the syntax for ternary if is ugly, and Guido came up > with that, and it doesn't even use punctuation. Off topic, but I happen to like Guido's ternary "if." I use it wherever I can, within reason. > > Why force a name to be used when none is needed? > > But a name is needed. > > class Foo(base1, base2, base3): > def meth(self, arg): > super(Foo, self).meth(arg) > print self > try: > value = _cache[self] > except KeyError: > value = some_long_calculation(self) > > How do you pass self to arbitrary functions without a name? I didn't say you *never* need the name. If you need it, then use it. But if you don't need it, you shouldn't be forced to use a name just for the sake of having a name. From tjreedy at udel.edu Sat Jul 26 17:25:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 17:25:02 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87k5f8afjl.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> Message-ID: Torsten Bronger wrote: > Hall?chen! > > D'Arcy J.M. Cain writes: > >> On Sat, 26 Jul 2008 09:45:21 +0200 >> Torsten Bronger wrote: >> >>> Of course, "self" would have to become a reserved word. You >>> could say that this may break some code, but I don't see much >>> freedom >> Isn't this a showstopper all by itself? > > Yes. But I've seen no code that uses some other word. There is a lot of code you have not seen. Really. In informal code I use 's' and 'o' for 'self' and 'other'. I don't usually post such because it is not considered polite. So you have seen a biased sample of the universe. From skip at pobox.com Tue Jul 22 14:52:50 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 22 Jul 2008 13:52:50 -0500 Subject: software engineering foundations? Message-ID: <18566.11394.326317.821553@montanaro-dyndns-org.local> Sorry for the off-topic-ish post. My son (a fairly junior sysadmin type) mentioned to me today that he was looking for online courses for Perl. (I don't hold that against him. Perl is still a lingua franca in the sysadmin realm.) In my work I have from time-to-time had to pick up and maintain scripts (generally shell/Python stuff) which non-professional programmers have written. It's never what you would call a "pleasant" task. There are software construction skills which are entirely distinct from the language in which you are programming. We can tout object-oriented, structured programming, test-driven development or other software engineering techniques, but there is a body of knowledge out there which is orthogonal to the language in which the code is written. People who are not professional programmers often lack those skills and their code shows it. Are there any good online resources for this "software structure" axis? Googling for "object oriented programming tutorial" yields a bunch of stuff, much of it language-specific. I'm trying to find something a bit more general than that though. I Googled for "software engineering tutorial" as well. Most of the early hits were either inaccessible (ACM subscription only) or contents-like stuff (conference announcements, for example). Number eight on the list was this rather promising page: http://www.cmcrossroads.com/bradapp/links/swe-links.html It was last updated over 10 years ago. I find it hard to believe that so little has changed in that time that some other page with more recent references hasn't percolated to the top of Google's page rank! After all, the Web has grown just a tad in that timeframe. I have a sneaking suspicion that what I'm looking for is out there, but that I'm not asking Google in the right manner. Any and all pointers/suggestions cheerfully accepted. Thx, -- Skip Montanaro - skip at pobox.com - http://www.webfast.com/~skip/ ------ ELON MUSK: If fuel cells were good, don't think you'd see them somewhere, like maybe in a laptop or a cell phone or a $200 million military satellite maybe? And yet, where do you see them? SPENCER MICHELS: You don't. ELON MUSK: Exactly. From ron.longo at cox.net Wed Jul 16 12:00:43 2008 From: ron.longo at cox.net (Ron Longo) Date: Wed, 16 Jul 2008 12:00:43 -0400 Subject: Is there any interest in working on an application? Message-ID: <005501c8e75d$1a06b0c0$6601a8c0@aristotle> Hello, I have an python application which I've been developing for several years (off and on, mostly off for lack of time) which I'm considering putting up to open source if I can find other developers interested in contributing. The application is a web publisher/information outliner. (See an example of a beta here: http://members.cox.net/ronpro/welcome.html where I test my ability to generate an interactive tree for the data in an outline.) The application is 100% Python. The gui is written using Tkinter and Tix -- I'm definitely open to other libraries for the GUI. The app supports unicode in the outlines. There's a spell-checker plugin (complements of the pyenchant project). The application is written on top of an application framework and plugin framework both of which I developed myself. Much of the application is actually plugins so it's very modular. For screen shots of the app so far see: http://members.cox.net/ronpro/scrnCap1.JPG and http://members.cox.net/ronpro/scrnCap2.JPG The development would probably be done through SourceForge. I'm in the process of documenting the current design in UML class diagrams using the free version of Visual Paradigm (if another tool is suggested we could switch). My motive: I'm a research scientist. My prefered method to record, review, edit and organize my notes is within an outline (rather than a flat notebook format used by most researchers). The ability to consider new ideas can be as easy as moving items around in the outline. I've used many commercial programs in the past but all have had some limitation or another. Most don't support unicode (I need unicode characters to record mathematical and logical formulae). Those that do produce html don't produce the side-by-side view of an interactive tree (able to expand or collapse nodes) beside the actual on-screen notes. The interactive tree is a necessity for me with over 2000 entries in my largest outline and growing fast. Design Philosophy: I've attempted to keep to the following design philosophy (prioritized by order). - User Experience -- everything should be easy for the user. - OO, Maximize modularity, minimize cross dependence. (e.g. The Application framework, plugin framework and word processor know nothing about the problem domain and nothing about the other modules in the application). - KISS, I prefer simple straightforward code over speedy "tricks". If it's hard to read or understand I'll probably hate it. - Minimize 3rd party modules in the core application. I know 3rd party libs can make it easier to develop and this would seem to violate KISS. However, with User Experience being higher priority, the less there is for a user to install the easier. Best case, the user installs Python and s/he's ready to go. I don't mind requiring 3rd party libs for most plugins. My take on this is here: - If it's part of the core distribution (the core application or a plugin that's part of the main distribution), do everything possible to avoid 3rd party libs. - For plugins distributed separately from the application installer, the plugin must check for the required libs upon loading and exit gracefully if the lib is not present (at most display a dialog stating that the required lib is not installed.) - If at all possible, provide unit test with each module (including plugins) Future Direction: - Some of the features in the menus and on the toolbars are not yet implemented. (e.g. find, search/replace, bulletized and numbered lists, tables) - The content of any tree entry is displayed in the content pane to the right of the outline. Right now the only supported content is formatted text in a word processor (actually a glorified Text widget). The Text widget is part of the core app. I want this widget to be turned into a plugin so that other kinds of content are possible with other content editor plugins. The main app would then select and display the appropriate content editor for a given kind of data. - Currently, cutting and pasting is possible, however cutting and pasing formatted text is only possible within the application. Want to support cutting and pasing stylized text with the system clipboard and other applications (word, star office, etc.) - Import export other formats (importers and exporters are already plugins). We just need to write more of them. - Support multiple views of a single outline so we can view different parts of the outline simultaneously. - Support cutting and pasting, dragging and dropping across different outlines. - Customizable appearance for HTML output. - Anything else the development group or users can think of. If you're interested in more information or trying out this app (note that it's very immature and probably only worthy of being called an alpa) please don't hesitate to contact me. Thanks for reading, Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From piet at cs.uu.nl Thu Jul 10 04:42:18 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 10 Jul 2008 10:42:18 +0200 Subject: Terminate a python script from linux shell / bash script References: Message-ID: >>>>> Gros Bedo (GB) wrote: >GB> I have a question about Python and Linux shell. I have a python >GB> program which is permanently resident in the end-user system. I'm >GB> currently producing a RPM package, and it works nicely. The problem is >GB> that when I uninstall it, my program keeps running in the background, >GB> even if the files are deleted. >GB> I know I can terminate python shell directly, but this is not a good >GB> idea because the end-user may be working with another important python >GB> application, and would be very angry if mine would close everything >GB> that is using python shell. That's not how it works. If you kill one running python script it will not effect other python scripts. Each script has its own interpreter process running. >GB> So, is there a way from the Linux shell or a bash script to terminate >GB> just one specific Python script ? So just kill it. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From mal at egenix.com Thu Jul 31 06:24:57 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 31 Jul 2008 12:24:57 +0200 Subject: Optimizing size of very large dictionaries In-Reply-To: <1217464179.31710.1266222419@webmail.messagingengine.com> References: <1217464179.31710.1266222419@webmail.messagingengine.com> Message-ID: <489192F9.3030005@egenix.com> On 2008-07-31 02:29, python at bdurham.com wrote: > Are there any techniques I can use to strip a dictionary data > structure down to the smallest memory overhead possible? > > I'm working on a project where my available RAM is limited to 2G > and I would like to use very large dictionaries vs. a traditional > database. > > Background: I'm trying to identify duplicate records in very > large text based transaction logs. I'm detecting duplicate > records by creating a SHA1 checksum of each record and using this > checksum as a dictionary key. This works great except for several > files whose size is such that their associated checksum > dictionaries are too big for my workstation's 2G of RAM. If you don't have a problem with taking a small performance hit, then I'd suggest to have a look at mxBeeBase, which is an on-disk dictionary implementation: http://www.egenix.com/products/python/mxBase/mxBeeBase/ Of course, you could also use a database table for this. Together with a proper index that should work as well (but it's likely slower than mxBeeBase). -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 31 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From fredrik at pythonware.com Tue Jul 22 17:49:00 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 23:49:00 +0200 Subject: Iterating Through List or Tuple In-Reply-To: References: Message-ID: Samir wrote: > Is there a way to loop or iterate through a list/tuple in such a way > that when you reach the end, you start over at the beginning? For > example, suppose I define a list "daysOfWeek" such that: > >>>> daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] >>> import itertools >>> help(itertools.cycle) Help on class cycle in module itertools: class cycle(__builtin__.object) | cycle(iterable) --> cycle object | | Return elements from the iterable until it is exhausted. | Then repeat the sequence indefinitely. ... >>> L = [1, 2, 3] >>> for i, x in enumerate(itertools.cycle(L)): ... print i, x ... if i >= 10: ... break ... 0 1 1 2 2 3 3 1 4 2 5 3 6 1 7 2 8 3 9 1 10 2 >>> From mccredie at gmail.com Thu Jul 24 16:02:41 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 24 Jul 2008 13:02:41 -0700 (PDT) Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: On Jul 24, 2:54?am, Lawrence D'Oliveiro wrote: > In message > , > > Matimus wrote: > > That isn't the standard. With that setup tabs will show up as 4 > > spaces, and still confuse you. > > Why should that be confusing? The most common tab-stop setting is 4 columns. I think if you continued reading my post you would see. The tabstop feature in Vi(m) sets how many spaces a tab character is displayed as. A tab character is specified as 8 spaces. The real problem is that the python interpreter itself follows the spec and interprets a tab as 8 spaces. If you are viewing the code and have mixed tabs and spaces and all of the tabs are showing up as 4 spaces you will not be able to spot the issues that will come up. 4 columns is not the most common setting, the most common setting is the default, which is 8. It is just very common for people to change it. I suggest that instead of changing the tabstop, just use spaces (not both) and use the `softtabstop` setting to allow a press of the tab key to insert four spaces instead. Matt From gnuarm at gmail.com Sun Jul 13 09:25:34 2008 From: gnuarm at gmail.com (rickman) Date: Sun, 13 Jul 2008 06:25:34 -0700 (PDT) Subject: spam References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> Message-ID: <1bc1ddbb-fbfc-4e0c-8337-71d2dd301e5d@z66g2000hsc.googlegroups.com> On Jul 12, 9:21 am, Scott in SoCal wrote: > In message > , > > rickman wrote: > >spam > > *PLONK!* I love the way that people who plonk others feel the need to inform everyone of it. That ranks up there with, "I know what you are, but what am I?" From wuwei23 at gmail.com Sun Jul 27 23:25:52 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 27 Jul 2008 20:25:52 -0700 (PDT) Subject: I love "shelf" BUT References: Message-ID: <1c2d28bb-06e8-4f02-a528-9d86f84366dd@n33g2000pri.googlegroups.com> On Jul 28, 12:46?pm, Sera Jackson wrote: > ok, I know its an over discussed topic. Althought I understand why it > is there I cant constantly see it in my argument list in parenthesis. > > can someone give me an insight of the cons of a syntax like this: > class Class: > ? ? def self.method(arguments): > ? ? ? ? etc, etc > > In other words def method(self, arg1, arg2 ,argN) becomes-> ?def > self.method(arg1, arg2 ,argN) Did you bother to check the group? You would've noticed it's being discussed -right now-: http://groups.google.com/group/comp.lang.python/browse_frm/thread/a5fa8ff0ffadd6ee/60e9dd04719e439a And this -exact- suggestion has been turned down by Guido: http://mail.python.org/pipermail/python-3000/2006-April/000793.html From bearophileHUGS at lycos.com Fri Jul 18 08:40:20 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 18 Jul 2008 05:40:20 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: Peter Otten: > PS: Take these numbers with a grain of salt, they vary a lot between runs. Another possibility :-) from itertools import imap id(x) in imap(id, items) >If you want efficiency you should use a dictionary instead of the list anyway: I agree, but sometimes you have few items to look for, so building the whole dict (that requires memory too) may be a waste of time. In theory this may be faster to build, but in practice you need a benchmark: ids = set(imap(id, items)) followed by: id(x) in ids Bye, bearophile From timr at probo.com Fri Jul 18 02:13:35 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 18 Jul 2008 06:13:35 GMT Subject: How can i use a variable without define it ? References: <87k5fm2p1x.fsf@benfinney.id.au> <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> <87fxqa2mu0.fsf@benfinney.id.au> <5dd91053-d239-4ff1-b693-d6afedf6bf24@x35g2000hsb.googlegroups.com> Message-ID: zhw wrote: >Ben Finney >wrote: >> >> What problem are you trying to solve? > >I an sorry, I can't tell you. That's nonsense. No one is asking you to reveal the design of your company's next product. However, you have some overall problem you are trying to solve, and you have focused in on one POSSIBLE solution. Instead, tell us about the PROBLEM, and we'll offer good solutions. >If you can't give a solution, just ignore it! NO ONE will be able to give you a solution, because you have not described the problem. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dylanwilson at ymail.com Fri Jul 18 13:33:52 2008 From: dylanwilson at ymail.com (Dylan Wilson) Date: Fri, 18 Jul 2008 10:33:52 -0700 (PDT) Subject: file() Message-ID: <191300.25030.qm@web59610.mail.ac4.yahoo.com> well, I'm in the beginings of making a random sentence generator for a mod my friend makes, but I want the nouns, verbs pastverbs, etc. to be easily customizable by editing a file, but, last night file() worked fine and today it's saying " line 1: `read_who = file('who.ini', 'r')'" here's what I have so far, but for reference it's possible I'm just being an idiot because I'm very new to Python and programming in general read_who = file('who.ini', 'r') who = read_who.read() read_what = file('what.ini', 'r') what = read_what.read() read_end = file('end.ini', 'r') end = read_end.read() read_because = file('because.ini', 'r') because = read_because.read() read_the = file('the.ini', 'r') da = read_the.read() read_period = file('punc.ini', 'r') period = read_period.read() prd = read_period.read() read_nouns = file('nouns.ini', 'r') nouns = read_nouns.read() read_verbs = file('verbs.ini', 'r') verbs = read_verbs.read() read_pastverbs = file('pastverbs.ini', 'r') pastverbs = read_pastverbs.read() -------------- next part -------------- An HTML attachment was scrubbed... URL: From dbpokorny at gmail.com Tue Jul 1 17:54:44 2008 From: dbpokorny at gmail.com (dbpokorny at gmail.com) Date: Tue, 1 Jul 2008 14:54:44 -0700 (PDT) Subject: How to make a function associated with a class? References: <69e26f9b-2f00-4318-9bc5-6aa94e141bca@59g2000hsb.googlegroups.com> <4d7cf477-e791-4122-bc20-0dbd1a16bc12@j22g2000hsf.googlegroups.com> <0d9c534b-8720-4363-b3e5-eb546dd3637c@8g2000hse.googlegroups.com> Message-ID: <607e76b4-d38f-43c4-8cc3-8c510c1785d2@u6g2000prc.googlegroups.com> On Jul 1, 2:24 pm, Kurda Yon wrote: > > By the way, "type(self)" returns the name of the class to which the > "self" belongs? > Does "instance" return "true" if the first argument belongs to the > class whose name is given in the second argument? $ python Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11) [GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> help(type) [...] >>> help(isinstance) [...] From ki4yjl at gmail.com Thu Jul 10 23:22:16 2008 From: ki4yjl at gmail.com (WDC) Date: Thu, 10 Jul 2008 20:22:16 -0700 (PDT) Subject: paypal wholesale men jordans 17 (paypal accept)(www super-saler com References: Message-ID: <5d746374-d2a0-411e-bf60-87256a219b7c@m44g2000hsc.googlegroups.com> On Jul 10, 10:33?pm, 128 wrote: > paypal wholesale men jordans (paypal accept)(www super-saler com > > paypal wholesale men jordans 1 (paypal accept)(www super-saler com > > paypal wholesale men jordans 2 (paypal accept)(www super-saler com > > paypal wholesale men jordans 3 (paypal accept)(www super-saler com > > paypal wholesale men jordans 4 (paypal accept)(www super-saler com > > paypal wholesale men jordans 5 (paypal accept)(www super-saler com > > paypal wholesale men jordans 6 (paypal accept)(www super-saler com > > paypal wholesale men jordans 7 (paypal accept)(www super-saler com > > paypal wholesale men jordans 8 (paypal accept)(www super-saler com > > paypal wholesale men jordans 9 (paypal accept)(www super-saler com > > paypal wholesale men jordans 10 (paypal accept)(www super-saler com > > paypal wholesale men jordans 11 (paypal accept)(www super-saler com > > paypal wholesale men jordans 12 (paypal accept)(www super-saler com > > paypal wholesale men jordans 13 (paypal accept)(www super-saler com > > paypal wholesale men jordans 14 (paypal accept)(www super-saler com > > paypal wholesale men jordans 15 (paypal accept)(www super-saler com > > paypal wholesale men jordans 16 (paypal accept)(www super-saler com > > paypal wholesale men jordans 17 (paypal accept)(www super-saler com > > paypal wholesale men jordans (paypal accept)(www super-saler com > > paypal wholesale men jordans 1 (paypal accept)(www super-saler com > > paypal wholesale men jordans 2 (paypal accept)(www super-saler com > > paypal wholesale men jordans 3 (paypal accept)(www super-saler com > > paypal wholesale men jordans 4 (paypal accept)(www super-saler com > > paypal wholesale men jordans 5 (paypal accept)(www super-saler com > > paypal wholesale men jordans 6 (paypal accept)(www super-saler com > > paypal wholesale men jordans 7 (paypal accept)(www super-saler com > > paypal wholesale men jordans 8 (paypal accept)(www super-saler com > > paypal wholesale men jordans 9 (paypal accept)(www super-saler com > > paypal wholesale men jordans 10 (paypal accept)(www super-saler com > > paypal wholesale men jordans 11 (paypal accept)(www super-saler com > > paypal wholesale men jordans 12 (paypal accept)(www super-saler com > > paypal wholesale men jordans 13 (paypal accept)(www super-saler com > > paypal wholesale men jordans 14 (paypal accept)(www super-saler com > > paypal wholesale men jordans 15 (paypal accept)(www super-saler com > > paypal wholesale men jordans 16 (paypal accept)(www super-saler com > > paypal wholesale men jordans 17 (paypal accept)(www super-saler com > > paypal wholesale men jordans (paypal accept)(www super-saler com > > paypal wholesale men jordans 1 (paypal accept)(www super-saler com > > paypal wholesale men jordans 2 (paypal accept)(www super-saler com > > paypal wholesale men jordans 3 (paypal accept)(www super-saler com > > paypal wholesale men jordans 4 (paypal accept)(www super-saler com > > paypal wholesale men jordans 5 (paypal accept)(www super-saler com > > paypal wholesale men jordans 6 (paypal accept)(www super-saler com > > paypal wholesale men jordans 7 (paypal accept)(www super-saler com > > paypal wholesale men jordans 8 (paypal accept)(www super-saler com > > paypal wholesale men jordans 9 (paypal accept)(www super-saler com > > paypal wholesale men jordans 10 (paypal accept)(www super-saler com > > paypal wholesale men jordans 11 (paypal accept)(www super-saler com > > paypal wholesale men jordans 12 (paypal accept)(www super-saler com > > paypal wholesale men jordans 13 (paypal accept)(www super-saler com > > paypal wholesale men jordans 14 (paypal accept)(www super-saler com > > paypal wholesale men jordans 15 (paypal accept)(www super-saler com > > paypal wholesale men jordans 16 (paypal accept)(www super-saler com > > paypal wholesale men jordans 17 (paypal accept)(www super-saler com > > paypal wholesale men jordans (paypal accept)(www super-saler com > > paypal wholesale men jordans 1 (paypal accept)(www super-saler com > > paypal wholesale men jordans 2 (paypal accept)(www super-saler com > > paypal wholesale men jordans 3 (paypal accept)(www super-saler com > > paypal wholesale men jordans 4 (paypal accept)(www super-saler com > > paypal wholesale men jordans 5 (paypal accept)(www super-saler com > > paypal wholesale men jordans 6 (paypal accept)(www super-saler com > > paypal wholesale men jordans 7 (paypal accept)(www super-saler com > > paypal wholesale men jordans 8 (paypal accept)(www super-saler com > > paypal wholesale men jordans 9 (paypal accept)(www super-saler com > > paypal wholesale men jordans 10 (paypal accept)(www super-saler com > > paypal wholesale men jordans 11 (paypal accept)(www super-saler com > > paypal wholesale men jordans 12 (paypal accept)(www super-saler com > > paypal wholesale men jordans 13 (paypal accept)(www super-saler com > > paypal wholesale men jordans 14 (paypal accept)(www super-saler com > > paypal wholesale men jordans 15 (paypal accept)(www super-saler com > > paypal wholesale men jordans 16 (paypal accept)(www super-saler com > > paypal wholesale men jordans 17 (paypal accept)(www super-saler com > > paypal wholesale men jordans 18 (paypal accept)(www super-saler com > > paypal wholesale men jordans 19 (paypal accept)(www super-saler com > > paypal wholesale men jordans 20 (paypal accept)(www super-saler com > > paypal wholesale men jordans 21 (paypal accept)(www super-saler com > > paypal wholesale men jordans 22 (paypal accept)(www super-saler com > > paypal wholesale men jordans 23 (paypal accept)(www super-saler com > > paypal wholesale men jordans (paypal accept)(www super-saler com > > paypal wholesale men jordans 1 (paypal accept)(www super-saler com > > paypal wholesale men jordans 2 (paypal accept)(www super-saler com > > paypal wholesale men jordans 3 (paypal accept)(www super-saler com > > paypal wholesale men jordans 4 (paypal accept)(www super-saler com > > paypal wholesale men jordans 5 (paypal accept)(www super-saler com > > paypal wholesale men jordans 6 (paypal accept)(www super-saler com > > paypal wholesale men jordans 7 (paypal accept)(www super-saler com > > paypal wholesale men jordans 8 (paypal accept)(www super-saler com > > paypal wholesale men jordans 9 (paypal accept)(www super-saler com > > paypal wholesale men jordans 10 (paypal accept)(www super-saler com > > paypal wholesale men jordans 11 (paypal accept)(www super-saler com > > paypal wholesale men jordans 12 (paypal accept)(www super-saler com > > paypal wholesale men jordans 13 (paypal accept)(www super-saler com > > paypal wholesale men jordans 14 (paypal accept)(www super-saler com > > paypal wholesale men jordans 15 (paypal accept)(www super-saler com > > paypal wholesale men jordans 16 (paypal accept)(www super-saler com > > paypal wholesale men jordans 17 (paypal accept)(www super-saler com > > paypal wholesale men jordans 18 (paypal accept)(www super-saler com > > paypal wholesale men jordans 19 (paypal accept)(www super-saler com > > paypal wholesale men jordans 20 (paypal accept)(www super-saler com > > paypal wholesale men jordans 21 (paypal accept)(www super-saler com > > paypal wholesale men jordans 22 (paypal accept)(www super-saler com > > paypal wholesale men jordans 23 (paypal accept)(www super-saler com > > paypal wholesale men jordans (paypal accept)(www super-saler com > > paypal wholesale men jordans 1 (paypal accept)(www super-saler com > > paypal wholesale men jordans 2 (paypal accept)(www super-saler com > > paypal wholesale men jordans 3 (paypal accept)(www super-saler com > > paypal wholesale men jordans 4 (paypal accept)(www super-saler com > > paypal wholesale men jordans 5 (paypal accept)(www super-saler com > > paypal wholesale men jordans 6 (paypal accept)(www super-saler com > > paypal wholesale men jordans 7 (paypal accept)(www super-saler com > > paypal wholesale men jordans 8 (paypal accept)(www super-saler com > > paypal wholesale men jordans 9 (paypal accept)(www super-saler com > > paypal wholesale men jordans 10 (paypal accept)(www super-saler com > > paypal wholesale men jordans 11 (paypal accept)(www super-saler com > > paypal wholesale men jordans 12 (paypal accept)(www super-saler com > > paypal wholesale men jordans 13 (paypal accept)(www super-saler com > > paypal wholesale men jordans 14 (paypal accept)(www super-saler com > > paypal wholesale men jordans 15 (paypal accept)(www super-saler com > > paypal wholesale men jordans 16 (paypal accept)(www super-saler com > > paypal wholesale men jordans 17 (paypal accept)(www super-saler com > > paypal wholesale men jordans 18 (paypal accept)(www super-saler com > > paypal wholesale men jordans 19 (paypal accept)(www super-saler com > > paypal wholesale men jordans 20 (paypal accept)(www super-saler com > > paypal wholesale men jordans 21 (paypal accept)(www super-saler com > > paypal wholesale men jordans 22 (paypal accept)(www super-saler com > > paypal wholesale men jordans 23 (paypal accept)(www super-saler com Is that spam i spy? From tim.tadh at gmail.com Tue Jul 29 11:22:52 2008 From: tim.tadh at gmail.com (Tim Henderson) Date: Tue, 29 Jul 2008 08:22:52 -0700 (PDT) Subject: Build tool for Python References: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Message-ID: On Jul 29, 11:08?am, Hussein B wrote: > Hi. > Apache Ant is the de facto building tool for Java (whether JSE, JEE > and JME) application. > With Ant you can do what ever you want: compile, generate docs, > generate code, packing, deploy, connecting to remote servers and every > thing. > Do we have such a tool for Python projects? > Thank you. You might want to take a look at Paver. http://www.blueskyonmars.com/projects/paver/ Tim From mail at timgolden.me.uk Tue Jul 29 09:12:37 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 29 Jul 2008 14:12:37 +0100 Subject: Windows Interpreter In-Reply-To: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> References: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> Message-ID: <488F1745.4020705@timgolden.me.uk> Victor Subervi wrote: > Hi: > I would like to make my windows python interpreter work like my linux > one. I want to be able to cut and paste multiple lines of code. You can already do this: what are you trying which isn't working? > Now I can only paste one line at a time. > I do not want it to indent > automatically. How can I change this? I realise this is a difficult thing to describe in words, but I regularly cut and paste multiple lines of code into my Python interpreter and it doesn't indent automatically. Can you give some specific examples of what you do and what does or doesn't work? TJG From babacity4 at gmail.com Thu Jul 24 16:52:55 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:52:55 -0700 (PDT) Subject: Xxxstash com - Amazing porn video collection Message-ID: <38c1e2dd-20c0-47b5-8976-b13cc96c6b69@x29g2000prd.googlegroups.com> xxxstash com . >>>>>>>>>>Best Collection of Xxxstash Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE xxxstash com VIDEOS<<<<<<<<<<< . xxxstash com From norseman at hughes.net Mon Jul 21 17:14:27 2008 From: norseman at hughes.net (norseman) Date: Mon, 21 Jul 2008 14:14:27 -0700 Subject: Importing different versions of a module In-Reply-To: <8b51e78c0807181750x66fd0372y82367245630e921f@mail.gmail.com> References: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> <48811064.5010603@hughes.net> <8b51e78c0807181750x66fd0372y82367245630e921f@mail.gmail.com> Message-ID: <4884FC33.2090006@hughes.net> mercado mercado wrote: > Thanks norseman for the reply. > > You're right that I didn't like it though. :-) > > Also note that my original question has to do with importing modules from > different locations. If all I had to do was use different paths within the > script (e.g. for sending to os.path.join or whatever), then I could just put > those in a config file. That's not a problem... > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list =================================== I started to import a module using its path and now see what you mean. Python is missing the concept: Programmer dictates what machine does. (I come from assembly. If the hardware can do it, so can I.) sys.path can be modified to switch between file sets (prod/test). if a global is set one way, use the normal paths, if set another, modify the needed to force the test_section into use. Unfortunately this is not much of an answer. It means hardcoding two paths into globals and using a third to control which is used. Since Python has a habit of coming and going on its own this may not work in a major effort. It may unload something and later reload with the sys.path set wrong. Docs say it will reload file that did load originally even if the file was modified between loads. Docs do not say it keeps original location. I'll need some time to set things up to test what it does. Nothing I've done in Python had bumped into your problem until I ran the test. Never dawned on me it would be this stupid. I had intended to use Python to talk to ESRI products and my stuff. I made a few minor routines just to get used to Python and was starting to tackle the real problem. My assembly, C, fortran & bash scripts all work as expected. They do, Python doesn't. ORIGINALLY, IN THIS REPLY, I HAD STARTED TO SAY: I've used this before. Maybe it will work in Python, maybe not. Global sets which section to use by being a prefix to each test module name. Something like "my_" for test and empty otherwise. global WHICH WHICH='my_' import WHICH+'subrtn' WHICH='' import WHICH+'subrtn2' gets my_subrtn from the test suite and gets subrtn2 from the production section. Each module would thus need to store/reset the Global's value upon init to be used in its own imports since it's status at any given time is in question. Python docs say Python keeps the original name of the originally successfully loaded file. The built-in 'reload' can get it back, even if it has been changed (edited) during the session. The files my_ whatever have the my_ removed from the disk name when they go production. ######################################################### BUT!!!! import WILL NOT TAKE VARS!!!!!!!! ######################################################### OK check#1 Python 2.5.2 (r252:60911, Mar 4 2008, 10:40:55) [GCC 3.3.6] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> WHICH="my_" >>> import WHICH+"popen2" File "", line 1 import WHICH+"popen2" ^ SyntaxError: invalid syntax >>> OK check#2 >>> >>> x=WHICH+"open2" >>> x 'my_open2' >>> import x Traceback (most recent call last): File "", line 1, in ImportError: No module named x >>> OK check#3 >>> >>> help(x) no Python documentation found for 'my_open2' #true, proves x OK >>> BOY-O-BOY, DOES THAT SCREW THE POOCH!!!! Mercado, like you, I'm not very happy right now. This means that prefixing cannot be used to control imports. For decades I have used prefixing in both scripts and compiled lib routines for controlling what gets loaded or not. Right now I'm not a happy Python camper, not at all. Steve norseman at hughes.net From bj_666 at gmx.net Sun Jul 27 10:50:04 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jul 2008 14:50:04 GMT Subject: Rant (was Re: x*x if x>10 References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> Message-ID: <6f3g8rF9gfj0U1@mid.uni-berlin.de> On Sun, 27 Jul 2008 16:41:19 +0200, Diez B. Roggisch wrote: > DaveM schrieb: >> Getting back to the >> list concatenation, I finally found the itertools.chain command which >> is the most compact and fastest (or second fastest by a trivial amount, >> I can't remember which). Along the way, I must have tried/used half a >> dozen methods, ...which brings me back my initial PERL comment. There's >> more than one way to do it in Python, too. > > Any non-trivial task has that property. I don't know enough perl to have > an example ready that shows something that python has only one way of > doing and perl has several. > > But I *do* know that taking the python zen literally is fruitless. I think it should be taken more literally than the wrong reduction to "there should be only one way". People tend to forget "obvious" and "preferably" all the time. Ciao, Marc 'BlackJack' Rintsch From zentraders at gmail.com Mon Jul 7 22:15:56 2008 From: zentraders at gmail.com (Zentrader) Date: Mon, 7 Jul 2008 19:15:56 -0700 (PDT) Subject: conflict between multiple installs of python (linux) References: <6bd22c06-a1e6-4247-9aff-2d0b29b1ec5e@d1g2000hsg.googlegroups.com> Message-ID: <7435a7c3-78b7-4339-a980-0d0ff3f34a5a@y38g2000hsy.googlegroups.com> On Jul 5, 11:09 am, david wrote: > You learn something new every day: > > On my ubuntu, update-manager is supposed to use the python2.5 > installed on /usr/bin. Well, I had subsequently installed a whole > bunch of stuff in /usr/local (/usr/local/bin/python and /usr/local/lib/ > python2.5 etc), which I have happily been using for development for a > year. I had thought that the two pythons were completely independent. > > Well, I was wrong. When /usr/bin/python2.5 runs, *by default*, it > adds /usr/local/lib/python2.5 to its sys path - and apparently there > are things in /usr/local which are inconsistent with those at /usr > (not suprising). > > I have fixed the problem - but I had to modify the actual update- > manager .py file itself. At the beginning, I set the sys.path in > python *explicitly* to not include the /usr/local stuff. > > But this is clearly a kludge. My question: how do I keep the Ubuntu > python stuff at /usr/bin/python2.5 from adding /usr/local/lib/ > python2.5 to the import search path in a clean and global way? I > really want both pythons completely isolated from one another! > > Thankyou. When you install a second version, let us say Python3.0, you want to download the source and do the normal config and make but not make install. Instead do a make altinstall. They will be kept separate. I have Ubuntu's 2.5 as well as 3.0. Ubuntu installs to /usr/bin and / usr/lib, so I installed 3.0 from /usr/local/Python-3.0 and those files installed into /usr/local/bin and lib and the executable is python3.0. Take a look at the README file that comes with the source code for other options. From jeffober at gmail.com Tue Jul 22 08:44:56 2008 From: jeffober at gmail.com (Jeff) Date: Tue, 22 Jul 2008 05:44:56 -0700 (PDT) Subject: simple question about dictionaries References: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> <8aedc744-f432-4a4a-a6e4-2bb714caf720@x35g2000hsb.googlegroups.com> Message-ID: On Jul 21, 8:14?am, Fredrik Lundh wrote: > Jeff wrote: > > ? throw KeyError('%s not found' % str(val)) > > "throw"? ?and shouldn't that be a ValueError? ;-) > > Whoops. Been working in too many different languages at the same time :). From cheappuma at 126.com Fri Jul 18 20:46:47 2008 From: cheappuma at 126.com (128) Date: Fri, 18 Jul 2008 17:46:47 -0700 (PDT) Subject: paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) Message-ID: paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) paypal wholesale evisu shirt (paypal accept)(www power-saler cn ) paypal wholesale evisu hat (paypal accept)(www power-saler cn ) paypal wholesale evisu hoody (paypal accept)(www power-saler cn ) paypal wholesale evisu jeans(paypal accept)(www power-saler cn ) paypal wholesale evisu sunnglass(paypal accept)(www power-saler cn ) From ldo at geek-central.gen.new_zealand Thu Jul 24 05:56:02 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 24 Jul 2008 21:56:02 +1200 Subject: scanf in python References: <4884be5e$0$19722$426a74cc@news.free.fr> <6ek4cgF7hq4vU1@mid.uni-berlin.de> <4884e77a$0$29405$426a74cc@news.free.fr> Message-ID: In message <4884e77a$0$29405$426a74cc at news.free.fr>, AMD wrote: > Actually it is quite common, it is used for processing of files not for > reading parameters. You can use it whenever you need to read a simple > csv file or fixed format file which contains many lines with several > fields per line. I do that all the time, in Python and C++, but I've never felt the need for a scanf-type function. For reading delimited fields in Python, you can use .split string method. From deets at nospam.web.de Wed Jul 2 16:04:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Jul 2008 22:04:00 +0200 Subject: detection of unplugged cable In-Reply-To: References: Message-ID: <6d259gFfevuU1@mid.uni-berlin.de> Oguz Yarimtepe schrieb: > Hi, > > I am tring to develeop a gui with pyqt. I need to detect whether the > the cable to vga, dmi or s-video outputs are plugged or unplugged. > After detection i need to run a process. How can i do this? Not with python as is. This is OS-specific, and you should see what your OS supports regarding DDC support & how much of that is exposed to the user. And it might not be to reliable. You are not *forced* to use a DDC monitor. Diez From robert.rawlins at thinkbluemedia.co.uk Tue Jul 15 07:32:06 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 15 Jul 2008 12:32:06 +0100 Subject: Logging in __del__() Message-ID: <013601c8e66e$69a4faf0$3ceef0d0$@rawlins@thinkbluemedia.co.uk> Guys, I'm trying to help trace when instances of particular classes are being destroyed by the garbage collector and thought the cleanest way would be to implement a logging call in __del__() on the class. However, I'm having an issue. I inject a logger instance into my class upon construction and set it to self.logger, I then use this within the class to log actions going on within, works fine. Now, when I make the call in the __del__() method like so: def __del__(self): # Log the classes destruction. self.logger.debug("Class Instance Destroyed") I then get the following exception thrown when running my code: Traceback (most recent call last): File "/usr/lib/python2.5/logging/handlers.py", line 73, in emit if self.shouldRollover(record): File "/usr/lib/python2.5/logging/handlers.py", line 147, in shouldRollover self.stream.seek(0, 2) #due to non-posix-compliant Windows feature ValueError: I/O operation on closed file Does anyone have any ideas as to what I'm doing wrong here? Is this a known issue which has a neat little work around? Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From kanchana.senevirathna at gmail.com Wed Jul 23 01:33:10 2008 From: kanchana.senevirathna at gmail.com (Kanch) Date: Tue, 22 Jul 2008 22:33:10 -0700 (PDT) Subject: xpathEval fails for large files References: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> <48864b0d$0$9494$9b4e6d93@newsspool3.arcor-online.net> Message-ID: On Jul 23, 2:03 am, Stefan Behnel wrote: > Fredrik Lundh wrote: > > Kanchana wrote: > > >> I tried to extract some data with xpathEval. Path contain more than > >> 100,000 elements. > > >> doc = libxml2.parseFile("test.xml") > >> ctxt = doc.xpathNewContext() > >> result = ctxt.xpathEval('//src_ref/@editions') > >> doc.freeDoc() > >> ctxt.xpathFreeContext() > > >> this will stuck in following line and will result in high usage of > >> CPU. > >> result = ctxt.xpathEval('//src_ref/@editions') > > >> Any suggestions to resolve this. > > > what happens if you just search for "//src_ref"? what happens if you > > use libxml's command line tools to do the same search? > > >> Is there any better alternative to handle large documents? > > > the raw libxml2 API is pretty hopeless; there's a much nicer binding > > called lxml: > > > http://codespeak.net/lxml/ > > > but that won't help if the problem is with libxml2 itself, though > > It may still help a bit as lxml's setup of libxml2 is pretty memory friendly > and hand-tuned in a lot of places. But it's definitely worth trying with both > cElementTree and lxml to see what works better for you. Depending on your > data, this may be fastest in lxml 2.1: > > doc = lxml.etree.parse("test.xml") > for el in doc.iter("src_ref"): > attrval = el.get("editions") > if attrval is not None: > # do something > > Stefan Original file was 18MB, and contained 288328 element attributes for the particular path. I wonder whether for loop will cause a problem in iterating for 288328 times. From dobedani at gmx.net Tue Jul 15 11:30:19 2008 From: dobedani at gmx.net (Dobedani) Date: Tue, 15 Jul 2008 08:30:19 -0700 (PDT) Subject: Invoking non-static methods of a non-Python object instance Message-ID: <0dc2b4f4-a918-49bb-a793-f0a4fd144286@27g2000hsf.googlegroups.com> Dear All, For some time now, I have been working with the ctypes module on Windows. First I got my hands on a library developed with Delphi 7. That library is exporting plain functions. Internally, reference is made to the instance of a class, which is instantiated in a kind of initialization section. Everything works fine. Now, I have developed a library in C#. I am able to get the result from static methods, e.g. public static String sayHello() { String msg = "Hello from MyLib, working in folder "; return msg + Directory.GetCurrentDirectory(); } To make sure that the libray can work as a Win32 library, I have added a V-Table by disassembling and then editing the IL code then compiling again, see: http://www.blong.com/Articles/DotNetInteropD8/Interop1/Win32AndDotNetInterop.htm However, in my code I am actually exporting the methods of a class and I added non-static methods - unlike what was the case with the DLL developed in Delphi. Unfortunately, it appears impossible to keep a reference to an instance of my class in the Python code. Suppose, I remove the keyword "static" from the above method declaration, this fails whatever I try: from ctypes import *; mylib = windll.LoadLibrary("MyLib"); mylib.getInstance.restype = ? myInst = mylib.getInstance(); print myInst.sayHello(); Is there a way to do this? FYI: I don't want to work with win32client, because this will require that my users install an extra extension and I am expected to deliver something which can work without such extra extensions. I look forward to your ideas! Kind regards, Dobedani From greg at cosc.canterbury.ac.nz Tue Jul 29 00:29:53 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 29 Jul 2008 16:29:53 +1200 Subject: Rant (was Re: x*x if x>10 In-Reply-To: <6f48ehF9p9bkU1@mid.uni-berlin.de> References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3qjoF9n3cpU1@mid.uni-berlin.de> <6f48ehF9p9bkU1@mid.uni-berlin.de> Message-ID: <6f7l2nFa9d5lU1@mid.individual.net> Diez B. Roggisch wrote: > I maybe should paraphrase "don't return objects you passed as arguments > from a function". The important thing is that a function shouldn't modify any object unless it's the express purpose of the function to do so. You could call this the "look but don't touch" rule. -- Greg From naude.jaco at gmail.com Wed Jul 23 03:45:23 2008 From: naude.jaco at gmail.com (Jaco Naude) Date: Wed, 23 Jul 2008 00:45:23 -0700 (PDT) Subject: Undefined calling conventions in Python.h Message-ID: Hi there, This is my first post over here and I hope someone can give me some guidance. I'm trying to embed Python into a Visual C++ 2008 application and I'm getting linker problems. I've compiled a DLL of the Python source code using the pythoncode VC++ project in the PCbuild folder of the source download and this works 100% without any warnings etc. I've done this in Debug and Release mode without any problems. When I include python_install_path\include\Python.h in my application (with the linking setup correctly to the .lib and .dll files generated by myself) it builds fine. However as soon as I try to call any Python function (Py_Exit for example) I get linker errors as shown below: 1>application.obj : error LNK2031: unable to generate p/invoke for "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@$$J0YMXH at Z); calling convention missing in metadata 1>frmPythonInterface.obj : error LNK2031: unable to generate p/invoke for "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@$$J0YMXH at Z); calling convention missing in metadata I'm probably missing something but I can't find any calling convention details in Python.h or the other headers included in this file. In my VC++ DLL project I've specified the calling convention as __stdcall. I know the __clrcall naming convention has to do with managed code in VC+ + but thats as far as my knowledge on that goes. Should I define the calling conventions manually? Or is there a setting wrong somewhere in my application project? If anybody can give some guidance it would be greatly appreciated. Thanks Jaco From hat at se-162.se.wtb.tue.nl Mon Jul 7 10:18:23 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 07 Jul 2008 16:18:23 +0200 Subject: I am looking for svn library(module) References: <6e1097a0-2a99-4885-a1ef-0684af5aa6a1@d1g2000hsg.googlegroups.com> Message-ID: On 2008-07-07, sniipe at gmail.com wrote: > Hi, > > I am looking fo svn library(module) which is used in the svn- > mailer(http://opensource.perlig.de/svnmailer/) project. Does anybody > know where can I find it(download url)? This is information which I > received from python error: > > from svn import core as svn_core > ImportError: No module named svn The module is called 'pysvn', available at tigris.org. They use it in their work-branch program. From hyugaricdeau at gmail.com Wed Jul 30 10:10:34 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Wed, 30 Jul 2008 07:10:34 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <2da5350e-d74e-4760-b9b8-7cc9869dc607@n33g2000pri.googlegroups.com> Message-ID: On Jul 30, 3:53?am, "Russ P." wrote: > Fair enough. I have no dog in this particular fight. I just think it > wouldn't hurt to add an "isempty()" or "isnonempty()" method to the > list type, and let people use it if they wish, or continue using "if > x" if that's what they prefer. Go right on ahead. You could implement it like this: class superenhancedlist(list): def isempty(self): return not self >>> a = superenhancedlist() >>> a.isempty() True >>> a.append(1) >>> a.isempty() False Amazingly useful! Go ahead and use that in all your code. Anyone else who comes along and looks at it or tries to maintain it will really love you for it. From circularfunc at gmail.com Thu Jul 10 09:15:49 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 10 Jul 2008 06:15:49 -0700 (PDT) Subject: TypeError, I know why but not how!? References: <03cbb0d2-6a0c-4b86-a75e-b73c5677acc7@c65g2000hsa.googlegroups.com> Message-ID: I don't fully understand why I have to do this. On Jul 10, 4:17?am, Robert Kern wrote: > ssecorp wrote: > > Im looking into PvsNP: > >http://www.claymath.org/millennium/P_vs_NP/ > > so I thought I'd write the program just to get a feel for it. > > > But I run into a problem. Why does it all the sudden return None? I > > mean I know why the program aborts but I dont understand why the None > > is generated all the sudden. Hitting recursion depth isn't reported > > with that error. > > def validate(placed): > ? ? ?student = round(random.random()*401) > ? ? ?if student in placed: > ? ? ? ? ?# You need to explicitly return, here: > ? ? ? ? ?return validate(placed) > ? ? ?else: > ? ? ? ? ?placed.append(student) > ? ? ? ? ?return student, placed > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > ? that is made terrible by our own mad attempt to interpret it as though it had > ? an underlying truth." > ? ?-- Umberto Eco From Lie.1296 at gmail.com Mon Jul 21 15:32:00 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 21 Jul 2008 12:32:00 -0700 (PDT) Subject: Change PC to Win or Windows References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> Message-ID: <82873ccd-9667-4dfa-9ec4-a9ac7c672aa7@w1g2000prk.googlegroups.com> > It very much IS the point. Language evolves based on common usage > patterns of the people who use it. That is inarguably correct. > The term "PC" is commonly used in English, in the United States > and other English speaking countries, to mean a computer running > Microsoft Windows. As far as I am aware, they're like that because most people aren't even aware that there are other OSes than Microsoft Windows. If the world is still back in the 80s or 90s when people that use computers means they're knowledgeable enough about computer, PCs would be either applied to "all kinds of small computer/microcomputer" or only to "IBM- branded microcomputers", the latter because PC is originally IBM's marketing term, the former is a natural expansion of the meaning since "Personal Computer" is a neutral term, unlike marketing terms like: "TravelMate", "Lifebook", "MacBook", "GeForce", etc. "Personal Computer" is more like the term "Mobile Phone" which is brand-neutral and is usable by any brand, regardless of how the term originated. The reason why the world hasn't evolved to the two predictable cases ("all kinds of microcomputers" or "IBM-PC and clones"), is what I'll explain below. > That's a simple fact that you can not escape, no matter how > much you may not like it (it just so happens that I also don't l > ike it, but I realized long ago the futility of arguing against > its usage). It's still a fact, and I described roughly how > that fact came to be. > It wasn't something that Apple started; it's been used this way > in increasingly common usage for at least 20 years, although > exactly what combination of hardware and software was being > refered to as a "PC" has evolved over that timeframe. Apple popularizes the term by explicit marketing, but the real blame is to Microsoft's dominance, though it is without their explicit consent, blessing, or resistance. Not entirely Microsoft's fault for being dominant, but their dominance in the lower level users makes those lower level user unaware of other OSes and applied the term PC to Windows-based computers. When other OSes are gaining popularity again (i.e. when Microsoft starts to lose its total and complete dominance, i.e. around right now) the term's meaning become a huge matter because people associated the term with Microsoft Windows (i.e. software), not with IBM-PC and its clones anymore (i.e. hardware). On Jul 21, 11:50?pm, Derek Martin wrote: > On Sat, Jul 19, 2008 at 02:56:07AM -0700, Lie wrote: > > government, etc. IBM PC is one of the first computers that ordinary > > people could possess, when IBM-clones appeared on the market, they're > > referred as PCs too because they are Personal Computer, a computer > > that is designed for personal use. > > Just to be clear, this statement is WRONG. ?PC-clones were so called > because they were clones of the IBM-PC. ?The term is very specific to > IBM-compatible hardware. ? > > ?http://en.wikipedia.org/wiki/Pc_clone > > ? ? IBM PC compatible computers are those generally similar to the > ? ? original IBM PC, XT, and AT. Such computers used to be referred to > ? ? as PC clones, or IBM clones since they almost exactly duplicated > ? ? all the significant features of the PC, XT, or AT internal design, > ? ? facilitated by various manufacturers' ability to legally reverse > ? ? engineer the BIOS through cleanroom design. > > Wikipedia's article on the personal computer accurately reflects > the multiple meanings of the term, and points out the common usage > to mean a Windows box: > > ?http://en.wikipedia.org/wiki/Personal_computer > > ? ? Today a PC may be a desktop computer, a laptop computer or a > ? ? tablet computer. The most common operating systems are Microsoft > ? ? Windows, Mac OS X and Linux, while the most common microprocessors > ? ? are x86 compatible CPUs. ?However, the term "PC" is often used > ? ? only to refer to computers running Microsoft Windows. > > So please stop your whining and get used to the idea that THE REST OF > THE WORLD uses PC to mean a Windows box. The rest of the world? Not in this part of the world, not in my whole country at the least... From coolman.guron at gmail.com Tue Jul 29 09:51:26 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Tue, 29 Jul 2008 06:51:26 -0700 (PDT) Subject: pygtk treview, ListStore not displaying properly Message-ID: <5cd417cf-4169-4805-8317-fb82c7e7be90@x29g2000prd.googlegroups.com> hi group i am running into a problem with gtk. i have a treeview that just displays tabular data (no down arrows or trees etc). it has 5 columns. The tiny problem i am having is that it is just display the data of the column named `title` in all the colums! here the pic of the app in action http://i36.tinypic.com/2djcqqr.png the related code of the app is as follows: self.tv = self.glade.get_widget('treeview1') #the treeview object def show_sync_wind(self,obj, data = None): t = Template.select(Template.q.synced == '0') self.synclstore = gtk.ListStore(str,str,str,str,str) x = 0 cr = gtk.CellRendererText() col = gtk.TreeViewColumn('#', cr); col.add_attribute(cr, 'markup', 1) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(0) self.tv.append_column(col) self.sno_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Title', cr); col.add_attribute(cr, 'markup', 1) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(1) self.tv.append_column(col) self.title_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Section', cr); col.add_attribute(cr, 'markup', 1) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(2) self.tv.append_column(col) self.section_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Category', cr); col.add_attribute(cr, 'markup', 1) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(3) self.tv.append_column(col) self.category_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Sync', cr); col.add_attribute(cr, 'markup', 1) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(4) self.tv.append_column(col) self.sync_col = col self.tv.set_model(self.synclstore) self.tv.set_headers_clickable(True) #self.tv.set_expander_column(self.title_col) for y in t: row = self.synclstore.append([str(x),y.title,y.section.name,y.category.name,y.synced]) self.synclstore.set(row,0,'0') self.synclstore.set(row,1,y.title) self.synclstore.set(row,2,y.section.name) self.synclstore.set(row,3,y.category.name) self.synclstore.set(row,4,y.synced) self.sync_window.show() From volcimaster at gmail.com Tue Jul 29 15:45:27 2008 From: volcimaster at gmail.com (Warren Myers) Date: Tue, 29 Jul 2008 15:45:27 -0400 Subject: Python Written in C? In-Reply-To: <5504f9ac0807211105h4604d332y5671243cb34abfc6@mail.gmail.com> References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> <5504f9ac0807211105h4604d332y5671243cb34abfc6@mail.gmail.com> Message-ID: The OO overheads for C++ are almost non-existent. http://www.informit.com/articles/article.aspx?p=1192024&ns=15058 On Mon, Jul 21, 2008 at 2:05 PM, Dan Upton wrote: > On Mon, Jul 21, 2008 at 1:21 PM, Marc 'BlackJack' Rintsch > wrote: >> On Mon, 21 Jul 2008 18:12:54 +0200, mk wrote: >> >>> Seriously, though, would there be any advantage in re-implementing >>> Python in e.g. C++? >>> >>> Not that current implementation is bad, anything but, but if you're not >>> careful, the fact that lists are implemented as C arrays can bite your >>> rear from time to time (it recently bit mine while using lxml). Suppose >>> C++ re-implementation used some other data structure (like linked list, >>> possibly with twists like having an array containing pointers to 1st >>> linked list elements to speed lookups up), which would be a bit slower >>> on average perhaps, but it would behave better re deletion? > > Aside (actual reply below): at least for a sorted LL, you're basically > describing Henriksen's algorithm. They can asymptotically be faster, > based on amortized analysis, but they're somewhat more complicated to > implement. > >> >> An operation that most people avoid because of the penalty of "shifting >> down" all elements after the deleted one. Pythonistas tend to build new >> lists without unwanted elements instead. I can't even remember when I >> deleted something from a list in the past. >> >> Ciao, >> Marc 'BlackJack' Rintsch > > The other side of the equation though is the OO-overhead for C++ > programs as compared to C. (A couple years ago we used an > instrumentation tool to check the instruction count for a simple hello > world program written in C (ie, main(){printf("Hello world!"); return > 0;}) and Python (main(){cout<<"hello world"< instruction count was significantly higher for C++. I expect any sort > of C++ objects you used to implement Python structures will be slower > than the equivalent in C. So even if writing it in C++ would reduce > the overhead for deleting from a list, I expect you would lose a lot > more. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Warren Myers http://warrenmyers.com From ivan at datasyncorp.com Wed Jul 2 13:55:35 2008 From: ivan at datasyncorp.com (Ivan Ven Osdel) Date: Wed, 2 Jul 2008 12:55:35 -0500 (CDT) Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: <1777569623.855701215020919496.JavaMail.root@saturn.datasyncintra.net> Message-ID: <145286708.856441215021335297.JavaMail.root@saturn.datasyncintra.net> The free Python editors/IDEs really do need work as far as code completion goes but I am hopeful. IMO Stani's Python Editor comes closest by providing some code sense through a combination of history and doc strings for Python built-ins. Where it falls short is the ability to scan doc strings for your own code and non built-in modules in the Python path. Python already has the ground work in place to accomplish something similar to VS's XML commenting/intellisense system. With a Python interpretor you can type help(myModule) and get the doc string documentation. So I imagine implementing code sense for code being developed as well as non built-in modules would just be a matter of finding the appropriate module at the right time and piping the output of help([module]) to a popup window. If your willing to help work on something like that I suggest contacting Stani directly http://pythonide.stani.be/ or creating a plugin for Geany http://geany.uvena.de/ Ivan Ven Osdel Software Engineer http://www.datasyncsuite.com/ ----- Original Message ----- From: "Ali Servet D?nmez" To: python-list at python.org Sent: Wednesday, July 2, 2008 3:33:59 AM GMT -06:00 US/Canada Central Subject: Re: Freesoftware for auto/intelligent code completing in Python On Jul 1, 12:15?am, Fuzzyman wrote: > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > > I don't want to be so mean here, but how hard it could be be writing a > > freesoftware which would automatically/intelligently auto complete > > Python code? (I mean something that really does the job, like > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > name it, but just don't give me PyDev please...) > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > even a brand new huge all-fancy IDE, I don't care, but what am I > > missing here? > > > Could someone please point me out something that I'm really missing > > which is already present in the wild, otherwise I'd like discuss with > > whoever is willing to help me to get this thing done. I made my mind > > and I could volunteer to make this happen as thesis project for my > > incoming graduation in the next year. > > > Regards you all, > > Ali Servet D?nmez > > Vim, Emacs, Wing, Komodo, ... more? > > Yeah, I guess you're missing something. :-) > > Michael Foordhttp://www.ironpythoninaction.com/http://www.trypython.org/ I've checkout Wing IDE's license and it doesnt' seem to be a freesoftware; am I wrong? From bdesth.quelquechose at free.quelquepart.fr Mon Jul 28 15:08:26 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Jul 2008 21:08:26 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> Message-ID: <488e3520$0$16766$426a74cc@news.free.fr> Russ P. a ?crit : > On Jul 28, 4:23 am, Bruno Desthuilliers > wrote: >> Russ P. a ?crit : (snip) >>> A bonus is that it becomes >>> clearer at the point of usage that ".data" is member data rather than >>> a local variable. >> I totally disagree. The dot character is less obvious than the 'self.' >> sequence, so your proposition is bad at least wrt/ readability (it's >> IMHO bad for other reasons too but I won't continue beating that poor >> dead horse...) > > Man, you are one dense dude! Can I give you a bit of personal advice? > I suggest you quit advertising your denseness in public. Thanks. > Letting "self" (or whatever the first argument was) be implied in > ".cat" does absolutely *NOTHING* to change the internal workings of > the Python interpreter. You probably have a way better knowledge of Python's compiler and interpreter than I do to assert such a thing. But if it's so easy, please provide a working patch. > It's a very simple idea that you insist on > making complicated. As I said, I could write a pre-processor myself to > implement it in less than a day. Preprocessor are not a solution. Sorry. > As for "dot" being less obvious than "self.", no kidding? Nope. I'm deadly serious. (snip no-op argument and name-calling). > Your posts here are typical. I'm trying to make a suggestion to reduce > the clutter in Python code, s/the clutter/what Russ P. decided to consider as clutter/ > and you throw tomatoes mindlessly. Oh, you don't stand people disagreing with you, that's it ? > You seem to think that being a "regular" on this newsgroup somehow > gives you special status. Why so ? Because I answer to your proposition and not agree with your arguments ??? C'mon, be serious, you have the right to post your proposition here, I have the right to post my reaction to your proposition, period. Grow up, boy. > I sure wish I had one tenth the time to > spend here that you have. But even if I did, I have far more important > work to do than to "hang out" on comp.lang.python all day every day. > Man, what a waste of a life. Well, I guess it keeps you off the > streets at least. Boy, I don't know who you think you're talking to, but you're obviously out of luck here. I'm 41, married, our son is now a teenager, I have an happy social life, quite a lot of work, and no time to waste in the streets. And FWIW, name-calling won't buy you much here. From noagbodjivictor at gmail.com Tue Jul 1 17:44:27 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Tue, 1 Jul 2008 17:44:27 -0400 Subject: How to make a function associated with a class? Message-ID: > > Hi, > > I have a class called "vector". And I would like to define a function > "dot" which would return a dot product of any two "vectors". I want > to call this function as follow: dot(x,y). > > Well, I can define a functions "dot" outside the class and it works > exactly as I want. However, the problem is that this function is not > associated with the class (like methods a method of the class). > > For example, if I call "x.calc()" or "y.calc()", python will execute > different methods if "x" and "y" belongs to different classes. I want > to have the same with my "dot" function. I.e. I want it calculates the > dot product ONLY IF the both arguments of that function belong to the > "vector" class. > > Is it possible? > > Thank you in advance. > > Do you think a static method will do the thing? > Well you can define the function inside the class. Then create a name outside the class that references it. Is is. dot = Class.dot. By the way, why do you want to tie this function to the class? -- NOAGBODJI Paul Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Jul 1 15:46:45 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 01 Jul 2008 15:46:45 -0400 Subject: convert unicode characters to visibly similar ascii characters In-Reply-To: References: Message-ID: Peter Bulychev wrote: > Hello. > > I want to convert unicode character into ascii one. > The method ".encode('ASCII') " can convert only those unicode > characters, which fit into 0..128 range. > > But there are still lots of characters beyond this range, which can be > manually converted to some visibly similar ascii characters. For > instance, there are several quotation marks in unicode, which can be > converted into ascii quotation mark. > > Can this conversion be performed in automatic manner? After googling > I've only found that there exists Unicode database, which stores > human-readable information on notation of all unicode characters > (ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt). And there also > exists the Python adapter for this database > (http://docs.python.org/lib/module-unicodedata.html). Using this > database I can do something like `if > notation.find('QUOTATION')!=-1:\n\treturn "'"`. I believe there is more > elegant way. Am I right? I believe you will have to make up your own translation dictionary for the translations *you* want. You should then be able to use that with the .translate() method. tjr From mensanator at aol.com Thu Jul 31 17:23:13 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 31 Jul 2008 14:23:13 -0700 (PDT) Subject: find and replace with regular expressions References: <91a5aec2-9c70-41c7-a1b2-d8e8c4ed9578@2g2000hsn.googlegroups.com> Message-ID: <8a16bb81-9a7a-43d6-98b8-42c2b791fdd2@27g2000hsf.googlegroups.com> On Jul 31, 3:56?pm, Mensanator wrote: > On Jul 31, 3:07?pm, chrispoliq... at gmail.com wrote: > > > > > > > I am using regular expressions to search a string (always full > > sentences, maybe more than one sentence) for common abbreviations and > > remove the periods. ?I need to break the string into different > > sentences but split('.') doesn't solve the whole problem because of > > possible periods in the middle of a sentence. > > > So I have... > > > ---------------- > > > import re > > > middle_abbr = re.compile('[A-Za-z0-9]\.[A-Za-z0-9]\.') > > > # this will find abbreviations like e.g. or i.e. in the middle of a > > sentence. > > # then I want to remove the periods. > > > ---------------- > > > I want to keep the ie or eg but just take out the periods. ?Any > > ideas? ?Of course newString = middle_abbr.sub('',txt) where txt is the > > string will take out the entire abbreviation with the alphanumeric > > characters included. > >>> middle_abbr = re.compile('[A-Za-z0-9]\.[A-Za-z0-9]\.') > >>> s = 'A test, i.e., an example.' > >>> a = middle_abbr.search(s) ? ? ?# find the abbreviation > >>> b = re.compile('\.') ? ? ? ? ? # period pattern > >>> c = b.sub('',a.group(0)) ? ? ? # remove periods from abbreviation > >>> d = middle_abbr.sub(c,s) ? ? ? # substitute new abbr for old > >>> d > > 'A test, ie, an example.' A more versatile version: import re middle_abbr = re.compile('[A-Za-z0-9]\.[A-Za-z0-9]\.') s = 'A test, i.e., an example.' a = middle_abbr.search(s) # find the abbreviation b = re.compile('\.') # period pattern c = b.sub('',a.group(0)) # remove periods from abbreviation d = middle_abbr.sub(c,s) # substitute new abbr for old print d print print s = """A test, i.e., an example. Yet another test, i.e., example with 2 abbr.""" a = middle_abbr.search(s) # find the abbreviation c = b.sub('',a.group(0)) # remove periods from abbreviation d = middle_abbr.sub(c,s) # substitute new abbr for old print d print print s = """A test, i.e., an example. Yet another test, i.e., example with 2 abbr. A multi-test, e.g., one with different abbr.""" done = False while not done: a = middle_abbr.search(s) # find the abbreviation if a: c = b.sub('',a.group(0)) # remove periods from abbreviation s = middle_abbr.sub(c,s,1) # substitute new abbr for old ONCE else: # repeat until all removed done = True print s ## A test, ie, an example. ## ## ## A test, ie, an example. ## Yet another test, ie, example with 2 abbr.' ## ## ## A test, ie, an example. ## Yet another test, ie, example with 2 abbr. ## A multi-test, eg, one with different abbr. From haraldarminmassa at gmail.com Tue Jul 22 08:56:06 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Tue, 22 Jul 2008 05:56:06 -0700 (PDT) Subject: is it possible to add a property to an instance? References: Message-ID: <2dda482a-d15c-4f8d-9fca-3bfffe9e4fa1@f63g2000hsf.googlegroups.com> > Does anyone know if it is possible to add a property to an instance at > runtime? I didn't see anything about it in the standard library's new > module, google hasn't turned up much either. yes. You need nothing special, just add it: class fish(object): pass a=fish() a.legs=4 print a.legs (or print (a.legs) on Python 3.0 and above) so you add a property to an instance and proove that Darwin was right in one go. Harald From tcfg at sina.com Thu Jul 24 08:27:14 2008 From: tcfg at sina.com (fang) Date: Thu, 24 Jul 2008 05:27:14 -0700 (PDT) Subject: how to cut and paste in the windows of python(command line) References: <9500663c-0985-4dfd-8d0a-ae25411f00e5@v39g2000pro.googlegroups.com> Message-ID: <8488675c-1815-4b3a-8299-6fe06e030b05@i20g2000prf.googlegroups.com> Dear: Thank you very much! I can do it! It's very nice! From larry.bates at websafe.com` Mon Jul 14 00:27:11 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 13 Jul 2008 23:27:11 -0500 Subject: while var, but var ==16 != true In-Reply-To: <8c2cd9ff-bec2-4844-82a8-8ce02df5663e@w7g2000hsa.googlegroups.com> References: <8c2cd9ff-bec2-4844-82a8-8ce02df5663e@w7g2000hsa.googlegroups.com> Message-ID: maestro wrote: > why does this work? "while p" = "while p != 0" ? 1 is True and 0 is > false in python but other numbers have no boolean value so why doesnt > it abort. > > > >>>> p=16 >>>> p > 16 >>>> while p: > print p > p -= 1 > > > 16 > 15 > 14 > 13 > 12 > 11 > 10 > 9 > 8 > 7 > 6 > 5 > 4 > 3 > 2 > 1 > > > i can also do: > >>>> k=[] >>>> while k: > k.pop() > > >>>> k=[1,2,3] >>>> while k: > k.pop() > > > 3 > 2 > 1 > > > so obv while var means while not empty or why not zero but it isnt > something youd guess unless youd beeen shown it. Python manuals outline that 0, None, empty list, empty dictionary are False anything else evaluates to True. This is all over this list as well. -Larry From fetchinson at googlemail.com Thu Jul 10 01:46:07 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 9 Jul 2008 22:46:07 -0700 Subject: python scalability In-Reply-To: <487598C3.9080306@vapourforge.com> References: <487590E6.7020004@gmail.com> <487598C3.9080306@vapourforge.com> Message-ID: >> I work on a desktop application that has been developed using python >> and GTK (see www.leapfrog3d.com). We have around 150k lines of python >> code (and 200k+ lines of C). We also have a new project manager with >> a C# background who has deep concerns about the scalability of python >> as our code base continues to grow and we are looking at introducing >> more products. I am looking for examples of other people like us (who >> write desktop apps in python) with code bases of a similar size who I >> can point to (and even better talk to) to help convince him that >> python is scalable to 300+ lines of code and beyond. I have looked at >> the python success stories page and haven't come up with anyone quite >> like us. One of my project managers questions is: "Are we the only >> company in the world with this kind and size of project?" >> I want to say no, but am having trouble convincing myself, let alone him. >> >> If you are involved in this kind of thing please get in touch with me. If python is suitable for large projects with over 300k lines of code but not in the desktop app scene but web apps then probably it is also suitable for desktop apps. You can probably convince your manager that the previous statement is true. Once that is done you can point to youtube and google who are heavy python users without scalability issues. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From karthikbalaguru79 at gmail.com Wed Jul 23 12:24:13 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Wed, 23 Jul 2008 09:24:13 -0700 (PDT) Subject: Strange problem .... References: <12fd8ef1-c7e0-470b-ba51-f946d8ea8e26@z6g2000pre.googlegroups.com> Message-ID: On Jul 23, 1:31 pm, "Simon Brunning" wrote: > 2008/7/23 karthikbalaguru : > > > I use Redhat 9.0, python-2.2.2-26, python-devel-2.2.2-26 and > > db4-4.0.14-20. > > > File "/usr/local/SDK/bin/../core/bin/processorlib.py", line 88 > > yield ProcessorObjectInfo(child, self.pt) > > ^ > > SyntaxError: invalid syntax > > > Is this error related with the version of python / python-devel that i > > use . > > Any ideas / tips ? > > Yup - generators (and hence the yield statement) were first introduced > in Python 2.2, but in order to maintain backward compatibility, you'll > need this line in any module using them: > > from __future__ import generators > > As of Python 2.3, this is no longer necessary, and I'd imagine that > whatever you are running was targeted at a post 2.2 release. > Your answers helped me to solve the problem. I found some while loop inside def children(def). I initially tried by putting 'from __future__ import generators' just before the def children(self): present inside the class definition of 'DebugProcessorInfo'. But it did not work. Later i placed the 'from __future__ import generators' at the beginning of the python file and it worked sucessfully. Thx for that info. Karthik Balaguru From deets at nospam.web.de Wed Jul 9 09:00:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Jul 2008 15:00:57 +0200 Subject: Newbie question References: <3b1e6f480807082337l419fd40ax91eaf13e0701c5b3@mail.gmail.com> Message-ID: <6djr5pF2rqi0U1@mid.uni-berlin.de> |e0 wrote: > I did not mean to use WMI on linux, but query win machines *from* linux. What do you mean by "query"? Using the WMI module? No. It's Windows only. Diez From bronger at physik.rwth-aachen.de Thu Jul 24 13:34:15 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 24 Jul 2008 19:34:15 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> Message-ID: <87sktz425k.fsf@physik.rwth-aachen.de> Hall?chen! Sebastian \"lunar\" Wiesner writes: > Torsten Bronger : > >> Bruno Desthuilliers writes: >> >>> Torsten Bronger a ?crit : >>> >>>> Bruno Desthuilliers writes: >>>> >>>> [...] >>>> >>>> Just like this. However, the compiler could add "self" to >>>> non-decorated methods which are defined within "class". >>> >>> What's defined within classes are plain functions. It's actually >>> the lookup mechanism that wraps them into methods (and manage to >>> insert the current instance as first argument). >> >> And why does this make the implicit insertion of "self" >> difficult? I could easily write a preprocessor which does it >> after all. > > Who said, that it would be "difficult"? He just corrected your > statement about definitions inside a class, and did not make any > assumption about making "self" implicit. If it is not the implementation, I don't see why the "definition inside a class" matters at all. It can be realised as a transformation of the syntax tree and would even be transparent for the compiling steps after it. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From circularfunc at gmail.com Thu Jul 10 07:21:58 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 10 Jul 2008 04:21:58 -0700 (PDT) Subject: TypeError, I know why but not how!? References: <03cbb0d2-6a0c-4b86-a75e-b73c5677acc7@c65g2000hsa.googlegroups.com> Message-ID: <90eefcec-1a6c-46f1-9d13-eab7f3ed4075@l64g2000hse.googlegroups.com> ty I came to the same conckusion in bed :) now it works. however since there are 400 students and some are incompatible I shouldnt be able to generate a 200room list right? but it works sometimes the other times i get an error. might be because of recursion depth i never let the error finish. i saw i also generate student 0 which shouldnt exist. and the actual problem is generating all possible combinations right? i mean i can easily generate one list that is made randomly so problem solved. why does one need to generate all possible lists? i guess there are other problems where that might be needed so is this just a bad example or am i missing something? From steve at REMOVE-THIS-cybersource.com.au Tue Jul 29 19:31:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 23:31:21 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> Message-ID: <009fa3c2$0$20313$c3e8da3@news.astraweb.com> On Tue, 29 Jul 2008 10:42:50 -0700, Carl Banks wrote: > On Jul 29, 11:12 am, Matthew Fitzgibbons wrote: ... >> My use case involves a DAG of filters that pass data (of a variety of >> types--filters just pass on data types they don't understand) between >> them. I can also drop out of the filter chain at any point, using >> critera determined by the filters. These criteria, you guessed it, are >> bound to __nonzero__ in the filter and I determine whether or not to >> continue through the graph using "if x". You can't code explicit tests >> if you don't know what the tests even are beforehand. Also, I wanted to >> support builtins (ints and lists in particular) because they can be >> meaningful inputs to filters. Finally, as I add more filters and data >> types, I don't want to go back and mess with the code that decides >> whether or not to break out of the graph. > > Much like in Steven D'Aprano's example, still the only actual code > snippet I've seen, it seems that this can easily be done with a simple > explicit test by having all no-advance filters return None and testing > with "if x is not None". Yet again you ignore the actual functional requirements of the code, and made vague claims that if we change the function to another function that behaves differently, we can replace our simple code with your more complex code, and it (probably) won't break. Even if we could redesign the functional requirements of the code, why on earth would we want to? -- Steven From gagsl-py2 at yahoo.com.ar Fri Jul 11 05:29:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Jul 2008 06:29:15 -0300 Subject: Basic Question about Python WebServer File handling References: Message-ID: En Thu, 10 Jul 2008 22:20:21 -0300, Alok Kumar escribi?: > I need to have a python webserver which can handle Get request from the > clients and upload the *files* from 4 different directories. > > Can someone please point me what to exactly look for. Look at SimpleHTTPServer.py in the standard library - either use it as it is or subclass SimpleHTTPRequestHandler to suit your needs. -- Gabriel Genellina From timothywayne.cook at gmail.com Wed Jul 9 06:57:19 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Wed, 09 Jul 2008 07:57:19 -0300 Subject: start reading from certain line In-Reply-To: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> Message-ID: <1215601039.2873.972.camel@localhost.localdomain> On Wed, 2008-07-09 at 03:30 -0700, antar2 wrote: > I am a starter in python and would like to write a program that reads > lines starting with a line that contains a certain word. > For example the program starts reading the program when a line is > encountered that contains 'item 1' > > > The weather is nice > Item 1 > We will go to the seaside > ... > > Only the lines coming after Item 1 should be read file=open(filename) while True: line=file.readline() if not line: break if 'Item 1' in line: print line HTH, Tim -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. Home page: https://launchpad.net/oship/ Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From origami.takarana at gmail.com Sun Jul 20 22:48:59 2008 From: origami.takarana at gmail.com (origami.takarana at gmail.com) Date: Sun, 20 Jul 2008 19:48:59 -0700 (PDT) Subject: Solutions Fast Track - Monitoring and Intrusion Message-ID: Dear Reader, Designing for Detection ---------------------------- - Get the right equipment from the start. Make sure all of the features you need, or will need, are available from the start. - Know your environment. Identify potential physical barriers and possible sources of interference. - If possible, integrate security monitoring and intrusion detection in your network from its inception. Defensive Monitoring Considerations ------------------------------------------ - Define your wireless network boundaries, and monitor to know if they?re being exceeded. - Limit signal strength to contain your network. - Make a list of all authorized wireless Access Points (APs) in your environment. Knowing what?s there can help you immediately identify rogue APs. Intrusion Detection Strategies ----------------------------------- - Watch for unauthorized traffic on your network. Odd traffic can be a warning sign. - Choose an intrusion detection software that best suits the needs of your environment. Make sure it supports customizable and updateable signatures. - Keep your signature files current.Whether modifying them yourself, or downloading updates from the manufacturer, make sure this step isn?t forgotten. Conducting Vulnerability Assessments ------------------------------------------- - Use tools like NetStumbler and various client software to measure the strength of your 802.11b signal. - Identify weaknesses in your wireless and wired security infrastructure. - Use the findings to know where to fortify your defenses. - Increase monitoring of potential trouble spots. Incident Response and Handling -------------------------------------- - If you already have a standard incident response policy, make updates to it to reflect new potential wireless incidents. - Great incident response policy templates can be found on the Internet. - While updating the policy for wireless activity, take the opportunity to review the policy in its entirety, and make changes where necessary to stay current. An out-of-date incident response policy can be as damaging as not having one at all. Conducting Site Surveys for Rogue Access Points ------------------------------------------------------- - The threat is real, so be prepared. Have a notebook computer handy to use specifically for scanning networks. - Conduct walkthroughs of your premises regularly, even if you don?t have a wireless network. - Keep a list of all authorized APs. Remember, Rogue APs aren?t necessarily only placed by attackers.A well-meaning employee can install APs as well. --- Thank You --- James Conack http://www.centronet.uni.cc From kyosohma at gmail.com Mon Jul 7 09:05:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 7 Jul 2008 06:05:25 -0700 (PDT) Subject: GUI Programming by hand not code with Python Code References: <7003b665-3227-47a7-ab06-1a486f87939a@a1g2000hsb.googlegroups.com> Message-ID: <4b217d2c-a83c-4882-b3fa-ea2253d304bb@25g2000hsx.googlegroups.com> On Jul 6, 9:33?pm, jayjaygi... at hotmail.co.uk wrote: > Is their a program that lets you design a GUI by hand (like gambas) > not by code (like wxpython) but the commands are in python? > > A program similar to gambas or vb > > Gambas with python code instead of gambas code would be perfect. > > Thanks in advance I think Dabo also has a way to do some Visual programming too. And there's also XRC. See the following links for more info: http://dabodev.com/ http://xrced.sourceforge.net/ Mike From bignose+hates-spam at benfinney.id.au Tue Jul 29 09:21:53 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 29 Jul 2008 23:21:53 +1000 Subject: Boolean tests References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <488e4d2d$0$5967$ba624c82@nntp06.dk.telia.net> <009e5e66$0$20313$c3e8da3@news.astraweb.com> <488ee6c9$0$4463$ba624c82@nntp02.dk.telia.net> Message-ID: <87y73kg70u.fsf@benfinney.id.au> "Anders J. Munch" <2007 at jmunch.dk> writes: > Steven D'Aprano wrote: > > I'm sorry Anders, that was a needlessly harsh thing for me to say. > > I apologize for the unpleasant tone. > > > > Still, __nonzero__ is a fundamental part of Python's behaviour. > > You should learn about it. > > Hm, first you apologize, then you repeat the insult? That's no basis > for a conversation. Bye from here. No, he retracted the *insult* and restated the *advice* as a distinct statement. I think it's quite worthwhile to help people see the difference. -- \ ?People are very open-minded about new things, as long as | `\ they're exactly like the old ones.? ?Charles F. Kettering | _o__) | Ben Finney From modelnine at modelnine.org Thu Jul 31 07:38:49 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Thu, 31 Jul 2008 13:38:49 +0200 Subject: How smart is the Python interpreter? In-Reply-To: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> References: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> Message-ID: <200807311338.49915.modelnine@modelnine.org> Am Donnerstag, 31. Juli 2008 13:09:57 schrieb ssecorp: > def str_sort(string): > s = "" > for a in sorted(string): > s+=a > return s > > > if i instead do: > > def str_sort(string): > s = "" > so = sorted(string) > for a in so: > s+=a > return s > > > will that be faster or the interpreter can figure out that it only has > to do sorted(string) once? or that kind of cleverness is usually > reserved for compilers and not interpreters? In a statement of the form for in : the expression will only be evaluated once (to retrieve an iterator), so basically, both ways of stating it are equivalent and make negligible difference in runtime (the second version will be slower, because you have additional code to assign/fetch a local). Anyway, if you care about speed, probably: def str_sort(string): return "".join(sorted(string)) will be the fastest way of stating this. -- Heiko Wundram From sturlamolden at yahoo.no Sat Jul 26 09:11:37 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 26 Jul 2008 06:11:37 -0700 (PDT) Subject: 2d graphics - what module to use? References: <5035d4cb-1976-47d5-8887-4e8381407a7b@m44g2000hsc.googlegroups.com> Message-ID: <70bfa323-5e20-4df4-b93d-b779ce9c5b9e@a1g2000hsb.googlegroups.com> On Jul 26, 6:47?am, Matthew Fitzgibbons wrote: > If you're using wx, there is also wx.lib.plot, which I found to be > _much_ faster than matplotlib in my application, especially when resizing. Yes. Matplotlib creates beautiful graphics, but are terribly slow on large data sets. From alexnbryan at gmail.com Wed Jul 16 16:09:16 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 13:09:16 -0700 (PDT) Subject: py2exe issues with pictures and icons In-Reply-To: References: <18493908.post@talk.nabble.com> Message-ID: <18495626.post@talk.nabble.com> Mike Driscoll wrote: > > On Jul 16, 1:37?pm, Alexnb wrote: >> Hello >> >> I am sure most of you are familiar with py2exe. I am having a bit of a >> problem. See the program has a few pictures involved and the .ico it uses >> for the windows. However, the pictures are stored in the same directory >> as >> the source, something like: C:\Docs and settings\me\My >> docs\python\program. >> When I run the program for the interpreter, just as a .py, everything >> works >> just as it should. However, when I compile the main source as an .exe, >> and >> say let a friend try the program. It fails because it is missing the >> .ico. >> The catch, is I don't want to have it have to installed, at least at this >> point, I want it to be able to just run. So how can I make it just run >> from >> any computer with the files not being in the immediate directory. If that >> is >> not possible, how can I put them in the immediate directory and still >> make >> it work. Because that directory may change a lot so the path will change. >> >> Just a few questions. I hope someone out there can help me out! >> -- >> View this message in >> context:http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp1849390... >> Sent from the Python - python-list mailing list archive at Nabble.com. > > > Put the part of the code that needs the ico file(s) into a try/except > block. You could also try reading the py2exe wiki and tutorials. This > one looks like it has relevant data: > > http://www.py2exe.org/index.cgi/CustomIcons > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > > Well, that may solve the icon problem. But what about getting pictures in there? -- View this message in context: http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp18493908p18495626.html Sent from the Python - python-list mailing list archive at Nabble.com. From cheapkobe at sina.com Fri Jul 18 01:13:28 2008 From: cheapkobe at sina.com (14789) Date: Thu, 17 Jul 2008 22:13:28 -0700 (PDT) Subject: wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal Message-ID: wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal From tjreedy at udel.edu Tue Jul 29 16:00:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 16:00:40 -0400 Subject: Windows Interpreter In-Reply-To: <488F1DB3.4010608@timgolden.me.uk> References: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> <488F1745.4020705@timgolden.me.uk> <4dc0cfea0807290626p4b05376en49ccb18f0e1eb4bb@mail.gmail.com> <488F1DB3.4010608@timgolden.me.uk> Message-ID: Tim Golden wrote: > Victor Subervi wrote: >> def a(): >> chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', >> '\\b', '\\yz'] >> rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is >> like the Beast? Who can wage war against him?\par' >> for char in chars: >> c = '(?<=' + char + ')' >> test = re.search(c, rtf_markup) >> try: >> junk = test.group(0) >> print char >> except: >> pass >> >> Now, I can paste that entire fn in linux. But in windows I have to >> paste it line_by_line. Pain in butt! And it indents automatically. How >> change that behavior. > > Well, I'm not really sure what to say. I've just copied that > whole section with drag-mouse, Ctrl-C. I then opened a new > interpreter window (effectively, Start > Run > python) and > right-clicked over the window. At this point, the lines I > copied were copied in and the function accepted by the > interpreter. > > I do have QuickEdit on by default in all by console windows, > but the only difference I expect that to make is that you'd > otherwise have to use the window's System Menu (Alt-Space, > Edit, Paste). I have to right-click on the title bar (or left-click on the icon on the title bar), select edit and then select paste -- but it does work. I just found the QuickEdit option. While in an administrator account (if Python is installed for all users), bring up the menu as specified above, select Properties instead, then the Options tab, then select QuickEdit on the right. When clicking OK, being admin allows modification of the shortcut and not just the current window. Learn something new every day. Thanks. Terry Jan Reedy From fredrik at pythonware.com Thu Jul 17 05:41:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 11:41:41 +0200 Subject: Getting a unknown word out of a list with no spaces In-Reply-To: <18503830.post@talk.nabble.com> References: <18502758.post@talk.nabble.com> <487EF593.5060505@promsoft.ru> <18503144.post@talk.nabble.com> <487EF7D9.8010400@promsoft.ru> <93164ef9-7079-44db-9ac4-b0a18b0ddf3e@b1g2000hsg.googlegroups.com> <18503830.post@talk.nabble.com> Message-ID: Alexnb wrote: >>>>> "hello"[0] >> 'h' >>>>> "hello"[0] == "<" >> False >>>>> "hello"[0] == "h" >> True >>>>> "hello".startswith("h") >> True > really? That's just like C. I thought that it would fail because of the way > lists work. Thanks! what way? the first three will fail if the string is empty. >>> ""[0] Traceback (most recent call last): File "", line 1, in IndexError: string index out of range if you may end up doing this on an empty string, use slicing instead: >>> "hello"[:1] == "<" False >>> ""[:1] == "<" False (startswith is perhaps more convenient, but method calls are rather expensive in Python, so if you're in a hurry, it's often better to use operators. when in doubt, benchmark the alternatives.) From chrispoliquin at gmail.com Thu Jul 31 16:21:45 2008 From: chrispoliquin at gmail.com (chrispoliquin at gmail.com) Date: Thu, 31 Jul 2008 13:21:45 -0700 (PDT) Subject: Case tagging and python References: Message-ID: I second the idea of just using the islower(), isupper(), and istitle() methods. So, you could have a function - let's call it checkCase() - that returns a string with the tag you want... def checkCase(word): if word.islower(): tag = 'nocap' elif word.isupper(): tag = 'allcaps' elif word.istitle(): tag = 'cap' return tag Then let's take an input file and pass every word through the function... f = open(path:to:file, 'r') corpus_text = f.read() f.close() tagged_corpus = '' all_words = corpus_text.split() for w in all_words: tagtext = checkCase(w) tagged_corpus = tagged_corpus + ' ' + w + '/' + tagtext output_file = open(path:to:file, 'w') output_file.write(tagged_corpus) print 'All Done!' Also, if you're doing natural language processing in Python, you should get NLTK. From dstromberglists at gmail.com Sat Jul 26 16:41:15 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Sat, 26 Jul 2008 20:41:15 GMT Subject: tcp socket problem References: Message-ID: On Fri, 25 Jul 2008 16:09:13 -0700, jm.carp wrote: > I'm writing a tcp client that grabs data from a server at 32hz. But the > connection drops exactly one minute after it's opened. I can get data > from the server fine for the first 60s, and then the connection goes > dead. What's going on? What does "goes dead" mean in this case? Is python giving a traceback? Is some I/O blocking? I'd probably use a system call tracer to track down something like that, unless there's a useful traceback. It may be useful in the client, or the server, or both. http://stromberg.dnsalias.org/~strombrg/debugging-with-syscall- tracers.html Also, be careful to check that you aren't reading two chunks when you think you're getting one or something. That could cause some I/O to block in a hard-to-track-down way. IOW, TCP feels free to chop your packets into multiple packets, or to aggregate multiple packets into a smaller number of them - whatever it wants, pretty much. This sometimes helps performance or reliability, but it complicates writing socket programs at times. Put another way, a single send might show up as two recv's, for example. Oh, and using a sniffer may help too. I like wireshark or tshark (GUI and text interfaces of the same underlying sniffer), but there are many available. Old hands seem to prefer tcpdump, though I'm clear on why. If you fire up a sniffer against your network communication, it should be possible to see, for example, the last packet transferred, which system it was to, and which system it was from. You may not know which host is having the problem without a detailed knowledge of the protocol, but since you're coding the program, you may have that. :) This may show packet splitting/aggregation too, but keep in mind that a sniffer only shows you the data stream at a particular point in the transfer - you could see different things when running a sniffer on the client, on the server, or even on a subnet in between the two. Oh, and many networks are switched now, so most sniffers don't do that well on subnets in between, but they frequently still work well on the client and server themselves. HTH . From dd55 at cornell.edu Tue Jul 22 08:20:39 2008 From: dd55 at cornell.edu (Darren Dale) Date: Tue, 22 Jul 2008 08:20:39 -0400 Subject: is it possible to add a property to an instance? Message-ID: Does anyone know if it is possible to add a property to an instance at runtime? I didn't see anything about it in the standard library's new module, google hasn't turned up much either. Thanks, Darren From ki4yjl at gmail.com Thu Jul 10 23:26:24 2008 From: ki4yjl at gmail.com (WDC) Date: Thu, 10 Jul 2008 20:26:24 -0700 (PDT) Subject: error with configure (svn 64857) References: <487681e9$0$9745$9b622d9e@news.freenet.de> Message-ID: On Jul 10, 6:57?pm, "Mathieu Prevot" wrote: > 2008/7/10 "Martin v. L?wis" : > > >> I have the following error when I run configure: > > >> checking size of wchar_t... configure: error: cannot compute sizeof (wchar_t) > > >> what can I do ? > > > Study config.log for the source of the problem. > > Thank you Martin. How can I remove -lgcc_s and use the Intel equivalent ? > > configure:21939: checking for wchar_t > configure:21970: icc -c -g -O2 ?conftest.c >&5 > conftest.c(123): warning #279: controlling expression is constant > ? if ((ac__type_new_ *) 0) > ? ? ? ^ > > configure:21976: $? = 0 > configure:21991: result: yes > configure:21998: checking size of wchar_t > configure:22306: icc -o conftest -g -O2 ? conftest.c ?>&5 > ld: library not found for -lgcc_s > configure:22309: $? = 1 > configure: program exited with status 1 > > Mathieu I think he wanted YOU to find the problem. The best way to learn is to figure it out yourself! Good luck. From nicolas.pourcelot at gmail.com Fri Jul 18 10:39:38 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Fri, 18 Jul 2008 07:39:38 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> > What is your (concrete) use case, by the way? I try to make it simple (there is almost 25000 lines of code...) I have a sheet with geometrical objects (points, lines, polygons, etc.) The sheet have an object manager. So, to simplify : >>> sheet.objects.A = Point(0, 0) >>> sheet.objects.B = Point(0, 2) >>> sheet.objects.C = Middle(A, B) Then we have : >>> sheet.objects.A == sheet.objects.B True since have and B have the same coordinates. But of course A and B objects are not same python objects. In certain cases, some geometrical objects are automatically referenced in the sheet, without being defined by the user. (Edges for polygons, for example...) But they must not be referenced twice. So if the edge of the polygon is already referenced (because the polygon uses an already referenced object for its construction...), it must not be referenced again. However, if there is an object, which accidentally have the same coordinates, it must be referenced with a different name. So, I use something like this in 'sheet.objects.__setattr__(self, name, value)': if type(value) == Polygon: for edge in value.edges: if edge is_in sheet.objects.__dict__.itervalues(): object.__setattr__(self, self.__new_name(), edge) Ok, I suppose it's confused, but it's difficult to sum up. ;-) > Another possibility :-) > from itertools import imap > id(x) in imap(id, items) I didn't know itertools. Thanks :-) From martin at v.loewis.de Sat Jul 26 05:28:53 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 26 Jul 2008 11:28:53 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: References: Message-ID: <488AEE55.3010503@v.loewis.de> > (Any recommendations on a flavor of 64 bit of Linux for the Intel > architecture would be appreciated) My recommendation is to use Debian or Ubuntu, as that's my personal preference. As MAL said, any recent distribution that supports AMD64 should be fine (assuming you are not interested in Itanium, SPARC64, HPPA (2.0), PPC64, or Alpha, which are all 64-bit flavors of Linux). Regards, Martin From gcmartijn at gmail.com Sat Jul 26 06:03:51 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Sat, 26 Jul 2008 03:03:51 -0700 (PDT) Subject: re.findall(a patern,'function(dsf sdf sdf)') Message-ID: <8fc6d72a-cfc5-4e9d-af56-a009a464c6bb@27g2000hsf.googlegroups.com> H! First I have some random string below. bla = """ """ Now I'm trying to get each BlaObject with the first (variable) function argument And I can say that this isn't working for a in re.findall(r'([BlaObject ])(.*)([)] *)',bla): print a The output must be something like: # ('BlaObject','argh 1a') # ('BlaObject','argh 1a') or # Blaobject("argh 1a", "argh 2a", "24", 24, 345) # BlaObject("argh 1b", "argh 2b", ""+(sv), ""+(2f), "4"); My simple idea was to a. the start position is the BlaObject b. the stop position is the character ) (not ); because its a javascript function) c. the output [a (everything between) b] Who knows the answer ? Thanks very much, GCMartijn From Scott.Daniels at Acm.Org Wed Jul 23 08:51:56 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 23 Jul 2008 05:51:56 -0700 Subject: maximum value in a column of file In-Reply-To: References: <4886DCF3.10107@isac.cnr.it> <4886F4CD.8010704@isac.cnr.it> Message-ID: maurizio wrote: > thank you for your answer > actually i've to do some statistics (maximum,minimum,mean,standard > deviation,....) of a file of data in which each column is a particular > type of data. (the file is a tab separated value). > I was trying to do this by using python (usually i work with fortran or > bash, but i'm learning python), that the reason why i tried to use numpy. > Look into the csv module (comma separated values). It also can deal with tab separated values. --Scott David Daniels Scott.Daniels at Acm.Org From jeffm_ at email.com Sun Jul 13 02:12:22 2008 From: jeffm_ at email.com (JeffM) Date: Sat, 12 Jul 2008 23:12:22 -0700 (PDT) Subject: spam <...googlegroups.com> <...googlegroups.com> References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> Message-ID: >WDC wrote: >>BTW I reported it, yo should too. >> Lew wrote: >To whom did you report it, so that we may also report it there? Reports made to Google Groups are a complete waste of time. Google will only cancel *that* account (without blocking the IP address). It takes the spammer 30 seconds to enable *another* account. That is, ZERO real effect. It should also be noted that each time this is done plonk files could grow by one item. For Blogspot/Googlepages spam, report those to mailto:adsense-abuse at google.com adsense-abuse@ google.com That puts his site into Google Hell (screws up his GoogleRank). The most effective effort you can make is to do a reverse-DNS on the NNTP-Posting-Host http://private.dnsstuff.com/tools/whois.ch?ip=122.164.105.235&email=on and report abusers to their providers. This assumes their ISPs aren't complete rogues. From keshet1 at umbc.edu Tue Jul 8 23:41:45 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Tue, 08 Jul 2008 23:41:45 -0400 Subject: a simple 'for' question In-Reply-To: <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> References: <4874017D.2000401@umbc.edu> <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> Message-ID: <48743379.3020303@umbc.edu> thanks for the reply - it worked. I just want to make sure that I understand the general syntax - when can I use the iteration variable as x (e..g. print x), and when do I need to use the ...%s... %x syntax? is it only when I need to call x as a "string"? I am not sure I am asking the question right or using the right terms as I am fairly new to programing and python. Thanks for your time. Ben Brian Blais wrote: > On Jul 8, 2008, at Jul 8:8:08 PM, Ben Keshet wrote: > >> I want to use a 'for' iteration to manipulate files in a set of >> folders, something like: >> >> folders= ['1A28','1A6W','56Y7'] >> for x in folders: >> print x # print the current folder >> f = open('my/path/way/x/my_file.txt', 'r') >> ... >> > > > I think: > > f = open('my/path/way/%s/my_file.txt' % x, 'r') > > should work, although I would probably be more clear about the names, > like: > > folders=['1A28','1A6W','56Y7'] > for folder in folders: > filename='my/path/way/%s/my_file.txt' % x > fid=open(filename,'r') > .... > > also, make sure that you do mean the relative path my/path/way/... > # in current folder > as opposed to the absolute path: /my/path/way > # in root folder > > > bb > -- > Brian Blais > bblais at bryant.edu > http://web.bryant.edu/~bblais > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Thu Jul 17 15:21:15 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 17 Jul 2008 12:21:15 -0700 (PDT) Subject: storing references instead of copies in a dictionary References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: On Jul 17, 10:05?am, mk wrote: > > def f2(arg): > > ? ? return "f2 "+arg > > > def f1(arg): > > ? ? return "f1 "+arg > > > a={"1":"f1","2":"f2"} > > print [eval(x[1])(x[0]) for x in a.items()] > > def f2(arg): > > ? ? return "New f2 "+arg > > print [eval(x[1])(x[0]) for x in a.items()] > > Neat trick, if probably dangerous in some circumstances. Anyway, thanks, > I didn't think of that. > > > Don't know if this is any use to you.. > > At least I learned something. :-) You want consistent access to a changing variable. Wrap it in an object: >>> a= Blank( ) >>> a.ref= 'X' >>> a.ref 'X' >>> b= a >>> b.ref 'X' >>> a.ref= 'Y' >>> b.ref 'Y' >>> From marc.wyburn at googlemail.com Wed Jul 30 07:45:50 2008 From: marc.wyburn at googlemail.com (marc wyburn) Date: Wed, 30 Jul 2008 04:45:50 -0700 (PDT) Subject: variable expansion with sqlite Message-ID: Hi I'm using SQlite and the CSV module and trying to create a class that converts data from CSV file into a SQLite table. My script curently uses functions for everything and I'm trying to improve my class programming. The problem I'm having is with variable expansion. self.cursor.executemany('INSERT INTO test VALUES (?)', CSVinput) If CSVinput is a tuple with only 1 value, everything is fine. If I want to use a tuple with more than 1 value, I need to add more question marks. As I'm writing a class I don't want to hard code a specific number of ?s into the INSERT statement. The two solutions I can think of are; using python subsitution to create a number of question marks, but this seems very dirty or finding someway to substitue tuples or lists into the statement - I'm not sure if this should be done using Python or SQLite substitution though. Any tips on where to start looking? Thanks, Marc. From max at alcyone.com Mon Jul 21 02:53:46 2008 From: max at alcyone.com (Erik Max Francis) Date: Sun, 20 Jul 2008 23:53:46 -0700 Subject: Genetic programming: pygene, pygp, AST, or (gasp) Lisp? In-Reply-To: <7bfb3c41-b08b-49dc-9711-6e39a4667db2@b1g2000hsg.googlegroups.com> References: <7bfb3c41-b08b-49dc-9711-6e39a4667db2@b1g2000hsg.googlegroups.com> Message-ID: John Ladasky wrote: > Why not do genetic programming directly on Python code? Maybe my code > tree data structure is redundant to something which already exists? > But apparently Python's "_ast" module offers only one-way access -- it > will generate an AST from a piece of code, but you can't modify an > AST, and turn it back into executable code? I would definitely need > this latter feature. > > ALTERNATELY -- and I don't mention this to start a flame war -- in > pondering this problem I've noticed the frightening fact that Lisp > seems set up to handle genetic programming by design. The s- > expression syntax IS essentially a parse tree. Now, I've spent a few > hours with Lisp so far, and I can't make it do much of anything -- but > I DO see how Lisp could be helpful. Still, I'm reluctant to pursue a > language I don't know, and which I'm finding much harder to grasp than > any language I've tried before. The main advantages that Lisp has to a structural language like Python are that in Lisp there is no distinction between code and data -- they're represented in the same way -- and the syntatic uniformity of the language. Originally the idea with Lisp was that s-expressions were a lower-level syntax that a more Algol-like syntax would be translated to ... then it became aware that the syntax was actually a benefice in many ways, not a hindrance. > Is there a way to interface Lisp to Python, so that I can do all the > interface programming in the language I already know best -- and just > do the genetic parts in Lisp? I haven't seen exception handling in > Lisp, a feature I've come to love in Python. Since it is fairly easy > for a randomly-generated program to generate illegal output (I already > know this from my initial experiments in Python), I don't think I can > live without exception handling. It is not likely you want to do this. Genetic programming systems are probably best run in a sandbox, for reasons which should be pretty reasonable. The point of genetic programming is to manipulate programs into new programs; thus, complicated syntax for those programs only increases the chances that either 1. you have to do an awful lot of extra work to make sure that you end up with valid programs or 2. you end up with an awful lot of syntactically invalid programs. Both of these waste large amounts of processing cycles that you could be focusing on creating new, valid programs from old ones. > I also think that Python has a higher-level understanding of a > variable's "type" or an object's "class" than Lisp does -- if I'm > hacking at a parse tree and I want to minimize syntax errors, I need > to know more than the fact that an element in an expression is an atom > or a list. If you're interested in typed genetic programming systems, then you might want to check out some of the stack-based genetic programming languages like Push or PushGP. These are in effect a stack-based form of Lisp, but which use different data stacks for different types. > Producing human-readable code from my genetic programming search would > be a great bonus -- and for me, at this moment, this seems to mean > Algol-style syntax. (Sigh.) But it's not a requirement. Well, you could always translate s-expressions into m-expressions ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis It isn't important to come out on top, what matters is to be the one who comes out alive. -- Bertolt Brecht, 1898-1956 From mrkafk at gmail.com Fri Jul 18 06:11:41 2008 From: mrkafk at gmail.com (mk) Date: Fri, 18 Jul 2008 12:11:41 +0200 Subject: Unusual Exception Behaviour In-Reply-To: <1214.94685668058$1216317006@news.gmane.org> References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> <8904.90077804333$1216313689@news.gmane.org> <006001c8e831$5c1487b0$143d9710$@rawlins@thinkbluemedia.co.uk> <1214.94685668058$1216317006@news.gmane.org> Message-ID: > Ok, Just to add a little interest, when I comment out the configuration line > for my logging, like so: > > #logging.config.fileConfig("/myapp/configuration/logging.conf") > It appears to throw the exceptions as normal :-) :-s To tell the truth I have never used logging module extensively, so I'm not expert in this area and can't help you there. However, it seems to me that you may have stumbled upon some subtle bug / side effect of logging module that could cause some side effects in exceptions. Or perhaps it surfaces only in combination with glib? If you discover the root cause, please let us know on this ng, I'm also using Python extensions and bindings to other libraries and this could be of interest at least to me. From mail at timgolden.me.uk Thu Jul 10 11:58:57 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 10 Jul 2008 16:58:57 +0100 Subject: Local User Control In-Reply-To: References: Message-ID: <487631C1.20403@timgolden.me.uk> Sparky wrote: > I don't know how feasible this is, but is it possible to have users > log in to access a local database file in such a way that allows the > program to know what user name and password they logged in with? This > would involve separate user names and passwords for each user. Well, this is a question which is crying out for some context. Are you talking about an existing database on an existing platform? If so, which one? Are you talking about a database youo're thinking of building? If so, the answer's probably yes but only you can know. Are you talking about something else altogether? TJG From cs at zip.com.au Sun Jul 27 19:10:58 2008 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 28 Jul 2008 09:10:58 +1000 Subject: Not entirely serious: recursive lambda? In-Reply-To: Message-ID: <20080727231058.GA24171@cskk.homeip.net> On 20Jul2008 00:08, Kay Schluehr wrote: | > Google was not my friend on this one, and I suspect there is no | > answer. | | Even the Great Google can't help if you don't use the right | keywords ;) Actually, I was shown an useful Google search syntax the other day: Searching for: foo looks just for "foo", but searching for: ~foo matches similar words. This came up in a discussion of web sites that use badly chosen keywords (the NSW Police gun licensing information talks only about "firearms", making it surprisingly hard to find; not that I have or want a gun license, but it was the example discussed). Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Humans are incapable of securely storing high quality cryptographic keys and they have unacceptable speed and accuracy when performing cryptographic operations. (They are also large, expensive to maintain diffcult to manage and they pollute the environment.) It is astonishing that these devices continue to be manufactured and deployed. But they are suffciently pervasive that we must design our protocols around their limitations. - C Kaufman, R Perlman, M Speciner _Network Security: PRIVATE Communication in a PUBLIC World_, Prentice Hall, 1995, pp. 205. From stefan_ml at behnel.de Wed Jul 2 12:22:16 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 02 Jul 2008 18:22:16 +0200 Subject: lxml validation and xpath id function In-Reply-To: <018b5155-64f5-46b3-b426-7e6d6d1b20e3@k37g2000hsf.googlegroups.com> References: <018b5155-64f5-46b3-b426-7e6d6d1b20e3@k37g2000hsf.googlegroups.com> Message-ID: <486bab38$0$27446$9b4e6d93@newsspool4.arcor-online.net> Floris Bruynooghe wrote: > I'm trying to use the .xpath('id("foo")') function on an lxml tree but > can't get it to work. Quick follow-up: this has been answered on the lxml mailing list: http://comments.gmane.org/gmane.comp.python.lxml.devel/3815 Stefan From fred.sells at adventistcare.org Fri Jul 11 14:20:36 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Fri, 11 Jul 2008 14:20:36 -0400 Subject: imaplib -- can't read body In-Reply-To: Message-ID: <0A53725C4A497848A7B3A0874B259831011B0992@acesxch01.ADVENTISTCORP.NET> I'm trying to read mail using the imaplib module. I can get the subject and date, but not the body, have not found any example on how to do that and I don't know much about imap. Here's what I have, working as noted... If anyone can show me what I'm missing in order to get the body of a mail message, that would be greatly appreciated, Fred ------------------- code starts below------------------------------- import imaplib, sys, os, re, rfc822 OK = "OK" FETCHTHIS = '(BODY[HEADER.FIELDS (SUBJECT FROM)])' ### got inemsg from the web, works up to the last line; msg.fp has no read and readline returns empty string. class inemsg: def __init__(self,msg): (self.msgfromname, self.msgfrom) = msg.getaddr('from') self.msgto = msg.getaddr('to') self.msgsubject = msg.getheader('subject') self.msgdate = msg.getheader('date') self.msgtext = msg.fp.read() class msg: # a file-like object for passing a string to rfc822.Message def __init__(self, text): self.lines = text.split('\015\012') self.lines.reverse() def readline(self): try: return self.lines.pop() + '\n' except: return '' class MailReader: def __init__(self, mailserver, user, password): self.M = imaplib.IMAP4(mailserver) self.M.login(user, password) result, message = self.M.select(readonly=1) print ( 'constructor', result, message) if result != OK: raise Exception, message def getMessages(self, *mailboxes): if mailboxes: filter = '(%s)' % ' '.join(list(mailboxes)) else: filter = '(UNSEEN UNDELETED)' mtype, data = self.M.search(None, filter ) print ('getMessages', mtype, data) for num in data[0].split(): f = self.M.fetch(num, FETCHTHIS) print ('fetch', f) m = rfc822.Message(msg(f[1][0][1]), 0) subject = m['subject'] fromaddr = m.getaddr('from') if fromaddr[0]=='': n = fromaddr[1] else: n=fromaddr[0] print (subject, fromaddr) return None #no reason to return until I can get the message content/body. if __name__=='__main__': x = MailReader("myserver", "myuser", "mypassword") messages = x.getMessages() print messages --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From paul.nospam at rudin.co.uk Tue Jul 22 02:30:52 2008 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Tue, 22 Jul 2008 07:30:52 +0100 Subject: Python Written in C? References: Message-ID: <87hcaiqvkz.fsf@rudin.co.uk> DaveM writes: > On Mon, 21 Jul 2008 03:18:01 +0200, Michiel Overtoom > wrote: > > >>Many major text/word processing programs (Emacs, vi, MS-Word) are also >>written in C. > > I thought Emacs was written in Lisp. The core - including the lisp interpreter - is written in C. A lot of the user functionality is written in (emacs) lisp. From __peter__ at web.de Tue Jul 22 11:31:10 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 22 Jul 2008 17:31:10 +0200 Subject: convert list of lists to list References: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> Message-ID: antar2 wrote: > Is there a way to convert list_of_listsA to list_of_listsB, where one > list in listof lists A is one element of listB? > > list_of_listsA: > [['klas*', '*', '*'], > ['mooi*', '*', '*', '*'], > ['koe'], > ['arm*', '*', '*(haar)'], > ['groei*', '*', '*', '*', '*']] > > listB: > ['klas* * *', 'mooi* * * *, 'koe', 'arm* * * (haar)', 'groei* * * * > *'] >>> outer = [['klas*', '*', '*'], ... ['mooi*', '*', '*', '*'], ... ['koe'], ... ['arm*', '*', '*(haar)'], ... ['groei*', '*', '*', '*', '*']] >>> [" ".join(inner) for inner in outer] ['klas* * *', 'mooi* * * *', 'koe', 'arm* * *(haar)', 'groei* * * * *'] Peter From bearophileHUGS at lycos.com Mon Jul 21 10:01:51 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 21 Jul 2008 07:01:51 -0700 (PDT) Subject: Almost keywords Message-ID: <30d1a9c0-331f-4263-9775-a1e639082769@m44g2000hsc.googlegroups.com> Once in a while I feel free to write about less defined things, saying mostly wrong things. This post is mostly chat, if you aren't interested please ignore it. Python is fit enough for newbie programmers, but some of its characteristics can confuse them still, like the variables referenced by name (that can be solved with a language that gives the illusion of always manging values), the finite nature of floating point numbers (that may be partially solved with interval arithmetic used in a smart way, even if it may end being quite slower than Python floats), the case sensitivity of all the language (in natural languages the case is often irrelevant), the absence of rational numbers from integer divisions, the code formatting precision required by significant indentations, the "artificial" difference between lazy and eager things, the silly syntax of tuples, some problems with closures that partially come from automatic creation of variable names, many inconsistencies present in the standard library, etc. Python 3.0 solved some of those problems, especially the smaller ones (for example the "nonlocal" keyword workaround, etc). If you take a look at the Python newsgroup, you can see that newbies there do many similar mistakes all the time. A language fit for newbies can adapt itself to avoiding those most common mistakes (but today Python is becoming larger and more complex, more fit for real programmers and less for programming newbies. This may be inevitable in the evolution of a a language with commercial success). One of the mistakes you see often is the rebinding of built-in things, like map, list, etc. (Python 3.0 again turns some of those names into keywords, avoiding part of those problems). So you can see code like this that may lead to bugs in programs written by newbies: list = [x*x for x in range(100) A possible way to avoid such bugs is to turn all those names like "list", "map", "filter", "self", etc into keywords. But this may have some disadvantages (well, I think I'd like to have "self" as keyword, seen how all Python books strong suggest to not use a name different from "self"). An intermediate solution is to change Python so that it allows you to rebind those half-keywords only of you want it and you know what you are doing, with a kind of comment at the top of the module: # rebinding = True This allows you to do: list = [x*x for x in range(100)] By default rebinding is False, so this produces a SyntaxError: list = [x*x for x in range(100)] This may be a silly idea. Designing a good syntax for a language isn't easy at all. Note that a widely used Scheme implementation, DrScheme, implements various sub-languages fit for newbies or almost-newbies or low- experienced programmers. What is possible for experts can be a syntax error for newbies. I don't like this feature much, I like more freedom, but for purely learning purposes it may have its place. So what I have said regarding the "almost keywords" isn't a totally new idea :-) Bye, bearophile From johnroth1 at gmail.com Fri Jul 11 10:22:19 2008 From: johnroth1 at gmail.com (John Roth) Date: Fri, 11 Jul 2008 07:22:19 -0700 (PDT) Subject: Python 3.0 and removal of the 'string' module References: <87wsjtqiyo.fsf@benfinney.id.au> <87iqvdq6qz.fsf@benfinney.id.au> <487706b7$0$9695$9b622d9e@news.freenet.de> <87abgorgiv.fsf@benfinney.id.au> Message-ID: <76f1bf48-b05f-472b-9bfc-cf59dd2a97ca@m45g2000hsb.googlegroups.com> On Jul 11, 6:26?am, Benjamin wrote: > On Jul 11, 3:06 am, Ben Finney > wrote: > > > "Martin v. L?wis" writes: > > > > > This is rather disappointing. Is that entire page suspect? > > > > All documentation about Python 3 is suspect until Python 3 gets > > > actually released (nobody can say for sure how the release will > > > look like in all details). > > > Is there a better information source, then, for the current state of > > what's expected in Python 3.0? > > Look at the development docs. We try to keep them up to date:http://doc.python.org/dev/3.0 > > > > > -- > > ?\ ? ? ? ??Somebody told me how frightening it was how much topsoil we | > > ? `\ ? are losing each year, but I told that story around the campfire | > > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? and nobody got scared.? ?Jack Handey | > > Ben Finney > > The PEPs are also a good source; library changes are all listed in PEP 3008. PEP 361 not only gives the schedule but it also gives a lot of detail on 3.0 features backported to 2.6 and incompatible features that raise warnings in 3.0 PEP 3000, PEP 3100 and PEP 3099 are also well worth reviewing. John Roth From rsimoes at gmail.com Wed Jul 16 01:57:32 2008 From: rsimoes at gmail.com (=?ISO-8859-1?Q?Richard_Sim=F5es?=) Date: Tue, 15 Jul 2008 22:57:32 -0700 (PDT) Subject: Redirecting stdout to another script Message-ID: Hopefully, this explanation will sufficiently clear despite the lack of code. I wrote a python script that takes data via stdin, does stuff with the data, and outputs the result to stdout. A friend wrote a perl script that opens a pipe to my script, feeds it data, and then accepts the result. The problem here is that the python script's outputting the result to stdout via print statements isn't doing what we expected: my friend's perl script isn't getting the result back via the pipe. Is there is simple solution for this problem? Whose script needs to be modified? Thanks, Richard Sim?es From wuwei23 at gmail.com Thu Jul 31 00:59:25 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 30 Jul 2008 21:59:25 -0700 (PDT) Subject: Native Code vs. Python code for modules References: Message-ID: On Jul 30, 11:14?pm, Sion Arrowsmith wrote: > >Well, the snarky response is most Python developers are too busy > >working on actual real world projects :) > > The follow-up snarky response is that working on actual real world > projects has lead Python developers to realise that most real world > bottlenecks arise from disk access, network speed, and user > interaction, and you should only sweat about code speed in the rare > case when you *know* that it's not its interface to the real world > that's slow. You won't hear any disagreement from me on that point :) From aahz at pythoncraft.com Sat Jul 26 20:03:50 2008 From: aahz at pythoncraft.com (Aahz) Date: 26 Jul 2008 17:03:50 -0700 Subject: Pwnie awards Message-ID: Boy, am I glad we're not listed: http://pwnie-awards.org/2008/awards.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From bearophileHUGS at lycos.com Tue Jul 29 19:07:35 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 29 Jul 2008 16:07:35 -0700 (PDT) Subject: static variables in Python? References: Message-ID: <115a132d-7edd-4b07-ba4f-7855577992d1@x41g2000hsb.googlegroups.com> kj: > OK, I guess that in Python the only way to do what I want to do > is with objects... There are other ways, like assigning the value out of the function, because Python functions too are objects: def iamslow(): return 100 def foo(x): return x + foo.y foo.y = iamslow() # slow computation print foo(1) print foo(2) Output is: 101 102 Another way is this, a bit more clean, with the same output: def iamslow(): return 100 def foo(x, y=iamslow()): return x + y print foo(1) print foo(2) But I suggest you to use a class in this situation, it's often the way that will keep your code more bug-free, and more readable by near- casual readers too. Python philosophy asks you to write readable code instead of clever code when possible, this is a difference from Perl, I presume. Bye, bearophile From fredrik at pythonware.com Thu Jul 17 06:16:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 12:16:11 +0200 Subject: Question about properties In-Reply-To: References: Message-ID: Frank Millman wrote: > I thought that the main point of using property was to prevent direct > access to the attribute. Not "prevent access to" as much as "add behaviour to". > Is this a valid comment, or does it come under the category of 'we are > all adults here'? The latter. And the "__" doesn't provide much protection, really (as we'll see below). > While experimenting, I came across the following curiosity. > > I know that prefixing a class attribute with a double-underscore makes > it difficult to access the attribute externally. Here is a simple > example - > >>>> class Test(object): > ... def __init__(self,x): > ... self.x = x > ... self.__y = 123 > ... def get_y(self): > ... return self.__y > >>>> t = Test(99) >>>> t.x > 99 >>>> t.get_y() > 123 >>>> t.__y > AttributeError: 'Test' object has no attribute '__y' > > I was surprised that I could do the following - > >>>> t.__y = 456 >>>> t.__y > 456 >>>> t.get_y() > 123 > > It's not important, but I am curious to know what is going on > internally here. hint: >>> dir(t) ['_Test__y', ..., '__y', 'get_y', 'x'] >>> t._Test__y 123 >>> t.__y 456 From ezindy at gmail.com Sat Jul 19 06:33:17 2008 From: ezindy at gmail.com (Egor Zindy) Date: Sat, 19 Jul 2008 11:33:17 +0100 Subject: ftdi chip + ctypes + ftd2xx... need help with reading chipid! (now with the right source code!) In-Reply-To: <4881C210.7000307@gmail.com> References: <4881C210.7000307@gmail.com> Message-ID: <4881C2ED.2080108@gmail.com> Egor Zindy wrote: > Dear List, > > This one is way beyond my comprehension skills, I just don't > understand what I'm doing wrong. > > I am trying to read the chipid from an FTDI chip based USB key > (DLP-D, http://www.ftdichip.com/Products/EvaluationKits/DLP-D.htm ), > using: > > - the ftd2xx module http://pypi.python.org/pypi/ftd2xx/0.1 > - the ftd2xx.dll which comes with the driver install > - the chipid dll (1.1.0) from here: > http://www.ftdichip.com/Projects/FTDIChip-ID.htm > - a ctypes interface I wrote by hand (only 7 functions to wrap, I > thought it'd be easy!) > > The ftd2xx is used for testing, to open / close the device. > > My Problem is that neither of the following two wrapped functions > (with the exact same arguments) return the right result (full > chipid.py library attached): > > def FTID_GetDeviceLocationID(DeviceIndex): > n = DWORD() > status = ftchipid.FTID_GetDeviceLocationID(DeviceIndex, > ctypes.byref(n)) > > if status != FTID_SUCCESS: > raise DeviceError,FTID_GetErrorCodeString("EN",status) > > return n.value > > def FTID_GetDeviceChipID(DeviceIndex): > n = DWORD() > status = ftchipid.FTID_GetDeviceChipID(DeviceIndex, > ctypes.byref(n)) > > if status != FTID_SUCCESS: > raise DeviceError,FTID_GetErrorCodeString("EN",status) > > return n.value > > * On my machine (XP, 32 bits), if I plug two keys in, I can get the > device chip id from the device with index=1. The one with index=0 > always gives the message "Invalid device handle." > * I get the wrong location id as well, 0 instead of 0x21... > * the FTID_GetNumDevices function also uses a byref, c_ulong and works. > * FTDI's win32 console example returns the right results (and uses c > unsigned longs) - available from > http://www.ftdichip.com/Projects/FTDIChip-ID.htm > > Any help appreciated! > > Regards, > Egor > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: chipid.py URL: From barry at python.org Thu Jul 17 23:42:31 2008 From: barry at python.org (Barry Warsaw) Date: Thu, 17 Jul 2008 23:42:31 -0400 Subject: RELEASED Python 2.6b2 and 3.0b2 Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team and the Python community, I am happy to announce the second beta releases of Python 2.6 and Python 3.0. Please note that these are beta releases, and as such are not suitable for production environments. We continue to strive for a high degree of quality, and these releases are intended to freeze the feature set for Python 2.6 and 3.0. From now until the planned final releases in October 2008, we will be fixing known problems and stabilizing these new Python versions. You can help by downloading and testing them, providing feedback and hopefully helping to fix bugs. You can also use these releases to determine how changes in 2.6 and 3.0 might impact you. ONLY ONE MORE BETA RELEASE IS PLANNED, so now is a great time to download the releases and try them with your code. If you find things broken or incorrect, please submit bug reports at http://bugs.python.org For more information and downloadable distributions, see the Python 2.6 website: http://www.python.org/download/releases/2.6/ and the Python 3.0 web site: http://www.python.org/download/releases/3.0/ See PEP 361 for release schedule details: http://www.python.org/dev/peps/pep-0361/ Enjoy, - -Barry Barry Warsaw barry at python.org Python 2.6/3.0 Release Manager (on behalf of the entire python-dev team) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSIARKHEjvBPtnXfVAQL7AQQAjPSbfKz2Oh/au/hPzS4x2IR5/R6FVe+g o9UYrONNRKJ14UHpbZRzvIvw/4G3PdpzzGxjYFIhVGEesEGJnMzT3YdkMHt4NW9d HOZxL3hseGbTdpUJPCsIkNG+4hX7iuY3NSV81Z75LGAL4tqbooGqwwUslXMT5f8s lRrZUcBRKZ0= =ju6s -----END PGP SIGNATURE----- From Tribulations at Paralleles.invalid Mon Jul 7 01:32:42 2008 From: Tribulations at Paralleles.invalid (TP) Date: Mon, 07 Jul 2008 07:32:42 +0200 Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> <6ddj74F21uhjU1@mid.individual.net> Message-ID: Peter Pearson wrote: Thanks for your answer. > When you run echo, it recognizes the 4-character "esc" as a > convention for representing a single character, and performs > the re-interpretation for you. When you tell python > "print '\033[30;44m foo \033[0m'", python interprets > the "\033" as a single character. So, the python print command *can* interpret these 4-character as a single character. It would be odd if there were no possibility to do the same thing when the characters are (i) stored in a python variable, or (ii) come from the environment variables. Does anybody know any way to re-interpret a string in Python? I have tried to play with "eval" (as in bash), but it does not yield anything. -- TP (Tribulations Parall?les) "Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert). From phillip.oldham at gmail.com Wed Jul 16 14:01:18 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Wed, 16 Jul 2008 11:01:18 -0700 (PDT) Subject: Is there any component-oriented (non-MVC) web framework available for Python? References: <5fdd1388-bb1e-4a59-8fd1-2aa1ce7fa6e0@79g2000hsk.googlegroups.com> Message-ID: On Jul 16, 6:48?pm, Alis wrote: > Hi > > Is there any component-oriented (non-MVC) web framework available for > Python? > > That is something like Apache Wicket, Tapestry or JSF, but I need it > to be in Python. > > Regards, > Ali Have you looked at kamaelia? http://kamaelia.sourceforge.net/ From larry.bates at websafe.com` Tue Jul 22 23:42:51 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 22 Jul 2008 22:42:51 -0500 Subject: Python Written in C? In-Reply-To: <6ejutcF6vgp3U4@mid.uni-berlin.de> References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Mon, 21 Jul 2008 18:12:54 +0200, mk wrote: > >> Seriously, though, would there be any advantage in re-implementing >> Python in e.g. C++? >> >> Not that current implementation is bad, anything but, but if you're not >> careful, the fact that lists are implemented as C arrays can bite your >> rear from time to time (it recently bit mine while using lxml). Suppose >> C++ re-implementation used some other data structure (like linked list, >> possibly with twists like having an array containing pointers to 1st >> linked list elements to speed lookups up), which would be a bit slower >> on average perhaps, but it would behave better re deletion? > > An operation that most people avoid because of the penalty of "shifting > down" all elements after the deleted one. Pythonistas tend to build new > lists without unwanted elements instead. I can't even remember when I > deleted something from a list in the past. > > Ciao, > Marc 'BlackJack' Rintsch When I use os.walk and need to remove directories or files. Seems to be the only way to do the in-place delete that is required. But you are right, it is very seldom. -Larry From larry.bates at websafe.com` Tue Jul 15 16:00:11 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 15:00:11 -0500 Subject: Testing for connection to a website In-Reply-To: References: Message-ID: Alexnb wrote: > Okay, I already made this post, but it kinda got lost. So anyway I need to > figure out how to test if the user is able to connect to a specific website. > Last time I got pointed to the urllib2 page, but if I do urlopen() and and > am not connected, the program stops. So I don't know if that was what you > guys wanted me to do, but I don't think so, you guys are smarter than that. > So, how can I test for connection to a website. You can test DNS resolution by doing this: import socket # # Check to make sure domain is legal and that I can resolve it to IP addr # try: ipaddr=socket.gethostbyname(domain) except socket.gaierror: print "Internet connection or DNS error" For the "connect to a specific website" portion you just have to wait until it times out to determine failure. -Larry From bj_666 at gmx.net Fri Jul 4 09:13:24 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 Jul 2008 13:13:24 GMT Subject: Static Class Initialization Question. References: <486e16c8$0$22780$426a34cc@news.free.fr> Message-ID: <6d6lvkF134f0U2@mid.uni-berlin.de> On Fri, 04 Jul 2008 14:59:05 +0200, Thomas Troeger wrote: > Bruno Desthuilliers wrote: >>> I want to have a list of such classes instantiated automatically on > > Of course I meant class instances ... sorry :) It's always good to have > an example to compensate for English errors *g*. Well, "class instances" is still a little bit ambiguous in a language where classes are objects too. ;-) > Ah I knew there was something and I couldn't find it in the docs > anymore! Now my potential follow-up question is answered as well, namely > how I can instantiate with variable argument lists, like this: > > >>> bla = [A(*args) for args in ((), (1,), (1, 2))] > >>> map(str, bla) > ['A(0,1)', 'A(1,1)', 'A(1,2)'] Looks like you want default values for the arguments of `A.__init__()`. Ciao, Marc 'BlackJack' Rintsch From mal at egenix.com Wed Jul 2 13:30:02 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 02 Jul 2008 19:30:02 +0200 Subject: Win32.client, DAO.DBEngine and exceeding the file sharing count lock In-Reply-To: <9ab0cc2d-5a7e-40ca-a4da-084347f147cd@m36g2000hse.googlegroups.com> References: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> <9ab0cc2d-5a7e-40ca-a4da-084347f147cd@m36g2000hse.googlegroups.com> Message-ID: <486BBB1A.5070305@egenix.com> On 2008-07-02 16:54, Iain King wrote: > On Jul 2, 3:29 pm, Tim Golden wrote: >> Iain King wrote: >>> Hi. I'm using the win32 module to access an Access database, but I'm >>> running into the File Sharing lock count as inhttp://support.microsoft.com/kb/815281 >>> The solution I'd like to use is the one where you can temporarily >>> override the setting using (if we were in VB): >>> DAO.DBEngine.SetOption dbmaxlocksperfile,15000 >> Really hurried answer: >> >> >> import win32com.client >> >> dao = win32com.client.gencache.EnsureDispatch ("DAO.DBEngine.36") >> dao.SetOption (Option=win32com.client.constants.dbMaxLocksPerFile, Value=15000) >> >> >> TJG > > Thanks. I found this: http://blogs.msdn.com/michkap/archive/2007/07/13/3849288.aspx > which outlines some difference between DAO and ADO, including: > "Capability to set and change Jet options without making registry > changes (works in DAO through DBEngine.GetOption and > DBEngine.SetOption, fails in ADO, which has no such analogue)." You could try to use the Access ODBC driver and access the database that way via mxODBC. That would be faster as well: http://www.microsoft.com/technet/prodtechnol/windows2000serv/technologies/iis/reskit/iischp7.mspx (scroll down to table 7.1) Apart from that option and if you are really in need for larger transactions, I'd suggest that you move to SQL Server for processing (if you can). Access is not really made for heavy-lifting and big transactions. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 02 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania 4 days to go :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From steve at REMOVE-THIS-cybersource.com.au Tue Jul 29 19:42:59 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 23:42:59 GMT Subject: Boolean tests References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <87y73kg70u.fsf@benfinney.id.au> Message-ID: <009fa67c$0$20313$c3e8da3@news.astraweb.com> On Tue, 29 Jul 2008 21:25:44 +0100, Matthew Woodcraft wrote: > Ben Finney wrote: >> No, he retracted the *insult* and restated the *advice* as a distinct >> statement. I think it's quite worthwhile to help people see the >> difference. > > Ben, it was quite clear from Anders' post that he knows about > __nonzero__ . That's why the so-called advice is insulting. The original > phrasing was just the icing on the cake. Anders wrote: "But then you decide to name the method "__nonzero__", instead of some nice descriptive name?" That suggests to me that Anders imagined that __nonzero__ is something I just made up, instead of a standard Python method. What does it suggest to you? -- Steven From musiccomposition at gmail.com Thu Jul 24 22:45:27 2008 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 24 Jul 2008 19:45:27 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <579f9d5b-8984-425d-8d4f-b2ed0be8eaba@o40g2000prn.googlegroups.com> <4888cd25$0$15527$426a74cc@news.free.fr> Message-ID: <89fdab20-3e1e-459d-af7d-697942bd5159@j1g2000prb.googlegroups.com> On Jul 24, 11:43?am, Bruno Desthuilliers wrote: > > "explicit-is-etc" - just like the remaining of Python's zen - is a > general philosophy statement, not an absolute rule. Another quote states > that practicality beats purity. Very much so. In fact, I'd like you all to take a detour to a recent bug report [1] where I gained some interesting insight into the Zen. [1] http://bugs.python.org/issue3364 From motoom at xs4all.nl Sun Jul 20 21:18:01 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Mon, 21 Jul 2008 03:18:01 +0200 Subject: Python Written in C? Message-ID: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> Giveitawhril wrote... > REAL WORLD programmers who want to be generally useful go > and learn C#. No: Real programmers first eat a quiche and then return to their Pascal programming. > But the SOURCE is some old, high level language which no one wants to > use anymore! C is alive and kicking. Every language has its place. Plus, there exists implementations of Python written in Python itself; see PyPy: http://codespeak.net/pypy/dist/pypy/doc/home.html > Just noting that, if it is written in C, that throws a curve at me > in trying to balance the value of learning Python vs. some other > major language. Many major text/word processing programs (Emacs, vi, MS-Word) are also written in C. Does that mean you should do all your text processing in C? Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From socyl at 987jk.com.invalid Tue Jul 29 14:22:54 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 18:22:54 +0000 (UTC) Subject: Where is the documentation for psycopg2? Message-ID: Hi. I can't find any documentation for psycopg2. I'm a noob, so I'm sure I'm just not looking in the right place... Anybody know where it is? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From martin at v.loewis.de Sat Jul 26 05:28:53 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 26 Jul 2008 11:28:53 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: References: Message-ID: <488AEE55.3010503@v.loewis.de> > (Any recommendations on a flavor of 64 bit of Linux for the Intel > architecture would be appreciated) My recommendation is to use Debian or Ubuntu, as that's my personal preference. As MAL said, any recent distribution that supports AMD64 should be fine (assuming you are not interested in Itanium, SPARC64, HPPA (2.0), PPC64, or Alpha, which are all 64-bit flavors of Linux). Regards, Martin From crazychimp132 at gmail.com Tue Jul 15 12:18:20 2008 From: crazychimp132 at gmail.com (crazychimp132 at gmail.com) Date: Tue, 15 Jul 2008 09:18:20 -0700 (PDT) Subject: Method behavior for user-created class instances References: <42433fcd-fcdc-4f42-a427-c28241734b7c@z66g2000hsc.googlegroups.com> Message-ID: <5826b9d9-dc73-40c1-a476-209beff4e104@f36g2000hsa.googlegroups.com> On Jul 15, 9:53 am, "bruno.desthuilli... at gmail.com" wrote: > On 15 juil, 01:24, crazychimp... at gmail.com wrote: > > > Greetings. > > > I am looking for a way to achieve method behavior for a class I > > created. That is, it has a __call__ method, so can be called like a > > function. But I also want it to be treated as a method when it appears > > in a class body. > > You need to implement the descriptor protocol the same way the > function type do. > > import types > > class Foo(object): > def __call__(self, instance): > print "%s - %s" % (self, instance) > > def __get__(self, instance, cls): > return types.MethodType(self, instance, cls) > > class Bar(object): > foo = Foo() > > b = Bar() > b.foo() > > > I know this has to do with writing the __get__ > > method of foo, but I am wondering if there is perhaps some class I can > > just inherit from to get the proper __get__, which behaves identically > > to that of regular Python functions. > > Extending types.FunctionType doesn't work OOTB (there's some > incompatibility wrt/ metaclasses) Thanks, this got me started in writing it for 3.0. There are no more unbound methods in 3.0, so a check for whether instance is None is necessary to give the right behavior. Here is the final implementation I came up with: from abc import ABCMeta, abstractmethod from functools import update_wrapper from types import MethodType class decorator(metaclass = ABCMeta): def __init__(self, function): update_wrapper(self, function) self.function = function def __get__(self, instance, cls): if instance is None: return self return MethodType(self, instance) @abstractmethod def __call__(): pass To use it, write a class that inherits decorator and overrides __call__, probably doing something with self.function. From torriem at gmail.com Tue Jul 15 03:56:51 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 15 Jul 2008 01:56:51 -0600 Subject: Why is there no GUI-tools like this for Windows? In-Reply-To: <48796BD1.9030406@internetnowasp.net> References: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> <48796BD1.9030406@internetnowasp.net> Message-ID: <487C5843.3020802@gmail.com> Marcus.CM wrote: > So python for me is for anything except GUI. It becomes self rejecting > notion to do GUI in python when you type in those stuff that could have > been handled by an IDE, > thus for linux project i just do the web interface + php and let python > do all the other hard core work. This is probably exactly backwards of how I think of it. Python is ideally suited for creating and driving GUIs, things that dispatch work to libraries and routines that do the real work. This is known as the separation of the user interface from the backend business logic. While I feel python is equally good at backend processing as it as front-end stuff, many folks feel that Python may be too slow for certain kinds of data processing. Therefore by that logic, python only makes sense on the front end. To the original poster, get yourself this package: http://gladewin32.sourceforge.net/ Then google around for getting PyGTK working on Win32 and you're in business. Don't use glade's code-generation tools; they are obsolete. Instead use the glade xml file and the libglade or GTK Builder python bindings for GTK to load and create the GUIs on the fly. Personally I think that designing good-looking guis in Python using wxWidgets, PyGTK or PyQT in plain code is very fast and very easy. In fact I think that GUI builders are somewhat overrated as they cannot possibly cope with a GUI that will display data dynamically, or use custom widgets. That said, check out PyQT (definitely available on windows) and Qt's Designer. It pretty much blows glade and anything else I've seen out of the water. From fredrik at pythonware.com Mon Jul 21 17:38:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 23:38:06 +0200 Subject: Getting the name of a variable which was used as a function parameter. In-Reply-To: <9c24ced1-4a0b-4e04-9ce2-1d730e3d8dd7@d77g2000hsb.googlegroups.com> References: <9e2e64db-d594-408d-9418-b17133f23204@27g2000hsf.googlegroups.com> <6ekbg0F6vgp3U5@mid.uni-berlin.de> <9c24ced1-4a0b-4e04-9ce2-1d730e3d8dd7@d77g2000hsb.googlegroups.com> Message-ID: Ravi Kotecha wrote: > Of course I wouldn't, it is a total hack, mostly useless but fun. I > tried to do it after someone in #python efnet said it was impossible! your function only finds *some* name (if it finds a name at all), not *the* name, so you haven't really proven that someone wrong yet. you can get a lot closer by using more radical approaches, but I don't think it's possible to do this in a fully robust way, at least not from the Python level. From bdesth.quelquechose at free.quelquepart.fr Mon Jul 28 14:53:25 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Jul 2008 20:53:25 +0200 Subject: Protecting instance variables In-Reply-To: References: <6eb9iaF6779oU1@mid.uni-berlin.de> Message-ID: <488e319c$0$14077$426a34cc@news.free.fr> Nikolaus Rath a ?crit : > Hi, > > Sorry for replying so late. Your MUA apparently messes up the > References:, so I saw you reply only now and by coincidence. > > "Diez B. Roggisch" writes: >> Nikolaus Rath schrieb: >>> Hello, >>> >>> I am really surprised that I am asking this question on the mailing >>> list, but I really couldn't find it on python.org/doc. >>> >>> Why is there no proper way to protect an instance variable from access >>> in derived classes? >>> >>> I can perfectly understand the philosophy behind not protecting them >>> from access in external code ("protection by convention"), but isn't >>> it a major design flaw that when designing a derived class I first >>> have to study the base classes source code? Otherwise I may always >>> accidentally overwrite an instance variable used by the base class... >> Here we go again... >> >> http://groups.google.com/group/comp.lang.python/browse_thread/thread/188467d724b48b32/ >> >> To directly answer your question: that's what the __ (double >> underscore) name mangling is for. > > > I understand that it is desirable not to completely hide instance > variables. But it seems silly to me that I should generally prefix > almost all my instance variables with two underscores. Why on earth would you protect "almost all" your attributes ??? > I am not so much concerned about data hiding, but about not > accidentally overwriting a variable of the class I'm inheriting from. > > And, unless I misunderstood something, this is only possible if I'm > prefixing them with __. > > How is this problem solved in practice? Which "problem" ?-) What your afraid of almost never happens. FWIW, it *never* happened to me in now 8+ years. And I almost never use __name_mangling_protection (I'd say about half a dozen times, and mostly because I was getting a bit paranoid on these occasions). > I probably don't have a > representative sample, but in the libraries that I have been using so > far, there were a lot of undocumented (in the sense of: not being part > of the public API) instance variables not prefixed with __. Oh, while we're at it: the convention for "protected" attributes (that is: not part of the API, but ok to override) is to use a single leading undescore. > I have > therefore started to first grep the source of all base classes > whenever I introduce a new variable in my derived class. Is that > really the way it's supposed to be? What if one of the base classes > introduces a new variable at a later point? Well... Since Python is dynamicall typed, and since it has good support for composition/delegation, type hierarchies tends to be *way* much flatter than in Java or C++. So there's way less name collision hazards. As I said, what you fear just never happened to me so far, even in frameworks like Zope which is probably where you'll find the worst case of deep type hierarchies and multiple inheritance abuse in Python. IOW : unless your code suddenly breaks in strange ways after you've added a new attribute (or renamed one), just don't worry. From steve at REMOVE-THIS-cybersource.com.au Thu Jul 10 02:55:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 10 Jul 2008 01:55:45 -0500 Subject: Impossible to change methods with special names of instances of new-style classes? References: Message-ID: On Tue, 08 Jul 2008 17:56:45 -0400, Joseph Barillari wrote: > Hi python-list, > > I've just started using new-style classes and am a bit confused as to > why I can't seem to alter methods with special names (__call__, etc.) of > new-style class instances. [deploy weapon of mass snippage] Here is a possible work-around: >>> class Special(object): ... def __call__(self): ... try: ... return self.__dict__['__call__']() ... except KeyError: ... return 'foo' ... >>> s = Special() >>> s() 'foo' >>> s.__call__ = lambda: 'bar' >>> s() 'bar' -- Steven From starsareblueandfaraway at gmail.com Thu Jul 17 10:41:22 2008 From: starsareblueandfaraway at gmail.com (Roy H. Han) Date: Thu, 17 Jul 2008 10:41:22 -0400 Subject: % sign in python? In-Reply-To: References: Message-ID: <6a5569ec0807170741q524fedaatd6d1f1f9dd52b6d7@mail.gmail.com> The percent sign is a placeholder. For example, if level = 1 msg = 'look' Then '[[Log level %d: %s]]' % ( level, msg ) becomes '[[Log level 1: look]]' %d means insert an integer %s means insert a string You can also use dictionaries. d = {'string1': 'hey', 'string2': 'you'} Then '%(string1)s %(string2)s' % d becomes 'hey you' On Thu, Jul 17, 2008 at 10:33 AM, korean_dave wrote: > What does this operator do? Specifically in this context > > test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) > > (Tried googling and searching, but the "%" gets interpreted as an > operation and distorts the search results) > -- > http://mail.python.org/mailman/listinfo/python-list > From thomas.bugzilla at gmx.net Wed Jul 9 06:22:46 2008 From: thomas.bugzilla at gmx.net (Thomas) Date: Wed, 09 Jul 2008 12:22:46 +0200 Subject: Manipulating sys.path Message-ID: Hi all, I want to manipulate sys.path outside of PYTHONPATH (environment) and sys.path.append() (programmatically). A bit of background: We're maintaining a small application that includes a couple of Python scripts. Over time, a decent amount of code has been forked into modules, so the overall file system layout of our kit looks like this: tool/ bin/ prog1.py prog2.py ... lib/ pack1/ mod1.py mod2.py ... The issue I have is that I want to add the 'lib' directory to the module search path so that our programs prog1.py, prog2.py,... can find the modules pack1.mod1, pack1.mod2, ... But I want to keep this out of the program's source code which rules out statements like 'sys.path.insert(0, "../lib")'. We also want to be minimal-invasive for the hosting environment, so no copying of 'lib' into the standard Python lib directories (like /usr/local/lib/python2.5/site-packages etc.), nor forcing the user to change his PYTHONPATH shell environment. It should be solved locally in our kit's directory tree. I was thinking about putting code into a 'bin/__init__.py' file but that's only working for modules and not for executable scripts, right?! Then I came across the '.pth' files, but unfortunately they only seem to work in some standard paths (like the before mentioned /usr/local/lib/python2.5/site-packages), and not in the script directory (like 'bin' in my case) which is automatically added to sys.path. Can anybody think of something that could be of help here? Thanks, Thomas From duncan.booth at invalid.invalid Sun Jul 13 05:35:03 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Jul 2008 09:35:03 GMT Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> Message-ID: "Giampaolo Rodola'" wrote: > Having said that I'd like to understand if there are cases where > deleting or moving an element of the heap, causes heappop() to return > an element which is not the smallest one. Yes, of course there are: any time you delete element 0 of the heap you can do that. >>> heap = [0, 2, 1, 4, 5, 6, 7, 8, 9] >>> heapify(heap) >>> heap [0, 2, 1, 4, 5, 6, 7, 8, 9] >>> del heap[0] >>> heappop(heap) 2 >>> By definition, element 0 is always the smallest but the next two elements could be in any order. If you delete an element other than 0 then the next pop won't be guaranteed to work. If you delete an element other than 0 the very next pop will work, but the heap conditions won't necessarily be restored so subsequent elements may come out in the wrong order. A simple example: >>> heap = [0, 1, 3, 4, 2, 5] >>> heapify(heap) >>> heap [0, 1, 3, 4, 2, 5] >>> del heap[1] >>> heappop(heap), heappop(heap), heappop(heap) (0, 3, 2) From gagsl-py2 at yahoo.com.ar Mon Jul 28 04:29:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 Jul 2008 05:29:14 -0300 Subject: Command line arguements References: <73045cca0807272113y397de468yfcb00ffbbec7990a@mail.gmail.com> Message-ID: En Mon, 28 Jul 2008 01:43:52 -0300, Henry Chang escribi?: > try optparse :) > http://docs.python.org/lib/module-optparse.html (optparse might be too much for a single argument) > On Sun, Jul 27, 2008 at 9:13 PM, aditya shukla > wrote: > >> in other words i do not want to do hard code the name of the file in my >> code every time i need to read it. >> >> I was reading about the sys module and i guess sys.argv would take the >> input from the command line whenever i run the python script . Exactly. Try this: import sys print sys.argv with no arguments, one, and several, and see what happens. -- Gabriel Genellina From python at rcn.com Sun Jul 20 02:38:24 2008 From: python at rcn.com (Raymond Hettinger) Date: Sat, 19 Jul 2008 23:38:24 -0700 (PDT) Subject: Question References: Message-ID: <6f98da19-d1d1-4e3f-ad5d-04c65a497894@y22g2000prd.googlegroups.com> On Jul 19, 2:27?am, perl_wiz... at manx.net wrote: > Why is Perl so much better than python? Because dollar signs are a superior form of punctuation. Raymond From goldtech at worldpost.com Sun Jul 13 11:30:14 2008 From: goldtech at worldpost.com (goldtech) Date: Sun, 13 Jul 2008 08:30:14 -0700 (PDT) Subject: SAX XML Parse Python error message Message-ID: SAX XML Parse Python error message Hi, My first attempt at SAX, but have an error message I need help with. I cite the error message, code, and xml below. Be grateful if anyone can tell me what the fix is. Thanks. >>> Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\pythonscripts\xml\parse3.py", line 43, in ? parser.parse(r'C:\perlscripts\xml\Document2.kml') File "C:\Python24\lib\xml\sax\expatreader.py", line 107, in parse xmlreader.IncrementalParser.parse(self, source) File "C:\Python24\lib\xml\sax\xmlreader.py", line 123, in parse self.feed(buffer) File "C:\Python24\lib\xml\sax\expatreader.py", line 207, in feed self._parser.Parse(data, isFinal) File "C:\Python24\lib\xml\sax\expatreader.py", line 303, in end_element self._cont_handler.endElement(name) File "C:\pythonscripts\xml\parse3.py", line 39, in endElement print self.description, str(self.coordinates) AttributeError: G_Handler instance has no attribute 'coordinates' >>> Code: from xml.sax import make_parser from xml.sax.handler import ContentHandler import string class G_Handler(ContentHandler): def __init__ (self): self.isFolderElement = 0 self.isdescriptionElement = 0 self.iscoordinatesElement = 0 def startElement(self, name , attrs): if name == 'Folder': self.isFolderElement= 1 self.Folder = "" if name == 'description': self.isdescriptionElement= 1 self.description = "" if name == 'coordinates': self.iscoordinatesElement = 1 self.coordinates = "" def characters (self, ch): if self.isFolderElement == 1: self.Folder = ch if self.isdescriptionElement == 1: self.description = ch if self.iscoordinatesElement == 1: self.coordinates = ch def endElement(self, name): if name == 'Folder': self.isFolderElement = 0 if name == 'description': self.isdescriptionElement= 0 if name == 'coordinates': self.iscoordinatesElement = 0 print self.description, str(self.coordinates) parser = make_parser() parser.setContentHandler(G_Handler()) parser.parse(r'C:\perlscripts\xml\Document2.kml') abc -84.4, 33.7 abc -86.7, 36.1 From castironpi at gmail.com Tue Jul 8 11:29:08 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 8 Jul 2008 08:29:08 -0700 (PDT) Subject: "in"consistency? References: Message-ID: <871c6735-f2d2-4cd0-811d-0cd774d55bdd@m45g2000hsb.googlegroups.com> On Jul 7, 5:02?pm, Gary Herron wrote: > Nick Dumas wrote: > > -----BEGIN PGP SIGNED MESSAGE----- > > Hash: SHA1 > > > [1,2] in [1,2,3] checks to see if the list [1,2] is an item in [1,2,3]. > > Because the list [1,2,3] only contains the integers 1,2,3, the code > > returns a False. Try "[1,2] in [[1,2],[2,3]]" > > The inconsistency goes deeper than that. ?For instance, the type of a > value returned by the indexing operation: > > ? ?Indexing a string returns a string (of length 1 of course), > ? ?while indexing a list does not (necessarily) return a list. > > Conclusion: ?They are different types supporting different operations. ? > Given all the obvious differences (mutability, sorting and other > methods, types of individual elements), I'd say there are more > differences than similarities, even though, as sequences, ?they both > support a small subset of similar operations. > > Gary Herron > > > David C. Ullrich wrote: > > >> Luckily I tried it before saying no, that's > >> not how "in" works: > > >>>>> 'ab' in 'abc' > > >> True > > >>>>> [1,2] in [1,2,3] > > >> False > > >> Is there a reason for the inconsistency? I would > >> have thought "in" would check for elements of a > >> sequence, regardless of what sort of sequence it was... Strings are not containers. Another container type: Python 3.0b1 on win32 >>> {0} in {0,1} False Another string-like, non-container type: >>> bytes( [ 0, 1 ] ) in bytes( [ 0, 1, 2 ] ) True From kay.schluehr at gmx.net Sun Jul 27 03:03:58 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 27 Jul 2008 00:03:58 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> Message-ID: On 26 Jul., 19:20, Michele Simionato wrote: > On Jul 26, 5:28 pm, a... at pythoncraft.com (Aahz) wrote: > > > IMO, you made a big mistake in combining your point with two other meaty > > issues (whether method definitions should include self and whether != > > should use __eq__() as a fallback). > > > If solid discussion > > is your goal, I suggest that you wait a couple of weeks and start over > > with a brand-new thread. > > I fully subscribe this. The point about __eq__ is legitimate and could > be discussed with quite tones. > I was bitten by this surprising behavior just a few > days ago, I had defined __eq__ and I expected __neq__ > to be defined in the obvious way. I saw that it was > not the case and I figured out immediately that > I had to override __neq__ explicitely (I have > the "explicit is better than implicit" mantra > ingrained in my mind too), I did so and everything > worked out as a charm. Total time loss: five minutes. > So, it is not a big point. Still I think > that it would make sense to automatically > define __neq__ as the negation of __eq__. > I suppose the developers did not want to make a special > case in the implementation and this is also a legitimate > concern. > > Michele Simionato Incidentally I knew that I had to overload the negation of __eq__ explicitely and did so writing an __neq__ method. A few minutes later I found out it's not __neq__ but __ne__. So another few minutes were lost. From dullrich at sprynet.com Wed Jul 23 11:04:52 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Wed, 23 Jul 2008 10:04:52 -0500 Subject: repr(string) Message-ID: I've been saving data in a file with one line per field. Now some of the fields may become multi-line strings... I was about to start escaping and unescaping linefeeds by hand, when I realized that repr() and eval() should do. Hence the question: If s is a string, is repr(s) guaranteed not to contain line breaks? -- David C. Ullrich From jr9445 at ATT.COM Tue Jul 15 16:13:18 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Tue, 15 Jul 2008 15:13:18 -0500 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Victor Noagbodji > Sent: Tuesday, July 15, 2008 3:44 PM > To: python-list at python.org > Subject: Re: 'if name is not None:' v. 'if name:' > > >>what's the difference between these two statement? > >one checks if the given object is not None, the other checks if it's a > true value: > >http://docs.python.org/ref/Booleans.html#Booleans > >>And which one should one use? > >depends on what you want to test for, of course. > > > > > > Well that's exactly why I'm asking. Since None returns False in if > statements. Why do people use if name is not None: instead of simply > writing if not name? > If name is None: Then name is NULL, nothing, nada, no object, no memory allocated, a NULL pointer If name is not None: Then name is an object. It's a pointer to some kind of allocated structure in memory. No idea if it contains a false or true value. If name: Then either a) name is an object, and that object does not have a 'false' value, such as False, zero, or empty. or b) name is NULL/None. No object. Try this: d = dict() if not d: d['a'] = 1 print d d = None if not d: d['c'] = 3 print d ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA622 From ajdamico at gmail.com Thu Jul 24 06:23:54 2008 From: ajdamico at gmail.com (Anthony) Date: Thu, 24 Jul 2008 03:23:54 -0700 (PDT) Subject: Autocompletion and Interactive Tables in a Python IDE References: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Message-ID: FoxPro is data-oriented, which means that at any time you have any number of data sets open in the workspace and browse them immediately by running one line of code in the command window. It's a really important feature in terms of efficiency; I don't want to have to move back and forth between SPSS and an IDE when I'm figuring out what code to write, that takes six keystrokes for what FoxPro can do in one. Again, here's what the BROWSE command presents: http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=vfptoolkit_figure02.tif Does VIM have the capability to keep data open? -- Do any of these IDEs have this browse capability?? On Jul 24, 4:10?am, Aspersieman wrote: > Anthony wrote: > > Hi, I'm a FoxPro programmer, but I want to learn python before it's > > too late. ?I do a lot of statistical programming, so I import SPSS > > into python. ?In my opinion, the best features of Visual FoxPro 9.0 > > were: > > a) Intellisense (tells you what classes/methods are available and what > > variables go into a function) > > b) Code Completion (guesses your code after four letters) > > c) Data-Orientation; multiple data sessions can be open, data can be > > viewed easily > > > Python's IDLE has only half of the first of these features. ?I did a > > lot of searching and found the PyDev extensions for Eclipse's Python > > IDE, and found that they've got Intellisense. ?I'm still missing b and > > c, and am getting extremely frustrated programming so slowly.. > > > So two questions: > > Is there any package, gui, IDE, anything that will do FoxPro-style > > code completion? ?If it works in Eclipse, even better.. > > I can't find a good screenshot, but here's a better description: > > You type "BROW" and it pops up a window that says "BROWSE" ..at this > > point if you hit enter it completes the word.. > > > and > > > How can I view open SPSS data in one of the Python GUIs? ?Again, > > Eclipse would be the preference. > > Here's an example of how I'd like to browse the data: > >http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=... > > I don't want to have to switch back and forth between Python and SPSS > > while I'm programming; I just want to stay in one of them.. > > > What can I do? ?I feel extremely inefficient when I don't have these > > three features.. > > > Thanks in advance. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > You might want to try vim. It has a steep learning curve, but definitely > increases productivity _alot_. > > Here is a tutorial on setting up vim with : > ? ? 1) Code completion (intellisense) - including tooltips (!!!) > ? ? 2) Jump between your python code and the python class libraries. > ? ? 3) Syntax checking > ? ? 4) A handy source browser > ? ? 5) Debugging (using pdb) > ? ? 6) [All the other vim goodies - already included] > Above instructions available herehttp://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/ > > I have been using the above setup for a while and find it superior to > _any_ IDE I've ever worked with. > > I'm not sure what you mean by 'Data-Orientation' but I'm sure there's a > suitable alternative/replacement for it in vim. > > Regards > > Nicolaas > > -- > > The three things to remember about Llamas: > 1) They are harmless > 2) They are deadly > 3) They are made of lava, and thus nice to cuddle. From wuwei23 at gmail.com Fri Jul 25 10:39:01 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 25 Jul 2008 07:39:01 -0700 (PDT) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <6c5e878b-8e82-4ffb-bd8a-c673804774fe@x29g2000prd.googlegroups.com> Message-ID: On Jul 25, 9:54?pm, Jeff wrote: > Look at using reduce(). ?You can collect information about all of the > nodes without necessarily building a large, intermediate list in the > process. From the OP's description, I assumed there'd be a list of all nodes, from which he wishes to derive a 2nd list of specific nodes. reduce() applies "a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value", which doesn't seem to me to be what the OP was asking for. I could understand using map() across the filter'd list, or embedding the conditional check within the map'd function and ignoring filter(), but at no point does the OP ask to perform any kind of function based on two nodes... I may have misunderstand your point, though :) Could you provide a quick code sample to clarify? From skeept at gmail.com Thu Jul 10 17:46:50 2008 From: skeept at gmail.com (skeept) Date: Thu, 10 Jul 2008 14:46:50 -0700 (PDT) Subject: redirecting output of process to a file using subprocess.Popen() References: <515ad1dd-15b0-4f7a-8ea2-87e0bb0cb47e@f36g2000hsa.googlegroups.com> Message-ID: <6bed3372-e049-4301-9d6b-6b7cf0a4c2d9@y21g2000hsf.googlegroups.com> On Jul 9, 7:32?pm, rpar... at gmail.com wrote: > I am trying to redirect stderr of a process to a temporary file and > then read back the contents of the file, all in the same python > script. As a simple exercise, I launched /bin/ls but this doesn't > work: > > #!/usr/bin/python > import subprocess as proc > import tempfile > name = tempfile.NamedTemporaryFile(mode='w+b') > print 'name is '+ name.name > > cmd = [] > cmd.append('/bin/ls') > cmd.append('-l') > cmd.append('/tmp') > p = proc.Popen(cmd, stdout=name, stderr=proc.STDOUT, close_fds=True) > while True: > ? ?ret = p.poll() > ? ?if (ret is not None): > ? ? ? output = name.readlines() > ? ? ? print 'out = ', output > ? ? ? break > > $python sub.py > name is /tmp/tmpjz4NJY > out = ?[] > > I tried calling flush() on the file object but this didn't help > either. Tried closing and re-opening the file, but closing the file > object results in it getting deleted. Can the above be made to work by > using tempfiles? > > thanks your script works just fine. The problem is that you have to move to the beggining of the file to read the actual contents of the file. name.seek(0) The whole program would be: #!/usr/bin/python import subprocess as proc import tempfile name = tempfile.NamedTemporaryFile(mode='w+b') print 'name is '+ name.name cmd = [] cmd.append('/bin/ls') cmd.append('-l') cmd.append('/tmp') p = proc.Popen(cmd, stdout=name, stderr=proc.STDOUT, close_fds=True) while True: ret = p.poll() if (ret is not None): name.seek(0) output = name.readlines() print 'out = ', output break From no at spam.no Fri Jul 11 03:01:19 2008 From: no at spam.no (Thin Myrna) Date: Fri, 11 Jul 2008 09:01:19 +0200 Subject: ActiveState Code: the new Python Cookbook site References: <4873F326.5010905@activestate.com> <4874698E.7000805@gmail.com> Message-ID: <4877053f$0$16181$5402220f@news.sunrise.ch> Trent Mick wrote: > Stef Mientki wrote: >> one small remark, >> If I want to browse 200 recipes, at 10 per page .... >> ... please make something like 100 available per page, >> are internet is fast enough nowadays. > > Touche. Done: > > http://code.activestate.com/recipes/?paginate_by=100 > The old cookbook offered choices by category. Did you drop that feature? > Cheers, > Trent > Thin From rw.segaar at xs4all.nl Wed Jul 9 15:23:20 2008 From: rw.segaar at xs4all.nl (Robert) Date: Wed, 9 Jul 2008 21:23:20 +0200 Subject: formatting list -> comma separated Message-ID: <48750e4f$0$15106$e4fe514c@dreader27.news.xs4all.nl> given d: d = ["soep", "reeds", "ook"] I want it to print like soep, reeds, ook I've come up with : print ("%s"+", %s"*(len(d)-1)) % tuple(d) but this fails for d = [] any (pythonic) options for this? Robert From bj_666 at gmx.net Tue Jul 15 11:44:26 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Jul 2008 15:44:26 GMT Subject: Python internals question References: Message-ID: <6e3uuqF527ucU2@mid.uni-berlin.de> On Tue, 15 Jul 2008 23:54:46 +1000, Peter Anderson wrote: > "Python is a dynamically typed language in which names can represent > values of different types during the execution of a program. In fact the > names used in the program are really just labels for various quantities > and objects. The assignment operator simply creates an association > between a name and a value. This is different from C, for example, in > which a name (variable) represents a fixed size and location in memory..." > > As an old mainframe programmer, I understand the way C does things with > variable but this text got me wondering how Python handles this > "association" between variable name and value at the lower level. Is it > like a fifo list? Why a fifo list? Names don't remember the values and types they are bound to over time, there's just one binding at any time if a name exists. Internally you can think of a pointer to a struct that represents the object. Ciao, Marc 'BlackJack' Rintsch From walter at livinglogic.de Thu Jul 3 17:48:27 2008 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Thu, 03 Jul 2008 23:48:27 +0200 Subject: ANN: XML builder for Python In-Reply-To: <10df03a30807030812g201f35aet87477a245ae71fc4@mail.gmail.com> References: <486C5CA1.3080105@behnel.de> <486C5D63.5030407@behnel.de> <486CB9F3.3020902@livinglogic.de> <10df03a30807030812g201f35aet87477a245ae71fc4@mail.gmail.com> Message-ID: <486D492B.9070706@livinglogic.de> Jonas Galvez wrote: > Walter D?rwald wrote: >> XIST has been using with blocks since version 3.0. >> [...] >> with xsc.Frag() as node: >> +xml.XML() >> +html.DocTypeXHTML10transitional() >> with html.html(): >> [...] > > Sweet! I don't like having to use the unary operator tho, I wanted > something as simple as possible, so I wouldn't even have to assign a > variable on the with block ("as something"). You only have to assign the node a name in the outermost with block so that you can use the node object afterwards. But of course you can always implement the outermost __enter__/__exit__ in such a way, that the node gets written to an outputstream immediately. > I plan to add some > validation and error checking, but for generating feeds for my Atom > store it's reasonably fast and lean (just over 50 lines of code). Servus, Walter From fredrik at pythonware.com Thu Jul 24 07:48:39 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 13:48:39 +0200 Subject: how to cut and paste in the windows of python(command line) In-Reply-To: <9500663c-0985-4dfd-8d0a-ae25411f00e5@v39g2000pro.googlegroups.com> References: <9500663c-0985-4dfd-8d0a-ae25411f00e5@v39g2000pro.googlegroups.com> Message-ID: fang wrote: > The mouse cannot be responded in the windows of python(command > line) and cut and paste cannot be done. ctrl c and ctrl v do not work. > But they do work in IDLE. that has absolutely nothing to do with Python, and everything to do with what console or terminal program you're using. if you're using windows, you'll find edit commands, including copy and paste, commands in the window menu (click on the icon in the upper left corner). Python also supports the standard "doskey" commands (text+F8 to search in history, UP/DOWN to recall commands, ESC to clear, etc). if you want better console support, consider installing the "ipython" shell: http://ipython.scipy.org/moin/ From tjreedy at udel.edu Thu Jul 24 21:21:46 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jul 2008 21:21:46 -0400 Subject: Encoding for Devanagari Script. In-Reply-To: References: Message-ID: Atul. wrote: > Hello All, > > I wanted to know what encoding should I use to open the files with > Devanagari characters. I was thinking of UTF-8 but was not sure, any > leads on this? Anyone used it earlier? You cannot hurt your machine by giving that a try. This is a general comment for all beginners. Before posting, open the interactive interpreter (or IDLE) and try something(s). If the result puzzles you, copy and paste into a post. Or if more appropriate, open the Python manuals and search a bit, or try a search engine. From motoom at xs4all.nl Sat Jul 12 08:45:53 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Sat, 12 Jul 2008 14:45:53 +0200 Subject: Use of index Message-ID: <2.2.32.20080712124553.00ca3e8c@pop.xs4all.nl> SUBHABRATA wrote... > Now, my q is can we use index like find? Yes, you can. There is only a difference when the string is not found: the 'find()' function will return -1, whereas 'index()' function will raise a ValueError exception. For example: >>> b="A spaghetti monster is always great" >>> print "monster" in b True >>> print b.find("monster") 12 >>> print b.index("monster") 12 >>> print b.find("pasta") -1 >>> print b.index("pasta") Traceback (most recent call last): File "", line 1, in print b.index("pasta") ValueError: substring not found >>> This is also documented in the built-in help: >>> help(b.index) Help on built-in function index: index(...) S.index(sub [,start [,end]]) -> int Like S.find() but raise ValueError when the substring is not found. >>> help(b.find) Help on built-in function find: find(...) S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. Hope this helps, Greetings -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From code at pizzashack.org Mon Jul 21 12:36:59 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 21 Jul 2008 12:36:59 -0400 Subject: Change PC to Win or Windows In-Reply-To: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> Message-ID: <20080721163659.GB8793@dragontoe.org> On Sat, Jul 19, 2008 at 02:56:07AM -0700, Lie wrote: > On Jul 19, 6:14?am, Derek Martin wrote: > > On Fri, Jul 18, 2008 at 03:46:13PM -0700, Joel Teichroeb wrote: > > Much like the English word "bank" (and numerous others), the term "PC" > > has come to have several meanings, one of which is the above. ?You may > > not like it, but we're pretty much stuck with the term, so you may as > > well get used to it. > > That's not the point, It very much IS the point. Language evolves based on common usage patterns of the people who use it. The term "PC" is commonly used in English, in the United States and other English speaking countries, to mean a computer running Microsoft Windows. That's a simple fact that you can not escape, no matter how much you may not like it (it just so happens that I also don't like it, but I realized long ago the futility of arguing against its usage). It's still a fact, and I described roughly how that fact came to be. It wasn't something that Apple started; it's been used this way in increasingly common usage for at least 20 years, although exactly what combination of hardware and software was being refered to as a "PC" has evolved over that timeframe. PC was a short form of "personal computer", which is how IBM came up with the name. Nevertheless, with the ubiquity of IBM hardware, and subsequent popularity of clones running Microsoft operating systems, the term "PC" has, in the present day, come to mean "a personal computer based on Intel-compatible hardware running a flavor of Microsoft Windows." It is used this way by the consumer computer industry, and it is used this way by the common population. Ipso facto "PC" means a windows box, in common English usage today. You don't have to like it, and you don't even have to acknowledge it. But if you choose not to, or argue against using it that way, you're in denial, plain and simple. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From fredrik at pythonware.com Thu Jul 24 07:58:18 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 13:58:18 +0200 Subject: Requires a character ... !! In-Reply-To: References: Message-ID: John Machin wrote: > You don't need a crystal ball; you just need to have been reading this > group/list for the last day or so --- the OP is trying to use Python > 2.2 on some *.py that are obviously written for a later version, > refuses to contemplate upgrading, and starts a new thread every time > he gets a syntax error. The traceback indicates that this is some software for working with debug data (http://dwarfstd.org/), but neither Google nor Kodos finds anything similar to the code you see in the tracebacks, so it's probably some proprietary stuff. And for some reason, the OP seems to be a bit unwilling to ask the supplier for help... From deets at nospam.web.de Wed Jul 30 13:25:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 30 Jul 2008 19:25:31 +0200 Subject: Standard module for parsing emails? References: <48908EF7.7060301@gmail.com> Message-ID: <6fbmilFanjibU1@mid.uni-berlin.de> Maric Michaud wrote: > Le Wednesday 30 July 2008 17:55:35 Aspersieman, vous avez ?crit?: >> For parsing the mails I would recommend pyparsing. > > Why ? email module is a great parser IMO. He talks about parsing the *content*, not the email envelope and possible mime-body. Diez From roy at panix.com Sat Jul 12 15:41:52 2008 From: roy at panix.com (Roy Smith) Date: Sat, 12 Jul 2008 15:41:52 -0400 Subject: why is "self" used in OO-Python? References: Message-ID: In article , Duncan Booth wrote: > Sadly a lot of Java programmers mistake the limitations of their language > for rules of OO programming, and worse this has spread from Java into other > languages where these restrictions no longer need apply. You can generalize that to, "a lot of programmers assume that OO is defined by whatever happens to be the first OO language they learn". In fact, it generalizes even further to the Law of Primacy (http://en.wikipedia.org/wiki/Principles_of_learning#Primacy). I recognize this drivel from the crud the FAA publishes: > Primacy, the state of being first, often creates a strong, almost unshakable, > impression. Things learned first create a strong impression in the mind that > is difficult to erase. For the instructor, this means that what is taught > must be right the first time. For the student, it means that learning must be > right. ?Unteaching? wrong first impressions is harder than teaching them > right the first time. If, for example, a student learns a faulty technique, > the instructor will have a difficult task correcting bad habits and > ?reteaching? correct ones. but fundamentally, it's true. If the first programming language (or the first OOPL) a person learns is Java, it should come as no surprise when they think they way Java does things is the only way to do things. Having seen no other ways yet, what else *could* they think? I have no objection to teaching Java in a CS curriculum. Or even making it the first language you teach. What I do object to is making it the ONLY language you teach. My next door neighbor's kid just finished a MSCS program. The curriculum did a pretty good job of covering most of the important topics, but they did it all in Java. Web development in Java, graphics programming in Java, algorithms in Java, etc. He's well prepared to get a job as a Java programmer (and, in fact, he did), but I don't think he's really trained to be a computer scientist. A good CS program should include a survey of different programming languages. Today, I would certainly want to give students exposure to C++, at least one of {Python,Ruby}, and a random sampling of some less main-line languages like Erlang, Lisp, PHP, Groovy, Smalltalk, or PostScript. Exactly which ones is not so important as getting to see a wide variety of different approaches. Only after you've seen a bunch of different ways of doing something can you start to appreciate the choices different language designers made. BTW, there's an interesting article in the July 2008 Computer Magazine: "In Priase of Scripting: Real Programming Pragmatism". Ronald Loui argues (amongst other things) that Python would make a good first language to teach in a CS curriculum. From sturlamolden at yahoo.no Fri Jul 11 14:16:37 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 11 Jul 2008 11:16:37 -0700 (PDT) Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> Message-ID: <13e282e4-cdf8-43f0-a42b-60158d36d56d@w7g2000hsa.googlegroups.com> On Jul 11, 12:00?pm, James Fassett wrote: > tuple_list = ( > ? ? ('John', 'Doe'), > ? ? ('Mark', 'Mason'), > ? ? ('Jeff', 'Stevens'), > ? ? ('Bat', 'Man') > ? ) > > # what I'd do in C or other procedural languages > result_list = [] > for item in tuple_list: > ? ? result_list.append(item[0]) Here are some various 'functional' solutions. Pick the one that fits your problem best: result_list = [fn for fn,ln in tuple_list] result_generator = (fn for fn,ln in tuple_list) result_list = map(lambda (fn,ln): fn, result_list) result_generator = itertools.imap(lambda (fn,ln): fn, result_list) From marcus at internetnowasp.net Mon Jul 21 12:17:44 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Tue, 22 Jul 2008 00:17:44 +0800 Subject: Python Written in C? In-Reply-To: References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> <4884B3EB.4090001@timgolden.me.uk> Message-ID: <4884B6A8.6070300@internetnowasp.net> Its called a BMW today. Fredrik Lundh wrote: > Tim Golden wrote: > >>> Wrong! Real programmers can program using only Touring machine >> >> Is that some kind of bicycle? > > there's a nearly infinite number of software projects with that name, > but the Ultimate Touring Machine could be found in sydney not long ago: > > http://tinyurl.com/5t2dl4 > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From s0suk3 at gmail.com Wed Jul 16 00:32:49 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Tue, 15 Jul 2008 21:32:49 -0700 (PDT) Subject: Modify a string's value References: Message-ID: <8c7245ed-2341-4283-988c-8a8adf3e58fd@56g2000hsm.googlegroups.com> On Jul 15, 6:46 pm, Larry Bates wrote: > s0s... at gmail.com wrote: > > Hi everyone, > > > I've heard that a 'str' object is immutable. But is there *any* way to > > modify a string's internal value? > > > Thanks, > > Sebastian > > Why would you care? Just create a new string (with the changed contents) and > let garbage collection take care of the old one when all the references to it > have gone away. Since these types of questions seem to appear almost every day > on this list, this Python stuff is so much different than old languages people > have hard time making the conceptual "jump". You can basically quite worrying > about how/where things are stored, they just are. > Thanks for the reply. It's not that I'm having a hard time learning Python. I've been programming it for some time. I just came across this unusual situation where I'd like to modify a string passed to a function, which seems impossible since Python passes arguments by value. (Whereas in C, you'd customarily pass a pointer to the first character in the string.) I was playing around trying to simulate C++-like stream operations: import sys from os import linesep as endl class PythonCout: def __lshift__(self, obj): sys.stdout.write(str(obj)) return self def __repr__(self): return "" cout = PythonCout() cout << "hello" << endl But then trying to simulate cin: class PythonCin: def __rshift__(self, string): string = sys.stdin.readline() # which doesn't make sense line = "" cin >> line And there goes the need to modify a string. :) From fredrik at pythonware.com Wed Jul 16 03:31:30 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 09:31:30 +0200 Subject: Is this correct behavior for default parameters? In-Reply-To: <344469045.20080716120322@wn.com.au> References: <344469045.20080716120322@wn.com.au> Message-ID: Bruce Pearson wrote: > The first call to test has the file_list empty but on the second call to > test the file_list is no longer empty but contains the values appended > in the first call. > > Is this correct behavior? I'm using python 2.5 yes: http://docs.python.org/ref/function.html "Default parameter values are evaluated when the function definition is executed." (in bold, even) it's also explained in the tutorial (section 4.7.1) and in the FAQ. (it's always a good idea to double-check the documentation or google a little before convincing yourself that you may have found a bug in a commonly used part of a system that's over 15 years old and has been used by hundred of thousands of programmers). From fredrik at pythonware.com Mon Jul 21 17:10:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 23:10:35 +0200 Subject: imported module no longer available In-Reply-To: <8496caf30807210931y27f5a198q195c9fb752eea5f3@mail.gmail.com> References: <8496caf30807210656y3d8467eer83a953e7c37e556c@mail.gmail.com> <8496caf30807210928m27456a1ex747221ea829409a6@mail.gmail.com> <8496caf30807210931y27f5a198q195c9fb752eea5f3@mail.gmail.com> Message-ID: Jeff Dyke wrote: >> actually no, the only things in that fucntion were. >> print globals().keys() - i see it here >> print mymodulename - it fails here. >> >> the `import mymodulename` statement is at the very top of the file. >> >> plus the processing that was attempted after. so how did that processing use the "mymodulename" name? >> in fact in the calling >> method i was able to execute print mymodulename and it printed the >> expected python output. the calling method has nothing to do with what's considered to be a local variable in the method being called, so that only means that the name is indeed available in the global scope. >> So i went back to check that the name 'mymodulename' was not getting >> overwritten by something else and the error went away. I've been >> working on something else entirely for the past few hours and have >> changed none of the code...and now it works. which is even more >> troublesome then the error itself. more likely, it indicates that you removed the line that caused Python to treat that name as a local variable. >> Follow on question. If this name, mymodulename, was imported in some >> other module.fucntion local to a function like >> def anotherfunc(): >> import mymodulename >> >> would that remove it from the globals() and save it to a locals() ? I >> would assume the answer to be no. even after reading the page I pointed you to? import binds a name, so an import statement inside a function will cause Python to treat that name as a local variable (unless you add a global declaration to that function). maybe a few examples will make this clearer; the following snippets are complete programs: snippet 1: import module # adds module to the global namespace def func(): module.func() # uses module from the global namespace func() # no error here snippet 2: def func(): import module # adds module to the *local* namespace module.func() func() # no error here module.func() # doesn't work; no module in global namespace snippet 3: def func(): global module # marks module as a global name import module # adds module to the *global* namespace module.func() func() # no error here module.func() # no error here; global module set by function snippet 4: import module # adds module to global namespace def func(): import module # adds module to local namespace too print module # prints local variable module = None # sets local variable to None func() # no error here module.func() # no error here either; uses global namespace snippet 5: import module def func(): print module # fails with an UnboundLocalError. # lots of lines import module # adds to local namespace; marks name as local # some more code func() # will fail at print statement my guess is that the last snippet corresponds to your case. From mariusz.karpowicz.84 at gmail.com Thu Jul 17 10:46:35 2008 From: mariusz.karpowicz.84 at gmail.com (=?ISO-8859-2?Q?Mariusz_=28Bia=B3ystok=29?=) Date: Thu, 17 Jul 2008 07:46:35 -0700 (PDT) Subject: twistedmatrix Message-ID: <9b545be3-4ab4-4398-933b-f75ac3dca03a@x41g2000hsb.googlegroups.com> Hi. I'm newbie in Twisted. Can anyone explain how does twisted server work? What happens after reactor.listenTCP running? I've got many connections from one client (one connection-one socket), each of them is served by class serve(Protocol). every protocol owns transport every transport owns socket for me it's obvious that protocol returning data to client should use it's own socket but transport.write(data) writes data into buffer what happens then? when my server handles two requests from one client (one by one) it writes first data part to buffer, then second part ... and then writes back to socket. what more it buffers data when I start many clients and sends it to last one. help me? please? Mariusz From gagsl-py2 at yahoo.com.ar Wed Jul 30 20:47:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 21:47:06 -0300 Subject: proxy class and __add__ method References: <18715799.post@talk.nabble.com> <18730676.post@talk.nabble.com> Message-ID: En Wed, 30 Jul 2008 07:48:45 -0300, Magnus Schuster escribi?: >> __magic__ methods on new style classes are searched in the class, *not* >> in >> the instance. prx_i+1 looks for __add__ in type(prx_i), that is, in the >> proxy class. > > With this explanation the behaviour is absolutely clear. Can I find some > documentation anywhere containing more background information how magic > functions are resolved? I haven't been successful with the Python > Language > Reference. There is some documentation collected in http://www.python.org/doc/newstyle/ and you can see also PEP252 and PEP253... >> Try implementing a similar __getattr__ method in a metaclass. > > I am totally clueless how to do this. Below you find my attempt. Neither > __getattr__ nor __add__ of the metaclass 'meta' are ever called. May I > ask > you for some more guidance or corrections to the code below? Unfortunately, as you have noted, my suggestion of using a metaclass with __getattr__ doesn't work. That method isn't invoked when resolving those names. I've found this recipe http://code.activestate.com/recipes/252151/ which goes step by step: first a Proxy for old-style classes that works fine, then a version for new-style classes identical to yours, then a metaclass version with __getattr__ that doesn't work either, and finally a working version. Very nice example. Another -more complete- version is at http://code.activestate.com/recipes/496741/ I hope you can adapt these to match your requirements. -- Gabriel Genellina From workitharder at gmail.com Mon Jul 28 13:34:40 2008 From: workitharder at gmail.com (bukzor) Date: Mon, 28 Jul 2008 10:34:40 -0700 (PDT) Subject: Easier way to get the "here" path? References: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> Message-ID: <649bb102-51aa-4781-ad40-3762e59db626@56g2000hsm.googlegroups.com> On Jul 26, 9:19?am, Andrew wrote: > bukzor wrote: > >>>> from os.path import abspath, realpath > >>>> realpath(path.__file__.rstrip("c")) > > > '/home/bgolemon/python/symlinks/path.py' > > >>>> realpath(abspath(path.__file__.rstrip("c"))) > > > '/home/bgolemon/python/symlinks/symlinks/path.py' > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I find it interesting that I get something different: > > In [1]: import path > path.pyc > > In [2]: path.__file__ > Out[2]: 'path.pyc' > > In [3]: path.__file__.rstrip("c") > Out[3]: 'path.py' > > In [4]: from os.path import abspath, realpath > > In [5]: realpath(path.__file__.rstrip("c")) > Out[5]: '/home/andrew/sym/sym/path.py' > > In [6]: realpath(abspath(path.__file__.rstrip("c"))) > Out[6]: '/home/andrew/sym/sym/path.py' > > I get the same thing for realpath() and realpath(abspath()) > It seems to me you can just use: > > In [1]: import path > path.pyc > > In [2]: from os.path import abspath > > In [3]: realpath(path.__file__.rstrip("c")) > Out[3]: '/home/andrew/sym/sym/path.py' > > By the way, I am in /home/andrew/sym and path is symlinked from > /home/andrew/sym/sym/path.py to /home/andrew/sym/path.py > > -- > Andrew As you can see above, I get the wrong think if I do that. It's very strange that we're getting different things. I'm using python 2.4, maybe it was updated in 2.5? From tdelaney at avaya.com Mon Jul 28 19:45:33 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 29 Jul 2008 07:45:33 +0800 Subject: Getting python 2.4 dll In-Reply-To: Message-ID: Guillermo wrote: > Hi there, > > Is it possible to get a 2.4 dll of python for Windows easily? I need > it to use python as scripting language for Vim. http://www.python.org/ which leads you to: http://www.python.org/download/ which leads you to: http://www.python.org/download/releases/2.4.5/ which leads you to (for a binary release): http://www.python.org/download/releases/2.4.4/ Further questions along this line should be directed to: http://www.catb.org/~esr/faqs/smart-questions.html#before Tim Delaney From bj_666 at gmx.net Wed Jul 16 10:35:35 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Jul 2008 14:35:35 GMT Subject: Logging in __del__() References: <17056.2125546441$1216121658@news.gmane.org> Message-ID: <6e6f9nF5eajaU2@mid.uni-berlin.de> On Wed, 16 Jul 2008 12:38:50 +0100, Robert Rawlins wrote: > So, am I right to assume that python will still handle its garbage disposal > if I implement __del__(), it just handles circular references in a slightly > different way, but to the same effect. Right? No. Circular references in objects with a `__del__()` implementation are not collected! Why are you using `__del__()` anyway? Are you aware of the promises that are *not* made! It's not guaranteed when the method is called nor if it is called at all! Ciao, Marc 'BlackJack' Rintsch From circularfunc at gmail.com Wed Jul 9 22:07:55 2008 From: circularfunc at gmail.com (ssecorp) Date: Wed, 9 Jul 2008 19:07:55 -0700 (PDT) Subject: TypeError, I know why but not how!? Message-ID: <03cbb0d2-6a0c-4b86-a75e-b73c5677acc7@c65g2000hsa.googlegroups.com> Im looking into PvsNP: http://www.claymath.org/millennium/P_vs_NP/ so I thought I'd write the program just to get a feel for it. But I run into a problem. Why does it all the sudden return None? I mean I know why the program aborts but I dont understand why the None is generated all the sudden. Hitting recursion depth isn't reported with that error. Guess I am missing something very obvious. Traceback (most recent call last): File "C:\Python25\Progs\PNP\pnp.py", line 34, in gen(50) File "C:\Python25\Progs\PNP\pnp.py", line 32, in gen return generateList([], [(1,10),(4,272),(34,442),(112,42)], [], rooms) File "C:\Python25\Progs\PNP\pnp.py", line 27, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 27, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 27, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 27, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 27, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 25, in generateList room, placed = pair(incompatibles, placed) File "C:\Python25\Progs\PNP\pnp.py", line 12, in pair student1, placed = validate(placed) TypeError: 'NoneType' object is not iterable >>> ---------------------------------- the program: import random def validate(placed): student = round(random.random()*401) if student in placed: validate(placed) else: placed.append(student) return student, placed def pair(incompatibles, placed): student1, placed = validate(placed) student2, placed = validate(placed) pair1 = (student1,student2) pair2 = (student2,student1) if (pair1 or pair2) in incompatibles: placed.remove(student1) placed.remove(student2) pair(incompatibles, placed) else: return pair1, placed def generateList(dormlist,incompatibles, placed, rooms): if len(dormlist) < (rooms + 1): room, placed = pair(incompatibles, placed) dormlist.append(room) generateList(dormlist,incompatibles,placed,rooms) else: return dormlist def gen(rooms): return generateList([], [(1,10),(4,272),(34,442),(112,42)], [], rooms) gen(50) ------------------------------------------------------------------------------------------------------------------- some tests inserted: import random def validate(placed): student = round(random.random()*401) if student in placed: validate(placed) else: placed.append(student) return student, placed def pair(incompatibles, placed): x = validate(placed) print "x",x y = validate(placed) print "y",y print "-------------------------------------" student1, placed = x student2, placed = y #student1, placed = validate(placed) #student2, placed = validate(placed) pair1 = (student1,student2) pair2 = (student2,student1) if (pair1 or pair2) in incompatibles: placed.remove(student1) placed.remove(student2) pair(incompatibles, placed) else: return pair1, placed def generateList(dormlist,incompatibles, placed, rooms): ## print dormlist ## print placed ## print "---------------------------------------------------" if len(dormlist) < (rooms + 1): room, placed = pair(incompatibles, placed) dormlist.append(room) generateList(dormlist,incompatibles,placed,rooms) else: return dormlist def gen(rooms): return generateList([], [(1,10),(4,272),(34,442),(112,42)], [], rooms) gen(50) ------------------------ x (283.0, [283.0]) y (8.0, [283.0, 8.0]) ------------------------------------- x (359.0, [283.0, 8.0, 359.0]) y (158.0, [283.0, 8.0, 359.0, 158.0]) ------------------------------------- x (249.0, [283.0, 8.0, 359.0, 158.0, 249.0]) y (371.0, [283.0, 8.0, 359.0, 158.0, 249.0, 371.0]) ------------------------------------- x (199.0, [283.0, 8.0, 359.0, 158.0, 249.0, 371.0, 199.0]) y (292.0, [283.0, 8.0, 359.0, 158.0, 249.0, 371.0, 199.0, 292.0]) ------------------------------------- x None y (227.0, [283.0, 8.0, 359.0, 158.0, 249.0, 371.0, 199.0, 292.0, 47.0, 227.0]) ------------------------------------- Traceback (most recent call last): File "C:\Python25\Progs\PNP\pnp.py", line 44, in gen(50) File "C:\Python25\Progs\PNP\pnp.py", line 42, in gen return generateList([], [(1,10),(4,272),(34,442),(112,42)], [], rooms) File "C:\Python25\Progs\PNP\pnp.py", line 37, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 37, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 37, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 37, in generateList generateList(dormlist,incompatibles,placed,rooms) File "C:\Python25\Progs\PNP\pnp.py", line 35, in generateList room, placed = pair(incompatibles, placed) File "C:\Python25\Progs\PNP\pnp.py", line 17, in pair student1, placed = x TypeError: 'NoneType' object is not iterable From grahn+nntp at snipabacken.se Mon Jul 7 13:57:14 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 7 Jul 2008 17:57:14 GMT Subject: Cross Compiler for Python? References: Message-ID: On Mon, 7 Jul 2008 10:15:59 +0200, Hendrik van Rooyen wrote: > Up to now, I have been innocently using the vanilla python > that comes with the Linux distribution (Suse in my case). > > For the past few days, I have been playing with a little > device called an eBox - it is basically a 486 with 128Mb > memory, and a 1Gig pcmcia flash drive. > > We want to try to use this as an industrial controller, so > I want to load python onto it. > > So I downloaded the sources, and got them into the box, > over its ethernet connection. > > Then I got stymied - the configure script will not run, > because the "distribution" has no C compiler - it is > basically a kernel, and Busybox, with precious little else. ... This is a special case of a more general, non-Python problem which you will have to address if you want to build an industrial controller. If your target has no C compiler[1], you have to set up a cross-compiling environment. I'd be surprised if the eBox doesn't come with documentation covering this. If there are special procedures and requirements for cross-compiling Python (someone else indicated there are), I guess the Python installation notes must cover this in a general way. /Jorgen [1] Or even if it has one. It is much more convenient to build in your normal work environment where you have plenty of disk, CPU and RAM, a good text editor, version control, Perl ... -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From davidreynon at gmail.com Thu Jul 24 16:48:46 2008 From: davidreynon at gmail.com (korean_dave) Date: Thu, 24 Jul 2008 13:48:46 -0700 (PDT) Subject: Neat way to get rid of [" "] in sys.argv[n:] returns Message-ID: so, i code this: ----------------------------- #!/usr/bin/python import sys import os for param in os.environ.keys(): print "%20s %s" % (param,os.environ[param]) print(os.environ['PATH']) print(sys.argv[1:]) -------------------------- and then when i type in --> python test.py "testparameter" I get this output: ------------- ['testparameter'] ---------------- Is there a way to neatly, in one call to the parameter, to get rid of the [' and '] without bothering to replace() '[ with "" and replace() '] with ''? Thanks, From phil.lemelin at gmail.com Fri Jul 18 09:45:19 2008 From: phil.lemelin at gmail.com (phil lemelin) Date: Fri, 18 Jul 2008 09:45:19 -0400 Subject: Core Dump - Segmentation Fault -Newbie In-Reply-To: <8ba4373d-3d97-4e9a-a15e-723f6818c757@k36g2000pri.googlegroups.com> References: <8ba4373d-3d97-4e9a-a15e-723f6818c757@k36g2000pri.googlegroups.com> Message-ID: I would suggest importing traceback. import traceback try : mystuff except : print str(traceback.format_exc()) But in the case of a SegFault or core dump, it might not help you at all. Can you post part of the function ? On Fri, Jul 18, 2008 at 9:25 AM, wrote: > Hi - I am very new to python. I get this random core dump and am > looking for a good way to catch the error. I know the function my core > dump occurs. Is there any error catching/handling that I could use in > python? > -- > http://mail.python.org/mailman/listinfo/python-list > -- Philippe-Alexandre Lemelin -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Jul 25 18:10:17 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Jul 2008 18:10:17 -0400 Subject: Histogram of floating point values. In-Reply-To: <73045cca0807251502i58c6e83dt872c46a9e7bb6775@mail.gmail.com> References: <73045cca0807251502i58c6e83dt872c46a9e7bb6775@mail.gmail.com> Message-ID: aditya shukla wrote: > Hello folks, > > I have a list say > > data=[0.99,0.98,0.98,0.98,0.97,0.93,0.92,0.92,0.83,0.66,0.50,0.50] > > i am trying to plot histogram of these values > > i have installed numpy and matplotlib and this is what i am doing* > import numpy > import pylab > from numpy import * > from pylab import * > > input_hist=array(data) > pylab.hist(input_hist,bins=0.1) > and this is the error that i am getting > > _*(array([], dtype=int32), array([ 0.5]), )*_ > > > does this mean that i cannot plot a histogram of floating point values ? > or is there a way around Ask the pylab (matplotlib?) people what their error message means. From timr at probo.com Tue Jul 29 02:46:56 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 29 Jul 2008 06:46:56 GMT Subject: interpreter vs. compiled References: <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> Message-ID: castironpi wrote: > >In CPython yes. In IronPython yes: the parts that are compiled into >machine code are the interpreter, *not user's code*. WRONG! You are WRONG. At "compile" time, the Python code is compiled to an intermediate language. At "run" time, the intermediate language (which is still the user's code, just in another representation) is compiled into machine language. It is the user's program, not the interpreter. It's the exact same process that occurs in a C compiler. Most C compilers translate the C program to an intermediate form before finally converting it to machine language. The only difference is that, in a C compiler, both steps occur within the compiler. In IronPython, the two steps are separated in time. There is no other difference. >Without that >step, the interpreter would be running on an interpreter, but that >doesn't get the user's statement 'a= b+ 1' into registers-- it gets >'push, push, add, pop' into registers. You have a fundamental misunderstanding of the compilation process. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From basti.wiesner at gmx.net Sun Jul 6 14:13:37 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sun, 06 Jul 2008 20:13:37 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Mark Wooding : > Sebastian "lunar" Wiesner wrote: > >> I just wanted to illustrate, that the speed of the given search is >> somehow related to the complexity of the engine. >> >> Btw, other pcre implementation are as slow as Python or "grep -P". I >> tried a sample C++-code using pcre++ (a wrapper around libpcre) and saw >> it running equally long. > > So some other implementations are equally poor. I note that Perl itself > handles this case very quickly, as does Edi Weitz's CL-PPCRE library. I don't know about the latter, but perl doesn't use any smart algorithm, it just heavily relies on memoization to gain speed. This makes perl perform poorly in other situations, as mentioned in the paper cited by Mark Dickinson: # perl -e '("a" x 100000) =~ /^(ab?)*$/;' zsh: segmentation fault perl -e '("a" x 100000) =~ /^(ab?)*$/;' In Python on the other, this pattern works fine, at the cost of performance losses on other patterns. It'd be interesting to know, how CL-PPCRE performs here (I don't know this library). > Yes, Perl-compatible `regular expressions' are more complicated than > POSIX extended regular expressions; but that doesn't mean that you have > to implement them in a dumb way. Indeed, it stands to reason that > expressions describing truly regular languages can be matched using the > same old algorithms that grep uses. I completely agree. I'd just believe, that the combination of some finite state machine for "classic" expressions with some backtracking code is terribly hard to implement. But I'm not an expert in this, probably some libraries out there already do this. In this case, it'd be time to give pythons re engine a more sophisticated implementation ;) -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From elessar at nienna.org Mon Jul 21 10:27:35 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Mon, 21 Jul 2008 23:27:35 +0900 Subject: Python Written in C? In-Reply-To: <488498f0$0$15075$e4fe514c@dreader28.news.xs4all.nl> References: <488473b7$0$3470$426a74cc@news.free.fr> <488498f0$0$15075$e4fe514c@dreader28.news.xs4all.nl> Message-ID: <48849CD7.2010501@nienna.org> Martin P. Hellwig wrote: > I disagree he has upper management written all over him. > In any case, the OP should remember that programming languages are all theoretically the same: if you can do it in one language, then you can theoretically do it any other. When choosing a language, you just need to find one that (a) has the right tools to do the job (libraries, methods of deployment, supported platforms, etc.) and (b) that you and your team are comfortable using. Python has the tools to tackle a huge range of problems (you can often use the standard library when you would have to write C code from scratch), and many find it, dare I say, fun to use (whereas I find C# roughly equivalent to being shot). Whether you should use it depends on your domain and your team's preference. -Matt From norseman at hughes.net Mon Jul 7 17:17:59 2008 From: norseman at hughes.net (norseman) Date: Mon, 07 Jul 2008 14:17:59 -0700 Subject: How to bypass Windows 'cooking' the I/O? (One more time, please) II In-Reply-To: References: Message-ID: <48728807.1010708@hughes.net> Dennis Lee Bieber wrote: > On Mon, 07 Jul 2008 01:03:10 -0700, norseman > declaimed the following in comp.lang.python: > >> > >> > Normal file I/O sequence: >> > >> > fp = open(target, 'wb') >> > >> > fp.seek(-1, 2) >> > >> > fp.write(record) >> > >> >> Except it doesn't do that in Windows. See below. >> > I wouldn't expect that sequence to work on any system... The "w" > implies "create new file, or truncate existing file to 0-bytes, then > write data to it" -- with no seeking permitted. You must include the "+" > to do seeking, and if you want to retain the existing file contents you > probably need to open with "a+" ("a" for append). > > The rest of your situation I won't touch. Other than to wonder why > the situation hasn't hit any of the various database servers which must > be operating in binary mode, and perform lots of seeking... Surely > somewhere out someone else must have encountered a seek crossing an > apparent mark (which isn't a normal Windows sequence anyway -- > since Windows uses for EOL, I'd have expected to see a problem > if backing over a ) ============================================= "I wouldn't expect..." ABSOLUTELY CORRECT. No append because the hex-1A has to be overwritten. (use r+b) There can be only one of those and it has to be the last byte of the file. The hex-0D at the beginning of a 32 BYTE segment signifies end of structure definition. The hex-1A double checks the record count. (standard Ashton-Tate dBASE file) If someone wants to check it out, appending the hex-1A to each record and backing up one byte on each write reduces coding complexity and machine cycles considerably. "The rest of..." I have seen the answer posted but can't find it. I'm hoping someone has it, sees this and posts the original solution again. Or knows how to set things to bypass the nonsense and posts that. Steve norseman at hughes.net From kmtracey at gmail.com Fri Jul 18 22:52:32 2008 From: kmtracey at gmail.com (Karen Tracey) Date: Fri, 18 Jul 2008 22:52:32 -0400 Subject: Change in Decimal repr in Python 2.6 In-Reply-To: References: Message-ID: On Fri, Jul 18, 2008 at 10:12 PM, Terry Reedy wrote: > If answers here do not satisfy, the pydev list would be the place to > request that this change be put off until 3.0, when changes that break are > more permissible. I do not remember any discussion of this issue. You can > also post there via news.gmane.org/g.c.python.devel (the mail to news > gateway). > Thanks, I'll probably try posting to pydev. Karen -------------- next part -------------- An HTML attachment was scrubbed... URL: From knielsen73 at gmail.com Mon Jul 28 18:34:54 2008 From: knielsen73 at gmail.com (knielsen73 at gmail.com) Date: Mon, 28 Jul 2008 15:34:54 -0700 (PDT) Subject: derivative in numpy Message-ID: Hi, I am looking to do a simple derivative. I would expect such a function to be available in numpy, but can't find it. I have written my own, but just curious if anybody knows of such function in numpy. Cheers, Kim From 2007 at jmunch.dk Tue Jul 29 05:45:44 2008 From: 2007 at jmunch.dk (Anders J. Munch) Date: Tue, 29 Jul 2008 11:45:44 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <488e4d2d$0$5967$ba624c82@nntp06.dk.telia.net> <009e5e66$0$20313$c3e8da3@news.astraweb.com> Message-ID: <488ee6c9$0$4463$ba624c82@nntp02.dk.telia.net> Steven D'Aprano wrote: > On Tue, 29 Jul 2008 00:23:02 +0000, Steven D'Aprano wrote: > >> Dude. Dude. Just... learn some Python before you embarrass yourself >> further. > > > I'm sorry Anders, that was a needlessly harsh thing for me to say. I > apologize for the unpleasant tone. > > Still, __nonzero__ is a fundamental part of Python's behaviour. You > should learn about it. Hm, first you apologize, then you repeat the insult? That's no basis for a conversation. Bye from here. regards, Anders From gherron at islandtraining.com Wed Jul 30 11:31:25 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 30 Jul 2008 08:31:25 -0700 Subject: Pointers/References in Python? In-Reply-To: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> References: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Message-ID: <4890894D.8020303@islandtraining.com> boblatest at googlemail.com wrote: > Hello, > > I have a long list of memory-heavy objects that I would like to access > in differently sorted order. Let's say I'd like to have lists called > by_date or by_size that I can use to access the objects in the > specified order. > > Of course I can just build those lists naively by creating copies of > the original list and then sorting them according to my wishes. But > that would create huge memory overhead. Of course I could use lists of > indices into the "master" list, just as in C I'd create lists or > arrays of pointers into the original data. > > Is there a clever Python way to do this, or should I just use lists of > indices? > No need. A Python list contains *references* to objects, not copies of objects. (The same is true of variables, dictionaries, sets, and so on...). For example, in the following code, only one copy of HeavyObject exists, however, it is referred to many times. a = HeavyObject() b = a A = [a,b] B = [b,a] C = set([a,b]) D = {1:a, 2:b} ... and do on Implementation wise, a long list consumes about 4 bytes per list element (that's one address per), plus a tine amount of overhead. Gary Herron > I know there is a thing called "shallow copy" that has something to do > with not duplicating memory content but I don't understand the > concept. Maybe that's what would help here, too. > > Thanks, > robert > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Tue Jul 22 11:42:08 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 17:42:08 +0200 Subject: convert list of lists to list In-Reply-To: References: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> Message-ID: Fredrik Lundh wrote: >> ['klas* * *', 'mooi* * * *, 'koe', 'arm* * * (haar)', 'groei* * * * >> *'] > > if there's only one level of recursion, and the lists aren't too long, > you can simply do: > > sum(list_of_lists, []) oops. that's what you get for taking the subject line too literally... From bruno.42.desthuilliers at websiteburo.invalid Tue Jul 1 05:41:38 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 01 Jul 2008 11:41:38 +0200 Subject: Functions associated with a class. In-Reply-To: References: Message-ID: <4869fbcd$0$4459$426a74cc@news.free.fr> Kurda Yon a ?crit : > Hi, > > I start to learn the object oriented programing in Python. As far as I > understood, every class has a set of corresponding methods and > variables. Every object has a set of attributes. Some of these attributes are methods (which are thmeselves objects too), some are not. Some are in fact attributes of the class of the object accessed thru the instance (mostly, the methods), some are instance-specific (mostly, non-methods). > For me it is easy to understand a method as a one-argument Why "one-argument" ? A method can take as amny arguments as necessary. > function associated with a class. s/class/object/. While methods are usually attributes of the class (accessed thru an instance), nothing prevents you from adding methods on a per-instance basis. This set aside, truth is that methods are just thin wrapper objects around a function, an instance and/or a class. The responsability of the method object is to delegate call to it's function object, inserting the instance (or the class in the case of a classmethod) as the first argument. > For example, if I call "x.calc" and > "y.calc" and if "x" and "y" belongs to different classes I, actually, > call to different function (the first one is associated with the first > class and the second one with the second class). Here again, it's a bit more complex. But this is a correct enough description of the most common case. > If "x" and "y" > belongs to the same class, the "x.calc" and "y.calc" refer to the same > function Usually, yes, but not necessarily: def yadda(obj): print "yadda(%s)" % obj class Bar(object): def foo(self): print "foo(%s)" % self b1 = Bar() b1.foo() b2 = Bar() b2.foo() b2.foo = yadda.__get__(b2, type(b2)) b2.foo() > (but called with different arguments ("x" and "y", > respectively)). > > In the above described case we have one-argument function. But what > should we do if we one two have a two-argument function. class Baaz(object): def gluuk(self, other): print "gluuk(%s, %s)" % (self, other) > For example, > we want to have a method "calc" which take two objects and returns one > value. How do we call this method? Like "x&y.calc"? class X(object): def calc(self, other): # this is silly since we don't use neither # self nor other, but you get the idea return "one value" Nope. > Or just calc(x,y)? That's one of the possibilities, but it's not a method anymore, just a plain function. The others solutions are either "x.calc(y)" or "y.calc(x)". Now which one is the right one depends on what calc do and how it relates to the respective classes of x and y. If the operation is really a responsability of one of the classes, then it should be a method of this class. Else it's probably better to stick to a plain function. > In the case of the one-argument functions Pythons automatically decide > which function to call Actually, x.calc() is (usually) a shortcut for type(x).calc(x), so you could say that in fact *you* make the decision of which function will be called !-) > (associated with the first class or with the > second class). Will it be the same in the case of the two-argument > function. It can't. OO polymorphic dispatch is (more or less by nature) a single dispatch mechanism. If you want a multiple dispatch (ie: dispatch on an arbitrary number of arguments) system, there are a couple packages providing this kind of features, but nothing builtin. Also, for a double dispatch mechanism, you can have a look at the Visitor design pattern. HTH From stesch at no-spoon.de Thu Jul 17 04:06:12 2008 From: stesch at no-spoon.de (Stefan Scholl) Date: Thu, 17 Jul 2008 10:06:12 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> <0T56p3tmInifNv8%stesch@parsec.no-spoon.de> <6e7v9qF5q74kU1@mid.uni-berlin.de> Message-ID: <0T56pitfI5raNv8%stesch@parsec.no-spoon.de> Marc 'BlackJack' Rintsch wrote: > On Thu, 17 Jul 2008 05:41:11 +0200, Stefan Scholl wrote: >> Fredrik Lundh wrote: >>> Stefan Scholl wrote: >>> >>>> Django isn't ready. >>> >>> That's a remarkably ignorant statement. >> >> The 1.0 release will be in September. > > So what? It's not the version number that matters but features and > stability. It's not uncommon in open source projects to have very usable > software with a version number below 1.0. The book is about the development version, which was current at the time the book was written. See page 4. Nobody says something about "Book after feature freeze" (or similar). Instead I get "ignorant statement" and "usable software". My conclusion: This book isn't about a stable release and not about a future stable release. (And even if it was about the last stable relase, too much has changed and will change until September 2008. IMHO.) And by the way: The quote was changed by deleting something on the same line: "June 2008 is a bit too early. Django isn't ready." vs. "Django isn't ready." -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 9 05:09:04 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 09 Jul 2008 11:09:04 +0200 Subject: Regular Expressions Quick Question In-Reply-To: References: Message-ID: <48748001$0$11973$426a74cc@news.free.fr> Rajanikanth Jammalamadaka a ?crit : (top-post corrected - Please, Rajanikanth, learn to trim"e properly, and by all means avoid top-posting) > > On Wed, Jul 9, 2008 at 12:13 AM, Lamonte Harris wrote: >> Alright, basically I have a list of words in a file and I load each word >> from each line into the array. I assume you meant 'list' ? > Then basically the question is how do I >> check if the input word matches multiple words in the list. >> >> Say someone input "test", how could I check if that word matches these list >> of words: >> >> test >> testing >> tested >> >> Out of the list of >> >> Hello >> blah >> example >> test >> ested >> tested >> testing >> >> I want it to loop then check if the input word I used starts any of the >> words in the list so if I typed 'tes' >> >> Then: >> >> test >> testing >> testing I assume you meant: test tested testing >> would be appended to a new array. > hi! > > Try this: > >>>> lis=['t','tes','test','testing'] >>>> [elem for elem in lis if re.compile("^te").search(elem)] Using a regexp for this is total overkill. But please at least use the proper regexp, and use re.compile correctly: exp = re.compile(r'^tes') found = [word for word in lis if exp.match(word)] But you just don't need a regexp for this - str.startswith is your friend: words = ['Hello', 'blah', 'example', 'test', 'ested', 'tested', 'testing'] found = [word for word in words if word.starswith('tes')] assert found == ['test', 'tested', 'testing'] HTH From ojeeves at gmail.com Fri Jul 18 08:21:19 2008 From: ojeeves at gmail.com (oj) Date: Fri, 18 Jul 2008 05:21:19 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> Message-ID: <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> On Jul 18, 12:10?pm, John Machin wrote: > On Jul 18, 9:05 pm, oj wrote: > > > > > On Jul 18, 11:33 am, arnimavidyar... at gmail.com wrote: > > > > Hi, > > > > Hi, > > > > I am taking a string as an input from the user and it should only > > > contain the chars:L , M or R > > > > I tried the folllowing in kodos but they are still not perfect: > > > > [^A-K,^N-Q,^S-Z,^0-9] > > > [L][M][R] > > > [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > > > > For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. > > > > regards, > > > SZ > > > > The string may or may not have all the three chars. > > > With regular expressions, [^LRM] matches a character that isn't L, R > > or M. So: > > > import re > > > var = "LRLRLRLNR" > > > if re.search(r'[^LRM]', var): > > ? ? print "Invalid" > > Fails if var refers to the empty string. No it doesn't, it succeeds if var is an empty string. An empty string doesn't contain characters that are not L, R or M. The OP doesn't specify whether an empty string is valid or not. My interpretation was that an empty string would be valid. From larry.bates at websafe.com` Sat Jul 19 16:31:47 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 19 Jul 2008 15:31:47 -0500 Subject: create instance attributes for every method argument In-Reply-To: <4780837f-a5bc-4071-94d3-28e2f206163e@k30g2000hse.googlegroups.com> References: <4780837f-a5bc-4071-94d3-28e2f206163e@k30g2000hse.googlegroups.com> Message-ID: Berco Beute wrote: > I remember reading somewhere how to create an instance attribute for > every method argument, but although Google is my friend, I can't seem > to find it. This could likely be done way more elegant: > > ========================= > class Test(object): > > def __init__(self, a, b, c, d, e, f): > self.a = a > self.b = b > self.c = c > self.d = d > ========================= > > 2B IMHO you can't do much better than that with positional arguments, but you can if they are keyword arguments. class foo(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) -Larry From andreas.mock at web.de Thu Jul 17 12:06:07 2008 From: andreas.mock at web.de (McA) Date: Thu, 17 Jul 2008 09:06:07 -0700 (PDT) Subject: unpacking with default values Message-ID: <335e7a21-e35e-41ee-9f92-fd4c2f6bf166@f36g2000hsa.googlegroups.com> Hi all, probably a dumb question, but I didn't find something elegant for my problem so far. In perl you can unpack the element of a list to variables similar as in python (a, b, c = [0, 1, 2]), but the number of variables need not to fit the number of list elements. That means, if you have less list elements variables are filled with 'undef' (None in python), if you have more list elements as necessary the rest is ignored. How can I achieve this behaviour with python in an elegant and fast way? Best regards Andreas Mock From basti.wiesner at gmx.net Wed Jul 23 12:00:26 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Wed, 23 Jul 2008 18:00:26 +0200 Subject: lxml, comparing nodes References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> Message-ID: code_berzerker : > I'd like to know if there is any built in mechanism in lxml that lets > you check equality of two nodes from separate documents. I'd like it > to ignore attribute order and so on. It would be even better if there > was built in method for checking equality of whole documents (ignoring > document order). Please let me know if you know of such method or > existing scipt. I dont like reinventing the wheel :) Did you try the equality operator? -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From code at pizzashack.org Sun Jul 27 23:39:18 2008 From: code at pizzashack.org (Derek Martin) Date: Sun, 27 Jul 2008 23:39:18 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <488ceae5$0$11227$426a34cc@news.free.fr> References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: <20080728033918.GG7373@dragontoe.org> On Sun, Jul 27, 2008 at 09:39:26PM +0200, Bruno Desthuilliers wrote: > >As for the latter part of #3, self (or some other variable) is > >required in the parameter list of object methods, > > It's actually the parameter list of the *function* that is used as the > implementation of a method. Not quite the same thing. The idea that Python behaves this way is new to me. For example, the tutorials make no mention of it: http://docs.python.org/tut/node11.html#SECTION0011300000000000000000 The Python reference manual has very little to say about classes, indeed. If it's discussed there, it's buried somewhere I could not easily find it. > consistency mandates that the target object of the method is part of > the parameter list of the *function*, since that's how you make > objects availables to a function. Fair enough, but I submit that this distinction is abstruse, and poorly documented, and also generally not something the average application developer should want to or have to care about... it's of interest primarily to computer scientists and language enthusiasts. The language should prefer to hide such details from the people using it. > >however when the method is *called*, it is omitted. > > Certainly not. Seems not so certain to me... We disagree, even after your careful explanation. See below. > You need to lookup the corresponding attribute *on a given object* > to get the method. Whether you write > > some_object.some_method() > > or > > some_function(some_object) > > you still need to explicitely mention some_object. But these two constructs are conceptually DIFFERENT, whether or not their implementation is the same or similar. The first says that some_method is defined within the name space of some_object. The second says that some_object is a parameter of some_function... Namespace != parameter!!!!!!!!! To many people previously familiar with OO programming in other languages (not just Java or C++), but not intimately familiar with Python's implementation details, the first also implies that some_method is inherently part of some_object, in which case explicitly providing a parameter to pass in the object naturally seems kind of crazy. The method can and should have implicit knowledge of what object it has been made a part. Part of the point of using objects is that they do have special knowledge of themselves... they (generally) manipulate data that's part of the object. Conceptually, the idea that an object's methods can be defined outside of the scope of the object, and need to be told what object they are part of/operating on is somewhat nonsensical... > >Thus when an object method is called, it must be called with one fewer > >arguments than those which are defined. This can be confusing, > >especially to new programmers. > > This is confusing as long as you insist on saying that what you > "def"ined is a method - which is not the case. I can see now the distinction, but please pardon my prior ignorance, since the documentation says it IS the case, as I pointed out earlier. Furthermore, as you described, defining the function within the scope of a class binds a name to the function and then makes it a method of the class. Once that happens, *the function has become a method*. To be perfectly honest, the idea that an object method can be defined outside the scope of an object (i.e. where the code has no reason to have any knowledge of the object) seems kind of gross to me... another Python wart. One which could occasionally be useful I suppose, but a wart nonetheless. This seems inherently not object-oriented at all, for reasons I've already stated. It also strikes me as a feature designed to encourage bad programming practices. Even discounting that, if Python had a keyword which referenced the object of which a given peice of code was a part, e.g. self, then a function written to be an object method could use this keyword *even if it is defined outside of the scope of a class*. The self keyword, once the function was bound to an object, would automatically refer to the correct object. If the function were called outside of the context of an object, then referencing self would result in an exception. You'll probably argue that this takes away your ability to define a function and subsequently use it both as a stand-alone function and also as a method. I'm OK with that -- while it might occasionally be useful, I think if you feel the need to do this, it probably means your program design is wrong/bad. More than likely what you really needed was to define a class that had the function as a method, and another class (or several) that inherits from the first. > The point is that you don't get access to the object "within itself". > You get access to an object *within a function*. Thus methods are not really methods at all, which would seem to suggest that Python's OO model is inherently broken (albeit by design, and perhaps occasionally to good effect). > The fact that a function is defined within a class statement doesn't > imply any "magic", It does indeed -- it does more than imply. It states outright that the function is defined within the namespace of that object, and as such that it is inherently part of that object. So why should it need to be explicitly told about the object of which it is already a part? It further does indeed imply, to hordes of programmers experienced with OO programming in other languages, that as a member, property, attribute, or what ever you care to call it, of the object, it should have special knowledge about the object of which it is a part. It just so happens that in Python, this implication is false. > IOW : there's one arguably good reason to drop the target object from > functions used as methods implementation, which is to make Python looks > more like Java No, that's not the reason. I don't especially like Java, nor do I use it. The reason is to make the object model behave more intuitively. >, and there's at least two good reason to keep it the way it is, >which are simplicity (no special case) and consistency (no special >case). Clearly a lot of people find that it is less simple TO USE. The point of computers is to make hard things easier... if there is a task that is annoying, or tedious, or repetitive, it should be done by code, not humans. This is something that Python should do automatically for its users. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From kyosohma at gmail.com Wed Jul 16 17:20:06 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 16 Jul 2008 14:20:06 -0700 (PDT) Subject: py2exe issues with pictures and icons References: <18493908.post@talk.nabble.com> <18495626.post@talk.nabble.com> Message-ID: <0c5dcb1e-11c2-4c3d-a485-625e76f00a95@m3g2000hsc.googlegroups.com> On Jul 16, 3:22?pm, Alexnb wrote: > Alexnb wrote: > > > Mike Driscoll wrote: > > >> On Jul 16, 1:37?pm, Alexnb wrote: > >>> Hello > > >>> I am sure most of you are familiar with py2exe. I am having a bit of a > >>> problem. See the program has a few pictures involved and the .ico it > >>> uses > >>> for the windows. However, the pictures are stored in the same directory > >>> as > >>> the source, something like: C:\Docs and settings\me\My > >>> docs\python\program. > >>> When I run the program for the interpreter, just as a .py, everything > >>> works > >>> just as it should. However, when I compile the main source as an .exe, > >>> and > >>> say let a friend try the program. It fails because it is missing the > >>> .ico. > >>> The catch, is I don't want to have it have to installed, at least at > >>> this > >>> point, I want it to be able to just run. So how can I make it just run > >>> from > >>> any computer with the files not being in the immediate directory. If > >>> that is > >>> not possible, how can I put them in the immediate directory and still > >>> make > >>> it work. Because that directory may change a lot so the path will > >>> change. > > >>> Just a few questions. I hope someone out there can help me out! > >>> -- > >>> View this message in > >>> context:http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp1849390... > >>> Sent from the Python - python-list mailing list archive at Nabble.com. > > >> Put the part of the code that needs the ico file(s) into a try/except > >> block. You could also try reading the py2exe wiki and tutorials. This > >> one looks like it has relevant data: > > >>http://www.py2exe.org/index.cgi/CustomIcons > > >> Mike > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > > Well, that may solve the icon problem. But what about getting pictures in > > there? > > Okay, the icon fix didn't really fix it, what it did was make the .exe have > the icon as the little picture for the shortcut, but it isn't really a > shortcut. Whatever. But, I went and ran it on another computer and this was > the error log it created right off the bat. > > Traceback (most recent call last): > ? File "The GUI.py", line 696, in > ? File "Tkinter.pyc", line 1515, in wm_iconbitmap > _tkinter.TclError: bitmap "C:\Documents and Settings\Alex\My > Documents\PYTHON\DictionaryApp\Windows.ico" not defined > > -- > View this message in context:http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp1849390... > Sent from the Python - python-list mailing list archive at Nabble.com. Crumb! I actually use a GUI wrapper for py2exe called GUI2Exe which makes this sort of thing much easier. Unfortunately, it also makes me less knowledgeable. You can check it out here: http://xoomer.alice.it/infinity77/main/GUI2Exe.html Also, there's a distutils group and a py2exe group. Both of them would know a lot more about how to do this. https://lists.sourceforge.net/lists/listinfo/py2exe-users http://www.python.org/community/sigs/current/distutils-sig/list/ Mike From bignose+hates-spam at benfinney.id.au Sun Jul 13 07:44:40 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 13 Jul 2008 21:44:40 +1000 Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> <85c3da91-9f2f-4d19-ba98-dfdc99b1e1e3@79g2000hsk.googlegroups.com> Message-ID: <87y746c8k7.fsf@benfinney.id.au> Bart Kastermans writes: > Roy Smith writes: > > The defensive thing to do is catch exactly the exception you > > expect to happen. In this case, that means IndexError. > > And you do that by > > except IndexError: > raise TheErrorYouNowWantToRaise You only do that if you want to throw away important information, such as the traceback associated with the original exception. Not very friendly to debugging. > And > except IndexError, e: > > if you want access to the exception as well. Usually best if it can be achieved. Not least because the bare 'raise' statement will re-raise the original exception, complete with all its context. -- \ ?If we don't believe in freedom of expression for people we | `\ despise, we don't believe in it at all.? ?Noam Chomsky, | _o__) 1992-11-25 | Ben Finney From upton at virginia.edu Mon Jul 7 08:02:55 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 7 Jul 2008 08:02:55 -0400 Subject: Cross Compiler for Python? In-Reply-To: <000901c8e009$dbd29e40$0d00a8c0@hendrik> References: <000901c8e009$dbd29e40$0d00a8c0@hendrik> Message-ID: <5504f9ac0807070502ub8258adx2eadfd6bde199df8@mail.gmail.com> On Mon, Jul 7, 2008 at 4:15 AM, Hendrik van Rooyen wrote: > Up to now, I have been innocently using the vanilla python > that comes with the Linux distribution (Suse in my case). > > For the past few days, I have been playing with a little > device called an eBox - it is basically a 486 with 128Mb > memory, and a 1Gig pcmcia flash drive. > > We want to try to use this as an industrial controller, so > I want to load python onto it. > > So I downloaded the sources, and got them into the box, > over its ethernet connection. > > Then I got stymied - the configure script will not run, > because the "distribution" has no C compiler - it is > basically a kernel, and Busybox, with precious little else. > > So I googled, and I found mobile python, and portable python, > both aimed at windows. - no good to me. > > Adding "embedded" to the Google string is also useless, > as it basically brings up instances of embedding the > interpreter into another app, not for small processors. > > So how does one do a compile of python on one machine > aimed at another one? - All I want is a vanilla installation > with the stuff in all the usual places. And just to make matters > interesting, the two Linux boxes I have available are both > 64 bit dual core animals, one Intel, one AMD... > > I don't need much more than the interpreter, sys, os, sockets > and ctypes. > > Alternatively, where can one find a set of binaries for > 32 bit Linux? > If you don't have a 32 bit system to build it on, you could always set up a VMWare machine... but that might be more effort than necessary. You can probably just run configure on your normal machine and then edit the makefile to add -m32 to the compiler or linker flags--that will force gcc to generate 32-bit code. You'd have to copy the files over and get the paths right yourself though. Alternately, if you can mount the eBox somewhere in Linux, you should be able to do configure --prefix=/path/to/eBox/mount and then make install will work for you too. (I haven't tried this before, but that's how I'd go about it.) From gherron at islandtraining.com Sun Jul 27 19:58:56 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 27 Jul 2008 16:58:56 -0700 Subject: Where is the correct round() method? In-Reply-To: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> Message-ID: <488D0BC0.3080701@islandtraining.com> josh logan wrote: > Hello, > > I need a round function that _always_ rounds to the higher integer if > the argument is equidistant between two integers. In Python 3.0, this > is not the advertised behavior of the built-in function round() as > seen below: > > >>>> round(0.5) >>>> > 0 > >>>> round(1.5) >>>> > 2 > >>>> round(2.5) >>>> > 2 > > Huh? >>> round(2.5) 3.0 Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo CPU". What system are you on? It could be that 2.5 is really 2.49999... which would round down to 2, but on any modern CPU (using IEEE floating point), 2.5 should be representable exactly. However, as with any floating point calculations, if you expect exact representation or calculations with any numbers, then you are misusing floating points. Gary Herron > I would think this is a common need, but I cannot find a function in > the Python library to do it. I wrote my own, but did I miss such a > method in my search of the Python library? > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > From grante at visi.com Fri Jul 25 12:50:39 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 25 Jul 2008 11:50:39 -0500 Subject: Calling external program from within python References: <6eu684F91muhU1@mid.uni-berlin.de> <6eu75mF92mqcU1@mid.uni-berlin.de> Message-ID: On 2008-07-25, Diez B. Roggisch wrote: > Because usually if a program *prompts* the user to enter input (and that > was what I read from the OP's post), one has to deal with pseudo > terminals, not with stdin/out. > >>> If interaction is required, the OP might consider using >>> pexpect. >> >> Pexpect is a good option, but it's just an automation layer on >> top of the same facilities that subprocess provides. > > AFAIK it's more than that. I'm not an expert on pseudo terminals, but > AFAIK setting using module pty isn't possible using subprocess. You're right. I forgot that pexect uses a pty. You could use a pty with the subprocess module, but it's a hassle to set up. -- Grant Edwards grante Yow! The PINK SOCKS were at ORIGINALLY from 1952!! visi.com But they went to MARS around 1953!! From fizzi at my10sen.com Thu Jul 3 06:34:43 2008 From: fizzi at my10sen.com (fizzi) Date: Thu, 03 Jul 2008 18:34:43 +0800 Subject: Iphone Going 3G! Message-ID: <486cab43$1_2@news.tm.net.my> For the Iphone lovers out there, The next generation of Iphone has been released with the additional features. You guess it, now Iphone comes with 3G. That ?s what we missed during the first release of Iphone which turn it into major drawback for Iphone buyers wannabe. Even more good news to those who wish to keep new iphone in the pocket the rest of the entry : http://www.my10sen.com/2008/07/03/iphone-going-3g/ From duncan.booth at invalid.invalid Thu Jul 17 13:27:22 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jul 2008 17:27:22 GMT Subject: properly delete item during "for item in..." References: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> <487F770D.8070405@islandtraining.com> Message-ID: mk wrote: > Iterating over a copy may _probably_ work: > > >>> t=['a', 'c', 'b', 'd'] > >>> > >>> for el in t[:]: > del t[t.index(el)] > > > >>> t > [] > > > However, is it really safe? Defining safe as "works reliably in every > corner case for every indexable data type"? No, because you cannot necessarily copy every indexable data type using t[:], and not all types will support index. Also it is inefficient to delete from the start of the list. If you are working with a list and deleting every object: del t[:] will suffice. If you don't want to delete everything then you could do: for index, el in enumerate(reversed(t)): if not wewant(el): del t[index] but the pythonic way is just: t[:] = [ el for el in t if wewant(el) ] or if you just want the filtered list and don't care about updating the original: t = [ el for el in t if wewant(el) ] > Con: suppose the data structure t is really, really big. Just deleting > some items from t temporarily doubles the memory consumption. No it doesn't. Copying a list doesn't copy any of the elements in the list, it just copies the references to those element. From nicola.musatti at gmail.com Wed Jul 9 07:20:54 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Wed, 9 Jul 2008 04:20:54 -0700 (PDT) Subject: GUI Programming by hand not code with Python Code References: <7003b665-3227-47a7-ab06-1a486f87939a@a1g2000hsb.googlegroups.com> Message-ID: <21f87365-ac36-452f-ac29-6df28f09abfa@56g2000hsm.googlegroups.com> On Jul 8, 10:09 pm, sturlamolden wrote: [...] > I use wxFormBuilder with wxPython. Works like a charm. Design the GUI > graphically, export it like a wx XML resource (.xrc). All you nedd to > code in Python is the event handlers and the code to bind/hook the > events. > > http://sturlamolden.blogspot.com/2008/03/howto-using-wxformbuilder-wi... I also use wxFormBuilder, but I use XRCed from wxPython 2.8.6.x to generate an application Skeleton from my .xrc file. This version creates explicit attributes for all the visual elements that have a name in the xrc file. Unfortunately the latest XRCed version requires you to annotate the xrc in order to obtain the same effect which is not only tedious, but as far as I can tell it also makes it impossible to round trip between XRCed and wxFormBuilder. Cheers, Nicola Musatti From nicolas.pourcelot at gmail.com Sun Jul 20 18:17:48 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Sun, 20 Jul 2008 15:17:48 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> <6ebshqF67cpfU4@mid.uni-berlin.de> <5d6b8066-c941-4f0c-abea-20baed33b4ab@l64g2000hse.googlegroups.com> <569da8b8-df8a-4115-a952-5d8c2d9744e0@i20g2000prf.googlegroups.com> <46c2153d-fef6-45b5-91af-9ecb359e6a2b@2g2000hsn.googlegroups.com> <141135ca-20fb-426e-a11f-bcd02aa01541@f40g2000pri.googlegroups.com> Message-ID: <7ecef9f2-567c-497c-aeaf-651f6c070f2b@2g2000hsn.googlegroups.com> On 20 juil, 23:18, John Machin wrote: > On Jul 21, 4:33 am, nicolas.pource... at gmail.com wrote: > > > > (1) You are searching through lists to find float objects by identity, > > > not by value > > > ???? > > You wrote """ > I used short lists (a list of 20 floats) and the element > checked was not in the list. > (That was the case I usually deals with in my code.) > """ :-D From bj_666 at gmx.net Tue Jul 1 06:52:54 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Jul 2008 10:52:54 GMT Subject: Having problems using Tkinter References: <144f93d3-b493-4280-a3a4-23a2b13b59c6@i36g2000prf.googlegroups.com> Message-ID: <6cugk6F3e7podU2@mid.uni-berlin.de> On Tue, 01 Jul 2008 03:13:42 -0700, viv1tyagi wrote: > Hi everyone ! ! ! > > I'm just a month old in the world of Python and trying to develop an > application using Tkinter in which a new window pops out on a > particular button press.The code for this new window is in > "AddKlas.py" file. > The problem is all the content of the new window is overwritten on > the previous window. > Below is the code of the two files There can be only one `Tkinter.Tk` instance per running program. Other top level windows have to be `Tkinter.Toplevel` instances. And you should reconsider your usage of classes. You are just abusing them as containers for functions without using `self` really. And you should pass the instance of the parent widget as first argument to constructors of widgets. Otherwise the very first, i.e. the `Tk` instance, is assumed, which is not true for the widgets that should appear in the `Toplevel` instance. Ciao, Marc 'BlackJack' Rintsch From bruno.42.desthuilliers at websiteburo.invalid Mon Jul 7 09:47:51 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 07 Jul 2008 15:47:51 +0200 Subject: yo... In-Reply-To: <1a767250-c2e6-4a07-8650-84b79bf628af@26g2000hsk.googlegroups.com> References: <1a767250-c2e6-4a07-8650-84b79bf628af@26g2000hsk.googlegroups.com> Message-ID: <48721e63$0$1120$426a74cc@news.free.fr> cokofreedom at gmail.com a ?crit : (snip) > However welcome to Python and this Google > Group. This is *not* a google group. This is the usenet newsgroup comp.lang.python, made accessible TTW by google. From fredrik at pythonware.com Wed Jul 16 05:01:30 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 11:01:30 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) In-Reply-To: <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> Message-ID: Stefan Scholl wrote: > Django isn't ready. That's a remarkably ignorant statement. From zellux at gmail.com Wed Jul 16 01:49:32 2008 From: zellux at gmail.com (ZelluX) Date: Tue, 15 Jul 2008 22:49:32 -0700 (PDT) Subject: Is there any library that can extract titles from PDFs? Message-ID: Hi, all I want to write a script which will rename PDFs according to their titles. I want to know if there is any library that can extract titles(the first line of the PDF) from PDFs. Many thanks for your reply ;-) From termim at gmail.com Thu Jul 3 15:41:37 2008 From: termim at gmail.com (Mike) Date: Thu, 3 Jul 2008 12:41:37 -0700 (PDT) Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> <6a8d3b30-b7d6-4f41-b491-0cfc44e46109@27g2000hsf.googlegroups.com> <3232ac82-97ee-4297-a511-5e1b61315b8e@t54g2000hsg.googlegroups.com> <2308f07f-61c8-46ae-8e91-d1c3f0629945@34g2000hsf.googlegroups.com> Message-ID: <31dd9e93-842a-40d3-898d-b40f0fcf1a8b@56g2000hsm.googlegroups.com> On Jul 2, 11:09 am, George Sakkis wrote: > On Jun 30, 3:16 pm, Mike wrote: > > > On Jun 30, 1:41 pm, George Sakkis wrote: > > > > Because _typically_ a web template consists of mostly HTML, with > > > relatively little presentational logic and (ideally) no business > > > logic. Now, if all one wants to do is a quick and dirty way to, say, > > > view a log file in the browser, a separate template is probably an > > > The keyword here is "(ideally)". These _typical_ cases are pretty much > > restricted to a helloworld-like examples or to a pure men log file > > browser ;). > > That's the opposite of what I said. For helloworld-like examples, a > web template is an overkill. It's non-trivial applications that can > show off what a template language buys you. > Yes, I really meant the opposite - _typically_ a web template consits of more than just HTML. Exception - helloworld-like examples. > > Real application templates quickly became complicated and > > require full blown scripting engine. Zope/Plone/Trac templates are > > good examples of this. > > What does "this" refer to? Injecting business logic or just > complicated presentational logic? > By "this" I try to support my statement that in real life applications templates are much mor complicated than just HTML. > > I took a look and as much as I like Python for general programming, I > find these templates more readable and maintenable than straight > string-concatenating Python. YMMV. > Completely agree here - straight string-concatenating in Python is not better. From bojannastic at googlemail.com Mon Jul 21 21:47:30 2008 From: bojannastic at googlemail.com (bojannastic at googlemail) Date: Mon, 21 Jul 2008 18:47:30 -0700 (PDT) Subject: Python Written in C? References: Message-ID: On Jul 20, 6:50 pm, giveitawhril2... at gmail.com wrote: > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! Young people these days... I will just answer using one of old Microsoft's ads: "My compiler compiled yours." From Nikolaus at rath.org Thu Jul 31 11:00:51 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Thu, 31 Jul 2008 17:00:51 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> <12072cbe-139a-430f-81aa-b64bc31b43e5@e39g2000hsf.googlegroups.com> <87zlny8cdg.fsf@nokile.rath.org> Message-ID: <87r69a85ek.fsf@nokile.rath.org> Maric Michaud writes: > Le Thursday 31 July 2008 14:30:19 Nikolaus Rath, vous avez ?crit?: >> oj writes: >> > On Jul 31, 11:37?am, Nikolaus Rath wrote: >> >> So why does Python distinguish between e.g. the type 'int' and the >> >> class 'myclass'? Why can't I say that 'int' is a class and 'myclass' >> >> is a type? >> > >> > I might be wrong here, but I think the point is that there is no >> > distinction. A class (lets call it SomeClass for this example) is an >> > object of type 'type', and an instance of a class is an object of type >> > 'SomeClass'. >> >> But there seems to be a distinction: >> >>> class int_class(object): >> >> ... pass >> ... >> >> >>> int_class >> >> >> >> >>> int >> >> >> >> why doesn't this print >> >> >>> class int_class(object): >> >> ... pass >> ... >> >> >>> int_class >> >> >> >> >>> int >> >> >> >> or >> >> >>> class int_class(object): >> >> ... pass >> ... >> >> >>> int_class >> >> >> >> >>> int >> >> >> >> If there is no distinction, how does the Python interpreter know when >> to print 'class' and when to print 'type'? >> > > There are some confusion about the terms here. > > Classes are instances of type 'type', Could you please clarify what you mean with 'instance of type X'? I guess you mean that 'y is an instance of type X' iif y is constructed by instantiating X. Is that correct? > What the means is that int is not a user type but a > builtin type, instances of int are not types (or classes) but common > objects, so its nature is the same as any classes. > > The way it prints doesn't matter, it's just the __repr__ of any instance, and > the default behavior for instances of type is to return '', but it > can be easily customized. But 'int' is an instance of 'type' (the metaclass): >>> int.__class__ so it should also return '' if that's the default behavior of the 'type' metaclass. I think that to get '' one would have to define a new metaclass like this: def type_meta(type): def __repr__(self) return "" % self.__name__ and then one should have int.__class__ == type_meta. But obviously that's not the case. Why? Moreover: >>> class myint(int): ... pass ... >>> myint.__class__ == int.__class__ True >>> int >>> myint despite int and myint having the same metaclass. So if the representation is really defined in the 'type' metaclass, then type.__repr__ has to make some kind of distinction between int and myint, so they cannot be on absolute equal footing. Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From tjreedy at udel.edu Wed Jul 23 23:24:45 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Jul 2008 23:24:45 -0400 Subject: Broken examples In-Reply-To: <4887DDA5.1010707@hughes.net> References: <4887DDA5.1010707@hughes.net> Message-ID: norseman wrote: > > I'm only talking about IPC related. > I have googled, yahooed, and so forth for several months now. ALL > examples I've come across have failed including those pertinent in the > Python doc area. > > Outline: > cd somedir > ls -1 *.xls >thislist #ls hyphen one > python process.py > (yes - ls can go here if wanted. easier to edit outside) > open thislist > loop until done > start excel (or scalc) > have it open file > have it save file as a .csv (or .dbf) > close excell (or scalc) > > Would seem to be a trivial exercise. > Starting Excel or any other executable in system path works fine. > popen3 opens whatever and reports no errors. r,w,and e all check as > being created. > > r,w,e= os.popen3('ls -l') > print r.read() # works as expected > > ALL attempts to send instructions to Excel or scalc FAIL COMPLETELY. > Actually, any attempt to communicate with a 'Point'n'Click' program > fails without errors being cited. They don't use redirectable command > line interfaces (like piping between programs) do they? :) > > Trying to use the examples I have found that supposedly setup IPC's of > one type or another have all failed with errors that point to things > that make no sense in the first place. > > Before you post a code example or a link to one be kind enough to run it > yourself first. You may get a surprise. The OOo examples do not work. > Not even when switching my system to their version. One problem they > have is asking a general user to change to places the user has no place > being and then to work there without permissions. I guess somebody > insists on doing all their work with root clearance down in the middle > of the vendor's tree. I don't think that's a healthy way to do things, > do you? > > In OOo in particular, using their version of VBA one can create the > macro and even port it to python. If one found the correct Microsoft > suite docs I suspect that same could be done there too. But that doesn't > activate it from a python control. As for setting the macro to run at > startup, well... maybe I had other uses in mind today???? Besides the > moment I change it, coworker in other room is going to decide to... :) > > Let's stick to Microsoft Office and OpenSource products for now. My > final goal will require specific conversations with a commercial vendor. > I would like those spread sheets working though. > > > Thanks > > Steve > norseman at hughes.net > -- > http://mail.python.org/mailman/listinfo/python-list > From stesch at no-spoon.de Sat Jul 19 05:33:33 2008 From: stesch at no-spoon.de (Stefan Scholl) Date: Sat, 19 Jul 2008 11:33:33 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> <0T56p3tmInifNv8%stesch@parsec.no-spoon.de> <6e7v9qF5q74kU1@mid.uni-berlin.de> <0T56pitfI5raNv8%stesch@parsec.no-spoon.de> Message-ID: <0T56v18vI5u9Nv8%stesch@parsec.no-spoon.de> Fredrik Lundh wrote: > (and the "stable release" and "much will change" stuff is pure FUD, of > course. what competing project will I find if I google your name?) Found something? Maybe this could help me to choose a web framework. -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ From ethan at stoneleaf.us Mon Jul 14 13:28:18 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 14 Jul 2008 09:28:18 -0800 Subject: Determining when a file has finished copying In-Reply-To: <7198df5e-e5e6-4b2d-9a7c-9ef2e30c87d1@x35g2000hsb.googlegroups.com> References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> <7198df5e-e5e6-4b2d-9a7c-9ef2e30c87d1@x35g2000hsb.googlegroups.com> Message-ID: <487B8CB2.6030400@stoneleaf.us> Sean DiZazzo wrote: > On Jul 9, 5:34 pm, keith wrote: > >>-----BEGIN PGP SIGNED MESSAGE----- >>Hash: SHA1 >> >> >> >>Ethan Furman wrote: >> >>>writeson wrote: >>> >>>>Guys, >> >>>>Thanks for your replies, they are helpful. I should have included in >>>>my initial question that I don't have as much control over the program >>>>that writes (pgm-W) as I'd like. Otherwise, the write to a different >>>>filename and then rename solution would work great. There's no way to >>>>tell from the os.stat() methods to tell when the file is finished >>>>being copied? I ran some test programs, one of which continously >>>>copies big files from one directory to another, and another that >>>>continously does a glob.glob("*.pdf") on those files and looks at the >>>>st_atime and st_mtime parts of the return value of os.stat(filename). >>>> >>>>>From that experiment it looks like st_atime and st_mtime equal each >>>> >>>>other until the file has finished being copied. Nothing in the >>>>documentation about st_atime or st_mtime leads me to think this is >>>>true, it's just my observations about the two test programs I've >>>>described. >> >>>>Any thoughts? Thanks! >>>>Doug >> >>>The solution my team has used is to monitor the file size. If the file >>>has stopped growing for x amount of time (we use 45 seconds) the file is >>>done copying. Not elegant, but it works. >>>-- >>>Ethan >> >>Also I think that matching the md5sums may work. Just set up so that it >>checks the copy's md5sum every couple of seconds (or whatever time >>interval you want) and matches against the original's. When they match >>copying's done. I haven't actually tried this but think it may work. >>Any more experienced programmers out there let me know if this is >>unworkable please. >>K >>-----BEGIN PGP SIGNATURE----- >>Version: GnuPG v1.4.6 (GNU/Linux) >>Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org >> >>iD8DBQFIdVkX8vmNfzrLpqoRAsJ2AKCp8wMz93Vz8y9K+MDSP33kH/WHngCgl/wM >>qTFBfyIEGhu/dNSQzeRrwYQ= >>=Xvjq >>-----END PGP SIGNATURE----- > > > I use a combination of both the os.stat() on filesize, and md5. > Checking md5s works, but it can take a long time on big files. To fix > that, I wrote a simple sparse md5 sum generator. It takes a small > number bytes from various areas of the file, and creates an md5 by > combining all the sections. This is, in fact, the only solution I have > come up with for watching a folder for windows copys. > > The filesize solution doesn't work when a user copies into the watch > folder using drag and drop on Windows because it allocates all the > attributes of the file before any data is written. The filesize will > always show the full size of the file. > > ~Sean Good info, Sean, thanks. One more option may be to attempt to rename the file -- if it's still open for copying, that will fail; success indicates the copy is done. Of course, as Larry Bates pointed out, this could fail if the copy is followed by a re-open and appending. Hopefully that's not an issue for the OP. -- Ethan From robert.rawlins at thinkbluemedia.co.uk Tue Jul 8 09:05:16 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 8 Jul 2008 14:05:16 +0100 Subject: Logger Configuration In-Reply-To: <001d01c8e0f4$b2c0c900$18425b00$@rawlins@thinkbluemedia.co.uk> References: <001d01c8e0f4$b2c0c900$18425b00$@rawlins@thinkbluemedia.co.uk> Message-ID: <004501c8e0fb$44a29d20$cde7d760$@rawlins@thinkbluemedia.co.uk> Ok, I've managed to resolve this issue, it seems it was because I had the file size and number of archives to keep in "" and was thus setting them as strings instead of numerical values. Robert From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Robert Rawlins Sent: 08 July 2008 13:18 To: python-list at python.org Subject: Logger Configuration Hello guys, I've attached an example of my logging configuration file for you to look at. The problem I'm experiencing is that the log files are not rotating as I would expect them to, they just keep growing and growing. Can you see any reason for this to happen? This is the first time I've used a config file and not just configured the logger programmatically. Thanks guys, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From jason at tishler.net Thu Jul 31 08:29:24 2008 From: jason at tishler.net (Jason Tishler) Date: Thu, 31 Jul 2008 08:29:24 -0400 Subject: SVN access with pysvn under Cygwin (Installation problems) In-Reply-To: <4cd368f8-6402-4f3e-8496-d9d227b39dd9@m73g2000hsh.googlegroups.com> References: <69da0a81-bf73-46cb-a762-b017a53e6ddf@e39g2000hsf.googlegroups.com> <4cd368f8-6402-4f3e-8496-d9d227b39dd9@m73g2000hsh.googlegroups.com> Message-ID: <20080731122924.GA3504@tishler.net> Andy, On Thu, Jul 31, 2008 at 03:10:26AM -0700, Andy Dingley wrote: > On 30 Jul, 20:30, Jason Tishler wrote: > > You need to build (and install) pysvn under Cygwin. The pre-built > > Windows version will not work under Cygwin. > > Thanks. Presumably this same problem would affect anything that uses a > .pyd under Cygwin? Yes, Python shared extension modules are specific to the Python used to build them. This is the situation even though Windows Python and Cygwin Python both run on the same operating system. BTW, this is why I added shared extension module support to Cygwin Python almost 8 years ago. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From larry.bates at websafe.com` Sun Jul 27 22:01:05 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 27 Jul 2008 21:01:05 -0500 Subject: write unsigned integer 32 bits to socket In-Reply-To: References: Message-ID: rkmr.em at gmail.com wrote: > hi > i want to send unsigned 32 bit integer to socket, and looking for > something equivalent to this method... > > http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt() > > is there such method / library available in python?! > > > this is as far as i have gotten along >>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>>> s.connect(('127.0.0.1',3000)) You will need to use struct module to build the 4 byte value and then send it. Something like (not tested): import struct us32bit = struct.pack("I", value) s.send(us32bit) -Larry From quarkthedark at gmail.com Wed Jul 16 09:55:51 2008 From: quarkthedark at gmail.com (AM) Date: Wed, 16 Jul 2008 06:55:51 -0700 (PDT) Subject: Playing stereo wav files in Python Message-ID: -Hello all, I am trying to play stereo wavefiles in python with no success. I can play mono wavefiles, using either pygames mixer library, python's winsound library or wxPython's wx.Sound library, but i cannot get stereo wavefiles to play in any of these. Normally i wouldn't care and covert the files to mono, but the phase difference between the two ears in important for this application. Does anyone know of a way that i have missed? I am using a LynxONE soundcard if that is important. -AM From ward.david at comcast.net Tue Jul 15 11:38:31 2008 From: ward.david at comcast.net (ward.david at comcast.net) Date: Tue, 15 Jul 2008 08:38:31 -0700 (PDT) Subject: Is it legal to rebuild Python.exe to include Version property tab? References: Message-ID: On Jul 15, 7:42?am, Michiel Overtoom wrote: > Why rebuild it? You can use a resource editor tool to add/edit/delete the > VERSIONINFO from any Windows executable, including Python.exe ;-) M, Thanks for you suggestion. I didn't know that there was anything like a "resource editor" outside of a dev IDE. You learn something new everyday. :) So, we've established that there is a different way to edit the VERSIONINFO of an EXE. However, the question still remains as to whether is is legal to edit the VERSIONINFO on Python.exe and distribute it? From gherron at islandtraining.com Sun Jul 13 14:16:46 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 13 Jul 2008 11:16:46 -0700 Subject: Mutually referencing imports -- impossible? In-Reply-To: References: Message-ID: <487A468E.5000000@islandtraining.com> Matthew Wilson wrote: > I started off with a module that defined a class Vehicle, and then > subclasses Car and Motorcycle. > > In the Car class, for some bizarre reason, I instantiated a Motorcycle. > Please pretend that this can't be avoided for now. > > Meanwhile, my Motorcycle class instantiated a Car as well. > > Then I moved the Car and Motorcycle classes into separate files. Each > imported the Vehicle module. > > Then I discovered that my Car module failed because the global > Motorcycle wasn't defined. The same problem happened in my Motorcycle > module. Car and Motorcycle can't both import each other. > > In the beginning, when all three (Vehicle, Car, and Motorcycle) were > defined in the same file, everything worked fine. > > I don't know how to split them out in separate files now though and I > really wish I could because the single file is enormous. > > Any ideas? > > Matt > It is easy for imports to be mutually referencing. This presents no problem to Python if the importing of one module is interrupted by the import of another. However, if one of them imports specific names from a module, from ABC import abc or from ABC import * then it's possible that the (interrupted) import of module ABC has not progressed to the point that abc is defined. The solution: Just import ABC and later reference ABC.abc That being said, it is still a good design practice to structure your modules hierarchically rather than a circularly. Gary Herron > > -- > http://mail.python.org/mailman/listinfo/python-list > From python at bdurham.com Tue Jul 29 01:02:43 2008 From: python at bdurham.com (python at bdurham.com) Date: Tue, 29 Jul 2008 01:02:43 -0400 Subject: Questions on 64 bit versions of Python (Thank-you!) In-Reply-To: <488cbeeb$0$17104$9b622d9e@news.freenet.de> References: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> <488cbeeb$0$17104$9b622d9e@news.freenet.de> Message-ID: <1217307763.13376.1265835765@webmail.messagingengine.com> Dear List, Thanks for everyone's feedback - excellent detail - all my questions have been answered. BTW: Roel was correct that I got confused over the AMD and Intel naming conventions regarding the 64 bit versions of Python for Windows. (I missed that nuance that the Intel build refered to the Itanium vs. the standard off-the-rack 64 bit version of Intel's 586/686 CPU) Best regards, Malcolm From __peter__ at web.de Sun Jul 13 06:30:52 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 13 Jul 2008 12:30:52 +0200 Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> Message-ID: Yosifov Pavel wrote: > On 13 ???, 14:12, Peter Otten <__pete... at web.de> wrote: >> Yosifov Pavel wrote: >> > Whats is the way to clone "independent" iterator? I can't use tee(), >> > because I don't know how many "independent" iterators I need. copy and >> > deepcopy doesn't work... >> >> There is no general way. For "short" sequences you can store the items in >> a list which is also the worst-case behaviour of tee(). >> >> What are you trying to do? >> >> Peter > > I try to generate iterators (iterator of iterators). Peter, you are > right! Thank you. For example, it's possible to use something like > this: > > def cloneiter( it ): > """return (clonable,clone)""" > return tee(it) [snip] That is too abstract, sorry. What concrete problem are you trying to solve with your cloned iterators? There might be a way to rearrange your setup in a way that doesn't need them. > But I think (I'm sure!) it's deficiency of Python iterators! They are > not very good... Well, I think Python's iterators, especially the generators, are beautiful. More importantly, I think there is no general way to make iterators copyable, regardless of the programming language. The problem is that most of the useful ones depend on external state. Peter From ggpolo at gmail.com Tue Jul 1 11:22:28 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 1 Jul 2008 12:22:28 -0300 Subject: dynamically load from module import xxx In-Reply-To: References: Message-ID: On Tue, Jul 1, 2008 at 12:11 PM, Neal Becker wrote: > What is a good way to emulate: > > from module import xxx > where 'module' is a dynamically generated string? > > __import__ ('modulename', fromlist=['xxx']) > > seems to be what I want, but then it seems 'xxx' is not placed in globals() > (which makes me wonder, what exactly did fromlist do?) fromlist is used for importing subpackages/submodules of the first arg of __import__. Since you are using "modulename", I'm guessing it is not a package, fromlist will do nothing for you. To solve your problem you could do getattr(__import__('modulename'), 'xxx'). > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From james at reggieband.com Mon Jul 14 05:51:39 2008 From: james at reggieband.com (James Fassett) Date: Mon, 14 Jul 2008 02:51:39 -0700 (PDT) Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> Message-ID: <6daf86f6-0a96-4811-90c4-2bc6ccbff9fb@x41g2000hsb.googlegroups.com> On Jul 12, 12:18?am, George Sakkis wrote: > It relies on positional arguments, tuple unpacking and > the signature of zip(), It moreso relies on the fact that: >>> t1 = (0,1,2,3) >>> t2 = (7,6,5,4) >>> [t1, t2] == zip(*zip(t1, t2)) True This is mathematically true given the definition of zip. To me that is very functional. Basically, unpacking a pair list into zip is the canonical definition of unzipping the list (which is exactly my intention). > Second, it is less readable, For a Python programmer - you are correct. For someone familiar with the use of zip (as described above) - I wonder. Since I am new to this I can't say for sure. If I posted the same code to a Haskell list or a ML list would their opinion be the same? > robust and efficient than the list comprehension. I don't know the internals of how the Python interpreter treats list comprehensions and zip but it seems reasonable to assume an extra list is created for the zip approach. However, in the limited functional code I have seen this is actually a common practice. I would suppose in languages with lazy evaluation this isn't a problem - but in Python it would be. > The list comprehension is still the most pythonic approach though. I agree that it is more Pythonic and preferable in this case. Cheers, James From jeffrey at fro.man Mon Jul 14 16:10:45 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Mon, 14 Jul 2008 13:10:45 -0700 Subject: while var, but var ==16 != true References: <8c2cd9ff-bec2-4844-82a8-8ce02df5663e@w7g2000hsa.googlegroups.com> Message-ID: Tim Roberts wrote: > Everything has a boolean value in > Python. ?0, None, False, '' (empty string), [] (empty list), () (empty > tuple), and {} (empty dictionary) all have a False value. ?Everything else > has a True value. Empty set objects also evaluate as false in a boolean context. Jeffrey From pavlovevidence at gmail.com Wed Jul 30 02:50:17 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 23:50:17 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> Message-ID: <29a131a5-d813-407a-b774-6f90b7f8f3e3@w1g2000prk.googlegroups.com> On Jul 30, 1:58 am, "Russ P." wrote: > On Jul 29, 10:33 pm, Carl Banks wrote: > > > On Jul 30, 1:15 am, "Russ P." wrote: > > > Having said that, it would sure be nice to be able to write > > > > if myList is not empty: > > > > instead of > > > > if len(myList) != 0: > > > I can agree with this. > > But I guess that could only work if there were only one empty list > that represents all empty lists (as there is only one actual "None"). > I don't know if that makes sense or not. I mean in general. I wouldn't spell it like that. I would prefer if empty(x), with an __empty__ method. (And support __nonzero__ aka __bool__ dropped completely.) Carl Banks From misterwang at gmail.com Mon Jul 21 12:58:46 2008 From: misterwang at gmail.com (Peter Wang) Date: Mon, 21 Jul 2008 09:58:46 -0700 (PDT) Subject: how to create GUI dynamically References: <84f144db-0d6c-44d5-a1ef-6e7778304c2a@r66g2000hsg.googlegroups.com> Message-ID: <80b2d543-cb76-4d2e-8958-3557fb617bd0@j22g2000hsf.googlegroups.com> On Jul 21, 8:19?am, hitechpun... at gmail.com wrote: > Hi; > > i m working on a project where i need ?run time creation of GUI. > > i have some no. of entities for which i want checkboxes in front of > them which can be checked/ unchecked by user. > > But the problem is that the number and name of entities is not fixed > and it depends on the file which is used as input. > > So is there any way to tackle this problem. > > By the way ; i use Boa constructor (zope editor) for GUI now. > > regards > pawan pundir You should check out Traits and Traits UI: http://code.enthought.com/projects/traits/examples.php It allows you to dynamically create views and UIs in an easy, declarative manner. It is also powerful enough to build much more complex interactions and dialogs. It currently supports both WX and Qt toolkits. -Peter From sjmachin at lexicon.net Mon Jul 28 20:59:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 28 Jul 2008 17:59:35 -0700 (PDT) Subject: seemingly simple list indexing problem References: Message-ID: <5c118411-5703-44b3-888f-3785b517b8d4@u12g2000prd.googlegroups.com> On Jul 29, 8:10 am, John Krukoff wrote: > On Mon, 2008-07-28 at 16:24 -0500, Ervan Ensis wrote: > > My programming skills are pretty rusty and I'm just learning Python so > > this problem is giving me trouble. > > > I have a list like [108, 58, 68]. I want to return the sorted indices > > of these items in the same order as the original list. So I should > > return [2, 0, 1] > > > For a list that's already in order, I'll just return the indices, i.e. > > [56, 66, 76] should return [0, 1, 2] > > > Any help would be appreciated. > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > If your lists aren't so large that memory is an issue, this might be a > good place for a variation of decorate, sort, undecorate. > > >>> listToSort = [ 108, 58, 68 ] > >>> decorated = [ ( data, index ) for index, data in > > enumerate( listToSort ) ]>>> decorated > > [(108, 0), (58, 1), (68, 2)]>>> result = [ None, ] * len( listToSort ) > >>> for sortedIndex, ( ignoredValue, originalIndex ) in > > enumerate( sorted( decorated ) ): > ... result[ originalIndex ] = sortedIndex > ...>>> result > > [2, 0, 1] > Simpliciter: >>> data = [99, 88, 77, 88, 66] >>> [x[1] for x in sorted(zip(data, xrange(len(data))))] [4, 2, 1, 3, 0] >>> Use case? Think data == database table, result == index ... From mensanator at aol.com Wed Jul 2 18:21:00 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 2 Jul 2008 15:21:00 -0700 (PDT) Subject: Generating list of possible configurations References: Message-ID: On Jul 2, 4:53?pm, "bjorklund.e... at gmail.com" wrote: > Hello pythonistas. > > I'm a newbie to pretty much both programming and Python. I have a task > that involves writing a test script for every possible combination of > preference settings for a software I'm testing. I figured that this > was something that a script could probably do pretty easily, given all > the various possibilites. > > I started creating a dictionary of all the settings, where each key > has a value that is a list of the possible values for that setting. > Most of the settings are simple booleans (setting is on or off), some > of them are drop-downs with several values. For example: > > settings = { > ? ? 'setting_a': (True, False), > ? ? 'setting_b': (True, False), > ? ? 'setting_c': (1, 2, 3, 4), > > } > > After this I tried figuring out a function that would generate the > different possible configurations, but I couldn't quite wrap my head > around it... Basically, for each setting of a, you must do each possible b, and for each a,b setting you must do each possible c, etc. > Are there any general patterns/structures that are suited > for this type of task? Lookup "Cartesian Product". > Any pointers as to how one would go about > solving something like this would be greatly appreciated. for a in [True,False]: for b in [True,False]: for c in [1,2,3,4]: print 'combined settings:',a,'\t',b,'\t',c combined settings: True True 1 combined settings: True True 2 combined settings: True True 3 combined settings: True True 4 combined settings: True False 1 combined settings: True False 2 combined settings: True False 3 combined settings: True False 4 combined settings: False True 1 combined settings: False True 2 combined settings: False True 3 combined settings: False True 4 combined settings: False False 1 combined settings: False False 2 combined settings: False False 3 combined settings: False False 4 > It's not > that I really need to use Python for it, but I thought it could be a > good learning excercise... :-) You may, then, also be interested in Permutations with Replacement Permutations without Replacement Combinations with Replacement Combinations without Replacement > > Kind regards, > //Emil From python at hope.cz Fri Jul 25 14:34:55 2008 From: python at hope.cz (Johny) Date: Fri, 25 Jul 2008 11:34:55 -0700 (PDT) Subject: How to find processes from Python Message-ID: <9f04931c-867b-4ff3-820c-3f8d0bfd2618@e53g2000hsa.googlegroups.com> Is there a way how to find out running processes?E.g. how many Appache's processes are running? Thanks for help. BB. From noelob at gmail.com Wed Jul 16 13:56:50 2008 From: noelob at gmail.com (noelob) Date: Wed, 16 Jul 2008 10:56:50 -0700 (PDT) Subject: Uploading an image using PUT Message-ID: <2375be12-6470-493c-9d4f-979e20c35502@k13g2000hse.googlegroups.com> Hi All, Let me start by saying that's I'm relatively new to Python, so please be gentle! I need to up upload a file to a Tomcat web app using httplib. The web app requires the following: Files need to be split into 100kb (102400b) and each file segment loaded using the PUT request. It is also a requirement that the following headers be sent: For simplicity I've used an image (jpg) smaller than 100kb, so it doesn't need to be chunked headers = { "Accept": "text/xml", "Authorization": "testAuthHeader", "Content-Length": 50172, "Content-Range": "bytes 0-50172/50172", "Content-Type": "image/jpeg", "If-Match": "1", "User-Agent": "(en-IE; Grinder)", } I make the following connection: conn = httplib.HTTPConnection(url) conn.request(method, uriStr, body, additionalHeaders) where: method = PUT uriStr is the web app specific URI body is the raw data (bytes) from the jpg image additionalHeaders are the headers above For some reason I keep getting a Status 400 error from the web server. Is it possible to PUT (or POST?) data in this fashion using httplib? Many thanks for your help Noelob From pavlovevidence at gmail.com Sat Jul 5 08:54:48 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 5 Jul 2008 05:54:48 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: On Jul 5, 6:44 am, "Sebastian \"lunar\" Wiesner" wrote: > Carl Banks : > > > > > On Jul 5, 4:12 am, "Sebastian \"lunar\" Wiesner" > > wrote: > >> Paddy : > > >> > On Jul 4, 1:36 pm, Peter Otten <__pete... at web.de> wrote: > >> >> Henning_Thornblad wrote: > >> >> > What can be the cause of the large difference between re.search and > >> >> > grep? > > >> >> grep uses a smarter algorithm ;) > > >> >> > This script takes about 5 min to run on my computer: > >> >> > #!/usr/bin/env python > >> >> > import re > > >> >> > row="" > >> >> > for a in range(156000): > >> >> > row+="a" > >> >> > print re.search('[^ "=]*/',row) > > >> >> > While doing a simple grep: > >> >> > grep '[^ "=]*/' input (input contains 156.000 a in > >> >> > one row) > >> >> > doesn't even take a second. > > >> >> > Is this a bug in python? > > >> >> You could call this a performance bug, but it's not common enough in > >> >> real code to get the necessary brain cycles from the core developers. > >> >> So you can either write a patch yourself or use a workaround. > > >> >> re.search('[^ "=]*/', row) if "/" in row else None > > >> >> might be good enough. > > >> >> Peter > > >> > It is not a smarter algorithm that is used in grep. Python RE's have > >> > more capabilities than grep RE's which need a slower, more complex > >> > algorithm. > > >> FWIW, grep itself can confirm this statement. The following command > >> roughly takes as long as Python's re.search: > > >> # grep -P '[^ "=]*/' input > > >> -P tells grep to use real perl-compatible regular expressions. > > > This confirms that a particular engine might not be optimized for it, > > but it's not necessarily a reflection that the engine is more complex. > > My posting wasn't intended to reflect the differences in complexity between > normal GNU grep expressions (which are basically extended POSIX > expressions) and perl-compatible expressions. The latter just _are_ more > complex, having additional features like look aheads or non-greedy > qualifiers. > > I just wanted to illustrate, that the speed of the given search is somehow > related to the complexity of the engine. I don't think you've illustrated that at all. What you've illustrated is that one implementation of regexp optimizes something that another doesn't. It might be due to differences in complexity; it might not. (Maybe there's something about PCREs that precludes the optimization that the default grep uses, but I'd be inclined to think not.) Carl Banks From max at alcyone.com Wed Jul 30 02:07:28 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 23:07:28 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: Russ P. wrote: > All this discussion about "if x" has me wondering. I use it all the > time because a fully explicit test just seems redundant. But maybe it > does have some value in terms of readability and type checking. After > all, it is possible to forget whether something is a number or a list. > > Having said that, it would sure be nice to be able to write > > if myList is not empty: I sure hope that's a joke. `x is not y` means something quite different. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The doors of Heaven and Hell are adjacent and identical. -- Nikos Kazantzakis From diordna at gmail.com Wed Jul 23 11:08:40 2008 From: diordna at gmail.com (Stephen Johnson) Date: Wed, 23 Jul 2008 11:08:40 -0400 Subject: Doubt In-Reply-To: References: Message-ID: <6165DF11-444D-4CCE-A35A-BA7A6A087B45@gmail.com> You don't need a mailing list, you need to read the tutorial. Those are completely trivial questions. http://docs.python.org/tut/tut.html -Steve Johnson On Jul 23, 2008, at 10:51 AM, ???????? wrote: > Friends > > I am a Perl programmer new to Python. I have a small doubt. > How to convert the perl notation > $a = ""; expression in Python ? > > How to represent the loop > for ($a = $b; $a<=$c;$a++){ > } in Python > > Jagan > Linguist > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From dorjetarap at googlemail.com Fri Jul 11 18:42:44 2008 From: dorjetarap at googlemail.com (kdt) Date: Fri, 11 Jul 2008 15:42:44 -0700 (PDT) Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: <4ae1e559-038d-4440-85d4-ae3e469fc7e8@b1g2000hsg.googlegroups.com> On Jul 11, 11:34?pm, Denis Kasak wrote: > On Sat, Jul 12, 2008 at 12:22 AM, kdt wrote: > > ?> Hi all, > ?> > ?> Can someone please explain to me why the following evaluates as false? > ?> > ?>>>>list=['a','n','n','a'] > ?>>>>list==list.reverse() > ?>>>>False > ?> > ?> I'm stumped :s > > Read the documentation on list.reverse(). > > Basically, it reverses the list in place, so it modifies the list which > called it. It does not return a /new/ list which is a reversed version > of the original, as you expected it to. Since it doesn't return anything > explicitly, Python makes it return None. Hence, the comparison you are > doing is between the original list and a None, which is False, naturally. > Try this: > > spam = ['a', 'n', 'n', 'a'] > eggs = spam[:] > if spam.reverse() == eggs: > ? ? print "Palindrome" > > Also, 'list' is a really bad name for a list, since this is the name of > the builtin type object for the list type. > > -- > Denis Kasak thanks for the explanation :D From tjreedy at udel.edu Sat Jul 26 17:07:13 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 17:07:13 -0400 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> Message-ID: Carl Banks wrote: > On Jul 24, 4:11 am, Jordan wrote: >> Of course not. >> >> I just think Explicit is better than Implicit is taken seriously by a >> large segment the Python community as a guiding principle, > > Yeah, try telling that to the people who advise writing "if x" instead > of "if x==0", or "if s" instead of "if len(s)==0". Whether or not one should write 'if x' or 'if x != 0' [typo corrected] depends on whether one means the general 'if x is any non-null object for which bool(x) == True' or the specific 'if x is anything other than numeric zero'. The two are not equivalent. Ditto for the length example. What people do properly advise against is the strictly redundant 'if x is True' or 'if x == True'. Both imply a misunderstanding of how 'if' works in Python. As a side note, the usefulness of specific comparisons is greater in 3.0 where spurious comparisons raise exceptions. In 3.0, 'if x >= 0' specifically means 'if x is a number comparable to ints that is greater than or equal to 0'. In 3.0, [] ==/!= 0 are still False/True, but one could exclude incomparables with 'if 0 <= x >= 0' (==0) or 'if x > 0 or x < 0' (!=0). Any such specific comparisons could be used with this pattern. try: x = [] if x >= 0: print('should not get here') except TypeError as m: if m.args[0].startswith('unorderable types:'): print('Here because of bad comparison') Terry Jan Reedy From GDavidson7 at gmail.com Thu Jul 10 14:50:14 2008 From: GDavidson7 at gmail.com (Guy Davidson) Date: Thu, 10 Jul 2008 11:50:14 -0700 (PDT) Subject: Problems Returning an HTTP 200 Ok Message Message-ID: <1cf880cc-2036-42dc-8217-d52a714c1710@a70g2000hsh.googlegroups.com> Hi Folks, I'm having some issues with an small socket based server I'm writing, and I was hoping I could get some help. My code (attached below) us supposed to read an HTTP Post message coming from a power meter, parse it, and return a proper HTTP 200 Ok message. The problem is that the socket fails to send the entire message as one message, creating a fragmented message which the power meter then fails to read and accept. Is there any way to force the socket to send the entire message at once? Am I doing anything wrong? Is there an easier way to implement this functionality? Thanks, Guy Davidson Code: # server application to read data from power meter # listens on port 80 # receives HTTP POST messages # author: Maria Kazandjieva , Guy Davidson # updated: July 7th, 2008: staring to add database writing functionality import time import datetime #datetime for response message from socket import * #socket module import DataPacket #local file with data packet class import library import MySQLdb #formats a proper response message myHost = "" myPort = 80 #response = "HTTP/1.1 200 OK\r\nDate: Fri, 20 June 2008 20:40:34 GMT\r \nServer:SING\r\nX-Powered-By: maria\r\nContent-Length: 7\r \nConnection:close\r\nContent-Type: text/html\r\n\r\n[0!:20]\n" #initializing the socket: s = socket(AF_INET, SOCK_STREAM) # create a TCP socket s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # allow port reuse? I hope s.bind((myHost, myPort)) # bind it to the server port s.listen(50) # allow 50 simultaneous pending connections print('Socket initialized') #intializing the database db = MySQLdb.connect(host='localhost', user='powernet', passwd='jplicks', db='test') cursor = db.cursor() print('Database cursor intialized') while 1: print('In while 1') connection, address = s.accept() # connection is a new socket print('Accepted a connection') # TODO: # verify connection is from powernet so we don't get random connections to port 80 # best way to get the data would be: # read until we get all the headers # parse Content header to get length of data # read for that many additional bytes while 1: print('In while 1 2') data = connection.recv(4096) # receive up to 4K bytes print('First set of data receieved:') #print(data) ''' if data: print data #connection.send(response) #send response; OK 200 HTTP message else: break ''' if data: # second read should recieve the rest of the packet # finding how long the content is length = data.find('Content-Length: ') print('Index of "Content-Length" = ' + str(length)) length = int(data[length+16:length+18]) # adding the bytes from the "Content-Type section:" length += 51 data += connection.recv(length) print('Second set of data received:') print(data) if data: #print('Found data:') #print data #print the string data packet = DataPacket.DataPacket(data) #use the string data to create a DataPacket object print(packet) #print the contents of the object, I hope :) #we have a packet, let's write it to the mysql DB packet.mysql_insert(cursor) #connection.send(response) #send response; OK 200 HTTP message print('Sending response') response = library.response_message() #get the response message totalsent = 0 #initialize a variable to track how much we've sent so far while totalsent < len(response): #while we haven't sent everything sent = connection.send(response[totalsent:]) #send whatever we can starting where we stopped totalsent += sent #increment the count of how much we've sent. else: print('No data') break else: print('No data') break From martinnorth at westnet.com.au Sat Jul 12 04:28:25 2008 From: martinnorth at westnet.com.au (martinnorth) Date: Sat, 12 Jul 2008 18:28:25 +1000 Subject: MySQLdb will only import for root In-Reply-To: References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> Message-ID: Peter Otten wrote: > martinnorth wrote: > >> Hi, >> >> I am running Python and MySQL on Ubuntu and have installed MySQLdb. If I >> try to import MySQLdb I get the following error: >> >> ActivePython 2.5.2.2 (ActiveState Software Inc.) based on >> Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08) >> [GCC 3.3.1 (SuSE Linux)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import MySQLdb >> Traceback (most recent call last): >> File "", line 1, in >> ImportError: No module named MySQLdb >> >> But if I lrun python as the root user it imports fine. Can anyone >> suggest what might be wrong with the installation? Or is there nothing >> wrong? I haven't seen any examples that mentioned being root to import a >> module. > > You have probably installed two versions of Python. You can verify that by > typing > > $ which python > > and > > $ sudo which python > > I suspect that root sees the python that comes with Ubuntu and that has > MySQLdb installed while the normal user sees ActiveState's Python. > > Peter > Thanks Peter, that was it. Located the ActiveState directory and removed it. Now the module imports for all users. Martin From tjreedy at udel.edu Mon Jul 21 17:47:26 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 21 Jul 2008 17:47:26 -0400 Subject: Python Written in C? In-Reply-To: References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> Message-ID: Fredrik Lundh wrote: > rynt wrote: > >> You're either --- >> A. A Troll >> B. A young, immature programmer trying to show off >> or >> C. A total idiot. > > you forgot the "All of the above" choice. Or Aspiring Comic. This is certain one of the more entertaining troll posts we have had ;-). From toby at tobiah.org Tue Jul 1 15:35:01 2008 From: toby at tobiah.org (Tobiah) Date: Tue, 01 Jul 2008 12:35:01 -0700 Subject: Please check my understanding... Message-ID: list.append([1,2]) will add the two element list as the next element of the list. list.extend([1,2]) is equivalent to list = list + [1, 2] and the result is that each element of the added list becomes it's own new element in the original list. Is that the only difference? >From the manual: s.extend(x) | same as s[len(s):len(s)] = x But: (python 2.5.2) >>> a [1, 2, 3] >>> a[len(a):len(a)] = 4 Traceback (most recent call last): File "", line 1, in TypeError: can only assign an iterable >>> Also, what is the difference between list[x:x] and list[x]? >>> a[3:3] = [4] >>> a [1, 2, 3, 4] ** Posted from http://www.teranews.com ** From ldo at geek-central.gen.new_zealand Fri Jul 25 00:44:35 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 25 Jul 2008 16:44:35 +1200 Subject: Question about inheritence References: Message-ID: In message , Fredrik Lundh wrote: > Python doesn't really have constructors; when you create an object, > Python first creates the object and then calls the __init__ method, if > available That's the usual meaning of "constructor". It doesn't actually "construct" the object, it really "initializes" it. From tjreedy at udel.edu Sat Jul 5 18:22:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 05 Jul 2008 18:22:02 -0400 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <9cae59d9-ead4-45bc-a980-2ac2e1616f9b@p25g2000hsf.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <9cae59d9-ead4-45bc-a980-2ac2e1616f9b@p25g2000hsf.googlegroups.com> Message-ID: Mark Dickinson wrote: > On Jul 5, 1:54 pm, Carl Banks wrote: > Part of the problem is a lack of agreement on what > 'regular expression' means. Twenty years ago, there was. Calling a extended re-derived grammar expression like Perl's a 'regular-expression' is a bit like calling a Hummer a 'car' -- perhaps to hide its gas-guzzling behavior. > Strictly speaking, PCREs aren't > regular expressions at all, for some values of the term > 'regular expression'. See > > http://en.wikipedia.org/wiki/Regular_expression From larry.bates at websafe.com` Wed Jul 9 20:25:22 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 09 Jul 2008 19:25:22 -0500 Subject: Terminate a python script from linux shell / bash script In-Reply-To: References: Message-ID: Gros Bedo wrote: > Hello :-) > > I have a question about Python and Linux shell. I have a python program which is permanently resident in the end-user system. I'm currently producing a RPM package, and it works nicely. The problem is that when I uninstall it, my program keeps running in the background, even if the files are deleted. > > I know I can terminate python shell directly, but this is not a good idea because the end-user may be working with another important python application, and would be very angry if mine would close everything that is using python shell. > > So, is there a way from the Linux shell or a bash script to terminate just one specific Python script ? > _________________________________________________________________ > Votre contact a choisi Hotmail, l'e-mail nouvelle g?n?ration. Cr?ez un compte. > http://www.windowslive.fr/hotmail/default.asp You should use the signal module to look for SIGINT signal and exit if it is received. -Larry From circularfunc at gmail.com Sat Jul 12 21:10:58 2008 From: circularfunc at gmail.com (ssecorp) Date: Sat, 12 Jul 2008 18:10:58 -0700 (PDT) Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> Message-ID: <85c3da91-9f2f-4d19-ba98-dfdc99b1e1e3@79g2000hsk.googlegroups.com> On Jul 13, 2:32?am, Roy Smith wrote: > In article > <3b78898b-6131-4137-9c1d-64deaf460... at p25g2000hsf.googlegroups.com>, > > > > ?ssecorp wrote: > > Is this correct use of exceptions? to raise an indexerror and add my > > own string insetad of just letting it raise a IndexError by itself and > > "blaming" it on list.pop? > > > class Stack(object): > > ? ? def __init__(self, *items): > > ? ? ? ? self.stack = list(items) > > > ? ? def push(self, item): > > ? ? ? ? self.stack.append(item) > > > ? ? def pop(self): > > ? ? ? ? try: > > ? ? ? ? ? ? return self.stack.pop() > > ? ? ? ? except: > > ? ? ? ? ? ? raise IndexError, "pop from empty stack" > > > class Queue(object): > > ? ? def __init__(self, *items): > > ? ? ? ? self.queue = list(items) > > > ? ? def append(self, item): > > ? ? ? ? self.queue.append(item) > > > ? ? def pop(self): > > ? ? ? ? try: > > ? ? ? ? ? ? return self.queue.pop(0) > > ? ? ? ? except: > > ? ? ? ? ? ? raise IndexError, "pop from empty queue" > > I think you would do better defining a new exception, PopError, or > something like that. ?Then you can write code which specifically catches > that and do something with it. > > It's also not a good idea to catch all exceptions. ?Catch the most specific > thing you can. ?Consider something like: > > try: > ? ? kew.pop(0) > except: > ? ?raise IndexError, "pop from empty kew" > > When I run it, it prints, "IndexError: pop from empty kew". ?The problem > is, the *real* error is "NameError: name 'kew' is not defined". ?By > catching all exceptions, I've masked a programming error by turning the > NameError into an IndexError. i dont get what you mean, if i dont do anything python will raise an indexerror so it is an indexerror. From tjreedy at udel.edu Tue Jul 22 12:28:29 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2008 12:28:29 -0400 Subject: string[i:j:k] In-Reply-To: References: Message-ID: konstantin wrote: > Hello, > I'm not a newbie in python, but recently faced a problem in simple > expression: > some_string[i:j:k] > What does it mean? I believe this grammar (http://docs.python.org/ref/ > slicings.html) describes the syntax. But I can't grasp it. When you post a link, please put it on one line by itself, like this: http://docs.python.org/ref/slicings.html so it will be clickable as a whole by modern newsreaders. Experimenting with bits of code in the interactive interpreter (or IDLE, which is easier to cut from), like the responders did, is a great way to learn. From ldo at geek-central.gen.new_zealand Fri Jul 18 01:38:51 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 18 Jul 2008 17:38:51 +1200 Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> <98eae1fc-ff34-4dcc-b46d-9e3da2850c28@r66g2000hsg.googlegroups.com> Message-ID: In message <98eae1fc-ff34-4dcc-b46d-9e3da2850c28 at r66g2000hsg.googlegroups.com>, Craig Allen wrote: > On Jul 16, 7:01 pm, Lawrence D'Oliveiro central.gen.new_zealand> wrote: >> >> >>> class TehLibrary(object) : >> >> ... @classmethod >> ... def __new__(self, cls) : >> ... return self >> >> >>> s = TehLibrary() >> >>> s == TehLibrary() >> >> True > > That's great, I simply didn't find that when looking. Thanks! Also note that s == TehLibrary will be true (the instance equals the class). I assume that doesn't matter for your purposes. :) From Scott.Daniels at Acm.Org Wed Jul 16 09:01:55 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 16 Jul 2008 06:01:55 -0700 Subject: Need Python Programmer (preferentially in Los Angeles) In-Reply-To: References: Message-ID: robnhood00 wrote: > I need a python programmer that can integrate graphics into an > existing python application. The application is a basic application > and the job should be pretty easy for an experienced Python > programmer. Los Angeles programmer is preferred but this can > obviously be done from anywhere. > Please contact me at robnhood007 at yahoo.com is you can help me. > Thank you. I get worried when I hear people tell me that a job they don't know how to do "should be pretty easy," but at least it is better than "should only take a week." What I'd rather hear is, "seems like it is a simple job." Beware of customers who know something will take little effort without being able to characterize that effort. --Scott David Daniels Scott.Daniels at Acm.Org From svenn.bjerkem at googlemail.com Mon Jul 28 17:49:19 2008 From: svenn.bjerkem at googlemail.com (Svenn Are Bjerkem) Date: Mon, 28 Jul 2008 14:49:19 -0700 (PDT) Subject: Parsing VHDL with python, where to start. References: <31888260-86a9-46b0-b0a4-79f7852f256a@k30g2000hse.googlegroups.com> Message-ID: Hi again, when I get far enough to parse the VHDL (which is not currently the fact, but I have to look at the work coming up downstream) I will have to put it into an internal data structure and then write some classes to handle the MVC between whatever data I have and the PyQt4 widget that is going to show the block diagram. I own the book "Rapig GUI Programming with Python and Qt" by Mark Summerfield and try to read up on the PyQt way of doing things as I try to make a plan for my application. I have been looking for possible data structures with google just to find out that most of the ideas are stored in proceedings or to conferences or ieee papers not generally available to me. Is anybody experienced with designing data structures willing to share some ideas with me? Since I am using the open-source version of PyQt4, any information will eventually be available to public (if the app pass the planning stage) if that makes helping out any easier: :-) There is already an app called Qucs that is running in Qt-3 and being ported to Qt-4 that is written in C++, but I don't know how wise it is to just reverse-engineering C++ classes and translate them into python classes. -- Svenn From jsanga at cox.net Thu Jul 10 08:24:57 2008 From: jsanga at cox.net (mzdude) Date: Thu, 10 Jul 2008 05:24:57 -0700 (PDT) Subject: Retrieving BSTR * from a DLL References: <500e422d-5868-4a2b-a213-7d4d13a51d23@j22g2000hsf.googlegroups.com> Message-ID: <3fe43184-d2d8-456b-a5b4-b8a878806bba@z72g2000hsb.googlegroups.com> On Jul 10, 6:15?am, Andrew MacIntyre wrote: > This likely indicates that the DLL is using the C calling convention > and not the stdcall calling convention. ?Use CDLL rather than WinDLL > to load the DLL. using cdll got me over the calling hurdle. However, I'm not seeing the returned BSTR. > You might like to join the ctypes-users mailing list at sourceforge. I did, thanks. From Scott.Daniels at Acm.Org Fri Jul 18 09:08:26 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 18 Jul 2008 06:08:26 -0700 Subject: trying to match a string In-Reply-To: References: Message-ID: arnimavidyarthy at gmail.com wrote: > I am taking a string as an input from the user and it should only > contain the chars:L , M or R How about skipping re's and doing something like: set(input_string) <= set('LMR') If you want to disallow the empty string: set([]) < set(input_string) <= set('LMR') --Scott David Daniels Scott.Daniels at Acm.Org From mrkafk at gmail.com Thu Jul 17 09:56:13 2008 From: mrkafk at gmail.com (mk) Date: Thu, 17 Jul 2008 15:56:13 +0200 Subject: storing references instead of copies in a dictionary In-Reply-To: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: Calvin Spealman wrote: > To your actual problem... Why do you wanna do this anyway? If you want > to change the function in the dictionary, why don't you simply define > the functions you'll want to use, and change the one you have bound to > the key in the dictionary when you want to change it? In other words, > define them all at once, and then just d['1'] = new_f1. What is wrong > with that? Well, basically nothing except I need to remember I have to do that. Suppose one does that frequently in a program. It becomes tedious. I think I will define some helper function then: >>> def helper(fundict, newfun): ... fundict[newfun.func_name] = newfun ... _If_ there were some shorter and still "proper" way to do it, I'd use it. If not, no big deal. > For completeness: > > def new_f1(arg): > return "NEW f1 " + arg > f1.func_code = new_f1.func_code > > Don't use that unless you really have to and I nearly promise that you don't. I promise I won't use it. :-) It seems like a 'wrong thing to do'. From stuart.a.hall at gmail.com Thu Jul 31 14:32:01 2008 From: stuart.a.hall at gmail.com (fprintf) Date: Thu, 31 Jul 2008 11:32:01 -0700 (PDT) Subject: Hobbyist - Python vs. other languages Message-ID: I have been playing with computers since I first learned to program moving shapes on an Atari 800XL in BASIC. After many years of dabbling in programming languages as a hobbyist (I am not a computer scientist or other IT professional), I have never found a way to stick with a language far enough to do anything useful. I learn all about loops and data structures and functions/methods etc. but never get to create a program that will do anything of value that I can't more easily do via freeware. Well, except the slot car timing system I wrote in C++ for Linux many moons ago. Honestly Python seems like a breath of fresh air and possibly a way to get back to my BASIC roots, you know, programming just for the fun of it. Since I don't have a specific problem to solve, besides Pythonchallenge (which I found very cryptic), and Project Euler (which I found beyond my mathematics skills), is there a place to go for increasingly difficult problems to solve? I have followed a number of the recommended online tutorials that contain a logical progression of problems and yet they all end at the point where a person has enough knowledge of the syntax, but not really enough to do anything. From larry.bates at websafe.com` Thu Jul 3 20:56:46 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 03 Jul 2008 19:56:46 -0500 Subject: How to bypass Windows 'cooking' the I/O? (One more time, please) In-Reply-To: References: Message-ID: norseman wrote: > > > I know I saw the answer recently, as in since February '08, but I can't > re-find it. :( I tried the mail archives and such and my own > collections but the piece I saw still eludes me. > > > Problem: (sos=same old s...) Microsoft insists the world work it's way > even when the Microsoft way was proven wrong decades ago. In this case > it's (still) 'cooking' the writes even with 'rwb' and O_RDWR|O_BINARY in > (proper respective) use. > > Specific: python created and inspected binary file ends: > 00460: 0D 1A (this is correct) > > after a write > os.lseek(target, -1, 2) > os.write(target,record) > the expected result would be: > 00460: 0D 20 .....data bytes.... 1A > > BUT I get: > 00460: 20 .... data bytes... 1A > > It is one byte off!!! And the 0D has to be there. Signifies the end of > the header. > > > Same python program runs as expected in Linux. Maybe because that's > where it was written?! :) > > > What I seek is the way to slap Microsoft up side the head and make it > work correctly. OK, well, at least in this situation. > > > Note: Things like this justify Python implementers bypassing OS calls > (data fetch, data write) and using the BIOS direct. Remember, the CPU > understands bit patterns only. It has no comprehension of 'text', > 'program', 'number', 'pointer', blah blah blah.... All that is totally > beyond it's understanding. A given bit pattern means 'do that'. The CPU > is 100% binary. Memory, storage and the rest is just bits-on, bits-off. > Patterns. Proper binary I/O is mandatory for the machine to function. > > > Anyway - if whoever mentioned the flags and such to 'over ride' > Microsoft's BS would re-send that piece I would be very appreciative. > > > Steve > norseman at hughes.net Since you didn't show any code context, I'll try my mind reading superpowers..... You may be the victim of buffering (not calling .flush() or .close() to commit your write to disk). Why aren't you using the file object to do you seek and write? Normal file I/O sequence: fp = open(target, 'wb') fp.seek(-1, 2) fp.write(record) by going through os. methods instead of the file instance I think you are accessing the file through 2 different I/O buffers. I could be all wrong here. -Larry From Nikolaus at rath.org Mon Jul 28 03:38:36 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 28 Jul 2008 09:38:36 +0200 Subject: Attack a sacred Python Cow References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c29cc$0$20302$c3e8da3@news.astraweb.com> <20080727193416.GE7373@dragontoe.org> <488D580B.9050001@gmail.com> Message-ID: <87myk2sbk3.fsf@nokile.rath.org> Michael Torrie writes: > I think the biggest reason why an implicit self is bad is because it > prevents monkey-patching of existing class objects. Right now I can add > a new method to any existing class just with a simple attribute like so > (adding a new function to an existing instance object isn't so simple, > but ah well): > > def a(self, x, y): > self.x = x > self.y = y > > class Test(object): > pass > > Test.setxy = a > > b = Test() > > b.setxy(4,4) > > print b.x, b.y > > If self was implicit, none of this would work. No, but it could work like this: def a(x, y): self.x = x self.y = y class Test(object): pass Test.setxy = a b = Test() # Still all the same until here # Since setxy is called as an instance method, it automatically # gets a 'self' variable and everything works nicely b.setxy(4,4) # This throws an exception, since self is undefined a(4,4) Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From gnuarm at gmail.com Sat Jul 12 00:05:16 2008 From: gnuarm at gmail.com (rickman) Date: Fri, 11 Jul 2008 21:05:16 -0700 (PDT) Subject: spam References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> Message-ID: spam From Russ.Paielli at gmail.com Wed Jul 30 02:39:45 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 23:39:45 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> Message-ID: On Jul 29, 11:36 pm, Erik Max Francis wrote: > Russ P. wrote: > > On Jul 29, 11:09 pm, Erik Max Francis wrote: > > >> I'm getting this sneaking suspicion that you guys are all putting us on. > > > As I said in an earlier post, I realize that this would only work if > > there were only one copy of "empty" (as there is only one copy of > > "None"). I don't know off hand if that is feasible or not. > > It's only feasible if you change what `is` means for this one bizarre > use case, which isn't a good idea. > > > You reply reeks of the kind of pedantic snobbishness that makes me > > sick. > > Well, if understanding what the `is` operator means is pedantic > snobbishness, then hey, go right ahead. > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis > The doors of Heaven and Hell are adjacent and identical. > -- Nikos Kazantzakis I fully understand what the "is" operator is, and I never had any problem with it at all, thank you. But then again, I suppose that depends on what the meaning of "is" is ... From timr at probo.com Sun Jul 27 00:20:37 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 27 Jul 2008 04:20:37 GMT Subject: How to close all python-opened file identifiers? References: Message-ID: BAnderton wrote: > >Question: Is there a way in Python to determine what all file >identifiers have been opened by Python, and to close them all? No. You are expected to be able to track this yourself. Python doesn't open any files that you didn't request. >Extra info on this specific problem: In my program, python (through >subprocess) launched a text editor on a text file, and I can't seem to >save the text file through that editor (I get a "this document is in >use by another application and cannot be accessed" error from the >editor [wordpad on winXp]). The text file in question is modified by >my program prior to its loading into the launched editor. Although I >can't find unmatched "open" and "fid.close()" statements, I'd like to >implement a check for open file identifiers before launching the >editor. If you want to post some code, perhaps we can find something. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From rkmr.em at gmail.com Sun Jul 27 21:26:13 2008 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Sun, 27 Jul 2008 18:26:13 -0700 Subject: write unsigned integer 32 bits to socket Message-ID: hi i want to send unsigned 32 bit integer to socket, and looking for something equivalent to this method... http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt() is there such method / library available in python?! this is as far as i have gotten along >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> s.connect(('127.0.0.1',3000)) From praveen.sunsetpoint at gmail.com Wed Jul 2 07:41:08 2008 From: praveen.sunsetpoint at gmail.com (Sallu) Date: Wed, 2 Jul 2008 04:41:08 -0700 (PDT) Subject: Email Validation with domain Message-ID: Hi All, import re msg=raw_input('Enter the email : ') def validateEmail(email): #if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9] {1,3})(\\]?)$", email) != None: if re.match("^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$", email) != None: print 'Valis' else: print 'not' validateEmail(msg) i wrote a script above it works fine but it does not check for valid domain like .com .org .in how to validate with domain From seberino at spawar.navy.mil Tue Jul 1 02:28:43 2008 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: Mon, 30 Jun 2008 23:28:43 -0700 (PDT) Subject: How make regex that means "contains regex#1 but NOT regex#2" ?? Message-ID: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> I'm looking over the docs for the re module and can't find how to "NOT" an entire regex. For example..... How make regex that means "contains regex#1 but NOT regex#2" ? Chris From Inyeol.Lee at gmail.com Fri Jul 11 09:01:33 2008 From: Inyeol.Lee at gmail.com (Inyeol.Lee at gmail.com) Date: Fri, 11 Jul 2008 06:01:33 -0700 (PDT) Subject: How to serialize and deserialize the objects into memory? References: <0a7ead85-2a38-41a8-98b8-59dede61f985@c58g2000hsc.googlegroups.com> Message-ID: <099408eb-30d4-4ad5-bb22-af238c7aca58@l64g2000hse.googlegroups.com> On Jul 11, 12:58 pm, hardemr wrote: > Hello Everyone, > > I want to serialize and deserialize the objects into Memory not into > file. How can i do that? pickle.dumps and pickle.loads. --Inyeol From mdw at distorted.org.uk Sun Jul 6 12:50:20 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Sun, 6 Jul 2008 16:50:20 +0000 (UTC) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Sebastian "lunar" Wiesner wrote: > I just wanted to illustrate, that the speed of the given search is somehow > related to the complexity of the engine. > > Btw, other pcre implementation are as slow as Python or "grep -P". I tried > a sample C++-code using pcre++ (a wrapper around libpcre) and saw it > running equally long. So some other implementations are equally poor. I note that Perl itself handles this case very quickly, as does Edi Weitz's CL-PPCRE library. Yes, Perl-compatible `regular expressions' are more complicated than POSIX extended regular expressions; but that doesn't mean that you have to implement them in a dumb way. Indeed, it stands to reason that expressions describing truly regular languages can be matched using the same old algorithms that grep uses. -- [mdw] From asmodai at in-nomine.org Thu Jul 24 07:59:53 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 24 Jul 2008 13:59:53 +0200 Subject: how to cut and paste in the windows of python(command line) In-Reply-To: References: <9500663c-0985-4dfd-8d0a-ae25411f00e5@v39g2000pro.googlegroups.com> Message-ID: <20080724115953.GU57040@nexus.in-nomine.org> -On [20080724 13:50], Fredrik Lundh (fredrik at pythonware.com) wrote: >if you want better console support, consider installing the "ipython" >shell: Unless you work with non-ASCII. Ipython mangles non-ASCII unfortunately. [Full UTF-8 environment] In [1]: a = u'?' In [2]: a Out[2]: u'\xe6\x84\x9b' Normal python shell: >>> a = u'?' >>> a u'\u611b' I wonder if it can be easily fixed with a getpreferredencoding() or by using an .encode(sys.stdout.encoding or getpreferredencoding() or 'ascii', 'replace') triplet. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B One who knows that enough is enough will always have enough... From adityashukla1983 at gmail.com Mon Jul 28 00:13:19 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Sun, 27 Jul 2008 23:13:19 -0500 Subject: Command line arguements Message-ID: <73045cca0807272113y397de468yfcb00ffbbec7990a@mail.gmail.com> Hello folks ,I have a program in which a text file is generated as an output eg C:\prog\ prog -x test.txt Right now whenever i have to read the test file i have to put its name manually in my code. eg f=open("c:\\prog\\test.txt","r") How ever i want to add the name of the test file dynamically to my program ie , if every time i give C:\prog\ prog -x test.txt The filename (test.txt) automatically comes in f=open("c:\\prog\\test.txt","r") C:\prog\ prog -x file1.txt f=open("c:\\prog\\file1","r") in other words i do not want to do hard code the name of the file in my code every time i need to read it. I was reading about the sys module and i guess sys.argv would take the input from the command line whenever i run the python script . Please guide me in the right direction on how to tackle the problem. Thanks in advance Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From dullrich at sprynet.com Thu Jul 24 12:26:12 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 24 Jul 2008 11:26:12 -0500 Subject: repr(string) References: Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > David C. Ullrich wrote: > > > In article , > > Fredrik Lundh wrote: > > > >> David C. Ullrich wrote: > >> > >> > I've been saving data in a file with one line per field. > >> > Now some of the fields may become multi-line strings... > >> > > >> > I was about to start escaping and unescaping linefeeds > >> > by hand, when I realized that repr() and eval() should > >> > do. Hence the question: If s is a string, is repr(s) > >> > guaranteed not to contain line breaks? > >> > >> yes. > >> > >> just keep in mind that using eval() on untrusted data isn't a very good > >> idea. > > > > Right. This data comes from me, gets put into a file and then > > read by me. Someone _could_ corrupt that file, but someone who > > could do that could more easily just throw the machine out > > the window... > > You could also use a csv file with a single row. Excellent suggestion. I have a different point of view on all this than most of you guys (see reply to F). From my curious point of view csv was no fun anymore when csvlib got added to Python... > Peter -- David C. Ullrich From grante at visi.com Tue Jul 1 10:07:07 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 01 Jul 2008 09:07:07 -0500 Subject: Implementing an 8 bit fixed point register References: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> Message-ID: On 2008-07-01, nickooooola wrote: > Hello to all > I'm about to write a simulator for a microcontroller in python > (why python? because I love it!!!) > > but I have a problem. > > The registry of this processor are all 8 bit long (and 10 bit > for some other strange register) and I need to simulate the > fixed point behaviour of the register, Somebody posted a class that impliments fixed-width integer types a while back. > and to access the single bit. The bitwise operators &, |, ~, ^ all work just like they do in C. You can write methods to dip those in syntactic sugar if you want. > f.x. (this is a pseudo python session, only for understanding) > >>>> reg1 = fixed_int(8) >>>> reg2 = fixed_int(10) >>>> reg1[0].set() > or >>>> reg1[0] = 1 # or True? how to rapresent a binary bit >>>> reg1[0] > 1 >>>> reg1[1] > 0 >>>> reg1[9] > >>>> reg2 = 0x7FE # in binary 11111111110 , or 11 bit long >>>> reg2 > 0x7FE > #or 1111111110, the memorization truncate the upper bits ( or perhaps > generate an exception?) >>>> reg2 += 0x02 #the result is 10000000000, again not contained in 10 bit >>>> reg2 > 0x00 > # truncated again >>>> myprocessor.flags['z'] > 1 > # or True? Z flag indicated an overflow in arithmetic operations > > Is possibile to do so in python? Yes. Everything shown above is possible. If you really want to get clever, you'll want to read up on the __setattr__, __getattr__, __getitem__, and __setitem__ object methods. They'll allow you to define special handling for the semantics below: foo.something = x # calls foo.__setattr___('something',x) x = foo.something # calls foo.__getattr___('something,) foo[n] = x # calls foo.__setitem__(n,x) x = foo[n] # calls foo.__getitme__(n) In the latter two cases, you can support slicing if you want. That could allows you to grab a "bitfield" out of a register: x = processor.regA[4:7] # get bits 4,5,6 processor.regA[4:7] # set bits 4,5,6 Just remember that in Python slices are traditionally half-open intervals -- they don't include the "right" endpoint. That's going to confuse people who are more used to reading processor data sheets where bit-ranges are traditionally closed intervals. You _could_ implment your __[sg]etitem__ slice handling so that they're treated as closed intervals. That will be a lot more intuitive to people used to dealing with microprocessor register definitions, but could confuse an experienced Python programmer. Writing methods for __setattr__ and __getattr__ is a little tricky. It's very easy to end up with infinite recursion. It's not that hard to fix/avoid, but it takes a while to get the hang of it. -- Grant Edwards grante Yow! at visi.com From manuel.dipl at gmail.com Tue Jul 15 03:36:21 2008 From: manuel.dipl at gmail.com (manu) Date: Tue, 15 Jul 2008 00:36:21 -0700 (PDT) Subject: trying to use sax for a very basic first xml parser References: <6ff86003-a3e8-4c5b-9276-1cd3c7f0ffa7@56g2000hsm.googlegroups.com> <3a7148a9-b95d-4e95-b3b7-492e0d016ab8@f36g2000hsa.googlegroups.com> <3cd4f2b6-8bd1-49c3-9958-de1af69b86af@f36g2000hsa.googlegroups.com> Message-ID: <882147ac-8998-465a-b16e-5a3a767d91d1@i76g2000hsf.googlegroups.com> > > May I suggest you ask in the blender list? > Will do that and report back. Thank you! Manuel From pyth0nc0d3r at gmail.com Wed Jul 9 03:13:48 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Wed, 9 Jul 2008 02:13:48 -0500 Subject: Regular Expressions Quick Question Message-ID: Alright, basically I have a list of words in a file and I load each word from each line into the array. Then basically the question is how do I check if the input word matches multiple words in the list. Say someone input "test", how could I check if that word matches these list of words: test testing tested Out of the list of Hello blah example test ested tested testing I want it to loop then check if the input word I used starts any of the words in the list so if I typed 'tes' Then: test testing testing would be appended to a new array. I'm unsure how to do this in python. Thanks in advanced. -------------- next part -------------- An HTML attachment was scrubbed... URL: From animator333 at gmail.com Fri Jul 18 05:36:20 2008 From: animator333 at gmail.com (King) Date: Fri, 18 Jul 2008 02:36:20 -0700 (PDT) Subject: sub typing built in type with common attributes. Am I right? References: <4d9c4b74-9c28-4b98-afe7-9eb774655c3a@v21g2000pro.googlegroups.com> Message-ID: <98c3de7d-f167-48f9-9736-b09938d96b92@f40g2000pri.googlegroups.com> My mistake... The correct __slots__ is like: __slots__ = ['_Attribute_name', '_Attribute_type', '_Attribute_range', 'label'] Could you please suggest an alternative or code improvement for the matter. Prashant From 4564 at 755189.45 Tue Jul 29 03:45:07 2008 From: 4564 at 755189.45 (Enrico) Date: Tue, 29 Jul 2008 09:45:07 +0200 Subject: multiple inheritance and __getattr__ References: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> <488e2e70$0$29472$426a74cc@news.free.fr> Message-ID: <488ecaaa$0$1090$4fafbaef@reader1.news.tin.it> "Bruno Desthuilliers" ha scritto nel messaggio news:488e2e70$0$29472$426a74cc at news.free.fr... > Indeed. You explicitely raise, so the lookup stops here. You'd need to > explicitely call on superclass instead to have B.__getattr__ called, ie: > > class A(object): > def __getattr__(self, name): > if name == 'a': > return 1 > return super(A, self).__getattr__(name) > > class B(object): > def __getattr__(self, name): > if name == 'b': > return 2 > return super(B, self).__getattr__(name) Hi Bruno, this is an interisting point. Just to understand better: when I raise an AttributeError the search stops but if I call a superclass (that for my understanding raises an AttributeError) the search continues. At this point I suspect that the search is doing something else, like checking if the class is at the top of the hierarchy. Do you know where I can look for this, probably in the core code of Python? > > Since A and B are not written by me I can only work on C. > > Really ? You know, Python is a *very* dynamic language. If A and B are > ordinary Python classes (ie: not builtin types, not C extensions, etc), > you can monkeypatch them. But that's not necessarily the best thing to > do (it would require more work than your actual solution). I know that I can do whatIwant with class A and class B (monkeypatch!) but I prefer to concentrate on my code and write a clean solution. Thanks for your help. Enrico From pyth0nc0d3r at gmail.com Sat Jul 19 15:13:04 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Sat, 19 Jul 2008 14:13:04 -0500 Subject: win32api not found? Message-ID: Where can I get the win32api module? I been searching all day on google and nothing, i installed https://sourceforge.net/project/showfiles.php?group_id=78018 which requires win32api and its not found... -------------- next part -------------- An HTML attachment was scrubbed... URL: From Bill at SynectixLtd.com Thu Jul 10 09:39:28 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Thu, 10 Jul 2008 14:39:28 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: "Tim Roberts" wrote in message news:h6k074119o4gomqlkju3mp7rj3i1bvha6j at 4ax.com... > "Bill Davy" wrote: >> >>I am trying to edit Contacts in Outlook. This is so I can transfer >>numbers >>from my address book which is an Excel spreadsheet to my mobile phone. > > Are you actually running Outlook? Your news posting was made from Outlook > Express, and Outlook Express cannot be controlled by COM (although MAPI > works). > -- > Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. I'm not sure OL2003 can read news. I think perhaps some later OL can (added tot he View menu, perhaps?). So I use OL Express to read news. The OL with which I wish to communicate is: Application name Outlook Version 11.0 Build 8217 Product ID 70141-700-0350904-56905 Language English (United States) Application Path C:\Program Files\Microsoft Office\OFFICE11\ System Language English (United Kingdom) Mail Support Not Available Current folder Inbox Current item Not Available Not sure why its says "Mail Support Not Available" as all I use it for is email (oh, and the calendar). Hey and ho Bill From h.goebel at goebel-consult.de Mon Jul 14 12:02:23 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Mon, 14 Jul 2008 18:02:23 +0200 Subject: Using McMillan Installer, PyInstall or py2exe cross-platform? Message-ID: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> Hi, has anybody used McMillan Installer, PyInstall or py2exe cross-platform? I have a Windows partition with Python installed there, so this would "only" required working on a different directory and for a different OS. Since I'm working on Linux, it's awful to boot Windows each time I want to build a new release. Any hint in this area? -- Sch?nen Gru? - Regards Hartmut Goebel Goebel Consult Spezialist f?r IT-Sicherheit in komplexen Umgebungen http://www.goebel-consult.de From davidreynon at gmail.com Thu Jul 17 10:33:08 2008 From: davidreynon at gmail.com (korean_dave) Date: Thu, 17 Jul 2008 07:33:08 -0700 (PDT) Subject: % sign in python? Message-ID: What does this operator do? Specifically in this context test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) (Tried googling and searching, but the "%" gets interpreted as an operation and distorts the search results) From basti.wiesner at gmx.net Sun Jul 6 11:34:04 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sun, 06 Jul 2008 17:34:04 +0200 Subject: Hands-on HTML Table Parser/Matrix? References: Message-ID: robert : > Often I want to extract some web table contents. Formats are > mostly static, simple text & numbers in it, other tags to be > stripped off. So a simple & fast approach would be ok. > > What of the different modules around is most easy to use, stable, > up-to-date, iterator access or best matrix-access (without need > for callback functions,classes.. for basic tasks)? Not more than a handful of lines with lxml.html: def htmltable2matrix(table): """Converts a html table to a matrix. :param table: The html table element :type table: An lxml element """ matrix = [] for row in table: matrix.append([e.text_content() for e in row]) return matrix -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From elessar at nienna.org Fri Jul 4 03:52:04 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 04 Jul 2008 01:52:04 -0600 Subject: Singleton implementation problems In-Reply-To: <87abgy2kcu.fsf@benfinney.id.au> References: <87abgy2kcu.fsf@benfinney.id.au> Message-ID: <486DD6A4.2080307@nienna.org> Ben Finney wrote: > Peter Otten <__peter__ at web.de> writes: > >> The problem is the structure of your program. The myset module is >> imported twice by Python, once as "myset" and once as "__main__". > > Yes, this is the problem. Each module imports the other. > >> Therefore you get two distinct MySet classes, and consequently two >> distinct MySet.__instance class attributes. > > Are you sure? This goes against my understanding: that 'import foo' > will not re-import a module that's already been imported, but will > instead simply return the existing module. > > So, I think if one evaluated 'myset is __main__', you'd find they are > exactly the same module under different names; and therefore that > there is only *one* instance of 'MySet', again under two names. > You can see that they're distinct by checking the addresses (the instances in the OP also have different addresses). Besides, __main__ isn't imported normally. -Matt From ptmcg at austin.rr.com Tue Jul 22 13:36:14 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 22 Jul 2008 10:36:14 -0700 (PDT) Subject: Not entirely serious: recursive lambda? References: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> Message-ID: On Jul 22, 11:52?am, Michael Tobis wrote: > Thanks all! What a remarkable set of answers, intelligent, thought > provoking and informative without exception. > > Of course, now I can't use Paul's version; it hardly counts as a japh > if someone else wrote it! It is probably the closest to my original > vision, alas. Miles' second suggestion was the one I was fumbling > toward; I will study it. No spoilers please. > > best > mt Michael - Sorry to spoil your fun - the concept of a recursive lambda was such an interesting diversion, I couldn't resist! I'll try to restrain myself next time. -- Paul From stefan_ml at behnel.de Wed Jul 23 12:29:22 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 23 Jul 2008 18:29:22 +0200 Subject: lxml, comparing nodes In-Reply-To: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> Message-ID: <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> code_berzerker wrote: > I'd like to know if there is any built in mechanism in lxml that lets > you check equality of two nodes from separate documents. No, because, as you state yourself, equality is not something that everyone defines the same way. > I'd like it > to ignore attribute order and so on. It would be even better if there > was built in method for checking equality of whole documents (ignoring > document order). Please let me know if you know of such method or > existing scipt. I dont like reinventing the wheel :) Your requirements for a single Element are simple enough to write it in three to five lines of Python code (depending on your definition of equality). Checking this equality recursively is another two to three lines. Not complex enough to be considered a wheel in the first place. Stefan From kyosohma at gmail.com Mon Jul 28 15:21:02 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 28 Jul 2008 12:21:02 -0700 (PDT) Subject: how to upload files to "google code" filesection ? References: <7f6182a3-4504-4239-8239-673a7e4bfefd@s50g2000hsb.googlegroups.com> Message-ID: <63de76c2-349c-4371-8732-1681301c7ab0@a1g2000hsb.googlegroups.com> Stef, > Mike Driscoll wrote: > > On Jul 26, 12:43 pm, Stef Mientki wrote: > > >> hello, > > >> In a program I want to download (updated) files from google code (not > >> the svn section). > >> I could find a python script to upload files, > >> but not for downloading. > > >> Anyone has a hint or a solution ? > > >> thanks, > >> Stef Mientki > > > You should be able to use urllib to do that. The following link has a > > recipe: > > >http://code.activestate.com/recipes/496685/ > > thanks Mike, > > I already found an even simpler solution (that works) > > ? ? filename, header = urllib.urlretrieve (url) > > > If you need to search Google Code, there's an API that appears to be > > exposed through their gdata module. > > Do you have perhaps a more specific link ? > I saw the Google API's, but its'quit large / complex, so I couldnt find > it there. > > cheers, > Stef > > > Mike I was looking at this page about Google Code Search: http://code.google.com/apis/codesearch/ You should be able to use the API that's outlined there in conjunction with the gdata module on this page: http://code.google.com/p/gdata-python-client/ Mike From wtanksleyjr at gmail.com Tue Jul 29 13:53:41 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Tue, 29 Jul 2008 10:53:41 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> Message-ID: <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> To ask another way: how do I convert from a file:// URL to a local path in a standard way, so that filepaths from two different sources will work the same way in a dictionary? Right now I'm using the following source: track_id = url2pathname(urlparse(track_id).path) url2pathname is from urllib; urlparse is from the urlparse module. The problems occur when the filenames have non-ascii characters in them -- I suspect that the URLs are having some encoding placed on them that Python's decoder doesn't know about. Thank you all in advance, and thank you for Python. -Wm From bj_666 at gmx.net Mon Jul 21 13:21:48 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Jul 2008 17:21:48 GMT Subject: Python Written in C? References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> Message-ID: <6ejutcF6vgp3U4@mid.uni-berlin.de> On Mon, 21 Jul 2008 18:12:54 +0200, mk wrote: > Seriously, though, would there be any advantage in re-implementing > Python in e.g. C++? > > Not that current implementation is bad, anything but, but if you're not > careful, the fact that lists are implemented as C arrays can bite your > rear from time to time (it recently bit mine while using lxml). Suppose > C++ re-implementation used some other data structure (like linked list, > possibly with twists like having an array containing pointers to 1st > linked list elements to speed lookups up), which would be a bit slower > on average perhaps, but it would behave better re deletion? An operation that most people avoid because of the penalty of "shifting down" all elements after the deleted one. Pythonistas tend to build new lists without unwanted elements instead. I can't even remember when I deleted something from a list in the past. Ciao, Marc 'BlackJack' Rintsch From rhamph at gmail.com Wed Jul 30 13:51:00 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 30 Jul 2008 10:51:00 -0700 (PDT) Subject: static variables in Python? References: Message-ID: <977b55ed-6fb1-4f5e-9090-047972e69c0c@n33g2000pri.googlegroups.com> On Jul 29, 2:40?pm, kj wrote: > Yet another noob question... > > Is there a way to mimic C's static variables in Python? ?Or something > like it? ?The idea is to equip a given function with a set of > constants that belong only to it, so as not to clutter the global > namespace with variables that are not needed elsewhere. I'd go ahead and use globals. If these really are constant you should just name them clearly (and possibly use all caps). If they have a possibility of becoming non-constant in the future, write a class. No fancy tricks needed to store state. From deets at nospam.web.de Tue Jul 22 08:51:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 14:51:30 +0200 Subject: is it possible to add a property to an instance? References: Message-ID: <6em3gfF7o4qgU2@mid.uni-berlin.de> Darren Dale wrote: > Does anyone know if it is possible to add a property to an instance at > runtime? I didn't see anything about it in the standard library's new > module, google hasn't turned up much either. Depending on what you *really* want - yes or no. It is *not* possible to have a property *only* on one instance, because properties rely on the descriptor-protocol being used, and that only works for class-attributes. So it's not a matter of "only" adding a = Foo() a.something = property(...) However, you can of course try & come up with a scheme that only invokes getters and setters if defined, and otherwise returns a default-value/raises an attribute-error. Roughly like this: class Base(object): def x_get(self): return self.x_get_overload() x = property(x_get) a = Base() def foo(self): return "something" a.x_get_overload = new.instancemethod(foo) Diez From Samnsparky at gmail.com Tue Jul 15 14:16:09 2008 From: Samnsparky at gmail.com (Sparky) Date: Tue, 15 Jul 2008 11:16:09 -0700 (PDT) Subject: File Locking Forced? Newbie question. References: <216e2396-65f6-4281-b3c5-754ceb07f3eb@m36g2000hse.googlegroups.com> Message-ID: On Jul 15, 11:38?am, Tim Golden wrote: > Sparky wrote: > > Hello! I am writing some software that will have many users accessing > > the same file resource at once for reading purposes only. I am > > programming on (Ubuntu) Linux and my question is in Windows, can I > > have it so that the same file can be open in read mode by more than > > one person or could Window's file locking system get in the way? > > Assuming your question is: can processes A, B & C read > from the same file at the same time, then: Yes. (You > can try it out yourself fairly easily if you want. Just > open a clutch of interpreter windows and do some > open ("abc.txt", "r").read () stuff in each one). > > But I'm surprised you think that anything might get > in the way of that. It would be a fairly limiting file > system which prevented multiple simultaneous readers. > > TJG Thank you. For some reason I thought there was a file locking system on Windows (http://en.wikipedia.org/wiki/ File_locking#File_locking_in_Microsoft_Windows). But, I believe that that only applies to those using Microsoft's file methods and only for writing. Thanks for clearing that up. Sam From moogyd at yahoo.co.uk Sat Jul 12 14:55:54 2008 From: moogyd at yahoo.co.uk (moogyd at yahoo.co.uk) Date: Sat, 12 Jul 2008 11:55:54 -0700 (PDT) Subject: Beginner Question : Iterators and zip Message-ID: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> Hi group, I have a basic question on the zip built in function. I am writing a simple text file comparison script, that compares line by line and character by character. The output is the original file, with an X in place of any characters that are different. I have managed a solution for a fixed (3) number of files, but I want a solution of any number of input files. The outline of my solution: for vec in zip(vec_list[0],vec_list[1],vec_list[2]): res = '' for entry in zip(vec[0],vec[1],vec[2]): if len(set(entry)) > 1: res = res+'X' else: res = res+entry[0] outfile.write(res) So vec is a tuple containing a line from each file, and then entry is a tuple containg a character from each line. 2 questions 1) What is the general solution. Using zip in this way looks wrong. Is there another function that does what I want 2) I am using set to remove any repeated characters. Is there a "better" way ? Any other comments/suggestions appreciated. Thanks, Steven From larry.bates at websafe.com` Tue Jul 1 14:57:16 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 01 Jul 2008 13:57:16 -0500 Subject: Convert string to char array In-Reply-To: <0%uak.283$4a3.73@trnddc04> References: <0%uak.283$4a3.73@trnddc04> Message-ID: Brandon wrote: > How do I convert a string to a char array? I am doing this so I can edit > the string received from an sql query so I can remove unnecessary > characters. > > The precise answer is: >>> s = 'abcdefghi' >>> l = list(s) >>> l ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] >>> But quite often you can just to the replace without doing the conversion >>> s = 'abc,de,fghi' >>> s2 = s.replace(',','') >>> s2 = s.replace(',','') 'abcdefghi' >>> -Larry From mhansen at gmail.com Wed Jul 9 22:40:59 2008 From: mhansen at gmail.com (Mike Hansen) Date: Wed, 9 Jul 2008 19:40:59 -0700 (PDT) Subject: sage vs enthought for sci computing References: <677e7819-e09e-43d3-8368-5864f91002be@34g2000hsh.googlegroups.com> Message-ID: On Jul 7, 3:35?pm, jadamwils... at gmail.com wrote: > Hello, > I have recently become interested in using python for scientific > computing, and came across both sage and enthought. I am curious if > anyone can tell me what the differences are between the two, since > there seems to be a lot of overlap (from what I have seen). If my goal > is to replace matlab (we do signal processing and stats on > physiological data, with a lot of visualization), would sage or > enthought get me going quicker? I realize that this is a pretty vague > question, and I can probably accomplish the same with either, but what > would lead me to choose one over the other? > Thanks! Hello, If you are using Windows, you're better off using Enthought for now since Sage does not run natively on Windows yet. Hopefully by the end of the year there will be a native version on Windows. If you're on Linux or OS X (or Solaris in the near future), then Sage does have some advantages. If you build Sage from source (which consists solely of type "make" once), then you get a copy of ATLAS tuned to your machine which can provide a solid speedup for numerical linear algebra problems. You also get all of the symbolic and exact arithmetic which may or may not be beneficial for your application. Sage also comes with libraries so that you can script Octave or Matlab or most any other system. --Mike Full disclosure: I'm a Sage developer :-) From paddy3118 at googlemail.com Sat Jul 12 01:49:30 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 11 Jul 2008 22:49:30 -0700 (PDT) Subject: read file into list of lists References: <1388b868-aae9-4233-b3ec-a85ffc029283@56g2000hsm.googlegroups.com> Message-ID: <59724a9a-6f49-448f-aaa3-dcf4c79ef96b@56g2000hsm.googlegroups.com> On Jul 11, 9:32?pm, John Machin wrote: > On Jul 11, 11:35 pm, Paddy wrote: > > > > > On Jul 11, 2:15 pm, antar2 wrote: > > > > Hello, > > > > I can not find out how to read a file into a list of lists. I know how > > > to split a text into a list > > > > sentences = line.split(\n) > > > > following text for example should be considered as a list of lists (3 > > > columns and 3 rows), so that when I make the print statement list[0] > > > [0], that the word pear appears > > > > pear noun singular > > > books nouns plural > > > table noun singular > > > > Can someone help me? > > > > Thanks > > > lofl = [line.strip().split() for line in the_opened_file] > > >>> line = ' ? foo ? bar ? ' > >>> line.strip().split() > ['foo', 'bar'] > >>> line.split() > > ['foo', 'bar'] Thanks , ta. - Paddy. From dingbat at codesmiths.com Thu Jul 31 06:10:26 2008 From: dingbat at codesmiths.com (Andy Dingley) Date: Thu, 31 Jul 2008 03:10:26 -0700 (PDT) Subject: SVN access with pysvn under Cygwin (Installation problems) References: <69da0a81-bf73-46cb-a762-b017a53e6ddf@e39g2000hsf.googlegroups.com> Message-ID: <4cd368f8-6402-4f3e-8496-d9d227b39dd9@m73g2000hsh.googlegroups.com> On 30 Jul, 20:30, Jason Tishler wrote: > You need to build (and install) pysvn under Cygwin. ?The pre-built > Windows version will not work under Cygwin. Thanks. Presumably this same problem would affect anything that uses a .pyd under Cygwin? From google at mrabarnett.plus.com Thu Jul 31 19:26:32 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 31 Jul 2008 16:26:32 -0700 (PDT) Subject: find and replace with regular expressions References: Message-ID: On Jul 31, 9:07?pm, chrispoliq... at gmail.com wrote: > I am using regular expressions to search a string (always full > sentences, maybe more than one sentence) for common abbreviations and > remove the periods. ?I need to break the string into different > sentences but split('.') doesn't solve the whole problem because of > possible periods in the middle of a sentence. > > So I have... > > ---------------- > > import re > > middle_abbr = re.compile('[A-Za-z0-9]\.[A-Za-z0-9]\.') > > # this will find abbreviations like e.g. or i.e. in the middle of a > sentence. > # then I want to remove the periods. > > ---------------- > > I want to keep the ie or eg but just take out the periods. ?Any > ideas? ?Of course newString = middle_abbr.sub('',txt) where txt is the > string will take out the entire abbreviation with the alphanumeric > characters included. It's recommended that you should use a raw strings for regular expressions. Capture the letters using parentheses: middle_abbr = re.compile(r'([A-Za-z0-9])\.([A-Za-z0-9])\.') and replace what was found with what was captured: newString = middle_abbr.sub(r'\1\2', txt) HTH From glman74 at gmail.com Sun Jul 27 11:44:07 2008 From: glman74 at gmail.com (glman74 at gmail.com) Date: Sun, 27 Jul 2008 08:44:07 -0700 (PDT) Subject: Iterating through 2 files simultaneously References: <7ae96aff-c1a7-4763-8db7-ff23766296df@u6g2000prc.googlegroups.com> Message-ID: > > So import STDOUT and make stderr=STDOUT in the Popen call, you will then > have one file/pipe to deal with p1.stdout. Thank you - that works great! Mahesh From semanticist at gmail.com Sun Jul 13 21:31:53 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 21:31:53 -0400 Subject: socket.connect() hangs in SYN_SENT state. In-Reply-To: References: <804bccb2-42c7-42e9-8f50-7a780d3438fd@j22g2000hsf.googlegroups.com> Message-ID: On Sun, Jul 13, 2008 at 8:35 PM, bukzor wrote: > The problem only manifests about 1 in 20 runs. Below there's code for > a client that shows the problem 100% of the time. > > The two URL's that I seem to be "confused" about point to the same IP. > Maybe this will make it clear: > > PING bukzor.hopto.org (75.61.84.249) 56(84) bytes of data. > 64 bytes from adsl-75-61-84-249.dsl.pltn13.sbcglobal.net > (75.61.84.249): icmp_seq=1 ttl=255 time=1.68 ms For me, buzkor.hopto.org resolves to 69.65.19.125, which I hope explains why I thought you were confused, and increases my own suspicion that DNS settings are to blame. I let the script run for about five minutes without it failing. Does your luck change if you use "localhost" or a numeric IP address in the ServerProxy URL? -Miles From tmohr at s.netic.de Fri Jul 18 11:03:43 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Fri, 18 Jul 2008 17:03:43 +0200 Subject: create PyString Message-ID: Hi, in an extension module i'd like to create a very large PyString. As the string is very large i'd first like to create the string and let Python allocate the space for it and then fill it from my code. But the only interface that i can find in Python/stringobject.h is: PyAPI_FUNC(PyObject *) PyString_FromStringAndSize(const char *, Py_ssize_t); But my extension module does not have the data consecutively in memory. If i'd use this function i'd first have to allocate the data, construct the string and then let python _again_ allocate the same amount of memory and copy my data. Is there a way to tell python to: 1. let python create a PyString with an allocated buffer 2. let my extension module fill the buffer 3. let python validate the strings hash value and whatever else is necessary? Thanks for any hints, Torsten. From bignose+hates-spam at benfinney.id.au Wed Jul 30 00:10:17 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 30 Jul 2008 14:10:17 +1000 Subject: Is it allowed to use function results as default arguments ? References: Message-ID: <87abg0dnbq.fsf@benfinney.id.au> "fred.haab" writes: > Well, others have answered the question, but I thought I'd throw in > that it would be more pythonic to do something like: > > def Get_Relative_Path(target, base = None): > if base is None: > base = os.curdir > ... Even more Pythonic would be to name the function by the style guide (PEP 8): def get_relative_path(target, base=None): if base is None: base = os.curdir # ? -- \ ?If trees could scream, would we be so cavalier about cutting | `\ them down? We might, if they screamed all the time, for no good | _o__) reason.? ?Jack Handey | Ben Finney From robert.rawlins at thinkbluemedia.co.uk Wed Jul 16 07:56:08 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Wed, 16 Jul 2008 12:56:08 +0100 Subject: Get current class namespace. Message-ID: <011401c8e73a$ef2fdd30$cd8f9790$@rawlins@thinkbluemedia.co.uk> Guys, What's the simplest way to access a classes namespace from within itself. I want to use it in a custom __repr__() method so it prints the current namespace for the class like package.module.class. Suggestions? I'm sure there is a simple enough method built in to help me here, I've just not seen it before. Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Sun Jul 13 09:56:40 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 13 Jul 2008 23:56:40 +1000 Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> <87skuems49.fsf@benfinney.id.au> Message-ID: <873amddh0n.fsf@benfinney.id.au> Roy Smith writes: > Ben Finney wrote: > > > If you are passing a sequence conceptually, then it's more Pythonic to > > pass it as a sequence explicitly:: > > > > def __init__(self, items): > > """ Call with e.g. Stack(["foo", "bar"]) """ > > self.stack = list(items) > > I don't get this. You're forcing a copy to be made of the list. The 'items' object might not be a list; it might be some other sequence. The rest of the class (as shown by the original poster) requires it to be a list. > This changes the semantics of the original class, because the > operations no longer change the original list. Which "original class" are you referring to? The one posted by the original poster of this thread had no "original list"; it gathered the positional arguments (using '*items') into an 'items' parameter, which *doesn't exist* until the function body executes. There *is* no "original list" in that implementation posed by the original poster; it's constructed at call time from the positional parameters to the function. If anything, my implementation above *preserves* that semantic, by making a new list from the passed-in sequence. -- \ ?Consider the daffodil. And while you're doing that, I'll be | `\ over here, looking through your stuff.? ?Jack Handey | _o__) | Ben Finney From max at alcyone.com Thu Jul 31 01:43:21 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Jul 2008 22:43:21 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > On Jul 30, 9:27 pm, Erik Max Francis wrote: >> You're sure going on about a distinction without a difference for a guy >> who childishly likes to call other people names. A reasonable person >> would have long ago moved on instead of blaming others for not >> immediately intuiting your thoughts, rather than straightforwardly >> reading your words. Which, by the way, includes at least three people >> other than myself. >> >> But I'll bet the mindless namecalling is really working out for you. >> Go, team, go! > > You earned the "childish name calling" by acting like a child -- with > your petty little game of trying to show that I don't understand a > basic concept in Python. As I said, your initial misunderstanding, > while silly, was at least forgivable. But your insistence on repeating > it time after time is not. It is truly pathetic. Sis, boom, rah rah rah! You're kind of skipping over the point where three other people had the same misunderstanding about your original statement and correction, so maybe the reader is not the problem but rather the writer, but hey, don't let that get in the way of a good public shitfit. You're winning! -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis I am not a Virginian, but an American. -- Patrick Henry From sunp1028 at gmail.com Sun Jul 13 08:16:46 2008 From: sunp1028 at gmail.com (patrol) Date: Sun, 13 Jul 2008 05:16:46 -0700 (PDT) Subject: About wmi Message-ID: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> I want to prevent some process from running. The code is in the following. I encounter some unexpected troubles. Probelm1: This program cannot terminate "scrcons.exe" and "FNPLicensingService.exe",which are system processes. Problem2:After a while, this program will abort by error File "C:\Python25\lib\wmi.py", line 397, in __call__ handle_com_error (error_info) File "C:\Python25\lib\wmi.py", line 190, in handle_com_error raise x_wmi, "\n".join (exception_string) UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 14: ordinal not in range(128) ---------------------------------------------------- code---------------------------------------------------------------------------------- # -*- coding:utf-8 -*- import pythoncom import wmi import threading import time from xml.dom.minidom import parse, parseString class Info (threading.Thread): def __init__ (self): threading.Thread.__init__ (self) def run (self): print 'In Another Thread...' pythoncom.CoInitialize () dom1 = parse('processTerminateList.xml') config_element = dom1.getElementsByTagName("processTerminateList") [0] servers = config_element.getElementsByTagName("processName") try: c = wmi.WMI () for process in c.Win32_Process (): for server in servers: if process.name == getText(server.childNodes): process.Terminate() print process.name process_watcher = c.Win32_Process.watch_for("creation") while True: new_process = process_watcher() name = new_process.Caption print name for server in servers: if name == getText(server.childNodes): new_process.Terminate() finally: pythoncom.CoUninitialize () def getText(nodelist): rc = "" for node in nodelist: if node.nodeType == node.TEXT_NODE: rc = rc + node.data return rc if __name__ == '__main__': Info().start() ------------------------------------------------------ processTerminateList.xml----------------------------------------------------------------------- scrcons.exe TXPlatform.exe mdm.exe FNPLicensingService.exe notepad.exe uedit32.exe From Lie.1296 at gmail.com Sat Jul 26 01:15:04 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 25 Jul 2008 22:15:04 -0700 (PDT) Subject: xml.dom's weirdness? Message-ID: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> Why this generates AttributeError, then not? Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import xml >>> xml.dom Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'dom' >>> xml.dom >>> From sjmachin at lexicon.net Tue Jul 15 20:19:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 15 Jul 2008 17:19:35 -0700 (PDT) Subject: How to figure out if the platform is 32bit or 64bit? References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: On Jul 16, 6:10 am, kjhish... at gmail.com wrote: > I need to know if I'm running on 32bit or 64bit ... so far I haven't > come up with how to get this info via python. sys.platform returns > what python was built on ... but not what the current system is. > > I thought platform.uname() or just platform.processor() would have > done it, but python returns an empty string on windows. Any ideas? > >>> import sys >>> hex(sys.maxint) '0x7fffffff' >>> x = sys.maxint >>> n = 1 >>> while x: ... n += 1 ... x >>= 1 ... >>> n 32 WARNING: Assumes nobody will be silly enough to build a machine with ones-complement integers in future :-) From WookieTim at gmail.com Sun Jul 6 09:18:57 2008 From: WookieTim at gmail.com (furby) Date: Sun, 6 Jul 2008 06:18:57 -0700 (PDT) Subject: Hi there! I need what is probably a very basic lesson in events.... Message-ID: <4d5a5286-f4cf-480e-9432-b4b337f7c145@x35g2000hsb.googlegroups.com> I am teaching myself Python... I'm nowhere near even intermediate level yet, so treat me like an idiot. I am using Boa Constructor on Ubuntu 8.04 if that helps. Here is what I have right now : I am plying with reading a URL (An RSS feed to be exact) and displaying it inside a HTMLWindow. I have that part working - It shows the title as a link and displays the description next to it. What I want to do is trap the mouseclick on the link and use that to grab just the text that is on the site. Right now, if I click on it, the HTML window control takes me to the site and doesn't really show the site very well, since it doesn't seem to do CSS. That's okay - I just want to display the text.... How do I trap the mouse clicking on the link? I know that HTMLwindow has a "OnLinkClicked" event - I can see it in the docs for that control. But it seems that Boa Constructor doesn't expose that event in it's frame designer.... How do I code a event that fires off instead of the default event? I don't know if I am being clear enough, so if not just tell me what I should say... Liek I said, I am a newbie right now. From Robert.Bossy at jouy.inra.fr Thu Jul 17 10:39:07 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Thu, 17 Jul 2008 16:39:07 +0200 Subject: % sign in python? In-Reply-To: References: Message-ID: <487F598B.9040208@jouy.inra.fr> korean_dave wrote: > What does this operator do? Specifically in this context > > test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) > > (Tried googling and searching, but the "%" gets interpreted as an > operation and distorts the search results) > It's the string formatting operator: http://docs.python.org/lib/typesseq-strings.html Btw, a good place to start searching would be: http://docs.python.org/lib/lib.html especially: http://docs.python.org/lib/genindex.html Cheers RB From norseman at hughes.net Thu Jul 10 17:44:32 2008 From: norseman at hughes.net (norseman) Date: Thu, 10 Jul 2008 14:44:32 -0700 Subject: Terminate a python script from linux shell / bash script In-Reply-To: References: Message-ID: <487682C0.70905@hughes.net> Gros Bedo wrote: > >>> That's not how it works. If you kill one running python script it will not >>> effect other python scripts. Each script has its own interpreter process >>> running. > >> GB> So, is there a way from the Linux shell or a bash script to terminate >> GB> just one specific Python script ? > >>> So just kill it. > > Yes I've seen that each python script calls its own instance of Python. But how to know which is the good one in bash ? Is there a command that gets the parameters of process, so I could use grep to select the one containing the name of my script ? > _________________________________________________________________ > Votre contact a choisi Hotmail, l'e-mail nouvelle g?n?ration. Cr?ez un compte. > http://www.windowslive.fr/hotmail/default.asp > -- > http://mail.python.org/mailman/listinfo/python-list > ============================== Yes. man ps explains try ps -AFL | grep [known filename or cmdlin token] then kill -9 [PID] found (check it more than twice) 1) If your script is known to hang use what another wrote: py s.py tokens & capture=$! (get the PID ready) kill -9 $capture 2) If you are like the other 99% needing the PID because we didn't know we were going to need it, use the ps/grep combo. Try not to damage your system. Which means: Trying to automate this is VERY dangerous! How long since your last full backup? And of course you can redo everything since last backup from memory, yes? It hangs, you kill it manually. Steve norseman at hughes.net From code at pizzashack.org Sun Jul 27 15:34:16 2008 From: code at pizzashack.org (Derek Martin) Date: Sun, 27 Jul 2008 15:34:16 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <009c29cc$0$20302$c3e8da3@news.astraweb.com> References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c29cc$0$20302$c3e8da3@news.astraweb.com> Message-ID: <20080727193416.GE7373@dragontoe.org> On Sun, Jul 27, 2008 at 08:13:53AM +0000, Steven D'Aprano wrote: > On Sun, 27 Jul 2008 10:23:06 +0800, Marcus.CM wrote: > > > Well after reading some of these posts on "sacred python cow" on the > > "self" , i would generally feel that most programmers who started with > > C++/Java would find it odd. > > You know, there are some programmers who haven't started with C++ or Java. Indeed, I'm one of them. In fact, I've never written even a single program in either language (except maybe hello world or the equivalent), and still, I have always thought that explicitly naming the class instance variable in the parameter list of the object's methods was a wart (albeit a very minor one) in Python. It's a waste of typing. > > And its true, i agree completely there should not be a need to put > > "self" into every single member function. If you were writing an > > application and one of your classes adds the same variable to each > > of its member function you would do away with it too. > > Would I? How would I do that here? You missed the point. The variable "other" in your posted class is not intended to always refer to the same *object*... Whereas "self" is and does, and that was what was meant. In such a case, you'd obviously convert the variable to a class property. Regardless of how it's implementd, it's such a common idiom to use self to refer to object instances within a class in Python that it ought to be more automatic. Personally, I kind of like the idea of using @ and thinking of it more like an operator... Kind of like dereferencing a pointer, only with an implied pointer name. class foo: def __init__(): @.increment = 2 def bar(a) return a + @.increment I'm sure all the Pythonistas will hate this idea though... ;-) To be honest, it smacks a little of Perl's magic variables, which I actually hate with a passion. This is the only place in Python I'd consider doing something like this. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From stef.mientki at gmail.com Mon Jul 7 18:47:01 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 08 Jul 2008 00:47:01 +0200 Subject: sage vs enthought for sci computing In-Reply-To: <677e7819-e09e-43d3-8368-5864f91002be@34g2000hsh.googlegroups.com> References: <677e7819-e09e-43d3-8368-5864f91002be@34g2000hsh.googlegroups.com> Message-ID: <48729CE5.3080704@gmail.com> jadamwilson2 at gmail.com wrote: > Hello, > I have recently become interested in using python for scientific > computing, and came across both sage and enthought. I am curious if > anyone can tell me what the differences are between the two, since > there seems to be a lot of overlap (from what I have seen). If my goal > is to replace matlab (we do signal processing and stats on > physiological data, with a lot of visualization), would sage or > enthought get me going quicker? I realize that this is a pretty vague > question, and I can probably accomplish the same with either, but what > would lead me to choose one over the other? > Scipy or the new x-y distro is almost identical like MatLab ( but you'll miss the var browser), and therefor get started faster. I've the same kind of applications and support medical researchers with collecting and analyzing physio data. About 2 years ago I wasn't satisfied with MatLab anymore, so I looked at LabView, SciLab, Octave and a few others, and decided to stay with Matlab, but embed it in my own shell. Worked with that for about half a year, then I tried Scipy (also embedded) and found it much better than MatLab. At the moment I switched totally to Python, and I'm working on a Labview like environment for Python. hopes that helps, cheers, Stef > Thanks! > -- > http://mail.python.org/mailman/listinfo/python-list > From dullrich at sprynet.com Mon Jul 7 17:23:43 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 07 Jul 2008 16:23:43 -0500 Subject: "in"consistency? Message-ID: Luckily I tried it before saying no, that's not how "in" works: >>> 'ab' in 'abc' True >>> [1,2] in [1,2,3] False Is there a reason for the inconsistency? I would have thought "in" would check for elements of a sequence, regardless of what sort of sequence it was... -- David C. Ullrich From fredrik at pythonware.com Mon Jul 21 06:16:57 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 12:16:57 +0200 Subject: calling source command within python In-Reply-To: References: Message-ID: Jie wrote: > i'm having trouble executing os.system('source .bashrc') command > within python, it always says that source not found and stuff. Any > clue? like in $ python >>> import os >>> os.system("source .bashrc") sh: source not found and stuff 256 ? I get $ python >>> import os >>> os.system("source .bashrc") /... stuff printed by my .bashrc file .../ 0 What happens if you do >>> import os >>> os.system("bash .bashrc") instead? From RonV at Nospam.com Thu Jul 10 20:04:27 2008 From: RonV at Nospam.com (RV) Date: Thu, 10 Jul 2008 20:04:27 -0400 Subject: Can anyone suggest a date peocedure... References: Message-ID: On Thu, 10 Jul 2008 13:39:29 -0700, Gary Herron wrote: >The datetime module has what you need. > >It has methods (with examples) on building a datetime object from a >string, and it has a object named timedelta, and the ability to subtract >a timedelta from a time. > >For instance, the time right now and the time exactly one day ago: > > >>> from datetime import * > >>> datetime.today() >datetime.datetime(2008, 7, 10, 13, 38, 48, 279539) > >>> datetime.today()-timedelta(1) >datetime.datetime(2008, 7, 9, 13, 38, 50, 939580) > > >Gary Herron Thanks Gary! This works great. Now all I need to know is how to plug the date into the datetime object from a string. Ron From deets at nospam.web.de Thu Jul 31 10:33:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 16:33:38 +0200 Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> Message-ID: <6fe0scFaus40U1@mid.uni-berlin.de> squishywaffle at gmail.com wrote: >> Ctypes is a since python2.5 built-in module that allows to declare >> interfaces to C-libraries in pure python. You declare datatypes and >> function prototypes, load a DLL/SO and then happily work with it. No C, >> no compiler, no refcounts, no nothing. >> >> And you can pass python-functions as callbacks. > > The first sentence (and some really crummy licensing restrictions > imposed by the library distributor) alone here excludes this as a > valid option for this particular case, I definitely need Python 2.4 > support. How much more liberal can it get than MIT-licensed? """ to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: """ But then, if you insist, go down the hard road. Diez From max at alcyone.com Wed Jul 30 04:07:10 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Jul 2008 01:07:10 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> Message-ID: Russ P. wrote: > Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > __nonzero__ work in Python. It's very basic stuff. You can quit > patronizing me (and Carl too, I'm sure). You suggested a syntax for testing non-emptiness (`x is not empty`) which indicated a profound misunderstanding of what the `is` operator does. You then acknowledged that there might be a problem because of the implication if the `is` operator and weren't sure whether it would work or not: | But I guess that could only work if there were only one empty list | that represents all empty lists (as there is only one actual "None"). | I don't know if that makes sense or not. This ends with you still sounding confused about what the operator does, because that can't make sense if you take into account the meaning of the `is` operator (surely not all empty lists are the same object) and polymorphism (not all empty containers are empty lists). Hey, everybody goofs. But pointing figures here doesn't help, since it's not unreasonable to assume that someone who says something clearly misunderstanding a feature of the language, and followups to responses _continuing to be confused about it_, is, in fact, confused. The only reason anyone thought you were confused was by your bizarre suggestion about the `empty` syntax and then your confused responses afterwards. Maybe chalk it up to experience and move on? > The point that you seem to be missing, or refuse to acknowledge for > some reason, is that "if x" can be mistakenly applied to any object > when the programmer thinks that x is a list -- and the programmer will > receive no feedback on the error. > > I have made errors like that, and I could have saved some time had I > used an "empty" method that only applies to a list or other sequence. Well, that's what you get when you use a dynamic language. There are times when `x + y` doesn't mean numeric addition, or in fact anything like it. Or `x % y` where it _really_ doesn't mean anything like the modulus operator. In dynamic languages, the effect of operations depend on their types. There's really no way around that, and Boolean testing if an object as in `if x: ...` is no different. It means different things depending on what `x` is. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The actor is not quite a human being -- but then, who is? -- George Sanders From asmodai at in-nomine.org Thu Jul 10 03:43:22 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 10 Jul 2008 09:43:22 +0200 Subject: Fwd: [ANN] Genshi 0.5.1 released Message-ID: <20080710074322.GO68329@nexus.in-nomine.org> We have put up eggs for various operating systems as well. ----- Forwarded message from Christopher Lenz ----- From: Christopher Lenz To: genshi at googlegroups.com Subject: [ANN] Genshi 0.5.1 released Date: Wed, 9 Jul 2008 21:44:11 +0200 X-Mailer: Apple Mail (2.926) Genshi 0.5.1 - Jul 9, 2008 ========================== We're proud to present the latest release of the Genshi: 0.5.1. Genshi is a Python library that provides an integrated set of components for parsing, generating, and processing HTML, XML or other textual content for output generation on the web. The major feature is a template language. This release contains a number of important bug fixes over the 0.5 release. You can download the new release here: Please don't hesitate to report any issues you may find with this release: For questions, comments and user discussions, please use the Genshi mailing list: What's New: ----------- * Fix problem with nested match templates not being applied when buffering on the outer `py:match` is disabled. Thanks to Erik Bray for reporting the problem and providing a test case! * Fix problem in `Translator` filter that would cause the translation of text nodes to fail if the translation function returned an object that was not directly a string, but rather something like an instance of the `LazyProxy` class in Babel (ticket #145). * Fix problem with match templates incorrectly being applied multiple times. * Includes from templates loaded via an absolute path now include the correct file in nested directories as long if no search path has been configured (ticket #240). * Unbuffered match templates could result in parts of the matched content being included in the output if the match template didn't actually consume it via one or more calls to the `select()` function (ticket #243). Acknowledgments ---------------- A big thank you to everyone who tried Genshi and provided feedback, reported bugs, and/or contributed patches! Cheers, -- Christopher Lenz cmlenz at gmx.de http://www.cmlenz.net/ ----- End forwarded message ----- -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Time is a twofold teacher, harsh and yet patient like no-one... From Jie.Bao at gmail.com Mon Jul 21 06:03:58 2008 From: Jie.Bao at gmail.com (Jie) Date: Mon, 21 Jul 2008 03:03:58 -0700 (PDT) Subject: calling source command within python Message-ID: Hi all, i'm having trouble executing os.system('source .bashrc') command within python, it always says that source not found and stuff. Any clue? Thanks, Jie From phillip.oldham at gmail.com Wed Jul 30 11:15:07 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Wed, 30 Jul 2008 08:15:07 -0700 (PDT) Subject: Standard module for parsing emails? References: <6fb93eFap7j5U1@mid.individual.net> Message-ID: If there isn't a standard library for parsing emails, is there one for connecting to a pop/imap resource and reading the mailbox? From kyosohma at gmail.com Thu Jul 3 12:27:38 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 3 Jul 2008 09:27:38 -0700 (PDT) Subject: distutils - setup - lib problem References: <6138c75a-601e-4c44-b765-364cadb16098@l64g2000hse.googlegroups.com> Message-ID: <33f8ff1e-6643-4880-9a25-ec3617c4d750@25g2000hsx.googlegroups.com> On Jul 2, 3:38?am, rocksportrocker wrote: > Hi, > > I've got some problems with the following setup.py file. > using "python setup.py install -f" it shows that wrap_ica.so is copied > to /usr and not to ..../site-packages as I assumed. > What am I doing wrong ? I'm using Python 2.4 on Debian Linux. > > ----------------------------------------------------- > > from distutils.core import setup > import glob > > setup(name='py_ica', > ? ? ? py_modules=['py_ica'], > ? ? ? data_files=[(".", ["wrap_ica.so"]), > ? ? ? ? ? ? ? ? ?] > ? ? ? ) > ----------------------------------------------------- > > Greetings, Uwe Try the distutils group. They'd probably be a little more helpful: http://mail.python.org/mailman/listinfo/distutils-sig Mike From bignose+hates-spam at benfinney.id.au Fri Jul 11 04:49:23 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 11 Jul 2008 18:49:23 +1000 Subject: Trying to learn References: Message-ID: <8763rcrejw.fsf@benfinney.id.au> luster123 writes: > Can someone please teach me the basics of Python and Pygame? Yes, you can do it. -- \ ?Too many pieces of music finish too long after the end.? ?Igor | `\ Stravinskey | _o__) | Ben Finney From jonas.esp at googlemail.com Mon Jul 14 08:04:54 2008 From: jonas.esp at googlemail.com (Kless) Date: Mon, 14 Jul 2008 05:04:54 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> <792048c1-5e18-4a2c-925d-a1c932d18a91@j22g2000hsf.googlegroups.com> <8923d0c5-29ce-495f-924a-6d9d2457138e@e39g2000hsf.googlegroups.com> <8933b108-45b4-438d-87d8-aad92a15188b@e53g2000hsa.googlegroups.com> Message-ID: Akathorn Greyhat sent me by email the next solution, which althought isn't generic it works well: ------------- You could make your own class for that, maybe something like ######### class MyCoolDictionary(dict): def __init__(self, *args, **kargs): dict.__init__(self, *args, **kargs) def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: keys=[] for i in dictio.keys(): if dictio[i]==item: keys.append(i) return keys dictio=MyCoolDictionary({"a" : 1, "b" : 2, "c" : 2}) print dictio["a"] print dictio["b"] print dictio[1] print dictio[2] ######### The output of this code is: 1 2 ['a'] ['c', 'b'] Note that it isn't finish, maybe you'll need to make some kind of test before adding a new value because with this code one value can have multiple keys, and I have fixed it by returning a list of keys instead a single value. It's up to you =) I'm sorry of my poor english =( Regards, Akathorn Greyhat ------------- From subhabrata.iisc at hotmail.com Fri Jul 18 06:00:41 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Fri, 18 Jul 2008 03:00:41 -0700 (PDT) Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> <6eb733F67cpfU2@mid.uni-berlin.de> Message-ID: <32a81d0c-a74f-4b22-8add-15beb2643529@h17g2000prg.googlegroups.com> Sorry if I didn't say that. The input is a string "Petrol Helium Heaven Sky" Now, in a3 it is "God Goddess Heaven Sky" is there, it is matching Heaven and Sky but not Petrol and Helium as they are not in a3. Now, as per the code it is giving me an output "S" of "Sky" and "Helium" But I was looking for an output of "H S Petrol Helium" and not "S Helium" meaning all the values of a5 and a6 will be concatenated in s. Best Regards, Subhabrata.. Marc 'BlackJack' Rintsch wrote: > On Fri, 18 Jul 2008 01:31:59 -0700, SUBHABRATA wrote: > > > def try2(n): > > a1=raw_input("PRINT A STRING:") > > a2=a1.split() > > a3="God Godess Heaven Sky" > > for x in a2: > > a4=a3.find(x) > > if a4>-1: > > a5=a3[a4] > > print a5 > > elif a4<0: > > a6=x > > print "It is not found" > > print a6 > > else: > > print "Error" > > s=a5+" "+a6 > > print s > > > > Here, if I put a string like: > > Petrol Helium Heaven Sky > > In s it is giving me S Helium > > But I am looking for an output of a5 and a6 concatenating all its > > values not the last ones. Can you suggest me any help? Am I missing > > any minor point? > > Maybe you should describe what the input looks like and what output you > want to have and how the input and output are connected. In words, not in > not very clear code with "numbered names". That's a silly idea and makes > understanding the code very hard. Please use meaningful names! > > Ciao, > Marc 'BlackJack' Rintsch From mail at timgolden.me.uk Tue Jul 15 12:35:40 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Jul 2008 17:35:40 +0100 Subject: Zipping files In-Reply-To: <9400be29-9c00-4868-91a9-ae82ebfc6364@56g2000hsm.googlegroups.com> References: <9400be29-9c00-4868-91a9-ae82ebfc6364@56g2000hsm.googlegroups.com> Message-ID: <487CD1DC.3050907@timgolden.me.uk> dp_pearce wrote: > When I saw "Permission denied", this was my suspicion. And I think you > are very right. I have just gone back and tried writing to a file > outside of C:, in this case C:/output/, and it seems to work again. > > Would I be right in guessing there is no way around this? Well, you could (presumably) alter your own user's groups / rights and/or the permissions on the root of the C: drive so that you *can* zip to that location. On the other hand, chucking random stuff into the root of the system drive has never been considered a brilliant idea. (Altho' I know a lot of people who do it :) ). Why not create a suitable folder lower down, or in your own %APPDATA% area, or using the tempfile module, depending on your needs? TJG From ethan at stoneleaf.us Tue Jul 15 12:56:59 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 15 Jul 2008 08:56:59 -0800 Subject: Measure class, precision, significant digits, and divmod() Message-ID: <487CD6DB.60500@stoneleaf.us> Hey all. My thanks to all who have responded so far with my other questions. It is much appreciated. Some background on what I'm doing (a good explanation can be found at http://www.hazelwood.k12.mo.us/~grichert/sciweb/phys8.htm): When measuring, there is some uncertainty as to the *exact* value; so, when doing calculations with these measured numbers, one should not present an answer that seems more accurate than the source. For addition and subtraction this means the final answer cannot be more precise than the least precise input: 5.0 + 21.23 = 26.2 (first number only measured to the tenths, so answer only good to the tenths); for multiplication and division this means the answer cannot have more significant digits than the input with the fewest significant digits: 231 * 0.25 = 58 (0.25 only has two significant digits, so answer only has two significant digits). Important point -- counting is not subject to precision error. As I have mentioned before, I am making this Measure class for two reasons: experience with unit testing, I like playing with numbers, I am unaware of anything like this having yet been done (okay, three reasons ;). So far, I have the init, add, sub, mul, div, cmp, neg, pos, and abs done, and I'm ready to tackle floordiv, mod, and divmod... okay, maybe 'ready' is too strong a word -- one of the obstacle's I'm facing is that I, myself, don't have any real use for this class, so I'm stuck on deciding how floordiv, mod, and divmod should function. As mentioned above, counting is precise... so should divmod (a // b, a % b), which returns the count of times b goes into a, and the remainder, be an exact number, or should it behave like floor(a / b), and preserve the inherent inaccury present in the measured value a? Should I have floordiv preserve inaccuracy, and divmod be exact? Any and all feedback welcome, particularly from anyone who might actually use the Measure class. ;) ~Ethan From tjreedy at udel.edu Wed Jul 23 18:31:11 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 23 Jul 2008 18:31:11 -0400 Subject: Segv in mmap.move() In-Reply-To: References: Message-ID: magnus.lycka at gmail.com wrote: > Does anyone recognize this little Python crasher? > > I'll file a bug report unless someone notices it as an already > documented bug. I found some open mmap bugs, but it wasn't > obvious to me that this problem was one of those... > > Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import mmap >>>> data = mmap.mmap(-1, 1) >>>> data.move(1,1,-1) > Segmenteringsfel (core dumped) > > I first noticed the problem under Windows in 2.5.1. On WinXP Py3.0b2, I see two bugs here. 1. For a length 1 sequence, the only offsets allowed should be 0. However, I can index to what I suspect is a null terminator byte at offset len(seq). This should be internally accessible only just as for regular strings and bytes (which also have null terminators, I believe). Indexing any farther past what should be the end gives the IndexError I expected when indexing just past the end. (Slicing and iterating, however, work correctly.) >>> import mmap >>> d=mmap.mmap(-1,5) >>> d[:]=b'abcde' >>> d[0], d[4],d[5] (97, 101, 0) 2. Running your code, or d.move(1,2,-1), I get python.exe 'encountered a problem ...shutting down ... Send report?' (yes) and window closed. Running IDLE, same msg, but after send report, IDLE shell restarted. Cute. Modules/mmapmodule.c - mmap_move_method declares count as unsigned. Further experimentation shows that the problem is telling it to move exactly -1 bytes, which I am sure gets translated to 2**32-1 = 4294967295 by PyArg_ParseTuple(args, "kkk:move", &dest, &src, &count) Passing 2**32-1 also crashes, while 2*32-2 and other bad values give >>> d.move(1,2,2**32-2) Traceback (most recent call last): File "", line 1, in d.move(1,2,2**32-2) ValueError: source or destination out of range I suspect the 2**32-1 bug is in C memmove, perhap inherited from a common source. I think either a)the docs should warn that a count of -1== 4294967295 (on 32bit machines) and just that may crash the interpreter or b) the wrapper of the underlying C function should raise ValueError for -1 also. The goal of 'no crashes' suggests the latter if sensibly possible. Terry Jan Reedy From semanticist at gmail.com Wed Jul 30 17:55:10 2008 From: semanticist at gmail.com (Miles) Date: Wed, 30 Jul 2008 17:55:10 -0400 Subject: how to split text into lines? In-Reply-To: References: Message-ID: On Wed, Jul 30, 2008 at 4:45 PM, kj wrote: >>What's the Python idiom for splitting text into lines, preserving >>the end-of-line sequence in each line? > > > Sorry, I should have googled this first. I just found splitlines()... > > Still, for my own edification, is there a way to achieve the same > effect using re.split? Not directly: re.split doesn't split on zero-length matches. http://mail.python.org/pipermail/python-dev/2004-August/047272.html http://bugs.python.org/issue852532 http://bugs.python.org/issue988761 http://bugs.python.org/issue3262 -Miles From grante at visi.com Mon Jul 21 11:04:40 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 21 Jul 2008 10:04:40 -0500 Subject: ntlm authentication References: <7B3D44209E8C944288889D4132FEC4125B98D8@IMCSRV6.MITRE.ORG> Message-ID: On 2008-07-21, Tim Golden wrote: > Neuberger, Sheldon N. wrote: >> Is there any way to make urllib2 handle NTLM authentication? > > Frankly, I'd hate to try. Have a look at this: > > http://sourceforge.net/projects/ntlmaps/ Here's a library that can be used to handle the NTLM authentication stuff: http://josefsson.org/libntlm/ There's no reason you couldn't translate it into Python (or just call it). -- Grant Edwards grante Yow! I wonder if I could at ever get started in the visi.com credit world? From weizhonghua.ati at gmail.com Wed Jul 16 04:29:19 2008 From: weizhonghua.ati at gmail.com (zhw) Date: Wed, 16 Jul 2008 01:29:19 -0700 (PDT) Subject: How can i use a variable without define it ? Message-ID: How can i use a variable without define it ? I have thought about the __import__ function, but the docs says "the __import__() function does not set the local variable named eggs"? From Henning.Thornblad at gmail.com Fri Jul 4 07:43:48 2008 From: Henning.Thornblad at gmail.com (Henning_Thornblad) Date: Fri, 4 Jul 2008 04:43:48 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions Message-ID: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> What can be the cause of the large difference between re.search and grep? This script takes about 5 min to run on my computer: #!/usr/bin/env python import re row="" for a in range(156000): row+="a" print re.search('[^ "=]*/',row) While doing a simple grep: grep '[^ "=]*/' input (input contains 156.000 a in one row) doesn't even take a second. Is this a bug in python? Thanks... Henning Thornblad From malaclypse2 at gmail.com Mon Jul 7 09:54:49 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 7 Jul 2008 09:54:49 -0400 Subject: Confused yet again: Very Newbie Question In-Reply-To: References: Message-ID: <16651e80807070654j12d55802yf3950e2375bbe67d@mail.gmail.com> On Mon, Jul 7, 2008 at 7:30 AM, mcl wrote: > I did not think you had to make the distinction between 'byvar' and > 'byref' as in Basic. Python does not use "call by value" or "call by reference" semantics. Instead, python's model is "call by object". See this writeup for some details: http://effbot.org/zone/call-by-object.htm -- Jerry From motoom at xs4all.nl Wed Jul 23 05:40:10 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Wed, 23 Jul 2008 11:40:10 +0200 Subject: maximum value in a column of file Message-ID: <2.2.32.20080723094010.01275db0@pop.xs4all.nl> Maurizio wrote... > the problem is that i don't know how to put the column of the file in an > array. (i'm new in phyton). Give us an example of how your file looks, and what you want to extract from it, so that we don't have to guess. Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From __peter__ at web.de Fri Jul 18 06:26:44 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 12:26:44 +0200 Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: nicolas.pourcelot at gmail.com wrote: > I think something like >>>> id(myobject) in (id(element) for element in mylist) > would also work, also it's not so readable, and maybe not so fast > (?)... > > An "is in" operator would be nice... And rarely used. Probably even less than the (also missing) < in, | in, you-name-it operators... > So, precisely, you mean that if hash(a) != hash(b), a and b are > considered distinct, and else [ie. if hash(a) == hash(b)], a and b are > the same if and only if a == b ? Correct for set, dict. For lists etc. the hash doesn't matter: >>> class A(object): ... def __hash__(self): ... return nexthash() ... def __eq__(self, other): ... return True ... >>> from itertools import count >>> nexthash = count().next >>> A() in [A() for _ in range(3)] True >>> d = dict.fromkeys([A() for a in range(3)]) >>> d.keys()[0] in d False Peter From snowballz.game at gmail.com Fri Jul 18 22:39:38 2008 From: snowballz.game at gmail.com (Michael Lubker) Date: Fri, 18 Jul 2008 19:39:38 -0700 (PDT) Subject: Any Game Developers here? References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> <4A235BC6-5E46-4402-AF2D-BA3DBC175517@gmail.com> Message-ID: <2a277fdc-e878-4f68-a758-03e22a72cd18@d1g2000hsg.googlegroups.com> I also know about Panda. ~Michael On Jul 18, 6:05?pm, "Michael Lubker" wrote: > I'm interested in general... I know about PyGame and Pyglet, and have > used both. We're currently using Python-Ogre. In the end, I am looking > to find people interested in my project ( seehttp://youtube.com/watch?v=E0QQ9JuclxE), but I also want to find > people experienced with Python in general, not just one library. > (though of course I know that's not too likely) > > Aren't you one of the Escort Wing developers? :) > > Thanks > Michael > > > > On Fri, Jul 18, 2008 at 5:13 PM, Stephen Johnson wrote: > > I use the Pyglet library to make games. You want to look at the pyglet and > > pygame mailing lists, not this one. Use Google. > > In my opinion, PyGame is clunky and Pyglet is elegant, simple, and > > comprehensive. PyGame has more examples available, but Pyglet has great > > documentation and enough examples to answer any questions you might have. > > Both have active communities. > > > -Steve Johnson > > On Jul 18, 2008, at 5:38 PM, Michael Lubker wrote: > > > Any people that use Python as the predominant language for their game > > development here? > > > ~Michael > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > ~ "The world hates change, yet it is the only thing that has brought > progress." ~ Charles Kettering > > http://snowballz.joey101.net From ldo at geek-central.gen.new_zealand Sat Jul 26 19:44:44 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 27 Jul 2008 11:44:44 +1200 Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> <24a548ad-4cb3-410c-89df-21da6ef4220f@j7g2000prm.googlegroups.com> Message-ID: In message <24a548ad-4cb3-410c-89df-21da6ef4220f at j7g2000prm.googlegroups.com>, Matimus wrote: > On Jul 24, 9:32?pm, Lawrence D'Oliveiro central.gen.new_zealand> wrote: > >> In message >> , >> Matimus wrote: >> >> > On Jul 24, 2:54?am, Lawrence D'Oliveiro > > central.gen.new_zealand> wrote: >> >> In message >> >> , >> >> >> Matimus wrote: >> >> > That isn't the standard. With that setup tabs will show up as 4 >> >> > spaces, and still confuse you. >> >> >> Why should that be confusing? The most common tab-stop setting is 4 >> >> columns. >> >> > A tab character is specified as 8 spaces. >> >> Specified by whom? The most common setting these days is 4 columns. > > All argument about specification aside, Python interprets a tab > character as equivalent to 8 spaces. If you are treating tabs as > equivalent to 4 spaces in your python code it will cause > IndentationError exceptions to be raised. I have Emacs configured to show tabs as 4 columns wide, and I've never had such an exception happen in my Python code as a result. From semanticist at gmail.com Sun Jul 13 21:49:11 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 21:49:11 -0400 Subject: socket.connect() hangs in SYN_SENT state. In-Reply-To: References: <804bccb2-42c7-42e9-8f50-7a780d3438fd@j22g2000hsf.googlegroups.com> Message-ID: On Sun, Jul 13, 2008 at 9:31 PM, Miles wrote: > On Sun, Jul 13, 2008 at 8:35 PM, bukzor wrote: >> The problem only manifests about 1 in 20 runs. Below there's code for >> a client that shows the problem 100% of the time. >> >> The two URL's that I seem to be "confused" about point to the same IP. >> Maybe this will make it clear: >> >> PING bukzor.hopto.org (75.61.84.249) 56(84) bytes of data. >> 64 bytes from adsl-75-61-84-249.dsl.pltn13.sbcglobal.net >> (75.61.84.249): icmp_seq=1 ttl=255 time=1.68 ms > > For me, buzkor.hopto.org resolves to 69.65.19.125 Ahhh... "bukzor". Well, that makes sense. Pardon my temporary dyslexia. -Miles From elessar at nienna.org Thu Jul 3 19:11:34 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Thu, 03 Jul 2008 17:11:34 -0600 Subject: Singleton implementation problems In-Reply-To: References: Message-ID: <486D5CA6.6020204@nienna.org> Urizev wrote: > Hi everyone > > I have developed the singleton implementation. However I have found a > strange behaviour when using from different files. The code is > attached. > > Executing main > new MySet object > No singleton instance > New singleton: > <__main__.Singleton instance at 0x2b98be474a70> > new MySet object > There is a singlenton instance > new Member > new MySet object > No singleton instance > New singleton: > > new Member > new MySet object > There is a singlenton instance > new Member > new MySet object > There is a singlenton instance > > I do not know why, but it creates two instances of the singleton. Does > anybody know why? > > Regards > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list I've run into a similar problem. Basically, when you refer to a class from __main__ (i.e., the .py file you're actually running) versus from an imported module, Python doesn't realize they're the same class. Your Singleton implementation is creating one instance for __main__ and one for everything else. I'm sure there's someone around here who can say why Python behaves this way. You should be fine if you can restructure your code so you don't use your Singleton from __main__. In my case, I added a new main.py file. -Matt From mrkafk at gmail.com Tue Jul 1 12:06:47 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Tue, 01 Jul 2008 18:06:47 +0200 Subject: Embedding Python In-Reply-To: <207312b70807010525m3a8e3acdj352a0b3c7d1a4f7d@mail.gmail.com> References: <207312b70807010525m3a8e3acdj352a0b3c7d1a4f7d@mail.gmail.com> Message-ID: Pau Freixes wrote: > If you search this function name into Google you will can found some > examples, use for example PyMarshal_ReadObjectFromString or > PyMarshal_ReadObjectFromFile Rest assured I looked at a lot of code, but none of it was reading in the .pyc file. I had no idea about the 8-byte header in the .pyc file, Carsten was so kind to show it. From http Thu Jul 17 11:19:01 2008 From: http (Paul Rubin) Date: 17 Jul 2008 08:19:01 -0700 Subject: Javascript - Python RSA encryption interoperability References: Message-ID: <7xhcaosfmi.fsf@ruckus.brouhaha.com> Evren Esat Ozkan writes: > I'm trying to encrypt a string with RSA. But it needs to be compitable > with Dave's JavaScript RSA implementation*. What exactly are you trying to do? That Javascript implementation looks like bad news. If you're trying to secure a web page, use SSL, don't mess around with trying to encrypt it with Javascript. From craig.pastro at gmail.com Fri Jul 11 13:08:26 2008 From: craig.pastro at gmail.com (craig75) Date: Fri, 11 Jul 2008 10:08:26 -0700 (PDT) Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> <3ebed664-a6ba-4e30-acc5-f7d5edb25e32@56g2000hsm.googlegroups.com> Message-ID: On Jul 11, 3:36?am, bearophileH... at lycos.com wrote: > James Fassett: > > > # the first Pythonic attempt using comprehensions > > result_list = [x[0] for x in tuple_list] > > > # the final functional way > > [result_list, _] = zip(*tuple_list) > > > I really like how Python allows me to do what I feel is the most > > natural solution (for a seasoned procedural programmer) while allowing > > a satisfying path towards a more functional approach. > > The list comprehension is quite more readable to me, so I suggest you > to use it. It's probably the default way to do it in Python. > > If you want functional code this is another way (I have not tested the > relative performance but it may be quick): > > >>> tuple_list = ( > > ... ? ? ('John', 'Doe'), > ... ? ? ('Mark', 'Mason'), > ... ? ? ('Jeff', 'Stevens'), > ... ? ? ('Bat', 'Man') > ... ? )>>> from operator import itemgetter > >>> map(itemgetter(0), tuple_list) > > ['John', 'Mark', 'Jeff', 'Bat'] > > Bye, > bearophile Functional programmers love pattern matching (which I think makes the code much easier to understand): [x for (x,y) in tuple_list] or map(lambda (x,y):x, tuple_list) From pavlovevidence at gmail.com Sat Jul 26 02:14:15 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 25 Jul 2008 23:14:15 -0700 (PDT) Subject: 2d graphics - what module to use? References: <5519ca3a-bef6-4673-981a-fb327425cfee@w39g2000prb.googlegroups.com> Message-ID: <8d4c2ba8-77e9-45ef-9c60-960e41b68c8b@34g2000hsh.googlegroups.com> On Jul 25, 4:10?am, King wrote: > Use python's default GUI tkinter's drawing functions or you can use > wxPython GUI kit or you can use pyopengl. > If you are only interested to draw sin waves or math functions that > you should give try to matlab atwww.mathworks.com If you're only interested in sine waves you most certainly should not give Matlab a try; even with student pricing it's going to be way expensive for something that simple. For just popping up a window and drawing on it I recommend PyGame. Carl Banks From cwitts at gmail.com Wed Jul 9 09:32:37 2008 From: cwitts at gmail.com (Chris) Date: Wed, 9 Jul 2008 06:32:37 -0700 (PDT) Subject: Returning the positions of a list that are non-zero References: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> Message-ID: On Jul 9, 7:48?am, "Rajanikanth Jammalamadaka" wrote: > Try this: > > >>> li=[0,0,1,2,1,0,0] > >>> li > > [0, 0, 1, 2, 1, 0, 0]>>> [i for i in range(len(li)) if li[i] != 0] > > [2, 3, 4] > > Cheers, > > Raj > > > > On Tue, Jul 8, 2008 at 10:26 PM, Benjamin Goudey wrote: > > I have a very large list of integers representing data needed for a > > histogram that I'm going to plot using pylab. However, most of these > > values (85%-95%) are zero and I would like to remove them to reduce > > the amount of memory I'm using and save time when it comes to plotting > > the data. To do this, I'm trying to find the best way to remove all of > > the zero values and produce a list of indices of where the non-zero > > values used to be. > > > For example, if my original list is [0,0,1,2,1,0,0] I would like to > > produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices > > of where the non-zero values used to be). Removing non-zero values is > > very easy but determining the indicies is where I'm having difficulty. > > > Thanks in advance for any help > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > "For him who has conquered the mind, the mind is the best of friends; > but for one who has failed to do so, his very mind will be the > greatest enemy." > > Rajanikanth Whoops, misread the question li =[0,0,1,2,1,0,0] [(index,data) for index,data in enumerate(li) if data] From circularfunc at gmail.com Thu Jul 3 16:39:07 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 3 Jul 2008 13:39:07 -0700 (PDT) Subject: PIL(Py Image lib), show() not showing picture... References: <84a8f15a-594f-4e02-aa89-b70932eae420@59g2000hsb.googlegroups.com> <486d366d$0$879$ba4acef3@news.orange.fr> Message-ID: On Jul 3, 10:20?pm, "M?ta-MCI \(MVP\)" wrote: > Hi! > > Which OS? ? On Vista, you MUST reconfig the "aper?u images et > t?l?copies" (in french ; sorry, I don't know the english translation). > > @-salutations > > Michel Claveau VISTA. i will try google translate :) From larry.bates at websafe.com` Mon Jul 21 17:33:50 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 16:33:50 -0500 Subject: Trying to solve a python/mechanize "error 500" http error In-Reply-To: References: Message-ID: <46-dnVVwBPBbnRjVnZ2dnUVZ_ojinZ2d@comcast.com> bruce wrote: > i'm getting the following error: > mechanize._response.httperror_seek_wrapper: HTTP Error 500: > > i'm running python 5.1 > and mechanize 0.1.7b > > I have no idea as to what I have to change/modify/include to handle this > issue. The link that I'm testing is at the bottom of the page. When I insert > the link into the browser, I actually get an err page.. so, I suspect that > there is a handler that I should be able to modify/use to handle this > situation... > > Thoughts/Comments will be greatly appreciated... > > Thanks > > > the output is: > > www = www.1800ink.com > url2= http://www.quantcast.com/www.1800ink.com/traffic > Traceback (most recent call last): > File "./reseller_scrape_child.py", line 288, in > q1 = shopfuncs.quant(rhref) > File "/adkiller/shopfuncs.py", line 56, in quant > br.open(url2) > File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 203, in > open > File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 254, in > _mech_open > mechanize._response.httperror_seek_wrapper: HTTP Error 500: > [root at toshiba adkiller]# ./reseller_scrape_child.py > > > > my code segment looks like: > ==================================== > from mechanize import Browser > import mechanize > br = Browser() > user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' > values1 = {'name' : 'Michael Foord', > 'location' : 'Northampton', > 'language' : 'Python' } > headers = { 'User-Agent' : user_agent } > > #br.set_cookiejar(cj) > br.set_handle_redirect(True) > br.set_handle_referer(True) > br.set_handle_robots(False) > br.addheaders = [('User-Agent', 'Firefox')] > > url2 ="http://www.quantcast.com/xxxx/traffic" > #gets the page (url) from the quantcast app > url2=url2.replace("xxxx",url) > print "url2=",url2 > br.open(url2) > > ======================================= > > this works ok for most of the sites.. but something weird is happening with > the actual page: > http://www.quantcast.com/www.1800ink.com/traffic > > > thanks... > > > Looking up 500 error (here http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) gives me: 10.5.1 500 Internal Server Error The server encountered an unexpected condition which prevented it from fulfilling the request. On some servers (Amazon), when you get 500 errors you are instructed to try the request again. I don't know about this server. -Larry From thomas.bugzilla at gmx.net Wed Jul 9 10:25:23 2008 From: thomas.bugzilla at gmx.net (Thomas) Date: Wed, 09 Jul 2008 16:25:23 +0200 Subject: Relative Package Import In-Reply-To: References: Message-ID: Robert Hancock wrote: > mypackage/ > __init__.py > push/ > __init__.py > dest.py > feed/ > __init__py > subject.py > > In subject.py I have > from ..push import dest There is no such thing as relative package imports. See http://www.python.org/doc/essays/packages.html Thomas > > But i receive the error: > Caught exception importing module subject: > File "/usr/local/python/lib/python2.5/site-packages/pychecker/ > checker.py", line 621, in setupMainCode() > module = imp.load_module(self.moduleName, file, filename, smt) > File "subject.py", line 1, in () > from ..feed import dest > ValueError: Attempted relative import in non-package > > What am I missing? > > > From tjreedy at udel.edu Thu Jul 10 14:09:16 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jul 2008 14:09:16 -0400 Subject: Weird lambda rebinding/reassignment without me doing it In-Reply-To: References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: David C. Ullrich wrote: > In article > <02ff4326-7b07-4ae6-8607-f58ea61802ef at z72g2000hsb.googlegroups.com>, > ssecorp wrote: > >> I am never redefining the or reassigning the list when using validate >> but since it spits the modified list back out that somehow means that >> the modified list is part of the environment and not the old one. >> i thought what happend inside a function stays inside a function >> meaning what comes out is independent of what comes in. >> Meaning if I want the list I send as a parameter to the function I >> have to do x = func(x) and not just func(x) and x is magically what >> comes out of func(). > > A function cannot modify the value of a global variable Yes it can. >>> a=[] >>> def f(): a.append('yes I can') >>> f() >>> a ['yes I can'] > (unless it specifies "global"). It doesn't reassign anything. The statement 'global a' would allow f to *rebind* the global *name* 'a'. The word 'variable' should almost not be used in discussing Python since it is often unclear whether it refers to a name (or collection slot) or an object bound thereto. > But in the functions below you're not reassigning a variable, > you're _modifiying_ an object. A function _can_ modify an > object you pass to it: It can modify any mutable object it can access. >> Doesnt Python have closure or that isnt what this is about? Python does have closures. This is not about that. >> def validate(placed): >> student = round(random.random()*401) >> if student in placed: >> return validate(placed) >> else: >> placed.append(student) >> return student, placed Delete this. It is redundant with the below. >> def val(placed): >> student = round(random.random()*401) >> if student in placed: >> return validate(placed) >> else: >> placed.append(student) >> return student I believe this is equivalent to def addval(placed): while True: student = round(random.random()*401) if student not in placed: break placed.append(student) return student While this avoids the indefinite recursion depth problem, it does not avoid the indefinite time problem. Use random.shuffle, or write your own version if doing this for practice. Also consider removing the return statement unless you actually directly use the added value. It is easier to remember that addval mutates 'placed' without the return. >>>>> g = lambda x:validate(x) This is doubly diseased. First, never write a 'name = lambda...' statement since it is equivalent to a def statement except that the resulting function object lacks a proper .funcname attribute. The above only trivially abbreviates def g(x): return validate(x) by 3 characters. Another reason is that the lambda form somehow more often tricks people into the next mistake . Second, never write a function (with either def or lambda) that simply returns a function of the argument(s). The wrapping does nothing! This is a waste of time and space for both you and the interpreter. The above is functionally equivalent to g = validate and if you want that, you could name the function 'g' when you define it. >>>>> l=[] In some fonts, 'l' and '1' are nearly identical; please use something else for public code, which you made this to be by posting it;-) >>>>> for x in range(1,10): >> g(l) As said, the 'g' wrapper is useless. addval(l) Hope this helps. Terry Jan Reedy From code at pizzashack.org Fri Jul 18 19:14:43 2008 From: code at pizzashack.org (Derek Martin) Date: Fri, 18 Jul 2008 19:14:43 -0400 Subject: Change PC to Win or Windows In-Reply-To: References: Message-ID: <20080718231443.GB3043@dragontoe.org> On Fri, Jul 18, 2008 at 03:46:13PM -0700, Joel Teichroeb wrote: > Calling Windows PC seems to be something that Apple did so they would > not have to directly mention Windows. Actually it's something IBM did when they created the IBM PC. Of course, all IBM PCs ran MS-DOS, since that's how IBM sold them... Then others started to build copies the IBM PC based on Intel hardware, and the resulting class of computers was called, collectively, "PC Clones" -- shortened to PCs -- by the industry and its market. Then companies like AMD and Cyrix started building Intel-compatible CPUs, and the term PC was extended to include systems built using those architectures. Eventually Windows was released, and PCs became Windows boxen running on Intel-compatible hardware, and I personally know no one who doesn't use the term that way... Much like the English word "bank" (and numerous others), the term "PC" has come to have several meanings, one of which is the above. You may not like it, but we're pretty much stuck with the term, so you may as well get used to it. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From animator333 at gmail.com Fri Jul 25 01:33:01 2008 From: animator333 at gmail.com (King) Date: Thu, 24 Jul 2008 22:33:01 -0700 (PDT) Subject: object persistency, store instances relationship externally Message-ID: <3183af12-4b1e-4bd1-8d21-b9fc2b421008@v1g2000pra.googlegroups.com> This is a new test for object persistency. I am trying to store the relationship between instances externally. It's not working as expected. May be I am doing it in wrong way. Any suggestions? import shelve class attrib(object): pass class node(object): def __init__(self): self.a = attrib() self.b = attrib() self.c = attrib() self.d = attrib() a = node() #store pair relationship. This relationship is created at run time. lst = [[a.a, a.b], [a.c, a.d]] #Write objects into file shelf = shelve.open('shelve_test_01.txt', writeback=True) shelf['node'] = a shelf['lst'] = lst shelf.sync() shelf.close() #Read objects from file shelf = shelve.open('shelve_test_01.txt', 'r') a = shelf['node'] lst = shelf['lst'] print a.a, a.b, a.c, a.d #lst does not contains the relationship of object 'a''s attributes, instead it's creating new instances #of 'attrib' class print lst From jordanrastrick at gmail.com Thu Jul 24 01:41:54 2008 From: jordanrastrick at gmail.com (Jordan) Date: Wed, 23 Jul 2008 22:41:54 -0700 (PDT) Subject: Attack a sacred Python Cow Message-ID: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Hi everyone, I'm a big Python fan who used to be involved semi regularly in comp.lang.python (lots of lurking, occasional posting) but kind of trailed off a bit. I just wrote a frustration inspired rant on my blog, and I thought it was relevant enough as a wider issue to the Python community to post here for your discussion and consideration. This is not flamebait. I love Python, and I'm not out to antagonise the community. I also realise that one of the issues I raise is way too ingrained to be changed now. I'd just like to share my thinking on a misstep in Python's guiding principles that has done more harm than good IMO. So anyway, here's the post. I've become utterly convinced that at least one criticism leveled at my favourite overall programming language, Python, is utterly true and fair. After quite a while away from writing Python code, I started last night on a whim to knock up some code for a prototype of an idea I once had. It's going swimmingly; the Python Image Library, which I'd never used before, seems quick, intuitive, and with the all the features I need for this project. As for Python itself, well, my heart still belongs to whitespace delimitation. All the basics of Python coding are there in my mind like I never stopped using them, or like I've been programming in this language for 10 years. Except when it comes to Classes. I added some classes to code that had previously just been functions, and you know what I did - or rather, forgot to do? Put in the 'self'. In front of some of the variable accesses, but more noticably, at the start of *every single method argument list.* This cannot be any longer blamed as a hangover from Java - I've written a ton more code, more recently in Python than in Java or any other OO language. What's more, every time I go back to Python after a break of more than about a week or so, I start making this 'mistake' again. The perennial justification for this 'feature' of the language? That old Python favourite, "Explicit is better than implicit." I'm sorry, but EXPLICIT IS NOT NECESSARILY BETTER THAN IMPLICIT. Assembler is explicit FFS. Intuitive, clever, dependable, expected, well-designed *implicit* behaviour is one of the chief reasons why I use a high level language. Implicitly garbage collect old objects for me? Yes, please! I was once bitten by a Python wart I felt was bad enough to raise and spend some effort advocating change for on comp.lang.python (never got around to doing a PEP; partly laziness, partly young and inexperienced enough to be intimidated at the thought. Still am, perhaps.) The following doesn't work as any sane, reasonable person would expect: # Blog code, not tested class A(): def __eq__(self, obj): return True a = A() b = [] assert a == b assert not (a != b) The second assertion fails. Why? Because coding __eq__, the most obvious way to make a class have equality based comparisons, buys you nothing from the != operator. != isn't (by default) a synonym for the negation of == (unlike in, say, every other language ever); not only will Python let you make them mean different things, without documenting this fact - it actively encourages you to do so. There were a disturbingly high number of people defending this (including one quite renowned Pythonista, think it might have been Effbot). Some had the temerity to fall back on "Explicit is better than implict: if you want != to work, you should damn well code __ne__!" Why, for heaven's sake, should I have to, when in 99.99% of use cases (and of those 0.01% instances quoted in the argument at the time only one struck me as remotely compelling) every programmer is going to want __ne__ to be the logical negation of __eq__? Why, dear Python, are you making me write evil Java-style language power reducing boilerplate to do the thing you should be doing yourself anyway? What's more, every programmer is going to unconciously expect it to work this way, and be as utterly as mystified as me when it fails to do so. Don't tell me to RTFM and don't tell me to be explicit. I'll repeat myself - if I wanted to be explicit, I'd be using C and managing my own memory thank you very much. Better yet, I'd explicitly and graphically swear - swear in frustration at this entrenched design philosophy madness that afflicts my favourite language. I think the real problem with the explicit is better than implicit, though, is that while you can see the underlying truth its trying to get at (which is perhaps better expressed by Ruby's more equivocal, less dependable, but more useful Principle of Least Surprise), in its stated form its actually kind of meanginless and is used mainly in defence of warts - no, we'll call them for what they are, a language design *bugs*. You see, the problem is, there's no such thing of explict in programming. Its not a question of not doing things implicitly; its a question of doing the most sensible thing implicitly. For example this python code: some_obj.some_meth(some_arg1, some_arg2) is implicitly equivalent to SomeClass.some_meth(some_obj, some_arg1, some_arg2) which in turn gives us self as a reference to some_obj, and Python's OO model merrily pretends its the same as Java's when in fact is a smarter version that just superficially looks the same. The problem is that the explicit requirement to have self at the start of every method is something that should be shipped off to the implicit category. You should have to be explicit, yes - explicit when you want the *other* behaviour, of self *not* being an argument, because thats the more unusual, less likely case. Likewise, a != b is implicitly equivalent to something like calling this function (may not be correct, its a while since I was heavily involved in this issue): def equal(a, b): if hasattr(a, "__ne__"): return a.__ne__(b) if hasattr(b, "__ne__"): return b.__ne__(a) if hasattr(a, "__cmp__"): return not (a.__cmp__(b) == 0) if hasattr(b, "__cmp__"): return not (b.__cmp__(a) == 0) return not (a is b) There's absolutely nothing explicit about this. I wasn't arguing for making behaviour implicit; I was arguing for changing the stupid implict behaviour to something more sensible and less surprising. The sad thing is there are plenty of smart Python programmers who will justify all kinds of idiocy in the name of their holy crusade against the implict. If there was one change I could make to Python, it would be to get that damn line out of the Zen. From noagbodjivictor at gmail.com Sun Jul 6 23:17:37 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Sun, 6 Jul 2008 23:17:37 -0400 Subject: GUI Programming by hand not code with Python Code Message-ID: > Is their a program that lets you design a GUI by hand (like gambas) > not by code (like wxpython) but the commands are in python? > > A program similar to gambas or vb > > Gambas with python code instead of gambas code would be perfect. > > Thanks in advance Check out the Designer program that comes with PyQt. -- NOAGBODJI Paul Victor From fredrik at pythonware.com Wed Jul 16 10:07:02 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 16:07:02 +0200 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: <487DFF56.7010405@timgolden.me.uk> References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> <487DFF56.7010405@timgolden.me.uk> Message-ID: Tim Golden wrote: > This is included in the latest pywin32-211 as well: > > > import win32process > print win32process.IsWow64Process () > on the other hand, "ctypes" is only an import away if you have a current Python... From adamc55 at gmail.com Tue Jul 8 10:33:02 2008 From: adamc55 at gmail.com (Adam C.) Date: Tue, 8 Jul 2008 07:33:02 -0700 (PDT) Subject: Dynamically Changing the Base Class References: <6d60c362-ba17-4414-babd-2cc254526bca@c58g2000hsc.googlegroups.com> <68bba759-864e-4943-9f1e-f19b99408ef7@l64g2000hse.googlegroups.com> Message-ID: <72e2ec01-2baa-45a6-a4d6-aaedf5451937@m3g2000hsc.googlegroups.com> On Jul 7, 4:04?pm, Carl Banks wrote: > On Jul 7, 9:31 am, "Adam C." wrote: > > > > > We have a situation where we want a Swig-generated Python class to > > have a different base (not object). It doesn't appear that we can > > coerce Swig into generating the class we want at present (but we are > > still enquiring). > > > Is it possible to dynamically change the base class to something else? > > Initial experiments appear to show it is not: > > -------------------------------- snip -------------------------------->>> class Foo(object): > > > ? ? ? ? pass > > > >>> class Foozle(object): > > > ? ? ? ? pass > > > >>> Foozle.__bases__ = (Foo,) > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? ? Foozle.__bases__ = (Foo,) > > TypeError: __bases__ assignment: 'Foo' deallocator differs from > > 'object' > > -------------------------------- snip -------------------------------- > > > Is there a solution I am missing? > > > Thanks in advance. > > You get the same effect as subclassing by using multiple inheritance. > Suppose your SWIG class called Foo to have a base class of Base. ?You > could instead call the SWIG class _Foo, and define Foo as a Python > class like this: > > class Foo(_Foo,Base): pass > > If you do that, the resulting class will behave exactly as if _Foo > were a subclass of base (apart from some introspection methods and > edge cases). ?You can see that this is so if you look at the MRO: > > Foo, _Foo, Base, object > > Which is the same MRO that would occur if _Foo derived from Base > directly. > > The drawback (which is also a drawback to the hypothetical base > reassignment) is that Foo's __init__ method won't call Base's. ?The > only way you can make SWIG __init__ call it's superclass's __init__ is > apparently a patch. > > Carl Banks Thanks. Looks like I will just write a patch step and hook it into the makefile. From bulg at ngs.ru Wed Jul 16 04:39:57 2008 From: bulg at ngs.ru (Yosifov Pavel) Date: Wed, 16 Jul 2008 01:39:57 -0700 (PDT) Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> <7348c0dc-028d-4f89-9d63-b1247fb6807c@m44g2000hsc.googlegroups.com> <6e5bu8F5eajaU1@mid.uni-berlin.de> Message-ID: On 16 ???, 11:32, Marc 'BlackJack' Rintsch wrote: > On Tue, 15 Jul 2008 19:54:30 -0700, Yosifov Pavel wrote: > > Kay, can you show example of such generator? ReIter, for example, work > > with usual generators. > > > But for "big" iterator, I think is no any good solutions. IMHO we can > > discern 2 types of iterators: re-startable (based on internal Python > > objects) and not re-startable (with an external state, side- > > effects)... > > Has nothing to do with internal vs. external. > Examples: ``itertools.count(1)``, ``itertools.cycle(iterable)``, or > > def fib(): > a, b = 0, 1 > while True: > yield a > a, b = b, a + b > > Ciao, > Marc 'BlackJack' Rintsch Yes. So, I'm disconcerted: what Python "means" about iterators. Why iterator's are not clonable in default?.. ``itertools.count(it) `` "suppose" ``it`` will be restarted after count? So ``count(it)`` "suppose" ``it`` is restarable and therefore clonable (why not?!). Generator is only function, so can be restarted/cloned. Generator keeps "position" and can't be iterated again. But this position can be reseted (main rule: if generator function has not side-effects/ external state, see below)! Iterator, I think, is more general method (for naturally serial access). For example, you can read values from some device (RS323 or other) and represent it in program like iterator. In this case, ``__iter__()`` make some preparation, ``next()`` read next value from RS232. In this case, iterator can't be restarted and really cloned. It has external state (state of device) and can't to return it at start. But when series of values are generated (are born) in the program: no problem to have the feature of clone/restart iterator. And is very interesting to research Icon iterators. Is possible to create something in Python such theirs, for non-deterministic solving purpose... :-) --pavel From norseman at hughes.net Tue Jul 8 20:51:52 2008 From: norseman at hughes.net (norseman) Date: Tue, 08 Jul 2008 17:51:52 -0700 Subject: a simple 'for' question In-Reply-To: <84bdef3c0807081732q33b3bccdvc1d2c361d8c34d80@mail.gmail.com> References: <4874017D.2000401@umbc.edu> <84bdef3c0807081732q33b3bccdvc1d2c361d8c34d80@mail.gmail.com> Message-ID: <48740BA8.5050605@hughes.net> Almost correct: There is a typo. Should read: for x in folders: open('my/path/way/'+x+'/myfile.txt','r') Rajanikanth Jammalamadaka wrote: > Hi! > > Try this > > for x in folders: > open('my/path/way'+x+'myfile.txt','r') > > Cheers, > > Raj > > On Tue, Jul 8, 2008 at 5:08 PM, Ben Keshet wrote: >> Hi fans, >> >> I want to use a 'for' iteration to manipulate files in a set of folders, >> something like: >> >> folders= ['1A28','1A6W','56Y7'] >> for x in folders: >> print x # print the current folder >> f = open('my/path/way/x/my_file.txt', 'r') >> ... >> >> where 'x' in the pathway should iterate over '1A28','1A6W','56Y7'. How >> should I identify 'x' in the pathway line as the same x that is iterating >> over 'folders'? >> >> I am getting the following error: >> >> Traceback (most recent call last): >> File >> "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", >> line 310, in RunScript >> exec codeObject in __main__.__dict__ >> File "C:\Linux\Dock_method_validation\myscripts\test_for.py", line 5, in >> >> f = open('c:/Linux/Dock_method_validation/x/receptor.mol2', 'r') >> IOError: [Errno 2] No such file or directory: >> 'c:/Linux/Dock_method_validation/x/receptor.mol2' >> >> I tired several variations: %x, 'x', "x", etc. all gave me similar errors. >> >> Thanks for your help, >> BK >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > From mail at timgolden.me.uk Thu Jul 24 11:25:37 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 24 Jul 2008 16:25:37 +0100 Subject: Attack a sacred Python Cow In-Reply-To: <48889a72$0$25165$426a74cc@news.free.fr> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <32e12408-fc9f-4eb4-8b9d-fb7fa69bd2fc@f36g2000hsa.googlegroups.com> <87zlo7y2wn.fsf@physik.rwth-aachen.de> <48889a72$0$25165$426a74cc@news.free.fr> Message-ID: <48889EF1.4000901@timgolden.me.uk> Just wondered whether the OP's Subject was a deliberate play on "flog a dead horse" or merely an ironic one :) TJG From Lie.1296 at gmail.com Tue Jul 8 06:45:41 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 8 Jul 2008 03:45:41 -0700 (PDT) Subject: Confused yet again: Very Newbie Question References: <13be8c54-3fa9-4a37-a0e6-45bb019bff7e@a1g2000hsb.googlegroups.com> Message-ID: On Jul 7, 7:09?pm, Jeff wrote: > When you call c3.createJoe(c1.fred), you are passing a copy of the > value stored in c1.fred to your function. ?Python passes function > parameters by value. No, python doesn't pass variable either by value or by reference. The behavior in python is a bit of mix between passing by value and by reference, because python use different variable model than Basic (in short, saying passing by reference or value in python doesn't make sense). In python, variables are names referring to an object, in Basic variables are the object itself. In python, when you pass variable as function parameter, you pass the object to the function and inside the function a new name is rebound to that object. These two names are not related in any way except that they refers to the same object. In python an immutable object can't be changed after creation and string is immutable, so when you reassign 'Joe' to myName, a string object 'Joe' is created and assigned to myName, myName's original string object ('fred') isn't affected and other names that refers to the string object 'fred' (i.e. c1.fred, one.fred) isn't changed. If you want to change all those values too, you'd have to change the inner string object itself (which is impossible since string object is immutable). If the object referred is mutable (e.g. list, dictionary) that example would work. >?The function will not destructively modify its > arguments; you must expliticly state your intention to modify an > object: > > class one(): > ? ? fred = 'fred' > > class three(): > ? ? def createJoe(self, myName): > ? ? ? ? return "Joe" > > def main(): > ? ? c1 = one() > ? ? c3 = three() > ? ? c1.fred = c3.createJoe() # Modify c1's attribute, fred, with the > return value from c3.createJoe From alan.franzoni.blahblah at example.com.invalid Mon Jul 28 04:02:42 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Mon, 28 Jul 2008 08:02:42 GMT Subject: write unsigned integer 32 bits to socket References: Message-ID: Michael Torrie was kind enough to say: > Of course any time you send coherent numbers over the network, I highly > recommend you use what's called network byte order. In C, you'd use the > htonl() call, and then when pulling it off the wire on the other end > you'd use ntohl(). If you don't then you will have problems when the > endianness is different between the hosts. Standard convention (even in > the MS word) is to use big-ending across the network. I'm sure python > has some convention in the struct module for dealing with this. Not in the struct module; such functions are available in the socket module, and should be employed indeed. -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From Russ.Paielli at gmail.com Mon Jul 28 21:54:02 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jul 2008 18:54:02 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> <488e3520$0$16766$426a74cc@news.free.fr> Message-ID: On Jul 28, 12:08 pm, Bruno Desthuilliers wrote: > > It's a very simple idea that you insist on > > making complicated. As I said, I could write a pre-processor myself to > > implement it in less than a day. > > Preprocessor are not a solution. Sorry. I never said that a pre-processor is a good permanent solution, but the simple fact that my proposal can be done with a simple pre- processor means that it does not change the inner workings of the Python interpreter. > Oh, you don't stand people disagreing with you, that's it ? I can stand people disagreeing with me all day long, so long as they are making sense. You are simply making the issue more complicated that it is because you are apparently incapable of understanding the substance of it. > > You seem to think that being a "regular" on this newsgroup somehow > > gives you special status. > > Why so ? Because I answer to your proposition and not agree with your > arguments ??? C'mon, be serious, you have the right to post your > proposition here, I have the right to post my reaction to your > proposition, period. Grow up, boy. > Boy, I don't know who you think you're talking to, but you're obviously > out of luck here. I'm 41, married, our son is now a teenager, I have an > happy social life, quite a lot of work, and no time to waste in the > streets. And FWIW, name-calling won't buy you much here. There you go again. Do you think you are proving something by addressing me as "boy"? I'll make a little wager with you. I'll bet that what I am using Python for dwarfs in importance what you are using it for. Care to put the cards on the table, big man? I'll tell you something else while I'm at it. I'm ten years older than you, but I pump iron and stay in excellent shape. If you addressed me as "boy" in person, I'd be more than happy to teach you a badly needed lesson you won't soon forget, big man. From noelob at gmail.com Wed Jul 23 04:44:13 2008 From: noelob at gmail.com (noelob) Date: Wed, 23 Jul 2008 01:44:13 -0700 (PDT) Subject: Uploading an image using PUT References: <2375be12-6470-493c-9d4f-979e20c35502@k13g2000hse.googlegroups.com> Message-ID: <8018550e-a5a2-46b7-a989-64b1aa6d2a26@2g2000hsn.googlegroups.com> Hi All, I finally figured it out, thanks to Wireshark! I was adding my own "Content-Length: 50173" header to the request, but httplib appears to add its own header (also "Content-Length: 50173") which must have been causing a conflict and making the sever return "HTTP/1.1 400 Bad Request\r\n". As soon as I removed my own Content-Length header, it worked! Regards, Noel From jr9445 at ATT.COM Tue Jul 15 16:21:24 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Tue, 15 Jul 2008 15:21:24 -0500 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Reedick, Andrew > Sent: Tuesday, July 15, 2008 4:13 PM > To: Victor Noagbodji; python-list at python.org > Subject: RE: 'if name is not None:' v. 'if name:' > > If name: > Then either > a) name is an object, and that object does not have a 'false' > value, such as False, zero, or empty. > or > b) name is NULL/None. No object. Change that to: If not name: Then either a) name is an object, and that object does not have a 'false' value, such as False, zero, or empty. or b) name is NULL/None. No object. From danb_83 at yahoo.com Mon Jul 21 22:34:57 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Mon, 21 Jul 2008 19:34:57 -0700 (PDT) Subject: Odd math related issue. References: <43332.3139710867$1216630189@news.gmane.org> Message-ID: <69374534-64bd-4784-9255-7238883ae51a@z6g2000pre.googlegroups.com> On Jul 21, 3:52?am, Fredrik Lundh wrote: > Robert Rawlins wrote: > > I?ve got what seems to me to be a totally illogical math issue here > > which I can?t figure out. Take a look at the following code: > > > ? ? ? ? /self/.__logger.info(/"%i / %i"/ % (bytes_transferred, > > /self/.__sessions[path].total_bytes)) > > > ? ? ? ? percentage = bytes_transferred / > > /self/.__sessions[path].total_bytes * 100 > > > ? ? ? ? /self/.__logger.info(/"%i"/ % percentage) > > > Seems fairly straight forward, you would think. It takes two values and > > calculates the percentage of one from the other, however, percentage > > always comes back as ?0? for some reason, look at this log output. > > if you divide two integers, you'll get an integer back (in Python 2.X, > at least). ?quick fix: > > ? ? ? percentage = bytes_transferred * 100 / total_bytes > > The most wonderful statement in the Python language is from __future__ import division From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 15:25:59 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 21:25:59 +0200 Subject: readln() until EOF In-Reply-To: References: Message-ID: <4888d744$0$5450$426a34cc@news.free.fr> korean_dave a ?crit : > a = open("Thefile.txt","r") > > while ?????: > result = a.readln() I assume you meant "a.readline()" ? Anyway... > what do i put in ???? if i want to keep reading line by line until i > reach the end of the file? a = open("path/to/file.ext") for line in a: do_something_with(line) a.close() From semanticist at gmail.com Sun Jul 13 16:08:28 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 16:08:28 -0400 Subject: socket.connect() hangs in SYN_SENT state. In-Reply-To: <804bccb2-42c7-42e9-8f50-7a780d3438fd@j22g2000hsf.googlegroups.com> References: <804bccb2-42c7-42e9-8f50-7a780d3438fd@j22g2000hsf.googlegroups.com> Message-ID: On Sun, Jul 13, 2008 at 2:32 PM, bukzor wrote: > On Jul 13, 1:14 am, Miles wrote: >> On Sat, Jul 12, 2008 at 11:23 PM, bukzor wrote: >> > I'm connecting to an apache2 process on the same machine, >> > for testing. When looking at netstat, the socket is in the SYN_SENT >> > state, like this: >> >> > $netstat -a -tcp >> > tcp 0 0 *:www *:* LISTEN 7635/apache2 >> > tcp 0 1 bukzor:38234 adsl-75-61-84-249.d:www SYN_SENT 9139/python >> >> > Anyone know a general reason this might happen? Even better, a way to >> > fix it? >> >> That socket connection is to a remote machine, not the same one. Your >> test code works fine for me. The "hang then crash" (and I'm assuming >> "crash" here means an uncaught exception) just means that your packets >> are being silently ignored by whatever machine you're actually >> attempting to connect to. It's possible that your machine has odd DNS >> settings causing buzkor.hopto.org to resolve to the wrong address. > > I'm connecting to my machine through the internet, and the resolved > URL of my router is what you're seeing above. If you run the code > above you'll see what I mean. I did run the code, and as I said, it works fine. Your description of the setup is not consistent. The netstat output unambiguously states that a Python script on "buzkor" is attempting to open a connection to the HTTP port on the "adsl" machine (and failing because "adsl" is not responding). The problem here is not Python; you seem to be confused about which machine is connecting to which. -Miles From google at mrabarnett.plus.com Wed Jul 30 13:25:42 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 30 Jul 2008 10:25:42 -0700 (PDT) Subject: Standard module for parsing emails? References: <6fb93eFap7j5U1@mid.individual.net> Message-ID: <86cbbf9d-e568-42a4-8839-5015225937dc@34g2000hsf.googlegroups.com> On Jul 30, 3:11?pm, Phillip B Oldham wrote: > On Jul 30, 2:36 pm, Thomas Guettler wrote: > > > What do you mean with "quote" here? > > ? 2. Prefix of quoted text like your text above in my mail > > Basically, just be able to parse an email into its actual and "quoted" > parts - lines which have been prefixed to indent from a previous > email. > > Most clients use ">" which is easy to check for, but I've seen some > which use "|" and some which *don't* quote at all. Its causing us > nightmares in parsing responses to system-generated emails. I was > hoping someone might've seen the problem previously and released some > code. The problem is that sometimes lines might start with ">" for other reasons, eg text copied from an interactive Python session, which could occur in ... um ... _this_ newsgroup. :-) From aoeui2008 at nospam.cox.net Sun Jul 20 20:50:38 2008 From: aoeui2008 at nospam.cox.net (Teiresias) Date: Sun, 20 Jul 2008 19:50:38 -0500 Subject: Python Written in C? References: Message-ID: <87r69ooyap.fsf@cox.net> giveitawhril2008 at gmail.com writes: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? Well, yes, the interpreter and a handful of the core modules are written in C. However, most of Python -- especially the cool bits -- aren't written in C. They're written in ... Python! -- Teiresias From circularfunc at yahoo.se Tue Jul 15 13:36:23 2008 From: circularfunc at yahoo.se (defn noob) Date: Tue, 15 Jul 2008 10:36:23 -0700 (PDT) Subject: isPrime works but UnBoundLocalError when mapping on list References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> <8a07445a-3ca8-4373-9312-cea8db83ec5c@l64g2000hse.googlegroups.com> Message-ID: <9f3c45f1-9cb2-46c1-838b-716180061956@e39g2000hsf.googlegroups.com> On Jul 15, 7:28?pm, Mensanator wrote: > On Jul 15, 11:26?am, defn noob wrote: > > > > > isPrime works when just calling a nbr but not when iterating on a > > list, why? adding x=1 makes it work though but why do I have to add > > it? > > Is there a cleaner way to do it? > > > def isPrime(nbr): > > ? ? for x in range(2, nbr + 1): > > ? ? ? ? if nbr % x == 0: > > ? ? ? ? ? ? break > > ? ? if x == nbr: > > ? ? ? ? return True > > ? ? else: > > ? ? ? ? return False > > > >>> [isPrime(y) for y in range(11)] > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? ? [isPrime(y) for y in range(11)] > > ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > > ? ? if x == nbr: > > UnboundLocalError: local variable 'x' referenced before assignment > > > >>> map(isPrime, range(100)) > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? ? map(isPrime, range(100)) > > ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > > ? ? if x == nbr: > > UnboundLocalError: local variable 'x' referenced before assignment>>> isPrime(10) > > False > > >>> isPrime(11) > > > True > > > adding x=1 makes it work though: > > > def isPrime(nbr): > > ? ? x=1 > > ? ? for x in range(2, nbr + 1): > > ? ? ? ? if nbr % x == 0: > > ? ? ? ? ? ? break > > ? ? if x == nbr: > > ? ? ? ? return True > > ? ? else: > > ? ? ? ? return False > > > >>> [isPrime(y) for y in range(11)] > > > [False, True, True, True, False, True, False, True, False, False, > > False] > > No, it doesn't. You are falsely reporting that 1 is prime. > > And instead of making the fake variable x, shouldn't you > instead test that nbr+1 is greater than 2? Or call it with > range(3,11) instead of range(11)? x isn't initialized > because if nbr+1 is <=2, the for loop has an invalid range > and doesn't even execute. def isPrime(nbr): for x in range(2, nbr + 1): if nbr % x == 0: break if x == nbr: return True else: return False this works for all primes, if i want to not include 1 i just do if nbr<=1 return false you are answering the wrong question. anyway here is a clear one: def isPrime(nbr): if nbr < 2: return False for x in range(2, nbr + 1): if nbr % x == 0: return nbr == x From fredrik at pythonware.com Wed Jul 23 08:26:39 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 14:26:39 +0200 Subject: os.walk question In-Reply-To: <79b8d5e1-709f-4a4f-957d-8acbee20018b@c2g2000pra.googlegroups.com> References: <79b8d5e1-709f-4a4f-957d-8acbee20018b@c2g2000pra.googlegroups.com> Message-ID: alex23 wrote: >> if you want a list of files from a single directory, use listdir, not walk: >> >> >>> import os, random >> >>> random.choice(os.listdir("/")) >> 'python25' > > This will include folders as well, though, which isn't what the OP > asked for. as illustrated by my example (cut and pasted from a windows machine). oops. random.choice(filter(os.path.isfile, glob.glob("/*"))) isn't that bad, though. From circularfunc at gmail.com Thu Jul 31 07:09:57 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 31 Jul 2008 04:09:57 -0700 (PDT) Subject: How smart is the Python interpreter? Message-ID: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> def str_sort(string): s = "" for a in sorted(string): s+=a return s if i instead do: def str_sort(string): s = "" so = sorted(string) for a in so: s+=a return s will that be faster or the interpreter can figure out that it only has to do sorted(string) once? or that kind of cleverness is usually reserved for compilers and not interpreters? From tjreedy at udel.edu Thu Jul 17 17:32:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jul 2008 17:32:30 -0400 Subject: x, = y (???) In-Reply-To: References: Message-ID: kj wrote: > > > I just came across an assignment of the form > > x, = y > > where y is a string (in case it matters). > > 1. What's the meaning of the comma in the LHS of the assignment? > 2. How could I have found this out on my own? 1.Experiment with the interactive interpreter. It is sooo easy. >>> x, = '1' >>> x '1' >>> x, = '12' Traceback (most recent call last): File "", line 1, in x, = '12' ValueError: too many values to unpack >>> x,y = '12' >>> x,y ('1', '2') >>> x, = 3 Traceback (most recent call last): File "", line 1, in x, = 3 TypeError: 'int' object is not iterable >>> *x, = [3] >>> x [3] 2. Read the Python docs which come with the interpreter. LanguageReference/SimpleStatements/AssignmentStatements: "If the target list is a comma-separated list of targets: ... Else: The object must be a sequence with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets." which is exactly the behavior observed above. From cjw at ncf.ca Sun Jul 27 16:04:43 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sun, 27 Jul 2008 16:04:43 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > On Jul 26, 2:25 pm, Terry Reedy >> There is a lot of code you have not seen. Really. In informal code I >> use 's' and 'o' for 'self' and 'other'. I don't usually post such >> because it is not considered polite. So you have seen a biased sample >> of the universe. > > You take the name down to a single letter. As I suggested in an > earlier post on this thread, why not take it down to zero letters? You > could if Python accepted something like > > class Whatever: > > def fun( , cat): > > .cat = cat > > This is even better than the single-character name, not only because > it is shorter, but also because there is no question that you are > referring to "self." No need to look back at the method signature to > verify that. > > For those who don't like the way the empty first argument looks, maybe > something like this could be allowed: > > def fun( ., cat): > I don't see the need for the comma in fun. Colin W. From tommy.nordgren at comhem.se Mon Jul 28 13:51:26 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Mon, 28 Jul 2008 19:51:26 +0200 Subject: like py2exe, but on a mac In-Reply-To: <5K9jk.278$rb5.198@trnddc04> References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> Message-ID: On 28 jul 2008, at 03.59, William McBrine wrote: > On Sun, 13 Jul 2008 00:58:59 +0200, Python.Arno wrote: > >> http://undefined.org/python/py2app.html > > py2app bundles Python itself into the app, right? I wonder, is there > no > way to create an app bundle that relies on the existing installation > of > Python, since OS X already comes with Python? I have a tiny little > program (~20k) that I'd like to make into an app bundle, if only to > suppress the console window, and I'd rather not lump in the whole > Python > interpreter if I can avoid it. > > -- > 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on > -- > http://mail.python.org/mailman/listinfo/python-list There is Platypus, a general open source program to wrap a script in an Macintosh (GUI) Application. -------------- next part -------------- A non-text attachment was scrubbed... Name: Platypus 4.0 software download - Mac OS X - VersionTracker.webloc Type: application/octet-stream Size: 286 bytes Desc: not available URL: -------------- next part -------------- ---------------------------------- Skinheads are so tired of immigration, that they are going to move to a country that don't accept immigrants! Tommy Nordgren tommy.nordgren at comhem.se From giltay at gmail.com Tue Jul 29 17:48:31 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Tue, 29 Jul 2008 14:48:31 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: <2ac250ee-131d-44a3-9b0a-f2fb34758147@c65g2000hsa.googlegroups.com> On Jul 29, 1:30?pm, Carl Banks wrote: > On Jul 29, 5:15 am, Heiko Wundram wrote: > > > I can't dig up a simple example from code I wrote quickly, but because of the > > fact that explicit comparisons always hamper polymorphism > > I'm not going to take your word for it. ?Do you have code that > demonstrates how "if x" improves polymorphism relative to simple > explicit tests? > > Carl Banks I think "if x" works in some cases, but not in others. Here's an example I just made up and a counterexample from my own code. Example: Here's a function, print_members. It's just something that takes some iterable and prints its members in XML. It's special-cased so that an empty iterable gets an empty tag. (This is a bit of a trivial example, I admit; the point is that the empty iterable is a special case.) def print_members(iterable): if not iterable: print '' return print '' for item in iterable: print '%s' % item print '' >>> print_members(['a', 'b', 'c']) a b c >>> print_members([]) I could have used "if len(iterable) == 0:" for these cases, but only because the length of a list means something. Say I were to implement a matrix class. The length of a matrix isn't well-defined, so I won't implement __len__. I will, however, implement __nonzero__, since if it has no members, it's empty. class SimpleMatrix(object): def __init__(self, *rows): self.rows = rows def __nonzero__(self): for row in self.rows: if row: return True return False def __iter__(self): return iter(sum(self.rows, [])) >>> a = SimpleMatrix([1, 2, 3], [4, 5, 6]) >>> print_members(a) 1 2 3 4 5 6 >>> b = SimpleMatrix([],[],[]) >>> len(b) Traceback (most recent call last): File "", line 1, in TypeError: object of type 'SimpleMatrix' has no len() >>> print_members(b) So print_members can work on iterables that have no len(), and handle the special case of an empty iterable, as long as __nonzero__ is implemented. Counterexample: While "if x" works well in some circumstances, I don't like using it for purely numeric types. For instance, I have a mutable Signal class for doing some basic DSP. Among other things, I can apply a DC offset to the signal (it just adds the offset to all the samples). I have a special case for an offset of 0 so I don't have to loop through all the samples (I also have a two-pass remove_offset method that subtracts the average; if it's already properly centred, I can skip a step). class Signal: [...] def dc_offset(self, amount): if amount == 0: return self.samples = [sample + amount for sample in self.samples] Here, "if amount == 0" is deliberate. At no point should I be adding an offset that's a list or a dict, even an empty one. Signal.dc_offset should raise an exception if I try to do that, because that indicates there's a bug somewhere. If I do pass in [] or {}, that test will fail, and it will try to add the list or dict to the samples, at which point I get a TypeError. Geoff G-T From thomas.troeger.ext at siemens.com Fri Jul 4 08:59:05 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Fri, 04 Jul 2008 14:59:05 +0200 Subject: Static Class Initialization Question. References: <486e16c8$0$22780$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > return "%s(%d,%d)" % (type(self).__name__, self.a, self.b) Er, yes exactly! I noticed it a few seconds after I had sent the message ;-( >> I want to have a list of such classes instantiated automatically on Of course I meant class instances ... sorry :) It's always good to have an example to compensate for English errors *g*. > bla = [A(*args) for args in ((1,2), (3,4))] ... > Note that it's not a list of classes, but a list of instances of A. But > given your specs, nope, your approach is the right one. Ah I knew there was something and I couldn't find it in the docs anymore! Now my potential follow-up question is answered as well, namely how I can instantiate with variable argument lists, like this: >>> bla = [A(*args) for args in ((), (1,), (1, 2))] >>> map(str, bla) ['A(0,1)', 'A(1,1)', 'A(1,2)'] > Basically (no pun intended[1]), Python is not C. Trying to write C in > Python will only buy you pain and frustration (and this can be > generalized for any combination of two languages for any known > programming language). Hehe. I am trying to develop a program prototype in python because of it's repaid prototyping properties, and once it's working I will port it to C, because of speed issues and the fact that it's running on an embedded machine without space for a python interpreter. I have like 4 Megs left, but until now noone has answered my question how I can cut down a standard python installation so that it fit's into 4 megs. Thanks for your quick answer :) T. From robinsiebler at gmail.com Thu Jul 31 17:41:22 2008 From: robinsiebler at gmail.com (robinsiebler at gmail.com) Date: Thu, 31 Jul 2008 14:41:22 -0700 (PDT) Subject: saving an e-mail attachement Message-ID: I'm trying to figure out how to save an e-mail attachment from a POP3 mailbox. I've scoured the web, but -none- of the examples I have found have actually worked. For instance, in this example: http://groups.google.com/group/comp.lang.python/browse_thread/thread/8423cad79ff21730/0d8922943a164ccf?lnk=gst&q=email+attachment#0d8922943a164ccf, fn is always None, but the e-mail -does- have an attachment (an xml file). From sri_annauni at yahoo.co.in Mon Jul 14 06:41:45 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Mon, 14 Jul 2008 16:11:45 +0530 (IST) Subject: Do we have perl's Data::Dumper equivalent in Python?? Message-ID: <502717.38540.qm@web7902.mail.in.yahoo.com> Thanks, Srini Bollywood, fun, friendship, sports and more. You name it, we have it on http://in.promos.yahoo.com/groups/bestofyahoo/ From __peter__ at web.de Tue Jul 1 07:22:37 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Jul 2008 13:22:37 +0200 Subject: Disabling the magic "last expression" _ variable References: <486a108d$0$14358$e4fe514c@news.xs4all.nl> Message-ID: Koen Vossen wrote: > A project I'm currently working on uses Turbogears as a framework. I'd > like to interact with it using the tg-admin shell. We also use gettext's > _() function for internationalization. Now, this function is overwritten > in interactive mode, which causes annoying exceptions. Is it possible to > disable this behavior? [correct overzealous snip] >>> import sys >>> def displayhook(result): ... if result is not None: ... __builtins__._last = result ... print result ... >>> sys.displayhook = displayhook >>> _ Traceback (most recent call last): File "", line 1, in NameError: name '_' is not defined >>> "yadda" yadda >>> _ Traceback (most recent call last): File "", line 1, in NameError: name '_' is not defined >>> _last yadda Peter From sjmachin at lexicon.net Sat Jul 19 17:44:24 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 19 Jul 2008 14:44:24 -0700 (PDT) Subject: regex doubts References: <532965.570.qm@web54502.mail.re2.yahoo.com> <504d473e-375a-4111-ae2e-c06aaa37b096@p25g2000pri.googlegroups.com> <5a77d3ef-2313-4f3a-9486-d27136ac0409@b1g2000hsg.googlegroups.com> Message-ID: <0d3a6680-3dce-4353-b389-c0e3b2930847@j1g2000prb.googlegroups.com> On Jul 20, 6:35 am, MRAB wrote: > On Jul 19, 9:12 pm, John Machin wrote: > > > > > On Jul 20, 5:04 am, Fredrik Lundh wrote: > > > > Mr SZ wrote: > > > > I am taking a string as an input from the user and it should only > > > > contain the chars:L , M or R > > > > > I tried the folllowing in kodos but they are still not perfect: > > > > > [^A-K,^N-Q,^S-Z,^0-9] > > > > [L][M][R] > > > > [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > > > > > For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. > > > > try "[LRM]+$" (an L or an R or an M, one or more times, all the way to > > > the end of the string). > > > Ummm ... with the default flag settings, shouldn't that be \Z instead > > of $ > > ? > > $ means end of string unless the multiline flag is used, in which case > it means end of line. What manual are you quoting that from? What version of Python are you using? Can you demonstrate that the pattern "[LRM]+$" will fail to match the string "L\n"? From ggpolo at gmail.com Mon Jul 28 19:43:39 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 28 Jul 2008 20:43:39 -0300 Subject: Tkinter fullscreen with Mac OS X In-Reply-To: References: Message-ID: On Mon, Jul 28, 2008 at 8:10 PM, C Martin wrote: > Is there a way to create a full screen app using Tkinter with Mac OS > X?? On windows, this is relatively easy with overrideredirect(1). > However, on the Mac, the top menu bar and dock are still displayed > over the app. Is there a way to get rid of them? > You could try this, supposing tl is a toplevel: tl.tk.call("::tk::unsupported::MacWindowStyle", "style", tl._w, "plain", "none") and if you are using python with tk 8.5 or newer (unlikely): tl.wm_attributes('-fullscreen', 1) But I don't have a mac, so I can't say for sure if these solve your problem. > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From fredrik at pythonware.com Mon Jul 21 03:17:55 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 09:17:55 +0200 Subject: Web Server In-Reply-To: References: Message-ID: James Tanis wrote: >> there's also apache, of course, and a bunch of others, including several >> Python solutions (more or less pre-packaged). but the "open up" part >> still sounds a bit risky. maybe you could turn things around, and let >> the application "push" data to your server instead? > > Either way requires an open port, otherwise there's no way to negotiate new > clients. The scenario I had in mind was rather to make his application the client for an external server, instead of using some external client to connect to someone's PC over HTTPS. That wouldn't need an open server port on the client; any Comet-style protocol would work. But at this point, only the OP knows enough about his application to be able to figure out if that's a usable approach. From alan.franzoni.blahblah at example.com.invalid Wed Jul 30 08:05:31 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Wed, 30 Jul 2008 12:05:31 GMT Subject: Continuous integration for Python projects References: Message-ID: Hussein B was kind enough to say: > Hi. > Please correct my if I'm wrong but it seems to me that the major > continuous integration servers (Hudson, CruiseControl, TeamCity ..) > don't support Python based application. If you want, you can use ant as a build script, and then define the usual targets (build, dist, test), ecc. and then use xmlrunner to publish them in a junit-like format which can be read through cruisecontrol or other CI tools. -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From animator333 at gmail.com Fri Jul 18 03:32:46 2008 From: animator333 at gmail.com (King) Date: Fri, 18 Jul 2008 00:32:46 -0700 (PDT) Subject: sub typing built in type with common attributes. Am I right? Message-ID: <4d9c4b74-9c28-4b98-afe7-9eb774655c3a@v21g2000pro.googlegroups.com> I am new to python and getting into classes. Here I am trying to create subtype of built in types with some additional attributes and function. 'Attributes' is the main class and holds all the common attributes that requires by these subtypes. This is what I came out with. I need to know whether everything is right here ? or there are some better ways to do it. class Attribute(object): """ Common attributes and methods for custom types """ def __init__(self, name=None, type=None, range=None, label=None): #read only attributes self._name = name self._type = type self._range = range #read/write attribute self.label = label #make read only attributes name = property(lambda self: self._name) type = property(lambda self: self._type) range = property(lambda self: self._range) class Float(float, Attribute): '''Custom Float class with some additional attributes.''' __slots__ = ['_Attribute__name', '_Attribute__type', '_Attribute__range', 'label'] def __new__(cls, value=0.0, *args, **kwargs): return float.__new__(cls, value) def __init__(self, value=0.0, name=None, label=None, type=None, range=(0.0, 1.0)): super(Float, self).__init__(name=name, label=label, type=type, range=range) def __str__(self): return '{ %s }' % (float.__str__(self)) class Int(int, Attribute): '''Custom Int class with some additional attributes.''' __slots__ = ['_Attribute__name', '_Attribute__type', '_Attribute__range', 'label'] def __new__(cls, value=0.0, *args, **kwargs): return int.__new__(cls, value) def __init__(self, value=0.0, name=None, label=None, type=None, range=(0.0, 1.0)): super(Int, self).__init__(name=name, label=label, type=type, range=range) def __str__(self): return '{ %s }' % (int.__str__(self)) From andreas.mock at web.de Wed Jul 16 10:18:39 2008 From: andreas.mock at web.de (McA) Date: Wed, 16 Jul 2008 07:18:39 -0700 (PDT) Subject: Logging to different addressees References: <8df30038-86c1-4376-b046-a50f2bcf0a2b@s50g2000hsb.googlegroups.com> <7b829a76-ba2c-4cb7-b216-0c9c01e5cd02@f36g2000hsa.googlegroups.com> <4d3df1d9-339b-43b2-9f25-c792e9bf549c@k13g2000hse.googlegroups.com> <4e30c301-294c-4160-8cb8-c924aed00f71@f63g2000hsf.googlegroups.com> <9566e05f-7ad6-499d-8404-52d60e23b6e8@m36g2000hse.googlegroups.com> Message-ID: <39b03da6-d8f4-4f4e-95c5-375be42035e3@j22g2000hsf.googlegroups.com> On 16 Jul., 15:38, Vinay Sajip wrote: > On Jul 16, 8:55 am, McA wrote: > > > messages tologging.getLogger('tree.leave') would also show up inlogging.getLogger('tree') automatically? > > Yes. Ok. > > > Hope not to bother. > > Use the propagate flag, which is mentioned in the documentation. That's the right hint. > In fact, please make sure you've reviewed all the documentation before > posting, as the documentation is intended to answer the more > straightforward and common questions which come up. I did it and I'll do it again. :-) You know, sometimes a piece of text/documentation starts to become information for the reader when he exactly hits the problem. Anyway, thank you for your help and for that module. > Best regards, > > Vinay Sajip Best regards Andreas Mock From ggpolo at gmail.com Mon Jul 28 18:52:36 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 28 Jul 2008 19:52:36 -0300 Subject: Download excel file from web? In-Reply-To: <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> References: <6f6vhlFa7anrU1@mid.uni-berlin.de> <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> Message-ID: On Mon, Jul 28, 2008 at 7:43 PM, patf at well.com wrote: > On Jul 28, 3:33 pm, "p... at well.com" wrote: >> On Jul 28, 3:29 pm, "Diez B. Roggisch" wrote: >> >> >> >> > p... at well.com schrieb: >> >> > > On Jul 28, 3:00 pm, "p... at well.com" wrote: >> > >> Hi - experienced programmer but this is my first Python program. >> >> > >> This URL will retrieve an excel spreadsheet containing (that day's) >> > >> msci stock index returns. >> >> > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... >> >> > >> Want to write python to download and save the file. >> >> > >> So far I've arrived at this: >> >> > >> [quote] >> > >> # import pdb >> > >> import urllib2 >> > >> from win32com.client import Dispatch >> >> > >> xlApp = Dispatch("Excel.Application") >> >> > >> # test 1 >> > >> # xlApp.Workbooks.Add() >> > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' >> > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' >> > >> # xlBook = xlApp.ActiveWorkbook >> > >> # xlBook.SaveAs(Filename='C:\\test.xls') >> >> > >> # pdb.set_trace() >> > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ >> > >> excel? >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> > >> +25%2C+2008&export=Excel_IEIPerfRegional') >> > >> # test 2 - returns check = False >> > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ >> > >> indexperf/excel? >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() >> >> > >> xlApp = response.fp >> > >> print(response.fp.name) >> > >> print(xlApp.name) >> > >> xlApp.write >> > >> xlApp.Close >> > >> [/quote] >> >> > > Woops hit Send when I wanted Preview. Looks like the html [quote] tag >> > > doesn't work from groups.google.com (nice). >> >> > > Anway, in test 1 above, I determined how to instantiate an excel >> > > object; put some stuff in it; then save to disk. >> >> > > So, in theory, I'm retrieving my excel spreadsheet with >> >> > > response = urllib2.urlopen() >> >> > > Except what then do I do with this? >> >> > > Well for one read some of the urllib2 documentation and found the >> > > Request class with the method has_data() on it. It returns False. >> > > Hmm that's not encouraging. >> >> > > I supposed the trick to understand what urllib2.urlopen is returning >> > > to me; rummage around in there; and hopefully find my excel file. >> >> > > I use pdb to debug. This is interesting: >> >> > > (Pdb) dir(response) >> > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', >> > > 'code', ' >> > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', >> > > 'readline', ' >> > > readlines', 'url'] >> > > (Pdb) >> >> > > I suppose the members with __*_ are methods; and the names without the >> > > underbars are attributes (variables) (?). >> >> > No, these are the names of all attributes and methods. read is a method, >> > for example. >> >> right - I got it backwards. >> >> >> >> >> >> > > Or maybe this isn't at all the right direction to take (maybe there >> > > are much better modules to do this stuff). Would be happy to learn if >> > > that's the case (and if that gets the job done for me). >> >> > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty >> > clear on this: >> >> > """ >> > This function returns a file-like object with two additional methods: >> > """ >> >> > And then for file-like objects: >> >> >http://docs.python.org/lib/bltin-file-objects.html >> >> > """ >> > read( [size]) >> > Read at most size bytes from the file (less if the read hits EOF >> > before obtaining size bytes). If the size argument is negative or >> > omitted, read all data until EOF is reached. The bytes are returned as a >> > string object. An empty string is returned when EOF is encountered >> > immediately. (For certain files, like ttys, it makes sense to continue >> > reading after an EOF is hit.) Note that this method may call the >> > underlying C function fread() more than once in an effort to acquire as >> > close to size bytes as possible. Also note that when in non-blocking >> > mode, less data than what was requested may be returned, even if no size >> > parameter was given. >> > """ >> >> > Diez >> >> Just stumbled upon .read: >> >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ >> excel? >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> +25%2C+2008&export=Excel_IEIPerfRegional').read >> >> Now the question is: what to do with this? I'll look at the >> documentation that you point to. >> >> thanx - pat > > Or rather (next iteration): > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > excel? > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > The file is generally something like 26 KB so specifying 1,000,000 > seems like a good idea (first approximation). > > And then when I do: > > print(response) > > I get a whole lot of garbage (and some non-garbage), so I know I'm > onto something. > > When I read the .read documentation further, it says that read() has > returned the data as a string object. Now - how do I convince Python > that the string object is in fact an excel file - and save it to disk? > You don't need to convince Python, just write it to a file. More reading for you: http://docs.python.org/tut/node9.html > pat > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From dstromberglists at gmail.com Sat Jul 26 16:54:07 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Sat, 26 Jul 2008 20:54:07 GMT Subject: SimpleJson is slow .... is there any C Compiled version ? References: <83a8a774-ddec-4137-9dbe-b6db3b4adfa2@p25g2000hsf.googlegroups.com> Message-ID: On Sat, 26 Jul 2008 00:49:20 -0700, Richard Levasseur wrote: > On Jul 25, 5:52?pm, Matt Nordhoff wrote: >> Also, simplejson and python-cjson might not be entirely compatible: >> there's one character that one escapes and the other doesn't, or >> something. -- > > They also have different interface. simplejson uses load/loads/dump/ > dumps, whereas cjson using encode/decode (its pretty simple to > monkeypatch cjson with some lambda's so it has the same interface, > though). > > Yeah, its frustrating that there are so many json encoders for python. > Its a bit disappointing simplejson is going into the stdlib; i hope they > rewrite it in C? C's great for performance, but if you want something featureful and reliable, you're probably better off in something else - including but not limited to python, optionally with psyco. I wish the pypy people would package up their stuff into a form that you can just ./configure && make && make install and then #! to - I believe it'd grow/mature faster than it is if they did (and they may have, but last time I looked it didn't appear so). But once they do, that might be a convenient way of getting better performance. From aljosa.mohorovic at gmail.com Thu Jul 31 09:36:08 2008 From: aljosa.mohorovic at gmail.com (Aljosa Mohorovic) Date: Thu, 31 Jul 2008 06:36:08 -0700 (PDT) Subject: current week / weeks in year - best practice Message-ID: i use this to find out current week and total number of weeks for current year: now = datetime.now() weeks_in_year = int(date(now.year, 12, 31).strftime("%W")) current_week = int(date(now.year, now.month, now.day).strftime("%W")) is this the best way or is there a better way? Aljosa Mohorovic From hyoogle at gmail.com Fri Jul 11 20:34:02 2008 From: hyoogle at gmail.com (Hugh M) Date: Fri, 11 Jul 2008 20:34:02 -0400 Subject: palindrome function In-Reply-To: References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: > Basically, it reverses the list in place, so it modifies the list which > called it. It does not return a /new/ list which is a reversed version of > the original, as you expected it to. Since it doesn't return anything > explicitly, Python makes it return None. Hence, the comparison you are doing > is between the original list and a None, which is False, naturally. > Try this: > > spam = ['a', 'n', 'n', 'a'] > eggs = spam[:] > if spam.reverse() == eggs: > print "Palindrome" > > Um, wouldn't this suffer the same problem- spam.reverse() would return None, so None==eggs test would return false? I think you meant to say: spam = ['a', 'n', 'n', 'a'] eggs = spam[:] spam.reverse() if spam == eggs: print "Palindrome" -Hugh > -- > Denis Kasak > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jkrukoff at ltgc.com Wed Jul 30 16:50:04 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Wed, 30 Jul 2008 14:50:04 -0600 Subject: seemingly simple list indexing problem In-Reply-To: References: <5c118411-5703-44b3-888f-3785b517b8d4@u12g2000prd.googlegroups.com> <46b0becc-2f24-41de-a9e5-3013c6089d24@8g2000hse.googlegroups.com> Message-ID: <1217451004.4123.160.camel@jmk> On Wed, 2008-07-30 at 12:06 -0700, Tobiah wrote: > On Mon, 28 Jul 2008 23:41:51 -0700, iu2 wrote: > > > On Jul 29, 3:59 am, John Machin wrote: > >> On Jul 29, 8:10 am, John Krukoff wrote: > >> > >> > >> > >> > >> > >> > On Mon, 2008-07-28 at 16:24 -0500, Ervan Ensis wrote: > >> > > My programming skills are pretty rusty and I'm just learning Python so > >> > > this problem is giving me trouble. > >> > >> > > I have a list like [108, 58, 68]. I want to return the sorted indices > >> > > of these items in the same order as the original list. So I should > >> > > return [2, 0, 1] > >> > >> > > For a list that's already in order, I'll just return the indices, i.e. > >> > > [56, 66, 76] should return [0, 1, 2] > >> > >> > > Any help would be appreciated. > >> > >> > > -- > >> > >http://mail.python.org/mailman/listinfo/python-list > >> > >> > If your lists aren't so large that memory is an issue, this might be a > >> > good place for a variation of decorate, sort, undecorate. > >> > >> > >>> listToSort = [ 108, 58, 68 ] > >> > >>> decorated = [ ( data, index ) for index, data in > >> > >> > enumerate( listToSort ) ]>>> decorated > >> > >> > [(108, 0), (58, 1), (68, 2)]>>> result = [ None, ] * len( listToSort ) > >> > >>> for sortedIndex, ( ignoredValue, originalIndex ) in > >> > >> > enumerate( sorted( decorated ) ): > >> > ... result[ originalIndex ] = sortedIndex > >> > ...>>> result > >> > >> > [2, 0, 1] > >> > >> Simpliciter: > >> > >> > >> > >> >>> data = [99, 88, 77, 88, 66] > >> >>> [x[1] for x in sorted(zip(data, xrange(len(data))))] > >> [4, 2, 1, 3, 0] > >> > >> Use case? Think data == database table, result == index ...- Hide quoted text - > >> > >> - Show quoted text - > > > > I think it is wrong, using this on my data returns the wrong result > > data = [108, 58, 68, 108] > >>>> [x[1] for x in sorted(zip(data, xrange(len(data))))] > > [1, 2, 0, 3] > > It looked wrong to me at first, but I think this is correct. > The two largest numbers were at positions 0 and 3. They come > last in the result. 58 is the smallest, and was at position > 1, which is the first in the result. > > > > ** Posted from http://www.teranews.com ** > -- > http://mail.python.org/mailman/listinfo/python-list It's wrong for the OP's sample, at least: >>> data = [ 108, 58, 68 ] >>> [x[1] for x in sorted(zip(data, xrange(len(data))))] [1, 2, 0] Which should be [2, 0, 1], according to the OP. I don't think the problem description makes it clear until you stare at the example a bit, but he's asking for a list where each value is the index in the sorted list of the value in that position in the original list. What you've got here is the index in the original list of the value that would be in that location when sorted. Clear as mud? Stealing the quite clever __getitem__ as indirect key idea, this is as short a solution as I've got: >>> listToSort = [ 108, 58, 68 ] >>> result = [ None, ] * len( listToSort ) >>> for sortedIndex, originalIndex in enumerate( sorted( range( len( listToSort ) ), key = listToSort.__getitem__ ) ): ... result[ originalIndex ] = sortedIndex ... >>> result [2, 0, 1] I haven't benchmarked, but I bet it'd be better overall to do the range sort in place, instead of with sorted. I'd like to be able to get rid of the intermediate result initialization, but I haven't found a method that's sane. This'd be my entry for obfuscated one-liner, though :) >>> listToSort = [ 108, 58, 68 ] >>> import operator >>> map( operator.itemgetter( 1 ), sorted( dict( ( originalIndex, sortedIndex ) for sortedIndex, originalIndex in enumerate( sorted( xrange( len( listToSort ) ), key = listToSort.__getitem__ ) ) ).items( ) ) ) [2, 0, 1] -- John Krukoff Land Title Guarantee Company From drakonik at gmail.com Thu Jul 10 11:04:00 2008 From: drakonik at gmail.com (Nick Dumas) Date: Thu, 10 Jul 2008 11:04:00 -0400 Subject: Smal question In-Reply-To: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> References: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 This is easy. Simply create a .py file containing all the methods you want to share. Put this file in the same directory as the rest of your project files. In each of your project files that requires one of the methods, simply "import ". Python supports impromptu module creation, which is great just for circumstances like this. Hans M?ller wrote: > Hello group, > > I have some scripts sharing some common functions. > So what I'd like to have is a modern include. > Of course python does not have (with good reasons) no include statement. > But I'm too lazy to create a module which has to be installed into the > interpreter for some functions I need to share in a project. > Is there any idea to do this ? > > Thanks a lot > > Hans -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkh2JOAACgkQLMI5fndAv9gZiACeP3puvMknR2HQTOXKaNeBtC+h tyEAn3C6g9E5U5xXE4SQ7u368xdvkRx4 =J6Sv -----END PGP SIGNATURE----- From david.lyon at preisshare.net Tue Jul 15 07:37:40 2008 From: david.lyon at preisshare.net (David Lyon) Date: Tue, 15 Jul 2008 21:37:40 +1000 Subject: Using McMillan Installer, PyInstall or py2exe cross-platform? In-Reply-To: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> References: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <487C8C04.2030307@preisshare.net> Hi Hartmut, I can sympathise with you on this one... There are a few options... there is a python based "bake" make like program... that is useful... http://projects.bertram-scharpf.de/bake/bake1.html then there is Wine... that is a windows emulator under linux... that might be pretty easy.... http://www.winehq.org/ If you want to get more heavy-weight, then get a virtual machine. But as per your question... the above specified options might satisfy your requests for speed and ease of use without having to change O/S. Regards David Hartmut Goebel wrote: > Hi, > > has anybody used McMillan Installer, PyInstall or py2exe cross-platform? > > I have a Windows partition with Python installed there, so this would > "only" required working on a different directory and for a different OS. > Since I'm working on Linux, it's awful to boot Windows each time I > want to build a new release. > > Any hint in this area? > From maric at aristote.info Wed Jul 9 08:47:33 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 9 Jul 2008 14:47:33 +0200 Subject: (silly?) speed comparisons In-Reply-To: References: <84bdef3c0807081516g7872d1d8x2ecb448fd1fa900c@mail.gmail.com> Message-ID: <200807091447.34094.maric@aristote.info> Le Wednesday 09 July 2008 12:35:10 mk, vous avez ?crit?: > vector move_slice(vector& vec, int start, int stop, int > dest) I guess the point is to make a vector of referene to string if you don't want to copy string objects all around but just a word for an address each time. The signature should be : vector move_slice(vector& vec, int start, int stop, int dest) or vector move_slice(vector& vec, int start, int stop, int dest) -- _____________ Maric Michaud From circularfunc at yahoo.se Thu Jul 3 05:28:54 2008 From: circularfunc at yahoo.se (defn noob) Date: Thu, 3 Jul 2008 02:28:54 -0700 (PDT) Subject: PIL(Py Image lib), show() not showing picture... Message-ID: <84a8f15a-594f-4e02-aa89-b70932eae420@59g2000hsb.googlegroups.com> from PIL import Image import os print os.path.exists('C:/Users/saftarn/Desktop/images/blob.jpg') im2 = Image.open('C:/Users/saftarn/Desktop/images/blob.jpg') im2.show() first the command prompt pops up then the normal window to display pictures but it doenst show a picture. the prin os.path.exists returns true and opening the file by clicking on it works. ive also tried gif-files with no success. From bruno.desthuilliers at gmail.com Thu Jul 3 14:06:56 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 3 Jul 2008 11:06:56 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: <6d4bfmFp3aoU1@mid.uni-berlin.de> <0f6f795d-8041-463e-8e98-9d830ca3fc5b@l42g2000hsc.googlegroups.com> Message-ID: <45111722-3f2c-476d-8e7b-fd65cc5100a6@56g2000hsm.googlegroups.com> On 3 juil, 18:51, defn noob wrote: > well the reason i unzipped and placed it in site-packages was because > nothign happened when i ran setup.py(unzipped). What do you mean, "running setup.py unzipped" ??? The correct way to install a package is to: - unzip (untar, whatever) the archive somewhere in your own directory - cd to the unzipped directory - *from there*, run python setup.py install From bdesth.quelquechose at free.quelquepart.fr Sun Jul 27 14:25:57 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Jul 2008 20:25:57 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <488cd9ac$0$14746$426a74cc@news.free.fr> Marcus.CM a ?crit : > Well after reading some of these posts on "sacred python cow" on the > "self" , i would generally feel that most programmers > who started with C++/Java would find it odd. And its true, i agree > completely there should not be a need to put "self" into every single > member function. "member function" is C++. The way Python works is that you defines functions (inside or outside a class, that doesn't matter) that, when set as *class* attributes, are used as the *implementation* of the corresponding method. I think it's very important to use appropriate terms to understand what's really going on here. As soon as you understand that what you "def"ine is a *not* a method, but a *function* (eventually) used as the *implementation* of a method, the necessary declaration of the target object (instance or class) in the function's signature just makes sense - the usual way to make some object accessible to the body of a function is to pass this object as argument, isn't it ? (snip) > What could be done instead is :- > > 1. python should hardcode the keyword "self". So whenever this keyword > is used, it would automatically implied that it is > referring to a class scope variable. Usually, 'self' is used for *instance* attributes, you know. "class attribute" are attributes of the class object itself (that is, shared by all instances of the class). > This would be similar to how the > "this" keyword is used in C++. > > 2. Omit self from the parameter. Now how would it work for functions defined outside a class statement, but used as the implementation of a method ? def toto(self): # dummy exemple code return self class Tata(object): pass Tata.tutu = toto class Titi(object): tutu = toto (snip) From jzakiya at mail.com Sat Jul 19 15:39:28 2008 From: jzakiya at mail.com (jzakiya) Date: Sat, 19 Jul 2008 12:39:28 -0700 (PDT) Subject: Ultimate Prime Sieve -- Sieve Of Zakiya (SoZ) References: <5ebb27cd-e938-4f06-9aad-4ea056b851a9@c65g2000hsa.googlegroups.com> <0acbf903-0d27-411f-8fa5-40e2da21ee95@m36g2000hse.googlegroups.com> Message-ID: On Jun 18, 7:58?pm, George Sakkis wrote: > On Jun 13, 1:12 pm, jzakiya wrote: > > > The paper presents benchmarks with Ruby 1.9.0-1 (YARV). ?I would love > > to see my variousprimegenerators benchmarked with optimized > > implementations in other languages. ?I'm hoping Python gurus will do > > better than I, though the methodology is very very simple, since all I > > do is additions, multiplications, and array reads/writes. > > After playing a little with it, I managed to get a 32-47% improvement > on average for the pure Python version, and a 230-650% improvement > with an extra "import psyco; psyco.full()" (pasted athttp://codepad.org/C2nQ8syr) > The changes are: > > - Replaced range() with xrange() > - Replaced x**2 with x*x > - Replaced (a,b) = (c,d) with a=c; b=d > - Replaced generator expressions with list comprehensions. This was > the big one for letting psyco do its magic. > > I also tried adding type declarations and running it through Cython > but the improvement was much less impressive than Psyco. I'm not a > Pyrex/Cython expert though so I may have missed something obvious. > > George George, I took your code and included more efficient/optimized versions of SoZ versions P3, P5, P7, and P11. I ran the code on my PCLinuxOS, Intel P4, Python 2.4.3 system and noted this. The SoZ code run much faster than the SoA in pure Python. When psyco is used the SoA is significantly faster than the pure Python version. The SoZ versions are faster too, but now they are slower than the SoA. You can download the code from http://www.4shared.com/dir/7467736/97bd7b71/sharing.html It would be interesting to see how this code runs in newer versions of Python (Psyco). FYI, someone else coded P7 in C on a QuadCore Intel 9650 3.67GHz overclocked cpu, using multiple threads, and got it to be faster than the SoA, SoE, Here's some of his results (times in seconds). Case nPrime7x nPrime7x nPrime7x nPrime7x Atkin Zakiya Eratosthenes Zakiya (8 core 2.5ghz) 100 billion 52.58 44.27 50.56 200 b 110.14 92.38 108.99 88.01 300 b 169.81 140.92 167.47 400 b 232.34 190.84 228.08 177.72 500 b 297.44 241.84 291.28 600 b 364.84 293.92 355.27 273.04 700 b 434.33 346.97 420.41 800 b 506.67 400.97 486.72 373.29 900 b 579.58 456.53 555.09 1 trillion 654.03 513.11 624.00 479.22 Jabari From bogus.relic2 at cjb.net Thu Jul 3 14:19:39 2008 From: bogus.relic2 at cjb.net (relic) Date: Thu, 3 Jul 2008 11:19:39 -0700 Subject: Iphone Going 3G! References: <486cab43$1_2@news.tm.net.my> Message-ID: <20fqou.nq0.19.1@news.alt.net> fizzi wrote: > For the Iphone lovers out there, Wrong group. No weirdos here. From fabio.oikawa at gmail.com Mon Jul 28 16:22:17 2008 From: fabio.oikawa at gmail.com (Fabio Oikawa) Date: Mon, 28 Jul 2008 17:22:17 -0300 Subject: xlrd: error open_workbook Message-ID: <47e3464c0807281322l458d2634v3370d7429152ee95@mail.gmail.com> Hello. I am trying to open an .xls (excel) file using xlrd, but an error message occurs when I open the workbook. I can open any other .xls file made by myself (either by MS Excel 2003 SP3 in Windows Vista or by OpenOffice 2.0 in Debian) using the *open_workbook*function: wb = xlrd.open_workbook('myworkbook.xls') but when I try to open a file from one specific site, I get the error message: In [2]: wb = xlrd.open_workbook('balanco.xls') WARNING *** file size (81192) not 512 + multiple of sector size (512) WARNING *** OLE2 inconsistency: SSCS size is 0 but SSAT size is non-zero --------------------------------------------------------------------------- struct.error Traceback (most recent call last) /home/oikawa/DB/ /usr/lib/python2.4/site-packages/xlrd/__init__.py in open_workbook(filename, logfile, verbos ity, pickleable, use_mmap, file_contents, encoding_override, formatting_info) 380 bk.parse_globals() 381 else: --> 382 bk.parse_globals() 383 bk.get_sheets() 384 bk.nsheets = len(bk._sheet_list) /usr/lib/python2.4/site-packages/xlrd/__init__.py in parse_globals(self) 1309 self.handle_name(data) 1310 elif rc == XL_PALETTE: -> 1311 self.handle_palette(data) 1312 elif rc == XL_STYLE: 1313 self.handle_style(data) /usr/lib/python2.4/site-packages/xlrd/formatting.py in handle_palette(book, data) 550 "PALETTE record with %d colours\n", n_colours) 551 fmt = ' 552 colours = unpack(fmt, data) 553 assert book.palette_record == [] # There should be only 1 PALETTE record 554 # a colour will be 0xbbggrr error: unpack str size does not match format I ran the xlrd in both Windows Vista / Python 2.5 and Debian / Python 2.4.4 and got the same problem, so I suppose there is something wrong with the .xls files (which can be downloaded at www.fundamentus.com.br --> "Dados Hist?ricos" menu --> "Balancos em Excel" --> choose any company). However, I need the files in order to create my database system. Actually I want to build all companies' informations in a mySQL database, and the fastest and easiest way I found is to download .xls files, to get the data using xlrd-Python and to add them in the mySQL database. Any sugestions for both questions? Thanks in advance. Best regards, Fabio Oikawa -------------- next part -------------- An HTML attachment was scrubbed... URL: From hobesh at gmail.com Mon Jul 21 14:12:30 2008 From: hobesh at gmail.com (Zach Hobesh) Date: Mon, 21 Jul 2008 11:12:30 -0700 Subject: automating python programs Message-ID: Hi, I'm trying to figure out how to run a python program on a schedule, maybe every half an hour... Is this possible? Thanks! -Zach -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Fri Jul 11 17:13:53 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 11 Jul 2008 23:13:53 +0200 Subject: error with configure (svn 64857) In-Reply-To: <3e473cc60807110343s100b8866k1353b3e8e61049b7@mail.gmail.com> References: <487681e9$0$9745$9b622d9e@news.freenet.de> <48770603$0$9695$9b622d9e@news.freenet.de> <3e473cc60807110343s100b8866k1353b3e8e61049b7@mail.gmail.com> Message-ID: <4877CD11.7030608@v.loewis.de> > If didn't investigate everything but I solved the problem by adding > the "-static-libgcc" option: > > CFLAGS="-w -static-intel -static-libgcc" > > I think one should commit changes so configure can manage this. I don't think that change should be made. I'm almost certain that it is correct. Many people build Python with icc, and never reported any such problem. So there must something be wrong with your icc installation. Regards, Martin From LessPaul at gmail.com Tue Jul 29 13:28:52 2008 From: LessPaul at gmail.com (LessPaul) Date: Tue, 29 Jul 2008 10:28:52 -0700 (PDT) Subject: Newbie Python questions Message-ID: I recently discovered Python and see it as a great language to use for personal projects (and more). I made my living for over a decade as a coder in C, C++, ADA, Fortran, and Assembly before moving to systems engineering. I'm now retired, and would love to code again. I see Python as the perfect language to get a good program working in a short time. My question is in regard to GUI platforms. My primary target would be Windows, but I would also like be able to support Linux and Mac versions if possible. I'm also interested in using a system that also has support for pure C++ applications. As such, and after reading many web pages regarding Python GUIs, I believe I have the candidates narrowed down to pyQT and wxPython. The first question -- how steep is the curve to become proficient with the above GUI packages? If the answer is "not very" then there is no need for the following questions as I can try both on for size to see which I like best. However if it is a sizable investment in time, I'd like to maximize my efforts and choose the one I'll end up using in the end. The biggest hurdle I can see is the cost of the QT licence for commercial software, though apparently it can be acquired for a reasonable price via the BlackAdder package. Does purchasing the BlackAdder also include the needed software support for C++ development? Does the BlackAdder purchase also allow for licence of standard C++ apps? Since there appears to be no commercial licencing fee for wxWidgets/ wxPython, the last question is what do I gain from going QT over wx? I've seen great applications written with both (on my computer I have the wxPython Digsby and the pyQT apps "Mnemosyne" and "Anki". All seem to be solid. From larry.bates at websafe.com` Wed Jul 9 20:42:39 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 09 Jul 2008 19:42:39 -0500 Subject: Determining when a file has finished copying In-Reply-To: References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> Message-ID: keith wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Ethan Furman wrote: >> writeson wrote: >>> Guys, >>> >>> Thanks for your replies, they are helpful. I should have included in >>> my initial question that I don't have as much control over the program >>> that writes (pgm-W) as I'd like. Otherwise, the write to a different >>> filename and then rename solution would work great. There's no way to >>> tell from the os.stat() methods to tell when the file is finished >>> being copied? I ran some test programs, one of which continously >>> copies big files from one directory to another, and another that >>> continously does a glob.glob("*.pdf") on those files and looks at the >>> st_atime and st_mtime parts of the return value of os.stat(filename). >>>> From that experiment it looks like st_atime and st_mtime equal each >>> other until the file has finished being copied. Nothing in the >>> documentation about st_atime or st_mtime leads me to think this is >>> true, it's just my observations about the two test programs I've >>> described. >>> >>> Any thoughts? Thanks! >>> Doug >> The solution my team has used is to monitor the file size. If the file >> has stopped growing for x amount of time (we use 45 seconds) the file is >> done copying. Not elegant, but it works. >> -- >> Ethan > Also I think that matching the md5sums may work. Just set up so that it > checks the copy's md5sum every couple of seconds (or whatever time > interval you want) and matches against the original's. When they match > copying's done. I haven't actually tried this but think it may work. > Any more experienced programmers out there let me know if this is > unworkable please. > K > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (GNU/Linux) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iD8DBQFIdVkX8vmNfzrLpqoRAsJ2AKCp8wMz93Vz8y9K+MDSP33kH/WHngCgl/wM > qTFBfyIEGhu/dNSQzeRrwYQ= > =Xvjq > -----END PGP SIGNATURE----- If the files are large this could consume a lot of CPU and I/O to recalculate the checksum over and over. I would try the "hasn't been modified/accessed/created" in some amount of time first. -Larry From jason-sage at creativetrax.com Sat Jul 26 09:58:43 2008 From: jason-sage at creativetrax.com (jason-sage at creativetrax.com) Date: Sat, 26 Jul 2008 08:58:43 -0500 Subject: clearing all warning module caches in a session Message-ID: <488B2D93.2070800@creativetrax.com> Hi all, I just started using the warnings module in Python 2.5.2. When I trigger a warning using the default warning options, an entry is created in a module-level cache so that the warning is ignored in the future. However, I don't see an easy way to clear or invalidate these module-level caches of previously triggered warnings. That means that if I ever have a warning triggered with a "once" or a default warning level or filter, I can never see that warning again until I restart python (or figure out what module contains the cache and delete it manually). I thought resetwarnings would invalidate the module-level caches, so that I could trigger a "once" warning, then do resetwarnings() and make the default an "always" action and see my warning displayed again. At least, the name seems to indicate that all *warnings* would be reset, not just the filter list. But apparently resetwarnings() just clears the filter list, which is helpful, but doesn't do anything for the already-cached warnings. A very small change in the code would make this possible. Instead of making the value of the warnings module-level cache just "1", make it an integer which is incremented each time resetwarnings() is called. That way calling resetwarnings() can invalidate the cache (i.e., the warnings processing would ignore the cache record if the value wasn't the current integer). Again, the question is: is there an easy way to invalidate all the module-level caches of warnings so that the entire warning system is truly reset? Thanks, Jason From dan at catfolks.net Wed Jul 9 17:12:12 2008 From: dan at catfolks.net (Daniel Mahoney) Date: Wed, 09 Jul 2008 16:12:12 -0500 Subject: Determining when a file has finished copying References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> Message-ID: > Thanks for your replies, they are helpful. I should have included in > my initial question that I don't have as much control over the program > that writes (pgm-W) as I'd like. Otherwise, the write to a different > filename and then rename solution would work great. There's no way to > tell from the os.stat() methods to tell when the file is finished > being copied? I ran some test programs, one of which continously > copies big files from one directory to another, and another that > continously does a glob.glob("*.pdf") on those files and looks at the > st_atime and st_mtime parts of the return value of os.stat(filename). > From that experiment it looks like st_atime and st_mtime equal each > other until the file has finished being copied. Nothing in the > documentation about st_atime or st_mtime leads me to think this is > true, it's just my observations about the two test programs I've > described. > > Any thoughts? Thanks! > Doug Could you maybe us the os module to call out to lsof to see if anyone still has the target file open? I am assuming that when the write process finishes writing it would close the file. Check "man lsof" From Murphy.MarkS at epamail.epa.gov Tue Jul 22 10:23:36 2008 From: Murphy.MarkS at epamail.epa.gov (Murphy.MarkS at epamail.epa.gov) Date: Tue, 22 Jul 2008 10:23:36 -0400 Subject: Question about admin rights and IDLE Message-ID: Hi All, Apologies in advance for a potentially redundant posting -- I sent a similar question to the help box yesterday. I have a Geographic Info System (GIS) user that is having problems editing with Python IDLE on a WindowsXP machine unless she has admin rights. I had initially thought there might be a place where you can change the 'user rights' settings in Python, but wasn't able to find it. So, I did a fresh install of Python 2.5.1 and told it to be available to all users during the install process. The problem is that IDLE still seems to be available only to the person who has admin rights on a given machine. Can anybody make sense of this and help me fix it? Thanks in advance! Mark Mark S. Murphy GIS/Remote Sensing Analyst Computer Sciences Corporation ITS-EPA Contract 79 T.W. Alexander Drive Bldg. 4201Rm 3259 Research Triangle Park, NC 27709 Work 919-767-7088 FAX 919-767-7082 Cell 951-252-4325 Murphy.Marks at epa.gov From fkaanonymity at mail.com Thu Jul 3 14:06:18 2008 From: fkaanonymity at mail.com (Dave) Date: Thu, 3 Jul 2008 11:06:18 -0700 (PDT) Subject: imap4_SSL from behind a proxy server Message-ID: First to admit I'm a newbie at Python, IMAP, or SSL. And it's been a long time since I've posted anything to a Usenet group. But I've spent countless hours spinning my wheels on this one, so I thought I'd ask for help. I'm trying write some Python code to connect to Gmail from work, where I need to direct all non-HTTP traffic through a proxy server. Can anyone provide syntax which would redirect the imap4_SSL method through a proxy server:port? I suspect there are some environment variables which, when set, will do this very easily and elegantly. I also suspect there is a really complicated way to 'wrap' the imap classes so as to force requests to go through a proxy which, as a newbie, I am trying to avoid. FYI, I'm currently running Python 2.5.2. via IDLE on Windows XP. But when this project is done, I will move it to Linux. Thanks for any help. Dave fkaprince, at Gmail, dot-com From gherron at islandtraining.com Thu Jul 17 12:33:32 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 17 Jul 2008 09:33:32 -0700 Subject: unpacking with default values In-Reply-To: <335e7a21-e35e-41ee-9f92-fd4c2f6bf166@f36g2000hsa.googlegroups.com> References: <335e7a21-e35e-41ee-9f92-fd4c2f6bf166@f36g2000hsa.googlegroups.com> Message-ID: <487F745C.5080605@islandtraining.com> McA wrote: > Hi all, > > probably a dumb question, but I didn't find something elegant for my > problem so far. > In perl you can unpack the element of a list to variables similar as > in python > (a, b, c = [0, 1, 2]), but the number of variables need not to fit the > number > of list elements. > That means, if you have less list elements variables are filled with > 'undef' (None in python), if you have more list elements as necessary > the rest is ignored. > > How can I achieve this behaviour with python in an elegant and fast > way? > > Best regards > Andreas Mock > -- > http://mail.python.org/mailman/listinfo/python-list > Python 3.0 has something a bit like this. Excess values can be bound (as a list) to the last variable: a,b,*c = [1,2,3,4,5] will result in c containing [3,4,5]. In Python 2.x, you can't do that directly, but you should be able to create a function that lengthens or shortens an input tuple of arguments to the correct length so you can do: a,c,b = fix(1,2) d,e,f = fix(1,2,3,4) However, the function won't know the length of the left hand side sequence, so it will have to be passed in as an extra parameter or hard coded. Gary Herron From sturlamolden at yahoo.no Tue Jul 8 16:09:36 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 8 Jul 2008 13:09:36 -0700 (PDT) Subject: GUI Programming by hand not code with Python Code References: <7003b665-3227-47a7-ab06-1a486f87939a@a1g2000hsb.googlegroups.com> Message-ID: On 7 Jul, 04:33, jayjaygi... at hotmail.co.uk wrote: > Is their a program that lets you design a GUI by hand (like gambas) > not by code (like wxpython) but the commands are in python? > > A program similar to gambas or vb > > Gambas with python code instead of gambas code would be perfect. > > Thanks in advance I use wxFormBuilder with wxPython. Works like a charm. Design the GUI graphically, export it like a wx XML resource (.xrc). All you nedd to code in Python is the event handlers and the code to bind/hook the events. http://sturlamolden.blogspot.com/2008/03/howto-using-wxformbuilder-with-wxpython.html If you can accept a Windows only solution, you can use Microsoft's IronPython with MS VisualStudio. It will be just like using VB, except you are coding in Python. But remember that extension libraries to CPython is generally not available for IronPython. Insted you must rely more on .NET and COM/ActiveX objects. From ajdamico at gmail.com Wed Jul 23 17:28:10 2008 From: ajdamico at gmail.com (Anthony) Date: Wed, 23 Jul 2008 14:28:10 -0700 (PDT) Subject: Autocompletion and Interactive Tables in a Python IDE Message-ID: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Hi, I'm a FoxPro programmer, but I want to learn python before it's too late. I do a lot of statistical programming, so I import SPSS into python. In my opinion, the best features of Visual FoxPro 9.0 were: a) Intellisense (tells you what classes/methods are available and what variables go into a function) b) Code Completion (guesses your code after four letters) c) Data-Orientation; multiple data sessions can be open, data can be viewed easily Python's IDLE has only half of the first of these features. I did a lot of searching and found the PyDev extensions for Eclipse's Python IDE, and found that they've got Intellisense. I'm still missing b and c, and am getting extremely frustrated programming so slowly.. So two questions: Is there any package, gui, IDE, anything that will do FoxPro-style code completion? If it works in Eclipse, even better.. I can't find a good screenshot, but here's a better description: You type "BROW" and it pops up a window that says "BROWSE" ..at this point if you hit enter it completes the word.. and How can I view open SPSS data in one of the Python GUIs? Again, Eclipse would be the preference. Here's an example of how I'd like to browse the data: http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=vfptoolkit_figure02.tif I don't want to have to switch back and forth between Python and SPSS while I'm programming; I just want to stay in one of them.. What can I do? I feel extremely inefficient when I don't have these three features.. Thanks in advance. From mal at egenix.com Sat Jul 26 14:30:06 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Sat, 26 Jul 2008 20:30:06 +0200 Subject: Gracefull application exit. In-Reply-To: <00ba01c8eda7$2e61ecb0$8b25c610$@rawlins@thinkbluemedia.co.uk> References: <00ba01c8eda7$2e61ecb0$8b25c610$@rawlins@thinkbluemedia.co.uk> Message-ID: <488B6D2E.2040403@egenix.com> On 2008-07-24 18:06, Robert Rawlins wrote: > Chaps, > > > > I'm looking to implement an exit/termination process for an application > which can be triggered by A) a keyboard interrupt or B) termination of the > application as a Daemon using a signal. > > > > I have a whole bunch of tasks I want to perform as a cleanup before the > application is terminated, cleaning files, database calls, closing open > connections and a few other things. > > > > I know we have: > > > > # I'm the main application started method. > > if __name__ == "__main__": > > > > For starting an application, but do we have an equivalent methods for when > an application is terminated which we can use to close down any current > internal processes before the application exits? > > > > I'd really love to have your thoughts and experience on gracefully killing > an application. Warp your whole application into a main() function and then use: try: main() finally: cleanup() -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 25 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From circularfunc at yahoo.se Wed Jul 2 12:34:16 2008 From: circularfunc at yahoo.se (defn noob) Date: Wed, 2 Jul 2008 09:34:16 -0700 (PDT) Subject: Most efficient way to get pixelcolors of an image? Message-ID: <2c4e285c-f355-4e09-bd67-6de5656dc6c9@m36g2000hse.googlegroups.com> i want to process a large number of images and store their respective pixels in a matrix. what is the mostt efficient way of opening and checking them? i doubt pygame is made for this purpose :) i guess i could also use tkinter? and why cant i print out matrix after getting the pixels? do i have to deinit() pygame somehow? import pygame import sys import os print os.path.exists('C:/users/saftarn/desktop/images/bloba.bmp') pygame.init() screen = pygame.display.set_mode((800, 600)) image = pygame.image.load('C:/users/saftarn/desktop/images/bloba.bmp') imrect = image.get_rect() imrect = imrect.move(200, 200) matrix = [] while 1: pygame.display.flip() screen.fill((255,255,255)) screen.blit(image, imrect) pygame.event.wait() event = pygame.event.wait() for x in range(1, 301): for y in range(1, 301): matrix.append(screen.get_at((x, y))) #print matrix if event.type == pygame.QUIT: #print matrix sys.exit() From aahz at pythoncraft.com Thu Jul 10 18:31:41 2008 From: aahz at pythoncraft.com (Aahz) Date: 10 Jul 2008 15:31:41 -0700 Subject: Smal question References: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> Message-ID: [contextectomy] If we answer a small question, are we making smalltalk? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From tjreedy at udel.edu Tue Jul 8 14:52:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 08 Jul 2008 14:52:52 -0400 Subject: "in"consistency? In-Reply-To: References: Message-ID: David C. Ullrich wrote: > In article , > Terry Reedy wrote: >>> Is there a reason for the inconsistency? I would >>> have thought "in" would check for elements of a >>> sequence, regardless of what sort of sequence it was... >> It is not an inconsistency but an extension corresponding to the >> limitation of what an string element can be. > > It's an inconsistency. That doesn't mean it's a bad thing or that > I want my money back. It may well be a reasonable inconsistency - > strings _can_ work that way while it's clear lists had better not. > But it's an inconsistency. To decisively argue 'inconsistency' as factual or not, versus us having divergent opinions, you would have to supply a technical definition ;-) The math definition of 'leading to a contradiction' in the sense of being able to prove False is True, does not seem to apply here. However, a) In common English, 'in' and 'contains', applied to strings of characters (text), is understood as applying to substrings that appear in the text. This is also true of many other programming languages. 'Dictionary' contains 'diction'. This is even the basis of various word games. b) Python otherwise allows operators to vary in meaning for different classes. In any case, back to your original question: the extension of meaning, 'inconsistent' or not, was deliberated and adopted on the basis that the usefulness of the extension would outweigh the confusion wrought by the class-specific nature of the extension. (In other words, threads such as this *were* anticipated ;-) Terry Jan Reedy From M8R-yfto6h at mailinator.com Tue Jul 15 03:03:51 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Tue, 15 Jul 2008 00:03:51 -0700 Subject: Unicode confusion References: <1216053600.3028.59.camel@localhost.localdomain> Message-ID: "Jerry Hill" wrote in message news:mailman.14.1216054283.922.python-list at python.org... > On Mon, Jul 14, 2008 at 12:40 PM, Tim Cook > wrote: >> if I say units=unicode("?"). I get >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: >> ordinal not in range(128) >> >> If I try x=unicode.decode(x,'utf-8'). I get >> TypeError: descriptor 'decode' requires a 'unicode' object but received >> a 'str' >> >> What is the correct way to interpret these symbols that come to me as a >> string? > > Part of it depends on where you're getting them from. If they are in > your source code, just define them like this: > >>>> units = u"?" >>>> print units > ? >>>> print repr(units) > u'\xb0' > > If they're coming from an external source, you have to know the > encoding they're being sent in. Then you can decode them into > unicode, like this: > >>>> units = "?" >>>> unicode_units = units.decode('Latin-1') >>>> print repr(unicode_units) > u'\xb0' >>>> print unicode_units > ? > > -- > Jerry > Even with source code you have to know the encoding. for pre-3.x, Python defaults to ascii encoding for source files: test.py contains: units = u"?" >>> import test Traceback (most recent call last): File "", line 1, in File "test.py", line 1 SyntaxError: Non-ASCII character '\xb0' in file test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details The encoding of the source file can be declared: # coding: latin-1 units = u"?" >>> import test >>> test.units u'\xb0' >>> print test.units ? Make sure to use the correct encoding! Here the file was saved in latin-1, but declared utf8: # coding: utf8 units = u"?" >>> import test Traceback (most recent call last): File "", line 1, in UnicodeDecodeError: 'utf8' codec can't decode byte 0xb0 in position 0: unexpected code byte >>> -- Mark From saluk64007 at gmail.com Wed Jul 30 15:48:14 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Wed, 30 Jul 2008 12:48:14 -0700 Subject: Reasoning behind 'self' parameter in classes? In-Reply-To: <496954360807301227h1dea050eg735314beb0b5ff16@mail.gmail.com> References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> <4890ACE4.4060703@acm.org> <496954360807301227h1dea050eg735314beb0b5ff16@mail.gmail.com> Message-ID: On Wed, Jul 30, 2008 at 12:27 PM, Robert Dailey wrote: > > Given the code samples above, is there any technical reason why this cannot > be done? Thanks for the input guys, and thanks more over for keeping this > easy-going. > > -- > http://mail.python.org/mailman/listinfo/python-list > Well, the linked thread gives many reasons, but as mentioned it is a flamewar thread. Philosophically python is not an "object oriented" language per say, it has an object system, a not bolted on one I might add, but it doesn't force developers to use that methodology. You can be functional or procedural if you'd rather. Following this philosophy, when methods were designed, they were merely functions that got passed an instance as the first argument. The parser followed this design choice. As far as I understand it, the underlying method object is not different from a function argument, thus it cannot have any magic arguments built in. The only magic involved is the fact that the object, when calling a method, will pass its instance as the first argument. I don't believe there is any chance of this changing in python 3, python 4 is anyone's guess... This does allow some good things that come for free, like adding methods later, or changing functions into methods or methods into functions. If you start out developing a class, but feel a class is too bulky, you can delete the "class" line, dedent the methods, and have a set of functions instead for free. Or, if you have functions that are set up to take instances as their first argument already, you can bundle them up into a class very easily. If by "hack" you mean using features already available in the language to accomplish things, that kind of is what it is, and that's kind of what python is about. New syntax for a new feature is uncommon, but it happens. New syntax that breaks old code is very uncommon, and is only now coming out in python 3. And the biggest change in python 3 is to eliminate added syntax, such as print being a statement, and make the code reuse more python features rather than have every feature exist as an island. Print being a function, for instance, lets you use the same syntax for it that you use for other functions, making everything clearer and more unified. A common thing programmers might do when upgrading their code is to turn print statements into better logging functions - if print was a function in the first place this would be an easier task. Eliminating self doesn't accomplish much, and changes of this nature just don't get done without a good reason. It takes away something that might be annoying, but doesn't add anything. The benefits of changing have to be significant for a code change to break the existing syntax. Many people are upset even about some of the changes in python 3, that the benefits don't outweight the cost of change, and most of those changes are less damaging than playing around with the self businss would be :) So no, self not a mysterious thing that we should never question. Self is an understood thing that has been questioned very often (weekly, monthly) for many many years - there are not enough good reasons to bother with changing it, and there enough good reasons for it that it's best to keep it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kris at FreeBSD.org Wed Jul 9 08:06:33 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Wed, 09 Jul 2008 14:06:33 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <750f823a-f9de-4f81-9eb3-7c7b39237c90@y38g2000hsy.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <750f823a-f9de-4f81-9eb3-7c7b39237c90@y38g2000hsy.googlegroups.com> Message-ID: <4874A9C9.7020804@FreeBSD.org> John Machin wrote: >> Hmm, unfortunately it's still orders of magnitude slower than grep in my >> own application that involves matching lots of strings and regexps >> against large files (I killed it after 400 seconds, compared to 1.5 for >> grep), and that's leaving aside the much longer compilation time (over a >> minute). If the matching was fast then I could possibly pickle the >> lexer though (but it's not). >> > > Can you give us some examples of the kinds of patterns that you are > using in practice and are slow using Python re? Trivial stuff like: (Str('error in pkg_delete'), ('mtree', 'mtree')), (Str('filesystem was touched prior to .make install'), ('mtree', 'mtree')), (Str('list of extra files and directories'), ('mtree', 'mtree')), (Str('list of files present before this port was installed'), ('mtree', 'mtree')), (Str('list of filesystem changes from before and after'), ('mtree', 'mtree')), (re('Configuration .* not supported'), ('arch', 'arch')), (re('(configure: error:|Script.*configure.*failed unexpectedly|script.*failed: here are the contents of)'), ('configure_error', 'configure')), ... There are about 150 of them and I want to find which is the first match in a text file that ranges from a few KB up to 512MB in size. > How large is "large"? > What kind of text? It's compiler/build output. > Instead of grep, you might like to try nrgrep ... google("nrgrep > Navarro Raffinot"): PDF paper about it on Citeseer (if it's up), > postscript paper and C source findable from Gonzalo Navarro's home- > page. Thanks, looks interesting but I don't think it is the best fit here. I would like to avoid spawning hundreds of processes to process each file (since I have tens of thousands of them to process). Kris From JordanNealBerg at gmail.com Tue Jul 22 12:39:42 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Tue, 22 Jul 2008 09:39:42 -0700 (PDT) Subject: Question about inheritence References: Message-ID: <4400226c-f077-46d9-9310-a8d1d7f4dfda@w7g2000hsa.googlegroups.com> On Jul 22, 12:26?pm, Catherine Heathcote wrote: > If I create a new class inherited from another with a constructor, what > happens with the new class's constructer? > Thanks for your time. Well, the __init__ method of the subclass is called, and from within it you can call the superclass constructor. Here is a sample code: class A(): def __init__(self, bla): #do some stuff here class B(A): def __init__(self, bla2): #do some stuff here A.__init__(self,bla) From castironpi at gmail.com Fri Jul 18 02:31:07 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 17 Jul 2008 23:31:07 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> Message-ID: On Jul 17, 11:39?pm, Kay Schluehr wrote: > On 18 Jul., 01:15, castironpi wrote: > > > > > On Jul 17, 5:37 pm, I V wrote: > > > > On Thu, 17 Jul 2008 15:08:17 -0700, castironpi wrote: > > > > The Python disassembly is baffling though. > > > > >>>> y= 3 > > > >>>> dis.dis('x=y+1') > > > > You can't disassemble strings of python source (well, you can, but, as > > > you've seen, the results are not meaningful). You need to compile the > > > source first: > > > > >>> code = compile('y=x+1','-', 'single') > > > >>> dis.dis(code) > > > > ? 1 ? ? ? ? ? 0 LOAD_NAME ? ? ? ? ? ? ? ?0 (x) > > > ? ? ? ? ? ? ? 3 LOAD_CONST ? ? ? ? ? ? ? 0 (1) > > > ? ? ? ? ? ? ? 6 BINARY_ADD > > > ? ? ? ? ? ? ? 7 STORE_NAME ? ? ? ? ? ? ? 1 (y) > > > ? ? ? ? ? ? ?10 LOAD_CONST ? ? ? ? ? ? ? 1 (None) > > > ? ? ? ? ? ? ?13 RETURN_VALUE > > > > You may well find these byte codes more meaningful. Note that there is a > > > list of opcodes athttp://docs.python.org/lib/bytecodes.html > > > Oh. ?How is the stack represented? > > As a pointer to a pointer of PyObject structs. > > > Does it keep track of which stack > > positions (TOS, TOS1, etc.) are in what registers? ?Does stack > > manipulation consume processor cycles? > > Python does not store values in registers. It stores locals in arrays > and accesses them by position ( you can see the positional index in > the disassembly right after the opcode name ) and globals / object > attributes in dicts. > > For more information you might just download the source distribution > and look for src/Python/ceval.c. This file contains the main > interpreter loop. Oh. I was interpreting, no pun, that the column of numbers to the left indicated how many processor cycles were consumed in each operation. It doesn't quite make sense, unless BINARY_ADD can refer to memory outside of the registers, which I doubt on the basis that two addresses would have to fit into a single operation, plus the architecture opcode. Given that, what does that column indicate? I'm intimidated by the source but I may look. From mensanator at aol.com Thu Jul 3 17:49:40 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 3 Jul 2008 14:49:40 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> Message-ID: <7db52b03-7a8a-40c4-b3cb-f6dccd273b90@59g2000hsb.googlegroups.com> On Jul 3, 2:52?pm, Terry Reedy wrote: > Mensanator wrote: > > On Jul 3, 2:13?am, Bruno Desthuilliers > 42.desthuilli... at websiteburo.invalid> wrote: > >> Terry Reedy a ?crit : > >>> This has been added to itertools at least for 2.6/3.0 > >> Great ! > > > Well, it will be great at some point in the future > > when Python 2.6/3.0 have actually been released and > > The betas 'have actually been released' and I am happily using 3.0. ? But you're not using it for production work. Unless you're ignoring the recommendations. > The > core features that I care about have mostly been untouched and where > they have, they work. That's not the issue. > > > third party extensions such as gmpy have caught up. > > Not my personal concern. ? Right. Which is why your 3.0 specific advice is worthless. Those ARE personal concerns of just about everyone else. > And certainly not a direct concern for nearly > all uses of itertools.product. > > > Until then, such solutions are worthless, i.e., of no value. > > Why are you so anxious to generalize your personal negative views to > everyone else. ? Not to everyone else, to the new and inexperienced Pyhton users. Maybe you don't remember what it was like being a new user where you need to have such things pointed out to you. And I'm not being negative, just realistic. If I ask a question today, I want an answer I can use tomorrow, not one I can use six months from now. > Worthless to you, worthwhile to me. ? The OP's opinion is the only one that matters. What do you suppose is the percentage of posts on this newsgroup by those using 3.0? > And for someone who > does not need cross-products today or in the next few months, > potentially valuable information for when the final releases do arrive, > maybe in September. That's fine for them. It's been said here that they will be a minority for a long time. > > tjr From speedoman11 at yahoo.com Mon Jul 14 18:50:28 2008 From: speedoman11 at yahoo.com (Ty hensons) Date: Mon, 14 Jul 2008 15:50:28 -0700 (PDT) Subject: How can I save command prompt screen Message-ID: <401698.26103.qm@web44903.mail.sp1.yahoo.com> how can i save my command prompt screen? -------------- next part -------------- An HTML attachment was scrubbed... URL: From iainking at gmail.com Fri Jul 25 11:08:57 2008 From: iainking at gmail.com (Iain King) Date: Fri, 25 Jul 2008 08:08:57 -0700 (PDT) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> <4889e5bc$1@news2-rz-ap.ethz.ch> Message-ID: <331bd56e-e446-4b08-bf72-be7482051f32@y22g2000prd.googlegroups.com> On Jul 25, 3:39 pm, Suresh Pillai wrote: > That's a good comparison for the general question I posed. Thanks. > Although I do believe lists are less than ideal here and a different data > structure should be used. > > To be more specific to my case: > As mentioned in my original post, I also have the specific condition that > one does not know which nodes to turn ON until after all the > probabilities are calculated (lets say we take the top m for example). > In this case, the second and third will perform worse as the second one > will require a remove from the list after the fact and the third will > require another loop through the nodes to build the new list. So you need to loops through twice regardless? i.e. loop once to gather data on off nodes, do some calculation to work out what to turn on, then loop again to turn on the relevant nodes? If so, then I think the functions above remain the same, becoming the 2nd loop. Every iteration you do a first loop over the off_nodes (or them all for (1)) to gather the data on them, perform your calculation, and then perform one of the above functions (minus the setup code at the begining; basically starting at the 'for') as a second loop, with the goes_on function now returning a value based on the calculation (rather than the calculation itself as I had it). Performance should be similar. Iain From bruno.desthuilliers at gmail.com Mon Jul 14 12:34:29 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 14 Jul 2008 09:34:29 -0700 (PDT) Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> <6daf86f6-0a96-4811-90c4-2bc6ccbff9fb@x41g2000hsb.googlegroups.com> Message-ID: <2ebe7d8a-acac-488c-80b6-fdc4d7618f21@l42g2000hsc.googlegroups.com> On 14 juil, 11:51, James Fassett wrote: > On Jul 12, 12:18 am, George Sakkis wrote: > > > It relies on positional arguments, tuple unpacking and > > the signature of zip(), > > It moreso relies on the fact that: > > >>> t1 = (0,1,2,3) > >>> t2 = (7,6,5,4) > >>> [t1, t2] == zip(*zip(t1, t2)) > > True > > This is mathematically true given the definition of zip. To me that is > very functional. Basically, unpacking a pair list into zip is the > canonical definition of unzipping the list (which is exactly my > intention). > > > Second, it is less readable, > > For a Python programmer - you are correct. For someone familiar with > the use of zip (as described above) - I wonder. Since I am new to this > I can't say for sure. If I posted the same code to a Haskell list or a > ML list would their opinion be the same? You might find interesting than Python's list comprehensions were stolen from Haskell then !-) > > robust and efficient than the list comprehension. > > I don't know the internals of how the Python interpreter treats list > comprehensions According to a post on the pypy team's blog, mostly as sugar candy for the procedural version (IOW: the generated byte-code will be roughly equivalent). > and zip but it seems reasonable to assume an extra list > is created for the zip approach. > > However, in the limited functional code I have seen this is actually a > common practice. I would suppose in languages with lazy evaluation > this isn't a problem - but in Python it would be. Python has some kind of lazy evaluation too - look for yield, generator expressions, iterators, and the itertools package. From lepto.python at gmail.com Tue Jul 1 03:16:03 2008 From: lepto.python at gmail.com (oyster) Date: Tue, 1 Jul 2008 15:16:03 +0800 Subject: how to judge urllib.Request is finished? Message-ID: <6a4f17690807010016s44ec90c2p2603ec408ff3f025@mail.gmail.com> currently I am using [code] req=urllib2.Request(url) data='' if '' not in data: fd=urllib2.urlopen(req) data=fd.read() time.sleep(10) time.sleep(10) blahblah [/code] Is there any other ready-to-use function? And what if the internet connection is chocked so that the html page can not be loaded entirely? From mail at timgolden.me.uk Mon Jul 21 10:45:39 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 21 Jul 2008 15:45:39 +0100 Subject: ntlm authentication In-Reply-To: <7B3D44209E8C944288889D4132FEC4125B98D8@IMCSRV6.MITRE.ORG> References: <7B3D44209E8C944288889D4132FEC4125B98D8@IMCSRV6.MITRE.ORG> Message-ID: <4884A113.6070305@timgolden.me.uk> Neuberger, Sheldon N. wrote: > Is there any way to make urllib2 handle NTLM authentication? Frankly, I'd hate to try. Have a look at this: http://sourceforge.net/projects/ntlmaps/ in case it helps, either by providing a solution or at least by illustrating some code. In addition, look at the sspi package in the latest pywin32 releases. There some sample code in the demos area there, too. Haven't used it myself (and I know it's messy) but I'm sure someone must have. TJG From diordna at gmail.com Fri Jul 18 18:13:24 2008 From: diordna at gmail.com (Stephen Johnson) Date: Fri, 18 Jul 2008 18:13:24 -0400 Subject: Any Game Developers here? In-Reply-To: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: <4A235BC6-5E46-4402-AF2D-BA3DBC175517@gmail.com> I use the Pyglet library to make games. You want to look at the pyglet and pygame mailing lists, not this one. Use Google. In my opinion, PyGame is clunky and Pyglet is elegant, simple, and comprehensive. PyGame has more examples available, but Pyglet has great documentation and enough examples to answer any questions you might have. Both have active communities. -Steve Johnson On Jul 18, 2008, at 5:38 PM, Michael Lubker wrote: > Any people that use Python as the predominant language for their game > development here? > > ~Michael > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rschroev_nospam_ml at fastmail.fm Sun Jul 27 04:34:18 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 27 Jul 2008 10:34:18 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> References: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> Message-ID: Tim Roberts schreef: > python at bdurham.com wrote: >> For Win64-Itanium users: python-2.5.2.ia64.msi >> For Win64-AMD64 users: python-2.5.2.amd64.msi >> >> 1. It looks like the 64 bit versions of Python for Windows are CPU >> vendor specific, eg. it doesn't look like there's a single, universal >> executable for Windows 64 bit platforms. Is this true? > > It's true for ALL operating systems, not just Windows. The ia64 (Itanium) > and the amd64 are completely separate processors with VERY different > instruction sets. Maybe I'm wrong, but I have the impression that Malcolm is a bit confused about the different 64-bit processors from Intel and AMD. So, to clear things up a bit: - The Itanium (ia64) is a 64-bit processor made by Intel, mostly for use in high-end systems (servers etc.) IIRC. It's instruction set is indeed completely different from the i386 instruction set (though I think there's an emulation mode) - AMD64 (or x86-64 or x64 or EMT64 or Intel64) is a 64-bit instruction set from AMD which is an extension to the i386 instruction set, and runs 32-bit (and 16-bit) i386-code natively. But, and this is important, despite the name the instruction set is also used by Intel (though they call it EMT64 and made a few minor changes). If you have or buy a 64-bit computer, it almost certainly uses the AMD64 instruction set, even if it has an Intel CPU (if you have an Itanium or other 64-bit CPU, I suppose you would know; it would not be something you buy from the shelf in a regular computer store). So you almost certainly need the AMD64 version of Python. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From wtanksleyjr at gmail.com Thu Jul 31 09:54:59 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Thu, 31 Jul 2008 06:54:59 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Message-ID: <4609709f-dc0f-47cc-905e-1552a02ec3b6@r15g2000prd.googlegroups.com> John Machin wrote: > william tanksley wrote: > > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" > > 1. This isn't Unicode; it's missing the u"" (I printed using repr). > > 2. It's got the UTF-8 bytes there in the middle. > > In addition to the above results, > *WHAT* results? I don't see any repr() output, just your > interpretation of what you think you saw! That *is* the repr. I said it's the repr, and it IS. It's not an interpretation; it's a screenscrape. Really, truly. If I paste it in again it'll look the same. What do you want? Can I post something that will convince you it's a repr? Oh well. You guys have been immensely helpful; my mental model of how Python works was vastly backwards, so it's a relief to get it corrected. Thanks to that, I was able to hack my code into working. I wish I could get entirely correct behavior, but at this point the miscommunication is too strong. I'll settle for the hack I've got now, and hope iTunes doesn't ever change its XML encoding (hey, I think I've got cause to be optimistic). -Wm From kay.schluehr at gmx.net Mon Jul 28 13:45:41 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 28 Jul 2008 10:45:41 -0700 (PDT) Subject: ActiveState Code (the new Python Cookbook) has been launched References: Message-ID: On 28 Jul., 18:55, Trent Mick wrote: > Nick Craig-Wood wrote: > > Trent Mick wrote: > >> I happy to announce that ActiveState Code has been taken out of beta. > >> This is the new site replacing the ASPN Cookbooks -- in particular the > >> Python Cookbook. > > >> http://code.activestate.com/ > > > Looks great and much faster than the old site! > > Thanks! > > > Mind telling us how it is implemented? I'm guessing python/django by > > the url and the fact that you have python stuff on your home pages but > > I could be wrong! > > Yup, it is a Django-based site -- a pleasure to work with, that. Using > django-tagging, django-template-utils & universal feedparser (for > hooking in Atom content for News section on home page), django-voting, > python-markdown2 (for rendering comments, discussion/descriptions), > recaptcha-client (for feedback when not logged in), pygments (for syntax > coloring). > > I've just submitted the site tohttp://www.djangosites.org/ > > I hope to do some blog posts about some parts of the site soon and > release the small re-usable "feedback" app I've put together for getting > feedback on the site. > > Cheers, > Trent > > -- > Trent Mick > trentm at activestate.com Hmm... overview is lost on the new site. My 15" notebook does not even display 3 full recipes in a firefox browser window ( with some tabs being opened ). I didn't check out the site on my 12" notebook but I suspect it tends to be close to 1. Otherwise the whole screen is filled with administrative debris which is a pitty. The dialogs seem to be pretty responsive and straightforward though. I used "submit recipe", typed my login data and got the input form immediately - instead of the main page (!) in the old system which was gruesome in this respect. From bignose+hates-spam at benfinney.id.au Tue Jul 15 18:26:01 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jul 2008 08:26:01 +1000 Subject: Python internals References: <008ca729$0$20313$c3e8da3@news.astraweb.com> Message-ID: <87hcaq7pja.fsf@benfinney.id.au> Larry Bates writes: > Names are pointers in Python that point to values in memory. The term "pointer" carries much extra baggage for a programmer thinking of C (as the original poster is). Python names give no access to the "address" of the value, and don't need to be "de-referenced". I've had better success explaining Python names to such people in terms of "references": there is no "address" and no "de-reference" needed. Access the name, and you get its value. On the other hand, I prefer to avoid using either of those concepts, and talk in terms of "name tags" or "sticky notes". Names (and other references, like list elements) attach to the object, and have no other value or purpose. They don't affect the object they're attached to; they are entirely independent of other bindings to the same object; they re-bind to another object with no history of what they were bound to previously. The analogy is quite robust, and carries none of the confusing baggage of "variable" or "pointer" or other overloaded language terms. -- \ ?Are you pondering what I'm pondering?? ?I think so, Brain, but | `\ I don't think Kay Ballard's in the union.? ?_Pinky and The | _o__) Brain_ | Ben Finney From google at mrabarnett.plus.com Sun Jul 20 17:40:06 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 20 Jul 2008 14:40:06 -0700 (PDT) Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> <3db7c643-56ca-4d6e-99eb-16176e1a2e88@d19g2000prm.googlegroups.com> <7b2d0e3b-0ee4-4f1b-90d5-90eae9f258a0@u6g2000prc.googlegroups.com> <3dd3ce99-e75b-4d5c-84dc-7854abd9d0e1@w8g2000prd.googlegroups.com> Message-ID: <0e86b400-b8a1-444f-bb1f-db423ffae71f@59g2000hsb.googlegroups.com> On Jul 19, 6:34?am, Dennis Lee Bieber wrote: > On Fri, 18 Jul 2008 16:43:35 -0700 (PDT), John Machin > declaimed the following in comp.lang.python: > > > > > The only language I remember that had implicit typing was FORTRAN (GOD > > is real, but JESUS is an integer). > > Hadn't seen that one before -- maybe because I learned FORTRAN IV at a > college in the middle of west Michigan; I think half the population was > one step away from turning Amish > > I learned it by the word: Indian -- implicit integers began at I, and > ended with N. > You could've just used the first 2 letters of 'integer'! :-) From lxz3002 at yahoo.com.cn Wed Jul 2 21:40:22 2008 From: lxz3002 at yahoo.com.cn (Leo Lee) Date: Thu, 3 Jul 2008 09:40:22 +0800 Subject: wxPython: How can I get window's HANDLE in wxPython. Message-ID: I need a window's handle to be passed to external c++. Thanks in advance From jonas at codeazur.com.br Thu Jul 3 11:12:17 2008 From: jonas at codeazur.com.br (Jonas Galvez) Date: Thu, 3 Jul 2008 12:12:17 -0300 Subject: ANN: XML builder for Python In-Reply-To: <486CB9F3.3020902@livinglogic.de> References: <486C5CA1.3080105@behnel.de> <486C5D63.5030407@behnel.de> <486CB9F3.3020902@livinglogic.de> Message-ID: <10df03a30807030812g201f35aet87477a245ae71fc4@mail.gmail.com> Walter D?rwald wrote: > XIST has been using with blocks since version 3.0. > [...] > with xsc.Frag() as node: > +xml.XML() > +html.DocTypeXHTML10transitional() > with html.html(): > [...] Sweet! I don't like having to use the unary operator tho, I wanted something as simple as possible, so I wouldn't even have to assign a variable on the with block ("as something"). I plan to add some validation and error checking, but for generating feeds for my Atom store it's reasonably fast and lean (just over 50 lines of code). --Jonas Galvez, http://jonasgalvez.com.br/log From Maria.Gordon at afconsult.com Tue Jul 29 09:31:58 2008 From: Maria.Gordon at afconsult.com (Gordon Maria) Date: Tue, 29 Jul 2008 15:31:58 +0200 Subject: Defunct when using subprocess.Popen References: <6D3D064BBC122445A4577CE1895FA06501755913@afsegbgex1.af.se> Message-ID: <6D3D064BBC122445A4577CE1895FA06501755914@afsegbgex1.af.se> An HTML attachment was scrubbed... URL: From stochashtic at yahoo.ca Fri Jul 25 10:59:18 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 25 Jul 2008 16:59:18 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> Message-ID: <4889ea46$1@news2-rz-ap.ethz.ch> On Fri, 25 Jul 2008 16:51:42 +0200, Fredrik Lundh wrote: > Unless I'm missing something, your example keeps going until it's > flagged *all* nodes as "on", which, obviously, kills performance for the > first version as the probability goes down. The OP's question was about > a single pass (but he did mention "as the simulation progresses", so I > guess it's fair to test a complete simulation.) I was referring to multiple passes as in Iain' test cases. Although not necessarily till all nodes are ON, let's say to to a large proportion at least. From kyosohma at gmail.com Tue Jul 8 10:05:07 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 8 Jul 2008 07:05:07 -0700 (PDT) Subject: How to make python scripts .py executable, not bring up editor References: Message-ID: <1160b521-eebb-4338-a66b-fa79ac7e0019@c65g2000hsa.googlegroups.com> On Jul 7, 4:56?pm, korean_dave wrote: > From command Prompt, i type in a script, ?"tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? You need to add python.exe to your system's path. In Windows XP, you need right-click "My Computer", choose Properties, and then the Advanced tab. Click the Environment Variables button. Then go to the System Variables section and double-click the Path entry (you may have to scroll down to get to it). Notice that everything in this list is separated by semi-colons. You should be at the end of the list, so just put a semi-colon at the end and then type C:\Python24 Then it should work. You'll probably need to restart your command line window though, as it doesn't always take affect on open windows. HTH ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From half.italian at gmail.com Tue Jul 8 15:35:54 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Tue, 8 Jul 2008 12:35:54 -0700 (PDT) Subject: Python for Kids Message-ID: Pretty cool!! Our base will be *much* bigger in about twenty years. I remember doing Basic on my dads Apple IIe. http://wiki.laptop.org/go/Pippy#Summary From grante at visi.com Mon Jul 28 13:18:25 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 28 Jul 2008 12:18:25 -0500 Subject: write unsigned integer 32 bits to socket References: <9_KdnfSDZ9xHIRDVnZ2dnUVZ_gCdnZ2d@pdx.net> Message-ID: On 2008-07-28, Alan Franzoni wrote: > Scott David Daniels was kind enough to say: > >> Alan Franzoni wrote: > >> Please don't pass this misinformation along. >> >> In the struct module document, see the section on the initial character: >> Character Byte order Size and alignment >> @ native native >> = native standard >> < little-endian standard >> > big-endian standard >> ! network (= big-endian) standard > > Sure, that's is one way to do it... but I was answering > Micheal Torrie, who said: > >> htonl() call, and then when pulling it off the wire on the >> other end you'd use ntohl(). If you don't then you will have >> problems when the > > htonl() and ntohl() are available in Python in the socket > module, so: > 1) i was just pointing the OP to the right place where to find > such functions > 2) they work just the same way, hence I can't see why the > "struct" way should be the preferred one while the "socket" > way should be misinformation Yes, the socket module does have ntohX and htonX calls. But they're superfluous, since you still have to call struct.pack/unpack to convert integer objects to/from the byte-strings that are transferred via send() and recv() calls. Changing the initial "=" in the format string to a "!" eliminates the need to pass the integer objects though calls to socket.ntohX() and socket.htonX() -- Grant Edwards grante Yow! Do you have exactly at what I want in a plaid visi.com poindexter bar bat?? From walter at livinglogic.de Thu Jul 3 17:46:39 2008 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Thu, 03 Jul 2008 23:46:39 +0200 Subject: ANN: XML builder for Python In-Reply-To: <486D22CF.3000505@behnel.de> References: <486C5CA1.3080105@behnel.de> <486C5D63.5030407@behnel.de> <486D22CF.3000505@behnel.de> Message-ID: <486D48BF.3050007@livinglogic.de> Stefan Behnel wrote: > Hi, > > Walter D?rwald wrote: >> XIST has been using with blocks since version 3.0. >> >> Take a look at: >> http://www.livinglogic.de/Python/xist/Examples.html >> >> >> from __future__ import with_statement >> >> from ll.xist import xsc >> from ll.xist.ns import html, xml, meta >> >> with xsc.Frag() as node: >> +xml.XML() >> +html.DocTypeXHTML10transitional() >> with html.html(): >> with html.head(): >> +meta.contenttype() >> +html.title("Example page") >> with html.body(): >> +html.h1("Welcome to the example page") >> with html.p(): >> +xsc.Text("This example page has a link to the ") >> +html.a("Python home page", href="http://www.python.org/") >> +xsc.Text(".") >> >> print node.conv().bytes(encoding="us-ascii") > > Interesting. Is the "+" actually required? Are there other operators that make > sense here? I do not see what "~" or "-" could mean. Of course the node constructor could append the node to the currently active element. However there might be cases where you want to do something else with the newly created node, so always appending the node is IMHO the wrong thing. > Are there other operators that make > sense here? I do not see what "~" or "-" could mean. > > Or is it just a technical constraint? You need *one* operator/method that appends a node to the currently active block without opening another new block. This operator should be short to type and should have the right connotations. I find that unary + is perfect for that. > I'm asking because I consider adding such a syntax to lxml as a separate > module. And I'd prefer copying an existing syntax over a (badly) home grown one. "Existing syntax" might be a little exaggeration, I know of no other Python package that uses __pos__ for something similar. (But then again, I know of no other Python package that uses with block for generating XML ;)). Servus, Walter From jadamwilson2 at gmail.com Wed Jul 23 15:37:06 2008 From: jadamwilson2 at gmail.com (jadamwil) Date: Wed, 23 Jul 2008 12:37:06 -0700 (PDT) Subject: fromfile error on windows, not mac References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> Message-ID: I found the problem: I thought it was opening in binary mode on BOTH windows and the mac, but on windows I passed "rb" with double quotes, not 'rb' with single quotes to the open file function. Changing it to 'rb' fixed it. On Jul 23, 8:25?am, Tommy Nordgren wrote: > One question : Did you remember to open the file in binary mode? > This MUST be done on windows. > On 22 jul 2008, at 06.36, jadamwil wrote: > > > > > Hello, > > I am using the numpy fromfile function to read binary data from a file > > on disk. The problem is that the program runs fine on a Mac, but gives > > an error or warning on windows when trying to read the data. I use it > > like this: > > > Signal = zeros((N, 16), dtype=float32) > > for sample in range(0, N): > > ?# this function gets the next position in the file to seek to > > ?s = getFilePos(sample) > > > ?# go to the correct location in the file; this IS checked to make > > sure it is within the file > > ?mFile.seek(s) > > > ?# read the 16 float32 values from the file > > ?D = fromfile(mFile, dtype=numpy.float32, 16) > > > ?# save D in Signal > > ?Signal[sample, :] = D > > > This will fail when sample is ~4. If I change the range to (5,N), > > skipping the "bad" file location, it will run fine for a few samples, > > and then give another error. The message it gives is: > > "16 items requested but only 7 read" > > > So D is a 7x1 vector, and the program dies when it tries to assign D > > to the slice of Signal ("ValueError: shape mismatch: objects cannot be > > broadcast to a single shape"). > > > On windows, the Python version is 2.5.2, and the most recent numpy and > > scipy are being used as well. I tried using Enthought, but it gave > > this error as well, in addition to a c runtime error whenever I > > imported scipy (which is another post topic...). > > > Any ideas on what might be causing this? Is there a way to debug the > > fromfile function? And, remember, this works perfectly on a Mac. Would > > compiling everything (python, scipy, numpy) potentially solve this? > > > Thanks! > > -- > >http://mail.python.org/mailman/listinfo/python-list > > ---------------------------------- > Skinheads are so tired of immigration, that they are going to move to ? > a country that don't accept immigrants! > Tommy Nordgren > tommy.nordg... at comhem.se From fredrik at pythonware.com Wed Jul 16 20:39:32 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 02:39:32 +0200 Subject: Manually prompting garbage collection In-Reply-To: References: <20080716230911.GD22400@monkey.ucolick.org> <20080716235656.GE22400@monkey.ucolick.org> Message-ID: Fredrik Lundh wrote: > Do these objects have direct references to a resource that you're > explicitly destroying from your C code? and yes, if this is the problem, the correct solution is to create an separate object type that's designed to manages the resource and act as a proxy against it, and then let all operations against the resource (from other objects) go via the proxy. never let more than one object "own" an external resource. if you need to explicitly kill the external resource, design the proxy so you can tell it to ignore (or reject) any subsequent calls to the resource from other parts of the program. From gherron at islandtraining.com Fri Jul 18 18:13:56 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 18 Jul 2008 15:13:56 -0700 Subject: Any Game Developers here? In-Reply-To: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: <488115A4.3070201@islandtraining.com> Michael Lubker wrote: > Any people that use Python as the predominant language for their game > development here? > You can find several whole (and reasonably large) communities of Python/Game developers associated with some Open Source projects: These two come to mind immediately. (Both have active new groups.) Pygame: http://www.pygame.org/news.html Pyglet: http://pyglet.org/ Gary Herron > ~Michael > -- > http://mail.python.org/mailman/listinfo/python-list > From circularfunc at gmail.com Mon Jul 21 23:01:35 2008 From: circularfunc at gmail.com (ssecorp) Date: Mon, 21 Jul 2008 20:01:35 -0700 (PDT) Subject: tail-rec decorator, well still blows the stack... Message-ID: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 so I try it and when I run: @Decorators.tail_recursion def fibtr(n): def fibt(a, b, n): if n <= 1: return b else: return fibt(b, a + b, n - 1) if n == 0: return 0 else: return fibt(0, 1, n); it still blows the stack. so what is the point? is it impossible to get "real" tail-recursion in Python? From vinay_sajip at yahoo.co.uk Wed Jul 16 09:38:56 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 16 Jul 2008 06:38:56 -0700 (PDT) Subject: Logging to different addressees References: <8df30038-86c1-4376-b046-a50f2bcf0a2b@s50g2000hsb.googlegroups.com> <7b829a76-ba2c-4cb7-b216-0c9c01e5cd02@f36g2000hsa.googlegroups.com> <4d3df1d9-339b-43b2-9f25-c792e9bf549c@k13g2000hse.googlegroups.com> <4e30c301-294c-4160-8cb8-c924aed00f71@f63g2000hsf.googlegroups.com> Message-ID: <9566e05f-7ad6-499d-8404-52d60e23b6e8@m36g2000hse.googlegroups.com> On Jul 16, 8:55 am, McA wrote: > Thank you for that snippet. That means, that the root-logger does > inherit > EVERY message (if it fits to the level and isn't filtered) and the > inheritage chain is build by the chosen logger names, e.g. > messages tologging.getLogger('tree.leave') would also show up inlogging.getLogger('tree') automatically? Yes. > If this is true, how can I avoid this "bubbling up" if I would like > to? > (You see, that's a new question, but I want to take the chance to get > the answers from you personally ;-) > > Hope not to bother. > Use the propagate flag, which is mentioned in the documentation. In fact, please make sure you've reviewed all the documentation before posting, as the documentation is intended to answer the more straightforward and common questions which come up. Best regards, Vinay Sajip From fredrik at pythonware.com Thu Jul 17 05:13:26 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 11:13:26 +0200 Subject: Remove some characters from a string In-Reply-To: <35cff1a6-74f6-4a68-b81e-71d8ff9c4633@a70g2000hsh.googlegroups.com> References: <35cff1a6-74f6-4a68-b81e-71d8ff9c4633@a70g2000hsh.googlegroups.com> Message-ID: Julien wrote: > I can't seem to find the right regular expression to achieve what I > want. I'd like to remove all characters from a string that are not > numbers, letters or underscores. > > For example: > >>>> magic_function('si_98%u^d at .as-*gf') > str: 'si_98udasgf' the easiest way is to replace the things you don't want with an empty string: >>> re.sub("\W", "", "si_98%u^d at .as-*gf") 'si_98udasgf' ("\W" matches everything that is "not numbers, letters, or underscores", where the alphabet defaults to ASCII. to include non-ASCII letters, add "(?u)" in front of the expression, and pass in a Unicode string). From pdorange at pas-de-pub-merci.mac.com Wed Jul 2 11:49:31 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Wed, 2 Jul 2008 17:49:31 +0200 Subject: Trouble using pinckle References: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <1ijgp2r.1j1k5xwwbtiwcN%pdorange@pas-de-pub-merci.mac.com> C?dric Lucantis wrote: > Here self is only a local variable and its meaning is only a convention. So > assigning it to a new value won't change the object itself (and is not a good > idea as it may be confusing for the reader). Thanks, i was thinking about something like that. > You should either use a static method which returns a new object: > > class Prefs (object) : > > def save (self, f) : > pickle.dump(self, f) > > @staticmethod > def load (f) : > return pickle.load(f) > > and load it with "prefs = Prefs.load(filename)" > > or store all the values in a dictionary and only pickle this object: > > class Prefs (object) : > > def __init__ (self) : > self.values = { 'test': 1, ... } > > def save (self, f) : > pickle.dump(self.values, f) > > def load (self, f) : > self.values = pickle.load(f) I try the staticmethod, it works fine. Very helpful. But i don't like it very much, it seems 'complicated' (python was supposed to be simple). I'll also try the dictionnary method. My final idea was that a dictionnary would be perhaps simple in the future to save/load as XML and a parser. But perhaps i'm wrong with my vision of python. On a more global perspective, what are the best method to implement a simple config file with pyhton. Assuming i finally want to made a bundle app for Mac, Windows and perhaps Linux. I develop on Mac, and on this platform the config fil (preferences) have to be stored in a special directory : ~/Library/Preferences, no problem. But on other platform that's not the same directory and perhaps i would also faced to permissions issues... But first is there a way to determine on which platfrom the python script is running ? -- Pierre-Alain Dorange Vid?o, DV et QuickTime Clarus, the DogCow From norseman at hughes.net Tue Jul 8 17:13:38 2008 From: norseman at hughes.net (norseman) Date: Tue, 08 Jul 2008 14:13:38 -0700 Subject: Cross Compiler for Python? In-Reply-To: <001101c8e0d2$36a50ec0$0d00a8c0@hendrik> References: <001101c8e0d2$36a50ec0$0d00a8c0@hendrik> Message-ID: <4873D882.6090109@hughes.net> Hendrik van Rooyen wrote: > norseman wrote: > >> ================================================== >> In case all else fails: >> >> This is not a cookbook answer, but: >> 1) gnu's gcc will compile to 16,32 or 64 bit intel architectures >> OK, the 32 bit version compiles to 16 or 32 & the 64 should. >> The 64 will run 32 bit programs, including the 32 bit gcc. >> chgroot can be (messy but) useful to maintain separation. >> 2) info gcc and look for compiler directives >> then info nasm and look for directives >> same for the linker >> I'm not specific because I use Slackware and different >> distros can use different modules. You may have an assembler >> with a different name. Switches can be different and so >> forth. >> On Slackware the installpkg (for tarballs already compiled) records the >> locations of where things go in /var/log/packages. I have to assume >> other distros have something similar since these are used to remove >> things later. Can we say 'updates'? If not you will need to wade >> through the .configure and Makefiles to root out what happens to get >> 'vanilla' locations. >> >> Like I said, it's not cookbook, but it will get you there and you will >> gain quite an insight into Linux. While the path may not be well marked >> in Linux, there usually is one. >> >> Sorry I don't have a more straight forward approach. >> >> - Steve >> > > Thanks Steve, for the tips. > > In a sense, I have dreaded an answer like this, as it is cold comfort > to realise that I will be hassled off my objective to take a side trip > through Linux's complexities, just so that I can play with the hardware > to evaluate if we can use it for what we want to do. > > I had fondly hoped that somebody would have blazed the way > before me. But it seems not. Tough. > > I will report here what I do and find - It may help some other > poor sod some day... > > - Hendrik > > > -- > http://mail.python.org/mailman/listinfo/python-list > ============================================= ....dreaded.... Yep! I know the feeling. Got lots of those T-Shirts. ;) I re-read your original post. I got the feeling the eBox is running a stripped down Linux. Is that so? If it is, then: You mention pcmcia. Is it external, a plug in? Do any of your desktops/etc have pcmcia slots? Because if so..... 1) Card can be mounted on your machine 2) Compile and install can be direct to card (rem 32bit output) just change the install path(s). Look over the eBox /lib ( I'm assuming Linux again) and put that lib path first in the compile command line. If no desktop pcmcia adapter - pay the $40 or so for an USB attachable pcmcia adapter sample: plug in card (if current drives on desktop are scsi or sata drives you may need to change sda to sdb or sdc or .... use fdisk /dev/sda to check existence. the single letter 'q' to exit without changing anything. Careful with fdisk - damage comes quickly, easily and unrepairable. All you are after is which letter to use. Last one before No such drive is the one. ) cd /mnt mkdir sda mount /dev/sda1 /mnt/sda ls /mnt/sda should give base dir listing of flashdrive (linux will treat the pcmcia flash as a removable HardDrive) install to /mnt/sda/usr/local/lib (or /mnt/sda/--where ever--) then: back on eBox cd /mnt mkdir sda cd sda ln -s /usr usr I did the soft link process above on my machine, then: ls /mnt/sda/usr/local/lib/python2.5 should list contents correctly (and does on my machine since it is located in /usr/local/lib/python2.5) thus keeping compile and install paths working. The use of the midnight commander (mc) with card mounted makes transferring whole trees simple. Soft links were invented for a reason! OF COURSE, if the eBox is not running Linux, all this is useless! ;) Steve norseman at hughes.net From bignose+hates-spam at benfinney.id.au Mon Jul 7 17:38:20 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 08 Jul 2008 07:38:20 +1000 Subject: "in"consistency? References: Message-ID: <87vdzhwf1v.fsf@benfinney.id.au> "David C. Ullrich" writes: > >>> 'ab' in 'abc' > True > >>> [1,2] in [1,2,3] > False > Is there a reason for the inconsistency? Probably. The special behaviour of string types was changed in Python 2.3, according to that document. -- \ ?I put contact lenses in my dog's eyes. They had little | `\ pictures of cats on them. Then I took one out and he ran around | _o__) in circles.? ?Steven Wright | Ben Finney From squishywaffle at gmail.com Thu Jul 31 10:41:34 2008 From: squishywaffle at gmail.com (squishywaffle at gmail.com) Date: Thu, 31 Jul 2008 07:41:34 -0700 (PDT) Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> <6fe0scFaus40U1@mid.uni-berlin.de> Message-ID: <6bc8bc07-eab0-4303-b8a4-c9470f96038d@c65g2000hsa.googlegroups.com> > How much more liberal can it get than MIT-licensed? Again, the licensing issue is everything to do with the original library distributor, NOT ctypes. > But then, if you insist, go down the hard road. Irrelevant and unnecessary. If you don't want to help, don't please don't reply. From mcmurtri at dslextreme.com Fri Jul 11 23:18:05 2008 From: mcmurtri at dslextreme.com (Kevin McMurtrie) Date: Fri, 11 Jul 2008 20:18:05 -0700 Subject: paypal wholesale men jordans 17 (paypal accept)(www super-saler com References: <5d746374-d2a0-411e-bf60-87256a219b7c@m44g2000hsc.googlegroups.com> <87skuhqerl.fsf@benfinney.id.au> Message-ID: In article <87skuhqerl.fsf at benfinney.id.au>, Ben Finney wrote: > WDC writes: > > > On Jul 10, 10:33?pm, 128 wrote: > > [?] > > > > > Is that spam i spy? > > It is, clearly. Please don't make the problem worse by repeating the > entire thing. I strongly recommend dropping all articles with "googlegroups.com" in the Message-ID. Some groups are getting hit with hundreds of Google spams a day and it's only going to get worse. -- I will not see your reply if you use Google. From kris at FreeBSD.org Thu Jul 10 13:15:13 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Thu, 10 Jul 2008 19:15:13 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <1215704825.11618.6.camel@aalcdl07.lib.unc.edu> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <1343fa73-fd32-46c3-8a75-0efc85b2660e@a70g2000hsh.googlegroups.com> <1215704825.11618.6.camel@aalcdl07.lib.unc.edu> Message-ID: <487643A1.3070705@FreeBSD.org> J. Cliff Dyer wrote: > On Wed, 2008-07-09 at 12:29 -0700, samwyse wrote: >> On Jul 8, 11:01 am, Kris Kennaway wrote: >>> samwyse wrote: >>>> You might want to look at Plex. >>>> http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/ >>>> "Another advantage of Plex is that it compiles all of the regular >>>> expressions into a single DFA. Once that's done, the input can be >>>> processed in a time proportional to the number of characters to be >>>> scanned, and independent of the number or complexity of the regular >>>> expressions. Python's existing regular expression matchers do not have >>>> this property. " >>> Hmm, unfortunately it's still orders of magnitude slower than grep in my >>> own application that involves matching lots of strings and regexps >>> against large files (I killed it after 400 seconds, compared to 1.5 for >>> grep), and that's leaving aside the much longer compilation time (over a >>> minute). If the matching was fast then I could possibly pickle the >>> lexer though (but it's not). >> That's funny, the compilation is almost instantaneous for me. >> However, I just tested it to several files, the first containing >> 4875*'a', the rest each twice the size of the previous. And you're >> right, for each doubling of the file size, the match take four times >> as long, meaning O(n^2). 156000*'a' would probably take 8 hours. >> Here are my results: >> >> compile_lexicon() took 0.0236021580595 secs >> test('file-0.txt') took 24.8322969831 secs >> test('file-1.txt') took 99.3956799681 secs >> test('file-2.txt') took 398.349623132 secs > > Sounds like a good strategy would be to find the smallest chunk of the > file that matches can't cross, and iterate your search on units of those > chunks. For example, if none of your regexes cross line boundaries, > search each line of the file individually. That may help turn around > the speed degradation you're seeing. That's what I'm doing. I've also tried various other things like mmapping the file and searching it at once, etc, but almost all of the time is spent in the regexp engine so optimizing other things only gives marginal improvement. Kris From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 09:07:07 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 15:07:07 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <87zlo7y2wn.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <32e12408-fc9f-4eb4-8b9d-fb7fa69bd2fc@f36g2000hsa.googlegroups.com> <87zlo7y2wn.fsf@physik.rwth-aachen.de> Message-ID: <48889a72$0$25165$426a74cc@news.free.fr> Torsten Bronger a ?crit : > Hall?chen! > > Kay Schluehr writes: > >> On 24 Jul., 11:40, Torsten Bronger >> wrote: >>> Bruno Desthuilliers writes: >>> >>>> [...] >>>> >>>> How would you handle this case with an implicit 'self' : >>>> >>>> class Foo(object): >>>> pass >>>> >>>> def bar(self): >>>> print self >>>> >>>> Foo.bar = bar >>> Just like this. However, the compiler could add "self" to >>> non-decorated methods which are defined within "class". >> And $self2, $self3, ... to the object methods of nested classes >> and $cls2, $cls3, ... to the classmethods of those classes...? > > One could surely find ways to realise this. However, the design > goal should be: Make the frequent case simple, and the rare case > possible. Given the (more and more prominent) use of decorators, metaclasses and other meta-programming techniques in Python, I'm not sure the cases where you really need access to Python's object model inners are that "rare". Not in my code at least. From ivlenin at gmail.com Thu Jul 17 18:37:59 2008 From: ivlenin at gmail.com (I V) Date: Thu, 17 Jul 2008 22:37:59 GMT Subject: interpreter vs. compiled References: Message-ID: On Thu, 17 Jul 2008 15:08:17 -0700, castironpi wrote: > The Python disassembly is baffling though. > >>>> y= 3 >>>> dis.dis('x=y+1') You can't disassemble strings of python source (well, you can, but, as you've seen, the results are not meaningful). You need to compile the source first: >>> code = compile('y=x+1','-', 'single') >>> dis.dis(code) 1 0 LOAD_NAME 0 (x) 3 LOAD_CONST 0 (1) 6 BINARY_ADD 7 STORE_NAME 1 (y) 10 LOAD_CONST 1 (None) 13 RETURN_VALUE You may well find these byte codes more meaningful. Note that there is a list of opcodes at http://docs.python.org/lib/bytecodes.html From gagsl-py2 at yahoo.com.ar Tue Jul 15 01:51:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 02:51:39 -0300 Subject: How to write a custom tracer/profiler? References: <28ee2efb-6c8a-4884-8d25-4b91fb73ebb2@f63g2000hsf.googlegroups.com> Message-ID: En Mon, 14 Jul 2008 23:48:20 -0300, AK at SYD escribi?: > The main logic will issue a number of calls to the DS in order to get > the data it needs and then carry out some calculations. > > I want to have a non-intrusive way to find out all the DS data > requested by the main logic. > > One thing to note, the DS is a big, messy bit of code. So putting > logger everywhere within DS and main logic is not a reliably, > satisfactory solution. > > I have thought about using somehting like aspect. But seems to me > there is no mature, widely-used aspect lib out there. > > Another idea is: let's roll a custom tracer/profiler. Whenever any > method/attributes in the DS package are called, the return values will > be logged. > > I have taken a quick look at profile.py in python 2.4, It seems sys > module will pass a frames to the profile class. Can I access the > return value of a function via these frame objects? You don't have to use a profiler; just replace the original DS functions that you're interested in monitoring, with a "wrapped" version that logs its parameters and then calls the original code. A skeleton example (suppose DS.open is one function you want to monitor): import DS original_open = DS.open def wrapped_open(*args, **kw): trace("open", *args, **kw) return original_open(*args, **kw) DS.open = wrapped_open This approach has some problems (it does not preserve the original function signature, by example). You may overcome this (and other problems) using the decorator module from M. Simionato; see -- Gabriel Genellina From mwalsh at groktech.org Mon Jul 14 02:21:19 2008 From: mwalsh at groktech.org (Martin Walsh) Date: Mon, 14 Jul 2008 01:21:19 -0500 Subject: Why is there no GUI-tools like this for Windows? In-Reply-To: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> References: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> Message-ID: <487AF05F.4050409@groktech.org> maestro wrote: > I can just do the layout with my mouse and then there is a program > that writes the code for me. > GUI-programming is hard for no reason. One good program then forever > easy... > > Is there not something like this for Python/Windows? Is the Linux one > only for ruby or for any language? > I only watched a small part of the video so I'm making some assumptions about it's content. But there is nothing preventing you from using the same(/similar) toolchain on windows, which I believe would include python, pygtk, the gtk+ runtime, and glade -- last I checked all have windows binary distributions. To quote the glade website """ The user interfaces designed in Glade are saved as XML, and by using the libglade library these can be loaded by applications dynamically as needed. By using libglade, Glade XML files can be used in numerous programming languages including C, C++, Java, Perl, Python, C#, Pike, Ruby, Haskell, Objective Caml and Scheme. Adding support for other languages is easy too. """ HTH, Marty From deets at nospam.web.de Mon Jul 28 08:19:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 14:19:57 +0200 Subject: Proxy server? References: Message-ID: <6f5rteF89muqU2@mid.uni-berlin.de> Gary wrote: > I've seen examples for HTTP and FTP use, but not for simply any TCP data > on any port, which is what I require. Can anyone please point me in the > right direction? For what? How to use such a thing, a transparent proxy? There is nothing to it, just plug it between your router and the internet, that's all. Or do you want to know how to capture all traffic using some other process, for analysis? Use wireshark. Diez From vino341 at gmail.com Sat Jul 19 04:06:35 2008 From: vino341 at gmail.com (hot rathi) Date: Sat, 19 Jul 2008 01:06:35 -0700 (PDT) Subject: Your win 10, 000$ in my groups Pls register your name and address in below of the website http://www.geocities.com/cathrina39 http://namithawithyou.blogspot.com/ Message-ID: <7f3d4b94-5fff-4cad-b688-d56aeb4ad1a2@v1g2000pra.googlegroups.com> Your win 10,000$ in my groups Pls register your name and address in below of the website http://www.geocities.com/cathrina39 http://namithawithyou.blogspot.com/ From socyl at 987jk.com.invalid Tue Jul 29 17:37:43 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 21:37:43 +0000 (UTC) Subject: iterating "by twos" References: Message-ID: In Terry Reedy writes: >kj wrote: >> Is there a special pythonic idiom for iterating over a list (or >> tuple) two elements at a time? >> >> I mean, other than >> >> for i in range(0, len(a), 2): >> frobnicate(a[i], a[i+1]) >There have been requests to add a grouper function to itertools, but its >author has resisted because there are at least three things one might do >with the short remainder group left over when the group size does not >evenly divide the sequence size: drop it, return it, or fill it to the >requested groupsize with a dummy value and then return it. Why not make this choice a third argument to the grouper function? Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From jr9445 at ATT.COM Tue Jul 1 10:06:42 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Tue, 1 Jul 2008 09:06:42 -0500 Subject: How make regex that means "contains regex#1 but NOT regex#2" ?? In-Reply-To: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> References: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of > seberino at spawar.navy.mil > Sent: Tuesday, July 01, 2008 2:29 AM > To: python-list at python.org > Subject: How make regex that means "contains regex#1 but NOT regex#2" > ?? > > I'm looking over the docs for the re module and can't find how to > "NOT" an entire regex. > > For example..... > > How make regex that means "contains regex#1 but NOT regex#2" ? > Match 'foo.*bar', except when 'not' appears between foo and bar. import re s = 'fooAAABBBbar' print "Should match:", s m = re.match(r'(foo(.(?!not))*bar)', s); if m: print m.groups() print s = 'fooAAAnotBBBbar' print "Should not match:", s m = re.match(r'(foo(.(?!not))*bar)', s); if m: print m.groups() == Output == Should match: fooAAABBBbar ('fooAAABBBbar', 'B') Should not match: fooAAAnotBBBbar ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA621 From lars at gustaebel.de Sat Jul 19 06:11:11 2008 From: lars at gustaebel.de (Lars =?iso-8859-1?Q?Gust=E4bel?=) Date: Sat, 19 Jul 2008 12:11:11 +0200 Subject: How to process a very large (4Gb) tarfile from python? In-Reply-To: <1fe948fd-63a3-48ef-b5a8-84f0e4dd48a2@y22g2000prd.googlegroups.com> References: <0e96241d-60a3-44fd-967a-394904ad5b34@e39g2000hsf.googlegroups.com> <4nqu74p3mmmdmf9pn7125voe6itko8d31k@4ax.com> <1fe948fd-63a3-48ef-b5a8-84f0e4dd48a2@y22g2000prd.googlegroups.com> Message-ID: <20080719101104.GA20323@axis.g33x.de> On Thu, Jul 17, 2008 at 11:41:50PM -0700, Uwe Schmitt wrote: > On 17 Jul., 22:21, Lars Gust?bel wrote: > > > > > Maybe we should post this issue to python-dev mailing list. > > > Parsing large tar-files is not uncommon. > > > > This issue is known and was fixed for Python 3.0, seehttp://bugs.python.org/issue2058. > > The proposed patch does not avoid caching the previous values of the > iterator, it just reduces the size of each cached object. > It would be nice to be able to avoid caching on demand, which would > make iteration independent of the size of the tar file. The size of the archive doesn't matter, it's the number of members. And I wouldn't call it caching either. The members are stored in order to have a table of contents and to allow random access. Also, the members list is required for resolving hard links within the archive. It cannot be dropped without side-effects. -- Lars Gust?bel lars at gustaebel.de Those who would give up essential liberty, to purchase a little temporary safety, deserve neither liberty nor safety. (Benjamin Franklin) From Henning.Thornblad at gmail.com Mon Jul 7 12:51:40 2008 From: Henning.Thornblad at gmail.com (Henning Thornblad) Date: Mon, 7 Jul 2008 09:51:40 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <6deq2uF21vo2U1@mid.uni-berlin.de> Message-ID: <9b841be4-cd9c-4782-8498-55f053cdbb71@x41g2000hsb.googlegroups.com> When trying to find an alternative way of solving my problem i found that running this script: #!/usr/bin/env python import re row="" for a in range(156000): row+="a" print "How many, dude?" print re.search('/[^ "=]*',row) (the / has moved) wouldn't take even a second (The re.search part of course) This is for me very strange since this, in theory, is the same problem as before. /Henning Thornblad From fredrik at pythonware.com Mon Jul 21 08:03:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 14:03:25 +0200 Subject: simple question about dictionaries In-Reply-To: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> References: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> Message-ID: skazhy wrote: > hi, i am new to python, so i've a really simple question about > dictionaries. > if i have a dictionary and I make have an input after it (to input > numbers) can i get the key of value that was in input? A dictionary contains (key, value) pairs, and is optimized for quickly finding the value in a pair, if given the key. > somehting like this: > dict = { "key1"=100,"key2"=200,"key3"=300} dict() is a built-in function; you're free to reuse the names of such functions as variable names in Python, but if you do, you won't be able to use those functions in that part of your program. And in this case, the dict() built-in might be useful (see below): > a = input() > print 'the key of inputted value is', dict['a'] > > this syntax of course is wrong, but i hope you got the point.. Assuming that you want the *key* in Python's sense, for a given value, you can either loop over the dictionary (called D below): for k, v in D.items(): if v == a: print 'the key of inputted value is', v break else: print "not found" or create an reverse mapping and use that (you only have to do this every time the dictionary changes, of course), e.g. reverse_D = dict((D[k], k) for k in D) a = input() print "the key for value", a, "is", reverse_D[a] (this doesn't work if you call your dictionary "dict", obviously.) From Russ.Paielli at gmail.com Tue Jul 29 21:33:30 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 18:33:30 -0700 (PDT) Subject: static variables in Python? References: Message-ID: <39a2e1f0-b919-4065-8a7a-e3a4b837a347@25g2000hsx.googlegroups.com> On Jul 29, 1:40 pm, kj wrote: > Yet another noob question... > > Is there a way to mimic C's static variables in Python? Or something > like it? The idea is to equip a given function with a set of > constants that belong only to it, so as not to clutter the global > namespace with variables that are not needed elsewhere. > > For example, in Perl one can define a function foo like this > > *foo = do { > my $x = expensive_call(); > sub { > return do_stuff_with( $x, @_ ); > } > > }; > > In this case, foo is defined by assigning to it a closure that has > an associated variable, $x, in its scope. > > Is there an equivalent in Python? > > Thanks! > > kynn > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. If the constant parameters are really only needed in one particular function, you can use default function arguments. An added benefit is that you can override them with another value if necessary. def fun(x, y, parameter1=0, parameter2=1): ... From jeffober at gmail.com Fri Jul 11 07:36:18 2008 From: jeffober at gmail.com (Jeff) Date: Fri, 11 Jul 2008 04:36:18 -0700 (PDT) Subject: MySQLdb will only import for root References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> <6dothnF3lqqmU1@mid.uni-berlin.de> Message-ID: <85d26ae4-757f-494c-bf7e-412323e26b8a@x41g2000hsb.googlegroups.com> Is it possible the module was installed with priviledges set too strict? Perhaps the interpreter cannot see the module when it is run from a normal user account. From modelnine at modelnine.org Thu Jul 31 09:58:10 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Thu, 31 Jul 2008 15:58:10 +0200 Subject: problem when reading file In-Reply-To: <8e50c4e80807310644u3c456ab4qce06c6997707db8d@mail.gmail.com> References: <8e50c4e80807310644u3c456ab4qce06c6997707db8d@mail.gmail.com> Message-ID: <200807311558.11141.modelnine@modelnine.org> Am Donnerstag, 31. Juli 2008 15:44:33 schrieb shrimpy: > hi every one, i am new to python, > and coz i want to write a handy command for my linux machine, to find > a word in all the files which are under the current folder. What about grep -R "myword" . ? Even works on regular expression (with e/fgrep). Type grep --help to see all the options you get (context display, ignoring anything that's not a proper file or directory, only printing filenames with matches, not the matches themselves, etc.). -- Heiko Wundram From alexnbryan at gmail.com Thu Jul 17 01:36:20 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 22:36:20 -0700 (PDT) Subject: Need help getting BeautifulSoup contents Message-ID: <18501881.post@talk.nabble.com> The trick to this one is that the html looks something like this: " My question is I want everything inside, the contents of each ad the regular text of the
american, a href="/browse/blue" linkindex="12" set="yes">blue , a href="/browse/brick" linkindex="13" set="yes">brick , brie, cheddar, cheshire, a href="/browse/churn" linkindex="14" set="yes">churn , a href="/browse/cottage" linkindex="15" set="yes">cottage , a href="/browse/cream" linkindex="16" set="yes">cream , dunlop, and it goes on . I know I can do like a.contents, but it only gives me the first one, in this case being "blue". I want the contents of each of those and the regular contents of the . Can anyone help? -- View this message in context: http://www.nabble.com/Need-help-getting-BeautifulSoup-contents-tp18501881p18501881.html Sent from the Python - python-list mailing list archive at Nabble.com. From Nikolaus at rath.org Thu Jul 31 13:59:58 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Thu, 31 Jul 2008 19:59:58 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> <87r69a85ek.fsf@nokile.rath.org> Message-ID: <87fxpq7x41.fsf@nokile.rath.org> Maric Michaud writes: >>> What the means is that int is not a user type but a >>> builtin type, instances of int are not types (or classes) but common >>> objects, so its nature is the same as any classes. >>> >>> The way it prints doesn't matter, it's just the __repr__ of any instance, >>> and the default behavior for instances of type is to return '', >>> but it can be easily customized. >> >> But 'int' is an instance of 'type' (the metaclass): >> >>> int.__class__ >> >> >> >> so it should also return '' if that's the default behavior >> of the 'type' metaclass. >> > > The fact that a class is an instance of type, which it is always true, doesn't > mean its metaclass is "type", it could be any subclass of type : Yes, that is true. But it's not what I said above (and below). 'obj.__class__' gives the class of 'obj', so if 'int.__class__ is type' then 'type' is the class of 'int' and 'int' is *not* an instance of some metaclass derived from 'type'. >> I think that to get '' one would have to define a new >> metaclass like this: >> >> def type_meta(type): >> ? ? def __repr__(self) >> ? ? ? ? ?return "" % self.__name__ >> >> and then one should have int.__class__ is type_meta. But obviously >> that's not the case. Why? >> >> Moreover: >> >>> class myint(int): >> >> ... ? ?pass >> ... >> >> >>> myint.__class__ is int.__class__ >> True >> >> >>> int >> >> >> >>> myint >> >> >> despite int and myint having the same metaclass. So if the >> representation is really defined in the 'type' metaclass, then >> type.__repr__ has to make some kind of distinction between int and >> myint, so they cannot be on absolute equal footing. > > You're right, type(int) is type, the way it renders differently is a > detail of its implementation, you can do things with builtin types > (written in C) you coudn't do in pure python, exactly as you > couldn't write recursive types like 'object' and 'type'. If it is just a matter of different rendering, what's the reason for doing it like that? Wouldn't it be more consistent and straightforward to denote builtin types as classes as well? And where exactly is this different rendering implemented? Could I write my own type (in C, of course) and make it behave like e.g. 'int'? I.e. its rendering should be different and not inherited to subclasses: >>> my_type >>> a = my_type(42) >>> a.__class__ >>> class derived(my_type): >>> pass or would I have to change the implemention of 'type' for this (since it contains the __repr__ function that renders the type)? This is of course purely theoretical and probably without any practical relevance. I'm if I just can't stop drilling, but I think this is really interesting. Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From circularfunc at gmail.com Mon Jul 7 13:36:31 2008 From: circularfunc at gmail.com (ssecorp) Date: Mon, 7 Jul 2008 10:36:31 -0700 (PDT) Subject: Very weird bug! References: <1c1c343a-dd63-454a-8e29-a5c70281ad90@c58g2000hsc.googlegroups.com> Message-ID: <1c7f6a82-bd0b-46bc-a6b7-23bf9f4b5ee3@m36g2000hse.googlegroups.com> i know, idid try it again and it works as expected. but how the h*** did it not work that one time? From norseman at hughes.net Thu Jul 10 14:34:53 2008 From: norseman at hughes.net (norseman) Date: Thu, 10 Jul 2008 11:34:53 -0700 Subject: sort(cmp=func) In-Reply-To: References: Message-ID: <4876564D.9060906@hughes.net> Tobiah wrote: > I have a list of objects that generate code. Some > of them depend on others being listed first, to > satisfy dependencies of others. > > I wrote a cmp function something like this: > > def dep_cmp(ob1, ob2): > > if ob1.name in ob2.deps: > return -1 > else: > return 1 > > I also tried returning 0 when there were no dependency > relationships between the objects. > > This failed, because every object was not compared with > ever other. I imagine that this is because sort assumes > that if a > b and b > c, then a > c. In my case, this > isn't really true. If a is not dependent on b, and > b is not dependent on c, that doesn't mean that a is not > dependent on c. > > Is there a better way? > > Thanks > > Tobiah > ** Posted from http://www.teranews.com ** > -- > http://mail.python.org/mailman/listinfo/python-list > ================================== If you are running Linux take a look at /lib/modules/[kernel-ver]/modules.dep In other words, to create a list like: this module: depends on these module-a module-f, module-g copy ALL modules to a scratch directory ls -1 | sort >file.lst (or dir /b/l | sort >file.lst) concept: #outer loop get a filename from file.lst create a list of all imports in it compare filename, in turn, to each line in file if it finds itself loop #inner loop otherwise open module and create 2nd list of all imports in this file compare each item in list one to each item in list two and output one line for each match to imports1.lst, format: module name needing, module name wanted (filenames not def names) #outer loop2 get a line from dep1.lst parse to f1=first-name, f2=second-name create list of imports for f2 #inner loop2 check each import of f2 against name of f1 if there is a match, print Circular conflict with: f1 and f2 to problems.lst A sort on second filename on line combined with a visual inspection will often help point out any 3-way (or more) circulars. (a needs b needs c needs a) No guarantees, though. You will have to resolve circulars yourself. Usually involves changing code. If A needs output from B to run and B needs output from A to run you have an obvious circular. Rewrite/fix the code. Perhaps make a lib file of all the imports for the project. (Which is the preferred practice.) Load it with the main logic. Thus none will be run until all are present. Then eliminate whatever circular nonsense still exists... If problems.lst is empty all that needs to be done is for each import to check the dep1.lst and first load the second filename on the line for each first-name matching module wanted. For a given first filename not being in a circular, manual ordering of the dep1.lst can be done if needed. (Perhaps f1,a1:f1,b1:f1,c1 needs to be f1,c1:f1,a1:f1,b1 ? Simply because descriptive alpha name sort winds up being wrong load sequence.) Just because a piece of code can be reused does not mean it is generically practical to do so. The why of this is your current problem. My first reaction to your original post is that you inherited something and are setting about cleaning it up so you can work on it. Best of luck. Succeed and you get to claim another T-shirt. :) Steve norseman at hughes.net From matt at tplus1.com Tue Jul 15 10:04:41 2008 From: matt at tplus1.com (Matthew Wilson) Date: Tue, 15 Jul 2008 14:04:41 GMT Subject: How to package a logging.config file? References: <0a5713d6-8337-44a3-8347-012814345dd8@79g2000hsk.googlegroups.com> Message-ID: On Mon 14 Jul 2008 09:25:19 AM EDT, Vinay Sajip wrote: > Is your package a library or an application? If it's a library, you > should avoid configuring logging using a config file - this is because > logging configuration is process-wide, and if multiple libraries use > fileConfig to configure their logging, you may get unexpected results. I thought that the point of using logging.getLogger('foo.bar.baz') was to allow each module/class/function to choose from the available configurations. So, I can define a really weird logger and still be a good citizen. As long as I don't tweak the root logger, is it safe to use a config file? Matt From martin at v.loewis.de Tue Jul 22 14:52:08 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 22 Jul 2008 20:52:08 +0200 Subject: CPython VM internals - Wiki page In-Reply-To: <48862716$0$17157$742ec2ed@news.sonic.net> References: <48862716$0$17157$742ec2ed@news.sonic.net> Message-ID: <48862C58.1020905@v.loewis.de> > That's interesting. It's dumber than I thought. All temporaries > on the stack are "boxed" as PyObjects. That's simple and portable, > but slow. Not only that - Python does not ever have the concept of unboxed values, except for local variables in the C implementations of arithmetic operations and system calls. Using true objects is slow only if allocation and deallocation is slow, which it fortunately isn't. Regards, Martin From modelnine at modelnine.org Tue Jul 29 06:36:32 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Tue, 29 Jul 2008 12:36:32 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <200807291115.05701.modelnine@modelnine.org> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <200807291115.05701.modelnine@modelnine.org> Message-ID: <200807291236.32517.modelnine@modelnine.org> Am Dienstag, 29. Juli 2008 11:15:05 schrieb Heiko Wundram: > I can't dig up a simple example from code I wrote quickly... Just to get back to that: an example I found where "if x" (the generic __nonzero__() test) will work to test for emptiness/non-emptiness of a container, whereas "if len(x) > 0" (the "specific" test for this example) will not, is my for own integer set type I wrote a while back (which you can find on ASPN). The corresponding set type allows you to create infinitely sized sets of integers (which of course are stored as pairs of ,-values, so the storage itself for the set is bounded), for which len(x) does not have a "proper" meaning anymore, and __len__() is limited to returning a (platform dependent) ssize_t anyway IIRC, so even with a bounded set, the length of the set might not necessarily be accessible using len(x); that's why the set type additionally got a member function called .len() to work around this restriction. I should think is a non-contrieved example where the generic test whether the object considers itself True/False (which for containers means non-empty/empty) is preferrable over the special case test whether the length is positive. A polymorphic function, which for example only accesses the first ten members of the container is able to work with an infinite set if it uses the generic test, but is not in case it uses len(x) > 0. -- Heiko Wundram From jcoglan at googlemail.com Sun Jul 20 05:20:58 2008 From: jcoglan at googlemail.com (James Coglan) Date: Sun, 20 Jul 2008 02:20:58 -0700 (PDT) Subject: MethodChain References: <6eej10F6k7g3U2@mid.uni-berlin.de> <342b5431-5ead-4827-8bdd-ab2cd50c2acc@i76g2000hsf.googlegroups.com> <6efv5cF6uhc3U1@mid.uni-berlin.de> Message-ID: > Name clashes aren't an issue, since MethodChain doesn't apply any > special meaning to the method names it knows; the limitation is > because JavaScript doesn't allow you to modify property lookup > behavior. ?And since we can make the chain object callable, we don't > need "fire" or "toFunction" methods. I'm the author of MethodChain, so just thought I'd confirm the above statement. All MethodChain does is store method calls so they can later be replayed on any object. All methods in MethodChain simply add their name and arguments to an array inside the MethodChain instance, they don't implement any concrete functionality. All that's important is the names of the methods -- the object the chain is fired on will decide how to handle those calls itself, so naming clashes aren't a problem. For example: var chain = it().toLowerCase().split('-').map(function() {...}); chain.fire('my-String'); is the same as 'my-String'.toLowerCase().split('-').map(function() {...}); So split() gets called on 'my-string', map() gets called on ['my', 'string']. The methods 'fire' and 'toFunction' are a problem but I can't see any way around having them in JavaScript -- you need some way of getting the method list out of the chain object. if JavaScript had method_missing, we wouldn't need to tell MethodChain about names in advance either. From basti.wiesner at gmx.net Wed Jul 2 10:12:18 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Wed, 02 Jul 2008 16:12:18 +0200 Subject: Scripting SAP GUI (Windows) References: <6d15tpFaec4U1@mid.individual.net> Message-ID: Thomas Guettler : > Hi, > > I need to script SAP GUI running on MS-Windows: Doesn't that thing have a COM interface? -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From shevitz at lanl.gov Wed Jul 23 19:01:41 2008 From: shevitz at lanl.gov (Danny Shevitz) Date: Wed, 23 Jul 2008 23:01:41 +0000 (UTC) Subject: problem doing unpickle in an exec statement Message-ID: Howdy, In my app I need to exec user text that defines a function. I want this function to unpickle an object. Pickle breaks because it is looking for the object definition that isn't in the calling namespace. I have mocked up a simple example that shows the problem. Run this first code (from create_pickle.py) to create the pickle. create_pickle.py: (run this first) ############################################# import cPickle # the pickle file name file_name = 'd:\\temp\\test1.pickle' # define a class class Tree(object): pass def main(): # instantiate t = Tree() # create the sweet pickle fp = open(file_name, 'wb') cPickle.dump(t, fp) fp.close() # try to unpickle directly fp = open(file_name, 'rb') result = cPickle.load(fp) fp.close() print "unpickling directly works just fine, result = ", result if __name__=='__main__': main() ############################################# run this second: exec_pickle.py ############################################# # this file shows a problem with sweet pickle in an exec statement # the pickle file name file_name = 'd:\\temp\\test1.pickle' # code to be turned into a function code_text = ''' def include(): print "this works!" ''' # a function for creating functions def create_fun(code_text): clean_dict = {} exec code_text in clean_dict return clean_dict['include'] # include_fun is a bona fide function include_fun = create_fun(code_text) # this works include_fun() # now try to load the pickle in an exec statement code_text = ''' def include(file_name): print "processing file_name: ", file_name import cPickle fp = open(file_name, "rb") result = cPickle.load(fp) fp.close() print "result = ", result ''' # create the new include_fun include_fun = create_fun(code_text) # run it include_fun(file_name) ############################################# Can anyone enlighten me what I need to do to exec_pickle.py to get this to work? thanks, Danny From mensanator at aol.com Thu Jul 31 13:46:50 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 31 Jul 2008 10:46:50 -0700 (PDT) Subject: Non Continuous Subsequences References: Message-ID: <8b59f734-b992-4977-97cd-90dcbc0f3ee5@w7g2000hsa.googlegroups.com> On Jul 30, 11:32?am, bearophileH... at lycos.com wrote: > This post is not about practical stuff, so if you have little time, > you may ignore it. > > This is a task of the rosettacode.org site:http://www.rosettacode.org/wiki/Non_Continuous_Subsequences > > A subsequence contains some subset of the elements of this sequence, > in the same order. A continuous subsequence is one in which no > elements are missing between the first and last elements of the > subsequence. The task is to enumerate all non-continuous subsequences > for a given sequence. > That's equivalent to asking which n-bit binary numbers have at least one 0 bracketed by 1s, isn't it? import gmpy import re for i in xrange(32): s = gmpy.digits(i,2).zfill(5) # convert to base 2 (padded) m = re.search('10+1',s) # at least one 0 between 1s if m: z = [j+1 for j,i in enumerate(s) if i=='1'] print z ## [3, 5] ## [2, 5] ## [2, 4] ## [2, 4, 5] ## [2, 3, 5] ## [1, 5] ## [1, 4] ## [1, 4, 5] ## [1, 3] ## [1, 3, 5] ## [1, 3, 4] ## [1, 3, 4, 5] ## [1, 2, 5] ## [1, 2, 4] ## [1, 2, 4, 5] ## [1, 2, 3, 5] From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 2 10:44:23 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Jul 2008 16:44:23 +0200 Subject: How do web templates separate content and logic? In-Reply-To: References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> <87vdzpmxv3.fsf@internal.daycos.com> Message-ID: <486b9441$0$24646$426a74cc@news.free.fr> TheDarkTrumpet a ?crit : > Another thing I'd like to add on this subject. > > I agree with others here that having logic in the view isn't really a > bad thing. I used to think it did, but now I don't think it does as > much. I feel that when you're separating out the view, you're giving > really non-programmers the ability to actually do the content. That > doesn't mean that non-programmers can't learn very very basic > programming logic. Take, for example, the Django code. The Django > template system is a very watered down version of a language. It > supports very basic stuff, and I feel that really anyone can pick up > on it. > > By totally separating out the logic, and using tags, you're adding a > lot of overhead in my opinion. It's another file that needs to be > included, and the logic of how it's displayed on the page is then > split a bit - between the developer and the designer. If the designer > feels that they want only 5 products to show on one page, they should > be able to change it. > > THis is how I feel on the whole idea anyways. Yeps. Kirk and you both expressed MHO better than I did... I did the half-backed-template Kirk describes a couple times, and what you wrote above apply to my own experience with too-dumbed-down templating systems that finally make it harder for both the programmer and the designer, since a good part of the presentation logic then moves up to the controller, which somehow ruins the whole idea. From tjreedy at udel.edu Tue Jul 29 03:03:46 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 03:03:46 -0400 Subject: Is it allowed to use function results as default arguments ? In-Reply-To: <488E2BF1.8020003@gmail.com> References: <488E2BF1.8020003@gmail.com> Message-ID: To answer the subject line: param= will assign the result of the expression as the default argument object for the parameter. tjr From gagsl-py2 at yahoo.com.ar Tue Jul 15 04:28:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 05:28:12 -0300 Subject: Using Python To Launch Python References: <20080714212454.GE16010@dragontoe.org> <23116d500807141440u402eed7du5e41d72bb0716c58@mail.gmail.com> <20080715003920.GF16010@dragontoe.org> Message-ID: En Mon, 14 Jul 2008 21:39:20 -0300, Derek Martin escribi?: > On Mon, Jul 14, 2008 at 05:40:43PM -0400, Aquil H. Abdullah wrote: >> You've hit the proverbial nail with the hammer. The problem is that my >> application needs to run under both the Linux and Windows OSs, so while >> I >> would love to use a nice sh, csh, or bash shell script. My hands are >> tied >> because Windows does not provide such wonderful shells. > > *Provides*, no... neither does it provide Python, for what that's > worth. But you can certainly get it (bash): > > http://win-bash.sourceforge.net/ Using the standard cmd.exe, the previously posted shell script becomes: === begin appname.cmd === set INSTALLPATH= call %INSTALLPATH%\bin\python %INSTALLPATH%\APPNAME.py %* === end appname.cmd === -- Gabriel Genellina From xdicry at gmail.com Mon Jul 14 21:00:22 2008 From: xdicry at gmail.com (Evan) Date: Mon, 14 Jul 2008 18:00:22 -0700 (PDT) Subject: Is it possible to create "network conneciton" on windows system? References: Message-ID: On Jul 15, 6:22 am, Larry Bates wrote: > Evan wrote: > > Hello, > > > one of my PC is window system, and in "control panel ->Network > >Connections", I can see somenetworkconnectionssuch as PPPOE or VPN > > which I created by click "create a new connection". > > > My question is, is it possible to create a new connection by using > > Python script? which means I do not want to use Window UI (via > > "control panel"), if it is possible, I can save so many time to > > create variousnetworkconnection when I want to do testing in the > > lab. > > > Thanks very much. > > Evan > > It is very likely that it is possible to do this. Most control panel > applications store the results of their GUI setup in the registry. If you can > determine what registry keys have been added/changed. Here is an open source > registry compare utility that might help: > > https://sourceforge.net/projects/regshot > > You can then use the _winreg module to make such changes on a new machine. > > HTH, > Larry Thanks Larry, The thing is, if I change the registry, I have to reboot the PC for applying new configuration of system. Any idea to apply the changing without reboot after modify registry? Thanks, From alexnbryan at gmail.com Wed Jul 16 14:29:24 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 11:29:24 -0700 (PDT) Subject: Testing for connection to a website In-Reply-To: References: <18473382.post@talk.nabble.com> <18476597.post@talk.nabble.com> Message-ID: <18493785.post@talk.nabble.com> Fredrik Lundh wrote: > > Alexnb wrote: > >> e = '' > >> try: >> ... >> except HTTPError, e: >> print e.code >> except URLError, e: >> print e.reason >> >> if e == '': >> print "good to go" > > footnote: here's a better way to test if an exception was raised or not: > > try: > ... > except HTTPError, e: > print e.code > except URLError, e: > print e.reason > else: > print "good to go" > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > Thanks! can't believe I didn't think of that. -- View this message in context: http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p18493785.html Sent from the Python - python-list mailing list archive at Nabble.com. From http Tue Jul 15 22:52:26 2008 From: http (Paul Rubin) Date: 15 Jul 2008 19:52:26 -0700 Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> Message-ID: <7xiqv68rrp.fsf@ruckus.brouhaha.com> James Fassett writes: > tuple_list = ( > ('John', 'Doe'), > ('Mark', 'Mason'), > ('Jeff', 'Stevens'), > ('Bat', 'Man') > ) > # the final functional way > [result_list, _] = zip(*tuple_list) That's really ugly IMO. I'd use: result_list = list(x for (x,y) in tuple_list) I don't like square-bracket listcomps because they leak the index variables to the outside. From ptmcg at austin.rr.com Tue Jul 1 10:05:55 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 1 Jul 2008 07:05:55 -0700 (PDT) Subject: pyparsing problem References: Message-ID: On Jul 1, 8:02?am, name wrote: > Hi, > > I try to parse a file with pyparsing and get this output: > > ? ? ['generic', 'host-01', 'host alias xyz', '10.0.0.1'] > ? ? - alias: host alias xyz > ? ? - host_name: ['host-01'] > ? ? - ip_address: ['10.0.0.1'] > ? ? - use: ['generic'] > > ? ? > ? ? ? generic > ? ? ? host-01 > ? ? ? host alias xyz > ? ? ? 10.0.0.1 > ? ? > > ? ? ['generic', 'host-01', 'host alias xyz', '10.0.0.1'] > > ? ? finished > > What I don't understand is why I get the line > > ? ? generic > > and not > > ? ? generic > > as there is an associated name in the dump() output. > > Thank you very much in advance for any clue or help you could > provide. > > The code: > --------- > > #!/usr/bin/env python > > from pyparsing import * > > sample = """ > define host{ > ? use ? ? ? ? ? ? ? ? ? generic > ? host_name ? ? ? ? ? ? host-01 > ? alias ? ? ? ? ? ? ? ? host alias xyz > ? address ? ? ? ? ? ? ? ? ? ? ? 10.0.0.1} > > """ > > # define tokens > LBRACE,RBRACE = map(Suppress, '{}') > ipAddress = Combine(Word(nums) + ('.' + Word(nums))*3) > useTemplate = oneOf('generic user') > > # define grammar > > deviceName = Word(alphanums+'-') > hostDef = Literal('define').suppress() + Literal('host').suppress() > useLine = Suppress('use') + useTemplate + Suppress(SkipTo(lineEnd)) > host_nameLine = Suppress('host_name') + deviceName + Suppress(SkipTo > (lineEnd)) > aliasLine = Suppress('alias') + SkipTo(lineEnd) > aliasLine.setParseAction(lambda x: ' '.join(x[0].split())) > ip_addressLine = Suppress('address') + ipAddress > > use = useLine.setResultsName('use') > host_name = host_nameLine.setResultsName('host_name') > alias = aliasLine.setResultsName('alias') > ip_address = ip_addressLine.setResultsName('ip_address') > > host_stmt = (use + host_name + alias + ip_address) > host = hostDef + LBRACE + host_stmt ?+ RBRACE > > test_file = OneOrMore(host) + stringEnd > > # test > x = test_file.parseString(sample) > print x.dump() > print > print x.asXML('Hosts') > print > print x.asList() > print > > print 'finished' Looks like this is a bug in asXML(). Note that if I reverse the use and host_name strings in the input and in your grammar, I get this XML output: host-01 generic host alias xyz 10.0.0.1 Fortunately, you have provided a nice short test case, which should allow me to track down the problem. Thanks, -- Paul From npropadovic at googlemail.com Thu Jul 31 09:55:33 2008 From: npropadovic at googlemail.com (Propad) Date: Thu, 31 Jul 2008 06:55:33 -0700 (PDT) Subject: Debugging of a long running process under Windows Message-ID: Hello, I know this issue pops up once in a while, but I haven't found a good answer to it. I need to debug a long running application under windows. The application is a combined java/python framework for testing ECUs in the automotive industry. Basically, the Java GUI (Eclipse-based) starts test-cases written in Python and provides the console where the test-logs are seen. When there is a exception somewhere in the testcases (or the underlying functionallity, also written in Python), those are also logged, and then the framework usually continues with the next command in the same test case. I'd like to have a debugging facillity better than print statements. I imagine: a) something like a debugger poping up when I get an exception, or b) something debugger-like poping up when it reaches a command I entered something in the code, or c) Me pressing on a button and getting a debugger-like-thing that lets me look into the running, possibly halted code. I've done some little experiments with the code module, which looks nice but does not seem to get over the control from the java-part, and with popen2("cmd"), which seems not even to work if I start the code from a dosbox (the same console is keept), and same thing when strated by the Java-App. Just to add, using pdb (or pythonwin debugger) seems not to be an option, as it makes the test-runs much slower. Does somebody have an idea? It seems there used to be a python debugger called Pygdb, able to attach to a running application, but now it seems it disapeared (now there is a python debugger with the same name, linked to ViM). Thanx, Propad From robert.rawlins at thinkbluemedia.co.uk Mon Jul 21 07:10:53 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Mon, 21 Jul 2008 12:10:53 +0100 Subject: Daemonize an application. Message-ID: <011101c8eb22$71685ee0$54391ca0$@rawlins@thinkbluemedia.co.uk> Guys, I've been looking to run one of my applications as a Deamon on a linux based system. I've been looking at this recipe this morning and it all looks relatively fine: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 I just noted that the recipe was written 5 years ago and thought I would see if there have been any progressions in Python which allow a more native approach to forking my application as a daemon? I essentially want to add a command line parameter "--as-daemon" to my application which would fork it as a daemon instead of running it as a standard python script, I also want to ensure that stdin/out/err are all configured in a way which means any exceptions thrown by the application or data output to the command line, which I haven't foreseen will be stored in a log file for review. I'd really appreciate your advice and experience. Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmcmonagle at velseis.com.au Sat Jul 5 04:52:00 2008 From: jmcmonagle at velseis.com.au (John McMoangle) Date: Sat, 5 Jul 2008 18:52:00 +1000 Subject: Tkinter Text widget get() In-Reply-To: <682C7C6A-9172-4673-955E-5B775115A689@gmail.com> References: <682C7C6A-9172-4673-955E-5B775115A689@gmail.com> Message-ID: <20080705084539.M83810@velseis.com.au> > Hey guys. I am having trouble understanding the get() method from > the Tkinter Text() widget. It isn't like the entry.get() one I am > used to. I know you have to put tags in, or at least I read. I > tried this but it didn't work. I think I was putting the tags in > wrong but I am not sure. I just need an example. So if someone > could maybe modify this code to get EVERYTHING inside the text widget. > > text = Text(parent) > text.pack() > > text.insert(END, "I am text!") > > Of course, I will have much more text, but I still want to get > everything in the box. > The arguments to the get method of the Text widget are strings in the form of "line.position". So, text.get('1.5', '2.7') returns the text from line 1 position 5 to line 2 position 7. There are also some special tagged names such as END and SEL. So, if you want to get all the text in your Text widget, text.get('1.0', END) will do the trick. I recommend finding the appropriate documentation at http://www.pythonware.com/library/tkinter/introduction/tkinter-reference.htm Regards, John From bignose+hates-spam at benfinney.id.au Sat Jul 19 20:04:59 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 20 Jul 2008 10:04:59 +1000 Subject: __del__ methods References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> Message-ID: <87hcalxvx0.fsf@benfinney.id.au> "Robert Rawlins" writes: > What is the benefit of extending the base 'object' class? What does that > give me that en empty, non subclassed object doesn't? In Python 2.x, "classic" classes (which are not part of the unified type hierarchy) are deprecated, and exist only for backward compatibility with old code. You need to create "new-style" classes by inheriting from some class that is part of the unified type hierarchy; if there is no obvious candidate, 'object' is the recommended choice. In Python 3.0, classic classes are no longer supported and this issue goes away. -- \ Q: ?I've heard that Linux causes cancer...? Torvalds: ?That's a | `\ filthy lie. Besides, it was only in rats and has not been | _o__) reproduced in humans.? ?Linus Torvalds | Ben Finney From straton at lampsacos.demon.co.uk Wed Jul 16 12:29:38 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Wed, 16 Jul 2008 17:29:38 +0100 Subject: Eclipse, Pydev, question In-Reply-To: References: Message-ID: I have a small project for further development in eclipse, using the pyDev plug-in. I am working on foo.py and bar.pyc is also in the directory. bar.py is not in the directory; it is someone else's (confidential) file, and I don't get the python source. Can I run bar.pyc from eclipse ? From spython01 at gmail.com Mon Jul 21 18:39:13 2008 From: spython01 at gmail.com (Samir) Date: Mon, 21 Jul 2008 15:39:13 -0700 (PDT) Subject: Converting List of String to Integer References: Message-ID: On Jul 21, 6:15?pm, Andrew Freeman wrote: > Samir wrote: > > On Jul 21, 3:20 pm, Gary Herron wrote: > > >> Samir wrote: > > >>> Hi Everyone, > > >>> I am relatively new to Python so please forgive me for what seems like > >>> a basic question. > > >>> Assume that I have a list, a, composed of nested lists with string > >>> representations of integers, such that > > >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > > >>> I would like to convert this to a similar list, b, where the values > >>> are represented by integers, such as > > >>> b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > >>> I have unsuccessfully tried the following code: > > >>> n = [] > >>> for k in a: > >>> ? ? n.append([int(v) for v in k]) > >>> print n > > >>> Does anyone know what I am doing wrong? > > >>> Thanks in advance. > > >>> Samir > >>> -- > >>>http://mail.python.org/mailman/listinfo/python-list > > >> You didn't tell us how it failed for you, so I can't guess what's wrong. > > >> However, your code works for me: > > >> ?>>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > >> ?>>> n = [] > >> ?>>> for k in a: > >> ... ? ?n.append([int(v) for v in k]) > >> ... > >> ?>>> print n > >> [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > >> (Although you seem to have confused variables b and n.) > > >> Gary Herron- Hide quoted text - > > >> - Show quoted text - > > > Hi Gary, > > > Thanks for your quick response (and sorry about mixing up b and n). > > For some reason, the logic I posted seems to work ok while I'm using > > the Python shell, but when used in my code, the program just hangs. > > It never outputs the results. ?Below is the code in its entirety. ?Is > > there a problem with my indendentation? > > > a = n = [] > > t = """ > > 1 2 > > 3 > > 4 5 6 > > 7 8 9 0 > > """ > > > d = t.split("\n") > > > for x in range(1,len(d)-1): > > ? ? a.append(d[x].split(" ")) > > print a > > > for k in a: > > ? ? n.append([int(v) for v in k]) > > > print n > > > Thanks again. > > > Samir > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I think this will work better, a sub-list comprehension of sorts: > n = [[int(i) for i in k] for k in a] > > here is an ipython interactive session using it: > In [1]: a = n = [] > > In [2]: t = """ > ? ?...: 1 2 > ? ?...: 3 > ? ?...: 4 5 6 > ? ?...: 7 8 9 0 > ? ?...: """ > > In [3]: > > In [4]: d = t.split("\n") > > In [5]: for x in range(1,len(d)-1): > ? ?...: ? ? a.append(d[x].split(" ")) > ? ?...: ? ? > ? ?...: ? ? > > In [6]: a > Out[6]: [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > > In [7]: n = [[int(i) for i in k] for k in a] > > In [8]: n > Out[8]: [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > -- > Andrew- Hide quoted text - > > - Show quoted text - Andrew, Thanks for the tip, though the syntax makes my head spin a bit in trying to comprehend it. For my small list, I didn't notice a discernible increase in speed, but I may have to try it with a larger list size. Incidentally, I had never heard of iPython but from their web site, it looks like an interesting tool. I'll have to check it out. Thanks. Samir From stefan_ml at behnel.de Thu Jul 17 10:29:21 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 17 Jul 2008 14:29:21 +0000 (UTC) Subject: Babelfish translation ... References: <487F2633.6000703@gmail.com> Message-ID: Stef Mientki gmail.com> writes: > Although it works functionally, > it can take lots of time waiting for the translation. > > What I basically do is, after selecting a new string to be translated: > > kwds = { 'trtext' : line_to_be_translated, 'lp' :'en_nl'} > soup = BeautifulSoup (urlopen(url, urlencode ( kwds ) ) ) > translation= soup.find ( 'div', style='padding:0.6em;' ).string > self.Editor_Babel.SetLabel ( translation ) You should give lxml.html a try. http://codespeak.net/lxml/ It can parse directly from HTTP URLs (no need to go through urlopen), and it frees the GIL while parsing, so it will become efficient to create a little Thread that doesn't do more than parsing the web site, as in (untested): def read_bablefish(text, lang, result): url = BABLEFISH_URL + '?' + urlencode({'trtext':text, 'lp':lang}) page = lxml.html.parse(url) for div in page.iter('div'): style = div.get('style') if style is not None and 'padding:0.6em;' in style: result.append( lxml.html.tostring(div, method="text", with_tail=False)) result = [] thread = threading.Thread(target=read_bablefish, args=("...", "en_nl", result)) thread.start() while thread.isAlive(): # ... do other stuff if result: print result[0] Stefan From mrkafk at gmail.com Thu Jul 17 07:45:06 2008 From: mrkafk at gmail.com (mk) Date: Thu, 17 Jul 2008 13:45:06 +0200 Subject: storing references instead of copies in a dictionary Message-ID: Hello everyone, I'm storing functions in a dictionary (this is basically for cooking up my own fancy schmancy callback scheme, mainly for learning purpose): >>> def f2(arg): ... return "f2 " + arg ... >>> >>> def f1(arg): ... return "f1" + arg ... >>> a={'1': f1, '2': f2} >>> >>> [ x[1](x[0]) for x in a.items() ] ['f11', 'f2 2'] Well, neat. Except if I change function definitions now, old functions are called. And rightly: {'1': , '2': } >>> f1 >>> >>> def f1(arg): ... return "NEW f1 " + arg ... >>> f1 The address of function f1 has obviously changed on redefinition. Storing value copies in a dictionary on assignment is a reasonable default behaviour. However, in this particular case I need to specifically store _references to objects_ (e.g. f1 function), or should I say _labels_ (leading to objects)? Of course, I can basically update the dictionary with a new function definition. But I wonder, is there not a way _in general_ to specifically store references to functions/variables/first-class objects instead of copies in a dictionary? From deets at nospam.web.de Mon Jul 21 07:30:40 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 21 Jul 2008 13:30:40 +0200 Subject: Please recommend a RPC system working with twisted. References: <312040c6-4011-451e-8a45-f982c2e4462f@j1g2000prb.googlegroups.com> Message-ID: <6ejacrF7dd9lU1@mid.uni-berlin.de> ??? wrote: > Hi all, > > I'm looking for an RPC system working with twisted. > > 1. Binary. I want it run faster than any xml based RPC. > > 2. Bidirectional. Unlike HTTP, on which the client has to poll the > sever for events, the server should "call" the client's method to > notify events. > > 3. C/Python support. Part of the system shall be written in C. CORBA, especially the very good omniORB-implementation for Python. > 4. Could easily integrated with twisted. > > Unfortunately, there seems no such resolution existed. So maybe I > have to give up some requirements. The last one, yes. At least it should be possible to integrate using threading though. And *maybe* you can even provide some event loop integration as well - I think omniORB should be that flexible. Diez From bdesth.quelquechose at free.quelquepart.fr Sat Jul 26 03:58:39 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 26 Jul 2008 09:58:39 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> Message-ID: <488af527$0$14761$426a74cc@news.free.fr> Matthew Fitzgibbons a ?crit : (snip) > As for !=, it seems like there is a technical reason for the behavior. > Remember, there is no default __ne__ method, so the behavior you want > would have to live in the interpreter. If __ne__ isn't defined, it would > have to try to call __eq__ and negate the result. Is there any other > lookup that is treated this way? There are quite a few cases in Python where there are both a specific magic method *and* a default behaviour based on another magic method if the specific one is not implemented. Just out of my mind: * __contains__ and __getitem__ * __iter__ and __getitem__ * __nonzero__ and __len__ Not to mention the fact that lookup rules even check the existence of special methods on class attributes (remember the descriptor protocol ?)... From waldemar.rymarkiewicz at gmail.com Thu Jul 24 10:30:57 2008 From: waldemar.rymarkiewicz at gmail.com (waldek) Date: Thu, 24 Jul 2008 07:30:57 -0700 (PDT) Subject: ctypes and reading value under pointer passed as param of a callback Message-ID: Hi, I'm using C dll with py module and wanna read value (buffer of bytes) returned in py callback as parameter passed to dll function. -------------------------------------------------- def mycallback(data, size): # how to read data buffer here ? return 0 cbfunc = CFUNCTYPE(c_int, POINTER(c_uint8), c_int) mydll = cdll.somedll mdll.foo(cbfunct) --------------------------------------------------------------- Question: How to get bytes from the buffer passed to mycallback ??? Let's assume that the buffer consist of 4 bytes 4 bytes 8 bytes. I tried unpack("ii8s", data[0]) and nothing. I tried different ctypes passed to callback and nothing. Any sugestions ? Thanks, Waldek From fetchinson at googlemail.com Thu Jul 10 17:23:24 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 10 Jul 2008 14:23:24 -0700 Subject: Python with Ecmascript In-Reply-To: References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <486fe241$0$867$ba4acef3@news.orange.fr> Message-ID: >> Is there a way to do similar things on linux? > > NJSModule? > http://en.wikipedia.org/wiki/NJS This seems to be very good indeed. Just downloaded njs but the only njsmodule version I could find was for python 2.1. Does anyone have a recent copy? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From mtobis at gmail.com Tue Jul 22 12:52:56 2008 From: mtobis at gmail.com (Michael Tobis) Date: Tue, 22 Jul 2008 09:52:56 -0700 (PDT) Subject: Not entirely serious: recursive lambda? References: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> Message-ID: Thanks all! What a remarkable set of answers, intelligent, thought provoking and informative without exception. Of course, now I can't use Paul's version; it hardly counts as a japh if someone else wrote it! It is probably the closest to my original vision, alas. Miles' second suggestion was the one I was fumbling toward; I will study it. No spoilers please. best mt From martinnorth at westnet.com.au Fri Jul 11 07:09:27 2008 From: martinnorth at westnet.com.au (martinnorth) Date: Fri, 11 Jul 2008 21:09:27 +1000 Subject: MySQLdb will only import for root Message-ID: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> Hi, I am running Python and MySQL on Ubuntu and have installed MySQLdb. If I try to import MySQLdb I get the following error: ActivePython 2.5.2.2 (ActiveState Software Inc.) based on Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08) [GCC 3.3.1 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb Traceback (most recent call last): File "", line 1, in ImportError: No module named MySQLdb But if I lrun python as the root user it imports fine. Can anyone suggest what might be wrong with the installation? Or is there nothing wrong? I haven't seen any examples that mentioned being root to import a module. Martin From geraint.williams at gmail.com Tue Jul 1 11:41:11 2008 From: geraint.williams at gmail.com (GHZ) Date: Tue, 1 Jul 2008 08:41:11 -0700 (PDT) Subject: Installing paramiko and pycrypto References: <4856638d-1c86-4d4d-ba50-4a808f722f10@79g2000hsk.googlegroups.com> Message-ID: <17d5049b-89cd-40af-81a2-80306a86eaf8@i36g2000prf.googlegroups.com> I installed from here: http://bazaar-vcs.org/WindowsInstall first pycrypto-2.0.1.win32-py2.5.zip then paramiko-1.7.1-ctypes.win32.exe From theller at python.net Thu Jul 24 11:01:28 2008 From: theller at python.net (Thomas Heller) Date: Thu, 24 Jul 2008 17:01:28 +0200 Subject: ctypes and reading value under pointer passed as param of a callback In-Reply-To: References: Message-ID: <6erjpeF88slmU1@mid.individual.net> waldek schrieb: > Hi, > > I'm using C dll with py module and wanna read value (buffer of bytes) > returned in py callback as parameter passed to dll function. > The callback receives a pointer instance. You can dereference the pointer to read individual bytes in this way: print data[0], data[5], data[42] or use slicing to read a bunch of bytes: print data[0:42] So, you probably want something like this: > -------------------------------------------------- > def mycallback(data, size): > # how to read data buffer here ? print data[:size] > return 0 > > cbfunc = CFUNCTYPE(c_int, POINTER(c_uint8), c_int) > > mydll = cdll.somedll > mdll.foo(cbfunct) > --------------------------------------------------------------- > > Question: How to get bytes from the buffer passed to mycallback ??? > Let's assume that the buffer consist of 4 bytes 4 bytes 8 bytes. > > I tried unpack("ii8s", data[0]) and nothing. I tried different ctypes > passed to callback and nothing. Thomas From __peter__ at web.de Sun Jul 13 03:12:03 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 13 Jul 2008 09:12:03 +0200 Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> Message-ID: Yosifov Pavel wrote: > Whats is the way to clone "independent" iterator? I can't use tee(), > because I don't know how many "independent" iterators I need. copy and > deepcopy doesn't work... There is no general way. For "short" sequences you can store the items in a list which is also the worst-case behaviour of tee(). What are you trying to do? Peter From fredrik at pythonware.com Tue Jul 22 11:25:43 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 17:25:43 +0200 Subject: convert list of lists to list In-Reply-To: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> References: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> Message-ID: antar2 wrote: > Is there a way to convert list_of_listsA to list_of_listsB, where one > list in listof lists A is one element of listB? > list_of_listsA: > [['klas*', '*', '*'], > ['mooi*', '*', '*', '*'], > ['koe'], > ['arm*', '*', '*(haar)'], > ['groei*', '*', '*', '*', '*']] > > listB: > ['klas* * *', 'mooi* * * *, 'koe', 'arm* * * (haar)', 'groei* * * * > *'] if there's only one level of recursion, and the lists aren't too long, you can simply do: sum(list_of_lists, []) (this has quadratic performance, so don't use it for large structures) for recursive solutions, see: http://www.google.com/search?q=flatten+lists+python From aahz at pythoncraft.com Tue Jul 1 09:14:04 2008 From: aahz at pythoncraft.com (Aahz) Date: 1 Jul 2008 06:14:04 -0700 Subject: [Employment] New TurboGears Job in Eugene, OR References: <4df107ec-7193-412a-addf-ecbb4b6a3f3a@p25g2000hsf.googlegroups.com> Message-ID: In article , Tim Roberts wrote: >aahz at pythoncraft.com (Aahz) wrote: >>Paul McNett

wrote: >>> >>>They want an expert for a maximum of $25 per hour? If they find someone, >>>it'll be a pretty good bullshitter looking for experience. >> >>Note that it's an "academic year" position -- lots and lots of vacation >>time. This would actually be a good job for e.g. a retired person who >>doesn't need lots of money. Also note that Eugene is not exactly an >>area with a high cost of living. > >I take it you're not from Oregon. Eugene is the second largest city. >Prices are not quite up to the San Jose at its peak, but there are no >bargains left in any of the urban sections of the state. It's certainly >far more expensive here than in the midwest or most of the south. Depends where you look in the midwest, of course. It's certainly cheaper than Minneapolis or Chicago. It's even cheaper than Cleveland or Columbus. It's cheaper than Atlanta. So yeah, I stick by my comment. It's all a matter of which perspective you're looking from. ;-) FYI, I'm pulling my info from http://swz.salary.com/CostOfLivingWizard/layouthtmls/coll_metrodetail_58.html which differs some from http://www.eugenechamber.com/relo/facts_figures.htm -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From miki.tebeka at gmail.com Fri Jul 4 00:53:16 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 3 Jul 2008 21:53:16 -0700 (PDT) Subject: manipulating movie files with Python References: Message-ID: <863b1ce8-9114-442e-b7f2-4c1391d5162d@z24g2000prf.googlegroups.com> Hello, > I would like to write a python script which could take a movie file name > (avi, mov, mpg) along with a start and stop time as parameters, and > return to me a ?new movie file just containing that section of the > original which I'm interested in. Is there a Python library which could > already perform such magic? Thanks for any suggestions. I think you'll find ffmpeg the right tool for the job. HTH, -- Miki http://pythonwise.blogspot.com From paul at boddie.org.uk Tue Jul 22 06:28:09 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 22 Jul 2008 03:28:09 -0700 (PDT) Subject: xpathEval fails for large files References: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> Message-ID: <720d459e-fc11-482c-91c2-4197feb295d6@s50g2000hsb.googlegroups.com> On 22 Jul, 11:00, Kanchana wrote: > > I tried to extract some data with xpathEval. Path contain more than > 100,000 elements. > > doc = libxml2.parseFile("test.xml") > ctxt = doc.xpathNewContext() > result = ctxt.xpathEval('//src_ref/@editions') > doc.freeDoc() > ctxt.xpathFreeContext() Another note on libraries: if you want a pure Python library which works on top of libxml2 and the bundled Python bindings, consider libxml2dom [1]. > this will stuck in following line and will result in high usage of > CPU. > result = ctxt.xpathEval('//src_ref/@editions') > > Any suggestions to resolve this. How big is your document and how much memory is the process using after you have parsed the document? Sometimes, you won't be able to effectively handle very large documents by having them loaded completely in memory because you'll require more main memory than your system has available, making operations on the document somewhat inefficient. > Is there any better alternative to handle large documents? Fredrik pointed out a few. There's also xml.dom.pulldom and xml.sax in the standard library - the latter attractive mostly if you have previous experience with it - providing stream-based processing of documents if you don't mind writing more code. Paul [1] http://www.python.org/pypi/libxml2dom From timr at probo.com Sun Jul 6 00:59:59 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 06 Jul 2008 04:59:59 GMT Subject: win32com.client (Howto edit Contacts in Outlook) References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: "Bill Davy" wrote: > >I am trying to edit Contacts in Outlook. This is so I can transfer numbers >from my address book which is an Excel spreadsheet to my mobile phone. Are you actually running Outlook? Your news posting was made from Outlook Express, and Outlook Express cannot be controlled by COM (although MAPI works). -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mrkafk at gmail.com Mon Jul 21 12:19:53 2008 From: mrkafk at gmail.com (mk) Date: Mon, 21 Jul 2008 18:19:53 +0200 Subject: Please recommend a RPC system working with twisted. In-Reply-To: <312040c6-4011-451e-8a45-f982c2e4462f@j1g2000prb.googlegroups.com> References: <312040c6-4011-451e-8a45-f982c2e4462f@j1g2000prb.googlegroups.com> Message-ID: > Unfortunately, there seems no such resolution existed. So maybe I > have to give up some requirements. Why not PYRO? Note: I haven't used it. From mrkafk at gmail.com Sun Jul 13 06:41:50 2008 From: mrkafk at gmail.com (mk) Date: Sun, 13 Jul 2008 12:41:50 +0200 Subject: Using SWIG to build C++ extension In-Reply-To: <4877ec43$0$877$ba4acef3@news.orange.fr> References: <4877ec43$0$877$ba4acef3@news.orange.fr> Message-ID: Hello Bas, Thanks, man! Your recipe worked on Debian system, though not on RedHat, and I still have no idea why. :-) Anyway, I have it working. Thanks again. > I took your example files and did the following: > changed the #include "edit_distance.h" to #include "edit_distance.c" > in the edit_distance.i file. > Then I changed the first few lines of your function definition > unsigned int edit_distance( const char* c1, const char* c2 ) > { > std::string s1( c1), s2( c2); > and also adapted the signature in the edit_distance.i file. > Then > swig -shadow -c++ -python edit_distance.i > g++ -c -fpic -I/usr/include/python edit_distance_wrap.cxx > g++ -shared edit_distance_wrap.o -o _edit_distance.so From r_e_s_01 at ZZZyahoo.com Thu Jul 10 21:03:24 2008 From: r_e_s_01 at ZZZyahoo.com (r.e.s.) Date: Thu, 10 Jul 2008 18:03:24 -0700 Subject: Can this program be shortened? Measuring program-length? References: <7Rtdk.16747$N87.3559@nlpi068.nbdc.sbc.com> <2ed6de5b-bf2f-4e3d-94af-c8e6c6a28f95@s50g2000hsb.googlegroups.com> Message-ID: "r.e.s." wrote ... > wrote ... >> "r.e.s." wrote: >>> Can the following program be shortened? ... >>> >>> def h(n,m): >>> E=n, >>> while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n >>> return n >>> h(9,9) >>> >> >> Some ideas... >> >> # h is your version >> def h(n,m): >> E=n, >> while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n >> return n >> >> def g(n,m): >> E=n, >> while E*m:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n ^ g >> return n >> >> def f(n,m): >> E=n, >> while E*m:n=h(n+1,m-1);E=(E[0]>0)*(E[0]-1,)*n+E[1:] ^ f >> return n >> >> def e(n,m): >> E=[n] >> while E*m:n=h(n+1,m-1);E[:1]=(E[0]>0)*[E[0]-1]*n ^ e >> return n >> >> # some tests >> print h(1,1), h(2,1), h(0,2) >> print g(1,1), g(2,1), g(0,2) >> print f(1,1), f(2,1), f(0,2) >> print e(1,1), e(2,1), e(0,2) > > Very instructive! Thank you for the "step-by-step". I forgot to mention the obvious typos. Thanks again. From victorsubervi at gmail.com Tue Jul 15 08:42:16 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 15 Jul 2008 14:42:16 +0200 Subject: Characters Being Misread Message-ID: <4dc0cfea0807150542j52bf645dy54d604088c2f950c@mail.gmail.com> Hi; Forgive multiple posts in one day: online very infrequently I'm having the darndest time trying to figure out how the character '\b0' is being read in "('\x0c')" >>> test = re.search('(?<=\\b)[0]', '\x0c0') >>> test.group(0) '0' >>> type('\x0c') >>> import binascii >>> binascii.unhexlify('\x0c') Traceback (most recent call last): File "", line 1, in binascii.unhexlify('\x0c') TypeError: Odd-length string What gives here? Here's another one: >>> rtf_markup = '\viewkind4\\uc1\\pard\nowidctlpar\\qc\\i\x0c0\x0cs36' >>> a = [] >>> a.append(re.compile('\\i').match(rtf_markup, 1)) >>> a [<_sre.SRE_Match object at 0x011802F8>] >>> a = [] >>> a.append(re.compile('\\qc').match(rtf_markup, 1)) [None] What's the problem? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Mon Jul 28 16:28:33 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 28 Jul 2008 22:28:33 +0200 Subject: Is it allowed to use function results as default arguments ? Message-ID: <488E2BF1.8020003@gmail.com> hello, I've a perfect working procedure, at least as far I've tested it it works perfect. But I was just experimenting with inspect, and saw that the default argument was not parsed correctly. So I wonder if this is allowed: def Get_Relative_Path ( target, base=os.curdir ) : ... As inspect returns the following: (['target', 'base'], None, None, ('.',)) thanks, Stef Mientki From spython01 at gmail.com Wed Jul 23 21:30:11 2008 From: spython01 at gmail.com (Samir) Date: Wed, 23 Jul 2008 18:30:11 -0700 (PDT) Subject: Request Help Debugging Program References: <898dfe7a-4133-4337-8243-f4936b8a8092@8g2000hse.googlegroups.com> <9ba3340e-1048-4958-b988-d2a83559111d@d77g2000hsb.googlegroups.com> Message-ID: On Jul 23, 9:14?pm, mzdude wrote: > On Jul 23, 6:30?pm, Samir wrote: > > > Hi Everyone, > > > def findSumOfDivisor(n): > > > ? ? return sum(divisor) ? ? ? ? ? ? ? ?# fine using function sum() > > > ? ? ? ? sum = findSumOfDivisor(i) ? ? ?# then find the sum of its divisors > > oops redefine what sum is. > > > > >>> x = [1,2] > >>> sum(x) > 3 > >>> sum = 4 > >>> sum(x) > > Traceback (most recent call last): > ? File "", line 1, in > ? ? sum(x) > TypeError: 'int' object is not callable > > > > - Hide quoted text - > > - Show quoted text - I am an IDIOT! Thanks, mzdude! That did the trick. Sorry for posting something this stupid. From bruno.desthuilliers at gmail.com Fri Jul 18 10:13:41 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 18 Jul 2008 07:13:41 -0700 (PDT) Subject: substitution of list elements References: <247ab26d-ba98-42cc-bf6e-738b4b32a70c@q28g2000prh.googlegroups.com> Message-ID: <9cf77901-60ee-4754-901b-a43f1fc1ef66@f40g2000pri.googlegroups.com> On 18 juil, 14:33, antar2 wrote: > I want to replace each first element in list 5 that is equal to the > first element of the list of lists4 by the fourth element. I wrote > following code that does not work: > > list4 = [['1', 'a', 'b', 'c'], ['2', 'd', 't', 'e'], ['8', 'g', 'q', > 'f']] > list5 = ['1', '2', '3'] > > for j in list4: > for k in list5: > if j[0] == k: > k = j[3] > print list5 > Wanted result: ['c', 'e', '3'] > > thanks! select = lambda item, lst: (item, lst[3])[item == lst[0]] list5[:] = [select(*pair) for pair in zip(list5, list4)] # or if you prefer a more procedural solution: for index, (item, lst) in enumerate(zip(list5, list4)): if item == lst[0]: list5[index] = lst[3] From ndbecker2 at gmail.com Tue Jul 1 11:55:34 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 01 Jul 2008 11:55:34 -0400 Subject: dynamically load from module import xxx References: Message-ID: Guilherme Polo wrote: > On Tue, Jul 1, 2008 at 12:11 PM, Neal Becker wrote: >> What is a good way to emulate: >> >> from module import xxx >> where 'module' is a dynamically generated string? >> >> __import__ ('modulename', fromlist=['xxx']) >> >> seems to be what I want, but then it seems 'xxx' is not placed in >> globals() (which makes me wonder, what exactly did fromlist do?) > > fromlist is used for importing subpackages/submodules of the first arg > of __import__. Since you are using "modulename", I'm guessing it is > not a package, fromlist will do nothing for you. > To solve your problem you could do getattr(__import__('modulename'), > 'xxx'). This seems to be what I want, don't know if there is a simpler way: stuff =['A','B'] module = __import__ (modulename) for e in stuff: globals().update({e : module.__dict__[e]}) From gagsl-py2 at yahoo.com.ar Wed Jul 30 22:40:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 23:40:21 -0300 Subject: Optimizing size of very large dictionaries References: <1217464179.31710.1266222419@webmail.messagingengine.com> Message-ID: En Wed, 30 Jul 2008 21:29:39 -0300, escribi?: > Are there any techniques I can use to strip a dictionary data > structure down to the smallest memory overhead possible? > > I'm working on a project where my available RAM is limited to 2G > and I would like to use very large dictionaries vs. a traditional > database. > > Background: I'm trying to identify duplicate records in very > large text based transaction logs. I'm detecting duplicate > records by creating a SHA1 checksum of each record and using this > checksum as a dictionary key. This works great except for several > files whose size is such that their associated checksum > dictionaries are too big for my workstation's 2G of RAM. You could use a different hash algorithm yielding a smaller value (crc32, by example, fits on an integer). At the expense of having more collisions, and more processing time to check those possible duplicates. -- Gabriel Genellina From drakonik at gmail.com Sun Jul 20 09:57:55 2008 From: drakonik at gmail.com (Nick Dumas) Date: Sun, 20 Jul 2008 09:57:55 -0400 Subject: a question that can accelerate learning python? In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Simple. dir(object) wangziqing1984 at hotmail.com wrote: > I am new to python .But interest in it . > I think if python could provide a method that show every method of an > object or an module.it will be great! We can save a lot of time to > find the document > take win32com as an example: > if code like this > "win32com.query"(or some other name that means query) > it would return a list of module or method that win32com have. > Does python have implement such interface yet? 'cause I have not so > familiar with python. > best wishes! > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkiDRGMACgkQLMI5fndAv9g76ACdGJsxrSuaFot0SnHmlnFYaw7W muoAn0KZvyG2PgE2hoaQZLIjD5YvBYuK =WFxU -----END PGP SIGNATURE----- From sterlingsomers at gmail.com Thu Jul 31 11:13:32 2008 From: sterlingsomers at gmail.com (sterling) Date: Thu, 31 Jul 2008 08:13:32 -0700 (PDT) Subject: win32com ChartObject pythonwin vs idle References: <670b57b7-d48e-44c0-abd0-b6772d23688d@79g2000hsk.googlegroups.com> Message-ID: <9236f4cd-8808-411a-835a-04e75e1927c1@34g2000hsf.googlegroups.com> On Jul 31, 4:28?am, Tim Golden wrote: > sterling wrote: > > I'm curious as to why the difference between IDLE and pythonWin when > > using win32com. > > opening an excel file, i've attempted to grab the chart information > > out of the file. > > > commands like co = ChartObjects(1) ?works in pythonWin but doesn't > > work in IDLE. > > > however, on both co = chartobjects(1) works just fine. > > I can't speak for IDLE vs PythonWin but in general > case-sensitivity of win32com stuff is related to > early vs late Dispatch. If you've explicitly generated > proxy modules for the Excel objects (via makepy, > EnsureDispatch or whatever) then those are Python > modules with case-sensitivity. If you're using dynamic > dispatch then Python is simply passing your attribute > name along to COM, which isn't case-sensitive, so either > case will work. > > Not sure why IDLE vs PythonWin should make a difference > here, but maybe the above explanation sheds some light... > > TJG Thanks Tim. I'm wondering if it's an OS issues with Vista (I'm strangly ashamed to admit that both my laptop and main computer are running it). I decided to try the same code on my main computer (do most of my work on my laptop) and the exact same thing has happened: I can run it in pythonwin and not idle. I found that I can't even run Open (I must have been running open() previously): i.e. >>> import win32com.client >>> ex = win32com.client.Dispatch("Excel.Application") >>> wb = ex.Workbooks.Open("C:\Temp\SalesChart.xls") Traceback (most recent call last): File "", line 1, in wb = ex.Workbooks.Open("C:\Temp\SalesChart.xlsx") File "C:\Python25\Lib\site-packages\win32com\client\dynamic.py", line 467, in __getattr__ if self._olerepr_.mapFuncs.has_key(attr): return self._make_method_(attr) File "C:\Python25\Lib\site-packages\win32com\client\dynamic.py", line 295, in _make_method_ methodCodeList = self._olerepr_.MakeFuncMethod(self._olerepr_.mapFuncs[name], methodName,0) File "C:\Python25\Lib\site-packages\win32com\client\build.py", line 297, in MakeFuncMethod return self.MakeDispatchFuncMethod(entry, name, bMakeClass) File "C:\Python25\Lib\site-packages\win32com\client\build.py", line 318, in MakeDispatchFuncMethod s = linePrefix + 'def ' + name + '(self' + BuildCallList(fdesc, names, defNamedOptArg, defNamedNotOptArg, defUnnamedArg, defOutArg) + '):' File "C:\Python25\Lib\site-packages\win32com\client\build.py", line 604, in BuildCallList argName = MakePublicAttributeName(argName) File "C:\Python25\Lib\site-packages\win32com\client\build.py", line 542, in MakePublicAttributeName return filter( lambda char: char in valid_identifier_chars, className) File "C:\Python25\Lib\site-packages\win32com\client\build.py", line 542, in return filter( lambda char: char in valid_identifier_chars, className) UnicodeDecodeError: 'ascii' codec can't decode byte 0x83 in position 52: ordinal not in range(128) but the exact same code works in PythonWin. Perhaps I will just find a way to code everything I want in the older lowercase. From benjamin.kaplan at case.edu Tue Jul 1 19:23:29 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 1 Jul 2008 19:23:29 -0400 Subject: Required items in a form In-Reply-To: <45yak.331$Ae3.313@trnddc05> References: <45yak.331$Ae3.313@trnddc05> Message-ID: On Tue, Jul 1, 2008 at 6:20 PM, Brandon wrote: > What I'm trying to do is essentially force a user to fill in required items > in a form, which will be saved to a database. How can I get it so that > once > the user clicks "OK" on the dialog box, it transfers control back to the > form, and not save the empty fields into the database? > > What GUI toolkit are you using? > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kirk at daycos.com Tue Jul 1 11:24:00 2008 From: kirk at daycos.com (Kirk Strauser) Date: Tue, 01 Jul 2008 10:24:00 -0500 Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> Message-ID: <87vdzpmxv3.fsf@internal.daycos.com> At 2008-06-30T19:34:53Z, Mike writes: > I should have say "why embedding HTML into Python is not good enough?" ;=) I'm a programmer and would be able to cope with embedding HTML in assembler if the need arose. Having said that, embedding HTML in anything but HTML tends to be a bad idea in the long run. Inevitably, you're going to want to move stuff around, and find out that you can't just move print "

    " for item in itemlist: print "
  • %s
  • " % item print "
" up near the top because you don't actually define itemlist until near the end of your function, because it's built on the results of a bunch of other code. So then you "solve" the problem by leaving that snippet where it is and moving all the other HTML print commands after it. Oh, crud! You realize too late that some of your print commands have side effects: for item in deletelist: print "

Deleting %s: %s

" % (str(item), mangle(item)) and if you run that code *after* you generate itemlist, the results will be all screwed up. So you go back and move all of your logic to the top of the function and all of the HTML print statements to the bottom. And then you realize you've written your very own page template, and that it's ugly, and that you should've used something different from the very beginning. That's why you don't embed HTML in Python, at least not for anything more complicated than "Hello, world". -- Kirk Strauser The Day Companies From google at mrabarnett.plus.com Thu Jul 10 13:35:33 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 10 Jul 2008 10:35:33 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: Message-ID: <8feab8ce-1e09-4438-b00a-3b31956c56af@k37g2000hsf.googlegroups.com> On Jul 10, 4:56?am, Jordan wrote: > I am trying to rewrite some C source code for a poker hand evaluator > in Python. ?Putting aside all of the comments such as just using the C > code, or using SWIG, etc. ?I have been having problems with my Python > code not responding the same way as the C version. > > C verison: > > unsigned find_fast(unsigned u) > { > ? ? unsigned a, b, r; > ? ? u += 0xe91aaa35; > ? ? u ^= u >> 16; > ? ? u += u << 8; > ? ? u ^= u >> 4; > ? ? b ?= (u >> 8) & 0x1ff; > ? ? a ?= (u + (u << 2)) >> 19; > ? ? r ?= a ^ hash_adjust[b]; > ? ? return r; > > } > > my version (Python, hopefully ;)): > > def find_fast(u): > ? ? u += 0xe91aaa35 > ? ? u ^= u >> 16 > ? ? u += u << 8 > ? ? u ^= u >> 4 > ? ? b ?= (u >> 8) & 0x1ff > ? ? a ?= (u + (u << 2)) >> 19 > ? ? r ?= a ^ hash_adjust[b] > ? ? return r > > As far as I understand the unsigned instructions in C just increase > amount of bytes the int can hold, and Python automatically converts to > longs which have infinite size when necessary, so I am not sure why I > am getting different results. > > I assume that I am missing something fairly simple here, so help a > n00b out if you can :) > > Thanks in advance, > > jnb You want to restrict the values to 32 bits. The result of + or << may exceed 32 bits, so you need to mask off the excess bits afterwards. def find_fast(u): mask = 0xffffffff u = (u + 0xe91aaa35) & mask u ^= u >> 16 u = (u + (u << 8)) & mask # can get away with only 1 mask here u ^= u >> 4 b = (u >> 8) & 0x1ff a = ((u + (u << 2)) & mask) >> 19 # can get away with only 1 mask here r = a ^ hash_adjust[b] return r HTH From larry.bates at websafe.com` Mon Jul 14 18:27:50 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 14 Jul 2008 17:27:50 -0500 Subject: Using Python To Launch Python In-Reply-To: References: Message-ID: aha wrote: > Hello All, > I have a situation where I can count on a Python installation being > available on a system, but I can't count on it being a version of > Python needed by my application. Since my application has it's own > version of Python installed with it how should I use the system Python > to launch the version of Python that launches my Application. Yes, > this is a convoluted process, but not all Pythons are built the > same :) > > Right now I am leaning towards using exec to start a new process, but > I thought I would check to see if anyone else has had the need to > perform a task similar to this one. > > AHA You didn't tell us what operating system, but if by chance it is Windows you should use py2exe to package up your program (along with the proper pythonXX.dll) into a distributable package. On Linux, others have posted answers. -Larry From russblau at hotmail.com Wed Jul 9 16:41:17 2008 From: russblau at hotmail.com (Russell Blau) Date: Wed, 9 Jul 2008 16:41:17 -0400 Subject: variable question References: <01da01c8e1fb$7615a4f0$a701a8c0@office.ipglobal.net> Message-ID: "Support Desk" wrote in message news:01da01c8e1fb$7615a4f0$a701a8c0 at office.ipglobal.net... > I am trying to assign a variable using an if / else statement like so: > If condition1: > Variable = something > If condition2: > Variable = something else > Do stuff with variable. > > But the variable assignment doesn't survive outside the if statement. Is > there > any better way to assign variables using an if statement or exception so I > don't > have to write two almost identical if statements. This is probably a dumb > question. The variable assignment should survive outside the if statements: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> if "yes" == "no": value = "impossible" >>> if "no" == "no": value = "possible" >>> print value possible >>> You probably want to watch out for the possibility that both Condition1 and Condition2 are false; otherwise, you will get a NameError when you try to access Variable without initializing it. (By the way, as a matter of style, Python variable names are usually written in all lower-case letters.) Russ From steve at REMOVE-THIS-cybersource.com.au Thu Jul 31 18:25:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Jul 2008 22:25:23 GMT Subject: Standard module for parsing emails? References: <6fb93eFap7j5U1@mid.individual.net> <00a11e11$0$20313$c3e8da3@news.astraweb.com> Message-ID: <00a2373d$0$20313$c3e8da3@news.astraweb.com> On Thu, 31 Jul 2008 02:25:37 +0000, Steven D'Aprano wrote: > On Wed, 30 Jul 2008 07:11:45 -0700, Phillip B Oldham wrote: > >> Most clients use ">" which is easy to check for, but I've seen some >> which use "|" and some which *don't* quote at all. Its causing us >> nightmares in parsing responses to system-generated emails. I was >> hoping someone might've seen the problem previously and released some >> code. > > My sympathies. > > I've even seen clients that prefix new (unquoted) text with the quote > character ">". Well, this is a new one I've never seen before: found on the python-dev mailing list, somebody who (apparently) marks quoted text by inserting a bare quote character on an otherwise empty line after each line of text, similar to this: I've even seen clients that prefix new (unquoted) text with the quote > character ">". > The user in question seems to be using gmail. I suspect a PEBCAK error. -- Steven From larry.bates at websafe.com` Mon Jul 21 23:40:21 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 22:40:21 -0500 Subject: Python Written in C? In-Reply-To: References: Message-ID: giveitawhril2008 at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. SPSS (was and may still be) written in Fortran and the Fortran compiler was written in C. But NOBODY would suggest that you try to solve the problems that SPSS is used for in C. You talk about "writing it in assembly language for each MPU chip". Actually it is even better than that. We now have these modern inventions, called compilers that do that type of work for us. They translate high level instructions, not into assembler but into machine language. -Larry From Caseyweb at gmail.com Mon Jul 28 09:42:39 2008 From: Caseyweb at gmail.com (Casey) Date: Mon, 28 Jul 2008 06:42:39 -0700 (PDT) Subject: Where is the correct round() method? References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> <90d24864-c67a-4594-b121-d0760f9e145b@m45g2000hsb.googlegroups.com> Message-ID: <765f65f2-9870-44d6-b6d9-d8efc07cb5f3@c65g2000hsa.googlegroups.com> On Jul 28, 12:34?am, Gary Herron wrote: > This will work as you wish: > ? math.floor(x+0.5) This works fine for positive x but what about negative: >>> round(2.5) 3.0 >>> floor(2.5 + 0.5) 3.0 >>> round(-2.5) -3.0 >>> floor(-2.5 + 0.5) -2.0 Maybe: def round2(x): return math.floor(x + (0.5 if x >= 0 else -0.5)) From KDawg44 at gmail.com Fri Jul 18 15:35:39 2008 From: KDawg44 at gmail.com (KDawg44) Date: Fri, 18 Jul 2008 12:35:39 -0700 (PDT) Subject: Distributing Python App Message-ID: <072bf39b-d700-482e-ab59-36840e21e83e@a70g2000hsh.googlegroups.com> Hi, I am very new to Python but find it very interesting (from what I know of it) and am considering writing an application. However, I have a question regarding distribution of the app once it is done. Is there a way to package everything a user needs to run the app or will they have to install Python their machine? This is probably an obvious question but most development I do is for administrative tasks on servers and such, not usually development of an app for someone else. Thanks for your help. Kevin From michael at stroeder.com Sun Jul 6 14:03:58 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Sun, 06 Jul 2008 20:03:58 +0200 Subject: ANN: python-ldap-2.3.5 Message-ID: Find a new release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.3.5 2008-07-06 Changes since 2.3.4: Lib/ * Fixed methods ldap.cidict.__contains__() and ldap.schema.models.Entry.__contains__() * FWIW method LDAPObject.cancel_s() returns a result now * Fixed ldap.schema.models.NameForm: Class attribute oc is now of type string, not tuple to be compliant with RFC 4512 From basti.wiesner at gmx.net Wed Jul 23 11:59:53 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Wed, 23 Jul 2008 17:59:53 +0200 Subject: Proper way to query user and group database on a Unix host? References: <87d4l5ozsc.fsf@cox.net> Message-ID: Guilherme Polo : > On Wed, Jul 23, 2008 at 9:16 AM, Sebastian lunar Wiesner > wrote: >> Chris Brannon : >> >> Iirc since Python 2.5 these tuples are named ... >> >>> Instead, do this: >>> >>> import grp >>> groupname = 'users' >>> groupusers = grp.getgrnam(groupname)[3] >> ... thus this line could be written as: >> >> groupusers = grp.getgrnam(groupname).gr_mem >> > > That is valid since Python 2.3 actually Thanks for clarification -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From usenet at solar-empire.de Tue Jul 15 06:36:44 2008 From: usenet at solar-empire.de (Marc Christiansen) Date: Tue, 15 Jul 2008 12:36:44 +0200 Subject: Testing for Internet Connection References: <1216113021.24038.0@proxy02.news.clara.net> Message-ID: Alex Marandon wrote: > Alexnb wrote: >> I am wondering, is there a simple way to test for Internet connection? If >> not, what is the hard way :p > > Trying to fetch the homepage from a few major websites (Yahoo, Google, > etc.)? If all of them are failing, it's very likely that the connection > is down or there is a mandatory proxy... Does it count as internet connection, when only port 80 and port 443 are accessible and those require going through a proxy (very strict firewall policy)? Or everything requires using SOCKS? Just some possible problems I came up with. I don't know how often some- thing like this will happen. Ciao Marc From Younger.Wang at packetfront.com Fri Jul 18 05:15:41 2008 From: Younger.Wang at packetfront.com (Younger Wang) Date: Fri, 18 Jul 2008 11:15:41 +0200 Subject: DocBook support of Python Message-ID: Hi, Is there any module for parsing DocBook? Thanks! BR Younger Wang -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcfg at sina.com Thu Jul 17 11:02:17 2008 From: tcfg at sina.com (fang) Date: Thu, 17 Jul 2008 08:02:17 -0700 (PDT) Subject: how to debug python's extend module written in c/c++ on windows References: <64d771b2-fbc8-4b6a-9725-3dc5063c5328@p25g2000hsf.googlegroups.com> <6e83v4F5pfg0U1@mid.uni-berlin.de> <6e8cfgF5n34gU1@mid.uni-berlin.de> <3ac0db1c-81d2-4922-9133-5da830f5a346@34g2000hsh.googlegroups.com> <6e93qhF60lqfU1@mid.uni-berlin.de> Message-ID: <0a809ea4-2211-4b02-84a3-784862248f23@b1g2000hsg.googlegroups.com> Dear Diez: I see. I appreciate your help really. best regards fang From barun.saha04 at gmail.com Wed Jul 23 09:32:20 2008 From: barun.saha04 at gmail.com (barun.saha04 at gmail.com) Date: Wed, 23 Jul 2008 06:32:20 -0700 (PDT) Subject: Problem with Python Server Pages (PSP) References: <9766b993-03e6-4b75-92a2-06244c41e51c@a1g2000hsb.googlegroups.com> <8ce2ffdd-0fb3-4f5f-bde8-1598f9b231bc@i20g2000prf.googlegroups.com> <53b1f015-edc8-4225-aeab-1082e07c57c3@j33g2000pri.googlegroups.com> Message-ID: <49fc194a-938b-4b36-b521-eaf9f474c85c@v39g2000pro.googlegroups.com> On Jul 23, 6:18 pm, Graham Dumpleton wrote: > On Jul 22, 1:54 pm, barun.sah... at gmail.com wrote: > > > > > On Jul 22, 5:18 am, Graham Dumpleton > > wrote: > > > > On Jul 21, 9:42 pm, barun.sah... at gmail.com wrote: > > > > > Hi, > > > > > I am facing a very basic problem with PSP. I have installedmod_python > > > > (in fedora Core 1), added the lines required for loading Python > > > > modules and handling PSP pages. I have created a hello.psp page. But > > > > when I try to view this hello.psp page, all Python code are getting > > > > displayed. > > > > > The said page is stored at /var/www/html/psp/hello.psp. I guess this > > > > is some configuration problem with Apache, but not able to figure out > > > > the exact problem. I have tried putting those configuration lines for > > > > psp in both httpd.conf and python.conf files. But still it is not > > > > working. > > > > > The Python module (mod_python) is getting loaded. Because when I > > > > telnet to my server, I can find that in the headers. > > > > > These are the versions of the softwares: > > > > Apache: 2.0.47 > > > > Python: 2.2.3mod_python: 3.0.3 > > > > > Thnaks for all your suggestions. > > > > What is the Apache configuration snippet you are using to enable > > >mod_pythonand PSP file handling? > > > > Graham- Hide quoted text - > > > > - Show quoted text - > > > Hi Graham, > > > The configuration used in httpd.conf file looks like: > > > > AddHandler .psp .psp_ > > PythonHandler modules/python > > PythonDebug On > > > > Go read the documentation properly. > > http://www.modpython.org/live/current/doc-html/hand-psp.html > > What is PythonHandler set to? > > Graham Hi Graham, I'm extremely sorry. I had typed wrongly the configuration. Following is the one I'm using: AddHandler mod_python .psp .psp_ PythonHandler mod_python.psp PythonDebug On Strange thing is, same thing is working in windows, but not in Linux. From fredrik at pythonware.com Wed Jul 23 16:06:18 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 22:06:18 +0200 Subject: repr(string) In-Reply-To: References: Message-ID: David C. Ullrich wrote: > I've been saving data in a file with one line per field. > Now some of the fields may become multi-line strings... > > I was about to start escaping and unescaping linefeeds > by hand, when I realized that repr() and eval() should > do. Hence the question: If s is a string, is repr(s) > guaranteed not to contain line breaks? yes. just keep in mind that using eval() on untrusted data isn't a very good idea. From tjreedy at udel.edu Fri Jul 18 16:37:07 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Jul 2008 16:37:07 -0400 Subject: Question on Joining of list In-Reply-To: <32a81d0c-a74f-4b22-8add-15beb2643529@h17g2000prg.googlegroups.com> References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> <6eb733F67cpfU2@mid.uni-berlin.de> <32a81d0c-a74f-4b22-8add-15beb2643529@h17g2000prg.googlegroups.com> Message-ID: SUBHABRATA wrote: > Sorry if I didn't say that. > The input is a string "Petrol Helium Heaven Sky" > Now, in a3 it is "God Goddess Heaven Sky" is there, > ...I was looking for an output of "H S Petrol Helium" Meaningful names, splitting the target string, and using 'in' makes the code much easier. inwords = "Petrol Helium Heaven Sky".split() targets = "God Goddess Heaven Sky".split() found = [] not_found = [] for word in inwords: if word in targets: found.append(word[0]) else: not_found.append(word) found.extend(not_found) print(' '.join(found)) # 3.0 #prints the requested H S Petrol Helium From steve at REMOVE-THIS-cybersource.com.au Wed Jul 30 22:41:08 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Jul 2008 02:41:08 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> Message-ID: <00a121b4$0$20313$c3e8da3@news.astraweb.com> On Wed, 30 Jul 2008 09:23:05 -0600, Matthew Fitzgibbons wrote: > If you're expecting a list (and only a list) > then your point makes sense. 'if x' can get you into trouble if you > _don't_ want its polymorphism. "if x" is hardly unique in that way. If you're expecting a list, and only a list, "len(x) != 0" will get you in trouble if somebody passes a string or a dictionary. I don't see any reason why we should single out "if x" as dangerous in the face of invalid types. With the exception of the "is" and "is not" operators, nothing in Python is guaranteed to work with any imaginable object. Even print can fail, if the object's __str__ method raises an exception. > Although, if my function is expecting a list, my preference is to do: > > if not isinstance(x, list): > raise SomeMeaningfulException() > # do stuff with the list > > I put my type checking at the top of the function, so readers can > reference it easily. And thus you break duck-typing and upset anybody who wants to pass a sequence that doesn't inherit directly from list. There are other (and arguably better, although more labour-intensive) techniques for defensive programming that don't break duck-typing. You can google for Look Before You Leap and Easier To Ask Forgiveness Than Permission for more information. Alex Martelli has a fine recipe in the Python Cookbook -- search for the recipe "Checking if an object has the necessary attributes". But in a nutshell, here's a toy example: def spam(seq): try: seq.append seq.extend seq[0] = seq[0] except Exception: raise TypeError("argument isn't sufficiently sequence-like") # No exceptions expected from here on seq.append(seq[0]) seq.extend([1,2,3]) seq[0] = "spam" -- Steven From kay.schluehr at gmx.net Sun Jul 20 03:08:02 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 20 Jul 2008 00:08:02 -0700 (PDT) Subject: Not entirely serious: recursive lambda? References: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> Message-ID: On 20 Jul., 04:43, Michael Tobis wrote: > Can a lambda call itself without giving itself a name? Sure, use a fixed point combinator. I've just added this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/576366 > Google was not my friend on this one, and I suspect there is no > answer. Even the Great Google can't help if you don't use the right keywords ;) From fredrik at pythonware.com Thu Jul 17 03:53:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 09:53:13 +0200 Subject: Rotating a cube In-Reply-To: References: Message-ID: J-Burns wrote: > Is there a built in Python function for this? for answering questions that have nothing to do with programming, and looks quite a bit like homework? don't think they've added that one yet. maybe you should look for a geometry newsgroup/forum? From cheappuma at 126.com Fri Jul 18 20:40:26 2008 From: cheappuma at 126.com (128) Date: Fri, 18 Jul 2008 17:40:26 -0700 (PDT) Subject: paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) Message-ID: paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle shirt (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hat (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle hoody (paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle jeans(paypal accept)(www power-saler cn ) paypal wholesale 5ive jungle sunnglass(paypal accept)(www power-saler cn ) From mrmakent at cox.net Tue Jul 1 14:58:55 2008 From: mrmakent at cox.net (Mike Kent) Date: Tue, 1 Jul 2008 11:58:55 -0700 (PDT) Subject: Convert string to char array References: <0%uak.283$4a3.73@trnddc04> Message-ID: <4670347e-2531-4449-a171-e352e1053864@r66g2000hsg.googlegroups.com> On Jul 1, 2:49?pm, "Brandon" wrote: > How do I convert a string to a char array? ?I am doing this so I can edit > the string received from an sql query so I can remove unnecessary > characters. Answering your specific question: Python 2.5.1 (r251:54863, Mar 31 2008, 11:09:52) [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> s = 'hello' >>> l = list(s) >>> l ['h', 'e', 'l', 'l', 'o'] >>> But more generally, you might want to read up on the string methods available to you, such as replace(): http://docs.python.org/lib/string-methods.html From rocksportrocker at googlemail.com Wed Jul 23 14:56:03 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Wed, 23 Jul 2008 11:56:03 -0700 (PDT) Subject: Using variables across modules References: <855136ce-6c70-40ac-a462-dc0bbfa1fc3a@b2g2000prf.googlegroups.com> Message-ID: <121c5161-9485-4d6a-a447-9f9dd4227bac@d77g2000hsb.googlegroups.com> Aaron Scott schrieb: > I'm having some trouble understanding how Python handles variables > across multiple modules. I've dug through the documentation, but I > still find myself at a loss. > > When you import a module, are you creating an instance of the > variables within? For instance, if I have one file, "variables.py", > which contains "myvar = 0", and I import it into both "foo.py" and > "bar.py" with the line "from variables import *", and then set myvar > in "foo.py" and "bar.py" to different values, will each file have a > different value for myvar? If so, how can I ensure that a change to > myvar in "bar.py" is reflected by "foo.py"? Or am I completely off > base? Just wirte test code ! Python is cool for checking such things, you do do not have to compile, you need not write boilerplate main() stuff. Greetings, Uwe From aisaac at american.edu Thu Jul 10 15:07:19 2008 From: aisaac at american.edu (Alan Isaac) Date: Thu, 10 Jul 2008 19:07:19 GMT Subject: Python with Ecmascript In-Reply-To: References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <486fe241$0$867$ba4acef3@news.orange.fr> Message-ID: Daniel Fetchinson wrote: > Is there a way to do similar things on linux? NJSModule? http://en.wikipedia.org/wiki/NJS Alan Isaac From jordanrastrick at gmail.com Thu Jul 24 11:03:45 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 08:03:45 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <40449826-c71d-4c6e-8b74-13069269e5da@z6g2000pre.googlegroups.com> <488896bf$0$3493$426a74cc@news.free.fr> Message-ID: <3d56ad67-bcd7-4840-979a-8648292afcff@j7g2000prm.googlegroups.com> > Then why do you write, let me quote: > > """ > (snip) coding __eq__ (snip) buys you > nothing from the != operator. != isn't (by default) a synonym for the > negation of == (unlike in, say, every other language ever); not only > will Python let you make them mean different things, without > documenting this fact - it actively encourages you to do so. > """ My words aren't as clear as they should be. I mean that Python lets *you* do something without documenting, or rather stating to use a better term, that your intention is the non-obvious one. I'm not saying that Python itself lacks documentation for its own behaviour; I'm saying it should force you to make your intentions clear and visible to someone reading your code when you want to do something non- obvious. > I was not commenting on the actual design choice, just stating that it > is actually documented. Yes, it is. I apologise for the poor construction of my statement which led to this confusion. > And you're talking about strawman ??? Come on, you obviously can tell > the difference between a one-line statement and your above strawman > argument, don't you ? I'm talking about strawmen because I was deliberately choosing to invoke one with rhetorical flourish for the purposes of making my point forcefully. I wanted people to be clear that I knew perfectly well what I was doing and that they needn't call me out on it. > Please understand that I'm not arguing about this particular design > choice (and FWIW, I'd mostly agree on the point that having a != b > different from not (a == b) is actually a wart). I'm just correcting > your statement about the behaviour of __eq__ / __ne__ not being > documented, which is obviously false. Good, at least we've come to a point in this discussion where I can firmly agree with somebody. From motoom at xs4all.nl Sat Jul 19 15:45:03 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Sat, 19 Jul 2008 21:45:03 +0200 Subject: win32api not found? In-Reply-To: References: Message-ID: <200807192145.03118.motoom@xs4all.nl> On Saturday 19 July 2008 21:13:04 Lamonte Harris wrote: > Where can I get the win32api module? I been searching all day on google and > nothing, i installed > https://sourceforge.net/project/showfiles.php?group_id=78018 which requires > win32api and its not found... What are the actions you do and the commands you give, and what is the precise error you get? Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From mccredie at gmail.com Mon Jul 14 21:56:34 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 14 Jul 2008 18:56:34 -0700 (PDT) Subject: One step up from str.split() References: Message-ID: <2f7e2895-e1ee-4113-a6bf-a3a15235f27c@w7g2000hsa.googlegroups.com> On Jul 14, 6:33 pm, "Joel Koltner" wrote: > I normally use str.split() for simple splitting of command line arguments, but > I would like to support, e.g., long file names which-- under windows -- are > typically provided as simple quoted string. E.g., > > myapp --dosomething --loadthis "my file name.fil" > > ...and I'd like to get back a list wherein ListEntry[3]="my file name.fil" , > but just running str.split() on the above string creates: > > >>> ListEntry='myapp --dosomething --loadthis "my file name.fil"' > >>> ListEntry.split() > > ['myapp', '--dosomething', '--loadthis', '"my', 'file', 'name.fil"'] > > Is there an easy way to provide just this one small additional feature > (keeping quoted names as a single entry) rather than going to a full-blown > command-line argument parsing tool? Even regular expressions seem like they'd > probably be overkill here? Or no? > > Thanks, > ---Joel look at the shlex module: >>> import shlex >>> txt = 'myapp --dosomething --loadthis "my file name.fil"' >>> shlex.split(txt) ['myapp', '--dosomething', '--loadthis', 'my file name.fil'] Matt From bruno.desthuilliers at gmail.com Tue Jul 15 09:53:31 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Tue, 15 Jul 2008 06:53:31 -0700 (PDT) Subject: Method behavior for user-created class instances References: <42433fcd-fcdc-4f42-a427-c28241734b7c@z66g2000hsc.googlegroups.com> Message-ID: On 15 juil, 01:24, crazychimp... at gmail.com wrote: > Greetings. > > I am looking for a way to achieve method behavior for a class I > created. That is, it has a __call__ method, so can be called like a > function. But I also want it to be treated as a method when it appears > in a class body. You need to implement the descriptor protocol the same way the function type do. import types class Foo(object): def __call__(self, instance): print "%s - %s" % (self, instance) def __get__(self, instance, cls): return types.MethodType(self, instance, cls) class Bar(object): foo = Foo() b = Bar() b.foo() > I know this has to do with writing the __get__ > method of foo, but I am wondering if there is perhaps some class I can > just inherit from to get the proper __get__, which behaves identically > to that of regular Python functions. Extending types.FunctionType doesn't work OOTB (there's some incompatibility wrt/ metaclasses) From JordanNealBerg at gmail.com Thu Jul 10 01:45:21 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Wed, 9 Jul 2008 22:45:21 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: Message-ID: <47741438-f523-4a9b-ad7f-86e5628dade8@m36g2000hse.googlegroups.com> if after the first step (u += 0xe91aaa35) you apply this function: invert = lambda x: ~int(hex(0xffffffff - x)[0:-1],16) it returns the correct value (corrected the overflow) but there is still something wrong, still looking into it, if someone knows how to do this, feel free to comment :) From jkugler at bigfoot.com Tue Jul 15 18:07:09 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Tue, 15 Jul 2008 14:07:09 -0800 Subject: Is re.findall guaranteed to be "in order?" Message-ID: I tried looking through re.py and sre_compile.py, but I can't really see an answer to my question. Experimenting has shown me that re.findall() will return a list with the matches in the order it found them. Am I lucky so far, or does the _sre.c's logic dictate the items will be added in order found? http://svn.python.org/view/python/tags/r25c1/Modules/_sre.c?rev=51334&view=auto (search for "pattern_findall") seems to indicate they will be added in order, but can someone with a better handle on Python internals (and quite frankly, C) confirm this? Thanks! j From jim.hefferon at gmail.com Tue Jul 1 20:42:28 2008 From: jim.hefferon at gmail.com (Jim) Date: Tue, 1 Jul 2008 17:42:28 -0700 (PDT) Subject: convert unicode characters to visibly similar ascii characters References: <17d4c282-8606-4d29-9e71-d34f5e6d13bb@m44g2000hsc.googlegroups.com> Message-ID: On Jul 1, 8:29 pm, John Machin wrote: > On Jul 2, 9:55 am, Jim wrote: > > Comments on the above grep output: > 1. You have SOFT HYPHEN twice, mapping it to u'-' and '-' Hmph. I'll correct that. Thanks. > 2. The idea of a soft hyphen is as a hint to a hyphenator about where > to insert a hyphen if one is necessary and the hyphenator is suspected > of acting cluelessly without the hint. IMHO, asciification should > substitute u'', not u'-'. Thanks also here. I'll think about it. > 3. Read PEP 8. s/:/: / I don't like the spacing in 8, personally. Thanks, Jim From ldo at geek-central.gen.new_zealand Wed Jul 23 19:12:59 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 24 Jul 2008 11:12:59 +1200 Subject: Is this a valid use of 'import'? References: Message-ID: In message , Frank Millman wrote: > from Utils.client import * Besides the objections that others have mentioned, I HATE seeing wildcard imports. From jeffober at gmail.com Tue Jul 8 07:47:58 2008 From: jeffober at gmail.com (Jeff) Date: Tue, 8 Jul 2008 04:47:58 -0700 (PDT) Subject: caseless dict - questions References: <77798300-820f-4175-a9cb-aef639d42a32@m45g2000hsb.googlegroups.com> Message-ID: <7370727f-7b15-4dbc-9f42-35ec2df34806@56g2000hsm.googlegroups.com> Use the __str__ and __unicode__ methods to control the printed representation of a class. From workitharder at gmail.com Mon Jul 28 13:30:51 2008 From: workitharder at gmail.com (bukzor) Date: Mon, 28 Jul 2008 10:30:51 -0700 (PDT) Subject: binding names doesn't affect the bound objects (was: print doesn't respect file inheritance?) References: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> <8763qtmgo7.fsf@benfinney.id.au> Message-ID: <87d64aab-49a1-4753-ac0e-6f7cbfd17e39@f36g2000hsa.googlegroups.com> On Jul 26, 7:08?am, "D'Arcy J.M. Cain" wrote: > On Sat, 26 Jul 2008 14:07:52 +1000 > > Ben Finney wrote: > > > ? ? sys.stdout = n > > > Re-binds the name 'sys.stdout' to the object already referenced by the > > name 'n'. No objects are changed by this; only bindings of names to > > objects. > > I do agree that the object formerly known as sys.stdout hasn't changed. > > > > ? ? print "Testing: 1, 2, 3..." > > > Doesn't rely at all on the name 'sys.stdout', so isn't affected by all > > the binding of names above. > > Hmm. ?Are you saying that the following doesn't work? > > $ python>>> f = open("test", "w") > >>> import sys > >>> sys.stdout = f > >>> print "test message" > >>> sys.exit(0) > > $ cat test > test message > > > In other words, you can't change the object used by the 'print' > > statement only by re-binding names (which is *all* that is done by the > > '=' operator). > > Apparently I can. > > > You can, however, specify which file 'print' should use > > . > > Which contains this statement. > > "Standard output is defined as the file object named stdout in the > built-in module sys." > > I suppose that there might be some ambiguity there but the proof, as > they say, is in the pudding. > > -- > D'Arcy J.M. Cain ? ? ? ? | ?Democracy is three wolveshttp://www.druid.net/darcy/? ? ? ? ? ? ? ?| ?and a sheep voting on > +1 416 425 1212 ? ? (DoD#0082) ? ?(eNTP) ? | ?what's for dinner. Thanks for backing me up. Nobody here thinks it's strange that print uses *none* of the attributes or methods of sys.stdout to do its job? The implementation seems to bypass the whole python system and use C-level FILE* pointers directly instead. From thogiti at gmail.com Mon Jul 7 17:48:12 2008 From: thogiti at gmail.com (Nagu) Date: Mon, 7 Jul 2008 14:48:12 -0700 Subject: Memory error while saving dictionary of size 65000X50 using pickle Message-ID: <21da85430807071448s43b69432q806705039aa3531a@mail.gmail.com> I didn't have the problem with dumping as a string. When I tried to save this object to a file, memory error pops up. I am sorry for the mention of size for a dictionary. What I meant by 65000X50 is that it has 65000 keys and each key has a list of 50 tuples. I was able to save a dictionary object with 65000 keys and a list of 15-tuple values to a file. But I could not do the same when I have a list of 25-tuple values for 65000 keys. You exmple works just fine on my side. Thank you, Nagu From fredrik at pythonware.com Wed Jul 23 16:18:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 22:18:25 +0200 Subject: interpreter vs. compiled In-Reply-To: <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> Message-ID: castironpi wrote: > Compiling a program is different than running it. A JIT compiler is a > kind of compiler and it makes a compilation step. I am saying that > Python is not a compiler and in order to implement JIT, it would have > to change that fact. good thing Python don't have to listen to you, then, so it can keep using its built-in compiler to produce programs for its built-in VM. > But still not the user's code, only the interpreter, which is running > in assembly already anyway in CPython. good luck with your future career in computing! From gnewsg at gmail.com Wed Jul 9 07:13:22 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Wed, 9 Jul 2008 04:13:22 -0700 (PDT) Subject: Doubts about how implementing asynchronous timeouts through a heap Message-ID: <80430d47-aac5-4123-8835-0591faf0baed@34g2000hsf.googlegroups.com> Hi, I'm trying to implement an asynchronous scheduler for asyncore to call functions at a later time without blocking the main loop. The logic behind it consists in: - adding the scheduled functions into a heapified list - calling a "scheduler" function at every loop which checks the scheduled functions due to expire soonest Note that, by using a heap, the first element of the list is always supposed to be the one with the lower timeout. Here's the code I wrote: <--- snippet ---> import heapq import time import sys delayed_map = [] class delayed_call: """Calls a function at a later time. The instance returned is an object that can be used to cancel the scheduled call, by calling its cancel() method. It also may be rescheduled by calling delay() or reset()} methods. """ def __init__(self, delay, target, *args, **kwargs): """ - delay: the number of seconds to wait - target: the callable object to call later - args: the arguments to call it with - kwargs: the keyword arguments to call it with """ assert callable(target), "%s is not callable" %target assert sys.maxint >= delay >= 0, "%s is not greater than or equal " \ "to 0 seconds" % (delay) self.__delay = delay self.__target = target self.__args = args self.__kwargs = kwargs # seconds from the epoch at which to call the function self.timeout = time.time() + self.__delay self.cancelled = False heapq.heappush(delayed_map, self) def __le__(self, other): return self.timeout <= other.timeout def active(self): """Return True if this scheduler has not been cancelled.""" return not self.cancelled def call(self): """Call this scheduled function.""" self.__target(*self.__args, **self.__kwargs) def reset(self): """Reschedule this call resetting the current countdown.""" assert not self.cancelled, "Already cancelled" self.timeout = time.time() + self.__delay if delayed_map[0] is self: heapq.heapify(delayed_map) def delay(self, seconds): """Reschedule this call for a later time.""" assert not self.cancelled, "Already cancelled." assert sys.maxint >= seconds >= 0, "%s is not greater than or equal " \ "to 0 seconds" %(seconds) self.__delay = seconds self.reset() def cancel(self): """Unschedule this call.""" assert not self.cancelled, "Already cancelled" del self.__target, self.__args, self.__kwargs if self in delayed_map: if delayed_map[0] is self: delayed_map.remove(self) heapq.heapify(delayed_map) else: delayed_map.remove(self) self.cancelled = True def fun(arg): print arg a = delayed_call(0.6, fun, '0.6') b = delayed_call(0.5, fun, '0.5') c = delayed_call(0.4, fun, '0.4') d = delayed_call(0.3, fun, '0.3') e = delayed_call(0.2, fun, '0.2') f = delayed_call(0.1, fun, '0.1') while delayed_map: now = time.time() while delayed_map and now >= delayed_map[0].timeout: delayed = heapq.heappop(delayed_map) try: delayed.call() finally: if not delayed.cancelled: delayed.cancel() time.sleep(0.01) Here comes the questions. Since that the timeouts of the scheduled functions contained in the list can change when I reset() or cancel() them I don't know exactly *when* the list needs to be heapified(). By doing some tests I came to the conclusion that I need the heapify() the list only when the function I reset() or cancel() is the *first of the list* but I'm not absolutely sure about it. When do you think it would be necessary calling heapify()? I wrote a short test suite which tests the code above and I didn't notice strange behaviors but since that I don't know much about the logic behind heaps I'd need some help. Thanks a lot in advance. --- Giampaolo http://code.google.com/p/pyftpdlib/ From mail at microcorp.co.za Wed Jul 9 03:09:14 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 9 Jul 2008 09:09:14 +0200 Subject: Cross Compiler for Python? References: <001101c8e0d2$36a50ec0$0d00a8c0@hendrik> <4873D882.6090109@hughes.net> Message-ID: <000e01c8e192$b4010660$0d00a8c0@hendrik> "norseman" wrote: 8< --------------------------------------------------------- > ....dreaded.... Yep! I know the feeling. Got lots of those T-Shirts. ;) > > > I re-read your original post. I got the feeling the eBox is running a > stripped down Linux. Is that so? If it is, then: Correct - a kernel, and busybox masquerading as the whole of GNU... > > You mention pcmcia. Is it external, a plug in? Do any of your > desktops/etc have pcmcia slots? Because if so..... Its part of the eBox - quite a neat implementation > > 1) Card can be mounted on your machine > 2) Compile and install can be direct to card (rem 32bit output) > just change the install path(s). Look over the eBox /lib > ( I'm assuming Linux again) and put that lib path first in > the compile command line. > > If no desktop pcmcia adapter - pay the $40 or so for an USB attachable > pcmcia adapter This is sane - I would need it if ever we get to using the thing, for loading software onto the devices anyway. > > sample: > plug in card > > (if current drives on desktop are scsi or sata drives you may need to > change sda to sdb or sdc or .... use fdisk /dev/sda to check existence. > the single letter 'q' to exit without changing anything. Careful with > fdisk - damage comes quickly, easily and unrepairable. All you are after > is which letter to use. Last one before No such drive is the one. > ) should be able to look in /dev - but I will be carefull... Also Suse and GUI should just pop up, like a USB stick does. > > cd /mnt > mkdir sda > mount /dev/sda1 /mnt/sda > ls /mnt/sda should give base dir listing of flashdrive > (linux will treat the pcmcia flash as a removable HardDrive) > > install to /mnt/sda/usr/local/lib (or /mnt/sda/--where ever--) > then: back on eBox > cd /mnt > mkdir sda > cd sda > ln -s /usr usr > > I did the soft link process above on my machine, then: > > ls /mnt/sda/usr/local/lib/python2.5 should list contents correctly > (and does on my machine since it is located in /usr/local/lib/python2.5) > thus keeping compile and install paths working. The use of the midnight > commander (mc) with card mounted makes transferring whole trees simple. > Soft links were invented for a reason! > > OF COURSE, if the eBox is not running Linux, all this is useless! ;) > > Steve Thanks a lot - this seems the way to go... - Hendrik From abumoaas1987 at yahoo.com Tue Jul 1 11:51:19 2008 From: abumoaas1987 at yahoo.com (ah) Date: Tue, 1 Jul 2008 08:51:19 -0700 (PDT) Subject: Discover Islam - The Fastest Growing Religion in the World ! Message-ID: <9d3ed65e-335c-4d45-8374-505ae7d434b1@p25g2000hsf.googlegroups.com> Correct your information about Islam , The Misunderstood Religion When you are ready_ you can enter this place!!! http://sultan.org From __peter__ at web.de Thu Jul 10 02:11:11 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Jul 2008 08:11:11 +0200 Subject: Relative Package Import References: Message-ID: Kay Schluehr wrote: > On 8 Jul., 21:09, Peter Otten <__pete... at web.de> wrote: >> Robert Hancock wrote: >> > mypackage/ >> > __init__.py >> > push/ >> > __init__.py >> > dest.py >> > feed/ >> > __init__py >> > subject.py >> >> > In subject.py I have >> > from ..push import dest >> >> > But i receive the error: >> > Caught exception importing module subject: >> > File "/usr/local/python/lib/python2.5/site-packages/pychecker/ >> > checker.py", line 621, in setupMainCode() >> > module = imp.load_module(self.moduleName, file, filename, smt) >> > File "subject.py", line 1, in () >> > from ..feed import dest >> > ValueError: Attempted relative import in non-package >> >> > What am I missing? >> >> When you run subject as a file >> >> pychecker mypackage/feed/subject.py >> >> subject.py is regarded as a standalone script, not as part of a package. >> Try >> >> pychecker mypackage.feed.subject >> >> instead to invoke the module via the standard import mechanism. >> >> Peter > > Since when are Python modules not regarded as standalone scripts but > as a "part of a package"? > > The only indication that there is some duality and that it is relevant > at all are those relative imports that came in with Python 2.5. As it > seems this feature is justified by the artificial semantic differences > it produces. I'm probably misunderstanding you, but the ambiguity I wanted to point out has existed before and has nothing artificial: $ tree . `-- mypackage |-- __init__.py |-- feed | |-- __init__.py | |-- subject.py | `-- subject.py~ `-- push |-- __init__.py `-- dest.py 3 directories, 6 files $ python2.4 -c "import mypackage.push.dest as d; print d.__name__" mypackage.push.dest $ cd mypackage/push/ $ python2.4 -c "import dest as d; print d.__name__" dest ".." in the import goes one up in the package name, not in the filesystem and therefore won't work in the second example. Peter From max at alcyone.com Wed Jul 30 02:36:58 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 23:36:58 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <6d906dd5-bf5a-44d5-a5a8-3875027f6b91@v26g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> <6d906dd5-bf5a-44d5-a5a8-3875027f6b91@v26g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > Come to think of it, shouldn't the list type have an "isempty" method? > Or does it? Yes. It's written: if not aList: ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The doors of Heaven and Hell are adjacent and identical. -- Nikos Kazantzakis From mensanator at aol.com Wed Jul 2 14:22:44 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 2 Jul 2008 11:22:44 -0700 (PDT) Subject: Python and timezones References: Message-ID: <66de1777-ab65-4708-904b-3e511409a662@m36g2000hse.googlegroups.com> On Jul 2, 12:43?am, "shand... at gmail.com" wrote: > I'm trying to write some code to deal with world timezones, and I'm > getting a strange result. ?America/Iqaluit should not be showing up in > UTC+00:00, but it is. ?Can anyone see what's wrong with this code? > > import time > from datetime import datetime > import os > import pytz > > def getZoneNamesOnThisComputer(): > ? ? for i in pytz.all_timezones: > ? ? ? ? if os.path.exists( os.path.join('/tmp/usr/share/zoneinfo/', > i)): > ? ? ? ? ? ? yield i > > def getZonesGroupedByOffset(): > ? ? '''return a dict of all the zone names , grouped by their offset > ? ? eg: > ? ? {'-0400': ['America/Blanc-Sablon', 'Etc/GMT+4'], > ? ? ?'+0000': ['America/Iqaluit', 'Etc/GMT', 'Europe/Belfast', 'GB', > 'GMT'], > ? ? ?... > ? ? } > ? ? ''' > ? ? Y,M,D,h,m,s = time.localtime()[:6] > > ? ? zonesGroupedByOffset = {} > > ? ? for name in getZoneNamesOnThisComputer(): > ? ? ? ? tz = pytz.timezone(name) > ? ? ? ? now = datetime(Y,M,D,h,m,s, tzinfo=tz) > ? ? ? ? # strfime returns a string like "-0800" or "+0430" or "0000" > ? ? ? ? offsetKey = now.strftime('%z') > ? ? ? ? if not zonesGroupedByOffset.has_key(offsetKey): > ? ? ? ? ? ? zonesGroupedByOffset[offsetKey] = [] > ? ? ? ? zonesGroupedByOffset[offsetKey].append(name) > ? ? return zonesGroupedByOffset > > z = getZonesGroupedByOffset() > print z['+0000'] > > # Why is America/Iqaluit showing up here??? The database contains an error. Shit happens, deal with it. From gh at ghaering.de Fri Jul 11 08:48:00 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 11 Jul 2008 14:48:00 +0200 Subject: python scalability In-Reply-To: <4876746D.3090003@gmail.com> References: <4876746D.3090003@gmail.com> Message-ID: Tim Mitchell wrote: > Thanks for all the replies - they have all been helpful. > > On reflection I think our problems are probably design and people related. I strongly agree. "Scalability" is becoming a buzzword lately, which is meaningless unless qualified what exactly is meant. It's overused wrt technologies, programming languages, tools, etc. But in other interesting areas people think much less about "scalability". Will the current software development process work with a team of 5, 10, 20, 50 team members? Does it "scale" here? Will the software development process still work with an increased turnover rate? Does it "scale"? Will the way of doing things still work with an increasingly aging codebase? -- Gerhard From tpt at kamstrup.dk Tue Jul 29 04:34:58 2008 From: tpt at kamstrup.dk (mindmind) Date: Tue, 29 Jul 2008 01:34:58 -0700 (PDT) Subject: ironpython, exception in mscorlib when reading .py file from network share Message-ID: <6dfb578a-17ff-434d-a071-646ed3ef2b03@z72g2000hsb.googlegroups.com> Hello, I have a ironpython 1.1.1.0 host in my c# app, and When doing a engine.ExecuteFile(file); i often get the error below, when "file" is on a network share : (winXp client , windows ??? server) 21-07-2008 12:47:28 : Traceback (most recent call last): 21-07-2008 12:47:28 : File c:\sandbox\xxx.cs 21-07-2008 12:47:28 : File c:\sandboxx\yyy.cs 21-07-2008 12:47:28 : File mscorlib, line unknown, in ReadAllBytes 21-07-2008 12:47:28 : File mscorlib, line unknown, in Read 21-07-2008 12:47:28 : File mscorlib, line unknown, in ReadCore 21-07-2008 12:47:28 : File mscorlib, line unknown, in WinIOError 21-07-2008 12:47:28 : IOError: The specified network name is no longer available. 21-07-2008 12:47:28 : Exception is caught before first line in python is executed. Other parts of the program is also accessing the network (for copying files etc), and never fails, so networks connection is "ok" (maybe not perfect, but at least present.) Is the ExecuteFile reading the contents of the .py file differently than a "copy" primitive is (other timeout/retry values) ? Does anyone have any ideas of how to setup windows , ironpython host or .NET lib differently, to stop it doing this ? Fallback solution is to copy file locally before execution, but I would rather fix this. thx From mail at timgolden.me.uk Thu Jul 17 04:22:37 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 17 Jul 2008 09:22:37 +0100 Subject: About wmi In-Reply-To: <3d1db021-6766-4d5d-9105-fdd81e27b671@26g2000hsk.googlegroups.com> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> <487E1AD4.9020509@timgolden.me.uk> <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> <3d1db021-6766-4d5d-9105-fdd81e27b671@26g2000hsk.googlegroups.com> Message-ID: <487F014D.40008@timgolden.me.uk> patrol wrote: > I will try to modify the wmi.py ,however I'm a novice.It will take a > long time. You can give it up temporarily. If you don't mind ,can you > tell me where needs modifying and how? Just unicode? Or Other? OK. Thanks for your patience on this one, Patrol. What I propose to do is to dig into the pywin32 sources to determine what's going on when the error messages are fetched. Then I'll be better placed to decide what to do when they come out. On the surface, the current module should be handling things correctly; but I've obviously missed an encode/decode somewhere. If I can think of an (even hackish) workaround for you in the meantime, I'll let you know. Until then... TJG From bj_666 at gmx.net Wed Jul 23 13:10:58 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 23 Jul 2008 17:10:58 GMT Subject: Python Written in C? References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> <6eosgtF7u58sU1@mid.uni-berlin.de> <537c58c3-d74c-41dd-8571-26cfbb415178@34g2000hsh.googlegroups.com> Message-ID: <6ep711F7u58sU2@mid.uni-berlin.de> On Wed, 23 Jul 2008 09:42:29 -0700, castironpi wrote: > On Jul 23, 9:11?am, Marc 'BlackJack' Rintsch wrote: >> On Wed, 23 Jul 2008 14:10:22 +0200, mk wrote: >> > Marc 'BlackJack' Rintsch wrote: >> >> I can't even remember when I deleted something from a list in the past. >> >> > Still, doesn't that strike you as.. workaround? >> >> No, I find it actually safer; I don't have to care where modifications of >> the list might be seen elsewhere in the program. >> >> Ciao, >> ? ? ? ? Marc 'BlackJack' Rintsch > > a[:]= newlist > > and > > a= newlist > > have two completely different effects, and one is just as safe as > 'del'. Besides, del isn't safe to be seen elsewhere in the program in > other threads, if they aren't locking the GIL. As usual you are talking nonsense? Ciao, Marc 'BlackJack' Rintsch From mathieu.prevot at ens.fr Fri Jul 11 06:50:20 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Fri, 11 Jul 2008 12:50:20 +0200 Subject: error with configure (svn 64857) In-Reply-To: References: <487681e9$0$9745$9b622d9e@news.freenet.de> Message-ID: <3e473cc60807110350s7db7f215hae510a1b9448144b@mail.gmail.com> 2008/7/11 WDC : > On Jul 10, 6:57 pm, "Mathieu Prevot" wrote: >> 2008/7/10 "Martin v. L?wis" : >> >> >> I have the following error when I run configure: >> >> >> checking size of wchar_t... configure: error: cannot compute sizeof (wchar_t) >> >> >> what can I do ? >> >> > Study config.log for the source of the problem. >> >> Thank you Martin. How can I remove -lgcc_s and use the Intel equivalent ? >> >> configure:21939: checking for wchar_t >> configure:21970: icc -c -g -O2 conftest.c >&5 >> conftest.c(123): warning #279: controlling expression is constant >> if ((ac__type_new_ *) 0) >> ^ >> >> configure:21976: $? = 0 >> configure:21991: result: yes >> configure:21998: checking size of wchar_t >> configure:22306: icc -o conftest -g -O2 conftest.c >&5 >> ld: library not found for -lgcc_s >> configure:22309: $? = 1 >> configure: program exited with status 1 >> >> Mathieu > > I think he wanted YOU to find the problem. The best way to learn is to > figure it out yourself! Good luck. Yes WDC I know, but for some problems 1) we can gain much efficiency with getting help from guys that are familiar with the environment and 2) we also allow the committers to know a problem and improve the sources. That's the way an open source group works IMHO :) Now that the problem is solved for me, it is for all MacOSX+Intel icc guys. Cheers, Mathieu From arnimavidyarthy at gmail.com Fri Jul 18 06:33:55 2008 From: arnimavidyarthy at gmail.com (arnimavidyarthy at gmail.com) Date: Fri, 18 Jul 2008 03:33:55 -0700 (PDT) Subject: trying to match a string Message-ID: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> Hi, Hi, I am taking a string as an input from the user and it should only contain the chars:L , M or R I tried the folllowing in kodos but they are still not perfect: [^A-K,^N-Q,^S-Z,^0-9] [L][M][R] [LRM]?L?[LRM]? etc but they do not exactly meet what I need. For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. regards, SZ The string may or may not have all the three chars. From timothywayne.cook at gmail.com Sun Jul 27 04:23:38 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Sun, 27 Jul 2008 05:23:38 -0300 Subject: Stripping parts of a path In-Reply-To: <8utn84hs5c713k54l5kmfrgbg3k2dr1oce@4ax.com> References: <8utn84hs5c713k54l5kmfrgbg3k2dr1oce@4ax.com> Message-ID: <1217147018.2920.1.camel@localhost.localdomain> On Sun, 2008-07-27 at 04:32 +0000, Tim Roberts wrote: > This doesn't do what you think it does. The parameter to rstrip is a set: > as long as the last character is in the set 'abcdhiloprs/', it will remove > it and check the next one. All of the characters in "shop" are in that > set. Thanks for all the replies. You are correct I misunderstood the docs. Finding and slicing works great. Cheers, Tim -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. Home page: https://launchpad.net/oship/ Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From sturlamolden at yahoo.no Tue Jul 8 16:35:49 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 8 Jul 2008 13:35:49 -0700 (PDT) Subject: sage vs enthought for sci computing References: <677e7819-e09e-43d3-8368-5864f91002be@34g2000hsh.googlegroups.com> Message-ID: On 7 Jul, 22:35, jadamwils... at gmail.com wrote: > Hello, > I have recently become interested in using python for scientific > computing, and came across both sage and enthought. I am curious if > anyone can tell me what the differences are between the two, since > there seems to be a lot of overlap (from what I have seen). If my goal > is to replace matlab (we do signal processing and stats on > physiological data, with a lot of visualization), would sage or > enthought get me going quicker? I realize that this is a pretty vague > question, and I can probably accomplish the same with either, but what > would lead me to choose one over the other? > Thanks! I work in neuroscience, and use Python of signal processing. I've used Matlab before. Python is just better. I do not use either Sage or Enthought. Instead I have istalled a vanilla Python and the libraries I need. The most important parts are: - Python 2.5.2 - NumPy - SciPy - Matplotlib - wxPython - pywin32 - PIL - Cython - PyOpenGL - mpi4py - processing module - gfortran and gcc (not a Python library, but I need a C and Fortran compiler) Less important stuff I also have installed: - Twisted - PyGame - MySQL and mysqldb - Python for .NET (http://pythonnet.sourceforge.net) - VideoCapture From asmodai at in-nomine.org Fri Jul 4 04:22:13 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 4 Jul 2008 10:22:13 +0200 Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: <486DCA32.5000705@gmail.com> References: <20080704053113.GJ34192@nexus.in-nomine.org> <486DCA32.5000705@gmail.com> Message-ID: <20080704082213.GN34192@nexus.in-nomine.org> -On [20080704 09:00], Aspersieman (aspersieman at gmail.com) wrote: >Here's a tutorial on setting this up. > http://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/ Thanks Nicol, there's some things there that can speed up my current setup as well. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Whispering winds in moonlit wood, a totem oak once golden stood... From mwilson at the-wire.com Tue Jul 8 21:54:30 2008 From: mwilson at the-wire.com (Mel) Date: Tue, 08 Jul 2008 21:54:30 -0400 Subject: "in"consistency? References: <87vdzhwf1v.fsf@benfinney.id.au> Message-ID: David C. Ullrich wrote: > Oh, of course that's a good thing - changing "in" for lists > to give True there would be awful. I was wondering why it > _does_ work that way for strings. > > Maybe the answer is "because it can" - for strings the sort > of possible problem you point out can't come up. I think that's it. When people realized how handy small_string in big_string would be, they expanded the string behaviour. Python is a pragmatic language. Cheers, Mel. From straton at lampsacos.demon.co.uk Mon Jul 28 19:12:50 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Tue, 29 Jul 2008 00:12:50 +0100 Subject: derivative in numpy In-Reply-To: References: Message-ID: knielsen73 at gmail.com wrote: > Hi, > > I am looking to do a simple derivative. I would expect such a function > to be available in numpy, but can't find it. I have written my own, > but just curious if anybody knows of such function in numpy. > > Cheers, > Kim numpy and much more are wrapped together in 'sage' and you should get the functionality you need there. For a review, see: http://vnoel.wordpress.com/2008/05/03/bye-matlab-hello-python-thanks-sage/ From skazhy at gmail.com Mon Jul 21 07:35:46 2008 From: skazhy at gmail.com (skazhy) Date: Mon, 21 Jul 2008 04:35:46 -0700 (PDT) Subject: simple question about dictionaries Message-ID: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> hi, i am new to python, so i've a really simple question about dictionaries. if i have a dictionary and I make have an input after it (to input numbers) can i get the key of value that was in input? somehting like this: dict = { "key1"=100,"key2"=200,"key3"=300} a = input() print 'the key of inputted value is', dict['a'] this syntax of course is wrong, but i hope you got the point.. thanks in advance! From castironpi at gmail.com Mon Jul 28 14:23:23 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 28 Jul 2008 11:23:23 -0700 (PDT) Subject: QOTW [was Re: Attack a sacred Python Cow] References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> <7360bd9a-4ff6-4e75-821c-eabc88ee6258@u6g2000prc.googlegroups.com> <009dce32$0$20313$c3e8da3@news.astraweb.com> Message-ID: <7e9ab1b7-75f8-4374-890d-2d9414acf254@c65g2000hsa.googlegroups.com> On Jul 28, 9:07?am, Steven D'Aprano wrote: > On Sun, 27 Jul 2008 21:42:37 -0700, Russ P. wrote: > >> +1 QOTW > > > Do you realize what an insult that is to everyone else who has posted > > here in the past week? > > Actually I don't. I hadn't realised that when a person believes that > somebody has made an especially clever, witty, insightful or fun remark, > that's actually a put-down of all the other people whose remarks weren't > quite as clever, witty, insightful or fun. > > But now that I've had this pointed out to me, why, I see insults > everywhere! Tonight, my wife said to me that she liked my new shirt, so I > replied "What's the matter, you think my trousers are ugly?" > > -- > Steven No insult was intended. The writer stated that where Java minimizes bad, Python maximizes good. This is a non-trivial truth, and a non- trivial observation. Also, clever. I agreed and said so, and compliments go a long way. Do you? > everywhere! Tonight, my wife said to me that she liked my new shirt, so I > replied "What's the matter, you think my trousers are ugly?" Arf, arf. -- For my special power, I want immunity to insults. From imxmwu at gmail.com Thu Jul 31 09:44:33 2008 From: imxmwu at gmail.com (shrimpy) Date: Thu, 31 Jul 2008 23:44:33 +1000 Subject: problem when reading file Message-ID: <8e50c4e80807310644u3c456ab4qce06c6997707db8d@mail.gmail.com> hi every one, i am new to python, and coz i want to write a handy command for my linux machine, to find a word in all the files which are under the current folder. the code is half done, but when i run it, it complain, and i don`t know why??? can anyone help me have a look at it? here is the message it complain ======================================= file is : qt_plugins_3.3rc Traceback (most recent call last): File "./python_script/svn_grep.py", line 34, in searPatten(file,'are','no') File "./python_script/svn_grep.py", line 8, in searPatten openFile = open(file, 'r') IOError: [Errno 2] No such file or directory: 'qt_plugins_3.3rc' here are the code i wrote ---------------------------------------------------------------code begin #!/usr/bin/python import os import string def searPatten(file, patten, isCaseSensitive): openFile = open(file, 'r') lines = openFile.readlines() lineNum = 1 for text in lines : words = text.split() existed = 0 for word in words : if isCaseSensitive == 'yes' : if word.lower() == patten.lower(): existed = 1 break else: if word == patten : existed = 1 break if existed == 1: print "line : " + str(lineNum) + " " + text lineNum += 1 openFile.close() for root, dirs, files in os.walk(os.getcwd()): for file in files: print "=======================================" print "file is : " + file + "\n" searPatten(file,'are','no') ---------------------------------------------------------------code end From castironpi at gmail.com Tue Jul 29 00:00:24 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 28 Jul 2008 21:00:24 -0700 (PDT) Subject: block/lambda References: <0406eb4f-8dec-4ce2-b506-8e597de2958d@56g2000hsm.googlegroups.com> <01754831-dde2-4c15-805c-236f841e3e2b@d77g2000hsb.googlegroups.com> Message-ID: On Jul 28, 3:12?pm, iu2 wrote: > On Jul 28, 10:06?pm, iu2 wrote: > > > > > Hi, > > > Playing with imitating lambdas and ruby blocks in Python, I came up > > with a very simple construct, for example: > > > import compiler > > > def dotimes(i, code): > > ? ? for i in range(i): > > ? ? ? ? exec code > > > dotimes(5, ''' > > for j in range(i): > > ? ? ? ? print j, > > print > > ''', '', 'exec') > > > This will print > > 0 > > 0 1 > > 0 1 2 > > 0 1 2 3 > > > A more efficient code would probably be > > > dotimes(5, compiler.compile(''' > > for j in range(i): > > ? ? ? ? print j, > > print > > ''', '', 'exec')) > > > which is, to my understanding, exactly what a ruby block is. > > > But the actual "discovery" here, is that the triple quote - ''' - > > makes a syntax for block passing. Having a code editor that keeps > > colorizing what's inside the quotes like a normal code would make it > > easier to maintain. > > > Is it possible to grant Python another syntactic mark, similar to > > triple quotes, that will actually make the enclosed code a compiled > > code, or an anonymous function? > > > I know that anonymous functions (long lambdas...) are not on the road > > map. But I ask this because, as I understand it, the triple quote > > actually presents a syntax for it. > > Isn't it actually a matter of taking the triple-quotes a little bit > > further? > > > Thanks > > There is a mistake in my first example, the code is, of course: > dotimes(5, ''' > for j in range(i): > ? ? ? ? print j, > print > ''') > > Sorry... You could do code= '''# for _ in range( 2 ): pass ''' and signify the code block to your editor with the leading blank comment. From yuwenwu001 at gmail.com Sat Jul 19 10:17:42 2008 From: yuwenwu001 at gmail.com (kjldf) Date: Sat, 19 Jul 2008 07:17:42 -0700 (PDT) Subject: cheap shox NZ shoes PayPal Message-ID: cheap shox NZ shoes PayPal welcome to shopping on www.cheapest-paypal.cn 1.5% paypal handling charge supports the online payment! 2.Use your intergla replacement more good gift! 3.notes by email and website of deliver each package at first time. Have a good day! Sincerely yours, CHINASILKROAD EXPORTS CO., LTD From tcfg at sina.com Thu Jul 24 07:17:03 2008 From: tcfg at sina.com (fang) Date: Thu, 24 Jul 2008 04:17:03 -0700 (PDT) Subject: how to cut and paste in the windows of python(command line) Message-ID: <9500663c-0985-4dfd-8d0a-ae25411f00e5@v39g2000pro.googlegroups.com> Dear all: The mouse cannot be responded in the windows of python(command line) and cut and paste cannot be done. ctrl c and ctrl v do not work. But they do work in IDLE. please teach me about the python(command line). From bj_666 at gmx.net Wed Jul 16 00:32:08 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Jul 2008 04:32:08 GMT Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> <7348c0dc-028d-4f89-9d63-b1247fb6807c@m44g2000hsc.googlegroups.com> Message-ID: <6e5bu8F5eajaU1@mid.uni-berlin.de> On Tue, 15 Jul 2008 19:54:30 -0700, Yosifov Pavel wrote: > Kay, can you show example of such generator? ReIter, for example, work > with usual generators. > > But for "big" iterator, I think is no any good solutions. IMHO we can > discern 2 types of iterators: re-startable (based on internal Python > objects) and not re-startable (with an external state, side- > effects)... Has nothing to do with internal vs. external. Examples: ``itertools.count(1)``, ``itertools.cycle(iterable)``, or def fib(): a, b = 0, 1 while True: yield a a, b = b, a + b Ciao, Marc 'BlackJack' Rintsch From kyosohma at gmail.com Wed Jul 16 13:33:49 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 16 Jul 2008 10:33:49 -0700 (PDT) Subject: how can i save my command prompt screen? References: Message-ID: <0e67407b-c595-4b02-9d25-21c9ee7ea9ed@f36g2000hsa.googlegroups.com> On Jul 16, 12:28?pm, norseman wrote: > Ty hensons wrote: > > ?> how can i save my command prompt screen? > > ============================================== > > That by itself leaves lots of questions. ?Taken literally to be the > "box" then: > > In Microsoft use the "Print Screen" followed by mspaint and Edit/paste > ? ?(Or SHIFT-PrintScreen if whole screen showed up, I forget which it is. > ? ? ?One does just the box that is hot while the other gets all) > In Windows you can right-click, choose "Mark" and then select the text. Hit to copy it to the clipboard. Then you can paste it into any text editor you like. > Steve > norse... at hughes.net Mike From bedouglas at earthlink.net Mon Jul 21 16:19:21 2008 From: bedouglas at earthlink.net (bruce) Date: Mon, 21 Jul 2008 13:19:21 -0700 Subject: Trying to solve a python/mechanize "error 500" http error Message-ID: <24db01c8eb6f$103783b0$0301a8c0@tmesa.com> i'm getting the following error: mechanize._response.httperror_seek_wrapper: HTTP Error 500: i'm running python 5.1 and mechanize 0.1.7b I have no idea as to what I have to change/modify/include to handle this issue. The link that I'm testing is at the bottom of the page. When I insert the link into the browser, I actually get an err page.. so, I suspect that there is a handler that I should be able to modify/use to handle this situation... Thoughts/Comments will be greatly appreciated... Thanks the output is: www = www.1800ink.com url2= http://www.quantcast.com/www.1800ink.com/traffic Traceback (most recent call last): File "./reseller_scrape_child.py", line 288, in q1 = shopfuncs.quant(rhref) File "/adkiller/shopfuncs.py", line 56, in quant br.open(url2) File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 203, in open File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 254, in _mech_open mechanize._response.httperror_seek_wrapper: HTTP Error 500: [root at toshiba adkiller]# ./reseller_scrape_child.py my code segment looks like: ==================================== from mechanize import Browser import mechanize br = Browser() user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values1 = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } #br.set_cookiejar(cj) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.addheaders = [('User-Agent', 'Firefox')] url2 ="http://www.quantcast.com/xxxx/traffic" #gets the page (url) from the quantcast app url2=url2.replace("xxxx",url) print "url2=",url2 br.open(url2) ======================================= this works ok for most of the sites.. but something weird is happening with the actual page: http://www.quantcast.com/www.1800ink.com/traffic thanks... From castironpi at gmail.com Fri Jul 11 15:27:32 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 11 Jul 2008 12:27:32 -0700 (PDT) Subject: Using the Random Module. References: Message-ID: On Jul 11, 1:29?pm, WDC wrote: > On Jul 11, 2:15?pm, Michiel Overtoom wrote: > > > You wrote... > > >Is there a better way to do that besides doing this: > > > >>>>random.randint(00000000000000000, 99999999999999999) > > >09657398671238769 > > > Maybe this? > > > ? ? ? ? random.randint(0, 9e16) > > > -- > > "The ability of the OSS process to collect and harness > > the collective IQ of thousands of individuals across > > the Internet is simply amazing." - Vinod Vallopillilhttp://www.catb.org/~esr/halloween/halloween4.html > > That would work yes, but is there a random() function that would do > that without the attributes? Not trying to be lazy, I just want to > know if there is a built in way. > > Thanks Michiel. You want a random integer. Is there a range you want it in? Past a certain point, you'll exceed the granularity of the random number generator, and some values in the range will never be generated. From eckhardt at satorlaser.com Thu Jul 31 07:30:21 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 31 Jul 2008 13:30:21 +0200 Subject: How smart is the Python interpreter? References: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> Message-ID: ssecorp wrote: > def str_sort(string): > s = "" > for a in sorted(string): > s+=a > return s > > > if i instead do: > > def str_sort(string): > s = "" > so = sorted(string) > for a in so: > s+=a > return s > > will that be faster or the interpreter can figure out that it only has > to do sorted(string) once? Actually, by replacing sorted() with a function that outputs when it is called you could have seen that this is only called once in both cases. It must not be called more than once in fact, consider e.g. the case that it introduces side effects (like e.g. reading a file). Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From google at mrabarnett.plus.com Wed Jul 16 17:54:33 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 16 Jul 2008 14:54:33 -0700 (PDT) Subject: Setting Message Importance using SMTP Mail References: <33672217-148c-4c6a-96be-25ef88ba773f@k37g2000hsf.googlegroups.com> Message-ID: On Jul 16, 4:42?pm, Whyatt wrote: > Hi all, > > I'm trying to create a message using SMTP Mail through Python with a > message Importance of either 0 (Low) or 2 (High). > > If I do outer.Add_header('Importance', '0') it is ignored. > > If I do uter.Replace_header('Importance', '0') I get the error below. > Traceback (most recent call last): > ? File "#####", line 840, in > ? ? outer.Replace_header('Importance', '0') > AttributeError: MIMEMultipart instance has no attribute > 'Replace_header' > > Can anyone provide any clues on the correct way of updating the Msg > Importance header? > Are you sure that shouldn't be outer.add_header(...) and outer.replace_header()? From bignose+hates-spam at benfinney.id.au Wed Jul 30 09:18:27 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 30 Jul 2008 23:18:27 +1000 Subject: Standard module for parsing emails? References: Message-ID: <87provbjdo.fsf@benfinney.id.au> Phillip B Oldham writes: > Is there a standard library for parsing emails that can cope with > the different way email clients quote? "Cope with" in what sense? i.e., what would the behaviour of such a library be? What would it do? Note also that it's not merely the mail client that does the quoting; frequently the user composing the message will have a heavy hand in how the quoted material appears. -- \ ?Time flies like an arrow. Fruit flies like a banana.? ?Groucho | `\ Marx | _o__) | Ben Finney From ewertman at gmail.com Sat Jul 26 16:10:58 2008 From: ewertman at gmail.com (Eric Wertman) Date: Sat, 26 Jul 2008 16:10:58 -0400 Subject: os.walk question In-Reply-To: References: Message-ID: <92da89760807261310r39df1109j4cf7133d8144508b@mail.gmail.com> I do this, mabye a no-no? import os for root,dirs,files in os.walk(dir) : break From kyosohma at gmail.com Fri Jul 25 09:46:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 25 Jul 2008 06:46:25 -0700 (PDT) Subject: Calling external program from within python References: Message-ID: On Jul 25, 7:56?am, Emmanouil Angelakis wrote: > Hi, > > I am tryiong to do something obviously trivial such as: > I have a c program called "tsys2list" that when it is ran it asks the user to give the value of "tcal" which is a variable. I want to call the ?"tsys2list" from within a pyrthon script lets call it "gamma.py" >>>but<<< I want to pass the value of "tcal" to th eprogram automatically and not by interacting with the keyboard. > > How do I do that? > > thanks i advance! > manolis There are probably many ways to do this. I would recommend checking out the subprocess module and see if it does what you want. Or you could learn a little Tkinter or wxPython and use that to get the user's variable. Or you could even do it via the command line using the "raw_input" command. http://docs.python.org/lib/module-subprocess.html Mike From nagle at animats.com Wed Jul 30 14:30:11 2008 From: nagle at animats.com (John Nagle) Date: Wed, 30 Jul 2008 11:30:11 -0700 Subject: Native Code vs. Python code for modules In-Reply-To: References: Message-ID: <4890aeb6$0$17192$742ec2ed@news.sonic.net> koblas wrote: > Ruby has been getting pummeled for the last year or more on the > performance subject. They've been working hard at improving it. From > my arm chair perspective Python is sitting on it's laurels and not > taking this as seriously as it probably should. PyPy was supposed to help, but that project has been dragging on for half a decade now. Personally, I think the Shed Skin approach is more promising. PyPy has too many different goals, and tends to generate lots of auxiliary tools, blogs, videos, and "sprints", but not a usable PyPy compiler. We'll have to see if PyPy 1.1 works. John Nagle From socyl at 987jk.com.invalid Tue Jul 29 16:40:36 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 20:40:36 +0000 (UTC) Subject: static variables in Python? Message-ID: Yet another noob question... Is there a way to mimic C's static variables in Python? Or something like it? The idea is to equip a given function with a set of constants that belong only to it, so as not to clutter the global namespace with variables that are not needed elsewhere. For example, in Perl one can define a function foo like this *foo = do { my $x = expensive_call(); sub { return do_stuff_with( $x, @_ ); } }; In this case, foo is defined by assigning to it a closure that has an associated variable, $x, in its scope. Is there an equivalent in Python? Thanks! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From paul.hankin at gmail.com Sat Jul 12 02:28:35 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Fri, 11 Jul 2008 23:28:35 -0700 (PDT) Subject: python scalability References: Message-ID: On Jul 10, 5:32?am, Tim Mitchell wrote: > I work on a desktop application that has been developed using python and > GTK (seewww.leapfrog3d.com). ?We have around 150k lines of python code > (and 200k+ lines of C). ?We also have a new project manager with a C# > background who has deep concerns about the scalability of python as our > code base continues to grow and we are looking at introducing more > products. ?I am looking for examples of other people like us (who write > desktop apps in python) with code bases of a similar size who I can > point to (and even better talk to) to help convince him that python is > scalable to 300+ lines of code and beyond. ?I have looked at the python > success stories page and haven't come up with anyone quite like us. > One of my project managers questions is: "Are we the only company in the > world with this kind and size of project?" > I want to say no, but am having trouble convincing myself, let alone him. > > If you are involved in this kind of thing please get in touch with me. Perhaps your manager is more concerned about python because he's less familiar with it, rather than because of scalability problems? Perhaps using python is actually a competitive advantage for your company? Have you seen this? http://www.paulgraham.com/pypar.html -- Paul Hankin From dullrich at sprynet.com Tue Jul 8 11:58:44 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 08 Jul 2008 10:58:44 -0500 Subject: "in"consistency? References: Message-ID: In article , Terry Reedy wrote: > David C. Ullrich wrote: > > >>>> 'ab' in 'abc' > > True > > 'a' in 'abc' works according to the standard meaning of o in collection. > > 'ab' in 'abc' could not work by that standard meaning because strings, > as virtual sequences, only contain characters (length 1 strings). Among > built-in collections, this limitation is unique to strings (and bytes, > in 3.0). So in 2.3, 'in' was given a useful extension of meaning that > is also unique to strings (and bytes). Ah, I didn't realize that this was new. Thanks - at least this means I was right about the way it worked formerly. > >>>> [1,2] in [1,2,3] > > False > > [1,2] can be an member of tuples, lists, dicts and other general > collections. [1,2] in collection therefore has that meaning, that it is > a single element of collection. Extending the meaning would conflict > with this basic meaning. Well of course. > > Is there a reason for the inconsistency? I would > > have thought "in" would check for elements of a > > sequence, regardless of what sort of sequence it was... > > It is not an inconsistency but an extension corresponding to the > limitation of what an string element can be. It's an inconsistency. That doesn't mean it's a bad thing or that I want my money back. It may well be a reasonable inconsistency - strings _can_ work that way while it's clear lists had better not. But it's an inconsistency. > Terry J. Reedy -- David C. Ullrich From wuwei23 at gmail.com Mon Jul 28 00:27:36 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 27 Jul 2008 21:27:36 -0700 (PDT) Subject: I love "shelf" BUT References: <1c2d28bb-06e8-4f02-a528-9d86f84366dd@n33g2000pri.googlegroups.com> Message-ID: <3f22dbca-43c8-497f-af77-c28d3df9ba1b@t1g2000pra.googlegroups.com> On Jul 28, 1:44?pm, Sera Jackson wrote: > Lot of thanks again, that's what I wanted to find, arguments against > it, I was aware I wan not speaking of sth new. Guido seems to keep hinting that someone should write a PEP, just so it can be officially denied and then there'll be a place to point to when the question arises again (as it inevitably will...) So if you wanna take a shot... :) From carsten.haese at gmail.com Tue Jul 15 13:32:40 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Tue, 15 Jul 2008 13:32:40 -0400 Subject: MySQL Insert In-Reply-To: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> References: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> Message-ID: maestroQC wrote: > cursor.execute("INSERT INTO es_accounts (dateCreated, > accountNumber, description, openingBalance) VALUES (%s, %s, %s > , %d)", (date, accountNumber, description, dec)) > File "c:\python25\lib\site-packages\MySQLdb\cursors.py", line 151, > in execute > query = query % db.literal(args) > TypeError: int argument required The placeholder for query parameters in MySQLdb is always %s, regardless of the data type the actual value might have. HTH, -- Carsten Haese http://informixdb.sourceforge.net From bdesth.quelquechose at free.quelquepart.fr Sat Jul 26 08:05:39 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 26 Jul 2008 14:05:39 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <488af527$0$14761$426a74cc@news.free.fr> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> <488af527$0$14761$426a74cc@news.free.fr> Message-ID: <488b1322$0$1294$426a74cc@news.free.fr> Bruno Desthuilliers a ?crit : (snip) > There are quite a few cases in Python where there are both a specific > magic method *and* a default behaviour based on another magic method if > the specific one is not implemented. Just out of my mind: s/out of my mind/Off the top of my head/ Pardon my french, and thanks to Tim Golden for the correction !-) From timothywayne.cook at gmail.com Sun Jul 13 23:28:06 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Mon, 14 Jul 2008 00:28:06 -0300 Subject: Malaysia python user group In-Reply-To: <487AC086.3010600@internetnowasp.net> References: <487AC086.3010600@internetnowasp.net> Message-ID: <1216006086.3028.25.camel@localhost.localdomain> Marcus, You should probably contact the Malaysian Public Sector Open Source Competency Centre (OSCC) in Cyberjaya. http://www.oscc.org.my HTH, Tim On Mon, 2008-07-14 at 10:57 +0800, Marcus.CM wrote: > Hi, > > I am thinking of promoting Python for the local developers here in > Malaysia, via Universities , seminars etc . > Is there already a user group here in Malaysia? Any pointers would help. > > Marcus. > > -- > http://mail.python.org/mailman/listinfo/python-list -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. Home page: https://launchpad.net/oship/ Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From max at alcyone.com Tue Jul 29 16:08:26 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 13:08:26 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> Message-ID: Carl Banks wrote: > On Jul 29, 1:30 pm, Carl Banks wrote: >> On Jul 29, 5:15 am, Heiko Wundram wrote: >> >>> I can't dig up a simple example from code I wrote quickly, but because of the >>> fact that explicit comparisons always hamper polymorphism >> I'm not going to take your word for it. Do you have code that >> demonstrates how "if x" improves polymorphism relative to simple >> explicit tests? > > And, in case it wasn't obvious, the way to demonstrate that "if x" > improves polymorphism relative to simple explicit tests would be > posting an example where "if x" works but a simple explicit test > doesn't. So don't accuse me of changing the question on you: it's the > same question. It's pretty elementary, and people thought just describing the issue of polymorphism and duck-typing was sufficient to explain it. Since it apparently isn't: Let's say you come up with some kind of custom sequence class. You want to act like any native sequence type (list, tuple, array, string, etc.) in all reasonable ways (length testing, iteration, indexing, etc.) so that it can be used in place of these things in code that doesn't require explicit types. You know, standard polymorphism and duck-typing. So you want a test for whether your custom sequence isn't empty. To create an "simple, explicit test" would be defined an `isntEmpty` method that you can call, like so: if myObject.isntEmpty(): # then do something However, this wouldn't be polymorphic since now someone would have to call a "simple, explicit test" that doesn't exist on all the other sequence-like objects. Therefore, you've broken polymorphism. The solution is to override the `__nonzero__` method so that you can use Boolean testing, just like all the other sequence-like objects: if myObject: # then do the same thing Now people who use your custom sequence type don't have to write special code, and code written to deal with sequences using duck typing (which is typically nearly all Python code) don't have to know anything special about your custom sequence class. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Everything's gonna be all right / Everything's gonna be okay -- Sweetbox From ethan at stoneleaf.us Wed Jul 30 05:17:56 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 30 Jul 2008 01:17:56 -0800 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> Message-ID: <489031C4.1030409@stoneleaf.us> Russ P. wrote: > Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > __nonzero__ work in Python. It's very basic stuff. You can quit > patronizing me (and Carl too, I'm sure). > > The point that you seem to be missing, or refuse to acknowledge for > some reason, is that "if x" can be mistakenly applied to any object > when the programmer thinks that x is a list -- and the programmer will > receive no feedback on the error. You know... or maybe you don't, since you did just say what you just said... that is such a ridiculous point it only barely qualifies as deserving comment. Rather than be really rude, I'll just say: test it's type() if the function is that specific, or your code that brittle. Python is not there to catch your logic mistakes, that's up to you. > I have made errors like that, and I could have saved some time had I > used an "empty" method that only applies to a list or other sequence. > > Is that an important issue? I don't know. I'm not claiming it is. But > you cannot just sweep it away as nothing. I don't sweep it away as nothing -- I sweep it away as stupid. The programmer is responsible for his (or her) program. An analogy would be a driver and a car -- if the driver cannot handle the power and speed of a fancy car (python :), then the driver should get a different car better matched to his abilities. It's not up to the car to say "oh, the speed limit is 50 here, I better apply the brakes for the driver." ~Ethan~ From motoom at xs4all.nl Tue Jul 15 19:47:19 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Wed, 16 Jul 2008 01:47:19 +0200 Subject: Python for Kids Message-ID: <2.2.32.20080715234719.01194a70@pop.xs4all.nl> Sean wrote... > Pretty cool!! Our base will be *much* bigger in about twenty years. > I remember doing Basic on my dads Apple IIe. Gee, I wish Python existed back then. I had to endure Commore Basic on the PET2001. The biggest challenge was how to fit the program in 8K... It didn't take me long to switch to 6502 machine language to get more out of it. And I was a really happy kid when the S100 systems with FORTRAN and simple C compilers came along ;-) I wish I still had my original K&R "Programming C" and Kernighan&Plaughers "Software Tools" using RATFOR, but they have been lost in the mist of years. Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From matt at tplus1.com Sun Jul 13 20:21:04 2008 From: matt at tplus1.com (Matthew Wilson) Date: Mon, 14 Jul 2008 00:21:04 GMT Subject: How to package a logging.config file? Message-ID: I'm working on a package that uses the standard library logging module along with a .cfg file. In my code, I use logging.config.fileConfig('/home/matt/mypackage/matt.cfg') to load in the logging config file. However, it seems really obvious to me that this won't work when I share this package with others. I can't figure out what path to use when I load my .cfg file. Any ideas? Matt From kraus at hagen-partner.de Fri Jul 18 08:41:18 2008 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Fri, 18 Jul 2008 14:41:18 +0200 Subject: substitution of list elements In-Reply-To: <247ab26d-ba98-42cc-bf6e-738b4b32a70c@q28g2000prh.googlegroups.com> References: <247ab26d-ba98-42cc-bf6e-738b4b32a70c@q28g2000prh.googlegroups.com> Message-ID: Am 18.07.2008 14:33, antar2 schrieb: > I want to replace each first element in list 5 that is equal to the > first element of the list of lists4 by the fourth element. I wrote > following code that does not work: > > list4 = [['1', 'a', 'b', 'c'], ['2', 'd', 't', 'e'], ['8', 'g', 'q', > 'f']] > list5 = ['1', '2', '3'] > > for j in list4: > for k in list5: for i,k in enumerate(list5): > if j[0] == k: > k = j[3] list5[i] = j[3] > print list5 > Wanted result: ['c', 'e', '3'] > > thanks! You didn't replace the list element itself. HTH, Wolfram From s0suk3 at gmail.com Fri Jul 25 05:27:34 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Fri, 25 Jul 2008 02:27:34 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> <5d3729f0-6e5d-4e3f-b4ed-e25f8ebc655f@q5g2000prf.googlegroups.com> Message-ID: <43d32584-e762-4578-82d9-0d4395bb4138@k36g2000pri.googlegroups.com> On Jul 25, 3:38 am, cokofreedom at gmail.com wrote: > > By that logic, C++ is not OO. By that logic, Ruby is not OO. By that > > logic, I know of only one OO language: Java :) > > > The fact that a language doesn't force you to do object-oriented > > programming doesn't mean that it's not object-oriented. In other > > words, your words are nonsense. > > No, what it means is that it might support OO but doesn't have to, it > isn't the only way to code. > "Support OO but it doesn't have to"? That sounds like saying that in some Python implementations you'll be able to use OO, but that you just might bump into a Python distribution where you would type class MClass: pass at the interpreter and it would give you an syntax error. Is that what you mean? > Supporting and Being OO are very different. I guess at this point it's rather pointless to discuss this because of the different and deep level of interpretation that we might have on the words "support" and "be." IMO, the obvious thing to say is that a language that *supports* OO can also be said to *be* OO. However, it would seem just ridiculous to me to say the same thing about a language like, e.g., Perl, where OO is so pathetic. But maybe this is just a game of words... I consider Python to *be* OO, anyway. Sebastian From jadamwilson2 at gmail.com Mon Jul 7 16:35:05 2008 From: jadamwilson2 at gmail.com (jadamwilson2 at gmail.com) Date: Mon, 7 Jul 2008 13:35:05 -0700 (PDT) Subject: sage vs enthought for sci computing Message-ID: <677e7819-e09e-43d3-8368-5864f91002be@34g2000hsh.googlegroups.com> Hello, I have recently become interested in using python for scientific computing, and came across both sage and enthought. I am curious if anyone can tell me what the differences are between the two, since there seems to be a lot of overlap (from what I have seen). If my goal is to replace matlab (we do signal processing and stats on physiological data, with a lot of visualization), would sage or enthought get me going quicker? I realize that this is a pretty vague question, and I can probably accomplish the same with either, but what would lead me to choose one over the other? Thanks! From gherron at islandtraining.com Thu Jul 24 16:27:52 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 24 Jul 2008 13:27:52 -0700 Subject: Reading a file In-Reply-To: <73045cca0807241306h370166ebwdd1b12227cef43c2@mail.gmail.com> References: <73045cca0807241306h370166ebwdd1b12227cef43c2@mail.gmail.com> Message-ID: <4888E5C8.1050502@islandtraining.com> aditya shukla wrote: > I have a text file whose contents are like this:- > > jd|fj|dnv|jd|0.33|c:\\windows\\win32 > shcbsbs|nscsjsj|0.93|hsbcjsnc > > I am trying to read the file like this:- > > >>> x = open("c:\\a.txt","r") Better to use "rb" (for binary read) rather than "r" mode. > >>> x.read() Now, tell us what you *really* did. Not that -- that would read the contents of the file, put throw the returned result away. You must have done something like c = x.read() > > the result that i get is ike this:- > 'jd|fj|dnv|jd|0.33|c:\\\\windows\\\\win32\nshcbsbs|nscsjsj|0.93|hsbcjsnc\n' > > My doubt is how can i read the file as it is? You *have* read the file as it is. Examine each character, and you'll see that the string is exactly as you expect. However, your output to the screen is escaping some character with backslashes. But that's just because of the method you used to print to the screen. What method *did* you use to print? If you just typed the variable into which you had read the contents, then you get the equivalent of print repr(c) which explains the escapes. Try print c and that won't happen. Gary Herron > > ie my output should be > > d|fj|dnv|jd|0.33|c:\\windows\\win32 > shcbsbs|nscsjsj|0.93|hsbcjsnc > > > Thanks in advance > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From jeffober at gmail.com Mon Jul 7 08:09:34 2008 From: jeffober at gmail.com (Jeff) Date: Mon, 7 Jul 2008 05:09:34 -0700 (PDT) Subject: Confused yet again: Very Newbie Question References: Message-ID: <13be8c54-3fa9-4a37-a0e6-45bb019bff7e@a1g2000hsb.googlegroups.com> When you call c3.createJoe(c1.fred), you are passing a copy of the value stored in c1.fred to your function. Python passes function parameters by value. The function will not destructively modify its arguments; you must expliticly state your intention to modify an object: class one(): fred = 'fred' class three(): def createJoe(self, myName): return "Joe" def main(): c1 = one() c3 = three() c1.fred = c3.createJoe() # Modify c1's attribute, fred, with the return value from c3.createJoe From barun.saha04 at gmail.com Mon Jul 21 07:42:35 2008 From: barun.saha04 at gmail.com (barun.saha04 at gmail.com) Date: Mon, 21 Jul 2008 04:42:35 -0700 (PDT) Subject: Problem with Python Server Pages (PSP) Message-ID: <9766b993-03e6-4b75-92a2-06244c41e51c@a1g2000hsb.googlegroups.com> Hi, I am facing a very basic problem with PSP. I have installed mod_python (in fedora Core 1), added the lines required for loading Python modules and handling PSP pages. I have created a hello.psp page. But when I try to view this hello.psp page, all Python code are getting displayed. The said page is stored at /var/www/html/psp/hello.psp. I guess this is some configuration problem with Apache, but not able to figure out the exact problem. I have tried putting those configuration lines for psp in both httpd.conf and python.conf files. But still it is not working. The Python module (mod_python) is getting loaded. Because when I telnet to my server, I can find that in the headers. These are the versions of the softwares: Apache: 2.0.47 Python: 2.2.3 mod_python: 3.0.3 Thnaks for all your suggestions. From bastard at example.org Tue Jul 15 07:57:41 2008 From: bastard at example.org (Anonymous Bastard) Date: Tue, 15 Jul 2008 14:57:41 +0300 Subject: Suggestion: Python global scope Message-ID: I've been tossing this idea in my mind for some time now: In Python, declaring a variable using the global statement automatically makes it available in all subsequent scopes. But to me, it makes more sense to use the global statement to 'import' a variable from the global scope into the current scope. For instance: [code] global X X = 1 def P(): X = 2 print X global X print X print X P() print X [code] Currently, this will print 1, 2, 2 and 2. But if global would be limited to current scope, it would print 1, 2, 1, 1. 'X = 2' would work on the local version of X, 'global X' will 'import' the global X into the local scope, so any actions on X would reference the global X, rather than previous X. From paul at boddie.org.uk Thu Jul 31 06:41:17 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 31 Jul 2008 03:41:17 -0700 (PDT) Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: <2a703a46-75bc-4228-95d1-05a4e6030b40@f63g2000hsf.googlegroups.com> <26c2fe8e-d464-44f0-8e57-3b8e82248691@x35g2000hsb.googlegroups.com> Message-ID: <69428617-ffc3-4f30-a267-102b68385341@34g2000hsf.googlegroups.com> On 30 Jul, 20:15, Peter Otten <__pete... at web.de> wrote: > Paul Boddie wrote: > > Who wants to be first to submit a patch? ;-) > > And where? The sourceforge page says > > "PyXML is no longer maintained." The minidom code is in the standard library: http://svn.python.org/view/python/trunk/Lib/xml/dom/ Paul From you2000too at gmail.com Mon Jul 21 23:31:59 2008 From: you2000too at gmail.com (youtoo) Date: Mon, 21 Jul 2008 20:31:59 -0700 (PDT) Subject: Time Complexity of String Operations Message-ID: It has been extensively discussed the time complexity (quadratic) of string concatenation (due to string's immutability). But what is: == the time complexity of string indexing? Is it constant? == the time complexity of string slicing? Is it O(K) with K the slice's length? How are strings stored in Python? As arrays? As linked lists? Thanks a lot! yt. From maric at aristote.info Thu Jul 31 11:08:08 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 31 Jul 2008 17:08:08 +0200 Subject: Difference between type and class In-Reply-To: <87tze6862j.fsf@nokile.rath.org> References: <87myjy2vc6.fsf@nokile.rath.org> <87tze6862j.fsf@nokile.rath.org> Message-ID: <200807311708.09241.maric@aristote.info> Le Thursday 31 July 2008 16:46:28 Nikolaus Rath, vous avez ?crit?: > Maric Michaud writes: > >> > Can someone explain to me the difference between a type and a class? > >> > >> If your confusion is of a more general nature I suggest reading the > >> introduction of `Design Patterns' (ISBN-10: 0201633612), under > >> `Specifying Object Interfaces'. > >> > >> In short: A type denotes a certain interface, i.e. a set of signatures, > >> whereas a class tells us how an object is implemented (like a > >> blueprint). A class can have many types if it implements all their > >> interfaces, and different classes can have the same type if they share a > >> common interface. The following example should clarify matters: > > > > Of course, this is what a type means in certain literature about OO > > (java-ish), but this absolutely not what type means in Python. Types > > are a family of object with a certain status, and they're type is > > "type", conventionnaly named a metatype in standard OO. > > [...] > > Hmm. Now you have said a lot about Python objects and their type, but > you still haven't said what a type actually is (in Python) and in what > way it is different from a class. Or did I miss something? This paragraph ? """ - types, or classes, are all instance of type 'type' (or a subclass of it), they can be instantiated and they produce objects (ordinary object in general) with theirslef as a type. """ Maybe it's still unclear that "types" and "classes" *are* synonyms in Python. -- _____________ Maric Michaud From frankrentef at yahoo.com Thu Jul 31 11:00:22 2008 From: frankrentef at yahoo.com (frankrentef) Date: Thu, 31 Jul 2008 08:00:22 -0700 (PDT) Subject: HELP - Attribute Error, no matter what I do on PAMIE... Message-ID: <38ed1b14-fb96-4891-9188-c62337aeef89@f36g2000hsa.googlegroups.com> Greetings all. I'm new to PAMIE and I've watched / followed to PAMIE videos on Show me Do. I've tried to duplicate the "scriptWrite" function in an attempt to automate the forms process... without success. Can someone PLEASE Assist!? I'm using the following code.... from cPAMIE import PAMIE #Imports - used to setup / control finding files import time import os import sys import cReport #import elementtree.ElementTree as ET #Create New Pamie Object ie=PAMIE() ie=Visible =1 t=time ie=PAMIE () ie.navigate ('http://bir1edptest2/iswebcommander/fi/default.aspx') ie.scriptWrite() And getting the following error.... Atribute Error:.nameProp File "C:\PYCODE\scriptWrite TEST.py", line 19, in ? ie.scriptWrite() File "C:\Python24\Lib\site-packages\cPAMIE.py", line 1837, in scriptWrite nameProp = getattr(x,"nameProp") File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 496, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) From hnsri49 at gmail.com Mon Jul 7 05:14:46 2008 From: hnsri49 at gmail.com (cna) Date: Mon, 7 Jul 2008 02:14:46 -0700 (PDT) Subject: python beginner Message-ID: <1cd8ffae-62a7-4cfb-b3ab-61c7004841c9@8g2000hse.googlegroups.com> Hi all and one, how may i learn python. is there any other website except python.org From jurgenex at hotmail.com Tue Jul 22 06:38:07 2008 From: jurgenex at hotmail.com (Jürgen Exner) Date: Tue, 22 Jul 2008 10:38:07 GMT Subject: proliferation of computer languages References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> <40429b65-23a0-489b-b5fd-ae6b8eee607d@t54g2000hsg.googlegroups.com> Message-ID: Chris Rathman wrote: >I can't say that I see any particular point to the essay. You must be new here. There never is any particular point to Xah Lee's rantings except to cross-post borderline topics to borderline relevant NGs and then lay back and enjoy the ensuing slaughter. PLEASE DO NOT FEED THE TROLL >On Jul 18, 12:17 pm, "xah... at gmail.com" wrote: jue From deanfamily11 at verizon.net Tue Jul 1 18:20:48 2008 From: deanfamily11 at verizon.net (Brandon) Date: Tue, 01 Jul 2008 22:20:48 GMT Subject: Required items in a form Message-ID: <45yak.331$Ae3.313@trnddc05> What I'm trying to do is essentially force a user to fill in required items in a form, which will be saved to a database. How can I get it so that once the user clicks "OK" on the dialog box, it transfers control back to the form, and not save the empty fields into the database? From stef.mientki at gmail.com Tue Jul 8 18:43:03 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 09 Jul 2008 00:43:03 +0200 Subject: find all ODBC databases ? Message-ID: <4873ED77.7080507@gmail.com> hello, I'm working on a general database manager, which will be open source and should preferable work under all OS. Now in windows I can find the ODBC databases by reading some reg key. I also know that ODBC is supported under Linux (I don't know anything of Linux), but how can I get all ODBC databases in a platform independant way ? thanks, Stef Mientki From emen999 at gmail.com Wed Jul 23 11:37:38 2008 From: emen999 at gmail.com (code_berzerker) Date: Wed, 23 Jul 2008 08:37:38 -0700 (PDT) Subject: lxml, comparing nodes Message-ID: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> I'd like to know if there is any built in mechanism in lxml that lets you check equality of two nodes from separate documents. I'd like it to ignore attribute order and so on. It would be even better if there was built in method for checking equality of whole documents (ignoring document order). Please let me know if you know of such method or existing scipt. I dont like reinventing the wheel :) From diordna at gmail.com Tue Jul 15 09:42:39 2008 From: diordna at gmail.com (Stephen Johnson) Date: Tue, 15 Jul 2008 09:42:39 -0400 Subject: Python embedding question. In-Reply-To: <5e0e47aa-a7bc-4e43-98cd-07fc0f6fe454@l42g2000hsc.googlegroups.com> References: <45f657a0-315f-421e-8d69-1c5b24e23887@k37g2000hsf.googlegroups.com> <5e0e47aa-a7bc-4e43-98cd-07fc0f6fe454@l42g2000hsc.googlegroups.com> Message-ID: The Pyglet library has all the functionality of pygame, but is smaller and much more self-contained. Pygame requires SDL, pyglet only OpenGL. On Jul 15, 2008, at 6:26 AM, Uwe Schmitt wrote: > On 15 Jul., 12:14, Thomas Troeger > wrote: >> Kay Schluehr wrote: >>> On 15 Jul., 11:51, Thomas Troeger >>> wrote: >> >>>> I've really looked at a lot of places but haven't found a suitable >>>> solutions yet, so I'm asking here in hope that someone has >>>> experience >>>> with that topic. >> >>> Which solutions did you rule out? >> >> - Python + Qt, because it's definitely overkill for my plans. I only >> need simple graphics and some sound, no widgets. Basically I'm >> looking >> for something really lightweight that has methods for drawing graphic >> primitives and renders fonts -- no complicated widgets, windows, >> scrollbars and the like. And, for example, the Qt library is a real >> heavyweight with approx. 10 MB for qt-3.3.8 alone. >> >> - The same holds for cairo/pango, I've written a test program (in >> C, I >> must say) that has dynamic links to 10 libraries that are all like >> 250kb >> in size. That's a lot for a small embedded device. >> > Did you try pygame ? I think it has a small footprint. > > Greetings, Uwe > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From ki4yjl at gmail.com Fri Jul 11 14:29:04 2008 From: ki4yjl at gmail.com (WDC) Date: Fri, 11 Jul 2008 11:29:04 -0700 (PDT) Subject: Using the Random Module. References: Message-ID: On Jul 11, 2:15?pm, Michiel Overtoom wrote: > You wrote... > >Is there a better way to do that besides doing this: > > >>>>random.randint(00000000000000000, 99999999999999999) > >09657398671238769 > > Maybe this? > > ? ? ? ? random.randint(0, 9e16) > > -- > "The ability of the OSS process to collect and harness > the collective IQ of thousands of individuals across > the Internet is simply amazing." - Vinod Vallopillilhttp://www.catb.org/~esr/halloween/halloween4.html That would work yes, but is there a random() function that would do that without the attributes? Not trying to be lazy, I just want to know if there is a built in way. Thanks Michiel. From siona at chiark.greenend.org.uk Thu Jul 10 08:09:10 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 10 Jul 2008 13:09:10 +0100 (BST) Subject: Allow tab completion when inputing filepath? References: <08e60124-51c1-40c1-bffe-52c22ff310db@l64g2000hse.googlegroups.com> Message-ID: Keith Hughitt wrote: >> Keith Hughitt wrote: >> > [ ... ] I have >> > found some ways to enable tab completion for program-related commands, >> > but not for system filepaths. >Currently Unix/Console. What's wrong with the readline module? http://docs.python.org/lib/module-readline.html -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From james at reggieband.com Thu Jul 10 13:06:36 2008 From: james at reggieband.com (James Fassett) Date: Thu, 10 Jul 2008 10:06:36 -0700 (PDT) Subject: Idiomatic Python to convert list to dict Message-ID: <7ec9405c-4e6f-491d-84b2-c81152302b13@79g2000hsk.googlegroups.com> Hi all, Simple question really on a best practice. I want to avoid adding duplicates to a list. my_list = ['a', 'b', 'c', 'd', 'e'] dup_map = {} for item in my_list: dup_map[item] = True # ... sometime later for complex_dict in large_list: if complex_dict["char"] not in dup_map: my_list.append(complex_dict["char"]) dup_map[complex_dict["char"]] = True For the first part (generating the duplicate map) is there a more idiomatic Python method for flipping the list into a dict? Is there a better way to achieve the overall objective (as hinted at by the above algorithm)? Thanks in advance for any tips. James. From animator333 at yahoo.com Thu Jul 17 00:29:08 2008 From: animator333 at yahoo.com (Prashant Saxena) Date: Wed, 16 Jul 2008 21:29:08 -0700 (PDT) Subject: subtype and super method. How to? Message-ID: <623762.62274.qm@web33406.mail.mud.yahoo.com> import sys class Attribute(object): ??? """ ??? Common attributes and methods for custom types ??? """ ??? __slots__ = [] ?? ? ??? def __init__(self, name=None, type=None, range=(0,1)): ??????? self.__name = name ??????? self.__type = type ??????? self.__range = range ?? ? ??? #Read only attributes ??? name = property(lambda self: self.__name) ??? type = property(lambda self: self.__type) ??? range = property(lambda self: self.__range) ?????? ? class Float(float, Attribute): ??? '''Custom Float type''' ??? __slots__ = ('__name', '__type', '__range') ??? def __new__(self, value=0.0, name=None, type=None, range=(0.0, 1.0)): ??????? try: ??????????? super(Float, self).__init__(name=name, type=type, range=range) ??????????? return float.__new__(self, value) ??????? except: ??????????? print 'Error : %s %s' % sys.exc_info()[:2] ?????????????? ? class Int(int, Attribute): ??? '''Custom Int type''' ??? __slots__ = ('__name', '__type', '__range') ??? def __new__(self, value=0, name=None, type=None, range=(0, 1)): ??????? try: ??????????? super(Int, self).__init__(name=name, type=type, range=range) ??????????? return int.__new__(self, value) ??????? except: ??????????? print 'Error : %s %s' % sys.exc_info()[:2] a = Float(2.0, name='myFloat') print a 'Float' & 'Int' instances are not getting initialize. How to solve? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From desothier at yahoo.com Wed Jul 9 04:56:19 2008 From: desothier at yahoo.com (antar2) Date: Wed, 9 Jul 2008 01:56:19 -0700 (PDT) Subject: delete lines Message-ID: <35d53620-16c7-4c2c-b904-04dbab6bc91a@z66g2000hsc.googlegroups.com> I am new in python and I have the following problem: Suppose I have a list with words of which I want to remove each time the words in the lines below item1 and above item2: item1 a b item2 c d item3 e f item4 g h item1 i j item2 k l item3 m n item4 o p I did not find out how to do this: Part of my script was f = re.compile("item\[1\]\:") g = re.compile("item\[2\]\:") for i, line in enumerate(list1): f_match = f.search(line) g_match = g.search(line) if f_match: if g_match: if list1[i] > f_match: if list1[i] < g_match: del list1[i] But this does not work If someone can help me, thanks! From carsten.haese at gmail.com Sun Jul 20 00:24:25 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Sun, 20 Jul 2008 00:24:25 -0400 Subject: atan2 weirdness In-Reply-To: <3b3ce28f-55d0-4db4-8eac-df0a9d1bc558@o40g2000prn.googlegroups.com> References: <3b3ce28f-55d0-4db4-8eac-df0a9d1bc558@o40g2000prn.googlegroups.com> Message-ID: narutocanada at gmail.com wrote: > hi > > atan2 is supposed to return the angle to x-axis when given y and x, I > suppose if I take [x,y] to one full circle, I should get 0-360 degree > back---- but no, I get 3 full revolutions! > maybe my understanding is wrong. > > from math import * > > def f(ang): > a=ang > if a>360: a-=360 > if a>360: a-=360 > if a<0: a+=360 > if a<0: a+=360 > return round(a) > > for i in range(0,360): > t=2*pi*i/360.0 > print i,f(atan2(sin(t),cos(t))*180.0) Your understanding of atan2 is correct, but your conversion from radians to degrees is off by a factor of pi. Since pi is close to 3, you're getting what appears to be three full revolutions. HTH, -- Carsten Haese http://informixdb.sourceforge.net From arazak73 at yahoo.com.my Tue Jul 1 23:12:14 2008 From: arazak73 at yahoo.com.my (ajak_yahoo) Date: Wed, 2 Jul 2008 11:12:14 +0800 Subject: how to used pyodbc to connect foxpro table Message-ID: <014501c8dbf1$70018c10$1f01a8c0@RAZAK> Good Morning to All, Can anyone help me to connect pyodbc to foxpro table. Below code can't works. import pyodbc cnxn = pyodbc.connect("DSN=sls_detl") Traceback (most recent call last): File "", line 1, in cnxn = pyodbc.connect("DSN=sls_detl") Error: ('S1000', "[S1000] [Microsoft][ODBC Visual FoxPro Driver]File is not open. (113) (SQLDriverConnectW); [01000] [Microsoft][ODBC Driver Manager] The driver doesn't support the version of ODBC behavior that the application requested (see SQLSetEnvAttr). (0)") T.q -------------- next part -------------- An HTML attachment was scrubbed... URL: From maric at aristote.info Fri Jul 18 06:28:26 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 18 Jul 2008 12:28:26 +0200 Subject: sub typing built in type with common attributes. Am I right? In-Reply-To: <98c3de7d-f167-48f9-9736-b09938d96b92@f40g2000pri.googlegroups.com> References: <4d9c4b74-9c28-4b98-afe7-9eb774655c3a@v21g2000pro.googlegroups.com> <98c3de7d-f167-48f9-9736-b09938d96b92@f40g2000pri.googlegroups.com> Message-ID: <200807181228.26446.maric@aristote.info> Le Friday 18 July 2008 11:36:20 King, vous avez ?crit?: > Could you please suggest an alternative or code improvement for the > matter. I'm not sure what you are trying to achieve with your snippet, but I suspect it's some sort of templating, right ? If so, using the dynamic nature of python should help : >>>[103]: def make_subtype_with_attr(type_, ro_attr, rw_attr) : dic = {} for i in ro_attr : dic[i] = property(lambda s, n=i : getattr(s, '_'+n)) def __new__(cls, *args, **kwargs) : instance = type_.__new__(cls, *args) for i in rw_attr : setattr(instance, i, kwargs[i]) for i in ro_attr : setattr(instance, '_'+i, ro_attr[i]) return instance dic['__new__'] = __new__ return type('my_' + type_.__name__, (type_,), dic) .....: >>>[113]: my_int = make_subtype_with_attr(int, {'name' : 'myint', 'id':123452}, ('foo',)) >>>[114]: i = my_int(5, foo=3) >>>[115]: i.foo ...[115]: 3 >>>[116]: i ...[116]: 5 >>>[117]: i.id ...[117]: 123452 >>>[118]: i.id = 2 --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /home/maric/ in () AttributeError: can't set attribute -- _____________ Maric Michaud From chrisspen at gmail.com Sun Jul 13 21:01:01 2008 From: chrisspen at gmail.com (Chris) Date: Sun, 13 Jul 2008 18:01:01 -0700 (PDT) Subject: Using Groups inside Braces with Regular Expressions References: <10284e46-1601-4269-a1a0-ef3831e9f85c@z66g2000hsc.googlegroups.com> <87e2b1a0-e732-42d3-aa94-061dcd81d35c@z72g2000hsb.googlegroups.com> Message-ID: <262021b7-ebdf-47ec-817f-54e42e84a94e@f63g2000hsf.googlegroups.com> On Jul 13, 8:14 pm, MRAB wrote: > On Jul 14, 12:05 am, Chris wrote:> I'm trying to delimit sentences in a block of text by defining the > > end-of-sentence marker as a period followed by a space followed by an > > uppercase letter or end-of-string. > > > I'd imagine the regex for that would look something like: > > [^(?:[A-Z]|$)]\.\s+(?=[A-Z]|$) > > > However, Python keeps giving me an "unbalanced parenthesis" error for > > the [^] part. If this isn't valid regex syntax, how else would I match > > a block of text that doesn't the delimiter pattern? > > What is the [^(?:[A-Z]|$)] part meant to be doing? Is it meant to be > matching everything up to the end of the sentence? > > [...] is a character class, so Python is parsing the character class > as: > > [^(?:[A-Z]|$)] > ^^^^^^^^^^ It was meant to include everything except the end-of-sentence pattern. However, I just realized that I can simply replace it with ".*?" From fuzzyman at gmail.com Fri Jul 11 09:25:47 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Fri, 11 Jul 2008 06:25:47 -0700 (PDT) Subject: ANN: P4D 1.1 References: Message-ID: On Jul 11, 10:09?am, Kay Schluehr wrote: > P4D = E4X style embedded DSL for Python but without E and X. > > For more information see: > > http://pypi.python.org/pypi/P4D/1.1-py2.5 That looks a lot like YAML. Any reason to use it over YAML? Michael Foord http://www.ironpythoninaction.com/ From google at mrabarnett.plus.com Mon Jul 14 11:44:55 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 14 Jul 2008 08:44:55 -0700 (PDT) Subject: Python beginner, unicode encode/decode Q References: <487B4BC5.7FA8FFF9@anonymous.com> Message-ID: <5ebb3820-4452-418a-bc01-9084701053bc@k30g2000hse.googlegroups.com> On Jul 14, 1:51?pm, anonymous wrote: > 1 Objective to write little programs to help me learn German. ?See code > after numbered comments. //Thanks in advance for any direction or > suggestions. > > tk > > 2 ?Want keyboard answer input, for example: ? > > answer_str ?= raw_input(' Enter answer > ') Herr ??? > > [ I keyboard in the following characters Herr ?? ] > print answer_str > Output on screen is > Herr ?? > > 3 ? history 1 and 2 ?code run interactively under Debian Linux Python > 2.4 and interactively under windows98, first edition IDLE, Python 2.3.5 > and it works. > > 4 ?history 3 and 4 code run from within a .py file produce different > output from example in book. > > 5 want to operate under Debian Linux but because the program failed > under Linux when I tried to run the code from a file in Linux Python, I > thougt I should fire up the win98 Idle/python program and try it to see > if ran there but it failed, too from within a file. > > 6 The sample code is from page 108-109 of: ? "Python for Dummies" > ? ? ? It says in the book: ?"Python's file objects and StringIO objects > don't support raw Unicode; the usual workaround is to encode Unicode as > UTF-8 before saving it to a file or stringIO object. ? > The sample code from the book is French as indicate here but trying > German produces the same result. > > 7 I have searched the net under all the keywords but this is as close as > I get to accomplishing my task. ?I suspect I may not be understanding: > StringIO objects don't support raw Unicode, but I don't know. > > #_*_ coding: utf-8 _*_ > > # code run under linux debian ?interactively from a terminal and works > > print " u'Libert\u00e9' " > > # y = raw_input('Enter >') ?commented out > > y = u'Lbert\u00e9' > y.encode('utf-8') > q = y.encode('utf-8') > q.decode('utf-8') > print q.decode('utf-8') > > history 1 works and here is the screen copy of interactive > > ?>>> y = raw_input ('>') > ?>Libert\xc3\xa9 > ?>>> q = 'Libert\xc3\xa9' > ?>>> q.decode('utf-8') > u'Libert\xe9' > ?>>> print q > Libert? > ?>>> > > [ ?screen output is next line ] > > Lbert? > > history 2 > # code run under win98, first edition, within IDLE interactively and > succeeded in produce correct results. > > # y = raw_input('Enter >') ?commented out > > y = u'Lbert\u00e9' > y.encode('utf-8') > q = y.encode('utf-8') > q.decode('utf-8') > print q.decode('utf-8') > > history 1 works and here is the screen copy of interactive > > ?>>> y = raw_input ('>') > ?>Libert\xc3\xa9 > ?>>> q = 'Libert\xc3\xa9' > ?>>> q.decode('utf-8') > u'Libert\xe9' > ?>>> print q > Libert? > ?>>> > > [ ?screen output is next line ] > > Lbert? > > # history 3 > > # this code is run from within idle on win98 and inside a python file. ? > # ?The code DOES NOT produce the proper outout. > > #_*_ coding: utf-8 _*_ > > # print "u'Libert\u00e9'" ?printed to screen > > y = raw_input('Enter >') > > # y = u'Lbert\u00e9' commented out > > y.encode('utf-8') > q = y.encode('utf-8') > q.decode('utf-8') > print q.decode('utf-8') > > # output is ?on the lines ?below was produced on the screen after run > > enter u'Libert\u00e9' on screen to copy into into y string > Enter >u'Libert\u00e9' > > u'Libert\u00e9' > > The code DOES NOT produce Libert? but instead produce u'Libert\u00e9' > > # history 4 > > # this code is run from within terminal on Debian linux ? inside a > python file. ? > # The code does not produce proper outout but produces the same output > as run on > # windows. > > #_*_ coding: utf-8 _*_ > > print "u'Libert\u00e9'" ?printed to screen > > y = raw_input('Enter >') > > # y = u'Lbert\u00e9' commented out > > y.encode('utf-8') > q = y.encode('utf-8') > q.decode('utf-8') > print q.decode('utf-8') > > # output is ?on the lines ?below was produced on the screen after run > > enter u'Libert\u00e9' on screen to copy into into y string > Enter >u'Libert\u00e9' > u'Libert\u00e9' > > The code DID NOT produce Libert? but instead produce u'Libert\u00e9' raw_input returns what you entered. You entered u'Libert\u00e9' so that's what was printed out. If you want to be able to enter escape sequences like \u00e9 and have them decoded to the appropriate character then you must do something like this: # The code text = raw_input('Enter >') decoded_text = text.decode("unicode-escape") print decoded_text # The output Enter >Libert\u00e9 Libert? HTH From deets at nospam.web.de Thu Jul 24 14:41:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 Jul 2008 20:41:13 +0200 Subject: need help with introducing more traffic In-Reply-To: References: <632875.28836.qm@web51808.mail.re2.yahoo.com> Message-ID: <6es0m9F8mehmU1@mid.uni-berlin.de> Fredrik Lundh schrieb: > leo davis skrev: > >> I found this code snippet(reference http://www.goldb.org) and wish to >> do more with it than just send out a Http Get request.I would like to >> introduce more traffic -say by downloading files,crawling through all >> the links,logging in etc etc,and wish to see how the web server >> reacts.I'm trying to stress the server to its limits....appreciate if >> anyone could provide me code/ideas to inject into this. >> the website -http://ftp.ruby-lang.org/pub/ruby/binaries/mswin32/ >> selected as example has many downloads.i tried from urllib import > > umm. are you saying that you run ruby-lang.org and want to write a > stress tester in Python just for the fun of it, or are we missing > something here... This: http://www.pylot.org/ Seems as if he *is* using various languages for fun... Diez From mrkafk at gmail.com Sun Jul 13 12:40:18 2008 From: mrkafk at gmail.com (mk) Date: Sun, 13 Jul 2008 18:40:18 +0200 Subject: Magic? Message-ID: So I was playing around with properties and wrote this: class lstr(str): def __init__(self, initval): self._s = initval self._len = len(self._s) def fget_s(self): return str(self._s) def fset_s(self, val): self._s = val self._len = len(self._s) s = property(fget_s, fset_s) def fget_len(self): return self._len def fset_len(self, val): raise AttributeError, "Attribute is read-only." len = property(fget_len, fset_len) I obviously aimed at defining setters and getters for 's' and 'len' attributes via using properties to that. However, it appears that somehow this object prints the value of 's' attribute without me setting any specific methods to do that: >>> astr = lstr('abcdef') >>> astr 'abcdef' >>> astr.swapcase() 'ABCDEF' How does it know to do that? I mean, I can understand how it knows to do that since I used property: >>> astr.s 'abcdef' >>> vars(astr) {'_len': 6, '_s': 'abcdef'} How does the instance know to use _s value to return when the instance is called? Is this due to some trick handling of overriden __init__ method (i.e. it knows to treat initval argument somehow specially)? Some other way? If so, how? From dorjetarap at googlemail.com Fri Jul 11 18:22:32 2008 From: dorjetarap at googlemail.com (kdt) Date: Fri, 11 Jul 2008 15:22:32 -0700 (PDT) Subject: palindrome function Message-ID: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Hi all, Can someone please explain to me why the following evaluates as false? >>>list=['a','n','n','a'] >>>list==list.reverse() >>>False I'm stumped :s From ptmcg at austin.rr.com Tue Jul 1 04:04:50 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 1 Jul 2008 01:04:50 -0700 (PDT) Subject: How make regex that means "contains regex#1 but NOT regex#2" ?? References: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> Message-ID: On Jul 1, 2:34?am, "A.T.Hofkamp" wrote: > On 2008-07-01, seber... at spawar.navy.mil wrote: > > > I'm looking over the docs for the re module and can't find how to > > "NOT" an entire regex. > > (?! R) > > > How make regex that means "contains regex#1 but NOT regex#2" ? > > (\1|(?!\2)) > > should do what you want. > > Albert I think the OP wants both A AND not B, not A OR not B. If the OP want to do re.match(A and not B), then I think this can be done as ((?! \2)\1), but if he really wants CONTAINS A and not B, then I think this requires 2 calls to re.search. See test code below: import re def test(restr,instr): print "%s match %s? %s" % (restr,instr,bool(re.match(restr,instr))) a = "AAA" b = "BBB" aAndNotB = "(%s|(?!%s))" % (a,b) test(aAndNotB,"AAA") test(aAndNotB,"BBB") test(aAndNotB,"AAABBB") test(aAndNotB,"zAAA") test(aAndNotB,"CCC") aAndNotB = "((?!%s)%s)" % (b,a) test(aAndNotB,"AAA") test(aAndNotB,"BBB") test(aAndNotB,"AAABBB") test(aAndNotB,"zAAA") test(aAndNotB,"CCC") def test2(arestr,brestr,instr): print "%s contains %s but NOT %s? %s" % \ (instr,arestr,brestr, bool(re.search(arestr,instr) and not re.search(brestr,instr))) test2(a,b,"AAA") test2(a,b,"BBB") test2(a,b,"AAABBB") test2(a,b,"zAAA") test2(a,b,"CCC") Prints: (AAA|(?!BBB)) match AAA? True (AAA|(?!BBB)) match BBB? False (AAA|(?!BBB)) match AAABBB? True (AAA|(?!BBB)) match zAAA? True (AAA|(?!BBB)) match CCC? True ((?!BBB)AAA) match AAA? True ((?!BBB)AAA) match BBB? False ((?!BBB)AAA) match AAABBB? True ((?!BBB)AAA) match zAAA? False ((?!BBB)AAA) match CCC? False AAA contains AAA but NOT BBB? True BBB contains AAA but NOT BBB? False AAABBB contains AAA but NOT BBB? False zAAA contains AAA but NOT BBB? True CCC contains AAA but NOT BBB? False As we've all seen before, posters are not always the most precise when describing whether they want match vs. search. Given that the OP used the word "contains", I read that to mean "search". I'm not an RE pro by any means, but I think the behavior that the OP wants is given in the last 4 tests, and I don't know how to do that in a single RE. -- Paul From Samnsparky at gmail.com Thu Jul 10 12:16:15 2008 From: Samnsparky at gmail.com (Sparky) Date: Thu, 10 Jul 2008 09:16:15 -0700 (PDT) Subject: Local User Control References: Message-ID: On Jul 10, 10:13?am, Tim Golden wrote: > Sparky wrote: > > On Jul 10, 9:58 am, Tim Golden wrote: > >> Sparky wrote: > >>> I don't know how feasible this is, but is it possible to have users > >>> log in to access a local database file in such a way that allows the > >>> program to know what user name and password they logged in with? This > >>> would involve separate user names and passwords for each user. > >> Well, this is a question which is crying out for some > >> context. Are you talking about an existing database > >> on an existing platform? If so, which one? Are you > >> talking about a database youo're thinking of building? > >> If so, the answer's probably yes but only you can > >> know. Are you talking about something else altogether? > > >> TJG > > > Thanks for the timely response. This would be a database that I am > > building myself. The question comes down to is there a feasible way to > > verify a user's user name and password from inside that database. > > Obviously the file would be encrypted, but if there is going to be > > more than one user using it I suppose there would be a separate file > > for a log-in. I am just asking for some guidance on how this would > > theoretically be implemented. > > Maybe someone else on the list has a clearer idea than I do, > but at this distance from an implementation, all I can say is: > yes, I'm sure you can achieve some kind of user authentication. > After all, lots of other products already do. Or is your proposed > db very different? > > TJG Thanks. I suppose I probably should get further down the road and come back with a more specific question. Thanks again, Sam From robert.kern at gmail.com Tue Jul 1 16:14:46 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 01 Jul 2008 15:14:46 -0500 Subject: ImportError: No module named _md5 In-Reply-To: References: Message-ID: neridaj at gmail.com wrote: > Hello, > > Does anyone know how to fix this error when trying to build MySQL- > python-1.2.2: > > python setup.py build > Traceback (most recent call last): > File "setup.py", line 5, in > import ez_setup; ez_setup.use_setuptools() > File "/Users/jasonnerida/Downloads/MySQL-python-1.2.2/ez_setup.py", > line 83, in use_setuptools > egg = download_setuptools(version, download_base, to_dir, > download_delay) > File "/Users/jasonnerida/Downloads/MySQL-python-1.2.2/ez_setup.py", > line 111, in download_setuptools > import urllib2, shutil > File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/ > lib/python2.5/urllib2.py", line 91, in > import hashlib > File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/ > lib/python2.5/hashlib.py", line 133, in > md5 = __get_builtin_constructor('md5') > File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/ > lib/python2.5/hashlib.py", line 60, in __get_builtin_constructor > import _md5 > ImportError: No module named _md5 > > I then tried installing py25-hashlib via macports, which never > completes: > > sudo port install py25-hashlib > Password: > Waiting for lock on /opt/local/var/macports/build/ > _opt_local_var_macports_sources_rsync.macports.org_release_ports_python_py25- > hashlib/work/.macports.py25-hashlib.state > > Do I need to completely reinstall python? I'm using 2.5.2 which > shipped with Leopard. Delete the directory /opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_python_py25-hashlib/ and try building py25-hashlib again. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From fuzzyman at gmail.com Mon Jul 28 18:52:48 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 28 Jul 2008 15:52:48 -0700 (PDT) Subject: ANN: PyCon UK Talks and Tutorials List Up Message-ID: PyCon UK 2008 is the second PyCon event in the UK, and is being held on 12th to 14th September at the Birmingham Conservatoire. We have a bevy of national and international Python stars speaking as well as a host of members of the Python community. The conference starts with a day of tutorials on the Friday. The timetable for the tutorials day has now been published: http://www.pyconuk.org/timetable.html We have abstracts of currently accepted talks, tutorials and BOFs: http://www.pyconuk.org/talk_abstracts.html The early bird rate is still open (but not for too much longer): http://www.pyconuk.org/booking.html We are almost there with the schedule, the plenary sessions will include Lightning talks as well as keynotes from Mark Shuttleworth and Ted Leung. We may be accepting a couple more talks if we can squeeze them in somewhere. (If you are expecting to give a talk but have not given us an abstract, then please give it to us ASAP) Michael Foord and the other PyCon UK Organisers From sjmachin at lexicon.net Sat Jul 19 17:55:23 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 19 Jul 2008 14:55:23 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> <6ebshqF67cpfU4@mid.uni-berlin.de> <5d6b8066-c941-4f0c-abea-20baed33b4ab@l64g2000hse.googlegroups.com> Message-ID: <569da8b8-df8a-4115-a952-5d8c2d9744e0@i20g2000prf.googlegroups.com> On Jul 20, 6:13 am, nicolas.pource... at gmail.com wrote: > On 18 juil, 17:52, Marc 'BlackJack' Rintsch wrote: > > > On Fri, 18 Jul 2008 07:39:38 -0700, nicolas.pourcelot wrote: > > > So, I use something like this in 'sheet.objects.__setattr__(self, > > > name, value)': > > > if type(value) == Polygon: > > > for edge in value.edges: > > > if edge is_in sheet.objects.__dict__.itervalues(): > > > object.__setattr__(self, self.__new_name(), edge) > > > > Ok, I suppose it's confused, but it's difficult to sum up. ;-) > > > You are setting attributes with computed names? How do you access them? > > Always with `gettattr()` or via the `__dict__`? If the answer is yes, why > > don't you put the objects the into a dictionary instead of the extra > > redirection of an objects `__dict__`? > > Yes, I may subclass dict, and change its __getitem__ and __setitem__ > methods, instead of changing objets __setattr__ and __getattr__... But > I prefer > > >>> sheet.objects.A = Point(0, 0) > than > >>> sheet.objects["A"] = Point(0, 0) > > Oh and the `type()` test smells like you are implementing polymorphism > > in a way that should be replaced by OOP techniques. > > I wrote 'type' here by mistake, but I used 'isinstance' in my > code. ;-) > > > If you make Point immutable you might be able to drop the "must not be > > referenced twice" requirement. > > Yes, but unfortunately I can't (or it would require complete > redesign...) (1) You are searching through lists to find float objects by identity, not by value (2) Peter says he doesn't understand (3) Marc thinks it smells IOW, the indications are that it *already* requires complete redesign. From theller at python.net Mon Jul 28 10:03:15 2008 From: theller at python.net (Thomas Heller) Date: Mon, 28 Jul 2008 16:03:15 +0200 Subject: ctypes and how to copy data passed to callback In-Reply-To: <2059b8a4-7651-4c3c-afbf-44caa8605c64@m3g2000hsc.googlegroups.com> References: <2059b8a4-7651-4c3c-afbf-44caa8605c64@m3g2000hsc.googlegroups.com> Message-ID: <6f61s7Fa0pq9U1@mid.individual.net> waldek schrieb: > Hi, > > I'm trying to handle data passed to Py Callback which is called from > C dll. Callback passes data to another thread using Queue module and > there the data are printed out. > > If data is printed out in a callback itself it's ok. If I put on > queue and next get from queue in another thread script prints some > trash. Looks like the data is released when callback returned. I tired > to make d = copy.deepcopy(data), but it does not work - I got nothing. > Any idea why it's happening ? > > --------------------- main thread -------- > def callback(data, size): > myqueue.put((data, size)) > > mydll = cdll.MyDLL > cbproto = CFUNCTYPE(c_int, POINTER(c_char), c_int) > mycallback = cbproto(callback) > > mydll.RegisterCallback(mycallback) > > ---------------------------------- thread listener > ---------------------- > > while True: > data, size = myqueue.get() > print "***", data[:size] > > ------------------------------------------------------------------------------ I guess your code would work if you change it in this way: > def callback(data, size): > myqueue.put(data[:size]) > while True: > data = myqueue.get() > print "***", data Thomas From cokofreedom at gmail.com Tue Jul 22 03:03:14 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 22 Jul 2008 00:03:14 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <9803eab7-3b01-4a9e-8672-43d153c1617e@w7g2000hsa.googlegroups.com> On Jul 22, 5:59 am, Larry Bates wrote: > Grant Edwards wrote: > > On 2008-07-22, Larry Bates wrote: > > >> You talk about "writing it in assembly language for each MPU > >> chip". Actually it is even better than that. We now have > >> these modern inventions, called compilers that do that type of > >> work for us. They translate high level instructions, not > >> into assembler but into machine language. > > > Actually, all of the compilers I'm familiar with (gcc and a > > handful of cross compilers for various microprocessors) > > translate from high-level languages (e.g. C, C++) into > > assembly, which is then assembled into relocatable object > > files, which are then linked/loaded to produce machine > > language. > > I just learned something I did not know. I was under the impression that they > translated directly to machine code without ever actually generating Assembler > text files. Seems like a waste to generate the text and turn around run that > through the assembler, but what do I know. I guess that way the compiler can > have pluggable assembler back-ends. > > -Larry I also I have just learned something new! Troll threads are useful. Yay. From fetchinson at googlemail.com Sat Jul 12 12:49:25 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 12 Jul 2008 09:49:25 -0700 Subject: How to create a timer/scheduler in Python? In-Reply-To: <0stg74t0eksmnfsslukn5m7f9s4rbub8kt@4ax.com> References: <0stg74t0eksmnfsslukn5m7f9s4rbub8kt@4ax.com> Message-ID: > I need what I'd call (in .Net) a timer, ie I need to run a function eg > every 2 seconds - it doesn't need to be millisec accurate but it would > be nice if it wasn't eg every 4 seconds or something. > > Rather surprisingly, Core Python (Chun) doesn't seem to index 'timer' > or 'scheduler', which leaves me wondering whether this is an aspect of > Python that isn't perhaps widely used? > > Looking around on the net I can see references to a thread timer, but > I'm not really looking to start any new threads (I just want part of > the GUI to update every 2 secs) and don't want to get into that sort > of complication while still just learning Python. > > Is there really no simple timer/scheduler function available in > Python? You might want to look at scheduler.py from turbogears which is exactly the tool you describe and luckily is 99.99% independent of turbogears. I'd think you need to modify 1-2 lines: http://svn.turbogears.org/tags/1.0.4.4/turbogears/scheduler.py Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From bearophileHUGS at lycos.com Thu Jul 31 15:59:02 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 31 Jul 2008 12:59:02 -0700 (PDT) Subject: simple problem with lists I am just forgetting References: Message-ID: <31fc98d7-ea8f-47b2-91f5-04a8f68313da@k37g2000hsf.googlegroups.com> Alexnb: > How can I test if the list item is empty without getting that exception? In Python such list cell isn't empty, it's absent. So you can use len(somelist) to see how much long the list is before accessing its items. Often you can iterate on the list with a for, so you don't need to care of the len(). Bye, bearophile From __peter__ at web.de Fri Jul 11 04:14:28 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jul 2008 10:14:28 +0200 Subject: ActiveState Code: the new Python Cookbook site References: <4873F326.5010905@activestate.com> <4874698E.7000805@gmail.com> <4877053f$0$16181$5402220f@news.sunrise.ch> Message-ID: Thin Myrna wrote: > The old cookbook offered choices by category. Did you drop that feature? Looks like categories have become tags: http://code.activestate.com/recipes/tags/ Peter From elessar at nienna.org Wed Jul 30 11:23:05 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Wed, 30 Jul 2008 09:23:05 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> Message-ID: <48908759.60202@nienna.org> Russ P. wrote: > On Jul 30, 12:03 am, Heiko Wundram wrote: >> Am Mittwoch, 30. Juli 2008 08:30:48 schrieb Russ P.: >> >>> On Jul 29, 11:09 pm, Erik Max Francis wrote: >>>> I'm getting this sneaking suspicion that you guys are all putting us on. >>> As I said in an earlier post, I realize that this would only work if >>> there were only one copy of "empty" (as there is only one copy of >>> "None"). I don't know off hand if that is feasible or not. >>> You reply reeks of the kind of pedantic snobbishness that makes me >>> sick. >> I can understand (and pretty much sympathise) that you get this kind of reply, >> simply because the point you and Carl Banks (formulated somewhat differently) >> put up has been answered again and again (in this thread), and I can only >> repeat it once more: >> >> __nonzero__(), i.e. the "cast" to boolean, is THE WAY to test whether a >> container is empty or not. Like this design decision, or don't like it, but >> the discussion is not going to go anywhere unless you concede that there is a >> (very explicit!) way to test for non-emptiness of a container already, and >> you're currently simply discussing about adding/using syntactic sugar >> (different means of expressing the test) to suit your own personal taste >> better. Anyway, check the documentation for __nonzero__(): if the object >> doesn't implement that, but implements __len__(), the interpreter "replaces" >> the __nonzero__() test by __len__()>0, so I guess someone in the design >> department must've seen it logical for the truth value of a container to >> express the test "len(x)>0" at some point in time to make this interpretation >> for the truth value of a container. >> >> There cannot be an argument about missing/misplaced functionality (that's what >> you make it sound like), if the functionality for doing what you want to do >> is there and you simply don't like the syntax, which I can somewhat relate to >> because style is a personal thing, even though I don't see either points made >> by you or Carl Banks, because implicit casting to bool is so common in pretty >> much every programming language to test for "truth" of an object, and IMHO >> it's completely logical to extend that idea to containers to mean >> empty/non-empty. >> >> Eric Max Francis tried to explain why your syntactic "enhancement" would come >> at a much greater price than its worth, and he's absolutely right in that, as >> it's an abuse of the "is" operator, but again, that's a somewhat different >> point. It changes nothing about the fact that all this discussion centers >> around something that is a non-point, but simply a matter of personal taste. >> >> -- >> Heiko Wundram > > Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > __nonzero__ work in Python. It's very basic stuff. You can quit > patronizing me (and Carl too, I'm sure). > > The point that you seem to be missing, or refuse to acknowledge for > some reason, is that "if x" can be mistakenly applied to any object > when the programmer thinks that x is a list -- and the programmer will > receive no feedback on the error. > > I have made errors like that, and I could have saved some time had I > used an "empty" method that only applies to a list or other sequence. > > Is that an important issue? I don't know. I'm not claiming it is. But > you cannot just sweep it away as nothing. > -- > http://mail.python.org/mailman/listinfo/python-list > See, I can agree with this. If you're expecting a list (and only a list) then your point makes sense. 'if x' can get you into trouble if you _don't_ want its polymorphism. Although, if my function is expecting a list, my preference is to do: if not isinstance(x, list): raise SomeMeaningfulException() # do stuff with the list I put my type checking at the top of the function, so readers can reference it easily. However, Carl's point is that 'if x' is never preferable to the more verbose and slower "simple test". I do not agree with this. -Matt From mingtian_good at sina.com Thu Jul 10 22:17:22 2008 From: mingtian_good at sina.com (128) Date: Thu, 10 Jul 2008 19:17:22 -0700 (PDT) Subject: paypal wholesale men jordans 17 (paypal accept)(www super-saler com Message-ID: <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans 18 (paypal accept)(www super-saler com paypal wholesale men jordans 19 (paypal accept)(www super-saler com paypal wholesale men jordans 20 (paypal accept)(www super-saler com paypal wholesale men jordans 21 (paypal accept)(www super-saler com paypal wholesale men jordans 22 (paypal accept)(www super-saler com paypal wholesale men jordans 23 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans 18 (paypal accept)(www super-saler com paypal wholesale men jordans 19 (paypal accept)(www super-saler com paypal wholesale men jordans 20 (paypal accept)(www super-saler com paypal wholesale men jordans 21 (paypal accept)(www super-saler com paypal wholesale men jordans 22 (paypal accept)(www super-saler com paypal wholesale men jordans 23 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans 18 (paypal accept)(www super-saler com paypal wholesale men jordans 19 (paypal accept)(www super-saler com paypal wholesale men jordans 20 (paypal accept)(www super-saler com paypal wholesale men jordans 21 (paypal accept)(www super-saler com paypal wholesale men jordans 22 (paypal accept)(www super-saler com paypal wholesale men jordans 23 (paypal accept)(www super-saler com From Ross at nomail.spam.thanks Fri Jul 4 15:37:31 2008 From: Ross at nomail.spam.thanks (RossGK) Date: Fri, 04 Jul 2008 15:37:31 -0400 Subject: pydev and psycopg2 - weird behaviour Message-ID: <486e7bfc@news.alcatel.com> I've been using pydev for a short while successfully, and Django with postgresql as well. psycopg2 is part of that behind the scenes I would imagine, to make django work. Now I'm trying to use psycopg2 in a non-Django program, I'm seeing some weird behaviour My "import psycopg2" is tagged in pyDev (eclipse) as "Unresolved Import: psycopg2" But when I run my code anyway, I seem to connect to the postgresql DB okay. If I remove the import, and try it, it fails. So it seems to use it, but thinks it's unresolved. Any idea what's going on there? Just to be sure it's installed right, I reinstalled with no change. I also opened a python shell (cmd window in winXP environment) and on the command line issued a psycopg2 connect request which succeeds as well. So it mostly seems to be an erroneous report from pydev that it can't resolve psycopg2 when it apparently can? Your input appreciated... Ross. From bourdenas at gmail.com Tue Jul 29 07:45:02 2008 From: bourdenas at gmail.com (Themis Bourdenas) Date: Tue, 29 Jul 2008 12:45:02 +0100 Subject: method decorators and more on decorators In-Reply-To: References: <7fd737460807271126m3dbdea8cv4dbd8c9058d4faea@mail.gmail.com> Message-ID: <7fd737460807290445p3b0a017dw54566fefd46edf0b@mail.gmail.com> On Mon, Jul 28, 2008 at 11:12 AM, Gabriel Genellina wrote: > En Sun, 27 Jul 2008 15:26:39 -0300, Themistoklis Bourdenas < > tbourden at doc.ic.ac.uk> escribi?: > > > On a related note, as the actual instance method of myclass is not foo > but > > decorate(foo), why are they called method decorators? This does not > decorate > > methods, they decorate functions and eventually the decorated functions > > become methods. The name method decorator sounds a bit misleading to me. > > Where have you found it? I've always seen the expression "function > decorator" or just "decorator", not "method decorator". > well a few occurrences of it can be found in PEP 318 > > > So returning to my original question is there any way I can get the class > > inside decorate()? I guess there is not, but just asking to make sure. > > "the class inside decorate"? What do you mean? The type of the x instance > in an x.foo() call? That should be determined inside the wrapped function > -when it is actually called-. > > Yes, what I was hoping is that it might be possible to get the name of the class the function is eventually is going to be bound to, but I guess that's not very likely to be possible. I wanted the name well before the function is called, actually even before an instance of the class is created. Anyway, I 've solved my problem with other means. Just out curiosity though, has there been any talk about actual method decorators? I guess you can work around them with the introduction of class decorators or even now with meta-classes, but you have to wrap methods manually with no syntactic sugar. Cheers, Themis -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Wed Jul 2 03:32:58 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Jul 2008 07:32:58 GMT Subject: n00bie wants advice. References: <8757c630-0518-4351-a319-124ced0ac92c@w4g2000prd.googlegroups.com> Message-ID: <6d0p98F6he9U1@mid.uni-berlin.de> On Tue, 01 Jul 2008 23:25:53 -0700, bsagert wrote: > This simple script writes html color codes that can be viewed in a > browser. I used short form hex codes (fff or 000, etc) and my list > has only six hex numbers otherwise the results get rather large. I > invite criticism as to whether my code is "pythonic". You should not rebind the name `list` because it shadows the built in type of that name then. A more descriptive name would be nice anyway, i.e. `hex_digits`. And strings are iterable too, so it's a bit shorter and easier to type the digits a string. Repeatedly concatenating strings with ``+=`` might be performance problem. Python strings are immutable so this operation has to copy the involved and growing strings over and over again. Although the current CPython implementation can optimize here in some cases, the usual idiom is to use the `join()` method of strings to build a string from components in a list or iterable. Alternative implementation of your script: from __future__ import with_statement def main(): html_template = ('\n' '%s\n' '\n') header_template = '

%s

' hex_digits = '369bdf' colors = (a + b + c for a in hex_digits for b in hex_digits for c in hex_digits) html = html_template % '\n'.join(header_template % (c, c) for c in colors) with open('test.html', 'w') as html_file: html_file.write(html) if __name__ == '__main__': main() From kib2 at free.fr Sun Jul 20 09:34:12 2008 From: kib2 at free.fr (kib2) Date: Sun, 20 Jul 2008 15:34:12 +0200 Subject: Genetic programming: pygene, pygp, AST, or (gasp) Lisp? In-Reply-To: References: <7bfb3c41-b08b-49dc-9711-6e39a4667db2@b1g2000hsg.googlegroups.com> Message-ID: <48833f5b$0$20551$426a34cc@news.free.fr> David Boddie a ?crit : > On Sunday 20 July 2008 09:52, John Ladasky wrote: > >> Is there a way to interface Lisp to Python, so that I can do all the >> interface programming in the language I already know best -- and just >> do the genetic parts in Lisp? I haven't seen exception handling in >> Lisp, a feature I've come to love in Python. Since it is fairly easy >> for a randomly-generated program to generate illegal output (I already >> know this from my initial experiments in Python), I don't think I can >> live without exception handling. > > Just searching the Web for Python and Lisp yielded some interesting > projects: > > http://www.biostat.wisc.edu/~annis/creations/PyLisp/ > http://www.livelogix.net/logix/ > > I've no idea if they're really that relevant to your problem, but they > might lead somewhere useful. > > David CLPython seems also a good alternative : http://common-lisp.net/project/clpython/ From animator333 at gmail.com Mon Jul 21 10:53:19 2008 From: animator333 at gmail.com (King) Date: Mon, 21 Jul 2008 07:53:19 -0700 (PDT) Subject: Safe guard .pyc files Message-ID: After google a lot I didn't find any way to safe guard .pyc files from decompilation. One way I can think of is to wrap important functions/classes as a libraby using SWIG/PyRex, but again is going to be a lot more of work and doesn't sound good. any body out there has done something for this? From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 3 08:25:18 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 03 Jul 2008 14:25:18 +0200 Subject: Trouble using pinckle In-Reply-To: <1ijia9i.j7cls41raaazgN%pdorange@pas-de-pub-merci.mac.com> References: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> <1ijgp2r.1j1k5xwwbtiwcN%pdorange@pas-de-pub-merci.mac.com> <486ba8a4$0$11957$426a74cc@news.free.fr> <1ijia9i.j7cls41raaazgN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <486cc523$0$12000$426a74cc@news.free.fr> Pierre-Alain Dorange a ?crit : > Bruno Desthuilliers wrote: > >>> I try the staticmethod, it works fine. Very helpful. >>> >>> But i don't like it very much, it seems 'complicated' (python was >>> supposed to be simple). >> Try doing the same thing in C++ !-) > > OK ;-) > > I just ask myself what was the best method (according to python > phylosophy). I'd personnaly use either one of the existing config packages, or something like json or yaml. From enleverlesX.XmcX at XmclaveauX.com Wed Jul 2 17:14:25 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Wed, 2 Jul 2008 23:14:25 +0200 Subject: Scripting SAP GUI (Windows) In-Reply-To: References: <6d15tpFaec4U1@mid.individual.net> Message-ID: <486bf048$0$843$ba4acef3@news.orange.fr> Hi! > Linux is much better place You confuse proselitism and objectivity... @-salutations -- Michel Claveau From googler.1.webmaster at spamgourmet.com Tue Jul 22 06:51:36 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Tue, 22 Jul 2008 03:51:36 -0700 (PDT) Subject: Python Embedding Thread References: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> <87bf413d-eb98-47c0-8466-237c45fd1a0e@e53g2000hsa.googlegroups.com> <5081c3df-cb66-443b-ac71-be9661ae057d@27g2000hsf.googlegroups.com> Message-ID: Hi! I fixed the code. This code snippet runs in a seperate thread: PyObject *dict=NULL; PyGILState_STATE state = PyGILState_Ensure(); dict = CreateMyGlobalDictionary(); PyRun_String(, Py_file_input, dict, dict); ReleaseGlobalDictionary(dict); But it still does not work... :-/ From cjw at ncf.ca Fri Jul 25 18:37:54 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 25 Jul 2008 18:37:54 -0400 Subject: An Attempt to download and install traits - to a Windows XP Message-ID: Using >easy_install -v -f http://code.enthought.com/enstaller/eggs/source enthought.traits The result is: ... many lines ... copying enthought\traits\ui\tests\shell_editor_test.py -> build\lib.win32-2.5\enthought\traits\ui\tests copying enthought\traits\ui\tests\table_editor_color_test.py -> build\lib.win32-2.5\enthought\traits\ui\tests copying enthought\traits\ui\tests\table_editor_focus_bug.py -> build\lib.win32-2.5\enthought\traits\ui\tests copying enthought\traits\ui\tests\table_editor_test.py -> build\lib.win32-2.5\enthought\traits\ui\tests copying enthought\traits\ui\tests\table_editor_test2.py -> build\lib.win32-2.5\enthought\traits\ui\tests copying enthought\traits\ui\tests\table_list_editor_test.py -> build\lib.win32-2.5\enthought\traits\ui\tests copying enthought\traits\ui\tests\tree_editor_test.py -> build\lib.win32-2.5\enthought\traits\ui\tests running build_ext error: Setup script exited with error: Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. Visual Studio 2003 was not found on this system. If you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py. C:\Documents and Settings\cjw\Desktop>python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> I would welcome any guidance. Colin W. From bdesth.quelquechose at free.quelquepart.fr Mon Jul 28 07:23:56 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Jul 2008 13:23:56 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> Message-ID: <488dc843$0$15497$426a74cc@news.free.fr> Russ P. a ?crit : > On Jul 27, 3:11 pm, "Russ P." wrote: >> On Jul 27, 12:39 pm, Bruno Desthuilliers >> >> >> >> wrote: >>> Derek Martin a ?crit : >>>> On Sun, Jul 27, 2008 at 08:19:17AM +0000, Steven D'Aprano wrote: >>>>>> You take the name down to a single letter. As I suggested in an earlier >>>>>> post on this thread, why not take it down to zero letters? >>>>> The question isn't "why not", but "why". The status quo works well as it >>>>> is, even if it isn't perfect. Prove that implicit self is a good idea -- >>>>> or at least prove that it is an idea worth considering. >>>> Come on, this sounds like a schoolyard argument. This comes down to a >>>> matter of style, and as such, is impossible to prove. It's largely a >>>> question of individual preference. >>>> That said, the argument in favor is rather simple: >>>> 1. This is an extremely common idiom in Python >>>> 2. It is completely unnecessary, and the language does not suffer for >>>> making it implicit >>>> 3. Making it implicit reduces typing, reduces opportunities for >>>> mistakes, and arguably increases consistency. >>> "arguably", indeed, cf below. >>>> As for the latter part of #3, self (or some other variable) is >>>> required in the parameter list of object methods, >>> It's actually the parameter list of the *function* that is used as the >>> implementation of a method. Not quite the same thing. And then, >>> consistency mandates that the target object of the method is part of the >>> parameter list of the *function*, since that's how you make objects >>> availables to a function. >>>> however when the >>>> method is *called*, it is omitted. >>> Certainly not. You need to lookup the corresponding attribute *on a >>> given object* to get the method. Whether you write >>> some_object.some_method() >>> or >>> some_function(some_object) >>> you still need to explicitely mention some_object. >>>> It is implied, supplied by Python. >>> Neither. The target object is passed to the function by the method >>> object, which is itself returned by the __get__ method of function >>> objects, which is one possible application of the more general >>> descriptor protocol (the same protocol that is used for computed >>> attributes). IOW, there's nothing specific to 'methods' here, just the >>> use of two general features (functions and the descriptor protocol). >>> FWIW, you can write your own callable, and write it so it behave just >>> like a function here: >>> import types >>> class MyCallable(object): >>> def __call__(self, obj): >>> print "calling %s with %s" % (self, obj) >>> def __get__(self, instance, cls): >>> return types.MethodType(self.__call__, instance, cls) >>> class Foo(object): >>> bar = MyCallable() >>> print Foo.bar >>> f = Foo() >>> f.bar() >>>> Thus when an object method is called, it must be called with one fewer >>>> arguments than those which are defined. This can be confusing, >>>> especially to new programmers. >>> This is confusing as long as you insist on saying that what you >>> "def"ined is a method - which is not the case. >>>> It can also be argued that it makes the code less ugly, though again, >>>> that's a matter of preference. >>>>> It's not enough to show that a change "isn't bad" -- you have to show >>>>> that it is actively good. >>>> But he did... he pointed out that *it saves work*, without actually >>>> being bad. Benefit, without drawback. Sounds good to me! >>>>> "Don't need to look at the method signature" is not an argument in favour >>>>> of implicit self. >>>> Yes, actually, it is. >>> It isn't, since there's no "method signature" to look at !-) >>>> If there is a well-defined feature of Python >>>> which provides access to the object within itself, >>> The point is that you don't get access to the object "within itself". >>> You get access to an object *within a function*. >>> The fact that a function is defined within a class statement doesn't >>> imply any "magic", it just creates a function object, bind it to a name, >>> and make that object an attribute of the class. You have the very same >>> result by defining the function outside the class statement and binding >>> it within the class statement, by defining the function outside the >>> class and binding it to the class outside the class statement, by >>> binding the name to a lambda within the class statement etc... >>>> then the >>>> opportunities for mistakes when someone decides to use something else >>>> are lessened. >>>>> You don't need to look at the method signature when you're using an >>>>> explicit self either. >>>> That isn't necessarily true. If you're using someone else's code, and >>>> they didn't use "self" -- or worse yet, if they chose this variable's >>>> name randomly throughout their classes -- then you may well need to >>>> look back to see what was used. >>>> It's bad programming, but the world is full of bad programmers, and we >>>> don't always have the choice not to use their code. Isn't one of >>>> Python's goals to minimize opportunities for bad programming? >>> Nope. That's Java's goal. Python's goals are to maximize opportunities >>> for good programming, which is quite different. >>>> Providing a keyword equivalent to self and removing the need to name >>>> it in object methods is one way to do that. >>> It's also a way to make Python more complicated than it needs to be. At >>> least with the current state, you define your functions the same way >>> regardless of how they are defined, and the implementation is >>> (relatively) easy to explain. Special-casing functions definition that >>> happens within a class statement would only introduce a special case. >>> Then you'd have to explain why you need to specify the target object in >>> the function's parameters when the function is defined outside the class >>> but not when it's defined within the class. >>> IOW : there's one arguably good reason to drop the target object from >>> functions used as methods implementation, which is to make Python looks >>> more like Java, and there's at least two good reason to keep it the way >>> it is, which are simplicity (no special case) and consistency (no >>> special case). >>> Anyway, the BDFL has the final word, and it looks like he's not going to >>> change anything here - but anyone is free to propose a PEP, isn't it ? >> The issue here has nothing to do with the inner workings of the Python >> interpreter. The issue is whether an arbitrary name such as "self" >> needs to be supplied by the programmer. >> >> Neither I nor the person to whom you replied to here (as far as I can >> tell) is suggesting that Python adopt the syntax of Java or C++, in >> which member data or functions can be accessed the same as local >> variables. Any suggestion otherwise is a red herring. >> >> All I am suggesting is that the programmer have the option of >> replacing "self.member" with simply ".member", since the word "self" >> is arbitrary and unnecessary. Otherwise, everything would work >> *EXACTLY* the same as it does now. This would be a shallow syntactical >> change with no effect on the inner workings of Python, but it could >> significantly unclutter code in many instances. >> >> The fact that you seem to think it would change the inner functioning >> of Python just shows that you don't understand the proposal. > > It just occurred to me that Python could allow the ".member" access > regardless of the name supplied in the argument list: > > class Whatever: > > def fun(self, cat): > > .cat = cat > self.cat += 1 > > This allows the programmer to use ".cat" and "self.cat" > interchangeably. If the programmer intends to use only the ".cat" > form, the first argument becomes arbitrary. Allowing him to use an > empty argument or "." would simply tell the reader of the code that > the ".cat" form will be used exclusively. > > When I write a function in which a data member Python has nothing like "data member" (nor "member function" etc). It has class attributes and instance attributes, period. *Python is not C++*. So please stop using C++ terms which have nothing to do with Python's object model. > will be used several > times, I usually do something like this: > > data = self.data > > so I can avoid the clutter of repeated use of "self.data". If I could > just use ".data", I could avoid most of the clutter without the extra > line of code renaming the data member. The main reason to alias an attribute is to avoid the overhead of attribute lookup. > A bonus is that it becomes > clearer at the point of usage that ".data" is member data rather than > a local variable. I totally disagree. The dot character is less obvious than the 'self.' sequence, so your proposition is bad at least wrt/ readability (it's IMHO bad for other reasons too but I won't continue beating that poor dead horse...) From alan.franzoni.blahblah at example.com.invalid Wed Jul 30 15:32:04 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Wed, 30 Jul 2008 19:32:04 GMT Subject: undo a dictionary References: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> <192b4786-85b2-43d3-bb7c-b5716068ff12@56g2000hsm.googlegroups.com> Message-ID: <5kcky4amfzdf.tw6k5ru36ohn.dlg@40tude.net> mmm was kind enough to say: > My desire is to take a set of data items in an alpha-numeric range and > oput them into a dictionary > > i.e., > x1=1 > x2=20 > x3=33 > > to yield the dictionary > > { 'x1':1, 'x2':20, 'x3':33 } > > without having to type in as above but instead invoke a function > > maybe with syntax of > > dd=make_dict('x1--x99') you'll need to pass the locals() or globals() manually. Can't be done (cleanly) otherwise. Check the following code: import re x1=1 x2=20 x3=30 q6=40 def make_dict(regex, nsmapping): output_dict = {} compiled_regex = re.compile(regex) for key, value in nsmapping.items(): if compiled_regex.match(key): output_dict[key] = value return output_dict d = make_dict("x[123]", locals()) print d -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From marcus at internetnowasp.net Sat Jul 12 22:43:29 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Sun, 13 Jul 2008 10:43:29 +0800 Subject: Why is there no GUI-tools like this for Windows? In-Reply-To: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> References: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> Message-ID: <48796BD1.9030406@internetnowasp.net> Hi, Coming from a windows world i could understand this. For GUI, there is nothing near the power of the Visual Studio, this is especially true since C#. So python for me is for anything except GUI. It becomes self rejecting notion to do GUI in python when you type in those stuff that could have been handled by an IDE, thus for linux project i just do the web interface + php and let python do all the other hard core work. But looking at the video, i think if they could do this for ruby, then the python community should be able to come out with a similar one. There is something called BOA i read somewhere but its having some kind of compatibility problem with newer versions of wxpyhon. (;-) i didnt really manage to see that video it took forever to load, but the comments gave enuf hints). Marcus. maestro wrote: > http://www.youtube.com/watch?v=PXpwC1o5AcI > > I have done some GUI-programming for windows with Python but the > Tkinter interface sucked and while it is the only one I tried I got > the impression they are all the same. > > It's amazing how retarded a lot of the stuff programmers do is. > Watcing that video, that is how it should be. > > I can just do the layout with my mouse and then there is a program > that writes the code for me. > GUI-programming is hard for no reason. One good program then forever > easy... > > Is there not something like this for Python/Windows? Is the Linux one > only for ruby or for any language? > > Oh well im switching to Linux anyway and mostly write webapps but > still... > -- > http://mail.python.org/mailman/listinfo/python-list > > From laredotornado at zipmail.com Wed Jul 30 13:43:11 2008 From: laredotornado at zipmail.com (laredotornado) Date: Wed, 30 Jul 2008 10:43:11 -0700 (PDT) Subject: Syntax error in my script References: Message-ID: <85a24d4f-aa04-416b-833b-44ca85c979a2@d1g2000hsg.googlegroups.com> On Jul 30, 11:26?am, Alan Franzoni wrote: > laredotornadowas kind enough to say: > > [cut] > > Indentation counts in Python. You're probably doing something wrong with > whitespace/tab/carriage return. > > -- > Alan Franzoni > - > Remove .xyz from my email in order to contact me. > - > GPG Key Fingerprint: > 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E That was it. Thanks, - From googler.1.webmaster at spamgourmet.com Mon Jul 21 12:35:53 2008 From: googler.1.webmaster at spamgourmet.com (googler.1.webmaster at spamgourmet.com) Date: Mon, 21 Jul 2008 09:35:53 -0700 (PDT) Subject: Python Embedding Thread References: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> Message-ID: Does anyone has a tip? From mail at timgolden.me.uk Wed Jul 9 10:18:39 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 09 Jul 2008 15:18:39 +0100 Subject: Allow tab completion when inputing filepath? In-Reply-To: References: Message-ID: <4874C8BF.7060108@timgolden.me.uk> Keith Hughitt wrote: > I've been looking around on the web for a way to do this, but so far > have not come across anything for this particular application. I have > found some ways to enable tab completion for program-related commands, > but not for system filepaths. This would be nice to have when > prompting the user to enter a file/directory location. What platform are you on? And what kind of display? (Console / GUI / wxPython / Qt / Web...) TJG From nick at craig-wood.com Tue Jul 1 16:46:50 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 01 Jul 2008 15:46:50 -0500 Subject: Why is recursion so slow? References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Message-ID: Luis Zarrabeitia wrote: > > is that what lazy evaluation in functional languages avoids thus > > making recursive versions much faster? > > Not exactly... Functional languages are (or should be) optimized for recursion, > but if the algorithm you write is still exponential, it will still > take a long time. Actually I think functional language are likely to perform memoization. By definition any function in a functional language will always produce the same result if given the same arguments, so you can memoize any function. See here for a python memoize which makes the recursive algorithm run fast... http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201 -- Nick Craig-Wood -- http://www.craig-wood.com/nick From lepto.python at gmail.com Mon Jul 14 22:47:52 2008 From: lepto.python at gmail.com (oyster) Date: Tue, 15 Jul 2008 10:47:52 +0800 Subject: a module.pth question Message-ID: <6a4f17690807141947n1e052c6dj436702f70ac1fda0@mail.gmail.com> there are 2 reasons: 1. I use both py24 and py25, I don't like to install 2 copies of pyglet, which is a pure python module and can be used by py24/25 at the same time, thus I am not willing to put a module under site-packages, instead I use a separate directory(h:\pure_pylib in my case) 2. I also carry python on my U-disk, as you know the driver letter assigned to it is not always same. so I can't use full path name > ---------- ????? ---------- > From: Mike Driscoll > To: python-list at python.org > Date: Mon, 14 Jul 2008 06:12:25 -0700 (PDT) > Subject: Re: a module.pth question > On Jul 14, 6:26 am, oyster wrote: > > My py24 is installed in h:\python24 > > I installed pyglet(http://pyglet.org/) in > > H:\pure_pylib\Multimedia\pyglet-1.0\, if I do > > [code]>>> import sys > > >>> > sys.path.append(r'H:\pure_pylib\Multimedia\pyglet-1.0') > > >>> import pyglet > > > > [/code] > > it is ok. > > > > but if I created h:\pure_pylib\pyglet.pth file, which containts > > [code] > > Multimedia\pyglet-1.0 > > [/code] > > > > then > > [code]>>> import sys > > >>> sys.path.append(r'h:\pure_pylib') > > >>> import pyglet > > > > Traceback (most recent call last): > > File "", line 1, in ? > > ImportError: No module named pyglet > > > > [/code] > > > > what is wrong with it? and How to fix it? thanks in advance > > I looked in my easy_install.pth and it looks like it should be: > > .\Multimedia\pyglet-1.0 > > But I don't really see any reason not to do it the way you were > earlier with the full path name. Besides, you should be able to > install pyglet to your site-packages folder. Or you could use buildout > if you're just testing modules and you don't want to screw up your > namespace. > > Mike From wuwei23 at gmail.com Fri Jul 25 06:52:56 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 25 Jul 2008 03:52:56 -0700 (PDT) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> Message-ID: On Jul 25, 7:57?pm, Suresh Pillai wrote: > The nodes in my network may be ON or OFF. ?The network starts off with > all nodes in the OFF state. ?I loop through the nodes. ?For each node > that is OFF, I consider some probability of it turning ON based on the > states of its neighbours. ?I MUST GO THROUGH ALL NODES BEFORE DECIDING > WHICH ONES TO TURN ON. > > So my question is whether it is faster to > > 1. loop through a list of ALL nodes and check for OFF nodes using ifs I'd recommend using 'filter' and list comprehensions. >>> import random >>> class Node: ... def __init__(self): ... self.on = False ... def toggle(self): ... self.on = random.choice([True, False]) ... >>> nodes = [Node() for i in range(0, 10000)] >>> for node in nodes: ... node.toggle() ... >>> off_nodes = filter(lambda x: not x.on, nodes) >>> len(off_nodes) 5050 From yuwenwu001 at gmail.com Thu Jul 24 11:00:23 2008 From: yuwenwu001 at gmail.com (kjldf) Date: Thu, 24 Jul 2008 08:00:23 -0700 (PDT) Subject: adidas adicolor shoes PayPal Message-ID: <46e6ef6f-5b18-4e0c-8f0f-c9a2d4351630@p10g2000prf.googlegroups.com> adidas adicolor shoes PayPal We export our brand shoes all over world because of our competitive price, good quality products and good service. All our products are guaranteed to be a minimum of AAA+ quality. Our price and good service are often appreciated by our customers. So we can get repeat order to sustain our development. Your support of our business is very thankful. Dear friend welcome to shopping on www.electronic-paypal.cn 1.5% paypal handling charge supports the online payment! 2.Use your intergla replacement more good gift! 3.notes by email and website of deliver each package at first time. From maheha845 at gmail.com Wed Jul 2 11:11:15 2008 From: maheha845 at gmail.com (maheha845 at gmail.com) Date: Wed, 2 Jul 2008 08:11:15 -0700 (PDT) Subject: internatinal jobs in USA free submet your resume Message-ID: Success usually comes to those who are too busy to be looking for it Visit Mobiles & Computers?, http://www.mobilecomputers4all.blogspot.com/
Hi..Click me

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi..Click me

From ggpolo at gmail.com Wed Jul 2 09:15:14 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 2 Jul 2008 10:15:14 -0300 Subject: dynamically load from module import xxx In-Reply-To: References: Message-ID: On Tue, Jul 1, 2008 at 1:46 PM, Gary Duzan wrote: > In article , > Neal Becker wrote: >>What is a good way to emulate: >> >>from module import xxx >>where 'module' is a dynamically generated string? >> >>__import__ ('modulename', fromlist=['xxx']) >> >>seems to be what I want, but then it seems 'xxx' is not placed in globals() >>(which makes me wonder, what exactly did fromlist do?) > > You might want to read what "help(__import__)" tells you. It > sounds like what you want is: But have you read it yourself ? > > mynamespace['xxx'] = __import__('modulename.xxx', fromlist=['xxx']) Only if modulename is actually a package, which doesn't really make sense for a "modulename". Also, fromlist doesn't need to be ['xxx'] if you want to import the submodule 'xxx' from the, now supposed, 'modulename' package, it could be anything that is not an empty list. > > Seems a bit weird to me, but that's the way it is, and I'm sure > there is a reason for it. > > Good luck. > > Gary Duzan > Motorola H&NM > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From basti.wiesner at gmx.net Tue Jul 15 12:47:06 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Tue, 15 Jul 2008 18:47:06 +0200 Subject: fork after creating temporary file using NamedTemporaryFile References: <0435315d-7b7d-4587-bc8c-000e3f2644a2@z72g2000hsb.googlegroups.com> Message-ID: rparimi at gmail.com : > When I create temporary file using the tempfile module, and forkI) > later on in my program, I always see errors when the program exits. Is > this because the child process deletes temp file? > Here's a stripped down version of my script that exhibits this > problem: > > #!/usr/bin/python > > import os > import tempfile > import sys > > cmd = [] > cmd.append('/bin/ls') > cmd.append('-l') > cmd.append('/tmp') > > foo = tempfile.NamedTemporaryFile(mode='w+b') > > pid = os.fork() > if pid: > print 'I am parent' > else: > print 'I am child' > sys.exit(0) > > $ python sub.py > I am child > I am parent > Exception exceptions.OSError: (2, 'No such file or directory', '/tmp/ > tmp-mZTPq') in file '', mode 'w+b' at 0xb7d2a578>> ignored NamedTemporaryFile attempts to delete the file, when "close" is invoked (which is done by the destructor in this case, because you're senselessly not closing that file explicitly). A "fork()" clones the whole process memory, after fork() is done, there are *two* NamedTemporaryFile objects, pointing to the *same* file, existing in two separate process (one in the parent, the other, cloned one, in the child). When the first process exists, the file is removed cleanly, the second process can't remove anything anymore, since there's nothing left to remove. Since the order of process execution is not deterministic and completely up to the systems scheduler, you can *never* say, which one will exit first. You should replace NamedTempraryFile with "mkstemp" and take care of deletion yourself. You could for instance call "os.wait" to wait for the child's termination in the parent process and thus delete the temporary file, once the child has gone. Of course, you could also catch the exception, if you properly close the file object (what you should be doing anyway!), but I'd consider this a not very robust solution. If one of the two processes exit unexpectedly early, the directory entry is gone, though it might still be needed by the parent process. > How can these warnings be avoided? I tried to catch this exception > using try/except but it didn't work. If you want to catch that exception, you should properly close the named temporary file and wrap the "close" call inside a try-except statement. Beginning with Python 2.5 you might also want to use the with-statement here. Relying on the destructor is *always* a bad idea, you should always close files explicitly! -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From asma61 at dsl.pipex.com Sun Jul 27 12:18:22 2008 From: asma61 at dsl.pipex.com (DaveM) Date: Sun, 27 Jul 2008 17:18:22 +0100 Subject: Rant (was Re: x*x if x>10 References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3g8rF9gfj0U1@mid.uni-berlin.de> <6f3gmaF9moqsU1@mid.uni-berlin.de> Message-ID: <1q5p845o2j9htp6vf44u6nqinucsr1numf@4ax.com> On Sun, 27 Jul 2008 16:57:14 +0200, "Diez B. Roggisch" wrote: >Marc 'BlackJack' Rintsch schrieb: >> On Sun, 27 Jul 2008 16:41:19 +0200, Diez B. Roggisch wrote: >> >>> DaveM schrieb: >>>> Getting back to the list concatenation, I finally found the itertools.chain >>>> command which is the most compact and fastest (or second fastest by a >>>> trivial amount, I can't remember which). Along the way, I must have >>>> tried/used half a dozen methods, ...which brings me back my initial PERL >>>> comment. There's more than one way to do it in Python, too. >>> But I *do* know that taking the python zen literally is fruitless. >> I think it should be taken more literally than the wrong reduction to >> "there should be only one way". People tend to forget "obvious" and >> "preferably" all the time. >Good point. The OP found the obvious way of extending. I wonder what his >reasons were to abandon it. You'll have guessed, I'm sure, that I'm not a professional programmer. This was the third rewrite of a program to match candidate groups to examiners on a three day course I run, necessitated on this occasion by a change in the structure of the course. I originally learnt python as I wrote, and some of the early code was ugly and verbose, so once the current rewrite was working I took the opportunity to tidy the code up and document it (yes, I know, but as I said, I'm an amateur). The list concatenation was an itch I couldn't scratch: temp = [] for value in sessexam.values(): temp.extend(value) c_exam = [name for name in set(temp)] #See what I mean about verbose? c_exam.sort() return c_exam Six lines just didn't feel like it ought to be the best way to do something so simple. I liked the attempt below better, but was foolish enough to time it, so that was the end of that. return sorted(list(set(reduce(lambda x, y: x+y, sessexam.values())))) The current version (below) is a compromise, but I still feel there _ought_ to be a simple one word command to join multiple lists. a = list(set(itertools.chain(*sessexam.values()))) a.sort() #As I write I'm wondering if I really need it sorted. Hmm... return a DaveM From metaperl at gmail.com Tue Jul 15 21:12:33 2008 From: metaperl at gmail.com (E. J. Gold is the Hi-Tech Shaman) Date: Tue, 15 Jul 2008 18:12:33 -0700 (PDT) Subject: graphing lifelines References: Message-ID: On Jul 15, 3:38?pm, Larry Bates wrote: > > Certainly a "Hi-Tech Shaman" can whip something up to do this, right? > Yes, well E.J. Gold is the Hi-Tech Shaman. I'm Terrence Brannon, stating that fact :) So, maybe EJ could whip up such a thing :) I like the sci.math answer I got the best and will go with that approach - http://groups.google.com/group/sci.math/browse_thread/thread/09b254718d4cbfeb# From tjreedy at udel.edu Wed Jul 2 04:27:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 02 Jul 2008 04:27:15 -0400 Subject: Problem with a for loop and a list In-Reply-To: <18232298.post@talk.nabble.com> References: <18232298.post@talk.nabble.com> Message-ID: Alexnb wrote: > I am not sure what is going on here. Here is the code that is being run: > > def getWords(self): > self.n=0 > for entry in self.listBuffer: > self.wordList[self.n] = entry.get() And what does self.wordList begin as? If {}, then the assignemt is invalid. Perhaps you want self.wordList.append(entry.get()) > self.n=self.n+1 Is this supposed to be incremented once per entry or once per getWords()? If the former, you would overwrite previous assignment (if it worked) for every item except the last. From gagsl-py2 at yahoo.com.ar Wed Jul 30 00:06:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 01:06:08 -0300 Subject: method decorators and more on decorators References: <7fd737460807271126m3dbdea8cv4dbd8c9058d4faea@mail.gmail.com> <7fd737460807290445p3b0a017dw54566fefd46edf0b@mail.gmail.com> Message-ID: En Tue, 29 Jul 2008 08:45:02 -0300, Themis Bourdenas escribi?: > On Mon, Jul 28, 2008 at 11:12 AM, Gabriel Genellina > wrote: > >> En Sun, 27 Jul 2008 15:26:39 -0300, Themistoklis Bourdenas < >> tbourden at doc.ic.ac.uk> escribi?: >> >> > On a related note, as the actual instance method of myclass is not foo >> but >> > decorate(foo), why are they called method decorators? This does not >> decorate >> > methods, they decorate functions and eventually the decorated >> functions >> > become methods. The name method decorator sounds a bit misleading to >> me. >> >> Where have you found it? I've always seen the expression "function >> decorator" or just "decorator", not "method decorator". > > well a few occurrences of it can be found in PEP 318 In a very strict sense, I'd say that all those references to "method decorators" are wrong - because those "def" statements inside a "class" statement define functions, not methods. In that sense almost every Python programmer is wrong too: in this example class X: @decorator def foo(self): pass most (if not all) people would refer to "foo" as "the foo method in class X" - even if foo is really a function, not a method. So a less restrictive meaning is usually adopted - and we all consider "foo" a method, and we're all happy... except in your case, when you just hit a point where the distinction is relevant. Perhaps a more careful wording in the PEP would help in those corner cases. >> > So returning to my original question is there any way I can get the >> class >> > inside decorate()? I guess there is not, but just asking to make sure. >> >> "the class inside decorate"? What do you mean? The type of the x >> instance >> in an x.foo() call? That should be determined inside the wrapped >> function >> -when it is actually called-. >> >> Yes, what I was hoping is that it might be possible to get the name of >> the > class the function is eventually is going to be bound to, but I guess > that's > not very likely to be possible. I wanted the name well before the > function > is called, actually even before an instance of the class is created. No, I think it's not possible - not using a function decorator, because when it is applied, the class doesn't exist yet. You might use a metaclass (or a class decorator, available on 2.6 and 3.0); iterate over the dictionary of the class about to be created and process their functions in any way you like. > Anyway, > I 've solved my problem with other means. Just out curiosity though, has > there been any talk about actual method decorators? I guess you can work > around them with the introduction of class decorators or even now with > meta-classes, but you have to wrap methods manually with no syntactic > sugar. Mmm... methods are ephemeral objects, once the call is completed, the method usually gets destroyed, so I don't think a true "method decorator" would be very useful. If you really want to customize a method, since they are created by the function type's __get__, a crazy idea would be to inherit from the function type and return something different in its __get__ - but I've never done something like that and don't even know if it's possible at all... -- Gabriel Genellina From ppearson at nowhere.invalid Wed Jul 16 14:24:04 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 16 Jul 2008 18:24:04 GMT Subject: bad recursion, still works References: <20cba7ab-72d2-4c7b-8f3f-48f39eaf9625@m3g2000hsc.googlegroups.com> Message-ID: <6e6sm3F5mk28U1@mid.individual.net> On Wed, 16 Jul 2008 15:20:23 +0200, Fredrik Lundh wrote: [snip] > Hope this helps more than it confuses. Absolutely. It is wonderfully enlightening. Many thanks. -- To email me, substitute nowhere->spamcop, invalid->net. From james at reggieband.com Thu Jul 10 13:35:32 2008 From: james at reggieband.com (James Fassett) Date: Thu, 10 Jul 2008 10:35:32 -0700 (PDT) Subject: Idiomatic Python to convert list to dict References: <7ec9405c-4e6f-491d-84b2-c81152302b13@79g2000hsk.googlegroups.com> <6dmuacF33kciU1@mid.uni-berlin.de> Message-ID: <9c057b7c-4cfb-49ea-9b80-d24df810d6a8@b1g2000hsg.googlegroups.com> On Jul 10, 6:13?pm, "Diez B. Roggisch" wrote: > > my_list = ['a', 'b', 'c', 'd', 'e'] > > dup_map = {} > > for item in my_list: > > ? ? dup_map[item] = True > > > # ... sometime later > > > for complex_dict in large_list: > > ? ? if complex_dict["char"] not in dup_map: > > ? ? ? ? my_list.append(complex_dict["char"]) > > ? ? ? ? dup_map[complex_dict["char"]] = True > > Instead of a dict, use a set. It's immediatly contructable from my_list, > and better suited for the task anyway. Cheers, I rewrote it similar to: dup_map = set(['a', 'b', 'c', 'd', 'e']) # ... sometime later for complex_dict in large_list: dup_map.add(complex_dict["char"]) my_list = list(dup_map) That is a little nicer. Thanks again, James. From m.liu.jin at gmail.com Fri Jul 18 02:58:38 2008 From: m.liu.jin at gmail.com (m.liu.jin at gmail.com) Date: Thu, 17 Jul 2008 23:58:38 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> Message-ID: On Jul 18, 2:31?pm, castironpi wrote: > Given that, what does that column indicate? Offset. From paddy3118 at googlemail.com Wed Jul 30 03:06:43 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 30 Jul 2008 00:06:43 -0700 (PDT) Subject: Native Code vs. Python code for modules References: Message-ID: On Jul 30, 4:56?am, koblas wrote: > Ruby has been getting pummeled for the last year or more on the > performance subject. ?They've been working hard at improving it. ?From > my arm chair perspective Python is sitting on it's laurels and not > taking this as seriously as it probably should. I personally DON'T think that the developers should be chasing down every micro-benchmark. Someone has to look-up and see the bigger picture. If you take a look at a larger set of micro benchmarks, then Ruby is below par when compared to Python and Perl on speed. I had the misfortune to read their development group entries when a critical bug was 'fixed' by a release from Japan that didn't have enough testing and so think the Ruby development 'group' have problems of quality that they also need to address. (And are doing I think by adding to their test-suite). PyPy and previous tools like Psyco are ways in which Python developers are continuing to see above the eternal grind of micro- optimising the C-interpreter to try and give us tools that can approach compiled language speeds from the language we love. I like to think of it as working smarter rather than harder - the brains a much better muscle :-) - Paddy. From hat at se-162.se.wtb.tue.nl Wed Jul 2 03:43:48 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 02 Jul 2008 09:43:48 +0200 Subject: Required items in a form References: <45yak.331$Ae3.313@trnddc05> Message-ID: On 2008-07-01, Brandon wrote: > What I'm trying to do is essentially force a user to fill in required items > in a form, which will be saved to a database. How can I get it so that once > the user clicks "OK" on the dialog box, it transfers control back to the > form, and not save the empty fields into the database? Follow the golden rule of not trusting user input. When you get back values for the fields, check them, and if not correct, ask again, give an error, abort the program, erase the data base, reboot the system, whatever is appropiate to handle such an error. Sincerely Albert From durand1 at gmail.com Sat Jul 19 15:09:56 2008 From: durand1 at gmail.com (Durand) Date: Sat, 19 Jul 2008 20:09:56 +0100 Subject: matplotlib: Plotting a graph against time Message-ID: Hi, I'm trying to plot a simple graph against date or time using matplotlib. I've read about date_plot but I'm not really sure how to use it. At the moment, I have some data arranged into lists, where list1 contains x values (time) and list2 contains y values just like is needed for the normal plot function. The time values are simply the output of datetime.date.today(), etc which I don't mind changing the format of. My question is, how do I plot the graph with list1 on the x axis and list2 on the y axis. Using plot and unixtime I get a very ugly scale as is to be expected so I want to know how to use the date_plot function efficiently. At the moment, I'm only concerned about the actual plotting but help with Locater Ticks (Months and Years) is also very appreciated. Thanks a lot! From marc.wyburn at googlemail.com Wed Jul 30 11:39:43 2008 From: marc.wyburn at googlemail.com (marc wyburn) Date: Wed, 30 Jul 2008 08:39:43 -0700 (PDT) Subject: variable expansion with sqlite References: <489059DC.5090501@timgolden.me.uk> Message-ID: Hi and thanks, I was hoping to avoid having to weld qmarks together but I guess that's why people use things like SQL alchemy instead. It's a good lesson anyway. Thanks, Marc. On Jul 30, 2:24?pm, Tim Golden wrote: > Gerhard H?ring wrote: > > My code would probably look very similar. Btw you don't need to use > > list() on an iterable to pass to executemany(). pysqlite's executemany() > > accepts anything iterable (so generators work fine, too). > > Thanks for that. My finger-memory told me to do that, possibly > because some *other* dbapi interface only accepts lists. Can't > quite remember. I'm usually all in favour of non-crystallised > iterators. > > > Also, with SQLite you can just skip data type definitions like > > VARCHAR(200). They're ignored anyway. > > Heh. Once again, finger memory forced me to put *something* > in there. I've been developing Enterprise databases for too > long :) > > TJG From pranny at gmail.com Fri Jul 11 00:34:07 2008 From: pranny at gmail.com (pranav) Date: Thu, 10 Jul 2008 21:34:07 -0700 (PDT) Subject: Bypassing WebFilter security Message-ID: <563968a1-3cc3-4009-beca-d5d367d4ccff@k13g2000hse.googlegroups.com> Hello everyone, I am working in an organization, which is using a very strict webcontent filter management suite. Due to this i am unable to download any exe file, or surf web (even the necessary downloads from sourceforgenet are blocked). I was wondering, if python could be of any help. Say i have a python script, and i pass the URL of downloadable file, and it just downloads the file for me. From daisha52014 at gmail.com Fri Jul 25 05:49:14 2008 From: daisha52014 at gmail.com (wholesale) Date: Fri, 25 Jul 2008 02:49:14 -0700 (PDT) Subject: sell shoes jeans t-shirt sunglasses swimsuit parda air jordan Message-ID: www.yahoo808.cn Your satisfactions,Our pursuit! From howe.steven at gmail.com Thu Jul 17 16:04:16 2008 From: howe.steven at gmail.com (Steven Howe) Date: Thu, 17 Jul 2008 13:04:16 -0700 Subject: % sign in python? In-Reply-To: References: Message-ID: <487FA5C0.30206@gmail.com> Terry Reedy wrote: > > > korean_dave wrote: >> What does this operator do? Specifically in this context >> >> test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) >> >> (Tried googling and searching, but the "%" gets interpreted as an >> operation and distorts the search results) > > Having seen a number of comments like this over the years (about the > difficulty of searching for symbol meanings), I just started, last > night, a symbol index listing nearly all Python syntax uses of > non-alpha-or-digit ascii symbols. When I finish and upload it > somewhere, I will post an announcement with the link. > > tjr > > -- > http://mail.python.org/mailman/listinfo/python-list > I thought, in this contexted, it was mapping operator. sph From asd at pittle.org Thu Jul 3 16:15:51 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Thu, 3 Jul 2008 13:15:51 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> <9cdbb215-d427-4694-a455-f2571ad42390@x19g2000prg.googlegroups.com> <54e0e7c5-113e-4296-a62f-e649d6ffa2d6@z66g2000hsc.googlegroups.com> Message-ID: <87b10cf3-4fd4-46e3-a33a-528f1180f69a@s21g2000prm.googlegroups.com> On Jul 3, 7:42?pm, Fuzzyman wrote: > On Jun 30, 11:25?pm, Ali Servet D?nmez wrote: > > > > > On Jul 1, 12:15?am, Fuzzyman wrote: > > > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > > I don't want to be so mean here, but how hard it could be be writing a > > > > freesoftware which would automatically/intelligently auto complete > > > > Python code? (I mean something that really does the job, like > > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > > name it, but just don't give me PyDev please...) > > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > > missing here? > > > > > Could someone please point me out something that I'm really missing > > > > which is already present in the wild, otherwise I'd like discuss with > > > > whoever is willing to help me to get this thing done. I made my mind > > > > and I could volunteer to make this happen as thesis project for my > > > > incoming graduation in the next year. > > > > > Regards you all, > > > > Ali Servet D?nmez > > > > Vim, Emacs, Wing, Komodo, ... more? > > > > Yeah, I guess you're missing something. :-) > > > > MichaelFoordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > > I probabily am... Could you please kindly tell me what's the way to > > get it work for Emacs? > > Not personally I'm afraid. Although I did use Emacs today for the > first time (pairing with a colleague who inflicted it upon me). We did > have code completion working fine, but I have no idea how to set it up > (maybe the intarwebz can help?). > > Michael Foord > --http://www.ironpythoninaction.com/http://www.trypython.org/ I tried code come completion options in Emacs for Python, but none of them was satisfactory to me. I'd be glad to hear how did your friend get it work though. From paul at boddie.org.uk Sat Jul 26 14:15:10 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 26 Jul 2008 11:15:10 -0700 (PDT) Subject: Questions on 64 bit versions of Python References: <1216966424.4685.1265275245@webmail.messagingengine.com> Message-ID: On 25 Jul, 12:35, "M.-A. Lemburg" wrote: > > But then Intel Itanium is being phased out anyway Citation needed! ;-) Paul From rotlaus at gmail.com Tue Jul 8 06:59:32 2008 From: rotlaus at gmail.com (Andre Adrian) Date: Tue, 8 Jul 2008 10:59:32 +0000 (UTC) Subject: extended setattr() References: <6dgfprF2ekq3U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch nospam.web.de> writes: > > def ext_setattr(obj, attr, val): > > for subattr in attr.split("."): > > obj = getattr(obj, subattr) > > obj = val > > > >>>> import test > >>>> a = A() > > Traceback (most recent call last): > > File "", line 1, in > > NameError: name 'A' is not defined > >>>> a = test.A() > >>>> a.B.C.txt > > 'foo' > >>>> ext_setattr(a, 'B.C.txt', 'bar') > >>>> a.B.C.txt > > 'foo' > > > > What am i doing wrong? > > obj = val won't work. Why is this so? Shouldn't it be the same? > You need to use a setattr(obj, name, val) > on the last attribute-name. Ok, so this works: def ext_setattr(obj, attr, val): attributes = attr.split('.') for subattr in attributes[:-1]: obj = getattr(obj, subattr) setattr(obj, attributes[-1], val) From jeff.dyke at gmail.com Mon Jul 21 09:56:03 2008 From: jeff.dyke at gmail.com (Jeff Dyke) Date: Mon, 21 Jul 2008 09:56:03 -0400 Subject: imported module no longer available Message-ID: <8496caf30807210656y3d8467eer83a953e7c37e556c@mail.gmail.com> I've come across an error that i'm not yet able to create a test case for but wanted to get see if someone could shed light on this. I have imported a module at the top of my file with import mymodulename this module is used many times in the current file successfully, but then I attempt to use it one more time and get: UnboundLocalError: local variable 'mymodulename' referenced before assignment if i add `print globals().keys()` right before the line where the error occurs l see the module in the list (actual output, names changed to protect the innocent) ['HPADao', 'RDao', 'DriverBase', 'FKSUtility', 'PMDao', 'mymodulename', 'IDriver', 'DriverTrack', 'HPPDao', 'setLogName', 'HPDao', 'iparser', '__builtins__', '__file__', 'driver', '_LOGNAME', 'sys', 'IClient', '__name__', 'copy', 'types', 'logging', 'iloader', 'HPADao', '__doc__', 'PMDao', 'time', 'FormatLoad'] Traceback (most recent call last): File "testunbound.py", line 475, in driver.getRData('0605', 22528) File "testunbound.py", line 256, in getRData print mymodulename the code that generates these two lines is: print globals().keys() print mymodulename I can solve this by placing import mymodulename again in this method, but can't have that everywhere. I will try to come up with a generic reproduction of this issue, but that might take some time. I've also seen this in the past with the python builtin 'sys' I did see a bug http://bugs.python.org/issue2378, which has very similar behaviour, but is different. Python 2.5, ubuntu hardy Thanks for any insight, Jeff From norseman at hughes.net Tue Jul 8 13:36:09 2008 From: norseman at hughes.net (norseman) Date: Tue, 08 Jul 2008 10:36:09 -0700 Subject: How to make python scripts .py executable, not bring up editor In-Reply-To: References: <4872BC20.3080702@hughes.net> Message-ID: <4873A589.4070201@hughes.net> OK- ; In Windows use the Window Explorer and go find a something.py. Right click on it and select Open With then Browse and go find your Python24\python.exe and select it. Then check the box that says "Always use this for..." and test it by closing/re-opening WinExplorer and left clicking (or double clicking if so set) and it should attempt to run. IF so then use the 'dos window' and try typing in just it's name. ie... tryme.py this should attempt to run also. If not, check the C:\autoexec.bat PATH line. It just might be that it has the unwanted Python editor's path there. If so, consider putting your python24 path BEFORE it. (Don't forget to re-boot after mods to autoexec.bat) If that isn't the problem you might consider a complete scrub, reformat and re-install of Windows and ALL your stuff. (Uggg!) Don't be surprised if at some point it may "reset itself" back to it's current bad behavior. The Python editor shouldn't unless it is re-installed for some reason. The use of the bat file ignores any 'self reset' nonsense by forcing the desired action(s) by keeping Windows from wandering about. During the development cycle a modified copy in the working directory can delete program created files before (re)running script. This keeps Microsoft from yelling it can't function because something is in it's way. And hardcoding the file under development, along with any needed tokens, simplifies the command line and the cycle. ( del any files created in this loop (one line each) ( drive:\path_to\python pgm.py token tokens..... ( don't remember if pause or whatever - but give time to inspect screen ( preferred_editor pgm.py if in t.bat then t tests it and returns you to edit. Saves lots of typos, lowers anxiety, speeds up cycle, increases confidence in progress. NOTE: I use Linux and I do have a typo in my original reply. USE %1 NOT %f in the .bat file. Sorry ^numeric one Steve norseman at hughes.net ======================================================================= David Eynon wrote: > When my anyname.py runs, instead of executing the script, it opens up > the file within the Pythonwin text editor. > ======================================================================= > On Mon, Jul 7, 2008 at 9:00 PM, norseman wrote: >> korean_dave wrote: >>>> From command Prompt, i type in a script, "tryme.py". >>> This, instead, brings up PythonWin editor and Interactive Window. >>> >>> Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) >>> >>> How do I make it so that the script runs? >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> ====================================== >> I get tired of Microsoft jerking me around too. Rather than spend hours >> trying to undo somebody's reorganizing my system preferences I just ignore >> them completely. >> >> py tryme is how I do it. >> >> py.bat is a file placed in a directory listed in PATH in autoexec.bat. Edit >> autoexec.bat to include directory you put it in and reboot system or it >> won't find it. something like: PATH=.;c:\py-stuff;[anything already >> listed] Don't forget the semicolons. >> >> The . (period) up front means look here first. here being where ever you are >> when you issued the command. (The pRESENT wORKING dIRECTORY :-) The >> c:\py-stuff (fix to suit yourself and make sure it exists) is where you can >> put your efforts to be called at your leisure. Your .py files you write and >> use. Even the py.bat can go there. >> >> (Short note: Microsoft usually does look in pwd first. But good form >> dictates being specific.) >> >> contents of py.bat: >> ======================== >> rem name: py.bat >> @echo off >> c:\Python24\python %f.py make it fit your path >> rem end of file >> ======================== >> >> This way - you get what you expect, when you expect it, & nothing else. >> Yeah - dumb, but it works! I have one similar for each of my compilers. >> They contain the whole command line switches stuff as well as things like >> remove old stuff before trying to over write with new since MS can be >> temperamental about that. >> >> Easiest way in the world to give it the finger and make it behave. >> >> Steve >> norseman at hughes.ney >> > From mcl.office at googlemail.com Mon Jul 7 08:41:22 2008 From: mcl.office at googlemail.com (mcl) Date: Mon, 7 Jul 2008 05:41:22 -0700 (PDT) Subject: Confused yet again: Very Newbie Question References: <13be8c54-3fa9-4a37-a0e6-45bb019bff7e@a1g2000hsb.googlegroups.com> Message-ID: <593b44b7-9a0a-4665-9926-19890d29eabe@2g2000hsn.googlegroups.com> On 7 Jul, 13:09, Jeff wrote: > When you call c3.createJoe(c1.fred), you are passing a copy of the > value stored in c1.fred to your function. ?Python passes function > parameters by value. ?The function will not destructively modify its > arguments; you must expliticly state your intention to modify an > object: > > class one(): > ? ? fred = 'fred' > > class three(): > ? ? def createJoe(self, myName): > ? ? ? ? return "Joe" > > def main(): > ? ? c1 = one() > ? ? c3 = three() > ? ? c1.fred = c3.createJoe() # Modify c1's attribute, fred, with the > return value from c3.createJoe Thank you very much for your helpful replies. Two questions: One: My use of classes is because I want two classes one for global variables and one for global functions. A function may set multiple global variable values, so what is the best way to do this as 'return' only appears to be able to set one value. Two: I am sorry but I do not understand the significance defining a Class as: >>> class MyClass(object): what is object ? I am using python with Google App Engine, and I only have Alex Martelli's book up to Python 2.2, if they has any relevance ? Thanks again for your help. I now understand what my mistakes were and why I was not getting the results I had expected. Richard From alexnbryan at gmail.com Thu Jul 17 03:34:33 2008 From: alexnbryan at gmail.com (Alexnb) Date: Thu, 17 Jul 2008 00:34:33 -0700 (PDT) Subject: Getting a unknown word out of a list with no spaces In-Reply-To: <487EF593.5060505@promsoft.ru> References: <18502758.post@talk.nabble.com> <487EF593.5060505@promsoft.ru> Message-ID: <18503144.post@talk.nabble.com> Alexandr N Zamaraev wrote: > >>>> s = '--a href="/browse/brick"--brick--/a--' >>>> s > '--a href="/browse/brick"--brick--/a--' >>>> ''.join('<%s>' % l if i % 2 == 1 else l for i, l in > enumerate(s.split('--'))) > ' /browse/brick brick ' > > -- > http://mail.python.org/mailman/listinfo/python-list > > I'm sorry, I don't think I was being clear. I replaced the <'s with -- so it would post online w/o actually making a link. I just need to know how to get the "brick" out. -- View this message in context: http://www.nabble.com/Getting-a-unknown-word-out-of-a-list-with-no-spaces-tp18502758p18503144.html Sent from the Python - python-list mailing list archive at Nabble.com. From fredrik at pythonware.com Wed Jul 23 07:44:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 13:44:37 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> Message-ID: Fredrik Lundh wrote: > > cl cl -EHsc -MD -I \python25\include test.cc \python25\libs\python25.lib cut and paste error there: the "cl cl" should be just one "cl", of course. and just for the record/google, if I 1) don't include the header file, I get test.cc(5) : error C3861: 'Py_Initialize': identifier not found, even with argument-dependent lookup 2) attempt to undef the __cplusplus macro, I get test.cc(1) : warning C4117: macro name '__cplusplus' is reserved, '#undef' ignored 3) cut and paste declarations from the header files to my own file instead of including the files, ignoring the extern "C" part, I get test.obj : error LNK2019: unresolved external symbol "int __cdecl Py_Finalize(void)" (?Py_Finalize@@YAHXZ) referenced in function _main which looks pretty similar to the errors posted earlier. From mattheww at chiark.greenend.org.uk Thu Jul 31 19:51:25 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 01 Aug 2008 00:51:25 +0100 (BST) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <00a124e1$0$20313$c3e8da3@news.astraweb.com> <00a24168$0$20313$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >On Thu, 31 Jul 2008 22:01:48 +0100, Matthew Woodcraft wrote: >> The point is that if you tell people that "if x" is the standard way to >> check for emptiness, and also support a general principle along the >> lines of "write your function using the interfaces you expect, and call >> it using the object you have", you should expect to end up with bugs of >> this sort. > I'm not sure that an occasional performance hit justifies calling it a > bug. I suppose you might come up with a scenario or two where it really > is a problem, but then I'm also free to imagine scenarios where calling > len(obj) takes a massive performance hit, or has irreversible side > effects. Of course performance problems can be bugs! And it was explicit in my example that this was supposed to be such a case. But here, have an example where it's a non-performance bug: def load_widgets(self, widgets): if not widgets: raise ValueError("no widgets specified") self._prepare_for_widgets() for widget in widgets: self._load_widget(widget) self._is_widgetty = True This way you can end up with an object in an invalid state. >> I'm not a fan of len() for testing emptiness. But it would have been >> better in this case, because it would have converted a hard-to-find >> performance bug into an obvious exception. > At the cost of wrongly raising a exception for perfectly good arguments, > namely non-empty iterators. Sure, which will be fixed when the code passing an iterator is first tested, whether the iterator is empty or not. It's the errors which pass silently that are most dangerous. As I said, I'm not a fan of len() for testing emptiness. But "if x" isn't good either. Often I end up rearranging things so I can get rid of the explicit test altogether, but there can be a cost in readability. I think any Python-like language would be better off with an explicit way of asking 'is this container empty?'. -M- From tjreedy at udel.edu Sat Jul 12 22:02:54 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 22:02:54 -0400 Subject: palindrome function In-Reply-To: References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: Mensanator wrote: > It hasn't. and here's why: > > IDLE 2.6b1 >>>> seq=['a','n','n','a'] >>>> seq.reversed() > > Traceback (most recent call last): > File "", line 1, in > seq.reversed() > AttributeError: 'list' object has no attribute 'reversed' My apologies. reversed() is a builtin func, not a method, and it produces an iterator, not a seq. SO, corrected, >>> for s in ((1,2,3,2,1), [1,2,3,2,1]): ... type(s)(reversed(s)) == s ... True True >>> s = '12121' >>> ''.join(reversed(s)) == s True From mathieu.prevot at gmail.com Tue Jul 8 11:09:16 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Tue, 8 Jul 2008 17:09:16 +0200 Subject: Tricky problem: loss of terminal control after python script running (depending on internal parameters) Message-ID: <3e473cc60807080809v54ebd453i574f2d4de4db06d8@mail.gmail.com> Hi there, I have a python script that runs subprocesses (task = ffmpeg for convertion of videos to images) from threads [1]. I want to run at most 4 (default) tasks at the same time, and I usually ask the python script to process 10 files for testing. I'll run it on thousands of files for primetime. It seems that when I ask to process < 4 files everything is ok, but if I ask for > 4 files to process, I loose terminal features (no more newlines, etc). What's happening ? What is wrong in my script ? Thanks, Mathieu [1]: ,-- thread -- subprocess script --|-- thread -- subprocess |-- thread -- subprocess '-- thread -- subprocess -------------- next part -------------- A non-text attachment was scrubbed... Name: youff.py Type: application/octet-stream Size: 1279 bytes Desc: not available URL: From robert.rawlins at thinkbluemedia.co.uk Sun Jul 20 07:30:28 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Sun, 20 Jul 2008 12:30:28 +0100 Subject: __del__ methods In-Reply-To: <48831cca$0$16250$426a74cc@news.free.fr> References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> <87hcalxvx0.fsf@benfinney.id.au> <87prp8x23x.fsf@benfinney.id.au> <48831cca$0$16250$426a74cc@news.free.fr> Message-ID: <008201c8ea5c$03462a80$09d27f80$@rawlins@thinkbluemedia.co.uk> > Are you talking about the __new__ method ? Or about metaclasses ? Sorry Bruno, I should have made that a little clearer. I was talking about the __new__ method. Cheers mate, Robert From wuwei23 at gmail.com Wed Jul 23 03:06:31 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 23 Jul 2008 00:06:31 -0700 (PDT) Subject: os.walk question References: Message-ID: <58aaf7f2-c0bc-4041-a14f-503b0eb0b0a9@y22g2000prd.googlegroups.com> On Jul 24, 11:52?am, "Lanny" wrote: > How would one make a list of the files in the top directory > using os.walk. > > I need to pick a random file from said list. So you -only- want the files from one directory? Try: _, _, files = os.walk('/top/folder/here').next() The single underscore is a convention to indicate we don't care about those results. The .next() is needed to step through os.walk once, which will start at the path you specify. Hope this helps. - alex23 From iainking at gmail.com Tue Jul 29 05:27:22 2008 From: iainking at gmail.com (Iain King) Date: Tue, 29 Jul 2008 02:27:22 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> <466157f1-adcb-45f6-8c2d-b3c245a6ce8d@p31g2000prf.googlegroups.com> <47a24fed-6822-4767-aad3-07a72ddc3a1a@m73g2000hsh.googlegroups.com> Message-ID: <7a090a5e-c103-4182-b8d9-c1c0c4819696@y38g2000hsy.googlegroups.com> On Jul 29, 5:33 am, "Russ P." wrote: > On Jul 28, 8:44 pm, alex23 wrote: > > > On Jul 29, 4:46 am, "Russ P." wrote: > > > > As I said, I could write a pre-processor myself to > > > implement it in less than a day. > > > So WHY DON'T YOU WRITE IT ALREADY? > > I'm working on something else right now if you don't mind, but I'll > get to it in good time. > > Conceptually, the matter is simple. All I need to do is to grab the > first formal argument of each def, then search for occurrences of any > word in the body of the def that starts with a dot, and insert that > first argument in front of it. > > I expect the "hard" part will be breaking up the body of the def into > "words." I could just split each line on white space, except for > situations like > > x+=.zzz > > So I need to account for the fact that operators do not need to be > surrounded by spaces. That's the hardest part I can think of off the > top of my head. > > Maybe I'll encounter an insurmountable problem and realize that the > idea can't work in general. If so, then so be it. Certainly, no one on > this thread has anticipated such a problem. Had someone pointed out an > actual technical problem with the idea, I would have gladly thanked > them. But I got a load of irrelevant crap instead, not to mention > being addressed as "boy." > > > If you're meeting so much resistance to your idea, why not scratch > > your own damn itch and just do it? > > > Or doesn't that afford you as many chances to insult others while > > feeling smugly superior? > > This coming from a guy who insulted my reading comprehension ability > -- when he was the one who was wrong! Are you actually this stupid? I mean, you were entertaining while you were mouthing of and insulting your betters, but now you're gonna complain the second anyone insults you (and I mean, 'boy' - what an insult!). Never mind that you're never gonna get off your ass to write a PEP, which would be rejected on language design grounds anyway (as demonstrated by alex23's link - the one you aren't comprehending). The most irritating thing is that I like the idea of being able to use '.x = 10' type notation (and have been for a long time), but the person arguing for it is an insufferable buffoon who's too dense to understand a cogent argument, never mind make one. So great, thanks, the chances of this (or a VB 'with'-like 'using' keyword) ever making it into the language get smaller every time you fire up your keyboard. Nice work. Iain p.s. am looking forward to your post whining about the invalid reasons your PEP got rejected, in the slim hope you actually write one. From Rakesh.Thakrar at microcom-it.com Thu Jul 31 07:50:11 2008 From: Rakesh.Thakrar at microcom-it.com (Rakesh Thakrar) Date: Thu, 31 Jul 2008 12:50:11 +0100 Subject: Python Contractor needed Message-ID: <17A5EF611D8AF34DA2E14B2354C9C3FE1EFA00@ern-server-mail> Hi All, An opportunity for a talented Python Software Engineer has arisen to join a company which is currently going through a phase of rapid expansion. Candidates must have excellent software development skills to join an established team within this small company with offices in the U.K. and U.S. An ideal candidate will be familiar with Linux, have a passion for working with OpenSource software and a flair for creating innovative solutions to complex problems. The candidate will be a self motivated, flexible software engineer working within the existing I.T. Team. The day to day role will almost exclusively focus on new projects. Key elements of the role include l Work closely with the I.T. team and business managers to aid the design and implementation of a new web based application for our customers and data processing engine. l Work closely with the application design team to understand, agree, plan and develop the new application. l Assess software requirements and assist with the project planning stage. l Design, code and test various software elements in both Windows and Linux based environments. l Ability to train and mentor other members of the software development team. l Experience of working within a development team using source control and collaborative tools such as Subversion, CVS, Trac, etc. l Providing required documentation (specifications, test plans, processes, etc). This is a 6-12 month contract based near Portsmouth in Hampshire UK . Please do not hesitate to contact me for further information. Regards Rakesh ___________________ Rakesh Thakrar Manager Microcom Tel: 01923 851225 Mob: 079 7094 3227 Fax: 0845 389 2392 www.microcom-IT.com Beaumont Gate Shenley Hill Radlett Hertfordshire WD7 7AR Permanent and Contract IT Specialists ____________________________________ P SAVE A TREE - PLEASE DO NOT PRINT THIS EMAIL UNLESS YOU REALLY NEED TO. ************************************************************************ ************ The views expressed in this e-mail are not necessarily the views of European Recruitment Network Ltd, its directors, officers or employees make no representation or accept any liability for its accuracy or completeness unless expressly stated to the contrary. This e-mail, and any attachments are strictly confidential and intended for the addressee(s) only. The content may also contain legal, professional or other privileged information. Unless expressly stated to the contrary, no contracts may be concluded on behalf of European Recruitment Network Ltd by means of e-mail communication. You may report the matter by calling us on 0845 389 2322. Please ensure you have adequate virus protection before you open or detach any documents from this transmission. European Network Recruitment Ltd does not accept any liability for viruses. European Recruitment Network Ltd is registered in England: Company Number: 5651508. Registered Office: Greener House, 66-68 Haymarket, London, SW1Y 4RF ************************************************************************ ************ -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Jul 25 16:47:47 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Jul 2008 16:47:47 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87d4l2v1op.fsf@nokile.rath.org> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> Message-ID: Nikolaus Rath wrote: > Terry Reedy writes: >> Torsten Bronger wrote: >>> Hall?chen! >> > And why does this make the implicit insertion of "self" difficult? >>> I could easily write a preprocessor which does it after all. >> class C(): >> def f(): >> a = 3 >> >> Inserting self into the arg list is trivial. Mindlessly deciding >> correctly whether or not to insert 'self.' before 'a' is impossible >> when 'a' could ambiguously be either an attribute of self or a local >> variable of f. Or do you and/or Jordan plan to abolish local >> variables for methods? > > Why do you think that 'self' should be inserted anywhere except in the > arg list? AFAIU, the idea is to remove the need to write 'self' in the > arg list, not to get rid of it entirely. Because you must prefix self attributes with 'self.'. If you do not use any attributes of the instance of the class you are making the function an instance method of, then it is not really an instance method and need not and I would say should not be masqueraded as one. If the function is a static method, then it should be labeled as one and no 'self' is not needed and auto insertion would be a mistake. In brief, I assume the OP wants 'self' inserted in the body because inserting it only in the parameter list and never using it in the body is either silly or wrong. tjr From gordon at panix.com Thu Jul 24 11:24:16 2008 From: gordon at panix.com (John Gordon) Date: Thu, 24 Jul 2008 15:24:16 +0000 (UTC) Subject: Inserting cookies into a web session References: Message-ID: In =?ISO-8859-1?Q?Michael_Str=F6der?= writes: > John Gordon wrote: > > I'm developing a web application that needs a semi-persistent way to > > store information. > > > > I've looked at some options such as writing entries to a database table > > or creating small textfiles, but I'm not thrilled with anything I've come > > up with so far. > What's the problem? The problem is databases and textfiles are too heavyweight. I only need the information for the duration of a session; I don't want to have to worry about cleaning up the database or textfile afterwards. To explain my requirements a bit more, I'm writing a web-based contact manager application. The basic contact unit is a person, and I'm currently working on the page layout for displaying information relating to a person. The top section of the page is always the same: it shows your personal information. Name, userid, title, etc. But the bottom section of the page can change; it shows one of several different kinds of information. It can either display your home and office address, or it can show all the ways you can be contacted (phone, email, pager, etc), or it can show the times during which you wish to be contacted. (I didn't choose this layout; it was all done and approved before I joined the project. I just have to implement it.) My problem is if the user goes to the top portion of the page and changes some of the information there, for example he wants to change his title, that information is self-contained in a form and knows nothing about the choice the user made of what to show at the bottom of the page. Of course, I could add the choice as a hidden form element at the top of the page. But that seems kludgy -- that form *shouldn't* have to know. And the page layout isn't as simple as I've described here; there are actually lots of these little self-contained forms that are unrelated to the information at the bottom of the page, and I'd rather not have to add a hidden element to all of them. Using a cookie seems like an ideal solution. When the session starts, I can set the choice to the default setting of "address", and if the user ever clicks on "show me my contact methods" or "show me my times", I just set the cookie to that choice. I don't have to worry about passing the choice around in each of the dozen or so forms that are on the page. > Before using cookies keep in mind that the cookies returned by the > browser are not trustworthy! You have to validate the values each time. I'm not sure it's worth the trouble in my case. I won't be depending on the cookie for sensitive information; I'm just using it as a stored setting for which kind of information to display on the page. > http://docs.python.org/lib/module-Cookie.html That looks great! > Ciao, Michael. Thanks Michael. :-) -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From sunp1028 at gmail.com Wed Jul 16 20:50:40 2008 From: sunp1028 at gmail.com (patrol) Date: Wed, 16 Jul 2008 17:50:40 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> <487E1AD4.9020509@timgolden.me.uk> <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> Message-ID: <26354141-eeaf-4e86-afaf-7cb79fa1a3b8@f36g2000hsa.googlegroups.com> On 7?17?, ??3?20?, Tim Golden wrote: > patrol wrote: > > On 7?17?, ??12?16?, Tim Golden wrote: > >> Assuming that the error comes back in the sys.stdout encoding, the following version *should* work ok. I still haven't got a non-English set up to test it on, but it certainly does return a Unicode error message. > > >>http://timgolden.me.uk/wmi-project/wmi.py > > >> The usual test case, if you wouldn't mind: > > >> > >> import wmi > > >> wmi.WMI ("non-existent computer") > > >> > > >> should give a (language-specific) error message, not an UnicodeDecodeError > > >> TJG > > -------------------------------------------------------------------------------------- > >>>> import wmi > >>>> wmi.WMI('non-existent computer') > > Traceback (most recent call last): > > File "", line 1, in > > File "C:\Python25\lib\wmi.py", line 1199, in connect > > handle_com_error (error_info) > > File "C:\Python25\lib\wmi.py", line 184, in handle_com_error > > exception_string = [u"%s - %s" % (hex (hresult_code), > > hresult_name)] > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > > 4: ordinal > > not in range(128) > > -------------------------------------------------------------------------------------- > > yup,error_info contains the Chinese encoded string. All of the Simple > > Chinese Windows use the CP936.Every Chinese word utilizes two > > bytes.Maybe you can fix this bug by modifying handle_com_error. > > Can you confirm that that last bit of > code was run with the version of wmi.py > currently at: > > http://timgolden.me.uk/wmi-project/wmi.py > > That version should already be decoding the > string correctly. > > TJG ---------------------------------------------------------------------------------------- >>> import wmi >>> wmi.WMI('non-existent computer') Traceback (most recent call last): File "", line 1, in wmi.WMI('non-existent computer') File "C:\Python25\lib\wmi.py", line 1199, in connect handle_com_error (error_info) File "C:\Python25\lib\wmi.py", line 189, in handle_com_error raise x_wmi, u"\n".join (exception_string) x_wmi: ------------------------------------------------------------------------------------------ # -*- coding:utf-8 -*- import wmi from time import sleep c = wmi.WMI () process_watcher = c.Win32_Process.watch_for("creation") while True: new_process = process_watcher() if new_process.Caption == 'notepad.exe': print "start killing.." sleep(5) result = new_process.Terminate() print "killed" When I kill the notepad.exe manually,it also results in errors. Traceback (most recent call last): File "C:\Documents and Settings\patrol\??\test.py", line 12, in result = new_process.Terminate() File "C:\Python25\lib\wmi.py", line 396, in __call__ handle_com_error (error_info) File "C:\Python25\lib\wmi.py", line 188, in handle_com_error exception_string.append (u" %s - %s" % (hex (scode), (error_description or u"").decode (sys.stdout.encoding).strip ())) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin al not in range(128) ----------------------------------------------------------------------------------------------- Patrol From CracKPod at googlemail.com Tue Jul 15 04:04:06 2008 From: CracKPod at googlemail.com (CracKPod) Date: Tue, 15 Jul 2008 01:04:06 -0700 (PDT) Subject: Python Tiddlywiki class References: Message-ID: <4ac68650-b2c0-4992-86aa-e0572bf7f0cb@m36g2000hse.googlegroups.com> On 15 Jul., 03:04, David wrote: > CracKPod wrote: > > Hello, I wrote a Python class to interact with the TiddlyWiki. In case > > you are interested you can find it on my blog: > > >http://crackpod.bplaced.net/ > > > CracKPod > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Thank you :) > > -- > Powered by Gentoo GNU/LINUXhttp://www.linuxcrazy.com You're welcome! If I may beg you, redownload it from my Blog. I had to make a small change that's why I released 1.0.1, elsewise you won't be able to change the tiddler content and save it afterwards. From fredrik at pythonware.com Mon Jul 21 12:16:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 18:16:31 +0200 Subject: Seriously, though, about LLVM In-Reply-To: References: Message-ID: mk wrote: > This project has gained some publicity. There's IronPython, right, so > has anybody thought about implementing Python using LLVM as backend, as > it seems not out of question at all? you mean like: http://llvm.org/ProjectsWithLLVM/#pypy ? From fredrik at pythonware.com Mon Jul 21 08:47:32 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 14:47:32 +0200 Subject: error In-Reply-To: <5f4395d7-9f5c-45c3-b137-655e5c618b8c@8g2000hse.googlegroups.com> References: <5f4395d7-9f5c-45c3-b137-655e5c618b8c@8g2000hse.googlegroups.com> Message-ID: Anish Chapagain wrote: > from Tkinter import * > root=Tk() > f=Frame(root,height=200,width=200) > b=Button(f,text="quit",command=f.quit) > f.pack() > root.mainloop() > > -------------------------------------------------- > from Tkinter import * > import sys > root=Tk() > f=Frame(root,height=200,width=200) > b=Button(f,text="quit",command=sys.exit) > f.pack() > root.mainloop() > > I am wondering that why the button after clikcing is not closing the > window..please any suggestion.. > i tries command=f.quit, sys.quit also.. > if there is something i'm missing please help Assuming you accidentally left out the line where you're displaying the button (e.g. "b.pack()"), both your samples work when running this from the command line. Are you perhaps running this code from inside IDLE? IDLE is itself written in Tkinter, and it doesn't always shut down the Tkinter subsystem properly. ... and I have to admit that I don't know what the currently recommended workaround is -- you'll find plenty of documentation on the net that just says "don't do that" (run Tkinter programs from within IDLE, that is), but surely someone should have fixed that issue by now?. From frankrentef at yahoo.com Thu Jul 24 12:09:12 2008 From: frankrentef at yahoo.com (frankrentef) Date: Thu, 24 Jul 2008 09:09:12 -0700 (PDT) Subject: Python / PAMIE References: <9e077ec9-9a07-4a3a-b5dc-bfd593162350@8g2000hse.googlegroups.com> Message-ID: On Jul 24, 10:45?am, Tim Golden wrote: > frankrentef wrote: > > THNX for your response. ?Based on the authors code it's very simple. > > > from cPAMIE import PAMIE > > ie=PAMIE () > > > #ie.navigate ("google.com") > > > #ie.linkClick > > #ie.textBoxSet > > #ie.writeScript > > > ie.navigate ('https://login.yahoo.com/config/mail?.intl=us') > > #ie.scriptWrite () > > > ie.scriptWrite() > > > Below is the error I get... > > > ?File "C:\Python24\lib\site-packages\cPAMIE.py", line 1837, in > > scriptWrite > > ? ? nameProp = getattr(x,"nameProp") > > ? File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", > > line 500, in __getattr__ > > ? ? raise AttributeError, "%s.%s" % (self._username_, attr) > > AttributeError: .nameProp > > I'm afraid I'm no IE expert (read: never use it if I can > avoid it) but I suspect here a combination of slightly > flaky code in the Python module plus, maybe, a change in > the IE dom object model. > > If you change lines 1832-1836 of cPAMIE.py to be as follows: > > > ? ? ? ? ? ? for j in range(doc.length): > ? ? ? ? ? ? ? ? x = doc[j] > ? ? ? ? ? ? ? ? etype = getattr(x,"type", "") > ? ? ? ? ? ? ? ? name = getattr(x,"name", "") > ? ? ? ? ? ? ? ? nameProp = getattr(x,"nameProp", "") > > > > then at least some kind of output is produced. But I'm > not entirely sure what this function is trying to achieve > so I don't guarantee it's doing the right thing yet. > > TJG- Hide quoted text - > > - Show quoted text - The idea is to run through a given url, detect any "form fields" that require populating and build a script listing the field names, etc. From there a PAMIE user can take the script returned and build a test case. In other words the user does not have to search through the HTML code for all the field names (blanks) radio button names, etc. It works "great" on the video tutorial but dang if I or any of our senior guys can get it to work here in house. THNX for input, we'll give it a try. From circularfunc at yahoo.se Thu Jul 3 14:47:11 2008 From: circularfunc at yahoo.se (defn noob) Date: Thu, 3 Jul 2008 11:47:11 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: <6d4bfmFp3aoU1@mid.uni-berlin.de> <0f6f795d-8041-463e-8e98-9d830ca3fc5b@l42g2000hsc.googlegroups.com> <45111722-3f2c-476d-8e7b-fd65cc5100a6@56g2000hsm.googlegroups.com> Message-ID: On Jul 3, 8:06?pm, "bruno.desthuilli... at gmail.com" wrote: > On 3 juil, 18:51, defn noob wrote: > > > well the reason i unzipped and placed it in site-packages was because > > nothign happened when i ran setup.py(unzipped). > > What do you mean, "running setup.py unzipped" ??? > > The correct way to install a package is to: > > - unzip (untar, whatever) the archive somewhere in your own directory > - cd to the unzipped directory > - *from there*, run python setup.py install yes, which i have done. the command row executes but nothing happens, no errors either. From alif016 at gmail.com Fri Jul 18 10:47:54 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Fri, 18 Jul 2008 09:47:54 -0500 Subject: trying to match a string In-Reply-To: <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> Message-ID: <4880AD1A.6040707@gmail.com> oj wrote: > On Jul 18, 12:10 pm, John Machin wrote: > >> On Jul 18, 9:05 pm, oj wrote: >> >> >> >> >>> On Jul 18, 11:33 am, arnimavidyar... at gmail.com wrote: >>> >>>> Hi, >>>> >>>> Hi, >>>> >>>> I am taking a string as an input from the user and it should only >>>> contain the chars:L , M or R >>>> >>>> I tried the folllowing in kodos but they are still not perfect: >>>> >>>> [^A-K,^N-Q,^S-Z,^0-9] >>>> [L][M][R] >>>> [LRM]?L?[LRM]? etc but they do not exactly meet what I need. >>>> >>>> For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. >>>> >>>> regards, >>>> SZ >>>> >>>> The string may or may not have all the three chars. >>>> >>> With regular expressions, [^LRM] matches a character that isn't L, R >>> or M. So: >>> >>> import re >>> >>> var = "LRLRLRLNR" >>> >>> if re.search(r'[^LRM]', var): >>> print "Invalid" >>> >> Fails if var refers to the empty string. >> > > No it doesn't, it succeeds if var is an empty string. An empty string > doesn't contain characters that are not L, R or M. > > The OP doesn't specify whether an empty string is valid or not. My > interpretation was that an empty string would be valid. > Why not just use * instead of + like: if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of string; $ means end of string print "Invalid" This will *only* print invalid when there is a character other than L, R, or M or a empty string. From __peter__ at web.de Thu Jul 3 02:43:45 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 Jul 2008 08:43:45 +0200 Subject: How to pickle bound methods References: Message-ID: srinivasan srinivas wrote: Please don't top-post. > Could you please explain?the code breifly?? I am not getting what it does. >> import copy_reg >> import new >> >> def make_instancemethod(inst, methodname): >> ? ? return getattr(inst, methodname) >> >> def pickle_instancemethod(method): >> ? ? return make_instancemethod, (method.im_self, method.im_func.__name__) >> >> copy_reg.pickle(new.instancemethod, pickle_instancemethod, >> make_instancemethod) If you have a type that cannot be pickled because it is implemented in C you can make it "picklable" by registering it with the copy_reg.pickle() function. This function takes three arguments: 1 the type (here: new.instancemethod) 2 a function that takes an instance of the type. This returns a factory function and a tuple of the arguments this factory function needs to recreate the instance. 3 the factory function. In short the following must work, and out_method should do the same thing as in_method: factory, args = pickle_instancemethod(in_method) out_method = factory(*args) Now to your other problem, pickling static methods. The type of a static method is just new.function, the same as that of a global function. Global functions are already picklable, so the copy_reg mechanism doesn't kick in. Peter From sjmachin at lexicon.net Thu Jul 31 19:19:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 31 Jul 2008 16:19:37 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> <4609709f-dc0f-47cc-905e-1552a02ec3b6@r15g2000prd.googlegroups.com> <416f2710-1295-4d8b-a356-98fd9e9a56ad@j7g2000prm.googlegroups.com> Message-ID: <33e97e69-84ec-4553-a7bd-aaba5ffe6944@v13g2000pro.googlegroups.com> On Aug 1, 7:44 am, william tanksley wrote: > John Machin wrote: > > william tanksley wrote: > > Let's try again: > > Cool. Sorry for the misunderstanding. Thank you for helping again! > > Postscript: your request to print the actual data did the trick. I'd back inspecting actual data against armchair philosophy any time :-) > I'm > including the rest of my reply just to provide context, but the answer > was the the Unicode was actually embedded in the URL, encoded as > distinct bytes. Thus, it *had* to be url-decoded and then UTF-8 > decoded, in that order, in order to recover the original filename. > > So the problem was indeed purely in my head -- I should have looked at > the original data (unfortunately, I was fooled by looking at the song > title, which is the same thing but with the raw UTF-8 bytes instead of > the URL escape codes). > > > > > >> track_id = url2pathname(urlparse(track_id).path) > > >> print repr(track_id) > > >> parse_result = urlparse(track_id).path > > >> print repr(parse_result) > > >> track_id_replacement = url2pathname(parse_result) > > >> print repr(track_id_replacement) > > > The "important" value here is track_id_replacement; it contains the > > > data that's throwing me. It appears that some UTF-8 characters are > > > being read as multiple bytes by ElementTree rather than being decoded > > > into Unicode. > > > Here's one example. The others are similar -- they have the same > > > things that look like problems to me. > > > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" > > ROTFL! I thought the Buffett thing was a Windows filename! What I was > > expecting was THREE lots of repr() output, and I'm quite unused to > > seeing repr() output with quotes around it instead of apostrophes; how > > did you achieve that? > > I don't know -- but I got it again when I printed out the original > version. My *guess* would be that this is what repr prints when asked > to print a byte string (but I don't know how to confirm that). > Alternately, the fact that I'm running these inside SPE might be > changing some defaults. I'm not sure. > > You're right that single quotes are expected -- and I'd expect a > preceding u, since they're supposed to be Unicode. I dunno what's > going on. Why do you suppose that the contents are Unicode? It's a URL-encoded string i.e. *deliberately* ASCII, in fact sub-ASCII (see all the %20 stuff?). What's going on is that ElementTree presents text as ASCII if it can be so represented, otherwise as Unicode. This is actually a *convenience*. Get used to it. Enjoy it. > > > So you're saying that track_id_replacement contains utf8 characters. > > It is obtained by track_id_replacement = url2pathname(parse_result). > > You don't show us what is in parse_result. url2pathname() is nothing > > to do with ElementTree. urlparse() is nothing to do with ElementTree. > > You have provided no evidence that ElementTree is doing what you > > accuse it of. > > Okay. Here's the evidence... Or something. Looking at this I begin to > see why things work the way they do. It's utterly bizzare, quite > frankly. > > > Please try again. Backtrack in your code to where you are pulling the > > url out of an element. Do print repr(some_element.some_attribute). > > Show us. > > Okay, the repr of the string that comes out of the .text attribute is: > > "file://localhost/C:/Documents%20and%20Settings/TanksleyJrW/My > %20Documents/My%20Music/iTunes/iTunes%20Music/Podcasts/Brian > %20Preston's%20_Money%20Guy_%20Blog%20and%20Pod/Buffett%20Time%20- > %20Annual%20Shareholders%C2%A0L.mp3" > > Looking at the XML, and THIS TIME actually looking at the correct > attribute (I was looking at the title before) I see... surprise! > That's the correct data. > > So all of the mysteries are solved (except for my Python's > doublequotes, but who cares), and ElementTree is entirely vindicated. Shucks. I can sense that you'd been looking forward to conducting an auto-da-fe followed by tossing the author on a bonfire ... but you can't burn a bot anyway :-) From rocksportrocker at googlemail.com Wed Jul 2 09:30:03 2008 From: rocksportrocker at googlemail.com (rocksportrocker) Date: Wed, 2 Jul 2008 06:30:03 -0700 (PDT) Subject: Distribute ctypes based modules Message-ID: Hi, how do you distribute ctypes based modules on a linux machine ? What does your setup.py look like ? I have to copy my shared library to /usr/lib or another common place, but I would prefer .../site-packages/... In the latter case I have to modify LD_LIBRARY_PATH oder some ld.so.conf configuration file. So, what is the prefered method for this task ? Greetings, Uwe From desothier at yahoo.com Tue Jul 22 11:10:41 2008 From: desothier at yahoo.com (antar2) Date: Tue, 22 Jul 2008 08:10:41 -0700 (PDT) Subject: convert list of lists to list Message-ID: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> Is there a way to convert list_of_listsA to list_of_listsB, where one list in listof lists A is one element of listB? list_of_listsA: [['klas*', '*', '*'], ['mooi*', '*', '*', '*'], ['koe'], ['arm*', '*', '*(haar)'], ['groei*', '*', '*', '*', '*']] listB: ['klas* * *', 'mooi* * * *, 'koe', 'arm* * * (haar)', 'groei* * * * *'] Thankx! From ojeeves at gmail.com Mon Jul 21 05:23:43 2008 From: ojeeves at gmail.com (oj) Date: Mon, 21 Jul 2008 02:23:43 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> Message-ID: <7574170c-ea58-48a5-83b0-0cd909f07d06@k37g2000hsf.googlegroups.com> On Jul 19, 3:04?am, Andrew Freeman wrote: > let me revise it please: > > To show if valid: > > if re.search(r'^[LRM]*$', 'LM'): > ? ? print 'Valid' Fine, this works, although match instead of search blah blah blah as has already been mentioned. I still think searching for one invalid character is more elegant then trying to match the entire string, but that's just personal preference, I guess. > > To show if invalid, > > if re.search(r'^[^LRM]*$', '0'): > ? ? print 'Inalid' No. This is wrong. This only matches strings that consist entirely of characters that are not L, R or M: >>> import re >>> if re.search(r'^[^LRM]*$', 'ZZZLZZZ'): ... print "Invalid" ... >>> This doesn't print "Invalid" because there is one non-invalid character there, which is clearly not what the OP wanted. From karthikbalaguru79 at gmail.com Thu Jul 17 02:56:05 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Wed, 16 Jul 2008 23:56:05 -0700 (PDT) Subject: Instance Message-ID: <120cea3a-33a9-49ec-8932-7cef2e5aef17@25g2000hsx.googlegroups.com> Hi, I am new to python. I am trying to use the python files given to me for bringing up a setup. I get the following error while trying to use a python file - AttributeError : Classroom instance has no attribute 'desk_offset' How to resolve this ? Should i need to define desk_offset to zero in the python file ? Any ideas .. Thx in advans, Karthik Balaguru From __peter__ at web.de Fri Jul 18 05:16:54 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 11:16:54 +0200 Subject: sub typing built in type with common attributes. Am I right? References: <4d9c4b74-9c28-4b98-afe7-9eb774655c3a@v21g2000pro.googlegroups.com> Message-ID: King wrote: > I am new to python and getting into classes. Here I am trying to > create subtype of built in types with some additional attributes and > function. 'Attributes' is the main class and holds all the common > attributes that requires by these subtypes. This is what I came out > with. I need to know whether everything is right here ? or there are > some better ways to do it. There may be some technical errors in your code, e. g. - the __slots__ look like a bit of bullshit: you already have a __dict__ from the Attribute base class - name mangling is done for attributes starting with two underscores But the greater problem I see is that you are building up a huge bureaucracy where pythonic code would concentrate on a concrete goal with minimal administrative overhead. Peter From stefan_ml at behnel.de Thu Jul 3 09:32:06 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 3 Jul 2008 13:32:06 +0000 (UTC) Subject: ANN: XML builder for Python References: <10df03a30807021716v33518930g951e903c2529ef82@mail.gmail.com> Message-ID: Hi, two comments. Gerard flanagan gmail.com> writes: > Nice! Here's a version that uses elementtree: [...] > def __call__(self, value='', **kargs): > self.element.text = value This should spell def __call__(self, value=None, **kargs): > class builder(element): > def __init__(self, version, encoding): > self.parent = ET.Element('root') And this might need some more work to fix as the root element shouldn't be necessary. But it's a good start. Look at the link I posted for some more ideas. Stefan From h.goebel at goebel-consult.de Tue Jul 15 17:00:58 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Tue, 15 Jul 2008 23:00:58 +0200 Subject: Using McMillan Installer, PyInstall or py2exe cross-platform? In-Reply-To: References: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <487d100a$0$7538$9b4e6d93@newsspool1.arcor-online.net> David Lyon schrieb: > there is a python based "bake" make like program... that is useful... > http://projects.bertram-scharpf.de/bake/bake1.html I'm not in the need of a build program :-) I would use Scons therefor, anyway. > then there is Wine... that is a windows emulator under linux... that > might be pretty easy.... http://www.winehq.org/ I don't like to use winw here, it would nor fit into my release process. I started working on cross-pyinstall today. -- Sch?nen Gru? - Regards Hartmut Goebel Goebel Consult Spezialist f?r IT-Sicherheit in komplexen Umgebungen http://www.goebel-consult.de From noorhanabbas at yahoo.co.uk Wed Jul 9 12:32:31 2008 From: noorhanabbas at yahoo.co.uk (Noorhan Abbas) Date: Wed, 9 Jul 2008 16:32:31 +0000 (GMT) Subject: Openine unicode files Message-ID: <92793.41064.qm@web27403.mail.ukl.yahoo.com> Hello, I wonder if someone can advise me on how to open unicode utf-8 files without using the codecs library . I am trying to use the codecs.open() from within Google Appengine but it is not working.?? Thank you very much in advance, Nora __________________________________________________________ Not happy with your email address?. Get the one you really want - millions of new email addresses available now at Yahoo! http://uk.docs.yahoo.com/ymail/new.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Thu Jul 24 04:57:53 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 24 Jul 2008 09:57:53 +0100 Subject: Recursion Performance Question In-Reply-To: References: Message-ID: <48884411.3020303@timgolden.me.uk> B wrote: > Now it works, but it runs quite slow (compared to the c++ app). I > changed gwl from strait recursion to use a generator and that helped, > but it still takes 0.5-1.0 seconds to populate the tree. What I'm > wondering is am I doing it in a really inefficient way, or is it just > python? Well I did just enough to get your code to work and ran it through timeit on my respectable but hardly bleeding-edge desktop PC. C:\temp>python -m timeit "import get_windows; get_windows.run ()" 100 loops, best of 3: 17.1 msec per loop So it's not that slow. Full code is posted below; uncomment the "print_tree" bit to see the results to confirm that it's doing what you think. I did this really quickly so it's possibly I've misunderstood what your code's up to. I'm not saying there aren't other ways to do this, but your code (at least inside my guessed-at wrapper) seems to do an adequate job in a reasonable time. import time from win32gui import GetWindow, GetWindowText, GetDesktopWindow from win32con import GW_CHILD, GW_HWNDNEXT class Node (object): def __init__ (self, hwnd): self.hwnd = hwnd self.children = [] def addChild (self, hwnd): self.children.append (Node (hwnd)) def gwl(node, hwnd): if hwnd: yield node, hwnd for nd, wnd in gwl(node.children[-1], GetWindow(hwnd, GW_CHILD)): yield nd, wnd for nd, wnd in gwl(node, GetWindow(hwnd, GW_HWNDNEXT)): yield nd, wnd def generateTree(self): t = time.clock() if self is not None: self.children = [] for nd, wnd in gwl(self, GetWindow(self.hwnd, GW_CHILD)): nd.addChild(wnd) def print_tree (root, level=0): print level * " ", GetWindowText (root.hwnd) or hex (root.hwnd) for child in root.children: print_tree (child, level + 1) def run (): desktop = Node (GetDesktopWindow ()) generateTree (desktop) #~ print_tree (desktop) > The second problem is reseting the list. In C++ I would use the STL > Vector's clear() method. In python, I can't think of a good way to free > all the nodes, so there is a large memory leak. I'm not clear here what you're getting at. Memory handling in Python is usually best left to Python unless you've got a very specific case -- and they do crop up occasionally. Just to be clear on something: Python does its own internal memory management, alloc-ing and free-ing with a variety of policies broadly managed by an internal pool. You're unlikely to see much memory released back to the system while Python's running. But this isn't a memory leak as such. You don't need to (and, in effect, can't) release the memory explicitly. But I'd be surprised if you had enough windows open for this to be even noticeable. TJG From paddy3118 at googlemail.com Tue Jul 22 18:11:35 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 22 Jul 2008 15:11:35 -0700 (PDT) Subject: Bidirectional Generators References: <8e2cf6b7-4b5f-4701-8a4c-bc779ed7305c@m45g2000hsb.googlegroups.com> Message-ID: <976df308-3855-4f2b-a82a-dacba480e7d7@i76g2000hsf.googlegroups.com> On Jul 22, 10:07?pm, william tanksley wrote: > Okay, I'm almost finished with my first bidirectional generator. By > "almost finished" I mean both that it's almost working, and that I'm > almost about to replace it with a class that works a bit more like > what I currently understand. > > Surely some other people have worked with this feature... Are there > any pages that discuss how it's been useful? > > No, I don't want to see an implementation of coroutines. I get that > one already. :-) > > -Wm What's one of them then? - Paddy. From victorsubervi at gmail.com Tue Jul 29 09:26:34 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 29 Jul 2008 15:26:34 +0200 Subject: Windows Interpreter In-Reply-To: <488F1745.4020705@timgolden.me.uk> References: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> <488F1745.4020705@timgolden.me.uk> Message-ID: <4dc0cfea0807290626p4b05376en49ccb18f0e1eb4bb@mail.gmail.com> def a(): chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', '\\yz'] rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like the Beast? Who can wage war against him?\par' for char in chars: c = '(?<=' + char + ')' test = re.search(c, rtf_markup) try: junk = test.group(0) print char except: pass Now, I can paste that entire fn in linux. But in windows I have to paste it line_by_line. Pain in butt! And it indents automatically. How change that behavior. TIA, Victor On 7/29/08, Tim Golden wrote: > > Victor Subervi wrote: > >> Hi: >> I would like to make my windows python interpreter work like my linux one. >> I want to be able to cut and paste multiple lines of code. >> > > You can already do this: what are you trying which isn't working? > > Now I can only paste one line at a time. I do not want it to indent >> automatically. How can I change this? >> > > I realise this is a difficult thing to describe in words, > but I regularly cut and paste multiple lines of code > into my Python interpreter and it doesn't indent automatically. Can you > give some specific examples of what you do and what does or doesn't work? > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alif016 at gmail.com Sat Jul 19 15:00:52 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Sat, 19 Jul 2008 14:00:52 -0500 Subject: trying to match a string In-Reply-To: <4881FE02.3000203@gmail.com> References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> <945275e9-8923-479c-8eec-258bd68063c0@z6g2000pre.googlegroups.com> <4881FE02.3000203@gmail.com> Message-ID: <488239E4.1010900@gmail.com> Andrew Freeman wrote: > John Machin wrote: >> A couple of points: >> (1) Instead of search(r'^blahblah', ...) use match(r'blahblah', ...) >> (2) You need to choose your end-anchor correctly; your pattern is >> permitting a newline at the end: I forgot to change search to match. This should be better: def match(var): if re.match(r'[LRM]*\Z', var): return True else: return False I was also thinking if you had a list of these items needing to be verified you could use this: >>> l = ['LLMMRR', '00thLL', 'L', '\n'] >>> out = [] >>> map(lambda i: match(i)==False or out.append(i), l) >>> print out ['LLMMRR', 'L'] -- Andrew From ggpolo at gmail.com Mon Jul 28 17:40:24 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 28 Jul 2008 18:40:24 -0300 Subject: seemingly simple list indexing problem In-Reply-To: References: Message-ID: On Mon, Jul 28, 2008 at 6:24 PM, Ervan Ensis wrote: > My programming skills are pretty rusty and I'm just learning Python so this > problem is giving me trouble. > > I have a list like [108, 58, 68]. I want to return the sorted indices of > these items in the same order as the original list. So I should return [2, > 0, 1] You could simply do this: a = [108, 58, 68] b = sorted(a) [b.index(c) for c in a] > > For a list that's already in order, I'll just return the indices, i.e. [56, > 66, 76] should return [0, 1, 2] > > Any help would be appreciated. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From stefan_ml at behnel.de Sun Jul 27 09:28:15 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 27 Jul 2008 15:28:15 +0200 Subject: Read .txt file like .py file In-Reply-To: <90f13013-bb20-4224-ac58-02947f3f9358@i24g2000prf.googlegroups.com> References: <90f13013-bb20-4224-ac58-02947f3f9358@i24g2000prf.googlegroups.com> Message-ID: <488c77ee$0$29452$9b4e6d93@newsspool4.arcor-online.net> King wrote: > I have a text file and contents are: > > Help=""" > Code is written by xteam. > """ > value = 0.0 > > > How do I read this file like python syntax. What I mean is first > readline operation should return complete declaration of 'Help' > variable. If I evaluate this string then it should create a 'Help' > variable with it's value. If you trust the author of the file and you're sure the code in the text file isn't an Internet worm and won't delete all your files, you can get away with the built-in "execfile" function. If you want more security, look at the compiler module and the ast module. They allow you to parse the file like a normal Python source file, and IIRC, there are also ways to execute single statements from a syntax tree. Stefan From gh at ghaering.de Tue Jul 15 08:17:06 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 15 Jul 2008 14:17:06 +0200 Subject: Suggestion: Python global scope In-Reply-To: References: Message-ID: Anonymous Bastard wrote: > I've been tossing this idea in my mind for some time now: > > In Python, declaring a variable using the global statement automatically > makes it available in all subsequent scopes. > > But to me, it makes more sense to use the global statement to 'import' a > variable from the global scope into the current scope. For instance: > > [code] > global X > X = 1 > > def P(): > X = 2 > print X > global X > print X > > print X > P() > print X > [code] > > Currently, this will print 1, 2, 2 and 2. But if global would be limited > to current scope, it would print 1, 2, 1, 1. > > 'X = 2' would work on the local version of X, 'global X' will 'import' > the global X into the local scope, so any actions on X would reference > the global X, rather than previous X. Anything backwards incompatible like this will never happen. -- Gerhard From mail at timgolden.me.uk Thu Jul 31 04:28:32 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 31 Jul 2008 09:28:32 +0100 Subject: win32com ChartObject pythonwin vs idle In-Reply-To: <670b57b7-d48e-44c0-abd0-b6772d23688d@79g2000hsk.googlegroups.com> References: <670b57b7-d48e-44c0-abd0-b6772d23688d@79g2000hsk.googlegroups.com> Message-ID: <489177B0.7000509@timgolden.me.uk> sterling wrote: > I'm curious as to why the difference between IDLE and pythonWin when > using win32com. > opening an excel file, i've attempted to grab the chart information > out of the file. > > commands like co = ChartObjects(1) works in pythonWin but doesn't > work in IDLE. > > however, on both co = chartobjects(1) works just fine. I can't speak for IDLE vs PythonWin but in general case-sensitivity of win32com stuff is related to early vs late Dispatch. If you've explicitly generated proxy modules for the Excel objects (via makepy, EnsureDispatch or whatever) then those are Python modules with case-sensitivity. If you're using dynamic dispatch then Python is simply passing your attribute name along to COM, which isn't case-sensitive, so either case will work. Not sure why IDLE vs PythonWin should make a difference here, but maybe the above explanation sheds some light... TJG From thomas.troeger.ext at siemens.com Fri Jul 18 09:59:49 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Fri, 18 Jul 2008 15:59:49 +0200 Subject: Using Tcl extensions with Python? References: <6f09cdf7-1156-4f41-af5f-c8e5b99eab2d@b1g2000hsg.googlegroups.com> Message-ID: C Martin wrote: > How do you setup a Tcl extension to be accessible through Python? I > understand that I'll have to use native Tcl calls to use it (tk.call() > etc), but I can't figure out where to put the files or how to > initialize them so I can call them. > > The package I would like to use is TkPNG: http://www.muonics.com/FreeStuff/TkPNG/ > > Thanks. ARGH, Tcl!!! ;-) I know that's not the question, but do you know PIL (http://www.pythonware.com/products/pil)? From usenetthrowaway at gmail.com Mon Jul 28 14:24:04 2008 From: usenetthrowaway at gmail.com (Gary) Date: Mon, 28 Jul 2008 19:24:04 +0100 Subject: Proxy server? References: <6f5rteF89muqU2@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote in message news:6f5rteF89muqU2 at mid.uni-berlin.de... > Gary wrote: > For what? A non-transparent proxy, for anonymity purposes only. From guilhem.faure at gmail.com Thu Jul 17 06:20:31 2008 From: guilhem.faure at gmail.com (Guilhem Faure) Date: Thu, 17 Jul 2008 12:20:31 +0200 Subject: Python Pmw ScrollListBox selectioncommand dblclickcommand Message-ID: <7c49f36f0807170320r60ad22cbwbf35b4b91cdfc5b5@mail.gmail.com> Hello everybody, I try to use Pmw library -> ScrollListBox. If I take the example of the reference web site (see below, I just quote the minimal code to launch, I note by <----- the line which are not execute when I click) It works, except selectioncommand and dblclickcommand: associate function doesn't run when I click one or two time. Could you have an idea about that ? Is it about my tried code ? Thank, Guilhem from Tkinter import * import Pmw #from pymol import * class Demo: def __init__(self): parent=Tk() Pmw.initialise(parent) # Create the ScrolledListBox. self.box = Pmw.ScrolledListBox(parent, items=('Sydney', 'Melbourne', 'Brisbane'), labelpos='nw', label_text='Cities', listbox_height = 6, selectioncommand=self.selectionCommand, dblclickcommand=self.defCmd, usehullsize = 1, hull_width = 200, hull_height = 200, ) # Create a group widget to contain the scrollmode options. w = Pmw.Group(parent, tag_text='Scroll mode') w.pack(side = 'bottom', padx = 5, pady = 5) hmode = Pmw.OptionMenu(w.interior(), labelpos = 'w', label_text = 'Horizontal:', items = ['none', 'static', 'dynamic'], command = self.sethscrollmode, menubutton_width = 8, ) hmode.pack(side = 'top', padx = 5, pady = 5) hmode.invoke('dynamic') vmode = Pmw.OptionMenu(w.interior(), labelpos = 'w', label_text = 'Vertical:', items = ['none', 'static', 'dynamic'], command = self.setvscrollmode, menubutton_width = 8, ) vmode.pack(side = 'top', padx = 5, pady = 5) vmode.invoke('dynamic') buttonBox = Pmw.ButtonBox(parent) buttonBox.pack(side = 'bottom') buttonBox.add('yview', text = 'Show\nyview', command = self.showYView) buttonBox.add('scroll', text = 'Page\ndown', command = self.pageDown) buttonBox.add('center', text = 'Center', command = self.centerPage) # Pack this last so that the buttons do not get shrunk when # the window is resized. self.box.pack(fill = 'both', expand = 1, padx = 5, pady = 5) # Do this after packing the scrolled list box, so that the # window does not resize as soon as it appears (because # alignlabels has to do an update_idletasks). Pmw.alignlabels((hmode, vmode)) def sethscrollmode(self, tag): self.box.configure(hscrollmode = tag) def setvscrollmode(self, tag): self.box.configure(vscrollmode = tag) def selectionCommand(self): print "toto" # <----------- doesn t run !!! def defCmd(self): print "toto2" # <----------- doen t run !!! def showYView(self): print self.box.yview() def pageDown(self): self.box.yview('scroll', 1, 'page') def centerPage(self): top, bottom = self.box.yview() size = bottom - top middle = 0.5 - size / 2 self.box.yview('moveto', middle) Demo() -------------- next part -------------- An HTML attachment was scrubbed... URL: From circularfunc at gmail.com Sun Jul 6 19:37:24 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 6 Jul 2008 16:37:24 -0700 (PDT) Subject: how are strings immutable in python? References: Message-ID: <337db7c6-0fc9-465e-b780-322c3a5cf8da@y38g2000hsy.googlegroups.com> so why would you ever want mutability? seems very counterintuitive and unreliable. From aaron.hildebrandt at gmail.com Mon Jul 21 13:30:38 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Mon, 21 Jul 2008 10:30:38 -0700 (PDT) Subject: Error importing modules with mod_python Message-ID: I've installed mod_python, and everything seems to be working, but it fails when I try to import another file into the file that's actually producing the output. I have these lines at the top of index.py: from mod_python import apache from storylab import * ... and in the directory where index.py resides (/htdocs/python/), I have a directory called "storylab". Inside that directory is __init__.py. When I try to execute /htdocs/python/index.py, I get the following error: --- MOD_PYTHON ERROR ProcessId: 828 Interpreter: 'localhost' ServerName: 'localhost' DocumentRoot: 'C:/htdocs' URI: '/python/index.py' Location: None Directory: 'C:/htdocs/python/' Filename: 'C:/htdocs/python/index.py' PathInfo: '' Phase: 'PythonHandler' Handler: 'index' Traceback (most recent call last): File "C:\Python25\lib\site-packages\mod_python\importer.py", line 1537, in HandlerDispatch default=default_handler, arg=req, silent=hlist.silent) File "C:\Python25\lib\site-packages\mod_python\importer.py", line 1202, in _process_target module = import_module(module_name, path=path) File "C:\Python25\lib\site-packages\mod_python\importer.py", line 296, in import_module log, import_path) File "C:\Python25\lib\site-packages\mod_python\importer.py", line 680, in import_module execfile(file, module.__dict__) File "C:\htdocs\python\index.py", line 2, in from storylab import * ImportError: No module named storylab --- What am I doing wrong? Any insight would be greatly appreciated. Thanks, Aaron From arkanes at gmail.com Thu Jul 17 16:03:52 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 17 Jul 2008 15:03:52 -0500 Subject: x, = y (???) In-Reply-To: References: Message-ID: <4866bea60807171303l6430ce58l16f9855fac0fd8b0@mail.gmail.com> On Thu, Jul 17, 2008 at 2:55 PM, kj wrote: > In Erik Max Francis writes: > >>kj wrote: > >>> I just came across an assignment of the form >>> >>> x, = y >>> >>> where y is a string (in case it matters). >>> >>> 1. What's the meaning of the comma in the LHS of the assignment? > >>It's unpacking a 1-tuple: > >> (x,) = y > >>The parentheses here are not necessary and are sometimes left out. > > I still don't get it. If we write > > y = 'Y' > x, = y > > what's the difference now between x and y? And if there's no > difference, what's the point of performing such "unpacking"? > > TIA! >>> y = (1,) >>> y (1,) >>> x, = y >>> x 1 >>> From bruno.desthuilliers at gmail.com Sat Jul 12 15:50:25 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 12 Jul 2008 12:50:25 -0700 (PDT) Subject: Beginner Question : Iterators and zip References: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> Message-ID: On 12 juil, 20:55, moo... at yahoo.co.uk wrote: > Hi group, > > I have a basic question on the zip built in function. > > I am writing a simple text file comparison script, that compares line > by line and character by character. The output is the original file, > with an X in place of any characters that are different. > > I have managed a solution for a fixed (3) number of files, but I want > a solution of any number of input files. > > The outline of my solution: > > for vec in zip(vec_list[0],vec_list[1],vec_list[2]): > res = '' > for entry in zip(vec[0],vec[1],vec[2]): > if len(set(entry)) > 1: > res = res+'X' > else: > res = res+entry[0] > outfile.write(res) > > So vec is a tuple containing a line from each file, and then entry is > a tuple containg a character from each line. > > 2 questions > 1) What is the general solution. Using zip in this way looks wrong. Is > there another function that does what I want zip is (mostly) ok. What you're missing is how to use it for any arbitrary number of sequences. Try this instead: >>> lists = [range(5), range(5,11), range(11, 16)] >>> lists [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15]] >>> for item in zip(*lists): ... print item ... (0, 5, 11) (1, 6, 12) (2, 7, 13) (3, 8, 14) (4, 9, 15) >>> lists = [range(5), range(5,11), range(11, 16), range(16, 20)] >>> for item in zip(*lists): ... print item ... (0, 5, 11, 16) (1, 6, 12, 17) (2, 7, 13, 18) (3, 8, 14, 19) >>> The only caveat with zip() is that it will only use as many items as there are in your shorter sequence, ie: >>> zip(range(3), range(10)) [(0, 0), (1, 1), (2, 2)] >>> zip(range(30), range(10)) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)] >>> So you'd better pad your sequences to make them as long as the longer one. There are idioms for doing this using the itertools package's chain and repeat iterators, but I'll leave concrete example as an exercice to the reader !-) > 2) I am using set to remove any repeated characters. Is there a > "better" way ? That's probably what I'd do too. > Any other comments/suggestions appreciated. There's a difflib package in the standard lib. Did you give it a try ? From michele.simionato at gmail.com Mon Jul 7 23:44:57 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 7 Jul 2008 20:44:57 -0700 (PDT) Subject: Dynamically Changing the Base Class References: <6d60c362-ba17-4414-babd-2cc254526bca@c58g2000hsc.googlegroups.com> Message-ID: <46e28471-54fc-4d15-b136-c17c35326bb3@t54g2000hsg.googlegroups.com> On Jul 7, 8:08?pm, "Adam C." wrote: > Thanks. I think we would want new-style classes, and 6-year-old > patches strike me as maybe a little out of the desired path... so this > really just doesn't work in modern Python? Can you use (multiple) inheritance instead of changing the bases? Alternatively, try using an old-style class, changing the bases and subclassing it inheriting from object too: class NewStyle(OldStyle, object): pass From Samnsparky at gmail.com Thu Jul 10 11:51:34 2008 From: Samnsparky at gmail.com (Sparky) Date: Thu, 10 Jul 2008 08:51:34 -0700 (PDT) Subject: Local User Control Message-ID: I don't know how feasible this is, but is it possible to have users log in to access a local database file in such a way that allows the program to know what user name and password they logged in with? This would involve separate user names and passwords for each user. Thanks for your time and help, Sam From basti.wiesner at gmx.net Mon Jul 14 14:00:29 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Mon, 14 Jul 2008 20:00:29 +0200 Subject: subprocess module References: <2e7f0504-cc1c-4cb6-b2d0-b67b004eca7d@x41g2000hsb.googlegroups.com> <39622612-5e43-45b4-800a-69277c2e2987@79g2000hsk.googlegroups.com> Message-ID: Peter Otten <__peter__ at web.de>: > - communicate() waits for the subprocess to terminate. > - stdout.read() is retried if an EINTR occurs (Not sure when this would > happen). EINTR happens, if the "read" syscall is interrupted by a signal handler. For instance, if a daemon handles SIGUSR to re-read its configuration, and the user issues SIGUSR in exactly that very moment, the daemon wants to read from a pipe, the read attempt would fail with EINTR. Shouldn't happen that often ... -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From subhabrata.iisc at hotmail.com Sat Jul 12 06:16:22 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Sat, 12 Jul 2008 03:16:22 -0700 (PDT) Subject: Use of index Message-ID: Dear All, I have a small question. If I have code line like the following: a1="God" a2="God is always great" a3=a2.index(a1) a4=a2.find(a1) a5=a2.split() a6=a5.index(a1) a7=a5.find(a1) # Invalid as find is applicable only in string but not in list. if a4>-1: print "God may be always great" -------------------------------------------------------------- Now, my q is can we use index like find? Regards, Subhabrata. From bruno.desthuilliers at gmail.com Sat Jul 12 14:35:01 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sat, 12 Jul 2008 11:35:01 -0700 (PDT) Subject: why is "self" used in OO-Python? References: Message-ID: <00530f42-d086-4449-a6ca-7a9a65903d10@m3g2000hsc.googlegroups.com> On 12 juil, 18:32, ssecorp wrote: > I first learned about OO from Java. > > I much prefer to program in Python though. > > However I am consufed about 2 things. > > 1. Why do I have to pass self into every method in a class? You mean "declare self as the first argument", I assume ? This has been explained many times here. Anyway: the point is that what you define is not a method, but a function. This function needs to have a way to get at the instance on which it's called, and the simplest way to do so is to use the common way: passing it as an argument. This avoids having to have two different constructs - functions and methods - when one is enough. > Since I am > always doing why cant this be automated or abstracted away? This could, probably, but you'd had complexity, break uniformity and loose some interesting features of the language. > > 2. self.item instead of getters and setters. I thought one of the main > purposes of OO was encapsulation. I don't know if it's "one of the main purposes", but you're missing the point: you have to use explicit getters and setters in Java because Java doesn't have any support for computed attributes. In Python, the object.attribute syntax doesn't mean you are directly accessing an instance attribute. First because lookup rules are more complex than that (not only the instance, but also it's class and it's class parents are looked up), then because there are several ways to hook into these lookup rules. Given that you can decouple the interface (looks like an access attribute) from the implementation (anything from an instance attribute to a method call in a distantly related class, possibly including a network connection and database access), you just don't need explicit getters and setters when directly accessing an instance attribute is enough (and that's more than often the case). > Doesn't messing with internal object- > representations break this? It does, indeed, but it's sometimes necessary (as a matter of fact, there are ways to get at private attributes even in Java). Anyway, this is unrelated to your above question about getters and setters. > I see how the getters and setters could be just visual clutter and you > have to add them to every class so it is annoying a bit in the same > way as self described above. > However I feel like I want getters and setters when I write classes, > not sure of the advantages/disadvantages though. Unless you need to do something else than accessing an instance attribute, explicit getters and setters in Python are a pure waste of time for you, anyone using your code, and even the computer. > Only looking at the documentation of a Python-class, will internal > representations be provided? For which definition of "internal representation" ? > If I have a class: > > class Stack(object): > def __init__(self, *items): > self.stack = list(items) > > def append(self, item): > self.stack.append(item) # OT : canonically, it's stac.push(item), not stack.append(item) > def pop(self): > return self.stack.pop() > > I can get to see the stack with var.stack but then why even implement > append when I could do self.stack.append(x) etc. Because you may want to change the implementation, as usual. But you shouldn't expose stack as part of your API. The convention in Python is to name implementation stuff with a leading underscore. This a *very* strong convention saying "don't mess with this unless you know exactly what you're doing and are willing and able to take full responsability if you break anything or if your code breaks when I'll change my class implementation". So just rename 'stack' to '_stack', and anyone using your class will ignore it unless they have a pretty good reason to mess with it and are ok to suffer the potential consequences. > That way you could do away with OO completely. You could, but what would be the point ? Why would I mess with implementation when I get what I need using the API ? > So why let people > access the main attribute but not let them manipulate it? You just can't stop them from manipulating it if they really want, you know. Don't worry, whatever the language, if someone want to mess with implementation, he will find a way. > Makes more sense to draw the line to not access any attributes at all > no? No. Most programmers are of at least median intelligence, and won't even have a look at your implementation as long as they can - because they don't want to have to worry about implementation. As long as you clearly marked something as being "implementation, don't touch", and provided a sound API, then you've done your job. I know this can sound disturbing when coming from the ultra-dogmatic chains-and-bondage world of Java, but from experience (from dozens of years of thousands of programmers), Python's pragmatic approach JustWorks(tm). From tjreedy at udel.edu Tue Jul 8 22:21:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 08 Jul 2008 22:21:31 -0400 Subject: (silly?) speed comparisons In-Reply-To: References: Message-ID: mk wrote: > Out of curiosity I decided to make some speed comparisons of the same > algorithm in Python and C++. Moving slices of lists of strings around > seemed like a good test case. If you use Python to, in effect, call well-written C functions, and most of the computation time is spent in the C functions, then the total time may be less than using C++ to call C or C++ functions that have not been as heavily optimized. (Python is nearly 2 decades old, and several people have perused the code base looking for speedups.) From samwyse at gmail.com Thu Jul 10 15:38:27 2008 From: samwyse at gmail.com (samwyse) Date: Thu, 10 Jul 2008 12:38:27 -0700 (PDT) Subject: Problems Returning an HTTP 200 Ok Message References: <1cf880cc-2036-42dc-8217-d52a714c1710@a70g2000hsh.googlegroups.com> Message-ID: <9bc65e72-be16-4f73-9dfb-6ddeaae34c21@m73g2000hsh.googlegroups.com> On Jul 10, 1:50?pm, Guy Davidson wrote: > Hi Folks, > > I'm having some issues with an small socket based server I'm writing, > and I was hoping I could get some help. > > My code (attached below) us supposed to read an HTTP Post message > coming from a power meter, parse it, and return a proper HTTP 200 Ok > message. The problem is that the socket fails to send the entire > message as one message, creating a fragmented message which the power > meter then fails to read and accept. > > Is there any way to force the socket to send the entire message at > once? Am I doing anything wrong? Is there an easier way to implement > this functionality? By 'message', do you mean a single IP datagram? In general, the answer is no. Each call to 'connection.send()' will (in general, see the next paragraph) transmit as much data as will fit into a single IP datagram, given the current MTU for the transmission circuit. The fact that you're calling it in a loop indicates that the data being sent may be larger than will fit into a datagram. Or, by 'message', do you mean a single TCP segment? Again, the answer is no. Your network stack will try to make the TCP segments the right size to fit within a single IP datagram, leading to the same result as above. From your description, I get the feeling that your power meter has a broken network stack, and you're trying to program around it. You need to repair the meter. From pavlovevidence at gmail.com Tue Jul 29 04:37:45 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 01:37:45 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> Message-ID: <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> On Jul 28, 8:15 pm, Steven D'Aprano wrote: > On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: > > On Jul 28, 10:00 am, Steven D'Aprano > cybersource.com.au> wrote: > >> Cutting to the crux of the discussion... > > >> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: > >> > I want something where "if x" will do but a simple explicit test > >> > won't. > > >> Explicit tests aren't simple unless you know what type x is. If x could > >> be of any type, you can't write a simple test. Does x have a length? Is > >> it a number? Maybe it's a fixed-length circular length, and the length > >> is non-zero even when it's empty? Who knows? How many cases do you need > >> to consider? > > > Use case, please. I'm asking for code, not arguments. Please give me a > > piece of code where you can write "if x" that works but a simple > > explicit test won't. > > I gave you a piece of code, actual code from one of my own projects. If > you wouldn't accept that evidence then, why would you accept it now? I would accept as "evidence" something that satisfies my criteria, which your example did not: it could have easily (and more robustly) been written with a simple explicit test. I am looking for one that can't. You keep bringing up this notion of "more complex with no benefit", which I'm simply not interested in talking about that at this time, and I won't respond to any of your points. I am seeking the answer to one question: whether "if x" can usefully do something a simple explicit test can't. Everyone already knows that "if x" requires fewer keystrokes and parses to fewer nodes. Carl Banks From M8R-yfto6h at mailinator.com Sun Jul 6 17:55:35 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Sun, 6 Jul 2008 14:55:35 -0700 Subject: how are strings immutable in python? References: Message-ID: "ssecorp" wrote in message news:a08a6406-6d54-402c-9271-9d1940f3dff6 at z72g2000hsb.googlegroups.com... > so if strings were mutable and i did > a = b = "foo" > and then did > a += "bar" > then a and b would be foobar? This can be demonstrated with a list of characters, which *is* mutable: >>> a = b = list('foo') >>> a += list('bar') >>> a ['f', 'o', 'o', 'b', 'a', 'r'] >>> b ['f', 'o', 'o', 'b', 'a', 'r'] --Mark From jim.hefferon at gmail.com Tue Jul 1 19:55:28 2008 From: jim.hefferon at gmail.com (Jim) Date: Tue, 1 Jul 2008 16:55:28 -0700 (PDT) Subject: convert unicode characters to visibly similar ascii characters References: Message-ID: <17d4c282-8606-4d29-9e71-d34f5e6d13bb@m44g2000hsc.googlegroups.com> Peter Bulychev wrote: > I want to convert unicode character into ascii one. You have to make some arbitrary choices of what to translate. Based on some materials on effbot's site, and a recipe, I made ftp://alan.smcvt.edu/hefferon/unicode2ascii.py which has at least some of what you are looking for. $ grep HYPHEN unicode2ascii.py u'\N{SOFT HYPHEN}':u'-', u'\N{HYPHEN}':u'-', u'\N{NON-BREAKING HYPHEN}':u'-', u'\N{SOFT HYPHEN}': '-', No doubt I have some terrible gaffes and some things missing. Corrections appreciated. Jim From george.sakkis at gmail.com Thu Jul 3 19:24:23 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 3 Jul 2008 16:24:23 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> <7db52b03-7a8a-40c4-b3cb-f6dccd273b90@59g2000hsb.googlegroups.com> Message-ID: On Jul 3, 5:49?pm, Mensanator wrote: > On Jul 3, 2:52?pm, Terry Reedy wrote: > > > Worthless to you, worthwhile to me. ? > > The OP's opinion is the only one that matters. I bet the OP doesn't know (or care) what gmpy is. > What do you suppose > is the percentage of posts on this newsgroup by those using 3.0? Taking into account 2.6 too (we're not talking about only 3.0 here), probably not much less than those who even know what is gmpy, let alone dismiss a beta Python release because their obscure pet module is not available yet. You will probably sound less negative if you refrain from projecting your own very specialized needs to those of the average pythonista. George From goldspin at gmail.com Mon Jul 28 00:43:52 2008 From: goldspin at gmail.com (Henry Chang) Date: Sun, 27 Jul 2008 21:43:52 -0700 Subject: Command line arguements In-Reply-To: <73045cca0807272113y397de468yfcb00ffbbec7990a@mail.gmail.com> References: <73045cca0807272113y397de468yfcb00ffbbec7990a@mail.gmail.com> Message-ID: try optparse :) http://docs.python.org/lib/module-optparse.html On Sun, Jul 27, 2008 at 9:13 PM, aditya shukla wrote: > Hello folks ,I have a program in which a text file is generated as an > output > eg > > C:\prog\ prog -x test.txt > Right now whenever i have to read the test file i have to put its name > manually in my code. > eg > f=open("c:\\prog\\test.txt","r") > > How ever i want to add the name of the test file dynamically to my program > ie , if every time i give > > C:\prog\ prog -x test.txt > The filename (test.txt) automatically comes in > f=open("c:\\prog\\test.txt","r") > > C:\prog\ prog -x file1.txt > f=open("c:\\prog\\file1","r") > > > in other words i do not want to do hard code the name of the file in my > code every time i need to read it. > > I was reading about the sys module and i guess sys.argv would take the > input from the command line whenever i run the python script . > > Please guide me in the right direction on how to tackle the problem. > > Thanks in advance > > Aditya > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wmcbrine at users.sf.net Mon Jul 28 14:59:13 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Mon, 28 Jul 2008 18:59:13 GMT Subject: Questions on 64 bit versions of Python References: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> <488cbeeb$0$17104$9b622d9e@news.freenet.de> Message-ID: <5Gojk.254$wS4.153@trnddc03> On Sun, 27 Jul 2008 20:31:07 +0200, Martin v. L?wis wrote: > Originally, AMD called it x86-64, and later renamed it to AMD64. Intel > originally implemented it under the name EM64T (for Extended Memory 64 > Technology), and now calls the architecture Intel 64. I hadn't heard "Intel 64" before. That's a bit nervy, isn't it? Plus it seems to conflict with their own use of "IA-64" (Intel Architecture 64) for the Itanium (vs. "IA-32" for traditional x86). -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From kurdayon at yahoo.com Tue Jul 1 17:24:48 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Tue, 1 Jul 2008 14:24:48 -0700 (PDT) Subject: How to make a function associated with a class? References: <69e26f9b-2f00-4318-9bc5-6aa94e141bca@59g2000hsb.googlegroups.com> <4d7cf477-e791-4122-bc20-0dbd1a16bc12@j22g2000hsf.googlegroups.com> Message-ID: <0d9c534b-8720-4363-b3e5-eb546dd3637c@8g2000hse.googlegroups.com> On Jul 1, 5:01 pm, "bruno.desthuilli... at gmail.com" wrote: > On 1 juil, 22:43, Kurda Yon wrote: > > > > > Hi, > > > I have a class called "vector". And I would like to define a function > > "dot" which would return a dot product of any two "vectors". I want > > to call this function as follow: dot(x,y). > > > Well, I can define a functions "dot" outside the class and it works > > exactly as I want. However, the problem is that this function is not > > associated with the class (like methods a method of the class). > > > For example, if I call "x.calc()" or "y.calc()", python will execute > > different methods if "x" and "y" belongs to different classes. I want > > to have the same with my "dot" function. I.e. I want it calculates the > > dot product ONLY IF the both arguments of that function belong to the > > "vector" class. > > > Is it possible? > > You don't need to make dot() a method of your Vector class to have > this behaviour, and making it a method of the Vector class isn't > enough to have this behaviour. > > The simplest solution would be: > > class Vector(object): > def dot(self, other): > if not isinstance(other, type(self)): > raise TypeError("can only calculate the dot product of two > vectors") > # do the job here and return what's appropriate > > Now since it's a binary operator, you might as well implement it as > such: > > class Vector(object): > def __mul__(self, other): > if not isinstance(other, type(self)): > raise TypeError("can only calculate the dot product of two > vectors") > # do the job here and return what's appropriate > > Then use it as doproduct = vector1 * vector2 > > HTH As far as I understood, In the first case, you gave, I need to call the function as follows "x.dot(y)". In the second case I need to call the function as follows "x*y". But I want to call the function as follows "dot(x,y)". By the way, "type(self)" returns the name of the class to which the "self" belongs? Does "instance" return "true" if the first argument belongs to the class whose name is given in the second argument? From aspersieman at gmail.com Thu Jul 24 04:10:29 2008 From: aspersieman at gmail.com (Aspersieman) Date: Thu, 24 Jul 2008 10:10:29 +0200 Subject: Autocompletion and Interactive Tables in a Python IDE In-Reply-To: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> References: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Message-ID: <488838F5.20803@gmail.com> Anthony wrote: > Hi, I'm a FoxPro programmer, but I want to learn python before it's > too late. I do a lot of statistical programming, so I import SPSS > into python. In my opinion, the best features of Visual FoxPro 9.0 > were: > a) Intellisense (tells you what classes/methods are available and what > variables go into a function) > b) Code Completion (guesses your code after four letters) > c) Data-Orientation; multiple data sessions can be open, data can be > viewed easily > > Python's IDLE has only half of the first of these features. I did a > lot of searching and found the PyDev extensions for Eclipse's Python > IDE, and found that they've got Intellisense. I'm still missing b and > c, and am getting extremely frustrated programming so slowly.. > > So two questions: > Is there any package, gui, IDE, anything that will do FoxPro-style > code completion? If it works in Eclipse, even better.. > I can't find a good screenshot, but here's a better description: > You type "BROW" and it pops up a window that says "BROWSE" ..at this > point if you hit enter it completes the word.. > > and > > How can I view open SPSS data in one of the Python GUIs? Again, > Eclipse would be the preference. > Here's an example of how I'd like to browse the data: > http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=vfptoolkit_figure02.tif > I don't want to have to switch back and forth between Python and SPSS > while I'm programming; I just want to stay in one of them.. > > What can I do? I feel extremely inefficient when I don't have these > three features.. > > Thanks in advance. > -- > http://mail.python.org/mailman/listinfo/python-list > > You might want to try vim. It has a steep learning curve, but definitely increases productivity _alot_. Here is a tutorial on setting up vim with : 1) Code completion (intellisense) - including tooltips (!!!) 2) Jump between your python code and the python class libraries. 3) Syntax checking 4) A handy source browser 5) Debugging (using pdb) 6) [All the other vim goodies - already included] Above instructions available here http://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/ I have been using the above setup for a while and find it superior to _any_ IDE I've ever worked with. I'm not sure what you mean by 'Data-Orientation' but I'm sure there's a suitable alternative/replacement for it in vim. Regards Nicolaas -- The three things to remember about Llamas: 1) They are harmless 2) They are deadly 3) They are made of lava, and thus nice to cuddle. From s0suk3 at gmail.com Tue Jul 15 09:59:33 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Tue, 15 Jul 2008 06:59:33 -0700 (PDT) Subject: Modify a string's value Message-ID: Hi everyone, I've heard that a 'str' object is immutable. But is there *any* way to modify a string's internal value? Thanks, Sebastian From mensanator at aol.com Thu Jul 3 09:54:58 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 3 Jul 2008 06:54:58 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> Message-ID: On Jul 3, 2:13?am, Bruno Desthuilliers wrote: > Terry Reedy a ?crit : > > > > > Mensanator wrote: > (snip) > >> Lookup "Cartesian Product". > (snip) > >> for a in [True,False]: > >> ? for b in [True,False]: > >> ? ? for c in [1,2,3,4]: > >> ? ? ? print 'combined settings:',a,'\t',b,'\t',c > > > This has been added to itertools at least for 2.6/3.0 > > Great ! Well, it will be great at some point in the future when Python 2.6/3.0 have actually been released and third party extensions such as gmpy have caught up. Until then, such solutions are worthless, i.e., of no value. From socyl at 987jk.com.invalid Tue Jul 29 17:31:01 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 21:31:01 +0000 (UTC) Subject: static variables in Python? References: Message-ID: In Larry Bates writes: >kj wrote: >> Yet another noob question... >> >> Is there a way to mimic C's static variables in Python? Or something >> like it? The idea is to equip a given function with a set of >> constants that belong only to it, so as not to clutter the global >> namespace with variables that are not needed elsewhere. >> >> For example, in Perl one can define a function foo like this >> >> *foo = do { >> my $x = expensive_call(); >> sub { >> return do_stuff_with( $x, @_ ); >> } >> }; >> >> In this case, foo is defined by assigning to it a closure that has >> an associated variable, $x, in its scope. >> >> Is there an equivalent in Python? >> >> Thanks! >> >> kynn >First names in Python are just that, names that point to objects. Those objects >can contain any type of information including other objects. They are NOT >buckets where things are stored. >1) Names (variables in Perl/C) defined within a Python function are placed in >its local namespace. They are not visible in the global namespace. >2) Yes you can have a local name point to a global. This is often used in >classes with attributes because looking up local is somewhat quicker than >looking up the class attribute. >def foo(): > x = expensive_call > return do_stuff_with(x()) Maybe I'm missing your point, the goal is to have a "runtime constant" associated with the function. In the your definition of foo, expensive_call gets called every time that foo gets called; this is what I'm trying to avoid! Maybe it's easier to see what I mean with JavaScript: function foo() { if (foo.x === undefined) foo.x = expensive_call(); return do_stuff_with(foo.x); } Here, expensive_call is called only once (assuming it never returns undefined). OK, I guess that in Python the only way to do what I want to do is with objects... kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From kay.schluehr at gmx.net Sun Jul 20 01:13:34 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 19 Jul 2008 22:13:34 -0700 (PDT) Subject: Best Python packages? References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> <17861f55-8ad1-4703-ad22-838675f2afc4@w1g2000prk.googlegroups.com> <86b446d2-0d11-4410-bf89-a2a05fac81b2@s50g2000hsb.googlegroups.com> Message-ID: <086cffec-44a8-4eac-ac67-f9ae4f30a61b@d77g2000hsb.googlegroups.com> On 20 Jul., 05:54, "Python Nutter" wrote: > I think the hidden gems in multimedia/game production are Pyglet and > Rabbyt. Whereas PyGame is the older api, its large and bloated and has > of course a heavy dependency on SDL. Pyglet and Rabbyt are > lightweight, efficient, have some amazing functions and hit native > OpenGL in all the major OS distributions and Bruce The Presentation > Tool utilizes the former to take on MS PowerPoint to show what you can > do besides games =) > > Pyglet:http://pyglet.org/ > Rabbyt:http://matthewmarshall.org/projects/rabbyt/ > Bruce The Presentation Tool:http://code.google.com/p/bruce-tpt/ > > Cheers, > PN > > > > > In the original post you asked for "hidden gems" and now it seems you > > just want to know about Madonna or Justin Timberlake. > > > Maybe a look on this collection helps > > >http://wiki.python.org/moin/UsefulModules > > -- > >http://mail.python.org/mailman/listinfo/python-list Maybe someone starts a blog with the title "Hidden Pythons"? Just one short remark about Python game toolkits. The single reason I won't use them is browser accessibility. It doesn't matter to me where Python scripts are running but less so where applications are executed. Right now I'm stuck with AS3/Flash. Given Adobes recent OSS commitments and PyPys efforts in translating RPython to several backends I'm not too pessimistic that we'll see Python in the Flashplayer in a year or two from now. From claird at lairds.us Thu Jul 3 22:02:29 2008 From: claird at lairds.us (Cameron Laird) Date: Fri, 4 Jul 2008 02:02:29 +0000 Subject: Testing for an empty list References: <18268092.post@talk.nabble.com> Message-ID: In article , Matthew Fitzgibbons wrote: >Alexnb wrote: >> Okay this is a simple question I just don't know how. If I have a list, say: >> >> funList = [] >> >> and after a while something possible should have been appended to it, but >> wasn't. How can I test if that list is empty. > >if not funList: > do_something() . . . It's also perfectly legitimate--and arguably even more precise--to write if funList == []: do_something() From bignose+hates-spam at benfinney.id.au Mon Jul 7 03:14:10 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 07 Jul 2008 17:14:10 +1000 Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> <6ddj74F21uhjU1@mid.individual.net> Message-ID: <874p72xj25.fsf@benfinney.id.au> TP writes: > Peter Pearson wrote: > > > When you tell python "print '\033[30;44m foo \033[0m'", python > > interprets the "\033" as a single character. > > So, the python print command *can* interpret these 4-character as a > single character. Not "interpret", no. It's more accurate to say that the Python *compiler* will translate "\033" within a string literal into a single character in the compiled executable byte code. That is, the input to the Python interpreter will not have "\033" in the string literal at all, but instead a single character produced by the Python compiler at that point in the byte code. > It would be odd if there were no possibility to do the same thing > when the characters are (i) stored in a python variable, or (ii) > come from the environment variables. Since those are not the input to the Python compiler, they can't be translated this way. -- \ ?You know I could rent you out as a decoy for duck hunters?? | `\ ?Groucho Marx | _o__) | Ben Finney From M8R-yfto6h at mailinator.com Tue Jul 15 02:39:25 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Mon, 14 Jul 2008 23:39:25 -0700 Subject: Python pack and unpack question References: Message-ID: "joe shoemaker" wrote in message news:mailman.25.1216087716.922.python-list at python.org... > If you have the following: > > data = unpack('>L', sock.recv(4)) > > Does this line of code means that incoming data is big endian and > unpack it to endianess of local machine? If local machine is little > endian, then big endian is automatically converted to little endian > format? > > thank you. Try it: >>> data = unpack('>L','\xaa\xbb\xcc\xdd') >>> data (2864434397L,) >>> hex(data[0]) '0xaabbccddL' >>> data = unpack('>L','\x11\x22\x33\x44') >>> data (287454020,) >>> hex(data[0]) '0x11223344' >>> Yes, it treats the incoming data as big-endian. The Python data type returned varies as needed to hold the value. You'd get the same results on a big-endian and little-endian local machine. How the Python data type is represented internally is an implementation detail and could be anything. -- Mark From gh at ghaering.de Wed Jul 30 09:15:33 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 30 Jul 2008 15:15:33 +0200 Subject: variable expansion with sqlite In-Reply-To: <489059DC.5090501@timgolden.me.uk> References: <489059DC.5090501@timgolden.me.uk> Message-ID: Tim Golden wrote: > marc wyburn wrote: >> Hi I'm using SQlite and the CSV module and trying to create a class >> that converts data from CSV file into a SQLite table. >> >> My script curently uses functions for everything and I'm trying to >> improve my class programming. The problem I'm having is with variable >> expansion. >> >> self.cursor.executemany('INSERT INTO test VALUES (?)', CSVinput) >> >> If CSVinput is a tuple with only 1 value, everything is fine. If I >> want to use a tuple with more than 1 value, I need to add more >> question marks. As I'm writing a class I don't want to hard code a >> specific number of ?s into the INSERT statement. >> >> The two solutions I can think of are; >> using python subsitution to create a number of question marks, but >> this seems very dirty >> or >> finding someway to substitue tuples or lists into the statement - I'm >> not sure if this should be done using Python or SQLite substitution >> though. > > > I do this kind of thing sometimes: > > > a,b,c > 1,2,3 > 4,5,6 > > > > import csv > import sqlite3 > > reader = csv.reader (open ("test.csv", "rb")) > csv_colnames = reader.next () > > db = sqlite3.connect (":memory:") > coldefs = ", ".join ("%s VARCHAR (200)" % c for c in csv_colnames) > db.execute ("CREATE TABLE test (%s)" % coldefs) > > insert_cols = ", ".join (csv_colnames) > insert_qmarks = ", ".join ("?" for _ in csv_colnames) > insert_sql = "INSERT INTO test (%s) VALUES (%s)" % (insert_cols, > insert_qmarks) > > db.executemany (insert_sql, list (reader)) > for row in db.execute ("SELECT * FROM test"): > print row > > > > Obviously, this is a proof-of-concept code. I'm (ab)using > the convenience functions at database level, I'm hardcoding > the column definitions, and I'm making a few other assumptions, but I > think it serves as an illustration. [..] My code would probably look very similar. Btw you don't need to use list() on an iterable to pass to executemany(). pysqlite's executemany() accepts anything iterable (so generators work fine, too). Also, with SQLite you can just skip data type definitions like VARCHAR(200). They're ignored anyway. -- Gerhard From deets at nospam.web.de Wed Jul 23 06:39:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 23 Jul 2008 12:39:56 +0200 Subject: Strange problem .... References: <12fd8ef1-c7e0-470b-ba51-f946d8ea8e26@z6g2000pre.googlegroups.com> Message-ID: <6eog5rF82itrU1@mid.uni-berlin.de> karthikbalaguru wrote: > Hi, > > I am new to python, Kindly suggest to resolve a problem with a python > file. > What does the below error refer to ? > I use Redhat 9.0, python-2.2.2-26, python-devel-2.2.2-26 and > db4-4.0.14-20. > > [root at localhost processor]# Analyzer processorcycle > /usr/local/SDK/bin/../core/bin/processorlib.py:8 > 8: Warning: 'yield' will become a reserved keyword in the future > Traceback (most recent call last): > File "/usr/local/SDK/bin/Analyzer", line 48, in ? > from debuglib import ProcessorInfo > File "/usr/local/SDK/bin/../core/bin/processorlib.py", line 88 > yield ProcessorObjectInfo(child, self.pt) > ^ > SyntaxError: invalid syntax > > Is this error related with the version of python / python-devel that i > use . > Any ideas / tips ? I asked you yesterday why you are under the impression that your script is destined for version 2.2. The above error proves: it is *not*. Why don't you try running it with the installed version 2.4 or whatever fedora ships? Diez From frank at chagford.com Tue Jul 29 07:09:27 2008 From: frank at chagford.com (Frank Millman) Date: Tue, 29 Jul 2008 04:09:27 -0700 (PDT) Subject: Questions about asyncore Message-ID: <5d30aad5-cad7-4e47-aa83-277202c70ae2@z72g2000hsb.googlegroups.com> Hi all I have been using my own home-brewed client/server technique for a while, using socket and select. It seems to work ok. The server can handle multiple clients. It does this by creating a new thread for each connection. Each thread runs its own select loop. I am making some fairly big changes, so I thought I would look at asyncore. I modified my program to use asyncore without much trouble, and it feels nicer. It uses async I/O instead of threading, and it relieves me of having to run my own select loop. I have two questions. They both relate to whether I am using the module as intended. The documentation is rather sparse, and I know from experience that just getting something working is no guarantee that I am getting the full benefit. Firstly, having got asyncore working, I had a look at asynchat. As far as I can see I get very little benefit from using it. I have already set up a 'messaging' protocol between server and client, where all messages consist of 5 digits for the message length, followed by the message. The message consists of a pickled tuple, where the first element is a message identifier, and the rest is the message body. This is how it works in asyncore - def __init__(self,channel): [...] self.msgLength = 0 self.recvData = '' # temporary buffer def handle_read(self): self.recvData += self.recv(8192) if not self.msgLength: if len(self.recvData) < 5: # 1st 5 bytes = msg length return self.msgLength = int(self.recvData[:5]) self.recvData = self.recvData[5:] if len(self.recvData) < self.msgLength: return data = loads(self.recvData[:self.msgLength]) self.recvData = self.recvData[self.msgLength:] self.msgLength = 0 [handle data] This is how I got it working in asynchat - def __init__(self,channel): [...] self.recvData = '' # temporary buffer self.set_terminator(5) self.gotMsgLength = False def collect_incoming_data(self, data): self.recvData += data def found_terminator(self): if self.gotMsgLength: # what follows is the message data = loads(self.recvData) self.set_terminator(5) self.gotMsgLength = False [handle data] else: # what follows is the message length self.set_terminator(int(self.recvData)) self.gotMsgLength = True self.recvData = '' It may be slightly neater, but it does not seem worth adding an extra layer just for that. Does asynchat give me any other benefits I may have overlooked? My second question relates to writing a dummy client program to test the server. I just want to send it some messages and print the responses. Some messages incorporate data extracted from previous responses, so I have to wait for the reply before continuing. I am using asyncore for this as well. However, the only way I can think of to get it working is to run asyncore.dispatcher in a separate thread. To send messages, I append them to a list of messages to be sent. The dispatcher method writable() returns True if there is anything in the list, else False. To receive messages, I run a 'while 1' loop in the main thread, with a sleep of 0.1, until recvData has something in it. It works, but it seems odd to use a separate thread, as one of the points of asyncore is to avoid multi-threading. Is there a better way to write the client program? Thanks Frank Millman From __peter__ at web.de Wed Jul 30 14:15:39 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 Jul 2008 20:15:39 +0200 Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: <2a703a46-75bc-4228-95d1-05a4e6030b40@f63g2000hsf.googlegroups.com> <26c2fe8e-d464-44f0-8e57-3b8e82248691@x35g2000hsb.googlegroups.com> Message-ID: Paul Boddie wrote: > Who wants to be first to submit a patch? ;-) And where? The sourceforge page says "PyXML is no longer maintained." Peter From urizev at gmail.com Sat Jul 5 17:31:23 2008 From: urizev at gmail.com (Urizev) Date: Sat, 5 Jul 2008 23:31:23 +0200 Subject: Singleton implementation problems In-Reply-To: References: <87abgy2kcu.fsf@benfinney.id.au> Message-ID: Great! Thanks everyone for so many references and comments. Lots of doubts have been solved. On Fri, Jul 4, 2008 at 10:33 AM, Peter Otten <__peter__ at web.de> wrote: > Ben Finney wrote: > >> Peter Otten <__peter__ at web.de> writes: >> >>> The problem is the structure of your program. The myset module is >>> imported twice by Python, once as "myset" and once as "__main__". >> >> Yes, this is the problem. Each module imports the other. >> >>> Therefore you get two distinct MySet classes, and consequently two >>> distinct MySet.__instance class attributes. >> >> Are you sure? This goes against my understanding: that 'import foo' >> will not re-import a module that's already been imported, but will >> instead simply return the existing module. > > The main script is put into the sys.modules cache as "__main__", not under > the script's name. Therefore the cache lookup fails. > >> So, I think if one evaluated 'myset is __main__', you'd find they are >> exactly the same module under different names; and therefore that >> there is only *one* instance of 'MySet', again under two names. > > No: > > $ cat tmp.py > import tmp > import __main__ > > print tmp is __main__ > > $ python tmp.py > False > False > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > -- Saludos Juan Carlos "??Viva lo rancio!!" From keith.hughitt at gmail.com Wed Jul 16 10:53:56 2008 From: keith.hughitt at gmail.com (Keith Hughitt) Date: Wed, 16 Jul 2008 07:53:56 -0700 (PDT) Subject: Angle brackets in command-line arguments? Message-ID: <52f1cde3-6240-46b0-8b03-478454e87688@b1g2000hsg.googlegroups.com> Hi all, I am using someone else's script which expects input in the form of: ./script.py arg2 I was wondering if the angle-brackets here have a special meaning? It seems like they specify an input and output stream to use in place of the console. I could not find anything in the python manual or Python in a Nut-shell though. Anyone know? Thanks, Keith From google at mrabarnett.plus.com Sun Jul 20 17:52:34 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 20 Jul 2008 14:52:34 -0700 (PDT) Subject: regex doubts References: <532965.570.qm@web54502.mail.re2.yahoo.com> <504d473e-375a-4111-ae2e-c06aaa37b096@p25g2000pri.googlegroups.com> <5a77d3ef-2313-4f3a-9486-d27136ac0409@b1g2000hsg.googlegroups.com> <0d3a6680-3dce-4353-b389-c0e3b2930847@j1g2000prb.googlegroups.com> Message-ID: <5a8416e9-b436-4ae4-b188-6c66b218e8d3@27g2000hsf.googlegroups.com> On Jul 19, 10:44?pm, John Machin wrote: > On Jul 20, 6:35 am, MRAB wrote: > > > > > On Jul 19, 9:12 pm, John Machin wrote: > > > > On Jul 20, 5:04 am, Fredrik Lundh wrote: > > > > > Mr SZ wrote: > > > > > I am taking a string as an input from the user and it should only > > > > > contain the chars:L , M or R > > > > > > I tried the folllowing in kodos but they are still not perfect: > > > > > > [^A-K,^N-Q,^S-Z,^0-9] > > > > > [L][M][R] > > > > > [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > > > > > > For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. > > > > > try "[LRM]+$" (an L or an R or an M, one or more times, all the way to > > > > the end of the string). > > > > Ummm ... with the default flag settings, shouldn't that be \Z instead > > > of $ > > > ? > > > $ means end of string unless the multiline flag is used, in which case > > it means end of line. > > What manual are you quoting that from? What version of Python are you > using? Can you demonstrate that the pattern "[LRM]+$" will fail to > match the string "L\n"? > I see what you mean: $ does match end of line if the newline is the last character of the string. From rocksportrocker at googlemail.com Thu Jul 17 08:15:13 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 17 Jul 2008 05:15:13 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Message-ID: <09811f1f-c007-49a6-bb13-f92ec9ccc030@a70g2000hsh.googlegroups.com> On 17 Jul., 00:20, Craig Allen wrote: > > I have several classes in our system which need to act like > singletons, they are libraries of data classifications, and other such > libraries of configurations for the system which need to be global. > ... > > Is it pythonic? My approach in this situation is to use the Borg pattern instead of singeltons. This is really pythonic, very simple and usefull. Look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 The german wikipedia shows another solution using metaclasse: http://de.wikipedia.org/wiki/Singleton_(Entwurfsmuster)#Das_Borg-Pattern Greetings, Uwe From tjreedy at udel.edu Sun Jul 13 13:49:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 13 Jul 2008 13:49:52 -0400 Subject: Beginner Question : Iterators and zip In-Reply-To: <0ea30e6f-fcf4-4f39-a091-10b2a2178efd@l64g2000hse.googlegroups.com> References: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> <0ea30e6f-fcf4-4f39-a091-10b2a2178efd@l64g2000hse.googlegroups.com> Message-ID: moogyd at yahoo.co.uk wrote: > What is this *lis operation called? I am having trouble finding any > reference to it in the python docs or the book learning python. One might call this argument unpacking, but Language Manual / Expressions / Primaries / Calls simply calls it *expression syntax. "If the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments; if there are positional arguments x1,...,*xN* , and expression evaluates to a sequence y1,...,*yM*, this is equivalent to a call with M+N positional arguments x1,...,*xN*,*y1*,...,*yM*." See Compound Statements / Function definitions for the mirror syntax in definitions. tjr From nodrogbrown at gmail.com Fri Jul 4 09:10:21 2008 From: nodrogbrown at gmail.com (gordon) Date: Fri, 4 Jul 2008 06:10:21 -0700 (PDT) Subject: origin of error message Message-ID: hi i was trying to create an image using user selection of a file in tix fileselection box ..and i check for exception like below ... from string import split from os.path import basename ... #this is done inside __init__method self.imgsel=FileSelectBox(self.imgSelectFrame) ... def button1Click(self): starttime=datetime.now() self.okButton.configure(state=DISABLED) #will clear canvas self.canvorig.delete(ALL) self.canvresult.delete(ALL) self.resultdisplay.delete(ALL) #image file selection by tix widget self.cursel=self.imgsel.selection.cget("value") print "self.cursel:",self.cursel self.imgsel.selection.selection_clear() #here i want to check if anything is selected by user if self.cursel: ext=split(basename(self.cursel),'.')[1] print "image extn:",ext try: self.selimg=ImageTk.PhotoImage(file=self.cursel) except Exception,inst: print "xceptn::",inst.message self.showresult(inst.message,"red") else: self.selimgtag=self.canvorig.create_image(70,100,image=self.selimg) self.canvorig.update_idletasks() ..... # some other tasks done ..... else: #no file was selected by user print "self.cursel=",self.cursel self.showresult("nothing selected","red") self.okButton.configure(state=NORMAL) endtime=datetime.now() print "total time:", endtime-starttime,"seconds" user is supposed to select an image to be displayed. when i select some file with a non compatible extension (say .zip) i get the following output >>>> self.cursel: F:/docs/python/gui3.zip image extn: zip xceptn:: cannot identify image file total time: 0:00:00.341000 seconds Exception exceptions.AttributeError: "PhotoImage instance has no attribute '_Pho toImage__photo'" in > ignored My belief was that the message 'total time: 0:00:00.341000 seconds ' should have been the last output message .I don't know where the Exception exceptions.AttributeError: etc comes from. Already i am catching the exception when creating PhotoImage .The message 'xceptn:: cannot identify image file' comes from there Can someone help me find how this error msg happens gordon From emen999 at gmail.com Thu Jul 24 06:03:17 2008 From: emen999 at gmail.com (code_berzerker) Date: Thu, 24 Jul 2008 03:03:17 -0700 (PDT) Subject: lxml, comparing nodes References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <6c91a4da-6443-4570-8dd3-01c4ec169bf3@t54g2000hsg.googlegroups.com> > off the top of my head (untested): > > ?>>> def equal(a, b): > ... ? ? if a.tag != b.tag or a.attrib != b.attrib: > ... ? ? ? ? return False > ... ? ? if a.text != b.text or a.tail != b.tail: > ... ? ? ? ? return False > ... ? ? if len(a) != len(b): > ... ? ? ? ? return False > ... ? ? if any(not equal(a, b) for a, b in zip(a, b)): > ... ? ? ? ? return False > ... ? ? return True > > this should work for arbitrary ET implementations (lxmk, xml.etree, ET, > etc). ?tweak as necessary. > > Thanks for help. Thats inspiring, tho not exactly what I need, coz ignoring document order is requirement (ignoring changes in order of different siblings of the same type, etc). I plan to try something like that: def xmlCmp(xmlStr1, xmlStr2): et1 = etree.XML(xmlStr1) et2 = etree.XML(xmlStr2) queue = [] tmpq = deque([et1]) tmpq2 = deque([et2]) while tmpq: el = tmpq.popleft() tmpq.extend(el) queue.append(el.tag) while queue: el = queue.pop() foundEl = findMatchingElem(el, et2) if foundEl: et1.remove(el) tmpq2.remove(foundEl) else: return False if len(tmpq2) == 0: return True else: return False def findMatchingElem(el, eTree): for elem in eTree: if elemCmp(el, elem): return elem return None def elemCmp(el1, el2): pass # yet to be implemented ;) From michele.simionato at gmail.com Fri Jul 11 13:03:55 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 11 Jul 2008 10:03:55 -0700 (PDT) Subject: decorator to prevent adding attributes to class? References: <98c6e83e-4a54-49ce-a32e-f03f5ab97f28@k13g2000hse.googlegroups.com> Message-ID: <6936f3a9-5402-4b41-9d55-315d251c402d@34g2000hsf.googlegroups.com> On Jul 11, 6:38?pm, Robert Bossy > I don't get it. Why use a metaclass? Wouldn't the following be the same, > but easier to grasp: > > class Frozen(object): > ? ? def __setattr__(self, name, value): > ? ? ? ?if not hasattr(self, name): > ? ? ? ? ? raise AttributeError, "cannot add attributes to %s" % self > ? ? ? ?object.__setattr__(self, name, value) This is easier, but it does not stop the user from adding class level attributes: this is the job of the metaclass. If you don't care about class level attributes (including methods, properties, etc) and you are content with restricting only the instance attributes your recipe is fine, yes. From straton at lampsacos.demon.co.uk Fri Jul 18 05:47:36 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 18 Jul 2008 10:47:36 +0100 Subject: % sign in python? In-Reply-To: References: Message-ID: Terry Reedy wrote: > > > korean_dave wrote: >> What does this operator do? Specifically in this context >> >> test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) >> >> (Tried googling and searching, but the "%" gets interpreted as an >> operation and distorts the search results) > > Having seen a number of comments like this over the years (about the > difficulty of searching for symbol meanings), I just started, last > night, a symbol index listing nearly all Python syntax uses of > non-alpha-or-digit ascii symbols. When I finish and upload it > somewhere, I will post an announcement with the link. > > tjr > This will be excellent, Terry. For the present case, perhaps we should also point out that in python 3.0: " Note The formatting operations described here are obsolete and may go away in future versions of Python. Use the new String Formatting in new code." (Taken from the provisional documentation at: http://docs.python.org/dev/3.0/library/stdtypes.html#old-string-formatting ) From you2000too at gmail.com Tue Jul 22 08:17:28 2008 From: you2000too at gmail.com (youtoo) Date: Tue, 22 Jul 2008 05:17:28 -0700 (PDT) Subject: Time Complexity of String Operations References: Message-ID: <8a7fc656-aa91-4609-9502-21be6596e5bf@25g2000hsx.googlegroups.com> On 22 jul, 01:39, "David Wahler" wrote: > On Mon, Jul 21, 2008 at 10:31 PM, youtoo wrote: > > It has been extensively discussed the time complexity (quadratic) of > > string concatenation (due to string's immutability). > > Actually, it is roughly linear, at least for reasonable string lengths: > > $ python -V > Python 2.5.2 > $ python -mtimeit -s "n=1000; a='#'*n" "a+a" > 1000000 loops, best of 3: 1 usec per loop > $ python -mtimeit -s "n=10000; a='#'*n" "a+a" > 100000 loops, best of 3: 5.88 usec per loop > $ python -mtimeit -s "n=100000; a='#'*n" "a+a" > 10000 loops, best of 3: 59.8 usec per loop > > Repeatedly constructing a string by appending a constant number of > characters at a time, however, is quadratic in the final string length > (although VM optimizations may affect this). > > > But what is: > > > == the time complexity of string indexing? Is it constant? > > Yes. > > > == the time complexity of string slicing? Is it O(K) with K the > > slice's length? > > I suspect so, since the time is dominated by the time taken to copy > the data into a new string object. > > > How are strings stored in Python? As arrays? As linked lists? > > Arrays; see Include/stringobject.h in the Python source distribution. > > -- David Thank you very much! yt. From knielsen73 at gmail.com Wed Jul 23 21:32:50 2008 From: knielsen73 at gmail.com (knielsen73 at gmail.com) Date: Wed, 23 Jul 2008 18:32:50 -0700 (PDT) Subject: fill in 3D array References: <3180f972-f2d4-43ff-81de-bcdd0a2ef906@59g2000hsb.googlegroups.com> Message-ID: <49fd3d80-d062-4c39-8274-f0b717486ad4@z66g2000hsc.googlegroups.com> On Jul 23, 9:18 pm, Robert Kern wrote: > knielse... at gmail.com wrote: > > Hi, > > > I am a python newbie, trying to convert my IDL scripts to python. I am > > kind of stuck at the moment. I am reading in a 1-D data file with 2000 > > data points. I need to put them in a 3-D array with size [10,10,20]. I > > have defined the field array as arr = zeros((10,10,20)) but don't know > > how to read the data into the array. > > I assume that you are using numpy. Use numpy.fromfile() and the .reshape() > method. Assuming that your file is ASCII with numbers separated by whitespace: > > import numpy > arr = numpy.fromfile(thefilename, sep=' ').reshape((10,10,20)) > > There is no need, in this case, to create an array before reading the data. > > > Also, I need to extract a slice of a 3-D array and tried a = > > array_name(:,:,20) but that didn't work. > > Python uses [] brackets for indexing, not (). > > arr[:,:,20] > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco Thanks, working like a charm. From rajanikanth at gmail.com Tue Jul 8 20:32:31 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Tue, 8 Jul 2008 17:32:31 -0700 Subject: a simple 'for' question In-Reply-To: <4874017D.2000401@umbc.edu> References: <4874017D.2000401@umbc.edu> Message-ID: <84bdef3c0807081732q33b3bccdvc1d2c361d8c34d80@mail.gmail.com> Hi! Try this for x in folders: open('my/path/way'+x+'myfile.txt','r') Cheers, Raj On Tue, Jul 8, 2008 at 5:08 PM, Ben Keshet wrote: > Hi fans, > > I want to use a 'for' iteration to manipulate files in a set of folders, > something like: > > folders= ['1A28','1A6W','56Y7'] > for x in folders: > print x # print the current folder > f = open('my/path/way/x/my_file.txt', 'r') > ... > > where 'x' in the pathway should iterate over '1A28','1A6W','56Y7'. How > should I identify 'x' in the pathway line as the same x that is iterating > over 'folders'? > > I am getting the following error: > > Traceback (most recent call last): > File > "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Linux\Dock_method_validation\myscripts\test_for.py", line 5, in > > f = open('c:/Linux/Dock_method_validation/x/receptor.mol2', 'r') > IOError: [Errno 2] No such file or directory: > 'c:/Linux/Dock_method_validation/x/receptor.mol2' > > I tired several variations: %x, 'x', "x", etc. all gave me similar errors. > > Thanks for your help, > BK > -- > http://mail.python.org/mailman/listinfo/python-list > -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From callen314 at gmail.com Thu Jul 17 18:26:34 2008 From: callen314 at gmail.com (Craig Allen) Date: Thu, 17 Jul 2008 15:26:34 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> <09811f1f-c007-49a6-bb13-f92ec9ccc030@a70g2000hsh.googlegroups.com> Message-ID: <25516604-0050-4300-b071-4c80dc99a5b7@f1g2000prb.googlegroups.com> On Jul 17, 2:15 am, Uwe Schmitt wrote: > On 17 Jul., 00:20, Craig Allen wrote: > > > > > I have several classes in our system which need to act like > > singletons, they are libraries of data classifications, and other such > > libraries of configurations for the system which need to be global. > > ... > > > Is it pythonic? > > My approach in this situation is to use the Borg pattern instead > of singeltons. This is really pythonic, very simple and usefull. > > Look athttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 > The german wikipedia shows another solution using metaclasse:http://de.wikipedia.org/wiki/Singleton_(Entwurfsmuster)#Das_Borg-Pattern > > Greetings, Uwe thanks uwe, doing some searching I ran into the borg pattern this morning. Definitely relevant. Thanks again and all for the feedback, I feel much reassured about the options when this sort of thing is required. From justin.mailinglists at gmail.com Fri Jul 4 05:59:31 2008 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Fri, 4 Jul 2008 02:59:31 -0700 (PDT) Subject: Newbie, list has no attribute iteritems References: <12caa75c-455a-4ab3-a9c3-4bd191b6965d@k13g2000hse.googlegroups.com> Message-ID: def handle_starttag(self, tag, attrs): # <-- attrs here is a list if 'a' != tag: self.stack.append(self.__html_start_tag(tag, attrs)) # <-- attrs here is still a list return attrs = dict(attrs) # <-- now attrs is a dictionary From sjmachin at lexicon.net Tue Jul 29 22:16:39 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 29 Jul 2008 19:16:39 -0700 (PDT) Subject: static variables in Python? References: <39a2e1f0-b919-4065-8a7a-e3a4b837a347@25g2000hsx.googlegroups.com> <27e92c0a-840a-4341-9185-3d8099ad1e99@w7g2000hsa.googlegroups.com> Message-ID: <913e8721-35b4-4e17-afd9-00c550411c86@u6g2000prc.googlegroups.com> On Jul 30, 11:57 am, "Russ P." wrote: > On Jul 29, 6:33 pm, "Russ P." wrote: > > > > > On Jul 29, 1:40 pm, kj wrote: > > > > Yet another noob question... > > > > Is there a way to mimic C's static variables in Python? Or something > > > like it? The idea is to equip a given function with a set of > > > constants that belong only to it, so as not to clutter the global > > > namespace with variables that are not needed elsewhere. > > > > For example, in Perl one can define a function foo like this > > > > *foo = do { > > > my $x = expensive_call(); > > > sub { > > > return do_stuff_with( $x, @_ ); > > > } > > > > }; > > > > In this case, foo is defined by assigning to it a closure that has > > > an associated variable, $x, in its scope. > > > > Is there an equivalent in Python? > > > > Thanks! > > > > kynn > > > -- > > > NOTE: In my address everything before the first period is backwards; > > > and the last period, and everything after it, should be discarded. > > > If the constant parameters are really only needed in one particular > > function, you can use default function arguments. An added benefit is > > that you can override them with another value if necessary. > > > def fun(x, y, parameter1=0, parameter2=1): > > ... > > I should add that the parameters need not be literal numbers. They can > be computed values as well. They will be computed only once, on the > first pass through the function definition, which I presume is exactly > what you want. > > I think this is the simplest solution to the problem you posed. Here's a real-life example, where the second and third args are run- time constants: def unescape(s, subber=re.compile(r'_x[0-9A-Fa-f]{4,4}_').sub, repl=lambda mobj: unichr(int(mobj.group(0)[2:6], 16)), ): if "_" in s: return subber(repl, s) return s # The if test is just an optimisation that unfortunately the re module doesn't nut out for itself. Cheers, John From winter at biotec.tu-dresden.de Mon Jul 28 06:32:58 2008 From: winter at biotec.tu-dresden.de (Christof Winter) Date: Mon, 28 Jul 2008 12:32:58 +0200 Subject: SOAPpy WSDL problem: namespace of schema and import match error Message-ID: <6f5lirF9vmv1U1@mid.dfncis.de> I am trying to use a webservice with SOAPpy: import SOAPpy intact_wsdl = "http://www.ebi.ac.uk/intact/binary-search-ws/binarysearch?wsdl" intact_serv = SOAPpy.WSDL.Proxy(intact_wsdl) The resulting error message is posted below. If I understand it right, XMLSchema.py complains about the imported XSD namespace being the same as the existing targetNamespace. Perl and Java have no problems with the WSDL document (see sample code at http://www.ebi.ac.uk/~intact/devsite/remote/binarysearch_ws.html) My question: - Is there a problem with the WSDL file being not valid? - Is there a problem with the Python SOAP/WSDL implementation? Any suggestions? Christof > Traceback (most recent call last): > File "testEBIIntactWebservice.py", line 3, in > intact_serv = SOAPpy.WSDL.Proxy(intact_wsdl) > File "/var/lib/python-support/python2.5/SOAPpy/WSDL.py", line 62, in __init__ > self.wsdl = reader.loadFromStream(stream, wsdlsource) > File "/var/lib/python-support/python2.5/SOAPpy/wstools/WSDLTools.py", line 34, in loadFromStream > wsdl.load(document) > File "/var/lib/python-support/python2.5/SOAPpy/wstools/WSDLTools.py", line 260, in load > schema = reader.loadFromNode(WSDLToolsAdapter(self), item) > File "/var/lib/python-support/python2.5/SOAPpy/wstools/XMLSchema.py", line 80, in loadFromNode > schema.load(reader) > File "/var/lib/python-support/python2.5/SOAPpy/wstools/XMLSchema.py", line 1076, in load > tp.fromDom(node) > File "/var/lib/python-support/python2.5/SOAPpy/wstools/XMLSchema.py", line 1177, in fromDom > raise SchemaError, 'namespace of schema and import match' > SOAPpy.wstools.XMLSchema.SchemaError: namespace of schema and import match From toby at tobiah.org Tue Jul 1 15:26:44 2008 From: toby at tobiah.org (Tobiah) Date: Tue, 01 Jul 2008 12:26:44 -0700 Subject: Getting sorting order References: <7cb9ebb7-e722-41e1-bdf2-693954a21b92@j22g2000hsf.googlegroups.com> Message-ID: >>>> master,slave1,slave2=zip(*x) What does the asterisk do here? Thanks ** Posted from http://www.teranews.com ** From dominik.raymann at gmail.com Mon Jul 28 11:54:48 2008 From: dominik.raymann at gmail.com (raymi) Date: Mon, 28 Jul 2008 08:54:48 -0700 (PDT) Subject: Using Python Modules from JAVA Message-ID: <65861251-6a40-44a2-b2e3-48928bb2e1d0@z72g2000hsb.googlegroups.com> Hi all, I'd like to use the pygments syntax highlighting module from within a JAVA application. While I understand how to use Jython to execute a script file or interpret single statements, I don't know how I can use a whole module (i.e. the several files pygments consists of). In order to deploy the application easily I don't want to install Jython or anything else on the system and then call pygment's installer from the shell. I imagine being able to just copy a jar (e.g. jython.jar) and an egg file to the target system and load the module in JAVA. Is this possible? Has anybody any experience with that? Thanks in advance for your help, raymi From tonal at promsoft.ru Wed Jul 30 23:46:14 2008 From: tonal at promsoft.ru (Alexandr N Zamaraev) Date: Thu, 31 Jul 2008 10:46:14 +0700 Subject: Interbase In-Reply-To: References: Message-ID: <48913586.1070602@promsoft.ru> Mike Hjorleifsson wrote: > Has anyone gotten python working with Interbase database platform ? I See KInterbasDB: http://kinterbasdb.sourceforge.net/ From samirg at lorentzsolution.com Fri Jul 11 18:57:14 2008 From: samirg at lorentzsolution.com (Samir Grover) Date: Fri, 11 Jul 2008 15:57:14 -0700 Subject: PyQt QScrollView/QGridLayout question Message-ID: <1215817034.3117.29.camel@localhost.localdomain> folks, I am trying put some user input fields into a scrollable (QScrollView) window. So, I placed a QLabel at 0,0 and QLineEdit at 0,1, next to QLabel. Somehow, results are not what I am expecting.It is placing QLineEdit below QLabel. I am not using designer for this. Please, notice that I convert vbox's box layout into grid layout, so that, I can place QLabel at 0,0 and QLineEdit at 0,1. But it does not do that. any advice on correcting this piece of code will be helpfull. regards, here is how this code looks like: ----- import sys, qt from qt import * class MyDialog(QDialog): def __init__(self,parent = None,name = None,modal = 0,fl = 0): QDialog.__init__(self,parent,name,modal,fl) if not name: self.setName("MyDialog") self.setSizeGripEnabled(1) self.build_window() def build_window(self): toplayout = QGridLayout(self,1,1,11,6,"toplayout") vbMain = qt.QVBox(self) toplayout.addWidget(vbMain, 0, 0) sview = qt.QScrollView(vbMain) vp = sview.viewport() vbox = qt.QVBox(vp) sview.addChild(vbox) vplayout = qt.QGridLayout(vp, 0, 0, 1,-1, 'vpl') vplayout.addWidget(vbox, 0, 0) grid = qt.QGridLayout(vbox.layout(), 2, 2) ll = qt.QLabel('circuit name', vbox) grid.addWidget(ll, 0,0, qt.Qt.AlignLeft) nameinput = qt.QLineEdit(vbox) grid.addWidget(nameinput, 0,1, qt.Qt.AlignLeft) if __name__ == "__main__": app = QApplication(sys.argv) f = MyDialog() f.show() app.setMainWidget(f) app.exec_loop() From babacity4 at gmail.com Thu Jul 24 16:53:12 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:53:12 -0700 (PDT) Subject: www Xxxstash - Amazing porn video collection Message-ID: <1e062eee-4685-4722-bf87-51aaab0b1851@z11g2000prl.googlegroups.com> www xxxstash . >>>>>>>>>>Best Collection of Xxxstash Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE www xxxstash VIDEOS<<<<<<<<<<< . www xxxstash From jr9445 at ATT.COM Thu Jul 17 15:56:27 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 17 Jul 2008 14:56:27 -0500 Subject: properly delete item during "for item in..." In-Reply-To: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> References: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Ratko > Sent: Thursday, July 17, 2008 12:27 PM > To: python-list at python.org > Subject: properly delete item during "for item in..." > > Say you have something like this: > > for item in myList: > del item > > Would this actually delete the item from the list or just decrement > the reference counter because the item in myList is not associated > with name "item" anymore (but still is with myList[itemIndex])? In > other words, is "item" a temporary reference to myList[itemIndex] or > is it actually that reference that myList has stored? > > I am not sure if this question even makes any sense anymore. I've been > using python for years and never had any problems (and I don't now > either) but now that I had to revisit c++/STL, I had to deal about > these issues and was wondering how python does it. > Walk the list backwards when deleting. master = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print "Deletes nothing" a = master[:] print a for i in a: del i print a print print print "Deletes safely from end" a = master[:] print a for i in range(len(a)-1, -1, -1): print i if i % 2 == 0: print " removing ", master[i] del a[i] print " ", a, if master[i] in a: print "Ooops, deleted wrong thing...", print print a print print print "Delete from front. Deletes wrong things and throws an exception..." a = master[:] print a #for i in range(len(a)-1, -1, -1): for i in range(len(a)): print i if i % 2 == 0: print " removing ", master[i] del a[i] print " ", a, if master[i] in a: print "Ooops, deleted wrong thing...", print print a From gnewsg at gmail.com Tue Jul 29 09:40:10 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Tue, 29 Jul 2008 06:40:10 -0700 (PDT) Subject: Questions about asyncore References: <5d30aad5-cad7-4e47-aa83-277202c70ae2@z72g2000hsb.googlegroups.com> Message-ID: On 29 Lug, 13:09, Frank Millman wrote: > Firstly, having got asyncore working, I had a look at asynchat. As far > as I can see I get very little benefit from using it. I have already > set up a 'messaging' protocol between server and client, where all > messages consist of 5 digits for the message length, followed by the > message. The message consists of a pickled tuple, where the first > element is a message identifier, and the rest is the message body. > > This is how it works in asyncore - > > def __init__(self,channel): > [...] > self.msgLength = 0 > self.recvData = '' # temporary buffer > > def handle_read(self): > self.recvData += self.recv(8192) > if not self.msgLength: > if len(self.recvData) < 5: # 1st 5 bytes = msg length > return > self.msgLength = int(self.recvData[:5]) > self.recvData = self.recvData[5:] > if len(self.recvData) < self.msgLength: > return > data = loads(self.recvData[:self.msgLength]) > self.recvData = self.recvData[self.msgLength:] > self.msgLength = 0 > [handle data] > > This is how I got it working in asynchat - > > def __init__(self,channel): > [...] > self.recvData = '' # temporary buffer > self.set_terminator(5) > self.gotMsgLength = False > > def collect_incoming_data(self, data): > self.recvData += data > > def found_terminator(self): > if self.gotMsgLength: # what follows is the message > data = loads(self.recvData) > self.set_terminator(5) > self.gotMsgLength = False > [handle data] > else: # what follows is the message length > self.set_terminator(int(self.recvData)) > self.gotMsgLength = True > self.recvData = '' > > It may be slightly neater, but it does not seem worth adding an extra > layer just for that. Does asynchat give me any other benefits I may > have overlooked? The benefit of asynchat is that it automatically handles the buffering of both input and output. Aside from set/found_terminator() the other two methods you could want to look at are push() and push_with_producer(). push() is a buffered version of asyncore.send(), push_with_producer() accepts a data-producer object you can use in case you want to deal with something other than strings (e.g. files, lists, generators, and so on...). > My second question relates to writing a dummy client program to test > the server. I just want to send it some messages and print the > responses. Some messages incorporate data extracted from previous > responses, so I have to wait for the reply before continuing. > > I am using asyncore for this as well. However, the only way I can > think of to get it working is to run asyncore.dispatcher in a separate > thread. > > To send messages, I append them to a list of messages to be sent. The > dispatcher method writable() returns True if there is anything in the > list, else False. > > To receive messages, I run a 'while 1' loop in the main thread, with a > sleep of 0.1, until recvData has something in it. > > It works, but it seems odd to use a separate thread, as one of the > points of asyncore is to avoid multi-threading. Is there a better way > to write the client program? I'm not sure to understand but I doubt you have to use a thread. If you "have to wait for the reply before continuing" just implement this logic into handle_read() or found_terminator() method. --- Giampaolo http://code.google.com/p/pyftpdlib/ From cs at zip.com.au Thu Jul 24 18:43:55 2008 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 25 Jul 2008 08:43:55 +1000 Subject: Gracefull application exit. Message-ID: <20080724224355.GA30988@cskk.homeip.net> On 24Jul2008 17:30, Robert Rawlins wrote: | > but mind the caveats: | | Thanks Tim, the main caveat which worries me is the fact that it doesn't get | called when being killed by SIGTERM. When I look at implementing the | application as Daemon will cause complications. | The implementation looks nice and is certainly the way I would like to go, | but unless it'll work when killed by sigterm it likely won't be for me. If you catch SIGTERM with the signal module and call sys.exit() they should fire. This all gets harder with threads. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ We _like_ the starter! Wouldn't have it any other way. If it doesn't grind, take it back to the dealer and make them fix it! - Jon N. Steiger, DoD#1038, From Russ.Paielli at gmail.com Mon Jul 28 15:00:49 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jul 2008 12:00:49 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> <6a5506b1-632e-4bf6-b0ce-4d51d1751aa9@i24g2000prf.googlegroups.com> <8b4b11c3-e306-4fe7-82d1-0a948c725f2f@r15g2000prd.googlegroups.com> <239a084f-b73d-4c20-aaaf-bbd05d452638@a2g2000prm.googlegroups.com> <8f675d65-e302-4428-a4bc-f494b230cb59@w1g2000prk.googlegroups.com> <744c27d4-e166-4b3a-9c2c-d4bf1a207fb8@a2g2000prm.googlegroups.com> <553e2d69-7ac7-4b27-bd09-4c35548ce5ec@a3g2000prm.googlegroups.com> Message-ID: <09a41b92-5f4f-4fe6-9592-bb06c17374ca@u12g2000prd.googlegroups.com> On Jul 28, 2:52 am, alex23 wrote: > On Jul 28, 3:07 pm, "Russ P." wrote: > > > What was "suggested in rejected" on the thread you pointed me to was > > not what I suggested. Not even close. Get it, genius? > > *sigh* Clearly I don't have better things to do right now than waste > my time. > > You wrote: > > So why not allow something like this?: > > class MyClass: > > def func( , xxx, yyy): > > .xxx = xxx > > local = .yyy > > The "self" argument is replaced with nothing, but a comma is used as a > > placeholder. > > Philip Eby suggested in the thread I linked to: > > > def .aMethod(arg1, arg2): > > return .otherMethod(arg1*2+arg2) > > In other words, 'self' here is uniformly replaced by an empty string. > > So you honestly see no similarity between your suggestion and the > latter? > > Or do you seriously think that placing an errant comma in the argument > list is somehow substantively different from placing a period before > the function name? Yes, in terms of Python syntax, it's completely different. Forget the empty first argument. As I explained in other posts on this thread, it is not even needed for my proposal. It was just a distraction from the main idea. From steve at REMOVE-THIS-cybersource.com.au Sun Jul 27 04:13:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Jul 2008 08:13:53 GMT Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <009c29cc$0$20302$c3e8da3@news.astraweb.com> On Sun, 27 Jul 2008 10:23:06 +0800, Marcus.CM wrote: > Well after reading some of these posts on "sacred python cow" on the > "self" , i would generally feel that most programmers who started with > C++/Java would find it odd. You know, there are some programmers who haven't started with C++ or Java. > And its true, i agree completely there > should not be a need to put "self" into every single member function. If > you were writing an application and one of your classes adds the same > variable to each of its member function you would do away with it too. Would I? How would I do that here? # untested class FunnyNumber(int): """Silly class that acts like an integer, only one larger.""" def __add__(self, other): return int(self)+1+other def __mul__(self, other): return (self+1)*other def __sub__(self, other): return int(self)+1-other -- Steven From Scott.Daniels at Acm.Org Wed Jul 16 08:40:30 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 16 Jul 2008 05:40:30 -0700 Subject: Python internals In-Reply-To: <008d93af$0$20327$c3e8da3@news.astraweb.com> References: <008ca729$0$20313$c3e8da3@news.astraweb.com> <87hcaq7pja.fsf@benfinney.id.au> <008d93af$0$20327$c3e8da3@news.astraweb.com> Message-ID: Peter Anderson wrote: > Thanks everyone! Just a quick correction - "as the original poster is" > is a bit of a jump that does not reflect my original question. I DO > understand how C and other programming languages handle variables > internally (the bits of actual memory reserved, etc. etc.) and that's > why I asked the question in the first place. > > If Python doesn't do it like C and the others then what mechanism does > it use - it's the sort of issue that helps me understand how the > language is interacting with the underlying operating system/hardware. The easiest way to think of this is that Python uses mostly dictionaries dictionaries for namespaces, and a few places it uses other techniques if there are over-riding considerations that make the dictionaries impractical in particular cases. Python performance would be crippled if their dictionary implementation(s) slowed down, much as C performance would suffer is access to RAM slowed down. --Scott David Daniels Scott.Daniels at Acm.Org From Ilan.i18n at gmail.com Sat Jul 12 14:39:38 2008 From: Ilan.i18n at gmail.com (Ilan) Date: Sat, 12 Jul 2008 11:39:38 -0700 (PDT) Subject: Does omniORBpy 3.2 supports DII? References: <20080710164217.da8448a3.feliphil@gmx.net> Message-ID: <9ac3c420-7be7-4c7b-839c-a5d89eed309e@8g2000hse.googlegroups.com> On 10 ????, 17:42, Wolfgang Keller wrote: > > My apologies if this is not the correct forum for thses quiestions, > > It's not the wrong place to ask, but you're more likely to get answers > from the omniORB mailing lists: > > http://www.omniorb-support.com/mailman/listinfo > > Sincerely, > > Wolfgang Thank you for your response. I already posted this question at that list, i did not get any response yet.. From spython01 at gmail.com Mon Jul 21 15:06:39 2008 From: spython01 at gmail.com (Samir) Date: Mon, 21 Jul 2008 12:06:39 -0700 (PDT) Subject: Converting List of String to Integer Message-ID: Hi Everyone, I am relatively new to Python so please forgive me for what seems like a basic question. Assume that I have a list, a, composed of nested lists with string representations of integers, such that a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] I would like to convert this to a similar list, b, where the values are represented by integers, such as b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] I have unsuccessfully tried the following code: n = [] for k in a: n.append([int(v) for v in k]) print n Does anyone know what I am doing wrong? Thanks in advance. Samir From fredrik at pythonware.com Fri Jul 25 07:08:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 13:08:38 +0200 Subject: scanf in python In-Reply-To: <4889ae4a$0$3726$426a74cc@news.free.fr> References: <4884be5e$0$19722$426a74cc@news.free.fr> <6ek4cgF7hq4vU1@mid.uni-berlin.de> <4884e77a$0$29405$426a74cc@news.free.fr> <4889ae4a$0$3726$426a74cc@news.free.fr> Message-ID: AMD wrote: >> For reading delimited fields in Python, you can use .split string method. > Yes, that is what I use right now, but I still have to do the conversion > to integers, floats, dates as several separate steps. What is nice about > the scanf function is that it is all done on the same step. Exactly like > when you use % to format a string and you pass it a dictionary, it does > all the conversions to string for you. You're confusing surface syntax with processing steps. If you want to do things on one line, just add a suitable helper to take care of the processing. E.g. for whitespace-separated data: >>> def scan(s, *types): ... return tuple(f(v) for (f, v) in zip(types, s.split())) ... >>> scan("1 2 3", int, int, float) (1, 2, 3.0) This has the additional advantage that it works with any data type that provides a way to convert from string to that type, not just a small number of built-in types. And you can even pass in your own local helper, of course: >>> def myfactory(n): ... return int(n) * "!" ... >>> scan("1 2 3", int, float, myfactory) (1, 2.0, '!!!') If you're reading multiple columns of the same type, you might as well inline the whole thing: data = map(int, line.split()) For other formats, replace the split with slicing or a regexp. Or use a ready-made module; there's hardly every any reason to read standard CSV files by hand when you can just do "import csv", for example. Also note that function *creation* is relatively cheap in Python, and since "def" is an executable statement, you can create them pretty much anywhere; if you find that need a helper somewhere in your code, just put it there. The following is a perfectly valid pattern: def myfunc(...): def myhelper(...): ... myhelper(...) myhelper(...) for line in open(file): myhelper(...) (I'd say knowing when and how to abstract things away into a local helper is an important step towards full Python fluency -- that is, the point where you're able to pack "a lot of action in a small amount of clear code" most of the time.) From doug.farrell at gmail.com Wed Jul 9 12:47:32 2008 From: doug.farrell at gmail.com (writeson) Date: Wed, 9 Jul 2008 09:47:32 -0700 (PDT) Subject: Anyone happen to have optimization hints for this loop? References: <43111321-2cc1-4a5e-9189-744131555841@26g2000hsk.googlegroups.com> Message-ID: <080b4c75-ef41-477b-967b-05bf5c445dd1@d1g2000hsg.googlegroups.com> On Jul 9, 12:04?pm, dp_pearce wrote: > I have some code that takes data from an Access database and processes > it into text files for another application. At the moment, I am using > a number of loops that are pretty slow. I am not a hugely experienced > python user so I would like to know if I am doing anything > particularly wrong or that can be hugely improved through the use of > another method. > > Currently, all of the values that are to be written to file are pulled > from the database and into a list called "domainVa". These values > represent 3D data and need to be written to text files using line > breaks to seperate 'layers'. I am currently looping through the list > and appending a string, which I then write to file. This list can > regularly contain upwards of half a million values... > > count = 0 > dmntString = "" > for z in range(0, Z): > ? ? for y in range(0, Y): > ? ? ? ? for x in range(0, X): > ? ? ? ? ? ? fraction = domainVa[count] > ? ? ? ? ? ? dmntString += " ?" > ? ? ? ? ? ? dmntString += fraction > ? ? ? ? ? ? count = count + 1 > ? ? ? ? dmntString += "\n" > ? ? dmntString += "\n" > dmntString += "\n***\n > > dmntFile ? ? = open(dmntFilename, 'wt') > dmntFile.write(dmntString) > dmntFile.close() > > I have found that it is currently taking ~3 seconds to build the > string but ~1 second to write the string to file, which seems wrong (I > would normally guess the CPU/Memory would out perform disc writing > speeds). > > Can anyone see a way of speeding this loop up? Perhaps by changing the > data format? Is it wrong to append a string and write once, or should > hold a file open and write at each instance? > > Thank you in advance for your time, > > Dan Hi Dan, Looking at the code sample you sent, you could do some clever stuff making dmntString a list rather than a string and appending everywhere you're doing a +=. Then at the end you build the string your write to the file one time with a dmntFile.write(''.join(dmntList). But I think the more straightforward thing would be to replace all the dmntString += ... lines in the loops with a dmntFile.write(whatever), you're just constantly adding onto the file in various ways. I think the slowdown you're seeing your code as written comes from Python string being immutable. Every time you perform a dmntString += ... in the loops you're creating a new dmntString, copying in the contents of the old, plus the appended content. And if your list can reach a half a million items, well that's a TON of string create, string copy operations. Hope you find this helpful, Doug From duncan.booth at invalid.invalid Sun Jul 13 16:16:14 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Jul 2008 20:16:14 GMT Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> Message-ID: "Giampaolo Rodola'" wrote: > Thanks, that's what I wanted to know. > I understand that heapq is not that efficient to implement timeouts as > I thought at first. > It would have been perfect if there were functions to remove arbitrary > elements withouth needing to re-heapify() the heap every time. > Thanks for your help anyway. > > There could be suitable functions, but there aren't any. I *think* this would work (untested): def popitem(heap, pos): if pos == 0: return heappop(heap) if pos == len(heap)-1: return heap.pop(pos) res = heap[pos] heap[pos] = heap.pop() heapq._siftup(heap, pos) return res the catch is that _siftup is written in Python whereas the publicly exposed heapq functions are written in C, so although in theory this is 'more efficient' than calling heapify() on the entire heap it may actually be slower. Bottom line though is that heaps aren't really suitable for timeouts. From bronger at physik.rwth-aachen.de Sat Jul 26 03:45:21 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 26 Jul 2008 09:45:21 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> Message-ID: <87fxpxw0ku.fsf@physik.rwth-aachen.de> Hall?chen! Terry Reedy writes: > [...] > > Or the proposal would have to be that 'self' is mandatory for all > programmers in all languages. I think *that* would be > pernicious. People are now free to write the more compact 's.sum = > s.a + s.b + s.c' if they want instead of the 'self' version. And > again, not everyone writes in English. Of course, "self" would have to become a reserved word. You could say that this may break some code, but I don't see much freedom removed from the language. After all, being a German, I still can't write "F?r i in range(10)". ;-) Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From timr at probo.com Mon Jul 21 01:33:18 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 21 Jul 2008 05:33:18 GMT Subject: Python Written in C? References: Message-ID: giveitawhril2008 at gmail.com wrote: > >I'm just learning about Python now and it sounds interesting. But I >just read (on the Wiki page) that mainstream Python was written in C. >That's what I was searching for: Python was written in what other >language? > >See, my concern was something like: OK, if Python is so hot, then, >hopefully someone is writing it in assembly language for each MPU chip >out there. ... No one writes compilers in assembly language. Most people don't even write assemblers in assembly language. >So I was suspecting the Python compiler or interpreter is written in a >REAL language like C#. So, Wiki says it's written in C! It's almost as >if it were an intentional trick...write your own, new language in an >OLD, real world language that is passe. You seem to believe that, because YOU are just learning about Python, that necessarily means that Python itself is new. That is incorrect. Python was originally conceived and developed in 1990. Anders Hejlsberg, who designed C#, was still at Borland at that time, and had not even created Delphi yet. C++ was still many years away from becoming an ISO standard. >I'm not dissing Python, here. Just noting that, if it is written in C, >that throws a curve at me in trying to balance the value of learning >Python vs. some other major language. I would say you have a very strange criteria for deciding whether a language is worth learning. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From vlastimil.brom at gmail.com Fri Jul 25 12:01:07 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 25 Jul 2008 18:01:07 +0200 Subject: Execution speed question In-Reply-To: <4889a36f$1@news2-rz-ap.ethz.ch> References: <4889a36f$1@news2-rz-ap.ethz.ch> Message-ID: <9fdb569a0807250901w6998115atca5e32bf3fb2d29e@mail.gmail.com> 2008/7/25 Suresh Pillai : > ... > I naturally started coding with (2), but couldn't decide on the best data > structure for python. A set seemed ideal for speedy removal, but then I > can't iterate through them with out popping. An ordered list? Some > creative solution with numpy arrays? > > ... Maybe I am missing something, but I'm not sure, where is the problem with non-destructive iterating over a set, e.g.: >>> my_set = set([1,2,3,4,5]) >>> my_set set([1, 2, 3, 4, 5]) >>> for item in my_set: print item, ... 1 2 3 4 5 >>> my_set set([1, 2, 3, 4, 5]) >>> my_set -= set([2,4]) >>> my_set set([1, 3, 5]) >>> Of course, the suitability for your application would depend on other factors too. vbr -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Mon Jul 7 18:40:47 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 08 Jul 2008 08:40:47 +1000 Subject: Emacs/Python Essentials? References: Message-ID: <87prppwc5s.fsf@benfinney.id.au> xkenneth writes: > What does everyone consider essential for emacs python dev? GNU Emacs 22. The 'whitespace-mode' and 'python-mode' are good improvements in that version of Emacs. I've heard good things also about: 'ropemacs' , an Emacs mode for using 'rope', a Python refactoring tool 'ido.el' , an alternative mode for navigating multiple related buffers and files. -- \ ?A society that will trade a little liberty for a little order | `\ will lose both, and deserve neither.? ?Thomas Jefferson, in a | _o__) letter to Madison | Ben Finney From anishchapagain at gmail.com Tue Jul 22 05:59:35 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Tue, 22 Jul 2008 02:59:35 -0700 (PDT) Subject: automating python programs References: Message-ID: <1d39f8f1-80a3-4644-a564-6b26e2206e23@s50g2000hsb.googlegroups.com> On Jul 21, 7:28?pm, "Dan Upton" wrote: > On Mon, Jul 21, 2008 at 2:12 PM, Zach Hobesh wrote: > > Hi, > > > I'm trying to figure out how to run a python program on a schedule, maybe > > every half an hour... ?Is this possible? > > > Thanks! > > > -Zach > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > On Linux, man cron. Hi!! I hope if you have written the Python code in Class and module then you can call the execution of module in main module using yourroot.after(millisecond,moduletobe executed) like, parent_root.after(3000, child1_root.destroy)#will destroy the child1_root module after 3second at this stage in mainmodule. parent_root.mainloop() anish From marcus at internetnowasp.net Mon Jul 28 14:00:54 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Tue, 29 Jul 2008 02:00:54 +0800 Subject: We programming In-Reply-To: <789038.29418.qm@web7906.mail.in.yahoo.com> References: <789038.29418.qm@web7906.mail.in.yahoo.com> Message-ID: <488E0956.8070002@internetnowasp.net> Hi , I hope this doesnt invite flames.....but for webpages i suggest stick with php... I'm outta here.....wooosh.... srinivasan srinivas wrote: > Hi, > Could someone suggest me better python modules for developing web programming related projects like web-pages download and uopload?? > Thanks, > Srini > > > Explore your hobbies and interests. Go to http://in.promos.yahoo.com/groups/ > -- > http://mail.python.org/mailman/listinfo/python-list > > From dsc at ecs.soton.ac.uk Fri Jul 25 07:27:04 2008 From: dsc at ecs.soton.ac.uk (Dave Challis) Date: Fri, 25 Jul 2008 12:27:04 +0100 Subject: Automatically loading and initialising objects from a plugins directory In-Reply-To: References: <488607BC.3040204@ecs.soton.ac.uk> Message-ID: <4889B888.8000600@ecs.soton.ac.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Fredrik Lundh wrote: > so now you're no longer supporting mixins and multiple-level > inheritance? why not just tweak Diez' example a little: > > for name in dir(plugin): > > thing = getattr(plugin, name) > > # make sure this is a plugin > try: > if thing is Plugin: > continue > if not issubclass(thing, Plugin): > continue > except ValueError: # issubclass sucks > continue # not a class > > thing() # probably needs error handling around this > > (I also moved the thing call out of the thing validation part, to allow > you to distinguish between ValueErrors caused by issubclass and errors > caused by things) > > (btw, another approach would be to use a metaclass to make Plugin > classes register themselves on import) > > Thanks, that works much better. I've only been using python a couple of months, so still getting to grips with how it treats classes/subclasses. I'll have a look into metaclasses too, haven't stumbled upon those yet at all. Cheers, Dave - -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ) <>< <>< ( Dave Challis ) ____dsc at ecs.soton.ac.uk_______(___________________________________________ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFIibiHv26GZvAVVFERAgcmAJ4tmC7jp6TTb3Dx2Lw+rKSmJkcSLQCfYFsA e0ZLOf8lQXhqHcz/Me8ok0E= =Qcg7 -----END PGP SIGNATURE----- From benjamin.kaplan at case.edu Mon Jul 14 17:25:27 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 14 Jul 2008 17:25:27 -0400 Subject: Using McMillan Installer, PyInstall or py2exe cross-platform? In-Reply-To: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> References: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> Message-ID: On Mon, Jul 14, 2008 at 12:02 PM, Hartmut Goebel wrote: > Hi, > > has anybody used McMillan Installer, PyInstall or py2exe cross-platform? > > I have a Windows partition with Python installed there, so this would > "only" required working on a different directory and for a different OS. > Since I'm working on Linux, it's awful to boot Windows each time I want to > build a new release. > > Any hint in this area? > > -- > Sch?nen Gru? - Regards > Hartmut Goebel > > Goebel Consult > Spezialist f?r IT-Sicherheit in komplexen Umgebungen > http://www.goebel-consult.de > -- I don't know if this will work, but you can try running them on Wine. I know that python 2.5 works fine right now. > > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hotsexq at gmail.com Fri Jul 18 07:01:03 2008 From: hotsexq at gmail.com (hot) Date: Fri, 18 Jul 2008 04:01:03 -0700 (PDT) Subject: welcome to $500 monthly in onlin jobs jest join him with in all datting in girls frined available Message-ID: <74695ab1-b155-4533-9878-2a35b5ce021a@c2g2000pra.googlegroups.com> welcome to $500 monthly in onlin jobs jest join him with in all datting in girls frined available in all information viset welcome to $500 monthly in onlin jobs jest join him with in all datting in girls frined available in all information viset web http://www.friendfinder.com/go/g775836-pmem http://mountanbikes.blogspot.com/ From josiah.carlson at gmail.com Sat Jul 12 15:16:54 2008 From: josiah.carlson at gmail.com (Josiah Carlson) Date: Sat, 12 Jul 2008 12:16:54 -0700 (PDT) Subject: Doubts about how implementing asynchronous timeouts through a heap References: <80430d47-aac5-4123-8835-0591faf0baed@34g2000hsf.googlegroups.com> Message-ID: <72232593-3138-4bec-9101-16cfa4259461@d45g2000hsc.googlegroups.com> On Jul 9, 4:13?am, "Giampaolo Rodola'" wrote: > Hi, > I'm trying to implement an asynchronous scheduler for asyncore to call > functions at a later time without blocking the main loop. > The logic behind it consists in: > > - adding the scheduled functions into a heapified list > - calling a "scheduler" function at every loop which checks the > scheduled functions due to expire soonest > > Note that, by using a heap, the first element of the list is always > supposed to be the one with the lower timeout. > Here's the code I wrote: > > <--- snippet ---> > import heapq > import time > import sys > > delayed_map = [] > > class delayed_call: > ? ? """Calls a function at a later time. > > ? ? The instance returned is an object that can be used to cancel the > ? ? scheduled call, by calling its cancel() method. > ? ? It also may be rescheduled by calling delay() or reset()} methods. > ? ? """ > > ? ? def __init__(self, delay, target, *args, **kwargs): > ? ? ? ? """ > ? ? ? ? - delay: the number of seconds to wait > ? ? ? ? - target: the callable object to call later > ? ? ? ? - args: the arguments to call it with > ? ? ? ? - kwargs: the keyword arguments to call it with > ? ? ? ? """ > ? ? ? ? assert callable(target), "%s is not callable" %target > ? ? ? ? assert sys.maxint >= delay >= 0, "%s is not greater than or > equal " \ > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"to 0 seconds" % (delay) > ? ? ? ? self.__delay = delay > ? ? ? ? self.__target = target > ? ? ? ? self.__args = args > ? ? ? ? self.__kwargs = kwargs > ? ? ? ? # seconds from the epoch at which to call the function > ? ? ? ? self.timeout = time.time() + self.__delay > ? ? ? ? self.cancelled = False > ? ? ? ? heapq.heappush(delayed_map, self) > > ? ? def __le__(self, other): > ? ? ? ? return self.timeout <= other.timeout > > ? ? def active(self): > ? ? ? ? """Return True if this scheduler has not been cancelled.""" > ? ? ? ? return not self.cancelled > > ? ? def call(self): > ? ? ? ? """Call this scheduled function.""" > ? ? ? ? self.__target(*self.__args, **self.__kwargs) > > ? ? def reset(self): > ? ? ? ? """Reschedule this call resetting the current countdown.""" > ? ? ? ? assert not self.cancelled, "Already cancelled" > ? ? ? ? self.timeout = time.time() + self.__delay > ? ? ? ? if delayed_map[0] is self: > ? ? ? ? ? ? heapq.heapify(delayed_map) > > ? ? def delay(self, seconds): > ? ? ? ? """Reschedule this call for a later time.""" > ? ? ? ? assert not self.cancelled, "Already cancelled." > ? ? ? ? assert sys.maxint >= seconds >= 0, "%s is not greater than or > equal " \ > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"to 0 seconds" %(seconds) > ? ? ? ? self.__delay = seconds > ? ? ? ? self.reset() > > ? ? def cancel(self): > ? ? ? ? """Unschedule this call.""" > ? ? ? ? assert not self.cancelled, "Already cancelled" > ? ? ? ? del self.__target, self.__args, self.__kwargs > ? ? ? ? if self in delayed_map: > ? ? ? ? ? ? if delayed_map[0] is self: > ? ? ? ? ? ? ? ? delayed_map.remove(self) > ? ? ? ? ? ? ? ? heapq.heapify(delayed_map) > ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? delayed_map.remove(self) > ? ? ? ? self.cancelled = True > > def fun(arg): > ? ? print arg > > a = delayed_call(0.6, fun, '0.6') > b = delayed_call(0.5, fun, '0.5') > c = delayed_call(0.4, fun, '0.4') > d = delayed_call(0.3, fun, '0.3') > e = delayed_call(0.2, fun, '0.2') > f = delayed_call(0.1, fun, '0.1') > > while delayed_map: > ? ? now = time.time() > ? ? while delayed_map and now >= delayed_map[0].timeout: > ? ? ? ? delayed = heapq.heappop(delayed_map) > ? ? ? ? try: > ? ? ? ? ? ? delayed.call() > ? ? ? ? finally: > ? ? ? ? ? ? if not delayed.cancelled: > ? ? ? ? ? ? ? ? delayed.cancel() > ? ? time.sleep(0.01) > > > Here comes the questions. > Since that the timeouts of the scheduled functions contained in the > list can change when I reset() or cancel() them I don't know exactly > *when* the list needs to be heapified(). > By doing some tests I came to the conclusion that I need the heapify() > the list only when the function I reset() or cancel() is the *first of > the list* but I'm not absolutely sure about it. > When do you think it would be necessary calling heapify()? > I wrote a short test suite which tests the code above and I didn't > notice strange behaviors but since that I don't know much about the > logic behind heaps I'd need some help. > Thanks a lot in advance. > > --- Giampaolohttp://code.google.com/p/pyftpdlib/ I dug through my old pair heap implementation, did a little hacking on heapq, and wrote a task scheduler system that plugs in to asyncore. To schedule a task, you use: task = asyncore.schedule_task(schedule, delay, callable, *args, **kwargs) Once you have that task object, you can then use: asyncore.reschedule_task(schedule, delay, task) asyncore.abs_reschedule_task(schedule, time, task) ... to reschedule the task into the future (or past). You can also: asyncore.delete_task(schedule, task) ... to completely remove the task from the scheduler. Each one of these operations are O(logn), where n is the number of tasks currently known to the scheduler. To accommodate the new scheduler, asyncore.loop() now has the following call signature. def loop(timeout=30.0, use_poll=False, map=None, count=None, schedule=None, use_schedule=False): To try to help prevent poll_fcn() starvation (in the case of long- running scheduled tasks), the task window execution is set just prior to the poll_fun() call to be now + .01 seconds. That is, window is set, poll_fun() is called (which should handle current I/O operations), and all tasks that are to be completed prior to the end of the task window (now+.01 seconds, set prior to the poll_fun() call). Asyncore objects will not gain a set_scheduler() method, nor will they gain a schedule keyword argument on instantiation. Why? Because the scheduler is not required for socket I/O to work properly. If you want to use the scheduler from your own subclasses, asyncore.(asyncore.scheduled_tasks, ...) should be sufficient. This scheduler can be easily plugged into other systems, and it's likely that I'll add it as an interactive scheduler to sched.py, put the pair heap implementation into collections, and call it good. - Josiah From bearophileHUGS at lycos.com Thu Jul 17 04:15:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 17 Jul 2008 01:15:58 -0700 (PDT) Subject: Getting a unknown word out of a list with no spaces References: <18502758.post@talk.nabble.com> <487EF593.5060505@promsoft.ru> <18503144.post@talk.nabble.com> <487EF7D9.8010400@promsoft.ru> Message-ID: <93164ef9-7079-44db-9ac4-b0a18b0ddf3e@b1g2000hsg.googlegroups.com> On Jul 17, 9:50 am, Alexnb: > how can I test to see if the first char of a string is "<"? I suggest you to try the interactive shell: >>> "hello"[0] 'h' >>> "hello"[0] == "<" False >>> "hello"[0] == "h" True >>> "hello".startswith("h") True Bye, bearophile From rjagodic at gmail.com Thu Jul 17 13:03:31 2008 From: rjagodic at gmail.com (Ratko) Date: Thu, 17 Jul 2008 10:03:31 -0700 (PDT) Subject: properly delete item during "for item in..." References: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> <487F770D.8070405@islandtraining.com> Message-ID: On Jul 17, 9:57 am, mk wrote: > Gary Herron wrote: > > You could remove the object from the list with > > del myList[i] > > if you knew i. HOWEVER, don't do that while looping through the list! > > Changing a list's length will interact badly with the for loop's > > indexing through the list, causing the loop to mis the element following > > the deleted item. > > Jumping into a thread, I know how not to do it, but not how to do it > properly? > > Iterating over a copy may _probably_ work: > > >>> t=['a', 'c', 'b', 'd'] > >>> > >>> for el in t[:]: > del t[t.index(el)] > > >>> t > [] > > However, is it really safe? Defining safe as "works reliably in every > corner case for every indexable data type"? > > Con: suppose the data structure t is really, really big. Just deleting > some items from t temporarily doubles the memory consumption. Would this work (safely) then? It does in my test cases but that of course doesn't prove it works in a general case... for item in myList: myList.remove(item) For dictionaries we can just iterate over values() or items() as opposed to itervalues() or iteritems() since that's technically a copy of values or items in the dict, right? R From john.smith at john-smith.con Fri Jul 4 17:30:54 2008 From: john.smith at john-smith.con (Aloysius Hibblenire-Ozzleridge) Date: Fri, 04 Jul 2008 14:30:54 -0700 Subject: Iphone Going 3G! References: <486cab43$1_2@news.tm.net.my> <20fqou.nq0.19.1@news.alt.net> Message-ID: <8w3konjjs1gg714.040720082231@gazwad.serveftp.com> On Thu, 3 Jul 2008 11:19:39 -0700 relic bogus.relic2 at cjb.net wrote in news:20fqou.nq0.19.1 at news.alt.net... > fizzi wrote: >> For the Iphone lovers out there, > > Wrong group. No weirdos here. The dumb cunt is posting old news too. From gherron at islandtraining.com Tue Jul 29 11:58:13 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 29 Jul 2008 08:58:13 -0700 Subject: Overloaded Functions In-Reply-To: <3070b5ff-0914-4109-841a-ee622e4105a5@27g2000hsf.googlegroups.com> References: <3070b5ff-0914-4109-841a-ee622e4105a5@27g2000hsf.googlegroups.com> Message-ID: <488F3E15.8000308@islandtraining.com> Tim Henderson wrote: > Hi, > > So this may have been asked before but i haven't found the answer by > googling so far. My situation is this: > > I want this structure for my code: > > @overloaded > def sign_auth(secret, salt, auth_normalized): > return __sign_auth(saltedhash_bin(secret, salt), auth_normalized) > > @sign_auth.register(str, str) > def sign_auth(secret_hash_normalized, auth_normalized): > return __sign_auth(qcrypt.denormalize(secret_hash_normalized), > auth_normalized) > > def __sign_auth(secret_hash_bin, auth_normalized): > auth = qcrypt.denormalize(auth_normalized) > aes = AES.new(secret_hash_bin, AES.MODE_CBC) > plaintext = aes.decrypt(auth) > ciphertext = qcrypt.normalize(xor_in_pi(plaintext)) > if debug: > print '\n------sign_auth------' > print qcrypt.normalize(secret_hash_bin) > print qcrypt.normalize(plaintext) > print ciphertext > print '-----sign_auth-------\n' > return ciphertext > > I am using the overloading module from: > http://svn.python.org/view/sandbox/trunk/overload/overloading.py?rev=43727&view=log > > However it doesn't actually support this functionality. Does any one > know of a decorator that does this? It would be really nice to have a > unified interface into the __sign_auth function for the two different > use cases. > Are you aware that you can do this kind of thing yourself, without using a module/decorator. def sign_auth(*args): if len(args) == 3: secret, salt, auth_normalized = args return __sign_auth(saltedhash_bin(secret, salt), auth_normalized) elif len(args) == 2: secret_hash_normalized, auth_normalized = args return __sign_auth(qcrypt.denormalize(secret_hash_normalized), auth_normalized) The checks could be more involved, perhaps checking not jsut the nuimber of args, but their types, and even their values, before calling __sign_auth(...). Gary Herron > Tim Henderson > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Sun Jul 6 16:50:33 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 06 Jul 2008 16:50:33 -0400 Subject: how are strings immutable in python? In-Reply-To: References: Message-ID: Peter Otten wrote: > ssecorp wrote: > >>>>> h = "aja baja" >>>>> h += 'e' >>>>> h >> 'aja bajae' > > The inplace-add operator doesn't mutate the lvalue, it just rebinds it: In Python, neither '=' nor members of the 'op=' family are operators. They all mark *assignment* or *augmented assignment* statements that *all* bind objects to targets. Augmented assignments are, rather obviously, restricted to binding one object to one target. For 'x op= y', if the object originally bound to x is mutable, the arithmetic operation part of the augmented assignment can (should) be implemented by an inplace __i__ special method that (normally, but not necessarily) mutates and returns self to be rebound. Otherwise, the interpreter calls the normal ____ special method (if it exits) that returns a new object to be bound. Thus, '+=' is neither an operator nor is the indicated operation necessarily inplace. Immutable built-in classes do not have __i__ methods. So given that name h is bound to a string, h += 'e' has exactly the same effect as h = h + 'e' which has exactly the same effect as h = h.__add__('e') The same is true for immutable instances of other built-in classes. Terry Jan Reedy From bignose+hates-spam at benfinney.id.au Mon Jul 28 23:20:59 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 29 Jul 2008 13:20:59 +1000 Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> <488e3520$0$16766$426a74cc@news.free.fr> <87myk1iknc.fsf@benfinney.id.au> Message-ID: <87od4hgyuc.fsf@benfinney.id.au> Ben Finney writes: > It has, at least, long ago bought him a place in my kill-file. > Seeing your side of the conversation, I can only confirm that > decision as correct. This should perhaps say "seeing the parts of his communication that leak through by being quoted in others's posts, I can only confirm my decision as correct." -- \ ?Pinky, are you pondering what I'm pondering?? ?Wuh, I think | `\ so, Brain, but wouldn't anything lose its flavor on the bedpost | _o__) overnight?? ?_Pinky and The Brain_ | Ben Finney From kmtracey at gmail.com Fri Jul 18 17:30:30 2008 From: kmtracey at gmail.com (Karen Tracey) Date: Fri, 18 Jul 2008 17:30:30 -0400 Subject: Change in Decimal repr in Python 2.6 Message-ID: I noticed when trying out Python's 2.6b2 release that the repr of Decimal has changed since 2.5. On 2.5: Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import decimal >>> decimal.Decimal(7) Decimal("7") >>> double quotes were used whereas on 2.6b2: Python 2.6b2 (r26b2:65082, Jul 18 2008, 13:36:54) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import decimal >>> decimal.Decimal(7) Decimal('7') >>> single quotes are used. Searching around I see this was done in r60773 with the log message: Fix decimal repr which should have used single quotes like other reprs. but I can't find any discussion other than that. My problem is this breaks a bunch of doctests that were written assuming the prior repr. I can't just update the tests to assume the new single quotes because they are for code that is supposed to run on everything back to Python 2.3. So my question: Is this backwards-incompatible change really necessary and could it be reconsidered? If it's here to stay, is there some straightforward why that I am unaware of to construct tests that use Decimal repr but will work correctly on Python 2.3-2.6? Also, if this is not the right list for this question please let me know where would be more appropriate and I will go there. Thanks for any feedback, Karen -------------- next part -------------- An HTML attachment was scrubbed... URL: From wtanksleyjr at gmail.com Wed Jul 30 14:27:28 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Wed, 30 Jul 2008 11:27:28 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Message-ID: "Jerry Hill" wrote: > william tanksley wrote: > > Here's one example. The others are similar -- they have the same > > things that look like problems to me. > > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" > > I tried doing track_id.encode("utf-8"), but it doesn't seem to make > > any difference at all. > I don't have anything to say about your iTunes problems, but encode() > is the wrong method to turn a byte string into a unicode string. > Instead, use decode(), like this: Awesome... Thank you! I had my mental model of Python turned around backwards. That's an odd feeling. Okay, so you decode to go from raw byes into a given encoding, and you encode to go from a given encoding to raw bytes. Not what I thought it was, but that's cool, makes sense. At first I thought this fixed my problem, but I had to tweak the obvious fix to make it work, and I don't understand why. Fix #1: track_id = track_id.decode('utf-8') track_id = url2pathname(urlparse(track_id).path) That doesn't work -- it produces no error, but the raw bytes appear in the unicode string. Fix #2: track_id = url2pathname(urlparse(track_id).path) track_id = track_id.decode('utf-8') This one appears to work. (Although I can't confirm it for sure, because although all my debug prints are now correct, the overall application fails in the same way it did before, back before I put in debug printfs. I'm going to spend some time assuming that the problem is elsewhere in my code, since at least I definitely fixed one serious problem.) I've got a few questions for Python-XML-Unicode experts... 1. Why does the order of those statements matter? 2. Shouldn't it be more correct to decode BEFORE transforming the string? Why does that kill the decoding? 3. Why is ElementTree dumping raw bytes on me instead of decoding to UTF-8? The XML file has its encoding set to: , so it seems like it should know what codec to use. > Jerry -Wm From maric at aristote.info Thu Jul 31 09:00:27 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 31 Jul 2008 15:00:27 +0200 Subject: Difference between type and class In-Reply-To: <87zlny8cdg.fsf@nokile.rath.org> References: <87myjy2vc6.fsf@nokile.rath.org> <12072cbe-139a-430f-81aa-b64bc31b43e5@e39g2000hsf.googlegroups.com> <87zlny8cdg.fsf@nokile.rath.org> Message-ID: <200807311500.27747.maric@aristote.info> Le Thursday 31 July 2008 14:30:19 Nikolaus Rath, vous avez ?crit?: > oj writes: > > On Jul 31, 11:37?am, Nikolaus Rath wrote: > >> So why does Python distinguish between e.g. the type 'int' and the > >> class 'myclass'? Why can't I say that 'int' is a class and 'myclass' > >> is a type? > > > > I might be wrong here, but I think the point is that there is no > > distinction. A class (lets call it SomeClass for this example) is an > > object of type 'type', and an instance of a class is an object of type > > 'SomeClass'. > > But there seems to be a distinction: > >>> class int_class(object): > > ... pass > ... > > >>> int_class > > > > >>> int > > > > why doesn't this print > > >>> class int_class(object): > > ... pass > ... > > >>> int_class > > > > >>> int > > > > or > > >>> class int_class(object): > > ... pass > ... > > >>> int_class > > > > >>> int > > > > If there is no distinction, how does the Python interpreter know when > to print 'class' and when to print 'type'? > There are some confusion about the terms here. Classes are instances of type 'type', but types are both instances and subclasses of 'type'. This recursivity is the base of the object model. An instance of 'type' is a class (or a new type), but instances of a classes are not. 'type' is a metatype in term of OO. What the means is that int is not a user type but a builtin type, instances of int are not types (or classes) but common objects, so its nature is the same as any classes. The way it prints doesn't matter, it's just the __repr__ of any instance, and the default behavior for instances of type is to return '', but it can be easily customized. >>>[1]: class A(object) : ...: class __metaclass__(type) : ...: def __repr__(self) : return "" ...: ...: >>>[2]: A ...[2]: >>>[3]: type('toto', (object,), {}) ...[3]: -- _____________ Maric Michaud From stochashtic at yahoo.ca Mon Jul 28 10:48:28 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 28 Jul 2008 16:48:28 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <488d86e2$1@news2-rz-ap.ethz.ch> <488dc3eb$1@news2-rz-ap.ethz.ch> Message-ID: <488ddc3c$1@news2-rz-ap.ethz.ch> On Mon, 28 Jul 2008 15:04:43 +0200, Suresh Pillai wrote: > On Mon, 28 Jul 2008 10:44:18 +0200, Suresh Pillai wrote: > >> Since I am doing A LOT of loops over the nodes and the number of nodes >> is also huge, my concern using sets is that in order to iterate over >> the set in each step of my simulation, the set items need to be >> converted to a list every time. So while removal from a set is much >> cheaper than say from a list, what about this conversion overhead in >> order to iterate over the items. > > I could of course use the old trick of using a dictionary with 'None' > values and then using iterkeys(). But I thought sets were supposed to > replace this. So maybe I should be asking a more basic question: is > there any way to iterate over the items in a set other than converting > to a list or using the pop() method. Okay, please consider this my one absolutely stupid post for the year. I'd like to pretend it never happened but unfortunately the web doesn't allow that. Having never used sets, I unfort read something that lead to it, but ... From mal at egenix.com Thu Jul 17 13:55:44 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 17 Jul 2008 19:55:44 +0200 Subject: Converting from local -> UTC In-Reply-To: <41d4ffc7-7fd5-4202-92ea-132c7d4f5cd4@s50g2000hsb.googlegroups.com> References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> <41d4ffc7-7fd5-4202-92ea-132c7d4f5cd4@s50g2000hsb.googlegroups.com> Message-ID: <487F87A0.9040702@egenix.com> On 2008-07-16 20:00, Keith Hughitt wrote: > Thanks Gabriel! > > That helps clear things up for me. The above method works very well. I > only have one remaining question: > How can I pass a datetime object to MySQL?' > > So far, what I've been doing is building the query as a string, for > example: > > query = "INSERT INTO image VALUES(%d, %d, %s, '%s')" % (id, meas, > date, 'jpg') > cursor.execute(query) Use binding parameters and it should work: query = "INSERT INTO image VALUES(%d, %d, %s, '%s')" cursor.execute(query, (id, meas, date, 'jpg')) Database interfaces typically do not support timezones, so I'm not sure why you are making things more complicated by adding a timezone to the date/time value. > This works fine for regular datetime objects, which are passed as > strings similar > to: "2003-10-01 00:00:00." When incorporating a timezone, however, the > resulting string > is of the form "2003-10-01 00:00:00+00:00." Unfortunately, MySQL does > not recognize > the offset. > > I know you said you don't use MySQL, but how would you do something > execute a similar query > on the database you normally interface with? > Thanks, > Keith > > > On Jul 15, 12:04 am, "Gabriel Genellina" > wrote: >> En Mon, 14 Jul 2008 12:06:30 -0300,KeithHughitt >> escribi?: >> >> >> >>> On Jul 12, 12:52 am, "Gabriel Genellina" >>> wrote: >>>> En Fri, 11 Jul 2008 15:42:37 -0300,KeithHughitt >>>> escribi?: >>>>> I am having a little trouble figuring out how to convert a python >>>>> datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would >>>>> like to create a UTC date so that when I send it to MySQL (which >>>>> treats all dates at local dates by default), it will already have >>>>> incorporated the proper UTC offset. I've tried looking through the >>>>> docshttp://python.active-venture.com/lib/datetime-datetime.html), but >>>>> have not had any luck. >>>> You have to use a "timezone aware" datetime object. If all you want is >>>> to >>>> store an UTC date, the tzinfo demo classes that you can find in the >>>> Python >>>> docs at may be enough. >>> Thanks for advice Gabriel. I downloaded the tzinfo demo class, saved >>> it as >>> UTC.py and imported it. I'm still not exactly sure how to use it >>> though. It looks like >>> the file already creates an instance of the UTC tzinfo class (line 20: >>> "utc = UTC()"), >>> however, when I try to test it out in the interpreter, it cannot be >>> found. I'm new >>> to python, and there is probably something obvious I'm missing, but do >>> you have any ideas? >> The import statement in Python doesn't behave the same way as similar >> statements in other languages - and it may be confusing you. I'll try to >> explain it using this example. >> You have: >> - a *file* UTC.py, containing the source code for the *module* UTC. It >> contains: >> - a *class* definition (UTC) and >> - an *instance* of that class, utc. >> >> --- begin UTC.py ---If you pass a "timezone aware" datetime object as a SQL parameter >> class UTC(tzinfo): >> ... >> utc = UTC() >> ... >> --- end UTC.py --- >> >>> Here is what I'm attempting: >>> ============ output begin ============= >>> Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) >>> [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>>>>> import datetime, UTC >> Here you have imported the *module* UTC. That is, the name UTC now refers >> to a newly created module just loaded from the UTC.py file. >> >>>>>> t = datetime.datetime(2008, 7, 14, 00, 00, 00, UTC()) >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: 'module' object is not callable >> The error comes from UTC(): UTC is a module, UTC() is attempting to "call" >> it, and since modules are not callable objects, we get a TypeError. >> >>>>>> utc >>> Traceback (most recent call last): >>> File "", line 1, in >>> NameError: name 'utc' is not defined >> The *only* name we have imported so far is UTC - the module. Lowercase utc >> isn't defined. >> >>>>>> utc = UTC() >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: 'module' object is not callable >> Same as above... >> >> Ok, how to solve it? We know that UTC refers to the *module* with the same >> name. To get the *class* inside that module, use UTC.UTC - try again in >> the interpreter. To create a new instance of that class, you can use >> UTC.UTC(). To obtain the instance already created in the UTC module, use >> UTC.utc >> >> **OR** >> >> Import those names explicitely: >> >> py> from UTC import UTC >> >> In this case the name UTC refers to the *class* inside the module. >> In this particular example it may be confusing - both have the same name. >> Another example from the standard library: the poplib module contains a >> POP3 class, so after executing this line: >> >> py> from poplib import POP3 >> >> the name POP3 refers to that class. The poplib module itself isn't >> directly available. >> Back to the UTC module, you could use: >> >> py> from UTC import utc >> >> and now utc refers to the *instance* already created inside the module. >> This last form may be the most convenient in your case: >> >> py> import datetime >> py> from UTC import utc >> py> print datetime.datetime(2008, 7, 14, 20, 30, 0, 0, utc) >> 2008-07-14 20:30:00+00:00 >> >> -- >> Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 17 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From g.threepwood at gmail.com Mon Jul 28 19:10:25 2008 From: g.threepwood at gmail.com (C Martin) Date: Mon, 28 Jul 2008 16:10:25 -0700 (PDT) Subject: Tkinter fullscreen with Mac OS X Message-ID: Is there a way to create a full screen app using Tkinter with Mac OS X?? On windows, this is relatively easy with overrideredirect(1). However, on the Mac, the top menu bar and dock are still displayed over the app. Is there a way to get rid of them? Thanks. From jason.scheirer at gmail.com Sun Jul 6 23:14:21 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Sun, 6 Jul 2008 20:14:21 -0700 (PDT) Subject: GUI Programming by hand not code with Python Code References: <7003b665-3227-47a7-ab06-1a486f87939a@a1g2000hsb.googlegroups.com> Message-ID: <85ab371e-9926-4bb3-bcd4-f441de7aa046@k30g2000hse.googlegroups.com> On Jul 6, 7:33?pm, jayjaygi... at hotmail.co.uk wrote: > Is their a program that lets you design a GUI by hand (like gambas) > not by code (like wxpython) but the commands are in python? > > A program similar to gambas or vb > > Gambas with python code instead of gambas code would be perfect. > > Thanks in advance Glade for GTK, wxGlade for wxPython. From rcdailey at gmail.com Wed Jul 30 12:39:34 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 30 Jul 2008 11:39:34 -0500 Subject: Reasoning behind 'self' parameter in classes? Message-ID: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> Hi, I want to point out first of all that I'm not as familiar with Python as I should be, and for that reason I question a lot of things because I'm mainly a C++ programmer and I'm used to certain conveniences. Having said that... I've always been curious (more so than annoyed) as to why one must explicitly specify a "self" parameter for member functions in a class in Python. This seems very "C" like to me, since to do object oriented programming in C you must devote one parameter to the object itself. In a higher order language like Python, I would not have expected (and thus am rather surprised) that this pattern would apply. Is there any particular reason why 'self' parameters must be specified explicitly? I am curious to understand the philosophy and design behind this. In Python 3 will there be any plans to eliminate this syntactic artifact? As I said, it's not terribly annoying to me but it seems like more of a hack than anything else. I would feel a bit better if I didn't have to see it. I don't mean to start any syntax wars or anything, so I hope everyone will keep an open mind and simply explain the design, rather than defend it. I'm interested in only facts, and not opinions. This is an example of a response I'm looking for: "The self parameter is required because the parser is a bit old and needs to know the exact object you're referencing" This is _not_ an example of what I'm looking for: "Specifying self is a great mysterious thing that we should never question. Do not question the language! The language is mighty! Don't bring C++ to Python!" I appreciate the community's time. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuwei23 at gmail.com Sun Jul 20 19:22:00 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 20 Jul 2008 16:22:00 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <55888f61-d179-4d6a-9003-a9fa2ca21373@x36g2000prg.googlegroups.com> On Jul 21, 8:50 am, giveitawhril2... at gmail.com wrote: > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. The advantage of Python over C - to me - is in the higher order abstractions it provides, not in pointless discussions of purity. Even better, Python allows me to -mix- both C & Python together, to take advantage of the strengths of each as appropriate. Try writing something of complexity in Python. Then write the same thing in C. -Then- make your decision which you prefer. From maestroQC at gmail.com Wed Jul 16 11:32:44 2008 From: maestroQC at gmail.com (maestroQC) Date: Wed, 16 Jul 2008 08:32:44 -0700 (PDT) Subject: MySQL Insert References: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> Message-ID: Thanks to all for your time and patience with this! The insert is working fine based on the suggestions in this thread. I now have another problem that should be resolved with a regular expression to remove currency formatting before inserting into the db. From larry.bates at websafe.com` Mon Jul 14 18:16:26 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 14 Jul 2008 17:16:26 -0500 Subject: logging via SocketHandler and TCPserver In-Reply-To: <81929250-449b-4686-acf3-dcc0095e341a@d1g2000hsg.googlegroups.com> References: <81929250-449b-4686-acf3-dcc0095e341a@d1g2000hsg.googlegroups.com> Message-ID: Vinay Sajip wrote: > On Jul 13, 9:25 pm, Larry Bates wrote: >> Every time I look at theloggingmodule (up until now) I've given up and >> continue to use my home-grown logger that I've been using for years. I'm not >> giving up this time ;-) >> >> I find that I REALLY need to be able to monitor LOTS of running >> programs/processes and thought it would be nice to have them use SocketHandlerloggingand then I would write TCPServer to accept the log messages for >> real-time monitoring. I Googled (is that now a verb?) for several hours and >> came up with some code that I've turned in to something that works, but I can't >> figure out how to disconnect the server once it is connected The goal is to be >> able to start TCPServer, monitor the log messages sent via SocketHandler logger, >> disconnect, and move to the next application. Eventually I would like to wrap a >> GUI around all of this for monitoring a complex web application. >> >> Everything works, it just appears that I get into the while loop in >> LogRecordStreamHandler.handle and it never breaks out (until I kill the client). >> I can't seem to do anything with the LogRecordSocketReceiver.abort attribute to >> make it quit. >> >> I'm sure it is something simple (stupid?), but I've spent about 4 hours and I'm >> not getting anywhere. >> >> Thanks in advance for any assistance. >> >> Regards, >> Larry >> >> Below is my code: >> >> import sys >> import time >> importlogging >> >> if sys.argv[1] == 'client': >> importlogging.config >> >> logging.config.fileConfig("logging.conf") >> >> #create logger >> logger =logging.getLogger("VESconsole") >> >> while 1: >> logger.debug("debug message") >> logger.info("info message") >> logger.warn("warn message") >> logger.error("error message") >> logger.critical("critical message") >> time.sleep(2) >> >> elif sys.argv[1] == 'server': >> import cPickle >> importlogging.handlers >> import SocketServer >> import struct >> import signal >> >> class LogRecordStreamHandler(SocketServer.StreamRequestHandler): >> """Handler for a streamingloggingrequest. >> >> This basically logs the record using whateverloggingpolicy is >> configured locally. >> """ >> >> def handle(self): >> """ >> Handle multiple requests - each expected to be a 4-byte length, >> followed by the LogRecord in pickle format. Logs the record >> according to whatever policy is configured locally. >> """ >> while 1: >> chunk = self.connection.recv(4) >> if len(chunk) < 4: >> break >> >> slen = struct.unpack(">L", chunk)[0] >> chunk = self.connection.recv(slen) >> while len(chunk) < slen: >> chunk = chunk + self.connection.recv(slen - len(chunk)) >> >> obj = self.unPickle(chunk) >> record =logging.makeLogRecord(obj) >> self.handleLogRecord(record) >> >> def unPickle(self, data): >> return cPickle.loads(data) >> >> def handleLogRecord(self, record): >> t = time.strftime('%a, %d %b %y %H:%M:%S', >> time.localtime(record.created)) >> >> print "%s %s" % (t, record.getMessage()) >> >> class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer): >> """simple TCP socket-basedloggingreceiver suitable for testing. >> """ >> >> allow_reuse_address = 1 >> >> def __init__(self, host='localhost', >> port=logging.handlers.DEFAULT_TCP_LOGGING_PORT, >> handler=LogRecordStreamHandler): >> >> SocketServer.ThreadingTCPServer.__init__(self, >> (host, port), >> handler) >> self.abort = 0 >> self.timeout = 1 >> self.logname = None >> >> def serve_until_stopped(self): >> import select >> abort = 0 >> while not abort: >> rd, wr, ex = select.select([self.socket.fileno()], >> [], [], >> self.timeout) >> if rd: >> self.handle_request() >> >> abort = self.abort >> >> print "serve_until_stopped exiting" >> >> # >> # Start ThreadingTCPServer instance to accept SocketHandler log >> # messages from client. >> # >> tcpserver = LogRecordSocketReceiver() >> print "Starting ThreadingTCPServer..." >> tcpserver.serve_until_stopped() >> >> ''' >> #-----logging.conf----- >> [loggers] >> keys=root >> >> [handlers] >> keys=socketHandler >> >> [formatters] >> keys=simpleFormatter >> >> [logger_root] >> level=DEBUG >> handlers=socketHandler >> >> [handler_socketHandler] >> class=handlers.SocketHandler >> level=DEBUG >> args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT) >> host=localhost >> port=DEFAULT_TCP_LOGGING_PORT >> >> [formatter_simpleFormatter] >> format=%(asctime)s - %(name)s - %(levelname)s - %(message)s >> datefmt= >> ''' > > Hi Larry, > > You can make the server quit (set abort to True) by changing the logic > of the server appropriately. In your script (as in the example at > http://docs.python.org/lib/network-logging.html), nothing sets > server.abort, so the server never quits. If you were to insert a line > "self.server.abort = True" before the break in the check "if > len(chunk) < 4:", then the server will quit whenever a message shorter > than 4 bytes is received; ordinarily, a SocketHandler will always send > a 4-byte length followed by content. You can test this easily as > follows: > > Run the server after modifying the script as described above. > Run the client and observe some messages printed by the server. > Kill the client. The server should still be waiting for events from > clients, though it might quit if, when you kill the client, a > truncated message is sent. > Run "telnet localhost 9020" and type a character. > The server should quit. If you make the "quitting" message a > raw_input() call, then you can see that the server has exited normally > via the abort flag. > > Don't forget, the receiver can receive events from several > applications. You don't need to disconnect and reconnect. Simply have > each event sent by an app identify the app in some way - e.g. the > logger name could be "VESconsole.app1" for one app and > "VESconsole.app2" in another. In your server's handleRecord code, you > can get the logger name, decode the sending app from that and route > the event appropriately. > > Another approach is to subclass SocketHandler and override the > makePickle method. This determines the wire format of the event sent > to the server, and if you change the wire format and modify the server > end to suit, then you can have any amount of flexibility in the > communications between the applications generating the events and the > server collating them. > > I'm not sure why you've had so much trouble with logging in the past, > or why it took several hours of Googling to find a solution relating > to logging events across a network. I Googled for "python network > logging" and the link in the Python docs which I referenced earlier > was the first result, and hence also available via the "I'm Feeling > Lucky" button ;-) > > Best regards, > > Vinay Vinay, Thanks for your detailed explanation, but IMHO your suggested solution is almost the opposite (right idea wrong direction) of what I'm looking for. Hypothetical setup: application1 - SocketHandler logging turned on application2 - SocketHandler logging turned on application3 - SocketHandler logging turned on . . . applicationN monitoring app - ThreadingTCPServer target that Allows user to connect to ANY running application and to view the real-time log messages. After monitoring, it should be able to disconnect and connect to another application... The clients (application1..N) never stop sending and don't ever send anything short to disconnect themselves from the monitoring application. The disconnect/ reconnect is done at the monitoring app end based on input from the user. I think each one would be logging to a different port, but I never really quite got that far. Perhaps there is some other way that I'm missing. It seems like this is something that might be able to be "generalized" into a robust monitoring application for an arbitrary number of asynchronously running applications. Each application's real-time log might be reached by clicking on a tab, menu, etc. As to the difficulty, I might just have a mental block but two modules that I've had a real hard time getting my mind wrapped around is your Logging and Twisted. They both have a multitude of options/ways to be used and not very many working examples to work from. Might be a chance to make some money on a book. If it was full of examples, I'd purchase it. Regards, Larry From stefan_ml at behnel.de Sun Jul 27 09:19:44 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 27 Jul 2008 15:19:44 +0200 Subject: xml.dom's weirdness? In-Reply-To: References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> <1c837e71-a191-4495-8ec8-0126003ba9c6@n33g2000pri.googlegroups.com> <488C3645.8060304@behnel.de> Message-ID: <488c75ee$0$29448$9b4e6d93@newsspool4.arcor-online.net> Lie wrote: > I'm more concerned about the number of modules imported by making an > error (from 30 on the startup to 187) and the side-effect of making an > error, which makes modules such as xml.*/email.* that previously > doesn't exist get imported out of the blue... Using my system Python (2.5.1 on Ubunutu Gutsy): $ strace -e open python -c '' 2>&1 | wc -l 551 $ strace -e open python -c '<><<' 2>&1 | wc -l 4631 Using a self-built Python I have lying around: $ strace -e open python2.3 -c '' 2>&1 | wc -l 210 $ strace -e open python2.3 -c '<><<' 2>&1 | wc -l 214 $ strace -e open python2.6 -c '' 2>&1 | wc -l 138 $ strace -e open python2.6 -c '<><<' 2>&1 | wc -l 142 Blame Ubuntu/Debian. Stefan From rocksportrocker at googlemail.com Fri Jul 18 08:19:00 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Fri, 18 Jul 2008 05:19:00 -0700 (PDT) Subject: How to process a very large (4Gb) tarfile from python? References: <0e96241d-60a3-44fd-967a-394904ad5b34@e39g2000hsf.googlegroups.com> <4nqu74p3mmmdmf9pn7125voe6itko8d31k@4ax.com> <1fe948fd-63a3-48ef-b5a8-84f0e4dd48a2@y22g2000prd.googlegroups.com> Message-ID: <1f1c0b2f-eb74-4949-95ff-0307acd490f7@p25g2000pri.googlegroups.com> Due to the discussion above I wrote a python module for scanning of large tarfiles. You can get it from http://www.procoders.net/wp-content/tarfile_scanner.zip Greetings, Uwe From dgeller at gmail.com Sat Jul 5 14:09:44 2008 From: dgeller at gmail.com (david) Date: Sat, 5 Jul 2008 11:09:44 -0700 (PDT) Subject: conflict between multiple installs of python (linux) Message-ID: <6bd22c06-a1e6-4247-9aff-2d0b29b1ec5e@d1g2000hsg.googlegroups.com> You learn something new every day: On my ubuntu, update-manager is supposed to use the python2.5 installed on /usr/bin. Well, I had subsequently installed a whole bunch of stuff in /usr/local (/usr/local/bin/python and /usr/local/lib/ python2.5 etc), which I have happily been using for development for a year. I had thought that the two pythons were completely independent. Well, I was wrong. When /usr/bin/python2.5 runs, *by default*, it adds /usr/local/lib/python2.5 to its sys path - and apparently there are things in /usr/local which are inconsistent with those at /usr (not suprising). I have fixed the problem - but I had to modify the actual update- manager .py file itself. At the beginning, I set the sys.path in python *explicitly* to not include the /usr/local stuff. But this is clearly a kludge. My question: how do I keep the Ubuntu python stuff at /usr/bin/python2.5 from adding /usr/local/lib/ python2.5 to the import search path in a clean and global way? I really want both pythons completely isolated from one another! Thankyou. From stefan_ml at behnel.de Tue Jul 22 17:03:09 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 22 Jul 2008 23:03:09 +0200 Subject: xpathEval fails for large files In-Reply-To: References: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> Message-ID: <48864b0d$0$9494$9b4e6d93@newsspool3.arcor-online.net> Fredrik Lundh wrote: > Kanchana wrote: > >> I tried to extract some data with xpathEval. Path contain more than >> 100,000 elements. >> >> doc = libxml2.parseFile("test.xml") >> ctxt = doc.xpathNewContext() >> result = ctxt.xpathEval('//src_ref/@editions') >> doc.freeDoc() >> ctxt.xpathFreeContext() >> >> this will stuck in following line and will result in high usage of >> CPU. >> result = ctxt.xpathEval('//src_ref/@editions') >> >> Any suggestions to resolve this. > > what happens if you just search for "//src_ref"? what happens if you > use libxml's command line tools to do the same search? > >> Is there any better alternative to handle large documents? > > the raw libxml2 API is pretty hopeless; there's a much nicer binding > called lxml: > > http://codespeak.net/lxml/ > > but that won't help if the problem is with libxml2 itself, though It may still help a bit as lxml's setup of libxml2 is pretty memory friendly and hand-tuned in a lot of places. But it's definitely worth trying with both cElementTree and lxml to see what works better for you. Depending on your data, this may be fastest in lxml 2.1: doc = lxml.etree.parse("test.xml") for el in doc.iter("src_ref"): attrval = el.get("editions") if attrval is not None: # do something Stefan From jordanrastrick at gmail.com Thu Jul 24 05:58:26 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 02:58:26 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> Message-ID: On Jul 24, 7:40?pm, Torsten Bronger wrote: > Hall?chen! > > Bruno Desthuilliers writes: > > [...] > > > How would you handle this case with an implicit 'self' : > > > class Foo(object): > > ? ?pass > > > def bar(self): > > ? ?print self > > > Foo.bar = bar > > Just like this. ?However, the compiler could add "self" to > non-decorated methods which are defined within "class". > > Tsch?, > Torsten. > > -- > Torsten Bronger, aquisgrana, europa vetus > ? ? ? ? ? ? ? ? ? ?Jabber ID: torsten.bron... at jabber.rwth-aachen.de Yeah, forgot what I said, Torsten's reply is much better :-) From basti.wiesner at gmx.net Thu Jul 10 12:46:37 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Thu, 10 Jul 2008 18:46:37 +0200 Subject: Emacs/Python Essentials? References: Message-ID: xkenneth : > What does everyone consider essential for emacs python dev? yasnippet is worth being looked at -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From catherine.heathcote at gmail.com Tue Jul 22 12:37:39 2008 From: catherine.heathcote at gmail.com (Catherine Heathcote) Date: Tue, 22 Jul 2008 17:37:39 +0100 Subject: Question about inheritence References: <26204bc2-a1f9-439c-aa0b-2d957ed81c5d@p25g2000hsf.googlegroups.com> Message-ID: On Tue, 22 Jul 2008 09:35:58 -0700, Matimus wrote: > On Jul 22, 9:26?am, Catherine Heathcote > wrote: >> If I create a new class inherited from another with a constructor, what >> happens with the new class's constructer? >> Thanks for your time. > > Nothing, unless you call it in your constructor. > > class Base(object): > def __init__(self): > print "Base constructor called" > > # without calling the base class constructor > class C(Base): > def __init__(self): > print "C constructor called" > > # call the base class constructor using super > class D(Base): > def __init__(self): > super(D, self).__init__() > print "D constructor called" > > c = C() > d = D() > > > Matt Aha! Makes sence, thankyou. As you can probably tell I am new to Python, but not programming as a whole. From kyosohma at gmail.com Thu Jul 31 14:58:54 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 31 Jul 2008 11:58:54 -0700 (PDT) Subject: Hobbyist - Python vs. other languages References: Message-ID: <68545bc7-6dfd-4988-b697-f93b8e26c527@s50g2000hsb.googlegroups.com> On Jul 31, 1:32?pm, fprintf wrote: > I have been playing with computers since I first learned to program > moving shapes on an Atari 800XL in BASIC. After many years of dabbling > in programming languages as a hobbyist (I am not a computer scientist > or other IT professional), I have never found a way to stick with a > language far enough to do anything useful. ?I learn all about loops > and data structures and functions/methods etc. but never get to create > a program that will do anything of value that I can't more easily do > via freeware. Well, except the slot car timing system I wrote in C++ > for Linux many moons ago. > > Honestly Python seems like a breath of fresh air and possibly a way to > get back to my BASIC roots, you know, programming just for the fun of > it. > > Since I don't have a specific problem to solve, besides > Pythonchallenge (which I found very cryptic), and Project Euler (which > I found beyond my mathematics skills), is there a place to go for > increasingly difficult problems to solve? I have followed a number of > the recommended online tutorials that contain a logical progression of > problems and yet they all end at the point where a person has enough > knowledge of the syntax, but not really enough to do anything. I've noticed that there's a gap between learning the syntax and actually being able to do something myself. It's pretty annoying. However, all you need is to come up with some projects that you'd like to do, such as inventorying some collection you have (CDs, DVDs, Clocks, whatever). Then you have a place to start. The next step is to break the project down into smaller parts until you have parts to tackle. Let's say you want to inventory your DVDs for example. First, you'd need to figure out how much data about each title you want. Examples might include Title, Director, top 3 actors, price, and purchase date. Once you know what you want to store, you can learn about data persistence (i.e. databases!). Or you could join a local Python Users Group or an open source project. I learn a lot just helping people on this and other Python lists. Mike From rcdailey at gmail.com Wed Jul 30 15:49:41 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 30 Jul 2008 14:49:41 -0500 Subject: Reasoning behind 'self' parameter in classes? In-Reply-To: <4890C526.70204@nienna.org> References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> <4890ACE4.4060703@acm.org> <496954360807301227h1dea050eg735314beb0b5ff16@mail.gmail.com> <4890C526.70204@nienna.org> Message-ID: <496954360807301249w6a5080d5p1efd0af4dd1252e5@mail.gmail.com> On Wed, Jul 30, 2008 at 2:46 PM, Matthew Fitzgibbons wrote: > Robert Dailey wrote: > >> On Wed, Jul 30, 2008 at 1:03 PM, Brett g Porter > bgporter at acm.org>> wrote: >> >> Robert Dailey wrote: >> >> This is an example of a response I'm looking for: >> "The self parameter is required because the parser is a bit old >> and needs to know the exact object you're referencing" >> >> This is _not_ an example of what I'm looking for: >> "Specifying self is a great mysterious thing that we should >> never question. Do not question the language! The language is >> mighty! Don't bring C++ to Python!" >> >> >> Fredrik Lundh has written a very clear explanation of this at >> >> http://effbot.org/pyfaq/why-must-self-be-used-explicitly-in-method-definitions-and-calls.htm >> >> (or http://bit.ly/3EUiCf if you don't feel like stitching that URL >> back together...) >> >> >> This sounds like an article of opinion. He's not really given any reasons >> other than "Well, it makes this easier or look better". True that >> declarations are the determining factor in C/C++, however I was thinking of >> more or less an implied 'self'. For example: >> >> # Consider this normal syntax: >> class MyFoo: >> def DoFoo( self ): >> self._member = 6 >> >> # Elimintating 'self' in the parameter list should still work as far as >> the >> # interpreter is concerned, since 'self' in this case now acts like 'this' >> # in C++. The below code should be equivalent. >> class MyFoo: >> def DoFoo(): >> self._member = 6 >> >> Given the code samples above, is there any technical reason why this >> cannot be done? Thanks for the input guys, and thanks more over for keeping >> this easy-going. >> >> >> ------------------------------------------------------------------------ >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > Your first example could be written: > > class MyFoo(object): > def do_foo(the_foo_instance): > the_foo_instance._member = 6 > > 'self' is not special the way 'this' is in C++. It's just a name for an > object reference just like any other name for any other object reference. > > -Matt > Yes, I realize that it can have any name. But this does not change its purpose. It was simply an example. In the second code snippet I gave you, 'self' would become a reserved word and a user would have to use that to reference the object from which the function was called. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at fenestra.com Tue Jul 22 12:29:40 2008 From: steve at fenestra.com (Steve Schafer) Date: Tue, 22 Jul 2008 12:29:40 -0400 Subject: The Importance of Terminology's Quality References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: On Tue, 22 Jul 2008 10:21:50 +0100, Martin Gregorie wrote: >The first time I ran across the term "thunking" was when Windows 3 >introduced the Win32S shim and hence the need to switch addressing between >16 bit and 32 bit modes across call interfaces. That was called "thunking" >by Microsoft and even they would surely admit it was a kludge. Win32s thunks are a completely different beast from the original Algol 60 thunks. As far as I know, the first published description of thunks was: Ingerman PZ (1961) Thunks: A way of compiling procedure statements with some comments on procedure declarations, CACM 4:55-58. Steve Schafer Fenestra Technologies Corp. http://www.fenestra.com/ From ggpolo at gmail.com Tue Jul 1 21:14:50 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 1 Jul 2008 22:14:50 -0300 Subject: SQLite and Python 2.4 In-Reply-To: <200807020051.m620pxS4011942@vm-mailout2.fpw.ch> References: <200807020051.m620pxS4011942@vm-mailout2.fpw.ch> Message-ID: On Tue, Jul 1, 2008 at 9:51 PM, Joe Goldthwaite wrote: > I'm confused. (Not a new experience). I've got a web application running > under Zope. I use the Wing IDE for testing and debugging. When trying to > recreate problems that come up on the web, I wrote some little routines that > pull my cookies out of the Firefox cookies.txt file into my code. That way, > I'm working with all the same options under Wing that my app uses when > running under Zope. > > That's worked great until I upgraded to Firefox 3. Firefox 3 moved their > cookies from cookies.txt to cookies.sqlite. I haven't worked with SQLite at > all so I started searching for examples and found this; > > import sqlite3 > conn = sqlite3.connect('test.db') > c = conn.cursor() > rows = c.execute('SELECT * from somefile') > > Looks simple enough but I can't get it to work. Here are my questions; > > 1. How do you get sqlite3 for Python 2.4? I can't find it anywhere. You need sqlite itself (www.sqlite.org) and bindings, pysqlite 2 (http://oss.itsystementwicklung.de/trac/pysqlite/) or aspw (http://code.google.com/p/apsw/) > > 2. If sqlite3 is only for Python 2.5, does sqlite2 work the same way? > You are confused, yes. The sqlite3 package that comes with python2.5 is actually pysqlite2, which interfaces with sqlite3. Also, sqlite3 and sqlite2 files format are not compatible. > 3. Looking at the cookies.sqlite file, I see some text right at the top > "SQLite format 3". Does that mean that I need to use sqlite3? Yes > > I kind of got the above example using pysqlite2.4.1 for python 2.4. I get > through the part where I create the connection object but the resulting > object doesn't have a cursor method. I thought that maybe it wasn't > recognizing the cookies.sqlite file as a SQLite database so I tried the same > code giving it a junk text file instead and it behaved the same way. Since > I didn't get an error message, I'm thinking that I've got the wrong version > for the Firefox cookies.sqlite file. > > I don't have a clue as to where else to look to trace it down. I'm hoping > that someone here is more familiar with it and can give me some pointers. > > Thanks, > > Joe Goldthwaite > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From dave.hirschfeld at gmail.com Tue Jul 1 06:51:11 2008 From: dave.hirschfeld at gmail.com (Dave) Date: Tue, 1 Jul 2008 03:51:11 -0700 (PDT) Subject: PyPy questions References: Message-ID: On 1 Jul, 04:09, Allen wrote: > I read the website of some information about PyPy, and how a translator > translates the RPython code to C/CLI/Java/etc to be compiled to a native > executable or something like that. ?Would it be possible, in PyPy, to > write such an extension that could easily be compiled to native code > from Python code? ?Is this functionality planned in a future release of > it? ?Also, how is the source distributed (If I opt to use it I will end > up compiling it on a system without an initial python install (a scratch > linux system)), so does the source include the generated C code? > > B. Vanderburg II Were you thinking of something like this? http://www.enthought.com/~ischnell/compdec.html -Dave From __peter__ at web.de Thu Jul 10 02:37:01 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Jul 2008 08:37:01 +0200 Subject: error when porting C code to Python (bitwise manipulation) References: Message-ID: Jordan wrote: > C: > > u starts at 1050 > > u += 0xe91aaa35; > > u is now -384127409 Hm, a negative unsigned... > Python: > > ? ?u starts at 1050 > > ? ?u += 0xe91aaa35 > > ? ?u is now ?3910839887L Seriously, masking off the leading ones is the way to go: >>> -384127409 & 0xffffffff == 3910839887 & 0xffffffff True Peter From jonnojohnson at gmail.com Tue Jul 1 17:46:35 2008 From: jonnojohnson at gmail.com (Jonno) Date: Tue, 1 Jul 2008 16:46:35 -0500 Subject: Combination of element-wise and matrix multiplication Message-ID: <3d15ebce0807011446k4347f2b7l462bb2491c79db2e@mail.gmail.com> I have two 2x2 arrays a & b. a=(([c,d],[e,f])) b=(([g,h],[i,j])) Each of c,d,e,f,g,h,i,j are all 1xN arrays I want to matrix multiply a & b to create a 2x2 array x, where the elements of x are created with element-wise math and result in the following: x[0,0] = c*g+d*i x[0,1] = c*h+d*j x[1,0] = e*g+f*i x[1,1] = e*h+f*j What is the simplest way to do this? I ended up doing the matrix multiplication manually as above but this doesn't scale very nicely if a & b become larger size. Cheers, Jonno. -- "If a theory can't produce hypotheses, can't be tested, can't be disproven, and can't make predictions, then it's not a theory and certainly not science." by spisska on Slashdot, Monday April 21, 2008 -------------- next part -------------- An HTML attachment was scrubbed... URL: From aspersieman at gmail.com Thu Jul 24 07:10:15 2008 From: aspersieman at gmail.com (Aspersieman) Date: Thu, 24 Jul 2008 13:10:15 +0200 Subject: Autocompletion and Interactive Tables in a Python IDE In-Reply-To: References: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Message-ID: <48886317.6040801@gmail.com> > > On Jul 24, 4:10 am, Aspersieman wrote: > >> Anthony wrote: >> >>> Hi, I'm a FoxPro programmer, but I want to learn python before it's >>> too late. I do a lot of statistical programming, so I import SPSS >>> into python. In my opinion, the best features of Visual FoxPro 9.0 >>> were: >>> a) Intellisense (tells you what classes/methods are available and what >>> variables go into a function) >>> b) Code Completion (guesses your code after four letters) >>> c) Data-Orientation; multiple data sessions can be open, data can be >>> viewed easily >>> >>> Python's IDLE has only half of the first of these features. I did a >>> lot of searching and found the PyDev extensions for Eclipse's Python >>> IDE, and found that they've got Intellisense. I'm still missing b and >>> c, and am getting extremely frustrated programming so slowly.. >>> >>> So two questions: >>> Is there any package, gui, IDE, anything that will do FoxPro-style >>> code completion? If it works in Eclipse, even better.. >>> I can't find a good screenshot, but here's a better description: >>> You type "BROW" and it pops up a window that says "BROWSE" ..at this >>> point if you hit enter it completes the word.. >>> >>> and >>> >>> How can I view open SPSS data in one of the Python GUIs? Again, >>> Eclipse would be the preference. >>> Here's an example of how I'd like to browse the data: >>> http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=... >>> I don't want to have to switch back and forth between Python and SPSS >>> while I'm programming; I just want to stay in one of them.. >>> >>> What can I do? I feel extremely inefficient when I don't have these >>> three features.. >>> >>> Thanks in advance. >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> You might want to try vim. It has a steep learning curve, but definitely >> increases productivity _alot_. >> >> Here is a tutorial on setting up vim with : >> 1) Code completion (intellisense) - including tooltips (!!!) >> 2) Jump between your python code and the python class libraries. >> 3) Syntax checking >> 4) A handy source browser >> 5) Debugging (using pdb) >> 6) [All the other vim goodies - already included] >> Above instructions available herehttp://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/ >> >> I have been using the above setup for a while and find it superior to >> _any_ IDE I've ever worked with. >> >> I'm not sure what you mean by 'Data-Orientation' but I'm sure there's a >> suitable alternative/replacement for it in vim. >> >> Regards >> >> Nicolaas >> >> -- >> Anthony wrote: > FoxPro is data-oriented, which means that at any time you have any > number of data sets open in the workspace and browse them immediately > by running one line of code in the command window. It's a really > important feature in terms of efficiency; I don't want to have to move > back and forth between SPSS and an IDE when I'm figuring out what code > to write, that takes six keystrokes for what FoxPro can do in one. > Again, here's what the BROWSE command presents: > > http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=vfptoolkit_figure02.tif > > > Does VIM have the capability to keep data open? -- Do any of these > IDEs have this browse capability?? I see what you mean by 'Data Oriented', however I'm not aware of such a 'data set' persistence functionality in vim. You can set up a similar (to FoxPro) environment using DBExt [1] plugin in vim and by using its (vims') built-in session functionality. To set up dbext for FoxPro in vim you might need to use ODBC but it should be quite straight forward provided you read the help. I work on SQL Server (using python and vim) and frequently have many queries result sets open that I'm busy with. When I have to go, all I do is save my session in vim. When I return the next day, I open the session, and it there I have all the queries (not the data sets they return (however you can save that too)) and scripts etc, I was working on. To execute a query (even one embedded in some python code) I merely select the lines the query is on and type the key-mapping (I set up) to execute the query (3 key strokes) and I can view the result set in a split window below the current one. The aforementioned vim setup for python [2] and the DBExt plugin for vim give me all the functionality I need to develop python and/or database applications/scripts in one editor (IDE?). Also, there are so many other useful plugins [3] for vim I have no need of any other IDE (I've replaced Visual Studio .Net with vim as my IDE for Asp.Net applications). I'm sure that vim can meet all the required features you wanted initially. [1] http://www.vim.org/scripts/script.php?script_id=356 [2] here it is again : http://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/ [3] http://www.vim.org/scripts/script.php?script_id=1318 and http://www.vim.org/scripts/script.php?script_id=910 and http://vim.sourceforge.net/scripts/script.php?script_id=69 and http://www.vim.org/scripts/script.php?script_id=1658 Hope this helps :) Regards Nicolaas -- The three things to remember about Llamas: 1) They are harmless 2) They are deadly 3) They are made of lava, and thus nice to cuddle. From tdelaney at avaya.com Tue Jul 29 17:17:07 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 30 Jul 2008 05:17:07 +0800 Subject: Execution speed question In-Reply-To: <6f8uc6FahulcU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> For sets, I presume they are built on top of or like dicts, and >> there is nothing crazy in the low level implementation so that I can >> be guaranteed that if I don't alter the set, then the order, >> although arbitrary, will be maintained in successive iterations over >> the contents? > > It is currently that way, but relying on it is certainly to be > considered an implementation detail that might disappear without > warning. Fortunately, that's incorrect - it is a documented feature that *so long as the set is not modified in any way*, iterating over the set will return the elements in the same order each time. Tim Delaney From larry.bates at websafe.com` Sun Jul 27 21:55:10 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 27 Jul 2008 20:55:10 -0500 Subject: Where is the correct round() method? In-Reply-To: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> Message-ID: josh logan wrote: > Hello, > > I need a round function that _always_ rounds to the higher integer if > the argument is equidistant between two integers. In Python 3.0, this > is not the advertised behavior of the built-in function round() as > seen below: > >>>> round(0.5) > 0 >>>> round(1.5) > 2 >>>> round(2.5) > 2 > > > I would think this is a common need, but I cannot find a function in > the Python library to do it. I wrote my own, but did I miss such a > method in my search of the Python library? > > Thanks I think what you want is something like: math.ceil(x-0.4999999999999) -Larry From luster123 at gmail.com Fri Jul 11 04:40:50 2008 From: luster123 at gmail.com (luster123) Date: Fri, 11 Jul 2008 01:40:50 -0700 (PDT) Subject: Trying to learn Message-ID: Hey, Can someone please teach me the basics of Python and Pygame? From trinityedusystems at gmail.com Thu Jul 24 12:04:18 2008 From: trinityedusystems at gmail.com (francis) Date: Thu, 24 Jul 2008 09:04:18 -0700 (PDT) Subject: earn from home blogging Message-ID: <9231e7f9-71a6-4405-9a4e-9ae62d8bcdd2@z6g2000pre.googlegroups.com> visit for more information http://2earnfromblog.blogspot.com http://trinityedusystems.blogspot.com From pauladospublicidad at yahoo.com Fri Jul 11 05:45:00 2008 From: pauladospublicidad at yahoo.com (pauladospublicidad) Date: Fri, 11 Jul 2008 09:45:00 -0000 Subject: Question about: GUI Builder for Tkinter and call to C/C++ code Message-ID: First I'll introduce myself. I normally programm in C/C++ and Java. Sometimes I have to mix them (normally using C/C++ in java, because in java is easier to make portable graphic user interfaces). However to use C/C++ code in java is really complex and difficult. Not too much time ago, I discover python. I had think to use it for developing portable graphic user intefaces, that will call my C/C++ code / libraries / programs. I had thought to use tkinter for making the GUIs, for portability and for not installing anything more than python. It's to say, for not adding more packages because I'm new in python and I don't now too much about install new packages. I have seen that for wxpython there is gui builders (such as boa) but for tkinter I have not found anyon. I would like to know if anyone knows a GUI Builder for tkinter in order to develop my GUI's graphically and in a easier way. Apart from this, I would like to call my C/C++ code / modulles / applications from python. I have read that python is implemented normally in C, so is easy to add new modules from C. I would like to find any tutorial / manual / link for dummies in order to make this (call my C code from python). Another solution could be to call the GUI made in python from C/C++ code, but I'm sure this would be more complex. To sum up, if anyone knows something about this subjects, about what I would like to do, I'll appreciate any answer :D Byee!!!!! From gros_bedo at hotmail.com Thu Jul 10 11:07:44 2008 From: gros_bedo at hotmail.com (Gros Bedo) Date: Thu, 10 Jul 2008 17:07:44 +0200 Subject: Terminate a python script from linux shell / bash script Message-ID: >>That's not how it works. If you kill one running python script it will not >>effect other python scripts. Each script has its own interpreter process >>running. >GB> So, is there a way from the Linux shell or a bash script to terminate >GB> just one specific Python script ? >>So just kill it. Yes I've seen that each python script calls its own instance of Python. But how to know which is the good one in bash ? Is there a command that gets the parameters of process, so I could use grep to select the one containing the name of my script ? _________________________________________________________________ Votre contact a choisi Hotmail, l'e-mail nouvelle g?n?ration. Cr?ez un compte. http://www.windowslive.fr/hotmail/default.asp From keshet1 at umbc.edu Wed Jul 9 00:00:38 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Wed, 09 Jul 2008 00:00:38 -0400 Subject: a simple 'for' question In-Reply-To: <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> References: <4874017D.2000401@umbc.edu> <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> Message-ID: <487437E6.8010609@umbc.edu> oops, my mistake, actually it didn't work... when I tried: for x in folders: print x # print the current folder filename='Folder/%s/myfile.txt' %x f=open(filename,'r') it says: IOError: [Errno 2] No such file or directory: 'Folder/1/myfile.txt' I should mention that I am working in windows, could it be the / vs. \? I tried: for x in folders: print x # print the current folder filename='Folder\%s\myfile.txt' %x f=open(filename,'r') filename is now 'Folder\\1\\myfile.txt', and the pathway doesn't exist. Any suggestions? Thanks again for your time. Ben Brian Blais wrote: > On Jul 8, 2008, at Jul 8:8:08 PM, Ben Keshet wrote: > >> I want to use a 'for' iteration to manipulate files in a set of >> folders, something like: >> >> folders= ['1A28','1A6W','56Y7'] >> for x in folders: >> print x # print the current folder >> f = open('my/path/way/x/my_file.txt', 'r') >> ... >> > > > I think: > > f = open('my/path/way/%s/my_file.txt' % x, 'r') > > should work, although I would probably be more clear about the names, > like: > > folders=['1A28','1A6W','56Y7'] > for folder in folders: > filename='my/path/way/%s/my_file.txt' % x > fid=open(filename,'r') > .... > > also, make sure that you do mean the relative path my/path/way/... > # in current folder > as opposed to the absolute path: /my/path/way > # in root folder > > > bb > -- > Brian Blais > bblais at bryant.edu > http://web.bryant.edu/~bblais > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Samnsparky at gmail.com Sun Jul 13 22:52:16 2008 From: Samnsparky at gmail.com (Sparky) Date: Sun, 13 Jul 2008 19:52:16 -0700 (PDT) Subject: Newbie Threading Question References: Message-ID: <6e92ab0c-0371-4897-b4c4-f607a16c49ce@m36g2000hse.googlegroups.com> On Jul 13, 1:30?pm, Nick Dumas wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > I'm not an expert on Python threading, so don't take my word as low, > however, I believe that there's no need for a list of systems which > support it because the Python virtual machine handles it. Thus, any > system which supports Python (or at least Python versions with > threading) will support Python threading. Again, I don't know a lot > about this, but it would make sense. > > Sparky wrote: > > It seems strange, but I can't find a list of operating systems which > > support / don't support threading in Python. Can anyone point me in > > the right direction? > > > Thanks, > > Sam > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (MingW32) > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > iEYEARECAAYFAkh6V8YACgkQLMI5fndAv9hVKgCePbrN4nwbsdZXNfIcnm3cXac5 > 5kUAnR0OeNB0gjsksRD2W5gcZ8c0pby0 > =p3U+ > -----END PGP SIGNATURE----- Thanks. I think that should make sense. Plus, if it is part of the standard distribution, I would assume it is supported in most places. Sam From usenetthrowaway at gmail.com Mon Jul 28 07:56:03 2008 From: usenetthrowaway at gmail.com (Gary) Date: Mon, 28 Jul 2008 12:56:03 +0100 Subject: Proxy server? Message-ID: I've seen examples for HTTP and FTP use, but not for simply any TCP data on any port, which is what I require. Can anyone please point me in the right direction? TIA From kris at FreeBSD.org Tue Jul 8 09:58:31 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Tue, 08 Jul 2008 15:58:31 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> Message-ID: <48737287.1080909@FreeBSD.org> samwyse wrote: > On Jul 4, 6:43 am, Henning_Thornblad > wrote: >> What can be the cause of the large difference between re.search and >> grep? > >> While doing a simple grep: >> grep '[^ "=]*/' input (input contains 156.000 a in >> one row) >> doesn't even take a second. >> >> Is this a bug in python? > > You might want to look at Plex. > http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/ > > "Another advantage of Plex is that it compiles all of the regular > expressions into a single DFA. Once that's done, the input can be > processed in a time proportional to the number of characters to be > scanned, and independent of the number or complexity of the regular > expressions. Python's existing regular expression matchers do not have > this property. " Very interesting! Thanks very much for the pointer. Kris From alexnbryan at gmail.com Tue Jul 15 15:43:38 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 15 Jul 2008 12:43:38 -0700 (PDT) Subject: Testing for connection to a website Message-ID: <18473382.post@talk.nabble.com> Okay, I already made this post, but it kinda got lost. So anyway I need to figure out how to test if the user is able to connect to a specific website. Last time I got pointed to the urllib2 page, but if I do urlopen() and and am not connected, the program stops. So I don't know if that was what you guys wanted me to do, but I don't think so, you guys are smarter than that. So, how can I test for connection to a website. -- View this message in context: http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p18473382.html Sent from the Python - python-list mailing list archive at Nabble.com. From akineko at gmail.com Sat Jul 5 00:57:37 2008 From: akineko at gmail.com (akineko) Date: Fri, 4 Jul 2008 21:57:37 -0700 (PDT) Subject: Python XML-RPC Server with clientside Javascript Message-ID: Hello everyone, I have used Python SimpleXMLRPCServer to expose several methods to be used. My Python script creates a free-standing server and not a CGI script. I have tested its exposed methods using the following Python script: import xmlrpclib s = xmlrpclib.ServerProxy('http://localhost:8765') print s.my_method() I tested all methods one by one and they are working as I intended. Now, I want to use those exposed methods from a static html file (without any web server) using client side javascript. (i.e. Open File... from the browser (or file://...) ) I found many XML-RPC examples with javascript but all of them I found assume XML-RPC services to be deliver from a web server, such as Apache, as a CGI. I tried those examples with placing 'http://localhost:8765' as url, but they didn't work. How can I utilize the XML-RPC services from a free-standing SimpleXMLRPCServer in a static HTML page? Is it possible to do such? Do I need web server to use client-side javascript? I have searched the Internet for similar questions. I found similar postings but there were no clear answers. Any suggestions will be highly appreciated. Best regards, Aki Niimura From snowballz.game at gmail.com Fri Jul 18 22:51:19 2008 From: snowballz.game at gmail.com (Michael Lubker) Date: Fri, 18 Jul 2008 21:51:19 -0500 Subject: Any Game Developers here? In-Reply-To: <9B960401-8D79-44BC-B4A5-4BE2BD1869BC@gmail.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> <4A235BC6-5E46-4402-AF2D-BA3DBC175517@gmail.com> <76b841590807181605r106995d2k98486993a4eaccc4@mail.gmail.com> <9B960401-8D79-44BC-B4A5-4BE2BD1869BC@gmail.com> Message-ID: <76b841590807181951p10159677n881d2bdadf4f69fc@mail.gmail.com> PyOhio sounds fun... I've been wanting to get some sort of Barcamp or GameJam running where I live (in Austin, so you'd think there would be people interested) but no-one will bite. :/ Escort Wing was a fun project... I did a few mods for EW1. Will you release this demo anywhere? Just curious. Thanks Michael On Fri, Jul 18, 2008 at 7:52 PM, Stephen Johnson wrote: > Yes, I wrote the music, the GUI, and bits of code here and there.. Will > Hogben is working on EW 2 for Freeverse right now. But that was in BlitzMax, > and I'm in greener pastures now, working on my demo for PyOhio. > -Steve Johnson > On Jul 18, 2008, at 7:05 PM, Michael Lubker wrote: > > I'm interested in general... I know about PyGame and Pyglet, and have > used both. We're currently using Python-Ogre. In the end, I am looking > to find people interested in my project ( see > http://youtube.com/watch?v=E0QQ9JuclxE ), but I also want to find > people experienced with Python in general, not just one library. > (though of course I know that's not too likely) > > Aren't you one of the Escort Wing developers? :) > > Thanks > Michael > > On Fri, Jul 18, 2008 at 5:13 PM, Stephen Johnson wrote: > > I use the Pyglet library to make games. You want to look at the pyglet and > > pygame mailing lists, not this one. Use Google. > > In my opinion, PyGame is clunky and Pyglet is elegant, simple, and > > comprehensive. PyGame has more examples available, but Pyglet has great > > documentation and enough examples to answer any questions you might have. > > Both have active communities. > > -Steve Johnson > > On Jul 18, 2008, at 5:38 PM, Michael Lubker wrote: > > Any people that use Python as the predominant language for their game > > development here? > > ~Michael > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > ~ "The world hates change, yet it is the only thing that has brought > progress." ~ Charles Kettering > > http://snowballz.joey101.net > > -- ~ "The world hates change, yet it is the only thing that has brought progress." ~ Charles Kettering http://snowballz.joey101.net From robert.kern at gmail.com Mon Jul 28 19:21:58 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 28 Jul 2008 18:21:58 -0500 Subject: derivative in numpy In-Reply-To: <488E4F1D.3060908@islandtraining.com> References: <488E4F1D.3060908@islandtraining.com> Message-ID: Gary Herron wrote: > knielsen73 at gmail.com wrote: >> Hi, >> >> I am looking to do a simple derivative. I would expect such a function >> to be available in numpy, but can't find it. I have written my own, >> but just curious if anybody knows of such function in numpy. >> > > Derivatives are a property of functions. Since numpy provides > representations of arrays not functions, how would you expect this to work? > > To be more concrete, what you you expect the derivative of > [ [ 1 2 ] > [ 3 4 ] > ] > to be? > > Or do you have in mind some array representation of the coefficients of > a function of some pre-defined type - like a polynomial? Typically, when people ask questions like this, they have a uniform, discretely sampled version of the function, and they want the (forward,central,backward)-difference approximation of the derivative. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mail at timgolden.me.uk Thu Jul 24 10:50:40 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 24 Jul 2008 15:50:40 +0100 Subject: Python / PAMIE In-Reply-To: References: Message-ID: <488896C0.7000007@timgolden.me.uk> frankrentef wrote: > Can someone help with a PAMIE issue? I'm new to Python / PAMIE and > they seem like great tools but to be honest I'm finding that no > responses to questions can be found (Experts Exchange, etc.) I'm > hoping this will be the place. > > I tried to duplicate the authors "ie.writeScript" function shown at > > http://showmedo.com/videos/video?name=pythonMarchettiPamie3&fromSeriesID=25 I'd rather you posted the code you've tried. I'm not too keen on viewing a video just to get hold of a piece of code, and in any case that would only show me what the author's done. We need to see what you've done, and what the traceback was. Would you mind posting some code, please? Thanks TJG From rtw at freenet.co.uk Sat Jul 26 15:02:59 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 26 Jul 2008 14:02:59 -0500 Subject: Questions on 64 bit versions of Python References: <488aec52$0$21481$9b622d9e@news.freenet.de> <488B570C.8070202@v.loewis.de> Message-ID: Martin v. L?wis wrote in news:488B570C.8070202 at v.loewis.de in comp.lang.python: >> I just tested, I built a default C# forms app using the "AnyCPU" >> option and it ran as a 64 bit app (no *32 in Task Manager), this is >> on XP64. >> >> I have though installed the AMD64 version of the 2.0 framework and >> AFAICT neither windows update or the Visual Studio installer >> will install that by default, you have to go get it your self. > > Interesting. I only tested this in .NET 1.1. Perhaps they have changed > something since. How exactly did you launch the program? Does it change > if you use Python's os.spawn* to launch it? If subprocess.call will do then I can report the same results, a 64 bit process, using 32 bit CPython 2.5 to call it. Also if the programme (C#) is built with the 3.5 framework I get the same results, however interestingly there is no 64 bit build for the 3.5 framework (or at least I was unable to find one). Rob. -- http://www.victim-prime.dsl.pipex.com/ From rpw3 at rpw3.org Tue Jul 22 08:23:22 2008 From: rpw3 at rpw3.org (Rob Warnock) Date: Tue, 22 Jul 2008 07:23:22 -0500 Subject: The Importance of Terminology's Quality References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: Martin Gregorie wrote: +--------------- | John W Kennedy wrote: | > No, the "thunks" were necessary at the machine-language level to | > /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. | | Are you sure about that? +--------------- I don't know if John is, but *I* am! ;-} +--------------- | I used Algol 60 on an Elliott 503 and the ICL 1900 series back when | it was a current language. The term "thunking" did not appear in either | compiler manual nor in any Algol 60 language definition I've seen. +--------------- It wouldn't have been. Thunks were something used by Algol 60 *compiler writers* in the code generated by their compilers to implement the semantics of Algol 60 call-by-name, but were not visible to users at all [except that they allowed call-by-name to "work right"]. +--------------- | A60 could pass values by name or value and procedures by name. That | was it. Call by name is what is now referred to as reference passing. +--------------- (*sigh*) NO, IT IS NOT!!! Please go read the following: http://en.wikipedia.org/wiki/Thunk http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_name http://en.wikipedia.org/wiki/Jensen%27s_Device +--------------- | [Algol 60] did not have a mechanism for declaring anonymous procedures. +--------------- Quite correct, but completely off the mark. While an Algol 60 *user* could not declare an anonymous procedure, the *implementation* of an Algol 60 compilers required the ability for the compiler itself to generate/emit internal anonymous procedures, to wit, the above-mentioned thunks, sometimes creating them dynamically during the procedure call. [Actually, a pair of them for each actual argument in a procedure call.] +--------------- | That, like the incorporation of machine code inserts, would have been | a compiler-specific extension, so it is a terminological mistake to | refer to it without specifying the implementing compiler. +--------------- Again, "incompetent, irrelevant, and immaterial" [as Perry Mason used to so frequently object during trials]. Thunks were not "extensions" to Algol 60 compilers; they were part of the basic implementation strategy *within* Algol 60 compilers, necessary because of the semantics required by call-by-name. Basically, in Algol 60, each parameter must be passed [in general, that is, one can optimize away many special cases] as *two* closures -- conventionally called "thunks" by Algol 60 compiler writers -- one for "getting" (evaluating) and the other for "setting" the parameter [if the parameter was a "place" in Common Lisp terms, else an error was signalled]... IN THE CALLER'S LEXICAL ENVIRONMENT!! The big deal was two-fold: (1) each time a formal parameter was *referenced* in a callee, the expression for the actual parameter in the caller had to be *(re)evaluated* in the *caller's* lexical environment, and the value of that (re)evaluation used as the value of the referenced formal parameter in the callee; and (2) if a variable appeared twice (or more) in a parameter list, say, once as a naked variable [which is a "place", note!] and again as a sub-expression of a more complicated parameter, then setting the formal parameter in the *callee* would *change* the value of the actual parameter in the caller(!!), which in turn would change the value of the *other* actual parameter in the caller the next time it was referenced in the callee. The above-referenced "Jensen's Device" shows how this can be used to do "very tricky stuff". A simpler and shorter example is here: http://www.cs.rit.edu/~afb/20013/plc/slides/procedures-07.html Because the actual parameters in the callee had to be evaluated in the *caller's* lexical environment -- and because Algol 60 was fully recursive, allowed nested procedure definitions, and could pass "local" procedures as arguments -- efficient implementation of Algol 60 procedure calls almost necessitated placing the bodies of the compiler-generated actual parameter thunks on the caller's dynamic stack frame [or at least call instructions *to* the thunks which could pass the current lexical contours as sub-arguments]. Knuth's nasty "man or boy test" stressed this to the limit: http://en.wikipedia.org/wiki/Man_or_boy_test -Rob p.s. IIRC [but it's been a *long* time!], the ALGOL-10 compiler for the DEC PDP-10 passed each actual parameter as the address of a triple of words, of which the first two were executable and the third could be used to store a variables value (simple case) or to pass the lexical contour (more complicated case). When the callee needed to reference (evaluate) an argument, it used the PDP-10 XCT ("execute") instruction to execute the first word of the block, which was required to deliver the value to a standard register [let's say "T0", just for concreteness], and if the callee wanted to *set* an argument, it executed the *second* word pointed to by the passed address, with the new value also in a defined place [again, let's use T0]. So to implement "X := X + 1;" in the callee, the compiler would emit code like this: MOVE T1,{the arg (address) corresponding to "X"} XCT 0(T1) ; fetch the current value of X into T0. ADDI T0, 1 ; increment it XCT 1(T1) ; execute the "setter" for X. Now in the case where the actual parameter in the caller was a simple global variable, call it "Y", then the address passed as the arg could be the following "YTHNK" in static data space: YTHNK: MOVE T0,.+2 ; one-instruction "getter" MOVEM T0,.+1 ; one-instruction "setter" Y: BLOCK 1 ; the actual place where the value "Y" lives Whereas if the argument being passed were some more complicated expression, such as an array reference or a reference to a local procedure in the caller, then the 3-word arg block would be passed on the stack and the passed address would point to this [possibly dynamically-constructed] triple, where PUSHJ is the PDP-10 stack- oriented subroutine call instruction: PUSHJ P,{lambda-lifted getter code} PUSHJ P,{lambda-lifted setter code} EXP {lexical contour info needed for getter/setter to work} Efficient for the simple case; slow-but-correct for the messy case. ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From kyosohma at gmail.com Mon Jul 14 17:32:14 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 14 Jul 2008 14:32:14 -0700 (PDT) Subject: Using Python To Launch Python References: Message-ID: <77f3294e-4c1d-42cc-804b-ed1d5ad0a5a4@f63g2000hsf.googlegroups.com> On Jul 14, 4:01?pm, aha wrote: > Hello All, > ? I have a situation where I can count on a Python installation being > available on a system, but I can't count on it being a version of > Python needed by my application. ?Since my application has it's own > version of Python installed with it how should I use the system Python > to launch the version of Python that launches my Application. ?Yes, > this is a convoluted process, but not all Pythons are built the > same :) > > Right now I am leaning towards using exec to start a new process, but > I thought I would check to see if anyone else has had the need to > perform a task similar to this one. > > AHA As an alternative, you may be able to use the subprocess module of Python to do this too. Mike From angelaki at mpifr-bonn.mpg.de Fri Jul 25 08:56:51 2008 From: angelaki at mpifr-bonn.mpg.de (Emmanouil Angelakis) Date: Fri, 25 Jul 2008 14:56:51 +0200 Subject: Calling external program from within python Message-ID: <4889CD93.10908@mpifr-bonn.mpg.de> Hi, I am tryiong to do something obviously trivial such as: I have a c program called "tsys2list" that when it is ran it asks the user to give the value of "tcal" which is a variable. I want to call the "tsys2list" from within a pyrthon script lets call it "gamma.py" >>>but<<< I want to pass the value of "tcal" to th eprogram automatically and not by interacting with the keyboard. How do I do that? thanks i advance! manolis From detlev at die-offenbachs.de Sat Jul 5 03:51:04 2008 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 05 Jul 2008 09:51:04 +0200 Subject: ANN: eric 4.1.6 released Message-ID: Hi, this is to inform all of you about the immediate availability of eric 4.1.5. It is a bug fix release. As usual, it is available via http://www.die-offenbachs.de/eric/index.html. Eric4 is a Python IDE written using PyQt4 and QScintilla2. It comes with batteries included. For more details see the link above. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 10 03:39:34 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 10 Jul 2008 09:39:34 +0200 Subject: Impossible to change methods with special names of instances of new-style classes? In-Reply-To: <429cbef9-0027-4717-a39f-d7e7599e07ae@x35g2000hsb.googlegroups.com> References: <429cbef9-0027-4717-a39f-d7e7599e07ae@x35g2000hsb.googlegroups.com> Message-ID: <4875bc82$0$14076$426a34cc@news.free.fr> samwyse a ?crit : > On Jul 8, 4:56 pm, Joseph Barillari wrote: > >> My question is: did something about the way the special method names are >> implemented change for new-style classes? > > Just off the top of my head, I'd guess that it's due to classes > already having a default __call__ method, >>> object.__dict__.keys() ['__setattr__', '__reduce_ex__', '__new__', '__reduce__', '__str__', '__getattribute__', '__class__', '__delattr__', '__repr__', '__hash__', '__doc__', '__init__'] No __call__ method here. > used when you instatiate. The __call__ method used to instanciate a class is actually the metaclass __call__ method. >>> class MyType(type): ... def __call__(self, *args, **kw): ... print "pikaboo" ... return type.__call__(self, *args, **kw) ... >>> class MyClass(object): ... __metaclass__ = MyType ... >>> MyClass() pikaboo <__main__.MyClass object at 0x8334eec> >>> From coolman.guron at gmail.com Tue Jul 29 11:28:56 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Tue, 29 Jul 2008 08:28:56 -0700 (PDT) Subject: pygtk treview, ListStore not displaying properly References: <5cd417cf-4169-4805-8317-fb82c7e7be90@x29g2000prd.googlegroups.com> Message-ID: finally i solved it. This for any googler who comes this way def show_sync_wind(self,obj, data = None): t = Template.select(Template.q.synced == '0') self.synclstore = gtk.ListStore(str,str,str,str,str) x = 0 cr = gtk.CellRendererText() col = gtk.TreeViewColumn('#', cr); col.set_attributes(cr, text=0)#<------ attaches col to the 0`th item of liststore col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(0) self.tv.append_column(col) self.sno_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Title', cr); col.set_attributes(cr, text=1) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(1) self.tv.append_column(col) self.title_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Section', cr); col.set_attributes(cr, text=2) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(2) self.tv.append_column(col) self.section_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Category', cr); col.set_attributes(cr, text=3) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(3) self.tv.append_column(col) self.category_col = col cr = gtk.CellRendererText() col = gtk.TreeViewColumn('Sync', cr); col.set_attributes(cr, text=4) col.set_expand(True) col.set_clickable(True) col.set_resizable(True) col.set_sort_column_id(4) self.tv.append_column(col) self.sync_col = col self.tv.set_model(self.synclstore) self.tv.set_headers_clickable(True) #self.tv.set_expander_column(self.title_col) for y in t: x = x+1 row = self.synclstore.append([str(x),y.title,y.section.name,y.category.name,y.synced]) self.sync_window.show() From alif016 at gmail.com Mon Jul 21 19:38:32 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Mon, 21 Jul 2008 18:38:32 -0500 Subject: Converting List of String to Integer In-Reply-To: References: Message-ID: <48851DF8.6070807@gmail.com> Samir wrote: > For my small list, I didn't notice a > discernible increase in speed, but I may have to try it with a larger > list size. > About speed, and memory consumption: List comprehensions (http://docs.python.org/tut/node7.html#SECTION007140000000000000000) are just shortcuts for for-loops. I do not believe there is any speed benefit. However, there are generators, they basically load one part of an iterator (a list in this case) at a time, this can greatly reduce memory usage. Have a look at PEP 289: http://www.python.org/dev/peps/pep-0289/ Here is the list comprehension as a generator (actually 2): n = ((int(i) for i in k) for k in a) Note, you can't just print a generator, it only computes something when needed: >>> print n You can, however iterate over it: In [2]: for k in n: ....: for i in k: ....: print i, ....: ....: 1 2 3 4 5 6 7 8 9 0 In [3]: n = ((int(i) for i in k) for k in a) In [49]: list(n) Out[49]: [, , , ] Each sub-list is a generator too! In [50]: n = ((int(i) for i in k) for k in a) In [51]: for i in list(n): # list() converts the variable n to a list ....: list(i) ....: ....: Out[51]: [1, 2] Out[51]: [3] Out[51]: [4, 5, 6] Out[51]: [7, 8, 9, 0] This is only going to make a difference if you were dealing with a *very* large data set. I thought I would show you even if you never user them, for learning purposes. Note: a generator is one way, redefine it every time you use it. -- Andrew From fredrik at pythonware.com Wed Jul 16 10:31:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 16:31:42 +0200 Subject: Best Python packages? In-Reply-To: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> Message-ID: Ben Sizer wrote: > make my development a lot easier. Knowing what kind of development you do might help, of course. Some libraries are excellent in some contexts and suck badly in others... Looking at things that larger projects and distributions use can also be a good idea. For example, if you're doing scientific stuff, go directly to enthought.com. If you're doing web stuff, look at the libraries big Django applications use. Etc. From ethan at stoneleaf.us Tue Jul 15 18:32:30 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 15 Jul 2008 14:32:30 -0800 Subject: Measure class, precision, significant digits, and divmod() In-Reply-To: References: Message-ID: <487D257E.7080506@stoneleaf.us> Ken Starks wrote: > Ethan Furman wrote: > >> Hey all. >> > > >> >> As I have mentioned before, I am making this Measure class for two >> reasons: experience with unit testing, I like playing with numbers, I >> am unaware of anything like this having yet been done (okay, three >> reasons ;). >> > > >> >> Any and all feedback welcome, particularly from anyone who might >> actually use the Measure class. ;) >> >> ~Ethan > [snip] > +++++++++++++++++++++++++++++++++++++++ > > My principal interest in your work, however, is in the use of > unit tests as a pedagogical method of teaching programming, whether > self-taught or taught by an instructor. > > The students would be taught how to __run__ a unit test-suite > at as early an opportunity as possible. I can't see > why an eleven or twelve year old should not be able to cope > with it in hour one or two of a carefully structured course. > > What is needed for such an approach is a copy--in a public > place--of your unit tests for all methods > that are really part of the funtionality; together with > blanked-out definitions for them (i.e just the first line, > any in-code documentation, and 'pass' ). > > You would not include any 'internal' methods that are merely the way > __you__ happened to achieve the result. > > The programming 'exercise' would then be for the students, or > groups of students, to roll their own version until their code > passed all the unit tests. Definitely an interesting idea. I'm not sure if I should be worried about the 12-13 year old students tackling a complex class such as a new number class, or if I should prepare to be embarrased by how much simpler they are able to make equivalent code! ;) At any rate, once I'm done the code will be released under a very friendly license, so you'll be free to do that should you desire to. ~Ethan From arsyed at gmail.com Thu Jul 24 01:22:58 2008 From: arsyed at gmail.com (arsyed) Date: Thu, 24 Jul 2008 01:22:58 -0400 Subject: PyOpenGL Tutorial? In-Reply-To: <1216843629.18962.16.camel@generator> References: <1216843629.18962.16.camel@generator> Message-ID: <9a2cc7a70807232222t7d401279t5d91d5b8a9220ceb@mail.gmail.com> On Wed, Jul 23, 2008 at 4:07 PM, Clay Hobbs wrote: > I need a tutorial for PyOpenGL (specifically, to be used with wxPython). > I searched with Google and didn't find one. Does anybody know where one > is? > > -- Ratfink > > -- > http://mail.python.org/mailman/listinfo/python-list > Showmedo recently put up a tutorial screencast of using wx, opengl, python to build a molecular viewer: http://showmedo.com/videos/series?name=vXJsRwlBX Also, see: http://www.siafoo.net/browse?keyword_id=245 From digetl.try at gmail.com Sat Jul 26 06:04:52 2008 From: digetl.try at gmail.com (raja) Date: Sat, 26 Jul 2008 03:04:52 -0700 (PDT) Subject: Superfruit strategy Message-ID: <4cd96b23-ec87-4ca5-b401-6b70c1a98c0b@y22g2000prd.googlegroups.com> Six Elements of Superfruit Success Buy new book of expert insights! http://food-drinks.page.tl/ From jwashin at vt.edu Tue Jul 22 07:48:01 2008 From: jwashin at vt.edu (Jim Washington) Date: Tue, 22 Jul 2008 07:48:01 -0400 Subject: xpathEval fails for large files In-Reply-To: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> References: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> Message-ID: <4885C8F1.6070904@vt.edu> Kanchana wrote: > Hi, > > I tried to extract some data with xpathEval. Path contain more than > 100,000 elements. > > doc = libxml2.parseFile("test.xml") > ctxt = doc.xpathNewContext() > result = ctxt.xpathEval('//src_ref/@editions') > doc.freeDoc() > ctxt.xpathFreeContext() > > this will stuck in following line and will result in high usage of > CPU. > result = ctxt.xpathEval('//src_ref/@editions') > > Any suggestions to resolve this. > > Is there any better alternative to handle large documents? One option might be an XML database. I'm familiar with Sedna ( http://modis.ispras.ru/sedna/ ). In practice, you store the document in the database, and let the database do the extracting for you. Sedna does XQuery, which is a very nice way to get just what you want out of your document or collection of documents. Good: It's free (Apache 2.0 license) It's cross-platform (later Windows x86, Linux x86, FreeBSD, MacOS X) It has python bindings (zif.sedna at the cheese shop and others). It's pretty fast, particularly if you set-up indexes. Document and document collection size are limited only by disk space. Not so good: Sedna runs as a server. Expect to use in the range of 100M of RAM per database. A database can contain many many documents, so you probably only want one database, anyway. Disclosure: I'm the author of the zif.sedna package, and I'm interpreting the fact that I have not received much feedback as "It works pretty well" :) - Jim Washington From grante at visi.com Tue Jul 22 16:23:09 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 22 Jul 2008 15:23:09 -0500 Subject: proliferation of computer languages References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> <40429b65-23a0-489b-b5fd-ae6b8eee607d@t54g2000hsg.googlegroups.com> Message-ID: On 2008-07-22, szr wrote: > J?rgen Exner wrote: >> Chris Rathman wrote: >> >>> I can't say that I see any particular point to the essay. >> >> You must be new here. There never is any particular point to >> Xah Lee's rantings except to cross-post borderline topics to >> borderline relevant NGs and then lay back and enjoy the >> ensuing slaughter. > > Admittedly, I'm not all too familiar with his postings, but on > a general note, isn't it possible that someone else might not > see it the same as you do? I really didn't see anything really > sinister about the posting or it's content. That's the, uh, "beauty" of Xah Lee's posts. There's enough "there" there to suck people into what they think is going to be a conversation. But it's not really a conversation. He doesn't really read (or doesn't comprehend) responses to his posts and will just continue to ramble on in a somewhat insulting, half-rational stream of utterly opaque metaphors that he thinks makes him sound deeply philosphical. It has been theorized that he's an AI project. > It may very well be someone attempting to create a > conversation, someone who may not be generally well received a > lot of the time I gather. Quite a few people here in c.l.p put forth a a lot of effort (for Usenet, anyway) trying to have a reasonable exchange with xah lee, but it seems to be pointless. He's a perpetual critic who looks down his nose at everything and thinks he could do everything better than everybody else (not that he has actually ever _done_ anything, AFAICT). > Also, if have such a distaste for his postings, you are free > to ignore them as well. That said, I am all for alerting > someone of something which may be a complete waste of their > time, It's not a waste of your time if you find him entertaining, but I wouldn't expect any actual conversation where he reads and understands your replies and responds to them in a rational manner. > but in this case it feels like you are projecting your > own dislike for the OP. Unless the OP really is deserving of > such branding (in which case I'd stand corrected), I don't > think it is reason enough to tell others not to read of his > work just because you aren't particularly fond of it. > > Perhaps citing an actual example illustrating a reason to > avoid him like the plague would of helped :-) google groups should be able to find you plenty of examples both here and in perl groups. -- Grant Edwards grante Yow! I feel partially at hydrogenated! visi.com From mnordhoff at mattnordhoff.com Thu Jul 10 18:31:02 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 10 Jul 2008 22:31:02 +0000 Subject: redirecting output of process to a file using subprocess.Popen() In-Reply-To: <6bed3372-e049-4301-9d6b-6b7cf0a4c2d9@y21g2000hsf.googlegroups.com> References: <515ad1dd-15b0-4f7a-8ea2-87e0bb0cb47e@f36g2000hsa.googlegroups.com> <6bed3372-e049-4301-9d6b-6b7cf0a4c2d9@y21g2000hsf.googlegroups.com> Message-ID: <48768DA6.6040709@mattnordhoff.com> skeept wrote: > On Jul 9, 7:32 pm, rpar... at gmail.com wrote: >> I am trying to redirect stderr of a process to a temporary file and >> then read back the contents of the file, all in the same python >> script. As a simple exercise, I launched /bin/ls but this doesn't >> work: >> >> #!/usr/bin/python >> import subprocess as proc >> import tempfile >> name = tempfile.NamedTemporaryFile(mode='w+b') >> print 'name is '+ name.name >> >> cmd = [] >> cmd.append('/bin/ls') >> cmd.append('-l') >> cmd.append('/tmp') >> p = proc.Popen(cmd, stdout=name, stderr=proc.STDOUT, close_fds=True) >> while True: >> ret = p.poll() >> if (ret is not None): >> output = name.readlines() >> print 'out = ', output >> break >> >> $python sub.py >> name is /tmp/tmpjz4NJY >> out = [] >> >> I tried calling flush() on the file object but this didn't help >> either. Tried closing and re-opening the file, but closing the file >> object results in it getting deleted. Can the above be made to work by >> using tempfiles? >> >> thanks > > > your script works just fine. > The problem is that you have to move to the beggining of the file to > read the actual contents of > the file. > name.seek(0) > > The whole program would be: > > #!/usr/bin/python > import subprocess as proc > import tempfile > name = tempfile.NamedTemporaryFile(mode='w+b') > print 'name is '+ name.name > > cmd = [] > cmd.append('/bin/ls') > cmd.append('-l') > cmd.append('/tmp') > p = proc.Popen(cmd, stdout=name, stderr=proc.STDOUT, close_fds=True) > while True: > ret = p.poll() > if (ret is not None): > name.seek(0) > output = name.readlines() > print 'out = ', output > break This is an aside, but why the loop? ... p = ... p.wait() name.seek(0) ... (p.wait() returns p.returncode, just like p.poll() does, but you aren't using it anyway...) -- From timothywayne.cook at gmail.com Mon Jul 14 12:40:00 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Mon, 14 Jul 2008 13:40:00 -0300 Subject: Unicode confusion Message-ID: <1216053600.3028.59.camel@localhost.localdomain> Hi All, I'm not clear on how to use the unicode module. I need to be able to use certain characters such as the degree symbol and the mu symbol, i.e.: units = <"?"> if I say units=unicode("?"). I get UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128) If I try x=unicode.decode(x,'utf-8'). I get TypeError: descriptor 'decode' requires a 'unicode' object but received a 'str' What is the correct way to interpret these symbols that come to me as a string? Thanks, Tim -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. Home page: https://launchpad.net/oship/ Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From irmen.NOSPAM at xs4all.nl Wed Jul 2 17:31:00 2008 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 02 Jul 2008 23:31:00 +0200 Subject: Pyro: ProtocolError('connection failed') In-Reply-To: <6d223oFetjoU1@mid.uni-berlin.de> References: <6d223oFetjoU1@mid.uni-berlin.de> Message-ID: <486bf396$0$14360$e4fe514c@news.xs4all.nl> Diez B. Roggisch wrote: > > THis is just a guess - but it seems that somehow you don't bind your > pyro objects to the NIC's IP address, but to localhost (127.0.0.1) - > which of course won't work. That never happened to me though, try and > see the pyro docs on how to prevent/control to which IP a proxy is bound. > This problem has been discussed quite a bit on the Pyro mailinglist. What's happening is that Pyro is indeed binding the server on the loopback adapter (making it invisible from the outside). It does this because of what I (and several others) believe to be a bug in the default hosts file of many linux distributions: the local hostname resolves to the loopback adapter's address 127.0.0.1 instead of a sensible IP address. Pyro provides some ways to work around this issue, if you can't or won't fix the /etc/hosts file. --irmen PS I've replied to the original poster by private email conversation. I'm filtering newsgroups posts that originate from google groups, hence I only saw this message because of Diez's reply. From python at rcn.com Mon Jul 28 19:05:58 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 28 Jul 2008 16:05:58 -0700 (PDT) Subject: seemingly simple list indexing problem References: Message-ID: <999589a9-e1bb-4a64-801c-74ce060bc0c6@i24g2000prf.googlegroups.com> [Ervan Ensis] > I have a list like [108, 58, 68]. ?I want to return > the sorted indices of these items in the same order > as the original list. ?So I should return [2, 0, 1] One solution is to think of the list indexes being sorted according the their corresponding values in the input array: >>> s = [ 108, 58, 68 ] >>> sorted(range(len(s)), key=s.__getitem__) [1, 2, 0] Raymond From tjreedy at udel.edu Wed Jul 30 12:22:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jul 2008 12:22:56 -0400 Subject: Correct Attribute Assignment Methodology? In-Reply-To: <1217355766.2930.10.camel@localhost.localdomain> References: <1217355766.2930.10.camel@localhost.localdomain> Message-ID: Tim Cook wrote: > Say I have these classes: > > class Parent(object): > """Parent is abstract""" > a=None > def showA(): > return self.a > > class Child(Parent): > """inherits a and showA from Parent""" > > def __init__(self,a,b): > self.a=a > self.b=b > > def showAB(): > return self.a,self.b > > > class GrandChild(Child): > """inherits all of the above""" > > def __init__(self,a,b,c): > self.a=a > self.b=b > """should this be Child.__init__(a,b)? or Child.__init__(b)?"" Child.__init__(self,a,b) # requires all three params. > """if so; why? if not why not?""" In this simple case, I would probably do what you did. But a reason to call the baseclass init would be to not repeat yourself and keep the derived class in sync. Suppose, for instance, Child.__init__ had 'self.frob = math.sin(a) + math.cos(b) - math.sqrt(a*a+b*b)', and then you realize that the formula needs to be changed. Better to have it in one place. > self.c=c > > Thanks for answering these very basic questions but I am not certain > about the correct way. I know that in Python, assignment in the > GrandChild class will work but is that correct? From gherron at islandtraining.com Thu Jul 17 14:33:28 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 17 Jul 2008 11:33:28 -0700 Subject: properly delete item during "for item in..." In-Reply-To: References: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> <487F770D.8070405@islandtraining.com> Message-ID: <487F9078.2000205@islandtraining.com> Ratko wrote: > On Jul 17, 9:57 am, mk wrote: > >> Gary Herron wrote: >> >>> You could remove the object from the list with >>> del myList[i] >>> if you knew i. HOWEVER, don't do that while looping through the list! >>> Changing a list's length will interact badly with the for loop's >>> indexing through the list, causing the loop to mis the element following >>> the deleted item. >>> >> Jumping into a thread, I know how not to do it, but not how to do it >> properly? >> >> Iterating over a copy may _probably_ work: >> >> >>> t=['a', 'c', 'b', 'd'] >> >>> >> >>> for el in t[:]: >> del t[t.index(el)] >> >> >>> t >> [] >> >> However, is it really safe? Defining safe as "works reliably in every >> corner case for every indexable data type"? >> >> Con: suppose the data structure t is really, really big. Just deleting >> some items from t temporarily doubles the memory consumption. >> > > > > Would this work (safely) then? It does in my test cases but that of > course doesn't prove it works in a general case... > > for item in myList: > myList.remove(item) > No. Same problem, The for loop iterates through the list by keeping and incrementing an internal index. Any modification of the list does not change the index correspondingly. One proper way: newList = [] for item in myList: if ... whatever... newList.append(item) myList = newList Another, using list comprehension (it's the same thing really as the above): myList = [item for item in myList if ... whatever...] > > For dictionaries we can just iterate over values() or items() as > opposed to itervalues() or iteritems() since that's technically a copy > of values or items in the dict, right? > No! In fact the whole point of iteritems and itervalues and iterkeys is that they *DO NOT* make copies, so changing the dictionary out from under them is a programming error. If you use dict.items(), dict.keys() or dict.values(), then you're OK, because these methods *do* create new lists for both. Gary Herron > > R > > -- > http://mail.python.org/mailman/listinfo/python-list > From mseverin at bedlamgames.com Fri Jul 25 12:18:48 2008 From: mseverin at bedlamgames.com (Matthew Severin) Date: Fri, 25 Jul 2008 12:18:48 -0400 Subject: Trouble with rpdb2 and winpdb debuggers in embedded Python script Message-ID: Having some trouble getting rpdb2 and winpdb running properly with Python embedded in a C++ project. Our implementation has a number of C++ classes associated with Python classes. I am able to attach to the embedded script with the debugger and the program freezes and waits. However, when I step, next or go with the debugger, it instantly gives control back to C++ and doesn't step nicely through the python. Similarly, if I set a breakpoint, the program pauses momentarily but then doesn't break properly in the debugger. Just wondering if anyone had encountered anything similar, or had an idea what we are doing wrong. Thanks, Matt From leo_365 at yahoo.com Thu Jul 24 11:24:00 2008 From: leo_365 at yahoo.com (leo davis) Date: Thu, 24 Jul 2008 08:24:00 -0700 (PDT) Subject: need help with introducing more traffic Message-ID: <632875.28836.qm@web51808.mail.re2.yahoo.com> Hiya, I found this code snippet(reference http://www.goldb.org) and wish to do more with it than just send out a Http Get request.I would like to introduce more traffic -say by downloading files,crawling through all the links,logging in?etc etc,and wish to see how the web server reacts.I'm trying to stress the server to its limits....appreciate if anyone could provide me code/ideas to inject into this. the website -http://ftp.ruby-lang.org/pub/ruby/binaries/mswin32/ selected as example has many downloads.i tried from urllib import urlretrieve urlretrieve('http://ftp.ruby-lang.org/pub/ruby/binaries/mswin32/ruby-1.6.4-i586-mswin32.zip','ruby-1.6.4-i586-mswin32.zip'),but didnt work..... [QUOTE]import time import os import sys, urllib, re import httplib #from urllib import urlretrieve import urllib2 from threading import Thread class LoadManager: ??? def __init__(self): ??????? self.thread_refs = [] ??????? self.msg = ('localhost') # default ??? ??? def stop(self): ??????? for thread in self.thread_refs: ??????????? thread.stop() ??????????? ??? def start(self, threads=1, interval=0, rampup=1): ??????? for i in range(threads): ??????????? spacing = (i * (float(rampup) / float(threads))) ??????????? time.sleep(spacing) ??????????? agent = LoadAgent(interval, self.msg) ??????????? agent.setDaemon(True) ??????????? agent.start() ??????????? # print 'started thread # ' + str(i + 1) ??????????? self.thread_refs.append(agent) ??????? class LoadAgent(Thread): ??? def __init__(self, interval, msg): ??????? Thread.__init__(self) ??????? self.running = True ??????? self.interval = interval ??????? self.msg = msg ??????? ??? def stop(self): ??????? self.running = False ??????? ??? def run(self): ??????? while self.running: ??????????? start_time = time.time() ??????????? if self.send(self.msg): ??????????????? end_time = time.time() ??????????????? raw_latency = end_time - start_time ??????????????? expire_time = (self.interval - raw_latency) ??????????????? latency = ('%.3f' % raw_latency) ??????????????? print latency ??????????? else: ??????????????? raw_latency = 0 ??????????????? expire_time = (self.interval - raw_latency) ??????????? if expire_time > 0: ??????????????? time.sleep(expire_time) ??????????????? ??? def send(self, msg): ??????? ??????? try: ??????????? ??????????? req = urllib2.Request(msg) ??????????? response = urllib2.urlopen(req) ??????????? the_page = response.read() ??????????? ??????????? return True ??????? except: ??????????? print 'failed request' ??????????? return False ? def main(): ??? # sample usage ??? manager = LoadManager() ??? manager.msg = ('http://ftp.ruby-lang.org/pub/ruby/binaries/mswin32') ??? manager.start(threads=5, interval=2, rampup=2) if __name__ == '__main__': ??? main()[/QUOTE] -------------- next part -------------- An HTML attachment was scrubbed... URL: From larry.bates at websafe.com` Tue Jul 15 19:06:43 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 18:06:43 -0500 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: kjhishere at gmail.com wrote: > I need to know if I'm running on 32bit or 64bit ... so far I haven't > come up with how to get this info via python. sys.platform returns > what python was built on ... but not what the current system is. > > I thought platform.uname() or just platform.processor() would have > done it, but python returns an empty string on windows. Any ideas? > > Thanks, Ken How about sys.maxint? 64 bit returns 9223372036854775807 on 64-bit Linux for me. -Larry From anishchapagain at gmail.com Mon Jul 21 08:30:19 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Mon, 21 Jul 2008 05:30:19 -0700 (PDT) Subject: error Message-ID: <5f4395d7-9f5c-45c3-b137-655e5c618b8c@8g2000hse.googlegroups.com> from Tkinter import * root=Tk() f=Frame(root,height=200,width=200) b=Button(f,text="quit",command=f.quit) f.pack() root.mainloop() -------------------------------------------------- from Tkinter import * import sys root=Tk() f=Frame(root,height=200,width=200) b=Button(f,text="quit",command=sys.exit) f.pack() root.mainloop() I am wondering that why the button after clikcing is not closing the window..please any suggestion.. i tries command=f.quit, sys.quit also.. if there is something i'm missing please help From max at alcyone.com Thu Jul 31 00:27:53 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Jul 2008 21:27:53 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > I don't know if you can read minds, but you seem to have a lot of > trouble reading words. > > Can you read "it would be nice to be able to write ..."? Can you > understand what it means? Can you understand that it does *not* mean, > "one *should* be able to write ..."? You're sure going on about a distinction without a difference for a guy who childishly likes to call other people names. A reasonable person would have long ago moved on instead of blaming others for not immediately intuiting your thoughts, rather than straightforwardly reading your words. Which, by the way, includes at least three people other than myself. But I'll bet the mindless namecalling is really working out for you. Go, team, go! -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis You are my martyr / I'm a vestige of a revolution -- Lamya From gherron at islandtraining.com Wed Jul 16 11:16:04 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 16 Jul 2008 08:16:04 -0700 Subject: Angle brackets in command-line arguments? In-Reply-To: <52f1cde3-6240-46b0-8b03-478454e87688@b1g2000hsg.googlegroups.com> References: <52f1cde3-6240-46b0-8b03-478454e87688@b1g2000hsg.googlegroups.com> Message-ID: <487E10B4.7010103@islandtraining.com> Keith Hughitt wrote: > Hi all, > > I am using someone else's script which expects input in the form of: > > ./script.py arg2 > > I was wondering if the angle-brackets here have a special meaning? It > seems like > they specify an input and output stream to use in place of the > console. I could not > find anything in the python manual or Python in a Nut-shell though. > > Anyone know? > > > Thanks, > Keith > -- > http://mail.python.org/mailman/listinfo/python-list > In most Unix/Linux and related OS shells, the angled brackets *do* specify input and output streams as you surmise. However, they are *not* seen by the script as command line arguments. (And they are *not* brackets, and do not need to be matched. ) For any command, cmd < file redirects the contents of file to cmd's standard input, which in Python is accessed by reading from sys.stdin (use input or raw_input or sys.stdin.read...) Also for any command, cmd > file redirects the output of cmd to the named file. In Python this can be accessed using print, sys.stdout.write, ... Anything written to sys.stderr will not be caught by the ">" redirection, ans so will probably end up on the screen instead of in file. Also various shells will provide similar functionality using a variety of similar syntaxes: <<, >>, >&, and |, and so on. Gary Herron From dear.jay.logan at gmail.com Sun Jul 27 20:48:08 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Sun, 27 Jul 2008 17:48:08 -0700 (PDT) Subject: Where is the correct round() method? References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> Message-ID: <1aa8d56d-2deb-4c31-93b0-b20008ddb7d3@l42g2000hsc.googlegroups.com> On Jul 27, 7:58?pm, Gary Herron wrote: > josh logan wrote: > > Hello, > > > I need a round function that _always_ rounds to the higher integer if > > the argument is equidistant between two integers. In Python 3.0, this > > is not the advertised behavior of the built-in function round() as > > seen below: > > >>>> round(0.5) > > > 0 > > >>>> round(1.5) > > > 2 > > >>>> round(2.5) > > > 2 > > Huh? > > ?>>> round(2.5) > 3.0 > > Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo > CPU". ?What system are you on? > > It could be that 2.5 is really 2.49999... which would round down to 2, > but on any modern CPU (using IEEE floating point), 2.5 should be > representable exactly. > > However, as with any floating point calculations, if you expect exact > representation or calculations with any numbers, then you are misusing > floating points. > > Gary Herron > > > I would think this is a common need, but I cannot find a function in > > the Python library to do it. I wrote my own, but did I miss such a > > method in my search of the Python library? > > > Thanks > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I should reiterate that I am using Python 3.0 and not Python 2.x. It looks like the behavior round() has changed between these two versions. Here is the documentation for round() in Python 3.0: http://docs.python.org/dev/3.0/library/functions.html#round Of interest in this discussion is the second paragraph, which explains the change: Does anyone know the reason behind this change, and what replacement method I can use to get the original behavior? From straton at lampsacos.demon.co.uk Sat Jul 5 07:13:46 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Sat, 05 Jul 2008 12:13:46 +0100 Subject: Getting a path from a file object In-Reply-To: <3c500ce7-c697-44e9-9f13-f65edc509e1c@a32g2000prf.googlegroups.com> References: <3c500ce7-c697-44e9-9f13-f65edc509e1c@a32g2000prf.googlegroups.com> Message-ID: Andrew Fong wrote: > Newbie question: > > Let's say I open a new file for writing in a certain path. How do I > get that path back? > > Example: > >>>> f = open('/some/path/file.ext') >>>> some_function(f) > '/some/path/file.ext' > > Does some_function(f) already exist? And if not, how would I define > it? > > -- Andrew Read about f.name which is a kind of read-only attribute with caveats in the documentation: http://docs.python.org/lib/bltin-file-objects.html From castironpi at gmail.com Mon Jul 28 14:16:28 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 28 Jul 2008 11:16:28 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> <490769a4-2a48-41dc-a069-2cc003b332a2@b1g2000hsg.googlegroups.com> Message-ID: On Jul 28, 2:26?am, Nikolaus Rath wrote: > castironpi writes: > >> I think you misunderstood him. What he wants is to write > > >> class foo: > >> ? ?def bar(arg): > >> ? ? ? ?self.whatever = arg + 1 > > >> instead of > > >> class foo: > >> ? ?def bar(self, arg) > >> ? ? ? ?self.whatever = arg + 1 > > >> so 'self' should *automatically* only be inserted in the function > >> declaration, and *manually* be typed for attributes. > > > There's a further advantage: > > > class A: > > ? def get_auxclass( self, b, c ): > > ? ? class B: > > ? ? ? def auxmeth( self2, d, e ): > > ? ? ? ? #here, ... > > ? ? return B > > In auxmeth, self would refer to the B instance. In get_auxclass, it > would refer to the A instance. If you wanted to access the A instance > in auxmeth, you'd have to use > > class A: > ? ?def get_auxclass(b, c ): > ? ? ?a_inst = self > ? ? ?class B: > ? ? ? ?def auxmeth(d, e ): > ? ? ? ? ?self # the B instance > ? ? ? ? ?a_inst # the A instance > ? ? ?return B > > This seems pretty natural to me (innermost scope takes precedence), > and AFAIR this is also how it is done in Java. True. Net keystrokes are down in this method. Consider this: class A: def get_auxclass(b, c ): a_inst = self class B: @staticmethod #<--- change def auxmeth(d, e ): self # -NOT- the B instance a_inst # the A instance return B What are the semantics here? Error, No 'self' allowed in staticmethod- wrapped functions. Or, the a instance, just like a_inst? Do you find no advantage to being able to give 'self' different names in different cases? From jeffober at gmail.com Fri Jul 25 07:54:40 2008 From: jeffober at gmail.com (Jeff) Date: Fri, 25 Jul 2008 04:54:40 -0700 (PDT) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> Message-ID: <6c5e878b-8e82-4ffb-bd8a-c673804774fe@x29g2000prd.googlegroups.com> > I'd recommend using 'filter' and list comprehensions. Look at using reduce(). You can collect information about all of the nodes without necessarily building a large, intermediate list in the process. You might get some ideas from here [http://en.wikipedia.org/wiki/ Antiobjects]. From mathieu.prevot at gmail.com Thu Jul 10 16:35:26 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Thu, 10 Jul 2008 22:35:26 +0200 Subject: error with configure (svn 64857) Message-ID: <3e473cc60807101335p74fb61fdn875cdfd6b3826902@mail.gmail.com> Hi, I have the following error when I run configure: checking size of wchar_t... configure: error: cannot compute sizeof (wchar_t) what can I do ? Mathieu From kay.schluehr at gmx.net Mon Jul 14 07:11:03 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 14 Jul 2008 04:11:03 -0700 (PDT) Subject: importing from .pyd References: <3d66daeb-d45a-46be-bd4d-34a2225683d1@2g2000hsn.googlegroups.com> Message-ID: <3d0c2dbb-6835-44c8-b663-ecb8677a46dd@2g2000hsn.googlegroups.com> On 14 Jul., 06:03, moijes12 wrote: > hi > > there is a .pyd file present in the same folder as the script abc.py > by the name foo.pyd .I don't have foo.py .In the script abc.py I try > > import foo > > Error i get is > ImportError: DLL load failed: The specified module could not be found. It looks like the module that was accessed is either corrupt ( unavailable entry point ) or it contains dependencies to other modules which are not available. At least the latter can be checked without access to the source using the DependencyWalker: http://www.dependencywalker.com/ Notice that the message clearly indicates that Python found the module but failed to load it i.e. performing a LoadLibrary() which yielded a NULL pointer. From bruno.42.desthuilliers at websiteburo.invalid Tue Jul 1 11:18:16 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 01 Jul 2008 17:18:16 +0200 Subject: Scope and program structure problems In-Reply-To: <2kck641lali2uenplo8rhp3l9qks3idl03@4ax.com> References: <486a210f$0$15472$426a34cc@news.free.fr> <2kck641lali2uenplo8rhp3l9qks3idl03@4ax.com> Message-ID: <486a4ab8$0$23808$426a74cc@news.free.fr> John Dann a ?crit : > Many thanks for the repsonse - much appreciated. > > And sorry - yes I was probably compounding two separate issues here - > the GUI one and the variable scope one. Maybe the wxPython list would > be the best place to ask more about the GUI side of things. > > Then actually I can simplify my remaining question quite a lot - I > know you've partly answered this already but let me just rephrase > this: > > It must be commonplace to first use a variable or object What difference do you make between a variable and an object in this context ? > within one > function in a module and then want to use it again - perhaps still > with the same value For which definition of "same value" ? Remember, Python has *no* primitive types. Everything is an object. > as in the first function - in a second function. > So what's the recommended Python way round this? This is way too general to give a single straight answer - whatever the language FWIW. Are both function in the same module ? Are they methods of a same object ? Is the first function calling the second or are they totally unrelated ? > If I was using .Net > then I'd be declaring the variables/objects explicitly I personnally find the assignment, import, class and def statements (all having a binding behaviour) to be rather explicit. > and could set > their scope according to how/where they were declared. Names bound at the top-level are globals to the module. Names bound within a function (including arguments) are locals, unless there has been a global statement for them before in the same function's body. Names bound within a class statement lives in the class's namespace (IOW : they become class attributes, shared by all instances). And names bound as object attributes (using either obj.name = whatever or setattr(obj, "name", whatever)) become, well, object attributes. Now there may be a couple points worth paying attention to : 1/ some types (numerics, strings and tuples at least) are immutable. When doing : i = 1 i = 2 the second assignment doesnt mutate the integer object bound to i, but rebinds i to another integer object. 2/ the scope of a name isn't necessarily related to the scope of the object bound to that name. As an example, function's parameters *names* are local to the function, but the actual arguments - the objects passed when calling the function - are not. IOW, rebinding a parameter name withing a function body will rebind the name locally, but will not affect the object originally bound to that name. But *mutating* an object passed as argument *will* (off course) affect the object outside the function. > But if the > Python way is not to declare vars before use For which definition of "var" and "use" ? Did you really try to use a name that didn't exist in the accessible namespace - I mean, "use" for anything else than binding ? The first binding of a name in a namespace *is* the 'declaration'. If a name is not defined in the currently accessible namespace, and you try to do anything else than binding it, you'll get an exception. > then this must create > some problems for cross-function use. If what you mean is that it makes it harder to litter you code with true global variables, then it's obviously a *very* good thing IMHO !-) But no, there's no more problem with shared state in Python than in any other (imperative) language I know - usually less in fact since there's no "application global" namespace. Most of the time, the appropriate way to share state is to use classes - heck, that's what they were created for, isn't it ?-). Sharing state thru module-level variables is ok as long you only access it for reading (pseudo-constants etc). Sometimes, it's ok to use a module-level variable read-write, but this should be restricted to this particular module's implementation stuff (IOW : the name is not part of the API, and only functions / methods in this same module access it), and never done without a clear enough understanding of Python's namespaces and bindings. > So it is best to declare such vars at the module level (ie outside of > a function) and set eg to Null/None or to assign them with a keyword > such as global or static (assuming that concept applies in Python) it doesnt. > at first use inside a function or what? Usually, when you really need a module-level variable to be shared read-write between functions, it happens that you can bind it to a sensible default. Now what is a "sensible default" depends on the concrete use case. Anyway, by all means, explicitely bind this name at the top-level, before any code accessing it, and if possible with a comment about this name being shared read/write by functions x and y. My 2 cents... From kent.t.pinegar at lmco.com Thu Jul 24 09:38:54 2008 From: kent.t.pinegar at lmco.com (Pinegar, Kent T) Date: Thu, 24 Jul 2008 08:38:54 -0500 Subject: FW: [Jython-users] Jython Licensing Question Message-ID: <051C069C08E8EE49BB81482A4470BDF11C659EF8@emss07m14.us.lmco.com> All, Can anyone answer my question about the licensing for SocketServer.py? I would appreciate it. Kent -----Original Message----- From: Tobias Ivarsson [mailto:thobes at gmail.com] Sent: Thursday, July 24, 2008 2:13 AM To: Pinegar, Kent T Subject: Re: [Jython-users] Jython Licensing Question No I don't, I spent a few minutes yesterday when researching in what revision it got in to try and find where a list of contributors who have signed the contributors agreement could be found, but without success. I think you should try asking on python-list (python-list at python.org), the e-mail list for discussion about Python in general. /Tobias On Wed, Jul 23, 2008 at 9:25 PM, Pinegar, Kent T wrote: Tobias, Thanks. Do you know where I can get information on CPython? Specifically, licensing information. Kent ________________________________ From: Tobias Ivarsson [mailto:thobes at gmail.com] Sent: Wednesday, July 23, 2008 10:10 AM To: Pinegar, Kent T Cc: jython-users at lists.sourceforge.net Subject: Re: [Jython-users] Jython Licensing Question SocketServer.py is imported from CPython to where this copyright notice was committed in revision 18872, Jan 19 2001. IANAL so I don't know what is required to be able to redistribute this with Jython. But I guess that if it has been part of CPython since version 2.0 it should be fine for us as well... In fact this file (with that copyright notice) was included in the previous version of Jython as well. /Tobias On Wed, Jul 23, 2008 at 4:27 PM, Pinegar, Kent T wrote: The file SocketServer.py in the latest version of Jython, contains a copyright by Luke Kenneth Casson Leighton. There is not, however, any license agreement to cover this copyright in the Jython download. Does anyone know if this was an oversight, or existing licenses covers it? Kent Pinegar ------------------------------------------------------------------------ - This SF.Net email is sponsored by the Moblin Your Move Developer's challenge Build the coolest Linux based applications with Moblin SDK & win great prizes Grand prize is a trip for two to an Open Source event anywhere in the world http://moblin-contest.org/redirect.php?banner_id=100&url=/ _______________________________________________ Jython-users mailing list Jython-users at lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/jython-users From nicolas.pourcelot at gmail.com Fri Jul 18 07:49:04 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Fri, 18 Jul 2008 04:49:04 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: On 18 juil, 13:13, Peter Otten <__pete... at web.de> wrote: > nicolas.pource... at gmail.com wrote: > > In fact, 'any(myobject is element for element in mylist)' is 2 times > > slower than using a for loop, and 'id(myobject) in (id(element) for > > element in mylist)' is 2.4 times slower. > > This is not a meaningful statement unless you at least qualify with the > number of item that are actually checked. For sufficently long sequences > both any() and the for loop take roughly the same amount of time over here. > Sorry. I used short lists (a list of 20 floats) and the element checked was not in the list. (That was the case I usually deals with in my code.) From marek.rocki at wp.pl Sun Jul 13 13:42:17 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Sun, 13 Jul 2008 10:42:17 -0700 (PDT) Subject: Unexpected default arguments behaviour (Maybe bug?) References: <4f29ccf6-4daf-4e8e-8735-96cffd8a882e@t54g2000hsg.googlegroups.com> Message-ID: <475185e0-360a-452b-8d22-33ffc243b8a0@z66g2000hsc.googlegroups.com> sukkop... at gmail.com napisa?(a): > Hi, I have just encountered a Python behaviour I wouldn't expect. Take > the following code: > > ------------------------------------------------------------------------ > class Parent: > a = 1 > > def m (self, param = a): > print "param = %d" % param > > class Child (Parent): > a = 2 > > > p = Parent () > p.m () > > c = Child () > c.m () > ------------------------------------------------------------------------ > > I would expect to receive the following output: > param = 1 > param = 2 > > But actually I get: > param = 1 > param = 1 > > Is this the correct behaviour, and then why, or is it a bug? For > reference, I am using Python 2.5.1 on UNIX. > > Thanks in advance! I expect it's because default values for parameters are evaluated and bound at definition time. So once "def m (self, param = a):" line executes, the default value for parameter is forever bound to be 1. What you can do is for example: > def m (self, param = None): > if param is None: param = self.a > print "param = %d" % param Regards, Marek From JordanNealBerg at gmail.com Thu Jul 17 18:19:38 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Thu, 17 Jul 2008 15:19:38 -0700 (PDT) Subject: % sign in python? References: Message-ID: On Jul 17, 3:42?pm, Terry Reedy wrote: > korean_dave wrote: > > What does this operator do? Specifically in this context > > > test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) > > > (Tried googling and searching, but the "%" gets interpreted as an > > operation and distorts the search results) > > Having seen a number of comments like this over the years (about the > difficulty of searching for symbol meanings), I just started, last > night, a symbol index listing nearly all Python syntax uses of > non-alpha-or-digit ascii symbols. ?When I finish and upload it > somewhere, I will post an announcement with the link. > > tjr That sounds great Terry! I look forward to seeing this. ~Jordan From bblais at bryant.edu Tue Jul 8 20:29:52 2008 From: bblais at bryant.edu (Brian Blais) Date: Tue, 8 Jul 2008 20:29:52 -0400 Subject: a simple 'for' question In-Reply-To: <4874017D.2000401@umbc.edu> References: <4874017D.2000401@umbc.edu> Message-ID: <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> On Jul 8, 2008, at Jul 8:8:08 PM, Ben Keshet wrote: > I want to use a 'for' iteration to manipulate files in a set of > folders, something like: > > folders= ['1A28','1A6W','56Y7'] > for x in folders: > print x # print the current folder > f = open('my/path/way/x/my_file.txt', 'r') > ... > I think: f = open('my/path/way/%s/my_file.txt' % x, 'r') should work, although I would probably be more clear about the names, like: folders=['1A28','1A6W','56Y7'] for folder in folders: filename='my/path/way/%s/my_file.txt' % x fid=open(filename,'r') .... also, make sure that you do mean the relative path my/path/way/... # in current folder as opposed to the absolute path: /my/path/way # in root folder bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rcn.com Sun Jul 20 00:50:11 2008 From: python at rcn.com (Raymond Hettinger) Date: Sat, 19 Jul 2008 21:50:11 -0700 (PDT) Subject: atan2 weirdness References: <3b3ce28f-55d0-4db4-8eac-df0a9d1bc558@o40g2000prn.googlegroups.com> Message-ID: On Jul 19, 9:12?pm, "narutocan... at gmail.com" wrote: > hi > > atan2 is supposed to return the angle to x-axis when given y and x, I > suppose if I take [x,y] to one full circle, I should get 0-360 degree > back---- but no, I get 3 full revolutions! > maybe my understanding is wrong. > > from math import * > > def f(ang): > ?a=ang > ?if a>360: a-=360 > ?if a>360: a-=360 > ?if a<0: a+=360 > ?if a<0: a+=360 > ?return round(a) > > for i in range(0,360): > ?t=2*pi*i/360.0 > ?print i,f(atan2(sin(t),cos(t))*180.0) The "*180.0" part should be "*180/pi". Do yourself some favors. First use the degrees and radians functions in the math module. Second, when in doubt, print the intermediate results (that would have made the error obvious). Third, pick just one line of the result and compute it with your calculator by hand (to make sure you know what your program is doing. Lastly, when working with trig functions, always check the docs to make sure you know the ranges of values returned (i.e. atan2 returns from -pi to +pi). Here's a proposed revision: from math import pi, atan2, radians, degrees, cos, sin for i in range(360): t = radians(i) x = cos(t) y = sin(t) a = degrees(atan2(y, x)) print i, t, x, y, a Raymond From ojeeves at gmail.com Fri Jul 18 07:05:47 2008 From: ojeeves at gmail.com (oj) Date: Fri, 18 Jul 2008 04:05:47 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> Message-ID: <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> On Jul 18, 11:33?am, arnimavidyar... at gmail.com wrote: > Hi, > > Hi, > > I am taking a string as an input from the user and it should only > contain the chars:L , M or R > > I tried the folllowing in kodos but they are still not perfect: > > [^A-K,^N-Q,^S-Z,^0-9] > [L][M][R] > [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > > For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. > > regards, > SZ > > The string may or may not have all the three chars. With regular expressions, [^LRM] matches a character that isn't L, R or M. So: import re var = "LRLRLRLNR" if re.search(r'[^LRM]', var): print "Invalid" From cjw at ncf.ca Fri Jul 25 19:44:28 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 25 Jul 2008 19:44:28 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> Message-ID: Fuzzyman wrote: > On Jul 24, 6:41 am, Jordan wrote: >> Hi everyone, >> >> I'm a big Python fan who used to be involved semi regularly in >> comp.lang.python (lots of lurking, occasional posting) but kind of >> trailed off a bit. I just wrote a frustration inspired rant on my >> blog, and I thought it was relevant enough as a wider issue to the >> Python community to post here for your discussion and consideration. >> >> This is not flamebait. I love Python, and I'm not out to antagonise >> the community. I also realise that one of the issues I raise is way >> too ingrained to be changed now. I'd just like to share my thinking on >> a misstep in Python's guiding principles that has done more harm than >> good IMO. So anyway, here's the post. >> >> I've become utterly convinced that at least one criticism leveled at >> my favourite overall programming language, Python, is utterly true and >> fair. After quite a while away from writing Python code, I started >> last night on a whim to knock up some code for a prototype of an idea >> I once had. It's going swimmingly; the Python Image Library, which I'd >> never used before, seems quick, intuitive, and with the all the >> features I need for this project. As for Python itself, well, my heart >> still belongs to whitespace delimitation. All the basics of Python >> coding are there in my mind like I never stopped using them, or like >> I've been programming in this language for 10 years. >> >> Except when it comes to Classes. I added some classes to code that had >> previously just been functions, and you know what I did - or rather, >> forgot to do? Put in the 'self'. In front of some of the variable >> accesses, but more noticably, at the start of *every single method >> argument list.* This cannot be any longer blamed as a hangover from >> Java - I've written a ton more code, more recently in Python than in >> Java or any other OO language. What's more, every time I go back to >> Python after a break of more than about a week or so, I start making >> this 'mistake' again. The perennial justification for this 'feature' >> of the language? That old Python favourite, "Explicit is better than >> implicit." >> > > > It's damn useful for scoping. You can look in the body of your method > and tell whether you are accessing local variables or instance > variables. > > I'm a great fan of self and I'm afraid you're flogging a dead horse on > that one. > > Your point about rich comparison (at least the == != problem) is fair.. > This one is fixed in Python 3 though I believe. > > Michael Foord > -- > http://www.ironpythoninaction.com/ I hope that the OP will develop some specific proposal, narrowly focused on the "self" issue. It has always seemed redundant on the argument line of a definition. It does permit one to use some other word but is that of any real value. One can still use self.a= 'z' or perhaps .a= 'z'. Colin W. From wtanksleyjr at gmail.com Wed Jul 30 20:53:53 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Wed, 30 Jul 2008 17:53:53 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> <4ae2518f-10c0-49f2-b5d7-a75993b0a67d@z66g2000hsc.googlegroups.com> Message-ID: william tanksley wrote: > I'm still puzzled why I'm getting some non-Unicode out of an > ElementTree's text, though. Now I know. Okay, my answer is that cElementTree (in Python 2.5) is simply deranged when it comes to Unicode. It assumes everything's ASCII. Reference: http://codespeak.net/lxml/compatibility.html (Note that the lxml version also doesn't handle Unicode correctly; it errors when XML declares its encoding.) This is unpleasant, but at least now I know WHY it was driving me insane. > -Wm -Wm From subhabrata.iisc at hotmail.com Fri Jul 18 06:10:48 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Fri, 18 Jul 2008 03:10:48 -0700 (PDT) Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> <6eb733F67cpfU2@mid.uni-berlin.de> <32a81d0c-a74f-4b22-8add-15beb2643529@h17g2000prg.googlegroups.com> Message-ID: Hi Peter, In your code s would print first_char(of the last word)+" "+missing_word(the last word) I was looking all. Best Regards, Subhabrata. SUBHABRATA wrote: > Sorry if I didn't say that. > The input is a string "Petrol Helium Heaven Sky" > Now, in a3 it is "God Goddess Heaven Sky" is there, > it is matching Heaven and Sky but not Petrol and Helium as they are > not in a3. > Now, as per the code it is giving me an output "S" of "Sky" and > "Helium" > But I was looking for an output of "H S Petrol Helium" and not "S > Helium" meaning all the values of a5 and a6 will be concatenated in s. > Best Regards, > Subhabrata.. > > Marc 'BlackJack' Rintsch wrote: > > On Fri, 18 Jul 2008 01:31:59 -0700, SUBHABRATA wrote: > > > > > def try2(n): > > > a1=raw_input("PRINT A STRING:") > > > a2=a1.split() > > > a3="God Godess Heaven Sky" > > > for x in a2: > > > a4=a3.find(x) > > > if a4>-1: > > > a5=a3[a4] > > > print a5 > > > elif a4<0: > > > a6=x > > > print "It is not found" > > > print a6 > > > else: > > > print "Error" > > > s=a5+" "+a6 > > > print s > > > > > > Here, if I put a string like: > > > Petrol Helium Heaven Sky > > > In s it is giving me S Helium > > > But I am looking for an output of a5 and a6 concatenating all its > > > values not the last ones. Can you suggest me any help? Am I missing > > > any minor point? > > > > Maybe you should describe what the input looks like and what output you > > want to have and how the input and output are connected. In words, not in > > not very clear code with "numbered names". That's a silly idea and makes > > understanding the code very hard. Please use meaningful names! > > > > Ciao, > > Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Thu Jul 24 05:01:42 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 24 Jul 2008 02:01:42 -0700 (PDT) Subject: instance comparison References: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> Message-ID: On Jul 24, 6:50?pm, King wrote: > I am facing a problem where I am really confused about it. > > I am trying to compare to instances using: > > if inst1 == inst2 > > These instances have a overridden method __str__ which returns same > string. The condition result is true although they are different > instances. > > If I use: > > if id(inst1) == id(inst2) > > The results is false. What's happening here? > > If I am trying to store this pair in a set where other instances are > already stored, but it's not storing it. Although I am sure that there > is no pair already stored of same but even if Set is comparing by > using string return by __str__ method then it won't. > > How do I solve this? > > Is this mean when you have overridden __str__ method then it comapre > with results of __str__ No. Do you have a __cmp__ method, or an __eq__ method? Any other __twounderscores__ methods? It is impossible to tell what is going on from your description. Please supply the source of a *short* class that demonstrates the problem, and demonstrate it. From ddasilva at umd.edu Thu Jul 10 17:06:25 2008 From: ddasilva at umd.edu (Daniel da Silva) Date: Thu, 10 Jul 2008 17:06:25 -0400 Subject: You, spare time and SyntaxError In-Reply-To: References: Message-ID: <8d9ec3dd0807101406t441b6c23qea16f4097b926181@mail.gmail.com> I applaud your creativity. Very nice. On Wed, Jul 9, 2008 at 10:56 AM, wrote: > def ine(you): > yourself = "what?" > go = list("something"), list("anything") > be = "something" > please = be, yourself > yourself = "great" > for good in yourself: > if you is good: > good in you > please.add(more, good) > else: > def inition(lacks, clarity): > if clarity not in you: > please.remove(everything and go) > for bad in yourself: > list(bad) if bad else (ignore, yourself) > try: > (to, escape, your, fate, but) > except (Exception), son: > if bad in (you, son): > (you is bad, son), so > finally: > if bad in you: > lie, cheat, steal, be, bad > else: > print you, "is", yourself > you is good and yourself is not bad > please, go > > ine("Everyone") > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From asd at pittle.org Sun Jul 6 07:15:40 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Sun, 6 Jul 2008 04:15:40 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <20080704053113.GJ34192@nexus.in-nomine.org> Message-ID: <57dd27f6-1eab-4131-b169-2c327e4eb496@i76g2000hsf.googlegroups.com> On Jul 4, 8:58?am, Aspersieman wrote: > Jeroen Ruigrok van der Werven wrote:> -On [20080630 23:51], Ali Servet D?nmez (a... at pittle.org) wrote: > > >> This could be an extension, a plugin, an Emacs mode, a new editor or > >> even a brand new huge all-fancy IDE, I don't care, but what am I > >> missing here? > > > Vim's omnicomplete (CTRL-X CTRL-O). > > > See :help omnifunc within vim. > > I find Vim with ctags, omnicomplete and calltip support the BEST I've > tried so far. And I've tried many. > > Here's a tutorial on setting this up. > ? ?http://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/ > > Regards > > Nicol > > -- > > The three things to remember about Llamas: > 1) They are harmless > 2) They are deadly > 3) They are made of lava, and thus nice to cuddle. Oh my, that thing seems to work! I didn't try it my self, but checked out the URL you've mentioned. I think I've been unfair to Yu-Xi Lim before... Thank you. From aahz at pythoncraft.com Sun Jul 20 13:05:23 2008 From: aahz at pythoncraft.com (Aahz) Date: 20 Jul 2008 10:05:23 -0700 Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Message-ID: In article <2476438f-eaa2-495f-95fa-eb9efec25875 at e39g2000hsf.googlegroups.com>, Craig Allen wrote: > >(option 2) >Therefore option two is a family of options where class level members >can be used to share whatever needs to be shared, though strictly the >class is not a singleton since multiple instances are created which >merely share the data that should be single (say a big dictionary of >configuration information the class manages). That's only true if you actually instantiate the class. You can just use the class directly -- that's what I do. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From gagsl-py2 at yahoo.com.ar Fri Jul 11 05:24:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Jul 2008 06:24:03 -0300 Subject: numeric emulation and the rich comparison operators References: <48767316.3060607@stoneleaf.us> Message-ID: En Thu, 10 Jul 2008 17:37:42 -0300, Ethan Furman escribi?: > Greetings, List! > > Still working on my Measure class, and my next question is... (drum roll > please ;) > > What are the advantages of using __[eq|ne|lt|gt|le|ge]__ vs __cmp__? If your objects obey the trichotomy law (an object MUST BE less than, greater than, or equal to another one, and there is no other possibility) then __cmp__ is enough, and easier to define than all the rich comparison operations. In other cases, __cmp__ is not suitable: by example, complex numbers can't define "greater than" [in a way that preserves the meaning for real numbers]; you can only use "equal" or "not equal". You can't use __cmp__ for this, because it *has* to return either >0 or <0 (implying "greater than" or "less than"). In this case it's best to use the rich comparison operators: define __eq__ and __ne__ and make all other comparisons between complex numbers raise an exception. -- Gabriel Genellina From Russ.Paielli at gmail.com Sun Jul 27 18:34:10 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 15:34:10 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> On Jul 27, 3:11 pm, "Russ P." wrote: > On Jul 27, 12:39 pm, Bruno Desthuilliers > > > > wrote: > > Derek Martin a ?crit : > > > > On Sun, Jul 27, 2008 at 08:19:17AM +0000, Steven D'Aprano wrote: > > >>> You take the name down to a single letter. As I suggested in an earlier > > >>> post on this thread, why not take it down to zero letters? > > >> The question isn't "why not", but "why". The status quo works well as it > > >> is, even if it isn't perfect. Prove that implicit self is a good idea -- > > >> or at least prove that it is an idea worth considering. > > > > Come on, this sounds like a schoolyard argument. This comes down to a > > > matter of style, and as such, is impossible to prove. It's largely a > > > question of individual preference. > > > > That said, the argument in favor is rather simple: > > > > 1. This is an extremely common idiom in Python > > > 2. It is completely unnecessary, and the language does not suffer for > > > making it implicit > > > 3. Making it implicit reduces typing, reduces opportunities for > > > mistakes, and arguably increases consistency. > > > "arguably", indeed, cf below. > > > > As for the latter part of #3, self (or some other variable) is > > > required in the parameter list of object methods, > > > It's actually the parameter list of the *function* that is used as the > > implementation of a method. Not quite the same thing. And then, > > consistency mandates that the target object of the method is part of the > > parameter list of the *function*, since that's how you make objects > > availables to a function. > > > > however when the > > > method is *called*, it is omitted. > > > Certainly not. You need to lookup the corresponding attribute *on a > > given object* to get the method. Whether you write > > > some_object.some_method() > > > or > > > some_function(some_object) > > > you still need to explicitely mention some_object. > > > > It is implied, supplied by Python. > > > Neither. The target object is passed to the function by the method > > object, which is itself returned by the __get__ method of function > > objects, which is one possible application of the more general > > descriptor protocol (the same protocol that is used for computed > > attributes). IOW, there's nothing specific to 'methods' here, just the > > use of two general features (functions and the descriptor protocol). > > FWIW, you can write your own callable, and write it so it behave just > > like a function here: > > > import types > > > class MyCallable(object): > > def __call__(self, obj): > > print "calling %s with %s" % (self, obj) > > def __get__(self, instance, cls): > > return types.MethodType(self.__call__, instance, cls) > > > class Foo(object): > > bar = MyCallable() > > > print Foo.bar > > f = Foo() > > f.bar() > > > > Thus when an object method is called, it must be called with one fewer > > > arguments than those which are defined. This can be confusing, > > > especially to new programmers. > > > This is confusing as long as you insist on saying that what you > > "def"ined is a method - which is not the case. > > > > It can also be argued that it makes the code less ugly, though again, > > > that's a matter of preference. > > > >> It's not enough to show that a change "isn't bad" -- you have to show > > >> that it is actively good. > > > > But he did... he pointed out that *it saves work*, without actually > > > being bad. Benefit, without drawback. Sounds good to me! > > > >> "Don't need to look at the method signature" is not an argument in favour > > >> of implicit self. > > > > Yes, actually, it is. > > > It isn't, since there's no "method signature" to look at !-) > > > > If there is a well-defined feature of Python > > > which provides access to the object within itself, > > > The point is that you don't get access to the object "within itself". > > You get access to an object *within a function*. > > > The fact that a function is defined within a class statement doesn't > > imply any "magic", it just creates a function object, bind it to a name, > > and make that object an attribute of the class. You have the very same > > result by defining the function outside the class statement and binding > > it within the class statement, by defining the function outside the > > class and binding it to the class outside the class statement, by > > binding the name to a lambda within the class statement etc... > > > > then the > > > opportunities for mistakes when someone decides to use something else > > > are lessened. > > > >> You don't need to look at the method signature when you're using an > > >> explicit self either. > > > > That isn't necessarily true. If you're using someone else's code, and > > > they didn't use "self" -- or worse yet, if they chose this variable's > > > name randomly throughout their classes -- then you may well need to > > > look back to see what was used. > > > > It's bad programming, but the world is full of bad programmers, and we > > > don't always have the choice not to use their code. Isn't one of > > > Python's goals to minimize opportunities for bad programming? > > > Nope. That's Java's goal. Python's goals are to maximize opportunities > > for good programming, which is quite different. > > > > Providing a keyword equivalent to self and removing the need to name > > > it in object methods is one way to do that. > > > It's also a way to make Python more complicated than it needs to be. At > > least with the current state, you define your functions the same way > > regardless of how they are defined, and the implementation is > > (relatively) easy to explain. Special-casing functions definition that > > happens within a class statement would only introduce a special case. > > Then you'd have to explain why you need to specify the target object in > > the function's parameters when the function is defined outside the class > > but not when it's defined within the class. > > > IOW : there's one arguably good reason to drop the target object from > > functions used as methods implementation, which is to make Python looks > > more like Java, and there's at least two good reason to keep it the way > > it is, which are simplicity (no special case) and consistency (no > > special case). > > > Anyway, the BDFL has the final word, and it looks like he's not going to > > change anything here - but anyone is free to propose a PEP, isn't it ? > > The issue here has nothing to do with the inner workings of the Python > interpreter. The issue is whether an arbitrary name such as "self" > needs to be supplied by the programmer. > > Neither I nor the person to whom you replied to here (as far as I can > tell) is suggesting that Python adopt the syntax of Java or C++, in > which member data or functions can be accessed the same as local > variables. Any suggestion otherwise is a red herring. > > All I am suggesting is that the programmer have the option of > replacing "self.member" with simply ".member", since the word "self" > is arbitrary and unnecessary. Otherwise, everything would work > *EXACTLY* the same as it does now. This would be a shallow syntactical > change with no effect on the inner workings of Python, but it could > significantly unclutter code in many instances. > > The fact that you seem to think it would change the inner functioning > of Python just shows that you don't understand the proposal. It just occurred to me that Python could allow the ".member" access regardless of the name supplied in the argument list: class Whatever: def fun(self, cat): .cat = cat self.cat += 1 This allows the programmer to use ".cat" and "self.cat" interchangeably. If the programmer intends to use only the ".cat" form, the first argument becomes arbitrary. Allowing him to use an empty argument or "." would simply tell the reader of the code that the ".cat" form will be used exclusively. When I write a function in which a data member will be used several times, I usually do something like this: data = self.data so I can avoid the clutter of repeated use of "self.data". If I could just use ".data", I could avoid most of the clutter without the extra line of code renaming the data member. A bonus is that it becomes clearer at the point of usage that ".data" is member data rather than a local variable. From mail at microcorp.co.za Mon Jul 7 04:15:59 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 7 Jul 2008 10:15:59 +0200 Subject: Cross Compiler for Python? Message-ID: <000901c8e009$dbd29e40$0d00a8c0@hendrik> Up to now, I have been innocently using the vanilla python that comes with the Linux distribution (Suse in my case). For the past few days, I have been playing with a little device called an eBox - it is basically a 486 with 128Mb memory, and a 1Gig pcmcia flash drive. We want to try to use this as an industrial controller, so I want to load python onto it. So I downloaded the sources, and got them into the box, over its ethernet connection. Then I got stymied - the configure script will not run, because the "distribution" has no C compiler - it is basically a kernel, and Busybox, with precious little else. So I googled, and I found mobile python, and portable python, both aimed at windows. - no good to me. Adding "embedded" to the Google string is also useless, as it basically brings up instances of embedding the interpreter into another app, not for small processors. So how does one do a compile of python on one machine aimed at another one? - All I want is a vanilla installation with the stuff in all the usual places. And just to make matters interesting, the two Linux boxes I have available are both 64 bit dual core animals, one Intel, one AMD... I don't need much more than the interpreter, sys, os, sockets and ctypes. Alternatively, where can one find a set of binaries for 32 bit Linux? Looking for some sane advice please. - Hendrik From aaa at bbb.it Thu Jul 31 07:00:52 2008 From: aaa at bbb.it (Fred Mangusta) Date: Thu, 31 Jul 2008 12:00:52 +0100 Subject: Case tagging and python Message-ID: Hi, I'm relatively new to programming in general, and totally new to python, and I've been told that this language is particularly good for what I need to do. Let me explain. I have a large corpus of English text, in the form of several files. First of all I would like to scan each file. Then, for each word I find, I'd like to examine its case status, and write the (lower case) word back to another text file - with, appended, a tag stating the case it had in the original file. An example. Suppose we have three possible "case conditions" -all lowercase -all uppercase -initial uppercase only Three corresponding tags for each of these might be, respectively: -nocap -allcaps -cap Therefore, given the string "The Chairman of BP was asleep" I would like to produce "the/cap chairman/cap of/nocap /bp/allcaps was/nocap /asleep/nocap" and writing this into a file. I have the following algorithm in mind: -open input file -open output file -get line of text -split line into words -for each word -tag = checkCase(word) -newword = lowercase(word) + append(tag) rejoin words into line write line into output file Now, I managed to write the following initial code for s in file: lines += 1 if lines % 1000 == 0: print '%d lines' % We print the total lines sent = s.split() #split string by spaces #... But then I don't quite know what would be the fastest/best way to do this. Could I use the join function to reform the string? And, regarding the casetest() function, what do you suggest to do? Should I test each character of each word or there are faster methods? Thanks very much, F. From larry.bates at websafe.com` Mon Jul 21 16:01:38 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 15:01:38 -0500 Subject: persistent deque (continued) In-Reply-To: <4c985e86-c0c4-4cb3-b7ce-f8e105b7f85d@y21g2000hsf.googlegroups.com> References: <4c985e86-c0c4-4cb3-b7ce-f8e105b7f85d@y21g2000hsf.googlegroups.com> Message-ID: castironpi wrote: > Some time ago, I was asking about the feasibility of a persistent > deque, a double-ended queue. > > It runs into the typical space allocation problems. If you're storing > a pickle, you have to allocate and fragment the file you've opened, > since pickles can be variable-length strings; i.e. if the new data is > too long, blank out its entry, and grow the file. If you're storing a > data-type, you lose Python's dynamic-type advantages, as well as its > long integers, as they can be any length. If you change the object in > the deque, such as when using any mutable type, you have to update the > container too. > > Does anyone have any experience storing pickles (I am aware of the > similarities to shelf) to a database? > Can the file system facilitate the variable-length string problem? > How feasible is a length-of-length - length - data solution to the > unbounded integer problem? > Is there any alternative to completely re-pickling a large (say 1k > pickled) object you only change slightly? > What other issues are there? > Is a hybrid-storage type possible, that stores the contents of its > Python-allocated memory block to disk, including reference count, even > if it's a lot slower? The object could not contain any references to > objects not allocated on disk. > > A first approach is for the file to look like this: > > 00 data 01 data 02 > 01 data 03 data 04 > 02 data 05 data 06 > > Append would add: > > 03 data 07 data 08 > > AppendLeft would add: > > -01 data 09 data 0a > > Pop would remove 03, PopLeft would remove -01. You would need a > length-and-head index to make 'rotate' available. Remove would run a > worst-case risk of renumbering half of the indices stored, plus a > rotate. It is so much easier to implement this using a database table that IMHO most people would go that route. -Larry From newptcai at gmail.com Mon Jul 21 03:27:37 2008 From: newptcai at gmail.com (=?GB2312?B?0rvK18qr?=) Date: Mon, 21 Jul 2008 00:27:37 -0700 (PDT) Subject: Please recommend a RPC system working with twisted. Message-ID: <312040c6-4011-451e-8a45-f982c2e4462f@j1g2000prb.googlegroups.com> Hi all, I'm looking for an RPC system working with twisted. 1. Binary. I want it run faster than any xml based RPC. 2. Bidirectional. Unlike HTTP, on which the client has to poll the sever for events, the server should "call" the client's method to notify events. 3. C/Python support. Part of the system shall be written in C. 4. Could easily integrated with twisted. Unfortunately, there seems no such resolution existed. So maybe I have to give up some requirements. --------------------------------------------------------------------------------------------------------------------------- It would be wonderful if ICE could integrate with twisted! From vinay_sajip at yahoo.co.uk Tue Jul 15 19:31:37 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 15 Jul 2008 16:31:37 -0700 (PDT) Subject: How to package a logging.config file? References: <0a5713d6-8337-44a3-8347-012814345dd8@79g2000hsk.googlegroups.com> Message-ID: <779746bc-93db-4225-9b9f-46419ab44282@f36g2000hsa.googlegroups.com> On Jul 15, 3:04 pm, Matthew Wilson wrote: > On Mon 14 Jul 2008 09:25:19 AM EDT, Vinay Sajip wrote: > > > Is your package a library or an application? If it's a library, you > > should avoid configuringloggingusing a config file - this is because > >loggingconfiguration is process-wide, and if multiple libraries use > > fileConfig to configure theirlogging, you may get unexpected results. > > I thought that the point of usinglogging.getLogger('foo.bar.baz') was > to allow each module/class/function to choose from the available > configurations. > > So, I can define a really weird logger and still be a good citizen. > > As long as I don't tweak the root logger, is it safe to use a config > file? > > Matt The reason why using fileConfig in libraries is problematic is that fileConfig assumes it does the entire logging configuration. Whenever fileConfig is called, any loggers which are not explicitly mentioned in the config file (but are present in the logging system) are disabled. (They are not actually removed, since there may be still- running threads that have references to them.) You may think this is odd, but it's only because fileConfig was never intended for incremental configuration, only for a one-off configuration. So, a fileConfig'd configuration is meant to completely replace the existing configuration. So - you can use hierarchical naming of loggers to avoid stepping on other loggers - for example, prefixing with the company domain name if there's a possibility of use outside the company (in the same way as Java packages use e.g. com.sun.XXX for Sun's proprietary Java packages, or com.ibm.YYY for IBM's proprietary packages). However, I'd advise against using fileConfig in library code, as it is likely to disable already-instantiated loggers in other library packages. Best regards, Vinay Sajip From ldo at geek-central.gen.new_zealand Thu Jul 17 01:16:55 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 17 Jul 2008 17:16:55 +1200 Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> Message-ID: In message <4627d685-6eb0-443d-83bb-6392ea83e8d1 at 2g2000hsn.googlegroups.com>, Keith Hughitt wrote: > I have a UTC date (e.g. 2008-07-11 00:00:00). I would like to create a > UTC date ... >>> import calendar >>> calendar.timegm((2008, 7, 11, 0, 0, 0, 0, 0, -1)) 1215734400 ldo at theon> TZ=NZ date -d "00:00:00 01-Jan-1970Z +1215734400 seconds" Fri Jul 11 12:00:00 NZST 2008 The general form of the call is "calendar.timegm((Y, M, D, hh, mm, ss, 0, 0, -1))". See also , . > ... so that when I send it to MySQL (which treats all dates at local dates > by default) ... I don't like to use MySQL's date/time types. Instead, I usually have a simple integer field containing seconds since some origin time in UTC. If the time is that of some event, an origin of 00:00:00 01-Jan-1970 lets you use Unix/Linux system times directly. For recording dates/times that might go further back (e.g. dates of birth, historical events), I have used the Julian day origin, 1st January 4713 BC. From hat at se-162.se.wtb.tue.nl Wed Jul 9 07:09:09 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 09 Jul 2008 13:09:09 +0200 Subject: start reading from certain line References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> Message-ID: On 2008-07-09, antar2 wrote: > I am a starter in python and would like to write a program that reads > lines starting with a line that contains a certain word. > For example the program starts reading the program when a line is > encountered that contains 'item 1' > > > The weather is nice > Item 1 > We will go to the seaside > ... > > Only the lines coming after Item 1 should be read Not possible at most OSes, file reading always starts at the first character at the first line. Also, most OSes don't understand the 'line' concept natively, a file is just a long sequence of characters to them (end-of-line is also just a character, namely '\n' (or '\r\n' if you are using Windows). So you have to read the entire file, then throw away the bits you don't want to keep. Luckily, Python does understand what a 'line' is, which makes the prblem simpler. Have a look at the readline() function (or the readlines() function if your file is not too long). That should give you a start. Albert From gh at ghaering.de Fri Jul 4 04:41:01 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 04 Jul 2008 10:41:01 +0200 Subject: Recursive wildcard file search In-Reply-To: <496954360807031353n4f91f691recb330f7350cbf70@mail.gmail.com> References: <496954360807031353n4f91f691recb330f7350cbf70@mail.gmail.com> Message-ID: Robert Dailey wrote: > Hi, > > Is there a way to perform a recursive file search using wildcards in > python 3.0b1? [...] glob.glob() or glob.iglob(). -- Gerhard From __peter__ at web.de Fri Jul 18 05:57:11 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 11:57:11 +0200 Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> Message-ID: SUBHABRATA wrote: > I am trying the following code line: def try2(n): user_line = raw_input("PRINT A STRING:") user_words = user_line.split() my_line = "God Godess Heaven Sky" for word in user_words: pos = my_line.find(word) if pos >- 1: first_char = my_line[pos] print first_char elif pos < 0: missing_word = word print "It is not found" print missing_word else: print "Error" s = first_char + " " + missing_word print s try2(1) Do you recognise your code? With that jumpstart you should find the error in no time ;) > Here, if I put a string like: > Petrol Helium Heaven Sky > In s it is giving me S Helium > But I am looking for an output of a5 and a6 concatenating all its > values not the last ones. Can you suggest me any help? Am I missing > any minor point? Yes, use meaningful variables. They won't make your code magically correct but will make it a lot easier to pinpoint mistakes and false assumptions -- for you and others. Peter From larry.bates at websafe.com` Wed Jul 9 12:04:20 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 09 Jul 2008 11:04:20 -0500 Subject: FOSS projects exhibiting clean/good OOP? In-Reply-To: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> Message-ID: Phillip B Oldham wrote: > I'm wondering whether anyone can offer suggestions on FOSS projects/ > apps which exhibit solid OO principles, clean code, good inline > documentation, and sound design principles? > > I'm devoting some time to reviewing other people's code to advance my > skills. Its good to review bad code (of which I have more than enough > examples) as well as good, but I'm lacking in finding good examples. > > Projects of varying sizes would be great. I think the following are very good: Python Imaging Library (PIL) elementTree (actually anything that Fredrick Lundh has written is an excellent example) ReportLab wxPython Django That should keep you busy for a while. -Larry From jkrukoff at ltgc.com Wed Jul 30 17:20:13 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Wed, 30 Jul 2008 15:20:13 -0600 Subject: seemingly simple list indexing problem In-Reply-To: References: <999589a9-e1bb-4a64-801c-74ce060bc0c6@i24g2000prf.googlegroups.com> Message-ID: <1217452813.4123.168.camel@jmk> On Wed, 2008-07-30 at 14:08 -0700, wolfram.hinderer at googlemail.com wrote: > On 29 Jul., 01:05, Raymond Hettinger wrote: > > [Ervan Ensis] > > > > > I have a list like [108, 58, 68]. I want to return > > > the sorted indices of these items in the same order > > > as the original list. So I should return [2, 0, 1] > > > > One solution is to think of the list indexes > > being sorted according the their corresponding > > values in the input array: > > > > >>> s = [ 108, 58, 68 ] > > >>> sorted(range(len(s)), key=s.__getitem__) > > > > [1, 2, 0] > > > > To get the desired output you have to apply it twice: > >>> sorted(range(len(s)), key=sorted(range(len(s)), key=s.__getitem__).__getitem__) > [2, 0, 1] > > Wolfram > -- > http://mail.python.org/mailman/listinfo/python-list Thanks, I knew I was missing something simpler. -- John Krukoff Land Title Guarantee Company From deets at nospam.web.de Wed Jul 23 10:07:34 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 23 Jul 2008 16:07:34 +0200 Subject: python.exe crash and ctypes use References: Message-ID: <6eosb5F83oe6U1@mid.uni-berlin.de> waldek wrote: > Hi, > > I have module A.py and B.dll which exports C functions by cdecl_ > > In A.py I pass callback (py callable) to dll. Next, thread inside dll > simply calls my callback (in a loop). After few secs I got crash of > python.exe. > > How to debug it? > > I'm using winxp and py 2.5.2 > > > =========================== > def mycallback(data, size) > return 0 > > CBFUNC = CFUNCTYPE(c_int,POINTER(c_int), c_int) > dll = cdll.mydll > > if dll.RegisterCallback(CBFUNC(mycallback)) != 0: > print "Error." > =========================== Attach a debugger of choice to your python-process, and see what happens. Diez From nicolas.pourcelot at gmail.com Fri Jul 18 06:27:35 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Fri, 18 Jul 2008 03:27:35 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: In fact, 'any(myobject is element for element in mylist)' is 2 times slower than using a for loop, and 'id(myobject) in (id(element) for element in mylist)' is 2.4 times slower. From mcfletch at vrplumber.com Fri Jul 25 07:22:42 2008 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Fri, 25 Jul 2008 07:22:42 -0400 Subject: PyOpenGL Tutorial? In-Reply-To: <9a2cc7a70807232222t7d401279t5d91d5b8a9220ceb@mail.gmail.com> References: <1216843629.18962.16.camel@generator> <9a2cc7a70807232222t7d401279t5d91d5b8a9220ceb@mail.gmail.com> Message-ID: <4889B782.4090809@vrplumber.com> arsyed wrote: ... > Also, see: > > http://www.siafoo.net/browse?keyword_id=245 > But note regarding the second tutorial there that the PyOpenGL 3.x *does* supply wrappers for most publicly known extensions, so you shouldn't have to create your own wrappers for them any more. There's also tutorials that are not wxPython specific on the PyOpenGL documentation page. HTH, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From ashmir.d at gmail.com Fri Jul 4 01:50:29 2008 From: ashmir.d at gmail.com (ashmir.d at gmail.com) Date: Thu, 3 Jul 2008 22:50:29 -0700 (PDT) Subject: problem parsing utf-8 encoded xml - minidom Message-ID: Hi, I am trying to parse an xml file using the minidom parser. from xml.dom import minidom xmlfilename = "sample.xml" xmldoc = minidom.parse(xmlfilename) The parser is failing on this line: Heinrich K?ufner, Norbert Nedopil, Heinz Sch?och (Hrsg.). This is the error message I get: Traceback (most recent call last): File "readXML.py", line 11, in xmldoc = minidom.parse(xmlfilename) File "C:\Python25\lib\xml\dom\minidom.py", line 1913, in parse return expatbuilder.parse(file) File "C:\Python25\lib\xml\dom\expatbuilder.py", line 924, in parse result = builder.parseFile(fp) File "C:\Python25\lib\xml\dom\expatbuilder.py", line 207, in parseFile parser.Parse(buffer, 0) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 2254, column 21 It seems to me that it is having an issue with the '?' character. I have even tried the following to make sure it recognises the file as utf-8 file: from xml.dom import minidom import codecs xmlfilename = "sample.xml" xmlfile = codecs.open(xmlfilename,"r","utf-8") xmlstring = xmlfile.read() xmldoc = minidom.parse(xmlfilename) However, this doesn't work either and I get the following error message: Traceback (most recent call last): File "readXML.py", line 9, in xmlstring = xmlfile.read() File "C:\Python25\lib\codecs.py", line 618, in read return self.reader.read(size) File "C:\Python25\lib\codecs.py", line 424, in read newchars, decodedbytes = self.decode(data, self.errors) UnicodeDecodeError: 'utf8' codec can't decode bytes in position 69343-69345: invalid data I'm assuming here that it is failing at the same place... Can someone please point me in the right direction? Thanks, Ashmir From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 12:43:25 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 18:43:25 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <579f9d5b-8984-425d-8d4f-b2ed0be8eaba@o40g2000prn.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <579f9d5b-8984-425d-8d4f-b2ed0be8eaba@o40g2000prn.googlegroups.com> Message-ID: <4888cd25$0$15527$426a74cc@news.free.fr> Jordan a ?crit : >> I don't really mind, what you think about my response. Python will suffer >> from it as little as it will suffer from your complaints: These things >> will not change, whatever any of us says about them. So this discussion >> unlikely to produce any new insight, especially because this as been >> discussed over and over again in the past, without any effect on Python. > > You're right, of course. Because Python is in so many ways what I'm > looking for in a language, I transform it in my mind to my own, > personal ideal, close to the real existing language but with what I > consider to be the imperfections removed. I guess you'll find a lot of us guilty here too - but do we really agree on what we consider to be "imperfections" ?-) (snip) > I was trying not to change explicit self, or even != (which has a much > better case.) I was trying to ask the community to reconsider a > premise that the language is built around. Explicit is actually kinda > annoying a lot of the time, viz., java. This is about social and > philosophical adjustments, not technical ones. > "explicit-is-etc" - just like the remaining of Python's zen - is a general philosophy statement, not an absolute rule. Another quote states that practicality beats purity. So yes, Python has warts, and one can't get away dogmatically quoting Python's zen. Even if I'm sometimes myself guilty here, it's certainly worth taking time to better address criticism, either by aknowledging effective warts when someone points them out or by explaining (or pointing to explanations of) the unusual parts of Python's design. Now since most of the times, criticisms expressed here fall in the second category, we're happy to learn you'll now take appropriate action here and help us keep c.l.py a newbie-friendly place !-) From robert.kern at gmail.com Sat Jul 26 04:29:31 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 26 Jul 2008 01:29:31 -0700 (PDT) Subject: An Attempt to download and install traits - to a Windows XP References: Message-ID: On Jul 25, 5:37?pm, "Colin J. Williams" wrote: > Using >easy_install -v -fhttp://code.enthought.com/enstaller/eggs/sourceenthought.traits > > The result is: > > ... > ? ?many lines > ... > > copyingenthought\traits\ui\tests\shell_editor_test.py > -> > build\lib.win32-2.5\enthought\traits\ui\tests > copyingenthought\traits\ui\tests\table_editor_color_test.py > -> > build\lib.win32-2.5\enthought\traits\ui\tests > copyingenthought\traits\ui\tests\table_editor_focus_bug.py > -> > build\lib.win32-2.5\enthought\traits\ui\tests > copyingenthought\traits\ui\tests\table_editor_test.py > -> > build\lib.win32-2.5\enthought\traits\ui\tests > copyingenthought\traits\ui\tests\table_editor_test2.py > -> > build\lib.win32-2.5\enthought\traits\ui\tests > copyingenthought\traits\ui\tests\table_list_editor_test.py > -> > build\lib.win32-2.5\enthought\traits\ui\tests > copyingenthought\traits\ui\tests\tree_editor_test.py > -> > build\lib.win32-2.5\enthought\traits\ui\tests > running build_ext > error: Setup script exited with error: > Python was built with Visual Studio 2003; > extensions must be built with a compiler > than can generate compatible binaries. > Visual Studio 2003 was not found on this > system. If you have Cygwin installed, > you can try compiling with MingW32, by > passing "-c mingw32" to setup.py. Traits includes an extension module. You will need a suitable compiler. http://www.develer.com/oss/GccWinBinaries To tell distutils to use this compiler for all extension modules, create pydistutils.cfg file with the following contents: [build_ext] compiler=mingw32 See this page for details about this file: http://docs.python.org/inst/config-syntax.html You will get the most help about Traits and the rest of the Enthought Tool Suite on the enthought-dev mailing list. https://mail.enthought.com/mailman/listinfo/enthought-dev -- Robert Kern From larry.bates at websafe.com` Sun Jul 13 21:53:44 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 13 Jul 2008 20:53:44 -0500 Subject: Dictionary bidirectional In-Reply-To: <8923d0c5-29ce-495f-924a-6d9d2457138e@e39g2000hsf.googlegroups.com> References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> <792048c1-5e18-4a2c-925d-a1c932d18a91@j22g2000hsf.googlegroups.com> <8923d0c5-29ce-495f-924a-6d9d2457138e@e39g2000hsf.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > bukzor: >> You need to use two dictionaries. Here's a class that someone's >> written that wraps it up into a single dict-like object for you: >> http://www.faqts.com/knowledge_base/view.phtml/aid/4376 > > It contains code like: > > try: > del self.data[item] > except KeyError: > pass > > Exceptions are useful in python, but with dictionaries this is > probably faster (and shorter), even if it may perform two lookups: > > if item in self.data: > del self.data[item] > > Bye, > bearophile The only case where it would be faster would be if most of the keys were NOT in the dictionary (rather odd use case). Otherwise I believe you will find the first way quicker as the exceptions are infrequent. -Larry From manuel.dipl at gmail.com Mon Jul 14 09:44:00 2008 From: manuel.dipl at gmail.com (manu) Date: Mon, 14 Jul 2008 06:44:00 -0700 (PDT) Subject: trying to use sax for a very basic first xml parser Message-ID: <6ff86003-a3e8-4c5b-9276-1cd3c7f0ffa7@56g2000hsm.googlegroups.com> Hi, I need to parse xml files for the Blender Game Engine. ATM I am trying to get this script running in the BGE. This is my first script and I dont have much experience programming... import xml.sax class PnmlHandler(xml.sax.ContentHandler): def __init__(self): self.inPlace=0 def startElement(self, name, attrs): if name != "place": return if attrs.getLength()==0: return print 'Starting element:', name print "attrs:", attrs.keys() id = attrs.get("id", None) print "id:", id if name == "place": self.inPlace=1 def endElement(self, name): if name == "place": self.inPlace=0 parser = xml.sax.make_parser() parser.setContentHandler(PnmlHandler()) parser.parse(open("bpm.pnml","r")) this works in the IDLE ide. Output: Starting element: place attrs: [u'id'] id: p9723441 Starting element: place attrs: [u'id'] id: p26811937 Starting element: place attrs: [u'id'] id: p24278422[/code] but when I copy the script into blender and run it I get: [code]Compiled with Python version 2.5. Checking for installed Python... got it! Traceback (most recent call last): File "Text", line 27, in File "H:\Python25\lib\xml\sax\__init__.py", line 93, in make_parser raise SAXReaderNotAvailable("No parsers found", None) xml.sax._exceptions.SAXReaderNotAvailable: No parsers found[/code] Its probably a stupid question but thanks anyway! From sjmachin at lexicon.net Fri Jul 4 18:47:31 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 4 Jul 2008 15:47:31 -0700 (PDT) Subject: running python from cmd.exe References: Message-ID: On Jul 5, 7:38 am, Dominic Rice wrote: > Chris Hulan wrote: > > On Jul 4, 5:38 am, Dominic Rice wrote: > >> Dominic Rice wrote: > >>> Miki wrote: > >>>> Hello, > >>>>> I can't seem to get python to run my scripts using the command: python > >>>>> .py > >>>>> If I type python the interpreter runs as I sorted out the Path property, > >>>>> I'm afraid I don't know much about this kind of thing as I'm a science > >>>>> student who needs some Python not a programmer! > >>>> Can you be more specific about the error you get? > >>>> Say you have a script hw.py that contains one line: > >>>> print "Hello Python" > >>>> and you run > >>>> python hw.py > >>>> What is the error you get? > >>>> HTH, > >>>> -- > >>>> Miki > >>>>http://pythonwise.blogspot.com > >>> Sure, I get: > >>> can't open file .py: [errorno 2]No such file or directory. > >>> Now if I've noticed that if I change directory to (for instance) > >>> \Python25 where the script is the command runs fine.(?) > >> Oh I just noticed you specified hw.py, in that case just to clarify it > >> would be can't open file hw.py: [errorno 2]No such file or directory > > > When you run a script, are you in the directory where the script is > > located? > > when it works yes! Does it have to be the case then? I assumed that > there was a default folder (eg \Python25) that the python command would > look for the file in, I take it this is not the case then? The default folder *is* the "current" folder, i.e. "the directory that you are in". If you want to run a script in another folder, you specify the path to that script. This is usual in Windows command-line operation, not special to Python. By the way, storing your own files in the same folder structure as a software package (e.g. \Python25) is not a good idea. Keep them somewhere else e.g. a separate folder for each significantly different project, a folder for commonly useful stuff, and a junk folder for mucking about trying things out. Then when e.g. you upgrade to Python 2.6 the possibility of drama is reduced. HTH, John From robert.rawlins at thinkbluemedia.co.uk Fri Jul 18 07:03:24 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Fri, 18 Jul 2008 12:03:24 +0100 Subject: Unusual Exception Behaviour In-Reply-To: References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> <8904.90077804333$1216313689@news.gmane.org> <006001c8e831$5c1487b0$143d9710$@rawlins@thinkbluemedia.co.uk> <1214.94685668058$1216317006@news.gmane.org> Message-ID: <000d01c8e8c5$e6f8de50$b4ea9af0$@rawlins@thinkbluemedia.co.uk> Hi Mk, > To tell the truth I have never used logging module extensively, so I'm > not expert in this area and can't help you there. > > However, it seems to me that you may have stumbled upon some subtle bug > / side effect of logging module that could cause some side effects in > exceptions. Or perhaps it surfaces only in combination with glib? > > If you discover the root cause, please let us know on this ng, I'm also > using Python extensions and bindings to other libraries and this could > be of interest at least to me. Yeah it's got me a little bemused to be honest, I've tried playing around with configuration options this morning and not been able to achieve anything that works properly. I'll keep testing though and as soon as I have a root cause to the problem I'll be sure to let the list know. Thanks mate, Robert From xdicry at gmail.com Mon Jul 14 11:31:44 2008 From: xdicry at gmail.com (Evan) Date: Mon, 14 Jul 2008 08:31:44 -0700 (PDT) Subject: Is it possible to create "network conneciton" on windows system? Message-ID: Hello, one of my PC is window system, and in "control panel -> Network Connections", I can see some network connections such as PPPOE or VPN which I created by click "create a new connection". My question is, is it possible to create a new connection by using Python script? which means I do not want to use Window UI (via "control panel"), if it is possible, I can save so many time to create various network connection when I want to do testing in the lab. Thanks very much. Evan From bj_666 at gmx.net Sat Jul 19 12:31:31 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Jul 2008 16:31:31 GMT Subject: Change PC to Win or Windows References: Message-ID: <6eej73F6k7g3U3@mid.uni-berlin.de> On Sat, 19 Jul 2008 11:02:51 -0500, Grant Edwards wrote: > On 2008-07-19, Dennis Lee Bieber wrote: > >> Which term applied to the TRS-80, the Apple II, Altair even... > > Not that I remember. I had a homebrew S-100 bus system, worked > with varioius Commodore machines, a few Apples, and some other > CP/M systems. I never heard any of them called a 'PC'. My > recollection is that 'PC' was a term that IBM coined. The C64 that still sits on my desk has a label on it saying ?commodore 64 - personal computer?. Ciao, Marc 'BlackJack' Rintsch From kay.schluehr at gmx.net Fri Jul 25 01:06:35 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 24 Jul 2008 22:06:35 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> Message-ID: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> On 25 Jul., 03:01, Terry Reedy wrote: > Torsten Bronger wrote: > > Hall?chen! > > > And why does this make the implicit insertion of "self" difficult? > > > I could easily write a preprocessor which does it after all. > > class C(): > def f(): > a = 3 > > Inserting self into the arg list is trivial. Mindlessly deciding > correctly whether or not to insert 'self.' before 'a' is impossible when > 'a' could ambiguously be either an attribute of self or a local variable > of f. Or do you and/or Jordan plan to abolish local variables for methods? > > tjr This isn't the problem Jordan tries to address. It's really just about `self` in the argument signature of f, not about its omission in the body. Some problems occur when not `self` shall be used but e.g. `this`. Here one has to specify more: class C(): __self__ = 'this' # use `this` instead of `self` def f(a): this.a = a or class C(): def f($this, a): # use `this` instead of `self` this.a = a When an $-prefixed parameter is found the automatic insertion of `self` will be blocked and the $-prefixed parameter name will be used instead but without the prefix. From murugesan550 at gmail.com Thu Jul 24 23:40:59 2008 From: murugesan550 at gmail.com (muruges) Date: Thu, 24 Jul 2008 20:40:59 -0700 (PDT) Subject: .............................on line jobs........................................ Message-ID: <5a9a7101-d5f0-4dc1-a8d3-2c900965f8ad@a21g2000prf.googlegroups.com> we are selecting you for this online jobs. For more information see this website in this.............................. we are selecting you for this online jobs. For more information see this website in this.............................. Details .................. Name of the job.........................Online job.......................... Nature of work...........................Like data entry.......................... Qualification required........................good knowledge in computer Basics Earnings................More then Rs=1000 per day......................Earnings depends on your work............................. FOR MORE DETAILS: WWW.Bigconstructions5.blogspot.com From dp_pearce at hotmail.com Wed Jul 9 12:04:25 2008 From: dp_pearce at hotmail.com (dp_pearce) Date: Wed, 9 Jul 2008 09:04:25 -0700 (PDT) Subject: Anyone happen to have optimization hints for this loop? Message-ID: <43111321-2cc1-4a5e-9189-744131555841@26g2000hsk.googlegroups.com> I have some code that takes data from an Access database and processes it into text files for another application. At the moment, I am using a number of loops that are pretty slow. I am not a hugely experienced python user so I would like to know if I am doing anything particularly wrong or that can be hugely improved through the use of another method. Currently, all of the values that are to be written to file are pulled from the database and into a list called "domainVa". These values represent 3D data and need to be written to text files using line breaks to seperate 'layers'. I am currently looping through the list and appending a string, which I then write to file. This list can regularly contain upwards of half a million values... count = 0 dmntString = "" for z in range(0, Z): for y in range(0, Y): for x in range(0, X): fraction = domainVa[count] dmntString += " " dmntString += fraction count = count + 1 dmntString += "\n" dmntString += "\n" dmntString += "\n***\n dmntFile = open(dmntFilename, 'wt') dmntFile.write(dmntString) dmntFile.close() I have found that it is currently taking ~3 seconds to build the string but ~1 second to write the string to file, which seems wrong (I would normally guess the CPU/Memory would out perform disc writing speeds). Can anyone see a way of speeding this loop up? Perhaps by changing the data format? Is it wrong to append a string and write once, or should hold a file open and write at each instance? Thank you in advance for your time, Dan From ki4yjl at gmail.com Fri Jul 11 15:25:45 2008 From: ki4yjl at gmail.com (WDC) Date: Fri, 11 Jul 2008 12:25:45 -0700 (PDT) Subject: Simple question, how do you tell how many items in a list? References: <268ac2770807102256o4f41e784q79a0caf849c046b4@mail.gmail.com> Message-ID: On Jul 11, 2:53?pm, Terry Reedy wrote: > Alex Bryan wrote: > > I am just wondering how you get an integer value for how many items > > there are in a list, preferably w/o a for loop. > > Read the library reference sections on built-in functions and classes. Quite simple. If I understand you correctly, you have a list like this: >>> list = ['a', 'b', 'c', 'd'] As you can see, the list has 4 entries. The len() function also says that we have 4 entries. >>> len(list) 4 Now, if we wanted a particular entry, we would do this: >>> list[0] 'a' (Remember, when calling something in a list we count zero.) >>> list[3] 'd' Hope this helped. David From robert.rawlins at thinkbluemedia.co.uk Mon Jul 21 05:02:27 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Mon, 21 Jul 2008 10:02:27 +0100 Subject: Odd math related issue. In-Reply-To: References: <43332.3139710867$1216630189@news.gmane.org> Message-ID: <00de01c8eb10$7fb23a50$7f16aef0$@rawlins@thinkbluemedia.co.uk> > if you divide two integers, you'll get an integer back (in Python 2.X, > at least). quick fix: > > percentage = bytes_transferred * 100 / total_bytes > > Hey That worked a charm mate, thanks for the info. From larry.bates at websafe.com` Sun Jul 13 01:16:13 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 13 Jul 2008 00:16:13 -0500 Subject: Determining when a file has finished copying In-Reply-To: <7198df5e-e5e6-4b2d-9a7c-9ef2e30c87d1@x35g2000hsb.googlegroups.com> References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> <7198df5e-e5e6-4b2d-9a7c-9ef2e30c87d1@x35g2000hsb.googlegroups.com> Message-ID: Sean DiZazzo wrote: > On Jul 9, 5:34 pm, keith wrote: >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> >> >> Ethan Furman wrote: >>> writeson wrote: >>>> Guys, >>>> Thanks for your replies, they are helpful. I should have included in >>>> my initial question that I don't have as much control over the program >>>> that writes (pgm-W) as I'd like. Otherwise, the write to a different >>>> filename and then rename solution would work great. There's no way to >>>> tell from the os.stat() methods to tell when the file is finished >>>> being copied? I ran some test programs, one of which continously >>>> copies big files from one directory to another, and another that >>>> continously does a glob.glob("*.pdf") on those files and looks at the >>>> st_atime and st_mtime parts of the return value of os.stat(filename). >>>>> From that experiment it looks like st_atime and st_mtime equal each >>>> other until the file has finished being copied. Nothing in the >>>> documentation about st_atime or st_mtime leads me to think this is >>>> true, it's just my observations about the two test programs I've >>>> described. >>>> Any thoughts? Thanks! >>>> Doug >>> The solution my team has used is to monitor the file size. If the file >>> has stopped growing for x amount of time (we use 45 seconds) the file is >>> done copying. Not elegant, but it works. >>> -- >>> Ethan >> Also I think that matching the md5sums may work. Just set up so that it >> checks the copy's md5sum every couple of seconds (or whatever time >> interval you want) and matches against the original's. When they match >> copying's done. I haven't actually tried this but think it may work. >> Any more experienced programmers out there let me know if this is >> unworkable please. >> K >> -----BEGIN PGP SIGNATURE----- >> Version: GnuPG v1.4.6 (GNU/Linux) >> Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org >> >> iD8DBQFIdVkX8vmNfzrLpqoRAsJ2AKCp8wMz93Vz8y9K+MDSP33kH/WHngCgl/wM >> qTFBfyIEGhu/dNSQzeRrwYQ= >> =Xvjq >> -----END PGP SIGNATURE----- > > I use a combination of both the os.stat() on filesize, and md5. > Checking md5s works, but it can take a long time on big files. To fix > that, I wrote a simple sparse md5 sum generator. It takes a small > number bytes from various areas of the file, and creates an md5 by > combining all the sections. This is, in fact, the only solution I have > come up with for watching a folder for windows copys. > > The filesize solution doesn't work when a user copies into the watch > folder using drag and drop on Windows because it allocates all the > attributes of the file before any data is written. The filesize will > always show the full size of the file. > > ~Sean While a lot depends on HOW the copying program does its copy, I've recently been able to get pyinotify to watch folders. By watching for IN_CLOSE_WRITE events I can see when files are closed by the writer and then process them instantly after they have been written. Now if the writer does something like: open write close open append write close . . . This won't work as well. FYI, Larry From is_this at visible.com Tue Jul 29 21:23:00 2008 From: is_this at visible.com (Bruce Frederiksen) Date: Wed, 30 Jul 2008 01:23:00 +0000 Subject: static variables in Python? References: Message-ID: <417ec$488fc274$18607848$7519@KNOLOGY.NET> On Tue, 29 Jul 2008 21:31:01 +0000, kj wrote: > In Larry Bates writes: > > [snip] > > Maybe it's easier to see what I mean with JavaScript: > > function foo() { > if (foo.x === undefined) foo.x = expensive_call(); > return do_stuff_with(foo.x); > } def foo(): if not hasattr(foo, 'x'): foo.x = expensive_call() return do_stuff_with(foo.x) or, maybe just define foo in two steps: def foo(): return do_stuff_with(foo.x) foo.x = expensive_call() From rNOSPAMon at flownet.com Sun Jul 6 03:47:50 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 06 Jul 2008 00:47:50 -0700 Subject: Parsing MIME-encoded data in an HTTP request References: <3a11k5-al7.ln1@nb2.stroeder.com> <5fq3k5-eva.ln1@nb2.stroeder.com> Message-ID: In article <5fq3k5-eva.ln1 at nb2.stroeder.com>, Michael Str?der wrote: > Ron Garret wrote: > > In article , > > Ron Garret wrote: > > > >> In article <3a11k5-al7.ln1 at nb2.stroeder.com>, > >> Michael Str?der wrote: > >> > >>> Ron Garret wrote: > >>>> I'm writing a little HTTP server and need to parse request content that > >>>> is mime-encoded. All the MIME routines in the Python standard library > >>>> seem to have been subsumed into the email package, which makes this > >>>> operation a little awkward. > >>> How about using cgi.parse_multipart()? > >>> > >> Unfortunately cgi.parse_multipart doesn't handle nested multiparts, > >> which the requests I'm getting have. You have to use a FieldStorage > >> object to do that, and that only works if you're actually in a cgi > >> environment, which I am not. The server responds to these requests > >> directly. > >> > >> Anyway, thanks for the idea. > > > > Hm, it actually seems to work if I manually pass in the outerboundary > > parameter and environ={'REQUEST_METHOD':'POST'} That seems like the > > Right Answer. > > I'm also using it to parse form parameters in a message body received by > POST. > > CIao, Michael. Just for the record, here's the incantation I ended up with: class post_handler(BaseHTTPRequestHandler): def do_POST(self): form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST'}) ... works like a charm. rg From deliverable at gmail.com Sun Jul 27 17:23:04 2008 From: deliverable at gmail.com (braver) Date: Sun, 27 Jul 2008 14:23:04 -0700 (PDT) Subject: with statement for two files Message-ID: <08d72316-15f1-45dd-b1f7-7b8ee06efef5@e39g2000hsf.googlegroups.com> Can open two files in a with statement: with open(src) as readin, open(dst,"w") as writin: # WRONG: comma doesn't work ... -- so that you have transactional safety for two file descriptors? The comma syntax doesn't work, but is there a way, except for with open(src) as readin: with open(dst,"w) as writin: ... Cheers, Alexy From maric at aristote.info Wed Jul 30 11:20:05 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 30 Jul 2008 17:20:05 +0200 Subject: Pointers/References in Python? In-Reply-To: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> References: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Message-ID: <200807301720.06023.maric@aristote.info> Le Wednesday 30 July 2008 16:46:37 boblatest at googlemail.com, vous avez ?crit?: > Hello, > > I have a long list of memory-heavy objects that I would like to access > in differently sorted order. Let's say I'd like to have lists called > by_date or by_size that I can use to access the objects in the > specified order. > ... > I know there is a thing called "shallow copy" that has something to do > with not duplicating memory content but I don't understand the > concept. Maybe that's what would help here, too. > In fact, all containers in python contains references of objects. >>>[54]: a = [1] >>>[55]: b = [a] >>>[56]: c = list(sorted(b)) >>>[57]: b, c ...[57]: ([[1]], [[1]]) >>>[58]: b.append(3) >>>[59]: b, c ...[59]: ([[1], 3], [[1]]) >>>[60]: a.append(0) >>>[61]: b, c ...[61]: ([[1, 0], 3], [[1, 0]]) This is if you want to make a true copy (called deep copy) that you'll have to do extra steps (using copy module for example). -- _____________ Maric Michaud From sjmachin at lexicon.net Mon Jul 21 08:36:39 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 21 Jul 2008 05:36:39 -0700 (PDT) Subject: Odd math related issue. References: <43332.3139710867$1216630189@news.gmane.org> Message-ID: <32ee578a-3c8e-4312-ba51-682cacd1d536@i20g2000prf.googlegroups.com> On Jul 21, 10:21 pm, Alexandru Palade wrote: > > Another thing, you could have just added a dot after the constant in > order to promote the expression to be evaluated as float. As in > percentage = bytes_transferred / /self/.__sessions[path].total_bytes > * 100. > (notice the last dot) > True, you get a float result, but not a very useful one: >>> a = 2 >>> b = 11 >>> a / b * 100 # OP's problem 0 >>> a / b * 100. # Your suggestion; same as (a / b) *100. 0.0 >>> a * 100 / b # Fredrik's suggestion 18 >>> a * 100. / b # What you probably meant 18.181818181818183 >>> From kay.schluehr at gmx.net Fri Jul 18 00:39:58 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 17 Jul 2008 21:39:58 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> Message-ID: On 18 Jul., 01:15, castironpi wrote: > On Jul 17, 5:37 pm, I V wrote: > > > > > On Thu, 17 Jul 2008 15:08:17 -0700, castironpi wrote: > > > The Python disassembly is baffling though. > > > >>>> y= 3 > > >>>> dis.dis('x=y+1') > > > You can't disassemble strings of python source (well, you can, but, as > > you've seen, the results are not meaningful). You need to compile the > > source first: > > > >>> code = compile('y=x+1','-', 'single') > > >>> dis.dis(code) > > > 1 0 LOAD_NAME 0 (x) > > 3 LOAD_CONST 0 (1) > > 6 BINARY_ADD > > 7 STORE_NAME 1 (y) > > 10 LOAD_CONST 1 (None) > > 13 RETURN_VALUE > > > You may well find these byte codes more meaningful. Note that there is a > > list of opcodes athttp://docs.python.org/lib/bytecodes.html > > Oh. How is the stack represented? As a pointer to a pointer of PyObject structs. > Does it keep track of which stack > positions (TOS, TOS1, etc.) are in what registers? Does stack > manipulation consume processor cycles? Python does not store values in registers. It stores locals in arrays and accesses them by position ( you can see the positional index in the disassembly right after the opcode name ) and globals / object attributes in dicts. For more information you might just download the source distribution and look for src/Python/ceval.c. This file contains the main interpreter loop. From pop.alert at gmail.com Wed Jul 2 10:40:18 2008 From: pop.alert at gmail.com (nabblepop) Date: Wed, 2 Jul 2008 07:40:18 -0700 (PDT) Subject: Spell suggest for locations Message-ID: <18239043.post@talk.nabble.com> I'm working on spell suggestions for a list of places(~10^6) e.g pizza hut I was trying to change the behaviour of print (tee all output to a temp file) by inheriting from file and overwriting sys.stdout, but it looks like print uses C-level stuff to do its writes which bypasses the python object/inhertiance system. It looks like I need to use composition instead of inheritance, but thought this was strange enough to note. $python -V Python 2.5 """A short demo script""" class notafile(file): def __init__(self, *args, **kwargs): readonly = ['closed', '__class__', 'encoding', 'mode', 'name', 'newlines', 'softspace'] file.__init__(self, *args, **kwargs) for attr in dir(file): if attr in readonly: continue setattr(self, attr, None) def main(): n = notafile('/dev/stdout', "w") print vars(n) import sys sys.stdout = n print "Testing: 1, 2, 3..." output: {'__str__': None, 'xreadlines': None, 'readlines': None, 'flush': None, 'close': None, 'seek': None, '__init__': None, '__setattr__': None, '__reduce_ex__': None, '__new__': None, 'readinto': None, 'next': None, 'write': None, '__doc__': None, 'isatty': None, 'truncate': None, 'read': None, '__reduce__': None, '__getattribute__': None, '__iter__': None, 'readline': None, 'fileno': None, 'writelines': None, 'tell': None, '__delattr__': None, '__repr__': None, '__hash__': None} Testing: 1, 2, 3... From ojeeves at gmail.com Tue Jul 8 11:13:18 2008 From: ojeeves at gmail.com (oj) Date: Tue, 8 Jul 2008 08:13:18 -0700 (PDT) Subject: caseless dict - questions References: <77798300-820f-4175-a9cb-aef639d42a32@m45g2000hsb.googlegroups.com> Message-ID: <3d9a9693-b333-484e-abde-b1933f2e2b65@c65g2000hsa.googlegroups.com> On Jul 5, 1:57?am, Phoe6 wrote: > I have a requirement for using caseless dict. I searched the web for > many different implementations and found one snippet which was > implemented in minimal and useful way. > > ############# > import UserDict > > class CaseInsensitiveDict(dict, UserDict.DictMixin): > ? ? def __init__(self, *args, **kwargs): > ? ? ? ? self.orig = {} > ? ? ? ? super(CaseInsensitiveDict, self).__init__(*args, **kwargs) > ? ? def items(self): > ? ? ? ? keys = dict.keys(self) > ? ? ? ? values = dict.values(self) > ? ? ? ? return [(self.orig[k],v) for k in keys for v in values] > ? ? def __setitem__(self, k, v): > ? ? ? ? hash_val = hash(k.lower()) > ? ? ? ? self.orig[hash_val] = k > ? ? ? ? dict.__setitem__(self, hash_val, v) > ? ? def __getitem__(self, k): > ? ? ? ? return dict.__getitem__(self, hash(k.lower())) > > obj = CaseInsensitiveDict() > obj['Name'] = 'senthil' > print obj > print obj.items() > > obj1 = {} > obj1['Name'] = 'senthil' > print obj1 > print obj1.items() > ########### > [ors at goofy python]$ python cid1.py > {15034981: 'senthil'} > [('Name', 'senthil')] > {'Name': 'senthil'} > [('Name', 'senthil')] > > --- > The difference between the Caselessdict and {} is that when called as > the object, the Caselessdict() is giving me the internal > representation. > obj = CaseInsensitiveDict() > obj['Name'] = 'senthil' > print obj > gives: {15034981: 'senthil'} > > obj1 = {} > obj1['Name'] = 'senthil' > print obj1 > Correctly gives {'Name': 'senthil'} > > What changes should I make to CaseInsensitiveDict ( written above), so > that its instance gives the actual dictionary instead of its internal > representation. > Constructing a dictionary and returning from __init__ method did not > work. > > TIA, > Senthil What I think you need to do, is define a __repr__(self) method (see http://docs.python.org/ref/customization.html) Something like: def __repr__(self): return dict(self.items()) I /think/ will work. I haven't tested it though. This isn't exactly what repr is supposed to do - evaling it won't give you the correct object back. Defining __str__ might be a better approach. -Oli From Scott.Daniels at Acm.Org Mon Jul 28 08:45:38 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 28 Jul 2008 05:45:38 -0700 Subject: write unsigned integer 32 bits to socket In-Reply-To: References: Message-ID: <9_KdnfSDZ9xHIRDVnZ2dnUVZ_gCdnZ2d@pdx.net> Alan Franzoni wrote: > Michael Torrie was kind enough to say: > >> Of course any time you send coherent numbers over the network, I highly >> recommend you use what's called network byte order.... I'm sure python >> has some convention in the struct module for dealing with this. > > Not in the struct module; such functions are available in the socket > module, and should be employed indeed. Please don't pass this misinformation along. In the struct module document, see the section on the initial character: Character Byte order Size and alignment @ native native = native standard < little-endian standard > big-endian standard ! network (= big-endian) standard and notes @ is the default. >>> print struct.pack('>> print struct.pack('>lh', 3,4) >>> print struct.pack('lh', 3,4) >>> print struct.pack('!lh', 3,4) From larry.bates at websafe.com` Tue Jul 15 15:38:01 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 14:38:01 -0500 Subject: graphing lifelines In-Reply-To: References: Message-ID: E. J. Gold is the Hi-Tech Shaman wrote: > (crossposted to sci.math) > > I'm looking for a tool which will take a dataset of tuples indicating > the year of birth and death of a person: > > (1872, 1950, "Sri Aurobindo") > (1821, 1910, "Mary Baker Eddy") > (1831, 1891, "HP. Blavatksy") > > And graph them out, in bars, annotating them with the person's name. > > A simple spreadsheet would've worked, but they seem to start from > zero. Thus, I would only be able to indicate the span of life (by > subtracting death year from birth year). Certainly a "Hi-Tech Shaman" can whip something up to do this, right? -Larry P. S. you will need look for something like a high-low graph or do something custom. I've used ReportLab's Graphing module quite effectively. All depends on what format you want the output to be in. From fuzzyman at gmail.com Mon Jul 28 18:58:38 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 28 Jul 2008 15:58:38 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> Message-ID: <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> On Jul 27, 6:02?am, castironpi wrote: > On Jul 24, 11:04?pm, Tim Roberts wrote: > > > > > castironpi wrote: > > > >Compiling a program is different than running it. ?A JIT compiler is a > > >kind of compiler and it makes a compilation step. ?I am saying that > > >Python is not a compiler and in order to implement JIT, it would have > > >to change that fact. > > > And I'm saying you are wrong. ?There is NOTHING inherent in Python that > > dictates that it be either compiled or interpreted. ?That is simply an > > implementation decision. ?The CPython implementation happens to interpret. > > The IronPython implementation compiles the intermediate language to native > > machine language. > > > >> of Python that uses .NET. ?In that case, the code *IS* JIT compiled to > > >> assembly when the program starts. > > > >But still not the user's code, only the interpreter, which is running > > >in assembly already anyway in CPython. > > > In CPython, yes. ?In IronPython, no; the user's code is compiled into > > machine language. ?Both of them are "Python". > > -- > > Tim Roberts, t... at probo.com > > Providenza & Boekelheide, Inc. > > In CPython yes. ?In IronPython yes: ?the parts that are compiled into > machine code are the interpreter, *not user's code*. ?Without that > step, the interpreter would be running on an interpreter, but that > doesn't get the user's statement 'a= b+ 1' into registers-- it gets > 'push, push, add, pop' into registers. Well - in IronPython user code gets compiled to in memory assemblies which can be JIT'ed. Michael Foord -- http://www.ironpythoninaction.com/ From larry.bates at websafe.com` Tue Jul 15 19:46:01 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 18:46:01 -0500 Subject: Modify a string's value In-Reply-To: References: Message-ID: s0suk3 at gmail.com wrote: > Hi everyone, > > I've heard that a 'str' object is immutable. But is there *any* way to > modify a string's internal value? > > Thanks, > Sebastian Why would you care? Just create a new string (with the changed contents) and let garbage collection take care of the old one when all the references to it have gone away. Since these types of questions seem to appear almost every day on this list, this Python stuff is so much different than old languages people have hard time making the conceptual "jump". You can basically quite worrying about how/where things are stored, they just are. -Larry From catherine.heathcote at gmail.com Tue Jul 22 12:26:22 2008 From: catherine.heathcote at gmail.com (Catherine Heathcote) Date: Tue, 22 Jul 2008 17:26:22 +0100 Subject: Question about inheritence Message-ID: If I create a new class inherited from another with a constructor, what happens with the new class's constructer? Thanks for your time. From mal at egenix.com Wed Jul 2 04:39:13 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 02 Jul 2008 10:39:13 +0200 Subject: convert unicode characters to visibly similar ascii characters In-Reply-To: References: Message-ID: <486B3EB1.6050907@egenix.com> On 2008-07-01 20:31, Peter Bulychev wrote: > Hello. > > I want to convert unicode character into ascii one. > The method ".encode('ASCII') " can convert only those unicode characters, > which fit into 0..128 range. > > But there are still lots of characters beyond this range, which can be > manually converted to some visibly similar ascii characters. For instance, > there are several quotation marks in unicode, which can be converted into > ascii quotation mark. > > Can this conversion be performed in automatic manner? After googling I've > only found that there exists Unicode database, which stores human-readable > information on notation of all unicode characters ( > ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt). And there also exists > the Python adapter for this database ( > http://docs.python.org/lib/module-unicodedata.html). Using this database I > can do something like `if notation.find('QUOTATION')!=-1:\n\treturn "'"`. I > believe there is more elegant way. Am I right? You could write a codec which translates Unicode into a ASCII lookalike characters, but AFAIK there is no standard for doing this. I guess the best choice is to use the Unicode code point names as basis. These can be accessed via unicodedata.name(). You can then create a mapping which can be processed by the character map codec. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 02 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2008-07-07: EuroPython 2008, Vilnius, Lithuania 4 days to go :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From adam at krusty.madoff.com Thu Jul 3 11:06:12 2008 From: adam at krusty.madoff.com (Adam Lanier) Date: Thu, 03 Jul 2008 11:06:12 -0400 Subject: Interest not met. In-Reply-To: <849453.75351.qm@web23404.mail.ird.yahoo.com> References: <849453.75351.qm@web23404.mail.ird.yahoo.com> Message-ID: <486CEAE4.6010301@krusty.madoff.com> david odey wrote: > I write to inform you that the reason I subscribed to this web page > is not been met. > > I want to be sent sample codes in programming languages especially > python and an email tutorial on C#. I will be happy if these demands > are met. > > Thanks in anticipation. > > > > ALWAYS THERE FOR YOU Well, good luck getting your demands met. From castironpi at gmail.com Wed Jul 30 00:20:04 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 29 Jul 2008 21:20:04 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> Message-ID: On Jul 29, 7:39?am, alex23 wrote: > On Jul 29, 2:21?pm, castironpi wrote: > > > On Jul 28, 5:58?pm, Fuzzyman wrote: > > > Well - in IronPython user code gets compiled to in memory assemblies > > > which can be JIT'ed. > > > I don't believe so. > > Uh, you're questioning someone who is not only co-author of a book on > IronPython, but also a developer on one of the first IronPython-based > commercial applications. > > I know authorship isn't always a guarantee of correctness, but what > experience do you have with IronPython that makes you so unwilling to > accept the opinion of someone with substantial knowledge of the > subject? None, no experience, no authority, only the stated premises & classifications, which I am generally tending to misinterpret. I'm overstepping my bounds and trying to do it politely. (Some might call it learning, which yes, though uncustomary, *requires questioning authorities*, or reinventing.) Evidently, I have a "fundamental misunderstanding of the compilation process", which I'm trying to correct by stating what I believe. I'm trying to elaborate, and I'm meeting with increasingly much detail. So, perhaps I'll learn something out of this. Until then... What I know I have is two conflicting, contradictory, inconsistent beliefs. Maybe I've spent too much time in Python to imagine how a dynamic language can compile. This is from 7/22/08, same author: > I wouldn't say "can't". The current CPython VM does not compile > code. It COULD. The C#/.NET VM does. Three big claims here that I breezed right over and didn't believe. > It COULD. I'm evidently assuming that if it could, it would. > The current CPython VM does not compile code. Therefore it couldn't, or the assumption is wrong. Tim says it is. And the glaring one-- WHY NOT? Why doesn't CPython do it? From 7/18/08, own author: >> #define TOP() (stack_pointer[-1]) #define BASIC_POP() (*--stack_pointer) ...(line 1159)... w = POP(); v = TOP(); if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { /* INLINE: int + int */ register long a, b, i; a = PyInt_AS_LONG(v); b = PyInt_AS_LONG(w); i = a + b; << I am imagining that every Python implementation has something like it. If IronPython does not, in particular, not have the 'POP(); TOP();' sequence, then it isn't running on a stack machine. Is the IronPython code open source, and can someone link to it? I'm not wading through it from scratch. What does it have instead? Does dynamic typing still work? If you're bluffing, bluff harder; I call. If you're not, I apologize; teach me something. If you can ask better, teach me that too. From ggpolo at gmail.com Wed Jul 23 11:44:24 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 23 Jul 2008 12:44:24 -0300 Subject: Proper way to query user and group database on a Unix host? In-Reply-To: References: <87d4l5ozsc.fsf@cox.net> Message-ID: On Wed, Jul 23, 2008 at 9:16 AM, Sebastian lunar Wiesner wrote: > Chris Brannon : > > Iirc since Python 2.5 these tuples are named ... > >> Instead, do this: >> >> import grp >> groupname = 'users' >> groupusers = grp.getgrnam(groupname)[3] > ... thus this line could be written as: > > groupusers = grp.getgrnam(groupname).gr_mem > That is valid since Python 2.3 actually > Slightly more readable, imho > > > > -- > Freedom is always the freedom of dissenters. > (Rosa Luxemburg) > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From rkmr.em at gmail.com Sun Jul 27 22:15:10 2008 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Sun, 27 Jul 2008 19:15:10 -0700 Subject: write unsigned integer 32 bits to socket In-Reply-To: References: Message-ID: On Sun, Jul 27, 2008 at 7:01 PM, Larry Bates wrote: > rkmr.em at gmail.com wrote: >> i want to send unsigned 32 bit integer to socket, and looking for >> something equivalent to this method... >> http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt() >> >> is there such method / library available in python?! > You will need to use struct module to build the 4 byte value and then send > it. > > Something like (not tested): > > import struct > us32bit = struct.pack("I", value) > s.send(us32bit) thanks a lot!!! just to make sure if I want 32 bit or 4 bytes then should I use the short or integer or long? this is short >>> struct.pack('!h',3) '\x00\x03' this is integer >>> struct.pack('!i',3) '\x00\x00\x00\x03' this is long >>> struct.pack('!l',3) '\x00\x00\x00\x03' From sleytr at gmail.com Thu Jul 17 08:48:50 2008 From: sleytr at gmail.com (Evren Esat Ozkan) Date: Thu, 17 Jul 2008 05:48:50 -0700 (PDT) Subject: Javascript - Python RSA encryption interoperability References: <79934f50-2208-4e68-8d61-1fd33d34a468@a1g2000hsb.googlegroups.com> Message-ID: <3e907959-32ab-4b98-bf7c-b19cf2776880@27g2000hsf.googlegroups.com> Hi, Thank you very much. Your code is worked like a charm and saved my honeymoon :) Thanks again, Evren On Jul 4, 6:19?pm, marek.ro... at wp.pl wrote: > Evren Esat Ozkan napisa?(a): > > > > > > > Hello, > > > I'm trying to encrypt a string with RSA. But it needs to be compitable > > with Dave's JavaScript RSA implementation*. I'm already read and tried > > lots of different things about RSA and RSA in Python. But could not > > produce the same result with the javascript library. > > > My experiments could be seen at:http://dpaste.com/hold/60741/ > > > * JavaScript RSA Library:http://www.ohdave.com/rsa/ > > > Python libraries which I tried; > > * PyCrtypo:http://www.amk.ca/python/code/crypto.html > > * rsa library fromhttp://www.stuvel.eu/rsa > > > How could I create the same results with the JS library in Python. > > > Any help would be appreciated > > > Evren, > > It seems that this Javascript is doing weird things to its input, > namely processing it in reverse. Try encrypting ciphertext[::-1] > instead of just ciphertext. > > public_modulus_hex = '9F2E..snip..4BC7' > public_exponent_hex = '10001' > public_modulus = int(public_modulus_hex, 16) > public_exponent = int(public_exponent_hex, 16) > > def encrypt(plaintext_text): > ? ? ? ? # Beware, plaintext must be short enough to fit in a single block! > ? ? ? ? plaintext = int(plaintext_text.encode('hex'), 16) > ? ? ? ? ciphertext = pow(plaintext, public_exponent, public_modulus) > ? ? ? ? return '%X' % ciphertext # return hex representation > > print encrypt('12345') > print encrypt('12345'[::-1]) # Will return the value compatible with > JS output > > Regards, > Marek From circularfunc at yahoo.se Thu Jul 3 12:51:44 2008 From: circularfunc at yahoo.se (defn noob) Date: Thu, 3 Jul 2008 09:51:44 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: <6d4bfmFp3aoU1@mid.uni-berlin.de> Message-ID: <0f6f795d-8041-463e-8e98-9d830ca3fc5b@l42g2000hsc.googlegroups.com> well the reason i unzipped and placed it in site-packages was because nothign happened when i ran setup.py(unzipped). this has worked with other packages before. From elbertlev at hotmail.com Mon Jul 14 02:53:08 2008 From: elbertlev at hotmail.com (Lev Elbert) Date: Sun, 13 Jul 2008 23:53:08 -0700 (PDT) Subject: Newbie Threading Question References: Message-ID: <52334d8a-c9ca-4560-8ad6-729ca4175811@8g2000hse.googlegroups.com> On Jul 13, 8:33?am, Sparky wrote: > It seems strange, but I can't find a list of operating systems which > support / don't support threading in Python. Can anyone point me in > the right direction? > > Thanks, > Sam Here is the list (from Python documentation of thread module): ================================================== 7.4 thread -- Multiple threads of control This module provides low-level primitives for working with multiple threads (a.k.a. light-weight processes or tasks) -- multiple threads of control sharing their global data space. For synchronization, simple locks (a.k.a. mutexes or binary semaphores) are provided. The module is optional. It is supported on Windows, Linux, SGI IRIX, Solaris 2.x, as well as on systems that have a POSIX thread (a.k.a. ``pthread'') implementation. For systems lacking the thread module, the dummy_thread module is available. It duplicates this module's interface and can be used as a drop-in replacement. ================================================== From motoom at xs4all.nl Tue Jul 15 10:15:39 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Tue, 15 Jul 2008 16:15:39 +0200 Subject: Characters Being Misread Message-ID: <2.2.32.20080715141539.0125b010@pop.xs4all.nl> Victor wrote... >>>> import binascii >>>> binascii.unhexlify('\x0c') >TypeError: Odd-length string >What gives here? The function unhexlify() wants an even-length string. From the online help: >>> help(binascii.unhexlify) unhexlify(...) a2b_hex(hexstr) -> s; Binary data of hexadecimal representation. hexstr must contain an even number of hex digits (upper or lower case). This function is also available as "unhexlify()" And you use it like this: >>> binascii.unhexlify("41") 'A' You feed it data without any '0x' prefixes. What are you trying to do? Parsing an RTF file which contains unicode characerts, encoded as hexadecimal? Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From cokofreedom at gmail.com Tue Jul 1 10:15:43 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 1 Jul 2008 07:15:43 -0700 (PDT) Subject: Installing paramiko and pycrypto Message-ID: <4856638d-1c86-4d4d-ba50-4a808f722f10@79g2000hsk.googlegroups.com> I am really stuck presently, trying to install these on my Windows XP. I have downloaded easy_install and it is now in Python25\Scripts but none of the commands I have read in either program folder have worked to install them. I was hoping someone could give me a step by step guide to installing these so I can use paramiko to perform SSH. Or at least point me in the right direction... Thanks Coko From deets at nospam.web.de Thu Jul 17 03:59:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 17 Jul 2008 09:59:38 +0200 Subject: how to debug python's extend module written in c/c++ on windows In-Reply-To: References: <64d771b2-fbc8-4b6a-9725-3dc5063c5328@p25g2000hsf.googlegroups.com> <6e83v4F5pfg0U1@mid.uni-berlin.de> Message-ID: <6e8cfgF5n34gU1@mid.uni-berlin.de> tcfg at sina.com schrieb: > dear Diez: > > I need step into c function in extending module(DLL) when debugging > the script. and I want Single-step debugging the extend module itself, > but python script Launched The whole process. That is exactly what attaching a C-debugger to python will give you. Did you actually try it? Do you know how to debug C-programs? Diez From miki.tebeka at gmail.com Thu Jul 3 16:00:41 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 3 Jul 2008 13:00:41 -0700 (PDT) Subject: Using Gnuplot and making an exe file outv the prog References: Message-ID: <54f1a50a-364d-4b71-ab3e-05b3b8b01db3@w1g2000prd.googlegroups.com> Hello, > Hello. Been using the gnuplot lately. Program runs fine. And its plots > as well. Now i want to make an exe file out of this program using > py2exe. Cud some1 help me in telling me how this is done. Thnks You probably mean the Python gnuplot bindings (otherwise you're in the wrong mailing list). Can you be more descriptive about the problem you have with py2exe? HTH, -- Miki http://pythonwise.blogspot.com From qgallet at gmail.com Fri Jul 18 06:45:49 2008 From: qgallet at gmail.com (Quentin Gallet-Gilles) Date: Fri, 18 Jul 2008 12:45:49 +0200 Subject: Question on Joining of list In-Reply-To: References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> <6eb733F67cpfU2@mid.uni-berlin.de> <32a81d0c-a74f-4b22-8add-15beb2643529@h17g2000prg.googlegroups.com> <8b943f2b0807180311p5ec7abady6736c381b06f19c6@mail.gmail.com> Message-ID: <8b943f2b0807180345u30dd9908va4a910e6818298dd@mail.gmail.com> Actually, since you want to keep the missing words apart from the found ones, it's not necessary to do that. Using "first_char" and "missing_word" (quoting Peter's code) as lists instead of strings comes to mind, then you can join both lists into a string once the code exits the for loop. Cheers, Quentin On Fri, Jul 18, 2008 at 12:34 PM, Subhabrata Banerjee < subhabrata.iisc at hotmail.com> wrote: > Dear Quentin, > That's true but where to place, if I use it after elif it is not giving > result but if I give in after for there is no use of iteration. > I'm thinking to use a3.find(s) whichever not availiable to split and > iterate and join with s. > Best Regards, > Subhabrata. > > > ------------------------------ > > Date: Fri, 18 Jul 2008 12:11:00 +0200 > From: qgallet at gmail.com > To: subhabrata.iisc at hotmail.com > Subject: Re: Question on Joining of list > > > > In that case, the line 's=a5+" "+a6' should be inside the for loop (and > slightly modified to concatenate the results) > > Cheers, > Quentin > > On Fri, Jul 18, 2008 at 12:00 PM, SUBHABRATA > wrote: > > Sorry if I didn't say that. > The input is a string "Petrol Helium Heaven Sky" > Now, in a3 it is "God Goddess Heaven Sky" is there, > it is matching Heaven and Sky but not Petrol and Helium as they are > not in a3. > Now, as per the code it is giving me an output "S" of "Sky" and > "Helium" > But I was looking for an output of "H S Petrol Helium" and not "S > Helium" meaning all the values of a5 and a6 will be concatenated in s. > Best Regards, > Subhabrata.. > > Marc 'BlackJack' Rintsch wrote: > > On Fri, 18 Jul 2008 01:31:59 -0700, SUBHABRATA wrote: > > > > > def try2(n): > > > a1=raw_input("PRINT A STRING:") > > > a2=a1.split() > > > a3="God Godess Heaven Sky" > > > for x in a2: > > > a4=a3.find(x) > > > if a4>-1: > > > a5=a3[a4] > > > print a5 > > > elif a4<0: > > > a6=x > > > print "It is not found" > > > print a6 > > > else: > > > print "Error" > > > s=a5+" "+a6 > > > print s > > > > > > Here, if I put a string like: > > > Petrol Helium Heaven Sky > > > In s it is giving me S Helium > > > But I am looking for an output of a5 and a6 concatenating all its > > > values not the last ones. Can you suggest me any help? Am I missing > > > any minor point? > > > > Maybe you should describe what the input looks like and what output you > > want to have and how the input and output are connected. In words, not > in > > not very clear code with "numbered names". That's a silly idea and makes > > understanding the code very hard. Please use meaningful names! > > > > Ciao, > > Marc 'BlackJack' Rintsch > -- > http://mail.python.org/mailman/listinfo/python-list > > > > ------------------------------ > This is your window into tinsel town. Keep abreast with the latest movie > releases, star shockers and juicy gossip. Try it! > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Nikolaus at rath.org Mon Jul 28 03:43:30 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 28 Jul 2008 09:43:30 +0200 Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: <87k5f6sbbx.fsf@nokile.rath.org> Bruno Desthuilliers writes: > The fact that a function is defined within a class statement doesn't > imply any "magic", it just creates a function object, bind it to a > name, and make that object an attribute of the class. You have the > very same result by defining the function outside the class statement > and binding it within the class statement, by defining the function > outside the class and binding it to the class outside the class > statement, by binding the name to a lambda within the class statement > etc... But why can't the current procedure to resolve method calls be changed to automatically define a 'self' variable in the scope of the called function, instead of binding its first argument? Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From kanchana.senevirathna at gmail.com Wed Jul 23 03:55:58 2008 From: kanchana.senevirathna at gmail.com (Kanch) Date: Wed, 23 Jul 2008 00:55:58 -0700 (PDT) Subject: xpathEval fails for large files References: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> <48864b0d$0$9494$9b4e6d93@newsspool3.arcor-online.net> <4886ca3b$0$18828$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <3157e3bd-12f0-4559-90e5-0090e1a28bee@h1g2000prh.googlegroups.com> On Jul 23, 11:05 am, Stefan Behnel wrote: > Kanch wrote: > > Original file was 18MB, and contained 288328 element attributes for > > the particular path. > > You didn't say how many elements there are in total, but I wouldn't expect > that to be a problem, unless you have very little free memory (say, way below > 256MB). I just tried with lxml 2.1 and a 40MB XML file with 300 000 elements > and it lets the whole Python interpreter take up some 140MB of memory in > total. Looping over all elements by calling "list(root.iter())" takes a bit > more than one second on my laptop. That suggests that /any/ solution involving > lxml (or cElementTree) will do just fine for you. > > > I wonder whether for loop will cause a problem in iterating for 288328 > > times. > > You are heavily underestimating the power of the Python here. > > Stefan Hi, thanks for the help. lxml will suit my work. I have not being working with python for that long. :) Kanch From jgardner at jonathangardner.net Thu Jul 17 16:03:57 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 17 Jul 2008 13:03:57 -0700 (PDT) Subject: x, = y (???) References: Message-ID: <028d7d39-f0b4-49fd-8061-3836d3f0dac4@v21g2000pro.googlegroups.com> On Jul 17, 12:55?pm, kj wrote: > what's the point of performing such "unpacking"? record = [name, address, telephone] ... name, address, telephone = record From tjreedy at udel.edu Thu Jul 3 16:11:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 03 Jul 2008 16:11:21 -0400 Subject: A fix for OverflowError in 64bits platforms In-Reply-To: <486CE046.6080104@gmail.com> References: <486CE046.6080104@gmail.com> Message-ID: Manuel Vazquez Acosta wrote: > Hi all, > > I'm debugging a Plone site in an AMD64 laptop. When I first tried to run > Zope, I got this exception: In general, versions numbers for both Python and the app are helpful. > OverflowError: signed integer is greater than maximum > > In the archives I encounter no solutions. Archives: Python? Zope? Plone? > This is what I could find, so I share with you all: I hope you have/will report this to the appropriate place. > It seems that on 64bit platforms, sys.maxint is much greater than list's > insertion maximum index. I'm not sure if this a bug in python or a This strikes me as an app bug. In any case, released versions of Python will not change. > logical bound ---given the amount of RAM it would take to insert > 9,223,372,036,854,775,807 items ;)--- Maybe a bug in the documentation, > though > > However, Archetypes.Schema.moveField method documents the use of maxint > for inserting at the end of the Schema:: > maxint can be used to move the field to the last position possible This is a bit flakey. If they are going to use a surrogate for len(schemalist)-1, they might as well accept anything larger and shrink it to the proper value as slicing does. In 2.5.2 >>> a=[1,2,3] >>> a[1:1000000000000000000000] [2, 3] > >>> from sys import maxint > >>> spos = schema.copy() > >>> spos.moveField('a', pos=maxint) > >>> spos.keys() > ['b', 'c', 'a'] > > I have seen this usage in some products. This raises and OverflowError > on 64bit platforms. > > The fix is simple in the code of the caller:: > from sys import maxint > if maxint >> 33: # Am I running on 64bits? > maxint = maxint >> 33 > theschema.moveField(the_name, pos=maxint) > > Now, the maxint variable holds an acceptable value. > > I think the docstring should be appended with a "Note: On 64bits > platform this raises an OverflowError blah blah..." Better to fix it ;-) From timr at probo.com Wed Jul 23 00:38:18 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 23 Jul 2008 04:38:18 GMT Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> Message-ID: castironpi wrote: > >You're saying the VM can't compile code. That makes sense, it's not a >compiler. I wouldn't say "can't". The current CPython VM does not compile code. It COULD. The C#/.NET VM does. IronPython, for example, is an implementation of Python that uses .NET. In that case, the code *IS* JIT compiled to assembly when the program starts. >Do I understand correctly that JIT does compile to native >code in some cases? VMs that use JIT do, yes. >But that's not the only thing that stops python >from precompiling to assembly directly. GNU doesn't come with >Python. Do you mean Linux? >What sorts of minimal information would be necessary to take >from the GNU libs for the user's specific processor, (the one they're >downloading their version of Python for), to move Python to the >further step of outputting the machine code? I don't know why you think GNU has anything to do with this. There's nothing that prevents the Python run-time from JIT compiling the code. IronPython does this. CPython does not. It's an implementation decision. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From maric at aristote.info Tue Jul 29 04:59:01 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 29 Jul 2008 10:59:01 +0200 Subject: multiple inheritance and __getattr__ In-Reply-To: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> References: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> Message-ID: <200807291059.01408.maric@aristote.info> Le Monday 28 July 2008 16:48:09 Enrico, vous avez ?crit?: > Hi there, > I have the following situation (I tryed to minimize the code to concentrate > > on the issue): > >>> class A(object): > > def __getattr__(self, name): > print 'A.__getattr__' > if name == 'a': return 1 > raise AttributeError('%s not found in A' % name) > > >>> class B(object): > > def __getattr__(self, name): > print 'B.__getattr__' > if name == 'b': return 1 > raise AttributeError('%s not found in B' % name) > > Both classes have a __getattr__ method. > > Now I want to have a class that inherits from both so I write: > >>> class C(B,A): > > pass > > The problem arise when I try something like this: > >>> c=C() > >>> c.a > > A.__getattr__ > 1 > > >>> c.b > > A.__getattr__ > > Traceback (most recent call last): > File "", line 1, in > c.b > File "", line 5, in __getattr__ > raise AttributeError('%s not found in A' % name) > AttributeError: b not found in A > > I was expecting, after a fail in A.__getattr__, a call to the __getattr__ > method of B but it seems that after A.__getattr__ fails the exception stops > the flow. So, if I did understand well, B.__getattr__ will be never called > "automatically". I don't know if this has a reason, if it is a design > choice or what else, any explanation is welcome. > No getattr is a lookup fallback, classes which implement them in a non-collaborative way are unlikely to be used for multiple inheritance. Given how multiple inheritance work and __getattr__ semantic, I was surprised it is not that easy to figure out how it could work in a collaborative, and how far fromm this are common implementation of __getattr__. Normally they should be implemented like that : >>>[89]: class A(object) : def __getattr__(self, name) : if name == 'a' : return 'a' try : g = super(A, self).__getattr__ except : raise AttributeError('no more __getattr__') return g(name) ....: ....: >>>[95]: class B(object) : def __getattr__(self, name) : if name == 'b' : return 'b' try : g = super(B, self).__getattr__ except : raise AttributeError('no more __getattr__') return g(name) .....: .....: >>>[101]: class C(A, B) : def __getattr__(self, name) : if name == 'c' : return 'c' try : g = super(C, self).__getattr__ except : raise AttributeError('no more __getattr__') return g(name) .....: .....: >>>[107]: C().a ...[107]: 'a' >>>[108]: C().b ...[108]: 'b' >>>[109]: C().c ...[109]: 'c' >>>[110]: C().k --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /home/maric/ in () /home/maric/ in __getattr__(self, name) /home/maric/ in __getattr__(self, name) /home/maric/ in __getattr__(self, name) AttributeError: no more __getattr__ > Since A and B are not written by me I can only work on C. The solution that > comes to my mind is to define a __getattr__ also in C and write something > > like: > >>> class C(A,B): > > def __getattr__(self, name): > try: > return A.__getattr__(self, name) > except AttributeError: > return B.__getattr__(self, name) > > >>> c=C() > >>> c.a > > A.__getattr__ > 1 > > >>> c.b > > A.__getattr__ > B.__getattr__ > 1 > > A better solution is welcome. There is no way to repair those clases for mulitple inheritance except monkey patching them. The idea of this patch would be : def collaborative_getattr(class_, old_name) : old_one = getattr(class_, old_name) def __getattr__(self, name) : try : return old_one(self, name) except AttributeError : try : g = super(class_, self).__getattr__ except : raise AttributeError('no more __getattr__') return g(name) if not getattr(C, '_C_fixed__', False) : C._C_fixed__ = C.__getattr__ C.__getattr__ = collaborative_getattr(C, '_C_fixed__') That said, if your class C is a real facade for its ancestors A and B (A and B won't appear at all in the hierarchies of your subclasses), your solution is near the best one in terms of simplicity-efficiency. I said near the best one because your __getattr__ isn't collaborative yet ! :). -- _____________ Maric Michaud From geraint.williams at gmail.com Tue Jul 22 20:02:03 2008 From: geraint.williams at gmail.com (GHZ) Date: Tue, 22 Jul 2008 17:02:03 -0700 (PDT) Subject: How do I compare files? References: Message-ID: <1fd4550e-1271-4c44-b14d-fe7de1be73ea@k37g2000hsf.googlegroups.com> On Jul 23, 1:27?am, Clay Hobbs wrote: > I am making a program that (with urllib) that downloads two jpeg files > and, if they are different, displays the new one. ?I need to find a way > to compare two files in Python. ?How is this done? > > -- Ratfink import hashlib file = open(path) m = hashlib.md5() m.update(file.read()) digest = m.hexdigest() file.close() and compare the digest on both files From phillip.oldham at gmail.com Wed Jul 30 10:11:45 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Wed, 30 Jul 2008 07:11:45 -0700 (PDT) Subject: Standard module for parsing emails? References: <6fb93eFap7j5U1@mid.individual.net> Message-ID: On Jul 30, 2:36 pm, Thomas Guettler wrote: > What do you mean with "quote" here? > 2. Prefix of quoted text like your text above in my mail Basically, just be able to parse an email into its actual and "quoted" parts - lines which have been prefixed to indent from a previous email. Most clients use ">" which is easy to check for, but I've seen some which use "|" and some which *don't* quote at all. Its causing us nightmares in parsing responses to system-generated emails. I was hoping someone might've seen the problem previously and released some code. From jsanga at cox.net Wed Jul 9 17:34:59 2008 From: jsanga at cox.net (mzdude) Date: Wed, 9 Jul 2008 14:34:59 -0700 (PDT) Subject: Retrieving BSTR * from a DLL Message-ID: <500e422d-5868-4a2b-a213-7d4d13a51d23@j22g2000hsf.googlegroups.com> I need to interface with a windows DLL that has the following signature extern "C" void Foo( BSTR in, BSTR *out ) Code so far >>> from ctypes import * >>> import comtypes >>> LPBSTR = POINTER(comtypes.BSTR) >>> >>> hdl = windll.MyDll.Foo >>> hdl.rettype = None >>> hdl.argtypes = [comtypes.BSTR, LPBSTR] >>> >>> inStr = comtypes.BSTR(u'Some Silly String') >>> out = comtypes.BSTR >>> >>> hdl(inStr,byref(out)) Traceback (most recent call last): File "", line 1, in hdl(inStr,byref(out)) TypeError: byref() argument must be a ctypes instance, not '_ctypes.SimpleType' Also tried the following >>> out = comtypes.BSTR(u'') >>> p = pointer(out) >>> hdl(inStr,p) Traceback (most recent call last): File "", line 1, in hdl(inStr,p) ValueError: Procedure probably called with too many arguments (8 bytes in excess) Any feedback would be appreciated. From ggpolo at gmail.com Tue Jul 29 06:32:30 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 29 Jul 2008 07:32:30 -0300 Subject: Download excel file from web? In-Reply-To: References: <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> <19fa0bb2-e101-47c9-84d4-1bf05d08ba39@b2g2000prf.googlegroups.com> Message-ID: On Tue, Jul 29, 2008 at 1:47 AM, patf at well.com wrote: > On Jul 28, 6:05 pm, "Guilherme Polo" wrote: >> On Mon, Jul 28, 2008 at 9:39 PM, MRAB wrote: >> > On Jul 29, 12:41 am, "p... at well.com" wrote: >> >> On Jul 28, 4:20 pm, "Guilherme Polo" wrote: >> >> >> > On Mon, Jul 28, 2008 at 8:04 PM, p... at well.com wrote: >> >> > > On Jul 28, 3:52 pm, "Guilherme Polo" wrote: >> >> > >> On Mon, Jul 28, 2008 at 7:43 PM, p... at well.com wrote: >> >> > >> > On Jul 28, 3:33 pm, "p... at well.com" wrote: >> >> > >> >> On Jul 28, 3:29 pm, "Diez B. Roggisch" wrote: >> >> >> > >> >> > p... at well.com schrieb: >> >> >> > >> >> > > On Jul 28, 3:00 pm, "p... at well.com" wrote: >> >> > >> >> > >> Hi - experienced programmer but this is my first Python program. >> >> >> > >> >> > >> This URL will retrieve an excel spreadsheet containing (that day's) >> >> > >> >> > >> msci stock index returns. >> >> >> > >> >> > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... >> >> >> > >> >> > >> Want to write python to download and save the file. >> >> >> > >> >> > >> So far I've arrived at this: >> >> >> > >> >> > >> [quote] >> >> > >> >> > >> # import pdb >> >> > >> >> > >> import urllib2 >> >> > >> >> > >> from win32com.client import Dispatch >> >> >> > >> >> > >> xlApp = Dispatch("Excel.Application") >> >> >> > >> >> > >> # test 1 >> >> > >> >> > >> # xlApp.Workbooks.Add() >> >> > >> >> > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' >> >> > >> >> > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' >> >> > >> >> > >> # xlBook = xlApp.ActiveWorkbook >> >> > >> >> > >> # xlBook.SaveAs(Filename='C:\\test.xls') >> >> >> > >> >> > >> # pdb.set_trace() >> >> > >> >> > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ >> >> > >> >> > >> excel? >> >> > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> >> > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional') >> >> > >> >> > >> # test 2 - returns check = False >> >> > >> >> > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ >> >> > >> >> > >> indexperf/excel? >> >> > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> >> > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() >> >> >> > >> >> > >> xlApp = response.fp >> >> > >> >> > >> print(response.fp.name) >> >> > >> >> > >> print(xlApp.name) >> >> > >> >> > >> xlApp.write >> >> > >> >> > >> xlApp.Close >> >> > >> >> > >> [/quote] >> >> >> > >> >> > > Woops hit Send when I wanted Preview. Looks like the html [quote] tag >> >> > >> >> > > doesn't work from groups.google.com (nice). >> >> >> > >> >> > > Anway, in test 1 above, I determined how to instantiate an excel >> >> > >> >> > > object; put some stuff in it; then save to disk. >> >> >> > >> >> > > So, in theory, I'm retrieving my excel spreadsheet with >> >> >> > >> >> > > response = urllib2.urlopen() >> >> >> > >> >> > > Except what then do I do with this? >> >> >> > >> >> > > Well for one read some of the urllib2 documentation and found the >> >> > >> >> > > Request class with the method has_data() on it. It returns False. >> >> > >> >> > > Hmm that's not encouraging. >> >> >> > >> >> > > I supposed the trick to understand what urllib2.urlopen is returning >> >> > >> >> > > to me; rummage around in there; and hopefully find my excel file. >> >> >> > >> >> > > I use pdb to debug. This is interesting: >> >> >> > >> >> > > (Pdb) dir(response) >> >> > >> >> > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', >> >> > >> >> > > 'code', ' >> >> > >> >> > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', >> >> > >> >> > > 'readline', ' >> >> > >> >> > > readlines', 'url'] >> >> > >> >> > > (Pdb) >> >> >> > >> >> > > I suppose the members with __*_ are methods; and the names without the >> >> > >> >> > > underbars are attributes (variables) (?). >> >> >> > >> >> > No, these are the names of all attributes and methods. read is a method, >> >> > >> >> > for example. >> >> >> > >> >> right - I got it backwards. >> >> >> > >> >> > > Or maybe this isn't at all the right direction to take (maybe there >> >> > >> >> > > are much better modules to do this stuff). Would be happy to learn if >> >> > >> >> > > that's the case (and if that gets the job done for me). >> >> >> > >> >> > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty >> >> > >> >> > clear on this: >> >> >> > >> >> > """ >> >> > >> >> > This function returns a file-like object with two additional methods: >> >> > >> >> > """ >> >> >> > >> >> > And then for file-like objects: >> >> >> > >> >> >http://docs.python.org/lib/bltin-file-objects.html >> >> >> > >> >> > """ >> >> > >> >> > read( [size]) >> >> > >> >> > Read at most size bytes from the file (less if the read hits EOF >> >> > >> >> > before obtaining size bytes). If the size argument is negative or >> >> > >> >> > omitted, read all data until EOF is reached. The bytes are returned as a >> >> > >> >> > string object. An empty string is returned when EOF is encountered >> >> > >> >> > immediately. (For certain files, like ttys, it makes sense to continue >> >> > >> >> > reading after an EOF is hit.) Note that this method may call the >> >> > >> >> > underlying C function fread() more than once in an effort to acquire as >> >> > >> >> > close to size bytes as possible. Also note that when in non-blocking >> >> > >> >> > mode, less data than what was requested may be returned, even if no size >> >> > >> >> > parameter was given. >> >> > >> >> > """ >> >> >> > >> >> > Diez >> >> >> > >> >> Just stumbled upon .read: >> >> >> > >> >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ >> >> > >> >> excel? >> >> > >> >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> >> > >> >> +25%2C+2008&export=Excel_IEIPerfRegional').read >> >> >> > >> >> Now the question is: what to do with this? I'll look at the >> >> > >> >> documentation that you point to. >> >> >> > >> >> thanx - pat >> >> >> > >> > Or rather (next iteration): >> >> >> > >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ >> >> > >> > excel? >> >> > >> > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> >> > >> > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) >> >> >> > >> > The file is generally something like 26 KB so specifying 1,000,000 >> >> > >> > seems like a good idea (first approximation). >> >> >> > >> > And then when I do: >> >> >> > >> > print(response) >> >> >> > >> > I get a whole lot of garbage (and some non-garbage), so I know I'm >> >> > >> > onto something. >> >> >> > >> > When I read the .read documentation further, it says that read() has >> >> > >> > returned the data as a string object. Now - how do I convince Python >> >> > >> > that the string object is in fact an excel file - and save it to disk? >> >> >> > >> You don't need to convince Python, just write it to a file. >> >> > >> More reading for you:http://docs.python.org/tut/node9.html >> >> >> > >> > pat >> >> > >> > -- >> >> > >> >http://mail.python.org/mailman/listinfo/python-list >> >> >> > >> -- >> >> > >> -- Guilherme H. Polo Goncalves >> >> >> > > OK: >> >> >> > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ >> >> > > excel? >> >> > > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> >> > > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) >> >> > > # print(response) >> >> > > f = open("c:\\msci.xls",'w') >> >> > > f.write(response) >> >> >> > I would initially change that to: >> >> >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&...) >> >> >> > f = open("c:\\msci.xls", "wb") >> >> > for line in response: >> >> > f.write(line) >> >> > f.close() >> >> >> > and then.. >> >> >> > > OK this makes the file, and there's a c:\msci.xls in place and it's >> >> > > about the right size. But whether I make the second param to open 'w' >> >> > > or 'wb', when I try to open msci.xls from the Windows file explorer, >> >> > > excel tells me that the file is corrupted. >> >> >> > try it. >> >> >> > > pat >> >> > > -- >> >> > >http://mail.python.org/mailman/listinfo/python-list >> >> >> > -- >> >> > -- Guilherme H. Polo Goncalves >> >> >> A simple f.write(response) does work (click on a single row in Excel >> >> and you get a single row). >> >> >> But I can see that what you recommend Guilherme is probably safer - >> >> thanx. >> >> >> pat >> >> > If response contains a string then: >> >> Did you notice I removed the read(...) part ? >> >> > for line in response: >> > f.write(line) >> >> > will actually be writing the string one character at a time! >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> -- >> -- Guilherme H. Polo Goncalves > > Actually no I didn't Guilherme (although I'll take it out now). > > Would leaving the in urllib2.urlopen().read() imply, as MRAB would > seem to indicate, that the following for loop would act byte-by-byte? > And if so, how? .read() returns a string, so yes. The point in removing the .read(xxxxx) is that you no longer need to guess how long is the file to read it entirely. > > Even with the .read() in, it was very fast. But it looks like it > won't hurt (and very possibly helps) to take it out. > > pat > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From arsyed at gmail.com Mon Jul 21 14:16:26 2008 From: arsyed at gmail.com (arsyed) Date: Mon, 21 Jul 2008 14:16:26 -0400 Subject: calling source command within python In-Reply-To: References: Message-ID: <9a2cc7a70807211116o4b1cb766k3833d1bf4958bdfc@mail.gmail.com> On Mon, Jul 21, 2008 at 1:59 PM, mk wrote: > Jie wrote: > >> Hi all, >> >> i'm having trouble executing os.system('source .bashrc') command >> within python, it always says that source not found and stuff. Any >> clue? >> > > It _might_ be that the shell it fires up is /bin/sh and this in turn is not > bash. > > Anyway, it's better to use subprocess / Popen for this sort of operation. > > > "source" is a bash built-in command and not an executable file. That's why you need to do something like execute "/bin/bash .bashrc". -------------- next part -------------- An HTML attachment was scrubbed... URL: From jordanrastrick at gmail.com Thu Jul 24 06:12:41 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 03:12:41 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> Message-ID: <40449826-c71d-4c6e-8b74-13069269e5da@z6g2000pre.googlegroups.com> OK, it seems my original reply to Bruno got lost in the Aether (apologies therefore if a paraphrased "quantum duplicate" of this message is eventually forthcoming.) Torsten has adequately responded to his second point, so I need only replicated what I said for the first. > Please get your facts, the behaviour *is* actually fully documented: I have the facts. I know full well the behaviour is documented - it was pointed out at the time of the original discussion. Documenting a confusing, unintuitive design decision (whether its in a programming language, an end user GUI app or anything in between) doesn't justify it. To attack a strawman: "foolanguage uses the bar IO library; printing to stdout takes about 10 mins on the average machine. But thats ok, because look, its documented right here." > FWIW, the __lt__ / __le__ / __eq__ / __ne__ / __gt__ / __ge__ methods > set, known as "rich comparisons", was added in Python 2.1 to give more > fine-grained control on comparisons. If you don't need such a > granularity, just implement the __cmp__ method and you'll have all > comparison operators working as expected. First, the most serious justification for rich comparisons I remember seeing was that scipy "needed" them. I never saw a good reason scipy couldnt use methods like the rest of us mortals, nor why it was justifiable introducing a wart into the entire language for the sake of mildly conveniencing an (admittedly important and widely used) library. Second, fine, have silly C++-operator-overloading-style rich comparisons that confuse people reading your code if you must. Why does it have to be the default behaviour? Its people wanting __ne__ do do something other than not __eq__ who should have to be explicit about it. Third, __cmp__ is no good as a fix. Most classes that wan't equality comparison (== and !=) don't want ordered based comparison (>= etc.) thrown in as well. I shouldn't implement __cmp__ unless I want my class to implement every order comparison operator. Fourth, I'm trying to examine the wider implications of the Explicit > Implict mantra here, not resurrect an old campaign to change != behaviour that I think is probably a lost cause (if it happens as a side effect though, that'd be kinda cool.) From socyl at 987jk.com.invalid Tue Jul 29 13:24:15 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 17:24:15 +0000 (UTC) Subject: DB access without object-relation mapping? References: Message-ID: In Tim Henderson writes: >I believe there are a couple of options but pyscopg, and PyGreSQL seem >to be popular. Great. Thanks! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From Scott.Daniels at Acm.Org Tue Jul 29 09:03:10 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 29 Jul 2008 06:03:10 -0700 Subject: Swap memory in Python ? - three questions In-Reply-To: References: Message-ID: Robert LaMarca wrote: > Hi, > > I am using numpy and wish to create very large arrays. My system is AMD 64 x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a 15 GB swap drive. > > The command I have been trying to use is; > g=numpy.ones([1000,1000,1000],numpy.int32) > > This returns a memory error. > A smaller array ([500,500,500]) worked fine.. > Two smaller arrays again crashed the system. > > So... I did the math. a 1000x1000x1000 array at 32 bits should be around 4gb RAM... Obviously larger than RAM, but much smaller than the swap drive. > > 1. So... does Numpy have a really lot of overhead? Or is my system just not somehow getting to make use of the 15gb swap area. > 2. Is there a way I can access the swap area, or direct numpy to do so? Or do I have to write out my own numpy cache system... > 3. How difficult is it to use data compression internally on numpy arrays? > > thanks very much > Robert There are architectural issues that you should not expect (and really do not want) the libraries / languages / os to handle for you automatically. The reason you don't even _want_ an automatic solution is that the computer has no understanding of the problem you are trying to solve. If the machine guesses wrong, it will be doing computations at I/O speeds, and for 4G of data, that will result in geological computing times. On big problems the programming issue is how to break the problem into tractable sub-problems (of feasible computing size), and how to stitch those results together. This is a place to apply human intellect, not machine effort. So, sorry, there is no way to solve the problem without understanding the field it occurs in and the question being addressed by the code. --Scott David Daniels Scott.Daniels at Acm.Org From gandalf at shopzeus.com Tue Jul 1 14:47:17 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 01 Jul 2008 20:47:17 +0200 Subject: convert unicode characters to visibly similar ascii characters In-Reply-To: References: Message-ID: <486A7BB5.3000501@shopzeus.com> Peter Bulychev wrote: > Hello. > > I want to convert unicode character into ascii one. > The method ".encode('ASCII') " can convert only those unicode > characters, which fit into 0..128 range. > > But there are still lots of characters beyond this range, which can be > manually converted to some visibly similar ascii characters. For > instance, there are several quotation marks in unicode, which can be > converted into ascii quotation mark. Please be more specific. There is no general solution. Unicode can handle latin, cyrilic (russian), chinese, japanese and arabic characters in the same string. There are thousands of possible non-ascii characters and many of them are not similar to any ascii character. If you only want this to work for a subset, please define that subset. Laszlo From pavlovevidence at gmail.com Sat Jul 5 04:21:41 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 5 Jul 2008 01:21:41 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: On Jul 5, 4:12 am, "Sebastian \"lunar\" Wiesner" wrote: > Paddy : > > > > > On Jul 4, 1:36 pm, Peter Otten <__pete... at web.de> wrote: > >> Henning_Thornblad wrote: > >> > What can be the cause of the large difference between re.search and > >> > grep? > > >> grep uses a smarter algorithm ;) > > >> > This script takes about 5 min to run on my computer: > >> > #!/usr/bin/env python > >> > import re > > >> > row="" > >> > for a in range(156000): > >> > row+="a" > >> > print re.search('[^ "=]*/',row) > > >> > While doing a simple grep: > >> > grep '[^ "=]*/' input (input contains 156.000 a in > >> > one row) > >> > doesn't even take a second. > > >> > Is this a bug in python? > > >> You could call this a performance bug, but it's not common enough in real > >> code to get the necessary brain cycles from the core developers. > >> So you can either write a patch yourself or use a workaround. > > >> re.search('[^ "=]*/', row) if "/" in row else None > > >> might be good enough. > > >> Peter > > > It is not a smarter algorithm that is used in grep. Python RE's have > > more capabilities than grep RE's which need a slower, more complex > > algorithm. > > FWIW, grep itself can confirm this statement. The following command roughly > takes as long as Python's re.search: > > # grep -P '[^ "=]*/' input > > -P tells grep to use real perl-compatible regular expressions. This confirms that a particular engine might not be optimized for it, but it's not necessarily a reflection that the engine is more complex. I'm not sure of the specifics and maybe that is the case, but it could also be a case of a different codebase which is optimized differently. Carl Banks From bignose+hates-spam at benfinney.id.au Wed Jul 16 19:30:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 17 Jul 2008 09:30:38 +1000 Subject: python doc in command line References: <2dae4588-7321-493b-8c9f-c4df1e44a02a@27g2000hsf.googlegroups.com> Message-ID: <87iqv5z9sx.fsf@benfinney.id.au> Peng Yu writes: > Perl has a command line help perldoc. I'm wondering if python has a > similar help command. The interactive interpreter has a "help" command, and a corresponding "help" function which can be passed an object to display its docstrings recursively and nicely-formatted. The same facility is available with the external 'pydoc' command. -- \ ?The right to search for truth implies also a duty; one must | `\ not conceal any part of what one has recognized to be true.? | _o__) ?Albert Einstein | Ben Finney From mccredie at gmail.com Mon Jul 14 11:36:57 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 14 Jul 2008 08:36:57 -0700 (PDT) Subject: screencapture with PIL question References: <8e9ca866-4f14-4dd6-a784-a76630d8d812@x35g2000hsb.googlegroups.com> Message-ID: <3176a1a8-0c38-43f9-a3c1-748eb2dbdfef@8g2000hse.googlegroups.com> On Jul 14, 8:11?am, greg wrote: > Is there any way to capture the entire window? ?specifically > the scrolled portion of a window that is _not_visible_on_the_screen_. I don't think there is. That is why it is called a _screen_ capture. Matt From jaganadhg at gmail.com Wed Jul 23 10:51:17 2008 From: jaganadhg at gmail.com (=?UTF-8?B?4LSc4LSX4LSo4LWN4LSo4LS+4LSl4LWN?=) Date: Wed, 23 Jul 2008 07:51:17 -0700 (PDT) Subject: Doubt Message-ID: Friends I am a Perl programmer new to Python. I have a small doubt. How to convert the perl notation $a = ""; expression in Python ? How to represent the loop for ($a = $b; $a<=$c;$a++){ } in Python Jagan Linguist From ethan at stoneleaf.us Mon Jul 14 23:05:39 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 14 Jul 2008 19:05:39 -0800 Subject: Determining when a file has finished copying In-Reply-To: <2.2.32.20080714163026.01217970@pop.xs4all.nl> References: <2.2.32.20080714163026.01217970@pop.xs4all.nl> Message-ID: <487C1403.8040107@stoneleaf.us> Michiel Overtoom wrote: > Ethan wrote: > >> One more option may be to attempt to rename >> the file -- if it's still open for copying, that will fail; >> success indicates the copy is done. > > Caveat -- this is dependent on the operating system! > > Windows will indeed not allow you to rename or delete a file that's still > open for writing by another process, at least not when the file is on a > local NTFS filesystem, but don't count on this on Unix or networked > filesystems. There you can easily rename, move or delete a filename from a > directory whilst other processes still write to it. After all, a directory > is nothing else than a list of filenames which map to certain inodes. Very good point. Thanks. ~Ethan From the.blue.valkyrie at gmail.com Wed Jul 16 06:39:53 2008 From: the.blue.valkyrie at gmail.com (=?ISO-8859-1?Q?Cristina_Yenyxe_Gonz=E1lez_Garc=EDa?=) Date: Wed, 16 Jul 2008 12:39:53 +0200 Subject: How can i use a variable without define it ? In-Reply-To: <5dd91053-d239-4ff1-b693-d6afedf6bf24@x35g2000hsb.googlegroups.com> References: <87k5fm2p1x.fsf@benfinney.id.au> <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> <87fxqa2mu0.fsf@benfinney.id.au> <5dd91053-d239-4ff1-b693-d6afedf6bf24@x35g2000hsb.googlegroups.com> Message-ID: Hello. 2008/7/16 zhw : > On 7?16?, ??5?35?, Ben Finney > wrote: >> zhw writes: >> > Here is a example that I want to complete: >> > >>> import sys, new >> > >>> context={"name":"david", "sex":"male"} >> >> Here you have a set of values addressible by name. >> >> > >>> sys.modules["foo"] = new.module("foo") >> >> Why do you believe you need to create a module object? >> >> > >>> import foo >> > >>> for attr in context: >> > setattr(foo, attr, context[attr]) >> Forgetting these considerations (I agree with Ben, though), your error is trying to use an 'import *' inside a function. You should take it outside the function, and try to run it again. >> >> > >>> def bar(): >> > # here is a error >> > # import * only allowed at module level >> > from foo import * >> > print name, sex >> There are different import statements you can use in Python. I recommend you to take a look at the tutorial to learn about the differences between them: http://docs.python.org/tut/node8.html Good luck. From Caseyweb at gmail.com Mon Jul 14 12:18:35 2008 From: Caseyweb at gmail.com (Casey) Date: Mon, 14 Jul 2008 09:18:35 -0700 (PDT) Subject: screencapture with PIL question References: <8e9ca866-4f14-4dd6-a784-a76630d8d812@x35g2000hsb.googlegroups.com> Message-ID: On Jul 14, 11:11?am, greg wrote: > I am able to use the PIL module to capture a screen or specific > window. ?My problem is when capturing a window (on windows XP) I can > only capture the "visible" portion of the window. ?Is there any way to > capture the entire window? ?specifically the scrolled portion of a > window that is not visible on the screen. > > Thanks for any help. You might want to check out http://wiki.wxpython.org/index.cgi/WorkingWithImages#head-e962ac20ad55c25bc069523cd7e0246068110233 . wxPython supports different types of device contexts including wx.ClientDC (the client area of a window), wx.WindowDC (a specific window), and wx.ScreenDC (anywhere or everywhere on the underlying screen). From larry.bates at websafe.com` Mon Jul 21 12:49:02 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 11:49:02 -0500 Subject: Run as Service In-Reply-To: <09c0bfa9-c86b-4153-ba91-cb9bf2e85e2a@k30g2000hse.googlegroups.com> References: <09c0bfa9-c86b-4153-ba91-cb9bf2e85e2a@k30g2000hse.googlegroups.com> Message-ID: misceverything at gmail.com wrote: > I have, in the past, used SRVANY to run a Python app as a Windows > service. However, now I am interested in distributing my scripts and > want to make it as painless for the end user as possible (hands-off is > best :). How can you go about running a Python app as a Windows > service without SRVANY? Pick up a copy of Mark Hammond's book "Python on Win32". It has an excellent chapter on using Win32 extensions to write Windows Services. Also you might consider looking at gmane.comp.python.windows usergroup. -Larry From fredrik at pythonware.com Wed Jul 16 05:28:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 11:28:58 +0200 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: <8AEDA5E3386EA742B8C24C95FF0C758004623111@PDC-MAIL3.ubisoft.org> References: <8AEDA5E3386EA742B8C24C95FF0C758004623111@PDC-MAIL3.ubisoft.org> Message-ID: Andreas Tawn wrote: > I never knew that and I can't find reference to it in the docs. the for-in loop does ordinary assignments in the current scope: http://docs.python.org/ref/for.html "Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed." somewhat simplified, "for vars in expression: code" is equivalent to inlining: _ = iter(expression) while 1: try: vars = _.next() except StopIteration: break else: body where "_" is an internal variable. From dickinsm at gmail.com Fri Jul 18 18:32:53 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 18 Jul 2008 15:32:53 -0700 (PDT) Subject: round function error??? References: Message-ID: <56957ba6-380e-4398-a974-07d76659eae7@34g2000hsf.googlegroups.com> On Jul 18, 11:15?pm, Terry Reedy wrote: > No, round() return binary floats that, in general, cannot represent > decimal floats exactly. ?Formatted printing gives what you expect. > ?>>> '%8.2f' % x > ' 3499.35' Sure. But it's still true that the second printed value (printed as 3499.3499999999999) is strictly less than 3499.35, so when rounding to 1 decimal place an ideal rounding routine would round it *down* to 3499.3 instead of up to 3499.4. This is what '%.1f' does, for example, on a platform where printf does correct rounding: Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = 3499.35 >>> x 3499.3499999999999 >>> print '%.1f' % x 3499.3 >>> print round(x, 1) 3499.4 Mark From rbossy at jouy.inra.fr Sat Jul 12 05:07:23 2008 From: rbossy at jouy.inra.fr (rbossy at jouy.inra.fr) Date: Sat, 12 Jul 2008 11:07:23 +0200 Subject: decorator to prevent adding attributes to class? Message-ID: <1215853643.4878744b60059@www.jouy.inra.fr> >> class Foo(Freezeable): >> def __init__(self): >> self.bar = 42 >> self.freeze() # ok, we set all variables, no more from here >> >> >> x = Foo() >> print x.bar >> x.bar = -42 >> print x.bar >> x.baz = "OMG! A typo!" >> > >Pretty nice, but unfortunately the subclass has to remember to call freeze >in it's init. Too bad that can't be automated. Not to mention that subclasses constructors could be bit, like that: class Foo(Freezeable): ... class Bar(Foo): def __init__(self, *args, **kw): Foo.__init__(self, *args, **kw) self.something_bar = 42 # this should raise AttributeError Cheers RB From code at pizzashack.org Mon Jul 14 20:39:20 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 14 Jul 2008 20:39:20 -0400 Subject: Using Python To Launch Python In-Reply-To: <23116d500807141440u402eed7du5e41d72bb0716c58@mail.gmail.com> References: <20080714212454.GE16010@dragontoe.org> <23116d500807141440u402eed7du5e41d72bb0716c58@mail.gmail.com> Message-ID: <20080715003920.GF16010@dragontoe.org> On Mon, Jul 14, 2008 at 05:40:43PM -0400, Aquil H. Abdullah wrote: > You've hit the proverbial nail with the hammer. The problem is that my > application needs to run under both the Linux and Windows OSs, so while I > would love to use a nice sh, csh, or bash shell script. My hands are tied > because Windows does not provide such wonderful shells. *Provides*, no... neither does it provide Python, for what that's worth. But you can certainly get it (bash): http://win-bash.sourceforge.net/ I suppose it's not worth installing just for this purpose though... But you can provide with your application a DoS batch file that does exactly the same thing (in addition to a shell script). The user would quite intuitively use whichever were appropriate, or follow your provided directions otherwise. Or, the equivalent in (hopefully OS-agnostic) Python: import os, sys # I believe this gets the name of the root in all major OSes def root_dir(path): if os.path.dirname(path) == path: return path return (root_dir(os.path.dirname(path))) appname = root = root_dir(os.getcwd()) install_path = os.path.join(root, "usr") bin_path = os.path.join(install_path, "bin") os.environ["PATH"] = bin_path + os.pathsep + os.environ["PATH"] python_path = os.path.join(bin_path, "python") args = sys.argv[1:] args.insert(0, os.path.join(bin_path, appname)) args.insert(0, python_path) args.insert(0, python_path) os.execv(python_path, args) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From timothywayne.cook at gmail.com Tue Jul 29 14:22:46 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Tue, 29 Jul 2008 15:22:46 -0300 Subject: Correct Attribute Assignment Methodology? Message-ID: <1217355766.2930.10.camel@localhost.localdomain> Say I have these classes: class Parent(object): """Parent is abstract""" a=None def showA(): return self.a class Child(Parent): """inherits a and showA from Parent""" def __init__(self,a,b): self.a=a self.b=b def showAB(): return self.a,self.b class GrandChild(Child): """inherits all of the above""" def __init__(self,a,b,c): self.a=a self.b=b """should this be Child.__init__(a,b)? or Child.__init__(b)?"" """if so; why? if not why not?""" self.c=c Thanks for answering these very basic questions but I am not certain about the correct way. I know that in Python, assignment in the GrandChild class will work but is that correct? --Tim -- ************************************************************************** Join the OSHIP project. It is the standards based, open source healthcare application platform in Python. Home page: https://launchpad.net/oship/ Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page ************************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 05:26:40 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 11:26:40 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <48884afe$0$10430$426a74cc@news.free.fr> Jordan a ?crit : (snip rant about self and __eq__ / __ne__) 1/ about the __eq__ / __ne__ stuff: Please get your facts, the behaviour *is* actually fully documented: """ There are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false. Accordingly, when defining __eq__(), one should also define __ne__() so that the operators will behave as expected. """ http://docs.python.org/ref/customization.html FWIW, the __lt__ / __le__ / __eq__ / __ne__ / __gt__ / __ge__ methods set, known as "rich comparisons", was added in Python 2.1 to give more fine-grained control on comparisons. If you don't need such a granularity, just implement the __cmp__ method and you'll have all comparison operators working as expected. 2/ wrt/ self in functions signatures: How would you handle this case with an implicit 'self' : class Foo(object): pass def bar(self): print self Foo.bar = bar From bignose+hates-spam at benfinney.id.au Tue Jul 15 23:11:32 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jul 2008 13:11:32 +1000 Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> <7xiqv68rrp.fsf@ruckus.brouhaha.com> Message-ID: <87vdz64j6j.fsf@benfinney.id.au> Paul Rubin writes: > I don't like square-bracket listcomps because they leak the index > variables to the outside. According to PEP 289 , this is an acknowledged wart that will be fixed in Python 3.0. -- \ ?None can love freedom heartily, but good men; the rest love | `\ not freedom, but license.? ?John Milton | _o__) | Ben Finney From rjagodic at gmail.com Thu Jul 17 15:32:00 2008 From: rjagodic at gmail.com (Ratko) Date: Thu, 17 Jul 2008 12:32:00 -0700 (PDT) Subject: properly delete item during "for item in..." References: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> <487F770D.8070405@islandtraining.com> Message-ID: <7436c7ba-a548-453a-8166-304bd2b2f7ef@k36g2000pri.googlegroups.com> > > For dictionaries we can just iterate over values() or items() as > > opposed to itervalues() or iteritems() since that's technically a copy > > of values or items in the dict, right? > > No! In fact the whole point of iteritems and itervalues and iterkeys is > that they *DO NOT* make copies, so changing the dictionary out from > under them is a programming error. > > If you use dict.items(), dict.keys() or dict.values(), then you're OK, > because these methods *do* create new lists for both. That's what I meant, it just didn't come across correctly I guess. Thanks for clarifying these issues. I think I have a better understanding now. R From timr at probo.com Sun Jul 27 00:14:15 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 27 Jul 2008 04:14:15 GMT Subject: Questions on 64 bit versions of Python References: Message-ID: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> python at bdurham.com wrote: > >For Win64-Itanium users: python-2.5.2.ia64.msi >For Win64-AMD64 users: python-2.5.2.amd64.msi > >1. It looks like the 64 bit versions of Python for Windows are CPU >vendor specific, eg. it doesn't look like there's a single, universal >executable for Windows 64 bit platforms. Is this true? It's true for ALL operating systems, not just Windows. The ia64 (Itanium) and the amd64 are completely separate processors with VERY different instruction sets. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 3 03:13:45 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 03 Jul 2008 09:13:45 +0200 Subject: Generating list of possible configurations In-Reply-To: References: Message-ID: <486c7c1f$0$10446$426a74cc@news.free.fr> Terry Reedy a ?crit : > > > Mensanator wrote: (snip) >> Lookup "Cartesian Product". (snip) >> for a in [True,False]: >> for b in [True,False]: >> for c in [1,2,3,4]: >> print 'combined settings:',a,'\t',b,'\t',c > > This has been added to itertools at least for 2.6/3.0 Great ! From adityashukla1983 at gmail.com Thu Jul 24 19:38:33 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Thu, 24 Jul 2008 18:38:33 -0500 Subject: File operations. Message-ID: <73045cca0807241638v55c8a5fem63bd716cf93017eb@mail.gmail.com> Guys i just understood the problem.Thanks for all your help Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajdamico at gmail.com Fri Jul 18 17:17:34 2008 From: ajdamico at gmail.com (Anthony) Date: Fri, 18 Jul 2008 14:17:34 -0700 (PDT) Subject: round function error??? Message-ID: Isn't this a mistake??? >>> round(3499.349439034,44) 3499.3494390340002 >>> round(_,2) 3499.3499999999999 >>> round(_,1) 3499.4000000000001 My Python 2.5.1 spat that out.. From jonas.haulin at gmail.com Thu Jul 24 21:54:11 2008 From: jonas.haulin at gmail.com (jrh) Date: Thu, 24 Jul 2008 18:54:11 -0700 (PDT) Subject: import dll instead of pyd Message-ID: <68310600-2efd-4f52-81d7-d0f3b40c7809@h17g2000prg.googlegroups.com> Hello, >From previous posts and documentation it seems python should be able to import a module that is compiled into a .dll just as well as a .pyd. I have a pyd that works fine, but after renaming it to dll the import fails. Running python with -vv flag indicates it doesn't actually look for the dll (see below). Has dll import been defeatured in python? Thanks! >>> import _mydllpythonmodule # trying _mydllpythonmodule.pyd # trying _mydllpythonmodule.py # trying _mydllpythonmodule.pyw # trying _mydllpythonmodule.pyc # trying C:\Python25\DLLs\_mydllpythonmodule.pyd # trying C:\Python25\DLLs\_mydllpythonmodule.py # trying C:\Python25\DLLs\_mydllpythonmodule.pyw # trying C:\Python25\DLLs\_mydllpythonmodule.pyc # trying C:\Python25\lib\_mydllpythonmodule.pyd # trying C:\Python25\lib\_mydllpythonmodule.py # trying C:\Python25\lib\_mydllpythonmodule.pyw # trying C:\Python25\lib\_mydllpythonmodule.pyc # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyd # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.py # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyw # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyc # trying C:\Python25\_mydllpythonmodule.pyd # trying C:\Python25\_mydllpythonmodule.py # trying C:\Python25\_mydllpythonmodule.pyw # trying C:\Python25\_mydllpythonmodule.pyc # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyd # trying C:\Python25\lib\site-packages\_mydllpythonmodule.py # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyw # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyc # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyd # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.py # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyw # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyc # trying C:\Python25\lib\site-packages\win32\lib \_mydllpythonmodule.pyd # trying C:\Python25\lib\site-packages\win32\lib\_mydllpythonmodule.py # trying C:\Python25\lib\site-packages\win32\lib \_mydllpythonmodule.pyw # trying C:\Python25\lib\site-packages\win32\lib \_mydllpythonmodule.pyc # trying C:\Python25\lib\site-packages\Pythonwin \_mydllpythonmodule.pyd # trying C:\Python25\lib\site-packages\Pythonwin\_mydllpythonmodule.py # trying C:\Python25\lib\site-packages\Pythonwin \_mydllpythonmodule.pyw # trying C:\Python25\lib\site-packages\Pythonwin \_mydllpythonmodule.pyc Traceback (most recent call last): File "", line 1, in ImportError: No module named _mydllpythonmodule >>> From pavlovevidence at gmail.com Tue Jul 29 13:47:01 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 10:47:01 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> On Jul 29, 1:30 pm, Carl Banks wrote: > On Jul 29, 5:15 am, Heiko Wundram wrote: > > > I can't dig up a simple example from code I wrote quickly, but because of the > > fact that explicit comparisons always hamper polymorphism > > I'm not going to take your word for it. Do you have code that > demonstrates how "if x" improves polymorphism relative to simple > explicit tests? And, in case it wasn't obvious, the way to demonstrate that "if x" improves polymorphism relative to simple explicit tests would be posting an example where "if x" works but a simple explicit test doesn't. So don't accuse me of changing the question on you: it's the same question. You see, what you are stating and expecting me to take for granted is exactly what I'm asking for a concrete example of. Carl Banks From grante at visi.com Tue Jul 22 08:51:48 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 22 Jul 2008 07:51:48 -0500 Subject: Python Written in C? References: Message-ID: On 2008-07-22, Larry Bates wrote: > Grant Edwards wrote: >> On 2008-07-22, Larry Bates wrote: >> >>> You talk about "writing it in assembly language for each MPU >>> chip". Actually it is even better than that. We now have >>> these modern inventions, called compilers that do that type of >>> work for us. They translate high level instructions, not >>> into assembler but into machine language. >> >> Actually, all of the compilers I'm familiar with (gcc and a >> handful of cross compilers for various microprocessors) >> translate from high-level languages (e.g. C, C++) into >> assembly, which is then assembled into relocatable object >> files, which are then linked/loaded to produce machine >> language. >> > I just learned something I did not know. I was under the > impression that they translated directly to machine code > without ever actually generating Assembler text files. There may indeed be compilers that work that way. On Unix systems (which is what I work with) compilers have traditionally generated assembly language files. > Seems like a waste to generate the text and turn around run > that through the assembler, but what do I know. I guess that > way the compiler can have pluggable assembler back-ends. Since you probably need an assembler anyway, generating assembly-language in the compiler prevents you from having to duplicate a bunch of object-code-generation code in two places. -- Grant Edwards grante Yow! Okay ... I'm going at home to write the "I HATE visi.com RUBIK's CUBE HANDBOOK FOR DEAD CAT LOVERS" ... From max at alcyone.com Wed Jul 30 03:56:57 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Jul 2008 00:56:57 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <29a131a5-d813-407a-b774-6f90b7f8f3e3@w1g2000prk.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> <29a131a5-d813-407a-b774-6f90b7f8f3e3@w1g2000prk.googlegroups.com> Message-ID: Carl Banks wrote: > I mean in general. I wouldn't spell it like that. I would prefer if > empty(x), with an __empty__ method. (And support __nonzero__ aka > __bool__ dropped completely.) So your argument is purely about style, then. You just wish it were written differently. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The actor is not quite a human being -- but then, who is? -- George Sanders From ptmcg at austin.rr.com Sun Jul 27 22:51:46 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 27 Jul 2008 19:51:46 -0700 (PDT) Subject: Where is the correct round() method? References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> Message-ID: On Jul 27, 8:55?pm, Larry Bates wrote: > josh logan wrote: > > Hello, > > > I need a round function that _always_ rounds to the higher integer if > > the argument is equidistant between two integers. In Python 3.0, this > > is not the advertised behavior of the built-in function round() as > > seen below: > > >>>> round(0.5) > > 0 > >>>> round(1.5) > > 2 > >>>> round(2.5) > > 2 > > > I would think this is a common need, but I cannot find a function in > > the Python library to do it. I wrote my own, but did I miss such a > > method in my search of the Python library? > > > Thanks > > I think what you want is something like: > > math.ceil(x-0.4999999999999) > > -Larry- Hide quoted text - > > - Show quoted text - The version I learned back in my FORTRAN days was: int(x + 0.5) -- Paul From miki.tebeka at gmail.com Sun Jul 13 15:46:50 2008 From: miki.tebeka at gmail.com (Miki) Date: Sun, 13 Jul 2008 12:46:50 -0700 (PDT) Subject: Generating Lip-Synched animation? Message-ID: Hello, I'm trying to write something like http://blabberize.com/, generating a video file with lip-sync. Currently the general idea is: * Generate animation images using GIMP * Sample voice and detect when there is sound and when there is silence - Still working on details for this one, will probably using audioop and wave modules * Generate a list of images according to the voice (using the bitrate for sync) * Generate video from images using mencoder Before I venture into this, does anybody has a better idea? Thanks, -- Miki http://pythonwise.blogspot.com From __peter__ at web.de Fri Jul 18 06:17:09 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 12:17:09 +0200 Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> Message-ID: SUBHABRATA wrote: > Thanx Peter, > I would change my variables next time I would post. No, you should use meaningful variable names when you write your code no matter whether you plan to post it or not. > And obviously, > thanx for your solution. I am reviewing it, I was also trying out some > solutions. You misunderstood. I did not modify your code other than changing the variable names. My hope was that with this modification any errors sprang to you eye... Peter From fredrik at pythonware.com Wed Jul 16 19:22:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 01:22:53 +0200 Subject: python doc in command line In-Reply-To: <2dae4588-7321-493b-8c9f-c4df1e44a02a@27g2000hsf.googlegroups.com> References: <2dae4588-7321-493b-8c9f-c4df1e44a02a@27g2000hsf.googlegroups.com> Message-ID: Peng Yu wrote: > Perl has a command line help perldoc. I'm wondering if python has a > similar help command. it's built into the interpreter, and Python tells you how to use it when you start Python in interactive mode. $ python Python 2.5.1 Type "help", "copyright", "credits" or "license" for more information. >>> help Type help() for interactive help, or help(object) for help about object. >>> help() Welcome to Python 2.5! This is the online help utility. If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://www.python.org/doc/tut/. Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit". To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam". help> quit You are now leaving help and returning to the Python interpreter. If you want to ask for help on a particular object directly from the interpreter, you can type "help(object)". Executing "help('string')" has the same effect as typing a particular string at the help> prompt. >>> help("string") Help on module string: NAME string - A collection of string operations (most are no longer used). FILE string.py ... >>> help(len) Help on built-in function len in module __builtin__: len(...) len(object) -> integer Return the number of items of a sequence or mapping. >>> (etc) From jeffober at gmail.com Wed Jul 16 08:09:30 2008 From: jeffober at gmail.com (Jeff) Date: Wed, 16 Jul 2008 05:09:30 -0700 (PDT) Subject: bad recursion, still works References: mailman.112.1216164093.922.python-list@python.org Message-ID: <20cba7ab-72d2-4c7b-8f3f-48f39eaf9625@m3g2000hsc.googlegroups.com> On Jul 15, 7:21?pm, Michael Torrie wrote: > iu2 wrote: > > I still don't understand: In each recursive call to flatten, acc > > should be bound to a new [], shouldn't it? Why does the binding happen > > only on the first call to flatten? > > Nope. ?In each new call it's (re)bound to the same original list, which > you've added to as your function continues--it's mutable. ?Default > variables that are bound to mutable objects are one of the big caveats > that is mentioned in the FAQ. Is this avoidable by using a call to list() in the definition instead? From fredrik at pythonware.com Sun Jul 20 10:30:16 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jul 2008 16:30:16 +0200 Subject: regex doubts In-Reply-To: <504d473e-375a-4111-ae2e-c06aaa37b096@p25g2000pri.googlegroups.com> References: <532965.570.qm@web54502.mail.re2.yahoo.com> <504d473e-375a-4111-ae2e-c06aaa37b096@p25g2000pri.googlegroups.com> Message-ID: John Machin wrote: >> try "[LRM]+$" (an L or an R or an M, one or more times, all the way to >> the end of the string). > > Ummm ... with the default flag settings, shouldn't that be \Z instead > of $ ? Why? The OP was reading input from a user; whether he gets a trailing newline or not depends on the input method, and $ does the right thing for all normal input methods. From tpt at kamstrup.dk Tue Jul 29 07:07:16 2008 From: tpt at kamstrup.dk (mindmind) Date: Tue, 29 Jul 2008 04:07:16 -0700 (PDT) Subject: ironpython, exception in mscorlib when reading .py file from network share References: <6dfb578a-17ff-434d-a071-646ed3ef2b03@z72g2000hsb.googlegroups.com> <15144d50-319d-48ce-bd16-0ead4226dd08@f63g2000hsf.googlegroups.com> Message-ID: > > I don't know the answer - I do know that .NET permissions issues and > accessing network resources are a bit 'weird'. You're likely to get an > answer if you ask on the IronPython mailing list. > I had it running through the night, ~100 times, 25 of these gave the above exception. Hard to see any pattern. From fredrik at pythonware.com Tue Jul 15 17:13:30 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2008 23:13:30 +0200 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: <16651e80807151332o1a2b7446r651f515724a27e0@mail.gmail.com> References: <16651e80807151332o1a2b7446r651f515724a27e0@mail.gmail.com> Message-ID: Jerry Hill wrote: > This is just plain untrue. If 'name is None' evaluates to true, then > the variable 'name' is bound to the singleton value None. It has > nothing to do with allocated memory or null pointers. All it means is > that someplace along the line you did the equivalent of 'name = None' > in your code. On the other hand, there's nothing that keeps a Python implementation from using NULL to represent the None value. From deets at nospam.web.de Tue Jul 22 08:42:18 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 14:42:18 +0200 Subject: Automatically loading and initialising objects from a plugins directory References: Message-ID: <6em2v8F7o4qgU1@mid.uni-berlin.de> Dave Challis wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > I'm trying to write some code which: > 1. Finds all modules in a plugin directory > 2. Imports those modules > 3. Creates an instance of each object defined in the module (each module > will contain exactly 1 object, which is a subclass of 'Plugin') > > The closest I've come so far is with something like: > > In plugin.py: > # taken from http://docs.python.org/lib/built-in-funcs.html > def my_import(name): > mod = __import__(name) > components = name.split('.') > for comp in components[1:]: > mod = getattr(mod, comp) > return mod > > def import_plugins(): > mods = [] > for filename in os.listdir('/plugins'): > if filename.endswith('.py'): > name = os.path.splitext(filename)[0] > mods.append(my_import('plugins.' + name)) > return mods > > class Plugin(object): > pass > > > In plugins/exampleplugin.py: > class ExamplePlugin(Plugin): > def __init__(self): > pass > > > Calling import_plugins() then gives me a list containing references to > modules. > > How can I loop through that list and create an instance of whatever > object was defined within the module? (In this case I'd want to > construct an instance of ExamplePlugin) Like this: for name in dir(plugin): thing = getattr(plugin, name) try: if issubclass(thing, Plugin): thing() except ValueError: # issubclass sucks pass Diez From wuwei23 at gmail.com Tue Jul 22 01:06:49 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 21 Jul 2008 22:06:49 -0700 (PDT) Subject: Website Creation using Python References: Message-ID: <3bdf7eb8-22a7-49f9-85c1-fce2a20e9fed@t12g2000prg.googlegroups.com> On Jul 22, 12:44?am, Amie wrote: > I would like some help on how to create a website using the python > programming language. > I've tried using enamel, but had some problems because I could not > create html tables and intergrating it with python, like you use it > when coding in php. If you're familiar with the PHP approach and are planning on using Apache, you might find mod_python and Python Server Pages more accessible: * http://en.wikipedia.org/wiki/Mod_python * http://www.onlamp.com/pub/a/python/2004/02/26/python_server_pages.html There are a *lot* of web frameworks for Python (I hadn't even heard of Enamel prior to your post) which provide varying degrees of support and ease of use, there's a nice overview here: * http://wiki.python.org/moin/WebFrameworks Django does seem to be leading in terms of popularity atm. Having developed an application in TurboGears, I can testify that having a large user base to draw support help from can be -very- handy. Hope this helps. - alex23 From jwkenne at attglobal.net Sun Jul 20 18:29:25 2008 From: jwkenne at attglobal.net (John W Kennedy) Date: Sun, 20 Jul 2008 18:29:25 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <48617847$0$5021$607ed4bc@cv.net> <486ae06b$0$5011$607ed4bc@cv.net> Message-ID: <4883bc90$0$7327$607ed4bc@cv.net> Robert Maas, http://tinyurl.com/uh3t wrote: >>>> ... the "thunks" were necessary at the machine-language level to >>>> /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. >>> Ah, thanks for the clarification. Is that info in the appropriate >>> WikiPedia page? If not, maybe you would edit it in? >> From: John W Kennedy >> It is explained s.v. "thunk", which is referenced from "ALGOL >> 60". The ALGOL "pass-by-name" argument/parameter matching was >> perhaps the most extreme example ever of a language feature that >> was "elegant" but insane. What it meant, in effect, was that, >> unless otherwise marked, every argument was passed as two closures, >> one that returned a fresh evaluation of the expression given as the >> argument, which was called every time the parameter was read, and >> one that set the argument to a new value, which was called every >> time the parameter was set. > > Wow! All these years when I occasionally heard of a "thunk" I never > was told, until now, what it really meant. Thanks for the info!! > > Followup question #1: I assume these are lexical closures in the > environment of the point of the call, right? Yes. (Actually, subprogram calls are first described as working like macro expansions, but then the specification adds that there must be magic fixups so that variable names are resolved in point-of-call context anyway.) At this point in the history of computing, the conceptual distinction between subprograms and macros was not at all clear. It was quite possible to have "macros" that generated an out-of-line subprogram once and then generated calling code the first time and every time thereafter (it was a way of life on systems without linkage editors or linking loaders), and it was also quite possible to refer to in-line macro expansions as "subprograms". I suspect that the triumph of FORTRAN may have had something to do with cleaning up the terminological mess by the mid-60s. Into the 60s, indeed, there were still machines being made that had no instruction comparable to the mainframe BASx/BALx family, or to Intel's CALL. You had to do a subprogram call by first overwriting the last instruction of what you were calling with a branch instruction that would return back to you. > Followup question #2: For simple arithmetic expressions, I can > possibly understand how the UPDATE closure might be implemeted > (expressed in Lisp to make the intent clear): > Call form: MyFunction(X+2); > GET closure: (+ closedX 2) > UPDATE closure: (lambda (newval) (setf closedX (- newval 2)) > Thus from inside MyFunction where formal parameter Arg1 is bound > to actual parameter X+2, after doing Arg1 := 7; X will have the > value 5 so that calling Arg1 will return 7 as expected, right? > But if the actual argument is something complicated, especially if > it makes a nested function call, how can that possibly be > implemented? It was forbidden. In the formal definition of ALGOL 60, there was no such thing as an external subprogram (except for non-ALGOL code, which was treated as magic), so the whole program was supposed to be one compile. Therefore, a theoretical compiler could verify that any parameter used as an LHS was always matched with an argument that was a variable. (However, a "thunk" was still required to evaluate any array index and, possibly, to convert between REAL and INTEGER variables.) Many actual compilers /did/ support separate complication as a language extension -- I suppose they had to use run-time checking. -- John W. Kennedy "Compact is becoming contract, Man only earns and pays." -- Charles Williams. "Bors to Elayne: On the King's Coins" From giltay at gmail.com Tue Jul 29 14:36:20 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Tue, 29 Jul 2008 11:36:20 -0700 (PDT) Subject: iterating "by twos" References: Message-ID: <70a172ac-0491-4918-9c74-6a577f35068a@d45g2000hsc.googlegroups.com> On Jul 29, 1:36?pm, kj wrote: > Is there a special pythonic idiom for iterating over a list (or > tuple) two elements at a time? I use this one a lot: for x, y in zip(a, a[1:]): frob(x, y) Geoff G-T From norseman at hughes.net Mon Jul 21 16:36:15 2008 From: norseman at hughes.net (norseman) Date: Mon, 21 Jul 2008 13:36:15 -0700 Subject: sending input to an embedded application In-Reply-To: <4884A558.2000209@nienna.org> References: <4884A558.2000209@nienna.org> Message-ID: <4884F33F.7000200@hughes.net> Matthew Fitzgibbons wrote: > > mefyl wrote: >> Uwe Schmitt wrote: >>> On 12 Jul., 09:08, George Oliver wrote: >>>> What I would like to do is take a program and embed it or put it >>>> within a Python-run GUI, using the GUI just to capture and send input >>>> to the application, and display the ouput. >>> Which interface does your interpreter provide ? Just commandline or >>> can you access by other methods ? >>> >>> http://sourceforge.net/projects/pexpect/ might help you >>> >> >> Although Pexpect looks more advanced and complete, you might want to >> take a >> look at popen* modules. It enables you to easily run a subprocess, >> feed him >> data on stdin, retrieve output from stdout/stderr, and wait for its >> completion. >> >> http://docs.python.org/lib/module-popen2.html >> > > I believe the subprocess module is the recommended module to use now. > > -Matt > -- > http://mail.python.org/mailman/listinfo/python-list > ===================================== HUMMMMMM! # print "popen3 run" ########## from existing python docs: from popen2 import * r,w,e= popen3('dmesg | grep hda') print r.read() print "subprocess run" ########## from existing python docs: # "... Replacing older functions with the subprocess module..." from subprocess import * p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0] #documentation quits print p2.communicate() # """ Why do children insists on making things more complicated than necessary? If the stated bragging rights of Python is that one writes less code to accomplish more, then I have to say "bullshit", just count the printable characters. to write less would be to change something like this: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close() ### I have to guess what type error to code for and I'll need another module to decode what actually went wrong. to this: if (fd = os.open(filename, 'O_RDRW|O_BINARY, 0666) == -1) ...handle it if fd.err.type == THIS #catagory if fd.err == this #specific do this etc. ## just to see what went wrong? print fd.err.type, fd.err else: #just to match above continue processing ### error reporting actually usefull who says fd cannot be simple interger or pointer to error block depending on whether it's valid or not? The bonus is, if there is no trap it will stop anyway first time fd is used as a file number. The crash usually actually points to the correct place. :) All that aside: subprocess seems to have a problem: """ # When I run the above I get: ============== PY:> py test.py popen3 run ide0: BM-DMA at 0x1400-0x1407, BIOS settings: hda:DMA, hdb:pio hda: ST9160821A, ATA DISK drive hda: attached ide-disk driver. hda: host protected area => 1 hda: cannot use LBA48 - capacity reset from 312581808 to 268435456 hda: 268435456 sectors (137439 MB) w/8192KiB Cache, CHS=19457/255/63, UDMA(100) hda: hda1 hda2 hda3 < hda5 hda6 hda7 hda8 > subprocess run ('', None) PY:> ============= Note subprocess yields unexpected answer. Probably needs better documentation and less typing. :) The "PY:> " is result of script to change to dir python and set the PATH py is copy of python renamed to afford less typing. (Unix vs Microsoft) Note: without lots of extra effort, the piping only works for commands like grep that are built to accept redirected I/O. I have yet to get it to work with the GUI type. Those need special things implanted at compile time because they don't use or even want the command line interface. Typically they are "Point'n'Click" or take a hike. GUIs are visually more appealing but don't play well in the production world. Steve norseman at hughes.net From keith.hughitt at gmail.com Mon Jul 14 11:06:30 2008 From: keith.hughitt at gmail.com (Keith Hughitt) Date: Mon, 14 Jul 2008 08:06:30 -0700 (PDT) Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> Message-ID: <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> On Jul 12, 12:52?am, "Gabriel Genellina" wrote: > En Fri, 11 Jul 2008 15:42:37 -0300, Keith Hughitt ? > escribi?: > > > I am having a little trouble figuring out how to convert a python > > datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would > > like to create a UTC date so that when I send it to MySQL (which > > treats all dates at local dates by default), it will already have > > incorporated the proper UTC offset. I've tried looking through the > > docshttp://python.active-venture.com/lib/datetime-datetime.html), but > > have not had any luck. > > You have to use a "timezone aware" datetime object. If all you want is to ? > store an UTC date, the tzinfo demo classes that you can find in the Python ? > docs at may be enough. > A more complete implementation is at > > If you pass a "timezone aware" datetime object as a SQL parameter, the ? > database should store it correctly (but I don't have a MySQL instance at ? > hand to test it) > > -- > Gabriel Genellina Thanks for advice Gabriel. I downloaded the tzinfo demo class, saved it as UTC.py and imported it. I'm still not exactly sure how to use it though. It looks like the file already creates an instance of the UTC tzinfo class (line 20: "utc = UTC()"), however, when I try to test it out in the interpreter, it cannot be found. I'm new to python, and there is probably something obvious I'm missing, but do you have any ideas? Here is what I'm attempting: ============ output begin ============= Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import datetime, UTC >>> t = datetime.datetime(2008, 7, 14, 00, 00, 00, UTC()) Traceback (most recent call last): File "", line 1, in TypeError: 'module' object is not callable >>> utc Traceback (most recent call last): File "", line 1, in NameError: name 'utc' is not defined >>> utc = UTC() Traceback (most recent call last): File "", line 1, in TypeError: 'module' object is not callable >>> ============ output begin ============= Any ideas? Thanks, Keith From jdscript at gmail.com Fri Jul 11 23:13:04 2008 From: jdscript at gmail.com (happy) Date: Fri, 11 Jul 2008 20:13:04 -0700 (PDT) Subject: variable question Message-ID: <6f02608a-2b2e-478d-a153-d10bbfb58981@c58g2000hsc.googlegroups.com> Can a variable be considered the simplest of the data structures. I am tutoring some kids about basics of programming using python. Not an expert in computer sciences, but am a python enthusiast. I wanted to know if it is correct to say a variable is a data structure, it has a name and a value. Put a stack of variables in a special data structure called a dictionary where the each name associates to a value. If in a data structure, one uses numbers starting from 0 to describe the name, it becomes a list and so forth.... From timothy.grant at gmail.com Mon Jul 14 22:14:39 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Mon, 14 Jul 2008 19:14:39 -0700 Subject: One step up from str.split() In-Reply-To: References: Message-ID: On Mon, Jul 14, 2008 at 6:33 PM, Joel Koltner wrote: > I normally use str.split() for simple splitting of command line arguments, > but > I would like to support, e.g., long file names which-- under windows -- are > typically provided as simple quoted string. E.g., > > myapp --dosomething --loadthis "my file name.fil" > > ...and I'd like to get back a list wherein ListEntry[3]="my file name.fil" > , > but just running str.split() on the above string creates: > > >>> ListEntry='myapp --dosomething --loadthis "my file name.fil"' > >>> ListEntry.split() > ['myapp', '--dosomething', '--loadthis', '"my', 'file', 'name.fil"'] > > Is there an easy way to provide just this one small additional feature > (keeping quoted names as a single entry) rather than going to a full-blown > command-line argument parsing tool? Even regular expressions seem like > they'd > probably be overkill here? Or no? > > Thanks, > ---Joel I've found that anytime I have more than one option on the command line, optparse is the way to go. It works very very well for every circumstance I've been able to throw at it. -- Stand Fast, tjg. [Timothy Grant] -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun Jul 27 19:00:51 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Jul 2008 23:00:51 GMT Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <009cf9ab$0$20302$c3e8da3@news.astraweb.com> On Sun, 27 Jul 2008 16:04:43 -0400, Colin J. Williams wrote: >> For those who don't like the way the empty first argument looks, maybe >> something like this could be allowed: >> >> def fun( ., cat): >> > I don't see the need for the comma in fun. Or the parentheses and colon. Can we remove them too? -- Steven From javaboy.ms at gmail.com Mon Jul 21 09:38:40 2008 From: javaboy.ms at gmail.com (sahasranaman) Date: Mon, 21 Jul 2008 06:38:40 -0700 (PDT) Subject: Odd math related issue. References: <43332.3139710867$1216630189@news.gmane.org> <48847F5D.9080509@sellerengine.com> Message-ID: <2dede424-2ed9-4634-8e18-1ff44cc8320d@y22g2000prd.googlegroups.com> On Jul 21, 5:30?pm, Fredrik Lundh wrote: > Alexandru Palade wrote: > > However, you should be carefully because using an %i modifier for a > > what-should-be a float value truncates the value in a way you may not > > expect. > > > What I mean is that if you have sent 2 out of 3 bytes, the math will be > > 200/3 which with the %i modifier will print 66, rather than 66.6 (or at > > least 67 which is closer - have a look at the round() function). > > My suggested workaround doesn't use floats. ?As for rounding, that's > more of a usability issue -- seeing the download process getting stuck > at 100% can be rather frustrating for the poor user. ?Better truncate > towards zero. > > > Another thing, you could have just added a dot after the constant in > > order to promote the expression to be evaluated as float. As in > > ? ?percentage = bytes_transferred / /self/.__sessions[path].total_bytes > > * 100. > > (notice the last dot) > > Did you try that? > > ?>>> 2 / 3 * 100. > 0.0 > > You can fix this with parentheses, but I usually recommend an explicit > "cast" instead, to make it obvious what you're doing: > > ? ? ?result = float(a) / b > > try 2.0 / 3 * 100 that would solve all trouble From Bill at SynectixLtd.com Sat Jul 12 08:36:16 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Sat, 12 Jul 2008 13:36:16 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: "Tim Golden" wrote in message news:mailman.332.1215788687.20628.python-list at python.org... > Bill Davy wrote: >> Traceback (most recent call last): >> File "H:/Personal/OutlookIF1/t2.py", line 18, in >> outlook = win32com.client.gencache.EnsureDispatch >> ("Outlook.Application") >> File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line >> 536, in EnsureDispatch >> mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], >> bForDemand=bForDemand) >> File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line >> 393, in EnsureModule >> module = GetModuleForTypelib(typelibCLSID, lcid, major, minor) >> File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line >> 262, in GetModuleForTypelib >> AddModuleToCache(typelibCLSID, lcid, major, minor) >> File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line >> 554, in AddModuleToCache >> dict = mod.CLSIDToClassMap >> AttributeError: 'module' object has no attribute 'CLSIDToClassMap' > > > Just in case, could you delete the contents of your gen_py > directory (probably in %TEMP%\gen_py) > > TJG OK, Put the following ahead with the following results. TempDir = os.getenv("TEMP"); WorkDir = TempDir + '\\gen_py' print WorkDir try: os.rmdir(WorkDir); except WindowsError, detail: print "Ignoring Windows error: ", detail ... Result: C:\DOCUME~1\Bill\LOCALS~1\Temp\gen_py Ignoring Windows error: [Error 2] The system cannot find the file specified: 'C:\\DOCUME~1\\Bill\\LOCALS~1\\Temp\\gen_py' Traceback (most recent call last): File "H:\Personal\OutlookIF1\t2.py", line 26, in outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 536, in EnsureDispatch mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], bForDemand=bForDemand) File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 393, in EnsureModule module = GetModuleForTypelib(typelibCLSID, lcid, major, minor) File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 262, in GetModuleForTypelib AddModuleToCache(typelibCLSID, lcid, major, minor) File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 554, in AddModuleToCache dict = mod.CLSIDToClassMap AttributeError: 'module' object has no attribute 'CLSIDToClassMap' >>> So, although that directory did exist, it does not now (even after the program has run). Any other ideas? But many thnaks, Bill From grflanagan at gmail.com Fri Jul 11 09:58:41 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Fri, 11 Jul 2008 15:58:41 +0200 Subject: read file into list of lists In-Reply-To: References: Message-ID: antar2 wrote: > Hello, > > I can not find out how to read a file into a list of lists. I know how > to split a text into a list > > sentences = line.split(\n) > > following text for example should be considered as a list of lists (3 > columns and 3 rows), so that when I make the print statement list[0] > [0], that the word pear appears > > > pear noun singular > books nouns plural > table noun singular > > Can someone help me? > class Table(object): def __init__(self, text=None): self.rows = [] if text: self.write(text) def write(self, text): self.rows.extend(line.split() for line in text.splitlines()) def read(self): return '\n'.join(' '.join(row) for row in self.rows) def __getitem__(self, i): return self.rows[i] def __iter__(self): return iter(self.rows) table = Table() table.write('apple orange coconut') print table[0][1] print table.read() table.write('clematis rose lily') print table[1][2] print table.read() for row in table: print row (If you have quoted items, it is more difficult) G. From mail at timgolden.me.uk Wed Jul 16 13:45:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 18:45:03 +0100 Subject: About wmi In-Reply-To: <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> <487E1AD4.9020509@timgolden.me.uk> <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> Message-ID: <487E339F.3040801@timgolden.me.uk> patrol wrote: >>>> import wmi >>>> wmi.WMI('non-existent computer') > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\wmi.py", line 1199, in connect > handle_com_error (error_info) > File "C:\Python25\lib\wmi.py", line 184, in handle_com_error > exception_string = [u"%s - %s" % (hex (hresult_code), > hresult_name)] > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > 4: ordinal > not in range(128) > -------------------------------------------------------------------------------------- > yup,error_info contains the Chinese encoded string. All of the Simple > Chinese Windows use the CP936.Every Chinese word utilizes two > bytes.Maybe you can fix this bug by modifying handle_com_error. Well, that's what I've done in that latest version. Only I naively assumed that I could use sys.stdout.encoding to determine the encoding. I'll have to try harder. TJG From yuwenwu010 at gmail.com Fri Jul 18 10:32:28 2008 From: yuwenwu010 at gmail.com (yuwenwu010 at gmail.com) Date: Fri, 18 Jul 2008 07:32:28 -0700 (PDT) Subject: cheap air max 87 shoes PayPal Message-ID: cheap air max 87 shoes PayPal Dear friend welcome to shopping on www.electronic-paypal.cn 1.5% paypal handling charge supports the online payment! 2.Use your intergla replacement more good gift! 3.notes by email and website of deliver each package at first time. Have a good day! Sincerely yours, CHINASILKROAD EXPORTS CO., LTD From __peter__ at web.de Tue Jul 1 07:20:28 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Jul 2008 13:20:28 +0200 Subject: Disabling the magic "last expression" _ variable References: <486a108d$0$14358$e4fe514c@news.xs4all.nl> Message-ID: Koen Vossen wrote: > A project I'm currently working on uses Turbogears as a framework. I'd > like to interact with it using the tg-admin shell. We also use gettext's > _() function for internationalization. Now, this function is overwritten > in interactive mode, which causes annoying exceptions. Is it possible to > disable this behavior? >>> import sys >>> def displayhook(result): ... if result is not None: ... __builtins__._last = result ... print result ... >>> "yadda" yadda >>> _ Traceback (most recent call last): File "", line 1, in NameError: name '_' is not defined >>> _last yadda Peter From B.L.Michielsen at wanadoo.fr Fri Jul 11 19:25:00 2008 From: B.L.Michielsen at wanadoo.fr (Bas Michielsen) Date: Sat, 12 Jul 2008 01:25:00 +0200 Subject: Using SWIG to build C++ extension References: Message-ID: <4877ec43$0$877$ba4acef3@news.orange.fr> mk wrote: > Hello, > > I'm having terrible problems building C++ extension to Python 2.4 using > SWIG. I'd appreciate if somebody knowledgeable at the subject took a > look at it. swig-1.3.29, g++ (GCC) 4.1.1 20070105 (Red Hat 4.1.1-52). > > I used following commands to build C++ extension: > > # swig -c++ -python edit_distance.i > # c++ -c edit_distance.c edit_distance_wrap.cxx edit_distance.cpp -I. > -I/usr/include/python2.4 > > > Linux RH (9.156.44.105) root ~/tmp # c++ -c edit_distance.c > edit_distance_wrap.cxx edit_distance.cpp -I. -I/usr/include/python2.4 > c++: edit_distance.cpp: No such file or directory > edit_distance_wrap.cxx: In function ?PyObject* > _wrap_edit_distance(PyObject*, PyObject*)?: > edit_distance_wrap.cxx:2579: error: ?string? was not declared in this > scope edit_distance_wrap.cxx:2579: error: ?arg1? was not declared in this > scope edit_distance_wrap.cxx:2580: error: ?arg2? was not declared in this > scope edit_distance_wrap.cxx:2597: error: expected type-specifier before > ?string? edit_distance_wrap.cxx:2597: error: expected `>' before ?string? > edit_distance_wrap.cxx:2597: error: expected `(' before ?string? > edit_distance_wrap.cxx:2597: error: expected primary-expression before > ?>? token > edit_distance_wrap.cxx:2597: error: expected `)' before ?;? token > edit_distance_wrap.cxx:2605: error: expected type-specifier before > ?string? edit_distance_wrap.cxx:2605: error: expected `>' before ?string? > edit_distance_wrap.cxx:2605: error: expected `(' before ?string? > edit_distance_wrap.cxx:2605: error: expected primary-expression before > ?>? token > edit_distance_wrap.cxx:2605: error: expected `)' before ?;? token > > What's weird is that I _did_ use std:: namespace prefix carefully in the > code: > > #include > #include > #include > > const unsigned int cost_del = 1; > const unsigned int cost_ins = 1; > const unsigned int cost_sub = 1; > > > unsigned int edit_distance( std::string& s1, std::string& s2 ) > { > const size_t len1 = s1.length(), len2 = s2.length(); > std::vector > d(len1 + 1, > std::vector(len2 + 1)); > > for(int i = 1; i <= len1; ++i) > for(int j = 1; j <= len2; ++j) > d[i][j] = std::min(d[i - 1][j] + 1, > std::min(d[i][j - 1] + 1, d[i - 1][j - 1] + (s1[i - 1] == s2[j - 1] ? 0 > : 1))); > > return d[len1][len2]; > } > > Ok, anyway I fixed it in the generated code (edit_distance_wrap.cxx). It > compiled to .o file fine then. It linked to _edit_distance.so as well: > > # c++ -shared edit_distance_wrap.o -o _edit_distance.so > > But now I get import error in Python! > > Linux RH root ~/tmp # python > Python 2.4.3 (#1, Dec 11 2006, 11:38:52) > [GCC 4.1.1 20061130 (Red Hat 4.1.1-43)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import edit_distance > Traceback (most recent call last): > File "", line 1, in ? > File "edit_distance.py", line 5, in ? > import _edit_distance > ImportError: ./_edit_distance.so: undefined symbol: _Z13edit_distanceRSsS_ > > > > What did I do to deserve this? :-) > > > edit_distance.i file just in case: > > %module edit_distance > %{ > #include "edit_distance.h" > %} > > extern unsigned int edit_distance(string& s1, string& s2); Hello, I took your example files and did the following: changed the #include "edit_distance.h" to #include "edit_distance.c" in the edit_distance.i file. Then I changed the first few lines of your function definition unsigned int edit_distance( const char* c1, const char* c2 ) { std::string s1( c1), s2( c2); and also adapted the signature in the edit_distance.i file. Then swig -shadow -c++ -python edit_distance.i g++ -c -fpic -I/usr/include/python edit_distance_wrap.cxx g++ -shared edit_distance_wrap.o -o _edit_distance.so I could import edit_distance without any error messages >>> import edit_distance >>> print edit_distance.edit_distance( "toto", "titi") 2 >>> print edit_distance.edit_distance( "toto", "toti") 1 Perhaps I changed too many things, but this may get you started, Regards, Bas From mail at timgolden.me.uk Mon Jul 7 10:17:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 07 Jul 2008 15:17:03 +0100 Subject: python mysteriously halts In-Reply-To: <13a33043-21d1-40c0-a938-6e905d958064@m3g2000hsc.googlegroups.com> References: <13a33043-21d1-40c0-a938-6e905d958064@m3g2000hsc.googlegroups.com> Message-ID: <4872255F.6000204@timgolden.me.uk> Todd wrote: > I ran a python script last night which connects to a matlab automation > server via DCOM (using win32com). I expected to see the results when > I came in this morning. But apparently, not long after I left, python > stopped. I hit enter in the console, and it started again. Symptomatically, at least, this can be caused by someone starting to select (with the mouse) an area of the screen: the process will pause until is pressed, which copies the area to the clipboard. This only happens with a console window, but it sounds like that's what you had running. TJG From is_this at visible.com Wed Jul 30 08:10:53 2008 From: is_this at visible.com (Bruce Frederiksen) Date: Wed, 30 Jul 2008 12:10:53 +0000 Subject: Defunct when using subprocess.Popen References: <6D3D064BBC122445A4577CE1895FA06501755913@afsegbgex1.af.se> Message-ID: <7802d$48905a4d$18607848$7519@KNOLOGY.NET> On Wed, 30 Jul 2008 01:56:28 -0300, Gabriel Genellina wrote: > You should call os.waitpid() after killing the child process, to let the > OS free the resources allocated to it. > The subprocess.Popen object supports a 'wait' method directly. From sri_annauni at yahoo.co.in Wed Jul 30 07:17:26 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Wed, 30 Jul 2008 16:47:26 +0530 (IST) Subject: Python Modules To convert PDF files to HTML files Message-ID: <217761.61697.qm@web7905.mail.in.yahoo.com> Hi, could someone tel me any python modules which can be used to convert PDF files to HTML files?? Thanks, Srini Unlimited freedom, unlimited storage. Get it now, on http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/ From tjreedy at udel.edu Wed Jul 30 12:39:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jul 2008 12:39:02 -0400 Subject: Pointers/References in Python? In-Reply-To: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> References: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Message-ID: boblatest at googlemail.com wrote: > Hello, > > I have a long list of memory-heavy objects that I would like to access > in differently sorted order. Let's say I'd like to have lists called > by_date or by_size that I can use to access the objects in the > specified order. > > Of course I can just build those lists naively by creating copies of > the original list and then sorting them according to my wishes. But > that would create huge memory overhead. Of course I could use lists of > indices into the "master" list, just as in C I'd create lists or > arrays of pointers into the original data. > > Is there a clever Python way to do this, or should I just use lists of > indices? > > I know there is a thing called "shallow copy" that has something to do > with not duplicating memory content but I don't understand the > concept. Maybe that's what would help here, too. A containers/collections contain/collect references to objects, not the objects themselves. lcopy = somelist[:] # or list(somelist) makes a shallow copy, which only copies the references. There are applications for lists of indexes, but they are fairly specialized. tjr From zstumgoren at gmail.com Thu Jul 31 15:01:36 2008 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 31 Jul 2008 15:01:36 -0400 Subject: Hobbyist - Python vs. other languages In-Reply-To: References: Message-ID: >From this noob's perspective, I'd say take a look at Magnus Lie Hetland's Beginning Pythonbook. It covers the core syntax (which it sounds like you're familiar with already) and then includes a bunch of projects, from text processing to cgi programming to remote file editing and basic game programming. Granted, you can find a lot of these examples as freeware, but I guess you stand to learn plenty by extending the code he provides. Good luck! Serdar T. On Thu, Jul 31, 2008 at 2:32 PM, fprintf wrote: > I have been playing with computers since I first learned to program > moving shapes on an Atari 800XL in BASIC. After many years of dabbling > in programming languages as a hobbyist (I am not a computer scientist > or other IT professional), I have never found a way to stick with a > language far enough to do anything useful. I learn all about loops > and data structures and functions/methods etc. but never get to create > a program that will do anything of value that I can't more easily do > via freeware. Well, except the slot car timing system I wrote in C++ > for Linux many moons ago. > > Honestly Python seems like a breath of fresh air and possibly a way to > get back to my BASIC roots, you know, programming just for the fun of > it. > > Since I don't have a specific problem to solve, besides > Pythonchallenge (which I found very cryptic), and Project Euler (which > I found beyond my mathematics skills), is there a place to go for > increasingly difficult problems to solve? I have followed a number of > the recommended online tutorials that contain a logical progression of > problems and yet they all end at the point where a person has enough > knowledge of the syntax, but not really enough to do anything. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Serdar Tumgoren The Record 150 River Street Hackensack, NJ 07601 201-403-0834 tumgoren at northjersey.com northjersey.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Wed Jul 9 01:55:06 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 09 Jul 2008 15:55:06 +1000 Subject: Returning the positions of a list that are non-zero References: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> Message-ID: <87bq17vbyd.fsf@benfinney.id.au> Benjamin Goudey writes: > For example, if my original list is [0,0,1,2,1,0,0] I would like to > produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices > of where the non-zero values used to be). Removing non-zero values > is very easy but determining the indicies is where I'm having > difficulty. The built-in 'enumerate' function is made for this. Creating the new list can be done efficiently and clearly with a list comprehension. Further, presumably you want to do further operations on these new series of data; wouldn't it be better to have the values and original indices actually correlated together? This code produces a two-element tuple for each original non-zero value: >>> sparse_data = [0, 0, 1, 2, 1, 0, 0] >>> nonzero_data = [(index, value) ... for (index, value) in enumerate(sparse_data) ... if value != 0] >>> nonzero_data [(2, 1), (3, 2), (4, 1)] >>> for (index, value) in nonzero_data: ... print "Value %(value)r was originally at index %(index)r" % vars() ... Value 1 was originally at index 2 Value 2 was originally at index 3 Value 1 was originally at index 4 -- \ ?Experience is that marvelous thing that enables you to | `\ recognize a mistake when you make it again.? ?Franklin P. Jones | _o__) | Ben Finney From mlowicki at gmail.com Thu Jul 31 04:33:45 2008 From: mlowicki at gmail.com (=?ISO-8859-2?Q?=A3owik?=) Date: Thu, 31 Jul 2008 10:33:45 +0200 Subject: hosting on djangodomain.com Message-ID: Hi! Did anyone used this hosting or heard about it? It's good or not? what can you talk about it? From ironfroggy at gmail.com Thu Jul 17 08:30:13 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Thu, 17 Jul 2008 08:30:13 -0400 Subject: storing references instead of copies in a dictionary In-Reply-To: References: Message-ID: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> On Thu, Jul 17, 2008 at 7:45 AM, mk wrote: > Hello everyone, > > I'm storing functions in a dictionary (this is basically for cooking up my > own fancy schmancy callback scheme, mainly for learning purpose): > >>>> def f2(arg): > ... return "f2 " + arg > ... >>>> >>>> def f1(arg): > ... return "f1" + arg > ... > >>>> a={'1': f1, '2': f2} >>>> >>>> [ x[1](x[0]) for x in a.items() ] > ['f11', 'f2 2'] > > Well, neat. Except if I change function definitions now, old functions are > called. And rightly: > > {'1': , '2': } >>>> f1 > >>>> >>>> def f1(arg): > ... return "NEW f1 " + arg > ... >>>> f1 > > > The address of function f1 has obviously changed on redefinition. > > Storing value copies in a dictionary on assignment is a reasonable default > behaviour. > > However, in this particular case I need to specifically store _references to > objects_ (e.g. f1 function), or should I say _labels_ (leading to objects)? > > Of course, I can basically update the dictionary with a new function > definition. > > But I wonder, is there not a way _in general_ to specifically store > references to functions/variables/first-class objects instead of copies in a > dictionary? As was pointed out already, this is a basic misunderstanding of assignment, which is common with people learning Python. To your actual problem... Why do you wanna do this anyway? If you want to change the function in the dictionary, why don't you simply define the functions you'll want to use, and change the one you have bound to the key in the dictionary when you want to change it? In other words, define them all at once, and then just d['1'] = new_f1. What is wrong with that? For completeness: def new_f1(arg): return "NEW f1 " + arg f1.func_code = new_f1.func_code Don't use that unless you really have to and I nearly promise that you don't. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From fredrik at pythonware.com Mon Jul 21 12:12:17 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 18:12:17 +0200 Subject: Python Written in C? In-Reply-To: <4884B3EB.4090001@timgolden.me.uk> References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> <4884B3EB.4090001@timgolden.me.uk> Message-ID: Tim Golden wrote: >> Wrong! Real programmers can program using only Touring machine > > Is that some kind of bicycle? there's a nearly infinite number of software projects with that name, but the Ultimate Touring Machine could be found in sydney not long ago: http://tinyurl.com/5t2dl4 From stochashtic at yahoo.ca Tue Jul 29 11:25:36 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 29 Jul 2008 17:25:36 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <488d86e2$1@news2-rz-ap.ethz.ch> <488dc3eb$1@news2-rz-ap.ethz.ch> <488ddc3c$1@news2-rz-ap.ethz.ch> Message-ID: <488f3670$1@news2-rz-ap.ethz.ch> On Mon, 28 Jul 2008 16:48:28 +0200, Suresh Pillai wrote: > Okay, please consider this my one absolutely stupid post for the year. > I'd like to pretend it never happened but unfortunately the web doesn't > allow that. Having never used sets, I unfort read something that lead > to it, but ... Okay, got some sleep and what I meant to ask, although equally basic, but not silly: For sets, I presume they are built on top of or like dicts, and there is nothing crazy in the low level implementation so that I can be guaranteed that if I don't alter the set, then the order, although arbitrary, will be maintained in successive iterations over the contents? From michael at stroeder.com Tue Jul 8 04:58:27 2008 From: michael at stroeder.com (=?UTF-8?B?TWljaGFlbCBTdHLDtmRlcg==?=) Date: Tue, 08 Jul 2008 10:58:27 +0200 Subject: windows active directory ldap output encoding In-Reply-To: References: Message-ID: Michael Str?der wrote: > jo3c wrote: >> Im trying to get some information out of a windows sever 2003 chinese >> active directory system >> so let's say encoding is probably big5 or utf-8 > > The Unicode encoding of LDAP attributes with syntax Directory String is > always UTF-8 (e.g. attributes 'cn', 'sn', 'givenName' or 'displayName'). BTW: I'd be curious to see whether my web2ldap works with Chinese characters. Since you already have python-ldap installed it's easy to download (from http://www.web2ldap.de/download.html) and unpack the tar.gz and start it as stand-alone web server: python /sbin/web2ldap.py -d off Ah forgot, pyweblib needs to also be installed with usual python setup.py install: http://www.stroeder.com/pylib/PyWebLib/ If everything is correctly configured in your browser you should the correct Unicode chars. Maybe you can even maintain your AD entries. Ciao, Michael. From 2007 at jmunch.dk Sun Jul 27 14:35:19 2008 From: 2007 at jmunch.dk (Anders J. Munch) Date: Sun, 27 Jul 2008 20:35:19 +0200 Subject: Rant (was Re: x*x if x>10 In-Reply-To: References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3g8rF9gfj0U1@mid.uni-berlin.de> <6f3gmaF9moqsU1@mid.uni-berlin.de> <1q5p845o2j9htp6vf44u6nqinucsr1numf@4ax.com> Message-ID: <488cbfe7$0$4452$ba624c82@nntp02.dk.telia.net> Gary Herron wrote: > >>> A = [1,2,3] > >>> B = [4,5,6] > >>> C = [7,8,9] > > >>> A+B+C > [1, 2, 3, 4, 5, 6, 7, 8, 9] > > >>> sum([A,B,C], []) > [1, 2, 3, 4, 5, 6, 7, 8, 9] Careful now, this can be very slow. sum uses __add__, not __iadd__, which gives this approach quadratic worst-case runtime. - Anders From norseman at hughes.net Mon Jul 21 12:26:42 2008 From: norseman at hughes.net (norseman) Date: Mon, 21 Jul 2008 09:26:42 -0700 Subject: win32api not found? In-Reply-To: References: Message-ID: <4884B8C2.9020905@hughes.net> Lamonte Harris wrote: > Where can I get the win32api module? I been searching all day on google and > nothing, i installed > https://sourceforge.net/project/showfiles.php?group_id=78018 which requires > win32api and its not found... > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list ============================ I followed the links from python.org to Mark Harmond's win32 package. It loads into (in my case) c:\\Python25\\Lib\\site-packages\\win32 as win32api.pyd Also: try the import win32api command another has suggested before searching all over. HTH Steve norseman at hughes.net From gerard.blais at gmail.com Mon Jul 14 10:24:28 2008 From: gerard.blais at gmail.com (Gerry) Date: Mon, 14 Jul 2008 07:24:28 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> <378b8499-4b1b-4eda-bb13-91bf59c77bfc@a70g2000hsh.googlegroups.com> Message-ID: If keys and values are unique, maybe just store both in the same dictionary: mydict[a] = b mydict[b] = a ... Gerry On Jul 14, 8:31?am, Impotent Verse wrote: > If keys and values are unique you could do this... > > -------------- > > # ? ? ? ? Left ? ? ?: Right > roman = { "One" ? ? : "I", > ? ? ? ? ? "Two" ? ? : "II", > ? ? ? ? ? "Three" ? : "III", > ? ? ? ? ? "Four" ? ?: "IV", > ? ? ? ? ? "Five" ? ?: "V", > ? ? ? ? ? "Six" ? ? : "VI", > ? ? ? ? ? "Seven" ? : "VII", > ? ? ? ? ? "Eight" ? : "VIII", > ? ? ? ? ? "Nine" ? ?: "IX", > ? ? ? ? ? "Ten" ? ? : "X" } > > left, right = zip( *roman.items() ) > left = list(left) > right = list(right) > > print left[ right.index("VIII") ] > > -------------- > > ... result is "Eight". > > Hmmm! zip returns tuples, which need to be turned into lists to do > much with. Maybe not the best solution in this case. > > Verse. From ruabag at gmail.com Fri Jul 4 05:37:38 2008 From: ruabag at gmail.com (rabad) Date: Fri, 4 Jul 2008 02:37:38 -0700 (PDT) Subject: Newbie, list has no attribute iteritems Message-ID: <12caa75c-455a-4ab3-a9c3-4bd191b6965d@k13g2000hse.googlegroups.com> Hi, I've created a custom filter based on HTMLParser, with the following source: class Filter(HTMLParser): def __init__(self, keyfile): HTMLParser.__init__(self) mykwfile = open(keyfile, 'r') self._keywords = [] for kw in mykwfile.read().split('\n'): self._keywords.append(kw) print kw mykwfile.close() self._toProcess = False self.stack = [] def handle_starttag(self, tag, attrs): if 'a' != tag: self.stack.append(self.__html_start_tag(tag, attrs)) return attrs = dict(attrs) self._toProcess = True for key in self._keywords: if 'a' == tag: p = re.compile(key, re.IGNORECASE) if 'href' in attrs: attrs['href'] = p.sub(r'XXXXX',attrs['href']) self.stack.append(self.__html_start_tag(tag, attrs)) def handle_startendtag(self, tag, attrs): if 'img' != tag and 'meta' != tag: self.stack.append(self.__html_startend_tag(tag, attrs)) return attrs = dict(attrs) self._toProcess = True for key in self._keywords: p = re.compile(key, re.IGNORECASE) if 'img' == tag: if 'src' in attrs: attrs['src'] = p.sub(r'XXXXX',attrs['src']) if 'alt' in attrs: attrs['alt'] = p.sub(r'XXXXX',attrs['alt']) if 'meta' == tag: if 'description' in attrs: attrs['description'] = p.sub(r'XXXXX',attrs['description']) if 'content' in attrs: attrs['content'] = p.sub(r'XXXXX',attrs['content']) if 'meta' == tag or 'img' == tag: self._toProcess = False self.stack.append(self.__html_startend_tag(tag, attrs)) def handle_endtag(self, tag): self.stack.append(self.__html_end_tag(tag)) if self._toProcess: self._toProcess = False def handle_data(self, data): if self._toProcess: for key in self._keywords: p = re.compile(key,re.IGNORECASE) data = p.sub(r'XXXXX',data) self.stack.append(data) def __html_start_tag(self, tag, attrs): return '<%s%s>' % (tag, self.__html_attrs(attrs)) def __html_startend_tag(self, tag, attrs): return '<%s%s/>' % (tag, self.__html_attrs(attrs)) def __html_end_tag(self, tag): return '' % (tag) def __html_attrs(self, attrs): _attrs = '' if attrs: _attrs = ' %s' % (' '.join([('%s="%s"' % (k,v)) for k,v in attrs.iteritems()])) return _attrs But when I use it, it gives me the following error message: ERROR Processor exception: AttributeError: 'list' object has no attribute 'it eritems' Traceback (most recent call last): File "d:\esp\lib\python2.3\processors\DocDumpF.py", line 87, in Process p.feed(document.GetValue("data")) File "HTMLParser.py", line 108, in feed File "HTMLParser.py", line 148, in goahead File "HTMLParser.py", line 281, in parse_starttag File "d:\esp\lib\python2.3\processors\DocDumpF.py", line 121, in handle_startt ag self.stack.append(self.__html_start_tag(tag, attrs)) File "d:\esp\lib\python2.3\processors\DocDumpF.py", line 167, in __html_start_ tag return '<%s%s>' % (tag, self.__html_attrs(attrs)) File "d:\esp\lib\python2.3\processors\DocDumpF.py", line 178, in __html_attrs _attrs = ' %s' % (' '.join([('%s="%s"' % (k,v)) for k,v in attrs.iteritems() ])) Anybody knows why it says attrs is not a list element? Thanks, Rub?n From robnhood007 at yahoo.com Tue Jul 15 16:54:39 2008 From: robnhood007 at yahoo.com (robnhood00) Date: Tue, 15 Jul 2008 13:54:39 -0700 (PDT) Subject: Need Python Programmer (preferentially in Los Angeles) Message-ID: I need a python programmer that can integrate graphics into an existing python application. The application is a basic application and the job should be pretty easy for an experienced Python programmer. Los Angeles programmer is preferred but this can obviously be done from anywhere. Please contact me at robnhood007 at yahoo.com is you can help me. Thank you. From mccredie at gmail.com Fri Jul 25 18:43:09 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 25 Jul 2008 15:43:09 -0700 (PDT) Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: <24a548ad-4cb3-410c-89df-21da6ef4220f@j7g2000prm.googlegroups.com> On Jul 24, 9:32?pm, Lawrence D'Oliveiro wrote: > In message > , Matimus > wrote: > > > On Jul 24, 2:54?am, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: > >> In message > >> , > > >> Matimus wrote: > >> > That isn't the standard. With that setup tabs will show up as 4 > >> > spaces, and still confuse you. > > >> Why should that be confusing? The most common tab-stop setting is 4 > >> columns. > > > A tab character is specified as 8 spaces. > > Specified by whom? The most common setting these days is 4 columns. All argument about specification aside, Python interprets a tab character as equivalent to 8 spaces. If you are treating tabs as equivalent to 4 spaces in your python code it will cause IndentationError exceptions to be raised. If you set 'tabstop' to 4 in Vim all of the blocks of code indented using 4 spaces will be aligned with code indented with tabs. That is obviously problematic. Setting 'et' will fix the problem of inserting tabs, but does nothing to adjust the way tabs are displayed. Vim has a feature 'softtabspace'/'sts' which is used to modify the way tabs are inserted without modifying the way they are displayed. If you are writing python code using Vim and you intend to indent using 4 spaces (as recommended by pep8), the best practice I have found is to `set sw=4 ts=8 sts=4 et`. Matt From sisson.j at gmail.com Sun Jul 13 14:52:18 2008 From: sisson.j at gmail.com (Jonathon Sisson) Date: Sun, 13 Jul 2008 13:52:18 -0500 Subject: Socket problems In-Reply-To: References: Message-ID: <487A4EE2.2010600@gmail.com> SSL objects use "write", not "send". You also need to change this: self.sock.write('NICK %s\r\n') % self.nick to this: self.sock.write('NICK %s\r\n' % self.nick) If you don't, the interpreter will bomb on trying to concatenate the return value for "write" (an integer) with the string self.nick. Hope this helps... Jonathon jjbutler88 at gmail.com wrote: > I am trying to write a simple python IRC client, roughly following > this guide: http://www.devshed.com/c/a/Python/Python-and-IRC/ > > I have written some code, which uses the same commands as the guide, > but I get this error: > Traceback (most recent call last): > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/threading.py", line 486, in __bootstrap_inner > self.run() > File "pythonirc.py", line 31, in run > self.sock.send('NICK %s\r\n') % self.nick > AttributeError: send > > Here is my code so far: > [code] > #!/usr/bin/env python > > from socket import * > from threading import Thread > import sys > > class IRCBot(Thread): > def __init__(self, host, room, nick, port=6667, ssl=0): > Thread.__init__(self) > self.host = host > self.port = port > self.ssl = ssl > self.room = room > self.nick = nick > self.sock = socket(AF_INET, SOCK_STREAM) > > def run(self): > print "Connecting..." > try: > self.sock.connect((self.host, self.port)) > except: > print "Could not connect to %s" % self.host > sys.exit(1) > if self.ssl: > try: > self.sock = ssl(self.sock) > except: > print "Server does not suport SSL" > sys.exit(1) > > self.sock.send('NICK %s\r\n') % self.nick > self.sock.send('USER PyIRC PyIRC PyIRC :Python IRC\r\n') > self.sock.send('JOIN #%s\r\n') % self.room > while True: > data = self.sock.recv(4096) > if data.find('PING') != -1: > self.sock.send('PONG' + data.split()[1]+'\r\n') > print data > > def close(self): > self.sock.send('PART #%s\r\n') % self.room > self.sock.send('QUIT\r\n') > self.sock.shutdown(SHIT_RDWR) > self.sock.close() > > IRCBot('irc.psych0tik.net','hbh', 'pythonircclient',6697,1).start() > [/code] > > Anyone know why it might be doing this? Config problem? > > Thanks in advance, > Jon > > -- > http://mail.python.org/mailman/listinfo/python-list > > From bkasterm at gmail.com Thu Jul 10 09:19:38 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Thu, 10 Jul 2008 08:19:38 -0500 Subject: Changing self: if self is a tree how to set to a different self Message-ID: I am playing with some trees. In one of the procedures I wrote for this I am trying to change self to a different tree. A tree here has four members (val/type/left/right). I found that self = SS does not work; I have to write self.val = SS.val and the same for the other members (as shown below). Is there a better way to do this? In the below self is part of a parse tree, F is the parse tree of a function f with argument x. If a node in the parse tree is labelled f, we should replace it by the parse tree for the function f, F, with the remainder of the tree substituted for the input variable for the function f, here x. def elimF (self): if self.val == "f": SS = F.copy () SS.subst ('x', self.left) self.val = SS.val # from here: set self to be SS self.type = SS.type self.left = SS.left self.right = SS.right # completed: set self to be SS if self.left != None: # iterate onward, inf recursion if f # appears. Would need a check in # real version self.left.elimF () if self.right != None: self.right.elimF () Best, Bart From jtanis at mdchs.org Sun Jul 20 13:58:11 2008 From: jtanis at mdchs.org (James Tanis) Date: Sun, 20 Jul 2008 13:58:11 -0400 Subject: Web Server In-Reply-To: <1dc5311f-6243-41d4-b5da-78183c9668e4@m44g2000hsc.googlegroups.com> Message-ID: <4498d5b98057018dd1a9c7cae17732a2@portal.mdchs.org> misceverything at gmail.com wrote: > Thanks, Fredrik - that definitely works. Now to get a little greedy - > is there something along those lines that is a bit more secure (i.e. > allows HTTPS, possibly with authentication)? Basically something that > you would feel more comfortable opening up to the Internet.. > > -- > http://mail.python.org/mailman/listinfo/python-list > You can do HTTPS with Twisted, you'll have to learn how to use Twisted which can sometimes be a task in itself. Most everything is pretty easy to learn although I get a little befuddled by the way they handle authentication myself. I personally think it's worth it though, Twisted is a great resource for rapid development of certain types of clients/servers. -- James Tanis Technical Coordinator Monsignor Donovan Catholic High School e: jtanis at mdchs.org From cyberco at gmail.com Sat Jul 19 15:24:59 2008 From: cyberco at gmail.com (Berco Beute) Date: Sat, 19 Jul 2008 12:24:59 -0700 (PDT) Subject: create instance attributes for every method argument Message-ID: <4780837f-a5bc-4071-94d3-28e2f206163e@k30g2000hse.googlegroups.com> I remember reading somewhere how to create an instance attribute for every method argument, but although Google is my friend, I can't seem to find it. This could likely be done way more elegant: ========================= class Test(object): def __init__(self, a, b, c, d, e, f): self.a = a self.b = b self.c = c self.d = d ========================= 2B From semanticist at gmail.com Sun Jul 13 04:14:15 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 04:14:15 -0400 Subject: socket.connect() hangs in SYN_SENT state. In-Reply-To: References: Message-ID: On Sat, Jul 12, 2008 at 11:23 PM, bukzor wrote: > I'm connecting to an apache2 process on the same machine, > for testing. When looking at netstat, the socket is in the SYN_SENT > state, like this: > > $netstat -a -tcp > tcp 0 0 *:www *:* LISTEN 7635/apache2 > tcp 0 1 bukzor:38234 adsl-75-61-84-249.d:www SYN_SENT 9139/python > > Anyone know a general reason this might happen? Even better, a way to > fix it? That socket connection is to a remote machine, not the same one. Your test code works fine for me. The "hang then crash" (and I'm assuming "crash" here means an uncaught exception) just means that your packets are being silently ignored by whatever machine you're actually attempting to connect to. It's possible that your machine has odd DNS settings causing buzkor.hopto.org to resolve to the wrong address. -Miles From lemcoe9 at bellsouth.net Sun Jul 20 17:07:42 2008 From: lemcoe9 at bellsouth.net (David M Lemcoe Jr.) Date: Sun, 20 Jul 2008 21:07:42 +0000 (UTC) Subject: Testing out Newsproxy. Message-ID: Going to see if Newsproxy actually blocks google groups. -=___________________________=- David M Lemcoe Jr. Roswell, Georgia http://www.davidlemcoe.com/ lemcoe9 at bellsouth.net QRZ: KI4YJL AIM: lemcoe9 YIM: lemcoe9 GTalk: ki4yl at gmail.com MSN: lemcoe9 at hotmail.com Xfire: shawtylo1 ICQ: 359114839 Alternate e-mail: lemcoe9.alt at gmail.com -=___________________________=- From ethan at stoneleaf.us Wed Jul 9 16:48:44 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 09 Jul 2008 12:48:44 -0800 Subject: a simple 'for' question In-Reply-To: <48749F60.7030106@umbc.edu> References: <4874017D.2000401@umbc.edu> <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> <487437E6.8010609@umbc.edu> <1215599630.2873.965.camel@localhost.localdomain> <48749F60.7030106@umbc.edu> Message-ID: <4875242C.8020009@stoneleaf.us> Ben Keshet wrote: > it didn't help. it reads the pathway "as is" (see errors for both > tries). It looks like it had the write pathway the first time, but > could not find it because it searched in the path/way instead of in the > path\way. thanks for trying. The form of slash ('\' vs '/') is irrelevant to Python. At least on Windows. > folders= ['1','2','3'] > for x in folders: > print x # print the current folder > filename='Folder/%s/myfile.txt' %[x] ^- brackets not needed > f=open(filename,'r') > > gives: IOError: [Errno 2] No such file or directory: > "Folder/['1']/myfile.txt" > Pay attention to the error message. Do you actually have the file "Folder\['1']\myfile.txt" on your machine? And did you really want brackets and quotes? Is the path located relative to whereever your python script is running from? If it's an absolute path, precede it with a leading slash. As far as the Python question of string substitution, "%s" % var is an appropriate way. Your above code should read: folders = ['1', '2', '3'] for x in folders: print x filename = 'Folder/%s/myfile.txt' % x f = open(filename, 'r') Again, in order for that to work, you *must* have a path/file of 'Folder\1\myfile.txt' existing from the same folder that this code is running from. This is O/S related, not Python related. -- Ethan From Nikolaus at rath.org Thu Jul 31 08:30:19 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Thu, 31 Jul 2008 14:30:19 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> <12072cbe-139a-430f-81aa-b64bc31b43e5@e39g2000hsf.googlegroups.com> Message-ID: <87zlny8cdg.fsf@nokile.rath.org> oj writes: > On Jul 31, 11:37?am, Nikolaus Rath wrote: >> So why does Python distinguish between e.g. the type 'int' and the >> class 'myclass'? Why can't I say that 'int' is a class and 'myclass' >> is a type? > > I might be wrong here, but I think the point is that there is no > distinction. A class (lets call it SomeClass for this example) is an > object of type 'type', and an instance of a class is an object of type > 'SomeClass'. But there seems to be a distinction: >>> class int_class(object): ... pass ... >>> int_class >>> int why doesn't this print >>> class int_class(object): ... pass ... >>> int_class >>> int or >>> class int_class(object): ... pass ... >>> int_class >>> int If there is no distinction, how does the Python interpreter know when to print 'class' and when to print 'type'? Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From larry.bates at websafe.com` Mon Jul 21 12:51:25 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 11:51:25 -0500 Subject: Please recommend a RPC system working with twisted. In-Reply-To: <312040c6-4011-451e-8a45-f982c2e4462f@j1g2000prb.googlegroups.com> References: <312040c6-4011-451e-8a45-f982c2e4462f@j1g2000prb.googlegroups.com> Message-ID: ??? wrote: > Hi all, > > I'm looking for an RPC system working with twisted. > > 1. Binary. I want it run faster than any xml based RPC. > > 2. Bidirectional. Unlike HTTP, on which the client has to poll the > sever for events, the server should "call" the client's method to > notify events. > > 3. C/Python support. Part of the system shall be written in C. > > 4. Could easily integrated with twisted. > > Unfortunately, there seems no such resolution existed. So maybe I > have to give up some requirements. > > --------------------------------------------------------------------------------------------------------------------------- > > It would be wonderful if ICE could integrate with twisted! Twisted Perspective Broker? -Larry From spython01 at gmail.com Tue Jul 22 17:43:10 2008 From: spython01 at gmail.com (Samir) Date: Tue, 22 Jul 2008 14:43:10 -0700 (PDT) Subject: Iterating Through List or Tuple Message-ID: Is there a way to loop or iterate through a list/tuple in such a way that when you reach the end, you start over at the beginning? For example, suppose I define a list "daysOfWeek" such that: >>> daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] If today is Sunday, I can set the variable "day" to today by: >>> i = iter(daysOfWeek) >>> day = i.next() >>> print day sunday If I want to find out the day of the week 2 days from now, then this code works ok: >>> for x in xrange(2): day = i.next() >>> print day tuesday However, when extending my range beyond the number of items in the list, I receive an error. For example, if I want to find out the day of the week 11 days from today, I get this: >>> for x in xrange(11): day = i.next() Traceback (most recent call last): File "", line 1, in for x in xrange(11): day = i.next() StopIteration Is there a way to easily loop through a list or tuple (and starting over at the beginning when reaching the end) without having to resort to an "if" or "while" statement? (My question concerns the more general use of lists and tuples, not necessarily determining days of the week. I know about using "import datetime" and "from calendar import weekday" but thought that using the days of the week would best illustrate my problem.) As always, thanks in advance. Samir From Russ.Paielli at gmail.com Wed Jul 30 23:44:40 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 30 Jul 2008 20:44:40 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> Message-ID: <8892522e-08b6-4506-a25d-c417e6342f3c@v1g2000pra.googlegroups.com> On Jul 30, 8:24 pm, "Russ P." wrote: > On Jul 30, 8:03 pm, Erik Max Francis wrote: > > > Russ P. wrote: > > > The reason I wrote that "it would be nice to be able to write" > > > > if x is not empty: > > > > is that it reads naturally. It was not an actual proposal, and the > > > fact that you took it as such was *your* mistake. > > ... > > > Now read carefully: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! Let > > > me repeat that for you: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! > > > Did you get that, idiot? > > > So people who can read words but not minds are idiots. Go get 'em, tiger! > > I don't know if you can read minds, but you seem to have a lot of > trouble reading words. > > Can you read "it would be nice to be able to write ..."? Can you > understand what it means? Can you understand that it does *not* mean, > "one *should* be able to write ..."? > > The really significant question here is why I waste my valuable time > with pedants like you. Folks, I'm sorry for being so harsh here. But this guy keeps insisting that I dispayed a "fundamental lack of understanding" of the correct usage of "is" in Python. If that were true, I would have gladly admitted it and dropped the matter. But it is completely false. The simple fact is that I fully understood how "is" works in Python from the first time I read about it -- as I'm sure most others here did too. It just gets my goat that someone would latch onto some whimsical suggestion I wrote to try to prove otherwise. He did not need to play that silly little game, and he could have easily avoided my insults had he not played it. From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 09:16:31 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 15:16:31 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <48889ca7$0$10455$426a34cc@news.free.fr> Lawrence D'Oliveiro a ?crit : > In message > <52404933-ce08-4dc1-a558-935bbbae779b at r35g2000prm.googlegroups.com>, Jordan > wrote: > >> Except when it comes to Classes. I added some classes to code that had >> previously just been functions, and you know what I did - or rather, >> forgot to do? Put in the 'self'. In front of some of the variable >> accesses, but more noticably, at the start of *every single method >> argument list.* > > The reason is quite simple. Python is not truly an "object-oriented" > language. Oh yes ? What's missing exactly ? You have objects that have an id, state and behaviour, and you have a message-passing mechanism. You meant "Python is not truly a mainstream class-based language", I think. > It's sufficiently close to fool those accustomed to OO ways of > doing things, s/OO/class-based/ > but it doesn't force you to do things that way. You still > have the choice. An implicit "self" would take away that choice. It's not even a question of OO/non-OO. An implicit "self" would take away some things that makes Python's *object* model so powerful. From lemcoe9 at bellsouth.net Sat Jul 19 11:05:55 2008 From: lemcoe9 at bellsouth.net (David M Lemcoe Jr.) Date: Sat, 19 Jul 2008 15:05:55 +0000 (UTC) Subject: Question References: Message-ID: Hello perl_wizard at manx.net, No language is better than another because Python is not intended for the same uses and/or people. Your question has no place here. David -=___________________________=- David M Lemcoe Jr. Roswell, Georgia http://www.davidlemcoe.com/ lemcoe9 at bellsouth.net QRZ: KI4YJL AIM: lemcoe9 YIM: lemcoe9 GTalk: ki4yl at gmail.com MSN: lemcoe9 at hotmail.com Xfire: shawtylo1 ICQ: 359114839 Alternate e-mail: lemcoe9.alt at gmail.com -=___________________________=- > Why is Perl so much better than python? > From kay.schluehr at gmx.net Thu Jul 31 17:19:32 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 31 Jul 2008 14:19:32 -0700 (PDT) Subject: Non Continuous Subsequences References: Message-ID: <650df4ae-2f63-4428-b780-3f7045164690@p25g2000hsf.googlegroups.com> Here is an evil imperative, non-recursive generator: def ncsub(seq): n = len(seq) R = xrange(n+1) for i in xrange(1,2**n): S = [] nc = False for j in R: k = i>>j if k == 0: if nc: yield S break elif k%2 == 1: S.append(seq[j]) elif S: nc = True And here is a cython version without yield expression which won't work with cython: def ncsub(seq): n = len(seq) cdef int i,j,k,nc res = [] R = xrange(n+1) for i in xrange(1,2**n): S = [] nc = False for j in R: k = i>>j if k == 0: if nc: res.append(S) break elif k%2 == 1: S.append(seq[j]) elif S: nc = True return res Application: list(ncsub(range(19))) On my 1.5GHz notebook your original version needed 11.2s ( psyco version = 9.5s), my pure Python generator got it in 7.75s and the cython version in 2.3s. [Yes, I have too much time...] From babacity2 at gmail.com Thu Jul 24 16:57:31 2008 From: babacity2 at gmail.com (babacity2 at gmail.com) Date: Thu, 24 Jul 2008 13:57:31 -0700 (PDT) Subject: Efukt com - Amazing porn video collection Message-ID: <86db5004-3bdb-461a-8ece-59406fae30ba@u36g2000pro.googlegroups.com> efukt com . >>>>>>>>>>Best Collection of Efukt Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE efukt com VIDEOS<<<<<<<<<<< . efukt com From tjreedy at udel.edu Sat Jul 5 18:27:23 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 05 Jul 2008 18:27:23 -0400 Subject: pythoncom InternetExplorer.Application don't work in vista || firefox pythoncom ? In-Reply-To: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> References: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> Message-ID: gcmartijn at gmail.com wrote: > H! > > I using a script that opens a internet page in a small window (what I > can control) > In XP everything was working fine, but now I'm using Vista with IE7 > and this is what happends now: > > First a small window opens at the postion x0 y0 (like I want) but then > IE thinks "Hey lets open a other main window too". > And that window opens the url 'http://www.google.nl' Perhaps on XP you changed the IE homepage to about:blank. On your Vista machine, it is set to Google, perhaps by the manufacturer (for a fee). Try changing it. From barun.saha04 at gmail.com Wed Jul 23 09:01:20 2008 From: barun.saha04 at gmail.com (barun.saha04 at gmail.com) Date: Wed, 23 Jul 2008 06:01:20 -0700 (PDT) Subject: Problem with Python Server Pages (PSP) References: <9766b993-03e6-4b75-92a2-06244c41e51c@a1g2000hsb.googlegroups.com> Message-ID: On Jul 22, 5:36 pm, "Sebastian \"lunar\" Wiesner" wrote: > barun.sah... at gmail.com : > > > Hi, > > > I am facing a very basic problem with PSP. I have installed mod_python > > (in fedora Core 1), added the lines required for loading Python > > modules and handling PSP pages. I have created a hello.psp page. But > > when I try to view this hello.psp page, all Python code are getting > > displayed. > > Not directly related to this issue, but I wouldn't start developing with > PSP. Modern web development is better done with a WSGI compatible > framework like Django ... > > -- > Freedom is always the freedom of dissenters. > (Rosa Luxemburg) Thanks to all. But can someone suggest me what the possible cause/ solution for this behaviour could be? From bblais at bryant.edu Wed Jul 30 11:13:04 2008 From: bblais at bryant.edu (Brian Blais) Date: Wed, 30 Jul 2008 11:13:04 -0400 Subject: Pointers/References in Python? In-Reply-To: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> References: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Message-ID: On Jul 30, 2008, at 10:46 , boblatest at googlemail.com wrote: > Of course I can just build those lists naively by creating copies of > the original list and then sorting them according to my wishes. But > that would create huge memory overhead. If the list itself is not memory intensive, but only the objects, then you shouldn't have to worry. For example, In [1]:big_object=[0.0]*int(1e7) # about 40 meg In [2]:big_object2=[0.0]*int(1e7) # another 40 meg In [3]:list1=[big_object,big_object2] # maybe a few bytes more, but no copy In [4]:list2=[big_object2,big_object] # maybe a few bytes more, but no copy after this, my python process takes about 80 meg. names like big_object are just names, and they reference an object in memory. if you say a=big_object, you are saying that the name "a" should also reference that same object. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From 4564 at 755189.45 Mon Jul 28 10:48:09 2008 From: 4564 at 755189.45 (Enrico) Date: Mon, 28 Jul 2008 16:48:09 +0200 Subject: multiple inheritance and __getattr__ Message-ID: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> Hi there, I have the following situation (I tryed to minimize the code to concentrate on the issue): >>> class A(object): def __getattr__(self, name): print 'A.__getattr__' if name == 'a': return 1 raise AttributeError('%s not found in A' % name) >>> class B(object): def __getattr__(self, name): print 'B.__getattr__' if name == 'b': return 1 raise AttributeError('%s not found in B' % name) Both classes have a __getattr__ method. Now I want to have a class that inherits from both so I write: >>> class C(B,A): pass The problem arise when I try something like this: >>> c=C() >>> c.a A.__getattr__ 1 >>> c.b A.__getattr__ Traceback (most recent call last): File "", line 1, in c.b File "", line 5, in __getattr__ raise AttributeError('%s not found in A' % name) AttributeError: b not found in A I was expecting, after a fail in A.__getattr__, a call to the __getattr__ method of B but it seems that after A.__getattr__ fails the exception stops the flow. So, if I did understand well, B.__getattr__ will be never called "automatically". I don't know if this has a reason, if it is a design choice or what else, any explanation is welcome. Since A and B are not written by me I can only work on C. The solution that comes to my mind is to define a __getattr__ also in C and write something like: >>> class C(A,B): def __getattr__(self, name): try: return A.__getattr__(self, name) except AttributeError: return B.__getattr__(self, name) >>> c=C() >>> c.a A.__getattr__ 1 >>> c.b A.__getattr__ B.__getattr__ 1 A better solution is welcome. Many thanks, Enrico From kay.schluehr at gmx.net Sat Jul 19 12:59:23 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 19 Jul 2008 09:59:23 -0700 (PDT) Subject: Best Python packages? References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> <17861f55-8ad1-4703-ad22-838675f2afc4@w1g2000prk.googlegroups.com> Message-ID: <86b446d2-0d11-4410-bf89-a2a05fac81b2@s50g2000hsb.googlegroups.com> On 18 Jul., 12:23, Ben Sizer wrote: > On Jul 16, 3:31 pm, Fredrik Lundh wrote: > > > Ben Sizer wrote: > > > make my development a lot easier. > > > Knowing what kind of development you do might help, of course. Some > > libraries are excellent in some contexts and suck badly in others... > > Sure. Mostly I'm just interested in what's out there though. In C++ > you have Boost which everybody knows are a source of high quality > libraries, covering a fairly wide set of applications. Obviously > that's more low-level and less application specific, and the Python > standard libs do pretty much everything that is in Boost, but it's > that sort of peer-reviewed and widely-applicable list that I'd like to > see. > > I (attempt to) use TurboGears for web development and that depends on > a whole bunch of libraries - SQLObject, PyProtocols, RuleDispatch, > SimpleJson, FormEncode, etc - and I would never have heard of these if > TurboGears' exposure of its internals wasn't so common. Some of these > are web-specific but some are not. And I'd never know to look for them > specificially, because in many cases it wouldn't occur to me that they > exist. (eg. Object-Relational Mappers like SQLObject may be obvious if > you come from certain areas of IT, but I'd never heard of them before > I started with TurboGears.) > > For what it's worth, my main areas of interest are gaming, multimedia, > and web development. But I just like to hear about anything that > people might use which makes their life a lot easier and which perhaps > is not application specific - like ORMs or something similar. > > > Looking at things that larger projects and distributions use can also be > > a good idea. For example, if you're doing scientific stuff, go directly > > to enthought.com. If you're doing web stuff, look at the libraries big > > Django applications use. Etc. > > Sadly, I know just as little about what major applications are out > there as I do about what libraries are out there! > > -- > Ben Sizer In the original post you asked for "hidden gems" and now it seems you just want to know about Madonna or Justin Timberlake. Maybe a look on this collection helps http://wiki.python.org/moin/UsefulModules From mal at egenix.com Thu Jul 31 06:20:00 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 31 Jul 2008 12:20:00 +0200 Subject: Interbase In-Reply-To: References: Message-ID: <489191D0.40104@egenix.com> On 2008-07-30 18:49, Mike Hjorleifsson wrote: > Has anyone gotten python working with Interbase database platform ? I > need to query some info from an interbase database on another server > need a lil help getting started. You could try the EasySoft ODBC driver for InterBase: http://www.easysoft.com/products/data_access/odbc_interbase_driver/index.html together with our mxODBC interface for Python: http://www.egenix.com/products/python/mxODBC/ -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 31 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From israelu at elbit.co.il Tue Jul 29 02:41:51 2008 From: israelu at elbit.co.il (iu2) Date: Mon, 28 Jul 2008 23:41:51 -0700 (PDT) Subject: seemingly simple list indexing problem References: <5c118411-5703-44b3-888f-3785b517b8d4@u12g2000prd.googlegroups.com> Message-ID: <46b0becc-2f24-41de-a9e5-3013c6089d24@8g2000hse.googlegroups.com> On Jul 29, 3:59?am, John Machin wrote: > On Jul 29, 8:10 am, John Krukoff wrote: > > > > > > > On Mon, 2008-07-28 at 16:24 -0500, Ervan Ensis wrote: > > > My programming skills are pretty rusty and I'm just learning Python so > > > this problem is giving me trouble. > > > > I have a list like [108, 58, 68]. ?I want to return the sorted indices > > > of these items in the same order as the original list. ?So I should > > > return [2, 0, 1] > > > > For a list that's already in order, I'll just return the indices, i.e. > > > [56, 66, 76] should return [0, 1, 2] > > > > Any help would be appreciated. > > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > If your lists aren't so large that memory is an issue, this might be a > > good place for a variation of decorate, sort, undecorate. > > > >>> listToSort = [ 108, 58, 68 ] > > >>> decorated = [ ( data, index ) for index, data in > > > enumerate( listToSort ) ]>>> decorated > > > [(108, 0), (58, 1), (68, 2)]>>> result = [ None, ] * len( listToSort ) > > >>> for sortedIndex, ( ignoredValue, originalIndex ) in > > > enumerate( sorted( decorated ) ): > > ... ? ? result[ originalIndex ] = sortedIndex > > ...>>> result > > > [2, 0, 1] > > Simpliciter: > > > > >>> data = [99, 88, 77, 88, 66] > >>> [x[1] for x in sorted(zip(data, xrange(len(data))))] > [4, 2, 1, 3, 0] > > Use case? Think data == database table, result == index ...- Hide quoted text - > > - Show quoted text - I think it is wrong, using this on my data returns the wrong result data = [108, 58, 68, 108] >>> [x[1] for x in sorted(zip(data, xrange(len(data))))] [1, 2, 0, 3] From bruno.42.desthuilliers at websiteburo.invalid Fri Jul 11 08:28:17 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 11 Jul 2008 14:28:17 +0200 Subject: strip() using strings instead of chars In-Reply-To: References: Message-ID: <487751a6$0$29402$426a74cc@news.free.fr> Christoph Zwerschke a ?crit : > In Python programs, you will quite frequently find code like the > following for removing a certain prefix from a string: > > if url.startswith('http://'): > url = url[7:] DRY/SPOT violation. Should be written as : prefix = 'http://' if url.startswith(prefix): url = url[len(prefix):] (snip) > My problem with this is that it's cumbersome and error prone to count > the number of chars of the prefix or suffix. cf above > If you want to change it > from 'http://' to 'https://', you must not forget to change the 7 to 8. > If you write len('http://') instead of the 7, you see this is actually > a DRY problem. cf above > Things get even worse if you have several prefixes to consider: > > if url.startswith('http://'): > url = url[7:] > elif url.startswith('https://'): > url = url[8:] > > You can't take use of url.startswith(('http://', 'https://')) here. for prefix in ('http://', 'https://'): if url.startswith(prefix): url = url[len(prefix):] break For most complex use case, you may want to consider regexps, specifically re.sub: >>> import re >>> pat = re.compile(r"(^https?://|\.txt$)") >>> urls = ['http://toto.com', 'https://titi.com', 'tutu.com', 'file://tata.txt'] >>> [pat.sub('', u) for u in urls] ['toto.com', 'titi.com', 'tutu.com', 'file://tata'] Not to dismiss your suggestion, but I thought you might like to know how to solve your problem with what's currently available !-) From mail at timgolden.me.uk Tue Jul 29 09:40:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 29 Jul 2008 14:40:03 +0100 Subject: Windows Interpreter In-Reply-To: <4dc0cfea0807290626p4b05376en49ccb18f0e1eb4bb@mail.gmail.com> References: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> <488F1745.4020705@timgolden.me.uk> <4dc0cfea0807290626p4b05376en49ccb18f0e1eb4bb@mail.gmail.com> Message-ID: <488F1DB3.4010608@timgolden.me.uk> Victor Subervi wrote: > def a(): > chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', > '\\yz'] > rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like > the Beast? Who can wage war against him?\par' > for char in chars: > c = '(?<=' + char + ')' > test = re.search(c, rtf_markup) > try: > junk = test.group(0) > print char > except: > pass > > Now, I can paste that entire fn in linux. But in windows I have to paste > it line_by_line. Pain in butt! And it indents automatically. How change > that behavior. Well, I'm not really sure what to say. I've just copied that whole section with drag-mouse, Ctrl-C. I then opened a new interpreter window (effectively, Start > Run > python) and right-clicked over the window. At this point, the lines I copied were copied in and the function accepted by the interpreter. I do have QuickEdit on by default in all by console windows, but the only difference I expect that to make is that you'd otherwise have to use the window's System Menu (Alt-Space, Edit, Paste). TJG From digetl.try at gmail.com Sat Jul 26 06:01:58 2008 From: digetl.try at gmail.com (raja) Date: Sat, 26 Jul 2008 03:01:58 -0700 (PDT) Subject: Weinhaus Weiler Message-ID: <2e8f47b7-b657-44c3-8d4b-2a2db427a7e8@w39g2000prb.googlegroups.com> Historical half-timbered house with excellent cuisine in Oberwesel http://food-drinks.page.tl/ From gagsl-py2 at yahoo.com.ar Tue Jul 29 22:48:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 29 Jul 2008 23:48:47 -0300 Subject: I CAN connect socket to any localhost port but I shouldn't be able to References: <13c78fbf-751f-4d70-a012-53aa1eb64e53@79g2000hsk.googlegroups.com> Message-ID: En Tue, 29 Jul 2008 14:56:08 -0300, qvx escribi?: > I don't have server listening on port 8084 but I can open socket to it > (and to many other ports, tested for all<8000) Your example fails -as expected- on my PC running Python 2.5.2 + Windows XP SP2. It may be something specific to your setup or your platform. py> test(8084) Traceback (most recent call last): File "", line 1, in File "", line 5, in test File "", line 1, in connect socket.error: (10061, 'Connection refused') -- Gabriel Genellina From kyosohma at gmail.com Mon Jul 7 13:30:27 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 7 Jul 2008 10:30:27 -0700 (PDT) Subject: VNC capture in python References: Message-ID: On Jul 6, 11:12?pm, Astan Chee wrote: > Hi, > I was wondering if I can do a capture of a VNC screen in python. Kinda > like this http://search.cpan.org/~lbrocard/Net-VNC-0.35/lib/Net/VNC.pm > but without opening a VNC window or doing a screen capture. > Thanks for any suggestions > > -- > "Formulations of number theory: Complete, Consistent, Non-trivial. Choose two." > > Animal Logichttp://www.animallogic.com > How can you do a screen capture without doing a screen capture? You'll probably have to use some kind of automation techniques, SendKeys, and/ or the subprocess module. If you can find a VNC program that has a COM interface, then you may be able to use Python's win32com module, which is a part of the win32 package. Mike From orsenthil at gmail.com Fri Jul 4 20:57:18 2008 From: orsenthil at gmail.com (Phoe6) Date: Fri, 4 Jul 2008 17:57:18 -0700 (PDT) Subject: caseless dict - questions Message-ID: <77798300-820f-4175-a9cb-aef639d42a32@m45g2000hsb.googlegroups.com> I have a requirement for using caseless dict. I searched the web for many different implementations and found one snippet which was implemented in minimal and useful way. ############# import UserDict class CaseInsensitiveDict(dict, UserDict.DictMixin): def __init__(self, *args, **kwargs): self.orig = {} super(CaseInsensitiveDict, self).__init__(*args, **kwargs) def items(self): keys = dict.keys(self) values = dict.values(self) return [(self.orig[k],v) for k in keys for v in values] def __setitem__(self, k, v): hash_val = hash(k.lower()) self.orig[hash_val] = k dict.__setitem__(self, hash_val, v) def __getitem__(self, k): return dict.__getitem__(self, hash(k.lower())) obj = CaseInsensitiveDict() obj['Name'] = 'senthil' print obj print obj.items() obj1 = {} obj1['Name'] = 'senthil' print obj1 print obj1.items() ########### [ors at goofy python]$ python cid1.py {15034981: 'senthil'} [('Name', 'senthil')] {'Name': 'senthil'} [('Name', 'senthil')] --- The difference between the Caselessdict and {} is that when called as the object, the Caselessdict() is giving me the internal representation. obj = CaseInsensitiveDict() obj['Name'] = 'senthil' print obj gives: {15034981: 'senthil'} obj1 = {} obj1['Name'] = 'senthil' print obj1 Correctly gives {'Name': 'senthil'} What changes should I make to CaseInsensitiveDict ( written above), so that its instance gives the actual dictionary instead of its internal representation. Constructing a dictionary and returning from __init__ method did not work. TIA, Senthil From alexnbryan at gmail.com Sat Jul 12 15:47:01 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sat, 12 Jul 2008 12:47:01 -0700 (PDT) Subject: Help with BeautifulSoup Message-ID: <18423003.post@talk.nabble.com> Michiel Overtoom wrote: > > Alex wrote... >> >>Okay, heres the general idea of the html I have to work with: >> >>
>> noun >> >>
>>
>>
>> verb >>
>>
>>
>> >> >>Okay, I left off some stuff. > > I wish you didn't, or at least provided an URL where I can get the page > which you are trying to parse. Now I don't have a valid testcase to > tinker > with. And maybe you can also show your code which you already came up > with. > > >> I can easily get the tables but it is the span's than I am having trouble > with. > > I can't see any SPAN tags in the example you provided. > > Greetings, > > -- > "The ability of the OSS process to collect and harness > the collective IQ of thousands of individuals across > the Internet is simply amazing." - Vinod Vallopillil > http://www.catb.org/~esr/halloween/halloween4.html > > -- > http://mail.python.org/mailman/listinfo/python-list > > Oh, well sorry, I wrote the span tags, but they didn't show up. But it was around the noun. Here is the code I have to get the definitions alone: import urllib from BeautifulSoup import BeautifulSoup class defWord: def __init__(self, word): self.word = word def get_defs(term): soup = BeautifulSoup(urllib.urlopen('http://dictionary.reference.com/search?q=%s' % term)) for tabs in soup.findAll('table', {'class': 'luna-Ent'}): yield tabs.findAll('td')[-1].contents[0].string self.mainList = list(get_defs(self.word)) Theres a bit more to it, but it doesn't matter here, and so if you look I am using dictionary.com as the website. If you look at the html, the "" tags are where the type of the word is and that is what I need, in order. Or if I can figure out how many
tags are inbetween each "" tag, that too would work. This is the type the code I am talking about if it helps: ?noun
1. the curd of milk separated from the whey and prepared in many ways as a food.
2. a definite mass of this substance, often in the shape of a wheel or cylinder.
?verb (used without object)
9.
?verb (used with object) If you need anything else, feel free to ask! -- View this message in context: http://www.nabble.com/Re%3A-Help-with-BeautifulSoup-tp18418004p18423003.html Sent from the Python - python-list mailing list archive at Nabble.com. From gagsl-py2 at yahoo.com.ar Fri Jul 11 23:51:13 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 12 Jul 2008 00:51:13 -0300 Subject: Pickle and wx.TextCtrl References: Message-ID: En Fri, 11 Jul 2008 10:15:36 -0300, escribi?: > Trying to read a pickled filed and list contents. > > The attached program works using pprint, but I want to write to my frame. > WriteText only produces half of the records. > What is happening? What do you mean by "only produces half of the records"? Probably your problem has nothing to do with a TextCtrl - ensure you can save and load your data with a simple, console-based script, and only then write the GUI. The way you read the file is rather strange -mixing calls to readline and pickle.load- I'd write the data using pickle.dump calls *only* and then read it using pickle.load calls *only*. -- Gabriel Genellina From pavlovevidence at gmail.com Sat Jul 26 03:51:00 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 26 Jul 2008 00:51:00 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> Message-ID: On Jul 24, 4:11?am, Jordan wrote: > Of course not. > > I just think Explicit is better than Implicit is taken seriously by a > large segment the Python community as a guiding principle, Yeah, try telling that to the people who advise writing "if x" instead of "if x==0", or "if s" instead of "if len(s)==0". Carl Banks From basti.wiesner at gmx.net Thu Jul 10 12:34:25 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Thu, 10 Jul 2008 18:34:25 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <6deq2uF21vo2U1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch : > On Mon, 07 Jul 2008 16:44:22 +0200, Sebastian \"lunar\" Wiesner wrote: > >> Mark Wooding : >> >>> Sebastian "lunar" Wiesner wrote: >>> >>>> # perl -e '("a" x 100000) =~ /^(ab?)*$/;' >>>> zsh: segmentation fault perl -e '("a" x 100000) =~ /^(ab?)*$/;' >>> >>> (Did you really run that as root?) >> >> How come, that you think so? > > The '#' is usually the prompt of root accounts while ordinary users get a > '$'. Oh ... I just used "#" as a general placeholder, because I didn't want to copy my whole two-line prompt ;) I can assure, that I did not try this as root ;) and will use "$" in future ;) -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From snowballz.game at gmail.com Fri Jul 18 17:38:21 2008 From: snowballz.game at gmail.com (Michael Lubker) Date: Fri, 18 Jul 2008 14:38:21 -0700 (PDT) Subject: Any Game Developers here? Message-ID: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Any people that use Python as the predominant language for their game development here? ~Michael From bdesth.quelquechose at free.quelquepart.fr Sat Jul 19 06:12:38 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 19 Jul 2008 12:12:38 +0200 Subject: Question In-Reply-To: References: Message-ID: <4881da0e$0$11232$426a74cc@news.free.fr> Peter Otten a ?crit : > perl_wizard at manx.net wrote: > >> Why is Perl so much better than python? > > Because you have the video: > > http://mail.python.org/pipermail/python-list/2004-March/253370.html > KEYBOARD !-) From carsten.haese at gmail.com Thu Jul 31 13:31:55 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Thu, 31 Jul 2008 13:31:55 -0400 Subject: Function References In-Reply-To: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> Message-ID: squishywaffle at gmail.com wrote: > Greetings, > > I'm trying to wrap a function in a C library as a compiled C Python > module. Everything is going great, but I've hit a snag. There's a > function in the form of this: > > First the typedef: > typedef void(*FPtr_DeviceMessageHandler) (const DeviceMessage, const > char*); > > Then the actual function prototype: > FPtr_DeviceMessageHandler > RegisterDeviceMessageHandler(FPtr_DeviceMessageHandler); > [...] > [I] can't figure out how to cast the function reference from Python into > something the C RegisterDevice... function can handle. Mere casting won't do the trick. The function reference from Python is basically just an object that contains byte-code to be executed by the Python Virtual Machine. There is no way you can magically transform that into a C function by casting the Python object pointer to anything. You'll need a write a C function that will call a given Python function, and then you need to supply the pointer to that C function as your DeviceMessageHandler callback function, and somehow communicate to your C function which Python function it should call. Good luck. -- Carsten Haese http://informixdb.sourceforge.net From shandy.b at gmail.com Thu Jul 3 19:18:08 2008 From: shandy.b at gmail.com (shandy.b at gmail.com) Date: Thu, 3 Jul 2008 16:18:08 -0700 (PDT) Subject: Python and timezones References: <66de1777-ab65-4708-904b-3e511409a662@m36g2000hse.googlegroups.com> Message-ID: Nah, it's got to be something more than that. A bunch of them are screwed up. It's showing America/Saskatchewan as UTC-06:59. I think there's something wrong with my code. I've put it up at a pastebin so that it's easier to read. http://pastebin.ca/1061776 On Jul 2, 11:22?am, Mensanator wrote: > On Jul 2, 12:43?am, "shand... at gmail.com" wrote: > > > > > I'm trying to write some code to deal with world timezones, and I'm > > getting a strange result. ?America/Iqaluit should not be showing up in > > UTC+00:00, but it is. ?Can anyone see what's wrong with this code? > > > import time > > from datetime import datetime > > import os > > import pytz > > > def getZoneNamesOnThisComputer(): > > ? ? for i in pytz.all_timezones: > > ? ? ? ? if os.path.exists( os.path.join('/tmp/usr/share/zoneinfo/', > > i)): > > ? ? ? ? ? ? yield i > > > def getZonesGroupedByOffset(): > > ? ? '''return a dict of all the zone names , grouped by their offset > > ? ? eg: > > ? ? {'-0400': ['America/Blanc-Sablon', 'Etc/GMT+4'], > > ? ? ?'+0000': ['America/Iqaluit', 'Etc/GMT', 'Europe/Belfast', 'GB', > > 'GMT'], > > ? ? ?... > > ? ? } > > ? ? ''' > > ? ? Y,M,D,h,m,s = time.localtime()[:6] > > > ? ? zonesGroupedByOffset = {} > > > ? ? for name in getZoneNamesOnThisComputer(): > > ? ? ? ? tz = pytz.timezone(name) > > ? ? ? ? now = datetime(Y,M,D,h,m,s, tzinfo=tz) > > ? ? ? ? # strfime returns a string like "-0800" or "+0430" or "0000" > > ? ? ? ? offsetKey = now.strftime('%z') > > ? ? ? ? if not zonesGroupedByOffset.has_key(offsetKey): > > ? ? ? ? ? ? zonesGroupedByOffset[offsetKey] = [] > > ? ? ? ? zonesGroupedByOffset[offsetKey].append(name) > > ? ? return zonesGroupedByOffset > > > z = getZonesGroupedByOffset() > > print z['+0000'] > > > # Why is America/Iqaluit showing up here??? > > The database contains an error. Shit happens, deal with it. From xdicry at gmail.com Mon Jul 7 09:40:50 2008 From: xdicry at gmail.com (Evan) Date: Mon, 7 Jul 2008 06:40:50 -0700 (PDT) Subject: Is there a good way to implement file updating? such as lock, update, reload... References: <2ebcf7f9-a8d9-403f-a05a-f26a9ca420b0@x41g2000hsb.googlegroups.com> <6deef6F271g5U1@mid.uni-berlin.de> Message-ID: If I get rid of the XML, I have to change my script more and more, it is not easy to do that. :( :( Thanks, From egbert.bouwman at hccnet.nl Wed Jul 9 17:08:22 2008 From: egbert.bouwman at hccnet.nl (egbert) Date: Wed, 9 Jul 2008 23:08:22 +0200 Subject: formatting list -> comma separated (slightly different) In-Reply-To: <2.2.32.20080709202533.01137964@pop.xs4all.nl> References: <2.2.32.20080709202533.01137964@pop.xs4all.nl> Message-ID: <20080709210822.GA28498@hccnet.nl> On Wed, Jul 09, 2008 at 10:25:33PM +0200, Michiel Overtoom wrote: > Formatting a sequence of items such that they are separated by > commas, except the last item, which is separated by the word 'and'. > > For example: > > Three friends have a dinner: Anne, Bob and Chris row = ["Anne","Bob","Chris"] txt = ", ".join(row) pos = txt.rfind(", ") new = "%s and %s" % (txt[0:pos], txt[pos+2:]) egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From hat at se-162.se.wtb.tue.nl Thu Jul 10 10:10:32 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 10 Jul 2008 16:10:32 +0200 Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: Python doesn't use value semantics for variables but reference semantics: a = [1] b = a In many languages, you'd now have 2 lists. In Python you still have one list, and both a and b refer to it. Now if you modify the data (the list), both variables will change a.append(2) # in-place modification of the list print b # will print [1,2] If you don't want this, you should make a copy somewhere a = a + [2] or b = a[:] It takes a bit of getting used to, but it is very handy in practice. Read the docs about 'immutable' and 'mutable' types. (I expected this to be a FAQ, but I couldn't quickly find a matching entry) Albert From mensanator at aol.com Thu Jul 3 23:10:14 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 3 Jul 2008 20:10:14 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> Message-ID: <3f59ead2-1fd2-4fee-a5fd-06147d48d086@e53g2000hsa.googlegroups.com> On Jul 3, 8:10?pm, casevh wrote: > On Jul 3, 6:54?am, Mensanator wrote: > > > > > Well, it will be great at some point in the future > > when Python 2.6/3.0 have actually been released and > > third party extensions such as gmpy have caught up. > > > Until then, such solutions are worthless, i.e., of > > no value. > > gmpy is supported on Python 2.6. A new version and Windows binaries > were released shortly after 2.6b1 was released. Great! Looks like I'll be installing 2.6 this weekend. > > casevh From hubaghdadi at gmail.com Mon Jul 28 08:07:54 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Mon, 28 Jul 2008 05:07:54 -0700 (PDT) Subject: Module clarification References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> <896c547e-9fa1-4f84-8c9b-53a96e70246c@y21g2000hsf.googlegroups.com> Message-ID: <00c033b9-1b5a-4165-abec-4ff6119298a5@z66g2000hsc.googlegroups.com> On Jul 28, 6:55 am, Floris Bruynooghe wrote: > On Jul 28, 9:54 am, Hussein B wrote: > > > Hi. > > I'm a Java guy and I'm playing around Python these days... > > In Java, we organize our classes into packages and then jarring the > > packages into JAR files. > > What are modules in Python? > > An importable or runable (i.e. script) collection of classes, > functions, variables etc... > > > What is the equivalent of modules in Java? > > Don't know. Not even sure if it exists, but my Java is old and never > been great. > > > Please correct me if I'm wrong: > > I saved my Python code under the file Wow.py > > Wow.py is now a module and I can use it in other Python code: > > import Wow > > Indeed, you can now access things defined in Wow as Wow.foo > > Regards > Floris If I have a couple of modules, is there a way to package them? or there is no such a thing in Python? From usenet at janc.be Tue Jul 15 15:00:47 2008 From: usenet at janc.be (Jan Claeys) Date: Tue, 15 Jul 2008 19:00:47 GMT Subject: Python internals References: <008ca729$0$20313$c3e8da3@news.astraweb.com> Message-ID: Op Tue, 15 Jul 2008 09:29:58 -0500, schreef Larry Bates: > Names are pointers in Python that point to values in memory. But "pointers" doesn't have the same meaning as in "C" here. Memory in Python is not (necessarily) an "array of bytes"; how & where the values are stored in "physical memory" at any time during the lifetime of an object is an implementation detail. Maybe you can compare it to how a (university) library works: you ask a librarian for a book named "The Taste Of Man by Slavenka Draculi?" and they fetch it for you, using whatever internal classification/retrieval system they use. -- JanC From enleverlesX.XmcX at XmclaveauX.com Sun Jul 6 02:10:12 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sun, 6 Jul 2008 08:10:12 +0200 Subject: Python with Ecmascript In-Reply-To: References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com><486fe241$0$867$ba4acef3@news.orange.fr> Message-ID: <48706543$1$860$ba4acef3@news.orange.fr> Hi! > Is there a way to do similar things on linux? I think no. Because these tech use COM. And COM don't exist under xxnux. But: - look if XPCOM, or dBus) can help you - search with the word "MOZLAB", who work a solution (plugin) for drive Firefox, from an external software. Good luck! -- Michel Claveau From __peter__ at web.de Fri Jul 4 08:36:52 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Jul 2008 14:36:52 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: Henning_Thornblad wrote: > What can be the cause of the large difference between re.search and > grep? grep uses a smarter algorithm ;) > This script takes about 5 min to run on my computer: > #!/usr/bin/env python > import re > > row="" > for a in range(156000): > row+="a" > print re.search('[^ "=]*/',row) > > > While doing a simple grep: > grep '[^ "=]*/' input (input contains 156.000 a in > one row) > doesn't even take a second. > > Is this a bug in python? You could call this a performance bug, but it's not common enough in real code to get the necessary brain cycles from the core developers. So you can either write a patch yourself or use a workaround. re.search('[^ "=]*/', row) if "/" in row else None might be good enough. Peter From noagbodjivictor at gmail.com Mon Jul 14 06:18:06 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Mon, 14 Jul 2008 06:18:06 -0400 Subject: Simple Image Cropper Message-ID: >Hi, > >I am designing a simple image cropper which simply takes an image and use PIL > to do the cropping.Now in order to do the cropping I simply draw a rectangle on > the image by dragging the mouse over the image.I then use button press and > button release events to find the mouse postition and send across the tuple to PIL. > Everything works fine but what I need is a way to show the user a dotted rectangle > as he drags across the mouse as in every other standard image editor. I have learnt > that using gnomecanvas will do that but given my time constraints and the lack of a > tutorial on pygtk ,I used gtk.image + event box to do the above. > >Can someone point to using gnomecanvas in the following directions: >1.Load an image into the canvas from file as well as pixbuf. >2.Draw a dotted rectangle >3.Fire and capture mouse events >4.Use PIL >I basically want to know about point 2. Also,will implementing cairo be easy on glade and pygtk? > >Regards, >Abhishek Hello, first of all I have no knowledge of pygtk. But after some googling I have found something that might help you: http://trac.bjourne.webfactional.com/ GtkImageViewer. It also comes with Python bindings. For the crop functionality, check the docs: http://trac.bjourne.webfactional.com/chrome/common/pygtkimageview-docs/ , there is a function ImageToolSelector (http://trac.bjourne.webfactional.com/chrome/common/pygtkimageview-docs/gtkimageview.ImageToolSelector-class.html) that can be customized to make an image cropper. Well, I hope my little finding can help. -- NOAGBODJI Paul Victor From sniipe at gmail.com Fri Jul 18 07:50:01 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Fri, 18 Jul 2008 04:50:01 -0700 (PDT) Subject: https in pylons Message-ID: Hello, I have a question about framework pylons - how to run(in paster) webpages over https? Is it possible, or not? Best regards From robert.rawlins at thinkbluemedia.co.uk Wed Jul 23 12:05:50 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Wed, 23 Jul 2008 17:05:50 +0100 Subject: Get dict value but not as reference. In-Reply-To: <16651e80807230855l745bba66u4c506e9fab5b38fa@mail.gmail.com> References: <4357936148771237039@unknownmsgid> <16651e80807230855l745bba66u4c506e9fab5b38fa@mail.gmail.com> Message-ID: <008f01c8ecdd$fa158120$ee408360$@rawlins@thinkbluemedia.co.uk> > Use the pop() method of the dictionary, like this: Ah, of course! Pop! I have seen this before I think Jerry, seems to do the trick nicely. Thank you. Robert From torriem at gmail.com Fri Jul 25 01:37:50 2008 From: torriem at gmail.com (Michael Torrie) Date: Thu, 24 Jul 2008 23:37:50 -0600 Subject: Doubt In-Reply-To: References: Message-ID: <488966AE.9040001@gmail.com> You wrote: > How to represent the loop > for ($a = $b; $a<=$c;$a++){ > } in Python As other pointed out, iterating through a list or range is often a far more elegant way to do a loop than a C-style loop. But the C-style for loop is just syntactic sugar for a while loop. In some cases, C-style for loops can have an initializer, a set of conditions, and incrementer parts that are all based on different variables. For example: for (a=begin_func() ; x < 3 and sometest(b) ; i=somefunc() ) This highly illogical and contrived function could not be represented in python with a simple "for x in blah" statement. Rather you have to represent it in its true form, which is a while loop: a=begin_func() while x < 3 and sometest(b): #do stuff #loop body i=somefunc() In fact, the perl/c for loop of the form: for (;;) always translates directly to: while : #loop body From norseman at hughes.net Mon Jul 7 04:03:10 2008 From: norseman at hughes.net (norseman) Date: Mon, 07 Jul 2008 01:03:10 -0700 Subject: How to bypass Windows 'cooking' the I/O? (One more time, please) II Message-ID: <4871CDBE.5050809@hughes.net> I know I saw the answer recently, as in since February '08, but I can't re-find it. :( I tried the mail archives and such and my own collections but the piece I saw still eludes me. Problem: (sos=same old s...) Microsoft insists the world work it's way even when the Microsoft way was proven wrong decades ago. In this case it's (still) 'cooking' the writes even with 'rwb' and O_RDWR|O_BINARY in (proper respective) use. Specific: python created and inspected binary file ends: 00460: 0D 1A (this is correct) after a write os.lseek(target, -1, 2) os.write(target,record) the expected result would be: 00460: 0D 20 .....data bytes.... 1A BUT I get: 00460: 20 .... data bytes... 1A It is one byte off!!! And the 0D has to be there. Signifies the end of the header. Same python program runs as expected in Linux. Maybe because that's where it was written?! :) What I seek is the way to slap Microsoft up side the head and make it work correctly. OK, well, at least in this situation. Note: Things like this justify Python implementers bypassing OS calls (data fetch, data write) and using the BIOS direct. Remember, the CPU understands bit patterns only. It has no comprehension of 'text', 'program', 'number', 'pointer', blah blah blah.... All that is totally beyond it's understanding. A given bit pattern means 'do that'. The CPU is 100% binary. Memory, storage and the rest is just bits-on, bits-off. Patterns. Proper binary I/O is mandatory for the machine to function. Anyway - if whoever mentioned the flags and such to 'over ride' Microsoft's BS would re-send that piece I would be very appreciative. Steve norseman at hughes.net ================================================================== Above is original request. I assume the answer I seek is by someone not receiving the list currently. I'm on and off myself so I can understand. I received two replies the the original request. Both insist on trying to use TEXT modes to do BINARY work. Allow me to explain before hooting and hollering that I'm all wet. Yes - 'rwb' is a typo. The compiler catches it every time I use it. READ as in read only, WRITE as in write only but NOT READ/WRITE in syntax when using STREAM I/O. One is to use r+ for rw and w+ for wr and tack on the b to eliminate the default of 'cooking' the data. File.verb is defined as being --- well a STREAM I/O handler. The docs insist on calling it a file descriptor somehow. Or at least that is the way it reads. Larry's 'fp' (file pointer) is a correct short form. Let's start with Larry: > You may be the victim of buffering (not calling .flush() or .close() > to commit your write to disk). Why aren't you using the file object > to do you seek and write? STREAM things take a great deal of overhead. I'm just reading, re-arranging and writing. (supposedly) Simple buffer stuff. > > Normal file I/O sequence: > > fp = open(target, 'wb') > > fp.seek(-1, 2) > > fp.write(record) > Except it doesn't do that in Windows. See below. > by going through os. methods instead of the file instance I think you > are accessing the file through 2 different I/O buffers. I could be > all wrong here. Nope (on 2 diff...) and You are but I can see where you might think as you do. Tim is my next victim: >>> f = open('x.bat','r+b') >>> >>> s = f.read() >>> >>> s 'sed -e "s/[ \\t]*$//" -e "/^$/d" %1\rhow about that\r\n' >>> >>> f.seek(-1,2) >>> >>> f.write('xxx\r\n') >>> >>> f.close() >>> >>> f = open('x.bat','rb') >>> >>> t = f.read() >>> >>> t 'sed -e "s/[ \\t]*$//" -e "/^$/d" %1\rhow about that\rxxx\r\n' >>> >>> If you put that in a binary file, that file will never work again. If you don't believe me, try it on ntldr and see what happens. (Tim - please don't. Your Window$ system won't boot if you do. Originally ALL STREAM I/O was supposed to 'cook' the stream for 'text' transmission. It has evolved, BUT.... legacy tends to linger.) This is the 'see below' place: concerning seek and write: let: 0123456789 be contents of a file. (offsets zero through nine) File size will be reported as 10 bytes If you seek to EOF and append ABC it will move to OFFSET 10 and put in ABC with a result of 0123456789ABC and report a file size of 13. With offsets it is simple math, quick and efficient. So move filesize minus 3 shifts to byte 10 which has a content of 9 This is correct and this is what Python on Linux does. (How many just got lost? Remember, byte 10 is offset 9) (or offset plus 1 is byte count) using ...seek(-1,2) (be it: os.lseek, file.seek, whatever - don't get dum on me) What Microsoft does is go to EOF and IF it is a hex-1A preceded by a hex-0D it then backs over the hex-0D also. If the last character of the file is a hex-1A and no EOL precedes it, it starts next write on top of hex-1A as it was told. Result: file is shifted left one byte. using ...seek(0,2) (os.lseek, file.seek, whatever - staaayy....) What Microsoft does is go to EOF and IF it is a hex-1A preceded by a line terminator hex-0D it then backs over the hex-1A and starts writing there. If the last character of the file is a hex-1A and no EOL precedes it, it starts next right after the hex-1A. Leaving the 1A in the file. Result: file data shifts one byte right for each record appended having a hex-1A terminator unless the 1A was preceded by a hex-0D. Fun Huh? BOTH CASES occur whichever I/O system is chosen and used. BOTH CASES are unacceptable behavior when the 'b' is added to the file use mode. Once in binary there is supposed to be no bullshit. In the mid 1960's I was updating code written in the early 1950's and my 0-9+ABC thing above was rule then too. Over half a century of legacy. Who's got the 'two by four' to pound Microsoft's nonsense switch into the off position? OK - the hooting and hollering that I'm all wet can start. :) Steve norseman at hughes.net From deets at nospam.web.de Thu Jul 17 02:00:04 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 17 Jul 2008 08:00:04 +0200 Subject: Is there any component-oriented (non-MVC) web framework available for Python? In-Reply-To: <5fdd1388-bb1e-4a59-8fd1-2aa1ce7fa6e0@79g2000hsk.googlegroups.com> References: <5fdd1388-bb1e-4a59-8fd1-2aa1ce7fa6e0@79g2000hsk.googlegroups.com> Message-ID: <6e85faF5le5kU1@mid.uni-berlin.de> Alis schrieb: > Hi > > Is there any component-oriented (non-MVC) web framework available for > Python? > > That is something like Apache Wicket, Tapestry or JSF, but I need it > to be in Python. ToscaWidgets, can be used with any WSGI-compliant framework. Diez From gagsl-py2 at yahoo.com.ar Tue Jul 15 00:04:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 01:04:21 -0300 Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> Message-ID: En Mon, 14 Jul 2008 12:06:30 -0300, Keith Hughitt escribi?: > On Jul 12, 12:52?am, "Gabriel Genellina" > wrote: >> En Fri, 11 Jul 2008 15:42:37 -0300, Keith Hughitt ? >> escribi?: >> >> > I am having a little trouble figuring out how to convert a python >> > datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would >> > like to create a UTC date so that when I send it to MySQL (which >> > treats all dates at local dates by default), it will already have >> > incorporated the proper UTC offset. I've tried looking through the >> > docshttp://python.active-venture.com/lib/datetime-datetime.html), but >> > have not had any luck. >> >> You have to use a "timezone aware" datetime object. If all you want is >> to ? >> store an UTC date, the tzinfo demo classes that you can find in the >> Python ? >> docs at may be enough. > > Thanks for advice Gabriel. I downloaded the tzinfo demo class, saved > it as > UTC.py and imported it. I'm still not exactly sure how to use it > though. It looks like > the file already creates an instance of the UTC tzinfo class (line 20: > "utc = UTC()"), > however, when I try to test it out in the interpreter, it cannot be > found. I'm new > to python, and there is probably something obvious I'm missing, but do > you have any ideas? The import statement in Python doesn't behave the same way as similar statements in other languages - and it may be confusing you. I'll try to explain it using this example. You have: - a *file* UTC.py, containing the source code for the *module* UTC. It contains: - a *class* definition (UTC) and - an *instance* of that class, utc. --- begin UTC.py --- class UTC(tzinfo): ... utc = UTC() ... --- end UTC.py --- > Here is what I'm attempting: > > ============ output begin ============= > > Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import datetime, UTC Here you have imported the *module* UTC. That is, the name UTC now refers to a newly created module just loaded from the UTC.py file. >>>> t = datetime.datetime(2008, 7, 14, 00, 00, 00, UTC()) > Traceback (most recent call last): > File "", line 1, in > TypeError: 'module' object is not callable The error comes from UTC(): UTC is a module, UTC() is attempting to "call" it, and since modules are not callable objects, we get a TypeError. >>>> utc > Traceback (most recent call last): > File "", line 1, in > NameError: name 'utc' is not defined The *only* name we have imported so far is UTC - the module. Lowercase utc isn't defined. >>>> utc = UTC() > Traceback (most recent call last): > File "", line 1, in > TypeError: 'module' object is not callable Same as above... Ok, how to solve it? We know that UTC refers to the *module* with the same name. To get the *class* inside that module, use UTC.UTC - try again in the interpreter. To create a new instance of that class, you can use UTC.UTC(). To obtain the instance already created in the UTC module, use UTC.utc **OR** Import those names explicitely: py> from UTC import UTC In this case the name UTC refers to the *class* inside the module. In this particular example it may be confusing - both have the same name. Another example from the standard library: the poplib module contains a POP3 class, so after executing this line: py> from poplib import POP3 the name POP3 refers to that class. The poplib module itself isn't directly available. Back to the UTC module, you could use: py> from UTC import utc and now utc refers to the *instance* already created inside the module. This last form may be the most convenient in your case: py> import datetime py> from UTC import utc py> print datetime.datetime(2008, 7, 14, 20, 30, 0, 0, utc) 2008-07-14 20:30:00+00:00 -- Gabriel Genellina From eckhardt at satorlaser.com Thu Jul 24 05:23:02 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Thu, 24 Jul 2008 11:23:02 +0200 Subject: Requires a character ... !! References: Message-ID: karthikbalaguru wrote: > [root at localhost hello]# Analyzer hello_input ^^^^^^^^^^^^^^ This is often a bad idea. Anyhow, that has nothing to do with Python. > Loading debug info: hello_input > Traceback (most recent call last): > File "/usr/local/SDK/host/bin/Analyzer", line 694, in ? > app.dbg.readObjectInfo(elf) > File "/usr/local/SDK/host/bin/debugprocessor.py", line 427, in > readObjectInfo > self.privateProcessorDwarfTree.readProcessorDwarfTree(filename) > File "/usr/local/SDK/bin/debugprocessor.py", line 314, in > readDwarfTree > if "DW_OP_reg" in value: > TypeError: 'in ' requires character as left operand > > Is this related with the version conflicts ? Which version conflict? Sorry, but my crystal ball is getting a new polish today, so I can't see the actual code that causes the error. I suggest that you reduce your code to the smallest possible piece of code that still shows the error and post it here, otherwise nobody will be able to help you. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From torriem at gmail.com Mon Jul 28 01:52:24 2008 From: torriem at gmail.com (Michael Torrie) Date: Sun, 27 Jul 2008 23:52:24 -0600 Subject: write unsigned integer 32 bits to socket In-Reply-To: References: Message-ID: <488D5E98.3080600@gmail.com> rkmr.em at gmail.com wrote: > thanks a lot!!! re-read it again!!! > > from the struct doc! > Standard size and alignment are as follows: no alignment is required > for any type (so you have to use pad bytes); short is 2 bytes; int and > long are 4 bytes; long long (__int64 on Windows) is 8 bytes; float and > double are 32-bit and 64-bit IEEE floating point numbers, > respectively. Of course any time you send coherent numbers over the network, I highly recommend you use what's called network byte order. In C, you'd use the htonl() call, and then when pulling it off the wire on the other end you'd use ntohl(). If you don't then you will have problems when the endianness is different between the hosts. Standard convention (even in the MS word) is to use big-ending across the network. I'm sure python has some convention in the struct module for dealing with this. From grante at visi.com Sat Jul 19 12:02:51 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 19 Jul 2008 11:02:51 -0500 Subject: Change PC to Win or Windows References: Message-ID: On 2008-07-19, Dennis Lee Bieber wrote: > On Fri, 18 Jul 2008 19:14:43 -0400, Derek Martin > declaimed the following in comp.lang.python: > >> On Fri, Jul 18, 2008 at 03:46:13PM -0700, Joel Teichroeb wrote: >> > Calling Windows PC seems to be something that Apple did so they would >> > not have to directly mention Windows. >> >> Actually it's something IBM did when they created the IBM PC. Of > > Bah... PC was short for Personal Computer... I had never heard PC or "Personal Computer" until the IBM-PC. Before that, such compturs were called "micro computers" > Which term applied to the TRS-80, the Apple II, Altair even... Not that I remember. I had a homebrew S-100 bus system, worked with varioius Commodore machines, a few Apples, and some other CP/M systems. I never heard any of them called a 'PC'. My recollection is that 'PC' was a term that IBM coined. > Being a computer small enough to be single-user ("personal") > vs a department-wide mini, or company-wide mainframe... I remember those being called microcomputers. A "PC" meant an IBM. -- Grant From michele.simionato at gmail.com Fri Jul 11 11:45:27 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 11 Jul 2008 08:45:27 -0700 (PDT) Subject: decorator to prevent adding attributes to class? References: Message-ID: <98c6e83e-4a54-49ce-a32e-f03f5ab97f28@k13g2000hse.googlegroups.com> On Jul 11, 5:29?pm, Neal Becker wrote: > After spending the morning debugging where I had misspelled the name of an > attribute (thus adding a new attr instead of updating an existing one), I > would like a way to decorate a class so that attributes cannot be (easily) > added. > > I guess class decorators are not available yet (pep 3129), but probably > inheritance can be used. > > Can anyone suggest an implementation? This article could give you same idea (it is doing the opposite, warning you if an attribute is overridden): http://stacktrace.it/articoli/2008/06/i-pericoli-della-programmazione-con-i-mixin1/ There is also a recipe that does exactly what you want by means of a metaclass: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158 It is so short I can write it down here: # requires Python 2.2+ def frozen(set): "Raise an error when trying to set an undeclared name." def set_attr(self,name,value): if hasattr(self,name): set(self,name,value) else: raise AttributeError("You cannot add attributes to %s" % self) return set_attr class Frozen(object): """Subclasses of Frozen are frozen, i.e. it is impossibile to add new attributes to them and their instances.""" __setattr__=frozen(object.__setattr__) class __metaclass__(type): __setattr__=frozen(type.__setattr__) Of course using frozen classes is not Pythonic at all, and I wrote the recipe as a proof of concept, not to use it. Michele Simionato From semanticist at gmail.com Sun Jul 13 16:35:45 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 16:35:45 -0400 Subject: heapq question In-Reply-To: References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> <487a3c0d$0$32256$9b622d9e@news.freenet.de> Message-ID: On Sun, Jul 13, 2008 at 3:05 PM, Giampaolo Rodola' wrote: > On 13 Lug, 19:31, "Martin v. L?wis" wrote: >> > I understand that heapq is not that efficient to implement timeouts as >> > I thought at first. >> > It would have been perfect if there were functions to remove arbitrary >> > elements withouth needing to re-heapify() the heap every time. >> >> It is efficient for that - you just need to use it correctly. >> >> To remove the nth element from a heap, replace it with the last element, >> and then _siftup that element: >> >> The time complexity for that operation is O(log(len(heap))). The problem is that in order to remove an arbitrary element from a heap, you usually have to do an O(n) linear search in order to find it first, since you can't know ahead of time which index an arbitrary element is at. (You can, actually, but only if your heap implementation somehow notifies the elements of their new index when it moves them in the heap, which the Python heapq module doesn't do, so you'd have to write your own heap implementation.) > And if instead of removing an element I'd want to change its value? > E.g.: > > >>> heap = [0, 2, 1, 4, 5, 6, 7, 8, 9] > >>> heapify(heap) > >>> heap > [0, 2, 1, 4, 5, 6, 7, 8, 9] > >>> heap[4] = 12 Don't do that; you must first remove the element and then reinsert it. -Miles From timothywayne.cook at gmail.com Thu Jul 3 16:05:31 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Thu, 03 Jul 2008 17:05:31 -0300 Subject: Instance Names In-Reply-To: References: Message-ID: <1215115531.2873.540.camel@localhost.localdomain> On Thu, 2008-07-03 at 14:20 -0500, Larry Bates wrote: > I suspect there is some "misunderstanding" here. Why exactly do you think you > need to have your instances named with [] characters in them? > I often misunderstand. :-) But, I am implementing specifications in Python that are already implemented in other languages. http://www.openehr.org/releases/1.0.1/roadmap.html These specifications say that an archetype node id consists of identifiers like [at0000] and [at0001]. Now these are valid URIs and the associated query language (AQL) used by other services will send queries with those characters in them. For example: FROM EHR [ehr_id/value=$ehrUid] CONTAINS COMPOSITION [openEHR-EHR-COMPOSITION.encounter.v1] CONTAINS OBSERVATION obs [openEHR-EHR-OBSERVATION.blood_pressure.v1] WHERE obs/data[at0001]/events[at0006]/data[at0003]/items[at0004]/value/value >= 140 Since I am also using Zope3 it would be easier on me to name the instances with those characters. But my fall back is to set at0000.__name__='[at0000]' and manipulate the query to match __name__ instead of the actual instance ID. Thoughts? --Tim -- Timothy Cook, MSc Health Informatics Research & Development Services LinkedIn Profile:http://www.linkedin.com/in/timothywaynecook Skype ID == timothy.cook ************************************************************** *You may get my Public GPG key from popular keyservers or * *from this link http://timothywayne.cook.googlepages.com/home* ************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From jonas at codeazur.com.br Thu Jul 3 23:34:38 2008 From: jonas at codeazur.com.br (Jonas Galvez) Date: Fri, 4 Jul 2008 00:34:38 -0300 Subject: HTTP request error with urlopen In-Reply-To: References: Message-ID: <10df03a30807032034w69370ec3s81395cf0854e5eec@mail.gmail.com> Try: import re import urllib2 url = 'http://www.google.com/search?num=20&hl=en&q=ipod&btnG=Search' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' headers = {'User-Agent' : user_agent} req = urllib2.Request(url, None, headers) file_source=open("google_source.txt", 'w') file_source.write(urllib2.urlopen(req).read()) file_source.close() I think Google blocks the User-Agent urllib2 sends. --Jonas Galvez, http://jonasgalvez.com.br/log On Thu, Jul 3, 2008 at 3:52 AM, spandana g wrote: > Hello , > > I have written a code to get the page source of the google search > page .. this is working for other urls. I have this problem with > > import re > from urllib2 import urlopen > string='http://www.google.com/search?num=20&hl=en&q=ipod&btnG=Search' > file_source=file("google_source.txt",'w') > file_source.write(urlopen(string).read()) > page_content=file_source.readlines() > > Traceback (most recent call last) : > File "C:/Python25/google.py", line 5,in > file_source.write(urlopen(string).read()) > File "C:\Python25\lib\urllib2.py", line 124 , in urlopen > return__opener.open(url, data) > File "C:\Python25\lib\urllib2.py", line 387 , in open > response =meth(req, response) > File "C:\Python25\lib\urllib2.py", line 498 , in http_response > 'http', request, response, code, msg, hdrs) > File "C:\Python25\lib\urllib2.py", line 425, in error > return self._call_chain(*args) > File "C:\Python25\lib\urllib2.py", line 360, in __call_chain > result = func(*args) > File "C:\Python25\lib\urllib2.py", line 506, in http_error_default > raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) > HTTPError: HTTP Error 403: Forbidden > > Actually urlopen is working for google labs sets page but not for the > google.com and even I have same problem with wikipedia . Please let me know > .. If any one of have any idea about this . > > Thank You, > Spandana. > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From josiah.carlson at gmail.com Thu Jul 10 20:31:41 2008 From: josiah.carlson at gmail.com (Josiah Carlson) Date: Thu, 10 Jul 2008 17:31:41 -0700 (PDT) Subject: Doubts about how implementing asynchronous timeouts through a heap References: <80430d47-aac5-4123-8835-0591faf0baed@34g2000hsf.googlegroups.com> <156ca6dc-2120-4107-9cc5-a05088ae1c63@27g2000hsf.googlegroups.com> Message-ID: <344ff89f-d8e0-468e-ba61-0438491b5496@56g2000hsm.googlegroups.com> On Jul 10, 11:30?am, Josiah Carlson wrote: > On Jul 9, 4:13?am, "Giampaolo Rodola'" wrote: > > > > > Hi, > > I'm trying to implement an asynchronous scheduler for asyncore to call > > functions at a later time without blocking the main loop. > > The logic behind it consists in: > > > - adding the scheduled functions into a heapified list > > - calling a "scheduler" function at every loop which checks the > > scheduled functions due to expire soonest > > > Note that, by using a heap, the first element of the list is always > > supposed to be the one with the lower timeout. > > Here's the code I wrote: > > > <--- snippet ---> > > import heapq > > import time > > import sys > > > delayed_map = [] > > > class delayed_call: > > ? ? """Calls a function at a later time. > > > ? ? The instance returned is an object that can be used to cancel the > > ? ? scheduled call, by calling its cancel() method. > > ? ? It also may be rescheduled by calling delay() or reset()} methods. > > ? ? """ > > > ? ? def __init__(self, delay, target, *args, **kwargs): > > ? ? ? ? """ > > ? ? ? ? - delay: the number of seconds to wait > > ? ? ? ? - target: the callable object to call later > > ? ? ? ? - args: the arguments to call it with > > ? ? ? ? - kwargs: the keyword arguments to call it with > > ? ? ? ? """ > > ? ? ? ? assert callable(target), "%s is not callable" %target > > ? ? ? ? assert sys.maxint >= delay >= 0, "%s is not greater than or > > equal " \ > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"to 0 seconds" % (delay) > > ? ? ? ? self.__delay = delay > > ? ? ? ? self.__target = target > > ? ? ? ? self.__args = args > > ? ? ? ? self.__kwargs = kwargs > > ? ? ? ? # seconds from the epoch at which to call the function > > ? ? ? ? self.timeout = time.time() + self.__delay > > ? ? ? ? self.cancelled = False > > ? ? ? ? heapq.heappush(delayed_map, self) > > > ? ? def __le__(self, other): > > ? ? ? ? return self.timeout <= other.timeout > > > ? ? def active(self): > > ? ? ? ? """Return True if this scheduler has not been cancelled.""" > > ? ? ? ? return not self.cancelled > > > ? ? def call(self): > > ? ? ? ? """Call this scheduled function.""" > > ? ? ? ? self.__target(*self.__args, **self.__kwargs) > > > ? ? def reset(self): > > ? ? ? ? """Reschedule this call resetting the current countdown.""" > > ? ? ? ? assert not self.cancelled, "Already cancelled" > > ? ? ? ? self.timeout = time.time() + self.__delay > > ? ? ? ? if delayed_map[0] is self: > > ? ? ? ? ? ? heapq.heapify(delayed_map) > > > ? ? def delay(self, seconds): > > ? ? ? ? """Reschedule this call for a later time.""" > > ? ? ? ? assert not self.cancelled, "Already cancelled." > > ? ? ? ? assert sys.maxint >= seconds >= 0, "%s is not greater than or > > equal " \ > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"to 0 seconds" %(seconds) > > ? ? ? ? self.__delay = seconds > > ? ? ? ? self.reset() > > > ? ? def cancel(self): > > ? ? ? ? """Unschedule this call.""" > > ? ? ? ? assert not self.cancelled, "Already cancelled" > > ? ? ? ? del self.__target, self.__args, self.__kwargs > > ? ? ? ? if self in delayed_map: > > ? ? ? ? ? ? if delayed_map[0] is self: > > ? ? ? ? ? ? ? ? delayed_map.remove(self) > > ? ? ? ? ? ? ? ? heapq.heapify(delayed_map) > > ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? delayed_map.remove(self) > > ? ? ? ? self.cancelled = True > > > def fun(arg): > > ? ? print arg > > > a = delayed_call(0.6, fun, '0.6') > > b = delayed_call(0.5, fun, '0.5') > > c = delayed_call(0.4, fun, '0.4') > > d = delayed_call(0.3, fun, '0.3') > > e = delayed_call(0.2, fun, '0.2') > > f = delayed_call(0.1, fun, '0.1') > > > while delayed_map: > > ? ? now = time.time() > > ? ? while delayed_map and now >= delayed_map[0].timeout: > > ? ? ? ? delayed = heapq.heappop(delayed_map) > > ? ? ? ? try: > > ? ? ? ? ? ? delayed.call() > > ? ? ? ? finally: > > ? ? ? ? ? ? if not delayed.cancelled: > > ? ? ? ? ? ? ? ? delayed.cancel() > > ? ? time.sleep(0.01) > > > > > Here comes the questions. > > Since that the timeouts of the scheduled functions contained in the > > list can change when I reset() or cancel() them I don't know exactly > > *when* the list needs to be heapified(). > > By doing some tests I came to the conclusion that I need the heapify() > > the list only when the function I reset() or cancel() is the *first of > > the list* but I'm not absolutely sure about it. > > When do you think it would be necessary calling heapify()? > > I wrote a short test suite which tests the code above and I didn't > > notice strange behaviors but since that I don't know much about the > > logic behind heaps I'd need some help. > > Thanks a lot in advance. > > > --- Giampaolohttp://code.google.com/p/pyftpdlib/ > > According to a quick scan, there is some inefficiencies with your > code. ?In particular, you don't need to re-heapify if the item you > need to remove is the first item; you only need to heappop(). > > In any case, if the Python standard library heapq module supported non- > lists as containers, then the pair heap implementation I wrote a > couple years ago would be perfect for this particular task. ?Because > of the rewriting of heapq in C, without a bit of monkeypatching, we > can't re-use that implementation (which offered insert/remove of > arbitrary entries in the heap in O(logn) time, which is significantly > faster than the O(n) time of your implementation). > > What I'm thinking is that we should add a pair heap implementation to > the heapq module (which can cache the pure Python functions if it > needs to use them), which would then allow us to use that (and others > to use it generally), add scheduling, etc. > > Regardless, it's a 2.7/3.1 feature, so it's ok if we take it slow. > > ?- Josiah Also...first I need to fix the unittest failures. ;) - Josiah From giveitawhril2008 at gmail.com Sun Jul 20 18:50:41 2008 From: giveitawhril2008 at gmail.com (giveitawhril2008 at gmail.com) Date: Sun, 20 Jul 2008 15:50:41 -0700 (PDT) Subject: Python Written in C? Message-ID: I'm just learning about Python now and it sounds interesting. But I just read (on the Wiki page) that mainstream Python was written in C. That's what I was searching for: Python was written in what other language? See, my concern was something like: OK, if Python is so hot, then, hopefully someone is writing it in assembly language for each MPU chip out there. Otherwise, if, say, they've written it in C#, then it looks like the REAL, generally useful language to learn is C# and Python is akin to Visual Basic or something: a specialty language....whereas REAL WORLD programmers who want to be generally useful go and learn C#. So I was suspecting the Python compiler or interpreter is written in a REAL language like C#. So, Wiki says it's written in C! It's almost as if it were an intentional trick...write your own, new language in an OLD, real world language that is passe. Compile it into executable modules of course, so it is a real, working compiler, alright. But the SOURCE is some old, high level language which no one wants to use anymore! So now you've got a hot new language package and no one can say "well, it is written in, the SOURCE code is written in, a REAL language." No, it's not! The source is some outdated language and compiler and no one is going to prefer learning THAT to learning your hot new language! I'm not dissing Python, here. Just noting that, if it is written in C, that throws a curve at me in trying to balance the value of learning Python vs. some other major language. From rtw at freenet.co.uk Sat Jul 26 15:43:09 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 26 Jul 2008 14:43:09 -0500 Subject: urllib and login with passwords References: Message-ID: Jive Dadson wrote in news:SvJik.317138$fz6.173226 at fe08.news.easynews.com in comp.lang.python: > Hey folks! > > There are various web pages that I would like to read using urllib, but > they require login with passwords. Can anyone tell me how to find out > how to do that, both in general and specifically for YouTube.com. > A typical pattern is submit a form to login and get a cookie back, subsuquent request with the cookie set are then "loged in". import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cj) ) page = opener.open( LOGIN_URL, data = LOGIN_FORM ) page.close() page = opener.open( DOWNLOAD_URL ) print page.read() page.close() You will need to work out what goes in LOGIN_FORM, it likely something like: LOGIN_FORM = "username=name&password=pass&submit-button=Some+value" where username, password and submit-button are the name of the controls on the form you would normally login from. If the form has an enctype='multipart/form-data' then things get a little more complex, possibly start here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 Rob. -- http://www.victim-prime.dsl.pipex.com/ From toby at tobiah.org Wed Jul 9 17:27:10 2008 From: toby at tobiah.org (Tobiah) Date: Wed, 09 Jul 2008 14:27:10 -0700 Subject: sort(cmp=func) Message-ID: I have a list of objects that generate code. Some of them depend on others being listed first, to satisfy dependencies of others. I wrote a cmp function something like this: def dep_cmp(ob1, ob2): if ob1.name in ob2.deps: return -1 else: return 1 I also tried returning 0 when there were no dependency relationships between the objects. This failed, because every object was not compared with ever other. I imagine that this is because sort assumes that if a > b and b > c, then a > c. In my case, this isn't really true. If a is not dependent on b, and b is not dependent on c, that doesn't mean that a is not dependent on c. Is there a better way? Thanks Tobiah ** Posted from http://www.teranews.com ** From callen314 at gmail.com Thu Jul 17 06:25:01 2008 From: callen314 at gmail.com (Craig Allen) Date: Thu, 17 Jul 2008 03:25:01 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Message-ID: <98eae1fc-ff34-4dcc-b46d-9e3da2850c28@r66g2000hsg.googlegroups.com> On Jul 16, 7:01 pm, Lawrence D'Oliveiro wrote: > In message > , Craig > > Allen wrote: > > ... the ideal is still that > > > tl = TehLibrary() would always return the same object. > >> class TehLibrary(object) : > > ... @classmethod > ... def __new__(self, cls) : > ... return self > > >>> s = TehLibrary() > >>> s == TehLibrary() > > True That's great, I simply didn't find that when looking. Thanks! From kyosohma at gmail.com Mon Jul 7 11:36:07 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 7 Jul 2008 08:36:07 -0700 (PDT) Subject: win32com extension documentation/API References: <996ff65c-8611-483e-90d6-3cf73b9e1496@25g2000hsx.googlegroups.com> Message-ID: <1fc3452a-8eca-4437-8322-5a7c10b14e48@f36g2000hsa.googlegroups.com> On Jul 7, 10:26?am, korean_dave wrote: > Hi. Where can i find the API for this extension? > > Sourceforge only has downloads. Python has stopped supporting the > upkeep of the versions. > > Thanks. I usually use ActiveState's docs: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/PyWin32.html http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/html/com/win32com/HTML/docindex.html There is a book on using the win32 modules that is still relevant by Mark Hammond. It's fairly pricey, but good. And there's also the PyWin32 mailing list. ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From mail at timgolden.me.uk Thu Jul 10 11:39:39 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 10 Jul 2008 16:39:39 +0100 Subject: Python / Windows process control In-Reply-To: <7b1097c5-7a8a-4bb8-b293-03d15aee98ed@m36g2000hse.googlegroups.com> References: <7b1097c5-7a8a-4bb8-b293-03d15aee98ed@m36g2000hse.googlegroups.com> Message-ID: <48762D3B.10205@timgolden.me.uk> Salim Fadhley wrote: > Does anybody know of a python module which can do process management > on Windows? The sort of thing that we might usually do with > taskmgr.exe or process explorer? > > For example: > > * Kill a process by ID > * Find out which process ID is locking an object in the filesystem > * Find out all the IDs of a particular .exe file > * Find all the details of a currently running process (e.g. given an > ID tell me which files it uses, niceness, runtime) As far as I know, the closest you're going to come here is WMI [1]. It won't do everything you ask, though. I don't know how to find out which processes have a lock on a filesystem object. When you say "Find all the ids of a particular .exe file" I assume you mean: all the processes which were started by running that file. import subprocess import time import wmi c = wmi.WMI () # # Kill a process by id # notepad = subprocess.Popen (["notepad.exe"]) time.sleep (1) for process in c.Win32_Process (ProcessId=notepad.pid): process.Terminate () # # Which process ids correspond to an .exe # for i in range (5): subprocess.Popen (["notepad.exe"]) for process in c.Win32_Process (caption="notepad.exe"): print process.ProcessId # # _Some_ (but not all) of the information about each file # for process in c.Win32_Process (caption="notepad.exe"): print process process.Terminate () HTH TJG [1] http://timgolden.me.uk/python/wmi.html From keithb at bailworthsolutions.com Sun Jul 6 06:33:08 2008 From: keithb at bailworthsolutions.com (Keith Bailey) Date: Sun, 06 Jul 2008 11:33:08 +0100 Subject: Python / WxPython error message Message-ID: <48709F64.3040707@bailworthsolutions.com> Dear All, Any help on this would be hugely appreciated. I have had a Python programme written for me, but when I try to run it, I get the following error message: /*Traceback (most recent call last): File "iTeddyConverter.py", line 3, in File "zipextimporter.pyc", line 82, in load_module File "iTeddyConverterPanel.pyc", line 4, in File "zipextimporter.pyc", line 98, in load_module ImportError: MemoryLoadLibrary failed loading win32file.pyd*/ I hav etrawled through the net trying to find a resolution but nothing works. I tried putting the DLL msvcp71.dll in the system32 folder but that made no difference. Please help if you can. Thanks Keith From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 3 03:11:45 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 03 Jul 2008 09:11:45 +0200 Subject: Times where one would use new style classes vs classic classes In-Reply-To: <6700e4ba-8573-44da-b75a-3b3e5ba1fd9b@i36g2000prf.googlegroups.com> References: <6700e4ba-8573-44da-b75a-3b3e5ba1fd9b@i36g2000prf.googlegroups.com> Message-ID: <486c7ba7$0$10446$426a74cc@news.free.fr> Quek a ?crit : > Hi all, > > I'm really new to Python and I've been reading up some texts on older > versions of Python (2.2 to be specific). > > The text briefly mentioned new style and classic classes. > > I'd really like to know in the current context of Python 2.5, besides > in the cases of multi-inheritance, where would I use new style > classes? Everywhere you don't have to support compat with ages-old versions of Python. MI is not the main point of newstyle classes (FWIW, you can do MI with old-style classes too), they have quite a lot more to offer. Consider "classic" classes as a legacy feature, period. From frank at chagford.com Thu Jul 17 05:57:32 2008 From: frank at chagford.com (Frank Millman) Date: Thu, 17 Jul 2008 02:57:32 -0700 (PDT) Subject: Question about properties Message-ID: Hi all I have started experimenting with properties. The example in the 2.5 docs uses an inconsistent mixture of single and double underscores for the internal representation of the attribute. I was going to file a documentation bug, but then I checked the 2.6 docs online, and I see it has been fixed, by using single underscores throughout. IMHO, it would make more sense to use double underscores throughout. I thought that the main point of using property was to prevent direct access to the attribute. With a single underscore you can access it if you prefix the attribute name with a single underscore, thus bypassing the logic in 'property'. Is this a valid comment, or does it come under the category of 'we are all adults here'? While experimenting, I came across the following curiosity. I know that prefixing a class attribute with a double-underscore makes it difficult to access the attribute externally. Here is a simple example - >>>class Test(object): ... def __init__(self,x): ... self.x = x ... self.__y = 123 ... def get_y(self): ... return self.__y >>>t = Test(99) >>>t.x 99 >>>t.get_y() 123 >>>t.__y AttributeError: 'Test' object has no attribute '__y' I was surprised that I could do the following - >>>t.__y = 456 >>>t.__y 456 >>>t.get_y() 123 It's not important, but I am curious to know what is going on internally here. Frank Millman From lxz3002 at yahoo.com.cn Wed Jul 16 22:04:45 2008 From: lxz3002 at yahoo.com.cn (Leo Lee) Date: Thu, 17 Jul 2008 10:04:45 +0800 Subject: wxpython: visual effects missing after py2exe Message-ID: Please take close look at the details of the two snapshots. I need explanation and correcting this problem. begin 666 after.png MB5!.1PT*&@H````-24A$4@```;0```#-" ,```#GL'7)`````7-21T(`KLX< MZ0````1G04U!``"QCPO\804````@8TA230``>B8``("$``#Z````@.@``'4P M``#J8 ``.I@``!=PG+I1/ ```P!03%1%````$S=X<6]D"AB#`!BK`!J\$CJ* M$CR)$CR*`"2F`!G/`!K/`!_2`"#(`"/6`#+!`#'&`#?+`#W,`#;2!S'8!S3: M`#O2`#_2`#C8`#W<"#'8"#'9"33:`#O@`#OB`$Z8%D"1`$'*`$//`$O-`$[( M`$_+`430`$?7`$#<`4S0`$K8`$K<`4W<`E#(`E'*`U#,`E'-`E3/`E;.`%/: M`EC2`%K?"%7=`$;D`$;J`$O@`$OG`$WC`$OK`%#@`%#B`%/A`%'E`%3C`%7E M`%'K`%7J`%CF`%KD`%KG`%[G`%GH`%CK`%CN`%SI`%[I`%SL`%OR`%KU`%_R M`&O+`&K/`&W/`&_/`&;8`&O1`&W1`&[0`&[1`W+2!7'1`'+8!G?:"GC5"7C: M"'G;#'K;#7O<#GS<$GW;%7_<`V#G!F?E!6;F`6'J`V/H`&+I`F#L`&#N`67K M`&?M!F3I!F?J!FGF!FGK`V#Q`6#U`V'V`V7Q!F?T`&#Y`&#\`63Y`&7]`&GR M`VCT`FSQ`V[U`VCZ`6KZ`VO[`FK^`V_Z`6S^`V[^`V[_!FKY!F_Z!FS\!V_] M`'OG`'/]`W+_!G'^!W+]!W3^%FKN$WK_&H+_-XW4(X7_(8G_)XW_*Y#_,8S_ M,93_.I'_/97_/Y?_0)?E1*+V:YO5:IS7;9G0:)[;_B___Y___Z___[___\ M___]___^____```````````````````````````````````````````````` M```````````````````````````````````````````````````````````` M```````````````````````````````````````````````````````````` M```````````````````````````````````````````````````````````` M````````````````````````````````````/^X!3@```!AT15AT4V]F='=A M%[MG8M_%4<5Q]>D1:4H MMKZM6 L*!E#16%&14"*/$$)"U/JH5EN?):4DVI)8##8-C;44"DEL:Q\4W^^F M4 at VONO^;\]C9G=V[]^[,W#UU)O=W/DGN37+V[-G?=\[,W)W)370;MPT]/9LV M;=Z\>>>N?0/[!L8.[1\Z-#0T--B9=M![BQBRGIY'%IYY]MG?O/#2A9=?OGCQ MM\HN=J:EU^_M$P:M9^B1F<5G&+7GGW_A1687+ES@#S!O%8ANN[VO=WQ\8F)B MYK%?+IX[?W[QW")[6#QW;G%^X3S,2P48M UW,!LX.CXQ,S/SF+*91YG]#$:B M0-1FU&CME at V]O;V<&L,V,?$+9NQA8OS8L6/#G6EL"D9L4=3>":*U:V_O4=#& M13\Y,3Y^=.S0H:']^_?"2!2(XJBMN-%;);1]O-*$'67$!@;V)6U$Q?'ME" 06N+&H>VJ?>.[_[H>_?= M]_T?_/#>>^_YSCU/?TUVC1U99_W]].V-0VN'6G3#.]Z[>>?N+W_]F]_XUK?O M_NK==_WN*[__YUT?[=S.\8UHJ0):'#F?*H'VGTNO,;MTZ;5+K_[KU7\_]Q% MR"^PHM,V1^W/3@\R(J-0^O>PS]A M=2J at QK2(F4OX8-9'/,'\70$5I,"[-[CR BGYA at O6K-N^Y[AT5AC=O7Z M7SXU-34U.V)$[R7[#X!JTN!2 3BU-PB,FA?&!R=_/"J5:O>PNS-PM[TF;E3ITZ> M[$YL>IH]X1AA=2K H;G%B]9\Z(L'1R(.,A4 at 3:A34[- MSIXY>W9!0LNH<7(=9Z::M^\7N17:G*BT$59JT[.G!;:%>6:RTMK/"A%(%(AN M6L>@'1PY?GSJT=G3IT^?.7/F<6ES<[.=:2>]-PYMQ^Z]>P>'CXVRC5U\X]SL M*6$GIZ?=)J2A'_5S[XU!6_?Y6]9OW+B1;>7?NG7KSAU]?7V[V&=?WPZ8IPH( M:.O7^+/\H[K.3OF!J>6[3ZW;_^[#(L* 4`+2A<,EE `[0`%0 at P950: MH 6H0( I:Y7&MYE$?)CCG^)9HR4NN5^4>P:H13 IZ]TC4S\#T 1%SB>8JUQA MB>:A::0`S5_2.6BR=Y2XDJ]%=DFE<2?>A6%-Z!Y@<$N"4"ST\L+;P%-_:D%'L-00$![!1:4`M'J M#P):4,18LH 6&C% "Y"8#FUYV7P0]F(*U<%)I-WCIR[PJI2>/;7:,G:=YSBO)TQ&:<5$FCJPV#2O9RG,ED;"X%D=H%F<0KJPV M#2O9QM,VBY7B#V@!DFR EJQ&J^67TF68)>N9B$W]F-=D@'K7DG(5M-*3M(:6 M<,[ASD%KN1Z7>5:MV]DWG5H4\R!((S2YL2K9(B>>-2Q[ELM5*$X#:&7T4FB5 M2ZV ]HKJE"0OM>U1(&-M*Z]@794&:&YEVZ+2!"M]FUQZ!@DM at 9GNIM.*4VZP M$]N#Y$%9_M=;TV`:T1FA),Z%3:/:I.-"G'%%K"3MO*FE:: M%BS%G(^NCVF)=_Z at 0KV[=3!A'U72/:J"J>H>%2O1C4FPLDM+H65;MXJ5EG22 MPC,_SVD!K<$S;.G=LV\.31&HJ+2L!U/H,FB-G9Y6.TFE%:KI?=MA' MMG5'1,FHX](K+>M8]4K3"C/I>/,CE3:FJ9H5PQN at J:;6-K2L2TR[Q[3O*Y\] M:O-*M0-=:_BY2M,VI^M?"NZ?=,Q:9 A^$2K;Y6[L7R$UEI 0 .T$$HLR=&QTLRV#L"+1@$G:,O+ MMML-X%^G`CEH-;<+Z^T_%>?W/5X=\G4M&5@>6IW-X3*?,=9IOL>KXUJ7NI:Z MJJT`K<[1V'R:;W96W^.97475C-AD>R*@U:%U;3%XI57WLBL#6N/M$@,9ZZY< M at U-6NCA#2_=C:>]+X:)*?@U:SU=%T]Z'I/)RLM7ODK_5=TDO6^/+!70*99"] MF4L-T.2)2M9FC#(H6:U6+P[5HU7HYO$*:[1&V6F-(."-+MZ&T!I"+I[:\),NX:430 M1-'F]G85EDTK-"C=9Y(VK$1A;3E/=1+-PA:@:9LF%*XWGEH-T-+=`TZMKKG( MZ9B6;.\QZR5;0LM":HOCK;O-W)@KUM&S15UM8*B_G%I$; -:LKE*[QX=&EUQ M(J)O(,E$:;)+K^3"FL?3WG,RJ[22^4H^:+'2LL%;'EOI_A"9:FNIN^XV 3SZ1CLXE7ER95<9S'M*K IK^O6Q33 M>)4EEER :3S3ZZW#SP6:P5J.A4M7;.%LX.I[/(-+J'0QO&'\KFQC3_5*#CRH M%3"[RZ]!JUX4@ >U`H!&K3!!?$ C$)4Z)*!1*TP0'] (1*4."6C4"A/$!S0" M4:E#`AJUP at 3Q`8U 5.J0@$:M,$%\0",0E3HDH%$K3! ?T A$I0X):-0*$\0' M- )1J4,"&K7"!/$!C4!4ZI" 1JTP07Q (Q"5.B2 at 42M,$!_0"$2E#@EHU H3 MQ $M%0`T"P% M\\$=T'R at 8)D#H%D*YH,[H/E P3('0+,4S =W0/.!@F4.@&8IF _N at .8#!GDE1>@>87#+!E ,]/) M*R] \PJ'63* 9J:35UZ YA4.LV0`S4PGK[P`S2L<9LD`FIE.7GD!FE>4%:%[A,$L&T,QT\LK+#!K>9 at G0O%(@P&10:8 6 MH (!IHQ*`[0`%0 at P950:H 6H0( IH](`+4 %`DP9E09H`2H08,JH-$ +4($` M4T:E`5J "@28,BH-T )4(,"446F %J "`::,2 at .T`!4(,&6S2KL5__3.)[: CYA,-PUP`S5 HG]Q,H/T/?S'YF:RO\Y `````245.1*Y"8((` ` end begin 666 before.png MB5!.1PT*&@H````-24A$4@```:(```"M" (```!]2.Q9`````7-21T(`KLX< MZ0````1G04U!``"QCPO\804````@8TA230``>B8``("$``#Z````@.@``'4P M``#J8 ``.I@``!=PG+I1/ ```!AT15AT4V]F='=A%[MG7^,'-==P.=NZ=F-@#]2$97^`ZA(_ &J9 0D M;1PU50M(#2V)TJ T25NGK1OGDCB*@T32 at AJ!^*.%("P5#$H`M4@@X#^H2BT0 MB(HV;A+W[*--S^=S[=B^\_WR^>Y\=NR[O5N^L^_NW;LWL[.SL_-VWNQ\5E^M MYF9GWON^SYOWV??VQ^U \-&_"LS;^J\.#-1D1V-M5[B[-K#YX-#N<'M7+?BQ M6E!?E_N!6JVQW at CJ&\'@8# 8!!M;I=3E#VX0Z&\"X1CA5AX"HKEF#/S6"8FA MQU9V'5I_Q^<;[_K#,-[]QXU?>+&QYT\;>[[2>-_A,.[ZBS#>?Z1EJ ,("/0Q M at 83KGX<\)!!HQPU^8D8<-_CDTJ[?W1#-:=/]W)<:$B*[7_SS[1#KJ3!WL at T! M"$# 0P)-S7W at U>#>\\']XP/[YR2"QRZK$.75#EZK/;TJX at N>7:\=:DBH;;G7 M.]6&VCGTS(9,!M61! 0@``$?"&QI[I[CP4-GM^.3EX)/SRCEB>Q4A,IK$>&C M!U:V8_]2C8 `!"#@!X$@^.7_"3X\$8CF[A_?#.6[INFT[#:G>(\O!SJV)GWR M4"C$?0N;\"GOCCQXY\__?;G3^]^_O1/?&'B M)W]_XM8_.'W+\^.[GQL/#HT-_=YX\.Q8\(5+P>?&8A:J??P<3M, at H A400W] MU,90.)D#IT;"^Z=' M[CXR&0R/?.AKU]>'WR-_!K_]&LM55N at 0@(#7!**:^][9B:.CIX[^W_C1T?'P M/HQ3X1[Y<_34-T;&_OWDJ:^/C/WSZ(7;7_Q^\-%C:,[K#F;^!0$(!._ZS^#V MUX([938W$=S_IHS81GA;31&-3__]^5:::Q;2L,:_VAG[$*: ``0 at X(I J+E? M&PWNG@@U)RO63N-QH;8:O_7S@[>]VKP\>G-4)\C:3YU*)?= M\LX_TGGK/=&'7+6-)S$(0 `"0F"'YN[3AA*CU1N-M<0Y7>/ WYZNW7>\]@GY M//",:;KHK$VK38E/[DT#HCD(0 `"#@EL:TZ^UBISL8]/-Y6D)F[1"=V.^=WP MRS_Y1S2W8SV[=;P^D0T(0 `"^1,( M?F8TN&LBG,W)"W7;FI-7Y>2UN3:SN6?^\O5!>6WNT>L#^ZX%#S7CX67S9;C- M-U6-G=8!FWY4EB0@``$(N" 0:N[.+_7C"_=NG='O./VYP8?'!TFQQZ?"J,QR;?]KDI%;6#&[6#C8$G-R3$=P0$( `!WPC(QX-'M.;$ M1YK^WW_RUFO#K$.$O M=7UJ>?NG",V?*#P0OK5JA;19O6/B]KUA/H,"@>()U(-]1'D(;&HNG-"=DU^$ M"#XX,O"A$_*[$.%/0\C_$V[&P$FNBK7$J"Y*G<_ M;2^0 at -(ZZ7RG??P*FYC"=T_Y"'HH]FRS6V MHI1%\7952E . M2*NYMA9K>T":U-%<&DH5TPJ32GK&'UD)5!JP,ZZJJH MYM+L24 at OX?2\"%(.!+(1,#6GMSL:+]GJK>!9:367++58T43G4VWYQEK)*D<= MDZS=5E/+V'E?VZPX``(N")AJ0W,N"!L+T';?:8U]>FF[:,WVI)1R\A6U5:>3 M3:=,*1P":0 at HM9G7/-_]2L,MPS%I/U!BK5A-T;1Z-:'3V9Q93D)U"3/'MF;ZB at RFS7 30G(O^ M0G-H#@)^$>"-LMQ-MT-SZN5/;A" ``3ZB< .S;W #0(0@$#?$0 at U]_:MG[SI MN];1( A ``(OH#DN`@A H,\)H+D^[V":!P$(M-33^M at L%0@`"E2+04G/BN(6_VW/SZ!V-8WL+B;7_>J\D(&E4 MJC]H+ 0 at D#N!EIH[\]7[;W[SCL8K>PL,24#2^*>C_WWX'[_N0WSUW_[CV,GC M,L%4<>*-$[W,K<#:K:ISOPHI$ ).";34W.&77J[7-PH/2>/BS+PG'^&YO'3U M&_][7.RF'"?;OF I' 7!$J at N0V/;NL79N9D!B=#7>XOS,SW M-K4":]^N&LVY&(>4Z91 "32WOEYOWM8*C[6UU>LKR[)\EJ$N]Y)8+W,KL':S M:C3G=$!2N L"'6M.?>'.7,Q&]^A'K2,S+(%ET;JZ>M./N'%M97EQ859K;C6\ M]2RW`FO?436::R^ UZQ31W(T;UW,/\6^TS-B=^K"WWKIV=6GA M\NR4UMR-&V\E))9<6JLKIM/#DXZVJT9S3`4GA+ at ADT9R82$_3U(;Y MISFY,Q_5_S6S(_>)YJY?7[E^_6JVD$IC3XS=W^I at 5<*U:\M+BW-ST^>UYIJ) MMH_5;A^F"SNI65 MQ<4K,[.7SAF:D\2VV:C3G8AQ2IE," M&36G%JIZ7F9NZ-&E%[/6]*W3V5Q;S5GBBS57PC':AI89+?>E$8WI"%.148W& M&BUZBCZL;>U1IT>;G#(]*S>K:C3G=$!2N L">6K.])?:-N^SO?W:G,TMR4C3 M(67*MKJW(OI0]+#8T\V=UBGZSZM7KUQ9F)Z9VI[-*1U8B;7ZT\PY-OE6C5(% MMJT]H?R$)D?!1JE:5:,Y%^.0,IT2R*ZYZ#K4D>;4(-B#[4] M1I^B2S8+U!4M+R\L7+XT/1E^8DY];DX+2%<1S3.:GI5A[ %F.6J[;>UFL28< MJW46QC2U6U6C.:<#DL)=$,A34/?FAM[6#Z7< M8QUFGF[6N[Q\>>'RU/3DCPS-73%SLTZT\DS..=H6LVK9;EM[J_)C(220L>J- M5HWF7(Q#RG1*H&/-I7_W()TZ?W-#G1N;24)Z5@)6U6C.Z8"DIDI^\U'];:Y#E7'6'O,$Z,/R:.+B_/S24M4<+M&CH>M/7;E6-YER,0\IT2J 4F at OG,H7' MXN+<_-S%J0L3>C:GYUD]R*VCVIL*:T,LS3&J$*MJ-.=T0%*X"P(ET)P::87' ME2LS<[,7)L^?UIK3%NA!;AW5+ at J+3/&SYWYOM:<)-.;W'I:#B[\B90$(% X`327@[!>^?:_RG-%X7W9LP1H M;\]04U&7!-2UBN;07,<$T%R78X_3>T8`S74\O%OU#<,^KZM6OG&15U$YEE.U M_LT17>%%%:DY]?TA$X'>8WT]7A]C[B^?'TN"Y_-1<%$75BCV$E5Y=FV%M.3Y-_J367H;VEUER: M#O6V at 2F3+^-A!6O.['(UGLW[;(.DJ&[(K#D]"U"96QRL1\V)K35 at M!![,^?- MJ[VJ%68S3;-'&Q4[M>]!VSMMK]F;5L]&&YO0S**NYWZJ%\WU[K6YMK-1+;C8 M<6Y==M'G@]AG"'?KHTZ'?323MD]IL:< MZZ_FDI_AU:->]5^GPR#EL&_53//Y/SH-M,:8"U".VILPHV_;S,(U9UZT5@>U M>NIJV[\N^JYJ91:O.>L)K>TS? \&<+:+(,VPM]RMQVVK)9NU+&VUBC>A.1WJ M9@*.VMMJ at I/PM&>:,58TV3K4.BM->UM5E- IT8?,BR&7S"D$S16V:#7G)FWG M*@S=YJ9G=.V5$U\7F at N^1)O-7WS[3K( M- at RB5WS*Z5CL+" Z^XNN;?.ZQ!VUUVQ";/*QUHA=!.1[A61K;^P:',WE=1&F M+*=,FM/+&3]G]=T, at X1%:\(BSGIZ,*40193OF)>J\VJOU:V6J1,:%0O-6MNF M' 9I#DO3WNB2.<%HK=3LY^6=!I&WQQ2I.6^A9$NL[3#(5JRW9WG5WMPE'L7N M57N]O2K\3 S-Y?;:G)\=W,=9N9NX]3&T*CD% @!"/A%`,WYU1]D`P$(Y$X`S>6.E (A``&_"* YO_J#;" `@=P)H+G< MD5(@!"#@%P$WFEO;J*]M^-50LH$`!*I*`,U5M>=I-P0J0P#-5::K:2@$JDH` MS56UYVDW!"I#`,U5IJMI* 2J2@#-5;7G:3<$*D,`S56FJVDH!*I*`,U5M>=I M-P0J0P#-5::K:2@$JDH`S56UYVDW!"I#`,U5IJMI* 2J2@#-5;7G:3<$*D,` MS56FJVDH!*I*`,U5M>=I-P0J0\")YM;6UB4JPY"&0@`"7A- P)HKGN&E `!"'A-`,UYW3TD!P$(=$\` MS77/D!(@``&O": YK[N'Y" `@>X)H+GN&5("!"#@-0$TYW7WD!P$(- ]`337 M/4-*@ `$O": YKSN'I*#``2Z)X#FNF=("1" @-<$'&FNOK96][K=) MYGSO(?*#``2Z)(#FN at 3(Z1" @.\$W&ANM;ZV6O>]Z>0'`0A4 at P":JT8_TTH( M5)@`FJMPY]-T"%2#0';-[4KX92\6K=6X>F at E!$I!`,V5HIM($@(0R$X`S65G MQYD0@$ I"*"Y4G0324(``MD)H+GL[#@3`A H!0$T5XIN(DD(0" [`327G1UG M0@`"I2" YDK1320)`0AD)X#FLK/C3 A H!0$T%PINHDD(0"![ 307'9VG D! M")2"@!/-K:ZN292B_20)`0CT/0$TU_==3 ,A4'4":*[J5P#MAT#?$\BFN?\' 4/X>GA=<>(=D`````245.1*Y"8((` ` end From torriem at gmail.com Mon Jul 28 01:24:27 2008 From: torriem at gmail.com (Michael Torrie) Date: Sun, 27 Jul 2008 23:24:27 -0600 Subject: Attack a sacred Python Cow In-Reply-To: <20080727193416.GE7373@dragontoe.org> References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c29cc$0$20302$c3e8da3@news.astraweb.com> <20080727193416.GE7373@dragontoe.org> Message-ID: <488D580B.9050001@gmail.com> Derek Martin wrote: > Regardless of how it's implementd, it's such a common idiom to use > self to refer to object instances within a class in Python that it > ought to be more automatic. Personally, I kind of like the idea of > using @ and thinking of it more like an operator... Kind of like > dereferencing a pointer, only with an implied pointer name. > > class foo: > def __init__(): > @.increment = 2 > > def bar(a) > return a + @.increment > > I'm sure all the Pythonistas will hate this idea though... ;-) To be > honest, it smacks a little of Perl's magic variables, which I actually > hate with a passion. This is the only place in Python I'd consider > doing something like this. I think the biggest reason why an implicit self is bad is because it prevents monkey-patching of existing class objects. Right now I can add a new method to any existing class just with a simple attribute like so (adding a new function to an existing instance object isn't so simple, but ah well): def a(self, x, y): self.x = x self.y = y class Test(object): pass Test.setxy = a b = Test() b.setxy(4,4) print b.x, b.y If self was implicit, none of this would work. Now this contrived example is not useful, and maybe not even correct, but I have patched existing classes on several occasions using this method. How could python retain it's dynamic nature and still have an implicit self? How would the interpreter know when to add the self variable and when not to? From wuwei23 at gmail.com Thu Jul 24 05:47:10 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 24 Jul 2008 02:47:10 -0700 (PDT) Subject: Requires a character ... !! References: Message-ID: On Jul 24, 7:33 pm, karthikbalaguru wrote: > Kindly let me know a trick to make to resolve > the 'in' operator related problem by using Python 2.2. You seem to be making life -very- difficult for yourself. Your distro is running Python 2.4, you've gone out of your way to get Py2.2 installed. Why are you so convinced that you -need- Python 2.2 over 2.4? Everyone problem you've posted here seems due to that assumption... Generally, Python is pretty good about backwards compatibility. Code written for 2.2 should run fine under 2.4. As you're discovering, the opposite isn't true. __future__ isn't a cure-all. From cito at online.de Fri Jul 11 07:55:05 2008 From: cito at online.de (Christoph Zwerschke) Date: Fri, 11 Jul 2008 13:55:05 +0200 Subject: strip() using strings instead of chars Message-ID: In Python programs, you will quite frequently find code like the following for removing a certain prefix from a string: if url.startswith('http://'): url = url[7:] Similarly for stripping suffixes: if filename.endswith('.html'): filename = filename[:-5] My problem with this is that it's cumbersome and error prone to count the number of chars of the prefix or suffix. If you want to change it from 'http://' to 'https://', you must not forget to change the 7 to 8. If you write len('http://') instead of the 7, you see this is actually a DRY problem. Things get even worse if you have several prefixes to consider: if url.startswith('http://'): url = url[7:] elif url.startswith('https://'): url = url[8:] You can't take use of url.startswith(('http://', 'https://')) here. Here is another concrete example taken from the standard lib: if chars.startswith(BOM_UTF8): chars = chars[3:].decode("utf-8") This avoids hardcoding the BOM_UTF8, but its length is still hardcoded, and the programmer had to know it or look it up when writing this line. So my suggestion is to add another string method, say "stripstr" that behaves like "strip", but instead of stripping *characters* strips *strings* (similarly for lstrip and rstrip). Then in the case above, you could simply write url = url.lstripstr('http://') or url = url.lstripstr(('http://', 'https://')). The new function would actually comprise the old strip function, you would have strip('aeiou') == stripstr(set('aeio')). Instead of a new function, we could also add another parameter to strip (lstrip, rstrip) for passing strings or changing the behavior, or we could create functions with the signature of startswith and endswith which instead of only checking whether the string starts or ends with the substring, remove the substring (startswith and endswith have additional "start" and "end" index parameters that may be useful). Or did I overlook anything and there is already a good idiom for this? Btw, in most other languages, "strip" is called "trim" and behaves like Python's strip, i.e. considers the parameter as a set of chars. There is one notable exception: In MySQL, trim behaves like stripstr proposed above (differently to SQLite, PostgreSQL and Oracle). -- Christoph From 1x7y2z9 at gmail.com Thu Jul 17 15:58:56 2008 From: 1x7y2z9 at gmail.com (1x7y2z9 at gmail.com) Date: Thu, 17 Jul 2008 12:58:56 -0700 (PDT) Subject: decorating a method in multiple child classes Message-ID: Say, we have a (parent) class P. It has N child classes C1(P), C2(P) ... CN(P) Each of the child classes defines (differently) a method func(). I wish to decorate all of the CX.func() in the same way. One way to do this is to add a decorator to each of the derived classes. But this is tedious and involves modifying multiple files. Is there a way to modify the parent class and have the same effect? Or some other way neater than the above? Thanks. visual: class P(object): ... class C1(P): def func(self, ...): ... class C2(P): def func(self, ...): ... From atulskulkarni at gmail.com Mon Jul 28 12:28:38 2008 From: atulskulkarni at gmail.com (Atul.) Date: Mon, 28 Jul 2008 09:28:38 -0700 (PDT) Subject: Encoding for Devanagari Script. References: Message-ID: Thanks, Tim that did work. I will proceed with my playing around now. Thanks a ton. Atul. > > Only slightly. You're importing the codecs module > but you're not using it. So you're *actually* using > the built-in open function, which doesn't have an > encoding parameter. It does have a third param > which is to do with the buffer size. > > Just change your code to use codecs.open ("...") > and, I suggest, either use raw strings for your > filename (r"c:\docume...") or use the other kind > of slash ("c:/documen..."). Otherwise you might > run into some problems. > > TJG From fredrik at pythonware.com Mon Jul 21 03:26:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 09:26:50 +0200 Subject: running a script with an input file In-Reply-To: References: Message-ID: David Bikard wrote: > I'd like to run a program so that it reads the input() or raw_input() > statements from an input file instead of > reading from keyboard. I'd also like it to write the print statements in > an output file rather than on the screen. > > I'm on windows XP and when I run: > > prog_name.py input_file output_file > > I get an EOF error. > > What should I do to make this work? Was that supposed to be prog_name.py output_file ? (< and > does i/o redirection; random google link: http://www.ss64.com/ntsyntax/redirection.html If you want to do the same thing from inside the program, you can do: import sys sys.stdin = open("input_file") sys.stdout = open("output_file", "w") before you start reading or writing stuff. From no-spam at no-spam-no-spam.invalid Sun Jul 6 08:40:06 2008 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sun, 06 Jul 2008 14:40:06 +0200 Subject: Hands-on HTML Table Parser/Matrix? Message-ID: Often I want to extract some web table contents. Formats are mostly static, simple text & numbers in it, other tags to be stripped off. So a simple & fast approach would be ok. What of the different modules around is most easy to use, stable, up-to-date, iterator access or best matrix-access (without need for callback functions,classes.. for basic tasks)? Robert From javaboy.ms at gmail.com Mon Jul 21 09:31:40 2008 From: javaboy.ms at gmail.com (sahasranaman) Date: Mon, 21 Jul 2008 06:31:40 -0700 (PDT) Subject: Odd math related issue. References: <43332.3139710867$1216630189@news.gmane.org> <48847F5D.9080509@sellerengine.com> Message-ID: <6472d2d2-1f0e-44af-8bdb-b7e475080e26@v28g2000pro.googlegroups.com> On Jul 21, 5:30?pm, Fredrik Lundh wrote: > Alexandru Palade wrote: > > However, you should be carefully because using an %i modifier for a > > what-should-be a float value truncates the value in a way you may not > > expect. > > > What I mean is that if you have sent 2 out of 3 bytes, the math will be > > 200/3 which with the %i modifier will print 66, rather than 66.6 (or at > > least 67 which is closer - have a look at the round() function). > > My suggested workaround doesn't use floats. ?As for rounding, that's > more of a usability issue -- seeing the download process getting stuck > at 100% can be rather frustrating for the poor user. ?Better truncate > towards zero. > > > Another thing, you could have just added a dot after the constant in > > order to promote the expression to be evaluated as float. As in > > ? ?percentage = bytes_transferred / /self/.__sessions[path].total_bytes > > * 100. > > (notice the last dot) > > Did you try that? > > ?>>> 2 / 3 * 100. > 0.0 > > You can fix this with parentheses, but I usually recommend an explicit > "cast" instead, to make it obvious what you're doing: > > ? ? ?result = float(a) / b > > Use 2.0 / 3 * 100 to solve this. Why make things look bigger? From gandalf at shopzeus.com Tue Jul 1 15:16:57 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 01 Jul 2008 21:16:57 +0200 Subject: convert unicode characters to visibly similar ascii characters In-Reply-To: References: <486A7BB5.3000501@shopzeus.com> Message-ID: <486A82A9.2050008@shopzeus.com> Peter Bulychev wrote: > Thank you for you answer. > > If you only want this to work for a subset, please define that subset. > > Actually, I want to convert only punctuations (dots, commas, hyphens > and so on). Then make your translation table manually and apply this method: unicode.translate Finally print s.encode('ascii') If you get an UnicodeEncodeError then it means you had other (not translated, non-ascii) characters in the original string. Best, Laszlo From python at rcn.com Sat Jul 12 10:11:35 2008 From: python at rcn.com (Raymond Hettinger) Date: Sat, 12 Jul 2008 07:11:35 -0700 (PDT) Subject: Perfect hashing for Py References: Message-ID: On Jul 12, 10:13?am, Raymond Hettinger wrote: > On Jul 11, 3:01?pm, bearophileH... at lycos.com wrote: > > > I have found this perfect hash (minimal too) implementation:http://burtleburtle.net/bob/hash/perfect.html > > > I have already translated part of it to D, and it seems to work well > > enough. As discussed in the PyConDue, I think this may be used in > > frozenset (and frozendict) to build a (minimal too?) perfect hash on > > the fly, to allow (hopefully) faster retrieval of items that don't > > change. I played around with the idea and have a rough implementation sketch: class PerfectSet(collections.Set): __slots__ = ['len', 'hashvalue', 'hashfunc', 'hashtable'] DUMMY = object() def __init__(self, keys, sparseness=0.5): keys = frozenset(keys) self.len = len(keys) self.hashvalue = hash(keys) n = (len(keys) / sparseness) + 1 assert n > self.len self.hashfunc = make_perfect_hash_function(keys, n) self.hashtable = [self.DUMMY] * n for k in keys: self.hashtable[self.hashfunc(k)] = k del __len__(self, k): return self.len def __iter__(self, k) return (k for k in self.hashtable if k is not self.DUMMY) def __contains__(self, k): return self.table[self.hashfunc(k)] is not self.DUMMY The perfect hash function will need to use the regular hash(obj) as a starting point. This helps with non-string types and it preserves existing relationships between __hash__ and __eq__. The construction is more expensive than with regular frozensets so it is only useful when lookups are very common. Playing around with the idea suggests that a sparseness variable for frozensets would largely accomplish the same goal without the overhead of creating and applying a perfect hash function. Sparse hash tables rarely collide. Raymond From jphalip at gmail.com Thu Jul 17 04:13:21 2008 From: jphalip at gmail.com (Julien) Date: Thu, 17 Jul 2008 01:13:21 -0700 (PDT) Subject: Remove some characters from a string Message-ID: <35cff1a6-74f6-4a68-b81e-71d8ff9c4633@a70g2000hsh.googlegroups.com> Hi, I can't seem to find the right regular expression to achieve what I want. I'd like to remove all characters from a string that are not numbers, letters or underscores. For example: >>> magic_function('si_98%u^d at .as-*gf') str: 'si_98udasgf' Would you have any hint? Thanks a lot! Julien From __peter__ at web.de Thu Jul 24 11:25:56 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 Jul 2008 17:25:56 +0200 Subject: repr(string) References: Message-ID: David C. Ullrich wrote: > In article , > Fredrik Lundh wrote: > >> David C. Ullrich wrote: >> >> > I've been saving data in a file with one line per field. >> > Now some of the fields may become multi-line strings... >> > >> > I was about to start escaping and unescaping linefeeds >> > by hand, when I realized that repr() and eval() should >> > do. Hence the question: If s is a string, is repr(s) >> > guaranteed not to contain line breaks? >> >> yes. >> >> just keep in mind that using eval() on untrusted data isn't a very good >> idea. > > Right. This data comes from me, gets put into a file and then > read by me. Someone _could_ corrupt that file, but someone who > could do that could more easily just throw the machine out > the window... You could also use a csv file with a single row. Peter From bruno.42.desthuilliers at websiteburo.invalid Tue Jul 1 08:20:37 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 01 Jul 2008 14:20:37 +0200 Subject: Scope and program structure problems In-Reply-To: References: Message-ID: <486a210f$0$15472$426a34cc@news.free.fr> John Dann a ?crit : > Trying to learn Python here, but getting tangled up with variable > scope across functions, modules etc and associated problems. Can > anyone advise please? > > Learning project is a GUI-based (wxPython) Python program that needs > to access external data across a serial port. > > The first thing that I need the program to do when it starts up is to > check that it can see the serial port, the first step of which is to > check that it can import the pySerial module, and display an > appropriate message in the statusbar of the main frame. (I know there > may be other ways of doing this but this is what I'm trying to do > currently and I'd like to understand how to make this approach work > robustly even if there are other options.) > (snip) > > ----------- > # Can't put serial import code here because there's no GUI yet to send > messages to. > > Class Frame(wx.Frame) > def __init__() > etc > #code to check and use serial port has to go below?? > def CheckSerial() # eg triggered by appropriate menu click event > Try: > import serial > etc > ser = Serial.etc # set ser object as handle to serial port > def UseSerial(): > # Code to perform serial IO > > app=App(wx.App) > app.MainLoop() > > # Can't put serial import code here because it won't execute until > frame closes? > ----------- > > But then I hit another problem. If I set the object ser to point to > the serial port in the CheckSerial function, then it's just got local > scope within the function and can't be seen from the UseSerial > function. > > So I've got 2 questions. The main one is whether there's any way of > explicitly giving the ser object global scope in the code line: > > ser = Serial.etc # set ser object as handle to serial port It is possible - for the python definition of 'global' being 'module-global' - but it's not necessarily the best solution. Look up the doc for the 'global' statement to learn more. Another solution would be to make ser an attribute of your Frame object: class Frame(wx.Frame): def __init__(self): self.serial = None #code to check and use serial port has to go below?? def setup_serial(self) # eg triggered by appropriate menu click event try: import serial except ImportError, e: # display an error message and either crash # or return else: # set self.serial object as handle to serial port self.serial = serial.etc() def use_serial(self): # Code to perform serial IO # won't work if setupSerial failed > And, second, does my overall description above reveal any serious > misunderstanding about how best to handle this sort of problem in > Python? Well... You'd get a very similar result by doing your import at the top-level but within a try/except block, then when you have a gui setup takes appropriate actions. try: import serial serial_import_error = None except ImportError, e: serial = None serial_import_error = e class Frame(wx.Frame): def __init__(self): self.serial = None def setup_serial(self): if serial is None: # display an error message and either crash # or return else: self.serial = serial.whatever() But anyway: I have no real (read : anything requiring any brain-cell) experience writing rich GUI apps in Python, and I haven't done rich GUI programming for four last years at least, so there may be better solutions here. So : Any wxPython guru around ?-) From jm.carp at gmail.com Fri Jul 25 19:09:13 2008 From: jm.carp at gmail.com (jm.carp at gmail.com) Date: Fri, 25 Jul 2008 16:09:13 -0700 (PDT) Subject: tcp socket problem Message-ID: I'm writing a tcp client that grabs data from a server at 32hz. But the connection drops exactly one minute after it's opened. I can get data from the server fine for the first 60s, and then the connection goes dead. What's going on? From tjreedy at udel.edu Sun Jul 27 21:21:10 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 21:21:10 -0400 Subject: Attack a sacred Python Cow In-Reply-To: References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: Russ P. wrote: > On Jul 27, 12:39 pm, Bruno Desthuilliers > All I am suggesting is that the programmer have the option of > replacing "self.member" with simply ".member", since the word "self" > is arbitrary and unnecessary. I presume you are proposing the opposite also, that ".member" would internally be expanded to "self.member". As I said before, that, or something near like it (it is hard to exactly compare underspecified proposals) has be suggested and rejected, even if someone gave you not the exact reference. For one thing, as Guido noted, a single . can be hard to see and easy to miss, depending on one's eyesight, environmental lighting, and exact display medium, including font. I suspect Guido's other reasons have been covered, but I do not want misquote him. I will leave you to search the pydev list archives. > Otherwise, everything would work *EXACTLY* the same as it does now. If I understand you, that would mean that .attribute would raise NameError: name 'self' is not defined if used anywhere where 'self' was not defined. From elessar at nienna.org Fri Jul 11 10:48:53 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 11 Jul 2008 08:48:53 -0600 Subject: Unit Testing Techniques In-Reply-To: References: Message-ID: <487772D5.3050308@nienna.org> I'm by no means a testing expert, but I'll take a crack at it. Casey McGinty wrote: > I'm familiar with the unittest module in Python, however I'm hoping > someone can point me to some examples of more advanced usages of the > framework. For example: > > 1. Using the framework to test a package with nested sub-packages and > modules without having to hard code the location/name of each test module. I've never run into this. > 2. Testing class/methods that depend on file system directory > structures, file data, or values read from system hardware. Rule of thumb: always separate software from hardware. Write mock classes or functions that do your hardware/file access that always return known data (but remember to test for alpha and beta errors--make sure both valid and invalid data are handled correctly). That way you can test the client code that is accessing the hardware. Testing the actual hardware/file access code can get more interesting. If you're just reading files, your test suite should write the test files in setUp, try to read them in the test* methods, then clean up in tearDown. Again, remember to test both good and bad files. In my shop, we do both hardware and software, and testing the comms between them can be a real pain. We've done lots of interesting things like wiring faults into the hardware with switches to connect and disconnect them, recording command sequences, etc., but I expect this is beyond the scope of what you're interested in. Just keep in mind that testing a chunk of code requires at least as much creativity as writing the code in the first place. > 3. Testing class/methods that require simulating functionality from > imported modules. You can do neat things like this: import unittest import mymodule def my_mock_function(): """Returns known values.""" class MyTest(unittest.TestCase): def setUp(self): self._orig_function = mymodule.function mymodule.function = my_mock_function def tearDown(self): # remember to restore the original function # unittest doesn't re-import modules mymodule.function = self._orig_function def test1(self): """Test some code that uses mymodule.""" # etc... The dynamic nature of Python makes this sort of thing much easier than other languages. > 4. Testing graphical interfaces and associated signal callback functions. Again, there are lots of strategies you can use; the specifics depend on you design and the toolkit. 1) You can mock the backend: make sure the right functions get called in response the user actions. 2) Simulate user actions by manually posting events, calling functions, etc. 3) Mock the gui: make sure the backend is calling all the right GUI functions. Try to keep your backend and gui as independent as possible, it will make testing much easier. > > Thank you. > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list I typically make a bunch of different suites that can be run individually, in various combinations, or all together. Testing I/O tends to be very slow, so it's nice to be able to turn of these tests when you're working on other parts of the system. There are many other testing tools besides unittest. The one I use the most is coverage.py, to determine if my test suites are hitting all my code. But you can check out pymock, doctest, nose, etc. too. You may have to use a combination of tools to meet your needs. There is also the Testing in Python mailing list (http://lists.idyll.org/listinfo/testing-in-python). You can probably get some advice there as well. The more specifics you can give, the better. As you solve your testing problems, please take the time to post your solutions (if you can) so we can all learn from your experiences. -Matt From tjreedy at udel.edu Sun Jul 27 14:00:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 14:00:27 -0400 Subject: Rant (was Re: x*x if x>10 In-Reply-To: <1q5p845o2j9htp6vf44u6nqinucsr1numf@4ax.com> References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3g8rF9gfj0U1@mid.uni-berlin.de> <6f3gmaF9moqsU1@mid.uni-berlin.de> <1q5p845o2j9htp6vf44u6nqinucsr1numf@4ax.com> Message-ID: DaveM wrote: > On Sun, 27 Jul 2008 16:57:14 +0200, "Diez B. Roggisch" > You'll have guessed, I'm sure, that I'm not a professional programmer. This > was the third rewrite of a program to match candidate groups to examiners on > a three day course I run, necessitated on this occasion by a change in the > structure of the course. I originally learnt python as I wrote, and some of > the early code was ugly and verbose, so once the current rewrite was working > I took the opportunity to tidy the code up and document it (yes, I know, but > as I said, I'm an amateur). The list concatenation was an itch I couldn't > scratch: > > temp = [] > for value in sessexam.values(): > temp.extend(value) > c_exam = [name for name in set(temp)] #See what I mean about verbose? > c_exam.sort() > return c_exam > > Six lines just didn't feel like it ought to be the best way to do something > so simple. I liked the attempt below better, but was foolish enough to time > it, so that was the end of that. > > return sorted(list(set(reduce(lambda x, y: x+y, sessexam.values())))) > > The current version (below) is a compromise, but I still feel there _ought_ > to be a simple one word command to join multiple lists. There is, as others have posted, but if you are going to dump the lists into a set, there is no need to concatenate them together first, and it is better not to. Just dump them directly into set. > > a = list(set(itertools.chain(*sessexam.values()))) This is a pretty good way of skipping the intermediate long list. Another: a = set() for l in sessexam.values(): a.update(set(l)) If course, if sessexam.values() does not need to be ordered and returns sets instead, the set call in not needed. > a.sort() #As I write I'm wondering if I really need it sorted. Hmm... > return a If you want all in one line... return sorted(set(itertools.chain(*sessexam.values()))) There is no virtue to calling list then .sort, since that is what sorted basically does. def sorted(iterable): tem = list(iterable) tem.sort() return tem tjr tjr From henrik at chamalulu.com Tue Jul 1 19:31:32 2008 From: henrik at chamalulu.com (chamalulu) Date: Tue, 1 Jul 2008 16:31:32 -0700 (PDT) Subject: Attribute reference design References: <6cvlk4F3s90U1@mid.uni-berlin.de> Message-ID: On Jul 2, 1:17 am, Gary Herron wrote: > No need. Also, you can define a class attribute (C++ might call it a > static attribute) and access it transparently through an instance. > > class C: > aClassAttribute = 123 > def __init__(self, ...): > ... > > c = C() > ... do something with c.aClassAttribute ... > Actually, this is why I started too look into the attribute reference mechanics to begin with. Coming from mostly C# development I think it's weird to be able to refer to class attributes (static members) through a class instance (object). But I think I'm getting the picture. Function objects lay flat in memory (some heap...). When defined inside classes they are wrapped in method objects. When refered through classes or class instances they are unbound method objects or bound method objects respectively. Am I on the right track? I still don't get why these methods show up when I dir() a class instance. /Henrik From lists at nanl.de Fri Jul 11 07:50:44 2008 From: lists at nanl.de (Mirko Vogt) Date: Fri, 11 Jul 2008 13:50:44 +0200 Subject: socket-module: different behaviour on windows / unix when a timeout is set In-Reply-To: References: <4874FD50.1070404@nanl.de> Message-ID: <48774914.3040902@nanl.de> Gabriel Genellina wrote: > En Wed, 09 Jul 2008 15:02:56 -0300, Mirko Vogt escribi?: > >> it seems that the socket-module behaves differently on unix / windows >> when a timeout is set. > [...] >> Now I will change the code slightly - to be precise I set a timeout on >> the socket: >> >> >> # test.py >> >> import socket >> sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) >> sock.settimeout(3.0) # <----- >> print 'trying to connect...' >> sock.connect(('127.0.0.1',9999)) >> print 'connected!' >> >> >> # executed on linux >> >> $ python test.py >> trying to connect... >> Traceback (most recent call last): >> File "test.py", line 5, in >> sock.connect(('127.0.0.1',9999)) >> File "", line 1, in connect >> socket.error: (111, 'Connection refused') >> $ >> >> >> # executed on windows >> >>> C:\Python25\python.exe test.py >> trying to connect... >> connected! > > Which Python version? Which Windows version? I've tried 2.3.4, 2.4.4, > 2.5.1 and 3.0a4, all on WinXP SP2, and in all cases I got an exception > (details differ between versions). In no case I could make the > connection succeed when nobody was listening at port 9999, as expected. > Hey, this is strange. Linux: $ python --version Python 2.5.2 $ Windows: C:\Python25>python.exe --version Python 2.5.2 C:\Python25> Mirko From deets at nospam.web.de Thu Jul 10 13:13:46 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 10 Jul 2008 19:13:46 +0200 Subject: Idiomatic Python to convert list to dict In-Reply-To: <7ec9405c-4e6f-491d-84b2-c81152302b13@79g2000hsk.googlegroups.com> References: <7ec9405c-4e6f-491d-84b2-c81152302b13@79g2000hsk.googlegroups.com> Message-ID: <6dmuacF33kciU1@mid.uni-berlin.de> James Fassett schrieb: > Hi all, > > Simple question really on a best practice. I want to avoid adding > duplicates to a list. > > my_list = ['a', 'b', 'c', 'd', 'e'] > dup_map = {} > for item in my_list: > dup_map[item] = True > > # ... sometime later > > for complex_dict in large_list: > if complex_dict["char"] not in dup_map: > my_list.append(complex_dict["char"]) > dup_map[complex_dict["char"]] = True > > For the first part (generating the duplicate map) is there a more > idiomatic Python method for flipping the list into a dict? > > Is there a better way to achieve the overall objective (as hinted at > by the above algorithm)? > > Thanks in advance for any tips. Instead of a dict, use a set. It's immediatly contructable from my_list, and better suited for the task anyway. Diez From kay.schluehr at gmx.net Sun Jul 20 05:08:35 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 20 Jul 2008 02:08:35 -0700 (PDT) Subject: Genetic programming: pygene, pygp, AST, or (gasp) Lisp? References: <7bfb3c41-b08b-49dc-9711-6e39a4667db2@b1g2000hsg.googlegroups.com> Message-ID: On 20 Jul., 09:52, John Ladasky wrote: > Why not do genetic programming directly on Python code? Maybe my code > tree data structure is redundant to something which already exists? > But apparently Python's "_ast" module offers only one-way access -- it > will generate an AST from a piece of code, but you can't modify an > AST, and turn it back into executable code? Why not? You can compile ASTs. Another option is to use EasyExtend http://www.fiber-space.de/EasyExtend/doc/EE.html which is a bit heavyweight though without prior knowledge of the framework. EE provides some generic functions over languages like parse/unparse. Python is just a special case. So you can do the following from EasyExtend.langlets.zero.langlet import parse, unparse src = """ if disc(a) < c: b = f1(a) else: b = f2(a) """ parse(src) # yields a parse tree unparse(parse(src)) # yields the source code of the parse tree Here `zero` means Python which is just the trivial/featureless langlet of the system or some kind of embedding. For meshing fragments together on random one can use cst.py. For each rule in Pythons grammar cst.py implements a corresponding function that produces the parse tree accordingly. So if there is a rule test: or_test ['if' or_test 'else' test] | lambdef a corresponding function test(*args) exists that produces a parse tree from components that were built using or_test(), test() or lambdef(). chaining these functions is just like building s-expr. > I would definitely need > this latter feature. > > ALTERNATELY -- and I don't mention this to start a flame war -- in > pondering this problem I've noticed the frightening fact that Lisp > seems set up to handle genetic programming by design. Definitely. But this is nothing new. Lisp was the original language used by John Koza to implement GP. > The s- > expression syntax IS essentially a parse tree. Now, I've spent a few > hours with Lisp so far, and I can't make it do much of anything -- but > I DO see how Lisp could be helpful. Still, I'm reluctant to pursue a > language I don't know, and which I'm finding much harder to grasp than > any language I've tried before. You can write a primitive s-expr evaluator/manipulator using Pythons overloading capabilities. But this way you will just produce s-expr and not Python functions. Kay From jwahlmann at gmail.com Mon Jul 21 11:51:10 2008 From: jwahlmann at gmail.com (jwahlmann at gmail.com) Date: Mon, 21 Jul 2008 08:51:10 -0700 (PDT) Subject: Weird Python startup behavior between different drives on PowerPC platform References: <616d9012-5b71-43c7-9141-bc4b37072642@y22g2000prd.googlegroups.com> Message-ID: <6c635cef-4605-4fb8-ae0c-7d8161196999@t12g2000prg.googlegroups.com> Bump. Anyone have any ideas on this? My next step is to either link together a static version of the compiler or create a debug version. Thanks, Jon On Jul 18, 11:43 am, jwahlm... at gmail.com wrote: > I'm experiencing some strange behavior when starting up python on a > Debian-based PowerPC platform. Normally, I operate from this platform > with a root file system on an IDE flash drive (/dev/hda1). However, > I'm trying to get my system to run with root on a mechanical SATA > drive (/dev/sda1). Both are installed on a PowerPC board via a PMC > daughter board. > > When running off the flash drive, the Python interpreter loads and > runs just fine. However, when running from SATA, the interpreter > seems to have problems with importing things like site, os, etc. I've > played around with PYTHONHOME to no effect. I even went as far as > setting PYTHONHOME to some off the wall location (so no stdlibs will > load) and invoking Python as: > > host$ PYTHONHOME=/tmp python -d -v -S > # installing zipimport hook > import zipimport # builtin > # installed zipimport hook > Python 2.4.4 (#2, Apr 5 2007, 19:01:44) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2>>> i=0 > > File "", line 1 > i=0 > ^ > SyntaxError: invalid syntax > > > > You'll note that doing something as simple as setting "i=0" results in > a syntax error. If I run the same thing on the IDE flash drive, it > works: > > host$ PYTHONHOME=/tmp python -d -v -S > # installing zipimport hook > import zipimport # builtin > # installed zipimport hook > Python 2.4.4 (#2, Apr 5 2007, 19:01:44) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > > >>> i=0 > > Any ideas?! What could possibly cause a difference of operation > between running from a IDE flash drive (/dev/hda1) vs. SATA (/dev/ > sda1)? Other than toggling hda1 vs. sda1 in /etc/fstab, the > filesystems are being built identically. Could it be that shared > libraries aren't being loaded correctly or fast enough off the SATA > drive vs. flash? Shooting in the dark here... > > Thanks, > Jon Wahlmann From mathieu.prevot at ens.fr Thu Jul 10 18:57:05 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Fri, 11 Jul 2008 00:57:05 +0200 Subject: error with configure (svn 64857) In-Reply-To: <487681e9$0$9745$9b622d9e@news.freenet.de> References: <487681e9$0$9745$9b622d9e@news.freenet.de> Message-ID: <3e473cc60807101557v202235f9s853c3bd2b39087b5@mail.gmail.com> 2008/7/10 "Martin v. L?wis" : >> I have the following error when I run configure: >> >> checking size of wchar_t... configure: error: cannot compute sizeof (wchar_t) >> >> what can I do ? > > Study config.log for the source of the problem. Thank you Martin. How can I remove -lgcc_s and use the Intel equivalent ? configure:21939: checking for wchar_t configure:21970: icc -c -g -O2 conftest.c >&5 conftest.c(123): warning #279: controlling expression is constant if ((ac__type_new_ *) 0) ^ configure:21976: $? = 0 configure:21991: result: yes configure:21998: checking size of wchar_t configure:22306: icc -o conftest -g -O2 conftest.c >&5 ld: library not found for -lgcc_s configure:22309: $? = 1 configure: program exited with status 1 Mathieu From martin at v.loewis.de Thu Jul 10 17:40:57 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 10 Jul 2008 23:40:57 +0200 Subject: error with configure (svn 64857) In-Reply-To: References: Message-ID: <487681e9$0$9745$9b622d9e@news.freenet.de> > I have the following error when I run configure: > > checking size of wchar_t... configure: error: cannot compute sizeof (wchar_t) > > what can I do ? Study config.log for the source of the problem. Regards, Martin From qvx3000 at gmail.com Tue Jul 29 13:56:08 2008 From: qvx3000 at gmail.com (qvx) Date: Tue, 29 Jul 2008 10:56:08 -0700 (PDT) Subject: I CAN connect socket to any localhost port but I shouldn't be able to Message-ID: <13c78fbf-751f-4d70-a012-53aa1eb64e53@79g2000hsk.googlegroups.com> Hi, I don't have server listening on port 8084 but I can open socket to it (and to many other ports, tested for all<8000) import socket def test(port): af, socktype, proto, canonname, sa = socket.getaddrinfo('localhost', port, socket.AF_INET, socket.SOCK_STREAM)[0] s = socket.socket(af, socktype, proto) s.settimeout(1.0) s.connect(('localhost', port)) s.close() # This doesn't throw socket.error, it happily finishes for x in range(1, 8000): test(x) Thanks, Tvrtko From apardon at forel.vub.ac.be Wed Jul 30 05:49:16 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 30 Jul 2008 09:49:16 GMT Subject: Change PC to Win or Windows References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> Message-ID: On 2008-07-21, Derek Martin wrote: > > --tsOsTdHNUZQcU9Ye > Content-Type: text/plain; charset=iso-8859-1 > Content-Disposition: inline > Content-Transfer-Encoding: quoted-printable > > On Sat, Jul 19, 2008 at 02:56:07AM -0700, Lie wrote: >> On Jul 19, 6:14=A0am, Derek Martin wrote: >> > On Fri, Jul 18, 2008 at 03:46:13PM -0700, Joel Teichroeb wrote: >> > Much like the English word "bank" (and numerous others), the term "PC" >> > has come to have several meanings, one of which is the above. =A0You may >> > not like it, but we're pretty much stuck with the term, so you may as >> > well get used to it. >> >> That's not the point,=20 > > It very much IS the point. Language evolves based on common usage > patterns of the people who use it. The term "PC" is commonly used in > English, in the United States and other English speaking countries, to > mean a computer running Microsoft Windows. You mean the same computer is no longer considered a PC if someone install linux on it? -- Antoon Pardon From fuzzyman at gmail.com Fri Jul 25 18:08:20 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Fri, 25 Jul 2008 15:08:20 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> On Jul 24, 6:41?am, Jordan wrote: > Hi everyone, > > I'm a big Python fan who used to be involved semi regularly in > comp.lang.python (lots of lurking, occasional posting) but kind of > trailed off a bit. I just wrote a frustration inspired rant on my > blog, and I thought it was relevant enough as a wider issue to the > Python community to post here for your discussion and consideration. > > This is not flamebait. I love Python, and I'm not out to antagonise > the community. I also realise that one of the issues I raise is way > too ingrained to be changed now. I'd just like to share my thinking on > a misstep in Python's guiding principles that has done more harm than > good IMO. So anyway, here's the post. > > I've become utterly convinced that at least one criticism leveled at > my favourite overall programming language, Python, is utterly true and > fair. After quite a while away from writing Python code, I started > last night on a whim to knock up some code for a prototype of an idea > I once had. It's going swimmingly; the Python Image Library, which I'd > never used before, seems quick, intuitive, and with the all the > features I need for this project. As for Python itself, well, my heart > still belongs to whitespace delimitation. All the basics of Python > coding are there in my mind like I never stopped using them, or like > I've been programming in this language for 10 years. > > Except when it comes to Classes. I added some classes to code that had > previously just been functions, and you know what I did - or rather, > forgot to do? Put in the 'self'. In front of some of the variable > accesses, but more noticably, at the start of *every single method > argument list.* This cannot be any longer blamed as a hangover from > Java - I've written a ton more code, more recently in Python than in > Java or any other OO language. What's more, every time I go back to > Python after a break of more than about a week or so, I start making > this 'mistake' again. The perennial justification for this 'feature' > of the language? That old Python favourite, "Explicit is better than > implicit." > It's damn useful for scoping. You can look in the body of your method and tell whether you are accessing local variables or instance variables. I'm a great fan of self and I'm afraid you're flogging a dead horse on that one. Your point about rich comparison (at least the == != problem) is fair. This one is fixed in Python 3 though I believe. Michael Foord -- http://www.ironpythoninaction.com/ From laredotornado at zipmail.com Wed Jul 30 13:49:58 2008 From: laredotornado at zipmail.com (laredotornado) Date: Wed, 30 Jul 2008 10:49:58 -0700 (PDT) Subject: Possible to have multiple loop variables? Message-ID: <5ff22b51-88e9-405c-aeb9-7b0abe9cf935@r66g2000hsg.googlegroups.com> I don't know why I thought this would work, but I would like to have 3 variables in my for loop per iteration. Those familiar will know that this ms1 = {'managed1':7019:8020,'managed2':7020:8021} for m, lp, ssl_lp in ms1.items(): managedServer = create(m,'Server') print 'creating managed server '+m managedServer.setListenAddress('147.191.71.70') managedServer.setListenPort(lp) managedServer.setEnabled(0) cd('SSL/cgServer') managedServer.setEnabled(1) managedServer.setListenPort(ssl_lp) managedServer.setCluster(clus1) causes File "/export/third-party/etsbea/home/etsbea/tests/wlst/ createcluster.py", line 9 ms1 = {'managed1':7019:8020,'managed2':7020:8021} ^ SyntaxError: invalid syntax How would I set up the ms1 array such that I can use three items per object? Thanks, - Dave From asma61 at dsl.pipex.com Sun Jul 27 15:43:58 2008 From: asma61 at dsl.pipex.com (DaveM) Date: Sun, 27 Jul 2008 20:43:58 +0100 Subject: Rant (was Re: x*x if x>10 References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3qjoF9n3cpU1@mid.uni-berlin.de> Message-ID: On Sun, 27 Jul 2008 19:46:32 +0200, "Diez B. Roggisch" wrote: >As a rule of thumb, don't return objects you didn't create inside a >function from scratch. I wish I'd had that advice when I started learning python. It would have saved me no end of grief. DaveM From ethan at stoneleaf.us Tue Jul 29 20:55:48 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 29 Jul 2008 16:55:48 -0800 Subject: Boolean tests In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8d <87y73kg70u.fsf@benfinney.id.au> Message-ID: <488FBC14.4090003@stoneleaf.us> Matthew Woodcraft wrote: > Ben Finney wrote: > >>No, he retracted the *insult* and restated the *advice* as a distinct >>statement. I think it's quite worthwhile to help people see the >>difference. > > > Ben, it was quite clear from Anders' post that he knows about > __nonzero__ . That's why the so-called advice is insulting. The > original phrasing was just the icing on the cake. > > -M- I got just the opposite -- it seems quite clear to me that Anders did *not* know about __nonzero__, and perhaps doesn't know about double-underscore functions in general... Here's his quote: > Okay, so you have this interesting object property that you often need > to test for, so you wrap the code for the test up in a method, because > that way you only need to write the complex formula once. I'm with > you so far. But then you decide to name the method "__nonzero__", > instead of some nice descriptive name? What's up with that? His last question, "What's up with that?" is the indicator. His comments after that, such as > Even if we find out that C.__nonzero__ is called, what was it that > __nonzero__ did again? reinforce the impression that he is unaware of the double-underscore functions and what they do and how they work. One can find out when they are called with a simple search of the python documentation. > Better dig up the class C documentation and find out, because there is > no single obvious interpretation of what is means for an object to > evaluate to true. If you are using somebody else's code, and maybe even your own, you should always check the docs if you don't know/can't remember what a function does. ~Ethan~ From Lie.1296 at gmail.com Sat Jul 19 05:23:11 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 19 Jul 2008 02:23:11 -0700 (PDT) Subject: Rotating a cube References: <3d47df08-9734-4e0f-96ad-37da445b4faf@34g2000hsh.googlegroups.com> Message-ID: <8156f68a-3f65-4fca-a725-2e0c4240abd1@v21g2000pro.googlegroups.com> On Jul 17, 3:11?pm, J-Burns wrote: > On Jul 17, 12:53 pm, Fredrik Lundh wrote: > > > J-Burns wrote: > > > Is there a built in Python function for this? > > > for answering questions that have nothing to do with programming, and > > looks quite a bit like homework? ?don't think they've added that one yet. > > > maybe you should look for a geometry newsgroup/forum? > > > > > I meant to ask how would you do this in Python... :S The same as you do it in any other languages. This question is marked correctly as having no relationship to python whatsoever. You'd get a better answer if you asked in mathematics/geometry group, many mathematician are adept programmer as well. From tjreedy at udel.edu Fri Jul 11 14:51:07 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 Jul 2008 14:51:07 -0400 Subject: Python 3.0 and removal of the 'string' module In-Reply-To: <87abgorgiv.fsf@benfinney.id.au> References: <87wsjtqiyo.fsf@benfinney.id.au> <87iqvdq6qz.fsf@benfinney.id.au> <487706b7$0$9695$9b622d9e@news.freenet.de> <87abgorgiv.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > "Martin v. L?wis" writes: > >>> This is rather disappointing. Is that entire page suspect? >> All documentation about Python 3 is suspect until Python 3 gets >> actually released (nobody can say for sure how the release will >> look like in all details). > > Is there a better information source, then, for the current state of > what's expected in Python 3.0? Start with the actual beta release. That is what is there. There are a few tweaks that might happen, and a few modules that might be added, and some bugs that should be fixed. The issue tracker has information on the day-to-day state of most of these. From robert.kern at gmail.com Tue Jul 8 16:11:01 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 08 Jul 2008 15:11:01 -0500 Subject: Logging to zero or more destinations In-Reply-To: References: Message-ID: samwyse wrote: > In the Python 2.5 Library Reference, section 14.5.3 (Logging to > multiple destinations), an example is given of logging to both a file > and the console. This is done by using logging.basicConfig() to > configure a log file, and then calling > logging.getLogger('').addHandler(console) to add the console. > > However, in section 14.5.4 (Sending and receiving logging events > across a network), a call is made to > rootLogger.addHandler(socketHandler), and later it is stated that "On > the client side, nothing is printed on the console". > > Finally, back in section 14.5.2 (Basic example), it's stated that "by > default, the root logger is configured to only handle messages with a > severity of WARNING or above. The message format is also a > configuration default, as is the output destination of the messages - > sys.stderr." > > The only way that I can see for all three statements to be consistent > is that the root logger starts with an empty list of handlers, and > doesn't instantiate a default handler until either > logging.basicConfig() is called, or the first time that a message is > logged. This would also seem to imply that there's no way to use an > empty handler list (say, if you want to suppress all logging), because > the root handler will instantiate a handler for you. Is this correct? Sort of. Your analysis of what happens is entirely correct (see below). However, a way to suppress all logging is to have a single Handler where the emit() method does nothing. Or you can set the level above CRITICAL. $ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> logging.warn('foo') WARNING:root:foo >>> logger = logging.getLogger() >>> logger.handlers [] >>> $ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> logger = logging.getLogger() >>> logger.handlers [] >>> logging.basicConfig() >>> logger.handlers [] >>> logger.handlers = [] >>> class NullHandler(logging.Handler): ... def emit(self, record): ... pass ... >>> logger.addHandler(NullHandler()) >>> logging.warn('foo') >>> > P.S. I tried researching this further by myself, but the logging > module doesn't come with source (apparently it's written in C?) and I > don't have the time to find and download the source to my laptop. No it's all Python. Look in c:\Python25\Lib\logging\ . -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From yuxi at ece.gatech.edu Fri Jul 4 01:10:57 2008 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Fri, 04 Jul 2008 01:10:57 -0400 Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: <87b10cf3-4fd4-46e3-a33a-528f1180f69a@s21g2000prm.googlegroups.com> References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> <9cdbb215-d427-4694-a455-f2571ad42390@x19g2000prg.googlegroups.com> <54e0e7c5-113e-4296-a62f-e649d6ffa2d6@z66g2000hsc.googlegroups.com> <87b10cf3-4fd4-46e3-a33a-528f1180f69a@s21g2000prm.googlegroups.com> Message-ID: Ali Servet D?nmez wrote: > > I tried code come completion options in Emacs for Python, but none of > them was satisfactory to me. I'd be glad to hear how did your friend > get it work though. Perhaps it would help to say what ways the completion in Emacs was not satisfactory? FWIW, it should be possible to get IPython-type completion in Emacs, but I hadn't managed that yet :( Refactoring, too. Both involve Pymacs but I've had limited success with that. As for PyDev (I know you said "No" to this already), the main problem I have with PyDev/Eclipse is the woefully underpowered editor (compared to Emacs), and poor indentation logic. On the plus side, refactoring works pretty well. So why not PyDev? I'm just wondering, you insist on Free/Libre software solutions, and say the ones you tried don't work for you. Why not "use the source" and fix them so they work your way? ;) To quote you: "how hard it could be be writing a freesoftware which would automatically/intelligently auto complete Python code?" From ethan at stoneleaf.us Tue Jul 22 10:43:31 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 22 Jul 2008 06:43:31 -0800 Subject: Python Written in C? In-Reply-To: <143349c3-b0e9-49d8-9426-8b030b23d2c9@l42g2000hsc.googlegroups.com> References: <143349c3-b0e9-49d8-9426-8b030b23d2c9@l42g2000hsc.googlegroups.com> Message-ID: <4885F213.2030101@stoneleaf.us> Iain King wrote: > On Jul 21, 6:58 am, "Krishnakant Mane" wrote: > >> First off all c# is absolute rubbish waist of time. if I need to >> learn it then I better lern java or pythonfor that matter. and by the >> way what is a "real programmer?" > > The story of a Real Programmer: > > http://www.pbm.com/~lindahl/mel.html > > Iain Wow. Awesome story. ~Ethan From sturlamolden at yahoo.no Fri Jul 25 16:21:53 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 25 Jul 2008 13:21:53 -0700 (PDT) Subject: 2d graphics - what module to use? References: Message-ID: <5035d4cb-1976-47d5-8887-4e8381407a7b@m44g2000hsc.googlegroups.com> On Jul 25, 8:13?am, Pierre Dagenais wrote: > What is the easiest way to draw to a window? I'd like to draw something > ? like sine waves from a mathematical equation. > Newbie to python. For mathematica equations, NumPy and matplotlib is probably the best option. I prefer to embed matplotlib in wxPython. wxAgg is an excellent backend. For more general 2D graphics, there are several options, including: - pygame (uses SDL) - aggdraw module - pycairo - pyopengl - wxPython's device context (ditto for other GUI libraries) From kirby.urner at gmail.com Sat Jul 12 22:41:15 2008 From: kirby.urner at gmail.com (kirby.urner at gmail.com) Date: Sat, 12 Jul 2008 19:41:15 -0700 (PDT) Subject: New TTF fonts in IDLE on Linux question Message-ID: So I'm using this Akbar font, a truetype, related to Simpsons, for coding in Python, just for kicks (looks pretty good actually). No prob on Windows, but when I sudo cp akbar.ttf to /usr/share/fonts/ truetype/ttf-misc, a directory I made myself (root root), then OpenOffice and WingWare find it right away, but IDLEs in Python 2.5 and 3.0 don't seem to see it. Is there some special place IDLE looks for fonts that I'm missing? http://worldgame.blogspot.com/2008/07/idle-language-games.html http://www.flickr.com/photos/17157315 at N00/2662994560/ Kirby From sjmachin at lexicon.net Thu Jul 31 16:41:38 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 31 Jul 2008 13:41:38 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> <4609709f-dc0f-47cc-905e-1552a02ec3b6@r15g2000prd.googlegroups.com> Message-ID: <416f2710-1295-4d8b-a356-98fd9e9a56ad@j7g2000prm.googlegroups.com> On Jul 31, 11:54 pm, william tanksley wrote: > John Machin wrote: > > william tanksley wrote: > > > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" > > > 1. This isn't Unicode; it's missing the u"" (I printed using repr). > > > 2. It's got the UTF-8 bytes there in the middle. > > > In addition to the above results, > > *WHAT* results? I don't see any repr() output, just your > > interpretation of what you think you saw! > > That *is* the repr. I said it's the repr, and it IS. It's not an > interpretation; it's a screenscrape. Really, truly. If I paste it in > again it'll look the same. > > What do you want? Can I post something that will convince you it's a > repr? > Let's try again: >> # track_id = url2pathname(urlparse(track_id).path) >> print repr(track_id) >> parse_result = urlparse(track_id).path >> print repr(parse_result) >> track_id_replacement = url2pathname(parse_result) >> print repr(track_id_replacement) > The "important" value here is track_id_replacement; it contains the > data that's throwing me. It appears that some UTF-8 characters are > being read as multiple bytes by ElementTree rather than being decoded > into Unicode. > Here's one example. The others are similar -- they have the same > things that look like problems to me. > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" ROTFL! I thought the Buffett thing was a Windows filename! What I was expecting was THREE lots of repr() output, and I'm quite unused to seeing repr() output with quotes around it instead of apostrophes; how did you achieve that? So you're saying that track_id_replacement contains utf8 characters. It is obtained by track_id_replacement = url2pathname(parse_result). You don't show us what is in parse_result. url2pathname() is nothing to do with ElementTree. urlparse() is nothing to do with ElementTree. You have provided no evidence that ElementTree is doing what you accuse it of. Please try again. Backtrack in your code to where you are pulling the url out of an element. Do print repr(some_element.some_attribute). Show us. From semanticist at gmail.com Sun Jul 13 22:37:06 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 22:37:06 -0400 Subject: socket.connect() hangs in SYN_SENT state. In-Reply-To: References: Message-ID: On Sun, Jul 13, 2008 at 10:29 PM, Miles wrote: > On Sat, Jul 12, 2008 at 11:23 PM, bukzor wrote: >> Anyone know a general reason this might happen? Even better, a way to >> fix it? > > Maybe your client has an unusually low socket timeout for some reason, > though; does increasing it (with socket.setdefaulttimeout) help? Never mind on that, as you already said that it hangs for about two minutes. Clearly my reading comprehension and retention rate are at an all-time low today. low-signal-to-noise-ratio-ly yours, Miles From pavlovevidence at gmail.com Tue Jul 15 12:39:02 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 15 Jul 2008 09:39:02 -0700 (PDT) Subject: Suggestion: Python global scope References: Message-ID: On Jul 15, 7:57?am, Anonymous Bastard wrote: > I've been tossing this idea in my mind for some time now: > > In Python, declaring a variable using the global statement automatically > makes it available in all subsequent scopes. > > But to me, it makes more sense to use the global statement to 'import' a > variable from the global scope into the current scope. No way. You'd need to find another keyword. "localize" might be a better word to use. > For instance: > > [code] > global X > X = 1 > > def P(): > ? ? ?X = 2 > ? ? ?print X > ? ? ?global X > ? ? ?print X > > print X > P() > print X > [code] > > Currently, this will print 1, 2, 2 and 2. But if global would be limited > to current scope, it would print 1, 2, 1, 1. What would it print if you changed P to this? def P(): X = 2 print X global X print X X = 3 Would it print 1, 2, 1, 1 or 1, 2, 1, 3? > 'X = 2' would work on the local version of X, 'global X' will 'import' > the global X into the local scope, so any actions on X would reference > the global X, rather than previous X. Do you have a specific use case in mind? Where would this sort of thing be useful? (The be sure, I can think of a use case for something like this, namely optimizing away hash lookups for frequently used globals. But such an optimization doesn't justify new syntax, especially when you can already do it only slightly less conveniently.) Carl Banks From __peter__ at web.de Fri Jul 18 07:13:18 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 13:13:18 +0200 Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: nicolas.pourcelot at gmail.com wrote: > In fact, 'any(myobject is element for element in mylist)' is 2 times > slower than using a for loop, and 'id(myobject) in (id(element) for > element in mylist)' is 2.4 times slower. This is not a meaningful statement unless you at least qualify with the number of item that are actually checked. For sufficently long sequences both any() and the for loop take roughly the same amount of time over here. $ python -m timeit -s"items=range(1000); x = 1000" "any(x is item for item in items)" 1000 loops, best of 3: 249 usec per loop $ python -m timeit -s"items=range(1000); x = 1000" "for item in items:" " if x is item: break" 1000 loops, best of 3: 276 usec per loop $ python -m timeit -s"items=range(1000); x = 0" "any(x is item for item in items)" 100000 loops, best of 3: 3 usec per loop $ python -m timeit -s"items=range(1000); x = 0" "for item in items:" " if x is item: break" 1000000 loops, best of 3: 0.317 usec per loop Peter PS: Take these numbers with a grain of salt, they vary a lot between runs. From fredrik at pythonware.com Fri Jul 25 03:57:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 09:57:58 +0200 Subject: file operations. In-Reply-To: <73045cca0807241546k3697a77cs999bad6d62867167@mail.gmail.com> References: <73045cca0807241546k3697a77cs999bad6d62867167@mail.gmail.com> Message-ID: aditya shukla wrote: > Guys thanks for your previous help .I have a doubt again (I'm sure you mean "a question"; in english, "a doubt" is something slightly different, and quite often more negative.) > Also , because of this i am not able to extract the floating point > values ie 0.50,0.50,0.66 respectively > cause when i use the proposed solution given earlier > > data=[] > for line in x: print repr(line) # added for debugging! > line=line.split("|") > data.append(float(line[-2])) --> i am trying to get the floating > point values from the back > > i receive this error message > > Traceback (most recent call last): > File "", line 3, in > d.append(float(line[-2])) > IndexError: list index out of range one or more lines in your file doesn't match the description; try adding a print statement (see above) to see what they might look like, and make sure that you filter them out (e.g. by checking the size of the list you get from the split, as Terry explains). From mmaccana at au1.ibm.com Wed Jul 23 20:54:51 2008 From: mmaccana at au1.ibm.com (Mike MacCana) Date: Thu, 24 Jul 2008 10:54:51 +1000 Subject: Proper way to query user and group database on a Unix host? In-Reply-To: References: <1216792038.7380.7.camel@mmaccana-laptop> Message-ID: <1216860891.7380.14.camel@mmaccana-laptop> On Wed, 2008-07-23 at 09:13 +0200, Fredrik Lundh wrote: > http://mail.python.org/mailman/listinfo/python-list Thanks - in the midst of trying to filter out search results for every damn python 'user group' 'yahoo group' 'interest group' etc, I seem to have missed this. Thanks to the other posters too. Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjw at ncf.ca Tue Jul 29 09:50:27 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Tue, 29 Jul 2008 09:50:27 -0400 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <200807291115.05701.modelnine@modelnine.org> Message-ID: Heiko Wundram wrote: > Am Dienstag, 29. Juli 2008 11:15:05 schrieb Heiko Wundram: >> I can't dig up a simple example from code I wrote quickly... > > Just to get back to that: an example I found where "if x" (the generic > __nonzero__() test) will work to test for emptiness/non-emptiness of a > container, whereas "if len(x) > 0" (the "specific" test for this example) > will not, is my for own integer set type I wrote a while back (which you can > find on ASPN). > > The corresponding set type allows you to create infinitely sized sets of > integers (which of course are stored as pairs of ,-values, so > the storage itself for the set is bounded), for which len(x) does not have > a "proper" meaning anymore, and __len__() is limited to returning a (platform > dependent) ssize_t anyway IIRC, so even with a bounded set, the length of the > set might not necessarily be accessible using len(x); that's why the set type > additionally got a member function called .len() to work around this > restriction. > > I should think is a non-contrieved example where the generic test whether the > object considers itself True/False (which for containers means > non-empty/empty) is preferrable over the special case test whether the length > is positive. A polymorphic function, which for example only accesses the > first ten members of the container is able to work with an infinite set if it > uses the generic test, but is not in case it uses len(x) > 0. > (+1) This an Heiko's previous post sets things out clearly. Colin W. From gherron at islandtraining.com Tue Jul 29 00:18:24 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 28 Jul 2008 21:18:24 -0700 Subject: exec(code) not allowing import on top level? In-Reply-To: References: Message-ID: <488E9A10.7040208@islandtraining.com> Peter Teuben wrote: > > if I define a simple string code, with the following contents: > > import math > def foo(x): > return math.sqrt(x) What? You have not told us something important here. First, that code won't fail because it does not even execute the function foo -- it just defines it. Second, if I extended your string with one more line "foo(123)" to actually execute the code, it still works as expected. So let's try this again... and this time please please also show us the full text of the error message. Gary Herron > > and i run it using exec(code) in python, math is not known. But when I > recode the string as: > > def foo(x): > import math > return math.sqrt(x) > > it works fine. That seemed like an inconsistency, since it works > fine otherwise, as expected. It's easy to work around, but > just odd to find this out. > > thanks > > peter > -- > http://mail.python.org/mailman/listinfo/python-list From swiftone at swiftone.org Sat Jul 26 14:32:36 2008 From: swiftone at swiftone.org (Brett Ritter) Date: Sat, 26 Jul 2008 11:32:36 -0700 (PDT) Subject: Simple Path issues Message-ID: <7bef6df9-45d6-4ef6-b802-1dd201ec66e3@k30g2000hse.googlegroups.com> New to Python, and I have some questions on how to best set up a basic development environment, particular relating to path issues. Note: I am not root on my development box (which is some flavor of BSD) Where should I develop my own modules so as to refer to them in the standard way. I.E. I want: import proj to work regardless of my current working directory, and to function as if "proj" were a core or third-party module. I saw that I can set PYTHONPATH, but that seems sub-prime. I noted that in installing pysqlite (the local installation of python is 2.4) that I had it install in a lib under my home dir...should I use that locale? What is the command to tell me what directories python is checking in? While I'm at it, what is the best (read: standard) locale to stick my test cases? same dir as my project? A subdir? Thanks in advance From sturlamolden at yahoo.no Fri Jul 25 16:05:31 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 25 Jul 2008 13:05:31 -0700 (PDT) Subject: Python program as daemon? References: <8bb6bd1a-cd85-4b7a-8fc9-844f3794bca0@c58g2000hsc.googlegroups.com> Message-ID: <13866da4-01ed-4330-8297-8bdecce1393a@x35g2000hsb.googlegroups.com> On Jul 25, 8:37?pm, Johny wrote: > Is it possible to run a Python program as daemon? > Thanks Here is an example on how to run a Python script as a Unix daemon: http://svn.plone.org/svn/collective/bda.daemon/trunk/bda/daemon/daemon.py Basically it forks twice and redirects open file descriptors to /dev/ null. On Windows, 'daemons' are called services. You can write Windows services in Python using the Pywin32 extension. See Mark Hammond's book for an explanation. From afriere at yahoo.co.uk Wed Jul 16 23:05:47 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Wed, 16 Jul 2008 20:05:47 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Message-ID: <30e884cf-a52e-4d74-8e2a-fc1f185ef7c2@d45g2000hsc.googlegroups.com> On Jul 17, 8:20 am, Craig Allen wrote: > Is it pythonic? You probably can't get anymore pythonic than something written by the BDFL. In describing the use of __new__ in Unifying types and classes in Python 2.2 he gives this recipe for a Singleton. class Singleton(object): def __new__(cls, *args, **kwds): it = cls.__dict__.get("__it__") if it is not None: return it cls.__it__ = it = object.__new__(cls) it.init(*args, **kwds) return it def init(self, *args, **kwds): pass You might find this a useful starting point. From peter.anderson at internode.on.net Wed Jul 16 02:47:53 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Wed, 16 Jul 2008 16:47:53 +1000 Subject: Python internals question In-Reply-To: <487cc4bb$0$2855$ba620e4c@news.skynet.be> References: <487cc4bb$0$2855$ba620e4c@news.skynet.be> Message-ID: <008d95ab$0$15868$c3e8da3@news.astraweb.com> Helmut Jarausch wrote: > > Please have a look at > ... > http://rg03.wordpress.com/2007/04/21/semantics-of-python-variable-names-from-a-c-perspective/ > Helmut, I found the second reference (the one above) very useful thank you. Most other respondents to my original question did not seem to understand what I was asking or didn't read the question and simply proceeded to re-state what I had quoted from Beazley - well I understood what he was saying, I simply wanted to find out how Python did it at a lower level. Your reference answered the question ;-) Thanks, Peter -- Peter Anderson There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things -- Niccolo Machiavelli, The Prince, ch. 6 From mcl.office at googlemail.com Mon Jul 7 13:39:42 2008 From: mcl.office at googlemail.com (mcl) Date: Mon, 7 Jul 2008 10:39:42 -0700 (PDT) Subject: Confused yet again: Very Newbie Question References: <13be8c54-3fa9-4a37-a0e6-45bb019bff7e@a1g2000hsb.googlegroups.com> <593b44b7-9a0a-4665-9926-19890d29eabe@2g2000hsn.googlegroups.com> Message-ID: On Jul 7, 5:07?pm, Dennis Lee Bieber wrote: > On Mon, 7 Jul 2008 05:41:22 -0700 (PDT), mcl > declaimed the following in comp.lang.python: > > > My use of classes is because I want two classes one for ?global > > variables and one for global functions. > > ? ? ? ? Which seems to violate the entire reason for using "classes" (and > sounds like something that Java's syntax forces upon one). Classes (and > instances of them) are typically defined to /combine/ the class/instance > specific data and the functions that operate upon that data into a > single object. > > ? ? ? ? If you just need a container for so-called "global" data, create a > module. Same for utility functions. > > -=-=-=-=-=- ? ? ? ? ? ? myGlobalData.py > > something = 1 > else = 3 > > -=-=-=-=-=- ? ? ? ? ? ? myUtilityFuncs.py > > def weird(a, b): > ? ? ? ? return (a-b, b-a, a*b, a/b, float(a)/b) > > -=-=-=-=-=- ? ? ? ? ? ? main.py > > import myGlobalData > import myUtilityFuncs > > results = myUtilityFuncs.weird(myGlobalData.something, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? myGlobalData.else) > print results > myGlobalData.something = results[2] > > > A function may set multiple global variable values, so what is the > > best way to do this as 'return' only appears to be able to set one > > value. > > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ Dennis, Thank you for this reply. You are correct in what I was trying to do and thank you for your very good example. I will now rewrite my code changing classes to modules, which make more sense to me, even if it is not proper Python. I am much wiser about classes, but still a long way from fully comprehending when and where to best use them. Thank you all for your replies and links, as it solved my problems enough, to get some code working. Richard From nagle at animats.com Wed Jul 30 14:22:12 2008 From: nagle at animats.com (John Nagle) Date: Wed, 30 Jul 2008 11:22:12 -0700 Subject: How can I check nbr of cores of computer? In-Reply-To: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> Message-ID: <4890acd6$0$17215$742ec2ed@news.sonic.net> defn noob wrote: > How can I check how many cores my computer has? > Is it possible to do this in a Python-app? Why do you care? Python can't use more than one of them at a time anyway. John Nagle From gherron at islandtraining.com Mon Jul 21 15:20:44 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 21 Jul 2008 12:20:44 -0700 Subject: Converting List of String to Integer In-Reply-To: References: Message-ID: <4884E18C.8060302@islandtraining.com> Samir wrote: > Hi Everyone, > > I am relatively new to Python so please forgive me for what seems like > a basic question. > > Assume that I have a list, a, composed of nested lists with string > representations of integers, such that > > a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > > I would like to convert this to a similar list, b, where the values > are represented by integers, such as > > b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > I have unsuccessfully tried the following code: > > n = [] > for k in a: > n.append([int(v) for v in k]) > print n > > Does anyone know what I am doing wrong? > > Thanks in advance. > > Samir > -- > http://mail.python.org/mailman/listinfo/python-list > You didn't tell us how it failed for you, so I can't guess what's wrong. However, your code works for me: >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] >>> n = [] >>> for k in a: ... n.append([int(v) for v in k]) ... >>> print n [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] (Although you seem to have confused variables b and n.) Gary Herron From robert.kern at gmail.com Mon Jul 7 17:58:32 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 07 Jul 2008 16:58:32 -0500 Subject: Standard Equation Description Language? In-Reply-To: <1cd1baf2-9816-4ac1-91ea-90f148167549@t54g2000hsg.googlegroups.com> References: <1cd1baf2-9816-4ac1-91ea-90f148167549@t54g2000hsg.googlegroups.com> Message-ID: xkenneth wrote: > Does anyone know of a standard inter-language syntax for describing > scientific/mathematical equations? Preferably something with parsers > in multiple libraries. MathML http://www.w3.org/Math/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From alexnbryan at gmail.com Tue Jul 15 20:58:49 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 15 Jul 2008 17:58:49 -0700 (PDT) Subject: Testing for connection to a website In-Reply-To: References: <18473382.post@talk.nabble.com> <18476597.post@talk.nabble.com> Message-ID: <18478103.post@talk.nabble.com> Timothy Grant wrote: > > On Tue, Jul 15, 2008 at 3:48 PM, Alexnb wrote: > >> >> >> >> Alexnb wrote: >> > >> > Okay, I already made this post, but it kinda got lost. So anyway I need >> to >> > figure out how to test if the user is able to connect to a specific >> > website. Last time I got pointed to the urllib2 page, but if I do >> > urlopen() and and am not connected, the program stops. So I don't know >> if >> > that was what you guys wanted me to do, but I don't think so, you guys >> are >> > smarter than that. So, how can I test for connection to a website. >> > >> >> Just for anyone looking this up later here is code that works :) >> >> from urllib2 import * >> import urllib2 >> e = '' >> >> req = urllib2.Request('http://www.dictionary.com') >> try: >> response = urlopen(req) >> >> except HTTPError, e: >> print e.code >> except URLError, e: >> print e.reason >> >> if e == '': >> print "good to go" >> -- >> View this message in context: >> http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p18476597.html >> Sent from the Python - python-list mailing list archive at Nabble.com. >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > I'm glad to see you found the old post and implemented the code suggested > there. > > -- > Stand Fast, > tjg. [Timothy Grant] > > -- > http://mail.python.org/mailman/listinfo/python-list > well I can tel you it didn't work for me. In fact I didn't see the code you posted on there, I ended up figuring it out on my own with a little help from the missing manual for urllib2. Also, being rude is kinda stupid because you don't have to help in the first place... -- View this message in context: http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p18478103.html Sent from the Python - python-list mailing list archive at Nabble.com. From kyosohma at gmail.com Fri Jul 18 16:51:08 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 18 Jul 2008 13:51:08 -0700 (PDT) Subject: Writing a program under GNU/Linux for MS Windows. References: Message-ID: <492dfb6f-9bbe-48f6-935d-b68ef63784c2@e39g2000hsf.googlegroups.com> On Jul 18, 3:26?pm, Levi Campbell wrote: > Hi, I'm trying to write a program for a friend of mine who uses > windows but I use GNU/Linux. I know you can use mingw and link to the > python dll, but is there a way to create a win32 service under Linux? Technically, you can probably write the code for the service in Linux, but I doubt you could test it. Here are some links on the subject, though: http://essiene.blogspot.com/2005/04/python-windows-services.html http://agiletesting.blogspot.com/2005/09/running-python-script-as-windows.html Mike From pfreixes at gmail.com Tue Jul 1 08:25:18 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Tue, 1 Jul 2008 14:25:18 +0200 Subject: Embedding Python In-Reply-To: References: Message-ID: <207312b70807010525m3a8e3acdj352a0b3c7d1a4f7d@mail.gmail.com> Hi If PyImport_ExecCodeModule have a two parameteres and second parameter is PyObject type why you are make a call with a unsigned char value ? If you search this function name into Google you will can found some examples, use for example PyMarshal_ReadObjectFromString or PyMarshal_ReadObjectFromFile Bye On Tue, Jul 1, 2008 at 11:36 AM, Marcin Krol wrote: > Hello everyone, > > I'm trying to embed Python interpreter in C code, but in a specific way: > loading compiled bytecode into a memory location and executing it (don't > ask why, complicated reasons). > > PyImport_ExecCodeModule seems like obvious candidate, docs say: > > "Given a module name (possibly of the form package.module) and a code > object read from a Python bytecode file or obtained from the built-in > function compile(), load the module." > > Code: > > ---cut--- > #include > #include > #include > #include > #include > > > int load_file(char *fname, unsigned char** result) > { > int size = 0; > FILE *f = fopen(fname, "rb"); > if (f == NULL) > { > *result = NULL; > return -1; > } > fseek(f, 0, SEEK_END); > size = ftell(f); > *result = (unsigned char *) malloc(size+1); > fseek(f, 0, SEEK_SET); > size = fread(*result, sizeof(unsigned char), size, f); > return size; > } > > int main(int argc, char **argv) > { > int size; > unsigned char *python_code; > PyObject *mainobj; > size = load_file("multiply.pyc", &python_code); > > Py_Initialize(); > mainobj = PyImport_ExecCodeModule("multiply", (PyObject *) > python_code); > Py_Finalize(); > > } > ---cut--- > > Compiling it following way works fine: > > ${CC} testit.c -g -o testit -I/usr/include/python2.4 -lpython2.4 -lm > -lutil -lpthread -ldl -L/usr/lib/python2.4/config > > > However, the damn thing crashes on this call: > > 33 mainobj = PyImport_ExecCodeModule("multiply", (PyObject > *) python_code); > (gdb) n > > Program received signal SIGSEGV, Segmentation fault. > 0x0804e7f6 in PyImport_ExecCodeModuleEx () > > The .pyc file woks just fine in Python interpreter: > > import multiply >>>> multiply.multiply() >>>> >>> The result of 12345 x 6789 : 83810205 > 83810205 > >> >>>> > > What I am doing wrong? Please help. > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Fri Jul 25 13:07:35 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 25 Jul 2008 10:07:35 -0700 (PDT) Subject: POP3 - Using poplib only shows the first few hundred messages in the mailbox References: <503aa944-bbf6-4d86-bd98-b58adcd5a2bd@y22g2000prd.googlegroups.com> Message-ID: On Jul 25, 1:18?pm, SteveC wrote: > Hello, > > I am trying to use POP3_SSL class of the poplib module to read email > from my gmail account. ?I can connect just fine using the example herehttp://www.python.org/doc/lib/pop3-example.html > > import getpass, poplib > > M = poplib.POP3('localhost') > M.user(getpass.getuser()) > M.pass_(getpass.getpass()) > numMessages = len(M.list()[1]) > for i in range(numMessages): > ? ? for j in M.retr(i+1)[1]: > ? ? ? ? print j > > That is the above sample code from the python doc. ?While everything > works fine, the problem is that when I use the list() function it only > returns about 400 messages starting from the beginning of my inbox. ?I > have probably 10,000 emails in my gmail account. ?I don't see any pop3 > object functions to "move" around the inbox or anything of the like. > > Could someone point me in the right direction? ?I'm sure there must be > something simple I am missing. > That's a lot of emails! :-) I had a quick look at poplib.py and I couldn't see any limit in the code itself. Perhaps it's the gmail server that's doing it. Can you retrieve the later messages, eg have you tried M.retr(500)? If you can then you could just try retrieving messages beyond what M.list() says until it says there's no such message. From malaclypse2 at gmail.com Tue Jul 15 09:31:08 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 15 Jul 2008 09:31:08 -0400 Subject: Python embedding question. In-Reply-To: References: Message-ID: <16651e80807150631m1b1a5b75t34fbdbbb006b9910@mail.gmail.com> On Tue, Jul 15, 2008 at 5:51 AM, Thomas Troeger wrote: > Or is there a method to have gzipped > modules that are unzipped on the fly into memory when they're accessed? That > would be even better. Yes. See the documentation for the zipimport module, and PEP 273. http://docs.python.org/lib/module-zipimport.html http://www.python.org/dev/peps/pep-0273/ -- Jerry From sbcook at gmail.com Fri Jul 25 08:18:44 2008 From: sbcook at gmail.com (SteveC) Date: Fri, 25 Jul 2008 05:18:44 -0700 (PDT) Subject: POP3 - Using poplib only shows the first few hundred messages in the mailbox Message-ID: <503aa944-bbf6-4d86-bd98-b58adcd5a2bd@y22g2000prd.googlegroups.com> Hello, I am trying to use POP3_SSL class of the poplib module to read email from my gmail account. I can connect just fine using the example here http://www.python.org/doc/lib/pop3-example.html import getpass, poplib M = poplib.POP3('localhost') M.user(getpass.getuser()) M.pass_(getpass.getpass()) numMessages = len(M.list()[1]) for i in range(numMessages): for j in M.retr(i+1)[1]: print j That is the above sample code from the python doc. While everything works fine, the problem is that when I use the list() function it only returns about 400 messages starting from the beginning of my inbox. I have probably 10,000 emails in my gmail account. I don't see any pop3 object functions to "move" around the inbox or anything of the like. Could someone point me in the right direction? I'm sure there must be something simple I am missing. Thanks, Steve From goldfita at signalsguru.net Mon Jul 7 09:02:31 2008 From: goldfita at signalsguru.net (Todd) Date: Mon, 7 Jul 2008 06:02:31 -0700 (PDT) Subject: python mysteriously halts Message-ID: <13a33043-21d1-40c0-a938-6e905d958064@m3g2000hsc.googlegroups.com> Hello everyone, I ran a python script last night which connects to a matlab automation server via DCOM (using win32com). I expected to see the results when I came in this morning. But apparently, not long after I left, python stopped. I hit enter in the console, and it started again. I scoured the handful of lines of code to see if there was any kind of input statement put there by accident but couldn't find one. Furthermore, I've run this code many times without it pausing. It's still possible I've done something boneheaded, but I'm wondering if there is another reason (e.g. a pause in the win32com module, some kind of timeout feature if the system is idle, etc.). thank you From deets at nospam.web.de Tue Jul 22 09:30:36 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 15:30:36 +0200 Subject: regarding SWIG References: <12e21dec-b269-4c34-9492-98424d207397@w7g2000hsa.googlegroups.com> Message-ID: <6em5ppF7r22oU2@mid.uni-berlin.de> Anish Chapagain wrote: > Hi.. > I'm new to SWIG and need to create Wrapper for C code, > so, I have installed the SWIG already but doesnot know how to run it > for generating Interface file... > My C code is in message.c so what do i need to do the first > step..uisng SWIG..i read the documentation but cannot grasp creating > interface file. If it's pure C, stop using SWIG. Create a DLL/SO-file of your message.c & use ctypes to wrap that. Diez From spython01 at gmail.com Mon Jul 21 16:11:38 2008 From: spython01 at gmail.com (Samir) Date: Mon, 21 Jul 2008 13:11:38 -0700 (PDT) Subject: Converting List of String to Integer References: Message-ID: On Jul 21, 3:20?pm, Gary Herron wrote: > Samir wrote: > > Hi Everyone, > > > I am relatively new to Python so please forgive me for what seems like > > a basic question. > > > Assume that I have a list, a, composed of nested lists with string > > representations of integers, such that > > > a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > > > I would like to convert this to a similar list, b, where the values > > are represented by integers, such as > > > b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > > I have unsuccessfully tried the following code: > > > n = [] > > for k in a: > > ? ? n.append([int(v) for v in k]) > > print n > > > Does anyone know what I am doing wrong? > > > Thanks in advance. > > > Samir > > -- > >http://mail.python.org/mailman/listinfo/python-list > > You didn't tell us how it failed for you, so I can't guess what's wrong. > > However, your code works for me: > > ?>>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > ?>>> n = [] > ?>>> for k in a: > ... ? ?n.append([int(v) for v in k]) > ... > ?>>> print n > [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > (Although you seem to have confused variables b and n.) > > Gary Herron- Hide quoted text - > > - Show quoted text - Hi Gary, Thanks for your quick response (and sorry about mixing up b and n). For some reason, the logic I posted seems to work ok while I'm using the Python shell, but when used in my code, the program just hangs. It never outputs the results. Below is the code in its entirety. Is there a problem with my indendentation? a = n = [] t = """ 1 2 3 4 5 6 7 8 9 0 """ d = t.split("\n") for x in range(1,len(d)-1): a.append(d[x].split(" ")) print a for k in a: n.append([int(v) for v in k]) print n Thanks again. Samir From paul.hankin at gmail.com Thu Jul 17 05:13:08 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 17 Jul 2008 02:13:08 -0700 (PDT) Subject: Remove some characters from a string References: <35cff1a6-74f6-4a68-b81e-71d8ff9c4633@a70g2000hsh.googlegroups.com> Message-ID: On Jul 17, 9:13?am, Julien wrote: > Hi, > > I can't seem to find the right regular expression to achieve what I > want. I'd like to remove all characters from a string that are not > numbers, letters or underscores. > > For example: > > >>> magic_function('si_98%u^d at .as-*gf') > > str: 'si_98udasgf' For speed, you can use 'string.translate', but simplest is to use a comprehension: import string def magic_function(s, keep=string.ascii_letters + string.digits + '_'): return ''.join(c for c in s if c in keep) -- Paul Hankin From grante at visi.com Wed Jul 23 00:07:58 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 22 Jul 2008 23:07:58 -0500 Subject: Python Written in C? References: Message-ID: On 2008-07-23, Larry Bates wrote: >> Since you probably need an assembler anyway, generating >> assembly-language in the compiler prevents you from having to >> duplicate a bunch of object-code-generation code in two places. > > I'm not sure I understand what you mean here. The code > generation phase of the top level compiler would have to > generate assembler mnemonics instead of just generating > machine coded directly. At that point it should be just as > easy to generate machine code, unless you take advantage of > macros, or other helpers provided in the assembly phase. Generating assembly language can be a lot easier than generating machine code. One of the big advantage if you're generating assembly language is you don't have to handle relocation and address fix-up issues -- you can let the assembler and linker take care of it. Letting the linker do the final machine-code generation step also allows certain optimizations that can't really be done by the compiler. > My "compiler" work was way back on mainframes and the ones I > worked with definitely didn't produce assembler then needed to > be run through the assembler. They created likable objects > directly. There probably are plenty of compilers that do that. My background is Unix and microprocessor stuff, and it could be that for various reasons the "emit assembly" approach was more common in that genre. > But that was over 30 years ago! > > All this may be a moot point, because assembler is just a > mnemonic representations of machine language anyway. On many architectures, a particular mnemonic can end up being translated into one of several slightly different machine instructions -- for example a simple "jump" mnemonic might generate any one of several instructions depending on how far away the destination is located. If you've already got an assembler and linker than know how to deal with that stuff, then rather than duplicate the same functionality in the compiler, one might just decided to emit a "jump mnemonic" and a label. -- Grant Edwards grante Yow! Wow! Look!! A stray at meatball!! Let's interview visi.com it! From fuzzyman at gmail.com Thu Jul 3 13:41:11 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 3 Jul 2008 10:41:11 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> <9ad840e1-e12f-4125-8537-4bad2ef77f51@w5g2000prd.googlegroups.com> Message-ID: On Jul 2, 9:33?am, Ali Servet D?nmez wrote: > On Jul 1, 12:15?am, Fuzzyman wrote: > > > > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > I don't want to be so mean here, but how hard it could be be writing a > > > freesoftware which would automatically/intelligently auto complete > > > Python code? (I mean something that really does the job, like > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > name it, but just don't give me PyDev please...) > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > missing here? > > > > Could someone please point me out something that I'm really missing > > > which is already present in the wild, otherwise I'd like discuss with > > > whoever is willing to help me to get this thing done. I made my mind > > > and I could volunteer to make this happen as thesis project for my > > > incoming graduation in the next year. > > > > Regards you all, > > > Ali Servet D?nmez > > > Vim, Emacs, Wing, Komodo, ... more? > > > Yeah, I guess you're missing something. :-) > > > MichaelFoordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > I've checkout Wing IDE's license and it doesnt' seem to be a > freesoftware; am I wrong? Wing 101 is free. The software is good enough though that it is worth supporting its development by paying for it. Michael Foord -- http://www.ironpythoninaction.com/ http://www.trypython.org/ From littlesweetmelon at gmail.com Mon Jul 21 04:47:38 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Mon, 21 Jul 2008 16:47:38 +0800 Subject: What is the role of python2.6 and C++? In-Reply-To: <74c92ee2-7b89-4579-b25a-a68262e2fee7@a70g2000hsh.googlegroups.com> References: <74c92ee2-7b89-4579-b25a-a68262e2fee7@a70g2000hsh.googlegroups.com> Message-ID: > I will program larger projects in 2.5 for a while and then perhaps > look to move it to 2.6 and 2.7, I won't touch the 3.x series until it > is the common choice, much as a lot of people still program in 2.3/4. Oh, I see. It seems the gap between 2.5 and 3.0 is not so small. Therefore, even if 3.0 is released, it may take many months for porting old projects. I agree with you to wait until python 3.0 becomes common choice. Hope this day comes as soon as possible. :P -- ShenLei From Tribulations at Paralleles.invalid Mon Jul 7 05:29:16 2008 From: Tribulations at Paralleles.invalid (TP) Date: Mon, 07 Jul 2008 11:29:16 +0200 Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> <6ddj74F21uhjU1@mid.individual.net> Message-ID: Peter Otten wrote: >>>> esc = os.environ["esc"].decode("string-escape") >>>> esc > '\x1b' >>>> print "%s[30;44malles so schoen bunt hier%s[0m" % (esc, esc) > alles so schoen bunt hier Thanks a lot for your help. It works perfectly. Indeed, one can read in the documentation concerning encodings: "Produce a string that is suitable as string literal in Python source code" -- TP (Tribulations Parall?les) "Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert). From sukkopera at gmail.com Sun Jul 13 18:29:17 2008 From: sukkopera at gmail.com (sukkopera at gmail.com) Date: Sun, 13 Jul 2008 15:29:17 -0700 (PDT) Subject: Unexpected default arguments behaviour (Maybe bug?) References: <4f29ccf6-4daf-4e8e-8735-96cffd8a882e@t54g2000hsg.googlegroups.com> <475185e0-360a-452b-8d22-33ffc243b8a0@z66g2000hsc.googlegroups.com> Message-ID: <98fdc845-cb62-4e7b-891c-dfc75d741a2f@z66g2000hsc.googlegroups.com> On 13 Lug, 19:42, marek.ro... at wp.pl wrote: > I expect it's because default values for parameters are evaluated and > bound at definition time. So once "def m (self, param = a):" line > executes, the default value for parameter is forever bound to be 1. > What you can do is for example: Yes, that's what I thought, too. Although, it does not seem to me the correct thing that has to be done, that is why I reported it. Also thanks for your suggestion, that might work, even though I already have implemented a workaround (two different methods). Regards! From victorsubervi at gmail.com Tue Jul 15 08:37:47 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 15 Jul 2008 14:37:47 +0200 Subject: Simplify Code Message-ID: <4dc0cfea0807150537w1361ccabq75039886600ce9f8@mail.gmail.com> Hi; Forgive multiple posts in one day: online very infrequently I set the following variables: # Headers are kept in order to determine nesting of chapters # They are labeled according to font size h36 = '' h26 = '' h22 = '' h18 = '' h14 = '' h12 = '' header_sizes = [36, 26, 22, 18, 14, 12] # Size is the font size of the header size = 0 I write code that grabs the size var. Then I have the following very laborious spaghetti code: if size == 36: h36 = line h26 = '' h22 = '' h18 = '' h14 = '' h12 = '' elif size == 26: h26 = line h22 = '' h18 = '' h14 = '' h12 = '' elif size == 22: h22 = line h18 = '' h14 = '' h12 = '' elif size == 18: h18 = line h14 = '' h12 = '' elif size == 14: h14 = line h12 = '' elif size == 12: h12 = line else: # THROW ERROR! I would like something more elegant, like this: # del is used to determine if should reset the lower header values to '' del = 0 for header_size in header_sizes: if header_size == size: # The following line is ILLEGAL h + string(header_size) = line del = 1 if del = 1 # The following line is ILLEGAL h + string(header_size) = '' How can I rewrite those illegal lines, such that I can create the proper name for the variable, and write the necessary data? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From omer at no-log.org Wed Jul 2 10:45:21 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Wed, 2 Jul 2008 16:45:21 +0200 Subject: Trouble using pinckle In-Reply-To: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> References: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <200807021645.21312.omer@no-log.org> Le Wednesday 02 July 2008 16:09:07 Pierre-Alain Dorange, vous avez ?crit?: > Hello, > > I'm new to python and i'm deelopping a small game with pygame. > I got lot of fun with python. > > Trying to implement a config file to save user score and config. > Reading doc and some tutorial about file handling i read about pickle, > and yes it's very easy to implement. > But i thought i miss something with the roots of python. > > I implement a Prefs class to handle config data and add it a load and > save method. It works but when reading self, it OK inside the load > function but outside the pref instance return to it's previus state... > I don't really understand. > > Here's the test code : > > #!/usr/bin/env python > > import os, pickle > > kFileName='test.ini' > > class Prefs(): note that using new-style classes is recommended today: class Prefs (object) : > def __init__(self): > self.test=1 > self.zorglub='bonjour' > > def load(self): > if os.path.exists(kFileName): > try: > print 'test %d (before)' % self.test > f=open(kFileName,'r') > self=pickle.load(f) > f.close() > print 'test %d (after)' % self.test > except IOError: > return 1 > > return 0 > Here self is only a local variable and its meaning is only a convention. So assigning it to a new value won't change the object itself (and is not a good idea as it may be confusing for the reader). You should either use a static method which returns a new object: class Prefs (object) : def save (self, f) : pickle.dump(self, f) @staticmethod def load (f) : return pickle.load(f) and load it with "prefs = Prefs.load(filename)" or store all the values in a dictionary and only pickle this object: class Prefs (object) : def __init__ (self) : self.values = { 'test': 1, ... } def save (self, f) : pickle.dump(self.values, f) def load (self, f) : self.values = pickle.load(f) -- C?dric Lucantis From eckhardt at satorlaser.com Mon Jul 7 06:30:04 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Mon, 07 Jul 2008 12:30:04 +0200 Subject: How to bypass Windows 'cooking' the I/O? (One more time, please) References: Message-ID: norseman wrote: > In this case it's [MS Windows] (still) 'cooking' the writes even > with 'rwb' and O_RDWR|O_BINARY in (proper respective) use. > > Specific: python created and inspected binary file ends: > 00460: 0D 1A (this is correct) I'm not actually sure what the 0x1a is supposed to do there. The 0x0d is a '\r' which looks like a MacOS line ending, but I also seem to remember 0x1a being use as EOF signal in some old system's text files. Anyway, you mentioned some "binary file" (aren't they all?) so this might not matter after all. > after a write > os.lseek(target, -1, 2) That should be os.SEEK_END and not 2. In any case, it moves the write position to the last byte (-1 offset to the end of the file). > os.write(target,record) > the expected result would be: > 00460: 0D 20 .....data bytes.... 1A I'm sorry, but I don't see that. write() will not insert the bytes but first overwrite till EOF and then append further output, i.e. the 0x1a at the end is only present if it was present in the record. > BUT I get: > 00460: 20 .... data bytes... 1A > > It is one byte off!!! And the 0D has to be there. Signifies the end of > the header. Okay, this looks strange, both the offset and the fact that it seems to insert bytes. How about providing a minimal example? > Anyway - if whoever mentioned the flags and such to 'over ride' > Microsoft's BS would re-send that piece I would be very appreciative. You are not one with the Tao, which is why you programs don't run. ;) Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From asma61 at dsl.pipex.com Thu Jul 17 18:01:37 2008 From: asma61 at dsl.pipex.com (DaveM) Date: Thu, 17 Jul 2008 23:01:37 +0100 Subject: x, = y (???) References: Message-ID: On Thu, 17 Jul 2008 17:32:30 -0400, Terry Reedy wrote: > >>> *x, = [3] > >>> x >[3] What does *x signify? DaveM From bignose+hates-spam at benfinney.id.au Fri Jul 18 20:48:43 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 19 Jul 2008 10:48:43 +1000 Subject: Trickiness with unittesting References: Message-ID: <873am6zok4.fsf@benfinney.id.au> arockstar at gmail.com writes: > Basically, I'm trying to implement a setUp() and TearDown() for a > python TestSuite (as opposed to an individual test within the suite). > > Sort of. I think your described requirements are well met by the 'nose' extension . It lets you continue writing 'unittest' tests, but also allows you to declare setup and teardown functions at package, module, class, and function-decorator level. -- \ ?I hate it when my foot falls asleep during the day, because | `\ that means it's gonna be up all night.? ?Steven Wright | _o__) | Ben Finney From tjreedy at udel.edu Tue Jul 29 16:38:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 16:38:53 -0400 Subject: iterating "by twos" In-Reply-To: References: Message-ID: kj wrote: > Is there a special pythonic idiom for iterating over a list (or > tuple) two elements at a time? > > I mean, other than > > for i in range(0, len(a), 2): > frobnicate(a[i], a[i+1]) There have been requests to add a grouper function to itertools, but its author has resisted because there are at least three things one might do with the short remainder group left over when the group size does not evenly divide the sequence size: drop it, return it, or fill it to the requested groupsize with a dummy value and then return it. Here is a version of the first alternative. def grouper(iterable,n): '''Return items from iterable in groups of n. This version drops incomplete groups. Python 3.0''' it=iter(iterable) ranger = range(n) while True: ret = [] for i in ranger: ret.append(next(it)) yield ret for pair in grouper(range(11),2): print(pair) [0, 1] [2, 3] [4, 5] [6, 7] [8, 9] >>> From sunp1028 at gmail.com Mon Jul 14 03:24:14 2008 From: sunp1028 at gmail.com (patrol) Date: Mon, 14 Jul 2008 00:24:14 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <51cb0fe0-58f2-4f56-a59e-59986177f3d5@c65g2000hsa.googlegroups.com> Message-ID: <573962d4-ae98-4cdd-bf8d-26c22ac221f1@m3g2000hsc.googlegroups.com> On 7?14?, ??12?29?, Larry Bates wrote: > patrol wrote: > > On 7?13?, ??10?26?, Larry Bates wrote: > >> patrol wrote: > >>> I want to prevent some process from running. The code is in the > >>> following. I encounter some unexpected troubles. > >>> Probelm1: This program cannot terminate "scrcons.exe" and > >>> "FNPLicensingService.exe",which are system processes. > >>> Problem2:After a while, this program will abort by error > >>> File "C:\Python25\lib\wmi.py", line 397, in __call__ > >>> handle_com_error (error_info) > >>> File "C:\Python25\lib\wmi.py", line 190, in handle_com_error raise > >>> x_wmi, "\n".join (exception_string) > >>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > >>> 14: ordinal not in range(128) > >>> ---------------------------------------------------- > >>> code------------------------------------------------------------------------------------ > >>> # -*- coding:utf-8 -*- > >>> import pythoncom > >>> import wmi > >>> import threading > >>> import time > >>> from xml.dom.minidom import parse, parseString > >>> class Info (threading.Thread): > >>> def __init__ (self): > >>> threading.Thread.__init__ (self) > >>> def run (self): > >>> print 'In Another Thread...' > >>> pythoncom.CoInitialize () > >>> dom1 = parse('processTerminateList.xml') > >>> config_element = dom1.getElementsByTagName("processTerminateList") > >>> [0] > >>> servers = config_element.getElementsByTagName("processName") > >>> try: > >>> c = wmi.WMI () > >>> for process in c.Win32_Process (): > >>> for server in servers: > >>> if process.name == getText(server.childNodes): > >>> process.Terminate() > >>> print process.name > >>> process_watcher = c.Win32_Process.watch_for("creation") > >>> while True: > >>> new_process = process_watcher() > >>> name = new_process.Caption > >>> print name > >>> for server in servers: > >>> if name == getText(server.childNodes): > >>> new_process.Terminate() > >>> finally: > >>> pythoncom.CoUninitialize () > >>> def getText(nodelist): > >>> rc = "" > >>> for node in nodelist: > >>> if node.nodeType == node.TEXT_NODE: > >>> rc = rc + node.data > >>> return rc > >>> if __name__ == '__main__': > >>> Info().start() > >>> ------------------------------------------------------ > >>> processTerminateList.xml------------------------------------------------------------------------- > >>> > >>> > >>> scrcons.exe > >>> TXPlatform.exe > >>> mdm.exe > >>> FNPLicensingService.exe > >>> notepad.exe > >>> uedit32.exe > >>> > >> You should probably post this to comp.python.windows. Tim Golden (author of WMI > >> interface) monitors that list religously (thanks Tim). > > >> -Larry- ??????? - > > >> - ??????? - > > > I cannot find comp.python.windows.What's the URL? > > http://news.gmane.org/gmane.comp.python.windows/cutoff=7565 > > -Larry- ??????? - > > - ??????? - Thanks From __peter__ at web.de Sun Jul 13 01:32:22 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 13 Jul 2008 07:32:22 +0200 Subject: filtering keyword arguments References: <633d6159-7803-4d9b-8f16-2a4a0a197a86@t54g2000hsg.googlegroups.com> Message-ID: Amir wrote: > How do you filter keyword arguments before passing them to a function? > > For example: > > def f(x=1): return x > > def g(a, **kwargs): print a, f(**kwargs) > > In [5]: g(1, x=3) > 1 3 > > In [6]: g(1, x=3, y=4) > TypeError: f() got an unexpected keyword argument 'y' > > Is there a way to do something like: > > def g(a, **kwargs): print a, f(filter_rules(f, **kwargs)) > > so only {'x': 3} is passed to f? I think you have to come up with something yourself. Here's a start: import inspect def filter_kw(f, **kw): names = inspect.getargspec(f)[0] return dict((n, kw[n]) for n in names if n in kw) Peter From utkualtinkaya at gmail.com Mon Jul 14 06:15:05 2008 From: utkualtinkaya at gmail.com (Utku Altinkaya) Date: Mon, 14 Jul 2008 03:15:05 -0700 (PDT) Subject: RPC Client acts like a server Message-ID: <1ae49371-ce95-469b-bc09-1c189bfa737c@c58g2000hsc.googlegroups.com> Hello, I need a client that connects to the server and answers remote calls. Is there a way to dot that using sandart xmlrpclib ? Currently I am using Remote Python Call library, but looking for alternative solutions as well. regards From bronger at physik.rwth-aachen.de Thu Jul 24 11:39:28 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 24 Jul 2008 17:39:28 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> Message-ID: <87zlo747gv.fsf@physik.rwth-aachen.de> Hall?chen! Bruno Desthuilliers writes: > Torsten Bronger a ?crit : > >> Bruno Desthuilliers writes: >> >>> [...] >>> >>> How would you handle this case with an implicit 'self' : >>> >>> class Foo(object): >>> pass >>> >>> def bar(self): >>> print self >>> >>> Foo.bar = bar >> >> Just like this. However, the compiler could add "self" to >> non-decorated methods which are defined within "class". > > What's defined within classes are plain functions. It's actually > the lookup mechanism that wraps them into methods (and manage to > insert the current instance as first argument). And why does this make the implicit insertion of "self" difficult? I could easily write a preprocessor which does it after all. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From bedouglas at earthlink.net Mon Jul 21 16:18:27 2008 From: bedouglas at earthlink.net (bruce) Date: Mon, 21 Jul 2008 13:18:27 -0700 Subject: Trying to solve a python/mechanize "error 500" http error Message-ID: <24da01c8eb6e$ef9ea2a0$0301a8c0@tmesa.com> i'm getting the following error: mechanize._response.httperror_seek_wrapper: HTTP Error 500: i'm running python 5.1 and mechanize 0.1.7b I have no idea as to what I have to change/modify/include to handle this issue. The link that I'm testing is at the bottom of the page. When I insert the link into the browser, I actually get an err page.. so, I suspect that there is a handler that I should be able to modify/use to handle this situation... Thoughts/Comments will be greatly appreciated... Thanks the output is: www = www.1800ink.com url2= http://www.quantcast.com/www.1800ink.com/traffic Traceback (most recent call last): File "./reseller_scrape_child.py", line 288, in q1 = shopfuncs.quant(rhref) File "/adkiller/shopfuncs.py", line 56, in quant br.open(url2) File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 203, in open File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 254, in _mech_open mechanize._response.httperror_seek_wrapper: HTTP Error 500: [root at toshiba adkiller]# ./reseller_scrape_child.py my code segment looks like: ==================================== from mechanize import Browser import mechanize br = Browser() user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values1 = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } #br.set_cookiejar(cj) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.addheaders = [('User-Agent', 'Firefox')] url2 ="http://www.quantcast.com/xxxx/traffic" #gets the page (url) from the quantcast app url2=url2.replace("xxxx",url) print "url2=",url2 br.open(url2) ======================================= this works ok for most of the sites.. but something weird is happening with the actual page: http://www.quantcast.com/www.1800ink.com/traffic thanks... From larry.bates at websafe.com` Tue Jul 29 18:47:21 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 29 Jul 2008 17:47:21 -0500 Subject: Python COM In-Reply-To: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> References: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> Message-ID: birdprince at gmail.com wrote: > I have implemented a COM in C++,buy i don't know how to use this COM > in python. > For example: the COM's ProgID is "MyCOM1.AdvMethod".this COM have two > interfaces,the default interface's name is IAdvMethod,the second > interface's name is IBasicMethod. > How do i use those interfaces in python.Thank you very much,please > answer my question in code. Suggestion: Post this to comp.python.windows instead of here. I think you will find that a better place for this question. -Larry From max at alcyone.com Wed Jul 30 22:05:48 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Jul 2008 19:05:48 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > On Jul 30, 1:07 am, Erik Max Francis wrote: >> Russ P. wrote: >>> Oh, Lordy. I understand perfectly well how boolean tests, __len__, and >>> __nonzero__ work in Python. It's very basic stuff. You can quit >>> patronizing me (and Carl too, I'm sure). >> You suggested a syntax for testing non-emptiness (`x is not empty`) >> which indicated a profound misunderstanding of what the `is` operator does. >> >> You then acknowledged that there might be a problem because of the >> implication if the `is` operator and weren't sure whether it would work >> or not: > > Oh, my. I wrote something like, "It would sure be nice to be able to > write > > if x is not empty: > > because it reads like natural language. Immediately after I posted it, > I thought, "oh, I'll bet some idiot takes that as a serious proposal." > Sure enough, some idiot did just that almost immediately. Yes, all people are idiots for reading what you wrote, reading your later realization that it was wrong, and taking both at face value. I'll be sure never to make that mistake again! > And he is > still patronizing me for it. No, I'm not patronizing you for your initial misstatement. I'm mocking you for your pathetic and transparent attempt to backpedal away from it. Just give it up, already. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Drifting from woman-who-tries misconstrued / Shifting to woman-wise -- Lamya From murugesan550 at gmail.com Thu Jul 24 23:18:56 2008 From: murugesan550 at gmail.com (muruges) Date: Thu, 24 Jul 2008 20:18:56 -0700 (PDT) Subject: .............................on line jobs........................................ Message-ID: we are selecting you for this online jobs. For more information see this website in this.............................. we are selecting you for this online jobs. For more information see this website in this.............................. Details .................. Name of the job.........................Online job.......................... Nature of work...........................Like data entry.......................... Qualification required........................good knowledge in computer Basics Earnings................More then Rs=1000 per day......................Earnings depends on your work............................. FOR MORE DETAILS: WWW.Bigconstructions5.blogspot.com From grflanagan at gmail.com Wed Jul 30 11:49:44 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Wed, 30 Jul 2008 17:49:44 +0200 Subject: ANN: Google custom search engine for Python Message-ID: What is it? ----------- A Google custom search engine which targets only the following sites: + `The Hazel Tree `__ + `The Python standard library docs `__ + `The Python wiki `__ + `Python Package Index `__ Where can I access it? ---------------------- The home page of the search engine is here: http://www.google.com/coop/cse?cx=002031040340806163079:nkigkp_irqk As well as accessing it from its home page, you can link to it from your own web sites, or add it as a gadget to your Google home page (if you have one) - see the above link for details. No ads ------ `The Hazel Tree `__ is a not-for-profit site and no ads will appear in the search results. Using refinements ----------------- To refine the search to any of the individual sites, you can specify a refinement using the following labels: stdlib, wiki, pypi, thehazeltree So, to just search the python wiki, you would do: somesearchterm more:wiki and similarly: somesearchterm more:stdlib somesearchterm more:pypi somesearchterm more:thehazeltree About http://thehazeltree.org ----------------------------- `The Hazel Tree `__ is a collection of popular Python texts that I have converted to reStructuredText and put together using `Sphinx `__. It's in a publishable state, but not as polished as I'd like, and since I'll be mostly offline for the next month it will have to remain as it is for the present. However, the search engine is ready now and the clock is ticking on its subscription (one year, renewal depending on success of site), so if it's useful to anyone, it's all yours (and a link back to http://thehazeltree.org would be appreciated). Cheers, G. From tjreedy at udel.edu Tue Jul 15 16:50:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Jul 2008 16:50:30 -0400 Subject: Modify a string's value In-Reply-To: References: Message-ID: s0suk3 at gmail.com wrote: > Hi everyone, > > I've heard that a 'str' object is immutable. But is there *any* way to > modify a string's internal value? In 3.0, ascii chars and encoded unicode chars in general can be stored in a mutable bytearray. From digetl.try at gmail.com Sat Jul 26 06:03:10 2008 From: digetl.try at gmail.com (raja) Date: Sat, 26 Jul 2008 03:03:10 -0700 (PDT) Subject: How I Lost My Belly Fat Message-ID: I fought with excess belly fat for years until I found this 1 trick. http://food-drinks.page.tl/ From deacon.sweeney at gmail.com Tue Jul 8 12:44:04 2008 From: deacon.sweeney at gmail.com (Deacon) Date: Tue, 8 Jul 2008 09:44:04 -0700 (PDT) Subject: plugins using cvs/distutils? Message-ID: Hi. I have an open-source application development environment that I would like to enable an automated package download system for (like downloadable plugins), using sourceforge as its repository. My software will have a menu-based popup window, that will list the packages (Applications) available through the project distribution page. If a user selects a package from this window, it should be automatically retrieved and installed by the development environment. My software already has a system for automatically recognizing and deploying new packages, so I'm only asking for help with distribution logistics, I think. I'm thinking that I will use the built-in ftplib to list and retrieve the files (but I'm not sure yet where to look), and then the distutils should probably be used in a standardized manner to actually install the packages, right? I've established a CVS, but I'm not aware of any built-in-python tools for managing the CVS, and I would rather not add any new user-has-to-download-dependencies for this. Is there an easier or alternative advisable approach? I have a linux box, should I be using it to build all of the platform versions? Any advice would be much appreciated, this is my first distribution project (sourceforge.net/projects/spade). Thanks a bunch, Deacon From pythonnutter at gmail.com Thu Jul 3 18:56:32 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Fri, 4 Jul 2008 08:56:32 +1000 Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: <1020285372.957161215116648910.JavaMail.root@saturn.datasyncintra.net> References: <552487307.956521215116093518.JavaMail.root@saturn.datasyncintra.net> <1020285372.957161215116648910.JavaMail.root@saturn.datasyncintra.net> Message-ID: If you guys can get your head out of IDE land, you'll find iPython does a fantastic job at introspection and Auto-completion, you can launch shell commands and editors and when done saving be back in the iPython shell, save memory/variable space to disk so you can come back the next day and continue off where you were. It puts IDEs to shame. If you can't get your Windows-centric IDE need eliminated, then Wing IDE 101 will not auto-complete, its been deliberately disabled to force students (hence 101) to memorize python/function names. Komodo Edit is a free download and will Auto-complete. Cheers, PN From norseman at hughes.net Wed Jul 16 13:11:42 2008 From: norseman at hughes.net (norseman) Date: Wed, 16 Jul 2008 10:11:42 -0700 Subject: How to figure out if the platform is 32bit or 64bit? Message-ID: <487E2BCE.30108@hughes.net> > > I need to know if I'm running on 32bit or 64bit ... so far I haven't > > come up with how to get this info via python. sys.platform returns > > what python was built on ... but not what the current system is. > > > > I thought platform.uname() or just platform.processor() would have > > done it, but python returns an empty string on windows. Any ideas? > > > > Thanks, Ken =========================================== From what I'm reading I think the answer lies in being able to see Microsoft's OS 'About' statement. One of the Python guru's should be able to supply the code. On Linux you should be able to uname -m and get a pretty good idea. See man uname. something like: #contents of t.py #----------- import os zstatflg= os.system("uname -m") #----------- EOF --- then: python t.py i686 (I'm running a stock Python 2.5.2) If the Python itself was compiled 32 bit and installed on a 64 bit machine that runs 32 bit code (like most all do during transition times) then all attempts with Python to check itself will return 32 bit responses. Using math and/or 'kibitz' (cheater text) will be useless. Hope this helps; Steve norseman at hughes.net From bearophileHUGS at lycos.com Mon Jul 14 07:48:22 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 14 Jul 2008 04:48:22 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> <792048c1-5e18-4a2c-925d-a1c932d18a91@j22g2000hsf.googlegroups.com> <8923d0c5-29ce-495f-924a-6d9d2457138e@e39g2000hsf.googlegroups.com> Message-ID: <8933b108-45b4-438d-87d8-aad92a15188b@e53g2000hsa.googlegroups.com> Larry Bates: > The only case where it would be faster would be if most of the keys were NOT in > the dictionary (rather odd use case). Otherwise I believe you will find the > first way quicker as the exceptions are infrequent. I have written a small benchmark: from random import shuffle def test1(data, to_delete): for item in to_delete: try: del data[item] except KeyError: pass def test2(data, to_delete): for item in to_delete: if item in data: del data[item] N = 1000000 M = 2 * N data = dict.fromkeys(xrange(N), 0) to_delete = range(M) shuffle(to_delete) from timeit import default_timer as clock t = clock() #test1(data, to_delete) # 2.4 s test2(data, to_delete) # 0.8 s print round(clock() - t, 2), "s" It creates a dictionary of the first million integers, and then tries to delete the first two million of integers. So about 1/2 numbers are present to be deleted. In this situation the version with the try- except seems about 3 times slower than the other. Bye, bearophile From bignose+hates-spam at benfinney.id.au Tue Jul 15 06:45:37 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 15 Jul 2008 20:45:37 +1000 Subject: Testing for Internet Connection References: Message-ID: <87bq0z8lym.fsf@benfinney.id.au> Alexnb writes: > I am wondering, is there a simple way to test for Internet > connection? If not, what is the hard way :p Refine the question: What do you mean by "internet"? It isn't a single entity. Do you mean "some particular internet host responding on a particular network port"? If you can define exactly what you mean by "internet connection", the test for it becomes correspondingly easier. -- \ ?Why should I care about posterity? What's posterity ever done | `\ for me?? ?Groucho Marx | _o__) | Ben Finney From circularfunc at gmail.com Sun Jul 6 17:47:40 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 6 Jul 2008 14:47:40 -0700 (PDT) Subject: Very weird bug! Message-ID: <1c1c343a-dd63-454a-8e29-a5c70281ad90@c58g2000hsc.googlegroups.com> I was looking into currying and Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.2.2 >>> h = "aja baja" >>> h += 'e' >>> h 'aja bajae' >>> h = h+'a' >>> h 'aja bajaea' >>> a = b = "foo" >>> a 'foo' >>> b 'foo' >>> a==b True >>> id(a) 35018400 >>> id(b) 35018400 >>> a += "bar" >>> id(a),a (35110112, 'foobar') >>> id(b),b (35018400, 'foo') >>> fac Traceback (most recent call last): File "", line 1, in fac NameError: name 'fac' is not defined >>> factorial Traceback (most recent call last): File "", line 1, in factorial NameError: name 'factorial' is not defined >>> import math >>> math >>> math.factorial Traceback (most recent call last): File "", line 1, in math.factorial AttributeError: 'module' object has no attribute 'factorial' >>> math.fac Traceback (most recent call last): File "", line 1, in math.fac AttributeError: 'module' object has no attribute 'fac' >>> dir(math) ['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] >>> pow >>> tan Traceback (most recent call last): File "", line 1, in tan NameError: name 'tan' is not defined >>> math.tan >>> def build(a,b): return a+b >>> build(5,4) (5, 4) >>> def build(x,y): a=x+y return a >>> build(5,4) 9 >>> def b(n, p): return n + p >>> b(1, 10) 11 >>> def b(n,p): return n+p >>> b(5,2) 7 >>> def build(x,y): return a+b >>> build(5,4) Traceback (most recent call last): File "", line 1, in build(5,4) File "", line 2, in build return a+b TypeError: cannot concatenate 'str' and 'function' objects >>> def build(x,y): yreturn x+ SyntaxError: invalid syntax >>> def build(x,y): return x+y >>> build(5,4) 9 >>> def build(a,b): return a+b >>> build(5,4) 9 >>> wtf was this in the middle!? >>> def build(a,b): return a+b >>> build(5,4) (5, 4) From bob.martin at excite.com Fri Jul 25 05:56:48 2008 From: bob.martin at excite.com (Bob Martin) Date: Fri, 25 Jul 2008 09:56:48 GMT Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> Message-ID: in 75186 20080725 050433 Tim Roberts wrote: >castironpi wrote: >> >>Compiling a program is different than running it. A JIT compiler is a >>kind of compiler and it makes a compilation step. I am saying that >>Python is not a compiler and in order to implement JIT, it would have >>to change that fact. > >And I'm saying you are wrong. There is NOTHING inherent in Python that >dictates that it be either compiled or interpreted. That is simply an >implementation decision. The CPython implementation happens to interpret. >The IronPython implementation compiles the intermediate language to native >machine language. > >>> of Python that uses .NET. In that case, the code *IS* JIT compiled to >>> assembly when the program starts. >> >>But still not the user's code, only the interpreter, which is running >>in assembly already anyway in CPython. > >In CPython, yes. In IronPython, no; the user's code is compiled into >machine language. Both of them are "Python". >-- >Tim Roberts, timr at probo.com >Providenza & Boekelheide, Inc. It's amazing how many people cannot differentiate between language and implementation. How many times have I read "x is an interpreted language"? I know many languages are designed for either compilation or interpretation, but I have used C and Pascal interpreters as well as Java and Rexx compilers. From metaperl at gmail.com Tue Jul 15 14:56:59 2008 From: metaperl at gmail.com (E. J. Gold is the Hi-Tech Shaman) Date: Tue, 15 Jul 2008 11:56:59 -0700 (PDT) Subject: graphing lifelines Message-ID: (crossposted to sci.math) I'm looking for a tool which will take a dataset of tuples indicating the year of birth and death of a person: (1872, 1950, "Sri Aurobindo") (1821, 1910, "Mary Baker Eddy") (1831, 1891, "HP. Blavatksy") And graph them out, in bars, annotating them with the person's name. A simple spreadsheet would've worked, but they seem to start from zero. Thus, I would only be able to indicate the span of life (by subtracting death year from birth year). From kak at purdue.edu Sat Jul 12 14:28:33 2008 From: kak at purdue.edu (Avi Kak) Date: Sat, 12 Jul 2008 11:28:33 -0700 (PDT) Subject: fix for wxPython incompatibility of BitTornado 0.3.18 Message-ID: If you are unable to use the wxPython-based GUI interfaces in the BitTornado 0.3.18 library on your Ubuntu 8.04 machine, you may wish to download a directory of the library available through http://cobweb.ecn.purdue.edu/~kak/distbt/ If any problems, send me email at kak at purdue.edu with "BitTornado" in the subject line to get past my procmail filter. Avi Kak From Graham.Dumpleton at gmail.com Fri Jul 18 09:06:00 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Fri, 18 Jul 2008 06:06:00 -0700 (PDT) Subject: Problem with MySQLdb and mod_python References: <48802594$0$17225$742ec2ed@news.sonic.net> Message-ID: <1d9296bb-9288-40ec-a9fc-b0048a6f20d5@z6g2000pre.googlegroups.com> On Jul 18, 3:28?pm, John Nagle wrote: > Cyril Bazin wrote: > > Thanks for your reply > > > The apache log contains lines like : > > > [Tue Jul 15 23:31:01 2008] [notice]mod_python(pid=11836, > > interpreter='www.toto.fr'):Importing module > > '/usr/local/apache2/htdocs/intranet/courrier/test.py' > > [Tue Jul 15 23:31:02 2008] [notice] child pid 11836 exit signal > > Segmentation fault (11) > > [Tue Jul 15 23:31:19 2008] [notice]mod_python(pid=11764, > > interpreter='www.toto.fr'):Importing module > > '/usr/local/apache2/htdocs/intranet/courrier/test.py' > > [Tue Jul 15 23:31:19 2008] [notice] child pid 11764 exit signal > > Segmentation fault (11) > > > I think the problem comes from the MySQLdb module. > > If I can't find another solution, I think I will downgrade the MySQLdb > > version to 1.2.1 > > ? ? Sounds like version hell. ?mod_python and MySQLdb have to be > compiled with exactly the same compiler for this to work. Use of compatible compilers applies to anything you want to use together. This is nothing specific to mod_python, so this comment is a bit misleading. These days with with GNU C everywhere, it is hardly and issue, and was usually only an issue with C++ code and not C code anyway. > ? ?mod_python is usually troublesome. ? Python doesn't really have > quite enough isolation to run multiple unrelated instances reliably. The isolation issue is nothing to do with Python itself. Isolation is an issue in this case, but most likely comes about because the OP is trying to use both PHP and mod_python together in the same Apache instance. In particular, the PHP package is likely loading a MySQL module and it is linked against a different version of the MySQL client libraries than what the Python MySQL package is wanting. People like to blame mod_python for these problems, but it can equally be attributed to PHP. In practice the reason it shows up as a mod_python issue is that PHP tries to preload a lot of stuff and so manages to load its version of shared libraries first. Python with its lazy loading comes in second, and so conflicts will occur. If mod_python preloaded stuff like PHP did and this was occurring before PHP got a chance, it would be the other way around and mod_python would work fine and PHP would instead be what crashes all the time. > We use FCGI, which has the isolation of CGI but doesn't reload the > application for every transaction. ?Also, it's easier to debug if > CPython is crashing. With the reason that FCGI works being that the processes, even if they are spawned by Apache, use a fork/exec, thus meaning they have a clean memory space when starting up. In summary, look at what version of MySQL libraries are used by PHP modules and ensure that Python MySQL module is compiled against the same version. Graham From arslanburney at gmail.com Wed Jul 2 09:00:25 2008 From: arslanburney at gmail.com (J-Burns) Date: Wed, 2 Jul 2008 06:00:25 -0700 (PDT) Subject: Using Gnuplot and making an exe file outv the prog Message-ID: Hello. Been using the gnuplot lately. Program runs fine. And its plots as well. Now i want to make an exe file out of this program using py2exe. Cud some1 help me in telling me how this is done. Thnks From mail at timgolden.me.uk Thu Jul 24 11:07:43 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 24 Jul 2008 16:07:43 +0100 Subject: Python / PAMIE In-Reply-To: References: Message-ID: <48889ABF.3080006@timgolden.me.uk> frankrentef wrote: > Can someone help with a PAMIE issue? I'm new to Python / PAMIE and > they seem like great tools but to be honest I'm finding that no > responses to questions can be found (Experts Exchange, etc.) I'm > hoping this will be the place. > > I tried to duplicate the authors "ie.writeScript" function shown at > > http://showmedo.com/videos/video?name=pythonMarchettiPamie3&fromSeriesID=25 I'd rather you posted the code you've tried. I'm not too keen on viewing a video just to get hold of a piece of code, and in any case that would only show me what the author's done. We need to see what you've done, and what the traceback was. Would you mind posting some code, please? Thanks TJG From kkwweett at hotmail.fr Wed Jul 2 16:26:06 2008 From: kkwweett at hotmail.fr (kkwweett) Date: Wed, 02 Jul 2008 22:26:06 +0200 Subject: wrong md5 checksum In-Reply-To: <2-CdnaVu6892xvfVnZ2dnUVZ_gGdnZ2d@supernews.com> References: <486a16ef$0$885$ba4acef3@news.orange.fr> <486a5316$0$864$ba4acef3@news.orange.fr> <2-CdnaVu6892xvfVnZ2dnUVZ_gGdnZ2d@supernews.com> Message-ID: <486be45d$0$859$ba4acef3@news.orange.fr> > > A. an error in the software that computed the value for the web page, > B. a transcription error in putting the checksum on the web page, > C. accidental corruption of the file, or > D. a deliberate attempt to substitute a file with a similar MD5 sum. > It seems that the answer is probably B. But, according to the release website manager, a mystery remains : http://mail.python.org/pipermail/python-3000/2008-July/014281.html From BruceP at wn.com.au Wed Jul 16 00:03:22 2008 From: BruceP at wn.com.au (Bruce Pearson) Date: Wed, 16 Jul 2008 12:03:22 +0800 Subject: Is this correct behavior for default parameters? Message-ID: <344469045.20080716120322@wn.com.au> The first call to test has the file_list empty but on the second call to test the file_list is no longer empty but contains the values appended in the first call. Is this correct behavior? I'm using python 2.5 def test(param_1, file_list = []): if len(file_list) == 0: print "Empty list" file_list.append("list item 1") file_list.append("list item 2") else: raise if __name__ == "__main__": test(1) test(2) -------------- next part -------------- An HTML attachment was scrubbed... URL: From upton at virginia.edu Mon Jul 21 14:05:49 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 21 Jul 2008 14:05:49 -0400 Subject: Python Written in C? In-Reply-To: <6ejutcF6vgp3U4@mid.uni-berlin.de> References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> Message-ID: <5504f9ac0807211105h4604d332y5671243cb34abfc6@mail.gmail.com> On Mon, Jul 21, 2008 at 1:21 PM, Marc 'BlackJack' Rintsch wrote: > On Mon, 21 Jul 2008 18:12:54 +0200, mk wrote: > >> Seriously, though, would there be any advantage in re-implementing >> Python in e.g. C++? >> >> Not that current implementation is bad, anything but, but if you're not >> careful, the fact that lists are implemented as C arrays can bite your >> rear from time to time (it recently bit mine while using lxml). Suppose >> C++ re-implementation used some other data structure (like linked list, >> possibly with twists like having an array containing pointers to 1st >> linked list elements to speed lookups up), which would be a bit slower >> on average perhaps, but it would behave better re deletion? Aside (actual reply below): at least for a sorted LL, you're basically describing Henriksen's algorithm. They can asymptotically be faster, based on amortized analysis, but they're somewhat more complicated to implement. > > An operation that most people avoid because of the penalty of "shifting > down" all elements after the deleted one. Pythonistas tend to build new > lists without unwanted elements instead. I can't even remember when I > deleted something from a list in the past. > > Ciao, > Marc 'BlackJack' Rintsch The other side of the equation though is the OO-overhead for C++ programs as compared to C. (A couple years ago we used an instrumentation tool to check the instruction count for a simple hello world program written in C (ie, main(){printf("Hello world!"); return 0;}) and Python (main(){cout<<"hello world"< Message-ID: On 20 Jul., 13:08, bearophileH... at lycos.com wrote: > Kay Schluehr: > > > Sure, use a fixed point combinator. I've just added this recipe: > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/576366 > > Does it work? > > Bye, > bearophile There are lots of informal derivations of the Y combinator on the web. I used one a while ago and translated the result into Python. So if there isn't an implementation bug it shall work. I added two examples for illustration purposes. From mail at timgolden.me.uk Fri Jul 4 09:25:57 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 04 Jul 2008 14:25:57 +0100 Subject: Recursive wildcard file search In-Reply-To: <496954360807031353n4f91f691recb330f7350cbf70@mail.gmail.com> References: <496954360807031353n4f91f691recb330f7350cbf70@mail.gmail.com> Message-ID: <486E24E5.8090000@timgolden.me.uk> [sorry; this got stuck in my outbox] Robert Dailey wrote: > Is there a way to perform a recursive file search using wildcards in > python 3.0b1? > > For example, if I have: > > C:\foo\abc*xyz.* > > I want all files in C:\foo and all subfolders (recursively) of C:\foo > that match the wildcard abc*xyz.* to be matched. In the end, I want a > list of files that matched the search, as well as the directory they're > located in. I haven't checked but I doubt this has changed from Python 2.x. Just use os.walk and filter on what you want. Vaguest and most untested code sample: import os import fnmatch ROOT = "c:/temp" PATTERN = "*c*.zip" filepaths = [] for dirpath, dirnames, filenames in os.walk (ROOT): filepaths.extend ( os.path.join (dirpath, f) for f in fnmatch.filter (filenames, PATTERN) ) If you need to match on directory names as well, then you'd have to adjust accordingly. TJG From bockman at virgilio.it Fri Jul 11 09:29:13 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Fri, 11 Jul 2008 06:29:13 -0700 (PDT) Subject: read file into list of lists References: Message-ID: <4570e246-3b36-469e-b1b0-f4c547fe079b@c65g2000hsa.googlegroups.com> On 11 Lug, 15:15, antar2 wrote: > Hello, > > I can not find out how to read a file into a list of lists. I know how > to split a text into a list > > sentences = line.split(\n) > > following text for example should be considered as a list of lists (3 > columns and 3 rows), so that when I make the print statement list[0] > [0], that the word pear appears > > pear noun singular > books nouns plural > table noun singular > > Can someone help me? > > Thanks You can use split again, using ' ' or nothing(defaults to whitespace characters) as separator, like this: >>> text = """pear noun singular books nouns plural table noun singular""" >>> words = [ x.split() for x in text.split('\n') ] >>> print words [['pear', 'noun', 'singular', ''], ['books', 'nouns', 'plural', ''], ['table', 'noun', 'singular']] Ciao ----- FB From mal at egenix.com Sat Jul 26 14:32:39 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Sat, 26 Jul 2008 20:32:39 +0200 Subject: Gracefull application exit. In-Reply-To: <488B6D2E.2040403@egenix.com> References: <00ba01c8eda7$2e61ecb0$8b25c610$@rawlins@thinkbluemedia.co.uk> <488B6D2E.2040403@egenix.com> Message-ID: <488B6DC7.2030809@egenix.com> On 2008-07-26 20:30, M.-A. Lemburg wrote: > On 2008-07-24 18:06, Robert Rawlins wrote: >> Chaps, >> >> >> >> I'm looking to implement an exit/termination process for an application >> which can be triggered by A) a keyboard interrupt or B) termination of >> the >> application as a Daemon using a signal. >> >> >> >> I have a whole bunch of tasks I want to perform as a cleanup before the >> application is terminated, cleaning files, database calls, closing open >> connections and a few other things. >> >> >> >> I know we have: >> >> >> >> # I'm the main application started method. >> >> if __name__ == "__main__": >> >> >> >> For starting an application, but do we have an equivalent methods for >> when >> an application is terminated which we can use to close down any current >> internal processes before the application exits? >> >> >> >> I'd really love to have your thoughts and experience on gracefully >> killing >> an application. > > Wrap your whole application into a main() function and then use: > > try: > main() > finally: > cleanup() > BTW: In order to catch signals, you'll have to install signal handlers which then raise Python exceptions, e.g. SystemExit. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 26 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From mail at timgolden.me.uk Wed Jul 9 06:05:40 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 09 Jul 2008 11:05:40 +0100 Subject: Newbie question In-Reply-To: References: <3b1e6f480807082337l419fd40ax91eaf13e0701c5b3@mail.gmail.com> Message-ID: <48748D74.8090701@timgolden.me.uk> A.T.Hofkamp wrote: > On 2008-07-09, |e0 wrote: >> So, i can't use wmi module on linux? >> >> On Wed, Jul 9, 2008 at 9:14 AM, Lamonte Harris wrote: >>> I think the win32 module is only for windows. >>> > > Welcome to the world outside MS. > > Many python modules don't actually do anything than passing on calls to an > existing underlying library. They are cheap to make, and make it possible to > use the functionality of the library from a Python program. The down-side is, > as you have discovered, that you need the underlying library to make it work. And this is of course true both ways. Python users under Windows miss out on about half [*] of the os module since it's just handing off to the *nix system calls. At the same time, *nix users won't be able to add Shell Namespace Extensions or use the Windows API to monitor directory changes. > So, the answer is no, you cannot use wmi under a non-MS OS. (But what did you > expect, given that wmi means WINDOWS Management Instrumentation?) I don't know if anyone's tried to get something like WMI running under Wine. In principal it might work but I suspect it would involve a lot of time and effort. Strictly, WMI is an implementation of the WBEM [2] standards. Googling around suggests that implementations exist for Linux but I've no idea how mature or robust they are, and I'm quite sure they're not going to be using a Windows API model for their interface. TJG [1] A pardonable exaggeration [2] http://www.dmtf.org/standards/wbem/ From petite.abeille at gmail.com Thu Jul 24 14:07:26 2008 From: petite.abeille at gmail.com (Petite Abeille) Date: Thu, 24 Jul 2008 20:07:26 +0200 Subject: instance comparison In-Reply-To: References: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> <4888879a$0$1043$426a74cc@news.free.fr> Message-ID: On Jul 24, 2008, at 7:53 PM, King wrote: > The the class is not subclass of another one. Problem still persist. > The code is pretty huge and I am trying to post the information as > clear as possible. Mark V. Shaney, from Dissociated Press, I presume? -- PA. http://alt.textdrive.com/nanoki/ From mccredie at gmail.com Wed Jul 23 10:55:50 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 23 Jul 2008 07:55:50 -0700 (PDT) Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: On Jul 22, 2:02?pm, ptn wrote: > Hi everybody, > > I have a weird problem. ?Say I have a .py file with some functions in > it, like this: > > ? ? # (...) > ? ? def foo(): > ? ? ? ? print("bar") > > When I open it and add a line to one of the functions, > > ? ? # (...) > ? ? def foo(): > ? ? ? ? troz = "bar" > ? ? ? ? print(troz) > > I get the following traceback from the interpreter: > > ? ? Traceback (most recent call last): > ? ? ? File "SOMEWHERE/example.py", line ?? > ? ? ? ? troz = "bar" > ? ? ? ? ? ? ? ? ? ? ? ? ? ^ > ? ? IndentationError: unindent does not match any outer indentation > level > > And so I'm forced to rewrite the function entirely just to add the new > line. > > I thought that my problem was the w option from formatoptions, so I > changed my .vimrc file to this: > > ? ? augroup filetype > ? ? ? autocmd BufNewFile,BufRead *.txt set filetype=human > ? ? augroup END > ? ? autocmd FileType human setlocal formatoptions+=ta2w > ? ? autocmd FileType lisp,scheme,python,c,java,vim setlocal > formatoptions-=ta2w > > But the problem didn't go away. ?I don't think this has anything to > do > with the tabs and spaces, because I have them set up like this: > > ? ? set tabstop=4 shiftwidth=4 expandtab > > which is the standard way to handle them. > > The scripts I load are: qbuf, TagList, indent/python.vim and a reduced > version of the standard python.vim > > Could someone provide some pointers? > > Thanks, > > Pablo Torres N. That isn't the standard. With that setup tabs will show up as 4 spaces, and still confuse you. You want this: set shiftwidth=4 set tabstop=8 set softtabstop=4 set expandtab tab characters in the file will show up as 8 characters long (which is how the python interpreter sees them also) but pressing tab will insert 4 spaces. Matt From tjreedy at udel.edu Wed Jul 30 11:07:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jul 2008 11:07:03 -0400 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <7f4a3d37-e551-4e21-b660-3618016cb67b@z6g2000pre.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> <7f4a3d37-e551-4e21-b660-3618016cb67b@z6g2000pre.googlegroups.com> Message-ID: Carl Banks wrote: > That's not what I was asking for. I was asking for a use case for "if > x" that can't be replaced by a simple explicit test. Your example > didn't satisfy that. But I believe my example of an iterator with __bool__ but not with __len__ does. From comp.ogz at gmail.com Wed Jul 2 06:32:59 2008 From: comp.ogz at gmail.com (Oguz Yarimtepe) Date: Wed, 2 Jul 2008 13:32:59 +0300 Subject: detection of unplugged cable Message-ID: <20831c740807020332y456a38d8rccce67abe320a629@mail.gmail.com> Hi, I am tring to develeop a gui with pyqt. I need to detect whether the the cable to vga, dmi or s-video outputs are plugged or unplugged. After detection i need to run a process. How can i do this? -- O?uz Yar?mtepe From tjreedy at udel.edu Sat Jul 12 15:18:06 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 15:18:06 -0400 Subject: palindrome function In-Reply-To: References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: Peter Otten wrote: > Denis Kasak wrote: > >> Basically, it reverses the list in place, so it modifies the list which >> called it. It does not return a /new/ list which is a reversed version >> of the original, as you expected it to. Since it doesn't return anything >> explicitly, Python makes it return None. Hence, the comparison you are >> doing is between the original list and a None, which is False, naturally. >> Try this: >> >> spam = ['a', 'n', 'n', 'a'] >> eggs = spam[:] >> if spam.reverse() == eggs: >> print "Palindrome" > > Your explanation is correct, but your example code compares None to > ['a', 'n', 'n', 'a'] and therefore won't print "Palindrome", either. I don't know if this was posted yet, but 'seq.reversed() == seq' is the simple way to test for 'palindomeness'. From gagsl-py2 at yahoo.com.ar Sat Jul 12 00:52:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 12 Jul 2008 01:52:16 -0300 Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> Message-ID: En Fri, 11 Jul 2008 15:42:37 -0300, Keith Hughitt escribi?: > I am having a little trouble figuring out how to convert a python > datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would > like to create a UTC date so that when I send it to MySQL (which > treats all dates at local dates by default), it will already have > incorporated the proper UTC offset. I've tried looking through the > docs http://python.active-venture.com/lib/datetime-datetime.html), but > have not had any luck. You have to use a "timezone aware" datetime object. If all you want is to store an UTC date, the tzinfo demo classes that you can find in the Python docs at may be enough. A more complete implementation is at If you pass a "timezone aware" datetime object as a SQL parameter, the database should store it correctly (but I don't have a MySQL instance at hand to test it) -- Gabriel Genellina From vinay_sajip at yahoo.co.uk Tue Jul 15 09:51:11 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 15 Jul 2008 06:51:11 -0700 (PDT) Subject: Logging to different addressees References: <8df30038-86c1-4376-b046-a50f2bcf0a2b@s50g2000hsb.googlegroups.com> Message-ID: <7b829a76-ba2c-4cb7-b216-0c9c01e5cd02@f36g2000hsa.googlegroups.com> On Jul 15, 1:27 pm, McA wrote: > Hi all, > > I need a recommendation. I would to like to use theloggingmodule to > create log messages the following way: > a) Every log message does go to a admin sink. > b) Theloggingof special messages should go to the admin sink AND to > a sink specifically for > a certain addressee. > c) I don't want to write the log message to two different loggers for > that purpose. I would like to do it this way: > common_logger.log('bla') -> message to admin sink > certain_logger.log('something' -> message to admin sink and addressee- > sink > d) Filtering and debug level should work as expected. > > I could I achieve this in a elegant way? > > Best regards > Andreas Mock Add a handler to the root logger (or common_logger) to send to the admin sink. Add a handler to certain_logger to send to the addressee sink. If you added the admin sink handler to the root logger, you're done. Otherwise, you need to ensure that certain_logger is a child of common_logger. Regards, Vinay Sajip From thermostat at gmail.com Fri Jul 18 15:13:02 2008 From: thermostat at gmail.com (Dan) Date: Fri, 18 Jul 2008 12:13:02 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> Message-ID: <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> On Jul 18, 2:17 pm, castironpi wrote: > On Jul 17, 11:39 pm, Kay Schluehr wrote: > > > > > On 18 Jul., 01:15, castironpi wrote: > > > > On Jul 17, 5:37 pm, I V wrote: > > > > > On Thu, 17 Jul 2008 15:08:17 -0700, castironpi wrote: > > > > > The Python disassembly is baffling though. > > > > > >>>> y= 3 > > > > >>>> dis.dis('x=y+1') > > > > > You can't disassemble strings of python source (well, you can, but, as > > > > you've seen, the results are not meaningful). You need to compile the > > > > source first: > > > > > >>> code = compile('y=x+1','-', 'single') > > > > >>> dis.dis(code) > > > > > 1 0 LOAD_NAME 0 (x) > > > > 3 LOAD_CONST 0 (1) > > > > 6 BINARY_ADD > > > > 7 STORE_NAME 1 (y) > > > > 10 LOAD_CONST 1 (None) > > > > 13 RETURN_VALUE > > > > > You may well find these byte codes more meaningful. Note that there is a > > > > list of opcodes athttp://docs.python.org/lib/bytecodes.html > > > > Oh. How is the stack represented? > > > As a pointer to a pointer of PyObject structs. > > > > Does it keep track of which stack > > > positions (TOS, TOS1, etc.) are in what registers? Does stack > > > manipulation consume processor cycles? > > > Python does not store values in registers. It stores locals in arrays > > and accesses them by position ( you can see the positional index in > > the disassembly right after the opcode name ) and globals / object > > attributes in dicts. > > > For more information you might just download the source distribution > > and look for src/Python/ceval.c. This file contains the main > > interpreter loop. > > Ah, found it. The parts that are making sense are: > > register PyObject **stack_pointer; > #define TOP() (stack_pointer[-1]) > #define BASIC_POP() (*--stack_pointer) > > ...(line 1159)... > w = POP(); > v = TOP(); > if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { > /* INLINE: int + int */ > register long a, b, i; > a = PyInt_AS_LONG(v); > b = PyInt_AS_LONG(w); > i = a + b; > if ((i^a) < 0 && (i^b) < 0) > goto slow_add; > x = PyInt_FromLong(i); > > ... Which is more than I was picturing was involved. I understand it > is also specific to CPython. Thanks for the pointer to the code. > > My basic question was, what is the difference between compilers and > interpreters, and why are interpreters slow? I'm looking at some of > the answer right now in "case BINARY_ADD:". The basic difference between a (traditional) compiler and an interpreter is that a compiler emits (assembly) code for a specific machine. Therefore it must know the specifics of the machine (how many registers, memory addressing modes, etc), whereas interpreters normally define themselves by their conceptual state, that is, a virtual machine. The instructions (bytecode) of the virtual machine are generally more high-level than real machine instructions, and the semantics of the bytecode are implemented by the interpreter, usually in a sort-of high level language like C. This means the interpreter can run without detailed knowledge of the machine as long as a C compiler exists. However, the trade off is that the interpreter semantics are not optimized for that machine. This all gets a little more hairy when you start talking about JITs, runtime optimizations, and the like. For a real in-depth look at the general topic of interpretation and virtual machines, I'd recommend Virtual Machines by Smith and Nair (ISBN:1-55860910-5). -Dan From durand1 at gmail.com Thu Jul 10 16:40:33 2008 From: durand1 at gmail.com (Durand) Date: Thu, 10 Jul 2008 21:40:33 +0100 Subject: PIL: Transparent PNGs and im.paste: ValueError: bad transparency mask Message-ID: I posted this too soon. Converting the images to png with image magick's convert did the trick...However, I'm still not sure why I need to convert the images in the first place. Are there different types of PNGs? From torriem at gmail.com Mon Jul 28 04:56:29 2008 From: torriem at gmail.com (Michael Torrie) Date: Mon, 28 Jul 2008 02:56:29 -0600 Subject: Attack a sacred Python Cow In-Reply-To: <87myk2sbk3.fsf@nokile.rath.org> References: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c29cc$0$20302$c3e8da3@news.astraweb.com> <20080727193416.GE7373@dragontoe.org> <488D580B.9050001@gmail.com> <87myk2sbk3.fsf@nokile.rath.org> Message-ID: <488D89BD.8060708@gmail.com> Nikolaus Rath wrote: > No, but it could work like this: > > def a(x, y): > self.x = x > self.y = y > Frankly this would make reading and debugging the code by a third party to be a nightmare. Rather than calling the variable self as I did in my example, I could it in a much better way: def method(my_object, a, b): my_object.a = a my_object.b = b Now if I saw this function standalone, I'd immediately know what it was doing. In fact, I can even unit test this function by itself, without even having to know that later on it's monkey-patched into an existing class. With your idea, I might get the picture this function should be used as a method in some object because of the self reference, but I can't test the method by itself. Trying to call it would instantly result in an exception. And if this was a large function, I might not even see the self reference right away. From basti.wiesner at gmx.net Wed Jul 23 08:16:03 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Wed, 23 Jul 2008 14:16:03 +0200 Subject: Proper way to query user and group database on a Unix host? References: <87d4l5ozsc.fsf@cox.net> Message-ID: Chris Brannon : Iirc since Python 2.5 these tuples are named ... > Instead, do this: > > import grp > groupname = 'users' > groupusers = grp.getgrnam(groupname)[3] ... thus this line could be written as: groupusers = grp.getgrnam(groupname).gr_mem Slightly more readable, imho -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From fredrik at pythonware.com Tue Jul 15 17:11:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2008 23:11:52 +0200 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: Victor Noagbodji wrote: > Well that's exactly why I'm asking. Since None returns False in if > statements. Why do people use if name is not None: instead of simply > writing if not name? Because they want to distinguish between None and other values that evaluate to False, of course. As the page I linked to explains, there are many objects that evaluate to false in a boolean context; None is just one of them. Or to spell it out: if you need to distinguish between None and other false values, use an explicit test. If you don't need to distinguish between None and other false values, don't use an explicit test. From asd at pittle.org Thu Jul 3 16:13:48 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Thu, 3 Jul 2008 13:13:48 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> <9ad840e1-e12f-4125-8537-4bad2ef77f51@w5g2000prd.googlegroups.com> <6b1e8a6c-4d21-488d-a8b9-74388f1f5c43@m45g2000hsb.googlegroups.com> Message-ID: <4574e6fb-0146-45b9-a84c-028787464f05@i36g2000prf.googlegroups.com> On Jul 3, 7:38?pm, Fuzzyman wrote: > On Jul 2, 9:33?am, Ali Servet D?nmez wrote: > > > > > On Jul 1, 12:15?am, Fuzzyman wrote: > > > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > > I don't want to be so mean here, but how hard it could be be writing a > > > > freesoftware which would automatically/intelligently auto complete > > > > Python code? (I mean something that really does the job, like > > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > > name it, but just don't give me PyDev please...) > > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > > missing here? > > > > > Could someone please point me out something that I'm really missing > > > > which is already present in the wild, otherwise I'd like discuss with > > > > whoever is willing to help me to get this thing done. I made my mind > > > > and I could volunteer to make this happen as thesis project for my > > > > incoming graduation in the next year. > > > > > Regards you all, > > > > Ali Servet D?nmez > > > > Vim, Emacs, Wing, Komodo, ... more? > > > > Yeah, I guess you're missing something. :-) > > > > MichaelFoordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > > I've checkout Wing IDE's license and it doesnt' seem to be a > > freesoftware; am I wrong? > > Wing 101 is free. The software is good enough though that it is worth > supporting its development by paying for it. > > Michael Foord > --http://www.ironpythoninaction.com/http://www.trypython.org/ I wasn't referring to its fee, but the fact of having a freedom restricting license. From Ilan.i18n at gmail.com Sun Jul 13 08:11:10 2008 From: Ilan.i18n at gmail.com (Ilan) Date: Sun, 13 Jul 2008 05:11:10 -0700 (PDT) Subject: Dynamic Invocation Interface Message-ID: <08386e58-5972-449b-8107-05bca20c6260@y38g2000hsy.googlegroups.com> Is there any python CORBA ORB that support Dynamic Invocation Interface? Thanks From pavlovevidence at gmail.com Sun Jul 13 14:30:36 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 13 Jul 2008 11:30:36 -0700 (PDT) Subject: Mutually referencing imports -- impossible? References: Message-ID: On Jul 13, 1:55?pm, Matthew Wilson wrote: > I started off with a module that defined a class Vehicle, and then > subclasses Car and Motorcycle. > > In the Car class, ?for some bizarre reason, I instantiated a Motorcycle. > Please pretend that this can't be avoided for now. > > Meanwhile, my Motorcycle class instantiated a Car as well. > > Then I moved the Car and Motorcycle classes into separate files. ?Each > imported the Vehicle module. > > Then I discovered that my Car module failed because the global > Motorcycle wasn't defined. ?The same problem happened in my Motorcycle > module. ?Car and Motorcycle can't both import each other. > > In the beginning, when all three (Vehicle, Car, and Motorcycle) were > defined in the same file, everything worked fine. > > I don't know how to split them out in separate files now though and I > really wish I could because the single file is enormous. > > Any ideas? First thing to do is ask yourself: Are the Car and Motorcycle being created at import time, or are they being created after the imports by a function call? If it's the former, then yes, it's impossible. You can't do this, for instance: car.py: ----------------- import motorcycle a = motorcycle.Motorcycle() ----------------- motorcycle.py: ----------------- import car b = car.Car() ----------------- However, you can stick them in functions and call them afterwards and it will work: car.py: ----------------- import motorcycle def create_motorcycle(): global a a = motorcycle.Motorcycle() ----------------- motorcycle.py: ----------------- import car def create_car(): global b a = car.Car() ----------------- vehicle.py ----------------- import car import motorcycle car.create_motorcycle() motorcycle.create_car() ----------------- Second, if you're using from ... import statements, it won't work; you should change it to use plain imports as I did above. So the following wouldn't work : motorcycle.py: ----------------- from car import * a = Motorcycle() ----------------- car.py: ----------------- from motorcycle import * b = Car() ----------------- Third, if Motorcycle and Car are inside packages, you still need to avoid from ... import even just to import the module (unless you're willing to hook into the import machinery). For example, if car.py, motorcycle.py, and vehicle.py are all parts of the package carsim, then you'd have to do this: motorcycle.py: ---------------- import carsim.car def create_car(): global a a = carsim.car.Car() ---------------- and not motorcycle.py: ---------------- from carsim import car def create_car(): global a a = car.Car() ---------------- This last limitation is due to a wart in the import logic. Carl Banks From babacity2 at gmail.com Thu Jul 24 16:56:39 2008 From: babacity2 at gmail.com (babacity2 at gmail.com) Date: Thu, 24 Jul 2008 13:56:39 -0700 (PDT) Subject: Peachy18 forum - Amazing porn video collection Message-ID: peachy18 forum . >>>>>>>>>>Best Collection of Peachy18 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE peachy18 forum VIDEOS<<<<<<<<<<< . peachy18 forum From workitharder at gmail.com Sat Jul 12 23:23:16 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 12 Jul 2008 20:23:16 -0700 (PDT) Subject: socket.connect() hangs in SYN_SENT state. Message-ID: I'm having an issue where my program hangs while doing socket.connect() for a couple minutes, then times out the connection and crashes. I'm connecting to an apache2 process on the same machine, for testing. When looking at netstat, the socket is in the SYN_SENT state, like this: $netstat -a -tcp tcp 0 0 *:www *:* LISTEN 7635/apache2 tcp 0 1 bukzor:38234 adsl-75-61-84-249.d:www SYN_SENT 9139/python Anyone know a general reason this might happen? Even better, a way to fix it? Doing a minimal amount of research, I found this in the netstat manual: The state SYN_SENT means that an application has made arequest for a TCP session, but has not yet received the return SYN+ACK packet. This would indicate it's a server issue, but it seems very stable when I look at it via a browser. Here's the server. If you browse to it, it documents the exported functions: http://bukzor.hopto.org/modpython/xmlrpc.py Here's my test client that's hanging. Turn 'verbose' to True to get more debugging info. [code] #!/usr/bin/env python from xmlrpclib import ServerProxy s = ServerProxy("http://bukzor.hopto.org/modpython/xmlrpc.py", verbose=False) print s.helloworld() print s.add(1,2) print s.subtract(1,2) [/code] Thanks, --Buck From Nikolaus at rath.org Mon Jul 28 05:31:29 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 28 Jul 2008 11:31:29 +0200 Subject: os.symlink() Message-ID: <87d4kys6by.fsf@nokile.rath.org> Hello, >From `pydoc os`: symlink(...) symlink(src, dst) Create a symbolic link pointing to src named dst. Is there any reason why this is so deliberately confusing? Why is the target of the symlink, the think where it points *to*, called the `src`? It seems to me that the names of the parameters should be reversed. Puzzled, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From gagsl-py2 at yahoo.com.ar Mon Jul 28 06:12:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 Jul 2008 07:12:38 -0300 Subject: method decorators and more on decorators References: <7fd737460807271126m3dbdea8cv4dbd8c9058d4faea@mail.gmail.com> Message-ID: En Sun, 27 Jul 2008 15:26:39 -0300, Themistoklis Bourdenas escribi?: > Hi, is there any possible way to get the class or class name inside a method > decorator? For example in the code sample below: > > def decorate(func): > print type(func) > return func > > class myclass: > > @decorate > def foo(self): > pass > > The output of this program will be the type of the supplied func in > decorate, i.e. method foo. However, the type is function foo, a free > function, not an instance method myclass.foo. Because the decorator is applied when the function is defined - and as you already noted, foo is a plain function (stored into myclass's namespace). Only when, later, the name foo is searched in the class, the descriptor protocol comes into play and a method object is built from the function and the myclass instance. > On a related note, as the actual instance method of myclass is not foo but > decorate(foo), why are they called method decorators? This does not decorate > methods, they decorate functions and eventually the decorated functions > become methods. The name method decorator sounds a bit misleading to me. Where have you found it? I've always seen the expression "function decorator" or just "decorator", not "method decorator". > So returning to my original question is there any way I can get the class > inside decorate()? I guess there is not, but just asking to make sure. "the class inside decorate"? What do you mean? The type of the x instance in an x.foo() call? That should be determined inside the wrapped function -when it is actually called-. > Speaking of decorators I'd also like to ask on the pending class decorators > that should be coming in a following version of the language. Are they going > to be in 2.6 or just 3.0? In the following example: Both versions come with class decorators. > In essence what is the order of application of class decorators compared to > the function decorators of their methods? I couldn't find any mention of > that issue in any of the PEPs. I guess it would be the latter, following the > behavior of metaclasses, but better be certain than speculate :) I don't have a 2.6/3.0 Python at hand to check, but the (decorated) functions must be built before the class is created (because they are contained in the class's namespace). So the function decorators should be aplied before the class decorator... -- Gabriel Genellina From israelu at elbit.co.il Mon Jul 28 19:00:31 2008 From: israelu at elbit.co.il (iu2) Date: Mon, 28 Jul 2008 16:00:31 -0700 (PDT) Subject: seemingly simple list indexing problem References: Message-ID: <1ad9234a-6bba-48ce-ad40-ea0aeabce492@79g2000hsk.googlegroups.com> On Jul 29, 12:10?am, John Krukoff wrote: > On Mon, 2008-07-28 at 16:24 -0500, Ervan Ensis wrote: > > My programming skills are pretty rusty and I'm just learning Python so > > this problem is giving me trouble. > > > I have a list like [108, 58, 68]. ?I want to return the sorted indices > > of these items in the same order as the original list. ?So I should > > return [2, 0, 1] > > > For a list that's already in order, I'll just return the indices, i.e. > > [56, 66, 76] should return [0, 1, 2] > > > Any help would be appreciated. > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > If your lists aren't so large that memory is an issue, this might be a > good place for a variation of decorate, sort, undecorate. > > >>> listToSort = [ 108, 58, 68 ] > >>> decorated = [ ( data, index ) for index, data in > > enumerate( listToSort ) ]>>> decorated > > [(108, 0), (58, 1), (68, 2)]>>> result = [ None, ] * len( listToSort ) > >>> for sortedIndex, ( ignoredValue, originalIndex ) in > > enumerate( sorted( decorated ) ): > ... ? ? result[ originalIndex ] = sortedIndex > ...>>> result > > [2, 0, 1] > > -- > John Krukoff > Land Title Guarantee Company Inspired by your idea and the above one, here is another try: >>> a0 = [108, 58, 68, 108, 58] >>> a1 = [(x, y) for x, y in enumerate(a0)] >>> a1 [(0, 108), (1, 58), (2, 68), (3, 108), (4, 58)] >>> a2 = sorted(a1, lambda x, y: cmp(x[1], y[1])) >>> a2 [(1, 58), (4, 58), (2, 68), (0, 108), (3, 108)] >>> a3 = [a2.index(x) for x in a1] >>> a3 [3, 0, 2, 4, 1] The idea is to make each item unique (by making it a tuple), and then apply the naive solution. From mensanator at aol.com Tue Jul 29 20:44:41 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 29 Jul 2008 17:44:41 -0700 (PDT) Subject: How can I check nbr of cores of computer? References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> Message-ID: <37e26af1-c6a7-4302-b93c-39164b222f26@34g2000hsf.googlegroups.com> On Jul 29, 5:53?pm, defn noob wrote: > How can I check how many cores my computer has? > Is it possible to do this in a Python-app? If you're using Windows, get PyWin32: win32api.GetSystemInfo tuple = GetSystemInfo() Retrieves information about the current system. Win32 API References Search for GetSystemInfo at msdn, google or google groups. Return Value The return value is a tuple of 9 values, which corresponds to the Win32 SYSTEM_INFO structure. The element names are: dwOemId dwPageSize lpMinimumApplicationAddress lpMaximumApplicationAddress dwActiveProcessorMask dwNumberOfProcessors dwProcessorType dwAllocationGranularity (wProcessorLevel,wProcessorRevision) >>> import win32api >>> win32api.GetSystemInfo() (0, 4096, 65536, 2147418111, 3L, 2, 586, 65536, (6, 3846)) | processors From deets at nospam.web.de Fri Jul 11 07:12:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 11 Jul 2008 13:12:53 +0200 Subject: MySQLdb will only import for root In-Reply-To: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> Message-ID: <6dothnF3lqqmU1@mid.uni-berlin.de> martinnorth schrieb: > Hi, > > I am running Python and MySQL on Ubuntu and have installed MySQLdb. If I > try to import MySQLdb I get the following error: > > ActivePython 2.5.2.2 (ActiveState Software Inc.) based on > Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08) > [GCC 3.3.1 (SuSE Linux)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import MySQLdb > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named MySQLdb > > But if I lrun python as the root user it imports fine. Can anyone > suggest what might be wrong with the installation? Or is there nothing > wrong? I haven't seen any examples that mentioned being root to import a > module. Try importing sys and printing out sys.path both with a "normal" account and the root-account, to see if there are any differences. And of course make sure both actually use the same interpreter. Beyond that, you are right: there is no root-only-importing. Diez From roy at panix.com Sun Jul 13 10:16:31 2008 From: roy at panix.com (Roy Smith) Date: Sun, 13 Jul 2008 10:16:31 -0400 Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> <87skuems49.fsf@benfinney.id.au> <873amddh0n.fsf@benfinney.id.au> Message-ID: In article <873amddh0n.fsf at benfinney.id.au>, Ben Finney wrote: > Which "original class" are you referring to? The one posted by the > original poster of this thread had no "original list"; it gathered the > positional arguments (using '*items') into an 'items' parameter, which > *doesn't exist* until the function body executes. Ah, I didn't notice that. From stefan_ml at behnel.de Wed Jul 30 13:40:42 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 30 Jul 2008 19:40:42 +0200 Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? In-Reply-To: <16218185-7d69-411c-a219-31f2e4e8df9e@p25g2000hsf.googlegroups.com> References: <16218185-7d69-411c-a219-31f2e4e8df9e@p25g2000hsf.googlegroups.com> Message-ID: <4890a79a$0$12954$9b4e6d93@newsspool2.arcor-online.net> Simon Willison wrote: > Follow up question: what's the best way of incrementally consuming XML > in Python that's character encoding aware? iterparse(), as implemented in (c)ElementTree and lxml. Note that ElementTree and cElementTree are part of Python 2.5, in the xml.etree package. > I have a very large file to > consume but I'd rather not have to fall back to the raw SAX API. Large is fairly relative. Both cElementTree and lxml are pretty memory friendly, even when parsing into an in-memory tree. Stefan From callen314 at gmail.com Fri Jul 18 21:17:42 2008 From: callen314 at gmail.com (Craig Allen) Date: Fri, 18 Jul 2008 18:17:42 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> <7ac1b818-8aa9-478f-a922-82baf0d51c5b@w39g2000prb.googlegroups.com> Message-ID: On Jul 17, 9:04 pm, Paddy wrote: > On Jul 16, 11:20 pm, Craig Allen wrote: > > > Hey, forgive me for just diving in, but I have a question I was > > thinking of asking on another list but it really is a general question > > so let me ask it here. It's about how to approach making singletons. > > Hi Craig, > This might be good for a general background on Design Patters in > Python: > > http://uk.youtube.com/watch?v=0vJJlVBVTFg > > - Paddy. thanks for the link paddy, I'll watch it. From hubaghdadi at gmail.com Tue Jul 29 11:08:46 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Tue, 29 Jul 2008 08:08:46 -0700 (PDT) Subject: Build tool for Python Message-ID: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Hi. Apache Ant is the de facto building tool for Java (whether JSE, JEE and JME) application. With Ant you can do what ever you want: compile, generate docs, generate code, packing, deploy, connecting to remote servers and every thing. Do we have such a tool for Python projects? Thank you. From bearophileHUGS at lycos.com Tue Jul 29 14:04:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 29 Jul 2008 11:04:13 -0700 (PDT) Subject: iterating "by twos" References: Message-ID: <9c269ce1-9f0b-430b-b448-1cb79f09263e@56g2000hsm.googlegroups.com> Something like this may be fast enough: >>> from itertools import izip >>> xpartition = lambda seq, n=2: izip(*(iter(seq),) * n) >>> xprimes = (x for x in xrange(2, 100) if all(x % i for i in xrange(2, x))) >>> list(xpartition(xprimes)) [(2, 3), (5, 7), (11, 13), (17, 19), (23, 29), (31, 37), (41, 43), (47, 53), (59, 61), (67, 71), (73, 79), (83, 89)] Bye, bearophile From sturlamolden at yahoo.no Fri Jul 25 10:24:17 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 25 Jul 2008 07:24:17 -0700 (PDT) Subject: PyOpenGL Tutorial? References: Message-ID: <204e0b01-b2e3-496c-98d6-620f373d69ff@n33g2000pri.googlegroups.com> On Jul 23, 10:07?pm, Clay Hobbs wrote: > I need a tutorial for PyOpenGL (specifically, to be used with wxPython). > I searched with Google and didn't find one. ?Does anybody know where one > is? PyOpenGL is just a wrapper for OpenGL. The API is identical. Do you need an OpenGL tutorial? As for wxPython, you just subclass wxGLCanvas. Call the method SetCurrent() before you call OpenGL (e.g. through PyOpenGL) and SwapBuffers() when you are done. See the wxWidgets reference. Personally I think PyOpenGL is a slow beast. It is not just a thin wrapper over OpenGL, but bloated with sanity checks, exception handling, etc (look at the code, it is pure Python and easy to read). I prefer to put all calls to OpenGL in a C DLL, and call that with ctypes. If I make repeated calls to functions like glVertex3f, I want them to to be fast, thus C is indicated over Python. And if all I do in C is to make calls into OpenGL, there is no real advantage to using Python here - the Python code would look almost exactly the same, but would be slower by several orders of magnitude. By the way, I still use wxGLCanvas from wxPython to set things up. The ctypes call into my C DLL is called between SetCurrent() and SwapBuffers(). If you want a pure Python solution, you will need to use display lists, vertex arrays (with NumPy) or vertex buffers (if your graphics card supports it) to get acceptable performance. Here is a short tutorial: import wx import wx.glcanvas import ctypes glrender = ctypes.pydll.glrender.render # use ctypes.cdll to call with GIL released glrender.argtypes = (ctypes.c_int, ctypes.c_int,) glrender.restype = None class MyCanvas(wx.glcanvas.GLCanvas): def __init__(self, parent): attribList = (wx.glcanvas.WX_GL_DOUBLEBUFFER, wx.glcanvas.WX_GL_RGBA, 0) wx.glcanvas.GLCanvas.__init__(self, parent, -1, attribList = attribList) self.context = wx.glcanvas.GLContext(self) self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_PAINT, self.OnPaint) def OnSize(self, evt): w,h = self.GetClientSize() self.w = w self.h = h dc = wx.ClientDC(self) self.Render(dc) def OnPaint(self, evt): dc = wx.PaintDC(self) self.Render(dc) def Render(self, dc): self.SetCurrent() glrender(self.w, self.h) self.SwapBuffers() And then in glrender.c, put the following: #include #include #include __declspec(dllexport) void render(int w, int h) { /* calls to OpenGL goes here */ return; } And for Python 2.5.x on Windows, compile with: gcc -O2 -o glrender.dll -shared -lopengl -lmsvcr71 glrender.c From mail at timgolden.me.uk Fri Jul 4 05:42:39 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 04 Jul 2008 10:42:39 +0100 Subject: better way to search the Python archive In-Reply-To: <00e901c8dd24$c3301ad0$8101a8c0@bocaron> References: <00e901c8dd24$c3301ad0$8101a8c0@bocaron> Message-ID: <486DF08F.4050501@timgolden.me.uk> Jeremy Link wrote: > Just an FYI out to folks that want a better way to search the Python > archive? > > I?ve been using MarkMail (www.markmail.org ) > to search the archives and it works MUCH better than the Google archive. > It is a free hosting of all sorts of GNU/open source mailing lists > (registration NOT required or even available). I agree; it *is* good. However, for a quick-and-dirty, a simple Google search for "site:mail.python.org blah blah" is also useful. TJG From david at abbottdavid.com Wed Jul 23 14:38:33 2008 From: david at abbottdavid.com (David) Date: Wed, 23 Jul 2008 14:38:33 -0400 Subject: tkinter for my python program !! In-Reply-To: <81554f58-cc9c-4649-afdd-45656ab0bf64@b2g2000prf.googlegroups.com> References: <6em5snF7r22oU3@mid.uni-berlin.de> <63ff0b6f-8c75-4172-b836-8497870544ca@s50g2000hsb.googlegroups.com> <6em86gF7q9djU1@mid.uni-berlin.de> <81554f58-cc9c-4649-afdd-45656ab0bf64@b2g2000prf.googlegroups.com> Message-ID: <48877AA9.9050908@abbottdavid.com> > > Further, finally when i invoke the python program by > giving the necessary input file, i get the following > errors . > Does it have any relation with the python version installed ? > yes > I am using Redhat 9.0 You may want to install a current Linux distro. From x at y.z Tue Jul 1 09:02:58 2008 From: x at y.z (name) Date: Tue, 1 Jul 2008 13:02:58 +0000 (UTC) Subject: pyparsing problem Message-ID: Hi, I try to parse a file with pyparsing and get this output: ['generic', 'host-01', 'host alias xyz', '10.0.0.1'] - alias: host alias xyz - host_name: ['host-01'] - ip_address: ['10.0.0.1'] - use: ['generic'] generic host-01 host alias xyz 10.0.0.1 ['generic', 'host-01', 'host alias xyz', '10.0.0.1'] finished What I don't understand is why I get the line generic and not generic as there is an associated name in the dump() output. Thank you very much in advance for any clue or help you could provide. The code: --------- #!/usr/bin/env python from pyparsing import * sample = """ define host{ use generic host_name host-01 alias host alias xyz address 10.0.0.1 } """ # define tokens LBRACE,RBRACE = map(Suppress, '{}') ipAddress = Combine(Word(nums) + ('.' + Word(nums))*3) useTemplate = oneOf('generic user') # define grammar deviceName = Word(alphanums+'-') hostDef = Literal('define').suppress() + Literal('host').suppress() useLine = Suppress('use') + useTemplate + Suppress(SkipTo(lineEnd)) host_nameLine = Suppress('host_name') + deviceName + Suppress(SkipTo (lineEnd)) aliasLine = Suppress('alias') + SkipTo(lineEnd) aliasLine.setParseAction(lambda x: ' '.join(x[0].split())) ip_addressLine = Suppress('address') + ipAddress use = useLine.setResultsName('use') host_name = host_nameLine.setResultsName('host_name') alias = aliasLine.setResultsName('alias') ip_address = ip_addressLine.setResultsName('ip_address') host_stmt = (use + host_name + alias + ip_address) host = hostDef + LBRACE + host_stmt + RBRACE test_file = OneOrMore(host) + stringEnd # test x = test_file.parseString(sample) print x.dump() print print x.asXML('Hosts') print print x.asList() print print 'finished' From forum at namit.org Fri Jul 11 05:31:54 2008 From: forum at namit.org (Christian Kortenhorst (Forum)) Date: Fri, 11 Jul 2008 10:31:54 +0100 Subject: Django admin multi layour Message-ID: Hey All Just been messing around with django and found that can not seam to get admin to work how, it does not support multilayer input I want it I know there is some way of writing your own "view", but wondering would it be possible to write a multilayer setup or what is the wok around or what should i be looking for? my setup is class Faculty(models.Model): class Admin: pass name = models.CharField(maxlength=200) director = models.CharField(maxlength=200) web_url = models.CharField(maxlength=200) def __str__(self): return self.name class School(models.Model): class Admin: pass faculty = models.ForeignKey(Faculty) name = models.CharField(maxlength=200) def __str__(self): return self.name class Programme(models.Model): class Admin: pass duration_choices = ( ('Years', 'years'), ('Days', 'days') ) school = models.ForeignKey(School) name = models.CharField(maxlength=200) description = models.CharField(maxlength=1000) def __str__(self): return self.name class Stream(models.Model): class Admin: pass programme_code = models.ForeignKey(Programme, edit_inline=models.TABULAR, num_in_admin=3) stream_number = models.IntegerField(core=True) ..... Want to be able to click in and keep adding programs to a school and when i do that a new box is created and a steam is created. e.g. add a Faculty -> input for school is shown -> add a school -> -> input for Programme is shown -> -> add a programme -> -> -> etc.. also the option to add new school and program so can have a one to many relationship. Thanks Christian K -- Christian Kortenhorst mod: +353-(0)87-6183349 home: +353-(0)1-4966287 -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Sun Jul 20 10:22:50 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 20 Jul 2008 16:22:50 +0200 Subject: Rotating a cube In-Reply-To: References: <3d47df08-9734-4e0f-96ad-37da445b4faf@34g2000hsh.googlegroups.com> <8156f68a-3f65-4fca-a725-2e0c4240abd1@v21g2000pro.googlegroups.com> <4881BBCF.2060905@preisshare.net> Message-ID: <48834A3A.4020502@gmail.com> Fredrik Lundh wrote: > David Lyon wrote: > >> But is the question about display graphics ? >> >> ie rotating a cube using a python framework ? >> >> With something like python and OpenGL ? or Python and PovRay... or >> perphaps python and imagemagick ? > > can you name one graphics framework that represents a cube as "x + 4*y > + 16*z" ? no, but ... I don't think the notation is so strange, in electronics (and others) I'm used to a 2-dimensional complex notation: vector = 3 + 4*i = 3*x +4*y but although my English isn;t very well, a "cube of 4*4" looks strange to me. cheers, Stef > > > > -- > http://mail.python.org/mailman/listinfo/python-list From gagsl-py2 at yahoo.com.ar Wed Jul 30 01:09:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 02:09:01 -0300 Subject: Dynamically adding methods to a class... References: <19ac19520807282117y4c34ed22n3bcb9c6cf7d198b8@mail.gmail.com> Message-ID: En Tue, 29 Jul 2008 01:17:13 -0300, Piyush Anonymous escribi?: > class MyObject: > def __init__(self, name): > self.name = name > > def do_this_default(self): > print "default do_this implementation for %s" % self.name > > def custom_do_this(): #method to be added > print "custom do_this implementation for %s" % self.name You forget the self argument (this explains the error you got). > def funcToMethod(func,clas,method_name=None): > """Adds func to class so it is an accessible method; use method_name > to > specify the name to be used for calling the method. > The new method is accessible to any instance immediately.""" > import new > method = new.instancemethod(func,None,clas) > print method > if not method_name: method_name=func.__name__ > clas.__dict__[method_name]=func It's a lot easier than that; just add the *function* object to the class namespace: setattr(clas, method_name, func) If you know the name when you write the code, just set the attribute: py> o = MyObject("hello") py> MyObject.custom_do_this = custom_do_this py> o.custom_do_this() custom do_this implementation for hello new.instancemethod is useful to add specific methods to individual instances, but it's not used to add methods globally to the class. > Error I am getting; > TypeError: custom_do_this() takes no arguments (1 given) Add the self argument and you're done. > Why am I getting it? > > Also how can I do this in new style class (inherited from 'object')? It's the same thing, no difference. -- Gabriel Genellina From Russ.Paielli at gmail.com Mon Jul 28 14:46:34 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jul 2008 11:46:34 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> Message-ID: <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> On Jul 28, 4:23 am, Bruno Desthuilliers wrote: > Russ P. a ?crit : > > > > > On Jul 27, 3:11 pm, "Russ P." wrote: > >> On Jul 27, 12:39 pm, Bruno Desthuilliers > > >> wrote: > >>> Derek Martin a ?crit : > >>>> On Sun, Jul 27, 2008 at 08:19:17AM +0000, Steven D'Aprano wrote: > >>>>>> You take the name down to a single letter. As I suggested in an earlier > >>>>>> post on this thread, why not take it down to zero letters? > >>>>> The question isn't "why not", but "why". The status quo works well as it > >>>>> is, even if it isn't perfect. Prove that implicit self is a good idea -- > >>>>> or at least prove that it is an idea worth considering. > >>>> Come on, this sounds like a schoolyard argument. This comes down to a > >>>> matter of style, and as such, is impossible to prove. It's largely a > >>>> question of individual preference. > >>>> That said, the argument in favor is rather simple: > >>>> 1. This is an extremely common idiom in Python > >>>> 2. It is completely unnecessary, and the language does not suffer for > >>>> making it implicit > >>>> 3. Making it implicit reduces typing, reduces opportunities for > >>>> mistakes, and arguably increases consistency. > >>> "arguably", indeed, cf below. > >>>> As for the latter part of #3, self (or some other variable) is > >>>> required in the parameter list of object methods, > >>> It's actually the parameter list of the *function* that is used as the > >>> implementation of a method. Not quite the same thing. And then, > >>> consistency mandates that the target object of the method is part of the > >>> parameter list of the *function*, since that's how you make objects > >>> availables to a function. > >>>> however when the > >>>> method is *called*, it is omitted. > >>> Certainly not. You need to lookup the corresponding attribute *on a > >>> given object* to get the method. Whether you write > >>> some_object.some_method() > >>> or > >>> some_function(some_object) > >>> you still need to explicitely mention some_object. > >>>> It is implied, supplied by Python. > >>> Neither. The target object is passed to the function by the method > >>> object, which is itself returned by the __get__ method of function > >>> objects, which is one possible application of the more general > >>> descriptor protocol (the same protocol that is used for computed > >>> attributes). IOW, there's nothing specific to 'methods' here, just the > >>> use of two general features (functions and the descriptor protocol). > >>> FWIW, you can write your own callable, and write it so it behave just > >>> like a function here: > >>> import types > >>> class MyCallable(object): > >>> def __call__(self, obj): > >>> print "calling %s with %s" % (self, obj) > >>> def __get__(self, instance, cls): > >>> return types.MethodType(self.__call__, instance, cls) > >>> class Foo(object): > >>> bar = MyCallable() > >>> print Foo.bar > >>> f = Foo() > >>> f.bar() > >>>> Thus when an object method is called, it must be called with one fewer > >>>> arguments than those which are defined. This can be confusing, > >>>> especially to new programmers. > >>> This is confusing as long as you insist on saying that what you > >>> "def"ined is a method - which is not the case. > >>>> It can also be argued that it makes the code less ugly, though again, > >>>> that's a matter of preference. > >>>>> It's not enough to show that a change "isn't bad" -- you have to show > >>>>> that it is actively good. > >>>> But he did... he pointed out that *it saves work*, without actually > >>>> being bad. Benefit, without drawback. Sounds good to me! > >>>>> "Don't need to look at the method signature" is not an argument in favour > >>>>> of implicit self. > >>>> Yes, actually, it is. > >>> It isn't, since there's no "method signature" to look at !-) > >>>> If there is a well-defined feature of Python > >>>> which provides access to the object within itself, > >>> The point is that you don't get access to the object "within itself". > >>> You get access to an object *within a function*. > >>> The fact that a function is defined within a class statement doesn't > >>> imply any "magic", it just creates a function object, bind it to a name, > >>> and make that object an attribute of the class. You have the very same > >>> result by defining the function outside the class statement and binding > >>> it within the class statement, by defining the function outside the > >>> class and binding it to the class outside the class statement, by > >>> binding the name to a lambda within the class statement etc... > >>>> then the > >>>> opportunities for mistakes when someone decides to use something else > >>>> are lessened. > >>>>> You don't need to look at the method signature when you're using an > >>>>> explicit self either. > >>>> That isn't necessarily true. If you're using someone else's code, and > >>>> they didn't use "self" -- or worse yet, if they chose this variable's > >>>> name randomly throughout their classes -- then you may well need to > >>>> look back to see what was used. > >>>> It's bad programming, but the world is full of bad programmers, and we > >>>> don't always have the choice not to use their code. Isn't one of > >>>> Python's goals to minimize opportunities for bad programming? > >>> Nope. That's Java's goal. Python's goals are to maximize opportunities > >>> for good programming, which is quite different. > >>>> Providing a keyword equivalent to self and removing the need to name > >>>> it in object methods is one way to do that. > >>> It's also a way to make Python more complicated than it needs to be. At > >>> least with the current state, you define your functions the same way > >>> regardless of how they are defined, and the implementation is > >>> (relatively) easy to explain. Special-casing functions definition that > >>> happens within a class statement would only introduce a special case. > >>> Then you'd have to explain why you need to specify the target object in > >>> the function's parameters when the function is defined outside the class > >>> but not when it's defined within the class. > >>> IOW : there's one arguably good reason to drop the target object from > >>> functions used as methods implementation, which is to make Python looks > >>> more like Java, and there's at least two good reason to keep it the way > >>> it is, which are simplicity (no special case) and consistency (no > >>> special case). > >>> Anyway, the BDFL has the final word, and it looks like he's not going to > >>> change anything here - but anyone is free to propose a PEP, isn't it ? > >> The issue here has nothing to do with the inner workings of the Python > >> interpreter. The issue is whether an arbitrary name such as "self" > >> needs to be supplied by the programmer. > > >> Neither I nor the person to whom you replied to here (as far as I can > >> tell) is suggesting that Python adopt the syntax of Java or C++, in > >> which member data or functions can be accessed the same as local > >> variables. Any suggestion otherwise is a red herring. > > >> All I am suggesting is that the programmer have the option of > >> replacing "self.member" with simply ".member", since the word "self" > >> is arbitrary and unnecessary. Otherwise, everything would work > >> *EXACTLY* the same as it does now. This would be a shallow syntactical > >> change with no effect on the inner workings of Python, but it could > >> significantly unclutter code in many instances. > > >> The fact that you seem to think it would change the inner functioning > >> of Python just shows that you don't understand the proposal. > > > It just occurred to me that Python could allow the ".member" access > > regardless of the name supplied in the argument list: > > > class Whatever: > > > def fun(self, cat): > > > .cat = cat > > self.cat += 1 > > > This allows the programmer to use ".cat" and "self.cat" > > interchangeably. If the programmer intends to use only the ".cat" > > form, the first argument becomes arbitrary. Allowing him to use an > > empty argument or "." would simply tell the reader of the code that > > the ".cat" form will be used exclusively. > > > When I write a function in which a data member > > Python has nothing like "data member" (nor "member function" etc). It > has class attributes and instance attributes, period. *Python is not > C++*. So please stop using C++ terms which have nothing to do with > Python's object model. > > > will be used several > > times, I usually do something like this: > > > data = self.data > > > so I can avoid the clutter of repeated use of "self.data". If I could > > just use ".data", I could avoid most of the clutter without the extra > > line of code renaming the data member. > > The main reason to alias an attribute is to avoid the overhead of > attribute lookup. > > > A bonus is that it becomes > > clearer at the point of usage that ".data" is member data rather than > > a local variable. > > I totally disagree. The dot character is less obvious than the 'self.' > sequence, so your proposition is bad at least wrt/ readability (it's > IMHO bad for other reasons too but I won't continue beating that poor > dead horse...) Man, you are one dense dude! Can I give you a bit of personal advice? I suggest you quit advertising your denseness in public. Letting "self" (or whatever the first argument was) be implied in ".cat" does absolutely *NOTHING* to change the internal workings of the Python interpreter. It's a very simple idea that you insist on making complicated. As I said, I could write a pre-processor myself to implement it in less than a day. As for "dot" being less obvious than "self.", no kidding? Hey, "self." is less obvious than "extraspecialme.", so why don't you start using the latter? Has it occurred to you that the difference between 1.000 and 1000 is just a dot? Can you see the difference, Mr. Magoo? Your posts here are typical. I'm trying to make a suggestion to reduce the clutter in Python code, and you throw tomatoes mindlessly. You seem to think that being a "regular" on this newsgroup somehow gives you special status. I sure wish I had one tenth the time to spend here that you have. But even if I did, I have far more important work to do than to "hang out" on comp.lang.python all day every day. Man, what a waste of a life. Well, I guess it keeps you off the streets at least. From martin at v.loewis.de Sat Jul 26 05:20:18 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 26 Jul 2008 11:20:18 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: References: <1216966424.4685.1265275245@webmail.messagingengine.com> <4889AC5E.8090909@egenix.com> Message-ID: <488aec52$0$21481$9b622d9e@news.freenet.de> > The end result of that is on a 32-bit machine IronPython runs in a > 32-bit process and on a 64-bit machine it runs in a 64-bit process. That's probably not exactly true (although I haven't checked). When you start a .NET .exe program, the operating system needs to decide whether to create a 32-bit or a 64-bit process (assuming the processor supports 64-bit mode). The Microsoft .NET commercial framework uses the PE architecture of the executable to make that decision (or, rather, it doesn't decide at all, but the underlying OS decides). The C# compiler (more specifically, the assembly linker) offers a choice of setting the .NET architecture to Itanium, AMD64, x86, or "any"; people use typically "any". This "any" choice is implemented by setting the PE architecture to "any", and then indicating to the .NET run-time that any other architecture would be fine as well. As a consequence, an architecture-any executable launches as a 32-bit process on a 64-bit system. To have the executable launch as 64-bit code, you must tell csc.exe to create an AMD64 binary (say), which then means that the binary won't launch on a 32-bit system. I haven't checked, but my guess is that IronPython uses architecture-any executables (unless you adjust the build process). Things are different in a DLL: an architecture-any DLL will load into a 32-bit process as 32-bit code, and into a 64-bit process as 64-bit code. Regards, Martin From fredrik at pythonware.com Wed Jul 23 15:52:46 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 21:52:46 +0200 Subject: Using variables across modules In-Reply-To: <855136ce-6c70-40ac-a462-dc0bbfa1fc3a@b2g2000prf.googlegroups.com> References: <855136ce-6c70-40ac-a462-dc0bbfa1fc3a@b2g2000prf.googlegroups.com> Message-ID: Aaron Scott wrote: > I'm having some trouble understanding how Python handles variables > across multiple modules. I've dug through the documentation, but I > still find myself at a loss. > > When you import a module, are you creating an instance of the > variables within? For instance, if I have one file, "variables.py", > which contains "myvar = 0", and I import it into both "foo.py" and > "bar.py" with the line "from variables import *", and then set myvar > in "foo.py" and "bar.py" to different values, will each file have a > different value for myvar? If so, how can I ensure that a change to > myvar in "bar.py" is reflected by "foo.py"? Or am I completely off > base? first read this to learn how objects and variables work in Python: http://effbot.org/zone/python-objects.htm and then read this to learn how from-import works, and when you're supposed to use it: http://effbot.org/zone/import-confusion.htm hope this helps! From mva.led at gmail.com Thu Jul 3 10:20:54 2008 From: mva.led at gmail.com (Manuel Vazquez Acosta) Date: Thu, 03 Jul 2008 10:20:54 -0400 Subject: A fix for OverflowError in 64bits platforms Message-ID: <486CE046.6080104@gmail.com> Hi all, I'm debugging a Plone site in an AMD64 laptop. When I first tried to run Zope, I got this exception: OverflowError: signed integer is greater than maximum In the archives I encounter no solutions. This is what I could find, so I share with you all: It seems that on 64bit platforms, sys.maxint is much greater than list's insertion maximum index. I'm not sure if this a bug in python or a logical bound ---given the amount of RAM it would take to insert 9,223,372,036,854,775,807 items ;)--- Maybe a bug in the documentation, though However, Archetypes.Schema.moveField method documents the use of maxint for inserting at the end of the Schema:: maxint can be used to move the field to the last position possible >>> from sys import maxint >>> spos = schema.copy() >>> spos.moveField('a', pos=maxint) >>> spos.keys() ['b', 'c', 'a'] I have seen this usage in some products. This raises and OverflowError on 64bit platforms. The fix is simple in the code of the caller:: from sys import maxint if maxint >> 33: # Am I running on 64bits? maxint = maxint >> 33 theschema.moveField(the_name, pos=maxint) Now, the maxint variable holds an acceptable value. I think the docstring should be appended with a "Note: On 64bits platform this raises an OverflowError blah blah..." Best regards, Manuel. From deets at nospam.web.de Tue Jul 29 07:32:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jul 2008 13:32:26 +0200 Subject: Python COM References: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> <488eff34$0$869$ba4acef3@news.orange.fr> Message-ID: <6f8dgfFabuohU1@mid.uni-berlin.de> M?ta-MCI (MVP) wrote: > Hi! > > Example, with Pywin32: > > import win32com.client > moncom = win32com.client.Dispatch('MyCOM1.AdvMethod') > moncom.IAdvMethod(... > > See Pywin32 here: http://sourceforge.net/projects/pywin32/ That's not working, because the OP has a custom interface, not IDispatch-based. Diez From jeffober at gmail.com Mon Jul 21 08:01:40 2008 From: jeffober at gmail.com (Jeff) Date: Mon, 21 Jul 2008 05:01:40 -0700 (PDT) Subject: simple question about dictionaries References: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> Message-ID: <8aedc744-f432-4a4a-a6e4-2bb714caf720@x35g2000hsb.googlegroups.com> On Jul 21, 7:35?am, skazhy wrote: > hi, i am new to python, so i've a really simple question about > dictionaries. > if i have a dictionary and I make have an input after it (to input > numbers) can i get the key of value that was in input? > > somehting like this: > dict = { "key1"=100,"key2"=200,"key3"=300} > a = input() > print 'the key of inputted value is', dict['a'] > > this syntax of course is wrong, but i hope you got the point.. > > thanks in advance! I don't think there is a built-in that retrieves dict keys by value, but if the dictionary were small enough, you could search the list of key/value pairs returned by dict.items(). You can also iterate through all pairs with dict.iteritems(), which returns an iterator. Something like: def key_by_value(dct, val): for k, v in dct.iteritems(): if v == val: return v throw KeyError('%s not found' % str(val)) From deets at nospam.web.de Thu Jul 31 05:29:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 11:29:02 +0200 Subject: working pylint anyone? Message-ID: <6fdf17Fb2bboU1@mid.uni-berlin.de> Hi, until yesterday I was a happy user of pylint. Then I upgraded to ubuntu hardy heron - and the trouble began. The packaged version of pylint (0.13.2) fails with this error (last line): logilab.common.configuration.UnsupportedAction: callback The same error happens if I use easy_install-2.5 http://release.ingeniweb.com/third-party-dist/logilab.installer-0.1.tgz as found on the net. Using easy_install pylint misses logilab-common & astng, installing these additionally (easy_install) creates two eggs - but unfortunately, the don't actually create a namespace-package logilab, instead either one of them is picked up depending on installation order. Then I tried the source releases - no luck either, either they produce the same error or something similar. I tried looking into the MLs - the last posts are from around 2006, so I refrained from actually subscribing. So - anybody out here having an actually working pylint config and can tell me what versions work together? I've become pretty dependend on it to be honest... Diez From boaz at feldbaum.name Fri Jul 18 09:14:27 2008 From: boaz at feldbaum.name (Boaz Feldbaum) Date: Fri, 18 Jul 2008 16:14:27 +0300 Subject: How to register an extension DLL with python 2.5? References: Message-ID: OK, found it! I just had to give my dll a new file extension: PYD, that is rename it from foo.dll to foo.pyd "Boaz Feldbaum" wrote in message news:g5pvco$j4c$1 at news4.netvision.net.il... > Hello all, > > I wrote an extension dll in C++ using VS2005 to be used in windows > platform. In pyhon 2.4 I used to copy my dll to the dlls sub-directory of > python installation and import my dll and it worked fine. This doesn't > work with python 2.5. I get the following when trying to import my dll: > >>>> import pywutil > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named pywutil >>>> > > What should I do in 2.5 to be able to import my extension dll? > > Thanks a lot in advance, > Boaz. > From mail at timgolden.me.uk Sun Jul 20 11:36:25 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 20 Jul 2008 16:36:25 +0100 Subject: Missing sqlite3.h Error when Building Debug Python -- Windows Vista In-Reply-To: <048b8df4-8468-47a1-ae15-d84ca9d43e0a@y38g2000hsy.googlegroups.com> References: <048b8df4-8468-47a1-ae15-d84ca9d43e0a@y38g2000hsy.googlegroups.com> Message-ID: <48835B79.6030105@timgolden.me.uk> Bev in TX wrote: > I am a complete newbie at building Python. I am trying to build it > under MS Windows Vista (64-bit AMD) with MS VS2005. I'm doing that > because I need debug libraries, which I did not see in the standard > distribution. I'll leave others to comment on whether or not it's expected to build with VS2005, but the easiest way to get a debug build is to pretend to be a buildbot. 1) Check out the python source into, say, c:\dev\python svn co http://svn.python.org/projects/python/trunk c:\dev\python 2) Switch to that directory cd \dev\python 3) Pretend to be a buildbot tools\buildbot\build This will checkout all the necessary sources into, in my example, c:\dev. It will then run all the build steps necessary to get a debug build which will then be in c:\dev\python\pcbuild\python_d.exe TJG From youlan_hao at sina.com Thu Jul 10 22:33:22 2008 From: youlan_hao at sina.com (128) Date: Thu, 10 Jul 2008 19:33:22 -0700 (PDT) Subject: paypal wholesale men jordans 17 (paypal accept)(www super-saler com Message-ID: paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans 18 (paypal accept)(www super-saler com paypal wholesale men jordans 19 (paypal accept)(www super-saler com paypal wholesale men jordans 20 (paypal accept)(www super-saler com paypal wholesale men jordans 21 (paypal accept)(www super-saler com paypal wholesale men jordans 22 (paypal accept)(www super-saler com paypal wholesale men jordans 23 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans 18 (paypal accept)(www super-saler com paypal wholesale men jordans 19 (paypal accept)(www super-saler com paypal wholesale men jordans 20 (paypal accept)(www super-saler com paypal wholesale men jordans 21 (paypal accept)(www super-saler com paypal wholesale men jordans 22 (paypal accept)(www super-saler com paypal wholesale men jordans 23 (paypal accept)(www super-saler com paypal wholesale men jordans (paypal accept)(www super-saler com paypal wholesale men jordans 1 (paypal accept)(www super-saler com paypal wholesale men jordans 2 (paypal accept)(www super-saler com paypal wholesale men jordans 3 (paypal accept)(www super-saler com paypal wholesale men jordans 4 (paypal accept)(www super-saler com paypal wholesale men jordans 5 (paypal accept)(www super-saler com paypal wholesale men jordans 6 (paypal accept)(www super-saler com paypal wholesale men jordans 7 (paypal accept)(www super-saler com paypal wholesale men jordans 8 (paypal accept)(www super-saler com paypal wholesale men jordans 9 (paypal accept)(www super-saler com paypal wholesale men jordans 10 (paypal accept)(www super-saler com paypal wholesale men jordans 11 (paypal accept)(www super-saler com paypal wholesale men jordans 12 (paypal accept)(www super-saler com paypal wholesale men jordans 13 (paypal accept)(www super-saler com paypal wholesale men jordans 14 (paypal accept)(www super-saler com paypal wholesale men jordans 15 (paypal accept)(www super-saler com paypal wholesale men jordans 16 (paypal accept)(www super-saler com paypal wholesale men jordans 17 (paypal accept)(www super-saler com paypal wholesale men jordans 18 (paypal accept)(www super-saler com paypal wholesale men jordans 19 (paypal accept)(www super-saler com paypal wholesale men jordans 20 (paypal accept)(www super-saler com paypal wholesale men jordans 21 (paypal accept)(www super-saler com paypal wholesale men jordans 22 (paypal accept)(www super-saler com paypal wholesale men jordans 23 (paypal accept)(www super-saler com From cromulent at justextrememetal.com Tue Jul 15 09:37:37 2008 From: cromulent at justextrememetal.com (Cromulent) Date: Tue, 15 Jul 2008 14:37:37 +0100 Subject: Why is there no GUI-tools like this for Windows? References: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> Message-ID: <2008071514373716807-cromulent@justextrememetalcom> On 2008-07-12 22:35:58 +0100, maestro said: > http://www.youtube.com/watch?v=PXpwC1o5AcI > > I have done some GUI-programming for windows with Python but the > Tkinter interface sucked and while it is the only one I tried I got > the impression they are all the same. > > It's amazing how retarded a lot of the stuff programmers do is. > Watcing that video, that is how it should be. > > I can just do the layout with my mouse and then there is a program > that writes the code for me. > GUI-programming is hard for no reason. One good program then forever > easy... > > Is there not something like this for Python/Windows? Is the Linux one > only for ruby or for any language? > > Oh well im switching to Linux anyway and mostly write webapps but > still... PyQt4 is available for Windows and lets you use the Qt Designer application which is pretty good. Works well, you should take a look. -- "I disapprove of what you say, but I'll defend to the death your right to say it." - Voltaire From george.sakkis at gmail.com Fri Jul 11 19:18:34 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 11 Jul 2008 16:18:34 -0700 (PDT) Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> Message-ID: On Jul 11, 1:00?pm, James Fassett wrote: > Hi all, > > Had a simple problem that turned into an interesting solution and I > thought I would share it here. > > I had a list of tuples that I needed to get the first value from and > generate a list. > > tuple_list = ( > ? ? ('John', 'Doe'), > ? ? ('Mark', 'Mason'), > ? ? ('Jeff', 'Stevens'), > ? ? ('Bat', 'Man') > ? ) > > # what I'd do in C or other procedural languages > result_list = [] > for item in tuple_list: > ? ? result_list.append(item[0]) > > # the first Pythonic attempt using comprehensions > result_list = [x[0] for x in tuple_list] > > # the final functional way > [result_list, _] = zip(*tuple_list) > > I really like how Python allows me to do what I feel is the most > natural solution (for a seasoned procedural programmer) while allowing > a satisfying path towards a more functional approach. First off, what exactly does make you think of the last approach as "functional" ? It relies on positional arguments, tuple unpacking and the signature of zip(), none of which are functional in the usual programming language sense of the word. Second, it is less readable, robust and efficient than the list comprehension. An example of a really functional approach without all these drawbacks would be bearophile's map(itemgetter(0), tuple_list) since itemgetter() is a high order function (more specifically, a function that returns another function). The list comprehension is still the most pythonic approach though. Regards, George From tjreedy at udel.edu Thu Jul 24 21:33:17 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jul 2008 21:33:17 -0400 Subject: file operations. In-Reply-To: <73045cca0807241546k3697a77cs999bad6d62867167@mail.gmail.com> References: <73045cca0807241546k3697a77cs999bad6d62867167@mail.gmail.com> Message-ID: aditya shukla wrote: > Guys thanks for your previous help .I have a doubt again > > My text file is :- > > 0\9\10\11|0.50|c:\windows\apppatch/AcLayers.dll ... > > now this is what happens > > >>> x=open("c:\\test2.txt","rb") > >>> x.readline() > > '\n' ---? i am not able to understand why is new line character > returned here Either because your text file starts with a blank line or because .readline does not work when you open in binary mode. In any case, you should probably change 'rb' to 'r'. > > >>> l =x.readline() > >>> print l > > > Also , because of this i am not able to extract the floating point > values ie 0.50,0.50,0.66 respectively > cause when i use the proposed solution given earlier > > data=[] > for line in x: > line=line.split("|") > data.append(float(line[-2])) --> i am trying to get the floating > point values from the back > > i receive this error message > > Traceback (most recent call last): > File "", line 3, in > d.append(float(line[-2])) > IndexError: list index out of range If you have a blank line, splitting returns a list of length 0 or 1, so there is no -2 element. Add something like if len(line) < 2: raise SomeError(message) after the split. If you should always have 3 parts, check '==3' and index to line[1]. tjr From siona at chiark.greenend.org.uk Wed Jul 30 09:14:42 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 30 Jul 2008 14:14:42 +0100 (BST) Subject: Native Code vs. Python code for modules References: Message-ID: alex23 wrote: >On Jul 30, 1:56=A0pm, koblas wrote: >> Ruby has been getting pummeled for the last year or more on the >> performance subject. =A0They've been working hard at improving it. =A0Fro= >m >> my arm chair perspective Python is sitting on it's laurels and not >> taking this as seriously as it probably should. > >Well, the snarky response is most Python developers are too busy >working on actual real world projects :) The follow-up snarky response is that working on actual real world projects has lead Python developers to realise that most real world bottlenecks arise from disk access, network speed, and user interaction, and you should only sweat about code speed in the rare case when you *know* that it's not its interface to the real world that's slow. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From Russ.Paielli at gmail.com Wed Jul 30 02:30:48 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 23:30:48 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> Message-ID: <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> On Jul 29, 11:09 pm, Erik Max Francis wrote: > I'm getting this sneaking suspicion that you guys are all putting us on. As I said in an earlier post, I realize that this would only work if there were only one copy of "empty" (as there is only one copy of "None"). I don't know off hand if that is feasible or not. You reply reeks of the kind of pedantic snobbishness that makes me sick. From kdawg44 at gmail.com Fri Jul 18 16:09:58 2008 From: kdawg44 at gmail.com (K-Dawg) Date: Fri, 18 Jul 2008 16:09:58 -0400 Subject: Distributing Python App In-Reply-To: References: <072bf39b-d700-482e-ab59-36840e21e83e@a70g2000hsh.googlegroups.com> Message-ID: <5caea3690807181309x686727dbs6d72fa6f594978d8@mail.gmail.com> On Fri, Jul 18, 2008 at 3:43 PM, Stephen Johnson wrote: > Look up py2app and py2exe, for OS X and Windows, respectively. They are > extensively documented and easy to use. > On Jul 18, 2008, at 3:35 PM, KDawg44 wrote: > > Hi, > > I am very new to Python but find it very interesting (from what I know > of it) and am considering writing an application. However, I have a > question regarding distribution of the app once it is done. Is there > a way to package everything a user needs to run the app or will they > have to install Python their machine? This is probably an obvious > question but most development I do is for administrative tasks on > servers and such, not usually development of an app for someone else. > > Thanks for your help. > > Kevin > -- > http://mail.python.org/mailman/listinfo/python-list > > > Thanks! I'll look into that. -- Kevin "We are what we repeatedly do. Excellence, then, is not an act, but a habit." - Aristotle." -------------- next part -------------- An HTML attachment was scrubbed... URL: From hat at se-162.se.wtb.tue.nl Wed Jul 9 05:04:21 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 09 Jul 2008 11:04:21 +0200 Subject: Newbie question References: <3b1e6f480807082337l419fd40ax91eaf13e0701c5b3@mail.gmail.com> Message-ID: On 2008-07-09, |e0 wrote: > So, i can't use wmi module on linux? > > On Wed, Jul 9, 2008 at 9:14 AM, Lamonte Harris wrote: >> I think the win32 module is only for windows. >> Welcome to the world outside MS. Many python modules don't actually do anything than passing on calls to an existing underlying library. They are cheap to make, and make it possible to use the functionality of the library from a Python program. The down-side is, as you have discovered, that you need the underlying library to make it work. So, the answer is no, you cannot use wmi under a non-MS OS. (But what did you expect, given that wmi means WINDOWS Management Instrumentation?) No doubt there are also open source variants of this package, however, I am not familiar with them, so I cannot help you. Albert From joe at goldthwaites.com Tue Jul 1 20:51:35 2008 From: joe at goldthwaites.com (Joe Goldthwaite) Date: Tue, 1 Jul 2008 17:51:35 -0700 Subject: SQLite and Python 2.4 Message-ID: <200807020051.m620pxS4011942@vm-mailout2.fpw.ch> I'm confused. (Not a new experience). I've got a web application running under Zope. I use the Wing IDE for testing and debugging. When trying to recreate problems that come up on the web, I wrote some little routines that pull my cookies out of the Firefox cookies.txt file into my code. That way, I'm working with all the same options under Wing that my app uses when running under Zope. That's worked great until I upgraded to Firefox 3. Firefox 3 moved their cookies from cookies.txt to cookies.sqlite. I haven't worked with SQLite at all so I started searching for examples and found this; import sqlite3 conn = sqlite3.connect('test.db') c = conn.cursor() rows = c.execute('SELECT * from somefile') Looks simple enough but I can't get it to work. Here are my questions; 1. How do you get sqlite3 for Python 2.4? I can't find it anywhere. 2. If sqlite3 is only for Python 2.5, does sqlite2 work the same way? 3. Looking at the cookies.sqlite file, I see some text right at the top "SQLite format 3". Does that mean that I need to use sqlite3? I kind of got the above example using pysqlite2.4.1 for python 2.4. I get through the part where I create the connection object but the resulting object doesn't have a cursor method. I thought that maybe it wasn't recognizing the cookies.sqlite file as a SQLite database so I tried the same code giving it a junk text file instead and it behaved the same way. Since I didn't get an error message, I'm thinking that I've got the wrong version for the Firefox cookies.sqlite file. I don't have a clue as to where else to look to trace it down. I'm hoping that someone here is more familiar with it and can give me some pointers. Thanks, Joe Goldthwaite From bronger at physik.rwth-aachen.de Sat Jul 26 17:49:29 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 26 Jul 2008 23:49:29 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> Message-ID: <87fxpw8geu.fsf@physik.rwth-aachen.de> Hall?chen! Terry Reedy writes: > Torsten Bronger wrote: > >> D'Arcy J.M. Cain writes: >> >>> On Sat, 26 Jul 2008 09:45:21 +0200 >>> Torsten Bronger wrote: >>> >>>> Of course, "self" would have to become a reserved word. You >>>> could say that this may break some code, but I don't see much >>>> freedom >>> >>> Isn't this a showstopper all by itself? >> >> Yes. But I've seen no code that uses some other word. > > There is a lot of code you have not seen. Really. In informal > code I use 's' and 'o' for 'self' and 'other'. I don't usually > post such because it is not considered polite. So you have seen a > biased sample of the universe. I didn't say that no code breaks, nor that I've analysed more than 0.1% of the global Python code. But still, this doesn't convice me. I still think that only a very small fraction of Python code would break. Since no one can make a global analysis, it is more sensible to compare it with the amount of code broken by Python 3.0 in my opinion. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From alexnbryan at gmail.com Sat Jul 5 04:15:32 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Sat, 5 Jul 2008 03:15:32 -0500 Subject: Tkinter Text widget get() Message-ID: <682C7C6A-9172-4673-955E-5B775115A689@gmail.com> Hey guys. I am having trouble understanding the get() method from the Tkinter Text() widget. It isn't like the entry.get() one I am used to. I know you have to put tags in, or at least I read. I tried this but it didn't work. I think I was putting the tags in wrong but I am not sure. I just need an example. So if someone could maybe modify this code to get EVERYTHING inside the text widget. text = Text(parent) text.pack() text.insert(END, "I am text!") Of course, I will have much more text, but I still want to get everything in the box. From fredrik at pythonware.com Tue Jul 22 12:28:28 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 18:28:28 +0200 Subject: Automatically loading and initialising objects from a plugins directory In-Reply-To: <488607BC.3040204@ecs.soton.ac.uk> References: <488607BC.3040204@ecs.soton.ac.uk> Message-ID: Dave Challis wrote: > Thanks for that, it helped as a starting point. I had some trouble with > using issubclass though (issubclass(Plugin, Plugin) returns true), which > was complicating things. > > I modified your code to the following instead (which may well have it's > own pitfalls I'm not aware of!): > > for name in dir(plugin): > thing = getattr(plugin, name) > if hasattr(thing, '__bases__') and \ > getattr(thing, '__bases__')[0] == Plugin: > thing() so now you're no longer supporting mixins and multiple-level inheritance? why not just tweak Diez' example a little: for name in dir(plugin): thing = getattr(plugin, name) # make sure this is a plugin try: if thing is Plugin: continue if not issubclass(thing, Plugin): continue except ValueError: # issubclass sucks continue # not a class thing() # probably needs error handling around this (I also moved the thing call out of the thing validation part, to allow you to distinguish between ValueErrors caused by issubclass and errors caused by things) (btw, another approach would be to use a metaclass to make Plugin classes register themselves on import) From larry.bates at websafe.com` Thu Jul 3 15:20:14 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 03 Jul 2008 14:20:14 -0500 Subject: Instance Names In-Reply-To: References: Message-ID: Tim Cook wrote: > Hi All, > > I have a need (if at all possible) to create instance names using '[' > and ']', i.e. [at0000]=ClassA0(), [at0001]=ClassB2(), etc. > > Of course Python tries to unpack a sequence when I do that. Is there > anyway to do this? > > I do have a workaround but it is an ugly, nasty URL mangling thing. :-) > > Cheers, > Tim > > > I suspect there is some "misunderstanding" here. Why exactly do you think you need to have your instances named with [] characters in them? You could put them in a dictionary: instances = {} instance['[at0000']] = ClassA0() but that isn't really different than: instance['at0000'] = ClassA0() -Larry From tamim.shahriar at gmail.com Sun Jul 6 06:32:48 2008 From: tamim.shahriar at gmail.com (subeen) Date: Sun, 6 Jul 2008 03:32:48 -0700 (PDT) Subject: Not necessarily related to python Web Crawlers References: Message-ID: <9fe3fff7-00c5-495f-a6d0-c64187af746b@d45g2000hsc.googlegroups.com> On Jul 5, 2:31?pm, disappeare... at gmail.com wrote: > Hi > Does anyone here have a good recommendation for an open source crawler > that I could get my hands on? It doesn't have to be python based. I am > interested in learning how crawling works. I think python based > crawlers will ensure a high degree of flexibility but at the same time > I am also torn between looking for open source crawlers in python vs C > ++ because the latter is much more efficient(or so I heard. I will be > crawling on very cheap hardware.) > > I am definitely open to suggestions. > > Thx You can check my python blog. There are some tips and codes on crawlers. http://love-python.blogspot.com/ regards, Subeen http://love-python.blogspot.com/ From steve at REMOVE-THIS-cybersource.com.au Tue Jul 29 19:30:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 23:30:12 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: <009fa37d$0$20313$c3e8da3@news.astraweb.com> On Tue, 29 Jul 2008 10:30:43 -0700, Carl Banks wrote: > On Jul 29, 5:15 am, Heiko Wundram wrote: >> I can't dig up a simple example from code I wrote quickly, but because >> of the fact that explicit comparisons always hamper polymorphism > > I'm not going to take your word for it. Do you have code that > demonstrates how "if x" improves polymorphism relative to simple > explicit tests? On the rapidly decreasing chance that you're not trolling (looking more and more unlikely every time you post): # The recommended way: if x: do_something # Carl's so-called "simple explicit tests" applied to polymorphic code: try: # could be a sequence or mapping? # WARNING: must do this test *before* the number test, otherwise # "if [] != 0" will return True, leading to the wrong branch being # taken. if len(x) != 0: do_something except AttributeError: # not a sequence or mapping, maybe it's a number of some sort try: int(x) except TypeError: # not convertable to numbers # FIXME: not really sure what to do here for arbitrary types # so fall back on converting to a boolean, and hope that works if bool(x): do_something else: if x != 0: do_something But wait... that can be re-written as follows: if bool(x): do_something and that can be re-written without the call to bool: if x: do_something -- Steven From __peter__ at web.de Mon Jul 14 11:44:20 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 14 Jul 2008 17:44:20 +0200 Subject: subprocess module References: <2e7f0504-cc1c-4cb6-b2d0-b67b004eca7d@x41g2000hsb.googlegroups.com> <39622612-5e43-45b4-800a-69277c2e2987@79g2000hsk.googlegroups.com> Message-ID: John Mechaniks wrote: > On Jul 14, 12:34?pm, Peter Otten <__pete... at web.de> wrote: >> John Mechaniks wrote: >> > from subprocess import call >> > call(['ls', '-l']) >> >> > How do I get the result (not the exit status of the command) of "ls - >> > l" into a variable? >> >> output = subprocess.Popen(["ls", "-l"], >> stdout=subprocess.PIPE).stdout.read() > What difference does the following code makes? What are the advantages > of the above method over this one? > output = subprocess.Popen(['ls', '-l'], > stdout=subprocess.PIPE).communicate()[0] Hm, I chose it because it looks cleaner. Looking into the source Popen.communicate() seems to do the following: output = p._fo_read_no_intr(p.stdout) p.wait() So there are two differences in this case - communicate() waits for the subprocess to terminate. - stdout.read() is retried if an EINTR occurs (Not sure when this would happen). > Also could someone show an example of using the optional input > argument for communicate() http://blog.doughellmann.com/2007/07/pymotw-subprocess.html I didn't read it myself, but Doug Hellmann's articles are usually quite good. Peter From larry.bates at websafe.com` Tue Jul 15 19:39:53 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 18:39:53 -0500 Subject: Python internals In-Reply-To: <87hcaq7pja.fsf@benfinney.id.au> References: <008ca729$0$20313$c3e8da3@news.astraweb.com> <87hcaq7pja.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Larry Bates writes: > >> Names are pointers in Python that point to values in memory. > > The term "pointer" carries much extra baggage for a programmer > thinking of C (as the original poster is). Python names give no access > to the "address" of the value, and don't need to be "de-referenced". > > I've had better success explaining Python names to such people in > terms of "references": there is no "address" and no "de-reference" > needed. Access the name, and you get its value. > > On the other hand, I prefer to avoid using either of those concepts, > and talk in terms of "name tags" or "sticky notes". Names (and other > references, like list elements) attach to the object, and have no > other value or purpose. They don't affect the object they're attached > to; they are entirely independent of other bindings to the same > object; they re-bind to another object with no history of what they > were bound to previously. > > The analogy is quite robust, and carries none of the confusing baggage > of "variable" or "pointer" or other overloaded language terms. > You are, of course, correct. Since I'm not a C programmer, the term pointer doesn't carry the same "baggage" as it might to others. The "problem" I had when I first started is that people were using such "vague" terms like names, tags, etc. that it had no meaning to me. I like your idea of "references". -Larry From M8R-yfto6h at mailinator.com Sun Jul 20 12:50:30 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Sun, 20 Jul 2008 09:50:30 -0700 Subject: getting with statement to deal with various exceptions References: Message-ID: "mk" wrote in message news:mailman.349.1216557748.922.python-list at python.org... > Hello, > > I'm trying to learn how with statement can be used to avoid writing: > > prepare() > try: > something_that_can_raise_SomeException() > except SomeException, err: > deal_with_SomeException > finally: > tear_it_down() > > Verbose, not very readable. OK, "with" to the rescue? > > Let's take a textbook example from PEP: > > with open('/etc/passwd', 'r') as f: > BLOCK > > Well, great, it's neat that "with" closes the file after BLOCK has > finished execution, but what if the file isn't there and attempt to open > it raises IOException? I'd like to be able to catch it precisely to avoid > writing verbose try: .. except: .. finally: .. blocks which as I > understand has been much of the rationale behind creating "with" statement > in the first place. > > "with" statement only allows easy dealing with prepare() and > tear_it_down(). When I try to get it to deal with exceptions that might > happen, it becomes more complicated: > > class FileContextManager: > def __enter__(self, filename, mode): > f = open(filename, mode) > return f > def __exit__(self, etype, evalue, etraceback): > print "etype", etype, "evalue", evalue, "etraceback", etraceback > > > >>> with FileContextManager("somefile", "r") as f: > a = f.readlines() > > > > Traceback (most recent call last): > File "", line 1, in > with FileContextManager("somefile", "r") as f: > TypeError: this constructor takes no arguments > > > Bummer. > > Plus, no documentation I've read (on effbot, in PEP 343, etc) says how to > deal with the exception happening in __enter__ method of context manager, > which is precisely what I'd like to do. > > This is only natural, isn't it? When e.g. reading the file, preparation > phase is typically checking if it can be opened in the first place. So it > falls into __enter__ method of context manager. > > "with" limited only to successful execution of a_statement from "with > a_statement" seems like limited benefit to me. > > I'd like to be able to write smth like > > class FileContextManager: > def __enter__(self, filename, mode): > f = open(filename, mode) > return f > def __except__(IOError, err): > do_this > print err > def __except__(RuntimeError, err): > do_that > print "something bad happened", err > def __exit__(self, etype, evalue, etraceback): > print "etype", etype, "evalue", evalue, "etraceback", etraceback > > __exit__ deals with exceptions happening in the BLOCK below "with" > statement, not with exceptions raised in "a_statement", when executing > > with a_statement as var: > BLOCK > > In the above way "with" would give me the benefit of more terse, but still > understandable and efficient code. > > Well, I can always do this: > > try: > with open("somefile.txt") as txtfile: > for line in txtfile: > print line > except IOError: > print "No such file." > > > No such file. > > > But that's just ugly, nested too many times (flat is better than nested, > right?) and not all that more readable. I just started looking at the with statement myself. How about: from __future__ import with_statement class ExceptionManager(object): def __enter__(self): pass def __exit__(self,exc_type,exc_value,tb): if exc_type == IOError: print 'IOError',exc_value[1] return True # suppress it with ExceptionManager(): with open('test.txt') as f: f.read() -- Mark From babacity4 at gmail.com Thu Jul 24 16:55:38 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:55:38 -0700 (PDT) Subject: Peachy18 com - Amazing porn video collection Message-ID: peachy18 com . >>>>>>>>>>Best Collection of Peachy18 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE peachy18 VIDEOS<<<<<<<<<<< . peachy18 com From news at prodata.co.uk Tue Jul 1 07:23:22 2008 From: news at prodata.co.uk (John Dann) Date: Tue, 01 Jul 2008 12:23:22 +0100 Subject: Scope and program structure problems Message-ID: Trying to learn Python here, but getting tangled up with variable scope across functions, modules etc and associated problems. Can anyone advise please? Learning project is a GUI-based (wxPython) Python program that needs to access external data across a serial port. The first thing that I need the program to do when it starts up is to check that it can see the serial port, the first step of which is to check that it can import the pySerial module, and display an appropriate message in the statusbar of the main frame. (I know there may be other ways of doing this but this is what I'm trying to do currently and I'd like to understand how to make this approach work robustly even if there are other options.) So it seems that if I want to write to the frame's statusbar, I can't do anything re serial import until the frame is initialising. And I can't put any serial import code after the app.Mainloop() code line because it won't run until the frame closes. In other words, I seem to be stuck with importing the serial library either in the __init__ function or - if implemented slightly differently - in a separate function of the wxPython Frame class, ie a code structure of: ----------- # Can't put serial import code here because there's no GUI yet to send messages to. Class Frame(wx.Frame) def __init__() etc #code to check and use serial port has to go below?? def CheckSerial() # eg triggered by appropriate menu click event Try: import serial etc ser = Serial.etc # set ser object as handle to serial port def UseSerial(): # Code to perform serial IO app=App(wx.App) app.MainLoop() # Can't put serial import code here because it won't execute until frame closes? ----------- But then I hit another problem. If I set the object ser to point to the serial port in the CheckSerial function, then it's just got local scope within the function and can't be seen from the UseSerial function. So I've got 2 questions. The main one is whether there's any way of explicitly giving the ser object global scope in the code line: ser = Serial.etc # set ser object as handle to serial port And, second, does my overall description above reveal any serious misunderstanding about how best to handle this sort of problem in Python? Apologies for the long post and hope that my description is clear enough to make sense. JGD From grante at visi.com Tue Jul 1 18:44:19 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 01 Jul 2008 17:44:19 -0500 Subject: Implementing an 8 bit fixed point register References: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> Message-ID: On 2008-07-01, Terry Reedy wrote: >>> A bytearray subclass could enforce that all 'bits' (stored as >>> bytes) are 0 or 1, have a customized representation to your >>> taste, and add methods like .flipall(). >> >> It seems like implementing ALU operations on such arrays would >> be a lot more work than implementing bit-indexing on a type >> derived on a more "integer" like base. I'm pretty fuzzy on how >> one sub-classes basic things like integers, so maybe I'm all >> wet, and adding __getitem__ and __setitem__ to an integer type >> isn't even possible. > > If one only wants bit operations, then the array approach is > easy. If one only wants int arithmetic and all-bits logic, > then int approach is easy. OP did not completely specify > needs. He said he's writing a microprocessor simulator, so he's going to want integer operations, all-bits logical operations, and individual bit acess (by number and by name) and bit-slice access. > The problem with the int approach is that ints are immutable. That dawned on me after I started googling around a little. > Therefore, if one wants to subclass int to hide the bit > masking for the bit operations, one must override *every* > operation one might use, including all arithmetic and all-bits > logic, even when the int operation gives the correct answer > other than the class of the result. Since we're doing fixed-width operations, Python's int operations don't give the correct answer other than the class of the result. > class bits(int): > ... > def __add__(self,other): > return bit(self+other) > ... > > If one does not, > > a,b = bits(1),bits(2) > c = a+b #c is now an int, not a bits > > So there is a tendency to not subclass and instead either leave the > extra functionality unmasked in repeated code or to put it in functions > instead. > > setters = (1,2,4,8,16,32,64, ..., 2147483648)# slightly pseudocode > unsetters = (~1,~2,~4,...~2147483648) # ditto > def bitset(n, bit): return n | setters[bit] > def bitunset(n,bit): return n & unsetters[bit] On a machine with a barrel shifter, it's probably faster to do this: def bitset(n,bit): return n | (1< thus not getting the nice reg[n] functionality, nor an easy > display of individual bits without callings *another* > function. > > One the other hand, with mutable arrays, setting bits is a > mutation and so no override of __setitem__ is required unless > one wants to be fancy and enforce setting to 0 or 1. More importantly, I presume that slices are supported so when you need values of bit-fields, you can do this: op = instruction[6:8] src = instruction[3:6] dest = instruction[0:3] The half-closed interval notation for slices is probably going to drive the programmer up the wall because all of the documentation that's being followed uses closed intervals. > It is a trade-off. And Python programmers are awfully spoiled. :) -- Grant Edwards grante Yow! I think my career at is ruined! visi.com From rocksportrocker at googlemail.com Sun Jul 13 12:32:47 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Sun, 13 Jul 2008 09:32:47 -0700 (PDT) Subject: wxPython Tab References: Message-ID: <75018ae6-6d8c-4962-9fd0-aedb52ad626f@k30g2000hse.googlegroups.com> On Jul 13, 6:20?pm, Sparky wrote: > Is there a way to get wxPython to change the visible tab in a notebook > (like I have tab 1 open but the computer will automatically change to > tab 2)? > > Thanks, > Sam look at http://docs.wxwidgets.org/stable/wx_wxnotebook.html#wxnotebooksetpagetext greetings, uwe From steve at REMOVE-THIS-cybersource.com.au Sun Jul 13 02:49:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 13 Jul 2008 01:49:31 -0500 Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: On Sat, 12 Jul 2008 16:32:25 -0400, Terry Reedy wrote: > Steven D'Aprano wrote: >> On Thu, 10 Jul 2008 14:09:16 -0400, Terry Reedy wrote: >> >>>>>>>> g = lambda x:validate(x) >>> This is doubly diseased. >>> >>> First, never write a 'name = lambda...' statement since it is >>> equivalent to a def statement except that the resulting function >>> object lacks a proper .funcname attribute. >> >> Using lambda in this way is no more "diseased" than aliasing any other >> object. > > In the context of giving advice to a confused beginner, I disagree. He > must learn def statements. Lambda expressions are optional. Lots of things are optional. sets and frozen sets and decorators and classes and all sorts of things are optional, *and* capable of being misused and/or abused. Would you describe properties as "diseased" because some people might fill their classes with useless getters and setters? > > It's a matter of personal preference not to bind a lambda to a >> name. Functions, whether created by lambda or def, are first class >> objects, and as such there's nothing wrong with binding them to names. > > When I brought this up on pydev, in the context of a style guide > addition, about 9 of 10 respondants agreed that this should be > discouraged. Alex Martelli reported his experience that this > construction more often leads people to the useless wrapping of function > calls, such as the OP posted, than the def statement equivalent does. I have great respect for Alex, but anecdotes of that nature aren't proof. Such anecdotal evidence is subject to confirmation bias. I'm sure that Alex remembers the stupid pieces of code where people make such mistakes but I doubt very much he remembers the cases where they don't. But as a style guide... fine. Tell people it is discouraged. Tell them that other Python developers will laugh at them if they do it, apart from the ten percent who don't mind named lambdas. Point out that, like factory functions, there's a debugging cost to having functions with a unhelpful func_name attribute. But don't cross that line from discouragement to telling people that it is wrong to use named lambdas. That's what I object to. > One of the major reasons people give for wanting lambda expressions kept > in Python and for using them is that they do not want to have to think > up a name for short expressions. If such a person then turns around and > binds the resulting function object to a name, then that rationale > disappears. That does not follow. The fact that I might choose to occasionally bind a lambda to a name doesn't mean I never use unbound functions. Your argument is like saying that the rationale for air conditioners ("cooling in the hot weather") disappears because we can also use reverse-cycle air conditioners for heating in the cold weather. Lambdas are *necessary* if you want anonymous functions, just as we have anonymous strings, anonymous integers and so forth. It would be a poor language that forced people to write this: x = 1 s = 'two' def f(arg): return arg+3 mylist = [x, s, f] instead of the more sensible: mylist = [1, 'two', lambda arg: arg+3] That's why we need lambda. But once we have lambda, there is absolutely no reason why we must prohibit other uses of it. Given the above definition of mylist, would you then describe the following piece of code as "diseased"? def foo(mylist): g = mylist[2] for i in xrange(10000): print g(i) That's a perfectly good micro-optimization technique, and I would hope you would not reject it merely because the function was anonymous. That would be irrational. I'm not defending the Original Poster's use of lambda in that specific piece of code. You are right to criticize it *specifically*. What I object to is that you generalize that criticism, and treat a personal preference as an absolute rule. By all means think my code is ugly for using named lambdas, and by all means tell me you think it is ugly, but don't tell me I'm corrupting the youth of today with my filthy disease- ridden code. -- Steven From cjw at ncf.ca Mon Jul 28 07:21:05 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 28 Jul 2008 07:21:05 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <488D5B2C.10808@gmail.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <488D5B2C.10808@gmail.com> Message-ID: <488DABA1.6030207@ncf.ca> An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sun Jul 13 19:17:52 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 13 Jul 2008 16:17:52 -0700 (PDT) Subject: Mutually referencing imports -- impossible? References: <2e6bcb14-1db7-413b-afa7-62a11c9e33e4@26g2000hsk.googlegroups.com> Message-ID: On Jul 14, 5:30 am, John Roth wrote: > On Jul 13, 11:55 am, Matthew Wilson wrote: > > > > > I started off with a module that defined a class Vehicle, and then > > subclasses Car and Motorcycle. > > > In the Car class, for some bizarre reason, I instantiated a Motorcycle. > > Please pretend that this can't be avoided for now. > > > Meanwhile, my Motorcycle class instantiated a Car as well. > > > Then I moved the Car and Motorcycle classes into separate files. Each > > imported the Vehicle module. > > > Then I discovered that my Car module failed because the global > > Motorcycle wasn't defined. The same problem happened in my Motorcycle > > module. Car and Motorcycle can't both import each other. > > > In the beginning, when all three (Vehicle, Car, and Motorcycle) were > > defined in the same file, everything worked fine. > > > I don't know how to split them out in separate files now though and I > > really wish I could because the single file is enormous. > > > Any ideas? > > > Matt > > While it's possible for circular imports to work, it's very dangerous: > it's not always possible to tell what went wrong without tracking down > the process of the import step by step. There are more productive ways > of banging your head against the wall and going insane. > > In your situation, it might be a whole lot easier to extract a common > superclass that both of your classes could inherit from. > Like the Vehicle class the OP mentioned? From fredrik at pythonware.com Fri Jul 25 07:54:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 13:54:34 +0200 Subject: object persistency, store instances relationship externally In-Reply-To: <3183af12-4b1e-4bd1-8d21-b9fc2b421008@v1g2000pra.googlegroups.com> References: <3183af12-4b1e-4bd1-8d21-b9fc2b421008@v1g2000pra.googlegroups.com> Message-ID: King wrote: > This is a new test for object persistency. I am trying to store the > relationship between instances externally. > It's not working as expected. May be I am doing it in wrong way. Any > suggestions? The shelve module pickles each stored item individually. To preserve inter-object relations, try putting all related things in a tuple, and store that instead. E.g. shelf['data'] = (a, lst) a, lst = shelf['data'] From trentm at activestate.com Mon Jul 14 13:52:51 2008 From: trentm at activestate.com (Trent Mick) Date: Mon, 14 Jul 2008 10:52:51 -0700 Subject: Building a Python app with Mozilla In-Reply-To: References: <46867432.7060400@codebykevin.com> <4686CC45.9010405@sweetapp.com> Message-ID: <487B9273.9010200@activestate.com> > Brian Quinlan wrote: >> Most application logic in Komodo is implemented in Python, using the >> PyXPCOM bindings. The UI is implemented using XUL and JavaScript. The >> editor is Scintilla (C++). >> >> ../Komodo Edit.app/Contents/MacOS % find . -name "*.py" | xargs wc >> ... >> ... >> 126392 456858 4949602 total >> >> This doesn't include the python code in the Python libraries themselves. An interesting breakdown here: http://www.ohloh.net/projects/10861/analyses/latest happybrowndog wrote: > Is that why Komodo is so damned slow???? Probably not, no. Pinpointing the reasons for slowness is often a lot more complicated. Particular slow points in any app/module -- especially pathologically slow things -- are more often algoritmic than a function of the language used. Komodo's use of Python is perhaps partially responsible for a slower startup time than might otherwise be possible -- but otherwise my experience in Komodo perf work has been algorithmic issues. Also, if Komodo hadn't been using Python for application logic since day one we probably wouldn't be much further than Notepad right now. :) Cheers, Trent (komodo developer) -- Trent Mick trentm at activestate.com From 2007 at jmunch.dk Thu Jul 24 08:24:38 2008 From: 2007 at jmunch.dk (Anders J. Munch) Date: Thu, 24 Jul 2008 14:24:38 +0200 Subject: Recursion Performance Question In-Reply-To: References: Message-ID: <48886e03$0$5958$ba624c82@nntp06.dk.telia.net> B wrote: > > # pass in window handle and parent node > def gwl(node, hwnd): > if hwnd: > yield node, hwnd > for nd, wnd in Wnd.gwl(node.children[-1], GetWindow(hwnd, > GW_CHILD)): > yield nd, wnd > for nd, wnd in Wnd.gwl(node, GetWindow(hwnd, GW_HWNDNEXT)): > yield nd, wnd [...] > > Now it works, but it runs quite slow (compared to the c++ app). I > changed gwl from strait recursion to use a generator and that helped, > but it still takes 0.5-1.0 seconds to populate the tree. Actually the generator could well be the problem here, because of time spent on yield propagation: gwl has worst-case quadratic performance, the worst case being if the tree is unbalanced and deep, because every yielded value must pass through a chain of propagation for-loops. Straight recursion should be faster; I don't know what you did to make it slow, but try something along these lines: def gwl_helper(node, hwnd, collect): if hwnd: collect((node,hwnd)) gwl_helper(node.children[-1], GetWindow(hwnd, GW_CHILD), collect) gwl_helper(node, GetWindow(hwnd, GW_HWNDNEXT), collect) def gwl(node, hwnd): result = [] gwl_helper(node, hwnd, result.append) return result - Anders From cokofreedom at gmail.com Wed Jul 9 10:56:04 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 9 Jul 2008 07:56:04 -0700 (PDT) Subject: You, spare time and SyntaxError Message-ID: def ine(you): yourself = "what?" go = list("something"), list("anything") be = "something" please = be, yourself yourself = "great" for good in yourself: if you is good: good in you please.add(more, good) else: def inition(lacks, clarity): if clarity not in you: please.remove(everything and go) for bad in yourself: list(bad) if bad else (ignore, yourself) try: (to, escape, your, fate, but) except (Exception), son: if bad in (you, son): (you is bad, son), so finally: if bad in you: lie, cheat, steal, be, bad else: print you, "is", yourself you is good and yourself is not bad please, go ine("Everyone") From conman5525 at gmail.com Fri Jul 18 18:47:00 2008 From: conman5525 at gmail.com (conman5525 at gmail.com) Date: Fri, 18 Jul 2008 15:47:00 -0700 (PDT) Subject: Any Game Developers here? References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: On Jul 18, 2:38?pm, Michael Lubker wrote: > Any people that use Python as the predominant language for their game > development here? > > ~Michael The Panda3d engine supports the development of 3d simulations in python. Disney uses the engine in two of their MMO games (toontown and pirates of the carribean). CMU uses it in their virtual reality lab course. The source and pre built binaries are available at www.panda3d.org From asd at pittle.org Sun Jul 6 07:09:22 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Sun, 6 Jul 2008 04:09:22 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> <9cdbb215-d427-4694-a455-f2571ad42390@x19g2000prg.googlegroups.com> <54e0e7c5-113e-4296-a62f-e649d6ffa2d6@z66g2000hsc.googlegroups.com> <87b10cf3-4fd4-46e3-a33a-528f1180f69a@s21g2000prm.googlegroups.com> Message-ID: <6df87bb6-12c1-4a2d-9d3d-3eec0f94069f@e53g2000hsa.googlegroups.com> On Jul 4, 7:10?am, Yu-Xi Lim wrote: > Ali Servet D?nmez wrote: > > > I tried code come completion options in Emacs for Python, but none of > > them was satisfactory to me. I'd be glad to hear how did your friend > > get it work though. > > Perhaps it would help to say what ways the completion in Emacs was not > satisfactory? I simply couldn't manage to get it work. > FWIW, it should be possible to get IPython-type completion in Emacs, but > I hadn't managed that yet :( Refactoring, too. Both involve Pymacs but > I've had limited success with that. Yeah, that's what I'm talking about. > As for PyDev (I know you said "No" to this already), the main problem I > have with PyDev/Eclipse is the woefully underpowered editor (compared to > Emacs), and poor indentation logic. On the plus side, refactoring works > pretty well. So why not PyDev? I tried PyDev with Eclipse too and it's an aweful environment to me. Auto-completion was a total failure too... > I'm just wondering, you insist on Free/Libre software solutions, and say > the ones you tried don't work for you. Why not "use the source" and fix > them so they work your way? ;) To quote you: "how hard it could be be > writing a freesoftware which would automatically/intelligently auto > complete Python code?" Yes Yu-Xi Lim, you are right. Let me quote my self here: "I made my mind and I could volunteer to make this happen as thesis project for my incoming graduation in the next year." From bruno.desthuilliers at gmail.com Mon Jul 14 12:36:41 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 14 Jul 2008 09:36:41 -0700 (PDT) Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> Message-ID: On 13 juil, 12:05, Yosifov Pavel wrote: (snip) > def cloneiter( it ): > """return (clonable,clone)""" > return tee(it) This might as well be written as cloneiter = tee Or yet better, just remove the above code and s/cloneiter/tee/g in the remaining... From kay.schluehr at gmx.net Tue Jul 15 05:57:32 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 15 Jul 2008 02:57:32 -0700 (PDT) Subject: Python embedding question. References: Message-ID: <45f657a0-315f-421e-8d69-1c5b24e23887@k37g2000hsf.googlegroups.com> On 15 Jul., 11:51, Thomas Troeger wrote: > I've really looked at a lot of places but haven't found a suitable > solutions yet, so I'm asking here in hope that someone has experience > with that topic. Which solutions did you rule out? From digetl.try at gmail.com Sat Jul 26 06:03:45 2008 From: digetl.try at gmail.com (raja) Date: Sat, 26 Jul 2008 03:03:45 -0700 (PDT) Subject: Parmigiano Reggiano DOP Message-ID: <727be5c4-3c59-4c8a-96fb-3ddb5701b043@b30g2000prf.googlegroups.com> Eccelsa Qualit? di Montagna per Rivenditori, Ristoranti e Privati. http://food-drinks.page.tl/ From timr at probo.com Thu Jul 10 03:34:06 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 10 Jul 2008 07:34:06 GMT Subject: a simple 'for' question References: <4874017D.2000401@umbc.edu> <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> <487437E6.8010609@umbc.edu> <1215599630.2873.965.camel@localhost.localdomain> <48749F60.7030106@umbc.edu> Message-ID: Ethan Furman wrote: >Ben Keshet wrote: >> it didn't help. it reads the pathway "as is" (see errors for both >> tries). It looks like it had the write pathway the first time, but >> could not find it because it searched in the path/way instead of in the >> path\way. thanks for trying. > >The form of slash ('\' vs '/') is irrelevant to Python. At least on >Windows. > >> folders= ['1','2','3'] >> for x in folders: >> print x # print the current folder >> filename='Folder/%s/myfile.txt' %[x] > ^- brackets not needed More than that, the brackets are CAUSING this problem. The "%" formatting operator expects to find either a single item, or a tuple containing multiple items. It does NOT look for a generic iterator. In this case, the %s will use the whole list as its parameter. Python converts the list to string, and the string representation of that one-item list is ['1']. >> f=open(filename,'r') >> >> gives: IOError: [Errno 2] No such file or directory: >> "Folder/['1']/myfile.txt" Just like that. >As far as the Python question of string substitution, "%s" % var is an >appropriate way. Right. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From paddy3118 at googlemail.com Tue Jul 29 17:33:25 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 29 Jul 2008 14:33:25 -0700 (PDT) Subject: Parsing VHDL with python, where to start. References: Message-ID: <09ec2cd2-37e6-4abe-bed9-fc593c4751ce@8g2000hse.googlegroups.com> On Jul 21, 12:09?pm, Svenn Are Bjerkem wrote: > Hi, > I am in the need to write an application for PyQt to visualise the > structure of a VHDL project I am working on. Looking for a sensible > way to parse VHDL files and putting them into a data structure that > PyQt can represent as a tree (or whatever the MVC is supporting) > through search engines does not give me many hints. From what I know, > VHDL is not a very easy language to parse. There seems to be a parser > for perl available, but I do not know if it is wise to use a perl > module as a template for writing something similar in python. > > My initial idea is to start simple and extend features in my > application, but I fear that I may start off with wrong ideas how to > parse and then code myself into a dead-end requiring myself to rewrite > the whole application in order to get any further. I would start > finding definitions of entities and the instantiations of these and > build a tree from a set of external vhdl files stored in a file > hierarchy. If somebody have a starting point where to get going with a > task like this, I would be happy to know. > > -- > kind regards, > Svenn Been their, partially done that. I started parsing an old version of VHDL (VHDL 87 I think); using regular expressions and carrying state around myself. It was tough, and I was doing it , but then Work mentioned that they were going to need to parse later versions of VHDL and that was a whole new ball- game, specifically configuration type information could be mixed in with the architecture. Luckily work had also decided to by in a commercial parser. I learned that add-hoc parsers have limits to their maintainability and become complex. You might not have such problems if your VHDL is all in one library. - Paddy. From pranny at gmail.com Fri Jul 11 03:13:31 2008 From: pranny at gmail.com (pranav) Date: Fri, 11 Jul 2008 00:13:31 -0700 (PDT) Subject: Bypassing WebFilter security References: <563968a1-3cc3-4009-beca-d5d367d4ccff@k13g2000hse.googlegroups.com> <4876F153.2020406@behnel.de> Message-ID: <25ff817d-2d0f-4806-b635-96e220d920f5@m44g2000hsc.googlegroups.com> On Jul 11, 11:42?am, "Daniel Fetchinson" wrote: > >> I am working in an organization, which is using a very strict > >> webcontent filter management suite. Due to this i am unable to > >> download any exe file, or surf web (even the necessary downloads from > >> sourceforgenet are blocked). I was wondering, if python could be of > >> any help. Say i have a python script, and i pass the URL of > >> downloadable file, and it just downloads the file for me. > > > Nice try. Can I talk to your employer for a minute? :) > > > Honestly, the language doesn't make any difference here, and there isn't > > much > > you can do unless you control both sides, i.e. the server and the client. > > But > > I would suggest you actually talk to your employer yourself to see if > > there's > > an official way to get what you want. > > Yes, the language itself doesn't matter as long as you go through the > web. But if I were you I would use an ssh client to ssh to a remote > machine on which I have an account, download the file there to that > machine and scp it to the local machine. Assuming of course port 21 is > not blocked. > > In fact, this is something I do regularly for similar reasons :) > > Good luck, > Daniel > -- > Psss, psss, put it down! -http://www.cafepress.com/putitdown Daniel, cool even i thought of the same thing, but you see, the assumption has no use in my case! It is also blocked, Anyways, i will talk to the system admins here. Thanks all From bignose+hates-spam at benfinney.id.au Fri Jul 11 19:43:03 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 12 Jul 2008 09:43:03 +1000 Subject: How to serialize and deserialize the objects into memory? References: <0a7ead85-2a38-41a8-98b8-59dede61f985@c58g2000hsc.googlegroups.com> Message-ID: <87wsjsoum0.fsf@benfinney.id.au> Gerhard H?ring writes: > You want to serialize the objects, but only keep them in memory? > That hardly makes any sense. Serialization is need if you want to > store your objects in a file or if you want to communicate (via > network) with other processes. If one needs to do further processing on the serialised stream before storing or transporting it, one needs to handle it in memory. Fortunately (as pointed out elsewhere in this thread) the pickle module provides for this. -- \ ?I love and treasure individuals as I meet them, I loathe and | `\ despise the groups they identify with and belong to.? ?George | _o__) Carlin, 2007 | Ben Finney From elessar at nienna.org Thu Jul 31 15:07:59 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Thu, 31 Jul 2008 13:07:59 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <4891FD6F.8090604@nienna.org> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <00a121b4$0$20313$c3e8da3@news.astraweb.com> <4891FD6F.8090604@nienna.org> Message-ID: <48920D8F.3030602@nienna.org> Matthew Fitzgibbons wrote: > Steven D'Aprano wrote: >> On Wed, 30 Jul 2008 09:23:05 -0600, Matthew Fitzgibbons wrote: >> >>> If you're expecting a list (and only a list) >>> then your point makes sense. 'if x' can get you into trouble if you >>> _don't_ want its polymorphism. >> >> "if x" is hardly unique in that way. If you're expecting a list, and >> only a list, "len(x) != 0" will get you in trouble if somebody passes >> a string or a dictionary. I don't see any reason why we should single >> out "if x" as dangerous in the face of invalid types. With the >> exception of the "is" and "is not" operators, nothing in Python is >> guaranteed to work with any imaginable object. Even print can fail, if >> the object's __str__ method raises an exception. >> >> >>> Although, if my function is expecting a list, my preference is to do: >>> >>> if not isinstance(x, list): >>> raise SomeMeaningfulException() >>> # do stuff with the list >>> >>> I put my type checking at the top of the function, so readers can >>> reference it easily. >> >> And thus you break duck-typing and upset anybody who wants to pass a >> sequence that doesn't inherit directly from list. >> >> There are other (and arguably better, although more labour-intensive) >> techniques for defensive programming that don't break duck-typing. You >> can google for Look Before You Leap and Easier To Ask Forgiveness Than >> Permission for more information. Alex Martelli has a fine recipe in >> the Python Cookbook -- search for the recipe "Checking if an object >> has the necessary attributes". >> >> But in a nutshell, here's a toy example: >> >> def spam(seq): >> try: >> seq.append >> seq.extend >> seq[0] = seq[0] >> except Exception: >> raise TypeError("argument isn't sufficiently sequence-like") >> # No exceptions expected from here on >> seq.append(seq[0]) >> seq.extend([1,2,3]) >> seq[0] = "spam" >> >> >> >> > > Yes, I know it breaks duck typing, which is why I do it only very > rarely, and never with e.g. sequence types. If I use ifinstance for type > checking, it's because I need some _very_ specific class, almost always > one that I wrote. My more usual use case for ifinstance is to figure out > how to handle a particular object using introspection. > > That said, your example is still helpful. It's a good approach, and I > should use it more often. Although I'd also lean toward hasattr and > iscallable and ordinary ifs instead of the try ... except where > possible. Depending on what you put in the try ... except, you risk > masking legit exceptions. > > Ahhh, Programing. Where no rule of thumb seems to last five minutes. > > -Matt > -- > http://mail.python.org/mailman/listinfo/python-list > Where by ifinstance I mean isinstance and by iscallable I mean callable. *hides* -Matt From fuzzyman at gmail.com Thu Jul 3 13:42:53 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 3 Jul 2008 10:42:53 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> <9cdbb215-d427-4694-a455-f2571ad42390@x19g2000prg.googlegroups.com> Message-ID: <54e0e7c5-113e-4296-a62f-e649d6ffa2d6@z66g2000hsc.googlegroups.com> On Jun 30, 11:25?pm, Ali Servet D?nmez wrote: > On Jul 1, 12:15?am, Fuzzyman wrote: > > > > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > I don't want to be so mean here, but how hard it could be be writing a > > > freesoftware which would automatically/intelligently auto complete > > > Python code? (I mean something that really does the job, like > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > name it, but just don't give me PyDev please...) > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > missing here? > > > > Could someone please point me out something that I'm really missing > > > which is already present in the wild, otherwise I'd like discuss with > > > whoever is willing to help me to get this thing done. I made my mind > > > and I could volunteer to make this happen as thesis project for my > > > incoming graduation in the next year. > > > > Regards you all, > > > Ali Servet D?nmez > > > Vim, Emacs, Wing, Komodo, ... more? > > > Yeah, I guess you're missing something. :-) > > > MichaelFoordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > I probabily am... Could you please kindly tell me what's the way to > get it work for Emacs? Not personally I'm afraid. Although I did use Emacs today for the first time (pairing with a colleague who inflicted it upon me). We did have code completion working fine, but I have no idea how to set it up (maybe the intarwebz can help?). Michael Foord -- http://www.ironpythoninaction.com/ http://www.trypython.org/ From rocksportrocker at googlemail.com Thu Jul 17 13:39:23 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 17 Jul 2008 10:39:23 -0700 (PDT) Subject: How to process a very large (4Gb) tarfile from python? References: <0e96241d-60a3-44fd-967a-394904ad5b34@e39g2000hsf.googlegroups.com> <4nqu74p3mmmdmf9pn7125voe6itko8d31k@4ax.com> Message-ID: On 17 Jul., 17:55, Terry Carroll wrote: > On Thu, 17 Jul 2008 06:14:45 -0700 (PDT), Uwe Schmitt > > wrote: > >I had a look at tarfile.py in my current Python 2.5 installations > >lib path. The iterator caches TarInfo objects in a list > >tf.members . If you only want to iterate and you ?are not interested > >in more functionallity, you could use "tf.members=[]" inside > >your loop. This is a dirty hack ! > > Thanks, Uwe. ?That works fine for me. ?It now reads through all 2.5 > million members, in about 30 minutes, never going above a 4M working > set. Maybe we should post this issue to python-dev mailing list. Parsing large tar-files is not uncommon. Greetings, Uwe From bignose+hates-spam at benfinney.id.au Wed Jul 16 00:55:54 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jul 2008 14:55:54 +1000 Subject: Modify a string's value References: <8c7245ed-2341-4283-988c-8a8adf3e58fd@56g2000hsm.googlegroups.com> Message-ID: <87k5fm4ecl.fsf@benfinney.id.au> s0suk3 at gmail.com writes: > I just came across this unusual situation where I'd like to modify a > string passed to a function Again: Why? The normal way to do this is to create a new string and return that. > which seems impossible since Python passes arguments by value. No, Python passes arguments by reference . -- \ ?For of those to whom much is given, much is required.? ?John | `\ F. Kennedy | _o__) | Ben Finney From cwitts at gmail.com Wed Jul 16 07:38:52 2008 From: cwitts at gmail.com (Chris) Date: Wed, 16 Jul 2008 04:38:52 -0700 (PDT) Subject: How can i use a variable without define it ? References: <87k5fm2p1x.fsf@benfinney.id.au> <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> Message-ID: <616b3539-c3e1-41ae-82d4-c9698ff0056e@k30g2000hse.googlegroups.com> On Jul 16, 11:06 am, zhw wrote: > On 7?16?, ??4?47?, Ben Finney > wrote: > > > > > zhw writes: > > > How can i use a variable without define it ? > > > What do you mean by "use"? That's so vague I can think of many > > possible interpretations. > > > What do you mean by "variable"? That term carries a lot of baggage > > that doesn't apply in Python. > > > Can you give a small, complete example that demonstrates the issue > > you're trying to solve? > > > -- > > \ "The face of a child can say it all, especially the mouth part | > > `\ of the face." --Jack Handey | > > _o__) | > > Ben Finney > > Thank you! Sorry for my poor english! > > Here is a example that I want to complete:>>> import sys, new > >>> context={"name":"david", "sex":"male"} > >>> sys.modules["foo"] = new.module("foo") > >>> import foo > >>> for attr in context: > > setattr(foo, attr, context[attr]) > > >>> def bar(): > > # here is a error > # import * only allowed at module level > from foo import * > print name, sex > > >>> bar() > > def bar(): from foo import name, sex print name, sex You will need to know beforehand what attributes you want to import into the function. From andreas.mock at web.de Thu Jul 17 13:27:38 2008 From: andreas.mock at web.de (McA) Date: Thu, 17 Jul 2008 10:27:38 -0700 (PDT) Subject: unpacking with default values References: <335e7a21-e35e-41ee-9f92-fd4c2f6bf166@f36g2000hsa.googlegroups.com> Message-ID: <6a105194-a248-4ee6-be01-5aef9e5bb648@e53g2000hsa.googlegroups.com> On 17 Jul., 18:33, Gary Herron wrote: > > In Python 2.x, you can't do that directly, but you should be able to > create a function that lengthens or shortens an input tuple of arguments > to the correct length so you can do: > > a,c,b = fix(1,2) > d,e,f = fix(1,2,3,4) > > However, the function won't know the length of the left hand side > sequence, so it will have to be passed in as an extra parameter or hard > coded. Hi Gary, thank you for the answer. Do you know the "protocol" used by python while unpacking? Is it a direct assingnment? Or iterating? Best regards Andreas Mock From jim.hefferon at gmail.com Tue Jul 1 19:55:11 2008 From: jim.hefferon at gmail.com (Jim) Date: Tue, 1 Jul 2008 16:55:11 -0700 (PDT) Subject: convert unicode characters to visibly similar ascii characters References: Message-ID: <040bbdba-169b-4340-aa76-a7d2d0954346@34g2000hsf.googlegroups.com> Peter Bulychev wrote: > I want to convert unicode character into ascii one. You have to make some arbitrary choices of what to translate. Based on some materials on effbot's site, and a recipe, I made ftp://alan.smcvt.edu/hefferon/unicode2ascii.py which has at least some of what you are looking for. $ grep HYPHEN unicode2ascii.py u'\N{SOFT HYPHEN}':u'-', u'\N{HYPHEN}':u'-', u'\N{NON-BREAKING HYPHEN}':u'-', u'\N{SOFT HYPHEN}': '-', No doubt I have some terrible gaffes and some things missing. Corrections appreciated. Jim From ezindy at gmail.com Sat Jul 19 06:29:36 2008 From: ezindy at gmail.com (Egor Zindy) Date: Sat, 19 Jul 2008 11:29:36 +0100 Subject: ftdi chip + ctypes + ftd2xx... need help with reading chipid! Message-ID: <4881C210.7000307@gmail.com> Dear List, This one is way beyond my comprehension skills, I just don't understand what I'm doing wrong. I am trying to read the chipid from an FTDI chip based USB key (DLP-D, http://www.ftdichip.com/Products/EvaluationKits/DLP-D.htm ), using: - the ftd2xx module http://pypi.python.org/pypi/ftd2xx/0.1 - the ftd2xx.dll which comes with the driver install - the chipid dll (1.1.0) from here: http://www.ftdichip.com/Projects/FTDIChip-ID.htm - a ctypes interface I wrote by hand (only 7 functions to wrap, I thought it'd be easy!) The ftd2xx is used for testing, to open / close the device. My Problem is that neither of the following two wrapped functions (with the exact same arguments) return the right result (full chipid.py library attached): def FTID_GetDeviceLocationID(DeviceIndex): n = DWORD() status = ftchipid.FTID_GetDeviceLocationID(DeviceIndex, ctypes.byref(n)) if status != FTID_SUCCESS: raise DeviceError,FTID_GetErrorCodeString("EN",status) return n.value def FTID_GetDeviceChipID(DeviceIndex): n = DWORD() status = ftchipid.FTID_GetDeviceChipID(DeviceIndex, ctypes.byref(n)) if status != FTID_SUCCESS: raise DeviceError,FTID_GetErrorCodeString("EN",status) return n.value * On my machine (XP, 32 bits), if I plug two keys in, I can get the device chip id from the device with index=1. The one with index=0 always gives the message "Invalid device handle." * I get the wrong location id as well, 0 instead of 0x21... * the FTID_GetNumDevices function also uses a byref, c_ulong and works. * FTDI's win32 console example returns the right results (and uses c unsigned longs) - available from http://www.ftdichip.com/Projects/FTDIChip-ID.htm Any help appreciated! Regards, Egor -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: chipid.py URL: From babacity2 at gmail.com Thu Jul 24 16:57:51 2008 From: babacity2 at gmail.com (babacity2 at gmail.com) Date: Thu, 24 Jul 2008 13:57:51 -0700 (PDT) Subject: www Efukt - Amazing porn video collection Message-ID: www efukt . >>>>>>>>>>Best Collection of Efukt Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE www efukt VIDEOS<<<<<<<<<<< . www efukt From Russ.Paielli at gmail.com Tue Jul 29 00:33:15 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 28 Jul 2008 21:33:15 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> <466157f1-adcb-45f6-8c2d-b3c245a6ce8d@p31g2000prf.googlegroups.com> Message-ID: <47a24fed-6822-4767-aad3-07a72ddc3a1a@m73g2000hsh.googlegroups.com> On Jul 28, 8:44 pm, alex23 wrote: > On Jul 29, 4:46 am, "Russ P." wrote: > > > As I said, I could write a pre-processor myself to > > implement it in less than a day. > > So WHY DON'T YOU WRITE IT ALREADY? I'm working on something else right now if you don't mind, but I'll get to it in good time. Conceptually, the matter is simple. All I need to do is to grab the first formal argument of each def, then search for occurrences of any word in the body of the def that starts with a dot, and insert that first argument in front of it. I expect the "hard" part will be breaking up the body of the def into "words." I could just split each line on white space, except for situations like x+=.zzz So I need to account for the fact that operators do not need to be surrounded by spaces. That's the hardest part I can think of off the top of my head. Maybe I'll encounter an insurmountable problem and realize that the idea can't work in general. If so, then so be it. Certainly, no one on this thread has anticipated such a problem. Had someone pointed out an actual technical problem with the idea, I would have gladly thanked them. But I got a load of irrelevant crap instead, not to mention being addressed as "boy." > If you're meeting so much resistance to your idea, why not scratch > your own damn itch and just do it? > > Or doesn't that afford you as many chances to insult others while > feeling smugly superior? This coming from a guy who insulted my reading comprehension ability -- when he was the one who was wrong! From pavlovevidence at gmail.com Tue Jul 29 13:28:10 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 10:28:10 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: On Jul 29, 5:27 am, Steven D'Aprano wrote: > On Tue, 29 Jul 2008 01:37:45 -0700, Carl Banks wrote: > > I am looking for one that can't. > > If you are writing code that needs to do the right thing with arbitrary > types, then your so-called "simple explicit tests" simply can't work. I asked for a code example. You say this is true, but neither you nor anyone else here has provided useful code that demonstrates it. Carl Banks From bronger at physik.rwth-aachen.de Sat Jul 26 17:35:22 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 26 Jul 2008 23:35:22 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> Message-ID: <87k5f88h2d.fsf@physik.rwth-aachen.de> Hall?chen! Terry Reedy writes: > Torsten Bronger wrote: > >> Terry Reedy writes: >> >>> [...] >>> >>> Or the proposal would have to be that 'self' is mandatory for >>> all programmers in all languages. I think *that* would be >>> pernicious. People are now free to write the more compact 's.sum >>> = s.a + s.b + s.c' if they want instead of the 'self' version. >>> And again, not everyone writes in English. >> >> Of course, "self" would have to become a reserved word. You >> could say that this may break some code, > > Will break. No more than Python 3.0 breaks. >> but I don't see much freedom removed from the language. After >> all, being a German, I still can't write "F?r i in range(10)". >> ;-) > > But you can write 'for ubermenchen in range(10):' and in 3.0, with > diacritics added. Would you really feel no loss of freedom if > Guido make i0, i1, ... into keywords, which means they could not > be used elsewhere, and mandated them as for loop index variables? I would, but I consider "self" becoming a keyword not even in the same league as i0, i1 etc. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From mrkafk at gmail.com Fri Jul 4 06:59:22 2008 From: mrkafk at gmail.com (mk) Date: Fri, 04 Jul 2008 12:59:22 +0200 Subject: Naming conventions for regular variables Message-ID: http://www.python.org/dev/peps/pep-0008/ "Function Names Function names should be lowercase, with words separated by underscores as necessary to improve readability." However, this PEP does not recommend any particular style for naming regular (local) variables. Personally I like "mixedCase", however using both styles looks a bit weird: def some_function_name(someVariableName, anotherVar) Naming both functions and variables using "lowercase with underscore separator between words for readability" leads to confusing function names with variable names - and distinguishing between variables and function names just by looking at them would be nice. Recommendations? From tjreedy at udel.edu Fri Jul 18 16:49:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Jul 2008 16:49:21 -0400 Subject: checking if an object IS in a list In-Reply-To: References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: Peter Otten wrote: >> So, precisely, you mean that if hash(a) != hash(b), a and b are >> considered distinct, and else [ie. if hash(a) == hash(b)], a and b are >> the same if and only if a == b ? > > Correct for set, dict. For lists etc. the hash doesn't matter: Since CPython saves strings hashes as part of the string object (last I read, as part of internal string caching), it does something similar. Compare lengths, then hashes, then C array. From fredrik at pythonware.com Tue Jul 22 04:59:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 10:59:13 +0200 Subject: scanf in python In-Reply-To: <488568f6$0$6120$426a74cc@news.free.fr> References: <4884be5e$0$19722$426a74cc@news.free.fr> <488568f6$0$6120$426a74cc@news.free.fr> Message-ID: AMD wrote: > I had seen this pure python implementation, but it is not as fast or as > elegant as would be an implementation written in C directly within > python with no need for import. maybe you should wait with disparaging comments about how Python is not what you want it to be until you've learned the language? From robert.kern at gmail.com Tue Jul 8 18:04:40 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 08 Jul 2008 17:04:40 -0500 Subject: Logging to zero or more destinations In-Reply-To: <87r6a4du2k.fsf@merkury.smsnet.pl> References: <87r6a4du2k.fsf@merkury.smsnet.pl> Message-ID: Rob Wolfe wrote: > samwyse writes: >> The only way that I can see for all three statements to be consistent >> is that the root logger starts with an empty list of handlers, and >> doesn't instantiate a default handler until either >> logging.basicConfig() is called, > > That is correct. > >> or the first time that a message is >> logged. > > That is not correct. The list of handlers is empty until `basicConfig` > or explicit `addHandler` is called. > >> This would also seem to imply that there's no way to use an >> empty handler list (say, if you want to suppress all logging), because >> the root handler will instantiate a handler for you. Is this correct? > > No. Consider this: > >>>> import logging >>>> logging.root.warning('error message') > No handlers could be found for logger "root" >>>> logging.root.warning('error message') > > Note only one warning message. Ah, right. It is the module-level functions logging.warn(), etc. that invoke basicConfig() if no handler is present. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From google at mrabarnett.plus.com Thu Jul 10 19:33:02 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 10 Jul 2008 16:33:02 -0700 (PDT) Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: <8397d958-2c0e-40c7-8488-152559711163@c65g2000hsa.googlegroups.com> On Jul 10, 9:46?pm, ssecorp wrote: > >>> def mod(x,y): > > ? ? ? ? return x.append(y) > append adds y to list x and returns None, which is then returned by mod. > > > >>> mod([1,2],3) > >>> k=[1,2,3] > >>> k > [1, 2, 3] > >>> l = mod(k,4) 4 has been appended to list k and mod has returned None, so l is now None. > >>> l > >>> k > [1, 2, 3, 4] > >>> l > >>> k==l > False Because k is [1, 2, 3, 4] and l is None. > >>> mod(k,5) > >>> k > [1, 2, 3, 4, 5] > >>> mod(l,4) > > Traceback (most recent call last): > ? File "", line 1, in > ? ? mod(l,4) > ? File "", line 2, in mod > ? ? return x.append(y) > AttributeError: 'NoneType' object has no attribute 'append' > l is None, not a list, so it complains! > >>> l > >>> l=k > >>> l > [1, 2, 3, 4, 5] > >>> i=mod(k,1) > >>> i > > same stuff but i dont find this intuitive. It's usual for methods which modify to return None. From tjreedy at udel.edu Tue Jul 8 17:17:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 08 Jul 2008 17:17:52 -0400 Subject: numeric emulation and __pos__ In-Reply-To: <4873A50C.5090003@stoneleaf.us> References: <92e3ea9f-5745-4072-9d09-7c14fd335828@f36g2000hsa.googlegroups.com> <4873A50C.5090003@stoneleaf.us> Message-ID: Ethan Furman wrote: > Anybody have an example of when the unary + actually does something? > Besides the below Decimal example. I'm curious under what circumstances > it would be useful for more than just completeness (although > completeness for it's own sake is important, IMO). All true operators and some built-in functions translate to special method calls. -x == x.__neg__() == type(x).__neg__(x) == x.__class__.__neg__(x) What should happen to '+x'? Raise SyntaxError? Ignore the '+'? Or translate it to __pos__ in analogy with '-' and __neg__? Guido made the third choice: partly for consistency perhaps, but also for the benefit of user-written classes. Decimal started as user-contributed decimal.py. Does anything else use this hook? I don't know, but I do know that there are periodic demands for *more* operators for user use. So I expect it has been. tjr From robert.rawlins at thinkbluemedia.co.uk Thu Jul 24 12:06:06 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 24 Jul 2008 17:06:06 +0100 Subject: Gracefull application exit. Message-ID: <00ba01c8eda7$2e61ecb0$8b25c610$@rawlins@thinkbluemedia.co.uk> Chaps, I'm looking to implement an exit/termination process for an application which can be triggered by A) a keyboard interrupt or B) termination of the application as a Daemon using a signal. I have a whole bunch of tasks I want to perform as a cleanup before the application is terminated, cleaning files, database calls, closing open connections and a few other things. I know we have: # I'm the main application started method. if __name__ == "__main__": For starting an application, but do we have an equivalent methods for when an application is terminated which we can use to close down any current internal processes before the application exits? I'd really love to have your thoughts and experience on gracefully killing an application. Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeffrey at fro.man Fri Jul 11 09:29:16 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Fri, 11 Jul 2008 06:29:16 -0700 Subject: MySQLdb will only import for root References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> <85d26ae4-757f-494c-bf7e-412323e26b8a@x41g2000hsb.googlegroups.com> <6dp092F3mhbaU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> Is it possible the module was installed with priviledges set too >> strict? ?Perhaps the interpreter cannot see the module when it is run >> from a normal user account. > > Possible - certainly. Yet unrealistic, because usually root access is > required to system-wide install a package - thus the normal install > processes ensure proper rights. According to the OP, it is root that *does* have access to MySQLdb and a normal user that does not. It is a very realistic possibility to install something as root to which normal users do not have access. Installation scripts that assume a particular umask during install, for example, are especial culprits. I have noticed this problem myself with python modules that include compiled C extensions, as MySQLdb does. However, in the case where the extension module itself has incorrect permissions, the error would point to a missing _mysql, rather than a missing MySQLdb. Jeffrey From support.desk.ipg at gmail.com Mon Jul 28 13:32:33 2008 From: support.desk.ipg at gmail.com (Support Desk) Date: Mon, 28 Jul 2008 12:32:33 -0500 Subject: python lists and newline character Message-ID: <053101c8f0d7$ebd7c340$a601a8c0@office.ipglobal.net> Hello all, I am using os.popen to get a list returned of vpopmail users, something like this x = os.popen('/home/vpopmail/bin/vuserinfo -n -D mydomain.com).readlines() x returns a list, of usernames, and I am trying to append the usernames with the domain like so for line in x: print line + '@' + domain but instead of getting user at domain.com im getting a newline character like: user @domain.com User @comain.com User2 @domain.com Is there some way I can get this list without the newline characters being added. or somehow remove the newline characters. Any help would be appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexnbryan at gmail.com Thu Jul 17 04:23:57 2008 From: alexnbryan at gmail.com (Alexnb) Date: Thu, 17 Jul 2008 01:23:57 -0700 (PDT) Subject: Getting a unknown word out of a list with no spaces In-Reply-To: <93164ef9-7079-44db-9ac4-b0a18b0ddf3e@b1g2000hsg.googlegroups.com> References: <18502758.post@talk.nabble.com> <487EF593.5060505@promsoft.ru> <18503144.post@talk.nabble.com> <487EF7D9.8010400@promsoft.ru> <93164ef9-7079-44db-9ac4-b0a18b0ddf3e@b1g2000hsg.googlegroups.com> Message-ID: <18503830.post@talk.nabble.com> bearophileHUGS wrote: > > On Jul 17, 9:50 am, Alexnb: >> how can I test to see if the first char of a string is "<"? > > I suggest you to try the interactive shell: > >>>> "hello"[0] > 'h' >>>> "hello"[0] == "<" > False >>>> "hello"[0] == "h" > True >>>> "hello".startswith("h") > True > > Bye, > bearophile > -- > http://mail.python.org/mailman/listinfo/python-list > > really? That's just like C. I thought that it would fail because of the way lists work. Thanks! -- View this message in context: http://www.nabble.com/Getting-a-unknown-word-out-of-a-list-with-no-spaces-tp18502758p18503830.html Sent from the Python - python-list mailing list archive at Nabble.com. From tjreedy at udel.edu Wed Jul 9 15:38:46 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 09 Jul 2008 15:38:46 -0400 Subject: Impossible to change methods with special names of instances of new-style classes? In-Reply-To: <429cbef9-0027-4717-a39f-d7e7599e07ae@x35g2000hsb.googlegroups.com> References: <429cbef9-0027-4717-a39f-d7e7599e07ae@x35g2000hsb.googlegroups.com> Message-ID: samwyse wrote: > On Jul 8, 4:56 pm, Joseph Barillari wrote: > >> My question is: did something about the way the special method names are >> implemented change for new-style classes? I believe the difference is that for new-style classes, when special methods are called 'behind the scenes' to implement built-in syntax and methods, they are looked up directly on the class instead of first on the instance. Note that functions attached to instances are *not* methods and do not get combined with the instance as a bound method. From bernhard.voigt at gmail.com Wed Jul 23 09:30:19 2008 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: Wed, 23 Jul 2008 06:30:19 -0700 (PDT) Subject: maximum value in a column of file References: <4886DCF3.10107@isac.cnr.it> <4886F4CD.8010704@isac.cnr.it> <488705D6.4090300@isac.cnr.it> Message-ID: <29926261-1f5b-48c3-8ed7-985dc7e3a072@j22g2000hsf.googlegroups.com> > > thank you for your answer > > actually i've to do some statistics (maximum,minimum,mean,standard > > deviation,....) of a file of data in which each column is a particular > > type of data. (the file is a tab separated value). > > I was trying to do this by using python (usually i work with fortran or > > bash, but i'm learning python), that the reason why i tried to use numpy. numpy.loadtxt is probably what your looking for, provided your file contains only numbers and comment lines. check the example here: http://www.scipy.org/Numpy_Example_List_With_Doc#head-88ade192dacf0c15e4f1377096134ee559df07a0 X = numpy.loadtxt('data.txt') X[:,0].mean() # mean of first column X[:,0].max() # mux of first column X[:,0].var() # variance of first column ... enjoy! bernhard > > As I implied, you can do all this in standard Python "by hand", but > numpy/scipy can definitely make things easier. There's a dependency > cost here (your program needs one or more extra libraries to work), but > if that's no problem in your environment, I'd recommend that approach. > > The scipy add-on contains a bunch of things for file i/o; see > > http://www.scipy.org/doc/api_docs/SciPy.io.html > > for an overview. Since you're reading text files, the "array_import" > module seems to be what you need: > > http://www.scipy.org/doc/api_docs/SciPy.io.array_import.html > > There are active user communities for both numpy and scipy that can help > you sort out any remaining issues; for details, see: > > http://www.scipy.org/Mailing_Lists > > Hope this helps! > > From morse at edoug.org Fri Jul 18 10:07:45 2008 From: morse at edoug.org (Doug Morse) Date: Fri, 18 Jul 2008 14:07:45 +0000 (UTC) Subject: Core Dump - Segmentation Fault -Newbie References: <8ba4373d-3d97-4e9a-a15e-723f6818c757@k36g2000pri.googlegroups.com> <4880A0FA.6030603@behnel.de> Message-ID: On Fri, 18 Jul 2008 15:56:10 +0200, Stefan Behnel wrote: > johnericaturnbull at yahoo.com wrote: > > Hi - I am very new to python. I get this random core dump and am > > looking for a good way to catch the error. I know the function my core > > dump occurs. Is there any error catching/handling that I could use in > > python? > > Since you are using Windows, this is somewhat non-trivial due to the lack of > tools shipped by Microsoft. Are you really getting crashes of the interpreter > and not just an exception with a stacktrace? > > Stefan Hi John, Well, I must be missing something re: why Stefan states that you are using Windows. I don't see that stated in your original post, and, AFAIK, the phrase "core dump" is seen much more in the Unix world than in the Windows world. So, just in case you are on some *nix variant, you can of course log all the system calls up until your core dump by running: $ strace -o logfile.txt python [...] where [...] should be replaced with any parameters to the python interpreter, such as the Python script you're running, e.g., $ strace -o logfile.txt python Hello.py The trace of system calls will be in the file logfile.txt. For more info on strace, see the strace(1) man page (i.e., run "man strace"). Doug From viv1tyagi at gmail.com Tue Jul 1 06:13:42 2008 From: viv1tyagi at gmail.com (viv1tyagi at gmail.com) Date: Tue, 1 Jul 2008 03:13:42 -0700 (PDT) Subject: Having problems using Tkinter Message-ID: <144f93d3-b493-4280-a3a4-23a2b13b59c6@i36g2000prf.googlegroups.com> Hi everyone ! ! ! I'm just a month old in the world of Python and trying to develop an application using Tkinter in which a new window pops out on a particular button press.The code for this new window is in "AddKlas.py" file. The problem is all the content of the new window is overwritten on the previous window. Below is the code of the two files PLEASE help me out ! ! ! ! #1st file #Klass.py from Tkinter import * import AddKlass class Klass(Frame): def __init__(self): self.labels() self.buttons() self.menubuttons() self.scrollandcanvas() def labels(self): label1=Label(relief='groove',text=" Class Id",width=20,anchor=W) label1.grid(row=0,column=0) label2=Label(relief='groove',text=" Class Name",width=20,anchor=W) label2.grid(row=0,column=1) label3=Label(relief='groove',text=" Class Room No.",width=20,anchor=W) label3.grid(row=0,column=2) label4=Label(relief='groove',text=" Category Id",width=80,anchor=W) label4.grid(row=0,column=3) def buttons(self): button1=Button(text="Add",width=10,command=self.CallAdd) button1.grid(row=2,column=5) button2=Button(text="View",width=10,state=DISABLED) button2.grid(row=3,column=5) button3=Button(text="Next",width=10,state=DISABLED) button3.grid(row=4,column=5) def menubuttons(self): menubutton=Menubutton(text="Options",width=10,relief="raised") menubutton.grid(row=5,column=5) menubutton.menu=Menu(menubutton) menubutton["menu"]=menubutton.menu menubutton.menu.add_command(label="Modify") menubutton.menu.add_command(label="Delete") def scrollandcanvas(self): yscroll=Scrollbar() yscroll.grid(row=1,column=4,rowspan=7,sticky=N+S) canva=Canvas(bg="#fff",yscrollcommand=yscroll.set) canva.grid(row=1,column=0,rowspan=7,columnspan=4,sticky=N+E+S +W) def CallAdd(self): AddKlass.root=Tk() AddKlass.AddKlas() AddKlass.root.focus_force() AddKlass.root.geometry("275x250") AddKlass.root.title("Add Class Information") AddKlass.root.resizable(width=False,height=False) AddKlass.root.mainloop() root=Tk() app = Klass() root.geometry("960x300") root.title("Class Information") root.resizable(width=False,height=False) root.mainloop() #2nd file #AddKlass.py from Tkinter import * class AddKlas(Frame): #root=None def __init__(self): self.labels() self.buttons() self.entry() def labels(self): label1=Label(relief='flat',text=" Class Id :",height=3,width=20) label1.grid() label2=Label(relief='flat',text=" Class Name :",height=3,width=20) label2.grid() label3=Label(relief='flat',text=" Class Room No. :",height=3,width=20) label3.grid() label4=Label(relief='flat',text=" Category Id :",height=3,width=20) label4.grid() def buttons(self): button1=Button(text="Add",width=10,state=DISABLED) button1.grid(row=5,column=0) button2=Button(text="Cancel",width=10,command=self.quit) button2.grid(row=5,column=1) def entry(self): entry1=Entry() #by default width =20 entry1.grid(row=0,column=1) entry2=Entry() entry2.grid(row=1,column=1) entry3=Entry() entry3.grid(row=2,column=1) entry4=Entry() entry4.grid(row=3,column=1) #root=Tk() #app = AddKlas() #root.geometry("275x250") #root.title("Add Class Information") #root.resizable(width=False,height=False) #root.mainloop() From mail at microcorp.co.za Tue Jul 8 04:10:35 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 8 Jul 2008 10:10:35 +0200 Subject: Cross Compiler for Python? Message-ID: <001101c8e0d2$36a50ec0$0d00a8c0@hendrik> norseman wrote: >================================================== >In case all else fails: > >This is not a cookbook answer, but: > 1) gnu's gcc will compile to 16,32 or 64 bit intel architectures > OK, the 32 bit version compiles to 16 or 32 & the 64 should. > The 64 will run 32 bit programs, including the 32 bit gcc. > chgroot can be (messy but) useful to maintain separation. > 2) info gcc and look for compiler directives > then info nasm and look for directives > same for the linker > I'm not specific because I use Slackware and different > distros can use different modules. You may have an assembler > with a different name. Switches can be different and so > forth. >On Slackware the installpkg (for tarballs already compiled) records the >locations of where things go in /var/log/packages. I have to assume >other distros have something similar since these are used to remove >things later. Can we say 'updates'? If not you will need to wade >through the .configure and Makefiles to root out what happens to get >'vanilla' locations. > >Like I said, it's not cookbook, but it will get you there and you will >gain quite an insight into Linux. While the path may not be well marked >in Linux, there usually is one. > >Sorry I don't have a more straight forward approach. > >- Steve > Thanks Steve, for the tips. In a sense, I have dreaded an answer like this, as it is cold comfort to realise that I will be hassled off my objective to take a side trip through Linux's complexities, just so that I can play with the hardware to evaluate if we can use it for what we want to do. I had fondly hoped that somebody would have blazed the way before me. But it seems not. Tough. I will report here what I do and find - It may help some other poor sod some day... - Hendrik From Lie.1296 at gmail.com Tue Jul 8 06:53:17 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 8 Jul 2008 03:53:17 -0700 (PDT) Subject: how are strings immutable in python? References: Message-ID: <1df93c62-3443-488c-9069-dcdc83842c8e@34g2000hsh.googlegroups.com> On Jul 7, 1:45?am, ssecorp wrote: > >>> h = "aja baja" # 'aja baja' is created and assigned to the name h > >>> h += 'e' # Is the equivalent of: # h = h + 'e' # # In there, a h and 'e' is concatenated and assigned to # a new string object which is bound to h. The # original string object which contains # 'aja baja' is "garbage collected"[1]. > >>> h # printing h which contains the new string object containing 'aja bajae' > 'aja bajae' [1] actually python uses reference counting first to choose which object to delete From gherron at islandtraining.com Tue Jul 1 19:47:53 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 01 Jul 2008 16:47:53 -0700 Subject: Attribute reference design In-Reply-To: References: <6cvlk4F3s90U1@mid.uni-berlin.de> Message-ID: <486AC229.60300@islandtraining.com> chamalulu wrote: > On Jul 2, 1:17 am, Gary Herron wrote: > >> No need. Also, you can define a class attribute (C++ might call it a >> static attribute) and access it transparently through an instance. >> >> class C: >> aClassAttribute = 123 >> def __init__(self, ...): >> ... >> >> c = C() >> ... do something with c.aClassAttribute ... >> >> > > Actually, this is why I started too look into the attribute reference > mechanics to begin with. Coming from mostly C# development I think > it's weird to be able to refer to class attributes (static members) > through a class instance (object). But I think I'm getting the > picture. Function objects lay flat in memory (some heap...). Not quite. Not *flat memory* or a heap. Modules are first class objects, and functions (and classes and anything else) defined at the top level of the module are *attributes* of the module. Gary Herron > When > defined inside classes they are wrapped in method objects. When > refered through classes or class instances they are unbound method > objects or bound method objects respectively. Am I on the right track? > I still don't get why these methods show up when I dir() a class > instance. > > /Henrik > -- > http://mail.python.org/mailman/listinfo/python-list > From stochashtic at yahoo.ca Mon Jul 28 03:50:54 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 28 Jul 2008 09:50:54 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> <4889e5bc$1@news2-rz-ap.ethz.ch> Message-ID: <488d7a5e$1@news2-rz-ap.ethz.ch> On Fri, 25 Jul 2008 09:22:06 -0600, Matthew Fitzgibbons wrote: > As for different data structures, it largely depends on how you need to > access the data. If you don't need to index the data, just loop through > it, you might try a linked list. The performance hit in (2) is coming > from the list del; using a linked list would make the removal constant > rather than O(n), and may even execute faster than (3) as well. > > -Matt Yes, this was my first inclination. So my question, as alluded to in my original post, is whether there are C compiled modules for linked lists, doubly linked lists, ordered lists ... (the standard data structures) somewhere, to get the extra performance out of them. With python we have all built up creative ways of using the native structures for efficiency reasons. This project was the first time (due to its extreme use of resources) that I've had to worry about these minute considerations of native vs new structure but also take into account native vs python level construct vs compiled module. [P.S. The linked list does compare well with (3) as expected.] From robert.kern at gmail.com Mon Jul 7 21:04:42 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 07 Jul 2008 20:04:42 -0500 Subject: Python Agile Software Development Tools Screencasts In-Reply-To: <87hcb1w6gl.fsf@benfinney.id.au> References: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> <87lk0dwbys.fsf@benfinney.id.au> <87hcb1w6gl.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Robert Kern writes: > >> Ben Finney wrote: >>> percious writes: >>> >>>> I started a new series about python on showmedo. Please feel free >>>> to take a look. >>> I'd love to, but showmedo refuses to show presentations to me >>> without installing non-free software. >> mplayer works just fine on the .flv's. > > Note that "works with mplayer" is not the same thing as "doesn't > require non-free software"; many "works with mplayer" stories have the > unspoken addendum of "... with these non-free codec libraries > installed". But, not having the video files, I can't say whether > that's the case in this instance. I believe .flv is entirely handled by ffmpeg. > Okay. Where would the public link to those files be? > > If I need to "log in" just to download it, that's a needless barrier > that's going to turn me away too. Yes, you do need to log in. If you don't want to do it, that's fine. I certainly don't care. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sneuberger at mitre.org Fri Jul 18 16:35:07 2008 From: sneuberger at mitre.org (Neuberger, Sheldon N.) Date: Fri, 18 Jul 2008 16:35:07 -0400 Subject: Writing a program under GNU/Linux for MS Windows. In-Reply-To: References: Message-ID: <7B3D44209E8C944288889D4132FEC4125B98C5@IMCSRV6.MITRE.ORG> If you're just writing Python code then it will run unmodified on his Windows machine. Are you planning on using other languages too? -----Original Message----- From: python-list-bounces+sneuberger=mitre.org at python.org [mailto:python-list-bounces+sneuberger=mitre.org at python.org] On Behalf Of Levi Campbell Sent: Friday, July 18, 2008 4:27 PM To: python-list at python.org Subject: Writing a program under GNU/Linux for MS Windows. Hi, I'm trying to write a program for a friend of mine who uses windows but I use GNU/Linux. I know you can use mingw and link to the python dll, but is there a way to create a win32 service under Linux? -- http://mail.python.org/mailman/listinfo/python-list From casevh at gmail.com Thu Jul 3 21:10:51 2008 From: casevh at gmail.com (casevh) Date: Thu, 3 Jul 2008 18:10:51 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> Message-ID: On Jul 3, 6:54?am, Mensanator wrote: > > Well, it will be great at some point in the future > when Python 2.6/3.0 have actually been released and > third party extensions such as gmpy have caught up. > > Until then, such solutions are worthless, i.e., of > no value. gmpy is supported on Python 2.6. A new version and Windows binaries were released shortly after 2.6b1 was released. casevh From michele.simionato at gmail.com Sat Jul 26 13:20:43 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 26 Jul 2008 10:20:43 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> Message-ID: On Jul 26, 5:28?pm, a... at pythoncraft.com (Aahz) wrote: > IMO, you made a big mistake in combining your point with two other meaty > issues (whether method definitions should include self and whether != > should use __eq__() as a fallback). > ?If solid discussion > is your goal, I suggest that you wait a couple of weeks and start over > with a brand-new thread. I fully subscribe this. The point about __eq__ is legitimate and could be discussed with quite tones. I was bitten by this surprising behavior just a few days ago, I had defined __eq__ and I expected __neq__ to be defined in the obvious way. I saw that it was not the case and I figured out immediately that I had to override __neq__ explicitely (I have the "explicit is better than implicit" mantra ingrained in my mind too), I did so and everything worked out as a charm. Total time loss: five minutes. So, it is not a big point. Still I think that it would make sense to automatically define __neq__ as the negation of __eq__. I suppose the developers did not want to make a special case in the implementation and this is also a legitimate concern. Michele Simionato From semanticist at gmail.com Sun Jul 13 17:33:37 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 17:33:37 -0400 Subject: Magic? In-Reply-To: References: Message-ID: On Sun, Jul 13, 2008 at 12:55 PM, mk wrote: > So my updated question is where does this lstr() instance keep the original > value ('abcdef')? It obviously has smth to do with inheriting after str > class, but I don't get the details of the mechanism. Through the str.__new__ method: http://docs.python.org/ref/customization.html Calling a constructor: foo = Foo(1, 2, 3) Is roughly equivalent to: foo = Foo.__new__(Foo, 1, 2, 3) Foo.__init__(foo, 1, 2, 3) As a side note, you may already know this, but it's not necessary to create a property setter that raises an error to make a property read-only; you can simply not define a setter method. -Miles From sunp1028 at gmail.com Tue Jul 15 23:10:36 2008 From: sunp1028 at gmail.com (patrol) Date: Tue, 15 Jul 2008 20:10:36 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> Message-ID: > At any rate, try using: > > result, = new_process.Terminate () Windows is sometime case insensitive,but the python is case sensitive. I also encountered this kind of problems. Thanks for Tim's help. Patrol From thomas.troeger.ext at siemens.com Tue Jul 15 05:51:47 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Tue, 15 Jul 2008 11:51:47 +0200 Subject: Python embedding question. Message-ID: Hi, Sorry I've posted a similar question some weeks ago, but I got no answers. I want to embed a Python application on a device with limited resources, esp. storage limitations. Is there a way to reduce the Python interpreter to a set of modules that's urgently needed? Or is there a method to have gzipped modules that are unzipped on the fly into memory when they're accessed? That would be even better. Additionally, is there a Python module that contains all the stuff needed for an embedded application like graphics, sound etc. or do I have to use the various bindings to libraries like cairo, Qt or similar? Is there a site that helps with those decisions? I've really looked at a lot of places but haven't found a suitable solutions yet, so I'm asking here in hope that someone has experience with that topic. Regards, Thomas. From mhansen at gmail.com Thu Jul 10 05:45:23 2008 From: mhansen at gmail.com (Mike Hansen) Date: Thu, 10 Jul 2008 02:45:23 -0700 (PDT) Subject: python scalability References: Message-ID: > I have looked at the python > success stories page and haven't come up with anyone quite like us. > One of my project managers questions is: "Are we the only company in the > world with this kind and size of project?" > I want to say no, but am having trouble convincing myself, let alone him. > > If you are involved in this kind of thing please get in touch with me. While Sage ( http://www.sagemath.org ) is more of a library than an application, it is approximately 350k lines of Python and Cython (in roughly a 2 to 1 ratio). I think it has scaled surprisingly well. --Mike From chris.hulan at gmail.com Fri Jul 4 09:55:34 2008 From: chris.hulan at gmail.com (Chris Hulan) Date: Fri, 4 Jul 2008 06:55:34 -0700 (PDT) Subject: running python from cmd.exe References: Message-ID: On Jul 4, 5:38 am, Dominic Rice wrote: > Dominic Rice wrote: > > Miki wrote: > >> Hello, > > >>> I can't seem to get python to run my scripts using the command: python > >>> .py > > >>> If I type python the interpreter runs as I sorted out the Path property, > > >>> I'm afraid I don't know much about this kind of thing as I'm a science > >>> student who needs some Python not a programmer! > >> Can you be more specific about the error you get? > > >> Say you have a script hw.py that contains one line: > >> print "Hello Python" > > >> and you run > >> python hw.py > > >> What is the error you get? > > >> HTH, > >> -- > >> Miki > >>http://pythonwise.blogspot.com > > > Sure, I get: > > > can't open file .py: [errorno 2]No such file or directory. > > > Now if I've noticed that if I change directory to (for instance) > > \Python25 where the script is the command runs fine.(?) > > Oh I just noticed you specified hw.py, in that case just to clarify it > would be can't open file hw.py: [errorno 2]No such file or directory When you run a script, are you in the directory where the script is located? From deets at nospam.web.de Thu Jul 31 19:35:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 01 Aug 2008 01:35:43 +0200 Subject: Function References In-Reply-To: References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> <6fe0scFaus40U1@mid.uni-berlin.de> <6bc8bc07-eab0-4303-b8a4-c9470f96038d@c65g2000hsa.googlegroups.com> <6fe1n2Faus40U3@mid.uni-berlin.de> Message-ID: <6ff0ifFbbpfbU1@mid.uni-berlin.de> squishywaffle at gmail.com schrieb: > On Jul 31, 10:47 am, "Diez B. Roggisch" wrote: >> I take the freedom to do so as I see fit - this is usenet... > > Fine, then keep beating a dead horse by replying to this thread with > things that do nobody any good. It seems like there are a lot better > way to waste time, though. You mean like trying to wrap ones head around the rather simple Python C API, not getting a callback mechanism implemented? For the record: I've wrapped C-libs myself, including callbacks. Been there, done that, discovered (years later) cytpes, been there for good. > The Python/C API can get me back further without reliance on third- > party libraries than ctypes. You don't consider your own library a third party lib? And unless you're wrapping C++, you're opinion is as uninformed as it is wrong. > It also isn't subject to the quirks that > ctypes is on platforms other than Windows (the target application runs > on Windows, Mac, and eventually Linux once the original distributor > has drivers for the device). I'm not even sure ctypes could load the > lib/driver the distributor packaged. Oh please. I'm 98% working on linux & osx. ctypes does a great job on these platforms. Regarding your objections I can only say: whatever the python runtime can load because of the underlying ld, ctypes can load. simply because they are the same. If *that* was the actual cause of problems, we wouldn't even talk about callbacks here. > So really, I appreciate the option in ctypes, it's good stuff. But > it's not for this project. Stop finding lame excuses for not wanting to ditch the work you've done in favor of a easier solution. You like your code, you want to keep it, you want to discover the intricasies of the Python C API? Be my guest. But stop embarassing yourself inventing reasons like licensing or linker problems you don't support with any facts whatsoever. > Once again, the original question stands for anyone who has experience > with the Python/C API callbacks. You know what? Just for the fun of it, I'll take a stab at it. It's easy: Create a "proxy-function" that matches the prototype of the c8allback which converts the passed arguments to python values using the C-api. Then call the registered python function using PyObject_CallFunction. Convert the return-value back to C, and return it. Make the function get the PyObject* for the call fetch from a global variable you set in the register-callback function, where you also register the proxy-function for the first time, or de-register if the passed value is None or such. Have fun. Diez From timr at probo.com Sun Jul 27 00:32:59 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 27 Jul 2008 04:32:59 GMT Subject: Stripping parts of a path References: Message-ID: <8utn84hs5c713k54l5kmfrgbg3k2dr1oce@4ax.com> Tim Cook wrote: > >I just ran into an issue with the rstrip method when using it on path >strings. > >When executing a function I have a need to strip off a portion of the >current working directory and add on a path to a log file. Initially >this worked great but then I added a branch in SVN which caused the path >to contain 'LNCCWorkshop'. The rstrip() then began removing the >characters 'shop' leaving an incorrect path to the log file. When I >hard coded this path it worked okay but then did the same thing later in >the file when I needed to point to a database. The code worked fine with >a different path. Here are some code fragments. > >logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/at_build_errors.log' This doesn't do what you think it does. The parameter to rstrip is a set: as long as the last character is in the set 'abcdhiloprs/', it will remove it and check the next one. All of the characters in "shop" are in that set. In a few minutes, I couldn't think of a clever one-liner to do this. You could do it with re.sub, but that seems like overkill. chk = '/src/oship/atbldr' cwd = os.getcwd() if cwd.endswith( chk ): cwd = cwd[:-len(chk)] -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steven.potter at gmail.com Sun Jul 6 23:55:02 2008 From: steven.potter at gmail.com (Steve Potter) Date: Sun, 6 Jul 2008 20:55:02 -0700 (PDT) Subject: mirroring files and data via http References: Message-ID: <9a56e820-164f-4151-82f0-0bdf64c6a636@59g2000hsb.googlegroups.com> On Jul 6, 8:19 pm, Matt Nordhoff wrote: > Steve Potter wrote: > > I'm working on a project to create a central administration interface > > for several websites located on different physical servers. > > > You can think of the websites as a blog type application. My > > administration application will be used to create new blog posts with > > associated media (images, etc..) > > > So I am thinking to setting up a script on each of the sites to "phone > > home" once per day and download any new posts and media files. > > > I am thinking of transmitting the post data in an xml format that > > could then be decoded an recorded into the database on the slave > > site. Are there any easy ways to encode a python dictionary to and > > from xml? > > > For the media files I am thinking that the administration interface > > would also provide an xml file with a list of all of the media files > > required along with an http path to retrieve them and a checksum of > > some sort to verify that they were downloaded correctly. > > > Basically I am trying to figure out if anything already exists to > > perform some of these functions or if I have to make them from > > scratch. I know none of it should be too hard, but I hate to re- > > invent the wheel. > > > Thanks, > > > Steven Potter > > It sounds like JSON would be perfect for this. For working with it in > Python, the simplejson module is popular: > > > -- Matt, You are correct JSON would be much easier to deal with than xml. That takes care of several of the problems. Now it really just comes down to the file transfer from one server to the other and a verification of some sort that the file transfer was not corrupt. Is there a python module that takes care of file downloads and verification? Thanks, Steve From fredrik at pythonware.com Wed Jul 16 12:46:46 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 18:46:46 +0200 Subject: how to match whole word In-Reply-To: <97461ec5-151a-4527-a5fa-c5da07941e46@l42g2000hsc.googlegroups.com> References: <97461ec5-151a-4527-a5fa-c5da07941e46@l42g2000hsc.googlegroups.com> Message-ID: Peng Yu wrote: > I didn't read the docs and tried the following code. > > regex = re.compile(r"\A" + re.escape(old_str) + r"\Z", > opts.ignore_case and re.I or 0) > > But I'm not sure why it is not working. as the documentation says, \A and \Z matches at the beginning/end of a *string*, not a word. From tcfg at sina.com Thu Jul 17 08:16:27 2008 From: tcfg at sina.com (fang) Date: Thu, 17 Jul 2008 05:16:27 -0700 (PDT) Subject: how to debug python's extend module written in c/c++ on windows References: <64d771b2-fbc8-4b6a-9725-3dc5063c5328@p25g2000hsf.googlegroups.com> <6e83v4F5pfg0U1@mid.uni-berlin.de> <6e8cfgF5n34gU1@mid.uni-berlin.de> Message-ID: <3ac0db1c-81d2-4922-9133-5da830f5a346@34g2000hsh.googlegroups.com> Dear Diez: It is attaching a C-debugger to python. I can attach python- debugger(for example:wingIDE) to c-debugger(for example:VS2008), but I cannot attach VS2008 to wingIDE. I need both python statement and c statement can be single-step debugged. best regards fang From eliben at gmail.com Fri Jul 11 01:27:24 2008 From: eliben at gmail.com (eliben) Date: Thu, 10 Jul 2008 22:27:24 -0700 (PDT) Subject: using Python's AST generator for other languages References: <6d31532b-9946-42a3-a20b-56c403a388b2@l42g2000hsc.googlegroups.com> Message-ID: > > 2) What is the meaning of the comment in astgen.py ? Are the Python > > maintainers unhappy with the design of the AST ?3 > > Node, I think, is talking about a node in the parse tree. (AST is > generated from another parse tree.) See PEP 339 for details. > Thanks, PEP 339 clarified a lot to me. I wonder, though, at the need for two Python compilation frameworks in the same code base. While CPython uses the flow described in PEP 339 (parsing to an AST generated from ASDL), the compiler module of the standard library takes a different approach, with a custom AST description syntax in ast.txt Why aren't the two methods unified. I.e. can't the compiler.ast module be also generated from ASDL, and provide a more unified interface to the real thing ? Eli From fredrik at pythonware.com Thu Jul 24 16:21:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 22:21:34 +0200 Subject: Reading a file In-Reply-To: <73045cca0807241306h370166ebwdd1b12227cef43c2@mail.gmail.com> References: <73045cca0807241306h370166ebwdd1b12227cef43c2@mail.gmail.com> Message-ID: aditya shukla wrote: > I have a text file whose contents are like this:- > > jd|fj|dnv|jd|0.33|c:\\windows\\win32 > shcbsbs|nscsjsj|0.93|hsbcjsnc > > I am trying to read the file like this:- > > >>> x = open("c:\\a.txt","r") > >>> x.read() eh, wouldn't it be easier if you actually read the replies to your last post on this topic? here's an excerpt from the reply you got last time: > Extracting is easy; you can do something like > > data = [] > for line in open("test.txt"): > line = line.split("|") > data.append(float(line[1])) which fetches floating point values from the text file example you posted last time: > 0\9\10\11|0.50|c:\windows\apppatch/AcLayers.dll > 0\9\10\11|0.50|c:\windows\apppatch/AcRedir.dll > 0\9\10|0.66|c:\windows\apppatch/AcSpecfc.dll > 0\9|0.83|c:\windows\apppatch/iebrshim.dll if the values have moved to some other column, adjust line[1] accordingly. From karthikbalaguru79 at gmail.com Wed Jul 23 04:19:48 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Wed, 23 Jul 2008 01:19:48 -0700 (PDT) Subject: Strange problem .... Message-ID: <12fd8ef1-c7e0-470b-ba51-f946d8ea8e26@z6g2000pre.googlegroups.com> Hi, I am new to python, Kindly suggest to resolve a problem with a python file. What does the below error refer to ? I use Redhat 9.0, python-2.2.2-26, python-devel-2.2.2-26 and db4-4.0.14-20. [root at localhost processor]# Analyzer processorcycle /usr/local/SDK/bin/../core/bin/processorlib.py:8 8: Warning: 'yield' will become a reserved keyword in the future Traceback (most recent call last): File "/usr/local/SDK/bin/Analyzer", line 48, in ? from debuglib import ProcessorInfo File "/usr/local/SDK/bin/../core/bin/processorlib.py", line 88 yield ProcessorObjectInfo(child, self.pt) ^ SyntaxError: invalid syntax Is this error related with the version of python / python-devel that i use . Any ideas / tips ? Thx in advans, Karthik Balaguru From jarausch at skynet.be Tue Jul 15 11:39:39 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 15 Jul 2008 17:39:39 +0200 Subject: Python internals question In-Reply-To: References: Message-ID: <487cc4bb$0$2855$ba620e4c@news.skynet.be> Peter Anderson wrote: > Hi! I am slowly teaching myself Python. I was reading David Beazley's > excellent book "Python - Essential Reference"; in particular about > variables. Let me quote: > > "Python is a dynamically typed language in which names can represent > values of different types during the execution of a program. In fact the > names used in the program are really just labels for various quantities > and objects. The assignment operator simply creates an association > between a name and a value. This is different from C, for example, in > which a name (variable) represents a fixed size and location in memory..." > > As an old mainframe programmer, I understand the way C does things with > variable but this text got me wondering how Python handles this > "association" between variable name and value at the lower level. Is it > like a fifo list? > > If there is any Python guru that can help I would be most interested in > your thoughts. > Please have a look at http://effbot.org/zone/call-by-object.htm and http://rg03.wordpress.com/2007/04/21/semantics-of-python-variable-names-from-a-c-perspective/ -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From pladow at gmail.com Tue Jul 1 17:49:23 2008 From: pladow at gmail.com (PlayDough) Date: Tue, 1 Jul 2008 14:49:23 -0700 (PDT) Subject: AttributeError with embedded Python Message-ID: <67f2b99f-2f9b-48b9-bb38-7f47c9097df6@e53g2000hsa.googlegroups.com> I've embedded Python in an extension for a program we are using here at work. And I'm a bit stumped as to why I am getting an AttributeError only in the embedded Python. First, a bit of what I am doing. We use a simulator for a microprocessor we are using in our systems. Our simulator allows for extensions that can be loaded as shared libraries. Rather than code the entire extension in C/C++, I would like to make use of Python to script the extension. So, I first initialize Python (examples below leave out the error checking, but it is there): Py_Initialize(); And then I make sure the script directory is in the path with Py_GetPath() and PySys_SetPath(). Finally, I import the script (say it is in a local file 'script.py'): pName = PyString_FromString("script"); pModule = PyImport_Import(pName); Once the module is imported, I get objects to the functions in the script I want to call later, which I do with: pName = PyString_FromString("foo"); pFunc = PyObject_GetAttr(pModule, pName); Later, I come back and call the function: pResult = PyObject_CallObject(pFunc, NULL); And it always fails whenever I iterate of a list. Say for example my Python function is: def foo(): a = ['cat', 'window', 'defenstrate'] for x in a: print x, len(x) Now, the function runs, i.e. I see the output ("cat 3\nwindow 6\ndefenstrate 11\n"), but I always get the following error message: Traceback (most recent call last): File "./script.py", line 3, in foo for x in a: AttributeError: 'module' object has no attribute 'reset' Now, if I run this exact same script using Python standalone, i.e.: Python 2.3.4 (#1, Nov 20 2007, 15:18:15) [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import script >>> script.foo() cat 3 window 6 defenstrate 11 >>> (I know, and old version of Python. But we are stuck with it because our processes require us to validate a newer version if we change.) This works great. What is the difference? Why does it work in one context but not the other? Thanks, Pete From tjreedy at udel.edu Thu Jul 17 15:42:38 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jul 2008 15:42:38 -0400 Subject: % sign in python? In-Reply-To: References: Message-ID: korean_dave wrote: > What does this operator do? Specifically in this context > > test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) > > (Tried googling and searching, but the "%" gets interpreted as an > operation and distorts the search results) Having seen a number of comments like this over the years (about the difficulty of searching for symbol meanings), I just started, last night, a symbol index listing nearly all Python syntax uses of non-alpha-or-digit ascii symbols. When I finish and upload it somewhere, I will post an announcement with the link. tjr From cito at online.de Sat Jul 12 11:09:15 2008 From: cito at online.de (Christoph Zwerschke) Date: Sat, 12 Jul 2008 17:09:15 +0200 Subject: strip() using strings instead of chars In-Reply-To: References: Message-ID: Duncan Booth schrieb: >> if url.startswith('http://'): >> url = url[7:] > > If I came across this code I'd want to know why they weren't using > urlparse.urlsplit()... Right, such code can have a smell since in the case of urls, file names, config options etc. there are specialized functions available. But I'm not sure whether the need for removing string prefix/suffixes in general is really so rare that we shouldn't worry to offer a simpler solution. -- Christoph From JordanNealBerg at gmail.com Thu Jul 10 16:26:28 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Thu, 10 Jul 2008 13:26:28 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: <8feab8ce-1e09-4438-b00a-3b31956c56af@k37g2000hsf.googlegroups.com> <5c521979-aaf0-4b4b-9673-671a978d050a@j22g2000hsf.googlegroups.com> <3hqc74lhdkdqrjb20h34k6ab65g2hc8ucp@4ax.com> Message-ID: On Jul 10, 4:04?pm, Harald Luessen wrote: > On Thu, 10 Jul 2008 Jordan wrote: > > > > >On Jul 10, 1:35?pm, MRAB wrote: > >> On Jul 10, 4:56?am, Jordan wrote: > > >> > I am trying to rewrite some C source code for a poker hand evaluator > >> > in Python. ?Putting aside all of the comments such as just using the C > >> > code, or using SWIG, etc. ?I have been having problems with my Python > >> > code not responding the same way as the C version. > > >> > C verison: > > >> > unsigned find_fast(unsigned u) > >> > { > >> > ? ? unsigned a, b, r; > >> > ? ? u += 0xe91aaa35; > >> > ? ? u ^= u >> 16; > >> > ? ? u += u << 8; > >> > ? ? u ^= u >> 4; > >> > ? ? b ?= (u >> 8) & 0x1ff; > >> > ? ? a ?= (u + (u << 2)) >> 19; > >> > ? ? r ?= a ^ hash_adjust[b]; > >> > ? ? return r; > > >> > } > > >> > my version (Python, hopefully ;)): > > >> > def find_fast(u): > >> > ? ? u += 0xe91aaa35 > >> > ? ? u ^= u >> 16 > >> > ? ? u += u << 8 > >> > ? ? u ^= u >> 4 > >> > ? ? b ?= (u >> 8) & 0x1ff > >> > ? ? a ?= (u + (u << 2)) >> 19 > >> > ? ? r ?= a ^ hash_adjust[b] > >> > ? ? return r > > >> > As far as I understand the unsigned instructions in C just increase > >> > amount of bytes the int can hold, and Python automatically converts to > >> > longs which have infinite size when necessary, so I am not sure why I > >> > am getting different results. > > >> > I assume that I am missing something fairly simple here, so help a > >> > n00b out if you can :) > > >> > Thanks in advance, > > >> > jnb > > >> You want to restrict the values to 32 bits. The result of + or << may > >> exceed 32 bits, so you need to mask off the excess bits afterwards. > > >> def find_fast(u): > >> ? ? mask = 0xffffffff > >> ? ? u ?= (u + 0xe91aaa35) & mask > >> ? ? u ^= u >> 16 > >> ? ? u ?= (u + (u << 8)) & mask # can get away with only 1 mask here > >> ? ? u ^= u >> 4 > >> ? ? b ?= (u >> 8) & 0x1ff > >> ? ? a ?= ((u + (u << 2)) & mask) >> 19 # can get away with only 1 mask > >> here > >> ? ? r ?= a ^ hash_adjust[b] > >> ? ? return r > > >> HTH > > >Well, I guess there are two problems....the masking and the fact the > >in C it seems to for some reason overflow and become a negative > >value....still not sure why it does it....So the code with just > >masking doesn't work, you still need some sort of weird inversion like > >the ~(0xFFFFFFFF - u).....weird > > >anyone? > > In C unsigned can not be negative. Why do you believe > the numbers are negative? If your debugger is telling > you this thow away the debugger and use printf. > If printf is telling you this then use the right format. > printf("%u", u); // for unsigned int u > printf("%lu", u); // for unsigned long u > printf("%x", u); > or > printf("0x%08x", u); // to see u in hex > > Harald haha....I was using printf, but for some reason I decided not to use %u...hmm...looking back over things now... From mrkafk at gmail.com Wed Jul 23 08:14:00 2008 From: mrkafk at gmail.com (mk) Date: Wed, 23 Jul 2008 14:14:00 +0200 Subject: Python Written in C? In-Reply-To: References: Message-ID: > Actually, all of the compilers I'm familiar with (gcc and a > handful of cross compilers for various microprocessors) > translate from high-level languages (e.g. C, C++) into > assembly, which is then assembled into relocatable object > files, which are then linked/loaded to produce machine > language. Doesn't g++ translate C++ into C and then compile C? Last I heard, most C++ compilers were doing that. From larry.bates at websafe.com` Mon Jul 14 18:22:50 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 14 Jul 2008 17:22:50 -0500 Subject: Is it possible to create "network conneciton" on windows system? In-Reply-To: References: Message-ID: Evan wrote: > Hello, > > one of my PC is window system, and in "control panel -> Network > Connections", I can see some network connections such as PPPOE or VPN > which I created by click "create a new connection". > > My question is, is it possible to create a new connection by using > Python script? which means I do not want to use Window UI (via > "control panel"), if it is possible, I can save so many time to > create various network connection when I want to do testing in the > lab. > > Thanks very much. > Evan It is very likely that it is possible to do this. Most control panel applications store the results of their GUI setup in the registry. If you can determine what registry keys have been added/changed. Here is an open source registry compare utility that might help: https://sourceforge.net/projects/regshot You can then use the _winreg module to make such changes on a new machine. HTH, Larry From wuwei23 at gmail.com Sun Jul 27 23:38:26 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 27 Jul 2008 20:38:26 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> <6a5506b1-632e-4bf6-b0ce-4d51d1751aa9@i24g2000prf.googlegroups.com> <8b4b11c3-e306-4fe7-82d1-0a948c725f2f@r15g2000prd.googlegroups.com> Message-ID: <239a084f-b73d-4c20-aaaf-bbd05d452638@a2g2000prm.googlegroups.com> On Jul 28, 4:59?am, "Russ P." wrote: > On Jul 27, 3:11 am, alex23 wrote: > > > On Jul 27, 4:26 pm, "Russ P." wrote: > > > > On Jul 26, 11:18 pm, Terry Reedy wrote: > > > > The use of '.' has been suggested before and rejected. > > > > Where and why? > > > Google is your friend:http://mail.python.org/pipermail/python-3000/2006-April/000793.html > > What Guido rejected there is most certainly *not* > what I suggested. I agree with Guido on that one. Orly? Ian Bicking wrote: "I propose that the self argument be removed from method definitions." Philip Eby suggested: > def .aMethod(arg1, arg2): > return .otherMethod(arg1*2+arg2) Guido shot them all down by stating: > [Y]ou're proposing to hide a > fundamental truth in Python, that methods are "just" functions whose > first argument can be supplied using syntactic sugar Any more reading comprehension we can do for you? From bdesth.quelquechose at free.quelquepart.fr Mon Jul 28 14:39:53 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Jul 2008 20:39:53 +0200 Subject: multiple inheritance and __getattr__ In-Reply-To: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> References: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> Message-ID: <488e2e70$0$29472$426a74cc@news.free.fr> Enrico a ?crit : > Hi there, > I have the following situation (I tryed to minimize the code to concentrate > on the issue): > >>>> class A(object): > def __getattr__(self, name): > print 'A.__getattr__' > if name == 'a': return 1 > raise AttributeError('%s not found in A' % name) > >>>> class B(object): > def __getattr__(self, name): > print 'B.__getattr__' > if name == 'b': return 1 > raise AttributeError('%s not found in B' % name) > > Both classes have a __getattr__ method. > Now I want to have a class that inherits from both so I write: > >>>> class C(B,A): > pass > > The problem arise when I try something like this: >>>> c=C() >>>> c.a > A.__getattr__ > 1 >>>> c.b > A.__getattr__ > > Traceback (most recent call last): > File "", line 1, in > c.b > File "", line 5, in __getattr__ > raise AttributeError('%s not found in A' % name) > AttributeError: b not found in A That's what I would have expected. > I was expecting, after a fail in A.__getattr__, a call to the __getattr__ > method of B but it seems that after A.__getattr__ fails the exception stops > the flow. Indeed. You explicitely raise, so the lookup stops here. You'd need to explicitely call on superclass instead to have B.__getattr__ called, ie: class A(object): def __getattr__(self, name): if name == 'a': return 1 return super(A, self).__getattr__(name) class B(object): def __getattr__(self, name): if name == 'b': return 2 return super(B, self).__getattr__(name) class C(A, B): pass c = C() c.a => 1 c.b => 2 > So, if I did understand well, B.__getattr__ will be never called > "automatically". I don't know if this has a reason, if it is a design choice > or what else, any explanation is welcome. > > Since A and B are not written by me I can only work on C. Really ? You know, Python is a *very* dynamic language. If A and B are ordinary Python classes (ie: not builtin types, not C extensions, etc), you can monkeypatch them. But that's not necessarily the best thing to do (it would require more work than your actual solution). > The solution that > comes to my mind is to define a __getattr__ also in C and write something > like: > >>>> class C(A,B): > def __getattr__(self, name): > try: > return A.__getattr__(self, name) > except AttributeError: > return B.__getattr__(self, name) or more generically: class C(A, B): def __getattr__(self, name): for cls in type(self).__mro__[1:]: try: return cls.__getattr__(self, name) except AttributeError: pass else: raise AttributeError('blah blah') You could also override __getattribute__, but then again, this wouldn't be better (more code, and possible performances loss). > A better solution is welcome. If you don't have commit rights on the module(s) defining A and B, then your solution is probably the simplest thing to do. From gagsl-py2 at yahoo.com.ar Wed Jul 30 00:46:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 01:46:02 -0300 Subject: Windows Interpreter References: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> <488F1745.4020705@timgolden.me.uk> <4dc0cfea0807290626p4b05376en49ccb18f0e1eb4bb@mail.gmail.com> <488F1DB3.4010608@timgolden.me.uk> Message-ID: En Tue, 29 Jul 2008 17:00:40 -0300, Terry Reedy escribi?: > I just found the QuickEdit option. While in an administrator account > (if Python is installed for all users), bring up the menu as specified > above, select Properties instead, then the Options tab, then select > QuickEdit on the right. When clicking OK, being admin allows > modification of the shortcut and not just the current window. > > Learn something new every day. Thanks. Just as a side note, setting QuickEdit on by default is not as good idea as it may appear. If you click or drag accidentally with the mouse over the console, the running program is blocked indefinitely (waiting for the selection to be completed; someone has to press ). Not very nice if you launched a long process and are waiting for it to finish... -- Gabriel Genellina From martin at v.loewis.de Sun Jul 13 13:31:57 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 13 Jul 2008 19:31:57 +0200 Subject: heapq question In-Reply-To: References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> Message-ID: <487a3c0d$0$32256$9b622d9e@news.freenet.de> > I understand that heapq is not that efficient to implement timeouts as > I thought at first. > It would have been perfect if there were functions to remove arbitrary > elements withouth needing to re-heapify() the heap every time. It is efficient for that - you just need to use it correctly. To remove the nth element from a heap, replace it with the last element, and then _siftup that element: def remove_at_index_n(heap, n): if n == len(heap)-1: return heap.pop() result = heap[n] heap[n] = heap.pop() heapq._siftup(heap, n) return result The time complexity for that operation is O(log(len(heap))). HTH, Martin From s0suk3 at gmail.com Tue Jul 1 21:31:47 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Tue, 1 Jul 2008 18:31:47 -0700 (PDT) Subject: raw_input into Tkinter ? References: <634e2b50-45ba-4b93-89b4-0afd739adaf3@z66g2000hsc.googlegroups.com> Message-ID: On Jun 30, 11:55 am, jamitwi... at gmail.com wrote: > Is there any way to type into a Tkinter frame window? > I want to use raw_input() within a Tkinter frame. import sys import Tkinter import cStringIO class GUIInputMgr(Tkinter.Entry): def __init__(self, parent): Tkinter.Entry.__init__(self, parent) sys.stdin = cStringIO.StringIO() self.bind("", self.__UpdateBuffer) def __UpdateBuffer(self, event): sys.stdin.truncate(0) sys.stdin.write(self.get()) entry = GUIInputMgr(top) # top is your Tk() instance entry.pack() raw_input() # should now get you user input :) Sebastian From bruno.42.desthuilliers at websiteburo.invalid Fri Jul 4 08:34:34 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 04 Jul 2008 14:34:34 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <486e17b2$0$12609$426a74cc@news.free.fr> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <486e17b2$0$12609$426a74cc@news.free.fr> Message-ID: <486e18c9$0$12609$426a74cc@news.free.fr> Bruno Desthuilliers a ?crit : > Henning_Thornblad a ?crit : >> What can be the cause of the large difference between re.search and >> grep? >> >> This script takes about 5 min to run on my computer: >> #!/usr/bin/env python >> import re >> >> row="" >> for a in range(156000): >> row+="a" >> print re.search('[^ "=]*/',row) >> >> >> While doing a simple grep: >> grep '[^ "=]*/' input (input contains 156.000 a in >> one row) >> doesn't even take a second. >> >> Is this a bug in python? > > Please re-read carefully your python code. Don't you think there's a > subtle difference between reading a file and buildin 156000 string > objects ? > Mmm... This set aside, after testing it (building the string in a somewhat more efficient way), the call to re.search effectively takes ages to return. Please forget my previous post. From hitechpundir at gmail.com Mon Jul 21 09:19:49 2008 From: hitechpundir at gmail.com (hitechpundir at gmail.com) Date: Mon, 21 Jul 2008 06:19:49 -0700 (PDT) Subject: how to create GUI dynamically Message-ID: <84f144db-0d6c-44d5-a1ef-6e7778304c2a@r66g2000hsg.googlegroups.com> Hi; i m working on a project where i need run time creation of GUI. i have some no. of entities for which i want checkboxes in front of them which can be checked/ unchecked by user. But the problem is that the number and name of entities is not fixed and it depends on the file which is used as input. So is there any way to tackle this problem. By the way ; i use Boa constructor (zope editor) for GUI now. regards pawan pundir From circularfunc at gmail.com Thu Jul 10 09:27:10 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 10 Jul 2008 06:27:10 -0700 (PDT) Subject: Weird lambda rebinding/reassignment without me doing it Message-ID: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> I am never redefining the or reassigning the list when using validate but since it spits the modified list back out that somehow means that the modified list is part of the environment and not the old one. i thought what happend inside a function stays inside a function meaning what comes out is independent of what comes in. Meaning if I want the list I send as a parameter to the function I have to do x = func(x) and not just func(x) and x is magically what comes out of func(). Doesnt Python have closure or that isnt what this is about? def validate(placed): student = round(random.random()*401) if student in placed: return validate(placed) else: placed.append(student) return student, placed def val(placed): student = round(random.random()*401) if student in placed: return validate(placed) else: placed.append(student) return student >>> g = lambda x:validate(x) >>> l=[] >>> for x in range(1,10): g(l) (141.0, [141.0]) (19.0, [141.0, 19.0]) (86.0, [141.0, 19.0, 86.0]) (120.0, [141.0, 19.0, 86.0, 120.0]) (76.0, [141.0, 19.0, 86.0, 120.0, 76.0]) (262.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0]) (234.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0]) (74.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0]) (325.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0, 325.0]) >>> g = lambda x:val(x) >>> l=[] >>> for x in range(1,10): g(l) 183.0 33.0 315.0 244.0 308.0 168.0 146.0 378.0 297.0 >>> From denis.kasak2718281828 at gmail.com Sat Jul 12 03:13:05 2008 From: denis.kasak2718281828 at gmail.com (Denis Kasak) Date: Sat, 12 Jul 2008 09:13:05 +0200 Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: Peter Otten wrote: > Denis Kasak wrote: > >> Basically, it reverses the list in place, so it modifies the list which >> called it. It does not return a /new/ list which is a reversed version >> of the original, as you expected it to. Since it doesn't return anything >> explicitly, Python makes it return None. Hence, the comparison you are >> doing is between the original list and a None, which is False, naturally. >> Try this: >> >> spam = ['a', 'n', 'n', 'a'] >> eggs = spam[:] >> if spam.reverse() == eggs: >> print "Palindrome" > > Your explanation is correct, but your example code compares None to > ['a', 'n', 'n', 'a'] and therefore won't print "Palindrome", either. Of course. Thank you for the correction. I guess you know your caffeine has started to wear off when you start making the same mistakes you were trying to fix. :-) -- Denis Kasak From mrkafk at gmail.com Mon Jul 21 13:59:11 2008 From: mrkafk at gmail.com (mk) Date: Mon, 21 Jul 2008 19:59:11 +0200 Subject: calling source command within python In-Reply-To: References: Message-ID: Jie wrote: > Hi all, > > i'm having trouble executing os.system('source .bashrc') command > within python, it always says that source not found and stuff. Any > clue? It _might_ be that the shell it fires up is /bin/sh and this in turn is not bash. Anyway, it's better to use subprocess / Popen for this sort of operation. From gary at byoteki.com Sun Jul 27 01:41:08 2008 From: gary at byoteki.com (Gary Josack) Date: Sun, 27 Jul 2008 01:41:08 -0400 Subject: Simple Path issues In-Reply-To: <6093d9df-d68d-43e7-90d4-44f964529299@m3g2000hsc.googlegroups.com> References: <7bef6df9-45d6-4ef6-b802-1dd201ec66e3@k30g2000hse.googlegroups.com> <6093d9df-d68d-43e7-90d4-44f964529299@m3g2000hsc.googlegroups.com> Message-ID: <488C0A74.10908@byoteki.com> Brett Ritter wrote: > On Jul 26, 2:57 pm, Gary Josack wrote: > >> sys.path is a list that will tell you where python is looking. You can >> append to this in your scripts to have python look in a specific >> directory for your own modules. >> > > I can, but that is almost certainly not the standard way to develop a > module. > > I see nothing in sys.path that I have write permissions to. > > Is altering my PYTHONPATH the normal way to develop (under the > assumption that later users will install in their conventional python > search path)? > > -- > http://mail.python.org/mailman/listinfo/python-list > If you plan to put your module in a non-standard location then your only options are adding to sys.path in you program or setting PYTHONPATH. If this is only for development then you're better off just using PYTHONPATH with the assumption "users will install in their conventional python search path". From mail at timgolden.me.uk Thu Jul 24 11:45:42 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 24 Jul 2008 16:45:42 +0100 Subject: Python / PAMIE In-Reply-To: <9e077ec9-9a07-4a3a-b5dc-bfd593162350@8g2000hse.googlegroups.com> References: <9e077ec9-9a07-4a3a-b5dc-bfd593162350@8g2000hse.googlegroups.com> Message-ID: <4888A3A6.7010801@timgolden.me.uk> frankrentef wrote: > THNX for your response. Based on the authors code it's very simple. > > from cPAMIE import PAMIE > ie=PAMIE () > > #ie.navigate ("google.com") > > #ie.linkClick > #ie.textBoxSet > #ie.writeScript > > ie.navigate ('https://login.yahoo.com/config/mail?.intl=us') > #ie.scriptWrite () > > ie.scriptWrite() > > > Below is the error I get... > > File "C:\Python24\lib\site-packages\cPAMIE.py", line 1837, in > scriptWrite > nameProp = getattr(x,"nameProp") > File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", > line 500, in __getattr__ > raise AttributeError, "%s.%s" % (self._username_, attr) > AttributeError: .nameProp I'm afraid I'm no IE expert (read: never use it if I can avoid it) but I suspect here a combination of slightly flaky code in the Python module plus, maybe, a change in the IE dom object model. If you change lines 1832-1836 of cPAMIE.py to be as follows: for j in range(doc.length): x = doc[j] etype = getattr(x,"type", "") name = getattr(x,"name", "") nameProp = getattr(x,"nameProp", "") then at least some kind of output is produced. But I'm not entirely sure what this function is trying to achieve so I don't guarantee it's doing the right thing yet. TJG From stefan_ml at behnel.de Wed Jul 30 16:51:16 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 30 Jul 2008 22:51:16 +0200 Subject: Python parsing iTunes XML/COM In-Reply-To: References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Message-ID: <4890d444$0$12943$9b4e6d93@newsspool2.arcor-online.net> william tanksley wrote: > Okay, so you decode to go from raw > byes into a given encoding, and you encode to go from a given encoding > to raw bytes. No, decoding goes from a byte sequence to a Unicode string and encoding goes from a Unicode string to a byte sequence. Unicode is not an encoding. A Unicode string is a character sequence, not a byte sequence. Stefan From steve at REMOVE-THIS-cybersource.com.au Sun Jul 27 06:15:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Jul 2008 10:15:31 GMT Subject: Confounded by Python objects References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> <5ddae1dd-c7dd-4f04-84f6-ad71c3282c92@j7g2000prm.googlegroups.com> <6f1a6uF9ctsmU1@mid.uni-berlin.de> Message-ID: <009c464f$0$20302$c3e8da3@news.astraweb.com> On Sat, 26 Jul 2008 18:54:22 +0000, Robert Latest wrote: > Here's an interesting side note: After fixing my "Channel" thingy the > whole project behaved as expected. But there was an interesting hitch. > The main part revolves around another class, "Sequence", which has a > list of Channels as attribute. I was curious about the performance of my > script, because eventually this construct is supposed to handle > megabytes of data. So I wrote a simple loop that creates a new Sequence, > fills all the Channels with data, and repeats. > > Interistingly, the first couple of dozens iterations went satisfactorily > quickly (took about 1 second total), but after a hundred or so times it > got really slow -- like a couple of seconds per iteration. > > Playing around with the code, not really knowing what to do, I found > that in the "Sequence" class I had again erroneously declared a > class-level attribute -- rather harmlessly, just a string, that got > assigned to once in each iteration on object creation. > > After I had deleted that, the loop went blindingly fast without slowing > down. > > What's the mechanics behind this behavior? Without actually seeing the code, it's difficult to be sure, but my guess is that you were accidentally doing repeated string concatenation. This can be very slow. In general, anything that looks like this: s = '' for i in range(10000): # or any big number s = s + 'another string' can be slow. Very slow. The preferred way is to build a list of substrings, then put them together in one go. L = [] for i in range(10000): L.append('another string') s = ''.join(L) It's harder to stumble across the slow behaviour these days, as Python 2.4 introduced an optimization that, under some circumstances, makes string concatenation almost as fast as using join(). But be warned: join() is still the recommended approach. Don't count on this optimization to save you from slow code. If you want to see just how slow repeated concatenation is compared to joining, try this: >>> import timeit >>> t1 = timeit.Timer('for i in xrange(1000): x=x+str(i)+"a"', 'x=""') >>> t2 = timeit.Timer('"".join(str(i)+"a" for i in xrange(1000))', '') >>> >>> t1.repeat(number=30) [0.8506159782409668, 0.80239105224609375, 0.73254203796386719] >>> t2.repeat(number=30) [0.052678108215332031, 0.052067995071411133, 0.052803993225097656] Concatenation is more than ten times slower in the example above, but it gets worse: >>> t1.repeat(number=40) [1.5138671398162842, 1.5060651302337646, 1.5035550594329834] >>> t2.repeat(number=40) [0.072292804718017578, 0.070636987686157227, 0.070624113082885742] And even worse: >>> t1.repeat(number=50) [2.7190279960632324, 2.6910948753356934, 2.7089321613311768] >>> t2.repeat(number=50) [0.087616920471191406, 0.088094949722290039, 0.087819099426269531] -- Steven From ethan at stoneleaf.us Thu Jul 31 00:13:07 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 30 Jul 2008 20:13:07 -0800 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> Message-ID: <48913BD3.9000708@stoneleaf.us> Carl Banks wrote: > On Jul 30, 4:49 am, Ethan Furman wrote: >> Even for those that did realize, and in fact hoped that that is what you >> were attempting to accomplish, > > I was not attempting to accomplish what you think I was. > > I was looking for it, but I didn't want to see it. I didn't expect to > see it. I wanted to show that "if x" doesn't have the polymorphic > advantage people mindlessly claim it does by posing the challenge and > having people fail to meet it, and for the most part the examples that > met the challenge were for minor usages. Ok, someone wrote a filter > that truly benefits from polymorphism of "if x" against very different > types, but really, these use cases aren't all that common. > > It's not like it's an everyday thing for you to write "if x" instead > of "if x!=0", and that it actually saves you from having to rewrite > the condition because later you decided to use a list. Actually, I use this construction a lot. But everybody has their own style, and I'm certainly not going to tell you yours is wrong. One of the fellows that works for me *loves* the (result if false, result if true)[condition] style of immediate if's -- it's one of the first things he learned about when studying Python, and he grins every time he talks about it; *I* know it's not the best way to do it, and that it has it's own set of gotchas -- so I made sure he was also aware of them, and uses them where and when they won't blow up in our faces. > So I stand by the point I was trying to make: for your average day-to- > day programming, the main benefit of "if x" is to save keystrokes. It > doesn't help your code become more polymophic in practice. A little > more polymorphic, yes. A lot, no. [snippitysnipsnip] > Carl Banks Hmmm... well, I see your point. Unfortunately, even though it feels incorrect to me, I do not (yet) have the breadth and depth of Python experience to come up with an example that would display such exquisite polymorphism. It also seems to me that such an example would be non-trivial in nature. Perhaps starting a new thread with this challenge, and adequate time (couple weeks at least, I would think) would net you the smoking gun you were after. At any rate, from my point of view, I like it. I like the visual clarity and simplistic nature of "if x" -- it tells me "if x is something", and I trust myself enough to know what I can do with the something that is x. I also expect anyone else passing me a something to know it has the appropriate interface to work with my code. ~Ethan~ From pythonnutter at gmail.com Sat Jul 19 23:54:08 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Sun, 20 Jul 2008 13:54:08 +1000 Subject: Best Python packages? In-Reply-To: <86b446d2-0d11-4410-bf89-a2a05fac81b2@s50g2000hsb.googlegroups.com> References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> <17861f55-8ad1-4703-ad22-838675f2afc4@w1g2000prk.googlegroups.com> <86b446d2-0d11-4410-bf89-a2a05fac81b2@s50g2000hsb.googlegroups.com> Message-ID: I think the hidden gems in multimedia/game production are Pyglet and Rabbyt. Whereas PyGame is the older api, its large and bloated and has of course a heavy dependency on SDL. Pyglet and Rabbyt are lightweight, efficient, have some amazing functions and hit native OpenGL in all the major OS distributions and Bruce The Presentation Tool utilizes the former to take on MS PowerPoint to show what you can do besides games =) Pyglet: http://pyglet.org/ Rabbyt: http://matthewmarshall.org/projects/rabbyt/ Bruce The Presentation Tool: http://code.google.com/p/bruce-tpt/ Cheers, PN > > In the original post you asked for "hidden gems" and now it seems you > just want to know about Madonna or Justin Timberlake. > > Maybe a look on this collection helps > > http://wiki.python.org/moin/UsefulModules > -- > http://mail.python.org/mailman/listinfo/python-list > From musiccomposition at gmail.com Thu Jul 10 18:54:27 2008 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 10 Jul 2008 15:54:27 -0700 (PDT) Subject: using Python's AST generator for other languages References: Message-ID: <6d31532b-9946-42a3-a20b-56c403a388b2@l42g2000hsc.googlegroups.com> On Jul 10, 12:40 pm, eliben wrote: > Hello, > > I'm building a parser in Python, and while pondering on the design of > my ASTs had the idea to see what Python uses. I quickly got to the > compiler.ast module, and understood it's automatically generated. So I > went to the source, ast.txt and tools/compiler/astgen.py, where I was > this unexpected message: > > """Generate ast module from specification > > This script generates the ast module from a simple specification, > which makes it easy to accomodate changes in the grammar. This > approach would be quite reasonable if the grammar changed often. > Instead, it is rather complex to generate the appropriate code. And > the Node interface has changed more often than the grammar. > """ > > Now, to me the design of the AST in Python looks quite elegant, > especially from the point of view of the AST's user (using Visitors to > walk the AST). And astgen.py looks like a nice approach to generate > tons of boilerplate code. > So, my questions: > 1) Is the compiler.ast module really employed during the compilation > of Python into .pyc files ? No, the comment refers to the builtin _ast module. The compiler package is a compiler for Python written in Python. > 2) What is the meaning of the comment in astgen.py ? Are the Python > maintainers unhappy with the design of the AST ?3 Node, I think, is talking about a node in the parse tree. (AST is generated from another parse tree.) See PEP 339 for details. > 3) What other approach would be recommended to generate a very > detailed AST hierarchy, if the one in astgen.py is dissapointing ? astgen.py contains things that are specific to writing Python's AST C code. Have a look at spark.py in the Parser dir. It is what astgen.py is based on. > > Thanks in advance > Eli From joshdw4 at gmail.com Wed Jul 30 17:33:37 2008 From: joshdw4 at gmail.com (joshdw4 at gmail.com) Date: Wed, 30 Jul 2008 14:33:37 -0700 (PDT) Subject: Tkinter- Possibly a basic question Message-ID: <59dee72b-3fb6-414b-ab49-33cab8f9c9e8@26g2000hsk.googlegroups.com> I hate to do this, but I've thoroughly exhausted google search. Yes, it's that pesky root window and I have tried withdraw to no avail. I'm assuming this is because of the methods I'm using. I guess my question is two-fold. 1) How do I get rid of that window? 2) Any comments in general? I am just learning python (and coding with classes), so I'm sure there are things I should pound into my head before I learn bad habits. Here's the code. It will eventually be a voltage measurement using an Arduino board. Just a simple plot for now. import Tkinter, time class App(Tkinter.Toplevel): def __init__(self,parent): Tkinter.Toplevel.__init__(self,parent) self.parent = parent self.initialize(parent) def initialize(self,parent): #create a menu self.menu = Tkinter.Menu(self) self.config(menu=self.menu) self.menu.filemenu = Tkinter.Menu(self.menu) self.menu.add_cascade(label="File", menu=self.menu.filemenu) #for later use #self.menu.filemenu.add_separator() self.menu.filemenu.add_command(label="Exit", command=self.kill) self.menu.helpmenu = Tkinter.Menu(self.menu) self.menu.add_cascade(label="Help", menu=self.menu.helpmenu) self.menu.helpmenu.add_command(label="About...", command=self.callback) #plotting canvas creation self.axis = SimplePlot(self,1000,500) #status bar self.status = StatusBar(self) self.resizable(width=Tkinter.FALSE,height=Tkinter.FALSE) def callback(self): #calls the function within status bar to set the new text, uses a tuple self.status.settext("%s %s","This callback","holds a place for now!") def kill(self): self.parent.quit() self.parent.destroy() def plot_data(self,data): self.axis.plot(data) class StatusBar(Tkinter.Frame): #initializes and draws def __init__(self,parent): Tkinter.Frame.__init__(self, parent) self.parent = parent self.label = Tkinter.Label(self.parent, bd=1, relief=Tkinter.SUNKEN, anchor=Tkinter.W,text='None') self.label.pack(fill=Tkinter.X) def settext(self, format,*args): self.label.config(text=format % args) self.label.update_idletasks() def clear(self): self.label.config(text="") self.label.update_idletasks() class SimplePlot(Tkinter.Frame): "Creates a simple plot frame of time<10 and V<5 of pixel size wxh" def __init__(self,parent,w,h): #this line was taken from online... not sure why it works, #but it allows packing outside of this __init__ Tkinter.Frame.__init__(self, parent) self.parent = parent self.canvas = Tkinter.Canvas(parent,width=w,height=h) #frame height in pixels self.canvas.h = h #frame width in pixels self.canvas.w = w self.canvas.pack(fill=Tkinter.X) #draw gridlines self.gridon() def gridon(self): "Draws gridlines on the plot at every 1 unit" for i in range(100,self.canvas.w,100): self.canvas.create_line(i,0,i,self.canvas.h) for i in range(100,self.canvas.h,100): self.canvas.create_line(0,i,self.canvas.w,i) def plot(self, data): "Plots data given as data = [], data.append( (x,y) )" for x, y in data: px = int(x/10*self.canvas.w) py = int(self.canvas.h-y/5*self.canvas.h) self.canvas.create_rectangle((px-1, py-1, px+1, py+1), outline="red") if __name__ == "__main__": root = Tkinter.Tk() root.withdraw() #create main window a = App(root) a.title('Plot') #create a sample data range for testing #data ranges from x=0, y=0 to x=10, y=5 data = [] for i in range(1000): data.append( (float(i)/1000*10,float(i)/1000*5) ) a.plot_data(data) #loop until destroy a.mainloop() From henryar2 at gmail.com Fri Jul 11 11:42:18 2008 From: henryar2 at gmail.com (Henry Read) Date: Fri, 11 Jul 2008 23:42:18 +0800 Subject: Editra In-Reply-To: References: Message-ID: It has been already in wxpython-doc-demos package. On Fri, Jul 11, 2008 at 11:38 PM, Henry Read wrote: > Editra is a multi-platform text editor with an implementation that focuses > on creating an easy to use interface and features that aid in code > development. Currently it supports syntax highlighting and variety of other > useful features for over 60 programming languages. > > Editra is freely available under the terms of the wxWindows Licence. > > > Currently the project is in the alpha development phase but test builds of > "stable" points are available for download and trial as Windows and Mac > OSX(Universal) binaries, currently other Unix and Linux based systems will > have to install from source using the included setup script. Please feel > free give it a try and to report bugs and request features. > > *Editra*.org | News > It is a good editor for Python, also it is small.It can also support auto > completion with Python modules. > It is suitable for Python beginners. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Wed Jul 23 16:30:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 22:30:06 +0200 Subject: fromfile error on windows, not mac In-Reply-To: <50af02ed0807231309p2f7b1333sf45f96a9f082d8f0@mail.gmail.com> References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> <50af02ed0807231309p2f7b1333sf45f96a9f082d8f0@mail.gmail.com> Message-ID: Manu Hack wrote: > by the way, anyone could explain why changing to single quote makes a > difference? > > >>> "rb" == 'rb' > True There's no difference between single quotes and double quotes in Python. My guess is cargo cult debugging. From stefan_ml at behnel.de Fri Jul 25 07:16:02 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 25 Jul 2008 13:16:02 +0200 Subject: lxml, comparing nodes In-Reply-To: References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> <6c91a4da-6443-4570-8dd3-01c4ec169bf3@t54g2000hsg.googlegroups.com> <4888ad28$0$9491$9b4e6d93@newsspool3.arcor-online.net> <4613042f-ed70-4cfa-8de9-a92b4df32923@k36g2000pri.googlegroups.com> <4889B2B1.5030204@behnel.de> Message-ID: <4889B5F2.4090605@behnel.de> code_berzerker wrote: >> Not in your code. >> >> Stefan > > Not sure what you mean, but I tested and so far every document with > the same order of elements had number of comparisons equal to number > of nodes. Sorry, missed the "let2.remove(foundEl)" line. Stefan From aahz at pythoncraft.com Sat Jul 26 11:28:21 2008 From: aahz at pythoncraft.com (Aahz) Date: 26 Jul 2008 08:28:21 -0700 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> Message-ID: In article <5845bf4f-65bf-4a36-b9fe-25cd896b6926 at q28g2000prh.googlegroups.com>, Jordan wrote: > >The point I was trying to make originally was that applying any mantra >dogmatically, including Explicit is better than implicit, can lead to >bad results. Perhaps having Practicality beats purity is enough of a >reminder of that fact for the Python community :-) IMO, you made a big mistake in combining your point with two other meaty issues (whether method definitions should include self and whether != should use __eq__() as a fallback). Moreover, your point is IMO not sufficiently proven (that is, I see little evidence that Python development follows any one point of the Zen of Python dogmatically). You should therefore not be particularly surprised that the discussion has gone sideways to your intentions -- especially when you start with a flamebait Subject: line of "attacking sacred cows"! If solid discussion is your goal, I suggest that you wait a couple of weeks and start over with a brand-new thread. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From giltay at gmail.com Wed Jul 30 10:00:27 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Wed, 30 Jul 2008 07:00:27 -0700 (PDT) Subject: iterating "by twos" References: <70a172ac-0491-4918-9c74-6a577f35068a@d45g2000hsc.googlegroups.com> Message-ID: <0e10dfb8-b1f7-4318-8244-7a0af7021b52@27g2000hsf.googlegroups.com> On Jul 29, 4:11?pm, Erik Max Francis wrote: > gil... at gmail.com wrote: > > for x, y in zip(a, a[1:]): > > ? ? frob(x, y) > > What you meant was this: > > ?>>> [(x, y) for x, y in zip(a[::2], a[1::2])] > [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] > > but this creates three sublists through slicing and zip. ?The use of > islice and izip is better, particularly if the list that's being > iterated over is large. The lists I use it with are generally pretty small (a few thousand items at most) so I decided to go with simple rather than clever. That said, I use it enough that it should become its own function, at which point I'll probably grab something from this thread. Cheers, Geoff G-T From deets at nospam.web.de Wed Jul 9 11:48:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Jul 2008 17:48:00 +0200 Subject: Anyone happen to have optimization hints for this loop? References: <32fd142e-b198-430e-888b-01aee4e63ac0@c65g2000hsa.googlegroups.com> Message-ID: <6dk4v0F311k1U1@mid.uni-berlin.de> dp_pearce wrote: > I have some code that takes data from an Access database and processes > it into text files for another application. At the moment, I am using > a number of loops that are pretty slow. I am not a hugely experienced > python user so I would like to know if I am doing anything > particularly wrong or that can be hugely improved through the use of > another method. > > Currently, all of the values that are to be written to file are pulled > from the database and into a list called "domainVa". These values > represent 3D data and need to be written to text files using line > breaks to seperate 'layers'. I am currently looping through the list > and appending a string, which I then write to file. This list can > regularly contain upwards of half a million values... > > count = 0 > dmntString = "" > for z in range(0, Z): > for y in range(0, Y): > for x in range(0, X): > fraction = domainVa[count] > dmntString += " " > dmntString += fraction > count = count + 1 > dmntString += "\n" > dmntString += "\n" > dmntString += "\n***\n > > dmntFile = open(dmntFilename, 'wt') > dmntFile.write(dmntString) > dmntFile.close() > > I have found that it is currently taking ~3 seconds to build the > string but ~1 second to write the string to file, which seems wrong (I > would normally guess the CPU/Memory would out perform disc writing > speeds). > > Can anyone see a way of speeding this loop up? Perhaps by changing the > data format? Is it wrong to append a string and write once, or should > hold a file open and write at each instance? Don't use in-place adding to concatenate strings. It might lead to quadaratic behavior. Use the "".join()-idiom instead: dmntStrings = [] .... dmntStrings.append("\n") .... dmntFile.write("".join(dmntStrings)) Diez From akathorn at gmail.com Sun Jul 13 22:28:39 2008 From: akathorn at gmail.com (Akathorn Greyhat) Date: Mon, 14 Jul 2008 03:28:39 +0100 Subject: Dictionary bidirectional In-Reply-To: References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> Message-ID: ---------- Forwarded message ---------- From: Akathorn Greyhat Date: 2008/7/14 Subject: Re: Dictionary bidirectional To: Kless 2008/7/14 Kless : I need a dictionary where get the result from a 'key' (on left), but > also from a 'value' (on right), how to get it? > > I know that dictionaries aren't bidirectional, but is there any way > without use two dictionaries? > > > Thanks in advance! > -- > http://mail.python.org/mailman/listinfo/python-list > You could make your own class for that, maybe something like ######### class MyCoolDictionary(dict): def __init__(self, *args, **kargs): dict.__init__(self, *args, **kargs) def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: keys=[] for i in dictio.keys(): if dictio[i]==item: keys.append(i) return keys dictio=MyCoolDictionary({"a" : 1, "b" : 2, "c" : 2}) print dictio["a"] print dictio["b"] print dictio[1] print dictio[2] ######### The output of this code is: 1 2 ['a'] ['c', 'b'] Note that it isn't finish, maybe you'll need to make some kind of test before adding a new value because with this code one value can have multiple keys, and I have fixed it by returning a list of keys instead a single value. It's up to you =) I'm sorry of my poor english =( Regards, Akathorn Greyhat -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Fri Jul 18 19:20:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 18 Jul 2008 16:20:44 -0700 (PDT) Subject: round function error??? References: <2da2f5f1-7ff2-46d7-a768-f0817e414615@f36g2000hsa.googlegroups.com> Message-ID: On Jul 19, 8:05 am, Mark Dickinson wrote: > On Jul 18, 10:17 pm, Anthony wrote: > > > Isn't this a mistake??? > > Which 'this'? That is, what were you expecting? > > If you're objecting to the fact that the second result > produces 3499.3499999999999 instead of 3499.35, then > no, that's not a mistake; see > > http://www.python.org/doc/faq/general/#why-are-floating-point-calcula... > > for more information. But I'm guessing that you're > questioning the fact that a value that's apparently > *less* than 3499.35 is rounded up to 3499.4, rather > than down to 3499.3. ? "apparently" being the operative word. >>> x = 3499.35 >>> repr(x) '3499.3499999999999' >>> float(repr(x)) == x True >>> float(repr(x)) < x False > > Then yes, I'd agree that's less than ideal, though I > don't consider it a particularly serious bug. > It's been on my list of things to fix for a while. I'd suggest adding this to the list of floating point strangenesses in the FAQ and/or the appendix to the tutorial, rather than "fixing" it. > (See http://bugs.python.org/issue1869). The example you give there seems to be somewhat more deserving of a fix. Cheers, John From drakonik at gmail.com Thu Jul 24 22:03:24 2008 From: drakonik at gmail.com (Nick Dumas) Date: Thu, 24 Jul 2008 22:03:24 -0400 Subject: import dll instead of pyd In-Reply-To: <68310600-2efd-4f52-81d7-d0f3b40c7809@h17g2000prg.googlegroups.com> References: <68310600-2efd-4f52-81d7-d0f3b40c7809@h17g2000prg.googlegroups.com> Message-ID: <6O2dnfUikbwXqRTVnZ2dnUVZ_j2dnZ2d@earthlink.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Is this DLL in the same directory as your script? If not, is it part of your pythonpath? If neither are true, then you won't be able to import it, regardless of whether it's a good file or not. jrh wrote: > Hello, > > From previous posts and documentation it seems python should be able > to import a module that is compiled into a .dll just as well as > a .pyd. I have a pyd that works fine, but after renaming it to dll the > import fails. Running python with -vv flag indicates it doesn't > actually look for the dll (see below). Has dll import been defeatured > in python? > > Thanks! > >>>> import _mydllpythonmodule > # trying _mydllpythonmodule.pyd > # trying _mydllpythonmodule.py > # trying _mydllpythonmodule.pyw > # trying _mydllpythonmodule.pyc > # trying C:\Python25\DLLs\_mydllpythonmodule.pyd > # trying C:\Python25\DLLs\_mydllpythonmodule.py > # trying C:\Python25\DLLs\_mydllpythonmodule.pyw > # trying C:\Python25\DLLs\_mydllpythonmodule.pyc > # trying C:\Python25\lib\_mydllpythonmodule.pyd > # trying C:\Python25\lib\_mydllpythonmodule.py > # trying C:\Python25\lib\_mydllpythonmodule.pyw > # trying C:\Python25\lib\_mydllpythonmodule.pyc > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyd > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.py > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyw > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyc > # trying C:\Python25\_mydllpythonmodule.pyd > # trying C:\Python25\_mydllpythonmodule.py > # trying C:\Python25\_mydllpythonmodule.pyw > # trying C:\Python25\_mydllpythonmodule.pyc > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyd > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.py > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyw > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyc > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyd > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.py > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyw > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyc > # trying C:\Python25\lib\site-packages\win32\lib > \_mydllpythonmodule.pyd > # trying C:\Python25\lib\site-packages\win32\lib\_mydllpythonmodule.py > # trying C:\Python25\lib\site-packages\win32\lib > \_mydllpythonmodule.pyw > # trying C:\Python25\lib\site-packages\win32\lib > \_mydllpythonmodule.pyc > # trying C:\Python25\lib\site-packages\Pythonwin > \_mydllpythonmodule.pyd > # trying C:\Python25\lib\site-packages\Pythonwin\_mydllpythonmodule.py > # trying C:\Python25\lib\site-packages\Pythonwin > \_mydllpythonmodule.pyw > # trying C:\Python25\lib\site-packages\Pythonwin > \_mydllpythonmodule.pyc > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named _mydllpythonmodule -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkiJNGwACgkQLMI5fndAv9hykgCcDf4cTZU0iDo+ELQ5aFGs9FIO 8GEAn3+egrPDtNrlbsssqti8YeZXXIeM =q31k -----END PGP SIGNATURE----- From tjreedy at udel.edu Sun Jul 27 21:22:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 21:22:41 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> Message-ID: Russ P. wrote: > When I write a function in which a data member will be used several > times, I usually do something like this: > > data = self.data > > so I can avoid the clutter of repeated use of "self.data". Another reason people do this is for speed, even if self.data is used just once but in a loop. From gherron at islandtraining.com Mon Jul 21 16:44:38 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 21 Jul 2008 13:44:38 -0700 Subject: Converting List of String to Integer In-Reply-To: References: Message-ID: <4884F536.5060307@islandtraining.com> Samir wrote: > On Jul 21, 3:20 pm, Gary Herron wrote: > >> Samir wrote: >> >>> Hi Everyone, >>> >>> I am relatively new to Python so please forgive me for what seems like >>> a basic question. >>> >>> Assume that I have a list, a, composed of nested lists with string >>> representations of integers, such that >>> >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] >>> >>> I would like to convert this to a similar list, b, where the values >>> are represented by integers, such as >>> >>> b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] >>> >>> I have unsuccessfully tried the following code: >>> >>> n = [] >>> for k in a: >>> n.append([int(v) for v in k]) >>> print n >>> >>> Does anyone know what I am doing wrong? >>> >>> Thanks in advance. >>> >>> Samir >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> You didn't tell us how it failed for you, so I can't guess what's wrong. >> >> However, your code works for me: >> >> >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] >> >>> n = [] >> >>> for k in a: >> ... n.append([int(v) for v in k]) >> ... >> >>> print n >> [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] >> >> (Although you seem to have confused variables b and n.) >> >> Gary Herron- Hide quoted text - >> >> - Show quoted text - >> > > Hi Gary, > > Thanks for your quick response (and sorry about mixing up b and n). > For some reason, the logic I posted seems to work ok while I'm using > the Python shell, but when used in my code, the program just hangs. > It never outputs the results. Below is the code in its entirety. Is > there a problem with my indendentation? > > Aha. There's the problem, right there in the first line. > a = n = [] > This sets a and n to the *same* empty list. This line creates one empty list and binds both n and a to that list. Note carefully, there is only one empty list here, but it can be accessed under two names Later in your code, for k in a: runs through that list, and n.append(...) append to the end of the same list. Thus the loop never get to the end of the (continually growing) list. Solve it by creating two different empty lists: a = [] n = [] Gary Herron > t = """ > 1 2 > 3 > 4 5 6 > 7 8 9 0 > """ > > d = t.split("\n") > > for x in range(1,len(d)-1): > a.append(d[x].split(" ")) > print a > > for k in a: > n.append([int(v) for v in k]) > > print n > > Thanks again. > > Samir > -- > http://mail.python.org/mailman/listinfo/python-list > From simon at simonwillison.net Wed Jul 30 11:59:16 2008 From: simon at simonwillison.net (Simon Willison) Date: Wed, 30 Jul 2008 08:59:16 -0700 (PDT) Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: <2a703a46-75bc-4228-95d1-05a4e6030b40@f63g2000hsf.googlegroups.com> Message-ID: On Jul 30, 4:43?pm, Paul Boddie wrote: > I can't reproduce this on Python 2.3.6 or 2.4.4 on RHEL 4. Instead, I > get the usual... > > ('CHARACTERS', ) I'm using Python 2.5.1 on OS X Leopard: $ python Python 2.5.1 (r251:54863, Feb 4 2008, 21:48:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin I just tried it out on Python 2.4.2 on an Ubuntu machine and it worked fine! I guess this must be an OS X Python bug. How absolutely infuriating. Thanks, Simon From ggpolo at gmail.com Thu Jul 17 18:18:29 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 17 Jul 2008 19:18:29 -0300 Subject: Using Tcl extensions with Python? In-Reply-To: <6f09cdf7-1156-4f41-af5f-c8e5b99eab2d@b1g2000hsg.googlegroups.com> References: <6f09cdf7-1156-4f41-af5f-c8e5b99eab2d@b1g2000hsg.googlegroups.com> Message-ID: On Thu, Jul 17, 2008 at 6:48 PM, C Martin wrote: > How do you setup a Tcl extension to be accessible through Python? I > understand that I'll have to use native Tcl calls to use it (tk.call() > etc), but I can't figure out where to put the files or how to > initialize them so I can call them. > > The package I would like to use is TkPNG: http://www.muonics.com/FreeStuff/TkPNG/ > You can put them anywhere, but if it is on tcl's auto_path then you just need a call to "package require tkpng". To check what directories are part of auto_path, start tclsh and enter "set auto_path". Follows a sample code to demonstrate how to load the required package: import Tkinter root = Tkinter.Tk() tkpnglib = "/usr/lib/tkpng0.9" root.tk.eval(""" global auto_path lappend auto_path {%s}""" % tkpnglib) root.tk.eval("package require tkpng") If tkpng were installed in some directory belonging to auto_path, then you wouldn't need that call to tk.eval. And.. for tkpng specifically, you won't need tk.call to use it, you just need to create your images using Tkinter.PhotoImage with a "png" type. > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From wuwei23 at gmail.com Tue Jul 15 20:13:24 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 15 Jul 2008 17:13:24 -0700 (PDT) Subject: Suggestion: Python global scope References: Message-ID: Anonymous Bastard wrote: > In Python, declaring a variable using the global statement automatically > makes it available in all subsequent scopes. > > But to me, it makes more sense to use the global statement to 'import' a > variable from the global scope into the current scope. My understanding is that this is exactly what the 'nonlocal' keyword in Python 3.0 provides. http://www.python.org/dev/peps/pep-3104/ From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 12:24:50 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 18:24:50 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <3d56ad67-bcd7-4840-979a-8648292afcff@j7g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <40449826-c71d-4c6e-8b74-13069269e5da@z6g2000pre.googlegroups.com> <488896bf$0$3493$426a74cc@news.free.fr> <3d56ad67-bcd7-4840-979a-8648292afcff@j7g2000prm.googlegroups.com> Message-ID: <4888c8cc$0$7205$426a74cc@news.free.fr> Jordan a ?crit : >> Then why do you write, let me quote: >> >> """ >> (snip) coding __eq__ (snip) buys you >> nothing from the != operator. != isn't (by default) a synonym for the >> negation of == (unlike in, say, every other language ever); not only >> will Python let you make them mean different things, without >> documenting this fact - it actively encourages you to do so. >> """ > > My words aren't as clear as they should be. I mean that Python lets > *you* do something without documenting, or rather stating to use a > better term, that your intention is the non-obvious one. > I'm not > saying that Python itself lacks documentation for its own behaviour; > I'm saying it should force you to make your intentions clear and > visible to someone reading your code when you want to do something non- > obvious. One could then answer than, the behaviour of __eq__ / __ne__ being clearly defined and documented, implementing one without the other - or in such a way that a != b is different from not(a == b) - is by itself an explicit 'statement of intention' !-) (snip strawmens) >> Please understand that I'm not arguing about this particular design >> choice (and FWIW, I'd mostly agree on the point that having a != b >> different from not (a == b) is actually a wart). > > Good, at least we've come to a point in this discussion where I can > firmly agree with somebody. On that concrete case, a priori, yes. wrt/ the 'explicit self', there are in fact two points: 1/ The mandatory use of 'self' to access the current instance. As far as I'm concerned, and *even if there was no other technical reasons*, I wholefully, happily and definitively agree with this choice - specially in a language like Python (it's not quite the same problem with Java where you just can't put anything outside a class). It's truly (and IMHO, of course) a case where explicit-is-better-than-implicit, period. Strange enough, I never heard of anyone complaining about the mandatory use of $this-> in PHP. Nor about the mandatory use of @/@@ in Ruby. Nor about the 'm_whatever' naming convention in C++. Nor about [add your own example here]. 2/ The need to explicitely declare the 'target' object (self or cls) as first param of a 'function-to-be-used-as-method'. Granted, this one may feel a bit "unfinished" at first. And I would not bet my life on it, but I think one could possibly find some "solution" that would not as a side-effect impose any restriction wrt/ the current implementation. OTHO, given 1/, and since the way Python builds "methods" out of just two more general constructs (the def statement and the descriptor protocol) is part of what makes it's object model so powerful, I don't feel like the price to pay to keep the implementation as simple as possible is too high. IOW, while I would not turn down a "solution" like the one mentionned above (let's say -0 as far as I'm concerned), I just don't think it would be worth the time spent. Anyway, "explicit is better than implicit" is not the appropriate dogmatic justification here - but a couple other quotes from the Python's Zen could apply (left as an exercice to the reader) !-) From robert.kern at gmail.com Mon Jul 7 20:09:41 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 07 Jul 2008 19:09:41 -0500 Subject: Python Agile Software Development Tools Screencasts In-Reply-To: <87lk0dwbys.fsf@benfinney.id.au> References: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> <87lk0dwbys.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > percious writes: > >> Hi All, >> >> I started a new series about python on showmedo. Please feel free to >> take a look. > > I'd love to, but showmedo refuses to show presentations to me without > installing non-free software. mplayer works just fine on the .flv's. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From bronger at physik.rwth-aachen.de Sat Jul 26 10:25:18 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 26 Jul 2008 16:25:18 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> Message-ID: <87k5f8afjl.fsf@physik.rwth-aachen.de> Hall?chen! D'Arcy J.M. Cain writes: > On Sat, 26 Jul 2008 09:45:21 +0200 > Torsten Bronger wrote: > >> Of course, "self" would have to become a reserved word. You >> could say that this may break some code, but I don't see much >> freedom > > Isn't this a showstopper all by itself? Yes. But I've seen no code that uses some other word. Emacs' syntax highlighting even treats it as reserved. So I think that other counter-arguments are stronger. The in my opinion strongest one is that automatic insertion of "self" would make Python less verbose but more complicated. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From mdsherry at gmail.com Tue Jul 15 16:39:33 2008 From: mdsherry at gmail.com (mdsherry at gmail.com) Date: Tue, 15 Jul 2008 13:39:33 -0700 (PDT) Subject: bad recursion, still works References: <7bf2bad5-d6b6-4929-a520-a82b7bb49916@34g2000hsf.googlegroups.com> <5be12739-7896-4112-9307-53897af4f691@f63g2000hsf.googlegroups.com> Message-ID: <47c4e651-b102-4ec0-907e-fa4712ae5b51@26g2000hsk.googlegroups.com> On Jul 15, 4:12?pm, iu2 wrote: > On Jul 15, 9:30?pm, mdshe... at gmail.com wrote: > > > > > On Jul 15, 2:59?pm, iu2 wrote: > > > > Hi, > > > > I wrote this wrong recursive function that flattens a list: > > > > def flatten(lst, acc=[]): > > > ? ? #print 'acc =', acc, 'lst =', lst > > > ? ? if type(lst) != list: > > > ? ? ? ? acc.append(lst) > > > ? ? else: > > > ? ? ? ? for item in lst: > > > ? ? ? ? ? ? flatten(item) > > > ? ? return acc > > > > a = [1, 2, [3, 4, 5], [6, [7, 8, [9, 10], 11], 12], 13, 14] > > > b = flatten(a) > > > print b > > > > I was amazed to realize that it flattens the list alright. Why? 'acc' > > > should be an empty list on each invocation of flatten, but is seems to > > > accumulate anyway... > > > When you say acc=[] in the function declaration, it binds acc to a > > particular list object, rather than to a concept of an empty list. > > Thus, all operations being performed on acc are being performed on the > > same list. If, after the sample code you provided, were to call > > > c = flatten([15,16,17,[18,19]]) > > print c > > > you would get back the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, > > 13, 14, 15, 16, 17, 18, 19]. > > > Mark Sherry > > I still don't understand: In each recursive call to flatten, acc > should be bound to a new [], shouldn't it? Why does the binding happen > only on the first call to flatten? Default values are bound when the function is defined, not when it's called. For example, >>> import random >>> def foo(bar = random.random()): ... print bar ... >>> foo() 0.632312549821312 >>> foo() 0.632312549821312 If you view [...] just as shorthand for list(...), it might make a bit more sense. For immutable values, one can't change the value bound to the name, only what the name is bound to, so this behaviour is less obvious. But still there. As to why default values are evaluated at define time vs. call time, I'd argue reasons of scope and speed - if the default value is a computed constant, it makes little sense to recompute it every time the function is called. Mark Sherry From fredrik at pythonware.com Sat Jul 19 14:58:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 19 Jul 2008 20:58:25 +0200 Subject: XML Parsing: Expat Error In-Reply-To: <0FF698F7C0354F42987734704458117F015DD7F0@EVS3.rose-hulman.edu> References: <0FF698F7C0354F42987734704458117F015DD7F0@EVS3.rose-hulman.edu> Message-ID: Gerth, William D wrote: > Hey all, I?m simply trying to get my feet wet with XML parsing, and I > tried to just do something simple with ElementTree, just throw the XML > tags from a file into a list. The code is as follows (and may be wrong): ... > xml.parsers.expat.ExpatError: no element found: line 3, column 0 > > What can I do to fix this, if anything? My overall goal has been to > simply get the text of the XML document into a text file, but even that > has failed (I get naught but gibberish), so any help would be appreciated. your XML file is broken (note that it's the "parse" function that throws this error). From lanny at freshells.ch Wed Jul 23 21:52:10 2008 From: lanny at freshells.ch (Lanny) Date: Wed, 23 Jul 2008 18:52:10 -0700 Subject: os.walk question Message-ID: How would one make a list of the files in the top directory using os.walk. I need to pick a random file from said list. Thanks. -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- From tjreedy at udel.edu Tue Jul 1 15:14:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 01 Jul 2008 15:14:15 -0400 Subject: Implementing an 8 bit fixed point register In-Reply-To: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> References: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> Message-ID: nickooooola wrote: > Hello to all > I'm about to write a simulator for a microcontroller in python > (why python? because I love it!!!) > > but I have a problem. > > The registry of this processor are all 8 bit long (and 10 bit for some > other strange register) > and I need to simulate the fixed point behaviour of the register, > and to access the single bit. In Python3, I would use a (mutable) bytearray. IDLE 3.0b1 >>> reg1 = bytearray((0,)*8) # or *10 for 10 bits >>> reg1 bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00') >>> reg1[1]=1 >>> reg1[1] 1 >>> tuple(reg1) (0, 1, 0, 0, 0, 0, 0, 0) A bytearray subclass could enforce that all 'bits' (stored as bytes) are 0 or 1, have a customized representation to your taste, and add methods like .flipall(). The overhead of using 8 bytes instead of 1 to hold the object value is actually small compared to the minimum object size of 16 bytes (on Win32XP). >>> sys.getsizeof(reg1) 24 In Python2.x, you can use the array module to make equivalent mutable arrays of chars. Terry Jan Reedy From drakonik at gmail.com Fri Jul 18 10:35:12 2008 From: drakonik at gmail.com (Nick Dumas) Date: Fri, 18 Jul 2008 10:35:12 -0400 Subject: Regular expression help In-Reply-To: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> References: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I think you're over-complicating this. I'm assuming that you're going to do a line graph of some sorta, and each new line of the file contains a new set of data. The problem you mentioned with your regex returning a match object rather than a string is because you're simply using a re function that doesn't return strings. re.findall() is what you want. That being said, here is working code to mine data from your file. [code] line = 'c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 mad=-3.597647 3pv=0' energypat = r'\betot=(-?\d*?[.]\d*)' #Note: To change the data grabbed from the line, you can change the #'etot' to 'afrac' or 'emad' or anything that doesn't contain a regex #special character. energypat = re.compile(energypat) re.findall(energypat, line)# returns a STRING containing '-12.020107' [/code] This returns a string, which is easy enough to convert to an int. After that, you can datapoints.append() to your heart's content. Good luck with your work. nclbndk759 at googlemail.com wrote: > Hello, > > I am new to Python, with a background in scientific computing. I'm > trying to write a script that will take a file with lines like > > c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647 > 3pv=0 > > extract the values of afrac and etot and plot them. I'm really > struggling with getting the values of efrac and etot. So far I have > come up with (small snippet of script just to get the energy, etot): > > def get_data_points(filename): > file = open(filename,'r') > data_points = [] > while 1: > line = file.readline() > if not line: break > energy = get_total_energy(line) > data_points.append(energy) > return data_points > > def get_total_energy(line): > rawstr = r"""(?P.*?)=(?P.*?)\s""" > p = re.compile(rawstr) > return p.match(line,5) > > What is being stored in energy is '<_sre.SRE_Match object at > 0x2a955e4ed0>', not '-11.020107'. Why? I've been struggling with > regular expressions for two days now, with no luck. Could someone > please put me out of my misery and give me a clue as to what's going > on? Apologies if it's blindingly obvious or if this question has been > asked and answered before. > > Thanks, > > Nicole -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkiAqiAACgkQLMI5fndAv9h7HgCfU6a7v1nE5iLYcUPbXhC6sfU7 mpkAn1Q/DyOI4Zo7QJhF9zqfqCq6boXv =L2VZ -----END PGP SIGNATURE----- From rocksportrocker at googlemail.com Thu Jul 17 08:04:52 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 17 Jul 2008 05:04:52 -0700 (PDT) Subject: storing references instead of copies in a dictionary References: Message-ID: <19eba037-f7e2-4934-a03b-f1956db8e999@a1g2000hsb.googlegroups.com> On 17 Jul., 13:45, mk wrote: > Hello everyone, > > I'm storing functions in a dictionary (this is basically for cooking up > my own fancy schmancy callback scheme, mainly for learning purpose): > > ?>>> def f2(arg): > ... ? ? return "f2 " + arg > ... > ?>>> > ?>>> def f1(arg): > ... ? ? return "f1" + arg > ... > > ?>>> a={'1': f1, '2': f2} > ?>>> > ?>>> [ x[1](x[0]) for x in a.items() ] > ['f11', 'f2 2'] > > Well, neat. Except if I change function definitions now, old functions > are called. And rightly: > > {'1': , '2': } > ?>>> f1 > > ?>>> > ?>>> def f1(arg): > ... ? ? return "NEW f1 " + arg > ... > ?>>> f1 > > > The address of function f1 has obviously changed on redefinition. > > Storing value copies in a dictionary on assignment is a reasonable > default behaviour. > > However, in this particular case I need to specifically store > _references to objects_ (e.g. f1 function), or should I say _labels_ > (leading to objects)? > > Of course, I can basically update the dictionary with a new function > definition. > > But I wonder, is there not a way _in general_ to specifically store > references to functions/variables/first-class objects instead of copies > in a dictionary? Python stores references in dictionaries and does not copy ! (unless you explicitly use the copy module) ! In your case the entry in the dictionary is a reference to the same object which f1 references, that is the object at 0xb7f0ba04. If you now say "f1=...:" then f1 references a new object at 0xb7f0b994, and the entry in your dictionary still references the "old" object at 0xb7f0ba04. I do not know any method to automatically update your dictionary as there is no possibility to overload the assignement operator "=". But may be somebody can teach me a new trick :-) Greetings, Uwe From cjstuttle at hotmail.com Sat Jul 26 17:16:33 2008 From: cjstuttle at hotmail.com (chris) Date: Sat, 26 Jul 2008 14:16:33 -0700 (PDT) Subject: pixel colour on screen References: Message-ID: <22940391-cf14-4022-8b00-8d7974590072@e39g2000hsf.googlegroups.com> On Jun 30, 4:37?am, Tim Roberts wrote: > cjstut... at hotmail.com wrote: > > >Could anyone help me, I'm a python noob and need some help. im trying > >to find some code that will, given ascreenco-ordinate, will give me > >thecolourof thatpixelin RGB. i have found a lot about getting the > >pixelcolourfrom a picture file with a given co-ordinate, but is it > >possible to do it from the wholescreenoutput regardless what > >application the selectedpixelis in? > > Which operating system? ?If you are on Windows, and you have pywin32 > loaded. you can use the Windows APIs GetDC and GetPixel. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. i have ubuntu hardy. does that help? From weihao89 at gmail.com Thu Jul 24 17:19:41 2008 From: weihao89 at gmail.com (Wei Hao) Date: Thu, 24 Jul 2008 17:19:41 -0400 Subject: Question about optimization Message-ID: Hi: I'm pretty new to python and I have some optimization issues. I'll show you the piece of code which is causing it, with pseudo-code before it and comments. I'm accessing a gigantic table (like 15 million rows) in SQL. d is some dictionary, r is a precompiled regex string Big loop, so I search through the table in chunks given by delta SQL query ("select * from table where rowID >= n and rowID < (n + delta)"), result of query stored in a. Each individual row is a[n1], columns of rows are a[n1][n2]. t1 = time.clock() #to track speed for m in a: for temp in m: if str(temp) == "None": #basically skip over the columns that are null for this particular row continue s += temp #get the columns into one long string s = s.replace("between", "") s = s.replace("and", "") s = s.replace("where", "") s = s.replace("like", "") #these words cause problems, need to get rid of them. b = re.findall(r,s) #looking for the stuff I want, always at least one per row of table, about 3-4 on average. for t in b: #store count of things I want in dictionary if t in d: d[t] += 1 else: d[t] = 1 print n, (time.clock()-t1) #to track speed I am 100% sure it's this code snippet that's the cause of my problems. Here's what I can tell you. Each chunk of rows that I grab is essentially equal in size (rowID skips over stuff, but rather arbitrarily). The time it takes to fetch the SQL query doesn't change. But as the program progresses, this snippet gets slower. Here's the output: 2500 0.441551299341 5000 1.26162739664 7500 2.35092688403 10000 3.48417469666 12500 4.59031305491 15000 5.78972588775 17500 6.28305527139 20000 6.73344570903 22500 8.31732146487 25000 9.65322872159 27500 8.98186042757 30000 11.8042818095 32500 12.1965593712 35000 13.2735763291 37500 14.0282617344 What is it in the code snippet that slows down as n increases? Is there something about the way low level python functions I don't understand which is slowing me down? Thanks in advance for your time. -Wei -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Wed Jul 23 18:31:21 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 24 Jul 2008 00:31:21 +0200 Subject: Undocumented Python 2.6 change: Py_None vs NULL when C implementation raises exception In-Reply-To: References: Message-ID: <4887b13a$0$7677$9b622d9e@news.freenet.de> Heikki Toivonen wrote: > I was debugging M2Crypto function written in C which changed behavior > between Python 2.6 and earlier Python versions. In an error condition > the function was supposed to raise exception type A, but with 2.6 it > raised type B, and further, there was no string value for the exception. > > I tracked this down to the C code incorrectly returning Py_None when it > should have returned NULL. Changing the C code to return NULL made it > behave correctly in 2.6. Can you please be specific what function you are talking about? > I don't know how common a mistake it is to return Py_None when NULL > should have been returned, but it might be worth a note in the list of > changes for 2.6 that this behavior changed, don't you think? Perhaps. OTOH, perhaps the change is completely erroneous. In that case, rather than documenting it, it should be reverted. Unfortunately, as you keep the specific issue secret, none of this will happen, as we have no clue what you are talking about. I'm sure there are tons of silent changes, in this release, all past releases, and all future releases, not only in Python, but in any software. Regards, Martin From mattheww at chiark.greenend.org.uk Tue Jul 29 15:30:11 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 29 Jul 2008 20:30:11 +0100 (BST) Subject: Where is the documentation for psycopg2? References: Message-ID: kj wrote: > Hi. I can't find any documentation for psycopg2. > > I'm a noob, so I'm sure I'm just not looking in the right place... > > Anybody know where it is? For basic use, psycopg2 follows the dbapi, which is described in http://www.python.org/dev/peps/pep-0249/ Additional features are described in doc/extensions.rst in the psycopg2 tarball. This leaves a gap for documentation of the basic features which the dbapi doesn't nail down (in particular, connecting to a database in the first place). I don't think there is any proper documentation covering this, but the scripts in examples/ (particularly simple.py) should make it reasonably clear. -M- From samwyse at gmail.com Wed Jul 9 15:29:00 2008 From: samwyse at gmail.com (samwyse) Date: Wed, 9 Jul 2008 12:29:00 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> Message-ID: <1343fa73-fd32-46c3-8a75-0efc85b2660e@a70g2000hsh.googlegroups.com> On Jul 8, 11:01?am, Kris Kennaway wrote: > samwyse wrote: > > You might want to look at Plex. > >http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/ > > > "Another advantage of Plex is that it compiles all of the regular > > expressions into a single DFA. Once that's done, the input can be > > processed in a time proportional to the number of characters to be > > scanned, and independent of the number or complexity of the regular > > expressions. Python's existing regular expression matchers do not have > > this property. " > Hmm, unfortunately it's still orders of magnitude slower than grep in my > own application that involves matching lots of strings and regexps > against large files (I killed it after 400 seconds, compared to 1.5 for > grep), and that's leaving aside the much longer compilation time (over a > minute). ?If the matching was fast then I could possibly pickle the > lexer though (but it's not). That's funny, the compilation is almost instantaneous for me. However, I just tested it to several files, the first containing 4875*'a', the rest each twice the size of the previous. And you're right, for each doubling of the file size, the match take four times as long, meaning O(n^2). 156000*'a' would probably take 8 hours. Here are my results: compile_lexicon() took 0.0236021580595 secs test('file-0.txt') took 24.8322969831 secs test('file-1.txt') took 99.3956799681 secs test('file-2.txt') took 398.349623132 secs And here's my (probably over-engineered) testbed: from __future__ import with_statement from os.path import exists from timeit import Timer from Plex import * filename = "file-%d.txt" def create_files(n): for x in range(0,n): fname = filename % x if not exists(fname): print 'creating', fname with open(fname, 'w') as f: print >>f, (4875*2**x)*'a', def compile_lexicon(): global lexicon lexicon = Lexicon([ (Rep(AnyBut(' "='))+Str('/'), TEXT), (AnyBut('\n'), IGNORE), ]) def test(fname): with open(fname, 'r') as f: scanner = Scanner(lexicon, f, fname) while 1: token = scanner.read() #print token if token[0] is None: break def my_timed_test(func_name, *args): stmt = func_name + '(' + ','.join(map(repr, args)) + ')' t = Timer(stmt, "from __main__ import "+func_name) print stmt, 'took', t.timeit(1), 'secs' if __name__ == '__main__': create_files(6) my_timed_test('compile_lexicon') for x in range(0,4): my_timed_test('test', filename%x) From david.lyon at preisshare.net Tue Jul 15 07:46:36 2008 From: david.lyon at preisshare.net (David Lyon) Date: Tue, 15 Jul 2008 21:46:36 +1000 Subject: Python embedding question. In-Reply-To: References: Message-ID: <487C8E1C.7050600@preisshare.net> Thomas Troeger wrote: > I want to embed a Python application on a device with limited > resources, esp. storage limitations. Is there a way to reduce the > Python interpreter to a set of modules that's urgently needed? Of course there is. What is the target platform ? What can be done is to go through the python source code and comment out everything that *you* find unneccessary. I can't tell you what this would be - because I don't know exactly what you are after. But to your question - the answer is yes.. of course. > Or is there a method to have gzipped modules that are unzipped on the > fly into memory when they're accessed? That would be even better. Yes - also possible. > > Additionally, is there a Python module that contains all the stuff > needed for an embedded application like graphics, sound etc. No. Because that depends on what hardware platform you want to run on. > or do I have to use the various bindings to libraries like cairo, Qt > or similar? Is there a site that helps with those decisions? I doubt it. These are decisions for you to make according to the limitations of your hardware. > > I've really looked at a lot of places but haven't found a suitable > solutions yet, so I'm asking here in hope that someone has experience > with that topic. > :-) Regards David From dullrich at sprynet.com Fri Jul 25 11:42:58 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 25 Jul 2008 10:42:58 -0500 Subject: repr(string) References: Message-ID: In article , MRAB wrote: > On Jul 23, 4:04?pm, "David C. Ullrich" wrote: > > I've been saving data in a file with one line per field. > > Now some of the fields may become multi-line strings... > > > > I was about to start escaping and unescaping linefeeds > > by hand, when I realized that repr() and eval() should > > do. Hence the question: If s is a string, is repr(s) > > guaranteed not to contain line breaks? > > > Might I suggest you use encode and decode instead? Ah, you certainly might! Seems exactly right, thanks. Many years ago I thought I had some idea of what was available in Python - these days it's full of all this neat stuff I never heard of... > >>> 'first line\nsecond line'.encode('string-escape') > 'first line\\nsecond line' > >>> _.decode('string-escape') > 'first line\nsecond line' > >>> u'first line\nsecond line'.encode('unicode-escape') > 'first line\\nsecond line' > >>> _.decode('unicode-escape') > u'first line\nsecond line' -- David C. Ullrich From victorsubervi at gmail.com Tue Jul 29 09:06:48 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 29 Jul 2008 15:06:48 +0200 Subject: Windows Interpreter Message-ID: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> Hi: I would like to make my windows python interpreter work like my linux one. I want to be able to cut and paste multiple lines of code. Now I can only paste one line at a time. I do not want it to indent automatically. How can I change this? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From HeinTest at web.de Thu Jul 10 11:32:34 2008 From: HeinTest at web.de (=?ISO-8859-1?Q?Hans_M=FCller?=) Date: Thu, 10 Jul 2008 17:32:34 +0200 Subject: Smal question In-Reply-To: References: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> Message-ID: <48762b92$0$11102$8e6e7893@newsreader.ewetel.de> Thanks a lot, you made my day. As often in python, it's really simple and useful ! Greetings Hans From Lie.1296 at gmail.com Sat Jul 26 05:35:57 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 26 Jul 2008 02:35:57 -0700 (PDT) Subject: Insert character at a fixed position of lines References: Message-ID: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> On Jul 26, 2:41?pm, "Francesco Pietra" wrote: > How to insert letter "A" on each line (of a very long list of lines) > at position 22, i.e., one space after "LEU", leaving all other > characters at the same position as in the original example: > > ATOM ? ? ?1 ?N ? LEU ? ? 1 ? ? 146.615 ?40.494 103.776 ?1.00 73.04 ? ? ? 1SG ? 2 > > In all lines"ATOM" is constant as to both position and string, while > "LEU" is constant as to position only, i.e., "LEU" may be replaced by > three different uppercase letters. Therefore, the most direct > indication would be position 22. > > Should the script introduce blank lines, no problem. That I know how > to correct with a subsequent script. > > Thanks > chiendarret If you want to leave the rest of the strings as-is (i.e. the letter A overwrites whatever on position 22), Peter's code need to be modified a little: line = line[:22] + " " + line[23:] From diordna at gmail.com Mon Jul 28 13:38:43 2008 From: diordna at gmail.com (Stephen Johnson) Date: Mon, 28 Jul 2008 13:38:43 -0400 Subject: python lists and newline character In-Reply-To: <053101c8f0d7$ebd7c340$a601a8c0@office.ipglobal.net> References: <053101c8f0d7$ebd7c340$a601a8c0@office.ipglobal.net> Message-ID: <46AF4AD1-8622-4E7E-BF26-6DECC0B5BF37@gmail.com> domain.strip() Assuming domain is the string with the newline. -Steve Johnson On Jul 28, 2008, at 1:32 PM, Support Desk wrote: > Hello all, > I am using os.popen to get a list returned of vpopmail > users, something like this > > x = os.popen('/home/vpopmail/bin/vuserinfo -n -D > mydomain.com).readlines() > > x returns a list, of usernames, and I am trying to append the > usernames with the domain like so > > for line in x: > print line + ?@? + domain > > but instead of getting > > user at domain.com > > im getting a newline character like: > user > @domain.com > User > @comain.com > User2 > @domain.com > > > Is there some way I can get this list without the newline characters > being added. or somehow remove the newline characters. Any help > would be appreciated. > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From dullrich at sprynet.com Tue Jul 29 11:40:39 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 29 Jul 2008 10:40:39 -0500 Subject: multiple inheritance and __getattr__ References: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> <488e2e70$0$29472$426a74cc@news.free.fr> Message-ID: In article <488e2e70$0$29472$426a74cc at news.free.fr>, Bruno Desthuilliers wrote: > Enrico a ?crit : > > Hi there, > > I have the following situation (I tryed to minimize the code to concentrate > > on the issue): > > > >>>> class A(object): > > def __getattr__(self, name): > > print 'A.__getattr__' > > if name == 'a': return 1 > > raise AttributeError('%s not found in A' % name) > > > >>>> class B(object): > > def __getattr__(self, name): > > print 'B.__getattr__' > > if name == 'b': return 1 > > raise AttributeError('%s not found in B' % name) > > > > Both classes have a __getattr__ method. > > Now I want to have a class that inherits from both so I write: > > > >>>> class C(B,A): > > pass > > > > The problem arise when I try something like this: > >>>> c=C() > >>>> c.a > > A.__getattr__ > > 1 > >>>> c.b > > A.__getattr__ > > > > Traceback (most recent call last): > > File "", line 1, in > > c.b > > File "", line 5, in __getattr__ > > raise AttributeError('%s not found in A' % name) > > AttributeError: b not found in A > > That's what I would have expected. > > > I was expecting, after a fail in A.__getattr__, a call to the __getattr__ > > method of B but it seems that after A.__getattr__ fails the exception stops > > the flow. > > Indeed. You explicitely raise, so the lookup stops here. ??? Surely the reason the lookup stops there is that a __getattr__ was _found_. In the code below the lookup is not continuing, there's a _second_ lookup started by the request for super.__getattr__. > You'd need to > explicitely call on superclass instead to have B.__getattr__ called, ie: > > class A(object): > def __getattr__(self, name): > if name == 'a': > return 1 > return super(A, self).__getattr__(name) > > class B(object): > def __getattr__(self, name): > if name == 'b': > return 2 > return super(B, self).__getattr__(name) > > class C(A, B): > pass > -- David C. Ullrich From paddy3118 at googlemail.com Tue Jul 22 16:21:34 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 22 Jul 2008 13:21:34 -0700 (PDT) Subject: software engineering foundations? References: Message-ID: <776bfd4d-a9c7-42f7-936f-967f58e7362d@59g2000hsb.googlegroups.com> On Jul 22, 7:52?pm, s... at pobox.com wrote: > Sorry for the off-topic-ish post. ?My son (a fairly junior sysadmin type) > mentioned to me today that he was looking for online courses for Perl. ?(I > don't hold that against him. ?Perl is still a lingua franca in the sysadmin > realm.) ?In my work I have from time-to-time had to pick up and maintain > scripts (generally shell/Python stuff) which non-professional programmers > have written. ?It's never what you would call a "pleasant" task. > > There are software construction skills which are entirely distinct from the > language in which you are programming. ?We can tout object-oriented, > structured programming, test-driven development or other software > engineering techniques, but there is a body of knowledge out there which is > orthogonal to the language in which the code is written. ?People who are not > professional programmers often lack those skills and their code shows it. > > Are there any good online resources for this "software structure" axis? > Googling for "object oriented programming tutorial" yields a bunch of stuff, > much of it language-specific. ?I'm trying to find something a bit more > general than that though. > > I Googled for "software engineering tutorial" as well. ?Most of the early > hits were either inaccessible (ACM subscription only) or contents-like stuff > (conference announcements, for example). ?Number eight on the list was this > rather promising page: > > ? ?http://www.cmcrossroads.com/bradapp/links/swe-links.html > > It was last updated over 10 years ago. ?I find it hard to believe that > so little has changed in that time that some other page with more recent > references hasn't percolated to the top of Google's page rank! ?After all, > the Web has grown just a tad in that timeframe. > > I have a sneaking suspicion that what I'm looking for is out there, but that > I'm not asking Google in the right manner. ?Any and all pointers/suggestions > cheerfully accepted. > > Thx, > > -- > Skip Montanaro - s... at pobox.com -http://www.webfast.com/~skip/ > ------ > ELON MUSK: If fuel cells were good, don't think you'd see them somewhere, > like maybe in a laptop or a cell phone or a $200 million military satellite > maybe? ?And yet, where do you see them? > SPENCER MICHELS: You don't. > ELON MUSK: Exactly. Is this the kind of thing you are after? http://www.swc.scipy.org/ "Software Carpentry" Overview Many scientists and engineers spend much of their lives programming, but only a handful have ever been taught how to do this well. As a result, they spend their time wrestling with software, instead of doing research, but have no idea how reliable or efficient their programs are. This course is an intensive introduction to basic software development practices for scientists and engineers that can reduce the time they spend programming by 20-25%. All of the material is open source: it may be used freely by anyone for educational or commercial purposes, and research groups in academia and industry are actively encouraged to adapt it to their needs. - Paddy. From pavlovevidence at gmail.com Wed Jul 30 02:48:07 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 23:48:07 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> <7f4a3d37-e551-4e21-b660-3618016cb67b@z6g2000pre.googlegroups.com> <68448887-4736-4af9-9f27-837bb5312cbd@o40g2000prn.googlegroups.com> Message-ID: <13bad2cb-32ec-4a61-bc44-09f5d6a89416@q5g2000prf.googlegroups.com> On Jul 30, 2:06 am, Erik Max Francis wrote: > Perhaps in the particular use case you're thinking of (numeric types vs. > container types), there aren't any good examples. But who cares? You don't have to. I am trying to set the record straight on just how much polymophism "if x" supports relative to explicit tests, which is to say, not much. BTW, I haven't changed my criteria since I asked for the challenge. Carl Banks From deets at nospam.web.de Mon Jul 28 07:13:41 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 13:13:41 +0200 Subject: Google Group: architectgurus References: Message-ID: <6f5o17F99fqqU1@mid.uni-berlin.de> Gerhard H?ring wrote: > Dear Guru, > > Sudhakar Chavali wrote: >> Hi >> >> I have created a group called architectgurus (http://groups.google.com/ >> group/architectgurus) or architectgurus at googlegroups.com . >> Irrespective of technology, vendor, domain I will be discussing and >> share my thoughts in homogenous and harmonious way. If you are >> interested *even you* can join and contribute your thoughts in this >> group. My intention doing these activities is to spread the knowledge >> and thoughts across the globe. > > What? even me? That's really nice of you. It's amazing - all his thoughts can be summarized in 2 lines of postings + a PDF-link to thoughts of *other* people. Lively discussions are to emerge pretty soon I'm sure.. Diez From scottpig1 at comcast.net Mon Jul 28 21:48:26 2008 From: scottpig1 at comcast.net (pigmartian) Date: Mon, 28 Jul 2008 21:48:26 -0400 Subject: ctypes - unloading implicitly loaded dlls In-Reply-To: References: Message-ID: Nick Craig-Wood wrote: > You could try loading C explicitly with ctypes.LoadLibrary() before > loading A, then you'll have a handle to unload it before you load B. I did think of that, but no luck. Guess the cdll doesn't look for a dll loaded already by python. I guess that does make sense. > I think I'd probably split the code into two or three processes > though. Perhaps use http://pypi.python.org/pypi/processing to > communicate between them. That should get you out of DLL Hell! > (Don't load any of the DLLs before you start the worker processes > off.) That was quite a helpful suggestion, thank you. I had been using the subprocess module actually, but really didn't like that approach. processing is much nicer. Pipes, in particular, is quite handy. ~Scott From gagsl-py2 at yahoo.com.ar Tue Jul 15 03:34:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 04:34:32 -0300 Subject: python mysteriously halts References: <13a33043-21d1-40c0-a938-6e905d958064@m3g2000hsc.googlegroups.com> Message-ID: En Mon, 07 Jul 2008 12:26:28 -0300, Todd escribi?: > On Jul 7, 10:17?am, Tim Golden wrote: >> Todd wrote: >> > I ran a python script last night which connects to a matlab automation >> > server via DCOM (using win32com). ?I expected to see the results when >> > I came in this morning. ?But apparently, not long after I left, python >> > stopped. ?I hit enter in the console, and it started again. >> >> Symptomatically, at least, this can be caused by someone starting to >> select (with the mouse) an area of the screen: the process will pause >> until is pressed, which copies the area to the clipboard. This >> only happens with a console window, but it sounds like that's what >> you had running. > > That might be it, although I don't recall doing that. Fortunately/ > unfortunately, it happened a few times, but it seems to have stopped > now. You could disable that behaviour by unchecking "Quick edit mode" (or something like that) in the Default preferences for the console window. (It's unchecked by default on WinXP and Win2003, I think). -- Gabriel Genellina From pavlovevidence at gmail.com Wed Jul 30 00:28:10 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 21:28:10 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <009fa37d$0$20313$c3e8da3@news.astraweb.com> Message-ID: On Jul 29, 7:30 pm, Steven D'Aprano wrote: > On Tue, 29 Jul 2008 10:30:43 -0700, Carl Banks wrote: > > On Jul 29, 5:15 am, Heiko Wundram wrote: > >> I can't dig up a simple example from code I wrote quickly, but because > >> of the fact that explicit comparisons always hamper polymorphism > > > I'm not going to take your word for it. Do you have code that > > demonstrates how "if x" improves polymorphism relative to simple > > explicit tests? > > On the rapidly decreasing chance that you're not trolling (looking more > and more unlikely every time you post): > > # The recommended way: > if x: > do_something > > # Carl's so-called "simple explicit tests" applied to polymorphic code: No, the following isn't my way. > try: > # could be a sequence or mapping? > # WARNING: must do this test *before* the number test, otherwise > # "if [] != 0" will return True, leading to the wrong branch being > # taken. > if len(x) != 0: > do_something > except AttributeError: > # not a sequence or mapping, maybe it's a number of some sort > try: > int(x) > except TypeError: > # not convertable to numbers > # FIXME: not really sure what to do here for arbitrary types > # so fall back on converting to a boolean, and hope that works > if bool(x): > do_something > else: > if x != 0: > do_something I say that you will never, ever have to do this because there isn't a do_something that's actually useful for all these types. Ok, tell me, oh indignant one, what is do_something? What could possibly be the contents of do_something such that it actually does something useful? If you can tell me what do_something is you will have answered my question. Carl Banks From fredrik at pythonware.com Thu Jul 24 11:35:40 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 17:35:40 +0200 Subject: repr(string) In-Reply-To: References: Message-ID: David C. Ullrich skrev: >> just keep in mind that using eval() on untrusted data isn't a very good >> idea. > > Right. This data comes from me, gets put into a file and then > read by me. Someone _could_ corrupt that file, but someone who > could do that could more easily just throw the machine out > the window... and then your boss finds your program useful, and it's installed on a shared server, and then the guys at the office in Eggkleiva wants a copy, and then people start shipping save files via mail to keep things synchronized, and then someone sets up a web service... ;-) From castironpi at gmail.com Sun Jul 27 14:20:38 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 27 Jul 2008 11:20:38 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> Message-ID: <490769a4-2a48-41dc-a069-2cc003b332a2@b1g2000hsg.googlegroups.com> On Jul 26, 4:08?am, Nikolaus Rath wrote: > Terry Reedy writes: > > Nikolaus Rath wrote: > >> Terry Reedy writes: > >>> Torsten Bronger wrote: > >>>> Hall?chen! > >>> ?> And why does this make the implicit insertion of "self" difficult? > >>>> I could easily write a preprocessor which does it after all. > >>> class C(): > >>> ? def f(): > >>> ? ? a = 3 > > >>> Inserting self into the arg list is trivial. ?Mindlessly deciding > >>> correctly whether or not to insert 'self.' before 'a' is impossible > >>> when 'a' could ambiguously be either an attribute of self or a local > >>> variable of f. ?Or do you and/or Jordan plan to abolish local > >>> variables for methods? > > >> Why do you think that 'self' should be inserted anywhere except in the > >> arg list? AFAIU, the idea is to remove the need to write 'self' in the > >> arg list, not to get rid of it entirely. > > > Because you must prefix self attributes with 'self.'. If you do not > > use any attributes of the instance of the class you are making the > > function an instance method of, then it is not really an instance > > method and need not and I would say should not be masqueraded as > > one. If the function is a static method, then it should be labeled > > as one and no 'self' is not needed and auto insertion would be a > > mistake. In brief, I assume the OP wants 'self' inserted in the body > > because inserting it only in the parameter list and never using it > > in the body is either silly or wrong. > > I think you misunderstood him. What he wants is to write > > class foo: > ? ?def bar(arg): > ? ? ? ?self.whatever = arg + 1 > > instead of > > class foo: > ? ?def bar(self, arg) > ? ? ? ?self.whatever = arg + 1 > > so 'self' should *automatically* only be inserted in the function > declaration, and *manually* be typed for attributes. > > Best, > > ? ?-Nikolaus > > -- > ??It is not worth an intelligent man's time to be in the majority. > ? By definition, there are already enough people to do that.? > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?-J.H. Hardy There's a further advantage: class A: def get_auxclass( self, b, c ): class B: def auxmeth( self2, d, e ): #here, ... return B Because Python permits you to name 'the current instance' any name you want, you're able to hold more than one current instance at one time. In this case, you could write 'return self.val+ self2.val' with no trouble, while I'm not even sure that anything like that is possible in C, C++, Java, or anything higher other than Python. (This is a good point, outside of the usual, by the way.) From thogiti at gmail.com Thu Jul 3 20:33:31 2008 From: thogiti at gmail.com (Nagu) Date: Thu, 3 Jul 2008 17:33:31 -0700 (PDT) Subject: Copyright issues for an application developed using django, python and mySQL Message-ID: <1f23a9fd-33a0-4a06-9733-241c8fd450d2@w4g2000prd.googlegroups.com> Hi, I made a small recommendation engine for our company using python, django, and mySQL. My supervisor and the senior management are worried about the copyright and licensing issues. They want to find out the details on how to go about start using it, like quoting python/django/ mySQL specifically on the bottom of the web page or some other thing. I would like our sales force to start using this new toy to recommend products to customers. They are going to type an intranet page in their browser, and enter the customer ID to get the product recommendations. How do I go about addressing the copyright and licensing issues? (I do not know if licensing is the right word here). Please advice. Thank you, Nagu From bj_666 at gmx.net Fri Jul 11 11:07:59 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Jul 2008 15:07:59 GMT Subject: strip() using strings instead of chars References: <487751a6$0$29402$426a74cc@news.free.fr> Message-ID: <6dpbaeF3l2h2U1@mid.uni-berlin.de> On Fri, 11 Jul 2008 16:45:20 +0200, Christoph Zwerschke wrote: > Bruno Desthuilliers schrieb: >> DRY/SPOT violation. Should be written as : >> >> prefix = 'http://' >> if url.startswith(prefix): >> url = url[len(prefix):] > > That was exactly my point. This formulation is a bit better, but it > still violates DRY, because you need to type "prefix" two times. It is > exactly this idiom that I see so often and that I wanted to simplify. > Your suggestions work, but I somehow feel such a simple task should have > a simpler formulation in Python, i.e. something like > > url = url.lstripstr(('http://', 'https://')) I would prefer a name like `remove_prefix()` instead of a variant with `strip` and abbreviations in it. Ciao, Marc 'BlackJack' Rintsch From fredrik at pythonware.com Thu Jul 17 06:26:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 12:26:42 +0200 Subject: Fwd: Hello In-Reply-To: References: Message-ID: spandana g wrote: > HTTPError: HTTP Error 999: Unable to process request at this time -- > error 999 > > Previously i got the error which I have attached below when I use just > urlopen . But now when I use this http request > user_agent='Mozilla/3.0(compatible;MISE 5.5;Windows NT)' > headers={'User-Agent':user_agent} > req=urllib2.Request(url,None,headers) > file_source.write(urllib2.urlopen(req).read() > > its still giving the error mentioned above .. Iam accessing the yahoo > search engine .. link is "http://search.yahoo.com/search?n=20&p=ipod > " > > I'm attaching the python file i have written just have a look and > suggest me something that works for this query they have an official API, you know: http://developer.yahoo.com/search/boss/ here's an article showing how to install and use it: http://lethain.com/entry/2008/jul/11/search-recipes-for-yahoo-s-boss-in-python/ From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 08:59:26 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 14:59:26 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <874p6fzkkh.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> Message-ID: <488898a5$0$12027$426a34cc@news.free.fr> Torsten Bronger a ?crit : > Hall?chen! > > Bruno Desthuilliers writes: > >> [...] >> >> How would you handle this case with an implicit 'self' : >> >> class Foo(object): >> pass >> >> def bar(self): >> print self >> >> Foo.bar = bar > > Just like this. However, the compiler could add "self" to > non-decorated methods which are defined within "class". What's defined within classes are plain functions. It's actually the lookup mechanism that wraps them into methods (and manage to insert the current instance as first argument). From tedshab at gmail.com Mon Jul 7 15:27:36 2008 From: tedshab at gmail.com (TBS) Date: Mon, 7 Jul 2008 12:27:36 -0700 (PDT) Subject: tale of two attachments Message-ID: <66ba192a-9430-45dc-968f-c41c1c8029d4@k30g2000hse.googlegroups.com> Hi, I have a script that is invoked by .forward on a Unix mailbox. It works fine parsing an attachment and saving to disk when the email is sent directly to the email address (header 1), but doesn't work when the email is sent via a majordomo mailing list (header 2). I've looked at the mime files coming into mail, and they look the same. I've attached the headers, and I don't see any major different, although there is a warning on the mailing list that "X-Authentication- Warning: lists...: pmx set sender to owner-list-report at ... using -f". Here is the code fragment, it seems to fail on the second header on the part.get_param call: parser=email.Parser.Parser() msg = parser.parsestr(raw_email) counter = 1 for part in msg.walk(): if part.get_main_type()== 'multipart': continue log.write("gets here") #gets to this point for majordomo send filename = part.get_param("name") log.write("...but not here") #but not to this point if filename==None: filename = "part-%1" % counter counter += 1 fp = open(os.path.join(dir, filename), 'wb') fp.write(part.get_payload(decode=1)) fp.close() ============================= Header 1 ============================= >From tshab at ... Mon Jul 7 11:00:46 2008 Received: from nospam3... by mail... with ESMTP id m67I0jSg023687 for ; Mon, 7 Jul 2008 11:00:45 -0700 (PDT) (envelope-from tshab at ...) X-MimeOLE: Produced By Microsoft Exchange V6.5 Content-class: urn:content-classes:message MIME-Version: 1.0 Content-Type: application/vnd.ms-excel; name="po_test.xls" Content-Transfer-Encoding: base64 Content-Description: po_test.xls Content-Disposition: attachment; filename="po_test.xls" Subject: test case Date: Mon, 7 Jul 2008 11:00:44 -0700 Message-ID: In-Reply-To: X-MS-Has-Attach: yes X-MS-TNEF-Correlator: Thread-Topic: test case thread-index: AcjgWxsfx8N1mNqFSOq9C/j/8FIZIQAADqBg References: From: "Shab, Theodore" To: "arf" Content-Length: 18675 Status: RO ============================= Header 2 ============================= >From owner-list-report at ... Mon Jul 7 11:01:05 2008 Received: from list... (list...) by mail with ESMTP id m67I14uL023715; Mon, 7 Jul 2008 11:01:04 -0700 (PDT) (envelope-from owner-list-report at ...) Received: from lists... by list... with ESMTP id m67I13bD017476 for ; Mon, 7 Jul 2008 11:01:03 -0700 (PDT) (envelope-from owner-list-report at ...) Received: (from pmx at localhost) by list.../Submit) id m67I13lG017475 for list-report-outgoing; Mon, 7 Jul 2008 11:01:03 -0700 (PDT) (envelope-from owner-list-report at ...) X-Authentication-Warning: lists...: pmx set sender to owner-list- report at ... using -f Received: from nospam... (nospam...) by lists... with ESMTP id m67I127h017471 for ; Mon, 7 Jul 2008 11:01:02 -0700 (PDT) (envelope-from tshab at ...) Received: from exch-mai...) by nospam... with ESMTP id m67I11g2014193 for ; Mon, 7 Jul 2008 11:01:02 -0700 (envelope-from tshab at ...) X-MimeOLE: Produced By Microsoft Exchange V6.5 Content-class: urn:content-classes:message MIME-Version: 1.0 Content-Type: application/vnd.ms-excel; name="po_test.xls" Content-Transfer-Encoding: base64 Content-Description: po_test.xls Content-Disposition: attachment; filename="po_test.xls" Subject: test case 2 Date: Mon, 7 Jul 2008 11:01:01 -0700 Message-ID: X-MS-Has-Attach: yes X-MS-TNEF-Correlator: Thread-Topic: test case 2 thread-index: AcjgW2qv6AWa1eUxTXGlSQ5a2g7OuA== From: "Shab, Theodore" To: "list-report" Sender: owner-list-report at ... Precedence: bulk Content-Length: 18675 Status: O From phillip.oldham at gmail.com Wed Jul 9 10:38:59 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Wed, 9 Jul 2008 07:38:59 -0700 (PDT) Subject: FOSS projects exhibiting clean/good OOP? Message-ID: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> I'm wondering whether anyone can offer suggestions on FOSS projects/ apps which exhibit solid OO principles, clean code, good inline documentation, and sound design principles? I'm devoting some time to reviewing other people's code to advance my skills. Its good to review bad code (of which I have more than enough examples) as well as good, but I'm lacking in finding good examples. Projects of varying sizes would be great. From thogiti at gmail.com Mon Jul 7 15:05:47 2008 From: thogiti at gmail.com (Nagu) Date: Mon, 7 Jul 2008 12:05:47 -0700 (PDT) Subject: Memory error while saving dictionary of size 65000X50 using pickle Message-ID: <43b21f62-edb6-4e37-89b8-f2460fdc36b3@25g2000hsx.googlegroups.com> I am trying to save a dictionary of size 65000X50 to a local file and I get the memory error problem. How do I go about resolving this? Is there way to partition the pickle object and combine later if this is a problem due to limited resources (memory) on the machine (it is 32 bit machine Win XP, with 4GB RAM). Here is the detail description of the error: Traceback (most recent call last): File "", line 1, in s = pickle.dumps(itemsim) File "C:\Python25\lib\pickle.py", line 1366, in dumps Pickler(file, protocol).dump(obj) File "C:\Python25\lib\pickle.py", line 224, in dump self.save(obj) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "C:\Python25\lib\pickle.py", line 663, in _batch_setitems save(v) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 600, in save_list self._batch_appends(iter(obj)) File "C:\Python25\lib\pickle.py", line 615, in _batch_appends save(x) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 562, in save_tuple save(element) File "C:\Python25\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Python25\lib\pickle.py", line 477, in save_float self.write(FLOAT + repr(obj) + '\n') MemoryError: out of memory From modelnine at modelnine.org Tue Jul 29 17:06:46 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Tue, 29 Jul 2008 22:06:46 +0100 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: Also, just a couple of points: Am 29.07.2008, 22:27 Uhr, schrieb Carl Banks : > 1. Any container type that returns a length that isn't exactly the > number of elements in it is broken. I agree, but how do you ever expect to return an infinite element count? The direction I took in that recipe was not returning some "magic" value but raising an OverflowError (for example, you could've also cropped the length at 2**31-1 as meaning anything equal to or larger). This is the thing that breaks your explicit test for non-emptyness using len(x) > 0, but it's also the only possible thing to do if you want to return the number of elements exactly where possible and inform the user when not (and OverflowError should make the point clear). Anyway, that's why there is a separate member function which is explicitly documented to return a magic value in case of an infinite set (i.e., -1) and an exact element count otherwise, but using that (you could write x.len() != 0 for the type in question to test for non-emptiness) breaks polymorphism. > 2. The need for __nonzero__ in this case depends on a limitation in > the language. True, but only for sets with are finite. For an infinite set, as I said above: what would you want __len__() to return? There is no proper interpretation of __len__() for an infinite set, even though the set is non-empty, except if you introduced the magic value infinity into Python (which I did as -1 for my "personal" length protocol). > 3. On the other hand, I will concede that sometimes calculating len is > a lot more expensive than determining emptiness, and at a basic level > it's important to avoid these costs. You have found a practical use > case for __nonzero__. This is just a somewhat additional point I was trying to make; the main argument are the two points you see above. > However, I'd like to point out the contrasting example of numpy > arrays. For numpy arrays, "if x" fails (it raises an exception) but > "if len(x)!=0" succeeds. > > The only sane advice for dealing with nonconformant classes like numpy > arrays or your interger set is to be wary of nonconformances and don't > expect polymorphism to work all the time. The thing is: my integer set type IS conformant to the protocols of all other sequence types that Python offers directly, and as such can be used in any polymorphic function that expects a sequence type and doesn't test for the length (because of the obvious limitation that the length might not have a bound), but only for emptiness/non-emptiness. It's the numpy array that's non-conformant (at least from what you're saying here; I haven't used numpy yet, so I can't comment). > So I guess I'll concede that in the occasional cases with > nonconformant classes the "if x" might help increase polymorphism a > little. > > (BTW: here's another little thing to think about: the "if x" is useful > here only because there isn't an explicit way to test emptiness > without len.) The thing being, again, as others have already stated: __nonzero__() IS the explicit way to test non-emptiness of a container (type)! If I wanted to make things more verbose, I'd not use "if len(x)>0", but "if bool(x)" anyway, because "casting" to a boolean calls __nonzero__(). "if len(x)>0" solves a different problem (even though in set theory the two are logically similar), and might not apply to all container types because of the restrictions on the return value of __len__(), which will always exist. --- Heiko. From trentm at activestate.com Thu Jul 10 12:48:16 2008 From: trentm at activestate.com (Trent Mick) Date: Thu, 10 Jul 2008 09:48:16 -0700 Subject: ActiveState Code: the new Python Cookbook site In-Reply-To: <4874698E.7000805@gmail.com> References: <4873F326.5010905@activestate.com> <4874698E.7000805@gmail.com> Message-ID: <48763D50.8010608@activestate.com> Stef Mientki wrote: > one small remark, > If I want to browse 200 recipes, at 10 per page .... > ... please make something like 100 available per page, > are internet is fast enough nowadays. Touche. Done: http://code.activestate.com/recipes/?paginate_by=100 Cheers, Trent -- Trent Mick trentm at activestate.com From robertmlamarca at yahoo.com Tue Jul 29 06:46:14 2008 From: robertmlamarca at yahoo.com (Robert LaMarca) Date: Tue, 29 Jul 2008 03:46:14 -0700 (PDT) Subject: Swap memory in Python ? - three questions Message-ID: <642068.13334.qm@web55102.mail.re4.yahoo.com> Hi, I am using numpy and wish to create very large arrays. My system is AMD 64 x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a 15 GB swap drive. The command I have been trying to use is; g=numpy.ones([1000,1000,1000],numpy.int32) This returns a memory error. A smaller array ([500,500,500]) worked fine.. Two smaller arrays again crashed the system. So... I did the math. a 1000x1000x1000 array at 32 bits should be around 4gb RAM... Obviously larger than RAM, but much smaller than the swap drive. 1. So... does Numpy have a really lot of overhead? Or is my system just not somehow getting to make use of the 15gb swap area. 2. Is there a way I can access the swap area, or direct numpy to do so? Or do I have to write out my own numpy cache system... 3. How difficult is it to use data compression internally on numpy arrays? thanks very much Robert From bignose+hates-spam at benfinney.id.au Fri Jul 11 20:13:14 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 12 Jul 2008 10:13:14 +1000 Subject: Python 3.0 and removal of the 'string' module References: <87wsjtqiyo.fsf@benfinney.id.au> <87iqvdq6qz.fsf@benfinney.id.au> <487706b7$0$9695$9b622d9e@news.freenet.de> <87abgorgiv.fsf@benfinney.id.au> <76f1bf48-b05f-472b-9bfc-cf59dd2a97ca@m45g2000hsb.googlegroups.com> Message-ID: <87od54ot7p.fsf@benfinney.id.au> John Roth writes: > library changes are all listed in PEP 3008. I assume you mean PEP 3108, "Standard Library Reorganization" . -- \ ?I have one rule to live by: Don't make it worse.? ?Hazel | `\ Woodcock | _o__) | Ben Finney From kyosohma at gmail.com Mon Jul 7 12:20:18 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 7 Jul 2008 09:20:18 -0700 (PDT) Subject: how to recognize IE window already opened using win32com extension References: <203fdfe3-78d6-4b08-a64f-a031df9cacc1@s50g2000hsb.googlegroups.com> Message-ID: <712283ff-7ed3-4bac-acc3-938bafef9639@i76g2000hsf.googlegroups.com> On Jul 7, 11:16?am, Tim Golden wrote: > korean_dave wrote: > > How do I use the win32com API to manipulate IE windows ALREADY open? > > > ie = Dispatch("InternetExplorer.Application") opens a new window. > > > But I'd like to be able to find, of windows already open, a specific > > window (with a specified property, matching url, etc.) > > I have this strange feeling of deja vu. Is there some sort of > "opening IE windows with Python" conference going on > somewhere? > > Have a look at Roger Upole's answer from the other day: > > http://mail.python.org/pipermail/python-win32/2008-June/007796.html > > TJG Crumb! That's way easier than the one I mentioned! Mike From steve at REMOVE-THIS-cybersource.com.au Wed Jul 30 22:25:37 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Jul 2008 02:25:37 GMT Subject: Standard module for parsing emails? References: <6fb93eFap7j5U1@mid.individual.net> Message-ID: <00a11e11$0$20313$c3e8da3@news.astraweb.com> On Wed, 30 Jul 2008 07:11:45 -0700, Phillip B Oldham wrote: > Most clients use ">" which is easy to check for, but I've seen some > which use "|" and some which *don't* quote at all. Its causing us > nightmares in parsing responses to system-generated emails. I was hoping > someone might've seen the problem previously and released some code. My sympathies. I've even seen clients that prefix new (unquoted) text with the quote character ">". Well, possibly it's not the mail client, but the user. Who knows? I will sometimes quote text like this: [quote] Something quoted. [end quote] But I'm writing for a human audience, not for a program. The simple answer is that you can catch 90% of cases by checking for ">", and another 1% by checking for "|". If the email contains HTML, I have found that quoted text is sometimes in another colour. As for the rest, well, sometimes even human beings can't easily determine what's quoted and what isn't. Good luck getting a program to do it. (Percentages are plucked out of thin air. YMMV.) -- Steven From cokofreedom at gmail.com Thu Jul 24 11:00:19 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 24 Jul 2008 08:00:19 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <40449826-c71d-4c6e-8b74-13069269e5da@z6g2000pre.googlegroups.com> <488896bf$0$3493$426a74cc@news.free.fr> Message-ID: > > Please understand that I'm not arguing about this particular design > choice (and FWIW, I'd mostly agree on the point that having a != b > different from not (a == b) is actually a wart). I'm just correcting > your statement about the behaviour of __eq__ / __ne__ not being > documented, which is obviously false. > > (snip) What was the reasoning behind having both __eq__ / __ne__ anyway? To fit in with the equality comparisons? I do agree this one seems like a wart, but not a serious one. I'd say it would make more sense for the interpreter to provide a warning on classes that define one and not that other, at least if set to a certain level, similar to -3 for depreciated. (Or does this exist? I think a "wart" catching level that outputs potential warts and issues would be a useful addition!) From mnordhoff at mattnordhoff.com Mon Jul 7 08:07:19 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 07 Jul 2008 12:07:19 +0000 Subject: Confused yet again: Very Newbie Question In-Reply-To: References: Message-ID: <487206F7.2070609@mattnordhoff.com> mcl wrote: > Why can I not the change the value of a variable in another class, > when I have passed it via a parameter list. > > I am sure I am being stupid, but I thought passed objects were Read/ > Write In Python, there are names which are bound to objects. Doing "foo = bar" and then "foo = spam" (re)binds the name "foo" to the same object as "spam" is bound to. This doesn't have any effect on any other names that were bound to the same object as "bar". > eg > ------------------------------------------------------------ > #!/usr/bin/python > > class one(): #my Global Vars > fred = 'fred' > > class three(): > def createJoe(self, myName): Here, the local name "myName" is bound to the same string object as one.fred. > c1 = one() > myName = 'Joe' #********************* Question why does this > not change variable fred in 'class one' Here, you rebind the local name "myName" to the string object 'Joe'. This doesn't change what one.fred is bound to. > print 'Three(Local): ' + myName + ' Three(Global): ' + > c1.fred > > def main(): > c1 = one() > c3 =three() > c3.createJoe(c1.fred) > > > if __name__ == '__main__' : main() > > Results: > Three(Local): Joe Three(Global): fred > > 'fred' in 'class one' does not get changed to 'joe' in 'class three' > 'createJoe', even though I have passed 'class one' 'fred' to > 'createJoe' > > I hope this makes sense. > > I did not think you had to make the distinction between 'byvar' and > 'byref' as in Basic. > > Thanks > > Richard There are a couple good articles about this online. The one below is lengthy and has ASCII art, but I don't remember if I liked it. BTW, in this example, there doesn't seem to be any need for you to be using classes. Also, you should always use new-style classes unless you have a specific reason not to >>> class MyClass(object): -- From ryntech at gmail.com Mon Jul 21 10:19:16 2008 From: ryntech at gmail.com (rynt) Date: Mon, 21 Jul 2008 07:19:16 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> On Jul 20, 3:50?pm, giveitawhril2... at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. You're either --- A. A Troll B. A young, immature programmer trying to show off or C. A total idiot. Who cares what language a language is written in as long as you can be productive - which you certainly can be in Python. RCB From naude.jaco at gmail.com Wed Jul 23 08:06:50 2008 From: naude.jaco at gmail.com (Jaco Naude) Date: Wed, 23 Jul 2008 05:06:50 -0700 (PDT) Subject: Undefined calling conventions in Python.h References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> Message-ID: <2690be50-3fee-4327-aeae-0c6e236f9aab@27g2000hsf.googlegroups.com> On Jul 23, 1:50?pm, Jaco Naude wrote: > On Jul 23, 1:10?pm, Fredrik Lundh wrote: > > > > > Jaco Naude wrote: > > > What Visual C++ is doing is that it is looking for mangled names since > > > it does not know the DLL contains C functions. I've managed to work > > > around this by declaring the Python functions as follows before using > > > them in the C++ application side: > > > > extern "C" > > > { > > > ? ? void Py_Initialize(void); > > > } > > > > This seems to work and the C++ application side is not looking for > > > mangled names any more. Is this the right way of doing it? It seems > > > unnecessary to have to declare each Python function you want to use > > > using the extern "C" way as shown above. > > > Eh, are you saying that you're not including the Python.h file? ?Because > > it does exactly that, for each and every public function in the C API. > > > > It is probably more of a C++ question it turns out, but I would think > > > that someone in the Python group would use the Python DLL in C++. The > > > documentation also suggest that there is no extra work needed when > > > using C++ rather than C. > > > Oh, but I do that all the time, without doing any extra work. ?Both > > embedding Python in C++ programs and existing it with C++ extensions. > > And I'm definitely not alone. > > > Here's an actual session, using the version of Visual Studio I happen to > > have on this machine (2003, I think) from the command line: > > > ?> more test.cc > > > #include "Python.h" > > #include > > > main() > > { > > ? ? ?Py_Initialize(); > > ? ? ?PyRun_SimpleString("print 'hello'\n"); > > ? ? ?Py_Finalize(); > > > ? ? ?std::cout << "world\n"; > > > } > > > ?> cl cl -EHsc -MD -I \python25\include test.cc \python25\libs\python25.lib > > Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 > > for 80x86 > > Copyright (C) Microsoft Corporation 1984-2002. All rights reserved. > > > ... > > > ?> test > > hello > > world > > > If you cannot get the same console program to work in your compiler > > setup, something's wrong with your configuration. > > > > > Ok that's probably good news, although it points out that there is > something wrong with my configuration since that does not work. I > would rather sort out the problem that having to defined each function > with a extern "C" command. > > That said, let me double check something which might be causing > problems since you will be familiar with this. Which Python.h file do > you include when including the DLL in your programs? The one in the > source distribution of the one in the installation distribution? I've > been including the one in the installation distribution all along. > When I try to include the one in the source distribution it gets up to > the point where it looks for the following include: > > #include "pyconfig.h" > > This file is not in the same directory as the Python.h file in the > source distribution. Because of this I just used Python.h in the > installation distribution. > > Thanks again, > Jaco I only saw your last message after posting my previous one. Ok, so the problem is definitely with the include file Python.h. As I said in my last post, I might be including the wrong one. I would appreciate it if you can tell me which one it the correct one to use: The one in the source distribution or the one in the release distribution (installation done from the .msi file). Thanks Jaco From exarkun at divmod.com Tue Jul 29 10:49:17 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 29 Jul 2008 10:49:17 -0400 Subject: [unittest] Run setUp only once In-Reply-To: <877ib4rc50.fsf@nokile.rath.org> Message-ID: <20080729144917.29191.1051727928.divmod.quotient.8220@ohm> On Tue, 29 Jul 2008 16:35:55 +0200, Nikolaus Rath wrote: >Hello, > >I have a number of conceptually separate tests that nevertheless need >a common, complicated and expensive setup. > >Unfortunately, unittest runs the setUp method once for each defined >test, even if they're part of the same class as in > >class TwoTests(unittest.TestCase): > def setUp(self): > # do something very time consuming > > def testOneThing(self): > > > def testADifferentThing(self): > > >which would call setUp twice. > > >Is there any way to avoid this, without packing all the unrelated >tests into one big function? > class TwoTests(unittest.TestCase): setUpResult = None def setUp(self): if self.setUpResult is None: self.setUpResult = computeIt() ... There are plenty of variations on this pattern. Jean-Paul > >Best, > > -Nikolaus > >-- > ?It is not worth an intelligent man's time to be in the majority. > By definition, there are already enough people to do that.? > -J.H. Hardy > > PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C > >-- >http://mail.python.org/mailman/listinfo/python-list > From kevin.dahlhausen at gmail.com Tue Jul 29 09:51:29 2008 From: kevin.dahlhausen at gmail.com (kpd) Date: Tue, 29 Jul 2008 06:51:29 -0700 (PDT) Subject: Automatically loading and initialising objects from a plugins directory References: <488607BC.3040204@ecs.soton.ac.uk> <4889B888.8000600@ecs.soton.ac.uk> Message-ID: On Jul 25, 7:50 am, Fredrik Lundh wrote: > It's a potentially brain-exploding topic, -that you made very understandable. Thanks for posting that explanation and example. From mccredie at gmail.com Tue Jul 8 14:23:42 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 8 Jul 2008 11:23:42 -0700 (PDT) Subject: How to make python scripts .py executable, not bring up editor References: Message-ID: <7a34ceb4-4f2e-4c79-aeb2-587235cab19d@z72g2000hsb.googlegroups.com> On Jul 7, 2:56?pm, korean_dave wrote: > From command Prompt, i type in a script, ?"tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? You can do this by editing the registry, but here is the general way to click through chaning file associations: Right click on any python file (*.py) and choose "Open With" from the context menu and select "Choose Program..." . From there select "Python" if it appears, or click "Browse" and browse to "C: \Python25\python.exe", or the appropriate location if you have it installed somewhere else. Make sure to check the box next to "Always use the selected program to open this kind of file." Click "Ok". Matt From spython01 at gmail.com Tue Jul 22 10:41:25 2008 From: spython01 at gmail.com (Samir) Date: Tue, 22 Jul 2008 07:41:25 -0700 (PDT) Subject: Converting List of String to Integer References: Message-ID: <71c13b1e-dca2-4246-adc2-4879e8f47ad5@k30g2000hse.googlegroups.com> Wow! Thanks for all of the great additional feedback and responses since I last checked in. The help this group provides is amazing. I'm glad I found it. @Andrew -- Thanks for the clarification on the nested for loop and how to intrepret it. Also, thanks for the information on generators. I have never come across this before so I will look into it a bit more. The same thing goes for iPython. I have been looking for an IDE that comes with better debugging capabilities that the default Python shell. @dusans -- Just when I thought I couldn't simplify my code anymore, you provide come up with another way. Thank you. @ptn -- Thanks for the explanation between "append" and "extend". I guess I've gotten lazy and have always used "append", apparently even in situations where it may not be appropriate. Thanks again, everyone! Samir From stodge at gmail.com Wed Jul 9 11:39:09 2008 From: stodge at gmail.com (Stodge) Date: Wed, 9 Jul 2008 08:39:09 -0700 (PDT) Subject: Boost Python - C++ class' private static data blown away before accessing in Python? References: Message-ID: <8741a327-0f93-452d-8bd0-3260993d5e41@27g2000hsf.googlegroups.com> Thanks. Maybe it's a DLL boundary issue? I'll look into this too. On Jul 5, 11:14?pm, Giuseppe Ottaviano wrote: > > In Python, I retrive an Entity from the EntityList: > > > elist = EntityList() > > elist.append(Entity()) > > elist.append(Entity()) > > > entity = elist.get_at(0) > > > entity.foo() > > > But it crashes inside foo() as the private static data is empty; or > > rather the string array is empty. I know before that point that the > > private static data is valid when accessed earlier by the C++ code as > > the program works fine. It just won't work from Python, so somehow the > > private static data has been blown away but I can't work out where or > > why. > > Probably it is a problem of lifetime. What is the signature of append? ? > Who deletes the appended Entity in C++ code? > If append takes a raw pointer, Boost.Python copies the pointer but ? > destroys the Entity object because it is a temporary and its reference ? > count went to zero. So the pointer in the list is referring to a ? > destroyed object, which results in undefined behaviour. > > Did you have a look at the lifetime policies of Boost.Python? The ? > simplest way to workaround the problem is using const reference ? > arguments, and always use value semantics. If it can result in a ? > performance penalty, another simple way is using shared_ptr's, which ? > have their own reference count (different from the one in CPython ? > lib), but Boost.Python does the magic to make them work together. > > HTH, > Giuseppe From richie at entrian.com Fri Jul 4 07:14:20 2008 From: richie at entrian.com (Richie Hindle) Date: Fri, 04 Jul 2008 12:14:20 +0100 Subject: Bug in re.findall? In-Reply-To: References: Message-ID: Hi Marcin, > subnetlist="192.168.100.0 , 192.168.101.0" > ipre=re.compile("([0-9]{1,3}\.){3}[0-9]{1,3}") > > >>> ipre.findall(subnetlist) > ['100.', '101.'] Correct - it returns the most recently captured text for your sole group. > a=ipre.finditer(subnetlist) > >>> a.next().group() > '192.168.100.0' Also correct, because match.group() returns the whole of the matched text. If you wanted just your captured piece, you need this: > >>> a.next().group(1) > '100.' Hope that helps! -- Richie Hindle richie at entrian.com http://entrian.com From tjreedy at udel.edu Wed Jul 30 12:12:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jul 2008 12:12:52 -0400 Subject: interpreter vs. compiled In-Reply-To: References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> Message-ID: castironpi wrote: >> The current CPython VM does not compile code. CPython compiles Python code to bytecode for its CPython *hardware independent* VM using standard compiler methdods and tools (lexer, parser, code generator, and optimizer). That VM (interpreter) is written in portable-as-possible C, with machine/OS #ifdefs added as needed. > WHY NOT? Why doesn't CPython do it? 1. Portability: The Microsoft C# JIT compiler runs under Windows .NET on x86/amd64 and maybe it64 and what else? Just porting .NET to run 0n Linux on the same processors was/is a bit task. Does MONO have a JIT also? There is a JIT for Python: Psyco. It originally only worked on x86. I am not sure what else. It originated as a PhD project, working with CPython, and was developed further as part of PyPy, but I do not know if there is any current progress. Python VM runs on numerous platforms. 2. Money: C#, its JIT, and IronPython were and are funded by MS. Getting JIT right is hard and tedious. CPython is mostly a volunteer project. It is also the Python development platform. So it has to be simple enough for volunteers to pick up on its innards and for experimentation to be possible. Give the PSF more resources and tjr From wmcbrine at users.sf.net Wed Jul 30 12:57:35 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Wed, 30 Jul 2008 16:57:35 GMT Subject: like py2exe, but on a mac References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> Message-ID: <341kk.407$aA5.312@trnddc05> On Tue, 29 Jul 2008 12:24:49 -0700, Russell E. Owen wrote: > That is exactly what py2app does by default if you run py2app with the > system python. Thanks. I see that it* avoids the issue with Tk starting in the background that I get with Platypus, too. In fact, it looks like the bundlebuilder module is adequate for my needs. It does put in a version-specific #! line, but if I change that to #!/usr/bin/env python, the app still works, and it seems to me that it will work for any version of Python on OS 10.4, 10.5, and maybe 10.3. * I still haven't actually tried "it" (py2app), since I realized that I already had bundlebuilder, but I'm assuming it's the same in this respect. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From gnewsg at gmail.com Sun Jul 13 15:05:07 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sun, 13 Jul 2008 12:05:07 -0700 (PDT) Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> <487a3c0d$0$32256$9b622d9e@news.freenet.de> Message-ID: On 13 Lug, 19:31, "Martin v. L?wis" wrote: > > I understand that heapq is not that efficient to implement timeouts as > > I thought at first. > > It would have been perfect if there were functions to remove arbitrary > > elements withouth needing to re-heapify() the heap every time. > > It is efficient for that - you just need to use it correctly. > > To remove the nth element from a heap, replace it with the last element, > and then _siftup that element: > > def remove_at_index_n(heap, n): > ? ? if n == len(heap)-1: > ? ? ? ? return heap.pop() > ? ? result = heap[n] > ? ? heap[n] = heap.pop() > ? ? heapq._siftup(heap, n) > ? ? return result > > The time complexity for that operation is O(log(len(heap))). > > HTH, > Martin Thanks, by doing some quick benchamrks it seems 20% faster than using heapify(). And if instead of removing an element I'd want to change its value? E.g.: >>> heap = [0, 2, 1, 4, 5, 6, 7, 8, 9] >>> heapify(heap) >>> heap [0, 2, 1, 4, 5, 6, 7, 8, 9] >>> heap[4] = 12 --- Giampaolo http://code.google.com/p/pyftpdlib/ From kylotan at gmail.com Wed Jul 16 10:16:24 2008 From: kylotan at gmail.com (Ben Sizer) Date: Wed, 16 Jul 2008 07:16:24 -0700 (PDT) Subject: Best Python packages? Message-ID: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> Although the standard library in Python is great, there are undoubtedly some great packages available from 3rd parties, and I've encountered a few almost by accident. However, I don't know how a user would become aware of many of these. http://pypi.python.org/pypi/ presumably lists most of the decent ones, but there's a lot there and little indication as to quality or popularity - great if you know exactly what you need, but not so great for just browsing. I'd love to have some way of finding out what hidden gems are out there in the Python world which could make my development a lot easier. Any suggestions? -- Ben Sizer From robert.kern at gmail.com Wed Jul 23 21:51:34 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 23 Jul 2008 20:51:34 -0500 Subject: fill in 3D array In-Reply-To: <49fd3d80-d062-4c39-8274-f0b717486ad4@z66g2000hsc.googlegroups.com> References: <3180f972-f2d4-43ff-81de-bcdd0a2ef906@59g2000hsb.googlegroups.com> <49fd3d80-d062-4c39-8274-f0b717486ad4@z66g2000hsc.googlegroups.com> Message-ID: knielsen73 at gmail.com wrote: > On Jul 23, 9:18 pm, Robert Kern wrote: >> knielse... at gmail.com wrote: >>> Hi, >>> I am a python newbie, trying to convert my IDL scripts to python. I am >>> kind of stuck at the moment. I am reading in a 1-D data file with 2000 >>> data points. I need to put them in a 3-D array with size [10,10,20]. I >>> have defined the field array as arr = zeros((10,10,20)) but don't know >>> how to read the data into the array. >> I assume that you are using numpy. Use numpy.fromfile() and the .reshape() >> method. Assuming that your file is ASCII with numbers separated by whitespace: >> >> import numpy >> arr = numpy.fromfile(thefilename, sep=' ').reshape((10,10,20)) >> >> There is no need, in this case, to create an array before reading the data. >> >>> Also, I need to extract a slice of a 3-D array and tried a = >>> array_name(:,:,20) but that didn't work. >> Python uses [] brackets for indexing, not (). >> >> arr[:,:,20] > > Thanks, working like a charm. Great. If you have more numpy questions, you will probably want to ask them on the numpy mailing list instead of here. http://www.scipy.org/Mailing_Lists -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From pavlovevidence at gmail.com Wed Jul 30 01:24:47 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 22:24:47 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> Message-ID: <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> On Jul 29, 6:42 pm, Matthew Fitzgibbons wrote: > Carl Banks wrote: > > Much like in Steven D'Aprano's example, still the only actual code > > snippet I've seen, it seems that this can easily be done with a simple > > explicit test by having all no-advance filters return None and testing > > with "if x is not None". So it doesn't pass my criterion of being not > > replaceable with simple explicit test. > > > Maybe that's not workable for some reason. Perhaps if you'd post a > > code example that shows this, rather than just talking about it, you > > might be more persuasive. > > > Carl Banks > > -- > >http://mail.python.org/mailman/listinfo/python-list > > The no-advance filters have to return the object because I don't just > forget about it; I evaluate whether I pass it to the next filter or drop > it in a completely different queue for use in the next stage of the > operation. True means 'I'm ready to move on to the next stage,' False > means 'Do the filter thing some more.' I think I see what you're saying, and yeah I guess that could really take advantage of polymorphism between very different types. > Furthermore, the argument that I should just change my API to make a > 'simple test' work is not very convincing. I wasn't suggesting you change it: I was trying to ascertain whether it would have suffered much if you had written it with explicit tests in the first place, or if Python didn't even have magical booleans. > The natural, obvious way for > a filter to work is to pass through the data it operates on; why on > Earth would it return None? I want to DO something with the data. In > this case, make a decision about where to pass the data next. If you don't mind me asking: what do you do actually DO with a zero or empty list? > In Java, > to accomplish this I would have to do lots of introspection and value > checking (adding more any time I came up with a new kind of input), or > make a new kind of interface that gives me a method so I can do a > 'simple test' (including wrappers for ints and arrays and anything else > I decide to pass in down the road). But Python supports duck typing and > gives me a handy __nonzero__ method; I can rebind __nonzero__ in my > filters for my own classes, and ints and lists are handled how I want > them to be by default. So why jump through hoops instead of just using > 'if x'? Ah, so it's just happens to work. Still, just happening to work works. (shrug) > I don't have any postable code (it's in a half way state and I haven't > touched it for a while), but I'll see if I can't find the time to bang > something up to give you the gist. I wouldn't bother at this point. I was looking to see if someone could come up with something to disprove my belief on the polymorphic uselessness of "if x" relative to explicit tests, and if (as I anticipated) they did not, I could claim that "if x" is really just a glorified keystroke saver. But I now realize that the failure of this bunch doesn't prove anything. I don't think most people even realize why answering the question I asked would demonstrate the usefulness of "if x". Your example isn't exactly the smoking gun I was looking for, but I guess we'll have to admit that at least one usage will suffer for not having it. Carl Banks From fredrik at pythonware.com Wed Jul 23 06:34:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 12:34:15 +0200 Subject: logging into a website using python In-Reply-To: <338837.60152.qm@web51802.mail.re2.yahoo.com> References: <338837.60152.qm@web51802.mail.re2.yahoo.com> Message-ID: leo davis wrote: > I''m trying achieve the following by running python programs > > -login to a website > -automate filling up web forms http://twill.idyll.org/ From castironpi at gmail.com Thu Jul 24 00:35:38 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 23 Jul 2008 21:35:38 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <488765A7.7030400@v.loewis.de> Message-ID: <71a1a016-08f0-41e0-9bed-0c93d850b09e@u36g2000pro.googlegroups.com> On Jul 23, 12:08?pm, "Martin v. L?wis" wrote: > >> Oh. ?How is the stack represented? > > > As usual, as successive locations in memory. > > I have the impression that CPython uses the same stack C does. > > Actually, it doesn't (at least not for the evaluation stack). > > In CPython, when a Python function starts, the maximum depth of the > evaluation stack is known, but it depends on the specific function > (of course). So Python needs to allocate an array for the evaluation > stack with known size, but can't do so on the C stack (at least not > portably), since you can't allocate dynamically-sized array as > a local variable in C. > > So instead, pymalloc is used to allocate the evaluation stack, and > it is part of the frame object (so the entire frame object is allocated > in one chunk, and then split up into local variables and evaluation > stack. > > > While conceptually, CPython may put objects on the stack, I am pretty > > sure it actually stacks references (C pointers) to objects in heap memory. > > Correct. > > >> Does it keep track of which stack > >> positions (TOS, TOS1, etc.) are in what registers? > > > I am sure they are not in registers, just normal memory. > > Correct. As discussed above, they are located on the heap (making > Python's frame stack a spaghetti stack). > > Regards, > Martin Martin, I am curious and pursuing it as an independent project. I'd like to write a specialized function to allocate memory from an memory-mapped file instead of the heap. On Windows, to use CreateFileMapping and MapViewOfFile. The companion function, premalloc, would re-open an existing Python object from a handle. (It would need a name or index - > offset look-up.) svn.python.org is down, so I can't tell if Python already implements its own memory management, and if so how that would extrapolate to a byte-array allocated specifically. From duncan.booth at invalid.invalid Thu Jul 31 04:11:33 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Jul 2008 08:11:33 GMT Subject: How can I check nbr of cores of computer? References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> <4890acd6$0$17215$742ec2ed@news.sonic.net> <00a1215d$0$20313$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I don't expect that Python will have a built-in core-counting function. > You would probably need to ask the operating system. On Linux, you could > do this: > > import os > text = os.popen('cat /proc/cpuinfo').read() > > > How you would do it in Windows or Mac, I have no idea. > One way on windows: >>> import win32pdhutil >>> def howmanycores(): for i in range(9999): try: win32pdhutil.GetPerformanceAttributes("Processor(%d)" % i,"% Processor Time") except: break return i >>> print howmanycores() 2 -- Duncan Booth http://kupuguy.blogspot.com From digetl.try at gmail.com Sat Jul 26 06:02:36 2008 From: digetl.try at gmail.com (raja) Date: Sat, 26 Jul 2008 03:02:36 -0700 (PDT) Subject: "Gain 700% More Muscle" Message-ID: How To Gain Freaky Muscle Mass. As Seen On CNN. http://food-drinks.page.tl/ From digetl.try at gmail.com Sat Jul 26 06:04:14 2008 From: digetl.try at gmail.com (raja) Date: Sat, 26 Jul 2008 03:04:14 -0700 (PDT) Subject: Traditional cuisine Message-ID: with italian regional recipes with italian master chefs http://food-drinks.page.tl/ From tjreedy at udel.edu Tue Jul 22 01:37:04 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2008 01:37:04 -0400 Subject: Time Complexity of String Operations In-Reply-To: References: Message-ID: youtoo wrote: > It has been extensively discussed the time complexity (quadratic) of > string concatenation (due to string's immutability). > But what is: > > == the time complexity of string indexing? Is it constant? > == the time complexity of string slicing? Is it O(K) with K the > slice's length? > > How are strings stored in Python? As arrays? As linked lists? There is a Py wiki page on such issues. A wiki search should find it. From joe.p.cool at googlemail.com Sat Jul 5 04:01:23 2008 From: joe.p.cool at googlemail.com (Joe P. Cool) Date: Sat, 5 Jul 2008 01:01:23 -0700 (PDT) Subject: multi-platform browser embedding Message-ID: <2b76ba49-14c1-4e22-a08b-de3b910f4687@8g2000hse.googlegroups.com> I fiddled a little with pyGTK and was quite happy to discover gtkMozEmbed because I want to write an application for Linux and Windows with a powerful browser widget. Unfortunatly I couldnt find a way to make gtkMozEmbed work on Windows. Are there alternatives? I'm lazy so I prefer to download binaries for Windows :) but I don't mind building from source as long as I can use MinGW/Msys and avoid an incalculable odyssey through cryptic compiler errors and makefile surgery. Thanks in advance for your hints. -- Joe From jkugler at bigfoot.com Wed Jul 16 14:40:53 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Wed, 16 Jul 2008 10:40:53 -0800 Subject: Framework recommendations for web service? References: Message-ID: Phillip B Oldham wrote: > So, can anyone suggest a lightweight python framework which just does > the essentials? web.py is pretty slim (not to be confused with web2py). Pylons isn't very large, depending on what you call "essential." j From chris at percious.com Mon Jul 7 17:42:00 2008 From: chris at percious.com (percious) Date: Mon, 7 Jul 2008 14:42:00 -0700 (PDT) Subject: Python Agile Software Development Tools Screencasts Message-ID: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> Hi All, I started a new series about python on showmedo. Please feel free to take a look. They are as follows: virtualenv pastescript nosetests coverage Here is the link: http://showmedo.com/videos/video?name=2910000&fromSeriesID=291 Tutorial materials can be found at http://pythontutorials.googlecode.com cheers. -chris From maric at aristote.info Wed Jul 30 12:02:46 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 30 Jul 2008 18:02:46 +0200 Subject: Standard module for parsing emails? In-Reply-To: <48908EF7.7060301@gmail.com> References: <48908EF7.7060301@gmail.com> Message-ID: <200807301802.46574.maric@aristote.info> Le Wednesday 30 July 2008 17:55:35 Aspersieman, vous avez ?crit?: > For parsing the mails I would recommend pyparsing. Why ? email module is a great parser IMO. -- _____________ Maric Michaud From exarkun at divmod.com Tue Jul 29 11:00:53 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 29 Jul 2008 11:00:53 -0400 Subject: Continuous integration for Python projects In-Reply-To: Message-ID: <20080729150053.29191.647320859.divmod.quotient.8226@ohm> On Tue, 29 Jul 2008 07:47:35 -0700 (PDT), Hussein B wrote: >Hi. >Please correct my if I'm wrong but it seems to me that the major >continuous integration servers (Hudson, CruiseControl, TeamCity ..) >don't support Python based application. >It seems they mainly support Java, .NET and Ruby. >Can I use one of the previous listed servers for Python project? >Thanks. I haven't used CruiseControl or the other CIS you mention, but I suspect they can probably support Python programs. The CruiseControl docs suggest that it supports builder plugins which can do arbitrary things. However, one CIS written in Python (which can also handle arbitrary builds, not just builds of Python software) is buildbot: http://buildbot.net/ Jean-Paul From gagsl-py2 at yahoo.com.ar Thu Jul 17 19:44:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 17 Jul 2008 20:44:28 -0300 Subject: Pickle and wx.TextCtrl References: Message-ID: En Thu, 17 Jul 2008 09:40:29 -0300, escribi?: > The way you read the file is rather strange -mixing calls to readline and > pickle.load- I'd write the data using pickle.dump calls *only* and then > read it using pickle.load calls *only*. > > I used 13.1.7 Example of the Python Library Referencebut. Got an error > message when I did not have the readline() statement. The example doesn't have any readline(). Make sure you open the file in binary format ('wb' or 'rb'). If you have a list of objects: just write the list. It takes a single call to pickle.dump(), and later, a single call to picle.load() If you have too many objects and don't want to save/load all of them at once, write them one at a time using pickle.dump(element, output_file, -1), ending with a sentinel value (e.g. None): pickle.dump(None, ...) You may read them again using something like this: pfile = open(..., 'rb') while True: element = pickle.load(pfile) if element is None: break do_something_with(element) pfile.close() Ensure that you can save and load your data using a simple script, *before* writing the GUI. -- Gabriel Genellina From ptmcg at austin.rr.com Tue Jul 8 09:37:28 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 8 Jul 2008 06:37:28 -0700 (PDT) Subject: How to make python scripts .py executable, not bring up editor References: Message-ID: <71fe0699-6e09-4fbb-8145-bd1bbe3a0356@k30g2000hse.googlegroups.com> On Jul 7, 4:56?pm, korean_dave wrote: > From command Prompt, i type in a script, ?"tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? type: python tryme.py or: C:\Python24\python tryme.py -- Paul From spython01 at gmail.com Wed Jul 23 18:30:54 2008 From: spython01 at gmail.com (Samir) Date: Wed, 23 Jul 2008 15:30:54 -0700 (PDT) Subject: Request Help Debugging Program Message-ID: <898dfe7a-4133-4337-8243-f4936b8a8092@8g2000hse.googlegroups.com> Hi Everyone, In order to get a better command of Python, I have been trying to solve the puzzles on the Project Euler web site. I've made my way down to problem 21: http://projecteuler.net/index.php?section=problems&id=21 I've created a function (findSumOfDivisor), that when passed an integer, will return the sum of the argument's natural divisors. When tested in isolation, it seems to do what I intended. When I incorporate it into the larger program, however, I start getting run-time errors that for the life of me I cannot debug. My brute-force approach is to cycle through all of the integers to find the sum of their divisors and then enter the number (as key) and the sum of the divisors (as values) to a dictionary called "amicable". I only call findSumOfDivisor if the key:value combination does not already exist in the dictionary (hoping to save some time when I loop through 10,000 integers). Below is the code I have so far. I'm not completely certain if my logic will lead me to the correct solution, but that is a different matter. For now, the program seems to get through the first integer, 2, successfully, but errors out in line 20 when it tries to call the function. Apparently, Python doesn't like line 12 in the function where it returns the sum of the divisors. The code, which is best viewed using a fixed-font, is: from math import sqrt def findSumOfDivisor(n): divisor = [1] # start list of divisors at 1 for x in range(2, int(sqrt(n))+1): # search for possible divisors between 2 and sqrt(n) if n%x == 0: # if x is a divisor of n if ((n/x) == x): # and if x is the sqrt of n divisor.append(x) # add x to the list of divisors else: # otherwise divisor.append(x) # add x to the list of divisors divisor.append(n/x) # and add n/x to the list as well return sum(divisor) # return the sum of the divisors answer = [] # initialize answer to empty amicable = {1:0} # initialize amicable dictionary for 1 (sum is 0) for i in range(2,10): # loop through integers 2 through 9 if not amicable.has_key(i): # if i not found in amicable keys sum = findSumOfDivisor(i) # then find the sum of its divisors amicable[i] = sum # and add both to amicable dictionary else: # otherwise sum = amicable[i] # just get its sum if not amicable.has_key(sum): sum2 = findSumOfDivisor(sum) # if sum of i's divisors not in amicable keys amicable[sum] = sum2 # then add both to amicable dictionary else: # otherwise sum2 = amicable[sum] # just get its sum if i == sum2: # if i is amicable with sum2 answer.append(i) # append i to list of answers answer.append(sum2) # and append sum2 to list of answers print "amicable =", amicable print "answer =", answer The error I receive is: Traceback (most recent call last): File "pe_prob021.py", line 19, in sum = findSumOfDivisor(i) # then find the sum of its divisors File "pe_prob021.py", line 12, in findSumOfDivisor return sum(divisor) # return the sum of the divisors TypeError: 'int' object is not callable Even after cluttering the code with print statements every other line, I am completely lost. Does anyone know why I get this error? Thanks in advance. Samir From busybeejoey at yahoo.com Sat Jul 19 03:46:21 2008 From: busybeejoey at yahoo.com (busybeejoe) Date: Sat, 19 Jul 2008 00:46:21 -0700 (PDT) Subject: Buy/sell/trade your used stuff and promote your small business to people in california Message-ID: <2c15e366-aa91-4527-b294-239b351736ec@i36g2000prf.googlegroups.com> Buy/sell/trade your used stuff and promote your small business to people in california I created a NEW forum where you can buy/sell/trade your used stuff and for small business owners to promote their services to others in their area... Its a simple and easy way to let everyone know about your company and services you offer....and its free to join http://www.yansbb.com/ From bj_666 at gmx.net Fri Jul 25 11:28:38 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Jul 2008 15:28:38 GMT Subject: Calling external program from within python References: <6eu684F91muhU1@mid.uni-berlin.de> <6eu75mF92mqcU1@mid.uni-berlin.de> Message-ID: <6eu9p6F8v6ooU1@mid.uni-berlin.de> On Fri, 25 Jul 2008 08:13:55 -0700, oj wrote: > On Jul 25, 3:44?pm, "Diez B. Roggisch" wrote: >> Because usually if a program *prompts* the user to enter input (and that >> was what I read from the OP's post), one has to deal with pseudo >> terminals, not with stdin/out. > > How does the program writing some text before taking input change how > it takes input? It might not write the text before taking input because it is buffered. But if the controlling program waits for some text before sending input to the other program all hangs. > If it runs in a terminal and takes input from the user via keyboard, > as in the user types a response and presses enter, it's most likely > using stdin, in which case subprocess would be perfect. But buffering messes with the order of inputs and outputs. Buffering is different if you "talk" to a real (or pseudo) terminal or to a file or pipe and the calling program can't influence the called programs buffering except if it pretends to be a terminal, which pexpect does. Ciao, Marc 'BlackJack' Rintsch From deets at nospam.web.de Thu Jul 31 09:58:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 15:58:56 +0200 Subject: current week / weeks in year - best practice References: Message-ID: <6fdur9Fb0nvuU1@mid.uni-berlin.de> Aljosa Mohorovic wrote: > i use this to find out current week and total number of weeks for > current year: > now = datetime.now() > weeks_in_year = int(date(now.year, 12, 31).strftime("%W")) > current_week = int(date(now.year, now.month, now.day).strftime("%W")) > > is this the best way or is there a better way? Instead of datetime.now() use date.today(), which removes a lot of boilerplate. int(date.today().strftime("%W")) Apart from that, I think it's the way to go. Diez From kay.schluehr at gmx.net Thu Jul 24 06:40:59 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 24 Jul 2008 03:40:59 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> Message-ID: <32e12408-fc9f-4eb4-8b9d-fb7fa69bd2fc@f36g2000hsa.googlegroups.com> On 24 Jul., 11:40, Torsten Bronger wrote: > Hall?chen! > > Bruno Desthuilliers writes: > > [...] > > > How would you handle this case with an implicit 'self' : > > > class Foo(object): > > pass > > > def bar(self): > > print self > > > Foo.bar = bar > > Just like this. However, the compiler could add "self" to > non-decorated methods which are defined within "class". And $self2, $self3, ... to the object methods of nested classes and $cls2, $cls3, ... to the classmethods of those classes...? And when we are at it, here is a nice little exercise for the proponents of compiler magic. Write a decorator that takes and returns a method and prints the object the method is bound to. It's very easy to do it when the object is passed explicitely: def print_self(func): def call(self, *args, **kwd): print self return func(self, *args, **kwd) return call Conceptual clarity isn't always an entirely bad thing to have. From svenn.bjerkem at googlemail.com Mon Jul 21 07:09:33 2008 From: svenn.bjerkem at googlemail.com (Svenn Are Bjerkem) Date: Mon, 21 Jul 2008 04:09:33 -0700 (PDT) Subject: Parsing VHDL with python, where to start. Message-ID: Hi, I am in the need to write an application for PyQt to visualise the structure of a VHDL project I am working on. Looking for a sensible way to parse VHDL files and putting them into a data structure that PyQt can represent as a tree (or whatever the MVC is supporting) through search engines does not give me many hints. From what I know, VHDL is not a very easy language to parse. There seems to be a parser for perl available, but I do not know if it is wise to use a perl module as a template for writing something similar in python. My initial idea is to start simple and extend features in my application, but I fear that I may start off with wrong ideas how to parse and then code myself into a dead-end requiring myself to rewrite the whole application in order to get any further. I would start finding definitions of entities and the instantiations of these and build a tree from a set of external vhdl files stored in a file hierarchy. If somebody have a starting point where to get going with a task like this, I would be happy to know. -- kind regards, Svenn From cjw at ncf.ca Sat Jul 12 08:22:12 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 12 Jul 2008 08:22:12 -0400 Subject: Python 3.0 and removal of the 'string' module In-Reply-To: References: <87wsjtqiyo.fsf@benfinney.id.au> <87iqvdq6qz.fsf@benfinney.id.au> <487706b7$0$9695$9b622d9e@news.freenet.de> <87abgorgiv.fsf@benfinney.id.au> Message-ID: Benjamin wrote: > On Jul 11, 3:06 am, Ben Finney > wrote: >> "Martin v. L?wis" writes: >> >>>> This is rather disappointing. Is that entire page suspect? >>> All documentation about Python 3 is suspect until Python 3 gets >>> actually released (nobody can say for sure how the release will >>> look like in all details). >> Is there a better information source, then, for the current state of >> what's expected in Python 3.0? > > Look at the development docs. We try to keep them up to date: > http://doc.python.org/dev/3.0 >> -- It would be good if the PEP references in 'What's New' could be clickable. Colin W. From duncan.booth at invalid.invalid Sat Jul 12 13:36:01 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jul 2008 17:36:01 GMT Subject: strip() using strings instead of chars References: Message-ID: Christoph Zwerschke wrote: > Duncan Booth schrieb: >>> if url.startswith('http://'): >>> url = url[7:] >> >> If I came across this code I'd want to know why they weren't using >> urlparse.urlsplit()... > > Right, such code can have a smell since in the case of urls, file names, > config options etc. there are specialized functions available. But I'm > not sure whether the need for removing string prefix/suffixes in general > is really so rare that we shouldn't worry to offer a simpler solution. > One of the great things about Python is that it resists bloating the builtin classes with lots of methods that just seem like a good idea at the time. If a lot of people make a case for this function then it might get added, but I think it is unlikely given how simple it is to write a function to do this for yourself. From fredrik at pythonware.com Fri Jul 25 06:52:09 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 12:52:09 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: <4889AC5E.8090909@egenix.com> References: <1216966424.4685.1265275245@webmail.messagingengine.com> <4889AC5E.8090909@egenix.com> Message-ID: M.-A. Lemburg wrote: >> 4. Is there a stable version of IronPython compiled under a 64 bit >> version of .NET? Anyone have experience with such a beast? > > Can't comment on that one. Should that matter? Isn't IronPython pure CLR? From mgeorge at gmail.com Wed Jul 9 12:02:49 2008 From: mgeorge at gmail.com (mg) Date: Wed, 9 Jul 2008 09:02:49 -0700 (PDT) Subject: trouble building Python 2.5.1 on solaris 10 Message-ID: <7c490a26-b967-4d33-933f-c692d111201a@m73g2000hsh.googlegroups.com> When make gets to the _ctypes section, I am getting the following in my output: building '_ctypes' extension creating build/temp.solaris-2.10-i86pc-2.5/home/ecuser/Python-2.5.1/ Modules/_ctypes creating build/temp.solaris-2.10-i86pc-2.5/home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi creating build/temp.solaris-2.10-i86pc-2.5/home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi/src creating build/temp.solaris-2.10-i86pc-2.5/home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi/src/x86 gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/_ctypes.c -o build/temp.solaris-2.10-i86pc-2.5/home/ ecuser/Python-2.5.1/Modules/_ctypes/_ctypes.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/callbacks.c -o build/temp.solaris-2.10-i86pc-2.5/home/ ecuser/Python-2.5.1/Modules/_ctypes/callbacks.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/callproc.c -o build/temp.solaris-2.10-i86pc-2.5/home/ ecuser/Python-2.5.1/Modules/_ctypes/callproc.o /home/ecuser/Python-2.5.1/Modules/_ctypes/callproc.c: In function `_CallProc': /home/ecuser/Python-2.5.1/Modules/_ctypes/callproc.c:918: warning: implicit declaration of function `alloca' gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/stgdict.c -o build/temp.solaris-2.10-i86pc-2.5/home/ ecuser/Python-2.5.1/Modules/_ctypes/stgdict.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/cfield.c -o build/temp.solaris-2.10-i86pc-2.5/home/ ecuser/Python-2.5.1/Modules/_ctypes/cfield.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/malloc_closure.c -o build/temp.solaris-2.10-i86pc-2.5/ home/ecuser/Python-2.5.1/Modules/_ctypes/malloc_closure.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi/src/prep_cif.c -o build/temp.solaris-2.10- i86pc-2.5/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/src/ prep_cif.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi/src/x86/ffi64.c -o build/temp.solaris-2.10- i86pc-2.5/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ ffi64.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi/src/x86/unix64.S -o build/temp.solaris-2.10- i86pc-2.5/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ unix64.o gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi/src/x86/ffi.c -o build/temp.solaris-2.10- i86pc-2.5/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ ffi.o /home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ffi.c:177: warning: function declaration isn't a prototype /home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ffi.c:194: warning: function declaration isn't a prototype gcc -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -I/home/ecuser/Python-2.5.1/./Include -Ibuild/ temp.solaris-2.10-i86pc-2.5/libffi/include -Ibuild/temp.solaris-2.10- i86pc-2.5/libffi -I/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/ src -I./Include -I. -I/usr/local/include -I/home/ecuser/Python-2.5.1/ Include -I/home/ecuser/Python-2.5.1 -c /home/ecuser/Python-2.5.1/ Modules/_ctypes/libffi/src/x86/sysv.S -o build/temp.solaris-2.10- i86pc-2.5/home/ecuser/Python-2.5.1/Modules/_ctypes/libffi/src/x86/ sysv.o Assembler: "/var/tmp//ccbsqiOB.s", line 236 : Syntax error Near line: ".section .note.GNU-stack,"",%progbits" my configure looks like this: ./configure --prefix=/home/ecuser/dev -- with-gcc --with-system-ffi any ideas? From castironpi at gmail.com Thu Jul 24 00:07:33 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 23 Jul 2008 21:07:33 -0700 (PDT) Subject: problem doing unpickle in an exec statement References: Message-ID: On Jul 23, 6:01?pm, Danny Shevitz wrote: > Howdy, > > In my app I need to exec user text that defines a function. I want this > function to unpickle an object. Pickle breaks because it is looking for > the object definition that isn't in the calling namespace. > > I have mocked up a simple example that shows the problem. Run this > first code (from create_pickle.py) to create the pickle. > > create_pickle.py: (run this first) > > ############################################# > import cPickle > > # the pickle file name > file_name = 'd:\\temp\\test1.pickle' > > # define a class > class Tree(object): > ? ? ? ? pass > > def main(): > ? ? ? ? # instantiate ? > ? ? ? ? t = Tree() > > ? ? ? ? # create the sweet pickle > ? ? ? ? fp = open(file_name, 'wb') > ? ? ? ? cPickle.dump(t, fp) > ? ? ? ? fp.close() > > ? ? ? ? # try to unpickle directly > ? ? ? ? fp = open(file_name, 'rb') > ? ? ? ? result = cPickle.load(fp) > ? ? ? ? fp.close() > ? ? ? ? print "unpickling directly works just fine, result = ", result > > if __name__=='__main__': > ? ? ? ? main() > ############################################# > > run this second: > > exec_pickle.py > ############################################# > # this file shows a problem with sweet pickle in an exec statement > > # the pickle file name > file_name = 'd:\\temp\\test1.pickle' > > # code to be turned into a function > code_text = ''' > def include(): > ? print "this works!" > ''' > > # a function for creating functions > def create_fun(code_text): > ? ? ? ? clean_dict = {} > ? ? ? ? exec code_text in clean_dict > ? ? ? ? return clean_dict['include'] > > # include_fun is a bona fide function > include_fun = create_fun(code_text) > > # this works > include_fun() > > # now try to load the pickle in an exec statement > code_text = ''' > def include(file_name): > ? print "processing file_name: ", file_name > ? import cPickle > ? fp = open(file_name, "rb") > ? result = cPickle.load(fp) > ? fp.close() > ? print "result = ", result > ''' > > # create the new include_fun > include_fun = create_fun(code_text) > > # run it > include_fun(file_name) > > ############################################# > > Can anyone enlighten me what I need to do to exec_pickle.py > to get this to work? > > thanks, > Danny Hi, It works if you paste # define a class class Tree(object): pass into exec_pickle.py. There are inherent dilemmas in pickling instances of non-primitive types, such as definition location, and change in definition across versions. How does 'class Tree' fit in to your design module? From user at domain.invalid Wed Jul 16 13:06:15 2008 From: user at domain.invalid (Dennis Cote) Date: Wed, 16 Jul 2008 17:06:15 GMT Subject: Best Python packages? In-Reply-To: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> Message-ID: Ben Sizer wrote: > I'd love to have some way of finding out what hidden gems are out > there in the Python world If they were easy to find, they wouldn't be "hidden gems". :-) Dennis Cote From philr at aspexconsulting.co.nz Mon Jul 21 16:48:19 2008 From: philr at aspexconsulting.co.nz (Phil Runciman) Date: Tue, 22 Jul 2008 08:48:19 +1200 Subject: Python Written in C? In-Reply-To: <5e098db8-38f0-42ac-9cb7-9eada66f9a00@z72g2000hsb.googlegroups.com> Message-ID: On 20 jul, 19:50, giveitawhril2... at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > > So I was suspecting the Python compiler or interpreter is written in a ".. if Python is so hot.." Python represents progress not the ultimate goal. Thank goodness we are continuing to learn from past mistakes. All compilers and interpreters started out being written in another language. You do not help us by stating the obvious. This is even true of the interpreter in your own brain that processes English. IMHO The latter still has some bugs in it. ;-) From __peter__ at web.de Thu Jul 24 03:13:59 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 Jul 2008 09:13:59 +0200 Subject: problem doing unpickle in an exec statement References: Message-ID: Danny Shevitz wrote: > Howdy, > > In my app I need to exec user text that defines a function. I want this > function to unpickle an object. Pickle breaks because it is looking for > the object definition that isn't in the calling namespace. > > I have mocked up a simple example that shows the problem. Run this > first code (from create_pickle.py) to create the pickle. > > create_pickle.py: (run this first) > > ############################################# > import cPickle > > # the pickle file name > file_name = 'd:\\temp\\test1.pickle' > > # define a class > class Tree(object): > pass > > > def main(): > # instantiate > t = Tree() > > # create the sweet pickle > fp = open(file_name, 'wb') > cPickle.dump(t, fp) > fp.close() > > # try to unpickle directly > fp = open(file_name, 'rb') > result = cPickle.load(fp) > fp.close() > print "unpickling directly works just fine, result = ", result > > if __name__=='__main__': > main() > ############################################# > > run this second: > > exec_pickle.py > ############################################# > # this file shows a problem with sweet pickle in an exec statement > > # the pickle file name > file_name = 'd:\\temp\\test1.pickle' > > # code to be turned into a function > code_text = ''' > def include(): > print "this works!" > ''' > > # a function for creating functions > def create_fun(code_text): > clean_dict = {} > exec code_text in clean_dict > return clean_dict['include'] > > # include_fun is a bona fide function > include_fun = create_fun(code_text) > > # this works > include_fun() > > > # now try to load the pickle in an exec statement > code_text = ''' > def include(file_name): > print "processing file_name: ", file_name > import cPickle > fp = open(file_name, "rb") > result = cPickle.load(fp) > fp.close() > print "result = ", result > ''' > > # create the new include_fun > include_fun = create_fun(code_text) > > # run it > include_fun(file_name) > > ############################################# > > Can anyone enlighten me what I need to do to exec_pickle.py > to get this to work? Pickling saves the name of the module and the class (and of course the instance data). Because you put the class in your main script the module name is __main__, and when you unpickle later pickle imports __main__ which unfortunately is now a different script that doesn't contain the/a Tree class. To solve that problem put the Tree class in a separate module, say tree.py, that can be imported by both create_pickle.py and exec_pickle.py. You only need an explicit from tree import Tree in create_pickle. Peter From bgeddy at home.havin.a.break Thu Jul 17 10:47:34 2008 From: bgeddy at home.havin.a.break (bgeddy) Date: Thu, 17 Jul 2008 15:47:34 +0100 Subject: storing references instead of copies in a dictionary In-Reply-To: References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: mk wrote: > Calvin Spealman wrote: >> To your actual problem... Why do you wanna do this anyway? If you want >> to change the function in the dictionary, why don't you simply define >> the functions you'll want to use, and change the one you have bound to >> the key in the dictionary when you want to change it? In other words, >> define them all at once, and then just d['1'] = new_f1. What is wrong >> with that? > > Well, basically nothing except I need to remember I have to do that. > > Suppose one does that frequently in a program. It becomes tedious. I > think I will define some helper function then: > > >>> def helper(fundict, newfun): > ... fundict[newfun.func_name] = newfun > ... > > _If_ there were some shorter and still "proper" way to do it, I'd use > it. If not, no big deal. > >> For completeness: >> >> def new_f1(arg): >> return "NEW f1 " + arg >> f1.func_code = new_f1.func_code >> >> Don't use that unless you really have to and I nearly promise that you >> don't. > > I promise I won't use it. :-) It seems like a 'wrong thing to do'. > > Well it's probably totally "non pythonic" but this does what you want: def f2(arg): return "f2 "+arg def f1(arg): return "f1 "+arg a={"1":"f1","2":"f2"} print [eval(x[1])(x[0]) for x in a.items()] def f2(arg): return "New f2 "+arg print [eval(x[1])(x[0]) for x in a.items()] Don't know if this is any use to you.. From hat at se-162.se.wtb.tue.nl Mon Jul 7 05:55:25 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 07 Jul 2008 11:55:25 +0200 Subject: yo... References: Message-ID: On 2008-07-07, abhishek wrote: > hey guys...me nu 2 python yo...help me...by da way...jus joined > in....thanks Ask a specific question and you may get an answer. If you want an answer from me, it helps *a lot* if you write full english sentences (starting with a capital letter and ending with a single '.') rather than the short-hand you seem to favor. (It costs me a lot of effort to decipher). Sincerely, Albert From martin at v.loewis.de Fri Jul 18 19:32:23 2008 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 19 Jul 2008 01:32:23 +0200 Subject: Change PC to Win or Windows In-Reply-To: References: Message-ID: <48812807.3000100@v.loewis.de> > Calling Windows PC seems to be something that Apple did so they would > not have to directly mention Windows. Could all the places that say PC > that are not referring to Personal Computers in general be changed to > Win or Windows. That's bikeshedding. If the name stops you from building your own binaries, you should use prebuilt binaries, or read the documentation. Regards, Martin From gros_bedo at hotmail.com Wed Jul 9 18:51:18 2008 From: gros_bedo at hotmail.com (Gros Bedo) Date: Thu, 10 Jul 2008 00:51:18 +0200 Subject: Terminate a python script from linux shell / bash script Message-ID: Hello :-) I have a question about Python and Linux shell. I have a python program which is permanently resident in the end-user system. I'm currently producing a RPM package, and it works nicely. The problem is that when I uninstall it, my program keeps running in the background, even if the files are deleted. I know I can terminate python shell directly, but this is not a good idea because the end-user may be working with another important python application, and would be very angry if mine would close everything that is using python shell. So, is there a way from the Linux shell or a bash script to terminate just one specific Python script ? _________________________________________________________________ Votre contact a choisi Hotmail, l'e-mail nouvelle g?n?ration. Cr?ez un compte. http://www.windowslive.fr/hotmail/default.asp From tjreedy at udel.edu Fri Jul 25 18:07:59 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Jul 2008 18:07:59 -0400 Subject: Quesion on class.attributes assignment In-Reply-To: References: Message-ID: John Hanks wrote: > Hi, > > I am reading a python program now but I just cannot understand how the > values of class attributes are assigned and changed. Here is the > original code url: > http://agolb.blogspot.com/2006/01/sudoku-solver-in-python.html > Here I am concerned is how attribute matrix.rows is changed. Through pdb > debugging, I can see in line 97, once "self.solutions = set((val,))" is > executed, cell.row and matrix.rows will be updated. But I did not see > any assignment codes here. How could this change happen then? Thanks a lot! Newsreaders do not typically have line counters. I presume you are referring to def setSolution(self, val): self.solved = True self.solutions = set((val,)) self.matrix.changed = True for other in self.row+self.col+self.submatrix: if other is self: continue if other.solutions == self.solutions: raise DeadEnd() other.delSolutions(self.solutions) First, self is an instance of the class, so these are all instance attributes, not class attributes. The difference is important. As to your question, the last line mutates (modifies, updates) each member of self.row, self.col, and self.submatrix that is not self itself. The method delSolutions has the actual target rebindings. tjr From mensanator at aol.com Fri Jul 11 19:20:47 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 11 Jul 2008 16:20:47 -0700 (PDT) Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: <2a13cea6-5144-4f37-af8a-607601f923a9@79g2000hsk.googlegroups.com> On Jul 11, 5:34?pm, Denis Kasak wrote: > On Sat, Jul 12, 2008 at 12:22 AM, kdt wrote: > > ?> Hi all, > ?> > ?> Can someone please explain to me why the following evaluates as false? > ?> > ?>>>>list=['a','n','n','a'] > ?>>>>list==list.reverse() > ?>>>>False > ?> > ?> I'm stumped :s > > Read the documentation on list.reverse(). > > Basically, it reverses the list in place, so it modifies the list which > called it. It does not return a /new/ list which is a reversed version > of the original, as you expected it to. Since it doesn't return anything > explicitly, Python makes it return None. Hence, the comparison you are > doing is between the original list and a None, which is False, naturally. > Try this: > > spam = ['a', 'n', 'n', 'a'] > eggs = spam[:] > if spam.reverse() == eggs: > ? ? print "Palindrome" You could also do >>> spam = ['a','n','n','a'] >>> if spam == [i for i in reversed(spam)]: print "Palindrome" > > Also, 'list' is a really bad name for a list, since this is the name of > the builtin type object for the list type. > > -- > Denis Kasak From zondo42 at googlemail.com Fri Jul 18 10:44:16 2008 From: zondo42 at googlemail.com (Glenn Hutchings) Date: Fri, 18 Jul 2008 15:44:16 +0100 Subject: [ANN] PyStar 0.1 -- A* graph search algorithm Message-ID: Announcing PyStar, a python module implementing the A* graph search algorithm. Available under the GPL, you can find it at http://fluffybunny.memebot.com/pystar.html I tried to find a decent Python version of this on the Interweb, but the only one I found (http://arainyday.se/projects/python/AStar) was just a bit too cryptic for me to understand and use. So I knocked this up from pseudocode on the Wikipedia A* page, and rewrote the AStar demo program in Tkinter. Comments, bug reports, big wads of cash, etc., are welcome. From kyosohma at gmail.com Wed Jul 23 16:18:35 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 23 Jul 2008 13:18:35 -0700 (PDT) Subject: need thumbnail from video References: Message-ID: <853c0f7d-0243-4829-8149-29afce203f40@d1g2000hsg.googlegroups.com> On Jul 22, 8:54?am, John Fabiani wrote: > Hi, > I need a py tool that will provide a thumbnail (bmp?) from a video (avi, > wmv) that will be cross platform (linux, windows). ?Research has provided > pymedia for Linux but I haven't found anything for windows. ?Hopefully, > someone has had to do this in the past and knows what has to be done. > > Thanks in Advance, > Johnf PyMedia works on Windows too, according to their website. Mike From steve at REMOVE-THIS-cybersource.com.au Tue Jul 29 19:59:50 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 23:59:50 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> Message-ID: <009faa6f$0$20313$c3e8da3@news.astraweb.com> On Tue, 29 Jul 2008 13:53:07 -0700, Carl Banks wrote: > Bzzt. "if len(x)!=0" is a simple explicit that would work for this > class and all built-in containers. (Or should--Steven D'Aprano's > objections notwithstanding, any reasonable container type should support > this invariant. What's the length of an empty list with a sentinel at the end? What's the length of a binary tree? Does it even have a length? What's the length of a constant-sized table where each position might be in use or free? You're making assumptions about what an empty object "should" look like. I say, just ask the object if it's empty, don't try to guess how you would find out. Maybe the object carries around a flag x.isempty. Who knows? Why do you care? You're basing your code on implementation details. That should be avoided whenever possible. [...] > Once again, I'm invoking the contraint against simply using x in a > boolean context, So, to put it another way... you want us to give you an example of using x in a boolean context, but you're excluding any example where we use x in a boolean context. Right-o, I've had enough of your trolling. I'm out of here. -- Steven From desothier at yahoo.com Wed Jul 9 06:30:22 2008 From: desothier at yahoo.com (antar2) Date: Wed, 9 Jul 2008 03:30:22 -0700 (PDT) Subject: start reading from certain line Message-ID: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> I am a starter in python and would like to write a program that reads lines starting with a line that contains a certain word. For example the program starts reading the program when a line is encountered that contains 'item 1' The weather is nice Item 1 We will go to the seaside ... Only the lines coming after Item 1 should be read Thanks! From deets at nospam.web.de Mon Jul 7 07:55:14 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 07 Jul 2008 13:55:14 +0200 Subject: Cross Compiler for Python? References: Message-ID: <6deeidF271g5U2@mid.uni-berlin.de> Hendrik van Rooyen wrote: > Up to now, I have been innocently using the vanilla python > that comes with the Linux distribution (Suse in my case). > > For the past few days, I have been playing with a little > device called an eBox - it is basically a 486 with 128Mb > memory, and a 1Gig pcmcia flash drive. > > We want to try to use this as an industrial controller, so > I want to load python onto it. > > So I downloaded the sources, and got them into the box, > over its ethernet connection. > > Then I got stymied - the configure script will not run, > because the "distribution" has no C compiler - it is > basically a kernel, and Busybox, with precious little else. > > So I googled, and I found mobile python, and portable python, > both aimed at windows. - no good to me. > > Adding "embedded" to the Google string is also useless, > as it basically brings up instances of embedding the > interpreter into another app, not for small processors. > > So how does one do a compile of python on one machine > aimed at another one? - All I want is a vanilla installation > with the stuff in all the usual places. And just to make matters > interesting, the two Linux boxes I have available are both > 64 bit dual core animals, one Intel, one AMD... > > I don't need much more than the interpreter, sys, os, sockets > and ctypes. > > Alternatively, where can one find a set of binaries for > 32 bit Linux? > > Looking for some sane advice please. Look at the gumstix project, they do have a cross-compiled python in there. You should be able to get an idea on how to do that yourself. It involves (or at least did back then) a bit of trickery as the build-process of python uses the freshly created interpreter to pre-compile modules. But it is possible. Diez From gary at byoteki.com Mon Jul 28 20:56:16 2008 From: gary at byoteki.com (Gary Josack) Date: Mon, 28 Jul 2008 20:56:16 -0400 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: <488DF599.7070904@activestate.com> References: <487E2BCE.30108@hughes.net> <488A2E72.6030802@activestate.com> <488D53AB.7090300@gmail.com> <488DF599.7070904@activestate.com> Message-ID: <488E6AB0.4000109@byoteki.com> Trent Mick wrote: > Manuel Vazquez Acosta wrote: >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> Just test for maxint value: >> >> from sys import maxint >> if maxint >> 33: >> print "more than 32 bits" # probably 64 >> else: >> print "32 bits" > > I believe that was already suggested in this thread. That test will > just tell you if the Python *build* is 32-bit or 64-bit. If the answer > is 32-bit, then that doesn't tell you if this is a 32-bit Python > running on a 64-bit OS. > > Trent > have you tried platform.architecture()? From paul at subsignal.org Sat Jul 5 06:39:34 2008 From: paul at subsignal.org (paul) Date: Sat, 05 Jul 2008 12:39:34 +0200 Subject: Python XML-RPC Server with clientside Javascript In-Reply-To: References: Message-ID: akineko schrieb: > Hello everyone, > > I have used Python SimpleXMLRPCServer to expose several methods to be > used. > My Python script creates a free-standing server and not a CGI script. > I have tested its exposed methods using the following Python script: > > import xmlrpclib > s = xmlrpclib.ServerProxy('http://localhost:8765') > print s.my_method() > > I tested all methods one by one and they are working as I intended. > > Now, I want to use those exposed methods from a static html file > (without any web server) using client side javascript. (i.e. Open > File... from the browser (or file://...) ) > > I found many XML-RPC examples with javascript but all of them I found > assume XML-RPC services to be deliver from a web server, such as > Apache, as a CGI. I'd think this has nothing to do with CGI vs. "free-standing", the client couldn't tell the difference anyway. It looks like you're running in the "same origin" javascript security restriction enforced by the browser. That is, the origin of your javascript is file://... and you're trying to access http://localhost:8765. This is not allowed. hth Paul From varun.consit at gmail.com Thu Jul 3 15:16:25 2008 From: varun.consit at gmail.com (varun chadha) Date: Thu, 3 Jul 2008 12:16:25 -0700 (PDT) Subject: controlling the windows Message-ID: <153e45a5-a161-4305-be6f-0fd56aee37e0@f1g2000prb.googlegroups.com> i am developing an application using Tkinter where 'next' button takes to another window and removes the first one from screen and 'back' button bring me back to previous window and so on. though i am able to move from one window to another but is unable to remove the previous one from the screen. does anybody have a idea how to do away with this problem. From jkrukoff at ltgc.com Mon Jul 28 19:26:12 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Mon, 28 Jul 2008 17:26:12 -0600 Subject: seemingly simple list indexing problem In-Reply-To: <1ad9234a-6bba-48ce-ad40-ea0aeabce492@79g2000hsk.googlegroups.com> References: <1ad9234a-6bba-48ce-ad40-ea0aeabce492@79g2000hsk.googlegroups.com> Message-ID: <1217287572.4123.118.camel@jmk> On Mon, 2008-07-28 at 16:00 -0700, iu2 wrote: > On Jul 29, 12:10 am, John Krukoff wrote: > > On Mon, 2008-07-28 at 16:24 -0500, Ervan Ensis wrote: > > > My programming skills are pretty rusty and I'm just learning Python so > > > this problem is giving me trouble. > > > > > I have a list like [108, 58, 68]. I want to return the sorted indices > > > of these items in the same order as the original list. So I should > > > return [2, 0, 1] > > > > > For a list that's already in order, I'll just return the indices, i.e. > > > [56, 66, 76] should return [0, 1, 2] > > > > > Any help would be appreciated. > > > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > > If your lists aren't so large that memory is an issue, this might be a > > good place for a variation of decorate, sort, undecorate. > > > > >>> listToSort = [ 108, 58, 68 ] > > >>> decorated = [ ( data, index ) for index, data in > > > > enumerate( listToSort ) ]>>> decorated > > > > [(108, 0), (58, 1), (68, 2)]>>> result = [ None, ] * len( listToSort ) > > >>> for sortedIndex, ( ignoredValue, originalIndex ) in > > > > enumerate( sorted( decorated ) ): > > ... result[ originalIndex ] = sortedIndex > > ...>>> result > > > > [2, 0, 1] > > > > -- > > John Krukoff > > Land Title Guarantee Company > > Inspired by your idea and the above one, here is another try: > > >>> a0 = [108, 58, 68, 108, 58] > >>> a1 = [(x, y) for x, y in enumerate(a0)] You know this line is a no-op, right? > >>> a1 > [(0, 108), (1, 58), (2, 68), (3, 108), (4, 58)] > >>> a2 = sorted(a1, lambda x, y: cmp(x[1], y[1])) If you're going to do the unpacking here for the sort, just use enumerate directly. Since this is a simple case, should use the key parameter instead of the cmp parameter for speed. Can also use the operator module to avoid a bit of lambda overhead: >>> import operator >>> a2 = sorted( enumerate( a0 ), key = operator.itemgetter( 1 ) ) > >>> a2 > [(1, 58), (4, 58), (2, 68), (0, 108), (3, 108)] > >>> a3 = [a2.index(x) for x in a1] > >>> a3 > [3, 0, 2, 4, 1] > > The idea is to make each item unique (by making it a tuple), and then > apply the naive solution. > > -- > http://mail.python.org/mailman/listinfo/python-list Using index is still kinda evil, due to the exponential time required since you're rescanning half the list (on average) to find each index value. -- John Krukoff Land Title Guarantee Company From yuxi at ece.gatech.edu Mon Jul 21 01:31:21 2008 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Mon, 21 Jul 2008 01:31:21 -0400 Subject: Python Written in C? In-Reply-To: References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> Message-ID: Grant Edwards wrote: > On 2008-07-21, Dan Upton wrote: > >>>> REAL WORLD programmers who want to be generally useful go and >>>> learn C#. >>> No: Real programmers first eat a quiche and then return to >>> their Pascal programming. >> Bah, new-fangled languages like Pascal... Real programmers >> write Fortran. > > Using punch-cards and paper-tape. Real programmers can edit > their programs with a pointy stick and some home-made > sticky-tape. > Bah. Butterflies! http://xkcd.com/378/ From patf at well.com Mon Jul 28 19:41:36 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 16:41:36 -0700 (PDT) Subject: Download excel file from web? References: <6f6vhlFa7anrU1@mid.uni-berlin.de> <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> <19fa0bb2-e101-47c9-84d4-1bf05d08ba39@b2g2000prf.googlegroups.com> Message-ID: On Jul 28, 4:20?pm, "Guilherme Polo" wrote: > On Mon, Jul 28, 2008 at 8:04 PM, p... at well.com wrote: > > On Jul 28, 3:52 pm, "Guilherme Polo" wrote: > >> On Mon, Jul 28, 2008 at 7:43 PM, p... at well.com wrote: > >> > On Jul 28, 3:33 pm, "p... at well.com" wrote: > >> >> On Jul 28, 3:29 pm, "Diez B. Roggisch" wrote: > > >> >> > p... at well.com schrieb: > > >> >> > > On Jul 28, 3:00 pm, "p... at well.com" wrote: > >> >> > >> Hi - experienced programmer but this is my first Python program. > > >> >> > >> This URL will retrieve an excel spreadsheet containing (that day's) > >> >> > >> msci stock index returns. > > >> >> > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > >> >> > >> Want to write python to download and save the file. > > >> >> > >> So far I've arrived at this: > > >> >> > >> [quote] > >> >> > >> # import pdb > >> >> > >> import urllib2 > >> >> > >> from win32com.client import Dispatch > > >> >> > >> xlApp = Dispatch("Excel.Application") > > >> >> > >> # test 1 > >> >> > >> # xlApp.Workbooks.Add() > >> >> > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > >> >> > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > >> >> > >> # xlBook = xlApp.ActiveWorkbook > >> >> > >> # xlBook.SaveAs(Filename='C:\\test.xls') > > >> >> > >> # pdb.set_trace() > >> >> > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> >> > >> excel? > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional') > >> >> > >> # test 2 - returns check = False > >> >> > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > >> >> > >> indexperf/excel? > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > >> >> > >> xlApp = response.fp > >> >> > >> print(response.fp.name) > >> >> > >> print(xlApp.name) > >> >> > >> xlApp.write > >> >> > >> xlApp.Close > >> >> > >> [/quote] > > >> >> > > Woops hit Send when I wanted Preview. ?Looks like the html [quote] tag > >> >> > > doesn't work from groups.google.com (nice). > > >> >> > > Anway, in test 1 above, I determined how to instantiate an excel > >> >> > > object; put some stuff in it; then save to disk. > > >> >> > > So, in theory, I'm retrieving my excel spreadsheet with > > >> >> > > response = urllib2.urlopen() > > >> >> > > Except what then do I do with this? > > >> >> > > Well for one read some of the urllib2 documentation and found the > >> >> > > Request class with the method has_data() on it. ?It returns False. > >> >> > > Hmm that's not encouraging. > > >> >> > > I supposed the trick to understand what urllib2.urlopen is returning > >> >> > > to me; rummage around in there; and hopefully find my excel file. > > >> >> > > I use pdb to debug. ?This is interesting: > > >> >> > > (Pdb) dir(response) > >> >> > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > >> >> > > 'code', ' > >> >> > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > >> >> > > 'readline', ' > >> >> > > readlines', 'url'] > >> >> > > (Pdb) > > >> >> > > I suppose the members with __*_ are methods; and the names without the > >> >> > > underbars are attributes (variables) (?). > > >> >> > No, these are the names of all attributes and methods. read is a method, > >> >> > for example. > > >> >> right - I got it backwards. > > >> >> > > Or maybe this isn't at all the right direction to take (maybe there > >> >> > > are much better modules to do this stuff). ?Would be happy to learn if > >> >> > > that's the case (and if that gets the job done for me). > > >> >> > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty > >> >> > clear on this: > > >> >> > """ > >> >> > This function returns a file-like object with two additional methods: > >> >> > """ > > >> >> > And then for file-like objects: > > >> >> >http://docs.python.org/lib/bltin-file-objects.html > > >> >> > """ > >> >> > read( ? [size]) > >> >> > ? ? ?Read at most size bytes from the file (less if the read hits EOF > >> >> > before obtaining size bytes). If the size argument is negative or > >> >> > omitted, read all data until EOF is reached. The bytes are returned as a > >> >> > string object. An empty string is returned when EOF is encountered > >> >> > immediately. (For certain files, like ttys, it makes sense to continue > >> >> > reading after an EOF is hit.) Note that this method may call the > >> >> > underlying C function fread() more than once in an effort to acquire as > >> >> > close to size bytes as possible. Also note that when in non-blocking > >> >> > mode, less data than what was requested may be returned, even if no size > >> >> > parameter was given. > >> >> > """ > > >> >> > Diez > > >> >> Just stumbled upon .read: > > >> >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> >> excel? > >> >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> >> +25%2C+2008&export=Excel_IEIPerfRegional').read > > >> >> Now the question is: what to do with this? ?I'll look at the > >> >> documentation that you point to. > > >> >> thanx - pat > > >> > Or rather (next iteration): > > >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > excel? > >> > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > >> > The file is generally something like 26 KB so specifying 1,000,000 > >> > seems like a good idea (first approximation). > > >> > And then when I do: > > >> > print(response) > > >> > I get a whole lot of garbage (and some non-garbage), so I know I'm > >> > onto something. > > >> > When I read the .read documentation further, it says that read() has > >> > returned the data as a string object. ?Now - how do I convince Python > >> > that the string object is in fact an excel file - and save it to disk? > > >> You don't need to convince Python, just write it to a file. > >> More reading for you:http://docs.python.org/tut/node9.html > > >> > pat > >> > -- > >> >http://mail.python.org/mailman/listinfo/python-list > > >> -- > >> -- Guilherme H. Polo Goncalves > > > OK: > > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > > excel? > > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > # print(response) > > f = open("c:\\msci.xls",'w') > > f.write(response) > > I would initially change that to: > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&...) > > f = open("c:\\msci.xls", "wb") > for line in response: > ? ? f.write(line) > f.close() > > and then.. > > > > > OK this makes the file, and there's a c:\msci.xls in place and it's > > about the right size. But whether I make the second param to open 'w' > > or 'wb', when I try to open msci.xls from the Windows file explorer, > > excel tells me that the file is corrupted. > > try it. > > > > > pat > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves A simple f.write(response) does work (click on a single row in Excel and you get a single row). But I can see that what you recommend Guilherme is probably safer - thanx. pat From vinay_sajip at yahoo.co.uk Mon Jul 14 09:58:46 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Mon, 14 Jul 2008 06:58:46 -0700 (PDT) Subject: logging via SocketHandler and TCPserver References: Message-ID: <81929250-449b-4686-acf3-dcc0095e341a@d1g2000hsg.googlegroups.com> On Jul 13, 9:25 pm, Larry Bates wrote: > Every time I look at theloggingmodule (up until now) I've given up and > continue to use my home-grown logger that I've been using for years. I'm not > giving up this time ;-) > > I find that I REALLY need to be able to monitor LOTS of running > programs/processes and thought it would be nice to have them use SocketHandlerloggingand then I would write TCPServer to accept the log messages for > real-time monitoring. I Googled (is that now a verb?) for several hours and > came up with some code that I've turned in to something that works, but I can't > figure out how to disconnect the server once it is connected The goal is to be > able to start TCPServer, monitor the log messages sent via SocketHandler logger, > disconnect, and move to the next application. Eventually I would like to wrap a > GUI around all of this for monitoring a complex web application. > > Everything works, it just appears that I get into the while loop in > LogRecordStreamHandler.handle and it never breaks out (until I kill the client). > I can't seem to do anything with the LogRecordSocketReceiver.abort attribute to > make it quit. > > I'm sure it is something simple (stupid?), but I've spent about 4 hours and I'm > not getting anywhere. > > Thanks in advance for any assistance. > > Regards, > Larry > > Below is my code: > > import sys > import time > importlogging > > if sys.argv[1] == 'client': > importlogging.config > > logging.config.fileConfig("logging.conf") > > #create logger > logger =logging.getLogger("VESconsole") > > while 1: > logger.debug("debug message") > logger.info("info message") > logger.warn("warn message") > logger.error("error message") > logger.critical("critical message") > time.sleep(2) > > elif sys.argv[1] == 'server': > import cPickle > importlogging.handlers > import SocketServer > import struct > import signal > > class LogRecordStreamHandler(SocketServer.StreamRequestHandler): > """Handler for a streamingloggingrequest. > > This basically logs the record using whateverloggingpolicy is > configured locally. > """ > > def handle(self): > """ > Handle multiple requests - each expected to be a 4-byte length, > followed by the LogRecord in pickle format. Logs the record > according to whatever policy is configured locally. > """ > while 1: > chunk = self.connection.recv(4) > if len(chunk) < 4: > break > > slen = struct.unpack(">L", chunk)[0] > chunk = self.connection.recv(slen) > while len(chunk) < slen: > chunk = chunk + self.connection.recv(slen - len(chunk)) > > obj = self.unPickle(chunk) > record =logging.makeLogRecord(obj) > self.handleLogRecord(record) > > def unPickle(self, data): > return cPickle.loads(data) > > def handleLogRecord(self, record): > t = time.strftime('%a, %d %b %y %H:%M:%S', > time.localtime(record.created)) > > print "%s %s" % (t, record.getMessage()) > > class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer): > """simple TCP socket-basedloggingreceiver suitable for testing. > """ > > allow_reuse_address = 1 > > def __init__(self, host='localhost', > port=logging.handlers.DEFAULT_TCP_LOGGING_PORT, > handler=LogRecordStreamHandler): > > SocketServer.ThreadingTCPServer.__init__(self, > (host, port), > handler) > self.abort = 0 > self.timeout = 1 > self.logname = None > > def serve_until_stopped(self): > import select > abort = 0 > while not abort: > rd, wr, ex = select.select([self.socket.fileno()], > [], [], > self.timeout) > if rd: > self.handle_request() > > abort = self.abort > > print "serve_until_stopped exiting" > > # > # Start ThreadingTCPServer instance to accept SocketHandler log > # messages from client. > # > tcpserver = LogRecordSocketReceiver() > print "Starting ThreadingTCPServer..." > tcpserver.serve_until_stopped() > > ''' > #-----logging.conf----- > [loggers] > keys=root > > [handlers] > keys=socketHandler > > [formatters] > keys=simpleFormatter > > [logger_root] > level=DEBUG > handlers=socketHandler > > [handler_socketHandler] > class=handlers.SocketHandler > level=DEBUG > args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT) > host=localhost > port=DEFAULT_TCP_LOGGING_PORT > > [formatter_simpleFormatter] > format=%(asctime)s - %(name)s - %(levelname)s - %(message)s > datefmt= > ''' Hi Larry, You can make the server quit (set abort to True) by changing the logic of the server appropriately. In your script (as in the example at http://docs.python.org/lib/network-logging.html), nothing sets server.abort, so the server never quits. If you were to insert a line "self.server.abort = True" before the break in the check "if len(chunk) < 4:", then the server will quit whenever a message shorter than 4 bytes is received; ordinarily, a SocketHandler will always send a 4-byte length followed by content. You can test this easily as follows: Run the server after modifying the script as described above. Run the client and observe some messages printed by the server. Kill the client. The server should still be waiting for events from clients, though it might quit if, when you kill the client, a truncated message is sent. Run "telnet localhost 9020" and type a character. The server should quit. If you make the "quitting" message a raw_input() call, then you can see that the server has exited normally via the abort flag. Don't forget, the receiver can receive events from several applications. You don't need to disconnect and reconnect. Simply have each event sent by an app identify the app in some way - e.g. the logger name could be "VESconsole.app1" for one app and "VESconsole.app2" in another. In your server's handleRecord code, you can get the logger name, decode the sending app from that and route the event appropriately. Another approach is to subclass SocketHandler and override the makePickle method. This determines the wire format of the event sent to the server, and if you change the wire format and modify the server end to suit, then you can have any amount of flexibility in the communications between the applications generating the events and the server collating them. I'm not sure why you've had so much trouble with logging in the past, or why it took several hours of Googling to find a solution relating to logging events across a network. I Googled for "python network logging" and the link in the Python docs which I referenced earlier was the first result, and hence also available via the "I'm Feeling Lucky" button ;-) Best regards, Vinay From deets at nospam.web.de Thu Jul 31 08:18:40 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 14:18:40 +0200 Subject: working pylint anyone? References: <6fdf17Fb2bboU1@mid.uni-berlin.de> Message-ID: <6fdovaFb2tndU1@mid.uni-berlin.de> Stefan Rank wrote: > on 31.07.2008 11:29 Diez B. Roggisch said the following: > >> >> The packaged version of pylint (0.13.2) fails with this error (last >> line): >> > >> >> So - anybody out here having an actually working pylint config and can >> tell me what versions work together? I've become pretty dependend on it >> to be honest... > > Three installations of pylint 0.14.0 that I have access to from here: > > pylint.bat 0.14.0, > astng 0.17.2, common 0.27.0 > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > (Intel)] > > pylint 0.14.0, > astng 0.17.2, common 0.31.0 > Python 2.5.2 (r252:60911, Jul 23 2008, 00:17:15) > [GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] > > pylint 0.14.0, > astng 0.17.2, common 0.27.0 > Python 2.5.1 (r251:54863, Jul 11 2007, 15:07:18) > [GCC 3.3.5 (Debian 1:3.3.5-13)] > > > All of them installed using good old setup.py (times 3). > easy_install does not work as you noted. Thanks, that helped. I got the same errors - but these are because of custom init-hooks I created. Now I need to debug these.. thanks! Diez From larry.bates at websafe.com` Sat Jul 26 09:59:18 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 26 Jul 2008 08:59:18 -0500 Subject: Stripping parts of a path In-Reply-To: References: Message-ID: Tim Cook wrote: > Hi All, > > I just ran into an issue with the rstrip method when using it on path > strings. > > When executing a function I have a need to strip off a portion of the > current working directory and add on a path to a log file. Initially > this worked great but then I added a branch in SVN which caused the path > to contain 'LNCCWorkshop'. The rstrip() then began removing the > characters 'shop' leaving an incorrect path to the log file. When I > hard coded this path it worked okay but then did the same thing later in > the file when I needed to point to a database. The code worked fine with > a different path. Here are some code fragments. > > logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/at_build_errors.log' > > this worked when the path was: > /home/tim/ref_impl_python/TRUNK/oship/src/oship/atbldr > > the code above returns: > /home/tim/ref_impl_python/TRUNK/oship/log/at_build_errors.log > > but when I tried a branches version that has the path: > /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/src/oship/atbldr > > it SHOULD return: > /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/log/at_build_errors.log > > but I get: > /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log > > logfile=os.getcwd() > print logfile is correct; but when I add the .rstrip('src/oship/atbldr') > it also strips the 'shop' off of LNCCWorkshop and returns > /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log > > I had two other people looking at this as we did troubleshooting and we > could not determine the cause. It is repeatable with this path name. > In resolution I renamed the branch to just LNCC and it works fine. > > Thoughts? > > Tim > > > > > > > Always helps to consult documentation when things don't work. Help on built-in function rstrip: rstrip(...) S.rstrip([chars]) -> string or unicode Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping If you give chars to rstrip() it removes all those characters from the string not that substring. -Larry From benjamin.kaplan at case.edu Mon Jul 7 21:05:58 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 7 Jul 2008 21:05:58 -0400 Subject: How to make python scripts .py executable, not bring up editor In-Reply-To: References: Message-ID: On Mon, Jul 7, 2008 at 5:56 PM, korean_dave wrote: > >From command Prompt, i type in a script, "tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? > -- > http://mail.python.org/mailman/listinfo/python-list > You need to set the file associations to use python.exe, instead of PythonWin. In Vista, you can to this from Control Panel -> Programs -> Default Programs. -------------- next part -------------- An HTML attachment was scrubbed... URL: From larry.bates at websafe.com` Tue Jul 15 23:09:16 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 22:09:16 -0500 Subject: graphing lifelines In-Reply-To: References: Message-ID: E. J. Gold is the Hi-Tech Shaman wrote: > On Jul 15, 3:38 pm, Larry Bates wrote: > >> Certainly a "Hi-Tech Shaman" can whip something up to do this, right? >> > > Yes, well E.J. Gold is the Hi-Tech Shaman. I'm Terrence Brannon, > stating that fact :) > > So, maybe EJ could whip up such a thing :) > > I like the sci.math answer I got the best and will go with that > approach - > http://groups.google.com/group/sci.math/browse_thread/thread/09b254718d4cbfeb# Hey you're the one using his email address ;-). -Larry From __peter__ at web.de Fri Jul 4 04:33:20 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Jul 2008 10:33:20 +0200 Subject: Singleton implementation problems References: <87abgy2kcu.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Peter Otten <__peter__ at web.de> writes: > >> The problem is the structure of your program. The myset module is >> imported twice by Python, once as "myset" and once as "__main__". > > Yes, this is the problem. Each module imports the other. > >> Therefore you get two distinct MySet classes, and consequently two >> distinct MySet.__instance class attributes. > > Are you sure? This goes against my understanding: that 'import foo' > will not re-import a module that's already been imported, but will > instead simply return the existing module. The main script is put into the sys.modules cache as "__main__", not under the script's name. Therefore the cache lookup fails. > So, I think if one evaluated 'myset is __main__', you'd find they are > exactly the same module under different names; and therefore that > there is only *one* instance of 'MySet', again under two names. No: $ cat tmp.py import tmp import __main__ print tmp is __main__ $ python tmp.py False False Peter From pavlovevidence at gmail.com Wed Jul 30 21:10:08 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 30 Jul 2008 18:10:08 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> <7f4a3d37-e551-4e21-b660-3618016cb67b@z6g2000pre.googlegroups.com> Message-ID: <035ef824-0fc2-408e-a6fc-e35df45ab625@d45g2000hsc.googlegroups.com> On Jul 30, 11:07 am, Terry Reedy wrote: > Carl Banks wrote: > > That's not what I was asking for. I was asking for a use case for "if > > x" that can't be replaced by a simple explicit test. Your example > > didn't satisfy that. > > But I believe my example of an iterator with __bool__ but not with > __len__ does. And I believe I followed up to your post saying as much. :) Carl Banks From socyl at 987jk.com.invalid Tue Jul 29 11:20:38 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 15:20:38 +0000 (UTC) Subject: DB access without object-relation mapping? Message-ID: Python noob here. I want to write a script that creates and populates a simple Postgres database. The word on the street is to use something like SQLAlchemy for database access in Python, but my experience in the past with packages that perform automated SQL generation has been awful, so I always return to lighter-weight solutions that allow me to write my own SQL. (E.g. when coding in Perl I've used Perl's DBI package and drivers, rather than the likes of Class::DBI.) So what's the standard Python way to send SQL directly to a Postgres database and get back results? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From martinskou at gmail.com Tue Jul 22 08:08:00 2008 From: martinskou at gmail.com (martinskou at gmail.com) Date: Tue, 22 Jul 2008 05:08:00 -0700 (PDT) Subject: Web Page Construction in Python References: Message-ID: Also, look at: http://www.djangoproject.com/ /Martin From support.desk.ipg at gmail.com Wed Jul 9 15:39:09 2008 From: support.desk.ipg at gmail.com (Support Desk) Date: Wed, 9 Jul 2008 14:39:09 -0500 Subject: variable question Message-ID: <01da01c8e1fb$7615a4f0$a701a8c0@office.ipglobal.net> I am trying to assign a variable using an if / else statement like so: If condition1: Variable = something If condition2: Variable = something else Do stuff with variable. But the variable assignment doesn't survive outside the if statement. Is there any better way to assign variables using an if statement or exception so I don't have to write two almost identical if statements. This is probably a dumb question. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bcurtu at gmail.com Tue Jul 22 06:19:00 2008 From: bcurtu at gmail.com (bcurtu) Date: Tue, 22 Jul 2008 03:19:00 -0700 (PDT) Subject: DB Pool Message-ID: <40f3a61b-8c37-4e26-90f6-02de760ce00e@c58g2000hsc.googlegroups.com> Hi, I use MySQLdb lib to access my DB, because I want to opttimize my sql queries. The application I'm working on has quite a few traffic load, so I want to minimize the time of creating/destroying cursors: My typical code is sth like: cursor=con.cursor() cursor.execute(sql) all= cursor.fetchall() cursor.close() So, the question is... how can I minimize this cost? I was thinking on Connection Pools, but I didn't find any good documentation or sample. Any idea? From ali.sakebi at gmail.com Wed Jul 16 13:48:13 2008 From: ali.sakebi at gmail.com (Alis) Date: Wed, 16 Jul 2008 10:48:13 -0700 (PDT) Subject: Is there any component-oriented (non-MVC) web framework available for Python? Message-ID: <5fdd1388-bb1e-4a59-8fd1-2aa1ce7fa6e0@79g2000hsk.googlegroups.com> Hi Is there any component-oriented (non-MVC) web framework available for Python? That is something like Apache Wicket, Tapestry or JSF, but I need it to be in Python. Regards, Ali From castironpi at gmail.com Mon Jul 21 15:08:43 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 21 Jul 2008 12:08:43 -0700 (PDT) Subject: persistent deque (continued) Message-ID: <4c985e86-c0c4-4cb3-b7ce-f8e105b7f85d@y21g2000hsf.googlegroups.com> Some time ago, I was asking about the feasibility of a persistent deque, a double-ended queue. It runs into the typical space allocation problems. If you're storing a pickle, you have to allocate and fragment the file you've opened, since pickles can be variable-length strings; i.e. if the new data is too long, blank out its entry, and grow the file. If you're storing a data-type, you lose Python's dynamic-type advantages, as well as its long integers, as they can be any length. If you change the object in the deque, such as when using any mutable type, you have to update the container too. Does anyone have any experience storing pickles (I am aware of the similarities to shelf) to a database? Can the file system facilitate the variable-length string problem? How feasible is a length-of-length - length - data solution to the unbounded integer problem? Is there any alternative to completely re-pickling a large (say 1k pickled) object you only change slightly? What other issues are there? Is a hybrid-storage type possible, that stores the contents of its Python-allocated memory block to disk, including reference count, even if it's a lot slower? The object could not contain any references to objects not allocated on disk. A first approach is for the file to look like this: 00 data 01 data 02 01 data 03 data 04 02 data 05 data 06 Append would add: 03 data 07 data 08 AppendLeft would add: -01 data 09 data 0a Pop would remove 03, PopLeft would remove -01. You would need a length-and-head index to make 'rotate' available. Remove would run a worst-case risk of renumbering half of the indices stored, plus a rotate. From qvx3000 at gmail.com Wed Jul 30 03:02:53 2008 From: qvx3000 at gmail.com (qvx) Date: Wed, 30 Jul 2008 00:02:53 -0700 (PDT) Subject: I CAN connect socket to any localhost port but I shouldn't be able to References: <13c78fbf-751f-4d70-a012-53aa1eb64e53@79g2000hsk.googlegroups.com> Message-ID: <55820cec-e899-406b-8bb9-00b4028a3ca7@z72g2000hsb.googlegroups.com> On Jul 30, 4:48?am, "Gabriel Genellina" wrote: > En Tue, 29 Jul 2008 14:56:08 -0300, qvx escribi : > > > I don't have server listening on port 8084 but I can open socket to it > > (and to many other ports, tested for all<8000) > > Your example fails -as expected- on my PC running Python 2.5.2 + Windows ? > XP SP2. It may be something specific to your setup or your platform. > > py> test(8084) > Traceback (most recent call last): > ? ?File "", line 1, in > ? ?File "", line 5, in test > ? ?File "", line 1, in connect > socket.error: (10061, 'Connection refused') > -- > Gabriel Genellina Thanks for confirmation. There is a similar function in CherryPy server which won't start anymore but it used to. I am currently examining Windows and any recently installed software. -- Tvrtko From socyl at 987jk.com.invalid Thu Jul 17 15:11:36 2008 From: socyl at 987jk.com.invalid (kj) Date: Thu, 17 Jul 2008 19:11:36 +0000 (UTC) Subject: x, = y (???) Message-ID: I just came across an assignment of the form x, = y where y is a string (in case it matters). 1. What's the meaning of the comma in the LHS of the assignment? 2. How could I have found this out on my own? (Regarding (2) above, I consulted the index of several Python reference books but I could not find the answer to (1). I hope to find a better Python reference!) TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From paddy3118 at googlemail.com Fri Jul 18 03:04:04 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 18 Jul 2008 00:04:04 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Message-ID: <7ac1b818-8aa9-478f-a922-82baf0d51c5b@w39g2000prb.googlegroups.com> On Jul 16, 11:20?pm, Craig Allen wrote: > Hey, forgive me for just diving in, but I have a question I was > thinking of asking on another list but it really is a general question > so let me ask it here. ?It's about how to approach making singletons. Hi Craig, This might be good for a general background on Design Patters in Python: http://uk.youtube.com/watch?v=0vJJlVBVTFg - Paddy. From matthieu.brucher at gmail.com Wed Jul 23 09:06:34 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Wed, 23 Jul 2008 15:06:34 +0200 Subject: Python Written in C? In-Reply-To: References: Message-ID: 2008/7/23 mk : >> Actually, all of the compilers I'm familiar with (gcc and a >> handful of cross compilers for various microprocessors) >> translate from high-level languages (e.g. C, C++) into >> assembly, which is then assembled into relocatable object >> files, which are then linked/loaded to produce machine >> language. > > Doesn't g++ translate C++ into C and then compile C? > > Last I heard, most C++ compilers were doing that. GCC translates every language into its one as a tree, which is then translated to assembly. Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher From robert.rawlins at thinkbluemedia.co.uk Thu Jul 17 11:23:47 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 17 Jul 2008 16:23:47 +0100 Subject: Unusual Exception Behaviour Message-ID: <002d01c8e821$1b870f20$52952d60$@rawlins@thinkbluemedia.co.uk> Hello Chaps, I have an unusual situation with my application which I've also seen once or twice in the past but never found a solution too. Basically the application stops properly reporting Exceptions when they are thrown. My application logs extensively to a file using the python logging module, when an exception is throw all the log data starts being thrown to the command prompt instead of the file, however, I don't get any actual exception information output. I have looked through the application for any unusual or bare try/except blocks that don't actually do anything with the except just in case any of them are causing the issue but can't seem to see any. This little issue makes debugging my application VERY hard, when running the app I can see it crash, but I get no information as to where the exception is being thrown from, as you can imagine, quite frustrating. Even when throwing my own exceptions just for testing like so: Raise Exception, "This is a test exception." In certain parts of the application it doesn't print the exception to screen, but all subsequent requests to the logger seem to print out at the command prompt. I would really love some suggestions on what might be causing this. Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From moogyd at yahoo.co.uk Sun Jul 13 03:23:40 2008 From: moogyd at yahoo.co.uk (moogyd at yahoo.co.uk) Date: Sun, 13 Jul 2008 00:23:40 -0700 (PDT) Subject: Beginner Question : Iterators and zip References: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> Message-ID: <0ea30e6f-fcf4-4f39-a091-10b2a2178efd@l64g2000hse.googlegroups.com> On 12 Jul, 21:50, "bruno.desthuilli... at gmail.com" wrote: > On 12 juil, 20:55, moo... at yahoo.co.uk wrote: > > > > zip is (mostly) ok. What you're missing is how to use it for any > arbitrary number of sequences. Try this instead: > > >>> lists = [range(5), range(5,11), range(11, 16)] > >>> lists > > [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]>>> for item in zip(*lists): > > ... print item > ... > (0, 5, 11) > (1, 6, 12) > (2, 7, 13) > (3, 8, 14) > (4, 9, 15) What is this *lis operation called? I am having trouble finding any reference to it in the python docs or the book learning python. > > Any other comments/suggestions appreciated. > > There's a difflib package in the standard lib. Did you give it a try ? I'll check it out, but I am a newbie, so I am writing this as a (useful) learning excercise. Thanks for the help Steven From dp_pearce at hotmail.com Wed Jul 9 11:44:38 2008 From: dp_pearce at hotmail.com (dp_pearce) Date: Wed, 9 Jul 2008 08:44:38 -0700 (PDT) Subject: Anyone happen to have optimization hints for this loop? Message-ID: <32fd142e-b198-430e-888b-01aee4e63ac0@c65g2000hsa.googlegroups.com> I have some code that takes data from an Access database and processes it into text files for another application. At the moment, I am using a number of loops that are pretty slow. I am not a hugely experienced python user so I would like to know if I am doing anything particularly wrong or that can be hugely improved through the use of another method. Currently, all of the values that are to be written to file are pulled from the database and into a list called "domainVa". These values represent 3D data and need to be written to text files using line breaks to seperate 'layers'. I am currently looping through the list and appending a string, which I then write to file. This list can regularly contain upwards of half a million values... count = 0 dmntString = "" for z in range(0, Z): for y in range(0, Y): for x in range(0, X): fraction = domainVa[count] dmntString += " " dmntString += fraction count = count + 1 dmntString += "\n" dmntString += "\n" dmntString += "\n***\n dmntFile = open(dmntFilename, 'wt') dmntFile.write(dmntString) dmntFile.close() I have found that it is currently taking ~3 seconds to build the string but ~1 second to write the string to file, which seems wrong (I would normally guess the CPU/Memory would out perform disc writing speeds). Can anyone see a way of speeding this loop up? Perhaps by changing the data format? Is it wrong to append a string and write once, or should hold a file open and write at each instance? Thank you in advance for your time, Dan From brad at 16systems.com Fri Jul 18 10:12:34 2008 From: brad at 16systems.com (Brad) Date: Fri, 18 Jul 2008 10:12:34 -0400 Subject: Regular expression help In-Reply-To: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> References: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> Message-ID: nclbndk759 at googlemail.com wrote: > Hello, > > I am new to Python, with a background in scientific computing. I'm > trying to write a script that will take a file with lines like > > c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647 > 3pv=0 > > extract the values of afrac and etot... Why not just split them out instead of using REs? fp = open("test.txt") lines = fp.readlines() fp.close() for line in lines: split = line.split() for pair in split: pair_split = pair.split("=") if len(pair_split) == 2: try: print pair_split[0], "is", pair_split[1] except: pass Results: IDLE 1.2.2 ==== No Subprocess ==== >>> afrac is .7 mmom is 0 sev is -9.56646 erep is 0 etot is -11.020107 emad is -3.597647 3pv is 0 >>> From mrkafk at gmail.com Fri Jul 11 13:06:54 2008 From: mrkafk at gmail.com (mk) Date: Fri, 11 Jul 2008 19:06:54 +0200 Subject: Using SWIG to build C++ extension In-Reply-To: References: Message-ID: And what's infuriating is that the .o files do contain the necessary symbol: # grep _Z13edit_distanceRSsS_ * Binary file edit_distance.o matches Binary file _edit_distance.so matches Binary file edit_distance_wrap.o matches From bdesth.quelquechose at free.quelquepart.fr Sun Jul 27 14:58:16 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Jul 2008 20:58:16 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <78446ee7-b035-49a8-ac73-46895391543d@o40g2000prn.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <87abg7pe16.fsf@benfinney.id.au> <78446ee7-b035-49a8-ac73-46895391543d@o40g2000prn.googlegroups.com> Message-ID: <488ce13e$0$11953$426a34cc@news.free.fr> Jordan a ?crit : (snip) about Python Zen: > Perhaps we're just looking at an instance of a wider problem - smart > people boil good ideas down into short slogans, which are nice and > memorable and somewhat helpful, but can lead to bad consequences when > lots of others start overusing or misunderstanding them. This is true for just each and every "golden rule" in programming - like "goto are evil", "globals are evil", "side effects are evil", "early returns are evil", "public attributes are evil", etc... If you blindly apply any rule without understanding the rationales behind it, then you're into cargo-cult thinking. And once you understand the reasons that led someone to formulate such a rule, you just don't have to bother about it anymore - you just use your common sense to do what seems appropriate in a given situation. From roy at panix.com Tue Jul 29 21:20:53 2008 From: roy at panix.com (Roy Smith) Date: Tue, 29 Jul 2008 21:20:53 -0400 Subject: [unittest] Run setUp only once References: <871w1cr49a.fsf@nokile.rath.org> Message-ID: In article <871w1cr49a.fsf at nokile.rath.org>, Nikolaus Rath wrote: > But at least this variation doesn't work, because unittest apparently > also creates two separate TwoTests instances for the two tests. Isn't > there some way to convince unittest to reuse the same instance instead > of trying to solve the problem in the test code itself? Nope. It's a fundamental part of the Xunit design that every test gets a complete, virgin environment in which to run. The sample code that Jean-Paul gave you: > class TwoTests(unittest.TestCase): > setUpResult = None > > def setUp(self): > if self.setUpResult is None: > self.setUpResult = computeIt() does indeed create two instances of TwoTests, but it only calls computeIt() once, into which (presumably) all the expensive stuff has been refactored. This is, of course, a violation of the rule that says each test must run in a clean environment, but if you want to violate that rule, that's up to you. Presumably you know your system and have made an informed decision as a consenting adult that you understand the risks and this is what you want to do. Another variation on this would be to take this code out of setUp(), and instead create a singleton class (there's a good recipe for this on active state) which does your shared setup. Then in the two tests which need this, explicitly call the singleton factory. I think this is a little cleaner than Jean-Paul's way, because at least it isolates the shared stuff to exactly the two tests which need it. From bwgoudey at gmail.com Wed Jul 9 01:26:36 2008 From: bwgoudey at gmail.com (Benjamin Goudey) Date: Tue, 8 Jul 2008 22:26:36 -0700 (PDT) Subject: Returning the positions of a list that are non-zero Message-ID: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> I have a very large list of integers representing data needed for a histogram that I'm going to plot using pylab. However, most of these values (85%-95%) are zero and I would like to remove them to reduce the amount of memory I'm using and save time when it comes to plotting the data. To do this, I'm trying to find the best way to remove all of the zero values and produce a list of indices of where the non-zero values used to be. For example, if my original list is [0,0,1,2,1,0,0] I would like to produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices of where the non-zero values used to be). Removing non-zero values is very easy but determining the indicies is where I'm having difficulty. Thanks in advance for any help From robert.rawlins at thinkbluemedia.co.uk Tue Jul 15 08:51:25 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 15 Jul 2008 13:51:25 +0100 Subject: Logging in __del__() In-Reply-To: References: <17056.2125546441$1216121658@news.gmane.org> Message-ID: <016e01c8e679$7ddc4cc0$7994e640$@rawlins@thinkbluemedia.co.uk> Hi Fredrik, > When the application is running, or when it is shutting down? This is interesting, I did a test where I explicitly destroyed the instance using 'del my_instance' while the application was running and no error was thrown. It would see you are right, when the application ends it kills the logging module before my classes. I think you're on the right approach just try/except it and leave it be. Am I right in thinking that Python destroys instances of classes when it deems they are no longer needed? I shouldn't have to explicitly delete the classes, right? Thanks Fredrik, Robert From Russ.Paielli at gmail.com Mon Jul 28 01:07:31 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 22:07:31 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> <6a5506b1-632e-4bf6-b0ce-4d51d1751aa9@i24g2000prf.googlegroups.com> <8b4b11c3-e306-4fe7-82d1-0a948c725f2f@r15g2000prd.googlegroups.com> <239a084f-b73d-4c20-aaaf-bbd05d452638@a2g2000prm.googlegroups.com> <8f675d65-e302-4428-a4bc-f494b230cb59@w1g2000prk.googlegroups.com> Message-ID: <744c27d4-e166-4b3a-9c2c-d4bf1a207fb8@a2g2000prm.googlegroups.com> On Jul 27, 9:44 pm, alex23 wrote: > > > > > On Jul 27, 4:26 pm, "Russ P." wrote: > > > > > > Terry Reedy wrote: > > > > > > > The use of '.' has been suggested before and rejected. > > > > > > Where and why? > > Dude, I agree with Guido completely on this one. You > > seem to be clueless about the issue here. You're the > > one with the reading comprehension problem. Please > > quit wasting my time with your irrelevant crap. > > I pointed you at a thread -where it had been suggested and rejected-. > And I'm the clueless one? > > I don't think I'm the one wasting anyone's time here, but fine. I've > got far better things to do with my time than waste it talking to you. What was "suggested in rejected" on the thread you pointed me to was not what I suggested. Not even close. Get it, genius? From stefan_ml at behnel.de Fri Jul 18 11:40:44 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 18 Jul 2008 17:40:44 +0200 Subject: Core Dump - Segmentation Fault -Newbie In-Reply-To: References: <8ba4373d-3d97-4e9a-a15e-723f6818c757@k36g2000pri.googlegroups.com> <4880A0FA.6030603@behnel.de> Message-ID: <4880B97C.2050708@behnel.de> Doug Morse wrote: > Well, I must be missing something re: why Stefan states that you are using > Windows. I don't see that stated in your original post It's stated in the mail headers of his post, though. That's the problem with newbies - you never know where that stops being right. Stefan From fredrik at pythonware.com Tue Jul 15 07:10:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2008 13:10:15 +0200 Subject: why is "self" used in OO-Python? In-Reply-To: References: Message-ID: ssecorp wrote: > def append(self, item): > self.stack.append(item) > > I can get to see the stack with var.stack but then why even implement > append when I could do self.stack.append(x) etc. > That way you could do away with OO completely. Umm. Even if you were to write that, self and stack would still be objects, and the "append" would still be a method defined by the stack object, right? What you seem to be referring to is the Law of Demeter, which is a design guideline for avoiding unnecessary coupling, not an absolute requirement for object-orientation: http://en.wikipedia.org/wiki/Law_of_Demeter As for the rest, I suspect you will have more success in using Python if you use it to write Python programs, not Java programs: http://dirtsimple.org/2004/12/python-is-not-java.html From tjreedy at udel.edu Thu Jul 3 15:52:16 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 03 Jul 2008 15:52:16 -0400 Subject: Generating list of possible configurations In-Reply-To: References: <486c7c1f$0$10446$426a74cc@news.free.fr> Message-ID: Mensanator wrote: > On Jul 3, 2:13?am, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> Terry Reedy a ?crit : >>> This has been added to itertools at least for 2.6/3.0 >> Great ! > > Well, it will be great at some point in the future > when Python 2.6/3.0 have actually been released and The betas 'have actually been released' and I am happily using 3.0. The core features that I care about have mostly been untouched and where they have, they work. > third party extensions such as gmpy have caught up. Not my personal concern. And certainly not a direct concern for nearly all uses of itertools.product. > Until then, such solutions are worthless, i.e., of no value. Why are you so anxious to generalize your personal negative views to everyone else. Worthless to you, worthwhile to me. And for someone who does not need cross-products today or in the next few months, potentially valuable information for when the final releases do arrive, maybe in September. tjr From Younger.Wang at packetfront.com Mon Jul 14 12:11:20 2008 From: Younger.Wang at packetfront.com (Younger Wang) Date: Mon, 14 Jul 2008 18:11:20 +0200 Subject: How to package a logging.config file? In-Reply-To: References: Message-ID: I had the similar question and my solution is: default_config = os.path.join(os.getcwd(), "log.config") def get_logger(name, config_file=None): if config_file: logging.config.fileConfig(config_file) else: logging.basicConfig(level=logging.INFO, format='%(levelname)s %(module)s:%(lineno)d: %(message)s') return logging.getLogger(name) I had to make this helper function because calling logging.getLogger will fail in an exception without configuring logging module. I wish it is not like that. BR Younger Wang -----Original Message----- From: python-list-bounces+younger.wang=packetfront.com at python.org [mailto:python-list-bounces+younger.wang=packetfront.com at python.org] On Behalf Of Matthew Wilson Sent: Monday, July 14, 2008 8:21 AM To: python-list at python.org Subject: How to package a logging.config file? I'm working on a package that uses the standard library logging module along with a .cfg file. In my code, I use logging.config.fileConfig('/home/matt/mypackage/matt.cfg') to load in the logging config file. However, it seems really obvious to me that this won't work when I share this package with others. I can't figure out what path to use when I load my .cfg file. Any ideas? Matt -- http://mail.python.org/mailman/listinfo/python-list From noagbodjivictor at gmail.com Tue Jul 15 11:55:23 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Tue, 15 Jul 2008 11:55:23 -0400 Subject: Is it legal to rebuild Python.exe to include Version property tab? Message-ID: I think it is. I got a bundle of Python named EnthoughtPython and the version string gave something different from original Python. -- NOAGBODJI Paul Victor From python at rcn.com Sat Jul 12 03:13:26 2008 From: python at rcn.com (Raymond Hettinger) Date: Sat, 12 Jul 2008 00:13:26 -0700 (PDT) Subject: Perfect hashing for Py References: Message-ID: On Jul 11, 3:01?pm, bearophileH... at lycos.com wrote: > I have found this perfect hash (minimal too) implementation:http://burtleburtle.net/bob/hash/perfect.html > > I have already translated part of it to D, and it seems to work well > enough. As discussed in the PyConDue, I think this may be used in > frozenset (and frozendict) to build a (minimal too?) perfect hash on > the fly, to allow (hopefully) faster retrieval of items that don't > change. A few thoughts: Objects currently have their own hash function that is independent of a given container. We also have to hash types other than strings (used in the examples in the links you provided). While a container such as a dict or set is being built, we don't even know how many unique keys there are until the container is fully populated. Set-to-set operations and set-to-dict operations get their speed from knowing that both containers use the same hash values -- this would get disrupted if each container had its own hash function. Some types like strings (especially interned strings) remember their own hash value -- this makes it very fast to look their values in a set or dict -- that would be defeated if each container has its own hash function which would need to be recomputed for every lookup. An important use case for sets is uniquification -- in that use case, speed is determined by insertion time, we just don't care about subsequent lookup time -- anything that slows down insertion (such as computing a perfect hash value) works to the detriment of that use case). In the current design, sets and dicts are never more than 2/3 full and are usually much more sparse than that -- accordingly lookups average between 1 and 1.5 probes per lookup. This is somewhat hard to beat with perfect hashing since we typically get very few collisions anyway -- so you get the cost of increased insertion time, loss of objects being able to remember their own hash, challenges with non- string keys, a more complicated algorithm, and decreased interoperability for set-to-set and set-to-dict options -- the only benefits are to reduce collisions to zero when they are already not that common. For frozensets, it may be possible to add an optimize() method that takes a completely built frozenset and optimizes its insertion order and/or increases its size to make it arbitrarily sparse. That would only be useful for cases when the costs of optimizing the table is fully repaid by an extensive number of lookups. There are use some cases where it would be pay table optimization costs in order to win decreased lookup costs, but there are plenty of use cases where that would not be a winning trade-off. So, the optimize() step would need to be optional, not builtin. Raymond FWIW, I mentioned all this at PyConDue but the message must have gotten lost. From paul at boddie.org.uk Sat Jul 19 09:43:36 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 19 Jul 2008 06:43:36 -0700 (PDT) Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> <0T56p3tmInifNv8%stesch@parsec.no-spoon.de> <6e7v9qF5q74kU1@mid.uni-berlin.de> <0T56pitfI5raNv8%stesch@parsec.no-spoon.de> Message-ID: On 17 Jul, 11:09, Fredrik Lundh wrote: > > (and the "stable release" and "much will change" stuff is pure FUD, of > course. what competing project will I find if I google your name?) That's a bit unfair. Maybe the guy was stung by previous experiences with books and certain other frameworks. It seems to me that the Django people have been quite cautious with the APIs and with their own book, but it isn't as if nothing has been changing with respect to the APIs and the preferred ways of doing things in Django. And I have to add that books which refer the reader to various Web sites in order to find out the status of the code, qualifying the prose with "by the time you read this", don't give a great impression. I can't say that the book referenced here does that, although short of a 1.0 release, I find it unlikely that the author could avoid it. Paul From dinov at exchange.microsoft.com Wed Jul 30 11:40:03 2008 From: dinov at exchange.microsoft.com (Dino Viehland) Date: Wed, 30 Jul 2008 08:40:03 -0700 Subject: interpreter vs. compiled In-Reply-To: <5be6b2bf-7bf3-42d7-9f31-5ccc886ec786@t54g2000hsg.googlegroups.com> References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> <5be6b2bf-7bf3-42d7-9f31-5ccc886ec786@t54g2000hsg.googlegroups.com> Message-ID: <7AD436E4270DD54A94238001769C2227012C9376BA99@DF-GRTDANE-MSG.exchange.corp.microsoft.com> It looks like the pickle differences are due to two issues. First IronPython doesn't have ASCII strings so it serializes strings as Unicode. Second there are dictionary ordering differences. If you just do: { 'a': True, 'b': set( ) } Cpy prints: {'a': True, 'b': set([])} Ipy prints: {'b': set([]), 'a': True} The important thing is that we interop - and indeed you can send either pickle string to either implementation and the correct results are deserialized (modulo getting Unicode strings). For your more elaborate example you're right that there could be a problem here. But the DLR actually recognizes this sort of pattern and optimizes for it. All of the additions in your code are what I've been calling serially monomorphic call sites. That is they see the same types for a while, maybe even just once as in your example, and then they switch to a new type - never to return to the old one. When IronPython gives the DLR the code for the call site the DLR can detect when the code only differs by constants - in this case type version checks. It will then re-write the code turning the changing constants into variables. The next time through when it sees the same code again it'll re-use the existing compiled code with the new sets of constants. That's still slower than we were in 1.x so we'll need to push on this more in the future - for example producing a general rule instead of a type-specific rule. But for the time being having the DLR automatically handle this has been working good enough for these situations. -----Original Message----- From: python-list-bounces+dinov=microsoft.com at python.org [mailto:python-list-bounces+dinov=microsoft.com at python.org] On Behalf Of castironpi Sent: Tuesday, July 29, 2008 11:40 PM To: python-list at python.org Subject: Re: interpreter vs. compiled I note that IronPython and Python's pickle.dumps do not return the same value. Perhaps this relates to the absence of interpreter loop. >>> p.dumps( { 'a': True, 'b': set( ) } ) IPy: '(dp0\nVb\np1\nc__builtin__\nset\np3\n((lp4\ntp5\nRp2\nsVa \np6\nI01\ns.' CPy: "(dp0\nS'a'\np1\nI01\nsS'b'\np2\nc__builtin__\nset \np3\n((lp4\ntp5\nRp6\ns." You make me think of a more elaborate example. for k in range( 100 ): i= j() g= h+ i e= f+ g c= d+ e a= b+ c Here, j creates a new class dynamically, and returns an instance of it. Addition is defined on it but the return type from it varies. If I read you correctly, IPy can leave hundreds of different addition stubs laying around at the end of the for-loop, each of which only gets executed once or twice, each of which was compiled for the exact combination of types it was called for. I might construe this to be a degenerate case, and the majority of times, you'll reexecute stubs enough to outweigh the length of time the compilation step takes. If you still do the bounds checking, it takes extra instructions (C doesn't), but operation switch-case BINARY_ADD, (PyInt_CheckExact(v) && PyInt_CheckExact(w)), and POP and TOP, are all handled by the selection of stubs from $addSite. I'm read from last April: >>> The most interesting cases to me are the 5 tests where CPython is more than 3x faster than IronPython and the other 5 tests where IronPython is more than 3x faster than CPython. CPython's strongest performance is in dictionaries with integer and string keys, list slicing, small tuples and code that actually throws and catches exceptions. IronPython's strongest performance is in calling builtin functions, if/then/else blocks, calling python functions, deep recursion, and try/except blocks that don't actually catch an exception. <<< http://lists.ironpython.com/pipermail/users-ironpython.com/2007-April/004773.html It's interesting that CPython can make those gains still by using a stack implementation. I'll observe that IronPython has the additional dependency of the full .NET runtime. (It was my point 7/18 about incorporating the GNU libs, that to compile to machine-native, as a JIT does, you need the instruction set of the machine.) Whereas, CPython can disregard them, having already been compiled for it. I think what I was looking for is that IronPython employs the .NET to compile to machine instructions, once it's known what the values of the variables are that are the operands. The trade-off is compilation time + type checks + stub look-up. What I want to know is, if __add__ performs an attribute look-up, is that optimized in any way, after the IP is already in compiled code? After all that, I don't feel so guilty about stepping on Tim's toes. On Jul 30, 12:12 am, Dino Viehland wrote: > IronPython doesn't have an interpreter loop and therefore has no POP / TOP / etc... Instead what IronPython has is a method call Int32Ops.Add which looks like: > > public static object Add(Int32 x, Int32 y) { > long result = (long) x + y; > if (Int32.MinValue <= result && result <= Int32.MaxValue) { > return Microsoft.Scripting.Runtime.RuntimeHelpers.Int32ToObject((Int32)(result)); > } > return BigIntegerOps.Add((BigInteger)x, (BigInteger)y); > } > > This is the implementation of int.__add__. Note that calling int.__add__ can actually return NotImplemented and that's handled by the method binder looking at the strong typing defined on Add's signature here - and then automatically generating the NotImplemented result when the arguments aren't ints. So that's why you don't see that here even though it's the full implementation of int.__add__. > > Ok, next if you define a function like: > > def adder(a, b): > return a + b > > this turns into a .NET method, which will get JITed, which in C# would look something like like: > > static object adder(object a, object b) { > return $addSite.Invoke(a, b) > > } > > where $addSite is a dynamically updated call site. > > $addSite knows that it's performing addition and knows how to do nothing other than update the call site the 1st time it's invoked. $addSite is local to the function so if you define another function doing addition it'll have its own site instance. > > So the 1st thing the call site does is a call back into the IronPython runtime which starts looking at a & b to figure out what to do. Python defines that as try __add__, maybe try __radd__, handle coercion, etc... So we go looking through finding the __add__ method - if that can return NotImplemented then we find the __radd__ method, etc... In this case we're just adding two integers and we know that the implementation of Add() won't return NotImplemented - so there's no need to call __radd__. We know we don't have to worry about NotImplemented because the Add method doesn't have the .NET attribute indicating it can return NotImplemented. > > At this point we need to do two things. We need to generate the test which is going to see if future arguments are applicable to what we just figured out and then we need to generate the code which is actually going to handle this. That gets combined together into the new call site delegate and it'll look something like: > > static void CallSiteStub(CallSite site, object a, object b) { > if (a != null && a.GetType() == typeof(int) && b != null && b.GetType() == typeof(int)) { > return IntOps.Add((int)a, (int)b); > } > return site.UpdateBindingAndInvoke(a, b); > > } > > That gets compiled down as a lightweight dynamic method which also gets JITed. The next time through the call site's Invoke body will be this method and things will go really fast if we have int's again. Also notice this is looking an awful lot like the inlined/fast-path(?) code dealing with int's that you quoted. If everything was awesome (currently it's not for a couple of reasons) the JIT would even inline the IntOps.Add call and it'd probably be near identical. And everything would be running native on the CPU. > > So that's how 2 + 2 works... Finally if it's a user type then we'd generate a more complicated test like (and getting more and more pseudo code to keep things simple): > > if (PythonOps.CheckTypeVersion(a, 42) && PythonOps.CheckTypeVersion(b, 42)) { > return $callSite.Invoke(__cachedAddSlot__.__get__(a), b); > > } > > Here $callSite is another stub which will handle doing optimal dispatch to whatever __add__.__get__ will return. It could be a Python type, it could be a user defined function, it could be the Python built-in sum function, etc... so that's the reason for the extra dynamic dispatch. > > So in summary: everything is compiled to IL. At runtime we have lots of stubs all over the place which do the work to figure out the dynamic operation and then cache the result of that calculation. > > Also what I've just described is how IronPython 2.0 works. IronPython 1.0 is basically the same but mostly w/o the stubs and where we use stub methods they're much less sophisticated. > > Also, IronPython is open source -www.codeplex.com/IronPython > > -----Original Message----- abriged: > This is from 7/22/08, same author: > > I wouldn't say "can't". The current CPython VM does not compile > > code. It COULD. The C#/.NET VM does. > > Three big claims here that I breezed right over and didn't believe. > > > It COULD. > > I'm evidently assuming that if it could, it would. > > > The current CPython VM does not compile code. > > Therefore it couldn't, or the assumption is wrong. Tim says it is. > And the glaring one-- > > WHY NOT? Why doesn't CPython do it? > > I am imagining that every Python implementation has something like > it. If IronPython does not, in particular, not have the 'POP(); > TOP();' sequence, then it isn't running on a stack machine. Is the > IronPython code open source, and can someone link to it? I'm not > wading through it from scratch. What does it have instead? Does > dynamic typing still work? -- http://mail.python.org/mailman/listinfo/python-list From bj_666 at gmx.net Mon Jul 21 16:59:19 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Jul 2008 20:59:19 GMT Subject: Python Written in C? References: Message-ID: <6ekbl7F6vgp3U6@mid.uni-berlin.de> On Mon, 21 Jul 2008 11:26:27 -0700, castironpi wrote: > On Jul 20, 11:59?pm, Michael Torrie wrote: >> giveitawhril2... at gmail.com wrote: >> > I'm not dissing Python, here. Just noting that, if it is written in C, >> > that throws a curve at me in trying to balance the value of learning >> > Python vs. some other major language. >> >> Definitely one of the most non-sequitor statements I have ever heard. >> Actually your entire post doesn't make much sense. ?Maybe you are a >> brother bot to castropini? ?Perhaps a less-trained one, although none of >> castropini's posts seem to make sense either. ?The AI needs a bit of work. > > Are you saying Python is not good for writing A.I., or the A.I. isn't > good at writing Python? Are you saying python is not as smart as you. Ciao, Marc 'BlackJack' Rintsch From andreas.mock at web.de Tue Jul 15 12:17:47 2008 From: andreas.mock at web.de (McA) Date: Tue, 15 Jul 2008 09:17:47 -0700 (PDT) Subject: Logging to different addressees References: <8df30038-86c1-4376-b046-a50f2bcf0a2b@s50g2000hsb.googlegroups.com> <7b829a76-ba2c-4cb7-b216-0c9c01e5cd02@f36g2000hsa.googlegroups.com> Message-ID: Hi Vinary, thank you for answering. I start be proud that the author of the logging package himself is answering. :-) On 15 Jul., 15:51, Vinay Sajip wrote: > On Jul 15, 1:27 pm, McA wrote: > > > > > Add a handler to the root logger (or common_logger) to send to the > admin sink. That's clear. > Add a handler to certain_logger to send to the addressee sink. That's also clear. > If you added the admin sink handler to the root logger, you're done. Isn't that the first thing above? What do you mean? > Otherwise, you need to ensure that certain_logger is a child of > common_logger. What I want to code is something like that. a) I know thet this is a message for the admin only: admin_logger.log('blabla') (admin_logger = root_logger = logging.get_logger("")) b) certain_logger.log('something' => log to the root/admin/-sink as well as to the certain-sink. Do I have to create a logger subclass where I do the multiplexing of the logging messages? I'm pretty sure I miss something. ;-) > > Regards, > > Vinay Sajip Regards Andreas Mock From jonas.haulin at gmail.com Fri Jul 25 02:51:03 2008 From: jonas.haulin at gmail.com (jrh) Date: Thu, 24 Jul 2008 23:51:03 -0700 (PDT) Subject: import dll instead of pyd References: <68310600-2efd-4f52-81d7-d0f3b40c7809@h17g2000prg.googlegroups.com> <6O2dnfUikbwXqRTVnZ2dnUVZ_j2dnZ2d@earthlink.com> Message-ID: <21d0cf65-0366-4473-8b3e-81f818aeb289@h17g2000prg.googlegroups.com> Yes it is in the same directory. The problem is it does not seem to look for dll's at all. So is this by design, or am I missing something? On 25 Juli, 10:03, Nick Dumas wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Is this DLL in the same directory as your script? If not, is it part of > your pythonpath? If neither are true, then you won't be able to import > it, regardless of whether it's a good file or not. > > > > jrh wrote: > > Hello, > > > From previous posts and documentation it seems python should be able > > to import a module that is compiled into a .dll just as well as > > a .pyd. I have a pyd that works fine, but after renaming it to dll the > > import fails. Running python with -vv flag indicates it doesn't > > actually look for the dll (see below). Has dll import been defeatured > > in python? > > > Thanks! > > >>>> import _mydllpythonmodule > > # trying _mydllpythonmodule.pyd > > # trying _mydllpythonmodule.py > > # trying _mydllpythonmodule.pyw > > # trying _mydllpythonmodule.pyc > > # trying C:\Python25\DLLs\_mydllpythonmodule.pyd > > # trying C:\Python25\DLLs\_mydllpythonmodule.py > > # trying C:\Python25\DLLs\_mydllpythonmodule.pyw > > # trying C:\Python25\DLLs\_mydllpythonmodule.pyc > > # trying C:\Python25\lib\_mydllpythonmodule.pyd > > # trying C:\Python25\lib\_mydllpythonmodule.py > > # trying C:\Python25\lib\_mydllpythonmodule.pyw > > # trying C:\Python25\lib\_mydllpythonmodule.pyc > > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyd > > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.py > > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyw > > # trying C:\Python25\lib\lib-tk\_mydllpythonmodule.pyc > > # trying C:\Python25\_mydllpythonmodule.pyd > > # trying C:\Python25\_mydllpythonmodule.py > > # trying C:\Python25\_mydllpythonmodule.pyw > > # trying C:\Python25\_mydllpythonmodule.pyc > > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyd > > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.py > > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyw > > # trying C:\Python25\lib\site-packages\_mydllpythonmodule.pyc > > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyd > > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.py > > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyw > > # trying C:\Python25\lib\site-packages\win32\_mydllpythonmodule.pyc > > # trying C:\Python25\lib\site-packages\win32\lib > > \_mydllpythonmodule.pyd > > # trying C:\Python25\lib\site-packages\win32\lib\_mydllpythonmodule.py > > # trying C:\Python25\lib\site-packages\win32\lib > > \_mydllpythonmodule.pyw > > # trying C:\Python25\lib\site-packages\win32\lib > > \_mydllpythonmodule.pyc > > # trying C:\Python25\lib\site-packages\Pythonwin > > \_mydllpythonmodule.pyd > > # trying C:\Python25\lib\site-packages\Pythonwin\_mydllpythonmodule.py > > # trying C:\Python25\lib\site-packages\Pythonwin > > \_mydllpythonmodule.pyw > > # trying C:\Python25\lib\site-packages\Pythonwin > > \_mydllpythonmodule.pyc > > Traceback (most recent call last): > > File "", line 1, in > > ImportError: No module named _mydllpythonmodule > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (MingW32) > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > iEYEARECAAYFAkiJNGwACgkQLMI5fndAv9hykgCcDf4cTZU0iDo+ELQ5aFGs9FIO > 8GEAn3+egrPDtNrlbsssqti8YeZXXIeM > =q31k > -----END PGP SIGNATURE----- From martin at v.loewis.de Sat Jul 26 12:55:40 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 26 Jul 2008 18:55:40 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: References: <488aec52$0$21481$9b622d9e@news.freenet.de> Message-ID: <488B570C.8070202@v.loewis.de> >> The Microsoft .NET commercial framework uses the PE architecture of the > > Whats the "Commercial framework" ? I've only come accross 3, the > standard 32 bit one and 2 64 bit variants. That's the name of the Microsoft .NET product available for Windows. There are other implementations as well, such as the Compact Framework, or GNU Mono. It's correct that the commercial framework is available for three architectures. In addition, the compact framework is also available for ARM. Mono is available for many more platforms, such as SPARC, PowerPC, MIPS and HPPA. > I just tested, I built a default C# forms app using the "AnyCPU" option > and it ran as a 64 bit app (no *32 in Task Manager), this is on XP64. > > I have though installed the AMD64 version of the 2.0 framework and > AFAICT neither windows update or the Visual Studio installer > will install that by default, you have to go get it your self. Interesting. I only tested this in .NET 1.1. Perhaps they have changed something since. How exactly did you launch the program? Does it change if you use Python's os.spawn* to launch it? Regards, Martin From google at mrabarnett.plus.com Tue Jul 15 18:17:43 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 15 Jul 2008 15:17:43 -0700 (PDT) Subject: Modify a string's value References: <87lk036y2u.fsf@benfinney.id.au> Message-ID: On Jul 15, 3:06?pm, Ben Finney wrote: > s0s... at gmail.com writes: > > I've heard that a 'str' object is immutable. But is there *any* way to > > modify a string's internal value? > > If there were, it would not be immutable. The 'str' type has only > immutable values. > > You could implement your own string type, and have it allow mutable > values. You'd have to take care of creating those values explicitly, > though. > You could write a C extension which modifies strings, but that would be a Bad Idea. From konstantin.selivanov at gmail.com Tue Jul 22 01:49:37 2008 From: konstantin.selivanov at gmail.com (konstantin) Date: Mon, 21 Jul 2008 22:49:37 -0700 (PDT) Subject: string[i:j:k] References: <4a9a4cf3-9ef4-4d9e-b714-bbf62b7c1917@v1g2000pra.googlegroups.com> Message-ID: <811e72db-a8bc-475a-b32a-38a9b6922600@k30g2000hse.googlegroups.com> On Jul 22, 9:18 am, alex23 wrote: > On Jul 22, 3:10 pm, konstantin wrote: > > > some_string[i:j:k] > > What does it mean? > > i = start position, j = end position, k = step size > > >>> s = "ABABABABABABAB" > >>> s[0:6:2] > 'AAA' > >>> s = "ABCABCABCABCABC" > >>> s[0:6:3] > > 'AA' > > Hope this helps. > > - alex23 Thanks! It seems that negative step leads in reverse direction. But logic isn't completely clear for me. >>> s = '123456789' >>> s[::-2] '97531' but >>> s[:-1:-2] '' though I expected something like '8642' What did i missed? From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 2 04:13:46 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Jul 2008 10:13:46 +0200 Subject: Attribute reference design In-Reply-To: References: <6cvlk4F3s90U1@mid.uni-berlin.de> Message-ID: <486b38b6$0$7210$426a74cc@news.free.fr> chamalulu a ?crit : > On Jul 2, 1:17 am, Gary Herron wrote: >> No need. Also, you can define a class attribute (C++ might call it a >> static attribute) and access it transparently through an instance. >> >> class C: >> aClassAttribute = 123 >> def __init__(self, ...): >> ... >> >> c = C() >> ... do something with c.aClassAttribute ... >> > > Actually, this is why I started too look into the attribute reference > mechanics to begin with. Coming from mostly C# development I think > it's weird to be able to refer to class attributes (static members) > through a class instance (object). But I think I'm getting the > picture. Function objects lay flat in memory (some heap...). Python's functions are ordinary objects, instance of type 'function'. > When > defined inside classes they are wrapped in method objects. Nope. The wrapping happens at lookup time, thru the descriptor protocol (the same thing that gives support for properties). > When > refered through classes or class instances they are unbound method > objects or bound method objects respectively. That's what function.__get__() returns, yes. What is stored in the class object's __dict__ is the plain function. > Am I on the right track? > I still don't get why these methods show up when I dir() a class > instance. """ Help on built-in function dir in module __builtin__: dir(...) dir([object]) -> list of strings Return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it: No argument: the names in the current scope. Module object: the module attributes. Type or class object: its attributes, and recursively the attributes of its bases. Otherwise: its attributes, its class's attributes, and recursively the attributes of its class's base classes. """ > /Henrik From amirnntp at gmail.com Sat Jul 12 23:44:13 2008 From: amirnntp at gmail.com (Amir) Date: Sat, 12 Jul 2008 20:44:13 -0700 (PDT) Subject: filtering keyword arguments Message-ID: <633d6159-7803-4d9b-8f16-2a4a0a197a86@t54g2000hsg.googlegroups.com> How do you filter keyword arguments before passing them to a function? For example: def f(x=1): return x def g(a, **kwargs): print a, f(**kwargs) In [5]: g(1, x=3) 1 3 In [6]: g(1, x=3, y=4) TypeError: f() got an unexpected keyword argument 'y' Is there a way to do something like: def g(a, **kwargs): print a, f(filter_rules(f, **kwargs)) so only {'x': 3} is passed to f? I was hoping for a pythonic way of doing what in Mathematica is done by FilterRules: http://reference.wolfram.com/mathematica/ref/FilterRules.html From alexnbryan at gmail.com Tue Jul 15 04:45:25 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 15 Jul 2008 01:45:25 -0700 (PDT) Subject: Testing for Internet Connection Message-ID: <18460572.post@talk.nabble.com> Hello internet. I am wondering, is there a simple way to test for Internet connection? If not, what is the hard way :p -- View this message in context: http://www.nabble.com/Testing-for-Internet-Connection-tp18460572p18460572.html Sent from the Python - python-list mailing list archive at Nabble.com. From deets at nospam.web.de Tue Jul 8 02:29:14 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 Jul 2008 08:29:14 +0200 Subject: extended setattr() In-Reply-To: References: Message-ID: <6dgfprF2ekq3U1@mid.uni-berlin.de> Rotlaus schrieb: > On 7 Jul., 08:01, Rotlaus wrote: >> 2 weeks ago i asked for a etended getattr() which worked really fine, >> but now i would love to have a extendedsetattr() as well. > > I've tried the following, but it doesn't work: > > class A(object): > def __init__(self): > self.B = B() > > class B(object): > def __init__(self): > self.C = C('foo') > > class C(object): > def __init__(self, txt=''): > self.txt = txt > > def ext_setattr(obj, attr, val): > for subattr in attr.split("."): > obj = getattr(obj, subattr) > obj = val > >>>> import test >>>> a = A() > Traceback (most recent call last): > File "", line 1, in > NameError: name 'A' is not defined >>>> a = test.A() >>>> a.B.C.txt > 'foo' >>>> ext_setattr(a, 'B.C.txt', 'bar') >>>> a.B.C.txt > 'foo' > > What am i doing wrong? obj = val won't work. You need to use a setattr(obj, name, val) on the last attribute-name. Diez From fredrik at pythonware.com Fri Jul 25 03:20:16 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 09:20:16 +0200 Subject: import dll instead of pyd In-Reply-To: <21d0cf65-0366-4473-8b3e-81f818aeb289@h17g2000prg.googlegroups.com> References: <68310600-2efd-4f52-81d7-d0f3b40c7809@h17g2000prg.googlegroups.com> <6O2dnfUikbwXqRTVnZ2dnUVZ_j2dnZ2d@earthlink.com> <21d0cf65-0366-4473-8b3e-81f818aeb289@h17g2000prg.googlegroups.com> Message-ID: jrh wrote: > Yes it is in the same directory. The problem is it does not seem to > look for dll's at all. So is this by design, or am I missing > something? looks like that was removed in 2.5; from Misc/NEWS: - On Windows, .DLL is not an accepted file name extension for extension modules anymore; extensions are only found if they end in .PYD. which is easily confirmed: Python 2.4.3 >>> import imp >>> imp.get_suffixes() [('.pyd', 'rb', 3), ('.dll', 'rb', 3), ('.py', 'U', 1), ('.pyw', 'U', 1), ('.pyc', 'rb', 2)] Python 2.5 >>> import imp >>> imp.get_suffixes() [('.pyd', 'rb', 3), ('.py', 'U', 1), ('.pyw', 'U', 1), ('.pyc', 'rb', 2)] (the DLL support was a compatibility thing anyway, so I guess removing it after 10+ years is a reasonable thing to do...) From DWebre at dotd.la.gov Thu Jul 17 08:40:29 2008 From: DWebre at dotd.la.gov (DWebre at dotd.la.gov) Date: Thu, 17 Jul 2008 07:40:29 -0500 Subject: Pickle and wx.TextCtrl Message-ID: D. J. Webre, Jr. PE & PLS "Gabriel Genellina" python-list at python.org Sent by: cc python-list-bounc es Subject +djwebre=dotd.la. Re: Pickle and wx.TextCtrl gov at python.org 07/11/2008 10:51 PM Thanks for the response. En Fri, 11 Jul 2008 10:15:36 -0300, escribi?: > Trying to read a pickled file and list contents. > > The attached program works using pprint, but I want to write to my frame. > WriteText only produces half of the records. > What is happening? What do you mean by "only produces half of the records"? Write Text list records from "Assignment" to "Report" pprint list records from "Assignment" to "Report" and continues to "TaskWeek", about twice as many records Probably your problem has nothing to do with a TextCtrl - ensure you can save and load your data with a simple, console-based script, and only then write the GUI. The way you read the file is rather strange -mixing calls to readline and pickle.load- I'd write the data using pickle.dump calls *only* and then read it using pickle.load calls *only*. I used 13.1.7 Example of the Python Library Referencebut. Got an error message when I did not have the readline() statement. Additional ideas will be appreciated. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: graycol.gif Type: image/gif Size: 105 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: pic20037.gif Type: image/gif Size: 1255 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ecblank.gif Type: image/gif Size: 45 bytes Desc: not available URL: From tomkur2006-takehome at yahoo.com Tue Jul 1 21:38:21 2008 From: tomkur2006-takehome at yahoo.com (tom) Date: Tue, 1 Jul 2008 18:38:21 -0700 (PDT) Subject: httplib HTTP: Logging request message References: <57053381-d73a-4099-af6b-da672b8718be@i36g2000prf.googlegroups.com> Message-ID: <170d29ce-054a-42ee-9251-1ec5c1595a37@f24g2000prh.googlegroups.com> I guess the easies way to do it is to copy and modify the httplib module to log both outgoing and incoming messages. From robinsiebler at gmail.com Thu Jul 31 20:07:15 2008 From: robinsiebler at gmail.com (robinsiebler at gmail.com) Date: Thu, 31 Jul 2008 17:07:15 -0700 (PDT) Subject: Decoding an attachment Message-ID: I figured out how to save an e-mail message as a text file, but I'm not sure how to decode the encoded part as I am not sure how much I need to include to decode it properly. Here is what a message looks like: Received: from INGESTOR2SQA ([10.220.83.198]) by sqaserver300 with Microsoft SMTPSVC(6.0.3790.0); Thu, 31 Jul 2008 12:10:26 -0700 mime-version: 1.0 from: "AVDN Ingestor" to: sqatest at ictvsys.pvt date: 31 Jul 2008 17:53:40 +0000 subject: Upload Status for test content-type: multipart/mixed; boundary=--boundary_2_09ab8836- ff06-41a6-94d6-59258539bf88 Return-Path: sqatest at ictvsys.pvt Message-ID: X-OriginalArrivalTime: 31 Jul 2008 19:10:26.0125 (UTC) FILETIME=[16D08FD0:01C8F341] ----boundary_2_09ab8836-ff06-41a6-94d6-59258539bf88 content-type: text/plain; charset=us-ascii content-transfer-encoding: quoted-printable For additional information, please see attachment. ----boundary_2_09ab8836-ff06-41a6-94d6-59258539bf88 content-type: text/xml; name=status.xml; charset=utf-8 content-transfer-encoding: base64 content-disposition: attachment PGF2ZG5fcG5tIHZlcnNpb249IjEuMSIgc2VuZGVyPSJhdmRud2VzdGRjMSIgZG9jbnVtYmVy PSJvaHV0bHBxeXptM25xd3lrYm9wd3pwdTUiIHN0YXR1cz0ic3VjY2Vzc2Z1bCI +PGNvbnRh Y3QgcGhvbmU9IjQwOC05MzEtOTIzMiIgZW1haWw9Im0uY2hhbkBhdm5ldHdvcmtzLmNvbSIg Lz48YXNzZXRzdGF0ZSBwcm92aWRlcmlkPSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJjZjcw NDcwNWFjIiBmaWxlbmFtZT0iXHZpZGVvXGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2NfYWMz XzAxLmpwZyIgbm90aWZpY2F0aW9uPSIxMjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJpZD0i U1FBIiBhc3NldGlkPSJhY2YxZTNkNmViY2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRlb1xm b29cYm91Z2UwMDMuMzIwXzI0MF9udHNjX2FjM18wMy5qcGciIG5vdGlmaWNhdGlvbj0iMTIw IiAvPjxhc3NldHN0YXRlIHByb3ZpZGVyaWQ9IlNRQSIgYXNzZXRpZD0iYWNmMWUzZDZlYmNm NzA0NzA1YWMiIGZpbGVuYW1lPSJcdmlkZW9cZm9vXGJvdWdlMDAzLjMyMF8yNDBfbnRzY19h YzNfMDQuanBnIiBub3RpZmljYXRpb249IjEyMCIgLz48YXNzZXRzdGF0ZSBwcm92aWRlcmlk PSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJjZjcwNDcwNWFjIiBmaWxlbmFtZT0iXHZpZGVv XGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2NfYWMzXzAyLmpwZyIgbm90aWZpY2F0aW9uPSIx MjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJpZD0iU1FBIiBhc3NldGlkPSJhY2YxZTNkNmVi Y2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRlb1xmb29cYm91Z2UwMDMuMzIwXzI0MF9udHNj X2FjMy5qcGciIG5vdGlmaWNhdGlvbj0iMTIwIiAvPjxhc3NldHN0YXRlIHByb3ZpZGVyaWQ9 IlNRQSIgYXNzZXRpZD0iYWNmMWUzZDZlYmNmNzA0NzA1YWMiIGZpbGVuYW1lPSJcdmlkZW9c Zm9vXGJvdWdlMDAzLjMyMF8yNDBfbnRzY19hYzNfMDguanBnIiBub3RpZmljYXRpb249IjEy MCIgLz48YXNzZXRzdGF0ZSBwcm92aWRlcmlkPSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJj ZjcwNDcwNWFjIiBmaWxlbmFtZT0iXHZpZGVvXGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2Nf YWMzXzA3LmpwZyIgbm90aWZpY2F0aW9uPSIxMjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJp ZD0iU1FBIiBhc3NldGlkPSJhY2YxZTNkNmViY2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRl b1xmb29cYm91Z2UwMDMuMzIwXzI0MF9udHNjX2FjM18wNi5qcGciIG5vdGlmaWNhdGlvbj0i MTIwIiAvPjxhc3NldHN0YXRlIHByb3ZpZGVyaWQ9IlNRQSIgYXNzZXRpZD0iYWNmMWUzZDZl YmNmNzA0NzA1YWMiIGZpbGVuYW1lPSJcdmlkZW9cZm9vXGJvdWdlMDAzLjMyMF8yNDBfbnRz Y19hYzNfMDUuanBnIiBub3RpZmljYXRpb249IjEyMCIgLz48YXNzZXRzdGF0ZSBwcm92aWRl cmlkPSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJjZjcwNDcwNWFjIiBmaWxlbmFtZT0iXHZp ZGVvXGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2NfYWMzXzA5LmpwZyIgbm90aWZpY2F0aW9u PSIxMjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJpZD0iU1FBIiBhc3NldGlkPSJhY2YxZTNk NmViY2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRlb1xmb29cYm91Z2UwMDMuMzIwXzI0MF9u dHNjX2FjMy50cyIgbm90aWZpY2F0aW9uPSIxMjAiIC8+PC9hdmRuX3BubT4= ----boundary_2_09ab8836-ff06-41a6-94d6-59258539bf88-- From szrRE at szromanMO.comVE Tue Jul 22 14:49:34 2008 From: szrRE at szromanMO.comVE (szr) Date: Tue, 22 Jul 2008 11:49:34 -0700 Subject: proliferation of computer languages References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> <40429b65-23a0-489b-b5fd-ae6b8eee607d@t54g2000hsg.googlegroups.com> Message-ID: J?rgen Exner wrote: > Chris Rathman wrote: > >> I can't say that I see any particular point to the essay. > > You must be new here. There never is any particular point to Xah > Lee's rantings except to cross-post borderline topics to borderline > relevant NGs and then lay back and enjoy the ensuing slaughter. Admittedly, I'm not all too familiar with his postings, but on a general note, isn't it possible that someone else might not see it the same as you do? I really didn't see anything really sinister about the posting or it's content. It may very well be someone attempting to create a conversation, someone who may not be generally well received a lot of the time I gather. Also, if have such a distaste for his postings, you are free to ignore them as well. That said, I am all for alerting someone of something which may be a complete waste of their time, but in this case it feels like you are projecting your own dislike for the OP. Unless the OP really is deserving of such branding (in which case I'd stand corrected), I don't think it is reason enough to tell others not to read of his work just because you aren't particularly fond of it. Perhaps citing an actual example illustrating a reason to avoid him like the plague would of helped :-) -- szr From sunp1028 at gmail.com Mon Jul 14 21:29:11 2008 From: sunp1028 at gmail.com (patrol) Date: Mon, 14 Jul 2008 18:29:11 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> Message-ID: Hi, > 1) I'm not sure if WMI can be forced to close down system processes, > but if it can it's probably by means of specifying one or more > privileges when you connect. Try looking in the WMI newsgroups > for a more general (non-Python) answer to this and I'll happily > explain how to apply it in a Python context. I use VBS to kill these processes,the VBS cannot kill these either. > 2) I can't quite see from this traceback where the problem > arises. Have you snipped the traceback at all, or was that > all there was? Can you narrow the thing down to a short > snippet of code which I'm likely to be able to run independently, > please? import wmi from time import sleep c = wmi.WMI () process_watcher = c.Win32_Process.watch_for("creation") while True: new_process = process_watcher() if new_process.Caption == 'notepad.exe': print "start killing.." sleep(5) result = new_process.terminate() print "killed" We must start the notepad.exe manually, then (1) kill the notepad.exe by this code. (2)we kill the notepad.exe before this code manually. Both will result in errors. From tjreedy at udel.edu Fri Jul 25 17:53:22 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Jul 2008 17:53:22 -0400 Subject: Calling external program from within python In-Reply-To: <296ec449-831e-4f1f-9082-5ad4991dfc04@i20g2000prf.googlegroups.com> References: <6eu684F91muhU1@mid.uni-berlin.de> <042e46cf-8ee8-4dd0-bc2b-716d588f8e83@o40g2000prn.googlegroups.com> <296ec449-831e-4f1f-9082-5ad4991dfc04@i20g2000prf.googlegroups.com> Message-ID: Michael Tobis wrote: > For some reason os.popen is deprecated in favor of the more verbose > subprocess.Popen, but this will work for a while. As explained in http://www.python.org/dev/peps/pep-0324/ subprocess consolidated replaced several modules and functions (popen*, system, spawn*, ???)with better security, exception handling, and flexibility. The deprecated modules are gone in 3.0, so the OP might want to start with subprocess now. From ethan at stoneleaf.us Tue Jul 8 13:34:04 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 08 Jul 2008 09:34:04 -0800 Subject: numeric emulation and __pos__ In-Reply-To: <92e3ea9f-5745-4072-9d09-7c14fd335828@f36g2000hsa.googlegroups.com> References: <92e3ea9f-5745-4072-9d09-7c14fd335828@f36g2000hsa.googlegroups.com> Message-ID: <4873A50C.5090003@stoneleaf.us> Mark Dickinson wrote: > On Jul 8, 12:12 am, Ethan Furman wrote: > >>1) Any reason to support the less common operators? >> i.e. <<, >>, &, ^, | > > No reason to support any of these for a nonintegral > nonbinary type, as far as I can see. > >>2) What, exactly, does .__pos__() do? An example would help, too. > > Very little: it implements the unary + operator, which > for most numeric types is a no-op: > >>>>+5.0 > > 5.0 Anybody have an example of when the unary + actually does something? Besides the below Decimal example. I'm curious under what circumstances it would be useful for more than just completeness (although completeness for it's own sake is important, IMO). > So you could safely implement it as: > > def __pos__(self): > return self > > By the way, have you met the Decimal type? It also > keeps track of significant zeros. For example: > >>>>from decimal import Decimal >>>>Decimal('1.95') + Decimal('2.05') > > Decimal("4.00") Significant zeroes is not quite the same as significant digits (although Decimal may support that too, I haven't studied it). The difference being, for example, the following: >>> from decimal import Decimal >>> first = Decimal("3.14") >>> second = Decimal("5.2") >>> first * second Decimal("16.328") >>> from measure import Measure >>> third = Measure("3.14") >>> fourth = Measure("5.2") >>> third * fourth Measure("16") In other words, any calculated value cannot be more accurate than the least accurate input (5.2 in the case above, which hase two significant digits). > (Note that the output includes the extra zeros...) > Interestingly, in Decimal the __pos__ operation isn't a no-op: > it rounds a Decimal to the current context, and it also > (mistakenly, in my opinion) changes -0.0 to 0.0: > > >>>>+Decimal('-0.0') > > Decimal("0.0") > >>>>+Decimal('123456789123456789123456789123456789') > > Decimal("1.234567891234567891234567891E+35") > > Mark -- Ethan From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 3 11:26:59 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 03 Jul 2008 17:26:59 +0200 Subject: Write a file - beginner's question In-Reply-To: References: Message-ID: <486cefb7$0$6040$426a74cc@news.free.fr> Ben Keshet a ?crit : > I have a probably simple beginner's question - > > I have a script that I am currently able to print its output. instead, > i want to write it into a file - I tried different versions of write() > but might have gotten the syntax wrong. The syntax is: fileobj.write(something) Now since you don't say exactly what you tried *and what you got*, we can't help much more here. > the variable I want to write is > a line from a file I am reading: > > "... > f = open('receptor.mol2', 'r') > line = f.readline()[:-1] If you want to strip the newline characters, you'd better use line.strip() or line.lstrip() > while '@ATOM' not in line: > line = f.readline()[:-1] > #print line Also, there are simpler ways to iterate over a file: f = open('somefile.txt') for line in f: if '@ATOM' in line: break print line.lstrip() f.close() > print random_mol2 > ..." > > e.g. I want to write to a file all the lines in 'receptor.mol2' up to > the string "@ATOM" (one after the other). Can anyone please > advice? The simplest solution for a unix-like command-line program would be to redirect the standard out to this file, ie: # python myprog.py > destfile.txt But this may not fit your needs !-) The other simplest solution is to open the destination file in write (or append) mode and write to it: source = open('somefile.txt') dest = open('otherfile.txt', 'w') for line in source: if '@ATOM' in line: break # we don't strip here, since write doesn't append a newline dest.write(line) source.close() dest.close() > On a related note - how do I read and write to a file that is not in the > same directory? Give the full absolute or relative path. > e.g how do I provide a pathway to an open command? source = open('/full/absolute/path/to/my/file.txt') Note that the exact syntax for a path depends on your os (but the os.path module can take care of most specificities). The above example is for a posix system. On Windows, you'll probably have something like: source = open('C:/full/absolute/path/to/my/file.txt') HTH From fredrik at pythonware.com Thu Jul 24 14:05:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 20:05:31 +0200 Subject: instance comparison In-Reply-To: References: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> <4888879a$0$1043$426a74cc@news.free.fr> Message-ID: King skrev: > The the class is not subclass of another one. Problem still persist. > The code is pretty huge and I am trying to post the information as > clear as possible. feel free to *add* stuff to the following example until it breaks, if that's easier: >>> class Spam: ... def __init__(self, label): ... self.label = label ... def __str__(self): ... return self.label ... >>> a = Spam("an object") >>> a <__main__.Spam instance at 0xb7e8faac> >>> print a an object >>> b = Spam("an object") >>> b <__main__.Spam instance at 0xb7e8fb6c> >>> print b an object >>> a == b False >>> a is b False >>> str(a) == str(b) True From Russ.Paielli at gmail.com Thu Jul 31 01:31:51 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 30 Jul 2008 22:31:51 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> Message-ID: On Jul 30, 9:27 pm, Erik Max Francis wrote: > Russ P. wrote: > > I don't know if you can read minds, but you seem to have a lot of > > trouble reading words. > > > Can you read "it would be nice to be able to write ..."? Can you > > understand what it means? Can you understand that it does *not* mean, > > "one *should* be able to write ..."? > > You're sure going on about a distinction without a difference for a guy > who childishly likes to call other people names. A reasonable person > would have long ago moved on instead of blaming others for not > immediately intuiting your thoughts, rather than straightforwardly > reading your words. Which, by the way, includes at least three people > other than myself. > > But I'll bet the mindless namecalling is really working out for you. > Go, team, go! You earned the "childish name calling" by acting like a child -- with your petty little game of trying to show that I don't understand a basic concept in Python. As I said, your initial misunderstanding, while silly, was at least forgivable. But your insistence on repeating it time after time is not. It is truly pathetic. From dusan.smitran at gmail.com Tue Jul 22 07:28:05 2008 From: dusan.smitran at gmail.com (dusans) Date: Tue, 22 Jul 2008 04:28:05 -0700 (PDT) Subject: Converting List of String to Integer References: Message-ID: <45493256-eaff-40e5-8414-59e7ce1b347c@m73g2000hsh.googlegroups.com> >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] >>> [map(int, i) for i in a] [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] On Jul 21, 9:06?pm, Samir wrote: > Hi Everyone, > > I am relatively new to Python so please forgive me for what seems like > a basic question. > > Assume that I have a list, a, composed of nested lists with string > representations of integers, such that > > a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > > I would like to convert this to a similar list, b, where the values > are represented by integers, such as > > b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > I have unsuccessfully tried the following code: > > n = [] > for k in a: > ? ? n.append([int(v) for v in k]) > print n > > Does anyone know what I am doing wrong? > > Thanks in advance. > > Samir From duncan.booth at invalid.invalid Thu Jul 17 17:02:42 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jul 2008 21:02:42 GMT Subject: x, = y (???) References: Message-ID: kj wrote: > I still don't get it. If we write > > y = 'Y' > x, = y > > what's the difference now between x and y? And if there's no > difference, what's the point of performing such "unpacking"? None whatsoever when the string has only one character, but with 2 characters it becomes an obfuscated way of checking that there was only one character: >>> x, = 'a' >>> x, = 'ab' Traceback (most recent call last): File "", line 1, in x, = 'ab' ValueError: too many values to unpack From fredrik at pythonware.com Mon Jul 21 11:04:08 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 17:04:08 +0200 Subject: Safe guard .pyc files In-Reply-To: References: Message-ID: King wrote: > After google a lot I didn't find any way to safe guard .pyc files from > decompilation. There's no bullet-proof way to do that (the interpreter needs the bytecodes to be able to run your program, so unless you create your own Python runtime, someone could always run your program with an instrumented stock interpreter, and get the code from there. If you build your own runtime, they'll just instrument your runtime instead, which might be a little more work, but not much for someone who knows how to do such things.) Possible solutions: - implement portions of your application as a web service - hardware dongles (hackers can usually get around them without too much work, but they work pretty well for some applications / markets.) - use an obfuscator, e.g. http://bitboost.com/#other or http://www.lysator.liu.se/~astrand/projects/pyobfuscate/ From rotlaus at gmail.com Tue Jul 8 02:27:06 2008 From: rotlaus at gmail.com (Rotlaus) Date: Mon, 7 Jul 2008 23:27:06 -0700 (PDT) Subject: extended setattr() References: Message-ID: On 7 Jul., 08:01, Rotlaus wrote: > 2 weeks ago i asked for a etended getattr() which worked really fine, > but now i would love to have a extendedsetattr() as well. I've tried the following, but it doesn't work: class A(object): def __init__(self): self.B = B() class B(object): def __init__(self): self.C = C('foo') class C(object): def __init__(self, txt=''): self.txt = txt def ext_setattr(obj, attr, val): for subattr in attr.split("."): obj = getattr(obj, subattr) obj = val >>> import test >>> a = A() Traceback (most recent call last): File "", line 1, in NameError: name 'A' is not defined >>> a = test.A() >>> a.B.C.txt 'foo' >>> ext_setattr(a, 'B.C.txt', 'bar') >>> a.B.C.txt 'foo' What am i doing wrong? From cricket.keith at gmail.com Wed Jul 2 17:26:41 2008 From: cricket.keith at gmail.com (Keith Nation) Date: Wed, 2 Jul 2008 16:26:41 -0500 Subject: Queue/Priority Needed Message-ID: <21935b370807021426l11f1fa0ayc52593cc184869b3@mail.gmail.com> I'm still very new to python, and I have a question about how to prioritize jobs in a queue. Currently, I have a simple script that does the following: job1 = [1, 'Task1', 'v03', '-start', 'Bonnie'] job2 = [2, 'Task2', 'v01', '-start', 'Billy'] job3 = [3, 'Task3', 'v01', '-start', 'Bob'] jobsequence = (job1, job2, job3) for job in jobsequence: jnam=job[1] jop=job[3] jver=job[2] jreq=job[4] jpatch=job[5] jid=jnam+'/'+jver cmdline= /home/user/program/start '+' '+jop+' -proj '+jnam+' -dir '+'/home/user/programdata/'+jnam+'/'+jver; os.popen2(cmdline,mode='t',bufsize=-1) x=0 delay=5 while os.path.exists(jid+'/log.pid'): time.sleep(60*delay) x=x+1 print 'Job Complete' What I would like to do is populate the job listings interactively (using input lines) and be able to change priority on uncompleted jobs still in the queue, and add jobs to the queue. I appreciate any help you folks can offer. Keith Nation -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sun Jul 20 01:18:31 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 19 Jul 2008 22:18:31 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> <945275e9-8923-479c-8eec-258bd68063c0@z6g2000pre.googlegroups.com> <4881FE02.3000203@gmail.com> Message-ID: <99a8d3a0-e58e-4129-ba5a-8f0eac193f8e@a2g2000prm.googlegroups.com> On Jul 20, 11:14 am, Andrew Freeman wrote: > John Machin wrote: > (4) I highly doubt that this code was actually to be used in an > interactive session, The offending code is a nonsense wherever it is used. > the False/True output was truncated intentionally, What meaning are you attaching to "truncated"? > it's an obvious, but superfluous output (unless you were to rely on this > by attaching it to a variable which might lead to sorting issues). > > I put together a generic matcher that returns either a list of True data > (if the input is a list or tuple) or a boolean value: > > def match(ex, var): > "ex is the regular expression to match for, var the iterable or > string to return a list of matching items or a boolean value respectively." > ex = re.compile(ex).match You lose clarity by rebinding ex like that, and you gain nothing. > if isinstance(var, (list, tuple)): > return filter(ex, var) > else: > return bool(ex(var)) > > I believe this is fairly clean and succinct code, it would help my > learning immensely if you feel there is a more succinct, generic way of > writing this function. You have created a function which does two quite different things depending on whether one of the arguments is one of only two of the many kinds of iterables and which has a rather generic (match what?) and misleading (something which filters matches is called "match"??) name. The loss of clarity and ease of understanding caused by the readers having to find the code for the function so that they can puzzle through it means that the most succinct, generic and *recommended* way of writing this function would be not to write it at all. Write a function which returns a MatchObject. In the unlikely event that that anyone really wants to put bools in a list and sort them, then they can wrap bool() around it. Give it a meaningful name e.g. match_LRM. You want to check if a single variable refers to a valid LRM string? Use match_LRM(the_variable). Nice and clear. You want to filter out of some iterable all the occurrences of valid LRM strings? Use filter (whose name indicates its task) or a generator or list comprehension ... what [x for x in some_iterable if match_LRM(x)] does should be screamingly obvious i.e. have less chance than filter of needing a trip to the manual. HTH, John From Samnsparky at gmail.com Sun Jul 13 12:20:40 2008 From: Samnsparky at gmail.com (Sparky) Date: Sun, 13 Jul 2008 09:20:40 -0700 (PDT) Subject: wxPython Tab Message-ID: Is there a way to get wxPython to change the visible tab in a notebook (like I have tab 1 open but the computer will automatically change to tab 2)? Thanks, Sam From Lie.1296 at gmail.com Sat Jul 26 06:23:52 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 26 Jul 2008 03:23:52 -0700 (PDT) Subject: xml.dom's weirdness? References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> Message-ID: On Jul 26, 2:29?pm, Fredrik Lundh wrote: > Lie wrote: > > Why this generates AttributeError, then not? > > > Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) > > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> import xml > >>>> xml.dom > > Traceback (most recent call last): > > ? File "", line 1, in > > AttributeError: 'module' object has no attribute 'dom' > >>>> xml.dom > > > > this is what I get, on both Windows and Linux: > > ?>>> import xml > ?>>> xml.dom > Traceback (most recent call last): > ? ?File "", line 1, in > AttributeError: 'module' object has no attribute 'dom' > ?>>> xml.dom > Traceback (most recent call last): > ? ?File "", line 1, in > AttributeError: 'module' object has no attribute 'dom' > > That was what I would have expected. The submodules shouldn't get imported unless explicitly imported with import xml.dom, but what I see right now in front of me... I wouldn't have believed such thing if this isn't happening right under my eyes. Doing several dir(xml) revealed that xml.dom and xml.parsers appeared only after doing xml.dom and getting AttributeError After further testing, I found that it also happens with xml.parsers, but not xml.sax nor xml.etree, odd thing. And I tried PIL modules, the oddities doesn't happen. Then I tested the email module, the same thing happened: Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import email >>> dir(email) ['Charset', 'Encoders', 'Errors', 'FeedParser', 'Generator', 'Header', 'Iterators', 'LazyImporter', 'MIMEAudio', 'MIMEBase', 'MIMEImage', 'MIMEMessage', 'MIMEMultipart', 'MIMENonMultipart', 'MIMEText', 'Message', 'Parser', 'Utils', '_LOWERNAMES', '_MIMENAMES', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__path__', '__version__', '_name', 'base64MIME', 'email', 'importer', 'message_from_file', 'message_from_string', 'mime', 'quopriMIME', 'sys'] >>> email.parser Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'parser' >>> dir(email) ['Charset', 'Encoders', 'Errors', 'FeedParser', 'Generator', 'Header', 'Iterators', 'LazyImporter', 'MIMEAudio', 'MIMEBase', 'MIMEImage', 'MIMEMessage', 'MIMEMultipart', 'MIMENonMultipart', 'MIMEText', 'Message', 'Parser', 'Utils', '_LOWERNAMES', '_MIMENAMES', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__path__', '__version__', '_name', '_parseaddr', 'base64MIME', 'base64mime', 'charset', 'email', 'encoders', 'errors', 'importer', 'iterators', 'message', 'message_from_file', 'message_from_string', 'mime', 'quopriMIME', 'quoprimime', 'sys', 'utils'] >>> It seems python (or my version of python, which is the one that shipped with Ubuntu) mysteriously imported several modules's submodules in a (seemingly) random, yet consistent manner after an error occurred (as far as now, it seems ANY error would trigger the mysterious submodule import). I got even more head scratching when I see this: Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ac Traceback (most recent call last): File "", line 1, in NameError: name 'ac' is not defined >>> import xml >>> dir(xml) ['_MINIMUM_XMLPLUS_VERSION', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__path__', '__version__', 'dom', 'parsers'] >>> The triggering errors happened BEFORE I imported a module, yet later module import would also import submodules If you have any idea what black magic is happening in my computer right now, I'd appreciate it. From elessar at nienna.org Mon Jul 21 11:03:52 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Tue, 22 Jul 2008 00:03:52 +0900 Subject: sending input to an embedded application In-Reply-To: References: Message-ID: <4884A558.2000209@nienna.org> mefyl wrote: > Uwe Schmitt wrote: >> On 12 Jul., 09:08, George Oliver wrote: >>> What I would like to do is take a program and embed it or put it >>> within a Python-run GUI, using the GUI just to capture and send input >>> to the application, and display the ouput. >> Which interface does your interpreter provide ? Just commandline or >> can you access by other methods ? >> >> http://sourceforge.net/projects/pexpect/ might help you >> > > Although Pexpect looks more advanced and complete, you might want to take a > look at popen* modules. It enables you to easily run a subprocess, feed him > data on stdin, retrieve output from stdout/stderr, and wait for its > completion. > > http://docs.python.org/lib/module-popen2.html > I believe the subprocess module is the recommended module to use now. -Matt From elessar at nienna.org Thu Jul 3 17:05:53 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Thu, 03 Jul 2008 15:05:53 -0600 Subject: Testing for an empty list In-Reply-To: <18268092.post@talk.nabble.com> References: <18268092.post@talk.nabble.com> Message-ID: <486D3F31.30202@nienna.org> Alexnb wrote: > Okay this is a simple question I just don't know how. If I have a list, say: > > funList = [] > > and after a while something possible should have been appended to it, but > wasn't. How can I test if that list is empty. if not funList: do_something() -Matt From michele.simionato at gmail.com Thu Jul 24 04:37:37 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 24 Jul 2008 01:37:37 -0700 (PDT) Subject: parameterized classes References: Message-ID: <1bbb53aa-eff0-4c03-a868-606396b6bbd6@y21g2000hsf.googlegroups.com> John Tantalo wrote: > I really wish I could create a class whose instances were classes that > subclassed BaseRequestHandler. Is this possible, or is there a better > way than my approach here? Or am I crazy? You may use type: type('MuSubclass', (Base, ), dict(a1=1, a2=2, ...)) From pavlovevidence at gmail.com Sat Jul 12 13:42:11 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 12 Jul 2008 10:42:11 -0700 (PDT) Subject: why is "self" used in OO-Python? References: Message-ID: <39b8817b-5297-486b-92df-7a900fcc2a35@x35g2000hsb.googlegroups.com> On Jul 12, 12:32 pm, ssecorp wrote: > I first learned about OO from Java. > > I much prefer to program in Python though. > > However I am consufed about 2 things. Short answer is, "Java isn't the only way OOP." Longer answers follow. > 1. Why do I have to pass self into every method in a class? Since I am > always doing why cant this be automated or abstracted away? > Are the instances where I won't pass self? > I imagine there is some tradeoff involved otherwise it would have been > done away with. This is pretty simple: it was judged to be significantly more readable if you mark class variables explicitly. That is, when you see something like "self.var" you instantly know it's an attribute of the object and not a local or global variable. That you sometimes see Java and (more often) C++ guidelines that recommend always using "this" for accessing class members shows that it's somewhat helpful to keep them visually distinct from other variables. I think it's a minor point, really, that people make a pretty big deal over. > 2. self.item instead of getters and setters. I thought one of the main > purposes of OO was encapsulation. Just as an aside: the usage of getters and setters probably does more to thwart encapsulation than to protect it, in practice. You see, it doesn't matter whether you access a member directly, or through getters and setters: you're still accessing the member. Getters and setters don't encapsulate your data one bit. All they do is to add a bunch of mostly unnecessary boilerplate. OTOH, many people add getters and setters recklessly, based on the above misconception. Not only are they exposing internal details by doing this, they're also giving the user a blessing to use them. The practical advantage getters and setters have in Java is that, if your class implementation changes and you no longer wish for something that was once a single variable to be that way anymore, you can change your underlying implementation without changing the interface. That advantage does not exist in Python, however, since in Python one can do the same thing with properties. > Doesn't messing with internal object- > representations break this? > I see how the getters and setters could be just visual clutter and you > have to add them to every class so it is annoying a bit in the same > way as self described above. > However I feel like I want getters and setters when I write classes, > not sure of the advantages/disadvantages though. > Only looking at the documentation of a Python-class, will internal > representations be provided? > > If I have a class: > > class Stack(object): > def __init__(self, *items): > self.stack = list(items) > > def append(self, item): > self.stack.append(item) > > def pop(self): > return self.stack.pop() > > I can get to see the stack with var.stack but then why even implement > append when I could do self.stack.append(x) etc. > That way you could do away with OO completely. So why let people > access the main attribute but not let them manipulate it? > Makes more sense to draw the line to not access any attributes at all > no? Much of what you're arguing is only true if you accept it as a given that data hiding is important. The designers of Python don't really think it is, and that's why they don't have it. Carl Banks From mva.led at gmail.com Wed Jul 9 12:09:55 2008 From: mva.led at gmail.com (Manuel Vazquez Acosta) Date: Wed, 09 Jul 2008 12:09:55 -0400 Subject: Determining when a file has finished copying In-Reply-To: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> Message-ID: <4874E2D3.4050707@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 This seems a synchronization problem. A scenario description could clear things up so we can help: Program W (The workflow) copies file F to directory B Program D (the dog) polls directory B to find is there's any new file F In this scenario, program D does not know whether F has been fully copied, but W does. Solution: Create a custom lock mechanism. Program W writes a file D/F.lock to indicate file F is not complete, it's removed when F is fully copied. I program W crashes in mid-copy both F and F.lock are kept so program D does not bother to process F. Recovery from the crash in W would another issue to tackle down. Best regards, Manuel. writeson wrote: > Hi all, > > I'm writing some code that monitors a directory for the appearance of > files from a workflow. When those files appear I write a command file > to a device that tells the device how to process the file. The > appearance of the command file triggers the device to grab the > original file. My problem is I don't want to write the command file to > the device until the original file from the workflow has been copied > completely. Since these files are large, my program has a good chance > of scanning the directory while they are mid-copy, so I need to > determine which files are finished being copied and which are still > mid-copy. > > I haven't seen anything on Google talking about this, and I don't see > an obvious way of doing this using the os.stat() method on the > filepath. Anyone have any ideas about how I might accomplish this? > > Thanks in advance! > Doug > -- > http://mail.python.org/mailman/listinfo/python-list > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkh04skACgkQI2zpkmcEAhi0eQCgsVqg51fWiwi47jxqtbR8Gz2U UukAoKm15UAm3KpEyjhsIGQ+68rq8WuU =UFHi -----END PGP SIGNATURE----- From nick at craig-wood.com Wed Jul 2 08:32:58 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 02 Jul 2008 07:32:58 -0500 Subject: Why is recursion so slow? References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Message-ID: Rich Harkins wrote: > Nick Craig-Wood wrote: > [snip] > > By definition any function in a functional language will > > always produce the same result if given the same arguments, so you can > > memoize any function. > > > > Ah, so that's why time.time() seems to be stuck... ;) ;-) As Bruno noted I should have said "pure functional language" above. As for how you deal with IO in a pure functional language, well, either you make it impure (eg Erlang or Lisp) - functions can have side effects, or you do other complicated things like monads in Haskell! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From castironpi at gmail.com Sun Jul 27 01:02:07 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 26 Jul 2008 22:02:07 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> Message-ID: <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> On Jul 24, 11:04?pm, Tim Roberts wrote: > castironpi wrote: > > >Compiling a program is different than running it. ?A JIT compiler is a > >kind of compiler and it makes a compilation step. ?I am saying that > >Python is not a compiler and in order to implement JIT, it would have > >to change that fact. > > And I'm saying you are wrong. ?There is NOTHING inherent in Python that > dictates that it be either compiled or interpreted. ?That is simply an > implementation decision. ?The CPython implementation happens to interpret. > The IronPython implementation compiles the intermediate language to native > machine language. > > >> of Python that uses .NET. ?In that case, the code *IS* JIT compiled to > >> assembly when the program starts. > > >But still not the user's code, only the interpreter, which is running > >in assembly already anyway in CPython. > > In CPython, yes. ?In IronPython, no; the user's code is compiled into > machine language. ?Both of them are "Python". > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. In CPython yes. In IronPython yes: the parts that are compiled into machine code are the interpreter, *not user's code*. Without that step, the interpreter would be running on an interpreter, but that doesn't get the user's statement 'a= b+ 1' into registers-- it gets 'push, push, add, pop' into registers. From mishok13 at gmail.com Wed Jul 9 09:20:24 2008 From: mishok13 at gmail.com (Andrii V. Mishkovskyi) Date: Wed, 9 Jul 2008 16:20:24 +0300 Subject: Returning the positions of a list that are non-zero In-Reply-To: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> References: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> Message-ID: <192840a00807090620s578ff6f9u9af8db40327f5640@mail.gmail.com> 2008/7/9 Benjamin Goudey : > I have a very large list of integers representing data needed for a > histogram that I'm going to plot using pylab. However, most of these > values (85%-95%) are zero and I would like to remove them to reduce > the amount of memory I'm using and save time when it comes to plotting > the data. To do this, I'm trying to find the best way to remove all of > the zero values and produce a list of indices of where the non-zero > values used to be. > > For example, if my original list is [0,0,1,2,1,0,0] I would like to > produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices > of where the non-zero values used to be). Removing non-zero values is > very easy but determining the indicies is where I'm having difficulty. > > Thanks in advance for any help >>> l = [0, 0, 1, 2, 1, 0, 0] >>> zip(*[(item, index) for (index, item) in enumerate(l) if item != 0]) [(1, 2, 1), (2, 3, 4)] > -- > http://mail.python.org/mailman/listinfo/python-list > -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. From kyosohma at gmail.com Sat Jul 26 20:48:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sat, 26 Jul 2008 17:48:13 -0700 (PDT) Subject: wx.Timer not working References: <7a2a1c54-6d74-475c-9566-4d94cb5b5962@a3g2000prm.googlegroups.com> Message-ID: On Jul 26, 5:22?pm, 5lvqbw... at sneakemail.com wrote: > On Jul 26, 3:13?pm, Mike Driscoll wrote: > > > > > On Jul 26, 2:33?pm, 5lvqbw... at sneakemail.com wrote: > > > > Windows XP SP3 > > > Python 2.5 > > > wx.version() = '2.8.1.1 (msw-unicode)' > > > ------ > > > I have written the following *simplest* implementation of wx.timer I > > > can think of. ?No workie. ? I want an exception, a print statement, or > > > something. > > > > The wxpython demos all work, but for some reason this isn't. ?The > > > demos are simple and straghtforward, so I think I understand how it > > > should work. ?Clues please? ?I've tried variations of ID's, SetOwners, > > > using and redefining Notify(), Bind, Connect, etc. ?In the cases where > > > the interpreter doesn't complain about passed argument types, the > > > callback function is never called. > > > > import wx > > > > class MyFrame(wx.Frame): > > > ? ? ? ? def __init__(self, parent, id, title): > > > ? ? ? ? ? ? ? ? wx.Frame.__init__(self, parent, id, ? ? title, pos=(100, 100)) > > > > ? ? ? ? ? ? ? ? timer = wx.Timer(self, -1) > > > ? ? ? ? ? ? ? ? self.Bind(wx.EVT_TIMER, self.OnTick, timer) > > > ? ? ? ? ? ? ? ? timer.Start(100) > > > > ? ? ? ? def OnTick(self, event): > > > ? ? ? ? ? ? ? ? print 'Hi. Bye.' > > > ? ? ? ? ? ? ? ? 1/0 #<-- should crash as evidence callback is being called > > > > class MyApp(wx.App): > > > ? ? ? ? def OnInit(self): > > > ? ? ? ? ? ? ? ? frame1 = MyFrame(None, wx.ID_ANY, "This is a test") > > > ? ? ? ? ? ? ? ? frame1.Show(True) > > > ? ? ? ? ? ? ? ? return True > > > > app ? ? = MyApp(0) > > > app.MainLoop() > > > > Thanks for any advice!! > > > > Michael > > > I'm not seeing anything either. Please post this to the wxPython > > user's group for additional help: > > >http://www.wxpython.org/maillist.php > > > Mike > > I think I figured it out. ?By looking at the wxTimer example here:http://wiki.wxpython.org/AnotherTutorial#head-420329f7c159d81cb03a6dd... > > My code created a temporary timer object and did not make it a class > member. ?When I changed it to be a class member with self.timer, then > it worked. > > thanks > Michael Ah...I didn't even think about that. I noticed I had self.timer in my code, but I didn't realize it was required. Sorry I wasn't of more help. Still, you can learn a lot from the wxPython user's group just by reading other people's posts. Mike From benjamin.kaplan at case.edu Wed Jul 2 23:10:17 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 2 Jul 2008 23:10:17 -0400 Subject: wxPython: How can I get window's HANDLE in wxPython. In-Reply-To: References: Message-ID: On Wed, Jul 2, 2008 at 9:40 PM, Leo Lee wrote: > I need a window's handle to be passed to external c++. > Thanks in advance > Try posting this to the wxPython-users mailing list. You'll probably get better answers there. http://www.wxpython.org/maillist.php > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From max at alcyone.com Wed Jul 30 02:09:16 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 23:09:16 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> Message-ID: Carl Banks wrote: > On Jul 30, 1:15 am, "Russ P." wrote: >> All this discussion about "if x" has me wondering. I use it all the >> time because a fully explicit test just seems redundant. But maybe it >> does have some value in terms of readability and type checking. After >> all, it is possible to forget whether something is a number or a list. > > IMO, the only time I think "if x" is really dangerous is if you are > using "if x" instead of "if x is None" to distinguish between None and > a type that can have false values. Well, that would be an exceptionally bad way to test for None-ness, since None is false. The test would never succeed. >> Having said that, it would sure be nice to be able to write >> >> if myList is not empty: >> >> instead of >> >> if len(myList) != 0: > > I can agree with this. I'm getting this sneaking suspicion that you guys are all putting us on. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The doors of Heaven and Hell are adjacent and identical. -- Nikos Kazantzakis From __peter__ at web.de Mon Jul 7 16:04:52 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 07 Jul 2008 22:04:52 +0200 Subject: do a sed / awk filter with python tools (at least as fast) References: Message-ID: Mathieu Prevot wrote: > I use in a bourne shell script the following filter: > > sed '/watch?v=/! d;s/.*v=//;s/\(.\{11\}\).*/\1/' \ > | sort | uniq | awk 'ORS=" "{print $1}' > > that give me all sets of 11 characters that follows the "watch?v=" > motif. I would like to do it in python on stdout from a > subprocess.Popen instance, using python tools rather than sed awk etc. > How can I do this ? Can I expect something as fast ? You should either do it in Python , e. g.: def process(lines): candidates = (line.rstrip().partition("/watch?v=") for line in lines) matches = (c[:11] for a, b, c in candidates if len(c) >= 11) print " ".join(sorted(set(matches))) if __name__ == "__main__": import sys process(sys.stdin) or invoke your shell script via subprocess.Popen(). Invoking a python script via subprocess doesn't make sense IMHO. Peter From kyosohma at gmail.com Wed Jul 16 15:40:58 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 16 Jul 2008 12:40:58 -0700 (PDT) Subject: New to Python - Accessing Lotus Notes References: Message-ID: On Jul 16, 2:11?pm, KDawg44 wrote: > Hi, > > We have a Lotus Notes Database that tracks time spent on projects. > What I would like to do is develop a Time Tracker in Python that > communicates with the server. ?This would pull projects in and allow a > use to start a timer as he/she works on a given project. ?The user > would then be able to commit this back to the database (thus, > preventing them from having to go to the calendar view and pick the > project and enter the hours). > > As another potential feature, I would like the user to be able to > create projects in the app and track time and then when a project > exists in the database, it would retroactively add those hours (users > cannot create their own projects and sometimes managers take some time > to actually get a project in the system). ?Lasty, the user could run a > report by date to get their hours on each project. > > Anyway, long story short, how can I communicate with Lotus Notes to > accomplish these tasks? ?Lotus Notes 7. > > Thank you for your help. ?I am very new to Python and am hoping to > learn a lot from this project so I can incorporate Python into my > daily tasks. ?Also, forgive my rant as I figured out some of my specs > as I typed this. > > Thanks again. > > Kevin Use Google...it is very cool. Here are some links I found: http://mail.python.org/pipermail/python-list/2005-May/323756.html http://www.velocityreviews.com/forums/t350942-python-and-lotus-notes.html HTH Mike From russblau at hotmail.com Fri Jul 18 10:04:29 2008 From: russblau at hotmail.com (Russell Blau) Date: Fri, 18 Jul 2008 10:04:29 -0400 Subject: Regular expression help References: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> Message-ID: wrote in message news:187a9118-97fb-41fc-87f2-d24c4d7522fb at w1g2000prk.googlegroups.com... > I am new to Python, with a background in scientific computing. I'm > trying to write a script that will take a file with lines like > > c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647 > 3pv=0 > > extract the values of afrac and etot and plot them. ... > What is being stored in energy is '<_sre.SRE_Match object at > 0x2a955e4ed0>', not '-11.020107'. Why? because the re.match() method returns a match object, as documented at http://www.python.org/doc/current/lib/match-objects.html But this looks like a problem where regular expressions are overkill. Assuming all your lines are formatted as in the example above (every value you are interested in contains an equals sign and is surrounded by spaces), you could do this: values = {} for expression in line.split(" "): if "=" in expression: name, val = expression.split("=") values[name] = val I'd wager that this will run a fair bit faster than any regex-based solution. Then you just use values['afrac'] and values['etot'] when you need them. And when you get to be a really hard-core Pythonista, you could write the whole routine above in one line, but this seems clearer. ;-) Russ From wuwei23 at gmail.com Thu Jul 24 06:03:09 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 24 Jul 2008 03:03:09 -0700 (PDT) Subject: Confounded by Python objects References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> Message-ID: <645148ca-9c52-44d7-a75a-b6c61c3ffb26@j33g2000pri.googlegroups.com> On Jul 24, 7:45 pm, "boblat... at googlemail.com" wrote: > class Channel: > name = '' > sample = [] > > def __init__(self, name): > self.name = name > > def append(self, time, value): > self.sample.append((time, value)) > self.diag() > > def diag(self): > print (self.name, self.sample) Okay, the problem is you're appending to a _class_ attribute, not to an instance attribute. If you change your class definition to this, it should work: class Channel: def __init__(self, name): self.name = name self.sample = [] That will provide each instance with its own version of the sample attribute. The 'self.name = name' in the __init__ for your original code binds a new attribute to the instance, whereas 'self.sample.append(...' in the class's append was appending to the class attribute instead. Hope this helps. - alex23 From mail at timgolden.me.uk Thu Jul 10 12:13:54 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 10 Jul 2008 17:13:54 +0100 Subject: Local User Control In-Reply-To: References: Message-ID: <48763542.8050304@timgolden.me.uk> Sparky wrote: > On Jul 10, 9:58 am, Tim Golden wrote: >> Sparky wrote: >>> I don't know how feasible this is, but is it possible to have users >>> log in to access a local database file in such a way that allows the >>> program to know what user name and password they logged in with? This >>> would involve separate user names and passwords for each user. >> Well, this is a question which is crying out for some >> context. Are you talking about an existing database >> on an existing platform? If so, which one? Are you >> talking about a database youo're thinking of building? >> If so, the answer's probably yes but only you can >> know. Are you talking about something else altogether? >> >> TJG > > Thanks for the timely response. This would be a database that I am > building myself. The question comes down to is there a feasible way to > verify a user's user name and password from inside that database. > Obviously the file would be encrypted, but if there is going to be > more than one user using it I suppose there would be a separate file > for a log-in. I am just asking for some guidance on how this would > theoretically be implemented. Maybe someone else on the list has a clearer idea than I do, but at this distance from an implementation, all I can say is: yes, I'm sure you can achieve some kind of user authentication. After all, lots of other products already do. Or is your proposed db very different? TJG From Nikolaus at rath.org Fri Jul 18 06:03:22 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Fri, 18 Jul 2008 12:03:22 +0200 Subject: Protecting instance variables Message-ID: <87zlof5x1x.fsf@nokile.rath.org> Hello, I am really surprised that I am asking this question on the mailing list, but I really couldn't find it on python.org/doc. Why is there no proper way to protect an instance variable from access in derived classes? I can perfectly understand the philosophy behind not protecting them from access in external code ("protection by convention"), but isn't it a major design flaw that when designing a derived class I first have to study the base classes source code? Otherwise I may always accidentally overwrite an instance variable used by the base class... Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From paul.hankin at gmail.com Wed Jul 9 15:49:41 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 9 Jul 2008 12:49:41 -0700 (PDT) Subject: Anyone happen to have optimization hints for this loop? References: <43111321-2cc1-4a5e-9189-744131555841@26g2000hsk.googlegroups.com> Message-ID: <1471d37a-d89a-4856-a67c-3e599270f3bf@34g2000hsf.googlegroups.com> On Jul 9, 5:04?pm, dp_pearce wrote: > count = 0 > dmntString = "" > for z in range(0, Z): > ? ? for y in range(0, Y): > ? ? ? ? for x in range(0, X): > ? ? ? ? ? ? fraction = domainVa[count] > ? ? ? ? ? ? dmntString += " ?" > ? ? ? ? ? ? dmntString += fraction > ? ? ? ? ? ? count = count + 1 > ? ? ? ? dmntString += "\n" > ? ? dmntString += "\n" > dmntString += "\n***\n > > dmntFile ? ? = open(dmntFilename, 'wt') > dmntFile.write(dmntString) > dmntFile.close() > Can anyone see a way of speeding this loop up? I'd consider writing it like this: def dmntGenerator(): count = 0 for z in xrange(Z): for y in xrange(Y): for x in xrange(X): yield ' ' yield domainVa[count] count += 1 yield '\n' yield '\n' yield '\n***\n' You can make the string using ''.join: dmntString = ''.join(dmntGenerator()) But if you don't need the string, just write straight to the file: for part in dmntGenerator(): dmntFile.write(part) This is likely to be a lot faster as no large string is produced. -- Paul Hankin From deets at nospam.web.de Tue Jul 22 03:02:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 09:02:38 +0200 Subject: Web Page Construction in Python In-Reply-To: References: Message-ID: <6elf0eF7k1pvU1@mid.uni-berlin.de> SUBHABRATA schrieb: > Dear Group, > I am getting some questions on doing Web Pages in Python. > I have some interactive codes in python for which I like to make web > pages. > I am trying to use kid. > Kid I learnt, and is easy, too. > My questions are: > i) Am I going correct? > ii) Is there any language other than kid? > iii) The worked out examples of kid are not opening properly, is there > any other URL where I can see them. > iv) Can cgi scripting be done with kid? > If any one can spend time on my questions. I suggest you take a look at TurboGears. It's a web-framework that uses KID (or genshi, which is extremely similar) to render pages, and makes web-development considerably easier. http://www.turbogears.org/ Diez From sjmachin at lexicon.net Mon Jul 7 20:48:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 7 Jul 2008 17:48:15 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <6deq2uF21vo2U1@mid.uni-berlin.de> <9b841be4-cd9c-4782-8498-55f053cdbb71@x41g2000hsb.googlegroups.com> Message-ID: On Jul 8, 2:51 am, Henning Thornblad wrote: > When trying to find an alternative way of solving my problem i found > that running this script: > > #!/usr/bin/env python > > import re > > row="" > for a in range(156000): > row+="a" > print "How many, dude?" > print re.search('/[^ "=]*',row) (the / has moved) > > wouldn't take even a second (The re.search part of course) > > This is for me very strange since this, > in theory, is the same problem as before. In theory. In practice, it is the same problem *iff* you start at the end of the text and work backwards. Your original pattern can be characterised as X*Y, where X and Y are character classes; your new one is YX*. You are asking each to search a text that contains many Xs and no Ys. The second pattern will cause a naive search engine to examine each character in the text (is it a Y?) as a candidate for the start of a successful match; each test fails, and the whole expedition has cost O(N). OTOH, the first pattern will start at offset 0, cheerfully cruising past all those lovely Xs, but failing (no Y) at the end of the text. It will then think that it's been too greedy, reduce the matched span of X* from N characters to N-1, fail to find Y, N-2, fail, ... so that's O(N) just for the first trial starting from offset 0. Being naive, it will try again starting from offset 1, 2, 3, ... an O(N**2) process. If Y were instead something more complicated, it would be worse than O(N**2). If you were to tell us what you are actually trying to do, we could probably help you with a faster method. BTW, if the text is 'aaa///bbb///ccc', your original search will find 'aaa///bbb///'; if you want it to find 'aaa/', the pattern should be: '[^ "=/]*/' Cheers, John From henrik at chamalulu.com Tue Jul 1 18:47:20 2008 From: henrik at chamalulu.com (chamalulu) Date: Tue, 1 Jul 2008 15:47:20 -0700 (PDT) Subject: Attribute reference design References: <6cvlk4F3s90U1@mid.uni-berlin.de> Message-ID: On Jul 1, 11:24 pm, "Diez B. Roggisch" wrote: > chamalulu schrieb: > > > Hello. > > I think I'm aware of how attribute access is resolved in python. When > > referencing a class instance attribute which is not defined in the > > scope of the instance, Python looks for a class attribute with the > > same name. (For assignment or deletion this is not the case, > > thankfully.) > > I've been trying to understand why? What is the reason behind, or > > practical purpose of, this design decision? Anyone, please enlighten > > me. > > How else would you resolve methods which are of course defined on the > class but invoked through the instance? > Yes, of course... You're right. Didn't think of that. Thank you. I'll go stand in the corner. :) I think I haven't got this bound/unbound stuff through my head yet. If I dir() a class instance I see the methods right there. Are they not bound to the class instance at instanciation (and as such be attributes of the class instance)? /Henrik From frank at chagford.com Tue Jul 22 11:28:24 2008 From: frank at chagford.com (Frank Millman) Date: Tue, 22 Jul 2008 08:28:24 -0700 (PDT) Subject: Is this a valid use of 'import'? References: Message-ID: <70869cae-ba4f-46c7-9def-c3e6175c3275@m45g2000hsb.googlegroups.com> On Jul 22, 5:22?pm, Tim Golden wrote: > Frank Millman wrote: > > In this particular case, when it is executed, it does a whole lot > > more. It reads in some parameters, establishes a socket connection, > > starts a thread, and starts monitoring the socket using select.select. > > It also exposes some functions that disguise the complexity of reading > > from and writing to the socket. > > This is not, in general, a good idea, no matter how appealing! > There is some subtle stuff going on within the chain of imports, > and firing off a new thread is quite likely to confuse it in > nasty ways later on. Less attractive though it may be, you're > better off having a "startup" function or whatever and calling > that: > > import Utils.client > Utils.client.startup () > > TJG Makes sense. Thanks, Tim. Frank From rajanikanth at gmail.com Tue Jul 8 18:16:21 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Tue, 8 Jul 2008 15:16:21 -0700 Subject: (silly?) speed comparisons In-Reply-To: References: Message-ID: <84bdef3c0807081516g7872d1d8x2ecb448fd1fa900c@mail.gmail.com> Try using a list instead of a vector for the C++ version. Raj On Tue, Jul 8, 2008 at 3:06 PM, mk wrote: > Out of curiosity I decided to make some speed comparisons of the same > algorithm in Python and C++. Moving slices of lists of strings around seemed > like a good test case. > > Python code: > > def move_slice(list_arg, start, stop, dest): > frag = list_arg[start:stop] > if dest > stop: > idx = dest - (stop - start) > else: > idx = dest > del list_arg[start:stop] > list_arg[idx:idx] = frag > return list_arg > > b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] > >>>> import timeit >>>> t = timeit.Timer("move_slice.move_slice(move_slice.b, 4, 6, 7)", "import >>>> move_slice") >>>> t.timeit() > 3.879252810063849 > > (Python 2.5, Windows) > > Implementing the same algorithm in C++: > > #include > #include > #include > > using namespace std; > > vector move_slice(vector vec, int start, int stop, int dest) > { > int idx = stop - start; > vector frag; > > // copy a fragment of vector > for (idx = start; idx < stop; idx++) > frag.push_back(vec.at(idx)); > if( dest > stop) > idx = dest - (stop - start); > else > idx = dest; > // delete the corresponding fragment of orig vector > vec.erase( vec.begin() + start, vec.begin() + stop); > > // insert the frag in proper position > vec.insert( vec.begin() + idx, frag.begin(), frag.end()); > > return vec; > } > > > int main(int argc, char* argv) > { > vector slice; > string u = "abcdefghij"; > int pos; > for (pos = 0; pos < u.length(); pos++) > slice.push_back(u.substr(pos,1)); > > int i; > for (i = 0; i<1000000; i++) > move_slice(slice, 4, 6, 7); > > } > > Now this is my first take at vectors in C++, so it's entirely possible that > an experienced coder would implement it in more efficient way. Still, > vectors of strings seemed like a fair choice - after all, Python version is > operating on similarly versatile objects. > > But I was still rather surprised to see that C++ version took 15% longer to > execute! > > (vector, 4, 6, 7) > $ time slice > > > real 0m4.478s > user 0m0.015s > sys 0m0.031s > > Compiler: MinGW32/gcc 3.4.5, with -O2 optimization (not cygwin's gcc, which > for some reason seems to produce sluggish code). > > > When I changed moving the slice closer to the end of the list / vector, > Python version executed even faster: > >>>> t = timeit.Timer("move_slice.move_slice(move_slice.b, 6, 7, 7)", "import >>>> move_slice") >>>> t.timeit() > 1.609766883779912 > > C++: > > (vector, 6, 7, 7) > $ time slice.exe > > > real 0m3.786s > user 0m0.015s > sys 0m0.015s > > Now C++ version took over twice the time to execute in comparison to Python > time! > > > Am I comparing apples to oranges? Should the implementations be different? > Or does the MinGW compiler simply suck? > > Note: it appears that speed of Python lists falls down quickly the closer to > the list beginning one deletes or inserts elements. C++ vectors do not seem > to be as heavily position-dependent. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From deets at nospam.web.de Tue Jul 29 03:35:41 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jul 2008 09:35:41 +0200 Subject: Python COM In-Reply-To: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> References: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> Message-ID: <6f7vieFa8u2cU1@mid.uni-berlin.de> birdprince at gmail.com schrieb: > I have implemented a COM in C++,buy i don't know how to use this COM > in python. > For example: the COM's ProgID is "MyCOM1.AdvMethod".this COM have two > interfaces,the default interface's name is IAdvMethod,the second > interface's name is IBasicMethod. > How do i use those interfaces in python.Thank you very much,please > answer my question in code. http://starship.python.net/crew/theller/comtypes/ Diez From alan.isaac at gmail.com Tue Jul 22 14:19:34 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Tue, 22 Jul 2008 18:19:34 GMT Subject: sys.stderr.write returns string length in Python 3 Message-ID: Is this new behavior intentional? :: >>> sys.stderr.write("thisisatest\n") thisisatest 12 Here is the reason for it: >>> help(sys.stderr.write) Help on method write in module io: write(self, s: str) method of io.TextIOWrapper instance Thank you, Alan Isaac From JO3chiang at gmail.com Tue Jul 8 03:02:59 2008 From: JO3chiang at gmail.com (jo3c) Date: Tue, 8 Jul 2008 00:02:59 -0700 (PDT) Subject: windows active directory ldap output encoding Message-ID: Hi.. Im trying to get some information out of a windows sever 2003 chinese active directory system so let's say encoding is probably big5 or utf-8 what im doing is simliar to ldapsearch in shell with my python script using python ldap module the result is not the correct encoding.. i've look many places and tried many different encoding on the top of the script #coding=big5 etc.. below is the wrong encoding output .. any help will be much appreciated.. *** ldap://2134.localhost.com:389 - SimpleLDAPObject.set_option ((17, 3),{}) CN=?,OU=2134,DC=localhost,DC=com {'accountExpires': ['9223372036854775807'], 'badPasswordTime': ['128566014672343750'], 'badPwdCount': ['0'], 'cn': ['\xe6\xb1\x9f\xe6\x9f\x8f\xe5\xa3\x95'], 'codePage': ['0'], 'company': ['\xe8\x8f\xaf\xe8\x81\xaf\xe7\x94\x9f \xe7\x89\xa9\xe7\xa7\x91\xe6\x8a\x80'], 'countryCode': ['0'], 'department': ['\xe7\x94\x9f\xe7\x89\xa9\xe7\xa7\x91\xe6\x8a \x80\xe8\x99\x95'], 'displayName': ['\xe6\xb1\x9f\xe6\x9f\x8f\xe5\xa3\x95'], 'distinguishedName': ['CN=\xe6\xb1\x9f\xe6\x9f\x8f \xe5\xa3\x95,OU=300\xe7\xa7\x91\xe6\x8a \x80\xe8\x99\x95,DC=localhost,DC=com'], 'givenName': ['\xe6\x9f\x8f\xe5\xa3\x95'], 'homeMDB': ['CN=\xe4\xbf\xa1\xe7\xae\xb1\xe5\x84\xb2\xe5\xad \x98\xe5\x8d\x80 (MAIL),CN=\xe9\xa0\x90\xe8\xa8\xad\xe5\x84\xb2\xe5\xad \x98\xe7\xbe\xa4\xe7\xb5\x84,CN=InformationStore,CN=MAIL,CN=Servers,CN= \xe9\xa0\x90\xe8\xa8\xad\xe7\xb3\xbb\xe7\xb5\xb1\xe7\xae \xa1\xe7\x90\x86\xe7\xbe\xa4\xe7\xb5\x84,CN=Administrative Groups,CN=localhost,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=localhost,DC=com'], 'homeMTA': ['CN=Microsoft MTA,CN=MAIL,CN=Servers,CN= \xe9\xa0\x90\xe8\xa8\xad\xe7\xb3\xbb\xe7\xb5\xb1\xe7\xae \xa1\xe7\x90\x86\xe7\xbe\xa4\xe7\xb5\x84,CN=Administrative Groups,CN=localhost,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=localhost,DC=com'], 'instanceType': ['4'], 'lastLogoff': ['0'], 'lastLogon': ['128598965066718750'], 'legacyExchangeDN': ['/o=localhost/ou=ExchangAdmin/cn=Recipients/ cn=joechiang'], 'logonCount': ['33'], 'mDBUseDefaults': ['TRUE'], 'mail': ['joechiang at localhost.com'], 'mailNickname': ['joechiang'], 'memberOf': ['CN=AllHQStaff,CN=Users,DC=localhost,DC=com'], 'msExchALObjectVersion': ['60'], 'msExchHomeServerName': ['/o=localhost/ou=ExchangAdmin/ cn=Configuration/cn=Servers/cn=MAIL'], 'msExchMailboxGuid': ['2\x04\x116^\xfc%J\x87yi\xbdj^\x1bl'], 'msExchMailboxSecurityDescriptor': ['\x01\x00\x04\x80x \x00\x00\x00\x94\x00\x00\x00\x00\x00\x00\x00\x14\x00\x00\x00\x04\x00d \x00\x01\x00\x00\x00\x00\x02\x14\x00\x03\x00\x02\x00\x01\x01\x00\x00\x00\x00\x00\x05\n \x00\x00\x00a\x00n\x00x\x00/\x00C\x00N\x00=\x00C\x00o\x00n\x00f\x00i \x00g\x00u\x00r\x00a\x00t\x00i\x00o\x00n \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x05\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00\xd6\xb2i \x1a^\xa7P\xcb\xday \x88\xa9\xf4\x01\x00\x00\x01\x05\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00\xd6\xb2i \x1a^\xa7P\xcb\xday\x88\xa9\xf4\x01\x00\x00'], 'msExchPoliciesIncluded': ['{C96E41C5-C5D5-411B-8672-1A3B6602437F}, {3B6813EC-CE89-42BA-9442-D87D4AA30DBC}', '{C96E41C5-C5D5-411B-8672-1A3B6602437F}, {26491CFC-9E50-4857-861B-0CB8DF22B5D7}'], 'msExchUserAccountControl': ['0'], 'name': ['\xe6\xb1\x9f\xe6\x9f\x8f\xe5\xa3\x95'], 'objectCategory': ['CN=Person,CN=Schema,CN=Configuration,DC=localhost,DC=com'], 'objectClass': ['top', 'person', 'organizationalPerson', 'user'], 'objectGUID': ['\x13\xfa\xc2\xbb\x9e\xee|C\x9d\xa8_\xea]\xef \xc6\x90'], 'objectSid': ['\x01\x05\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00\xd6\xb2i\x1a^\xa7P \xcb\xday\x88\xa9u\x0c\x00\x00'], 'primaryGroupID': ['513'], 'proxyAddresses': ['X400:c=TW;a= ;p=localhost;o=Exchange;s=joechiang;', 'SMTP:joechiang at localhost.com'], 'pwdLastSet': ['128587670396562500'], 'sAMAccountName': ['joechiang'], 'sAMAccountType': ['805306368'], 'showInAddressBook': ['CN=\xe5\x85\xa8\xe5\x9f\x9f\xe9\x80\x9a \xe8\xa8\x8a\xe6\xb8\x85\xe5\x96\xae,CN=All Global Address Lists,CN=Address Lists Container,CN=localhost,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=localhost,DC=com', 'CN=\xe7\x87\x9f\xe9\x81\x8b\xe8\x99\x95,CN=All Address Lists,CN=Address Lists Container,CN=localhost,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=localhost,DC=com', 'CN=\xe7\x94\x9f\xe7\x89\xa9\xe7\xa7\x91\xe6\x8a \x80\xe8\x99\x95,CN=All Address Lists,CN=Address Lists Container,CN=localhost,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=localhost,DC=com', 'CN=\xe6\x89\x80\xe6\x9c\x89\xe4\xbd\xbf \xe7\x94\xa8\xe8\x80\x85,CN=All Address Lists,CN=Address Lists Container,CN=localhost,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=localhost,DC=com'], 'sn': ['\xe6\xb1\x9f'], 'textEncodedORAddress': ['c=TW;a= ;p=localhost;o=Exchange;s=joechiang;'], 'uSNChanged': ['22943844'], 'uSNCreated': ['21991450'], 'userAccountControl': ['66048'], 'userPrincipalName': ['joe at localhost.com'], 'whenChanged': ['20080624074423.0Z'], 'whenCreated': ['20071205035154.0Z']} None From socyl at 987jk.com.invalid Tue Jul 29 09:27:53 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 13:27:53 +0000 (UTC) Subject: backspace problems Message-ID: If I'm in the python interactive interpreter, I get a beep when I hit the backspace key. I must confess, though, that my terminal is "complicated", to put it mildly: I work on a Mac running Leopard; I open a Terminal session, and through it I ssh to an Ubuntu server; on this server I connect to a permanently-running GNU screen session, which has several multiplexed windows going, all running zsh; it is in this convoluted environment that I run the python interactive interpreter.[*] I've determined that the problem occurs only within the GNU screen session. GNU screen is one of the coolest Unix programs ever, one that literally changed the way I work, is there's no way I'll stop using it. So I need to figure out how to fix this. How can I determine the character that the python session is receiving when I hit the backspace key, and how can I tell it to handle it as a backward-delete character? TIA! kynn [*] Actually, it gets worse. My .zshrc file (which gets executed whenever an interactive shell is started) runs the command bindkey '^[[3~' backward-delete-char because, otherwise my regular zsh interaction would not handle the backspace key properly. But the problem I described above occurs whether this command is executed or not. -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From s0suk3 at gmail.com Mon Jul 28 04:47:12 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Mon, 28 Jul 2008 01:47:12 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> <6385b0a8-f7f3-4dc3-91be-e6f158ffb439@a1g2000hsb.googlegroups.com> Message-ID: <13c15de6-2e28-4896-a6ab-67572a27c001@y21g2000hsf.googlegroups.com> On Jul 28, 1:55 am, Lawrence D'Oliveiro wrote: > In message > , > > > > s0s... at gmail.com wrote: > > On Jul 27, 10:55 pm, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: > >> In message > >> <6385b0a8-f7f3-4dc3-91be-e6f158ffb... at a1g2000hsb.googlegroups.com>, > > >> s0s... at gmail.com wrote: > >> > On Jul 26, 6:47 pm, Lawrence D'Oliveiro >> > central.gen.new_zealand> wrote: > >> >> In message > >> >> <024ace13-f72f-4093-bcc9-f8a339c32... at v1g2000pra.googlegroups.com>, > > >> >> s0s... at gmail.com wrote: > >> >> > On Jul 24, 5:01 am, Lawrence D'Oliveiro >> >> > central.gen.new_zealand> wrote: > > >> >> >> In message > > <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, > > > > >> >> >> Jordan wrote: > > >> >> >> > Except when it comes to Classes. I added some classes to code > >> >> >> > that had previously just been functions, and you know what I did > >> >> >> > - or rather, forgot to do? Put in the 'self'. In front of some of > >> >> >> > the variable accesses, but more noticably, at the start of *every > >> >> >> > single method argument list.* > > >> >> >> The reason is quite simple. Python is not truly an > >> >> >> "object-oriented" language. It's sufficiently close to fool those > >> >> >> accustomed to OO ways of doing things, but it doesn't force you to > >> >> >> do things that way. You still have the choice. An implicit "self" > >> >> >> would take away that choice. > > >> >> > By that logic, C++ is not OO. > > >> >> Yes it is, because it has "this". > > >> > You mean the keyword "this"? It's just a feature. How does that make a > >> > difference on being or not being OO? > > >> Because it was one of the things the OP was complaining about (see > >> above). > > > Wrong. > > Reread what the OP said. Stop quoting only portions of my posts that lead to misinterpretation of them. Next time you quote, be sure to quote this (which I also mentioned in the previous post): What the OP complains about has no relevance on what makes a language OO or not. Do you believe otherwise? From INVALID at EXAMPLE.COM Sun Jul 13 12:54:39 2008 From: INVALID at EXAMPLE.COM (INVALID at EXAMPLE.COM) Date: Sun, 13 Jul 2008 16:54:39 +0000 Subject: spam References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <1bc1ddbb-fbfc-4e0c-8337-71d2dd301e5d@z66g2000hsc.googlegroups.com> Message-ID: rickman wrote: >I love the way that people who plonk others feel the need to inform >everyone of it. That ranks up there with, "I know what you are, but >what am I?" It is a matter of basic politeness and common courtesy. Without the plonk, the killfiled poster is left hanging in the wind, wasting his time writing responses that will never be read. If you were talking with a blind man, would you silently creep out of the room leaving him talking to the walls, or would you be polite and excuse yourself before leaving? From Michael.Coll-Barth at VerizonWireless.com Mon Jul 21 12:12:12 2008 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Mon, 21 Jul 2008 12:12:12 -0400 Subject: Python Written in C? In-Reply-To: References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> Message-ID: <20080721162454.9EB5D1E4008@bag.python.org> > > From: mk > Wrong! Real programmers can program using only Touring machine (and > something having to do with post for some reason). I'm sure our > brilliant OP[1] could program in both. Ah, now we can really got OT. My favorite Touring machine is a Jaguar ( with the pronounced 'U' in there ). Oh, you meant "Turing"; . Sorry, I just couldn't resist after the tortured route this thread has taken. The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From Graham.Dumpleton at gmail.com Mon Jul 21 20:18:24 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Mon, 21 Jul 2008 17:18:24 -0700 (PDT) Subject: Problem with Python Server Pages (PSP) References: <9766b993-03e6-4b75-92a2-06244c41e51c@a1g2000hsb.googlegroups.com> Message-ID: <8ce2ffdd-0fb3-4f5f-bde8-1598f9b231bc@i20g2000prf.googlegroups.com> On Jul 21, 9:42?pm, barun.sah... at gmail.com wrote: > Hi, > > I am facing a very basic problem with PSP. I have installedmod_python > (in fedora Core 1), added the lines required for loading Python > modules and handling PSP pages. I have created a hello.psp page. But > when I try to view this hello.psp page, all Python code are getting > displayed. > > The said page is stored at /var/www/html/psp/hello.psp. I guess this > is some configuration problem with Apache, but not able to figure out > the exact problem. I have tried putting those configuration lines for > psp in both httpd.conf and python.conf files. But still it is not > working. > > The Python module (mod_python) is getting loaded. Because when I > telnet to my server, I can find that in the headers. > > These are the versions of the softwares: > Apache: 2.0.47 > Python: 2.2.3mod_python: 3.0.3 > > Thnaks for all your suggestions. What is the Apache configuration snippet you are using to enable mod_python and PSP file handling? Graham From keith.hughitt at gmail.com Wed Jul 16 11:29:26 2008 From: keith.hughitt at gmail.com (Keith Hughitt) Date: Wed, 16 Jul 2008 08:29:26 -0700 (PDT) Subject: Angle brackets in command-line arguments? References: <52f1cde3-6240-46b0-8b03-478454e87688@b1g2000hsg.googlegroups.com> Message-ID: <16827dd4-4621-43d1-b5ee-ab9340f54a96@m36g2000hse.googlegroups.com> On Jul 16, 11:16?am, Gary Herron wrote: > Keith Hughitt wrote: > > Hi all, > > > I am using someone else's script which expects input in the form of: > > > ? ? ?./script.py arg2 > > > I was wondering if the angle-brackets here have a special meaning? It > > seems like > > they specify an input and output stream to use in place of the > > console. I could not > > find anything in the python manual or Python in a Nut-shell though. > > > Anyone know? > > > Thanks, > > Keith > > -- > >http://mail.python.org/mailman/listinfo/python-list > > In most Unix/Linux and related OS shells, ?the angled brackets *do* > specify input and output streams as you surmise. ?However, they are > *not* seen by the script ?as command line arguments. ?(And they are > *not* brackets, and do not need to be matched. ) > > For any command, > ? cmd < file > redirects the contents of file to cmd's standard input, which in Python > is accessed by reading from sys.stdin (use input or raw_input or > sys.stdin.read...) > > Also for any command, > ? cmd > file > redirects the output of cmd to the named file. ?In Python this can be > accessed using print, sys.stdout.write, ... > > Anything written to sys.stderr will not be caught by the ">" > redirection, ans so will probably end up on the screen instead of in file. > > ?Also various shells will provide similar functionality using a variety > of similar syntaxes: ?<<, >>, >&, and |, and so on. > > Gary Herron Thanks all for the quick response. I should have known it was shell- related. I haven't ever had to use this kind of redirection before, mostly just the single-bracket version to feed the contents of a file into some command. The reason it was causing me concern in the first place was that I was trying to execute a python script from Apache Ant, and it was failing. It turned out that when I escaped the angle brackets in Ant, they were there-after treated as normal command-line arguments, so when the script was then executed, it just had some additional values in sys.argv. I ended up getting around the issue by creating a small bash-script which simply wraps input in angle brackets and then executes the python script itself. That way I didn't have to escape anything in in Ant, and things worked well. Thanks everyone for taking the time to explain things to me. I really appreciate the help :) Take care, Keith From ojeeves at gmail.com Wed Jul 2 08:33:14 2008 From: ojeeves at gmail.com (oj) Date: Wed, 2 Jul 2008 05:33:14 -0700 (PDT) Subject: Email Validation with domain References: Message-ID: <9d6f2e4f-099b-404d-a8db-c87ab15062d6@79g2000hsk.googlegroups.com> On Jul 2, 12:41?pm, Sallu wrote: > Hi All, ? import re > msg=raw_input('Enter the email : ') > > def validateEmail(email): > > ? ? ? ? #if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9] > {1,3})(\\]?)$", email) != None: > ? ? ? ? if re.match("^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$", > email) != None: > ? ? ? ? ? ? ? ? print 'Valis' > ? ? ? ? else: > ? ? ? ? ? ? ? ? print 'not' > > validateEmail(msg) ?i wrote a script above it works fine but it does > not check for valid domain like .com .org .in > how to validate with domain Don't try and check that the TLD (.com .org etc.) is valid with a regular expression. Just don't. Especially now that the rules about domain names are now being relaxed and there is no possible way of you predicating what all the new TLDs will be. Validating that that the e-mail address is in a valid form, and validating the domain is valid are two separate things. If you want to validate the domain, do a DNS lookup on the domain or some such. I don't think there are standard modules to provide this functionality included with python. You could try using the socket module, and reading up on the relevant protocols, or making calls to external programs. From carroll at nospam-tjc.com Thu Jul 17 04:01:26 2008 From: carroll at nospam-tjc.com (Terry Carroll) Date: Thu, 17 Jul 2008 01:01:26 -0700 Subject: How to process a very large (4Gb) tarfile from python? Message-ID: I am trying to do something with a very large tarfile from within Python, and am running into memory constraints. The tarfile in question is a 4-gigabyte datafile from freedb.org, http://ftp.freedb.org/pub/freedb/ , and has about 2.5 million members in it. Here's a simple toy program that just goes through and counts the number of members in the tarfile, printing a status message every N records (N=10,000 for the smaller file; N=100,000 for the larger). I'm finding that memory usage goes through the roof, simply iterating over the tarfile. I'm using over 2G when I'm barely halfway through the file. This surprises me; I'd expect the memory associated with each iteration to be released at the end of the iteration; but something's obviously building up. On one system, this ends with a MemoryError exception. On another system, it just hangs, bringing the system to its knees, to the point that it takes a minute or so to do simple task switching. Any suggestions to process this beast? I suppose I could just untar the file, and process 2.5 million individual files, but I'm thinking I'd rather process it directly if that's possible. Here's the toy code. (One explanation about the "import tarfilex as tarfile" statement. I'm running Activestate Python 2.5.0, and the tarfile.py module of that vintage was buggy, to the point that it couldn't read these files at all. I brought down the most recent tarfile.py from http://svn.python.org/view/python/trunk/Lib/tarfile.py and saved it as tarfilex.py. It works, at least until I start processing some very large files, anyway.) import tarfilex as tarfile import os, time SOURCEDIR = "F:/Installs/FreeDB/" smallfile = "freedb-update-20080601-20080708.tar" # 63M file smallint = 10000 bigfile = "freedb-complete-20080708.tar" # 4,329M file bigiTnt = 100000 TARFILENAME, INTERVAL = smallfile, smallint # TARFILENAME, INTERVAL = bigfile, bigint def filetype(filename): return os.path.splitext(filename)[1] def memusage(units="M"): import win32process current_process = win32process.GetCurrentProcess() memory_info = win32process.GetProcessMemoryInfo(current_process) bytes = 1 Kbytes = 1024*bytes Mbytes = 1024*Kbytes Gbytes = 1024*Mbytes unitfactors = {'B':1, 'K':Kbytes, 'M':Mbytes, 'G':Gbytes} return memory_info["WorkingSetSize"]//unitfactors[units] def opentar(filename): modes = {".tar":"r", ".gz":"r:gz", ".bz2":"r:bz2"} openmode = modes[filetype(filename)] openedfile = tarfile.open(filename, openmode) return openedfile TFPATH=SOURCEDIR+'/'+TARFILENAME assert os.path.exists(TFPATH) assert tarfile.is_tarfile(TFPATH) tf = opentar(TFPATH) count = 0 print "%s memory: %sM count: %s (starting)" % (time.asctime(), memusage(), count) for tarinfo in tf: count += 1 if count % INTERVAL == 0: print "%s memory: %sM count: %s" % (time.asctime(), memusage(), count) print "%s memory: %sM count: %s (completed)" % (time.asctime(), memusage(), count) Results with the smaller (63M) file: Thu Jul 17 00:18:21 2008 memory: 4M count: 0 (starting) Thu Jul 17 00:18:23 2008 memory: 18M count: 10000 Thu Jul 17 00:18:26 2008 memory: 32M count: 20000 Thu Jul 17 00:18:28 2008 memory: 46M count: 30000 Thu Jul 17 00:18:30 2008 memory: 55M count: 36128 (completed) Results with the larger (4.3G) file: Thu Jul 17 00:18:47 2008 memory: 4M count: 0 (starting) Thu Jul 17 00:19:40 2008 memory: 146M count: 100000 Thu Jul 17 00:20:41 2008 memory: 289M count: 200000 Thu Jul 17 00:21:41 2008 memory: 432M count: 300000 Thu Jul 17 00:22:42 2008 memory: 574M count: 400000 Thu Jul 17 00:23:47 2008 memory: 717M count: 500000 Thu Jul 17 00:24:49 2008 memory: 860M count: 600000 Thu Jul 17 00:25:51 2008 memory: 1002M count: 700000 Thu Jul 17 00:26:54 2008 memory: 1145M count: 800000 Thu Jul 17 00:27:59 2008 memory: 1288M count: 900000 Thu Jul 17 00:29:03 2008 memory: 1430M count: 1000000 Thu Jul 17 00:30:07 2008 memory: 1573M count: 1100000 Thu Jul 17 00:31:11 2008 memory: 1716M count: 1200000 Thu Jul 17 00:32:15 2008 memory: 1859M count: 1300000 Thu Jul 17 00:33:23 2008 memory: 2001M count: 1400000 Traceback (most recent call last): File "C:\test\freedb\tardemo.py", line 40, in for tarinfo in tf: File "C:\test\freedb\tarfilex.py", line 2406, in next tarinfo = self.tarfile.next() File "C:\test\freedb\tarfilex.py", line 2311, in next tarinfo = self.tarinfo.fromtarfile(self) File "C:\test\freedb\tarfilex.py", line 1235, in fromtarfile obj = cls.frombuf(buf) File "C:\test\freedb\tarfilex.py", line 1193, in frombuf if chksum not in calc_chksums(buf): File "C:\test\freedb\tarfilex.py", line 261, in calc_chksums unsigned_chksum = 256 + sum(struct.unpack("148B", buf[:148]) + struct.unpack("356B", buf[156:512])) MemoryError From drakonik at gmail.com Tue Jul 15 09:13:02 2008 From: drakonik at gmail.com (Nick Dumas) Date: Tue, 15 Jul 2008 09:13:02 -0400 Subject: Suggestion: Python global scope In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 The function of the global keyword is to 'push' local variables to the global scope. If you want to 'import' a variable into a local scope, pass the variable to your function/method as an argument. Anonymous Bastard wrote: > I've been tossing this idea in my mind for some time now: > > In Python, declaring a variable using the global statement automatically > makes it available in all subsequent scopes. > > But to me, it makes more sense to use the global statement to 'import' a > variable from the global scope into the current scope. For instance: > > [code] > global X > X = 1 > > def P(): > X = 2 > print X > global X > print X > > print X > P() > print X > [code] > > Currently, this will print 1, 2, 2 and 2. But if global would be limited > to current scope, it would print 1, 2, 1, 1. > > 'X = 2' would work on the local version of X, 'global X' will 'import' > the global X into the local scope, so any actions on X would reference > the global X, rather than previous X. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkh8ol4ACgkQLMI5fndAv9ieGwCgi51Vs45tgj3mbom0BeM/nBzL XwsAnjRZr9An617xXyiWp9AVBv3FQ3+z =EFee -----END PGP SIGNATURE----- From socyl at 987jk.com.invalid Wed Jul 30 16:41:48 2008 From: socyl at 987jk.com.invalid (kj) Date: Wed, 30 Jul 2008 20:41:48 +0000 (UTC) Subject: how to split text into lines? Message-ID: In Perl, one can break a chunk of text into an array of lines while preserving the trailing line-termination sequence in each line, if any, by splitting the text on the regular expression /^/: DB<1> x split(/^/, "foo\nbar\nbaz") 0 'foo ' 1 'bar ' 2 'baz' But nothing like this seems to work in Python: >>> re.split('^', 'foo\nbar\nbaz') ['foo\nbar\nbaz'] (One gets the same result if one adds the re.MULTILINE flag to the re.split call.) What's the Python idiom for splitting text into lines, preserving the end-of-line sequence in each line? -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From fredrik at pythonware.com Sun Jul 20 09:29:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jul 2008 15:29:15 +0200 Subject: Rotating a cube In-Reply-To: <4881BBCF.2060905@preisshare.net> References: <3d47df08-9734-4e0f-96ad-37da445b4faf@34g2000hsh.googlegroups.com> <8156f68a-3f65-4fca-a725-2e0c4240abd1@v21g2000pro.googlegroups.com> <4881BBCF.2060905@preisshare.net> Message-ID: David Lyon wrote: > But is the question about display graphics ? > > ie rotating a cube using a python framework ? > > With something like python and OpenGL ? or Python and PovRay... or > perphaps python and imagemagick ? can you name one graphics framework that represents a cube as "x + 4*y + 16*z" ? From cokofreedom at gmail.com Thu Jul 24 11:07:34 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 24 Jul 2008 08:07:34 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <40449826-c71d-4c6e-8b74-13069269e5da@z6g2000pre.googlegroups.com> <488896bf$0$3493$426a74cc@news.free.fr> <3d56ad67-bcd7-4840-979a-8648292afcff@j7g2000prm.googlegroups.com> Message-ID: <402c3712-f9bc-4605-b559-33b5adf9c530@b1g2000hsg.googlegroups.com> > > My words aren't as clear as they should be. I mean that Python lets > *you* do something without documenting, or rather stating to use a > better term, that your intention is the non-obvious one. I'm not > saying that Python itself lacks documentation for its own behaviour; > I'm saying it should force you to make your intentions clear and > visible to someone reading your code when you want to do something non- > obvious. > I take it you are relating to the need for less comments within the code as the idea is the Python code itself is readable? Or are you saying that when someone does a clever trick it should be documented better? I'm a little confused as what you mean by no-documenting? I always add doc-strings to modules I will be using heavily as well as a README with them. But that isn't different from programming in other languages and using comments. (Do you mean something like JavaDoc?) From keith.hughitt at gmail.com Wed Jul 9 10:04:04 2008 From: keith.hughitt at gmail.com (Keith Hughitt) Date: Wed, 9 Jul 2008 07:04:04 -0700 (PDT) Subject: Allow tab completion when inputing filepath? Message-ID: Hi all, I've been looking around on the web for a way to do this, but so far have not come across anything for this particular application. I have found some ways to enable tab completion for program-related commands, but not for system filepaths. This would be nice to have when prompting the user to enter a file/directory location. Any suggestions? Thanks, Keith From bruno.desthuilliers at gmail.com Wed Jul 9 16:22:15 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 9 Jul 2008 13:22:15 -0700 (PDT) Subject: Anyone happen to have optimization hints for this loop? References: <43111321-2cc1-4a5e-9189-744131555841@26g2000hsk.googlegroups.com> Message-ID: <7f6c348f-3d49-4483-a3cc-7d4b8eb863a4@27g2000hsf.googlegroups.com> On 9 juil, 18:04, dp_pearce wrote: > I have some code that takes data from an Access database and processes > it into text files for another application. At the moment, I am using > a number of loops that are pretty slow. I am not a hugely experienced > python user so I would like to know if I am doing anything > particularly wrong or that can be hugely improved through the use of > another method. > > Currently, all of the values that are to be written to file are pulled > from the database and into a list called "domainVa". These values > represent 3D data and need to be written to text files using line > breaks to seperate 'layers'. I am currently looping through the list > and appending a string, which I then write to file. This list can > regularly contain upwards of half a million values... > > count = 0 > dmntString = "" > for z in range(0, Z): > for y in range(0, Y): > for x in range(0, X): > fraction = domainVa[count] > dmntString += " " > dmntString += fraction > count = count + 1 > dmntString += "\n" > dmntString += "\n" > dmntString += "\n***\n > > dmntFile = open(dmntFilename, 'wt') > dmntFile.write(dmntString) > dmntFile.close() > > I have found that it is currently taking ~3 seconds to build the > string but ~1 second to write the string to file, which seems wrong (I > would normally guess the CPU/Memory would out perform disc writing > speeds). Not necessarily - when the dataset becomes too big and your process has eaten all available RAM, your OS starts swapping, and then it's getting worse than disk IO. IOW, for large datasets (for a definition of 'large' depending on the available resources), you're sometimes better doing direct disk access - which BTW are usually buffered by the OS. > Can anyone see a way of speeding this loop up? Perhaps by changing the > data format? Almost everyone told you to use a list and str.join()... Which used to be a sound advice wrt/ both performances and readability, but nowadays "only" makes your code more readable (and pythonic...) : bruno at bibi ~ $ python Python 2.5.1 (r251:54863, Apr 6 2008, 17:20:35) [GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from timeit import Timer >>> def dostr(): ... s = '' ... for i in xrange(10000): ... s += ' ' + str(i) ... >>> def dolist(): ... s = [] ... for i in xrange(10000): ... s.append(str(i)) ... s = ' '.join(s) ... >>> tstr = Timer("dostr", "from __main__ import dostr") >>> tlist = Timer("dolist", "from __main__ import dolist") >>> tlist.timeit(10000000) 1.4280490875244141 >>> tstr.timeit(10000000) 1.4347598552703857 >>> The list + str.join version is only marginaly faster... But you should consider this solution even if doesn't that change much to perfs - readabilty counts, too// > Is it wrong to append a string and write once, or should > hold a file open and write at each instance? Is it really a matter of one XOR the other ? Perhaps you should try a midway solution, ie building not-too-big chunks as lists, and writing them to the (opened file) ? This would avoids possible swap and reduce disk IO. I suggest you try this approach with different list-size / write ratios, using the timeit module (and eventually the "top" program on unix or it's equivalent if you're on another platform to check memory/CPU usage) to find out which ratio works best for a representative sample of your input data. That's at least what I'd do... HTH From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 2 04:34:46 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Jul 2008 10:34:46 +0200 Subject: How to make a function associated with a class? In-Reply-To: <0d9c534b-8720-4363-b3e5-eb546dd3637c@8g2000hse.googlegroups.com> References: <69e26f9b-2f00-4318-9bc5-6aa94e141bca@59g2000hsb.googlegroups.com> <4d7cf477-e791-4122-bc20-0dbd1a16bc12@j22g2000hsf.googlegroups.com> <0d9c534b-8720-4363-b3e5-eb546dd3637c@8g2000hse.googlegroups.com> Message-ID: <486b3da1$0$6039$426a34cc@news.free.fr> Kurda Yon a ?crit : > On Jul 1, 5:01 pm, "bruno.desthuilli... at gmail.com" > wrote: >> On 1 juil, 22:43, Kurda Yon wrote: >> >> >> >>> Hi, >>> I have a class called "vector". And I would like to define a function >>> "dot" which would return a dot product of any two "vectors". I want >>> to call this function as follow: dot(x,y). >>> Well, I can define a functions "dot" outside the class and it works >>> exactly as I want. However, the problem is that this function is not >>> associated with the class (like methods a method of the class). >>> For example, if I call "x.calc()" or "y.calc()", python will execute >>> different methods if "x" and "y" belongs to different classes. I want >>> to have the same with my "dot" function. I.e. I want it calculates the >>> dot product ONLY IF the both arguments of that function belong to the >>> "vector" class. >>> Is it possible? >> You don't need to make dot() a method of your Vector class to have >> this behaviour, and making it a method of the Vector class isn't >> enough to have this behaviour. >> >> The simplest solution would be: >> >> class Vector(object): >> def dot(self, other): >> if not isinstance(other, type(self)): >> raise TypeError("can only calculate the dot product of two >> vectors") >> # do the job here and return what's appropriate >> >> Now since it's a binary operator, you might as well implement it as >> such: >> >> class Vector(object): >> def __mul__(self, other): >> if not isinstance(other, type(self)): >> raise TypeError("can only calculate the dot product of two >> vectors") >> # do the job here and return what's appropriate >> >> Then use it as doproduct = vector1 * vector2 >> >> HTH > > As far as I understood, In the first case, you gave, I need to call > the function as follows "x.dot(y)". In the second case I need to call > the function as follows "x*y". But I want to call the function as > follows "dot(x,y)". I tought you could figure it out by yourself from the above examples. > By the way, "type(self)" returns the name of the class to which the > "self" belongs? Nope, it returns the class object (for new-style classes at least). > Does "instance" return "true" if the first argument belongs to the > class whose name Python's classes are objects. type() returns a class object (or a type object for old-style classes IIRC), and isinstance() takes a class or style object (or a tuple of class / type objects) as second argument. > is given in the second argument? isinstance() is documented, you know ? As well as type() FWIW. What about first looking up the fine manual, then come back if there's something you have problem with ?-) From wtanksleyjr at gmail.com Tue Jul 22 17:07:37 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Tue, 22 Jul 2008 14:07:37 -0700 (PDT) Subject: Bidirectional Generators Message-ID: <8e2cf6b7-4b5f-4701-8a4c-bc779ed7305c@m45g2000hsb.googlegroups.com> Okay, I'm almost finished with my first bidirectional generator. By "almost finished" I mean both that it's almost working, and that I'm almost about to replace it with a class that works a bit more like what I currently understand. Surely some other people have worked with this feature... Are there any pages that discuss how it's been useful? No, I don't want to see an implementation of coroutines. I get that one already. :-) -Wm From peter.bulychev at gmail.com Tue Jul 1 14:31:15 2008 From: peter.bulychev at gmail.com (Peter Bulychev) Date: Tue, 1 Jul 2008 22:31:15 +0400 Subject: convert unicode characters to visibly similar ascii characters Message-ID: Hello. I want to convert unicode character into ascii one. The method ".encode('ASCII') " can convert only those unicode characters, which fit into 0..128 range. But there are still lots of characters beyond this range, which can be manually converted to some visibly similar ascii characters. For instance, there are several quotation marks in unicode, which can be converted into ascii quotation mark. Can this conversion be performed in automatic manner? After googling I've only found that there exists Unicode database, which stores human-readable information on notation of all unicode characters ( ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt). And there also exists the Python adapter for this database ( http://docs.python.org/lib/module-unicodedata.html). Using this database I can do something like `if notation.find('QUOTATION')!=-1:\n\treturn "'"`. I believe there is more elegant way. Am I right? Thanks. -- Best regards, Peter Bulychev. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Sun Jul 20 23:51:59 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 20 Jul 2008 20:51:59 -0700 (PDT) Subject: Python Written in C? References: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> Message-ID: On Jul 20, 10:05?pm, Stephen Johnson wrote: > > Carry bits? Who worries about carry bits when you have > > unlimited precision arithmetic? You want cool? > > THIS is cool: > > > j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2])) > > % xyz[1]**(k-1))/xyz[1]**(k-2) > > You call that "cool." I call it "unreadable." Ok, but not in the sense that something like Scheme is unreadable as this is nothing but algebra (albeit complicaed). > > -Steve Johnson From notnorwegian at yahoo.se Sat Jul 12 17:35:58 2008 From: notnorwegian at yahoo.se (maestro) Date: Sat, 12 Jul 2008 14:35:58 -0700 (PDT) Subject: Why is there no GUI-tools like this for Windows? Message-ID: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> http://www.youtube.com/watch?v=PXpwC1o5AcI I have done some GUI-programming for windows with Python but the Tkinter interface sucked and while it is the only one I tried I got the impression they are all the same. It's amazing how retarded a lot of the stuff programmers do is. Watcing that video, that is how it should be. I can just do the layout with my mouse and then there is a program that writes the code for me. GUI-programming is hard for no reason. One good program then forever easy... Is there not something like this for Python/Windows? Is the Linux one only for ruby or for any language? Oh well im switching to Linux anyway and mostly write webapps but still... From craig.pastro at gmail.com Thu Jul 10 13:32:52 2008 From: craig.pastro at gmail.com (craig75) Date: Thu, 10 Jul 2008 10:32:52 -0700 (PDT) Subject: Idiomatic Python to convert list to dict References: <7ec9405c-4e6f-491d-84b2-c81152302b13@79g2000hsk.googlegroups.com> Message-ID: <89d99e55-4a26-4d76-813a-debcf8ff9901@s50g2000hsb.googlegroups.com> On Jul 10, 10:06?am, James Fassett wrote: > Hi all, > > Simple question really on a best practice. I want to avoid adding > duplicates to a list. > > my_list = ['a', 'b', 'c', 'd', 'e'] > dup_map = {} > for item in my_list: > ? ? dup_map[item] = True > > # ... sometime later > > for complex_dict in large_list: > ? ? if complex_dict["char"] not in dup_map: > ? ? ? ? my_list.append(complex_dict["char"]) > ? ? ? ? dup_map[complex_dict["char"]] = True > > For the first part (generating the duplicate map) is there a more > idiomatic Python method for flipping the list into a dict? > > Is there a better way to achieve the overall objective (as hinted at > by the above algorithm)? > > Thanks in advance for any tips. > > James. The dictionary seems like overkill here because, if I understand correctly, the only value associated with a key is "True". So in that case just remove all the code related to the dictionary (and complex_dict) and you end up with my_list = ['a', 'b', 'c', 'd', 'e'] # ... sometime later for char in large_list: if char not in my_list: my_list.append(char) However, as Diez suggests, use a set: my_list = set(['a', 'b', 'c', 'd', 'e']) # ... sometime later for char in large_list: my_list.add(char) # will not add duplicates From ojeeves at gmail.com Fri Jul 25 11:13:55 2008 From: ojeeves at gmail.com (oj) Date: Fri, 25 Jul 2008 08:13:55 -0700 (PDT) Subject: Calling external program from within python References: <6eu684F91muhU1@mid.uni-berlin.de> <6eu75mF92mqcU1@mid.uni-berlin.de> Message-ID: On Jul 25, 3:44?pm, "Diez B. Roggisch" wrote: > Because usually if a program *prompts* the user to enter input (and that > was what I read from the OP's post), one has to deal with pseudo > terminals, not with stdin/out. How does the program writing some text before taking input change how it takes input? If it runs in a terminal and takes input from the user via keyboard, as in the user types a response and presses enter, it's most likely using stdin, in which case subprocess would be perfect. Perhaps that OP can clarify how the tcal program takes input? From bignose+hates-spam at benfinney.id.au Mon Jul 28 20:44:39 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 29 Jul 2008 10:44:39 +1000 Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> <488e3520$0$16766$426a74cc@news.free.fr> Message-ID: <87myk1iknc.fsf@benfinney.id.au> Bruno Desthuilliers writes: > Boy, I don't know who you think you're talking to, but you're > obviously out of luck here. I'm 41, married, our son is now a > teenager, I have an happy social life, quite a lot of work, and no > time to waste in the streets. And FWIW, name-calling won't buy you > much here. It has, at least, long ago bought him a place in my kill-file. Seeing your side of the conversation, I can only confirm that decision as correct. -- \ ?bash awk grep perl sed, df du, du-du du-du, vi troff su fsck | `\ rm * halt LART LART LART!? ?The Swedish BOFH, | _o__) alt.sysadmin.recovery | Ben Finney From basti.wiesner at gmx.net Thu Jul 10 12:58:06 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Thu, 10 Jul 2008 18:58:06 +0200 Subject: plugins using cvs/distutils? References: Message-ID: Deacon : > Hi. I have an open-source application development environment that I > would like to enable an automated package download system for (like > downloadable plugins), using sourceforge as its repository. My > software will have a menu-based popup window, that will list the > packages (Applications) available through the project distribution > page. If a user selects a package from this window, it should be > automatically retrieved and installed by the development environment. > My software already has a system for automatically recognizing and > deploying new packages, so I'm only asking for help with distribution > logistics, I think. > > I'm thinking that I will use the built-in ftplib to list and retrieve > the files (but I'm not sure yet where to look), and then the distutils > should probably be used in a standardized manner to actually install > the packages, right? I've established a CVS, but I'm not aware of any > built-in-python tools for managing the CVS, and I would rather not add > any new user-has-to-download-dependencies for this. Is there an easier > or alternative advisable approach? I have a linux box, should I be > using it to build all of the platform versions? Any advice would be > much appreciated, this is my first distribution project > (sourceforge.net/projects/spade). I'd use setuptools entrypoints. This takes the task of plugin discovery from you, as this is done by setuptools, and allows you to utilize pypi/easy_install for plugin distribution. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From guillermo.listas at googlemail.com Mon Jul 28 09:39:04 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Mon, 28 Jul 2008 06:39:04 -0700 (PDT) Subject: Getting python 2.4 dll Message-ID: Hi there, Is it possible to get a 2.4 dll of python for Windows easily? I need it to use python as scripting language for Vim. Regards, Guillermo From mrkafk at gmail.com Wed Jul 9 10:56:02 2008 From: mrkafk at gmail.com (mk) Date: Wed, 09 Jul 2008 16:56:02 +0200 Subject: (silly?) speed comparisons In-Reply-To: <200807091447.34094.maric@aristote.info> References: <84bdef3c0807081516g7872d1d8x2ecb448fd1fa900c@mail.gmail.com> <200807091447.34094.maric@aristote.info> Message-ID: P.S. Java 1.6 rocks - I wrote equivalent version using ArrayList and it executed in 0.7s. From subhabrata.iisc at hotmail.com Fri Jul 18 06:06:35 2008 From: subhabrata.iisc at hotmail.com (SUBHABRATA) Date: Fri, 18 Jul 2008 03:06:35 -0700 (PDT) Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> Message-ID: Thanx Peter, I would change my variables next time I would post. And obviously, thanx for your solution. I am reviewing it, I was also trying out some solutions. Best Regards, Subhabrata. Peter Otten wrote: > SUBHABRATA wrote: > > > I am trying the following code line: > > def try2(n): > user_line = raw_input("PRINT A STRING:") > user_words = user_line.split() > my_line = "God Godess Heaven Sky" > for word in user_words: > pos = my_line.find(word) > if pos >- 1: > first_char = my_line[pos] > print first_char > elif pos < 0: > missing_word = word > print "It is not found" > print missing_word > else: > print "Error" > s = first_char + " " + missing_word > print s > > try2(1) > > Do you recognise your code? With that jumpstart you should find the error in > no time ;) > > > Here, if I put a string like: > > Petrol Helium Heaven Sky > > In s it is giving me S Helium > > But I am looking for an output of a5 and a6 concatenating all its > > values not the last ones. Can you suggest me any help? Am I missing > > any minor point? > > Yes, use meaningful variables. They won't make your code magically correct > but will make it a lot easier to pinpoint mistakes and false assumptions -- > for you and others. > > Peter From JordanNealBerg at gmail.com Thu Jul 10 00:34:55 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Wed, 9 Jul 2008 21:34:55 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: Message-ID: <5b9065a5-a98d-4a97-8f07-e3a0c12b80a8@i76g2000hsf.googlegroups.com> I was actually just going through an example to show what was happening each step of the way and noticed the overflow!!! bah, stupid tricks tricks tricks!!! The problem is def the overflow, I notice that I start to get negative numbers in the C version, which makes me think that the & 0xffffffff trick won't work (because it will never evaluate to negative in python, right?) Seeing that the problem is the overflow and the bitwise operations returning a negative, does anyone have any suggestions...I will look more into C bitwise tricks in the meantime haha. And in terms of what this is doing in a poker hand evaluator: http://www.suffecool.net/poker/evaluator.html (an evaluator using some nice tricks to evaluate for flushes, straights, and highcard with LU tables then binary search for the rest) then http://senzee.blogspot.com/2006/06/some-perfect-hash.html (does the same thing, but uses perfect hashing instead of a binary search) the function I am having issues with comes up in the hashing algorithm :) From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 11:04:50 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 17:04:50 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <87zlo747gv.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> Message-ID: <4888b609$0$27463$426a74cc@news.free.fr> Torsten Bronger a ?crit : > Hall?chen! > > Bruno Desthuilliers writes: > >> Torsten Bronger a ?crit : >> >>> Bruno Desthuilliers writes: >>> >>>> [...] >>>> >>>> How would you handle this case with an implicit 'self' : >>>> >>>> class Foo(object): >>>> pass >>>> >>>> def bar(self): >>>> print self >>>> >>>> Foo.bar = bar >>> Just like this. However, the compiler could add "self" to >>> non-decorated methods which are defined within "class". >> What's defined within classes are plain functions. It's actually >> the lookup mechanism that wraps them into methods (and manage to >> insert the current instance as first argument). > > And why does this make the implicit insertion of "self" difficult? Did I say such a thing ? Call me pedantic if you want, but I find it easier to understand how something works when using the appropriate terms, that's all. > I could easily write a preprocessor which does it after all. A source-code-preprocessor based solution wouldn't do IMHO. But that was not the point. The point is that a working solution would require to handle "functions-or-else" defined within a class statement as a special case, which obviously makes thing more compl[ex|icated]. Now as far as I'm concerned, as long as such a solution 1/ doesn't impose any restriction wrt/ current features of Python's object model and 2/ doesn't make any of the currently used "metaprogramming" idioms more difficult, I just wouldn't care. From mrkafk at gmail.com Thu Jul 17 11:05:57 2008 From: mrkafk at gmail.com (mk) Date: Thu, 17 Jul 2008 17:05:57 +0200 Subject: storing references instead of copies in a dictionary In-Reply-To: References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: > def f2(arg): > return "f2 "+arg > > def f1(arg): > return "f1 "+arg > > a={"1":"f1","2":"f2"} > print [eval(x[1])(x[0]) for x in a.items()] > def f2(arg): > return "New f2 "+arg > print [eval(x[1])(x[0]) for x in a.items()] Neat trick, if probably dangerous in some circumstances. Anyway, thanks, I didn't think of that. > Don't know if this is any use to you.. At least I learned something. :-) From jwkenne at attglobal.net Tue Jul 22 15:54:05 2008 From: jwkenne at attglobal.net (John W Kennedy) Date: Tue, 22 Jul 2008 15:54:05 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: <48863add$0$5013$607ed4bc@cv.net> Martin Gregorie wrote: > I used Algol 60 on an Elliott 503 and the ICL 1900 series back when it was > a current language. The term "thunking" did not appear in either compiler > manual nor in any Algol 60 language definition I've seen. It doesn't have to; Algol 60 thunks are not part of the language. However, practical implementation of Algol 60 call by name means that thunks are created by every Algol 60 compiler, and the word "thunk" was coined in 1961 to designate them. > A60 could pass > values by name or value and procedures by name. That was it. Call by name > is what is now referred to as reference passing. Either you misunderstood (because in many simple cases the semantics of call-by-reference and call-by-name cannot be distinguished) or the compiler you used implemented non-standard Algol (which was fairly common in compilers meant for day-to-day practical work). Algol call-by-name was a unique form that subsequent language designers have recoiled from in horror. (Historically, "call-by-name" has sometimes been used in non-Algol contexts to mean "call-by-reference".) > Algol 60 did not have 'functions'. It had procedures which could be > declared to return values or not. A procedure that returned a value was > equivalent to a function but the term 'function' was not used. This is simply wrong. You are accurately describing the language syntax, which used (as PL/I does) the keyword "procedure" for both functions and subroutines, but Algol documentation nevertheless referred to "functions". > Similarly > it did not have a mechanism for declaring anonymous procedures. That, like > the incorporation of machine code inserts, would have been a > compiler-specific extension, so it is a terminological mistake to refer to > it without specifying the implementing compiler. Standards-conforming Algol compilers had a limited ability to create de-facto anonymous functions in the call-by-name implementation. -- John W. Kennedy "Information is light. Information, in itself, about anything, is light." -- Tom Stoppard. "Night and Day" From mail at timgolden.me.uk Tue Jul 29 04:33:39 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 29 Jul 2008 09:33:39 +0100 Subject: Questions on 64 bit versions of Python (Thank-you!) In-Reply-To: <1217307763.13376.1265835765@webmail.messagingengine.com> References: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> <488cbeeb$0$17104$9b622d9e@news.freenet.de> <1217307763.13376.1265835765@webmail.messagingengine.com> Message-ID: <488ED5E3.9090607@timgolden.me.uk> python at bdurham.com wrote: > Thanks for everyone's feedback - excellent detail - all my questions > have been answered. > > BTW: Roel was correct that I got confused over the AMD and Intel naming > conventions regarding the 64 bit versions of Python for Windows. (I > missed that nuance that the Intel build refered to the Itanium vs. the > standard off-the-rack 64 bit version of Intel's 586/686 CPU) Frankly, I'm very glad you did get confused: I've learnt more about the various 64-bit architectures in this thread than I ever thought I'd need to know :) TJG From josiah.carlson at gmail.com Thu Jul 10 14:30:11 2008 From: josiah.carlson at gmail.com (Josiah Carlson) Date: Thu, 10 Jul 2008 11:30:11 -0700 (PDT) Subject: Doubts about how implementing asynchronous timeouts through a heap References: <80430d47-aac5-4123-8835-0591faf0baed@34g2000hsf.googlegroups.com> Message-ID: <156ca6dc-2120-4107-9cc5-a05088ae1c63@27g2000hsf.googlegroups.com> On Jul 9, 4:13?am, "Giampaolo Rodola'" wrote: > Hi, > I'm trying to implement an asynchronous scheduler for asyncore to call > functions at a later time without blocking the main loop. > The logic behind it consists in: > > - adding the scheduled functions into a heapified list > - calling a "scheduler" function at every loop which checks the > scheduled functions due to expire soonest > > Note that, by using a heap, the first element of the list is always > supposed to be the one with the lower timeout. > Here's the code I wrote: > > <--- snippet ---> > import heapq > import time > import sys > > delayed_map = [] > > class delayed_call: > ? ? """Calls a function at a later time. > > ? ? The instance returned is an object that can be used to cancel the > ? ? scheduled call, by calling its cancel() method. > ? ? It also may be rescheduled by calling delay() or reset()} methods. > ? ? """ > > ? ? def __init__(self, delay, target, *args, **kwargs): > ? ? ? ? """ > ? ? ? ? - delay: the number of seconds to wait > ? ? ? ? - target: the callable object to call later > ? ? ? ? - args: the arguments to call it with > ? ? ? ? - kwargs: the keyword arguments to call it with > ? ? ? ? """ > ? ? ? ? assert callable(target), "%s is not callable" %target > ? ? ? ? assert sys.maxint >= delay >= 0, "%s is not greater than or > equal " \ > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"to 0 seconds" % (delay) > ? ? ? ? self.__delay = delay > ? ? ? ? self.__target = target > ? ? ? ? self.__args = args > ? ? ? ? self.__kwargs = kwargs > ? ? ? ? # seconds from the epoch at which to call the function > ? ? ? ? self.timeout = time.time() + self.__delay > ? ? ? ? self.cancelled = False > ? ? ? ? heapq.heappush(delayed_map, self) > > ? ? def __le__(self, other): > ? ? ? ? return self.timeout <= other.timeout > > ? ? def active(self): > ? ? ? ? """Return True if this scheduler has not been cancelled.""" > ? ? ? ? return not self.cancelled > > ? ? def call(self): > ? ? ? ? """Call this scheduled function.""" > ? ? ? ? self.__target(*self.__args, **self.__kwargs) > > ? ? def reset(self): > ? ? ? ? """Reschedule this call resetting the current countdown.""" > ? ? ? ? assert not self.cancelled, "Already cancelled" > ? ? ? ? self.timeout = time.time() + self.__delay > ? ? ? ? if delayed_map[0] is self: > ? ? ? ? ? ? heapq.heapify(delayed_map) > > ? ? def delay(self, seconds): > ? ? ? ? """Reschedule this call for a later time.""" > ? ? ? ? assert not self.cancelled, "Already cancelled." > ? ? ? ? assert sys.maxint >= seconds >= 0, "%s is not greater than or > equal " \ > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"to 0 seconds" %(seconds) > ? ? ? ? self.__delay = seconds > ? ? ? ? self.reset() > > ? ? def cancel(self): > ? ? ? ? """Unschedule this call.""" > ? ? ? ? assert not self.cancelled, "Already cancelled" > ? ? ? ? del self.__target, self.__args, self.__kwargs > ? ? ? ? if self in delayed_map: > ? ? ? ? ? ? if delayed_map[0] is self: > ? ? ? ? ? ? ? ? delayed_map.remove(self) > ? ? ? ? ? ? ? ? heapq.heapify(delayed_map) > ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? delayed_map.remove(self) > ? ? ? ? self.cancelled = True > > def fun(arg): > ? ? print arg > > a = delayed_call(0.6, fun, '0.6') > b = delayed_call(0.5, fun, '0.5') > c = delayed_call(0.4, fun, '0.4') > d = delayed_call(0.3, fun, '0.3') > e = delayed_call(0.2, fun, '0.2') > f = delayed_call(0.1, fun, '0.1') > > while delayed_map: > ? ? now = time.time() > ? ? while delayed_map and now >= delayed_map[0].timeout: > ? ? ? ? delayed = heapq.heappop(delayed_map) > ? ? ? ? try: > ? ? ? ? ? ? delayed.call() > ? ? ? ? finally: > ? ? ? ? ? ? if not delayed.cancelled: > ? ? ? ? ? ? ? ? delayed.cancel() > ? ? time.sleep(0.01) > > > Here comes the questions. > Since that the timeouts of the scheduled functions contained in the > list can change when I reset() or cancel() them I don't know exactly > *when* the list needs to be heapified(). > By doing some tests I came to the conclusion that I need the heapify() > the list only when the function I reset() or cancel() is the *first of > the list* but I'm not absolutely sure about it. > When do you think it would be necessary calling heapify()? > I wrote a short test suite which tests the code above and I didn't > notice strange behaviors but since that I don't know much about the > logic behind heaps I'd need some help. > Thanks a lot in advance. > > --- Giampaolohttp://code.google.com/p/pyftpdlib/ According to a quick scan, there is some inefficiencies with your code. In particular, you don't need to re-heapify if the item you need to remove is the first item; you only need to heappop(). In any case, if the Python standard library heapq module supported non- lists as containers, then the pair heap implementation I wrote a couple years ago would be perfect for this particular task. Because of the rewriting of heapq in C, without a bit of monkeypatching, we can't re-use that implementation (which offered insert/remove of arbitrary entries in the heap in O(logn) time, which is significantly faster than the O(n) time of your implementation). What I'm thinking is that we should add a pair heap implementation to the heapq module (which can cache the pure Python functions if it needs to use them), which would then allow us to use that (and others to use it generally), add scheduling, etc. Regardless, it's a 2.7/3.1 feature, so it's ok if we take it slow. - Josiah From animator333 at gmail.com Thu Jul 24 04:50:06 2008 From: animator333 at gmail.com (King) Date: Thu, 24 Jul 2008 01:50:06 -0700 (PDT) Subject: instance comparison Message-ID: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> I am facing a problem where I am really confused about it. I am trying to compare to instances using: if inst1 == inst2 These instances have a overridden method __str__ which returns same string. The condition result is true although they are different instances. If I use: if id(inst1) == id(inst2) The results is false. What's happening here? If I am trying to store this pair in a set where other instances are already stored, but it's not storing it. Although I am sure that there is no pair already stored of same but even if Set is comparing by using string return by __str__ method then it won't. How do I solve this? Is this mean when you have overridden __str__ method then it comapre with results of __str__ or else it will comapre whether they are the same instances? From bignose+hates-spam at benfinney.id.au Mon Jul 7 21:13:59 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 08 Jul 2008 11:13:59 +1000 Subject: Python Agile Software Development Tools Screencasts References: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> <87lk0dwbys.fsf@benfinney.id.au> <87hcb1w6gl.fsf@benfinney.id.au> Message-ID: <87abgtw52g.fsf@benfinney.id.au> Robert Kern writes: > Ben Finney wrote: > > Okay. Where would the public link to those files be? > > > > If I need to "log in" just to download it, that's a needless barrier > > that's going to turn me away too. > > Yes, you do need to log in. Thanks. > If you don't want to do it, that's fine. I certainly don't care. No problem. I hope the OP, who wanted people to see his videos, does care enough to put them somewhere people can get them without needless barriers. -- \ ?Money is always to be found when men are to be sent to the | `\ frontiers to be destroyed: when the object is to preserve them, | _o__) it is no longer so.? ?Voltaire, _Dictionnaire Philosophique_ | Ben Finney From fredrik at pythonware.com Sat Jul 26 07:03:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Jul 2008 13:03:15 +0200 Subject: xml.dom's weirdness? In-Reply-To: References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> Message-ID: Lie wrote: > If you have any idea what black magic is happening in my computer > right now, I'd appreciate it. command completion? (no ubuntu within reach right now, so I cannot check how they've set it up). try starting python with the "-v" option, so you can see exactly when the import occurs. From deets at nospam.web.de Thu Jul 31 10:39:40 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 16:39:40 +0200 Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> <6fe0scFaus40U1@mid.uni-berlin.de> Message-ID: <6fe17mFaus40U2@mid.uni-berlin.de> Diez B. Roggisch wrote: > squishywaffle at gmail.com wrote: > >>> Ctypes is a since python2.5 built-in module that allows to declare >>> interfaces to C-libraries in pure python. You declare datatypes and >>> function prototypes, load a DLL/SO and then happily work with it. No C, >>> no compiler, no refcounts, no nothing. >>> >>> And you can pass python-functions as callbacks. >> >> The first sentence (and some really crummy licensing restrictions >> imposed by the library distributor) alone here excludes this as a >> valid option for this particular case, I definitely need Python 2.4 >> support. > > How much more liberal can it get than MIT-licensed? > > """ > to deal in the Software without restriction, including > without limitation the rights to use, copy, modify, merge, publish, > distribute, sublicense, and/or sell copies of the Software, and to > permit persons to whom the Software is furnished to do so, subject to > the following conditions: > """ Sorry, missed the paragraph """ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. """ Still, AFAIK MIT is pretty liberal. Diez From sorsorday at gmail.com Sun Jul 27 20:35:08 2008 From: sorsorday at gmail.com (Herman) Date: Sun, 27 Jul 2008 17:35:08 -0700 Subject: Where is the correct round() method? Use math.ceil Message-ID: <98aab64d0807271735w111f6ec7w81c9e65f99744199@mail.gmail.com> > > Where is the correct round() method? > Hello, > > I need a round function that _always_ rounds to the higher integer if > the argument is equidistant between two integers. In Python 3.0, this > is not the advertised behavior of the built-in function round() as > seen below: > > >>> round(0.5) > 0 > >>> round(1.5) > 2 > >>> round(2.5) > 2 > > > I would think this is a common need, but I cannot find a function in > the Python library to do it. I wrote my own, but did I miss such a > method in my search of the Python library? > > Thanks Use ceil in the math module: import math math.ceil(number) -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcus at internetnowasp.net Sun Jul 13 22:57:10 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Mon, 14 Jul 2008 10:57:10 +0800 Subject: Malaysia python user group Message-ID: <487AC086.3010600@internetnowasp.net> Hi, I am thinking of promoting Python for the local developers here in Malaysia, via Universities , seminars etc . Is there already a user group here in Malaysia? Any pointers would help. Marcus. From ppearson at nowhere.invalid Tue Jul 8 00:01:05 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 8 Jul 2008 04:01:05 GMT Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> <6ddj74F21uhjU1@mid.individual.net> <4cv8k5-dsg.ln1@rama.nodalpoint> Message-ID: <6dg740F2b1mkU1@mid.individual.net> On Mon, 07 Jul 2008 10:05:56 +0200, TP wrote: > TP wrote: > >> So, the python print command *can* interpret these 4-character as a single >> character. It would be odd if there were no possibility to do the same >> thing when the characters are (i) stored in a python variable > > Sorry, it works when using variables. Try for example: > > col="[0;31m" > esc="\033" > colreset="[0m" > print esc + col + "foobar" + esc + colreset I don't understand exactly what you mean by "Sorry", but let me direct your attention to the fact that the "interpretation" step about which we're talking happens during the parsing of the string literal (i.e., while the statement esc="\033" is processed), not during the execution of the print statement. To prove this assertion, simply print len(esc). You will see that esc is a single character long. -- To email me, substitute nowhere->spamcop, invalid->net. From mdboldin at gmail.com Wed Jul 30 15:14:31 2008 From: mdboldin at gmail.com (mmm) Date: Wed, 30 Jul 2008 12:14:31 -0700 (PDT) Subject: undo a dictionary References: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> Message-ID: <192b4786-85b2-43d3-bb7c-b5716068ff12@56g2000hsm.googlegroups.com> > > And for that matter a way to create a > > dictionary from a set of variables (local or global). > > You have to be more specific: there are {} displays and dict(args) call > and other methods. ?Read the manual. My desire is to take a set of data items in an alpha-numeric range and oput them into a dictionary i.e., x1=1 x2=20 x3=33 to yield the dictionary { 'x1':1, 'x2':20, 'x3':33 } without having to type in as above but instead invoke a function maybe with syntax of dd=make_dict('x1--x99') From kylotan at gmail.com Fri Jul 18 06:23:39 2008 From: kylotan at gmail.com (Ben Sizer) Date: Fri, 18 Jul 2008 03:23:39 -0700 (PDT) Subject: Best Python packages? References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> Message-ID: <17861f55-8ad1-4703-ad22-838675f2afc4@w1g2000prk.googlegroups.com> On Jul 16, 3:31?pm, Fredrik Lundh wrote: > Ben Sizer wrote: > > make my development a lot easier. > > Knowing what kind of development you do might help, of course. ?Some > libraries are excellent in some contexts and suck badly in others... Sure. Mostly I'm just interested in what's out there though. In C++ you have Boost which everybody knows are a source of high quality libraries, covering a fairly wide set of applications. Obviously that's more low-level and less application specific, and the Python standard libs do pretty much everything that is in Boost, but it's that sort of peer-reviewed and widely-applicable list that I'd like to see. I (attempt to) use TurboGears for web development and that depends on a whole bunch of libraries - SQLObject, PyProtocols, RuleDispatch, SimpleJson, FormEncode, etc - and I would never have heard of these if TurboGears' exposure of its internals wasn't so common. Some of these are web-specific but some are not. And I'd never know to look for them specificially, because in many cases it wouldn't occur to me that they exist. (eg. Object-Relational Mappers like SQLObject may be obvious if you come from certain areas of IT, but I'd never heard of them before I started with TurboGears.) For what it's worth, my main areas of interest are gaming, multimedia, and web development. But I just like to hear about anything that people might use which makes their life a lot easier and which perhaps is not application specific - like ORMs or something similar. > Looking at things that larger projects and distributions use can also be > a good idea. ?For example, if you're doing scientific stuff, go directly > to enthought.com. ?If you're doing web stuff, look at the libraries big > Django applications use. ?Etc. Sadly, I know just as little about what major applications are out there as I do about what libraries are out there! -- Ben Sizer From aljosa.mohorovic at gmail.com Thu Jul 31 11:42:46 2008 From: aljosa.mohorovic at gmail.com (Aljosa Mohorovic) Date: Thu, 31 Jul 2008 08:42:46 -0700 (PDT) Subject: current week / weeks in year - best practice References: <6fdur9Fb0nvuU1@mid.uni-berlin.de> Message-ID: <2ac30ca6-554a-4b40-bdb8-a61f2311ab24@l42g2000hsc.googlegroups.com> On Jul 31, 3:58 pm, "Diez B. Roggisch" wrote: > Instead of datetime.now() use date.today(), which removes a lot of > boilerplate. > > int(date.today().strftime("%W")) > > Apart from that, I think it's the way to go. what if i know current context week = 20 (example), what would be the best way to get datetime objects for first and last day of current context week? by "current context week" i don't mean current week for current year but current week when program is iterating all weeks in year. Aljosa From atulskulkarni at gmail.com Thu Jul 24 11:34:40 2008 From: atulskulkarni at gmail.com (Atul.) Date: Thu, 24 Jul 2008 08:34:40 -0700 (PDT) Subject: Encoding for Devanagari Script. Message-ID: Hello All, I wanted to know what encoding should I use to open the files with Devanagari characters. I was thinking of UTF-8 but was not sure, any leads on this? Anyone used it earlier? Thanks in Advance. Regards, Atul. From fredrik at pythonware.com Tue Jul 22 15:08:32 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 21:08:32 +0200 Subject: software engineering foundations? In-Reply-To: <18566.11394.326317.821553@montanaro-dyndns-org.local> References: <18566.11394.326317.821553@montanaro-dyndns-org.local> Message-ID: skip at pobox.com wrote: > Sorry for the off-topic-ish post. My son (a fairly junior sysadmin type) > mentioned to me today that he was looking for online courses for Perl. (I > don't hold that against him. Perl is still a lingua franca in the sysadmin > realm.) In my work I have from time-to-time had to pick up and maintain > scripts (generally shell/Python stuff) which non-professional programmers > have written. It's never what you would call a "pleasant" task. > > There are software construction skills which are entirely distinct from the > language in which you are programming. We can tout object-oriented, > structured programming, test-driven development or other software > engineering techniques, but there is a body of knowledge out there which is > orthogonal to the language in which the code is written. People who are not > professional programmers often lack those skills and their code shows it. just get McDonnell's "Code Complete": http://www.cc2e.com/ From nclbndk759 at googlemail.com Fri Jul 18 10:40:02 2008 From: nclbndk759 at googlemail.com (nclbndk759 at googlemail.com) Date: Fri, 18 Jul 2008 07:40:02 -0700 (PDT) Subject: Regular expression help References: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> Message-ID: <8a5492e9-15a6-458e-90b1-c25b5bf4a318@i20g2000prf.googlegroups.com> On Jul 18, 3:35?pm, Nick Dumas wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > I think you're over-complicating this. I'm assuming that you're going to > do a line graph of some sorta, and each new line of the file contains a > new set of data. > > The problem you mentioned with your regex returning a match object > rather than a string is because you're simply using a re function that > doesn't return strings. re.findall() is what you want. That being said, > here is working code to mine data from your file. > > [code] > line = 'c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 > mad=-3.597647 3pv=0' > > energypat = r'\betot=(-?\d*?[.]\d*)' > > #Note: To change the data grabbed from the line, you can change the > #'etot' to 'afrac' or 'emad' or anything that doesn't contain a regex > #special character. > > energypat = re.compile(energypat) > > re.findall(energypat, line)# returns a STRING containing '-12.020107' > > [/code] > > This returns a string, which is easy enough to convert to an int. After > that, you can datapoints.append() to your heart's content. Good luck > with your work. > > > > nclbndk... at googlemail.com wrote: > > Hello, > > > I am new to Python, with a background in scientific computing. I'm > > trying to write a script that will take a file with lines like > > > c afrac=.7 mmom=0 sev=-9.56646 erep=0 etot=-11.020107 emad=-3.597647 > > 3pv=0 > > > extract the values of afrac and etot and plot them. I'm really > > struggling with getting the values of efrac and etot. So far I have > > come up with (small snippet of script just to get the energy, etot): > > > def get_data_points(filename): > > ? ? file = open(filename,'r') > > ? ? data_points = [] > > ? ? while 1: > > ? ? ? ? line = file.readline() > > ? ? ? ? if not line: break > > ? ? ? ? energy = get_total_energy(line) > > ? ? ? ? data_points.append(energy) > > ? ? return data_points > > > def get_total_energy(line): > > ? ? rawstr = r"""(?P.*?)=(?P.*?)\s""" > > ? ? p = re.compile(rawstr) > > ? ? return p.match(line,5) > > > What is being stored in energy is '<_sre.SRE_Match object at > > 0x2a955e4ed0>', not '-11.020107'. Why? I've been struggling with > > regular expressions for two days now, with no luck. Could someone > > please put me out of my misery and give me a clue as to what's going > > on? Apologies if it's blindingly obvious or if this question has been > > asked and answered before. > > > Thanks, > > > Nicole > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (MingW32) > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org > > iEYEARECAAYFAkiAqiAACgkQLMI5fndAv9h7HgCfU6a7v1nE5iLYcUPbXhC6sfU7 > mpkAn1Q/DyOI4Zo7QJhF9zqfqCq6boXv > =L2VZ > -----END PGP SIGNATURE----- Thanks guys :-) From lxz3002 at yahoo.com.cn Wed Jul 16 22:10:16 2008 From: lxz3002 at yahoo.com.cn (Leo Lee) Date: Thu, 17 Jul 2008 10:10:16 +0800 Subject: wxPython: How can I get window's HANDLE in wxPython. References: Message-ID: Thank you , Mike. "Mike Driscoll" ??????:ad849714-c6a9-4308-a997-d6d1d43a915b at t54g2000hsg.googlegroups.com... On Jul 2, 8:40 pm, "Leo Lee" wrote: > I need a window's handle to be passed to external c++. > Thanks in advance Are you talking about a wxPython wx.Window object or an external window handle? If the latter, then I recommend asking about that on the PyWin32 user's group. Otherwise, follow Paul's suggestion. Mike From victorsubervi at gmail.com Tue Jul 15 08:41:03 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 15 Jul 2008 14:41:03 +0200 Subject: Type Problem Message-ID: <4dc0cfea0807150541p43e3c3eco749f02dc712d9ff0@mail.gmail.com> Hi; Forgive multiple posts in one day: online very infrequently Why am I getting this error? import os dir_dict = {6:36, 5:26, 4:22, 3:18, 2:14, 1:12} cur_dir = os.getcwd() dirs = os.path.split(cur_dir) len = len(dirs) type(len(dirs)) Traceback (most recent call last): File "", line 1, in type(len(dirs)) TypeError: 'int' object is not callable Forgot to bring it with me, but type(len) gives me an intelligent response. TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From eliben at gmail.com Thu Jul 10 13:40:35 2008 From: eliben at gmail.com (eliben) Date: Thu, 10 Jul 2008 10:40:35 -0700 (PDT) Subject: using Python's AST generator for other languages Message-ID: Hello, I'm building a parser in Python, and while pondering on the design of my ASTs had the idea to see what Python uses. I quickly got to the compiler.ast module, and understood it's automatically generated. So I went to the source, ast.txt and tools/compiler/astgen.py, where I was this unexpected message: """Generate ast module from specification This script generates the ast module from a simple specification, which makes it easy to accomodate changes in the grammar. This approach would be quite reasonable if the grammar changed often. Instead, it is rather complex to generate the appropriate code. And the Node interface has changed more often than the grammar. """ Now, to me the design of the AST in Python looks quite elegant, especially from the point of view of the AST's user (using Visitors to walk the AST). And astgen.py looks like a nice approach to generate tons of boilerplate code. So, my questions: 1) Is the compiler.ast module really employed during the compilation of Python into .pyc files ? 2) What is the meaning of the comment in astgen.py ? Are the Python maintainers unhappy with the design of the AST ? 3) What other approach would be recommended to generate a very detailed AST hierarchy, if the one in astgen.py is dissapointing ? Thanks in advance Eli From cwitts at gmail.com Thu Jul 31 02:59:50 2008 From: cwitts at gmail.com (Chris) Date: Wed, 30 Jul 2008 23:59:50 -0700 (PDT) Subject: how to split text into lines? References: Message-ID: <7ed81072-aaf1-4e06-98b5-e6fa94268cbd@r66g2000hsg.googlegroups.com> On Jul 31, 7:26?am, alex23 wrote: > kj wrote: > > Sorry, I should have googled this first. ?I just found splitlines()... > > > Still, for my own edification, is there a way to achieve the same > > effect using re.split? > > re.split(os.linesep, ) works the same as .splitlines() > > Neither retain the EOL for each line, though. The only way I'm aware > of is to re-add it: > > [s+os.linesep for s in re.split(os.linesep, )] > > Was that what you were after? or what about 'string'.splitlines(True) as that retains newline characters. ;) From otr2 at tuningchannel.de Mon Jul 21 07:56:26 2008 From: otr2 at tuningchannel.de (otr2 at tuningchannel.de) Date: Mon, 21 Jul 2008 04:56:26 -0700 (PDT) Subject: Python Embedding Thread Message-ID: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> Hi :) I want to run Python in my app. That works still fine. But my app supports now Threads and I would like to know what to do, that it runs without problems. PyGILState_Release and PyGILState_Ensure should solve the problem right? Where do I have to put this two commands around? between each Command that increase, decrease a reference? Currently, this is a small code-snippet that represents the part of the code-execution: PyObject *f_globals=NULL, *f_locals=NULL, *mod=NULL, *rv=NULL; mod = PyImport_ImportModule("__main__"); if (!mod) return; f_globals = PyModule_GetDict(mod); f_locals = PyDict_New(); PyDict_Update(f_locals, f_globals); if (!f_locals) { Py_DECREF(mod); PyErr_Print(); return; } rv = PyRun_String( , Py_file_input, f_locals, f_locals); if (!rv) PyErr_Print(); Py_XDECREF(rv); Py_DECREF(mod); Py_DECREF(f_locals); Py_DECREF(f_locals); Thanks a lot for your help :) From timaranz at gmail.com Thu Jul 10 00:32:38 2008 From: timaranz at gmail.com (Tim Mitchell) Date: Thu, 10 Jul 2008 16:32:38 +1200 Subject: python scalability Message-ID: <487590E6.7020004@gmail.com> Hi All, I work on a desktop application that has been developed using python and GTK (see www.leapfrog3d.com). We have around 150k lines of python code (and 200k+ lines of C). We also have a new project manager with a C# background who has deep concerns about the scalability of python as our code base continues to grow and we are looking at introducing more products. I am looking for examples of other people like us (who write desktop apps in python) with code bases of a similar size who I can point to (and even better talk to) to help convince him that python is scalable to 300+ lines of code and beyond. I have looked at the python success stories page and haven't come up with anyone quite like us. One of my project managers questions is: "Are we the only company in the world with this kind and size of project?" I want to say no, but am having trouble convincing myself, let alone him. If you are involved in this kind of thing please get in touch with me. Thanks, Tim From Russ.Paielli at gmail.com Sat Jul 26 15:48:33 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 26 Jul 2008 12:48:33 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> Message-ID: <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> > If, as I wrote, you permit the omission of "self" in method signatures > defined within class definitions, then you could still insist on > instance attribute qualification using "self" - exactly as one would > when writing Java according to certain style guidelines. I'm not sure exactly what people mean here by allowing "self" to be "omitted" in method signatures. If it is omitted, then it seems to me that a place holder would be needed to the interpreter that the first argument is not just another name for "self." In an earlier post on this thread (don't feel like looking it up at the moment), someone suggested that member data could be accessed using simply ".member". I think he might be on to something. The dot is a minimal indicator that the data is a class member rather than just local. However, a placeholder is still needed in the signature. So why not allow something like this?: class MyClass: def func( , xxx, yyy): .xxx = xxx local = .yyy The "self" argument is replaced with nothing, but a comma is used as a placeholder. From segfaulthunter at gmail.com Mon Jul 14 18:53:12 2008 From: segfaulthunter at gmail.com (name) Date: Mon, 14 Jul 2008 15:53:12 -0700 (PDT) Subject: Why is there no GUI-tools like this for Windows? References: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> Message-ID: <6b3ee6bd-c83f-4d24-9ed1-4aeb1a39275b@w7g2000hsa.googlegroups.com> It seems the video is showing glade, which is also available for wx under the name wxglade, I do not know whether it's available for Windows. I think it should work because it itself is written in Python. I personally prefer to code my GUI myself, so I can do looping stuff with it, but that is just me. From thomas.troeger.ext at siemens.com Fri Jul 25 05:00:44 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Fri, 25 Jul 2008 11:00:44 +0200 Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: Lawrence D'Oliveiro wrote: > Specified by whom? The most common setting these days is 4 columns. Where? I've randomly seen code snipplets that indent using spaces or, worse, tabstop != 8, but most code I've come across uses tabstop width 8, which is how it was meant to be from the beginning of time. Unfortunately, for many people it's hard to understand that a tabstop is not the same as indenting with spaces, but I think this is leading too far and will end in a dogmatic discussion like the `ViM vs. Emacs' war. Anyways, if you claim tabstop 4 is most widely used I'd like to see some kind of a reference for that since it contradicts not only my experience. Finally, I'd like to throw in this one from the Linux kernel sources, from `Documentation/CodingStyle: ------------------------------------------------------------------------ Chapter 1: Indentation Tabs are 8 characters, and thus indentations are also 8 characters. There are heretic movements that try to make indentations 4 (or even 2!) characters deep, and that is akin to trying to define the value of PI to be 3. [...] Now, some people will claim that having 8-character indentations makes the code move too far to the right, and makes it hard to read on a 80-character terminal screen. The answer to that is that if you need more than 3 levels of indentation, you're screwed anyway, and should fix your program. In short, 8-char indents make things easier to read, and have the added benefit of warning you when you're nesting your functions too deep. Heed that warning. ------------------------------------------------------------------------ From Tribulations at Paralleles.invalid Sun Jul 6 17:42:26 2008 From: Tribulations at Paralleles.invalid (TP) Date: Sun, 06 Jul 2008 23:42:26 +0200 Subject: interpretation of special characters in Python Message-ID: <3rq7k5-lqf.ln1@rama.nodalpoint> Hi everybody, I am new to Python, I try to understand how Python treats special characters. For example, if I execute the following line in a shell console, I obtain a colored string: $ python -c "print '\033[30;44m foo \033[0m'" So, it works. Some time ago, I have made a lot of shell variables with all possible colors (with shell functions executed each time I launch a new shell). For example: $ echo -e $esc$ColorBlackOnDarkblue foo $esc$ColorReset gives the same result than the python command above. To know the corresponding non-interpreted characters, I can use the -n option of echo: $ echo -n $esc$ColorBlackOnDarkblue foo $esc$ColorReset \033[30;44m foo \033[0m So, it is exactly the string above, as expected. My problem arises when it comes to get these shell variables ( $esc, $ColorBlackOnDarkblue, $ColorReset) in a Python script, with os.environ, in the following 5-line script: import os Color = os.environ['ColorBlackOnDarkblue'] ColorReset = os.environ['ColorReset'] Esc = os.environ['esc'] print '%s%s%s%s%s' % (Esc, Color, " foo ", Esc, ColorReset) Run this script color.py, but after having defined these shell variables in a shell: $ export esc="\033" $ export ColorBlackOnDarkblue="[30;44m" $ export ColorReset="[0m" When I execute the Python script, I do not obtain any special character interpretation in Python: $ python color.py \033[30;44m foo \033[0m Why? What is the problem? Is there any solution? I really want to get my shell color variables. Thanks a lot -- TP (Tribulations Parall?les) "Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert). From stefan_ml at behnel.de Fri Jul 11 01:36:19 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 11 Jul 2008 07:36:19 +0200 Subject: Bypassing WebFilter security In-Reply-To: <563968a1-3cc3-4009-beca-d5d367d4ccff@k13g2000hse.googlegroups.com> References: <563968a1-3cc3-4009-beca-d5d367d4ccff@k13g2000hse.googlegroups.com> Message-ID: <4876F153.2020406@behnel.de> pranav wrote: > I am working in an organization, which is using a very strict > webcontent filter management suite. Due to this i am unable to > download any exe file, or surf web (even the necessary downloads from > sourceforgenet are blocked). I was wondering, if python could be of > any help. Say i have a python script, and i pass the URL of > downloadable file, and it just downloads the file for me. Nice try. Can I talk to your employer for a minute? :) Honestly, the language doesn't make any difference here, and there isn't much you can do unless you control both sides, i.e. the server and the client. But I would suggest you actually talk to your employer yourself to see if there's an official way to get what you want. Stefan From gherron at islandtraining.com Thu Jul 17 12:45:01 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 17 Jul 2008 09:45:01 -0700 Subject: properly delete item during "for item in..." In-Reply-To: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> References: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> Message-ID: <487F770D.8070405@islandtraining.com> Ratko wrote: > Say you have something like this: > > for item in myList: > del item > > Would this actually delete the item from the list or just decrement > the reference counter because the item in myList is not associated > with name "item" anymore (but still is with myList[itemIndex])? In > other words, is "item" a temporary reference to myList[itemIndex] or > is it actually that reference that myList has stored? > The 'del' statement does not delete an object, it deletes a reference to an object. In this case, the variable item is deleted from the scope, and the referred-to object will have its reference counter decremented by 1. (But, as you surmise, not to zero, because the list will still reference it.) You could remove the object from the list with del myList[i] if you knew i. HOWEVER, don't do that while looping through the list! Changing a list's length will interact badly with the for loop's indexing through the list, causing the loop to mis the element following the deleted item. Gary Herron > I am not sure if this question even makes any sense anymore. I've been > using python for years and never had any problems (and I don't now > either) but now that I had to revisit c++/STL, I had to deal about > these issues and was wondering how python does it. > > Thanks, > Ratko > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Sat Jul 12 01:10:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 01:10:52 -0400 Subject: Python 3.0 and removal of the 'string' module In-Reply-To: <87skugotpw.fsf@benfinney.id.au> References: <87wsjtqiyo.fsf@benfinney.id.au> <87iqvdq6qz.fsf@benfinney.id.au> <487706b7$0$9695$9b622d9e@news.freenet.de> <87abgorgiv.fsf@benfinney.id.au> <76f1bf48-b05f-472b-9bfc-cf59dd2a97ca@m45g2000hsb.googlegroups.com> <87skugotpw.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > So, in summary, despite the appearance of the "Python 3.0" page on the > wiki, there's really no single clearing-house source of Python 3.0 > information that is maintained. The interested party needs to know a > half-dozen different resources to find out what's changing, and none > of the resources seems to attempt to be a single point of entry for > the interested party. The problem in this respect, as I hinted before, is that nothing gets added or changed unless someone (or ones) volunteers to write a complete patch (code + tests + doc as appropriate) and, usually, someone (or ones) reviews and applies the patch. And once it is in, it is there for anyone to look at. At this point, the changes Guido most cared about have pretty much been done as far as I know, subject to bug fixes and a few tweaks. Other things that might go in are things he will allow but does not care too much about. The process is looser than I imagine it would be in a compamy where the project manager (or someone) hires people and directs them to work on specific items. From animator333 at gmail.com Thu Jul 24 05:53:15 2008 From: animator333 at gmail.com (King) Date: Thu, 24 Jul 2008 02:53:15 -0700 (PDT) Subject: instance comparison References: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> Message-ID: The only methods I do have in class is __init__ and __str__. How ever inst1 and inst2 is coming from a dictionary where I stored them with a unique id. inst1 = stored[id] inst2 = stored[id] Is this makes a difference? I will rip down the piece of code giving me problem and post. From bearophileHUGS at lycos.com Fri Jul 11 19:10:09 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 11 Jul 2008 16:10:09 -0700 (PDT) Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: Denis Kasak: > spam = ['a', 'n', 'n', 'a'] > eggs = spam[:] > if spam.reverse() == eggs: > print "Palindrome" An alternative version: >>> txt = "anna" >>> txt == txt[::-1] True >>> txt = "annabella" >>> txt == txt[::-1] False Bye, bearophile From tjreedy at udel.edu Sat Jul 26 00:06:05 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 00:06:05 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> Message-ID: Paul Boddie wrote: > On 25 Jul, 22:37, Terry Reedy wrote: >> Kay Schluehr wrote: >>> This isn't the problem Jordan tries to address. It's really just about >>> `self` in the argument signature of f, not about its omission in the >>> body. >> That is not at all how I read him, so I will let him respond if he >> wishes. The main problem moving a function from module scope to class >> scope is prefixing the proper variables. Adding a param name, whether >> 'self', 's', 'this', or whatever, is trivial and hardly worth the ink. > > He wrote the following of relevance: > > "I added some classes to code that had previously just been functions, > and you know what I did - or rather, forgot to do? Put in the 'self'. > In front of some of the variable accesses, but more noticably, at the > start of *every single method argument list.*" > > And rounding off with this on the subject: > > "The problem is that the explicit requirement to have self at the > start > of every method is something that should be shipped off to the > implicit category." There is no requirement to have 'self' in the parameter list. It can be 's', 'this', 'me', 'yo'(Spanish for I), or 'cls' (for class methods), or any other identifier in whatever language. In 3.0, identifiers are not restricted to ascii but can be any unicode 'word' as defined in the manual. So the proposal would have to be that the compiler scan the function body and decide which dotted name prefix is the one to be implicitly added. Have fun writing the discovery algorithm. However, I think this is pretty silly. Just write the name you want. Or the proposal would have to be that 'self' is mandatory for all programmers in all languages. I think *that* would be pernicious. People are now free to write the more compact 's.sum = s.a + s.b + s.c' if they want instead of the 'self' version. And again, not everyone writes in English. tjr From robert.rawlins at thinkbluemedia.co.uk Sun Jul 20 06:33:07 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Sun, 20 Jul 2008 11:33:07 +0100 Subject: __del__ methods In-Reply-To: <87hcalxvx0.fsf@benfinney.id.au> References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> <87hcalxvx0.fsf@benfinney.id.au> Message-ID: <007d01c8ea54$0067e360$0137aa20$@rawlins@thinkbluemedia.co.uk> > In Python 2.x, "classic" classes (which are not part of the unified > type hierarchy) are deprecated, and exist only for backward > compatibility with old code. > > You need to create "new-style" classes > by inheriting from some > class that is part of the unified type hierarchy; if there is no > obvious candidate, 'object' is the recommended choice. Thanks Ben, This isn?t something I'd seen before (god that makes me feel stupid). I've always based my code off the odd example that's dotted around and hadn?t ever done any proper reading on these new type classes. I've done a little reading this morning and really love a great deal of the concepts, I'll be upgrading my app to this spec in the next few days. Robert From bj_666 at gmx.net Tue Jul 1 05:10:06 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Jul 2008 09:10:06 GMT Subject: how to judge urllib.Request is finished? References: Message-ID: <6cuajeF3e7podU1@mid.uni-berlin.de> On Tue, 01 Jul 2008 15:16:03 +0800, oyster wrote: > currently I am using > [code] > req=urllib2.Request(url) > data='' > if '' not in data: > fd=urllib2.urlopen(req) > data=fd.read() > time.sleep(10) > time.sleep(10) > blahblah > [/code] That looks very strange. Why the ``if`` and the `sleep()`\s? The ``if`` condition is always true, so it's completely unnecessary. The `read()` call is blocking, that means it returns iff the complete data is read. So there's no need to wait or to check if all is read. If there's a problem with the connection an exception should be raised by `urllib2`. Ciao, Marc 'BlackJack' Rintsch From waldemar.rymarkiewicz at gmail.com Thu Jul 24 04:02:18 2008 From: waldemar.rymarkiewicz at gmail.com (waldek) Date: Thu, 24 Jul 2008 01:02:18 -0700 (PDT) Subject: python.exe crash and ctypes use References: <6eou4dF82ehaU1@mid.individual.net> Message-ID: <89572ec1-fad8-4b42-a2da-73c62d469ee5@m36g2000hse.googlegroups.com> On Jul 23, 4:39 pm, Thomas Heller wrote: > waldek schrieb: > > > > > Hi, > > > I have module A.py and B.dll which exports C functions by cdecl_ > > > In A.py I pass callback (py callable) to dll. Next, thread inside dll > > simply calls my callback (in a loop). After few secs I got crash of > > python.exe. > > > How to debug it? > > > I'm using winxp and py 2.5.2 > > > =========================== > > def mycallback(data, size) > > return 0 > > > CBFUNC = CFUNCTYPE(c_int,POINTER(c_int), c_int) > > dll = cdll.mydll > > > if dll.RegisterCallback(CBFUNC(mycallback)) != 0: > > print "Error." > > =========================== > > You need the callback function instance - what the CBFUNC(mycallback) > call returns - alive as long as some C code is calling it. > If you don't sooner or later the Python garbage collector will > free it since it seems to be no longer used. ctypes does NOT keep > the callback function alive itself. > > Thomas In fact ctypes does not keep references to callback passed directly to dll. Now it works. Thanks Thomas. Waldek From cjw at ncf.ca Tue Jul 29 18:29:23 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Tue, 29 Jul 2008 18:29:23 -0400 Subject: static variables in Python? In-Reply-To: References: Message-ID: <488F99C3.1000501@ncf.ca> kj wrote: > In Larry Bates writes: > >> kj wrote: >>> Yet another noob question... >>> >>> Is there a way to mimic C's static variables in Python? Or something >>> like it? The idea is to equip a given function with a set of >>> constants that belong only to it, so as not to clutter the global >>> namespace with variables that are not needed elsewhere. >>> >>> For example, in Perl one can define a function foo like this >>> >>> *foo = do { >>> my $x = expensive_call(); >>> sub { >>> return do_stuff_with( $x, @_ ); >>> } >>> }; >>> >>> In this case, foo is defined by assigning to it a closure that has >>> an associated variable, $x, in its scope. >>> >>> Is there an equivalent in Python? >>> >>> Thanks! >>> >>> kynn > > >> First names in Python are just that, names that point to objects. Those objects >> can contain any type of information including other objects. They are NOT >> buckets where things are stored. > >> 1) Names (variables in Perl/C) defined within a Python function are placed in >> its local namespace. They are not visible in the global namespace. > >> 2) Yes you can have a local name point to a global. This is often used in >> classes with attributes because looking up local is somewhat quicker than >> looking up the class attribute. > >> def foo(): >> x = expensive_call >> return do_stuff_with(x()) > > Maybe I'm missing your point, the goal is to have a "runtime > constant" associated with the function. In the your definition of > foo, expensive_call gets called every time that foo gets called; > this is what I'm trying to avoid! > > Maybe it's easier to see what I mean with JavaScript: > > function foo() { > if (foo.x === undefined) foo.x = expensive_call(); > return do_stuff_with(foo.x); > } > > Here, expensive_call is called only once (assuming it never returns > undefined). > > OK, I guess that in Python the only way to do what I want to do is > with objects... > > kynn You might consider using a singleton class. Colin W. From max at alcyone.com Thu Jul 17 15:19:29 2008 From: max at alcyone.com (Erik Max Francis) Date: Thu, 17 Jul 2008 12:19:29 -0700 Subject: x, = y (???) In-Reply-To: References: Message-ID: kj wrote: > I just came across an assignment of the form > > x, = y > > where y is a string (in case it matters). > > 1. What's the meaning of the comma in the LHS of the assignment? > 2. How could I have found this out on my own? > > (Regarding (2) above, I consulted the index of several Python > reference books but I could not find the answer to (1). I hope to > find a better Python reference!) It's unpacking a 1-tuple: (x,) = y The parentheses here are not necessary and are sometimes left out. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The United States, while they wish for war with no nation, will buy peace with none. -- James Madison From ddasilva at umd.edu Wed Jul 30 02:03:04 2008 From: ddasilva at umd.edu (Daniel da Silva) Date: Wed, 30 Jul 2008 02:03:04 -0400 Subject: Overloaded Functions In-Reply-To: <12f9fcac-501b-4eba-8068-24dca22a94b5@m36g2000hse.googlegroups.com> References: <3070b5ff-0914-4109-841a-ee622e4105a5@27g2000hsf.googlegroups.com> <12f9fcac-501b-4eba-8068-24dca22a94b5@m36g2000hse.googlegroups.com> Message-ID: <8d9ec3dd0807292303g5508c554g14439644debc549e@mail.gmail.com> With a little hacking, you might be able to do something like this: @overload("f", (int, int, str)) def f1(x, y, z): pass @overload("f", (str, str)) def f2(x, y): pass The way I would typically do method overloading would be as follows (this has been tested): class Person: def __init__(*args): argTypes = tuple(map(type,args)) methods = { (str,int) : Person.initAllInfo, (str,) : Person.initOnlyName, } methods[argTypes[1:]](*args) # ........................ def initAllInfo(self, name, age): self.name = name self.age = age def initOnlyName(self, name): self.name = name self.age = 100 With this overload-dictionary approach, it may be possible to elegantly implement the overloading decorator I described at the top of this email. I hoped this helped. Daniel On Tue, Jul 29, 2008 at 12:05 PM, Tim Henderson wrote: > Yes i am aware of that but I want the code to be self documenting, so > the intent is clear. I actually have an implementation using that > style which you suggest. I would like cleaner style, like the one i > suggested in my first post. > > Cheers > Tim Henderson > -- > http://mail.python.org/mailman/listinfo/python-list > From dingo_1980 at yahoo.com Tue Jul 1 00:33:11 2008 From: dingo_1980 at yahoo.com (dingo_1980) Date: Mon, 30 Jun 2008 21:33:11 -0700 (PDT) Subject: Are the following supported in scipy.sparse Message-ID: <7f324b8e-e1f9-466e-b6f2-fde8d5f11494@a70g2000hsh.googlegroups.com> I wanted to know if scipy.sparse support or will support the following functions which are available in scipy.linalg or scipy or numpy: Inverse Cholesky SVD multiply power append eig concatenate Thanks... From peter.anderson at internode.on.net Tue Jul 15 09:50:12 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Tue, 15 Jul 2008 23:50:12 +1000 Subject: Python internals Message-ID: <008ca729$0$20313$c3e8da3@news.astraweb.com> Hi! I am slowly teaching myself Python. I was reading David Beazley's excellent book "Python - Essential Reference"; in particular about variables. Let me quote: "Python is a dynamically typed language in which names can represent values of different types during the execution of a program. In fact the names used in the program are really just labels for various quantities and objects. The assignment operator simply creates an association between a name and a value. This is different from C, for example, in which a name (variable) represents a fixed size and location in memory..." As an old mainframe programmer, I understand the way C does things with variable but this text got me wondering how Python handles this "association" between variable name and value at the lower level. Is it like a fifo list? If there is any Python guru that can help I would be most interested in your thoughts. Regards, Peter -- Peter Anderson There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things -- Niccolo Machiavelli, The Prince, ch. 6 From wuwei23 at gmail.com Wed Jul 23 09:19:59 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 23 Jul 2008 06:19:59 -0700 (PDT) Subject: os.walk question References: <79b8d5e1-709f-4a4f-957d-8acbee20018b@c2g2000pra.googlegroups.com> Message-ID: On Jul 23, 10:26?pm, Fredrik Lundh wrote: > ? ? ?random.choice(filter(os.path.isfile, glob.glob("/*"))) > > isn't that bad, though. I'll agree to that. From bgporter at acm.org Wed Jul 30 14:03:16 2008 From: bgporter at acm.org (Brett g Porter) Date: Wed, 30 Jul 2008 14:03:16 -0400 Subject: Reasoning behind 'self' parameter in classes? In-Reply-To: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> Message-ID: <4890ACE4.4060703@acm.org> Robert Dailey wrote: > This is an example of a response I'm looking for: > "The self parameter is required because the parser is a bit old and > needs to know the exact object you're referencing" > > This is _not_ an example of what I'm looking for: > "Specifying self is a great mysterious thing that we should never > question. Do not question the language! The language is mighty! Don't > bring C++ to Python!" > Fredrik Lundh has written a very clear explanation of this at http://effbot.org/pyfaq/why-must-self-be-used-explicitly-in-method-definitions-and-calls.htm (or http://bit.ly/3EUiCf if you don't feel like stitching that URL back together...) From jazle at nospam.log.web.id Tue Jul 22 22:15:44 2008 From: jazle at nospam.log.web.id (Jaimy Azle) Date: Wed, 23 Jul 2008 09:15:44 +0700 Subject: Python Embedding Thread References: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> <87bf413d-eb98-47c0-8466-237c45fd1a0e@e53g2000hsa.googlegroups.com> <5081c3df-cb66-443b-ac71-be9661ae057d@27g2000hsf.googlegroups.com> Message-ID: wrote: > I fixed the code. This code snippet runs in a seperate thread: > > > PyObject *dict=NULL; > PyGILState_STATE state = PyGILState_Ensure(); > dict = CreateMyGlobalDictionary(); > > PyRun_String(, Py_file_input, dict, dict); > > ReleaseGlobalDictionary(dict); > > But it still does not work... :-/ Have you initialize interpreter with PyEval_InitThreads? look at http://www.python.org/doc/1.5.2/api/threads.html for more information. Oh, btw... I did use python in a bit different scenario than you've described. Since you attempt to run different script per-host thread, you might need python multiple interpreter support, I suggest you take a look mod_python implementation. Salam, -Jaimy. From bruno.desthuilliers at gmail.com Fri Jul 18 08:13:17 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 18 Jul 2008 05:13:17 -0700 (PDT) Subject: storing references instead of copies in a dictionary References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: <87150e65-907d-485a-90be-f4ad441415fd@y22g2000prd.googlegroups.com> On 17 juil, 15:56, mk wrote: > Calvin Spealman wrote: > > To your actual problem... Why do you wanna do this anyway? If you want > > to change the function in the dictionary, why don't you simply define > > the functions you'll want to use, and change the one you have bound to > > the key in the dictionary when you want to change it? In other words, > > define them all at once, and then just d['1'] = new_f1. What is wrong > > with that? > > Well, basically nothing except I need to remember I have to do that. > > Suppose one does that frequently in a program. It becomes tedious. I > think I will define some helper function then: > > >>> def helper(fundict, newfun): > ... fundict[newfun.func_name] = newfun > ... > > _If_ there were some shorter and still "proper" way to do it, I'd use > it. You're halfway there. from functools import partial callbacks = {} register_callback = partial(helper, callbacks) @register_callback def f1(arg): print "f1", arg callbacks['f1']('ok') @register_callback def f1(arg): print "new f1", arg callbacks['f1']('ok') From Scott.Daniels at Acm.Org Tue Jul 22 21:36:39 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 22 Jul 2008 18:36:39 -0700 Subject: Python Written in C? In-Reply-To: References: <143349c3-b0e9-49d8-9426-8b030b23d2c9@l42g2000hsc.googlegroups.com> Message-ID: <1uKdnTtUhIQHFRvVnZ2dnUVZ_q_inZ2d@pdx.net> Erik Max Francis wrote: > Ethan Furman wrote: > >> Iain King wrote: >>> The story of a Real Programmer: >>> http://www.pbm.com/~lindahl/mel.html >>> Iain >> >> Wow. Awesome story. > > If my google-fu is up to snuff, these are "screenshots" (scans of > printouts) of the actual blackjack game in operation: > > http://wps.com/projects/LGP-21/Software/LGP30-Blackjack1.jpg > http://wps.com/projects/LGP-21/Software/LGP30-Blackjack2.jpg > > and here's a scan of a printout of some "source code" (machine language): > > http://wps.com/projects/LGP-21/Software/CrapGame.tiff > The high school I went to had an LGP-30, and I learned to program on it. Rumor had it that a student from two years before me used to work late in the lab, and allow the janitors to play blackjack, and it is further rumored that he made a bit of money leaning on the transfer control button. --Scott David Daniels Scott.Daniels at Acm.Org From s0suk3 at gmail.com Wed Jul 23 23:22:31 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Wed, 23 Jul 2008 20:22:31 -0700 (PDT) Subject: Autocompletion and Interactive Tables in a Python IDE References: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Message-ID: <66184e22-13e0-43fe-a6c4-21b1edee7267@i20g2000prf.googlegroups.com> On Jul 23, 4:28 pm, Anthony wrote: > Hi, I'm a FoxPro programmer, but I want to learn python before it's > too late. I do a lot of statistical programming, so I import SPSS > into python. In my opinion, the best features of Visual FoxPro 9.0 > were: > a) Intellisense (tells you what classes/methods are available and what > variables go into a function) > b) Code Completion (guesses your code after four letters) > c) Data-Orientation; multiple data sessions can be open, data can be > viewed easily > > Python's IDLE has only half of the first of these features. I did a > lot of searching and found the PyDev extensions for Eclipse's Python > IDE, and found that they've got Intellisense. I'm still missing b and > c, and am getting extremely frustrated programming so slowly.. > > So two questions: > Is there any package, gui, IDE, anything that will do FoxPro-style > code completion? If it works in Eclipse, even better.. > I can't find a good screenshot, but here's a better description: > You type "BROW" and it pops up a window that says "BROWSE" ..at this > point if you hit enter it completes the word.. > > and > > How can I view open SPSS data in one of the Python GUIs? Again, > Eclipse would be the preference. > Here's an example of how I'd like to browse the data:http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=... > I don't want to have to switch back and forth between Python and SPSS > while I'm programming; I just want to stay in one of them.. > > What can I do? I feel extremely inefficient when I don't have these > three features.. > You're looking at it the wrong way. A programming language's strength is not the availability if IDEs that exist for it. It might be a bit convenient, depending on the circumstances, but it is, by no means, what makes a language a good language, because it's actually not a property of the language itself. And if you're new to any programming language in particular, that's actually the lesser of the things you should be worrying about. However, when you become more experienced and need to be more productive, that might be problem. It's a shame that there aren't as much IDEs for Python as there are for, e.g., Java or C++. I usually use Komodo. Then there's the one you mentioned, Eclipse. You'll probably get more replies mentioning a lot of others, but what I think I should point out is that you seem to be overrating the importance of it. Sebastian From deets at nospam.web.de Mon Jul 21 14:55:12 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 21 Jul 2008 20:55:12 +0200 Subject: scanf in python In-Reply-To: <4884be5e$0$19722$426a74cc@news.free.fr> References: <4884be5e$0$19722$426a74cc@news.free.fr> Message-ID: <6ek4cgF7hq4vU1@mid.uni-berlin.de> AMD schrieb: > Hello, > > I often need to parse strings which contain a mix of characters, > integers and floats, the C-language scanf function is very practical for > this purpose. > I've been looking for such a feature and I have been quite surprised to > find that it has been discussed as far back as 2001 but never > implemented. The recommended approach seems to be to use split and then > atoi or atof or to use regex and then atoi and atof. Both approaches > seem to be a lot less natural and much more cumbersome than scanf. If > python already has a % string operator that behaves like printf, why not > implement either a %% or << string operator to behave like scanf, use > could be like the followng: > > a, b, c = "%d %f %5c" %% "1 2.0 abcde" > > or > > a, b, c = "%d %f %5c" << "1 2.0 abcde" > > %% is closer to the % operator > > << seems more intuitive to me > > either of this methods seems to me much simpler than: > > lst = "1 2;0 abcde".split() > a = int(lst[0]) > b = float(lst[1]) > c = lst[2] > > or even worse when using regular expressions to parse such simple input. > > I like python because it is concise and easy to read and I really think > it could use such an operator. > > I know this has been discussed before and many times, but all previous > threads I found seem to be dead and I would like to invite further > investigation of this topic. I'm pretty certain python won't grow an additional operator for this. Yet you are free to create a scanf-implementation as 3rd-party-module. IMHO the usability of the approach is very limited though. First of all, the need to capture more than one input token is *very* seldom - nearly all commandline-tools I know that do require interactive user-input (like the linux kernel config tool) do so by providing either line-by-line value entry (including defaults, something you can't do with your approach), or even dialog-centric value entry with curses. So - I doubt you will gather much momentum on this. Good luck though. Diez From tjreedy at udel.edu Fri Jul 25 17:05:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 25 Jul 2008 17:05:27 -0400 Subject: Execution speed question In-Reply-To: <4889a36f$1@news2-rz-ap.ethz.ch> References: <4889a36f$1@news2-rz-ap.ethz.ch> Message-ID: Suresh Pillai wrote: > I am performing simulations on networks (graphs). I have a question on > speed of execution (assuming very ample memory for now). I simplify the > details of my simulation below, as the question I ask applies more > generally than my specific case. I would greatly appreciate general > feedback in terms of computing and of course considerations specific to > implementation in Python. > > The nodes in my network may be ON or OFF. The network starts off with > all nodes in the OFF state. I loop through the nodes. For each node > that is OFF, I consider some probability of it turning ON based on the > states of its neighbours. I MUST GO THROUGH ALL NODES BEFORE DECIDING > WHICH ONES TO TURN ON. If the nodes do not have to be processed in any particular order, then you could keep them either in a dict, with the value being either On or Off (True,False)(plus connection data) or a pair of sets, one for On and one for Off. The advantage of the dict is that the items would be fixed and only their values would change, but you needlessly scan through On items. The advantage of the set pair is that you only scan through Off items but have to move some from Off to On. I will not guess which would be faster over a complete run, or how this will compare with using lists. tjr From bignose+hates-spam at benfinney.id.au Fri Jul 11 04:06:48 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 11 Jul 2008 18:06:48 +1000 Subject: Python 3.0 and removal of the 'string' module References: <87wsjtqiyo.fsf@benfinney.id.au> <87iqvdq6qz.fsf@benfinney.id.au> <487706b7$0$9695$9b622d9e@news.freenet.de> Message-ID: <87abgorgiv.fsf@benfinney.id.au> "Martin v. L?wis" writes: > > This is rather disappointing. Is that entire page suspect? > > All documentation about Python 3 is suspect until Python 3 gets > actually released (nobody can say for sure how the release will > look like in all details). Is there a better information source, then, for the current state of what's expected in Python 3.0? -- \ ?Somebody told me how frightening it was how much topsoil we | `\ are losing each year, but I told that story around the campfire | _o__) and nobody got scared.? ?Jack Handey | Ben Finney From dikkie at nospam.org Wed Jul 2 14:21:20 2008 From: dikkie at nospam.org (Dikkie Dik) Date: Wed, 02 Jul 2008 20:21:20 +0200 Subject: Discover Islam - The Fastest Growing Religion in the World ! In-Reply-To: <9d3ed65e-335c-4d45-8374-505ae7d434b1@p25g2000hsf.googlegroups.com> References: <9d3ed65e-335c-4d45-8374-505ae7d434b1@p25g2000hsf.googlegroups.com> Message-ID: <486bc722$0$23180$bf4948fe@news.tele2.nl> If it so fast growing, I'd rather wait for a stable release... LOL From sneuberger at mitre.org Mon Jul 21 09:14:53 2008 From: sneuberger at mitre.org (Neuberger, Sheldon N.) Date: Mon, 21 Jul 2008 09:14:53 -0400 Subject: ntlm authentication Message-ID: <7B3D44209E8C944288889D4132FEC4125B98D8@IMCSRV6.MITRE.ORG> Is there any way to make urllib2 handle NTLM authentication? Sheldon Neuberger -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris.hulan at gmail.com Tue Jul 8 13:41:36 2008 From: chris.hulan at gmail.com (Chris Hulan) Date: Tue, 8 Jul 2008 10:41:36 -0700 (PDT) Subject: How to make python scripts .py executable, not bring up editor References: Message-ID: On Jul 7, 5:56 pm, korean_dave wrote: > From command Prompt, i type in a script, "tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? sounds like you need to adjust the file association so .py files are associated with python.exe From workitharder at gmail.com Mon Jul 28 14:03:10 2008 From: workitharder at gmail.com (bukzor) Date: Mon, 28 Jul 2008 11:03:10 -0700 (PDT) Subject: Easier way to get the "here" path? References: <5260a10a-2605-493d-85a3-ce2dbb119f50@m73g2000hsh.googlegroups.com> <649bb102-51aa-4781-ad40-3762e59db626@56g2000hsm.googlegroups.com> Message-ID: <53f12f73-74da-4ac4-ac9d-8981da3d9ca6@34g2000hsf.googlegroups.com> On Jul 28, 10:34?am, bukzor wrote: > On Jul 26, 9:19?am, Andrew wrote: > > > > > bukzor wrote: > > >>>> from os.path import abspath, realpath > > >>>> realpath(path.__file__.rstrip("c")) > > > > '/home/bgolemon/python/symlinks/path.py' > > > >>>> realpath(abspath(path.__file__.rstrip("c"))) > > > > '/home/bgolemon/python/symlinks/symlinks/path.py' > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > I find it interesting that I get something different: > > > In [1]: import path > > path.pyc > > > In [2]: path.__file__ > > Out[2]: 'path.pyc' > > > In [3]: path.__file__.rstrip("c") > > Out[3]: 'path.py' > > > In [4]: from os.path import abspath, realpath > > > In [5]: realpath(path.__file__.rstrip("c")) > > Out[5]: '/home/andrew/sym/sym/path.py' > > > In [6]: realpath(abspath(path.__file__.rstrip("c"))) > > Out[6]: '/home/andrew/sym/sym/path.py' > > > I get the same thing for realpath() and realpath(abspath()) > > It seems to me you can just use: > > > In [1]: import path > > path.pyc > > > In [2]: from os.path import abspath > > > In [3]: realpath(path.__file__.rstrip("c")) > > Out[3]: '/home/andrew/sym/sym/path.py' > > > By the way, I am in /home/andrew/sym and path is symlinked from > > /home/andrew/sym/sym/path.py to /home/andrew/sym/path.py > > > -- > > Andrew > > As you can see above, I get the wrong think if I do that. It's very > strange that we're getting different things. I'm using python 2.4, > maybe it was updated in 2.5? After doing a little testing, it seems that realpath was in fact improved between 2.4 and 2.5. I need to stick with 2.4, so the abspath() call is still necessary for me. Regardless, the answer to my question is that there's no good built-in way to do this. Even the code above fails for some cases (say the symlink is named just "c"), making the problem non-trivial. To me, this is a failure of python's "batteries included". Is this worthy of a PEP? I'd like to add something like "__absfile__" or maybe "os.path.absolute_script_path()". Sample implementation: def scriptpath(): from inspect import currentframe file = currentframe().f_back.f_locals.get('__file__', None) if file.endswith(".pyc"): file = file.rstrip("c") from os.path import realpath, abspath return realpath(abspath(file)) Testing: ~/python>ls -l foo.py* c sym/* lrwxrwxrwx 1 bgolemon asic 10 Jul 28 10:46 c -> sym/ bar.py* lrwxrwxrwx 1 bgolemon asic 10 Jul 28 10:38 foo.py -> sym/ bar.py* -rw-rw-r-- 1 bgolemon asic 149 Jul 28 10:57 foo.pyc -rwxrwx--- 1 bgolemon asic 76 Jul 28 10:53 sym/bar.py* -rw-rw-r-- 1 bgolemon asic 149 Jul 28 10:58 sym/bar.pyc ~/python>cat sym/bar.py #!/usr/bin/env python from scriptpath import scriptpath print scriptpath() ~/python>./c /home/bgolemon/python/sym/bar.py ~/python>./sym/bar.py /home/bgolemon/python/sym/bar.py ~/python>./foo.py /home/bgolemon/python/sym/bar.py ~/python>python >>> import foo /home/bgolemon/python/sym/bar.py ~/python>cd sym/ ~/python/sym>python >>> import bar /home/bgolemon/python/sym/bar.py --Buck From bignose+hates-spam at benfinney.id.au Wed Jul 9 07:12:25 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 09 Jul 2008 21:12:25 +1000 Subject: mock with inheritance References: <87df8aea-a7e4-4e30-9384-960b0a8cfc89@27g2000hsf.googlegroups.com> Message-ID: <873amjux9i.fsf@benfinney.id.au> lidiriel writes: > But i don't know how to mock the class Component. Note that Component > provide the attribut env. I prefer to use the MiniMock framework . You don't need to specify what interface the mock object has. Its Mock objects will allow *any* attribute access, method or otherwise, and simply report what was done. You can then check that report to see if it matches what you expect; the author suggests that the existing standard-library 'doctest' module is ideal for such checking. -- \ ?It is the mark of an educated mind to be able to entertain a | `\ thought without accepting it.? ?Aristotle | _o__) | Ben Finney From larry.bates at websafe.com` Thu Jul 10 12:03:10 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 10 Jul 2008 11:03:10 -0500 Subject: Loading just in time In-Reply-To: References: Message-ID: D'Arcy J.M. Cain wrote: > I am trying to create a utility module that only loads functions when > they are first called rather than loading everything. I have a bunch > of files in my utility directory with individual methods and for each I > have lines like this in __init__.py: > > def calc_tax(*arg, **name): > from calc_tax import calc_tax as _func_ > calc_tax = _func_ > return _func_(*arg, **name) > > This works the first time I call utility.calc_tax but if I call it > again I get a "TypeError: 'module' object is not callable" error. Is > there any way to do what I want or do I have to put everything back > into a single file. Of course, I can simply change all my calls to > utility.calc_tax.calc_tax(...) but I have a lot of code to change if I > do that. > > Thanks. > You are stuck in a futile battle called "premature optimization". I would suggest that you stop worrying about any performance you would gain from doing something like this. Python has been "highly" optimized to handle imports in a very efficient way. Just put your functions in a file and import them. from myfunctions import calc_tax, ... Then you don't have to preface the function name with the module name. -Larry From JordanNealBerg at gmail.com Wed Jul 9 23:56:59 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Wed, 9 Jul 2008 20:56:59 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) Message-ID: I am trying to rewrite some C source code for a poker hand evaluator in Python. Putting aside all of the comments such as just using the C code, or using SWIG, etc. I have been having problems with my Python code not responding the same way as the C version. C verison: unsigned find_fast(unsigned u) { unsigned a, b, r; u += 0xe91aaa35; u ^= u >> 16; u += u << 8; u ^= u >> 4; b = (u >> 8) & 0x1ff; a = (u + (u << 2)) >> 19; r = a ^ hash_adjust[b]; return r; } my version (Python, hopefully ;)): def find_fast(u): u += 0xe91aaa35 u ^= u >> 16 u += u << 8 u ^= u >> 4 b = (u >> 8) & 0x1ff a = (u + (u << 2)) >> 19 r = a ^ hash_adjust[b] return r As far as I understand the unsigned instructions in C just increase amount of bytes the int can hold, and Python automatically converts to longs which have infinite size when necessary, so I am not sure why I am getting different results. I assume that I am missing something fairly simple here, so help a n00b out if you can :) Thanks in advance, jnb From tjreedy at udel.edu Tue Jul 29 15:28:45 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 15:28:45 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87tze9qeyw.fsf@nokile.rath.org> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <488D5B2C.10808@gmail.com> <488e6af8$0$20692$426a74cc@news.free.fr> <87tze9qeyw.fsf@nokile.rath.org> Message-ID: Nikolaus Rath wrote: > Bruno Desthuilliers writes: >> Nikolaus Rath a ?crit : >>> Thats true. But out of curiosity: why is changing the interpreter such >>> a bad thing? (If we suppose for now that the change itself is a good >>> idea). >> Because it would very seriously break a *lot* of code ? > > Well, Python 3 will break lots of code anyway, won't it? Each code breaking change was evaluated as a cost against the long-term net benefits. Many are removals that were announced years ago and which will not break code written with an eye to the future. An example is the removal of 'apply', which was replace with '*iterable' years ago. Some proposed changes, were rejected only because they would break too much code, or because automatic fixed would not be easy. For these reasons, the core Python syntax is pretty much untouched. Attribute lookup is part of core syntax. From samwyse at gmail.com Mon Jul 14 16:46:12 2008 From: samwyse at gmail.com (samwyse) Date: Mon, 14 Jul 2008 13:46:12 -0700 (PDT) Subject: Problems Returning an HTTP 200 Ok Message References: <1cf880cc-2036-42dc-8217-d52a714c1710@a70g2000hsh.googlegroups.com> <9bc65e72-be16-4f73-9dfb-6ddeaae34c21@m73g2000hsh.googlegroups.com> <8596af5b-fd0a-413e-8051-62d650e9a153@8g2000hse.googlegroups.com> Message-ID: <8e0527eb-3af1-428f-bfc2-5c1809c33274@t54g2000hsg.googlegroups.com> On Jul 11, 3:46?am, "Gabriel Genellina" wrote: > As Guy Davidson has already pointed out, this is a problem in the meter ? > TCP implementation, and you should ask the vendor to fix it. That would have been me, not Guy. From omer at no-log.org Wed Jul 2 06:35:04 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Wed, 2 Jul 2008 12:35:04 +0200 Subject: Attribute reference design In-Reply-To: <486ABB01.1040904@islandtraining.com> References: <486ABB01.1040904@islandtraining.com> Message-ID: <200807021235.04262.omer@no-log.org> Le Wednesday 02 July 2008 01:17:21 Gary Herron, vous avez ?crit?: > chamalulu wrote: > > On Jul 1, 11:24 pm, "Diez B. Roggisch" wrote: > >> chamalulu schrieb: > >>> Hello. > >>> I think I'm aware of how attribute access is resolved in python. When > >>> referencing a class instance attribute which is not defined in the > >>> scope of the instance, Python looks for a class attribute with the > >>> same name. (For assignment or deletion this is not the case, > >>> thankfully.) > >>> I've been trying to understand why? What is the reason behind, or > >>> practical purpose of, this design decision? Anyone, please enlighten > >>> me. > >> > >> How else would you resolve methods which are of course defined on the > >> class but invoked through the instance? > > > > Yes, of course... You're right. > > Didn't think of that. > > Thank you. I'll go stand in the corner. :) > > No need. Also, you can define a class attribute (C++ might call it a > static attribute) and access it transparently through an instance. > > class C: > aClassAttribute = 123 > def __init__(self, ...): > ... > > c = C() > ... do something with c.aClassAttribute ... > Be very careful with that, as it looks like C++ or similar other OO languages, but python handles it in a strange way if you assign a value to such an attribute. It took me a long time to understand what happens here: class Foo (object) : bar = 0 foo = Foo() print '(1) Foo.bar: %d' % Foo.bar print '(1) foo.bar: %d' % foo.bar Foo.bar += 1 print '(2) Foo.bar: %d' % Foo.bar print '(2) foo.bar: %d' % foo.bar foo.bar += 1 print '(3) Foo.bar: %d' % Foo.bar print '(3) foo.bar: %d' % foo.bar here's the output: (1) Foo.bar: 0 (1) foo.bar: 0 (2) Foo.bar: 1 (2) foo.bar: 1 (3) Foo.bar: 1 # hey dude, where is my bar ? (3) foo.bar: 2 In the third case, you might expect foo.bar += 1 to just increment Foo.bar, but actually it doesn't. I first thought it was a bug, but it's not. When you write foo.bar += 1 (equivalent to foo.bar = foo.bar + 1), python first looks for a bar attribute, finds it in the class members, and then creates an instance member with the result. Things would be different with a mutable type implementing the += operator. I discovered this in a middle of a project and it was hard to track all these assignments in my code to correct them, so I'd suggest to always access class members through the class instead of the instance, unless you have no choice or know exactly what you are doing. -- C?dric Lucantis From steve at REMOVE-THIS-cybersource.com.au Mon Jul 28 20:15:08 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 00:15:08 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> Message-ID: <009e5c8d$0$20313$c3e8da3@news.astraweb.com> On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: > On Jul 28, 10:00 am, Steven D'Aprano cybersource.com.au> wrote: >> Cutting to the crux of the discussion... >> >> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: >> > I want something where "if x" will do but a simple explicit test >> > won't. >> >> Explicit tests aren't simple unless you know what type x is. If x could >> be of any type, you can't write a simple test. Does x have a length? Is >> it a number? Maybe it's a fixed-length circular length, and the length >> is non-zero even when it's empty? Who knows? How many cases do you need >> to consider? > > Use case, please. I'm asking for code, not arguments. Please give me a > piece of code where you can write "if x" that works but a simple > explicit test won't. I gave you a piece of code, actual code from one of my own projects. If you wouldn't accept that evidence then, why would you accept it now? It isn't that explicit tests will fail, it is that explicit tests are more work for no benefit. You keep talking about "simple explicit tests", but it seems to me that you're missing something absolutely fundamental: "if x" is simpler than "if x!=0" and significantly simpler than "if len (x)!=0". Even if you discount the evidence of the character lengths (4 versus 7 versus 12) just use the dis module to see what those expressions are compiled into. Or use timeit to see the execution speed. So I'm not really sure what your point is. Yes, for vast amounts of code, there's no *need* to write "if x". If x is always a number, you can replace it with "if x != 0" and it will still work. Big deal. I never said differently. But if I don't care what type x is, why should I write code that cares what type x is? All you're doing is writing an expression that does more work than it needs to. Although the amount of work is trivial for built-ins, it's still more than necessary. But provided x is always the right sort of duck, your code will work. It will be longer, more verbose, slower, fail in unexpected ways if x is an unexpected type, and it goes against the spirit of duck-typing, but it will work. -- Steven From castironpi at gmail.com Mon Jul 28 23:57:02 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 28 Jul 2008 20:57:02 -0700 (PDT) Subject: derivative in numpy References: Message-ID: <45321c72-795e-47d8-86be-d64c2864d60c@l64g2000hse.googlegroups.com> On Jul 28, 5:34?pm, knielse... at gmail.com wrote: > Hi, > > I am looking to do a simple derivative. I would expect such a function > to be available in numpy, but can't find it. I have written my own, > but just curious if anybody knows of such function in numpy. > > Cheers, > ?Kim I presume you are taking the numerical derivative, not the symbolic one. From casey.mcginty at gmail.com Sun Jul 20 23:39:20 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Sun, 20 Jul 2008 17:39:20 -1000 Subject: Python Written in C? In-Reply-To: References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> Message-ID: On Sun, Jul 20, 2008 at 5:06 PM, Grant Edwards wrote: > On 2008-07-21, Dan Upton wrote: > > Using punch-cards and paper-tape. Real programmers can edit > their programs with a pointy stick and some home-made > sticky-tape. > > Doesn't everyone know that REAL programmers use butterflies. http://xkcd.com/378/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From LEnglish5 at cox.net Tue Jul 15 09:29:18 2008 From: LEnglish5 at cox.net (Lawson English) Date: Tue, 15 Jul 2008 06:29:18 -0700 Subject: [ANN} Daily pyogp coders meeting (PYthon Open Grid Protocols for virtual worlds) Message-ID: pyogp is a Python-based virtual worlds test harness and client library being developed by Linden Lab, makers of Second Life, and members of the SL Architecture Working Group, in order to test the Open Grid Protocols that were used in the recent "proof of concept" demo by IBM and Linden Lab, that allowed avatars to teleport from one virtual world (Second Life) to another (Open Simulator) using standardized interoperability protocols. http://www.informationweek.com/news/personal_tech/virtualworlds/showArticle.jhtml?articleID=208803274 A daily meeting within Second Life has been setup for pyogp coders and designers to meet, as described in the announcement below. This is the transcript of the first meeting: http://wiki.secondlife.com/wiki/Pyogp/Chat_Logs/Daily_Meeting/14_jul_2008 The pyogp meetings are open to any "resident" of Second Life, and any Python person (or design expert) with a desire to contribute to the process is certainly welcome. In World Meetings We're going to start having daily meetings at "infinity is full of stars" in the Levenhall simulator in Second Life at 9:30AM SLT (Pacific Coast Time) each day. These meetings are for the PyOGP coders to meet and discuss design, process and status. In the near term, these are likely to be "somewhat beefy" meetings where design issues are discussed and differences hammered out. In the longer term, these will hopefully be more "Agile Stand-Up" style meetings where we discuss: a. what we've done in the last 24 hours, b. what we're going to do in the next 24 and c. what we're blocked on. what PyOGP Coders Meeting who PyOGP l33t C0d3rZ where "infinity is full of stars" @ http://slurl.com/secondlife/Levenhall/91/208/22 when 9:30AM SLT / 12:30PM Eastern Time / 5:30PM GMT / 6:30PM Central European Time why for PyOGP contributors to hash out architecture, design, test and deploy issues IRC: irc://irc.freenode.com/#pyogp Mailing list: https://lists.secondlife.com/cgi-bin/mailman/listinfo/pyogp wiki: http://wiki.secondlife.com/wiki/Pyogp From jiri.zahradil at gmail.com Tue Jul 29 10:26:38 2008 From: jiri.zahradil at gmail.com (jiri.zahradil at gmail.com) Date: Tue, 29 Jul 2008 07:26:38 -0700 (PDT) Subject: block/lambda References: <0406eb4f-8dec-4ce2-b506-8e597de2958d@56g2000hsm.googlegroups.com> Message-ID: <0b6a5dff-dae5-4cd8-9dfd-18737c4a8746@f36g2000hsa.googlegroups.com> > 2. Will it be possible in Python 3.0 to do the following: > > >>> def dotimes(n, callable): > > ? ? ? ? for i in range(n): callable() > > >>> def block(): > > ? ? ? ? nonlocal i > ? ? ? ? for j in range(i): > ? ? ? ? ? ? ? ? print j, > ? ? ? ? print dotimes seems ok and what is wrong with that function "block"? You do not need to specify that i is "nonlocal", global i will be used. >>> i=10 >>> def block(): for j in range(i): print j, print >>> block() 0 1 2 3 4 5 6 7 8 9 Jiri From alexnbryan at gmail.com Wed Jul 16 16:22:49 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 13:22:49 -0700 (PDT) Subject: py2exe issues with pictures and icons In-Reply-To: <18495626.post@talk.nabble.com> References: <18493908.post@talk.nabble.com> <18495626.post@talk.nabble.com> Message-ID: <18495836.post@talk.nabble.com> Alexnb wrote: > > > > Mike Driscoll wrote: >> >> On Jul 16, 1:37?pm, Alexnb wrote: >>> Hello >>> >>> I am sure most of you are familiar with py2exe. I am having a bit of a >>> problem. See the program has a few pictures involved and the .ico it >>> uses >>> for the windows. However, the pictures are stored in the same directory >>> as >>> the source, something like: C:\Docs and settings\me\My >>> docs\python\program. >>> When I run the program for the interpreter, just as a .py, everything >>> works >>> just as it should. However, when I compile the main source as an .exe, >>> and >>> say let a friend try the program. It fails because it is missing the >>> .ico. >>> The catch, is I don't want to have it have to installed, at least at >>> this >>> point, I want it to be able to just run. So how can I make it just run >>> from >>> any computer with the files not being in the immediate directory. If >>> that is >>> not possible, how can I put them in the immediate directory and still >>> make >>> it work. Because that directory may change a lot so the path will >>> change. >>> >>> Just a few questions. I hope someone out there can help me out! >>> -- >>> View this message in >>> context:http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp1849390... >>> Sent from the Python - python-list mailing list archive at Nabble.com. >> >> >> Put the part of the code that needs the ico file(s) into a try/except >> block. You could also try reading the py2exe wiki and tutorials. This >> one looks like it has relevant data: >> >> http://www.py2exe.org/index.cgi/CustomIcons >> >> Mike >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > Well, that may solve the icon problem. But what about getting pictures in > there? > > Okay, the icon fix didn't really fix it, what it did was make the .exe have the icon as the little picture for the shortcut, but it isn't really a shortcut. Whatever. But, I went and ran it on another computer and this was the error log it created right off the bat. Traceback (most recent call last): File "The GUI.py", line 696, in File "Tkinter.pyc", line 1515, in wm_iconbitmap _tkinter.TclError: bitmap "C:\Documents and Settings\Alex\My Documents\PYTHON\DictionaryApp\Windows.ico" not defined -- View this message in context: http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp18493908p18495836.html Sent from the Python - python-list mailing list archive at Nabble.com. From nagle at animats.com Sat Jul 5 00:23:19 2008 From: nagle at animats.com (John Nagle) Date: Fri, 04 Jul 2008 21:23:19 -0700 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: <486ef34e$0$17156$742ec2ed@news.sonic.net> Henning_Thornblad wrote: > What can be the cause of the large difference between re.search and > grep? > > This script takes about 5 min to run on my computer: > #!/usr/bin/env python > import re > > row="" > for a in range(156000): > row+="a" > print re.search('[^ "=]*/',row) > > > While doing a simple grep: > grep '[^ "=]*/' input (input contains 156.000 a in > one row) > doesn't even take a second. > > Is this a bug in python? > > Thanks... > Henning Thornblad You're recompiling the regular expression on each use. Use "re.compile" before the loop to do it once. John Nagle From cwitts at gmail.com Wed Jul 9 09:29:09 2008 From: cwitts at gmail.com (Chris) Date: Wed, 9 Jul 2008 06:29:09 -0700 (PDT) Subject: Returning the positions of a list that are non-zero References: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> Message-ID: <51b454d7-2300-4f56-b596-d899551f810d@i76g2000hsf.googlegroups.com> On Jul 9, 7:48?am, "Rajanikanth Jammalamadaka" wrote: > Try this: > > >>> li=[0,0,1,2,1,0,0] > >>> li > > [0, 0, 1, 2, 1, 0, 0]>>> [i for i in range(len(li)) if li[i] != 0] > > [2, 3, 4] > > Cheers, > > Raj > > > > On Tue, Jul 8, 2008 at 10:26 PM, Benjamin Goudey wrote: > > I have a very large list of integers representing data needed for a > > histogram that I'm going to plot using pylab. However, most of these > > values (85%-95%) are zero and I would like to remove them to reduce > > the amount of memory I'm using and save time when it comes to plotting > > the data. To do this, I'm trying to find the best way to remove all of > > the zero values and produce a list of indices of where the non-zero > > values used to be. > > > For example, if my original list is [0,0,1,2,1,0,0] I would like to > > produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices > > of where the non-zero values used to be). Removing non-zero values is > > very easy but determining the indicies is where I'm having difficulty. > > > Thanks in advance for any help > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > "For him who has conquered the mind, the mind is the best of friends; > but for one who has failed to do so, his very mind will be the > greatest enemy." > > Rajanikanth That's a waste >>> li=[0,0,1,2,1,0,0] >>> [i for i in li if i] That's all you need. :) From anthony.hw.kong at gmail.com Mon Jul 14 22:48:20 2008 From: anthony.hw.kong at gmail.com (AK@SYD) Date: Mon, 14 Jul 2008 19:48:20 -0700 (PDT) Subject: How to write a custom tracer/profiler? Message-ID: <28ee2efb-6c8a-4884-8d25-4b91fb73ebb2@f63g2000hsf.googlegroups.com> Hi, all, Just wanna look for some suggestions on how to appoarch this problem... I have some code ("main logic") which has a dependency on a library. Let's call it DS. ("data source"). The main logic will issue a number of calls to the DS in order to get the data it needs and then carry out some calculations. I want to have a non-intrusive way to find out all the DS data requested by the main logic. One thing to note, the DS is a big, messy bit of code. So putting logger everywhere within DS and main logic is not a reliably, satisfactory solution. I have thought about using somehting like aspect. But seems to me there is no mature, widely-used aspect lib out there. Another idea is: let's roll a custom tracer/profiler. Whenever any method/attributes in the DS package are called, the return values will be logged. I have taken a quick look at profile.py in python 2.4, It seems sys module will pass a frames to the profile class. Can I access the return value of a function via these frame objects? Cheers, Anthony From fredrik at pythonware.com Mon Jul 21 10:07:59 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 16:07:59 +0200 Subject: error In-Reply-To: <0b48f3b2-0927-4745-97ce-6ee2bc8bcbe0@m73g2000hsh.googlegroups.com> References: <5f4395d7-9f5c-45c3-b137-655e5c618b8c@8g2000hse.googlegroups.com> <0b48f3b2-0927-4745-97ce-6ee2bc8bcbe0@m73g2000hsh.googlegroups.com> Message-ID: Anish Chapagain wrote: > hi thank's i probably missed the b.pack() but it's till the window is > not closed and error message of Windows Appear what does that error message say? From cyril.bazin at info.unicaen.fr Tue Jul 15 17:42:21 2008 From: cyril.bazin at info.unicaen.fr (Cyril Bazin) Date: Tue, 15 Jul 2008 23:42:21 +0200 Subject: Problem with MySQLdb and mod_python Message-ID: Hi, I installed an apache server with mod_python. I have got a problem with the mysql connection of my python script. In fact I tried this file : --------------------------------- import os os.environ["PYTHON_EGG_CACHE"] = "/tmp" import MySQLdb from mod_python import apache def test(req): db=MySQLdb.connect(user="xxx",passwd="xxx",host="xxx.xxx",db="xxx") c = db.cursor() requete = "SELECT * FROM document" nbRows = c.execute(requete) req.write("Result : %s"%repr(nbRows)) return apache.OK --------------------------------- But it seems, after many tests, that the script stops at the instruction : "c.execute(requete)" The script works if I am logged on the server as "root" or "www". I use : --------------------------------- Python 2.4.4 (#1, Oct 23 2006, 13:58:00) [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb >>> MySQLdb.__version__ '1.2.2' >>> import mod_python >>> mod_python.version '3.3.1' --------------------------------- If someone has any information that can help me... Thanks in advance, Cyril BAZIN From mercado949 at gmail.com Fri Jul 18 20:50:22 2008 From: mercado949 at gmail.com (mercado mercado) Date: Fri, 18 Jul 2008 20:50:22 -0400 Subject: Importing different versions of a module In-Reply-To: <48811064.5010603@hughes.net> References: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> <48811064.5010603@hughes.net> Message-ID: <8b51e78c0807181750x66fd0372y82367245630e921f@mail.gmail.com> Thanks norseman for the reply. You're right that I didn't like it though. :-) Also note that my original question has to do with importing modules from different locations. If all I had to do was use different paths within the script (e.g. for sending to os.path.join or whatever), then I could just put those in a config file. That's not a problem... -------------- next part -------------- An HTML attachment was scrubbed... URL: From mdboldin at gmail.com Wed Jul 30 10:51:43 2008 From: mdboldin at gmail.com (mmm) Date: Wed, 30 Jul 2008 07:51:43 -0700 (PDT) Subject: undo a dictionary Message-ID: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> I found code to undo a dictionary association. def undict(dd, name_space=globals()): for key, value in dd.items(): exec "%s = %s" % (key, repr(value)) in name_space So if i run >>> dx= { 'a':1, 'b': 'B'} >>> undict(dx) I get >>> print A, B 1 B Here, a=1 and b='B' This works well enough for simple tasks and I understand the role of globals() as the default names space, but creating local variables is a problem. Also having no output arguemtns to undict() seems counterintuitive. Also, the function fails if the key has spaces or operand characters (-,$,/,%). Finally I know I will have cases where not clearing (del(a,b)) each key-value pair might create problems in a loop. So I wonder if anyone has more elegant code to do the task that is basically the opposite of creating a dictionary from a set of globally assigned variables. And for that matter a way to create a dictionary from a set of variables (local or global). Note I am not simply doing and undoing dict(zip(keys,values)) From tjreedy at udel.edu Sun Jul 6 15:58:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 06 Jul 2008 15:58:43 -0400 Subject: re.search much slower then grep on some regular expressions In-Reply-To: References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Sebastian "lunar" Wiesner wrote: > I completely agree. I'd just believe, that the combination of some finite > state machine for "classic" expressions with some backtracking code is > terribly hard to implement. But I'm not an expert in this, probably some > libraries out there already do this. In this case, it'd be time to give > pythons re engine a more sophisticated implementation ;) One thing to remember in making comparisons is that Python moved to its own implementation to support unicode as well as extended ascii (bytes in 3.0). Does grep do that? Has pcre, which Python once used, been upgraded to do that? From mrkafk at gmail.com Wed Jul 2 12:01:33 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Wed, 02 Jul 2008 18:01:33 +0200 Subject: Importing modules in embedded Python In-Reply-To: References: Message-ID: OK I found the answer in yet another Google search, right after I gave up and posted here - turns out in order to import dynamically linked modules, one has to pass -E argument to the linker. > Exception exceptions.ImportError: > '/usr/lib/python2.4/lib-dynload/timemodule.so: undefined symbol: > PyModule_AddObject' in 'garbage collection' ignored > Fatal Python error: unexpected exception during garbage collection > Aborted From rw at smsnet.pl Sun Jul 20 07:30:09 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Sun, 20 Jul 2008 13:30:09 +0200 Subject: Help Tracing urllib2 Error, Please? References: <263aa5e2-f620-4d17-b95d-bd0b81f934a6@8g2000hse.googlegroups.com> Message-ID: <877ibgkd32.fsf@merkury.smsnet.pl> Larry Hale writes: > Since it seems I have a "unique" problem, I wonder if anyone could > point me in the general/right direction for tracking down the issue > and resolving it myself. > > See my prior post @ http://groups.google.com/group/comp.lang.python/browse_thread/thread/44775994a6b55161?hl=en# > for more info. (Python 2.5.2 on Win XP 64 ==>> Squid Proxy requiring > Authentication ==>> Internet not working.) > > I've looked the urllib2 source over, but am having trouble following > it. As previously mentioned, urllib2 initiates the request, Squid > replies "407 error" that auth's required, and then urllib2 just stops, > throwing error 407. > > Any though(s) on what to check out? > > It's frustrating (to say the least) that it seems so many are > successfully accomplishing this task, and all's working perfectly for > them, but I'm failing miserably. > > Would any quotes viewed in the HTTP traffic help? (Wireshark shows > all! :) I don't even know what other info could help. > > Any info to get about Squid's configuration that might make it "non > standard" in a way that could cause my problem? Any question(s) I > should ask my Net Admin to relay info to you all? Maybe Squid is configured to not allow sending authentication directly in URI. Or maybe there is only digest scheme allowed. Try this: def getopener(proxy=None, digest=False): opener = urllib2.build_opener(urllib2.HTTPHandler) if proxy: passwd_mgr = urllib2.HTTPPasswordMgr() passwd_mgr.add_password(None, 'http://localhost:3128', 'user', 'password') if digest: proxy_support = urllib2.ProxyDigestAuthHandler(passwd_mgr) else: proxy_support = urllib2.ProxyBasicAuthHandler(passwd_mgr) opener.add_handler(proxy_support) return opener def fetchurl(url, opener): f = opener.open(url) data = f.read() f.close() return data print fetchurl('http://www.python.org', getopener('127.0.0.1:3128')) print fetchurl('http://www.python.org', getopener('127.0.0.1:3128', digest=True)) HTH, Rob From bruno.desthuilliers at gmail.com Wed Jul 2 13:35:26 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 2 Jul 2008 10:35:26 -0700 (PDT) Subject: Trouble using pinckle References: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> <1ijgp2r.1j1k5xwwbtiwcN%pdorange@pas-de-pub-merci.mac.com> <486ba8a4$0$11957$426a74cc@news.free.fr> Message-ID: <386f827f-1cc0-4d87-842e-29d9d04cf4f3@z72g2000hsb.googlegroups.com> On 2 juil, 18:40, C?dric Lucantis wrote: > > > I'll also try the dictionnary method. > > > My final idea was that a dictionnary would be perhaps simple in the > > > future to save/load as XML and a parser. > > XML ? What a strange idea ? > > Why is it so strange ? It was kind of joke. But only kind of... > Many softs have their config in xml, and the xml.* > modules are not that hard to use. It makes sense if you have a lot of config > entries with nested sections. Lightweight solutions like json or yaml comes to mind here... From vshankar0 at gmail.com Sat Jul 19 15:10:31 2008 From: vshankar0 at gmail.com (Venky K Shankar) Date: Sun, 20 Jul 2008 00:40:31 +0530 Subject: How do you check if a program/process is running using python? In-Reply-To: References: Message-ID: <200807200040.32190.vshankar0@gmail.com> On Sunday 20 July 2008 12:08:49 am Lamonte Harris wrote: > How do you check if a program or process is running when using python? > What I want to do is have an infinite loop to check if a program is running > or not and send data to my web server to check yes or no. Is this > possible? If so how? you can execute OS system call. here i execute ps -ef and grep the required process name (or you can grep by pid on that particular column using awk) import os os.system("ps -ef | grep -v grep | grep ") in my system it gives result 0 if the process is running >>> a = os.system("ps -ef | grep -v grep | grep python") root 8749 5331 0 Jul19 pts/1 00:00:00 python >>> a 0 else gives non 0 : >>> a = os.system("ps -ef | grep -v grep | grep python123") >>> a 256 you can check this inside while True: I am sure there should be a far better solution that this in python. -Venky From vlastimil.brom at gmail.com Tue Jul 1 07:11:12 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 1 Jul 2008 13:11:12 +0200 Subject: How make regex that means "contains regex#1 but NOT regex#2" ?? In-Reply-To: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> References: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> Message-ID: <9fdb569a0807010411u2da4ea5xbec69b5b695605d9@mail.gmail.com> 2008/7/1, seberino at spawar.navy.mil : > > I'm looking over the docs for the re module and can't find how to > "NOT" an entire regex. > > For example..... > > How make regex that means "contains regex#1 but NOT regex#2" ? > > Chris > > -- > http://mail.python.org/mailman/listinfo/python-list > Maybe I'm missing something, but the negative lookahead seems to do roughly that (at least for simpler cases); the usual form is the check the text after the match, but it can also be used at the beginning of the pattern. ie. (?!regex#2)regex#1 e.g. the following should search for "words" discarding some very frequent ones; the important part seems to be keeping the excluding regexp2 compatible with the matching regex#1. (?!\b(?:an?|the|is|are|of|in|to|and)\b)\b\w+\b (without the checks for word boundaries \b, this pattern would also exclude "words" only partly containing the stopwords) regards vbr -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick at craig-wood.com Mon Jul 28 06:35:27 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 28 Jul 2008 05:35:27 -0500 Subject: ctypes - unloading implicitly loaded dlls References: Message-ID: pigmartian wrote: > I'm writing a program that uses functionality from two different sets of > cdlls which reside in two different directories, call them 'libA.dll' > and 'libB.dll'. Although I don't directly use it, both directories > contain a dll with the same name, although they aren't in fact > identical. Call them, "libC.dll". However, the c-functions I call from > the clls I do use seem to implicitly use "libC.dll". The problem that > occurs after I load one dll and call functions in it, when I try to load > the second dll I get windows errors because the second dll tries to call > a function in its version of libC.dll, but it finds the version meant > for libB.dll, which doesn't contain that function. > > Oy, I hope some sample code makes it clearer: > > def demo(): > > A = ctypes.cdll.LoadLibrary('/path1/libA.dll') > A.foo() # implicitly uses '/path1/libC.dll' > > _ctypes.FreeLibrary(A._handle) > > # CRASH! > B = ctypes.cdll.LoadLibrary('/path2/libB.dll') > # "The procedure entry point some_func could not be located > # in the dynamic link library libC.dll.": > > # libB.dll wants to use code from '/path2/libC.dll', but > # instead it finds '/path1/libC.dll' already loaded > # in memory, which doesn't > # contain the function call it wants. > > > Assuming my understanding of things is correct, then I believe what I > need to do is to remove /path1/libC.dll from memory before I try loading > libB.dll, but I haven't found any way of doing that. Can anyone offer > my some suggestions? Or, am I S.O.L.? You could try loading C explicitly with ctypes.LoadLibrary() before loading A, then you'll have a handle to unload it before you load B. I think I'd probably split the code into two or three processes though. Perhaps use http://pypi.python.org/pypi/processing to communicate between them. That should get you out of DLL Hell! (Don't load any of the DLLs before you start the worker processes off.) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From snowballz.game at gmail.com Fri Jul 18 19:05:44 2008 From: snowballz.game at gmail.com (Michael Lubker) Date: Fri, 18 Jul 2008 18:05:44 -0500 Subject: Any Game Developers here? In-Reply-To: <4A235BC6-5E46-4402-AF2D-BA3DBC175517@gmail.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> <4A235BC6-5E46-4402-AF2D-BA3DBC175517@gmail.com> Message-ID: <76b841590807181605r106995d2k98486993a4eaccc4@mail.gmail.com> I'm interested in general... I know about PyGame and Pyglet, and have used both. We're currently using Python-Ogre. In the end, I am looking to find people interested in my project ( see http://youtube.com/watch?v=E0QQ9JuclxE ), but I also want to find people experienced with Python in general, not just one library. (though of course I know that's not too likely) Aren't you one of the Escort Wing developers? :) Thanks Michael On Fri, Jul 18, 2008 at 5:13 PM, Stephen Johnson wrote: > I use the Pyglet library to make games. You want to look at the pyglet and > pygame mailing lists, not this one. Use Google. > In my opinion, PyGame is clunky and Pyglet is elegant, simple, and > comprehensive. PyGame has more examples available, but Pyglet has great > documentation and enough examples to answer any questions you might have. > Both have active communities. > > -Steve Johnson > On Jul 18, 2008, at 5:38 PM, Michael Lubker wrote: > > Any people that use Python as the predominant language for their game > development here? > > ~Michael > -- > http://mail.python.org/mailman/listinfo/python-list > > -- ~ "The world hates change, yet it is the only thing that has brought progress." ~ Charles Kettering http://snowballz.joey101.net From timothywayne.cook at gmail.com Sun Jul 6 08:52:11 2008 From: timothywayne.cook at gmail.com (Tim Cook) Date: Sun, 06 Jul 2008 09:52:11 -0300 Subject: Hands-on HTML Table Parser/Matrix? In-Reply-To: References: Message-ID: <1215348731.2873.734.camel@localhost.localdomain> There are couple of HTML examples using Pyparsing here: http://pyparsing.wikispaces.com/Examples --Tim On Sun, 2008-07-06 at 14:40 +0200, robert wrote: > Often I want to extract some web table contents. Formats are > mostly static, simple text & numbers in it, other tags to be > stripped off. So a simple & fast approach would be ok. > > What of the different modules around is most easy to use, stable, > up-to-date, iterator access or best matrix-access (without need > for callback functions,classes.. for basic tasks)? > > > Robert > -- > http://mail.python.org/mailman/listinfo/python-list -- Timothy Cook, MSc Health Informatics Research & Development Services LinkedIn Profile:http://www.linkedin.com/in/timothywaynecook Skype ID == timothy.cook ************************************************************** *You may get my Public GPG key from popular keyservers or * *from this link http://timothywayne.cook.googlepages.com/home* ************************************************************** -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From fredrik at pythonware.com Wed Jul 23 16:43:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 22:43:31 +0200 Subject: Raw Strings (I Think) In-Reply-To: References: Message-ID: Lanny wrote: >> No, it doesn't. Instead of guessing what the cause might be, please show >> us your code and show us the error message you're getting, so that we can >> determine what the cause really is. > > Ok, sorry. Heres my code: > > import glob > import random > import os > > songs = glob.glob('C:\###\###\###\*.mp3') > pick = random.choice(songs) > os.system(pick) > > And yes, I know there are better ways of randomly selecting > a .mp3 file to play but I don't care. my guess is that the real problem is that you get back filenames with spaces in them, which gets treated as multiple arguments by os.system. using os.startfile will fix this: >>> import glob, os, random >>> file = random.choice(glob.glob("\\music\\*.mp3")) >>> file '\\music\\Madrugada - Grit - 05 - Seven Seconds.mp3' >>> print file \music\Madrugada - Grit - 05 - Seven Seconds.mp3 >>> os.system(file) '\music\Madrugada' is not recognized as an internal or external command, operable program or batch file. 1 >>> os.startfile(file) ... music starts playing ... From bj_666 at gmx.net Fri Jul 18 05:46:11 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Jul 2008 09:46:11 GMT Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> Message-ID: <6eb733F67cpfU2@mid.uni-berlin.de> On Fri, 18 Jul 2008 01:31:59 -0700, SUBHABRATA wrote: > def try2(n): > a1=raw_input("PRINT A STRING:") > a2=a1.split() > a3="God Godess Heaven Sky" > for x in a2: > a4=a3.find(x) > if a4>-1: > a5=a3[a4] > print a5 > elif a4<0: > a6=x > print "It is not found" > print a6 > else: > print "Error" > s=a5+" "+a6 > print s > > Here, if I put a string like: > Petrol Helium Heaven Sky > In s it is giving me S Helium > But I am looking for an output of a5 and a6 concatenating all its > values not the last ones. Can you suggest me any help? Am I missing > any minor point? Maybe you should describe what the input looks like and what output you want to have and how the input and output are connected. In words, not in not very clear code with "numbered names". That's a silly idea and makes understanding the code very hard. Please use meaningful names! Ciao, Marc 'BlackJack' Rintsch From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 08:51:20 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 14:51:20 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <40449826-c71d-4c6e-8b74-13069269e5da@z6g2000pre.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <40449826-c71d-4c6e-8b74-13069269e5da@z6g2000pre.googlegroups.com> Message-ID: <488896bf$0$3493$426a74cc@news.free.fr> Jordan a ?crit : > OK, it seems my original reply to Bruno got lost in the Aether > (apologies therefore if a paraphrased "quantum duplicate" of this > message is eventually forthcoming.) > > Torsten has adequately responded to his second point, Not MHO, by far. > so I need only > replicated what I said for the first. > >> Please get your facts, the behaviour *is* actually fully documented: > > I have the facts. I know full well the behaviour is documented Then why do you write, let me quote: """ (snip) coding __eq__ (snip) buys you nothing from the != operator. != isn't (by default) a synonym for the negation of == (unlike in, say, every other language ever); not only will Python let you make them mean different things, without documenting this fact - it actively encourages you to do so. """ >- it > was pointed out at the time of the original discussion. Documenting a > confusing, unintuitive design decision (whether its in a programming > language, an end user GUI app or anything in between) doesn't justify > it. I was not commenting on the actual design choice, just stating that it is actually documented. > To attack a strawman: "foolanguage uses the bar IO library; printing > to stdout takes about 10 mins on the average machine. But thats ok, > because look, its documented right here." And you're talking about strawman ??? Come on, you obviously can tell the difference between a one-line statement and your above strawman argument, don't you ? Please understand that I'm not arguing about this particular design choice (and FWIW, I'd mostly agree on the point that having a != b different from not (a == b) is actually a wart). I'm just correcting your statement about the behaviour of __eq__ / __ne__ not being documented, which is obviously false. (snip) From rajanikanth at gmail.com Wed Jul 9 01:48:26 2008 From: rajanikanth at gmail.com (Rajanikanth Jammalamadaka) Date: Tue, 8 Jul 2008 22:48:26 -0700 Subject: Returning the positions of a list that are non-zero In-Reply-To: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> References: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> Message-ID: <84bdef3c0807082248u4714fe35xcff80d4288185eff@mail.gmail.com> Try this: >>> li=[0,0,1,2,1,0,0] >>> li [0, 0, 1, 2, 1, 0, 0] >>> [i for i in range(len(li)) if li[i] != 0] [2, 3, 4] Cheers, Raj On Tue, Jul 8, 2008 at 10:26 PM, Benjamin Goudey wrote: > I have a very large list of integers representing data needed for a > histogram that I'm going to plot using pylab. However, most of these > values (85%-95%) are zero and I would like to remove them to reduce > the amount of memory I'm using and save time when it comes to plotting > the data. To do this, I'm trying to find the best way to remove all of > the zero values and produce a list of indices of where the non-zero > values used to be. > > For example, if my original list is [0,0,1,2,1,0,0] I would like to > produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices > of where the non-zero values used to be). Removing non-zero values is > very easy but determining the indicies is where I'm having difficulty. > > Thanks in advance for any help > -- > http://mail.python.org/mailman/listinfo/python-list > -- "For him who has conquered the mind, the mind is the best of friends; but for one who has failed to do so, his very mind will be the greatest enemy." Rajanikanth From jamitwidme at gmail.com Wed Jul 2 10:09:05 2008 From: jamitwidme at gmail.com (jamitwidme at gmail.com) Date: Wed, 2 Jul 2008 07:09:05 -0700 (PDT) Subject: Pyro: ProtocolError('connection failed') Message-ID: Hello everyone Can someone help me fix this problem? I am using an example from Pyro(Python Remote Object) website directly. It is the last example from http://pyro.sourceforge.net/manual/8-example.htm I have two computers to run Server and Client. ############################################ server.py import Pyro.naming import Pyro.core from Pyro.errors import PyroError,NamingError ###### testclass Pyro object class testclass(Pyro.core.ObjBase): def mul(s, arg1, arg2): return arg1*arg2 def add(s, arg1, arg2): return arg1+arg2 def sub(s, arg1, arg2): return arg1-arg2 def div(s, arg1, arg2): return arg1/arg2 ###### main server program def main(): Pyro.core.initServer() daemon = Pyro.core.Daemon() # locate the NS locator = Pyro.naming.NameServerLocator() print 'searching for Name Server...' ns = locator.getNS(host='drizzle.des.hep.uiuc.edu', port=9090) daemon.useNameServer(ns) # connect a new object implementation (first unregister previous one) try: # 'test' is the name by which our object will be known to the outside world ns.unregister('test') except NamingError: pass # connect new object implementation daemon.connect(testclass(),'test') # enter the server loop. print 'Server object "test" ready.' daemon.requestLoop() if __name__=="__main__": main() ################################### ################################### client.py import Pyro.naming, Pyro.core from Pyro.errors import NamingError # locate the NS locator = Pyro.naming.NameServerLocator() print 'Searching Name Server...', ns = locator.getNS(host='drizzle.des.hep.uiuc.edu',port=9090) # resolve the Pyro object print 'finding object' try: URI=ns.resolve('test') print 'URI:',URI except NamingError,x: print 'Couldn\'t find object, name server says:',x raise SystemExit # create a proxy for the Pyro object, and return that test = Pyro.core.getProxyForURI(URI) print test.mul(111,9) print test.add(100,222) print test.sub(222,100) print test.div(2.0,9.0) print test.mul('*',10) print test.add('String1','String2') ####################################### It does not matter which computer Pyro NameServer is located. When Server and Client are in a same computer, it works perfectly fine. But whenever Server and Client run in different computers, I get a following error message. ######################################## Pyro Client Initialized. Using Pyro V3.7 Searching Name Server... finding object URI: PYRO://127.0.0.1:7888/7f000001193649ab6a89d5592bc843bb Traceback (most recent call last): File "client.py", line 22, in print test.mul(111,9) File "/usr/local/lib/python2.5/site-packages/Pyro/core.py", line 390, in __call__ return self.__send(self.__name, args, kwargs) File "/usr/local/lib/python2.5/site-packages/Pyro/core.py", line 467, in _invokePYRO self.adapter.bindToURI(self.URI) File "/usr/local/lib/python2.5/site-packages/Pyro/protocol.py", line 255, in bindToURI raise ProtocolError('connection failed') Pyro.errors.ProtocolError: connection failed ######################################## Thanks a lot. From max at alcyone.com Tue Jul 29 16:11:57 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 13:11:57 -0700 Subject: iterating "by twos" In-Reply-To: <70a172ac-0491-4918-9c74-6a577f35068a@d45g2000hsc.googlegroups.com> References: <70a172ac-0491-4918-9c74-6a577f35068a@d45g2000hsc.googlegroups.com> Message-ID: giltay at gmail.com wrote: > On Jul 29, 1:36 pm, kj wrote: >> Is there a special pythonic idiom for iterating over a list (or >> tuple) two elements at a time? > > I use this one a lot: > > for x, y in zip(a, a[1:]): > frob(x, y) It doesn't work: >>> a = range(10) >>> [(x, y) for x, y in zip(a, a[1:])] [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)] What you meant was this: >>> [(x, y) for x, y in zip(a[::2], a[1::2])] [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] but this creates three sublists through slicing and zip. The use of islice and izip is better, particularly if the list that's being iterated over is large. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Tell me the truth / I'll take it like a man -- Chante Moore From duncan.booth at invalid.invalid Sat Jul 19 16:39:34 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Jul 2008 20:39:34 GMT Subject: create instance attributes for every method argument References: <4780837f-a5bc-4071-94d3-28e2f206163e@k30g2000hse.googlegroups.com> Message-ID: Berco Beute wrote: > I remember reading somewhere how to create an instance attribute for > every method argument, but although Google is my friend, I can't seem > to find it. This could likely be done way more elegant: > >========================= > class Test(object): > > def __init__(self, a, b, c, d, e, f): > self.a = a > self.b = b > self.c = c > self.d = d >========================= > > 2B You *could* do something like this: >>> class Test(object): def __init__(self, a, b, c, d, e, f): self.update(locals()) def update(self, adict): for k in adict: if k != 'self': setattr(self, k, adict[k]) >>> c = Test(1, 2, 3, 4, 5, 6) >>> c.__dict__ {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'f': 6} >>> but to be honest, your original is much clearer as it expresses the intention without any obfuscation and as soon as you want to do anything more than simply copying all arguments you'll want to do the assignments individually anyway. From __peter__ at web.de Mon Jul 7 09:31:31 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 07 Jul 2008 15:31:31 +0200 Subject: python mysteriously halts References: <13a33043-21d1-40c0-a938-6e905d958064@m3g2000hsc.googlegroups.com> Message-ID: Todd wrote: > I ran a python script last night which connects to a matlab automation > server via DCOM (using win32com). I expected to see the results when > I came in this morning. But apparently, not long after I left, python > stopped. I hit enter in the console, and it started again. I scoured > the handful of lines of code to see if there was any kind of input > statement put there by accident but couldn't find one. Furthermore, > I've run this code many times without it pausing. It's still possible > I've done something boneheaded, but I'm wondering if there is another > reason (e.g. a pause in the win32com module, some kind of timeout > feature if the system is idle, etc.). thank you You could start your debugging process by hitting Control-C instead of and study the traceback. Peter From lars at gustaebel.de Thu Jul 17 16:21:34 2008 From: lars at gustaebel.de (Lars =?iso-8859-1?Q?Gust=E4bel?=) Date: Thu, 17 Jul 2008 22:21:34 +0200 Subject: How to process a very large (4Gb) tarfile from python? In-Reply-To: References: <0e96241d-60a3-44fd-967a-394904ad5b34@e39g2000hsf.googlegroups.com> <4nqu74p3mmmdmf9pn7125voe6itko8d31k@4ax.com> Message-ID: <20080717202134.GA7617@axis.g33x.de> On Thu, Jul 17, 2008 at 10:39:23AM -0700, Uwe Schmitt wrote: > On 17 Jul., 17:55, Terry Carroll wrote: > > On Thu, 17 Jul 2008 06:14:45 -0700 (PDT), Uwe Schmitt > > > > wrote: > > >I had a look at tarfile.py in my current Python 2.5 installations > > >lib path. The iterator caches TarInfo objects in a list > > >tf.members . If you only want to iterate and you ?are not interested > > >in more functionallity, you could use "tf.members=[]" inside > > >your loop. This is a dirty hack ! > > > > Thanks, Uwe. ?That works fine for me. ?It now reads through all 2.5 > > million members, in about 30 minutes, never going above a 4M working > > set. > > Maybe we should post this issue to python-dev mailing list. > Parsing large tar-files is not uncommon. This issue is known and was fixed for Python 3.0, see http://bugs.python.org/issue2058. -- Lars Gust?bel lars at gustaebel.de Es gen?gt nicht nur, keine Gedanken zu haben, man mu? auch unf?hig sein, sie auszudr?cken. (anonym) From callen314 at gmail.com Wed Jul 16 18:20:04 2008 From: callen314 at gmail.com (Craig Allen) Date: Wed, 16 Jul 2008 15:20:04 -0700 (PDT) Subject: singletons Message-ID: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Hey, forgive me for just diving in, but I have a question I was thinking of asking on another list but it really is a general question so let me ask it here. It's about how to approach making singletons. Background: I've been programming in python seriously for about a year now, maybe a little longer depending how you count, and the system I am making is sophisticated enough that I've had to enter into a few idioms which were beyond my knowledge of python, and I had to do quick research and test my ideas with test code (which of course can miss subtle problems). Otoh, I have decades of programming experience now and wasn't totally without footing. I think I have a solution I like for creating something to act as a singleton but I'm curious what other's think. I have several classes in our system which need to act like singletons, they are libraries of data classifications, and other such libraries of configurations for the system which need to be global. The first thing I found searching for singleton, early in this project, trying to be a good citizen and find a decent idiom from the python community itself, knowing someone had mentioned "singleton" and "python" together at some point, was a recommendation to do this: (option 1) class TehLibrary(object): __single = None def __init__(self): if (TehLibrary.__single): raise AlreadyExistsException # or whatever This sucks because that means creation of the object has to be in a try block as a matter of course, something I promptly hid in a factory function, but still. But the way this worked made me realize that the Class itself is a full fledged object, quite instance-like from my C++ addled (I love you C++) perspective and it's single. If I can store that instance, I can make a class that shares member at the class level. The class doesn't even have to be a singleton exactly. (option 2) Therefore option two is a family of options where class level members can be used to share whatever needs to be shared, though strictly the class is not a singleton since multiple instances are created which merely share the data that should be single (say a big dictionary of configuration information the class manages). (option 3) I still wanted actual singletons and realized that since I had to create a factory function even in option 1, that I could use module level variables to control the behavior of those factories, which led me to realize I'm basically just using the module itself as a singleton. And this is sort of where I have arrived... when I import the modules it runs code to build up it's basic services, much like an object construction. It only runs once no matter how many times it's imported. When client code asks for the library that should be a singleton, it gets a singleton which has been stored in a module level variable. Anyone have any comments? Is there anything wrong, evil, or ugly about using a module this way, or am I correct to think that actually, this is a common approach in python. Is it pythonic? From nicolas.pourcelot at gmail.com Fri Jul 18 06:03:53 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Fri, 18 Jul 2008 03:03:53 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> Message-ID: <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> On 18 juil, 11:30, Peter Otten <__pete... at web.de> wrote: > nicolas.pource... at gmail.com wrote: > > Hi, > > > I want to test if an object IS in a list (identity and not equality > > test). > > I can if course write something like this : > > > test = False > > myobject = MyCustomClass(*args, **kw) > > for element in mylist: > > ? ? if element is myobject: > > ? ? ? ? test = True > > ? ? ? ? break > > > and I can even write a isinlist(elt, mylist) function. > > > But most of the time, when I need some basic feature in python, I > > discover later it is in fact already implemented. ;-) > > > So, is there already something like that in python ? > > I tried to write : > > 'element is in mylist' > > but this appeared to be incorrect syntax... > > There is no "is in" operator in Python, but you can write your test more > concisely as > > any(myobject is element for element in mylist) > > > Thanks a lot However, any() is only available if python version is >= 2.5, but I may define a any() function on initialisation, if python version < 2.5 I think something like >>> id(myobject) in (id(element) for element in mylist) would also work, also it's not so readable, and maybe not so fast (?)... An "is in" operator would be nice... > > PS: Btw, how is set element comparison implemented ? My first > > impression was that 'a' and 'b' members are considered equal if and > > only if hash(a) == hash(b), but I was obviously wrong : > >>>> class A(object): > > ... def __eq__(self,y): > > ... return False > > ... def __hash__(self): > > ... return 5 > > ... > >>>> a=A();b=A() > >>>> a==b > > False > >>>> hash(b)==hash(a) > > True > >>>> b in set([a]) > > False > >>>> S=set([a]) > >>>> S.difference([b]) > > set([<__main__.A object at 0xb7a91dac>]) > > > So there is some equality check also, maybe only if '__eq__' is > > implemented ? > > In general equality is determined by __eq__() or __cmp__(). By default > object equality checks for identity. > > Some containers (like the built-in set and dict) assume that a==b implies > hash(a) == hash(b). > > Peter So, precisely, you mean that if hash(a) != hash(b), a and b are considered distinct, and else [ie. if hash(a) == hash(b)], a and b are the same if and only if a == b ? From stodge at gmail.com Wed Jul 9 14:53:28 2008 From: stodge at gmail.com (Stodge) Date: Wed, 9 Jul 2008 11:53:28 -0700 (PDT) Subject: Boost Python - C++ class' private static data blown away before accessing in Python? References: <8b864486-9283-4991-a3cd-3c59c309959a@56g2000hsm.googlegroups.com> Message-ID: <69f5feb2-afbb-4353-b5ee-1bfbf4d8bf6e@z72g2000hsb.googlegroups.com> Oops - I didn't see my post so I thought something had gone wrong and reposted. Apologies for the multiple posts. On Jul 9, 11:57?am, Stodge wrote: > Could it be a boundary problem? The static data is initialised by the > application. The problem arises when the python module tries to access > it. > > On Jul 5, 11:14?pm, Giuseppe Ottaviano wrote: > > > > In Python, I retrive an Entity from the EntityList: > > > > elist = EntityList() > > > elist.append(Entity()) > > > elist.append(Entity()) > > > > entity = elist.get_at(0) > > > > entity.foo() > > > > But it crashes inside foo() as the private static data is empty; or > > > rather the string array is empty. I know before that point that the > > > private static data is valid when accessed earlier by the C++ code as > > > the program works fine. It just won't work from Python, so somehow the > > > private static data has been blown away but I can't work out where or > > > why. > > > Probably it is a problem of lifetime. What is the signature of append? ? > > Who deletes the appended Entity in C++ code? > > If append takes a raw pointer, Boost.Python copies the pointer but ? > > destroys the Entity object because it is a temporary and its reference ? > > count went to zero. So the pointer in the list is referring to a ? > > destroyed object, which results in undefined behaviour. > > > Did you have a look at the lifetime policies of Boost.Python? The ? > > simplest way to workaround the problem is using const reference ? > > arguments, and always use value semantics. If it can result in a ? > > performance penalty, another simple way is using shared_ptr's, which ? > > have their own reference count (different from the one in CPython ? > > lib), but Boost.Python does the magic to make them work together. > > > HTH, > > Giuseppe From bulg at ngs.ru Sun Jul 13 06:05:49 2008 From: bulg at ngs.ru (Yosifov Pavel) Date: Sun, 13 Jul 2008 03:05:49 -0700 (PDT) Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> Message-ID: <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> On 13 ???, 14:12, Peter Otten <__pete... at web.de> wrote: > Yosifov Pavel wrote: > > Whats is the way to clone "independent" iterator? I can't use tee(), > > because I don't know how many "independent" iterators I need. copy and > > deepcopy doesn't work... > > There is no general way. For "short" sequences you can store the items in a > list which is also the worst-case behaviour of tee(). > > What are you trying to do? > > Peter I try to generate iterators (iterator of iterators). Peter, you are right! Thank you. For example, it's possible to use something like this: def cloneiter( it ): """return (clonable,clone)""" return tee(it) and usage: clonable,seq1 = cloneiter(seq) ...iter over seq1... then clone again: clonable,seq2 = cloneiter(clonable) ...iter over seq2... Or in class: class ReIter: def __init__( self, it ): self._it = it def __iter__( self ): self._it,ret = tee(self._it) return ret and usage: ri = ReIter(seq) ...iter over ri... ...again iter over ri... ...and again... But I think (I'm sure!) it's deficiency of Python iterators! They are not very good... --Pavel From walter at livinglogic.de Thu Jul 3 07:37:23 2008 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Thu, 03 Jul 2008 13:37:23 +0200 Subject: ANN: XML builder for Python In-Reply-To: <486C5D63.5030407@behnel.de> References: <486C5CA1.3080105@behnel.de> <486C5D63.5030407@behnel.de> Message-ID: <486CB9F3.3020902@livinglogic.de> Stefan Behnel wrote: > Stefan Behnel wrote: >> Jonas Galvez wrote: >>> Not sure if it's been done before, but still... >> Obviously ;) >> >> http://codespeak.net/lxml/tutorial.html#the-e-factory >> >> ... and tons of other tools that generate XML, check PyPI. > > Although it might be the first time I see the with statement "misused" for > this. :) XIST has been using with blocks since version 3.0. Take a look at: http://www.livinglogic.de/Python/xist/Examples.html from __future__ import with_statement from ll.xist import xsc from ll.xist.ns import html, xml, meta with xsc.Frag() as node: +xml.XML() +html.DocTypeXHTML10transitional() with html.html(): with html.head(): +meta.contenttype() +html.title("Example page") with html.body(): +html.h1("Welcome to the example page") with html.p(): +xsc.Text("This example page has a link to the ") +html.a("Python home page", href="http://www.python.org/") +xsc.Text(".") print node.conv().bytes(encoding="us-ascii") Servus, Walter From mensanator at aol.com Wed Jul 2 18:05:19 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 2 Jul 2008 15:05:19 -0700 (PDT) Subject: internet porn References: <620da533-6fe0-4dd0-bda1-c40e322a8fda@a1g2000hsb.googlegroups.com> Message-ID: <3a3fb630-b7a6-403a-a414-b6ed0d7988d7@59g2000hsb.googlegroups.com> On Jul 2, 4:42?pm, NewsChann... at gmail.com wrote: > Hello, WNBC is looking to interview someone who is addicted to > internet porn for our 11pm newscast, if you are interested or > availbale we can also disguse your identity. > Call 212-664-2731 And don't be put off by the heavy breathing. > or email wnbc.newsd... at nbcuni.com > Thanks From fredrik at pythonware.com Thu Jul 24 16:16:18 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 22:16:18 +0200 Subject: need help with introducing more traffic In-Reply-To: References: <632875.28836.qm@web51808.mail.re2.yahoo.com> <6es0m9F8mehmU1@mid.uni-berlin.de> Message-ID: Fredrik Lundh wrote: > "load testing" other people's sites are known as something else, of course. message.replace(" are ", " is ") # do'h! (when do we get the ability to edit our c.l.python messages for, say, 30 minutes after they're posted? ;-) From robert.rawlins at thinkbluemedia.co.uk Thu Jul 24 12:30:02 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 24 Jul 2008 17:30:02 +0100 Subject: Gracefull application exit. In-Reply-To: <4888AB7C.5040003@timgolden.me.uk> References: <00ba01c8eda7$2e61ecb0$8b25c610$@rawlins@thinkbluemedia.co.uk> <4888AB7C.5040003@timgolden.me.uk> Message-ID: <00d701c8edaa$860ea8b0$922bfa10$@rawlins@thinkbluemedia.co.uk> > but mind the caveats: Thanks Tim, the main caveat which worries me is the fact that it doesn't get called when being killed by SIGTERM. When I look at implementing the application as Daemon will cause complications. The implementation looks nice and is certainly the way I would like to go, but unless it'll work when killed by sigterm it likely won't be for me. Thanks Tim, if you're aware of any other methods then give me a shout. Rob From cmbrannon at cox.net Wed Jul 23 02:55:15 2008 From: cmbrannon at cox.net (Chris Brannon) Date: Wed, 23 Jul 2008 01:55:15 -0500 Subject: Proper way to query user and group database on a Unix host? References: Message-ID: <87d4l5ozsc.fsf@cox.net> Mike MacCana writes: > Hi folks, > > What's the proper way to query the passwd and group database on a Unix > host? Use the pwd and grp modules, respectively. > ## Get the full group database entry, leave just the user list, > ## and split the list on comma > groupname=users > groupsusers = commands.getoutput('getent group '+groupname).split(':',-1)[3].split(',') Instead, do this: import grp groupname = 'users' groupusers = grp.getgrnam(groupname)[3] print 'The group named "users" contains:' for username in groupusers: print username The functions from the grp and pwd modules return tuples. The docs describe their formats. Hope this helps, -- Chris From circularfunc at gmail.com Thu Jul 10 16:46:44 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 10 Jul 2008 13:46:44 -0700 (PDT) Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: >>> def mod(x,y): return x.append(y) >>> mod([1,2],3) >>> k=[1,2,3] >>> k [1, 2, 3] >>> l = mod(k,4) >>> l >>> k [1, 2, 3, 4] >>> l >>> k==l False >>> mod(k,5) >>> k [1, 2, 3, 4, 5] >>> mod(l,4) Traceback (most recent call last): File "", line 1, in mod(l,4) File "", line 2, in mod return x.append(y) AttributeError: 'NoneType' object has no attribute 'append' >>> l >>> l=k >>> l [1, 2, 3, 4, 5] >>> i=mod(k,1) >>> i >>> same stuff but i dont find this intuitive. From python at rgbaz.eu Sat Jul 12 18:58:59 2008 From: python at rgbaz.eu (Python.Arno) Date: Sun, 13 Jul 2008 00:58:59 +0200 Subject: like py2exe, but on a mac In-Reply-To: <18424336.post@talk.nabble.com> References: <18424336.post@talk.nabble.com> Message-ID: On 13 jul 2008, at 00:39, Alexnb wrote: > > Hi All > > I am wondering what I can do to turn a python app (.py) into a mac OSX > applicaiton (.app). Just like py2exe does. i use these: http://undefined.org/python/py2app.html http://effbot.org/pyfaq/how-do-i-create-a-pyc-file.htm > But I am also wondering since in > your applications folder on macs it usually doesn't have an actual > folder > for each app. Rather an icon. so for firefox, you just see the icon. > Unlike > windows where you have a folder with everything, and the actual > program is > in it. where is all the application info stored? just in the .app? apps on OSX are also folder, yet with the reserved .app extension the OS then presents this as an app (right click on an app and choose 'Show package content') py2app creates all that for you > Finally > whether or not there is an app like py2exe for mac, is there a way > to skip > the middle man and turn it straight into a .dmg with the app inside? > -- a dmg is a disk image, similar to iso on windows you can create an empty one with Disk Utility then drop everything in it's NOT an installer > cheers Arno From gordon at panix.com Wed Jul 23 14:55:34 2008 From: gordon at panix.com (John Gordon) Date: Wed, 23 Jul 2008 18:55:34 +0000 (UTC) Subject: Inserting cookies into a web session Message-ID: I'm developing a web application that needs a semi-persistent way to store information. I've looked at some options such as writing entries to a database table or creating small textfiles, but I'm not thrilled with anything I've come up with so far. Then a coworker suggested that I could just insert a cookie into the current session, which would store whatever information I wanted. This seems like a really good solution. That's what cookies are *for*, right? But I've never worked with cookies before. Is there a Python package for handling cookies? And are there any back-end requirements? I assume you would have to be running a webserver that supports sessions. Do you also have to be running some sort of web container or servlet engine? Thanks for any suggestions. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From tjreedy at udel.edu Thu Jul 24 21:01:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jul 2008 21:01:58 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87zlo747gv.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> Message-ID: Torsten Bronger wrote: > Hall?chen! > And why does this make the implicit insertion of "self" difficult? > I could easily write a preprocessor which does it after all. class C(): def f(): a = 3 Inserting self into the arg list is trivial. Mindlessly deciding correctly whether or not to insert 'self.' before 'a' is impossible when 'a' could ambiguously be either an attribute of self or a local variable of f. Or do you and/or Jordan plan to abolish local variables for methods? tjr From jeremy at 54oaks.com Thu Jul 3 11:52:12 2008 From: jeremy at 54oaks.com (Jeremy Link) Date: Thu, 3 Jul 2008 08:52:12 -0700 Subject: better way to search the Python archive Message-ID: <00e901c8dd24$c3301ad0$8101a8c0@bocaron> Just an FYI out to folks that want a better way to search the Python archive. I've been using MarkMail (www.markmail.org ) to search the archives and it works MUCH better than the Google archive. It is a free hosting of all sorts of GNU/open source mailing lists (registration NOT required or even available). -------------- next part -------------- An HTML attachment was scrubbed... URL: From maric at aristote.info Wed Jul 30 10:50:00 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 30 Jul 2008 16:50:00 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <25f024b4-1b0c-4265-bc30-24431ebbe079@z72g2000hsb.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <25f024b4-1b0c-4265-bc30-24431ebbe079@z72g2000hsb.googlegroups.com> Message-ID: <200807301650.01377.maric@aristote.info> Le Wednesday 30 July 2008 15:31:28 giltay at gmail.com, vous avez ?crit?: > > > class Signal: > > > ? ? [...] > > > ? ? def dc_offset(self, amount): > > > ? ? ? ? if amount == 0: > > > ? ? ? ? ? ? return > > > ? ? ? ? self.samples = [sample + amount for sample in self.samples] > > > > This function is also wrong assuming that because amount compare to zero, > > it can be added to sample. > > Not quite. ?I'm assuming that if amount equals 0, then amount is some > scalar. ?In fact, only if that comparison fails will I get my > exception: since [] != 0, it will then try to add sample + [], which > will raise TypeError. > > > If you want to make type checking just check the type or convert your > > parameter to an int, but the test "== 0" is of no help here. > > I'm not going for type checking here because I want Signal to support > int and float samples (and numpy.int16, &c.). Ok, but the fact that amount == 0 passes, doesn't ensure you didn't a programming error, this add just some relative robustness (protect you from passing an empty list). And a reader would probably not see your intention here (he already expect a scalar due to the name of the variable). This is exactly the problem ABC is intended to solve. Without ABC, to explicitly ensure amount is a scalar, just doing a int(amount) or int(abs(amount)) if you want to deal with complex numbers too, at the begining of the function is a common idiom. -- _____________ Maric Michaud From martin at v.loewis.de Fri Jul 11 03:04:35 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 11 Jul 2008 09:04:35 +0200 Subject: error with configure (svn 64857) In-Reply-To: References: <487681e9$0$9745$9b622d9e@news.freenet.de> Message-ID: <48770603$0$9695$9b622d9e@news.freenet.de> > Thank you Martin. How can I remove -lgcc_s and use the Intel equivalent ? I'm not so sure that there is anything wrong in configure. configure doesn't pass -lgcc_s to icc; instead, icc is making this up on its own. So I would guess you need to get libgcc_s onto you system in a way that the linker finds it. Else you need to read the icc documentation (but I'm fairly sure that icc is *required* to link with libgcc_s, for interoperability with gcc-compiled binaries). I'm somewhat puzzled that the wchar_t test is the one where it crashes; this test comes fairly late, and configure has run multiple compiler invocations before that. Can you build any binaries at all with your icc installation? Regards, Martin From disappearedng at gmail.com Sat Jul 5 04:31:33 2008 From: disappearedng at gmail.com (disappearedng at gmail.com) Date: Sat, 5 Jul 2008 01:31:33 -0700 (PDT) Subject: Not necessarily related to python Web Crawlers Message-ID: Hi Does anyone here have a good recommendation for an open source crawler that I could get my hands on? It doesn't have to be python based. I am interested in learning how crawling works. I think python based crawlers will ensure a high degree of flexibility but at the same time I am also torn between looking for open source crawlers in python vs C ++ because the latter is much more efficient(or so I heard. I will be crawling on very cheap hardware.) I am definitely open to suggestions. Thx From lanclos at ucolick.org Wed Jul 16 19:09:11 2008 From: lanclos at ucolick.org (Kyle Lanclos) Date: Wed, 16 Jul 2008 16:09:11 -0700 Subject: Manually prompting garbage collection Message-ID: <20080716230911.GD22400@monkey.ucolick.org> I've done a lot of web searching, a fair bit of C-source reading, and quite a lot of miscellaneous head scratching, and I find that I am not necessarily closer to an ideal solution. I have a Python/C interface layer that essentially does the following: Py_XDECREF (some_callback); closeService (some_service); return; The problem, of course, is that way back in my Python layer, I have Objects that are poised to be de-allocated due to the Py_XDECREF call above; those Objects have __del__ () methods that invoke calls to the service that is about to be closed in the second line above. I want to modify the above sequence to manually prompt Python's garbage collection routine(s) to take over (performance is not an issue here), similar to the following: Py_XDECREF (some_callback); PyCollect_Garbage (); closeService (some_service); return; Is that possible? I can work around this with additional convoluted tracking of the services in the C layer, but the problem would disappear entirely if the garbage collection could be explicitly invoked. I suspect the likely workaround would involve returning from the above C function, letting Whatever happen a few times, and only invoking the real closeServce () after I've returned to the C layer. To wit: Py_XDECREF (some_callback); markForClosure (some_service); return; (( ...time passes in Python-space, and a C function is invoked... )) if ( servicesNeedClosing ()) { closeServices (); } return; I would prefer, however, an explicit solution, as the above workaround continues to rely on the assumption that garbage collection occurs magically at some point when I'm not paying attention. Solutions I've read about, and/or attempted, and am not wholly interested in hearing more about: 1. Don't use __del__ methods. I'm using __del__ methods, which are otherwise doing the right thing in non-sequence-sensitive situations, so this option is off the table. 2. Don't assume that __del__ methods will be invoked in a timely fashion. I'm not making this assumption, but rather, I would like to *explicitly* assert that garbage collection has occurred. 3. Use the gc module (or PyGC_Collect). These appear to only address situations with circular references, which are not my problem-- the Py_XDECREF call makes the right thing happen, it's just that the garbage collection happens *after* the service has been properly closed. I've tried inserting calls to PyGC_Collect (including an invocation of "while (PyGC_Collect() > 0)") with no change in behavior. Suggestions are welcome. Cheers, --Kyle From jyoung79 at kc.rr.com Wed Jul 30 09:10:44 2008 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Wed, 30 Jul 2008 8:10:44 -0500 Subject: elementtree and rounding questions Message-ID: <27976748.917531217423445156.JavaMail.root@hrndva-web18-z02> Thank you very much Gabriel and Stefan for your help! I really appreciate the excellent examples you've shared which is helping me understand how all this works. Again, thank you for taking the time to help me with this. Jay From bj_666 at gmx.net Fri Jul 18 11:41:43 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Jul 2008 15:41:43 GMT Subject: Regular expression help References: <187a9118-97fb-41fc-87f2-d24c4d7522fb@w1g2000prk.googlegroups.com> Message-ID: <6ebrtnF67cpfU3@mid.uni-berlin.de> On Fri, 18 Jul 2008 10:04:29 -0400, Russell Blau wrote: > values = {} > for expression in line.split(" "): > if "=" in expression: > name, val = expression.split("=") > values[name] = val > [?] > > And when you get to be a really hard-core Pythonista, you could write > the whole routine above in one line, but this seems clearer. ;-) I know it's a matter of taste but I think the one liner is still clear (enough):: values = dict(s.split('=') for s in line.split() if '=' in s) Ciao, Marc 'BlackJack' Rintsch From upton at virginia.edu Mon Jul 21 14:28:05 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 21 Jul 2008 14:28:05 -0400 Subject: automating python programs In-Reply-To: References: Message-ID: <5504f9ac0807211128p3b94b4c2tb8f454ef54f50a27@mail.gmail.com> On Mon, Jul 21, 2008 at 2:12 PM, Zach Hobesh wrote: > Hi, > > I'm trying to figure out how to run a python program on a schedule, maybe > every half an hour... Is this possible? > > Thanks! > > -Zach > > -- > http://mail.python.org/mailman/listinfo/python-list > On Linux, man cron. From keshet1 at umbc.edu Tue Jul 8 20:08:29 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Tue, 08 Jul 2008 20:08:29 -0400 Subject: a simple 'for' question Message-ID: <4874017D.2000401@umbc.edu> Hi fans, I want to use a 'for' iteration to manipulate files in a set of folders, something like: folders= ['1A28','1A6W','56Y7'] for x in folders: print x # print the current folder f = open('my/path/way/x/my_file.txt', 'r') ... where 'x' in the pathway should iterate over '1A28','1A6W','56Y7'. How should I identify 'x' in the pathway line as the same x that is iterating over 'folders'? I am getting the following error: Traceback (most recent call last): File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Linux\Dock_method_validation\myscripts\test_for.py", line 5, in f = open('c:/Linux/Dock_method_validation/x/receptor.mol2', 'r') IOError: [Errno 2] No such file or directory: 'c:/Linux/Dock_method_validation/x/receptor.mol2' I tired several variations: %x, 'x', "x", etc. all gave me similar errors. Thanks for your help, BK From sjmachin at lexicon.net Sat Jul 19 16:12:14 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 19 Jul 2008 13:12:14 -0700 (PDT) Subject: regex doubts References: <532965.570.qm@web54502.mail.re2.yahoo.com> Message-ID: <504d473e-375a-4111-ae2e-c06aaa37b096@p25g2000pri.googlegroups.com> On Jul 20, 5:04 am, Fredrik Lundh wrote: > Mr SZ wrote: > > I am taking a string as an input from the user and it should only > > contain the chars:L , M or R > > > I tried the folllowing in kodos but they are still not perfect: > > > [^A-K,^N-Q,^S-Z,^0-9] > > [L][M][R] > > [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > > > For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. > > try "[LRM]+$" (an L or an R or an M, one or more times, all the way to > the end of the string). Ummm ... with the default flag settings, shouldn't that be \Z instead of $ ? From frank at chagford.com Tue Jul 22 11:12:06 2008 From: frank at chagford.com (Frank Millman) Date: Tue, 22 Jul 2008 08:12:06 -0700 (PDT) Subject: Is this a valid use of 'import'? Message-ID: Hi all I am familiar enough with the normal use of 'import'. However, I have found a use for it which seems effective, but I have not seen it used like this before, so I am not sure if there are any downsides. I know that when a module is imported the first time, it is 'executed'. This normally entails setting up constants, classes, functions, etc, that you want to make available to the importer. In this particular case, when it is executed, it does a whole lot more. It reads in some parameters, establishes a socket connection, starts a thread, and starts monitoring the socket using select.select. It also exposes some functions that disguise the complexity of reading from and writing to the socket. This enables me to write a 'client' program that look like this - --------------------------- from Utils.client import * connect(userid='frank',pwd='') cust = getRecord( company='chagford',table='ArCustomers', column='CustNo',value='A001') print cust close() --------------------------- As you can see, it makes writing a client program very easy. Are there any problems with this approach? Frank Millman From binjured at gmail.com Tue Jul 1 09:44:53 2008 From: binjured at gmail.com (Tom Davis) Date: Tue, 1 Jul 2008 06:44:53 -0700 (PDT) Subject: Looping-related Memory Leak References: <94312edc-babb-4c1b-8db1-233404aa4a02@i76g2000hsf.googlegroups.com> <0abf2145-231c-4189-a8ca-b1f327a735dd@a1g2000hsb.googlegroups.com> <1e36866c-4a94-40b6-9780-81e104286862@d1g2000hsg.googlegroups.com> Message-ID: <5fcaf13f-5fc1-44bc-befe-e8763e3fef60@d1g2000hsg.googlegroups.com> On Jun 30, 3:12 pm, Marc 'BlackJack' Rintsch wrote: > On Mon, 30 Jun 2008 10:55:00 -0700, Tom Davis wrote: > > To me, this seems illogical. I can understand that the GC is > > reluctant to reclaim objects that have many connections to other > > objects and so forth, but once those objects' scopes are gone, why > > doesn't it force a reclaim? For instance, I can use timeit to create > > an object instance, run a method of it, then `del` the variable used > > to store the instance, but each loop thereafter continues to require > > more memory and take more time. 1000 runs may take .27 usec/pass > > whereas 100000 takes 2 usec/pass (Average). > > `del` just removes the name and one reference to that object. Objects are > only deleted when there's no reference to them anymore. Your example > sounds like you keep references to objects somehow that are accumulating. > Maybe by accident. Any class level bound mutables or mutable default > values in functions in that source code? Would be my first guess. > > Ciao, > Marc 'BlackJack' Rintsch Marc, Thanks for the tips. A quick confirmation: I took "class level bound mutables" to mean something like: Class A(object): SOME_MUTABLE = [1,2] ... And "mutable default values" to mean: ... def a(self, arg=[1,2]): ... If this is correct, I have none of these. I understand your point about the references, but in my `timeit` example the statement is as simple as this: import MyClass a = MyClass() del a So, yes, it would seem that object references are piling up and not being removed. This is entirely by accident. Is there some kind of list somewhere that says "If your class has any of these attributes (mutable defaults, class-level mutables, etc.) it may not be properly dereferenced:"? My obvious hack around this is to only do X loops at a time and make a cron to run the script over and over until all the files have been processed, but I'd much prefer to make the code run as intended. I ran a test overnight last night and found that at first a few documents were handled per second, but when I woke up it had slowed down so much that it took over an hour to process a single document! The RAM usage went from 20mb at the start to over 300mb when it should actually never use more than about 20mb because everything is handled with local variables and new objects are instantiated for each document. This is a serious problem. Thanks, Tom From wuwei23 at gmail.com Thu Jul 17 07:30:07 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 17 Jul 2008 04:30:07 -0700 (PDT) Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> <0T56p3tmInifNv8%stesch@parsec.no-spoon.de> Message-ID: <33bbf8d8-f5b9-430b-9c47-06a6fa4477ee@w7g2000hsa.googlegroups.com> On Jul 17, 6:04 pm, Fredrik Lundh wrote: > Django's 0.91 release in early 1996 While I totally agree with position, I'm pretty sure you mean 2006 here :) From motoom at xs4all.nl Sat Jul 19 20:41:24 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Sun, 20 Jul 2008 02:41:24 +0200 Subject: Change PC to Win or Windows In-Reply-To: <6tednSAkCcl50x_VnZ2dnUVZ_oPinZ2d@earthlink.com> References: <6eeir8F6itbqU1@mid.individual.net> <6tednSAkCcl50x_VnZ2dnUVZ_oPinZ2d@earthlink.com> Message-ID: <200807200241.24695.motoom@xs4all.nl> On Saturday 19 July 2008 22:30:29 Dennis Lee Bieber wrote: > I still wonder who came up with the Commodore PET -- Personal > Electronic Transactor... yeesh... But the "Personal" was already in play > way back then. Probably Chuck Peddle, Jack Tramiel or Leonard Tramiel. For your amusement: http://en.wikipedia.org/wiki/PET_2001 Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From musiccomposition at gmail.com Mon Jul 21 22:43:13 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 21 Jul 2008 19:43:13 -0700 (PDT) Subject: Python Embedding Thread References: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> Message-ID: <87bf413d-eb98-47c0-8466-237c45fd1a0e@e53g2000hsa.googlegroups.com> On Jul 21, 6:56?am, o... at tuningchannel.de wrote: > Hi :) > > I want to run Python in my app. That works still fine. But my app > supports now Threads and I would like to know what to do, that it runs > without problems. > > PyGILState_Release and PyGILState_Ensure should solve the problem > right? Where do I have to put this two commands around? between each > Command that increase, decrease a reference? Two threads should not be running through the Python VM concurrently in the same process. The GIL has to be held *any* time you use the Python API. When you want to release the GIL (to process something in C), use PY_BEGIN_ALLOW_THREADS and PY_END_ALLOW_THREADS around the places where threads can run. > > Currently, this is a small code-snippet that represents the part of > the code-execution: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? PyObject *f_globals=NULL, *f_locals=NULL, *mod=NULL, *rv=NULL; > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? mod = PyImport_ImportModule("__main__"); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (!mod) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? return; > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? f_globals = PyModule_GetDict(mod); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? f_locals = PyDict_New(); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? PyDict_Update(f_locals, f_globals); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (!f_locals) { > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Py_DECREF(mod); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? PyErr_Print(); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? return; > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? } > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? rv = PyRun_String( ? ? ?, Py_file_input, f_locals, > f_locals); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (!rv) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? PyErr_Print(); > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Py_XDECREF(rv); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Py_DECREF(mod); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Py_DECREF(f_locals); > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Py_DECREF(f_locals); > > Thanks a lot for your help :) From ethan at stoneleaf.us Wed Jul 9 19:54:05 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 09 Jul 2008 15:54:05 -0800 Subject: Determining when a file has finished copying In-Reply-To: References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> Message-ID: <48754F9D.1000306@stoneleaf.us> writeson wrote: > Guys, > > Thanks for your replies, they are helpful. I should have included in > my initial question that I don't have as much control over the program > that writes (pgm-W) as I'd like. Otherwise, the write to a different > filename and then rename solution would work great. There's no way to > tell from the os.stat() methods to tell when the file is finished > being copied? I ran some test programs, one of which continously > copies big files from one directory to another, and another that > continously does a glob.glob("*.pdf") on those files and looks at the > st_atime and st_mtime parts of the return value of os.stat(filename). >>From that experiment it looks like st_atime and st_mtime equal each > other until the file has finished being copied. Nothing in the > documentation about st_atime or st_mtime leads me to think this is > true, it's just my observations about the two test programs I've > described. > > Any thoughts? Thanks! > Doug The solution my team has used is to monitor the file size. If the file has stopped growing for x amount of time (we use 45 seconds) the file is done copying. Not elegant, but it works. -- Ethan From tjreedy at udel.edu Fri Jul 11 01:09:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 Jul 2008 01:09:34 -0400 Subject: Python 3.0 and removal of the 'string' module In-Reply-To: <87wsjtqiyo.fsf@benfinney.id.au> References: <87wsjtqiyo.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Howdy all, > > The Python wiki page states on its page for Python 3.0 > , in the section for > "Standard Library Changes" > , > that the 'string' module is to be removed. > > It references PEP 4 , > which has nothing to say about the status of the 'string' module. > > Further, the 'string' module has existing functionality (the Template > class, the character sets 'whitespace' etc.) that, to my knowledge, > has no replacement in Python 3.0. > > Can anyone see a reason to believe the above wiki page's statement > about the 'string' module being removed? More to the point, can anyone > see a reason why that statement should remain on that page? Removing string and moving the functionality elsewhere was considered, but... IDLE 3.0b1 >>> import string >>> dir(string) ['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'maketrans', 'octdigits', 'printable', 'punctuation', 'whitespace'] Feel free to edit the wiki. From elessar at nienna.org Thu Jul 3 15:02:08 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Thu, 03 Jul 2008 13:02:08 -0600 Subject: Write a file - beginner's question In-Reply-To: <8d278055-29be-46f1-8a6b-044838bd4b00@p25g2000pri.googlegroups.com> References: <486cefb7$0$6040$426a74cc@news.free.fr> <8d278055-29be-46f1-8a6b-044838bd4b00@p25g2000pri.googlegroups.com> Message-ID: <486D2230.2000600@nienna.org> Callie Bertsche wrote: > I have a closely related note. How do I write to a relative path with > python? Example, > source = open('/../../directory/subdirectory/file.extension') > > What am I missing? > -- > http://mail.python.org/mailman/listinfo/python-list > Leave off the beginning slash. -Matt From Phillip.Ross.Taylor at gmail.com Thu Jul 24 06:52:57 2008 From: Phillip.Ross.Taylor at gmail.com (Philluminati) Date: Thu, 24 Jul 2008 03:52:57 -0700 (PDT) Subject: Working with ctypes and char** data type Message-ID: <14b44a64-ec58-4ff2-abce-1cc44557e4e4@27g2000hsf.googlegroups.com> I'm a bit of a python newbie and I need to wrap a C library. I can initialise the library using CDLL('mcclient.so') and I can call functions correctly inside the library but I need to invoke one function which has this function definition: char ** CAPAPI McSearch(HMCLINK Handle, short nSearchType, short nNoSelect, char **pSelect, short nNoWhere, char **pWhere, char **pData, int iTimeout); For **pSelect I want to pass in an array of char points, which in C would be declared as char *pData[] = { "ADDR", "POSTCODE" }; Can someone tell me how use pointers + char pointers together in python with ctypes please? Thank you Phill From aaa at bbb.it Thu Jul 31 16:11:08 2008 From: aaa at bbb.it (Fred Mangusta) Date: Thu, 31 Jul 2008 21:11:08 +0100 Subject: Case tagging and python In-Reply-To: <1cdb154c-da87-47a8-9e6d-66597a107480@x35g2000hsb.googlegroups.com> References: <1cdb154c-da87-47a8-9e6d-66597a107480@x35g2000hsb.googlegroups.com> Message-ID: Hi, I came up with the following procedure ALLCAPS = "|ALLCAPS" NOCAPS = "|NOCAPS" MIDCAPS = "|MIDCAPS" CAPS = "|CAPS" DIGIT = "|DIGIT" def test_case(w): w_out = '' if w.isalpha(): #se la virgola non ci entra if w.isupper(): w_out = w.lower() + ALLCAPS return w_out elif w.islower(): w_out = w + NOCAPS return w_out else: m = re.match("^[A-Z]",w) if m: w_out = w.lower() + CAPS #notsure about this.. return w_out else: w_out = w.lower() + MIDCAPS return w_out elif w.isdigit(): w_out = w + DIGIT return w_out Called in here: #========================= lines = 0 for s in file: lines += 1 if lines % 1000 == 0: print '%d lines' % lines #sent = sent.replace(",","") sent = s.split() #split string by spaces for w in sent: wout= test_case(w) #========================== But I don't know if I'm doing something sensible? Moreover: - test_case has problems, cause whenever It finds some punctuation character attached to some word, doesn't tag it. I was thinking of cleaning the line of the punctuation before using split on it (see commented row) but I don't know if I have to call that replace() once for every punctuation char? -Is there a way to reprint the tagged text in a file including punctuation? -Is my test_case a good start? Would you use regular expressions? Thanks very much! F. From durumdara at gmail.com Mon Jul 28 04:27:43 2008 From: durumdara at gmail.com (durumdara at gmail.com) Date: Mon, 28 Jul 2008 10:27:43 +0200 Subject: Callback Python procedure from Delphi DLL Message-ID: Hi! I have a component, and a tool in Delphi. I wanna call it from Python. I can implement all things I need into a Delphi generated DLL. It is ok, I can use this DLL from Python, but the DLL procedure needs a callback procedure to return the partially output, and needs a python passed variable to check terminate/abort signal. For example: procedure ProcessFiles(InputFiles : string; CallBackProc: ????????????????????????); export; begin .... CallBackProc(ProcessedFiles, Percentage, NeedToAbort); if NeedToAbort then Exit; .... end; def CallBackProc(ProcessedFiles, Percentage, NeedToAbort): ... But I don't know, how to call back this procedure, and how to pass variables. The other way is a ActiveX. This time I don't load the DLL, I only construct the Delphi based Com Object, and I start the process. But in this way I also don't know how to implement the callback, because the main code uses callback events, and I need to use too... Thanks for every usable help! dd From Nikolaus at rath.org Mon Jul 28 06:13:18 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 28 Jul 2008 12:13:18 +0200 Subject: os.symlink() References: <6f5ik2F9t9b5U1@mid.uni-berlin.de> Message-ID: <87abg2s4e9.fsf@nokile.rath.org> "Diez B. Roggisch" writes: > Nikolaus Rath wrote: > >> Hello, >> >>>From `pydoc os`: >> >> symlink(...) >> symlink(src, dst) >> >> Create a symbolic link pointing to src named dst. >> >> >> Is there any reason why this is so deliberately confusing? Why is the >> target of the symlink, the think where it points *to*, called the >> `src`? It seems to me that the names of the parameters should be >> reversed. > > I used the command the other day, and didn't feel the slightest confusion. > > To me, the process of creating a symlink is like a "virtual copy". > Which the above parameter names reflect perfectly. Is this interpretation really widespread? I couldn't find any other sources using it. On the other hand: >From ln(2): ,---- | SYNOPSIS | ln [OPTION]... [-T] TARGET LINK_NAME (1st form) | | DESCRIPTION | In the 1st form, create a link to TARGET with the name LINK_NAME. `---- >From Wikipedia: ,---- | A symbolic link merely contains a text string that is interpreted and | followed by the operating system as a path to another file or | directory. It is a file on its own and can exist independently of its | target. If a symbolic link is deleted, its target remains unaffected. | If the target is moved, renamed or deleted, any symbolic link that | used to point to it continues to exist but now points to a | non-existing file. `---- Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From diordna at gmail.com Fri Jul 18 15:43:14 2008 From: diordna at gmail.com (Stephen Johnson) Date: Fri, 18 Jul 2008 15:43:14 -0400 Subject: Distributing Python App In-Reply-To: <072bf39b-d700-482e-ab59-36840e21e83e@a70g2000hsh.googlegroups.com> References: <072bf39b-d700-482e-ab59-36840e21e83e@a70g2000hsh.googlegroups.com> Message-ID: Look up py2app and py2exe, for OS X and Windows, respectively. They are extensively documented and easy to use. On Jul 18, 2008, at 3:35 PM, KDawg44 wrote: > Hi, > > I am very new to Python but find it very interesting (from what I know > of it) and am considering writing an application. However, I have a > question regarding distribution of the app once it is done. Is there > a way to package everything a user needs to run the app or will they > have to install Python their machine? This is probably an obvious > question but most development I do is for administrative tasks on > servers and such, not usually development of an app for someone else. > > Thanks for your help. > > Kevin > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Jul 9 06:09:01 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 09 Jul 2008 12:09:01 +0200 Subject: delete lines References: <35d53620-16c7-4c2c-b904-04dbab6bc91a@z66g2000hsc.googlegroups.com> Message-ID: antar2 wrote: > I am new in python and I have the following problem: > > Suppose I have a list with words of which I want to remove each time > the words in the lines below item1 and above item2: > f = re.compile("item\[1\]\:") > g = re.compile("item\[2\]\:") > for i, line in enumerate(list1): > ????????????????f_match = f.search(line) > ????????????????g_match = g.search(line) > ????????????????if f_match: > ????????????????????????if g_match: > ????????????????????????????????if list1[i] > f_match: > ????????????????????????????????????????if list1[i] < g_match: > ????????????????????????????????????????????????del list1[i] > > > But this does not work > > If someone can help me, thanks! I see two problems with your code: - You are altering the list while you iterate over it. Don't do that, it'll cause Python to skip items, and the result is usually a mess. Make a new list instead. - You don't keep track of whether you are between "item1" and "item2". A simple flag will help here. A working example: inlist = """item1 a b item2 c d item3 e f item4 g h item1 i j item2 k l item3 m n item4 o p """.splitlines() print inlist outlist = [] between = False for item in inlist: if between: if item == "item2": between = False outlist.append(item) else: outlist.append(item) if item == "item1": between = True print outlist Peter From deets at nospam.web.de Tue Jul 22 05:26:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 11:26:47 +0200 Subject: Hello,who can help me! References: <163330b8-8d0d-44c4-baf7-450bd42f8402@c65g2000hsa.googlegroups.com> Message-ID: <6elngkF7mgmfU1@mid.uni-berlin.de> birdprince at gmail.com wrote: > I have implemented a C++ COM,which contains two interface in one > coclass. > when i use this COM in python: > dll=win32com.client.Dispatch("XXXXX") > then i can only call default interface's method,but can't call non > default interface's method. > who can tell me how to call non default interface's method. > thank you very much! > you can send the answer to my mailbox:birdprince at hotmail.com AFAIK win32com only supports IDispatch-based interfaces, not custom interfaces. Diez From torriem at gmail.com Mon Jul 28 05:02:45 2008 From: torriem at gmail.com (Michael Torrie) Date: Mon, 28 Jul 2008 03:02:45 -0600 Subject: Attack a sacred Python Cow In-Reply-To: <87proysbpn.fsf@nokile.rath.org> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <488D5B2C.10808@gmail.com> <87proysbpn.fsf@nokile.rath.org> Message-ID: <488D8B35.7090203@gmail.com> Nikolaus Rath wrote: > Thats true. But out of curiosity: why is changing the interpreter such > a bad thing? (If we suppose for now that the change itself is a good > idea). Round and round and round we go. Because by doing as you suggest you'd be altering the internal consistency of how python deals with objects, particularly function objects. By keeping all functions as function objects, we're able to provide a consistent view of things both to the programmer and the interpreter. If we break this consistency then we're saying, well this is always a function, except in this case, and except in this case, when it's dealt with specially. This does not fit at all with python's established mantras. In python, "def" does only one thing: it creates a function object and binds it to a name. That's it! Making what def does context-sensitive seems pretty silly to me, and without any real benefit. As said before, adding attributes after the fact that are functions is a chore, because those functions can't be unit tested, and can't be clearly read and understood by other programmers. From wuwei23 at gmail.com Tue Jul 22 01:18:37 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 21 Jul 2008 22:18:37 -0700 (PDT) Subject: string[i:j:k] References: Message-ID: <4a9a4cf3-9ef4-4d9e-b714-bbf62b7c1917@v1g2000pra.googlegroups.com> On Jul 22, 3:10?pm, konstantin wrote: > some_string[i:j:k] > What does it mean? i = start position, j = end position, k = step size >>> s = "ABABABABABABAB" >>> s[0:6:2] 'AAA' >>> s = "ABCABCABCABCABC" >>> s[0:6:3] 'AA' Hope this helps. - alex23 From adityashukla1983 at gmail.com Thu Jul 24 16:06:08 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Thu, 24 Jul 2008 15:06:08 -0500 Subject: Reading a file Message-ID: <73045cca0807241306h370166ebwdd1b12227cef43c2@mail.gmail.com> I have a text file whose contents are like this:- jd|fj|dnv|jd|0.33|c:\\windows\\win32 shcbsbs|nscsjsj|0.93|hsbcjsnc I am trying to read the file like this:- >>> x = open("c:\\a.txt","r") >>> x.read() the result that i get is ike this:- 'jd|fj|dnv|jd|0.33|c:\\\\windows\\\\win32\nshcbsbs|nscsjsj|0.93|hsbcjsnc\n' My doubt is how can i read the file as it is? ie my output should be d|fj|dnv|jd|0.33|c:\\windows\\win32 shcbsbs|nscsjsj|0.93|hsbcjsnc Thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Fri Jul 25 00:38:45 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 25 Jul 2008 16:38:45 +1200 Subject: os.walk question References: Message-ID: In message , Fredrik Lundh wrote: > Lanny wrote: > >> How would one make a list of the files in the top directory >> using os.walk. >> >> I need to pick a random file from said list. > > if you want a list of files from a single directory, use listdir, not > walk: > > >>> import os, random > >>> random.choice(os.listdir("/")) > 'python25' Won't that return any subdirectories as well as files? From stefan_ml at behnel.de Fri Jul 18 02:58:57 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 18 Jul 2008 08:58:57 +0200 Subject: wholesale n i k e [...] In-Reply-To: References: Message-ID: <48803f31$0$6614$9b4e6d93@newsspool2.arcor-online.net> hyh_david at hotmail.com wrote: > [incomplete babbling removed] I guess this guy meant the "whole snake", but messed up his keyboard. Stefan From lew at lewscanon.com Sun Jul 13 00:05:51 2008 From: lew at lewscanon.com (Lew) Date: Sun, 13 Jul 2008 00:05:51 -0400 Subject: spam <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> In-Reply-To: <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> Message-ID: WDC wrote: > BTW I reported it, yo should too. To whom did you report it, so that we may also report it there? -- Lew From casey.mcginty at gmail.com Fri Jul 25 20:13:35 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Fri, 25 Jul 2008 14:13:35 -1000 Subject: DBUS/HAL Manager Interface Help Message-ID: Can someone explain to me why this sample code does not work? I am trying to test if a device exists. ---------------- dbus_test.py -------------------------- import dbus bus = dbus.SystemBus() proxy = bus.get_object( 'org.freedesktop.Hal', '/org/freedesktop/Hal/Manager' ) manager = dbus.Interface( proxy, 'org.freedesktop.Hal.Manager' ) some_dev = manager.GetAllDevices()[0] print "Calling DeviceExists on '%s'" % some_dev print manager.DeviceExists( some_dev ) ------------------- output ------------------------------ $ python dbus_test.py Calling DeviceExists on '/org/freedesktop/Hal/devices/platform_bluetooth' Traceback (most recent call last): File "dbus_test.py", line 9, in print manager.DeviceExists( some_dev ) File "/var/lib/python-support/python2.5/dbus/proxies.py", line 140, in __call__ **keywords) File "/var/lib/python-support/python2.5/dbus/connection.py", line 607, in call_blocking message, timeout) dbus.exceptions.DBusException: org.freedesktop.Hal.SyntaxError: There is a syntax error in the invocation of the method Manager.DeviceExists -------------- next part -------------- An HTML attachment was scrubbed... URL: From Nikolaus at rath.org Thu Jul 31 10:46:28 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Thu, 31 Jul 2008 16:46:28 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> Message-ID: <87tze6862j.fsf@nokile.rath.org> Maric Michaud writes: >> > Can someone explain to me the difference between a type and a class? >> >> If your confusion is of a more general nature I suggest reading the >> introduction of `Design Patterns' (ISBN-10: 0201633612), under >> `Specifying Object Interfaces'. >> >> In short: A type denotes a certain interface, i.e. a set of signatures, >> whereas a class tells us how an object is implemented (like a >> blueprint). A class can have many types if it implements all their >> interfaces, and different classes can have the same type if they share a >> common interface. The following example should clarify matters: >> > > Of course, this is what a type means in certain literature about OO > (java-ish), but this absolutely not what type means in Python. Types > are a family of object with a certain status, and they're type is > "type", conventionnaly named a metatype in standard OO. [...] Hmm. Now you have said a lot about Python objects and their type, but you still haven't said what a type actually is (in Python) and in what way it is different from a class. Or did I miss something? Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From dullrich at sprynet.com Mon Jul 28 11:58:22 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 28 Jul 2008 10:58:22 -0500 Subject: multiple inheritance and __getattr__ References: <488ddc51$0$41654$4fafbaef@reader4.news.tin.it> Message-ID: In article <488ddc51$0$41654$4fafbaef at reader4.news.tin.it>, "Enrico" <4564 at 755189.45> wrote: > Hi there, > I have the following situation (I tryed to minimize the code to concentrate > on the issue): > > >>> class A(object): > def __getattr__(self, name): > print 'A.__getattr__' > if name == 'a': return 1 > raise AttributeError('%s not found in A' % name) > > >>> class B(object): > def __getattr__(self, name): > print 'B.__getattr__' > if name == 'b': return 1 > raise AttributeError('%s not found in B' % name) > > Both classes have a __getattr__ method. > Now I want to have a class that inherits from both so I write: > > >>> class C(B,A): > pass > > The problem arise when I try something like this: > >>> c=C() > >>> c.a > A.__getattr__ > 1 > >>> c.b > A.__getattr__ > > Traceback (most recent call last): > File "", line 1, in > c.b > File "", line 5, in __getattr__ > raise AttributeError('%s not found in A' % name) > AttributeError: b not found in A > > I was expecting, after a fail in A.__getattr__, a call to the __getattr__ > method of B but it seems that after A.__getattr__ fails the exception stops > the flow. So, if I did understand well, B.__getattr__ will be never called > "automatically". I don't know if this has a reason, if it is a design choice > or what else, any explanation is welcome. Well, it's simply the way it works. When you say C(A, B) then A is searched first for a given attribute and if A has no such attribute then B is searched. If you really want to do something like this then yes, you have to do something as below. I suspect that the people who feel expert enough to talk about what you should and shouldn't want are going to say that you shouldn't want something like this - with things set up the way you have them you really can't tell what's going to happen with c.__getattr__ unless you look at all the code in all the subclasses. > Since A and B are not written by me I can only work on C. The solution that > comes to my mind is to define a __getattr__ also in C and write something > like: > > >>> class C(A,B): > def __getattr__(self, name): > try: > return A.__getattr__(self, name) > except AttributeError: > return B.__getattr__(self, name) > > >>> c=C() > >>> c.a > A.__getattr__ > 1 > >>> c.b > A.__getattr__ > B.__getattr__ > 1 > > A better solution is welcome. > Many thanks, Enrico -- David C. Ullrich From __peter__ at web.de Fri Jul 18 15:56:29 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 21:56:29 +0200 Subject: Trickiness with unittesting References: Message-ID: arockstar at gmail.com wrote: > Basically, I'm trying to implement a setUp() and TearDown() for a > python TestSuite (as opposed to an individual test within the suite). > > Sort of. > > I have a few different test suites (call them SuiteA, SuiteB,...). For > one of the test suites (SuiteA), I need to execute a bit of code (say > startFoo()) before the first test in SuiteA runs, and once when the > last test of SuiteA finishes (endFoo()). > > Making this even trickier is that the testing framework combines the > different suites (SuiteA, SuiteB) as well as individual tests into > master test suite which my testrunner then runs. > > Also complicating matters is the fact that the testing framework can > run an *individual* test from any TestSuite: in that case, if I'm > running SuiteA.test1, I'd want to call startFoo() and endFoo() as > well. > > I could use a global variable as a flag and see if it's been set > during the setUp() method of the test cases (which would allow me to > call startFoo() once when tests from SuiteA are run from the master > suite), but that doesn't help me with calling endFoo() when the tests > from SuiteA finish. Plus, it's not very elegant. > > So: > Given a master test suite comprised of a bunch of different tests from > different suites, I need to call startFoo() before tests from SuiteA > are run, and stopFoo() after all the tests from SuiteA have finished > running. Here's a glorified version of you global flag idea: class Nested(object): def __init__(self, start, end): self.level = 0 self._start = start self._end = end def start(self): if self.level == 0: self._start() self.level += 1 def end(self): assert self.level > 0 self.level -= 1 if self.level == 0: self._end() def start_foo(): print "start foo" def end_foo(): print "end foo" foo = Nested(start_foo, end_foo) print "--- 1 ---" foo.start() print "--- 2 ---" foo.start() print "--- 3 ---" foo.end() print "--- 4 ---" foo.end() print "--- 5 ---" Peter From shandy.b at gmail.com Wed Jul 2 01:43:18 2008 From: shandy.b at gmail.com (shandy.b at gmail.com) Date: Tue, 1 Jul 2008 22:43:18 -0700 (PDT) Subject: Python and timezones Message-ID: I'm trying to write some code to deal with world timezones, and I'm getting a strange result. America/Iqaluit should not be showing up in UTC+00:00, but it is. Can anyone see what's wrong with this code? import time from datetime import datetime import os import pytz def getZoneNamesOnThisComputer(): for i in pytz.all_timezones: if os.path.exists( os.path.join('/tmp/usr/share/zoneinfo/', i)): yield i def getZonesGroupedByOffset(): '''return a dict of all the zone names , grouped by their offset eg: {'-0400': ['America/Blanc-Sablon', 'Etc/GMT+4'], '+0000': ['America/Iqaluit', 'Etc/GMT', 'Europe/Belfast', 'GB', 'GMT'], ... } ''' Y,M,D,h,m,s = time.localtime()[:6] zonesGroupedByOffset = {} for name in getZoneNamesOnThisComputer(): tz = pytz.timezone(name) now = datetime(Y,M,D,h,m,s, tzinfo=tz) # strfime returns a string like "-0800" or "+0430" or "0000" offsetKey = now.strftime('%z') if not zonesGroupedByOffset.has_key(offsetKey): zonesGroupedByOffset[offsetKey] = [] zonesGroupedByOffset[offsetKey].append(name) return zonesGroupedByOffset z = getZonesGroupedByOffset() print z['+0000'] # Why is America/Iqaluit showing up here??? From larry.bates at websafe.com` Wed Jul 9 16:43:08 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 09 Jul 2008 15:43:08 -0500 Subject: User-defined exception: "global name 'TestRunError' is not defined" In-Reply-To: References: Message-ID: jmike at alum.mit.edu wrote: > I'm using some legacy code that has a user-defined exception in it. > > The top level program includes this line > > from TestRunError import * > > It also imports several other modules. These other modules do not > explicitly import TestRunError. TestRunError is raised in various > places throughout the modules. > > There are a few cases where something goes wrong with the program and > I get this error: > > FATAL ERROR: global name 'TestRunError' is not defined > > I realize this is kind of a silly question to ask in the general sense > without showing more of the code, but does anyone have any suggestions > as to the most likely causes of this error coming up? Could it be > something like an error happening where it is not explicitly in a try > block, or an error happening while I'm already in an except block, or > something like that? > > Thanks, > --JMike Please post the entire traceback and we might actually be able to help. The traceback will show a line number where it failed, you can look to see what is going on at the time. It is more likely a scoping issue where TestRunError isn't defined in the scope where the exception is being raised. -Larry From semanticist at gmail.com Wed Jul 30 22:47:04 2008 From: semanticist at gmail.com (Miles) Date: Wed, 30 Jul 2008 22:47:04 -0400 Subject: overriding file.readline: "an integer is required" In-Reply-To: References: Message-ID: On Wed, Jul 30, 2008 at 5:52 PM, kj wrote: > I know that I could rewrite the method like this: > > def readline(self, size=None): > if size == None: > line = self.file.readline() > else: > line = self.file.readline(size) > # etc., etc. > > ...but this seems to me exceptionally awkward. (Actually, it's worse > than awkward: it fails to complain when the overriding method is > called with the argument None. IMO, the method should have been possible to call with None in the first place (like str.split and list.sort), and it's not incorrect for your method to allow it. > It would be better to test for the > number of arguments passed to the function, but I can't figure out > how to do this either.) You could of course do: def readline(self, *args): line = self.file.readline(*args) # etc., etc. But this has its drawbacks. -Miles From ldo at geek-central.gen.new_zealand Sat Jul 26 19:47:30 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 27 Jul 2008 11:47:30 +1200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> Message-ID: In message <024ace13-f72f-4093-bcc9-f8a339c324e2 at v1g2000pra.googlegroups.com>, s0suk3 at gmail.com wrote: > On Jul 24, 5:01 am, Lawrence D'Oliveiro central.gen.new_zealand> wrote: > >> In message >> <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, >> Jordan wrote: >> >> > Except when it comes to Classes. I added some classes to code that had >> > previously just been functions, and you know what I did - or rather, >> > forgot to do? Put in the 'self'. In front of some of the variable >> > accesses, but more noticably, at the start of *every single method >> > argument list.* >> >> The reason is quite simple. Python is not truly an "object-oriented" >> language. It's sufficiently close to fool those accustomed to OO ways of >> doing things, but it doesn't force you to do things that way. You still >> have the choice. An implicit "self" would take away that choice. > > By that logic, C++ is not OO. Yes it is, because it has "this". From gerthwd at rose-hulman.edu Thu Jul 17 15:58:33 2008 From: gerthwd at rose-hulman.edu (Gerth, William D) Date: Thu, 17 Jul 2008 15:58:33 -0400 Subject: XML Parsing: Expat Error Message-ID: <0FF698F7C0354F42987734704458117F015DD7F0@EVS3.rose-hulman.edu> Hey all, I'm simply trying to get my feet wet with XML parsing, and I tried to just do something simple with ElementTree, just throw the XML tags from a file into a list. The code is as follows (and may be wrong): import glob import xml.etree.ElementTree as ET tree = ET.parse('nameofFilehere').getroot() list = [] for branch in tree: this = {} for child in branch.getchildren(): this[child.tag] = child.text list.append(this) Every time I run the program, I get this error: Traceback (most recent call last): File "nameofFilehere", line 4, in coords = ET.parse('nameofFilehere').getroot() File "C:\Program Files\Python25\Lib\xml\etree\ElementTree.py", line 862, in parse tree.parse(source, parser) File "C:\Program Files\Python25\Lib\xml\etree\ElementTree.py", line 587, in parse self._root = parser.close() File "C:\Program Files\Python25\Lib\xml\etree\ElementTree.py", line 1254, in close self._parser.Parse("", 1) # end of data xml.parsers.expat.ExpatError: no element found: line 3, column 0 What can I do to fix this, if anything? My overall goal has been to simply get the text of the XML document into a text file, but even that has failed (I get naught but gibberish), so any help would be appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mrkafk at gmail.com Sun Jul 20 08:42:09 2008 From: mrkafk at gmail.com (mk) Date: Sun, 20 Jul 2008 14:42:09 +0200 Subject: getting with statement to deal with various exceptions Message-ID: Hello, I'm trying to learn how with statement can be used to avoid writing: prepare() try: something_that_can_raise_SomeException() except SomeException, err: deal_with_SomeException finally: tear_it_down() Verbose, not very readable. OK, "with" to the rescue? Let's take a textbook example from PEP: with open('/etc/passwd', 'r') as f: BLOCK Well, great, it's neat that "with" closes the file after BLOCK has finished execution, but what if the file isn't there and attempt to open it raises IOException? I'd like to be able to catch it precisely to avoid writing verbose try: .. except: .. finally: .. blocks which as I understand has been much of the rationale behind creating "with" statement in the first place. "with" statement only allows easy dealing with prepare() and tear_it_down(). When I try to get it to deal with exceptions that might happen, it becomes more complicated: class FileContextManager: def __enter__(self, filename, mode): f = open(filename, mode) return f def __exit__(self, etype, evalue, etraceback): print "etype", etype, "evalue", evalue, "etraceback", etraceback >>> with FileContextManager("somefile", "r") as f: a = f.readlines() Traceback (most recent call last): File "", line 1, in with FileContextManager("somefile", "r") as f: TypeError: this constructor takes no arguments Bummer. Plus, no documentation I've read (on effbot, in PEP 343, etc) says how to deal with the exception happening in __enter__ method of context manager, which is precisely what I'd like to do. This is only natural, isn't it? When e.g. reading the file, preparation phase is typically checking if it can be opened in the first place. So it falls into __enter__ method of context manager. "with" limited only to successful execution of a_statement from "with a_statement" seems like limited benefit to me. I'd like to be able to write smth like class FileContextManager: def __enter__(self, filename, mode): f = open(filename, mode) return f def __except__(IOError, err): do_this print err def __except__(RuntimeError, err): do_that print "something bad happened", err def __exit__(self, etype, evalue, etraceback): print "etype", etype, "evalue", evalue, "etraceback", etraceback __exit__ deals with exceptions happening in the BLOCK below "with" statement, not with exceptions raised in "a_statement", when executing with a_statement as var: BLOCK In the above way "with" would give me the benefit of more terse, but still understandable and efficient code. Well, I can always do this: try: with open("somefile.txt") as txtfile: for line in txtfile: print line except IOError: print "No such file." No such file. But that's just ugly, nested too many times (flat is better than nested, right?) and not all that more readable. From mrkafk at gmail.com Wed Jul 2 12:46:23 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Wed, 02 Jul 2008 18:46:23 +0200 Subject: Bloody signal handling (in embedded Python code) In-Reply-To: References: Message-ID: Right, I didn't realize before that Python interpreter has its own signal handling routines. Now I am able to handle signals in Python code, but it still barfs on exit: import time import signal import sys def userBreak(sigNum, execFrame): print "Interrupted,,," sys.exit(sigNum) def terminateRun(sigNum, execFrame): print "SIGTERM received, terminating." sys.exit(sigNum) def test(): time.sleep(1) print "success" time.sleep(90) if __name__ == "__main__": signal.signal(signal.SIGTERM, terminateRun) signal.signal(signal.SIGINT, userBreak) test() The error: ./test success ( pressing Ctrl-C ) Interrupted,,, Exception exceptions.SystemExit: 2 in 'garbage collection' ignored Fatal Python error: unexpected exception during garbage collection Aborted So the real question is - how to exit cleanly from embedded Python code? From shahmed at sfwmd.gov Thu Jul 10 15:35:33 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Thu, 10 Jul 2008 15:35:33 -0400 Subject: parsing incoming emails Message-ID: HI, I am working on a project where I need to parse incoming emails (Microsoft outlook) with a specific subject into an excel file or a Microsoft access table. I am using python for my GIS works but not sure how I can use python script here to work with Microsoft outlook email. Any help or idea is highly appreciated. Thanks SA -------------- next part -------------- An HTML attachment was scrubbed... URL: From niklas.norrthon at hotmail.com Tue Jul 22 02:32:06 2008 From: niklas.norrthon at hotmail.com (Niklas Norrthon) Date: Mon, 21 Jul 2008 23:32:06 -0700 (PDT) Subject: formatting list -> comma separated (slightly different) References: Message-ID: On 9 Juli, 22:25, Michiel Overtoom wrote: > Paul & Robert wrote... > > d = ["soep", "reeds", "ook"] > >print ', '.join(d) > > soep, reeds, ook > > I occasionally have a need for printing lists of items too, but in the form: > "Butter, Cheese, Nuts and Bolts". ?The last separator is the word 'and' > instead of the comma. The clearest I could come up with in Python is below. > I wonder if there is a more pythonic solution for this problem. ?Maybe > something recursive? [snip] > def pretty(f): > ? ? if len(f)==0: return '' > ? ? if len(f)==1: return f[0] > ? ? sepwithcommas=f[:-1] > ? ? sepwithand=f[-1] > ? ? s=', '.join(sepwithcommas) > ? ? if sepwithand: > ? ? ? ? s+=' and '+sepwithand > ? ? return s def pretty(names): return ' and '.join(', '.join(names).rsplit(', ', 1)) > friends=['Anne','Bob','Chris','Debbie','Eve','Fred'] print pretty(friends) From mensanator at aol.com Fri Jul 18 20:58:24 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 18 Jul 2008 17:58:24 -0700 (PDT) Subject: new itertools functions in Python 2.6 References: <4dd80ff2-5fda-405a-a637-08c985ff8add@e53g2000hsa.googlegroups.com> <498a38d4-10b5-4824-8401-5ebb510fcfa8@y38g2000hsy.googlegroups.com> <49e8f7eb-b4c6-4a51-af0d-54a257fcc353@x41g2000hsb.googlegroups.com> Message-ID: <5032701a-5a82-4dfe-9899-a180ed50a274@c65g2000hsa.googlegroups.com> On Jul 16, 5:05 am, Mark Dickinson wrote: > On Jul 16, 7:20 am, Mensanator wrote: > > > > > ## Combinations with replacement > > > > ## ----------------------------- > > > > ## aaa aab aac aad aae abb abc abd abe acc acd ace > > > > ## add ade aee bbb bbc bbd bbe bcc bcd bce bdd bde > > > > ## bee ccc ccd cce cdd cde cee ddd dde dee eee > > > > ## > > > > ## actual words: 35 (m+n-1)!/(n!(m-1)!) words: 35 > >>> for x in combinations(range(7), 4): > ... x = [-1] + list(x) + [7] > ... print ''.join(c*(x[i+1]-x[i]-1) for i, c in enumerate('abcde')) > > Generalization left as an exercise for the reader. First part of exercise: figure out what's going on. ##[-1, 0, 1, 2, 3, 7] ['', '', '', '', 'eee'] eee ##[-1, 0, 1, 2, 4, 7] ['', '', '', 'd', 'ee'] dee ##[-1, 0, 1, 2, 5, 7] ['', '', '', 'dd', 'e'] dde ##[-1, 0, 1, 2, 6, 7] ['', '', '', 'ddd', ''] ddd ##[-1, 0, 1, 3, 4, 7] ['', '', 'c', '', 'ee'] cee ##[-1, 0, 1, 3, 5, 7] ['', '', 'c', 'd', 'e'] cde ##[-1, 0, 1, 3, 6, 7] ['', '', 'c', 'dd', ''] cdd ##[-1, 0, 1, 4, 5, 7] ['', '', 'cc', '', 'e'] cce ##[-1, 0, 1, 4, 6, 7] ['', '', 'cc', 'd', ''] ccd ##[-1, 0, 1, 5, 6, 7] ['', '', 'ccc', '', ''] ccc ## Damn, that's clever ## empty strings disappear when joined Here's what I came with for a generalization. s = 'abcde' m = len(s) n = 3 mn1 = m+n-1 m1 = m-1 p = [tuple(''.join(c*(q[i+1]-q[i]-1) for i, c in enumerate(s))) \ for q in [[t for t in chain.from_iterable(([-1],r,[mn1]))] \ for r in combinations(range(mn1), m1)]] I used the tuple() to give output consistent with the itertools functions. Combinations with replacement [26 letters 4 at a time] version 2 (Mark Dickinson) ------------------------------------------------------- actual words: 23751 (m+n-1)!/(n!(m-1)!) words: 23751 0.828000068665 seconds Drat, that's not very impressive. And here I thought using chain.from_iterable was a nice touch. Not much better than my version. p = [i for i in ifilter(lambda x: list(x)==sorted(x),product(s,repeat=n))] Combinations with replacement [26 letters 4 at a time] (using ifilter(product)) ------------------------------------------------------- actual words: 23751 (m+n-1)!/(n!(m-1)!) words: 23751 0.84299993515 seconds Maybe all the time saved not iterating through the entire Cartesian Product is lost to the overhead of all that list and string manipulation. Makes me wish they had done this function directly in itertools. Even the full Cartesian Product is faster despite being almost 20 times larger: Permutations with replacement [26 letters 4 at a time] (using product) ------------------------------------------------------- 0.453000068665 seconds for 456976 words Not to mention my goofy ooloop6 program (which certainly isn't a replacement for itertools since it only works with a single sorted iterable). Combinations with replacement [26 letters 4 at a time] original nested for loop ------------------------------------------------------- 0.18700003624 seconds for 23751 words Permutations with replacement [26 letters 4 at a time] original nested for loop ------------------------------------------------------- 0.344000101089 seconds for 456976 words So, maybe there simply ISN'T a GOOD way to do Combinations With Replacement. Thanks anyway. > > Mark From mail at timgolden.me.uk Wed Jul 16 03:29:45 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 08:29:45 +0100 Subject: About wmi In-Reply-To: <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> Message-ID: <487DA369.5080607@timgolden.me.uk> patrol wrote: >> http://timgolden.me.uk/wmi-project/wmi.py > > It cannot work either. Oh well. It was only a quick fix! I'll try to get some kind of non-ASCII edition of Windows to test against. As I understand it, the situation is that some WMI exception (ie coming from the underlying WMI/COM subsystem) results in an error message which contains non-ASCII characters. Just so I'm not chasing red herrings, could you paste the output from the following code, please? import wmi # use the version linked above c = wmi.WMI ("non-existent computer") # # Should give a traceback here for the DCOM # error, not a UnicodeDecodeError. # Thanks TJG From malaclypse2 at gmail.com Fri Jul 11 15:20:01 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 11 Jul 2008 15:20:01 -0400 Subject: Filechooser issues In-Reply-To: <576590.26999.qm@web54501.mail.re2.yahoo.com> References: <576590.26999.qm@web54501.mail.re2.yahoo.com> Message-ID: <16651e80807111220h19e9bd76u94f88afc09f10ad0@mail.gmail.com> On Fri, Jul 11, 2008 at 3:09 PM, Mr SZ wrote: > ff = gtk.FileFilter.add_pixbuf_formats() > The documentation doesn't say anything about an argument to be passed: > http://www.pygtk.org/docs/pygtk/class-gtkfilefilter.html#method-gtkfilefilter--add-pixbuf-formats I don't know anything about gtk or its python bindings. That being said, the reference page seems to say you need to do this: ff = gtk.FileFilter() #Create a file filter object ff.add_pixbuf_formats() #Tell the object what to filter for -- Jerry From is_this at visible.com Thu Jul 31 13:02:53 2008 From: is_this at visible.com (Bruce Frederiksen) Date: Thu, 31 Jul 2008 17:02:53 +0000 Subject: problem when reading file References: Message-ID: <4ad40$4891f03d$18607848$1746@KNOLOGY.NET> On Thu, 31 Jul 2008 23:44:33 +1000, shrimpy wrote: > hi every one, i am new to python, > and coz i want to write a handy command for my linux machine, to find > a word in all the files which are under the current folder. > > the code is half done, but when i run it, it complain, and i don`t know why??? > > can anyone help me have a look at it? > > > here is the message it complain > ======================================= > file is : qt_plugins_3.3rc > > Traceback (most recent call last): > File "./python_script/svn_grep.py", line 34, in > searPatten(file,'are','no') > File "./python_script/svn_grep.py", line 8, in searPatten > openFile = open(file, 'r') > IOError: [Errno 2] No such file or directory: 'qt_plugins_3.3rc' > > > here are the code i wrote > ---------------------------------------------------------------code begin > > > for root, dirs, files in os.walk(os.getcwd()): > for file in files: > print "=======================================" > print "file is : " + file + "\n" > searPatten(file,'are','no') > > ---------------------------------------------------------------code end Try changing that last line to: searPatten(os.path.join(root, file), 'are', 'no') You'll have to import os.path too... From mensanator at aol.com Sat Jul 12 15:28:06 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 12 Jul 2008 12:28:06 -0700 (PDT) Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: On Jul 12, 2:18?pm, Terry Reedy wrote: > Peter Otten wrote: > > Denis Kasak wrote: > > >> Basically, it reverses the list in place, so it modifies the list which > >> called it. It does not return a /new/ list which is a reversed version > >> of the original, as you expected it to. Since it doesn't return anything > >> explicitly, Python makes it return None. Hence, the comparison you are > >> doing is between the original list and a None, which is False, naturally. > >> Try this: > > >> spam = ['a', 'n', 'n', 'a'] > >> eggs = spam[:] > >> if spam.reverse() == eggs: > >> ? ? print "Palindrome" > > > Your explanation is correct, but your example code compares None to > > ['a', 'n', 'n', 'a'] and therefore won't print "Palindrome", either. > > I don't know if this was posted yet, It hasn't. and here's why: IDLE 2.6b1 >>> seq=['a','n','n','a'] >>> seq.reversed() Traceback (most recent call last): File "", line 1, in seq.reversed() AttributeError: 'list' object has no attribute 'reversed' > but 'seq.reversed() == seq' is the > simple way to test for 'palindomeness'. Not in 2.x. From mail at microcorp.co.za Tue Jul 8 03:51:17 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 8 Jul 2008 09:51:17 +0200 Subject: Cross Compiler for Python? Message-ID: <001001c8e0d2$3604d720$0d00a8c0@hendrik> Jorgen Grahn wrote: >This is a special case of a more general, non-Python problem which you >will have to address if you want to build an industrial controller. > >If your target has no C compiler[1], you have to set up a cross-compiling >environment. I'd be surprised if the eBox doesn't come with >documentation covering this. The eBox comes with a non free (both as in beer and speech) distribution, without even a root password, and tied to the mac address in the hardware so that it can only run on a specific box. So we (the local distributor and us) are trying to put together something free and useful. I think what they are doing is of dubious legality, but instead of fighting it, we are simply ignoring it. If there was any documentation, I certaintly did not see it. > >If there are special procedures and requirements for cross-compiling >Python (someone else indicated there are), I guess the Python >installation notes must cover this in a general way. > The python readme tells you how to install on the same box - I have not found anything that tells me how to do a cross compile, which is the reason I started this thread... >/Jorgen > >[1] Or even if it has one. It is much more convenient to build in your >normal work environment where you have plenty of disk, CPU and RAM, >a good text editor, version control, Perl ... So far, I have sternly resisted getting involved with Perl, and I hope to die before I have to wrap my head around it. - Hendrik From Xue.Huichao at gmail.com Thu Jul 17 05:19:46 2008 From: Xue.Huichao at gmail.com (Bighead) Date: Thu, 17 Jul 2008 02:19:46 -0700 (PDT) Subject: common elements between list of lists and lists References: <2724c6f8-d75d-4fc2-ac8f-310f4f622aae@p25g2000hsf.googlegroups.com> Message-ID: On Jul 17, 4:30 pm, antar2 wrote: > Hello, > > I am a beginner in python. > following program prints the second element in list of lists 4 for the > first elements in list 4 that are common with the elements in list 5 > > list4 = [['1', 'a'],['4', 'd'],['8', 'g']] > list5 = ['1', '2', '3'] > > for j in list4: > for k in list5: > if j[0] == k: > print j[1] > > Result: a > > I would like to do the same thing starting with following lists, where > the numbers in list 5 are without ''. Is there a way to convert > integers in a list to integers in '' ? This is based on a situation > where I want to find common numbers between a list and a list of lists > where the numbers in the list are without '' and the numbers in the > list of lists are with '' > > list4 = [['1', 'a'],['4', 'd'],['8', 'g']] > list5 = [1, 2, 3] > > This might be a stupid question, but anyway, thanks for your answer > It is not my first post on this site. In some way it is not possible > to react on the messages that I receive to thank the persons that > react. Anyway, thanks a lot By "integer without ''" you mean integers not embraced by single quotes, right? Actually, '1' is a string, not an integer. If you want to normalize the first elements of all the lists in list4, just use int() to convert them. That is: list4 = [['1', 'a'],['4', 'd'],['8', 'g']] list5 = ['1', '2', '3'] set5 = set(map(int, list5)) list4 = [[int(i[0]), i[1]] for i in list4] for j in list4: if j[0] in set5: print j[1] You can have a try :) From chrisspen at gmail.com Thu Jul 31 00:35:55 2008 From: chrisspen at gmail.com (Chris) Date: Wed, 30 Jul 2008 21:35:55 -0700 (PDT) Subject: Executing Python From Perl Message-ID: <5720e913-e3ce-4ea5-a0a4-b92e53e89682@59g2000hsb.googlegroups.com> I have an old application that has an embedded Perl interpreter exposing an API. However, all the code I have needs to use the API is in Python. What's the easiest way access my Python code from inside Perl? The closest thing I've found is the Inline::Python module (http://search.cpan.org/~neilw/Inline-Python-0.22/Python.pod), but it seems to have died about 6 years ago. From fredrik at pythonware.com Mon Jul 21 03:10:21 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 09:10:21 +0200 Subject: Python Written in C? In-Reply-To: <48841799.5020808@gmail.com> References: <48841799.5020808@gmail.com> Message-ID: Michael Torrie wrote: > giveitawhril2008 at gmail.com wrote: >> I'm not dissing Python, here. Just noting that, if it is written in C, >> that throws a curve at me in trying to balance the value of learning >> Python vs. some other major language. > > Definitely one of the most non-sequitor statements I have ever heard. > Actually your entire post doesn't make much sense. Maybe you are a > brother bot to castropini? or that perl troll making another attempt to add noise to this newsgroup? I'm a bit surprised that he managed to generate this many replies, really. From sk8in_zombi at yahoo.com.au Fri Jul 18 10:27:10 2008 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Fri, 18 Jul 2008 07:27:10 -0700 (PDT) Subject: Help with decorators Message-ID: <947605.33489.qm@web54507.mail.re2.yahoo.com> Hi, I'm using decos for the first time.I want to check the input and then call a function in a class. I'm pasting the code: ??? def check_input_sanity(self,rover_input): ??? ??? '''Check the input from client''' ??? ??? def _check(fn): ??? ??? ??? def _inner(rover_input): ??? ??? ??? ??? if rover_input[0].upper().replace('L','').replace('R').replace('M') == '' and rover_input[1].upper() in ['N','S','E','W']: ??? ??? ??? ??? ??? print 'Input is sane'??? ??? ??? ??? ??? ??? fn() ??? ??? ??? ??? return _inner ??? ??? return _check??? ??? ??? ??? ??? ??? ?? ??? @check_input_sanity([self.origorient,self.direction_str,self.init_loc]) ??? def tell_coord_from_path(self): ??? ??? '''Gives the final co-ordinate and the direction untill it falls off/reaches.''' ??? ??? pdir = self.origorient #Present direction here the vars : self.origorient,self.direction_str,self.init_loc are the ones I would like to check for sanity. But I get an error: Traceback (most recent call last): ? File "tw.py", line 5, in ??? import sys,os,robo ? File "C:\Python25\thought\robo.py", line 30, in ??? class robo_actions(robo): ? File "C:\Python25\thought\robo.py", line 58, in robo_actions ??? @check_input_sanity([self.origorient,self.direction_str,self.init_loc]) NameError: name 'self' is not defined Why is this so? aren't they to be referred to by self with in a class as they are attributes of the object ? " life isn't heavy enough,it flies away and floats far above action" Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: From robnhood007 at yahoo.com Thu Jul 17 14:45:25 2008 From: robnhood007 at yahoo.com (robnhood00) Date: Thu, 17 Jul 2008 11:45:25 -0700 (PDT) Subject: Need Python Programmer (preferentially in Los Angeles) References: Message-ID: Fair enough. All details of the project will be disclosed so a proper bid can be put in place. I just need an experienced Python Programmer and I'll put you in direct contact with the client and I won't even take a referral fee. I just want the project completed. Thanks again, Rob On Jul 16, 6:01?am, Scott David Daniels wrote: > robnhood00 wrote: > > I need apythonprogrammer that can integrate graphics into an > > existingpythonapplication. ?The application is a basic application > > and the job should be pretty easy for an experiencedPython > > programmer. ?Los Angeles programmer is preferred but this can > > obviously be done from anywhere. > > Please contact me at robnhood... at yahoo.com is you can help me. > > Thank you. > > I get worried when I hear people tell me that a job they don't know > how to do "should be pretty easy," but at least it is better than > "should only take a week." ?What I'd rather hear is, "seems like it > is a simple job." > > Beware of customers who know something will take little effort > without being able to characterize that effort. > > --Scott David Daniels > Scott.Dani... at Acm.Org From larry.bates at websafe.com` Sat Jul 12 15:18:34 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 12 Jul 2008 14:18:34 -0500 Subject: Beginner Question : Iterators and zip In-Reply-To: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> References: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> Message-ID: <4qCdnURK6q4XnuTVnZ2dnUVZ_vzinZ2d@comcast.com> moogyd at yahoo.co.uk wrote: > Hi group, > > I have a basic question on the zip built in function. > > I am writing a simple text file comparison script, that compares line > by line and character by character. The output is the original file, > with an X in place of any characters that are different. > > I have managed a solution for a fixed (3) number of files, but I want > a solution of any number of input files. > > The outline of my solution: > > for vec in zip(vec_list[0],vec_list[1],vec_list[2]): > res = '' > for entry in zip(vec[0],vec[1],vec[2]): > if len(set(entry)) > 1: > res = res+'X' > else: > res = res+entry[0] > outfile.write(res) > > So vec is a tuple containing a line from each file, and then entry is > a tuple containg a character from each line. > > 2 questions > 1) What is the general solution. Using zip in this way looks wrong. Is > there another function that does what I want > 2) I am using set to remove any repeated characters. Is there a > "better" way ? > > Any other comments/suggestions appreciated. > > Thanks, > > Steven > > > > > You should take a look at Python's difflib library. I probably already does what you are attempting to "re-invent". -Larry From mrkafk at gmail.com Mon Jul 21 12:12:54 2008 From: mrkafk at gmail.com (mk) Date: Mon, 21 Jul 2008 18:12:54 +0200 Subject: Python Written in C? In-Reply-To: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> Message-ID: > Who cares what language a language is written in as long as you can be > productive - which you certainly can be in Python. Seriously, though, would there be any advantage in re-implementing Python in e.g. C++? Not that current implementation is bad, anything but, but if you're not careful, the fact that lists are implemented as C arrays can bite your rear from time to time (it recently bit mine while using lxml). Suppose C++ re-implementation used some other data structure (like linked list, possibly with twists like having an array containing pointers to 1st linked list elements to speed lookups up), which would be a bit slower on average perhaps, but it would behave better re deletion? From ojeeves at gmail.com Fri Jul 18 12:29:10 2008 From: ojeeves at gmail.com (oj) Date: Fri, 18 Jul 2008 09:29:10 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> Message-ID: <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> > > > Why not just use * instead of + like: > > > if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of > > string; $ means end of string > > ? ?print "Invalid" > > > This will *only* print invalid when there is a character other than L, > > R, or M or a empty string. > > Sorry, forget the beginning and ending markers, I just tried it out, it > doesn't work. > use this instead: > > if re.search(r'[^LRM]*', var): > ? ?print "Invalid" No, that's broken. That searches for any number of invalid characters. Even 0, so it ALWAYS matches, no matter what string you give it. My regex worked in the first place, you're complicating it needlessly. The presence of one invalid character makes the string invalid, so why not just search for one? Similarly, there's no need to stick in the beginning and end markers - you're not trying to match the entire string, just find part of it that is invalid. However, I think the sets solution by Scott David Daniels is the most elegant method put forward. From spython01 at gmail.com Tue Jul 22 17:56:45 2008 From: spython01 at gmail.com (Samir) Date: Tue, 22 Jul 2008 14:56:45 -0700 (PDT) Subject: Iterating Through List or Tuple References: Message-ID: <422bf0e3-da8c-42bf-b6da-67111dc8fb2a@2g2000hsn.googlegroups.com> Fredrik, Marc, Larry -- Thank you all for your very fast and informative replies. I had not come across "itertools" in my search. This group is a great resource. Samir From gcmartijn at gmail.com Sat Jul 26 08:54:14 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Sat, 26 Jul 2008 05:54:14 -0700 (PDT) Subject: re.findall(a patern,'function(dsf sdf sdf)') References: <8fc6d72a-cfc5-4e9d-af56-a009a464c6bb@27g2000hsf.googlegroups.com> <2dd5c418-f532-4f50-923e-057a10f01fdd@79g2000hsk.googlegroups.com> Message-ID: <47a011c8-c672-4dd2-b33a-3dde8733770c@l42g2000hsc.googlegroups.com> On 26 jul, 14:25, Fredrik Lundh wrote: > gcmart... at gmail.com wrote: > > - For me its hard to learn the re , I will try to search again at > > google for examples and do some copy past things. > > this might be useful when figuring out how RE:s work: > > ? ? ?http://kodos.sourceforge.net/ > > also, don't forget the following guideline: > > ? ? "Some people, when confronted with a problem, think 'I know, > ? ? I'll use regular expressions.' ? Now they have two problems." > > some advice: > > - Keep the RE:s simple. ?You can often simplify things a lot by doing > multiple searches, or even by applying a second RE on the results from > the first. ?In this case, you could use one RE to search for BlaObject, > and then use another one to extract the first argument. > > - Ordinary string methods (e.g. find, partition, split) are often a very > capable alternative (in combination with simple RE:s). ?In your case, > for JavaScript code that's as regular as the one in your example, you > can split the string on "BlaObject(" and then use partition to strip off > the first argument. > > - only use RE:s to read specialized file formats if you know exactly > what you're doing; there's often a ready-made library that does it much > better. > > - The regular expression machinery is not a parser. ?You cannot handle > all possible syntaxes with it, so don't even try. > > Thanks for the info, I will download that program later so I can build a re (i hope) Because I can't wait for that re, I have made a non re solution what is working for now. for a in bla.split(): if a.find('BlaObject')<>-1: print a[11:].replace("'","").replace('"',"").replace(",","") (I know this is not the best way, but it helps me for now) From ggpolo at gmail.com Mon Jul 28 18:38:24 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 28 Jul 2008 19:38:24 -0300 Subject: Is it allowed to use function results as default arguments ? In-Reply-To: <488E2BF1.8020003@gmail.com> References: <488E2BF1.8020003@gmail.com> Message-ID: On Mon, Jul 28, 2008 at 5:28 PM, Stef Mientki wrote: > hello, > > I've a perfect working procedure, > at least as far I've tested it it works perfect. > > But I was just experimenting with inspect, > and saw that the default argument was not parsed correctly. > > So I wonder if this is allowed: > > def Get_Relative_Path ( target, base=os.curdir ) : > ... > > As inspect returns the following: > > (['target', 'base'], None, None, ('.',)) Are you referring to the last item in the tuple above ? It is merely listing the default values, it is not associating target to '.'. What else would the tuple be if there is just base with a default value ? > > thanks, > Stef Mientki > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From rNOSPAMon at flownet.com Fri Jul 4 03:17:14 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Fri, 04 Jul 2008 00:17:14 -0700 Subject: Parsing MIME-encoded data in an HTTP request References: <4834df8f-2cf8-434c-8c95-ff53024766c8@p25g2000hsf.googlegroups.com> Message-ID: In article <4834df8f-2cf8-434c-8c95-ff53024766c8 at p25g2000hsf.googlegroups.com>, s0suk3 at gmail.com wrote: > On Jul 3, 3:59 pm, Ron Garret wrote: > > I'm writing a little HTTP server and need to parse request content that > > is mime-encoded. All the MIME routines in the Python standard library > > seem to have been subsumed into the email package, which makes this > > operation a little awkward. > > To deal with messages of that kind, I've seen modules such as > 'rfc822', and 'mimetools' (which apparently builds itself from > 'rfc822', so it might be more complete). There's also 'mimetypes', in > case you need to deal with file extensions and their corresponding > MIME media type. >From the mimetools docs: "Deprecated since release 2.3. The email package should be used in preference to the module. This module is present only to maintain backward compatibility." > > > It seems I have to do the following: > > > > 1. Extract the content-length header from the HTTP request and use that > > to read the payload. > > > > 2. Stick some artificial-looking headers onto the beginning of this > > payload to make it look like an email message (including the > > content-type and content-transfer-encoding headers) > > > > 3. Parse the resulting string into a email message > > > > Email? Why does an HTTP server need to build an email message? It shouldn't. That's my whole point. But see the docs excerpt above. > I remember doing things like that some time ago when building an HTTP > server myself (http://code.google.com/p/sws-d/). Incidentally, I > resisted the urge to use much of the Python's library facilities (most > things are done manually; am I a knucklehead or what!? :). You might > wanna take a look to get some ideas. I'd much prefer not to reinvent this particular wheel. rg From semanticist at gmail.com Wed Jul 30 23:21:15 2008 From: semanticist at gmail.com (Miles) Date: Wed, 30 Jul 2008 23:21:15 -0400 Subject: Optimizing size of very large dictionaries In-Reply-To: <1217464179.31710.1266222419@webmail.messagingengine.com> References: <1217464179.31710.1266222419@webmail.messagingengine.com> Message-ID: On Wed, Jul 30, 2008 at 8:29 PM, wrote: > Background: I'm trying to identify duplicate records in very large text > based transaction logs. I'm detecting duplicate records by creating a SHA1 > checksum of each record and using this checksum as a dictionary key. This > works great except for several files whose size is such that their > associated checksum dictionaries are too big for my workstation's 2G of RAM. What are the values of this dictionary? You can save memory by representing the checksums as long integers, if you're currently using strings. -Miles From Bill at SynectixLtd.com Fri Jul 11 04:18:12 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Fri, 11 Jul 2008 09:18:12 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: "Tim Golden" wrote in message news:mailman.256.1215697841.20628.python-list at python.org... > Bill Davy wrote: >> I'm not sure OL2003 can read news. I think perhaps some later OL can >> (added tot he View menu, perhaps?). So I use OL Express to read news. >> The OL with which I wish to communicate is: >> >> Application name Outlook >> Version 11.0 >> Build 8217 >> Product ID 70141-700-0350904-56905 >> Language English (United States) >> Application Path C:\Program Files\Microsoft Office\OFFICE11\ >> System Language English (United Kingdom) >> Mail Support Not Available >> Current folder Inbox >> Current item Not Available > > Where did you get to with this, Bill? I wasn't sure if no news > was good news or whether you'd gone a different way, or > were still trying things... > > TJG Hi Tim, Well, at 5pm last Friday I posted: " I kept looking and thought I was saved when I found Receipe 10.16 in the Python Cookbook but .... I changed the following: self.oOutlookApp = Dispatch("Outlook.Application") #self.oOutlookApp = gencache.EnsureDispatch("Outlook.Application") Because gencache failed and I hade run makepy last week (I only get one day a week to look at this). Then the following failed because (as I found) olFolderContacts is not in any of constants' dictionaries. ofContacts = onMAPI.GetDefaultFolder(constants.olFolderContacts) So, sadly, I shall have to put this aside for another week and get on with some work. Any thoughts would be gratefully accepted. TIA, Bill " and since then have been busy with work, and my other job, and the garden. Now I am back looking at this (and using WInUSB to talk to a Maxim 3421E etc etc but that's another story). So any help today will be much appreciated. Rgds, Bill From sjmachin at lexicon.net Mon Jul 28 20:35:00 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 28 Jul 2008 17:35:00 -0700 (PDT) Subject: seemingly simple list indexing problem References: <488E4170.2020804@islandtraining.com> Message-ID: <83dc4629-7a34-4721-a0fa-d97589c3f571@u12g2000prd.googlegroups.com> Guilherme Polo wrote: > It wasn't supposed to be the fastest solution, also, he didn't mention > duplicated items. He didn't need to. He explicitly said "list" (which permits duplicates) and didn't mention a self-imposed uniqueness constraint. From alexnbryan at gmail.com Fri Jul 11 01:56:10 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Fri, 11 Jul 2008 00:56:10 -0500 Subject: Simple question, how do you tell how many items in a list? Message-ID: <268ac2770807102256o4f41e784q79a0caf849c046b4@mail.gmail.com> I am just wondering how you get an integer value for how many items there are in a list, preferably w/o a for loop. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stesch at no-spoon.de Wed Jul 16 23:41:11 2008 From: stesch at no-spoon.de (Stefan Scholl) Date: Thu, 17 Jul 2008 05:41:11 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> Message-ID: <0T56p3tmInifNv8%stesch@parsec.no-spoon.de> Fredrik Lundh wrote: > Stefan Scholl wrote: > >> Django isn't ready. > > That's a remarkably ignorant statement. The 1.0 release will be in September. -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ From steve at REMOVE-THIS-cybersource.com.au Sun Jul 27 18:54:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Jul 2008 22:54:41 GMT Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <7eabe5a6-357a-4255-a958-0804959ce844@a6g2000prm.googlegroups.com> Message-ID: <009cf838$0$20302$c3e8da3@news.astraweb.com> On Sun, 27 Jul 2008 12:33:16 -0700, Russ P. wrote: > On Jul 27, 1:19 am, Steven D'Aprano cybersource.com.au> wrote: >> On Sat, 26 Jul 2008 17:14:46 -0700, Russ P. wrote: > >> > You take the name down to a single letter. As I suggested in an >> > earlier post on this thread, why not take it down to zero letters? >> >> The question isn't "why not", but "why". The status quo works well as >> it is, even if it isn't perfect. Prove that implicit self is a good >> idea -- or at least prove that it is an idea worth considering. >> >> "I don't like typing self" doesn't convince me. The same argument could >> be made typing parentheses, colons, commas, etc. We could end up with >> something like this: >> >> class Foo base >> def method x y z >> .args = list x y z >> >> That's not necessarily wrong, but it's not Python. > > And what does that have to do with my suggestion? Absolutely nothing. Not at all. You're suggesting a change to Python's syntax. I've suggested a couple more changes to Python syntax. I don't intend them to be taken seriously, but only to illustrate a point that syntax defines how a language is written. You want to change that. > It's a red herring that you seem to be using to obscure the fact that > you have no rational argument to make. I don't have to make a rational argument for keeping the status quo. That status quo just *is*. You want people to change, you need to convince them that such a change is not just "not bad" but a serious advantage, enough to make up for all the work required to implement it. I'm listening. Tell me why removing self if not merely harmless, but actively better. [...] >> By "better" do you mean "uglier"? If so, I agree with you. If not, then >> I disagree that it is better. > > You seem to be freaked out by an empty argument. Actually, it bothers me > a bit too, which is why I suggested that a period could be used as the > first argument to indicate that, like Clint Eastwood in The Good, the > Bad, and the Ugly, "self" had no name here. Well there you go now. How should we *talk* about this piece of code? Try writing a comment or docstring, or even sitting down with a fellow programmer and discussing it. What do you call this implicit Object With No Name? def fun( , cat): .cat = cat # assumes that the Object With No Name has foo versus def fun(self, cat): self.cat = cat # assumes that self has foo Before you suggest that people will continue to call the first argument "self" but just not write it down anywhere, I suggest that's a terrible idea and one which will confuse a lot of people. "Where's this 'self' defined? I can't find it anywhere!" A slightly better suggestion is "the instance", but that fails here: class C(object): def method(, other): assert isinstance(other, C) .cat = other # assumes that the instance has foo # er, that is to say, the implicit instance, # not the other instance The ability to talk easily about the code is invaluable. Implicit self makes it harder to talk about the code. [...] >> Even uglier than the first. Convince me there's a benefit. > > Actually, I think it's elegant. And I'll bet that if Guido had suggested > it, you would think it was beautiful. Oh please. I think the syntax for ternary if is ugly, and Guido came up with that, and it doesn't even use punctuation. > Why force a name to be used when none is needed? But a name is needed. class Foo(base1, base2, base3): def meth(self, arg): super(Foo, self).meth(arg) print self try: value = _cache[self] except KeyError: value = some_long_calculation(self) How do you pass self to arbitrary functions without a name? -- Steven From dthole at gmail.com Wed Jul 2 09:21:34 2008 From: dthole at gmail.com (TheDarkTrumpet) Date: Wed, 2 Jul 2008 06:21:34 -0700 (PDT) Subject: How do web templates separate content and logic? References: <486510f7$0$3007$c3e8da3@news.astraweb.com> <4866ff46$0$7333$607ed4bc@cv.net> <4868f46d$0$24451$426a74cc@news.free.fr> <87vdzpmxv3.fsf@internal.daycos.com> Message-ID: Another thing I'd like to add on this subject. I agree with others here that having logic in the view isn't really a bad thing. I used to think it did, but now I don't think it does as much. I feel that when you're separating out the view, you're giving really non-programmers the ability to actually do the content. That doesn't mean that non-programmers can't learn very very basic programming logic. Take, for example, the Django code. The Django template system is a very watered down version of a language. It supports very basic stuff, and I feel that really anyone can pick up on it. By totally separating out the logic, and using tags, you're adding a lot of overhead in my opinion. It's another file that needs to be included, and the logic of how it's displayed on the page is then split a bit - between the developer and the designer. If the designer feels that they want only 5 products to show on one page, they should be able to change it. THis is how I feel on the whole idea anyways. From waldemar.rymarkiewicz at gmail.com Fri Jul 25 04:06:32 2008 From: waldemar.rymarkiewicz at gmail.com (waldek) Date: Fri, 25 Jul 2008 01:06:32 -0700 (PDT) Subject: ctypes and reading value under pointer passed as param of a callback References: <6erjpeF88slmU1@mid.individual.net> Message-ID: On Jul 24, 5:01 pm, Thomas Heller wrote: > waldekschrieb: > > > Hi, > > > I'm using C dll with py module and wanna read value (buffer of bytes) > > returned in py callback as parameter passed to dll function. > > The callback receives a pointer instance. You can dereference the pointer > to read individual bytes in this way: > print data[0], data[5], data[42] > or use slicing to read a bunch of bytes: > print data[0:42] > > So, you probably want something like this: > > > -------------------------------------------------- > > def mycallback(data, size): > > # how to read data buffer here ? > > print data[:size] > > > return 0 > > > cbfunc = CFUNCTYPE(c_int, POINTER(c_uint8), c_int) > > > mydll = cdll.somedll > > mdll.foo(cbfunct) > > --------------------------------------------------------------- > > > Question: How to get bytes from the buffer passed to mycallback ??? > > Let's assume that the buffer consist of 4 bytes 4 bytes 8 bytes. > > > I tried unpack("ii8s", data[0]) and nothing. I tried different ctypes > > passed to callback and nothing. > > Thomas Cool, works fine now. ... and how to convert a list of bytes to py string or int ?? i.e data[:4] -> py int data[4:8] -> py int data[8:] -> py strng I tried unpack and unpack_from but the buff should be an string or buffer not a list of bytes as data is. any suggestions? From toby at tobiah.org Wed Jul 30 15:42:42 2008 From: toby at tobiah.org (Tobiah) Date: Wed, 30 Jul 2008 12:42:42 -0700 Subject: How do I include a shell variable in my script? References: Message-ID: On Tue, 29 Jul 2008 07:53:53 -0700, laredotornado wrote: > Hi, > > I'm running a Python script on a Solaris 9 machine, invoking the > Python script from ksh, if that matters. There is an enviornment > variable, $JAVA_HOME, that I would like to include in my script, > replacing "/path/to/java/home'" with the value of $JAVA_HOME. > > java_home='/path/to/java/home' > > How do I do this? If I need to pass a command line argument, so be > it, but I figure there is a more direct way to get the value. > > Thanks, - Dave import os java_home = os.environ['JAVA_HOME'] ** Posted from http://www.teranews.com ** From stefan_ml at behnel.de Tue Jul 29 16:26:41 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 29 Jul 2008 22:26:41 +0200 Subject: SWIG and char* newb questions :) In-Reply-To: <7ec26fb6-3d6a-4e1b-b2c9-a0a254780153@26g2000hsk.googlegroups.com> References: <7ec26fb6-3d6a-4e1b-b2c9-a0a254780153@26g2000hsk.googlegroups.com> Message-ID: <488f7d01$0$1071$9b4e6d93@newsspool3.arcor-online.net> code_berzerker wrote: > Hi i'm relatively new to Python and my C/C++ knowledge is near to > None. Having said that I feel justified to ask stupid questions :) Have you considered using Cython? It's almost Python, but it compiles to C code for a Python extension module and even lets you call C functions directly from your code. http://cython.org/ Stefan From google at mrabarnett.plus.com Sun Jul 13 20:14:23 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 13 Jul 2008 17:14:23 -0700 (PDT) Subject: Using Groups inside Braces with Regular Expressions References: <10284e46-1601-4269-a1a0-ef3831e9f85c@z66g2000hsc.googlegroups.com> Message-ID: <87e2b1a0-e732-42d3-aa94-061dcd81d35c@z72g2000hsb.googlegroups.com> On Jul 14, 12:05?am, Chris wrote: > I'm trying to delimit ?sentences in a block of text by defining the > end-of-sentence marker as a period followed by a space followed by an > uppercase letter or end-of-string. > > I'd imagine the regex for that would look something like: > [^(?:[A-Z]|$)]\.\s+(?=[A-Z]|$) > > However, Python keeps giving me an "unbalanced parenthesis" error for > the [^] part. If this isn't valid regex syntax, how else would I match > a block of text that doesn't the delimiter pattern? > What is the [^(?:[A-Z]|$)] part meant to be doing? Is it meant to be matching everything up to the end of the sentence? [...] is a character class, so Python is parsing the character class as: [^(?:[A-Z]|$)] ^^^^^^^^^^ From wiggly at wiggly.org Thu Jul 31 07:21:55 2008 From: wiggly at wiggly.org (Nigel Rantor) Date: Thu, 31 Jul 2008 12:21:55 +0100 Subject: Terminate a python script from linux shell / bash script In-Reply-To: References: Message-ID: <4891A053.1080003@wiggly.org> Gros Bedo wrote: > Thank you guys for your help. My problem is that I project to use this command to terminate a script when uninstalling the software, so I can't store the PID. This command will be integrated in the spec file of the RPM package. Here's the script I'll use, it may help someone else: > > #!/bin/sh > # PYTHON SCRIPT PROCESS KILLER by GBO v0.1 > # This script will look for all the lines containing $SOFTWARENAME in the process list, and close them > > SOFTWARENAME='yoursoftware' #This is case insensitive > JOBPRESENT=$(ps -ef | grep -i $SOFTWARENAME | grep -v grep) > echo $JOBPRESENT > ps -ef | grep -i $SOFTWARENAME | grep -v grep | awk '{print $2}' | xargs kill If you have a long running process you wish to be able to kill at a later date the normal way of doing it would be for the script itself to write it's own PID to a file that you can then inspect from a different process and use to kill it. So, my_daemon.py might shove its PID into /var/run/my_daemon.pid And later my_daemon_killer.py (or indeed my_daemon_killer.sh) would read the PID out of /var/run/my_daemon.pid and pass that to a kill command. Using ps/grep in the way you're trying to do is always going to be inexact and people will not thank you for killing processes they wanted running. n From bronger at physik.rwth-aachen.de Sat Jul 26 11:22:55 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 26 Jul 2008 17:22:55 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <2b74a8a8-e1fe-4ddd-862d-033d77f57535@a70g2000hsh.googlegroups.com> Message-ID: <874p6cacvk.fsf@physik.rwth-aachen.de> Hall?chen! Kay Schluehr writes: > On 26 Jul., 09:45, Torsten Bronger > wrote: >> >> Terry Reedy writes: >> >>> [...] >>> >>> Or the proposal would have to be that 'self' is mandatory for >>> all programmers in all languages. I think *that* would be >>> pernicious. People are now free to write the more compact 's.sum >>> = s.a + s.b + s.c' if they want instead of the 'self' version. >>> And again, not everyone writes in English. >> >> Of course, "self" would have to become a reserved word. > > ?? > > This is an extra requirement. Why do you want to make 'self' a > keyword? How could one determine which other identifier must be inserted into the method's signature? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From nightdreams143 at gmail.com Sat Jul 26 04:50:05 2008 From: nightdreams143 at gmail.com (Enjoy) Date: Sat, 26 Jul 2008 01:50:05 -0700 (PDT) Subject: Just click and Enjoy the latest Shreya and Asin Message-ID: Just click and Enjoy the latest Shreya and Asin SEXY photes also your favorite Heroines............... ############################ http://lovegroup341.blogspot.com/ ############################# ENJOY each moments From laiyijia at yahoo.ca Mon Jul 28 09:27:31 2008 From: laiyijia at yahoo.ca (Harry) Date: Mon, 28 Jul 2008 13:27:31 -0000 Subject: Python FTP - NameError: name 'mydpa' is not defined Message-ID: Hi there. I am trying to download a file(sn.last) from a public FTP server with the following code: from ftplib import FTP ftp=FTP('tgftp.nws.noaa.gov') ftp.login() ftp.cwd('SL.us008001/DF.of/DC.radar/DS.81dpr/SI.kbuf') ftp.retrbinar('RETR sn.last', open(mydpa,'wb').write) ftp.quit() but got an error message, which I think is normal: Traceback (most recent call last): File "", line 1, in ftp.retrbinary('RETR sn.last', open(mydpa,'wb').write) NameError: name 'mydpa' is not defined I don't know much about python, but just try to use the code to download data. I don't know where the file will be saved to. Is the mydata a file name or a folder name? where will it be saved to even if it's working? Please help be fixed the problem step by step? I am using 2.5.2 by the way. I really appreciate your help. Thanks. From pythonnutter at gmail.com Sat Jul 19 23:33:36 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Sun, 20 Jul 2008 13:33:36 +1000 Subject: Any Game Developers here? In-Reply-To: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: I used to use PyGame but the horrible delay waiting for OS X binaries put me off. I now use Pyglet extensively, and combine Pyglet + Rabbyt to get amazing sprite handling speeds. Pyglet/Rabbyt make use of OpenGL which comes installed on all the major systems out there. PyGame requires the installation of the SDL library to work so is a lot larger installation requirement. There are two books I know of currently in print on game programming, both use PyGame as it was out first. One book is horrible and only worth for cleaning yourself up after you use the bathroom. The second is really well written (The L express game programming book) and highly recommended if you need to get some basic game design and programming under your belt in Python. That said its stupidly easy to port examples to work on Pyglet/Rabbyt so you won't do yourself a dis-service if you want to buy the book but want to develop later in Pyglet/Rabbyt. Cheers, PN P.S. Since you've likely found Pyglet and PyGame already, the only other reference URL you need is for Rabbyt so go here for that: http://matthewmarshall.org/projects/rabbyt/ 2008/7/19 Michael Lubker : > Any people that use Python as the predominant language for their game > development here? > > ~Michael > -- > http://mail.python.org/mailman/listinfo/python-list > From alexnbryan at gmail.com Thu Jul 17 03:07:40 2008 From: alexnbryan at gmail.com (Alexnb) Date: Thu, 17 Jul 2008 00:07:40 -0700 (PDT) Subject: Getting a unknown word out of a list with no spaces Message-ID: <18502758.post@talk.nabble.com> Hello Lets say I have a string: --a href="/browse/brick"--brick--/a-- The -- needs to be replaced with < or > where applicable. and I want the "brick" out of that string (the second brick that is). How can I get just the "brick" out of that string? -- View this message in context: http://www.nabble.com/Getting-a-unknown-word-out-of-a-list-with-no-spaces-tp18502758p18502758.html Sent from the Python - python-list mailing list archive at Nabble.com. From larry.bates at websafe.com` Thu Jul 3 16:14:36 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 03 Jul 2008 15:14:36 -0500 Subject: Instance Names In-Reply-To: References: Message-ID: Tim Cook wrote: > On Thu, 2008-07-03 at 14:20 -0500, Larry Bates wrote: > >> I suspect there is some "misunderstanding" here. Why exactly do you think you >> need to have your instances named with [] characters in them? >> > > I often misunderstand. :-) > > But, I am implementing specifications in Python that are already > implemented in other languages. > > http://www.openehr.org/releases/1.0.1/roadmap.html > > These specifications say that an archetype node id consists of > identifiers like [at0000] and [at0001]. Now these are valid URIs and > the associated query language (AQL) used by other services will send > queries with those characters in them. > > For example: > FROM EHR [ehr_id/value=$ehrUid] CONTAINS COMPOSITION > [openEHR-EHR-COMPOSITION.encounter.v1] > CONTAINS OBSERVATION obs [openEHR-EHR-OBSERVATION.blood_pressure.v1] > WHERE > obs/data[at0001]/events[at0006]/data[at0003]/items[at0004]/value/value >> = 140 > > Since I am also using Zope3 it would be easier on me to name the > instances with those characters. > > But my fall back is to set at0000.__name__='[at0000]' and manipulate the > query to match __name__ instead of the actual instance ID. > > Thoughts? > > --Tim > > > If these will be class attributes, I believe you can use setattr() setattr('[at0000]') = ... obj = getattr(self, '[at0000]') -Larry From giltay at gmail.com Wed Jul 30 09:31:28 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Wed, 30 Jul 2008 06:31:28 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <2ac250ee-131d-44a3-9b0a-f2fb34758147@c65g2000hsa.googlegroups.com> Message-ID: <25f024b4-1b0c-4265-bc30-24431ebbe079@z72g2000hsb.googlegroups.com> On Jul 30, 5:09?am, Maric Michaud wrote: > Le Tuesday 29 July 2008 23:48:31 gil... at gmail.com, vous avez ?crit?: > > def print_members(iterable): > > ? ? if not iterable: > > ? ? ? ? print '' > > ? ? ? ? return > > ? ? print '' > > ? ? for item in iterable: > > ? ? ? ? print '%s' % item > > ? ? print '' > > But iterables can have no notion of emptiness too : > > >>>[25]: print_members((e for e in range(0))) > > > Ack! Maybe I meant "container" rather than "iterable". Or maybe I'd be wrong on that count, too. Other people have come up with better examples, so I won't try to fix my hasty code (although I'll keep that in mind if I have to write a custom XML writer). > > class Signal: > > ? ? [...] > > ? ? def dc_offset(self, amount): > > ? ? ? ? if amount == 0: > > ? ? ? ? ? ? return > > ? ? ? ? self.samples = [sample + amount for sample in self.samples] > > This function is also wrong assuming that because amount compare to zero, it > can be added to sample. Not quite. I'm assuming that if amount equals 0, then amount is some scalar. In fact, only if that comparison fails will I get my exception: since [] != 0, it will then try to add sample + [], which will raise TypeError. > If you want to make type checking just check the type or convert your > parameter to an int, but the test "== 0" is of no help here. I'm not going for type checking here because I want Signal to support int and float samples (and numpy.int16, &c.). > The only valuable point I see for this idiom is to make more explicit I am > testing a numerical value. That's one of the reasons I wrote it that way. Signal has other methods that take lists (like mix and envelope), which I could get confused with the ones that take scalars (offset and change volume). Cheers, Geoff G-T From israelu at elbit.co.il Tue Jul 29 06:04:58 2008 From: israelu at elbit.co.il (iu2) Date: Tue, 29 Jul 2008 03:04:58 -0700 (PDT) Subject: block/lambda References: <0406eb4f-8dec-4ce2-b506-8e597de2958d@56g2000hsm.googlegroups.com> Message-ID: On Jul 29, 9:36?am, Duncan Booth wrote: > iu2 wrote: > > Is it possible to grant Python another syntactic mark, similar to > > triple quotes, that will actually make the enclosed code a compiled > > code, or an anonymous function? > > Yes, the syntactic mark you are looking for is 'def'. > > Your example becomes: > > >>> def dotimes(n, callable): > > ? ? ? ? for i in range(n): callable(i) > > >>> def block(i): > > ? ? ? ? for j in range(i): > ? ? ? ? ? ? ? ? print j, > ? ? ? ? print > > >>> dotimes(5, block) > > 0 > 0 1 > 0 1 2 > 0 1 2 3 > > The only thing you asked for that this doesn't do is make 'block' > anonymous, but actually that is a good thing. > > -- > Duncan Boothhttp://kupuguy.blogspot.com Ok, I've got 2 questions about it: 1. Can you please explain why it is a good thing? 2. Will it be possible in Python 3.0 to do the following: >>> def dotimes(n, callable): for i in range(n): callable() >>> def block(): nonlocal i for j in range(i): print j, print Thanks From vlastimil.brom at gmail.com Sat Jul 26 16:13:46 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sat, 26 Jul 2008 22:13:46 +0200 Subject: wx.Timer not working In-Reply-To: <7a2a1c54-6d74-475c-9566-4d94cb5b5962@a3g2000prm.googlegroups.com> References: <7a2a1c54-6d74-475c-9566-4d94cb5b5962@a3g2000prm.googlegroups.com> Message-ID: <9fdb569a0807261313h7dc90182h8da9b7fff58d7cc6@mail.gmail.com> 2008/7/26 <5lvqbwl02 at sneakemail.com> > Windows XP SP3 > Python 2.5 > wx.version() = '2.8.1.1 (msw-unicode)' > ------ > I have written the following *simplest* implementation of wx.timer I > can think of. No workie. I want an exception, a print statement, or > something. > > The wxpython demos all work, but for some reason this isn't. The > demos are simple and straghtforward, so I think I understand how it > should work. Clues please? I've tried variations of ID's, SetOwners, > using and redefining Notify(), Bind, Connect, etc. In the cases where > the interpreter doesn't complain about passed argument types, the > callback function is never called. > > > import wx > > class MyFrame(wx.Frame): > def __init__(self, parent, id, title): > wx.Frame.__init__(self, parent, id, title, pos=(100, > 100)) > > timer = wx.Timer(self, -1) > self.Bind(wx.EVT_TIMER, self.OnTick, timer) > timer.Start(100) > > def OnTick(self, event): > print 'Hi. Bye.' > 1/0 #<-- should crash as evidence callback is being called > > class MyApp(wx.App): > def OnInit(self): > frame1 = MyFrame(None, wx.ID_ANY, "This is a test") > frame1.Show(True) > return True > > app = MyApp(0) > app.MainLoop() > > > Thanks for any advice!! > > Michael > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, not exactly sure, but compared to the demo, it seems to be a binding problem; Using "self.timer" instead of "timer" in the __init__ section and self.Bind(wx.EVT_TIMER, self.OnTick) instead of self.Bind(wx.EVT_TIMER, self.OnTick, timer) seems to work; HTH, Vlasta -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun Jul 27 04:19:17 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Jul 2008 08:19:17 GMT Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <009c2b11$0$20302$c3e8da3@news.astraweb.com> On Sat, 26 Jul 2008 17:14:46 -0700, Russ P. wrote: > On Jul 26, 2:25 pm, Terry Reedy >> There is a lot of code you have not seen. Really. In informal code I >> use 's' and 'o' for 'self' and 'other'. I don't usually post such >> because it is not considered polite. So you have seen a biased sample >> of the universe. > > You take the name down to a single letter. As I suggested in an earlier > post on this thread, why not take it down to zero letters? The question isn't "why not", but "why". The status quo works well as it is, even if it isn't perfect. Prove that implicit self is a good idea -- or at least prove that it is an idea worth considering. "I don't like typing self" doesn't convince me. The same argument could be made typing parentheses, colons, commas, etc. We could end up with something like this: class Foo base def method x y z .args = list x y z That's not necessarily wrong, but it's not Python. It's not enough to show that a change "isn't bad" -- you have to show that it is actively good. Why should Python make any changes to the current explicit self without a clear and solid reason to change? > You could if Python accepted something like > > class Whatever: > > def fun( , cat): > > .cat = cat > > This is even better than the single-character name, By "better" do you mean "uglier"? If so, I agree with you. If not, then I disagree that it is better. > not only because it > is shorter, but also because there is no question that you are referring > to "self." No need to look back at the method signature to verify that. "Don't need to look at the method signature" is not an argument in favour of implicit self. You don't need to look at the method signature when you're using an explicit self either. What happens with class-methods? With the cls (or if you prefer klass) convention, it is simple to tell what object I am referring to. Now I have to go back to the method signature to see if it is a class method or instance method, instead of just looking at the explicit name. > For those who don't like the way the empty first argument looks, maybe > something like this could be allowed: > > def fun( ., cat): Even uglier than the first. Convince me there's a benefit. -- Steven From iainking at gmail.com Tue Jul 8 09:54:33 2008 From: iainking at gmail.com (Iain King) Date: Tue, 8 Jul 2008 06:54:33 -0700 (PDT) Subject: How to make python scripts .py executable, not bring up editor References: Message-ID: On Jul 7, 10:56?pm, korean_dave wrote: > From command Prompt, i type in a script, ?"tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? find a .py file in windows explorer. Right click it->Open With- >Choose Program... Now find your python.exe file (should be in c:\python24), select it, and tick the box that says "Always use the selected program" Iain From norseman at hughes.net Fri Jul 18 17:51:32 2008 From: norseman at hughes.net (norseman) Date: Fri, 18 Jul 2008 14:51:32 -0700 Subject: Importing different versions of a module In-Reply-To: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> References: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> Message-ID: <48811064.5010603@hughes.net> mercado mercado wrote: > I have two versions of a script on my machine. One version is for new > development and the other version is a production version. This script > imports a module from a different directory, and this module again has two > versions (a development version and a production version). What I want is > for the development script to import the development module, and the > production script to import the production module, without making any > changes to the code in the script. > > For example, suppose the development script is in ~/dev/rss.py, and the > production script is in ~/prod/rss.py. I want the dev version to import > /usr/lib/python2.5/site-packages/lib_dev/parse.py, and the prod version to > import usr/lib/python2.5/site-packages/lib_prod/parse.py. > > My first instinct was to place a .pth file in ~/dev that points to > /usr/lib/python2.5/site-packages/lib_dev, and a .pth file in ~/prod that > points to /usr/lib/python2.5/site-packages/lib_prod, but it seems that > site.py doesn't look at .pth files in the current working directory. My > next attempt was to create a symbolic link in ~/dev called parse.py, > pointing to /usr/lib/python2.5/site-packages/lib_dev/parse.py, and a > symbolic link in ~/prod called parse.py, pointing to > /usr/lib/python2.5/site-packages/lib_prod/parse.py, but that didn't work > either. > > Can anybody suggest a way to achieve my goal? Thanks in advance. > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list ========================================================== Yes, but you may not like it. I do what you do. Prod and devel subdirs. I store the paths in a var at the top of my programs. I change it(them) when the program graduates. example: #!/usr/local.... . . DvlpPATH=...... #usually a full hardcoded path ending with a '/' #FnlPATH=..... . . PATH2USE=DvlpPATH #which gets changed to FnlPATH when graduating # I keep the DvlpPATH until I'm positive I'm not # going to send it back to school x= os.open(PATH2USE+"pgm_or_file.ext", 'r+b') and so forth If the there is a need, I'll hardcode to a branch point and create sub branch vars as needed and chain as needed. company_one + accounting + payables + vendors + inventory + shelf + vendors + real_property + locations company_two + (same as above) you get the idea YES! You do have to change the code. But in one place only once you are correctly set. Steve norseman at hughesnet From mail at timgolden.me.uk Mon Jul 14 07:18:53 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 14 Jul 2008 12:18:53 +0100 Subject: About wmi In-Reply-To: <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> Message-ID: <487B361D.1070503@timgolden.me.uk> Larry Bates wrote: > patrol wrote: >> I want to prevent some process from running. The code is in the >> following. I encounter some unexpected troubles. >> Probelm1: This program cannot terminate "scrcons.exe" and >> "FNPLicensingService.exe",which are system processes. >> Problem2:After a while, this program will abort by error >> File "C:\Python25\lib\wmi.py", line 397, in __call__ >> handle_com_error (error_info) >> File "C:\Python25\lib\wmi.py", line 190, in handle_com_error raise >> x_wmi, "\n".join (exception_string) >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position >> 14: ordinal not in range(128) [... snip code ...] > You should probably post this to comp.python.windows. Tim Golden > (author of WMI interface) monitors that list religously (thanks Tim). Actually, I follow this one pretty much, too. I've just been a bit busy these last few days. And still am, so this answer will be short :) 1) I'm not sure if WMI can be forced to close down system processes, but if it can it's probably by means of specifying one or more privileges when you connect. Try looking in the WMI newsgroups for a more general (non-Python) answer to this and I'll happily explain how to apply it in a Python context. 2) I can't quite see from this traceback where the problem arises. Have you snipped the traceback at all, or was that all there was? Can you narrow the thing down to a short snippet of code which I'm likely to be able to run independently, please? Sorry for the haste. TJG From maric at aristote.info Mon Jul 28 14:30:34 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 28 Jul 2008 20:30:34 +0200 Subject: Where is the correct round() method? Use math.ceil In-Reply-To: <98aab64d0807271735w111f6ec7w81c9e65f99744199@mail.gmail.com> References: <98aab64d0807271735w111f6ec7w81c9e65f99744199@mail.gmail.com> Message-ID: <200807282030.34568.maric@aristote.info> Le Monday 28 July 2008 02:35:08 Herman, vous avez ?crit?: > Where is the correct round() method? > Hello, > > I need a round function that _always_ rounds to the higher integer if > the argument is equidistant between two integers. In Python 3.0, this > is not the advertised behavior of the built-in function round() as > > seen below: > >>> round(0.5) > > 0 > > >>> round(1.5) > > 2 > > >>> round(2.5) > > 2 Hmm, I don't have the same result in python2.6, I suspect it's a floating point precision problem, try just to type "0.5" in the console to see the exact representation of this value on your system, it may be just over or just down by a small quantity. On mine with 2.6 this typically give : >>>[26]: 0.5 ...[26]: 0.5 >>>[27]: 0.49 ...[27]: 0.48999999999999999 >>>[29]: 0.51 ...[29]: 0.51000000000000001 >>>[28]: 1.1 ...[28]: 1.1000000000000001 >>>[35]: round(0.5) ...[35]: 1.0 -- _____________ Maric Michaud From kris at FreeBSD.org Thu Jul 10 06:21:31 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Thu, 10 Jul 2008 12:21:31 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <750f823a-f9de-4f81-9eb3-7c7b39237c90@y38g2000hsy.googlegroups.com> Message-ID: <4875E2AB.3020902@FreeBSD.org> John Machin wrote: > Uh-huh ... try this, then: > > http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ > > You could use this to find the "Str" cases and the prefixes of the > "re" cases (which seem to be no more complicated than 'foo.*bar.*zot') > and use something slower like Python's re to search the remainder of > the line for 'bar.*zot'. If it was just strings, then sure...with regexps it might be possible to make it work, but it doesn't sound particularly maintainable. I will stick with my shell script until python gets a regexp engine of equivalent performance. Kris From pavlovevidence at gmail.com Tue Jul 29 13:42:50 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 10:42:50 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> On Jul 29, 11:12 am, Matthew Fitzgibbons wrote: > Carl Banks wrote: > > On Jul 28, 8:15 pm, Steven D'Aprano > cybersource.com.au> wrote: > >> On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: > >>> On Jul 28, 10:00 am, Steven D'Aprano >>> cybersource.com.au> wrote: > >>>> Cutting to the crux of the discussion... > >>>> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: > >>>>> I want something where "if x" will do but a simple explicit test > >>>>> won't. > >>>> Explicit tests aren't simple unless you know what type x is. If x could > >>>> be of any type, you can't write a simple test. Does x have a length? Is > >>>> it a number? Maybe it's a fixed-length circular length, and the length > >>>> is non-zero even when it's empty? Who knows? How many cases do you need > >>>> to consider? > >>> Use case, please. I'm asking for code, not arguments. Please give me a > >>> piece of code where you can write "if x" that works but a simple > >>> explicit test won't. > >> I gave you a piece of code, actual code from one of my own projects. If > >> you wouldn't accept that evidence then, why would you accept it now? > > > I would accept as "evidence" something that satisfies my criteria, > > which your example did not: it could have easily (and more robustly) > > been written with a simple explicit test. I am looking for one that > > can't. > > > You keep bringing up this notion of "more complex with no benefit", > > which I'm simply not interested in talking about that at this time, > > and I won't respond to any of your points. I am seeking the answer to > > one question: whether "if x" can usefully do something a simple > > explicit test can't. Everyone already knows that "if x" requires > > fewer keystrokes and parses to fewer nodes. > > > Carl Banks > > -- > >http://mail.python.org/mailman/listinfo/python-list > > My use case involves a DAG of filters that pass data (of a variety of > types--filters just pass on data types they don't understand) between > them. I can also drop out of the filter chain at any point, using > critera determined by the filters. These criteria, you guessed it, are > bound to __nonzero__ in the filter and I determine whether or not to > continue through the graph using "if x". You can't code explicit tests > if you don't know what the tests even are beforehand. Also, I wanted to > support builtins (ints and lists in particular) because they can be > meaningful inputs to filters. Finally, as I add more filters and data > types, I don't want to go back and mess with the code that decides > whether or not to break out of the graph. Much like in Steven D'Aprano's example, still the only actual code snippet I've seen, it seems that this can easily be done with a simple explicit test by having all no-advance filters return None and testing with "if x is not None". So it doesn't pass my criterion of being not replaceable with simple explicit test. Maybe that's not workable for some reason. Perhaps if you'd post a code example that shows this, rather than just talking about it, you might be more persuasive. Carl Banks From deets at nospam.web.de Mon Jul 28 08:16:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 14:16:06 +0200 Subject: Module clarification References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> Message-ID: <6f5rm7F89muqU1@mid.uni-berlin.de> Hussein B wrote: > Hi. > I'm a Java guy and I'm playing around Python these days... > In Java, we organize our classes into packages and then jarring the > packages into JAR files. > What are modules in Python? > What is the equivalent of modules in Java? Read the docs: http://docs.python.org/tut/node8.html And read about eggs, the jars of python: http://peak.telecommunity.com/DevCenter/PythonEggs Diez From ptmcg at austin.rr.com Tue Jul 1 23:02:24 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 1 Jul 2008 20:02:24 -0700 (PDT) Subject: pyparsing problem References: Message-ID: On Jul 1, 8:02?am, name wrote: > Hi, > > I try to parse a file with pyparsing and get this output: > > ? ? ['generic', 'host-01', 'host alias xyz', '10.0.0.1'] > ? ? - alias: host alias xyz > ? ? - host_name: ['host-01'] > ? ? - ip_address: ['10.0.0.1'] > ? ? - use: ['generic'] > > ? ? > ? ? ? generic > ? ? ? host-01 > ? ? ? host alias xyz > ? ? ? 10.0.0.1 > ? ? > > ? ? ['generic', 'host-01', 'host alias xyz', '10.0.0.1'] > > ? ? finished > > What I don't understand is why I get the line > > ? ? generic > > and not > > ? ? generic > > as there is an associated name in the dump() output. > > Thank you very much in advance for any clue or help you could > provide. > > The code: > --------- > > #!/usr/bin/env python > > from pyparsing import * > > sample = """ > define host{ > ? use ? ? ? ? ? ? ? ? ? generic > ? host_name ? ? ? ? ? ? host-01 > ? alias ? ? ? ? ? ? ? ? host alias xyz > ? address ? ? ? ? ? ? ? ? ? ? ? 10.0.0.1} > > """ > > # define tokens > LBRACE,RBRACE = map(Suppress, '{}') > ipAddress = Combine(Word(nums) + ('.' + Word(nums))*3) > useTemplate = oneOf('generic user') > > # define grammar > > deviceName = Word(alphanums+'-') > hostDef = Literal('define').suppress() + Literal('host').suppress() > useLine = Suppress('use') + useTemplate + Suppress(SkipTo(lineEnd)) > host_nameLine = Suppress('host_name') + deviceName + Suppress(SkipTo > (lineEnd)) > aliasLine = Suppress('alias') + SkipTo(lineEnd) > aliasLine.setParseAction(lambda x: ' '.join(x[0].split())) > ip_addressLine = Suppress('address') + ipAddress > > use = useLine.setResultsName('use') > host_name = host_nameLine.setResultsName('host_name') > alias = aliasLine.setResultsName('alias') > ip_address = ip_addressLine.setResultsName('ip_address') > > host_stmt = (use + host_name + alias + ip_address) > host = hostDef + LBRACE + host_stmt ?+ RBRACE > > test_file = OneOrMore(host) + stringEnd > > # test > x = test_file.parseString(sample) > print x.dump() > print > print x.asXML('Hosts') > print > print x.asList() > print > > print 'finished' Try downloading the latest pyparsing.py file from the SourceForge SVN repository. This bug should be fixed in the latest version. -- Paul From ldo at geek-central.gen.new_zealand Thu Jul 24 06:01:23 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 24 Jul 2008 22:01:23 +1200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: In message <52404933-ce08-4dc1-a558-935bbbae779b at r35g2000prm.googlegroups.com>, Jordan wrote: > Except when it comes to Classes. I added some classes to code that had > previously just been functions, and you know what I did - or rather, > forgot to do? Put in the 'self'. In front of some of the variable > accesses, but more noticably, at the start of *every single method > argument list.* The reason is quite simple. Python is not truly an "object-oriented" language. It's sufficiently close to fool those accustomed to OO ways of doing things, but it doesn't force you to do things that way. You still have the choice. An implicit "self" would take away that choice. From sn.oo.py.9027 at gmail.com Mon Jul 14 04:18:51 2008 From: sn.oo.py.9027 at gmail.com (John Mechaniks) Date: Mon, 14 Jul 2008 01:18:51 -0700 (PDT) Subject: subprocess module Message-ID: <2e7f0504-cc1c-4cb6-b2d0-b67b004eca7d@x41g2000hsb.googlegroups.com> from subprocess import call call(['ls', '-l']) How do I get the result (not the exit status of the command) of "ls - l" into a variable? From comp.ogz at gmail.com Thu Jul 24 10:54:50 2008 From: comp.ogz at gmail.com (Oguz Yarimtepe) Date: Thu, 24 Jul 2008 17:54:50 +0300 Subject: pci card adjusting Message-ID: <20831c740807240754o407c7383h462e01fecb8364c0@mail.gmail.com> Hi all, I need to adjust the dimming property of my video card. There is currently a written application called nvclock but it is not supporting my card right now. So i need to implement the requiered register jobs on the card. This is already done to a degree in C. But i don't want to dive in to the C code right now. I prefer Python so may i implement such a feature by Python? Is there any library that i can use inside Python to get or set some register values of my pci card. Some memory stuff might be necessarry, i dont know yet how to implement the dim feature for my card. But till i observe the code, pmc smartdim offset, smartdim mask and shift amount is used for such a thing. These are vendor spesific values and lets imagine i have these values now. What is the next movement or any suggestions about this issue? -- O?uz Yar?mtepe www.loopbacking.info From bruno.desthuilliers at gmail.com Mon Jul 14 12:40:51 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 14 Jul 2008 09:40:51 -0700 (PDT) Subject: while var, but var ==16 != true References: <8c2cd9ff-bec2-4844-82a8-8ce02df5663e@w7g2000hsa.googlegroups.com> Message-ID: <689d495a-af00-4af6-86ce-b20861ef42f3@f36g2000hsa.googlegroups.com> On 14 juil, 07:32, Tim Roberts wrote: (snip) > Everything has a boolean value in > Python. 0, None, False, '' (empty string), [] (empty list), () (empty > tuple), and {} (empty dictionary) all have a False value. Everything else > has a True value. Unless the author of the class specified it otherwise (implementing the appropriate __magic_method__). From bronger at physik.rwth-aachen.de Thu Jul 17 08:26:44 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 17 Jul 2008 14:26:44 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> Message-ID: <87lk00d7cr.fsf@physik.rwth-aachen.de> Hall?chen! bruno.desthuilliers at gmail.com writes: > On 16 juil, 10:35, Stefan Scholl wrote: > >> Dave U. Random wrote: >> >>> http://snipr.com/PracticalDjango >> >> June 2008 is a bit too early. Django isn't ready. > > Oh, really ? Too bad. But, wait... If Django isn't ready, what's > that framework I've been using for almost three years now, then > ??? Before writing sarcastic comments, reading the thread would be really polite. As far as versioning is concerned, Django's policy is that "1.0" equals "API is frozen". And I consider publishing a book four months before the API is polished bad timing, too. Especially because Django is exquisitely documented on its webpage, so there is no urgent need for it. I thought about buying a Django book, too. I'm happy to have delayed it, for the same reason Stefan mentioned. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From ggpolo at gmail.com Wed Jul 30 18:48:47 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 30 Jul 2008 19:48:47 -0300 Subject: Tkinter- Possibly a basic question In-Reply-To: <59dee72b-3fb6-414b-ab49-33cab8f9c9e8@26g2000hsk.googlegroups.com> References: <59dee72b-3fb6-414b-ab49-33cab8f9c9e8@26g2000hsk.googlegroups.com> Message-ID: On Wed, Jul 30, 2008 at 6:33 PM, wrote: > I hate to do this, but I've thoroughly exhausted google search. Yes, > it's that pesky root window and I have tried withdraw to no avail. I'm > assuming this is because of the methods I'm using. I guess my question > is two-fold. > 1) How do I get rid of that window? You don't. > 2) Any comments in general? I am just learning python (and coding with > classes), so I'm sure there are things I should pound into my head > before I learn bad habits. > > Here's the code. It will eventually be a voltage measurement using an > Arduino board. Just a simple plot for now. > > import Tkinter, time > > ... > > if __name__ == "__main__": > root = Tkinter.Tk() > root.withdraw() > > #create main window > a = App(root) > a.title('Plot') > > #create a sample data range for testing > #data ranges from x=0, y=0 to x=10, y=5 > data = [] > for i in range(1000): > data.append( (float(i)/1000*10,float(i)/1000*5) ) > > a.plot_data(data) > > #loop until destroy > a.mainloop() > Before anything.. root withdraw works here but I wouldn't do it anyway. There are several solutions to this actually, I will list some, and none involve withdrawing the root window. The first thing you could do is change App to not inherit from Toplevel, instead change it to inherit object at max and pass the root object to it (to act as the parent for menu and other things). The drawback here is that you will have to change several lines, those that involve menu creation for example and this a.title and a.mainloop. The second option is to not create the root there, instead, make App inherit Tk. I rarely see people doing this, but it works too. Here you won't need to store the parent in an instance attribute, given it is always accessible through self.master since you are subclassing Tk. Another option is to make App subclass Frame instead of Toplevel, so you don't create an unecessary window. But if it is really a window, it doesn't make much sense to inherit Frame, so we are back at the first proposed solution. -- -- Guilherme H. Polo Goncalves From david.lyon at preisshare.net Tue Jul 15 09:38:42 2008 From: david.lyon at preisshare.net (David Lyon) Date: Tue, 15 Jul 2008 23:38:42 +1000 Subject: AW: Python embedding question. In-Reply-To: References: <487C8E1C.7050600@preisshare.net> Message-ID: <487CA862.2000400@preisshare.net> Troeger, Thomas (ext) wrote: > Thanks for your answer. The plattform is x86, so basically it's a PC > with a compact flash drive. The problem is that the compact flash is > rather limited in speed and size (there is other stuff on it too). > Oh ok. Well just keep in mind that 4GB of flash memory can be bought in China for about 5 euros. Since programming time is pretty expensive you need to do your sums about where you want to spend the time/money. >>> Or is there a method to have gzipped modules that are unzipped on >>> > the > >>> fly into memory when they're accessed? That would be even better. >>> >> Yes - also possible. >> > > That sounds promising, is there a link you can give? Or do I have to > modify the module loading code for this, i.e. the interpreter? http://squashfs.sourceforge.net/ > I think > that wouldn't be too much of a problem if I understand where Python > loads modules; I haven't checked the Python source yet for that one, and > searching for Python and zip or similar always yields tons of links that > use the Python zip or tar module :) > Python modules are byte compiled. You can usually cut out a lot/some of space by removing the source (.py) and leaving the compile (.pyc) modules. There is usually a lib or a sitelib directory. You could try cleaning that out of unwanted modules. My advice would be to simply buy higher capacity flash memory.... Regards David -------------- next part -------------- An HTML attachment was scrubbed... URL: From ivan at datasyncorp.com Wed Jul 2 16:39:48 2008 From: ivan at datasyncorp.com (Ivan Ven Osdel) Date: Wed, 2 Jul 2008 15:39:48 -0500 (CDT) Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: <4400a687-f424-45ba-93f5-e096913f52a9@s21g2000prm.googlegroups.com> Message-ID: <562513320.877251215031188320.JavaMail.root@saturn.datasyncintra.net> Not really, I have just worked with them more. ----- Original Message ----- From: "Ali Servet D?nmez" To: python-list at python.org Sent: Wednesday, July 2, 2008 1:15:04 PM GMT -06:00 US/Canada Central Subject: Re: Freesoftware for auto/intelligent code completing in Python On Jul 2, 7:55?pm, Ivan Ven Osdel wrote: > The free Python editors/IDEs really do need work as far as code completion goes but I am hopeful. > > IMO Stani's Python Editor comes closest by providing some code sense through a combination of history and doc strings for Python built-ins. Where it falls short is the ability to scan doc strings for your own code and non built-in modules in the Python path. Python already has the ground work in place to accomplish something similar to VS's XML commenting/intellisense system. With a Python interpretor you can type help(myModule) and get the doc string documentation. So I imagine implementing code sense for code being developed as well as non built-in modules would just be a matter of finding the appropriate module at the right time and piping the output of help([module]) to a popup window. > > If your willing to help work on something like that I suggest contacting Stani directlyhttp://pythonide.stani.be/or creating a plugin for Geanyhttp://geany.uvena.de/ > > Ivan Ven Osdel > Software Engineerhttp://www.datasyncsuite.com/ > > ----- Original Message ----- > From: "Ali Servet D?nmez" > To: python-l... at python.org > Sent: Wednesday, July 2, 2008 3:33:59 AM GMT -06:00 US/Canada Central > Subject: Re: Freesoftware for auto/intelligent code completing in Python > > On Jul 1, 12:15?am, Fuzzyman wrote: > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > I don't want to be so mean here, but how hard it could be be writing a > > > freesoftware which would automatically/intelligently auto complete > > > Python code? (I mean something that really does the job, like > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > name it, but just don't give me PyDev please...) > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > missing here? > > > > Could someone please point me out something that I'm really missing > > > which is already present in the wild, otherwise I'd like discuss with > > > whoever is willing to help me to get this thing done. I made my mind > > > and I could volunteer to make this happen as thesis project for my > > > incoming graduation in the next year. > > > > Regards you all, > > > Ali Servet D?nmez > > > Vim, Emacs, Wing, Komodo, ... more? > > > Yeah, I guess you're missing something. :-) > > > Michael Foordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > I've checkout Wing IDE's license and it doesnt' seem to be a > freesoftware; am I wrong? > > Ivan, thanks for your reply. I am curious how come you're suggesting me those two, but not others. Is there a good/particular reason for that? From motoom at xs4all.nl Thu Jul 10 16:13:53 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Thu, 10 Jul 2008 22:13:53 +0200 Subject: parsing incoming emails Message-ID: <2.2.32.20080710201353.01167514@pop.xs4all.nl> Ahmed wrote... > I am working on a project where I need to parse incoming emails > (Microsoft outlook) I'm not sure if you are able to bypass Outlook (and have Python fetch the mail itself using poplib), but if you are, the following code might be useful. I use this to pry apart emails which might contain multiple MIME parts. from email.Parser import Parser from rfc822 import parseaddr import poplib import smtplib popserver="pop.site.com" popuser="user at site.com" poppassword="secret" # split a message into an header- and body part def separate(msg): if isinstance(msg,str): msg=msg.split('\n') emptyline=msg.index('') return msg[:emptyline],msg[emptyline+1:] # return a certain headerline from the headers def headerline(header,tag="From: "): for h in header: if h.startswith(tag): return h[len(tag)+1:] return "" # enumerate recursively the contents of a MIME message # remember the first text/plain and text/html part(s) that is found # also remember if any other parts were found (like attachments) # def enummimeparts(msg,extract,level=1,verbose=False): m=Parser().parsestr(msg) if m.is_multipart(): if verbose: print '\t'*level,'multipart' for part in m.get_payload(): enummimeparts(part.as_string(),extract,level+1,verbose) else: t=m.get_content_type() if verbose: print '\t'*level,t if t=="text/plain": if not "text/plain" in extract: headers,body=separate(m.as_string()) extract["text/plain"]='\n'.join(body) else: extract["others"]=True elif t=="text/html": if not "text/html" in extract: headers,body=separate(m.as_string()) extract["text/html"]='\n'.join(body) else: extract["others"]=True else: extract["others"]=True # extract the first 'text/plain' and 'text/html' mime-parts from a message def extracttext(msg): extract={} enummimeparts(msg,extract) return extract.get("text/plain",None),extract.get("text/html",None),extract.get("ot hers",False) def processmessage(msgnr): # get a message from the POP server, extract the parts response,lines,bytes=pop.retr(msgnr) msg='\n'.join(lines) headers,body=separate(lines) name,fromaddress=parseaddr(headerline(headers,"From:")) subject=headerline(headers,"Subject:") logging.info(subject+" ("+fromaddress+")") (plain,html,others)=extracttext(msg) # prefer flat text; if not present in the message, fallback to HTML content (if any) texttoprocess="" if plain: texttoprocess=plain elif html: texttoprocess=html # now do something useful with the text processtext(texttoprocess) # delete message from pop server after processing pop.dele(msgnr) # connect to the pop server and process all messages logging.info("Checking pop server '%s', user '%s'" % (popserver,popuser)) pop=poplib.POP3(popserver) pop.user(popuser) pop.pass_(poppassword) stat=pop.stat() if stat[0]: for n in range(stat[0]): processmessage(n+1) pop.quit() -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From larry.bates at websafe.com` Wed Jul 16 22:27:50 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 16 Jul 2008 21:27:50 -0500 Subject: py2exe issues with pictures and icons In-Reply-To: References: Message-ID: Alexnb wrote: > Hello > > I am sure most of you are familiar with py2exe. I am having a bit of a > problem. See the program has a few pictures involved and the .ico it uses > for the windows. However, the pictures are stored in the same directory as > the source, something like: C:\Docs and settings\me\My docs\python\program. > When I run the program for the interpreter, just as a .py, everything works > just as it should. However, when I compile the main source as an .exe, and > say let a friend try the program. It fails because it is missing the .ico. > The catch, is I don't want to have it have to installed, at least at this > point, I want it to be able to just run. So how can I make it just run from > any computer with the files not being in the immediate directory. If that is > not possible, how can I put them in the immediate directory and still make > it work. Because that directory may change a lot so the path will change. > > Just a few questions. I hope someone out there can help me out! Windows can't read minds. The icon's/pictures have to either be in the same directory as the .exe or the .exe has to have a way to find them in another folder (e.g. via .ini config file). Takw a few minutes and go to: http://jrsoftware.org/isinfo.php It is a free Windows installer that I use to take py2exe, icons, pictures, .ini files, documentation, etc and wrap it all up into a nice, neat package that can be distributed as a single .exe. It will take a couple of hours, but it will be hours well spent (especially if you think you will do this more than once). Larry From kyosohma at gmail.com Sun Jul 13 19:30:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sun, 13 Jul 2008 16:30:25 -0700 (PDT) Subject: wxPython code giving strange errors. References: <01694ab5-7b5e-4e57-8b86-bf89b0beec82@m44g2000hsc.googlegroups.com> Message-ID: On Jul 13, 10:18?am, teh_sAbEr wrote: > I'm busy trying to learn wxPython, and i'm trying to run the following > piece of code (its from the wxPyWiki tutorial): > > import wx > > ID_ABOUT = 101 > ID_EXIT = 110 > > class MainWindow(wx.Frame): > ? ? def __init__(self,parent,id,title): > ? ? ? ? wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) > ? ? ? ? self.control = wx.TextCtrl(self,1,style=wx.TE_MULTILINE) > ? ? ? ? self.CreateStatusBar() > > ? ? ? ? filemenu = wx.Menu() > ? ? ? ? filemenu.Append(ID_ABOUT,"&About"," Information about this > program.") > ? ? ? ? filemenu.AppendSeparator() > ? ? ? ? filemenu.Append(ID_EXIT,"E&xit"," Terminate the program.") > > ? ? ? ? menuBar = wx.MenuBar() > ? ? ? ? menuBar.Append(filemenu,"&File") > ? ? ? ? self.SetMenuBar(menuBar) > ? ? ? ? self.Show(True) > > app = wx.PySimpleApp() > frame = MainWindow(None, -1, "Sample editor") > app.MainLoop() > > Simple enough, but every single time I try to run it IDLE gives me > this instead of the app I was hoping for: > > Traceback (most recent call last): > ? File "C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap > \Python Stuff\Batch Picture Converter\main.py", line 24, in > ? ? frame = MainWindow(None, -1, "Sample editor") > ? File "C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap > \Python Stuff\Batch Picture Converter\main.py", line 9, in __init__ > ? ? wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) > ? File "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx > \_windows.py", line 501, in __init__ > ? ? _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, > **kwargs)) > PyNoAppError: The wx.App object must be created first! > > As far as I can tell, the wx.App object IS being created first. I > suspect a race condition of some sort here, but can anyone shed some > light on this? This code works "as is" on Windows XP. However, I have gotten this error when trying to run it from IDLE and I've heard that that can happen in other Tkinter-based IDEs. Try running it from the command line and I'll bet you won't get that error. Also, there's a great wxPython user's group you can join from the official website: www.wxpython.org Mike From jadamwilson2 at gmail.com Tue Jul 22 22:06:50 2008 From: jadamwilson2 at gmail.com (jadamwil) Date: Tue, 22 Jul 2008 19:06:50 -0700 (PDT) Subject: fromfile error on windows, not mac References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> <9650a33b-40b5-46a7-a05e-5b059117891f@b1g2000hsg.googlegroups.com> <185cc290-18a5-4572-9fda-fa0bb785c831@z72g2000hsb.googlegroups.com> Message-ID: <8b6b03d3-089a-4157-b425-54040e8620c8@d1g2000hsg.googlegroups.com> On Jul 22, 8:35?am, jadamwil wrote: > On Jul 22, 2:05?am, Uwe Schmitt > wrote: > > > > > jadamwil schrieb: > > > > Hello, > > > I am using the numpy fromfile function to read binary data from a file > > > on disk. The problem is that the program runs fine on a Mac, but gives > > > an error or warning onwindowswhen trying to read the data. I use it > > > like this: > > > > Signal = zeros((N, 16), dtype=float32) > > > for sample in range(0, N): > > > ? # this function gets the next position in the file to seek to > > > ? s = getFilePos(sample) > > > > ? # go to the correct location in the file; this IS checked to make > > > sure it is within the file > > > ? mFile.seek(s) > > > > ? # read the 16 float32 values from the file > > > ? D = fromfile(mFile, dtype=numpy.float32, 16) > > > > ? # save D in Signal > > > ? Signal[sample, :] = D > > > > This will fail when sample is ~4. If I change the range to (5,N), > > > skipping the "bad" file location, it will run fine for a few samples, > > > and then give another error. The message it gives is: > > > "16 items requested but only 7 read" > > > > So D is a 7x1 vector, and the program dies when it tries to assign D > > > to the slice of Signal ("ValueError: shape mismatch: objects cannot be > > > broadcast to a single shape"). > > > > Onwindows, the Python version is 2.5.2, and the most recent numpy and > > > scipy are being used as well. I tried using Enthought, but it gave > > > this error as well, in addition to a c runtime error whenever I > > > imported scipy (which is another post topic...). > > > > Any ideas on what might be causing this? Is there a way to debug the > > > fromfile function? And, remember, this works perfectly on a Mac. Would > > > compiling everything (python, scipy, numpy) potentially solve this? > > > Did you open the file in binary mode ? > > > Greetings, Uwe > > Yes I did. Would that make a difference between a mac andwindows? > Thanks Uwe, Thanks for the suggestion. I passed "rb" to the open file command, not 'rb' which made a difference. I thought it opened in binary, but it did not, and it seems windows is not as good unix for dealing with this situation. Adam From rkmr.em at gmail.com Mon Jul 28 09:02:48 2008 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Mon, 28 Jul 2008 06:02:48 -0700 Subject: write unsigned integer 32 bits to socket In-Reply-To: <9_KdnfSDZ9xHIRDVnZ2dnUVZ_gCdnZ2d@pdx.net> References: <9_KdnfSDZ9xHIRDVnZ2dnUVZ_gCdnZ2d@pdx.net> Message-ID: On Mon, Jul 28, 2008 at 5:45 AM, Scott David Daniels wrote: > Alan Franzoni wrote: >> >> Michael Torrie was kind enough to say: >> >>> Of course any time you send coherent numbers over the network, I highly >>> recommend you use what's called network byte order.... I'm sure python >>> has some convention in the struct module for dealing with this. >> >> Not in the struct module; such functions are available in the socket >> module, and should be employed indeed. > > Please don't pass this misinformation along. > > In the struct module document, see the section on the initial character: > Character Byte order Size and alignment > @ native native > = native standard > < little-endian standard > > big-endian standard > ! network (= big-endian) standard > and notes @ is the default. >>>> print struct.pack('>>> print struct.pack('>lh', 3,4) >>>> print struct.pack('lh', 3,4) >>>> print struct.pack('!lh', 3,4) thanks for clarifying, and just to make sure, i am using '!' format from the struct package... i had this even in my previous email.... what am doing below is fine right? this is short >>> struct.pack('!h',3) '\x00\x03' this is integer >>> struct.pack('!i',3) '\x00\x00\x00\x03' this is long >>> struct.pack('!l',3) '\x00\x00\x00\x03' From marcus at internetnowasp.net Mon Jul 21 12:14:42 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Tue, 22 Jul 2008 00:14:42 +0800 Subject: Python Written in C? In-Reply-To: References: Message-ID: <4884B5F2.5020102@internetnowasp.net> Hi everyone, Yes, python is written in C. Maybe the original poster is looking for "ultimate" language and thus finds it uncomfortable that python should be written in C and not python itself. Actually it doesnt matter if IronPython is written in C# and Python in C. Each programming language is like a tool to the programmer and no, C is not outdate, its just a language with a much higher learning curve and its best left to do stuffs requiring drivers or optimized algorithms and other embedded stuffs that is usable by other languages. What do you think C# is written in? C# ? You see how flawed this logic is. Anyway, good luck on your search. But why look for "ultimate" language, when the core difference is the "programmmer" him/herself. In the hands of an skilled programmer, any language could accomplish much and then there is an issue with "time". I would cringe to do in C what i do in python nowadays, and i have like 14 years of C/C++ programming background. Someone wrote bittorrent in python and today its Utorrent written in C/C++ that is "cool", you see that doesnt mean that the next guy wrote write it in python would not beat the cool factor, its a matter of design, look, feel and ....its all about the programmer. Like they say in racing, its the driver not the car. From __peter__ at web.de Sat Jul 19 16:38:38 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 19 Jul 2008 22:38:38 +0200 Subject: create instance attributes for every method argument References: <4780837f-a5bc-4071-94d3-28e2f206163e@k30g2000hse.googlegroups.com> Message-ID: Berco Beute wrote: > I remember reading somewhere how to create an instance attribute for > every method argument, but although Google is my friend, I can't seem > to find it. This could likely be done way more elegant: > > ========================= > class Test(object): > > def __init__(self, a, b, c, d, e, f): > self.a = a > self.b = b > self.c = c > self.d = d > ========================= http://code.activestate.com/recipes/280381/ Personally, I prefer to spell it out like you did above. Peter From urizev at gmail.com Thu Jul 3 18:58:01 2008 From: urizev at gmail.com (Urizev) Date: Fri, 4 Jul 2008 00:58:01 +0200 Subject: Singleton implementation problems Message-ID: Hi everyone I have developed the singleton implementation. However I have found a strange behaviour when using from different files. The code is attached. Executing main new MySet object No singleton instance New singleton: <__main__.Singleton instance at 0x2b98be474a70> new MySet object There is a singlenton instance new Member new MySet object No singleton instance New singleton: new Member new MySet object There is a singlenton instance new Member new MySet object There is a singlenton instance I do not know why, but it creates two instances of the singleton. Does anybody know why? Regards -------------- next part -------------- A non-text attachment was scrubbed... Name: member.py Type: text/x-python Size: 175 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: myset.py Type: text/x-python Size: 1466 bytes Desc: not available URL: From ldo at geek-central.gen.new_zealand Thu Jul 17 01:31:37 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 17 Jul 2008 17:31:37 +1200 Subject: fork after creating temporary file using NamedTemporaryFile References: <0435315d-7b7d-4587-bc8c-000e3f2644a2@z72g2000hsb.googlegroups.com> Message-ID: In message , Sebastian "lunar" Wiesner wrote: > Relying on the destructor is *always* a bad idea, you should always > close files explicitly! There shouldn't be any problem with files opened read-only. From alexnbryan at gmail.com Thu Jul 17 01:38:05 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 22:38:05 -0700 (PDT) Subject: Need help getting BeautifulSoup contents Message-ID: <18501881.post@talk.nabble.com> The trick to this one is that the html looks something like this:
american, a href="/browse/blue" linkindex="12" set="yes">blue brick churn cottage cream " My question is I want everything inside, the contents of each ad the regular text of the . I know I can do like a.contents, but it only gives me the first one, in this case being "blue". I want the contents of each of those and the regular contents of the . P.S. notice the things inbetween the Message-ID: <74c92ee2-7b89-4579-b25a-a68262e2fee7@a70g2000hsh.googlegroups.com> On Jul 21, 10:17 am, "??" wrote: > Howdy, > > I'm confused about the motivation of releasing python2.6 and python3.0 > at the *same* time. IMO, 2.6 should be compatible with 2.5 while 3.0 > is new style python. Currenly, most python projects works fine in 2.5. > When 3.0 becomes final release, those projects will be gradually moved > to 3.0. But even without the intermediate version 2.6, project > transformation with be smooth enough, and then 2.5, 2.6 will be > replaced by 3.0. I will not spend any time on studying 2.6. So why > does python development team put many efforts on 2.6? What is the role > of 2.6? > > Best regards, > > -- > ShenLei 2.6 is meant to be a continuation of the 2.x line of Python, to support a gradual move of larger projects over to the Python 3.x series. The idea is that as Python 3.x will cause some major and minor changes to the basics of Python as we currently know it, trying to move everyone straight away will be problematic. Therefore the point is there will be a 2.7, 2.8 and so forth until there is almost no difference between the 2.x and 3.x at which time most users will have moved to the 3.x series and the 2.x can be discontinued. I will program larger projects in 2.5 for a while and then perhaps look to move it to 2.6 and 2.7, I won't touch the 3.x series until it is the common choice, much as a lot of people still program in 2.3/4. From binjured at gmail.com Tue Jul 1 09:50:49 2008 From: binjured at gmail.com (Tom Davis) Date: Tue, 1 Jul 2008 06:50:49 -0700 (PDT) Subject: Looping-related Memory Leak References: <94312edc-babb-4c1b-8db1-233404aa4a02@i76g2000hsf.googlegroups.com> <0abf2145-231c-4189-a8ca-b1f327a735dd@a1g2000hsb.googlegroups.com> <1e36866c-4a94-40b6-9780-81e104286862@d1g2000hsg.googlegroups.com> Message-ID: <186a7a16-2f3c-4e52-a280-c615cd320126@f63g2000hsf.googlegroups.com> On Jun 30, 8:24?pm, Carl Banks wrote: > On Jun 30, 1:55 pm, Tom Davis wrote: > > > > > On Jun 26, 5:38 am, Carl Banks wrote: > > > > On Jun 26, 5:19 am, Tom Davis wrote: > > > > > I am having a problem where a long-running function will cause a > > > > memory leak / balloon for reasons I cannot figure out. ?Essentially, I > > > > loop through a directory of pickled files, load them, and run some > > > > other functions on them. ?In every case, each function uses only local > > > > variables and I even made sure to use `del` on each variable at the > > > > end of the loop. ?However, as the loop progresses the amount of memory > > > > used steadily increases. > > > > Do you happen to be using a single Unpickler instance? ?If so, change > > > it to use a different instance each time. ?(If you just use the module- > > > level load function you are already using a different instance each > > > time.) > > > > Unpicklers hold a reference to everything they've seen, which prevents > > > objects it unpickles from being garbage collected until it is > > > collected itself. > > > > Carl Banks > > > Carl, > > > Yes, I was using the module-level unpickler. ?I changed it with little > > effect. ?I guess perhaps this is my misunderstanding of how GC works. > > For instance, if I have `a = Obj()` and run `a.some_method()` which > > generates a highly-nested local variable that cannot be easily garbage > > collected, it was my assumption that either (1) completing the method > > call or (2) deleting the object instance itself would automatically > > destroy any variables used by said method. ?This does not appear to be > > the case, however. ?Even when a variable/object's scope is destroyed, > > it would seem t hat variables/objects created within that scope cannot > > always be reclaimed, depending on their complexity. > > > To me, this seems illogical. ?I can understand that the GC is > > reluctant to reclaim objects that have many connections to other > > objects and so forth, but once those objects' scopes are gone, why > > doesn't it force a reclaim? > > Are your objects involved in circular references, and do you have any > objects with a __del__ method? ?Normally objects are reclaimed when > the reference count goes to zero, but if there are cycles then the > reference count never reaches zero, and they remain alive until the > generational garbage collector makes a pass to break the cycle. > However, the generational collector doesn't break cycles that involve > objects with a __del__method. There are some circular references, but these are produced by objects created by BeautifulSoup. I try to decompose all of them, but if there's one part of the code to blame it's almost certainly this. I have no objects with __del__ methods, at least none that I wrote. > Are you calling any C extensions that might be failing to decref an > object? ?There could be a memory leak. Perhaps. Yet another thing to look into. > Are you keeping a reference around somewhere. ?For example, appending > results to a list, and the result keeps a reference to all of your > unpickled data for some reason. No. > You know, we can throw out all these scenarios, but these suggestions > are just common pitfalls. ?If it doesn't look like one of these > things, you're going to have to do your own legwork to help isolate > what's causing the behavior. ?Then if needed you can come back to us > with more detailed information. > > Start with your original function, and slowly remove functionality > from it until the bad behavior goes away. ?That will give you a clue > what's causing it. I realize this and thank you folks for your patience. I thought perhaps there was something simple I was overlooking, but in this case it would seem that there are dozens of things outside of my direct control that could be causing this, most likely from third-party libraries I am using. I will continue to try to debug this on my own and see if I can figure anything out. Memory leaks and failing GC and so forth are all new concerns for me. Thanks Again, Tom From siona at chiark.greenend.org.uk Thu Jul 10 08:37:37 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 10 Jul 2008 13:37:37 +0100 (BST) Subject: User-defined exception: "global name 'TestRunError' is not defined" References: Message-ID: In article , wrote: >I'm using some legacy code that has a user-defined exception in it. > >The top level program includes this line > >from TestRunError import * > >It also imports several other modules. These other modules do not >explicitly import TestRunError. TestRunError is raised in various >places throughout the modules. The import line imports TestRunError into the "global" namespeace of the top level program module *only*. It is not magically propogated to the other modules imported -- if they want to use TestRunError themselves, they have to import it, otherwise this happens: >FATAL ERROR: global name 'TestRunError' is not defined >I realize this is kind of a silly question to ask in the general sense >without showing more of the code, but does anyone have any suggestions >as to the most likely causes of this error coming up? The cause is whoever wrote the legacy code not understanding how to program in Python. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From cokofreedom at gmail.com Thu Jul 10 02:53:05 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 9 Jul 2008 23:53:05 -0700 (PDT) Subject: You, spare time and SyntaxError References: Message-ID: <8731210e-34cf-4aa7-9a6e-66edce00d157@x35g2000hsb.googlegroups.com> > > just... great !-) > Thanks :) From larry.bates at websafe.com` Mon Jul 21 12:54:25 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 11:54:25 -0500 Subject: how to create GUI dynamically In-Reply-To: <84f144db-0d6c-44d5-a1ef-6e7778304c2a@r66g2000hsg.googlegroups.com> References: <84f144db-0d6c-44d5-a1ef-6e7778304c2a@r66g2000hsg.googlegroups.com> Message-ID: hitechpundir at gmail.com wrote: > Hi; > > i m working on a project where i need run time creation of GUI. > > i have some no. of entities for which i want checkboxes in front of > them which can be checked/ unchecked by user. > > But the problem is that the number and name of entities is not fixed > and it depends on the file which is used as input. > > So is there any way to tackle this problem. > > By the way ; i use Boa constructor (zope editor) for GUI now. > > regards > pawan pundir All the GUI tookits (Tkinter, wxWindows, QT) allow you to build the GUI dynamically. -Larry From bgeddy at home.havin.a.break Thu Jul 17 20:36:44 2008 From: bgeddy at home.havin.a.break (bgeddy) Date: Fri, 18 Jul 2008 01:36:44 +0100 Subject: storing references instead of copies in a dictionary In-Reply-To: References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: bgeddy wrote: > castironpi wrote: >> On Jul 17, 10:05 am, mk wrote: >>>> def f2(arg): >>>> return "f2 "+arg >>>> def f1(arg): >>>> return "f1 "+arg >>>> a={"1":"f1","2":"f2"} >>>> print [eval(x[1])(x[0]) for x in a.items()] >>>> def f2(arg): >>>> return "New f2 "+arg >>>> print [eval(x[1])(x[0]) for x in a.items()] >>> Neat trick, if probably dangerous in some circumstances. Anyway, thanks, >>> I didn't think of that. >>> >>>> Don't know if this is any use to you.. >>> At least I learned something. :-) >> >> You want consistent access to a changing variable. Wrap it in an >> object: >> >>>>> a= Blank( ) >>>>> a.ref= 'X' >>>>> a.ref >> 'X' >>>>> b= a >>>>> b.ref >> 'X' >>>>> a.ref= 'Y' >>>>> b.ref >> 'Y' >> > My "old fashioned" programing paradigms think of this in terms of > "pointers", a throw back to my schooling in 'C'. I find this general > form of problem to be common across languages and in some ways hard to > express in python. The whole idea of labels bound to objects is quite > alien to traditional terminology. I find one of the main attractions of > python is this new mindset that the language makes you adopt - a > different set of tools are at hand for the old school programmer. > > castironpi - please give an example of what you are thinking as I find > this interesting. preferably post some brief example code. castironpi - please forgive the double post but my newsreader didn't display your code correctly.. Doh !! Anyway - a nice way of addressing the problem. However the OP's post revolved around having a rewritable set of "labels" - which could be recorded at one time and when re referenced the new definitions of those labels would be used. For example a "collection" (list,dictionary,tuple) could be made of these "labels" and then the underlying code accessed by the labels changed. If the code was now ran indirectly by referencing the list then the new code would be ran. These building blocks are how parsers are built and the basis of language. I can see how you form two ways of addressing the variable but can't figure how this fits the original problem. Please elaborate for my ignorance. EdH. From fuzzyman at gmail.com Sat Jul 19 16:07:49 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sat, 19 Jul 2008 13:07:49 -0700 (PDT) Subject: win32api not found? References: Message-ID: On Jul 19, 8:45?pm, Michiel Overtoom wrote: > On Saturday 19 July 2008 21:13:04 Lamonte Harris wrote: > > > Where can I get the win32api module? I been searching all day on google and > > nothing, i installed > >https://sourceforge.net/project/showfiles.php?group_id=78018which requires > > win32api and its not found... > If you have successfully installed the pywin32 extensions then you *will* be able to import win32api. What happens if you start the Python interactive interpreter and enter 'import win32api' ? Michael Foord http://www.ironpythoninaction.com/ > What are the actions you do and the commands you give, and what is the precise > error you get? > > Greetings, > > -- > "The ability of the OSS process to collect and harness > the collective IQ of thousands of individuals across > the Internet is simply amazing." - Vinod Vallopillilhttp://www.catb.org/~esr/halloween/halloween4.html From littlesweetmelon at gmail.com Mon Jul 21 04:17:00 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Mon, 21 Jul 2008 16:17:00 +0800 Subject: What is the role of python2.6 and C++? Message-ID: Howdy, I'm confused about the motivation of releasing python2.6 and python3.0 at the *same* time. IMO, 2.6 should be compatible with 2.5 while 3.0 is new style python. Currenly, most python projects works fine in 2.5. When 3.0 becomes final release, those projects will be gradually moved to 3.0. But even without the intermediate version 2.6, project transformation with be smooth enough, and then 2.5, 2.6 will be replaced by 3.0. I will not spend any time on studying 2.6. So why does python development team put many efforts on 2.6? What is the role of 2.6? Another question is about the future of C++. I am a C++ programmer. Since I studied python, most of my projects becomes written in python because of the better and simpler OOP representation. As a supplement, I use python C extension for computational extensive jobs. Therefore, for a relatively long time, I do not use C++ any more... Anyone is same to me? What is your attitude to the role of C++ in the age of python? Best regards, -- ShenLei From circularfunc at gmail.com Sat Jul 12 12:20:58 2008 From: circularfunc at gmail.com (ssecorp) Date: Sat, 12 Jul 2008 09:20:58 -0700 (PDT) Subject: Why is this blowing the stack, thought it was tail-recursive... Message-ID: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> def fib(n): def fibt(a, b, n): if n <= 1: return b else: return fibt(b, a + b, n - 1) if n == 0: return 0 else: return fibt(0, 1, n); and can memoization speed up this even more? tesintg with memoization doesnt really say anything because it is so fast it is instant anyway. (the classic easy-redable exponential fib-function can obv be helped enormously with memoization though.) From p0q0b0d at gmail.com Wed Jul 9 02:37:20 2008 From: p0q0b0d at gmail.com (|e0) Date: Wed, 9 Jul 2008 08:37:20 +0200 Subject: Newbie question Message-ID: <3b1e6f480807082337l419fd40ax91eaf13e0701c5b3@mail.gmail.com> Hi list, i'm running Ubuntu Hardy Desktop and i've installed Tim Golden WMI. However importing wmi module i have this error: >>> import wmi Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/site-packages/wmi.py", line 141, in from win32com.client import GetObject, Dispatch ImportError: cannot import name GetObject I can import win32com.client without problems. Do i need to install any extra package? On win i suppose i need win32 extensions, but on linux? Thank you! -- Regards, Leonardo From randall at tnr.cc Sat Jul 26 20:58:38 2008 From: randall at tnr.cc (Randall Smith) Date: Sat, 26 Jul 2008 19:58:38 -0500 Subject: bundling python with application Message-ID: I'd like to bundle Python with my app, which will be targeted at Linux, Windows and Mac. Discussions I've found about this tend to lead to py2exe, freeze, etc, but I'd like to do something rather simple and am seeking advice. What I'd like to do is just copy the standard libraries and executable(s) and adjust the paths in the environment variables. The libraries and executable(s) would reside in the same directory with the application so that you could run the application without needing to install it. The directory might look like this: $ ls start-app.sh app_lib/ python_lib/ python_bin/ start-app.sh would look like this: #!/bin/sh PATH="python_bin:$PATH" PYTHON_HOME="./python_lib" python app_lib/start.py Of course, there would be a start-app.bat for Windows. The PATH is altered to make sure the right python interpreter is found and PYTHON_HOME makes sure the right (local) libraries are found. Can this be done? Randall From benjamin.kaplan at case.edu Tue Jul 15 16:39:31 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 15 Jul 2008 16:39:31 -0400 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: On Tue, Jul 15, 2008 at 4:10 PM, wrote: > I need to know if I'm running on 32bit or 64bit ... so far I haven't > come up with how to get this info via python. sys.platform returns > what python was built on ... but not what the current system is. > > I thought platform.uname() or just platform.processor() would have > done it, but python returns an empty string on windows. Any ideas? > > Thanks, Ken > -- platform.architecture() should have it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sat Jul 26 18:58:16 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 26 Jul 2008 15:58:16 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> Message-ID: <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> On Jul 26, 5:07?pm, Terry Reedy wrote: > Whether or not one should write 'if x' or 'if x != 0' [typo corrected] > depends on whether one means the general 'if x is any non-null object > for which bool(x) == True' or the specific 'if x is anything other than > numeric zero'. ?The two are not equivalent. ?Ditto for the length example. Can you think of any use cases for the former? And I mean something where it can't be boiled down to a simple explicit test for the sorts of arguments you're expecting; something that really takes advantage of the "all objects are either true or false" paradigm. The best thing I can come up with out of my mind is cases where you want to check for zero or an empty sequence, and you want to accept None as an alternative negative as well. But that's pretty weak. The use case of simply passing something to a function that accepts any boolean doesn't count. For instance, I could write: def nand(a,b): return not (a and b) And then I could use it like this, even if x is an interger and y a string: if nand(x,y): But that doesn't buy much since I could just pass in the explicit tests like this: if nand(x!=0,y!=""): Carl Banks From desothier at yahoo.com Fri Jul 18 08:33:57 2008 From: desothier at yahoo.com (antar2) Date: Fri, 18 Jul 2008 05:33:57 -0700 (PDT) Subject: substitution of list elements Message-ID: <247ab26d-ba98-42cc-bf6e-738b4b32a70c@q28g2000prh.googlegroups.com> I want to replace each first element in list 5 that is equal to the first element of the list of lists4 by the fourth element. I wrote following code that does not work: list4 = [['1', 'a', 'b', 'c'], ['2', 'd', 't', 'e'], ['8', 'g', 'q', 'f']] list5 = ['1', '2', '3'] for j in list4: for k in list5: if j[0] == k: k = j[3] print list5 Wanted result: ['c', 'e', '3'] thanks! From larry.bates at websafe.com` Sun Jul 13 21:55:49 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 13 Jul 2008 20:55:49 -0500 Subject: How to package a logging.config file? In-Reply-To: References: Message-ID: Matthew Wilson wrote: > I'm working on a package that uses the standard library logging module > along with a .cfg file. > > In my code, I use > logging.config.fileConfig('/home/matt/mypackage/matt.cfg') to load in > the logging config file. > > However, it seems really obvious to me that this won't work when I share > this package with others. > > I can't figure out what path to use when I load my .cfg file. > > Any ideas? > > Matt Normally you put the logging configuration file in the path where you put the program that you will be sharing (quite often with no path at all). -Larry From david.lyon at preisshare.net Sat Jul 19 06:02:55 2008 From: david.lyon at preisshare.net (David Lyon) Date: Sat, 19 Jul 2008 20:02:55 +1000 Subject: Rotating a cube In-Reply-To: <8156f68a-3f65-4fca-a725-2e0c4240abd1@v21g2000pro.googlegroups.com> References: <3d47df08-9734-4e0f-96ad-37da445b4faf@34g2000hsh.googlegroups.com> <8156f68a-3f65-4fca-a725-2e0c4240abd1@v21g2000pro.googlegroups.com> Message-ID: <4881BBCF.2060905@preisshare.net> Lie wrote: > On Jul 17, 3:11 pm, J-Burns wrote: > >> On Jul 17, 12:53 pm, Fredrik Lundh wrote: >> >> >>> J-Burns wrote: >>> >>>> Is there a built in Python function for this? >>>> >>> for answering questions that have nothing to do with programming, and >>> looks quite a bit like homework? don't think they've added that one yet. >>> >>> maybe you should look for a geometry newsgroup/forum? >>> >>> >>> >> I meant to ask how would you do this in Python... :S >> > > The same as you do it in any other languages. This question is marked > correctly as having no relationship to python whatsoever. You'd get a > better answer if you asked in mathematics/geometry group, many > mathematician are adept programmer as well. > - But is the question about display graphics ? ie rotating a cube using a python framework ? With something like python and OpenGL ? or Python and PovRay... or perphaps python and imagemagick ? If so... i would have thought he should be able to ask that question here.... David -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Sat Jul 26 22:38:26 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 27 Jul 2008 02:38:26 GMT Subject: pixel colour on screen References: <22940391-cf14-4022-8b00-8d7974590072@e39g2000hsf.googlegroups.com> Message-ID: <6pnn84t2uvmg5akolipt493773oddv1a3u@4ax.com> chris wrote: >On Jun 30, 4:37?am, Tim Roberts wrote: >> cjstut... at hotmail.com wrote: >> >> >Could anyone help me, I'm a python noob and need some help. im trying >> >to find some code that will, given ascreenco-ordinate, will give me >> >thecolourof thatpixelin RGB. i have found a lot about getting the >> >pixelcolourfrom a picture file with a given co-ordinate, but is it >> >possible to do it from the wholescreenoutput regardless what >> >application the selectedpixelis in? >> >> Which operating system? ?If you are on Windows, and you have pywin32 >> loaded. you can use the Windows APIs GetDC and GetPixel. > >i have ubuntu hardy. does that help? Then you will have to use a GUI library of some kind: wx, or Qt, or tkinter. The answer depends on which GUI library you decide to use. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From python at rcn.com Mon Jul 21 18:20:39 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 21 Jul 2008 15:20:39 -0700 (PDT) Subject: persistent deque (continued) References: <4c985e86-c0c4-4cb3-b7ce-f8e105b7f85d@y21g2000hsf.googlegroups.com> Message-ID: <4126ceeb-128e-4aa1-af95-31648d42eade@i24g2000prf.googlegroups.com> On Jul 21, 12:08?pm, castironpi wrote: > Some time ago, I was asking about the feasibility of a persistent > deque, a double-ended queue. > > It runs into the typical space allocation problems. ? Try starting with a dict-based implementation of a double-ended queue ( http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259179 ) and then replace the dict with a shelf. Presto, you've got a persistent deque. Raymond From asd at pittle.org Wed Jul 2 04:33:59 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Wed, 2 Jul 2008 01:33:59 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> Message-ID: <9ad840e1-e12f-4125-8537-4bad2ef77f51@w5g2000prd.googlegroups.com> On Jul 1, 12:15?am, Fuzzyman wrote: > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > > I don't want to be so mean here, but how hard it could be be writing a > > freesoftware which would automatically/intelligently auto complete > > Python code? (I mean something that really does the job, like > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > name it, but just don't give me PyDev please...) > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > even a brand new huge all-fancy IDE, I don't care, but what am I > > missing here? > > > Could someone please point me out something that I'm really missing > > which is already present in the wild, otherwise I'd like discuss with > > whoever is willing to help me to get this thing done. I made my mind > > and I could volunteer to make this happen as thesis project for my > > incoming graduation in the next year. > > > Regards you all, > > Ali Servet D?nmez > > Vim, Emacs, Wing, Komodo, ... more? > > Yeah, I guess you're missing something. :-) > > Michael Foordhttp://www.ironpythoninaction.com/http://www.trypython.org/ I've checkout Wing IDE's license and it doesnt' seem to be a freesoftware; am I wrong? From eddie at holyrood.ed.ac.uk Fri Jul 18 06:46:53 2008 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 18 Jul 2008 10:46:53 +0000 (UTC) Subject: trying to match a string References: Message-ID: arnimavidyarthy at gmail.com writes: >Hi, >Hi, >I am taking a string as an input from the user and it should only >contain the chars:L , M or R >I tried the folllowing in kodos but they are still not perfect: >[^A-K,^N-Q,^S-Z,^0-9] >[L][M][R] >[LRM]?L?[LRM]? etc but they do not exactly meet what I need. >For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. >regards, >SZ >The string may or may not have all the three chars. >>> var = 'LRLRLRNL' >>> residue = var.replace('L','').replace('R','').replace('M','') >>> if residue != '': ... print 'Invalid characters in input',residue ... Invalid characters in input N From wesbrooks at gmail.com Tue Jul 1 11:38:23 2008 From: wesbrooks at gmail.com (Wesley Brooks) Date: Tue, 1 Jul 2008 16:38:23 +0100 Subject: Error from zipfile Message-ID: Dear Users, I'm having a problem when trying to move script from Linux to Windows. A zipfile opperation is failing with the message: "BadZipFile: File is not a zip file" I have a simple scripts that reads a zip file in the same way as any other file into a string, then sends it across to a network where it is saved as perusual into a file, then read in and processed by zipfile. I've tried adding the flag to allow 64 bit and even using uncompressed zip files. Niether fixes the problem. The zip file and contents were created on linux. To be certain that was not the issue I have emptied the zip file, created a new one, opend all the files in wordpad and saved them, then put the contents into the new file. Still no joy. Any help would be greatly appreciated. On linux I'm running python 2.5 and on windows it is 2.4. Thanks, Wesley Brooks. From rw at smsnet.pl Tue Jul 8 16:01:07 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Tue, 08 Jul 2008 22:01:07 +0200 Subject: Logging to zero or more destinations References: Message-ID: <87r6a4du2k.fsf@merkury.smsnet.pl> samwyse writes: > In the Python 2.5 Library Reference, section 14.5.3 (Logging to > multiple destinations), an example is given of logging to both a file > and the console. This is done by using logging.basicConfig() to > configure a log file, and then calling > logging.getLogger('').addHandler(console) to add the console. > > However, in section 14.5.4 (Sending and receiving logging events > across a network), a call is made to > rootLogger.addHandler(socketHandler), and later it is stated that "On > the client side, nothing is printed on the console". > > Finally, back in section 14.5.2 (Basic example), it's stated that "by > default, the root logger is configured to only handle messages with a > severity of WARNING or above. The message format is also a > configuration default, as is the output destination of the messages - > sys.stderr." > > The only way that I can see for all three statements to be consistent > is that the root logger starts with an empty list of handlers, and > doesn't instantiate a default handler until either > logging.basicConfig() is called, That is correct. > or the first time that a message is > logged. That is not correct. The list of handlers is empty until `basicConfig` or explicit `addHandler` is called. > This would also seem to imply that there's no way to use an > empty handler list (say, if you want to suppress all logging), because > the root handler will instantiate a handler for you. Is this correct? No. Consider this: >>> import logging >>> logging.root.warning('error message') No handlers could be found for logger "root" >>> logging.root.warning('error message') Note only one warning message. > P.S. I tried researching this further by myself, but the logging > module doesn't come with source (apparently it's written in C?) and I > don't have the time to find and download the source to my laptop. Hmmm... that's strange. It is a pure Python package. $ ls /usr/lib/python2.5/logging/ config.py config.pyc handlers.py handlers.pyc __init__.py __init__.pyc HTH, Rob From tjreedy at udel.edu Thu Jul 31 23:42:00 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 31 Jul 2008 23:42:00 -0400 Subject: Decoding an attachment In-Reply-To: References: Message-ID: robinsiebler at gmail.com wrote: > I figured out how to save an e-mail message as a text file, but I'm > not sure how to decode the encoded part as I am not sure how much I > need to include to decode it properly. Here is what a message looks > like: The email.parser and email.message modules will do this for you. But understanding the parts will help you use them properly. I am 99% sure of the following comments. > > > Received: from INGESTOR2SQA ([10.220.83.198]) by sqaserver300 with > Microsoft SMTPSVC(6.0.3790.0); > Thu, 31 Jul 2008 12:10:26 -0700 > mime-version: 1.0 > from: "AVDN Ingestor" > to: sqatest at ictvsys.pvt > date: 31 Jul 2008 17:53:40 +0000 > subject: Upload Status for test > content-type: multipart/mixed; This says multiple mime parts of mixed types boundary=--boundary_2_09ab8836- > ff06-41a6-94d6-59258539bf88 This is the boundary between parts > Return-Path: sqatest at ictvsys.pvt > Message-ID: > X-OriginalArrivalTime: 31 Jul 2008 19:10:26.0125 (UTC) > FILETIME=[16D08FD0:01C8F341] > > blank lines separate header from body > ----boundary_2_09ab8836-ff06-41a6-94d6-59258539bf88 This is the boundary specified above, with '--' prepended > content-type: text/plain; charset=us-ascii > content-transfer-encoding: quoted-printable This is header of first part > Blank separates part header from part boundary > For additional information, please see attachment. This is first (and last) list of first, plain text part > ----boundary_2_09ab8836-ff06-41a6-94d6-59258539bf88 This is boundary ending first part and starting second part > content-type: text/xml; name=status.xml; charset=utf-8 > content-transfer-encoding: base64 > content-disposition: attachment This is 2nd part header, specifying base64 coding, which is one of the two that email.message knows about. > Blank separating header and payload > PGF2ZG5fcG5tIHZlcnNpb249IjEuMSIgc2VuZGVyPSJhdmRud2VzdGRjMSIgZG9jbnVtYmVy > PSJvaHV0bHBxeXptM25xd3lrYm9wd3pwdTUiIHN0YXR1cz0ic3VjY2Vzc2Z1bCI+PGNvbnRh > Y3QgcGhvbmU9IjQwOC05MzEtOTIzMiIgZW1haWw9Im0uY2hhbkBhdm5ldHdvcmtzLmNvbSIg > Lz48YXNzZXRzdGF0ZSBwcm92aWRlcmlkPSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJjZjcw > NDcwNWFjIiBmaWxlbmFtZT0iXHZpZGVvXGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2NfYWMz > XzAxLmpwZyIgbm90aWZpY2F0aW9uPSIxMjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJpZD0i > U1FBIiBhc3NldGlkPSJhY2YxZTNkNmViY2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRlb1xm > b29cYm91Z2UwMDMuMzIwXzI0MF9udHNjX2FjM18wMy5qcGciIG5vdGlmaWNhdGlvbj0iMTIw > IiAvPjxhc3NldHN0YXRlIHByb3ZpZGVyaWQ9IlNRQSIgYXNzZXRpZD0iYWNmMWUzZDZlYmNm > NzA0NzA1YWMiIGZpbGVuYW1lPSJcdmlkZW9cZm9vXGJvdWdlMDAzLjMyMF8yNDBfbnRzY19h > YzNfMDQuanBnIiBub3RpZmljYXRpb249IjEyMCIgLz48YXNzZXRzdGF0ZSBwcm92aWRlcmlk > PSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJjZjcwNDcwNWFjIiBmaWxlbmFtZT0iXHZpZGVv > XGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2NfYWMzXzAyLmpwZyIgbm90aWZpY2F0aW9uPSIx > MjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJpZD0iU1FBIiBhc3NldGlkPSJhY2YxZTNkNmVi > Y2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRlb1xmb29cYm91Z2UwMDMuMzIwXzI0MF9udHNj > X2FjMy5qcGciIG5vdGlmaWNhdGlvbj0iMTIwIiAvPjxhc3NldHN0YXRlIHByb3ZpZGVyaWQ9 > IlNRQSIgYXNzZXRpZD0iYWNmMWUzZDZlYmNmNzA0NzA1YWMiIGZpbGVuYW1lPSJcdmlkZW9c > Zm9vXGJvdWdlMDAzLjMyMF8yNDBfbnRzY19hYzNfMDguanBnIiBub3RpZmljYXRpb249IjEy > MCIgLz48YXNzZXRzdGF0ZSBwcm92aWRlcmlkPSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJj > ZjcwNDcwNWFjIiBmaWxlbmFtZT0iXHZpZGVvXGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2Nf > YWMzXzA3LmpwZyIgbm90aWZpY2F0aW9uPSIxMjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJp > ZD0iU1FBIiBhc3NldGlkPSJhY2YxZTNkNmViY2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRl > b1xmb29cYm91Z2UwMDMuMzIwXzI0MF9udHNjX2FjM18wNi5qcGciIG5vdGlmaWNhdGlvbj0i > MTIwIiAvPjxhc3NldHN0YXRlIHByb3ZpZGVyaWQ9IlNRQSIgYXNzZXRpZD0iYWNmMWUzZDZl > YmNmNzA0NzA1YWMiIGZpbGVuYW1lPSJcdmlkZW9cZm9vXGJvdWdlMDAzLjMyMF8yNDBfbnRz > Y19hYzNfMDUuanBnIiBub3RpZmljYXRpb249IjEyMCIgLz48YXNzZXRzdGF0ZSBwcm92aWRl > cmlkPSJTUUEiIGFzc2V0aWQ9ImFjZjFlM2Q2ZWJjZjcwNDcwNWFjIiBmaWxlbmFtZT0iXHZp > ZGVvXGZvb1xib3VnZTAwMy4zMjBfMjQwX250c2NfYWMzXzA5LmpwZyIgbm90aWZpY2F0aW9u > PSIxMjAiIC8+PGFzc2V0c3RhdGUgcHJvdmlkZXJpZD0iU1FBIiBhc3NldGlkPSJhY2YxZTNk > NmViY2Y3MDQ3MDVhYyIgZmlsZW5hbWU9Ilx2aWRlb1xmb29cYm91Z2UwMDMuMzIwXzI0MF9u > dHNjX2FjMy50cyIgbm90aWZpY2F0aW9uPSIxMjAiIC8+PC9hdmRuX3BubT4= end of payload, lines in between go to base64 module > ----boundary_2_09ab8836-ff06-41a6-94d6-59258539bf88-- End of part 2 and mime body #I believe s = message_as_string m = email.parser.message_from_string(s) # email.message.Message object p = m.get_payload(1,True) # should give you the 2nd part as a message with the body base64-decoded q = p.get_payload() # utf-8 encoded xml string # I recommend trying out other Message methods # In particular, you want to be able to retrieve the subfields of content_type and I don't know exactly how. Terry Jan Reedy From ndbecker2 at gmail.com Fri Jul 11 15:24:13 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 11 Jul 2008 15:24:13 -0400 Subject: decorator to prevent adding attributes to class? References: <98c6e83e-4a54-49ce-a32e-f03f5ab97f28@k13g2000hse.googlegroups.com> <48778CA2.2000402@jouy.inra.fr> Message-ID: Robert Bossy wrote: > class Foo(Freezeable): > def __init__(self): > self.bar = 42 > self.freeze() # ok, we set all variables, no more from here > > > x = Foo() > print x.bar > x.bar = -42 > print x.bar > x.baz = "OMG! A typo!" > Pretty nice, but unfortunately the subclass has to remember to call freeze in it's init. Too bad that can't be automated. From r_e_s_01 at ZZZyahoo.com Thu Jul 10 20:46:00 2008 From: r_e_s_01 at ZZZyahoo.com (r.e.s.) Date: Thu, 10 Jul 2008 17:46:00 -0700 Subject: Can this program be shortened? Measuring program-length? References: <7Rtdk.16747$N87.3559@nlpi068.nbdc.sbc.com> <2ed6de5b-bf2f-4e3d-94af-c8e6c6a28f95@s50g2000hsb.googlegroups.com> Message-ID: wrote ... > "r.e.s." wrote: >> Can the following program be shortened? ... >> >> def h(n,m): >> E=n, >> while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n >> return n >> h(9,9) >> > > Some ideas... > > # h is your version > def h(n,m): > E=n, > while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n > return n > > def g(n,m): > E=n, > while E*m:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n > return n > > def f(n,m): > E=n, > while E*m:n=h(n+1,m-1);E=(E[0]>0)*(E[0]-1,)*n+E[1:] > return n > > def e(n,m): > E=[n] > while E*m:n=h(n+1,m-1);E[:1]=(E[0]>0)*[E[0]-1]*n > return n > > # some tests > print h(1,1), h(2,1), h(0,2) > print g(1,1), g(2,1), g(0,2) > print f(1,1), f(2,1), f(0,2) > print e(1,1), e(2,1), e(0,2) Very instructive! Thank you for the "step-by-step". From martin at v.loewis.de Wed Jul 23 13:08:55 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 23 Jul 2008 19:08:55 +0200 Subject: interpreter vs. compiled In-Reply-To: References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> Message-ID: <488765A7.7030400@v.loewis.de> >> Oh. How is the stack represented? > > As usual, as successive locations in memory. > I have the impression that CPython uses the same stack C does. Actually, it doesn't (at least not for the evaluation stack). In CPython, when a Python function starts, the maximum depth of the evaluation stack is known, but it depends on the specific function (of course). So Python needs to allocate an array for the evaluation stack with known size, but can't do so on the C stack (at least not portably), since you can't allocate dynamically-sized array as a local variable in C. So instead, pymalloc is used to allocate the evaluation stack, and it is part of the frame object (so the entire frame object is allocated in one chunk, and then split up into local variables and evaluation stack. > While conceptually, CPython may put objects on the stack, I am pretty > sure it actually stacks references (C pointers) to objects in heap memory. Correct. >> Does it keep track of which stack >> positions (TOS, TOS1, etc.) are in what registers? > > I am sure they are not in registers, just normal memory. Correct. As discussed above, they are located on the heap (making Python's frame stack a spaghetti stack). Regards, Martin From mnordhoff at mattnordhoff.com Fri Jul 25 20:52:19 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sat, 26 Jul 2008 00:52:19 +0000 Subject: SimpleJson is slow .... is there any C Compiled version ? In-Reply-To: References: Message-ID: <488A7543.2090205@mattnordhoff.com> sanket wrote: > Hello All, > > I have created an API which fetches some data from the database. > I am using simplejson to encode it and return it back. > > Now the problem is that, this API is being called for millions of > times in a sequence. > I ran a profiler and saw that most of the time is consumed in encoding > my database results in to json. > So I was just wondering is there any C compiled version of simplejson > is available? > or any help regarding this issue would be appreciated. > > Thank you, > Sanket simplejson is not the only JSON library out there. For example, there's python-cjson, which is written entirely in C: There's also an enhanced version of it: I think simplejson has some small, optional C bits that will improve performance if you compile them. Also, be aware that I think simplejson is being integrated into the stdlib in Python 2.6. Also, simplejson and python-cjson might not be entirely compatible: there's one character that one escapes and the other doesn't, or something. -- From magnus.lycka at gmail.com Wed Jul 23 14:07:57 2008 From: magnus.lycka at gmail.com (magnus.lycka at gmail.com) Date: Wed, 23 Jul 2008 11:07:57 -0700 (PDT) Subject: Segv in mmap.move() Message-ID: Does anyone recognize this little Python crasher? I'll file a bug report unless someone notices it as an already documented bug. I found some open mmap bugs, but it wasn't obvious to me that this problem was one of those... Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import mmap >>> data = mmap.mmap(-1, 1) >>> data.move(1,1,-1) Segmenteringsfel (core dumped) I first noticed the problem under Windows in 2.5.1. From ojeeves at gmail.com Wed Jul 2 10:01:16 2008 From: ojeeves at gmail.com (oj) Date: Wed, 2 Jul 2008 07:01:16 -0700 (PDT) Subject: simple UnZip References: <5b915a0e-a227-460f-8273-ecc01b800884@2g2000hsn.googlegroups.com> Message-ID: On Jul 2, 2:39?pm, noydb wrote: > Can someone help me with this script, which I found posted elsewhere? > I'm trying to figure out what is going on here so that I can alter it > for my needs, but the lack of descriptive names is making it > difficult. ?And, the script doesn't quite do anything worthwhile -- it > unzips one file from a zipfile, not all files in a zipfile. > > *** > import zipfile, os, sys, glob > > os.chdir("C:\\Temp") > zips = glob.glob('*.zip') > > for fzip in zips: > ? ? if zipfile.is_zipfile(fzip): > ? ? ? ? print fzip," is a zip" > ? ? ? ? z = zipfile.ZipFile(fzip,'r') > ? ? ? ? lstName = z.namelist() > ? ? ? ? sHgt = lstName[0] > ? ? ? ? print "Unpacking",sHgt > ? ? ? ? hgt = z.read(sHgt) > ? ? ? ? fHgt = open(sHgt,'wb') > ? ? ? ? fHgt.write(hgt) > ? ? ? ? # fHgt.flush > ? ? ? ? fHgt.close > print "Finished" > *** > > I changed it somewhat to > &&& > import zipfile, os, sys > > event_zip = ("C:\\Temp\\data4event.zip") > > z = zipfile.ZipFile(event_zip, 'r') > > zList = z.namelist() > > for zItem in zList: > ? ? print "Unpacking",zItem > ? ? zRead = z.read(zItem) > ? ? z1File = open(zItem,'wb') > ? ? z1File.write(zRead) > ? ? z1File.close > print "Finished" > &&& > > This works, but I want to be able to specify a different output > location. > > The scenario is that the zip file will always be the same (gets copied > over daily), but it needs to be unzipped to a specific different > directory. > > Can anyone help? > > Thanks! Firstly, I'd recommend just reading the documentation for the zipfile module, it's fairly straight forwards. To write the files to a different location, just change this line: z1File = open(zItem,'wb') This is where you're opening a file to write to. Try something like: z1File = open( os.path.join(output_dir, zItem), 'wb') to write the files into the path specified in output_dir. You don't even have to save the files with the same names they have in the zipfile; you don't have to save the files at all. In one project I'm working on, I just read files from a zip file into memory and process them there. From fred.sells at adventistcare.org Tue Jul 15 12:50:24 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Tue, 15 Jul 2008 12:50:24 -0400 Subject: need ldap windows binary and/or installation help In-Reply-To: <487B361D.1070503@timgolden.me.uk> Message-ID: <0A53725C4A497848A7B3A0874B259831011B09A1@acesxch01.ADVENTISTCORP.NET> I'm running python 2.5 (or 2.4) in an XP environment. I downloaded and installed the .dll's from OpenLDAP-2.4.8+OpenSSL-0.9.8g-Win32.zip and copied the .dll's in c:/windows/system32 as instructed now I get this error. Is there anyway to avoid building the python_ldap binaries? Apart from being lazy, I've got a secure system policy issue if I start compiling apps. I could give up and just start running in linux, but my xp environment is much friendlier to develop in. I've googled a lot, but all the links I've found talk to Unix or to compiling from source. Even if I build from source, will the mingw compiler mentioned in most posts produce something that is compatible with "Python was built with Visual Studio 2003". c:\all>easy_install python_ldap Searching for python-ldap Reading http://pypi.python.org/simple/python_ldap/ Reading http://pypi.python.org/simple/python-ldap/ Reading http://python-ldap.sourceforge.net/ Reading http://python-ldap.sourceforge.net/download.shtml Reading http://sourceforge.net/project/showfiles.php?group_id=2072&package_id=2011 Best match: python-ldap 2.3.5 Downloading http://downloads.sourceforge.net/python-ldap/python-ldap-2.3.5.tar.gz?modtime=1215364319&big_mirror=0 Processing python-ldap-2.3.5.tar.gz Running python-ldap-2.3.5\setup.py -q bdist_egg --dist-dir c:\documents and settings\frsells\local settings\temp\easy_install-uczq5i\python-ld extra_compile_args: extra_objects: include_dirs: /usr/local/openldap-2.3/include /usr/include/sasl library_dirs: /usr/local/openldap-2.3/lib libs: ldap_r lber sasl2 ssl crypto file Lib\ldap.py (for module ldap) not found file Lib\ldap\schema.py (for module ldap.schema) not found warning: no files found matching 'Makefile' warning: no files found matching 'Modules\LICENSE' file Lib\ldap.py (for module ldap) not found file Lib\ldap\schema.py (for module ldap.schema) not found file Lib\ldap.py (for module ldap) not found file Lib\ldap\schema.py (for module ldap.schema) not found error: Setup script exited with error: Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. Visual Studio 2003 was not found on this system. If you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py. --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From konstantin.selivanov at gmail.com Tue Jul 22 03:39:12 2008 From: konstantin.selivanov at gmail.com (konstantin) Date: Tue, 22 Jul 2008 00:39:12 -0700 (PDT) Subject: string[i:j:k] References: <4a9a4cf3-9ef4-4d9e-b714-bbf62b7c1917@v1g2000pra.googlegroups.com> <811e72db-a8bc-475a-b32a-38a9b6922600@k30g2000hse.googlegroups.com> Message-ID: <947e9bfd-a172-4b8b-abf2-c4391f0da709@z66g2000hsc.googlegroups.com> Now it's clear. Thanks. From paul at boddie.org.uk Tue Jul 29 11:58:49 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 29 Jul 2008 08:58:49 -0700 (PDT) Subject: DB access without object-relation mapping? References: Message-ID: On 29 Jul, 17:20, kj wrote: > > ?So what's the > standard Python way to send SQL directly to a Postgres database > and get back results? Take a look at this page: http://wiki.python.org/moin/DatabaseInterfaces I've used psycopg2 and pyPgSQL successfully, although pg_proboscis looks very interesting, too. Paul From mdw at distorted.org.uk Sun Jul 6 17:36:36 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Sun, 6 Jul 2008 21:36:36 +0000 (UTC) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Sebastian "lunar" Wiesner wrote: > # perl -e '("a" x 100000) =~ /^(ab?)*$/;' > zsh: segmentation fault perl -e '("a" x 100000) =~ /^(ab?)*$/;' (Did you really run that as root?) > It'd be interesting to know, how CL-PPCRE performs here (I don't know this > library). Stack overflow condition. :-( -- [mdw] From dieter at handshake.de Fri Jul 4 00:20:13 2008 From: dieter at handshake.de (Dieter Maurer) Date: Fri, 4 Jul 2008 06:20:13 +0200 Subject: Nested generator caveat Message-ID: <18541.42237.847192.691004@gargle.gargle.HOWL> I met the following surprising behaviour >>> def gen0(): ... for i in range(3): ... def gen1(): ... yield i ... yield i, gen1() ... >>> for i,g in gen0(): print i, g.next() ... 0 0 1 1 2 2 >>> for i,g in list(gen0()): print i, g.next() ... 0 2 1 2 2 2 If this is not a bug, it is at least quite confusing. The apparent reason is that the free variables in nested generator definitions are not bound (to a value) at invocation time but only at access time. Almost surely, the same applies to all locally defined functions with free variables. This would mean that locally defined functions with free variables are very risky in generators. -- Dieter From ivan at datasyncorp.com Mon Jul 14 17:48:55 2008 From: ivan at datasyncorp.com (Ivan Ven Osdel) Date: Mon, 14 Jul 2008 16:48:55 -0500 (CDT) Subject: Using Python To Launch Python In-Reply-To: <1197830015.1651011216072000480.JavaMail.root@saturn.datasyncintra.net> Message-ID: <338494552.1651151216072135866.JavaMail.root@saturn.datasyncintra.net> >Hello All, > I have a situation where I can count on a Python installation being >available on a system, but I can't count on it being a version of >Python needed by my application. Since my application has it's own >version of Python installed with it how should I use the system Python >to launch the version of Python that launches my Application. Yes, >this is a convoluted process, but not all Pythons are built the >same :) > >Right now I am leaning towards using exec to start a new process, but >I thought I would check to see if anyone else has had the need to >perform a task similar to this one. >AHA Simplest case: >>> import os >>> os.system("/path/to/your/python app.py") Obviously things can be shortened by adding to the PATH. Ivan Ven Osdel Software Engineer http://datasyncsuite.com From tjreedy at udel.edu Tue Jul 15 16:16:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Jul 2008 16:16:41 -0400 Subject: Simplify Code In-Reply-To: <4dc0cfea0807150537w1361ccabq75039886600ce9f8@mail.gmail.com> References: <4dc0cfea0807150537w1361ccabq75039886600ce9f8@mail.gmail.com> Message-ID: Victor Subervi wrote: > I set the following variables: > # Headers are kept in order to determine nesting of chapters > # They are labeled according to font size > h36 = '' > h26 = '' > h22 = '' > h18 = '' > h14 = '' > h12 = '' > header_sizes = [36, 26, 22, 18, 14, 12] > # Size is the font size of the header > size = 0 > > I write code that grabs the size var. > Then I have the following very laborious spaghetti code: > > if size == 36: > h36 = line > h26 = '' > h22 = '' > h18 = '' > h14 = '' > h12 = '' > elif size == 26: > h26 = line > h22 = '' > h18 = '' > h14 = '' > h12 = '' > elif size == 22: > h22 = line > h18 = '' > h14 = '' > h12 = '' > elif size == 18: > h18 = line > h14 = '' > h12 = '' > elif size == 14: > h14 = line > h12 = '' > elif size == 12: > h12 = line > else: > # THROW ERROR! Multiple elifs indicate a possible use for dicts. Untested possibility header_sizes = [36, 26, 22, 18, 14, 12] header_num = len(header_sizes) header_blank = ['']*header_num # makes resetting headers much easier! header_dexes = dict(zip(header_sizes, range(header_num))) hearders = header_blank[0:] #initialize # You can now change header_sizes length and contents # and others will be built to match .. def adjust_headers(size, line): dex = header_dexes[size] headers[dex] = line headers[dex+1:] = header_blank[dex+1:] Terry Jan Reedy From motoom at xs4all.nl Wed Jul 9 16:25:33 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Wed, 09 Jul 2008 22:25:33 +0200 Subject: formatting list -> comma separated (slightly different) Message-ID: <2.2.32.20080709202533.01137964@pop.xs4all.nl> Paul & Robert wrote... > d = ["soep", "reeds", "ook"] >print ', '.join(d) > soep, reeds, ook I occasionally have a need for printing lists of items too, but in the form: "Butter, Cheese, Nuts and Bolts". The last separator is the word 'and' instead of the comma. The clearest I could come up with in Python is below. I wonder if there is a more pythonic solution for this problem. Maybe something recursive? Greetings, ''' Formatting a sequence of items such that they are separated by commas, except the last item, which is separated by the word 'and'. Used for making lists of dates and items more human-readable in generated emails and webpages. For example: Four friends have a dinner: Anne, Bob, Chris and Debbie Three friends have a dinner: Anne, Bob and Chris Two friends have a dinner: Anne and Bob One friend has a dinner: Anne No friend has a dinner: ['Anne','Bob','Chris','Debbie'] -> "Anne, Bob, Chris and Debbie" ['Bob','Chris','Debbie'] -> "Bob, Chris and Debbie" ['Chris','Debbie'] -> "Chris and Debbie" ['Debbie'] -> "Debbie" [] -> "" ''' def pretty(f): if len(f)==0: return '' if len(f)==1: return f[0] sepwithcommas=f[:-1] sepwithand=f[-1] s=', '.join(sepwithcommas) if sepwithand: s+=' and '+sepwithand return s friends=['Anne','Bob','Chris','Debbie','Eve','Fred'] while True: print friends,'->',pretty(friends) if friends: friends.pop(0) else: break -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From deets at nospam.web.de Sun Jul 27 17:35:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2008 23:35:06 +0200 Subject: with statement for two files In-Reply-To: <08d72316-15f1-45dd-b1f7-7b8ee06efef5@e39g2000hsf.googlegroups.com> References: <08d72316-15f1-45dd-b1f7-7b8ee06efef5@e39g2000hsf.googlegroups.com> Message-ID: <6f480aF9r4s5U1@mid.uni-berlin.de> braver schrieb: > Can open two files in a with statement: > > with open(src) as readin, open(dst,"w") as writin: # WRONG: comma > doesn't work > ... > > -- so that you have transactional safety for two file descriptors? > The comma syntax doesn't work, but is there a way, except for > > with open(src) as readin: > with open(dst,"w) as writin: > ... I'm not aware of any pre-defined context manager which does that. But you can write your own context manager to do that, even a generalized combinator for taking two managers and create one, like this: with context_creator(open, [src], open, [dst, "w"]) as readin, writin: ... A fundamental problem though would be that the semantics become difficult. If closing the "outer" file fails, it's impossible to "rollback" the inner one. So I think it really is better to use the nested with, which makes it crystal clear that the inner block might succeed independently from the outer one. Diez From nicolas.pourcelot at gmail.com Fri Jul 18 07:39:40 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Fri, 18 Jul 2008 04:39:40 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> Message-ID: <88704e81-8208-4785-a725-8dcde080225f@z16g2000prn.googlegroups.com> On 18 juil, 12:26, Peter Otten <__pete... at web.de> wrote: > nicolas.pource... at gmail.com wrote: > > I think something like > >>>> id(myobject) in (id(element) for element in mylist) > > would also work, also it's not so readable, and maybe not so fast > > (?)... > > > An "is in" operator would be nice... > > And rarely used. Probably even less than the (also missing) > > < in, | in, you-name-it > > operators... > Maybe, but imho >>> myobject is in mylist is highly readable, when >>> myobject < in mylist is not. From tjreedy at udel.edu Wed Jul 2 20:27:19 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 02 Jul 2008 20:27:19 -0400 Subject: wrong md5 checksum In-Reply-To: <486be45d$0$859$ba4acef3@news.orange.fr> References: <486a16ef$0$885$ba4acef3@news.orange.fr> <486a5316$0$864$ba4acef3@news.orange.fr> <2-CdnaVu6892xvfVnZ2dnUVZ_gGdnZ2d@supernews.com> <486be45d$0$859$ba4acef3@news.orange.fr> Message-ID: kkwweett wrote: > >> >> A. an error in the software that computed the value for the web page, >> B. a transcription error in putting the checksum on the web page, >> C. accidental corruption of the file, or >> D. a deliberate attempt to substitute a file with a similar MD5 sum. >> > > It seems that the answer is probably B. But, according to the release > website manager, a mystery remains : > > http://mail.python.org/pipermail/python-3000/2008-July/014281.html Marcin Kowalczyk pointed out in a follow-up to the above that the replacement of 'a5' with 'b1' could have been part of a global search/replace that would have been correct everywhere else on the page. Thus case C. Barry remembers doing some such. Lesson. Take care with blind global replacements. From nicolas.pourcelot at gmail.com Sat Jul 19 16:13:40 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Sat, 19 Jul 2008 13:13:40 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> <6ebshqF67cpfU4@mid.uni-berlin.de> Message-ID: <5d6b8066-c941-4f0c-abea-20baed33b4ab@l64g2000hse.googlegroups.com> On 18 juil, 17:52, Marc 'BlackJack' Rintsch wrote: > On Fri, 18 Jul 2008 07:39:38 -0700, nicolas.pourcelot wrote: > > So, I use something like this in 'sheet.objects.__setattr__(self, > > name, value)': > > if type(value) == Polygon: > > ? ? for edge in value.edges: > > ? ? ? ? if edge is_in sheet.objects.__dict__.itervalues(): > > ? ? ? ? ? ? object.__setattr__(self, self.__new_name(), edge) > > > Ok, I suppose it's confused, but it's difficult to sum up. ;-) > > You are setting attributes with computed names? ?How do you access them? > Always with `gettattr()` or via the `__dict__`? ?If the answer is yes, why > don't you put the objects the into a dictionary instead of the extra > redirection of an objects `__dict__`? > Yes, I may subclass dict, and change its __getitem__ and __setitem__ methods, instead of changing objets __setattr__ and __getattr__... But I prefer >>> sheet.objects.A = Point(0, 0) than >>> sheet.objects["A"] = Point(0, 0) > Oh and the `type()` test smells like you are implementing polymorphism > in a way that should be replaced by OOP techniques. I wrote 'type' here by mistake, but I used 'isinstance' in my code. ;-) > If you make Point immutable you might be able to drop the "must not be referenced twice" requirement. Yes, but unfortunately I can't (or it would require complete redesign...) From Bill at SynectixLtd.com Sat Jul 12 10:14:06 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Sat, 12 Jul 2008 15:14:06 +0100 Subject: ..\..\Python-2.5.2\Include\pyport.h(117) : fatal error C1189: #error : "Python needs a typedef for Py_ssize_t in pyport.h." Message-ID: <2Y2dnWAl9dSwIeXVnZ2dnUVZ8u-dnZ2d@bt.com> When I try and compile using VS2003 for Release. Compiles fine for Debug. In a hurry (should be gardening). Any solution? TIA Bill From asmodai at in-nomine.org Fri Jul 4 01:31:14 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 4 Jul 2008 07:31:14 +0200 Subject: Freesoftware for auto/intelligent code completing in Python In-Reply-To: References: Message-ID: <20080704053113.GJ34192@nexus.in-nomine.org> -On [20080630 23:51], Ali Servet D?nmez (asd at pittle.org) wrote: >This could be an extension, a plugin, an Emacs mode, a new editor or >even a brand new huge all-fancy IDE, I don't care, but what am I >missing here? Vim's omnicomplete (CTRL-X CTRL-O). See :help omnifunc within vim. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Don't always think in a straight line... From omer at no-log.org Wed Jul 2 12:40:03 2008 From: omer at no-log.org (=?iso-8859-1?q?C=E9dric_Lucantis?=) Date: Wed, 2 Jul 2008 18:40:03 +0200 Subject: Trouble using pinckle In-Reply-To: <486ba8a4$0$11957$426a74cc@news.free.fr> References: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> <1ijgp2r.1j1k5xwwbtiwcN%pdorange@pas-de-pub-merci.mac.com> <486ba8a4$0$11957$426a74cc@news.free.fr> Message-ID: <200807021840.03888.omer@no-log.org> > > I'll also try the dictionnary method. > > My final idea was that a dictionnary would be perhaps simple in the > > future to save/load as XML and a parser. > XML ? What a strange idea ? Why is it so strange ? Many softs have their config in xml, and the xml.* modules are not that hard to use. It makes sense if you have a lot of config entries with nested sections. > > On a more global perspective, what are the best method to implement a > > simple config file with pyhton. > > Well... Python does have a couple of config-related packages, starting > with the one in the stdlib. You may want to find out if any of these > packages fits your needs before reinventing the wheel ? Right, ConfigParser should do the trick for simpler things. -- C?dric Lucantis From bedouglas at earthlink.net Sun Jul 20 21:43:03 2008 From: bedouglas at earthlink.net (bruce) Date: Sun, 20 Jul 2008 18:43:03 -0700 Subject: db question Message-ID: <229701c8ead3$1e9eecf0$0301a8c0@tmesa.com> Hi... simple test mysql cmd - select * from foo where dog like "%small%"; sql ="""select * from foo where dog like "%%%s%%" """ c.execute(sql, (var,)) the above doesn't work, and I can't seem to figure out how to display/print out the sql as i't actually been excuted, so I can see where the issue is. i've tried to "/" escape, as well as a few other things, now of which shed any light on the issue. haven't found any information via google either. the above works if i have something like sql="""select * from foo where dog=%s""" c.execute(sql,(var,)) so.. any help/pointers on what i've screwed up/missed would be helpful. thanks From alexnbryan at gmail.com Thu Jul 31 15:51:49 2008 From: alexnbryan at gmail.com (Alexnb) Date: Thu, 31 Jul 2008 12:51:49 -0700 (PDT) Subject: simple problem with lists I am just forgetting Message-ID: <18762181.post@talk.nabble.com> Lets say we have this list: funlist = ['a', 'b', 'c'] and lets say I do this: if funlist[4]: print funlist[4] I will get the exception "list index out of range" How can I test if the list item is empty without getting that exception? -- View this message in context: http://www.nabble.com/simple-problem-with-lists-I-am-just-forgetting-tp18762181p18762181.html Sent from the Python - python-list mailing list archive at Nabble.com. From d3vvnull at gmail.com Sun Jul 20 15:53:46 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Sun, 20 Jul 2008 14:53:46 -0500 Subject: question In-Reply-To: References: Message-ID: <170543c70807201253r5af5b54bv7e00a63aa7dc43fd@mail.gmail.com> I think the question was: why does anyone still use perl when Python is clearly the better language? On Sun, Jul 20, 2008 at 2:17 PM, Paddy wrote: > On Jul 20, 6:39 pm, wrote: > > Nobody any sensible answers. Too complicated I suppose! > > The sensible question was? > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From vaibhav4947 at gmail.com Mon Jul 7 02:10:51 2008 From: vaibhav4947 at gmail.com (vaibhav pol) Date: Mon, 7 Jul 2008 11:40:51 +0530 Subject: error in SimpleXMLRPCServer Message-ID: <18a05b120807062310m47d3def4k972c7d9af1fca421@mail.gmail.com> hi, I create a SimpleXMLRPCServer script which execute the command on server and return the result. code is below accessList=( 'test.org' ) class Server(SimpleXMLRPCServer.SimpleXMLRPCServer): def __init__(self,*args): SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self,(args[0],args[1])) def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) SimpleXMLRPCServer.SimpleXMLRPCServer.server_bind(self) def verify_request(self,request, client_address): if client_address[0] in accessList: return 1 else: return 0 class xmlrpc_registers: def __init__(self): self.python_string = string def clientfun(self,argument): try: cmd = argument (stdin,stdout,stderr)=popen3(cmd) stdin.close() value2=stdout.read() value3=stderr.read() stdout.close() stderr.close() output = {"stdout":value2,"stderr": value3} return output if __name__ == "__main__": if (len(sys.argv) == 3): try : servername=sys.argv[1] portnumber=int(sys.argv[2]) server = Server(servername,portnumber) server.register_instance(xmlrpc_registers()) server.serve_forever() except Exception,e: print "Root service is shutting down .." print str(e) else: print "Please provide <\"hostname or ip\"> <\"portnumber\">" this server side code i run in background using nohup from client when i call function it execute fine but after some time when i call it gives following error and server program killed. please help -------------- next part -------------- An HTML attachment was scrubbed... URL: From mrkafk at gmail.com Wed Jul 23 08:10:22 2008 From: mrkafk at gmail.com (mk) Date: Wed, 23 Jul 2008 14:10:22 +0200 Subject: Python Written in C? In-Reply-To: <6ejutcF6vgp3U4@mid.uni-berlin.de> References: <01095ee1-f981-4912-a191-06255a15080a@p31g2000prf.googlegroups.com> <6ejutcF6vgp3U4@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > An operation that most people avoid because of the penalty of "shifting > down" all elements after the deleted one. Pythonistas tend to build new > lists without unwanted elements instead. Which is exactly what I have done with my big lxml.etree, from which I needed to delete some elements: constructed a new tree only with elements I wanted. Sure, that works. There _is_ a minor side effect: nearly doubling memory usage while the operation lasts. 99% of the time it's not a problem, sure. > I can't even remember when I > deleted something from a list in the past. Still, doesn't that strike you as.. workaround? I half-got used to it, but it would still be nice not to (practically) have to use it. Enough whining. Gonna eat my quiche and do my Python. :-) From pavlovevidence at gmail.com Tue Jul 29 17:27:48 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 14:27:48 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: On Jul 29, 3:43 pm, "Heiko Wundram" wrote: > Am 29.07.2008, 18:30 Uhr, schrieb Carl Banks : > > > On Jul 29, 5:15 am, Heiko Wundram wrote: > >> I can't dig up a simple example from code I wrote quickly, but because > >> of the > >> fact that explicit comparisons always hamper polymorphism > > > I'm not going to take your word for it. Do you have code that > > demonstrates how "if x" improves polymorphism relative to simple > > explicit tests? > > As I wrote in the second reply email I sent, check out my integer set > recipe on ASPN (and to save you the search: http://code.activestate.com/recipes/466286/). Couple points: 1. Any container type that returns a length that isn't exactly the number of elements in it is broken. 2. The need for __nonzero__ in this case depends on a limitation in the language. 3. On the other hand, I will concede that sometimes calculating len is a lot more expensive than determining emptiness, and at a basic level it's important to avoid these costs. You have found a practical use case for __nonzero__. However, I'd like to point out the contrasting example of numpy arrays. For numpy arrays, "if x" fails (it raises an exception) but "if len(x)!=0" succeeds. The only sane advice for dealing with nonconformant classes like numpy arrays or your interger set is to be wary of nonconformances and don't expect polymorphism to work all the time. So I guess I'll concede that in the occasional cases with nonconformant classes the "if x" might help increase polymorphism a little. (BTW: here's another little thing to think about: the "if x" is useful here only because there isn't an explicit way to test emptiness without len.) Carl Banks From michael at stroeder.com Thu Jul 24 02:49:33 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 24 Jul 2008 08:49:33 +0200 Subject: Inserting cookies into a web session In-Reply-To: References: Message-ID: John Gordon wrote: > I'm developing a web application that needs a semi-persistent way to > store information. > > I've looked at some options such as writing entries to a database table > or creating small textfiles, but I'm not thrilled with anything I've come > up with so far. What's the problem? > Then a coworker suggested that I could just insert a cookie into the > current session, which would store whatever information I wanted. This > seems like a really good solution. That's what cookies are *for*, right? Before using cookies keep in mind that the cookies returned by the browser are not trustworthy! You have to validate the values each time. > But I've never worked with cookies before. Is there a Python package for > handling cookies? http://docs.python.org/lib/module-Cookie.html > And are there any back-end requirements? No. > I assume you > would have to be running a webserver that supports sessions. You can do this all within your web application. > Do you also > have to be running some sort of web container or servlet engine? No. Ciao, Michael. From JordanNealBerg at gmail.com Tue Jul 15 15:36:05 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Tue, 15 Jul 2008 12:36:05 -0700 (PDT) Subject: graphing lifelines References: Message-ID: There are several different modules for graphing in Python which you can find easily by searching, but to my knowledge none of them will simply take in a set of tuples and turn them into what you want, although I am sure that it is certainly possible to program a app that could do that for you... If you can't/don't want to program such an app and you don't have many data points, you could probably just cook one up using Photoshop/GIMP/ MSPaint, or whatnot (although clearly I could understand not wanting to do that for 100's of points)... sounds like an interesting project an auto lifeline maker that takes in data points...hmm From carbonimax at gmail.com Tue Jul 8 08:56:46 2008 From: carbonimax at gmail.com (Carbonimax) Date: Tue, 8 Jul 2008 05:56:46 -0700 (PDT) Subject: py2exe, PyQT, QtWebKit and jpeg problem References: Message-ID: <3eead611-60be-4ccd-bc9b-d62ef3b74578@8g2000hse.googlegroups.com> On Jun 29, 4:14 pm, yang.zenggu... at gmail.com wrote: > On 6?20?, ??11?04?, Carbonimax wrote: > > > hello > > > I have a problem with py2exe and QtWebKit : > > I make a program with a QtWebKit view. > > If I launch the .py directly, all images (jpg, png) are displayed but > > if I compile it with py2exe I have only png images. No jpg ! > > No error message, nothing. > > > Have you a solution ? Thank you. > > I have the same problem with you. I find a way to fix it: > 1. Copy Qt plugins to the directory: $YOUR_DIST_PATH/PyQt4/plugins; > 2. Copy qt.conf to youar dist directory; > 3. Edit qt.conf, change Prefix to $YOUR_DIST_PATH/PyQt4 > > Orit It work, thank you :) From jgardner at jonathangardner.net Thu Jul 17 16:02:57 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 17 Jul 2008 13:02:57 -0700 (PDT) Subject: x, = y (???) References: Message-ID: On Jul 17, 12:55?pm, kj wrote: > I still don't get it. ?If we write > > ? y ?= 'Y' > ? x, = y > > what's the difference now between x and y? ?And if there's no > difference, what's the point of performing such "unpacking"? > Try: y = "abc" x, = y You were unpacking y into ('Y',) From mensanator at aol.com Mon Jul 21 01:16:39 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 20 Jul 2008 22:16:39 -0700 (PDT) Subject: Python Written in C? References: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> Message-ID: <02065923-76b6-4b4e-a1a0-19ee8ac49c04@59g2000hsb.googlegroups.com> On Jul 20, 11:08?pm, "Dan Upton" wrote: > On Sun, Jul 20, 2008 at 11:51 PM, Mensanator wrote: > > On Jul 20, 10:05?pm, Stephen Johnson wrote: > >> > Carry bits? Who worries about carry bits when you have > >> > unlimited precision arithmetic? You want cool? > >> > THIS is cool: > > >> > j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2])) > >> > % xyz[1]**(k-1))/xyz[1]**(k-2) > > >> You call that "cool." I call it "unreadable." > > > Ok, but not in the sense that something like > > Scheme is unreadable as this is nothing but > > algebra (albeit complicaed). > > Scheme doesn't *have* to be unreadable... any more unreadable than any > other language when poorly documented/formatted, anyway. When I needed to whip up a variation on Ulam's Spiral recently, I went and got the Scheme version I wrote 4 years ago when I briefly toyed with Scheme and thought I'd just translate the plotting part to Python. Couldn't make any sense of it and ended up doing the Python version with Turtle Graphics. From karthikbalaguru79 at gmail.com Tue Jul 22 09:27:19 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Tue, 22 Jul 2008 06:27:19 -0700 (PDT) Subject: tkinter for my python program !! Message-ID: Hi, One of my python program needs tkinter to be installed to run successfully. I am using Redhat 9.0 and hence tried installing by copying the tkinter-2.2.2-36.i386.rpm alone from the CD 3 to my pc. But, it is not getting installed and is failing by throwing the below errors. Should i need to configure / install any specific files for resolving this issue ? [root at localhost karthik]# rpm -ivh tkinter-2.2.2-26.i386.rpm warning: tkinter-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key ID db42a 60e error: Failed dependencies: libtcl8.3.so is needed by tkinter-2.2.2-26.i386 libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 libtk8.3.so is needed by tkinter-2.2.2-26.i386 Any ideas ? Thx in advans, Karthik Balaguru From sjmachin at lexicon.net Sun Jul 13 21:13:11 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 13 Jul 2008 18:13:11 -0700 (PDT) Subject: Using Groups inside Braces with Regular Expressions References: <10284e46-1601-4269-a1a0-ef3831e9f85c@z66g2000hsc.googlegroups.com> Message-ID: <5428c947-56bd-4ab5-bfdd-2797b031d3f7@27g2000hsf.googlegroups.com> On Jul 14, 9:05 am, Chris wrote: Misleading subject. [] brackets or "square brackets" {} braces or "curly brackets" () parentheses or "round brackets" > I'm trying to delimit sentences in a block of text by defining the > end-of-sentence marker as a period followed by a space followed by an > uppercase letter or end-of-string. ... which has at least two problems: (1) You are insisting on at least one space between the period and the end-of-string (this can be overcome, see later). (2) Periods are often dropped in after abbreviations and contractions e.g. "Mr. Geo. Smith". You will get three "sentences" out of that. > > I'd imagine the regex for that would look something like: > [^(?:[A-Z]|$)]\.\s+(?=[A-Z]|$) > > However, Python keeps giving me an "unbalanced parenthesis" error for > the [^] part. It's nice to know that Python is consistent with its error messages. > If this isn't valid regex syntax, If? It definitely isn't valid syntax. The brackets should delimit a character class. You are trying to cram a somewhat complicated expression into a character class, or you should be using parentheses. However it's a bit hard to determine what you really meant that part of the pattern to achieve. > how else would I match > a block of text that doesn't the delimiter pattern? Start from the top down: A sentence is: anything (with some qualifications) followed by (but not including): a period followed by either 1 or more whitespaces then a capital letter or 0 or more whitespaces then end-of-string So something like this might do the trick: >>> sep = re.compile(r'\.(?:\s+(?=[A-Z])|\s*(?=\Z))') >>> sep.split('Hello. Mr. Chris X\nis here.\nIP addr 1.2.3.4. ') ['Hello', 'Mr', 'Chris X\nis here', 'IP addr 1.2.3.4', ''] From praveen.sunsetpoint at gmail.com Thu Jul 3 01:38:11 2008 From: praveen.sunsetpoint at gmail.com (Sallu) Date: Wed, 2 Jul 2008 22:38:11 -0700 (PDT) Subject: Email Validation with domain References: <873ams770b.fsf@benfinney.id.au> Message-ID: On Jul 2, 6:25?pm, Ben Finney wrote: > Sallu writes: > > validateEmail(msg) ?i wrote a script above it works fine > > Actually, no. It rejects a great many email addresses that are valid. > > > but it does not check for valid domain like .com .org .in how to > > validate with domain > > To validate a domain for delivery of email, check with the DNS by > requesting the A or MX record for that domain. > > To validate an email address, check with the mail server for that > domain by sending a message to the address. > > Neither of them should be "validated" by a regular expression. > > Please refer to RFC 3696 > described as "Recommended techniques for applications checking or > manipulating domain and other internet names". > > -- > ?\ ? ? ? ??Pinky, are you pondering what I'm pondering?? ?Wuh, I think | > ? `\ ? so, Brain, but wouldn't anything lose its flavor on the bedpost | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? overnight?? ?_Pinky and The Brain_ | > Ben Finney Thank you to all of you and clearing my idea.. From larudwer at freenet.de Fri Jul 25 11:52:11 2008 From: larudwer at freenet.de (Rüdiger Werner) Date: Fri, 25 Jul 2008 17:52:11 +0200 Subject: Python base distribution come with a validating XML parser? References: <4205c679-4a0e-41d6-8311-2e033b7b5e0d@j7g2000prm.googlegroups.com> Message-ID: > Hi, > > Basic XML questions, > > I have a .xml file I want to validate against a .xsd file... > > Does the Python base distribution come with a validating XML parser? > > I want to make sure the elements in my xml file vs. the elements > defined in my xsd are a match. > > I could parse both XML and xsd elements to lists and compare the > lists, but I imagine the validation process can do this too... > > Some of this is basic stuff - just a link to a site or doc is > sufficient. > > Thanks. I think you are looking for lxml http://codespeak.net/lxml/ From steve at REMOVE-THIS-cybersource.com.au Tue Jul 29 19:39:06 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 23:39:06 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> Message-ID: <009fa593$0$20313$c3e8da3@news.astraweb.com> On Tue, 29 Jul 2008 21:15:12 +0100, Matthew Woodcraft wrote: > Steven D'Aprano wrote: >> "if x" is completely type agnostic. You can pass an object of any type >> to it, and it will work. (Excluding objects with buggy methods, >> naturally.) > > There are many circumstances where if a parameter is None I'd rather get > an exception than have the code carry on with the 'empty container' > branch (and silently give me a meaningless result). Sure. The way I'd handle that is test for None at the start of the function, and raise an error there, rather than deal with it at some arbitrary part of the function body. -- Steven From trentm at activestate.com Mon Jul 28 12:55:49 2008 From: trentm at activestate.com (Trent Mick) Date: Mon, 28 Jul 2008 09:55:49 -0700 Subject: ActiveState Code (the new Python Cookbook) has been launched In-Reply-To: References: Message-ID: <488DFA15.9080407@activestate.com> Nick Craig-Wood wrote: > Trent Mick wrote: >> I happy to announce that ActiveState Code has been taken out of beta. >> This is the new site replacing the ASPN Cookbooks -- in particular the >> Python Cookbook. >> >> http://code.activestate.com/ > > Looks great and much faster than the old site! Thanks! > Mind telling us how it is implemented? I'm guessing python/django by > the url and the fact that you have python stuff on your home pages but > I could be wrong! Yup, it is a Django-based site -- a pleasure to work with, that. Using django-tagging, django-template-utils & universal feedparser (for hooking in Atom content for News section on home page), django-voting, python-markdown2 (for rendering comments, discussion/descriptions), recaptcha-client (for feedback when not logged in), pygments (for syntax coloring). I've just submitted the site to http://www.djangosites.org/ I hope to do some blog posts about some parts of the site soon and release the small re-usable "feedback" app I've put together for getting feedback on the site. Cheers, Trent -- Trent Mick trentm at activestate.com From fredrik at pythonware.com Wed Jul 23 08:19:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 14:19:06 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: <216dcee8-ad3d-4ae1-ac4a-4f4819775c7e@d1g2000hsg.googlegroups.com> References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> <216dcee8-ad3d-4ae1-ac4a-4f4819775c7e@d1g2000hsg.googlegroups.com> Message-ID: Ben Sizer wrote: > You should put the extern block around the #include call > rather than individual functions, as surely the C calling convention > should apply to everything within. Hello? Python's include files are C++ safe. I even posted a complete compiler session to show that I'm not making that up. From sjmachin at lexicon.net Fri Jul 18 07:10:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 18 Jul 2008 04:10:44 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> Message-ID: On Jul 18, 9:05 pm, oj wrote: > On Jul 18, 11:33 am, arnimavidyar... at gmail.com wrote: > > > > > Hi, > > > Hi, > > > I am taking a string as an input from the user and it should only > > contain the chars:L , M or R > > > I tried the folllowing in kodos but they are still not perfect: > > > [^A-K,^N-Q,^S-Z,^0-9] > > [L][M][R] > > [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > > > For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. > > > regards, > > SZ > > > The string may or may not have all the three chars. > > With regular expressions, [^LRM] matches a character that isn't L, R > or M. So: > > import re > > var = "LRLRLRLNR" > > if re.search(r'[^LRM]', var): > print "Invalid" Fails if var refers to the empty string. From jake at vapourforge.com Thu Jul 10 01:06:11 2008 From: jake at vapourforge.com (Jake Anderson) Date: Thu, 10 Jul 2008 15:06:11 +1000 Subject: python scalability In-Reply-To: <487590E6.7020004@gmail.com> References: <487590E6.7020004@gmail.com> Message-ID: <487598C3.9080306@vapourforge.com> Tim Mitchell wrote: > Hi All, > > I work on a desktop application that has been developed using python > and GTK (see www.leapfrog3d.com). We have around 150k lines of python > code (and 200k+ lines of C). We also have a new project manager with > a C# background who has deep concerns about the scalability of python > as our code base continues to grow and we are looking at introducing > more products. I am looking for examples of other people like us (who > write desktop apps in python) with code bases of a similar size who I > can point to (and even better talk to) to help convince him that > python is scalable to 300+ lines of code and beyond. I have looked at > the python success stories page and haven't come up with anyone quite > like us. One of my project managers questions is: "Are we the only > company in the world with this kind and size of project?" > I want to say no, but am having trouble convincing myself, let alone him. > > If you are involved in this kind of thing please get in touch with me. > > Thanks, > Tim > -- > http://mail.python.org/mailman/listinfo/python-list It'd be 1500k lines of C if not for the 150k of python ;-> From fredrik at pythonware.com Wed Jul 16 04:57:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 10:57:52 +0200 Subject: reading one byte from stdin In-Reply-To: <40DC41E9-DBFA-45F3-B155-92785AA9490B@fastsoft.com> References: <40DC41E9-DBFA-45F3-B155-92785AA9490B@fastsoft.com> Message-ID: Mark McDuff wrote: > I'm trying to read one byte from stdin, without the newline. > > If I try something like: > >>> import os, sys > >>> os.read(sys.stdin.fileno(),1) > > I can input a character, but then I have to press enter, which leaves a > newline character in the stdin buffer and requires two keypresses. Is > there any way to read only one keypress in a simple manner (i.e. no > curses)? in addition to the cookbook article Diez posted, there's also a FAQ entry about this: http://effbot.org/pyfaq/how-do-i-get-a-single-keypress-at-a-time.htm From robert.rawlins at thinkbluemedia.co.uk Fri Jul 18 12:12:39 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Fri, 18 Jul 2008 17:12:39 +0100 Subject: Unusual Exception Behaviour In-Reply-To: <1e6def2a-9c44-419e-a450-5fe596c5e3c0@j1g2000prb.googlegroups.com> References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> <8904.90077804333$1216313689@news.gmane.org> <006001c8e831$5c1487b0$143d9710$@rawlins@thinkbluemedia.co.uk> <1214.94685668058$1216317006@news.gmane.org> <1e6def2a-9c44-419e-a450-5fe596c5e3c0@j1g2000prb.googlegroups.com> Message-ID: <002901c8e8f1$1a00c6c0$4e025440$@rawlins@thinkbluemedia.co.uk> > The logging configuration functionality provided by fileConfig is all- > or-nothing, i.e. it does not support incremental configuration. > > Do you know if any libraries you depend on use fileConfig? > > If you use programmatic configuration only, and don't use fileConfig > at all, does everything work as expected? Vinay, I changed this over to programmatic configuration this afternoon and it works just great, all the logging I require, and my exceptions get thrown. :-D I have no idea if any of the librarys I use work from a file config, I'm certainly not aware of them doing so. This is really quite frustrating as I'd much rather use a conf file than work this programmatically. I get the feeling that it's because in the config file I was not attaching any handlers to the root logger, but I don't know. Robert From hv at tbz-pariv.de Wed Jul 2 09:24:47 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Wed, 02 Jul 2008 15:24:47 +0200 Subject: Scripting SAP GUI (Windows) In-Reply-To: <6d15tpFaec4U1@mid.individual.net> References: <6d15tpFaec4U1@mid.individual.net> Message-ID: <6d1dsvFb31rU2@mid.individual.net> I just got this link in a german newsgroup: http://pywinauto.openqa.org/ Seems to be what I was looking for. Nevertheless feedback still welcome. Thomas Guettler schrieb: > Hi, > > I need to script SAP GUI running on MS-Windows: > > Open SAP GUI window, if it is not already open, and then batch input > some keystrokes. > > The following solutions were found by google: > > - autohotkey: not preferred, since it has an own programming > language. This will slow down development. > - pyHook > - user pywin32 and SetWindowsHookEx > > I develop with python since seven years, but only on linux. > > Any hints? > > -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From basti.wiesner at gmx.net Sat Jul 5 19:26:05 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sun, 06 Jul 2008 01:26:05 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <9cae59d9-ead4-45bc-a980-2ac2e1616f9b@p25g2000hsf.googlegroups.com> Message-ID: Terry Reedy : > Mark Dickinson wrote: >> On Jul 5, 1:54 pm, Carl Banks wrote: > >> Part of the problem is a lack of agreement on what >> 'regular expression' means. > > Twenty years ago, there was. Calling a extended re-derived grammar > expression like Perl's a 'regular-expression' is a bit like calling a > Hummer a 'car' -- perhaps to hide its gas-guzzling behavior. Yet, to many programmers the Hummer is not only just a car, its _the_ car. Everything else is just silly, bloody old posix crap ;) (meaning, that pcres are often seen as true regular expressions, and everything else is referred to as "being somehow restricted") -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From ki4yjl at gmail.com Sat Jul 12 12:17:31 2008 From: ki4yjl at gmail.com (WDC) Date: Sat, 12 Jul 2008 09:17:31 -0700 (PDT) Subject: spam <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> Message-ID: <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> On Jul 11, 7:21?pm, Nobody Here wrote: > rickman wrote: > > spam > > No fucking shit, Sherlock, why double the volume by pointing out the obvious? Calm down you all. BTW I reported it, yo should too. From davidreynon at gmail.com Mon Jul 7 17:56:23 2008 From: davidreynon at gmail.com (korean_dave) Date: Mon, 7 Jul 2008 14:56:23 -0700 (PDT) Subject: How to make python scripts .py executable, not bring up editor Message-ID: >From command Prompt, i type in a script, "tryme.py". This, instead, brings up PythonWin editor and Interactive Window. Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) How do I make it so that the script runs? From basti.wiesner at gmx.net Sat Jul 5 04:12:05 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sat, 05 Jul 2008 10:12:05 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Paddy : > On Jul 4, 1:36?pm, Peter Otten <__pete... at web.de> wrote: >> Henning_Thornblad wrote: >> > What can be the cause of the large difference between re.search and >> > grep? >> >> grep uses a smarter algorithm ;) >> >> >> >> > This script takes about 5 min to run on my computer: >> > #!/usr/bin/env python >> > import re >> >> > row="" >> > for a in range(156000): >> > row+="a" >> > print re.search('[^ "=]*/',row) >> >> > While doing a simple grep: >> > grep '[^ "=]*/' input ? ? ? ? ? ? ? ? ?(input contains 156.000 a in >> > one row) >> > doesn't even take a second. >> >> > Is this a bug in python? >> >> You could call this a performance bug, but it's not common enough in real >> code to get the necessary brain cycles from the core developers. >> So you can either write a patch yourself or use a workaround. >> >> re.search('[^ "=]*/', row) if "/" in row else None >> >> might be good enough. >> >> Peter > > It is not a smarter algorithm that is used in grep. Python RE's have > more capabilities than grep RE's which need a slower, more complex > algorithm. FWIW, grep itself can confirm this statement. The following command roughly takes as long as Python's re.search: # grep -P '[^ "=]*/' input -P tells grep to use real perl-compatible regular expressions. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From mrkafk at gmail.com Thu Jul 17 13:10:47 2008 From: mrkafk at gmail.com (mk) Date: Thu, 17 Jul 2008 19:10:47 +0200 Subject: Unusual Exception Behaviour In-Reply-To: <8904.90077804333$1216313689@news.gmane.org> References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> <8904.90077804333$1216313689@news.gmane.org> Message-ID: > http://linux.byexamples.com/archives/365/python-convey-the-exception-traceba > ck-into-log-file/ >> if __name__=="__main__": >> try: >> main() >> except: >> print "Trigger Exception, traceback info forward to log file." >> traceback.print_exc(file=open("errlog.txt","a")) >> sys.exit(1) >> > > I've just given this solution a shot but I still seem to get the same > result, it suddenly starts dumping the log data to the command line, and > nothing gets printed in error.txt apart from the keyboard interrupt from > when I kill the application. That's seriously weird. What's your Python version and platform? On my Windows and Linux machines, with more recent Python versions the above trick works flawlessly. Check your environment, namely PYTHON* variables. There may be something causing this behaviour. Unset them. Check the first line of your scripts. If you're calling wrong Python interpreter (there may be more than one in the system for some reason), this may cause it. You could also try setting up PYTHONINSPECT environment variable or run the python interpreter with -i option before program filename, which drops you into an interactive shell upon exception or termination of a program. > For some reason the exceptions don't seem to be raised properly so obviously > aren't being caught at this higher level. > > So confusing. This behavior is seriously unusual for Python. Maybe you have some old / buggy version? From sjmachin at lexicon.net Tue Jul 1 17:49:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 1 Jul 2008 14:49:28 -0700 (PDT) Subject: Error from zipfile References: Message-ID: <0ee648ae-25d3-4c51-8b40-ba2f88612e4c@q27g2000prf.googlegroups.com> On Jul 2, 1:38 am, "Wesley Brooks" wrote: > Dear Users, > > I'm having a problem when trying to move script from Linux to Windows. > A zipfile opperation is failing with the message: > > "BadZipFile: File is not a zip file" > > I have a simple scripts that reads a zip file in the same way as any > other file into a string, then sends it across to a network where it > is saved as perusual into a file, then read in and processed by > zipfile. If "saved as per usual" means something like open('foo.zip', 'w').write(the_string) then this is highly likely to be your problem. Use 'wb'. Get into the habit of using the 'b' flag on binary files in your scripts (whether reading or writing) and they'll be much more portable. Something to check: on the Linux side, do wc -l foo.zip (that option's 'L'.lower()) to get the number of pseudo-lines in your zip file, and compare the sizes of the file on Linux and Windows. What do you see? HTH, John From wbsoft at xs4all.nl Sat Jul 19 16:18:46 2008 From: wbsoft at xs4all.nl (Wilbert Berendsen) Date: Sat, 19 Jul 2008 22:18:46 +0200 Subject: Determining when a file has finished copying In-Reply-To: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> Message-ID: <200807192218.46396.wbsoft@xs4all.nl> You could also copy to a different name on the same disk, and when the copying has been finished just 'move' (mv) the file to the filename the other application expects. E.g. QMail works this way, writing incoming mails in folders. Met vriendelijke groet, Wilbert Berendsen -- http://www.wilbertberendsen.nl/ "You must be the change you wish to see in the world." -- Mahatma Gandhi From sjmachin at lexicon.net Sun Jul 20 17:12:10 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 Jul 2008 14:12:10 -0700 (PDT) Subject: regex doubts References: <532965.570.qm@web54502.mail.re2.yahoo.com> <504d473e-375a-4111-ae2e-c06aaa37b096@p25g2000pri.googlegroups.com> Message-ID: On Jul 21, 12:30 am, Fredrik Lundh wrote: > John Machin wrote: > >> try "[LRM]+$" (an L or an R or an M, one or more times, all the way to > >> the end of the string). > > > Ummm ... with the default flag settings, shouldn't that be \Z instead > > of $ ? > > Why? The OP was reading input from a user; whether he gets a trailing > newline or not depends on the input method, and $ does the right thing > for all normal input methods. The goal as far as I can tell was to produce a pattern that matched one (maybe zero) or more instances of 'L', 'R', or 'M', and no other characters. >>> bool(re.match(r'[LRM]+\Z', 'MRL\n')) False >>> bool(re.match(r'[LRM]+$', 'MRL\n')) True >>> '\n' is an "other character". Perhaps you could explain what you mean by "$ does the right thing". From kw at codebykevin.com Tue Jul 8 13:41:43 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 08 Jul 2008 13:41:43 -0400 Subject: system tray for Tk In-Reply-To: References: Message-ID: <4873A6D7.308@codebykevin.com> Oguz Yarimtepe wrote: > Hi, > > Is there any binding that i can use for my python-tk application that > will show an icon at the system tray when the application runs which > will be able to be change during the process? > See http://wiki.tcl.tk/4090 for some ideas. This will require installing some Tcl/Tk packages, but they can probably be called easily enough from Python. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From socyl at 987jk.com.invalid Thu Jul 17 15:55:59 2008 From: socyl at 987jk.com.invalid (kj) Date: Thu, 17 Jul 2008 19:55:59 +0000 (UTC) Subject: x, = y (???) References: Message-ID: In Erik Max Francis writes: >kj wrote: >> I just came across an assignment of the form >> >> x, = y >> >> where y is a string (in case it matters). >> >> 1. What's the meaning of the comma in the LHS of the assignment? >It's unpacking a 1-tuple: > (x,) = y >The parentheses here are not necessary and are sometimes left out. I still don't get it. If we write y = 'Y' x, = y what's the difference now between x and y? And if there's no difference, what's the point of performing such "unpacking"? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From deets at nospam.web.de Wed Jul 2 14:49:16 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Jul 2008 20:49:16 +0200 Subject: Most efficient way to get pixelcolors of an image? In-Reply-To: <2c4e285c-f355-4e09-bd67-6de5656dc6c9@m36g2000hse.googlegroups.com> References: <2c4e285c-f355-4e09-bd67-6de5656dc6c9@m36g2000hse.googlegroups.com> Message-ID: <6d20tcFf205U1@mid.uni-berlin.de> defn noob schrieb: > i want to process a large number of images and store their respective > pixels in a matrix. > > what is the mostt efficient way of opening and checking them? > i doubt pygame is made for this purpose :) Au contaraire, it is. http://www.pygame.org/docs/ref/pixelarray.html Diez From ppearson at nowhere.invalid Mon Jul 7 11:29:57 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 7 Jul 2008 15:29:57 GMT Subject: Confused yet again: Very Newbie Question References: <13be8c54-3fa9-4a37-a0e6-45bb019bff7e@a1g2000hsb.googlegroups.com> <593b44b7-9a0a-4665-9926-19890d29eabe@2g2000hsn.googlegroups.com> Message-ID: <6der3lF25815U1@mid.individual.net> On Mon, 7 Jul 2008 05:41:22 -0700 (PDT), mcl wrote: [snip] > My use of classes is because I want two classes one for global > variables and one for global functions. One of the many lovely things about programming in the Python style is that very few things need to be global. When you make something global, you're in effect saying that it has no particular connection to anything else. If it has a connection to something else, then it should probably be combined into an object with that something else. -- To email me, substitute nowhere->spamcop, invalid->net. From asma61 at dsl.pipex.com Mon Jul 21 18:53:36 2008 From: asma61 at dsl.pipex.com (DaveM) Date: Mon, 21 Jul 2008 23:53:36 +0100 Subject: Python Written in C? References: Message-ID: On Mon, 21 Jul 2008 03:18:01 +0200, Michiel Overtoom wrote: >Many major text/word processing programs (Emacs, vi, MS-Word) are also >written in C. I thought Emacs was written in Lisp. DaveM From news at prodata.co.uk Tue Jul 1 09:43:52 2008 From: news at prodata.co.uk (John Dann) Date: Tue, 01 Jul 2008 14:43:52 +0100 Subject: Scope and program structure problems References: <486a210f$0$15472$426a34cc@news.free.fr> Message-ID: <2kck641lali2uenplo8rhp3l9qks3idl03@4ax.com> Many thanks for the repsonse - much appreciated. And sorry - yes I was probably compounding two separate issues here - the GUI one and the variable scope one. Maybe the wxPython list would be the best place to ask more about the GUI side of things. Then actually I can simplify my remaining question quite a lot - I know you've partly answered this already but let me just rephrase this: It must be commonplace to first use a variable or object within one function in a module and then want to use it again - perhaps still with the same value as in the first function - in a second function. So what's the recommended Python way round this? If I was using .Net then I'd be declaring the variables/objects explicitly and could set their scope according to how/where they were declared. But if the Python way is not to declare vars before use then this must create some problems for cross-function use. So it is best to declare such vars at the module level (ie outside of a function) and set eg to Null/None or to assign them with a keyword such as global or static (assuming that concept applies in Python) at first use inside a function or what? JGD From patf at well.com Mon Jul 28 18:33:29 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 15:33:29 -0700 (PDT) Subject: Download excel file from web? References: <6f6vhlFa7anrU1@mid.uni-berlin.de> Message-ID: On Jul 28, 3:29?pm, "Diez B. Roggisch" wrote: > p... at well.com schrieb: > > > > > On Jul 28, 3:00 pm, "p... at well.com" wrote: > >> Hi - experienced programmer but this is my first Python program. > > >> This URL will retrieve an excel spreadsheet containing (that day's) > >> msci stock index returns. > > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > >> Want to write python to download and save the file. > > >> So far I've arrived at this: > > >> [quote] > >> # import pdb > >> import urllib2 > >> from win32com.client import Dispatch > > >> xlApp = Dispatch("Excel.Application") > > >> # test 1 > >> # xlApp.Workbooks.Add() > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > >> # xlBook = xlApp.ActiveWorkbook > >> # xlBook.SaveAs(Filename='C:\\test.xls') > > >> # pdb.set_trace() > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> excel? > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> +25%2C+2008&export=Excel_IEIPerfRegional') > >> # test 2 - returns check = False > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > >> indexperf/excel? > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > >> xlApp = response.fp > >> print(response.fp.name) > >> print(xlApp.name) > >> xlApp.write > >> xlApp.Close > >> [/quote] > > > Woops hit Send when I wanted Preview. ?Looks like the html [quote] tag > > doesn't work from groups.google.com (nice). > > > Anway, in test 1 above, I determined how to instantiate an excel > > object; put some stuff in it; then save to disk. > > > So, in theory, I'm retrieving my excel spreadsheet with > > > response = urllib2.urlopen() > > > Except what then do I do with this? > > > Well for one read some of the urllib2 documentation and found the > > Request class with the method has_data() on it. ?It returns False. > > Hmm that's not encouraging. > > > I supposed the trick to understand what urllib2.urlopen is returning > > to me; rummage around in there; and hopefully find my excel file. > > > I use pdb to debug. ?This is interesting: > > > (Pdb) dir(response) > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > > 'code', ' > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > > 'readline', ' > > readlines', 'url'] > > (Pdb) > > > I suppose the members with __*_ are methods; and the names without the > > underbars are attributes (variables) (?). > > No, these are the names of all attributes and methods. read is a method, > for example. right - I got it backwards. > > > Or maybe this isn't at all the right direction to take (maybe there > > are much better modules to do this stuff). ?Would be happy to learn if > > that's the case (and if that gets the job done for me). > > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty > clear on this: > > """ > This function returns a file-like object with two additional methods: > """ > > And then for file-like objects: > > http://docs.python.org/lib/bltin-file-objects.html > > """ > read( ? [size]) > ? ? ?Read at most size bytes from the file (less if the read hits EOF > before obtaining size bytes). If the size argument is negative or > omitted, read all data until EOF is reached. The bytes are returned as a > string object. An empty string is returned when EOF is encountered > immediately. (For certain files, like ttys, it makes sense to continue > reading after an EOF is hit.) Note that this method may call the > underlying C function fread() more than once in an effort to acquire as > close to size bytes as possible. Also note that when in non-blocking > mode, less data than what was requested may be returned, even if no size > parameter was given. > """ > > Diez Just stumbled upon .read: response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ excel? priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul +25%2C+2008&export=Excel_IEIPerfRegional').read Now the question is: what to do with this? I'll look at the documentation that you point to. thanx - pat From mccredie at gmail.com Mon Jul 14 18:00:32 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 14 Jul 2008 15:00:32 -0700 (PDT) Subject: Bug when using with_statement with exec Message-ID: I think I'm going to create a new issue in Pythons issue database, but I wanted to run it by the news group first. See if I can get any useful feed back. The following session demonstrates the issue: Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> exec "def foo():\n return 0" # no ending newline works fine >>> foo() 0 >>> exec "def foo():\n return 1\n" # with an ending newline works fine >>> foo() 1 >>> from __future__ import with_statement >>> exec "def foo():\n return 2\n" # with an ending newline works fine >>> foo() 2 >>> exec "def foo():\n return 3" # without an ending new line... breaks Traceback (most recent call last): File "", line 1, in File "", line 2 return 3 ^ SyntaxError: invalid syntax If I create a function by using exec on a string and _don't_ end the string with a new-line it will work just fine unless I "from __future__ import with_statement". I can imagine that it is probably a good practice to always end function body's with a new-line, but the requirement should be consistent and the syntax error text could be a _little_ more descriptive (and flag something other than the 2nd to last character). Note that you don't need to be in the interpreter to reproduce this issue. I searched python's issue database and didn't see anything similar to this. If there is already an issue related to this, please point me to it... or better yet, let me know how you found it. Matt From castironpi at gmail.com Thu Jul 24 13:34:40 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 24 Jul 2008 10:34:40 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> Message-ID: <24197170-ac41-4cec-8056-6b0ffbb3483d@x29g2000prd.googlegroups.com> On Jul 24, 11:49?am, "Sebastian \"lunar\" Wiesner" wrote: > Torsten Bronger : > > > > > Hall?chen! > > > Bruno Desthuilliers writes: > > >> Torsten Bronger a ?crit : > > >>> Bruno Desthuilliers writes: > > >>>> [...] > > >>>> How would you handle this case with an implicit 'self' : > > >>>> class Foo(object): > >>>> ? ?pass > > >>>> def bar(self): > >>>> ? ?print self > > >>>> Foo.bar = bar > > >>> Just like this. ?However, the compiler could add "self" to > >>> non-decorated methods which are defined within "class". > > >> What's defined within classes are plain functions. It's actually > >> the lookup mechanism that wraps them into methods (and manage to > >> insert the current instance as first argument). > > > And why does this make the implicit insertion of "self" difficult? > > I could easily write a preprocessor which does it after all. > > Who said, that it would be "difficult"? ?He just corrected your statement > about definitions inside a class, and did not make any assumption about > making "self" implicit. > > I'd assume, that making self implicit wouldn't be that difficult to assume. > But does the fact, that it could easily be done, alone mean, that it > _should_ be done? ?The explicit "self" was a design decision, that can't > really be judged by technical arguments from implementation side. ?Its a > discussion about design from a programmers point of view ... > > -- > Freedom is always the freedom of dissenters. > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? (Rosa Luxemburg) I don't think you can infer from 'explicit is better than implicit' that 'the more explicit the better'. For instance, we don't use: python.callbyvalue.foo( bar, 1, 2 ) python.callbyref.foo2( bar, x, y ) or further: foo( byref bar, byval 1, byval 2 ) foo2( byref bar, byref x, byref x ) though some languages do. Python doesn't do that much implicity, like copying, with the exception of copying strings, which some string functions do, such as lower, replace, strip. (Does slicing return a new string?) What is the most surprisingly implicit behavior in Python? What is the most explicit? From joemystery123 at gmail.com Mon Jul 14 22:08:26 2008 From: joemystery123 at gmail.com (joe shoemaker) Date: Mon, 14 Jul 2008 22:08:26 -0400 Subject: Python pack and unpack question Message-ID: <372de840807141908y501d04baxccc09701d439e555@mail.gmail.com> If you have the following: data = unpack('>L', sock.recv(4)) Does this line of code means that incoming data is big endian and unpack it to endianess of local machine? If local machine is little endian, then big endian is automatically converted to little endian format? thank you. From larry.bates at websafe.com` Wed Jul 16 22:19:53 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 16 Jul 2008 21:19:53 -0500 Subject: Framework recommendations for web service? In-Reply-To: References: Message-ID: Phillip B Oldham wrote: > We're looking at the next phase of development for our webapp, and the > main focus will be to move the core from the app to a web service so > other systems can use the data we've gathered (we're thinking along > the lines of the XML API of Highrise from 37Signals). > > Its possible that we'll extend the service to allow access via vanilla > XML, JSON, and YAML at some point, however we've decided to use > Facebook's Thrift for connectivity initially to support as many techs > as possible and also because our web interface for the app is written > in PHP. > > As we're extracting the core we'll be translating it to Python to make > use of the wealth of well-structured libraries and hopefully make the > project shorter. However, we've hit a snag in choosing a framework > around which to rebuild the service. > > It seems the more popular frameworks (django, turbogears) are all > focused on providing web content. Since our core will be using thrift > to communicate, we don't need templating, feeds, admin pages (django), > or ajax (turbogears). > > What we *do* need is a lightweight, simple framework that will allow > us to create a RESTful interface and throw code together fast. We'll > probably go with SQLObject (unless we can extract the ORM from django > - lazy evaluation would be very useful), and we're just looking for > something fast and light to sit between that and the thrift interfaces > we'll create. > > So, can anyone suggest a lightweight python framework which just does > the essentials? You want thin and fast with little cruft and a focus on interfaces, look at Twisted. -Larry From max at alcyone.com Wed Jul 30 02:36:20 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 23:36:20 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> Message-ID: Russ P. wrote: > On Jul 29, 11:09 pm, Erik Max Francis wrote: > >> I'm getting this sneaking suspicion that you guys are all putting us on. > > As I said in an earlier post, I realize that this would only work if > there were only one copy of "empty" (as there is only one copy of > "None"). I don't know off hand if that is feasible or not. It's only feasible if you change what `is` means for this one bizarre use case, which isn't a good idea. > You reply reeks of the kind of pedantic snobbishness that makes me > sick. Well, if understanding what the `is` operator means is pedantic snobbishness, then hey, go right ahead. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis The doors of Heaven and Hell are adjacent and identical. -- Nikos Kazantzakis From mva.led at gmail.com Thu Jul 10 13:20:48 2008 From: mva.led at gmail.com (Manuel Vazquez Acosta) Date: Thu, 10 Jul 2008 13:20:48 -0400 Subject: Determining when a file has finished copying In-Reply-To: <20080710014412.GA29399@cskk.homeip.net> References: <20080710014412.GA29399@cskk.homeip.net> Message-ID: <487644F0.9070906@gmail.com> Cameron Simpson wrote: > On 09Jul2008 15:54, Ethan Furman wrote: >> The solution my team has used is to monitor the file size. If the file >> has stopped growing for x amount of time (we use 45 seconds) the file is >> done copying. Not elegant, but it works. > > If you know that files appear in sequence (a single serial upload > process, not multiple uploaders) you can augument this with a check > that an additional file has started to upload, ergo the current file > has finished. Of course, only you can decide if this might be relied upon. > > Cheers, Hum, what about the last file in the sequence? I think polling file's size maybe a good indicator, as Ethan proposed. Best regards, Manuel. From larry.bates at websafe.com` Tue Jul 15 14:46:14 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 13:46:14 -0500 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: Victor Noagbodji wrote: > Hello, > > what's the difference between these two statement? And which one should one use? > if name ... Will be false if: name is an integer == 0 name is a float == 0 name is an empty string name is an empty list name is an empty dictionary There are others, but you get the idea. If name is not None: Is false only if name is not None but will be true for all the others. -Larry From jr9445 at ATT.COM Tue Jul 1 11:06:49 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Tue, 1 Jul 2008 10:06:49 -0500 Subject: How make regex that means "contains regex#1 but NOT regex#2" ?? In-Reply-To: References: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Reedick, Andrew > Sent: Tuesday, July 01, 2008 10:07 AM > To: seberino at spawar.navy.mil; python-list at python.org > Subject: RE: How make regex that means "contains regex#1 but NOT > regex#2" ?? > > Match 'foo.*bar', except when 'not' appears between foo and bar. > > > import re > > s = 'fooAAABBBbar' > print "Should match:", s > m = re.match(r'(foo(.(?!not))*bar)', s); > if m: > print m.groups() > > print > > s = 'fooAAAnotBBBbar' > print "Should not match:", s > m = re.match(r'(foo(.(?!not))*bar)', s); > if m: > print m.groups() > > > == Output == > Should match: fooAAABBBbar > ('fooAAABBBbar', 'B') > > Should not match: fooAAAnotBBBbar > Fixed a bug with 'foonotbar'. Conceptually it breaks down into: First_half_of_Regex#1(not Regex#2)(any_char_Not_followed_by_Regex#2)*Second_half_of_Regex#1 However, if possible, I would make it a two pass regex. Match on Regex#1, throw away any matches that then match on Regex#2. A two pass is faster and easier to code and understand. Easy to understand == less chance of a bug. If you're worried about performance, then a) a complicated regex may or may not be faster than two simple regexes, and b) if you're passing that much data through a regex, you're probably I/O bound anyway. import re ss = ('foobar', 'fooAAABBBbar', 'fooAAAnotBBBbar', 'fooAAAnotbar', 'foonotBBBbar', 'foonotbar') for s in ss: print s, m = re.match(r'(foo(?!not)(?:.(?!not))*bar)', s); if m: print m.groups() else: print == output == foobar ('foobar',) fooAAABBBbar ('fooAAABBBbar',) fooAAAnotBBBbar fooAAAnotbar foonotBBBbar foonotbar ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA621 From robert.kern at gmail.com Mon Jul 7 19:59:48 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 07 Jul 2008 18:59:48 -0500 Subject: complex representation In-Reply-To: References: Message-ID: DSM wrote: > From the nothing-is-so-trivial-it's-not-worth-a-usenet-post file: > > Shouldn't the default representation of complex numbers be like that of > floats? That is, have a decimal point? > > >>> 1 > 1 > >>> 1.0 > 1.0 > >>> 1j > 1j > >>> 1.0j > 1j > >>> 1.0+1.0j > (1+1j) > > > In the relevant bit of floatobject.c, there's a comment explaining that > 1.0 isn't accidental: > > /* Subroutine for float_repr and float_print. > We want float numbers to be recognizable as such, > i.e., they should contain a decimal point or an exponent. > However, %g may print the number as an integer; > in such cases, we append ".0" to the string. */ > > ISTM the same reasoning applies equally to complex numbers. Not necessarily. The reason that having floats always have a decimal point is desirable is to ensure roundtripping through eval(repr(x)). The j is sufficient for complexes. There are no complex integers to confuse it with. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From Russ.Paielli at gmail.com Wed Jul 30 03:18:48 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 30 Jul 2008 00:18:48 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> Message-ID: <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> On Jul 30, 12:03 am, Heiko Wundram wrote: > Am Mittwoch, 30. Juli 2008 08:30:48 schrieb Russ P.: > > > On Jul 29, 11:09 pm, Erik Max Francis wrote: > > > I'm getting this sneaking suspicion that you guys are all putting us on. > > > As I said in an earlier post, I realize that this would only work if > > there were only one copy of "empty" (as there is only one copy of > > "None"). I don't know off hand if that is feasible or not. > > > You reply reeks of the kind of pedantic snobbishness that makes me > > sick. > > I can understand (and pretty much sympathise) that you get this kind of reply, > simply because the point you and Carl Banks (formulated somewhat differently) > put up has been answered again and again (in this thread), and I can only > repeat it once more: > > __nonzero__(), i.e. the "cast" to boolean, is THE WAY to test whether a > container is empty or not. Like this design decision, or don't like it, but > the discussion is not going to go anywhere unless you concede that there is a > (very explicit!) way to test for non-emptiness of a container already, and > you're currently simply discussing about adding/using syntactic sugar > (different means of expressing the test) to suit your own personal taste > better. Anyway, check the documentation for __nonzero__(): if the object > doesn't implement that, but implements __len__(), the interpreter "replaces" > the __nonzero__() test by __len__()>0, so I guess someone in the design > department must've seen it logical for the truth value of a container to > express the test "len(x)>0" at some point in time to make this interpretation > for the truth value of a container. > > There cannot be an argument about missing/misplaced functionality (that's what > you make it sound like), if the functionality for doing what you want to do > is there and you simply don't like the syntax, which I can somewhat relate to > because style is a personal thing, even though I don't see either points made > by you or Carl Banks, because implicit casting to bool is so common in pretty > much every programming language to test for "truth" of an object, and IMHO > it's completely logical to extend that idea to containers to mean > empty/non-empty. > > Eric Max Francis tried to explain why your syntactic "enhancement" would come > at a much greater price than its worth, and he's absolutely right in that, as > it's an abuse of the "is" operator, but again, that's a somewhat different > point. It changes nothing about the fact that all this discussion centers > around something that is a non-point, but simply a matter of personal taste. > > -- > Heiko Wundram Oh, Lordy. I understand perfectly well how boolean tests, __len__, and __nonzero__ work in Python. It's very basic stuff. You can quit patronizing me (and Carl too, I'm sure). The point that you seem to be missing, or refuse to acknowledge for some reason, is that "if x" can be mistakenly applied to any object when the programmer thinks that x is a list -- and the programmer will receive no feedback on the error. I have made errors like that, and I could have saved some time had I used an "empty" method that only applies to a list or other sequence. Is that an important issue? I don't know. I'm not claiming it is. But you cannot just sweep it away as nothing. From vinay_sajip at yahoo.co.uk Sun Jul 20 09:51:36 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Sun, 20 Jul 2008 06:51:36 -0700 (PDT) Subject: Unusual Exception Behaviour References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> <8904.90077804333$1216313689@news.gmane.org> <006001c8e831$5c1487b0$143d9710$@rawlins@thinkbluemedia.co.uk> <1214.94685668058$1216317006@news.gmane.org> <1e6def2a-9c44-419e-a450-5fe596c5e3c0@j1g2000prb.googlegroups.com> Message-ID: <1317c3ed-1bfe-4fc2-b2f2-9dba13a28b04@m3g2000hsc.googlegroups.com> On Jul 18, 5:12 pm, "Robert Rawlins" wrote: > > This is really quite frustrating as I'd much rather use a conf file than > work this programmatically. I get the feeling that it's because in the > config file I was not attaching any handlers to the root logger, but I don't > know. > There's no reason why not having a handler for the root logger would cause any particular problem. For example, the following script: #- start of logconftest.py ------------------ import logging, logging.config logging.config.fileConfig("log.conf") app_logger = logging.getLogger("application") sa_logger = logging.getLogger("sqlalchemy") loggers = [app_logger, sa_logger] def func1(): raise Exception("Exception from func1") def func2(): raise TypeError("TypeError from func2") def func3(): raise ValueError("ValueError from func3") funcs = [func1, func2, func3] for x in range(10): try: f = funcs[x % 3] f() except Exception, e: loggers[x % 2].exception("%d. Problem in %s", x, f.__name__) #- end of logconftest.py -------------------- together with the following configuration file (almost the same as yours): ;-- start of log.conf ----------------------- [loggers] keys=root,application,sqlalchemy [handlers] keys=hand01,hand03 [formatters] keys=form01 [logger_root] level=DEBUG handlers= [logger_application] level=DEBUG handlers=hand01 qualname=application [logger_sqlalchemy] level=DEBUG handlers=hand03 qualname=sqlalchemy [handler_hand01] class=handlers.RotatingFileHandler level=DEBUG formatter=form01 args=('application.log', 'a', 800000, 5) [handler_hand03] class=handlers.RotatingFileHandler level=DEBUG formatter=form01 args=('sqlalchemy.log', 'a', 800000, 5) [formatter_form01] format=%(asctime)s %(filename)s %(lineno)d %(levelname)-8s %(message)s datefmt= class=logging.Formatter ;-- end of log.conf ------------------------- gives the following output: -- start of application.log ----------------- 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 0. Problem in func1 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 11, in func1 raise Exception("Exception from func1") Exception: Exception from func1 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 2. Problem in func3 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 17, in func3 raise ValueError("ValueError from func3") ValueError: ValueError from func3 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 4. Problem in func2 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 14, in func2 raise TypeError("TypeError from func2") TypeError: TypeError from func2 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 6. Problem in func1 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 11, in func1 raise Exception("Exception from func1") Exception: Exception from func1 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 8. Problem in func3 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 17, in func3 raise ValueError("ValueError from func3") ValueError: ValueError from func3 -- end of application.log ------------------- -- start of sqlalchemy.log ------------------ 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 1. Problem in func2 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 14, in func2 raise TypeError("TypeError from func2") TypeError: TypeError from func2 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 3. Problem in func1 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 11, in func1 raise Exception("Exception from func1") Exception: Exception from func1 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 5. Problem in func3 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 17, in func3 raise ValueError("ValueError from func3") ValueError: ValueError from func3 2008-07-20 14:47:05,608 logconftest.py 26 ERROR 7. Problem in func2 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 14, in func2 raise TypeError("TypeError from func2") TypeError: TypeError from func2 2008-07-20 14:47:05,625 logconftest.py 26 ERROR 9. Problem in func1 Traceback (most recent call last): File "C:\Temp\logconftest.py", line 24, in f() File "C:\Temp\logconftest.py", line 11, in func1 raise Exception("Exception from func1") Exception: Exception from func1 -- end of sqlalchemy.log -------------------- which is, from a quick scan, the expected result - all the expected exceptions are thrown. Note the absence of any handlers on the root logger. Regards, Vinay Sajip From roy at panix.com Thu Jul 3 22:26:57 2008 From: roy at panix.com (Roy Smith) Date: Thu, 03 Jul 2008 22:26:57 -0400 Subject: Testing for an empty list References: <18268092.post@talk.nabble.com> Message-ID: In article , claird at lairds.us (Cameron Laird) wrote: > In article , > Matthew Fitzgibbons wrote: > >Alexnb wrote: > >> Okay this is a simple question I just don't know how. If I have a list, > >> say: > >> > >> funList = [] > >> > >> and after a while something possible should have been appended to it, but > >> wasn't. How can I test if that list is empty. > > > >if not funList: > > do_something() > . > . > . > It's also perfectly legitimate--and arguably even more > precise--to write > > if funList == []: > do_something() Any of these will be true for an empty list and false for a non-empty list: not funList len(funList) == 0 funList == [] Where they differ is how they behave for values of funList which are not lists. For example, if you did funList = (), then the first two would be true and the last one false. If you did funList = 0, the first and last would be true, and the middle one would raise an exception. The point is that if you're *sure* the item in question is going to be a list, then any of them are pretty much as good as any other. If it's a parameter that's being passed into a routine, so you can't be sure what type it is, then you should be thinking a little harder about how flexible you want to be. From g.threepwood at gmail.com Thu Jul 17 17:48:45 2008 From: g.threepwood at gmail.com (C Martin) Date: Thu, 17 Jul 2008 14:48:45 -0700 (PDT) Subject: Using Tcl extensions with Python? Message-ID: <6f09cdf7-1156-4f41-af5f-c8e5b99eab2d@b1g2000hsg.googlegroups.com> How do you setup a Tcl extension to be accessible through Python? I understand that I'll have to use native Tcl calls to use it (tk.call() etc), but I can't figure out where to put the files or how to initialize them so I can call them. The package I would like to use is TkPNG: http://www.muonics.com/FreeStuff/TkPNG/ Thanks. From gnuarm at gmail.com Fri Jul 11 13:12:44 2008 From: gnuarm at gmail.com (rickman) Date: Fri, 11 Jul 2008 10:12:44 -0700 (PDT) Subject: spam References: <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> Message-ID: <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> spam From hyh_david at hotmail.com Thu Jul 17 15:18:15 2008 From: hyh_david at hotmail.com (hyh_david at hotmail.com) Date: Thu, 17 Jul 2008 12:18:15 -0700 (PDT) Subject: wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal Message-ID: paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal accept)(www all-wholesaler com)paypal wholesale adidas sneaker(paypal ... From rogerkolsson at yahoo.co.uk Sun Jul 27 05:02:46 2008 From: rogerkolsson at yahoo.co.uk (rogerkolsson at yahoo.co.uk) Date: Sun, 27 Jul 2008 02:02:46 -0700 (PDT) Subject: Rifle & Ammunition Retail Store - Sportsman, Wildlife and Outdoor Supply Message-ID: Giuen Interpose & Outright Company ? Huntingrifle, Ammunition, Optics, Navigation ? Surplus Rifle Sale ? Pre-Owned Rifles ? Precision Rifle - Pistol A New Generation Outright Company begun in 2008 the funding for a battlefield data link that projected data onto a computer screen inside for example vehicles and inside the tanks. A system mated up with vehicle sets permanent to the base top-of-the-line included in the Inter-Vehicle Information System, a simple system for trading data, it presented the crew with a comprehensive overview of the battlefield, and converted hard-won reconnaissance information into general knowledge in a matter of seconds. No longer was data on a developing engagement limited to a harried and distracted unit commander. Now sergants knew everything the colonel did, and information was still the most valuable commodity known to man. The funding for that equipment on the agent exchange management for the obvious reason that it was too expensive to transport it all back and forth was yet not in harbour to the full at the end of 2007, however it still crapped out in a hurry to bring great benefit for the coming. Machines that did things at the bidding of others, to be thrown away when convenient and mass produce of such systems is neither anymore the mission he would welcome anywhere at all, this is a system that could work in helicopters with skilled computers in the modern age as well. He might have some position in the expanding unit government, security or intelligence, probably, with a comfortable office and a sizable stipend, able finally to settle down in peace and safety. However it takes to make a successful launch, and anyway with the newest variant of the system which meet the proper protective measures with a computerized database, divisions aided as always. Perhaps, it didn?t really matter. Conditions was good enough that such a person would be spotted. They will make their moves to continue their missions full of assurance to all. Their first mission briefing to request for support was just now getting started in a big way in advance of the main force in traditional working relationship on national defense and allied parnerships more substantial. The security detatchment made official was expect for the information in detailed reports and heading more precise the exact performance of every subsystem. Exactly what they?d been designed to do can neverthless be fully briefed in other than character and integrity at this time on industry routinely produced all manner of specialized products most for strategic partnership respectfully request information. Hummer H2 2004 at Dealership in Sweden Giuen Holding Ltd. Int. Call: +46 (0) 705474830 Hollywood NetBook ? Shopping Astore Sports http://astore.amazon.com/entertainmens-20 International Yatcht Trade http://www.rapidsellers.com/molsson3/ Janine Cabriore Powertriumph www.rapidsellers.com/molsson3/contact.asp Giuen Holding Ltd.? Export & Import Public Form http://publishing.yudu.com/Freedom/Akx6s/G1public/ Munifus Landmark Estate ? Prospect: http://publishing.yudu.com/Freedom/Ak8i8/DevelopmentProject/ Giuen Interpose & Outright Company ? Security ? Hunting - Equipment http://www.impactguns.com/cgi-bin/affiliates/clickthru.cgi?id=Outright From larry.bates at websafe.com` Mon Jul 14 21:04:14 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 14 Jul 2008 20:04:14 -0500 Subject: Method behavior for user-created class instances In-Reply-To: <42433fcd-fcdc-4f42-a427-c28241734b7c@z66g2000hsc.googlegroups.com> References: <42433fcd-fcdc-4f42-a427-c28241734b7c@z66g2000hsc.googlegroups.com> Message-ID: crazychimp132 at gmail.com wrote: > Greetings. > > I am looking for a way to achieve method behavior for a class I > created. That is, it has a __call__ method, so can be called like a > function. But I also want it to be treated as a method when it appears > in a class body. > > Eg. > > class foo: > def __call__(self, inst): pass > > class bar: > meth = foo() > > such that bar().meth() will not raise an exception for too few > arguments (because the inst argument in foo.__call__ is implicitly set > to the bar instance). I know this has to do with writing the __get__ > method of foo, but I am wondering if there is perhaps some class I can > just inherit from to get the proper __get__, which behaves identically > to that of regular Python functions. The need for this arises out of > the implementation of a function decorator as a class. > > Thanks. While it is not clear "why" you would want this, I believe this works. If not, take a look at staticmethods or classmethods, they might work for you. >>> class foo(object): ... def __call__(self, inst): ... print "foo.__call__", inst ... >>> class bar: ... def __init__(self): ... self.foo = foo() ... self.meth = self.foo.__call__ ... >>> b = bar() >>> b.meth(1) foo.__call__ 1 -Larry From jonas at codeazur.com.br Thu Jul 3 22:30:22 2008 From: jonas at codeazur.com.br (Jonas Galvez) Date: Thu, 3 Jul 2008 23:30:22 -0300 Subject: ANN: XML builder for Python In-Reply-To: <486D48BF.3050007@livinglogic.de> References: <486C5CA1.3080105@behnel.de> <486C5D63.5030407@behnel.de> <486D22CF.3000505@behnel.de> <486D48BF.3050007@livinglogic.de> Message-ID: <10df03a30807031930h2b71eb9bu811fc92c8e366037@mail.gmail.com> Walter D?rwald wrote: > Of course the node constructor could append the > node to the currently active element. However there > might be cases where you want to do something else > with the newly created node, so always appending the > node is IMHO the wrong thing. Unless you're using it as a templating engine of sorts, much like Ruby's builder used in Rails. Which is exactly what I'm trying to get at. I don't want to store the tree in any way or be able to modify it afterwards, I just want to generate the XML as the block is executed. Using ElementTree as suggested previously might be a good solution if you want to preserve what you've generated, tho. --Jonas Galvez From martin at v.loewis.de Fri Jul 4 16:49:58 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 04 Jul 2008 22:49:58 +0200 Subject: Can't get Python for Windows to run In-Reply-To: References: <486E4125.5080201@timgolden.me.uk> Message-ID: <486e8cf6$0$5679$9b622d9e@news.freenet.de> > Is it worth flagging as an issue somewhere the fact that the pywin > installer assumes a particular structure for the start menu No. This is the first time in several years that this was reported, and chances that this gets fixed in the upcoming years are very low, unless a patch gets contributed. (IOW, I couldn't care less about implementing it myself, and find installers annoying that ask too many questions). In any case, try installing with msiexec /i 'ProgramMenuFolder=C:\Documents and Settings\All Users\StartMenu\Programs\Programming' or some such. Regards, Martin From xng at xs4all.nl Mon Jul 21 10:11:03 2008 From: xng at xs4all.nl (Martin P. Hellwig) Date: Mon, 21 Jul 2008 16:11:03 +0200 Subject: Python Written in C? In-Reply-To: <488473b7$0$3470$426a74cc@news.free.fr> References: <488473b7$0$3470$426a74cc@news.free.fr> Message-ID: <488498f0$0$15075$e4fe514c@dreader28.news.xs4all.nl> Bruno Desthuilliers wrote: > giveitawhril2008 at gmail.com a ?crit : > (snip clueless nonsense) > > Surely a troll... No one on earth can be *that* clueless. I disagree he has upper management written all over him. -- mph From mmaccana at au1.ibm.com Wed Jul 23 01:47:18 2008 From: mmaccana at au1.ibm.com (Mike MacCana) Date: Wed, 23 Jul 2008 15:47:18 +1000 Subject: Proper way to query user and group database on a Unix host? Message-ID: <1216792038.7380.7.camel@mmaccana-laptop> Hi folks, What's the proper way to query the passwd and group database on a Unix host? I'd like to fetch the users in a group (obviously from name services), but my many varied searches can't find any reference of someone ever looking up users on a Unix system, just NT. Weird, I know. Currently I'm calling the getent command, which works well enough, but surely there's a more Pythonic method of looking up OS user and group data ... ## Get the full group database entry, leave just the user list, and split the list on comma groupname=users groupsusers = commands.getoutput('getent group '+groupname).split(':',-1)[3].split(',') Cheers, Mike ________________________________________________ Mike MacCana Technical Specialist Australia Linux and Virtualisation Services IBM Global Services Level 14, 60 City Rd Southgate Vic 3000 Phone: +61-3-8656-2138 Fax: +61-3-?8656-2423 Email: mmaccana at au1.ibm.com From mail at timgolden.me.uk Tue Jul 22 04:09:19 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 22 Jul 2008 09:09:19 +0100 Subject: Missing sqlite3.h Error when Building Debug Python -- Windows Vista In-Reply-To: References: <048b8df4-8468-47a1-ae15-d84ca9d43e0a@y38g2000hsy.googlegroups.com> Message-ID: <488595AF.1070205@timgolden.me.uk> Bev in TX wrote: > Thanks for letting me know about this. I installed Subversion and > tried to make the build work like that, but it fails. [... snip problems ...] I'm afraid I'm not using VS 2005, nor Vista, nor 64-bit, so I hope someone else can help. If you don't get any take-up here try the python-win32 list; there may be people there who don't follow this (rather higher volume) list. TJG From davideyork at gmail.com Fri Jul 25 20:34:09 2008 From: davideyork at gmail.com (David York) Date: Fri, 25 Jul 2008 17:34:09 -0700 Subject: Porting python to C++ Message-ID: <38c9cdb10807251734v3a827aaah86c379ebda92bc9a@mail.gmail.com> Hello, I'm a longtime lurker of python-list, python-C++ and a couple of others. I have a commercial project being prototyped in Python, brought to a very fine level of completion and which needs to be ported to C++. I would like to outsource this project - does anybody have any experience with Python -> C++ porting that could give advice? Does anybody have any experience with outsourcing such projects? Any experience (or being redirected to a more appropriate forum) would be greatly appreciated. I'm currently thinking about breaking the program down into pieces inside unit tests then taking care of them via rentacoder.com but having no experience I don't know if this idea is good or not. David -------------- next part -------------- An HTML attachment was scrubbed... URL: From elessar at nienna.org Thu Jul 31 13:59:11 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Thu, 31 Jul 2008 11:59:11 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <00a121b4$0$20313$c3e8da3@news.astraweb.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <00a121b4$0$20313$c3e8da3@news.astraweb.com> Message-ID: <4891FD6F.8090604@nienna.org> Steven D'Aprano wrote: > On Wed, 30 Jul 2008 09:23:05 -0600, Matthew Fitzgibbons wrote: > >> If you're expecting a list (and only a list) >> then your point makes sense. 'if x' can get you into trouble if you >> _don't_ want its polymorphism. > > "if x" is hardly unique in that way. If you're expecting a list, and only > a list, "len(x) != 0" will get you in trouble if somebody passes a string > or a dictionary. I don't see any reason why we should single out "if x" > as dangerous in the face of invalid types. With the exception of the "is" > and "is not" operators, nothing in Python is guaranteed to work with any > imaginable object. Even print can fail, if the object's __str__ method > raises an exception. > > >> Although, if my function is expecting a list, my preference is to do: >> >> if not isinstance(x, list): >> raise SomeMeaningfulException() >> # do stuff with the list >> >> I put my type checking at the top of the function, so readers can >> reference it easily. > > And thus you break duck-typing and upset anybody who wants to pass a > sequence that doesn't inherit directly from list. > > There are other (and arguably better, although more labour-intensive) > techniques for defensive programming that don't break duck-typing. You > can google for Look Before You Leap and Easier To Ask Forgiveness Than > Permission for more information. Alex Martelli has a fine recipe in the > Python Cookbook -- search for the recipe "Checking if an object has the > necessary attributes". > > But in a nutshell, here's a toy example: > > def spam(seq): > try: > seq.append > seq.extend > seq[0] = seq[0] > except Exception: > raise TypeError("argument isn't sufficiently sequence-like") > # No exceptions expected from here on > seq.append(seq[0]) > seq.extend([1,2,3]) > seq[0] = "spam" > > > > Yes, I know it breaks duck typing, which is why I do it only very rarely, and never with e.g. sequence types. If I use ifinstance for type checking, it's because I need some _very_ specific class, almost always one that I wrote. My more usual use case for ifinstance is to figure out how to handle a particular object using introspection. That said, your example is still helpful. It's a good approach, and I should use it more often. Although I'd also lean toward hasattr and iscallable and ordinary ifs instead of the try ... except where possible. Depending on what you put in the try ... except, you risk masking legit exceptions. Ahhh, Programing. Where no rule of thumb seems to last five minutes. -Matt From malaclypse2 at gmail.com Tue Jul 29 11:05:31 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 29 Jul 2008 11:05:31 -0400 Subject: How do I include a shell variable in my script? In-Reply-To: References: Message-ID: <16651e80807290805j11ac4d31v11c7658c7d29b90d@mail.gmail.com> On Tue, Jul 29, 2008 at 10:53 AM, laredotornado wrote: > Hi, > > I'm running a Python script on a Solaris 9 machine, invoking the > Python script from ksh, if that matters. There is an enviornment > variable, $JAVA_HOME, that I would like to include in my script, > replacing "/path/to/java/home'" with the value of $JAVA_HOME. > > java_home='/path/to/java/home' import os java_home = os.environ['JAVA_HOME'] -- Jerry From siona at chiark.greenend.org.uk Wed Jul 9 11:44:48 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 09 Jul 2008 16:44:48 +0100 (BST) Subject: numeric emulation and __pos__ References: <92e3ea9f-5745-4072-9d09-7c14fd335828@f36g2000hsa.googlegroups.com> Message-ID: Ethan Furman wrote: >Anybody have an example of when the unary + actually does something? I've seen it (jokingly) used to implement a prefix increment operator. I'm not going to repeat the details in case somebody decides it's serious code. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From animator333 at gmail.com Sun Jul 27 09:14:48 2008 From: animator333 at gmail.com (King) Date: Sun, 27 Jul 2008 06:14:48 -0700 (PDT) Subject: Read .txt file like .py file Message-ID: <90f13013-bb20-4224-ac58-02947f3f9358@i24g2000prf.googlegroups.com> I have a text file and contents are: Help=""" Code is written by xteam. """ value = 0.0 How do I read this file like python syntax. What I mean is first readline operation should return complete declaration of 'Help' variable. If I evaluate this string then it should create a 'Help' variable with it's value. May be something related to 'parsing' would help but I don't know much. From bdesth.quelquechose at free.quelquepart.fr Sun Jul 27 14:07:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Jul 2008 20:07:35 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <874p6f5m5u.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <32e12408-fc9f-4eb4-8b9d-fb7fa69bd2fc@f36g2000hsa.googlegroups.com> <87zlo7y2wn.fsf@physik.rwth-aachen.de> <48889a72$0$25165$426a74cc@news.free.fr> <874p6f5m5u.fsf@physik.rwth-aachen.de> Message-ID: <488cd55e$0$21184$426a34cc@news.free.fr> Torsten Bronger a ?crit : > Hall?chen! > > Bruno Desthuilliers writes: > >> Torsten Bronger a ?crit : (snip) >>> One could surely find ways to realise this. However, the design >>> goal should be: Make the frequent case simple, and the rare case >>> possible. >> Given the (more and more prominent) use of decorators, metaclasses >> and other meta-programming techniques in Python, I'm not sure the >> cases where you really need access to Python's object model inners >> are that "rare". Not in my code at least. > > What does "not rare" mean for you? More than once a week. From ptmcg at austin.rr.com Sat Jul 12 08:46:03 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 12 Jul 2008 05:46:03 -0700 (PDT) Subject: Changing self: if self is a tree how to set to a different self References: Message-ID: <0101e32d-bba2-4821-aaf4-97944c9d8f3a@f63g2000hsf.googlegroups.com> On Jul 12, 6:18?am, Bart Kastermans wrote: > This uses the function: > > def NoneOr (tree, mem_function, *arguments): > ? ? """ if tree is not None then tree.mem_function (arguments). """ > ? ? if tree == None: > ? ? ? ? return None > ? ? else: > ? ? ? ? return getattr (tree, mem_function) (*arguments) > > Bart This code reads wrongly to me on a couple of levels. First, I think the general computing consensus is that if-then-else is more readable/ logical if you assert the positive condition for the then-part, and put the alternative condition in the else-part. My impression is that the non-None-ness of tree is actually the positive assertion, as in: if tree != None: return getattr(tree, mem_function)(*arguments) else: return None Next, the more Pythonic test for None-ness is most clearly written as: if tree is not None: as there is only one None, and the identity "is not" check is simpler/ faster for Python to execute (and possibly - and more importantly - also simpler for readers to follow, as this reads more like a continuous sentence instead of a mixture of prose and mathematical notations). One might even suggest you could further abbreviate this test to: if tree: and get the same behavior. I would quibble with that, however, that this merely exploits a side-effect of Python, in which None values are always False, and *most* non-None values are True. But Python also interprets many non-None values as False, such as 0, or empty containers, such as lists, tuples, dicts, and strings. In fact, your tree class sounds like a structured container to me, and it would be reasonable to assume that you might implement __nonzero__ (pre-Python 2.6) or __bool__ (Python 2.6 and later) in your class to return False for an empty tree, which would still be a valid and not-None tree. You should be able to invoke methods on an empty tree just as one can call "".upper(). So for this case, I would stick with the more explicit "if tree is not None". Another Pythonicity is that methods will *always* return a value, even if you do not write a return statement - and that value is None. So if you assert the tree-not-None as the if condition, you don't even need the else part. You could just write: def NoneOr (tree, mem_function, *arguments): """ if tree is not None then tree.mem_function (arguments). """ if tree is not None: return getattr(tree, mem_function)(*arguments) Surprisingly, this actually reads almost verbatim from your doc string! So I would guess that this implementation is probably closest to your original intent for this method. Still, for explicitness'- sake, you might want to keep the else-part, just to make your intent clear and spelled-out. (Complaining about the presence or absence of this bit of code goes beyond "persnickety"...) Note that the original code is perfectly valid Python, and will run just as efficiently as any of my alternative suggestions, which is why I enclosed my comments in 'persnickety' (http:// dictionary.reference.com/browse/persnickety) tags. -- Paul From squishywaffle at gmail.com Thu Jul 31 11:27:14 2008 From: squishywaffle at gmail.com (squishywaffle at gmail.com) Date: Thu, 31 Jul 2008 08:27:14 -0700 (PDT) Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> <6fe0scFaus40U1@mid.uni-berlin.de> <6bc8bc07-eab0-4303-b8a4-c9470f96038d@c65g2000hsa.googlegroups.com> <6fe1n2Faus40U3@mid.uni-berlin.de> Message-ID: On Jul 31, 10:47?am, "Diez B. Roggisch" wrote: > I take the freedom to do so as I see fit - this is usenet... Fine, then keep beating a dead horse by replying to this thread with things that do nobody any good. It seems like there are a lot better way to waste time, though. The Python/C API can get me back further without reliance on third- party libraries than ctypes. It also isn't subject to the quirks that ctypes is on platforms other than Windows (the target application runs on Windows, Mac, and eventually Linux once the original distributor has drivers for the device). I'm not even sure ctypes could load the lib/driver the distributor packaged. So really, I appreciate the option in ctypes, it's good stuff. But it's not for this project. Once again, the original question stands for anyone who has experience with the Python/C API callbacks. From lanny at freshells.ch Thu Jul 24 11:02:00 2008 From: lanny at freshells.ch (Lanny) Date: Thu, 24 Jul 2008 08:02:00 -0700 Subject: Raw Strings (I Think) Message-ID: I've used glob.glob to get a list of files in a directory and now I want to use os.system to execute one of those files, the problem is that python automatically puts a escape charater infront of the back slashes so the os.system gets X:\\####\\####\\ and is useless, I think I need to convert my string to a raw string but I don't know how. -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- From malaclypse2 at gmail.com Wed Jul 23 15:26:52 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 23 Jul 2008 15:26:52 -0400 Subject: Using variables across modules In-Reply-To: References: <855136ce-6c70-40ac-a462-dc0bbfa1fc3a@b2g2000prf.googlegroups.com> <121c5161-9485-4d6a-a447-9f9dd4227bac@d77g2000hsb.googlegroups.com> Message-ID: <16651e80807231226v5efded9cwcf4b23c185cc88de@mail.gmail.com> On Wed, Jul 23, 2008 at 3:06 PM, Aaron Scott wrote: > ... which is what I was expecting, but not what I want. Obviously, > each import is creating its own instance of the variable. What I need > is a way to change myvar from within "bar.py" so that PrintVar() > returns the new value, even though it's in a different module. That's what happens when you do "from variables import *", it creates those names in the local namespace. If you just import the module, then you can do what you want. For example: ---variables.py--- myvar = 5 print myvar ---foo.py--- import variables def PrintVar(): print variables.myvar ---bar.py--- import variables, foo print variables.myvar variables.myvar = 2 print variables.myvar foo.PrintVar() ---output from running bar.py--- 5 5 2 2 For more on how the import statement works, see the library reference (http://docs.python.org/ref/import.html), or maybe this article on the various ways you can import things and the differences between them (http://effbot.org/zone/import-confusion.htm) -- Jerry From arockstar at gmail.com Fri Jul 18 15:17:33 2008 From: arockstar at gmail.com (arockstar at gmail.com) Date: Fri, 18 Jul 2008 12:17:33 -0700 (PDT) Subject: Trickiness with unittesting Message-ID: Basically, I'm trying to implement a setUp() and TearDown() for a python TestSuite (as opposed to an individual test within the suite). Sort of. I have a few different test suites (call them SuiteA, SuiteB,...). For one of the test suites (SuiteA), I need to execute a bit of code (say startFoo()) before the first test in SuiteA runs, and once when the last test of SuiteA finishes (endFoo()). Making this even trickier is that the testing framework combines the different suites (SuiteA, SuiteB) as well as individual tests into master test suite which my testrunner then runs. Also complicating matters is the fact that the testing framework can run an *individual* test from any TestSuite: in that case, if I'm running SuiteA.test1, I'd want to call startFoo() and endFoo() as well. I could use a global variable as a flag and see if it's been set during the setUp() method of the test cases (which would allow me to call startFoo() once when tests from SuiteA are run from the master suite), but that doesn't help me with calling endFoo() when the tests from SuiteA finish. Plus, it's not very elegant. So: Given a master test suite comprised of a bunch of different tests from different suites, I need to call startFoo() before tests from SuiteA are run, and stopFoo() after all the tests from SuiteA have finished running. From deets at nospam.web.de Sun Jul 27 10:57:14 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2008 16:57:14 +0200 Subject: Rant (was Re: x*x if x>10 In-Reply-To: <6f3g8rF9gfj0U1@mid.uni-berlin.de> References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3g8rF9gfj0U1@mid.uni-berlin.de> Message-ID: <6f3gmaF9moqsU1@mid.uni-berlin.de> Marc 'BlackJack' Rintsch schrieb: > On Sun, 27 Jul 2008 16:41:19 +0200, Diez B. Roggisch wrote: > >> DaveM schrieb: >>> Getting back to the >>> list concatenation, I finally found the itertools.chain command which >>> is the most compact and fastest (or second fastest by a trivial amount, >>> I can't remember which). Along the way, I must have tried/used half a >>> dozen methods, ...which brings me back my initial PERL comment. There's >>> more than one way to do it in Python, too. >> Any non-trivial task has that property. I don't know enough perl to have >> an example ready that shows something that python has only one way of >> doing and perl has several. >> >> But I *do* know that taking the python zen literally is fruitless. > > I think it should be taken more literally than the wrong reduction to > "there should be only one way". People tend to forget "obvious" and > "preferably" all the time. Good point. The OP found the obvious way of extending. I wonder what his reasons were to abandon it. Diez From tjreedy at udel.edu Thu Jul 24 21:02:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 24 Jul 2008 21:02:48 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <20b5e80c-ba2a-4cd0-9a6a-beeef6134839@r35g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <1de235af-4245-41aa-9091-bb7b112f4ce5@n33g2000pri.googlegroups.com> <20b5e80c-ba2a-4cd0-9a6a-beeef6134839@r35g2000prm.googlegroups.com> Message-ID: Jordan wrote: > I wish in retrospect I'd had the time, patience and focus to edit the > initial post to make it more measured and less inflammatory, because > its clear the tone I will ignore that. > detracts from the argument I'm making, which I feel still stands. class C(): def f(): a = 3 You made a complaint and an incomplete proposal identical to what others have proposed. But here is where the idea always sinks. Suppose as you propose 'self' is added to the arg list. How is a mindless algorithm to decide whether to change a to 'self.a' to make it an attribute or leave it alone as a local variable? Or would you abolish local vars from methods (which would slow them down)? As near as I can see, any concrete detailed implementable proposal would be a more major change in Python or its implementation than 'down-with-self'ers usually admit. If the argument you refer to is instead that 'Explicit is better than Implicit' is a bit overused and inadequate as a technical response, then I agree. But excuse me for being unsure ;-). Terry Jan Reedy From paddy3118 at googlemail.com Fri Jul 4 12:40:47 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 4 Jul 2008 09:40:47 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> On Jul 4, 1:36?pm, Peter Otten <__pete... at web.de> wrote: > Henning_Thornblad wrote: > > What can be the cause of the large difference between re.search and > > grep? > > grep uses a smarter algorithm ;) > > > > > This script takes about 5 min to run on my computer: > > #!/usr/bin/env python > > import re > > > row="" > > for a in range(156000): > > ? ? row+="a" > > print re.search('[^ "=]*/',row) > > > While doing a simple grep: > > grep '[^ "=]*/' input ? ? ? ? ? ? ? ? ?(input contains 156.000 a in > > one row) > > doesn't even take a second. > > > Is this a bug in python? > > You could call this a performance bug, but it's not common enough in real > code to get the necessary brain cycles from the core developers. > So you can either write a patch yourself or use a workaround. > > re.search('[^ "=]*/', row) if "/" in row else None > > might be good enough. > > Peter It is not a smarter algorithm that is used in grep. Python RE's have more capabilities than grep RE's which need a slower, more complex algorithm. You could argue that if the costly RE features are not used then maybe simpler, faster algorithms should be automatically swapped in but .... - Paddy. From kyosohma at gmail.com Mon Jul 7 10:34:56 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 7 Jul 2008 07:34:56 -0700 (PDT) Subject: Hi there! I need what is probably a very basic lesson in events.... References: <4d5a5286-f4cf-480e-9432-b4b337f7c145@x35g2000hsb.googlegroups.com> Message-ID: <8fca22ab-67ad-4dbb-b92c-d5412a8eba2f@m44g2000hsc.googlegroups.com> On Jul 6, 8:18?am, furby wrote: > I am teaching myself Python... I'm nowhere near even intermediate > level yet, so treat me like an idiot. I am using Boa Constructor on > Ubuntu 8.04 if that helps. Here is what I have right now : > > I am plying with reading a URL (An RSS feed to be exact) and > displaying it inside a HTMLWindow. I have that part working - It shows > the title as a link and displays the description next to it. What I > want to do is trap the mouseclick on the link and use that to grab > just the text that is on the site. Right now, if I click on it, the > HTML window control takes me to the site and doesn't really show the > site very well, since it doesn't seem to do CSS. That's okay - I just > want to display the text.... How do I trap the mouse clicking on the > link? > > I know that HTMLwindow has a "OnLinkClicked" event - I can see it in > the docs for that control. But it seems that Boa Constructor doesn't > expose that event in it's frame designer.... How do I code a event > that fires off instead of the default event? > > I don't know if I am being clear enough, so if not just tell me what I > should say... Liek I said, I am a newbie right now. I think you just need to override that method (OnLinkClicked) in the class you use to subclass the HtmlWindow widget. Something like this: class MyCustomDlg(wx.Frame): def __init__(self, parent, title, icon, pos): wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(400,400)) x,y = pos self.SetPosition((x+30, y+30)) self.SetIcon(icon) html = wxHTML(self) class wxHTML(wx.html.HtmlWindow): def OnLinkClicked(self, link): # do something here pass However, for wxPython questions, it's best to post to the wxPython user's group. They are very knowledgeable there. http://wxpython.org/maillist.php Hope that helps. ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From Russ.Paielli at gmail.com Wed Jul 30 01:15:30 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 22:15:30 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: On Jul 29, 9:52 pm, Carl Banks wrote: > On Jul 29, 11:17 pm, Terry Reedy wrote: > > > > > Carl Banks wrote: > > >> As I wrote in the second reply email I sent, check out my integer set > > >> recipe on ASPN (and to save you the search: http://code.activestate.com/recipes/466286/). > > > > Couple points: > > > > 1. Any container type that returns a length that isn't exactly the > > > number of elements in it is broken. > > > 2. The need for __nonzero__ in this case depends on a limitation in > > > the language. > > > 3. On the other hand, I will concede that sometimes calculating len is > > > a lot more expensive than determining emptiness, and at a basic level > > > it's important to avoid these costs. You have found a practical use > > > case for __nonzero__. > > > I thought of another one: testing whether an iterator is 'empty' (will > > raise StopIteration on the next next() (3.0) call) or not. As virtual > > collections, iterators generally have neither __len__ or __bool__. But > > __bool__ (but only __bool__) can be added to any iterator by wrapping it > > with something like the following 3.0 code (not tested): > > > class look_ahead_it(): > > def __init__(self, iterable): > > self.it = iter(iterable) > > self.fill_next() > > > def __iter__(self): > > return self > > def __next__(self): > > tem = self.next > > if tem is self.empty: > > raise StopIteration > > else: > > self.fill_next() > > return tem > > > empty = object() > > def fill_next(self) > > try: > > self.next = next(self.it) > > except StopIteration: > > self.next = self.empty > > > def __bool__(self): > > return self.next is not self.empty > > Iterators are funny: if there's any reason you should not use "if x" > it's because of them. Built-in iterators are always true, so if > you're writing a function that accepts an iterable you should never > use the "if x" to test whether it's empty, because it fails for a > whole class of iterables. > > However, given that that wart exists, your example does work for "if > x" and not with "if len(x)!=0". > > Then again, it really only works to accommodate faulty code, because > no code that expects an iterable should be using that test in the > first place. (Unless you wrap every iterable as soon as you get it, > but then you're not bound to use __nonzero__.) > > Carl Banks All this discussion about "if x" has me wondering. I use it all the time because a fully explicit test just seems redundant. But maybe it does have some value in terms of readability and type checking. After all, it is possible to forget whether something is a number or a list. Having said that, it would sure be nice to be able to write if myList is not empty: instead of if len(myList) != 0: From wuwei23 at gmail.com Thu Jul 31 01:26:04 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 30 Jul 2008 22:26:04 -0700 (PDT) Subject: how to split text into lines? References: Message-ID: kj wrote: > Sorry, I should have googled this first. ?I just found splitlines()... > > Still, for my own edification, is there a way to achieve the same > effect using re.split? re.split(os.linesep, ) works the same as .splitlines() Neither retain the EOL for each line, though. The only way I'm aware of is to re-add it: [s+os.linesep for s in re.split(os.linesep, )] Was that what you were after? From zapwireDASHgroups at yahoo.com Mon Jul 14 21:33:18 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Mon, 14 Jul 2008 18:33:18 -0700 Subject: One step up from str.split() Message-ID: I normally use str.split() for simple splitting of command line arguments, but I would like to support, e.g., long file names which-- under windows -- are typically provided as simple quoted string. E.g., myapp --dosomething --loadthis "my file name.fil" ...and I'd like to get back a list wherein ListEntry[3]="my file name.fil" , but just running str.split() on the above string creates: >>> ListEntry='myapp --dosomething --loadthis "my file name.fil"' >>> ListEntry.split() ['myapp', '--dosomething', '--loadthis', '"my', 'file', 'name.fil"'] Is there an easy way to provide just this one small additional feature (keeping quoted names as a single entry) rather than going to a full-blown command-line argument parsing tool? Even regular expressions seem like they'd probably be overkill here? Or no? Thanks, ---Joel From basti.wiesner at gmx.net Thu Jul 24 06:02:15 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Thu, 24 Jul 2008 12:02:15 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: Jordan : > # Blog code, not tested > class A(): > def __eq__(self, obj): > return True > a = A() > b = [] > assert a == b > assert not (a != b) > > The second assertion fails. Why? Because coding __eq__, the most > obvious way to make a class have equality based comparisons, buys you > nothing from the != operator. != isn't (by default) a synonym for the > negation of == (unlike in, say, every other language ever); This is just plain wrong for at least C# and C++. C# wants you to explicitly overload "!=", if you have overloaded "==", C++ complains about "!=" not being defined for class A. If you had derived A from a another class in C++, the compiler would happily use the operator from the base class instead of doing silly aliasing of "!=" to "! ==" ... > The sad thing is there are plenty of smart Python programmers who will > justify all kinds of idiocy in the name of their holy crusade against > the implict. > > If there was one change I could make to Python, it would be to get > that damn line out of the Zen. Fortunately, Python isn't designed according to your ideas, and won't change, so consider your posting a waste of time. If feeling like bringing such old "issues" up again next time, spend your time learning another programming language, as you would obviously not get happy with Python anyway ... -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From mgi820 at motorola.com Tue Jul 1 12:46:43 2008 From: mgi820 at motorola.com (Gary Duzan) Date: Tue, 1 Jul 2008 16:46:43 +0000 (UTC) Subject: dynamically load from module import xxx References: Message-ID: In article , Neal Becker wrote: >What is a good way to emulate: > >from module import xxx >where 'module' is a dynamically generated string? > >__import__ ('modulename', fromlist=['xxx']) > >seems to be what I want, but then it seems 'xxx' is not placed in globals() >(which makes me wonder, what exactly did fromlist do?) You might want to read what "help(__import__)" tells you. It sounds like what you want is: mynamespace['xxx'] = __import__('modulename.xxx', fromlist=['xxx']) Seems a bit weird to me, but that's the way it is, and I'm sure there is a reason for it. Good luck. Gary Duzan Motorola H&NM From stefan_ml at behnel.de Sun Jul 13 11:47:49 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 13 Jul 2008 17:47:49 +0200 Subject: SAX XML Parse Python error message In-Reply-To: References: Message-ID: <487A23A5.7000905@behnel.de> goldtech wrote: > My first attempt at SAX, but have an error message I need help with. Just in case you prefer writing readable code over debugging SAX code into existence, try lxml. http://codespeak.net/lxml/ Here is a presentation you might find interesting. http://codespeak.net/lxml/s5/lxml-ep2008.html Stefan From kylefarthing at msn.com Sun Jul 6 05:21:29 2008 From: kylefarthing at msn.com (kylefarthing at msn.com) Date: Sun, 6 Jul 2008 02:21:29 -0700 (PDT) Subject: Discover Islam - The Fastest Growing Religion in the World ! References: <9d3ed65e-335c-4d45-8374-505ae7d434b1@p25g2000hsf.googlegroups.com> Message-ID: On Jul 1, 4:51?pm, ah wrote: > Correct your information about Islam > , > The Misunderstood Religion > > ? When you are ready_ you can enter this place!!! > ?http://sultan.org all u muslim liers get your facts stright According to the Carnegie Endowment for International Peace, the World Christian Database as of 2007 estimated the six fastest growing religions of the world to be Islam (1.84%), the Bah?'? Faith (1.7%), Sikhism (1.62%), Jainism (1.57%), Hinduism (1.52%), and Christianity (1.32%). High birth rates were cited as the reason for the growth. [13] From enleverlesX.XmcX at XmclaveauX.com Sat Jul 5 17:14:15 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 5 Jul 2008 23:14:15 +0200 Subject: pythoncom InternetExplorer.Application don't work in vista || firefox pythoncom ? In-Reply-To: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> References: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> Message-ID: <486fe5cc$0$926$ba4acef3@news.orange.fr> Hi! Your code run OK for me (Vista Ultimate). This other version run also OK : def webbrowser(url=None): import win32com.client, time ie=win32com.client.Dispatch('InternetExplorer.Application') while ie.Busy==True: time.sleep(0.125) ie.Top = 0 ie.Left = 0 ie.Height = 400 ie.Width = 400 ie.AddressBar = False ie.MenuBar = False ie.Resizable = False ie.StatusBar = False ie.ToolBar = False ie.Visible = 1 return ie w = webbrowser() w.Navigate('http://www.google.nl') @-salutations -- Michel Claveau From exarkun at divmod.com Tue Jul 29 14:28:02 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 29 Jul 2008 14:28:02 -0400 Subject: [unittest] Run setUp only once In-Reply-To: <87y73kpnk1.fsf@nokile.rath.org> Message-ID: <20080729182802.29191.2001258936.divmod.quotient.8313@ohm> On Tue, 29 Jul 2008 20:12:14 +0200, Nikolaus Rath wrote: >Jean-Paul Calderone writes: >> On Tue, 29 Jul 2008 19:26:09 +0200, Nikolaus Rath wrote: >>>Jean-Paul Calderone writes: >>>> On Tue, 29 Jul 2008 16:35:55 +0200, Nikolaus Rath wrote: >>>>>Hello, >>>>> >>>>>I have a number of conceptually separate tests that nevertheless need >>>>>a common, complicated and expensive setup. >>>>> >>>>>Unfortunately, unittest runs the setUp method once for each defined >>>>>test, even if they're part of the same class as in >>>>> >>>>>class TwoTests(unittest.TestCase): >>>>> def setUp(self): >>>>> # do something very time consuming >>>>> >>>>> def testOneThing(self): >>>>> >>>>> >>>>> def testADifferentThing(self): >>>>> >>>>> >>>>>which would call setUp twice. >>>>> >>>>> >>>>>Is there any way to avoid this, without packing all the unrelated >>>>>tests into one big function? >>>>> >>>> >>>> class TwoTests(unittest.TestCase): >>>> setUpResult = None >>>> >>>> def setUp(self): >>>> if self.setUpResult is None: >>>> self.setUpResult = computeIt() >>>> >>>> ... >>>> >>>> There are plenty of variations on this pattern. >>> >>> >>>But at least this variation doesn't work, because unittest apparently >>>also creates two separate TwoTests instances for the two tests. Isn't >>>there some way to convince unittest to reuse the same instance instead >>>of trying to solve the problem in the test code itself? >>> >> >> Eh sorry, you're right, the above is broken. `setUpResult` should be >> a class attribute instead of an instance attribute. > >Yeah, well, I guess that would work. But to me this looks really more >like a nasty hack.. isn't there a proper solution? > How is it a nasty hack? It's a straight-forward implementation of shared state, which is what you said you wanted. If you prefer, you could keep the state somewhere else - like by applying a memoizer to `computeIt? and just calling it unconditionally in `setUp?. Jean-Paul From patf at well.com Mon Jul 28 18:43:20 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 15:43:20 -0700 (PDT) Subject: Download excel file from web? References: <6f6vhlFa7anrU1@mid.uni-berlin.de> Message-ID: <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> On Jul 28, 3:33?pm, "p... at well.com" wrote: > On Jul 28, 3:29?pm, "Diez B. Roggisch" wrote: > > > > > p... at well.com schrieb: > > > > On Jul 28, 3:00 pm, "p... at well.com" wrote: > > >> Hi - experienced programmer but this is my first Python program. > > > >> This URL will retrieve an excel spreadsheet containing (that day's) > > >> msci stock index returns. > > > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > > >> Want to write python to download and save the file. > > > >> So far I've arrived at this: > > > >> [quote] > > >> # import pdb > > >> import urllib2 > > >> from win32com.client import Dispatch > > > >> xlApp = Dispatch("Excel.Application") > > > >> # test 1 > > >> # xlApp.Workbooks.Add() > > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > > >> # xlBook = xlApp.ActiveWorkbook > > >> # xlBook.SaveAs(Filename='C:\\test.xls') > > > >> # pdb.set_trace() > > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > > >> excel? > > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > >> +25%2C+2008&export=Excel_IEIPerfRegional') > > >> # test 2 - returns check = False > > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > > >> indexperf/excel? > > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > > >> xlApp = response.fp > > >> print(response.fp.name) > > >> print(xlApp.name) > > >> xlApp.write > > >> xlApp.Close > > >> [/quote] > > > > Woops hit Send when I wanted Preview. ?Looks like the html [quote] tag > > > doesn't work from groups.google.com (nice). > > > > Anway, in test 1 above, I determined how to instantiate an excel > > > object; put some stuff in it; then save to disk. > > > > So, in theory, I'm retrieving my excel spreadsheet with > > > > response = urllib2.urlopen() > > > > Except what then do I do with this? > > > > Well for one read some of the urllib2 documentation and found the > > > Request class with the method has_data() on it. ?It returns False. > > > Hmm that's not encouraging. > > > > I supposed the trick to understand what urllib2.urlopen is returning > > > to me; rummage around in there; and hopefully find my excel file. > > > > I use pdb to debug. ?This is interesting: > > > > (Pdb) dir(response) > > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > > > 'code', ' > > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > > > 'readline', ' > > > readlines', 'url'] > > > (Pdb) > > > > I suppose the members with __*_ are methods; and the names without the > > > underbars are attributes (variables) (?). > > > No, these are the names of all attributes and methods. read is a method, > > for example. > > right - I got it backwards. > > > > > > > > Or maybe this isn't at all the right direction to take (maybe there > > > are much better modules to do this stuff). ?Would be happy to learn if > > > that's the case (and if that gets the job done for me). > > > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty > > clear on this: > > > """ > > This function returns a file-like object with two additional methods: > > """ > > > And then for file-like objects: > > >http://docs.python.org/lib/bltin-file-objects.html > > > """ > > read( ? [size]) > > ? ? ?Read at most size bytes from the file (less if the read hits EOF > > before obtaining size bytes). If the size argument is negative or > > omitted, read all data until EOF is reached. The bytes are returned as a > > string object. An empty string is returned when EOF is encountered > > immediately. (For certain files, like ttys, it makes sense to continue > > reading after an EOF is hit.) Note that this method may call the > > underlying C function fread() more than once in an effort to acquire as > > close to size bytes as possible. Also note that when in non-blocking > > mode, less data than what was requested may be returned, even if no size > > parameter was given. > > """ > > > Diez > > Just stumbled upon .read: > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > excel? > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > +25%2C+2008&export=Excel_IEIPerfRegional').read > > Now the question is: what to do with this? ?I'll look at the > documentation that you point to. > > thanx - pat Or rather (next iteration): response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ excel? priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) The file is generally something like 26 KB so specifying 1,000,000 seems like a good idea (first approximation). And then when I do: print(response) I get a whole lot of garbage (and some non-garbage), so I know I'm onto something. When I read the .read documentation further, it says that read() has returned the data as a string object. Now - how do I convince Python that the string object is in fact an excel file - and save it to disk? pat From martin at v.loewis.de Mon Jul 7 16:36:19 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 07 Jul 2008 22:36:19 +0200 Subject: Memory error while saving dictionary of size 65000X50 using pickle In-Reply-To: <43b21f62-edb6-4e37-89b8-f2460fdc36b3@25g2000hsx.googlegroups.com> References: <43b21f62-edb6-4e37-89b8-f2460fdc36b3@25g2000hsx.googlegroups.com> Message-ID: <48727e43$0$20740$9b622d9e@news.freenet.de> Nagu wrote: > I am trying to save a dictionary of size 65000X50 to a local file and > I get the memory error problem. What do you mean by this size specification? When I interpreter X as multiplication, I can't see a problem: the code import pickle d = {} for i in xrange(65000*50): d[i]=i print "Starting dump" s = pickle.dumps(d) works just fine for me. Can you please modify it so that it does cause a problem? Regards, Martin From mnordhoff at mattnordhoff.com Mon Jul 7 09:17:09 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 07 Jul 2008 13:17:09 +0000 Subject: I am looking for svn library(module) In-Reply-To: <6e1097a0-2a99-4885-a1ef-0684af5aa6a1@d1g2000hsg.googlegroups.com> References: <6e1097a0-2a99-4885-a1ef-0684af5aa6a1@d1g2000hsg.googlegroups.com> Message-ID: <48721755.4050507@mattnordhoff.com> sniipe at gmail.com wrote: > Hi, > > I am looking fo svn library(module) which is used in the svn- > mailer(http://opensource.perlig.de/svnmailer/) project. Does anybody > know where can I find it(download url)? This is information which I > received from python error: > > from svn import core as svn_core > ImportError: No module named svn > > Best regards Those would be the bindings that come with Subversion. They're covered at the end of ./INSTALL in the source tree (which just points you to ./subversion/bindings/swig/INSTALL). If you installed svn with a package manager, there's probably a package for them (e.g. python-subversion on Ubuntu). -- From tjreedy at udel.edu Sat Jul 12 15:46:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 15:46:49 -0400 Subject: Confused In-Reply-To: <4878DC07.9000302@gmail.com> References: <000001c8e417$c2b5bc50$0a01a8c0@HOMEPC> <4878DC07.9000302@gmail.com> Message-ID: Michael Torrie wrote: > eric.butteriss wrote: >> Please tell me why may mail is being returned. The message says I >> have been blacklisted...for what reason? I never open mail that I >> know is not expected and I never send junk or spam. I am trying to >> send important info to my cousin. > > Now I'm confused. Is the python mailing list blacklisting you? Unless > this is a python-related thing, I doubt you'll find anyone here who can > help. I think the OP is another spammer. Who would email a cousin via a language email list? This was probably sent to multiple lists. From s0suk3 at gmail.com Thu Jul 3 23:50:45 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Thu, 3 Jul 2008 20:50:45 -0700 (PDT) Subject: Parsing MIME-encoded data in an HTTP request References: Message-ID: <4834df8f-2cf8-434c-8c95-ff53024766c8@p25g2000hsf.googlegroups.com> On Jul 3, 3:59 pm, Ron Garret wrote: > I'm writing a little HTTP server and need to parse request content that > is mime-encoded. All the MIME routines in the Python standard library > seem to have been subsumed into the email package, which makes this > operation a little awkward. To deal with messages of that kind, I've seen modules such as 'rfc822', and 'mimetools' (which apparently builds itself from 'rfc822', so it might be more complete). There's also 'mimetypes', in case you need to deal with file extensions and their corresponding MIME media type. > It seems I have to do the following: > > 1. Extract the content-length header from the HTTP request and use that > to read the payload. > > 2. Stick some artificial-looking headers onto the beginning of this > payload to make it look like an email message (including the > content-type and content-transfer-encoding headers) > > 3. Parse the resulting string into a email message > Email? Why does an HTTP server need to build an email message? I remember doing things like that some time ago when building an HTTP server myself (http://code.google.com/p/sws-d/). Incidentally, I resisted the urge to use much of the Python's library facilities (most things are done manually; am I a knucklehead or what!? :). You might wanna take a look to get some ideas. Sebastian From kay.schluehr at gmx.net Sat Jul 12 09:35:56 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 12 Jul 2008 06:35:56 -0700 (PDT) Subject: Changing self: if self is a tree how to set to a different self References: Message-ID: On 10 Jul., 15:19, Bart Kastermans wrote: > I am playing with some trees. In one of the procedures I wrote > for this I am trying to change self to a different tree. A tree > here has four members (val/type/left/right). I found that self = SS > does not work; I have to write self.val = SS.val and the same for > the other members (as shown below). Is there a better way to do this? > > In the below self is part of a parse tree, F is the parse tree of a > function f with argument x. If a node in the parse tree is labelled > f, we should replace it by the parse tree for the function f, F, with > the remainder of the tree substituted for the input variable for the > function f, here x. > > def elimF (self): > if self.val == "f": > SS = F.copy () > SS.subst ('x', self.left) > self.val = SS.val # from here: set self to be SS > self.type = SS.type > self.left = SS.left > self.right = SS.right # completed: set self to be SS > > if self.left != None: # iterate onward, inf recursion if f > # appears. Would need a check in > # real version > self.left.elimF () > if self.right != None: > self.right.elimF () > > Best, > Bart Since it is acting on a tree why doesn't the code substitute self in its parent by SS? That's the natural perspective if one considers a tree as a linked structure and inserts and deletes nodes within this structure. From 2007 at jmunch.dk Mon Jul 28 19:19:00 2008 From: 2007 at jmunch.dk (Anders J. Munch) Date: Tue, 29 Jul 2008 01:19:00 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <009dcc93$0$20313$c3e8da3@news.astraweb.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> Message-ID: <488e4d2d$0$5967$ba624c82@nntp06.dk.telia.net> Steven D'Aprano wrote: > On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: > >> I want something where "if x" will do but a simple explicit test won't. > > Explicit tests aren't simple unless you know what type x is. If you don't even know a duck-type for x, you have no business invoking any methods on that object. If you do know a duck-type for x, then you also know which explicit test to perform. > Explicit tests are not necessarily simple for custom classes. Testing for > emptiness could be arbitrarily complex. That's why we have __nonzero__, > so you don't have to fill your code with complex expressions like (say) > > if len(x.method()[x.attribute]) > -1 > > Instead you write it once, in the __nonzero__ method, and never need to > think about it again. Okay, so you have this interesting object property that you often need to test for, so you wrap the code for the test up in a method, because that way you only need to write the complex formula once. I'm with you so far. But then you decide to name the method "__nonzero__", instead of some nice descriptive name? What's up with that? This is the kind of code I would write: class C: def attribute_is_nonnegative(self): return len(self.method()[self.attribute]) > -1 ... c = get_a_C() if c.attribute_is_nonnegative(): ... Now suppose you were reading these last few lines and got to wondering if get_a_C might ever return None. The answer is obviously no. get_a_C must always return a C object or something compatible. If not, it's a bug and an AttributeError will ensue. The code tells you that. By giving the method a name the intent of the test is perfectly documented. In comparison, I gather you would write something like this: class C: def __nonzero__(self): return len(self.method()[self.attribute]) > -1 ... c = get_a_C() if c: ... Again, the question is, can get_a_C return None? Well that's hard to say really. It could be that "if c" is intended to test for None. Or it could be intended to call C.__nonzero__. Or it could be cleverly intended to test not-None and C.__nonzero__ at the same time. It may be impossible to discern the writer's true intent. Even if we find out that C.__nonzero__ is called, what was it that __nonzero__ did again? Did it test for the queue being non-empty? Did it test for the queue being not-full? Did it test whether for the consumer thread is running? Did it test for if there are any threads blocked on the queue? Better dig up the class C documentation and find out, because there is no single obvious interpretation of what is means for an object to evaluate to true. "if x" is simple to type, but not so simple to read. "if x.namedPredicate()" is harder to type, but easier to read. I prefer the latter because code is read more often than it is written. regards, Anders From timothy.grant at gmail.com Fri Jul 25 02:32:40 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Thu, 24 Jul 2008 23:32:40 -0700 Subject: Function editing with Vim throws IndentError In-Reply-To: References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: On Thu, Jul 24, 2008 at 9:32 PM, Lawrence D'Oliveiro wrote: > In message > , > Matimus > wrote: > > > On Jul 24, 2:54 am, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: > >> In message > >> , > >> > >> Matimus wrote: > >> > That isn't the standard. With that setup tabs will show up as 4 > >> > spaces, and still confuse you. > >> > >> Why should that be confusing? The most common tab-stop setting is 4 > >> columns. > > > > A tab character is specified as 8 spaces. > > Specified by whom? The most common setting these days is 4 columns. > -- > http://mail.python.org/mailman/listinfo/python-list > A tab-stop has historically been 8 spaces. Most terminals, printers and other devices understand the tab as 8 characters. Smart editors have made it easy to make tabs APPEAR as four spaces, but they are almost universally interpreted elsewhere as 8 characters. http://en.wikipedia.org/wiki/Tab_key -- Stand Fast, tjg. [Timothy Grant] -------------- next part -------------- An HTML attachment was scrubbed... URL: From torainLight at gmail.com Thu Jul 24 20:42:54 2008 From: torainLight at gmail.com (satoru) Date: Thu, 24 Jul 2008 17:42:54 -0700 (PDT) Subject: Confounded by Python objects References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> Message-ID: <5ddae1dd-c7dd-4f04-84f6-ad71c3282c92@j7g2000prm.googlegroups.com> On Jul 24, 6:10?pm, "boblat... at googlemail.com" wrote: > On Jul 24, 11:59 am, Fredrik Lundh wrote: > > > tip: if you're not 100% sure why you would want to put an attribute > > on the class level, don't do it. > > The reason I did it was sort of C++ish (that's where I come from): I > somehow wanted a list of attributes on the class level. More for > readibility than anything elase, really. > > > hope this helps! > > Yup, did the trick. Thanks! > robert yes, i thought your code is kind of static, so it didn't work for a dynamic language like python. in python, you don't have to say "static" to make an variable a class variable, so the "name" and "sample" you kind of "declared" is indeed class variables. you may wonder why then the two instaces of "Channel" has different names, that's because you assign to name in "__init__" and make it an instance variable that shared the name "name" with a class variable. As to "sample", it never get assigned to and when you say "append" the class variable is changed in place. hope my explaination helps. From david at boddie.org.uk Sun Jul 20 08:18:03 2008 From: david at boddie.org.uk (David Boddie) Date: Sun, 20 Jul 2008 14:18:03 +0200 Subject: Genetic programming: pygene, pygp, AST, or (gasp) Lisp? References: <7bfb3c41-b08b-49dc-9711-6e39a4667db2@b1g2000hsg.googlegroups.com> Message-ID: On Sunday 20 July 2008 09:52, John Ladasky wrote: > Is there a way to interface Lisp to Python, so that I can do all the > interface programming in the language I already know best -- and just > do the genetic parts in Lisp? I haven't seen exception handling in > Lisp, a feature I've come to love in Python. Since it is fairly easy > for a randomly-generated program to generate illegal output (I already > know this from my initial experiments in Python), I don't think I can > live without exception handling. Just searching the Web for Python and Lisp yielded some interesting projects: http://www.biostat.wisc.edu/~annis/creations/PyLisp/ http://www.livelogix.net/logix/ I've no idea if they're really that relevant to your problem, but they might lead somewhere useful. David From semanticist at gmail.com Sun Jul 20 03:18:55 2008 From: semanticist at gmail.com (Miles) Date: Sun, 20 Jul 2008 03:18:55 -0400 Subject: MethodChain In-Reply-To: <6efv5cF6uhc3U1@mid.uni-berlin.de> References: <6eej10F6k7g3U2@mid.uni-berlin.de> <342b5431-5ead-4827-8bdd-ab2cd50c2acc@i76g2000hsf.googlegroups.com> <6efv5cF6uhc3U1@mid.uni-berlin.de> Message-ID: On Sun, Jul 20, 2008 at 1:01 AM, Marc 'BlackJack' Rintsch wrote: > The methods are a problem IMHO. You can't add an own method/function with > the name `fire()` or `toFunction()`. `MethodChain` has to know all > functions/methods in advance. You can add the methods of whole classes at > once and there are over 300 pre-added, this begs for name clashes. Name clashes aren't an issue, since MethodChain doesn't apply any special meaning to the method names it knows; the limitation is because JavaScript doesn't allow you to modify property lookup behavior. And since we can make the chain object callable, we don't need "fire" or "toFunction" methods. ########### from functools import partial class MethodChain(object): # The implementation of this could be cleaner. I would prefer # chain.foo() to return a new object instead of modifying chain. # But this is easier to write and closer to the JavaScript implementation. def __init__(self): self._methodname = None self._chain = [] def __getattr__(self, methodname): assert self._methodname is None self._methodname = methodname return self def __call__(self, *args, **kwargs): if self._methodname is None: assert len(args) == 1 and not kwargs result = args[0] for method in self._chain: result = getattr(result, method[0])(*method[1], **method[2]) return result else: self._chain.append((self._methodname, args, kwargs)) self._methodname = None return self def compose(*callables): def composition(arg): result = arg for callable in callables: # or should that be reversed(callables)? to be mathematically # accurate, yes, probably; however, it also makes sense to # specify the callables in the order they'll be applied result = callable(result) return result return composition chain = MethodChain().lower().replace('ello,', 'ey').title().split() print chain('HELLO, world') func = compose(chain, partial(map, lambda s: s+'!'), ' '.join) print func('HELLO, world') ########### -Miles From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 10 12:45:42 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 10 Jul 2008 18:45:42 +0200 Subject: Smal question In-Reply-To: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> References: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> Message-ID: <48763c7f$0$9609$426a74cc@news.free.fr> Hans M?ller a ?crit : > Hello group, > > I have some scripts sharing some common functions. > So what I'd like to have is a modern include. > Of course python does not have (with good reasons) no include statement. > But I'm too lazy to create a module which has to be installed into the > interpreter for some functions I need to share in a project. What do you mean "installed in the interpreter" ? From wuwei23 at gmail.com Wed Jul 23 07:48:36 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 23 Jul 2008 04:48:36 -0700 (PDT) Subject: os.walk question References: Message-ID: <79b8d5e1-709f-4a4f-957d-8acbee20018b@c2g2000pra.googlegroups.com> On Jul 23, 5:22?pm, Fredrik Lundh wrote: > if you want a list of files from a single directory, use listdir, not walk: > > ? ? ? >>> import os, random > ? ? ? >>> random.choice(os.listdir("/")) > ? ? ? 'python25' This will include folders as well, though, which isn't what the OP asked for. >>> import os, random >>> root = "/" >>> random.choice([f for f in os.listdir(root) if os.path.isfile(os.path.join(root, f))]) 'initrd.img' It just seems clunky compared to os.walk :) From jcn-france1972 at pobox.com Sun Jul 6 21:10:20 2008 From: jcn-france1972 at pobox.com (Jean-Claude Neveu) Date: Sun, 06 Jul 2008 18:10:20 -0700 Subject: Using poplib to parse headers - Thank You All! In-Reply-To: References: Message-ID: Tim Roberts wrote: >You've received some very confusing advice in this thread. Alex had the >right answer, but I want to expand it a bit. > >[...] > >poplib.retr gives you a string. You need to hand that string to the email >module, and you do that using "email.message_from_string". This is just to thank Tim, Alex, and everyone who posted for their help in getting this to work. It's been more than a month since you answered my question and I've been having to focus on other things. Last week, I finally got back to this task and your answers helped me get it working. To save time for future people who might have the same question, I'm posting a basic script for reading mail from a POP server and passing the email message to the Python email library for parsing. I'm new to Python (but experienced in other languages) so please feel free to tell me if any of my syntax is clumsy, or if I did something the difficult way when Python has an easier or more efficient way to do it. I hope this will be useful for the archives. # import getpass, poplib, email # Set up the connection to the POP server popconnection = poplib.POP3('mail.blah.com') popconnection.user('user-name-goes-here') popconnection.pass_('password-goes-here') # Find out how many messages are waiting numMessages = len(popconnection.list()[1]) # Iterate through the messages for i in range(numMessages): # retr will be called three times for each email message in the j loop below. # # The first call will return a string telling you how many bytes (i.e., octets) # are in the message. The string will look like this: OK octets # (where is the total number of bytes in the message). # # The second call will return a list containing the elements of the message. # # The third call will return an integer containing the total number of # bytes in the message for j in popconnection.retr(i+1): # We are interested only in the contents of the list. And we need to put the # list contents into a string, because that is what message_from_string expects. # We must also be sure to put a line break at the end of the substring that # represents each list element, as message_from_string relies on line breaks # to parse the email message. The k loop below builds the string from the list. if type(j) == list: numElements = len(j) outString = "" for k in range(numElements): outString += j[k] outString += '\n' message = email.message_from_string(outString) # Now that we have got the contents of the email into an email object, we can # access the logical elements of the email at will, in any order. The call to # get_payload() is to retrieve the body of the message. print message['Subject'] print message['From'] print message.get_payload() # Strictly speaking, all we need to do on quitting is to disconnect, but in some # applications it would be a good idea to delete the email from the server. popconnection.quit() From hyh_david at hotmail.com Thu Jul 17 15:17:26 2008 From: hyh_david at hotmail.com (hyh_david at hotmail.com) Date: Thu, 17 Jul 2008 12:17:26 -0700 (PDT) Subject: wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal Message-ID: paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal accept)(www all-wholesaler com)paypal wholesale n i k e sneaker(paypal ... From __peter__ at web.de Sat Jul 5 02:01:06 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 05 Jul 2008 08:01:06 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Paddy wrote: > It is not a smarter algorithm that is used in grep. Python RE's have > more capabilities than grep RE's which need a slower, more complex > algorithm. So you're saying the Python algo is alternatively gifted... Peter From bronger at physik.rwth-aachen.de Sat Jul 19 09:10:15 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 19 Jul 2008 15:10:15 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> <87lk00d7cr.fsf@physik.rwth-aachen.de> <4881e41d$0$10421$426a34cc@news.free.fr> Message-ID: <87prpam348.fsf@physik.rwth-aachen.de> Hall?chen! Bruno Desthuilliers writes: > Torsten Bronger a ?crit : > >> bruno.desthuilliers at gmail.com writes: >> >>> On 16 juil, 10:35, Stefan Scholl wrote: >>> >>>> Dave U. Random wrote: >>>> >>>>> http://snipr.com/PracticalDjango >>>> >>>> June 2008 is a bit too early. Django isn't ready. >>> >>> Oh, really ? Too bad. But, wait... If Django isn't ready, what's >>> that framework I've been using for almost three years now, then >>> ??? >> >> Before writing sarcastic comments, reading the thread would be >> really polite. > > You may not have notice, but applied to a piece of software, > "ready" is usually understood as "ready for production use". Which > Django is, and has been for years now. Yes, so Stefan used the wrong English word. The rest of the thread had already revealed it when you made your statement. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From hdante at gmail.com Tue Jul 29 22:37:50 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Tue, 29 Jul 2008 19:37:50 -0700 (PDT) Subject: Parsing VHDL with python, where to start. References: <31888260-86a9-46b0-b0a4-79f7852f256a@k30g2000hse.googlegroups.com> <50129a5b-b2f3-48a8-9ff6-1ac27918f4d4@r66g2000hsg.googlegroups.com> Message-ID: On Jul 29, 11:23?pm, Henrique Dante de Almeida wrote: > On Jul 28, 6:49?pm, Svenn Are Bjerkem > wrote: > > > > > Hi again, > > > when I get far enough to parse the VHDL (which is not currently the > > fact, but I have to look at the work coming up downstream) I will have > > to put it into an internal data structure and then write some classes > > to handle the MVC between whatever data I have and the PyQt4 widget > > that is going to show the block diagram. I own the book "Rapig GUI > > Programming with Python and Qt" by Mark Summerfield and try to read up > > on the PyQt way of doing things as I try to make a plan for my > > application. I have been looking for possible data structures with > > google just to find out that most of the ideas are stored in > > proceedings or to conferences or ieee papers not generally available > > to me. Is anybody experienced with designing data structures willing > > to share some ideas with me? Since I am using the open-source version > > of PyQt4, any information will eventually be available to public (if > > the app pass the planning stage) if that makes helping out any > > easier: :-) There is already an app called Qucs that is running in > > Qt-3 and being ported to Qt-4 that is written in C++, but I don't know > > how wise it is to just reverse-engineering C++ classes and translate > > them into python classes. > > > -- > > Svenn > > ?Don't mix the parsing code with Qt. They're independent. Qt should be > used mostly for the model and the view. The controller should be > completelly decoupled from the model and the view. If you need to wrap > the controller in some Qt object, first write the controller without > Qt, then wrap it in the Qt object. Considering that you need a full > parser for VHDL, my option would be to take the VHDL grammar: > > ?http://tams-www.informatik.uni-hamburg.de/vhdl/tools/grammar/vhdl93-b... > > ?and port it to a LR(1) or LALR parser that emits python code. See: > > ?http://en.wikipedia.org/wiki/Comparison_of_parser_generators > > ?Then, add action code to the grammar that you wrote, so that it > builds a tree representing the parsed file. I think SableCC seems to be the best choice: http://www.mare.ee/indrek/sablecc/ From gnewsg at gmail.com Sun Jul 13 11:17:07 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sun, 13 Jul 2008 08:17:07 -0700 (PDT) Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> Message-ID: On 13 Lug, 11:35, Duncan Booth wrote: > "Giampaolo Rodola'" wrote: > > Having said that I'd like to understand if there are cases where > > deleting or moving an element of the heap, causes heappop() to return > > an element which is not the smallest one. > > Yes, of course there are: any time you delete element 0 of the heap you can > do that. > > >>> heap = [0, 2, 1, 4, 5, 6, 7, 8, 9] > >>> heapify(heap) > >>> heap > > [0, 2, 1, 4, 5, 6, 7, 8, 9] > > >>> del heap[0] > >>> heappop(heap) > 2 > > By definition, element 0 is always the smallest but the next two elements > could be in any order. If you delete an element other than 0 then the next > pop won't be guaranteed to work. > > If you delete an element other than 0 the very next pop will work, but the > heap conditions won't necessarily be restored so subsequent elements may > come out in the wrong order. A simple example: > > >>> heap = [0, 1, 3, 4, 2, 5] > >>> heapify(heap) > >>> heap > [0, 1, 3, 4, 2, 5] > >>> del heap[1] > >>> heappop(heap), heappop(heap), heappop(heap) > > (0, 3, 2) Thanks, that's what I wanted to know. I understand that heapq is not that efficient to implement timeouts as I thought at first. It would have been perfect if there were functions to remove arbitrary elements withouth needing to re-heapify() the heap every time. Thanks for your help anyway. --- Giampaolo http://code.google.com/p/pyftpdlib/ From lists at nanl.de Wed Jul 9 14:02:56 2008 From: lists at nanl.de (Mirko Vogt) Date: Wed, 09 Jul 2008 20:02:56 +0200 Subject: socket-module: different behaviour on windows / unix when a timeout is set Message-ID: <4874FD50.1070404@nanl.de> Hey, it seems that the socket-module behaves differently on unix / windows when a timeout is set. Here an example: # test.py import socket sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print 'trying to connect...' sock.connect(('127.0.0.1',9999)) print 'connected!' # executed on windows >C:\Python25\python.exe test.py trying to connect... Traceback (most recent call last): File "test.py", line 4, in sock.connect(('127.0.0.1',9999)) File "", line 1, in connect socket.error: (10061, 'Connection refused') > # executed on linux $ python test.py trying to connect... Traceback (most recent call last): File "test.py", line 4, in sock.connect(('127.0.0.1',9999)) File "", line 1, in connect socket.error: (111, 'Connection refused') $ Even if the error-codes are different both raise an socket.error with the message 'Connection refused' - good so far. Now I will change the code slightly - to be precise I set a timeout on the socket: # test.py import socket sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.settimeout(3.0) # <---------------------------------------------------------- print 'trying to connect...' sock.connect(('127.0.0.1',9999)) print 'connected!' # executed on linux $ python test.py trying to connect... Traceback (most recent call last): File "test.py", line 5, in sock.connect(('127.0.0.1',9999)) File "", line 1, in connect socket.error: (111, 'Connection refused') $ # executed on windows >C:\Python25\python.exe test.py trying to connect... connected! > The code executed by python running on windows does *not* raise the exception anymore. The Linux does as expected. Is that behaviour common or even documented? Found nothing. It took me lot's of time to figure this out, because there was no exception which was raised when testing for open / ports. When I try to read from the socket (e.g. on port 9999 on which nothing runs) I get a timeout after the via settimeou() specified value. Thanks in advance, Mirko From mensanator at aol.com Thu Jul 3 23:27:16 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 3 Jul 2008 20:27:16 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> <7db52b03-7a8a-40c4-b3cb-f6dccd273b90@59g2000hsb.googlegroups.com> <45ce2acc-e4b5-4762-8daa-b67a78b02411@w7g2000hsa.googlegroups.com> Message-ID: <5b9a9fda-f736-4f72-b878-16008097f13f@34g2000hsf.googlegroups.com> On Jul 3, 9:09?pm, George Sakkis wrote: > On Jul 3, 7:51 pm, Mensanator wrote: > > > On Jul 3, 6:24 pm, George Sakkis wrote: > > > > Taking into account 2.6 too (we're not talking about only 3.0 here), > > > probably not much less than those who even know what is gmpy, let > > > alone dismiss a beta Python release because their obscure pet module > > > is not available yet. > > > That was just an example. When you consider ALL the pet > > modules like PIL, Numpy, Win32, etc., that's a lot, isn't it. > > A few points: > - The OP acknowledged he's a newbie, and as a newbie he'll probably > spend some time getting used to the language and the standard library > before jumping to the dozens 3rd party packages. > - I am sure many Python users are productive without ever touching an > external package; that is after all the point of "batteries included". > - Even if they do have external dependencies, chances are that they > are pure Python modules, which typically work without modification on > new 2.x versions. Yes, these points are valid, although I think mine are valid also. But there's no point in any further arguing. > > > I was just trying to be helpful (I admit I often sound > > negative when I'm not trying to be). > > Well, something like "Until then, such solutions are worthless, i.e., > of no value" is too strong, subjective and biased to be really > helpful. I was trying NOT to imply "broken" or "doesn't do anything useful". I guess I'll have to try to be less succinct. > > George From misceverything at gmail.com Sun Jul 20 12:05:12 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Sun, 20 Jul 2008 09:05:12 -0700 (PDT) Subject: Web Server References: Message-ID: <1dc5311f-6243-41d4-b5da-78183c9668e4@m44g2000hsc.googlegroups.com> Thanks, Fredrik - that definitely works. Now to get a little greedy - is there something along those lines that is a bit more secure (i.e. allows HTTPS, possibly with authentication)? Basically something that you would feel more comfortable opening up to the Internet.. From fredrik at pythonware.com Tue Jul 22 13:21:00 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 19:21:00 +0200 Subject: Importing different versions of a module In-Reply-To: <8b51e78c0807221005k4ead9652i721a030c592273af@mail.gmail.com> References: <8b51e78c0807171614s54101ce7oa7102455cb6bdd4e@mail.gmail.com> <48811064.5010603@hughes.net> <8b51e78c0807181750x66fd0372y82367245630e921f@mail.gmail.com> <4884FC33.2090006@hughes.net> <8b51e78c0807221005k4ead9652i721a030c592273af@mail.gmail.com> Message-ID: mercado mercado wrote: > It seems that you can specify the name of the module to be imported at > runtime using the following syntax: > > X = __import__('X') > > (from http://effbot.org/zone/import-confusion.htm) > > Of course, I would rather specify the path to the module at runtime, not > the module name itself, but at least this is a start... additional approaches can be found here: http://effbot.org/zone/import-string.htm also see my other reply to you in this thread. From robert.kern at gmail.com Tue Jul 29 18:01:19 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 29 Jul 2008 17:01:19 -0500 Subject: Swap memory in Python ? - three questions In-Reply-To: References: <642068.13334.qm@web55102.mail.re4.yahoo.com> Message-ID: Terry Reedy wrote: > > Robert LaMarca wrote: >> Hi, >> I am using numpy and wish to create very large arrays. My system is >> AMD 64 x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a >> 15 GB swap drive. >> The command I have been trying to use is; >> g=numpy.ones([1000,1000,1000],numpy.int32) >> >> This returns a memory error. A smaller array ([500,500,500]) worked >> fine.. Two smaller arrays again crashed the system. >> >> So... I did the math. a 1000x1000x1000 array at 32 bits should be >> around 4gb RAM... Obviously larger than RAM, but much smaller than the >> swap drive. >> >> 1. So... does Numpy have a really lot of overhead? Or is my system >> just not somehow getting to make use of the 15gb swap area. 2. Is >> there a way I can access the swap area, or direct numpy to do so? Or >> do I have to write out my own numpy cache system... 3. How difficult >> is it to use data compression internally on numpy arrays? > > I do not know what numpy does, but constant arrays only need to store > the dimensions and the constant value and have a getitem method that > returns that constant value for any valid index. This is at most a few > hundred bytes regardless of the dimensions. Presumably, he's using numpy.ones() as an example of creating a large array, not because he actually needs an array full of 1s. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From paul at boddie.org.uk Wed Jul 30 11:43:58 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 30 Jul 2008 08:43:58 -0700 (PDT) Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: Message-ID: <2a703a46-75bc-4228-95d1-05a4e6030b40@f63g2000hsf.googlegroups.com> On 30 Jul, 16:32, Simon Willison wrote: > I'm having a horrible time trying to get xml.dom.pulldom to consume a > UTF8 encoded XML file. Here's what I've tried so far: > > >>> xml_utf8 = """ > > Simon\xe2\x80\x99s XML nightmare > """>>> from xml.dom import pulldom > >>> parser = pulldom.parseString(xml_utf8) > >>> parser.next() > > ('START_DOCUMENT', )>>> parser.next() > > ('START_ELEMENT', )>>> parser.next() > > ... > UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in > position 21: ordinal not in range(128) I can't reproduce this on Python 2.3.6 or 2.4.4 on RHEL 4. Instead, I get the usual... ('CHARACTERS', ) And I can get the content of the text node as a proper Unicode object. [...] > Is it possible to consume utf8 or unicode using xml.dom.pulldom or > should I try something else? Yes, it is possible, at least in Python 2.3.6 and 2.4.4 configured with --enable-unicode=ucs4 (which is what Red Hat does and expects). Paul P.S. You shouldn't try and pass Unicode to the parser, since XML parsing in its entirety deals with byte sequences and character encodings, although I suppose that there's some kind of character- based (ie. Unicode value-based) parsing method defined somewhere by some committee or other. From animator333 at gmail.com Fri Jul 25 04:10:52 2008 From: animator333 at gmail.com (King) Date: Fri, 25 Jul 2008 01:10:52 -0700 (PDT) Subject: 2d graphics - what module to use? References: Message-ID: <5519ca3a-bef6-4673-981a-fb327425cfee@w39g2000prb.googlegroups.com> Use python's default GUI tkinter's drawing functions or you can use wxPython GUI kit or you can use pyopengl. If you are only interested to draw sin waves or math functions that you should give try to matlab at www.mathworks.com From s0suk3 at gmail.com Sun Jul 27 00:46:31 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Sat, 26 Jul 2008 21:46:31 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> Message-ID: <6385b0a8-f7f3-4dc3-91be-e6f158ffb439@a1g2000hsb.googlegroups.com> On Jul 26, 6:47 pm, Lawrence D'Oliveiro wrote: > In message > <024ace13-f72f-4093-bcc9-f8a339c32... at v1g2000pra.googlegroups.com>, > > > > s0s... at gmail.com wrote: > > On Jul 24, 5:01 am, Lawrence D'Oliveiro > central.gen.new_zealand> wrote: > > >> In message > >> <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, > >> Jordan wrote: > > >> > Except when it comes to Classes. I added some classes to code that had > >> > previously just been functions, and you know what I did - or rather, > >> > forgot to do? Put in the 'self'. In front of some of the variable > >> > accesses, but more noticably, at the start of *every single method > >> > argument list.* > > >> The reason is quite simple. Python is not truly an "object-oriented" > >> language. It's sufficiently close to fool those accustomed to OO ways of > >> doing things, but it doesn't force you to do things that way. You still > >> have the choice. An implicit "self" would take away that choice. > > > By that logic, C++ is not OO. > > Yes it is, because it has "this". You mean the keyword "this"? It's just a feature. How does that make a difference on being or not being OO? (It's true that C++ has more OO features than Python, like private/ public members, virtual methods, etc. But I don't see how a trivial feature like an additional keyword makes a difference.) From patf at well.com Mon Jul 28 19:04:37 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 16:04:37 -0700 (PDT) Subject: Download excel file from web? References: <6f6vhlFa7anrU1@mid.uni-berlin.de> <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> Message-ID: <19fa0bb2-e101-47c9-84d4-1bf05d08ba39@b2g2000prf.googlegroups.com> On Jul 28, 3:52?pm, "Guilherme Polo" wrote: > On Mon, Jul 28, 2008 at 7:43 PM, p... at well.com wrote: > > On Jul 28, 3:33 pm, "p... at well.com" wrote: > >> On Jul 28, 3:29 pm, "Diez B. Roggisch" wrote: > > >> > p... at well.com schrieb: > > >> > > On Jul 28, 3:00 pm, "p... at well.com" wrote: > >> > >> Hi - experienced programmer but this is my first Python program. > > >> > >> This URL will retrieve an excel spreadsheet containing (that day's) > >> > >> msci stock index returns. > > >> > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > >> > >> Want to write python to download and save the file. > > >> > >> So far I've arrived at this: > > >> > >> [quote] > >> > >> # import pdb > >> > >> import urllib2 > >> > >> from win32com.client import Dispatch > > >> > >> xlApp = Dispatch("Excel.Application") > > >> > >> # test 1 > >> > >> # xlApp.Workbooks.Add() > >> > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > >> > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > >> > >> # xlBook = xlApp.ActiveWorkbook > >> > >> # xlBook.SaveAs(Filename='C:\\test.xls') > > >> > >> # pdb.set_trace() > >> > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > >> excel? > >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> +25%2C+2008&export=Excel_IEIPerfRegional') > >> > >> # test 2 - returns check = False > >> > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > >> > >> indexperf/excel? > >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > >> > >> xlApp = response.fp > >> > >> print(response.fp.name) > >> > >> print(xlApp.name) > >> > >> xlApp.write > >> > >> xlApp.Close > >> > >> [/quote] > > >> > > Woops hit Send when I wanted Preview. ?Looks like the html [quote] tag > >> > > doesn't work from groups.google.com (nice). > > >> > > Anway, in test 1 above, I determined how to instantiate an excel > >> > > object; put some stuff in it; then save to disk. > > >> > > So, in theory, I'm retrieving my excel spreadsheet with > > >> > > response = urllib2.urlopen() > > >> > > Except what then do I do with this? > > >> > > Well for one read some of the urllib2 documentation and found the > >> > > Request class with the method has_data() on it. ?It returns False. > >> > > Hmm that's not encouraging. > > >> > > I supposed the trick to understand what urllib2.urlopen is returning > >> > > to me; rummage around in there; and hopefully find my excel file. > > >> > > I use pdb to debug. ?This is interesting: > > >> > > (Pdb) dir(response) > >> > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > >> > > 'code', ' > >> > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > >> > > 'readline', ' > >> > > readlines', 'url'] > >> > > (Pdb) > > >> > > I suppose the members with __*_ are methods; and the names without the > >> > > underbars are attributes (variables) (?). > > >> > No, these are the names of all attributes and methods. read is a method, > >> > for example. > > >> right - I got it backwards. > > >> > > Or maybe this isn't at all the right direction to take (maybe there > >> > > are much better modules to do this stuff). ?Would be happy to learn if > >> > > that's the case (and if that gets the job done for me). > > >> > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty > >> > clear on this: > > >> > """ > >> > This function returns a file-like object with two additional methods: > >> > """ > > >> > And then for file-like objects: > > >> >http://docs.python.org/lib/bltin-file-objects.html > > >> > """ > >> > read( ? [size]) > >> > ? ? ?Read at most size bytes from the file (less if the read hits EOF > >> > before obtaining size bytes). If the size argument is negative or > >> > omitted, read all data until EOF is reached. The bytes are returned as a > >> > string object. An empty string is returned when EOF is encountered > >> > immediately. (For certain files, like ttys, it makes sense to continue > >> > reading after an EOF is hit.) Note that this method may call the > >> > underlying C function fread() more than once in an effort to acquire as > >> > close to size bytes as possible. Also note that when in non-blocking > >> > mode, less data than what was requested may be returned, even if no size > >> > parameter was given. > >> > """ > > >> > Diez > > >> Just stumbled upon .read: > > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> excel? > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> +25%2C+2008&export=Excel_IEIPerfRegional').read > > >> Now the question is: what to do with this? ?I'll look at the > >> documentation that you point to. > > >> thanx - pat > > > Or rather (next iteration): > > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > > excel? > > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > > The file is generally something like 26 KB so specifying 1,000,000 > > seems like a good idea (first approximation). > > > And then when I do: > > > print(response) > > > I get a whole lot of garbage (and some non-garbage), so I know I'm > > onto something. > > > When I read the .read documentation further, it says that read() has > > returned the data as a string object. ?Now - how do I convince Python > > that the string object is in fact an excel file - and save it to disk? > > You don't need to convince Python, just write it to a file. > More reading for you:http://docs.python.org/tut/node9.html > > > pat > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves OK: response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ excel? priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) # print(response) f = open("c:\\msci.xls",'w') f.write(response) OK this makes the file, and there's a c:\msci.xls in place and it's about the right size. But whether I make the second param to open 'w' or 'wb', when I try to open msci.xls from the Windows file explorer, excel tells me that the file is corrupted. pat From carsten.haese at gmail.com Wed Jul 23 16:48:36 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Wed, 23 Jul 2008 16:48:36 -0400 Subject: Raw Strings (I Think) In-Reply-To: References: Message-ID: Lanny wrote: >> No, it doesn't. Instead of guessing what the cause might be, please show >> us your code and show us the error message you're getting, so that we can >> determine what the cause really is. > > Ok, sorry. Heres my code: > [...] And the error message you're getting is...? -- Carsten Haese http://informixdb.sourceforge.net From tjreedy at udel.edu Tue Jul 22 13:26:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2008 13:26:15 -0400 Subject: Is this a valid use of 'import'? In-Reply-To: References: Message-ID: Frank Millman wrote: > I know that when a module is imported the first time, it is > 'executed'. This normally entails setting up constants, classes, > functions, etc, that you want to make available to the importer. And every time thereafter, the module code is not executed*. So module code should only be code you want executed exactly once, on first import, and never again. > In this particular case, when it is executed, it does a whole lot > more. It reads in some parameters, establishes a socket connection, > starts a thread, and starts monitoring the socket using select.select. > It also exposes some functions that disguise the complexity of reading > from and writing to the socket. What if you want to open another connection, because you want a second, or because you closed the first (to help the server while the client does something else) or because the connection got dropped because the server timed it out or because of network congestion or whatever? tjr *Python2 has a built-in reload function, but in 3.0 it is removed because it almost never did what people wanted or expected and thus lead to surprising bugs. You can delete a module from sys.modules and re-import it, but the module object and those it created will not disappear as long as there are other references to them. From miki.tebeka at gmail.com Fri Jul 4 00:20:41 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 3 Jul 2008 21:20:41 -0700 (PDT) Subject: running python from cmd.exe References: Message-ID: Hello, > I can't seem to get python to run my scripts using the command: python > .py > > If I type python the interpreter runs as I sorted out the Path property, > > I'm afraid I don't know much about this kind of thing as I'm a science > student who needs some Python not a programmer! Can you be more specific about the error you get? Say you have a script hw.py that contains one line: print "Hello Python" and you run python hw.py What is the error you get? HTH, -- Miki http://pythonwise.blogspot.com From pavlovevidence at gmail.com Wed Jul 30 00:17:24 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 21:17:24 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> Message-ID: <7f4a3d37-e551-4e21-b660-3618016cb67b@z6g2000pre.googlegroups.com> On Jul 29, 10:23 pm, Erik Max Francis wrote: > Carl Banks wrote: > > Bzzt. "if len(x)!=0" is a simple explicit that would work for this > > class and all built-in containers. (Or should--Steven D'Aprano's > > objections notwithstanding, any reasonable container type should > > support this invariant. From a language design standpoint, an "empty" > > builtin could have been created to simplify this even more, but since > > there isn't one len(x)!=0 will have to do.) > > That you choose not to test for non-emptiness doesn't change the fact > that it's already a builtin part of the language that is supported by > all fundamental types and is overridable by anyone writing a custom > type. Use it or don't use it, but it's an example of precisely what you > were asking for that is both practical and already in widespread use. That's not what I was asking for. I was asking for a use case for "if x" that can't be replaced by a simple explicit test. Your example didn't satisfy that. Carl Banks From apardon at forel.vub.ac.be Tue Jul 1 07:46:39 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 1 Jul 2008 11:46:39 GMT Subject: Why is recursion so slow? References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Message-ID: On 2008-06-29, slix wrote: > Recursion is awesome for writing some functions, like searching trees > etc but wow how can it be THAT much slower for computing fibonacci- > numbers? Try the following recursive function: def fib(n): def gfib(a, b , n): if n == 0: return a else: return gfib(b, a + b, n - 1) return gfib(0, 1, n) -- Antoon Pardon From tjreedy at udel.edu Wed Jul 9 13:42:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 09 Jul 2008 13:42:14 -0400 Subject: Anyone happen to have optimization hints for this loop? In-Reply-To: <6dk4v0F311k1U1@mid.uni-berlin.de> References: <32fd142e-b198-430e-888b-01aee4e63ac0@c65g2000hsa.googlegroups.com> <6dk4v0F311k1U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > dp_pearce wrote: >> >> count = 0 >> dmntString = "" >> for z in range(0, Z): >> for y in range(0, Y): >> for x in range(0, X): >> fraction = domainVa[count] >> dmntString += " " >> dmntString += fraction Minor point, just construct " "+domain[count] all at once >> count = count + 1 >> dmntString += "\n" >> dmntString += "\n" >> dmntString += "\n***\n >> >> dmntFile = open(dmntFilename, 'wt') >> dmntFile.write(dmntString) >> dmntFile.close() >> >> I have found that it is currently taking ~3 seconds to build the >> string but ~1 second to write the string to file, which seems wrong (I >> would normally guess the CPU/Memory would out perform disc writing >> speeds). >> >> Can anyone see a way of speeding this loop up? Perhaps by changing the >> data format? Is it wrong to append a string and write once, or should >> hold a file open and write at each instance? > > Don't use in-place adding to concatenate strings. It might lead to > quadaratic behavior. Semantically, repeated extension of an immutable is inherently quadratic. And it is for strings in Python until 2.6 or possibly 2.5 (not sure), when more sophisticated code was added because people kept falling into this trap. But since the more sophisticated code 'cheats' by mutating the immutable (with an algorithm similar to list.extend),I am pretty sure it will only be used when there is only one reference to the string and the extension is with +=, so that the extension can reliably be done in-place without changing semantics. Thus, Python programmers should still learn the following. > Use the "".join()-idiom instead: (Or upgrade) > > dmntStrings = [] > .... > dmntStrings.append("\n") > .... > dmntFile.write("".join(dmntStrings)) Note that the minor point above will cut the number of things to be joined nearly in half. tjr From tjreedy at udel.edu Thu Jul 10 15:52:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jul 2008 15:52:08 -0400 Subject: parsing incoming emails In-Reply-To: References: Message-ID: > I am working on a project where I need to parse incoming emails > (Microsoft outlook) with a specific subject into an excel file or a > Microsoft access table. You should be able to give Outlook a rule to call a program (your Python one) when the subject matches whatever. From Python, use the mail module to parse and the windows extensions to access Excel and perhaps Access. There should also be a DBapi extension for accessing Access through sql. Search c.l.p archives, the web, or wait for others to post. From deets at nospam.web.de Mon Jul 28 18:29:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jul 2008 00:29:09 +0200 Subject: Download excel file from web? In-Reply-To: References: Message-ID: <6f6vhlFa7anrU1@mid.uni-berlin.de> patf at well.com schrieb: > On Jul 28, 3:00 pm, "p... at well.com" wrote: >> Hi - experienced programmer but this is my first Python program. >> >> This URL will retrieve an excel spreadsheet containing (that day's) >> msci stock index returns. >> >> http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... >> >> Want to write python to download and save the file. >> >> So far I've arrived at this: >> >> [quote] >> # import pdb >> import urllib2 >> from win32com.client import Dispatch >> >> xlApp = Dispatch("Excel.Application") >> >> # test 1 >> # xlApp.Workbooks.Add() >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' >> # xlBook = xlApp.ActiveWorkbook >> # xlBook.SaveAs(Filename='C:\\test.xls') >> >> # pdb.set_trace() >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ >> excel? >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> +25%2C+2008&export=Excel_IEIPerfRegional') >> # test 2 - returns check = False >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ >> indexperf/excel? >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() >> >> xlApp = response.fp >> print(response.fp.name) >> print(xlApp.name) >> xlApp.write >> xlApp.Close >> [/quote] > > Woops hit Send when I wanted Preview. Looks like the html [quote] tag > doesn't work from groups.google.com (nice). > > Anway, in test 1 above, I determined how to instantiate an excel > object; put some stuff in it; then save to disk. > > So, in theory, I'm retrieving my excel spreadsheet with > > response = urllib2.urlopen() > > Except what then do I do with this? > > Well for one read some of the urllib2 documentation and found the > Request class with the method has_data() on it. It returns False. > Hmm that's not encouraging. > > I supposed the trick to understand what urllib2.urlopen is returning > to me; rummage around in there; and hopefully find my excel file. > > I use pdb to debug. This is interesting: > > (Pdb) dir(response) > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > 'code', ' > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > 'readline', ' > readlines', 'url'] > (Pdb) > > I suppose the members with __*_ are methods; and the names without the > underbars are attributes (variables) (?). No, these are the names of all attributes and methods. read is a method, for example. > Or maybe this isn't at all the right direction to take (maybe there > are much better modules to do this stuff). Would be happy to learn if > that's the case (and if that gets the job done for me). The docs (http://docs.python.org/lib/module-urllib2.html) are pretty clear on this: """ This function returns a file-like object with two additional methods: """ And then for file-like objects: http://docs.python.org/lib/bltin-file-objects.html """ read( [size]) Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread() more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. """ Diez From p0q0b0d at gmail.com Wed Jul 9 03:19:45 2008 From: p0q0b0d at gmail.com (|e0) Date: Wed, 9 Jul 2008 09:19:45 +0200 Subject: Newbie question In-Reply-To: References: <3b1e6f480807082337l419fd40ax91eaf13e0701c5b3@mail.gmail.com> Message-ID: <3b1e6f480807090019p1d9ed0ev7a950d026424f826@mail.gmail.com> So, i can't use wmi module on linux? On Wed, Jul 9, 2008 at 9:14 AM, Lamonte Harris wrote: > I think the win32 module is only for windows. > From wuwei23 at gmail.com Fri Jul 25 10:43:17 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 25 Jul 2008 07:43:17 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <579f9d5b-8984-425d-8d4f-b2ed0be8eaba@o40g2000prn.googlegroups.com> <6c809cef-3549-4887-85c2-9110a2858a9b@y22g2000prd.googlegroups.com> Message-ID: On Jul 25, 9:49?pm, Lie wrote: > These two statements contradicts each other, > implying an implicit Zen: "Foolish consistency is the hobgoblin's > little minds", it is OK to break the rules sometimes. "A foolish consistency is _the_ hobgoblin of little minds." (Ralph Waldo Emerson, although the emphasis is mine) I do like your version, though :) From bj_666 at gmx.net Sun Jul 20 16:27:07 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Jul 2008 20:27:07 GMT Subject: question References: Message-ID: <6ehlcrF6uhc3U4@mid.uni-berlin.de> On Sun, 20 Jul 2008 18:39:52 +0100, Perl_Wizard wrote: > Nobody any sensible answers. Too complicated I suppose! I've often been asked that, i'd be able to buy me a mars bar! Ciao, Marc 'BlackJack' Rintsch From larry.bates at websafe.com` Mon Jul 21 23:59:15 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 21 Jul 2008 22:59:15 -0500 Subject: Python Written in C? In-Reply-To: References: Message-ID: Grant Edwards wrote: > On 2008-07-22, Larry Bates wrote: > >> You talk about "writing it in assembly language for each MPU >> chip". Actually it is even better than that. We now have >> these modern inventions, called compilers that do that type of >> work for us. They translate high level instructions, not >> into assembler but into machine language. > > Actually, all of the compilers I'm familiar with (gcc and a > handful of cross compilers for various microprocessors) > translate from high-level languages (e.g. C, C++) into > assembly, which is then assembled into relocatable object > files, which are then linked/loaded to produce machine > language. > I just learned something I did not know. I was under the impression that they translated directly to machine code without ever actually generating Assembler text files. Seems like a waste to generate the text and turn around run that through the assembler, but what do I know. I guess that way the compiler can have pluggable assembler back-ends. -Larry From mnordhoff at mattnordhoff.com Tue Jul 1 03:12:22 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Tue, 01 Jul 2008 07:12:22 +0000 Subject: Are the following supported in scipy.sparse In-Reply-To: <7f324b8e-e1f9-466e-b6f2-fde8d5f11494@a70g2000hsh.googlegroups.com> References: <7f324b8e-e1f9-466e-b6f2-fde8d5f11494@a70g2000hsh.googlegroups.com> Message-ID: <4869D8D6.3010602@mattnordhoff.com> dingo_1980 wrote: > I wanted to know if scipy.sparse support or will support the following > functions which are available in scipy.linalg or scipy or numpy: > > Inverse > Cholesky > SVD > multiply > power > append > eig > concatenate > > Thanks... You should probably ask on a SciPy mailing list. -- From cheapkobe at sina.com Fri Jul 18 01:16:23 2008 From: cheapkobe at sina.com (14789) Date: Thu, 17 Jul 2008 22:16:23 -0700 (PDT) Subject: wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal Message-ID: <8be58a85-04e1-4617-8ba7-1d10b09b83a3@a3g2000prm.googlegroups.com> wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal wholesale p u m a sneaker(paypal accept)(www goodsaler com)paypal From jordanrastrick at gmail.com Thu Jul 24 01:46:38 2008 From: jordanrastrick at gmail.com (Jordan) Date: Wed, 23 Jul 2008 22:46:38 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: On Jul 24, 3:41?pm, Jordan wrote: > Hi everyone, > > I'm a big Python fan who used to be involved semi regularly in > comp.lang.python (lots of lurking, occasional posting) but kind of > trailed off a bit. I just wrote a frustration inspired rant on my > blog, and I thought it was relevant enough as a wider issue to the > Python community to post here for your discussion and consideration. > > This is not flamebait. I love Python, and I'm not out to antagonise > the community. I also realise that one of the issues I raise is way > too ingrained to be changed now. I'd just like to share my thinking on > a misstep in Python's guiding principles that has done more harm than > good IMO. So anyway, here's the post. > > I've become utterly convinced that at least one criticism leveled at > my favourite overall programming language, Python, is utterly true and > fair. After quite a while away from writing Python code, I started > last night on a whim to knock up some code for a prototype of an idea > I once had. It's going swimmingly; the Python Image Library, which I'd > never used before, seems quick, intuitive, and with the all the > features I need for this project. As for Python itself, well, my heart > still belongs to whitespace delimitation. All the basics of Python > coding are there in my mind like I never stopped using them, or like > I've been programming in this language for 10 years. > > Except when it comes to Classes. I added some classes to code that had > previously just been functions, and you know what I did - or rather, > forgot to do? Put in the 'self'. In front of some of the variable > accesses, but more noticably, at the start of *every single method > argument list.* This cannot be any longer blamed as a hangover from > Java - I've written a ton more code, more recently in Python than in > Java or any other OO language. What's more, every time I go back to > Python after a break of more than about a week or so, I start making > this 'mistake' again. The perennial justification for this 'feature' > of the language? That old Python favourite, "Explicit is better than > implicit." > > I'm sorry, but EXPLICIT IS NOT NECESSARILY BETTER THAN IMPLICIT. > Assembler is explicit FFS. Intuitive, clever, dependable, expected, > well-designed *implicit* behaviour is one of the chief reasons why I > use a high level language. Implicitly garbage collect old objects for > me? Yes, please! > > I was once bitten by a Python wart I felt was bad enough to raise and > spend some effort advocating change for on comp.lang.python (never got > around to doing a PEP; partly laziness, partly young and inexperienced > enough to be intimidated at the thought. Still am, perhaps.) > > The following doesn't work as any sane, reasonable person would > expect: > > # Blog code, not tested > class A(): > ? def __eq__(self, obj): > ? ? return True > a = A() > b = [] > assert a == b > assert not (a != b) > > The second assertion fails. Why? Because coding __eq__, the most > obvious way to make a class have equality based comparisons, buys you > nothing from the != operator. != isn't (by default) a synonym for the > negation of == (unlike in, say, every other language ever); not only > will Python let you make them mean different things, without > documenting this fact - it actively encourages you to do so. > > There were a disturbingly high number of people defending this > (including one quite renowned Pythonista, think it might have been > Effbot). Some had the temerity to fall back on "Explicit is better > than implict: if you want != to work, you should damn well code > __ne__!" > > Why, for heaven's sake, should I have to, when in 99.99% of use cases > (and of those 0.01% instances quoted in the argument at the time only > one struck me as remotely compelling) every programmer is going to > want __ne__ to be the logical negation of __eq__? Why, dear Python, > are you making me write evil Java-style language power reducing > boilerplate to do the thing you should be doing yourself anyway? > What's more, every programmer is going to unconciously expect it to > work this way, and be as utterly as mystified as me when it fails to > do so. Don't tell me to RTFM and don't tell me to be explicit. I'll > repeat myself - if I wanted to be explicit, I'd be using C and > managing my own memory thank you very much. Better yet, I'd explicitly > and graphically swear - swear in frustration at this entrenched design > philosophy madness that afflicts my favourite language. > > I think the real problem with the explicit is better than implicit, > though, is that while you can see the underlying truth its trying to > get at (which is perhaps better expressed by Ruby's more equivocal, > less dependable, but more useful Principle of Least Surprise), in its > stated form its actually kind of meanginless and is used mainly in > defence of warts - no, we'll call them for what they are, a language > design *bugs*. > > You see, the problem is, there's no such thing of explict in > programming. Its not a question of not doing things implicitly; its a > question of doing the most sensible thing implicitly. For example this > python code: > > some_obj.some_meth(some_arg1, some_arg2) > > is implicitly equivalent to > > SomeClass.some_meth(some_obj, some_arg1, some_arg2) > > which in turn gives us self as a reference to some_obj, and Python's > OO model merrily pretends its the same as Java's when in fact is a > smarter version that just superficially looks the same. > > The problem is that the explicit requirement to have self at the start > of every method is something that should be shipped off to the > implicit category. You should have to be explicit, yes - explicit when > you want the *other* behaviour, of self *not* being an argument, > because thats the more unusual, less likely case. > > Likewise, > > a != b > > is implicitly equivalent to something like calling this function (may > not be correct, its a while since I was heavily involved in this > issue): > > def equal(a, b): > ? if hasattr(a, "__ne__"): return a.__ne__(b) > ? if hasattr(b, "__ne__"): return b.__ne__(a) > ? if hasattr(a, "__cmp__"): return not (a.__cmp__(b) == 0) > ? if hasattr(b, "__cmp__"): return not (b.__cmp__(a) == 0) > ? return not (a is b) > > There's absolutely nothing explicit about this. I wasn't arguing for > making behaviour implicit; I was arguing for changing the stupid > implict behaviour to something more sensible and less surprising. > > The sad thing is there are plenty of smart Python programmers who will > justify all kinds of idiocy in the name of their holy crusade against > the implict. > > If there was one change I could make to Python, it would be to get > that damn line out of the Zen. P.S. Forgive the typos, it was blogged in extreme haste and then only quickly proofread and edited before posting here. Hopefully the point I'm making is not diminshed by your reduced respect for me as a result of my carelessness :-) From lemcoe9 at bellsouth.net Fri Jul 18 17:47:39 2008 From: lemcoe9 at bellsouth.net (David M Lemcoe Jr.) Date: Fri, 18 Jul 2008 21:47:39 +0000 (UTC) Subject: Any Game Developers here? References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: Hello Michael, > Any people that use Python as the predominant language for their game > development here? > > ~Michael > Well, I make little CLI games that are extremely basic and have no actual graphics, but i'm sure a few people actually use them in video games. David From tonal at promsoft.ru Thu Jul 17 03:32:35 2008 From: tonal at promsoft.ru (Alexandr N Zamaraev) Date: Thu, 17 Jul 2008 14:32:35 +0700 Subject: Getting a unknown word out of a list with no spaces In-Reply-To: <18502758.post@talk.nabble.com> References: <18502758.post@talk.nabble.com> Message-ID: <487EF593.5060505@promsoft.ru> >>> s = '--a href="/browse/brick"--brick--/a--' >>> s '--a href="/browse/brick"--brick--/a--' >>> ''.join('<%s>' % l if i % 2 == 1 else l for i, l in enumerate(s.split('--'))) 'brick' From nicolas.pourcelot at gmail.com Sun Jul 20 14:33:06 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Sun, 20 Jul 2008 11:33:06 -0700 (PDT) Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> <6ebshqF67cpfU4@mid.uni-berlin.de> <5d6b8066-c941-4f0c-abea-20baed33b4ab@l64g2000hse.googlegroups.com> <569da8b8-df8a-4115-a952-5d8c2d9744e0@i20g2000prf.googlegroups.com> Message-ID: <46c2153d-fef6-45b5-91af-9ecb359e6a2b@2g2000hsn.googlegroups.com> > (1) You are searching through lists to find float objects by identity, > not by value ???? From callen314 at gmail.com Wed Jul 16 21:25:15 2008 From: callen314 at gmail.com (Craig Allen) Date: Wed, 16 Jul 2008 18:25:15 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Message-ID: I don't intend to do much subclassing of this, but of course, I'd rather not second guess the future and it's not hard to imagine we will come to some point that we need to do just that. Thanks for the ideas about repairing option one, which I'd given up, though the ideal is still that tl = TehLibrary() would always return the same object. -craig On Jul 16, 2:00 pm, castironpi wrote: > On Jul 16, 5:20 pm, Craig Allen wrote: > > > > > Hey, forgive me for just diving in, but I have a question I was > > thinking of asking on another list but it really is a general question > > so let me ask it here. It's about how to approach making singletons. > > Background: I've been programming in python seriously for about a year > > now, maybe a little longer depending how you count, and the system I > > am making is sophisticated enough that I've had to enter into a few > > idioms which were beyond my knowledge of python, and I had to do quick > > research and test my ideas with test code (which of course can miss > > subtle problems). Otoh, I have decades of programming experience now > > and wasn't totally without footing. I think I have a solution I like > > for creating something to act as a singleton but I'm curious what > > other's think. > > > I have several classes in our system which need to act like > > singletons, they are libraries of data classifications, and other such > > libraries of configurations for the system which need to be global. > > > The first thing I found searching for singleton, early in this > > project, trying to be a good citizen and find a decent idiom from the > > python community itself, knowing someone had mentioned "singleton" and > > "python" together at some point, was a recommendation to do this: > > > (option 1) > > > class TehLibrary(object): > > __single = None > > def __init__(self): > > if (TehLibrary.__single): > > raise AlreadyExistsException # or whatever > > > This sucks because that means creation of the object has to be in a > > try block as a matter of course, something I promptly hid in a factory > > function, but still. > > > But the way this worked made me realize that the Class itself is a > > full fledged object, quite instance-like from my C++ addled (I love > > you C++) perspective and it's single. If I can store that instance, I > > can make a class that shares member at the class level. The class > > doesn't even have to be a singleton exactly. > > > (option 2) > > Therefore option two is a family of options where class level members > > can be used to share whatever needs to be shared, though strictly the > > class is not a singleton since multiple instances are created which > > merely share the data that should be single (say a big dictionary of > > configuration information the class manages). > > > (option 3) > > I still wanted actual singletons and realized that since I had to > > create a factory function even in option 1, that I could use module > > level variables to control the behavior of those factories, which led > > me to realize I'm basically just using the module itself as a > > singleton. And this is sort of where I have arrived... when I import > > the modules it runs code to build up it's basic services, much like an > > object construction. It only runs once no matter how many times it's > > imported. When client code asks for the library that should be a > > singleton, it gets a singleton which has been stored in a module level > > variable. > > > Anyone have any comments? Is there anything wrong, evil, or ugly > > about using a module this way, or am I correct to think that actually, > > this is a common approach in python. > > > Is it pythonic? > > In option 1, you could use the __new__ method, and return the existing > instance if there is one, or, I believe, call __init__ on the > superclass. Alternatively, define your own 'create' method with the > @classmethod decorator, instantiate with ClassA.create( ), and return > any existing instance from there. The catch is you need to rely on > the discipline of not using the default instantiation syntax. > > In option 2, you would have to wrap the functions with the > @staticmethod decorator, and all instance methods would act on the > same object. > > Each of these have different consequences for inheritance, if that is > on the horizon in your project. From sri_annauni at yahoo.co.in Thu Jul 3 00:55:44 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Thu, 3 Jul 2008 10:25:44 +0530 (IST) Subject: How to pickle bound methods Message-ID: <573056.8255.qm@web7910.mail.in.yahoo.com> Peter, Could you please explain?the code breifly?? I am not getting what it does. Thanks, Srini? ----- Original Message ---- From: Peter Otten <__peter__ at web.de> To: python-list at python.org Sent: Wednesday, 2 July, 2008 12:53:19 PM Subject: Re: How to pickle bound methods srinivasan srinivas wrote: > I would like?to know how to pickle a bound method?? $ cat pickle_method.py import copy_reg import new def make_instancemethod(inst, methodname): ? ? return getattr(inst, methodname) def pickle_instancemethod(method): ? ? return make_instancemethod, (method.im_self, method.im_func.__name__) copy_reg.pickle(new.instancemethod, pickle_instancemethod, make_instancemethod) if __name__ == "__main__": ? ? import pickle ? ? class A(object): ? ? ? ? def __init__(self, who): ? ? ? ? ? ? self.who = who ? ? ? ? def alpha(self): ? ? ? ? ? ? print "Hello,", self.who ? ? FILENAME = "method.pickle" ? ? import sys ? ? args = sys.argv[1:] ? ? if args: ? ? ? ? a = A(args[0]) ? ? ? ? m = a.alpha ? ? ? ? pickle.dump(m, open(FILENAME, "wb")) ? ? else: ? ? ? ? m = pickle.load(open(FILENAME, "rb")) ? ? ? ? m() $ python pickle_method.py world $ python pickle_method.py Hello, world $ python pickle_method.py Srini $ python pickle_method.py Hello, Srini Peter -- http://mail.python.org/mailman/listinfo/python-list Share files, take polls, and make new friends - all under one roof. Go to http://in.promos.yahoo.com/groups/ From Chris.Rathman at gmail.com Tue Jul 22 01:43:24 2008 From: Chris.Rathman at gmail.com (Chris Rathman) Date: Mon, 21 Jul 2008 22:43:24 -0700 (PDT) Subject: proliferation of computer languages References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> Message-ID: <40429b65-23a0-489b-b5fd-ae6b8eee607d@t54g2000hsg.googlegroups.com> I can't say that I see any particular point to the essay. But I did want to point out that Oz should not be considered part of the ML family. Aside from not being statically typed - a very central tenet to ML, Oz is much more part of the Logic family of languages (Mercury, Prolog, etc...). On Jul 18, 12:17 pm, "xah... at gmail.com" wrote: > Today, i took sometime to list some major or talked-about langs that > arose in recent years. > > ML Family: > > * Oz?J. Concurrent. Multiparadigm. > * Alice?J. Concurrent, ML derivative. Saarland University, Germany. > * OCaml?J > * F#?J. Microsoft's functional lang. From peter.anderson at internode.on.net Wed Jul 16 02:39:25 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Wed, 16 Jul 2008 16:39:25 +1000 Subject: Python internals In-Reply-To: <87hcaq7pja.fsf@benfinney.id.au> References: <008ca729$0$20313$c3e8da3@news.astraweb.com> <87hcaq7pja.fsf@benfinney.id.au> Message-ID: <008d93af$0$20327$c3e8da3@news.astraweb.com> Ben Finney wrote: > Larry Bates writes: > > The term "pointer" carries much extra baggage for a programmer > thinking of C (as the original poster is)... Thanks everyone! Just a quick correction - "as the original poster is" is a bit of a jump that does not reflect my original question. I DO understand how C and other programming languages handle variables internally (the bits of actual memory reserved, etc. etc.) and that's why I asked the question in the first place. If Python doesn't do it like C and the others then what mechanism does it use - it's the sort of issue that helps me understand how the language is interacting with the underlying operating system/hardware. By way of background, in my ancient working days I looked after mainframe systems written in COBOL and Natural (and some assembler which I never had to support personally but my staff did). I found that most programmers write bad code because they don't understand what the machine is doing with their code. Probably doesn't matter any more but old habits die hard! ;-) Regards, Peter -- Peter Anderson There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things -- Niccolo Machiavelli, The Prince, ch. 6 From straton at lampsacos.demon.co.uk Fri Jul 11 07:42:58 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 11 Jul 2008 12:42:58 +0100 Subject: PIL: Transparent PNGs and im.paste: ValueError: bad transparency mask In-Reply-To: References: Message-ID: Durand wrote: > I posted this too soon. Converting the images to png with image magick's convert did the trick...However, I'm still not sure why I need to convert the images in the first place. Are there different types of PNGs? http://en.wikipedia.org/wiki/Portable_Network_Graphics#Transparency_of_image From gherron at islandtraining.com Mon Jul 7 18:02:15 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 07 Jul 2008 15:02:15 -0700 Subject: "in"consistency? In-Reply-To: References: Message-ID: <48729267.1060104@islandtraining.com> Nick Dumas wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > [1,2] in [1,2,3] checks to see if the list [1,2] is an item in [1,2,3]. > Because the list [1,2,3] only contains the integers 1,2,3, the code > returns a False. Try "[1,2] in [[1,2],[2,3]]" > The inconsistency goes deeper than that. For instance, the type of a value returned by the indexing operation: Indexing a string returns a string (of length 1 of course), while indexing a list does not (necessarily) return a list. Conclusion: They are different types supporting different operations. Given all the obvious differences (mutability, sorting and other methods, types of individual elements), I'd say there are more differences than similarities, even though, as sequences, they both support a small subset of similar operations. Gary Herron > David C. Ullrich wrote: > >> Luckily I tried it before saying no, that's >> not how "in" works: >> >> >>>>> 'ab' in 'abc' >>>>> >> True >> >>>>> [1,2] in [1,2,3] >>>>> >> False >> >> Is there a reason for the inconsistency? I would >> have thought "in" would check for elements of a >> sequence, regardless of what sort of sequence it was... >> >> > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (MingW32) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iEYEARECAAYFAkhyiwEACgkQLMI5fndAv9jbiwCeKMXrAclILJMPro5VuSRgdkvB > cGkAn1igcjFWRQJSwEDOxpk3spzceZGa > =iq8L > -----END PGP SIGNATURE----- > -- > http://mail.python.org/mailman/listinfo/python-list > From Dogzilla1000 at gmail.com Tue Jul 8 12:44:21 2008 From: Dogzilla1000 at gmail.com (Dogzilla1000 at gmail.com) Date: Tue, 8 Jul 2008 09:44:21 -0700 (PDT) Subject: problem with Tkinter after installing Python 2.5.2 on UBUNTU Message-ID: <83df18ac-e39c-4a1d-95a0-53886d873ea8@s50g2000hsb.googlegroups.com> I just installed Python 2.5.2 on UBUNTU Linux. It seems to work, however I don't seem to have access Tkinter. This is the result of "import Tkinter": Python 2.5.2 (r252:60911, Jul 7 2008, 12:39:49) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Tkinter Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.5/lib-tk/Tkinter.py", line 38, in import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter >>> What do I need to do to configure Python for Tk? From tjreedy at udel.edu Sat Jul 26 18:24:04 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 18:24:04 -0400 Subject: os.walk question In-Reply-To: <92da89760807261310r39df1109j4cf7133d8144508b@mail.gmail.com> References: <92da89760807261310r39df1109j4cf7133d8144508b@mail.gmail.com> Message-ID: Eric Wertman wrote: > I do this, mabye a no-no? It is a roundabout way to do multiple assignment: > import os > for root,dirs,files in os.walk(dir) : break root,dirs,files = os.walk(dir).next #2.x root,dirs,files = next(os.walk(dir))#3.x From deets at nospam.web.de Mon Jul 28 17:39:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 23:39:19 +0200 Subject: Proxy server? In-Reply-To: References: <6f5rteF89muqU2@mid.uni-berlin.de> Message-ID: <6f6sk7Fa4tf5U1@mid.uni-berlin.de> Gary schrieb: > "Diez B. Roggisch" wrote in message > news:6f5rteF89muqU2 at mid.uni-berlin.de... >> Gary wrote: > >> For what? > > A non-transparent proxy, for anonymity purposes only. You can't make any TCP/IP communication run through a proxy, unless it's transparent. HTTP (and maybe FTP, I personally don't know) have that built-in, and of course anything that builds upon them (SOAP, XMLRPC). But e.g. CORBA or bittorrent or .... don't support that. You can try and install TOR or use it. It is a transparent proxy: http://wiki.noreply.org/noreply/TheOnionRouter/TransparentProxy Diez From norseman at hughes.net Thu Jul 10 13:03:01 2008 From: norseman at hughes.net (norseman) Date: Thu, 10 Jul 2008 10:03:01 -0700 Subject: variable question In-Reply-To: <01da01c8e1fb$7615a4f0$a701a8c0@office.ipglobal.net> References: <01da01c8e1fb$7615a4f0$a701a8c0@office.ipglobal.net> Message-ID: <487640C5.5030604@hughes.net> Support Desk wrote: > I am trying to assign a variable using an if / else statement like so: > > > > If condition1: > > Variable = something > > If condition2: > > Variable = something else > > Do stuff with variable. > > > > But the variable assignment doesn't survive outside the if statement. Is > there any better way to assign variables using an if statement or exception > so I don't have to write two almost identical if statements. This is > probably a dumb question. > > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list =================================== Is this test in a def? If in-line there should be no problem if Var is done as this: var= ' ' test= '2' if test == '1': var= 'choice 1' elif test == '2': var= 'choice 2' elif test == '3': var= 'default' #endif #do something with var print var ----------------- if inside a def: var= 0 def xxx(): global var var += 1 # whatever, if var was set to text, do text things #possible other commands #enddef # somewhere below in 'main' (runtime portion of code) xxx() print var #use var, etc. etc. ----------------- It is ALWAYS good form to prime a var before using. Steve norseman at hughes.net From semanticist at gmail.com Thu Jul 31 18:58:24 2008 From: semanticist at gmail.com (Miles) Date: Thu, 31 Jul 2008 18:58:24 -0400 Subject: Difference between type and class In-Reply-To: <87fxpq7x41.fsf@nokile.rath.org> References: <87myjy2vc6.fsf@nokile.rath.org> <87r69a85ek.fsf@nokile.rath.org> <87fxpq7x41.fsf@nokile.rath.org> Message-ID: On Thu, Jul 31, 2008 at 1:59 PM, Nikolaus Rath wrote: > If it is just a matter of different rendering, what's the reason for > doing it like that? Wouldn't it be more consistent and straightforward > to denote builtin types as classes as well? Yes, and in Python 3, it will be so: >>> class myint(int): pass ... >>> int >>> myint The reason the distinction is made currently is that before Python 2.2, "types" were built-in (or C extension) classes, and "classes" were Python classes; it was not possible to subclass built-in types. That "classic" style of classes are still supported in Python 2.2 and above (but not in Python 3), by not inheriting from object or any other built-in. However, for new-style classes, the only distinction is in the repr. >>> class classic: pass ... >>> class newstyle(object): pass ... >>> type(classic) >>> type(classic()) >>> classic.__class__ Traceback (most recent call last): File "", line 1, in AttributeError: class classic has no attribute '__class__' >>> classic().__class__ >>> >>> type(newstyle) >>> type(newstyle()) Further reading: http://www.python.org/download/releases/2.2.3/descrintro/ http://svn.python.org/view?rev=23331&view=rev http://bugs.python.org/issue2565 -Miles From jonas at codeazur.com.br Wed Jul 2 20:16:28 2008 From: jonas at codeazur.com.br (Jonas Galvez) Date: Wed, 2 Jul 2008 21:16:28 -0300 Subject: ANN: XML builder for Python Message-ID: <10df03a30807021716v33518930g951e903c2529ef82@mail.gmail.com> Not sure if it's been done before, but still... from __future__ import with_statement from xmlbuilder import builder, element xml = builder(version="1.0", encoding="utf-8") with xml.feed(xmlns='http://www.w3.org/2005/Atom'): xml.title('Example Feed') xml.link(None, href='http://example.org/') xml.updated('2003-12-13T18:30:02Z') with xml.author: xml.name('John Doe') xml.id('urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6') with xml.entry: xml.title('Atom-Powered Robots Run Amok') xml.link(None, href='http://example.org/2003/12/13/atom03') xml.id('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a') xml.updated('2003-12-13T18:30:02Z') xml.summary('Some text.') print xml Will produce: Example Feed 2003-12-13T18:30:02Z John Doe urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6 Atom-Powered Robots Run Amok urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a 2003-12-13T18:30:02Z Some text. http://github.com/galvez/gae-rest/tree/258066f5e1a32c999e04a9313943fdfa8e64edd9/xmlbuilder.py --Jonas Galvez From alexnbryan at gmail.com Sat Jul 5 07:15:41 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Sat, 5 Jul 2008 06:15:41 -0500 Subject: Margins in the Tkinter Text widget Message-ID: <10942F2C-5D83-4A14-8777-F2B1449E65BC@gmail.com> Okay, so i am trying to have some sort of formatting going on in a textbox, and I need left margins. I see that there are two, one for the first line and th other for every line but that line. My program gives a word and a list of definitions for the word. So my question is how can I make the it repeat itself. Like I want to have something formatted like this: word: definiton1 definition2 word2: defintion12 definition22 and so on. So I don't really understand how to keep like redoing the margins I guess. Would love some help! From sun_tong_001 at users.sourceforge.net Sat Jul 5 18:06:27 2008 From: sun_tong_001 at users.sourceforge.net (* Tong *) Date: Sat, 05 Jul 2008 17:06:27 -0500 Subject: perl + python tutorial available for download References: <86c4090b-ed0b-4249-b3ee-517c94328741@z32g2000prh.googlegroups.com> Message-ID: On Tue, 01 Jul 2008 12:02:24 +0000, Ben Bullock wrote: > I'm a big fan of code samples - most of my code starts as other people's > code samples. What I think is missing, Xah, is that the actual result. I.e, showing that "you can do this" only covers less than half of the tutorial, showing what the result is is more important. From basti.wiesner at gmx.net Sun Jul 6 14:33:42 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sun, 06 Jul 2008 20:33:42 +0200 Subject: Problem with subprocess.Popen wget within a thread References: Message-ID: Mathieu Prevot : > it seems the script (A) finishes before the downloading ends, and the > (B) version doesn't (wanted behavior) ... this is unexpected. What > happens ? "readlines" blocks, until the pipe is closed, which usually happens, if the process dies. On the other hand, spawned processes are usually asynchronous, you have to explicitly _wait_ for them. And you're not waiting for it in example A. Anyway, the _proper_ way to wait for a child process is ... guess what ... the "wait" method of the Popen object ;) -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From casey.mcginty at gmail.com Tue Jul 29 19:07:40 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Tue, 29 Jul 2008 13:07:40 -1000 Subject: How can I check nbr of cores of computer? In-Reply-To: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> Message-ID: On Tue, Jul 29, 2008 at 12:53 PM, defn noob wrote: > How can I check how many cores my computer has? > Is it possible to do this in a Python-app? > -- > http://mail.python.org/mailman/listinfo/python-list > You can use the HAL interface from the DBUS module. See also the gnome-device-manager app which lists all the HAL devices. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Wed Jul 9 11:55:16 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 9 Jul 2008 08:55:16 -0700 (PDT) Subject: Regular Expressions Quick Question References: Message-ID: <5d82ad48-5ffc-44db-a3bd-3773fe7c8709@l64g2000hse.googlegroups.com> On Jul 9, 2:24?am, "Rajanikanth Jammalamadaka" wrote: > hi! > > Try this: > > >>> lis=['t','tes','test','testing'] > >>> [elem for elem in lis if re.compile("^te").search(elem)] > > ['tes', 'test', 'testing'] > > Cheers, > > Raj > > > > > > On Wed, Jul 9, 2008 at 12:13 AM, Lamonte Harris wrote: > > Alright, basically I have a list of words in a file and I load each word > > from each line into the array. ?Then basically the question is how do I > > check if the input word matches multiple words in the list. > > > Say someone input "test", how could I check if that word matches these list > > of words: > > > test > > testing > > tested > > > Out of the list of > > > Hello > > blah > > example > > test > > ested > > tested > > testing > > > I want it to loop then check if the input word I used starts any of the > > words in the list so if I typed 'tes' > > > Then: > > > test > > testing > > testing > > > would be appended to a new array. > > > I'm unsure how to do this in python. > > > Thanks in advanced. > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > "For him who has conquered the mind, the mind is the best of friends; > but for one who has failed to do so, his very mind will be the > greatest enemy." > > Rajanikanth- Hide quoted text - > > - Show quoted text - Give the built-in string functions a try before resorting to the re howitzers: >>> lis=['t','tes','test','testing'] >>> [elem for elem in lis if elem.startswith("te")] ['tes', 'test', 'testing'] -- Paul From dwahli at gmail.com Fri Jul 4 07:21:25 2008 From: dwahli at gmail.com (dwahli at gmail.com) Date: Fri, 4 Jul 2008 04:21:25 -0700 (PDT) Subject: Bug in re.findall? References: Message-ID: <9a34cb6a-4d18-4ab6-8ddd-f44fd450a4e4@m45g2000hsb.googlegroups.com> On Jul 4, 12:33?pm, Marcin Krol wrote: > Hello everyone, > > Is there a bug in re.findall in Python 2.4? See: > > subnetlist="192.168.100.0 , 192.168.101.0" > ipre=re.compile("([0-9]{1,3}\.){3}[0-9]{1,3}") > > ?>>> ipre.findall(subnetlist) > > ['100.', '101.'] > > But: > > a=ipre.finditer(subnetlist) > > ?>>> a.next().group() > '192.168.100.0' > ?>>> a.next().group() > '192.168.101.0' > ?>>> a.next().group() > Traceback (most recent call last): > ? ?File "", line 1, in ? > StopIteration > > Also: > > ?>>> ipre.search(subnetlist).group() > '192.168.100.0' > > Is this a bug or am I doing smth wrong? Look strange but match the Python documentation for re.findall: "If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group" you must use this RE for your example to match what you expect: ipre=re.compile("(?:[0-9]{1,3}\.){3}[0-9]{1,3}") but using re.finditer is IMHO better. Cheer, Dom From bmassel at descartes.com Tue Jul 15 15:51:41 2008 From: bmassel at descartes.com (Brock Massel) Date: Tue, 15 Jul 2008 15:51:41 -0400 Subject: graphing lifelines In-Reply-To: References: Message-ID: <78CC970856BCB3468058B65560DA97D003E7643D@XPOCSCA.corp.descartes.com> Google this: "drawing graphs with dot" dotguide.pdf Look at page ~40ff. Perhaps a simple script to generate graphviz input. Then let those excellent tools do the heavy lifting. -----Original Message----- From: python-list-bounces+bmassel=descartes.com at python.org [mailto:python-list-bounces+bmassel=descartes.com at python.org] On Behalf Of E. J. Gold is the Hi-Tech Shaman Sent: Tuesday, July 15, 2008 14:57 To: python-list at python.org Subject: graphing lifelines (crossposted to sci.math) I'm looking for a tool which will take a dataset of tuples indicating the year of birth and death of a person: (1872, 1950, "Sri Aurobindo") (1821, 1910, "Mary Baker Eddy") (1831, 1891, "HP. Blavatksy") And graph them out, in bars, annotating them with the person's name. A simple spreadsheet would've worked, but they seem to start from zero. Thus, I would only be able to indicate the span of life (by subtracting death year from birth year). -- http://mail.python.org/mailman/listinfo/python-list From adityashukla1983 at gmail.com Wed Jul 23 17:02:18 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Wed, 23 Jul 2008 16:02:18 -0500 Subject: Taking the floating point distances and plotting histogram Message-ID: <73045cca0807231402m1c439414s516e5409a704506f@mail.gmail.com> Hello folks:- I have a program whose output is stored in a text file , say test.txt eg. 0\9\10\11|0.50|c:\windows\apppatch/AcLayers.dll 0\9\10\11|0.50|c:\windows\apppatch/AcRedir.dll 0\9\10|0.66|c:\windows\apppatch/AcSpecfc.dll 0\9|0.83|c:\windows\apppatch/iebrshim.dll After reading this text file i need to extract the float point values from each line ie , 0.50,0.50,0.66.0.83 respectively in this case, till the end of the file is reached and then i need to plot a histogram based on these values . Please provide any hints on how to do this. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Nikolaus at rath.org Tue Jul 29 10:35:55 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Tue, 29 Jul 2008 16:35:55 +0200 Subject: [unittest] Run setUp only once Message-ID: <877ib4rc50.fsf@nokile.rath.org> Hello, I have a number of conceptually separate tests that nevertheless need a common, complicated and expensive setup. Unfortunately, unittest runs the setUp method once for each defined test, even if they're part of the same class as in class TwoTests(unittest.TestCase): def setUp(self): # do something very time consuming def testOneThing(self): def testADifferentThing(self): which would call setUp twice. Is there any way to avoid this, without packing all the unrelated tests into one big function? Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From ldo at geek-central.gen.new_zealand Mon Jul 21 05:15:24 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 21 Jul 2008 21:15:24 +1200 Subject: atan2 weirdness References: <3b3ce28f-55d0-4db4-8eac-df0a9d1bc558@o40g2000prn.googlegroups.com> Message-ID: In message , Carsten Haese wrote: > Since pi is close to 3 ... "Biblical pi" = 3. From mail at timgolden.me.uk Tue Jul 15 12:07:10 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Jul 2008 17:07:10 +0100 Subject: How can I save command prompt screen In-Reply-To: <401698.26103.qm@web44903.mail.sp1.yahoo.com> References: <401698.26103.qm@web44903.mail.sp1.yahoo.com> Message-ID: <487CCB2E.30501@timgolden.me.uk> Ty hensons wrote: > how can i save my command prompt screen? (Trying to be helpful here...) What do mean by "save" and what do you mean by "command prompt screen"? And, especially, what platform are you running on? TJG From paddy3118 at googlemail.com Wed Jul 23 15:56:35 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 23 Jul 2008 12:56:35 -0700 (PDT) Subject: Doubt References: Message-ID: <8c8592be-3bb2-4ee6-9f90-cd374233ba05@w7g2000hsa.googlegroups.com> On Jul 23, 3:51?pm, ???????? wrote: > Friends > > I am a Perl programmer new to Python. I have a small doubt. > How to convert the perl notation > $a = ""; expression in Python ? > > How to represent the loop > for ($a = $b; $a<=$c;$a++){ > > } in Python > > Jagan > Linguist This might help you generally: http://wiki.python.org/moin/PerlPhrasebook - Paddy. From marcus at internetnowasp.net Sat Jul 26 22:23:06 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Sun, 27 Jul 2008 10:23:06 +0800 Subject: Attack a sacred Python Cow In-Reply-To: <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <488BDC0A.50403@internetnowasp.net> Well after reading some of these posts on "sacred python cow" on the "self" , i would generally feel that most programmers who started with C++/Java would find it odd. And its true, i agree completely there should not be a need to put "self" into every single member function. If you were writing an application and one of your classes adds the same variable to each of its member function you would do away with it too. What could be done instead is :- 1. python should hardcode the keyword "self". So whenever this keyword is used, it would automatically implied that it is referring to a class scope variable. This would be similar to how the "this" keyword is used in C++. 2. Omit self from the parameter. class Abc : def DoSomething (a,b,c) : # class variable self.somevar = a self.someblar = b self.somec = c somevar = a * b # local variable Russ P. wrote: > On Jul 26, 2:25 pm, Terry Reedy > >> There is a lot of code you have not seen. Really. In informal code I >> use 's' and 'o' for 'self' and 'other'. I don't usually post such >> because it is not considered polite. So you have seen a biased sample >> of the universe. >> > > You take the name down to a single letter. As I suggested in an > earlier post on this thread, why not take it down to zero letters? You > could if Python accepted something like > > class Whatever: > > def fun( , cat): > > .cat = cat > > This is even better than the single-character name, not only because > it is shorter, but also because there is no question that you are > referring to "self." No need to look back at the method signature to > verify that. > > For those who don't like the way the empty first argument looks, maybe > something like this could be allowed: > > def fun( ., cat): > > -- > http://mail.python.org/mailman/listinfo/python-list > > From zondo42 at googlemail.com Fri Jul 11 17:20:41 2008 From: zondo42 at googlemail.com (Glenn Hutchings) Date: Fri, 11 Jul 2008 22:20:41 +0100 Subject: Graphics References: Message-ID: vanam writes: > hi all > i am new to python programming a beginner. I Came to know from the > groups that "How to think like a computer scientist" is preferable for > begineers. i just looking through that i came to one section where a > sample program for generation of graphics is present.i tried to copy > the same script to the interpreter and it is showing an error i want > to know whether is there anything that has to be installed in addition > to python 2.5 > below is the program > from gasp import * > begin_graphics() > Circle((200, 200), 60) > Line((100, 400), (580, 200)) > Box((400, 350), 120, 100) > end_graphics() You're probably getting an ImportError from the 'from gasp...' line. You need to grab and install the GASP package from https://launchpad.net/gasp. Glenn From durand1 at gmail.com Thu Jul 10 16:31:43 2008 From: durand1 at gmail.com (Durand) Date: Thu, 10 Jul 2008 21:31:43 +0100 Subject: PIL: Transparent PNGs and im.paste: ValueError: bad transparency mask Message-ID: Hi! I'm trying to paste a png with a transparent layer into an image using "image.paste(tesla,(20,10), tesla)" but I'm getting this error: ValueError: bad transparency mask I have used im.paste(image,box,image) sucessfully before to paste an image with transparency, however, it doesn't seem to work for this particular image. How would I change the image so that it doesn't give me this error? The image is http://img293.imageshack.us/img293/1434/teslahv5.png Thanks in advance! From Russ.Paielli at gmail.com Mon Jul 28 00:42:37 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 21:42:37 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> Message-ID: <7360bd9a-4ff6-4e75-821c-eabc88ee6258@u6g2000prc.googlegroups.com> On Jul 27, 8:58 pm, castironpi wrote: > On Jul 27, 2:39 pm, Bruno Desthuilliers > > wrote: > > Derek Martin a ?crit : > > > It's bad programming, but the world is full of bad programmers, and we > > > don't always have the choice not to use their code. Isn't one of > > > Python's goals to minimize opportunities for bad programming? > > > Nope. That's Java's goal. Python's goals are to maximize opportunities > > for good programming, which is quite different. Oh, gosh, that is so clever. What a bunch of crap. > +1 QOTW Do you realize what an insult that is to everyone else who has posted here in the past week? From sjmachin at lexicon.net Sat Jul 19 17:07:10 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 19 Jul 2008 14:07:10 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> <945275e9-8923-479c-8eec-258bd68063c0@z6g2000pre.googlegroups.com> <4881FE02.3000203@gmail.com> Message-ID: On Jul 20, 5:00 am, Andrew Freeman wrote: > Andrew Freeman wrote: > > John Machin wrote: > >> A couple of points: > >> (1) Instead of search(r'^blahblah', ...) use match(r'blahblah', ...) > >> (2) You need to choose your end-anchor correctly; your pattern is > >> permitting a newline at the end: > > I forgot to change search to match. This should be better: > > def match(var): > if re.match(r'[LRM]*\Z', var): > return True > else: > return False A bit wordy ... if blahblah: return True else: return False can in total generality be replaced by: return blahblah > > I was also thinking if you had a list of these items needing to be > verified you could use this: You could, but I suggest you don't use it in a job interview :-) > >>> l = ['LLMMRR', '00thLL', 'L', '\n'] (1) Don't use 'L'.lower() as a name; it slows down reading as people need to fire up their mental parser to distinguish it from the result of 3 - 2 > >>> out = [] > >>> map(lambda i: match(i)==False or out.append(i), l) (2) Read PEP 8 (3) blahblah == False ==> not blahblah (4) You didn't show the output from map() i.e. something like [None, True, None, True] (5) or out.append(...) is a baroque use of a side-effect, and is quite unnecessary. If you feel inexorably drawn to following the map way, read up on the filter and reduce functions. Otherwise learn about list comprehensions and generators. > >>> print out > ['LLMMRR', 'L'] > Consider this: >>> import re >>> alist = ['LLMMRR', '00thLL', 'L', '\n'] >>> zeroplusLRM = re.compile(r'[LRM]*\Z').match >>> filter(zeroplusLRM, alist) ['LLMMRR', 'L'] >>> [x for x in alist if zeroplusLRM(x)] ['LLMMRR', 'L'] >>> Cheers, John From anjalinapriya at gmail.com Wed Jul 30 04:13:51 2008 From: anjalinapriya at gmail.com (sexy) Date: Wed, 30 Jul 2008 01:13:51 -0700 (PDT) Subject: play boy sex videos Message-ID: <7eaac699-2a1d-4c41-a86f-4cb1ae5b4c0f@q5g2000prf.googlegroups.com> play boy sex videos ** SEXY GIRLS HOT SEXY PICTURES AND NUDE VIDEO'S ** ^ Sexy boobs ^^ New Fresh Girls ^^ Nude Sexy Stores ^ **sex galexcy and more ****************************************************** http://www.funnywworld.com http://www.funnywworld.com http://www.funnywworld.com http://www.funnywworld.com ******************************************************* From kay.schluehr at gmx.net Fri Jul 11 17:14:47 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 11 Jul 2008 14:14:47 -0700 (PDT) Subject: ANN: P4D 1.1 References: Message-ID: <13bc226c-e096-4739-a7c5-8f8e1db0c4f5@a70g2000hsh.googlegroups.com> On 11 Jul., 15:25, Fuzzyman wrote: > On Jul 11, 10:09 am, Kay Schluehr wrote: > > > P4D = E4X style embedded DSL for Python but without E and X. > > > For more information see: > > >http://pypi.python.org/pypi/P4D/1.1-py2.5 > > That looks a lot like YAML. Any reason to use it over YAML? > > Michael Foordhttp://www.ironpythoninaction.com/ I considered an embedded YAML DSL for Python a long time ago but YAML and Python are not orthogonal. For instance YAML specifies syntax for lists and dictionaries and also data sections which can be expressed easily as triple quoted strings in Python. Embedding YAML is a bit excessive. Syntactically P4D is inspired by SLiP http://slip.sourceforge.net/ and I'd say it is mostly Python extened by SLiP + extra syntax for element filters and attribute access which was kept from E4X. Why an embedded DSL and not an external one? I don't want to argue about this but just say that you need to feel the difference. Check out the package and start editing P4D elements on the console prompt. It's just like a Python feature... Notice that there was a showstopper in the initial release I announced. It has been corrected here: http://pypi.python.org/pypi/P4D/1.1.1-py2.5 From grante at visi.com Tue Jul 15 15:49:19 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 15 Jul 2008 14:49:19 -0500 Subject: Testing for connection to a website References: Message-ID: On 2008-07-15, Alexnb wrote: > Okay, I already made this post, but it kinda got lost. No, it didn't get lost. Your question was answered and you didn't like the answer. > So anyway I need to figure out how to test if the user is able > to connect to a specific website. Last time I got pointed to > the urllib2 page, but if I do urlopen() and and am not > connected, the program stops. How long did you wait? Depending on what/how/where the network is broken, it make take a minute or two for the connection attempt to fail. You may not like it, but that's how TCP works. You're concerned with TCP connections, so you're going to have to live with it. > So I don't know if that was what you guys wanted me to do, Yes it was what we advised you to do. > but I don't think so, you guys are smarter than that. So, how > can I test for connection to a website. Like we told you: 1) Open a connection using urllib or urllib2. 2) The attempt will either fail or succeed. 3) Proceed accordingly. -- Grant Edwards grante Yow! HUGH BEAUMONT died at in 1982!! visi.com From deets at nospam.web.de Tue Jul 22 09:29:40 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 15:29:40 +0200 Subject: DB Pool References: <40f3a61b-8c37-4e26-90f6-02de760ce00e@c58g2000hsc.googlegroups.com> Message-ID: <6em5o2F7r22oU1@mid.uni-berlin.de> bcurtu wrote: > Hi, > > I use MySQLdb lib to access my DB, because I want to opttimize my sql > queries. The application I'm working on has quite a few traffic load, > so I want to minimize the time of creating/destroying cursors: > > My typical code is sth like: > > cursor=con.cursor() > cursor.execute(sql) > all= cursor.fetchall() > cursor.close() > > So, the question is... how can I minimize this cost? I was thinking on > Connection Pools, but I didn't find any good documentation or sample. > Any idea? What has the above (getting *cursors* from a given connection) to do with connection-pooling? I'm not sure what the actual costs of creating a cursor are (might well be that these are neglibel) but why don't you stop closing the cursor and just re-use it? Connection pooling is of course useful - frameworks such as SQLAlchemy and SQLObject do that for you, if used proper. Diez From mensanator at aol.com Tue Jul 15 13:42:03 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 15 Jul 2008 10:42:03 -0700 (PDT) Subject: isPrime works but UnBoundLocalError when mapping on list References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> <487CD564.5020008@hughes.net> Message-ID: <2d8e4a25-f29e-46b5-a580-ff5663ff29d6@34g2000hsf.googlegroups.com> On Jul 15, 12:28?pm, "Andreas Tawn" wrote: > >defn noob wrote: > >> isPrime works when just calling a nbr but not when iterating on a > >> list, why? adding x=1 makes it work though but why do I have to add > >> it? > >> Is there a cleaner way to do it? > > >> def isPrime(nbr): > >> ? ? for x in range(2, nbr + 1): > >> ? ? ? ? if nbr % x == 0: > >> ? ? ? ? ? ? break > >> ? ? if x == nbr: > >> ? ? ? ? return True > >> ? ? else: > >> ? ? ? ? return False > > >>>>> [isPrime(y) for y in range(11)] > > >> Traceback (most recent call last): > >> ? File "", line 1, in > >> ? ? [isPrime(y) for y in range(11)] > >> ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > >> ? ? if x == nbr: > >> UnboundLocalError: local variable 'x' referenced before assignment > > >>>>> map(isPrime, range(100)) > > >> Traceback (most recent call last): > >> ? File "", line 1, in > >> ? ? map(isPrime, range(100)) > >> ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > >> ? ? if x == nbr: > >> UnboundLocalError: local variable 'x' referenced before assignment > >>>>> isPrime(10) > >> False > >>>>> isPrime(11) > >> True > > >> adding x=1 makes it work though: > > >> def isPrime(nbr): > >> ? ? x=1 > >> ? ? for x in range(2, nbr + 1): > >> ? ? ? ? if nbr % x == 0: > >> ? ? ? ? ? ? break > >> ? ? if x == nbr: > >> ? ? ? ? return True > >> ? ? else: > >> ? ? ? ? return False > > >>>>> [isPrime(y) for y in range(11)] > >> [False, True, True, True, False, True, False, True, False, False, > >> False] > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > >======================================== > >Yep - "local variable 'x' referenced before assignment" is correct. > >You state: for x in range... but x doesn't exist until initialized. > > ? To save a loop, initialize x=2 (the minimum value) and loop executes > > ? on pass one. > >In a straight 'C' program > > ? ( ?for (x=1, x=(nbr+1), x++) ?etc... ?) > > ? the x is initialized and forceably incremented. > > ? seems Python does not auto initialize but does auto increment. > > I think a better explanation is that in your original function, x only > existed while the for loop was running. The for loop never ran. > As soon as execution hit the break statement, It never hit the break statement, the first call from [isPrime(y) for y in range(11)] attempted to do for x in range(2,1). > x ceased to exist. Something has to exist before it can cease to exist. > When you attempted to reference it > in the next line, Python has no variable called x so it complains that x > hasn't been initialised. Right conlusion but false premise. > > A more idiomatic way to write it... > > def isPrime(nbr): > ? ? if nbr <= 1: > ? ? ? ? return False > ? ? for x in xrange(2, nbr+1): > ? ? ? ? if not nbr % x: > ? ? ? ? ? ? return x == nbr > > Cheers, > > Drea From python7946 at gmail.com Wed Jul 2 08:05:39 2008 From: python7946 at gmail.com (Jim Brown) Date: Wed, 2 Jul 2008 20:05:39 +0800 Subject: How to modify the data in a binary file? Message-ID: <21563db10807020505p11561ce2k31d36f2731342c78@mail.gmail.com> Hi all, I'm a Python newbie, so please pardon me if my question may look a little silly. :) I want to modify a binary file p.data (which has some C-style "short" integers -- 16-bit integers) in such a way: The bit m and bit n of every "short int" si in the file are set to 1, and the left bits in si are not affected. I.e, for the first short int in the file, I think the code would be: import os f = os.open("/root/p.data", os.O_RDWR) str = os.read(f, 2) #assume the short int in str is 0x0102, and I want to change it to 0x8182 (changing bit7 and bit15 to 1). #how to change the str into a short int variable si?? ??? si = (si & ~0x8080) | 0x8080 # how to change the si to a two-byte str? ??? os.lseek(f, 0, 0); os.write(f, si) os.close(f) Thanks a lot! -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick at craig-wood.com Mon Jul 28 10:35:28 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 28 Jul 2008 09:35:28 -0500 Subject: ActiveState Code (the new Python Cookbook) has been launched References: Message-ID: Trent Mick wrote: > I happy to announce that ActiveState Code has been taken out of beta. > This is the new site replacing the ASPN Cookbooks -- in particular the > Python Cookbook. > > http://code.activestate.com/ Looks great and much faster than the old site! Mind telling us how it is implemented? I'm guessing python/django by the url and the fact that you have python stuff on your home pages but I could be wrong! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From tcfg at sina.com Wed Jul 16 21:50:37 2008 From: tcfg at sina.com (tcfg at sina.com) Date: Wed, 16 Jul 2008 18:50:37 -0700 (PDT) Subject: how to debug python's extend module written in c/c++ on windows Message-ID: <64d771b2-fbc8-4b6a-9725-3dc5063c5328@p25g2000hsf.googlegroups.com> dear all: I have searched the debug informations of many python's IDE, but I cannot find the method about debuging the extend module written in Visual studio 2008 on windows. The wingIDE tell me that we can debug the extend module on linux, but cannot on windows. and using wingdbstub.py we can embed python into other's source code but not extending. Who can tell me the skills, I appreciate! best regards fang 2008.07.17 From Graham.Dumpleton at gmail.com Mon Jul 21 20:11:15 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Mon, 21 Jul 2008 17:11:15 -0700 (PDT) Subject: Error importing modules with mod_python References: Message-ID: On Jul 22, 3:30?am, Aaron Scott wrote: > I've installedmod_python, and everything seems to be working, but it > fails when I try to import another file into the file that's actually > producing the output. I have these lines at the top of index.py: > > frommod_pythonimport apache > from storylab import * > > ... and in the directory where index.py resides (/htdocs/python/), I > have a directory called "storylab". Inside that directory is > __init__.py. When I try to execute /htdocs/python/index.py, I get the > following error: > > --- > > MOD_PYTHONERROR > ProcessId: ? ? ?828 > Interpreter: ? ?'localhost' > ServerName: ? ? 'localhost' > DocumentRoot: ? 'C:/htdocs' > URI: ? ? ? ? ? ?'/python/index.py' > Location: ? ? ? None > Directory: ? ? ?'C:/htdocs/python/' > Filename: ? ? ? 'C:/htdocs/python/index.py' > PathInfo: ? ? ? '' > Phase: ? ? ? ? ?'PythonHandler' > Handler: ? ? ? ?'index' > > Traceback (most recent call last): > > ? File "C:\Python25\lib\site-packages\mod_python\importer.py", line > 1537, in HandlerDispatch > ? ? default=default_handler, arg=req, silent=hlist.silent) > > ? File "C:\Python25\lib\site-packages\mod_python\importer.py", line > 1202, in _process_target > ? ? module = import_module(module_name, path=path) > > ? File "C:\Python25\lib\site-packages\mod_python\importer.py", line > 296, in import_module > ? ? log, import_path) > > ? File "C:\Python25\lib\site-packages\mod_python\importer.py", line > 680, in import_module > ? ? execfile(file, module.__dict__) > > ? File "C:\htdocs\python\index.py", line 2, in > ? ? from storylab import * > > ImportError: No module named storylab > > --- > > What am I doing wrong? Any insight would be greatly appreciated. You can't put Python packages in same directory as handler scripts managed by mod_python. See documentation for import_module() in: http://www.modpython.org/live/current/doc-html/pyapi-apmeth.html Graham From mail at timgolden.me.uk Fri Jul 11 05:09:50 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 11 Jul 2008 10:09:50 +0100 Subject: importing .dll in a python file In-Reply-To: <4dfaeb7b-8e7e-4f0b-80a8-ed24ed1c46d3@x35g2000hsb.googlegroups.com> References: <4dfaeb7b-8e7e-4f0b-80a8-ed24ed1c46d3@x35g2000hsb.googlegroups.com> Message-ID: <4877235E.80708@timgolden.me.uk> moijes12 wrote: > I need to use a .dll from a python script.I have installed pywin.But > in the program ,which is like: > > import dllName > > I get : > > Import Error : DLL not found > > Please suggest a solution! Well, the short answer is: use the ctypes module. The longer answer is: read around the subject a bit before you expect Python to import an arbitrary DLL and then give up when it doesn't :) TJG From sjmachin at lexicon.net Wed Jul 16 18:33:55 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 16 Jul 2008 15:33:55 -0700 (PDT) Subject: python's YENC.DECODE -> weird output References: <0807160233556.16Jul08$rookswood@suburbian.com> Message-ID: On Jul 16, 11:33 pm, John Savage wrote: > I save posts from a midi music newsgroup, some are encoded with > yenc encoding. This gave me an opportunity to try out the decoders > in Python. The UU decoder works okay, but my YENC effort gives > results unexpected: > > import yenc, sys > > fd1=open(sys.argv[1],'r') > #yenc.encode(sys.argv[1],"outfile.yenc",bytes=0) > yenc.decode(sys.argv[1],"outfile.mid",bytes=0,crc_in='') > > I confirmed that yenc.decode exactly reverses yenc.encode, BUT the > encoding itself seems to differ from the USENET standard. That is, > when I decode USENET files the result isn't a valid music file. > (I did try both with and w/o the headers.) > > Maybe it uses a different character set? I can't quite put my > finger on what might be happening. What I can say is that the > yenc coding from the newsgroup article, when viewed with Linux > 'more', displays roughly 10% of its characters as a question mark, > whereas when I give Python's yenc.encode a binary music file and > view its output using 'more', it displays about 90% of the output > as a question mark. > > Any ideas? 1. It isn't "Python's yenc". Consider directing your question to whoever (if anyone) is maintaining whichever third-party module you are talking about. 2. Consider using a tool that will display what is going on in characters and hex e.g. http://linux.about.com/library/cmd/blcmdl1_hexdump.htm From Nikolaus at rath.org Thu Jul 31 06:37:13 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Thu, 31 Jul 2008 12:37:13 +0200 Subject: Difference between type and class Message-ID: <87myjy2vc6.fsf@nokile.rath.org> Hello, Can someone explain to me the difference between a type and a class? After reading http://www.cafepy.com/article/python_types_and_objects/ it seems to me that classes and types are actually the same thing: - both are instances of a metaclass, and the same metaclass ('type') can instantiate both classes and types. - both can be instantiated and yield an "ordinary" object - I can even inherit from a type and get a class So why does Python distinguish between e.g. the type 'int' and the class 'myclass'? Why can't I say that 'int' is a class and 'myclass' is a type? I hope I have managed to get across the point of my confusion... Thanks in advance, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From hyh_david at hotmail.com Thu Jul 17 15:19:00 2008 From: hyh_david at hotmail.com (hyh_david at hotmail.com) Date: Thu, 17 Jul 2008 12:19:00 -0700 (PDT) Subject: wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal Message-ID: <66dc049d-d057-48a3-b109-8d18ec7042c0@i36g2000prf.googlegroups.com> paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal accept)(www all-wholesaler com)paypal wholesale air bape sneaker(paypal ... From rupole at hotmail.com Thu Jul 31 23:22:27 2008 From: rupole at hotmail.com (Roger Upole) Date: Thu, 31 Jul 2008 23:22:27 -0400 Subject: win32com ChartObject pythonwin vs idle References: <670b57b7-d48e-44c0-abd0-b6772d23688d@79g2000hsk.googlegroups.com> Message-ID: "sterling" wrote in message news:670b57b7-d48e-44c0-abd0-b6772d23688d at 79g2000hsk.googlegroups.com... > I'm curious as to why the difference between IDLE and pythonWin when > using win32com. > opening an excel file, i've attempted to grab the chart information > out of the file. > > commands like co = ChartObjects(1) works in pythonWin but doesn't > work in IDLE. > > however, on both co = chartobjects(1) works just fine. > > The same goes other things like SeriesCollection()/ > seriescollection(1),seriescollection(2)..., Close()/close > > Is there any way to fix it such that IDLE works with ChartObject() > too? I'd really like to be able to use ChartObject().Count() (there > doesn't seem to be an equivalent chartobject.count) > > Thanks. This was probably due to a conflict with the way IDLE sets the locale. Bug report here: http://sourceforge.net/tracker/index.php?func=detail&aid=2006053&group_id=78018&atid=551954 This is fixed in build 212, just released today. Roger From perl_wizard at manx.net Sat Jul 19 05:27:28 2008 From: perl_wizard at manx.net (perl_wizard at manx.net) Date: 19 Jul 2008 10:27:28 +0100 Subject: Question Message-ID: <200807190927.CQP26713@manxnetsf02.manx.net> Why is Perl so much better than python? From M.Busetto at isac.cnr.it Wed Jul 23 03:25:39 2008 From: M.Busetto at isac.cnr.it (maurizio) Date: Wed, 23 Jul 2008 09:25:39 +0200 Subject: maximum value in a column of file Message-ID: <4886DCF3.10107@isac.cnr.it> which is the best way for the calculation of the maximum value in a column of a file? From bignose+hates-spam at benfinney.id.au Sat Jul 12 22:32:06 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 13 Jul 2008 12:32:06 +1000 Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> Message-ID: <87skuems49.fsf@benfinney.id.au> ssecorp writes: > Is this correct use of exceptions? to raise an indexerror and add my > own string insetad of just letting it raise a IndexError by itself > and "blaming" it on list.pop? > > class Stack(object): > def __init__(self, *items): > self.stack = list(items) If you are passing a sequence conceptually, then it's more Pythonic to pass it as a sequence explicitly:: def __init__(self, items): """ Call with e.g. Stack(["foo", "bar"]) """ self.stack = list(items) > def pop(self): > try: > return self.stack.pop() > except: > raise IndexError, "pop from empty stack" Don't use this form of 'raise', it's deprecated. Instead, create the exception instance with the arguments:: raise IndexError("pop from empty stack") Don't use a bare 'except'; you will thereby catch *all* exceptions in the 'try' block, masking errors you did not expect to handle, making debugging unnecessarily difficult. Instead, always be explicit about *which* exceptions you're handling here. Don't catch the exception only to raise a new one; the context of the original exception is lost. If all you want to do is have a different message, modify the existing exception instance's args and re-raise it. try: return self.stack.pop() except IndexError, exc: exc.args = ["pop from empty stack"] raise -- \ ?Experience is that marvelous thing that enables you to | `\ recognize a mistake when you make it again.? ?Franklin P. Jones | _o__) | Ben Finney From sjmachin at lexicon.net Fri Jul 18 19:43:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 18 Jul 2008 16:43:35 -0700 (PDT) Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> <3db7c643-56ca-4d6e-99eb-16176e1a2e88@d19g2000prm.googlegroups.com> <7b2d0e3b-0ee4-4f1b-90d5-90eae9f258a0@u6g2000prc.googlegroups.com> Message-ID: <3dd3ce99-e75b-4d5c-84dc-7854abd9d0e1@w8g2000prd.googlegroups.com> On Jul 18, 11:42 pm, ptn wrote: [snip] > Remember C, where i, j, > k are indices, p, q, r are pointers, s, t are strings and x, y, z are > integers. Only by convention (even-K&R-v1 C required explicit declarations almost everywhere), and x etc being used for integers is news to me ... perhaps you were thinking of m and n. The only language I remember that had implicit typing was FORTRAN (GOD is real, but JESUS is an integer). From python at rcn.com Thu Jul 31 03:21:24 2008 From: python at rcn.com (Raymond Hettinger) Date: Thu, 31 Jul 2008 00:21:24 -0700 (PDT) Subject: Optimizing size of very large dictionaries References: <1217464179.31710.1266222419@webmail.messagingengine.com> Message-ID: <45a2a32e-eb88-4eab-a4de-718896c3dbbb@b2g2000prf.googlegroups.com> > > Are there any techniques I can use to strip a dictionary data > > structure down to the smallest memory overhead possible? Sure. You can build your own version of a dict using UserDict.DictMixin. The underlying structure can be as space efficient as you want. FWIW, dictionaries automatically become more space efficient at largers sizes (50,000+ records). The size quadrupling strategy falls back to just doubling whenever a dict gets two thirds full. > > Background: I'm trying to identify duplicate records in very > > large text based transaction logs. I'm detecting duplicate > > records by creating a SHA1 checksum of each record and using this > > checksum as a dictionary key. This works great except for several > > files whose size is such that their associated checksum > > dictionaries are too big for my workstation's 2G of RAM. Tons of memory can be saved by not storing the contents of the record. Just make an initial pass to identify the digest values of possible duplicates. The use a set to identify actual dups but only store the records for those whose digest is a possible duplicate: bag = collections.defaultdict(int) for record in logs: bag[sha1(record).digest()] += 1 possible_dups = set() while bag: hashval, cnt = bag.popitem() if cnt > 1: possible_dups.add(hashvalue) seen = set() for record in logs: if record in seen: print 'Duplicate:', record elif sha1(record).digest() in possible_dups: seen.add(record) Raymond P.S. If the log entries are one liners, maybe it would be better to use the operating system's sort/uniq filters. From patf at well.com Tue Jul 29 00:47:16 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 21:47:16 -0700 (PDT) Subject: Download excel file from web? References: <6f6vhlFa7anrU1@mid.uni-berlin.de> <3a90a01e-2bd9-43ea-b422-9ef8fb90c23b@a21g2000prf.googlegroups.com> <19fa0bb2-e101-47c9-84d4-1bf05d08ba39@b2g2000prf.googlegroups.com> Message-ID: On Jul 28, 6:05?pm, "Guilherme Polo" wrote: > On Mon, Jul 28, 2008 at 9:39 PM, MRAB wrote: > > On Jul 29, 12:41 am, "p... at well.com" wrote: > >> On Jul 28, 4:20 pm, "Guilherme Polo" wrote: > > >> > On Mon, Jul 28, 2008 at 8:04 PM, p... at well.com wrote: > >> > > On Jul 28, 3:52 pm, "Guilherme Polo" wrote: > >> > >> On Mon, Jul 28, 2008 at 7:43 PM, p... at well.com wrote: > >> > >> > On Jul 28, 3:33 pm, "p... at well.com" wrote: > >> > >> >> On Jul 28, 3:29 pm, "Diez B. Roggisch" wrote: > > >> > >> >> > p... at well.com schrieb: > > >> > >> >> > > On Jul 28, 3:00 pm, "p... at well.com" wrote: > >> > >> >> > >> Hi - experienced programmer but this is my first Python program. > > >> > >> >> > >> This URL will retrieve an excel spreadsheet containing (that day's) > >> > >> >> > >> msci stock index returns. > > >> > >> >> > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > >> > >> >> > >> Want to write python to download and save the file. > > >> > >> >> > >> So far I've arrived at this: > > >> > >> >> > >> [quote] > >> > >> >> > >> # import pdb > >> > >> >> > >> import urllib2 > >> > >> >> > >> from win32com.client import Dispatch > > >> > >> >> > >> xlApp = Dispatch("Excel.Application") > > >> > >> >> > >> # test 1 > >> > >> >> > >> # xlApp.Workbooks.Add() > >> > >> >> > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > >> > >> >> > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > >> > >> >> > >> # xlBook = xlApp.ActiveWorkbook > >> > >> >> > >> # xlBook.SaveAs(Filename='C:\\test.xls') > > >> > >> >> > >> # pdb.set_trace() > >> > >> >> > >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > >> >> > >> excel? > >> > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional') > >> > >> >> > >> # test 2 - returns check = False > >> > >> >> > >> check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > >> > >> >> > >> indexperf/excel? > >> > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > >> > >> >> > >> xlApp = response.fp > >> > >> >> > >> print(response.fp.name) > >> > >> >> > >> print(xlApp.name) > >> > >> >> > >> xlApp.write > >> > >> >> > >> xlApp.Close > >> > >> >> > >> [/quote] > > >> > >> >> > > Woops hit Send when I wanted Preview. ?Looks like the html [quote] tag > >> > >> >> > > doesn't work from groups.google.com (nice). > > >> > >> >> > > Anway, in test 1 above, I determined how to instantiate an excel > >> > >> >> > > object; put some stuff in it; then save to disk. > > >> > >> >> > > So, in theory, I'm retrieving my excel spreadsheet with > > >> > >> >> > > response = urllib2.urlopen() > > >> > >> >> > > Except what then do I do with this? > > >> > >> >> > > Well for one read some of the urllib2 documentation and found the > >> > >> >> > > Request class with the method has_data() on it. ?It returns False. > >> > >> >> > > Hmm that's not encouraging. > > >> > >> >> > > I supposed the trick to understand what urllib2.urlopen is returning > >> > >> >> > > to me; rummage around in there; and hopefully find my excel file. > > >> > >> >> > > I use pdb to debug. ?This is interesting: > > >> > >> >> > > (Pdb) dir(response) > >> > >> >> > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', > >> > >> >> > > 'code', ' > >> > >> >> > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', > >> > >> >> > > 'readline', ' > >> > >> >> > > readlines', 'url'] > >> > >> >> > > (Pdb) > > >> > >> >> > > I suppose the members with __*_ are methods; and the names without the > >> > >> >> > > underbars are attributes (variables) (?). > > >> > >> >> > No, these are the names of all attributes and methods. read is a method, > >> > >> >> > for example. > > >> > >> >> right - I got it backwards. > > >> > >> >> > > Or maybe this isn't at all the right direction to take (maybe there > >> > >> >> > > are much better modules to do this stuff). ?Would be happy to learn if > >> > >> >> > > that's the case (and if that gets the job done for me). > > >> > >> >> > The docs (http://docs.python.org/lib/module-urllib2.html) are pretty > >> > >> >> > clear on this: > > >> > >> >> > """ > >> > >> >> > This function returns a file-like object with two additional methods: > >> > >> >> > """ > > >> > >> >> > And then for file-like objects: > > >> > >> >> >http://docs.python.org/lib/bltin-file-objects.html > > >> > >> >> > """ > >> > >> >> > read( ? [size]) > >> > >> >> > ? ? ?Read at most size bytes from the file (less if the read hits EOF > >> > >> >> > before obtaining size bytes). If the size argument is negative or > >> > >> >> > omitted, read all data until EOF is reached. The bytes are returned as a > >> > >> >> > string object. An empty string is returned when EOF is encountered > >> > >> >> > immediately. (For certain files, like ttys, it makes sense to continue > >> > >> >> > reading after an EOF is hit.) Note that this method may call the > >> > >> >> > underlying C function fread() more than once in an effort to acquire as > >> > >> >> > close to size bytes as possible. Also note that when in non-blocking > >> > >> >> > mode, less data than what was requested may be returned, even if no size > >> > >> >> > parameter was given. > >> > >> >> > """ > > >> > >> >> > Diez > > >> > >> >> Just stumbled upon .read: > > >> > >> >> response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > >> >> excel? > >> > >> >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> >> +25%2C+2008&export=Excel_IEIPerfRegional').read > > >> > >> >> Now the question is: what to do with this? ?I'll look at the > >> > >> >> documentation that you point to. > > >> > >> >> thanx - pat > > >> > >> > Or rather (next iteration): > > >> > >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > >> > excel? > >> > >> > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > >> > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > > >> > >> > The file is generally something like 26 KB so specifying 1,000,000 > >> > >> > seems like a good idea (first approximation). > > >> > >> > And then when I do: > > >> > >> > print(response) > > >> > >> > I get a whole lot of garbage (and some non-garbage), so I know I'm > >> > >> > onto something. > > >> > >> > When I read the .read documentation further, it says that read() has > >> > >> > returned the data as a string object. ?Now - how do I convince Python > >> > >> > that the string object is in fact an excel file - and save it to disk? > > >> > >> You don't need to convince Python, just write it to a file. > >> > >> More reading for you:http://docs.python.org/tut/node9.html > > >> > >> > pat > >> > >> > -- > >> > >> >http://mail.python.org/mailman/listinfo/python-list > > >> > >> -- > >> > >> -- Guilherme H. Polo Goncalves > > >> > > OK: > > >> > > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > >> > > excel? > >> > > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > >> > > +25%2C+2008&export=Excel_IEIPerfRegional').read(1000000) > >> > > # print(response) > >> > > f = open("c:\\msci.xls",'w') > >> > > f.write(response) > > >> > I would initially change that to: > > >> > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&...) > > >> > f = open("c:\\msci.xls", "wb") > >> > for line in response: > >> > ? ? f.write(line) > >> > f.close() > > >> > and then.. > > >> > > OK this makes the file, and there's a c:\msci.xls in place and it's > >> > > about the right size. But whether I make the second param to open 'w' > >> > > or 'wb', when I try to open msci.xls from the Windows file explorer, > >> > > excel tells me that the file is corrupted. > > >> > try it. > > >> > > pat > >> > > -- > >> > >http://mail.python.org/mailman/listinfo/python-list > > >> > -- > >> > -- Guilherme H. Polo Goncalves > > >> A simple f.write(response) does work (click on a single row in Excel > >> and you get a single row). > > >> But I can see that what you recommend Guilherme is probably safer - > >> thanx. > > >> pat > > > If response contains a string then: > > Did you notice I removed the read(...) part ? > > > for line in response: > > ? ?f.write(line) > > > will actually be writing the string one character at a time! > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves Actually no I didn't Guilherme (although I'll take it out now). Would leaving the in urllib2.urlopen().read() imply, as MRAB would seem to indicate, that the following for loop would act byte-by-byte? And if so, how? Even with the .read() in, it was very fast. But it looks like it won't hurt (and very possibly helps) to take it out. pat From Scott.Daniels at Acm.Org Sat Jul 12 15:20:33 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 12 Jul 2008 12:20:33 -0700 Subject: Why is this blowing the stack, thought it was tail-recursive... In-Reply-To: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> References: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> Message-ID: <_MadnaFbKtwVnOTVnZ2dnUVZ_jydnZ2d@pdx.net> ssecorp wrote: > and can memoization speed up this even more? .... Generators get you to an even clearer Fibonacci expression. def _Fibonacci_gen(): a, b = 1, 0 while True: a += b yield a b += a yield b Here's how to use it to avoid redundant comutation: _next_entry = _Fibonacci_gen().next _sofar = [] def fib(n): while len(_sofar) <= n: _sofar.append(_next_entry()) return _sofar[n] --Scott David Daniels Scott.Daniels at Acm.Org From arsyed at gmail.com Thu Jul 24 05:00:15 2008 From: arsyed at gmail.com (arsyed) Date: Thu, 24 Jul 2008 05:00:15 -0400 Subject: Autocompletion and Interactive Tables in a Python IDE In-Reply-To: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> References: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Message-ID: <9a2cc7a70807240200h455cf49cm99bbd5227f2312fc@mail.gmail.com> On Wed, Jul 23, 2008 at 5:28 PM, Anthony wrote: > Hi, I'm a FoxPro programmer, but I want to learn python before it's > too late. I do a lot of statistical programming, so I import SPSS > into python. In my opinion, the best features of Visual FoxPro 9.0 > were: > a) Intellisense (tells you what classes/methods are available and what > variables go into a function) > b) Code Completion (guesses your code after four letters) > c) Data-Orientation; multiple data sessions can be open, data can be > viewed easily > > Python's IDLE has only half of the first of these features. I did a > lot of searching and found the PyDev extensions for Eclipse's Python > IDE, and found that they've got Intellisense. I'm still missing b and > c, and am getting extremely frustrated programming so slowly.. > > So two questions: > Is there any package, gui, IDE, anything that will do FoxPro-style > code completion? If it works in Eclipse, even better.. > I can't find a good screenshot, but here's a better description: > You type "BROW" and it pops up a window that says "BROWSE" ..at this > point if you hit enter it completes the word.. > > and > > How can I view open SPSS data in one of the Python GUIs? Again, > Eclipse would be the preference. > Here's an example of how I'd like to browse the data: > http://www.vfpconversion.com/ArticleImage.aspx?QuickID=0209071&Image=vfptoolkit_figure02.tif > I don't want to have to switch back and forth between Python and SPSS > while I'm programming; I just want to stay in one of them.. > > What can I do? I feel extremely inefficient when I don't have these > three features.. > I don't know of any python IDE that provides the data orientation feature, but there may be an Eclipse plugin for that sort of thing. Otherwise, if you're on windows, check out PyScripter, which is free: http://mmm-experts.com/Products.aspx?ProductId=4 and WingIDE which is quite nice and cross-platform (not free, though): http://www.wingware.com/ I use Vim, which is worth learning IMHO, but somewhat difficult to get started with especially if you're coming from FoxPro. From circularfunc at yahoo.se Sat Jul 5 05:07:04 2008 From: circularfunc at yahoo.se (defn noob) Date: Sat, 5 Jul 2008 02:07:04 -0700 (PDT) Subject: Not necessarily related to python Web Crawlers References: Message-ID: just crawling is supereasy. its how to index and search that is hard. just start at yahoo.com, scrape out all the links and then for every site visit every link. i wrote a crawler in 15 lines of code. but then it all it did was visit the sites, not indexing them or anything. you could write a faster one in C++ probably but if you are new to it doing it in python will let you experiment and learn faster. some links: http://infolab.stanford.edu/~backrub/google.html http://www-csli.stanford.edu/~hinrich/information-retrieval-book.html http://www.example-code.com/python/pythonspider.asp http://www.example-code.com/python/spider_simpleCrawler.asp From samwyse at gmail.com Tue Jul 8 08:59:02 2008 From: samwyse at gmail.com (samwyse) Date: Tue, 8 Jul 2008 05:59:02 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> On Jul 4, 6:43?am, Henning_Thornblad wrote: > What can be the cause of the large difference between re.search and > grep? > While doing a simple grep: > grep '[^ "=]*/' input ? ? ? ? ? ? ? ? ?(input contains 156.000 a in > one row) > doesn't even take a second. > > Is this a bug in python? You might want to look at Plex. http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/ "Another advantage of Plex is that it compiles all of the regular expressions into a single DFA. Once that's done, the input can be processed in a time proportional to the number of characters to be scanned, and independent of the number or complexity of the regular expressions. Python's existing regular expression matchers do not have this property. " I haven't tested this, but I think it would do what you want: from Plex import * lexicon = Lexicon([ (Rep(AnyBut(' "='))+Str('/'), TEXT), (AnyBut('\n'), IGNORE), ]) filename = "my_file.txt" f = open(filename, "r") scanner = Scanner(lexicon, f, filename) while 1: token = scanner.read() print token if token[0] is None: break From steve at REMOVE-THIS-cybersource.com.au Mon Jul 28 10:07:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Jul 2008 14:07:44 GMT Subject: QOTW [was Re: Attack a sacred Python Cow] References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> <7360bd9a-4ff6-4e75-821c-eabc88ee6258@u6g2000prc.googlegroups.com> Message-ID: <009dce32$0$20313$c3e8da3@news.astraweb.com> On Sun, 27 Jul 2008 21:42:37 -0700, Russ P. wrote: >> +1 QOTW > > Do you realize what an insult that is to everyone else who has posted > here in the past week? Actually I don't. I hadn't realised that when a person believes that somebody has made an especially clever, witty, insightful or fun remark, that's actually a put-down of all the other people whose remarks weren't quite as clever, witty, insightful or fun. But now that I've had this pointed out to me, why, I see insults everywhere! Tonight, my wife said to me that she liked my new shirt, so I replied "What's the matter, you think my trousers are ugly?" -- Steven From bignose+hates-spam at benfinney.id.au Sun Jul 20 06:48:50 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 20 Jul 2008 20:48:50 +1000 Subject: __del__ methods References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> <87hcalxvx0.fsf@benfinney.id.au> Message-ID: <87prp8x23x.fsf@benfinney.id.au> "Robert Rawlins" writes: > This isn?t something I'd seen before (god that makes me feel stupid). No need to feel stupid, unless you've had the opportunity to learn and passed it by. > I've always based my code off the odd example that's dotted around Time to fix that, then, with some documentation , and by working through the Python tutorial . -- \ ?I was married by a judge. I should have asked for a jury.? | `\ ?Groucho Marx | _o__) | Ben Finney From fredrik at pythonware.com Tue Jul 15 14:52:22 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2008 20:52:22 +0200 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: Victor Noagbodji wrote: > what's the difference between these two statement? one checks if the given object is not None, the other checks if it's a true value: http://docs.python.org/ref/Booleans.html#Booleans > And which one should one use? depends on what you want to test for, of course. From kyosohma at gmail.com Mon Jul 14 09:12:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 14 Jul 2008 06:12:25 -0700 (PDT) Subject: a module.pth question References: Message-ID: On Jul 14, 6:26?am, oyster wrote: > My py24 is installed in h:\python24 > I installed pyglet(http://pyglet.org/) in > H:\pure_pylib\Multimedia\pyglet-1.0\, if I do > [code]>>> import sys > >>> sys.path.append(r'H:\pure_pylib\Multimedia\pyglet-1.0') > >>> import pyglet > > [/code] > it is ok. > > but if I created h:\pure_pylib\pyglet.pth file, which containts > [code] > Multimedia\pyglet-1.0 > [/code] > > then > [code]>>> import sys > >>> sys.path.append(r'h:\pure_pylib') > >>> import pyglet > > Traceback (most recent call last): > ? File "", line 1, in ? > ImportError: No module named pyglet > > [/code] > > what is wrong with it? and How to fix it? thanks in advance I looked in my easy_install.pth and it looks like it should be: .\Multimedia\pyglet-1.0 But I don't really see any reason not to do it the way you were earlier with the full path name. Besides, you should be able to install pyglet to your site-packages folder. Or you could use buildout if you're just testing modules and you don't want to screw up your namespace. Mike From gherron at islandtraining.com Thu Jul 31 12:16:16 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 31 Jul 2008 09:16:16 -0700 Subject: How smart is the Python interpreter? In-Reply-To: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> References: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> Message-ID: <4891E550.7010106@islandtraining.com> ssecorp wrote: > def str_sort(string): > s = "" > for a in sorted(string): > s+=a > return s > > > if i instead do: > > def str_sort(string): > s = "" > so = sorted(string) > for a in so: > s+=a > return s > > > will that be faster or the interpreter can figure out that it only has > to do sorted(string) once? or that kind of cleverness is usually > reserved for compilers and not interpreters? > -- > http://mail.python.org/mailman/listinfo/python-list > The 'for' statement is only executed once of course. It's the body of the 'for' which is executed multiple times. So in both pieces of code, the 'sorted' is only executed once, and the returned string is bound to a name in the second but not the first. However, you are worrying about optimizing the wrong things here. The 's+=a' line has terrible (quadratic) performance. Instead use the string method 'join' which has linear performance. def str_sort(string): return "".join(sorted(string)) No for loop, no inefficient accumulation. Gary Herron From nick83ola at gmail.com Tue Jul 1 02:57:39 2008 From: nick83ola at gmail.com (nickooooola) Date: Mon, 30 Jun 2008 23:57:39 -0700 (PDT) Subject: Implementing an 8 bit fixed point register Message-ID: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> Hello to all I'm about to write a simulator for a microcontroller in python (why python? because I love it!!!) but I have a problem. The registry of this processor are all 8 bit long (and 10 bit for some other strange register) and I need to simulate the fixed point behaviour of the register, and to access the single bit. f.x. (this is a pseudo python session, only for understanding) >>> reg1 = fixed_int(8) >>> reg2 = fixed_int(10) >>> reg1[0].set() or >>> reg1[0] = 1 # or True? how to rapresent a binary bit >>> reg1[0] 1 >>> reg1[1] 0 >>> reg1[9] >>> reg2 = 0x7FE # in binary 11111111110 , or 11 bit long >>> reg2 0x7FE #or 1111111110, the memorization truncate the upper bits ( or perhaps generate an exception?) >>> reg2 += 0x02 #the result is 10000000000, again not contained in 10 bit >>> reg2 0x00 # truncated again >>> myprocessor.flags['z'] 1 # or True? Z flag indicated an overflow in arithmetic operations Is possibile to do so in python? thanks From alexnbryan at gmail.com Thu Jul 3 04:51:56 2008 From: alexnbryan at gmail.com (Alex Bryan) Date: Thu, 3 Jul 2008 03:51:56 -0500 Subject: Creating an .exe with Tkinter involved Message-ID: <1BB24C28-FCDF-4FC5-84CA-D79EAD477FCA@gmail.com> I know this is possible so someone out there should be able to help me! Okay, I have a program that uses Tkinter, and BeautifulSoup. I don't think it should be a problem. I want to create an exe of it. I have py2exe but I don't really know how to work it. I read their tutorial thing and did a setup that looked something like this: from distutils.core import setup import py2exe setup(console['myFunProgram.py']) (isn't really called myFunProgram) This seems terribly wrong however because... it isn't a console app. So I am wondering if anyone can show me how or point me in the right direction to a place where I can learn how to do this. I would appreciate it! From jordanrastrick at gmail.com Fri Jul 25 22:49:57 2008 From: jordanrastrick at gmail.com (Jordan) Date: Fri, 25 Jul 2008 19:49:57 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> Message-ID: <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> Well this discussion is chugging along merrily now under its own steam, but as the OP I should probably clarify a few things about my own views since people continue to respond to them (and are in some cases misunderstanding me.) I *like* explicit self for instance variable access. There are arguments for and against, and my personal opinion is that the arguments for are stronger. Local variables and instance variables should be explicitly differentiated somehow, for the sake of readability. Python's approach works. I slightly prefer Ruby's @, because I think the brevity is a net win for something so commonplace (is it less readable? Maybe. is "def" less readable than "define"? I don't know - I think about 10 seconds of coding in Python or Ruby is enough for you to be able to instantly grok def. Likewise, @. The argument is more aesthetic IMO - how many perl-style/1337speak pu|\| (tu at t10n m at r|<$ can you stand?) I have come to dislike explicit self in method argument lists. Sure, there are reasons. I don't think they're at all strong enough. I'm definitely against the != behaviour, and maybe will get around to actually PEPing it. The point I was trying to make originally was that applying any mantra dogmatically, including Explicit is better than implicit, can lead to bad results. Perhaps having Practicality beats purity is enough of a reminder of that fact for the Python community :-) From pavlovevidence at gmail.com Thu Jul 31 23:56:33 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 31 Jul 2008 20:56:33 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> Message-ID: <6813ac09-18f9-4950-bef6-91d4dfcdb577@k13g2000hse.googlegroups.com> On Jul 30, 10:05 pm, Erik Max Francis wrote: > Russ P. wrote: > > On Jul 30, 1:07 am, Erik Max Francis wrote: > >> Russ P. wrote: > >>> Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > >>> __nonzero__ work in Python. It's very basic stuff. You can quit > >>> patronizing me (and Carl too, I'm sure). > >> You suggested a syntax for testing non-emptiness (`x is not empty`) > >> which indicated a profound misunderstanding of what the `is` operator does. > > >> You then acknowledged that there might be a problem because of the > >> implication if the `is` operator and weren't sure whether it would work > >> or not: > > > Oh, my. I wrote something like, "It would sure be nice to be able to > > write > > > if x is not empty: > > > because it reads like natural language. Immediately after I posted it, > > I thought, "oh, I'll bet some idiot takes that as a serious proposal." > > Sure enough, some idiot did just that almost immediately. > > Yes, all people are idiots for reading what you wrote, reading your > later realization that it was wrong, and taking both at face value. > I'll be sure never to make that mistake again! I thought it was obvious that he was paraphrasing. I also think that, among the people who took it literally, those who are not an ass would have accepted his explanation that he was paraphrasing it and moved on, rather than rubbing it in. If you recall, I agreed with his statement. Would you like to claim that I don't understand the fundamentals of Python? Carl Banks From tjreedy at udel.edu Mon Jul 7 01:53:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 07 Jul 2008 01:53:02 -0400 Subject: Very weird bug! In-Reply-To: <1c1c343a-dd63-454a-8e29-a5c70281ad90@c58g2000hsc.googlegroups.com> References: <1c1c343a-dd63-454a-8e29-a5c70281ad90@c58g2000hsc.googlegroups.com> Message-ID: ssecorp wrote: > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > wtf was this in the middle!? > >>>> def build(a,b): > return a+b > >>>> build(5,4) > (5, 4) I have exactly the same build on Windows and get the expected 9. Try it again. From jorjun at gmail.com Thu Jul 10 08:13:16 2008 From: jorjun at gmail.com (jorjun) Date: Thu, 10 Jul 2008 05:13:16 -0700 (PDT) Subject: Automatic keyword argument source change? Message-ID: <8caa4111-52af-4df8-9bbf-7261835ef53a@34g2000hsf.googlegroups.com> Anyone know of a Python source code utility PSU, to automatically add keyword arguments to method calls that don't have them? : BEFORE def get_total(books, binders, hinges): return (binders.total + hinges.total - books.cost) def print_total(): print get_total(novels, covers, brackets) AFTER .... def print_total(): -- print get_total(novels, covers, brackets) ++ print get_total(books=novels, binders=covers, hinges=brackets) From grflanagan at gmail.com Thu Jul 3 03:29:12 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Thu, 03 Jul 2008 09:29:12 +0200 Subject: ANN: XML builder for Python In-Reply-To: <10df03a30807021716v33518930g951e903c2529ef82@mail.gmail.com> References: <10df03a30807021716v33518930g951e903c2529ef82@mail.gmail.com> Message-ID: Jonas Galvez wrote: > Not sure if it's been done before, but still... > > from __future__ import with_statement > from xmlbuilder import builder, element > > xml = builder(version="1.0", encoding="utf-8") > with xml.feed(xmlns='http://www.w3.org/2005/Atom'): > xml.title('Example Feed') > xml.link(None, href='http://example.org/') > xml.updated('2003-12-13T18:30:02Z') > with xml.author: > xml.name('John Doe') > xml.id('urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6') > with xml.entry: > xml.title('Atom-Powered Robots Run Amok') > xml.link(None, href='http://example.org/2003/12/13/atom03') > xml.id('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a') > xml.updated('2003-12-13T18:30:02Z') > xml.summary('Some text.') > print xml > > Will produce: > > > > Example Feed > > 2003-12-13T18:30:02Z > > John Doe > > urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6 > > Atom-Powered Robots Run Amok > > urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a > 2003-12-13T18:30:02Z > Some text. > > > > http://github.com/galvez/gae-rest/tree/258066f5e1a32c999e04a9313943fdfa8e64edd9/xmlbuilder.py > > --Jonas Galvez > -- > http://mail.python.org/mailman/listinfo/python-list > Nice! Here's a version that uses elementtree: 8<---------------------------------------------------- from __future__ import with_statement from xml.etree import ElementTree as ET class element(object): def __init__(self, name, parent): self.parent = parent self.element = ET.SubElement(parent, name) def __str__(self): return ET.tostring(self.parent) def __getattr__(self, name): return element(name, self.parent) def __getitem__(self, name): return element(name, self.parent) def __enter__(self): self.parent = self.element return self def __exit__(self, type, value, tb): pass def __call__(self, value='', **kargs): self.element.text = value self.element.attrib = kargs return self class builder(element): def __init__(self, version, encoding): self.parent = ET.Element('root') if __name__ == "__main__": xml = builder(version="1.0", encoding="utf-8") with xml.feed(xmlns='http://www.w3.org/2005/Atom') as feed: feed.title('Example Feed') feed.link(href='http://example.org/') feed.updated('2003-12-13T18:30:02Z') with feed.author as author: author.name('John Doe') feed.id('urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6') with feed.entry as entry: entry.title('Atom-Powered Robots Run Amok', class_='l') entry.link(href='http://example.org/2003/12/13/atom03') entry.id('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a') entry.updated('2003-12-13T18:30:02Z') entry.summary('Some text.') with feed.entry as entry: entry.title('2') entry.link(href='2') entry.id('2') entry.updated('2') entry.summary('2') print xml 8<---------------------------------------------------- From tjreedy at udel.edu Sun Jul 27 13:17:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 13:17:30 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <009c29cc$0$20302$c3e8da3@news.astraweb.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c29cc$0$20302$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Sun, 27 Jul 2008 10:23:06 +0800, Marcus.CM wrote: > >> Well after reading some of these posts on "sacred python cow" on the >> "self" , i would generally feel that most programmers who started with >> C++/Java would find it odd. > > You know, there are some programmers who haven't started with C++ or Java. Like my teenager, who is only 1 of many kids learning Python as a first algorithm language. If not now, eventually, I expect a majority of Python programmers to *not* be C++/Java graduates. tjr From smalladi at gmail.com Thu Jul 10 14:35:59 2008 From: smalladi at gmail.com (Sashi) Date: Thu, 10 Jul 2008 11:35:59 -0700 (PDT) Subject: Elisp Lesson on file processing (make downloadable copy of a website) References: Message-ID: <7095dc5e-3008-45b8-8665-e746bff84dd6@m36g2000hse.googlegroups.com> On Jul 6, 4:05 am, "xah... at gmail.com" wrote: > In this week i wrote a emacs program and tutorial that does archiving > a website for offline reading. > (Seehttp://xahlee.org/emacs/make_download_copy.html) Why not use wget or curl? From noreply at yahoo.com Tue Jul 1 05:20:26 2008 From: noreply at yahoo.com (Kirk) Date: 1 Jul 2008 09:20:26 GMT Subject: Freeze problem with Regular Expression References: <6cf614F3f8ocoU1@mid.individual.net> <0e1a9726-cc1d-4bd2-b0ba-b2bcc1c27ee8@f24g2000prh.googlegroups.com> <6cs9rtF3g9fsvU1@mid.individual.net> <08a8164c-fb82-4265-a84e-c0ccd92a01db@a32g2000prf.googlegroups.com> Message-ID: <6cub6qF3g9fsvU2@mid.individual.net> On Mon, 30 Jun 2008 13:43:22 -0700, John Machin wrote: >> I reply here to all of you about such point: that's not important, >> although I appreciate very much your suggestions! My point was >> 'something that works in Perl, has problems in Python'. > > It *is* important; our point was 'you didn't define "works", and it was ok... > near-impossible (without transcribing your regex into verbose mode) to > guess at what you suppose it might do sometimes'. fine: it's supposed to terminate! :-) Do you think that hanging is an *admissible* behavior? Couldn't we learn something from Perl implementation? This is my point. Bye -- Kirk From bdesth.quelquechose at free.quelquepart.fr Sun Jul 27 15:39:26 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Jul 2008 21:39:26 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> Message-ID: <488ceae5$0$11227$426a34cc@news.free.fr> Derek Martin a ?crit : > On Sun, Jul 27, 2008 at 08:19:17AM +0000, Steven D'Aprano wrote: >>> You take the name down to a single letter. As I suggested in an earlier >>> post on this thread, why not take it down to zero letters? >> The question isn't "why not", but "why". The status quo works well as it >> is, even if it isn't perfect. Prove that implicit self is a good idea -- >> or at least prove that it is an idea worth considering. > > Come on, this sounds like a schoolyard argument. This comes down to a > matter of style, and as such, is impossible to prove. It's largely a > question of individual preference. > > That said, the argument in favor is rather simple: > > 1. This is an extremely common idiom in Python > 2. It is completely unnecessary, and the language does not suffer for > making it implicit > 3. Making it implicit reduces typing, reduces opportunities for > mistakes, and arguably increases consistency. "arguably", indeed, cf below. > As for the latter part of #3, self (or some other variable) is > required in the parameter list of object methods, It's actually the parameter list of the *function* that is used as the implementation of a method. Not quite the same thing. And then, consistency mandates that the target object of the method is part of the parameter list of the *function*, since that's how you make objects availables to a function. > however when the > method is *called*, it is omitted. Certainly not. You need to lookup the corresponding attribute *on a given object* to get the method. Whether you write some_object.some_method() or some_function(some_object) you still need to explicitely mention some_object. > It is implied, supplied by Python. Neither. The target object is passed to the function by the method object, which is itself returned by the __get__ method of function objects, which is one possible application of the more general descriptor protocol (the same protocol that is used for computed attributes). IOW, there's nothing specific to 'methods' here, just the use of two general features (functions and the descriptor protocol). FWIW, you can write your own callable, and write it so it behave just like a function here: import types class MyCallable(object): def __call__(self, obj): print "calling %s with %s" % (self, obj) def __get__(self, instance, cls): return types.MethodType(self.__call__, instance, cls) class Foo(object): bar = MyCallable() print Foo.bar f = Foo() f.bar() > Thus when an object method is called, it must be called with one fewer > arguments than those which are defined. This can be confusing, > especially to new programmers. This is confusing as long as you insist on saying that what you "def"ined is a method - which is not the case. > It can also be argued that it makes the code less ugly, though again, > that's a matter of preference. > >> It's not enough to show that a change "isn't bad" -- you have to show >> that it is actively good. > > But he did... he pointed out that *it saves work*, without actually > being bad. Benefit, without drawback. Sounds good to me! > >> "Don't need to look at the method signature" is not an argument in favour >> of implicit self. > > Yes, actually, it is. It isn't, since there's no "method signature" to look at !-) > If there is a well-defined feature of Python > which provides access to the object within itself, The point is that you don't get access to the object "within itself". You get access to an object *within a function*. The fact that a function is defined within a class statement doesn't imply any "magic", it just creates a function object, bind it to a name, and make that object an attribute of the class. You have the very same result by defining the function outside the class statement and binding it within the class statement, by defining the function outside the class and binding it to the class outside the class statement, by binding the name to a lambda within the class statement etc... > then the > opportunities for mistakes when someone decides to use something else > are lessened. > >> You don't need to look at the method signature when you're using an >> explicit self either. > > That isn't necessarily true. If you're using someone else's code, and > they didn't use "self" -- or worse yet, if they chose this variable's > name randomly throughout their classes -- then you may well need to > look back to see what was used. > > It's bad programming, but the world is full of bad programmers, and we > don't always have the choice not to use their code. Isn't one of > Python's goals to minimize opportunities for bad programming? Nope. That's Java's goal. Python's goals are to maximize opportunities for good programming, which is quite different. > Providing a keyword equivalent to self and removing the need to name > it in object methods is one way to do that. It's also a way to make Python more complicated than it needs to be. At least with the current state, you define your functions the same way regardless of how they are defined, and the implementation is (relatively) easy to explain. Special-casing functions definition that happens within a class statement would only introduce a special case. Then you'd have to explain why you need to specify the target object in the function's parameters when the function is defined outside the class but not when it's defined within the class. IOW : there's one arguably good reason to drop the target object from functions used as methods implementation, which is to make Python looks more like Java, and there's at least two good reason to keep it the way it is, which are simplicity (no special case) and consistency (no special case). Anyway, the BDFL has the final word, and it looks like he's not going to change anything here - but anyone is free to propose a PEP, isn't it ? From israelu at elbit.co.il Tue Jul 15 16:12:28 2008 From: israelu at elbit.co.il (iu2) Date: Tue, 15 Jul 2008 13:12:28 -0700 (PDT) Subject: bad recursion, still works References: <7bf2bad5-d6b6-4929-a520-a82b7bb49916@34g2000hsf.googlegroups.com> Message-ID: <5be12739-7896-4112-9307-53897af4f691@f63g2000hsf.googlegroups.com> On Jul 15, 9:30?pm, mdshe... at gmail.com wrote: > On Jul 15, 2:59?pm, iu2 wrote: > > > > > Hi, > > > I wrote this wrong recursive function that flattens a list: > > > def flatten(lst, acc=[]): > > ? ? #print 'acc =', acc, 'lst =', lst > > ? ? if type(lst) != list: > > ? ? ? ? acc.append(lst) > > ? ? else: > > ? ? ? ? for item in lst: > > ? ? ? ? ? ? flatten(item) > > ? ? return acc > > > a = [1, 2, [3, 4, 5], [6, [7, 8, [9, 10], 11], 12], 13, 14] > > b = flatten(a) > > print b > > > I was amazed to realize that it flattens the list alright. Why? 'acc' > > should be an empty list on each invocation of flatten, but is seems to > > accumulate anyway... > > When you say acc=[] in the function declaration, it binds acc to a > particular list object, rather than to a concept of an empty list. > Thus, all operations being performed on acc are being performed on the > same list. If, after the sample code you provided, were to call > > c = flatten([15,16,17,[18,19]]) > print c > > you would get back the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, > 13, 14, 15, 16, 17, 18, 19]. > > Mark Sherry I still don't understand: In each recursive call to flatten, acc should be bound to a new [], shouldn't it? Why does the binding happen only on the first call to flatten? From scottpig1 at comcast.net Sun Jul 27 20:45:48 2008 From: scottpig1 at comcast.net (pigmartian) Date: Sun, 27 Jul 2008 20:45:48 -0400 Subject: Where is the correct round() method? In-Reply-To: References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> Message-ID: it could be that 3.0 is using "banker's rounding" --- rounding to the even digit. the idea behind it behind it being to reduce error accumulation when working with large sets of values. > Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo > CPU". What system are you on? > > > It could be that 2.5 is really 2.49999... which would round down to 2, > but on any modern CPU (using IEEE floating point), 2.5 should be > representable exactly. > > From bj_666 at gmx.net Fri Jul 18 17:15:15 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Jul 2008 21:15:15 GMT Subject: how to avoid line return when using python -c 'print "foo"' References: <63d7l5-72p.ln1@rama.nodalpoint> Message-ID: <6ecff3F67cpfU6@mid.uni-berlin.de> On Fri, 18 Jul 2008 23:04:06 +0200, TP wrote: > All my problem is in the title. > If I try: > > $ python -c 'print "foo",' > > It does not change anything, surely because the line return is added > by "python -c". It is added by the interpreter at exit time. The interpreter tries to be smart here deciding for you that the last printed line before program exit should end in a newline. Use `sys.write()` instead of ``print``. Ciao, Marc 'BlackJack' Rintsch From tonal at promsoft.ru Thu Jul 17 04:45:48 2008 From: tonal at promsoft.ru (Alexandr N Zamaraev) Date: Thu, 17 Jul 2008 15:45:48 +0700 Subject: common elements between list of lists and lists In-Reply-To: <2724c6f8-d75d-4fc2-ac8f-310f4f622aae@p25g2000hsf.googlegroups.com> References: <2724c6f8-d75d-4fc2-ac8f-310f4f622aae@p25g2000hsf.googlegroups.com> Message-ID: <487F06BC.4000202@promsoft.ru> >>> list4 = [['1', 'a'],['4', 'd'],['8', 'g']] >>> list5 = [1, 2, 3] >>> set5 = set(list5) >>> [x for n, x in list4 if int(n) in set5] ['a'] From fredrik at pythonware.com Wed Jul 23 05:44:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 11:44:50 +0200 Subject: maximum value in a column of file In-Reply-To: <4886F4CD.8010704@isac.cnr.it> References: <4886DCF3.10107@isac.cnr.it> <4886F4CD.8010704@isac.cnr.it> Message-ID: maurizio wrote: > i tryed to use the module max of numpy, > the problem is that i don't know how to put the column of the file in an > array. > (i'm new in phyton). > anyway if you think there is a better way..... What kind of file is it? Did you pick numpy because you want to do matrix operations (beyond just finding a maximum value), or was it just the first thing you stumbled upon when researching the problem? A simple pattern for finding the maximum value in a file, using only plain Python code, is: max_value = ... some very small value ... for line in file: value = ... extract value from line ... if value > max_value: max_value = value If it's not obvious what "some very small value" is, given the range of data you're working with, you can do max_value = None for line in file: value = ... extract value from line ... if max_value is None or value > max_value: max_value = value instead (this leaves max_value set to None if the file is empty) A more experienced Python hacker might write def get_all_values(file): for line in file: value = ... extract value from line ... yield value ... max_value = max(get_all_values(file)) instead. But this still leaves us with the problem of extracting the value. The best way to do that depends on the kind of files you're working with; for fixed-format text files, you could use string slicing and int/float for conversion (e.g. "value = float(line[10:20])", see the tutorial for details); for other text formats, you could use split/partition or regular expressions, or maybe an existing module (such as "csv"); for binary formats, there's a large number of existing tools. And if you really want to use numpy for other reasons than just getting a maximum value from a column, there's plenty of stuff in NumPy and SciPy (http://www.scipy.org/) that might be useful. So, in other words, I guess we still need more info. From tjreedy at udel.edu Thu Jul 17 21:47:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jul 2008 21:47:30 -0400 Subject: interpreter vs. compiled In-Reply-To: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> Message-ID: castironpi wrote: > On Jul 17, 5:37 pm, I V wrote: > > > Oh. How is the stack represented? As usual, as successive locations in memory. I have the impression that CPython uses the same stack C does. While conceptually, CPython may put objects on the stack, I am pretty sure it actually stacks references (C pointers) to objects in heap memory. > Does it keep track of which stack > positions (TOS, TOS1, etc.) are in what registers? I am sure they are not in registers, just normal memory. The C code that implements bytecodes to act on stack values will use registers just like any other C code. So using registers for the stack would get in the way. Of course, the C code might load pointers on the stack into address registers when actually needed. But this depends on the address scheme of a particular processor and how the C code is compiled to its object code. > Does stack manipulation consume processor cycles? Of course. For much more, you should peruse the CPython source. From andymac at bullseye.apana.org.au Thu Jul 10 06:15:11 2008 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 10 Jul 2008 21:15:11 +1100 Subject: Retrieving BSTR * from a DLL In-Reply-To: <500e422d-5868-4a2b-a213-7d4d13a51d23@j22g2000hsf.googlegroups.com> References: <500e422d-5868-4a2b-a213-7d4d13a51d23@j22g2000hsf.googlegroups.com> Message-ID: <4875E12F.8090401@bullseye.andymac.org> mzdude wrote: > I need to interface with a windows DLL that has the following > signature > > extern "C" void Foo( BSTR in, BSTR *out ) > > Code so far > >>>> from ctypes import * >>>> import comtypes >>>> LPBSTR = POINTER(comtypes.BSTR) >>>> >>>> hdl = windll.MyDll.Foo >>>> hdl.rettype = None >>>> hdl.argtypes = [comtypes.BSTR, LPBSTR] >>>> >>>> inStr = comtypes.BSTR(u'Some Silly String') >>>> out = comtypes.BSTR out = comtypes.BSTR() >>>> hdl(inStr,byref(out)) > > Traceback (most recent call last): > File "", line 1, in > hdl(inStr,byref(out)) > TypeError: byref() argument must be a ctypes instance, not > '_ctypes.SimpleType' comtypes.BSTR is a type; the type error makes clear you need an instance, as above. > Also tried the following > >>>> out = comtypes.BSTR(u'') >>>> p = pointer(out) >>>> hdl(inStr,p) > > Traceback (most recent call last): > File "", line 1, in > hdl(inStr,p) > ValueError: Procedure probably called with too many arguments (8 bytes > in excess) This likely indicates that the DLL is using the C calling convention and not the stdcall calling convention. Use CDLL rather than WinDLL to load the DLL. You might like to join the ctypes-users mailing list at sourceforge. -- ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From timr at probo.com Fri Jul 18 02:18:07 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 18 Jul 2008 06:18:07 GMT Subject: % sign in python? References: Message-ID: <48d08494p4jnhkrhgidmgppg1aostmurvn@4ax.com> Steven Howe wrote: >Terry Reedy wrote: >> >> korean_dave wrote: >>> What does this operator do? Specifically in this context >>> >>> test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) > >I thought, in this contexted, it was mapping operator. What?? Python does not have a "mapping operator". It has a "map" function, but no equivalent operator. % is either the string formatting operator (when the left-hand operand is a string) or the modulo operator (when the left-hand operand is a number). -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dariusz.malec at gmail.com Thu Jul 24 15:28:24 2008 From: dariusz.malec at gmail.com (Dariusz Malec) Date: Thu, 24 Jul 2008 21:28:24 +0200 Subject: curses problem References: Message-ID: forgot to post the code. Server does not allow to post attachments. The code is here http://www.kos.wsiz.rzeszow.pl/~dmalec/src.zip -- Dariusz Malec http://www.kos.wsiz.rzeszow.pl JID:dmalec at jabber.kos.wsiz.rzeszow.pl From q2w3qw14 at gmail.com Sun Jul 27 22:46:36 2008 From: q2w3qw14 at gmail.com (Sera Jackson) Date: Sun, 27 Jul 2008 19:46:36 -0700 (PDT) Subject: I love "shelf" BUT Message-ID: ok, I know its an over discussed topic. Althought I understand why it is there I cant constantly see it in my argument list in parenthesis. can someone give me an insight of the cons of a syntax like this: class Class: def self.method(arguments): etc, etc In other words def method(self, arg1, arg2 ,argN) becomes-> def self.method(arg1, arg2 ,argN) From richard at pyweek.org Sat Jul 19 00:50:15 2008 From: richard at pyweek.org (richard at pyweek.org) Date: Sat, 19 Jul 2008 14:50:15 +1000 Subject: Python game programming challenge, NUMBER 7, in September! Message-ID: <200807191450.16148.richard@pyweek.org> The date for the SEVENTH bi-annual PyWeek challenge has been set: Sunday 7th September to Sunday 14th September (00:00UTC to 00:00UTC). http://pyweek.org/ The PyWeek challenge invites entrants to write a game in one week from scratch either as an individual or in a team. Entries must be developed in Python, during the challenge, and must incorporate some theme chosen at the start of the challenge. REGISTRATION IS NOT YET OPEN -- In order to reduce the number of unnecessary registrations, we will open the challenge for registration one month before the start date. See the competition timetable and rules: http://www.pyweek.org/ PLANNING FOR THE CHALLENGE -- Make sure you have working versions of the libraries you're going to use. The rules page has a list of libraries and other resources. Make sure you know how to build an MD5 sum for your submission. See the challenge help page for more information. Make sure you can build packages to submit as your final submission (if you're going to use py2exe, make sure you know how to use it and that it works). If you don't have access to Linux, Windows or a Mac to test on, contact friends, family or other competitors to find someone who is able to test for you. -- Visit the PyWeek website: http://www.pyweek.org/ From animator333 at gmail.com Mon Jul 28 05:39:30 2008 From: animator333 at gmail.com (King) Date: Mon, 28 Jul 2008 02:39:30 -0700 (PDT) Subject: Read .txt file like .py file References: <90f13013-bb20-4224-ac58-02947f3f9358@i24g2000prf.googlegroups.com> <488c77ee$0$29452$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <389d95bf-15c7-44bb-a317-16854e1a0631@v13g2000pro.googlegroups.com> Well, I have a look to into compiler module and gave it a try using compiler.parseFile and compiler.walk but I haven't got what I need here. From james at reggieband.com Fri Jul 11 06:00:47 2008 From: james at reggieband.com (James Fassett) Date: Fri, 11 Jul 2008 03:00:47 -0700 (PDT) Subject: Moving to functional programming Message-ID: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> Hi all, Had a simple problem that turned into an interesting solution and I thought I would share it here. I had a list of tuples that I needed to get the first value from and generate a list. tuple_list = ( ('John', 'Doe'), ('Mark', 'Mason'), ('Jeff', 'Stevens'), ('Bat', 'Man') ) # what I'd do in C or other procedural languages result_list = [] for item in tuple_list: result_list.append(item[0]) # the first Pythonic attempt using comprehensions result_list = [x[0] for x in tuple_list] # the final functional way [result_list, _] = zip(*tuple_list) I really like how Python allows me to do what I feel is the most natural solution (for a seasoned procedural programmer) while allowing a satisfying path towards a more functional approach. Cheers, James From steve at REMOVE-THIS-cybersource.com.au Mon Jul 28 10:11:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Jul 2008 14:11:12 GMT Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <488d86e2$1@news2-rz-ap.ethz.ch> <488dc3eb$1@news2-rz-ap.ethz.ch> Message-ID: <009dcf02$0$20313$c3e8da3@news.astraweb.com> On Mon, 28 Jul 2008 15:04:43 +0200, Suresh Pillai wrote: > I could of course use the old trick of using a dictionary with 'None' > values and then using iterkeys(). But I thought sets were supposed to > replace this. So maybe I should be asking a more basic question: is > there any way to iterate over the items in a set other than converting > to a list or using the pop() method. Yes, just do it. >>> for i in set([1,2,3]): ... print i ... 1 2 3 -- Steven From martin at v.loewis.de Sun Jul 27 14:31:07 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 27 Jul 2008 20:31:07 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: References: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> Message-ID: <488cbeeb$0$17104$9b622d9e@news.freenet.de> > - AMD64 (or x86-64 or x64 or EMT64 or Intel64) is a 64-bit instruction > set from AMD which is an extension to the i386 instruction set, and runs > 32-bit (and 16-bit) i386-code natively. But, and this is important, > despite the name the instruction set is also used by Intel (though they > call it EMT64 and made a few minor changes). Indeed, there are (unfortunately) many names for the architecture. Originally, AMD called it x86-64, and later renamed it to AMD64. Intel originally implemented it under the name EM64T (for Extended Memory 64 Technology), and now calls the architecture Intel 64. Microsoft (apparently not wanting to take sides) calls it x64. I personally believe that whoever invents a technology also gets to name it, so I encourage use of the name AMD gives it (which is AMD64). That's why the Python installer has that label in its name. Regards, Martin From Russ.Paielli at gmail.com Sat Jul 26 17:16:42 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 26 Jul 2008 14:16:42 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> Message-ID: <370a7975-cc00-4c15-b095-7c942d8084ed@i24g2000prf.googlegroups.com> > > So why not allow something like this?: > > > class MyClass: > > > def func( , xxx, yyy): > > > .xxx = xxx > > > local = .yyy > > > The "self" argument is replaced with nothing, but a comma is used as a > > placeholder. > > (+1) but why retain the leading comma in > the argument list? As I said, the leading comma is a place holder. Without it, the interpreter would have no way of knowing that the first argument is not just another name for "self." We need to maintain compatibility with existing Python rules. If we were designing a new language, we could omit the "self" argument in the signature, and allow either ".xxx" or "self.xxx," at the programmers discretion (i.e., let "self" be the standard name, like "this" in C++). From list-ener at strank.info Thu Jul 31 05:53:34 2008 From: list-ener at strank.info (Stefan Rank) Date: Thu, 31 Jul 2008 11:53:34 +0200 Subject: working pylint anyone? In-Reply-To: <6fdf17Fb2bboU1@mid.uni-berlin.de> References: <6fdf17Fb2bboU1@mid.uni-berlin.de> Message-ID: <48918B9E.9020403@strank.info> on 31.07.2008 11:29 Diez B. Roggisch said the following: > > The packaged version of pylint (0.13.2) fails with this error (last line): > > > So - anybody out here having an actually working pylint config and can tell > me what versions work together? I've become pretty dependend on it to be > honest... Three installations of pylint 0.14.0 that I have access to from here: pylint.bat 0.14.0, astng 0.17.2, common 0.27.0 Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] pylint 0.14.0, astng 0.17.2, common 0.31.0 Python 2.5.2 (r252:60911, Jul 23 2008, 00:17:15) [GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] pylint 0.14.0, astng 0.17.2, common 0.27.0 Python 2.5.1 (r251:54863, Jul 11 2007, 15:07:18) [GCC 3.3.5 (Debian 1:3.3.5-13)] All of them installed using good old setup.py (times 3). easy_install does not work as you noted. Hope that helps. cheers, stefan From karthikbalaguru79 at gmail.com Thu Jul 24 05:08:31 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Thu, 24 Jul 2008 02:08:31 -0700 (PDT) Subject: Requires a character ... !! Message-ID: Hi, I am new to python . I am face few problems related with python and iam trying to resolve it. The below is the error that i get when i invoke my application by giving the necessary input file. [root at localhost hello]# Analyzer hello_input Loading debug info: hello_input Traceback (most recent call last): File "/usr/local/SDK/host/bin/Analyzer", line 694, in ? app.dbg.readObjectInfo(elf) File "/usr/local/SDK/host/bin/debugprocessor.py", line 427, in readObjectInfo self.privateProcessorDwarfTree.readProcessorDwarfTree(filename) File "/usr/local/SDK/bin/debugprocessor.py", line 314, in readDwarfTree if "DW_OP_reg" in value: TypeError: 'in ' requires character as left operand Is this related with the version conflicts ? Should i need to configure any environment variables or change some source code. Any ideas ? Thx in advans, Karthik Balaguru From fredrik at pythonware.com Mon Jul 21 10:19:23 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 16:19:23 +0200 Subject: imported module no longer available In-Reply-To: <8496caf30807210656y3d8467eer83a953e7c37e556c@mail.gmail.com> References: <8496caf30807210656y3d8467eer83a953e7c37e556c@mail.gmail.com> Message-ID: Jeff Dyke wrote: > I've come across an error that i'm not yet able to create a test case > for but wanted to get see if someone could shed light on this. > > I have imported a module at the top of my file with > import mymodulename > > this module is used many times in the current file successfully, but > then I attempt to use it one more time and get: UnboundLocalError: > local variable 'mymodulename' referenced before assignment Let me guess: you've done def myfunc(): print mymodulename import mymodulename or something similar? Getting an exception in this case is the excepted behaviour; the reason being that a variable in a block only belongs to a single scope. for the entire block. For details, see: http://docs.python.org/ref/naming.html Especially this section: "If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can lead to errors when a name is used within a block before it is bound. This rule is subtle. Python lacks declarations and allows name binding operations to occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations." To fix this, mark the name as global: def myfunc(): global mymodulename # I mean the global name! print mymodulename import mymodulename From code at pizzashack.org Mon Jul 21 16:45:31 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 21 Jul 2008 16:45:31 -0400 Subject: Change PC to Win or Windows In-Reply-To: <82873ccd-9667-4dfa-9ec4-a9ac7c672aa7@w1g2000prk.googlegroups.com> References: <7a6c8b36-c9ac-402f-87c6-64cde4df498d@k36g2000pri.googlegroups.com> <82873ccd-9667-4dfa-9ec4-a9ac7c672aa7@w1g2000prk.googlegroups.com> Message-ID: <20080721204531.GE8793@dragontoe.org> On Mon, Jul 21, 2008 at 12:32:00PM -0700, Lie wrote: > > The term "PC" is commonly used in English, in the United States > > and other English speaking countries, to mean a computer running > > Microsoft Windows. > > As far as I am aware, they're like that because most people aren't > even aware that there are other OSes than Microsoft Windows. You are missing two points. The first one: It doesn't matter what the reasons are for the terminology to be common. It only matters that it IS common. It is; and it is therefore "correct" in the sense that it conveys a meaning to the overwhelming majority of English speakers, which is the intended one. As for the question of whether or not it is appropriate to refer to Windows installations as "PC", it's as simple as that. It is, by definition (via common usage). That is what this thread is about. > The reason why the world hasn't evolved to the two predictable cases > ("all kinds of microcomputers" or "IBM-PC and clones"), is what I'll > explain below. Your explanation is irrelevant to the argument of whether or not the term PC is an inappropriate term to describe a Windows installation, which is what this thread is about. That is the premise put forth by the OP, and that is the notion to which I am responding. It simply is not wrong or inappropriate in any sense; it is in fact correct, regardless of how the meaning or usage resulted, and regardless of any ADDITIONAL meanings the term may have. For what it's worth, your explanation is also WRONG; the term PC began to be popularly used in the United States to describe Intel-based Microsoft machines when there was a proliferation of other kinds of personal computers available to consumers. When it was first used this way, the IBM PC was *NOT* the most popular personal computer... the Commodore 64 was. It dates from a time when the Commodore VIC-20 and C64, Atari 400 and 800, Timex Sinclair, and other computers were all very popluar home machines. The term probably originated primarily because IBM chose to name their computer the IBM PC, and because of Americans' predeliction to abbreviate everything that's more than 2 syllables. ;-) > > It wasn't something that Apple started; it's been used this way > > in increasingly common usage for at least 20 years, although > > exactly what combination of hardware and software was being > > refered to as a "PC" has evolved over that timeframe. > > Apple popularizes the term by explicit marketing, And here is the last point you are missing: Apple does no such thing. They are only using a term in a way that has previously been popularized by the computer industry as a whole, and its market (i.e. consumers, predominantly American consumers historically) for *DECADES*. If I'm not mistaken, their ad campaign mentioning PCs is less than 10 years old (though I can't quickly find any references as to the date). The popularization of the term PC to refer to Intel-compatible machines running Microsoft OSes PREDATES APPLE'S AD CAMPAIGN BY OVER 10 YEARS. Therefore none of your points are valid or relevant, as to the question of whether the usage of the term "PC" to describe windows builds of Python is appropriate. Can we return to the subject of Python now? -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jkugler at bigfoot.com Thu Jul 10 15:01:51 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Thu, 10 Jul 2008 11:01:51 -0800 Subject: Problems Returning an HTTP 200 Ok Message References: <1cf880cc-2036-42dc-8217-d52a714c1710@a70g2000hsh.googlegroups.com> Message-ID: Guy Davidson wrote: > Hi Folks, > > I'm having some issues with an small socket based server I'm writing, > and I was hoping I could get some help. > > My code (attached below) us supposed to read an HTTP Post message > coming from a power meter, parse it, and return a proper HTTP 200 Ok > message. The problem is that the socket fails to send the entire > message as one message, creating a fragmented message which the power > meter then fails to read and accept. > > Is there any way to force the socket to send the entire message at > once? Am I doing anything wrong? Is there an easier way to implement > this functionality? I don't have a solution to the problem presented, per se, but you might have an easier time implementing this if you use SimpleHTTPServer or CGIHTTPServer modules. This will take care of all the socket listening, and a lot of other low-level details. Hope that helps! j From duncan.booth at invalid.invalid Thu Jul 17 16:58:44 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jul 2008 20:58:44 GMT Subject: decorating a method in multiple child classes References: Message-ID: 1x7y2z9 at gmail.com wrote: > I wish to decorate all of the CX.func() in the same way. One way to > do this is to add a decorator to each of the derived classes. But > this is tedious and involves modifying multiple files. > > Is there a way to modify the parent class and have the same effect? > Or some other way neater than the above? > Use a metaclass. >>> def decorate(f): print "decorating", f return f >>> class meta(type): def __init__(self, name, bases, dictionary): if 'func' in dictionary: dictionary['func'] = decorate(dictionary['func']) type.__init__(self, name, bases, dictionary) >>> class P(object): __metaclass__ = meta >>> class C1(P): def func(self): pass decorating >>> From bj_666 at gmx.net Tue Jul 1 16:50:34 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Jul 2008 20:50:34 GMT Subject: Please check my understanding... References: Message-ID: <6cvjkqF9eaU2@mid.uni-berlin.de> On Tue, 01 Jul 2008 12:35:01 -0700, Tobiah wrote: > list.append([1,2]) will add the two element list as the next > element of the list. > > list.extend([1,2]) is equivalent to list = list + [1, 2] > and the result is that each element of the added list > becomes it's own new element in the original list. It's not 100% equivalent because `list.extend()` mutates the original list while ``+`` creates a new list object: In [8]: a = [1, 2, 3] In [9]: b = a In [10]: b.extend([4, 5]) In [11]: b Out[11]: [1, 2, 3, 4, 5] In [12]: a Out[12]: [1, 2, 3, 4, 5] In [13]: b = b + [6, 7] In [14]: b Out[14]: [1, 2, 3, 4, 5, 6, 7] In [15]: a Out[15]: [1, 2, 3, 4, 5] > Is that the only difference? > > From the manual: > > s.extend(x) | same as s[len(s):len(s)] = x > > But: (python 2.5.2) > >>>> a > [1, 2, 3] >>>> a[len(a):len(a)] = 4 > Traceback (most recent call last): > File "", line 1, in > TypeError: can only assign an iterable >>>> Have you tried `extend()` with the same value? In [15]: a Out[15]: [1, 2, 3, 4, 5] In [16]: a.extend(6) --------------------------------------------------------------------------- Traceback (most recent call last) /home/bj/ in () : 'int' object is not iterable See, both ways need something iterable. Ciao, Marc 'BlackJack' Rintsch From mrkafk at gmail.com Tue Jul 1 12:07:49 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Tue, 01 Jul 2008 18:07:49 +0200 Subject: Embedding Python In-Reply-To: References: Message-ID: Carsten Haese wrote: > python_code is a C string containing the raw bytes from your pyc file. > Casting that to a PyObject pointer will not magically transform it into > a Python code object. well yeah, I kind of didn't think that through.. A pyc file contains the following: > > 1) An 8 byte header containing a magic number. > 2) A "marshal" serialization of the code object. > > So, in order to transform those contents into a code object, you need to > skip the 8 byte header and an unmarshal the rest. Basically, replace the > line above with something like this: > > codeobj = PyMarshal_ReadObjectFromString(python_code+8, size-8); > mainobj = PyImport_ExecCodeModule("multiply", codeobj); > > where codeobj is of type (PyObject *). > > Once that works, add magic number checking and exception handling to taste. Thanks. That's exactly what I was looking for. From zapwireDASHgroups at yahoo.com Tue Jul 15 19:28:54 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Tue, 15 Jul 2008 16:28:54 -0700 Subject: One step up from str.split() References: Message-ID: "Sion Arrowsmith" wrote in message news:Tiv*wYYhs at news.chiark.greenend.org.uk... > What's wrong with sys.argv ? Mainly that it doesn't exist. :-) The example was slightly contrived -- I'm really dealing with commands interactively entered within a program in response to raw_input(), although the format of the commands is meant to be consistent with command-line usage. (A real command, for instance, would be something like this: load "my firmware file.bin" .) I ended up using shlex.strip() -- works great! ---Joel From thomas.troeger.ext at siemens.com Thu Jul 17 06:22:20 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Thu, 17 Jul 2008 12:22:20 +0200 Subject: Python embedding question. References: Message-ID: Jan Claeys wrote: > I'd say that PyGame could be a solution. > > Or otherwise you could do your own audio/graphics programming (you don't > tell us which OS you use, but there exist python modules that allow you > to do barebones graphics & sound programming on linux...). Yes, I'm using a very small Linux system with busybox, running from a compact flash drive. I'll investigate PyGame, it sounds as if it is a good candidate :P Thanks so far, Thomas. From circularfunc at yahoo.se Thu Jul 3 11:02:59 2008 From: circularfunc at yahoo.se (defn noob) Date: Thu, 3 Jul 2008 08:02:59 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: <938b7b06-33db-4f0d-89cc-4ce52c9cf0b3@25g2000hsx.googlegroups.com> Message-ID: <3531f0b9-7c83-4e8b-bd67-adbce5c85518@k37g2000hsf.googlegroups.com> On Jul 3, 5:02?pm, Chris wrote: > On Jul 3, 4:11?pm, defn noob wrote: > > > i unzipped and put the folder in site-packages. when i run setup.py > > install nothing happens. > > > when i do import pp from shell it complains it doesnt exist. > > > isnt placing the folder in site-packages enough? > > > these setup.py-files often dont work but normally it still works. > > "python setup.py install" windows...i run setup.py install From denis.kasak2718281828 at gmail.com Fri Jul 11 18:34:42 2008 From: denis.kasak2718281828 at gmail.com (Denis Kasak) Date: Sat, 12 Jul 2008 00:34:42 +0200 Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: On Sat, Jul 12, 2008 at 12:22 AM, kdt wrote: > Hi all, > > Can someone please explain to me why the following evaluates as false? > >>>>list=['a','n','n','a'] >>>>list==list.reverse() >>>>False > > I'm stumped :s Read the documentation on list.reverse(). Basically, it reverses the list in place, so it modifies the list which called it. It does not return a /new/ list which is a reversed version of the original, as you expected it to. Since it doesn't return anything explicitly, Python makes it return None. Hence, the comparison you are doing is between the original list and a None, which is False, naturally. Try this: spam = ['a', 'n', 'n', 'a'] eggs = spam[:] if spam.reverse() == eggs: print "Palindrome" Also, 'list' is a really bad name for a list, since this is the name of the builtin type object for the list type. -- Denis Kasak From ptmcg at austin.rr.com Thu Jul 31 19:15:13 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 31 Jul 2008 16:15:13 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> <7360bd9a-4ff6-4e75-821c-eabc88ee6258@u6g2000prc.googlegroups.com> Message-ID: On Jul 28, 12:15?pm, Kay Schluehr wrote: > On 28 Jul., 06:42, "Russ P." wrote: > > > > > > > On Jul 27, 8:58 pm, castironpi wrote: > > > > On Jul 27, 2:39 pm, Bruno Desthuilliers > > > > wrote: > > > > Derek Martin a ?crit : > > > > > It's bad programming, but the world is full of bad programmers, and we > > > > > don't always have the choice not to use their code. ?Isn't one of > > > > > Python's goals to minimize opportunities for bad programming? > > > > > Nope. That's Java's goal. Python's goals are to maximize opportunities > > > > for good programming, which is quite different. > > > Oh, gosh, that is so clever. What a bunch of crap. > > > > +1 QOTW > > > Do you realize what an insult that is to everyone else who has posted > > here in the past week? > > Nothing glues a community together so well as a common enemy. Or even > better: two enemies i.e. Perl and Java in Pythons case. On the other > hand, some enemies have to be ignored or declared to be not an enemy > ( Ruby ), although oneself is clearly an enemy for them. The same > antisymmetry holds for Python and Java. Java is an enemy for Python > but Python is not worth for Java to be an enemy as long as it can be > ignored. C++ and Java are enemies for each other. Same holds for Java > and C#.- Hide quoted text - > > - Show quoted text - Help... being... sucked into... black hole... inside a... Klein... bottle... From dbpokorny at gmail.com Tue Jul 1 17:50:40 2008 From: dbpokorny at gmail.com (dbpokorny at gmail.com) Date: Tue, 1 Jul 2008 14:50:40 -0700 (PDT) Subject: How to make a function associated with a class? References: <69e26f9b-2f00-4318-9bc5-6aa94e141bca@59g2000hsb.googlegroups.com> Message-ID: On Jul 1, 1:43 pm, Kurda Yon wrote: > Hi, > > I have a class called "vector". And I would like to define a function > "dot" which would return a dot product of any two "vectors". I want > to call this function as follow: dot(x,y). > > Well, I can define a functions "dot" outside the class and it works > exactly as I want. However, the problem is that this function is not > associated with the class (like methods a method of the class). > > For example, if I call "x.calc()" or "y.calc()", python will execute > different methods if "x" and "y" belongs to different classes. I want > to have the same with my "dot" function. I.e. I want it calculates the > dot product ONLY IF the both arguments of that function belong to the > "vector" class. > > Is it possible? > > Thank you in advance. It sounds like you are talking about data-directed programming (see http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-17.html#%_sec_2.4.3). Basically you have two options: def dot(x,y): if isinstance(x,Vector) and isintance(y,Vector): ... raise TypeError("...") which quickly breaks down in a mess of if-then clauses when you want to expand the dot function to handle other datatypes, or you create a table and populate it with entries like this dispatch_table[('dot','Vector','Vector')] = Vector.dot # this has to be declared @staticmethod in class Vector dispatch_table[('dot','str','str')] = operator.add # borrowed from PHP dispatch_table[('mul',Matrix,Matrix)] = Matrix.mul You now have to write something like this (this isn't even valid Python code, but hopefully you get the idea) def generic_function(name): def exec_generic_function(*args): f = dispatch_table.get((name, *(type(arg).__name__ for arg in args)),None) if f == None: raise TypeError('...') return f(*args) return exec_generic_function dot = generic_function('dot') # NB: (a, *b) means (a,) + b until the generalized *-unpacking syntax is accepted This is essentially a translation into Python of the content of the link. Neither of these options are great (and the latter is marginal at best) if you care about performance (but maybe it will all become C anyway so you don't care). If you want to do it the Python way, use __mul__. Cheers, David From sjmachin at lexicon.net Thu Jul 31 04:43:58 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 31 Jul 2008 01:43:58 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Message-ID: On Jul 31, 12:58?am, william tanksley wrote: > Thank you for the response. Here's some more info, including a little > that you didn't ask me for but which might be useful. > > John Machin wrote: > > william tanksley wrote: > > > To ask another way: how do I convert from a file:// URL to a local > > > path in a standard way, so that filepaths from two different sources > > > will work the same way in a dictionary? > > > The problems occur when the filenames have non-ascii characters in > > > them -- I suspect that the URLs are having some encoding placed on > > > them that Python's decoder doesn't know about. > > # track_id = url2pathname(urlparse(track_id).path) > > print repr(track_id) > > parse_result = urlparse(track_id).path > > print repr(parse_result) > > track_id_replacement = url2pathname(parse_result) > > print repr(track_id_replacement) > > The "important" value here is track_id_replacement; it contains the > data that's throwing me. It appears that some UTF-8 characters are > being read as multiple bytes by ElementTree rather than being decoded > into Unicode. Appearances can be deceptive. You present no evidence. > Could this be a bug in ElementTree's Unicode support? It could, yes, but the probability is extremely low. > If > so, can I work around it? > > Here's one example. The others are similar -- they have the same > things that look like problems to me. > > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" > > Note some problems here: Where? > > 1. This isn't Unicode; it's missing the u"" (I printed using repr). > 2. It's got the UTF-8 bytes there in the middle. > > I tried doing track_id.encode("utf-8"), but it doesn't seem to make > any difference at all. > > Of course, my ultimate goal is to compare the track_id to the track_id > I get from iTunes' COM interface, including hashing to the same value > for dict lookups. > > > and copy/paste the results into your next posting. > > In addition to the above results, *WHAT* results? I don't see any repr() output, just your interpretation of what you think you saw! From max at alcyone.com Wed Jul 30 23:03:03 2008 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Jul 2008 20:03:03 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> Message-ID: Russ P. wrote: > The reason I wrote that "it would be nice to be able to write" > > if x is not empty: > > is that it reads naturally. It was not an actual proposal, and the > fact that you took it as such was *your* mistake. ... > Now read carefully: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! Let > me repeat that for you: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! > Did you get that, idiot? So people who can read words but not minds are idiots. Go get 'em, tiger! -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis If you turned right / You turned left / Or if you just walked out ahead -- Anggun From jmcmonagle at velseis.com.au Tue Jul 22 02:05:46 2008 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Tue, 22 Jul 2008 16:05:46 +1000 Subject: string[i:j:k] In-Reply-To: <811e72db-a8bc-475a-b32a-38a9b6922600@k30g2000hse.googlegroups.com> References: <4a9a4cf3-9ef4-4d9e-b714-bbf62b7c1917@v1g2000pra.googlegroups.com> <811e72db-a8bc-475a-b32a-38a9b6922600@k30g2000hse.googlegroups.com> Message-ID: <488578BA.5050703@velseis.com.au> konstantin wrote: > > Thanks! > It seems that negative step leads in reverse direction. > But logic isn't completely clear for me. >>>> s = '123456789' >>>> s[::-2] > '97531' > > but >>>> s[:-1:-2] > '' > though I expected something like '8642' > What did i missed? > > -- You need to *start* at the second from last index: s[-2::-2] Regards, John From cwitts at gmail.com Thu Jul 3 11:02:00 2008 From: cwitts at gmail.com (Chris) Date: Thu, 3 Jul 2008 08:02:00 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: Message-ID: <938b7b06-33db-4f0d-89cc-4ce52c9cf0b3@25g2000hsx.googlegroups.com> On Jul 3, 4:11?pm, defn noob wrote: > i unzipped and put the folder in site-packages. when i run setup.py > install nothing happens. > > when i do import pp from shell it complains it doesnt exist. > > isnt placing the folder in site-packages enough? > > these setup.py-files often dont work but normally it still works. "python setup.py install" From dullrich at sprynet.com Tue Jul 1 13:25:35 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 01 Jul 2008 12:25:35 -0500 Subject: ask for a RE pattern to match TABLE in html References: <6a4f17690806260653i136681bdsabe0f6bb1dfab67b@mail.gmail.com> <62f752f3-d840-42de-a414-0d56d15d7c5a@w4g2000prd.googlegroups.com> <87bb8346-6498-4e51-b065-88d915dcff0d@p39g2000prm.googlegroups.com> Message-ID: In article <87bb8346-6498-4e51-b065-88d915dcff0d at p39g2000prm.googlegroups.com>, Jonathan Gardner wrote: > On Jun 27, 10:32?am, "David C. Ullrich" wrote: > > (ii) The regexes in languages like Python and Perl include > > features that are not part of the formal CS notion of > > "regular expression". Do they include something that > > does allow parsing nested delimiters properly? > > > > In perl, there are some pretty wild extensions to the regex syntax, > features that make it much more than a regular expression engine. > > Yes, it is possible to match parentheses and other nested structures > (such as HTML), and the regex to do so isn't incredibly difficult. > Note that Python doesn't support this extension. Huh. My evidently misinformed impression was that the regexes in P and P were essentially equivalent. (I hope nobody takes that as a complaint...) > See http://www.perl.com/pub/a/2003/08/21/perlcookbook.html -- David C. Ullrich From Nikolaus at rath.org Tue Jul 29 13:26:09 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Tue, 29 Jul 2008 19:26:09 +0200 Subject: [unittest] Run setUp only once References: Message-ID: <871w1cr49a.fsf@nokile.rath.org> Jean-Paul Calderone writes: > On Tue, 29 Jul 2008 16:35:55 +0200, Nikolaus Rath wrote: >>Hello, >> >>I have a number of conceptually separate tests that nevertheless need >>a common, complicated and expensive setup. >> >>Unfortunately, unittest runs the setUp method once for each defined >>test, even if they're part of the same class as in >> >>class TwoTests(unittest.TestCase): >> def setUp(self): >> # do something very time consuming >> >> def testOneThing(self): >> >> >> def testADifferentThing(self): >> >> >>which would call setUp twice. >> >> >>Is there any way to avoid this, without packing all the unrelated >>tests into one big function? >> > > class TwoTests(unittest.TestCase): > setUpResult = None > > def setUp(self): > if self.setUpResult is None: > self.setUpResult = computeIt() > > ... > > There are plenty of variations on this pattern. But at least this variation doesn't work, because unittest apparently also creates two separate TwoTests instances for the two tests. Isn't there some way to convince unittest to reuse the same instance instead of trying to solve the problem in the test code itself? Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From iainking at gmail.com Wed Jul 2 10:11:51 2008 From: iainking at gmail.com (Iain King) Date: Wed, 2 Jul 2008 07:11:51 -0700 (PDT) Subject: Win32.client, DAO.DBEngine and exceeding the file sharing count lock Message-ID: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> Hi. I'm using the win32 module to access an Access database, but I'm running into the File Sharing lock count as in http://support.microsoft.com/kb/815281 The solution I'd like to use is the one where you can temporarily override the setting using (if we were in VB): DAO.DBEngine.SetOption dbmaxlocksperfile,15000 Can I do this in win32com? I've been using ADO, not DAO, but I have to confess to not knowing exactly what the difference is. I set up my recordset thusly: rs = win32com.client.Dispatch(r'ADODB.Recordset') can I jigger it to increase it's max locks? Iain From prasanths89 at gmail.com Mon Jul 21 21:50:58 2008 From: prasanths89 at gmail.com (Prasanth) Date: Mon, 21 Jul 2008 18:50:58 -0700 (PDT) Subject: Pinging a machine from python References: <0abad6b7-87bc-42d2-88ee-1f2ed40aa07f@w1g2000prd.googlegroups.com> Message-ID: <85a9e54a-e12a-446c-972f-d4e9c398d5ce@p25g2000pri.googlegroups.com> On May 26, 5:21?am, Zerge wrote: > On May 25, 11:13 am, Prasanth wrote: > > > I tried pinging a machine from python using socket programming but > > could not do it. Is there any module which we can use to ping the > > machine < like net::ping in perl> or can you give me simple program. > > Import OS > ip=192.168.1.1 > pingtext="ping "+ip+" -n 1" > pingresult=os.popen(pingtext).readlines() > > "OS" gives you access to the command line of the operating system. Thanks for the solution guys. But the above program is giving the output as : If we print pingresult it is giving the output as : ['\r\n', 'Pinging 0.168.1.1 with 32 bytes of data:\r\n', '\r\n', 'Request timed out.\r\n', '\r\n', 'Ping statistics for 0.168.1.1:\r \n', ' Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),\r\n'] my requirement is IP address and whether the machine is pinging or not. we should not display the above output. However we can do it by using regular expression or there is any other way. Please suggest. Thanks, Prasanth. From castironpi at gmail.com Sun Jul 27 00:59:08 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 26 Jul 2008 21:59:08 -0700 (PDT) Subject: persistent deque (continued) References: <4c985e86-c0c4-4cb3-b7ce-f8e105b7f85d@y21g2000hsf.googlegroups.com> <4126ceeb-128e-4aa1-af95-31648d42eade@i24g2000prf.googlegroups.com> Message-ID: <90422c5b-0688-408d-a342-411bf5c86a9f@34g2000hsh.googlegroups.com> On Jul 21, 5:20?pm, Raymond Hettinger wrote: > On Jul 21, 12:08?pm, castironpi wrote: > > > Some time ago, I was asking about the feasibility of a persistent > > deque, a double-ended queue. > > > It runs into the typical space allocation problems. ? > > Try starting with a dict-based implementation of a double-ended queue > (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259179) > and then replace the dict with a shelf. ?Presto, you've got a > persistent deque. > > Raymond We have the cookbook recipe Raymond brings up, and an automatic pickler that inhahe brought up in May. I've initiated the approach to the solution I have in mind, but the dilemma comes early and isn't pleasant. I can either (i) recompile the whole interpreter, replacing malloc with a custom function that allocates from disk; or (ii) duplicate every class I want to be persistable, making every change to the allocations by hand. Disk-resident objects can clearly not contain references to any objects not on disk (arguably at finalization-stage only), and references to ones that are need to be wrapped by offset, and 'made live' at initialization-time, so that references to the mapped file resume succeeding after termination and restart--- the mapped memory segment won't be the same from run to run. Further, if I can't hijack the existing arena-pool model native in Python, it would take writing a dedicated memory manager. Assuming the whole memory isn't moved to disk, which is feasible, the usage would look like this, to ensure that 'disk-resident' objects don't refer to 'live' ones. listA= perst( [ perst( 0 ), perst( 1 ), perst( "abc" ) ] ) to create the list [ 0, 1, "abc" ]. Modifications, e.g. append "def", would look like this: listA.append( perst( "def" ) ) and would execute the addition directly to mapped memory. The memory file would then have five objects: 0, 1, "abc", "def", and this list. It is not clear that normal assignments would still work, self.b= c, even for disk-resident c, since on a later run, 'self.b' would refer to a different place in memory. It might take either trapping updates to self.__dict__, or something deeper at the level of the ast and Assm't statements. Or an extra level of indirection in accessing it. >>> self.b The indirection would consist of an offset-finder and a delegation layer. >>> self.b.append( perst( set( ) ) ) It would first have to look-up 'self.b', as opposed to accessing it directly by memory address. What I want from the group is to know if I've assessed the options for a model of persistence accurately. Or if I haven't depicted what I'm going for clearly. It seems enormous and if it is this hard, I doubt I'll produce anything other than a few correct persistent types. From Russ.Paielli at gmail.com Thu Jul 17 01:20:12 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 16 Jul 2008 22:20:12 -0700 (PDT) Subject: Best Python packages? References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> Message-ID: <0e63942e-e84f-45c3-9e78-1c67860d760b@p25g2000hsf.googlegroups.com> On Jul 16, 7:16 am, Ben Sizer wrote: > Although the standard library in Python is great, there are > undoubtedly some great packages available from 3rd parties, and I've > encountered a few almost by accident. However, I don't know how a user > would become aware of many of these.http://pypi.python.org/pypi/ > presumably lists most of the decent ones, but there's a lot there and > little indication as to quality or popularity - great if you know > exactly what you need, but not so great for just browsing. I'd love to > have some way of finding out what hidden gems are out there in the > Python world which could make my development a lot easier. Any > suggestions? > > -- > Ben Sizer One good place to look is The Python Papers, "a free e-journal, including industry and academic articles" at http://pythonpapers.org/ The current issue (vol. 3, issue 1) has an article that I wrote called, "An Efficient Scalar Package in Python." If you do engineering or scientific computing with Python, and you wish to avoid unit errors without slowing down your production runs, then I suggest take a look at this package. You can download it and its user's guide at http://RussP.us/scalar.htm . From karthikbalaguru79 at gmail.com Thu Jul 24 00:58:51 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Wed, 23 Jul 2008 21:58:51 -0700 (PDT) Subject: tkinter for my python program !! References: <6em5snF7r22oU3@mid.uni-berlin.de> <63ff0b6f-8c75-4172-b836-8497870544ca@s50g2000hsb.googlegroups.com> <6em86gF7q9djU1@mid.uni-berlin.de> <81554f58-cc9c-4649-afdd-45656ab0bf64@b2g2000prf.googlegroups.com> Message-ID: On Jul 23, 11:38 pm, David wrote: > > Further, finally when i invoke the python program by > > giving the necessary input file, i get the following > > errors . > > Does it have any relation with the python version installed ? > > yes > > > I am using Redhat 9.0 > > You may want to install a current Linux distro. I got the info from this usenet group. Thx for that info. The problem got resolved after including 'from __future__ import generators' in the beginning of the file. Karthik Balaguru From mail at timgolden.me.uk Wed Jul 2 10:29:28 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 02 Jul 2008 15:29:28 +0100 Subject: Win32.client, DAO.DBEngine and exceeding the file sharing count lock In-Reply-To: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> References: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> Message-ID: <486B90C8.6030801@timgolden.me.uk> Iain King wrote: > Hi. I'm using the win32 module to access an Access database, but I'm > running into the File Sharing lock count as in http://support.microsoft.com/kb/815281 > The solution I'd like to use is the one where you can temporarily > override the setting using (if we were in VB): > > DAO.DBEngine.SetOption dbmaxlocksperfile,15000 Really hurried answer: import win32com.client dao = win32com.client.gencache.EnsureDispatch ("DAO.DBEngine.36") dao.SetOption (Option=win32com.client.constants.dbMaxLocksPerFile, Value=15000) TJG From fredrik at pythonware.com Wed Jul 23 16:04:24 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 22:04:24 +0200 Subject: lxml, comparing nodes In-Reply-To: References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> Message-ID: code_berzerker wrote: >> Your requirements for a single Element are simple enough to write it in three >> to five lines of Python code (depending on your definition of equality). >> Checking this equality recursively is another two to three lines. Not complex >> enough to be considered a wheel in the first place. > > Forgive my ignorance as I am new to both Python and lxml ;) off the top of my head (untested): >>> def equal(a, b): ... if a.tag != b.tag or a.attrib != b.attrib: ... return False ... if a.text != b.text or a.tail != b.tail: ... return False ... if len(a) != len(b): ... return False ... if any(not equal(a, b) for a, b in zip(a, b)): ... return False ... return True this should work for arbitrary ET implementations (lxmk, xml.etree, ET, etc). tweak as necessary. From alexnbryan at gmail.com Thu Jul 3 16:58:26 2008 From: alexnbryan at gmail.com (Alexnb) Date: Thu, 3 Jul 2008 13:58:26 -0700 (PDT) Subject: Testing for an empty list Message-ID: <18268092.post@talk.nabble.com> Okay this is a simple question I just don't know how. If I have a list, say: funList = [] and after a while something possible should have been appended to it, but wasn't. How can I test if that list is empty. -- View this message in context: http://www.nabble.com/Testing-for-an-empty-list-tp18268092p18268092.html Sent from the Python - python-list mailing list archive at Nabble.com. From john.goodleaf at gmail.com Thu Jul 31 19:23:49 2008 From: john.goodleaf at gmail.com (john.goodleaf) Date: Thu, 31 Jul 2008 16:23:49 -0700 (PDT) Subject: Problem with pyodbc, Python? Message-ID: I've just built pyodbc 2.0.58 against freetds and unixodbc. When I attempt to invoke it, either from the test script or from the interpreter, I get: ImportError: build/lib.linux-x86_64-2.5/pyodbc.so: undefined symbol: PyUnicodeUCS2_Resize I'm not quite sure how to go about troubleshooting this. More info: Build is on opensuse 11.0, intel x86_64 from Python 2.5.2. I've also tried a custom built (i.e. not the SuSE package) Python with the same result. Yes, I have the Python-dev package installed. I had this working on this very machine when I was running Mandriva but I recently, overly whimsically, decided to try opensuse. Near as I can figure, something about how Python or supporting libraries are built is different between the two distros but I'm not sure how to go about fixing things. Any thoughts? J From kinokunya at gmail.com Mon Jul 14 02:22:20 2008 From: kinokunya at gmail.com (Kinokunya) Date: Sun, 13 Jul 2008 23:22:20 -0700 (PDT) Subject: Need help in writing up a Python Syntax checker Message-ID: Hi guys, My group and I will be working on our final year project, the scope to do a program/web-based application similar areas of functionalities like the PyLint and PyChecker; a Python syntax checker. We have no Python background, equipped only with some knowledge of Java and Dot net. We did some research on PyLint and found out that there are 2 common modules that PyLint & PyChecker are using, namely logilab-astng and logilab-common. I'm not really sure what these 2 modules are for. Quoted from the offical site, The aim of this module (logilab-astng) is to provide a common base representation of python source code We're not really sure what they meant by common base representation of source codes. Does that mean logilab-astng is somewhat like a repository/library of Python syntax API so that we can easily 'call' these module to aid in syntax checking? My group and I were considering of using Java as a basis for this project, but if these 2 modules were really the repositories for Python syntax codes then we are restricted to using Python to make full use of the above mentioned dependencies. Our current stand was to use Jython as it is able to support Java as well as the .PY files inside logilab-astng and logilab-common, but having no knowledge in Python, we're unable to make out whatever was in the 2 above modules, was was unable to find user support forums/ communities for Logilab related stuff. You insights are greatly appreciated. Windows platform (XP & vista) Python (If need be, we will install the latest official version of it) Jython 2.2.1 (Latest version) Server: Apache Tomcat 2.2 (Should we require one for the project) From iainking at gmail.com Fri Jul 25 10:07:34 2008 From: iainking at gmail.com (Iain King) Date: Fri, 25 Jul 2008 07:07:34 -0700 (PDT) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> Message-ID: <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> On Jul 25, 1:46 pm, Iain King wrote: > On Jul 25, 10:57 am, Suresh Pillai wrote: > > > > > I am performing simulations on networks (graphs). I have a question on > > speed of execution (assuming very ample memory for now). I simplify the > > details of my simulation below, as the question I ask applies more > > generally than my specific case. I would greatly appreciate general > > feedback in terms of computing and of course considerations specific to > > implementation in Python. > > > The nodes in my network may be ON or OFF. The network starts off with > > all nodes in the OFF state. I loop through the nodes. For each node > > that is OFF, I consider some probability of it turning ON based on the > > states of its neighbours. I MUST GO THROUGH ALL NODES BEFORE DECIDING > > WHICH ONES TO TURN ON. > > > So my question is whether it is faster to > > > 1. loop through a list of ALL nodes and check for OFF nodes using ifs > > > or to > > > 2. loop through a container of OFF nodes and remove from this when they > > turn ON > > or 3. build a new list every iteration intead of deleting from the old > one: > > while processing: > new_off_list = [] > for x in off_list: > if goes_on(x): > on_list.append(x) > else: > new_off_list.append(x) > off_list = new_off_list > generation += 1 > > Iain I was curious to what extent the different methods varied in time, so I checked it out. Here there are three procedures: test_every which matches your (1), destructive which matches your (2), and constructive which is (3) as I've outlined above. On varying the size of the dataset I get this (probability a node goes on = 50%): Length of initial list: 100000 Test every: 1.16085492357 Destructive: 2.592310272 Constructive: 0.850312458886 Length of initial list: 200000 Test every: 2.48013843287 Destructive: 9.20894689718 Constructive: 1.73562198439 Length of initial list: 400000 Test every: 5.00652267447 Destructive: 44.9696004134 Constructive: 3.51687329373 Length of initial list: 800000 Test every: 9.67657648655 Destructive: 220.57583941 Constructive: 7.06614485537 and changing the probability that a nodes goes on (dataset size = 200000): Probability goes on: 1/2 Test every: 2.24765364513 Destructive: 9.28801971614 Constructive: 1.62770773816 Probability goes on: 1/4 Test every: 4.77387350904 Destructive: 13.4432467571 Constructive: 3.45467140006 Probability goes on: 1/8 Test every: 11.0514899721 Destructive: 18.4026878278 Constructive: 6.86778036177 Probability goes on: 1/16 Test every: 22.5896021593 Destructive: 25.7784044083 Constructive: 13.8631404605 Probability goes on: 1/32 Test every: 49.7667941179 Destructive: 39.3652502735 Constructive: 27.2527219598 Probability goes on: 1/64 Test every: 91.0523955153 Destructive: 65.7747103963 Constructive: 54.4087322936 Code: import random from timeit import Timer SIZE = 100000 MAX = 2 def goes_on(x): global MAX return random.randint(1,MAX) == 1 def test_every(): global SIZE print "Test every:", nodes = range(SIZE) is_on = [False for x in xrange(SIZE)] count = SIZE while count: for i,x in enumerate(nodes): if not is_on[i] and goes_on(x): is_on[i] = True count -= 1 def destructive(): global SIZE print "Destructive:", off_list = range(SIZE) on_list = [] count = SIZE while count: for i in xrange(len(off_list)-1, -1, -1): x = off_list[i] if goes_on(x): on_list.append(x) del(off_list[i]) count -= 1 def constructive(): global SIZE print "Constructive:", off_list = range(SIZE) on_list = [] count = SIZE while count: new_off_list = [] for x in off_list: if goes_on(x): on_list.append(x) count -= 1 else: new_off_list.append(x) off_list = new_off_list #SIZE = 200000 while True: print "Length of initial list:", SIZE #print "Probability goes on: 1/%d" % MAX print Timer("test_every()", "from __main__ import test_every").timeit(1) print Timer("destructive()", "from __main__ import destructive").timeit(1) print Timer("constructive()", "from __main__ import constructive").timeit(1) print SIZE *= 2 #MAX *= 2 Conclusions: On size, (2) really doesn't like bigger datasets, taking exponentially longer as it increases, while (1) and (3) happily increase linearly. (3) is faster. On probability it's (1) who's the loser, while (2) and (3) are happy. (3) is once again faster. I think (2)'s poor performance is being amplified by how python handles lists and list deletions; the effect may be stymied in other languages, or by using other data constructs in python (like a dictionary or a user made list class). If you were short on memory then (2) would have an advantage, but as it is, (3) is the clear winner. I'm a fan of list comprehensions, and it feels like they could be nice here, but since we are making two lists at once here I don't see how to... anyone see how to use them (or 'map' if you want to be old school)? Iain From tjreedy at udel.edu Tue Jul 22 14:20:20 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2008 14:20:20 -0400 Subject: CPython VM internals - Wiki page Message-ID: Various people have asked on c.l.p about documentation of CPython's virtual machine internals. The usual answers have been to see the dis module doc for bytecodes and 'read the code' for more. Jakob Sievers did so and posted his notes, with additions from Martin v. L?wis, as http://wiki.python.org/moin/CPythonVmInternals From cokofreedom at gmail.com Mon Jul 7 06:00:13 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 7 Jul 2008 03:00:13 -0700 (PDT) Subject: yo... References: Message-ID: <1a767250-c2e6-4a07-8650-84b79bf628af@26g2000hsk.googlegroups.com> On Jul 7, 11:55 am, "A.T.Hofkamp" wrote: > On 2008-07-07, abhishek wrote: > > > hey guys...me nu 2 python yo...help me...by da way...jus joined > > in....thanks > > Ask a specific question and you may get an answer. > > If you want an answer from me, it helps *a lot* if you write full english > sentences (starting with a capital letter and ending with a single '.') rather > than the short-hand you seem to favor. (It costs me a lot of effort to > decipher). > > Sincerely, > Albert Considering I speak English as a first language, it is still rather difficult to understand you. However welcome to Python and this Google Group. If you have questions in the future, feel free to ask them. Though you might want to use less Text-style lingo as many of the users here are not first-language English speakers. From tommy.nordgren at comhem.se Wed Jul 23 09:25:52 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Wed, 23 Jul 2008 15:25:52 +0200 Subject: fromfile error on windows, not mac In-Reply-To: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> Message-ID: <611B728A-16C6-4033-B4E3-1AC4183A28F0@comhem.se> One question : Did you remember to open the file in binary mode? This MUST be done on windows. On 22 jul 2008, at 06.36, jadamwil wrote: > Hello, > I am using the numpy fromfile function to read binary data from a file > on disk. The problem is that the program runs fine on a Mac, but gives > an error or warning on windows when trying to read the data. I use it > like this: > > Signal = zeros((N, 16), dtype=float32) > for sample in range(0, N): > # this function gets the next position in the file to seek to > s = getFilePos(sample) > > # go to the correct location in the file; this IS checked to make > sure it is within the file > mFile.seek(s) > > # read the 16 float32 values from the file > D = fromfile(mFile, dtype=numpy.float32, 16) > > # save D in Signal > Signal[sample, :] = D > > This will fail when sample is ~4. If I change the range to (5,N), > skipping the "bad" file location, it will run fine for a few samples, > and then give another error. The message it gives is: > "16 items requested but only 7 read" > > So D is a 7x1 vector, and the program dies when it tries to assign D > to the slice of Signal ("ValueError: shape mismatch: objects cannot be > broadcast to a single shape"). > > On windows, the Python version is 2.5.2, and the most recent numpy and > scipy are being used as well. I tried using Enthought, but it gave > this error as well, in addition to a c runtime error whenever I > imported scipy (which is another post topic...). > > Any ideas on what might be causing this? Is there a way to debug the > fromfile function? And, remember, this works perfectly on a Mac. Would > compiling everything (python, scipy, numpy) potentially solve this? > > Thanks! > -- > http://mail.python.org/mailman/listinfo/python-list ---------------------------------- Skinheads are so tired of immigration, that they are going to move to a country that don't accept immigrants! Tommy Nordgren tommy.nordgren at comhem.se From gcmartijn at gmail.com Sun Jul 6 06:06:06 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Sun, 6 Jul 2008 03:06:06 -0700 (PDT) Subject: pythoncom InternetExplorer.Application don't work in vista || firefox pythoncom ? References: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> Message-ID: On 5 jul, 15:27, Terry Reedy wrote: > gcmart... at gmail.com wrote: > > H! > > > I using a script that opens a internet page in a small window (what I > > can control) > > In XP everything was working fine, but now I'm using Vista with IE7 > > and this is what happends now: > > > First a small window opens at the postion x0 y0 (like I want) but then > > IE thinks "Hey lets open a other main window too". > > And that window opens the url 'http://www.google.nl' > > Perhaps on XP you changed the IE homepage to about:blank. ?On your Vista > machine, it is set to Google, perhaps by the manufacturer (for a fee). > Try changing it. Nope when its about:blank I get that google page (because I say that in the script) From rridge at csclub.uwaterloo.ca Fri Jul 11 18:23:55 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Fri, 11 Jul 2008 18:23:55 -0400 Subject: Loading just in time References: Message-ID: D'Arcy J.M. Cain wrote: >def calc_tax(*arg, **name): > from calc_tax import calc_tax as _func_ > calc_tax = _func_ > return _func_(*arg, **name) This should do what you want: def calc_tax(*arg, **name): global calc_tax from calc_tax import calc_tax return calc_tax(*arg, **name) I suspect though that the cost of importing a lot of little modules won't be as bad as you might think. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From wuwei23 at gmail.com Mon Jul 28 23:44:04 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 28 Jul 2008 20:44:04 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> Message-ID: <466157f1-adcb-45f6-8c2d-b3c245a6ce8d@p31g2000prf.googlegroups.com> On Jul 29, 4:46?am, "Russ P." wrote: > As I said, I could write a pre-processor myself to > implement it in less than a day. So WHY DON'T YOU WRITE IT ALREADY? If you're meeting so much resistance to your idea, why not scratch your own damn itch and just do it? Or doesn't that afford you as many chances to insult others while feeling smugly superior? From marcus at internetnowasp.net Sat Jul 12 22:11:43 2008 From: marcus at internetnowasp.net (Marcus Low) Date: Sun, 13 Jul 2008 10:11:43 +0800 Subject: Someone enlightened me Message-ID: <4879645F.3070504@internetnowasp.net> Opps here is the mail again, incase my formatting is lost, can someone explain to me why this code behaves differently when "lister" and "self.lister" is swap remarked. class abc : # remark this later and unremark "self.lister" lister = [] def __init__ (self, val): #self.lister = [] self.lister.append(val) globallist = [] def test () : global l for x in range(10) : o = abc(x) globallist.append(o) o = "" for i in globallist : print i.lister test() From ptmcg at austin.rr.com Wed Jul 9 10:37:54 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 9 Jul 2008 07:37:54 -0700 (PDT) Subject: Returning the positions of a list that are non-zero References: <80efdd10-b8c8-4a17-9e41-f00cf59f23d2@l64g2000hse.googlegroups.com> Message-ID: <3aaf581d-eec7-4b20-a75c-f5ff6829e10a@2g2000hsn.googlegroups.com> On Jul 9, 12:26?am, Benjamin Goudey wrote: > I have a very large list of integers representing data needed for a > histogram that I'm going to plot using pylab. However, most of these > values (85%-95%) are zero and I would like to remove them to reduce > the amount of memory I'm using and save time when it comes to plotting > the data. To do this, I'm trying to find the best way to remove all of > the zero values and produce a list of indices of where the non-zero > values used to be. > > For example, if my original list is [0,0,1,2,1,0,0] I would like to > produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices > of where the non-zero values used to be). Removing non-zero values is > very easy but determining the indicies is where I'm having difficulty. > >>> sparse_data = [0, 0, 1, 2, 1, 0, 0] >>> values,locns = zip(*[ (x,i) for i,x in enumerate(sparse_data) if x ]) >>> print values (1, 2, 1) >>> print locns (2, 3, 4) >>> -- Paul From gherron at islandtraining.com Mon Jul 28 13:46:18 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 28 Jul 2008 10:46:18 -0700 Subject: python lists and newline character In-Reply-To: <053101c8f0d7$ebd7c340$a601a8c0@office.ipglobal.net> References: <053101c8f0d7$ebd7c340$a601a8c0@office.ipglobal.net> Message-ID: <488E05EA.80800@islandtraining.com> Support Desk wrote: > > Hello all, > > I am using os.popen to get a list returned of vpopmail > users, something like this > > > > x = os.popen('/home/vpopmail/bin/vuserinfo -n -D mydomain.com).readlines() > > > > x returns a list, of usernames, and I am trying to append the > usernames with the domain like so > > > > for line in x: > > print line + ?@? + domain > > > > but instead of getting > > > > user at domain.com > > > > im getting a newline character like: > > user > > @domain.com > > User > > @comain.com > > User2 > > @domain.com > > > > > > Is there some way I can get this list without the newline characters > being added. or somehow remove the newline characters. Any help would > be appreciated. > The problem has nothing to do with lists. The readlines() function returns each line *with* its newline. To strip it off, use line.strip() Gary Herron > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From doug.farrell at gmail.com Wed Jul 9 14:48:59 2008 From: doug.farrell at gmail.com (writeson) Date: Wed, 9 Jul 2008 11:48:59 -0700 (PDT) Subject: Determining when a file has finished copying References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> Message-ID: Guys, Thanks for your replies, they are helpful. I should have included in my initial question that I don't have as much control over the program that writes (pgm-W) as I'd like. Otherwise, the write to a different filename and then rename solution would work great. There's no way to tell from the os.stat() methods to tell when the file is finished being copied? I ran some test programs, one of which continously copies big files from one directory to another, and another that continously does a glob.glob("*.pdf") on those files and looks at the st_atime and st_mtime parts of the return value of os.stat(filename). >From that experiment it looks like st_atime and st_mtime equal each other until the file has finished being copied. Nothing in the documentation about st_atime or st_mtime leads me to think this is true, it's just my observations about the two test programs I've described. Any thoughts? Thanks! Doug From notontheweb at noisp.com Sat Jul 26 19:17:15 2008 From: notontheweb at noisp.com (Jive Dadson) Date: Sat, 26 Jul 2008 23:17:15 GMT Subject: urllib and login with passwords In-Reply-To: References: Message-ID: <%fOik.344229$tY4.283186@fe06.news.easynews.com> Thanks, Rob! Some of that is beyond my maturity level, but I'll try to figure it out. If anyone has specific info on about how YouTube does it, I would appreciate the info. From martin at v.loewis.de Wed Jul 23 12:24:28 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 23 Jul 2008 18:24:28 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: References: Message-ID: <48875B3C.2030900@v.loewis.de> > 1>application.obj : error LNK2031: unable to generate p/invoke for > "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@$$J0YMXH at Z); > calling convention missing in metadata The main problem here is the __clrcall hint: apparently, you are using Managed C++ resp. C++/CLI, i.e. the Microsoft .NET Framework for C++. Don't do that. Instead, make sure that your project targets native Intel x86 code; then compile your code either as C or C++ (your choice). To integrate Python into managed C++ would require a lot of experience, and it may well not be possible. Regards, Martin From 4vinoth at gmail.com Wed Jul 30 10:17:43 2008 From: 4vinoth at gmail.com (:-)) Date: Wed, 30 Jul 2008 07:17:43 -0700 (PDT) Subject: New CMS in Python Message-ID: HI I am Glad to announce you that I am creating New CMS for Python. I'll post it after Python 3 release. Currently I only the Developer/Team Lead/Project Lead/Organization :) It would be Very lightweight Fast Easy to Use Ajax Enabled new?? Done. Please send me how U expect your new CMS would be? Cheers Vinoth From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 2 05:05:27 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Jul 2008 11:05:27 +0200 Subject: Problem with a for loop and a list In-Reply-To: References: Message-ID: <486b44d2$0$15038$426a74cc@news.free.fr> Alexnb a ?crit : > I am not sure what is going on here. Here is the code that is being run: > > def getWords(self): > self.n=0 > for entry in self.listBuffer: > self.wordList[self.n] = entry.get() > self.n=self.n+1 > print self.wordList def get_words(self): self.word_list = [e.get() for e in self.list_buffer] > This is the "listBuffer" that you see: > > self.listBuffer=[self.e1, self.e2, self.e3, self.e4, > self.e5, self.e6, self.e7, self.e8, > self.e9, self.e10, self.e11, > self.e12, self.e13, self.e14] What a fantastic naming scheme. So easy to read, understand and maintain. Congratulation, you just won the right to read "How to write unmaintainable code": http://mindprod.com/jgloss/unmain.html From steve at REMOVE-THIS-cybersource.com.au Sun Jul 13 02:56:20 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 13 Jul 2008 01:56:20 -0500 Subject: Why is this blowing the stack, thought it was tail-recursive... References: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> Message-ID: On Sat, 12 Jul 2008 19:25:18 -0400, Terry Reedy wrote: > ssecorp wrote: >> def fib(n): >> def fibt(a, b, n): >> if n <= 1: >> return b >> else: >> return fibt(b, a + b, n - 1) >> if n == 0: >> return 0 >> else: >> return fibt(0, 1, n); >> >> and can memoization speed up this even more? tesintg with memoization >> doesnt really say anything because it is so fast it is instant anyway. > > Except for the fact that a+b gets slower as a and b get bigger, this > would already be linear time in n. Memoization (here by means of a > linear list) only helps if the list is preserved and one makes repeated > requests for various fib values. > > I am just curious what input you tried that blew the stack? It had to > be pretty large. No, not really. Try it for yourself: on my system, I get RuntimeError: maximum recursion depth exceeded with fib(999). fib(999) is a large number, with 208 digits, but not that large: 268638100244853593861467272021429239676166093189869523401 231759976179817002478816893383696544833565641918278561614 433563129766736422103503246348504103776803673341511728991 69723197082763985615764450078474174626L -- Steven From paul at boddie.org.uk Tue Jul 29 12:21:04 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 29 Jul 2008 09:21:04 -0700 (PDT) Subject: Build tool for Python References: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Message-ID: On 29 Jul, 17:08, Hussein B wrote: > Apache Ant is the de facto building tool for Java (whether JSE, JEE > and JME) application. > With Ant you can do what ever you want: compile, generate docs, > generate code, packing, deploy, connecting to remote servers and every > thing. > Do we have such a tool for Python projects? There are quite a few similar tools here: http://wiki.python.org/moin/ConfigurationAndBuildTools Having looked at a few such tools recently, I found myself considering using plain old make for automating various non-compilation-related activities, but then again, plain Python is actually very good for automation if you get into the right mindset. Consequently, I've just written a bunch of functions which run programs, test outputs and potentially feed those outputs to other programs. Where most of the available generic tools seem to frustrate is in their support of the often necessary but complicated behaviour required to minimise the amount of unnecessary work performed, through frameworks which seem to obscure the nature of the work itself. I do understand that it can be awkward to work out which object files need recompiling due to changes in source files, for example, and that one doesn't want to see the logic involved reproduced all over the place, but I do wonder whether the machinery around such matters isn't sometimes more complicated in these tools as soon as one strays outside the common cases. It seems to me that some common build-related primitives implemented as functions combined with plain Python would be a good enough combination for a lot of tasks in this domain. Paul From bignose+hates-spam at benfinney.id.au Fri Jul 11 20:19:20 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 12 Jul 2008 10:19:20 +1000 Subject: Loading just in time References: Message-ID: <87k5fsosxj.fsf@benfinney.id.au> Ross Ridge writes: > D'Arcy J.M. Cain wrote: > >def calc_tax(*arg, **name): > > from calc_tax import calc_tax as _func_ > > calc_tax = _func_ > > return _func_(*arg, **name) > > This should do what you want: > > def calc_tax(*arg, **name): > global calc_tax > from calc_tax import calc_tax > return calc_tax(*arg, **name) > > I suspect though that the cost of importing a lot of little modules > won't be as bad as you might think. The performance cost isn't the only consideration. Importing modules at arbitrary places scattered through the code imposes a maintenance burden on any reader of the code. For this reason, PEP 8 requires conformant code to have imports in a standard location in the module: - Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. Imports should be grouped in the following order: 1. standard library imports 2. related third party imports 3. local application/library specific imports You should put a blank line between each group of imports. Put any relevant __all__ specification after the imports. This doesn't contradict the use of many small modules, but please, keep them imported according to PEP 8. -- \ ?People always ask me, ?Where were you when Kennedy was shot?? | `\ Well, I don't have an alibi.? ?Emo Philips | _o__) | Ben Finney From ewertman at gmail.com Sat Jul 26 15:58:51 2008 From: ewertman at gmail.com (Eric Wertman) Date: Sat, 26 Jul 2008 15:58:51 -0400 Subject: Execution speed question In-Reply-To: <4889a36f$1@news2-rz-ap.ethz.ch> References: <4889a36f$1@news2-rz-ap.ethz.ch> Message-ID: <92da89760807261258m5233145dr912c0d129c1c2045@mail.gmail.com> > The number of nodes is very large: millions for sure, maybe tens > of millions. If considering (2), take note of my BOLD text above, which > means I can't remove nodes as I iterate through them in the main loop. Since your use of 'node' is pretty vague and I don't have a good sense of what tests you are running and how long they would take, I'm only speculating, but a single loop might be the wrong way to go about that. If you are going to be frequently running tests and switching nodes on/off, have you considered a separate set of processes to do both? For example: A set of some number of "tester" threads, that loop through and test, recording thier results (somewhere). You could then have a separate loop that runs every so often, checks all the current test values, and runs through the nodes once, switching them on or off. I know it's not exactly what you asked, but depending on what your nodes are exactly, you can avoid a lot of other problems down the road. What if your single loop dies or gets hung on a test? With a separate approach, you'll have a lot more resilience too.. if there's some problem with a single tester or node, it won't keep the rest of the program from continuing to function. From gerard.blais at gmail.com Wed Jul 9 07:40:59 2008 From: gerard.blais at gmail.com (Gerry) Date: Wed, 9 Jul 2008 04:40:59 -0700 (PDT) Subject: How to make python scripts .py executable, not bring up editor References: <7a34ceb4-4f2e-4c79-aeb2-587235cab19d@z72g2000hsb.googlegroups.com> Message-ID: <12faab2c-1fdd-4858-8c61-d57548076aa6@e39g2000hsf.googlegroups.com> And if you've gotten this far, why not take the next step: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/476204 and just type tryme (as opposed to tryme.py) Gerry From Eric_Dexter at msn.com Mon Jul 14 10:56:47 2008 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Mon, 14 Jul 2008 07:56:47 -0700 (PDT) Subject: new python podcast Message-ID: http://www.podango.com/tag/python I just started to play with this and I wanted to know if there is any interest in this sort of thing now that the last (maybe I should say most proliffic) python podcaster has stopped being active.. I would also be intrested in knowing if there is a particular bit rate that people are after... first episode is an intro to the panda python setup.. mostly from the manual.. From eric.butteriss at wanadoo.fr Sat Jul 12 08:06:37 2008 From: eric.butteriss at wanadoo.fr (eric.butteriss) Date: Sat, 12 Jul 2008 14:06:37 +0200 Subject: Confused Message-ID: <000001c8e417$c2b5bc50$0a01a8c0@HOMEPC> Please tell me why may mail is being returned. The message says I have been blacklisted...for what reason? I never open mail that I know is not expected and I never send junk or spam. I am trying to send important info to my cousin. Thank you in anticipation E Butteriss -------------- next part -------------- An HTML attachment was scrubbed... URL: From cokofreedom at gmail.com Wed Jul 9 07:10:59 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 9 Jul 2008 04:10:59 -0700 (PDT) Subject: a simple 'for' question References: Message-ID: On Jul 9, 2:08 am, Ben Keshet wrote: > Hi fans, > > I want to use a 'for' iteration to manipulate files in a set of folders, > something like: > > folders= ['1A28','1A6W','56Y7'] > for x in folders: > print x # print the current folder > f = open('my/path/way/x/my_file.txt', 'r') > ... > > where 'x' in the pathway should iterate over '1A28','1A6W','56Y7'. How > should I identify 'x' in the pathway line as the same x that is > iterating over 'folders'? > > I am getting the following error: > > Traceback (most recent call last): > File > "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Linux\Dock_method_validation\myscripts\test_for.py", line 5, > in > f = open('c:/Linux/Dock_method_validation/x/receptor.mol2', 'r') > IOError: [Errno 2] No such file or directory: > 'c:/Linux/Dock_method_validation/x/receptor.mol2' > > I tired several variations: %x, 'x', "x", etc. all gave me similar errors. > > Thanks for your help, > BK >>> folders = ["a", "b", "c"] >>> for item in folders: print item file = open("my/path/way/" + item + "/my_file.txt", "r") From gagsl-py2 at yahoo.com.ar Mon Jul 28 07:05:48 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 28 Jul 2008 08:05:48 -0300 Subject: Raw Strings (I Think) References: Message-ID: En Thu, 24 Jul 2008 12:02:00 -0300, Lanny escribi?: > I've used glob.glob to get a list of files in a directory > and now I want to use os.system to execute one of > those files, the problem is that python automatically > puts a escape charater infront of the back slashes > so the os.system gets X:\\####\\####\\ and is useless, > I think I need to convert my string to a raw string but > I don't know how. Those \\ represent a SINGLE character. That is, they LOOK duplicated in code and when you use repr(...) but it's actually a single backslash: >>> path = "X:\\abc" >>> path 'X:\\abc' >>> print path X:\abc >>> len(path) 6 Probably you have another issue - please post a short but complete failing code... -- Gabriel Genellina From straton at lampsacos.demon.co.uk Mon Jul 28 19:22:40 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Tue, 29 Jul 2008 00:22:40 +0100 Subject: derivative in numpy In-Reply-To: References: Message-ID: Ken Starks wrote: > knielsen73 at gmail.com wrote: >> Hi, >> >> I am looking to do a simple derivative. I would expect such a function >> to be available in numpy, but can't find it. I have written my own, >> but just curious if anybody knows of such function in numpy. >> >> Cheers, >> Kim > numpy and much more are wrapped together in 'sage' and you should get > the functionality you need there. > > For a review, see: > > http://vnoel.wordpress.com/2008/05/03/bye-matlab-hello-python-thanks-sage/ Sorry, the review isn't very useful. for something more focused on your request, see: http://www.sagemath.org/doc/tut/node13.html From tjreedy at udel.edu Wed Jul 2 20:40:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 02 Jul 2008 20:40:52 -0400 Subject: Generating list of possible configurations In-Reply-To: References: Message-ID: Mensanator wrote: > On Jul 2, 4:53 pm, "bjorklund.e... at gmail.com" > wrote: >> After this I tried figuring out a function that would generate the >> different possible configurations, but I couldn't quite wrap my head >> around it... > Lookup "Cartesian Product". > >> Any pointers as to how one would go about >> solving something like this would be greatly appreciated. > > for a in [True,False]: > for b in [True,False]: > for c in [1,2,3,4]: > print 'combined settings:',a,'\t',b,'\t',c This has been added to itertools at least for 2.6/3.0 >>> import itertools as it >>> for prod in it.product((True,False), (True,False), (1,2,3,4)): print(prod) # or run test (True, True, 1) (True, True, 2) (True, True, 3) (True, True, 4) (True, False, 1) (True, False, 2) (True, False, 3) (True, False, 4) (False, True, 1) (False, True, 2) (False, True, 3) (False, True, 4) (False, False, 1) (False, False, 2) (False, False, 3) (False, False, 4) The sequences of sequences can, of course, be a variable: >>> options = ((True,False), (True,False), (1,2,3,4)) >>> for prod in it.product(*options): print(prod) does the same thing. So you can change 'options' without changing the test runner. tjr From ldo at geek-central.gen.new_zealand Mon Jul 21 05:13:39 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 21 Jul 2008 21:13:39 +1200 Subject: Python Written in C? References: Message-ID: In message , Michiel Overtoom wrote: > Many major text/word processing programs (Emacs, vi, MS-Word) are also > written in C. Does that mean you should do all your text processing in C? How else would you implement a Boyer-Moore algorithm? From rocksportrocker at googlemail.com Tue Jul 22 08:46:42 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Tue, 22 Jul 2008 05:46:42 -0700 (PDT) Subject: Python embedding question (2). References: Message-ID: On 22 Jul., 14:07, Thomas Troeger wrote: > Carl Banks wrote: > > On Jul 17, 9:57 am, Thomas Troeger > > wrote: > >>> I'd say that PyGame could be a solution. > >>> Or otherwise you could do your own audio/graphics programming (you don't > >>> tell us which OS you use, but there exist python modules that allow you > >>> to do barebones graphics & sound programming on linux...). > > Pyglet runs on top of OpenGL, which might have performance problems on > > an embedded device, if OpenGL or Mesa is even supported. ?If it's > > supported, I suspect performance will be adequate for 2D drawing. ?It > > almost certainly is the lightest solution you can find. > > > Carl Banks > > I've managed to put together a small pyGame program, it runs smoothly > and seems to be exactly what I wanted. It's fast! Even with 100 moving > objects it still runs so fast that I can consider using Python/pyGame > for the whole project. > > There are still some questions left which I haven't found out by myself, > so maybe someone here can answer them: > > - I can't see how to create more sophisticated text output, it seems the > built in font render facilities are limited to simple strings. Is that > true? I'd need a way to at least render multiline text with paragraphs > and bidirectionality, like pango does it. Is there a way to integrate > pango support into pyGame? I'd prefer marked up text display with text > properties ... > - Is there some way to reserve screen areas so they are excluded from a > blit, or do I have to manage stuff like this myself? I am thinking about > several graphic layers where each layer is painted on top of the next > layer, for example to draw a gui in front of a background image. > - There seems to be support for video overlay, i.e. is it possible to > have an external program paint an image from a camera into a portion of > the screen while pyGame is running? > > Maybe this is the wrong list to ask, so please forgive the question but > direct me to somewhere better. > > Cheers, > Thomas. Maybe http://sourceforge.net/projects/pygameui/ helps you, at least the source code. Greetings, Uwe From larzluv at hotmail.com Fri Jul 18 14:43:26 2008 From: larzluv at hotmail.com (Larry Hale) Date: Fri, 18 Jul 2008 11:43:26 -0700 (PDT) Subject: Python Behind a Squid Corporate Proxy on Windows References: <7b541a3b-846f-496a-aee1-d5719217e011@m45g2000hsb.googlegroups.com> <821d7616-3faa-4dae-a988-18caf4f8598a@8g2000hse.googlegroups.com> <84c473ed-6993-481a-b789-35851242895b@f1g2000prb.googlegroups.com> Message-ID: Thank you so much for the reply, but alas: I get the same results. (urllib2 makes the initial request, Squid replies "Error 407: Proxy Authentication Required", which urllib2 dutifully fails on/raises said error...) I do appreciate your time, though! :) -Larry On Jul 18, 3:08?am, Chris wrote: > On Jul 17, 6:40?pm, Larry Hale wrote: > > > Err, the line above should be: > > > proxy_handler = urllib2.ProxyHandler( { "http": "http:// > > myusername:passw... at webfilter.xyz.local:3128" } ) > > > (Sorry! ?:) > > some old code I wrote to download public domain info for our company, > also through a squid proxy and this still works for me > > import urllib2, urllib > > proxy = urllib2.ProxyHandler({'http': 'http:// > username:password at proxy_url:proxy_port'}) > auth = urllib2.HTTPBasicAuthHandler() > opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) > urllib2.install_opener(opener) > > conn = urllib2.urlopen('http://python.org') > return_str = conn.read() > > fp = open('python.html','w').write(return_str) From PengYu.UT at gmail.com Thu Jul 24 13:48:05 2008 From: PengYu.UT at gmail.com (Peng Yu) Date: Thu, 24 Jul 2008 10:48:05 -0700 (PDT) Subject: Is there a metacharacter to match transitions between any two of a set of non intersected char classes? Message-ID: Hi, '\b' only match the boundary between alphanumerical char and nonalphanumerical char. I'm wonder if there is a generic metacharacter to match the boundary between any non intersected char set defined in regex and its complement. For example, I have a few non intersected char sets [a-zA-Z_0-9], [:] and [\s], and lets call the new metacharactor \m. r"abc\m" would be the same as r"abc\b" r"abc:\m' would match "abc:" in r"abc:xy" but not "abc::xy" r"a \m" (with one space) would match "a " (with one space) in "a abc" but not "a abc" (with two spaces). I would like that I have the flexibility to define more non intersected char sets, while I don't want change the regex that I have written. Thanks, Peng From asd at pittle.org Sun Jul 6 07:10:50 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Sun, 6 Jul 2008 04:10:50 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: Message-ID: <8ad14f1d-f10b-4a1c-b66a-67ce987def88@m36g2000hse.googlegroups.com> On Jul 4, 7:31?am, Jeroen Ruigrok van der Werven wrote: > -On [20080630 23:51], Ali Servet D?nmez (a... at pittle.org) wrote: > > >This could be an extension, a plugin, an Emacs mode, a new editor or > >even a brand new huge all-fancy IDE, I don't care, but what am I > >missing here? > > Vim's omnicomplete (CTRL-X CTRL-O). > > See :help omnifunc within vim. > > -- > Jeroen Ruigrok van der Werven / asmodai > ????? ?????? ??? ?? ??????http://www.in-nomine.org/|http://www.rangaku.org/| GPG: 2EAC625B > Don't always think in a straight line... Jeroen, your advice might be *the solution* to the problem; but I'm not really into using Vi(m). Thank your very much anyway! From kyosohma at gmail.com Thu Jul 31 09:05:51 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 31 Jul 2008 06:05:51 -0700 (PDT) Subject: working pylint anyone? References: <6fdf17Fb2bboU1@mid.uni-berlin.de> Message-ID: On Jul 31, 4:29?am, "Diez B. Roggisch" wrote: > Hi, > > until yesterday I was a happy user of pylint. Then I upgraded to ubuntu > hardy heron - and the trouble began. > > The packaged version of pylint (0.13.2) fails with this error (last line): > > logilab.common.configuration.UnsupportedAction: callback > > The same error happens if I use > > easy_install-2.5http://release.ingeniweb.com/third-party-dist/logilab.installer-0.1.tgz > > as found on the net. Using easy_install pylint misses logilab-common & > astng, installing these additionally (easy_install) creates two eggs - but > unfortunately, the don't actually create a namespace-package logilab, > instead either one of them is picked up depending on installation order. > > Then I tried the source releases - no luck either, either they produce the > same error or something similar. > > I tried looking into the MLs - the last posts are from around 2006, so I > refrained from actually subscribing. > > So - anybody out here having an actually working pylint config and can tell > me what versions work together? I've become pretty dependend on it to be > honest... > > Diez For future reference, I found this installer package helpful in getting PyLint and its dependencies to all install correctly: http://tarekziade.wordpress.com/2008/02/20/pylint-installation-made-easier/ http://pypi.python.org/pypi/logilab.pylintinstaller I used it on Windows, but it should (theoretically) work on Linux just as well. Mike From heikki at osafoundation.org Thu Jul 24 01:33:19 2008 From: heikki at osafoundation.org (Heikki Toivonen) Date: Wed, 23 Jul 2008 22:33:19 -0700 Subject: Undocumented Python 2.6 change: Py_None vs NULL when C implementation raises exception In-Reply-To: <4887b13a$0$7677$9b622d9e@news.freenet.de> References: <4887b13a$0$7677$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > Heikki Toivonen wrote: >> I tracked this down to the C code incorrectly returning Py_None when it >> should have returned NULL. Changing the C code to return NULL made it >> behave correctly in 2.6. > > Can you please be specific what function you are talking about? Perhaps it wasn't clear that I was referring to the C code in an extension, M2Crypto. I assumed that this affected all extension code like this, which is why I didn't mention the actual lines. It appears from Fredrik's comment that this might not be just a 2.6 issue, but that this problem has cropped up in the past as well more or less randomly. >> I don't know how common a mistake it is to return Py_None when NULL >> should have been returned, but it might be worth a note in the list of >> changes for 2.6 that this behavior changed, don't you think? > > Perhaps. OTOH, perhaps the change is completely erroneous. In that case, > rather than documenting it, it should be reverted. > > Unfortunately, as you keep the specific issue secret, none of this will > happen, as we have no clue what you are talking about. I don't know what change in Python caused the change in M2Crypto behavior. I can only point you to the change I made in M2Crypto if you are interested: http://viewcvs.osafoundation.org/m2crypto/trunk/SWIG/_pkcs7.i?rev=531&r1=611&r2=531 If you revert that change and run the M2Crypto unit tests you will see the single error in the tests. > I'm sure there are tons of silent changes, in this release, all past > releases, and all future releases, not only in Python, but in any > software. Given that there is a long document showing the changes in each Python release, I would hope all intended changes of significance would be listed. Of course mistakes can happen, which was why I posted in the first place. I have no plans to track down the exact change in Python code that caused this. There does not seem to be much point, since according to Fredrik this seems to be an area that is practically undefined and the M2Crypto code was clearly buggy. -- Heikki Toivonen From ddasilva at umd.edu Wed Jul 30 00:30:37 2008 From: ddasilva at umd.edu (Daniel da Silva) Date: Wed, 30 Jul 2008 00:30:37 -0400 Subject: static variables in Python? In-Reply-To: References: Message-ID: <8d9ec3dd0807292130p7452e54eoba116d2f346d9b70@mail.gmail.com> This is the solution I suggest. It is fairly trivial, and works by introducing the "self.static" namespace for a class's static variables, in contrast to "self" for the class's instance variables. ----------------------------------- class Static(object): pass personStatic = Static() class Person: static = personStatic def __init__(self, name, age): self.name = name self.age = age def setVersion(self, version): self.static.version = version def getVersion(self): return self.static.version ----------------------------------- Daniel On Tue, Jul 29, 2008 at 4:40 PM, kj wrote: > > > Yet another noob question... > > Is there a way to mimic C's static variables in Python? Or something > like it? The idea is to equip a given function with a set of > constants that belong only to it, so as not to clutter the global > namespace with variables that are not needed elsewhere. > > For example, in Perl one can define a function foo like this > > *foo = do { > my $x = expensive_call(); > sub { > return do_stuff_with( $x, @_ ); > } > }; > > In this case, foo is defined by assigning to it a closure that has > an associated variable, $x, in its scope. > > Is there an equivalent in Python? > > Thanks! > > kynn > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. > -- > http://mail.python.org/mailman/listinfo/python-list > From elessar at nienna.org Sat Jul 26 00:43:45 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 25 Jul 2008 22:43:45 -0600 Subject: Attack a sacred Python Cow In-Reply-To: <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <5dd326f8-97ed-4761-b132-a2ead497a66b@m45g2000hsb.googlegroups.com> <5845bf4f-65bf-4a36-b9fe-25cd896b6926@q28g2000prh.googlegroups.com> Message-ID: <488AAB81.5070603@nienna.org> Jordan wrote: > Well this discussion is chugging along merrily now under its own > steam, but as the OP I should probably clarify a few things about my > own views since people continue to respond to them (and are in some > cases misunderstanding me.) > > I *like* explicit self for instance variable access. There are > arguments for and against, and my personal opinion is that the > arguments for are stronger. Local variables and instance variables > should be explicitly differentiated somehow, for the sake of > readability. Python's approach works. I slightly prefer Ruby's @, > because I think the brevity is a net win for something so commonplace > (is it less readable? Maybe. is "def" less readable than "define"? I > don't know - I think about 10 seconds of coding in Python or Ruby is > enough for you to be able to instantly grok def. Likewise, @. The > argument is more aesthetic IMO - how many perl-style/1337speak pu|\| > (tu at t10n m at r|<$ can you stand?) > > I have come to dislike explicit self in method argument lists. Sure, > there are reasons. I don't think they're at all strong enough. > > I'm definitely against the != behaviour, and maybe will get around to > actually PEPing it. > > The point I was trying to make originally was that applying any mantra > dogmatically, including Explicit is better than implicit, can lead to > bad results. Perhaps having Practicality beats purity is enough of a > reminder of that fact for the Python community :-) > -- > http://mail.python.org/mailman/listinfo/python-list > Having followed this entire discussion, I don't think that explicit vs. implicit is really the issue. Your own examples, self in the arg list and __ne__ not being the negation of __eq__ by default, seem to contradict your premise that explicit is dogmatically favored over implicit. Keep in mind that another core principle of Python is "don't make the user type it if they don't have to." As you yourself admit, there are very compelling reasons to make the user type self in every method argument list, one of which being yet another Python principle, readability. Therefore, explicit self didn't come through dogmatic adherence to explicit over implicit, but through careful consideration. As for !=, it seems like there is a technical reason for the behavior. Remember, there is no default __ne__ method, so the behavior you want would have to live in the interpreter. If __ne__ isn't defined, it would have to try to call __eq__ and negate the result. Is there any other lookup that is treated this way? It seems like a kludge to add this special type of behavior for one case that doesn't seem to bother most people anyway. So really, this is about a couple annoyances you've found in a language you otherwise like. And it seems like both can be addressed pretty easily. PyLint, for example, already checks that self is the first argument of methods. And since it has a plugin system, I'm sure you could add a check for __ne__ if __eq__ is defined. You can turn off the checks you don't care about and bind it to a key combo in your text editor. Those annoying little errors will be exposed very quickly. -Matt From deets at nospam.web.de Tue Jul 29 11:11:28 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jul 2008 17:11:28 +0200 Subject: Build tool for Python References: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Message-ID: <6f8qb5Fafh42U2@mid.uni-berlin.de> Hussein B wrote: > Hi. > Apache Ant is the de facto building tool for Java (whether JSE, JEE > and JME) application. > With Ant you can do what ever you want: compile, generate docs, > generate code, packing, deploy, connecting to remote servers and every > thing. > Do we have such a tool for Python projects? distutils and setuptools are used to create distributions of python-packages, potentially compiling e.g. C or pyrex-sources, and you can hook into them to create e.g. api-docs. Diez From fredrik at pythonware.com Tue Jul 22 15:34:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 21:34:51 +0200 Subject: software engineering foundations? In-Reply-To: References: <18566.11394.326317.821553@montanaro-dyndns-org.local> Message-ID: Fredrik Lundh wrote: > just get McDonnell's "Code Complete": > > http://www.cc2e.com/ McConnell, that is. McConnell. sorry. From fabiofz at gmail.com Sat Jul 5 07:34:56 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Sat, 5 Jul 2008 08:34:56 -0300 Subject: pydev and psycopg2 - weird behaviour In-Reply-To: <486e7bfc@news.alcatel.com> References: <486e7bfc@news.alcatel.com> Message-ID: Hi Ross, Usually that happens when some module contains too much runtime information and the static analysis cannot get it... You can probably fix that by adding 'psycopg2' to the list of builtin modules... See http://fabioz.com/pydev/manual_101_interpreter.html for information on how to configure that (look for forced builtins). Cheers, Fabio On 7/4/08, RossGK wrote: > > > I've been using pydev for a short while successfully, and Django with > postgresql as well. psycopg2 is part of that behind the scenes I would > imagine, to make django work. > > Now I'm trying to use psycopg2 in a non-Django program, I'm seeing some > weird behaviour > > My "import psycopg2" is tagged in pyDev (eclipse) as "Unresolved Import: > psycopg2" > > But when I run my code anyway, I seem to connect to the postgresql DB okay. > If I remove the import, and try it, it fails. > > So it seems to use it, but thinks it's unresolved. Any idea what's going > on there? > > Just to be sure it's installed right, I reinstalled with no change. I also > opened a python shell (cmd window in winXP environment) and on the command > line issued a psycopg2 connect request which succeeds as well. So it mostly > seems to be an erroneous report from pydev that it can't resolve psycopg2 > when it apparently can? > > Your input appreciated... > > Ross. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From circularfunc at yahoo.se Thu Jul 3 14:00:20 2008 From: circularfunc at yahoo.se (defn noob) Date: Thu, 3 Jul 2008 11:00:20 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: <6d4bfmFp3aoU1@mid.uni-berlin.de> <0f6f795d-8041-463e-8e98-9d830ca3fc5b@l42g2000hsc.googlegroups.com> Message-ID: <64c5634a-f8af-4de6-a337-be83c59aed3b@m44g2000hsc.googlegroups.com> and yes it is parallel python. and windows vista. and the python GUI shell. From rotlaus at gmail.com Mon Jul 7 02:01:45 2008 From: rotlaus at gmail.com (Rotlaus) Date: Sun, 6 Jul 2008 23:01:45 -0700 (PDT) Subject: extended setattr() Message-ID: 2 weeks ago i asked for a etended getattr() which worked really fine, but now i would love to have a extended setattr() as well. Lets assume i have some classes: class A(object): def __init__(self): self.B = B() class B(object): def __init__(self): self.C = C() class C(object): def __init__(self, foo='', bar=''): self.foo = foo self.bar = bar and now i wanna do something like this: a=A() ext_setattr(a, 'B.C', ('a', 'b')) Is this possible? It would also be nice if the attributes would be created if they not exist, always implying that objectname==objecttype. Kind regards, Andre From M.Busetto at isac.cnr.it Wed Jul 23 05:07:25 2008 From: M.Busetto at isac.cnr.it (maurizio) Date: Wed, 23 Jul 2008 11:07:25 +0200 Subject: maximum value in a column of file In-Reply-To: References: <4886DCF3.10107@isac.cnr.it> Message-ID: <4886F4CD.8010704@isac.cnr.it> i tryed to use the module max of numpy, the problem is that i don't know how to put the column of the file in an array. (i'm new in phyton). anyway if you think there is a better way..... Fredrik Lundh wrote: >
maurizio > wrote: > >> which is the best way for the calculation of the maximum value in >> a column of a file? > > what approach have you tried, and what happened when you tried it? > > > > >
From tjreedy at udel.edu Fri Jul 18 03:45:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Jul 2008 03:45:58 -0400 Subject: % sign in python? In-Reply-To: <48d08494p4jnhkrhgidmgppg1aostmurvn@4ax.com> References: <48d08494p4jnhkrhgidmgppg1aostmurvn@4ax.com> Message-ID: Tim Roberts wrote: > Steven Howe wrote: > >> Terry Reedy wrote: >>> korean_dave wrote: >>>> What does this operator do? Specifically in this context >>>> >>>> test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) >> I thought, in this contexted, it was mapping operator. You miss clipped. I never wrote that. Please be careful, especially about attributing mis-information. > What?? > > Python does not have a "mapping operator". It has a "map" function, but no > equivalent operator. > > % is either the string formatting operator (when the left-hand operand is a > string) or the modulo operator (when the left-hand operand is a number). Which I learned 10 years ago. What I did write was a pre-announcement of a Python symbol glossary, which I just finished a first draft of. And now to bed ;-) From enleverlesX.XmcX at XmclaveauX.com Thu Jul 3 16:20:43 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Thu, 3 Jul 2008 22:20:43 +0200 Subject: PIL(Py Image lib), show() not showing picture... In-Reply-To: <84a8f15a-594f-4e02-aa89-b70932eae420@59g2000hsb.googlegroups.com> References: <84a8f15a-594f-4e02-aa89-b70932eae420@59g2000hsb.googlegroups.com> Message-ID: <486d366d$0$879$ba4acef3@news.orange.fr> Hi! Which OS? On Vista, you MUST reconfig the "aper?u images et t?l?copies" (in french ; sorry, I don't know the english translation). @-salutations Michel Claveau From fredrik at pythonware.com Mon Jul 21 08:14:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 14:14:15 +0200 Subject: simple question about dictionaries In-Reply-To: <8aedc744-f432-4a4a-a6e4-2bb714caf720@x35g2000hsb.googlegroups.com> References: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> <8aedc744-f432-4a4a-a6e4-2bb714caf720@x35g2000hsb.googlegroups.com> Message-ID: Jeff wrote: > throw KeyError('%s not found' % str(val)) "throw"? and shouldn't that be a ValueError? ;-) From tcfg at sina.com Thu Jul 17 02:18:45 2008 From: tcfg at sina.com (tcfg at sina.com) Date: Wed, 16 Jul 2008 23:18:45 -0700 (PDT) Subject: how to debug python's extend module written in c/c++ on windows References: <64d771b2-fbc8-4b6a-9725-3dc5063c5328@p25g2000hsf.googlegroups.com> <6e83v4F5pfg0U1@mid.uni-berlin.de> Message-ID: dear Diez: I need step into c function in extending module(DLL) when debugging the script. and I want Single-step debugging the extend module itself, but python script Launched The whole process. best regards fang From workitharder at gmail.com Sat Jul 12 23:03:17 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 12 Jul 2008 20:03:17 -0700 (PDT) Subject: Someone enlightened me References: Message-ID: <1724abf3-232a-4ffd-893d-fb0ee81e59e8@z72g2000hsb.googlegroups.com> On Jul 12, 7:08 pm, Marcus Low wrote: > Can someone explain to me, why the behaviour below is different when u > remark "lister" and unremark "self.lister"? > > #-------------------------------------------------------------- > class abc : > # remark this later and unremark "self.lister" > lister = [] > > def __init__ (self, val): > #self.lister = [] > self.lister.append(val) > > #-------------------------------------------------------------- > globallist = [] > #-------------------------------------------------------------- > def test () : > global l > for x in range(10) : > o = abc(x) > globallist.append(o) > o = "" > > for i in globallist : > print i.lister > > #-------------------------------------------------------------- > test() > #-------------------------------------------------------------- The way it's written, you're appending to a list associated with the class itself, which is created only once, then printing out that list 10 times. After you uncomment and comment the specified lines (this is the usual term, rather than "remark"), you are using a list that is associated with the actual object, then printing out the 10 different lists. Hope that's clear enough. --Buck From fredrik at pythonware.com Wed Jul 23 16:25:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 22:25:11 +0200 Subject: Raw Strings (I Think) In-Reply-To: References: Message-ID: Lanny wrote: > I've used glob.glob to get a list of files in a directory > and now I want to use os.system to execute one of > those files, the problem is that python automatically > puts a escape charater infront of the back slashes > so the os.system gets X:\\####\\####\\ and is useless, No, it doesn't. The backslash doubling only happens when you "echo" a variable to the terminal in interactive mode. If you want to know that the string really contains, use "print". Here's an example: >>> import glob >>> files = glob.glob("\\bin\\ls.exe") >>> files ['\\bin\\ls.exe'] >>> files[0] '\\bin\\ls.exe' >>> print files[0] \bin\ls.exe >>> import os >>> os.system(files[0]) Demo Makefile.pre.in Parser Doc Misc Python Grammar Modules README Include Objects RISCOS LICENSE PC Tools Lib PCbuild configure Mac PCbuild8 configure.in Btw, if you want to pass arguments to the program, you might want to use the "subprocess" module instead, since it handles escaping and quoting for you all by itself: >>> import subprocess >>> subprocess.call([files[0], "-l"]) total 479 drwxr-xr-x 26 1006 everyone 0 Oct 14 2006 Demo drwxr-xr-x 33 1006 everyone 0 Oct 14 2006 Doc drwxr-xr-x 6 1006 everyone 0 Oct 14 2006 Grammar ... There's also a function called "os.startfile", which can be used to "open" an arbitrary file (in the same as if you'd double-click on it in the explorer). > I think I need to convert my string to a raw string but > I don't know how. Raw strings are an alternate syntax for adding string literals to your source code, and has nothing to do with output. From adityashukla1983 at gmail.com Thu Jul 24 16:41:59 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Thu, 24 Jul 2008 15:41:59 -0500 Subject: Reading a file Message-ID: <73045cca0807241341x4c1e6b2cs3aab64be7df6e406@mail.gmail.com> Thanks a lot guys , i got it now. Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From laredotornado at zipmail.com Wed Jul 30 12:28:07 2008 From: laredotornado at zipmail.com (laredotornado) Date: Wed, 30 Jul 2008 09:28:07 -0700 (PDT) Subject: Syntax error in my script Message-ID: Hi, This might be more relevant for another group, but since this is a Python script, thought I'd start here. I'm trying to write a WLST script for WebLogic 9.2. I coped one directly from WebLogic's site (http://e-docs.bea.com/wls/docs90/config_scripting/ using_WLST.html#1078952), but I'm getting errors. Specifically, I'm getting $HOSTNAME:"$PWD"->sh run_setup_cluster.sh Initializing WebLogic Scripting Tool (WLST) ... Welcome to WebLogic Server Administration Scripting Shell Type help() for help on available commands Problem invoking WLST - Traceback (innermost last): (no code object) at line 0 File "/export/third-party/etsbea/home/etsbea/tests/npsconfig/ createcluster.py", line 2 from javax.management import * ^ SyntaxError: invalid syntax Below is my script. I know nothing about Python but cutting and pasting from BEA's site isn't cutting it. ============Begin createcluster.py file======================= from java.util import * from javax.management import * import javax.management.Attribute print 'starting the script .... ' connect('system','weblogic','t3://localhost:7001') clusters = "NPSCONFIG_GUI_Cluster" ms1 = {'managed1':7019:8020,'managed2':7020:8021} clustHM = HashMap() edit() startEdit() for c in clusters: print 'creating cluster '+c clu = create(c,'Cluster') clustHM.put(c,clu) cd('Clusters/' + c) set('MulticastAddress', '237.0.0.101') set('MulticastPort', 9200) set('WeblogicPluginEnabled', 'true') cd('..\..') clus1 = clustHM.get(clusters[0]) for m, lp, ssl_lp in ms1.items(): managedServer = create(m,'Server') print 'creating managed server '+m managedServer.setListenAddress('10.61.6.134') managedServer.setListenPort(lp) managedServer.setEnabled(0) cd('SSL/cgServer') managedServer.setEnabled(1) managedServer.setListenPort(ssl_lp) managedServer.setCluster(clus1) save() activate(block="true") disconnect() print 'End of script ...' exit() ==============End cretaecluster.py file======================= From duncan.booth at invalid.invalid Fri Jul 11 13:18:53 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Jul 2008 17:18:53 GMT Subject: strip() using strings instead of chars References: Message-ID: Christoph Zwerschke wrote: > In Python programs, you will quite frequently find code like the > following for removing a certain prefix from a string: > > if url.startswith('http://'): > url = url[7:] If I came across this code I'd want to know why they weren't using urlparse.urlsplit()... > > Similarly for stripping suffixes: > > if filename.endswith('.html'): > filename = filename[:-5] ... and I'd want to know why os.path.splitext() wasn't appropriate here. > > My problem with this is that it's cumbersome and error prone to count > the number of chars of the prefix or suffix. If you want to change it > from 'http://' to 'https://', you must not forget to change the 7 to 8. > If you write len('http://') instead of the 7, you see this is actually > a DRY problem. > > Things get even worse if you have several prefixes to consider: > > if url.startswith('http://'): > url = url[7:] > elif url.startswith('https://'): > url = url[8:] > > You can't take use of url.startswith(('http://', 'https://')) here. > No you can't, so you definitely want to be parsing the URL properly. I can't actually think of a use for stripping off the scheme without either saving it somewhere or doing further parsing of the url. From dear.jay.logan at gmail.com Sun Jul 27 17:49:01 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Sun, 27 Jul 2008 14:49:01 -0700 (PDT) Subject: Where is the correct round() method? Message-ID: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> Hello, I need a round function that _always_ rounds to the higher integer if the argument is equidistant between two integers. In Python 3.0, this is not the advertised behavior of the built-in function round() as seen below: >>> round(0.5) 0 >>> round(1.5) 2 >>> round(2.5) 2 I would think this is a common need, but I cannot find a function in the Python library to do it. I wrote my own, but did I miss such a method in my search of the Python library? Thanks From elessar at nienna.org Tue Jul 29 18:42:59 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Tue, 29 Jul 2008 16:42:59 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> Message-ID: <488F9CF3.6050301@nienna.org> Carl Banks wrote: > On Jul 29, 11:12 am, Matthew Fitzgibbons wrote: >> Carl Banks wrote: >>> On Jul 28, 8:15 pm, Steven D'Aprano >> cybersource.com.au> wrote: >>>> On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: >>>>> On Jul 28, 10:00 am, Steven D'Aprano >>>> cybersource.com.au> wrote: >>>>>> Cutting to the crux of the discussion... >>>>>> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: >>>>>>> I want something where "if x" will do but a simple explicit test >>>>>>> won't. >>>>>> Explicit tests aren't simple unless you know what type x is. If x could >>>>>> be of any type, you can't write a simple test. Does x have a length? Is >>>>>> it a number? Maybe it's a fixed-length circular length, and the length >>>>>> is non-zero even when it's empty? Who knows? How many cases do you need >>>>>> to consider? >>>>> Use case, please. I'm asking for code, not arguments. Please give me a >>>>> piece of code where you can write "if x" that works but a simple >>>>> explicit test won't. >>>> I gave you a piece of code, actual code from one of my own projects. If >>>> you wouldn't accept that evidence then, why would you accept it now? >>> I would accept as "evidence" something that satisfies my criteria, >>> which your example did not: it could have easily (and more robustly) >>> been written with a simple explicit test. I am looking for one that >>> can't. >>> You keep bringing up this notion of "more complex with no benefit", >>> which I'm simply not interested in talking about that at this time, >>> and I won't respond to any of your points. I am seeking the answer to >>> one question: whether "if x" can usefully do something a simple >>> explicit test can't. Everyone already knows that "if x" requires >>> fewer keystrokes and parses to fewer nodes. >>> Carl Banks >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> My use case involves a DAG of filters that pass data (of a variety of >> types--filters just pass on data types they don't understand) between >> them. I can also drop out of the filter chain at any point, using >> critera determined by the filters. These criteria, you guessed it, are >> bound to __nonzero__ in the filter and I determine whether or not to >> continue through the graph using "if x". You can't code explicit tests >> if you don't know what the tests even are beforehand. Also, I wanted to >> support builtins (ints and lists in particular) because they can be >> meaningful inputs to filters. Finally, as I add more filters and data >> types, I don't want to go back and mess with the code that decides >> whether or not to break out of the graph. > > Much like in Steven D'Aprano's example, still the only actual code > snippet I've seen, it seems that this can easily be done with a simple > explicit test by having all no-advance filters return None and testing > with "if x is not None". So it doesn't pass my criterion of being not > replaceable with simple explicit test. > > Maybe that's not workable for some reason. Perhaps if you'd post a > code example that shows this, rather than just talking about it, you > might be more persuasive. > > > Carl Banks > -- > http://mail.python.org/mailman/listinfo/python-list > The no-advance filters have to return the object because I don't just forget about it; I evaluate whether I pass it to the next filter or drop it in a completely different queue for use in the next stage of the operation. True means 'I'm ready to move on to the next stage,' False means 'Do the filter thing some more.' Furthermore, the argument that I should just change my API to make a 'simple test' work is not very convincing. The natural, obvious way for a filter to work is to pass through the data it operates on; why on Earth would it return None? I want to DO something with the data. In this case, make a decision about where to pass the data next. In Java, to accomplish this I would have to do lots of introspection and value checking (adding more any time I came up with a new kind of input), or make a new kind of interface that gives me a method so I can do a 'simple test' (including wrappers for ints and arrays and anything else I decide to pass in down the road). But Python supports duck typing and gives me a handy __nonzero__ method; I can rebind __nonzero__ in my filters for my own classes, and ints and lists are handled how I want them to be by default. So why jump through hoops instead of just using 'if x'? I don't have any postable code (it's in a half way state and I haven't touched it for a while), but I'll see if I can't find the time to bang something up to give you the gist. -Matt From varun.consit at gmail.com Tue Jul 1 09:35:25 2008 From: varun.consit at gmail.com (varun chadha) Date: Tue, 1 Jul 2008 06:35:25 -0700 (PDT) Subject: connecting to DBMS Message-ID: <669fe460-77bf-4e53-9f05-1237f2147b10@j1g2000prb.googlegroups.com> i am a newbie to python and is working on an application which needs to connect to the database. can anyone guide me through the DBMS that i can use and the module to connect to it. currently i have MySQL installed using the link on the python.org site but is unable to connect to it through python. pls specify the link to the tutorials which can guide to connect and execute my query. hopes u understood what i meant to say. thanks in advance From jonas.esp at googlemail.com Mon Jul 14 04:01:25 2008 From: jonas.esp at googlemail.com (Kless) Date: Mon, 14 Jul 2008 01:01:25 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> Message-ID: But in my dictionary both keys and values are unique. On Jul 14, 7:34?am, Dennis Lee Bieber wrote: > On Sun, 13 Jul 2008 16:21:11 -0700 (PDT), Kless > declaimed the following in comp.lang.python: > > > I need a dictionary where get the result from a 'key' (on left), but > > also from a 'value' (on right), how to get it? > > > I know that dictionaries aren't bidirectional, but is there any way > > without use two dictionaries? > > ? ? ? ? Just out of curiosity... What do you expect to have returned from... > > aDict = { "one" : "two", > ? ? ? ? ? ? ? ? "three" : "four", > ? ? ? ? ? ? ? ? "What?" : "two" ? ? } > > when looking for the value "two"? > > ? ? ? ? In a dictionary, the /keys/ are unique... but the /values/ can be > duplicates. From fredrik at pythonware.com Mon Jul 21 08:54:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 14:54:52 +0200 Subject: How to install simplejson on WinXP In-Reply-To: References: Message-ID: lookon wrote: > I am new to python and had difficulty in installing simplejson on > WinXP...Could anyone help me? Thanks what did you try, and what happened when you tried that? From mattheww at chiark.greenend.org.uk Tue Jul 29 21:52:31 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 30 Jul 2008 02:52:31 +0100 (BST) Subject: Boolean tests References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <87y73kg70u.fsf@benfinney.id.au> <009fa67c$0$20313$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >Anders wrote: >> "But then you decide to name the method "__nonzero__", instead of some >> nice descriptive name?" > That suggests to me that Anders imagined that __nonzero__ is something I > just made up, instead of a standard Python method. What does it suggest > to you? That he thinks using __nonzero__ like this decreases readability. He also wrote > In comparison, I gather you would write something like this: > class C: > def __nonzero__(self): > return len(self.method()[self.attribute]) > -1 > ... > c = get_a_C() > if c: > ... If he had imagined that __nonzero__ was something you just made up, the second-last line there would have read if c.__nonzero__() -M- From timothy.grant at gmail.com Tue Jul 15 20:53:09 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Tue, 15 Jul 2008 17:53:09 -0700 Subject: Testing for connection to a website In-Reply-To: <18476597.post@talk.nabble.com> References: <18473382.post@talk.nabble.com> <18476597.post@talk.nabble.com> Message-ID: On Tue, Jul 15, 2008 at 3:48 PM, Alexnb wrote: > > > > Alexnb wrote: > > > > Okay, I already made this post, but it kinda got lost. So anyway I need > to > > figure out how to test if the user is able to connect to a specific > > website. Last time I got pointed to the urllib2 page, but if I do > > urlopen() and and am not connected, the program stops. So I don't know if > > that was what you guys wanted me to do, but I don't think so, you guys > are > > smarter than that. So, how can I test for connection to a website. > > > > Just for anyone looking this up later here is code that works :) > > from urllib2 import * > import urllib2 > e = '' > > req = urllib2.Request('http://www.dictionary.com') > try: > response = urlopen(req) > > except HTTPError, e: > print e.code > except URLError, e: > print e.reason > > if e == '': > print "good to go" > -- > View this message in context: > http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p18476597.html > Sent from the Python - python-list mailing list archive at Nabble.com. > > -- > http://mail.python.org/mailman/listinfo/python-list > I'm glad to see you found the old post and implemented the code suggested there. -- Stand Fast, tjg. [Timothy Grant] -------------- next part -------------- An HTML attachment was scrubbed... URL: From shandy.b at gmail.com Thu Jul 3 21:19:58 2008 From: shandy.b at gmail.com (shandy.b at gmail.com) Date: Thu, 3 Jul 2008 18:19:58 -0700 (PDT) Subject: Python and timezones References: <66de1777-ab65-4708-904b-3e511409a662@m36g2000hse.googlegroups.com> Message-ID: I found a solution: http://groups.google.com/group/comp.lang.python/browse_thread/thread/aea64448eaca4778/250e908652e2646d If I use datetime.now(tz=tz) instead of datetime(Y,M,D,h,m,s, tzinfo=tz), it works. On Jul 3, 4:18?pm, "shand... at gmail.com" wrote: > Nah, it's got to be something more than that. ?A bunch of them are > screwed up. ?It's showing America/Saskatchewan as UTC-06:59. > > I think there's something wrong with my code. ?I've put it up at a > pastebin so that it's easier to read. > > http://pastebin.ca/1061776 > > On Jul 2, 11:22?am, Mensanator wrote: > > > On Jul 2, 12:43?am, "shand... at gmail.com" wrote: > > > > I'm trying to write some code to deal with world timezones, and I'm > > > getting a strange result. ?America/Iqaluit should not be showing up in > > > UTC+00:00, but it is. ?Can anyone see what's wrong with this code? > > > > import time > > > from datetime import datetime > > > import os > > > import pytz > > > > def getZoneNamesOnThisComputer(): > > > ? ? for i in pytz.all_timezones: > > > ? ? ? ? if os.path.exists( os.path.join('/tmp/usr/share/zoneinfo/', > > > i)): > > > ? ? ? ? ? ? yield i > > > > def getZonesGroupedByOffset(): > > > ? ? '''return a dict of all the zone names , grouped by their offset > > > ? ? eg: > > > ? ? {'-0400': ['America/Blanc-Sablon', 'Etc/GMT+4'], > > > ? ? ?'+0000': ['America/Iqaluit', 'Etc/GMT', 'Europe/Belfast', 'GB', > > > 'GMT'], > > > ? ? ?... > > > ? ? } > > > ? ? ''' > > > ? ? Y,M,D,h,m,s = time.localtime()[:6] > > > > ? ? zonesGroupedByOffset = {} > > > > ? ? for name in getZoneNamesOnThisComputer(): > > > ? ? ? ? tz = pytz.timezone(name) > > > ? ? ? ? now = datetime(Y,M,D,h,m,s, tzinfo=tz) > > > ? ? ? ? # strfime returns a string like "-0800" or "+0430" or "0000" > > > ? ? ? ? offsetKey = now.strftime('%z') > > > ? ? ? ? if not zonesGroupedByOffset.has_key(offsetKey): > > > ? ? ? ? ? ? zonesGroupedByOffset[offsetKey] = [] > > > ? ? ? ? zonesGroupedByOffset[offsetKey].append(name) > > > ? ? return zonesGroupedByOffset > > > > z = getZonesGroupedByOffset() > > > print z['+0000'] > > > > # Why is America/Iqaluit showing up here??? > > > The database contains an error. Shit happens, deal with it. > > From dream.andy at yahoo.com Fri Jul 25 23:47:10 2008 From: dream.andy at yahoo.com (Andy Peter) Date: Fri, 25 Jul 2008 20:47:10 -0700 (PDT) Subject: Exposure Your Google Groups in our FREE Advertising Board ! Message-ID: Exposure Your Google Groups in our FREE Advertising Board ! http://you.forumgogo.com/forum-7045-1.html Free Advertising Board in you.forumgogo.com (FREE AD EXPOSURES! ) http://you.forumgogo.com/forum-6637-1.html Your Forums and Community (Freebies, Games, Chat Room, Funny Stuff, General Discussion etc) http://you.forumgogo.com . From emen999 at gmail.com Fri Jul 25 06:05:00 2008 From: emen999 at gmail.com (code_berzerker) Date: Fri, 25 Jul 2008 03:05:00 -0700 (PDT) Subject: lxml, comparing nodes References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> <6c91a4da-6443-4570-8dd3-01c4ec169bf3@t54g2000hsg.googlegroups.com> <4888ad28$0$9491$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <4613042f-ed70-4cfa-8de9-a92b4df32923@k36g2000pri.googlegroups.com> > If document order doesn't matter, try sorting the elements of each level in > the two documents by some arbitrary deterministic key, such as (tag name, > text, attr count, whatever), and then compare them in order, instead of trying > to find matches in multiple passes. itertools.groupby() might be your friend here. I think that sorting multiple times by each attribute will cost more than I've managed to do: from lxml import etree from collections import deque import string, re, time def xmlEqual(xmlStr1, xmlStr2): et1 = etree.XML(xmlStr1) et2 = etree.XML(xmlStr2) let1 = [x for x in et1.iter()] let2 = [x for x in et2.iter()] if len(let1) != len(let2): return False while let1: el = let1.pop(0) foundEl = findMatchingElem(el, let2) if foundEl is None: return False let2.remove(foundEl) return True def findMatchingElem(el, eList): for elem in eList: if elemsEqual(el, elem): return elem return None def elemsEqual(el1, el2): if el1.tag != el2.tag or el1.attrib != el2.attrib: return False # no requirement for text checking for now #if el1.text != el2.text or el1.tail != el2.tail: #return False path1 = el1.getroottree().getpath(el1) path2 = el2.getroottree().getpath(el2) idxRE = re.compile(r"(\[\d*\])") path1 = idxRE.sub("", path1) path2 = idxRE.sub("", path2) if path1 != path2: return False return True Notice that if documents are in exact same order, each element is compared only once! From grante at visi.com Tue Jul 1 14:14:54 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 01 Jul 2008 13:14:54 -0500 Subject: How to use gnu readline library in program? References: Message-ID: <6e-dnXtxRu6D6ffVnZ2dnUVZ_sPinZ2d@posted.visi> >> What I want to do is replace sys.stdin.readline() with >> something that will provide the user with line editing and >> history recall. In other languages, one uses the Gnu readline >> library to do that, but my reading of the Python library >> documentation is that's not what the Python readline module is >> for. Am I wrong? > > Here's a simple example: > > import readline > > for s in "alpha beta gamma".split(): > readline.add_history(s) > > candidates = "red yellow pink blue black".split() > > def completer(word, index): > matches = [c for c in candidates if c.startswith(word)] > try: > return matches[index] + " " > except IndexError: > pass > > > readline.set_completer(completer) > readline.parse_and_bind("tab: complete") > > while 1: > print raw_input("$ ") Ah, thanks. It was far too simple. What I was looking for was simply: import readline then replace sys.stdin.readline() with raw_input() > You may also consider using the cmd module. I'll have to keep the cmd module in mind for other applications (where the user is entering commands). Rather than commands, the user of this application is entering data that changes little (if any) from one line to the next, so raw_input() is exactly what I needed. -- Grant Edwards grante Yow! I'm young ... I'm at HEALTHY ... I can HIKE visi.com THRU CAPT GROGAN'S LUMBAR REGIONS! From glman74 at gmail.com Sun Jul 27 05:51:40 2008 From: glman74 at gmail.com (glman74 at gmail.com) Date: Sun, 27 Jul 2008 02:51:40 -0700 (PDT) Subject: Iterating through 2 files simultaneously Message-ID: <7ae96aff-c1a7-4763-8db7-ff23766296df@u6g2000prc.googlegroups.com> Hi folks, I am trying to tee off both stdout and stderr from a process run through Popen. As a test, I am first trying to print the output below: from subprocess import Popen,PIPE ... p1 = Popen(['cvs', 'update'], stdout=PIPE, stderr=PIPE) for (l1, l2) in zip(p1.stdout, p1.stderr): print '-->' + l1, print '-->' + l2, This doesn't work - probably because I cannot iterate through the pipes this way. I am new to Python, and I'd appreciate it if you could please explain why this doesn't work and/or suggest an alternate way to redirect stdout and stderr to a common place. My objective is for my code to print out stdout/stderr messages and at the same time redirect them to a log file. Thanks Mahesh From basti.wiesner at gmx.net Tue Jul 15 13:46:09 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Tue, 15 Jul 2008 19:46:09 +0200 Subject: Is it legal to rebuild Python.exe to include Version property tab? References: Message-ID: ward.david at comcast.net : > My company distributes a COM object that can be license and userd by > our customers. Some of my company's internal application also use the > COM object. However, for internal applications, instead of licensing > the COM object, we just make the application registered as "friendly". > We accomplish this be including various information in the "version" > property tab of the calling EXE. > > In my case, the calling EXE is Python.exe. So, my question is, can we > rebuild Python.exe to include the various "version" information? Is > this allowed under the Python licensing agreement? Though being not a lawyer, I'd say "yes". Afair version metadata for windows executables is passed as compiler options, so you wouldn't even have to change the sources. Paragraph 2 of the PSF (the python license) grants you an explicit right to "reproduce, [...], prepare derivative works (and) distribute" Python, and there's no other paragraph saying "don't touch version information". Still, not sure paragraph 3 would affect distributors: "In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python." Looks like you have to add a document describing your changes to the modified distribution, but that shouldn't be showstopper ;) -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From tjreedy at udel.edu Sat Jul 12 19:25:18 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 19:25:18 -0400 Subject: Why is this blowing the stack, thought it was tail-recursive... In-Reply-To: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> References: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> Message-ID: ssecorp wrote: > def fib(n): > def fibt(a, b, n): > if n <= 1: > return b > else: > return fibt(b, a + b, n - 1) > if n == 0: > return 0 > else: > return fibt(0, 1, n); > > and can memoization speed up this even more? tesintg with memoization > doesnt really say anything because it is so fast it is instant anyway. Except for the fact that a+b gets slower as a and b get bigger, this would already be linear time in n. Memoization (here by means of a linear list) only helps if the list is preserved and one makes repeated requests for various fib values. I am just curious what input you tried that blew the stack? It had to be pretty large. The stack problem, by the way, is one reason linear induction is usually written in Python with iteration syntax instead of recursion syntax. Another is the extra simplicity. def fib(n): a,b = 1,0 while n: a,b,n = b, a+b, n-1 return b A third is the ease of conversion to a (space-efficient) generator function. def fib_gen() a,b = 1,0 while True: yield b a,b = b, a+b The generator it produces can be used, for instance, to fill a list (linear memo) 'on demand'. A model that leads to the linear algorithm (as opposed to the double recursion derived from Fibonacci's rabbit model) is as follows: A population consists of juveniles and adults. In one period, juveniles become adults (which never die) and adults birth (or bud off) one juvenile. (Yeast are somewhat like this.) At time 0, we start with 1 juvenile and 0 adults. How many adults are there at time n? Terry Jan Reedy From fredrik at pythonware.com Wed Jul 16 11:10:14 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 17:10:14 +0200 Subject: Angle brackets in command-line arguments? In-Reply-To: <52f1cde3-6240-46b0-8b03-478454e87688@b1g2000hsg.googlegroups.com> References: <52f1cde3-6240-46b0-8b03-478454e87688@b1g2000hsg.googlegroups.com> Message-ID: Keith Hughitt wrote: > I am using someone else's script which expects input in the form of: > > ./script.py arg2 is a common notation for "replace with argument value", so it could be that they're just expecting you to type: ./script.py arg1 arg2 Alternatively, they meant ./script.py arg2 in which case arg1 and arg2 are filenames. This is most commonly used with tools that process textfiles in some way. In the latter case, you can try the script simply by running: ./script.py and then typing the input to the terminal (use control-D on Unix or control-Z on Windows to terminate). Do the instructions use more meaningful names than "arg1" and "arg2"? From maphew at gmail.com Sat Jul 5 02:29:31 2008 From: maphew at gmail.com (maphew) Date: Fri, 4 Jul 2008 23:29:31 -0700 (PDT) Subject: install py2exe in vista References: <98aab64d0806211028i57bdc3e3kfaf2cf3b97e351e2@mail.gmail.com> Message-ID: <924c20f6-df19-449d-80ec-e69c9c8a6359@t54g2000hsg.googlegroups.com> SOLVED: right-click on the install program and "Run as administrator" solution courtesy of http://support.esri.com/index.cfm?fa=knowledgebase.techarticles.articleShow&d=34538 On Jun 22, 11:34?am, jim-on-linux wrote: > On Saturday 21 June 2008 13:28, Herman wrote: > > > ?I want to install it in > > vista >l#>, but i get this message in the process: > >couldnotcreate...py2exe-py2.5 > > I forwarded your question but you may want to ask again > at the link below. > > py2exe-us... at lists.sourceforge.net > > jim-on-linuxhttp://inqvista.com > > > > > I press 'OK', then.. > >couldnotset key value python 2.5 py2exe-0.6.8 > > > I press 'OK' again, then... > >couldnotset key value > > c:\Python25\Removepy2exe.exe" -u > > "c:\python25\py2exe-wininst.log > > > The installation goes on and do something, run some > > postinstall script. > > > I thought it should be ok, but i fail even creating > > a simple hello word exe. I get this message after i > > run python setup.py install: running install > > running build > > running install_egg_info > > Writing > > c:\Python25\Lib\site-packages\UNKNOWN-0.0.0-py2.5-eg > >g-info > > > No output is created. > > > Can I anyone help me with this? > > > > >ost&p=631985>- Hide quoted text - > > - Show quoted text - From stefan_ml at behnel.de Wed Jul 23 02:05:47 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 23 Jul 2008 08:05:47 +0200 Subject: xpathEval fails for large files In-Reply-To: References: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> <48864b0d$0$9494$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <4886ca3b$0$18828$9b4e6d93@newsspool2.arcor-online.net> Kanch wrote: > Original file was 18MB, and contained 288328 element attributes for > the particular path. You didn't say how many elements there are in total, but I wouldn't expect that to be a problem, unless you have very little free memory (say, way below 256MB). I just tried with lxml 2.1 and a 40MB XML file with 300 000 elements and it lets the whole Python interpreter take up some 140MB of memory in total. Looping over all elements by calling "list(root.iter())" takes a bit more than one second on my laptop. That suggests that /any/ solution involving lxml (or cElementTree) will do just fine for you. > I wonder whether for loop will cause a problem in iterating for 288328 > times. You are heavily underestimating the power of the Python here. Stefan From paul at boddie.org.uk Mon Jul 28 11:51:04 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 28 Jul 2008 08:51:04 -0700 (PDT) Subject: xml.dom's weirdness? References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> <488C3645.8060304@behnel.de> <488c75ee$0$29448$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <913ac597-6be3-4394-b3a6-79a2ac06d3c3@34g2000hsf.googlegroups.com> On 28 Jul, 16:15, Sion Arrowsmith wrote: > Stefan Behnel wrote: > >Blame Ubuntu/Debian. > > I'd be wary about including Debian in that blame. Using 4.0 here, > with a 2.4.4 default and a 2.5.0 straight from the package: [...] I can imagine that some of the Python Eggs magic could quite easily inflate the number of files opened when doing imports. Information on things like the state of site-packages, .pth files, the length of PYTHONPATH and so on should surely accompany the numbers before fingers are pointed. Paul From enleverlesX.XmcX at XmclaveauX.com Tue Jul 29 07:19:47 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Tue, 29 Jul 2008 13:19:47 +0200 Subject: Python COM In-Reply-To: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> References: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> Message-ID: <488eff34$0$869$ba4acef3@news.orange.fr> Hi! Example, with Pywin32: import win32com.client moncom = win32com.client.Dispatch('MyCOM1.AdvMethod') moncom.IAdvMethod(... See Pywin32 here: http://sourceforge.net/projects/pywin32/ @-salutations Michel Claveau From hobesh at gmail.com Mon Jul 28 16:41:31 2008 From: hobesh at gmail.com (Zach Hobesh) Date: Mon, 28 Jul 2008 13:41:31 -0700 Subject: Running python scripts in a VB program Message-ID: Does anyone have any clue on how to embed python scripts in a visual basic windows app? Additionally, does anybody else feel like Visual Basic is ridiculously confusing? Any help is appreciated. Thanks, -Zach -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Sun Jul 20 20:11:34 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 20 Jul 2008 17:11:34 -0700 (PDT) Subject: Python Written in C? References: Message-ID: On Jul 20, 5:50?pm, giveitawhril2... at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. Python is for people who want to program, not REAL WORLD programmers. > > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language C isn't a high level language, that's part of its problem. > which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > > I'm not dissing Python, here. Yes, you are. > Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. Then go learn C, nobody's stopping you. From Vern.Muhr at gmail.com Mon Jul 28 18:58:38 2008 From: Vern.Muhr at gmail.com (VernM) Date: Mon, 28 Jul 2008 15:58:38 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <8287c9c5-d6bb-4f67-9dec-00bc59bcb546@q28g2000prh.googlegroups.com> On Jul 20, 3:50?pm, giveitawhril2... at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. Thank you giveitawhril2...!! I haven't had so much fun reading a thead in years. Hilarious!!!! From steve at holdenweb.com Tue Jul 29 11:32:26 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 29 Jul 2008 11:32:26 -0400 Subject: Public Pythn Classs, September 9, 2008 Message-ID: <488F380A.4070105@holdenweb.com> Holden Web is please to announce its third public "Introduction to Python" class, near Washington DC, from September 9-11. Further details are available from http://holdenweb.com/py/training/ We are also interested in adding to our course repertoire. If you have ideas for suitable one-day classes please visit http://holdenweb.blogspot.com/2008/07/one-day-python-classes.html and leave a comment on that page. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From ldo at geek-central.gen.new_zealand Mon Jul 28 02:55:56 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 28 Jul 2008 18:55:56 +1200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> <6385b0a8-f7f3-4dc3-91be-e6f158ffb439@a1g2000hsb.googlegroups.com> Message-ID: In message , s0suk3 at gmail.com wrote: > On Jul 27, 10:55 pm, Lawrence D'Oliveiro central.gen.new_zealand> wrote: >> In message >> <6385b0a8-f7f3-4dc3-91be-e6f158ffb... at a1g2000hsb.googlegroups.com>, >> >> >> >> s0s... at gmail.com wrote: >> > On Jul 26, 6:47 pm, Lawrence D'Oliveiro > > central.gen.new_zealand> wrote: >> >> In message >> >> <024ace13-f72f-4093-bcc9-f8a339c32... at v1g2000pra.googlegroups.com>, >> >> >> s0s... at gmail.com wrote: >> >> > On Jul 24, 5:01 am, Lawrence D'Oliveiro > >> > central.gen.new_zealand> wrote: >> >> >> >> In message >> >> >> <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, >> >> >> Jordan wrote: >> >> >> >> > Except when it comes to Classes. I added some classes to code >> >> >> > that had previously just been functions, and you know what I did >> >> >> > - or rather, forgot to do? Put in the 'self'. In front of some of >> >> >> > the variable accesses, but more noticably, at the start of *every >> >> >> > single method argument list.* >> >> >> >> The reason is quite simple. Python is not truly an >> >> >> "object-oriented" language. It's sufficiently close to fool those >> >> >> accustomed to OO ways of doing things, but it doesn't force you to >> >> >> do things that way. You still have the choice. An implicit "self" >> >> >> would take away that choice. >> >> >> > By that logic, C++ is not OO. >> >> >> Yes it is, because it has "this". >> >> > You mean the keyword "this"? It's just a feature. How does that make a >> > difference on being or not being OO? >> >> Because it was one of the things the OP was complaining about (see >> above). > > Wrong. Reread what the OP said. From crazychimp132 at gmail.com Mon Jul 14 19:24:27 2008 From: crazychimp132 at gmail.com (crazychimp132 at gmail.com) Date: Mon, 14 Jul 2008 16:24:27 -0700 (PDT) Subject: Method behavior for user-created class instances Message-ID: <42433fcd-fcdc-4f42-a427-c28241734b7c@z66g2000hsc.googlegroups.com> Greetings. I am looking for a way to achieve method behavior for a class I created. That is, it has a __call__ method, so can be called like a function. But I also want it to be treated as a method when it appears in a class body. Eg. class foo: def __call__(self, inst): pass class bar: meth = foo() such that bar().meth() will not raise an exception for too few arguments (because the inst argument in foo.__call__ is implicitly set to the bar instance). I know this has to do with writing the __get__ method of foo, but I am wondering if there is perhaps some class I can just inherit from to get the proper __get__, which behaves identically to that of regular Python functions. The need for this arises out of the implementation of a function decorator as a class. Thanks. From larry.bates at websafe.com` Mon Jul 14 00:29:41 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 13 Jul 2008 23:29:41 -0500 Subject: About wmi In-Reply-To: <51cb0fe0-58f2-4f56-a59e-59986177f3d5@c65g2000hsa.googlegroups.com> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <51cb0fe0-58f2-4f56-a59e-59986177f3d5@c65g2000hsa.googlegroups.com> Message-ID: patrol wrote: > On 7?13?, ??10?26?, Larry Bates wrote: >> patrol wrote: >>> I want to prevent some process from running. The code is in the >>> following. I encounter some unexpected troubles. >>> Probelm1: This program cannot terminate "scrcons.exe" and >>> "FNPLicensingService.exe",which are system processes. >>> Problem2:After a while, this program will abort by error >>> File "C:\Python25\lib\wmi.py", line 397, in __call__ >>> handle_com_error (error_info) >>> File "C:\Python25\lib\wmi.py", line 190, in handle_com_error raise >>> x_wmi, "\n".join (exception_string) >>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position >>> 14: ordinal not in range(128) >>> ---------------------------------------------------- >>> code----------------------------------------------------------------------------------- >>> # -*- coding:utf-8 -*- >>> import pythoncom >>> import wmi >>> import threading >>> import time >>> from xml.dom.minidom import parse, parseString >>> class Info (threading.Thread): >>> def __init__ (self): >>> threading.Thread.__init__ (self) >>> def run (self): >>> print 'In Another Thread...' >>> pythoncom.CoInitialize () >>> dom1 = parse('processTerminateList.xml') >>> config_element = dom1.getElementsByTagName("processTerminateList") >>> [0] >>> servers = config_element.getElementsByTagName("processName") >>> try: >>> c = wmi.WMI () >>> for process in c.Win32_Process (): >>> for server in servers: >>> if process.name == getText(server.childNodes): >>> process.Terminate() >>> print process.name >>> process_watcher = c.Win32_Process.watch_for("creation") >>> while True: >>> new_process = process_watcher() >>> name = new_process.Caption >>> print name >>> for server in servers: >>> if name == getText(server.childNodes): >>> new_process.Terminate() >>> finally: >>> pythoncom.CoUninitialize () >>> def getText(nodelist): >>> rc = "" >>> for node in nodelist: >>> if node.nodeType == node.TEXT_NODE: >>> rc = rc + node.data >>> return rc >>> if __name__ == '__main__': >>> Info().start() >>> ------------------------------------------------------ >>> processTerminateList.xml------------------------------------------------------------------------ >>> >>> >>> scrcons.exe >>> TXPlatform.exe >>> mdm.exe >>> FNPLicensingService.exe >>> notepad.exe >>> uedit32.exe >>> >> You should probably post this to comp.python.windows. Tim Golden (author of WMI >> interface) monitors that list religously (thanks Tim). >> >> -Larry- ??????? - >> >> - ??????? - > > I cannot find comp.python.windows.What's the URL? http://news.gmane.org/gmane.comp.python.windows/cutoff=7565 -Larry From malaclypse2 at gmail.com Wed Jul 9 15:33:50 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 9 Jul 2008 15:33:50 -0400 Subject: formatting list -> comma separated In-Reply-To: <48750e4f$0$15106$e4fe514c@dreader27.news.xs4all.nl> References: <48750e4f$0$15106$e4fe514c@dreader27.news.xs4all.nl> Message-ID: <16651e80807091233p3d297d80p93a1e45d17fb23e9@mail.gmail.com> On Wed, Jul 9, 2008 at 3:23 PM, Robert wrote: > given d: > d = ["soep", "reeds", "ook"] > > I want it to print like > soep, reeds, ook use the join() method of strings, like this: >>> d = ["soep", "reeds", "ook"] >>> ', '.join(d) 'soep, reeds, ook' >>> d = [] >>> ', '.join(d) '' >>> -- Jerry From lanny at freshells.ch Thu Jul 24 11:24:38 2008 From: lanny at freshells.ch (Lanny) Date: Thu, 24 Jul 2008 08:24:38 -0700 Subject: Raw Strings (I Think) References: Message-ID: > No, it doesn't. Instead of guessing what the cause might be, please show > us your code and show us the error message you're getting, so that we can > determine what the cause really is. Ok, sorry. Heres my code: import glob import random import os songs = glob.glob('C:\###\###\###\*.mp3') pick = random.choice(songs) os.system(pick) And yes, I know there are better ways of randomly selecting a .mp3 file to play but I don't care. -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- From deets at nospam.web.de Mon Jul 7 07:53:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 07 Jul 2008 13:53:31 +0200 Subject: Is there a good way to implement file updating? such as lock, update, reload... References: <2ebcf7f9-a8d9-403f-a05a-f26a9ca420b0@x41g2000hsb.googlegroups.com> Message-ID: <6deef6F271g5U1@mid.uni-berlin.de> Evan wrote: > Hello - > > My script use a DB file which is written by XML, and the user load > this DB file (XML tree in memory), and then do some updating about > this tree, such as delete element, generate new element or move > element. > > The thing is, my script is a cmd based program (based on module > "cmd"), and there are many users would use this script at same time, > in a shell style prompt (module "cmd"), so I want to implement a > updating after a user update the XML tree, it such as a "signal > console", so that all the user can keep same DB, or other user can > see update a few seconds later. > > What I did is, create a new file calling "db_change", and put a number > "1" in file, and then update the real "DB" file (by change uid to lock > file), other user to check this file and then re-load XML file, but I > do not think it is a good idea, the performance is not good. > > I would like to know if you could help on this matter, I hope I can > get inspiration/example from you guys. Start using a proper database. And get rid of the XML. If you need it for output/exchange purposes, generate it from the DB. Diez From kalaiarasanq at gmail.com Wed Jul 2 11:36:33 2008 From: kalaiarasanq at gmail.com (kali) Date: Wed, 2 Jul 2008 08:36:33 -0700 (PDT) Subject: Woman on Top Sex Position - The Sexiest Mattress Move ... Message-ID: <940ba25c-297e-4e68-8fc5-fee646b708b4@s33g2000pri.googlegroups.com> Woman on Top Sex Position - The Sexiest Mattress Move ... Top 10 Sex Stories of 2006 For your end-of-the-year sexual entertainment, my picks for the Top 10 Sex Stories of 2006:. 10. The Larry Wachowski Story ... click him in poen viset. ************************************* htt://mountanbikes.blogspot.com/ ************************************* From hubaghdadi at gmail.com Mon Jul 28 10:03:48 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Mon, 28 Jul 2008 07:03:48 -0700 (PDT) Subject: Module clarification References: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> <896c547e-9fa1-4f84-8c9b-53a96e70246c@y21g2000hsf.googlegroups.com> <00c033b9-1b5a-4165-abec-4ff6119298a5@z66g2000hsc.googlegroups.com> Message-ID: On Jul 28, 8:11 am, Duncan Booth wrote: > Hussein B wrote: > > If I have a couple of modules, is there a way to package them? or > > there is no such a thing in Python? > > It sounds rather as though you haven't yet gone through the Python > tutorial. You really should read it, even if you just skim through it to > see what topics are covered. The tutorial explains both modules and > packages:http://docs.python.org/tut/node8.html > > What it doesn't cover is that you can import modules or packages directly > from a zip file. > > Then read about eggs. > > -- > Duncan Boothhttp://kupuguy.blogspot.com I'm reading "Learning Python, 3rd Edition" What do you think about it? From nodrogbrown at gmail.com Fri Jul 4 04:15:30 2008 From: nodrogbrown at gmail.com (gordon) Date: Fri, 4 Jul 2008 01:15:30 -0700 (PDT) Subject: compatible image type Message-ID: hi in my application a file selection by user returns a pathname string like F:/images/png/my.png or F:/docs/text/somedoc.txt ....etc. I can get the extension using extn=string.split(os.path.basename(pathname),'.' )[1] then later on i want to create a Photoimage using ImageTk.PhotoImage(file=pathname) and display it on a canvas. the extn can be anything ..even zip or bat ,doc whatever depending on user selection...I want to put someway to raise an error message to the user if he selects a file with extension not of a compatible image type for PhotoImage.How should i do this? should i check 'extn' to a list of compatible image type extensions(something like [''jpg','jpeg','png','gif'...] ) or is there a better way? gordon From comp.ogz at gmail.com Tue Jul 8 01:10:28 2008 From: comp.ogz at gmail.com (Oguz Yarimtepe) Date: Tue, 8 Jul 2008 08:10:28 +0300 Subject: Tk overrideredirect problem Message-ID: <20831c740807072210m3c3e66c0j42f7e9bbd87f70fc@mail.gmail.com> Hi, At my GUI application i am catching a key press action. The code is working if i don't enable the overrideredirect. When i comment out the overriderect part i can see the picture but i am not able to catch the key presses. It seems like the GUI is stucked. But i want to have windowless appereance that is just the picture itself. Also a working application that will catch my key presses. So how can i fix it? Here is the code part related with my question: from Tkinter import * from Xlib import * import Image #PIL import ImageTk #PIL self.root = Tk() #self.root.overrideredirect(1) self.root.title("Status") self.root.bind('', self.action) dsp = display.Display() self.screen = dsp.screen().root self.screen.grab_key(self.actionkey, X.AnyModifier, 1,X.GrabModeAsync, X.GrabModeAsync) # we tell the X server we want to catch keyPress event self.screen.change_attributes(event_mask = X.KeyPressMask) def action(self,event): #print event.keycode if event.keycode == self.actionkey: self.showImage() def showImage(self,imageName="w_on_b_on.jpg"): print imageName im = Image.open(imageName) xlocation = 440 ylocation = 640 width = im.size[0]+20 height = im.size[1]+20 newgeometry = str(width)+"x"+str(height)+"+"+str(xlocation)+"+"+str(ylocation) self.root.geometry(newgeometry) self.root.protocol('WM_DELETE_WINDOW', self.doExit) # add 20 to account for border defined in create_image self.canvas = Canvas(self.root, height=im.size[1]+20, width=im.size[0]+20) self.canvas.pack(side=LEFT,fill=BOTH,expand=1) photo = ImageTk.PhotoImage(im) item = self.canvas.create_image(10,10,anchor=NW, image=photo) self.counter += 1 #self.canvas.update() mainloop() I didn't check the code below, the whole working one is here: http://rafb.net/p/SvqqjH64.html I pasted it to give an idea. -- O?uz Yar?mtepe From __peter__ at web.de Sat Jul 5 02:06:26 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 05 Jul 2008 08:06:26 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: Filipe Fernandes wrote: > but why would you say this particular > regex isn't common enough in real code? As Carl says, it's not just the regex, it's the the combination with a long line that exposes the re library's weakness. Peter From animator333 at gmail.com Fri Jul 18 06:56:11 2008 From: animator333 at gmail.com (King) Date: Fri, 18 Jul 2008 03:56:11 -0700 (PDT) Subject: sub typing built in type with common attributes. Am I right? References: <4d9c4b74-9c28-4b98-afe7-9eb774655c3a@v21g2000pro.googlegroups.com> <98c3de7d-f167-48f9-9736-b09938d96b92@f40g2000pri.googlegroups.com> Message-ID: <6849e509-9132-4628-8cbb-af818e5b6762@q28g2000prh.googlegroups.com> Thanks Michaud, You have actually solved an another problem by 'make_subtype_with_attr' function. What actually I am trying to do here is to create custom types using built in types to use in my application. For example , float2, float3, color, vector, point, normal, matrix etc. The reason being creating as individual subtypes is because each subtypes has it's own set of functions as well as common functions and attributes defined in 'Attribute' class. Although I won't be doing any math using subtypes like multiply a color by another color or add a float and a color. One of the important function that every subtype has is to print itself in a special format. For 'color' it would be : 'type' + 'name' + ' = color('+color[0]+', '+color[2]+', '+color[2]+');' Result: color myColor = color(0.5, 0.1, 1.0); I hope this will make things more clearer. If you do have any suggestions then please send it across. Prashant From ldo at geek-central.gen.new_zealand Fri Jul 25 00:32:59 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 25 Jul 2008 16:32:59 +1200 Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: In message , Matimus wrote: > On Jul 24, 2:54?am, Lawrence D'Oliveiro central.gen.new_zealand> wrote: >> In message >> , >> >> Matimus wrote: >> > That isn't the standard. With that setup tabs will show up as 4 >> > spaces, and still confuse you. >> >> Why should that be confusing? The most common tab-stop setting is 4 >> columns. > > A tab character is specified as 8 spaces. Specified by whom? The most common setting these days is 4 columns. From ptmcg at austin.rr.com Sun Jul 20 01:42:04 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 19 Jul 2008 22:42:04 -0700 (PDT) Subject: MethodChain References: <6eej10F6k7g3U2@mid.uni-berlin.de> <342b5431-5ead-4827-8bdd-ab2cd50c2acc@i76g2000hsf.googlegroups.com> <6efv5cF6uhc3U1@mid.uni-berlin.de> Message-ID: On Jul 20, 12:01?am, Marc 'BlackJack' Rintsch wrote: > The methods are a problem IMHO. ?You can't add an own method/function with > the name `fire()` or `toFunction()`. ?`MethodChain` has to know all > functions/methods in advance. ?You can add the methods of whole classes at > once and there are over 300 pre-added, this begs for name clashes. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch If you shift the syntax just a bit, instead of writing a.b.c, pass a, b, and c as the args to a MethodChain object. Here's a rough stab at the problem: class MethodChain(object): def __init__(self, *fns): self.fns = fns[:] def __call__(self,*args): if self.fns: for f in self.fns: args = (f(*args),) return args[0] def dncase(s): return s.lower() def upcase(s): return s.upper() def stripVowels(s): return "".join( c for c in s if c not in "aeiou" ) def selectItems(items,s): return "".join(c for i,c in enumerate(s) if i in items) from functools import partial chn = MethodChain( dncase, stripVowels, upcase, partial(selectItems,(0,2)) ) print chn("FoO Bar") -- Paul From alexnbryan at gmail.com Sat Jul 12 19:01:00 2008 From: alexnbryan at gmail.com (Alexnb) Date: Sat, 12 Jul 2008 16:01:00 -0700 (PDT) Subject: like py2exe, but on a mac In-Reply-To: References: <18424336.post@talk.nabble.com> Message-ID: <18424499.post@talk.nabble.com> Python.Arno wrote: > > > On 13 jul 2008, at 00:39, Alexnb wrote: > >> >> Hi All >> >> I am wondering what I can do to turn a python app (.py) into a mac OSX >> applicaiton (.app). Just like py2exe does. > > i use these: > http://undefined.org/python/py2app.html > http://effbot.org/pyfaq/how-do-i-create-a-pyc-file.htm > >> But I am also wondering since in >> your applications folder on macs it usually doesn't have an actual >> folder >> for each app. Rather an icon. so for firefox, you just see the icon. >> Unlike >> windows where you have a folder with everything, and the actual >> program is >> in it. where is all the application info stored? just in the .app? > > apps on OSX are also folder, yet with the reserved .app extension > the OS then presents this as an app (right click on an app and choose > 'Show package content') > > py2app creates all that for you > > >> Finally >> whether or not there is an app like py2exe for mac, is there a way >> to skip >> the middle man and turn it straight into a .dmg with the app inside? >> -- > > a dmg is a disk image, similar to iso on windows > you can create an empty one with Disk Utility then drop everything in > it's NOT an installer > >> > cheers > Arno > -- > http://mail.python.org/mailman/listinfo/python-list > > Okay, well thank you very much for your help you answered all my questions :) -- View this message in context: http://www.nabble.com/like-py2exe%2C-but-on-a-mac-tp18424336p18424499.html Sent from the Python - python-list mailing list archive at Nabble.com. From moijes12 at gmail.com Mon Jul 14 00:03:08 2008 From: moijes12 at gmail.com (moijes12) Date: Sun, 13 Jul 2008 21:03:08 -0700 (PDT) Subject: importing from .pyd Message-ID: <3d66daeb-d45a-46be-bd4d-34a2225683d1@2g2000hsn.googlegroups.com> hi there is a .pyd file present in the same folder as the script abc.py by the name foo.pyd .I don't have foo.py .In the script abc.py I try import foo Error i get is ImportError: DLL load failed: The specified module could not be found. I have tried placing .pyd under C:\python25\DLLs but it didn't work.I have also given the path for foo.pyd in PYTHONPATH.but i still recieve the same error. Please suggest a solution moijes12 From kyosohma at gmail.com Thu Jul 3 14:37:52 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 3 Jul 2008 11:37:52 -0700 (PDT) Subject: manipulating movie files with Python References: Message-ID: <61fdcc89-8c1b-4446-8c1b-3a68f1a86689@2g2000hsn.googlegroups.com> On Jul 3, 12:15?pm, Tim Grove wrote: > I would like to write a python script which could take a movie file name > (avi, mov, mpg) along with a start and stop time as parameters, and > return to me a ?new movie file just containing that section of the > original which I'm interested in. Is there a Python library which could > already perform such magic? Thanks for any suggestions. > > Best regards, > Tim You might check these out: http://pymedia.org/ http://www.unixuser.org/~euske/vnc2swf/pyvnc2swf.html Mike From cokofreedom at gmail.com Fri Jul 25 04:38:30 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Fri, 25 Jul 2008 01:38:30 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> Message-ID: <5d3729f0-6e5d-4e3f-b4ed-e25f8ebc655f@q5g2000prf.googlegroups.com> > > By that logic, C++ is not OO. By that logic, Ruby is not OO. By that > logic, I know of only one OO language: Java :) > > The fact that a language doesn't force you to do object-oriented > programming doesn't mean that it's not object-oriented. In other > words, your words are nonsense. > No, what it means is that it might support OO but doesn't have to, it isn't the only way to code. Supporting and Being OO are very different. From akineko at gmail.com Sat Jul 5 08:11:48 2008 From: akineko at gmail.com (akineko) Date: Sat, 5 Jul 2008 05:11:48 -0700 (PDT) Subject: Python XML-RPC Server with clientside Javascript References: Message-ID: <7d589fd8-2877-4427-84a6-d5e999172305@d77g2000hsb.googlegroups.com> Hello Paul, Thank you very much for your prompt and clear answer. I didn't know the "same origin" javascript security policy (as I'm not familiar with javascript). After reading the description of the "same origin" javascript policy, I think you are absolutely correct. The security policy does make sense. However, if that is the case, it seems I have only two options to make my project work: (1) Place my XML-CGI services under a web server so that both HTML page and RPC services are coming from the same origin (2) Expand Python DocXMLRPCServer, which renders a HTML page, to implement my own HTML page from it I wanted to run the program as a standalone one (no external web server required). Therefore, (2) seems the only option I have to make it work. Anyway, thank you for solving my days-long question. Best regards, Aki Niimura On Jul 5, 3:39 am, paul wrote: > > I'd think this has nothing to do with CGI vs. "free-standing", the > client couldn't tell the difference anyway. > It looks like you're running in the "same origin" javascript security > restriction enforced by the browser. That is, the origin of your > javascript is file://... and you're trying to accesshttp://localhost:8765. This is not allowed. > > hth > Paul From grante at visi.com Tue Jul 15 15:05:11 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 15 Jul 2008 14:05:11 -0500 Subject: Testing for Internet Connection References: <18460572.post@talk.nabble.com> <1216113021.24038.0@proxy02.news.clara.net> Message-ID: On 2008-07-15, norseman wrote: > Process: > copy/paste into afile > slide lines left to create proper indent values > save > python afile > > I get same as Grant > > > If one does a copy/paste into interactive Python, it does fail. > (Lots of indent error messages. After all, it is Python :) I'm always a bit conflicted about how to post code snippets. IMO, the posting is a lot more readable if the code is indented to offset it from the prose, but it does make more work for anybody who wants to run the example. -- Grant Edwards grante Yow! Did I SELL OUT yet?? at visi.com From bignose+hates-spam at benfinney.id.au Wed Jul 16 04:47:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 16 Jul 2008 18:47:38 +1000 Subject: How can i use a variable without define it ? References: Message-ID: <87k5fm2p1x.fsf@benfinney.id.au> zhw writes: > How can i use a variable without define it ? What do you mean by "use"? That's so vague I can think of many possible interpretations. What do you mean by "variable"? That term carries a lot of baggage that doesn't apply in Python. Can you give a small, complete example that demonstrates the issue you're trying to solve? -- \ ?The face of a child can say it all, especially the mouth part | `\ of the face.? ?Jack Handey | _o__) | Ben Finney From stanc at al.com.au Mon Jul 7 00:12:48 2008 From: stanc at al.com.au (Astan Chee) Date: Mon, 07 Jul 2008 14:12:48 +1000 Subject: VNC capture in python Message-ID: <487197C0.1090006@al.com.au> Hi, I was wondering if I can do a capture of a VNC screen in python. Kinda like this http://search.cpan.org/~lbrocard/Net-VNC-0.35/lib/Net/VNC.pm but without opening a VNC window or doing a screen capture. Thanks for any suggestions -- "Formulations of number theory: Complete, Consistent, Non-trivial. Choose two." Animal Logic http://www.animallogic.com Please think of the environment before printing this email. This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. From pavlovevidence at gmail.com Thu Jul 31 23:44:20 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 31 Jul 2008 20:44:20 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> Message-ID: <5a0b303a-8324-4eeb-a975-397371bf2875@b1g2000hsg.googlegroups.com> On Jul 31, 12:13 am, Ethan Furman wrote: > Carl Banks wrote: > > So I stand by the point I was trying to make: for your average day-to- > > day programming, the main benefit of "if x" is to save keystrokes. It > > doesn't help your code become more polymophic in practice. A little > > more polymorphic, yes. A lot, no. > > Hmmm... well, I see your point. Unfortunately, even though it feels > incorrect to me, I do not (yet) have the breadth and depth of Python > experience to come up with an example that would display such exquisite > polymorphism. It also seems to me that such an example would be > non-trivial in nature. Wrong on both counts. Let me give you a hint. Take integers and lists. Count how many methods the two types have in common. By my reckoning, they are: __add__, __iadd__, __mul__, _imul__, __str__, __repr__, and __nonzero__. Also there are __getattribute__ and __setattr__, but lists and ints share no common attributes. I don't think ints have any at all aside from the special methods. What this means is: any code that can work for both ints and lists must use only these methods (this is not quite correct, but mostly is). That eliminates probably 99.9% of code right off the bat. Then you have to consider that some code that does use only these attributes does something useful only for either ints or lists, not both. Take this simple example: def foil(a,b,c,d): return a*b + a*d + b*c + b*d This code works if a and c are both ints, or are both lists (while b and d would have to be ints). It does something useful for ints and other numeric types, but does it do anything useful for lists? Third, there are cases where you have code that works for both ints and lists, that does do something useful for both, but it makes no sense to apply "if x" to it. def print_if_true(x): if x: print x This little piece of code might actually come in handy here and there, but would it end up being used for numeric types a whole lot? It seems like if you have an empty list you might reasonably want to print nothing at all, but when you have a zero integer you usually want to print the zero. (However, you might reasonably want to print some object unless it's None. You could then use this one function to handle that case as well as the case with empty lists, instead of defining two functions, like so: print_if_not_empty(x): if len(x)!=0: print x print_if_not_None(x): if x is not None: print x But wait! What if you had a value that could be either an integer or None? You can't use the "if x" variant because x could be False. So you'd have to define the "if x is not None" variant anyway. I might use the "if x" variant in throwaway scripts, but for anything production I would prefer the explicit variants, partially because, as shown above, even when "if x" does rear it's polymoprhic head, it doesn't necessarily buy you much. Nevertheless, I think this is probably the best example of the enhanced polymorphism of "if x" yet. I'm kind of surprised no one came up with it.) In general, the ability to take advantage of "if x" polymorphism across numeric, container, and other types depends on the something/ nothing dichotomy to be applicable. Something versus nothing is a useless concept most of the time, but occasionally finds use in human interaction cases such as printing. So there you have it. This is why I didn't expect anyone to come up with a good example: you just don't have a lot to work with. Carl Banks From tjreedy at udel.edu Tue Jul 29 15:11:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 15:11:53 -0400 Subject: block/lambda In-Reply-To: References: <0406eb4f-8dec-4ce2-b506-8e597de2958d@56g2000hsm.googlegroups.com> Message-ID: iu2 wrote: > On Jul 29, 9:36 am, Duncan Booth wrote: >> Your example becomes: >> >>>>> def dotimes(n, callable): >> for i in range(n): callable(i) >> >>>>> def block(i): >> for j in range(i): >> print j, >> print >> >>>>> dotimes(5, block) >> 0 >> 0 1 >> 0 1 2 >> 0 1 2 3 >> >> The only thing you asked for that this doesn't do is make 'block' >> anonymous, but actually that is a good thing. > > Ok, I've got 2 questions about it: > > 1. Can you please explain why it is a good thing? All functions defined with lambda expressions get the pseudoname ''. All functions defined with def get the name you give it, which is typically unique within some scope. The representation of a function, whether intentionally printed or printed as part of a traceback, is more meaningful with a specific name than a general name. > 2. Will it be possible in Python 3.0 to do the following: > >>>> def dotimes(n, callable): > for i in range(n): callable() > >>>> def block(): > nonlocal i > for j in range(i): > print j, > print If you indent block so it is a nested function, yes. But the nonlocal declaration is not needed unless you rebind 'i' from within the nested function, which block does not do. tjr From bdesth.quelquechose at free.quelquepart.fr Mon Jul 28 07:17:32 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 28 Jul 2008 13:17:32 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: <488dc6c2$0$24366$426a34cc@news.free.fr> Russ P. a ?crit : > On Jul 27, 12:39 pm, Bruno Desthuilliers > wrote: >> Derek Martin a ?crit : >> >> >> >>> On Sun, Jul 27, 2008 at 08:19:17AM +0000, Steven D'Aprano wrote: >>>>> You take the name down to a single letter. As I suggested in an earlier >>>>> post on this thread, why not take it down to zero letters? >>>> The question isn't "why not", but "why". The status quo works well as it >>>> is, even if it isn't perfect. Prove that implicit self is a good idea -- >>>> or at least prove that it is an idea worth considering. >>> Come on, this sounds like a schoolyard argument. This comes down to a >>> matter of style, and as such, is impossible to prove. It's largely a >>> question of individual preference. >>> That said, the argument in favor is rather simple: >>> 1. This is an extremely common idiom in Python >>> 2. It is completely unnecessary, and the language does not suffer for >>> making it implicit >>> 3. Making it implicit reduces typing, reduces opportunities for >>> mistakes, and arguably increases consistency. >> "arguably", indeed, cf below. >> >>> As for the latter part of #3, self (or some other variable) is >>> required in the parameter list of object methods, >> It's actually the parameter list of the *function* that is used as the >> implementation of a method. Not quite the same thing. And then, >> consistency mandates that the target object of the method is part of the >> parameter list of the *function*, since that's how you make objects >> availables to a function. >> >>> however when the >>> method is *called*, it is omitted. >> Certainly not. You need to lookup the corresponding attribute *on a >> given object* to get the method. Whether you write >> >> some_object.some_method() >> >> or >> >> some_function(some_object) >> >> you still need to explicitely mention some_object. >> >>> It is implied, supplied by Python. >> Neither. The target object is passed to the function by the method >> object, which is itself returned by the __get__ method of function >> objects, which is one possible application of the more general >> descriptor protocol (the same protocol that is used for computed >> attributes). IOW, there's nothing specific to 'methods' here, just the >> use of two general features (functions and the descriptor protocol). >> FWIW, you can write your own callable, and write it so it behave just >> like a function here: >> >> import types >> >> class MyCallable(object): >> def __call__(self, obj): >> print "calling %s with %s" % (self, obj) >> def __get__(self, instance, cls): >> return types.MethodType(self.__call__, instance, cls) >> >> class Foo(object): >> bar = MyCallable() >> >> print Foo.bar >> f = Foo() >> f.bar() >> >>> Thus when an object method is called, it must be called with one fewer >>> arguments than those which are defined. This can be confusing, >>> especially to new programmers. >> This is confusing as long as you insist on saying that what you >> "def"ined is a method - which is not the case. >> >>> It can also be argued that it makes the code less ugly, though again, >>> that's a matter of preference. >>>> It's not enough to show that a change "isn't bad" -- you have to show >>>> that it is actively good. >>> But he did... he pointed out that *it saves work*, without actually >>> being bad. Benefit, without drawback. Sounds good to me! >>>> "Don't need to look at the method signature" is not an argument in favour >>>> of implicit self. >>> Yes, actually, it is. >> It isn't, since there's no "method signature" to look at !-) >> >>> If there is a well-defined feature of Python >>> which provides access to the object within itself, >> The point is that you don't get access to the object "within itself". >> You get access to an object *within a function*. >> >> The fact that a function is defined within a class statement doesn't >> imply any "magic", it just creates a function object, bind it to a name, >> and make that object an attribute of the class. You have the very same >> result by defining the function outside the class statement and binding >> it within the class statement, by defining the function outside the >> class and binding it to the class outside the class statement, by >> binding the name to a lambda within the class statement etc... >> >>> then the >>> opportunities for mistakes when someone decides to use something else >>> are lessened. >>>> You don't need to look at the method signature when you're using an >>>> explicit self either. >>> That isn't necessarily true. If you're using someone else's code, and >>> they didn't use "self" -- or worse yet, if they chose this variable's >>> name randomly throughout their classes -- then you may well need to >>> look back to see what was used. >>> It's bad programming, but the world is full of bad programmers, and we >>> don't always have the choice not to use their code. Isn't one of >>> Python's goals to minimize opportunities for bad programming? >> Nope. That's Java's goal. Python's goals are to maximize opportunities >> for good programming, which is quite different. >> >>> Providing a keyword equivalent to self and removing the need to name >>> it in object methods is one way to do that. >> It's also a way to make Python more complicated than it needs to be. At >> least with the current state, you define your functions the same way >> regardless of how they are defined, and the implementation is >> (relatively) easy to explain. Special-casing functions definition that >> happens within a class statement would only introduce a special case. >> Then you'd have to explain why you need to specify the target object in >> the function's parameters when the function is defined outside the class >> but not when it's defined within the class. >> >> IOW : there's one arguably good reason to drop the target object from >> functions used as methods implementation, which is to make Python looks >> more like Java, and there's at least two good reason to keep it the way >> it is, which are simplicity (no special case) and consistency (no >> special case). >> >> Anyway, the BDFL has the final word, and it looks like he's not going to >> change anything here - but anyone is free to propose a PEP, isn't it ? > > The issue here has nothing to do with the inner workings of the Python > interpreter. Oh yes, really ??? > The issue is whether an arbitrary name such as "self" > needs to be supplied by the programmer. > > Neither I nor the person to whom you replied to here (as far as I can > tell) is suggesting that Python adopt the syntax of Java or C++, in > which member data or functions can be accessed the same as local > variables. Any suggestion otherwise is a red herring. I didn't talk about the implicit self/this reference in methods, but about java/C++/PHP/etc method signatures vs python's *functions* signature. > All I am suggesting is that the programmer have the option of > replacing "self.member" with simply ".member", since the word "self" > is arbitrary and unnecessary. It is arbitrary, indeed. And FWIW, you can use any other (legal) arbitrary identifier you like. But if you still assert it is unnecessary, then either you didn't read the above explanation of how and why the whole thing works in Python, or you didn't understand it. > Otherwise, everything would work > *EXACTLY* the same as it does now. This would be a shallow syntactical > change with no effect on the inner workings of Python, but it could > significantly unclutter code in many instances. > > The fact that you seem to think it would change the inner functioning > of Python just shows that you don't understand the proposal. The fact that you seem to think it would *not* change the inner working of Python just shows that you don't understand how Python works. We're not going very far with such arguments. Sorry but I perfectly understood the proposition, and explained why this would require changes to how Python actually implements methods. From omer at no-log.org Wed Jul 2 08:15:38 2008 From: omer at no-log.org (=?utf-8?q?C=C3=A9dric_Lucantis?=) Date: Wed, 2 Jul 2008 14:15:38 +0200 Subject: How to modify the data in a binary file? In-Reply-To: <21563db10807020505p11561ce2k31d36f2731342c78@mail.gmail.com> References: <21563db10807020505p11561ce2k31d36f2731342c78@mail.gmail.com> Message-ID: <200807021415.38666.omer@no-log.org> Le Wednesday 02 July 2008 14:05:39 Jim Brown, vous avez ?crit?: > Hi all, I'm a Python newbie, so please pardon me if my question may look a > little silly. :) > > I want to modify a binary file p.data (which has some C-style "short" > integers -- 16-bit integers) in such a way: > The bit m and bit n of every "short int" si in the file are set to 1, and > the left bits in si are not affected. > > I.e, for the first short int in the file, I think the code would be: > > import os > f = os.open("/root/p.data", os.O_RDWR) > str = os.read(f, 2) > > #assume the short int in str is 0x0102, and I want to change it to 0x8182 > (changing bit7 and bit15 to 1). > #how to change the str into a short int variable si?? > ??? > > si = (si & ~0x8080) | 0x8080 > You can either do it by hand by splitting your string in chars and getting the bytes values with ord (described here: http://docs.python.org/lib/built-in-funcs.html) : byte0 = ord(s[0]) byte1 = ord(s[1]) si = (byte0 << 8) | byte1 # or maybe the inverse ? or use the struct module: http://docs.python.org/lib/module-struct.html -- C?dric Lucantis From norseman at hughes.net Wed Jul 23 21:40:53 2008 From: norseman at hughes.net (norseman) Date: Wed, 23 Jul 2008 18:40:53 -0700 Subject: Broken examples Message-ID: <4887DDA5.1010707@hughes.net> I'm only talking about IPC related. I have googled, yahooed, and so forth for several months now. ALL examples I've come across have failed including those pertinent in the Python doc area. Outline: cd somedir ls -1 *.xls >thislist #ls hyphen one python process.py (yes - ls can go here if wanted. easier to edit outside) open thislist loop until done start excel (or scalc) have it open file have it save file as a .csv (or .dbf) close excell (or scalc) Would seem to be a trivial exercise. Starting Excel or any other executable in system path works fine. popen3 opens whatever and reports no errors. r,w,and e all check as being created. r,w,e= os.popen3('ls -l') print r.read() # works as expected ALL attempts to send instructions to Excel or scalc FAIL COMPLETELY. Actually, any attempt to communicate with a 'Point'n'Click' program fails without errors being cited. They don't use redirectable command line interfaces (like piping between programs) do they? :) Trying to use the examples I have found that supposedly setup IPC's of one type or another have all failed with errors that point to things that make no sense in the first place. Before you post a code example or a link to one be kind enough to run it yourself first. You may get a surprise. The OOo examples do not work. Not even when switching my system to their version. One problem they have is asking a general user to change to places the user has no place being and then to work there without permissions. I guess somebody insists on doing all their work with root clearance down in the middle of the vendor's tree. I don't think that's a healthy way to do things, do you? In OOo in particular, using their version of VBA one can create the macro and even port it to python. If one found the correct Microsoft suite docs I suspect that same could be done there too. But that doesn't activate it from a python control. As for setting the macro to run at startup, well... maybe I had other uses in mind today???? Besides the moment I change it, coworker in other room is going to decide to... :) Let's stick to Microsoft Office and OpenSource products for now. My final goal will require specific conversations with a commercial vendor. I would like those spread sheets working though. Thanks Steve norseman at hughes.net From naude.jaco at gmail.com Wed Jul 23 05:58:42 2008 From: naude.jaco at gmail.com (Jaco Naude) Date: Wed, 23 Jul 2008 02:58:42 -0700 (PDT) Subject: Undefined calling conventions in Python.h References: Message-ID: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> On Jul 23, 9:59?am, Fredrik Lundh wrote: > Jaco Naude wrote: > > 1>application.obj : error LNK2031: unable to generate p/invoke for > > "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@$$J0YMXH at Z); > > calling convention missing in metadata > > 1>frmPythonInterface.obj : error LNK2031: unable to generate p/invoke > > for "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@$$J0YMXH at Z); > > calling convention missing in metadata > > > I'm probably missing something but I can't find any calling convention > > details in Python.h or the other headers included in this file. > > the precence of name mangling indicates that your compiler doesn't > understand that Python's a C library, and therefore uses C calling > conventions. ?have you managed to override the defaults in some odd > way? > > good point. I agree that the problem is probably due to name mangling. I'm not sure how its possible to tell the application that the DLL is a C dll? I've looked at the DLL using Dependency Walker and the functions in the DLL are clean (Thus no name mangling used). How do I tell Visual C++ that the DLL is a C dll? I thought it should be in Python.h but this line appears at the top of the file: /* Since this is a "meta-include" file, no #ifdef __cplusplus / extern "C" { */ Thanks for the help Jaco From dariusz.malec at gmail.com Thu Jul 24 15:26:42 2008 From: dariusz.malec at gmail.com (Dariusz Malec) Date: Thu, 24 Jul 2008 21:26:42 +0200 Subject: curses problem Message-ID: Hi, I'm very new to python and to curses but i guess someone can help me understand the problem: I wrote a little application (attachment) and the problem is when I resize the terminal the sub-window (log window) gets wrong size (rows) and when restoring previous terminal size the window row size does not change at all. Is there some kind of method to set directly window size in python curses? I'm using mvwin() method to set the windows new position but the problem is the size. -- Dariusz Malec http://www.kos.wsiz.rzeszow.pl JID:dmalec at jabber.kos.wsiz.rzeszow.pl From robin at alldunn.com Mon Jul 21 01:44:44 2008 From: robin at alldunn.com (Robin Dunn) Date: Sun, 20 Jul 2008 22:44:44 -0700 Subject: ANNOUNCE: wxPython 2.8.8.1 Message-ID: <4884224C.8080603@alldunn.com> Announcing ---------- The 2.8.8.1 release of wxPython is now available for download at http://wxpython.org/download.php. This is a minor bugfix release with several fixes for problems discovered in the 2.8.8.0 release. Source code is available, as well as binaries for Python 2.3, 2.4 and 2.5, for Windows and Mac, as well some packages for various Linux distributions. A summary of changes is listed below and also at http://wxpython.org/recentchanges.php. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit Microsoft Windows, most Linux or other Unix-like systems using GTK2, and Mac OS X 10.3+, in most cases the native widgets are used on each platform to provide a 100% native look and feel for the application. Changes in 2.8.8.1 ------------------ wx.richtext: Added wrappers for the RichTextPrinting and RichTextPrintout classes. Make it easier to replace the check box images used in the CheckListCtrlMixin class. Fixed bug in wx.ScrolledWindow when child focus events caused unneccessary or incorrect scrolling. Fixed a bug in wx.GridBagSizer where hidden items were not ignored in part of the layout algorithm. Several other bugs also fixed. Added builds for Ubuntu Hardy (8.04) -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From Bill at SynectixLtd.com Fri Jul 4 12:00:38 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Fri, 4 Jul 2008 17:00:38 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: "Bill Davy" wrote in message news:lPmdnYSbNrM6sPPVnZ2dneKdnZydnZ2d at bt.com... > "Tim Golden" wrote in message > news:mailman.61.1215177888.20628.python-list at python.org... >> Bill Davy wrote: >>> I am trying to edit Contacts in Outlook. This is so I can transfer >>> numbers from my address book which is an Excel spreadsheet to my mobile >>> phone. I came across the following snippet of code >> >> --- hey! that looks familiar :) >> >>> which enabled me to the contacts at least list. I had to root around to >>> discover CdoDefaultFolderContacts (though it was guessable; how could I >>> enumerate win32com.client.constants?). >> >> Well that bit's easy: win32com.client.constants is a small class with >> a __dicts__ attribute (note the "s") which is a list of dictionaries, one >> per generated library. So you can do something like this: >> >> >> import win32com.client >> >> outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") >> outlook_constants = win32com.client.constants.__dicts__[0] >> >> for k, v in outlook_constants.items (): >> print k, "=>", v >> >> >> >>> I now want to work through the Contacts in Outlook patching in data from >>> my spreadsheet, and also making new contacts where there is an entry in >>> my spreadsheet which has not gone into Contacts already. >> >> OK. >> >>> Where can I find the API? >> >> I recommend: >> >> http://msdn.microsoft.com/en-us/library/ms526861.aspx >> >> and >> >> http://www.outlookcode.com/article.aspx?id=20 >> >> and >> >> http://www.cdolive.com/cdo10.htm >> >> TJG > > > Brilliant. But I was a bit disappointed by one experiment. In MSDN I > found "Exploring the Outlook Object Model". That suggested: > Outlook | Tools | Macros | VB Editor | View | Object Browser > > There I found ContactItems and reckoned I was onto a winner, but found > that a "message" from the ContactFolder might have Subject but it did not > have a FullName. Also, if Python crashed, it left Outlook complaing that > someone was accessing it but had disappeaared so Outlook has to be > restarted each time. > > But you have suggested some more things to look at so thanks. I have had > a quick look but have not so far even found "Subject" as a member/property > of a message/contact. I shall keep looking. > > Rgds, > Bill > I kept looking and thought I was saved when I found Receipe 10.16 in the Python Cookbook but .... I changed the following: self.oOutlookApp = Dispatch("Outlook.Application") #self.oOutlookApp = gencache.EnsureDispatch("Outlook.Application") Because gencache failed and I hade run makepy last week (I only get one day a week to look at this). Then the following failed because (as I found) olFolderContacts is not in any of constants' dictionaries. ofContacts = onMAPI.GetDefaultFolder(constants.olFolderContacts) So, sadly, I shall have to put this aside for another week and get on with some work. Any thoughts would be gratefully accepted. TIA, Bill From andre at descombes.info Sat Jul 19 11:54:15 2008 From: andre at descombes.info (=?ISO-8859-1?Q?Andr=E9_Michel_Descombes?=) Date: Sat, 19 Jul 2008 17:54:15 +0200 Subject: scanf in python Message-ID: Hello, I often need to parse strings which contain a mix of characters, integers and floats, the C-language scanf function is very practical for this purpose. I've been looking for such a feature and I have been quite surprised to find that it has been discussed as far back as 2001 but never implemented. The recommended approach seems to be to use split and then atoi or atof or to use regex and then atoi and atof. Both approaches seem to be a lot less natural and much more cumbersome than scanf. If python already has a % string operator that behaves like printf, why not implement either a %% or << string operator to behave like scanf, use could be like the followng: a, b, c = "%d %f %5c" %% "1 2.0 abcde" or a, b, c = "%d %f %5c" << "1 2.0 abcde" %% is closer to the % operator << seems more intuitive either of this methods seems to me much simpler than: lst = "1 2;0 abcde".split() a = int(lst[0]) b = float(lst[1]) c = lst[2] or even worse when using regular expressions to parse such simple input. I like python because it is concise and easy to read and I really think it could use such an operator. I know this has been discussed before and many times, but all previous threads I found seem to be dead and I would like to invite further investigation of this topic. Best Regards, Andr? M. Descombes -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sat Jul 26 00:27:06 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 00:27:06 -0400 Subject: print doesn't respect file inheritance? In-Reply-To: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> References: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> Message-ID: bukzor wrote: > I was trying to change the behaviour of print (tee all output to a > temp file) by inheriting from file and overwriting sys.stdout, but it > looks like print uses C-level stuff to do its writes which bypasses > the python object/inhertiance system. It looks like I need to use > composition instead of inheritance, but thought this was strange > enough to note. > > $python -V > Python 2.5 > > """A short demo script""" > class notafile(file): > def __init__(self, *args, **kwargs): > readonly = ['closed', '__class__', 'encoding', 'mode', 'name', > 'newlines', 'softspace'] > file.__init__(self, *args, **kwargs) > for attr in dir(file): > if attr in readonly: continue > setattr(self, attr, None) Drop the __init__ and give notafile a .write method. Composition version inheritance is not the the real issue. >>> class nf(object): def write(s): print(s) print(s) >>> print >>nf(), 'testing' testing testing Now change nf.write to put the copy where you want it. tjr From basti.wiesner at gmx.net Thu Jul 24 09:11:49 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Thu, 24 Jul 2008 15:11:49 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> Message-ID: Jordan : >> Fortunately, Python isn't designed according to your ideas, and won't >> change, so consider your posting a waste of time. ?If feeling like >> bringing such old "issues" up again next time, spend your time learning >> another programming language, as you would obviously not get happy with >> Python anyway ... > > OK, if that's your response, that's sad. Of course, I try to learn new > languages all the time. Python is still IMO the best. If the attitude > in the community in response to feedback/criticism has gone from > "maybe you've got a point" to "your a lunatic, we'll never change", > well, only Python will suffer in the long term. I don't really mind, what you think about my response. Python will suffer from it as little as it will suffer from your complaints: These things will not change, whatever any of us says about them. So this discussion unlikely to produce any new insight, especially because this as been discussed over and over again in the past, without any effect on Python. Let's just drop this, and if you want to complain next time, just complain about something, that is really worth being complained about, like for instance old and outdated modules in the standard library, or real showstoppers in Python (e.g. the GIL). -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From alia_khouri at yahoo.com Wed Jul 16 01:34:42 2008 From: alia_khouri at yahoo.com (Alia Khouri) Date: Tue, 15 Jul 2008 22:34:42 -0700 (PDT) Subject: snippet to update local (bazaar, mercurial, svn) versioned source Message-ID: Here's a very simple snippet I use to automatically keep my versioned sources fresh.. Posted here in case it may be of use to anybody... #!/usr/local/bin/python import os, sys src = '/Users/ak/Code/src' # utility functions join, isdir, listdir = os.path.join, os.path.isdir def run(cmd): print cmd os.system(cmd) ops = { '.bzr': ['bzr pull', 'bzr update'], '.hg': ['hg pull', 'hg update'], '.svn': ['svn update'] } for folder in os.listdir(src): target = os.path.join(src,folder) if os.path.isdir(target): internal = os.listdir(target) for f in internal: if f in ops: print os.chdir(target) cmds = ops[f] print print target, '-->', for cmd in cmds: run(cmd) From sjmachin at lexicon.net Thu Jul 24 07:12:18 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 24 Jul 2008 04:12:18 -0700 (PDT) Subject: Requires a character ... !! References: Message-ID: On Jul 24, 7:23 pm, Ulrich Eckhardt wrote: > karthikbalaguru wrote: > > [root at localhost hello]# Analyzer hello_input > > ^^^^^^^^^^^^^^ > This is often a bad idea. Anyhow, that has nothing to do with Python. > > > Loading debug info: hello_input > > Traceback (most recent call last): > > File "/usr/local/SDK/host/bin/Analyzer", line 694, in ? > > app.dbg.readObjectInfo(elf) > > File "/usr/local/SDK/host/bin/debugprocessor.py", line 427, in > > readObjectInfo > > self.privateProcessorDwarfTree.readProcessorDwarfTree(filename) > > File "/usr/local/SDK/bin/debugprocessor.py", line 314, in > > readDwarfTree > > if "DW_OP_reg" in value: > > TypeError: 'in ' requires character as left operand > > > Is this related with the version conflicts ? > > Which version conflict? Sorry, but my crystal ball is getting a new polish > today, so I can't see the actual code that causes the error. I suggest that > you reduce your code to the smallest possible piece of code that still > shows the error and post it here, otherwise nobody will be able to help > you. You don't need a crystal ball; you just need to have been reading this group/list for the last day or so --- the OP is trying to use Python 2.2 on some *.py that are obviously written for a later version, refuses to contemplate upgrading, and starts a new thread every time he gets a syntax error. From callie.m.bradley at gmail.com Thu Jul 3 14:45:30 2008 From: callie.m.bradley at gmail.com (Callie Bertsche) Date: Thu, 3 Jul 2008 11:45:30 -0700 (PDT) Subject: Write a file - beginner's question References: <486cefb7$0$6040$426a74cc@news.free.fr> Message-ID: <8d278055-29be-46f1-8a6b-044838bd4b00@p25g2000pri.googlegroups.com> I have a closely related note. How do I write to a relative path with python? Example, source = open('/../../directory/subdirectory/file.extension') What am I missing? From gcmartijn at gmail.com Sat Jul 26 08:01:29 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Sat, 26 Jul 2008 05:01:29 -0700 (PDT) Subject: re.findall(a patern,'function(dsf sdf sdf)') References: <8fc6d72a-cfc5-4e9d-af56-a009a464c6bb@27g2000hsf.googlegroups.com> Message-ID: <2dd5c418-f532-4f50-923e-057a10f01fdd@79g2000hsk.googlegroups.com> > In short, the regular expression you used doesn't seem to be an effort > to solve the problem. In other words, you haven't read the regular > expression docs:http://docs.python.org/lib/module-re.html. In other > words, it's useless to talk with you until then. > Its a combination - I don't understand english very good (yet) - For me its hard to learn the re , I will try to search again at google for examples and do some copy past things. From __peter__ at web.de Tue Jul 1 11:58:33 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Jul 2008 17:58:33 +0200 Subject: How to use gnu readline library in program? References: Message-ID: Grant Edwards wrote: > I'm trying to figure out how to use the gnu readline library so > that when my program is prompting the user for input there is > line editing and history support. > > I've read and re-read the documentation for the "readline" > module in the standard library and I still can't figure out how > to use the module or even if the module is intended to do what > I want. The example code all seems to be about on how to > modify the behavior of an interactive Python interpreter > session so you have things like auto-completion of Python > identifiers. > > What I want to do is replace sys.stdin.readline() with > something that will provide the user with line editing and > history recall. In other languages, one uses the Gnu readline > library to do that, but my reading of the Python library > documentation is that's not what the Python readline module is > for. Am I wrong? Here's a simple example: import readline for s in "alpha beta gamma".split(): readline.add_history(s) candidates = "red yellow pink blue black".split() def completer(word, index): matches = [c for c in candidates if c.startswith(word)] try: return matches[index] + " " except IndexError: pass readline.set_completer(completer) readline.parse_and_bind("tab: complete") while 1: print raw_input("$ ") You may also consider using the cmd module. Peter From bblais at bryant.edu Wed Jul 30 11:12:37 2008 From: bblais at bryant.edu (Brian Blais) Date: Wed, 30 Jul 2008 11:12:37 -0400 Subject: Pointers/References in Python? In-Reply-To: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> References: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Message-ID: <80F2428C-C66D-4D3C-9FB1-3B7432B30057@bryant.edu> On Jul 30, 2008, at 10:46 , boblatest at googlemail.com wrote: > Of course I can just build those lists naively by creating copies of > the original list and then sorting them according to my wishes. But > that would create huge memory overhead. If the list itself is not memory intensive, but only the objects, then you shouldn't have to worry. For example, In [1]:big_object=[0.0]*int(1e7) # about 40 meg In [2]:big_object2=[0.0]*int(1e7) # another 40 meg In [3]:list1=[big_object,big_object2] # maybe a few bytes more, but no copy In [4]:list2=[big_object2,big_object] # maybe a few bytes more, but no copy after this, my python process takes about 80 meg. names like big_object are just names, and they reference an object in memory. if you say a=big_object, you are saying that the name "a" should also reference that same object. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From jenn.duerr at gmail.com Wed Jul 2 09:39:51 2008 From: jenn.duerr at gmail.com (noydb) Date: Wed, 2 Jul 2008 06:39:51 -0700 (PDT) Subject: simple UnZip Message-ID: <5b915a0e-a227-460f-8273-ecc01b800884@2g2000hsn.googlegroups.com> Can someone help me with this script, which I found posted elsewhere? I'm trying to figure out what is going on here so that I can alter it for my needs, but the lack of descriptive names is making it difficult. And, the script doesn't quite do anything worthwhile -- it unzips one file from a zipfile, not all files in a zipfile. *** import zipfile, os, sys, glob os.chdir("C:\\Temp") zips = glob.glob('*.zip') for fzip in zips: if zipfile.is_zipfile(fzip): print fzip," is a zip" z = zipfile.ZipFile(fzip,'r') lstName = z.namelist() sHgt = lstName[0] print "Unpacking",sHgt hgt = z.read(sHgt) fHgt = open(sHgt,'wb') fHgt.write(hgt) # fHgt.flush fHgt.close print "Finished" *** I changed it somewhat to &&& import zipfile, os, sys event_zip = ("C:\\Temp\\data4event.zip") z = zipfile.ZipFile(event_zip, 'r') zList = z.namelist() for zItem in zList: print "Unpacking",zItem zRead = z.read(zItem) z1File = open(zItem,'wb') z1File.write(zRead) z1File.close print "Finished" &&& This works, but I want to be able to specify a different output location. The scenario is that the zip file will always be the same (gets copied over daily), but it needs to be unzipped to a specific different directory. Can anyone help? Thanks! From wtanksleyjr at gmail.com Wed Jul 30 20:33:24 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Wed, 30 Jul 2008 17:33:24 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> Message-ID: <4ae2518f-10c0-49f2-b5d7-a75993b0a67d@z66g2000hsc.googlegroups.com> "Jerry Hill" wrote: > On Wed, Jul 30, 2008 at 2:27 PM, william tanksley wrote: > > Awesome... Thank you! I had my mental model of Python turned around > > backwards. That's an odd feeling. Okay, so you decode to go from raw > > byes into a given encoding, and you encode to go from a given encoding > > to raw bytes. Not what I thought it was, but that's cool, makes sense. > That's not quite right. ?Decoding takes a byte string that is already > in a particular encoding and transforms it to unicode. ?Unicode isn't > a encoding of it's own. ?Decoding takes a unicode string (which > doesn't have any encoding associated with it), and gives you back a > sequence of bytes in a particular encoding. Okay, this is useful. Thank you for straightening out my mental model. It makes sense to define strings as just naturally Unicode... and anything else is in some ways not really a string, although it's something that might have many of the same methods. I guess this mental model is being implemented more thoroughly in Py3K... Anyhow, it makes sense. I'm still puzzled why I'm getting some non-Unicode out of an ElementTree's text, though. > Jerry -Wm From tjreedy at udel.edu Sat Jul 26 17:19:59 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 17:19:59 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87ljzpt3lv.fsf@nokile.rath.org> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> <87ljzpt3lv.fsf@nokile.rath.org> Message-ID: Nikolaus Rath wrote: > > I think you misunderstood him. I did, but addressed the below in another post. > What he wants is to write > > class foo: > def bar(arg): > self.whatever = arg + 1 > > instead of > > class foo: > def bar(self, arg) > self.whatever = arg + 1 > > so 'self' should *automatically* only be inserted in the function > declaration, and *manually* be typed for attributes. which means making 'self' a keyword just so it can be omitted. Silly and pernicious. tjr From jonas.esp at googlemail.com Sun Jul 20 11:19:37 2008 From: jonas.esp at googlemail.com (Kless) Date: Sun, 20 Jul 2008 08:19:37 -0700 (PDT) Subject: Passing keywords Message-ID: <73285f0c-da54-4c43-b83e-27c3e1b26951@2g2000hsn.googlegroups.com> I've a constructor with several values that must be used by any functions: --------------- class foo: def __init__(self, foo1, foo2, foon): self.__check(foo1=foo1, foo2=foo2, foon=foon) self.__check2(foo1=foo1, foo2=foo2, foon=foon) def __check(self, foo1, foo2, foon): ... def __check2(self, foo1, foo2, foon): ... --------------- How simplify all that? I could use the next but I don't think... --------------- def __check(self, **keywords): --------------- From robert.rawlins at thinkbluemedia.co.uk Mon Jul 21 04:46:51 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Mon, 21 Jul 2008 09:46:51 +0100 Subject: Odd math related issue. Message-ID: <00bb01c8eb0e$51face80$f5f06b80$@rawlins@thinkbluemedia.co.uk> Guys, I've got what seems to me to be a totally illogical math issue here which I can't figure out. Take a look at the following code: self.__logger.info("%i / %i" % (bytes_transferred, self.__sessions[path].total_bytes)) percentage = bytes_transferred / self.__sessions[path].total_bytes * 100 self.__logger.info("%i" % percentage) Seems fairly straight forward, you would think. It takes two values and calculates the percentage of one from the other, however, percentage always comes back as '0' for some reason, look at this log output. 2008-07-21 08:39:05,465 manager.py 78 INFO 290112 / 442435 2008-07-21 08:39:05,466 manager.py 80 INFO 0 Any suggestions as to why this might be the case? I'm sure it's something dumb but I can't spot it. Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Wed Jul 9 22:20:41 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 9 Jul 2008 19:20:41 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <750f823a-f9de-4f81-9eb3-7c7b39237c90@y38g2000hsy.googlegroups.com> Message-ID: On Jul 9, 10:06 pm, Kris Kennaway wrote: > John Machin wrote: > >> Hmm, unfortunately it's still orders of magnitude slower than grep in my > >> own application that involves matching lots of strings and regexps > >> against large files (I killed it after 400 seconds, compared to 1.5 for > >> grep), and that's leaving aside the much longer compilation time (over a > >> minute). If the matching was fast then I could possibly pickle the > >> lexer though (but it's not). > > > Can you give us some examples of the kinds of patterns that you are > > using in practice and are slow using Python re? > > Trivial stuff like: > > (Str('error in pkg_delete'), ('mtree', 'mtree')), > (Str('filesystem was touched prior to .make install'), > ('mtree', 'mtree')), > (Str('list of extra files and directories'), ('mtree', 'mtree')), > (Str('list of files present before this port was installed'), > ('mtree', 'mtree')), > (Str('list of filesystem changes from before and after'), > ('mtree', 'mtree')), > > (re('Configuration .* not supported'), ('arch', 'arch')), > > (re('(configure: error:|Script.*configure.*failed > unexpectedly|script.*failed: here are the contents of)'), > ('configure_error', 'configure')), > ... > > There are about 150 of them and I want to find which is the first match > in a text file that ranges from a few KB up to 512MB in size. > > > How large is "large"? > > > What kind of text? > > It's compiler/build output. > > > Instead of grep, you might like to try nrgrep ... google("nrgrep > > Navarro Raffinot"): PDF paper about it on Citeseer (if it's up), > > postscript paper and C source findable from Gonzalo Navarro's home- > > page. > > Thanks, looks interesting but I don't think it is the best fit here. I > would like to avoid spawning hundreds of processes to process each file > (since I have tens of thousands of them to process). > Uh-huh ... try this, then: http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ You could use this to find the "Str" cases and the prefixes of the "re" cases (which seem to be no more complicated than 'foo.*bar.*zot') and use something slower like Python's re to search the remainder of the line for 'bar.*zot'. Cheers, John From bborcic at gmail.com Fri Jul 25 10:10:21 2008 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 25 Jul 2008 16:10:21 +0200 Subject: 2d graphics - what module to use? In-Reply-To: References: Message-ID: Pierre Dagenais wrote: > What is the easiest way to draw to a window? I'd like to draw something > like sine waves from a mathematical equation. > Newbie to python. > -- > http://mail.python.org/mailman/listinfo/python-list > For very simple things, the standard module turtle might be your best bet. BB From noagbodjivictor at gmail.com Tue Jul 15 14:37:05 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Tue, 15 Jul 2008 14:37:05 -0400 Subject: 'if name is not None:' v. 'if name:' Message-ID: Hello, what's the difference between these two statement? And which one should one use? -- NOAGBODJI Paul Victor From stef.mientki at gmail.com Wed Jul 23 06:35:54 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 23 Jul 2008 12:35:54 +0200 Subject: Is this possible .... In-Reply-To: References: Message-ID: <4887098A.8040009@gmail.com> thanks Paul, your solution works very well. cheers, Stef Paul Hankin wrote: > On Jul 23, 9:58 am, Stef Mientki wrote: > > .... > You could use version() instead of module.version(), and just > declare 'version' in one place. Presumably you already have a module > for getting the metadata out of one of your modules; perhaps it could > go in there? > > def version(module): > return getattr(module, 'Version_Text')[0][0] > > -- > Paul Hankin > From jcd at sdf.lonestar.org Thu Jul 10 11:47:05 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 10 Jul 2008 11:47:05 -0400 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <1343fa73-fd32-46c3-8a75-0efc85b2660e@a70g2000hsh.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <1343fa73-fd32-46c3-8a75-0efc85b2660e@a70g2000hsh.googlegroups.com> Message-ID: <1215704825.11618.6.camel@aalcdl07.lib.unc.edu> On Wed, 2008-07-09 at 12:29 -0700, samwyse wrote: > On Jul 8, 11:01 am, Kris Kennaway wrote: > > samwyse wrote: > > > > You might want to look at Plex. > > >http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/ > > > > > "Another advantage of Plex is that it compiles all of the regular > > > expressions into a single DFA. Once that's done, the input can be > > > processed in a time proportional to the number of characters to be > > > scanned, and independent of the number or complexity of the regular > > > expressions. Python's existing regular expression matchers do not have > > > this property. " > > > Hmm, unfortunately it's still orders of magnitude slower than grep in my > > own application that involves matching lots of strings and regexps > > against large files (I killed it after 400 seconds, compared to 1.5 for > > grep), and that's leaving aside the much longer compilation time (over a > > minute). If the matching was fast then I could possibly pickle the > > lexer though (but it's not). > > That's funny, the compilation is almost instantaneous for me. > However, I just tested it to several files, the first containing > 4875*'a', the rest each twice the size of the previous. And you're > right, for each doubling of the file size, the match take four times > as long, meaning O(n^2). 156000*'a' would probably take 8 hours. > Here are my results: > > compile_lexicon() took 0.0236021580595 secs > test('file-0.txt') took 24.8322969831 secs > test('file-1.txt') took 99.3956799681 secs > test('file-2.txt') took 398.349623132 secs Sounds like a good strategy would be to find the smallest chunk of the file that matches can't cross, and iterate your search on units of those chunks. For example, if none of your regexes cross line boundaries, search each line of the file individually. That may help turn around the speed degradation you're seeing. Cheers, Cliff From __peter__ at web.de Fri Jul 18 12:19:51 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jul 2008 18:19:51 +0200 Subject: checking if an object IS in a list References: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> <5310bac6-e13d-41c9-9c48-52a0c8d9d64a@i20g2000prf.googlegroups.com> <7f58d77a-fe19-42b4-9794-f0c13220da7d@u36g2000pro.googlegroups.com> Message-ID: nicolas.pourcelot at gmail.com wrote: >> What is your (concrete) use case, by the way? > > > > I try to make it simple (there is almost 25000 lines of code...) > I have a sheet with geometrical objects (points, lines, polygons, > etc.) > The sheet have an object manager. > > So, to simplify : > >>>> sheet.objects.A = Point(0, 0) >>>> sheet.objects.B = Point(0, 2) >>>> sheet.objects.C = Middle(A, B) > > Then we have : > >>>> sheet.objects.A == sheet.objects.B > True > > since have and B have the same coordinates. > But of course A and B objects are not same python objects. > In certain cases, some geometrical objects are automatically > referenced in the sheet, without being defined by the user. > (Edges for polygons, for example...) > But they must not be referenced twice. So if the edge of the polygon > is already referenced (because the polygon uses an already referenced > object for its construction...), it must not be referenced again. > However, if there is an object, which accidentally have the same > coordinates, it must be referenced with a different name. > > So, I use something like this in 'sheet.objects.__setattr__(self, > name, value)': > if type(value) == Polygon: > for edge in value.edges: > if edge is_in sheet.objects.__dict__.itervalues(): > object.__setattr__(self, self.__new_name(), edge) > > Ok, I suppose it's confused, but it's difficult to sum up. ;-) I won't pretend I understand ;) If you make Point immutable you might be able to drop the "must not be referenced twice" requirement. Peter From mensanator at aol.com Sat Jul 26 22:04:02 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 26 Jul 2008 19:04:02 -0700 (PDT) Subject: Insert string into string References: <56ff99b9-b4d4-4077-8de1-97a771ac526a@k13g2000hse.googlegroups.com> Message-ID: <486aa16d-0cd5-4f26-86e3-9574998bdf5b@x35g2000hsb.googlegroups.com> On Jul 26, 6:32?pm, Mensanator wrote: > On Jul 26, 4:40?pm, "Francesco Pietra" wrote: > > > > > > > I am posting ex novo as it became confusing to me. I take the > > opportunity to ask advice for a second problem. > > > FIRST PROBLEM > > For file xxx.pdb, insert letter "A" into each line that starts with > > "ATOM". "A" should be inserted at position 22, i.e., one space after > > "LEU", leaving all other characters at the same position as in the > > original example: > > > ATOM ? ? ?1 ?N ? LEU ? ? 1 ? ? 146.615 ?40.494 103.776 ?1.00 73.04 ? ? ? 1SG ? 2 > > > In all lines starting with "ATOM", "LEU" is constant as to position > > only (18-20), i.e., "LEU" may be replaced by > > three different uppercase letters. Therefore, the most direct > > indication would be position 22. If specifying line starting with > > "ATOM" makes complication, forget about that as most lines begin with > > "ATOM" so that hand correction will be easy. > > > Script > > f = open("xxx.pdb", "w") > > import sys > > > for line in sys.stdin: > > ? ? line = line[:22] + "A" + line[23:] > > ? ? sys.stdout.write(line) > > > destroys the xxxx.pdb file and python exits witha non zero exit status. > > > The same occurs with script > > > f = open("hASIC1a.B99990003.pdb", "w") > > f.write(' line = line[:22] + "A" + line[23:]') > > f.close() > > > I must have misunderstood the suggestion I received on previous posting. > > ____________________________________ > > SECOND PROBLEM > > File xxx.pdb above has 426 lines stating with "ATOM", this serial > > number occupying positions 7-11, right justified (Thus 1, as in the > > line example above, means first line). A second, similar file yyy.pdb > > has to be concatenated to xxx.pdb. Before that it should be added of > > "A" as above and renumbered at position 7-11, starting from 428 (there > > is an intermediate line to add). How should a script look like for > > this string insertion into string with recursive +1? > > > Thanks > > francesco > > I don't know why you're using stdin if you're reading from a file. > > Also, the serial number isn't 7-11, it's 6-10 (remember to > count from 0, so character 1 is position 0, etc.) > > fx = open('xxx.pdb','r') # first input file > fy = open('yyy.pdb','r') # second input file > fz = open('zzz.pdb','w') # output file (to be created) > > for xline in fx: ? ? ? ? # read input one line at a time > ? if len(xline) >= 80: ? # don't process invalid lines > ? ? line_index = int(xline[7:12]) # keep track of this Forgot to fix this after I discovered your error. S/b int(xline[6:11]) > ? ? if xline[:4]=='ATOM': > ? ? ? fz.write(xline[:22] + 'A' + xline[23:]) > ? ? else: > ? ? ? fz.write(xline) > > fx.close() # done with first file > > fz.write('the extra line \n') > line_index += 1 ? ? ? ? ? ? ? # don't forget to count it > > for yline in fy: ? ? ? ? ? ? ?# read second file > ? if len(yline) >= 80: ? ? ? ?# again, valid only > ? ? line_index += 1 ? ? ? ? ? # ignore serial number, use > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? # ? where we left off from > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? # ? from first file > ? ? if yline[:4]=='ATOM': > ? ? ? # note use of .rjust(5) to creat new serial number > ? ? ? fz.write(yline[:6] + \ > ? ? ? ? ? ? ? ?str(line_index).rjust(5) + \ > ? ? ? ? ? ? ? ?yline[11:22] + 'A' + yline[23:]) > ? ? else: > ? ? ? fz.write(yline[:6] + \ > ? ? ? ? ? ? ? ?str(line_index).rjust(5) + yline[11:]) > > fy.close() # done with second file > > fz.close() # done with output file From inhahe at gmail.com Sun Jul 6 03:04:02 2008 From: inhahe at gmail.com (inhahe) Date: Sun, 6 Jul 2008 03:04:02 -0400 Subject: The Yield statement References: Message-ID: "Alex Bryan" wrote in message news:mailman.1009.1214865088.1044.python-list at python.org... > Okay, so i don't really understand the Yield thing and i know it is > useful. I've read a few things about it but it is all programming jargon > and so basically it is hard for me to understand. So can anyone give me a > description or link me to a site that has a good definition and/or > examples of it? If you could I would really appreciate it. Really short answer: def f(): yield 1 yield 2 yield 3 for x in f(): print x, # should print 1 2 3 def f(): for x in xrange(10): yield x for x in f(): print x, # should print 0 1 2 3 4 5 6 7 8 9 note that this won't work; def f(): for x in xrange(10): for y in xrange(10): yield (x,y) yield just doesn't work right with multiple levels of loops. i had to discover that the hard way. From sjmachin at lexicon.net Mon Jul 14 04:08:24 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 14 Jul 2008 01:08:24 -0700 (PDT) Subject: while var, but var ==16 != true References: <8c2cd9ff-bec2-4844-82a8-8ce02df5663e@w7g2000hsa.googlegroups.com> Message-ID: <8c98aa5d-12f4-43ea-af1f-ddf5e88f900e@k37g2000hsf.googlegroups.com> On Jul 14, 3:32?pm, Tim Roberts wrote: > maestro wrote: > > >why does this work? ?"while p" = "while p != 0" ? 1 is True and 0 is > >false in python but other numbers have no boolean value so why doesnt > >it abort. > > Because your statement is incorrect. ?Everything has a boolean value in > Python. ?0, None, False, '' (empty string), [] (empty list), () (empty > tuple), and {} (empty dictionary) all have a False value. ?Everything else > has a True value. Not quite; for example: >>> bool(set()) False >>> According to section 5.10 of the Reference Manual: """ In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. """ ... and for the definition for what a user-written class needs to do, see section 3.4.1: """ __nonzero__( self) Called to implement truth value testing, and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1. When this method is not defined, __len__() is called, if it is defined (see below). If a class defines neither __len__() nor __nonzero__(), all its instances are considered true. """ Cheers, John From aahz at pythoncraft.com Wed Jul 9 23:40:40 2008 From: aahz at pythoncraft.com (Aahz) Date: 9 Jul 2008 20:40:40 -0700 Subject: Python equivalent of call/cc? References: Message-ID: In article , The Pythonista wrote: > >Yesterday, I was hacking around a bit, trying to figure out how to >implement the semantics of call/cc in Python. Specifically, I wanted to >translate this Scheme code to equivalent Python: > >#### > >(define theContinuation #f) > > (define (test) > (let ((i 0)) > (call/cc (lambda (k) (set! theContinuation k))) > (set! i (+ i 1)) > i)) > > (test) > (theContinuation) > (theContinuation) > Python relies on mutables to do this: class holder: pass def call(): x = holder() x.counter = 0 def cc(): x.counter += 1 return x.counter return cc foo = call() print foo() print foo() print foo() -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From mrkafk at gmail.com Thu Jul 17 12:28:02 2008 From: mrkafk at gmail.com (mk) Date: Thu, 17 Jul 2008 18:28:02 +0200 Subject: Unusual Exception Behaviour In-Reply-To: <21965.9065748148$1216310669@news.gmane.org> References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> Message-ID: Robert Rawlins wrote: > I certainly like that implementation for logging the exceptions, however, at > the moment I don't even know where the exceptions are occurring, or what > type they are, could I still use this method to log any and all exceptions > raised in the application? Sure. I'm a little confused as to how I can modify that > implementation to do so. Remember, Google is your friend, here's the crux of the method without the fancy schmancy sugar coating: http://linux.byexamples.com/archives/365/python-convey-the-exception-traceback-into-log-file/ if __name__=="__main__": try: main() except: print "Trigger Exception, traceback info forward to log file." traceback.print_exc(file=open("errlog.txt","a")) sys.exit(1) This will obviously capture every exception happening in the main() function. The drawback of this method is that you cannot capture the error message / object accompanying the exception, as you normally can do while capturing specific exception: >>> import sys >>> import traceback >>> def anindextoofar(alist): print alist[10] >>> shortlist=range(1,10) >>> >>> try: anindextoofar(shortlist) except IndexError, err: print err traceback.print_exc(file=sys.stdout) list index out of range Traceback (most recent call last): File "", line 2, in File "", line 2, in anindextoofar IndexError: list index out of range From kurdayon at yahoo.com Tue Jul 1 16:43:45 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Tue, 1 Jul 2008 13:43:45 -0700 (PDT) Subject: How to make a function associated with a class? Message-ID: <69e26f9b-2f00-4318-9bc5-6aa94e141bca@59g2000hsb.googlegroups.com> Hi, I have a class called "vector". And I would like to define a function "dot" which would return a dot product of any two "vectors". I want to call this function as follow: dot(x,y). Well, I can define a functions "dot" outside the class and it works exactly as I want. However, the problem is that this function is not associated with the class (like methods a method of the class). For example, if I call "x.calc()" or "y.calc()", python will execute different methods if "x" and "y" belongs to different classes. I want to have the same with my "dot" function. I.e. I want it calculates the dot product ONLY IF the both arguments of that function belong to the "vector" class. Is it possible? Thank you in advance. From pavlovevidence at gmail.com Thu Jul 31 22:36:48 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 31 Jul 2008 19:36:48 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: <9f4b1c12-d010-45f6-91ee-d490e2f850dc@79g2000hsk.googlegroups.com> On Jul 31, 1:27 pm, "Chris Mellon" wrote: > I'm really not sure where you're going with this or what you're trying > to prove. "if x" is a duck-type test for a boolean value. Obviously if > you know the type and want a more *specific* test, then you can use an > explicit one. Any time you don't know or don't care about a more > specific type than "something which probably is boolean true", or any > time where you know the boolean semantics of the type and want to drop > some typing, you can use "if x". The more specific test is what you'd > use if you want more specific results. What's complicated about this > idea? Many people trumpet that "if x" makes your code more polymorphic whenever this comes up--in fact you just repeated the claim--without ever considering how rarely this more extensive polymorphism comes up in practice. I was calling them out to say "prove to me that it actually happens". I believe it's very rare not to know enough about the expected type that explicit tests won't work. We've uncovered a few examples of it in this thread, but IMO we haven't uncovered any sort of broad, wide- ranging use cases. Carl Banks From henrik at chamalulu.com Tue Jul 1 17:20:11 2008 From: henrik at chamalulu.com (chamalulu) Date: Tue, 1 Jul 2008 14:20:11 -0700 (PDT) Subject: Attribute reference design Message-ID: Hello. I think I'm aware of how attribute access is resolved in python. When referencing a class instance attribute which is not defined in the scope of the instance, Python looks for a class attribute with the same name. (For assignment or deletion this is not the case, thankfully.) I've been trying to understand why? What is the reason behind, or practical purpose of, this design decision? Anyone, please enlighten me. /Henrik From gagsl-py2 at yahoo.com.ar Wed Jul 30 21:07:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 22:07:31 -0300 Subject: undo a dictionary References: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> <192b4786-85b2-43d3-bb7c-b5716068ff12@56g2000hsm.googlegroups.com> Message-ID: En Wed, 30 Jul 2008 16:14:31 -0300, mmm escribi?: >> > And for that matter a way to create a >> > dictionary from a set of variables (local or global). >> >> You have to be more specific: there are {} displays and dict(args) call >> and other methods. ?Read the manual. > > My desire is to take a set of data items in an alpha-numeric range and > oput them into a dictionary > > i.e., > x1=1 > x2=20 > x3=33 > > to yield the dictionary > > { 'x1':1, 'x2':20, 'x3':33 } > > without having to type in as above but instead invoke a function dict(x1=1, x2=20, x3=33) does the same thing. Or, do you mean you already have those names and values, perhaps mixed with a lot more names, and want to extract only those starting with "x" and following with a number? result = {} for name, value in vars(): # or locals().items(), or globals().items(), or vars(some_module) if name[0]=='x' and name[1:].isdigit(): result[name] = value -- Gabriel Genellina From wtanksleyjr at gmail.com Thu Jul 31 17:44:51 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Thu, 31 Jul 2008 14:44:51 -0700 (PDT) Subject: Python parsing iTunes XML/COM References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> <4609709f-dc0f-47cc-905e-1552a02ec3b6@r15g2000prd.googlegroups.com> <416f2710-1295-4d8b-a356-98fd9e9a56ad@j7g2000prm.googlegroups.com> Message-ID: John Machin wrote: > william tanksley wrote: > Let's try again: Cool. Sorry for the misunderstanding. Thank you for helping again! Postscript: your request to print the actual data did the trick. I'm including the rest of my reply just to provide context, but the answer was the the Unicode was actually embedded in the URL, encoded as distinct bytes. Thus, it *had* to be url-decoded and then UTF-8 decoded, in that order, in order to recover the original filename. So the problem was indeed purely in my head -- I should have looked at the original data (unfortunately, I was fooled by looking at the song title, which is the same thing but with the raw UTF-8 bytes instead of the URL escape codes). > >> track_id = url2pathname(urlparse(track_id).path) > >> print repr(track_id) > >> parse_result = urlparse(track_id).path > >> print repr(parse_result) > >> track_id_replacement = url2pathname(parse_result) > >> print repr(track_id_replacement) > > The "important" value here is track_id_replacement; it contains the > > data that's throwing me. It appears that some UTF-8 characters are > > being read as multiple bytes by ElementTree rather than being decoded > > into Unicode. > > Here's one example. The others are similar -- they have the same > > things that look like problems to me. > > "Buffett Time - Annual Shareholders\xc2\xa0L.mp3" > ROTFL! I thought the Buffett thing was a Windows filename! What I was > expecting was THREE lots of repr() output, and I'm quite unused to > seeing repr() output with quotes around it instead of apostrophes; how > did you achieve that? I don't know -- but I got it again when I printed out the original version. My *guess* would be that this is what repr prints when asked to print a byte string (but I don't know how to confirm that). Alternately, the fact that I'm running these inside SPE might be changing some defaults. I'm not sure. You're right that single quotes are expected -- and I'd expect a preceding u, since they're supposed to be Unicode. I dunno what's going on. > So you're saying that track_id_replacement contains utf8 characters. > It is obtained by track_id_replacement = url2pathname(parse_result). > You don't show us what is in parse_result. url2pathname() is nothing > to do with ElementTree. urlparse() is nothing to do with ElementTree. > You have provided no evidence that ElementTree is doing what you > accuse it of. Okay. Here's the evidence... Or something. Looking at this I begin to see why things work the way they do. It's utterly bizzare, quite frankly. > Please try again. Backtrack in your code to where you are pulling the > url out of an element. Do print repr(some_element.some_attribute). > Show us. Okay, the repr of the string that comes out of the .text attribute is: "file://localhost/C:/Documents%20and%20Settings/TanksleyJrW/My %20Documents/My%20Music/iTunes/iTunes%20Music/Podcasts/Brian %20Preston's%20_Money%20Guy_%20Blog%20and%20Pod/Buffett%20Time%20- %20Annual%20Shareholders%C2%A0L.mp3" Looking at the XML, and THIS TIME actually looking at the correct attribute (I was looking at the title before) I see... surprise! That's the correct data. So all of the mysteries are solved (except for my Python's doublequotes, but who cares), and ElementTree is entirely vindicated. -Wm From larry.bates at websafe.com` Tue Jul 15 15:41:55 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 15 Jul 2008 14:41:55 -0500 Subject: logging via SocketHandler and TCPserver In-Reply-To: <87tzerndq9.fsf@merkury.smsnet.pl> References: <81929250-449b-4686-acf3-dcc0095e341a@d1g2000hsg.googlegroups.com> <87tzerndq9.fsf@merkury.smsnet.pl> Message-ID: Rob Wolfe wrote: > Larry Bates writes: > >> Can multiple applications send SocketHandler logging records to the >> same socket server on the same port simultaneously? > > Of course they can. Server can accept requests from many clients. > You have used `SocketServer.ThreadingTCPServer`. That server for example > handles every request in a different thread. > >> If so, then I understand your answer completely and will go >> in that direction. I guess I was trying to not use up >> bandwidth/CPU cycles on the applications that weren't being actively >> monitored by just not having the socket server connected to them. >> >> I think you may be a 'little to close' to the (excellent) application >> you have written to understand the steep learning curve that I see. >> You know the saying, "Brain surgery is easy to a brain surgeon". I >> should point out that I'm no newbie. I've used PIL, ReportLab, >> BeautifulSoup, Mechanize, Win32 extensions, ElementTree and a whole >> host of other modules with less difficulty. Please don't take this as >> anything more than an observation on my part. From what I see, you >> have written (and generously donated) an extremely powerful library >> and it is greatly appreciated. It is most likely just me. > > Well, I know what you mean. I had troubles to understand that library > either. Logging docs are quite good as a reference, but there is lack > of a good introductory tutorial. Now when I know `logging` I can't live > without it, but the start wasn't easy. > I shouldn't say it here, but I found helpful docs to the similar > library in Java. ;) > http://logging.apache.org/log4j/1.2/manual.html > > There are many differences (e.g. Appenders vs Handlers), but the rule > is the same. > >> As far as the book is concerned, I guess I'd purchase the only copy ;-). > > "The Art of Logging" - four volumes. ;-) > > Regards, > Rob Five volumes if you add in "Logging within Frameworks (Django, TurboGears, and Pylons" ;-). Now on to UnitTesting (I use a home-grown method), Twisted, and other things I can't seem to find time to get my brain around... -Larry From blake.anderton at gmail.com Fri Jul 25 20:19:36 2008 From: blake.anderton at gmail.com (BAnderton) Date: Fri, 25 Jul 2008 17:19:36 -0700 (PDT) Subject: How to close all python-opened file identifiers? Message-ID: Greetings from beautiful Tucson, Arizona. Question: Is there a way in Python to determine what all file identifiers have been opened by Python, and to close them all? Why I ask: I learned Python after cutting my programming teeth on Matlab, where you get a list of all open file identifiers (that is, those opened from a particular Matlab session) with "fopen('all')" and close them with "fclose('all')". In my 4 years of experience with Python, I haven't yet come across an equivalent means of doing this in Python. I understand that this problem can be prevented by making sure a "fid.close()" exists for every "open"; I need this however for a file-permissions troubleshooting problem. Extra info on this specific problem: In my program, python (through subprocess) launched a text editor on a text file, and I can't seem to save the text file through that editor (I get a "this document is in use by another application and cannot be accessed" error from the editor [wordpad on winXp]). The text file in question is modified by my program prior to its loading into the launched editor. Although I can't find unmatched "open" and "fid.close()" statements, I'd like to implement a check for open file identifiers before launching the editor. Thanks very much in advance for your time and any help you can provide. From mnordhoff at mattnordhoff.com Mon Jul 7 13:06:00 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 07 Jul 2008 17:06:00 +0000 Subject: Confused yet again: Very Newbie Question In-Reply-To: <16651e80807070654j12d55802yf3950e2375bbe67d@mail.gmail.com> References: <16651e80807070654j12d55802yf3950e2375bbe67d@mail.gmail.com> Message-ID: <48724CF8.6030009@mattnordhoff.com> Jerry Hill wrote: > On Mon, Jul 7, 2008 at 7:30 AM, mcl wrote: >> I did not think you had to make the distinction between 'byvar' and >> 'byref' as in Basic. > > Python does not use "call by value" or "call by reference" semantics. > Instead, python's model is "call by object". See this writeup for > some details: http://effbot.org/zone/call-by-object.htm Ah-ha! That's the article I've been trying to find! I can never remember "effbot"'s name. Thanks! -- From thudfoo at opensuse.us Mon Jul 28 11:23:36 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Mon, 28 Jul 2008 08:23:36 -0700 Subject: QOTW [was Re: Attack a sacred Python Cow] In-Reply-To: <009dce32$0$20313$c3e8da3@news.astraweb.com> References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> <7360bd9a-4ff6-4e75-821c-eabc88ee6258@u6g2000prc.googlegroups.com> <009dce32$0$20313$c3e8da3@news.astraweb.com> Message-ID: <3d881a310807280823h46ec1d40yfd9eac1ca2791bfd@mail.gmail.com> On 28 Jul 2008 14:07:44 GMT, Steven D'Aprano wrote: > On Sun, 27 Jul 2008 21:42:37 -0700, Russ P. wrote: > > >> +1 QOTW > > > > Do you realize what an insult that is to everyone else who has posted > > here in the past week? > > Actually I don't. I hadn't realised that when a person believes that > somebody has made an especially clever, witty, insightful or fun remark, > that's actually a put-down of all the other people whose remarks weren't > quite as clever, witty, insightful or fun. > > But now that I've had this pointed out to me, why, I see insults > everywhere! Tonight, my wife said to me that she liked my new shirt, so I > replied "What's the matter, you think my trousers are ugly?" > > > -- > Steven > It is difficult to not offend the insult-sensitive. From russandheather at gmail.com Sat Jul 19 01:45:32 2008 From: russandheather at gmail.com (Russell Warren) Date: Fri, 18 Jul 2008 22:45:32 -0700 (PDT) Subject: "proper"/best way to hack SimpleXmlRpcServer to support datetime? Message-ID: <7e2bab15-d655-4741-974f-d5dfa2bea9f8@m36g2000hse.googlegroups.com> I'm running python 2.5.1 and it seems that SimpleXmlRpcServer is not setup to support the base datetime module in the same way xmlrpclib has been with "use_datetime". I see that someone (Virgil Dupras) has recently submitted a fix to address this, but I don't want to patch my python distro. I want to work around it until the real upgrade comes. I have a klugey workaround I can just drop in my program that does the trick, but I'm curious if there is a better way? I have not done that many monkey patches. I'm also of course interested in someone telling me I don't need to patch this and I'm just blind to the correct way. My monkey patch is below... ### HACK HACK HACK ### ## Patching SimpleXmlRpcServer to support datetime (just like xmlrpclib does) from SimpleXMLRPCServer import xmlrpclib as _xmlrpclib _old_loads = _xmlrpclib.loads def _new_loads(*args, **kwargs): kwargs["use_datetime"] = True return _old_loads(*args, **kwargs) _xmlrpclib.loads = _new_loads ### ENDHACK ENDHACK ### That works, but are there any better, slicker, more pythonic, more robust, more interesting, or just plain more fun ways to do it? From malaclypse2 at gmail.com Wed Jul 23 11:55:27 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 23 Jul 2008 11:55:27 -0400 Subject: Get dict value but not as reference. In-Reply-To: <4357936148771237039@unknownmsgid> References: <4357936148771237039@unknownmsgid> Message-ID: <16651e80807230855l745bba66u4c506e9fab5b38fa@mail.gmail.com> On Wed, Jul 23, 2008 at 11:49 AM, Robert Rawlins wrote: > I have a dictionary, and I want to get one of the values from it, but rather > than returning it as a reference I want to actually detach/remove the > element from the dictionary. Like so: Use the pop() method of the dictionary, like this: >>> my_dict = {'a': 'Item A', 'b': 'Item B', 'c': 'Item C'} >>> my_dict.pop('a') 'Item A' >>> my_dict {'c': 'Item C', 'b': 'Item B'} >>> -- Jerry From fredrik at pythonware.com Wed Jul 23 03:22:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 09:22:38 +0200 Subject: os.walk question In-Reply-To: References: Message-ID: Lanny wrote: > How would one make a list of the files in the top directory > using os.walk. > > I need to pick a random file from said list. if you want a list of files from a single directory, use listdir, not walk: >>> import os, random >>> random.choice(os.listdir("/")) 'python25' From babacity4 at gmail.com Thu Jul 24 16:55:04 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:55:04 -0700 (PDT) Subject: www spankwire com - Amazing porn video collection Message-ID: www spankwire com . >>>>>>>>>>Best Collection of Spankwire Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE www spankwire VIDEOS<<<<<<<<<<< . www spankwire com From dominic.rice at gmail.com Fri Jul 4 05:38:35 2008 From: dominic.rice at gmail.com (Dominic Rice) Date: Fri, 04 Jul 2008 10:38:35 +0100 Subject: running python from cmd.exe References: Message-ID: Dominic Rice wrote: > Miki wrote: >> Hello, >> >>> I can't seem to get python to run my scripts using the command: python >>> .py >>> >>> If I type python the interpreter runs as I sorted out the Path property, >>> >>> I'm afraid I don't know much about this kind of thing as I'm a science >>> student who needs some Python not a programmer! >> Can you be more specific about the error you get? >> >> Say you have a script hw.py that contains one line: >> print "Hello Python" >> >> and you run >> python hw.py >> >> What is the error you get? >> >> HTH, >> -- >> Miki >> http://pythonwise.blogspot.com >> > Sure, I get: > > can't open file .py: [errorno 2]No such file or directory. > > Now if I've noticed that if I change directory to (for instance) > \Python25 where the script is the command runs fine.(?) Oh I just noticed you specified hw.py, in that case just to clarify it would be can't open file hw.py: [errorno 2]No such file or directory From sn.oo.py.9027 at gmail.com Mon Jul 14 12:41:15 2008 From: sn.oo.py.9027 at gmail.com (John Mechaniks) Date: Mon, 14 Jul 2008 09:41:15 -0700 (PDT) Subject: subprocess module References: <2e7f0504-cc1c-4cb6-b2d0-b67b004eca7d@x41g2000hsb.googlegroups.com> <39622612-5e43-45b4-800a-69277c2e2987@79g2000hsk.googlegroups.com> Message-ID: <83c5472c-935d-4eda-ad98-dbb6dd02222a@l64g2000hse.googlegroups.com> On Jul 14, 7:44?pm, Peter Otten <__pete... at web.de> wrote: > John Mechaniks wrote: > > On Jul 14, 12:34?pm, Peter Otten <__pete... at web.de> wrote: > >> John Mechaniks wrote: > >> > from subprocess import call > >> > call(['ls', '-l']) > > >> > How do I get the result (not the exit status of the command) of "ls - > >> > l" into a variable? > > >> output = subprocess.Popen(["ls", "-l"], > >> stdout=subprocess.PIPE).stdout.read() > > What difference does the following code makes? What are the advantages > > of the above method over this one? > > output = subprocess.Popen(['ls', '-l'], > > stdout=subprocess.PIPE).communicate()[0] > > Hm, I chose it because it looks cleaner. Looking into the source > Popen.communicate() seems to do the following: > > output = p._fo_read_no_intr(p.stdout) ? > p.wait() ? ? ? ? ? ? > > So there are two differences in this case > > - communicate() waits for the subprocess to terminate. > - stdout.read() is retried if an EINTR occurs (Not sure when this would > happen). > > > Also could someone show an example of using the optional input > > argument for communicate() > > http://blog.doughellmann.com/2007/07/pymotw-subprocess.html > > I didn't read it myself, but Doug Hellmann's articles are usually quite > good. > > Peter Thanks Peter From boblatest at yahoo.com Sat Jul 26 14:54:22 2008 From: boblatest at yahoo.com (Robert Latest) Date: 26 Jul 2008 18:54:22 GMT Subject: Confounded by Python objects References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> <5ddae1dd-c7dd-4f04-84f6-ad71c3282c92@j7g2000prm.googlegroups.com> Message-ID: <6f1a6uF9ctsmU1@mid.uni-berlin.de> satoru wrote: > As to "sample", it never get assigned to and when you say "append" the > class variable is changed in place. > hope my explaination helps. Sure does, thanks a lot. Here's an interesting side note: After fixing my "Channel" thingy the whole project behaved as expected. But there was an interesting hitch. The main part revolves around another class, "Sequence", which has a list of Channels as attribute. I was curious about the performance of my script, because eventually this construct is supposed to handle megabytes of data. So I wrote a simple loop that creates a new Sequence, fills all the Channels with data, and repeats. Interistingly, the first couple of dozens iterations went satisfactorily quickly (took about 1 second total), but after a hundred or so times it got really slow -- like a couple of seconds per iteration. Playing around with the code, not really knowing what to do, I found that in the "Sequence" class I had again erroneously declared a class-level attribute -- rather harmlessly, just a string, that got assigned to once in each iteration on object creation. After I had deleted that, the loop went blindingly fast without slowing down. What's the mechanics behind this behavior? robert From fredrik at pythonware.com Wed Jul 16 20:24:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 17 Jul 2008 02:24:25 +0200 Subject: Manually prompting garbage collection In-Reply-To: <20080716235656.GE22400@monkey.ucolick.org> References: <20080716230911.GD22400@monkey.ucolick.org> <20080716235656.GE22400@monkey.ucolick.org> Message-ID: Kyle Lanclos wrote: > The DECREF decrements the reference count, but does not immediately prompt > garbage collection when the reference count drops to zero; that garbage > collection does not appear to occur until I return from the particular C > function I am in the middle of executing. Yeah, but what do you expect that garbage collection pass to result in? What objects do you want to get rid of? Do these objects have direct references to a resource that you're explicitly destroying from your C code? Why? > Ideally, I want to explicitly prompt garbage collection in the middle > of a C function, without first returning to the larger Python > interpreter. PyGC_Collect() does exactly that, so if that doesn't solve your problem, the only way to fix is this is to go back to the drawing board (and even if it would fix this, it's a good idea to get back to the drawing board anyway; Python's not C++, and code that relies on destructors to fire in a specific order, or before a specific event, is bound to fail sooner or later.) From tjreedy at udel.edu Thu Jul 17 17:19:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Jul 2008 17:19:08 -0400 Subject: unpacking with default values In-Reply-To: <6a105194-a248-4ee6-be01-5aef9e5bb648@e53g2000hsa.googlegroups.com> References: <335e7a21-e35e-41ee-9f92-fd4c2f6bf166@f36g2000hsa.googlegroups.com> <6a105194-a248-4ee6-be01-5aef9e5bb648@e53g2000hsa.googlegroups.com> Message-ID: McA wrote: > Do you know the "protocol" used by python while unpacking? > Is it a direct assingnment? Or iterating? In CPython, at least, both, just as with normal unpack and multiple assignment. The iterable is unpacked into pieces by iterating (with knowledge of the number of targets and which is the catchall). The targets are then directly bound. >>> from dis import dis # first standard assignment >>> dis(compile("a,b,c = range(3)", '','single')) 1 0 LOAD_NAME 0 (range) 3 LOAD_CONST 0 (3) 6 CALL_FUNCTION 1 9 UNPACK_SEQUENCE 3 12 STORE_NAME 1 (a) 15 STORE_NAME 2 (b) 18 STORE_NAME 3 (c) 21 LOAD_CONST 1 (None) 24 RETURN_VALUE # now starred assignment >>> dis(compile("a,b,*c = range(3)", '','single')) 1 0 LOAD_NAME 0 (range) 3 LOAD_CONST 0 (3) 6 CALL_FUNCTION 1 9 UNPACK_EX 2 12 STORE_NAME 1 (a) 15 STORE_NAME 2 (b) 18 STORE_NAME 3 (c) 21 LOAD_CONST 1 (None) 24 RETURN_VALUE The only difference is UNPACK_EX (tended) instead of UNPACK_SEQUENCE. Tne UNPACK_EX code is not yet in the dis module documentation. But a little reverse engineering reveals the parameter meaning: a,*b,c and *a,b,c give parameters 257 and 512 instead of 2. Separating 2,257,512 into bytes gives 0,2; 1,1; 2,0. a,*b and *a,b give 1, 256 or 0,1; 1,0. The two bytes are the number of targets after and before the starred target. Terry Jan Reedy From tn.pablo at gmail.com Mon Jul 21 09:12:30 2008 From: tn.pablo at gmail.com (ptn) Date: Mon, 21 Jul 2008 06:12:30 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <0537f970-6a87-42f8-872c-6a48fd2211a6@e53g2000hsa.googlegroups.com> On Jul 20, 5:50?pm, giveitawhril2... at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. Sounds like you program only because someone's paying you. Any programmer who says that C is outdated and not real *is* outdated and not real. Not used anymore? Mmmmm I wonder, have you heard of something called "Linux"? The open source Unix-like system? Or perhaps you are familiar with "Apache"? Does "GNOME" ring any bells to you? "Vim"? "Git"? You got some serious research to do, STFW. From fredrik at pythonware.com Wed Jul 23 03:07:27 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 09:07:27 +0200 Subject: sys.stderr.write returns string length in Python 3 In-Reply-To: References: <43ab2eb4-31ec-4574-ab54-4467fa89d187@27g2000hsf.googlegroups.com> Message-ID: Alan G Isaac wrote: > Can you give me an example of using the returned value? it's for consistency with stream objects that support raw I/O (as described in the PEP). when using buffered I/O, you can ignore it. From stephan at transvection.de Tue Jul 1 08:06:41 2008 From: stephan at transvection.de (Stephan Diehl) Date: Tue, 01 Jul 2008 14:06:41 +0200 Subject: PyPy questions In-Reply-To: References: Message-ID: Allen schrieb: > I read the website of some information about PyPy, and how a translator > translates the RPython code to C/CLI/Java/etc to be compiled to a native > executable or something like that. Would it be possible, in PyPy, to > write such an extension that could easily be compiled to native code > from Python code? Is this functionality planned in a future release of > it? Also, how is the source distributed (If I opt to use it I will end > up compiling it on a system without an initial python install (a scratch > linux system)), so does the source include the generated C code? > > B. Vanderburg II these kind of questions are better asked on pypy-dev. Anyway, at the moment you need a working python installation in order to run the pypy chain. I have to admit that I didn't understand your question, but you should read the pypy documentation on codespeak.net as it will probably answer all of your questions. Alternativly, you might want to join the #pypy channel on freenode Stephan From fredrik at pythonware.com Wed Jul 16 10:14:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 16:14:35 +0200 Subject: Regular expression In-Reply-To: References: Message-ID: Beema shafreen wrote: > How do I write a regular expression for this kind of sequences > > >gi|158028609|gb|ABW08583.1| CG8385-PF, isoform F [Drosophila melanogaster] > MGNVFANLFKGLFGKKEMRILMVGLDAAGKTTILYKLKLGEIVTTIPTIGFNVETVE line.split("|") ? it's a bit hard to come up with a working RE with only a single sample; what are the constraints for the different fields? is the last part free form text or something else, etc. have you googled for existing implementations of the format you're using? From enleverlesX.XmcX at XmclaveauX.com Sat Jul 5 16:57:40 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 5 Jul 2008 22:57:40 +0200 Subject: Python with Ecmascript In-Reply-To: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> Message-ID: <486fe241$0$867$ba4acef3@news.orange.fr> Hi! Ecmascript (Jscript) is Active-Scripting compliant. With PyWin32, you can : - call JScript functions (with parameters) - define pieces of code (& run it) Another way, is to drive Internet-Explorer (via COM). You can set the IE-Windows as invisible, and connect the motor of execution (of JScript). Then, you can : - call JScript functions, with parameters et return ; variables, but also array (<=> lists) - connect to JScripts's objects (for read/write) - write new functions in JScript - etc. @-salutations Michel Claveau From cs at zip.com.au Thu Jul 10 18:37:53 2008 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 11 Jul 2008 08:37:53 +1000 Subject: Determining when a file has finished copying In-Reply-To: <487644F0.9070906@gmail.com> Message-ID: <20080710223753.GA14055@cskk.homeip.net> On 10Jul2008 13:20, Manuel Vazquez Acosta wrote: | Cameron Simpson wrote: | > On 09Jul2008 15:54, Ethan Furman wrote: | >> The solution my team has used is to monitor the file size. If the file | >> has stopped growing for x amount of time (we use 45 seconds) the file is | >> done copying. Not elegant, but it works. | > | > If you know that files appear in sequence (a single serial upload | > process, not multiple uploaders) you can augument this with a check | > that an additional file has started to upload, ergo the current file | > has finished. Of course, only you can decide if this might be relied upon. | | Hum, what about the last file in the sequence? | I think polling file's size maybe a good indicator, as Ethan proposed. Hence the word "augument". It may let you short circuit the time delay, if a new file appears. Obviously it's not enough on its own. -- Cameron Simpson DoD#743 From babacity4 at gmail.com Thu Jul 24 16:51:50 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:51:50 -0700 (PDT) Subject: sextv1 player - Amazing porn video collection Message-ID: <2adc914d-0115-4cc0-8e67-058d9cf9b072@v39g2000pro.googlegroups.com> sextv1 player . >>>>>>>>>>Best Collection of Sextv1 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE sextv1 player VIDEOS<<<<<<<<<<< . sextv1 player From deets at nospam.web.de Mon Jul 28 09:31:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 15:31:26 +0200 Subject: ctypes and how to copy data passed to callback References: <2059b8a4-7651-4c3c-afbf-44caa8605c64@m3g2000hsc.googlegroups.com> Message-ID: <6f603fFa1lhcU1@mid.uni-berlin.de> waldek wrote: > Hi, > > I'm trying to handle data passed to Py Callback which is called from > C dll. Callback passes data to another thread using Queue module and > there the data are printed out. > > If data is printed out in a callback itself it's ok. If I put on > queue and next get from queue in another thread script prints some > trash. Looks like the data is released when callback returned. I tired > to make d = copy.deepcopy(data), but it does not work - I got nothing. > Any idea why it's happening ? > > --------------------- main thread -------- > def callback(data, size): > myqueue.put((data, size)) > > mydll = cdll.MyDLL > cbproto = CFUNCTYPE(c_int, POINTER(c_char), c_int) > mycallback = cbproto(callback) > > mydll.RegisterCallback(mycallback) > > ---------------------------------- thread listener > ---------------------- > > while True: > data, size = myqueue.get() > print "***", data[:size] > > ------------------------------------------------------------------------------ You need to allocate e.g. a bytebuffer using ctypes and then copy the memory area you get passed into that buffer. Otherwise I presume whoever invokes the callback releases the originaly memory block after the callback terminated. Diez From deets at nospam.web.de Sun Jul 27 08:20:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 27 Jul 2008 14:20:09 +0200 Subject: bundling python with application In-Reply-To: References: Message-ID: <6f37fqF97ndoU1@mid.uni-berlin.de> Randall Smith schrieb: > I'd like to bundle Python with my app, which will be targeted at Linux, > Windows and Mac. Discussions I've found about this tend to lead to > py2exe, freeze, etc, but I'd like to do something rather simple and am > seeking advice. > > What I'd like to do is just copy the standard libraries and > executable(s) and adjust the paths in the environment variables. The > libraries and executable(s) would reside in the same directory with the > application so that you could run the application without needing to > install it. The directory might look like this: > > $ ls > > start-app.sh > app_lib/ > python_lib/ > python_bin/ > > > start-app.sh would look like this: > > #!/bin/sh > > PATH="python_bin:$PATH" PYTHON_HOME="./python_lib" python app_lib/start.py > > Of course, there would be a start-app.bat for Windows. > > The PATH is altered to make sure the right python interpreter is found > and PYTHON_HOME makes sure the right (local) libraries are found. > > Can this be done? It might be doable (virtualenv shows it works, you might consider taking a look into it), but I would advise against it. py2exe and py2app for example do a great job to provide a way to distribute software in a way the respective target OS (and their users) are expecting it. For example, OSX uses so-called "application bundles" which py2app (guess where the name comes from...) produces for you. Not using them might cripple you, because e.g. GUI-stuff isn't working properly (or will show an arbitrary icon in the dock, instead of one you chose). Why do you insist on re-inventing a wheel that's rolling fine? Diez From gnewsg at gmail.com Sun Jul 13 22:16:47 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sun, 13 Jul 2008 19:16:47 -0700 (PDT) Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> <487a3c0d$0$32256$9b622d9e@news.freenet.de> Message-ID: <18f16069-aab6-495d-86e2-3080421e52db@79g2000hsk.googlegroups.com> On 13 Lug, 22:35, Miles wrote: > On Sun, Jul 13, 2008 at 3:05 PM, Giampaolo Rodola' wrote: > > On 13 Lug, 19:31, "Martin v. L?wis" wrote: > >> > I understand that heapq is not that efficient to implement timeouts as > >> > I thought at first. > >> > It would have been perfect if there were functions to remove arbitrary > >> > elements withouth needing to re-heapify() the heap every time. > > >> It is efficient for that - you just need to use it correctly. > > >> To remove the nth element from a heap, replace it with the last element, > >> and then _siftup that element: > > >> The time complexity for that operation is O(log(len(heap))). > > The problem is that in order to remove an arbitrary element from a > heap, you usually have to do an O(n) linear search in order to find it > first, since you can't know ahead of time which index an arbitrary > element is at. ?(You can, actually, but only if your heap > implementation somehow notifies the elements of their new index when > it moves them in the heap, which the Python heapq module doesn't do, > so you'd have to write your own heap implementation.) > > > And if instead of removing an element I'd want to change its value? > > E.g.: > > > ?>>> heap = [0, 2, 1, 4, 5, 6, 7, 8, 9] > > ?>>> heapify(heap) > > ?>>> heap > > ?[0, 2, 1, 4, 5, 6, 7, 8, 9] > > ?>>> heap[4] = 12 > > Don't do that; you must first remove the element and then reinsert it. > > -Miles That seems to be slower than re-heapifying() the heap. The code I used (which is probably wrong): def reset(self): """Reschedule this call resetting the current countdown.""" assert not self.cancelled, "Already cancelled" self.timeout = time.time() + self.__delay n = heap.index(self) if n == len(heap) - 1: heap.pop() else: heap[n] = heap.pop() heapq._siftup(heap, n) heapq.heappush(heap, self) Moreover I have the feeling that doing such thing requires a different code whether the new value I use as replacement is lower or higher in comparison to the older one. Am I right? --- Giampaolo http://code.google.com/p/pyftpdlib/ From exarkun at divmod.com Tue Jul 29 13:32:34 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 29 Jul 2008 13:32:34 -0400 Subject: [unittest] Run setUp only once In-Reply-To: <871w1cr49a.fsf@nokile.rath.org> Message-ID: <20080729173234.29191.503309096.divmod.quotient.8288@ohm> On Tue, 29 Jul 2008 19:26:09 +0200, Nikolaus Rath wrote: >Jean-Paul Calderone writes: >> On Tue, 29 Jul 2008 16:35:55 +0200, Nikolaus Rath wrote: >>>Hello, >>> >>>I have a number of conceptually separate tests that nevertheless need >>>a common, complicated and expensive setup. >>> >>>Unfortunately, unittest runs the setUp method once for each defined >>>test, even if they're part of the same class as in >>> >>>class TwoTests(unittest.TestCase): >>> def setUp(self): >>> # do something very time consuming >>> >>> def testOneThing(self): >>> >>> >>> def testADifferentThing(self): >>> >>> >>>which would call setUp twice. >>> >>> >>>Is there any way to avoid this, without packing all the unrelated >>>tests into one big function? >>> >> >> class TwoTests(unittest.TestCase): >> setUpResult = None >> >> def setUp(self): >> if self.setUpResult is None: >> self.setUpResult = computeIt() >> >> ... >> >> There are plenty of variations on this pattern. > > >But at least this variation doesn't work, because unittest apparently >also creates two separate TwoTests instances for the two tests. Isn't >there some way to convince unittest to reuse the same instance instead >of trying to solve the problem in the test code itself? > Eh sorry, you're right, the above is broken. `setUpResult` should be a class attribute instead of an instance attribute. Jean-Paul From robert.rawlins at thinkbluemedia.co.uk Tue Jul 8 08:22:31 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 8 Jul 2008 13:22:31 +0100 Subject: No Exceptions Message-ID: <002901c8e0f5$52a47ca0$f7ed75e0$@rawlins@thinkbluemedia.co.uk> Morning Guys, This morning I've been having a strange issue where my application doesn't appear to raise any exceptions. Even when manually placing code in the application which raises an exception explicitly like: Raise Exception, "This is a test exception" The application doesn't appear to throw it, it will fail to execute any code in the block following the exception but does not throw any exceptions to the command prompt. Any ideas what might be causing this? I've just sent another support request to this list about logging configuration, could the two issues be related? Thank you, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Thu Jul 17 01:27:42 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 17 Jul 2008 17:27:42 +1200 Subject: Problem with MySQLdb and mod_python References: Message-ID: In message , Cyril Bazin wrote: > But it seems, after many tests, that the script stops at the > instruction : "c.execute(requete)" What's the error message? This should be in Apache's error_log file. From pavlovevidence at gmail.com Wed Jul 30 00:52:52 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 29 Jul 2008 21:52:52 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: On Jul 29, 11:17 pm, Terry Reedy wrote: > Carl Banks wrote: > >> As I wrote in the second reply email I sent, check out my integer set > >> recipe on ASPN (and to save you the search: http://code.activestate.com/recipes/466286/). > > > Couple points: > > > 1. Any container type that returns a length that isn't exactly the > > number of elements in it is broken. > > 2. The need for __nonzero__ in this case depends on a limitation in > > the language. > > 3. On the other hand, I will concede that sometimes calculating len is > > a lot more expensive than determining emptiness, and at a basic level > > it's important to avoid these costs. You have found a practical use > > case for __nonzero__. > > I thought of another one: testing whether an iterator is 'empty' (will > raise StopIteration on the next next() (3.0) call) or not. As virtual > collections, iterators generally have neither __len__ or __bool__. But > __bool__ (but only __bool__) can be added to any iterator by wrapping it > with something like the following 3.0 code (not tested): > > class look_ahead_it(): > def __init__(self, iterable): > self.it = iter(iterable) > self.fill_next() > > def __iter__(self): > return self > def __next__(self): > tem = self.next > if tem is self.empty: > raise StopIteration > else: > self.fill_next() > return tem > > empty = object() > def fill_next(self) > try: > self.next = next(self.it) > except StopIteration: > self.next = self.empty > > def __bool__(self): > return self.next is not self.empty Iterators are funny: if there's any reason you should not use "if x" it's because of them. Built-in iterators are always true, so if you're writing a function that accepts an iterable you should never use the "if x" to test whether it's empty, because it fails for a whole class of iterables. However, given that that wart exists, your example does work for "if x" and not with "if len(x)!=0". Then again, it really only works to accommodate faulty code, because no code that expects an iterable should be using that test in the first place. (Unless you wrap every iterable as soon as you get it, but then you're not bound to use __nonzero__.) Carl Banks From paul at boddie.org.uk Sat Jul 26 20:39:43 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 26 Jul 2008 17:39:43 -0700 (PDT) Subject: Pwnie awards References: Message-ID: On 27 Jul, 02:03, a... at pythoncraft.com (Aahz) wrote: > Boy, am I glad we're not listed: > > http://pwnie-awards.org/2008/awards.html An amusing mention, though: 2008-03-03: Core sends proof-of-concept code written in Python. 2008-03-05: Vendor asks for compiler tools required to use the PoC code. 2008-03-05: Core sends a link to http://www.python.org http://pwnie-awards.org/2008/awards.html#lamestvendor Paul From dullrich at sprynet.com Tue Jul 8 11:54:13 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 08 Jul 2008 10:54:13 -0500 Subject: "in"consistency? References: Message-ID: In article , Nick Dumas wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > [1,2] in [1,2,3] checks to see if the list [1,2] is an item in [1,2,3]. > Because the list [1,2,3] only contains the integers 1,2,3, the code > returns a False. Try "[1,2] in [[1,2],[2,3]]" Thanks. I understand how it works for lists and why - I was wondering why it's not the same for strings. > David C. Ullrich wrote: > > Luckily I tried it before saying no, that's > > not how "in" works: > > > >>>> 'ab' in 'abc' > > True > >>>> [1,2] in [1,2,3] > > False > > > > Is there a reason for the inconsistency? I would > > have thought "in" would check for elements of a > > sequence, regardless of what sort of sequence it was... > > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (MingW32) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iEYEARECAAYFAkhyiwEACgkQLMI5fndAv9jbiwCeKMXrAclILJMPro5VuSRgdkvB > cGkAn1igcjFWRQJSwEDOxpk3spzceZGa > =iq8L > -----END PGP SIGNATURE----- -- David C. Ullrich From bignose+hates-spam at benfinney.id.au Wed Jul 2 06:57:00 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 02 Jul 2008 20:57:00 +1000 Subject: beginner's questions - manipulating text files References: <486ABACE.9050103@umbc.edu> Message-ID: <87k5g47dvn.fsf@benfinney.id.au> C?dric Lucantis writes: > Le Wednesday 02 July 2008 01:16:30 Ben Keshet, vous avez ?crit?: > > I am trying to write a script that will search for the second and > > third appearance of the symbol '@' in a file, will read a random > > line between them, and write the line into a new file. > > If the file you're reading is not too big, you can use > file.readlines() which read all the files and returns its content as > a list of lines. Better is to iterate over the file object, getting a line each time. This works regardless of the size of the file, because it doesn't attempt to read the entirety of a large file in at once. > text.find('@') will return the position of the first occurence of > '@', or a negative value if not found. If one is interested only in *whether* text is contained within a string (and is uninterested in its position), the 'in' operator returns a boolean value. Untried code: import random separator = "@" interesting_lines = [] input_file = open("foo.txt") seen_separator_count = 0 for line in input_file: if separator in line: # Count this separator, but don't keep the line. seen_separator_count += 1 continue if seen_separator_count == 2: # We have seen exactly two lines with separators, # so we're interested in the current line. interesting_lines.append(line) if seen_separator_count >= 3: # After seeing three lines with separators, stop reading. break chosen_line = random.choice(interesting_lines) output_file = open("bar.txt", 'w') output_file.write(chosen_line) -- \ ?Smoking cures weight problems. Eventually.? ?Steven Wright | `\ | _o__) | Ben Finney From deanfamily11 at verizon.net Tue Jul 1 15:26:12 2008 From: deanfamily11 at verizon.net (Brandon) Date: Tue, 01 Jul 2008 19:26:12 GMT Subject: Convert string to char array References: <0%uak.283$4a3.73@trnddc04> <4670347e-2531-4449-a171-e352e1053864@r66g2000hsg.googlegroups.com> Message-ID: Thank you both for your help. "Mike Kent" wrote in message news:4670347e-2531-4449-a171-e352e1053864 at r66g2000hsg.googlegroups.com... On Jul 1, 2:49 pm, "Brandon" wrote: > How do I convert a string to a char array? I am doing this so I can edit > the string received from an sql query so I can remove unnecessary > characters. Answering your specific question: Python 2.5.1 (r251:54863, Mar 31 2008, 11:09:52) [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> s = 'hello' >>> l = list(s) >>> l ['h', 'e', 'l', 'l', 'o'] >>> But more generally, you might want to read up on the string methods available to you, such as replace(): http://docs.python.org/lib/string-methods.html From alexnbryan at gmail.com Wed Jul 16 17:50:05 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 14:50:05 -0700 (PDT) Subject: Having trouble with some lists in BeautifulSoup Message-ID: <18497409.post@talk.nabble.com> Okay, what I want to do with this code is to got to thesaurus.reference.com and then search for a word and get the syns for it. Now, I can get the syns, but they are still in html form and some are hyperlinks. But I can't get the contents out. I am not that familiar with BeautifulSoup. So if anyone wants to look over this code(if you run it, it will make a lot more sense) and maybe help me out. side note: if you run it, a list object will print and what I am after is the part that starts:
american... Heres the code: import urllib from BeautifulSoup import BeautifulSoup class defSyn: def __init__(self, word): self.word = word def get_syn(term): soup = BeautifulSoup(urllib.urlopen('http://thesaurus.reference.com/search?q=%s' % term)) balls = soup.findAll('table', {'width': '100%'}) print soup.prettify() for tabs in soup.findAll('table', {'width': '100%'}): yield tabs.findAll('td', {'colspan': '2'}) self.mainList = list(get_syn(self.word)) print self.mainList[2] if You have any further questions I would be happy to answer. -- View this message in context: http://www.nabble.com/Having-trouble-with-some-lists-in-BeautifulSoup-tp18497409p18497409.html Sent from the Python - python-list mailing list archive at Nabble.com. From castironpi at gmail.com Sun Jul 27 23:58:15 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 27 Jul 2008 20:58:15 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: <684cb9e4-309d-4185-883f-35ee1d67ed19@z66g2000hsc.googlegroups.com> On Jul 27, 2:39?pm, Bruno Desthuilliers wrote: > Derek Martin a ?crit : > > It's bad programming, but the world is full of bad programmers, and we > > don't always have the choice not to use their code. ?Isn't one of > > Python's goals to minimize opportunities for bad programming? > > Nope. That's Java's goal. Python's goals are to maximize opportunities > for good programming, which is quite different. +1 QOTW From ggpolo at gmail.com Mon Jul 28 18:33:38 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 28 Jul 2008 19:33:38 -0300 Subject: seemingly simple list indexing problem In-Reply-To: <488E4170.2020804@islandtraining.com> References: <488E4170.2020804@islandtraining.com> Message-ID: On Mon, Jul 28, 2008 at 7:00 PM, Gary Herron wrote: > Guilherme Polo wrote: >> >> On Mon, Jul 28, 2008 at 6:24 PM, Ervan Ensis >> wrote: >> >>> >>> My programming skills are pretty rusty and I'm just learning Python so >>> this >>> problem is giving me trouble. >>> >>> I have a list like [108, 58, 68]. I want to return the sorted indices of >>> these items in the same order as the original list. So I should return >>> [2, >>> 0, 1] >>> >> >> You could simply do this: >> >> a = [108, 58, 68] >> b = sorted(a) >> [b.index(c) for c in a] >> > > Yuck. Slow, and it fails if duplicate list elements exist. It wasn't supposed to be the fastest solution, also, he didn't mention duplicated items. > > Also... This looks like a beginners programming assignment. Let's let > him try it himself. We can offer help rather than full solutions if he has > specific Python questions. > > > > > >> >>> >>> For a list that's already in order, I'll just return the indices, i.e. >>> [56, >>> 66, 76] should return [0, 1, 2] >>> >>> Any help would be appreciated. >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> >> >> >> > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From wolfram.hinderer at googlemail.com Thu Jul 10 17:59:13 2008 From: wolfram.hinderer at googlemail.com (wolfram.hinderer at googlemail.com) Date: Thu, 10 Jul 2008 14:59:13 -0700 (PDT) Subject: Can this program be shortened? Measuring program-length? References: <7Rtdk.16747$N87.3559@nlpi068.nbdc.sbc.com> Message-ID: <2ed6de5b-bf2f-4e3d-94af-c8e6c6a28f95@s50g2000hsb.googlegroups.com> On 10 Jul., 21:57, "r.e.s." wrote: > Can the following program be shortened? ... > > def h(n,m): > E=n, > while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n > return n > h(9,9) > Some ideas... # h is your version def h(n,m): E=n, while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n return n def g(n,m): E=n, while E*m:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n return n def f(n,m): E=n, while E*m:n=h(n+1,m-1);E=(E[0]>0)*(E[0]-1,)*n+E[1:] return n def e(n,m): E=[n] while E*m:n=h(n+1,m-1);E[:1]=(E[0]>0)*[E[0]-1]*n return n # some tests print h(1,1), h(2,1), h(0,2) print g(1,1), g(2,1), g(0,2) print f(1,1), f(2,1), f(0,2) print e(1,1), e(2,1), e(0,2) From kotecha.ravi at googlemail.com Mon Jul 21 17:05:02 2008 From: kotecha.ravi at googlemail.com (Ravi Kotecha) Date: Mon, 21 Jul 2008 14:05:02 -0700 (PDT) Subject: Getting the name of a variable which was used as a function parameter. References: <9e2e64db-d594-408d-9418-b17133f23204@27g2000hsf.googlegroups.com> <6ekbg0F6vgp3U5@mid.uni-berlin.de> Message-ID: <9c24ced1-4a0b-4e04-9ce2-1d730e3d8dd7@d77g2000hsb.googlegroups.com> Of course I wouldn't, it is a total hack, mostly useless but fun. I tried to do it after someone in #python efnet said it was impossible! On Jul 21, 9:56?pm, Marc 'BlackJack' Rintsch wrote: > On Mon, 21 Jul 2008 09:01:10 -0700, Ravi Kotecha wrote: > > I thought this was pretty cool and since I spent 30 mins or so > > goggling before giving up and figuring out myself I thought I'd share > > it with you. > > >>>> def a(a): > > ... ? ? for k,v in sys._getframe(1).f_locals.items(): > > ... ? ? ? ? if id(v) == id(a): > > ... ? ? ? ? ? ? print k > > ... > > >>>> hello = 123 > > >>>> a(hello) > > hello > > > ## pretty cool. > > Or ugly hack. ?Beauty lies in the eye of the beer holder? > > > It's totally useless but I wanted to do it for logging purposes. > > Don't use such things in production code, please. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch From arsyed at gmail.com Tue Jul 22 05:56:32 2008 From: arsyed at gmail.com (arsyed) Date: Tue, 22 Jul 2008 05:56:32 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: <9a2cc7a70807220256k543365d3y3f4832239d955bac@mail.gmail.com> On Tue, Jul 22, 2008 at 5:21 AM, Martin Gregorie wrote: > On Tue, 24 Jun 2008 18:42:15 -0400, John W Kennedy wrote: > >> David Combs wrote: >>> passing >>> *unnamed* functions as args (could Algol 60 also do something like that, >>> via something it maybe termed a "thunk") >> >> No, the "thunks" were necessary at the machine-language level to >> /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. >> > Are you sure about that? > > The first time I ran across the term "thunking" was when Windows 3 > introduced the Win32S shim and hence the need to switch addressing between > 16 bit and 32 bit modes across call interfaces. That was called "thunking" > by Microsoft and even they would surely admit it was a kludge. > > I used Algol 60 on an Elliott 503 and the ICL 1900 series back when it was > a current language. The term "thunking" did not appear in either compiler > manual nor in any Algol 60 language definition I've seen. A60 could pass > values by name or value and procedures by name. That was it. Call by name > is what is now referred to as reference passing. > On Tue, Jul 22, 2008 at 5:21 AM, Martin Gregorie wrote: > On Tue, 24 Jun 2008 18:42:15 -0400, John W Kennedy wrote: > >> David Combs wrote: >>> passing >>> *unnamed* functions as args (could Algol 60 also do something like that, >>> via something it maybe termed a "thunk") >> >> No, the "thunks" were necessary at the machine-language level to >> /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. >> > Are you sure about that? > > The first time I ran across the term "thunking" was when Windows 3 > introduced the Win32S shim and hence the need to switch addressing between > 16 bit and 32 bit modes across call interfaces. That was called "thunking" > by Microsoft and even they would surely admit it was a kludge. > > I used Algol 60 on an Elliott 503 and the ICL 1900 series back when it was > a current language. The term "thunking" did not appear in either compiler > manual nor in any Algol 60 language definition I've seen. A60 could pass > values by name or value and procedures by name. That was it. Call by name > is what is now referred to as reference passing. > Thunk has more than one meaning. The ALGOL 60 usage predates Windows obviously. Also, call-by-name is distinct from call-by-reference. See: http://en.wikipedia.org/wiki/Evaluation_strategy And, for fun with call-by-name: http://en.wikipedia.org/wiki/Jensen%27s_Device http://en.wikipedia.org/wiki/Man_or_boy_test From rNOSPAMon at flownet.com Fri Jul 4 18:30:30 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Fri, 04 Jul 2008 15:30:30 -0700 Subject: Parsing MIME-encoded data in an HTTP request References: <3a11k5-al7.ln1@nb2.stroeder.com> Message-ID: In article <3a11k5-al7.ln1 at nb2.stroeder.com>, Michael Str?der wrote: > Ron Garret wrote: > > I'm writing a little HTTP server and need to parse request content that > > is mime-encoded. All the MIME routines in the Python standard library > > seem to have been subsumed into the email package, which makes this > > operation a little awkward. > > How about using cgi.parse_multipart()? > > Ciao, Michael. Unfortunately cgi.parse_multipart doesn't handle nested multiparts, which the requests I'm getting have. You have to use a FieldStorage object to do that, and that only works if you're actually in a cgi environment, which I am not. The server responds to these requests directly. Anyway, thanks for the idea. rg From mail at timgolden.me.uk Mon Jul 28 11:56:58 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 28 Jul 2008 16:56:58 +0100 Subject: Encoding for Devanagari Script. In-Reply-To: References: Message-ID: <488DEC4A.2040603@timgolden.me.uk> Atul. wrote: > Hi Fredrik and Terry, > > Well I got this on IDLE I think I have done something wrong. > >>>> import codecs >>>> f = open("C:\Documents and Settings\admin\My Documents\corpus\dainaikAikya collected by sushant.txt","r", "utf_8") > > Traceback (most recent call last): > File "", line 1, in > f = open("C:\Documents and Settings\admin\My Documents\corpus > \dainaikAikya collected by sushant.txt","r", "utf_8") > TypeError: an integer is required > > PS: the above code I wrote using the information from the Library > Reference pdf section 4.8 "Codecs". Something wrong I am doing? Please > do let me know. Only slightly. You're importing the codecs module but you're not using it. So you're *actually* using the built-in open function, which doesn't have an encoding parameter. It does have a third param which is to do with the buffer size. Just change your code to use codecs.open ("...") and, I suggest, either use raw strings for your filename (r"c:\docume...") or use the other kind of slash ("c:/documen..."). Otherwise you might run into some problems. TJG From thomas.troeger.ext at siemens.com Thu Jul 31 09:16:38 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Thu, 31 Jul 2008 15:16:38 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> <873alq9r2q.fsf@nokile.rath.org> Message-ID: > That would imply that I cannot create instances of a type, only of > a class that implements the type, wouldn't it? > > But Python denotes 'int' as a type *and* I can instantiate it. Now I start getting confused also ;-) >>> a=5 >>> a.__class__ >>> a.__class__.__class__ >>> dir(a) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] I think in Python everything is implemented as a class which makes sense. AFAIK you can implement a certain interface in a custom class and it behaves like, for example, a builtin integer. But I guess one of the gurus can clarify this matter with an appropriate URL ;-) From robert.rawlins at thinkbluemedia.co.uk Tue Jul 8 08:18:15 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 8 Jul 2008 13:18:15 +0100 Subject: Logger Configuration Message-ID: <001d01c8e0f4$b2c0c900$18425b00$@rawlins@thinkbluemedia.co.uk> Hello guys, I've attached an example of my logging configuration file for you to look at. The problem I'm experiencing is that the log files are not rotating as I would expect them to, they just keep growing and growing. Can you see any reason for this to happen? This is the first time I've used a config file and not just configured the logger programmatically. Thanks guys, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: logging.conf Type: application/octet-stream Size: 391 bytes Desc: not available URL: From steven at REMOVE.THIS.cybersource.com.au Mon Jul 28 21:12:46 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 29 Jul 2008 01:12:46 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <488e4d2d$0$5967$ba624c82@nntp06.dk.telia.net> <009e5e66$0$20313$c3e8da3@news.astraweb.com> Message-ID: On Tue, 29 Jul 2008 00:23:02 +0000, Steven D'Aprano wrote: > Dude. Dude. Just... learn some Python before you embarrass yourself > further. I'm sorry Anders, that was a needlessly harsh thing for me to say. I apologize for the unpleasant tone. Still, __nonzero__ is a fundamental part of Python's behaviour. You should learn about it. -- Steven From gary at byoteki.com Sat Jul 26 14:57:30 2008 From: gary at byoteki.com (Gary Josack) Date: Sat, 26 Jul 2008 14:57:30 -0400 Subject: Simple Path issues In-Reply-To: <7bef6df9-45d6-4ef6-b802-1dd201ec66e3@k30g2000hse.googlegroups.com> References: <7bef6df9-45d6-4ef6-b802-1dd201ec66e3@k30g2000hse.googlegroups.com> Message-ID: <488B739A.5070603@byoteki.com> Brett Ritter wrote: > New to Python, and I have some questions on how to best set up a basic > development environment, particular relating to path issues. > > Note: I am not root on my development box (which is some flavor of > BSD) > > Where should I develop my own modules so as to refer to them in the > standard way. I.E. I want: > import proj > > to work regardless of my current working directory, and to function as > if "proj" were a core or third-party module. > > I saw that I can set PYTHONPATH, but that seems sub-prime. I noted > that in installing pysqlite (the local installation of python is 2.4) > that I had it install in a lib under my home dir...should I use that > locale? > > What is the command to tell me what directories python is checking in? > > While I'm at it, what is the best (read: standard) locale to stick my > test cases? same dir as my project? A subdir? > > Thanks in advance > -- > http://mail.python.org/mailman/listinfo/python-list > sys.path is a list that will tell you where python is looking. You can append to this in your scripts to have python look in a specific directory for your own modules. Thanks, Gary M. Josack From ojeeves at gmail.com Tue Jul 1 09:13:57 2008 From: ojeeves at gmail.com (oj) Date: Tue, 1 Jul 2008 06:13:57 -0700 (PDT) Subject: recursive import Message-ID: <54205cc0-8fc6-41f3-86bc-1f88b911bc62@f36g2000hsa.googlegroups.com> Hi, I'm just toying around with some ideas at the moment. Is there an easy and safe way to recursivly import all modules under a particular namespace? Say, I had modules: foo foo.bar foo.bar.baz foo.baz bar bar.baz I want to import all the modules in the foo namespace, so the first four modules in that list. Other then having those modules explicitly import their children, or explicitly importing them all from where I want to use them, can I do this? Should I do this? The idea is that function decorates 'register' functions in those modules, so they become available without having to have a list of all the modules that contain them, and without all the modules necessarily needing to know about each other. From norseman at hughes.net Wed Jul 16 13:28:46 2008 From: norseman at hughes.net (norseman) Date: Wed, 16 Jul 2008 10:28:46 -0700 Subject: how can i save my command prompt screen? Message-ID: <487E2FCE.6070508@hughes.net> Ty hensons wrote: > how can i save my command prompt screen? ============================================== That by itself leaves lots of questions. Taken literally to be the "box" then: In Microsoft use the "Print Screen" followed by mspaint and Edit/paste (Or SHIFT-PrintScreen if whole screen showed up, I forget which it is. One does just the box that is hot while the other gets all) In Unix use xwd. See man xwd and xwud. Also man convert with box open and text you want for show'n'tell visible xwd>screen_1.xwd (click in box of choice) to view results: xwud Vanam wrote... > I want to know whether is there anything that has > to be installed in addition to python 2.5 > > from gasp import * You have to install the 'gasp' package too. https://launchpad.net/gasp-code/stable-0.1.x/0.1.1 -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From bruno.desthuilliers at gmail.com Tue Jul 1 16:46:48 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Tue, 1 Jul 2008 13:46:48 -0700 (PDT) Subject: Please check my understanding... References: Message-ID: <3e82eab6-6df1-4a16-83d8-96a22ad247cf@k37g2000hsf.googlegroups.com> On 1 juil, 21:35, Tobiah wrote: > list.append([1,2]) will add the two element list as the next > element of the list. list.append(obj) will add obj as the last element of list, whatever type(obj) is. > list.extend([1,2]) is equivalent to list = list + [1, 2] Not quite. The second statement rebinds the name list (a very bad name BTW but anyway...) to a new list object composed of elements of the list object previously bound to the name list and the elements of the anonymous list object [1, 2], while the first expression modifies the original list object in place. The results will compare equal (same type, same content), but won't be identical (not the same object). A better definition for list.extend(iterable) is that it is equivalent to: for item in iterable: list.append(item) The difference is important if list is bound to other names. A couple examples: a = [1, 2, 3} b = a # b and a points to the same list object b is a => True a.append(4) print b => [1, 2, 3, 4] b.extend([5, 6]) print a => [1, 2, 3, 4, 5, 6] a = a + [7, 8] print b => [1, 2, 3, 4, 5, 6] print a => [1, 2, 3, 4, 5, 6, 7, 8] a is b => False def func1(lst): lst.extend([9, 10]) print lst def func2(lst): lst = lst + [11, 12] print lst func1(a) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print a => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] func2(a) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] print a => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > Is that the only difference? cf above. > From the manual: > > s.extend(x) | same as s[len(s):len(s)] = x > > But: (python 2.5.2) > > >>> a > [1, 2, 3] > >>> a[len(a):len(a)] = 4 > > Traceback (most recent call last): > File "", line 1, in > TypeError: can only assign an iterable And if you try with extend, you'll also have a TypeError: a.extend(4) => Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not iterable list.extend expects an iterable, and so does slice assignment. You want: a[len(a):len(a)] = [4] > > Also, what is the difference between list[x:x] and list[x]? The first expression refers to the *sublist* starting at x and ending one element before x. Of course, if x == x, then it refers to an empty list !-) >>> a[3:3] [] >>> a[1:3] [2, 3] >>> a[0:2] [1, 2] >>> a[0:1] [1] >>> The second expression refers to the *element* at index x. HTH From mnordhoff at mattnordhoff.com Sun Jul 6 21:19:58 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 07 Jul 2008 01:19:58 +0000 Subject: mirroring files and data via http In-Reply-To: References: Message-ID: <48716F3E.3020509@mattnordhoff.com> Steve Potter wrote: > I'm working on a project to create a central administration interface > for several websites located on different physical servers. > > You can think of the websites as a blog type application. My > administration application will be used to create new blog posts with > associated media (images, etc..) > > So I am thinking to setting up a script on each of the sites to "phone > home" once per day and download any new posts and media files. > > I am thinking of transmitting the post data in an xml format that > could then be decoded an recorded into the database on the slave > site. Are there any easy ways to encode a python dictionary to and > from xml? > > For the media files I am thinking that the administration interface > would also provide an xml file with a list of all of the media files > required along with an http path to retrieve them and a checksum of > some sort to verify that they were downloaded correctly. > > Basically I am trying to figure out if anything already exists to > perform some of these functions or if I have to make them from > scratch. I know none of it should be too hard, but I hate to re- > invent the wheel. > > Thanks, > > Steven Potter It sounds like JSON would be perfect for this. For working with it in Python, the simplejson module is popular: -- From jcd at sdf.lonestar.org Tue Jul 15 14:48:18 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 15 Jul 2008 14:48:18 -0400 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: <1216147698.27311.12.camel@aalcdl07.lib.unc.edu> On Tue, 2008-07-15 at 14:37 -0400, Victor Noagbodji wrote: > Hello, > > what's the difference between these two statement? And which one should one use? > Aside: Please include all relevant information in the *body* of your post, not just the subject header. The two statements in question are: if name is not None: and if name: The difference? name='' if name is not None: print "name is not None." if name: print "name is." Give it a whirl. Cheers, Cliff From bdesth.quelquechose at free.quelquepart.fr Sun Jul 27 14:37:30 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Jul 2008 20:37:30 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> <5d3729f0-6e5d-4e3f-b4ed-e25f8ebc655f@q5g2000prf.googlegroups.com> <43d32584-e762-4578-82d9-0d4395bb4138@k36g2000pri.googlegroups.com> Message-ID: <488cdc61$0$7006$426a74cc@news.free.fr> Lawrence D'Oliveiro a ?crit : > In message > <43d32584-e762-4578-82d9-0d4395bb4138 at k36g2000pri.googlegroups.com>, > s0suk3 at gmail.com wrote: > >> "Support OO but it doesn't have to"? That sounds like saying that in >> some Python implementations you'll be able to use OO, but that you >> just might bump into a Python distribution ... > > Change "distribution" to "program" and you're on the right track. Since just everything that can be bound to a name is actually an object, I don't see how you could do anything in Python without using objects. Now if what you meant is that nothing in Python forces you into designing your program the OO way, then Java is not an OOPL neither (never seen a Java program where you have classes with only static methods and classes with only public attributes - IOW, functions and structs ?). From fetchinson at googlemail.com Sat Jul 5 17:40:12 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 5 Jul 2008 14:40:12 -0700 Subject: Python with Ecmascript In-Reply-To: <486fe241$0$867$ba4acef3@news.orange.fr> References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <486fe241$0$867$ba4acef3@news.orange.fr> Message-ID: > Ecmascript (Jscript) is Active-Scripting compliant. > With PyWin32, you can : > - call JScript functions (with parameters) > - define pieces of code (& run it) > > Another way, is to drive Internet-Explorer (via COM). You can set the > IE-Windows as invisible, and connect the motor of execution (of > JScript). Then, you can : > - call JScript functions, with parameters et return ; variables, but > also array (<=> lists) > - connect to JScripts's objects (for read/write) > - write new functions in JScript > - etc. Is there a way to do similar things on linux? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From socyl at 987jk.com.invalid Fri Jul 18 11:49:49 2008 From: socyl at 987jk.com.invalid (kj) Date: Fri, 18 Jul 2008 15:49:49 +0000 (UTC) Subject: x, = y (???) References: Message-ID: In Matthew Woodcraft writes: >kj wrote: >> I still don't get it. If we write >> >> y = 'Y' >> x, = y >> >> what's the difference now between x and y? And if there's no >> difference, what's the point of performing such "unpacking"? >If y really is is a string, I think it's likely that the line you came >across was a typo. OK, this is the best explanation I've seen for the code I'm talking about. This code may be found at: http://norvig.com/sudo.py in the definition of the function eliminate. Here's the fragment: elif len(values[s]) == 1: ## If there is only one value (d2) left in square, remove it from peers d2, = values[s] Now, in the assignment, values[s] *is* a string of length 1. So this assignment appears to me entirely equivalent (in its ultimate effect) to the more straightforward d2 = values[s] ...but, since I'm a noob, I thought I'd ask :-) Thanks! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From invalid at nowhere.invalid.org Tue Jul 15 05:09:54 2008 From: invalid at nowhere.invalid.org (Alex Marandon) Date: Tue, 15 Jul 2008 10:09:54 +0100 Subject: Testing for Internet Connection In-Reply-To: References: Message-ID: <1216113021.24038.0@proxy02.news.clara.net> Alexnb wrote: > I am wondering, is there a simple way to test for Internet connection? If > not, what is the hard way :p Trying to fetch the homepage from a few major websites (Yahoo, Google, etc.)? If all of them are failing, it's very likely that the connection is down. You can use urllib2 [1] to accomplish that. [1] From moijes12 at gmail.com Fri Jul 11 04:23:07 2008 From: moijes12 at gmail.com (moijes12) Date: Fri, 11 Jul 2008 01:23:07 -0700 (PDT) Subject: importing .dll in a python file Message-ID: <4dfaeb7b-8e7e-4f0b-80a8-ed24ed1c46d3@x35g2000hsb.googlegroups.com> Hi I need to use a .dll from a python script.I have installed pywin.But in the program ,which is like: import dllName I get : Import Error : DLL not found Please suggest a solution! From arnimavidyarthy at gmail.com Fri Jul 18 11:01:56 2008 From: arnimavidyarthy at gmail.com (arni) Date: Fri, 18 Jul 2008 08:01:56 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> Message-ID: <292d640d-1c84-4f7c-8b57-1db23e53aeff@f1g2000prb.googlegroups.com> On Jul 18, 7:51?pm, Andrew Freeman wrote: > Andrew Freeman wrote: > > oj wrote: > >> On Jul 18, 12:10 pm, John Machin wrote: > > >>> On Jul 18, 9:05 pm, oj wrote: > > >>>> On Jul 18, 11:33 am, arnimavidyar... at gmail.com wrote: > > >>>>> Hi, > >>>>> ? ? ? ? Hi, > >>>>> ? ? ? ? I am taking a string as an input from the user and it > >>>>> should only > >>>>> contain the chars:L , M or R > >>>>> ? ? ? ? I tried the folllowing in kodos but they are still not > >>>>> perfect: > >>>>> ? ? ? ? [^A-K,^N-Q,^S-Z,^0-9] > >>>>> [L][M][R] > >>>>> [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > >>>>> ? ? ? ? For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' > >>>>> .like that. > >>>>> ? ? ? ? regards, > >>>>> SZ > >>>>> ? ? ? ? The string may or may not have all the three chars. > > >>>> With regular expressions, [^LRM] matches a character that isn't L, R > >>>> or M. So: > >>>> ? ? ? import re > >>>> ? ? ? var = "LRLRLRLNR" > >>>> ? ? ? if re.search(r'[^LRM]', var): > >>>> ? ? print "Invalid" > > >>> Fails if var refers to the empty string. > > >> No it doesn't, it succeeds if var is an empty string. An empty string > >> doesn't contain characters that are not L, R or M. > > >> The OP doesn't specify whether an empty string is valid or not. My > >> interpretation was that an empty string would be valid. > > > Why not just use * instead of + like: > > > if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of > > string; $ means end of string > > ? ?print "Invalid" > > > This will *only* print invalid when there is a character other than L, > > R, or M or a empty string. > > Sorry, forget the beginning and ending markers, I just tried it out, it > doesn't work. > use this instead: > > if re.search(r'[^LRM]*', var): > ? ?print "Invalid" I was using kodos to check the regex.I should have used the IDE instead.Thanks a lot again. From robert.rawlins at thinkbluemedia.co.uk Wed Jul 16 07:38:50 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Wed, 16 Jul 2008 12:38:50 +0100 Subject: Logging in __del__() In-Reply-To: References: <17056.2125546441$1216121658@news.gmane.org> Message-ID: <011001c8e738$8483bcb0$8d8b3610$@rawlins@thinkbluemedia.co.uk> Hi Vinay, > Python uses reference counting with a cycle detector, but the > detector's behaviour is different if there are finalizers (__del__) - > see > > http://www.python.org/doc/ext/refcounts.html > Thank you for the link, that certainly explains a great deal. So, am I right to assume that python will still handle its garbage disposal if I implement __del__(), it just handles circular references in a slightly different way, but to the same effect. Right? Cheers, Robert From xkenneth at gmail.com Mon Jul 7 17:39:36 2008 From: xkenneth at gmail.com (xkenneth) Date: Mon, 7 Jul 2008 14:39:36 -0700 (PDT) Subject: Emacs/Python Essentials? Message-ID: What does everyone consider essential for emacs python dev? Regards, Ken From moneymakecash2 at gmail.com Thu Jul 24 13:18:28 2008 From: moneymakecash2 at gmail.com (MERLIN) Date: Thu, 24 Jul 2008 10:18:28 -0700 (PDT) Subject: Free Online Trading Courses - Online Trading Academy - Stock Trading ... Message-ID: <32d526d4-785b-4f3b-b8f7-cbaf907d7f08@v39g2000pro.googlegroups.com> Free Online Trading Courses - Online Trading Academy - Stock Trading ... ____________________ http://dayonlinetrading.blogspot.com _________________ From stefan_ml at behnel.de Thu Jul 31 01:59:28 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 31 Jul 2008 07:59:28 +0200 Subject: Unicode characters, XML/RSS In-Reply-To: <832add51-92e1-4420-9279-5b503b453869@u6g2000prc.googlegroups.com> References: <832add51-92e1-4420-9279-5b503b453869@u6g2000prc.googlegroups.com> Message-ID: <489154C0.3060401@behnel.de> Adam W. wrote: > File "C:\Python25\lib\xml\sax\expatreader.py", line 207, in feed > self._parser.Parse(data, isFinal) > File "C:\Users\Adam\Desktop\Rev3 DL\XMLWorkspace.py", line 51, in > characters > self.data.append(string) > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in > position 236: ordinal not in range(128) You seem to be doing an implicit conversion from a unicode string to a byte string, maybe by concatenating ('+' operator) strings of different types or by writing it out into a file (or printing it, or ...) - I don't know what self.data is or does, since you didn't provide any code. Stefan From siona at chiark.greenend.org.uk Mon Jul 28 10:15:54 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 28 Jul 2008 15:15:54 +0100 (BST) Subject: xml.dom's weirdness? References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> <488C3645.8060304@behnel.de> <488c75ee$0$29448$9b4e6d93@newsspool4.arcor-online.net> Message-ID: Stefan Behnel wrote: >Using my system Python (2.5.1 on Ubunutu Gutsy): > > $ strace -e open python -c '' 2>&1 | wc -l > 551 > $ strace -e open python -c '<><<' 2>&1 | wc -l > 4631 > >Using a self-built Python I have lying around: > > $ strace -e open python2.3 -c '' 2>&1 | wc -l > 210 > $ strace -e open python2.3 -c '<><<' 2>&1 | wc -l > 214 > > $ strace -e open python2.6 -c '' 2>&1 | wc -l > 138 > $ strace -e open python2.6 -c '<><<' 2>&1 | wc -l > 142 > >Blame Ubuntu/Debian. I'd be wary about including Debian in that blame. Using 4.0 here, with a 2.4.4 default and a 2.5.0 straight from the package: $ strace -e open python -c '' 2>&1 | wc -l 171 $ strace -e open python -c '<><<' 2>&1 | wc -l 175 $ strace -e open python2.5 -c '' 2>&1 | wc -l 105 $ strace -e open python2.5 -c '<><<' 2>&1 | wc -l 109 -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From sjmachin at lexicon.net Tue Jul 1 20:29:52 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 1 Jul 2008 17:29:52 -0700 (PDT) Subject: convert unicode characters to visibly similar ascii characters References: <17d4c282-8606-4d29-9e71-d34f5e6d13bb@m44g2000hsc.googlegroups.com> Message-ID: On Jul 2, 9:55 am, Jim wrote: > Peter Bulychev wrote: > > I want to convert unicode character into ascii one. > > You have to make some arbitrary choices of what to translate. Based > on some materials on effbot's site, and a recipe, I made > ftp://alan.smcvt.edu/hefferon/unicode2ascii.py > which has at least some of what you are looking for. > $ grep HYPHEN unicode2ascii.py > u'\N{SOFT HYPHEN}':u'-', > u'\N{HYPHEN}':u'-', > u'\N{NON-BREAKING HYPHEN}':u'-', > u'\N{SOFT HYPHEN}': '-', > No doubt I have some terrible gaffes and some things missing. > Corrections appreciated. Comments on the above grep output: 1. You have SOFT HYPHEN twice, mapping it to u'-' and '-' 2. The idea of a soft hyphen is as a hint to a hyphenator about where to insert a hyphen if one is necessary and the hyphenator is suspected of acting cluelessly without the hint. IMHO, asciification should substitute u'', not u'-'. 3. Read PEP 8. s/:/: / Cheers, John From martinnorth at westnet.com.au Fri Jul 11 21:02:54 2008 From: martinnorth at westnet.com.au (martinnorth) Date: Sat, 12 Jul 2008 11:02:54 +1000 Subject: MySQLdb will only import for root In-Reply-To: <6dothnF3lqqmU1@mid.uni-berlin.de> References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> <6dothnF3lqqmU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > martinnorth schrieb: >> Hi, >> >> I am running Python and MySQL on Ubuntu and have installed MySQLdb. If >> I try to import MySQLdb I get the following error: >> >> ActivePython 2.5.2.2 (ActiveState Software Inc.) based on >> Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08) >> [GCC 3.3.1 (SuSE Linux)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import MySQLdb >> Traceback (most recent call last): >> File "", line 1, in >> ImportError: No module named MySQLdb >> >> But if I lrun python as the root user it imports fine. Can anyone >> suggest what might be wrong with the installation? Or is there nothing >> wrong? I haven't seen any examples that mentioned being root to import >> a module. > > Try importing sys and printing out sys.path both with a "normal" account > and the root-account, to see if there are any differences. And of course > make sure both actually use the same interpreter. > > Beyond that, you are right: there is no root-only-importing. > > Diez Now that I look at, it appears it might not be the same interpreter. When running python as root I get: Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. Which is completely different from when I'm a normal user (see original post). And yes, sys.path is different. Being somewhat new to python and linux, how would I go about fixing this? How do I get a normal user to run the same interpreter? Is it to do with my PATH? Martin From ojeeves at gmail.com Wed Jul 2 08:55:34 2008 From: ojeeves at gmail.com (oj) Date: Wed, 2 Jul 2008 05:55:34 -0700 (PDT) Subject: n00bie wants advice. References: <8757c630-0518-4351-a319-124ced0ac92c@w4g2000prd.googlegroups.com> Message-ID: <08fa3c12-07bf-467f-a098-c4c3b373a1a3@y38g2000hsy.googlegroups.com> On Jul 2, 7:25?am, bsag... at gmail.com wrote: > This simple script writes html color codes that can be viewed in a > browser. ?I used short form hex codes (fff or 000, etc) and my list > has only six hex numbers otherwise the results get rather large. I > invite criticism as to whether my code is "pythonic". Are there other > ways to generate the hex combos besides the nested "for" loops? Thanks > in advance, Bill > > list = ['3','6','9','b','d','f'] > > s = '\n' > > for a in list: > ? ? ? ? for b in list: > ? ? ? ? ? ? ? ? for c in list: > ? ? ? ? ? ? ? ? ? ? ? ? s += '

'+ a + b + c +'

> \n' > > s += '' > > f = open('c:/x/test.htm', 'w') > f.write(s) > f.close() You could write the loop like this: for red, green, blue in [(r, g, b) for r in list for g in list for b in list]: s += blah blah blah but, arguably, that isn't easier to read or understand. It's a matter of taste, I guess. As has already been mentioned, list is not a good name, because it is already used. Also, personally, I find it easier to read strings that aren't constructed with concatenation, but using pythons string formatting gubbins: '

' % (red, green, blue) Again, I think this is mostly personal preference. From deets at nospam.web.de Wed Jul 2 16:56:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Jul 2008 22:56:44 +0200 Subject: Run interpreter in emacs? In-Reply-To: References: Message-ID: <6d28ccFftk4U1@mid.uni-berlin.de> defn noob schrieb: > Can I run the python interpreter from with in Emacs? Yes, the python-mode supports that. Make sure to install the proper one http://www.emacswiki.org/cgi-bin/wiki/PythonMode > Do i have to change anything then? or is it by default? it already > syntax-highlights python-files. See above for docs. Diez From noagbodjivictor at gmail.com Tue Jul 15 15:44:25 2008 From: noagbodjivictor at gmail.com (Victor Noagbodji) Date: Tue, 15 Jul 2008 15:44:25 -0400 Subject: 'if name is not None:' v. 'if name:' In-Reply-To: References: Message-ID: >>what's the difference between these two statement? >one checks if the given object is not None, the other checks if it's a true value: >http://docs.python.org/ref/Booleans.html#Booleans >>And which one should one use? >depends on what you want to test for, of course. > > Well that's exactly why I'm asking. Since None returns False in if statements. Why do people use if name is not None: instead of simply writing if not name? -- NOAGBODJI Paul Victor From amdescombes at gmail.com Mon Jul 21 12:50:29 2008 From: amdescombes at gmail.com (AMD) Date: Mon, 21 Jul 2008 18:50:29 +0200 Subject: scanf in python Message-ID: <4884be5e$0$19722$426a74cc@news.free.fr> Hello, I often need to parse strings which contain a mix of characters, integers and floats, the C-language scanf function is very practical for this purpose. I've been looking for such a feature and I have been quite surprised to find that it has been discussed as far back as 2001 but never implemented. The recommended approach seems to be to use split and then atoi or atof or to use regex and then atoi and atof. Both approaches seem to be a lot less natural and much more cumbersome than scanf. If python already has a % string operator that behaves like printf, why not implement either a %% or << string operator to behave like scanf, use could be like the followng: a, b, c = "%d %f %5c" %% "1 2.0 abcde" or a, b, c = "%d %f %5c" << "1 2.0 abcde" %% is closer to the % operator << seems more intuitive to me either of this methods seems to me much simpler than: lst = "1 2;0 abcde".split() a = int(lst[0]) b = float(lst[1]) c = lst[2] or even worse when using regular expressions to parse such simple input. I like python because it is concise and easy to read and I really think it could use such an operator. I know this has been discussed before and many times, but all previous threads I found seem to be dead and I would like to invite further investigation of this topic. Cheers, Andr? M. Descombes From larry.bates at websafe.com` Mon Jul 28 13:26:03 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 28 Jul 2008 12:26:03 -0500 Subject: Suggestions for creating a PDF table In-Reply-To: References: Message-ID: Kirk Strauser wrote: > Short question: > > Is there a good library for generating HTML-style tables with the equivalent > of colspans, automatically sized columns, etc. that can render directly to > PDF? > > Longer question: > > I'm re-doing a big chunk of locally-written code. I have a > report-generating function that takes a list of lists of lists as input and > returns either a PDF, an HTML table, or an Excel spreadsheet as requested. > For example, input might look like: > > makereport('html', > headers=['Invoice number', 'Customer', 'Price'], > data=[ > [['123', 'John Doe', '$50.00'], > ['Ordered on 2008-01-01 via the website']], > [['124', 'Peter Bilt', '$25.99'], > ['Mail via African swallow']] > ]) > > This would result in HTML like: > > > > > > > > > > > > > > > > > > > > > > > >
Invoice numberCustomerPrice
123John Doe$50.00
Ordered on 2008-01-01 via the website
124Peter Bilt$25.99
Mail via African swallow
> > Note particularly how the explanatory notes for each invoice are similar in > appearance to the "primary" report lines they're associated with. > > Now, I have a similar transformation to PDF via pdflatex. This works fairly > well but requires a bunch of temp files and subprocesses, and I've never > been 100% happy with the LaTeX output (you have to calculate your own > column widths, for instance). Since I plan to re-write this anyway, I'd > like to find a more widely used library if one was available. > > ReportLab seemed *almost* perfect, except that it doesn't support colspans. > As I hope I demonstrated in the example, most of our reports depend on that > ability. > > So, again, any thoughts on a PDF generator that can generate tables with the > same kind of flexibility as HTML? It does support the equivalent of colspans. See page 75 of the userguide manual. -Larry From mrkafk at gmail.com Fri Jul 11 13:02:15 2008 From: mrkafk at gmail.com (mk) Date: Fri, 11 Jul 2008 19:02:15 +0200 Subject: Using SWIG to build C++ extension Message-ID: Hello, I'm having terrible problems building C++ extension to Python 2.4 using SWIG. I'd appreciate if somebody knowledgeable at the subject took a look at it. swig-1.3.29, g++ (GCC) 4.1.1 20070105 (Red Hat 4.1.1-52). I used following commands to build C++ extension: # swig -c++ -python edit_distance.i # c++ -c edit_distance.c edit_distance_wrap.cxx edit_distance.cpp -I. -I/usr/include/python2.4 Linux RH (9.156.44.105) root ~/tmp # c++ -c edit_distance.c edit_distance_wrap.cxx edit_distance.cpp -I. -I/usr/include/python2.4 c++: edit_distance.cpp: No such file or directory edit_distance_wrap.cxx: In function ?PyObject* _wrap_edit_distance(PyObject*, PyObject*)?: edit_distance_wrap.cxx:2579: error: ?string? was not declared in this scope edit_distance_wrap.cxx:2579: error: ?arg1? was not declared in this scope edit_distance_wrap.cxx:2580: error: ?arg2? was not declared in this scope edit_distance_wrap.cxx:2597: error: expected type-specifier before ?string? edit_distance_wrap.cxx:2597: error: expected `>' before ?string? edit_distance_wrap.cxx:2597: error: expected `(' before ?string? edit_distance_wrap.cxx:2597: error: expected primary-expression before ?>? token edit_distance_wrap.cxx:2597: error: expected `)' before ?;? token edit_distance_wrap.cxx:2605: error: expected type-specifier before ?string? edit_distance_wrap.cxx:2605: error: expected `>' before ?string? edit_distance_wrap.cxx:2605: error: expected `(' before ?string? edit_distance_wrap.cxx:2605: error: expected primary-expression before ?>? token edit_distance_wrap.cxx:2605: error: expected `)' before ?;? token What's weird is that I _did_ use std:: namespace prefix carefully in the code: #include #include #include const unsigned int cost_del = 1; const unsigned int cost_ins = 1; const unsigned int cost_sub = 1; unsigned int edit_distance( std::string& s1, std::string& s2 ) { const size_t len1 = s1.length(), len2 = s2.length(); std::vector > d(len1 + 1, std::vector(len2 + 1)); for(int i = 1; i <= len1; ++i) for(int j = 1; j <= len2; ++j) d[i][j] = std::min(d[i - 1][j] + 1, std::min(d[i][j - 1] + 1, d[i - 1][j - 1] + (s1[i - 1] == s2[j - 1] ? 0 : 1))); return d[len1][len2]; } Ok, anyway I fixed it in the generated code (edit_distance_wrap.cxx). It compiled to .o file fine then. It linked to _edit_distance.so as well: # c++ -shared edit_distance_wrap.o -o _edit_distance.so But now I get import error in Python! Linux RH root ~/tmp # python Python 2.4.3 (#1, Dec 11 2006, 11:38:52) [GCC 4.1.1 20061130 (Red Hat 4.1.1-43)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import edit_distance Traceback (most recent call last): File "", line 1, in ? File "edit_distance.py", line 5, in ? import _edit_distance ImportError: ./_edit_distance.so: undefined symbol: _Z13edit_distanceRSsS_ What did I do to deserve this? :-) edit_distance.i file just in case: %module edit_distance %{ #include "edit_distance.h" %} extern unsigned int edit_distance(string& s1, string& s2); From vinay_sajip at yahoo.co.uk Fri Jul 18 11:07:26 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 18 Jul 2008 08:07:26 -0700 (PDT) Subject: Unusual Exception Behaviour References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> <8904.90077804333$1216313689@news.gmane.org> <006001c8e831$5c1487b0$143d9710$@rawlins@thinkbluemedia.co.uk> <1214.94685668058$1216317006@news.gmane.org> Message-ID: <1e6def2a-9c44-419e-a450-5fe596c5e3c0@j1g2000prb.googlegroups.com> On Jul 18, 12:03 pm, "Robert Rawlins" wrote: > > Yeah it's got me a little bemused to be honest, I've tried playing around > with configuration options this morning and not been able to achieve > anything that works properly. > The logging configuration functionality provided by fileConfig is all- or-nothing, i.e. it does not support incremental configuration. Do you know if any libraries you depend on use fileConfig? If you use programmatic configuration only, and don't use fileConfig at all, does everything work as expected? Regards, Vinay Sajip From mtobis at gmail.com Fri Jul 25 12:23:38 2008 From: mtobis at gmail.com (Michael Tobis) Date: Fri, 25 Jul 2008 09:23:38 -0700 (PDT) Subject: Calling external program from within python References: <6eu684F91muhU1@mid.uni-berlin.de> <042e46cf-8ee8-4dd0-bc2b-716d588f8e83@o40g2000prn.googlegroups.com> Message-ID: <296ec449-831e-4f1f-9082-5ad4991dfc04@i20g2000prf.googlegroups.com> These answers are too elaborate and abstract for the question. Emmanouil, Here is a program "myprog" which takes input and writes output to a file. It happens to be python but it could be anything. ##### #!/usr/bin/env python a = int(raw_input("enter thing 1 ")) b = int(raw_input("enter thing 2 ")) c = raw_input("enter output file name ") f = open(c,"w") f.write("answer is %s\n" % str(a + b)) f.close() ##### Here is python code which runs that program ##### import os f = os.popen("/path/to/myprog","w") f.write("3\n4\noutputname\n") #can also do three separate writes if that is more convenient f.close() ##### For some reason os.popen is deprecated in favor of the more verbose subprocess.Popen, but this will work for a while. Here is an even simpler approach that will take you a long way. This should be very easy to understand. ##### import os params = open("temp","w") params.write("3\n") params.write("4\n") params.write("outputname2\n") params.close() os.system("/path/to/myprog < temp") ##### If you want python to pick up the stdout of your program as well look into popen2. Try basing your solution on those and if you have any problems let us know what they are. In most cases such as you describe these will work. mt From 5lvqbwl02 at sneakemail.com Wed Jul 30 16:05:24 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Wed, 30 Jul 2008 13:05:24 -0700 (PDT) Subject: static variables in Python? References: Message-ID: <413b5eb3-27fd-40a3-962f-027ca1ad7b39@o40g2000prn.googlegroups.com> kj wrote: > Yet another noob question... > > Is there a way to mimic C's static variables in Python? Or something > like it? The idea is to equip a given function with a set of > constants that belong only to it, so as not to clutter the global > namespace with variables that are not needed elsewhere. > > For example, in Perl one can define a function foo like this > > *foo = do { > my $x = expensive_call(); > sub { > return do_stuff_with( $x, @_ ); > } > }; > > In this case, foo is defined by assigning to it a closure that has > an associated variable, $x, in its scope. > > Is there an equivalent in Python? > I found the following link addressing this problem several different ways. My favorite (trickiest) way is using decorators... http://www.daniweb.com/code/snippet501.html From __peter__ at web.de Sat Jul 12 02:19:13 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Jul 2008 08:19:13 +0200 Subject: palindrome function References: <1802296d-6822-4682-8a79-d468c42395e6@k30g2000hse.googlegroups.com> Message-ID: Denis Kasak wrote: > Basically, it reverses the list in place, so it modifies the list which > called it. It does not return a /new/ list which is a reversed version > of the original, as you expected it to. Since it doesn't return anything > explicitly, Python makes it return None. Hence, the comparison you are > doing is between the original list and a None, which is False, naturally. > Try this: > > spam = ['a', 'n', 'n', 'a'] > eggs = spam[:] > if spam.reverse() == eggs: > print "Palindrome" Your explanation is correct, but your example code compares None to ['a', 'n', 'n', 'a'] and therefore won't print "Palindrome", either. Peter From tjreedy at udel.edu Tue Jul 22 13:58:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 22 Jul 2008 13:58:27 -0400 Subject: Question about admin rights and IDLE In-Reply-To: References: Message-ID: Murphy.MarkS at epamail.epa.gov wrote: > Hi All, > > Apologies in advance for a potentially redundant posting -- I sent a > similar question to the help box yesterday. > > I have a Geographic Info System (GIS) user that is having problems > editing with Python IDLE on a WindowsXP machine unless she has admin > rights. I had initially thought there might be a place where you can > change the 'user rights' settings in Python, but wasn't able to find it. > So, I did a fresh install of Python 2.5.1 and told it to be available to > all users during the install process. The problem is that IDLE still > seems to be available only to the person who has admin rights on a given > machine. Can anybody make sense of this and help me fix it? I have both 2.5.2 and 3.0b2 loaded for all users on stock xp with all upgrades. I put /Python25 and /Python30 under Program Files instead of C:. As normal non-admin user, I can edit files in ./misc (added by me) under either, or in ./Lib/site-packages/my_package or, of course, under My Documents. You did not specify the 'problems'. If it is saving (which is required to run a file), then perhaps your user is trying to save in an admin-only directory. If IDLE is not running at all, perhaps you have some special government security mods. Perhaps changing install location would help. Also, does 'fresh install' mean uninstall first? This is not normally required, but you are not in a normal situation ;-). Or perhaps you are running into somthing connected with this warning: **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** Perhaps you are getting silent blockage. Related to the above, there can only be one IDLE process running on the machine at one time. If somehow one were being started on the admin account, for instance .... . Terry Jan Reedy PS. Unless you have good reason not too, consider installing 2.5.2 instead with its many bug fixes. From darcy at druid.net Thu Jul 10 10:45:30 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 10 Jul 2008 10:45:30 -0400 Subject: Loading just in time Message-ID: <20080710104530.bcfc8aa8.darcy@druid.net> I am trying to create a utility module that only loads functions when they are first called rather than loading everything. I have a bunch of files in my utility directory with individual methods and for each I have lines like this in __init__.py: def calc_tax(*arg, **name): from calc_tax import calc_tax as _func_ calc_tax = _func_ return _func_(*arg, **name) This works the first time I call utility.calc_tax but if I call it again I get a "TypeError: 'module' object is not callable" error. Is there any way to do what I want or do I have to put everything back into a single file. Of course, I can simply change all my calls to utility.calc_tax.calc_tax(...) but I have a lot of code to change if I do that. Thanks. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From stefan_ml at behnel.de Sat Jul 12 01:55:12 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 12 Jul 2008 07:55:12 +0200 Subject: Help with using findAll() in BeautifulSoup In-Reply-To: References: Message-ID: <48784741$0$6606$9b4e6d93@newsspool2.arcor-online.net> Alexnb wrote: > Okay, I am not sure if there is a better way of doing this than findAll() but > that is how I am doing it right now. Consider using lxml.html and lxml.cssselect. http://codespeak.net/lxml/ > I am making an app that screen scapes > dictionary.com for definitions. Do they have a policy for doing that? > noun > >
> verb >
> > I want to be able to do like findAll('span', {'class': 'pg'}), but tell me > how many
things are after it, or before the next so I know how many > defintions it has. You didn't say where the "span" is in the HTML code, but lxml.cssselect should get you pretty close to what you want. If your tables are descendants of the "span"s, a selector like: "span.pg table" might work. There's also a CSS syntax for siblings. Stefan From stochashtic at yahoo.ca Fri Jul 25 10:39:56 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 25 Jul 2008 16:39:56 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> Message-ID: <4889e5bc$1@news2-rz-ap.ethz.ch> That's a good comparison for the general question I posed. Thanks. Although I do believe lists are less than ideal here and a different data structure should be used. To be more specific to my case: As mentioned in my original post, I also have the specific condition that one does not know which nodes to turn ON until after all the probabilities are calculated (lets say we take the top m for example). In this case, the second and third will perform worse as the second one will require a remove from the list after the fact and the third will require another loop through the nodes to build the new list. From roy at panix.com Sat Jul 12 21:33:13 2008 From: roy at panix.com (Roy Smith) Date: Sat, 12 Jul 2008 21:33:13 -0400 Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> <85c3da91-9f2f-4d19-ba98-dfdc99b1e1e3@79g2000hsk.googlegroups.com> Message-ID: ssecorp wrote: > i dont get what you mean, if i dont do anything python will raise an > indexerror so it is an indexerror. You wrote: > > > ? ? def pop(self): > > > ? ? ? ? try: > > > ? ? ? ? ? ? return self.queue.pop(0) > > > ? ? ? ? except: > > > ? ? ? ? ? ? raise IndexError, "pop from empty queue" You are assuming that the only possible exception that can be thrown by "return self.queue.pop(0)" is IndexError. Maybe, maybe not. I gave you one example of how something else could be thrown -- a typo in your code leading to a NameError. Maybe even something more exotic like MemoryError? The defensive thing to do is catch exactly the exception you expect to happen. In this case, that means IndexError. From mmcduff at fastsoft.com Wed Jul 16 01:39:38 2008 From: mmcduff at fastsoft.com (Mark McDuff) Date: Tue, 15 Jul 2008 22:39:38 -0700 Subject: reading one byte from stdin Message-ID: <40DC41E9-DBFA-45F3-B155-92785AA9490B@fastsoft.com> I'm trying to read one byte from stdin, without the newline. If I try something like: >>> import os, sys >>> os.read(sys.stdin.fileno(),1) I can input a character, but then I have to press enter, which leaves a newline character in the stdin buffer and requires two keypresses. Is there any way to read only one keypress in a simple manner (i.e. no curses)? From PengYu.UT at gmail.com Tue Jul 22 18:33:04 2008 From: PengYu.UT at gmail.com (Peng Yu) Date: Tue, 22 Jul 2008 15:33:04 -0700 (PDT) Subject: How to match word boundary? Message-ID: <94c0d7d1-5263-45f6-a75d-a9751b3785f9@d45g2000hsc.googlegroups.com> Hi, I use r"\ba\b" to match "a". However, I can not use "\ba::\b" to match "a::b". I would like to match "a::" in "a::b", but not in "a:: b". That is, the character after "::" should be a alphanumeric character. Could you let me know how to do it and why "\b" would not work? Thanks, Peng From chiendarret at gmail.com Sat Jul 26 06:42:40 2008 From: chiendarret at gmail.com (Francesco Pietra) Date: Sat, 26 Jul 2008 12:42:40 +0200 Subject: Insert character at a fixed position of lines In-Reply-To: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> Message-ID: I am still at the stone age, using scripts (e.g., to insert a string after a string) of the type f = open("xxx.pdb", "r") for line in f: print line if "H16Z POPC" in line: print "TER" f.close() That is, I have to learn about modules. In your scripts I am lost about the filename for the pdb file to modify, francesco On Sat, Jul 26, 2008 at 11:35 AM, Lie wrote: > On Jul 26, 2:41 pm, "Francesco Pietra" wrote: >> How to insert letter "A" on each line (of a very long list of lines) >> at position 22, i.e., one space after "LEU", leaving all other >> characters at the same position as in the original example: >> >> ATOM 1 N LEU 1 146.615 40.494 103.776 1.00 73.04 1SG 2 >> >> In all lines"ATOM" is constant as to both position and string, while >> "LEU" is constant as to position only, i.e., "LEU" may be replaced by >> three different uppercase letters. Therefore, the most direct >> indication would be position 22. >> >> Should the script introduce blank lines, no problem. That I know how >> to correct with a subsequent script. >> >> Thanks >> chiendarret > > If you want to leave the rest of the strings as-is (i.e. the letter A > overwrites whatever on position 22), Peter's code need to be modified > a little: > line = line[:22] + " " + line[23:] > -- > http://mail.python.org/mailman/listinfo/python-list > -- Dr Francesco Pietra Professor of Chemistry Accademia Lucchese di Scienze, Lettere e Arti, founded in 1594 Palazzo Ducale 55100 Lucca (Italy) e-mail chiendarret at gmail.com From __peter__ at web.de Wed Jul 9 10:42:05 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 09 Jul 2008 16:42:05 +0200 Subject: Relative Package Import References: Message-ID: Thomas wrote: > Robert Hancock wrote: >> mypackage/ >> __init__.py >> push/ >> __init__.py >> dest.py >> feed/ >> __init__py >> subject.py >> >> In subject.py I have >> from ..push import dest > > There is no such thing as relative package imports. See > http://www.python.org/doc/essays/packages.html Unless you are using Python 1.5 the following document is a bit more relevant: http://www.python.org/dev/peps/pep-0328/ Peter From Ralf.Schaa at gmail.com Sun Jul 13 04:59:35 2008 From: Ralf.Schaa at gmail.com (Ralf.Schaa at gmail.com) Date: Sun, 13 Jul 2008 01:59:35 -0700 (PDT) Subject: matplotlib: is there something like DISLIN's "call newpag" ? Message-ID: Hi there, hope somebody here can help me out: is there a command in matplotlib which resembles DISLIN's "CALL NEWPAG" ? I am trying to make multiple plots on several pages, all stored in one ps (or pdf) document. Cheers -Ralf From iainking at gmail.com Fri Jul 25 08:46:56 2008 From: iainking at gmail.com (Iain King) Date: Fri, 25 Jul 2008 05:46:56 -0700 (PDT) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> Message-ID: <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> On Jul 25, 10:57 am, Suresh Pillai wrote: > I am performing simulations on networks (graphs). I have a question on > speed of execution (assuming very ample memory for now). I simplify the > details of my simulation below, as the question I ask applies more > generally than my specific case. I would greatly appreciate general > feedback in terms of computing and of course considerations specific to > implementation in Python. > > The nodes in my network may be ON or OFF. The network starts off with > all nodes in the OFF state. I loop through the nodes. For each node > that is OFF, I consider some probability of it turning ON based on the > states of its neighbours. I MUST GO THROUGH ALL NODES BEFORE DECIDING > WHICH ONES TO TURN ON. > > So my question is whether it is faster to > > 1. loop through a list of ALL nodes and check for OFF nodes using ifs > > or to > > 2. loop through a container of OFF nodes and remove from this when they > turn ON or 3. build a new list every iteration intead of deleting from the old one: while processing: new_off_list = [] for x in off_list: if goes_on(x): on_list.append(x) else: new_off_list.append(x) off_list = new_off_list generation += 1 Iain From misceverything at gmail.com Sun Jul 20 11:48:40 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Sun, 20 Jul 2008 08:48:40 -0700 (PDT) Subject: Run as Service Message-ID: <09c0bfa9-c86b-4153-ba91-cb9bf2e85e2a@k30g2000hse.googlegroups.com> I have, in the past, used SRVANY to run a Python app as a Windows service. However, now I am interested in distributing my scripts and want to make it as painless for the end user as possible (hands-off is best :). How can you go about running a Python app as a Windows service without SRVANY? From castironpi at gmail.com Wed Jul 30 22:26:05 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 30 Jul 2008 19:26:05 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> <29a131a5-d813-407a-b774-6f90b7f8f3e3@w1g2000prk.googlegroups.com> Message-ID: <8f058531-8c1b-4654-a205-9bec0281b830@k37g2000hsf.googlegroups.com> On Jul 30, 1:50?am, Carl Banks wrote: > On Jul 30, 1:58 am, "Russ P." wrote: > > > > > On Jul 29, 10:33 pm, Carl Banks wrote: > > > > On Jul 30, 1:15 am, "Russ P." wrote: > > > > Having said that, it would sure be nice to be able to write > > > > > if myList is not empty: > > > > > instead of > > > > > if len(myList) != 0: > > > > I can agree with this. > > > But I guess that could only work if there were only one empty list > > that represents all empty lists (as there is only one actual "None"). > > I don't know if that makes sense or not. > > I mean in general. ?I wouldn't spell it like that. ?I would prefer if > empty(x), with an __empty__ method. ?(And support __nonzero__ aka > __bool__ dropped completely.) > > Carl Banks An __empty__ method could return True for my social life, ha ha. Does __nonzero__ just mean __nonempty__? From ldo at geek-central.gen.new_zealand Thu Jul 24 05:54:03 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 24 Jul 2008 21:54:03 +1200 Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: In message , Matimus wrote: > That isn't the standard. With that setup tabs will show up as 4 > spaces, and still confuse you. Why should that be confusing? The most common tab-stop setting is 4 columns. From Samnsparky at gmail.com Sun Jul 13 22:51:16 2008 From: Samnsparky at gmail.com (Sparky) Date: Sun, 13 Jul 2008 19:51:16 -0700 (PDT) Subject: wxPython Tab References: <75018ae6-6d8c-4962-9fd0-aedb52ad626f@k30g2000hse.googlegroups.com> Message-ID: <9a360a73-fa6b-4559-929d-909bc83430f3@34g2000hsf.googlegroups.com> On Jul 13, 10:32?am, Uwe Schmitt wrote: > On Jul 13, 6:20?pm, Sparky wrote: > > > Is there a way to get wxPython to change the visible tab in a notebook > > (like I have tab 1 open but the computer will automatically change to > > tab 2)? > > > Thanks, > > Sam > > look athttp://docs.wxwidgets.org/stable/wx_wxnotebook.html#wxnotebooksetpage... > > greetings, uwe Works like a charm. Thanks! Sam From sunp1028 at gmail.com Fri Jul 18 03:18:52 2008 From: sunp1028 at gmail.com (patrol) Date: Fri, 18 Jul 2008 00:18:52 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> <487E1AD4.9020509@timgolden.me.uk> <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> <3d1db021-6766-4d5d-9105-fdd81e27b671@26g2000hsk.googlegroups.com> Message-ID: On 7?17?, ??4?22?, Tim Golden wrote: > patrol wrote: > > I will try to modify the wmi.py ,however I'm a novice.It will take a > > long time. You can give it up temporarily. If you don't mind ,can you > > tell me where needs modifying and how? Just unicode? Or Other? > > OK. Thanks for your patience on this one, Patrol. What I propose > to do is to dig into the pywin32 sources to determine what's going > on when the error messages are fetched. Then I'll be better placed > to decide what to do when they come out. On the surface, the current > module should be handling things correctly; but I've obviously missed > an encode/decode somewhere. > > If I can think of an (even hackish) workaround for you in the meantime, > I'll let you know. Until then... > > TJG Thanks for Tim's help. Patrol From castironpi at gmail.com Thu Jul 17 18:08:17 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 17 Jul 2008 15:08:17 -0700 (PDT) Subject: interpreter vs. compiled Message-ID: I'm curious about some of the details of the internals of the Python interpreter: I understand C from a hardware perspective. x= y+ 1; Move value from place y into a register Add 1 to the value in the register Move the addition's result to place x The Python disassembly is baffling though. >>> y= 3 >>> dis.dis('x=y+1') 0 SETUP_LOOP 31037 (to 31040) 3 STORE_SLICE+3 4 <49> What are SETUP_LOOP and STORE_SLICE? What are these instructions? From socyl at 987jk.com.invalid Wed Jul 30 17:52:26 2008 From: socyl at 987jk.com.invalid (kj) Date: Wed, 30 Jul 2008 21:52:26 +0000 (UTC) Subject: overriding file.readline: "an integer is required" Message-ID: I'm trying to subclass file, overriding the readline method. The new method definition begins with def readline(self, size=None): line = self.file.readline(size) # etc., etc. ...where the self.file attribute is a regular file object. This works fine if I invoke the new method with an integer argument, but if I invoke it without arguments, I get the error TypeError: an integer is required ...which I suppose comes from the call to self.file.readline(None). I know that I could rewrite the method like this: def readline(self, size=None): if size == None: line = self.file.readline() else: line = self.file.readline(size) # etc., etc. ...but this seems to me exceptionally awkward. (Actually, it's worse than awkward: it fails to complain when the overriding method is called with the argument None. It would be better to test for the number of arguments passed to the function, but I can't figure out how to do this either.) Is there a better idiom? TIA! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From mdboldin at gmail.com Thu Jul 31 11:29:39 2008 From: mdboldin at gmail.com (mmm) Date: Thu, 31 Jul 2008 08:29:39 -0700 (PDT) Subject: undo a dictionary References: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> <192b4786-85b2-43d3-bb7c-b5716068ff12@56g2000hsm.googlegroups.com> Message-ID: Gabriel, I meant the latter, so this helps > Or, do you mean you already have those names and values, perhaps mixed ? > with a lot more names, and want to extract only those starting with "x" ? > and following with a number? > > result = {} > for name, value in vars(): # or locals().items(), or globals().items(), or ? > vars(some_module) > ? ?if name[0]=='x' and name[1:].isdigit(): > ? ? ?result[name] = value But I got an error with 'for name, value in vars():' RuntimeError: dictionary changed size during iteration I think globals() has the same problem, but globals.items() works. I will need to read the docs to learn why '.items()' works but the changing global dictionary problem makes sense. I assume I need to use a non dynamic created list. Sometimes I get the error about 'too many variables to unpack' (can not consistently repeat the error however) In any event, thanks for the suggestions, everyone. Using a blank class for unpacking the dictionary makes the most sense, for safety sake. So you know the general issue is I want to switch between using dictionaries for storing data items and simple variable names for writing equations/formulas, So (a) and (b) below are preferred to (c) for readability (a) straight forward equation y = b0 + b1*Age + b2*Size (b) Class version y = b0 + b1*x.Age + b2*x.Size (c) Dictionary version y = b0 + b1*dd.get('Age') + b2*dd.get('Size') From asma61 at dsl.pipex.com Sun Jul 27 10:17:51 2008 From: asma61 at dsl.pipex.com (DaveM) Date: Sun, 27 Jul 2008 15:17:51 +0100 Subject: Rant (was Re: x*x if x>10 Message-ID: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> On Sun, 27 Jul 2008 05:24:36 -0700 (PDT), alex23 wrote: >On Jul 27, 10:13?pm, ssecorp wrote: >> I have seen somewhere that you can write something like: >> x*x if x>10 >> but exactly that doesn't work and I can't get any variation to work. >It's called a ternary operator. The format is: > My question is I want everything inside, the contents of each ad the regular text of the " My question is I want everything inside, the contents of each ad the regular text of the
american, a href="/browse/blue" linkindex="12" set="yes">blue brick churn cottage cream " My question is I want everything inside, the contents of each ad the regular text of the . I know I can do like a.contents, but it only gives me the first one, in this case being "blue". I want the contents of each of those and the regular contents of the . P.S. notice the things inbetween the tags, I need those too :( Can anyone help? -- View this message in context: http://www.nabble.com/Need-help-getting-BeautifulSoup-contents-tp18501881p18501881.html Sent from the Python - python-list mailing list archive at Nabble.com. From dusan.smitran at gmail.com Thu Jul 17 04:14:52 2008 From: dusan.smitran at gmail.com (dusans) Date: Thu, 17 Jul 2008 01:14:52 -0700 (PDT) Subject: Need help getting BeautifulSoup contents References: Message-ID: <3b6240a5-3f2a-4c44-8944-34079d8e990a@e39g2000hsf.googlegroups.com> I dont quite understand what u want. U should paste the html here http://pastebin.com/ also provide the result that u want. If u dont take the time to write what u wont, nobody will take the time to help u On Jul 17, 7:38?am, Alexnb wrote: > The trick to this one is that the html looks something like this: > > > american, > a href="/browse/blue" linkindex="12" set="yes">blue brick churn cottage > cream " > > My question is I want everything inside, the contents of each ? ad the > regular text of the . > I know I can do like a.contents, but it only gives me the first one, in this > case being "blue". I want the contents of each of those and the regular > contents of the . > > P.S. notice the things inbetween the > Can anyone help? > > -- > View this message in context:http://www.nabble.com/Need-help-getting-BeautifulSoup-contents-tp1850... > Sent from the Python - python-list mailing list archive at Nabble.com. From chrisspen at gmail.com Sun Jul 13 19:05:13 2008 From: chrisspen at gmail.com (Chris) Date: Sun, 13 Jul 2008 16:05:13 -0700 (PDT) Subject: Using Groups inside Braces with Regular Expressions Message-ID: <10284e46-1601-4269-a1a0-ef3831e9f85c@z66g2000hsc.googlegroups.com> I'm trying to delimit sentences in a block of text by defining the end-of-sentence marker as a period followed by a space followed by an uppercase letter or end-of-string. I'd imagine the regex for that would look something like: [^(?:[A-Z]|$)]\.\s+(?=[A-Z]|$) However, Python keeps giving me an "unbalanced parenthesis" error for the [^] part. If this isn't valid regex syntax, how else would I match a block of text that doesn't the delimiter pattern? Thanks, Chris From fredrik at pythonware.com Tue Jul 15 06:49:49 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2008 12:49:49 +0200 Subject: screencapture with PIL question In-Reply-To: <8e9ca866-4f14-4dd6-a784-a76630d8d812@x35g2000hsb.googlegroups.com> References: <8e9ca866-4f14-4dd6-a784-a76630d8d812@x35g2000hsb.googlegroups.com> Message-ID: greg wrote: > I am able to use the PIL module to capture a screen or specific > window. My problem is when capturing a window (on windows XP) I can > only capture the "visible" portion of the window. Is there any way to > capture the entire window? specifically the scrolled portion of a > window that is not visible on the screen. If we're talking arbitrary applications, that portion doesn't necessarily exist other than as a collection of data structures deep inside the application. To fix this, your captura program needs to take repeated screenshots, adjust the view between every shot, and then stitch them together. See Gabriel's post for a link to a nice automation tool for Windows. There are also various browser screenshot tools around that might work in your case (I think I've seen Python code for that somewhere, but cannot find it right now). Google can probably help. From hat at se-162.se.wtb.tue.nl Wed Jul 2 03:56:03 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 02 Jul 2008 09:56:03 +0200 Subject: n00bie wants advice. References: <8757c630-0518-4351-a319-124ced0ac92c@w4g2000prd.googlegroups.com> Message-ID: On 2008-07-02, bsagert at gmail.com wrote: > This simple script writes html color codes that can be viewed in a > browser. I used short form hex codes (fff or 000, etc) and my list > has only six hex numbers otherwise the results get rather large. I > invite criticism as to whether my code is "pythonic". Are there other > ways to generate the hex combos besides the nested "for" loops? Thanks > in advance, Bill ok. variable names of 1 letter are very bad. Use more meaningful names like 'red' 'green' etc. 'list' is better, but also a name reserved by Python, so change that too. Indenting is normally 4 spaces in Python You can see "a + b +c" twice, compute it once, and assign it to a intermediate variable Use string formatting for better readability. In this case, you could also open the file earlier, and write all strings directly to file instead of first creating a string in memory Otherways of creating the colour code permutations: In this case, this is most Pythonic imho. You could write a list comprehension of even a recursive function, but I think it wouldn't increase readability. Albert > list = ['3','6','9','b','d','f'] > > s = '\n' > > for a in list: > for b in list: > for c in list: > s += '

'+ a + b + c +'

> \n' > > s += '' > > f = open('c:/x/test.htm', 'w') > f.write(s) > f.close() From stefan_ml at behnel.de Fri Jul 25 07:02:09 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 25 Jul 2008 13:02:09 +0200 Subject: lxml, comparing nodes In-Reply-To: <4613042f-ed70-4cfa-8de9-a92b4df32923@k36g2000pri.googlegroups.com> References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> <6c91a4da-6443-4570-8dd3-01c4ec169bf3@t54g2000hsg.googlegroups.com> <4888ad28$0$9491$9b4e6d93@newsspool3.arcor-online.net> <4613042f-ed70-4cfa-8de9-a92b4df32923@k36g2000pri.googlegroups.com> Message-ID: <4889B2B1.5030204@behnel.de> code_berzerker wrote: >> If document order doesn't matter, try sorting the elements of each level in >> the two documents by some arbitrary deterministic key, such as (tag name, >> text, attr count, whatever), and then compare them in order, instead of trying >> to find matches in multiple passes. itertools.groupby() might be your friend here. > > I think that sorting multiple times by each attribute will cost more > than I've managed to do: [...] > let1 = [x for x in et1.iter()] > let2 = [x for x in et2.iter()] > [...] > while let1: > el = let1.pop(0) > foundEl = findMatchingElem(el, let2) > if foundEl is None: > return False > let2.remove(foundEl) > return True > > def findMatchingElem(el, eList): > for elem in eList: > if elemsEqual(el, elem): > return elem > return None [...] > Notice that if documents are in exact same order, each element is > compared only once! Not in your code. Stefan From tdelaney at avaya.com Mon Jul 21 21:01:17 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 22 Jul 2008 09:01:17 +0800 Subject: Python Written in C? In-Reply-To: Message-ID: Fredrik Lundh wrote: > rynt wrote: > >> You're either --- >> A. A Troll >> B. A young, immature programmer trying to show off or >> C. A total idiot. > > you forgot the "All of the above" choice. I read it as an inclusive "or". Tim Delaney From bearophileHUGS at lycos.com Sat Jul 19 16:57:33 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 19 Jul 2008 13:57:33 -0700 (PDT) Subject: MethodChain References: <6eej10F6k7g3U2@mid.uni-berlin.de> Message-ID: <342b5431-5ead-4827-8bdd-ab2cd50c2acc@i76g2000hsf.googlegroups.com> Marc 'BlackJack' Rintsch: > What's called `MethodChain` there seems to be function composition in > functional languages. Maybe `functools` could grow a `compose()` function. To me it looks like a quite more "refined" thing, it's an object, it has some special methods, etc. I think it's not too much difficult to implement it with Python. Bye, bearophile From Russ.Paielli at gmail.com Sun Jul 27 15:33:16 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 12:33:16 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> Message-ID: <7eabe5a6-357a-4255-a958-0804959ce844@a6g2000prm.googlegroups.com> On Jul 27, 1:19 am, Steven D'Aprano wrote: > On Sat, 26 Jul 2008 17:14:46 -0700, Russ P. wrote: > > You take the name down to a single letter. As I suggested in an earlier > > post on this thread, why not take it down to zero letters? > > The question isn't "why not", but "why". The status quo works well as it > is, even if it isn't perfect. Prove that implicit self is a good idea -- > or at least prove that it is an idea worth considering. > > "I don't like typing self" doesn't convince me. The same argument could > be made typing parentheses, colons, commas, etc. We could end up with > something like this: > > class Foo base > def method x y z > .args = list x y z > > That's not necessarily wrong, but it's not Python. And what does that have to do with my suggestion? Absolutely nothing. It's a red herring that you seem to be using to obscure the fact that you have no rational argument to make. By the way, according to your "reasoning," Python 2.5 was *not* Python when 2.1 was the latest version. But now it is! Yes, Python has actually changed, yet remained Python. What a concept! > It's not enough to show that a change "isn't bad" -- you have to show > that it is actively good. Why should Python make any changes to the > current explicit self without a clear and solid reason to change? > > > You could if Python accepted something like > > > class Whatever: > > > def fun( , cat): > > > .cat = cat > > > This is even better than the single-character name, > > By "better" do you mean "uglier"? If so, I agree with you. If not, then I > disagree that it is better. You seem to be freaked out by an empty argument. Actually, it bothers me a bit too, which is why I suggested that a period could be used as the first argument to indicate that, like Clint Eastwood in The Good, the Bad, and the Ugly, "self" had no name here. > > not only because it > > is shorter, but also because there is no question that you are referring > > to "self." No need to look back at the method signature to verify that. > > "Don't need to look at the method signature" is not an argument in favour > of implicit self. You don't need to look at the method signature when > you're using an explicit self either. Actually, you do. The name "self" could be used for any argument -- or even for a local variable. No good programmer would do such a thing, of course, but not all programmers are good programmers (and not all Python programmers read the stern admonitions against such practices on this forum). And if you are reviewing critical code, you had darn well better verify that "self" is the first argument. With my proposal, you would not need to do that. Is that a major advantage? No. But it is a minor advantage. And it is perfectly logical. Am I suggesting that unnamed first arguments should always be used? No, of course not. But I am saying that in some cases it can unclutter and simplify the code. > What happens with class-methods? With the cls (or if you prefer klass) > convention, it is simple to tell what object I am referring to. Now I > have to go back to the method signature to see if it is a class method or > instance method, instead of just looking at the explicit name. Bzzzzt. Wrong again. The exact same convention could apply there. And the same benefits apply: less clutter and no need to keep the name of the first argument in your head when reading the code. > > For those who don't like the way the empty first argument looks, maybe > > something like this could be allowed: > > > def fun( ., cat): > > Even uglier than the first. Convince me there's a benefit. Actually, I think it's elegant. And I'll bet that if Guido had suggested it, you would think it was beautiful. Why force a name to be used when none is needed? Think about lambda functions. From mrkafk at gmail.com Mon Jul 21 12:03:08 2008 From: mrkafk at gmail.com (mk) Date: Mon, 21 Jul 2008 18:03:08 +0200 Subject: Python Written in C? In-Reply-To: References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> Message-ID: Grant Edwards wrote: > Using punch-cards and paper-tape. Real programmers can edit > their programs with a pointy stick and some home-made > sticky-tape. Wrong! Real programmers can program using only Touring machine (and something having to do with post for some reason). I'm sure our brilliant OP[1] could program in both. [1] Troll, really. Don't feed the troll. I wouldn't have posted about him because that only adds to the noise. oops. From nagle at animats.com Tue Jul 29 02:08:32 2008 From: nagle at animats.com (John Nagle) Date: Mon, 28 Jul 2008 23:08:32 -0700 Subject: block/lambda In-Reply-To: <0406eb4f-8dec-4ce2-b506-8e597de2958d@56g2000hsm.googlegroups.com> References: <0406eb4f-8dec-4ce2-b506-8e597de2958d@56g2000hsm.googlegroups.com> Message-ID: <488eaf61$0$17164$742ec2ed@news.sonic.net> iu2 wrote: > Hi, > > Playing with imitating lambdas and ruby blocks in Python, I came up > with a very simple construct, for example: > > import compiler Python supports nested functions. You don't have to use a lambda form just to get a local function. Just write an ordinary nested def within another def. John Nagle From dinov at exchange.microsoft.com Fri Jul 25 11:32:11 2008 From: dinov at exchange.microsoft.com (Dino Viehland) Date: Fri, 25 Jul 2008 08:32:11 -0700 Subject: Questions on 64 bit versions of Python In-Reply-To: References: <1216966424.4685.1265275245@webmail.messagingengine.com> <4889AC5E.8090909@egenix.com> Message-ID: <7AD436E4270DD54A94238001769C2227012C935C06F4@DF-GRTDANE-MSG.exchange.corp.microsoft.com> The end result of that is on a 32-bit machine IronPython runs in a 32-bit process and on a 64-bit machine it runs in a 64-bit process. -----Original Message----- From: python-list-bounces+dinov=microsoft.com at python.org [mailto:python-list-bounces+dinov=microsoft.com at python.org] On Behalf Of Mike Driscoll Sent: Friday, July 25, 2008 5:58 AM To: python-list at python.org Subject: Re: Questions on 64 bit versions of Python On Jul 25, 5:52 am, Fredrik Lundh wrote: > M.-A. Lemburg wrote: > >> 4. Is there a stable version of IronPython compiled under a 64 bit > >> version of .NET? Anyone have experience with such a beast? > > > Can't comment on that one. > > Should that matter? Isn't IronPython pure CLR? > > IronPython is written in C# and runs in/with the CLR, if that's what you mean. Well, IronPython one works with the CLR and is equivalent to Python 2.4, whereas IronPython 2 works with the DLR and is equivalent to Python 2.5 Mike -- http://mail.python.org/mailman/listinfo/python-list From modelnine at modelnine.org Tue Jul 29 07:13:23 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Tue, 29 Jul 2008 13:13:23 +0200 Subject: SWIG and char* newb questions :) In-Reply-To: <7ec26fb6-3d6a-4e1b-b2c9-a0a254780153@26g2000hsk.googlegroups.com> References: <7ec26fb6-3d6a-4e1b-b2c9-a0a254780153@26g2000hsk.googlegroups.com> Message-ID: <200807291313.24134.modelnine@modelnine.org> Am Dienstag, 29. Juli 2008 12:51:36 schrieb code_berzerker: > Ok now more seriously. I have question refering to char* used as > function parameters to return values. I have read SWIG manual to find > best way to overcome that, but there are many warnings about memory > leaks and stuff, so I feel confused. > > Ok to put it more simply: how to safely define a variable in Python > and have it modified by C/C++ function? At least for strings, this won't work. Python strings are immutable (and Python optimizes some things based on this knowledge), and as such you can pass a Python string(-object) into a C/C++ function and retrieve its value there as a const (!) char* using the PyString_*-API (I have no idea how this is encapsulated in SWIG), but cannot/should not modify it (a const_cast<> is almost always a sign of bad programming, anyway). The only real choice you have is to have your wrapper return a new string object, created using one of the PyString_FromString[AndSize] functions. Check the Python C-API documentation for more info on this. Anyway, on a different note, I personally have always found it simpler to not use SWIG to generate C extensions for Python, but to use the Python C-API directly. Hope this helps! -- Heiko Wundram From deets at nospam.web.de Wed Jul 16 03:04:37 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Jul 2008 09:04:37 +0200 Subject: reading one byte from stdin In-Reply-To: References: Message-ID: <6e5ksbF5c5a4U1@mid.uni-berlin.de> Mark McDuff schrieb: > I'm trying to read one byte from stdin, without the newline. > > If I try something like: > >>> import os, sys > >>> os.read(sys.stdin.fileno(),1) > > I can input a character, but then I have to press enter, which leaves a > newline character in the stdin buffer and requires two keypresses. Is > there any way to read only one keypress in a simple manner (i.e. no > curses)? Depending on your OS, yes. Under *nix, you need to set the terminal to RAW-mode. This recipe claims to be OS-agnostinc: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 Diez From dominic.rice at gmail.com Fri Jul 4 17:38:21 2008 From: dominic.rice at gmail.com (Dominic Rice) Date: Fri, 04 Jul 2008 22:38:21 +0100 Subject: running python from cmd.exe References: Message-ID: Chris Hulan wrote: > On Jul 4, 5:38 am, Dominic Rice wrote: >> Dominic Rice wrote: >>> Miki wrote: >>>> Hello, >>>>> I can't seem to get python to run my scripts using the command: python >>>>> .py >>>>> If I type python the interpreter runs as I sorted out the Path property, >>>>> I'm afraid I don't know much about this kind of thing as I'm a science >>>>> student who needs some Python not a programmer! >>>> Can you be more specific about the error you get? >>>> Say you have a script hw.py that contains one line: >>>> print "Hello Python" >>>> and you run >>>> python hw.py >>>> What is the error you get? >>>> HTH, >>>> -- >>>> Miki >>>> http://pythonwise.blogspot.com >>> Sure, I get: >>> can't open file .py: [errorno 2]No such file or directory. >>> Now if I've noticed that if I change directory to (for instance) >>> \Python25 where the script is the command runs fine.(?) >> Oh I just noticed you specified hw.py, in that case just to clarify it >> would be can't open file hw.py: [errorno 2]No such file or directory > > When you run a script, are you in the directory where the script is > located? when it works yes! Does it have to be the case then? I assumed that there was a default folder (eg \Python25) that the python command would look for the file in, I take it this is not the case then? From bj_666 at gmx.net Thu Jul 17 00:14:50 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Jul 2008 04:14:50 GMT Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> <0T56p3tmInifNv8%stesch@parsec.no-spoon.de> Message-ID: <6e7v9qF5q74kU1@mid.uni-berlin.de> On Thu, 17 Jul 2008 05:41:11 +0200, Stefan Scholl wrote: > Fredrik Lundh wrote: >> Stefan Scholl wrote: >> >>> Django isn't ready. >> >> That's a remarkably ignorant statement. > > The 1.0 release will be in September. So what? It's not the version number that matters but features and stability. It's not uncommon in open source projects to have very usable software with a version number below 1.0. Ciao, Marc 'BlackJack' Rintsch From fetchinson at googlemail.com Fri Jul 11 02:42:39 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 10 Jul 2008 23:42:39 -0700 Subject: Bypassing WebFilter security In-Reply-To: <4876F153.2020406@behnel.de> References: <563968a1-3cc3-4009-beca-d5d367d4ccff@k13g2000hse.googlegroups.com> <4876F153.2020406@behnel.de> Message-ID: >> I am working in an organization, which is using a very strict >> webcontent filter management suite. Due to this i am unable to >> download any exe file, or surf web (even the necessary downloads from >> sourceforgenet are blocked). I was wondering, if python could be of >> any help. Say i have a python script, and i pass the URL of >> downloadable file, and it just downloads the file for me. > > Nice try. Can I talk to your employer for a minute? :) > > Honestly, the language doesn't make any difference here, and there isn't > much > you can do unless you control both sides, i.e. the server and the client. > But > I would suggest you actually talk to your employer yourself to see if > there's > an official way to get what you want. Yes, the language itself doesn't matter as long as you go through the web. But if I were you I would use an ssh client to ssh to a remote machine on which I have an account, download the file there to that machine and scp it to the local machine. Assuming of course port 21 is not blocked. In fact, this is something I do regularly for similar reasons :) Good luck, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From paul at boddie.org.uk Fri Jul 25 18:32:44 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 25 Jul 2008 15:32:44 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> Message-ID: <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> On 25 Jul, 22:37, Terry Reedy wrote: > Kay Schluehr wrote: > > > > This isn't the problem Jordan tries to address. It's really just about > > `self` in the argument signature of f, not about its omission in the > > body. > > That is not at all how I read him, so I will let him respond if he > wishes. The main problem moving a function from module scope to class > scope is prefixing the proper variables. Adding a param name, whether > 'self', 's', 'this', or whatever, is trivial and hardly worth the ink. He wrote the following of relevance: "I added some classes to code that had previously just been functions, and you know what I did - or rather, forgot to do? Put in the 'self'. In front of some of the variable accesses, but more noticably, at the start of *every single method argument list.*" And rounding off with this on the subject: "The problem is that the explicit requirement to have self at the start of every method is something that should be shipped off to the implicit category." I guess the desire is to have Java-like behaviour: when defining a method, which must typically be done in the class definition in Java (unless they've enhanced that area in the past few years), you never write a "this" parameter in the method signature, but you are free to qualify instance attribute accesses with "this". Personally, I liked the Modula-3-inspired requirement for "self" in Python, but I can see how a reminder of what it is in every method signature (defined within a class) might be regarded as overly explicit. Paul From execrable at gmail.com Wed Jul 23 22:40:38 2008 From: execrable at gmail.com (B) Date: Wed, 23 Jul 2008 19:40:38 -0700 Subject: os.walk question In-Reply-To: References: Message-ID: Lanny wrote: > How would one make a list of the files in the top directory > using os.walk. > > I need to pick a random file from said list. > > Thanks. > > > > > -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- > how about: import os x = os.walk('/') (root,dirs,files) = x.next() 'files' should contain a list of filenames. From zondo42 at googlemail.com Fri Jul 25 13:13:10 2008 From: zondo42 at googlemail.com (Glenn Hutchings) Date: Fri, 25 Jul 2008 18:13:10 +0100 Subject: calling source command within python References: Message-ID: Jie writes: > i'm having trouble executing os.system('source .bashrc') command > within python, it always says that source not found and stuff. Any > clue? There's no 'source' program; it's a shell builtin. Even if there was, it almost certainly wouldn't do what you want. The .bashrc file is supposed to contain settings applying to the current shell, and os.system() runs in a subshell, so the settings will only affect that shell. If you're doing this to set environment variables, try modifying os.environ instead. Glenn From wuwei23 at gmail.com Thu Jul 24 08:40:16 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 24 Jul 2008 05:40:16 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> Message-ID: <1de235af-4245-41aa-9091-bb7b112f4ce5@n33g2000pri.googlegroups.com> On Jul 24, 8:21?pm, Jordan wrote: > If the attitude > in the community in response to feedback/criticism has gone from > "maybe you've got a point" to "your a lunatic, we'll never change", > well, only Python will suffer in the long term. Personally, I think it has more to do with statements like "there are plenty of smart Python programmers who will justify all kinds of idiocy in the name of their holy crusade" than with your position. You don't begin a discussion by discrediting anyone who might disagree with you as some kind of religious bigot while simultaneously holding that you are the only sane voice speaking. From darcy at druid.net Sat Jul 26 10:36:30 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 26 Jul 2008 10:36:30 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <87k5f8afjl.fsf@physik.rwth-aachen.de> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> Message-ID: <20080726103630.04297f88.darcy@druid.net> On Sat, 26 Jul 2008 16:25:18 +0200 Torsten Bronger wrote: > > Isn't this a showstopper all by itself? > > Yes. But I've seen no code that uses some other word. Emacs' > syntax highlighting even treats it as reserved. So I think that > other counter-arguments are stronger. > > The in my opinion strongest one is that automatic insertion of > "self" would make Python less verbose but more complicated. Well, if we are arguing over which reason to not change it is more important than I would say that we are in "violent agreement." :-) -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From __peter__ at web.de Mon Jul 7 04:10:14 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 07 Jul 2008 10:10:14 +0200 Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> <6ddj74F21uhjU1@mid.individual.net> Message-ID: Peter Pearson wrote: > On Sun, 06 Jul 2008 23:42:26 +0200, TP > wrote: >> >> $ python -c "print '\033[30;44m foo \033[0m'" > [writes an escape sequence to stdout] > >> $ echo -e $esc$ColorBlackOnDarkblue foo $esc$ColorReset > [also writes an escape sequence to stdout] > >> $ echo -n $esc$ColorBlackOnDarkblue foo $esc$ColorReset >> \033[30;44m foo \033[0m > > [snip, shuffle] >> $ export esc="\033" >> $ export ColorBlackOnDarkblue="[30;44m" >> $ export ColorReset="[0m" >> >> import os >> Color = os.environ['ColorBlackOnDarkblue'] >> ColorReset = os.environ['ColorReset'] >> Esc = os.environ['esc'] >> print '%s%s%s%s%s' % (Esc, Color, " foo ", Esc, ColorReset) > [snip] >> $ python color.py >> \033[30;44m foo \033[0m > > The string "\033" is 4 characters long. Your shell variable > "esc" is 4 characters long. Your Python program prints > those four characters. You want it to re-interpret those 4 > characters into a single escape character. > > One of this group's regular participants can (I hope) tell > us three breathtakingly elegant ways to do that. I'm sorry > I can't. > > When you run echo, it recognizes the 4-character "esc" as a > convention for representing a single character, and performs > the re-interpretation for you. When you tell python > "print '\033[30;44m foo \033[0m'", python interprets > the "\033" as a single character. Peter Pearson's explanation is spot-on. You get the 4-character sequence instead of the escape code chr(27). $ export esc="\033" $ python Python 2.5.1 (r251:54863, Mar 7 2008, 03:39:23) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ["esc"] '\\033' >>> print _ \033 If you want to interpret "\\033" as "\033" you have to perform the conversion explicitly. Fortunately there already is an encoding that understands these escape sequences for characters: >>> esc = os.environ["esc"].decode("string-escape") >>> esc '\x1b' >>> print "%s[30;44malles so schoen bunt hier%s[0m" % (esc, esc) alles so schoen bunt hier Peter From simon at simonwillison.net Wed Jul 30 10:32:16 2008 From: simon at simonwillison.net (Simon Willison) Date: Wed, 30 Jul 2008 07:32:16 -0700 (PDT) Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? Message-ID: I'm having a horrible time trying to get xml.dom.pulldom to consume a UTF8 encoded XML file. Here's what I've tried so far: >>> xml_utf8 = """ Simon\xe2\x80\x99s XML nightmare """ >>> from xml.dom import pulldom >>> parser = pulldom.parseString(xml_utf8) >>> parser.next() ('START_DOCUMENT', ) >>> parser.next() ('START_ELEMENT', ) >>> parser.next() ... UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 21: ordinal not in range(128) xml.dom.minidom can handle the string just fine: >>> from xml.dom import minidom >>> dom = minidom.parseString(xml_utf8) >>> dom.toxml() u'Simon\u2019s XML nightmare' If I pass a unicode string to pulldom instead of a utf8 encoded bytestring it still breaks: >>> xml_unicode = u'Simon\u2019s XML nightmare' >>> parser = pulldom.parseString(xml_unicode) ... /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ xml/dom/pulldom.py in parseString(string, parser) 346 347 bufsize = len(string) --> 348 buf = StringIO(string) 349 if not parser: 350 parser = xml.sax.make_parser() UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 32: ordinal not in range(128) Is it possible to consume utf8 or unicode using xml.dom.pulldom or should I try something else? Thanks, Simon Willison From sjmachin at lexicon.net Thu Jul 17 08:29:44 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 17 Jul 2008 05:29:44 -0700 (PDT) Subject: storing references instead of copies in a dictionary References: Message-ID: <4eec55f0-91a0-4635-bf0c-a4c4573bf81e@p25g2000hsf.googlegroups.com> On Jul 17, 9:45 pm, mk wrote: > Hello everyone, > > I'm storing functions in a dictionary (this is basically for cooking up > my own fancy schmancy callback scheme, mainly for learning purpose): > > >>> def f2(arg): > ... return "f2 " + arg > ... > >>> > >>> def f1(arg): > ... return "f1" + arg > ... > > >>> a={'1': f1, '2': f2} > >>> > >>> [ x[1](x[0]) for x in a.items() ] > ['f11', 'f2 2'] > > Well, neat. Except if I change function definitions now, old functions > are called. And rightly: > > {'1': , '2': } > >>> f1 > > >>> > >>> def f1(arg): > ... return "NEW f1 " + arg > ... > >>> f1 > > > The address of function f1 has obviously changed on redefinition. I wouldn't put it like that. You have created a new function, with a different address to the original function, and bound the name "f1" to that new function. The address of the old function is still stored in the dictionary. A function (or any other object) can have 0, 1, or many names: >>> def foo(): ... print "The function formerly known as foo" ... >>> fred = foo # 2 names >>> del foo # back to one name >>> fred() The function formerly known as foo >>> L = [fred] >>> del fred # 0 names >>> L[0]() # You can't keep a good function down ... The function formerly known as foo >>> > Of course, I can basically update the dictionary with a new function > definition. Uh-huh ... > > But I wonder, is there not a way _in general_ to specifically store > references to functions/variables/first-class objects instead of copies > in a dictionary? Yup, and that's what happens all the time, unless you explicitly make a copy ... some objects have a copy method, sequences can be copied by taking a full slice (seq_copy = seq[:]), otherwise read up on the copy module. From fredrik at pythonware.com Sat Jul 26 07:45:55 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Jul 2008 13:45:55 +0200 Subject: Insert character at a fixed position of lines In-Reply-To: References: Message-ID: Francesco Pietra wrote: > How to insert letter "A" on each line (of a very long list of lines) > at position 22, i.e., one space after "LEU", leaving all other > characters at the same position as in the original example: > > > ATOM 1 N LEU 1 146.615 40.494 103.776 1.00 73.04 1SG 2 > > In all lines"ATOM" is constant as to both position and string, while > "LEU" is constant as to position only, i.e., "LEU" may be replaced by > three different uppercase letters. Therefore, the most direct > indication would be position 22. you may find the fileinput module helpful, combined with the tips you've already gotten in this thread. reference: http://docs.python.org/lib/module-fileinput.html examples: http://effbot.org/librarybook/fileinput.htm http://blog.doughellmann.com/2007/03/pymotw-fileinput.html From fetchinson at googlemail.com Sun Jul 6 03:13:01 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sun, 6 Jul 2008 00:13:01 -0700 Subject: Python with Ecmascript In-Reply-To: <48706543$1$860$ba4acef3@news.orange.fr> References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <486fe241$0$867$ba4acef3@news.orange.fr> <48706543$1$860$ba4acef3@news.orange.fr> Message-ID: >> Is there a way to do similar things on linux? > > I think no. Because these tech use COM. And COM don't exist under xxnux. > But: > - look if XPCOM, or dBus) can help you > - search with the word "MOZLAB", who work a solution (plugin) for > drive Firefox, from an external software. Wow, mozlab is amazing! Thanks, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From larry.bates at websafe.com` Mon Jul 14 22:19:23 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 14 Jul 2008 21:19:23 -0500 Subject: One step up from str.split() In-Reply-To: References: Message-ID: Joel Koltner wrote: > I normally use str.split() for simple splitting of command line arguments, but > I would like to support, e.g., long file names which-- under windows -- are > typically provided as simple quoted string. E.g., > > myapp --dosomething --loadthis "my file name.fil" > > ...and I'd like to get back a list wherein ListEntry[3]="my file name.fil" , > but just running str.split() on the above string creates: > >>>> ListEntry='myapp --dosomething --loadthis "my file name.fil"' >>>> ListEntry.split() > ['myapp', '--dosomething', '--loadthis', '"my', 'file', 'name.fil"'] > > Is there an easy way to provide just this one small additional feature > (keeping quoted names as a single entry) rather than going to a full-blown > command-line argument parsing tool? Even regular expressions seem like they'd > probably be overkill here? Or no? > > Thanks, > ---Joel > > Sounds like it is time to look at getopt Library module. I handles these types of args lines. -Larry From sri_annauni at yahoo.co.in Wed Jul 2 06:32:44 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Wed, 2 Jul 2008 16:02:44 +0530 (IST) Subject: How to identify whether a function is module scoped function or static method of a class by using its fully qualified name Message-ID: <534745.21348.qm@web7906.mail.in.yahoo.com> Thanks, Srini Best Jokes, Best Friends, Best Food and more. Go to http://in.promos.yahoo.com/groups/bestofyahoo/ From news at prodata.co.uk Sat Jul 12 05:30:00 2008 From: news at prodata.co.uk (John Dann) Date: Sat, 12 Jul 2008 10:30:00 +0100 Subject: How to create a timer/scheduler in Python? Message-ID: <0stg74t0eksmnfsslukn5m7f9s4rbub8kt@4ax.com> I need what I'd call (in .Net) a timer, ie I need to run a function eg every 2 seconds - it doesn't need to be millisec accurate but it would be nice if it wasn't eg every 4 seconds or something. Rather surprisingly, Core Python (Chun) doesn't seem to index 'timer' or 'scheduler', which leaves me wondering whether this is an aspect of Python that isn't perhaps widely used? Looking around on the net I can see references to a thread timer, but I'm not really looking to start any new threads (I just want part of the GUI to update every 2 secs) and don't want to get into that sort of complication while still just learning Python. Is there really no simple timer/scheduler function available in Python? From dear.jay.logan at gmail.com Sun Jul 27 20:52:09 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Sun, 27 Jul 2008 17:52:09 -0700 (PDT) Subject: Where is the correct round() method? References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> Message-ID: <90d24864-c67a-4594-b121-d0760f9e145b@m45g2000hsb.googlegroups.com> On Jul 27, 8:45?pm, pigmartian wrote: > it could be that 3.0 is using "banker's rounding" --- rounding to the > even digit. ?the idea behind it behind it being to reduce error > accumulation when working with large sets of values. > > > Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo > > CPU". ?What system are you on? > > > It could be that 2.5 is really 2.49999... which would round down to 2, > > but on any modern CPU (using IEEE floating point), 2.5 should be > > representable exactly. > > That's exactly what's happening, pigmartian. Thank you for explaining the reasoning behind this change. So am I relegated to building my own round() function that behaves like the original function? Or did they move the functionality to a new method somewhere for backwards-compatibility? From luismgz at gmail.com Mon Jul 21 15:12:39 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 21 Jul 2008 12:12:39 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <5e098db8-38f0-42ac-9cb7-9eada66f9a00@z72g2000hsb.googlegroups.com> Let's say you want to build a house... You can use pre-built bricks and stack them together to build your walls, or you can cook your own bricks out of clay because hey! clay is the real thing.... not those ready-made bricks that anyone can use! In the end, you'll have a truly original house but you would have spent 5 years instead of 6 months. The question is: Is it worth it? Bceause you can use pre-built bricks instead and, after applying stucco, nobody will notice you used bricks instead of your own in house-original-cooked bricks. Ok, making your own bricks give you more control over the final result and the way you work with them, but after building two or three houses, you realize it is very cumbersome and time consuming, and not really practical for a "real world" builder... Although making your own bricks could make sense if instead of being a house builder, you are a bricks vendor. It is the same with programming languages: If you are planning to write the next operating system, or a database management system to be used in mission critical applications by millions of users, or perhaps a 3D graphics application, you'd better use C. Fort anything else, boy, don't lose your time. Use Python, get the job done with the least delay and have fun. My two cents... Luis On 20 jul, 19:50, giveitawhril2... at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > > So I was suspecting the Python compiler or interpreter is written in a From rNOSPAMon at flownet.com Fri Jul 4 18:37:12 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Fri, 04 Jul 2008 15:37:12 -0700 Subject: Parsing MIME-encoded data in an HTTP request References: <3a11k5-al7.ln1@nb2.stroeder.com> Message-ID: In article , Ron Garret wrote: > In article <3a11k5-al7.ln1 at nb2.stroeder.com>, > Michael Str?der wrote: > > > Ron Garret wrote: > > > I'm writing a little HTTP server and need to parse request content that > > > is mime-encoded. All the MIME routines in the Python standard library > > > seem to have been subsumed into the email package, which makes this > > > operation a little awkward. > > > > How about using cgi.parse_multipart()? > > > > Ciao, Michael. > > Unfortunately cgi.parse_multipart doesn't handle nested multiparts, > which the requests I'm getting have. You have to use a FieldStorage > object to do that, and that only works if you're actually in a cgi > environment, which I am not. The server responds to these requests > directly. > > Anyway, thanks for the idea. > > rg Hm, it actually seems to work if I manually pass in the outerboundary parameter and environ={'REQUEST_METHOD':'POST'} That seems like the Right Answer. Woohoo! Thanks Michael! rg From boblatest at googlemail.com Wed Jul 30 10:46:37 2008 From: boblatest at googlemail.com (boblatest at googlemail.com) Date: Wed, 30 Jul 2008 07:46:37 -0700 (PDT) Subject: Pointers/References in Python? Message-ID: <0accb66b-bbd8-48ec-b9e0-d1fe02316d44@t54g2000hsg.googlegroups.com> Hello, I have a long list of memory-heavy objects that I would like to access in differently sorted order. Let's say I'd like to have lists called by_date or by_size that I can use to access the objects in the specified order. Of course I can just build those lists naively by creating copies of the original list and then sorting them according to my wishes. But that would create huge memory overhead. Of course I could use lists of indices into the "master" list, just as in C I'd create lists or arrays of pointers into the original data. Is there a clever Python way to do this, or should I just use lists of indices? I know there is a thing called "shallow copy" that has something to do with not duplicating memory content but I don't understand the concept. Maybe that's what would help here, too. Thanks, robert From tjreedy at udel.edu Mon Jul 14 14:17:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Jul 2008 14:17:49 -0400 Subject: Moving to functional programming In-Reply-To: <6daf86f6-0a96-4811-90c4-2bc6ccbff9fb@x41g2000hsb.googlegroups.com> References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> <6daf86f6-0a96-4811-90c4-2bc6ccbff9fb@x41g2000hsb.googlegroups.com> Message-ID: James Fassett wrote: ... >> robust and efficient than the list comprehension. > > I don't know the internals of how the Python interpreter treats list > comprehensions and zip but it seems reasonable to assume an extra list > is created for the zip approach. Minor times differences between this and that way of writing things tend to be version and even system dependent. In 3.0, for instance, zip produces an iterator, not a list. So it will be faster. On the other hand, list comprehensions will be a bit slower to fix what many, including Guido, consider to be a slight design bug. From mail at timgolden.me.uk Mon Jul 7 12:16:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 07 Jul 2008 17:16:03 +0100 Subject: how to recognize IE window already opened using win32com extension In-Reply-To: <203fdfe3-78d6-4b08-a64f-a031df9cacc1@s50g2000hsb.googlegroups.com> References: <203fdfe3-78d6-4b08-a64f-a031df9cacc1@s50g2000hsb.googlegroups.com> Message-ID: <48724143.7040905@timgolden.me.uk> korean_dave wrote: > How do I use the win32com API to manipulate IE windows ALREADY open? > > ie = Dispatch("InternetExplorer.Application") opens a new window. > > But I'd like to be able to find, of windows already open, a specific > window (with a specified property, matching url, etc.) I have this strange feeling of deja vu. Is there some sort of "opening IE windows with Python" conference going on somewhere? Have a look at Roger Upole's answer from the other day: http://mail.python.org/pipermail/python-win32/2008-June/007796.html TJG From timothy.grant at gmail.com Sat Jul 19 01:18:25 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Fri, 18 Jul 2008 22:18:25 -0700 Subject: Change PC to Win or Windows In-Reply-To: <48812807.3000100@v.loewis.de> References: <48812807.3000100@v.loewis.de> Message-ID: On Fri, Jul 18, 2008 at 4:32 PM, "Martin v. L?wis" wrote: > > Calling Windows PC seems to be something that Apple did so they would > > not have to directly mention Windows. Could all the places that say PC > > that are not referring to Personal Computers in general be changed to > > Win or Windows. > > That's bikeshedding. If the name stops you from building your own > binaries, you should use prebuilt binaries, or read the documentation. > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list > Thank you for introducing me to a fabulous new word. Had to look it up, but I like it. -- Stand Fast, tjg. [Timothy Grant] -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Fri Jul 25 12:17:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 25 Jul 2008 18:17:44 +0200 Subject: Calling external program from within python In-Reply-To: <042e46cf-8ee8-4dd0-bc2b-716d588f8e83@o40g2000prn.googlegroups.com> References: <6eu684F91muhU1@mid.uni-berlin.de> <042e46cf-8ee8-4dd0-bc2b-716d588f8e83@o40g2000prn.googlegroups.com> Message-ID: <6eucl8F90apnU2@mid.uni-berlin.de> Mike Driscoll schrieb: > On Jul 25, 9:28 am, "Diez B. Roggisch" wrote: >> Mike Driscoll schrieb: >> >>> On Jul 25, 7:56 am, Emmanouil Angelakis >>> wrote: >>>> Hi, >>>> I am tryiong to do something obviously trivial such as: >>>> I have a c program called "tsys2list" that when it is ran it asks the user to give the value of "tcal" which is a variable. I want to call the "tsys2list" from within a pyrthon script lets call it "gamma.py" >>>but<<< I want to pass the value of "tcal" to th eprogram automatically and not by interacting with the keyboard. >>>> How do I do that? >>>> thanks i advance! >>>> manolis >>> There are probably many ways to do this. I would recommend checking >>> out the subprocess module and see if it does what you want. >> This will only work if the program can be fully controlled by >> commandline arguments. If interaction is required, the OP might consider >> using pexpect. >> >>> Or you >>> could learn a little Tkinter or wxPython and use that to get the >>> user's variable. Or you could even do it via the command line using >>> the "raw_input" command. >> I fail to see how *gathering* input (regardless of the method) solves >> the problem of *passing* input to a subprocess. >> >> Diez > > My understanding of the OP's request was that "tsys2list" was a custom > script of some sort that gathered info from the user, so I wanted to > know why he didn't just skip calling it and write something in Tkinter > or wxPython or even via the CLI instead. > > I'm probably just not understanding something. The program is doing some work, and needs to be told what actually to do. It does so by asking the user, sure. But then it *works*. I think that's pretty clear from """ I have a c program called "tsys2list" that when it is ran it asks the user to give the value of "tcal" which is a variable. I want to call the "tsys2list" from within a pyrthon script lets call it "gamma.py" >>>but<<< I want to pass the value of "tcal" to th eprogram automatically and not by interacting with the keyboard. """ So replacing it with something that asks the same questions leaves us with the work undone... Diez From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 2 12:11:22 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Jul 2008 18:11:22 +0200 Subject: Trouble using pinckle In-Reply-To: <1ijgp2r.1j1k5xwwbtiwcN%pdorange@pas-de-pub-merci.mac.com> References: <1ijgkgu.14kfvaq3zy0sgN%pdorange@pas-de-pub-merci.mac.com> <1ijgp2r.1j1k5xwwbtiwcN%pdorange@pas-de-pub-merci.mac.com> Message-ID: <486ba8a4$0$11957$426a74cc@news.free.fr> Pierre-Alain Dorange a ?crit : > C?dric Lucantis wrote: > >> Here self is only a local variable and its meaning is only a convention. So >> assigning it to a new value won't change the object itself (and is not a good >> idea as it may be confusing for the reader). > > Thanks, i was thinking about something like that. > (snip) > I try the staticmethod, it works fine. Very helpful. > > But i don't like it very much, it seems 'complicated' (python was > supposed to be simple). Try doing the same thing in C++ !-) > I'll also try the dictionnary method. > My final idea was that a dictionnary would be perhaps simple in the > future to save/load as XML and a parser. XML ? What a strange idea ? > But perhaps i'm wrong with my vision of python. > > On a more global perspective, what are the best method to implement a > simple config file with pyhton. Well... Python does have a couple of config-related packages, starting with the one in the stdlib. You may want to find out if any of these packages fits your needs before reinventing the wheel ? > Assuming i finally want to made a bundle > app for Mac, Windows and perhaps Linux. > I develop on Mac, and on this platform the config fil (preferences) have > to be stored in a special directory : ~/Library/Preferences, no problem. > But on other platform that's not the same directory and perhaps i would > also faced to permissions issues... Yeps. Portability sometimes has a cost. I can't help you wrt/ Windows, but on unix the convention is to save user's prefs in a .yourprogram file (or directory) in the user's home directory. > But first is there a way to determine on which platfrom the python > script is running ? the os package is your friend. From pavlovevidence at gmail.com Mon Jul 7 17:04:49 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 7 Jul 2008 14:04:49 -0700 (PDT) Subject: Dynamically Changing the Base Class References: <6d60c362-ba17-4414-babd-2cc254526bca@c58g2000hsc.googlegroups.com> Message-ID: <68bba759-864e-4943-9f1e-f19b99408ef7@l64g2000hse.googlegroups.com> On Jul 7, 9:31 am, "Adam C." wrote: > We have a situation where we want a Swig-generated Python class to > have a different base (not object). It doesn't appear that we can > coerce Swig into generating the class we want at present (but we are > still enquiring). > > Is it possible to dynamically change the base class to something else? > Initial experiments appear to show it is not: > -------------------------------- snip -------------------------------->>> class Foo(object): > > pass > > >>> class Foozle(object): > > pass > > >>> Foozle.__bases__ = (Foo,) > > Traceback (most recent call last): > File "", line 1, in > Foozle.__bases__ = (Foo,) > TypeError: __bases__ assignment: 'Foo' deallocator differs from > 'object' > -------------------------------- snip -------------------------------- > > Is there a solution I am missing? > > Thanks in advance. You get the same effect as subclassing by using multiple inheritance. Suppose your SWIG class called Foo to have a base class of Base. You could instead call the SWIG class _Foo, and define Foo as a Python class like this: class Foo(_Foo,Base): pass If you do that, the resulting class will behave exactly as if _Foo were a subclass of base (apart from some introspection methods and edge cases). You can see that this is so if you look at the MRO: Foo, _Foo, Base, object Which is the same MRO that would occur if _Foo derived from Base directly. The drawback (which is also a drawback to the hypothetical base reassignment) is that Foo's __init__ method won't call Base's. The only way you can make SWIG __init__ call it's superclass's __init__ is apparently a patch. Carl Banks From tom.machinski at gmail.com Mon Jul 21 18:29:27 2008 From: tom.machinski at gmail.com (Tom Machinski) Date: Mon, 21 Jul 2008 15:29:27 -0700 Subject: Getting clear error messages with a Python templating system? Message-ID: Hi there, I'm developing web applications in Python, so I use a templating system to produce HTML. We're dealing with heavy traffic here, so my original choice was the fast and efficient Cheetah. The main problem is that Cheetah doesn't provide clear error messages. Even in the best cases, you only get some indication of the nature of the error ("TypeError: 'str' object is not callable") but you can't see the code where the error occurs. You can't even know the approximate region of the template code where the problem originates. So I tried another templating system, the newer and equally efficient Mako. Again, same problem. It should be noted that both Cheetah and Mako compile themselves to an intermediary Python file. This Python file is what's actually running, so that's where the error originates. This is very efficient, but also severely hinders debugging (see below for example of what a very simple error on a very short Mako template generates). So my question is: is there any way to get clear error messages with a Python templating system? I welcome both suggestion on how to get those with Cheetah (or Mako), and suggestions about alternative templating systems that provide better error messages. Thanks, Tom ----- # foo.mako: hello ${data} >>> print mako.template.Template(filename="foo.mako").render(data="world") hello world >>> print mako.template.Template(filename="foo.mako").render(dataerr="world") Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/site-packages/Mako-0.1.10-py2.5.egg/mako/template.py", line 114, in render return runtime._render(self, self.callable_, args, data) File "/usr/lib/python2.5/site-packages/Mako-0.1.10-py2.5.egg/mako/runtime.py", line 287, in _render _render_context(template, callable_, context, *args, **_kwargs_for_callable(callable_, data)) File "/usr/lib/python2.5/site-packages/Mako-0.1.10-py2.5.egg/mako/runtime.py", line 304, in _render_context _exec_template(inherit, lclcontext, args=args, kwargs=kwargs) File "/usr/lib/python2.5/site-packages/Mako-0.1.10-py2.5.egg/mako/runtime.py", line 337, in _exec_template callable_(context, *args, **kwargs) File "foo_mako", line 19, in render_body File "/usr/lib/python2.5/site-packages/Mako-0.1.10-py2.5.egg/mako/runtime.py", line 91, in __str__ raise NameError("Undefined") NameError: Undefined -------------- next part -------------- An HTML attachment was scrubbed... URL: From anishchapagain at gmail.com Mon Jul 21 09:11:50 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Mon, 21 Jul 2008 06:11:50 -0700 (PDT) Subject: error References: <5f4395d7-9f5c-45c3-b137-655e5c618b8c@8g2000hse.googlegroups.com> Message-ID: <0b48f3b2-0927-4745-97ce-6ee2bc8bcbe0@m73g2000hsh.googlegroups.com> On Jul 21, 1:47?pm, Fredrik Lundh wrote: > Anish Chapagain wrote: > > from Tkinter import * > > root=Tk() > > f=Frame(root,height=200,width=200) > > b=Button(f,text="quit",command=f.quit) > > f.pack() > > root.mainloop() > > > -------------------------------------------------- > > from Tkinter import * > > import sys > > root=Tk() > > f=Frame(root,height=200,width=200) > > b=Button(f,text="quit",command=sys.exit) > > f.pack() > > root.mainloop() > > > I am wondering that why the button after clikcing is not closing the > > window..please any suggestion.. > > i tries command=f.quit, sys.quit also.. > > if there is something i'm missing please help > > Assuming you accidentally left out the line where you're displaying the > button (e.g. "b.pack()"), both your samples work when running this from > the command line. > > Are you perhaps running this code from inside IDLE? ?IDLE is itself > written in Tkinter, and it doesn't always shut down the Tkinter > subsystem properly. > > ... and I have to admit that I don't know what the currently recommended > workaround is -- you'll find plenty of documentation on the net that > just says "don't do that" (run Tkinter programs from within IDLE, that > is), but surely someone should have fixed that issue by now?. > > - Hide quoted text - > > - Show quoted text - hi thank's i probably missed the b.pack() but it's till the window is not closed and error message of Windows Appear From fredrik at pythonware.com Wed Jul 23 15:45:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 21:45:52 +0200 Subject: Undocumented Python 2.6 change: Py_None vs NULL when C implementation raises exception In-Reply-To: References: Message-ID: Heikki Toivonen wrote: > I was debugging M2Crypto function written in C which changed behavior > between Python 2.6 and earlier Python versions. In an error condition > the function was supposed to raise exception type A, but with 2.6 it > raised type B, and further, there was no string value for the exception. > > I tracked this down to the C code incorrectly returning Py_None when it > should have returned NULL. Changing the C code to return NULL made it > behave correctly in 2.6. > > I don't know how common a mistake it is to return Py_None when NULL > should have been returned, but it might be worth a note in the list of > changes for 2.6 that this behavior changed, don't you think? the behaviour when setting the exception status without returning NULL has never been well-defined; it pretty much depends on what kind of error checking the code that runs later happens to use. (this has been an entertaining source of obscure errors over the years; code that uses PyErr_Clear may mask errors, and code that uses PyErr_Occurred to check if something went wrong might raise the wrong error, often at an unexpected location). From hubaghdadi at gmail.com Mon Jul 28 04:54:11 2008 From: hubaghdadi at gmail.com (Hussein B) Date: Mon, 28 Jul 2008 01:54:11 -0700 (PDT) Subject: Module clarification Message-ID: <9d64065f-0ae8-40cf-bfdb-4ef62894166e@34g2000hsh.googlegroups.com> Hi. I'm a Java guy and I'm playing around Python these days... In Java, we organize our classes into packages and then jarring the packages into JAR files. What are modules in Python? What is the equivalent of modules in Java? Please correct me if I'm wrong: I saved my Python code under the file Wow.py Wow.py is now a module and I can use it in other Python code: import Wow Thanks. From sunp1028 at gmail.com Wed Jul 16 11:54:02 2008 From: sunp1028 at gmail.com (patrol) Date: Wed, 16 Jul 2008 08:54:02 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> Message-ID: On 7?16?, ??10?39?, Tim Golden wrote: > patrol wrote: > > The errors are in the following: > > > Traceback (most recent call last): > > File "D:\My Documents\code\python\wmi\test.py", line 5, in > > c = wmi.WMI ("non-existent computer") > > File "C:\Python25\lib\wmi.py", line 1199, in connect > > handle_com_error (error_info) > > File "C:\Python25\lib\wmi.py", line 184, in handle_com_error > > exception_string = [u"%s - %s" % (hex (hresult_code), > > hresult_name)] > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > > 4: ordinal not in range(128) > > OK, I'm trying to set up a Virtual PC so I can install > a non-English XP. But would you mind running the > following code for me, please, so I can get a handle > on what's coming back: > > > import pythoncom > import win32com.client > > try: > win32com.client.GetObject ("winmgmts://blahblah") > except pythoncom.com_error, info: > for i in info: > print repr (i) > > > > Thanks > TJG -2147023174 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3' None None ---------------------------------------------------------------------- import pythoncom import win32com.client try: win32com.client.GetObject ("winmgmts://blahblah") except pythoncom.com_error, info: for i in info: print i -2147023174 RPC ??????? None None ------------------------------------------------------------------------- >>> a="RPC ???????" >>> a 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3' >>> ------------------------------------------------------------------------- Patrol From hat at se-162.se.wtb.tue.nl Thu Jul 10 02:24:51 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 10 Jul 2008 08:24:51 +0200 Subject: socket-module: different behaviour on windows / unix when a timeout is set References: Message-ID: On 2008-07-09, Mirko Vogt wrote: > Is that behaviour common or even documented? Found nothing. Second sentence in the socket module documentation: Note: Some behavior may be platform dependent, since calls are made to the operating system socket APIs. So yes, what you found is probably how it should behave. Albert From andre at descombes.info Sun Jul 20 10:11:56 2008 From: andre at descombes.info (=?ISO-8859-1?Q?Andr=E9_Michel_Descombes?=) Date: Sun, 20 Jul 2008 16:11:56 +0200 Subject: scanf equivalent in python Message-ID: Hello, I often need to parse strings which contain a mix of characters, integers and floats, the C-language scanf function is very practical for this purpose. I've been looking for such a feature and I have been quite surprised to find that it has been discussed as far back as 2001 but never implemented. The recommended approach seems to be to use split and then atoi or atof or to use regex and then atoi and atof. Both approaches seem to be a lot less natural and much more cumbersome than scanf. If python already has a % string operator that behaves like printf, why not implement either a %% or << string operator to behave like scanf, use could be like the followng: a, b, c = "%d %f %5c" %% "1 2.0 abcde" or a, b, c = "%d %f %5c" << "1 2.0 abcde" %% is closer to the % operator << seems more intuitive to me either of this methods seems to me much simpler than: lst = "1 2;0 abcde".split() a = int(lst[0]) b = float(lst[1]) c = lst[2] or even worse when using regular expressions to parse such simple input. I like python because it is concise and easy to read and I really think it could use such an operator. I know this has been discussed before and many times, but all previous threads I found seem to be dead and I would like to invite further investigation of this topic. Cheers, Andr? M. Descombes -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.desthuilliers at gmail.com Tue Jul 1 16:53:24 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Tue, 1 Jul 2008 13:53:24 -0700 (PDT) Subject: Why is recursion so slow? References: <25660cd1-dd91-4236-bd95-c074e1b27f49@26g2000hsk.googlegroups.com> Message-ID: On 1 juil, 22:46, Nick Craig-Wood wrote: (snip) > By definition any function in a functional language will > always produce the same result if given the same arguments, This is only true for pure functional languages. I know you know it, but someone might think it also applies to unpure FPLs like Common Lisp. (snip) From torriem at gmail.com Mon Jul 28 01:37:48 2008 From: torriem at gmail.com (Michael Torrie) Date: Sun, 27 Jul 2008 23:37:48 -0600 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <488D5B2C.10808@gmail.com> Colin J. Williams wrote: >> >> def fun( ., cat): >> > I don't see the need for the comma in fun. It (the entire first variable!) is needed because a method object is constructed from a normal function object: def method(self,a,b): pass class MyClass(object): pass MyClass.testmethod=method That's precisely the same as if you'd defined method inside of the class to begin with. A function becomes a method when the lookup procedure in the instance object looks up the attribute and returns (from what I understand) essentially a closure that binds the instance to the first variable of the function. The result is known as a bound method, which is a callable object: >>> instance=MyClass() >>> instance.testmethod > How would this work if there was not first parameter at all? In short, unlike what most of the implicit self advocates are saying, it's not just a simple change to the python parser to do this. It would require a change in the interpreter itself and how it deals with classes. From rocksportrocker at googlemail.com Sat Jul 12 06:39:12 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Sat, 12 Jul 2008 03:39:12 -0700 (PDT) Subject: How to create a timer/scheduler in Python? References: <0stg74t0eksmnfsslukn5m7f9s4rbub8kt@4ax.com> Message-ID: <90d09691-1c43-4618-bbb7-a8c04496752f@k37g2000hsf.googlegroups.com> On 12 Jul., 11:30, John Dann wrote: > I need what I'd call (in .Net) a timer, ie I need to run a function eg > every 2 seconds - it doesn't need to be millisec accurate but it would > be nice if it wasn't eg every 4 seconds or something. > > Rather surprisingly, Core Python (Chun) doesn't seem to index 'timer' > or 'scheduler', which leaves me wondering whether this is an aspect of > Python that isn't perhaps widely used? > > Looking around on the net I can see references to a thread timer, but > I'm not really looking to start any new threads (I just want part of > the GUI to update every 2 secs) and don't want to get into that sort > of complication while still just learning Python. > > Is there really no simple timer/scheduler function available in > Python? The usual way is to use threads. Depending on you GUI lib there may exist replacements for threads, eg wxPython. As most (all ?) GUIs have some event handling mechanisms they should be able to schedule tasks and process them in the background. By the way: Using threads in Python is quite simple, even if you are a novice. Greetings, Uwe From max at alcyone.com Tue Jul 22 17:13:34 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 22 Jul 2008 14:13:34 -0700 Subject: Python Written in C? In-Reply-To: References: <143349c3-b0e9-49d8-9426-8b030b23d2c9@l42g2000hsc.googlegroups.com> Message-ID: Ethan Furman wrote: > Iain King wrote: >> On Jul 21, 6:58 am, "Krishnakant Mane" wrote: >> >>> First off all c# is absolute rubbish waist of time. if I need to >>> learn it then I better lern java or pythonfor that matter. and by the >>> way what is a "real programmer?" >> >> The story of a Real Programmer: >> >> http://www.pbm.com/~lindahl/mel.html >> >> Iain > > Wow. Awesome story. If my google-fu is up to snuff, these are "screenshots" (scans of printouts) of the actual blackjack game in operation: http://wps.com/projects/LGP-21/Software/LGP30-Blackjack1.jpg http://wps.com/projects/LGP-21/Software/LGP30-Blackjack2.jpg and here's a scan of a printout of some "source code" (machine language): http://wps.com/projects/LGP-21/Software/CrapGame.tiff -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis In time of war the devil makes more room in hell. -- (a German proverb) From bearophileHUGS at lycos.com Thu Jul 31 07:13:35 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 31 Jul 2008 04:13:35 -0700 (PDT) Subject: Case tagging and python References: Message-ID: <1cdb154c-da87-47a8-9e6d-66597a107480@x35g2000hsb.googlegroups.com> Fred Mangusta: > Could I use the join function to reform the string? You can write a function to split the words, for example taking in account the points too, etc. > And, regarding the casetest() function, what do you suggest to do? Python strings have isupper, islower, istitle methods, they may be enough for your purposes. > -open input file > -open output file > -get line of text > -split line into words > -for each word > -tag = checkCase(word) > -newword = lowercase(word) + append(tag) > rejoin words into line > write line into output file It seems good. To join the words of a line there's str.join. Now you can write a function that splits lines, and another to check the case, then you can show them to us. Yet, I don't see how much use can have your output file :-) Bye, bearophile From arslanburney at gmail.com Thu Jul 17 02:50:25 2008 From: arslanburney at gmail.com (J-Burns) Date: Wed, 16 Jul 2008 23:50:25 -0700 (PDT) Subject: Rotating a cube Message-ID: Hello. Need some help here. I have a 4*4 cube. So the equation of the cube becoming: x + 4*y + 16*z Now i want to rotate this cube 90 degrees anticlockwise( a right rotation). How can i do that? The rotation must take place with the axis of rotation being the straight line through the center of the cube and perpendicular to the "xz-plane." The axis are aligned in this fashion: y | | |________ x / / z Moreover, also tell me how to perform a rotation with the axis of rotation being the straight line through the center of the cube and perpendicular to the "yz-plane." Essentially, I need the equations of the lines after the rotation has been done in both cases. Is there a built in Python function for this? From r.grimm at science-computing.de Fri Jul 18 02:52:13 2008 From: r.grimm at science-computing.de (r.grimm at science-computing.de) Date: Thu, 17 Jul 2008 23:52:13 -0700 (PDT) Subject: None in comparison Message-ID: <549f01d2-1d15-4b0d-9440-a9402c0449ff@b2g2000prf.googlegroups.com> Hello, I'm a little confused about None in comparison. >>> id ( None ) 3086100672L >>> id ( 1 ) 134541104 >>> None < 1 True >>> I thought, the id of the object is the last comparison criterion. Therefore, None must be greater then 1. Where is the behaviour of the comparison defined?. In the __cmp__ of int. Or in the global cmp Function? Thanks in advance Rainer From bdesth.quelquechose at free.quelquepart.fr Sun Jul 27 14:27:11 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 27 Jul 2008 20:27:11 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> Message-ID: <488cd9f5$0$14746$426a74cc@news.free.fr> Russ P. a ?crit : > On Jul 26, 11:22 pm, Terry Reedy wrote: >> Russ P. wrote: >>> On Jul 26, 2:25 pm, Terry Reedy >>>> There is a lot of code you have not seen. Really. In informal code I >>>> use 's' and 'o' for 'self' and 'other'. I don't usually post such >>>> because it is not considered polite. So you have seen a biased sample >>>> of the universe. >>> You take the name down to a single letter. As I suggested in an >>> earlier post on this thread, why not take it down to zero letters? >> Because 1 letter is legal now, while no letters (already proposed and >> rejected) is a major change and breakage of current simplicity and >> consistency for zero functional benefit. > > Sorry, but I fail to see how it is a "major change." It only applies > to the first argument of a class member function, There's nothing like a "class member function" in Python. From kyosohma at gmail.com Thu Jul 3 10:35:10 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 3 Jul 2008 07:35:10 -0700 (PDT) Subject: site-packages, unzipepd there but import fails References: Message-ID: On Jul 3, 9:11?am, defn noob wrote: > i unzipped and put the folder in site-packages. when i run setup.py > install nothing happens. > > when i do import pp from shell it complains it doesnt exist. What is "pp"? Parallel Python? > > isnt placing the folder in site-packages enough? Usually. Sometimes you have to add the package to the Path too though. > > these setup.py-files often dont work but normally it still works. I rarely have any trouble with them on Windows, although the troublesome ones do exist. Mike From semanticist at gmail.com Sun Jul 13 16:40:30 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 16:40:30 -0400 Subject: heapq question In-Reply-To: References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> Message-ID: On Sun, Jul 13, 2008 at 4:16 PM, Duncan Booth wrote: > "Giampaolo Rodola'" wrote: >> I understand that heapq is not that efficient to implement timeouts as >> I thought at first. >> It would have been perfect if there were functions to remove arbitrary >> elements withouth needing to re-heapify() the heap every time. >> > There could be suitable functions, but there aren't any. > ... > Bottom line though is that heaps aren't really suitable for timeouts. I would argue that heaps in general are ideally suited for timeouts; it's just that the Python heapq implementation is lacking if you ever need to cancel a timeout before it expires. -Miles From cokofreedom at gmail.com Thu Jul 24 11:04:44 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 24 Jul 2008 08:04:44 -0700 (PDT) Subject: New to Python, familiar with Perl - Seeking info sources References: <18c8fc73-8ff9-4640-a020-de0be4b76ca4@z72g2000hsb.googlegroups.com> Message-ID: On Jul 24, 3:53 pm, Brett Ritter wrote: > After many years happily coding Perl, I'm looking to expand my > horizons. [no flames please, I'm pretty aware of Perl's strengths and > weaknesses and I'm just here to learn more, not to enter religious > debates]. > > I've gone through some of the online tutorials and I'll be browsing > the reference before starting the "code a lot" phase. > > My question is: What are the best sources to learn best practices or > get the answers to questions? Are there any good sources to tell me > what Perl habits are good/bad in the Python paradigm? What about > common packages that will change my life? (I do a lot of web work, > but also a lot of DB reporting) I'm also working as a Java developer > primarily, so I'm glad to see that Jython has been resurrected, but > I'm focusing on vanilla Python for the moment. > > As examples: PerlMonks has been my info source. The Perl Best > Practices and Higher Order Perl books have been my tutors into better > coding practices. CPAN has my life easy, giving me access to the DBI, > Class::DBI (and its successors), HTML::FillInForm, > Data::FormValidator, CGI::Application, and Text::CSV::Simple modules > that are staples of my coding. The (occasionally complete) Perl > Advent calendars have proven to be a good source to learn about > helpful modules that I might not otherwise stumble across. > > (I've encountered Django, but I'm getting my fill of "frameworks" from > Java for the moment, so I'm looking for lightweight pieces at the > moment) > > My (admittedly brief) searches here and on google didn't lead me to > any particular spots of concentrated Python info, and most of the Perl/ > Python stuff is either a smug attack by one camp on the other or a > rant about the behavior of an obscure feature between the two. > > Any recommendations? Thanks in advance. Best start is a quick read of DiveIntoPython that provides a nice account of how to work with Python, and relates to coming from a programming background. I also keep this List on my bookmarks, as well as the python library (http://docs.python.org//lib/). The ActiveState Python Cookbook (http://aspn.activestate.com/ASPN/ Python/Cookbook/) generally has a lot of useful code snippets worth using. Zen of Python (http://www.python.org/dev/peps/pep-0020/) shows the idea of Python and (http://www.python.org/dev/peps/pep-0008/) is the Style Guidelines for Python code. I haven't worked with the web and Python much yet so maybe someone else can help you there. Welcome :) From kanchana.senevirathna at gmail.com Tue Jul 22 05:00:41 2008 From: kanchana.senevirathna at gmail.com (Kanchana) Date: Tue, 22 Jul 2008 02:00:41 -0700 (PDT) Subject: xpathEval fails for large files Message-ID: <6edfd8b2-1297-4d56-a2ab-4046e7697f32@y38g2000hsy.googlegroups.com> Hi, I tried to extract some data with xpathEval. Path contain more than 100,000 elements. doc = libxml2.parseFile("test.xml") ctxt = doc.xpathNewContext() result = ctxt.xpathEval('//src_ref/@editions') doc.freeDoc() ctxt.xpathFreeContext() this will stuck in following line and will result in high usage of CPU. result = ctxt.xpathEval('//src_ref/@editions') Any suggestions to resolve this. Is there any better alternative to handle large documents? Kanch From fredrik at pythonware.com Wed Jul 16 17:23:48 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 23:23:48 +0200 Subject: how to match whole word In-Reply-To: <31b6a6c2-e152-418d-b5a1-477dc3dd15aa@s50g2000hsb.googlegroups.com> References: <97461ec5-151a-4527-a5fa-c5da07941e46@l42g2000hsc.googlegroups.com> <31b6a6c2-e152-418d-b5a1-477dc3dd15aa@s50g2000hsb.googlegroups.com> Message-ID: John S wrote: > Not sure why you picked \A and \Z -- they are only useful if you are > using the re.M flag. Well, they're aliases for ^ and $ in "normal" mode, at least for strings that don't end with a newline. > re.I is the same as re.IGNORECASE. More than one option may be OR'ed > together. There's no such thing as "re.O" in Python. I can understand > where you get the idea, as there is an 'o' modifier for REs in Perl. His code did opts.ignore_case and re.I or 0 which is the same as "re.I if opts.ignore_case else 0" in Python 2.5, where 0 is a zero and not an O. From JordanNealBerg at gmail.com Thu Jul 10 16:47:02 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Thu, 10 Jul 2008 13:47:02 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: <8feab8ce-1e09-4438-b00a-3b31956c56af@k37g2000hsf.googlegroups.com> <5c521979-aaf0-4b4b-9673-671a978d050a@j22g2000hsf.googlegroups.com> <3hqc74lhdkdqrjb20h34k6ab65g2hc8ucp@4ax.com> Message-ID: Well, that about wraps this up...MRAB was 100% correct, that solution worked...not sure how I managed to mess it up when I tried it early. Based on the incoming values of u here is the code with the minimal number of maskings: def findit(u): mask = 0xffffffff u += 0xe91aaa35 u ^= u >> 16 u = (u + (u << 8)) & mask u ^= u >> 4 b = (u >> 8) & 0x1ff a = (u + (u << 2) & mask) >> 19 r = a ^ hash_adjust[b] return r Thanks for your help all! From lie.1296 at gmail.com Sat Jul 26 19:26:04 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 27 Jul 2008 06:26:04 +0700 Subject: Insert character at a fixed position of lines In-Reply-To: References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> Message-ID: <1217114764.6402.5.camel@lieryan-laptop> On Sat, 2008-07-26 at 17:47 +0200, Francesco Pietra wrote: > Sorry to come again for the same problem. On commanding: > > $ python script.py 2>&1 | tee fileout.pdb > > nothing occurred (fileout.pdb was zero byte). The script reads: > > f = open("xxx.pdb", "w") > f.write('line = line[:22] + "A" + line[23:]') > f.close() > > File xxx.pdb is opened by the command: when I forgot the single quote > ' after [23:] the error answer was: > SynthaxError: EOL while scanning single-quoted string. > > Thanks > francesco I'd expect fileout.pdb to be zero bytes, what you have piped to tee fileout.pdb is the stdout of your script, i.e. whatever you "print". Since you "print"ed nothing, nothing is written to fileout.pdb You'd find your written material in the file referenced by f, i.e. "xxx.pdb". Btw, if you do f.write('line = line[:22] + "A" + line[23:]'), you'd output exactly that, and not inserting the 23rd character, you'd want to do this instead: f.write(?line = line[:22] + "A" + line[23:]) > On Sat, Jul 26, 2008 at 1:10 PM, Lie wrote: > > On Jul 26, 5:42 pm, "Francesco Pietra" wrote: > >> I am still at the stone age, using scripts (e.g., to insert a string > >> after a string) of the type > >> > >> f = open("xxx.pdb", "r") > >> for line in f: > >> print line > >> if "H16Z POPC" in line: > >> print "TER" > >> f.close() > >> > >> That is, I have to learn about modules. In your scripts I am lost > >> about the filename for the pdb file to modify, > > > > In Python, stdin and stdout (as provided by the sys module) is a file- > > like object, i.e. it have similar behavior as regular files you opened > > with open(). stdin is a read-only file, while stdout is a write-only > > file. You already know how to make read-only file, f = open("xxx.pdb", > > "r"), to make it writable, you've got to use 'w' as the mode: f = > > open("xxx.pdb", "w") > > > > After that you can do this: > > f.write('some string') > > > > > >> francesco > >> > >> > >> > >> On Sat, Jul 26, 2008 at 11:35 AM, Lie wrote: > >> > On Jul 26, 2:41 pm, "Francesco Pietra" wrote: > >> >> How to insert letter "A" on each line (of a very long list of lines) > >> >> at position 22, i.e., one space after "LEU", leaving all other > >> >> characters at the same position as in the original example: > >> > >> >> ATOM 1 N LEU 1 146.615 40.494 103.776 1.00 73.04 1SG 2 > >> > >> >> In all lines"ATOM" is constant as to both position and string, while > >> >> "LEU" is constant as to position only, i.e., "LEU" may be replaced by > >> >> three different uppercase letters. Therefore, the most direct > >> >> indication would be position 22. > >> > >> >> Should the script introduce blank lines, no problem. That I know how > >> >> to correct with a subsequent script. > >> > >> >> Thanks > >> >> chiendarret > >> > >> > If you want to leave the rest of the strings as-is (i.e. the letter A > >> > overwrites whatever on position 22), Peter's code need to be modified > >> > a little: > >> > line = line[:22] + " " + line[23:] > >> > -- > >> >http://mail.python.org/mailman/listinfo/python-list > >> > >> -- > >> Dr Francesco Pietra > >> Professor of Chemistry > >> Accademia Lucchese di Scienze, Lettere e Arti, founded in 1594 > >> Palazzo Ducale > >> 55100 Lucca (Italy) > >> e-mail chiendar... at gmail.com > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > From stefan_ml at behnel.de Thu Jul 24 12:26:16 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 24 Jul 2008 18:26:16 +0200 Subject: lxml, comparing nodes In-Reply-To: <6c91a4da-6443-4570-8dd3-01c4ec169bf3@t54g2000hsg.googlegroups.com> References: <804a4959-3724-4008-a450-856e637ec7e2@w7g2000hsa.googlegroups.com> <48875c62$0$19907$9b4e6d93@newsspool1.arcor-online.net> <6c91a4da-6443-4570-8dd3-01c4ec169bf3@t54g2000hsg.googlegroups.com> Message-ID: <4888ad28$0$9491$9b4e6d93@newsspool3.arcor-online.net> code_berzerker wrote: > Thanks for help. Thats inspiring, tho not exactly what I need, coz > ignoring document order is requirement (ignoring changes in order of > different siblings of the same type, etc). I plan to try something > like that: > > def xmlCmp(xmlStr1, xmlStr2): > et1 = etree.XML(xmlStr1) > et2 = etree.XML(xmlStr2) > > queue = [] > tmpq = deque([et1]) > tmpq2 = deque([et2]) > > while tmpq: > el = tmpq.popleft() > tmpq.extend(el) > queue.append(el.tag) > > while queue: > el = queue.pop() > foundEl = findMatchingElem(el, et2) > if foundEl: > et1.remove(el) > tmpq2.remove(foundEl) > else: > return False > > if len(tmpq2) == 0: > return True > else: > return False If document order doesn't matter, try sorting the elements of each level in the two documents by some arbitrary deterministic key, such as (tag name, text, attr count, whatever), and then compare them in order, instead of trying to find matches in multiple passes. itertools.groupby() might be your friend here. Stefan From bsagert at gmail.com Wed Jul 9 19:39:24 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Wed, 9 Jul 2008 16:39:24 -0700 (PDT) Subject: Python and decimal character entities over 128. Message-ID: <95e7a2c4-0027-45e6-ace6-f0b414a0fd1c@34g2000hsh.googlegroups.com> Some web feeds use decimal character entities that seem to confuse Python (or me). For example, the string "doesn't" may be coded as "doesn’t" which should produce a right leaning apostrophe. Python hates decimal entities beyond 128 so it chokes unless you do something like string.encode('utf-8'). Even then, what should have been a right-leaning apostrophe ends up as "???". The following script does just that. Look for the string "The Canuck iPhone: Apple doesn? ??t care" after running it. # coding: UTF-8 import feedparser s = '' d = feedparser.parse('http://feeds.feedburner.com/Mathewingramcom/ work') title = d.feed.title link = d.feed.link for i in range(0,4): title = d.entries[i].title link = d.entries[i].link s += title +'\n' + link + '\n' f = open('c:/x/test.txt', 'w') f.write(s.encode('utf-8')) f.close() This useless script is adapted from a "useful" script. Its only purpose is to ask the Python community how I can deal with decimal entities > 128. Thanks in advance, Bill From thomas.troeger.ext at siemens.com Thu Jul 31 07:32:39 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Thu, 31 Jul 2008 13:32:39 +0200 Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> Message-ID: > Can someone explain to me the difference between a type and a class? If your confusion is of a more general nature I suggest reading the introduction of `Design Patterns' (ISBN-10: 0201633612), under `Specifying Object Interfaces'. In short: A type denotes a certain interface, i.e. a set of signatures, whereas a class tells us how an object is implemented (like a blueprint). A class can have many types if it implements all their interfaces, and different classes can have the same type if they share a common interface. The following example should clarify matters: class A: def bar(self): print "A" class B: def bar(self): print "B" class C: def bla(self): print "C" def foo(x): x.bar() you can call foo with instances of both A and B, because both classes share a common type, namely the type that has a `bar' method), but not with an instance of C because it has no method `bar'. Btw, this example shows the use of duck typing (http://en.wikipedia.org/wiki/Duck_typing). HTH, Thomas. From jeffrey at fro.man Thu Jul 10 10:30:37 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 10 Jul 2008 07:30:37 -0700 Subject: python scalability References: Message-ID: Tim Mitchell wrote: > One of my project managers questions is: "Are we the only company in the > world with this kind and size of project?" I can't provide a bigger success story personally (my largest project is currently about 15k lines of code, eminently manageable by one person.) But Google comes to mind. Just a feeling I get from quotes like: "Python is big at Google ... being used for everything from build tools to managing ads." -- Guido Van Rossum http://www.artima.com/weblogs/viewpost.jsp?thread=143947 "When programming in python, one should design for scalability. If you design properly, the you should be able to just throw more machines at the problem and your app should scale fine." -- Greg Stein's PyCON keynote, paraphrased by Matt Harrison http://panela.blog-city.com/python_at_google_greg_stein__sdforum.htm Maybe that's not exactly the sort of scalability you're referring to, but certainly Goolge is colossal in its deployment. I have a hard time imagining that scalability based on "N lines of code" is going to be any better in any other language. Jeffrey From bj_666 at gmx.net Thu Jul 10 00:55:45 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Jul 2008 04:55:45 GMT Subject: Manipulating bitsets in struct References: Message-ID: <6dlj2hF35ua2U1@mid.uni-berlin.de> On Wed, 09 Jul 2008 20:04:24 -0400, Allen wrote: > I'm using Python to do some simple network programming, and found the > struct module very useful for such things, but is there a way to easily > manipulate bitsets such as a 16 bit word being split into 4 parts like 2 > bits, 1 bit, 4 bits, and 9 bits? > > Perhaps something like: > > struct.pack('!h(2:1:4:9)',2,0,1,100) Take a look at Construct_ instead of `struct`. .. _Construct: http://construct.wikispaces.com/ Ciao, Marc 'BlackJack' Rintsch From michael at stroeder.com Fri Jul 4 03:49:55 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 04 Jul 2008 09:49:55 +0200 Subject: Parsing MIME-encoded data in an HTTP request In-Reply-To: References: Message-ID: <3a11k5-al7.ln1@nb2.stroeder.com> Ron Garret wrote: > I'm writing a little HTTP server and need to parse request content that > is mime-encoded. All the MIME routines in the Python standard library > seem to have been subsumed into the email package, which makes this > operation a little awkward. How about using cgi.parse_multipart()? Ciao, Michael. From andreas.tawn at ubisoft.com Wed Jul 16 08:24:19 2008 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Wed, 16 Jul 2008 14:24:19 +0200 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: <487DDEE9.8060305@timgolden.me.uk> References: <8AEDA5E3386EA742B8C24C95FF0C758004623111@PDC-MAIL3.ubisoft.org> <487DDEE9.8060305@timgolden.me.uk> Message-ID: <8AEDA5E3386EA742B8C24C95FF0C7580046232B6@PDC-MAIL3.ubisoft.org> > Andreas Tawn wrote: > > Terry Reedy wrote: > >> Wrong. > > Thank you. > > > >> For loop variables continue after the loop exits. This is > >> intentional. > > I never knew that and I can't find reference to it in the docs. > > Interesting starting point. It never occurred to me > that they might not. (So I didn't look for anything > in the docs when they did :) ). > > TJG I don't have experience of too many other languages, but in C++ (and I guess C)... for (int i=0; i<10; ++i) { doStuff(i); } doStuff(i); // Error int i; for (i=0; i<10;++i) { doStuff(i); } doStuff(i); // No error That's the behaviour I was expecting. Is the Python behaviour just a happy side effect of the target list assignment or specific design decision? Cheers, Drea From babacity4 at gmail.com Thu Jul 24 16:54:51 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:54:51 -0700 (PDT) Subject: www Spankwire - Amazing porn video collection Message-ID: <06ee6164-9e2f-446a-9d4e-3826b61b94f3@j1g2000prb.googlegroups.com> www spankwire . >>>>>>>>>>Best Collection of Spankwire Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE www spankwire VIDEOS<<<<<<<<<<< . www spankwire From xahlee at gmail.com Tue Jul 22 21:44:02 2008 From: xahlee at gmail.com (xahlee at gmail.com) Date: Tue, 22 Jul 2008 18:44:02 -0700 (PDT) Subject: proliferation of computer languages References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> Message-ID: <637ca9de-75d6-48e4-b6fd-0bd36020c209@c65g2000hsa.googlegroups.com> over the past 5 years there are some negative remarks on me or my posts. I have almost never responded to any of them. Here i want to clarify a few things. ? I seldomly write off-topic posts. For example, any argument about netiquette, i consider off-topic, including defense such as what i'm doing now. But in recent years i gradually relaxed my stringent self- imposed rules in my posting habit. (See ?Aloofness vs Approable? http://xahlee.org/UnixResource_dir/writ/aloof_vs_approachable.html ) ? many says i'm posting off topic posts. In recent years they start to say i'm posting tangentially relevant posts. That's not correct. In fact, there are huge number of blatantly off-topics posts by regulars that spawn off from threads, happens regularly. The topics vary anywhere from discussing politics, law, licenses, free speech, math education, yapping on happenings of celebrity programers, and including rampant flamewars and accusations among themselves. (see ? ?Old School Netiquette? http://xahlee.org/UnixResource_dir/writ/os_netiquette.html ) ? Some people says that i don't participate in discussion, and this is part of the reason they think i'm a so-called ?troll?. Actually i do, and read every reply to my post, as well have replied to technical questions other posted. Most reply to my posts are attacks or trivial (of few sentences) i don't consider worthy to reply. A few, maybe 10% replies to my controvial posts, i consider having some value. But if i don't have opinion on what they remarked, i don't reply. Also, if all i wanted to say is ?thanks?, i tend to avoid posting such trivial posts too. (i used to reply by personal email in such cases, I still do sometimes now, but today that can be considered intrusive.) (see ? ?Philosophies of Netiquette? http://xahlee.org/UnixResource_dir/writ/phil_netiquette.html , ) In newsgroups which i feel i'm more part of the community, i do reply more often. (e.g. in the dot com years (~1999) i'm much more active in comp.lang.perl.misc including asking technical questions; during 2005-2006 while i was learning python, did somewhat frequent posts to comp.lang.python; in this year in comp.lang.lisp, i frequently replied and argued more freely. But in this year, also very active in gnu.emacs.help, most of my posts there just answered tech questions) ? Most newsgroup tech geekers consider cross-posting wrong. I consider the taboo of this convention being a major contribution to the redundant creation of new languages, and foster the hostile faction nature of programing language communities we see. (see ? ?Cross-posting & Language Factions? http://xahlee.org/Netiquette_dir/cross-post.html ) ? There's a lot rumors that says i post prodigiously. Actually, when i'm active, i post only about 1 or 2 posts per week, in the past 10 years. (See the ?Aloofness vs Approachble? article cited above. Note that, last time i checked, the stat given by poster's profile at groups.google.com is actually erroneous. I think it counts all replies or multiply cross posts) ? Many say i repeatedly post old essays i wrote that are published on my website. The total number of times i've done that is perhaps 4 or absoletly less than than 10, since the 12 years of using newsgroup started in 1996. The first of such ?repeat? must be sometimes after 2004. The interval of a ?repeat? happens is at least half a year, more likely 1 or 2 years. Also, the repeat does not happen more than once. (to be absolutely correct, possibly there is 1 essay that are posted at a max of 3 times) I ?repeat? a essay i've written because i think the issue is important, the situation has not changed, and i consider it worth to be said again. When appropriate, i incorporate information from the discussion into by my essay, with proper credits. (this esp has happened in my Python tutorial, emacs lisp tutorial, java tutorial, various classical literature on my site) Actually, most accusations about me falls apart if one just take 10 min to check the facts. ? When i used my google email account to post, as opposed to my older google account xah at xahlee.org, often people accuse me of ?changing identity to avoid killfile?. This is just one of their ways these people drivel. I don't really give a fuck i'm kill filed or not kill filed. People change emails all the time. In the past 10 years of using newsgroups, i've only used xah at xahlee.org and xahlee at gmail.com . And before 2000, i had few other emails before i registered the domain xahlee.org. I rather stick with xah at xahlee.org, but the re-login to different google accounts with several of their services is becoming a pain. See, for example, this post this month: http://groups.google.com/group/Google-Accounts-API/browse_thread/thread/a179b4fd348900aa?tvc=2 Also, whenever i had a new webhosting provider, people dig it up and accuse me of changing IP to troll. (this happens more frequently in the past, say before 2003, i think that the knowledge of digging up IP is now considered lame even amoneg these stupid tech geekers) My site xahlee.org has changed web hosting about every 2 years for variety of reasons. For a few years it was hosted free on the math educational site that used to be mathforum.org of Swathmore edu. (For some detail of my website hosting and history, see: ? ?Web Hosting Compared: 2006-01? http://xahlee.org/Periodic_dosage_dir/t1/webhosting.html A little trivia: before i had xahlee.org in 2000, my site was hosted at best.com/~xah starting in 1996. Some very very old sites still link to that. ) The only time that my change of web hoster has anything to do with my posting, is in 2006 someone harrassed me to have my web hosting kick me off due to my controversial postings in comp.lang.* groups. I have written a detailed account about it on my website. you can easily find the url by web search ?xah, dreamhost, harrassment?. (for the record, any ban, or harrasment on me, i keep a record as truthful as possile. Most of these bans, kicks, or fights happens in just aboun every online forum, inworld game groups, irc chat groups, ...etc where the participants are almost all males. Typically, they are not unlike highschool boys brawling things out. If the issue effected me or pissed me in some serious way, i publish it on my website. The keeping record is very tedious. For example, in newsgroups you might want to save all the messages in a thread this happened. In online forums, blogs, social networking sites, where posts can be deleted or modified easily, it's more tedious to keep a history of the site (e.g. screenshots), and to keep a manual written log of what happened when. Similarly, in irc, you have to save the chat, manage the chat logs, adding comment on what happened where with what chat log, finding out people's real identities if proper, etc. (as a example, i've been ban'd in freenode.com's #emacs irc chat since 2006. See ? ?Emacs Irc Channel Ban on Xah Lee? http://xahlee.org/emacs/xah_ban_emacs_irc.html . I have a bunch of irc chat logs when i'm banned. I always save the chat log when someone ban me unjustly. But it's quite time consuming to organize them and write about them.)) (as another example of ban, in about 2 months ago i was ban'd in Wikipedia. I was editing 3 article related to Tibet, of which i consider my edit very proper. But, in my opinion, it's too much againt Western's popular beliefs. I wrote detailed argument about my edit in my Wikipedia's personal talk page. The Wikipedia fuckheads not only ban'd me, but subsequently ban'd me in editing my pesonal Wikipedia page too, and blatantly deleted the detailed reason that i defended my edit. The incident is here, bottom: http://en.wikipedia.org/wiki/User_talk:P0lyglut the writing where i defended my edit, is here: http://en.wikipedia.org/w/index.php?title=User_talk:P0lyglut&diff=prev&oldid=215672906 Wikipedia these days is a huge organization (ranked top 10 of all sites), and part of the good thing is that they have some rules and regulations that prevents the fuckheads powers struggle too much, in that they have 1-month ban, with record of history, and in general has ways to further one's case to judgement. However, it's still subject to a lot tech geekers or other cartel of vested interest in keeping some article to the way they liked. I do consider Wikipedia one of the most important site and in fact part of my life, but these days i avoid ?contributing?. (e.g. i have now over 4000 links to Wikipedia articles from my site. I estimate, that for each link i've made, there are maybe 10 more article i've read. See for example: ? ?Links To Wikipedia from XahLee.org? http://xahlee.org/wikipedia_links.html , ? ?Generate a Web Links Report with Emacs Lisp? http://xahlee.org/emacs/elisp_link_report.html , ? ?Encyclopedia, My Experiences? http://xahlee.org/Periodic_dosage_dir/encyclopedia.html ? ?Lispers and Wikipedia? http://xahlee.org/emacs/lispers_n_wikipedia.html ) ) ----------------- I've been actively using online forums since 1991 in CompuServe and AppleLink days. I've seen my share of flames, netiquette arguments, etc. (the medium include: newsgroup, mailing list, web forum, irc, communities inside massive multi-player online games) I've been banned now and then in places. (in one case, legally definable harrassment, which happened and perhapss well-known at the time in comp.lang.* groups few years ago) From what i see, the banning, heated accusations and quarrels, are mostly exhibition of male nature and political struggle, not unlike political struggles that happens in society at large, such as in academia, corporations, goverment orgs, between corporations, between nations. Some say ?why can't you be normal?? It is true i tend to discuss controversial topics and with non- conformal attitude. I have my reasons and you could say it's just a personality. However, ?being not normal? is not a reason to accuse. There are philosophers, unorthodox, dissenters, free thinkers, flag bunners, protesters, traitor/founder, homosexuals ... many are persecuted, considered a crime, in the past, and some are now considered national or international heros. Btw, this post is not some kinda formal defense to some formal accusations. Newsgroups has always been a very contentious and argumentive medium, and perhaps far more wortheless with relatively little readership and impact on society than tech geeking regulars like to think. People in fact like newsgroups that way. I don't feel necessary to respond to morons. This post is just one of my post i feels like writing. You guys to whatever it is that you do. PS as i have detailed, i have my own moral ethics in posting. Most posts and opinions are just too stupid, igonrant, for me to consider replying. If you really belived that some of my opinion or posts are wrong, contain bad advice, or wrong fact, then do post, as i do read every reply it shows up in groups.google.com. And, whatever is your opinion, i would recommend you spend 30 minutes to write your reply. (as i do spend 1 to even 6 hours in most of my newsgroup posts as explained in detail in one of the above cited article) Also, if the subject is unconventional and you see i put forth my opinion forcefully, i suggest you take 30 minutes, to think, do research, about it before you reply. Also, if prefer to reply to those who post with real names. Again, i don't consider this is some serious issue, or that my opinions and beliefs and behaviors are always correct. It's just another newsgroup day. Do whatever it is that you do. Xah ? http://xahlee.org/ ? From bignose+hates-spam at benfinney.id.au Thu Jul 10 19:50:31 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 11 Jul 2008 09:50:31 +1000 Subject: Python and decimal character entities over 128. References: <95e7a2c4-0027-45e6-ace6-f0b414a0fd1c@34g2000hsh.googlegroups.com> Message-ID: <87vdzds3i0.fsf@benfinney.id.au> I don't have an answer for why Python might be mis-handling the data, but wanted to make a factual correction: bsagert at gmail.com writes: > Some web feeds use decimal character entities that seem to confuse > Python (or me). For example, the string "doesn't" may be coded as > "doesn’t" which should produce a right leaning apostrophe. That character isn't a "right leaning apostrophe"; it has nothing to do with apostrophes. It is the character called "right single quotation mark" in and in Unicode (code point U+2019). It's a typographical error to use a quotation mark as an apostrophe. Use the apostrophe character (U+0027) where an apostrophe is intended, and quotation mark characters where those are intended. This is directed, of course, at the person generating that output. -- \ ?If you go to a costume party at your boss's house, wouldn't | `\ you think a good costume would be to dress up like the boss's | _o__) wife? Trust me, it's not.? ?Jack Handey | Ben Finney From fredrik at pythonware.com Wed Jul 23 08:02:24 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 14:02:24 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> Message-ID: Jaco Naude wrote: > That said, let me double check something which might be causing > problems since you will be familiar with this. Which Python.h file do > you include when including the DLL in your programs? The one in the > source distribution of the one in the installation distribution? I've > been including the one in the installation distribution all along. > When I try to include the one in the source distribution it gets up to > the point where it looks for the following include: > > #include "pyconfig.h" > > This file is not in the same directory as the Python.h file in the > source distribution. Because of this I just used Python.h in the > installation distribution. that's just two copies of the same file, as far as I know. the "pyconfig.h" file contains platform-specific information; it's generated from pyconfig.h.in on Unix-style systems, and copied from the PC directory on Windows. From nagle at animats.com Tue Jul 22 14:48:25 2008 From: nagle at animats.com (John Nagle) Date: Tue, 22 Jul 2008 11:48:25 -0700 Subject: CPython VM internals - Wiki page In-Reply-To: References: Message-ID: <48862716$0$17157$742ec2ed@news.sonic.net> Terry Reedy wrote: > Various people have asked on c.l.p about documentation of CPython's > virtual machine internals. The usual answers have been to see the dis > module doc for bytecodes and 'read the code' for more. Jakob Sievers > did so and posted his notes, with additions from Martin v. L?wis, as > > http://wiki.python.org/moin/CPythonVmInternals That's interesting. It's dumber than I thought. All temporaries on the stack are "boxed" as PyObjects. That's simple and portable, but slow. John Nagle From pavlovevidence at gmail.com Sat Jul 26 04:19:05 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 26 Jul 2008 01:19:05 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: On Jul 24, 1:41?am, Jordan wrote: > Except when it comes to Classes. I added some classes to code that had > previously just been functions, and you know what I did - or rather, > forgot to do? Put in the 'self'. In front of some of the variable > accesses, but more noticably, at the start of *every single method > argument list.* This cannot be any longer blamed as a hangover from > Java - I've written a ton more code, more recently in Python than in > Java or any other OO language. What's more, every time I go back to > Python after a break of more than about a week or so, I start making > this 'mistake' again. The perennial justification for this 'feature' > of the language? That old Python favourite, "Explicit is better than > implicit." I'm sure some people use that argument, but in my observations the more common justification for explicit self is that makes code easier to read, by making it obvious that something is a class attribute instead of a local or global variable. Your claim is that self makes code a lot harder to write, but you've disregarded the viewpoint of the reader altogether. You probably are aware that there is another Zen that says "Readability Counts". Would you also suggest that Zen needs to be done away with? > If there was one change I could make to Python, it would be to get > that damn line out of the Zen. Personally, I think you've applied it to things that it wasn't really intended for. It's mostly applies to things like language syntax, type conversions, and other semantics. For instance in Perl there are cases where you can omit quotes around strings; that'd be a major no- no in Python. Or how about this: a = 1 # a is an integer a += "hello" # oops, now it's a string Let me suggest that such things are a Very Bad Idea and so that line is better left in place. Carl Banks From patf at well.com Mon Jul 28 18:07:20 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 15:07:20 -0700 (PDT) Subject: Download excel file from web? References: Message-ID: On Jul 28, 3:00?pm, "p... at well.com" wrote: > Hi - experienced programmer but this is my first Python program. > > This URL will retrieve an excel spreadsheet containing (that day's) > msci stock index returns. > > http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&... > > Want to write python to download and save the file. > > So far I've arrived at this: > > [quote] > # import pdb > import urllib2 > from win32com.client import Dispatch > > xlApp = Dispatch("Excel.Application") > > # test 1 > # xlApp.Workbooks.Add() > # xlApp.ActiveSheet.Cells(1,1).Value = 'A' > # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' > # xlBook = xlApp.ActiveWorkbook > # xlBook.SaveAs(Filename='C:\\test.xls') > > # pdb.set_trace() > response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ > excel? > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > +25%2C+2008&export=Excel_IEIPerfRegional') > # test 2 - returns check = False > check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ > indexperf/excel? > priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul > +25%2C+2008&export=Excel_IEIPerfRegional').has_data() > > xlApp = response.fp > print(response.fp.name) > print(xlApp.name) > xlApp.write > xlApp.Close > [/quote] Woops hit Send when I wanted Preview. Looks like the html [quote] tag doesn't work from groups.google.com (nice). Anway, in test 1 above, I determined how to instantiate an excel object; put some stuff in it; then save to disk. So, in theory, I'm retrieving my excel spreadsheet with response = urllib2.urlopen() Except what then do I do with this? Well for one read some of the urllib2 documentation and found the Request class with the method has_data() on it. It returns False. Hmm that's not encouraging. I supposed the trick to understand what urllib2.urlopen is returning to me; rummage around in there; and hopefully find my excel file. I use pdb to debug. This is interesting: (Pdb) dir(response) ['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', 'code', ' fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next', 'read', 'readline', ' readlines', 'url'] (Pdb) I suppose the members with __*_ are methods; and the names without the underbars are attributes (variables) (?). Or maybe this isn't at all the right direction to take (maybe there are much better modules to do this stuff). Would be happy to learn if that's the case (and if that gets the job done for me). pat From paddy3118 at googlemail.com Sat Jul 5 12:42:34 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 5 Jul 2008 09:42:34 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <9cae59d9-ead4-45bc-a980-2ac2e1616f9b@p25g2000hsf.googlegroups.com> Message-ID: <887bdcaa-7d90-4bf7-81b8-bd70dbe11e31@l64g2000hse.googlegroups.com> On Jul 5, 4:13?pm, Mark Dickinson wrote: > It seems like an appropriate moment to point out *this* paper: > > http://swtch.com/~rsc/regexp/regexp1.html > That's the one! Thanks Mark. - Paddy. From robert.rawlins at thinkbluemedia.co.uk Thu Jul 17 13:47:13 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 17 Jul 2008 18:47:13 +0100 Subject: Unusual Exception Behaviour In-Reply-To: <006001c8e831$5c1487b0$143d9710$@rawlins@thinkbluemedia.co.uk> References: <22681.110565509$1216308418@news.gmane.org> <21965.9065748148$1216310669@news.gmane.org> <8904.90077804333$1216313689@news.gmane.org> <006001c8e831$5c1487b0$143d9710$@rawlins@thinkbluemedia.co.uk> Message-ID: <007001c8e835$252a2990$6f7e7cb0$@rawlins@thinkbluemedia.co.uk> >> That's seriously weird. What's your Python version and platform? On my >> Windows and Linux machines, with more recent Python versions the above >> trick works flawlessly. >> >> Check your environment, namely PYTHON* variables. There may be >> something causing this behaviour. Unset them. >> >> Check the first line of your scripts. If you're calling wrong Python >> interpreter (there may be more than one in the system for some >> reason), this may cause it. >> >> You could also try setting up PYTHONINSPECT environment variable or >> run the python interpreter with -i option before program filename, >> which drops you into an interactive shell upon exception or >> termination of a program. >> >> This behavior is seriously unusual for Python. Maybe you have some old >> / buggy version? > > Thanks for that MK. I'm using Debian with Python 2.5 from the stable apt repository, installed > but a couple of days ago. I'll be sure to look into those other elements you suggested also. > > I'm not sure if it bares any resemblance but this application runs a gobject mainloop and uses > > dbus quite extensively. > > Don't think this might have something to do with the way I have my loggers configured do you? > > For some reason it sits in my mind that this issue started when I moved my logging > > > > > > > configuration from programmatic into a config file, I can't be totally sure of that though. > > I've attached the config file that I use, does it all look ok to you? I wonder if the way I've > not added any handles/formatters to my root logger might be causing beef? > > This is certainly a strange one. Ok, Just to add a little interest, when I comment out the configuration line for my logging, like so: #logging.config.fileConfig("/myapp/configuration/logging.conf") It appears to throw the exceptions as normal :-) :-s Sounds as if it's a conflict with my logging configuration, I wonder what though. From siona at chiark.greenend.org.uk Tue Jul 15 10:21:13 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 15 Jul 2008 15:21:13 +0100 (BST) Subject: One step up from str.split() References: Message-ID: Joel Koltner wrote: >I normally use str.split() for simple splitting of command line arguments, but >I would like to support, e.g., long file names which-- under windows -- are >typically provided as simple quoted string. E.g., > >myapp --dosomething --loadthis "my file name.fil" > >...and I'd like to get back a list wherein ListEntry[3]="my file name.fil" , > [ ... ] Hang on, let's back up here a second. You want a command line like >myapp --dosomething --loadthis "my file name.fil" to be available as ['--dosomething', '--loadthis', 'my file name.fil'] ? What's wrong with sys.argv ? -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From google at mrabarnett.plus.com Tue Jul 15 18:11:43 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 15 Jul 2008 15:11:43 -0700 (PDT) Subject: Python internals References: <008ca729$0$20313$c3e8da3@news.astraweb.com> Message-ID: On Jul 15, 2:50?pm, Peter Anderson wrote: > Hi! ?I am slowly teaching myself Python. ?I was reading David Beazley's > excellent book "Python - Essential Reference"; in particular about > variables. ?Let me quote: > > "Python is a dynamically typed language in which names can represent > values of different types during the execution of a program. In fact the > names used in the program are really just labels for various quantities > and objects. The assignment operator simply creates an association > between a name and a value. This is different from C, for example, in > which a name (variable) represents a fixed size and location in memory..." > > As an old mainframe programmer, I understand the way C does things with > variable but this text got me wondering how Python handles this > "association" between variable name and value at the lower level. ?Is it > like a fifo list? > > If there is any Python guru that can help I would be most interested in > your thoughts. > They're stored in a dictionary (hash table), called a "dict" in Python, the name being the key and the value being a reference to the actual value. The CPython implementation is written in C (hence the name) and implements references with pointers. From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 10 07:47:48 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 10 Jul 2008 13:47:48 +0200 Subject: FOSS projects exhibiting clean/good OOP? In-Reply-To: <1fdb9220-4ddd-4633-b5bd-91fbfc91453d@z66g2000hsc.googlegroups.com> References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> <1fdb9220-4ddd-4633-b5bd-91fbfc91453d@z66g2000hsc.googlegroups.com> Message-ID: <4875f6af$0$26425$426a74cc@news.free.fr> Phillip B Oldham a ?crit : > On Jul 9, 9:26 pm, "bruno.desthuilli... at gmail.com" > wrote: >> This is somewhat subjective... Some would say that Python's object >> model is fundamentally broken and crappy (not MHO, needless to say) >> that Python + "solid OO principles" is antinomic !-) > > Really? Would you happen to be able to provide any further information > on that? Well... Some people seems to think that an object model with no language-enforced access restriction, no implicit 'self' reference and the necessity to explicitely declare 'self' as first argument of methods is broken. You'll also find a couple guys complaining about Python not forcing you to put everything into classes, ? la Java. From duncan.booth at invalid.invalid Sat Jul 12 14:15:28 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jul 2008 18:15:28 GMT Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> Message-ID: "Giampaolo Rodola'" wrote: > > My question is the following: is it safe to avoid to re-heapify() a > heap when I remove or move an element which is not the first one? > Example: > >>>> from heapq import * >>>> heap = [2,4,6,7,1,2,3] >>>> heapify(heap) >>>> del heap[4] >>>> # Am I forced to heapify() the heap here? > > Thanks in advance. No, it is not safe to avoid re-heapifying. After you call heapify the list is ordered such that for any 'n' in the range 1..len(heap)//2 it is the case that heap[n-1] <= heap[2*n-1] and when heap[2*n] exists heap[n-1] <= heap[2*n]. So: >>> heap = [0, 100, 1, 101, 102, 2, 3] >>> heapify(heap) >>> heap [0, 100, 1, 101, 102, 2, 3] >>> del(heap[4]) >>> heap [0, 100, 1, 101, 2, 3] >>> heapify(heap) >>> heap [0, 2, 1, 101, 100, 3] after deleting heap[4] it is no longer the case that heap[1] >= heap[4] as the old heap[5] was a child of heap[2] not of heap[1]. From basti.wiesner at gmx.net Sat Jul 5 06:44:05 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Sat, 05 Jul 2008 12:44:05 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Carl Banks : > On Jul 5, 4:12 am, "Sebastian \"lunar\" Wiesner" > wrote: >> Paddy : >> >> >> >> > On Jul 4, 1:36 pm, Peter Otten <__pete... at web.de> wrote: >> >> Henning_Thornblad wrote: >> >> > What can be the cause of the large difference between re.search and >> >> > grep? >> >> >> grep uses a smarter algorithm ;) >> >> >> > This script takes about 5 min to run on my computer: >> >> > #!/usr/bin/env python >> >> > import re >> >> >> > row="" >> >> > for a in range(156000): >> >> > row+="a" >> >> > print re.search('[^ "=]*/',row) >> >> >> > While doing a simple grep: >> >> > grep '[^ "=]*/' input (input contains 156.000 a in >> >> > one row) >> >> > doesn't even take a second. >> >> >> > Is this a bug in python? >> >> >> You could call this a performance bug, but it's not common enough in >> >> real code to get the necessary brain cycles from the core developers. >> >> So you can either write a patch yourself or use a workaround. >> >> >> re.search('[^ "=]*/', row) if "/" in row else None >> >> >> might be good enough. >> >> >> Peter >> >> > It is not a smarter algorithm that is used in grep. Python RE's have >> > more capabilities than grep RE's which need a slower, more complex >> > algorithm. >> >> FWIW, grep itself can confirm this statement. The following command >> roughly takes as long as Python's re.search: >> >> # grep -P '[^ "=]*/' input >> >> -P tells grep to use real perl-compatible regular expressions. > > This confirms that a particular engine might not be optimized for it, > but it's not necessarily a reflection that the engine is more complex. My posting wasn't intended to reflect the differences in complexity between normal GNU grep expressions (which are basically extended POSIX expressions) and perl-compatible expressions. The latter just _are_ more complex, having additional features like look aheads or non-greedy qualifiers. I just wanted to illustrate, that the speed of the given search is somehow related to the complexity of the engine. Btw, other pcre implementation are as slow as Python or "grep -P". I tried a sample C++-code using pcre++ (a wrapper around libpcre) and saw it running equally long. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From mccredie at gmail.com Tue Jul 1 16:23:54 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 1 Jul 2008 13:23:54 -0700 (PDT) Subject: Please check my understanding... References: Message-ID: On Jul 1, 12:35?pm, Tobiah wrote: > list.append([1,2]) will add the two element list as the next > element of the list. > > list.extend([1,2]) is equivalent to list = list + [1, 2] > and the result is that each element of the added list > becomes it's own new element in the original list. > > Is that the only difference? > > From the manual: > > s.extend(x) ?| ?same as s[len(s):len(s)] = x > > But: (python 2.5.2) > > >>> a > [1, 2, 3] > >>> a[len(a):len(a)] = 4 > > Traceback (most recent call last): > ? File "", line 1, in > TypeError: can only assign an iterable > > > > Also, what is the difference between list[x:x] and list[x]? > > >>> a[3:3] = [4] > >>> a > > [1, 2, 3, 4] > ** Posted fromhttp://www.teranews.com** In this example: > s.extend(x) | same as s[len(s):len(s)] = x x _must_ be iterable. As the error states, `4` is not iterable. the s[start:stop] notation is called slicing: >>> x = range(10) >>> x[0] 0 >>> x[1] 1 >>> x[0:1] [0] >>> x[0:2] [0, 1] >>> x[0:3] [0, 1, 2] >>> x[1:3] [1, 2] >>> x[5:-1] [5, 6, 7, 8] >>> x[5:] [5, 6, 7, 8, 9] In general `x[len(x):len(x)] = seq` is a stupid way to extend a list, just use .extend or +=. Matt From winter at biotec.tu-dresden.de Mon Jul 28 12:15:19 2008 From: winter at biotec.tu-dresden.de (Christof Winter) Date: Mon, 28 Jul 2008 18:15:19 +0200 Subject: SOAPpy WSDL problem: namespace of schema and import match error In-Reply-To: <6f5lirF9vmv1U1@mid.dfncis.de> References: <6f5lirF9vmv1U1@mid.dfncis.de> Message-ID: <6f69knFa1adaU1@mid.dfncis.de> Christof Winter wrote, On 28.07.2008 12:32: > I am trying to use a webservice with SOAPpy: > > import SOAPpy > intact_wsdl = "http://www.ebi.ac.uk/intact/binary-search-ws/binarysearch?wsdl" > intact_serv = SOAPpy.WSDL.Proxy(intact_wsdl) [...] > My question: > - Is there a problem with the WSDL file being not valid? I just figured out that this could indeed be true. The WSDL document contains an XML Schema import that probably should be an XML Schema include: "The import element is used to add multiple schemas with different target namespace to a document." http://www.w3schools.com/schema/el_import.asp "The include element is used to add multiple schemas with the same target namespace to a document." http://www.w3schools.com/schema/el_include.asp Maybe I should post this to comp.text.xml Christof From tjreedy at udel.edu Fri Jul 18 18:15:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Jul 2008 18:15:48 -0400 Subject: round function error??? In-Reply-To: References: Message-ID: Anthony wrote: > Isn't this a mistake??? > >>>> round(3499.349439034,44) > 3499.3494390340002 >>>> round(_,2) > 3499.3499999999999 >>>> round(_,1) > 3499.4000000000001 > > My Python 2.5.1 spat that out.. No, round() return binary floats that, in general, cannot represent decimal floats exactly. Formatted printing gives what you expect. >>> '%8.2f' % x ' 3499.35' From fredrik at pythonware.com Sun Jul 20 14:30:28 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jul 2008 20:30:28 +0200 Subject: Web Server In-Reply-To: <1dc5311f-6243-41d4-b5da-78183c9668e4@m44g2000hsc.googlegroups.com> References: <1dc5311f-6243-41d4-b5da-78183c9668e4@m44g2000hsc.googlegroups.com> Message-ID: misceverything at gmail.com wrote: > Thanks, Fredrik - that definitely works. Now to get a little greedy - > is there something along those lines that is a bit more secure (i.e. > allows HTTPS, possibly with authentication)? Basically something that > you would feel more comfortable opening up to the Internet.. open up to whom? I'm not sure I like the combination of "windows app" and "opened up to the internet", really... but assuming that you're aware of the issues involved, and want a light-weight HTTP server for Windows, this one's pretty nice: http://www.aprelium.com/abyssws/ there's also apache, of course, and a bunch of others, including several Python solutions (more or less pre-packaged). but the "open up" part still sounds a bit risky. maybe you could turn things around, and let the application "push" data to your server instead? From dstromberglists at gmail.com Sat Jul 26 15:15:40 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Sat, 26 Jul 2008 19:15:40 GMT Subject: Stripping parts of a path References: Message-ID: On Sat, 26 Jul 2008 08:59:15 -0300, Tim Cook wrote: > Hi All, > > I just ran into an issue with the rstrip method when using it on path > strings. > > When executing a function I have a need to strip off a portion of the > current working directory and add on a path to a log file. Initially > this worked great but then I added a branch in SVN which caused the path > to contain 'LNCCWorkshop'. The rstrip() then began removing the > characters 'shop' leaving an incorrect path to the log file. When I > hard coded this path it worked okay but then did the same thing later in > the file when I needed to point to a database. The code worked fine with > a different path. Here are some code fragments. > > logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/ at_build_errors.log' > > this worked when the path was: > /home/tim/ref_impl_python/TRUNK/oship/src/oship/atbldr > > the code above returns: > /home/tim/ref_impl_python/TRUNK/oship/log/at_build_errors.log > > but when I tried a branches version that has the path: > /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/src/oship/atbldr > > it SHOULD return: > /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/log/ at_build_errors.log > > but I get: > /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/ at_build_errors.log > > logfile=os.getcwd() > print logfile is correct; but when I add the .rstrip('src/oship/atbldr') > it also strips the 'shop' off of LNCCWorkshop and returns > /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/ at_build_errors.log > > I had two other people looking at this as we did troubleshooting and we > could not determine the cause. It is repeatable with this path name. In > resolution I renamed the branch to just LNCC and it works fine. > > Thoughts? > > Tim Is this the Tim Cook I worked with at UCI? Anyway, I think the os.path module might have something for you. As a little bonus, it should produce code that works well with other operating systems, and should deal gracefully with repeated slashes. From callen314 at gmail.com Thu Jul 31 21:27:36 2008 From: callen314 at gmail.com (Craig Allen) Date: Thu, 31 Jul 2008 18:27:36 -0700 (PDT) Subject: when does the GIL really block? Message-ID: I have followed the GIL debate in python for some time. I don't want to get into the regular debate about if it should be gotten rid of (though I am curious about the status of that for Python 3)... personally I think I can do multi-threaded programming well, but I also see the benefits of a multiprocess approach. I'm not so egotistical that I don't realize perhaps my mt programming has not been "right" (though it worked and was debuggable) or more likely that doing it right I have avoided even trying some things people want mt programming to do... i.e. to do mt programming right you start to use queues a lot, inter-thread asynchronous, non-blocking, communication, which is essentially the multi-process approach, using IPC (except that the threads can see the same memory when, in your special case, you know that's ok. Given something like a reader-writer lock, this can have benefits... but again, whatever. My question is that given this problem, years ago before I started writing in python I wrote some short programs in python which could, in fact, busy both my CPUs. In retrospect I assume I did not have code in my run function that causes a GIL lock... so I have done this again. I start two threads... I use gkrellm to watch my processors (dual processor machine). If I merely print a number... both CPUS are getting 90% simultaneous loads. If I increment a counter and print it too, the same, and if I create a small list and sort it, the same. I did not expect this... I expected to see one processor pegged at around 100%, which should sometimes switch to the other processor. Granted, the same program in C/C++ would peg both processors at 100%... but given that the overhead in the interpreter cannot explain the extra usage, I assume the code in my thread's run functions is actually executing non-serially. I assume this is because what I am doing does not require the GIL to be locked for a significant part of the time my code is running... what code could I put in my run function to see the behavior I expected? What code could I put there to take advantage of the possibility that really the GIL is not locked enough to cause actual serialization of the threads... anyone care to explain? From rocksportrocker at googlemail.com Tue Jul 1 06:56:25 2008 From: rocksportrocker at googlemail.com (rocksportrocker) Date: Tue, 1 Jul 2008 03:56:25 -0700 (PDT) Subject: problem with exec and locals() Message-ID: <95f07476-e3c8-45e4-82b3-0e48c9188f8e@79g2000hsk.googlegroups.com> Hi, the following code does not work until I ommit the "a=0" statement. def test(): exec "a=3" in locals() print a a=0 test() print raises: UnboundLocalError: local variable 'a' referenced before assignment Can anybody explain what is going wrong here ? Greetings, Uwe From phil at freehackers.org Wed Jul 30 07:24:15 2008 From: phil at freehackers.org (BlueBird) Date: Wed, 30 Jul 2008 04:24:15 -0700 (PDT) Subject: Continuous integration for Python projects References: <6f8pelFafh42U1@mid.uni-berlin.de> Message-ID: <551e5dcc-bc22-4a23-9adf-f13a05c1e9cf@z66g2000hsc.googlegroups.com> On Jul 29, 4:56?pm, "Diez B. Roggisch" wrote: > Hussein B wrote: > > Hi. > > Please correct my if I'm wrong but it seems to me that the major > > continuous integration servers (Hudson, CruiseControl, TeamCity ..) > > don't support Python based application. > > It seems they mainly support Java, .NET and Ruby. > > Can I use one of the previous listed servers for Python project? > > Hudson can, and AFAIK CC as well - they only invoke shell-scripts (at least > hudson does, and CC you can convince doing that using ANT) > I have CC almost running here with python tests and there is no technical problem in front. You must package your test scripts so that they exit with something different than 0 in case of failure, and then just use the Exec runner of CC to run them. From bj_666 at gmx.net Sun Jul 13 04:41:37 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Jul 2008 08:41:37 GMT Subject: Problems with curses References: Message-ID: <6dtte1F49rsiU1@mid.uni-berlin.de> On Sat, 12 Jul 2008 20:49:56 -0400, Clay Hobbs wrote: > Unfortunately, the error message isn't very helpful. But it would be helpful to tell it. If you get exceptions, always copy'n'paste the traceback here. People might know what the exception means and share their wisdom. Ciao, Marc 'BlackJack' Rintsch From iainking at gmail.com Thu Jul 3 05:01:08 2008 From: iainking at gmail.com (Iain King) Date: Thu, 3 Jul 2008 02:01:08 -0700 (PDT) Subject: Win32.client, DAO.DBEngine and exceeding the file sharing count lock References: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> <9ab0cc2d-5a7e-40ca-a4da-084347f147cd@m36g2000hse.googlegroups.com> <486BAA56.4070303@timgolden.me.uk> Message-ID: <45054c4a-e673-4e0e-9569-232dfa8ee12d@k13g2000hse.googlegroups.com> On Jul 2, 8:13?pm, Tim Golden wrote: > In case it helps, there's a recipe just shown up > on the Python Cookbook which at least illustrates > DAO use: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/572165 > > TJG On Jul 2, 6:30 pm, "M.-A. Lemburg" wrote: > You could try to use the Access ODBC driver and access the database > that way via mxODBC. That would be faster as well: > > http://www.microsoft.com/technet/prodtechnol/windows2000serv/technolo... > (scroll down to table 7.1) > > Apart from that option and if you are really in need for larger > transactions, I'd suggest that you move to SQL Server for processing > (if you can). Access is not really made for heavy-lifting and big > transactions. Thanks for the help. I'll check those out, in case there's a performance gain to be had, but I found that ADO can in fact do exactly what I want; on the comments of the page I previously linked to which said ADO couldn't was a posting which refuted some of the OP's claims; ADO can set some options on it's open connection, including Max Locks Per Record. My code now looks like this: self._connection.Open(self._DSN) if MAX_LOCKS != None: self._connection.Properties("Jet OLEDB:Max Locks Per File").Value = MAX_LOCKS rs = win32com.client.Dispatch(r'ADODB.Recordset') N.B. I'm writing tools software for a 3rd party app which uses an Access db as it's output format, so I'm locked in. No way to switch to SQL server. Thanks both! Iain From alexnbryan at gmail.com Thu Jul 17 01:37:39 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 22:37:39 -0700 (PDT) Subject: Need help getting BeautifulSoup contents Message-ID: <18501881.post@talk.nabble.com> The trick to this one is that the html looks something like this:
american, a href="/browse/blue" linkindex="12" set="yes">blue brick churn cottage cream " My question is I want everything inside, the contents of each ad the regular text of the . I know I can do like a.contents, but it only gives me the first one, in this case being "blue". I want the contents of each of those and the regular contents of the . P.S. notice the things inbetween the tags, I need those too :( Can anyone help? -- View this message in context: http://www.nabble.com/Need-help-getting-BeautifulSoup-contents-tp18501881p18501881.html Sent from the Python - python-list mailing list archive at Nabble.com. From steve at REMOVE-THIS-cybersource.com.au Wed Jul 30 23:29:28 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Jul 2008 03:29:28 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <00a121b4$0$20313$c3e8da3@news.astraweb.com> Message-ID: <00a12d08$0$20313$c3e8da3@news.astraweb.com> On Thu, 31 Jul 2008 02:41:08 +0000, Steven D'Aprano wrote: > On Wed, 30 Jul 2008 09:23:05 -0600, Matthew Fitzgibbons wrote: ... >> Although, if my function is expecting a list, my preference is to do: >> >> if not isinstance(x, list): >> raise SomeMeaningfulException() >> # do stuff with the list >> >> I put my type checking at the top of the function, so readers can >> reference it easily. > > And thus you break duck-typing and upset anybody who wants to pass a > sequence that doesn't inherit directly from list. Correction: delete "directly" from the above. -- Steven From claird at lairds.us Wed Jul 30 20:55:52 2008 From: claird at lairds.us (Cameron Laird) Date: Thu, 31 Jul 2008 00:55:52 +0000 Subject: Is there a such Python module ? References: Message-ID: In article , Matthew Fitzgibbons wrote: >Johny wrote: >> Is there a Python module that can help with reading SMS message from a >> mobile phone? >> Or is there an example how to read SMS message using a program written >> in Python,C, or any other language? >> Thank you very much for help >> L. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > >There is a Python distro for Symbian, if your phone is running that. You >can do things like send/receive SMS messages, control the camera, etc. >http://wiki.opensource.nokia.com/projects/PyS60. Can't speak to anything >else. Cellular handsets are consumer devices; their notion of "standardization" is ENTIRELY different from the way most of Pythonia behaves. So, yes, there are all sorts of resources of Nokia devices. Gammu is also likely to interest you, depending on your hardware. There are still other solutions specific to Motorola, ..., although Python's presence and compatibility declines steeply when you leave Nokia and/or Gammu. From __peter__ at web.de Sat Jul 12 04:26:46 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Jul 2008 10:26:46 +0200 Subject: variable question References: <6f02608a-2b2e-478d-a153-d10bbfb58981@c58g2000hsc.googlegroups.com> <48782d93$0$20780$9b622d9e@news.freenet.de> <98553eaa-a435-488f-9f14-831d858ac800@m45g2000hsb.googlegroups.com> Message-ID: happy wrote: > I think its better to leave the "teach kiddies" tutoring opportunity > for the python experts out there. If you know how to make some simple scripts that do something that kids find interesting and are able to convey your enthusiasm, you are better suited to teach than any expert who tortures them with explanations of how a variable is not a name is not a pointer. Peter From Russ.Paielli at gmail.com Wed Jul 30 00:36:45 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 21:36:45 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> <341d8eaa-4884-4ce5-b6e4-094ac718e0bf@u36g2000pro.googlegroups.com> <488dc843$0$15497$426a74cc@news.free.fr> <1247a297-768c-4dbe-aa96-fd8456f9279b@r15g2000prd.googlegroups.com> <466157f1-adcb-45f6-8c2d-b3c245a6ce8d@p31g2000prf.googlegroups.com> <47a24fed-6822-4767-aad3-07a72ddc3a1a@m73g2000hsh.googlegroups.com> <7a090a5e-c103-4182-b8d9-c1c0c4819696@y38g2000hsy.googlegroups.com> Message-ID: <90f35a30-3fea-43f1-bda8-74960412aa75@q28g2000prh.googlegroups.com> On Jul 29, 2:27 am, Iain King wrote: > On Jul 29, 5:33 am, "Russ P." wrote: > > > > > On Jul 28, 8:44 pm, alex23 wrote: > > > > On Jul 29, 4:46 am, "Russ P." wrote: > > > > > As I said, I could write a pre-processor myself to > > > > implement it in less than a day. > > > > So WHY DON'T YOU WRITE IT ALREADY? > > > I'm working on something else right now if you don't mind, but I'll > > get to it in good time. > > > Conceptually, the matter is simple. All I need to do is to grab the > > first formal argument of each def, then search for occurrences of any > > word in the body of the def that starts with a dot, and insert that > > first argument in front of it. > > > I expect the "hard" part will be breaking up the body of the def into > > "words." I could just split each line on white space, except for > > situations like > > > x+=.zzz > > > So I need to account for the fact that operators do not need to be > > surrounded by spaces. That's the hardest part I can think of off the > > top of my head. > > > Maybe I'll encounter an insurmountable problem and realize that the > > idea can't work in general. If so, then so be it. Certainly, no one on > > this thread has anticipated such a problem. Had someone pointed out an > > actual technical problem with the idea, I would have gladly thanked > > them. But I got a load of irrelevant crap instead, not to mention > > being addressed as "boy." > > > > If you're meeting so much resistance to your idea, why not scratch > > > your own damn itch and just do it? > > > > Or doesn't that afford you as many chances to insult others while > > > feeling smugly superior? > > > This coming from a guy who insulted my reading comprehension ability > > -- when he was the one who was wrong! > > Are you actually this stupid? I mean, you were entertaining while you > were mouthing of and insulting your betters, but now you're gonna > complain the second anyone insults you (and I mean, 'boy' - what an > insult!). Never mind that you're never gonna get off your ass to > write a PEP, which would be rejected on language design grounds anyway > (as demonstrated by alex23's link - the one you aren't > comprehending). The most irritating thing is that I like the idea of > being able to use '.x = 10' type notation (and have been for a long > time), but the person arguing for it is an insufferable buffoon who's > too dense to understand a cogent argument, never mind make one. So > great, thanks, the chances of this (or a VB 'with'-like 'using' > keyword) ever making it into the language get smaller every time you > fire up your keyboard. Nice work. > > Iain > > p.s. am looking forward to your post whining about the invalid reasons > your PEP got rejected, in the slim hope you actually write one. +1 POTW Thanks for the gentle prod! I'm on it -- well, soon anyway. I have to consciously avoid thinking about this post whenever I consume a beverage! From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 9 07:52:45 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 09 Jul 2008 13:52:45 +0200 Subject: a simple 'for' question In-Reply-To: References: <4874017D.2000401@umbc.edu> <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> <487437E6.8010609@umbc.edu> Message-ID: <4874a65e$0$11358$426a74cc@news.free.fr> Tim Cook a ?crit : > On Wed, 2008-07-09 at 00:00 -0400, Ben Keshet wrote: >> oops, my mistake, actually it didn't work... >> when I tried: >> for x in folders: >> print x # print the current folder >> filename='Folder/%s/myfile.txt' %x >> f=open(filename,'r') >> >> it says: IOError: [Errno 2] No such file or directory: >> 'Folder/1/myfile.txt' >> > > I believe it's because x is the position marker what you want instead is > the contents of folders at x; therefore folders[x] Nope. Python's for loops iterate over elements, not over indices. Here, the following code: folders= ['1A28','1A6W','56Y7'] for x in folders: print x filename='Folder/%s/myfile.txt' %x print filename yields: 1A28 Folder/1A28/myfile.txt 1A6W Folder/1A6W/myfile.txt 56Y7 Folder/56Y7/myfile.txt IOW: the problem is elsewhere. From larry.bates at websafe.com` Wed Jul 9 16:49:02 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 09 Jul 2008 15:49:02 -0500 Subject: Determining when a file has finished copying In-Reply-To: References: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> <4874E2D3.4050707@gmail.com> Message-ID: writeson wrote: > Guys, > > Thanks for your replies, they are helpful. I should have included in > my initial question that I don't have as much control over the program > that writes (pgm-W) as I'd like. Otherwise, the write to a different > filename and then rename solution would work great. There's no way to > tell from the os.stat() methods to tell when the file is finished > being copied? I ran some test programs, one of which continously > copies big files from one directory to another, and another that > continously does a glob.glob("*.pdf") on those files and looks at the > st_atime and st_mtime parts of the return value of os.stat(filename). > From that experiment it looks like st_atime and st_mtime equal each > other until the file has finished being copied. Nothing in the > documentation about st_atime or st_mtime leads me to think this is > true, it's just my observations about the two test programs I've > described. > > Any thoughts? Thanks! > Doug I guess the problem is "What is the definition of 'finished copying'?". There is no explicit operating system command that says "I'm done copying to this file and I won't add anything on to the end of it". If I could not control the sending application, I would make an estimation of how long the longest file could possibly take to copy, double it and then only look at files where the st_ctime was at least that far in the past. What you suggest could work as well. -Larry From Samnsparky at gmail.com Tue Jul 15 13:20:49 2008 From: Samnsparky at gmail.com (Sparky) Date: Tue, 15 Jul 2008 10:20:49 -0700 (PDT) Subject: File Locking Forced? Newbie question. Message-ID: <216e2396-65f6-4281-b3c5-754ceb07f3eb@m36g2000hse.googlegroups.com> Hello! I am writing some software that will have many users accessing the same file resource at once for reading purposes only. I am programming on (Ubuntu) Linux and my question is in Windows, can I have it so that the same file can be open in read mode by more than one person or could Window's file locking system get in the way? Thanks, Sam From workitharder at gmail.com Mon Jul 14 00:12:21 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 13 Jul 2008 21:12:21 -0700 (PDT) Subject: socket.connect() hangs in SYN_SENT state. References: <804bccb2-42c7-42e9-8f50-7a780d3438fd@j22g2000hsf.googlegroups.com> Message-ID: On Jul 13, 6:31 pm, Miles wrote: > On Sun, Jul 13, 2008 at 8:35 PM, bukzor wrote: > > The problem only manifests about 1 in 20 runs. Below there's code for > > a client that shows the problem 100% of the time. > > > The two URL's that I seem to be "confused" about point to the same IP. > > Maybe this will make it clear: > > > PING bukzor.hopto.org (75.61.84.249) 56(84) bytes of data. > > 64 bytes from adsl-75-61-84-249.dsl.pltn13.sbcglobal.net > > (75.61.84.249): icmp_seq=1 ttl=255 time=1.68 ms > > For me, buzkor.hopto.org resolves to 69.65.19.125, which I hope > explains why I thought you were confused, and increases my own > suspicion that DNS settings are to blame. I let the script run for > about five minutes without it failing. > > Does your luck change if you use "localhost" or a numeric IP address > in the ServerProxy URL? > > -Miles It seems to work fairly perfectly If i use localhost or even my LAN IP address, but starts to fail if I go beyond that. You said you ran it for five minuts without error. Did it error out after that? If you can't reproduce it, that would indicate something else. From keshet1 at umbc.edu Tue Jul 1 19:16:30 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Tue, 01 Jul 2008 19:16:30 -0400 Subject: beginner's questions - manipulating text files Message-ID: <486ABACE.9050103@umbc.edu> Hi, I am a very beginner Python programmer with limited programming experience overall. I am trying to write a script that will search for the second and third appearance of the symbol '@' in a file, will read a random line between them, and write the line into a new file. So far I was only able to open the file using 'open', but I am not sure how to proceed. I tried to read it line by line using 'readline' but was not sure how to manipulate the text the way I need to. Could anyone please give me |a basic guidance as for what functions may be useful for my purpose? (e.g how to search for a string '@' in a text? how to identify its location? how to choose a random number in a defined range? how to read that line number from a text file? etc.)| || |Any help will be much appreciated (please remember that I am a super beginner).| || |Thanks.| || | | -------------- next part -------------- An HTML attachment was scrubbed... URL: From keith.hughitt at gmail.com Fri Jul 11 14:42:37 2008 From: keith.hughitt at gmail.com (Keith Hughitt) Date: Fri, 11 Jul 2008 11:42:37 -0700 (PDT) Subject: Converting from local -> UTC Message-ID: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> Hi, I am having a little trouble figuring out how to convert a python datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would like to create a UTC date so that when I send it to MySQL (which treats all dates at local dates by default), it will already have incorporated the proper UTC offset. I've tried looking through the docs http://python.active-venture.com/lib/datetime-datetime.html), but have not had any luck. Does anyone have any suggestions? Any help would be greatly appreciated. Thanks, Keith From vshankar0 at gmail.com Thu Jul 17 07:54:20 2008 From: vshankar0 at gmail.com (Venky Shankar) Date: Thu, 17 Jul 2008 17:24:20 +0530 Subject: Testing for connection to a website In-Reply-To: References: Message-ID: ping the universal DNS ? (4.2.2.2) -Venky On Wed, Jul 16, 2008 at 1:17 AM, Jordan wrote: > On Jul 15, 3:43 pm, Alexnb wrote: > > Okay, I already made this post, but it kinda got lost. So anyway I need > to > > figure out how to test if the user is able to connect to a specific > website. > > Last time I got pointed to the urllib2 page, but if I do urlopen() and > and > > am not connected, the program stops. So I don't know if that was what you > > guys wanted me to do, but I don't think so, you guys are smarter than > that. > > So, how can I test for connection to a website. > > -- > > View this message in context: > http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p... > > Sent from the Python - python-list mailing list archive at Nabble.com. > > Ping it? ~_^ > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.franzoni.blahblah at example.com.invalid Wed Jul 30 13:26:37 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Wed, 30 Jul 2008 17:26:37 GMT Subject: Syntax error in my script References: Message-ID: laredotornado was kind enough to say: [cut] Indentation counts in Python. You're probably doing something wrong with whitespace/tab/carriage return. -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From samwyse at gmail.com Mon Jul 14 16:45:21 2008 From: samwyse at gmail.com (samwyse) Date: Mon, 14 Jul 2008 13:45:21 -0700 (PDT) Subject: Problems Returning an HTTP 200 Ok Message References: <1cf880cc-2036-42dc-8217-d52a714c1710@a70g2000hsh.googlegroups.com> <9bc65e72-be16-4f73-9dfb-6ddeaae34c21@m73g2000hsh.googlegroups.com> <8596af5b-fd0a-413e-8051-62d650e9a153@8g2000hse.googlegroups.com> Message-ID: On Jul 10, 4:10?pm, Guy Davidson wrote: > I try to send the following message, using the socket.send() command: > > 'HTTP/1.1 200 OK\r\nDate: Thu, 10 July 2008 14:07:50 GMT\r\nServer: > Apache/2.2.8 (Fedora)\r\nX-Powered-By: PHP/5.2.4\r\nContent-Length: 4\r > \nConnection: close\r\nContent-Type: text/html; charset=UTF-8\r\n\r > \n[0]\n' > > However, when I snoop on the packets in wireshark, here's what I see: > > HTTP/1.1 200 Ok: > > HTTP/1.1 200 OK > Date: Wed, 09 July 2008 14:55:50 GMT > Server: Apache/2.2.8 (Fedora) > X-Powered-By: > > Continuation or non-HTTP traffic: > > PHP/5.2.4 > Content-Length: 4 > Connection: close > Content-Type: text/html; charset=UTF-8 > > [0] > > It splits into two packages, which the meter can't read, and the > communication breaks down there. OK, it looks like a single TCP segment is being sent by you (which is consistent with only one socket.send() command being needed), but something along the way to the meter is using an MTU (Maximum Transmission Unit) of about 100 bytes, producing two IP datagrams. How many hops are there between the PC and the meter? Are you sniffing on the same subnet as the PC, the meter, or somewhere in between? MTU is normally set to about 1500 (and MSS is generally MTU-40), but you can generally change these values. You should be able to set the do-not-fragment flag on your IP packets, but that may cause them to get dropped instead of sent. You could also try setting a smaller ICP MSS (Maximum Segment Size), which the meter might be able to assemble, even if it can't handle fragmented IP datagrams. Try http://www.cisco.com/en/US/tech/tk870/tk877/tk880/technologies_tech_note09186a008011a218.shtml#prob_desc for more help. You really need to get a networking guru involved if you want to go down this path. I used to be one, but that was years ago. Or, you can take Gabriel Genellina's advice and try coding smaller responses. From frankrentef at yahoo.com Thu Jul 24 11:13:26 2008 From: frankrentef at yahoo.com (frankrentef) Date: Thu, 24 Jul 2008 08:13:26 -0700 (PDT) Subject: Python / PAMIE References: Message-ID: <9e077ec9-9a07-4a3a-b5dc-bfd593162350@8g2000hse.googlegroups.com> On Jul 24, 10:07?am, Tim Golden wrote: > frankrentef wrote: > > Can someone help with a PAMIE issue? ?I'm new to Python / PAMIE and > > they seem like great tools but to be honest I'm finding that no > > responses to questions can be found (Experts Exchange, etc.) ?I'm > > hoping this will be the place. > > > I tried to duplicate the authors "ie.writeScript" function shown at > > >http://showmedo.com/videos/video?name=pythonMarchettiPamie3&fromSerie... > > I'd rather you posted the code you've tried. > I'm not too keen on viewing a video just to get > hold of a piece of code, and in any case that > would only show me what the author's done. > > We need to see what you've done, and what the > traceback was. Would you mind posting some code, > please? > > Thanks > > TJG THNX for your response. Based on the authors code it's very simple. from cPAMIE import PAMIE ie=PAMIE () #ie.navigate ("google.com") #ie.linkClick #ie.textBoxSet #ie.writeScript ie.navigate ('https://login.yahoo.com/config/mail?.intl=us') #ie.scriptWrite () ie.scriptWrite() Below is the error I get... File "C:\Python24\lib\site-packages\cPAMIE.py", line 1837, in scriptWrite nameProp = getattr(x,"nameProp") File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 500, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: .nameProp From sunp1028 at gmail.com Wed Jul 16 08:28:54 2008 From: sunp1028 at gmail.com (patrol) Date: Wed, 16 Jul 2008 05:28:54 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> Message-ID: On 7?16?, ??3?29?, Tim Golden wrote: > patrol wrote: > >>http://timgolden.me.uk/wmi-project/wmi.py > > > It cannot work either. > > Oh well. It was only a quick fix! I'll try > to get some kind of non-ASCII edition of Windows > to test against. As I understand it, the situation > is that some WMI exception (ie coming from the > underlying WMI/COM subsystem) results in an error > message which contains non-ASCII characters. > > Just so I'm not chasing red herrings, could you > paste the output from the following code, please? > > > import wmi # use the version linked above > > c = wmi.WMI ("non-existent computer") > > # > # Should give a traceback here for the DCOM > # error, not a UnicodeDecodeError. > # > > > Thanks > > TJG The errors are in the following: Traceback (most recent call last): File "D:\My Documents\code\python\wmi\test.py", line 5, in c = wmi.WMI ("non-existent computer") File "C:\Python25\lib\wmi.py", line 1199, in connect handle_com_error (error_info) File "C:\Python25\lib\wmi.py", line 184, in handle_com_error exception_string = [u"%s - %s" % (hex (hresult_code), hresult_name)] UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 4: ordinal not in range(128) Patrol From tjreedy at udel.edu Tue Jul 8 15:25:47 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 08 Jul 2008 15:25:47 -0400 Subject: "in"consistency? In-Reply-To: <871c6735-f2d2-4cd0-811d-0cd774d55bdd@m45g2000hsb.googlegroups.com> References: <871c6735-f2d2-4cd0-811d-0cd774d55bdd@m45g2000hsb.googlegroups.com> Message-ID: castironpi wrote: > Strings are not containers. Library Reference/Built-in Types/Sequence Types says "Strings contain Unicode characters." Perhaps you have a different notion of contain/container. I prefer 'collection' to 'container' since 'container' tends to imply an exclusiveness that is not true. Byte/character sequences *are* different from tuples, lists, sets, dicts, etc, in the following sense: members of the latter collection classes must exist first before being added to the collection (non-exclusively). Members of the former do not. (In CPython, at least, they do not). So I consider them to (reiterable) *virtual* sequence collections that can produce subsequences on demand, So I partially agree with you in that byte/char sequences are a different sub-category. > Another container type: > > Python 3.0b1 on win32 >>>> {0} in {0,1} > False And similarly, (0,) not in (0,1), [0] not in [0,1], {0:None} not in {0:None,1:None). These are all general manifest collection types that can contain any Python object, and which could contain a sub-collection even if they do not. Terry Jan Reedy From tjreedy at udel.edu Sun Jul 27 21:32:06 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 21:32:06 -0400 Subject: Where is the correct round() method? In-Reply-To: <488D0BC0.3080701@islandtraining.com> References: <28f88423-901a-49c7-91fd-e3352fcd6b47@l64g2000hse.googlegroups.com> <488D0BC0.3080701@islandtraining.com> Message-ID: Gary Herron wrote: > josh logan wrote: >> I need a round function that _always_ rounds to the higher integer if >> the argument is equidistant between two integers. In Python 3.0, this >> is not the advertised behavior of the built-in function round() as >> seen below: >>>>> round(2.5) >>>>> >> 2 > Huh? > >>> round(2.5) > 3.0 As the OP said, PY 3.0, where statisticians' unbiased round to even was explicitly adopted. (I think before it was maybe left to the C library?) >> I would think this is a common need, If you need any particular rounding for legal/finance-rule reasons, you probably need the decimal module, which has several rounding modes and other features catering to money calculation rules. For general data analysis with floats, round to even is better. tjr From ethan at stoneleaf.us Tue Jul 15 14:11:15 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 15 Jul 2008 10:11:15 -0800 Subject: MySQL Insert In-Reply-To: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> References: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> Message-ID: <487CE843.2080704@stoneleaf.us> maestroQC wrote: > Hi, > > Its one of those days. I cannot solve this. Any help would be greatly > appreciated! > When I execute this: > > class Db(object): > def insertAccount(self, date, accountNumber, description, > openingBalance): > dec = decimal.Decimal(openingBalance) > db = MySQLdb.connect(host="localhost", user="dumb", > passwd="dumber", db="rdc") > cursor = db.cursor() > cursor.execute("INSERT INTO es_accounts (dateCreated, > accountNumber, description, openingBalance) VALUES (%s, %s, %s, %d)", > (date, accountNumber, description, dec)) > > I get this error: > Traceback (most recent call last): > File "main.py", line 59, in > main() > File "main.py", line 40, in main > dbObj.insertAccount(dateTo, item[0], item[1], item[8]) > File "C:\projects\workspace\INYR_ES_0.1\src\db.py", line 19, in > insertAccount > cursor.execute("INSERT INTO es_accounts (dateCreated, > accountNumber, description, openingBalance) VALUES (%s, %s, %s > , %d)", (date, accountNumber, description, dec)) > File "c:\python25\lib\site-packages\MySQLdb\cursors.py", line 151, > in execute > query = query % db.literal(args) > TypeError: int argument required > > My table is defined as: > CREATE TABLE es_accounts ( > id int(6) not null auto_increment, > dateCreated date DEFAULT '0000-00-00', > accountNumber int(6) not null, > description varchar(255) not null, > openingBalance decimal(15,8) NOT NULL DEFAULT 0.00000000, > primary key (id) > ); > > TIA The problem is your %d in Values, and then using a Decimal type to feed it. Depending on the type of your openingBalance field, you may want to change the %d to %s, or change dec to int(dec), or change the %d to %f and change dec to float(dec). My experience with the Decimal type is limited, so there may be other options as well. ~Ethan From deets at nospam.web.de Wed Jul 16 03:05:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Jul 2008 09:05:58 +0200 Subject: Redirecting stdout to another script In-Reply-To: References: Message-ID: <6e5kusF5c5a4U2@mid.uni-berlin.de> Richard Sim?es schrieb: > Hopefully, this explanation will sufficiently clear despite the lack > of code. > > I wrote a python script that takes data via stdin, does stuff with the > data, and outputs the result to stdout. A friend wrote a perl script > that opens a pipe to my script, feeds it data, and then accepts the > result. The problem here is that the python script's outputting the > result to stdout via print statements isn't doing what we expected: my > friend's perl script isn't getting the result back via the pipe. > > Is there is simple solution for this problem? Whose script needs to be > modified? That of your friend, if he is the one invoking you. Because the invoking script is the one responsible for connecting the pipes properly. Diez From larry.bates at websafe.com` Thu Jul 10 11:47:38 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 10 Jul 2008 10:47:38 -0500 Subject: python scalability In-Reply-To: References: Message-ID: Tim Mitchell wrote: > Hi All, > > I work on a desktop application that has been developed using python and > GTK (see www.leapfrog3d.com). We have around 150k lines of python code > (and 200k+ lines of C). We also have a new project manager with a C# > background who has deep concerns about the scalability of python as our > code base continues to grow and we are looking at introducing more > products. I am looking for examples of other people like us (who write > desktop apps in python) with code bases of a similar size who I can > point to (and even better talk to) to help convince him that python is > scalable to 300+ lines of code and beyond. I have looked at the python > success stories page and haven't come up with anyone quite like us. One > of my project managers questions is: "Are we the only company in the > world with this kind and size of project?" > I want to say no, but am having trouble convincing myself, let alone him. > > If you are involved in this kind of thing please get in touch with me. > > Thanks, > Tim It is not clear what "scalability" means to a desktop application? When maximum calculation speeds are required, you can drop into C libraries from Python with ease. If this is about making use of multiple cores on a machine this link (http://wiki.python.org/moin/ParallelProcessing) covers most of the solutions that can be implementing in Python. Another poster has suggested that you would need 1500K lines of C to replace 300K lines of Python (and he may be being generous to C). Projects are about more than raw speed: maintainability, speed of adding features, etc. Python wins those races in most situations. I'm sure that hand coded assembler would run fastest of all, but little application software is written that way these days. -Larry From tn.pablo at gmail.com Tue Jul 22 17:02:57 2008 From: tn.pablo at gmail.com (ptn) Date: Tue, 22 Jul 2008 14:02:57 -0700 (PDT) Subject: Function editing with Vim throws IndentError Message-ID: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Hi everybody, I have a weird problem. Say I have a .py file with some functions in it, like this: # (...) def foo(): print("bar") When I open it and add a line to one of the functions, # (...) def foo(): troz = "bar" print(troz) I get the following traceback from the interpreter: Traceback (most recent call last): File "SOMEWHERE/example.py", line ?? troz = "bar" ^ IndentationError: unindent does not match any outer indentation level And so I'm forced to rewrite the function entirely just to add the new line. I thought that my problem was the w option from formatoptions, so I changed my .vimrc file to this: augroup filetype autocmd BufNewFile,BufRead *.txt set filetype=human augroup END autocmd FileType human setlocal formatoptions+=ta2w autocmd FileType lisp,scheme,python,c,java,vim setlocal formatoptions-=ta2w But the problem didn't go away. I don't think this has anything to do with the tabs and spaces, because I have them set up like this: set tabstop=4 shiftwidth=4 expandtab which is the standard way to handle them. The scripts I load are: qbuf, TagList, indent/python.vim and a reduced version of the standard python.vim Could someone provide some pointers? Thanks, Pablo Torres N. From Ming.YIN at murex.com Fri Jul 11 06:31:35 2008 From: Ming.YIN at murex.com (YIN Ming) Date: Fri, 11 Jul 2008 18:31:35 +0800 Subject: recommended gcc versions for python2.5 compilation on Solarissparc/x86, AIX, Linux In-Reply-To: <20080711095456.GW68329@nexus.in-nomine.org> References: <9347F3EEF61FC542A7D9211A42CD7E6387E071@dolphin.sg.murex.com> <20080711095456.GW68329@nexus.in-nomine.org> Message-ID: <200807111031.m6BAVRGh012217@mail.m> Dear Jeroen, Thanks so much for your help. :) Best regards, Yin Ming -----Original Message----- From: Jeroen Ruigrok van der Werven [mailto:asmodai at in-nomine.org] Sent: Friday, July 11, 2008 5:55 PM To: YIN Ming Cc: python-list at python.org; LEGRAND Mathieu Subject: Re: recommended gcc versions for python2.5 compilation on Solarissparc/x86, AIX, Linux -On [20080711 06:18], YIN Ming (Ming.YIN at murex.com) wrote: >2. use new version of gcc (rather than odd version) See http://www.in-nomine.org/2008/04/11/python-26a2-execution-times-with-various-compilers/ that I wrote a while ago. Basically for Python GCC 3.4.6 outperformed the newer GCCs. So do not automatically assume that newer is better. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B The weak can never forgive. Forgiveness is the attribute of the strong... -------------------------------------------------------- This e-mail contains information for the intended recipient only. It may contain proprietary material or confidential information. If you are not the intended recipient you are not authorised to distribute, copy or use this e-mail or any attachment to it. Murex cannot guarantee that it is virus free and accepts no responsibility for any loss or damage arising from its use. If you have received this e-mail in error please notify immediately the sender and delete the original email received, any attachments and all copies from your system. From code at pizzashack.org Sun Jul 27 15:59:26 2008 From: code at pizzashack.org (Derek Martin) Date: Sun, 27 Jul 2008 15:59:26 -0400 Subject: Attack a sacred Python Cow In-Reply-To: <009c2b11$0$20302$c3e8da3@news.astraweb.com> References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> Message-ID: <20080727195926.GF7373@dragontoe.org> On Sun, Jul 27, 2008 at 08:19:17AM +0000, Steven D'Aprano wrote: > > You take the name down to a single letter. As I suggested in an earlier > > post on this thread, why not take it down to zero letters? > > The question isn't "why not", but "why". The status quo works well as it > is, even if it isn't perfect. Prove that implicit self is a good idea -- > or at least prove that it is an idea worth considering. Come on, this sounds like a schoolyard argument. This comes down to a matter of style, and as such, is impossible to prove. It's largely a question of individual preference. That said, the argument in favor is rather simple: 1. This is an extremely common idiom in Python 2. It is completely unnecessary, and the language does not suffer for making it implicit 3. Making it implicit reduces typing, reduces opportunities for mistakes, and arguably increases consistency. As for the latter part of #3, self (or some other variable) is required in the parameter list of object methods, however when the method is *called*, it is omitted. It is implied, supplied by Python. Thus when an object method is called, it must be called with one fewer arguments than those which are defined. This can be confusing, especially to new programmers. It can also be argued that it makes the code less ugly, though again, that's a matter of preference. > It's not enough to show that a change "isn't bad" -- you have to show > that it is actively good. But he did... he pointed out that *it saves work*, without actually being bad. Benefit, without drawback. Sounds good to me! > "Don't need to look at the method signature" is not an argument in favour > of implicit self. Yes, actually, it is. If there is a well-defined feature of Python which provides access to the object within itself, then the opportunities for mistakes when someone decides to use something else are lessened. > You don't need to look at the method signature when you're using an > explicit self either. That isn't necessarily true. If you're using someone else's code, and they didn't use "self" -- or worse yet, if they chose this variable's name randomly throughout their classes -- then you may well need to look back to see what was used. It's bad programming, but the world is full of bad programmers, and we don't always have the choice not to use their code. Isn't one of Python's goals to minimize opportunities for bad programming? Providing a keyword equivalent to self and removing the need to name it in object methods is one way to do that. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From iainking at gmail.com Sat Jul 19 04:52:56 2008 From: iainking at gmail.com (Iain King) Date: Sat, 19 Jul 2008 01:52:56 -0700 (PDT) Subject: Best Python packages? References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> <17861f55-8ad1-4703-ad22-838675f2afc4@w1g2000prk.googlegroups.com> <48819E2D.10903@behnel.de> Message-ID: On Jul 19, 8:56 am, Stefan Behnel wrote: > Iain King wrote: > > Well, if you're looking for a list of excellent 3rd party Python > > libraries, then I can give you the ones I like and use a lot: > [...] > > BeautifulSoup : for real-world (i.e. not-at-all-recommendation- > > compliant) HTML processing > > You forgot lxml.html, which is much faster, more memory friendly and more > feature-rich than BS. > > Stefan Never heard of it :) Iain From mwilson at the-wire.com Tue Jul 1 08:47:18 2008 From: mwilson at the-wire.com (Mel) Date: Tue, 01 Jul 2008 08:47:18 -0400 Subject: Implementing an 8 bit fixed point register References: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> Message-ID: nickooooola wrote: > Hello to all > I'm about to write a simulator for a microcontroller in python > (why python? because I love it!!!) [...] > The registry of this processor are all 8 bit long (and 10 bit for some > other strange register) > and I need to simulate the fixed point behaviour of the register, > and to access the single bit. > > f.x. (this is a pseudo python session, only for understanding) > >>>> reg1 = fixed_int(8) >>>> reg2 = fixed_int(10) >>>> reg1[0].set() > or >>>> reg1[0] = 1 # or True? how to rapresent a binary bit >>>> reg1[0] > 1 >>>> reg1[1] > 0 >>>> reg1[9] > >>>> reg2 = 0x7FE # in binary 11111111110 , or 11 bit long >>>> reg2 > 0x7FE > #or 1111111110, the memorization truncate the upper bits ( or perhaps > generate an exception?) >>>> reg2 += 0x02 #the result is 10000000000, again not contained in 10 bit >>>> reg2 > 0x00 > # truncated again >>>> myprocessor.flags['z'] > 1 > # or True? Z flag indicated an overflow in arithmetic operations > > Is possibile to do so in python? I did this for a PIC, and generally just used brute force, e.g. temp = reg2 + 0x02 reg2 = temp & 0xFF if temp & 0x100: flags |= CARRY_MASK else: flags &= ~CARRY_MASK if temp & 0xFF: flags &= ~ZERO_MASK else: flags |= ZERO_MASK Since it was a PIC, and there were only a half-dozen arithmetic/logical operations, the code stayed in this form. With something bigger, it would have been attractive to wrap these operations up in a class, as you suggest.. (just a sketch) .. class fixed_register (object): def __init__ (self, size, val=0): self.mask = ~(-1 << size) self.ovfmask = 1 << size self.val = val & self.mask with appropriate __add__, __sub__, etc. Perhaps __getitem__, __setitem__ to manipulate bits. Good Luck, Mel. From musiccomposition at gmail.com Fri Jul 11 08:28:56 2008 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 11 Jul 2008 05:28:56 -0700 (PDT) Subject: using Python's AST generator for other languages References: <6d31532b-9946-42a3-a20b-56c403a388b2@l42g2000hsc.googlegroups.com> Message-ID: On Jul 11, 12:27 am, eliben wrote: > > > 2) What is the meaning of the comment in astgen.py ? Are the Python > > > maintainers unhappy with the design of the AST ?3 > > > Node, I think, is talking about a node in the parse tree. (AST is > > generated from another parse tree.) See PEP 339 for details. > > > > Thanks, PEP 339 clarified a lot to me. I wonder, though, at the need > for two Python compilation frameworks in the same code base. While > CPython uses the flow described in PEP 339 (parsing to an AST > generated from ASDL), the compiler module of the standard library > takes a different approach, with a custom AST description syntax in > ast.txt > Why aren't the two methods unified. I.e. can't the compiler.ast module > be also generated from ASDL, and provide a more unified interface to > the real thing ? You are correct on all points and this is one of the main reasons that the compiler package is going away in 3.0. > > Eli From jmcmonagle at velseis.com.au Tue Jul 8 21:02:08 2008 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Wed, 09 Jul 2008 11:02:08 +1000 Subject: a simple 'for' question In-Reply-To: <4874017D.2000401@umbc.edu> References: <4874017D.2000401@umbc.edu> Message-ID: <48740E10.7020400@velseis.com.au> Ben Keshet wrote: > Hi fans, > > I want to use a 'for' iteration to manipulate files in a set of folders, > something like: > > folders= ['1A28','1A6W','56Y7'] > for x in folders: > print x # print the current folder > f = open('my/path/way/x/my_file.txt', 'r') > ... > Use os.path.join import os folders = ['1A2B', '1A6W', '56Y7'] for x in folders: f = open(os.path.join('my/path/way', x, 'my_file.txt'), 'r') From fuzzyman at gmail.com Tue Jul 29 05:09:07 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Tue, 29 Jul 2008 02:09:07 -0700 (PDT) Subject: ironpython, exception in mscorlib when reading .py file from network share References: <6dfb578a-17ff-434d-a071-646ed3ef2b03@z72g2000hsb.googlegroups.com> Message-ID: <15144d50-319d-48ce-bd16-0ead4226dd08@f63g2000hsf.googlegroups.com> On Jul 29, 9:34?am, mindmind wrote: > Hello, > > I have a ironpython 1.1.1.0 host in my c# app, and When doing a > ? engine.ExecuteFile(file); > i often get the error below, when "file" is on a network share : > (winXp client , windows ??? server) > > 21-07-2008 12:47:28 : Traceback (most recent call last): > 21-07-2008 12:47:28 : ? File c:\sandbox\xxx.cs > 21-07-2008 12:47:28 : ? File c:\sandboxx\yyy.cs > 21-07-2008 12:47:28 : ? File mscorlib, line unknown, in ReadAllBytes > 21-07-2008 12:47:28 : ? File mscorlib, line unknown, in Read > 21-07-2008 12:47:28 : ? File mscorlib, line unknown, in ReadCore > 21-07-2008 12:47:28 : ? File mscorlib, line unknown, in WinIOError > 21-07-2008 12:47:28 : IOError: The specified network name is no longer > available. > 21-07-2008 12:47:28 : > > Exception is caught before first line in python is executed. > > Other parts of the program is also accessing the network (for copying > files etc), and never fails, > so networks connection is "ok" (maybe not perfect, but at least > present.) > > Is the ExecuteFile reading the contents of the .py file differently > than a "copy" primitive is (other timeout/retry values) ? > > Does anyone have any ideas of how to setup windows , ironpython host > or .NET lib differently, to stop it doing this ? Fallback solution is > to copy file locally before execution, but I would rather fix this. > > thx I don't know the answer - I do know that .NET permissions issues and accessing network resources are a bit 'weird'. You're likely to get an answer if you ask on the IronPython mailing list. Michael Foord -- http://www.ironpythoninaction.com/ From mcmurtri at dslextreme.com Sun Jul 13 03:22:52 2008 From: mcmurtri at dslextreme.com (Kevin McMurtrie) Date: Sun, 13 Jul 2008 00:22:52 -0700 Subject: spam <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> Message-ID: In article , Lew wrote: > WDC wrote: > > BTW I reported it, yo should too. > > To whom did you report it, so that we may also report it there? Google does not accept spam complaints. Go ahead, try it. That's why they've been the #1 Usenet spamming tool for years now. What you're seeing is the spam slowly expanding into the software development groups. uk.railway is probably a random group added to confuse spam filters. Some groups, like rec.photo.digital, have been getting hundreds of Google spams a day for about a year. Ask your news service for a Google UDP (Usenet Death Penalty) or configure your reader to drop everything with "googlegroups.com" in the Message-ID. http://improve-usenet.org/ -- I will not see your reply if you use Google. From anonymous at anonymitaet-im-inter.net Mon Jul 14 00:08:54 2008 From: anonymous at anonymitaet-im-inter.net (Dave U. Random) Date: Mon, 14 Jul 2008 06:08:54 +0200 (CEST) Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) Message-ID: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> http://snipr.com/PracticalDjango From sjmachin at lexicon.net Wed Jul 2 18:29:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 2 Jul 2008 15:29:28 -0700 (PDT) Subject: Sorting two dimentional array by column? References: Message-ID: On Jul 3, 7:35 am, Tobiah wrote: > > Imagine an excel spreadsheet. I can choose > > a column and sort the records based on the items > > in that column. I would like to do the same > > thing with a large two dimensional array. > > What would be the fastest way (in computation time) > > to accomplish this? > > Now that I think about the problem more, I really want > to sort an array of dictionaries according one of the > keys of each. Could I use: > > array.sort(key = something) > > Where something looks at the proper item in the > current row? I can't quite visualize how to pull > the item out of the dictionary. Manual sez: """key specifies a function of one argument that is used to extract a comparison key from each list element: "key=str.lower" """ Assuming that "sort an array of dictionaries according one of the keys of each" means "sort an array of dictionaries according to the value stored for one of the keys of each". If the dict key were a constant, you could do: array.sort(key=lambda adict: adict['the_constant_key']) However you want the current row, and sort wants a 1-arg key function ... to stick with the key= caper you'll need to curry the extra arg. So (Python 2.5 onwards): # do this once import functools def dict_extract(adict, akey): return adict[akey] # do this each time you want to sort current_row_key = whatever() sort_key_func = functools.partial(dict_extract, akey=current_row_key) array.sort(key=sort_key_func) Alternatively, use the decorate-sort-undecorate procedure: temp = [(d[current_row_key], d) for d in array] temp.sort() array[:] = [tup[1] for tup in temp] HTH, John From bruno.desthuilliers at gmail.com Wed Jul 9 16:44:31 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 9 Jul 2008 13:44:31 -0700 (PDT) Subject: You, spare time and SyntaxError References: Message-ID: On 9 juil, 16:56, cokofree... at gmail.com wrote: > def ine(you): > yourself = "what?" > go = list("something"), list("anything") > be = "something" > please = be, yourself > yourself = "great" > for good in yourself: > if you is good: > good in you > please.add(more, good) > else: > def inition(lacks, clarity): > if clarity not in you: > please.remove(everything and go) > for bad in yourself: > list(bad) if bad else (ignore, yourself) > try: > (to, escape, your, fate, but) > except (Exception), son: > if bad in (you, son): > (you is bad, son), so > finally: > if bad in you: > lie, cheat, steal, be, bad > else: > print you, "is", yourself > you is good and yourself is not bad > please, go > > ine("Everyone") just... great !-) From alif016 at gmail.com Mon Jul 7 23:27:02 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Mon, 07 Jul 2008 22:27:02 -0500 Subject: Python Agile Software Development Tools Screencasts In-Reply-To: <8763rhw0vv.fsf@benfinney.id.au> References: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> <87lk0dwbys.fsf@benfinney.id.au> <87hcb1w6gl.fsf@benfinney.id.au> <87abgtw52g.fsf@benfinney.id.au> <8763rhw0vv.fsf@benfinney.id.au> Message-ID: <4872DE86.4030508@gmail.com> Ben Finney wrote: > Andrew Freeman writes: > >> http://videos1.showmedo.com/ShowMeDos/2910000.flv >> > > Which leads one to wonder why they don't just present that URL for > download instead of behind a "log in" gate. And how long that will be > possible before they break it ? presumably the site admins put that > barrier there for a reason. > It appears that the url would be difficult to change; it appears to be mapped to a database: http://showmedo.com/videos/video?name=2910000&fromSeriesID=291 notice the "name" is the same in this URL and the flv. -- Andrew From mail at timgolden.me.uk Fri Jul 11 11:04:35 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 11 Jul 2008 16:04:35 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) In-Reply-To: References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: <48777683.2080804@timgolden.me.uk> Bill Davy wrote: > Traceback (most recent call last): > File "H:/Personal/OutlookIF1/t2.py", line 18, in > outlook = win32com.client.gencache.EnsureDispatch > ("Outlook.Application") > File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line > 536, in EnsureDispatch > mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], > bForDemand=bForDemand) > File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line > 393, in EnsureModule > module = GetModuleForTypelib(typelibCLSID, lcid, major, minor) > File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line > 262, in GetModuleForTypelib > AddModuleToCache(typelibCLSID, lcid, major, minor) > File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line > 554, in AddModuleToCache > dict = mod.CLSIDToClassMap > AttributeError: 'module' object has no attribute 'CLSIDToClassMap' Just in case, could you delete the contents of your gen_py directory (probably in %TEMP%\gen_py) TJG From siona at chiark.greenend.org.uk Tue Jul 29 12:26:31 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 29 Jul 2008 17:26:31 +0100 (BST) Subject: Continuous integration for Python projects References: <6f8pelFafh42U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >Hussein B wrote: >> Please correct my if I'm wrong but it seems to me that the major >> continuous integration servers (Hudson, CruiseControl, TeamCity ..) >> don't support Python based application. >> It seems they mainly support Java, .NET and Ruby. >> Can I use one of the previous listed servers for Python project? >Hudson can, and AFAIK CC as well - they only invoke shell-scripts (at least >hudson does, and CC you can convince doing that using ANT) You can definitely set up CruiseControl to handle Python, but don't ask me for details as it was a couple of years and a change of job ago. I seem to remember it being easier when CC was driving make, but we had makefiles in any case for building the extension modules needed -- writing a makefile from scratch might be a bit much. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From dp_pearce at hotmail.com Tue Jul 15 11:24:55 2008 From: dp_pearce at hotmail.com (dp_pearce) Date: Tue, 15 Jul 2008 08:24:55 -0700 (PDT) Subject: Zipping files Message-ID: Hi all, I have come across an error while using zipfile and I can't seem to find somewhere that explains the problem. My script needs to be able to take text files from one drive and add them to zip files on another drive. The following seems to work just fine. import zipfile # write test file in working directory directory folder = "J:/" filename = "testing.txt" fullpath = folder+filename fout = open(fullpath, 'wt') fout.write(str1) fout.close() # Add text file to zip file on same drive zFolder = "J:/" zFilename = "testing.zip" zFullpath = zFolder+zFilename zout = zipfile.ZipFile(zFullpath, "w") zout.write(fullpath) zout.close() print fullpath, "successfully added to", zFullpath However, if I change the drive letters to anything other than the drive from which the Python script is saved (e.g. run script from J: but zip to C:), I get the following warning: Traceback (most recent call last): File "J:/test.py", line 18, in zout = zipfile.ZipFile(zFullpath, "w") File "C:\Python25\lib\zipfile.py", line 339, in __init__ self.fp = open(file, modeDict[mode]) IOError: [Errno 13] Permission denied: 'C:/testing.zip' Can anyopne shed some light on what I am missing here? If it has any relevance to the permissions part of the error, I am currently using Windows machines. Thanks in advance for your time. Dan From jadamwilson2 at gmail.com Tue Jul 22 00:36:38 2008 From: jadamwilson2 at gmail.com (jadamwil) Date: Mon, 21 Jul 2008 21:36:38 -0700 (PDT) Subject: fromfile error on windows, not mac Message-ID: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> Hello, I am using the numpy fromfile function to read binary data from a file on disk. The problem is that the program runs fine on a Mac, but gives an error or warning on windows when trying to read the data. I use it like this: Signal = zeros((N, 16), dtype=float32) for sample in range(0, N): # this function gets the next position in the file to seek to s = getFilePos(sample) # go to the correct location in the file; this IS checked to make sure it is within the file mFile.seek(s) # read the 16 float32 values from the file D = fromfile(mFile, dtype=numpy.float32, 16) # save D in Signal Signal[sample, :] = D This will fail when sample is ~4. If I change the range to (5,N), skipping the "bad" file location, it will run fine for a few samples, and then give another error. The message it gives is: "16 items requested but only 7 read" So D is a 7x1 vector, and the program dies when it tries to assign D to the slice of Signal ("ValueError: shape mismatch: objects cannot be broadcast to a single shape"). On windows, the Python version is 2.5.2, and the most recent numpy and scipy are being used as well. I tried using Enthought, but it gave this error as well, in addition to a c runtime error whenever I imported scipy (which is another post topic...). Any ideas on what might be causing this? Is there a way to debug the fromfile function? And, remember, this works perfectly on a Mac. Would compiling everything (python, scipy, numpy) potentially solve this? Thanks! From lanny at freshells.ch Thu Jul 24 11:56:44 2008 From: lanny at freshells.ch (Lanny) Date: Thu, 24 Jul 2008 08:56:44 -0700 Subject: Raw Strings (I Think) References: Message-ID: > my guess is that the real problem is that you get back filenames with > spaces in them, which gets treated as multiple arguments by os.system. > > using os.startfile will fix this: > > >>> import glob, os, random > >>> file = random.choice(glob.glob("\\music\\*.mp3")) > >>> file > '\\music\\Madrugada - Grit - 05 - Seven Seconds.mp3' > >>> print file > \music\Madrugada - Grit - 05 - Seven Seconds.mp3 > >>> os.system(file) > '\music\Madrugada' is not recognized as an internal or external command, > operable program or batch file. > 1 > >>> os.startfile(file) > ... music starts playing ... > > Thanks I just switched the startfile for system and it worked like a charm Thanks -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- From keshet1 at umbc.edu Thu Jul 3 11:02:20 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Thu, 03 Jul 2008 11:02:20 -0400 Subject: Write a file - beginner's question Message-ID: <486CE9FC.3090204@umbc.edu> I have a probably simple beginner's question - I have a script that I am currently able to print its output. instead, i want to write it into a file - I tried different versions of write() but might have gotten the syntax wrong. the variable I want to write is a line from a file I am reading: "... f = open('receptor.mol2', 'r') line = f.readline()[:-1] while '@ATOM' not in line: line = f.readline()[:-1] #print line print random_mol2 ..." e.g. I want to write to a file all the lines in 'receptor.mol2' up to the string "@ATOM" (one after the other). Can anyone please advice? On a related note - how do I read and write to a file that is not in the same directory? e.g how do I provide a pathway to an open command? Please remember that I am a very beginner in Python and programming - Thank you. From jaganadhg at gmail.com Thu Jul 24 01:57:51 2008 From: jaganadhg at gmail.com (=?UTF-8?B?4LSc4LSX4LSo4LWN4LSo4LS+4LSl4LWN?=) Date: Wed, 23 Jul 2008 22:57:51 -0700 (PDT) Subject: Doubt References: Message-ID: On Jul 24, 1:13 am, Fredrik Lundh wrote: > ???????? wrote: > > I am a Perl programmer new to Python. I have a small doubt. > > I suspect you mean "question", not "doubt". It's not quite the same thing. > > > How to convert the perl notation > > $a = ""; expression in Python ? > Thank you for all to giving suggestions . With regards Jaganadh G > > How to represent the loop > > for ($a = $b; $a<=$c;$a++){ > > } in Python > > Start here: > > http://www.lucasmanual.com/mywiki/PerlPythonPhrasebook > > and then read either of these (preferably both): > > http://www.swaroopch.com/byteofpython/ > http://docs.python.org/tut/ > > From ojeeves at gmail.com Mon Jul 14 11:37:54 2008 From: ojeeves at gmail.com (oj) Date: Mon, 14 Jul 2008 08:37:54 -0700 (PDT) Subject: Do we have perl's Data::Dumper equivalent in Python?? References: Message-ID: On Jul 14, 11:41?am, srinivasan srinivas wrote: > Thanks, > Srini > > ? ? ? Bollywood, fun, friendship, sports and more. You name it, we have it onhttp://in.promos.yahoo.com/groups/bestofyahoo/ You might have more luck asking for help if you explained what Perl's Data::Dumper actually does, instead of expecting people to either just know, or to go and look it up. In particular, what functionality of Data::Dumper is it you are looking for? For a user friendly representation of a python data structure, look at pprint: http://docs.python.org/lib/module-pprint.html For a string representing a data structure that can be eval'd to get the structure back again, look at the built-in repr() -Oli From rowen at cesmail.net Tue Jul 29 15:28:12 2008 From: rowen at cesmail.net (Russell E. Owen) Date: Tue, 29 Jul 2008 12:28:12 -0700 Subject: like py2exe, but on a mac References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> Message-ID: In article , Tommy Nordgren wrote: > On 28 jul 2008, at 03.59, William McBrine wrote: > > > On Sun, 13 Jul 2008 00:58:59 +0200, Python.Arno wrote: > > > >> http://undefined.org/python/py2app.html > > > > py2app bundles Python itself into the app, right? I wonder, is there > > no > > way to create an app bundle that relies on the existing installation > > of > > Python, since OS X already comes with Python? I have a tiny little > > program (~20k) that I'd like to make into an app bundle, if only to > > suppress the console window, and I'd rather not lump in the whole > > Python > > interpreter if I can avoid it. > > > There is Platypus, a general open source program to wrap a script > in an Macintosh (GUI) It's an interesting application, but... I tried it to bundle a script that puts up a standard Tkinter file save dialog box and I found that the dialog box was not in front -- I had to switch applications to get to it. Still, it looks useful for fully faceless applications; unlike py2applet the text to stdout shows up in a log window. -- Russell From michael at stroeder.com Tue Jul 8 04:52:13 2008 From: michael at stroeder.com (=?UTF-8?B?TWljaGFlbCBTdHLDtmRlcg==?=) Date: Tue, 08 Jul 2008 10:52:13 +0200 Subject: windows active directory ldap output encoding In-Reply-To: References: Message-ID: jo3c wrote: > Im trying to get some information out of a windows sever 2003 chinese > active directory system > so let's say encoding is probably big5 or utf-8 The Unicode encoding of LDAP attributes with syntax Directory String is always UTF-8 (e.g. attributes 'cn', 'sn', 'givenName' or 'displayName'). > what im doing is simliar to ldapsearch in shell with my python script > using python ldap module > > the result is not the correct encoding.. What exactly did you expect? > 'cn': ['\xe6\xb1\x9f\xe6\x9f\x8f\xe5\xa3\x95'], >>> unicode('\xe6\xb1\x9f\xe6\x9f\x8f\xe5\xa3\x95','utf-8') u'\u6c5f\u67cf\u58d5' I cannot tell whether this Unicode string of length 3 is correct since I cannot read Chinese and I probably don't have the necessary fonts installed. At least it decodes as UTF-8 which is correct at the LDAP level. > 'displayName': ['\xe6\xb1\x9f\xe6\x9f\x8f\xe5\xa3\x95'], >>> unicode('\xe6\xb1\x9f\xe6\x9f\x8f\xe5\xa3\x95','utf-8') u'\u6c5f\u67cf\u58d5' Maybe you should provide the original Unicode string (e.g. in Python syntax) and tell us how you store that into your AD server. Note that the tools used to maintain AD are also part of the game. Ciao, Michael. From bj_666 at gmx.net Tue Jul 15 11:39:39 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Jul 2008 15:39:39 GMT Subject: String flags - redundant? References: Message-ID: <6e3ulrF527ucU1@mid.uni-berlin.de> On Tue, 15 Jul 2008 18:14:15 +0300, Alexandru Palade wrote: > I'm rather a Python newbie, so I've put myself a question. Are these two > statements (performance-wise) equal? > > r""" Text """ > and > """ Text """ > > I mean using the raw flag speeds up things because the interpreter > doesn't need to look after escape sequences? Or it's rather optimized? > I'm asking you this because I want to know how my """-style comments > should be written in order not to affect the performance. *Please* stop worrying about the speed of the compilation here. If you have doubts about speed then measure and find the bottlenecks in your code and iff you find hotspots *then* try to optimize. But only iff the program is *to slow*, not when it's fast enough anyway. In that case you should always favor more readable code above speed. > And another short question... Are there any flags to specify variables > intercalation in a string? I mean "I have x apples", how can i specify > for the interpreter to substitute x with it's value? (in case *x* is a > variable). And if this flag exists is it better to use "I have " + x + " > apples" or the above mentioned way? Maybe you should work through the tutorial in the Python documentation. Ciao, Marc 'BlackJack' Rintsch From sjdevnull at yahoo.com Sun Jul 6 03:07:32 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Sun, 6 Jul 2008 00:07:32 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> <9cae59d9-ead4-45bc-a980-2ac2e1616f9b@p25g2000hsf.googlegroups.com> Message-ID: <1fed692b-099a-4a66-a26d-c937b5c610c8@f63g2000hsf.googlegroups.com> On Jul 5, 11:13 am, Mark Dickinson wrote: > Apparently, grep and Tcl convert a regex to a finite state machine. ... > But not all PCREs can be converted to a finite state machine ... > Part of the problem is a lack of agreement on what > 'regular expression' means. Strictly speaking, PCREs aren't > regular expressions at all, for some values of the term > 'regular expression'. See > > http://en.wikipedia.org/wiki/Regular_expression Formally, there's no lack of agreement that I'm aware of. Anyone formally defining it will use something along the lines of what wikipedia specifies (with "Regular expressions in this sense can express the regular languages, exactly the class of languages accepted by finite state automata."). Colloquially it's used to mean "any text- matching scheme that looks vaguely like sed/grep regexes". PCREs are certainly not "real" regular expressions, but they are colloquially. From deets at nospam.web.de Thu Jul 24 05:47:24 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 24 Jul 2008 11:47:24 +0200 Subject: Requires a character ... !! References: Message-ID: <6er1fdF8cqfvU1@mid.uni-berlin.de> > Thx for that info. I understand. > The requirements state that it needs Python 2.2, But i wonder > how that program has been implemented using Python 2.3 features. > Anyhow, this has to be resolved and i need your help. > > Kindly let me know a trick to make to resolve > the 'in' operator related problem by using Python 2.2. You obviously don't understand and it appears that it's time to resort to somewhat more explicit clue-batting: YOU ARE UNDER A WRONG IMPRESSION THAT YOUR SOFTWARE REQUIRES PYTHON 2.2. YOU HAVE BEEN TOLD THAT NUMEROUS TIMES. SO PLEASE - STOP USING PYTHON 2.2 FOR IT. WHOEVER TOLD YOU THAT IT IS NEEDED WAS ****WROOOOONG****** Now did that get through? Given your record here, I think I have to repeat... STOP USING PYTHON 2.2. NOW! Diez From diordna at gmail.com Sun Jul 20 23:05:54 2008 From: diordna at gmail.com (Stephen Johnson) Date: Sun, 20 Jul 2008 23:05:54 -0400 Subject: Python Written in C? In-Reply-To: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> References: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> Message-ID: <81FB1292-CE2E-49DB-AEF9-72F4D7866AD6@gmail.com> > Carry bits? Who worries about carry bits when you have > unlimited precision arithmetic? You want cool? > THIS is cool: > > j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2])) > % xyz[1]**(k-1))/xyz[1]**(k-2) You call that "cool." I call it "unreadable." -Steve Johnson From arsyed at gmail.com Sun Jul 20 18:09:19 2008 From: arsyed at gmail.com (arsyed) Date: Sun, 20 Jul 2008 18:09:19 -0400 Subject: examples of pipe usage? In-Reply-To: <5aab8bb6-0d56-475d-85c2-ced908e29412@x36g2000prg.googlegroups.com> References: <5aab8bb6-0d56-475d-85c2-ced908e29412@x36g2000prg.googlegroups.com> Message-ID: <9a2cc7a70807201509g5a41f6b9sb563bafcbdab5aa5@mail.gmail.com> On Sun, Jul 20, 2008 at 5:27 PM, Sean McIlroy wrote: > hola > > i'd like to control another interpreter from idle. i don't have any > experience using unix but i think a "pipe" is what i need. am i right > about this? can anybody point me to a simple example of using a pipe > (if that's the right thing) for this kind of task? thanks if you can > help. > > Take a look at the URL below which has a bunch of examples of using the subprocess module to interact with other processes. http://blog.doughellmann.com/2007/07/pymotw-subprocess.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From joshdw4 at gmail.com Thu Jul 31 07:15:04 2008 From: joshdw4 at gmail.com (joshdw4 at gmail.com) Date: Thu, 31 Jul 2008 04:15:04 -0700 (PDT) Subject: Tkinter- Possibly a basic question References: <59dee72b-3fb6-414b-ab49-33cab8f9c9e8@26g2000hsk.googlegroups.com> Message-ID: <75d21498-8bb7-43ac-842f-f4b6f2b0d179@m45g2000hsb.googlegroups.com> On Jul 30, 6:48?pm, "Guilherme Polo" wrote: > On Wed, Jul 30, 2008 at 6:33 PM, ? wrote: > >... > > ... > > The second option is to not create the root there, instead, make App > inherit Tk. I rarely see people doing this, but it works too. Here you > won't need to store the parent in an instance attribute, given it is > always accessible through self.master since you are subclassing Tk. > > ... > > -- > -- Guilherme H. Polo Goncalves Excellent, this one was easy enough for me to understand/implement and it worked. Thanks for the help. From pythonnutter at gmail.com Sat Jul 19 23:36:03 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Sun, 20 Jul 2008 13:36:03 +1000 Subject: Any Game Developers here? In-Reply-To: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> Message-ID: PS. To see some real games developed under pressure/time constraints in Python you should visit PyWeek to see what individuals and teams can create in only a weeks time! http://pyweek.org/ 2008/7/19 Michael Lubker : > Any people that use Python as the predominant language for their game > development here? > > ~Michael > -- > http://mail.python.org/mailman/listinfo/python-list > From anishchapagain at gmail.com Tue Jul 22 05:34:55 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Tue, 22 Jul 2008 02:34:55 -0700 (PDT) Subject: regarding SWIG Message-ID: <12e21dec-b269-4c34-9492-98424d207397@w7g2000hsa.googlegroups.com> Hi.. I'm new to SWIG and need to create Wrapper for C code, so, I have installed the SWIG already but doesnot know how to run it for generating Interface file... My C code is in message.c so what do i need to do the first step..uisng SWIG..i read the documentation but cannot grasp creating interface file. thank's anish From cwitts at gmail.com Wed Jul 23 04:51:45 2008 From: cwitts at gmail.com (Chris) Date: Wed, 23 Jul 2008 01:51:45 -0700 (PDT) Subject: maximum value in a column of file References: Message-ID: On Jul 23, 9:25?am, maurizio wrote: > ?which is the best way for the calculation of the maximum value in a > ? ? column of a file? oddly enough >>> help(max) Help on built-in function max in module __builtin__: max(...) max(iterable[, key=func]) -> value max(a, b, c, ...[, key=func]) -> value With a single iterable argument, return its largest item. With two or more arguments, return the largest argument. From castironpi at gmail.com Wed Jul 23 12:38:56 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 23 Jul 2008 09:38:56 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> Message-ID: <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> On Jul 22, 11:38?pm, Tim Roberts wrote: > castironpi wrote: > > >You're saying the VM can't compile code. ?That makes sense, it's not a > >compiler. > > I wouldn't say "can't". ?The current CPython VM does not compile code. ?It > COULD. ?The C#/.NET VM does. ?IronPython, for example, is an implementation > of Python that uses .NET. ?In that case, the code *IS* JIT compiled to > assembly when the program starts. > > >Do I understand correctly that JIT does compile to native > >code in some cases? > > VMs that use JIT do, yes. > > >But that's not the only thing that stops python > >from precompiling to assembly directly. ?GNU doesn't come with > >Python. > > Do you mean Linux? > > >What sorts of minimal information would be necessary to take > >from the GNU libs for the user's specific processor, (the one they're > >downloading their version of Python for), to move Python to the > >further step of outputting the machine code? > > I don't know why you think GNU has anything to do with this. ?There's > nothing that prevents the Python run-time from JIT compiling the code. > IronPython does this. ?CPython does not. ?It's an implementation decision. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. Compiling a program is different than running it. A JIT compiler is a kind of compiler and it makes a compilation step. I am saying that Python is not a compiler and in order to implement JIT, it would have to change that fact. > of Python that uses .NET. In that case, the code *IS* JIT compiled to > assembly when the program starts. But still not the user's code, only the interpreter, which is running in assembly already anyway in CPython. From fredrik at pythonware.com Tue Jul 22 16:41:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 22:41:56 +0200 Subject: software engineering foundations? In-Reply-To: <776bfd4d-a9c7-42f7-936f-967f58e7362d@59g2000hsb.googlegroups.com> References: <776bfd4d-a9c7-42f7-936f-967f58e7362d@59g2000hsb.googlegroups.com> Message-ID: Paddy wrote: > This course is an intensive introduction to basic software development > practices for scientists and engineers that can reduce the time they > spend programming by 20-25%. Judging from the table of contents and a quick sampling of a few lectures, that's mostly about programming (with a strong Python flavour), and the material about the engineering process is pretty simplistic, I'd say. On the other hand, the bibliography does have the following to say about the book I recommended: In short, it is everything I wished someone had told me before I started my first full-time programming job. so I guess it's not all that bad ;-) From amdescombes at gmail.com Sat Jul 26 07:33:09 2008 From: amdescombes at gmail.com (AMD) Date: Sat, 26 Jul 2008 13:33:09 +0200 Subject: scanf in python In-Reply-To: References: <4884be5e$0$19722$426a74cc@news.free.fr> <6ek4cgF7hq4vU1@mid.uni-berlin.de> <4884e77a$0$29405$426a74cc@news.free.fr> <4889ae4a$0$3726$426a74cc@news.free.fr> Message-ID: <488b0b7c$0$9616$426a74cc@news.free.fr> Thanks Fredrik, very nice examples. Andr? > AMD wrote: > >>> For reading delimited fields in Python, you can use .split string >>> method. > >> Yes, that is what I use right now, but I still have to do the >> conversion to integers, floats, dates as several separate steps. What >> is nice about the scanf function is that it is all done on the same >> step. Exactly like when you use % to format a string and you pass it a >> dictionary, it does all the conversions to string for you. > > You're confusing surface syntax with processing steps. If you want to > do things on one line, just add a suitable helper to take care of the > processing. E.g. for whitespace-separated data: > > >>> def scan(s, *types): > ... return tuple(f(v) for (f, v) in zip(types, s.split())) > ... > >>> scan("1 2 3", int, int, float) > (1, 2, 3.0) > > This has the additional advantage that it works with any data type that > provides a way to convert from string to that type, not just a small > number of built-in types. And you can even pass in your own local > helper, of course: > > >>> def myfactory(n): > ... return int(n) * "!" > ... > >>> scan("1 2 3", int, float, myfactory) > (1, 2.0, '!!!') > > If you're reading multiple columns of the same type, you might as well > inline the whole thing: > > data = map(int, line.split()) > > For other formats, replace the split with slicing or a regexp. Or use a > ready-made module; there's hardly every any reason to read standard CSV > files by hand when you can just do "import csv", for example. > > Also note that function *creation* is relatively cheap in Python, and > since "def" is an executable statement, you can create them pretty much > anywhere; if you find that need a helper somewhere in your code, just > put it there. The following is a perfectly valid pattern: > > def myfunc(...): > > def myhelper(...): > ... > > myhelper(...) > myhelper(...) > > for line in open(file): > myhelper(...) > > (I'd say knowing when and how to abstract things away into a local > helper is an important step towards full Python fluency -- that is, the > point where you're able to pack "a lot of action in a small amount of > clear code" most of the time.) > > > From pavlovevidence at gmail.com Sun Jul 20 21:00:07 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 20 Jul 2008 18:00:07 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <4ffdeab2-7422-4e08-8acb-e97d6b28cfef@m44g2000hsc.googlegroups.com> On Jul 20, 6:50?pm, giveitawhril2... at gmail.com wrote: > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. I somehow doubt the Python community will feel much of a loss if you decide to learn some other language. Carl Banks From modelnine at modelnine.org Wed Jul 30 03:49:34 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Wed, 30 Jul 2008 09:49:34 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> Message-ID: <200807300949.35060.modelnine@modelnine.org> Am Mittwoch, 30. Juli 2008 09:18:48 schrieb Russ P.: > Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > __nonzero__ work in Python. It's very basic stuff. You can quit > patronizing me (and Carl too, I'm sure). I'll stop repeating what the current state is (which might sound like I'm patronizing, but that's not the real intent actually, I'm just trying to get the discussion straight with what is fact, namely that there already exists an explicit way which doesn't seem to be recognized by some people here) if you agree to my point that we're not talking about a problem with Python, but about a personal stylistic issue with the language design. That's just what I said in my last mail: I can concede that you, personally, have an issue with the current state, but for me and seemingly also for a majority of people who have posted in this thread, that's a non-issue. > The point that you seem to be missing, or refuse to acknowledge for > some reason, is that "if x" can be mistakenly applied to any object > when the programmer thinks that x is a list -- and the programmer will > receive no feedback on the error. > > I have made errors like that, and I could have saved some time had I > used an "empty" method that only applies to a list or other sequence. For me, I've never had this kind of problem, simply because if I test for the truth value of something, I'm going to do something with it later on, and as soon as I'm doing something with it, I'll see whether the object supports the interface I want it to support (and get an error there if the object doesn't support the basic notions of a sequence type, for example, i.e. __iter__()). Testing for truth is IMHO not doing something with an object, and as such I'm more than happy that it's "foolproof". This is one thing that I personally find attractive about Python's way of duck-typing. But, if you personally have been bitten by this, give an example, and I'm sure that we can start discussing from there. I've already given an example why the explicit test for length is less polymorphic than the explicit test for truth of a container elsewhere as a proof for the point I'm trying to make. -- Heiko Wundram From gagsl-py2 at yahoo.com.ar Tue Jul 15 00:16:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 01:16:23 -0300 Subject: Problems Returning an HTTP 200 Ok Message References: <1cf880cc-2036-42dc-8217-d52a714c1710@a70g2000hsh.googlegroups.com> <9bc65e72-be16-4f73-9dfb-6ddeaae34c21@m73g2000hsh.googlegroups.com> <8596af5b-fd0a-413e-8051-62d650e9a153@8g2000hse.googlegroups.com> <8e0527eb-3af1-428f-bfc2-5c1809c33274@t54g2000hsg.googlegroups.com> Message-ID: En Mon, 14 Jul 2008 17:46:12 -0300, samwyse escribi?: > On Jul 11, 3:46?am, "Gabriel Genellina" > wrote: > >> As Guy Davidson has already pointed out, this is a problem in the meter > That would have been me, not Guy. Indeed, sorry the misattribution! -- Gabriel Genellina From john.hanks0 at gmail.com Fri Jul 25 15:36:44 2008 From: john.hanks0 at gmail.com (John Hanks) Date: Fri, 25 Jul 2008 15:36:44 -0400 Subject: Quesion on class.attributes assignment Message-ID: Hi, I am reading a python program now but I just cannot understand how the values of class attributes are assigned and changed. Here is the original code url: http://agolb.blogspot.com/2006/01/sudoku-solver-in-python.html Here I am concerned is how attribute matrix.rows is changed. Through pdb debugging, I can see in line 97, once "self.solutions = set((val,))" is executed, cell.row and matrix.rows will be updated. But I did not see any assignment codes here. How could this change happen then? Thanks a lot! John # http://agolb.blogspot.com/2006/01/sudoku-solver-in-python.html #!/usr/bin/env python # # sudoku-solver version 3 # # Some ideas ripped-off from: # http://www.linuxjournal.com/article/8729 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440542 # Pavol solver in # http://groups.google.com/group/comp.lang.python/browse_thread/thread/5087890f4c5e770d # # Copyright 2005 Ago, # But you are free to copy, reuse, modify and distribute the code as you see fit from copy import deepcopy class DeadEnd(Exception): pass class Matrix: def __init__(self, input): self.rows = [[] for i in range(9)] self.cols = [[] for i in range(9)] self.submatrices = [[] for i in range(9)] self.cells = [Cell(i,self) for i in range(81)] self.subdiagonals = [self.rows[i][j+i%3] for i in range(9) for j in [0,3,6]] input = [s not in '-*' and int(s) or 0 for s in input if s in '0123456789-*'] for cell,val in zip(self.cells, input): if val: cell.setSolution(val) def solve(self): #Brute-force solver self.solveByReduction() lensols=[(len(c.solutions),c.index) for c in self.cells if not c.solved] if not lensols: return True unsolved = min(lensols)[1] solutions = list(self.cells[unsolved].solutions) for s in solutions: tmpmatrix = deepcopy(self) try: tmpmatrix.cells[unsolved].setSolution(s) if tmpmatrix.solve(): self.update(tmpmatrix) return True except DeadEnd: pass def solveByReduction(self): while True: self.changed = False for c in self.cells: c.solve() for c in self.subdiagonals: c.skim() if not self.changed: break def update(self, m): self.rows, self.cols, self.submatrices, self.cells, self.subdiagonals=\ m.rows, m.cols, m.submatrices, m.cells, m.subdiagonals def __str__(self): return "\n".join(str([c for c in row ])[1:-1] for row in self.rows) class Cell: def __init__(self, index, matrix): self.solved = False self.matrix = matrix self.index = index self.row = matrix.rows[index/9] self.col = matrix.cols[index%9] self.submatrix = matrix.submatrices[((index/9)/3)*3+(index%9)/3] self.row.append(self) self.col.append(self) self.submatrix.append(self) self.solutions = set(range(1,10)) def solve(self): if self.solved: return if len(self.solutions) == 1: self.setSolution(self.solutions.pop()) else: sol = set() for cells in [self.row, self.col, self.submatrix]: otherSolutions = self.cells2sols(cells, self) sol |= (self.solutions - otherSolutions) if len(sol) > 1: raise DeadEnd() if sol: self.setSolution(sol.pop()) def skim(self): submatrix = set(self.submatrix) for r in (set(self.row), set(self.col)): subset1 = submatrix - r subset2 = r - submatrix solsNotIn1 = set(range(1,10)) - self.cells2sols(subset2) solsNotIn2 = set(range(1,10)) - self.cells2sols(subset1) for c in subset1: c.delSolutions(solsNotIn1) for c in subset2: c.delSolutions(solsNotIn2) def setSolution(self, val): self.solved = True self.solutions = set((val,)) self.matrix.changed = True for other in self.row+self.col+self.submatrix: if other is self: continue if other.solutions == self.solutions: raise DeadEnd() other.delSolutions(self.solutions) def delSolutions(self, val): if not self.solved and val & self.solutions: self.solutions -= val self.matrix.changed = True if not self.solutions: raise DeadEnd() def __repr__(self): return str(self.solved and list(self.solutions)[0] or list(self.solutions)) @staticmethod def cells2sols(cells, exclude=None): return set(s for c in cells for s in c.solutions if c is not exclude) if __name__ == "__main__": input =''' 1,0,0,0,0,0,0,0,2 0,9,0,4,0,0,0,5,0 0,0,6,0,0,0,7,0,0 0,5,0,9,0,3,0,0,0 0,0,0,0,7,0,0,0,0 0,0,0,8,5,0,0,4,0 7,0,0,0,0,0,6,0,0 0,3,0,0,0,9,0,8,0 0,0,2,0,0,0,0,0,1 ''' matrix = Matrix(input) matrix.solve() print matrix -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: AgolB.py URL: From mail at timgolden.me.uk Fri Jul 4 09:24:36 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 04 Jul 2008 14:24:36 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) In-Reply-To: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: <486E2494.3080905@timgolden.me.uk> Bill Davy wrote: > I am trying to edit Contacts in Outlook. This is so I can transfer numbers > from my address book which is an Excel spreadsheet to my mobile phone. I > came across the following snippet of code --- hey! that looks familiar :) > which enabled me to the contacts > at least list. I had to root around to discover CdoDefaultFolderContacts > (though it was guessable; how could I enumerate win32com.client.constants?). Well that bit's easy: win32com.client.constants is a small class with a __dicts__ attribute (note the "s") which is a list of dictionaries, one per generated library. So you can do something like this: import win32com.client outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") outlook_constants = win32com.client.constants.__dicts__[0] for k, v in outlook_constants.items (): print k, "=>", v > I now want to work through the Contacts in Outlook patching in data from my > spreadsheet, and also making new contacts where there is an entry in my > spreadsheet which has not gone into Contacts already. OK. > Where can I find the API? I recommend: http://msdn.microsoft.com/en-us/library/ms526861.aspx and http://www.outlookcode.com/article.aspx?id=20 and http://www.cdolive.com/cdo10.htm TJG From deets at nospam.web.de Thu Jul 17 07:31:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 17 Jul 2008 13:31:13 +0200 Subject: Good HTML Parser References: Message-ID: <6e8otlF5k4pgU1@mid.uni-berlin.de> Chris wrote: > Can anyone recommend a good HTML/XHTML parser, similar to > HTMLParser.HTMLParser or htmllib.HTMLParser, but able to intelligently > know that certain tags, like
, are implicitly closed? I need to > iterate through the entire DOM, building up a DOM path, but the stdlib > parsers aren't calling handle_endtag() for any implicitly closed tags. > I looked at BeautifulSoup, but it only seems to work by first parsing > the entire document, then allowing you to query the document > afterwards. I need something like a SAX parser. This isn't possible. Your own example of arbitrarily closeable Tags needs context that just a SAX-like parser can't provide. I suggest you use BeautifulSoup, and if you must create your own event-generation around that which you can attach consumers to. Diez From bignose+hates-spam at benfinney.id.au Thu Jul 10 23:30:06 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 11 Jul 2008 13:30:06 +1000 Subject: paypal wholesale men jordans 17 (paypal accept)(www super-saler com References: <5d746374-d2a0-411e-bf60-87256a219b7c@m44g2000hsc.googlegroups.com> Message-ID: <87skuhqerl.fsf@benfinney.id.au> WDC writes: > On Jul 10, 10:33?pm, 128 wrote: [?] > > Is that spam i spy? It is, clearly. Please don't make the problem worse by repeating the entire thing. -- \ ?I got fired from my job the other day. They said my | `\ personality was weird. ? That's okay, I have four more.? | _o__) ?Bug-Eyed Earl, _Red Meat_ | Ben Finney From bj_666 at gmx.net Mon Jul 7 11:12:30 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Jul 2008 15:12:30 GMT Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: <6deq2uF21vo2U1@mid.uni-berlin.de> On Mon, 07 Jul 2008 16:44:22 +0200, Sebastian \"lunar\" Wiesner wrote: > Mark Wooding : > >> Sebastian "lunar" Wiesner wrote: >> >>> # perl -e '("a" x 100000) =~ /^(ab?)*$/;' >>> zsh: segmentation fault perl -e '("a" x 100000) =~ /^(ab?)*$/;' >> >> (Did you really run that as root?) > > How come, that you think so? The '#' is usually the prompt of root accounts while ordinary users get a '$'. Ciao, Marc 'BlackJack' Rintsch From sunp1028 at gmail.com Mon Jul 14 22:22:01 2008 From: sunp1028 at gmail.com (patrol) Date: Mon, 14 Jul 2008 19:22:01 -0700 (PDT) Subject: About wmi References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> Message-ID: Situation (1): result = new_process.terminate() TypeError: 'int' object is not callable Situation (2): result = new_process.terminate() File "C:\Python25\lib\wmi.py", line 494, in __getattr__ handle_com_error (error_info) File "C:\Python25\lib\wmi.py", line 190, in handle_com_error raise x_wmi, "\n".join (exception_string) UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 14: ordinal not in range(128) BTW, My windows' languange is Chinese. From torainLight at gmail.com Sun Jul 13 08:35:01 2008 From: torainLight at gmail.com (satoru) Date: Sun, 13 Jul 2008 05:35:01 -0700 (PDT) Subject: why is "self" used in OO-Python? References: Message-ID: <9c766948-5d96-44ac-b0d9-9e99b702359c@z66g2000hsc.googlegroups.com> On Jul 13, 12:32?am, ssecorp wrote: > I first learned about OO from Java. > > I much prefer to program in Python though. > > However I am consufed about 2 things. > > 1. Why do I have to pass self into every method in a class? Since I am > always doing why cant this be automated or abstracted away? > Are the instances where I won't pass self? > I imagine there is some tradeoff involved otherwise it would have been > done away with. > > 2. self.item instead of getters and setters. I thought one of the main > purposes of OO was encapsulation. Doesn't messing with internal object- > representations break this? > I see how the getters and setters could be just visual clutter and you > have to add them to every class so it is annoying a bit in the same > way as self described above. > However I feel like I want getters and setters when I write classes, > not sure of the advantages/disadvantages though. > Only looking at the documentation of a Python-class, will internal > representations be provided? > > If I have a class: > > class Stack(object): > ? ? def __init__(self, *items): > ? ? ? ? self.stack = list(items) > > ? ? def append(self, item): > ? ? ? ? self.stack.append(item) > > ? ? def pop(self): > ? ? ? ? return self.stack.pop() > > I can get to see the stack with var.stack but then why even implement > append when I could do self.stack.append(x) etc. > That way you could do away with OO completely. So why let people > access the main attribute but not let them manipulate it? > Makes more sense to draw the line to not access any attributes at all > no? i think the following article may be helpful to you. "Introduction to OOP with Python" http://www.voidspace.org.uk/python/articles/OOP.shtml#id34 From fredrik at pythonware.com Wed Jul 23 03:47:10 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 09:47:10 +0200 Subject: mean of arobase in python In-Reply-To: <7c49f36f0807230033k40722abfwdb28c34d3d88a32a@mail.gmail.com> References: <7c49f36f0807230033k40722abfwdb28c34d3d88a32a@mail.gmail.com> Message-ID: Guilhem Faure wrote: > What means @ in python ? usually called "at sign" in english. > In this script for exemple (this script return an error in my konsole...) > > @f1(arg) > @f2 > def func(): pass > > I see several script where used this symbol but I can't understand. in your example, "f1(arg)" and "f2" are decorators. the above is equivalent to writing def func(): pass func = f1(arg)(f2(func)) that is, define a function, and then pass it to the function "f2", and then to the function that's returned by calling "f1(arg)". the final value of the "func" variable is whatever the decorators returned. the decorator functions (f2 and whatever f1(arg) returns) can manipulate the function being defined, or even replace it with something else. specification: http://www.python.org/dev/peps/pep-0318/ some (semi-advanced) articles: http://www.ibm.com/developerworks/linux/library/l-cpdecor.html http://www.phyast.pitt.edu/~micheles/python/documentation.html From tjreedy at udel.edu Fri Jul 18 17:57:13 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Jul 2008 17:57:13 -0400 Subject: Core Dump - Segmentation Fault -Newbie In-Reply-To: <8ba4373d-3d97-4e9a-a15e-723f6818c757@k36g2000pri.googlegroups.com> References: <8ba4373d-3d97-4e9a-a15e-723f6818c757@k36g2000pri.googlegroups.com> Message-ID: johnericaturnbull at yahoo.com wrote: > Hi - I am very new to python. I get this random core dump and am > looking for a good way to catch the error. I know the function my core > dump occurs. Is there any error catching/handling that I could use in > python? When posting such questions, please supply Python version, system info, and usually code. If you wrote a function in Python that seg faulted, congratulations, its hard (but not impossible) to do ;-). Post it. If you (or someone else) wrote a C function that seg faulted while calling the Python api, well that is much easier. Post it or bug the author. If you (or someone else) wrote a C function that seg faulted in normal C code, well that's easy. Most likely a bad pointer. tjr From bearophileHUGS at lycos.com Wed Jul 30 12:32:25 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 30 Jul 2008 09:32:25 -0700 (PDT) Subject: Non Continuous Subsequences Message-ID: This post is not about practical stuff, so if you have little time, you may ignore it. This is a task of the rosettacode.org site: http://www.rosettacode.org/wiki/Non_Continuous_Subsequences A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subsequence. The task is to enumerate all non-continuous subsequences for a given sequence. Translating the Scheme code to Python was easy (and I think this is quite more readable than the Scheme version): def ncsub(seq, s=0): if seq: x = seq[:1] xs = seq[1:] p2 = s % 2 p1 = not p2 return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2) else: return [[]] if s >= 3 else [] Output: >>> ncsub(range(1, 4)) [[1, 3]] >>> ncsub(range(1, 5)) [[1, 2, 4], [1, 3, 4], [1, 3], [1, 4], [2, 4]] >>> ncsub(range(1, 6)) [[1, 2, 3, 5], [1, 2, 4, 5], [1, 2, 4], [1, 2, 5], [1, 3, 4, 5], [1, 3, 4], [1, 3, 5], [1, 3], [1, 4, 5], [1, 4], [1, 5], [2, 3, 5], [2, 4, 5], [2, 4], [2, 5], [3, 5]] To test its speed I use this: from sys import argv def ncsub(seq, s=0): if seq: x = seq[:1] xs = seq[1:] p2 = s % 2 p1 = not p2 return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2) else: return [[]] if s >= 3 else [] import psyco; psyco.bind(ncsub) print len( ncsub(range(1, int(argv[1]))) ) On a 2 GHz CPU it needs 6.4s with n=20 (the output contains 524_097 sublists!), and 7.8s without Psyco, so I think the speed isn't bad. With the libs I have written for D, translating the Python code is not difficult (with n=20 it runs in 3.72s with the last DMD compiler): import d.all; T[][] ncsub(T)(T[] seq, int s=0) { if (seq.length) { T[] xs = seq[1..$]; int p2 = s % 2; int p1 = !p2; return map((T[] ys){return seq[0]~ys;}, ncsub(xs, s+p1)) ~ ncsub(xs, s+p2); } else return s >= 3 ? [DA!(T)] : null; } void main() { foreach (m; xrange(4, 7)) putr(ncsub(range(1, m))); } But with normal D the program is short enough anyway (but a slower to run (4.7s with n=20) and faster to compile, about 0.1s with full optimizations and about 0.07s without): import std.stdio: writefln; T[][] ncsub(T)(T[] seq, int s=0) { if (seq.length) { T[][] aux; foreach (ys; ncsub(seq[1..$], s + !(s % 2))) aux ~= seq[0] ~ ys; return aux ~ ncsub(seq[1..$], s + s % 2); } else return s >= 3 ? [new T[0]] : null; } void main() { writefln(ncsub([1, 2, 3])); writefln(ncsub([1, 2, 3, 4])); writefln(ncsub([1, 2, 3, 4, 5])); } The Scheme version is eager, it comes from the first Haskell version, that I think is lazy. In Python the management of lazy iterables feels almost bolted-on compared to Haskell, for example in Haskell lazy iterables don't exhaust like in Python (because they are immutable), and while you create a lazy list you can refer to the items already created. But in many cases you can create a lazy code in Python too, even if that may be harder. So I have tried to create a lazy version for Python, hoping to speed up the code avoiding the creation and joining of most/all sublists, but I have failed so far (once I have created a lazy Python version, I can probably create a short lazy version in D too, my D libs contain most of itertools module too). In my failed attempts I have used chain() to join the sublists, islice() to slice their items, and iter() to make the management more uniform when the input seq is a Python list instead of an xrange, etc. The: if seq: can be replaced by something like: try: x = seq2.next() except StopIteration: ... else: ... If you have some time to waste you may suggest me how to write a lazy version in Python :-) Bye, bearophile From israelu at elbit.co.il Tue Jul 29 02:49:55 2008 From: israelu at elbit.co.il (iu2) Date: Mon, 28 Jul 2008 23:49:55 -0700 (PDT) Subject: seemingly simple list indexing problem References: <1ad9234a-6bba-48ce-ad40-ea0aeabce492@79g2000hsk.googlegroups.com> Message-ID: On Jul 29, 2:26?am, John Krukoff wrote: > On Mon, 2008-07-28 at 16:00 -0700, iu2 wrote: > > On Jul 29, 12:10 am, John Krukoff wrote: > > > On Mon, 2008-07-28 at 16:24 -0500, Ervan Ensis wrote: > > > > My programming skills are pretty rusty and I'm just learning Python so > > > > this problem is giving me trouble. > > > > > I have a list like [108, 58, 68]. ?I want to return the sorted indices > > > > of these items in the same order as the original list. ?So I should > > > > return [2, 0, 1] > > > > > For a list that's already in order, I'll just return the indices, i.e. > > > > [56, 66, 76] should return [0, 1, 2] > > > > > Any help would be appreciated. > > > > > -- > > > >http://mail.python.org/mailman/listinfo/python-list > > > > If your lists aren't so large that memory is an issue, this might be a > > > good place for a variation of decorate, sort, undecorate. > > > > >>> listToSort = [ 108, 58, 68 ] > > > >>> decorated = [ ( data, index ) for index, data in > > > > enumerate( listToSort ) ]>>> decorated > > > > [(108, 0), (58, 1), (68, 2)]>>> result = [ None, ] * len( listToSort ) > > > >>> for sortedIndex, ( ignoredValue, originalIndex ) in > > > > enumerate( sorted( decorated ) ): > > > ... ? ? result[ originalIndex ] = sortedIndex > > > ...>>> result > > > > [2, 0, 1] > > > > -- > > > John Krukoff > > > Land Title Guarantee Company > > > Inspired by your idea and the above one, here is another try: > > > >>> a0 = [108, 58, 68, 108, 58] > > >>> a1 = [(x, y) for x, y in enumerate(a0)] > > You know this line is a no-op, right? > > > >>> a1 > > [(0, 108), (1, 58), (2, 68), (3, 108), (4, 58)] > > >>> a2 = sorted(a1, lambda x, y: cmp(x[1], y[1])) > > If you're going to do the unpacking here for the sort, just use > enumerate directly. Since this is a simple case, should use the key > parameter instead of the cmp parameter for speed. Can also use the > operator module to avoid a bit of lambda overhead: > > >>> import operator > >>> a2 = sorted( enumerate( a0 ), key = operator.itemgetter( 1 ) ) > > >>> a2 > > [(1, 58), (4, 58), (2, 68), (0, 108), (3, 108)] > > >>> a3 = [a2.index(x) for x in a1] > > >>> a3 > > [3, 0, 2, 4, 1] > > > The idea is to make each item unique (by making it a tuple), and then > > apply the naive solution. > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Using index is still kinda evil, due to the exponential time required > since you're rescanning half the list (on average) to find each index > value. > > -- > John Krukoff > Land Title Guarantee Company- Hide quoted text - > > - Show quoted text - Well, a dictionary can replace the index search helper_dict = dict(zip(a2, xrange(len(a2)))) >>> helper_dict {(1, 58): 0, (4, 58): 1, (3, 108): 4, (2, 68): 2, (0, 108): 3} a3 = [helper_dict[x] for x in a1] >>> a3 [3, 0, 2, 4, 1] The performance now should be n*log(n) From p0q0b0d at gmail.com Wed Jul 9 08:52:18 2008 From: p0q0b0d at gmail.com (|e0) Date: Wed, 9 Jul 2008 14:52:18 +0200 Subject: Newbie question In-Reply-To: References: <3b1e6f480807082337l419fd40ax91eaf13e0701c5b3@mail.gmail.com> Message-ID: <3b1e6f480807090552m51be62a9tbb76085504e5d4e3@mail.gmail.com> I did not mean to use WMI on linux, but query win machines *from* linux. Thank you for your clarifications - Leonardo On Wed, Jul 9, 2008 at 11:04 AM, A.T.Hofkamp wrote: > Welcome to the world outside MS. > > Many python modules don't actually do anything than passing on calls to an > existing underlying library. They are cheap to make, and make it possible to > use the functionality of the library from a Python program. The down-side is, > as you have discovered, that you need the underlying library to make it work. > > So, the answer is no, you cannot use wmi under a non-MS OS. (But what did you > expect, given that wmi means WINDOWS Management Instrumentation?) No doubt > there are also open source variants of this package, however, I am not familiar > with them, so I cannot help you. > > > Albert From timr at probo.com Thu Jul 31 02:17:59 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 31 Jul 2008 06:17:59 GMT Subject: interpreter vs. compiled References: <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> Message-ID: <4rl294duo83eujnq6tjbk215mavpl87o9r@4ax.com> castironpi wrote: > >In C, we have: > >int x, y; >x= 10; >y= x+ 1; > >It translates as, roughly: >> >8000 .data >7996 ffffffff #x >7992 ffffffff #y >7988 .end data >7984 loadi reg0 7996 >7980 loadi reg1 7992 >7976 loadi reg2 10 >7972 loadi reg3 1 >7968 storv reg2 reg0 >7964 add reg0 reg1 reg2 >7960 storv reg3 reg1 I don't recognize that assembly language. Is that another intermediate language? >You are telling me that the same thing happens in IronPython. Yes, the same process happens. >By the >time the instruction pointer gets to 'x= 10', the next 7 instructions >are the ones shown here compiled from C. I most certainly did NOT say that, as you well know. Different C compilers produce different instruction sequences for a given chunk of code. Indeed, a single C compiler will produce different instruction sequences based on the different command-line options. It's unreasonable to expect a Python compiler to produce exactly the same code as a C compiler. However, that does disqualify the Python processor as a "compiler". >CMIIW, but the CPython implementation -does- -not-. And again, I never said that it did. CPython is an interpreter. the user's code is never translated into machine language. >My point is, CPython takes more than seven steps. My question is, >does IronPython? So, if compiler B isn't as good at optimization as compiler A, does that mean in your mind that compiler B is not a "compiler"? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From torriem at gmail.com Mon Jul 21 00:50:40 2008 From: torriem at gmail.com (Michael Torrie) Date: Sun, 20 Jul 2008 22:50:40 -0600 Subject: Python Written in C? In-Reply-To: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> References: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> Message-ID: <488415A0.10107@gmail.com> Mensanator wrote: > On Jul 20, 7:37?pm, Roy Smith wrote: >> In article >> , >> >> ?Mensanator wrote: >>> C isn't a high level language, that's part of its problem. >> C is the highest level assembler language > > Isn't that like bragging about being the smartest > kid on the short bus? > >> I've ever used. ?And I've used a >> few. ?It really is cool that you can add two 32-bit integers and not have >> to worry about all those carry bits. > > Carry bits? Who worries about carry bits when you have > unlimited precision arithmetic? You want cool? Perhaps you missed the wonderful humor in Roy's post. It was rather brilliant. Sorry you missed it. From paul.hankin at gmail.com Wed Jul 23 05:11:17 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 23 Jul 2008 02:11:17 -0700 (PDT) Subject: Is this possible .... References: Message-ID: On Jul 23, 9:58?am, Stef Mientki wrote: > hello, > > I'm looking for a way to remove duplicate code. > The problem is this: > In all my modules I've version information, > containing version information, date, author, testconditions etc, > something like this: > > Version_Text = [ > [ 0.2, '10-02-2008', 'Stef Mientki', > 'Test Conditions:', (1,2), > _(0, """ > ? ?- scaling and offset is set for each individual signal > ? ?- Time history window for 1 signal with min/max display > ? ?- set attributes for all signals at once > """) ], > > [ 0.1, '04-11-2007', 'Stef Mientki', > 'Test Conditions:', (1,), > """ > ? ? - orginal release > """ ] > ] > > Now I've made modules that can generate docs, a library manager, etc, > and that even in different languages. > > But for the simple case I would like to have a simple function, which > just displays the version number. > So in each module, there is a function: > > def version () : > ? return ( version_text [0] [0] ) > > But is there a way to avoid the placing of this function "version" in > each module, > and still use a simple call like: > ? .version() You could use version() instead of module.version(), and just declare 'version' in one place. Presumably you already have a module for getting the metadata out of one of your modules; perhaps it could go in there? def version(module): return getattr(module, 'Version_Text')[0][0] -- Paul Hankin From bignose+hates-spam at benfinney.id.au Tue Jul 29 19:14:56 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 30 Jul 2008 09:14:56 +1000 Subject: DB access without object-relation mapping? References: Message-ID: <87tze8ffkf.fsf@benfinney.id.au> kj writes: > The word on the street is to use something like SQLAlchemy for > database access in Python, but my experience in the past with > packages that perform automated SQL generation has been awful, so I > always return to lighter-weight solutions that allow me to write my > own SQL. Using SQLAlchemy, you *can* write your own SQL (with its 'text' query type to feed explicit SQL text on the connection); you just don't *need* to for the majority of simple and not-so-simple cases. I've been using SQLAlchemy for some time and have found its combination of "make the simple cases simple" and "allow full control when needed" to be close to ideal. I can use exactly the same interface to leverage the SQL generation for mundane tasks and to craft custom weird SQL that I need. Combine that with active, level-headed maintenance, and comprehensive documentation, and I don't even need to consider using the ORM layer :-) -- \ ?Know what I hate most? Rhetorical questions.? ?Henry N. Camp | `\ | _o__) | Ben Finney From rparimi at gmail.com Wed Jul 9 19:32:28 2008 From: rparimi at gmail.com (rparimi at gmail.com) Date: Wed, 9 Jul 2008 16:32:28 -0700 (PDT) Subject: redirecting output of process to a file using subprocess.Popen() Message-ID: <515ad1dd-15b0-4f7a-8ea2-87e0bb0cb47e@f36g2000hsa.googlegroups.com> I am trying to redirect stderr of a process to a temporary file and then read back the contents of the file, all in the same python script. As a simple exercise, I launched /bin/ls but this doesn't work: #!/usr/bin/python import subprocess as proc import tempfile name = tempfile.NamedTemporaryFile(mode='w+b') print 'name is '+ name.name cmd = [] cmd.append('/bin/ls') cmd.append('-l') cmd.append('/tmp') p = proc.Popen(cmd, stdout=name, stderr=proc.STDOUT, close_fds=True) while True: ret = p.poll() if (ret is not None): output = name.readlines() print 'out = ', output break $python sub.py name is /tmp/tmpjz4NJY out = [] I tried calling flush() on the file object but this didn't help either. Tried closing and re-opening the file, but closing the file object results in it getting deleted. Can the above be made to work by using tempfiles? thanks From fredrik at pythonware.com Mon Jul 21 10:10:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 16:10:35 +0200 Subject: Odd math related issue. In-Reply-To: <6472d2d2-1f0e-44af-8bdb-b7e475080e26@v28g2000pro.googlegroups.com> References: <43332.3139710867$1216630189@news.gmane.org> <48847F5D.9080509@sellerengine.com> <6472d2d2-1f0e-44af-8bdb-b7e475080e26@v28g2000pro.googlegroups.com> Message-ID: sahasranaman wrote: > Use 2.0 / 3 * 100 to solve this. Why make things look bigger? you mean that a.0 / 3 * 100 works in your Python version? that's interesting. (maybe you should at least skim the the thread before you jump in?) From mathieu.prevot at gmail.com Sun Jul 6 14:05:56 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Sun, 6 Jul 2008 20:05:56 +0200 Subject: Problem with subprocess.Popen wget within a thread Message-ID: <3e473cc60807061105n6cdd67ffw5044b8abe7a0725a@mail.gmail.com> Hi it seems the script (A) finishes before the downloading ends, and the (B) version doesn't (wanted behavior) ... this is unexpected. What happens ? (A) ============================================ class vid(threading.Thread): def __init__(self): threading.Thread.__init__(self) def download(self): self.cmd = 'wget ftp://ftp.freebsd.org/pub/FreeBSD/releases/i386/ISO-IMAGES/7.0/7.0-RELEASE-i386-bootonly.iso' self.child = subprocess.Popen(self.cmd.split()) def run(self): self.download() def main(): w = vid() w.start() w.join() (B) ============================================ class vid(threading.Thread): def __init__(self): threading.Thread.__init__(self) def download(self): self.cmd = 'wget ftp://ftp.freebsd.org/pub/FreeBSD/releases/i386/ISO-IMAGES/7.0/7.0-RELEASE-i386-bootonly.iso' self.child = subprocess.Popen(self.cmd.split(), stderr=subprocess.PIPE) def run(self): self.download() self.child.stderr.readlines() def main(): w = vid() w.start() w.join() ============================================ From jayjaygibbs at hotmail.co.uk Sun Jul 6 22:33:27 2008 From: jayjaygibbs at hotmail.co.uk (jayjaygibbs at hotmail.co.uk) Date: Sun, 6 Jul 2008 19:33:27 -0700 (PDT) Subject: GUI Programming by hand not code with Python Code Message-ID: <7003b665-3227-47a7-ab06-1a486f87939a@a1g2000hsb.googlegroups.com> Is their a program that lets you design a GUI by hand (like gambas) not by code (like wxpython) but the commands are in python? A program similar to gambas or vb Gambas with python code instead of gambas code would be perfect. Thanks in advance From david.lyon at preisshare.net Sat Jul 19 08:37:15 2008 From: david.lyon at preisshare.net (David Lyon) Date: Sat, 19 Jul 2008 22:37:15 +1000 Subject: Help with displaying images in CherryPy Message-ID: <4881DFFB.5060306@preisshare.net> Hi all, I have a very simple question about configuration under CherryPy - it is such a simple one but I have been struggling to find an answer for a few days. All I want is a sample configuration file that will allow me to display a page with a jpeg on it. Whilst there are some examples in the CherryPy examples, they are mixed with so many other concepts that it is difficult for me (a newbie) to figure it out. None actually show me where to put image files. This really should only take a few minutes for somebody who has done this in CherryPy before and I would certainly appreciate the assistance because it doesn't seem covered in any documentation that i could find. Regards David From gh at ghaering.de Wed Jul 23 04:19:24 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 23 Jul 2008 10:19:24 +0200 Subject: How do I compare files? In-Reply-To: <1216769247.18962.7.camel@generator> References: <1216769247.18962.7.camel@generator> Message-ID: Clay Hobbs wrote: > I am making a program that (with urllib) that downloads two jpeg files > and, if they are different, displays the new one. I need to find a way > to compare two files in Python. How is this done? There's a module in the standard library called filecmp ;-) -- Gerhard From fredrik at pythonware.com Thu Jul 24 06:13:01 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 12:13:01 +0200 Subject: instance comparison In-Reply-To: References: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> Message-ID: King wrote: > The only methods I do have in class is __init__ and __str__. > How ever inst1 and inst2 is coming from a dictionary where I stored > them with a unique id. > > inst1 = stored[id] > inst2 = stored[id] > > Is this makes a difference? unlikely (well, if that's the literal code, both variables will point to the same variable, but I guess that's not what you meant). > I will rip down the piece of code giving me problem and post. please do. and don't be surprised if you find the problem while doing so ;-) From socyl at 987jk.com.invalid Tue Jul 29 17:13:36 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 21:13:36 +0000 (UTC) Subject: Where is the documentation for psycopg2? References: Message-ID: In Matthew Woodcraft writes: >kj wrote: >> Hi. I can't find any documentation for psycopg2. >> >> I'm a noob, so I'm sure I'm just not looking in the right place... >> >> Anybody know where it is? >For basic use, psycopg2 follows the dbapi, which is described in >http://www.python.org/dev/peps/pep-0249/ >Additional features are described in doc/extensions.rst in the psycopg2 >tarball. >This leaves a gap for documentation of the basic features which the >dbapi doesn't nail down (in particular, connecting to a database in the >first place). I don't think there is any proper documentation covering >this, but the scripts in examples/ (particularly simple.py) should make >it reasonably clear. That's very helpful. I would have never found it on my own. Thanks! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From gros_bedo at hotmail.com Wed Jul 9 19:07:03 2008 From: gros_bedo at hotmail.com (Gros Bedo) Date: Thu, 10 Jul 2008 01:07:03 +0200 Subject: Freesoftware for auto/intelligent code completing in Python Message-ID: Hello, Ali I totally support you, neither I couldn't find any really working code completion for python in a free software, and it's really a mess, at least on Linux. On Windows, there is PyScripter (http://pyscripter.googlepages.com/), but it is based on Delphi, and as such it's not portable. But it's a free software (even if I couldn't find the sources, they say you can download them). It is said to be working on Linux via Wine, so if you really need a code completion tool you could give it a try. _________________________________________________________________ T?l?chargez gratuitement des ?motic?nes pour pimenter vos conversations Messenger http://specials.fr.msn.com/femmes/amour/emoticonesLove.aspx From marcus at internetnowasp.net Sat Jul 12 22:14:15 2008 From: marcus at internetnowasp.net (Marcus Low) Date: Sun, 13 Jul 2008 10:14:15 +0800 Subject: Someone enlightened me In-Reply-To: <4879645F.3070504@internetnowasp.net> References: <4879645F.3070504@internetnowasp.net> Message-ID: <487964F7.8000908@internetnowasp.net> Duh, Ok here is the file again ...attached. I give up doing this via the email editor. Sorry! new to the mailing list. Marcus Marcus Low wrote: > Opps here is the mail again, incase my formatting is lost, can someone > explain to me why this code behaves differently when "lister" and > "self.lister" is swap remarked. > > > class abc : > # remark this later and unremark "self.lister" > lister = [] > def __init__ (self, val): > #self.lister = [] > self.lister.append(val) > globallist = [] > > def test () : > > global l > for x in range(10) : > o = abc(x) globallist.append(o) o > = "" > for i in globallist : > print i.lister > test() > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: k.txt URL: From cokofreedom at gmail.com Wed Jul 9 07:08:30 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 9 Jul 2008 04:08:30 -0700 (PDT) Subject: Impossible to change methods with special names of instances of new-style classes? References: Message-ID: > > My question is: did something about the way the special method names are > implemented change for new-style classes? > >>> class old: pass >>> class new(object): pass >>> testone = old() >>> testone.__call__ = lambda : 33 >>> testone() 33 >>> testtwo = new() >>> testtwo.__call__ = lambda : 33 >>> testtwo() Traceback (most recent call last): File "", line 1, in testtwo() TypeError: 'new' object is not callable >>> old.__call__ Traceback (most recent call last): File "", line 1, in old.__call__ AttributeError: class old has no attribute '__call__' >>> new.__call__ >>> testone.__call__ at 0x00C35EB0> >>> testtwo.__call__ at 0x00C35B70> >>> dir(testtwo) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] >>> dir(testone) ['__call__', '__doc__', '__module__'] >>> dir(new) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] >>> dir(old) ['__doc__', '__module__'] I don't see __call__ in either class structures, but for new style classes it is a wrapper and for old it is nothing. Not sure if that helps, but this is rather over my head. From greg at cosc.canterbury.ac.nz Tue Jul 29 00:32:51 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 29 Jul 2008 16:32:51 +1200 Subject: with statement for two files In-Reply-To: <6f6cfdFa22kkU1@mid.uni-berlin.de> References: <08d72316-15f1-45dd-b1f7-7b8ee06efef5@e39g2000hsf.googlegroups.com> <7xsktuvusj.fsf@ruckus.brouhaha.com> <6f6cfdFa22kkU1@mid.uni-berlin.de> Message-ID: <6f7l86Fa9d5lU2@mid.individual.net> Diez B. Roggisch wrote: > Paul Rubin wrote: > > > use contextlib.nexted(). > > You mean contextlib.nested I guess. Although "nexted" is an intriguing-sounding word. I wonder what it could mean? -- Greg From fuzzyman at gmail.com Thu Jul 3 13:38:31 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 3 Jul 2008 10:38:31 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: <998a4731-c6db-4f46-be6b-775fd7af4a18@m44g2000hsc.googlegroups.com> <9ad840e1-e12f-4125-8537-4bad2ef77f51@w5g2000prd.googlegroups.com> Message-ID: <6b1e8a6c-4d21-488d-a8b9-74388f1f5c43@m45g2000hsb.googlegroups.com> On Jul 2, 9:33?am, Ali Servet D?nmez wrote: > On Jul 1, 12:15?am, Fuzzyman wrote: > > > > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > I don't want to be so mean here, but how hard it could be be writing a > > > freesoftware which would automatically/intelligently auto complete > > > Python code? (I mean something that really does the job, like > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > name it, but just don't give me PyDev please...) > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > missing here? > > > > Could someone please point me out something that I'm really missing > > > which is already present in the wild, otherwise I'd like discuss with > > > whoever is willing to help me to get this thing done. I made my mind > > > and I could volunteer to make this happen as thesis project for my > > > incoming graduation in the next year. > > > > Regards you all, > > > Ali Servet D?nmez > > > Vim, Emacs, Wing, Komodo, ... more? > > > Yeah, I guess you're missing something. :-) > > > MichaelFoordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > I've checkout Wing IDE's license and it doesnt' seem to be a > freesoftware; am I wrong? Wing 101 is free. The software is good enough though that it is worth supporting its development by paying for it. Michael Foord -- http://www.ironpythoninaction.com/ http://www.trypython.org/ From three3q at arcor.de Mon Jul 7 18:59:49 2008 From: three3q at arcor.de (three3q) Date: Tue, 08 Jul 2008 00:59:49 +0200 Subject: sage vs enthought for sci computing In-Reply-To: References: <677e7819-e09e-43d3-8368-5864f91002be@34g2000hsh.googlegroups.com> Message-ID: <48729fe9$0$7550$9b4e6d93@newsspool1.arcor-online.net> Hi, >> If my goal >> is to replace matlab (we do signal processing and stats on >> physiological data, with a lot of visualization), would sage or >> enthought get me going quicker? Pylab. > At the moment I switched totally to Python, Me too, porting scripts was easy. Dan From alexnbryan at gmail.com Thu Jul 17 01:35:29 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 16 Jul 2008 22:35:29 -0700 (PDT) Subject: Need help getting BeautifulSoup contents Message-ID: <18501881.post@talk.nabble.com> The trick to this one is that the html looks something like this:
american, /browse/blue blue , /browse/brick brick , brie, cheddar, cheshire, /browse/churn churn , /browse/cottage cottage , /browse/cream cream , dunlop, and it goes on . I know I can do like a.contents, but it only gives me the first one, in this case being "blue". I want the contents of each of those and the regular contents of the . Can anyone help? -- View this message in context: http://www.nabble.com/Need-help-getting-BeautifulSoup-contents-tp18501881p18501881.html Sent from the Python - python-list mailing list archive at Nabble.com. From fredrik at pythonware.com Mon Jul 21 08:30:44 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 14:30:44 +0200 Subject: Odd math related issue. In-Reply-To: <48847F5D.9080509@sellerengine.com> References: <43332.3139710867$1216630189@news.gmane.org> <48847F5D.9080509@sellerengine.com> Message-ID: Alexandru Palade wrote: > However, you should be carefully because using an %i modifier for a > what-should-be a float value truncates the value in a way you may not > expect. > > What I mean is that if you have sent 2 out of 3 bytes, the math will be > 200/3 which with the %i modifier will print 66, rather than 66.6 (or at > least 67 which is closer - have a look at the round() function). My suggested workaround doesn't use floats. As for rounding, that's more of a usability issue -- seeing the download process getting stuck at 100% can be rather frustrating for the poor user. Better truncate towards zero. > Another thing, you could have just added a dot after the constant in > order to promote the expression to be evaluated as float. As in > percentage = bytes_transferred / /self/.__sessions[path].total_bytes > * 100. > (notice the last dot) Did you try that? >>> 2 / 3 * 100. 0.0 You can fix this with parentheses, but I usually recommend an explicit "cast" instead, to make it obvious what you're doing: result = float(a) / b From duncan.booth at invalid.invalid Sat Jul 19 10:01:59 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Jul 2008 14:01:59 GMT Subject: __del__ methods References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> Message-ID: "Robert Rawlins" wrote: > I've just recently (in the past week) started using the __del__ method > to log class instance destruction so I can keep a track of when > objects are created and destroyed, in order to help me trace and fix > memory leaks. That sounds like an appropriate use for __del__: it won't matter that it may not be called when your app exits. > > Are you saying that on the adverse side to this, __del__ may in fact > be the CAUSE of a memory leak within my application? Yes, but there is an easy work-around. If you want to track destruction of objects of type C then don't add a __del__ method to the C objects. Instead create a separate class which does nothing but track it's own desctruction and reference that from the class which may be leaking. >>> class Track(object): def __init__(self, parent): self.parentid = id(parent) self.parenttype = type(parent).__name__ def __del__(self): print "Destroyed <%s object at %s>" % (self.parenttype, self.parentid) >>> class C(object): def __init__(self): self._track = Track(self) >>> a = C() >>> b = C() >>> a.b = b >>> b.a = a >>> del a >>> del b >>> gc.collect() Destroyed Destroyed 19 > If this is the case and __del__ creates such a vulnerability within > the application, and apparently isn't all that reliable anyway, why is > it still part of the python platform? > Because it does have a very few cases where it is useful. Tracking memory leaks may be one. However you should also consider that __del__ only lets you log when objects are destroyed. Using weak references may be a more useful option as it will let you track which objects are not being destroyed: you can easily keep a dictionary of weak references to all existing objects of interest. Check its length periodically to see whether objects are being leaked and then inspect the objects themselves to see which ones have leaked. You can use gc.get_referrers() to find everything that references a particular objects and gradually trace backwards until you find the problem reference (it is tricky though as any code which does this needs to ignore its own references to the object in question). From fredrik at pythonware.com Thu Jul 24 04:13:27 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 10:13:27 +0200 Subject: parameterized classes In-Reply-To: References: Message-ID: John Tantalo wrote: > Is there is a better way to create parameterized classes than defining > and returning a class in a closure? I ask because I want to create > arbitrary BaseRequestHandler subclasses that delegate line handling to a > given line handler, as in this example: Oh, now I get it. Maybe. Wouldn't it be easier to just use subclassing for parametrization: class LineRequestHandler(StreamRequestHandler): ... self.handle_line(line) ... class SomeLineHandler(LineRequestHandler): def handle_line(self, line): print "I got a line: %s" % line Alternatively, note that the SocketServer framework doesn't require the request handler baseclass to actually be a class; it works with any factory object that takes the same three arguments and returns an handler instance. You can use a plain function closure as a factory, if you prefer that. From ojeeves at gmail.com Thu Jul 31 07:29:45 2008 From: ojeeves at gmail.com (oj) Date: Thu, 31 Jul 2008 04:29:45 -0700 (PDT) Subject: Difference between type and class References: <87myjy2vc6.fsf@nokile.rath.org> Message-ID: <12072cbe-139a-430f-81aa-b64bc31b43e5@e39g2000hsf.googlegroups.com> On Jul 31, 11:37?am, Nikolaus Rath wrote: > So why does Python distinguish between e.g. the type 'int' and the > class 'myclass'? Why can't I say that 'int' is a class and 'myclass' > is a type? I might be wrong here, but I think the point is that there is no distinction. A class (lets call it SomeClass for this example) is an object of type 'type', and an instance of a class is an object of type 'SomeClass'. So int is a type, but if you have an int variable, its type is int. Same for your classes. This is, ignoring old style classes. Make sure all your classes inherit from object to get new style classes. From roy at panix.com Sat Jul 26 21:25:09 2008 From: roy at panix.com (Roy Smith) Date: Sat, 26 Jul 2008 21:25:09 -0400 Subject: Insert string into string References: Message-ID: In article , "Francesco Pietra" wrote: > I am posting ex novo as it became confusing to me. I take the > opportunity to ask advice for a second problem. > > FIRST PROBLEM > For file xxx.pdb, insert letter "A" into each line that starts with > "ATOM". "A" should be inserted at position 22, i.e., one space after > "LEU", leaving all other characters at the same position as in the > original example: > > > ATOM 1 N LEU 1 146.615 40.494 103.776 1.00 73.04 1SG > 2 > > In all lines starting with "ATOM", "LEU" is constant as to position > only (18-20), i.e., "LEU" may be replaced by > three different uppercase letters. Therefore, the most direct > indication would be position 22. If specifying line starting with > "ATOM" makes complication, forget about that as most lines begin with > "ATOM" so that hand correction will be easy. > > Script > f = open("xxx.pdb", "w") > import sys > > for line in sys.stdin: > line = line[:22] + "A" + line[23:] > sys.stdout.write(line) You're opening "xxx.pdb" for writing, but then not writing to it. You're writing to stdout. BTW, you might want to take a look at http://biopython.org. From carsten.haese at gmail.com Tue Jul 1 09:41:28 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Tue, 01 Jul 2008 09:41:28 -0400 Subject: Embedding Python In-Reply-To: References: Message-ID: Marcin Krol wrote: > Hello everyone, > > I'm trying to embed Python interpreter in C code, but in a specific way: > loading compiled bytecode into a memory location and executing it (don't > ask why, complicated reasons). > > PyImport_ExecCodeModule seems like obvious candidate, docs say: > > "Given a module name (possibly of the form package.module) and a code > object read from a Python bytecode file or obtained from the built-in > function compile(), load the module." > [...] > mainobj = PyImport_ExecCodeModule("multiply", (PyObject *) > python_code); > [...] python_code is a C string containing the raw bytes from your pyc file. Casting that to a PyObject pointer will not magically transform it into a Python code object. A pyc file contains the following: 1) An 8 byte header containing a magic number. 2) A "marshal" serialization of the code object. So, in order to transform those contents into a code object, you need to skip the 8 byte header and an unmarshal the rest. Basically, replace the line above with something like this: codeobj = PyMarshal_ReadObjectFromString(python_code+8, size-8); mainobj = PyImport_ExecCodeModule("multiply", codeobj); where codeobj is of type (PyObject *). Once that works, add magic number checking and exception handling to taste. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From circularfunc at gmail.com Sat Jul 12 12:32:12 2008 From: circularfunc at gmail.com (ssecorp) Date: Sat, 12 Jul 2008 09:32:12 -0700 (PDT) Subject: why is "self" used in OO-Python? Message-ID: I first learned about OO from Java. I much prefer to program in Python though. However I am consufed about 2 things. 1. Why do I have to pass self into every method in a class? Since I am always doing why cant this be automated or abstracted away? Are the instances where I won't pass self? I imagine there is some tradeoff involved otherwise it would have been done away with. 2. self.item instead of getters and setters. I thought one of the main purposes of OO was encapsulation. Doesn't messing with internal object- representations break this? I see how the getters and setters could be just visual clutter and you have to add them to every class so it is annoying a bit in the same way as self described above. However I feel like I want getters and setters when I write classes, not sure of the advantages/disadvantages though. Only looking at the documentation of a Python-class, will internal representations be provided? If I have a class: class Stack(object): def __init__(self, *items): self.stack = list(items) def append(self, item): self.stack.append(item) def pop(self): return self.stack.pop() I can get to see the stack with var.stack but then why even implement append when I could do self.stack.append(x) etc. That way you could do away with OO completely. So why let people access the main attribute but not let them manipulate it? Makes more sense to draw the line to not access any attributes at all no? From jordanrastrick at gmail.com Thu Jul 24 11:17:36 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 08:17:36 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <87abg7pe16.fsf@benfinney.id.au> Message-ID: <78446ee7-b035-49a8-ac73-46895391543d@o40g2000prn.googlegroups.com> > > You're not a lunatic. > > We, and Python itself, change quite readily. > > Neither of those mean your ideas in this instance have merit. You're right, these premises don't lead to this conclusion. Neither do they lead to its negation, of course. As it happens, you're wrong on both counts. I do in fact suffer from a mental illness and have spent a week in a psych ward, so am a lunatic by some reasonable definitions. Python readily changes in some regards, but not in others. Of course, a great many things of worth have this as one of their essential qualities. Pithy replies are fun. > Thanks for your opinion. I disagree strongly: I think its influence is > nicely balanced by the other important principles that are also > followed. This isn't just being clever, there's substance here. A clearly stated opposing position, with a decent if somewhat short justification. I think you're right insofar as you go - that if someone really sits down, and thinks clearly about all the Pythonic principles, as a whole, and in detail, then the net result in the shaping their thinking will be positive more often than not. Perhaps we're just looking at an instance of a wider problem - smart people boil good ideas down into short slogans, which are nice and memorable and somewhat helpful, but can lead to bad consequences when lots of others start overusing or misunderstanding them. From bj_666 at gmx.net Tue Jul 1 11:45:23 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Jul 2008 15:45:23 GMT Subject: Error from zipfile References: Message-ID: <6cv1oiF9eaU1@mid.uni-berlin.de> On Tue, 01 Jul 2008 16:38:23 +0100, Wesley Brooks wrote: > Dear Users, > > I'm having a problem when trying to move script from Linux to Windows. > A zipfile opperation is failing with the message: > > "BadZipFile: File is not a zip file" > > I have a simple scripts that reads a zip file in the same way as any > other file into a string, then sends it across to a network where it > is saved as perusual into a file, [?] Are you sure you read and save the file in binary mode, especially on windows!? Ciao, Marc 'BlackJack' Rintsch From amnorvend at gmail.com Fri Jul 18 14:31:20 2008 From: amnorvend at gmail.com (Jason Baker) Date: Fri, 18 Jul 2008 11:31:20 -0700 (PDT) Subject: __del__ methods Message-ID: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> I have a class that I need to do some finalization on when it dies. I know I can use the __del__ method, but I seem to recall that it impedes garbage collection. Is this the case? (keep in mind that my code aims to be compatible with python 2.3 to python 2.5) From motoom at xs4all.nl Tue Jul 15 10:02:11 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Tue, 15 Jul 2008 16:02:11 +0200 Subject: Simplify Code Message-ID: <2.2.32.20080715140211.00d47cb0@pop.xs4all.nl> Victor wrote... ># del is used to determine if should reset the lower header values to '' >del = 0 Apart from many other things that spring to mind, I already see an obvious flaw: 'del' is a keyword, or a 'reserved word' in Python. It is used to remove variables from the namespace. Tip: Use some other name as a variable, eg. 'deletethisone'. Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From deets at nospam.web.de Fri Jul 11 07:59:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 11 Jul 2008 13:59:27 +0200 Subject: MySQLdb will only import for root In-Reply-To: <85d26ae4-757f-494c-bf7e-412323e26b8a@x41g2000hsb.googlegroups.com> References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> <6dothnF3lqqmU1@mid.uni-berlin.de> <85d26ae4-757f-494c-bf7e-412323e26b8a@x41g2000hsb.googlegroups.com> Message-ID: <6dp092F3mhbaU1@mid.uni-berlin.de> Jeff schrieb: > Is it possible the module was installed with priviledges set too > strict? Perhaps the interpreter cannot see the module when it is run > from a normal user account. Possible - certainly. Yet unrealistic, because usually root access is *required* to system-wide install a package - thus the normal install processes ensure proper rights. Diez From kay.schluehr at gmx.net Wed Jul 9 16:53:26 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 9 Jul 2008 13:53:26 -0700 (PDT) Subject: Relative Package Import References: Message-ID: On 8 Jul., 21:09, Peter Otten <__pete... at web.de> wrote: > Robert Hancock wrote: > > mypackage/ > > __init__.py > > push/ > > __init__.py > > dest.py > > feed/ > > __init__py > > subject.py > > > In subject.py I have > > from ..push import dest > > > But i receive the error: > > Caught exception importing module subject: > > File "/usr/local/python/lib/python2.5/site-packages/pychecker/ > > checker.py", line 621, in setupMainCode() > > module = imp.load_module(self.moduleName, file, filename, smt) > > File "subject.py", line 1, in () > > from ..feed import dest > > ValueError: Attempted relative import in non-package > > > What am I missing? > > When you run subject as a file > > pychecker mypackage/feed/subject.py > > subject.py is regarded as a standalone script, not as part of a package. Try > > pychecker mypackage.feed.subject > > instead to invoke the module via the standard import mechanism. > > Peter Since when are Python modules not regarded as standalone scripts but as a "part of a package"? The only indication that there is some duality and that it is relevant at all are those relative imports that came in with Python 2.5. As it seems this feature is justified by the artificial semantic differences it produces. From ericdfirst at gmail.com Thu Jul 24 10:23:33 2008 From: ericdfirst at gmail.com (Eric First) Date: Thu, 24 Jul 2008 09:23:33 -0500 Subject: Wrapping std::set in boost::python Message-ID: <349c44440807240723i56e28823q587e7c0a7e63658d@mail.gmail.com> Has anybody wrapped std::set using boost::python? I'm trying to find the best way to do this. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From animator333 at yahoo.com Wed Jul 16 10:53:13 2008 From: animator333 at yahoo.com (Prashant Saxena) Date: Wed, 16 Jul 2008 07:53:13 -0700 (PDT) Subject: Custom 'Float' class. Am I right here? Message-ID: <552799.63120.qm@web33404.mail.mud.yahoo.com> import sys class Float(float): """ Custom float datatype with addtional attributes. """ def __new__(self, value=0.0, #default value name='', # string range=(0.0, 1.0) # tuple ) try: self.name = name self.range = range self.pos = (1, 1) return float.__new__(self, value) except: print ('Invalid value : Float = %s %s' % (str(value), sys.exc_info()[:2])) def setpos(self, value): self.pos = value def getpos(self): return self.pos*2.0 p = property(getpos, setpos) myFloat = Float(0.23) print myFloat.pos I am trying to create a custom 'float' datatype by subtyping default 'float'. There are few things I would like to know here: 1. How to make 'name' & 'range' only readable attributes. 2. The property 'p' is not working as it has to. What's wrong here? 3. I would be heavily instancing this class, and I won't be creating any new attribute on instance. Is there any way to optimize? __slots__? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From jtanis at mdchs.org Sun Jul 20 17:20:17 2008 From: jtanis at mdchs.org (James Tanis) Date: Sun, 20 Jul 2008 17:20:17 -0400 Subject: Web Server In-Reply-To: Message-ID: "Fredrik Lundh" wrote: > there's also apache, of course, and a bunch of others, including several > Python solutions (more or less pre-packaged). but the "open up" part > still sounds a bit risky. maybe you could turn things around, and let > the application "push" data to your server instead? Either way requires an open port, otherwise there's no way to negotiate new clients. If your in a closed environment that's not a concern, you could just define what clients to push to and when, but it sounds like he wants something a bit more dynamic. -- James Tanis Technical Coordinator Monsignor Donovan Catholic High School e: jtanis at mdchs.org From bj_666 at gmx.net Thu Jul 10 01:07:21 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Jul 2008 05:07:21 GMT Subject: Python and decimal character entities over 128. References: <95e7a2c4-0027-45e6-ace6-f0b414a0fd1c@34g2000hsh.googlegroups.com> Message-ID: <6dljo8F35ua2U2@mid.uni-berlin.de> On Wed, 09 Jul 2008 16:39:24 -0700, bsagert wrote: > Some web feeds use decimal character entities that seem to confuse > Python (or me). I guess they confuse you. Python is fine. > For example, the string "doesn't" may be coded as "doesn’t" which > should produce a right leaning apostrophe. Python hates decimal entities > beyond 128 so it chokes unless you do something like > string.encode('utf-8'). Python doesn't hate nor chokes on these entities. It just refuses to guess which encoding you want, if you try to write *unicode* objects into a file. Files contain byte values not characters. > Even then, what should have been a right-leaning apostrophe ends up as > "???". The following script does just that. Look for the string "The > Canuck iPhone: Apple doesn? ??t care" after running it. Then you didn't tell the application you used to look at the result, that the text is UTF-8 encoded. I guess you are using Windows and the application expects cp1252 encoded text because an UTF-8 encoded apostrophe looks like '???' in cp1252. Choose the encoding you want the result to have and anything is fine. Unless you stumble over a feed using characters which can't be encoded in the encoding of your choice. That's why UTF-8 might have been a good idea. Ciao, Marc 'BlackJack' Rintsch From tjreedy at udel.edu Thu Jul 10 01:49:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Jul 2008 01:49:41 -0400 Subject: variable question In-Reply-To: <01da01c8e1fb$7615a4f0$a701a8c0@office.ipglobal.net> References: <01da01c8e1fb$7615a4f0$a701a8c0@office.ipglobal.net> Message-ID: Support Desk wrote: > I am trying to assign a variable using an if / else statement like so: > If condition1: Variable = something > If condition2: Variable = something else > Do stuff with variable. > But the variable assignment doesn?t survive outside the if statement. When things do not work as you expect, post minimal actual code that does not work, what happened, and if not obvious, what you expected different. From rcdailey at gmail.com Wed Jul 30 16:12:19 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 30 Jul 2008 15:12:19 -0500 Subject: Reasoning behind 'self' parameter in classes? In-Reply-To: References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> <4890ACE4.4060703@acm.org> <496954360807301227h1dea050eg735314beb0b5ff16@mail.gmail.com> Message-ID: <496954360807301312vd528870vccec29cf3f2f09d3@mail.gmail.com> On Wed, Jul 30, 2008 at 2:48 PM, Patrick Mullen wrote: > Well, the linked thread gives many reasons, but as mentioned it is a > flamewar thread. Philosophically python is not an "object oriented" > language per say, it has an object system, a not bolted on one I might add, > but it doesn't force developers to use that methodology. You can be > functional or procedural if you'd rather. Following this philosophy, when > methods were designed, they were merely functions that got passed an > instance as the first argument. The parser followed this design choice. As > far as I understand it, the underlying method object is not different from a > function argument, thus it cannot have any magic arguments built in. The > only magic involved is the fact that the object, when calling a method, will > pass its instance as the first argument. > > I don't believe there is any chance of this changing in python 3, python 4 > is anyone's guess... > > This does allow some good things that come for free, like adding methods > later, or changing functions into methods or methods into functions. If you > start out developing a class, but feel a class is too bulky, you can delete > the "class" line, dedent the methods, and have a set of functions instead > for free. Or, if you have functions that are set up to take instances as > their first argument already, you can bundle them up into a class very > easily. > > If by "hack" you mean using features already available in the language to > accomplish things, that kind of is what it is, and that's kind of what > python is about. New syntax for a new feature is uncommon, but it happens. > New syntax that breaks old code is very uncommon, and is only now coming out > in python 3. And the biggest change in python 3 is to eliminate added > syntax, such as print being a statement, and make the code reuse more python > features rather than have every feature exist as an island. Print being a > function, for instance, lets you use the same syntax for it that you use for > other functions, making everything clearer and more unified. A common thing > programmers might do when upgrading their code is to turn print statements > into better logging functions - if print was a function in the first place > this would be an easier task. > > Eliminating self doesn't accomplish much, and changes of this nature just > don't get done without a good reason. It takes away something that might be > annoying, but doesn't add anything. The benefits of changing have to be > significant for a code change to break the existing syntax. Many people are > upset even about some of the changes in python 3, that the benefits don't > outweight the cost of change, and most of those changes are less damaging > than playing around with the self businss would be :) > > So no, self not a mysterious thing that we should never question. Self is > an understood thing that has been questioned very often (weekly, monthly) > for many many years - there are not enough good reasons to bother with > changing it, and there enough good reasons for it that it's best to keep it. > This is quite possibly the best explanation yet. Thank you very much for this. You bring much insight into the feature. You see, a lot of people I've worked with have complained about the 'self' parameter. While this has never bothered me personally, other people find it a "flaw in the language". I often argue with my coworkers that Python is better than Ruby (This is of course opinionated and biased), but sometimes I find I cannot defend python when I need to, and in the argument of 'self' I find that to be one of those situations. Anyway, I appreciate everyone taking the time to explain this to me. I'm sure you guys are at the point of copy/paste of your responses on these topics :) They're far too frequent it seems. In any case, I still appreciate the responses. This topic can die now, I would hate to see it continue and another flame war to start. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexnbryan at gmail.com Wed Jul 2 04:21:58 2008 From: alexnbryan at gmail.com (Alexnb) Date: Wed, 2 Jul 2008 01:21:58 -0700 (PDT) Subject: Problem with a for loop and a list In-Reply-To: References: <18232298.post@talk.nabble.com> Message-ID: <18232528.post@talk.nabble.com> well okay, so what can I do? A.T.Hofkamp-3 wrote: > > On 2008-07-02, Alexnb wrote: >> I have no idea what "list assignment index out of range means?!?! > > You are assigning a value to a non-existing list element, as in > >>>> x = [1] >>>> x[2] = 4 > Traceback (most recent call last): > File "", line 1, in ? > IndexError: list assignment index out of range > > > Albert > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Problem-with-a-for-loop-and-a-list-tp18232298p18232528.html Sent from the Python - python-list mailing list archive at Nabble.com. From bignose+hates-spam at benfinney.id.au Thu Jul 24 10:12:05 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 25 Jul 2008 00:12:05 +1000 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> Message-ID: <87abg7pe16.fsf@benfinney.id.au> Jordan writes: > If the attitude in the community in response to feedback/criticism > has gone from "maybe you've got a point" to "your a lunatic, we'll > never change", well, only Python will suffer in the long term. You're not a lunatic. We, and Python itself, change quite readily. Neither of those mean your ideas in this instance have merit. -- \ ?Pinky, are you pondering what I'm pondering?? ?Well, I think | `\ so, Brain, but do I really need two tongues?? ?_Pinky and The | _o__) Brain_ | Ben Finney From sean_mcilroy at yahoo.com Sun Jul 20 17:27:35 2008 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: Sun, 20 Jul 2008 14:27:35 -0700 (PDT) Subject: examples of pipe usage? Message-ID: <5aab8bb6-0d56-475d-85c2-ced908e29412@x36g2000prg.googlegroups.com> hola i'd like to control another interpreter from idle. i don't have any experience using unix but i think a "pipe" is what i need. am i right about this? can anybody point me to a simple example of using a pipe (if that's the right thing) for this kind of task? thanks if you can help. peace stm From starsareblueandfaraway at gmail.com Thu Jul 17 13:32:13 2008 From: starsareblueandfaraway at gmail.com (Roy H. Han) Date: Thu, 17 Jul 2008 13:32:13 -0400 Subject: property getter with more than 1 argument? In-Reply-To: References: Message-ID: <6a5569ec0807171032n5f0f666evcab326fdf6300683@mail.gmail.com> I don't understand what you're trying to do here. On Thu, Jul 17, 2008 at 10:57 AM, mk wrote: > > It seems like getter is defined in such way that it passes only 'self': > > > class FunDict(dict): > def __init__(self): > self.fundict = dict() > > def fget(self, fun): > return fundict[fun.func_name] > > def fset(self, newfun): > self.fundict[newfun.func_name] = newfun > > newfun = property (fget, fset) > > >>>> a=FunDict() >>>> >>>> a.newfun=f1 >>>> >>>> a.newfun('f1') > > Traceback (most recent call last): > File "", line 1, in > a.newfun('f1') > TypeError: fget() takes exactly 2 arguments (1 given) > > > > Is it possible to pass more than one argument to fget function? > > I know: I can define a function with property name ('newfun' in the example) > and call it with more arguments. But then I do not get the benefits of > setter and property in general! > > -- > http://mail.python.org/mailman/listinfo/python-list > From arsyed at gmail.com Sun Jul 20 17:06:32 2008 From: arsyed at gmail.com (arsyed) Date: Sun, 20 Jul 2008 17:06:32 -0400 Subject: matplotlib: Plotting a graph against time In-Reply-To: <4249053c-d350-445a-977f-04799bb236cb@t54g2000hsg.googlegroups.com> References: <293e05cf-3a50-40e3-961c-926cafe14762@e53g2000hsa.googlegroups.com> <4249053c-d350-445a-977f-04799bb236cb@t54g2000hsg.googlegroups.com> Message-ID: <9a2cc7a70807201406r4e06980am1b4c90db72c317eb@mail.gmail.com> On Sun, Jul 20, 2008 at 9:57 AM, Durand wrote: > Oooh, this is almost what I want but I'm not really sure how I'd > incorporate this into real dates... > If I have a list of dates like ['2008-07-18 14:36:53.494013', > '2008-07-20 14:37:01.508990', '2008-07-28 14:49:26.183256'], how would > I convert it to a format that pylab can understand? When I tried > type(datetime.now()) it gave me datetime.datetime whereas the objects > in this list are strings...Am I doing something wrong here? > -- > http://mail.python.org/mailman/listinfo/python-list > To convert strings to date, you can use datetime.strptime but it doesn't seem to handle fractional seconds. I usually opt for the dateutil module [1]: import dateutil, pylab datestrings = ['2008-07-18 14:36:53.494013','2008-07-20 14:37:01.508990', '2008-07-28 14:49:26.183256'] dates = [dateutil.parser.parse(s) for s in datestrings] pylab.plot_date(pylab.date2num(dates), values, linestyle='-') where values is the list of corresponding y-values. [1] http://labix.org/python-dateutil -------------- next part -------------- An HTML attachment was scrubbed... URL: From mrkafk at gmail.com Tue Jul 1 12:11:02 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Tue, 01 Jul 2008 18:11:02 +0200 Subject: Embedding Python In-Reply-To: References: Message-ID: Hello everyone, In the meantime I managed to work out another solution, mainly thanks to reading the source code of some OSS projects. I post it here so somebody else looking for solution to this problem had the example available: ----cut---- #include #include #include #include #include static FILE *read_module(const char *cpathname, long mtime) { FILE *fp; long magic; long pyc_mtime; fp = fopen (cpathname, "rb"); if (fp == NULL) return NULL; magic = PyMarshal_ReadLongFromFile (fp); if (magic != PyImport_GetMagicNumber()) { fclose(fp); return NULL; } pyc_mtime = PyMarshal_ReadLongFromFile (fp); if (mtime && pyc_mtime != mtime) { fclose(fp); return NULL; } return fp; } int main(int argc, char **argv) { int size; Py_Initialize(); PyCodeObject *mainobj, *pycode; PyObject *result, *mainmodule, *maindict; mainmodule = PyImport_AddModule("__main__"); maindict = PyModule_GetDict(mainmodule); FILE *f = read_module("multiply.pyc", 0L); pycode = (PyCodeObject *) PyMarshal_ReadObjectFromFile(f); printf("pointer: %d\n", pycode); PyEval_EvalCode(pycode, maindict, maindict); Py_Finalize(); } ----cut---- From cwitts at gmail.com Wed Jul 2 10:03:56 2008 From: cwitts at gmail.com (Chris) Date: Wed, 2 Jul 2008 07:03:56 -0700 (PDT) Subject: simple UnZip References: <5b915a0e-a227-460f-8273-ecc01b800884@2g2000hsn.googlegroups.com> Message-ID: On Jul 2, 3:39?pm, noydb wrote: > Can someone help me with this script, which I found posted elsewhere? > I'm trying to figure out what is going on here so that I can alter it > for my needs, but the lack of descriptive names is making it > difficult. ?And, the script doesn't quite do anything worthwhile -- it > unzips one file from a zipfile, not all files in a zipfile. > > *** > import zipfile, os, sys, glob > > os.chdir("C:\\Temp") > zips = glob.glob('*.zip') > > for fzip in zips: > ? ? if zipfile.is_zipfile(fzip): > ? ? ? ? print fzip," is a zip" > ? ? ? ? z = zipfile.ZipFile(fzip,'r') > ? ? ? ? lstName = z.namelist() > ? ? ? ? sHgt = lstName[0] > ? ? ? ? print "Unpacking",sHgt > ? ? ? ? hgt = z.read(sHgt) > ? ? ? ? fHgt = open(sHgt,'wb') > ? ? ? ? fHgt.write(hgt) > ? ? ? ? # fHgt.flush > ? ? ? ? fHgt.close > print "Finished" > *** > > I changed it somewhat to > &&& > import zipfile, os, sys > > event_zip = ("C:\\Temp\\data4event.zip") > > z = zipfile.ZipFile(event_zip, 'r') > > zList = z.namelist() > > for zItem in zList: > ? ? print "Unpacking",zItem > ? ? zRead = z.read(zItem) > ? ? z1File = open(zItem,'wb') > ? ? z1File.write(zRead) > ? ? z1File.close > print "Finished" > &&& > > This works, but I want to be able to specify a different output > location. > > The scenario is that the zip file will always be the same (gets copied > over daily), but it needs to be unzipped to a specific different > directory. > > Can anyone help? > > Thanks! Well, how is the output directory different ? Is it just a timestamp like 'YYYYMMDD' that obviously changes every day or is it named after the file used ? If it is timestamp style you can do import zipfile, os, sys, time folder_name = time.strftime("%Y%m%d", time.localtime(time.time())) event_zip = ("C:\\Temp\\data4event.zip") z = zipfile.ZipFile(event_zip, 'r') zList = z.namelist() for zItem in zList: print "Unpacking",zItem zRead = z.read(zItem) z1File = open(os.path.join(folder_name, zItem),'wb') z1File.write(zRead) z1File.close print "Finished" That will create a folder in your current working directory with the name of todays date and unzip it there. This is just one example route. From grflanagan at gmail.com Thu Jul 31 06:47:30 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Thu, 31 Jul 2008 12:47:30 +0200 Subject: ANN: Google custom search engine for Python In-Reply-To: References: Message-ID: <48919842.1020502@gmail.com> Gerard flanagan wrote: > What is it? > ----------- > > A Google custom search engine which targets only the following sites: > > + `The Hazel Tree `__ > + `The Python standard library docs `__ > + `The Python wiki `__ > + `Python Package Index `__ > > Where can I access it? > ---------------------- > > The home page of the search engine is here: > > http://www.google.com/coop/cse?cx=002031040340806163079:nkigkp_irqk > > As well as accessing it from its home page, you can link to it from your > own web sites, or add it as a gadget to your Google home page (if you > have one) - see the above link for details. > > No ads > ------ > > `The Hazel Tree `__ is a not-for-profit site > and no ads will appear in the search results. > > Using refinements > ----------------- > > To refine the search to any of the individual sites, you can specify a > refinement using the following labels: stdlib, wiki, pypi, thehazeltree > > So, to just search the python wiki, you would do: > > somesearchterm more:wiki > > and similarly: > > somesearchterm more:stdlib > somesearchterm more:pypi > somesearchterm more:thehazeltree > > About http://thehazeltree.org > ----------------------------- > > `The Hazel Tree `__ is a collection of popular > Python texts that I have converted to reStructuredText and put together > using `Sphinx `__. It's in a publishable state, > but not as polished as I'd like, and since I'll be mostly offline for > the next month it will have to remain as it is for the present. However, > the search engine is ready now and the clock is ticking on its > subscription (one year, renewal depending on success of site), so if > it's useful to anyone, it's all yours (and a link back to > http://thehazeltree.org would be appreciated). > > Cheers, > > G. > > -- > http://mail.python.org/mailman/listinfo/python-list > Added http://code.activestate.com/recipes/ (refinement name is `aspn`) G. From tjreedy at udel.edu Mon Jul 7 21:46:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 07 Jul 2008 21:46:48 -0400 Subject: complex representation In-Reply-To: References: Message-ID: DSM wrote: > ISTM the same reasoning applies equally to complex numbers. My interest > arose because of what I think is a bug in pypy's complex printing: > > > Python 2.4.1 (pypy 1.0.0 build 56124) on linux2 > Type "help", "copyright", "credits" or "license" for more information. > ``RPython: we use it so you don't have to'' > >>>> (1.1+1.1j)**200 > (240733537691613523198532543387690598400L+236495565429619338248192Lj) > > > This strangeness comes about because a hack used to recover cpython's > behaviour fails at large values. (x.real == floor(x.real), so it > decides the value's an integer, and returns the repr of int(x.real).) > It's trivial to fix but I think cpython's behaviour is slightly odd > here, and the real and imaginary parts of the complex repr should be > identical to those of the underlying floats. CPython 2.4, 2.5, and 3.0 on WinXP (and hence I presume 2.6) produce (with a trivial variation) >>> (1.1+1.1j)**200 (2.407335376916204e+38+2.3649556542962612e+23j) That Pypy disagrees in the 14th digit is a bit odd, but I suspect a C math library difference. Unless they are actually calculating 40 digits exactly, the extra digits should be filled with 0s if they want integers. Take that, and whatever you think is strange, up with them. From diordna at gmail.com Fri Jul 18 20:52:52 2008 From: diordna at gmail.com (Stephen Johnson) Date: Fri, 18 Jul 2008 20:52:52 -0400 Subject: Any Game Developers here? In-Reply-To: <76b841590807181605r106995d2k98486993a4eaccc4@mail.gmail.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> <4A235BC6-5E46-4402-AF2D-BA3DBC175517@gmail.com> <76b841590807181605r106995d2k98486993a4eaccc4@mail.gmail.com> Message-ID: <9B960401-8D79-44BC-B4A5-4BE2BD1869BC@gmail.com> Yes, I wrote the music, the GUI, and bits of code here and there.. Will Hogben is working on EW 2 for Freeverse right now. But that was in BlitzMax, and I'm in greener pastures now, working on my demo for PyOhio. -Steve Johnson On Jul 18, 2008, at 7:05 PM, Michael Lubker wrote: > I'm interested in general... I know about PyGame and Pyglet, and have > used both. We're currently using Python-Ogre. In the end, I am looking > to find people interested in my project ( see > http://youtube.com/watch?v=E0QQ9JuclxE ), but I also want to find > people experienced with Python in general, not just one library. > (though of course I know that's not too likely) > > Aren't you one of the Escort Wing developers? :) > > Thanks > Michael > > On Fri, Jul 18, 2008 at 5:13 PM, Stephen Johnson > wrote: >> I use the Pyglet library to make games. You want to look at the >> pyglet and >> pygame mailing lists, not this one. Use Google. >> In my opinion, PyGame is clunky and Pyglet is elegant, simple, and >> comprehensive. PyGame has more examples available, but Pyglet has >> great >> documentation and enough examples to answer any questions you might >> have. >> Both have active communities. >> >> -Steve Johnson >> On Jul 18, 2008, at 5:38 PM, Michael Lubker wrote: >> >> Any people that use Python as the predominant language for their game >> development here? >> >> ~Michael >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > > > -- > ~ "The world hates change, yet it is the only thing that has brought > progress." ~ Charles Kettering > > http://snowballz.joey101.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Tue Jul 15 07:42:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 15 Jul 2008 13:42:37 +0200 Subject: Logging in __del__() In-Reply-To: <17056.2125546441$1216121658@news.gmane.org> References: <17056.2125546441$1216121658@news.gmane.org> Message-ID: Robert Rawlins wrote: > I then get the following exception thrown when running my code: When the application is running, or when it is shutting down? > Traceback (most recent call last): > File "/usr/lib/python2.5/logging/handlers.py", line 73, in emit > if self.shouldRollover(record): > File "/usr/lib/python2.5/logging/handlers.py", line 147, in shouldRollover > self.stream.seek(0, 2) #due to non-posix-compliant Windows feature > ValueError: I/O operation on closed file > > Does anyone have any ideas as to what I?m doing wrong here? Is this a > known issue which has a neat little work around? Python makes no guarantees that it will tear down your objects before it tears down the library's objects (or the library itself). See e.g. http://www.python.org/doc/essays/cleanup/ (old and probably somewhat outdated, but you get the idea) I'd just put a try/except around it, and ignore any exceptions that may occur. From mensanator at aol.com Wed Jul 16 02:20:58 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 15 Jul 2008 23:20:58 -0700 (PDT) Subject: new itertools functions in Python 2.6 References: <4dd80ff2-5fda-405a-a637-08c985ff8add@e53g2000hsa.googlegroups.com> <498a38d4-10b5-4824-8401-5ebb510fcfa8@y38g2000hsy.googlegroups.com> Message-ID: On Jul 15, 1:44 am, Raymond Hettinger wrote: > On Jul 14, 1:26 pm, Mensanator wrote: > > > ## Combinations with replacement > > ## ----------------------------- > > ## aaa aab aac aad aae abb abc abd abe acc acd ace > > ## add ade aee bbb bbc bbd bbe bcc bcd bce bdd bde > > ## bee ccc ccd cce cdd cde cee ddd dde dee eee > > ## > > ## actual words: 35 (m+n-1)!/(n!(m-1)!) words: 35 > > > Although it works, it's somewhat slow as we have to iterate > > over the entire Cartesian Product and the filter list(x)==sorted(x) > > has got to be expensive (it's slower than the nested loop algorithm). > > > Is there a better way to get Combinations With Replacement > > using itertools? > > There may a technique to start with the combinations without > replacement and then grow the result by repeating elements: Great idea, I had only considered making a sub=set. It never occured to me to try and make a super=set. Thanks for the suggestions, they've given me some ideas to try. > > result = set(combinations('abcde', 3)) > # transform 'ab ac ad ae bc bd be cd ce de' into 'aab abb aac > acc ...' > for c in combinations('abcde', 2): > # transform 'ab' --> 'aab abb' > for i in range(2): > result.add(c[:i] + c[i]*1 + c[i:]) > for c in combinations('abcde', 1): > for i in range(1): > # 'a' --> 'aaa' > result.add(c[:i] + c[i]*2 + c[i:]) > > If you generalize the above, it may solve the problem using itertools > as a starting point. > > Alternatively, it's not too hard to transform the pure python version > given in the docs to one that supports combinations with replacement: I was trying to avoid that kind of solution. ifilter(product()) is exactly the kind of thing I'm looking for, just wondering if there's a better way, using a different combination of functions. > > def combinations_with_replacement(iterable, r): > pool = tuple(iterable) > n = len(pool) > indices = [0] * r > yield tuple(pool[i] for i in indices) > while 1: > for i in reversed(range(r)): > if indices[i] != n - 1: > break > else: > return > indices[i] += 1 > for j in range(i+1, r): > indices[j] = indices[j-1] > yield tuple(pool[i] for i in indices) > > Raymond From fredrik at pythonware.com Mon Jul 21 04:55:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 10:55:56 +0200 Subject: What is the role of python2.6 and C++? In-Reply-To: <74c92ee2-7b89-4579-b25a-a68262e2fee7@a70g2000hsh.googlegroups.com> References: <74c92ee2-7b89-4579-b25a-a68262e2fee7@a70g2000hsh.googlegroups.com> Message-ID: cokofreedom at gmail.com wrote: > 2.6 is meant to be a continuation of the 2.x line of Python, to > support a gradual move of larger projects over to the Python 3.x > series. note that Python also has a tradition of releasing X.6 and (X+1).0 at the same time: http://mail.python.org/pipermail/python-announce-list/2000-September/000513.html http://mail.python.org/pipermail/python-list/2000-September/051263.html From paul at boddie.org.uk Sat Jul 26 14:22:59 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 26 Jul 2008 11:22:59 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> Message-ID: On 26 Jul, 06:06, Terry Reedy wrote: > Paul Boddie wrote: > > "The problem is that the explicit requirement to have self at the > > start of every method is something that should be shipped off to the > > implicit category." Here, I presume that the author meant "at the start of every method signature". > There is no requirement to have 'self' in the parameter list. It can be > 's', 'this', 'me', 'yo'(Spanish for I), or 'cls' (for class methods), or > any other identifier in whatever language. But Jordan apparently wanted to omit that parameter. The omission of all mentions of "self" could be regarded as a bonus, but it's a non- trivial goal. > In 3.0, identifiers are not restricted to ascii but can be any unicode > 'word' as defined in the manual. > > So the proposal would have to be that the compiler scan the function > body and decide which dotted name prefix is the one to be implicitly > added. Have fun writing the discovery algorithm. However, I think this > is pretty silly. Just write the name you want. If, as I wrote, you permit the omission of "self" in method signatures defined within class definitions, then you could still insist on instance attribute qualification using "self" - exactly as one would when writing Java according to certain style guidelines. Paul From circularfunc at yahoo.se Thu Jul 3 10:11:09 2008 From: circularfunc at yahoo.se (defn noob) Date: Thu, 3 Jul 2008 07:11:09 -0700 (PDT) Subject: site-packages, unzipepd there but import fails Message-ID: i unzipped and put the folder in site-packages. when i run setup.py install nothing happens. when i do import pp from shell it complains it doesnt exist. isnt placing the folder in site-packages enough? these setup.py-files often dont work but normally it still works. From george.trojan at noaa.gov Tue Jul 29 13:58:05 2008 From: george.trojan at noaa.gov (George Trojan) Date: Tue, 29 Jul 2008 17:58:05 +0000 Subject: iterating "by twos" In-Reply-To: References: Message-ID: kj wrote: > Is there a special pythonic idiom for iterating over a list (or > tuple) two elements at a time? > > I mean, other than > > for i in range(0, len(a), 2): > frobnicate(a[i], a[i+1]) > > ? > > I think I once saw something like > > for (x, y) in forgotten_expression_using(a): > frobnicate(x, y) > > Or maybe I just dreamt it! :) > > Thanks! I saw the same thing, forgot where though. But I put it in my library. Here it is: # x.py import itertools def pairs(seq): is1 = itertools.islice(iter(seq), 0, None, 2) is2 = itertools.islice(iter(seq), 1, None, 2) return itertools.izip(is1, is2) s = range(9) for x, y in pairs(s): print x, y dilbert at trojan> python x.py 0 1 2 3 4 5 6 7 From toby at tobiah.org Thu Jul 24 14:46:49 2008 From: toby at tobiah.org (Tobiah) Date: Thu, 24 Jul 2008 11:46:49 -0700 Subject: Doubt References: <8c8592be-3bb2-4ee6-9f90-cd374233ba05@w7g2000hsa.googlegroups.com> Message-ID: >> How to convert the perl notation >> $a = ""; expression in Python ? a = "" >> How to represent the loop >> for ($a = $b; $a<=$c;$a++){ >> >> } in Python for a in range(b, c + 1): do_something() ** Posted from http://www.teranews.com ** From wuwei23 at gmail.com Sat Jul 26 23:02:54 2008 From: wuwei23 at gmail.com (alex23) Date: Sat, 26 Jul 2008 20:02:54 -0700 (PDT) Subject: Insert character at a fixed position of lines References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> <7895c8b2-fa01-483c-8ba9-d90975ea688d@o40g2000prn.googlegroups.com> Message-ID: <8b0f4fe2-d8ab-4230-9032-ccd02878d349@v39g2000pro.googlegroups.com> Ugh, and in pointing our your inaccurate code I posted my own: > >>> f = open('dummy.txt','w') > >>> f.write(line = 'this doesn't work') > > File "", line 1 > f.write(line = 'this doesn't work') > ^ > SyntaxError: invalid syntax That should be: >>> f.write(line = "this doesn't work") Traceback (most recent call last): File "", line 1, in TypeError: write() takes no keyword arguments Sorry about that :) From ironfroggy at gmail.com Thu Jul 17 08:34:13 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Thu, 17 Jul 2008 08:34:13 -0400 Subject: Instance In-Reply-To: <120cea3a-33a9-49ec-8932-7cef2e5aef17@25g2000hsx.googlegroups.com> References: <120cea3a-33a9-49ec-8932-7cef2e5aef17@25g2000hsx.googlegroups.com> Message-ID: <76fd5acf0807170534y3aa2a8fft96b1c8a7a7a57f65@mail.gmail.com> On Thu, Jul 17, 2008 at 2:56 AM, karthikbalaguru wrote: > Hi, > > I am new to python. I am trying to use the python files given to me > for bringing up a setup. > I get the following error while trying to use a python file - > AttributeError : Classroom instance has no attribute 'desk_offset' > > How to resolve this ? > Should i need to define desk_offset to zero in the python file ? > > Any ideas .. This means you did something like this: class Foo: def __init__(self): self.bar = 10 f = Foo() print f.quu ... AttributeError : Foo instance has no attribute 'quu' See? You tried to use an attribute that simply doesn't exist. Look in the traceback for where you used the desk_offset attribute, and figure out why you thought the object had such an attribute and why it does not. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From bronger at physik.rwth-aachen.de Thu Jul 24 06:47:36 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 24 Jul 2008 12:47:36 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <32e12408-fc9f-4eb4-8b9d-fb7fa69bd2fc@f36g2000hsa.googlegroups.com> Message-ID: <87zlo7y2wn.fsf@physik.rwth-aachen.de> Hall?chen! Kay Schluehr writes: > On 24 Jul., 11:40, Torsten Bronger > wrote: >> >> Bruno Desthuilliers writes: >> >>> [...] >>> >>> How would you handle this case with an implicit 'self' : >>> >>> class Foo(object): >>> pass >>> >>> def bar(self): >>> print self >>> >>> Foo.bar = bar >> >> Just like this. However, the compiler could add "self" to >> non-decorated methods which are defined within "class". > > And $self2, $self3, ... to the object methods of nested classes > and $cls2, $cls3, ... to the classmethods of those classes...? One could surely find ways to realise this. However, the design goal should be: Make the frequent case simple, and the rare case possible. (Actually, I'm -0 on this anyway because I forget "self" very seldomly, and you would still have ".self" all over the place.) Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From clay at lakeserv.net Sun Jul 13 09:22:01 2008 From: clay at lakeserv.net (Clay Hobbs) Date: Sun, 13 Jul 2008 09:22:01 -0400 Subject: Problems with curses Message-ID: <1215955321.19541.3.camel@generator> > On Sat, 12 Jul 2008 20:49:56 -0400, Clay Hobbs wrote: > > > Unfortunately, the error message isn't very helpful. > > But it would be helpful to tell it. If you get exceptions, always > copy'n'paste the traceback here. People might know what the exception > means and share their wisdom. Here is the error message: Traceback (most recent call last): File "./text_adventure.py", line 25, in curses.wrapper(main) File "/usr/lib/python2.5/curses/wrapper.py", line 44, in wrapper return func(stdscr, *args, **kwds) File "./text_adventure.py", line 19, in main stdscr.scroll(3) _curses.error: scroll() returned ERR -- Ratfink From tjreedy at udel.edu Sun Jul 13 14:00:32 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 13 Jul 2008 14:00:32 -0400 Subject: Functional/Best? In-Reply-To: <1215956345.3028.10.camel@localhost.localdomain> References: <1215956345.3028.10.camel@localhost.localdomain> Message-ID: Tim Cook wrote: > I guess I can classify my application(s) as more procedural than > anything else. But I have a question about the best way to handle > something in Python. > > When given a mapping of keywords, I want to call a function based on a > certain keyword found when parsing a text file. The mapping looks like > this: > > definClassMap={'SECTION':'bldSection','COMPOSITION':'bldComposition','OBSERVATION':'bldObservation','ITEM_TREE':'bldItemTree'} > > So if the text file contains 'ITEM_TREE' I want to call bldItemTree > which creates an instance of the class ItemTree. > > I currently use an if ..., elif ... construct. > Is there a better, more efficient, more Pythonic way of doing this? Yes. Create a mapping of keywords to function objects rather than to function names! def bldSection(): ... def bldItemTree(): class_map={ 'SECTION':bldSection, 'COMPOSITION':bldComposition, 'OBSERVATION':bldObservation, 'ITEM_TREE':bldItemTree, # trailing comma allows easy additions } for word in parselist: try; class_map[word]() except KeyError: tjr From coolman.guron at gmail.com Thu Jul 31 11:40:03 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Thu, 31 Jul 2008 08:40:03 -0700 (PDT) Subject: Newbie Python questions References: <12p2941fee0nnimqmraqt9cm1vml7ra2kt@4ax.com> Message-ID: <706f52bb-c206-4021-9a2f-2e52f6e3429b@u6g2000prc.googlegroups.com> One great open source GUI package that you left out is GTK ie. pygtk. i cant compare it with wx as i have never used it but isay its much better than QT. Anyway for ur q if u want to compair qt n wx. QT should be faster coz it has a better documentation. and welcome to the python family! kind regards binaryjesus On Jul 31, 12:10 pm, Tim Roberts wrote: > LessPaul wrote: > > >...My > >question is in regard to GUI platforms. My primary target would be > >Windows, but I would also like be able to support Linux and Mac > >versions if possible. I'm also interested in using a system that also > >has support for pure C++ applications. As such, and after reading many > >web pages regarding Python GUIs, I believe I have the candidates > >narrowed down to pyQT and wxPython. > > >The first question -- how steep is the curve to become proficient with > >the above GUI packages? > > There is so much personal preference here that it is extremely hard to give > any guidance. If you have done any Windows programming at all, so that you > are familiar with the event-driven programming model, then I don't think > you would see that much difference in learning curve. The two packages are > more alike than they are different -- the various APIs are just spelled > differently. > > I happen to be a big wxPython fan. I learn best by example, and wxPython > has a 44,000-line demo suite with 167 source files that demonstrates > virtually every class it includes. > > >Since there appears to be no commercial licencing fee for wxWidgets/ > >wxPython, the last question is what do I gain from going QT over wx? > >I've seen great applications written with both (on my computer I have > >the wxPython Digsby and the pyQT apps "Mnemosyne" and "Anki". All seem > >to be solid. > > Yep. Personal preference. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. From circularfunc at yahoo.se Tue Jul 15 12:26:55 2008 From: circularfunc at yahoo.se (defn noob) Date: Tue, 15 Jul 2008 09:26:55 -0700 (PDT) Subject: isPrime works but UnBoundLocalError when mapping on list Message-ID: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> isPrime works when just calling a nbr but not when iterating on a list, why? adding x=1 makes it work though but why do I have to add it? Is there a cleaner way to do it? def isPrime(nbr): for x in range(2, nbr + 1): if nbr % x == 0: break if x == nbr: return True else: return False >>> [isPrime(y) for y in range(11)] Traceback (most recent call last): File "", line 1, in [isPrime(y) for y in range(11)] File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime if x == nbr: UnboundLocalError: local variable 'x' referenced before assignment >>> map(isPrime, range(100)) Traceback (most recent call last): File "", line 1, in map(isPrime, range(100)) File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime if x == nbr: UnboundLocalError: local variable 'x' referenced before assignment >>> isPrime(10) False >>> isPrime(11) True adding x=1 makes it work though: def isPrime(nbr): x=1 for x in range(2, nbr + 1): if nbr % x == 0: break if x == nbr: return True else: return False >>> [isPrime(y) for y in range(11)] [False, True, True, True, False, True, False, True, False, False, False] From bruno.42.desthuilliers at websiteburo.invalid Wed Jul 2 04:47:02 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Jul 2008 10:47:02 +0200 Subject: Mako vs. Cheetah? In-Reply-To: References: <4862f57c$0$11621$607ed4bc@cv.net> <4863bf9c$0$14081$c3e8da3@news.astraweb.com> Message-ID: <486b4081$0$13874$426a74cc@news.free.fr> Maric Michaud a ?crit : > Le Saturday 28 June 2008 06:30:50 Tim Roberts, vous avez ?crit : >> Others really like the TAL scheme in Zope. >> For my taste, TAL just requires too much non-essential syntax; it >> interferes with the reading of the page. >> >> So, the folks who like TAL can go ahead and be productive with TAL, and >> I'll keep on being productive with Cheetah. > > Yes, TAL is a bit more hard and require some added learning, but tal templates > are very powerful and well structured, and they have a real advantage over > all other templating system, they are valid xhtml, So are Kid and Genshi, and they are way less verbose than TAL. And FWIW making Django's templating system xhtml compliant mostly requires redefining a couple constants to replace {% %} with and {{ }} with ${ }. From __peter__ at web.de Wed Jul 2 07:45:41 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Jul 2008 13:45:41 +0200 Subject: How to pickle bound methods References: Message-ID: srinivasan srinivas wrote: (Please don't top-post) > It works will for instance and class methods. But it doesn't work for > static methods. Can you tel me how to pickle static methods as well?? For static methods pickling is not so easy because these don't carry information about the class they belong to. What are you trying to do? Peter From duane.kaufman at gmail.com Mon Jul 21 11:51:04 2008 From: duane.kaufman at gmail.com (TheSeeker) Date: Mon, 21 Jul 2008 08:51:04 -0700 (PDT) Subject: how to create GUI dynamically References: <84f144db-0d6c-44d5-a1ef-6e7778304c2a@r66g2000hsg.googlegroups.com> Message-ID: On Jul 21, 8:19 am, hitechpun... at gmail.com wrote: > Hi; > > i m working on a project where i need run time creation of GUI. > > i have some no. of entities for which i want checkboxes in front of > them which can be checked/ unchecked by user. > > But the problem is that the number and name of entities is not fixed > and it depends on the file which is used as input. > > So is there any way to tackle this problem. > > By the way ; i use Boa constructor (zope editor) for GUI now. > > regards > pawan pundir Hi, Boa constructor can be used for the main part of the application, but you'll probably need to 'roll your own' builder of the dynamic portion (which isn't very hard). A wonderful list for these kinds of questions is: https://lists.sourceforge.net/lists/listinfo/boa-constructor-users Duane From gcmartijn at gmail.com Mon Jul 7 13:27:43 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Mon, 7 Jul 2008 10:27:43 -0700 (PDT) Subject: pythoncom InternetExplorer.Application don't work in vista || firefox pythoncom ? References: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> <486fe5cc$0$926$ba4acef3@news.orange.fr> <29c70427-07f2-43ae-b742-86af4431edd8@34g2000hsh.googlegroups.com> <48714f2f$0$897$ba4acef3@news.orange.fr> Message-ID: On 6 jul, 16:00, "M?ta-MCI \(MVP\)" wrote: > Hmmmm... ?I have a similary problem, in another circumstances. > It's often a problem of configuration of IE (for news customers). ?But, > it is not easy, because IE has many parameters. > > Good luck! > > Michel Claveau IE have many options, you say that the code is working so I was hoping that you could answer these questions: - Is your tabbed browsing on ? - Do you use the default 'securiy' settings ? - Do you use by privacy option: Medium ? - The advanced options are to much to ask here :( Greetings, GCMartijn From norseman at hughes.net Thu Jul 3 20:16:33 2008 From: norseman at hughes.net (norseman) Date: Thu, 03 Jul 2008 17:16:33 -0700 Subject: How to bypass Windows 'cooking' the I/O? (One more time, please) Message-ID: <486D6BE1.3000501@hughes.net> I know I saw the answer recently, as in since February '08, but I can't re-find it. :( I tried the mail archives and such and my own collections but the piece I saw still eludes me. Problem: (sos=same old s...) Microsoft insists the world work it's way even when the Microsoft way was proven wrong decades ago. In this case it's (still) 'cooking' the writes even with 'rwb' and O_RDWR|O_BINARY in (proper respective) use. Specific: python created and inspected binary file ends: 00460: 0D 1A (this is correct) after a write os.lseek(target, -1, 2) os.write(target,record) the expected result would be: 00460: 0D 20 .....data bytes.... 1A BUT I get: 00460: 20 .... data bytes... 1A It is one byte off!!! And the 0D has to be there. Signifies the end of the header. Same python program runs as expected in Linux. Maybe because that's where it was written?! :) What I seek is the way to slap Microsoft up side the head and make it work correctly. OK, well, at least in this situation. Note: Things like this justify Python implementers bypassing OS calls (data fetch, data write) and using the BIOS direct. Remember, the CPU understands bit patterns only. It has no comprehension of 'text', 'program', 'number', 'pointer', blah blah blah.... All that is totally beyond it's understanding. A given bit pattern means 'do that'. The CPU is 100% binary. Memory, storage and the rest is just bits-on, bits-off. Patterns. Proper binary I/O is mandatory for the machine to function. Anyway - if whoever mentioned the flags and such to 'over ride' Microsoft's BS would re-send that piece I would be very appreciative. Steve norseman at hughes.net From motoom at xs4all.nl Tue Jul 15 10:42:31 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Tue, 15 Jul 2008 16:42:31 +0200 Subject: Is it legal to rebuild Python.exe to include Version property tab? Message-ID: <2.2.32.20080715144231.012aacdc@pop.xs4all.nl> Ward wrote... > Can we rebuild Python.exe to include the various "version" > information? Why rebuild it? You can use a resource editor tool to add/edit/delete the VERSIONINFO from any Windows executable, including Python.exe ;-) Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From circularfunc at gmail.com Sun Jul 6 14:45:54 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 6 Jul 2008 11:45:54 -0700 (PDT) Subject: how are strings immutable in python? Message-ID: >>> h = "aja baja" >>> h += 'e' >>> h 'aja bajae' >>> From afriere at yahoo.co.uk Tue Jul 22 21:39:22 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 22 Jul 2008 18:39:22 -0700 (PDT) Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: <76e68c88-a720-464b-96f4-95e744468bd7@k37g2000hsf.googlegroups.com> On Jul 23, 7:02 am, ptn wrote: > Hi everybody, > > I have a weird problem. Say I have a .py file with some functions in > it, like this: > > # (...) > def foo(): > print("bar") > > When I open it and add a line to one of the functions, > > # (...) > def foo(): > troz = "bar" > print(troz) > > I get the following traceback from the interpreter: > > Traceback (most recent call last): > File "SOMEWHERE/example.py", line ?? > troz = "bar" > ^ > IndentationError: unindent does not match any outer indentation > level > > And so I'm forced to rewrite the function entirely just to add the new > line. > > I thought that my problem was the w option from formatoptions, so I > changed my .vimrc file to this: > > augroup filetype > autocmd BufNewFile,BufRead *.txt set filetype=human > augroup END > autocmd FileType human setlocal formatoptions+=ta2w > autocmd FileType lisp,scheme,python,c,java,vim setlocal > formatoptions-=ta2w > > But the problem didn't go away. It doesn't look like those formatoptions would be called when the filetype is python. Or am I missing something? > I don't think this has anything to do > with the tabs and spaces, because I have them set up like this: > > set tabstop=4 shiftwidth=4 expandtab > > which is the standard way to handle them. Did you actually search for tabs (/\t)? If the file was orginally edited without expandtabs and later expandtabs was used this is exactly the sort of problem you would encounter. Also you don't need to set tabstop if you in- and de-dented using [ctrl]-[t] and [ctrl]-[d] in insert mode, and '>>' and '<<' in command mode. > > The scripts I load are: qbuf, TagList, indent/python.vim and a reduced > version of the standard python.vim > > Could someone provide some pointers? > > Thanks, > > Pablo Torres N. From gnewsg at gmail.com Thu Jul 31 16:39:22 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 31 Jul 2008 13:39:22 -0700 (PDT) Subject: Questions about asyncore References: <5d30aad5-cad7-4e47-aa83-277202c70ae2@z72g2000hsb.googlegroups.com> <6db7042c-02bb-42ef-b578-3811d8f427f5@m36g2000hse.googlegroups.com> <4903018c-feac-40fb-81fc-002dfc430f84@z66g2000hsc.googlegroups.com> <85bd837a-62e3-455d-8bec-3d778231bfc5@i76g2000hsf.googlegroups.com> Message-ID: On 31 Lug, 08:30, Frank Millman wrote: > On Jul 30, 7:50 pm, "Giampaolo Rodola'" wrote: > > > On 30 Lug, 09:49, Frank Millman wrote: > > Thanks again, Giampaolo, your input is really appreciated. > > > > > I pretty much have the same overview I had before. > > As far as I can tell the only reason you want to use a thread is when > > you have to do something which requires a consistent amount of time to > > complete so that the asyncore loop gets blocked. > > The question is: is there anything like that in your code? > > If the answer is no then you don't need to use threads. > > Maybe you are just not used to the asynchronous approach where "wait > > for server to respond" or "wait for the response to be complete" > > doesn't mean that YOU have to wait. > > It means that when a specific condition occurs (e.g. some data is > > received) a certain method of the framework you're using will be > > called and then it will be up to you deciding what do to. > > Maybe I am not being clear enough on my side. > > I (hope I) understand the power of asnyc. I have written the server to > use async techniques, and when I get around to writing the full-blown > client, that will also use async techniques. > > However, at this stage, all I want to do is write something quick and > dirty to check that the server is behaving as intended. I want to > throw some messages at it, more or less at random, and check the > responses. I found it much easier to do this with asyncore.loop > running in a separate thread. I don't know why you find more convenient running asyncore.loop in a separate thread but if your purpose is writing a test suite in which a client checks responses sent by server I *would not* recommend using asyncore. The common way to do that is starting the server into setUp() method and shut it down in tearDown(). Every test consists in a client which uses the socket module to connect() to the server, send() something and recv() the response. That's all. pyftpdlib, which consists of an asyncore-based FTP server, has a test suite behaving exactly like that. Try to take a look and see if it could fit your purposes: http://code.google.com/p/pyftpdlib/source/browse/tags/release-0.4.0/test/test_ftpd.py > To send a message from the main thread, I append it to a list called > self.sendData. In asyncore.dispatcher, writable() returns True if the > list contains anything, and handle_write() pops the message off the > list and sends it. > > To receive messages, readable() always return True, and handle_read() > breaks up the input into individual messages and appends them to a > list called self.recvData. When the main thread is waiting for a > response, it simply loops until self.recvData contains something. > > To do this asynchronously, for every test I would have to define the > detailed interaction between client and server, and write methods to > be called from within handle_read(). It could be done, but it would be > much more tedious. > > Does this make sense? Now I see why you find it more tedious, in fact I wouldn't use that kind of approach in the test suite. Anyway, I still don't understand why running asyncore.loop into a thread could make any difference. --- Giampaolo http://code.google.com/p/pyftpdlib/ From bignose+hates-spam at benfinney.id.au Sat Jul 26 00:07:52 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 26 Jul 2008 14:07:52 +1000 Subject: binding names doesn't affect the bound objects (was: print doesn't respect file inheritance?) References: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> Message-ID: <8763qtmgo7.fsf@benfinney.id.au> bukzor writes: > I was trying to change the behaviour of print (tee all output to a > temp file) by inheriting from file and overwriting sys.stdout That's not what your code does, though. > def main(): > n = notafile('/dev/stdout', "w") Creates a new instance of the 'notafile' class; the '=' operator then binds that instance to the name 'n'. > import sys Imports a module, and binds the module to the name 'sys'. This includes, usually, the module attribute named by 'sys.stdout'. > sys.stdout = n Re-binds the name 'sys.stdout' to the object already referenced by the name 'n'. No objects are changed by this; only bindings of names to objects. > print "Testing: 1, 2, 3..." Doesn't rely at all on the name 'sys.stdout', so isn't affected by all the binding of names above. In other words, you can't change the object used by the 'print' statement only by re-binding names (which is *all* that is done by the '=' operator). You can, however, specify which file 'print' should use . -- \ ?When I wake up in the morning, I just can't get started until | `\ I've had that first, piping hot pot of coffee. Oh, I've tried | _o__) other enemas...? ?Emo Philips | Ben Finney From iainking at gmail.com Wed Jul 2 10:54:50 2008 From: iainking at gmail.com (Iain King) Date: Wed, 2 Jul 2008 07:54:50 -0700 (PDT) Subject: Win32.client, DAO.DBEngine and exceeding the file sharing count lock References: <5fa3b133-749d-4bac-a6bb-89cb9157e700@d45g2000hsc.googlegroups.com> Message-ID: <9ab0cc2d-5a7e-40ca-a4da-084347f147cd@m36g2000hse.googlegroups.com> On Jul 2, 3:29?pm, Tim Golden wrote: > Iain King wrote: > > Hi. ?I'm using the win32 module to access an Access database, but I'm > > running into the File Sharing lock count as inhttp://support.microsoft.com/kb/815281 > > The solution I'd like to use is the one where you can temporarily > > override the setting using (if we were in VB): > > > DAO.DBEngine.SetOption dbmaxlocksperfile,15000 > > Really hurried answer: > > > import win32com.client > > dao = win32com.client.gencache.EnsureDispatch ("DAO.DBEngine.36") > dao.SetOption (Option=win32com.client.constants.dbMaxLocksPerFile, Value=15000) > > > TJG Thanks. I found this: http://blogs.msdn.com/michkap/archive/2007/07/13/3849288.aspx which outlines some difference between DAO and ADO, including: "Capability to set and change Jet options without making registry changes (works in DAO through DBEngine.GetOption and DBEngine.SetOption, fails in ADO, which has no such analogue)." Now, I'm pretty sure I tried to use DAO before and failed to get it to work, but maybe you could look at my code and suggest the DAO equivalent? --- self._connection = win32com.client.Dispatch(r'ADODB.Connection') self._DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE='+dbfile+';' self._connection.Open(self._DSN) rs = win32com.client.Dispatch(r'ADODB.Recordset') query = 'SELECT '+field+' FROM '+self.__TABLE rs.Open(query, self._connection, 1, 3) while not rs.EOF: v = function(rs.Fields.Item(0).Value) if v != RETAIN_VALUE: rs.Fields.Item(0).Value = v rs.MoveNext() rs.Close() --- aTdHvAaNnKcSe, Iain From Samnsparky at gmail.com Thu Jul 10 12:08:03 2008 From: Samnsparky at gmail.com (Sparky) Date: Thu, 10 Jul 2008 09:08:03 -0700 (PDT) Subject: Local User Control References: Message-ID: On Jul 10, 9:58?am, Tim Golden wrote: > Sparky wrote: > > I don't know how feasible this is, but is it possible to have users > > log in to access a local database file in such a way that allows the > > program to know what user name and password they logged in with? This > > would involve separate user names and passwords for each user. > > Well, this is a question which is crying out for some > context. Are you talking about an existing database > on an existing platform? If so, which one? Are you > talking about a database youo're thinking of building? > If so, the answer's probably yes but only you can > know. Are you talking about something else altogether? > > TJG Thanks for the timely response. This would be a database that I am building myself. The question comes down to is there a feasible way to verify a user's user name and password from inside that database. Obviously the file would be encrypted, but if there is going to be more than one user using it I suppose there would be a separate file for a log-in. I am just asking for some guidance on how this would theoretically be implemented. Thanks again, Sam From rw at smsnet.pl Tue Jul 15 15:34:22 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Tue, 15 Jul 2008 21:34:22 +0200 Subject: logging via SocketHandler and TCPserver References: <81929250-449b-4686-acf3-dcc0095e341a@d1g2000hsg.googlegroups.com> Message-ID: <87tzerndq9.fsf@merkury.smsnet.pl> Larry Bates writes: > Can multiple applications send SocketHandler logging records to the > same socket server on the same port simultaneously? Of course they can. Server can accept requests from many clients. You have used `SocketServer.ThreadingTCPServer`. That server for example handles every request in a different thread. > If so, then I understand your answer completely and will go > in that direction. I guess I was trying to not use up > bandwidth/CPU cycles on the applications that weren't being actively > monitored by just not having the socket server connected to them. > > I think you may be a 'little to close' to the (excellent) application > you have written to understand the steep learning curve that I see. > You know the saying, "Brain surgery is easy to a brain surgeon". I > should point out that I'm no newbie. I've used PIL, ReportLab, > BeautifulSoup, Mechanize, Win32 extensions, ElementTree and a whole > host of other modules with less difficulty. Please don't take this as > anything more than an observation on my part. From what I see, you > have written (and generously donated) an extremely powerful library > and it is greatly appreciated. It is most likely just me. Well, I know what you mean. I had troubles to understand that library either. Logging docs are quite good as a reference, but there is lack of a good introductory tutorial. Now when I know `logging` I can't live without it, but the start wasn't easy. I shouldn't say it here, but I found helpful docs to the similar library in Java. ;) http://logging.apache.org/log4j/1.2/manual.html There are many differences (e.g. Appenders vs Handlers), but the rule is the same. > As far as the book is concerned, I guess I'd purchase the only copy ;-). "The Art of Logging" - four volumes. ;-) Regards, Rob From bignose+hates-spam at benfinney.id.au Thu Jul 10 19:38:48 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 11 Jul 2008 09:38:48 +1000 Subject: Loading just in time References: Message-ID: <87zlops41j.fsf@benfinney.id.au> "D'Arcy J.M. Cain" writes: > Performance optimization wasn't really my goal here. What I was > looking for was the ability to spread the functions around different > files to manage them better from a proggrammer's POV. Why not do that, then? Your functions should be organised into conceptually sensible module groupings. -- \ ?My doctor told me to stop having intimate dinners for four. | `\ Unless there are three other people.? ?Orson Welles | _o__) | Ben Finney From bdesth.quelquechose at free.quelquepart.fr Mon Jul 28 18:58:09 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 29 Jul 2008 00:58:09 +0200 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <488D5B2C.10808@gmail.com> Message-ID: <488e6af8$0$20692$426a74cc@news.free.fr> Nikolaus Rath a ?crit : > Michael Torrie writes: (snip) >> In short, unlike what most of the implicit self advocates are >> saying, it's not just a simple change to the python parser to do >> this. It would require a change in the interpreter itself and how it >> deals with classes. > > > Thats true. But out of curiosity: why is changing the interpreter such > a bad thing? (If we suppose for now that the change itself is a good > idea). Because it would very seriously break a *lot* of code ? From bruno.desthuilliers at gmail.com Thu Jul 17 08:13:23 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 17 Jul 2008 05:13:23 -0700 (PDT) Subject: How can i use a variable without define it ? References: <87k5fm2p1x.fsf@benfinney.id.au> <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> Message-ID: <67dda03d-0d90-47ee-920b-2706a4779f15@x41g2000hsb.googlegroups.com> On 16 juil, 11:06, zhw wrote: > On 7?16?, ??4?47?, Ben Finney > wrote: > > > > > zhw writes: > > > How can i use a variable without define it ? > > > What do you mean by "use"? That's so vague I can think of many > > possible interpretations. > > > What do you mean by "variable"? That term carries a lot of baggage > > that doesn't apply in Python. > > > Can you give a small, complete example that demonstrates the issue > > you're trying to solve? > > > -- > > \ ?The face of a child can say it all, especially the mouth part | > > `\ of the face.? ?Jack Handey | > > _o__) | > > Ben Finney > > Thank you! Sorry for my poor english! > > Here is a example that I want to complete:>>> import sys, new > >>> context={"name":"david", "sex":"male"} > >>> sys.modules["foo"] = new.module("foo") > >>> import foo > >>> for attr in context: > > setattr(foo, attr, context[attr]) > > >>> def bar(): > > # here is a error > # import * only allowed at module level > from foo import * > print name, sex > > >>> bar() Looks like a major WTF to me. What's wrong with: class Person(object): def __init__(self, name, sex): self.name = name self.sex = sex def bar(self): print self.name, self.sex p = Person("david", "male") p.bar() From patf at well.com Mon Jul 28 18:00:42 2008 From: patf at well.com (patf at well.com) Date: Mon, 28 Jul 2008 15:00:42 -0700 (PDT) Subject: Download excel file from web? Message-ID: Hi - experienced programmer but this is my first Python program. This URL will retrieve an excel spreadsheet containing (that day's) msci stock index returns. http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul+25%2C+2008&export=Excel_IEIPerfRegional Want to write python to download and save the file. So far I've arrived at this: [quote] # import pdb import urllib2 from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") # test 1 # xlApp.Workbooks.Add() # xlApp.ActiveSheet.Cells(1,1).Value = 'A' # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B' # xlBook = xlApp.ActiveWorkbook # xlBook.SaveAs(Filename='C:\\test.xls') # pdb.set_trace() response = urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/ excel? priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul +25%2C+2008&export=Excel_IEIPerfRegional') # test 2 - returns check = False check_for_data = urllib2.Request('http://www.mscibarra.com/webapp/ indexperf/excel? priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul +25%2C+2008&export=Excel_IEIPerfRegional').has_data() xlApp = response.fp print(response.fp.name) print(xlApp.name) xlApp.write xlApp.Close [/quote] From alokkat at gmail.com Tue Jul 8 21:07:06 2008 From: alokkat at gmail.com (Alok Kumar) Date: Tue, 8 Jul 2008 21:07:06 -0400 Subject: Python HTTPS Bus Error Message-ID: Hi, Can someone help me what to look for fixing Bus error. I must mention that I am working in embedded environment and it does have selective installation of python I am getting following error from client when it is trying to talk with server over *HTTPS*. HTTP works fine. *Alignment trap: python2.5 (1030) PC=0x4058a738 Instr=0xe5902004 Address=0x000001* *35 FSR 0x001* *Bus error* Server throws SSL handshake failure error. It will be great if someone can throw any pointers. Regards Alok -------------- next part -------------- An HTML attachment was scrubbed... URL: From gary at byoteki.com Mon Jul 28 20:59:26 2008 From: gary at byoteki.com (Gary Josack) Date: Mon, 28 Jul 2008 20:59:26 -0400 Subject: python lists and newline character In-Reply-To: <488E05EA.80800@islandtraining.com> References: <053101c8f0d7$ebd7c340$a601a8c0@office.ipglobal.net> <488E05EA.80800@islandtraining.com> Message-ID: <488E6B6E.2060505@byoteki.com> Gary Herron wrote: > Support Desk wrote: >> >> Hello all, >> >> I am using os.popen to get a list returned of vpopmail >> users, something like this >> >> >> >> x = os.popen('/home/vpopmail/bin/vuserinfo -n -D >> mydomain.com).readlines() >> >> >> >> x returns a list, of usernames, and I am trying to append the >> usernames with the domain like so >> >> >> >> for line in x: >> >> print line + ?@? + domain >> >> >> >> but instead of getting >> >> >> >> user at domain.com >> >> >> >> im getting a newline character like: >> >> user >> >> @domain.com >> >> User >> >> @comain.com >> >> User2 >> >> @domain.com >> >> >> >> >> >> Is there some way I can get this list without the newline characters >> being added. or somehow remove the newline characters. Any help would >> be appreciated. >> > > The problem has nothing to do with lists. The readlines() function > returns each line *with* its newline. To strip it off, use line.strip() > > Gary Herron > >> ------------------------------------------------------------------------ >> >> -- >> http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list Also os.popen is deprecated. You should probably learn subprocess. Thanks, Gary M. Josack From tjreedy at udel.edu Sun Jul 27 17:26:24 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Jul 2008 17:26:24 -0400 Subject: Rant (was Re: x*x if x>10 In-Reply-To: References: <57vo84dk446ul22f6nhogrtpqfjj8um6ls@4ax.com> <6f3fogF9jpidU1@mid.uni-berlin.de> <6f3qjoF9n3cpU1@mid.uni-berlin.de> Message-ID: DaveM wrote: > On Sun, 27 Jul 2008 19:46:32 +0200, "Diez B. Roggisch" > wrote: >> As a rule of thumb, don't return objects you didn't create inside a >> function from scratch. Unless its job is specifically to get/fetch an object (reference thereto) from someplace the caller cannot or should not access. But then it should probably not mutate the object before returning the reference. > > I wish I'd had that advice when I started learning python. It would have > saved me no end of grief. I wish I had seen this 'rule' before too. From robert.kern at gmail.com Wed Jul 23 21:18:32 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 23 Jul 2008 20:18:32 -0500 Subject: fill in 3D array In-Reply-To: <3180f972-f2d4-43ff-81de-bcdd0a2ef906@59g2000hsb.googlegroups.com> References: <3180f972-f2d4-43ff-81de-bcdd0a2ef906@59g2000hsb.googlegroups.com> Message-ID: knielsen73 at gmail.com wrote: > Hi, > > I am a python newbie, trying to convert my IDL scripts to python. I am > kind of stuck at the moment. I am reading in a 1-D data file with 2000 > data points. I need to put them in a 3-D array with size [10,10,20]. I > have defined the field array as arr = zeros((10,10,20)) but don't know > how to read the data into the array. I assume that you are using numpy. Use numpy.fromfile() and the .reshape() method. Assuming that your file is ASCII with numbers separated by whitespace: import numpy arr = numpy.fromfile(thefilename, sep=' ').reshape((10,10,20)) There is no need, in this case, to create an array before reading the data. > Also, I need to extract a slice of a 3-D array and tried a = > array_name(:,:,20) but that didn't work. Python uses [] brackets for indexing, not (). arr[:,:,20] -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ki4yjl at gmail.com Fri Jul 11 12:59:03 2008 From: ki4yjl at gmail.com (WDC) Date: Fri, 11 Jul 2008 09:59:03 -0700 (PDT) Subject: Using the Random Module. Message-ID: I am currently learning, and loving, Python and have a question about random(). Right now, what I have to do to get a whole number and not a decimal using random.random() is this: >>>random.random() 0.84765728501856734 >>>_ * 10**17 84765728501856734.0 Is there a better way to do that besides doing this: >>>random.randint(00000000000000000, 99999999999999999) 09657398671238769 Thanks for your time. David From alif016 at gmail.com Fri Jul 18 22:04:36 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Fri, 18 Jul 2008 21:04:36 -0500 Subject: trying to match a string In-Reply-To: <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> Message-ID: <48814BB4.700@gmail.com> oj wrote: >>> Why not just use * instead of + like: >>> >>> if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of >>> string; $ means end of string >>> print "Invalid" >>> >>> This will *only* print invalid when there is a character other than L, >>> R, or M or a empty string. >>> >> Sorry, forget the beginning and ending markers, I just tried it out, it >> doesn't work. >> use this instead: >> >> if re.search(r'[^LRM]*', var): >> print "Invalid" >> > > No, that's broken. > > That searches for any number of invalid characters. Even 0, so it > ALWAYS matches, no matter what string you give it. > > My regex worked in the first place, you're complicating it needlessly. > The presence of one invalid character makes the string invalid, so why > not just search for one? Similarly, there's no need to stick in the > beginning and end markers - you're not trying to match the entire > string, just find part of it that is invalid. > > However, I think the sets solution by Scott David Daniels is the most > elegant method put forward. > -- > http://mail.python.org/mailman/listinfo/python-list > I see your point after rereading the question, he only wants to match L R and M let me revise it please: To show if valid: if re.search(r'^[LRM]*$', 'LM'): print 'Valid' To show if invalid, if re.search(r'^[^LRM]*$', '0'): print 'Inalid' Example session: >>> import re >>> def match(var): >>> if re.search(r'^[LRM]*$', var): ....... print 'Valid' ....... else: ....... print 'Invalid' >>> >>> eg = 'LRLRLRLRLM' >>> match(eg) Valid >>> fg = 'LRLRLRNL' >>> match(fg) Invalid -- Andrew From stodge at gmail.com Fri Jul 4 12:18:33 2008 From: stodge at gmail.com (Stodge) Date: Fri, 4 Jul 2008 09:18:33 -0700 (PDT) Subject: Boost Python - C++ class' private static data blown away before accessing in Python? Message-ID: I've exposed a C++ class to Python using Boost Python. The class, let's say it's called Entity, contains private static data, which is an array of strings. Though I think it implements it using MFC's CPtrArray. I've also exposed a public function from Entity - let's say it's called foo. This function accesses the private static data (the string array). I have multiple instances of Entity stored in a custom C++ container, which is also exposed to Python as class EntityList. In Python, I retrive an Entity from the EntityList: elist = EntityList() elist.append(Entity()) elist.append(Entity()) entity = elist.get_at(0) entity.foo() But it crashes inside foo() as the private static data is empty; or rather the string array is empty. I know before that point that the private static data is valid when accessed earlier by the C++ code as the program works fine. It just won't work from Python, so somehow the private static data has been blown away but I can't work out where or why. The static data is setup at initialisation - my Python code is only called long after initialisation is complete. I added a static dump() function to the Entity class that dumps the string array, and even if I just do the following in Python: Entity.dump() in Python, the private static data is empty. Doing the same from C++ works fine. Weird. I know this is an impossible question to ask, but can anyone think of something obvious I need to look into? Thanks From gcmartijn at gmail.com Sat Jul 5 04:12:04 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Sat, 5 Jul 2008 01:12:04 -0700 (PDT) Subject: pythoncom InternetExplorer.Application don't work in vista || firefox pythoncom ? Message-ID: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> H! I using a script that opens a internet page in a small window (what I can control) In XP everything was working fine, but now I'm using Vista with IE7 and this is what happends now: First a small window opens at the postion x0 y0 (like I want) but then IE thinks "Hey lets open a other main window too". And that window opens the url 'http://www.google.nl' It seems that I can't control/use my first window anymore, and that IE7/vista is forcing to open it in a big new window. The code below is what I'm using. def webbrowser(url=None): import pythoncom from win32com.client import Dispatch ie = pythoncom.CoCreateInstance("InternetExplorer.Application", None,pythoncom.CLSCTX_SERVER,pythoncom.IID_IDispatch) ie = Dispatch(ie) ie.Top = 0.0 ie.Left = 0.0 ie.Height = 400 ie.Width = 400 ie.AddressBar = False ie.MenuBar = False ie.Resizable = False ie.StatusBar = False ie.ToolBar = False ie.Visible = 1 return ie w = webbrowser() w.Navigate('http://www.google.nl') -- ow and why can't I find a pythoncom.CoCreateInstance.FireFox example ? Thanks for helping. From sjmachin at lexicon.net Sun Jul 13 19:15:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 13 Jul 2008 16:15:47 -0700 (PDT) Subject: Mutually referencing imports -- impossible? References: Message-ID: <4ce90db0-3ed3-4525-b1a3-a59851b37d30@f63g2000hsf.googlegroups.com> On Jul 14, 3:55 am, Matthew Wilson wrote: > I started off with a module that defined a class Vehicle, and then > subclasses Car and Motorcycle. > > In the Car class, for some bizarre reason, I instantiated a Motorcycle. > Please pretend that this can't be avoided for now. > > Meanwhile, my Motorcycle class instantiated a Car as well. > > Then I moved the Car and Motorcycle classes into separate files. Each > imported the Vehicle module. > > Then I discovered that my Car module failed because the global > Motorcycle wasn't defined. The same problem happened in my Motorcycle > module. Car and Motorcycle can't both import each other. And they should not import each other. > > In the beginning, when all three (Vehicle, Car, and Motorcycle) were > defined in the same file, everything worked fine. You seem to have a strange notion of "worked fine". > > I don't know how to split them out in separate files now though and I > really wish I could because the single file is enormous. What is making a file with 3 classes "enormous"?? What is "enormous"? > > Any ideas? *WRONG WAY* *GO BACK* Your structure is not only bizarre, it is also (sticking with only 1 letter of the alphabet) a Byzantine, baroque, and broken concept. Asking us to "pretend that this can't be avoided for now" is asking us to aid and abet you in creating a meaningless and unmaintainable monster. Consider adding Truck and Bus subclasses. Will each subclass instantiate the other 3??? You should be able to add or remove a subclass without having to modify all other subclasses. The only rational solution is not to have the subclasses refer to each other. Tell us *why* you think you need to have Car refer to Motorcycle and vice versa, and we should be able to help you find a way out. Cheers, John From deets at nospam.web.de Fri Jul 25 10:28:20 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 25 Jul 2008 16:28:20 +0200 Subject: Calling external program from within python In-Reply-To: References: Message-ID: <6eu684F91muhU1@mid.uni-berlin.de> Mike Driscoll schrieb: > On Jul 25, 7:56 am, Emmanouil Angelakis > wrote: >> Hi, >> >> I am tryiong to do something obviously trivial such as: >> I have a c program called "tsys2list" that when it is ran it asks the user to give the value of "tcal" which is a variable. I want to call the "tsys2list" from within a pyrthon script lets call it "gamma.py" >>>but<<< I want to pass the value of "tcal" to th eprogram automatically and not by interacting with the keyboard. >> >> How do I do that? >> >> thanks i advance! >> manolis > > There are probably many ways to do this. I would recommend checking > out the subprocess module and see if it does what you want. This will only work if the program can be fully controlled by commandline arguments. If interaction is required, the OP might consider using pexpect. > Or you > could learn a little Tkinter or wxPython and use that to get the > user's variable. Or you could even do it via the command line using > the "raw_input" command. I fail to see how *gathering* input (regardless of the method) solves the problem of *passing* input to a subprocess. Diez From modelnine at modelnine.org Wed Jul 30 03:03:49 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Wed, 30 Jul 2008 09:03:49 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> Message-ID: <200807300903.49378.modelnine@modelnine.org> Am Mittwoch, 30. Juli 2008 08:30:48 schrieb Russ P.: > On Jul 29, 11:09 pm, Erik Max Francis wrote: > > I'm getting this sneaking suspicion that you guys are all putting us on. > > As I said in an earlier post, I realize that this would only work if > there were only one copy of "empty" (as there is only one copy of > "None"). I don't know off hand if that is feasible or not. > > You reply reeks of the kind of pedantic snobbishness that makes me > sick. I can understand (and pretty much sympathise) that you get this kind of reply, simply because the point you and Carl Banks (formulated somewhat differently) put up has been answered again and again (in this thread), and I can only repeat it once more: __nonzero__(), i.e. the "cast" to boolean, is THE WAY to test whether a container is empty or not. Like this design decision, or don't like it, but the discussion is not going to go anywhere unless you concede that there is a (very explicit!) way to test for non-emptiness of a container already, and you're currently simply discussing about adding/using syntactic sugar (different means of expressing the test) to suit your own personal taste better. Anyway, check the documentation for __nonzero__(): if the object doesn't implement that, but implements __len__(), the interpreter "replaces" the __nonzero__() test by __len__()>0, so I guess someone in the design department must've seen it logical for the truth value of a container to express the test "len(x)>0" at some point in time to make this interpretation for the truth value of a container. There cannot be an argument about missing/misplaced functionality (that's what you make it sound like), if the functionality for doing what you want to do is there and you simply don't like the syntax, which I can somewhat relate to because style is a personal thing, even though I don't see either points made by you or Carl Banks, because implicit casting to bool is so common in pretty much every programming language to test for "truth" of an object, and IMHO it's completely logical to extend that idea to containers to mean empty/non-empty. Eric Max Francis tried to explain why your syntactic "enhancement" would come at a much greater price than its worth, and he's absolutely right in that, as it's an abuse of the "is" operator, but again, that's a somewhat different point. It changes nothing about the fact that all this discussion centers around something that is a non-point, but simply a matter of personal taste. -- Heiko Wundram From fredrik at pythonware.com Wed Jul 23 07:10:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 13:10:38 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> Message-ID: Jaco Naude wrote: > What Visual C++ is doing is that it is looking for mangled names since > it does not know the DLL contains C functions. I've managed to work > around this by declaring the Python functions as follows before using > them in the C++ application side: > > extern "C" > { > void Py_Initialize(void); > } > > This seems to work and the C++ application side is not looking for > mangled names any more. Is this the right way of doing it? It seems > unnecessary to have to declare each Python function you want to use > using the extern "C" way as shown above. Eh, are you saying that you're not including the Python.h file? Because it does exactly that, for each and every public function in the C API. > It is probably more of a C++ question it turns out, but I would think > that someone in the Python group would use the Python DLL in C++. The > documentation also suggest that there is no extra work needed when > using C++ rather than C. Oh, but I do that all the time, without doing any extra work. Both embedding Python in C++ programs and existing it with C++ extensions. And I'm definitely not alone. Here's an actual session, using the version of Visual Studio I happen to have on this machine (2003, I think) from the command line: > more test.cc #include "Python.h" #include main() { Py_Initialize(); PyRun_SimpleString("print 'hello'\n"); Py_Finalize(); std::cout << "world\n"; } > cl cl -EHsc -MD -I \python25\include test.cc \python25\libs\python25.lib Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80x86 Copyright (C) Microsoft Corporation 1984-2002. All rights reserved. ... > test hello world If you cannot get the same console program to work in your compiler setup, something's wrong with your configuration. From fredrik at pythonware.com Sat Jul 19 15:04:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 19 Jul 2008 21:04:06 +0200 Subject: regex doubts In-Reply-To: <532965.570.qm@web54502.mail.re2.yahoo.com> References: <532965.570.qm@web54502.mail.re2.yahoo.com> Message-ID: Mr SZ wrote: > I am taking a string as an input from the user and it should only > contain the chars:L , M or R > > I tried the folllowing in kodos but they are still not perfect: > > [^A-K,^N-Q,^S-Z,^0-9] > [L][M][R] > [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > > For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. try "[LRM]+$" (an L or an R or an M, one or more times, all the way to the end of the string). From fredrik at pythonware.com Sun Jul 20 11:48:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jul 2008 17:48:58 +0200 Subject: Web Server In-Reply-To: References: Message-ID: misceverything at gmail.com wrote: > As part of a Python app I wrote recently (for Windows), I would like > to give the option of an HTTP (HTTPS if possible, but not necessary) > front end, which would then call some existing python scripts. My > question is - I know I can write a simple HTTP server in Python, but > if there's something simple already out there, I'd prefer to just use > that. Basically all I need is a simple (i.e. preferably a single > executable) web server that can serve up my content - the only thing I > want the user to be able to configure is the port the web server > listens on (or ports if HTTPS also), and the location of the HTML > files... thanks in advance for your help. import SimpleHTTPServer ? sample code here: http://effbot.org/librarybook/simplehttpserver.htm From asmodai at in-nomine.org Thu Jul 10 13:50:45 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 10 Jul 2008 19:50:45 +0200 Subject: Fwd: [ANN] Babel 0.9.3 released Message-ID: <20080710175045.GR68329@nexus.in-nomine.org> ----- Forwarded message from Christopher Lenz ----- From: Christopher Lenz To: python-babel at googlegroups.com Cc: cldr-users at unicode.org Subject: [ANN] Babel 0.9.3 released Date: Thu, 10 Jul 2008 11:26:23 +0200 X-Mailer: Apple Mail (2.926) Babel 0.9.3 - Jul 9, 2007 ========================= We're proud to present the latest release of the Babel: 0.9.3. Babel is a Python library that provides an integrated collection of utilities that assist with internationalizing and localizing Python applications (in particular web-based applications.) This release contains a number of bugfixes over the 0.9.2 release. You can download the new release here: Please don't hesitate to report any issues you may find with this release: For questions, comments and user discussions, please use the Babel mailing list: What's New: ----------- * Fixed invalid message extraction methods causing an UnboundLocalError. * Extraction method specification can now use a dot instead of the colon to separate module and function name (ticket #105). * Fixed message catalog compilation for locales with more than two plural forms (ticket #95). * Fixed compilation of message catalogs for locales with more than two plural forms where the translations were empty (ticket #97). * The stripping of the comment tags in comments is optional now and is done for each line in a comment. * Added a JavaScript message extractor. * Updated to CLDR 1.6. * Fixed timezone calculations when formatting datetime and time values. * Added a `get_plural` function into the plurals module that returns the correct plural forms for a locale as tuple. * Added support for alias definitions in the CLDR data files, meaning that the chance for items missing in certain locales should be greatly reduced (ticket #68). Acknowledgments ---------------- A big thank you to everyone who tried Babel and provided feedback, reported bugs, and/or contributed patches! Cheers, Chris -- Christopher Lenz cmlenz at gmx.de http://www.cmlenz.net/ ----- End forwarded message ----- -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B No man is good enough to govern another man without the other's consent... From bignose+hates-spam at benfinney.id.au Tue Jul 29 19:27:00 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 30 Jul 2008 09:27:00 +1000 Subject: static variables in Python? References: Message-ID: <87prowff0b.fsf@benfinney.id.au> kj writes: > Is there a way to mimic C's static variables in Python? Or something > like it? A "static variable" in C is one that has access limited to the scope in which it is declared. Python approaches the same issue through namespaces: a name binding made at a class or module level is accessible only via specification of the class or module namespace. > The idea is to equip a given function with a set of constants that > belong only to it, so as not to clutter the global namespace with > variables that are not needed elsewhere. Python functions have local name bindings by default . Python doesn't have "variables" in the sense of boxes containing values, so it doesn't have "constants" in the sense of boxes that don't change. Instead, Python has names bound to objects like sticky notes. A name can later be re-bound to some other object. What use case are you trying to address? It seems that the normal use of local function names and class attributes would serve your described requirements. -- \ ?It is hard to believe that a man is telling the truth when you | `\ know that you would lie if you were in his place.? ?Henry L. | _o__) Mencken | Ben Finney From vinay_sajip at yahoo.co.uk Tue Jul 15 09:56:15 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 15 Jul 2008 06:56:15 -0700 (PDT) Subject: Logging in __del__() References: <17056.2125546441$1216121658@news.gmane.org> Message-ID: On Jul 15, 1:51 pm, "Robert Rawlins" wrote: > > Am I right in thinking that Python destroys instances of classes when it > deems they are no longer needed? I shouldn't have to explicitly delete the > classes, right? Python uses reference counting with a cycle detector, but the detector's behaviour is different if there are finalizers (__del__) - see http://www.python.org/doc/ext/refcounts.html Regards, Vinay Sajip From goldfita at gmail.com Mon Jul 7 11:22:12 2008 From: goldfita at gmail.com (goldfita at gmail.com) Date: Mon, 7 Jul 2008 08:22:12 -0700 (PDT) Subject: python mysteriously halts References: <13a33043-21d1-40c0-a938-6e905d958064@m3g2000hsc.googlegroups.com> Message-ID: On Jul 7, 10:17?am, Tim Golden wrote: > Todd wrote: > > I ran a python script last night which connects to a matlab automation > > server via DCOM (using win32com). ?I expected to see the results when > > I came in this morning. ?But apparently, not long after I left, python > > stopped. ?I hit enter in the console, and it started again. > > Symptomatically, at least, this can be caused by someone starting to > select (with the mouse) an area of the screen: the process will pause > until is pressed, which copies the area to the clipboard. This > only happens with a console window, but it sounds like that's what > you had running. > > TJG That might be it, although I don't recall doing that. Fortunately/ unfortunately, it happened a few times, but it seems to have stopped now. From gptutorsx at gmail.com Wed Jul 23 03:33:00 2008 From: gptutorsx at gmail.com (smartx) Date: Wed, 23 Jul 2008 00:33:00 -0700 (PDT) Subject: game programming Message-ID: <8890c74b-e92c-4dfd-9a3a-4399f83a42c2@x35g2000hsb.googlegroups.com> Game programming became as a box of art and science, the box contains a lot of arts, musics, sounds, graphics,scenario, math, ai and physics ...etc. great department, great skills, great tips, also you can observe your source is the internet that has a lot of articles a lot of great sites like gamedev.net, gameinstitute.com, gametutorials.com. all of these encourage you to be a professional game programmer, for me I love it so much, it's important to love something, because this will help you to develop yourself in this domain, I hope for all the best wishes in game development's journey. Best wishes for all, smartx gptutors.com From mwilson at the-wire.com Tue Jul 1 09:15:27 2008 From: mwilson at the-wire.com (Mel) Date: Tue, 01 Jul 2008 09:15:27 -0400 Subject: problem with exec and locals() References: <95f07476-e3c8-45e4-82b3-0e48c9188f8e@79g2000hsk.googlegroups.com> Message-ID: rocksportrocker wrote: > > Hi, > > the following code does not work until I ommit the "a=0" statement. > > > def test(): > exec "a=3" in locals() > print a > a=0 > > test() > > print raises: > UnboundLocalError: local variable 'a' referenced before > assignment > > Can anybody explain what is going wrong here ? AFAIK, local variables are implemented rather like __slots__ in new-style classes. This is a very valuable efficiency measure, but it can cause this kind of trouble. Without `a=0`, the bytecode compiler makes no slot for a, and dis.dis shows the following bytecode for test: >>> dis.dis (test) 2 0 LOAD_CONST 1 ('a=3') 3 LOAD_NAME 0 (locals) 6 CALL_FUNCTION 0 9 DUP_TOP 10 EXEC_STMT 3 11 LOAD_NAME 1 (a) 14 PRINT_ITEM 15 PRINT_NEWLINE 16 LOAD_CONST 0 (None) 19 RETURN_VALUE At address 11, LOAD_NAME 1(a) gets the value that was set by exec. With a=0, the code is >>> dis.dis(test2) 2 0 LOAD_CONST 1 ('a=4') 3 LOAD_NAME 0 (locals) 6 CALL_FUNCTION 0 9 DUP_TOP 10 EXEC_STMT 3 11 LOAD_FAST 0 (a) 14 PRINT_ITEM 15 PRINT_NEWLINE 4 16 LOAD_CONST 2 (0) 19 STORE_FAST 0 (a) 22 LOAD_CONST 0 (None) 25 RETURN_VALUE and here, the value of a is found in slot 0 via LOAD_FAST. Slot 0 is used because a=0 forced a to be a local variable. Apparently, exec in locals() knows nothing about slots (because locals() is the only dictionary in the universe where slots would be involved ? -- perhaps not, but close). Mel. From dominic.rice at gmail.com Fri Jul 4 20:10:37 2008 From: dominic.rice at gmail.com (Dominic Rice) Date: Sat, 05 Jul 2008 01:10:37 +0100 Subject: running python from cmd.exe References: Message-ID: John Machin wrote: > On Jul 5, 7:38 am, Dominic Rice wrote: >> Chris Hulan wrote: >>> On Jul 4, 5:38 am, Dominic Rice wrote: >>>> Dominic Rice wrote: >>>>> Miki wrote: >>>>>> Hello, >>>>>>> I can't seem to get python to run my scripts using the command: python >>>>>>> .py >>>>>>> If I type python the interpreter runs as I sorted out the Path property, >>>>>>> I'm afraid I don't know much about this kind of thing as I'm a science >>>>>>> student who needs some Python not a programmer! >>>>>> Can you be more specific about the error you get? >>>>>> Say you have a script hw.py that contains one line: >>>>>> print "Hello Python" >>>>>> and you run >>>>>> python hw.py >>>>>> What is the error you get? >>>>>> HTH, >>>>>> -- >>>>>> Miki >>>>>> http://pythonwise.blogspot.com >>>>> Sure, I get: >>>>> can't open file .py: [errorno 2]No such file or directory. >>>>> Now if I've noticed that if I change directory to (for instance) >>>>> \Python25 where the script is the command runs fine.(?) >>>> Oh I just noticed you specified hw.py, in that case just to clarify it >>>> would be can't open file hw.py: [errorno 2]No such file or directory >>> When you run a script, are you in the directory where the script is >>> located? >> when it works yes! Does it have to be the case then? I assumed that >> there was a default folder (eg \Python25) that the python command would >> look for the file in, I take it this is not the case then? > > The default folder *is* the "current" folder, i.e. "the directory that > you are in". If you want to run a script in another folder, you > specify the path to that script. This is usual in Windows command-line > operation, not special to Python. > > By the way, storing your own files in the same folder structure as a > software package (e.g. \Python25) is not a good idea. Keep them > somewhere else e.g. a separate folder for each significantly different > project, a folder for commonly useful stuff, and a junk folder for > mucking about trying things out. Then when e.g. you upgrade to Python > 2.6 the possibility of drama is reduced. > > HTH, > John seems like very good advice, many thanks! From mail at timgolden.me.uk Wed Jul 16 15:20:29 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 20:20:29 +0100 Subject: About wmi In-Reply-To: <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> <487E1AD4.9020509@timgolden.me.uk> <154fb80b-da69-4ebf-8549-7b992b730c1b@26g2000hsk.googlegroups.com> Message-ID: <487E49FD.7050005@timgolden.me.uk> patrol wrote: > On 7?17?, ??12?16?, Tim Golden wrote: >> Assuming that the error comes back in the sys.stdout encoding, the following version *should* work ok. I still haven't got a non-English set up to test it on, but it certainly does return a Unicode error message. >> >> http://timgolden.me.uk/wmi-project/wmi.py >> >> The usual test case, if you wouldn't mind: >> >> >> import wmi >> >> wmi.WMI ("non-existent computer") >> >> >> >> should give a (language-specific) error message, not an UnicodeDecodeError >> >> TJG > -------------------------------------------------------------------------------------- >>>> import wmi >>>> wmi.WMI('non-existent computer') > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\wmi.py", line 1199, in connect > handle_com_error (error_info) > File "C:\Python25\lib\wmi.py", line 184, in handle_com_error > exception_string = [u"%s - %s" % (hex (hresult_code), > hresult_name)] > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > 4: ordinal > not in range(128) > -------------------------------------------------------------------------------------- > yup,error_info contains the Chinese encoded string. All of the Simple > Chinese Windows use the CP936.Every Chinese word utilizes two > bytes.Maybe you can fix this bug by modifying handle_com_error. Can you confirm that that last bit of code was run with the version of wmi.py currently at: http://timgolden.me.uk/wmi-project/wmi.py That version should already be decoding the string correctly. TJG From jiri.zahradil at gmail.com Mon Jul 7 03:23:33 2008 From: jiri.zahradil at gmail.com (jiri.zahradil at gmail.com) Date: Mon, 7 Jul 2008 00:23:33 -0700 (PDT) Subject: Python with Ecmascript References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> <8ek074tia4l47tcfo6tqfo9huv2hb68hkt@4ax.com> <7eaf458d-b355-4112-a947-b2b7fe0d1f8d@s50g2000hsb.googlegroups.com> Message-ID: On 7 ?ec, 08:21, alex23 wrote: > On Jul 7, 12:31 am, "jiri.zahra... at gmail.com" > > wrote: > > I personally does not like COM solution. I prefer some simple library > > but may be it is just a hope. > > Have you looked at the module 'python-spidermonkey'? It apparently > "allows for the implementation of Javascript classes, objects and > functions in Python, as well as the evaluation and calling of > Javascript scripts and functions". > > http://code.google.com/p/python-spidermonkey/ I have looked at it. It seems to be not fully working version, but I have not check it properly because the project homepage says "windows version is forthcoming". At this time I am considering using some command line interpreter (maybe jsdb, http://www.jsdb.org/, based on spidermonkey) Idea is to save script code to file and let it run by interpreter and then parse the results. Problem is that this approach has very limited access to variables and objects exposed to javascript (they needs to be serialized before script run, script cannot call python functions etc) and also retrieving results is not straigtforward. Still looking for better solution ... JZ From alan.isaac at gmail.com Tue Jul 22 23:13:37 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Wed, 23 Jul 2008 03:13:37 GMT Subject: sys.stderr.write returns string length in Python 3 In-Reply-To: <43ab2eb4-31ec-4574-ab54-4467fa89d187@27g2000hsf.googlegroups.com> References: <43ab2eb4-31ec-4574-ab54-4467fa89d187@27g2000hsf.googlegroups.com> Message-ID: Benjamin wrote: > http://www.python.org/dev/peps/pep-3116/. Thanks. Can you give me an example of using the returned value? Alan From elessar at nienna.org Wed Jul 30 12:25:58 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Wed, 30 Jul 2008 10:25:58 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> Message-ID: <48909616.6050004@nienna.org> Carl Banks wrote: > On Jul 29, 6:42 pm, Matthew Fitzgibbons wrote: >> Carl Banks wrote: >>> Much like in Steven D'Aprano's example, still the only actual code >>> snippet I've seen, it seems that this can easily be done with a simple >>> explicit test by having all no-advance filters return None and testing >>> with "if x is not None". So it doesn't pass my criterion of being not >>> replaceable with simple explicit test. >>> Maybe that's not workable for some reason. Perhaps if you'd post a >>> code example that shows this, rather than just talking about it, you >>> might be more persuasive. >>> Carl Banks >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> The no-advance filters have to return the object because I don't just >> forget about it; I evaluate whether I pass it to the next filter or drop >> it in a completely different queue for use in the next stage of the >> operation. True means 'I'm ready to move on to the next stage,' False >> means 'Do the filter thing some more.' > > I think I see what you're saying, and yeah I guess that could really > take advantage of polymorphism between very different types. > >> Furthermore, the argument that I should just change my API to make a >> 'simple test' work is not very convincing. > > I wasn't suggesting you change it: I was trying to ascertain whether > it would have suffered much if you had written it with explicit tests > in the first place, or if Python didn't even have magical booleans. Yes it would have suffered. I chose the implementation I did because it made the most sense to me and was the most flexible (a key requirement). Instead of cobbling together my own way, I used the way that Python gave me. Python doesn't have magic booleans. They are instead a very well-defined language mechanism that isn't perfect for every circumstance, but is pretty good for the most part. I wanted to do meaningful boolean tests on various objects, so I used the mechanism that my language gave me. > >> The natural, obvious way for >> a filter to work is to pass through the data it operates on; why on >> Earth would it return None? I want to DO something with the data. In >> this case, make a decision about where to pass the data next. > > If you don't mind me asking: what do you do actually DO with a zero or > empty list? Depends on exactly what the next stage is. Typically, zeros and empty lists are not meaningful for the next stage, so they get dropped then if they make it through. I don't want to restrict what gets passed through, though, because I could end up with several meaningful data types, making a simple test again impossible. So I pass everything through and let the next stage decide. > >> In Java, >> to accomplish this I would have to do lots of introspection and value >> checking (adding more any time I came up with a new kind of input), or >> make a new kind of interface that gives me a method so I can do a >> 'simple test' (including wrappers for ints and arrays and anything else >> I decide to pass in down the road). But Python supports duck typing and >> gives me a handy __nonzero__ method; I can rebind __nonzero__ in my >> filters for my own classes, and ints and lists are handled how I want >> them to be by default. So why jump through hoops instead of just using >> 'if x'? > > Ah, so it's just happens to work. Still, just happening to work > works. (shrug) Nonono. The point you seem to be missing is that 'if x' is very well defined. There is nothing magic or arbitrary about what it does. It works here and elsewhere because Python (a) chooses good default behavior (its treatment of lists and ints, etc) and (b) gives you a way, __nonzero__, to change the behavior to suit your needs. > >> I don't have any postable code (it's in a half way state and I haven't >> touched it for a while), but I'll see if I can't find the time to bang >> something up to give you the gist. > > I wouldn't bother at this point. I was looking to see if someone > could come up with something to disprove my belief on the polymorphic > uselessness of "if x" relative to explicit tests, and if (as I > anticipated) they did not, I could claim that "if x" is really just a > glorified keystroke saver. But I now realize that the failure of this > bunch doesn't prove anything. I don't think most people even realize > why answering the question I asked would demonstrate the usefulness of > "if x". Of course you don't _need_ to have 'if x'; after all, REAL programmers code in machine language. The whole point of a high-level language is to make life easier. Python is very dynamic and allows duck typing so that you can use these tools to do clever things that would otherwise be very difficult. It even gives you a handy polymorphic mechanism to do boolean tests, which my example illustrates. You asked for a use case for a polymorphic 'if x' that can't be easily replaced by a simple test. I gave one. Then you asked for a code sample, but now have dismissed my sample as not compelling without having seen it. But here it is anyway (attached). It's pretty rough since I just threw it together. I'm sure there are mistakes. I also dropped the DAG, where all the queueing and decision making is handled in the actual program. The filters and data are arbitrary but should illustrate the setup. You care about line 66. Again, the same thing could be accomplished in various ways; but keep in mind that data could be _anything_, so you can't easily rewrite line 66. > > Your example isn't exactly the smoking gun I was looking for, but I > guess we'll have to admit that at least one usage will suffer for not > having it. > > > Carl Banks > -- > http://mail.python.org/mailman/listinfo/python-list > So you hypothesized that you can easily rewrite any 'if x' as a simple, explicit test. I produced an example that shows this cannot be done; therefore your hypothesis is not correct. For most cases, you can come up with a simple test, even if it's not the best way to implement you problem. But other times, the poylmorphic, duck typing behavior of 'if x' allows you to make your problem much easier, in a way a simple test can't. To deny this fact is to deny to power of dynamic languages in general. -Matt -------------- next part -------------- A non-text attachment was scrubbed... Name: filterex.py Type: text/x-python Size: 4647 bytes Desc: not available URL: From bj_666 at gmx.net Sat Jul 19 12:28:16 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Jul 2008 16:28:16 GMT Subject: MethodChain References: Message-ID: <6eej10F6k7g3U2@mid.uni-berlin.de> On Sat, 19 Jul 2008 08:55:23 -0700, bearophileHUGS wrote: > Found from Reddit, it's for e ECMA(Java)Script, but something similar > may be useful for Python too: > > http://jsclass.jcoglan.com/methodchain.html > http://blog.jcoglan.com/2008/07/16/where-did-all-my-code-go-using-ojay-chains-to-express-yourself-clearly/ What's called `MethodChain` there seems to be function composition in functional languages. Maybe `functools` could grow a `compose()` function. Ciao, Marc 'BlackJack' Rintsch From svenn.bjerkem at googlemail.com Tue Jul 29 13:54:54 2008 From: svenn.bjerkem at googlemail.com (Svenn Are Bjerkem) Date: Tue, 29 Jul 2008 10:54:54 -0700 (PDT) Subject: Parsing VHDL with python, where to start. References: <31888260-86a9-46b0-b0a4-79f7852f256a@k30g2000hse.googlegroups.com> <488F33E9.8090004@ericsson.com> Message-ID: <4e02f7d1-b342-4413-be4b-525f273e0d5f@56g2000hsm.googlegroups.com> On Jul 29, 5:14 pm, Wolfgang Grafen wrote: > For me it is not very clear what you intend to do. After years of > parsing parts of VHDL from time to time the rapid parsing way for me is > using regular expressions instead of one of the parser frame works > because of following reasons: > > - It is hard for me to understand those frameworks > - They are very slow > - It is too much work for me to bring them up to work in a sensible way > - Compared with regular expression matching they usually need a lot of > extra work. I agree with frameworks being difficult to understand and that is why I also have been using regular expressions in tcl to parse spice netlists before. Now I want to parse spice, vhdl and also maybe verilog. I think I will end up with regular expressions unless I get a grip on SimpleParse. The rationale for the whole project has been to finally be able to view spice and specially vhdl code for projects I work on. This has been something I have wanted to have for years, without having the ressources to complete it. There are commercial tools available, but I was looking for something more open/free that could be maintained independently of what tools I have at work. > PyQt as a widget framework is not useful until here, but of course you > could display your results in arbitrary graphical ways with PyQt, if you > rally need to. You should know, printing out an ASCII or XML > representation is so much more easy and quicker to code so I always > prefer that. There are even editors/visualizers ready to display XML... PyQt4 doesn't help me parse my sources, but it helps me visualise them. I did something in tcl/tk to get hierarchical spice netlists into a tree structure, but extending that app was too much hassle. PyQt4 offers a lot of functionality once the threshold of learning it has been passed. It also installs nicely on windows and most linux distributions offer it ready to install. And I like Qt. -- Svenn From zapwireDASHgroups at yahoo.com Mon Jul 14 22:24:54 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Mon, 14 Jul 2008 19:24:54 -0700 Subject: One step up from str.split() References: <2f7e2895-e1ee-4113-a6bf-a3a15235f27c@w7g2000hsa.googlegroups.com> Message-ID: Thanks Matt, that looks like just what I want! From gros_bedo at hotmail.com Sun Jul 13 14:59:04 2008 From: gros_bedo at hotmail.com (Gros Bedo) Date: Sun, 13 Jul 2008 20:59:04 +0200 Subject: Terminate a python script from linux shell / bash script Message-ID: Thank you guys for your help. My problem is that I project to use this command to terminate a script when uninstalling the software, so I can't store the PID. This command will be integrated in the spec file of the RPM package. Here's the script I'll use, it may help someone else: #!/bin/sh # PYTHON SCRIPT PROCESS KILLER by GBO v0.1 # This script will look for all the lines containing $SOFTWARENAME in the process list, and close them SOFTWARENAME='yoursoftware' #This is case insensitive JOBPRESENT=$(ps -ef | grep -i $SOFTWARENAME | grep -v grep) echo $JOBPRESENT ps -ef | grep -i $SOFTWARENAME | grep -v grep | awk '{print $2}' | xargs kill _________________________________________________________________ Pendant tout l'?t?, consultez vos emails Hotmail sur votre mobile ! http://www.messengersurvotremobile.com/?d=hotmail From Nikolaus at rath.org Mon Jul 28 03:26:02 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 28 Jul 2008 09:26:02 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> <490769a4-2a48-41dc-a069-2cc003b332a2@b1g2000hsg.googlegroups.com> Message-ID: <87tzeasc51.fsf@nokile.rath.org> castironpi writes: >> I think you misunderstood him. What he wants is to write >> >> class foo: >> ? ?def bar(arg): >> ? ? ? ?self.whatever = arg + 1 >> >> instead of >> >> class foo: >> ? ?def bar(self, arg) >> ? ? ? ?self.whatever = arg + 1 >> >> so 'self' should *automatically* only be inserted in the function >> declaration, and *manually* be typed for attributes. >> > > There's a further advantage: > > class A: > def get_auxclass( self, b, c ): > class B: > def auxmeth( self2, d, e ): > #here, ... > return B In auxmeth, self would refer to the B instance. In get_auxclass, it would refer to the A instance. If you wanted to access the A instance in auxmeth, you'd have to use class A: def get_auxclass(b, c ): a_inst = self class B: def auxmeth(d, e ): self # the B instance a_inst # the A instance return B This seems pretty natural to me (innermost scope takes precedence), and AFAIR this is also how it is done in Java. Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From fredrik at pythonware.com Sat Jul 26 08:25:49 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Jul 2008 14:25:49 +0200 Subject: re.findall(a patern,'function(dsf sdf sdf)') In-Reply-To: <2dd5c418-f532-4f50-923e-057a10f01fdd@79g2000hsk.googlegroups.com> References: <8fc6d72a-cfc5-4e9d-af56-a009a464c6bb@27g2000hsf.googlegroups.com> <2dd5c418-f532-4f50-923e-057a10f01fdd@79g2000hsk.googlegroups.com> Message-ID: gcmartijn at gmail.com wrote: > - For me its hard to learn the re , I will try to search again at > google for examples and do some copy past things. this might be useful when figuring out how RE:s work: http://kodos.sourceforge.net/ also, don't forget the following guideline: "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." some advice: - Keep the RE:s simple. You can often simplify things a lot by doing multiple searches, or even by applying a second RE on the results from the first. In this case, you could use one RE to search for BlaObject, and then use another one to extract the first argument. - Ordinary string methods (e.g. find, partition, split) are often a very capable alternative (in combination with simple RE:s). In your case, for JavaScript code that's as regular as the one in your example, you can split the string on "BlaObject(" and then use partition to strip off the first argument. - only use RE:s to read specialized file formats if you know exactly what you're doing; there's often a ready-made library that does it much better. - The regular expression machinery is not a parser. You cannot handle all possible syntaxes with it, so don't even try. From toby at tobiah.org Wed Jul 2 17:25:49 2008 From: toby at tobiah.org (Tobiah) Date: Wed, 02 Jul 2008 14:25:49 -0700 Subject: Sorting two dimentional array by column? Message-ID: Imagine an excel spreadsheet. I can choose a column and sort the records based on the items in that column. I would like to do the same thing with a large two dimensional array. What would be the fastest way (in computation time) to accomplish this? This seems similar to a recent sorting thread, but with that one, the 'master' table was sequential integers. This array would be filled with arbitrary data. Thanks ** Posted from http://www.teranews.com ** From nagle at animats.com Tue Jul 22 12:07:18 2008 From: nagle at animats.com (John Nagle) Date: Tue, 22 Jul 2008 09:07:18 -0700 Subject: DB Pool In-Reply-To: <40f3a61b-8c37-4e26-90f6-02de760ce00e@c58g2000hsc.googlegroups.com> References: <40f3a61b-8c37-4e26-90f6-02de760ce00e@c58g2000hsc.googlegroups.com> Message-ID: <48860153$0$17207$742ec2ed@news.sonic.net> bcurtu wrote: > Hi, > > I use MySQLdb lib to access my DB, because I want to optimize my SQL > queries. The application I'm working on has quite a few traffic load, > so I want to minimize the time of creating/destroying cursors: > > My typical code is sth like: > > cursor=con.cursor() > cursor.execute(sql) > all= cursor.fetchall() > cursor.close() > > So, the question is... how can I minimize this cost? I was thinking on > Connection Pools, but I didn't find any good documentation or sample. > Any idea? Creating and destroying MySQLdb cursors is cheap, because it doesn't really do anything. MySQL doesn't actually support cursors; you can only do one thing at a time per connection, and thus you can only have one cursor per connection. So cursor creation is a dummy operation for MySQLdb. Creating connections to the database is more expensive, and it helps to reuse those. There was once something called the "pool module" for doing this ("http://dustman.net/andy/python/Pool") but it's a dead link now. This is usually an issue only in multithreaded programs. Also, it's OK to have multiple connections open to the database from multiple threads, until you have so many that the database server starts to run out of resources. John Nagle From Scott.Daniels at Acm.Org Wed Jul 23 00:32:00 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 22 Jul 2008 21:32:00 -0700 Subject: Question about inheritence In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Catherine Heathcote wrote: > >> If I create a new class inherited from another with a constructor, what >> happens with the new class's constructer? > Python doesn't really have constructors; when you create an object, > Python first creates the object and then calls the __init__ method, if > available To elaborate a bit on Fredrik's response, there is a sense in which Python has constructors, but, to the extent it does, a constructor is the __new__, __init__ pair. For immutables, everything happens in __new__, for mutables, most things happen in the __init__ chain. --Scott David Daniels Scott.Daniels at Acm.Org From stefan_ml at behnel.de Sun Jul 27 04:48:05 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 27 Jul 2008 10:48:05 +0200 Subject: xml.dom's weirdness? In-Reply-To: <1c837e71-a191-4495-8ec8-0126003ba9c6@n33g2000pri.googlegroups.com> References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> <1c837e71-a191-4495-8ec8-0126003ba9c6@n33g2000pri.googlegroups.com> Message-ID: <488C3645.8060304@behnel.de> Lie wrote: > Question: Is there a way to list loaded modules, including those that > aren't in my namespace? such as sys.modules? Modules are not unloaded automatically just because you do not use them yourselves. If the module is imported for whatever reason by whatever other module, it stays alive until it's no longer referenced (including the reference in sys.modules). Stefan From alexnbryan at gmail.com Tue Jul 15 18:48:15 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 15 Jul 2008 15:48:15 -0700 (PDT) Subject: Testing for connection to a website In-Reply-To: <18473382.post@talk.nabble.com> References: <18473382.post@talk.nabble.com> Message-ID: <18476597.post@talk.nabble.com> Alexnb wrote: > > Okay, I already made this post, but it kinda got lost. So anyway I need to > figure out how to test if the user is able to connect to a specific > website. Last time I got pointed to the urllib2 page, but if I do > urlopen() and and am not connected, the program stops. So I don't know if > that was what you guys wanted me to do, but I don't think so, you guys are > smarter than that. So, how can I test for connection to a website. > Just for anyone looking this up later here is code that works :) from urllib2 import * import urllib2 e = '' req = urllib2.Request('http://www.dictionary.com') try: response = urlopen(req) except HTTPError, e: print e.code except URLError, e: print e.reason if e == '': print "good to go" -- View this message in context: http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p18476597.html Sent from the Python - python-list mailing list archive at Nabble.com. From nagle at animats.com Fri Jul 18 01:28:06 2008 From: nagle at animats.com (John Nagle) Date: Thu, 17 Jul 2008 22:28:06 -0700 Subject: Problem with MySQLdb and mod_python In-Reply-To: References: Message-ID: <48802594$0$17225$742ec2ed@news.sonic.net> Cyril Bazin wrote: > Thanks for your reply > > The apache log contains lines like : > > [Tue Jul 15 23:31:01 2008] [notice] mod_python (pid=11836, > interpreter='www.toto.fr'): Importing module > '/usr/local/apache2/htdocs/intranet/courrier/test.py' > [Tue Jul 15 23:31:02 2008] [notice] child pid 11836 exit signal > Segmentation fault (11) > [Tue Jul 15 23:31:19 2008] [notice] mod_python (pid=11764, > interpreter='www.toto.fr'): Importing module > '/usr/local/apache2/htdocs/intranet/courrier/test.py' > [Tue Jul 15 23:31:19 2008] [notice] child pid 11764 exit signal > Segmentation fault (11) > > I think the problem comes from the MySQLdb module. > If I can't find another solution, I think I will downgrade the MySQLdb > version to 1.2.1 Sounds like version hell. mod_python and MySQLdb have to be compiled with exactly the same compiler for this to work. mod_python is usually troublesome. Python doesn't really have quite enough isolation to run multiple unrelated instances reliably. We use FCGI, which has the isolation of CGI but doesn't reload the application for every transaction. Also, it's easier to debug if CPython is crashing. John Nagle From jim.hefferon at gmail.com Wed Jul 2 12:42:00 2008 From: jim.hefferon at gmail.com (Jim) Date: Wed, 2 Jul 2008 09:42:00 -0700 (PDT) Subject: convert unicode characters to visibly similar ascii characters References: <17d4c282-8606-4d29-9e71-d34f5e6d13bb@m44g2000hsc.googlegroups.com> Message-ID: On Jul 1, 8:42 pm, Jim wrote: > On Jul 1, 8:29 pm, John Machin wrote: > > Comments on the above grep output: > > 1. You have SOFT HYPHEN twice, mapping it to u'-' and '-' > > Hmph. I'll correct that. Thanks. Well, maybe not. I forgot that I got the by-hand conversions from three different sources and that's why that character appears in two different places. (I thought that listing all cases for each source was less confusing. Arguable, for sure.) > 2. The idea of a soft hyphen is as a hint to a hyphenator about where > > to insert a hyphen if one is necessary and the hyphenator is suspected > > of acting cluelessly without the hint. IMHO, asciification should > > substitute u'', not u'-'. > > Thanks also here. I'll think about it. Googling "soft hyphen" showed me that the question is not perfectly clear-- some people seem to have very elaborate opinions on the topic-- but I've gone with your suggestion. Thank you. Again, I'd appreciate additional corrections. Not do I only speak ASCII :-( but I admit to entering the data while watching a basketball game, so no doubt there are some real blunders. Thanks, Jim From elessar at nienna.org Thu Jul 31 16:28:26 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Thu, 31 Jul 2008 14:28:26 -0600 Subject: Hobbyist - Python vs. other languages In-Reply-To: References: Message-ID: <4892206A.4000007@nienna.org> fprintf wrote: > I have been playing with computers since I first learned to program > moving shapes on an Atari 800XL in BASIC. After many years of dabbling > in programming languages as a hobbyist (I am not a computer scientist > or other IT professional), I have never found a way to stick with a > language far enough to do anything useful. I learn all about loops > and data structures and functions/methods etc. but never get to create > a program that will do anything of value that I can't more easily do > via freeware. Well, except the slot car timing system I wrote in C++ > for Linux many moons ago. > > Honestly Python seems like a breath of fresh air and possibly a way to > get back to my BASIC roots, you know, programming just for the fun of > it. > > Since I don't have a specific problem to solve, besides > Pythonchallenge (which I found very cryptic), and Project Euler (which > I found beyond my mathematics skills), is there a place to go for > increasingly difficult problems to solve? I have followed a number of > the recommended online tutorials that contain a logical progression of > problems and yet they all end at the point where a person has enough > knowledge of the syntax, but not really enough to do anything. > -- > http://mail.python.org/mailman/listinfo/python-list > My situation's a bit different because I code for a living, but I also code sometimes for the heck of it. I come up with small, hobby projects one of two ways. (1) There's a whole lot of comp sci stuff out there that I don't know. So when I come across a new concept, pattern, etc., I write a little implementation. E.g., one day I was reading about how someone used memoization in a certain problem (don't remember what), so I thought "I bet I could do that as a decorator." So I did. (2) If you have some simple task, write a program to do it (even if there's a program out there already). E.g., I recently took a trip to Japan and decided to learn the kana before going. I found a website to help me learn them, then implemented my own version in Python for the heck of it. If you just examine the things you do with a computer, and challenge yourself "I bet I can do that in 100 lines of Python," I think you'll find no shortage of projects. -Matt From piyush.subscription at gmail.com Tue Jul 29 00:17:13 2008 From: piyush.subscription at gmail.com (Piyush Anonymous) Date: Tue, 29 Jul 2008 09:47:13 +0530 Subject: Dynamically adding methods to a class... Message-ID: <19ac19520807282117y4c34ed22n3bcb9c6cf7d198b8@mail.gmail.com> class MyObject: def __init__(self, name): self.name = name def do_this_default(self): print "default do_this implementation for %s" % self.name def custom_do_this(): #method to be added print "custom do_this implementation for %s" % self.name def funcToMethod(func,clas,method_name=None): """Adds func to class so it is an accessible method; use method_name to specify the name to be used for calling the method. The new method is accessible to any instance immediately.""" import new method = new.instancemethod(func,None,clas) print method if not method_name: method_name=func.__name__ clas.__dict__[method_name]=func myobj = MyObject('myobj1') funcToMethod(custom_do_this,MyObject) #trying 2 add method to class not instance print myobj.custom_do_this() --- Error I am getting; TypeError: custom_do_this() takes no arguments (1 given) Why am I getting it? Also how can I do this in new style class (inherited from 'object')? -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at hope.cz Fri Jul 25 14:37:20 2008 From: python at hope.cz (Johny) Date: Fri, 25 Jul 2008 11:37:20 -0700 (PDT) Subject: Python program as daemon? Message-ID: <8bb6bd1a-cd85-4b7a-8fc9-844f3794bca0@c58g2000hsc.googlegroups.com> Is it possible to run a Python program as daemon? Thanks From tjreedy at udel.edu Wed Jul 16 19:51:37 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 Jul 2008 19:51:37 -0400 Subject: python's YENC.DECODE -> weird output In-Reply-To: <0807160233556.16Jul08$rookswood@suburbian.com> References: <0807160233556.16Jul08$rookswood@suburbian.com> Message-ID: John Savage wrote: > I save posts from a midi music newsgroup, some are encoded with > yenc encoding. This gave me an opportunity to try out the decoders > in Python. The UU decoder works okay, but my YENC effort gives > results unexpected: > > import yenc, sys > > fd1=open(sys.argv[1],'r') > #yenc.encode(sys.argv[1],"outfile.yenc",bytes=0) > yenc.decode(sys.argv[1],"outfile.mid",bytes=0,crc_in='') > > I confirmed that yenc.decode exactly reverses yenc.encode, BUT the > encoding itself seems to differ from the USENET standard. I do not believe that there really is a yenc standard. I have noticed that the yenc decoder in Mozilla Thunderbird never decodes posts from certain posters (and hence certain encoders) whereas uu decoding only sporadically fails. From stodge at gmail.com Wed Jul 9 11:44:27 2008 From: stodge at gmail.com (Stodge) Date: Wed, 9 Jul 2008 08:44:27 -0700 (PDT) Subject: Boost Python - C++ class' private static data blown away before accessing in Python? References: Message-ID: <99b74b4f-935d-44e7-a578-99b8ae71ef60@34g2000hsf.googlegroups.com> I wonder if it's a DLL boundary problem. On Jul 5, 11:14?pm, Giuseppe Ottaviano wrote: > > In Python, I retrive an Entity from the EntityList: > > > elist = EntityList() > > elist.append(Entity()) > > elist.append(Entity()) > > > entity = elist.get_at(0) > > > entity.foo() > > > But it crashes inside foo() as the private static data is empty; or > > rather the string array is empty. I know before that point that the > > private static data is valid when accessed earlier by the C++ code as > > the program works fine. It just won't work from Python, so somehow the > > private static data has been blown away but I can't work out where or > > why. > > Probably it is a problem of lifetime. What is the signature of append? ? > Who deletes the appended Entity in C++ code? > If append takes a raw pointer, Boost.Python copies the pointer but ? > destroys the Entity object because it is a temporary and its reference ? > count went to zero. So the pointer in the list is referring to a ? > destroyed object, which results in undefined behaviour. > > Did you have a look at the lifetime policies of Boost.Python? The ? > simplest way to workaround the problem is using const reference ? > arguments, and always use value semantics. If it can result in a ? > performance penalty, another simple way is using shared_ptr's, which ? > have their own reference count (different from the one in CPython ? > lib), but Boost.Python does the magic to make them work together. > > HTH, > Giuseppe From stefan_ml at behnel.de Wed Jul 30 02:25:53 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 30 Jul 2008 08:25:53 +0200 Subject: elementtree and rounding questions In-Reply-To: References: Message-ID: <48900971$0$11730$9b4e6d93@newsspool1.arcor-online.net> jyoung79 at kc.rr.com wrote: > ============================================================ > > > > > > > > > > ============================================================ You can exploit the structure: the Elements you are looking for do not have children, but they do have a "name" attribute. declarations = [ fontData for fontData in root.getiterator('fontData') if fontData.get("name") ] This gives you a list of all "fontData" Elements that declare a font name. The one you want is the last one, i.e. declarations[-1]. You can also do font_names = [ fontData.get("name") for fontData in root.getiterator('fontData') if fontData.get("name") ] or something like that. And if you only want the fontData Elements that appear in the template Elements, try findall instead of getiterator: tree.findall("//template//fontData") ("//" means: descend into the subtree, while "/" would mean: look only at the direct children). > f = root.getiterator('fonts') > n = f[-1].getiterator('fontData') You should not rely on ET returning a list from ".getiterator()", so avoid using f[-1] here. > fntList = [] > f = root.getiterator('fonts') > n = f[-1].find('fontData') > for i in n: > fntList.append(i.get('name')) > > print fntList > ============================================================ > > This code just gave me ['Courier']. Now if I change 'find' to 'findall' then I'll get [None, 'Helvetica']. Not exactly sure what exactly that's doing. The first value (None) comes from the "fontData" Element that does not have a "name" attibute. The path expression "fontData" means: find all children that are named "fontData". As above, what you want is ".//fontData". Stefan From naude.jaco at gmail.com Wed Jul 23 08:22:19 2008 From: naude.jaco at gmail.com (Jaco Naude) Date: Wed, 23 Jul 2008 05:22:19 -0700 (PDT) Subject: Undefined calling conventions in Python.h References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> <216dcee8-ad3d-4ae1-ac4a-4f4819775c7e@d1g2000hsg.googlegroups.com> Message-ID: On Jul 23, 2:08?pm, Ben Sizer wrote: > On Jul 23, 11:43?am, Jaco Naude wrote: > > > What Visual C++ is doing is that it is looking for mangled names since > > it does not know the DLL contains C functions. I've managed to work > > around this by declaring the Python functions as follows before using > > them in the C++ application side: > > > extern "C" > > { > > ? ? void Py_Initialize(void); > > > } > > You should put the extern block around the #include call > rather than individual functions, as surely the C calling convention > should apply to everything within. > > > It is probably more of a C++ question it turns out, but I would think > > that someone in the Python group would use the Python DLL in C++. > > More of a Visual C++ question specifically, since the __clrcall prefix > is a MS specific extension (http://msdn.microsoft.com/en-us/library/ > ec7sfckb(VS.80).aspx). If you're not using managed code in your app, > disable it in the project/build options. If you are, then perhaps you > just need to specify that you're not with this DLL, though I've never > had to deal with anything like that myself. > > -- > Ben Sizer Fredrik, thanks for the help. I'm not sure why but it seems to work now even if I don't include the extern "C" command. It also works with both Python.h files (after I copied pyconfig.h from the PC folder). So it seems like everything is working now. Ben, Thanks for the reply. Good suggestion to place the extern "C" around the include. I will remember that. It turns out that it works without that as well in the end. As for the question on managed code: My application do use managed code. I've been able to turn this off when I created the Python DLL and it seems to work. Thanks for all the help, All the best Jaco From socyl at 987jk.com.invalid Tue Jul 29 16:22:16 2008 From: socyl at 987jk.com.invalid (kj) Date: Tue, 29 Jul 2008 20:22:16 +0000 (UTC) Subject: iterating "by twos" References: Message-ID: Thanks for all the replies. I learned a lot! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From deets at nospam.web.de Tue Jul 29 18:46:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 30 Jul 2008 00:46:30 +0200 Subject: Python: SPREE HELP (willing to pay someone) In-Reply-To: References: <25fb9200-9be5-456f-b711-804a830b3297@m44g2000hsc.googlegroups.com> Message-ID: <6f9ku6Fahtg6U1@mid.uni-berlin.de> > I cannot help but wonder if this is spam meant to drive traffic to the > site. If yes, you just managed to increase its visibility by quoting the whole post including the post. Diez From castironpi at gmail.com Wed Jul 30 22:29:58 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 30 Jul 2008 19:29:58 -0700 (PDT) Subject: undo a dictionary References: <92027f02-e4fb-4205-a525-41f55d437a57@m45g2000hsb.googlegroups.com> <192b4786-85b2-43d3-bb7c-b5716068ff12@56g2000hsm.googlegroups.com> Message-ID: On Jul 30, 8:07?pm, "Gabriel Genellina" wrote: > En Wed, 30 Jul 2008 16:14:31 -0300, mmm escribi : > > > > >> > And for that matter a way to create a > >> > dictionary from a set of variables (local or global). > > >> You have to be more specific: there are {} displays and dict(args) call > >> and other methods. ?Read the manual. > > > My desire is to take a set of data items in an alpha-numeric range and > > oput them into a dictionary > > > i.e., > > x1=1 > > x2=20 > > x3=33 > > > to yield ?the dictionary > > > { 'x1':1, 'x2':20, 'x3':33 } > > > without having to type in as above but instead invoke a function > > dict(x1=1, x2=20, x3=33) does the same thing. > > Or, do you mean you already have those names and values, perhaps mixed ? > with a lot more names, and want to extract only those starting with "x" ? > and following with a number? > > result = {} > for name, value in vars(): # or locals().items(), or globals().items(), or ? > vars(some_module) > ? ?if name[0]=='x' and name[1:].isdigit(): > ? ? ?result[name] = value > > -- > Gabriel Genellina You can also use a blank class instance, and update its __dict__ member with the dictionary you design. >>> class A: pass ... >>> d= { 'x1': 0, 'x2': set( ) } >>> A.__dict__ {'__module__': '__main__', '__doc__': None} >>> A.__dict__.update( d ) >>> A.__dict__ {'x2': set([]), '__module__': '__main__', 'x1': 0, '__doc__': None} >>> A.x1 0 >>> A.x2 set([]) >>> I agree that locals( ) shouldn't necessarily be read-only, and I believe it would extend the power of Python if it weren't. From martin at v.loewis.de Fri Jul 11 03:07:35 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 11 Jul 2008 09:07:35 +0200 Subject: Python 3.0 and removal of the 'string' module In-Reply-To: <87iqvdq6qz.fsf@benfinney.id.au> References: <87wsjtqiyo.fsf@benfinney.id.au> <87iqvdq6qz.fsf@benfinney.id.au> Message-ID: <487706b7$0$9695$9b622d9e@news.freenet.de> > This is rather disappointing. Is that entire page suspect? All documentation about Python 3 is suspect until Python 3 gets actually released (nobody can say for sure how the release will look like in all details). Wiki pages, traditionally, are always suspect for incorrect or outdated information, IMO. It's in the nature of Wikis. Regards, Martin From torriem at gmail.com Sat Jul 12 12:29:59 2008 From: torriem at gmail.com (Michael Torrie) Date: Sat, 12 Jul 2008 10:29:59 -0600 Subject: Confused In-Reply-To: <000001c8e417$c2b5bc50$0a01a8c0@HOMEPC> References: <000001c8e417$c2b5bc50$0a01a8c0@HOMEPC> Message-ID: <4878DC07.9000302@gmail.com> eric.butteriss wrote: > Please tell me why may mail is being returned. The message says I > have been blacklisted...for what reason? I never open mail that I > know is not expected and I never send junk or spam. I am trying to > send important info to my cousin. Now I'm confused. Is the python mailing list blacklisting you? Unless this is a python-related thing, I doubt you'll find anyone here who can help. From hat at se-162.se.wtb.tue.nl Thu Jul 10 02:39:39 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 10 Jul 2008 08:39:39 +0200 Subject: TypeError, I know why but not how!? References: <03cbb0d2-6a0c-4b86-a75e-b73c5677acc7@c65g2000hsa.googlegroups.com> Message-ID: On 2008-07-10, ssecorp wrote: > > def validate(placed): > student = round(random.random()*401) > if student in placed: > validate(placed) > else: > placed.append(student) > return student, placed > > def pair(incompatibles, placed): > student1, placed = validate(placed) > student2, placed = validate(placed) > pair1 = (student1,student2) > pair2 = (student2,student1) > if (pair1 or pair2) in incompatibles: > placed.remove(student1) > placed.remove(student2) > pair(incompatibles, placed) > else: > return pair1, placed > > def generateList(dormlist,incompatibles, placed, rooms): > if len(dormlist) < (rooms + 1): > room, placed = pair(incompatibles, placed) > dormlist.append(room) > generateList(dormlist,incompatibles,placed,rooms) > else: > return dormlist In each of the above functions, the 'if' part has no 'return', while the 'else' part has. You should add a 'return' statement at every exit from the function. If you don't expect the program to get at some point, you should add a check like raise ValueError("This shouldn't happen") you'd be surprised how often 'impossible' things do happen (and writing such a statement costs less than a minute, and saves you many hours debugging). Some people so as far as demanding that there is exactly 1 return statement, namely at the bottom of the function. While I don't favor that approach, it may help you in always returning a value. BTW: For performance and readability, you may want to replace your direct recursion with iterations. Albert From jaywgraves at gmail.com Mon Jul 7 09:16:28 2008 From: jaywgraves at gmail.com (jay graves) Date: Mon, 7 Jul 2008 06:16:28 -0700 (PDT) Subject: I am looking for svn library(module) References: <6e1097a0-2a99-4885-a1ef-0684af5aa6a1@d1g2000hsg.googlegroups.com> Message-ID: <566b1cc4-79aa-4b05-8129-a1bed2baed61@l64g2000hse.googlegroups.com> On Jul 7, 7:49?am, sni... at gmail.com wrote: > Hi, > I am looking fo svn library(module) which is used in the svn- > mailer(http://opensource.perlig.de/svnmailer/) project. Does anybody > know where can I find it(download url)? This is information which I > received from python error: > from svn import core as svn_core > ImportError: No module named svn > Best regards I believe that it is the python binding provided by Subversion. You didn't say what platform you are on or what version of SVN you are using so I can't point you any closer than: http://subversion.tigris.org/ HTH ... Jay Graves From ldo at geek-central.gen.new_zealand Fri Jul 25 00:36:47 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 25 Jul 2008 16:36:47 +1200 Subject: Broken examples References: Message-ID: In message , norseman wrote: > Lawrence D'Oliveiro wrote: > >> In message , norseman >> wrote: >> >>> The OOo examples do not work. >> >> I have done OOo scripting in Python. What exactly does not work? > > soffice "-accept=socket,host=localhost,port=2002;urp;" & > sleep 9 > > ./python ./zhw.py I've never tried that. I've run Python scripts from the "Tools/Macros/Run Macro..." dialog. From noZ.spamZ at ZZ.ZsvpZ.com Tue Jul 29 18:30:14 2008 From: noZ.spamZ at ZZ.ZsvpZ.com (Michel Claveau - NoSpam SVP ; merci) Date: Wed, 30 Jul 2008 00:30:14 +0200 Subject: Python COM In-Reply-To: <6f8dgfFabuohU1@mid.uni-berlin.de> References: <6d124557-27d9-468e-a07d-8d6a6f650a98@a6g2000prm.googlegroups.com> <488eff34$0$869$ba4acef3@news.orange.fr> <6f8dgfFabuohU1@mid.uni-berlin.de> Message-ID: <488f9c24$1$12756$426a74cc@news.free.fr> Re! Pywin32 can use dynamic COM server (without tlb). Therefore, I prefer to wait the return from birdprince... @-salutations -- Michel Claveau From Lie.1296 at gmail.com Sat Jul 26 06:48:18 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 26 Jul 2008 03:48:18 -0700 (PDT) Subject: re.findall(a patern,'function(dsf sdf sdf)') References: <8fc6d72a-cfc5-4e9d-af56-a009a464c6bb@27g2000hsf.googlegroups.com> Message-ID: On Jul 26, 5:03?pm, gcmart... at gmail.com wrote: > H! > > First I have some random string below. > > bla = """ ? ? ? ? ? ? ? ? """ > > Now I'm trying to get each BlaObject with the first (variable) > function argument > First of all, since you're dealing with Javascript, which is case- sensitive, Blaobject and BlaObject means different thing, if the dummy code is real, it'd have raised a name not found error. > And I can say that this isn't working > for a in re.findall(r'([BlaObject ])(.*)([)] *)',bla): > ? ? print a Of course that doesn't work, you've put BlaObject in a square bracket (character class notation), which means the re module would search for _a single letter_ that exist inside the square bracket. Then you do a '.*', a greedy match-all, something that you generally don't want to do. Next is the '[)] *', a character class containing only a single character is the same as the character itself, and the zero-or-more- repetition (*) is applied to the white space after the character class, not to the character class itself. In short, the regular expression you used doesn't seem to be an effort to solve the problem. In other words, you haven't read the regular expression docs: http://docs.python.org/lib/module-re.html . In other words, it's useless to talk with you until then. (snip) From rkmr.em at gmail.com Sun Jul 27 22:26:09 2008 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Sun, 27 Jul 2008 19:26:09 -0700 Subject: write unsigned integer 32 bits to socket In-Reply-To: References: Message-ID: On Sun, Jul 27, 2008 at 7:17 PM, Larry Bates wrote: > rkmr.em at gmail.com wrote: >> On Sun, Jul 27, 2008 at 7:01 PM, Larry Bates >> wrote: >>> rkmr.em at gmail.com wrote: >>>> i want to send unsigned 32 bit integer to socket, and looking for >>>> something equivalent to this method... >>>> >>>> http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt() >>>> >>>> is there such method / library available in python?! >>> >>> You will need to use struct module to build the 4 byte value and then >>> send >>> it. >>> >>> Something like (not tested): >>> >>> import struct >>> us32bit = struct.pack("I", value) >>> s.send(us32bit) >> >> thanks a lot!!! >> >> just to make sure if I want 32 bit or 4 bytes then should I use the >> short or integer or long? >> >> this is short >>>>> >>>>> struct.pack('!h',3) >> >> '\x00\x03' >> >> this is integer >>>>> >>>>> struct.pack('!i',3) >> >> '\x00\x00\x00\x03' >> >> this is long >>>>> >>>>> struct.pack('!l',3) >> >> '\x00\x00\x00\x03' > > Short is 16 bits, Integer is 32 bits, long is 64 bits (as I read and have > found). thanks a lot!!! re-read it again!!! from the struct doc! Standard size and alignment are as follows: no alignment is required for any type (so you have to use pad bytes); short is 2 bytes; int and long are 4 bytes; long long (__int64 on Windows) is 8 bytes; float and double are 32-bit and 64-bit IEEE floating point numbers, respectively. From dickinsm at gmail.com Fri Jul 18 18:05:46 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 18 Jul 2008 15:05:46 -0700 (PDT) Subject: round function error??? References: Message-ID: <2da2f5f1-7ff2-46d7-a768-f0817e414615@f36g2000hsa.googlegroups.com> On Jul 18, 10:17?pm, Anthony wrote: > Isn't this a mistake??? Which 'this'? That is, what were you expecting? If you're objecting to the fact that the second result produces 3499.3499999999999 instead of 3499.35, then no, that's not a mistake; see http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate for more information. But I'm guessing that you're questioning the fact that a value that's apparently *less* than 3499.35 is rounded up to 3499.4, rather than down to 3499.3. ? Then yes, I'd agree that's less than ideal, though I don't consider it a particularly serious bug. It's been on my list of things to fix for a while. (See http://bugs.python.org/issue1869 ). Contributions welcome! Mark From paul at boddie.org.uk Thu Jul 24 11:46:29 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 24 Jul 2008 08:46:29 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: On 24 Jul, 12:02, "Sebastian \"lunar\" Wiesner" wrote: > > Fortunately, Python isn't designed according to your ideas, and won't > change, so consider your posting a waste of time. This is the kind of petty response that serves only to shut down discussion that might actually lead to genuine attempts to remedy issues (or "warts") with Python. Although the tone of the complaint was badly chosen, it is always worth jumping over the fence and considering whether things could be made better. Without complaints being aired, how do you expect any advances around things like the "old and outdated modules in the standard library, or real showstoppers in Python (e.g. the GIL)" that you mention elsewhere? > If feeling like bringing such old "issues" up again next time, spend > your time learning another programming language, as you would > obviously not get happy with Python anyway ... Such a constructive response that is! Instead, I think it is interesting to consider why methods still require an explicit "self" parameter - something which has been discussed previously - and whether there might be a case for omitting it from the signature - perhaps in a variant of Python - in methods which are defined within class definitions (as opposed to those assigned to classes later). Indeed, there's scope for experimentation with Python variants, just to investigate whether certain features added to CPython can be considered essential, and which features might be considered of marginal benefit. I recall that some features (eg. lexical scoping and closures) were eventually added to Python partly to remedy issues with lambda definitions, but also because the lack of such features was cited repeatedly by proponents of other languages. In such a climate, it can be easier to "meet the challenge" and implement features to silence the critics rather than to insist that they are of marginal benefit (although it's interesting to note this in a thread where improvement suggestions are deemed "a waste of time" - I suppose the community is now more resistant to suggestions from "unofficial" sources). A review of such language "enhancement" decisions would be interesting, but since one shouldn't expect this from the CPython implementers, I feel that it is the role of others to do so in their own experiments. Of course, such experiments are often derided as "lesser Pythons" or misunderstood, but that's another unfortunate trait exhibited by parts of the Python community. Paul From peter.anderson at internode.on.net Tue Jul 15 09:54:46 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Tue, 15 Jul 2008 23:54:46 +1000 Subject: Python internals question Message-ID: <487CAC26.9050904@internode.on.net> Hi! I am slowly teaching myself Python. I was reading David Beazley's excellent book "Python - Essential Reference"; in particular about variables. Let me quote: "Python is a dynamically typed language in which names can represent values of different types during the execution of a program. In fact the names used in the program are really just labels for various quantities and objects. The assignment operator simply creates an association between a name and a value. This is different from C, for example, in which a name (variable) represents a fixed size and location in memory..." As an old mainframe programmer, I understand the way C does things with variable but this text got me wondering how Python handles this "association" between variable name and value at the lower level. Is it like a fifo list? If there is any Python guru that can help I would be most interested in your thoughts. Regards, Peter -- Peter Anderson There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things ? Niccolo Machiavelli, /The Prince/, ch. 6 From laredotornado at zipmail.com Tue Jul 29 10:53:53 2008 From: laredotornado at zipmail.com (laredotornado) Date: Tue, 29 Jul 2008 07:53:53 -0700 (PDT) Subject: How do I include a shell variable in my script? Message-ID: Hi, I'm running a Python script on a Solaris 9 machine, invoking the Python script from ksh, if that matters. There is an enviornment variable, $JAVA_HOME, that I would like to include in my script, replacing "/path/to/java/home'" with the value of $JAVA_HOME. java_home='/path/to/java/home' How do I do this? If I need to pass a command line argument, so be it, but I figure there is a more direct way to get the value. Thanks, - Dave From arkanes at gmail.com Thu Jul 31 13:27:41 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 31 Jul 2008 12:27:41 -0500 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: <4866bea60807311027g521a00e7i9bfe0ce2776863bb@mail.gmail.com> On Tue, Jul 29, 2008 at 3:37 AM, Carl Banks wrote: > On Jul 28, 8:15 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: >> > On Jul 28, 10:00 am, Steven D'Aprano > > cybersource.com.au> wrote: >> >> Cutting to the crux of the discussion... >> >> >> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: >> >> > I want something where "if x" will do but a simple explicit test >> >> > won't. >> >> >> Explicit tests aren't simple unless you know what type x is. If x could >> >> be of any type, you can't write a simple test. Does x have a length? Is >> >> it a number? Maybe it's a fixed-length circular length, and the length >> >> is non-zero even when it's empty? Who knows? How many cases do you need >> >> to consider? >> >> > Use case, please. I'm asking for code, not arguments. Please give me a >> > piece of code where you can write "if x" that works but a simple >> > explicit test won't. >> >> I gave you a piece of code, actual code from one of my own projects. If >> you wouldn't accept that evidence then, why would you accept it now? > > I would accept as "evidence" something that satisfies my criteria, > which your example did not: it could have easily (and more robustly) > been written with a simple explicit test. I am looking for one that > can't. > > You keep bringing up this notion of "more complex with no benefit", > which I'm simply not interested in talking about that at this time, > and I won't respond to any of your points. I am seeking the answer to > one question: whether "if x" can usefully do something a simple > explicit test can't. Everyone already knows that "if x" requires > fewer keystrokes and parses to fewer nodes. > I'm really not sure where you're going with this or what you're trying to prove. "if x" is a duck-type test for a boolean value. Obviously if you know the type and want a more *specific* test, then you can use an explicit one. Any time you don't know or don't care about a more specific type than "something which probably is boolean true", or any time where you know the boolean semantics of the type and want to drop some typing, you can use "if x". The more specific test is what you'd use if you want more specific results. What's complicated about this idea? From pavlovevidence at gmail.com Thu Jul 17 02:46:36 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 16 Jul 2008 23:46:36 -0700 (PDT) Subject: singletons References: <2476438f-eaa2-495f-95fa-eb9efec25875@e39g2000hsf.googlegroups.com> Message-ID: On Jul 16, 6:20?pm, Craig Allen wrote: > Anyone have any comments? ?Is there anything wrong, evil, or ugly > about using a module this way, or am I correct to think that actually, > this is a common approach in python. > > Is it pythonic? The one drawback to this is that it could require lots of globals definitions. Whereas in a regular class you could do this: def something(self): self.var = 1 self.max = 10 using a module as a singleton you'd be doing this: def something(): global var global max var = 1 max = 10 If you have a lot of "attributes" of your module to redefine, I'd suggest taking steps to avoid globals. The most straightforward way is to define a self variable in your module that is bound to the module itself, and access all "attributes" through that. The following code should suffice (though it may not work in some corner cases): self = sys.modules[__name__] So then you could rewrite the something method like so: def something(): self.var = 1 self.max = 10 [Another possibility, and this is what I do, is to use a function decorator that passes the module in as the first argument. I have reasons for doing it but it doesn't do anything the above method does. It would be used like this: @modmethod def something(self): self.var = 1 self.max = 10 ] Carl Banks From RonV at Nospam.com Sat Jul 12 12:08:02 2008 From: RonV at Nospam.com (RV) Date: Sat, 12 Jul 2008 12:08:02 -0400 Subject: Can anyone suggest a date peocedure... References: Message-ID: <7flh74peqavr4uvogmoo7ergas1hcjsvjs@4ax.com> On Thu, 10 Jul 2008 20:04:27 -0400, RV wrote: Gary, Larry, Michiel , Thanks very much, your helpful info has enabled me to get past a learning bump. Ron From alexnbryan at gmail.com Tue Jul 15 13:49:32 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 15 Jul 2008 10:49:32 -0700 (PDT) Subject: Testing for Internet Connection In-Reply-To: <1216113021.24038.0@proxy02.news.clara.net> References: <18460572.post@talk.nabble.com> <1216113021.24038.0@proxy02.news.clara.net> Message-ID: <18471183.post@talk.nabble.com> Alex Marandon-3 wrote: > > Alexnb wrote: >> I am wondering, is there a simple way to test for Internet connection? If >> not, what is the hard way :p > > Trying to fetch the homepage from a few major websites (Yahoo, Google, > etc.)? If all of them are failing, it's very likely that the connection > is down. You can use urllib2 [1] to accomplish that. > > [1] > -- > http://mail.python.org/mailman/listinfo/python-list > > What exactly do you think will work? I am not sure what you think I should do? If I use urlopen("http://www.google.com") and I am not connected, I am not going to get an exception, the program will fail. -- View this message in context: http://www.nabble.com/Testing-for-Internet-Connection-tp18460572p18471183.html Sent from the Python - python-list mailing list archive at Nabble.com. From cmake-bounces at cmake.org Thu Jul 24 18:43:34 2008 From: cmake-bounces at cmake.org (cmake-bounces at cmake.org) Date: Thu, 24 Jul 2008 18:43:34 -0400 Subject: Your message to CMake awaits moderator approval Message-ID: Your mail to 'CMake' with the subject Status Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. If you would like to cancel this posting, please visit the following URL: http://www.cmake.org/mailman/confirm/cmake/42b7f3960ed3942796005bcc10ef862779cd7985 From frankrentef at yahoo.com Tue Jul 29 14:30:44 2008 From: frankrentef at yahoo.com (frankrentef) Date: Tue, 29 Jul 2008 11:30:44 -0700 (PDT) Subject: Python / PAMIE - scriptWrite Function References: Message-ID: <5562e1cc-21a9-4740-a5d9-8bec67e7d32a@34g2000hsh.googlegroups.com> On Jul 29, 1:26?pm, frankrentef wrote: > In using PAMIE 2.0 specifically the "scripWrite" function I'm getting > the following error... > > File "C:\Python23\Lib\site-packages\win32com\client\dynamic.py", line > 489, in _getattr_ > > further states... > > raise AttributeError, "%s.%s" % (self._username_, attr) > > Help... :) Further messages found are: C:\Python23\lib\site-packages\win32com\client\dynamic.py:476: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up debug_attr_print("Getting property Id 0x%x from OLE object" % retEntry.dispid) From deets at nospam.web.de Wed Jul 9 06:53:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Jul 2008 12:53:19 +0200 Subject: start reading from certain line References: <68ee3a0a-9ffd-489d-b609-f074737d7010@z66g2000hsc.googlegroups.com> Message-ID: <6djjmfF2tamgU1@mid.uni-berlin.de> antar2 wrote: > I am a starter in python and would like to write a program that reads > lines starting with a line that contains a certain word. > For example the program starts reading the program when a line is > encountered that contains 'item 1' > > > The weather is nice > Item 1 > We will go to the seaside > ... > > Only the lines coming after Item 1 should be read Start reading each line, and skip them until your criterion matches. Like this: def line_skipper(predicate, line_iterable): for line in line_iterable: if predicate(line): break for line in line_iterable: yield line Diez From anonymous at anonymous.com Mon Jul 14 08:51:06 2008 From: anonymous at anonymous.com (anonymous) Date: Mon, 14 Jul 2008 12:51:06 GMT Subject: Python beginner, unicode encode/decode Q Message-ID: <487B4BC5.7FA8FFF9@anonymous.com> 1 Objective to write little programs to help me learn German. See code after numbered comments. //Thanks in advance for any direction or suggestions. tk 2 Want keyboard answer input, for example: answer_str = raw_input(' Enter answer > ') Herr ?? [ I keyboard in the following characters Herr ?? ] print answer_str Output on screen is > Herr ?? 3 history 1 and 2 code run interactively under Debian Linux Python 2.4 and interactively under windows98, first edition IDLE, Python 2.3.5 and it works. 4 history 3 and 4 code run from within a .py file produce different output from example in book. 5 want to operate under Debian Linux but because the program failed under Linux when I tried to run the code from a file in Linux Python, I thougt I should fire up the win98 Idle/python program and try it to see if ran there but it failed, too from within a file. 6 The sample code is from page 108-109 of: "Python for Dummies" It says in the book: "Python's file objects and StringIO objects don't support raw Unicode; the usual workaround is to encode Unicode as UTF-8 before saving it to a file or stringIO object. The sample code from the book is French as indicate here but trying German produces the same result. 7 I have searched the net under all the keywords but this is as close as I get to accomplishing my task. I suspect I may not be understanding: StringIO objects don't support raw Unicode, but I don't know. #_*_ coding: utf-8 _*_ # code run under linux debian interactively from a terminal and works print " u'Libert\u00e9' " # y = raw_input('Enter >') commented out y = u'Lbert\u00e9' y.encode('utf-8') q = y.encode('utf-8') q.decode('utf-8') print q.decode('utf-8') history 1 works and here is the screen copy of interactive >>> y = raw_input ('>') >Libert\xc3\xa9 >>> q = 'Libert\xc3\xa9' >>> q.decode('utf-8') u'Libert\xe9' >>> print q Libert? >>> [ screen output is next line ] Lbert? history 2 # code run under win98, first edition, within IDLE interactively and succeeded in produce correct results. # y = raw_input('Enter >') commented out y = u'Lbert\u00e9' y.encode('utf-8') q = y.encode('utf-8') q.decode('utf-8') print q.decode('utf-8') history 1 works and here is the screen copy of interactive >>> y = raw_input ('>') >Libert\xc3\xa9 >>> q = 'Libert\xc3\xa9' >>> q.decode('utf-8') u'Libert\xe9' >>> print q Libert? >>> [ screen output is next line ] Lbert? # history 3 # this code is run from within idle on win98 and inside a python file. # The code DOES NOT produce the proper outout. #_*_ coding: utf-8 _*_ # print "u'Libert\u00e9'" printed to screen y = raw_input('Enter >') # y = u'Lbert\u00e9' commented out y.encode('utf-8') q = y.encode('utf-8') q.decode('utf-8') print q.decode('utf-8') # output is on the lines below was produced on the screen after run enter u'Libert\u00e9' on screen to copy into into y string Enter >u'Libert\u00e9' u'Libert\u00e9' The code DOES NOT produce Libert? but instead produce u'Libert\u00e9' # history 4 # this code is run from within terminal on Debian linux inside a python file. # The code does not produce proper outout but produces the same output as run on # windows. #_*_ coding: utf-8 _*_ print "u'Libert\u00e9'" printed to screen y = raw_input('Enter >') # y = u'Lbert\u00e9' commented out y.encode('utf-8') q = y.encode('utf-8') q.decode('utf-8') print q.decode('utf-8') # output is on the lines below was produced on the screen after run enter u'Libert\u00e9' on screen to copy into into y string Enter >u'Libert\u00e9' u'Libert\u00e9' The code DID NOT produce Libert? but instead produce u'Libert\u00e9' From paddy3118 at googlemail.com Sun Jul 20 15:17:57 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 20 Jul 2008 12:17:57 -0700 (PDT) Subject: question References: Message-ID: On Jul 20, 6:39?pm, wrote: > Nobody any sensible answers. Too complicated I suppose! The sensible question was? From xkenneth at gmail.com Mon Jul 7 17:38:28 2008 From: xkenneth at gmail.com (xkenneth) Date: Mon, 7 Jul 2008 14:38:28 -0700 (PDT) Subject: Standard Equation Description Language? Message-ID: <1cd1baf2-9816-4ac1-91ea-90f148167549@t54g2000hsg.googlegroups.com> Does anyone know of a standard inter-language syntax for describing scientific/mathematical equations? Preferably something with parsers in multiple libraries. Regards, Kenneth Miller From michele.simionato at gmail.com Thu Jul 10 07:54:45 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 10 Jul 2008 04:54:45 -0700 (PDT) Subject: FOSS projects exhibiting clean/good OOP? References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> Message-ID: <5c3e8cf2-ffae-4930-8f2f-d8bc081518c0@56g2000hsm.googlegroups.com> On Jul 9, 4:38?pm, Phillip B Oldham wrote: > I'm wondering whether anyone can offer suggestions on FOSS projects/ > apps which exhibit solid OO principles, clean code, good inline > documentation, and sound design principles? > > I'm devoting some time to reviewing other people's code to advance my > skills. Its good to review bad code (of which I have more than enough > examples) as well as good, but I'm lacking in finding good examples. > > Projects of varying sizes would be great. I vote for the doctest module in the standard library. From mattheww at chiark.greenend.org.uk Tue Jul 29 16:25:44 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 29 Jul 2008 21:25:44 +0100 (BST) Subject: Boolean tests References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8d <87y73kg70u.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > No, he retracted the *insult* and restated the *advice* as a distinct > statement. I think it's quite worthwhile to help people see the > difference. Ben, it was quite clear from Anders' post that he knows about __nonzero__ . That's why the so-called advice is insulting. The original phrasing was just the icing on the cake. -M- From ironfroggy at gmail.com Thu Jul 17 08:35:30 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Thu, 17 Jul 2008 08:35:30 -0400 Subject: Getting a unknown word out of a list with no spaces In-Reply-To: <18502758.post@talk.nabble.com> References: <18502758.post@talk.nabble.com> Message-ID: <76fd5acf0807170535s63ea3d41m8b42850671a9dad6@mail.gmail.com> BeautifulSoup. You need a good html parsing, not some one-shot code to handle one tiny unflexable pattern. On Thu, Jul 17, 2008 at 3:07 AM, Alexnb wrote: > > Hello > > Lets say I have a string: > > --a href="/browse/brick"--brick--/a-- > > The -- needs to be replaced with < or > where applicable. > > and I want the "brick" out of that string (the second brick that is). How > can I get just the "brick" out of that string? > -- > View this message in context: http://www.nabble.com/Getting-a-unknown-word-out-of-a-list-with-no-spaces-tp18502758p18502758.html > Sent from the Python - python-list mailing list archive at Nabble.com. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From rocksportrocker at googlemail.com Tue Jul 15 06:26:10 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Tue, 15 Jul 2008 03:26:10 -0700 (PDT) Subject: Python embedding question. References: <45f657a0-315f-421e-8d69-1c5b24e23887@k37g2000hsf.googlegroups.com> Message-ID: <5e0e47aa-a7bc-4e43-98cd-07fc0f6fe454@l42g2000hsc.googlegroups.com> On 15 Jul., 12:14, Thomas Troeger wrote: > Kay Schluehr wrote: > > On 15 Jul., 11:51, Thomas Troeger > > wrote: > > >> I've really looked at a lot of places but haven't found a suitable > >> solutions yet, so I'm asking here in hope that someone has experience > >> with that topic. > > > Which solutions did you rule out? > > - Python + Qt, because it's definitely overkill for my plans. I only > need simple graphics and some sound, no widgets. Basically I'm looking > for something really lightweight that has methods for drawing graphic > primitives and renders fonts -- no complicated widgets, windows, > scrollbars and the like. And, for example, the Qt library is a real > heavyweight with approx. 10 MB for qt-3.3.8 alone. > > - The same holds for cairo/pango, I've written a test program (in C, I > must say) that has dynamic links to 10 libraries that are all like 250kb > in size. That's a lot for a small embedded device. > Did you try pygame ? I think it has a small footprint. Greetings, Uwe From bignose+hates-spam at benfinney.id.au Thu Jul 24 11:09:54 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 25 Jul 2008 01:09:54 +1000 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <579f9d5b-8984-425d-8d4f-b2ed0be8eaba@o40g2000prn.googlegroups.com> Message-ID: <871w1jpbct.fsf@benfinney.id.au> Jordan writes: > Explicit is actually kinda annoying a lot of the time Yes. It is also very helpful for those who will later try to understand, interface with, debug, modify, or otherwise work with the code (including, in a great many cases, the original author of that code). The great boost that EIBTI grants to maintainability trumps, in my view, the annoyance felt by some at the time of writing the code. -- \ ?An eye for an eye would make the whole world blind.? ?Mahatma | `\ Gandhi | _o__) | Ben Finney From maric at aristote.info Wed Jul 30 11:54:27 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 30 Jul 2008 17:54:27 +0200 Subject: Standard module for parsing emails? In-Reply-To: References: Message-ID: <200807301754.28054.maric@aristote.info> Le Wednesday 30 July 2008 17:15:07 Phillip B Oldham, vous avez ?crit?: > If there isn't a standard library for parsing emails, is there one for > connecting to a pop/imap resource and reading the mailbox? > -- > http://mail.python.org/mailman/listinfo/python-list There are both shipped with python, email module and poplib, both very well documented in the official doc (with examples and all). email module is rather easy to use, and really powerful, but you'l need to manage yourself the many ways email clients compose a message, and broken php webmails that doesn't respect RFCs (notably about encoding)... -- _____________ Maric Michaud From mtobis at gmail.com Sat Jul 19 22:43:35 2008 From: mtobis at gmail.com (Michael Tobis) Date: Sat, 19 Jul 2008 19:43:35 -0700 (PDT) Subject: Not entirely serious: recursive lambda? Message-ID: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> I came across the "japh" concept today and decided to do one of my own, obviously, interpreting the 'p' somewhat loosely, http://en.wikipedia.org/wiki/JAPH but I'm not entirely satisfied with it: #### # japh, for certain values of 'p' f=lambda(r,N):N and f((" acdefijlmnopqrstuv"[N%19]+r,N/19))or(r,N) print f( ("",reduce(lambda c,m:c*95+''.join(map(chr,range(32,127))).index(m), "!b)'1Mgh0z+fYQ]g::i^<&y~g)cnE-d=K&{GMNQ1gx+ooY<~L##N'X]P2<@XYXwX3z", 0)))[0] #### it bothers me that there are two statements. (In case you are wondering what they do, it's all essentially about changing from base 95 to base 19. It's based loosely on this fine, simple recipe by Drew Perttula which I have found to be useful on several occasions: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 ) Anyway, I'd much prefer an even uglier japh like this: # does not work print (lambda(r,N):N and $$$$((" acdefijlmnopqrstuv"[N%19]+r,N/ 19))or(r,N))( ("",reduce(lambda c,m:c*95+''.join(map(chr,range(32,127))).index(m), "!b)'1Mgh0z+fYQ]g::i^<&y~g)cnE-d=K&{GMNQ1gx+ooY<~L##N'X]P2<@XYXwX3z", 0)))[0] but what would $$$$ be for an unnamed function to call itself? I realize that lambda is something of an orphan and was arguably a bad idea for anything besides obfuscation, but obfuscation is exactly my purpose here. Can a lambda call itself without giving itself a name? Google was not my friend on this one, and I suspect there is no answer. Relax, I am not going to submit a PEP about it. mt From castironpi at gmail.com Wed Jul 9 21:01:30 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 9 Jul 2008 18:01:30 -0700 (PDT) Subject: "in"consistency? References: <871c6735-f2d2-4cd0-811d-0cd774d55bdd@m45g2000hsb.googlegroups.com> Message-ID: On Jul 8, 2:25?pm, Terry Reedy wrote: > castironpi wrote: > > Strings are not containers. > > Library Reference/Built-in Types/Sequence Types says > "Strings contain Unicode characters." > Perhaps you have a different notion of contain/container. > > I prefer 'collection' to 'container' since 'container' tends to imply an > exclusiveness that is not true. ?Byte/character sequences *are* > different from tuples, lists, sets, dicts, etc, in the following sense: > members of the latter collection classes must exist first before being > added to the collection (non-exclusively). ?Members of the former do > not. ?(In CPython, at least, they do not). ?So I consider them to > (reiterable) *virtual* sequence collections that can produce > subsequences on demand, > > So I partially agree with you in that byte/char sequences are a > different sub-category. > > > Another container type: > > > Python 3.0b1 on win32 > >>>> {0} in {0,1} > > False > > And similarly, (0,) not in (0,1), [0] not in [0,1], {0:None} not in > {0:None,1:None). ?These are all general manifest collection types that > can contain any Python object, and which could contain a sub-collection > even if they do not. > > Terry Jan Reedy Under that definition, "a" in "abc" is clearly well-defined. I construe "abc" to "contain Unicode characters", specifically, "a", "b", and "c". But "ab" is not a Unicode character. "Contain" is still a good word for what strings "do", to the extent that they "do" anything at all. The fact that they contain a uniform data-type permits the extension of "in" to subset/substring testing. Compare to an imaginary "set of ints" data type: >>> a= setofints( [ 0, 1, 2 ] ) Then, the semantics of >>> b= setofints( [ 0, 1 ] ) >>> b in a True are consistent and predictable. Correct me if I'm wrong. From Russ.Paielli at gmail.com Wed Jul 30 01:58:28 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 22:58:28 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> Message-ID: <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> On Jul 29, 10:33 pm, Carl Banks wrote: > On Jul 30, 1:15 am, "Russ P." wrote: > > Having said that, it would sure be nice to be able to write > > > if myList is not empty: > > > instead of > > > if len(myList) != 0: > > I can agree with this. But I guess that could only work if there were only one empty list that represents all empty lists (as there is only one actual "None"). I don't know if that makes sense or not. From notnorwegian at yahoo.se Sun Jul 13 23:03:38 2008 From: notnorwegian at yahoo.se (maestro) Date: Sun, 13 Jul 2008 20:03:38 -0700 (PDT) Subject: while var, but var ==16 != true Message-ID: <8c2cd9ff-bec2-4844-82a8-8ce02df5663e@w7g2000hsa.googlegroups.com> why does this work? "while p" = "while p != 0" ? 1 is True and 0 is false in python but other numbers have no boolean value so why doesnt it abort. >>> p=16 >>> p 16 >>> while p: print p p -= 1 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 >>> i can also do: >>> k=[] >>> while k: k.pop() >>> k=[1,2,3] >>> while k: k.pop() 3 2 1 >>> so obv while var means while not empty or why not zero but it isnt something youd guess unless youd beeen shown it. From adamc55 at gmail.com Mon Jul 7 09:31:57 2008 From: adamc55 at gmail.com (Adam C.) Date: Mon, 7 Jul 2008 06:31:57 -0700 (PDT) Subject: Dynamically Changing the Base Class Message-ID: <6d60c362-ba17-4414-babd-2cc254526bca@c58g2000hsc.googlegroups.com> We have a situation where we want a Swig-generated Python class to have a different base (not object). It doesn't appear that we can coerce Swig into generating the class we want at present (but we are still enquiring). Is it possible to dynamically change the base class to something else? Initial experiments appear to show it is not: -------------------------------- snip -------------------------------- >>> class Foo(object): pass >>> class Foozle(object): pass >>> Foozle.__bases__ = (Foo,) Traceback (most recent call last): File "", line 1, in Foozle.__bases__ = (Foo,) TypeError: __bases__ assignment: 'Foo' deallocator differs from 'object' -------------------------------- snip -------------------------------- Is there a solution I am missing? Thanks in advance. From rw at smsnet.pl Tue Jul 8 15:43:28 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Tue, 08 Jul 2008 21:43:28 +0200 Subject: Logger Configuration References: Message-ID: <87vdzgduvz.fsf@merkury.smsnet.pl> "Robert Rawlins" writes: > Hello guys, > > > > I?ve attached an example of my logging configuration file for you to look at. > The problem I?m experiencing is that the log files are not rotating as I would > expect them to, they just keep growing and growing. > > > > Can you see any reason for this to happen? This is the first time I?ve used a > config file and not just configured the logger programmatically. I think that you should use integers instead of strings in that line: args=('/logs/application.log', 'a', '800000', '5') so it would look like this: args=('/logs/application.log', 'a', 800000, 5) HTH, Rob From norseman at hughes.net Mon Jul 7 21:00:16 2008 From: norseman at hughes.net (norseman) Date: Mon, 07 Jul 2008 18:00:16 -0700 Subject: How to make python scripts .py executable, not bring up editor In-Reply-To: References: Message-ID: <4872BC20.3080702@hughes.net> korean_dave wrote: >>From command Prompt, i type in a script, "tryme.py". > > This, instead, brings up PythonWin editor and Interactive Window. > > Path variable is "C:\Python24". (I need Python 2.4 installed, not 2.5) > > How do I make it so that the script runs? > -- > http://mail.python.org/mailman/listinfo/python-list > ====================================== I get tired of Microsoft jerking me around too. Rather than spend hours trying to undo somebody's reorganizing my system preferences I just ignore them completely. py tryme is how I do it. py.bat is a file placed in a directory listed in PATH in autoexec.bat. Edit autoexec.bat to include directory you put it in and reboot system or it won't find it. something like: PATH=.;c:\py-stuff;[anything already listed] Don't forget the semicolons. The . (period) up front means look here first. here being where ever you are when you issued the command. (The pRESENT wORKING dIRECTORY :-) The c:\py-stuff (fix to suit yourself and make sure it exists) is where you can put your efforts to be called at your leisure. Your .py files you write and use. Even the py.bat can go there. (Short note: Microsoft usually does look in pwd first. But good form dictates being specific.) contents of py.bat: ======================== rem name: py.bat @echo off c:\Python24\python %f.py make it fit your path rem end of file ======================== This way - you get what you expect, when you expect it, & nothing else. Yeah - dumb, but it works! I have one similar for each of my compilers. They contain the whole command line switches stuff as well as things like remove old stuff before trying to over write with new since MS can be temperamental about that. Easiest way in the world to give it the finger and make it behave. Steve norseman at hughes.ney From simon.peverett at gmail.com Mon Jul 14 08:31:03 2008 From: simon.peverett at gmail.com (Impotent Verse) Date: Mon, 14 Jul 2008 05:31:03 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> Message-ID: <378b8499-4b1b-4eda-bb13-91bf59c77bfc@a70g2000hsh.googlegroups.com> If keys and values are unique you could do this... -------------- # Left : Right roman = { "One" : "I", "Two" : "II", "Three" : "III", "Four" : "IV", "Five" : "V", "Six" : "VI", "Seven" : "VII", "Eight" : "VIII", "Nine" : "IX", "Ten" : "X" } left, right = zip( *roman.items() ) left = list(left) right = list(right) print left[ right.index("VIII") ] -------------- ... result is "Eight". Hmmm! zip returns tuples, which need to be turned into lists to do much with. Maybe not the best solution in this case. Verse. From magnusschuster at yahoo.com Tue Jul 29 12:13:51 2008 From: magnusschuster at yahoo.com (Magnus Schuster) Date: Tue, 29 Jul 2008 09:13:51 -0700 (PDT) Subject: proxy class and __add__ method Message-ID: <18715799.post@talk.nabble.com> Hello, I have written the following small proxy class which I expect to pass all function calls to the 'original' object: --- BEGIN --- class proxy(object): def __init__( self, subject ): self.__subject = subject def __getattr__( self, name ): return getattr( self.__subject, name ) prx_i=proxy(1) print hasattr(prx_i,'__add__') j=prx_i.__add__(1) k=prx_i+1 --- END --- Actually the "hasattr(prx_i,'__add__')" returns "True" as expected, and "j=prx_i.__add__(1)" sets j=2. But "k=prx_i+1" raises a : unsupported operand type(s) for +: 'proxy' and 'int'. How is this addition different from the previous line "j=..."? And how can I modify the proxy class so that all methods are passed on, which are not explicitly overloaded? Regards, Magnus -- View this message in context: http://www.nabble.com/proxy-class-and-__add__-method-tp18715799p18715799.html Sent from the Python - python-list mailing list archive at Nabble.com. From diordna at gmail.com Tue Jul 22 11:27:56 2008 From: diordna at gmail.com (Stephen Johnson) Date: Tue, 22 Jul 2008 11:27:56 -0400 Subject: convert list of lists to list In-Reply-To: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> References: <6a40e1d5-c4cb-4581-a052-8461992e316f@d45g2000hsc.googlegroups.com> Message-ID: <370A5418-B09B-4ED4-B3DE-FCBFF7564AB1@gmail.com> list_A = [['klas*', '*', '*'], ['mooi*', '*', '*', '*'], ['koe'], ['arm*', '*', '*(haar)'], ['groei*', '*', '*', '*', '*']] list_B = [] for inner_list in list_A: #join elements of list into a string with separator ' ' list_B.append(' '.join(inner_list)) print list_B Output: ['klas* * *', 'mooi* * * *', 'koe', 'arm* * *(haar)', 'groei* * * * *'] -Steve Johnson On Jul 22, 2008, at 11:10 AM, antar2 wrote: > Is there a way to convert list_of_listsA to list_of_listsB, where one > list in listof lists A is one element of listB? > > list_of_listsA: > [['klas*', '*', '*'], > ['mooi*', '*', '*', '*'], > ['koe'], > ['arm*', '*', '*(haar)'], > ['groei*', '*', '*', '*', '*']] > > listB: > ['klas* * *', 'mooi* * * *, 'koe', 'arm* * * (haar)', 'groei* * * * > *'] > > Thankx! > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.rawlins at thinkbluemedia.co.uk Sat Jul 19 10:46:34 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Sat, 19 Jul 2008 15:46:34 +0100 Subject: __del__ methods In-Reply-To: References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> Message-ID: <016a01c8e9ae$3de4b840$b9ae28c0$@rawlins@thinkbluemedia.co.uk> Hi Duncan, > That sounds like an appropriate use for __del__: it won't matter that it > may not be called when your app exits. Ok, well that's good to know. :-) > Yes, but there is an easy work-around. If you want to track destruction of > objects of type C then don't add a __del__ method to the C objects. Instead > create a separate class which does nothing but track it's own desctruction > and reference that from the class which may be leaking. > > >>> class Track(object): > def __init__(self, parent): > self.parentid = id(parent) > self.parenttype = type(parent).__name__ > def __del__(self): > print "Destroyed <%s object at %s>" % (self.parenttype, > self.parentid) > > > >>> class C(object): > def __init__(self): > self._track = Track(self) > I like this idea, I can definitely see the benefits to working with this concept. One things I will take this quick opportunity to ask, even though it's a little OT: What is the benefit of extending the base 'object' class? What does that give me that en empty, non subclassed object doesn't? > However you should also consider that __del__ only lets you log when > objects are destroyed. Using weak references may be a more useful option as > it will let you track which objects are not being destroyed: you can easily > keep a dictionary of weak references to all existing objects of interest. > Check its length periodically to see whether objects are being leaked and > then inspect the objects themselves to see which ones have leaked. > > You can use gc.get_referrers() to find everything that references a > particular objects and gradually trace backwards until you find the problem > reference (it is tricky though as any code which does this needs to ignore > its own references to the object in question). Yes, that's a very nice concept and like you say gives you quite a nice visual reference of what objects are and aren't being destroyed. Cheers Duncan, Robert From sk8in_zombi at yahoo.com.au Fri Jul 18 06:05:20 2008 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Fri, 18 Jul 2008 03:05:20 -0700 (PDT) Subject: regex doubts Message-ID: <532965.570.qm@web54502.mail.re2.yahoo.com> Hi, I am taking a string as an input from the user and it should only contain the chars:L , M or R I tried the folllowing in kodos but they are still not perfect: [^A-K,^N-Q,^S-Z,^0-9] [L][M][R] [LRM]?L?[LRM]? etc but they do not exactly meet what I need. For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. regards, SZ The string may or may not have all the three chars. " life isn't heavy enough,it flies away and floats far above action" Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.tawn at ubisoft.com Wed Jul 16 05:04:09 2008 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Wed, 16 Jul 2008 11:04:09 +0200 Subject: isPrime works but UnBoundLocalError when mapping on list Message-ID: <8AEDA5E3386EA742B8C24C95FF0C758004623111@PDC-MAIL3.ubisoft.org> Terry Reedy wrote: >Wrong. Thank you. >For loop variables continue after the loop exits. This is >intentional. I never knew that and I can't find reference to it in the docs. Can you help me with the reasons for it? Drea From timr at probo.com Mon Jul 14 01:32:29 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 14 Jul 2008 05:32:29 GMT Subject: while var, but var ==16 != true References: <8c2cd9ff-bec2-4844-82a8-8ce02df5663e@w7g2000hsa.googlegroups.com> Message-ID: maestro wrote: > >why does this work? "while p" = "while p != 0" ? 1 is True and 0 is >false in python but other numbers have no boolean value so why doesnt >it abort. Because your statement is incorrect. Everything has a boolean value in Python. 0, None, False, '' (empty string), [] (empty list), () (empty tuple), and {} (empty dictionary) all have a False value. Everything else has a True value. Python didn't even have a boolean type (True and False) until rather recently (2.2?). This is a very handy feature, and it's one of the things I love about Python. >so obv while var means while not empty or why not zero but it isnt >something youd guess unless youd beeen shown it. It's clearly stated in the documentation. I don't know how you concluded that True and False were the only boolean values. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From asd at pittle.org Thu Jul 3 16:17:04 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Thu, 3 Jul 2008 13:17:04 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: Message-ID: <905975ec-70e0-48ef-9611-a8309170620a@w1g2000prd.googlegroups.com> On Jul 2, 10:39?pm, Ivan Ven Osdel wrote: > Not really, I have just worked with them more. > > ----- Original Message ----- > From: "Ali Servet D?nmez" > To: python-l... at python.org > Sent: Wednesday, July 2, 2008 1:15:04 PM GMT -06:00 US/Canada Central > Subject: Re: Freesoftware for auto/intelligent code completing in Python > > On Jul 2, 7:55?pm, Ivan Ven Osdel wrote: > > The free Python editors/IDEs really do need work as far as code completion goes but I am hopeful. > > > IMO Stani's Python Editor comes closest by providing some code sense through a combination of history and doc strings for Python built-ins. Where it falls short is the ability to scan doc strings for your own code and non built-in modules in the Python path. Python already has the ground work in place to accomplish something similar to VS's XML commenting/intellisense system. With a Python interpretor you can type help(myModule) and get the doc string documentation. So I imagine implementing code sense for code being developed as well as non built-in modules would just be a matter of finding the appropriate module at the right time and piping the output of help([module]) to a popup window. > > > If your willing to help work on something like that I suggest contacting Stani directlyhttp://pythonide.stani.be/orcreating a plugin for Geanyhttp://geany.uvena.de/ > > > Ivan Ven Osdel > > Software Engineerhttp://www.datasyncsuite.com/ > > > ----- Original Message ----- > > From: "Ali Servet D?nmez" > > To: python-l... at python.org > > Sent: Wednesday, July 2, 2008 3:33:59 AM GMT -06:00 US/Canada Central > > Subject: Re: Freesoftware for auto/intelligent code completing in Python > > > On Jul 1, 12:15?am, Fuzzyman wrote: > > > On Jun 30, 10:46?pm, Ali Servet D?nmez wrote: > > > > > I don't want to be so mean here, but how hard it could be be writing a > > > > freesoftware which would automatically/intelligently auto complete > > > > Python code? (I mean something that really does the job, like > > > > Microsoft's Visual Studio or Sun's NetBeans or something else, you > > > > name it, but just don't give me PyDev please...) > > > > > This could be an extension, a plugin, an Emacs mode, a new editor or > > > > even a brand new huge all-fancy IDE, I don't care, but what am I > > > > missing here? > > > > > Could someone please point me out something that I'm really missing > > > > which is already present in the wild, otherwise I'd like discuss with > > > > whoever is willing to help me to get this thing done. I made my mind > > > > and I could volunteer to make this happen as thesis project for my > > > > incoming graduation in the next year. > > > > > Regards you all, > > > > Ali Servet D?nmez > > > > Vim, Emacs, Wing, Komodo, ... more? > > > > Yeah, I guess you're missing something. :-) > > > > Michael Foordhttp://www.ironpythoninaction.com/http://www.trypython.org/ > > > I've checkout Wing IDE's license and it doesnt' seem to be a > > freesoftware; am I wrong? > > Ivan, thanks for your reply. I am curious how come you're suggesting > me those two, but not others. Is there a good/particular reason for > that? > > I see, thank you! I'll certainly keep that in mind. From toby at tobiah.org Wed Jul 2 18:22:34 2008 From: toby at tobiah.org (Tobiah) Date: Wed, 02 Jul 2008 15:22:34 -0700 Subject: Sorting two dimentional array by column? References: Message-ID: >> Imagine an excel spreadsheet. I can choose >> a column and sort the records based on the items >> in that column. I would like to do the same >> thing with a large two dimensional array. >> What would be the fastest way (in computation time) >> to accomplish this? > > Now that I think about the problem more, I really want > to sort an array of dictionaries according one of the > keys of each. Could I use: > > array.sort(key = something) > > Where something looks at the proper item in the > current row? I can't quite visualize how to pull > the item out of the dictionary. Sorry to reply to myself so many times, but I have come up with the answer: from operator import itemgetter thing = [ {'animal': 'duck', 'tool': 'pond'}, {'animal': 'dog', 'tool': 'bone'}, {'animal': 'bear', 'tool': 'hive'} ] get = itemgetter('animal') thing.sort(key = get) print thing ***************************************** [ {'tool': 'hive', 'animal': 'bear'}, {'tool': 'bone', 'animal': 'dog'}, {'tool': 'pond', 'animal': 'duck'} ] ** Posted from http://www.teranews.com ** From vlastimil.brom at gmail.com Fri Jul 11 02:22:51 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 11 Jul 2008 08:22:51 +0200 Subject: Simple question, how do you tell how many items in a list? In-Reply-To: <268ac2770807102256o4f41e784q79a0caf849c046b4@mail.gmail.com> References: <268ac2770807102256o4f41e784q79a0caf849c046b4@mail.gmail.com> Message-ID: <9fdb569a0807102322r7723848dt8e192545a513282e@mail.gmail.com> 2008/7/11, Alex Bryan : > > I am just wondering how you get an integer value for how many items there > are in a list, preferably w/o a for loop. > > -- > http://mail.python.org/mailman/listinfo/python-list > Use len >>> len([1,2,3]) 3 >>> vbr -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at gmail.com Mon Jul 21 07:44:44 2008 From: cwitts at gmail.com (Chris) Date: Mon, 21 Jul 2008 04:44:44 -0700 (PDT) Subject: howto check is function capable of obtaining **kwargs? References: Message-ID: On Jul 21, 1:20?pm, dmitrey wrote: > hi all, > howto check is function capable of obtaining **kwargs? > > i.e. I have some funcs like > def myfunc(a,b,c,...):... > > some like > def myfunc(a,b,c,...,*args):... > > some like > def myfunc(a,b,c,...,*args, **kwargs):... > > some like > def myfunc(a,b,c,...,zz=zz0):... > > So I need to know is the given function capable of handling zz > parameter, for example the call > myfunc(a,b,c,...,zz=4,...) > > Thank you in advance, D. >>> def f(a, b=1, c={}, *args, **kwargs): pass >>> inspect.getargspec(f) (['a', 'b', 'c'], 'args', 'kwargs', (1, {})) >>> print inspect.getargspec.__doc__ Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. Hope that helps. Chris From basti.wiesner at gmx.net Mon Jul 7 10:44:22 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Mon, 07 Jul 2008 16:44:22 +0200 Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: Mark Wooding : > Sebastian "lunar" Wiesner wrote: > >> # perl -e '("a" x 100000) =~ /^(ab?)*$/;' >> zsh: segmentation fault perl -e '("a" x 100000) =~ /^(ab?)*$/;' > > (Did you really run that as root?) How come, that you think so? -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From norseman at hughes.net Tue Jul 22 20:30:08 2008 From: norseman at hughes.net (norseman) Date: Tue, 22 Jul 2008 17:30:08 -0700 Subject: How do I compare files? In-Reply-To: References: <1216769247.18962.7.camel@generator> Message-ID: <48867B90.90406@hughes.net> Timothy Grant wrote: > On Tue, Jul 22, 2008 at 4:27 PM, Clay Hobbs wrote: > >> I am making a program that (with urllib) that downloads two jpeg files >> and, if they are different, displays the new one. I need to find a way >> to compare two files in Python. How is this done? >> >> -- Ratfink >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > I'd start with file sizes. > > If that's not enough you might look at the md5 library and check the md5 > values for the files. > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list =================================== If you are on a Unix platform: man cmp man identify man display (ImageMagick) gimp If you use mc (MidnightCommander) the F3 key can help. Jef Poskanzer's package has tools too. If you are on a Microsoft platform: you needs lots money. :) CorelDraw is available for under $100.00 American Steve norseman at hughes.net From jmike at alum.mit.edu Wed Jul 9 13:39:48 2008 From: jmike at alum.mit.edu (jmike at alum.mit.edu) Date: Wed, 9 Jul 2008 10:39:48 -0700 (PDT) Subject: User-defined exception: "global name 'TestRunError' is not defined" Message-ID: I'm using some legacy code that has a user-defined exception in it. The top level program includes this line from TestRunError import * It also imports several other modules. These other modules do not explicitly import TestRunError. TestRunError is raised in various places throughout the modules. There are a few cases where something goes wrong with the program and I get this error: FATAL ERROR: global name 'TestRunError' is not defined I realize this is kind of a silly question to ask in the general sense without showing more of the code, but does anyone have any suggestions as to the most likely causes of this error coming up? Could it be something like an error happening where it is not explicitly in a try block, or an error happening while I'm already in an except block, or something like that? Thanks, --JMike From fredrik at pythonware.com Mon Jul 21 04:01:04 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 21 Jul 2008 10:01:04 +0200 Subject: regex doubts In-Reply-To: References: <532965.570.qm@web54502.mail.re2.yahoo.com> <504d473e-375a-4111-ae2e-c06aaa37b096@p25g2000pri.googlegroups.com> Message-ID: >> Perhaps you could explain what you mean by "$ does the right thing". > > wtf is wrong with you? (I mean, you do know under what circumstances $ matches a newline character when used without modifiers, right? So why do you keep behaving like a reddit commenter?) From motoom at xs4all.nl Tue Jul 22 21:26:50 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Wed, 23 Jul 2008 03:26:50 +0200 Subject: Python Written in C? Message-ID: <2.2.32.20080723012650.012742b8@pop.xs4all.nl> giveitawhril2008 wrote... > I think someone should write a compiler, "Revenge of BASIC." Your remark made an immediate association with me with the following soundtrack: http://www.empire-of-the-claw.com/files/Empire%20of%20The%20Claw%20-%20Tranc e%20of%20the%2080's%20Arcade.mp3 "A creature for my amusement" Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From Tribulations at Paralleles.invalid Mon Jul 7 01:25:34 2008 From: Tribulations at Paralleles.invalid (TP) Date: Mon, 07 Jul 2008 07:25:34 +0200 Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> Message-ID: Dennis Lee Bieber wrote: > Off-hand, I'd probably try first with: > > csi = "\033[" > > and then define your > > colorblackondarkblue = $csi"30;44m" Thanks for your answer. I have tried this slight modification, but it does not change anything on my terminal. -- TP (Tribulations Parall?les) "Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert). From fabiofz at gmail.com Sun Jul 27 17:29:02 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Sun, 27 Jul 2008 18:29:02 -0300 Subject: Autocompletion and Interactive Tables in a Python IDE In-Reply-To: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> References: <6d0ba3c2-4778-4c7d-97a4-586a6286431a@e53g2000hsa.googlegroups.com> Message-ID: > a) Intellisense (tells you what classes/methods are available and what > variables go into a function) > b) Code Completion (guesses your code after four letters) > c) Data-Orientation; multiple data sessions can be open, data can be > viewed easily > > Python's IDLE has only half of the first of these features. I did a > lot of searching and found the PyDev extensions for Eclipse's Python > IDE, and found that they've got Intellisense. I'm still missing b and > c, and am getting extremely frustrated programming so slowly.. Hi Anthony, Actually, Pydev (both open source and Pydev Extensions) provide 'a' and 'b' -- if it's not showing to you, it may be that the pythonpath is not correctly configured (see http://fabioz.com/pydev/manual_101_root.html for instructions on how to configure it). As for 'c', I'm sure there's more than one plugin that can give that to you within Eclipse (search google for eclipse database plugins) -- I haven't used any of those, so, I can't really comment on them. Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeffrey at fro.man Tue Jul 15 15:50:50 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Tue, 15 Jul 2008 12:50:50 -0700 Subject: 'if name is not None:' v. 'if name:' References: Message-ID: Victor Noagbodji wrote: > Why do people use if name is not None: instead of simply > writing if not name? To differentiate from the case where name == '', or some other non-None false value. So the question is, do you want to test for identity with None, or for truth in general? Jeffrey From wuwei23 at gmail.com Tue Jul 29 08:39:58 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 29 Jul 2008 05:39:58 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> Message-ID: On Jul 29, 2:21?pm, castironpi wrote: > On Jul 28, 5:58?pm, Fuzzyman wrote: > > Well - in IronPython user code gets compiled to in memory assemblies > > which can be JIT'ed. > > I don't believe so. Uh, you're questioning someone who is not only co-author of a book on IronPython, but also a developer on one of the first IronPython-based commercial applications. I know authorship isn't always a guarantee of correctness, but what experience do you have with IronPython that makes you so unwilling to accept the opinion of someone with substantial knowledge of the subject? From andrewthommo at gmail.com Fri Jul 11 23:24:02 2008 From: andrewthommo at gmail.com (Andrew Thompson) Date: Fri, 11 Jul 2008 20:24:02 -0700 (PDT) Subject: paypal wholesale men jordans 17 (paypal accept)(www super-saler com References: <5d746374-d2a0-411e-bf60-87256a219b7c@m44g2000hsc.googlegroups.com> <87skuhqerl.fsf@benfinney.id.au> Message-ID: <8557ccba-9ad1-4f83-9069-e02b80ccdefe@f63g2000hsf.googlegroups.com> On Jul 12, 1:18?pm, Kevin McMurtrie wrote: ... > I strongly recommend dropping all articles with "googlegroups.com" in > the Message-ID. ? I strongly recommend setting follow-ups in inane, multi-posted, spam based threads. F-U set to cam.misc, since I do not read it, and do not care too much to see any replies. -- Andrew Thompson http://pscode.org/ From digitig at gmail.com Mon Jul 7 10:47:39 2008 From: digitig at gmail.com (Tim Rowe) Date: Mon, 7 Jul 2008 15:47:39 +0100 Subject: Can't get Python for Windows to run In-Reply-To: <486e8cf6$0$5679$9b622d9e@news.freenet.de> References: <486E4125.5080201@timgolden.me.uk> <486e8cf6$0$5679$9b622d9e@news.freenet.de> Message-ID: 2008/7/4 "Martin v. L?wis" : > and find installers annoying that ask too many questions So do I, but not as annoying as installers that do the Wrong Thing because they didn't ask! ;-) Still, it's your call. > In any case, try installing with > > msiexec /i 'ProgramMenuFolder=C:\Documents and Settings\All > Users\StartMenu\Programs\Programming' Thanks, that looks like just what I need. -- Tim Rowe From castironpi at gmail.com Mon Jul 21 14:37:43 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 21 Jul 2008 11:37:43 -0700 (PDT) Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> Message-ID: <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> On Jul 18, 2:13?pm, Dan wrote: > On Jul 18, 2:17 pm, castironpi wrote: > > > > > On Jul 17, 11:39 pm, Kay Schluehr wrote: > > > > On 18 Jul., 01:15, castironpi wrote: > > > > > On Jul 17, 5:37 pm, I V wrote: > > > > > > On Thu, 17 Jul 2008 15:08:17 -0700, castironpi wrote: > > > > > > The Python disassembly is baffling though. > > > > > > >>>> y= 3 > > > > > >>>> dis.dis('x=y+1') > > > > > > You can't disassemble strings of python source (well, you can, but, as > > > > > you've seen, the results are not meaningful). You need to compile the > > > > > source first: > > > > > > >>> code = compile('y=x+1','-', 'single') > > > > > >>> dis.dis(code) > > > > > > ? 1 ? ? ? ? ? 0 LOAD_NAME ? ? ? ? ? ? ? ?0 (x) > > > > > ? ? ? ? ? ? ? 3 LOAD_CONST ? ? ? ? ? ? ? 0 (1) > > > > > ? ? ? ? ? ? ? 6 BINARY_ADD > > > > > ? ? ? ? ? ? ? 7 STORE_NAME ? ? ? ? ? ? ? 1 (y) > > > > > ? ? ? ? ? ? ?10 LOAD_CONST ? ? ? ? ? ? ? 1 (None) > > > > > ? ? ? ? ? ? ?13 RETURN_VALUE > > > > > > You may well find these byte codes more meaningful. Note that there is a > > > > > list of opcodes athttp://docs.python.org/lib/bytecodes.html > > > > > Oh. ?How is the stack represented? > > > > As a pointer to a pointer of PyObject structs. > > > > > Does it keep track of which stack > > > > positions (TOS, TOS1, etc.) are in what registers? ?Does stack > > > > manipulation consume processor cycles? > > > > Python does not store values in registers. It stores locals in arrays > > > and accesses them by position ( you can see the positional index in > > > the disassembly right after the opcode name ) and globals / object > > > attributes in dicts. > > > > For more information you might just download the source distribution > > > and look for src/Python/ceval.c. This file contains the main > > > interpreter loop. > > > Ah, found it. ?The parts that are making sense are: > > > register PyObject **stack_pointer; > > #define TOP() ? ? ? ? ? (stack_pointer[-1]) > > #define BASIC_POP() ? ? (*--stack_pointer) > > > ...(line 1159)... > > w = POP(); > > v = TOP(); > > if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { > > ? ? ? ? /* INLINE: int + int */ > > ? ? ? ? register long a, b, i; > > ? ? ? ? a = PyInt_AS_LONG(v); > > ? ? ? ? b = PyInt_AS_LONG(w); > > ? ? ? ? i = a + b; > > ? ? ? ? if ((i^a) < 0 && (i^b) < 0) > > ? ? ? ? ? ? ? ? goto slow_add; > > ? ? ? ? x = PyInt_FromLong(i); > > > ... Which is more than I was picturing was involved. ?I understand it > > is also specific to CPython. ?Thanks for the pointer to the code. > > > My basic question was, what is the difference between compilers and > > interpreters, and why are interpreters slow? ?I'm looking at some of > > the answer right now in "case BINARY_ADD:". > > The basic difference between a (traditional) compiler and an > interpreter is that a compiler emits (assembly) code for a specific > machine. Therefore it must know the specifics of the machine (how many > registers, memory addressing modes, etc), whereas interpreters > normally define themselves by their conceptual state, that is, a > virtual machine. The instructions (bytecode) of the virtual machine > are generally more high-level than real machine instructions, and the > semantics of the bytecode are implemented by the interpreter, usually > in a sort-of high level language like C. This means the interpreter > can run without detailed knowledge of the machine as long as a C > compiler exists. However, the trade off is that the interpreter > semantics are not optimized for that machine. > > This all gets a little more hairy when you start talking about JITs, > runtime optimizations, and the like. For a real in-depth look at the > general topic of interpretation and virtual machines, I'd recommend > Virtual Machines by Smith and Nair (ISBN:1-55860910-5). > > -Dan You're saying the VM can't compile code. That makes sense, it's not a compiler. Do I understand correctly that JIT does compile to native code in some cases? Python: x= y+ 1 Python VM: push, push, add, store Assembly: load, load, add, store Except, the assembly doesn't contain the type-checking that PyInt_AS_LONG does. But that's not the only thing that stops python from precompiling to assembly directly. GNU doesn't come with Python. What sorts of minimal information would be necessary to take from the GNU libs for the user's specific processor, (the one they're downloading their version of Python for), to move Python to the further step of outputting the machine code? From konstantin.selivanov at gmail.com Tue Jul 22 01:10:02 2008 From: konstantin.selivanov at gmail.com (konstantin) Date: Mon, 21 Jul 2008 22:10:02 -0700 (PDT) Subject: string[i:j:k] Message-ID: Hello, I'm not a newbie in python, but recently faced a problem in simple expression: some_string[i:j:k] What does it mean? I believe this grammar (http://docs.python.org/ref/ slicings.html) describes the syntax. But I can't grasp it. Thanks! From david at abbottdavid.com Mon Jul 14 21:04:39 2008 From: david at abbottdavid.com (David) Date: Mon, 14 Jul 2008 21:04:39 -0400 Subject: Python Tiddlywiki class In-Reply-To: References: Message-ID: <487BF7A7.5050602@abbottdavid.com> CracKPod wrote: > Hello, I wrote a Python class to interact with the TiddlyWiki. In case > you are interested you can find it on my blog: > > http://crackpod.bplaced.net/ > > CracKPod > -- > http://mail.python.org/mailman/listinfo/python-list > > > Thank you :) -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From arsyed at gmail.com Fri Jul 25 05:36:55 2008 From: arsyed at gmail.com (arsyed) Date: Fri, 25 Jul 2008 05:36:55 -0400 Subject: 2d graphics - what module to use? In-Reply-To: References: Message-ID: <9a2cc7a70807250236u7e7cfdfaxe326cc1f4bb41cef@mail.gmail.com> On Fri, Jul 25, 2008 at 2:13 AM, Pierre Dagenais wrote: > What is the easiest way to draw to a window? I'd like to draw something > like sine waves from a mathematical equation. > Newbie to python. > -- > http://mail.python.org/mailman/listinfo/python-list > I'd recommend matplotlib: http://matplotlib.sourceforge.net/ Also see the "GUI" and "Plotting" sections on this page: http://wiki.python.org/moin/UsefulModules From mensanator at aol.com Tue Jul 15 14:30:14 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 15 Jul 2008 11:30:14 -0700 (PDT) Subject: isPrime works but UnBoundLocalError when mapping on list References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> <8a07445a-3ca8-4373-9312-cea8db83ec5c@l64g2000hse.googlegroups.com> <9f3c45f1-9cb2-46c1-838b-716180061956@e39g2000hsf.googlegroups.com> Message-ID: On Jul 15, 12:36?pm, defn noob wrote: > On Jul 15, 7:28?pm, Mensanator wrote: > > > > > > > On Jul 15, 11:26?am, defn noob wrote: > > > > isPrime works when just calling a nbr but not when iterating on a > > > list, why? adding x=1 makes it work though but why do I have to add > > > it? > > > Is there a cleaner way to do it? > > > > def isPrime(nbr): > > > ? ? for x in range(2, nbr + 1): > > > ? ? ? ? if nbr % x == 0: > > > ? ? ? ? ? ? break > > > ? ? if x == nbr: > > > ? ? ? ? return True > > > ? ? else: > > > ? ? ? ? return False > > > > >>> [isPrime(y) for y in range(11)] > > > > Traceback (most recent call last): > > > ? File "", line 1, in > > > ? ? [isPrime(y) for y in range(11)] > > > ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > > > ? ? if x == nbr: > > > UnboundLocalError: local variable 'x' referenced before assignment > > > > >>> map(isPrime, range(100)) > > > > Traceback (most recent call last): > > > ? File "", line 1, in > > > ? ? map(isPrime, range(100)) > > > ? File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > > > ? ? if x == nbr: > > > UnboundLocalError: local variable 'x' referenced before assignment>>> isPrime(10) > > > False > > > >>> isPrime(11) > > > > True > > > > adding x=1 makes it work though: > > > > def isPrime(nbr): > > > ? ? x=1 > > > ? ? for x in range(2, nbr + 1): > > > ? ? ? ? if nbr % x == 0: > > > ? ? ? ? ? ? break > > > ? ? if x == nbr: > > > ? ? ? ? return True > > > ? ? else: > > > ? ? ? ? return False > > > > >>> [isPrime(y) for y in range(11)] > > > > [False, True, True, True, False, True, False, True, False, False, > > > False] > > > No, it doesn't. You are falsely reporting that 1 is prime. > > > And instead of making the fake variable x, shouldn't you > > instead test that nbr+1 is greater than 2? Or call it with > > range(3,11) instead of range(11)? x isn't initialized > > because if nbr+1 is <=2, the for loop has an invalid range > > and doesn't even execute. > > def isPrime(nbr): > ? ? for x in range(2, nbr + 1): > ? ? ? ? if nbr % x == 0: > ? ? ? ? ? ? break > ? ? if x == nbr: > ? ? ? ? return True > ? ? else: > ? ? ? ? return False > > this works for all primes, if i want to not include 1 i just do if > nbr<=1 return false > > you are answering the wrong question. No, I also mentioned the for loop having an invalid range, which is why your original failed. Pointing out that 1 isn't prime was a bonus. > > anyway here is a clear one: > def isPrime(nbr): > ? ? if nbr < 2: > ? ? ? ? return False > ? ? for x in range(2, nbr + 1): > ? ? ? ? if nbr % x == 0: > ? ? ? ? ? ? return nbr == x I suppose you're not interested in knowing you don't have to test anything higher than the square root of the number. From workitharder at gmail.com Sun Jul 13 02:04:23 2008 From: workitharder at gmail.com (bukzor) Date: Sat, 12 Jul 2008 23:04:23 -0700 (PDT) Subject: filtering keyword arguments References: <633d6159-7803-4d9b-8f16-2a4a0a197a86@t54g2000hsg.googlegroups.com> Message-ID: On Jul 12, 8:44 pm, Amir wrote: > How do you filter keyword arguments before passing them to a function? > > For example: > > def f(x=1): return x > > def g(a, **kwargs): print a, f(**kwargs) > > In [5]: g(1, x=3) > 1 3 > > In [6]: g(1, x=3, y=4) > TypeError: f() got an unexpected keyword argument 'y' > > Is there a way to do something like: > > def g(a, **kwargs): print a, f(filter_rules(f, **kwargs)) > > so only {'x': 3} is passed to f? > > I was hoping for a pythonic way of doing what in Mathematica is done > by FilterRules: > > http://reference.wolfram.com/mathematica/ref/FilterRules.html Here it is as a decorator: def filter_arguments(func): def func2(*args, **kwargs): import inspect arglist, vararg, kwarg, defaults = inspect.getargspec(func) for k in kwargs.copy(): if k not in arglist: del kwargs[k] return func(*args, **kwargs) return func2 @filter_arguments def func(a=1, b=2): return a+b print func() print func(c=3) print func(a=3,b=4) From bruno.42.desthuilliers at websiteburo.invalid Mon Jul 7 04:52:19 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 07 Jul 2008 10:52:19 +0200 Subject: Validation in plone In-Reply-To: <3d02ab9e-6f81-4b56-b6ef-786e8e6f070a@m44g2000hsc.googlegroups.com> References: <3d02ab9e-6f81-4b56-b6ef-786e8e6f070a@m44g2000hsc.googlegroups.com> Message-ID: <4871d920$0$11997$426a74cc@news.free.fr> Sallu a ?crit : > Hi all and one, > How to do server side validation in plone? Wrong place for Plone related questions. Try the Plone mailing list. From steve at REMOVE-THIS-cybersource.com.au Wed Jul 30 22:54:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Jul 2008 02:54:41 GMT Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <00a124e1$0$20313$c3e8da3@news.astraweb.com> On Wed, 30 Jul 2008 20:55:03 +0100, Matthew Woodcraft wrote: > On the other hand, iterators provide a clear example of problems with > "if x": __nonzero__ for iterators (in general) returns True even if they > are 'empty'. How do you propose telling whether an iterator is empty? That's a generic problem with any sort of lazy function. You don't know if it has finished unless you try grabbing data from it. > For example, this function (which attempts to avoid making an expensive > call when not necessary) is buggy, but easy to write if you've been > taught that "if x" will work with any kind of object. > > def frob(widgets, power): > if widgets: > frobber = Frobber(power) # expensive call > for widget in widgets: > frobber.frob(widget) AFAIK there's no great solution to this problem. It's inherent in the way lazy functions work. Certainly you can't replace the call to "if widgets" with "if len(widgets)", because iterators don't have a length. However, there is a good (but not great) solution: def frob(widgets, power): widgets = iter(widgets) # in case widgets is a sequence try: first = widgets.next() except StopIteration: # empty iterator, nothing to do return None frobber = Frobber(power) # expensive call frobber.frob(widget) for widget in widgets: frobber.frob(widget) -- Steven From ervan.ensis at gmail.com Mon Jul 28 17:24:43 2008 From: ervan.ensis at gmail.com (Ervan Ensis) Date: Mon, 28 Jul 2008 16:24:43 -0500 Subject: seemingly simple list indexing problem Message-ID: My programming skills are pretty rusty and I'm just learning Python so this problem is giving me trouble. I have a list like [108, 58, 68]. I want to return the sorted indices of these items in the same order as the original list. So I should return [2, 0, 1] For a list that's already in order, I'll just return the indices, i.e. [56, 66, 76] should return [0, 1, 2] Any help would be appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Wed Jul 30 14:20:15 2008 From: nagle at animats.com (John Nagle) Date: Wed, 30 Jul 2008 11:20:15 -0700 Subject: Reasoning behind 'self' parameter in classes? In-Reply-To: References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> Message-ID: <4890ac61$0$17215$742ec2ed@news.sonic.net> Matthew Fitzgibbons wrote: > Robert Dailey wrote: >> I've always been curious (more so than annoyed) as to why one must >> explicitly specify a "self" parameter for member functions in a class >> in Python. This seems very "C" like to me, since to do object oriented >> programming in C you must devote one parameter to the object itself. >> In a higher order language like Python, I would not have expected (and >> thus am rather surprised) that this pattern would apply. Is there any >> particular reason why 'self' parameters must be specified explicitly? >> I am curious to understand the philosophy and design behind this. Think about the implications of a language without real declarations and it will come to you. John Nagle Animats From larry.bates at websafe.com` Fri Jul 4 09:21:47 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Fri, 04 Jul 2008 08:21:47 -0500 Subject: compatible image type In-Reply-To: References: Message-ID: gordon wrote: > hi > in my application a file selection by user returns a pathname string > like F:/images/png/my.png or F:/docs/text/somedoc.txt ....etc. > I can get the extension using > extn=string.split(os.path.basename(pathname),'.' )[1] > > then later on i want to create a Photoimage using > > ImageTk.PhotoImage(file=pathname) and display it on a canvas. > > the extn can be anything ..even zip or bat ,doc whatever depending on > user selection...I want to put someway to raise an error message to > the user if he selects a file with extension not of a compatible image > type for PhotoImage.How should i do this? should i check 'extn' to a > list of compatible image type extensions(something like > [''jpg','jpeg','png','gif'...] ) or is there a better way? > > gordon You do know that there is a method for getting extensions easily? extn = os.path.splitext(pathname)[1] Note: It does include the '.' separator (e.g. it returns .txt) but that's easy to handle. If you just catch the exception (as Mark suggested), you don't even have to look at the extension. -Larry From sthembilengidi at gmail.com Mon Jul 21 10:44:05 2008 From: sthembilengidi at gmail.com (Amie) Date: Mon, 21 Jul 2008 07:44:05 -0700 (PDT) Subject: Website Creation using Python Message-ID: Afternoon, I would like some help on how to create a website using the python programming language. I've tried using enamel, but had some problems because I could not create html tables and intergrating it with python, like you use it when coding in php. Any help would be appreciated. Thanks From gherron at islandtraining.com Wed Jul 16 01:29:20 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 15 Jul 2008 22:29:20 -0700 Subject: how to match whole word In-Reply-To: References: Message-ID: <487D8730.60802@islandtraining.com> Peng Yu wrote: > Hi, > > The following code snippet is from /usr/bin/rpl. I would like the it > to match a word, for example, "abc" in ":abc:". But the current one > would not match "abc" in ":abc:". I tried to modify it myself. Would > you please let me know what is the corrected way to do it? > > Thanks, > Peng > > if opts.whole_words: > regex = re.compile(r"(?:(?<=\s)|^)" + re.escape(old_str) + r"(?=\s| > $)", > opts.ignore_case and re.I or 0) > -- > http://mail.python.org/mailman/listinfo/python-list > The regular expression "\w+" will match (what might be your definition of) a word, and in particular will match abc in :abc:. Regular expressions have lots of other special \-sequences that might be worth your while to read about: http://docs.python.org/lib/re-syntax.html Gary Herron From wuwei23 at gmail.com Mon Jul 28 05:52:23 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 28 Jul 2008 02:52:23 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> <6a5506b1-632e-4bf6-b0ce-4d51d1751aa9@i24g2000prf.googlegroups.com> <8b4b11c3-e306-4fe7-82d1-0a948c725f2f@r15g2000prd.googlegroups.com> <239a084f-b73d-4c20-aaaf-bbd05d452638@a2g2000prm.googlegroups.com> <8f675d65-e302-4428-a4bc-f494b230cb59@w1g2000prk.googlegroups.com> <744c27d4-e166-4b3a-9c2c-d4bf1a207fb8@a2g2000prm.googlegroups.com> Message-ID: <553e2d69-7ac7-4b27-bd09-4c35548ce5ec@a3g2000prm.googlegroups.com> On Jul 28, 3:07 pm, "Russ P." wrote: > What was "suggested in rejected" on the thread you pointed me to was > not what I suggested. Not even close. Get it, genius? *sigh* Clearly I don't have better things to do right now than waste my time. You wrote: > So why not allow something like this?: > class MyClass: > def func( , xxx, yyy): > .xxx = xxx > local = .yyy > The "self" argument is replaced with nothing, but a comma is used as a > placeholder. Philip Eby suggested in the thread I linked to: > def .aMethod(arg1, arg2): > return .otherMethod(arg1*2+arg2) > In other words, 'self' here is uniformly replaced by an empty string. So you honestly see no similarity between your suggestion and the latter? Or do you seriously think that placing an errant comma in the argument list is somehow substantively different from placing a period before the function name? Or are you trying to say that '"self" argument is replaced with nothing' is in no way the same suggestion as "'self' here is uniformly replaced by an empty string"? And do you -really- believe that Guido's rejection reasons of * "you're proposing to hide a fundamental truth in Python, that methods are "just" functions whose first argument can be supplied using syntactic sugar" * "that's a lot of new syntax for no gain in readability. You just need to get your head around the fundamental truth" ...somehow don't apply to your suggestion? Did you even read the thread? From drobinow at gmail.com Thu Jul 3 21:25:31 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Thu, 3 Jul 2008 18:25:31 -0700 (PDT) Subject: Copyright issues for an application developed using django, python and mySQL References: <1f23a9fd-33a0-4a06-9733-241c8fd450d2@w4g2000prd.googlegroups.com> Message-ID: <13318ff0-196b-4430-86f3-4839d7859be7@x41g2000hsb.googlegroups.com> On Jul 3, 8:33?pm, Nagu wrote: > ... > How do I go about addressing the copyright and licensing issues? (I do > not know if licensing is the right word here). > > Please advice. > > Thank you, > Nagu I suggest you take the advice of random idiots on a python mailing list. From squishywaffle at gmail.com Thu Jul 31 10:15:20 2008 From: squishywaffle at gmail.com (squishywaffle at gmail.com) Date: Thu, 31 Jul 2008 07:15:20 -0700 (PDT) Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> Message-ID: <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> > Ctypes is a since python2.5 built-in module that allows to declare > interfaces to C-libraries in pure python. You declare datatypes and > function prototypes, load a DLL/SO and then happily work with it. No C, no > compiler, no refcounts, no nothing. > > And you can pass python-functions as callbacks. The first sentence (and some really crummy licensing restrictions imposed by the library distributor) alone here excludes this as a valid option for this particular case, I definitely need Python 2.4 support. So the question comes back around to being how is this same desired behavior duplicated in the Python/C API? From deets at nospam.web.de Thu Jul 17 01:34:22 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 17 Jul 2008 07:34:22 +0200 Subject: how to debug python's extend module written in c/c++ on windows In-Reply-To: <64d771b2-fbc8-4b6a-9725-3dc5063c5328@p25g2000hsf.googlegroups.com> References: <64d771b2-fbc8-4b6a-9725-3dc5063c5328@p25g2000hsf.googlegroups.com> Message-ID: <6e83v4F5pfg0U1@mid.uni-berlin.de> tcfg at sina.com schrieb: > dear all: > > I have searched the debug informations of many python's IDE, but I > cannot find the method about debuging the extend module written in > Visual studio 2008 on windows. > The wingIDE tell me that we can debug the extend module on linux, but > cannot on windows. and using wingdbstub.py we can embed python into > other's source code but not extending. > Who can tell me the skills, I appreciate! I use plain gdb (aka the C-debugger) for this purpose. Create a small test-script that exposes the error you want to debug, and then start the python interpreter in the debugger. Set breakpoints, or watch backtraces. I can't comment on how that works on VS08 though - but it shouldn't be to hard. Diez From neridaj at gmail.com Tue Jul 1 01:33:44 2008 From: neridaj at gmail.com (neridaj at gmail.com) Date: Mon, 30 Jun 2008 22:33:44 -0700 (PDT) Subject: ImportError: No module named _md5 Message-ID: Hello, Does anyone know how to fix this error when trying to build MySQL- python-1.2.2: python setup.py build Traceback (most recent call last): File "setup.py", line 5, in import ez_setup; ez_setup.use_setuptools() File "/Users/jasonnerida/Downloads/MySQL-python-1.2.2/ez_setup.py", line 83, in use_setuptools egg = download_setuptools(version, download_base, to_dir, download_delay) File "/Users/jasonnerida/Downloads/MySQL-python-1.2.2/ez_setup.py", line 111, in download_setuptools import urllib2, shutil File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/ lib/python2.5/urllib2.py", line 91, in import hashlib File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/ lib/python2.5/hashlib.py", line 133, in md5 = __get_builtin_constructor('md5') File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/ lib/python2.5/hashlib.py", line 60, in __get_builtin_constructor import _md5 ImportError: No module named _md5 I then tried installing py25-hashlib via macports, which never completes: sudo port install py25-hashlib Password: Waiting for lock on /opt/local/var/macports/build/ _opt_local_var_macports_sources_rsync.macports.org_release_ports_python_py25- hashlib/work/.macports.py25-hashlib.state Do I need to completely reinstall python? I'm using 2.5.2 which shipped with Leopard. Thanks for any help, Jason From sukkopera at gmail.com Fri Jul 18 09:00:42 2008 From: sukkopera at gmail.com (sukkopera at gmail.com) Date: Fri, 18 Jul 2008 06:00:42 -0700 (PDT) Subject: Unexpected default arguments behaviour (Maybe bug?) References: <4f29ccf6-4daf-4e8e-8735-96cffd8a882e@t54g2000hsg.googlegroups.com> <475185e0-360a-452b-8d22-33ffc243b8a0@z66g2000hsc.googlegroups.com> <98fdc845-cb62-4e7b-891c-dfc75d741a2f@z66g2000hsc.googlegroups.com> Message-ID: On 18 Lug, 13:23, "Sebastian \"lunar\" Wiesner" wrote: > It _is_ the correct thing. ?Evaluation of default parameters at "declaration > time" and not at invocation is truely a language feature, not a bug. > > You'll find your bug report being closed quickly. It has ;). I had totally missed the tutorial section where it is stated, which actually even has an example quite close to the one I provided. Sorry for the waste of time. Giorgio From larry.bates at websafe.com` Tue Jul 29 16:57:27 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 29 Jul 2008 15:57:27 -0500 Subject: static variables in Python? In-Reply-To: References: Message-ID: kj wrote: > Yet another noob question... > > Is there a way to mimic C's static variables in Python? Or something > like it? The idea is to equip a given function with a set of > constants that belong only to it, so as not to clutter the global > namespace with variables that are not needed elsewhere. > > For example, in Perl one can define a function foo like this > > *foo = do { > my $x = expensive_call(); > sub { > return do_stuff_with( $x, @_ ); > } > }; > > In this case, foo is defined by assigning to it a closure that has > an associated variable, $x, in its scope. > > Is there an equivalent in Python? > > Thanks! > > kynn First names in Python are just that, names that point to objects. Those objects can contain any type of information including other objects. They are NOT buckets where things are stored. 1) Names (variables in Perl/C) defined within a Python function are placed in its local namespace. They are not visible in the global namespace. 2) Yes you can have a local name point to a global. This is often used in classes with attributes because looking up local is somewhat quicker than looking up the class attribute. def foo(): x = expensive_call return do_stuff_with(x()) In this particular case it doesn't really help. It would be more useful in something like: class foo(object): def __init__(self, initialvalue = 0) self.currentvalue = initialvalue def longloopingmethod(self, listtosum): currentvalue = self.currentvalue for v in listtosum: currentvalue += v BTW - There are BETTER ways to sum a list, so this is just an example. -Larry From jason at tishler.net Wed Jul 30 15:30:21 2008 From: jason at tishler.net (Jason Tishler) Date: Wed, 30 Jul 2008 15:30:21 -0400 Subject: SVN access with pysvn under Cygwin (Installation problems) In-Reply-To: <69da0a81-bf73-46cb-a762-b017a53e6ddf@e39g2000hsf.googlegroups.com> References: <69da0a81-bf73-46cb-a762-b017a53e6ddf@e39g2000hsf.googlegroups.com> Message-ID: <20080730193021.GA3888@tishler.net> Andy, On Wed, Jul 30, 2008 at 07:46:32AM -0700, Andy Dingley wrote: > Trying to install the pysvn module I'm running into problems getting > it to work under Cygwin. Works fine from a Windows command prompt, > with both the svn_cmd.py example and my own Python code. Under Cygwin > though I just get import failures. pysvn/__init__.py seems to be > invoked happily enough, but then fails when it tries to import > _pysvn_2_5.pyd > > $ python svn_cmd.py > Traceback (most recent call last): > File "svn_cmd.py", line 10, in > import pysvn > File "/usr/lib/python2.5/pysvn/__init__.py", line 104, in > import _pysvn_2_5 > ImportError: No module named _pysvn_2_5 > > Is there some trick to getting .pyd to work under Cygwin? You need to build (and install) pysvn under Cygwin. The pre-built Windows version will not work under Cygwin. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From timr at probo.com Fri Jul 25 00:04:33 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 25 Jul 2008 04:04:33 GMT Subject: interpreter vs. compiled References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> Message-ID: castironpi wrote: > >Compiling a program is different than running it. A JIT compiler is a >kind of compiler and it makes a compilation step. I am saying that >Python is not a compiler and in order to implement JIT, it would have >to change that fact. And I'm saying you are wrong. There is NOTHING inherent in Python that dictates that it be either compiled or interpreted. That is simply an implementation decision. The CPython implementation happens to interpret. The IronPython implementation compiles the intermediate language to native machine language. >> of Python that uses .NET. In that case, the code *IS* JIT compiled to >> assembly when the program starts. > >But still not the user's code, only the interpreter, which is running >in assembly already anyway in CPython. In CPython, yes. In IronPython, no; the user's code is compiled into machine language. Both of them are "Python". -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bj_666 at gmx.net Mon Jul 21 16:56:32 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Jul 2008 20:56:32 GMT Subject: Getting the name of a variable which was used as a function parameter. References: <9e2e64db-d594-408d-9418-b17133f23204@27g2000hsf.googlegroups.com> Message-ID: <6ekbg0F6vgp3U5@mid.uni-berlin.de> On Mon, 21 Jul 2008 09:01:10 -0700, Ravi Kotecha wrote: > I thought this was pretty cool and since I spent 30 mins or so > goggling before giving up and figuring out myself I thought I'd share > it with you. > >>>> def a(a): > ... for k,v in sys._getframe(1).f_locals.items(): > ... if id(v) == id(a): > ... print k > ... > >>>> hello = 123 > >>>> a(hello) > hello > > ## pretty cool. Or ugly hack. Beauty lies in the eye of the beer holder? > It's totally useless but I wanted to do it for logging purposes. Don't use such things in production code, please. Ciao, Marc 'BlackJack' Rintsch From deets at nospam.web.de Tue Jul 29 10:56:16 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 29 Jul 2008 16:56:16 +0200 Subject: Continuous integration for Python projects References: Message-ID: <6f8pelFafh42U1@mid.uni-berlin.de> Hussein B wrote: > Hi. > Please correct my if I'm wrong but it seems to me that the major > continuous integration servers (Hudson, CruiseControl, TeamCity ..) > don't support Python based application. > It seems they mainly support Java, .NET and Ruby. > Can I use one of the previous listed servers for Python project? Hudson can, and AFAIK CC as well - they only invoke shell-scripts (at least hudson does, and CC you can convince doing that using ANT) So go ahead and use them - shouldn't be much (more) effort than for java projects. Diez From dp_pearce at hotmail.com Tue Jul 15 10:10:34 2008 From: dp_pearce at hotmail.com (dp_pearce) Date: Tue, 15 Jul 2008 07:10:34 -0700 (PDT) Subject: Anyone happen to have optimization hints for this loop? References: <43111321-2cc1-4a5e-9189-744131555841@26g2000hsk.googlegroups.com> <7f6c348f-3d49-4483-a3cc-7d4b8eb863a4@27g2000hsf.googlegroups.com> Message-ID: <5d9afe6f-9055-465a-8991-803ca63b7fed@27g2000hsf.googlegroups.com> Thank you so much for all your advice. I have learnt a lot. In the end, the solution was perhaps self evident. Why try and build a huge string AND THEN write it to file when you can just write it to file? Writing this much data directly to file completed in ~1.5 seconds instead of the 3-4 seconds that any of the .join methods produced. Interestingly, I found that my tests agreed with Bruno. There wasn't a huge change in speed between a lot of the other methods, other than them looking a lot tidier. Again, many thanks. Dan From atulskulkarni at gmail.com Mon Jul 28 11:48:38 2008 From: atulskulkarni at gmail.com (Atul.) Date: Mon, 28 Jul 2008 08:48:38 -0700 (PDT) Subject: Encoding for Devanagari Script. References: Message-ID: Hi Fredrik and Terry, Well I got this on IDLE I think I have done something wrong. >>> import codecs >>> f = open("C:\Documents and Settings\admin\My Documents\corpus\dainaikAikya collected by sushant.txt","r", "utf_8") Traceback (most recent call last): File "", line 1, in f = open("C:\Documents and Settings\admin\My Documents\corpus \dainaikAikya collected by sushant.txt","r", "utf_8") TypeError: an integer is required after that I tried the read binary mode and tried reading the firt 32 bytes and this is what I got. >>> f = open("C:\Documents and Settings\\admin\\My Documents\\corpus\\dainaikAikya collected by sushant.txt","rb") >>> f.read(32) '\xef\xbb\xbf\xe0\xa4\xa8\xe0\xa4\xb5\xe0\xa5\x80 \xe0\xa4\xa6\xe0\xa4\xbf\xe0\xa4\xb2\xe0\xa5\x8d \xe0\xa4\xb2\xe0\xa5\x80,' Now based on my knowledge of Unicode I think this is a utf-8 file (the first 3 bytes \xef\xbb\xbf), please correct me if I am wrong. How do I read this? Atul. PS: the above code I wrote using the information from the Library Reference pdf section 4.8 "Codecs". Something wrong I am doing? Please do let me know. On Jul 25, 6:21?am, Terry Reedy wrote: > Atul. wrote: > > Hello All, > > > I wanted to know what encoding should I use to open the files with > >Devanagaricharacters. I was thinking of UTF-8 but was not sure, any > > leads on this? Anyone used it earlier? > > You cannot hurt your machine by giving that a try. > > This is a general comment for all beginners. ?Before posting, open the > interactive interpreter (or IDLE) and try something(s). ?If the result > puzzles you, copy and paste into a post. ?Or if more appropriate, open > the Python manuals and search a bit, or try a search engine. From mrkafk at gmail.com Mon Jul 21 13:49:36 2008 From: mrkafk at gmail.com (mk) Date: Mon, 21 Jul 2008 19:49:36 +0200 Subject: Seriously, though, about LLVM In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > mk wrote: > >> This project has gained some publicity. There's IronPython, right, so >> has anybody thought about implementing Python using LLVM as backend, >> as it seems not out of question at all? > > you mean like: > > http://llvm.org/ProjectsWithLLVM/#pypy > > ? No, I don't mean "Python written in Python", with whatever backend. From tjreedy at udel.edu Wed Jul 9 13:44:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 09 Jul 2008 13:44:31 -0400 Subject: Openine unicode files In-Reply-To: <92793.41064.qm@web27403.mail.ukl.yahoo.com> References: <92793.41064.qm@web27403.mail.ukl.yahoo.com> Message-ID: Noorhan Abbas wrote: > Hello, > I wonder if someone can advise me on how to open unicode utf-8 files > without using the codecs library . I am trying to use the codecs.open() > from within Google Appengine but it is not working. When posting about something 'not working', post at least a line of code and the resulting exception traceback, if there is one, or a printing of the erroneous value, if that instead is the problem. From mefyl at lrde.epita.fr Sat Jul 12 08:16:22 2008 From: mefyl at lrde.epita.fr (mefyl) Date: Sat, 12 Jul 2008 14:16:22 +0200 Subject: sending input to an embedded application References: Message-ID: Uwe Schmitt wrote: > On 12 Jul., 09:08, George Oliver wrote: >> What I would like to do is take a program and embed it or put it >> within a Python-run GUI, using the GUI just to capture and send input >> to the application, and display the ouput. > > Which interface does your interpreter provide ? Just commandline or > can you access by other methods ? > > http://sourceforge.net/projects/pexpect/ might help you > Although Pexpect looks more advanced and complete, you might want to take a look at popen* modules. It enables you to easily run a subprocess, feed him data on stdin, retrieve output from stdout/stderr, and wait for its completion. http://docs.python.org/lib/module-popen2.html -- mefyl R&D engineer at Gostai - http://www.gostai.com To understand recursion, you must first understand recursion. From stochashtic at yahoo.ca Fri Jul 25 05:57:03 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 25 Jul 2008 11:57:03 +0200 Subject: Execution speed question Message-ID: <4889a36f$1@news2-rz-ap.ethz.ch> I am performing simulations on networks (graphs). I have a question on speed of execution (assuming very ample memory for now). I simplify the details of my simulation below, as the question I ask applies more generally than my specific case. I would greatly appreciate general feedback in terms of computing and of course considerations specific to implementation in Python. The nodes in my network may be ON or OFF. The network starts off with all nodes in the OFF state. I loop through the nodes. For each node that is OFF, I consider some probability of it turning ON based on the states of its neighbours. I MUST GO THROUGH ALL NODES BEFORE DECIDING WHICH ONES TO TURN ON. So my question is whether it is faster to 1. loop through a list of ALL nodes and check for OFF nodes using ifs or to 2. loop through a container of OFF nodes and remove from this when they turn ON The second would result in looping through less nodes, especially as the simulation progresses, but how does the cost of removal compare with cheap ifs and would the extra memory usage affect performance. I an appreciate that the cost of the if check, the number of nodes, and the type of container I use will come into the answer. In my case, the ifs are cheap boolean queries (whether the node is ON or OFF). The number of nodes is very large: millions for sure, maybe tens of millions. If considering (2), take note of my BOLD text above, which means I can't remove nodes as I iterate through them in the main loop. I naturally started coding with (2), but couldn't decide on the best data structure for python. A set seemed ideal for speedy removal, but then I can't iterate through them with out popping. An ordered list? Some creative solution with numpy arrays? There is also the complication that since we are in interpreted python, what is theoretically the best data structure may not in reality be optimal unless it is a default system object or coded externally in a compiled module. Of course, I will start experimenting to see what the execution difference is, but I would appreciate some suggestions from others re which is best and also on best data structure for (2). I'm not a newbie, so you can get technical with me python-wise and algorithm wise. I realise it is a 'basic' question, but it is something that I have always wondered about (cheap ifs versus extra structure) and with the number of nodes I am considering, it actually becomes an issue. Many Thanks, Suresh From rmanocha at gmail.com Tue Jul 22 08:01:59 2008 From: rmanocha at gmail.com (Rishabh Manocha) Date: Tue, 22 Jul 2008 17:31:59 +0530 Subject: Converting List of String to Integer In-Reply-To: <45493256-eaff-40e5-8414-59e7ce1b347c@m73g2000hsh.googlegroups.com> References: <45493256-eaff-40e5-8414-59e7ce1b347c@m73g2000hsh.googlegroups.com> Message-ID: <65b679260807220501j77246cdcp642c2814492a8d21@mail.gmail.com> Just to throw my hat in the ring, this is another way you can do this: [(lambda x : [int(ii) for ii in x])(y) for y in a] However, I do think dusans way is more elegant. Best, R On Tue, Jul 22, 2008 at 4:58 PM, dusans wrote: > >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > >>> [map(int, i) for i in a] > [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > On Jul 21, 9:06 pm, Samir wrote: > > Hi Everyone, > > > > I am relatively new to Python so please forgive me for what seems like > > a basic question. > > > > Assume that I have a list, a, composed of nested lists with string > > representations of integers, such that > > > > a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']] > > > > I would like to convert this to a similar list, b, where the values > > are represented by integers, such as > > > > b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]] > > > > I have unsuccessfully tried the following code: > > > > n = [] > > for k in a: > > n.append([int(v) for v in k]) > > print n > > > > Does anyone know what I am doing wrong? > > > > Thanks in advance. > > > > Samir > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From amdescombes at gmail.com Tue Jul 22 15:00:38 2008 From: amdescombes at gmail.com (AMD) Date: Tue, 22 Jul 2008 21:00:38 +0200 Subject: scanf in python In-Reply-To: References: <4884be5e$0$19722$426a74cc@news.free.fr> <488568f6$0$6120$426a74cc@news.free.fr> Message-ID: <48862e5a$0$13865$426a74cc@news.free.fr> > AMD wrote: > >> I had seen this pure python implementation, but it is not as fast or >> as elegant as would be an implementation written in C directly within >> python with no need for import. > > maybe you should wait with disparaging comments about how Python is not > what you want it to be until you've learned the language? > > > Hello Fredrik, I didn't think my comment would offend anyone, I'm sorry if it did. I have been developping in Python for about 5 years, my company uses Python as a scripting language for all of its products. We use Jython for our server products. I think I know it pretty well by now. So I think I have earned the right to try to suggest improvements to the language or at least intelligent discussion of new features without need for offensive comments, don't you think? Andr? From gnewsg at gmail.com Sat Jul 12 15:05:01 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sat, 12 Jul 2008 12:05:01 -0700 (PDT) Subject: heapq question References: <634aa38f-69dc-4934-bf25-43435aba4a27@k37g2000hsf.googlegroups.com> Message-ID: <3d8eef68-ee0f-4708-a2e4-c99a4693d9e4@d45g2000hsc.googlegroups.com> On 12 Lug, 20:15, Duncan Booth wrote: > "Giampaolo Rodola'" wrote: > > > My question is the following: is it safe to avoid to re-heapify() a > > heap when I remove or move an element which is not the first one? > > Example: > > >>>> from heapq import * > >>>> heap = [2,4,6,7,1,2,3] > >>>> heapify(heap) > >>>> del heap[4] > >>>> # Am I forced to heapify() the heap here? > > > Thanks in advance. > > No, it is not safe to avoid re-heapifying. > > After you call heapify the list is ordered such that for any 'n' in the > range 1..len(heap)//2 it is the case that heap[n-1] <= heap[2*n-1] and when > heap[2*n] exists heap[n-1] <= heap[2*n]. > > So: > > >>> heap = [0, 100, 1, 101, 102, 2, 3] > >>> heapify(heap) > >>> heap > > [0, 100, 1, 101, 102, 2, 3]>>> del(heap[4]) > >>> heap > > [0, 100, 1, 101, 2, 3]>>> heapify(heap) > >>> heap > > [0, 2, 1, 101, 100, 3] > > after deleting heap[4] it is no longer the case that heap[1] >= heap[4] as > the old heap[5] was a child of heap[2] not of heap[1]. Even if I avoid to re-heapify() it seems that the first element returned by heappop() is always the smaller one. >>> heap = [0, 100, 1, 101, 102, 2, 3] >>> heapify(heap) >>> heap [0, 100, 1, 101, 102, 2, 3] >>> del heap[4] >>> heap [0, 100, 1, 101, 2, 3] >>> heappop(heap) 0 >>> heappop(heap) 1 >>> heappop(heap) 2 >>> heappop(heap) 3 >>> heappop(heap) 100 >>> heappop(heap) 101 >>> heappop(heap) Traceback (most recent call last): File "", line 1, in IndexError: index out of range >>> That would be ok for me, as long as heappop() always returns the smallest item. Having said that I'd like to understand if there are cases where deleting or moving an element of the heap, causes heappop() to return an element which is not the smallest one. --- Giampaolo http://code.google.com/p/pyftpdlib/ From circularfunc at gmail.com Thu Jul 3 16:40:13 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 3 Jul 2008 13:40:13 -0700 (PDT) Subject: PIL(Py Image lib), show() not showing picture... References: <84a8f15a-594f-4e02-aa89-b70932eae420@59g2000hsb.googlegroups.com> <486d366d$0$879$ba4acef3@news.orange.fr> Message-ID: <09525702-bf03-437b-8fe1-e85a9759a711@2g2000hsn.googlegroups.com> On Jul 3, 10:20?pm, "M?ta-MCI \(MVP\)" wrote: > Hi! > > Which OS? ? On Vista, you MUST reconfig the "aper?u images et > t?l?copies" (in french ; sorry, I don't know the english translation). > > @-salutations > > Michel Claveau thumbnail images and faxes? and how do i do that? i must do it in windows or in the python library? From python at lists.wgwh.ch Wed Jul 16 11:01:08 2008 From: python at lists.wgwh.ch (Oli Schacher) Date: Wed, 16 Jul 2008 17:01:08 +0200 Subject: poplib 100% cpu usage Message-ID: <487E0D34.4060401@lists.wgwh.ch> Hi all I wrote a multithreaded script that polls mails from several pop/imap accounts. To fetch the messages I'm using the getmail classes ( http://pyropus.ca/software/getmail/ ) , those classes use the poplib for the real pop transaction. When I run my script for a few hours cpu usage goes up to 100%, sometimes even 104% according to 'top' :-) This made our test machine freeze once. First I thought I maybe didn't stop my threads correctly after polling an account but I attached a remote debugger and it showed that threads are stopped ok and that the cpu gets eaten in poplib in the function "_getline" which states in the description: ---snip--- # Internal: return one line from the server, stripping CRLF. # This is where all the CPU time of this module is consumed. # Raise error_proto('-ERR EOF') if the connection is closed. def _getline(self): ---snip--- So for testing purposes I changed this function and added: time.sleep(0.0001) (googling about similar problems with cpu usage yields this time.sleep() trick) It now looks ok, cpu usage is at about 30% with a few spikes to 80-90%. Of course I don't feel cozy about changing a standard library as the changes will be overwritten by python upgrades. Did someone else from the list hit a similar problem and maybe has a better solution? Thanks for your hints. Best regards, Oli Schacher From ldo at geek-central.gen.new_zealand Fri Jul 25 00:33:51 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 25 Jul 2008 16:33:51 +1200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <8233fbfb-ad9b-43ef-b722-9738ef129d0b@q5g2000prf.googlegroups.com> Message-ID: In message <8233fbfb-ad9b-43ef-b722-9738ef129d0b at q5g2000prf.googlegroups.com>, Jordan wrote: > On Jul 24, 8:01?pm, Lawrence D'Oliveiro central.gen.new_zealand> wrote: > >> In message >> <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, >> Jordan wrote: >> >> > Except when it comes to Classes. I added some classes to code that had >> > previously just been functions, and you know what I did - or rather, >> > forgot to do? Put in the 'self'. In front of some of the variable >> > accesses, but more noticably, at the start of *every single method >> > argument list.* >> >> The reason is quite simple. Python is not truly an "object-oriented" >> language. It's sufficiently close to fool those accustomed to OO ways of >> doing things, but it doesn't force you to do things that way. You still >> have the choice. An implicit "self" would take away that choice. > > You could still explicitly request non-implicit self on a method by > method basis. That would mean making OO the default. Which Python doesn't do. From tjreedy at udel.edu Mon Jul 7 16:45:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 07 Jul 2008 16:45:58 -0400 Subject: Confused yet again: Very Newbie Question In-Reply-To: <13be8c54-3fa9-4a37-a0e6-45bb019bff7e@a1g2000hsb.googlegroups.com> References: <13be8c54-3fa9-4a37-a0e6-45bb019bff7e@a1g2000hsb.googlegroups.com> Message-ID: Jeff wrote: > When you call c3.createJoe(c1.fred), you are passing a copy of the > value stored in c1.fred to your function. Python passes function > parameters by value. These statements are both wrong. Function argument objects or objects derived therefrom are bound to function parameter names. One could say that Python calls by cross-namespace assignment. No copying is done, anymore than with assignment statements. It returns objects the same way if there is a target to receive them. > The function will not destructively modify its arguments; If the argument is mutable and the function calls a mutation method of the object, it is mutated. tjr From larry.bates at websafe.com` Tue Jul 22 17:52:50 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 22 Jul 2008 16:52:50 -0500 Subject: Iterating Through List or Tuple In-Reply-To: References: Message-ID: Samir wrote: > Is there a way to loop or iterate through a list/tuple in such a way > that when you reach the end, you start over at the beginning? For > example, suppose I define a list "daysOfWeek" such that: > >>>> daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] > > If today is Sunday, I can set the variable "day" to today by: > >>>> i = iter(daysOfWeek) >>>> day = i.next() >>>> print day > sunday > > If I want to find out the day of the week 2 days from now, then this > code works ok: > >>>> for x in xrange(2): day = i.next() > >>>> print day > tuesday > > However, when extending my range beyond the number of items in the > list, I receive an error. For example, if I want to find out the day > of the week 11 days from today, I get this: > >>>> for x in xrange(11): day = i.next() > > > Traceback (most recent call last): > File "", line 1, in > for x in xrange(11): day = i.next() > StopIteration > > Is there a way to easily loop through a list or tuple (and starting > over at the beginning when reaching the end) without having to resort > to an "if" or "while" statement? > > (My question concerns the more general use of lists and tuples, not > necessarily determining days of the week. I know about using "import > datetime" and "from calendar import weekday" but thought that using > the days of the week would best illustrate my problem.) > > As always, thanks in advance. > > Samir >>> import itertools >>> i = itertools.cycle(daysOfWeek) >>> i.next() 'sunday' >>> i.next() 'monday' . . . >>> i.next() 'saturday' >>> i.next() 'sunday' -Larry From lepto.python at gmail.com Mon Jul 14 07:26:49 2008 From: lepto.python at gmail.com (oyster) Date: Mon, 14 Jul 2008 19:26:49 +0800 Subject: a module.pth question Message-ID: <6a4f17690807140426m1d8d6544ye60a5bd560863389@mail.gmail.com> My py24 is installed in h:\python24 I installed pyglet(http://pyglet.org/) in H:\pure_pylib\Multimedia\pyglet-1.0\, if I do [code] >>> import sys >>> sys.path.append(r'H:\pure_pylib\Multimedia\pyglet-1.0') >>> import pyglet [/code] it is ok. but if I created h:\pure_pylib\pyglet.pth file, which containts [code] Multimedia\pyglet-1.0 [/code] then [code] >>> import sys >>> sys.path.append(r'h:\pure_pylib') >>> import pyglet Traceback (most recent call last): File "", line 1, in ? ImportError: No module named pyglet >>> [/code] what is wrong with it? and How to fix it? thanks in advance From ki4yjl at gmail.com Sun Jul 13 19:37:11 2008 From: ki4yjl at gmail.com (WDC) Date: Sun, 13 Jul 2008 16:37:11 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> Message-ID: <7769c9aa-5084-4e71-9699-fd9949e51352@x41g2000hsb.googlegroups.com> On Jul 13, 4:21 pm, Kless wrote: > I need a dictionary where get the result from a 'key' (on left), but > also from a 'value' (on right), how to get it? > > I know that dictionaries aren't bidirectional, but is there any way > without use two dictionaries? > > Thanks in advance! You want to print the key as well as the value? From __peter__ at web.de Sat Jul 12 02:24:04 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Jul 2008 08:24:04 +0200 Subject: MySQLdb will only import for root References: <2bmdnTt3DeQZourVnZ2dnUVZ8uednZ2d@westnet.com.au> <6dothnF3lqqmU1@mid.uni-berlin.de> Message-ID: martinnorth wrote: > Diez B. Roggisch wrote: >> martinnorth schrieb: >>> Hi, >>> >>> I am running Python and MySQL on Ubuntu and have installed MySQLdb. If >>> I try to import MySQLdb I get the following error: >>> >>> ActivePython 2.5.2.2 (ActiveState Software Inc.) based on >>> Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08) >>> [GCC 3.3.1 (SuSE Linux)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> import MySQLdb >>> Traceback (most recent call last): >>> File "", line 1, in >>> ImportError: No module named MySQLdb >>> >>> But if I lrun python as the root user it imports fine. Can anyone >>> suggest what might be wrong with the installation? Or is there nothing >>> wrong? I haven't seen any examples that mentioned being root to import >>> a module. >> >> Try importing sys and printing out sys.path both with a "normal" account >> and the root-account, to see if there are any differences. And of course >> make sure both actually use the same interpreter. >> >> Beyond that, you are right: there is no root-only-importing. >> >> Diez > > Now that I look at, it appears it might not be the same interpreter. > When running python as root I get: > > Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > Which is completely different from when I'm a normal user (see original > post). And yes, sys.path is different. > > Being somewhat new to python and linux, how would I go about fixing > this? How do I get a normal user to run the same interpreter? Is it to > do with my PATH? Yes, you can either invoke the standard interpreter explicitly with $ /usr/bin/python or remove /the/path/to/activestate/python from your PATH. (If you were just experimenting and don't really need ActiveState I recommend that you remove it completely) Peter From tommy.nordgren at comhem.se Mon Jul 28 15:09:10 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Mon, 28 Jul 2008 21:09:10 +0200 Subject: like py2exe, but on a mac In-Reply-To: <_7ojk.253$wS4.85@trnddc03> References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> <_7ojk.253$wS4.85@trnddc03> Message-ID: On 28 jul 2008, at 20.22, William McBrine wrote: > On Mon, 28 Jul 2008 19:51:26 +0200, Tommy Nordgren wrote: > >> There is Platypus, a general open source program to wrap a script >> in an Macintosh (GUI) Application. > > Thanks. I tried Platypus, and it's close to what I want. But I still > can't seem to get rid of the small "Console" window that pops up > behind > my Tkinter app. > > -- > 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on > -- > http://mail.python.org/mailman/listinfo/python-list Try setting the Output popup menu to 'None' ------ What is a woman that you forsake her, and the hearth fire and the home acre, to go with the old grey Widow Maker. --Kipling, harp song of the Dane women Tommy Nordgren tommy.nordgren at comhem.se From mdw at distorted.org.uk Sun Jul 6 12:03:02 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Sun, 6 Jul 2008 16:03:02 +0000 (UTC) Subject: Nested generator caveat References: Message-ID: Dieter Maurer wrote: > I met the following surprising behaviour [code moved until later...] > The apparent reason is that the free variables in nested generator > definitions are not bound (to a value) at invocation time but only at > access time. No. This is about the difference between binding and assignment. Unfortunately, Python doesn't have explicit syntax for doing the former. Here's what's actually going on in your generator. >>>> def gen0(): > ... for i in range(3): > ... def gen1(): > ... yield i > ... yield i, gen1() The function gen0 contains a yield statement; it's therefore a generator. It contains an assignment to a variable i (in this case, it's implicit in the `for' loop). So, on entry to the code, a fresh location is allocated, and the variable i is bound to it. The function gen1 contains a yield statement too, so it's also a generator. It contains a free reference to a variable i, so it shares the binding in the outer scope. Here's the important part: the for loop works by assigning to the location named by i each time through. It doesn't rebind i to a fresh location. So each time you kick gen1, it produces the current value of i at that time. So... >>>> for i,g in gen0(): print i, g.next() > 0 0 > 1 1 > 2 2 Here, the for loop in gen0 is suspended each iteration while we do some printing. So the variable i (in gen0) still matches the value yielded by gen0. But... >>>> for i,g in list(gen0()): print i, g.next() > 0 2 > 1 2 > 2 2 Here, gen0 has finished all of its iterations before we start kicking any of the returned generators. So the value of i in gen0 is 2 (the last element of range(3)). > Almost surely, the same applies to all locally defined functions > with free variables. > This would mean that locally defined functions with free > variables are very risky in generators. It means that you must be careful about the difference between binding and assignment when dealing with closures of whatever kind. Here's an example without involving nested generators. def gen(): for i in xrange(3): yield lambda: i for f in gen(): print f() for f in list(gen()): print f() To fix the problem, you need to arrange for something to actually rebind a variable around your inner generator on each iteration through. Since Python doesn't have any mechanism for controlling variable binding other than defining functions, that's what you'll have to do. def genfix(): for i in xrange(3): def bind(i): def geninner(): yield i return geninner() yield i, bind(i) shows the general pattern, but since a generator has the syntactic form of a function anyway, we can fold the two together. def genfix2(): for i in xrange(3): def geninner(i): yield i yield i, geninner(i) Yes, this is cumbersome. A `let' statement would help a lot. Or macros. ;-) -- [mdw] From joan.pallares at gmail.com Fri Jul 18 12:39:30 2008 From: joan.pallares at gmail.com (=?ISO-8859-1?Q?Joan_Pallar=E8s?=) Date: Fri, 18 Jul 2008 18:39:30 +0200 Subject: Backtracking problem Message-ID: Hi, In my first message in the list I'm going to ask you to solve this problem or at least help me to solve it by myself: We have a list a couples created this way: *parejas = [(1, 'a'), (1, 'b'), (1, 'c'), (1, 'd'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c'), (3, 'd')]* We want to get all te possible combinations in an ordered way. Good combinations examples are: *1a,2b,3c 1a,2b,3d 1b,2a,3c* As you note, the numbers or characters cannont be repeated. The objective is to get one possible combination and if the user wants another possible combination he can get it. And if he wants to get bak the previous combiantion is also has to be possible. That's way I said to *get all possible combinations in an ordered way. * I made a Backtracking algorithm and I get the first result, but I'm not able to get the following result. Any help? My code, just in case it helps you: *parejas = [(1, 'a'), (1, 'b'), (1, 'c'), (1, 'd'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c'), (3, 'd')] print parejas listasCorrectas = [] lista = [] def numerosDiferentes(lista): numeros = [] letras = [] for numero,letra in lista: numeros.append(numero) letras.append(letra) if len(numeros) == len(set(numeros)) and len(letras) == len(set(letras)): return True return False def backTracking(parejas,lista): if len(lista) == 3 and numerosDiferentes(lista): listasCorrectas.append(lista) print 'LISTA CORRECTA',lista return if len(lista) < 2: lista.append(parejas[0]) print lista backTracking(parejas[1:],lista) while(not numerosDiferentes(lista) and len(lista)>1): lista = lista[:-1] lista.append(parejas[0]) print lista backTracking(parejas[1:],lista) backTracking(parejas,lista)* -------------- next part -------------- An HTML attachment was scrubbed... URL: From dstromberglists at gmail.com Thu Jul 10 00:25:53 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Thu, 10 Jul 2008 04:25:53 GMT Subject: error when porting C code to Python (bitwise manipulation) References: Message-ID: On Wed, 09 Jul 2008 20:56:59 -0700, Jordan wrote: > I am trying to rewrite some C source code for a poker hand evaluator in > Python. Putting aside all of the comments such as just using the C > code, or using SWIG, etc. I have been having problems with my Python > code not responding the same way as the C version. > > C verison: > > unsigned find_fast(unsigned u) > { > unsigned a, b, r; > u += 0xe91aaa35; > u ^= u >> 16; > u += u << 8; > u ^= u >> 4; > b = (u >> 8) & 0x1ff; > a = (u + (u << 2)) >> 19; > r = a ^ hash_adjust[b]; > return r; > } > > > my version (Python, hopefully ;)): > > def find_fast(u): > u += 0xe91aaa35 > u ^= u >> 16 > u += u << 8 > u ^= u >> 4 > b = (u >> 8) & 0x1ff > a = (u + (u << 2)) >> 19 > r = a ^ hash_adjust[b] > return r > > > As far as I understand the unsigned instructions in C just increase > amount of bytes the int can hold, and Python automatically converts to > longs which have infinite size when necessary, so I am not sure why I am > getting different results. > > I assume that I am missing something fairly simple here, so help a n00b > out if you can :) > > Thanks in advance, > > jnb What business does a poker hand evaluator have doing that kind of bitwise arithmetic? One problem with C is not the language itself, but the culture of using bitwise tricks where they aren't really necessary. Anyway, I believe in C unsigned bitwise arithmetic, when overflowing an integer will simply throw away the bits that are "too big". So if python is converting to a long when overflowing, that would cause a different result right there. You could try throwing in "&= 0xffffffff" all over the place if the C code was written for a 32 bit unsigned int. unsigned int will usually be 32 or 64 bits these days. If it's a 64 bit unsigned int in C, it'd be "&= 0xffffffffffffffff". From dickinsm at gmail.com Sun Jul 20 10:56:26 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 20 Jul 2008 07:56:26 -0700 (PDT) Subject: round function error??? References: <2da2f5f1-7ff2-46d7-a768-f0817e414615@f36g2000hsa.googlegroups.com> Message-ID: On Jul 19, 12:20?am, John Machin wrote: > On Jul 19, 8:05 am, Mark Dickinson wrote: > > for more information. ?But I'm guessing that you're > > questioning the fact that a value that's apparently > > *less* than 3499.35 is rounded up to 3499.4, rather > > than down to 3499.3. ?? > > "apparently" being the operative word. Well, it's not just an apparent problem: the closest floating-point number to 3499.35 really *is* less than 3499.35. A nice way to check this is using the new fractions module in 2.6, which allows exact conversions of floats and Decimals into rational numbers: Python 2.6b2+ (trunk:65155, Jul 20 2008, 15:39:46) [GCC 4.0.1 (Apple Inc. build 5484)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from decimal import Decimal >>> from fractions import Fraction >>> x = 3499.35 >>> y = Decimal('3499.35') >>> Fraction.from_float(x) Fraction(7695152029315891, 2199023255552) >>> Fraction.from_decimal(y) Fraction(69987, 20) [54933 refs] >>> Fraction.from_float(x) < Fraction.from_decimal(y) True Mark From wolfgang.grafen at ericsson.com Tue Jul 29 11:14:49 2008 From: wolfgang.grafen at ericsson.com (Wolfgang Grafen) Date: Tue, 29 Jul 2008 17:14:49 +0200 Subject: Parsing VHDL with python, where to start. In-Reply-To: References: <31888260-86a9-46b0-b0a4-79f7852f256a@k30g2000hse.googlegroups.com> Message-ID: <488F33E9.8090004@ericsson.com> Svenn Are Bjerkem schrieb: > Hi again, > > when I get far enough to parse the VHDL (which is not currently the > fact, but I have to look at the work coming up downstream) I will have > to put it into an internal data structure and then write some classes > to handle the MVC between whatever data I have and the PyQt4 widget > that is going to show the block diagram. I own the book "Rapig GUI > Programming with Python and Qt" by Mark Summerfield and try to read up > on the PyQt way of doing things as I try to make a plan for my > application. I have been looking for possible data structures with > google just to find out that most of the ideas are stored in > proceedings or to conferences or ieee papers not generally available > to me. Is anybody experienced with designing data structures willing > to share some ideas with me? Since I am using the open-source version > of PyQt4, any information will eventually be available to public (if > the app pass the planning stage) if that makes helping out any > easier: :-) There is already an app called Qucs that is running in > Qt-3 and being ported to Qt-4 that is written in C++, but I don't know > how wise it is to just reverse-engineering C++ classes and translate > them into python classes. For me it is not very clear what you intend to do. After years of parsing parts of VHDL from time to time the rapid parsing way for me is using regular expressions instead of one of the parser frame works because of following reasons: - It is hard for me to understand those frameworks - They are very slow - It is too much work for me to bring them up to work in a sensible way - Compared with regular expression matching they usually need a lot of extra work. Regular expressions work very well once the validation of the VHDL code was done by one of the commercial compilers. Once you can rely on the code that it is valid VHDL - Parse it with a regular expression for simple VHDL structures or - Extract a structure first and analyse that with a set of regular expressions The result can be stored into a combination of lists and dictionaries, dependend on the problem. For processing with other tools the results could be stored into XML structures. PyQt as a widget framework is not useful until here, but of course you could display your results in arbitrary graphical ways with PyQt, if you rally need to. You should know, printing out an ASCII or XML representation is so much more easy and quicker to code so I always prefer that. There are even editors/visualizers ready to display XML... Best regards Wolfgang From gagsl-py2 at yahoo.com.ar Tue Jul 15 00:26:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Jul 2008 01:26:03 -0300 Subject: a module.pth question References: <6a4f17690807140426m1d8d6544ye60a5bd560863389@mail.gmail.com> Message-ID: En Mon, 14 Jul 2008 08:26:49 -0300, oyster escribi?: > My py24 is installed in h:\python24 > I installed pyglet(http://pyglet.org/) in > H:\pure_pylib\Multimedia\pyglet-1.0\, if I do > [code] >>>> import sys >>>> sys.path.append(r'H:\pure_pylib\Multimedia\pyglet-1.0') >>>> import pyglet > [/code] > it is ok. > > but if I created h:\pure_pylib\pyglet.pth file, which containts > [code] > Multimedia\pyglet-1.0 > [/code] > > then > [code] >>>> import sys >>>> sys.path.append(r'h:\pure_pylib') >>>> import pyglet > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named pyglet .pth files are searched only when Python starts (specifically: when the site.py script is executed). If you later add a directory containing a .pth file, it is *not* processed. Put your .pth files inside a directory *already* in the search path - see http://docs.python.org/lib/module-site.html -- Gabriel Genellina From skip at pobox.com Tue Jul 22 21:09:26 2008 From: skip at pobox.com (Skip Montanaro) Date: Wed, 23 Jul 2008 01:09:26 +0000 (UTC) Subject: software engineering foundations? References: <18566.11394.326317.821553@montanaro-dyndns-org.local> Message-ID: > just get McConnell's "Code Complete": > > http://www.cc2e.com/ Thanks Fredrik. It looks interesting. I just bought a copy online and will skim it myself before passing it along to Chris. Skip From ldo at geek-central.gen.new_zealand Sat Jul 26 19:45:39 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 27 Jul 2008 11:45:39 +1200 Subject: Function editing with Vim throws IndentError References: <4d1e1d1e-def7-4cc9-83a8-9c049cf8a301@8g2000hse.googlegroups.com> Message-ID: In message , Thomas Troeger wrote: > Finally, I'd like to throw in this one from the Linux kernel sources, > from `Documentation/CodingStyle: > > ------------------------------------------------------------------------ > > Chapter 1: Indentation > > Tabs are 8 characters, and thus indentations are also 8 characters. > There are heretic movements that try to make indentations 4 (or even 2!) > characters deep, and that is akin to trying to define the value of PI to > be 3. > > [...] > > Now, some people will claim that having 8-character indentations makes > the code move too far to the right, and makes it hard to read on a > 80-character terminal screen. The answer to that is that if you need > more than 3 levels of indentation, you're screwed anyway, and should fix > your program. Which is, of course, a load of nonsense. From szrRE at szromanMO.comVE Tue Jul 22 18:14:41 2008 From: szrRE at szromanMO.comVE (szr) Date: Tue, 22 Jul 2008 15:14:41 -0700 Subject: proliferation of computer languages References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> <40429b65-23a0-489b-b5fd-ae6b8eee607d@t54g2000hsg.googlegroups.com> Message-ID: Grant Edwards wrote: > On 2008-07-22, szr wrote: >> J?rgen Exner wrote: >>> Chris Rathman wrote: >>> >>>> I can't say that I see any particular point to the essay. >>> >>> You must be new here. There never is any particular point to >>> Xah Lee's rantings except to cross-post borderline topics to >>> borderline relevant NGs and then lay back and enjoy the >>> ensuing slaughter. >> >> Admittedly, I'm not all too familiar with his postings, but on >> a general note, isn't it possible that someone else might not >> see it the same as you do? I really didn't see anything really >> sinister about the posting or it's content. > > That's the, uh, "beauty" of Xah Lee's posts. There's enough > "there" there to suck people into what they think is going to > be a conversation. But it's not really a conversation. He > doesn't really read (or doesn't comprehend) responses to his > posts and will just continue to ramble on in a somewhat > insulting, half-rational stream of utterly opaque metaphors > that he thinks makes him sound deeply philosphical. It has > been theorized that he's an AI project. So, some dark government experiment gone horribly wrong? >> It may very well be someone attempting to create a >> conversation, someone who may not be generally well received a >> lot of the time I gather. > > Quite a few people here in c.l.p put forth a a lot of effort > (for Usenet, anyway) trying to have a reasonable exchange with > xah lee, but it seems to be pointless. He's a perpetual critic > who looks down his nose at everything and thinks he could do > everything better than everybody else (not that he has actually > ever _done_ anything, AFAICT). That's good to know. >> Also, if have such a distaste for his postings, you are free >> to ignore them as well. That said, I am all for alerting >> someone of something which may be a complete waste of their >> time, > > It's not a waste of your time if you find him entertaining, but > I wouldn't expect any actual conversation where he reads and > understands your replies and responds to them in a rational > manner. Yeah I wasn't really aware it was that bad. >> but in this case it feels like you are projecting your >> own dislike for the OP. Unless the OP really is deserving of >> such branding (in which case I'd stand corrected), I don't >> think it is reason enough to tell others not to read of his >> work just because you aren't particularly fond of it. >> >> Perhaps citing an actual example illustrating a reason to >> avoid him like the plague would of helped :-) > > google groups should be able to find you plenty of examples > both here and in perl groups. Thank you for filling in some voids. -- szr From frankrentef at yahoo.com Tue Jul 29 14:26:28 2008 From: frankrentef at yahoo.com (frankrentef) Date: Tue, 29 Jul 2008 11:26:28 -0700 (PDT) Subject: Python / PAMIE - scriptWrite Function Message-ID: In using PAMIE 2.0 specifically the "scripWrite" function I'm getting the following error... File "C:\Python23\Lib\site-packages\win32com\client\dynamic.py", line 489, in _getattr_ further states... raise AttributeError, "%s.%s" % (self._username_, attr) Help... :) From martin at v.loewis.de Mon Jul 28 17:06:04 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Mon, 28 Jul 2008 23:06:04 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: <5Gojk.254$wS4.153@trnddc03> References: <5ctn849uqrmr3v2t38tot6o0abfft558j1@4ax.com> <488cbeeb$0$17104$9b622d9e@news.freenet.de> <5Gojk.254$wS4.153@trnddc03> Message-ID: <488E34BC.4060005@v.loewis.de> > I hadn't heard "Intel 64" before. That's a bit nervy, isn't it? Plus it > seems to conflict with their own use of "IA-64" (Intel Architecture 64) > for the Itanium (vs. "IA-32" for traditional x86). Indeed. Microsoft Installer has an architecture string for the MSI file; "Intel64" there means Itanium (and AMD64 can be denoted by either "AMD64" or "x64"). This was from a time when Intel still told people that the future of 64-bit computing is in Itanium (and architecturally, I still think this would have been the right choice). Regards, Martin From quekshuy at gmail.com Thu Jul 3 13:51:19 2008 From: quekshuy at gmail.com (Quek) Date: Thu, 3 Jul 2008 10:51:19 -0700 (PDT) Subject: Times where one would use new style classes vs classic classes References: <6700e4ba-8573-44da-b75a-3b3e5ba1fd9b@i36g2000prf.googlegroups.com> <486c7ba7$0$10446$426a74cc@news.free.fr> Message-ID: <75aa3baa-f495-4d51-bf48-185ad966fe5d@u6g2000prc.googlegroups.com> On Jul 3, 3:11?pm, Bruno Desthuilliers wrote: > Quek a ?crit : > > > Hi all, > > > I'm reallynewto Python and I've been reading up some texts on older > > versions of Python (2.2 to be specific). > > > The text briefly mentionednewstyleand classic classes. > > > I'd really like to know in the current context of Python 2.5, besides > > in the cases of multi-inheritance, where would I usenewstyle > > classes? > > Everywhere you don't have to support compat with ages-old versions of > Python. MI is not the main point of newstyle classes (FWIW, you can do > MI with old-styleclasses too), they have quite a lot more to offer. > Consider "classic" classes as a legacy feature, period. Thanks everyone. From norseman at hughes.net Thu Jul 17 15:04:43 2008 From: norseman at hughes.net (norseman) Date: Thu, 17 Jul 2008 12:04:43 -0700 Subject: Rotating a cube In-Reply-To: References: Message-ID: <487F97CB.10404@hughes.net> J-Burns wrote: > Hello. Need some help here. I have a 4*4 cube. So the equation of the > cube becoming: > > x + 4*y + 16*z > > Now i want to rotate this cube 90 degrees anticlockwise( a right > rotation). How can i do that? The rotation must take place with the > axis of rotation being the straight line through the center of the > cube and perpendicular to the "xz-plane." The axis are aligned in this > fashion: > > y > | > | > |________ x > / > / > z > > Moreover, also tell me how to perform a rotation with the axis of > rotation being the straight line through the center of the cube and > perpendicular to the "yz-plane." > > Essentially, I need the equations of the lines after the rotation has > been done in both cases. > Is there a built in Python function for this? > -- > http://mail.python.org/mailman/listinfo/python-list > ====================================== OH-Boy! 1) a regular cube is dimensioned having three mutually perpendicular axis, each of same length. The 4x4 would be for a plane. 2) Clockwise IS Angles Right. (Rotate to right.) Normal Angles Right would put zero at +Y, 90 at +X as viewed from +Z. Norman Angles Right would put zero at +Z, 90 at +Y as viewed from +X. Normal Angles Right would put zero at +Z, 90 at -X as viewed from +Y. (there are six faces, finish the defs for the rest.) 3) Normally all rotations are defined as pivoting about the 0,0,0 point. To use center of a plane or other pivot point is to add offsets. 4) Sequence of rotations controls final spatial orientation. As for finding a cube handling graphic in the standard package download, I did not. Somebody else can answer if there is a full blown Python vector graphic package. At a minimum you need to define a: rotational routine that handles N 3D points as a single bundle. The usual routines consider each rotation as being about a single axis. It computes all N corners each time. translation routine that moves N 3D points as a single bundle along a single 3D vector. It computes all N corners each time. scaler routine that expands/contracts the relative distances between the N 3D points using vectors from the computed 3D center. It computes all N corners each time. Some pre-/post routines to put things together to get the desired effects. If N=0 (the nothing) there is nothing to do. If N=1 (the point) there is no rotation or scale. If N>1 (the line,plane,box,sphere,torus,etc.) then use all three. (a sphere can be computed as three points of an isosceles triangle in which the third side can equal the other two. The points then are used to create a circle (ellipse) which is rotated about the third side. In case it isn't obvious - the perpendicular bisector of the third side is the center of the sphere. To track a point on a sphere is simply to use 4 points. 0,1,2 are triangle and 3 is the point. Do your thing on all 4, use 0,1,2 to remake sphere and 3 will be right place.) The Chemical Rubber Company's Handbook of Physics and Chemistry is a good starting point for the equations. Johnny, George, Willie and I also used a few Celestial Mechanics books from the Library when we wrote those in assembly in the long ago and far away. (back in the '60s on the other side of the continent.) Sorry, but the punch cards disappeared long ago and access to CAD programs deletes my need to re-write them. Steve norseman at hughes.net From wjmtrade003 at gmail.com Fri Jul 18 13:17:55 2008 From: wjmtrade003 at gmail.com (avan) Date: Fri, 18 Jul 2008 10:17:55 -0700 (PDT) Subject: accept paypal,www.wjmtrade.com sell adidas35 jordan af1 bape puma Message-ID: <5009fd51-e24d-4b34-8307-ba1ddb7f1490@u12g2000prd.googlegroups.com> We are manufacturer/wholesaler for branded sport shoes and clothings, supplying 3A quality product with reasonable price, such as series of : Jordan 1-22 Air force one (AF1),Dunks, air max 95,97,2003,2004,2005,tn shox TL/TL2/TL3, R4/R5, monster, turbo, NZ bape shoes,adidas ,Timberlands etc. t-shirt, hoody, jeans,bag, watch etc. 1) high quality. All the Shoes we offer are of the grade AAA. Packing: original box with retro cards tags 2) safety. We have a lot of experience to pass the custom inspection. 3) fast shipment. We have agreement with some international express Corporation, the shoes will be sent out within 24 hours after we receive your Payment. You will receive the shoes within 5-7 days. 4) lowest Price. We can give you competitive price based on equal conditions in china. 5) We are very serious business man.hope do the long term business with you! please kindly visite our website: www.wjmtrade.com msn: wjmtrade at hotmail.com email: wjmtrade at gmail.com From fredrik at pythonware.com Wed Jul 16 05:16:28 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 11:16:28 +0200 Subject: Testing for connection to a website In-Reply-To: <18476597.post@talk.nabble.com> References: <18473382.post@talk.nabble.com> <18476597.post@talk.nabble.com> Message-ID: Alexnb wrote: > e = '' > try: > ... > except HTTPError, e: > print e.code > except URLError, e: > print e.reason > > if e == '': > print "good to go" footnote: here's a better way to test if an exception was raised or not: try: ... except HTTPError, e: print e.code except URLError, e: print e.reason else: print "good to go" From h.goebel at goebel-consult.de Wed Jul 30 03:48:52 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Wed, 30 Jul 2008 09:48:52 +0200 Subject: Using McMillan Installer, PyInstall or py2exe cross-platform? In-Reply-To: <6e1492db-6868-4554-9b85-96c1717b6b6a@s50g2000hsb.googlegroups.com> References: <487b7890$0$7553$9b4e6d93@newsspool1.arcor-online.net> <487d100a$0$7538$9b4e6d93@newsspool1.arcor-online.net> <6e1492db-6868-4554-9b85-96c1717b6b6a@s50g2000hsb.googlegroups.com> Message-ID: <48901ce5$0$20699$9b4e6d93@newsspool4.arcor-online.net> Paul Boddie schrieb: > On 15 Jul, 23:00, Hartmut Goebel wrote: >> I started working on cross-pyinstall today. > > Let us know how you get on! In theory, one should be able to build > Python (and derived works) using the mingw32 libraries and a suitable > cross-compiler on platforms other than Windows, but I've never > bothered to do so myself. Pyinstaller trunk is now able to build exe for Windows on Linux/Unix. This includes only the "bundling" of scripts and modules into an exe, not compiling anything. -- Sch?nen Gru? - Regards Hartmut Goebel Goebel Consult Spezialist f?r IT-Sicherheit in komplexen Umgebungen http://www.goebel-consult.de From frank at chagford.com Thu Jul 31 02:30:16 2008 From: frank at chagford.com (Frank Millman) Date: Wed, 30 Jul 2008 23:30:16 -0700 (PDT) Subject: Questions about asyncore References: <5d30aad5-cad7-4e47-aa83-277202c70ae2@z72g2000hsb.googlegroups.com> <6db7042c-02bb-42ef-b578-3811d8f427f5@m36g2000hse.googlegroups.com> <4903018c-feac-40fb-81fc-002dfc430f84@z66g2000hsc.googlegroups.com> Message-ID: <85bd837a-62e3-455d-8bec-3d778231bfc5@i76g2000hsf.googlegroups.com> On Jul 30, 7:50?pm, "Giampaolo Rodola'" wrote: > On 30 Lug, 09:49, Frank Millman wrote: > Thanks again, Giampaolo, your input is really appreciated. > > I pretty much have the same overview I had before. > As far as I can tell the only reason you want to use a thread is when > you have to do something which requires a consistent amount of time to > complete so that the asyncore loop gets blocked. > The question is: is there anything like that in your code? > If the answer is no then you don't need to use threads. > Maybe you are just not used to the asynchronous approach where "wait > for server to respond" or "wait for the response to be complete" > doesn't mean that YOU have to wait. > It means that when a specific condition occurs (e.g. some data is > received) a certain method of the framework you're using will be > called and then it will be up to you deciding what do to. Maybe I am not being clear enough on my side. I (hope I) understand the power of asnyc. I have written the server to use async techniques, and when I get around to writing the full-blown client, that will also use async techniques. However, at this stage, all I want to do is write something quick and dirty to check that the server is behaving as intended. I want to throw some messages at it, more or less at random, and check the responses. I found it much easier to do this with asyncore.loop running in a separate thread. To send a message from the main thread, I append it to a list called self.sendData. In asyncore.dispatcher, writable() returns True if the list contains anything, and handle_write() pops the message off the list and sends it. To receive messages, readable() always return True, and handle_read() breaks up the input into individual messages and appends them to a list called self.recvData. When the main thread is waiting for a response, it simply loops until self.recvData contains something. To do this asynchronously, for every test I would have to define the detailed interaction between client and server, and write methods to be called from within handle_read(). It could be done, but it would be much more tedious. Does this make sense? Frank From alif016 at gmail.com Mon Jul 7 21:53:15 2008 From: alif016 at gmail.com (Andrew Freeman) Date: Mon, 07 Jul 2008 20:53:15 -0500 Subject: Python Agile Software Development Tools Screencasts In-Reply-To: <87abgtw52g.fsf@benfinney.id.au> References: <079f600a-7354-4a10-8e3c-3ea01e1fe3b5@f36g2000hsa.googlegroups.com> <87lk0dwbys.fsf@benfinney.id.au> <87hcb1w6gl.fsf@benfinney.id.au> <87abgtw52g.fsf@benfinney.id.au> Message-ID: <4872C88B.4080307@gmail.com> Ben Finney wrote: > Robert Kern writes: > > >> Ben Finney wrote: >> >>> Okay. Where would the public link to those files be? >>> >>> If I need to "log in" just to download it, that's a needless barrier >>> that's going to turn me away too. >>> >> Yes, you do need to log in. >> > > Thanks. > > >> If you don't want to do it, that's fine. I certainly don't care. >> > > No problem. > > I hope the OP, who wanted people to see his videos, does care enough > to put them somewhere people can get them without needless barriers. > > The URL for the flv is: http://videos1.showmedo.com/ShowMeDos/2910000.flv I hope the presenter doesn't mind, but it is quite simple to discover using open source tools like firebug. As for playing back flvs with free software, there is Gnash -- an open source flash player -- http://www.gnu.org/software/gnash/ -- Andrew From Bill at SynectixLtd.com Fri Jul 4 10:03:19 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Fri, 4 Jul 2008 15:03:19 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: "Tim Golden" wrote in message news:mailman.61.1215177888.20628.python-list at python.org... > Bill Davy wrote: >> I am trying to edit Contacts in Outlook. This is so I can transfer >> numbers from my address book which is an Excel spreadsheet to my mobile >> phone. I came across the following snippet of code > > --- hey! that looks familiar :) > >> which enabled me to the contacts at least list. I had to root around to >> discover CdoDefaultFolderContacts (though it was guessable; how could I >> enumerate win32com.client.constants?). > > Well that bit's easy: win32com.client.constants is a small class with > a __dicts__ attribute (note the "s") which is a list of dictionaries, one > per generated library. So you can do something like this: > > > import win32com.client > > outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") > outlook_constants = win32com.client.constants.__dicts__[0] > > for k, v in outlook_constants.items (): > print k, "=>", v > > > >> I now want to work through the Contacts in Outlook patching in data from >> my spreadsheet, and also making new contacts where there is an entry in >> my spreadsheet which has not gone into Contacts already. > > OK. > >> Where can I find the API? > > I recommend: > > http://msdn.microsoft.com/en-us/library/ms526861.aspx > > and > > http://www.outlookcode.com/article.aspx?id=20 > > and > > http://www.cdolive.com/cdo10.htm > > TJG Brilliant. But I was a bit disappointed by one experiment. In MSDN I found "Exploring the Outlook Object Model". That suggested: Outlook | Tools | Macros | VB Editor | View | Object Browser There I found ContactItems and reckoned I was onto a winner, but found that a "message" from the ContactFolder might have Subject but it did not have a FullName. Also, if Python crashed, it left Outlook complaing that someone was accessing it but had disappeaared so Outlook has to be restarted each time. But you have suggested some more things to look at so thanks. I have had a quick look but have not so far even found "Subject" as a member/property of a message/contact. I shall keep looking. Rgds, Bill From manuel.dipl at gmail.com Mon Jul 14 14:46:43 2008 From: manuel.dipl at gmail.com (manu) Date: Mon, 14 Jul 2008 11:46:43 -0700 (PDT) Subject: trying to use sax for a very basic first xml parser References: <6ff86003-a3e8-4c5b-9276-1cd3c7f0ffa7@56g2000hsm.googlegroups.com> <3a7148a9-b95d-4e95-b3b7-492e0d016ab8@f36g2000hsa.googlegroups.com> Message-ID: On Jul 14, 8:14?pm, Miki wrote: > Python is using an external library for SAX (expat IIRC). > I *guess* the Python that comes with Blender don't have this library. > I don't know... I didnt install any external libraries for sax. I think python comes with a standard sax library. And before I had python installed Blender said at startup: "Compiled with Python version 2.5. Checking for installed Python... No installed Python found. Some scripts will not run. Continuing happily" After installing Python 2.5.2 it now says: "Compiled with Python version 2.5. Checking for installed Python... got it!" So I think it is using the installed Python. Could it be that I have to install the same python version Blender was compiled with? From tjreedy at udel.edu Tue Jul 1 18:08:16 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 01 Jul 2008 18:08:16 -0400 Subject: Implementing an 8 bit fixed point register In-Reply-To: References: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> Message-ID: Grant Edwards wrote: > On 2008-07-01, Terry Reedy wrote: >> >> nickooooola wrote: >>> Hello to all >>> I'm about to write a simulator for a microcontroller in python >>> (why python? because I love it!!!) >>> >>> but I have a problem. >>> >>> The registry of this processor are all 8 bit long (and 10 bit for some >>> other strange register) >>> and I need to simulate the fixed point behaviour of the register, >>> and to access the single bit. >> In Python3, I would use a (mutable) bytearray. >> >> IDLE 3.0b1 >>>>> reg1 = bytearray((0,)*8) # or *10 for 10 bits >>>>> reg1 >> bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00') >>>>> reg1[1]=1 >>>>> reg1[1] >> 1 >>>>> tuple(reg1) >> (0, 1, 0, 0, 0, 0, 0, 0) >> >> A bytearray subclass could enforce that all 'bits' (stored as bytes) are >> 0 or 1, have a customized representation to your taste, and add methods >> like .flipall(). > > It seems like implementing ALU operations on such arrays would > be a lot more work than implementing bit-indexing on a type > derived on a more "integer" like base. I'm pretty fuzzy on how > one sub-classes basic things like integers, so maybe I'm all > wet, and adding __getitem__ and __setitem__ to an integer type > isn't even possible. If one only wants bit operations, then the array approach is easy. If one only wants int arithmetic and all-bits logic, then int approach is easy. OP did not completely specify needs. The problem with the int approach is that ints are immutable. Therefore, if one wants to subclass int to hide the bit masking for the bit operations, one must override *every* operation one might use, including all arithmetic and all-bits logic, even when the int operation gives the correct answer other than the class of the result. class bits(int): ... def __add__(self,other): return bit(self+other) ... If one does not, a,b = bits(1),bits(2) c = a+b #c is now an int, not a bits So there is a tendency to not subclass and instead either leave the extra functionality unmasked in repeated code or to put it in functions instead. setters = (1,2,4,8,16,32,64, ..., 2147483648)# slightly pseudocode unsetters = (~1,~2,~4,...~2147483648) # ditto def bitset(n, bit): return n | setters[bit] def bitunset(n,bit): return n & unsetters[bit] thus not getting the nice reg[n] functionality, nor an easy display of individual bits without callings *another* function. One the other hand, with mutable arrays, setting bits is a mutation and so no override of __setitem__ is required unless one wants to be fancy and enforce setting to 0 or 1. It is a trade-off. Terry Jan Reedy From michele.simionato at gmail.com Sun Jul 27 00:58:29 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 26 Jul 2008 21:58:29 -0700 (PDT) Subject: How to close all python-opened file identifiers? References: Message-ID: <4b2ee8eb-e9e1-4338-b099-5355854d063f@i76g2000hsf.googlegroups.com> On Jul 26, 2:19?am, BAnderton wrote: ?Although I > can't find unmatched "open" and "fid.close()" statements, I'd like to > implement a check for open file identifiers before launching the > editor. So you need a debug tool to track down the opened files. How about that: # assume Python 2.5 from __future__ import with_statement import __builtin__ orig_file = __builtin__.file # you could do the same for open class ChattyFile(file): opened = [] def __init__(self, *args, **kw): super(ChattyFile, self).__init__(*args, **kw) self.opened.append(self) print 'opened %s' % self def close(self): super(ChattyFile, self).close() self.opened.remove(self) print 'closed %s' % self class ContextManager(object): def __init__(self): self.opened = ChattyFile.opened def __enter__(self): __builtin__.file = ChattyFile def __exit__(self, *exc_info): __builtin__.file = orig_file chattyfile = ContextManager() with chattyfile: f = file('x.txt', 'w') f.write('hello') f.close() file('x.txt') print chattyfile.opened gives: $ python chattyfile.py opened closed opened [] Warning: I did not test this more than you see. Notice also that overriding the builtins is fine for debugging purposes (it is perhaps the only good use case for this feature, together with testing, for mock objects). You are expected to use it as follows: from chattyfile import chattyfile from mylibrary import main with chattyfile: main() and all calls to 'file' will be tracked down. Since 'open' is basically an alias for 'file' (they were exactly the same in Python 2.4) you could also track 'open' in the same way. If you are using Python 2.4 you can use the same trick, but in a less clean way, using a try ..finally instead of the context manager. Michele Simionato From s0suk3 at gmail.com Wed Jul 16 06:55:10 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Wed, 16 Jul 2008 03:55:10 -0700 (PDT) Subject: Modify a string's value References: <8c7245ed-2341-4283-988c-8a8adf3e58fd@56g2000hsm.googlegroups.com> <87k5fm4ecl.fsf@benfinney.id.au> Message-ID: On Jul 15, 11:55 pm, Ben Finney wrote: > s0s... at gmail.com writes: > > I just came across this unusual situation where I'd like to modify a > > string passed to a function > > Again: Why? The normal way to do this is to create a new string and > return that. > Yes, usually, but that won't work in this case (look at my previous post around the 'cin >> line' line). This is what I came up with: class StreamLineBuffer: def __init__(self): self.buf = "" def __rrshift__(self, stream): self.buf = stream.readline() def __str__(self): return self.buf cin = sys.stdin buf = StreamLineBuffer() cin >> buf line = str(buf) Works like a charm :) From basti.wiesner at gmx.net Thu Jul 24 12:49:16 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Thu, 24 Jul 2008 18:49:16 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> Message-ID: Torsten Bronger : > Hall?chen! > > Bruno Desthuilliers writes: > >> Torsten Bronger a ?crit : >> >>> Bruno Desthuilliers writes: >>> >>>> [...] >>>> >>>> How would you handle this case with an implicit 'self' : >>>> >>>> class Foo(object): >>>> pass >>>> >>>> def bar(self): >>>> print self >>>> >>>> Foo.bar = bar >>> >>> Just like this. However, the compiler could add "self" to >>> non-decorated methods which are defined within "class". >> >> What's defined within classes are plain functions. It's actually >> the lookup mechanism that wraps them into methods (and manage to >> insert the current instance as first argument). > > And why does this make the implicit insertion of "self" difficult? > I could easily write a preprocessor which does it after all. Who said, that it would be "difficult"? He just corrected your statement about definitions inside a class, and did not make any assumption about making "self" implicit. I'd assume, that making self implicit wouldn't be that difficult to assume. But does the fact, that it could easily be done, alone mean, that it _should_ be done? The explicit "self" was a design decision, that can't really be judged by technical arguments from implementation side. Its a discussion about design from a programmers point of view ... -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From wilson.t.thompson at gmail.com Sat Jul 5 02:24:08 2008 From: wilson.t.thompson at gmail.com (wilson) Date: Fri, 4 Jul 2008 23:24:08 -0700 (PDT) Subject: how to get selected filename in FileSelectBox Message-ID: hi i am using tix FileSelectBox in my application .I want to get the selected filename as a string i do this as follows fselectbox=FileSelectBox(someframe) fselectbox.__setitem__("dir",join(fselectbox.cget("dir"),"..")) fselectbox.pack(side=LEFT) ... selectedfile=fselectbox.selection.cget("value") fselectbox.selection.selection_clear() print "file=",selectedfile i did these by going thru the docs in tix ,actually i couldn't find an example so i am not sure if this is the right way..it does print the filename but i want to know if this is the way..Can someone comment? Wilson From samwyse at gmail.com Tue Jul 8 08:26:01 2008 From: samwyse at gmail.com (samwyse) Date: Tue, 8 Jul 2008 05:26:01 -0700 (PDT) Subject: Logging to zero or more destinations Message-ID: In the Python 2.5 Library Reference, section 14.5.3 (Logging to multiple destinations), an example is given of logging to both a file and the console. This is done by using logging.basicConfig() to configure a log file, and then calling logging.getLogger('').addHandler(console) to add the console. However, in section 14.5.4 (Sending and receiving logging events across a network), a call is made to rootLogger.addHandler(socketHandler), and later it is stated that "On the client side, nothing is printed on the console". Finally, back in section 14.5.2 (Basic example), it's stated that "by default, the root logger is configured to only handle messages with a severity of WARNING or above. The message format is also a configuration default, as is the output destination of the messages - sys.stderr." The only way that I can see for all three statements to be consistent is that the root logger starts with an empty list of handlers, and doesn't instantiate a default handler until either logging.basicConfig() is called, or the first time that a message is logged. This would also seem to imply that there's no way to use an empty handler list (say, if you want to suppress all logging), because the root handler will instantiate a handler for you. Is this correct? P.S. I tried researching this further by myself, but the logging module doesn't come with source (apparently it's written in C?) and I don't have the time to find and download the source to my laptop. Thanks! From code at pizzashack.org Fri Jul 18 17:41:59 2008 From: code at pizzashack.org (Derek Martin) Date: Fri, 18 Jul 2008 17:41:59 -0400 Subject: Multiple variable control in for loops. Doable in Python? In-Reply-To: <20080718212832.GA1994@dragontoe.org> References: <28efa6970807181221o67c90575w690464f1442dc47d@mail.gmail.com> <20080718212832.GA1994@dragontoe.org> Message-ID: <20080718214159.GA3043@dragontoe.org> On Fri, Jul 18, 2008 at 05:28:32PM -0400, Derek Martin wrote: > def control(i, j): > print i,j > if not (i < 5 or j < 10): Rather, if not (i < 5 and j < 10): > return > else: > control(some_increment_function(i), other_increment_function(j)) -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From fredrik at pythonware.com Wed Jul 23 03:19:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 09:19:58 +0200 Subject: How to replace the values with keys ? In-Reply-To: <92df0f7c0807222130n382edf5di8c7124690f3dffa7@mail.gmail.com> References: <92df0f7c0807222130n382edf5di8c7124690f3dffa7@mail.gmail.com> Message-ID: "Graps Graps" wrote: > Text2 is a python dictionary containing data as > > {0: 'a', 1: 'b', 2: 'c'...} > > now I want the data in text1 to be replaced with the keys, say like > > 0 1 > 0 2 > 0 3 > 0 6 > 1 2... so on.. someone asked a very similar question not long ago, so maybe you're really supposed to figure this out yourself. I'm sure your teacher won't kill you if you ask for a hint. (if you asked me for a hint, I'd tell you to look for questions about dictionaries in the mailing list archives). From wuwei23 at gmail.com Wed Jul 23 09:16:50 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 23 Jul 2008 06:16:50 -0700 (PDT) Subject: os.walk question References: Message-ID: On Jul 23, 10:11?pm, Larry Bates wrote: > import glob > random.choice([f for f in glob.glob(root, "*")]) glob.glob only accepts one argument though, did you mean root + "*"? It also returns folders as well as files, though, and the list comprehension is not necessary given it returns a list itself. From theller at python.net Wed Jul 23 10:39:29 2008 From: theller at python.net (Thomas Heller) Date: Wed, 23 Jul 2008 16:39:29 +0200 Subject: python.exe crash and ctypes use In-Reply-To: References: Message-ID: <6eou4dF82ehaU1@mid.individual.net> waldek schrieb: > Hi, > > I have module A.py and B.dll which exports C functions by cdecl_ > > In A.py I pass callback (py callable) to dll. Next, thread inside dll > simply calls my callback (in a loop). After few secs I got crash of > python.exe. > > How to debug it? > > I'm using winxp and py 2.5.2 > > > =========================== > def mycallback(data, size) > return 0 > > CBFUNC = CFUNCTYPE(c_int,POINTER(c_int), c_int) > dll = cdll.mydll > > if dll.RegisterCallback(CBFUNC(mycallback)) != 0: > print "Error." > =========================== You need the callback function instance - what the CBFUNC(mycallback) call returns - alive as long as some C code is calling it. If you don't sooner or later the Python garbage collector will free it since it seems to be no longer used. ctypes does NOT keep the callback function alive itself. Thomas From ddasilva at umd.edu Wed Jul 30 01:08:26 2008 From: ddasilva at umd.edu (Daniel da Silva) Date: Wed, 30 Jul 2008 01:08:26 -0400 Subject: iterating "by twos" In-Reply-To: References: Message-ID: <8d9ec3dd0807292208p3ff225bs49a9ca5c748a0360@mail.gmail.com> The following method is similar to the others provided, but yields an index value as well (similar to the enumerate(iterable) function). This is useful in some (but not all) situations. If the iterable object's iterator returns an even number of items then you're fine; otherwise it will throw away the last item because it doesn't have a full pair to return. ------------------------- import itertools def enumeratePairs(x): it = iter(x) for i in itertools.count(): p = it.next() q = it.next() yield i, (p,q) raise StopIteration -------------------------- >>> for v in enumeratePairs("hello i am daniel"): ... print v ... (0, ('h', 'e')) (1, ('l', 'l')) (2, ('o', ' ')) (3, ('i', ' ')) (4, ('a', 'm')) (5, (' ', 'd')) (6, ('a', 'n')) (7, ('i', 'e')) ------------------------------- On Tue, Jul 29, 2008 at 1:36 PM, kj wrote: > > > > Is there a special pythonic idiom for iterating over a list (or > tuple) two elements at a time? > > I mean, other than > > for i in range(0, len(a), 2): > frobnicate(a[i], a[i+1]) > > ? > > I think I once saw something like > > for (x, y) in forgotten_expression_using(a): > frobnicate(x, y) > > Or maybe I just dreamt it! :) > > Thanks! > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. > -- > http://mail.python.org/mailman/listinfo/python-list > From misceverything at gmail.com Wed Jul 23 19:30:17 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Wed, 23 Jul 2008 16:30:17 -0700 (PDT) Subject: Run as Service References: <09c0bfa9-c86b-4153-ba91-cb9bf2e85e2a@k30g2000hse.googlegroups.com> Message-ID: <7c79c170-a92b-42d5-9362-5c3370118b59@m73g2000hsh.googlegroups.com> Jay/Larry - Thanks for the suggestions! From gherron at islandtraining.com Wed Jul 9 11:43:58 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 09 Jul 2008 08:43:58 -0700 Subject: Opening Unicode files In-Reply-To: <636110.21350.qm@web27405.mail.ukl.yahoo.com> References: <636110.21350.qm@web27405.mail.ukl.yahoo.com> Message-ID: <4874DCBE.6000902@islandtraining.com> Noorhan Abbas wrote: > Hello, > I wonder if you don't mind helping me out in this problem. I have been > developing a tool in python that opens some unicode files, reading > them and processing the data. It is working fine. When I started to > write a cgi module that does the same thing for google > appengine(actually it is using the same files that I used befoer), I > get an error: > > f = codecs.open (FileName , 'rU', 'utf-8') > > It says that the above functions takes 3 arguments but 4 were given. Truly? I ran that line and found it works perfectly. What version of python are you using (I used 2.5.1). What OS? (That should not matter, however you should tell us anyway.) Are you sure your codecs is the Python module imported normally. (You may have to show us all your code.) With no code and a careful look at your error message, here's my guess: That error message is what you get when you call an instance's method with the wrong number of arguments. (And in that case the extra argument it's referring to is the instance itself begin passed in as the first (self) parameter.) I believe your codecs value is no longer the imported module, but rather some instance object you've assigned into it: codecs = ...something overwriting the module object ... Gary Herron > I wonder if I need to do something before using the codecs library > from within the cgi module?! > > Thank you very much for your help, > Nora > > ------------------------------------------------------------------------ > Not happy with your email address? > Get the one you really want > - millions of new email addresses available now at Yahoo! > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From Perl_Wizard at manx.net Sun Jul 20 13:39:52 2008 From: Perl_Wizard at manx.net (Perl_Wizard at manx.net) Date: Sun, 20 Jul 2008 18:39:52 +0100 (BST) Subject: question Message-ID: <200807201739.CQT04024@manxnetsf02.manx.net> Nobody any sensible answers. Too complicated I suppose! From Nikolaus at rath.org Mon Jul 28 06:23:21 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 28 Jul 2008 12:23:21 +0200 Subject: Protecting instance variables References: <6eb9iaF6779oU1@mid.uni-berlin.de> Message-ID: <877ib6s3xi.fsf@nokile.rath.org> Hi, Sorry for replying so late. Your MUA apparently messes up the References:, so I saw you reply only now and by coincidence. "Diez B. Roggisch" writes: > Nikolaus Rath schrieb: >> Hello, >> >> I am really surprised that I am asking this question on the mailing >> list, but I really couldn't find it on python.org/doc. >> >> Why is there no proper way to protect an instance variable from access >> in derived classes? >> >> I can perfectly understand the philosophy behind not protecting them >> from access in external code ("protection by convention"), but isn't >> it a major design flaw that when designing a derived class I first >> have to study the base classes source code? Otherwise I may always >> accidentally overwrite an instance variable used by the base class... > > Here we go again... > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/188467d724b48b32/ > > To directly answer your question: that's what the __ (double > underscore) name mangling is for. I understand that it is desirable not to completely hide instance variables. But it seems silly to me that I should generally prefix almost all my instance variables with two underscores. I am not so much concerned about data hiding, but about not accidentally overwriting a variable of the class I'm inheriting from. And, unless I misunderstood something, this is only possible if I'm prefixing them with __. How is this problem solved in practice? I probably don't have a representative sample, but in the libraries that I have been using so far, there were a lot of undocumented (in the sense of: not being part of the public API) instance variables not prefixed with __. I have therefore started to first grep the source of all base classes whenever I introduce a new variable in my derived class. Is that really the way it's supposed to be? What if one of the base classes introduces a new variable at a later point? Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From martin at v.loewis.de Mon Jul 7 00:53:47 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 07 Jul 2008 06:53:47 +0200 Subject: how are strings immutable in python? In-Reply-To: <337db7c6-0fc9-465e-b780-322c3a5cf8da@y38g2000hsy.googlegroups.com> References: <337db7c6-0fc9-465e-b780-322c3a5cf8da@y38g2000hsy.googlegroups.com> Message-ID: <4871a15c$0$23475$9b622d9e@news.freenet.de> > so why would you ever want mutability? > > > seems very counterintuitive and unreliable. For lists, mutability is fairly natural. Suppose you have a function f that copies some items from one list to another. You write it as def f(src, dst): for x in src: if condition(x): dst.append(x) If dst was immutable, an .append method could not be defined (since it modifies the list itself), so you would have to write dst = dst + [x] However, that would only modify the local variable dst in the function f - the parameter of the caller of f would not get modified. The same holds for many other operations on lists. You can pass very complex data structures around (lists of lists of dictionaries etc), and have functions modify the lists, rather than creating new ones. For example, to change a two-dimensional matrix (which is a list of lists), you can write M[10][11] = 3.14 whereas with immutable lists, you would have to write M_10_new = M[10][:11] + [3.14] + [M10][12:] M = M[:10] + [M_10_new] + M[11:] HTH, Martin From mattheww at chiark.greenend.org.uk Thu Jul 31 12:51:31 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 31 Jul 2008 17:51:31 +0100 (BST) Subject: Function References References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> Message-ID: >> Ctypes is a since python2.5 built-in module that allows to declare >> interfaces to C-libraries in pure python. You declare datatypes and >> function prototypes, load a DLL/SO and then happily work with it. No C, no >> compiler, no refcounts, no nothing. >> >> And you can pass python-functions as callbacks. squishywaffle at gmail.com wrote: > The first sentence (and some really crummy licensing restrictions > imposed by the library distributor) alone here excludes this as a > valid option for this particular case, I definitely need Python 2.4 > support. Perhaps all is not lost: ctypes works from Python 2.3 up. That first sentence is saying that since Python 2.5 it has been included in the standard Python distribution, but you can still download it separately. -M- From python at rcn.com Tue Jul 15 02:44:56 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 14 Jul 2008 23:44:56 -0700 (PDT) Subject: new itertools functions in Python 2.6 References: <4dd80ff2-5fda-405a-a637-08c985ff8add@e53g2000hsa.googlegroups.com> Message-ID: <498a38d4-10b5-4824-8401-5ebb510fcfa8@y38g2000hsy.googlegroups.com> On Jul 14, 1:26?pm, Mensanator wrote: > ## ?Combinations with replacement > ## ?----------------------------- > ## ?aaa aab aac aad aae abb abc abd abe acc acd ace > ## ?add ade aee bbb bbc bbd bbe bcc bcd bce bdd bde > ## ?bee ccc ccd cce cdd cde cee ddd dde dee eee > ## > ## ?actual words: 35 ? ?(m+n-1)!/(n!(m-1)!) words: 35 > > Although it works, it's somewhat slow as we have to iterate > over the entire Cartesian Product and the filter list(x)==sorted(x) > has got to be expensive (it's slower than the nested loop algorithm). > > Is there a better way to get Combinations With Replacement > using itertools? There may a technique to start with the combinations without replacement and then grow the result by repeating elements: result = set(combinations('abcde', 3)) # transform 'ab ac ad ae bc bd be cd ce de' into 'aab abb aac acc ...' for c in combinations('abcde', 2): # transform 'ab' --> 'aab abb' for i in range(2): result.add(c[:i] + c[i]*1 + c[i:]) for c in combinations('abcde', 1): for i in range(1): # 'a' --> 'aaa' result.add(c[:i] + c[i]*2 + c[i:]) If you generalize the above, it may solve the problem using itertools as a starting point. Alternatively, it's not too hard to transform the pure python version given in the docs to one that supports combinations with replacement: def combinations_with_replacement(iterable, r): pool = tuple(iterable) n = len(pool) indices = [0] * r yield tuple(pool[i] for i in indices) while 1: for i in reversed(range(r)): if indices[i] != n - 1: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] yield tuple(pool[i] for i in indices) Raymond From kirk at strauser.com Mon Jul 28 12:14:19 2008 From: kirk at strauser.com (Kirk Strauser) Date: Mon, 28 Jul 2008 11:14:19 -0500 Subject: Suggestions for creating a PDF table Message-ID: Short question: Is there a good library for generating HTML-style tables with the equivalent of colspans, automatically sized columns, etc. that can render directly to PDF? Longer question: I'm re-doing a big chunk of locally-written code. I have a report-generating function that takes a list of lists of lists as input and returns either a PDF, an HTML table, or an Excel spreadsheet as requested. For example, input might look like: makereport('html', headers=['Invoice number', 'Customer', 'Price'], data=[ [['123', 'John Doe', '$50.00'], ['Ordered on 2008-01-01 via the website']], [['124', 'Peter Bilt', '$25.99'], ['Mail via African swallow']] ]) This would result in HTML like:
Invoice number Customer Price
123 John Doe $50.00
Ordered on 2008-01-01 via the website
124 Peter Bilt $25.99
Mail via African swallow
Note particularly how the explanatory notes for each invoice are similar in appearance to the "primary" report lines they're associated with. Now, I have a similar transformation to PDF via pdflatex. This works fairly well but requires a bunch of temp files and subprocesses, and I've never been 100% happy with the LaTeX output (you have to calculate your own column widths, for instance). Since I plan to re-write this anyway, I'd like to find a more widely used library if one was available. ReportLab seemed *almost* perfect, except that it doesn't support colspans. As I hope I demonstrated in the example, most of our reports depend on that ability. So, again, any thoughts on a PDF generator that can generate tables with the same kind of flexibility as HTML? -- Kirk Strauser From tjreedy at udel.edu Wed Jul 30 11:14:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 30 Jul 2008 11:14:28 -0400 Subject: Is it allowed to use function results as default arguments ? In-Reply-To: References: Message-ID: fred.haab wrote: > Well, others have answered the question, but I thought I'd throw in > that it would be more pythonic to do something like: > > def Get_Relative_Path(target, base = None): > if base is None: > base = os.curdir > ... Since os.curdir is a constant, this is nonesensical. One only needs the dummy default when one wants an expression re-evaluated with each call. From clay at lakeserv.net Wed Jul 23 16:07:08 2008 From: clay at lakeserv.net (Clay Hobbs) Date: Wed, 23 Jul 2008 16:07:08 -0400 Subject: PyOpenGL Tutorial? Message-ID: <1216843629.18962.16.camel@generator> I need a tutorial for PyOpenGL (specifically, to be used with wxPython). I searched with Google and didn't find one. Does anybody know where one is? -- Ratfink From leonhard.vogt at gmx.ch Wed Jul 30 16:58:20 2008 From: leonhard.vogt at gmx.ch (Leonhard Vogt) Date: Wed, 30 Jul 2008 22:58:20 +0200 Subject: How can I check nbr of cores of computer? In-Reply-To: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> Message-ID: defn noob schrieb: > How can I check how many cores my computer has? > Is it possible to do this in a Python-app? processing (http://pyprocessing.berlios.de/) has an utility function processing.cpuCount(). Leo From fredrik at pythonware.com Thu Jul 24 03:53:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 09:53:31 +0200 Subject: parameterized classes In-Reply-To: References: Message-ID: John Tantalo wrote: > I really wish I could create a class whose instances were classes that > subclassed BaseRequestHandler. Is this possible, or is there a better > way than my approach here? Or am I crazy? no you so much as your code. unfortunately, it fails the "decipher in allocated time slot" test, though, so I hope someone else will have time to untangle it for you. > And I may be dense, so if there is an easier way to stream sockets as > line streams, please let me know. I honestly don't think it should be > this difficult to implement a socket handler this simple. there's a StreamRequestHandler class in SocketServer that buffered streams via the rfile and wfile attributes. From deets at nospam.web.de Tue Jul 22 09:32:10 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 15:32:10 +0200 Subject: tkinter for my python program !! References: Message-ID: <6em5snF7r22oU3@mid.uni-berlin.de> karthikbalaguru wrote: > Hi, > > One of my python program needs tkinter to be installed to run > successfully. > I am using Redhat 9.0 and hence tried installing by copying the > tkinter-2.2.2-36.i386.rpm > alone from the CD 3 to my pc. But, it is not getting installed and is > failing by throwing > the below errors. Should i need to configure / install any specific > files for resolving this issue ? > > [root at localhost karthik]# rpm -ivh tkinter-2.2.2-26.i386.rpm > warning: tkinter-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, > key ID db42a > 60e > error: Failed dependencies: > libtcl8.3.so is needed by tkinter-2.2.2-26.i386 > libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 > libtk8.3.so is needed by tkinter-2.2.2-26.i386 > > Any ideas ? Yes: you should consider reading error-messages. What does error: Failed dependencies: libtcl8.3.so is needed by tkinter-2.2.2-26.i386 libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 libtk8.3.so is needed by tkinter-2.2.2-26.i386 look like for you? Small hint: if you install something that depends on something else, you need to .... the missing dependency first. Fill in the dots... Diez From elessar at nienna.org Fri Jul 25 11:22:06 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Fri, 25 Jul 2008 09:22:06 -0600 Subject: Execution speed question In-Reply-To: <4889e5bc$1@news2-rz-ap.ethz.ch> References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> <4889e5bc$1@news2-rz-ap.ethz.ch> Message-ID: <4889EF9E.5050602@nienna.org> Suresh Pillai wrote: > That's a good comparison for the general question I posed. Thanks. > Although I do believe lists are less than ideal here and a different data > structure should be used. > > To be more specific to my case: > As mentioned in my original post, I also have the specific condition that > one does not know which nodes to turn ON until after all the > probabilities are calculated (lets say we take the top m for example). > In this case, the second and third will perform worse as the second one > will require a remove from the list after the fact and the third will > require another loop through the nodes to build the new list. > -- > http://mail.python.org/mailman/listinfo/python-list > It seems like the probability calculation applies to all three equally, and can therefore be ignored for the simulations. You said that your algorithm must be a two-stage process: (A) calculate the probabilities then (B) turn on some nodes. Iain's simulations assume (A) is already done. He just addressed the performance of (B). Part (A) is invariant for all his simulations, because your requirement forces it to be. As for different data structures, it largely depends on how you need to access the data. If you don't need to index the data, just loop through it, you might try a linked list. The performance hit in (2) is coming from the list del; using a linked list would make the removal constant rather than O(n), and may even execute faster than (3) as well. -Matt From wuwei23 at gmail.com Sun Jul 27 08:24:36 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 27 Jul 2008 05:24:36 -0700 (PDT) Subject: x*x if x>10 References: <59b5d431-8218-4a07-a9d7-5357f1c474f8@f36g2000hsa.googlegroups.com> Message-ID: On Jul 27, 10:13?pm, ssecorp wrote: > I have seen somewhere that you can write something like: > > x*x if x>10 > > but exactly that doesn't work and I can't get any variation to work. It's called a ternary operator. The format is:
american, /browse/blue blue , /browse/brick brick , brie, cheddar, cheshire, /browse/churn churn , /browse/cottage cottage , /browse/cream cream , dunlop, and it goes on . I know I can do like a.contents, but it only gives me the first one, in this case being "blue". I want the contents of each of those and the regular contents of the . Can anyone help? -- View this message in context: http://www.nabble.com/Need-help-getting-BeautifulSoup-contents-tp18501881p18501881.html Sent from the Python - python-list mailing list archive at Nabble.com. From bierbaum at vierfalt.com Thu Jul 10 17:12:36 2008 From: bierbaum at vierfalt.com (Simon Bierbaum) Date: Thu, 10 Jul 2008 23:12:36 +0200 Subject: handling unexpected exceptions in pdb In-Reply-To: References: Message-ID: Am 10.07.2008 um 20:52 schrieb R. Bernstein: > Simon Bierbaum writes: > >> Hi all, >> >> I'm in an interactive session in pdb, debugging my code using >> pdb.runcall. Somewhere, an exception is raised and lands uncaught on >> stdout. Is there any way of picking up this exception and at least >> read the full message, or even accessing its stack trace to determine >> where exactly within the one line I just executed it was raised? This >> is where I'm stuck: >> >>> /usr/local/apache2/bin/Model/Database.py(287)disconnect() >> (Pdb) n >> FlushError: FlushErr...perly.",) >>> /usr/local/apache2/bin/Model/Database.py(287)disconnect() >> (Pdb) import sys >> (Pdb) sys.last_traceback >> *** AttributeError: 'module' object has no attribute 'last_traceback' >> >> Thanks, Simon > > I think basically you want runcall to be wrapped in a try block. So > in pdb.py > instead of: > > def runcall(*args, **kwds): > return Pdb().runcall(*args, **kwds) > > > Change with: > > def runcall(*args, **kwds): > p=Pdb() > try: > return p.runcall(*args, **kwds) > except: > traceback.print_exc() > print "Uncaught exception. Entering post mortem debugging" > t = sys.exc_info()[2] > p.interaction(t.tb_frame,t) > print "Post mortem debugger finished." > return None > > Code like this appears near the bottom of the pdb.py file. If that > works, you may want to file a bug Python report to change pdb. Also > note that one may want to do the same thing on run() and runeval() > > But also if this does what you want, please file a feature request > to pydb: > http://sourceforge.net/tracker/?func=add&group_id=61395&atid=497162 > > and I'll probably make it happen in the next release. > > This is the first time I've heard of anyone using runcall. My app is called from mod_python with the PythonEnablePdb option set to On, which makes mod_python call my handler function not directly, but wrapped into a pdb.runcall(). I figure I might not be the first one to use runcall under these circumstances ;-) I'll definitely give your hack a try, thank you for your help! Cheers, Simon From paul at boddie.org.uk Wed Jul 30 13:54:17 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 30 Jul 2008 10:54:17 -0700 (PDT) Subject: Is it possible to consume UTF8 XML documents using xml.dom.pulldom? References: <2a703a46-75bc-4228-95d1-05a4e6030b40@f63g2000hsf.googlegroups.com> <26c2fe8e-d464-44f0-8e57-3b8e82248691@x35g2000hsb.googlegroups.com> Message-ID: On 30 Jul, 19:23, Peter Otten <__pete... at web.de> wrote: > > I'm on Kubuntu 7.10 and see the same error as Simon. The problem is in the > minidom.CharacterData class which has the following method > > ? ? def __repr__(self): > ? ? ? ? data = self.data > ? ? ? ? if len(data) > 10: > ? ? ? ? ? ? dotdotdot = "..." > ? ? ? ? else: > ? ? ? ? ? ? dotdotdot = "" > ? ? ? ? return "" % ( > ? ? ? ? ? ? self.__class__.__name__, data[0:10], dotdotdot) > > The data attribute is a unicode instance... Who wants to be first to submit a patch? ;-) Paul From Scott.Daniels at Acm.Org Wed Jul 23 00:06:47 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 22 Jul 2008 21:06:47 -0700 Subject: fromfile error on windows, not mac In-Reply-To: <185cc290-18a5-4572-9fda-fa0bb785c831@z72g2000hsb.googlegroups.com> References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> <9650a33b-40b5-46a7-a05e-5b059117891f@b1g2000hsg.googlegroups.com> <185cc290-18a5-4572-9fda-fa0bb785c831@z72g2000hsb.googlegroups.com> Message-ID: <56Sdncz234dVNhvVnZ2dnUVZ_oLinZ2d@pdx.net> jadamwil wrote: > On Jul 22, 2:05 am, Uwe Schmitt > wrote: >> jadamwil schrieb: >> >> >> >>> Hello, >>> I am using the numpy fromfile function to read binary data from a file >>> on disk. The problem is that the program runs fine on a Mac, but gives >>> an error or warning on windows when trying to read the data. I use it >>> like this: >>> Signal = zeros((N, 16), dtype=float32) >>> for sample in range(0, N): >>> # this function gets the next position in the file to seek to >>> s = getFilePos(sample) >>> # go to the correct location in the file; this IS checked to make >>> sure it is within the file >>> mFile.seek(s) >>> # read the 16 float32 values from the file >>> D = fromfile(mFile, dtype=numpy.float32, 16) >>> # save D in Signal >>> Signal[sample, :] = D >>> This will fail when sample is ~4. If I change the range to (5,N), >>> skipping the "bad" file location, it will run fine for a few samples, >>> and then give another error. The message it gives is: >>> "16 items requested but only 7 read" >>> So D is a 7x1 vector, and the program dies when it tries to assign D >>> to the slice of Signal ("ValueError: shape mismatch: objects cannot be >>> broadcast to a single shape"). >>> On windows, the Python version is 2.5.2, and the most recent numpy and >>> scipy are being used as well. I tried using Enthought, but it gave >>> this error as well, in addition to a c runtime error whenever I >>> imported scipy (which is another post topic...). >>> Any ideas on what might be causing this? Is there a way to debug the >>> fromfile function? And, remember, this works perfectly on a Mac. Would >>> compiling everything (python, scipy, numpy) potentially solve this? >> Did you open the file in binary mode ? >> >> Greetings, Uwe > > Yes I did. Would that make a difference between a mac and windows? > Thanks In a word, yes. the values for bytes that have issues are 10 and 13. --Scott David Daniels Scott.Daniels at Acm.Org From boblatest at googlemail.com Thu Jul 24 06:10:49 2008 From: boblatest at googlemail.com (boblatest at googlemail.com) Date: Thu, 24 Jul 2008 03:10:49 -0700 (PDT) Subject: Confounded by Python objects References: <33c9309a-9679-41f6-a777-2874aad1903a@z66g2000hsc.googlegroups.com> Message-ID: On Jul 24, 11:59 am, Fredrik Lundh wrote: > tip: if you're not 100% sure why you would want to put an attribute > on the class level, don't do it. The reason I did it was sort of C++ish (that's where I come from): I somehow wanted a list of attributes on the class level. More for readibility than anything elase, really. > hope this helps! Yup, did the trick. Thanks! robert From miki.tebeka at gmail.com Mon Jul 14 14:14:46 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 14 Jul 2008 11:14:46 -0700 (PDT) Subject: trying to use sax for a very basic first xml parser References: <6ff86003-a3e8-4c5b-9276-1cd3c7f0ffa7@56g2000hsm.googlegroups.com> Message-ID: <3a7148a9-b95d-4e95-b3b7-492e0d016ab8@f36g2000hsa.googlegroups.com> Hello, > but when I copy the script into blender and run it I get: > > [code]Compiled with Python version 2.5. > Checking for installed Python... got it! > Traceback (most recent call last): > ? File "Text", line 27, in > ? File "H:\Python25\lib\xml\sax\__init__.py", line 93, in make_parser > ? ? raise SAXReaderNotAvailable("No parsers found", None) > xml.sax._exceptions.SAXReaderNotAvailable: No parsers found[/code] Python is using an external library for SAX (expat IIRC). I *guess* the Python that comes with Blender don't have this library. > Its probably a stupid question but thanks anyway! He who asks is a fool for five minutes, but he who does not ask remains a fool forever. - Chinese Proverb HTH, -- Miki http://pythonwise.blogspot.com From koen at asemic.org Tue Jul 1 07:10:05 2008 From: koen at asemic.org (Koen Vossen) Date: 01 Jul 2008 11:10:05 GMT Subject: Disabling the magic "last expression" _ variable Message-ID: <486a108d$0$14358$e4fe514c@news.xs4all.nl> A project I'm currently working on uses Turbogears as a framework. I'd like to interact with it using the tg-admin shell. We also use gettext's _() function for internationalization. Now, this function is overwritten in interactive mode, which causes annoying exceptions. Is it possible to disable this behavior? From aquil.abdullah at gmail.com Mon Jul 14 17:01:04 2008 From: aquil.abdullah at gmail.com (aha) Date: Mon, 14 Jul 2008 14:01:04 -0700 (PDT) Subject: Using Python To Launch Python Message-ID: Hello All, I have a situation where I can count on a Python installation being available on a system, but I can't count on it being a version of Python needed by my application. Since my application has it's own version of Python installed with it how should I use the system Python to launch the version of Python that launches my Application. Yes, this is a convoluted process, but not all Pythons are built the same :) Right now I am leaning towards using exec to start a new process, but I thought I would check to see if anyone else has had the need to perform a task similar to this one. AHA From __peter__ at web.de Fri Jul 11 04:08:58 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jul 2008 10:08:58 +0200 Subject: problem with exec and locals() References: <95f07476-e3c8-45e4-82b3-0e48c9188f8e@79g2000hsk.googlegroups.com> <2fc55416-76c7-48c8-8f49-64c10c5daeda@w7g2000hsa.googlegroups.com> Message-ID: Uwe Schmitt wrote: >> Apparently, exec in locals() knows nothing about slots (because locals() >> is the only dictionary in the universe where slots would be involved ? -- >> perhaps not, but close). >> >> Mel. > > Thanks for your answer. I wonder if this is a bug, or did I miss > something in the docs ??? Hm, the documentation has an explicit warning: http://docs.python.org/lib/built-in-funcs.html#l2h-47 """ locals( ) Update and return a dictionary representing the current local symbol table. Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. """ By the way, the local namespace is affected if you don't provide it explicitly: >>> def f(): ... exec "a=42" ... print a ... a = "whatever" ... >>> f() 42 Peter From ppearson at nowhere.invalid Sat Jul 5 00:08:59 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 5 Jul 2008 04:08:59 GMT Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: <6d8aeqF1cgfsU1@mid.individual.net> On Fri, 4 Jul 2008 20:34:03 -0700 (PDT), Carl Banks wrote: > On Jul 4, 4:43 pm, "Filipe Fernandes" wrote: >> On Fri, Jul 4, 2008 at 8:36 AM, Peter Otten <__pete... at web.de> wrote: >> > Henning_Thornblad wrote: >> >> >> This script takes about 5 min to run on my computer: >> >> #!/usr/bin/env python >> >> import re >> >> >> row="" >> >> for a in range(156000): >> >> row+="a" >> >> print re.search('[^ "=]*/',row) [snip] >> >> Is this a bug in python? > > This behavior is showing that you're getting n-squared performance; > the regexp seems to be checking 156000*(156000-1)/2 substrings for a > match. I did this: $ python -m timeit -s "import re" "re.search( '[^13]*x', 900*'a' )" 100 loops, best of 3: 16.7 msec per loop for values of 900 ranging from 300 to 1000, and the time taken per loop was indeed quadratic. -- To email me, substitute nowhere->spamcop, invalid->net. From paddy3118 at googlemail.com Sat Jul 5 03:31:24 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 5 Jul 2008 00:31:24 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: <8d2a078c-ccb4-4e09-a802-b35886207e50@56g2000hsm.googlegroups.com> On Jul 5, 7:01?am, Peter Otten <__pete... at web.de> wrote: > Paddy wrote: > > It is not a smarter algorithm that is used in grep. Python RE's have > > more capabilities than grep RE's which need a slower, more complex > > algorithm. > > So you're saying the Python algo is alternatively gifted... > > Peter The following isn't the article I read on regexp types and their speed differences but it does give info on regexp engine types: http://books.google.co.uk/books?id=GX3w_18-JegC&pg=PA145&lpg=PA145&dq=%2Bregex+%2Bspeed+%2Bgrep+%2Btcl+&source=web&ots=PHljNqeuJZ&sig=CyBCOZYsyZaJTMfj2Br53if46Bc&hl=en&sa=X&oi=book_result&resnum=3&ct=result#PPA145,M1 - Paddy. From ldo at geek-central.gen.new_zealand Mon Jul 28 00:00:39 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 28 Jul 2008 16:00:39 +1200 Subject: Python program as daemon? References: <8bb6bd1a-cd85-4b7a-8fc9-844f3794bca0@c58g2000hsc.googlegroups.com> <13866da4-01ed-4330-8297-8bdecce1393a@x35g2000hsb.googlegroups.com> Message-ID: In message <13866da4-01ed-4330-8297-8bdecce1393a at x35g2000hsb.googlegroups.com>, sturlamolden wrote: > Basically it forks twice ... What's the advantage of forking twice over forking once and calling setsid? From vinay_sajip at yahoo.co.uk Mon Jul 14 09:25:19 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Mon, 14 Jul 2008 06:25:19 -0700 (PDT) Subject: How to package a logging.config file? References: Message-ID: <0a5713d6-8337-44a3-8347-012814345dd8@79g2000hsk.googlegroups.com> On Jul 14, 1:21 am, Matthew Wilson wrote: > I'm working on a package that uses the standard libraryloggingmodule > along with a .cfg file. > > In my code, I uselogging.config.fileConfig('/home/matt/mypackage/matt.cfg') to load in > theloggingconfig file. > > However, it seems really obvious to me that this won't work when I share > this package with others. > > I can't figure out what path to use when I load my .cfg file. > > Any ideas? > > Matt Is your package a library or an application? If it's a library, you should avoid configuring logging using a config file - this is because logging configuration is process-wide, and if multiple libraries use fileConfig to configure their logging, you may get unexpected results. If it's an application, then Larry's advice is good. Regards, Vinay Sajip From hat at se-162.se.wtb.tue.nl Tue Jul 1 03:34:13 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 01 Jul 2008 09:34:13 +0200 Subject: How make regex that means "contains regex#1 but NOT regex#2" ?? References: <53e41dec-895f-44c4-9686-f7cc022ef4ac@f1g2000prb.googlegroups.com> Message-ID: On 2008-07-01, seberino at spawar.navy.mil wrote: > I'm looking over the docs for the re module and can't find how to > "NOT" an entire regex. (?! R) > How make regex that means "contains regex#1 but NOT regex#2" ? (\1|(?!\2)) should do what you want. Albert From jeffober at gmail.com Tue Jul 22 08:42:32 2008 From: jeffober at gmail.com (Jeff) Date: Tue, 22 Jul 2008 05:42:32 -0700 (PDT) Subject: simple question about dictionaries References: <165f274f-d7cb-4889-b9d5-30394285fd5f@56g2000hsm.googlegroups.com> <8aedc744-f432-4a4a-a6e4-2bb714caf720@x35g2000hsb.googlegroups.com> Message-ID: <051bfa54-fd66-4a01-978d-3a05e4527c38@34g2000hsf.googlegroups.com> On Jul 21, 8:14?am, Fredrik Lundh wrote: > Jeff wrote: > > ? throw KeyError('%s not found' % str(val)) > > "throw"? ?and shouldn't that be a ValueError? ;-) > > Whoops. Been working in too many different languages at the same time :). From gherron at islandtraining.com Sun Jul 13 11:23:28 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 13 Jul 2008 08:23:28 -0700 Subject: Someone enlightened me In-Reply-To: <4879645F.3070504@internetnowasp.net> References: <4879645F.3070504@internetnowasp.net> Message-ID: <487A1DF0.70503@islandtraining.com> Marcus Low wrote: > Opps here is the mail again, incase my formatting is lost, can someone > explain to me why this code behaves differently when "lister" and > "self.lister" is swap remarked. > > > class abc : > # remark this later and unremark "self.lister" > lister = [] > def __init__ (self, val): > #self.lister = [] > self.lister.append(val) > globallist = [] > > def test () : > > global l > for x in range(10) : > o = abc(x) globallist.append(o) o > = "" > for i in globallist : > print i.lister > test() > > -- > http://mail.python.org/mailman/listinfo/python-list It's a Python scoping rule: If a variable is assigned to anywhere within a function, it is assumed to be local *everywhere* within that function. See the faq for more: http://www.python.org/doc/faq/programming/#what-are-the-rules-for-local-and-global-variables-in-python Gary Herron From Donald at dontdoithere.com Sun Jul 13 11:17:39 2008 From: Donald at dontdoithere.com (donald) Date: Sun, 13 Jul 2008 08:17:39 -0700 Subject: spam <1c5402a8-3e1d-4891-9a7d-8f70174649d2@w7g2000hsa.googlegroups.com> <4dfb46e1-0b5b-486c-b4dd-abbd29ef9308@m44g2000hsc.googlegroups.com> In-Reply-To: <487a0d4d$0$90272$14726298@news.sunsite.dk> References: <-NadnSfGJfB5d-rVRVnyvgA@posted.plusnet> <3b6a3bbc-ec13-4b9f-896f-b119ce543587@c58g2000hsc.googlegroups.com> <487a0d4d$0$90272$14726298@news.sunsite.dk> Message-ID: Arne Vajh?j wrote: >> >> Google does not accept spam complaints. Go ahead, try it. That's why >> they've been the #1 Usenet spamming tool for years now. What you're >> seeing is the spam slowly expanding into the software development >> groups. uk.railway is probably a random group added to confuse spam >> filters. Some groups, like rec.photo.digital, have been getting >> hundreds of Google spams a day for about a year. >> >> Ask your news service for a Google UDP (Usenet Death Penalty) or >> configure your reader to drop everything with "googlegroups.com" in >> the Message-ID. > > Some real users do use GG. This is true, however there are acceptable losses. donald > > Arne From ethan at stoneleaf.us Tue Jul 15 14:27:11 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 15 Jul 2008 10:27:11 -0800 Subject: MySQL Insert In-Reply-To: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> References: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> Message-ID: <487CEBFF.2070003@stoneleaf.us> maestroQC wrote: > Hi, > > Its one of those days. I cannot solve this. Any help would be greatly > appreciated! > When I execute this: > > class Db(object): > def insertAccount(self, date, accountNumber, description, > openingBalance): > dec = decimal.Decimal(openingBalance) > db = MySQLdb.connect(host="localhost", user="dumb", > passwd="dumber", db="rdc") > cursor = db.cursor() > cursor.execute("INSERT INTO es_accounts (dateCreated, > accountNumber, description, openingBalance) VALUES (%s, %s, %s, %d)", > (date, accountNumber, description, dec)) > > I get this error: > Traceback (most recent call last): > File "main.py", line 59, in > main() > File "main.py", line 40, in main > dbObj.insertAccount(dateTo, item[0], item[1], item[8]) > File "C:\projects\workspace\INYR_ES_0.1\src\db.py", line 19, in > insertAccount > cursor.execute("INSERT INTO es_accounts (dateCreated, > accountNumber, description, openingBalance) VALUES (%s, %s, %s > , %d)", (date, accountNumber, description, dec)) > File "c:\python25\lib\site-packages\MySQLdb\cursors.py", line 151, > in execute > query = query % db.literal(args) > TypeError: int argument required > > My table is defined as: > CREATE TABLE es_accounts ( > id int(6) not null auto_increment, > dateCreated date DEFAULT '0000-00-00', > accountNumber int(6) not null, > description varchar(255) not null, > openingBalance decimal(15,8) NOT NULL DEFAULT 0.00000000, > primary key (id) > ); > > TIA How embarassing. My previous post is not correct in it's explanation, unless there is some way to tell Decimal not to allow int coercion... --> from decimal import Decimal --> n10_25 = Decimal('10.25') --> n10_25 Decimal("10.25") --> "%d" % n10_25 '10' About the only thing it had even partially right is not using %d, as it will truncate the fractional part of your opening balance. As far as why you are getting that error, I now have no idea, and I apologize for any confusion created by my error. ~Ethan From russblau at hotmail.com Tue Jul 15 15:50:09 2008 From: russblau at hotmail.com (Russell Blau) Date: Tue, 15 Jul 2008 15:50:09 -0400 Subject: 'if name is not None:' v. 'if name:' References: Message-ID: "Victor Noagbodji" wrote in message news:fdd6be670807151244v6d63e5baj7e316a4ce861ac80 at mail.gmail.com... > > Well that's exactly why I'm asking. Since None returns False in if > statements. Why do people use if name is not None: instead of simply > writing if not name? > Because '' is a string value that is treated as false. If name=='', then "if name:" will be false, but "if name is not None:" will be true. Which one to use depends entirely on how you want to treat empty strings. For all other (string) values of name, the two statements will give the same results. Russ From steve at REMOVE-THIS-cybersource.com.au Sat Jul 26 08:24:28 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Jul 2008 12:24:28 GMT Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> Message-ID: <009b130f$0$20313$c3e8da3@news.astraweb.com> On Sat, 26 Jul 2008 11:08:12 +0200, Nikolaus Rath wrote: > Terry Reedy writes: ... >> Because you must prefix self attributes with 'self.'. If you do not use >> any attributes of the instance of the class you are making the function >> an instance method of, then it is not really an instance method and >> need not and I would say should not be masqueraded as one. If the >> function is a static method, then it should be labeled as one and no >> 'self' is not needed and auto insertion would be a mistake. In brief, I >> assume the OP wants 'self' inserted in the body because inserting it >> only in the parameter list and never using it in the body is either >> silly or wrong. > > > I think you misunderstood him. What he wants is to write > > > class foo: > def bar(arg): > self.whatever = arg + 1 > > > instead of > > class foo: > def bar(self, arg) > self.whatever = arg + 1 > > > so 'self' should *automatically* only be inserted in the function > declaration, and *manually* be typed for attributes. That idea might have worked many years ago, but not now. The problem is, what happens here? class Foo(object): def foo(self, arg): self.whatever = arg + 1 @classmethod def cfoo(cls, arg): cls.whatever = arg - 1 @staticmethod def sfoo(arg): print arg How does the compiler know to insert "self" into the argument list for foo, "cls" into that of cfoo, but do nothing for sfoo? Decorators can transform methods in arbitrarily complex ways using the Descriptor protocol. -- Steven From xushunttr2 at yahoo.cn Tue Jul 1 06:52:32 2008 From: xushunttr2 at yahoo.cn (jinole) Date: Tue, 1 Jul 2008 03:52:32 -0700 (PDT) Subject: Create a sex site Message-ID: <6b749394-46a9-4966-8000-bb6b6d33a68a@l28g2000prd.googlegroups.com> Asian porn sites! Not the best, only better. To join our team, we do together.URL: http://www.loioi.com From dullrich at sprynet.com Mon Jul 7 16:59:10 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 07 Jul 2008 15:59:10 -0500 Subject: caseless dict - questions References: <77798300-820f-4175-a9cb-aef639d42a32@m45g2000hsb.googlegroups.com> Message-ID: In article <77798300-820f-4175-a9cb-aef639d42a32 at m45g2000hsb.googlegroups.com>, Phoe6 wrote: > I have a requirement for using caseless dict. I searched the web for > many different implementations and found one snippet which was > implemented in minimal and useful way. > > ############# > import UserDict > > class CaseInsensitiveDict(dict, UserDict.DictMixin): > def __init__(self, *args, **kwargs): > self.orig = {} > super(CaseInsensitiveDict, self).__init__(*args, **kwargs) > def items(self): > keys = dict.keys(self) > values = dict.values(self) This items() can't be what anyone would want items to be for a "caseless dict". > return [(self.orig[k],v) for k in keys for v in values] > def __setitem__(self, k, v): > hash_val = hash(k.lower()) > self.orig[hash_val] = k > dict.__setitem__(self, hash_val, v) > def __getitem__(self, k): > return dict.__getitem__(self, hash(k.lower())) > > > obj = CaseInsensitiveDict() > obj['Name'] = 'senthil' > print obj > print obj.items() > > obj1 = {} > obj1['Name'] = 'senthil' > print obj1 > print obj1.items() > ########### > [ors at goofy python]$ python cid1.py > {15034981: 'senthil'} > [('Name', 'senthil')] > {'Name': 'senthil'} > [('Name', 'senthil')] > > --- > The difference between the Caselessdict and {} is that when called as > the object, the Caselessdict() is giving me the internal > representation. > obj = CaseInsensitiveDict() > obj['Name'] = 'senthil' > print obj > gives: {15034981: 'senthil'} > > obj1 = {} > obj1['Name'] = 'senthil' > print obj1 > Correctly gives {'Name': 'senthil'} > > What changes should I make to CaseInsensitiveDict ( written above), so > that its instance gives the actual dictionary instead of its internal > representation. > Constructing a dictionary and returning from __init__ method did not > work. It's not entirely clear to me what you want: Since this is supposed to be a "caseless" dict, I imagine that if you say d['Name'] = 'first value' d['name'] = 'new value' then d['Name'] should now be 'new value'. Fine. Now in that case exactly what do you want to see when you print d? Do you want to see {'name':'new value'} or {'name':'new value', 'Name': 'newvalue'}? > TIA, > Senthil -- David C. Ullrich From mail at timgolden.me.uk Thu Jul 10 04:17:51 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 10 Jul 2008 09:17:51 +0100 Subject: Allow tab completion when inputing filepath? In-Reply-To: <08e60124-51c1-40c1-bffe-52c22ff310db@l64g2000hse.googlegroups.com> References: <08e60124-51c1-40c1-bffe-52c22ff310db@l64g2000hse.googlegroups.com> Message-ID: <4875C5AF.60702@timgolden.me.uk> Keith Hughitt wrote: > On Jul 9, 10:18 am, Tim Golden wrote: >> Keith Hughitt wrote: >>> I've been looking around on the web for a way to do this, but so far >>> have not come across anything for this particular application. I have >>> found some ways to enable tab completion for program-related commands, >>> but not for system filepaths. This would be nice to have when >>> prompting the user to enter a file/directory location. >> What platform are you on? And what kind of display? >> (Console / GUI / wxPython / Qt / Web...) >> >> TJG > > Hi TJG, > > Currently Unix/Console. Although I don't have any plans at the moment > to add a GUI, it would be great if a cross-platform solution existed. Ah. Not my area then, I'm afraid :( I mostly do Windows stuff. However, I don't remember ever coming across a standard way of doing this, although it shouldn't be too hard to roll your own. TJG From enleverlesX.XmcX at XmclaveauX.com Sun Jul 6 19:00:53 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Mon, 7 Jul 2008 01:00:53 +0200 Subject: pythoncom InternetExplorer.Application don't work in vista || firefox pythoncom ? In-Reply-To: <29c70427-07f2-43ae-b742-86af4431edd8@34g2000hsh.googlegroups.com> References: <8709b332-9136-4195-839d-f8c17f242a35@59g2000hsb.googlegroups.com> <486fe5cc$0$926$ba4acef3@news.orange.fr> <29c70427-07f2-43ae-b742-86af4431edd8@34g2000hsh.googlegroups.com> Message-ID: <48714f2f$0$897$ba4acef3@news.orange.fr> Hmmmm... I have a similary problem, in another circumstances. It's often a problem of configuration of IE (for news customers). But, it is not easy, because IE has many parameters. Good luck! Michel Claveau From kyosohma at gmail.com Sat Jul 26 18:13:37 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sat, 26 Jul 2008 15:13:37 -0700 (PDT) Subject: wx.Timer not working References: <7a2a1c54-6d74-475c-9566-4d94cb5b5962@a3g2000prm.googlegroups.com> Message-ID: On Jul 26, 2:33?pm, 5lvqbw... at sneakemail.com wrote: > Windows XP SP3 > Python 2.5 > wx.version() = '2.8.1.1 (msw-unicode)' > ------ > I have written the following *simplest* implementation of wx.timer I > can think of. ?No workie. ? I want an exception, a print statement, or > something. > > The wxpython demos all work, but for some reason this isn't. ?The > demos are simple and straghtforward, so I think I understand how it > should work. ?Clues please? ?I've tried variations of ID's, SetOwners, > using and redefining Notify(), Bind, Connect, etc. ?In the cases where > the interpreter doesn't complain about passed argument types, the > callback function is never called. > > import wx > > class MyFrame(wx.Frame): > ? ? ? ? def __init__(self, parent, id, title): > ? ? ? ? ? ? ? ? wx.Frame.__init__(self, parent, id, ? ? title, pos=(100, 100)) > > ? ? ? ? ? ? ? ? timer = wx.Timer(self, -1) > ? ? ? ? ? ? ? ? self.Bind(wx.EVT_TIMER, self.OnTick, timer) > ? ? ? ? ? ? ? ? timer.Start(100) > > ? ? ? ? def OnTick(self, event): > ? ? ? ? ? ? ? ? print 'Hi. Bye.' > ? ? ? ? ? ? ? ? 1/0 #<-- should crash as evidence callback is being called > > class MyApp(wx.App): > ? ? ? ? def OnInit(self): > ? ? ? ? ? ? ? ? frame1 = MyFrame(None, wx.ID_ANY, "This is a test") > ? ? ? ? ? ? ? ? frame1.Show(True) > ? ? ? ? ? ? ? ? return True > > app ? ? = MyApp(0) > app.MainLoop() > > Thanks for any advice!! > > Michael I'm not seeing anything either. Please post this to the wxPython user's group for additional help: http://www.wxpython.org/maillist.php Mike From grante at visi.com Wed Jul 23 09:52:05 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 23 Jul 2008 08:52:05 -0500 Subject: Python Written in C? References: Message-ID: On 2008-07-23, mk wrote: >> Actually, all of the compilers I'm familiar with (gcc and a >> handful of cross compilers for various microprocessors) >> translate from high-level languages (e.g. C, C++) into >> assembly, which is then assembled into relocatable object >> files, which are then linked/loaded to produce machine >> language. > > Doesn't g++ translate C++ into C and then compile C? No. > Last I heard, most C++ compilers were doing that. A decade or two ago there were some C++ front-ends that did that, but I don't think it's common in modern C++ compilers. -- Grant Edwards grante Yow! Oh, I get it!! at "The BEACH goes on", huh, visi.com SONNY?? From timr at probo.com Sun Jul 20 23:44:03 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 21 Jul 2008 03:44:03 GMT Subject: % sign in python? References: <48d08494p4jnhkrhgidmgppg1aostmurvn@4ax.com> Message-ID: <7c188491si65q4gsnj63vbf87n0h1sb8j3@4ax.com> Terry Reedy wrote: > >Tim Roberts wrote: >> Steven Howe wrote: >> >>> Terry Reedy wrote: >>>> korean_dave wrote: >>>>> What does this operator do? Specifically in this context >>>>> >>>>> test.log( "[[Log level %d: %s]]" % ( level, msg ), description ) >>> >>> I thought, in this contexted, it was mapping operator. > >You miss clipped. I never wrote that. Please be careful, especially >about attributing mis-information. If you count the > signs, you'll see that I correctly attributed the question to korean_dave, and the answer to Steve Howe. Steve's reply contained your name, but there was no text from you in my post. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From larry.bates at websafe.com` Mon Jul 28 11:45:13 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Mon, 28 Jul 2008 10:45:13 -0500 Subject: We programming In-Reply-To: References: Message-ID: <6uadnZFLhJMQdBDVnZ2dnUVZ_rrinZ2d@comcast.com> srinivasan srinivas wrote: > Hi, > Could someone suggest me better python modules for developing web programming related projects like web-pages download and uopload?? > Thanks, > Srini > > > Explore your hobbies and interests. Go to http://in.promos.yahoo.com/groups/ urllib, urllib2, httplib All depends on what you want to do with them. -Larry From gagsl-py2 at yahoo.com.ar Wed Jul 30 00:38:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 01:38:12 -0300 Subject: RTF Parsing References: <4dc0cfea0807290608v3e89a5c6m7dc0ca70fd064a00@mail.gmail.com> Message-ID: En Tue, 29 Jul 2008 10:08:21 -0300, Victor Subervi escribi?: > Hi; > I have this code: > def a(): > chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', > '\\yz'] > rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like the > Beast? Who can wage war against him?\par' The \ is an escape character inside string literals. '\n' contains a *single* character and it's the same as chr(10). '\f0' is two characters long, not three. You have two alternatives: a) double each \ (because \\ is interpreted as a single backslash): rtf_markup = 'viewkind4\\uc1\\pard\\nowidctlpar\\qc...' b) use raw strings - that is, prefix each string literal with a small r: rtf_markup = r'viewkind4\uc1\pard\nowidctlpar...' See the tutorial http://docs.python.org/tut/node5.html#SECTION005120000000000000000 and the gory details at http://docs.python.org/ref/strings.html -- Gabriel Genellina From bearophileHUGS at lycos.com Mon Jul 28 06:28:05 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 28 Jul 2008 03:28:05 -0700 (PDT) Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <488d7d43$1@news2-rz-ap.ethz.ch> Message-ID: <41b03ed3-c515-48c7-9546-84a8bf9178bd@l42g2000hsc.googlegroups.com> Suresh Pillai: > Or 4, since the order of my nodes doesn't matter: swap the node to be > deleted with the last node in the list and then remove the last node of > the list. This is the fastest to date, if using native structures, for > low number nodes being deleted per cycle (def if only deleting one). Using Psyco this suggestion may lead to code as fast as it gets in Python :-) Bye, bearophile From asmodai at in-nomine.org Wed Jul 9 08:18:48 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Wed, 9 Jul 2008 14:18:48 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <4874A9C9.7020804@FreeBSD.org> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <750f823a-f9de-4f81-9eb3-7c7b39237c90@y38g2000hsy.googlegroups.com> <4874A9C9.7020804@FreeBSD.org> Message-ID: <20080709121848.GO26006@nexus.in-nomine.org> -On [20080709 14:08], Kris Kennaway (kris at FreeBSD.org) wrote: >It's compiler/build output. Sounds like the FreeBSD ports build cluster. :) Kris, have you tried a PGO build of Python with your specific usage? I cannot guarantee it will significantly speed things up though. Also, a while ago I did tests with various GCC compilers and their effect on Python running time as well as Intel's cc. Intel won on (nearly) all accounts, meaning it was faster overall. >From the top of my mind: GCC 4.1.x was faster than GCC 4.2.x. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Beware of the fury of the patient man... From timr at probo.com Fri Jul 4 01:31:56 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 04 Jul 2008 05:31:56 GMT Subject: Required items in a form References: <45yak.331$Ae3.313@trnddc05> Message-ID: "Brandon" wrote: > >What I'm trying to do is essentially force a user to fill in required items >in a form, which will be saved to a database. How can I get it so that once >the user clicks "OK" on the dialog box, it transfers control back to the >form, and not save the empty fields into the database? What do you mean by "transfers control back to the form"? A form doesn't have any code, and so can't "control" anything. Now, it is certainly possible to define an onSubmit handler in the header, then write a Javascript function that validates the input. If the function returns false, the submit won't happen. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mail at timgolden.me.uk Wed Jul 16 10:01:58 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 15:01:58 +0100 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: <487DFF56.7010405@timgolden.me.uk> Fredrik Lundh wrote: > Ken Hartling wrote: > > > Thanks .. but I want to find out if the system is "running on 64bit" > > even when the interpreter is a 32-bit build executable ("what python > > was built on"). platform.architecture() and platform() in general > > seems to only be looking at the build executable > > You can pass in an arbitrary binary to architecture(), so I guess you > could use this on some suitable thing under "/bin" on a Unix box. This > doesn't work on Windows, though. > > In this message, > > http://mail.python.org/pipermail/python-list/2005-June/326158.html > > Thomas Heller suggests using ctypes to call the Windows API directly; so > something like this could work: > > >>> import ctypes, sys > >>> i = ctypes.c_int() > >>> kernel32 = ctypes.windll.kernel32 > >>> process = kernel32.GetCurrentProcess() > >>> kernel32.IsWow64Process(process, ctypes.byref(i)) > 1 > >>> is64bit = (i.value != 0) > >>> is64bit > False This is included in the latest pywin32-211 as well: import win32process print win32process.IsWow64Process () TJG From bearophileHUGS at lycos.com Fri Jul 11 06:36:45 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 11 Jul 2008 03:36:45 -0700 (PDT) Subject: Moving to functional programming References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> Message-ID: <3ebed664-a6ba-4e30-acc5-f7d5edb25e32@56g2000hsm.googlegroups.com> James Fassett: > # the first Pythonic attempt using comprehensions > result_list = [x[0] for x in tuple_list] > > # the final functional way > [result_list, _] = zip(*tuple_list) > > I really like how Python allows me to do what I feel is the most > natural solution (for a seasoned procedural programmer) while allowing > a satisfying path towards a more functional approach. The list comprehension is quite more readable to me, so I suggest you to use it. It's probably the default way to do it in Python. If you want functional code this is another way (I have not tested the relative performance but it may be quick): >>> tuple_list = ( ... ('John', 'Doe'), ... ('Mark', 'Mason'), ... ('Jeff', 'Stevens'), ... ('Bat', 'Man') ... ) >>> from operator import itemgetter >>> map(itemgetter(0), tuple_list) ['John', 'Mark', 'Jeff', 'Bat'] Bye, bearophile From google at mrabarnett.plus.com Thu Jul 24 21:40:41 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 24 Jul 2008 18:40:41 -0700 (PDT) Subject: Is there a metacharacter to match transitions between any two of a set of non intersected char classes? References: Message-ID: <2ada0734-9193-45ef-ad08-1ac9fdcd8fcd@a21g2000prf.googlegroups.com> On Jul 24, 6:48?pm, Peng Yu wrote: > Hi, > > '\b' only match the boundary between alphanumerical char and > nonalphanumerical char. I'm wonder if there is a generic metacharacter > to match the boundary between any non intersected char set defined in > regex and its complement. > > For example, I have a few non intersected char sets [a-zA-Z_0-9], [:] > and [\s], and lets call the new metacharactor \m. > > r"abc\m" would be the same as r"abc\b" > r"abc:\m' would match "abc:" in r"abc:xy" but not "abc::xy" > r"a \m" (with one space) would match "a " (with one space) in "a abc" > but not "a ?abc" (with two spaces). > > I would like that I have the flexibility to define more non > intersected char sets, while I don't want change the regex that I have > written. > Interesting idea. It could be added, but how much demand is there for it? From gagsl-py2 at yahoo.com.ar Thu Jul 17 19:26:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 17 Jul 2008 20:26:11 -0300 Subject: Converting from local -> UTC References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> <41d4ffc7-7fd5-4202-92ea-132c7d4f5cd4@s50g2000hsb.googlegroups.com> Message-ID: En Wed, 16 Jul 2008 15:00:50 -0300, Keith Hughitt escribi?: > Thanks Gabriel! > > That helps clear things up for me. The above method works very well. I > only have one remaining question: > How can I pass a datetime object to MySQL?' > > So far, what I've been doing is building the query as a string, for > example: > > query = "INSERT INTO image VALUES(%d, %d, %s, '%s')" % (id, meas, > date, 'jpg') > cursor.execute(query) That's not a good idea, in general (among other problems: what if any text contains a quote? ever heard of "sql injection"?). Use this form instead: query = "INSERT INTO image VALUES(%s, %s, %s, %s)" cursor.execute(query, (id, meas, date, 'jpg')) Note that I used %s everywhere (it's just a placeholder, not a format) and the execute method receives two arguments, the second being a tuple containing the desired values. -- Gabriel Genellina From jordanrastrick at gmail.com Thu Jul 24 06:21:20 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 03:21:20 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> > This is just plain wrong for at least C# and C++. ?C# wants you to > explicitly overload "!=", if you have overloaded "==", While this is as inconvenient as Python at least it doesn't catch you unawares. C# 1 (or maybe 0.5), Python 0. > C++ complains > about "!=" not being defined for class A. ? See above. C++ 1, Python 0. So in showing my clearly hyperbolic comment was technically incorrect (something I could have told you myself), you have merely shown that two languages I find vastly inferior to Python overall are actually better than it in this case. > Fortunately, Python isn't designed according to your ideas, and won't > change, so consider your posting a waste of time. ?If feeling like bringing > such old "issues" up again next time, spend your time learning another > programming language, as you would obviously not get happy with Python > anyway ... OK, if that's your response, that's sad. Of course, I try to learn new languages all the time. Python is still IMO the best. If the attitude in the community in response to feedback/criticism has gone from "maybe you've got a point" to "your a lunatic, we'll never change", well, only Python will suffer in the long term. From WookieTim at gmail.com Mon Jul 7 11:28:34 2008 From: WookieTim at gmail.com (furby) Date: Mon, 7 Jul 2008 08:28:34 -0700 (PDT) Subject: Hi there! I need what is probably a very basic lesson in events.... References: <4d5a5286-f4cf-480e-9432-b4b337f7c145@x35g2000hsb.googlegroups.com> <8fca22ab-67ad-4dbb-b92c-d5412a8eba2f@m44g2000hsc.googlegroups.com> Message-ID: On Jul 7, 10:34?am, Mike Driscoll wrote: > On Jul 6, 8:18?am, furby wrote: > > > > > I am teaching myself Python... I'm nowhere near even intermediate > > level yet, so treat me like an idiot. I am using Boa Constructor on > > Ubuntu 8.04 if that helps. Here is what I have right now : > > > I am plying with reading a URL (An RSS feed to be exact) and > > displaying it inside a HTMLWindow. I have that part working - It shows > > the title as a link and displays the description next to it. What I > > want to do is trap the mouseclick on the link and use that to grab > > just the text that is on the site. Right now, if I click on it, the > > HTML window control takes me to the site and doesn't really show the > > site very well, since it doesn't seem to do CSS. That's okay - I just > > want to display the text.... How do I trap the mouse clicking on the > > link? > > > I know that HTMLwindow has a "OnLinkClicked" event - I can see it in > > the docs for that control. But it seems that Boa Constructor doesn't > > expose that event in it's frame designer.... How do I code a event > > that fires off instead of the default event? > > > I don't know if I am being clear enough, so if not just tell me what I > > should say... Liek I said, I am a newbie right now. > > I think you just need to override that method (OnLinkClicked) in the > class you use to subclass the HtmlWindow widget. Something like this: > > > class MyCustomDlg(wx.Frame): > It sounds eminently reasonable. I'll try it tonight when I get home and let you know if it works! > ? ? def __init__(self, parent, title, icon, pos): > > ? ? ? ? wx.Frame.__init__(self, parent, wx.ID_ANY, title, > size=(400,400)) > > ? ? ? ? x,y = pos > ? ? ? ? self.SetPosition((x+30, y+30)) > > ? ? ? ? self.SetIcon(icon) > ? ? ? ? html = wxHTML(self) > > class wxHTML(wx.html.HtmlWindow): > ? ? ?def OnLinkClicked(self, link): > ? ? ? ? ?# do something here > ? ? ? ? ?pass > > > However, for wxPython questions, it's best to post to the wxPython > user's group. They are very knowledgeable there.http://wxpython.org/maillist.php > > Hope that helps. > > ------------------- > Mike Driscoll > > Blog: ?http://blog.pythonlibrary.org > Python Extension Building Network: ? ?http://www.pythonlibrary.org From Nikolaus at rath.org Tue Jul 29 04:20:07 2008 From: Nikolaus at rath.org (Nikolaus Rath) Date: Tue, 29 Jul 2008 10:20:07 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <488D5B2C.10808@gmail.com> <488e6af8$0$20692$426a74cc@news.free.fr> Message-ID: <87tze9qeyw.fsf@nokile.rath.org> Bruno Desthuilliers writes: > Nikolaus Rath a ?crit : >> Michael Torrie writes: > > (snip) > >>> In short, unlike what most of the implicit self advocates are >>> saying, it's not just a simple change to the python parser to do >>> this. It would require a change in the interpreter itself and how it >>> deals with classes. >> >> >> Thats true. But out of curiosity: why is changing the interpreter such >> a bad thing? (If we suppose for now that the change itself is a good >> idea). > > Because it would very seriously break a *lot* of code ? Well, Python 3 will break lots of code anyway, won't it? Best, -Nikolaus -- ?It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.? -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From gherron at islandtraining.com Tue Jul 29 00:17:55 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 28 Jul 2008 21:17:55 -0700 Subject: exec(code) not allowing import on top level? In-Reply-To: References: Message-ID: <488E99F3.9040608@islandtraining.com> Peter Teuben wrote: > > if I define a simple string code, with the following contents: > > import math > def foo(x): > return math.sqrt(x) What? You have not told us something important here. First, that code won't fail because it does not even execute the function foo -- it just defines it. Second, if I exend your string with one more line "foo(123)" to actually execute the code, it still works as expected. So let's try this again... and this time please please also show us the full text of the error message. Gary Herron > > and i run it using exec(code) in python, math is not known. But when I > recode the string as: > > def foo(x): > import math > return math.sqrt(x) > > it works fine. That seemed like an inconsistency, since it works > fine otherwise, as expected. It's easy to work around, but > just odd to find this out. > > thanks > > peter > -- > http://mail.python.org/mailman/listinfo/python-list From martin at v.loewis.de Fri Jul 4 02:36:56 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 04 Jul 2008 08:36:56 +0200 Subject: problem parsing utf-8 encoded xml - minidom In-Reply-To: References: Message-ID: <486dc508$0$23431$9b622d9e@news.freenet.de> > The parser is failing on this line: > > Heinrich K?ufner, Norbert Nedopil, Heinz Sch?och (Hrsg.). mrcb245-c> If it is literally this line, it's no surprise: there must not be a line break between the slash and the closing element name. However, since you are getting the error in a different column, it's indeed more likely that there is a problem with the encoding. Given that the Python UTF-8 codec refuses the data, most likely, the data is *not* encoded in UTF-8 (but perhaps in Latin-1). If so, you need to prefix the XML document with a proper XML declaration, such as Alternatively, make sure that the file is really encoded in UTF-8. Regards, Martin From rocksportrocker at googlemail.com Fri Jul 18 02:41:50 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 17 Jul 2008 23:41:50 -0700 (PDT) Subject: How to process a very large (4Gb) tarfile from python? References: <0e96241d-60a3-44fd-967a-394904ad5b34@e39g2000hsf.googlegroups.com> <4nqu74p3mmmdmf9pn7125voe6itko8d31k@4ax.com> Message-ID: <1fe948fd-63a3-48ef-b5a8-84f0e4dd48a2@y22g2000prd.googlegroups.com> On 17 Jul., 22:21, Lars Gust?bel wrote: > > > Maybe we should post this issue to python-dev mailing list. > > Parsing large tar-files is not uncommon. > > This issue is known and was fixed for Python 3.0, seehttp://bugs.python.org/issue2058. The proposed patch does not avoid caching the previous values of the iterator, it just reduces the size of each cached object. It would be nice to be able to avoid caching on demand, which would make iteration independent of the size of the tar file. Greetings Uwe From mail at timgolden.me.uk Wed Jul 16 11:59:16 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 16 Jul 2008 16:59:16 +0100 Subject: About wmi In-Reply-To: References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> <65eef996-c1cb-4611-934f-94a88aeb1757@m36g2000hse.googlegroups.com> Message-ID: <487E1AD4.9020509@timgolden.me.uk> patrol wrote: > -2147023174 > 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3' > None > None > > ---------------------------------------------------------------------- > import pythoncom > import win32com.client > > > try: > win32com.client.GetObject ("winmgmts://blahblah") > except pythoncom.com_error, info: > for i in info: > print i > > -2147023174 > RPC ??????? > None > None > ------------------------------------------------------------------------- >>>> a="RPC ???????" >>>> a > 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3' > ------------------------------------------------------------------------- > Patrol Brilliant. Thanks, Patrol. So the error message comes back encoded. Can you confirm what your console encoding is, please? The following script should confirm: import os, sys print sys.stdout.encoding os.system ("chcp") TJG From code at pizzashack.org Mon Jul 14 17:24:54 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 14 Jul 2008 17:24:54 -0400 Subject: Using Python To Launch Python In-Reply-To: References: Message-ID: <20080714212454.GE16010@dragontoe.org> On Mon, Jul 14, 2008 at 02:01:04PM -0700, aha wrote: > Since my application has it's own version of Python installed with > it how should I use the system Python to launch the version of > Python that launches my Application. Yes, this is a convoluted > process, but not all Pythons are built the same :) /usr/local/bin/$APPNAME: #!/bin/sh INSTALLPATH= PATH=$INSTALLPATH/bin:$PATH exec $INSTALLPATH/bin/python $APPNAME "$@" Doesn't get much simpler than that. :) You can certainly do the equivalent in Python... there's not much difference. Slightly less typing in bourne/bash shell, I guess... -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From dinov at exchange.microsoft.com Wed Jul 30 01:12:32 2008 From: dinov at exchange.microsoft.com (Dino Viehland) Date: Tue, 29 Jul 2008 22:12:32 -0700 Subject: interpreter vs. compiled In-Reply-To: References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> <70bf12ba-22b8-458b-8b95-54f434124e5e@79g2000hsk.googlegroups.com> <5cc96c41-9ec2-40b8-bcb4-48bc50b9038f@34g2000hsh.googlegroups.com> Message-ID: <7AD436E4270DD54A94238001769C2227012C9376BA46@DF-GRTDANE-MSG.exchange.corp.microsoft.com> IronPython doesn't have an interpreter loop and therefore has no POP / TOP / etc... Instead what IronPython has is a method call Int32Ops.Add which looks like: public static object Add(Int32 x, Int32 y) { long result = (long) x + y; if (Int32.MinValue <= result && result <= Int32.MaxValue) { return Microsoft.Scripting.Runtime.RuntimeHelpers.Int32ToObject((Int32)(result)); } return BigIntegerOps.Add((BigInteger)x, (BigInteger)y); } This is the implementation of int.__add__. Note that calling int.__add__ can actually return NotImplemented and that's handled by the method binder looking at the strong typing defined on Add's signature here - and then automatically generating the NotImplemented result when the arguments aren't ints. So that's why you don't see that here even though it's the full implementation of int.__add__. Ok, next if you define a function like: def adder(a, b): return a + b this turns into a .NET method, which will get JITed, which in C# would look something like like: static object adder(object a, object b) { return $addSite.Invoke(a, b) } where $addSite is a dynamically updated call site. $addSite knows that it's performing addition and knows how to do nothing other than update the call site the 1st time it's invoked. $addSite is local to the function so if you define another function doing addition it'll have its own site instance. So the 1st thing the call site does is a call back into the IronPython runtime which starts looking at a & b to figure out what to do. Python defines that as try __add__, maybe try __radd__, handle coercion, etc... So we go looking through finding the __add__ method - if that can return NotImplemented then we find the __radd__ method, etc... In this case we're just adding two integers and we know that the implementation of Add() won't return NotImplemented - so there's no need to call __radd__. We know we don't have to worry about NotImplemented because the Add method doesn't have the .NET attribute indicating it can return NotImplemented. At this point we need to do two things. We need to generate the test which is going to see if future arguments are applicable to what we just figured out and then we need to generate the code which is actually going to handle this. That gets combined together into the new call site delegate and it'll look something like: static void CallSiteStub(CallSite site, object a, object b) { if (a != null && a.GetType() == typeof(int) && b != null && b.GetType() == typeof(int)) { return IntOps.Add((int)a, (int)b); } return site.UpdateBindingAndInvoke(a, b); } That gets compiled down as a lightweight dynamic method which also gets JITed. The next time through the call site's Invoke body will be this method and things will go really fast if we have int's again. Also notice this is looking an awful lot like the inlined/fast-path(?) code dealing with int's that you quoted. If everything was awesome (currently it's not for a couple of reasons) the JIT would even inline the IntOps.Add call and it'd probably be near identical. And everything would be running native on the CPU. So that's how 2 + 2 works... Finally if it's a user type then we'd generate a more complicated test like (and getting more and more pseudo code to keep things simple): if (PythonOps.CheckTypeVersion(a, 42) && PythonOps.CheckTypeVersion(b, 42)) { return $callSite.Invoke(__cachedAddSlot__.__get__(a), b); } Here $callSite is another stub which will handle doing optimal dispatch to whatever __add__.__get__ will return. It could be a Python type, it could be a user defined function, it could be the Python built-in sum function, etc... so that's the reason for the extra dynamic dispatch. So in summary: everything is compiled to IL. At runtime we have lots of stubs all over the place which do the work to figure out the dynamic operation and then cache the result of that calculation. Also what I've just described is how IronPython 2.0 works. IronPython 1.0 is basically the same but mostly w/o the stubs and where we use stub methods they're much less sophisticated. Also, IronPython is open source - www.codeplex.com/IronPython -----Original Message----- From: python-list-bounces+dinov=microsoft.com at python.org [mailto:python-list-bounces+dinov=microsoft.com at python.org] On Behalf Of castironpi Sent: Tuesday, July 29, 2008 9:20 PM To: python-list at python.org Subject: Re: interpreter vs. compiled On Jul 29, 7:39 am, alex23 wrote: > On Jul 29, 2:21 pm, castironpi wrote: > > > On Jul 28, 5:58 pm, Fuzzyman wrote: > > > Well - in IronPython user code gets compiled to in memory assemblies > > > which can be JIT'ed. > > > I don't believe so. > > Uh, you're questioning someone who is not only co-author of a book on > IronPython, but also a developer on one of the first IronPython-based > commercial applications. > > I know authorship isn't always a guarantee of correctness, but what > experience do you have with IronPython that makes you so unwilling to > accept the opinion of someone with substantial knowledge of the > subject? None, no experience, no authority, only the stated premises & classifications, which I am generally tending to misinterpret. I'm overstepping my bounds and trying to do it politely. (Some might call it learning, which yes, though uncustomary, *requires questioning authorities*, or reinventing.) Evidently, I have a "fundamental misunderstanding of the compilation process", which I'm trying to correct by stating what I believe. I'm trying to elaborate, and I'm meeting with increasingly much detail. So, perhaps I'll learn something out of this. Until then... What I know I have is two conflicting, contradictory, inconsistent beliefs. Maybe I've spent too much time in Python to imagine how a dynamic language can compile. This is from 7/22/08, same author: > I wouldn't say "can't". The current CPython VM does not compile > code. It COULD. The C#/.NET VM does. Three big claims here that I breezed right over and didn't believe. > It COULD. I'm evidently assuming that if it could, it would. > The current CPython VM does not compile code. Therefore it couldn't, or the assumption is wrong. Tim says it is. And the glaring one-- WHY NOT? Why doesn't CPython do it? >From 7/18/08, own author: >> #define TOP() (stack_pointer[-1]) #define BASIC_POP() (*--stack_pointer) ...(line 1159)... w = POP(); v = TOP(); if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) { /* INLINE: int + int */ register long a, b, i; a = PyInt_AS_LONG(v); b = PyInt_AS_LONG(w); i = a + b; << I am imagining that every Python implementation has something like it. If IronPython does not, in particular, not have the 'POP(); TOP();' sequence, then it isn't running on a stack machine. Is the IronPython code open source, and can someone link to it? I'm not wading through it from scratch. What does it have instead? Does dynamic typing still work? If you're bluffing, bluff harder; I call. If you're not, I apologize; teach me something. If you can ask better, teach me that too. -- http://mail.python.org/mailman/listinfo/python-list From bulg at ngs.ru Sun Jul 13 21:51:19 2008 From: bulg at ngs.ru (Yosifov Pavel) Date: Sun, 13 Jul 2008 18:51:19 -0700 (PDT) Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> Message-ID: > Well, I think Python's iterators, especially the generators, are beautiful. > More importantly, I think there is no general way to make iterators > copyable, regardless of the programming language. The problem is that most > of the useful ones depend on external state. > > Peter Hmm, but tee() de facto do it (clone iterator) and ignore side-effects of iterator ("external" state). And tee() create independent **internal** state of iterator (current position). But **external** state - is headache of programmer. So, iterator/generator have to be method for copy itself (the tee() implementation) or be "re- startable". Why not? Concrete problem was to generate iterators (iterator of slices). It was solved with ReIter. --Best regards, --pavel From __peter__ at web.de Tue Jul 29 07:48:39 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Jul 2008 13:48:39 +0200 Subject: exec(code) not allowing import on top level? References: Message-ID: Peter Teuben wrote: > > if I define a simple string code, with the following contents: > > import math > def foo(x): > return math.sqrt(x) The import math statement puts 'math' in the local namespace, and foo looks it up in the global namespace. This can only work when these namespaces are the same: >>> code = """ ... import math ... def foo(x): ... return math.sqrt(x) ... print foo(2) ... """ >>> exec code in {} 1.41421356237 >>> exec code in {}, {} Traceback (most recent call last): File "", line 1, in File "", line 5, in File "", line 4, in foo NameError: global name 'math' is not defined You could argue that Python should always look into the local namespace and then fall back to the global namespace but that would be fruitless extra work in most cases. I think it can only hapen with exec/eval, and as you have seen in the other responses even there it works on the module level because -- tada! >>> globals() is locals() True > and i run it using exec(code) in python, math is not known. But when I > recode the string as: > > def foo(x): > import math > return math.sqrt(x) Here Python "guesses" that math is a local variable and that guess is correct. If you wrote import math def foo(x): return math.sqrt(x) math = 42 Python would still guess that math is a local name and you would end up with a runtime exception. Peter From rw at smsnet.pl Wed Jul 9 15:56:46 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 09 Jul 2008 21:56:46 +0200 Subject: FOSS projects exhibiting clean/good OOP? References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> Message-ID: <87iqve25mp.fsf@merkury.smsnet.pl> Phillip B Oldham writes: > I'm wondering whether anyone can offer suggestions on FOSS projects/ > apps which exhibit solid OO principles, clean code, good inline > documentation, and sound design principles? > > I'm devoting some time to reviewing other people's code to advance my > skills. Its good to review bad code (of which I have more than enough > examples) as well as good, but I'm lacking in finding good examples. > > Projects of varying sizes would be great. IMHO these projects are examples of very interesting and clean design: docutils: http://docutils.sourceforge.net/docs/dev/hacking.html trac: http://trac.edgewall.org/wiki/TracDev/ComponentArchitecture In both of them code is not just clean, it is a work of art. ;) HTH, Rob From Russ.Paielli at gmail.com Wed Jul 30 22:36:53 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 30 Jul 2008 19:36:53 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> Message-ID: <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> On Jul 30, 7:05 pm, Erik Max Francis wrote: > Russ P. wrote: > > On Jul 30, 1:07 am, Erik Max Francis wrote: > >> Russ P. wrote: > >>> Oh, Lordy. I understand perfectly well how boolean tests, __len__, and > >>> __nonzero__ work in Python. It's very basic stuff. You can quit > >>> patronizing me (and Carl too, I'm sure). > >> You suggested a syntax for testing non-emptiness (`x is not empty`) > >> which indicated a profound misunderstanding of what the `is` operator does. > > >> You then acknowledged that there might be a problem because of the > >> implication if the `is` operator and weren't sure whether it would work > >> or not: > > > Oh, my. I wrote something like, "It would sure be nice to be able to > > write > > > if x is not empty: > > > because it reads like natural language. Immediately after I posted it, > > I thought, "oh, I'll bet some idiot takes that as a serious proposal." > > Sure enough, some idiot did just that almost immediately. > > Yes, all people are idiots for reading what you wrote, reading your > later realization that it was wrong, and taking both at face value. > I'll be sure never to make that mistake again! > > > And he is > > still patronizing me for it. > > No, I'm not patronizing you for your initial misstatement. I'm mocking > you for your pathetic and transparent attempt to backpedal away from it. > Just give it up, already. > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis > Drifting from woman-who-tries misconstrued / Shifting to woman-wise > -- Lamya The reason I wrote that "it would be nice to be able to write" if x is not empty: is that it reads naturally. It was not an actual proposal, and the fact that you took it as such was *your* mistake. I can understand your misunderstanding one time, but you have now repeated it three times, despite my (unnecessary) explanations. One more time, and you graduate from idiot to moron. Having said that, the syntax I wrote *could* conceivably work IF all empty lists pointed to one empty list, just as all values set to None actually point to the same None. That is possible, but probably not a good idea. Now read carefully: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! Let me repeat that for you: I DID NOT CLAIM THAT THIS IS THE WAY TO DO IT! Did you get that, idiot? From tjreedy at udel.edu Fri Jul 11 15:06:11 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 Jul 2008 15:06:11 -0400 Subject: Moving to functional programming In-Reply-To: <3ebed664-a6ba-4e30-acc5-f7d5edb25e32@56g2000hsm.googlegroups.com> References: <5b31d997-a02d-4bb5-9710-24b312a68667@56g2000hsm.googlegroups.com> <3ebed664-a6ba-4e30-acc5-f7d5edb25e32@56g2000hsm.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > James Fassett: >> # the first Pythonic attempt using comprehensions >> result_list = [x[0] for x in tuple_list] This has the virtue of working for tuples of any length and doing the minimal work required. >> # the final functional way >> [result_list, _] = zip(*tuple_list) This requires the tuples in tuple_list to be of length 2. It also produces a second list that is then tossed away. > The list comprehension is quite more readable to me, so I suggest you > to use it. It's probably the default way to do it in Python. It also has two virtues that the non-equivalent alternative lacks. > If you want functional code this is another way (I have not tested the > relative performance but it may be quick): > >>>> tuple_list = ( > ... ('John', 'Doe'), > ... ('Mark', 'Mason'), > ... ('Jeff', 'Stevens'), > ... ('Bat', 'Man') > ... ) >>>> from operator import itemgetter >>>> map(itemgetter(0), tuple_list) > ['John', 'Mark', 'Jeff', 'Bat'] This again makes just one list from tuples of any length. Some of the other alternatives in another post do minimal work but only work with pairs. tjr From marek.rocki at wp.pl Fri Jul 4 11:19:01 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Fri, 4 Jul 2008 08:19:01 -0700 (PDT) Subject: Javascript - Python RSA encryption interoperability References: Message-ID: <79934f50-2208-4e68-8d61-1fd33d34a468@a1g2000hsb.googlegroups.com> Evren Esat Ozkan napisa?(a): > Hello, > > I'm trying to encrypt a string with RSA. But it needs to be compitable > with Dave's JavaScript RSA implementation*. I'm already read and tried > lots of different things about RSA and RSA in Python. But could not > produce the same result with the javascript library. > > My experiments could be seen at: http://dpaste.com/hold/60741/ > > * JavaScript RSA Library: http://www.ohdave.com/rsa/ > > Python libraries which I tried; > * PyCrtypo: http://www.amk.ca/python/code/crypto.html > * rsa library from http://www.stuvel.eu/rsa > > How could I create the same results with the JS library in Python. > > > Any help would be appreciated > > Evren, It seems that this Javascript is doing weird things to its input, namely processing it in reverse. Try encrypting ciphertext[::-1] instead of just ciphertext. public_modulus_hex = '9F2E..snip..4BC7' public_exponent_hex = '10001' public_modulus = int(public_modulus_hex, 16) public_exponent = int(public_exponent_hex, 16) def encrypt(plaintext_text): # Beware, plaintext must be short enough to fit in a single block! plaintext = int(plaintext_text.encode('hex'), 16) ciphertext = pow(plaintext, public_exponent, public_modulus) return '%X' % ciphertext # return hex representation print encrypt('12345') print encrypt('12345'[::-1]) # Will return the value compatible with JS output Regards, Marek From larry.bates at websafe.com` Fri Jul 25 07:30:33 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Fri, 25 Jul 2008 06:30:33 -0500 Subject: object persistency, store instances relationship externally In-Reply-To: <3183af12-4b1e-4bd1-8d21-b9fc2b421008@v1g2000pra.googlegroups.com> References: <3183af12-4b1e-4bd1-8d21-b9fc2b421008@v1g2000pra.googlegroups.com> Message-ID: <2dqdnXc7zqT2JBTVnZ2dnUVZ_umdnZ2d@comcast.com> King wrote: > This is a new test for object persistency. I am trying to store the > relationship between instances externally. > It's not working as expected. May be I am doing it in wrong way. Any > suggestions? > > > import shelve > > class attrib(object): > pass > > class node(object): > def __init__(self): > self.a = attrib() > self.b = attrib() > self.c = attrib() > self.d = attrib() > > a = node() > #store pair relationship. This relationship is created at run time. > lst = [[a.a, a.b], [a.c, a.d]] > #Write objects into file > shelf = shelve.open('shelve_test_01.txt', writeback=True) > shelf['node'] = a > shelf['lst'] = lst > shelf.sync() > shelf.close() > > > #Read objects from file > shelf = shelve.open('shelve_test_01.txt', 'r') > a = shelf['node'] > lst = shelf['lst'] > print a.a, a.b, a.c, a.d > #lst does not contains the relationship of object 'a''s attributes, > instead it's creating new instances > #of 'attrib' class > print lst > You may want to take a look at Zope's ZODB. -Larry From RyanSmithEE at gmail.com Thu Jul 17 14:47:14 2008 From: RyanSmithEE at gmail.com (Ryan Smith) Date: Thu, 17 Jul 2008 11:47:14 -0700 (PDT) Subject: Rotating a cube References: <3d47df08-9734-4e0f-96ad-37da445b4faf@34g2000hsh.googlegroups.com> Message-ID: <58b8339f-658e-432d-9231-3509a04f422b@s21g2000prm.googlegroups.com> Have you taken the time to solve the problem for the 2D case? I can't say my code is correct or even good python, but this was my attempt at the 2D case, maybe it will give you some ideas. http://code.google.com/p/rs-wxpython-nooberdev/source/browse/rectangle.py For the rest of c.l.p, criticism is welcome :-) Regards, Ryan On Jul 17, 2:11 am, J-Burns wrote: > On Jul 17, 12:53 pm, Fredrik Lundh wrote: > > > J-Burns wrote: > > > Is there a built in Python function for this? > > > for answering questions that have nothing to do with programming, and > > looks quite a bit like homework? don't think they've added that one yet. > > > maybe you should look for a geometry newsgroup/forum? > > > > > I meant to ask how would you do this in Python... :S From mangaboy001 at gmail.com Tue Jul 1 06:15:45 2008 From: mangaboy001 at gmail.com (mangaboy001) Date: Tue, 1 Jul 2008 03:15:45 -0700 (PDT) Subject: Naruto 407, One Piece 506, Bleach 329 Hot manga Download Message-ID: <062683aa-ff14-43f9-818d-a3a623b0e051@u36g2000prf.googlegroups.com> Naruto 407, One Piece 506, Bleach 329 Hot manga Download The hottest mangas and the latest chapters Manga news, Most popular mangas, Latest mangas, Latest chapters http://english1.isoshu.com/?recommid=1023 http://emanga1.isoshu.com/?recommid=1023 A New Wonderful Manga: Maken-ki! http://english1.isoshu.com/search/Maken-ki/all-1?recommid=1023 Hi, my friends!!! Have you read the manga named Maken-ki? This manga series is as nice as To-Love-ru!!! The illustrator is Hiromitsu Takeda and his girls are incredibly gorgeous. The story is described as an "ecchi love comedy with battle action." Oyama Takeshi happily enrolls in a co-ed school that didn't required any entrance exams and has hostels to book... Only to find out that there's more to the school than he thought! It is very good that Takeda-san likes to draw his girls with very big eyes. Have only read a bit so far but many of the girls have an item called "Maken" - each are different and have varying powers when used in battle. And as with all good school girl battles, their clothes easily explode. And there are characters for folks who like loli's too. Maken Ki has been an entertaining read so far and look forward to more!!! I am sure that you must be love it at the first glance!!! http://english1.isoshu.com/search/Maken-ki/all-1?recommid=1023 From wuwei23 at gmail.com Thu Jul 24 13:03:35 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 24 Jul 2008 10:03:35 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> Message-ID: <73ba661a-9d3b-4e53-b233-fd1b21dc9f6d@a2g2000prm.googlegroups.com> On Jul 25, 1:39 am, Torsten Bronger wrote: > I could easily write a preprocessor which does it after all. Have you considered actually doing so? That might resolve the whole issue, if a tool exists for those who want implicit self. After all, if -you- have the itch... Perhaps you could leverage off of EasyExtend? "EasyExtend (EE) is a preprocessor generator and metaprogramming framework written in pure Python and integrated with CPython. The main purpose of EasyExtend is the creation of extension languages i.e. adding custom syntax and semantics to Python." http://www.fiber-space.de/EasyExtend/doc/EE.html From tjreedy at udel.edu Tue Jul 15 17:00:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Jul 2008 17:00:48 -0400 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: <8AEDA5E3386EA742B8C24C95FF0C758004622F93@PDC-MAIL3.ubisoft.org> References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> <487CD564.5020008@hughes.net> <8AEDA5E3386EA742B8C24C95FF0C758004622F93@PDC-MAIL3.ubisoft.org> Message-ID: Andreas Tawn wrote: > I think a better explanation is that in your original function, x only > existed while the for loop was running. As soon as execution hit the > break statement, x ceased to exist. Wrong. For loop variables continue after the loop exits. This is intentional. Mensanator gave the correct explanation (loop never enters for nbr==1). From bruno.42.desthuilliers at websiteburo.invalid Fri Jul 4 08:29:56 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 04 Jul 2008 14:29:56 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> Message-ID: <486e17b2$0$12609$426a74cc@news.free.fr> Henning_Thornblad a ?crit : > What can be the cause of the large difference between re.search and > grep? > > This script takes about 5 min to run on my computer: > #!/usr/bin/env python > import re > > row="" > for a in range(156000): > row+="a" > print re.search('[^ "=]*/',row) > > > While doing a simple grep: > grep '[^ "=]*/' input (input contains 156.000 a in > one row) > doesn't even take a second. > > Is this a bug in python? Please re-read carefully your python code. Don't you think there's a subtle difference between reading a file and buildin 156000 string objects ? From scottpig1 at comcast.net Tue Jul 29 21:38:01 2008 From: scottpig1 at comcast.net (pigmartian) Date: Tue, 29 Jul 2008 21:38:01 -0400 Subject: static variables in Python? In-Reply-To: <115a132d-7edd-4b07-ba4f-7855577992d1@x41g2000hsb.googlegroups.com> References: <115a132d-7edd-4b07-ba4f-7855577992d1@x41g2000hsb.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > kj: >> OK, I guess that in Python the only way to do what I want to do >> is with objects... > > There are other ways, like assigning the value out of the function, > because Python functions too are objects: > ... > But I suggest you to use a class in this situation, it's often the way > that will keep your code more bug-free, and more readable by near- > casual readers too. Python philosophy asks you to write readable code > instead of clever code when possible, this is a difference from Perl, > I presume. > > Bye, > bearophile Here's a solution using decorators, I like it, but I'm biased: def staticAttrs(**kwds): """ Adds attributes to a function, akin to c-style "static" variables """ def _decorator(fcn): for k in kwds: setattr(fcn, k, kwds[k]) return fcn return _decorator @staticAttrs(n=0) def rememberCalls(): """ >>> rememberCalls() 0 >>> rememberCalls() 1 >>> rememberCalls() 2 """ print rememberCalls.n rememberCalls.n += 1 ~Scott From motoom at xs4all.nl Thu Jul 10 20:26:42 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Fri, 11 Jul 2008 02:26:42 +0200 Subject: Can anyone suggest a date peocedure... In-Reply-To: References: Message-ID: <3B32695E-249A-4D4A-B69D-F1A0E5A85474@xs4all.nl> Ron wrote: > Now all I need to know is how to > plug the date into the datetime object from a string. You could use simple string manipulation: >>> import datetime >>> a="20081031" >>> d=datetime.date(int(a[0:4]),int(a[4:6]),int(a[6:8])) >>> d datetime.date(2008, 10, 31) >>> print d 2008-10-31 Greetings, From robert.rawlins at thinkbluemedia.co.uk Sat Jul 19 05:43:54 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Sat, 19 Jul 2008 10:43:54 +0100 Subject: __del__ methods In-Reply-To: References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> Message-ID: <010101c8e983$f785ae60$e6910b20$@rawlins@thinkbluemedia.co.uk> > Yes. > > "Objects that have __del__() methods and are part of a reference cycle > cause the entire reference cycle to be uncollectable, including > objects not necessarily in the cycle but reachable only from it. > Python doesn't collect such cycles automatically because, in general, > it isn't possible for Python to guess a safe order in which to run the > __del__() methods." > > The uncollectable objects are stored in gc.garbage and will not be > freed until their reference cycles are broken and they are removed > from that list. Ok, guys, I've just recently (in the past week) started using the __del__ method to log class instance destruction so I can keep a track of when objects are created and destroyed, in order to help me trace and fix memory leaks. Are you saying that on the adverse side to this, __del__ may in fact be the CAUSE of a memory leak within my application? If this is the case and __del__ creates such a vulnerability within the application, and apparently isn't all that reliable anyway, why is it still part of the python platform? Cheers, Robert From sjmachin at lexicon.net Sun Jul 20 20:43:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 Jul 2008 17:43:46 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <41d4aa44-253b-42f6-8c02-4eec4eaf6647@w39g2000prb.googlegroups.com> On Jul 21, 8:50 am, giveitawhril2... at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Why do that, when gcc has a code generator for just about every MPU chip out there? > Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# A bit of a non sequitur .... and C# is available on how many different MPU chips? > and Python is > akin to Visual Basic > or something: a specialty language > ....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. ? > > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! Nobody wants to use C any more? > So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. It should be sublimely irrelevant to most people learning LanguageX what language LanguageX is written in. Some other implementations of Python: PyPy (written in Python), Jython (written in Java) and IronPython (written in C#). From Graham.Dumpleton at gmail.com Wed Jul 23 08:50:25 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Wed, 23 Jul 2008 05:50:25 -0700 (PDT) Subject: Python Embedding Thread References: <0d9f5285-8cf8-445b-a467-e123f87a15cf@c58g2000hsc.googlegroups.com> <87bf413d-eb98-47c0-8466-237c45fd1a0e@e53g2000hsa.googlegroups.com> <5081c3df-cb66-443b-ac71-be9661ae057d@27g2000hsf.googlegroups.com> Message-ID: On Jul 23, 12:15?pm, "Jaimy Azle" wrote: > wrote: > > I fixed the code. This code snippet runs in a seperate thread: > > > PyObject *dict=NULL; > > PyGILState_STATE state = PyGILState_Ensure(); > > dict = CreateMyGlobalDictionary(); > > > PyRun_String(, Py_file_input, dict, dict); > > > ReleaseGlobalDictionary(dict); > > > But it still does not work... :-/ > > Have you initialize interpreter with PyEval_InitThreads? look athttp://www.python.org/doc/1.5.2/api/threads.htmlfor more information. > > Oh, btw... I did use python in a bit different scenario than you've > described. Since you attempt to run different script per-host thread, you > might need python multiple interpreter support, I suggest you take a lookmod_pythonimplementation. Please don't look at mod_python. Current versions of mod_python don't use Python simplified GIL APIs correctly. http://issues.apache.org/jira/browse/MODPYTHON-217 Look at mod_wsgi instead, it is closer to the mark, although still has some not quite cruft in there to workaround mistakes in mod_python for case where mod_python and mod_wsgi are being loaded together. :-( Graham From fredrik at pythonware.com Wed Jul 16 16:24:22 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 22:24:22 +0200 Subject: For_loops hurt my brain. In-Reply-To: <4874c21f-befa-4e9f-a99d-486cc9c9b5b8@d77g2000hsb.googlegroups.com> References: <4874c21f-befa-4e9f-a99d-486cc9c9b5b8@d77g2000hsb.googlegroups.com> Message-ID: bsagert at gmail.com wrote: > This script uses a simple for loop to zip some files. However I am > repeating code that cries out for a nested loop. Cries out for a *function*, I'd say. > My two lists of files_to_be_zipped (spare and seekfacts) are of > uneven length so I can't seem to decipher the "for_logic". > I would appreciate any help. > import zipfile > import os > spare = [ > 'c:/spare/huge.fm3', > 'c:/spare/huge.wk3' > ] > seekfacts = [ > 'c:/seekfacts/bookmark.html', > 'c:/seekfacts/index.htm', > 'c:/seekfacts/seek.css', > 'c:/seekfacts/seek.js' > ] def zipit(outfile, file_list): zFile = zipfile.ZipFile(zips[0], 'w') for file in file_list: zFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) zFile.close() zipit("c:/spare.zip", spare) zipit("c:/seekfacts.zip", seekfacts) From drakonik at gmail.com Sun Jul 13 15:30:14 2008 From: drakonik at gmail.com (Nick Dumas) Date: Sun, 13 Jul 2008 15:30:14 -0400 Subject: Newbie Threading Question In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I'm not an expert on Python threading, so don't take my word as low, however, I believe that there's no need for a list of systems which support it because the Python virtual machine handles it. Thus, any system which supports Python (or at least Python versions with threading) will support Python threading. Again, I don't know a lot about this, but it would make sense. Sparky wrote: > It seems strange, but I can't find a list of operating systems which > support / don't support threading in Python. Can anyone point me in > the right direction? > > Thanks, > Sam -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkh6V8YACgkQLMI5fndAv9hVKgCePbrN4nwbsdZXNfIcnm3cXac5 5kUAnR0OeNB0gjsksRD2W5gcZ8c0pby0 =p3U+ -----END PGP SIGNATURE----- From dullrich at sprynet.com Fri Jul 11 12:20:53 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 11 Jul 2008 11:20:53 -0500 Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: In article , ssecorp wrote: > >>> def mod(x,y): > return x.append(y) > > >>> mod([1,2],3) > >>> k=[1,2,3] > >>> k > [1, 2, 3] > >>> l = mod(k,4) > >>> l > >>> k > [1, 2, 3, 4] > >>> l > >>> k==l > False > >>> mod(k,5) > >>> k > [1, 2, 3, 4, 5] > >>> mod(l,4) > > Traceback (most recent call last): > File "", line 1, in > mod(l,4) > File "", line 2, in mod > return x.append(y) > AttributeError: 'NoneType' object has no attribute 'append' > >>> l > >>> l=k > >>> l > [1, 2, 3, 4, 5] > >>> i=mod(k,1) > >>> i > >>> > > same stuff but i dont find this intuitive. You need to read the docs. AList.append(x) does _not_ return AList with x appended. In fact it returns None, because it wants to be a "procedure" that doesn't return anything at all, but there is no such thing in Python; functions and methods that do not explicitly contain a "return" statement return None. So when you say "return x.append(a)" you're saying "return None", which explains the rest of it. You noticed that the second line of > >>> l = mod(k,4) > >>> l didn't print anything? That's because the first line set l to None. If you'd typed "print l" instead of just "l" you would have seen >>> l = mod(k,4) >>> l >>> None -- David C. Ullrich From robert.rawlins at thinkbluemedia.co.uk Sun Jul 20 06:56:58 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Sun, 20 Jul 2008 11:56:58 +0100 Subject: __del__ methods In-Reply-To: <87prp8x23x.fsf@benfinney.id.au> References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> <87hcalxvx0.fsf@benfinney.id.au> <87prp8x23x.fsf@benfinney.id.au> Message-ID: <007e01c8ea57$57225020$0566f060$@rawlins@thinkbluemedia.co.uk> > Time to fix that, then, with some documentation > , and by working through the Python > tutorial . Thanks Ben, I'll be sure to read through these. I also read through this http://www.geocities.com/foetsch/python/new_style_classes.htm earlier this morning which was also a nice little resource. Just about all of it makes sense at the moment, apart from the new constructor types which are constructors at a class level opposed to at instance level. I found this a little confusing but who knows. Presumably this is where you would deal with setting things which exist in every instance of a class, and properties that can vary from instance to instance go into the standard __init_(), have I got that right? Cheers Ben, Robert From gagsl-py2 at yahoo.com.ar Fri Jul 11 05:45:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Jul 2008 06:45:45 -0300 Subject: Trying to learn References: <8763rcrejw.fsf@benfinney.id.au> Message-ID: En Fri, 11 Jul 2008 05:49:23 -0300, Ben Finney escribi?: > luster123 writes: > >> Can someone please teach me the basics of Python and Pygame? > > Yes, you can do it. > > > > Also you can find other resources in the Python wiki: -- Gabriel Genellina From ldo at geek-central.gen.new_zealand Mon Jul 28 00:02:02 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 28 Jul 2008 16:02:02 +1200 Subject: How to find processes from Python References: <9f04931c-867b-4ff3-820c-3f8d0bfd2618@e53g2000hsa.googlegroups.com> Message-ID: In message <9f04931c-867b-4ff3-820c-3f8d0bfd2618 at e53g2000hsa.googlegroups.com>, Johny wrote: > Is there a way how to find out running processes?E.g. how many > Appache's processes are running? Under Linux, every process has a procfs directory /proc/, where is the process ID. In here you will find all kinds of interesting information about the process command line, what files it has open, its environment, its memory usage etc. From ldo at geek-central.gen.new_zealand Mon Jul 21 05:32:04 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 21 Jul 2008 21:32:04 +1200 Subject: db question References: Message-ID: In message , Dennis Lee Bieber wrote: > On Sun, 20 Jul 2008 18:43:03 -0700, "bruce" > declaimed the following in comp.lang.python: >> >> mysql cmd - select * from foo where dog like "%small%"; >> >> sql ="""select * from foo where dog like "%%%s%%" """ >> c.execute(sql, (var,)) > > The execute statement is responsible quoting your literals, so the > final statement you end up submitting looks like: > > select * from foo where dog like ""%"xxx"%"" > > or some variant thereof. > > Anything parameterized with %s must be a complete term! > > Try: > > sql = "select * from foo where dog like %s" > c.execute(sql, ("%" + var + "%",) ) > > IOW: you need to massage the variable search term to include the > wildcard % FIRST, then let MySQLdb substitute it (with surrounding > quotes and escapes) into the SQL. More general, less pitfall-prone solution: select * from foo where dog like %s" % SQLString("%" + EscapeSQLWild("small") + "%") where SQLString and EscapeSQLWild are defined as in . From ivan at datasyncorp.com Wed Jul 16 14:45:38 2008 From: ivan at datasyncorp.com (Ivan Ven Osdel) Date: Wed, 16 Jul 2008 13:45:38 -0500 (CDT) Subject: Framework recommendations for web service? In-Reply-To: <1561508290.1827571216233656023.JavaMail.root@saturn.datasyncintra.net> Message-ID: <2002101011.1828051216233938686.JavaMail.root@saturn.datasyncintra.net> >I don't think RESTful interfaces are built in but I know people have succesfully built RESTful apps on top of CherryPy. Also plans >for REST in CherryPy 3 look promising. Here is a post I ran across from one of the contributers. >"Hey there, >CherryPy 3 is currently under brainstorming before being first draft. There some feature we do want such as the ability to change >the URL dispatching at will depending on what is required for a given application. > >One dispatching rule I do want is the one based on HTTP verbs. So it might take a few months to get there but eventually it will be >a built-in :) > >- Sylvain" My apologies, it appears that post was from 2006! -- Ivan Ven Osdel Senior Software Engineer http://datasyncsuite.com From tjreedy at udel.edu Tue Jul 29 23:17:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 23:17:49 -0400 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> Message-ID: Carl Banks wrote: >> As I wrote in the second reply email I sent, check out my integer set >> recipe on ASPN (and to save you the search: http://code.activestate.com/recipes/466286/). > > Couple points: > > 1. Any container type that returns a length that isn't exactly the > number of elements in it is broken. > 2. The need for __nonzero__ in this case depends on a limitation in > the language. > 3. On the other hand, I will concede that sometimes calculating len is > a lot more expensive than determining emptiness, and at a basic level > it's important to avoid these costs. You have found a practical use > case for __nonzero__. I thought of another one: testing whether an iterator is 'empty' (will raise StopIteration on the next next() (3.0) call) or not. As virtual collections, iterators generally have neither __len__ or __bool__. But __bool__ (but only __bool__) can be added to any iterator by wrapping it with something like the following 3.0 code (not tested): class look_ahead_it(): def __init__(self, iterable): self.it = iter(iterable) self.fill_next() def __iter__(self): return self def __next__(self): tem = self.next if tem is self.empty: raise StopIteration else: self.fill_next() return tem empty = object() def fill_next(self) try: self.next = next(self.it) except StopIteration: self.next = self.empty def __bool__(self): return self.next is not self.empty From nagle at animats.com Fri Jul 25 14:24:13 2008 From: nagle at animats.com (John Nagle) Date: Fri, 25 Jul 2008 11:24:13 -0700 Subject: interpreter vs. compiled In-Reply-To: References: <5d2d76ac-0e0d-497c-8005-51937cd643fe@m36g2000hse.googlegroups.com> <40bde101-8077-4145-9f3c-7a4299c8da05@t54g2000hsg.googlegroups.com> <29f0f094-b67b-4ebb-a98e-f161ea068ddf@d45g2000hsc.googlegroups.com> <4f75fabc-c56f-4a3a-8005-969bc921ddec@25g2000hsx.googlegroups.com> Message-ID: <488a15ed$0$17181$742ec2ed@news.sonic.net> Tim Roberts wrote: > And I'm saying you are wrong. There is NOTHING inherent in Python that > dictates that it be either compiled or interpreted. That is simply an > implementation decision. The CPython implementation happens to interpret. > The IronPython implementation compiles the intermediate language to native > machine language. Well, actually there are some Python language features which make static compilation to machine code difficult. PyPy and Shed Skin have to impose some restrictions on dynamism to make efficient compilation feasible. The big problem is "hidden dynamism", where the code looks static, but at run time, some external piece of code replaces a function or adds an unexpected attribute to what looked like a simple object or function in the defining module. In CPython, everything is a general object internally, and all the names are resolved over and over again at run time by dictionary lookup. This is simple, but there's a sizable speed penalty. John Nagle From deets at nospam.web.de Fri Jul 25 10:44:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 25 Jul 2008 16:44:06 +0200 Subject: Calling external program from within python In-Reply-To: References: <6eu684F91muhU1@mid.uni-berlin.de> Message-ID: <6eu75mF92mqcU1@mid.uni-berlin.de> Grant Edwards schrieb: > On 2008-07-25, Diez B. Roggisch wrote: > >>> There are probably many ways to do this. I would recommend >>> checking out the subprocess module and see if it does what you >>> want. >> This will only work if the program can be fully controlled by >> commandline arguments. > > Why do you say that? You can interact with programs via > stdin/stdout using the subprocess module. Because usually if a program *prompts* the user to enter input (and that was what I read from the OP's post), one has to deal with pseudo terminals, not with stdin/out. >> If interaction is required, the OP might consider using >> pexpect. > > Pexpect is a good option, but it's just an automation layer on > top of the same facilities that subprocess provides. AFAIK it's more than that. I'm not an expert on pseudo terminals, but AFAIK setting using module pty isn't possible using subprocess. Diez From ndbecker2 at gmail.com Fri Jul 11 11:29:55 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 11 Jul 2008 11:29:55 -0400 Subject: decorator to prevent adding attributes to class? Message-ID: After spending the morning debugging where I had misspelled the name of an attribute (thus adding a new attr instead of updating an existing one), I would like a way to decorate a class so that attributes cannot be (easily) added. I guess class decorators are not available yet (pep 3129), but probably inheritance can be used. Can anyone suggest an implementation? From alan.franzoni.blahblah at example.com.invalid Mon Jul 28 12:01:41 2008 From: alan.franzoni.blahblah at example.com.invalid (Alan Franzoni) Date: Mon, 28 Jul 2008 16:01:41 GMT Subject: write unsigned integer 32 bits to socket References: <9_KdnfSDZ9xHIRDVnZ2dnUVZ_gCdnZ2d@pdx.net> Message-ID: Scott David Daniels was kind enough to say: > Alan Franzoni wrote: > Please don't pass this misinformation along. > > In the struct module document, see the section on the initial character: > Character Byte order Size and alignment > @ native native > = native standard > < little-endian standard > > big-endian standard > ! network (= big-endian) standard Sure, that's is one way to do it... but I was answering Micheal Torrie, who said: > htonl() call, and then when pulling it off the wire on the other end >you'd use ntohl(). If you don't then you will have problems when the htonl() and ntohl() are available in Python in the socket module, so: 1) i was just pointing the OP to the right place where to find such functions 2) they work just the same way, hence I can't see why the "struct" way should be the preferred one while the "socket" way should be misinformation :P Bye! -- Alan Franzoni - Remove .xyz from my email in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From execrable at gmail.com Wed Jul 23 23:02:03 2008 From: execrable at gmail.com (B) Date: Wed, 23 Jul 2008 20:02:03 -0700 Subject: Recursion Performance Question Message-ID: Hey I found some (VERY) old C++ code of mine that recursively built a tree of the desktop window handles (on windows) using: (they are stored in an STL vector) void FWL(HWND hwnd, int nFlag) // Recursive Function { hwnd = GetWindow(hwnd, nFlag); if(hwnd == NULL) return; AddWnd(hwnd); nLevel++; FWL(hwnd, GW_CHILD); nLevel--; FWL(hwnd, GW_HWNDNEXT); return; } int FillWindowList(bool bReset) // Build Window List { WLI wli; if(bReset) ResetWindowList(); nLevel = 0; FWL(ui.hWnd, GW_HWNDFIRST); return nCount; } Now the interface on this program is really ugly (i hate UI coding), so I was thinking about re-writing it in python to use PyQt for an easy GUI. So far I have (they are stored in a 'tree' class): # pass in window handle and parent node def gwl(node, hwnd): if hwnd: yield node, hwnd for nd, wnd in Wnd.gwl(node.children[-1], GetWindow(hwnd, GW_CHILD)): yield nd, wnd for nd, wnd in Wnd.gwl(node, GetWindow(hwnd, GW_HWNDNEXT)): yield nd, wnd def generateTree(self): t = time.clock() if self is not None: self.children = [] for nd, wnd in Wnd.gwl(self, GetWindow(self.hwnd, GW_CHILD)): nd.addChild(wnd) Now it works, but it runs quite slow (compared to the c++ app). I changed gwl from strait recursion to use a generator and that helped, but it still takes 0.5-1.0 seconds to populate the tree. What I'm wondering is am I doing it in a really inefficient way, or is it just python? The second problem is reseting the list. In C++ I would use the STL Vector's clear() method. In python, I can't think of a good way to free all the nodes, so there is a large memory leak. I can post more of the code if it's unclear, I just didn't want to write a really long post. From iainking at gmail.com Thu Jul 31 05:06:56 2008 From: iainking at gmail.com (Iain King) Date: Thu, 31 Jul 2008 02:06:56 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <3a699735-f376-4d62-9e6d-bfd0415df709@z11g2000prl.googlegroups.com> <05954b0d-4c35-4a99-9df3-900dcd19b51f@k36g2000pri.googlegroups.com> <19e04b2c-0c3f-405b-8607-1f5a429c9009@v26g2000prm.googlegroups.com> <4e0f0c85-b1de-46b4-99bc-c41be9b39c25@a6g2000prm.googlegroups.com> <024f39e3-4a24-489f-812f-38977e468075@o40g2000prn.googlegroups.com> Message-ID: On Jul 31, 7:08 am, "Russ P." wrote: > On Jul 30, 10:43 pm, Erik Max Francis wrote: > > > > > Russ P. wrote: > > > On Jul 30, 9:27 pm, Erik Max Francis wrote: > > >> You're sure going on about a distinction without a difference for a guy > > >> who childishly likes to call other people names. A reasonable person > > >> would have long ago moved on instead of blaming others for not > > >> immediately intuiting your thoughts, rather than straightforwardly > > >> reading your words. Which, by the way, includes at least three people > > >> other than myself. > > > >> But I'll bet the mindless namecalling is really working out for you. > > >> Go, team, go! > > > > You earned the "childish name calling" by acting like a child -- with > > > your petty little game of trying to show that I don't understand a > > > basic concept in Python. As I said, your initial misunderstanding, > > > while silly, was at least forgivable. But your insistence on repeating > > > it time after time is not. It is truly pathetic. > > > Sis, boom, rah rah rah! > > > You're kind of skipping over the point where three other people had the > > same misunderstanding about your original statement and correction, so > > Another whopper, but who's counting? > > > maybe the reader is not the problem but rather the writer, but hey, > > don't let that get in the way of a good public shitfit. > > > You're winning! > > And you're a professional of some sort? Man, I can't even imagine > working in an environment with people like you. I guess I'm pretty > lucky to work with real professionals who don't play petty little > games like the one you played here -- and are still playing. Go ahead, > have the last word, loser -- then get lost. You understand this is usenet, right? Where we can all read the entire thread? So trying to spin the situation just doesn't work? Just checking... Iain From dickinsm at gmail.com Sat Jul 5 11:13:36 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 5 Jul 2008 08:13:36 -0700 (PDT) Subject: re.search much slower then grep on some regular expressions References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <460ed57e-ada1-481c-afb9-456c95574590@56g2000hsm.googlegroups.com> Message-ID: <9cae59d9-ead4-45bc-a980-2ac2e1616f9b@p25g2000hsf.googlegroups.com> On Jul 5, 1:54?pm, Carl Banks wrote: > I don't think you've illustrated that at all. ?What you've illustrated > is that one implementation of regexp optimizes something that another > doesn't. ?It might be due to differences in complexity; it might not. > (Maybe there's something about PCREs that precludes the optimization > that the default grep uses, but I'd be inclined to think not.) It seems like an appropriate moment to point out *this* paper: http://swtch.com/~rsc/regexp/regexp1.html Apparently, grep and Tcl convert a regex to a finite state machine. Matching is then *very* fast: essentially linear time in the length of the string being matched, even in the worst case. Though it is possible for the size of the finite state machine to grow exponentially with the size of the regex. But not all PCREs can be converted to a finite state machine, so Perl, Python, etc. use a backtracking approach, which has exponential running time in the worst case. In particular, it's not possible to use a finite state machine to represent a regular expression that contains backreferences. Part of the problem is a lack of agreement on what 'regular expression' means. Strictly speaking, PCREs aren't regular expressions at all, for some values of the term 'regular expression'. See http://en.wikipedia.org/wiki/Regular_expression Mark From mensanator at aol.com Thu Jul 3 19:51:52 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 3 Jul 2008 16:51:52 -0700 (PDT) Subject: Generating list of possible configurations References: <486c7c1f$0$10446$426a74cc@news.free.fr> <7db52b03-7a8a-40c4-b3cb-f6dccd273b90@59g2000hsb.googlegroups.com> Message-ID: <45ce2acc-e4b5-4762-8daa-b67a78b02411@w7g2000hsa.googlegroups.com> On Jul 3, 6:24?pm, George Sakkis wrote: > On Jul 3, 5:49?pm, Mensanator wrote: > > > On Jul 3, 2:52?pm, Terry Reedy wrote: > > > > Worthless to you, worthwhile to me. ? > > > The OP's opinion is the only one that matters. > > I bet the OP doesn't know (or care) what gmpy is. But he'll care if he tries to use something specific to 2.6 and it fails and he doesn't know why. > > > What do you suppose > > is the percentage of posts on this newsgroup by those using 3.0? > > Taking into account 2.6 too (we're not talking about only 3.0 here), > probably not much less than those who even know what is gmpy, let > alone dismiss a beta Python release because their obscure pet module > is not available yet. That was just an example. When you consider ALL the pet modules like PIL, Numpy, Win32, etc., that's a lot, isn't it. > You will probably sound less negative if you refrain from projecting > your own very specialized needs to those of the average pythonista. Funny how you don't complain when Mr. Reedy projects HIS specialized needs to the average pythonista. I was just trying to be helpful (I admit I often sound negative when I'm not trying to be). > > George From cwitts at gmail.com Fri Jul 18 04:08:25 2008 From: cwitts at gmail.com (Chris) Date: Fri, 18 Jul 2008 01:08:25 -0700 (PDT) Subject: Python Behind a Squid Corporate Proxy on Windows References: <7b541a3b-846f-496a-aee1-d5719217e011@m45g2000hsb.googlegroups.com> <821d7616-3faa-4dae-a988-18caf4f8598a@8g2000hse.googlegroups.com> Message-ID: <84c473ed-6993-481a-b789-35851242895b@f1g2000prb.googlegroups.com> On Jul 17, 6:40?pm, Larry Hale wrote: > Err, the line above should be: > > proxy_handler = urllib2.ProxyHandler( { "http": "http:// > myusername:passw... at webfilter.xyz.local:3128" } ) > > (Sorry! ?:) some old code I wrote to download public domain info for our company, also through a squid proxy and this still works for me import urllib2, urllib proxy = urllib2.ProxyHandler({'http': 'http:// username:password at proxy_url:proxy_port'}) auth = urllib2.HTTPBasicAuthHandler() opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) urllib2.install_opener(opener) conn = urllib2.urlopen('http://python.org') return_str = conn.read() fp = open('python.html','w').write(return_str) From tjreedy at udel.edu Wed Jul 16 19:56:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 Jul 2008 19:56:02 -0400 Subject: Custom 'Float' class. Am I right here? In-Reply-To: <552799.63120.qm@web33404.mail.mud.yahoo.com> References: <552799.63120.qm@web33404.mail.mud.yahoo.com> Message-ID: Prashant Saxena wrote: > import sys > > class Float(float): > """ > Custom float datatype with addtional attributes. > """ > > def __new__(self, > value=0.0, #default value > name='', # string > & nbsp; range=(0.0, 1.0) # tuple > ) > > try: > self.name = name > self.range = range > self.pos = (1, 1) > return float.__new__(self, value) > except: > print ('Invalid value : Float = %s %s' % (str(value), > sys.exc_info()[:2])) > > > def setpos(self, value): > self.pos = value > def getpos(self): > return self.pos*2.0 > p = property(getpos, setpos) > > myFloat = Float(0.23) > print myFloat.pos > > I am trying to create a custom 'float' datatype by subtyping default > 'float'. There are few things I would like to know here: > > 1. How to make 'name' & 'range' only readable attributes. A property with a working get and set that raises an exception. > 2. The property 'p' is not working as it has to. What's wrong here? Don't know. > 3. I would be heavily instancing this class, and I won't be creating any > new attribute on instance. Is there any way to optimize? __slots__? I believe this is what slots is for. From samwyse at gmail.com Thu Jul 10 14:46:31 2008 From: samwyse at gmail.com (samwyse) Date: Thu, 10 Jul 2008 11:46:31 -0700 (PDT) Subject: Loading just in time References: Message-ID: On Jul 10, 9:45?am, "D'Arcy J.M. Cain" wrote: > I am trying to create a utility module that only loads functions when > they are first called rather than loading everything. ?I have a bunch > of files in my utility directory with individual methods and for each I > have lines like this in __init__.py: > > def calc_tax(*arg, **name): > ? ? from calc_tax import calc_tax as _func_ > ? ? calc_tax = _func_ > ? ? return _func_(*arg, **name) This doesn't do what you think. The line "calc_tax = _func_" is probably modifying a local variable that is then thrown away. I've got a slightly different (simpler) version to illustrate: === main.py === def calc_tax(*arg, **name): from calc_tax import calc_tax as _func_ #global calc_tax calc_tax = _func_ print '_func_ is', repr(_func_) print 'calc_tax is', repr(calc_tax) return _func_(*arg, **name) print 'before: calc_tax is', repr(calc_tax) result = calc_tax() print 'after: calc_tax is', repr(calc_tax) === calc_tax.py === def calc_tax(*arg, **name): return 42 === end of files === Running main.py gives this: before: calc_tax is _func_ is calc_tax is after: calc_tax is Note that the value of calc_test is the same in the first and last lines. If you uncomment the line "#global calc_tax" and run it again, you get this: before: calc_tax is _func_ is calc_tax is after: calc_tax is Interestingly, neither version gives me a TypeError, no matter how many times I call calc_tax. (BTW, you might want to look up Memoization; it's very similar to what you want to do, and might give you a way to more efficiently code things.) From arkanes at gmail.com Thu Jul 31 13:39:50 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 31 Jul 2008 12:39:50 -0500 Subject: Function References In-Reply-To: References: <545ac201-95c7-45b6-b076-00ea153a3c8b@m36g2000hse.googlegroups.com> <6fdut5Fb0nvuU2@mid.uni-berlin.de> <6fdv9tFb0nvuU3@mid.uni-berlin.de> <3e604620-2c0c-430c-811a-3f0d553df08f@c65g2000hsa.googlegroups.com> <6fe0scFaus40U1@mid.uni-berlin.de> <6bc8bc07-eab0-4303-b8a4-c9470f96038d@c65g2000hsa.googlegroups.com> <6fe1n2Faus40U3@mid.uni-berlin.de> Message-ID: <4866bea60807311039h7f8d62bcv31b8299bb100a264@mail.gmail.com> On Thu, Jul 31, 2008 at 10:27 AM, squishywaffle at gmail.com wrote: > On Jul 31, 10:47 am, "Diez B. Roggisch" wrote: >> I take the freedom to do so as I see fit - this is usenet... > > Fine, then keep beating a dead horse by replying to this thread with > things that do nobody any good. It seems like there are a lot better > way to waste time, though. > > The Python/C API can get me back further without reliance on third- > party libraries than ctypes. It also isn't subject to the quirks that > ctypes is on platforms other than Windows (the target application runs > on Windows, Mac, and eventually Linux once the original distributor > has drivers for the device). I'm not even sure ctypes could load the > lib/driver the distributor packaged. > Ctypes works fine on many platforms. Since you didn't even know about ctypes until you were told about it, don't you think it's a little premature to be speculating about problems you haven't actually experienced? > So really, I appreciate the option in ctypes, it's good stuff. But > it's not for this project. > It's actually perfectly suited, but you're (I'm assuming) and adult and can make your own decisions... > Once again, the original question stands for anyone who has experience > with the Python/C API callbacks. > -- If you know how to write a callback in C, you know how to do it with Python/C. It's not real flexible if the callback API you're using doesn't include user data, and it looks like it doesn't. Ctypes can generate dynamic thunks and therefore will let you use any Python object as a callback. It's a lot more flexible and it's a lot easier to not write your own thunk generation in C. From HeinTest at web.de Thu Jul 10 10:55:00 2008 From: HeinTest at web.de (=?ISO-8859-1?Q?Hans_M=FCller?=) Date: Thu, 10 Jul 2008 16:55:00 +0200 Subject: Smal question Message-ID: <487622c4$0$11102$8e6e7893@newsreader.ewetel.de> Hello group, I have some scripts sharing some common functions. So what I'd like to have is a modern include. Of course python does not have (with good reasons) no include statement. But I'm too lazy to create a module which has to be installed into the interpreter for some functions I need to share in a project. Is there any idea to do this ? Thanks a lot Hans From sukkopera at gmail.com Mon Jul 14 05:41:23 2008 From: sukkopera at gmail.com (sukkopera at gmail.com) Date: Mon, 14 Jul 2008 02:41:23 -0700 (PDT) Subject: subprocess module References: <2e7f0504-cc1c-4cb6-b2d0-b67b004eca7d@x41g2000hsb.googlegroups.com> Message-ID: <88a36645-851d-4c72-9095-796dfe1d94c9@k30g2000hse.googlegroups.com> On 14 Lug, 10:34, Peter Otten <__pete... at web.de> wrote: > John Mechaniks wrote: > > from subprocess import call > > call(['ls', '-l']) > > > How do I get the result (not the exit status of the command) of "ls - > > l" into a variable? > > output = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE).stdout.read() > > Peter Correct, but I would rather use Python's os.listdir() and/or os.stat(). Executing a simple ls running a subprocess is overkill. From larry.bates at websafe.com` Sun Jul 13 10:26:02 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sun, 13 Jul 2008 09:26:02 -0500 Subject: About wmi In-Reply-To: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> References: <9efb5a93-3c48-4533-84fa-10167b60c2ec@y21g2000hsf.googlegroups.com> Message-ID: <0tudnQ5Vg-ThjefVnZ2dnUVZ_jednZ2d@comcast.com> patrol wrote: > I want to prevent some process from running. The code is in the > following. I encounter some unexpected troubles. > Probelm1: This program cannot terminate "scrcons.exe" and > "FNPLicensingService.exe",which are system processes. > Problem2:After a while, this program will abort by error > File "C:\Python25\lib\wmi.py", line 397, in __call__ > handle_com_error (error_info) > File "C:\Python25\lib\wmi.py", line 190, in handle_com_error raise > x_wmi, "\n".join (exception_string) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > 14: ordinal not in range(128) > > > ---------------------------------------------------- > code---------------------------------------------------------------------------------- > # -*- coding:utf-8 -*- > import pythoncom > import wmi > import threading > import time > from xml.dom.minidom import parse, parseString > > class Info (threading.Thread): > def __init__ (self): > threading.Thread.__init__ (self) > def run (self): > print 'In Another Thread...' > pythoncom.CoInitialize () > dom1 = parse('processTerminateList.xml') > config_element = dom1.getElementsByTagName("processTerminateList") > [0] > servers = config_element.getElementsByTagName("processName") > try: > c = wmi.WMI () > for process in c.Win32_Process (): > for server in servers: > if process.name == getText(server.childNodes): > process.Terminate() > print process.name > process_watcher = c.Win32_Process.watch_for("creation") > while True: > new_process = process_watcher() > name = new_process.Caption > print name > for server in servers: > if name == getText(server.childNodes): > new_process.Terminate() > finally: > pythoncom.CoUninitialize () > def getText(nodelist): > rc = "" > for node in nodelist: > if node.nodeType == node.TEXT_NODE: > rc = rc + node.data > return rc > > if __name__ == '__main__': > Info().start() > ------------------------------------------------------ > processTerminateList.xml----------------------------------------------------------------------- > > > scrcons.exe > TXPlatform.exe > mdm.exe > FNPLicensingService.exe > notepad.exe > uedit32.exe > You should probably post this to comp.python.windows. Tim Golden (author of WMI interface) monitors that list religously (thanks Tim). -Larry From info at egenix.com Mon Jul 21 09:25:40 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Mon, 21 Jul 2008 15:25:40 +0200 Subject: ANN: eGenix EuroPython 2008 Presentations & Videos Message-ID: <48848E54.70408@egenix.com> ________________________________________________________________________ eGenix EuroPython 2008 Presentations & Videos ________________________________________________________________________ We have uploaded our EuroPython 2008 presentations to our website. Learn the concepts behind the Python DB-API and how to design large-scale applications. This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/EuroPython-2008-Presentations.html ________________________________________________________________________ INTRODUCTION The EuroPython Conference is the one of the premier conferences for Python & Zope users and developers. This year it was being held from the 7th to 9th July in Vilnius, Lithuania. eGenix was one of the founding members of the EuroPython conference team and played a major role in organizing the first EuroPython conference in the year 2002. Since then we have attended every EuroPython conference to meet up face-to-face with the people from the Python & Zope communities and have given regular talks at these conferences. ________________________________________________________________________ TALKS AT EUROPYTHON 2008 We gave the following two talks at the conference. The presentations are available for viewing and download from our Presentations and Talks section: http://www.egenix.com/library/presentations/ As special feature, we have added talk videos in addition to providing the slide PDFs. You can view the talks online if you have the Adobe Flash Player 8 or later installed. * Using the Python Database API The Python Database API (DB-API) is a specification of a module interface that allows interfacing from Python to a relational database. The talk gives a high-level introduction to the concepts used in the Python DB-API and relational databases in general. Connection, cursors and transactions are discussed, and their use in Python database applications is explained. * Designing Large-Scale Applications in Python Python is widely and somewhat inaccurately referred to as a scripting language. While Python is an ideal platform for small scripting tasks, it does in fact cover all the concepts needed for large scale object oriented application development. However, complex applications bring different challenges. This talk draws on eGenix' many years experience with large scale application development using Python as central implementation language and provides a cookbook approach to many of the the problems you face when designing and organizing complex application frameworks. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 21 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From robert.kern at gmail.com Mon Jul 21 19:48:21 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 21 Jul 2008 18:48:21 -0500 Subject: scanf in python In-Reply-To: <4884be5e$0$19722$426a74cc@news.free.fr> References: <4884be5e$0$19722$426a74cc@news.free.fr> Message-ID: AMD wrote: > Hello, > > I often need to parse strings which contain a mix of characters, > integers and floats, the C-language scanf function is very practical for > this purpose. > I've been looking for such a feature and I have been quite surprised to > find that it has been discussed as far back as 2001 but never > implemented. The second Google hit is a pure Python implementation of scanf. http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From waldemar.rymarkiewicz at gmail.com Tue Jul 29 06:05:14 2008 From: waldemar.rymarkiewicz at gmail.com (waldek) Date: Tue, 29 Jul 2008 03:05:14 -0700 (PDT) Subject: ctypes and how to copy data passed to callback References: <2059b8a4-7651-4c3c-afbf-44caa8605c64@m3g2000hsc.googlegroups.com> <6f61s7Fa0pq9U1@mid.individual.net> Message-ID: On Jul 28, 4:03 pm, Thomas Heller wrote: > waldek schrieb: > > > > > Hi, > > > I'm trying to handle data passed to Py Callback which is called from > > C dll. Callback passes data to another thread using Queue module and > > there the data are printed out. > > > If data is printed out in a callback itself it's ok. If I put on > > queue and next get from queue in another thread script prints some > > trash. Looks like the data is released when callback returned. I tired > > to make d = copy.deepcopy(data), but it does not work - I got nothing. > > Any idea why it's happening ? > > > --------------------- main thread -------- > > def callback(data, size): > > myqueue.put((data, size)) > > > mydll = cdll.MyDLL > > cbproto = CFUNCTYPE(c_int, POINTER(c_char), c_int) > > mycallback = cbproto(callback) > > > mydll.RegisterCallback(mycallback) > > > ---------------------------------- thread listener > > ---------------------- > > > while True: > > data, size = myqueue.get() > > print "***", data[:size] > > > ------------------------------------------------------------------------------ > > I guess your code would work if you change it in this way: > > > def callback(data, size): > > myqueue.put(data[:size]) > > while True: > > data = myqueue.get() > > print "***", data > > Thomas Both solutions work fine. The secon is nicer :) Thanks From wuwei23 at gmail.com Wed Jul 30 00:32:30 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 29 Jul 2008 21:32:30 -0700 (PDT) Subject: Native Code vs. Python code for modules References: Message-ID: On Jul 30, 1:56?pm, koblas wrote: > Ruby has been getting pummeled for the last year or more on the > performance subject. ?They've been working hard at improving it. ?From > my arm chair perspective Python is sitting on it's laurels and not > taking this as seriously as it probably should. Well, the snarky response is most Python developers are too busy working on actual real world projects :) A more measured response would be that it's so easy to integrate Python with C that most developers would prefer to profile their own code and implement bottleneck code in C where appropriate. >?In general it's > possible to make many comments that swirl around religion and > approach, one of the things that I've noticed is that wile Python has > a much more disciplined developer community they're not using this for > the greater good. I guess it all depends on what you define by "greater good". If you mean "faster performance", then maybe not, although it definitely seems to be -one- aspect being addressed by the PyPy project, at least. For me, "greater good" == "makes my life as a developer easier", and from that definition I've nothing but admiration for the community as a whole. > This got me to think, why does python have "pickle" and "cPickle"? Because sometimes you want something to be fast, but other times you want a pure Python version that's easy to extend. > To that end why would somebody write big try catch blocks to see if > modules exist and if they exist alias their names. Because it's the established approach, they're run through once during importing, and it doesn't require modifying the language to achieve it. >?Wouldn't it be > better if there was a way that if I have an "interface compatible" > native (aka C) module that has better performance that there could be > a way that python would give it preference. Shouldn't that -always- be decided by the developer? I don't want to rely on magic behaviour based on what is installed in the runtime environment by an end user... > ? import random(version=1.2, lang=c) > or > ? import random(version=1.2, lang=py) I don't see the gain over sticking with an established convention, like pickle and cPickle. > ? import random ? ? # ?use the latest version in the "fastest" code (C > given preference) I personally have a preference for predictable behaviour over idealised optimisation. All of this, of course, is personal preference; please don't take me for a jihadi :) - alex23 From tjreedy at udel.edu Fri Jul 18 22:12:45 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Jul 2008 22:12:45 -0400 Subject: Change in Decimal repr in Python 2.6 In-Reply-To: References: Message-ID: Karen Tracey wrote: > I noticed when trying out Python's 2.6b2 release that the repr of > Decimal has changed since 2.5. On 2.5: > > Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import decimal > >>> decimal.Decimal(7) > Decimal("7") > >>> > > double quotes were used whereas on 2.6b2: > > Python 2.6b2 (r26b2:65082, Jul 18 2008, 13:36:54) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import decimal > >>> decimal.Decimal(7) > Decimal('7') > >>> > > single quotes are used. Searching around I see this was done in r60773 > with the log message: > > Fix decimal repr which should have used single quotes like other reprs. > > but I can't find any discussion other than that. > > My problem is this breaks a bunch of doctests that were written assuming > the prior repr. I can't just update the tests to assume the new single > quotes because they are for code that is supposed to run on everything > back to Python 2.3. > > So my question: > > Is this backwards-incompatible change really necessary and could it be > reconsidered? > If it's here to stay, is there some straightforward why that I am > unaware of to construct tests that use Decimal repr but will work > correctly on Python 2.3-2.6? > > Also, if this is not the right list for this question please let me know > where would be more appropriate and I will go there. If answers here do not satisfy, the pydev list would be the place to request that this change be put off until 3.0, when changes that break are more permissible. I do not remember any discussion of this issue. You can also post there via news.gmane.org/g.c.python.devel (the mail to news gateway). From wuwei23 at gmail.com Thu Jul 24 12:34:37 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 24 Jul 2008 09:34:37 -0700 (PDT) Subject: New to Python, familiar with Perl - Seeking info sources References: <18c8fc73-8ff9-4640-a020-de0be4b76ca4@z72g2000hsb.googlegroups.com> Message-ID: <8397b80b-80d5-4470-9605-1c0340cf1c53@r35g2000prm.googlegroups.com> On Jul 24, 11:53 pm, Brett Ritter wrote: > My question is: What are the best sources to learn best practices or > Are there any good sources to tell me > what Perl habits are good/bad in the Python paradigm? I've never used Perl myself, so I can't comment on the quality, but this document was recommended earlier this week: http://wiki.python.org/moin/PerlPhrasebook > What about > common packages that will change my life? (I do a lot of web work, > but also a lot of DB reporting) If you're not anti-ORM, I highly recommend checking out SQLAlchemy. It's not part of the standard lib, but it's an amazing tool: http://www.sqlalchemy.org/ > The (occasionally complete) Perl > Advent calendars have proven to be a good source to learn about > helpful modules that I might not otherwise stumble across. You might appreciate Doug Hellman's Python Module of the Week blog: http://www.doughellmann.com/projects/PyMOTW/ > (I've encountered Django, but I'm getting my fill of "frameworks" from > Java for the moment, so I'm looking for lightweight pieces at the > moment) The Web Services Gateway Interface (WSGI) was designed to promote the building of web applications using interchangeable middleware. It's definitely worth having an understanding of if you plan on developing web apps in Python: http://www.wsgi.org/wsgi/ If you're wanting to avoid the larger frameworks, check out CherryPy, it's a thing of beauty: http://www.cherrypy.org/ From hackingkk at gmail.com Mon Jul 21 01:58:40 2008 From: hackingkk at gmail.com (Krishnakant Mane) Date: Mon, 21 Jul 2008 11:28:40 +0530 Subject: Python Written in C? In-Reply-To: References: Message-ID: <8d3752f20807202258w2a4167e4hd40b56b12c0c74fc@mail.gmail.com> On 21/07/2008, giveitawhril2008 at gmail.com wrote: > I'm just learning about Python now and it sounds interesting. But I > just read (on the Wiki page) that mainstream Python was written in C. > That's what I was searching for: Python was written in what other > language? > Are you a PH.d researcher In the first place why do you want to make an issue of "what an x language is compiled in " and if that' is what you are researching in, then sorry to say you don't seam to have a mindset needed for researcher. > See, my concern was something like: OK, if Python is so hot, then, > hopefully someone is writing it in assembly language for each MPU chip > out there. Otherwise, if, say, they've written it in C#, then it looks > like the REAL, generally useful language to learn is C# and Python is > akin to Visual Basic or something: a specialty language....whereas > REAL WORLD programmers who want to be generally useful go and learn > C#. > First off all c# is absolute rubbish waist of time. if I need to learn it then I better lern java or pythonfor that matter. and by the way what is a "real programmer?" I never knew that there are robots who program vertually and a "real programmer ". What do you think I am a spam bot who is writing a "vertual program " every day? first give me your defination for real programmer. > So I was suspecting the Python compiler or interpreter is written in a > REAL language like C#. So, Wiki says it's written in C! It's almost as > if it were an intentional trick...write your own, new language in an > OLD, real world language that is passe. Compile it into executable > modules of course, so it is a real, working compiler, alright. But the > SOURCE is some old, high level language which no one wants to use > anymore! So now you've got a hot new language package and no one can > say "well, it is written in, the SOURCE code is written in, a REAL > language." No, it's not! The source is some outdated language and > compiler and no one is going to prefer learning THAT to learning your > hot new language! > what! no one is using c? I want to know what people use to write device drivers? I am such a fool I really never new that people use c# to create device drivers for hardware and for creating firmware. I admit my stupidity that I never knew that c# is "real programming language ". and what is "your programming language?"python is a free and open source programming language and does not belong to one person. > I'm not dissing Python, here. Just noting that, if it is written in C, > that throws a curve at me in trying to balance the value of learning > Python vs. some other major language. My request and strong recommendation to you is "don't learn python, because you don't deserve to. " I am not saying for dissing you, i know you are "real programmer ". but you seam to have a typical mindset which the rubbish microsoft has inculcated in many programmers, aa sorry "real programmers " line you. I don't think there is any point saying "vvb kind of " some thing is great and python is rubbish. every language has its value and vb is not a language in the first place. python is made with a view that it is usefull for all purposes and it has been so far successful and I don't really care why it is done in c as long as it does the work. happy hacking. Krishnakant. > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Fri Jul 25 10:51:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 16:51:42 +0200 Subject: Execution speed question In-Reply-To: <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> Message-ID: Iain King wrote: > I think (2)'s poor performance is being amplified by how python > handles lists and list deletions; the effect may be stymied in other > languages Delete is O(n) (or "O(n/2) on average", if you prefer), while append is amortized O(1). Unless I'm missing something, your example keeps going until it's flagged *all* nodes as "on", which, obviously, kills performance for the first version as the probability goes down. The OP's question was about a single pass (but he did mention "as the simulation progresses", so I guess it's fair to test a complete simulation.) Btw, if the nodes can be enumerated, I'd probably do something like: node_list = ... get list of nodes ... random.shuffle(node_list) start = 0 end = len(node_list) step = end / MAX while start < end: for i in xrange(start, start + step): ... switch on node_list[i] ... ... do whatever you want to do after a step ... # prepare for next simulation step start += step step = max((len(node_list) - start) / MAX, 1) which is near O(n) overall, and mostly constant wrt. the probability for each pass (where the probability is 1:MAX). Might need some tuning; tweak as necessary. From JordanNealBerg at gmail.com Thu Jul 10 04:47:54 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Thu, 10 Jul 2008 01:47:54 -0700 (PDT) Subject: error when porting C code to Python (bitwise manipulation) References: Message-ID: <48435624-6422-4d27-be4f-476b3b949ecb@c58g2000hsc.googlegroups.com> Well, I have figured out something that works: def findit(u): u += 0xe91aaa35 u1 = ~(0xffffffff - u) ^ u >> 16 u1 += ((u1 << 8) & 0xffffffff) u1 ^= (u1 & 0xffffffff) >> 4 b = (u1 >> 8) & 0x1ff a = (u1 + (u1 << 2) & 0xffffffff) >> 19 r = int(a) ^ hash_adjust[int(b)] return r I feel like this cannot possibly be the best way of doing this, but it does work!!!! haha If anyone would care to share a more elegant solution, that would be great :) From amheiserbush at yahoo.com.au Thu Jul 31 17:09:12 2008 From: amheiserbush at yahoo.com.au (James Calivar) Date: Thu, 31 Jul 2008 14:09:12 -0700 (PDT) Subject: Newbie having issues with threads Message-ID: <6f262ce0-0b03-4891-9d43-f83398500e5d@a2g2000prm.googlegroups.com> I'm a newbie trying to write a script that uses threads. I'm right now a little bit stuck in understanding why the code snippet I wrote doesn't seem to be entering the function defined in the start_new_thread() call. If I run it as is (the threaded version), the output is: UA_1 configuring... UA_1 halting.. But if I comment out the line w/ the thread and just call the function directly, everything seems to work OK: UA_1 configuring... UA_1 executing... UA_1 halting... Can anyone tell me why the thread doesn't seem to invoke the function "execute()"? I'm running Python 2.4.3. Here is my code: =========== import thread class Test(object): def __init__(self, instanceID): self.instanceID = instanceID def configure(self): print self.instanceID + " configuring..." def execute(self): print self.instanceID + " executing..." def halt(self): print self.instanceID + " halting..." if __name__ == "__main__": """usage: sipp_auto [options]""" ua1 = Test("UA_1") ua1.configure() #ua1.execute() thread.start_new_thread(ua1.execute, ()) ua1.halt() =========== Thanks, James From mal at egenix.com Fri Jul 18 11:48:19 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 18 Jul 2008 17:48:19 +0200 Subject: Converting from local -> UTC In-Reply-To: <_L2dnRlm9sNmkB3VnZ2dnUVZ_j2dnZ2d@earthlink.com> References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> <41d4ffc7-7fd5-4202-92ea-132c7d4f5cd4@s50g2000hsb.googlegroups.com> <_L2dnRlm9sNmkB3VnZ2dnUVZ_j2dnZ2d@earthlink.com> Message-ID: <4880BB43.4050209@egenix.com> On 2008-07-18 05:28, Dennis Lee Bieber wrote: > On Thu, 17 Jul 2008 20:26:11 -0300, "Gabriel Genellina" > declaimed the following in comp.lang.python: > > >> Note that I used %s everywhere (it's just a placeholder, not a format) and > > > > Unfortunately, in the case of MySQLdb... It is both -- maybe that > will change once MySQLdb gives up compatibility with MySQL 4.x by > incorporating usage of prepared statements in place of a Python % > interpolation. > > It has to be %s as the adapter first converts to string, escapes, > and quotes the arguments; regardless of native datatype they are strings > when put into the SQL statement... If you prefer a different parameter style, you could use mxODBC and the MySQL ODBC drivers. You'd then write: query = "INSERT INTO image VALUES(?, ?, ?, ?)" and avoid any confusion due to the parameter style looking a lot like the Python string formatting markers (for obvious reasons, since that's what the MySQLdb module uses internally). -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 18 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From ggpolo at gmail.com Sat Jul 12 17:52:56 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sat, 12 Jul 2008 18:52:56 -0300 Subject: Why is there no GUI-tools like this for Windows? In-Reply-To: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> References: <14020136-1e9e-4a4e-96f6-c7413b962e2b@56g2000hsm.googlegroups.com> Message-ID: On Sat, Jul 12, 2008 at 6:35 PM, maestro wrote: > http://www.youtube.com/watch?v=PXpwC1o5AcI > > I have done some GUI-programming for windows with Python but the > Tkinter interface sucked and while it is the only one I tried I got > the impression they are all the same. > > It's amazing how retarded a lot of the stuff programmers do is. > Watcing that video, that is how it should be. > > I can just do the layout with my mouse and then there is a program > that writes the code for me. There are several programs that allow you to that, there is one not really nice for tkinter, GUI Builder, there are glade and gazpacho for gtk, Qt Designer for qt, wxglade and xrc (and others) for wxwidgets. There are probably others for each of the toolkits I described on the previous sentence, but those are the most well known (or not known at all in case of GUI Builder for tkinter). > GUI-programming is hard for no reason. One good program then forever > easy... > > Is there not something like this for Python/Windows? Is the Linux one > only for ruby or for any language? All the examples I mentioned previously works both in Linux and Windows. Also, they tend to not be language dependent either, they tend to save the user interface description to some format like XML, which you can then use independently of language (as long as your language has a lib for reading its format and doing proper processing). > > Oh well im switching to Linux anyway and mostly write webapps but > still... > -- > http://mail.python.org/mailman/listinfo/python-list > Note: I didn't watch the video, if it presents something totally unrelated to my answer, my bad then. -- -- Guilherme H. Polo Goncalves From Graham.Dumpleton at gmail.com Wed Jul 23 09:18:27 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Wed, 23 Jul 2008 06:18:27 -0700 (PDT) Subject: Problem with Python Server Pages (PSP) References: <9766b993-03e6-4b75-92a2-06244c41e51c@a1g2000hsb.googlegroups.com> <8ce2ffdd-0fb3-4f5f-bde8-1598f9b231bc@i20g2000prf.googlegroups.com> Message-ID: <53b1f015-edc8-4225-aeab-1082e07c57c3@j33g2000pri.googlegroups.com> On Jul 22, 1:54?pm, barun.sah... at gmail.com wrote: > On Jul 22, 5:18?am, Graham Dumpleton > wrote: > > > > > On Jul 21, 9:42?pm, barun.sah... at gmail.com wrote: > > > > Hi, > > > > I am facing a very basic problem with PSP. I have installedmod_python > > > (in fedora Core 1), added the lines required for loading Python > > > modules and handling PSP pages. I have created a hello.psp page. But > > > when I try to view this hello.psp page, all Python code are getting > > > displayed. > > > > The said page is stored at /var/www/html/psp/hello.psp. I guess this > > > is some configuration problem with Apache, but not able to figure out > > > the exact problem. I have tried putting those configuration lines for > > > psp in both httpd.conf and python.conf files. But still it is not > > > working. > > > > The Python module (mod_python) is getting loaded. Because when I > > > telnet to my server, I can find that in the headers. > > > > These are the versions of the softwares: > > > Apache: 2.0.47 > > > Python: 2.2.3mod_python: 3.0.3 > > > > Thnaks for all your suggestions. > > > What is the Apache configuration snippet you are using to enable > >mod_pythonand PSP file handling? > > > Graham- Hide quoted text - > > > - Show quoted text - > > Hi Graham, > > The configuration used in httpd.conf file looks like: > > ? ? AddHandler .psp .psp_ > ? ? PythonHandler modules/python > ? ? PythonDebug On > Go read the documentation properly. http://www.modpython.org/live/current/doc-html/hand-psp.html What is PythonHandler set to? Graham From sconnoll at lowes.com Fri Jul 18 15:14:47 2008 From: sconnoll at lowes.com (sconnoll at lowes.com) Date: Fri, 18 Jul 2008 12:14:47 -0700 (PDT) Subject: bsddb - help needed with btflags values for Python Message-ID: import bsddb bsddb.btopen(file, flag='c', mode=438, btflags=0, cachesize=None, maxkeypage=None, minkeypage=None, pgsize=None, lorder=None) Can anyone help me with the values to use for btflags? I'd like to tell the database manager that I want to allow duplicate values. The ORACLE Berkeley documentation addresses C (not Python), so I can't find the approprate btflags values documented for Python anywhere. Help!!!!......and thanks in advance. Sean From jmcmonagle at velseis.com.au Wed Jul 2 04:33:25 2008 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Wed, 02 Jul 2008 18:33:25 +1000 Subject: Problem with a for loop and a list In-Reply-To: <18232528.post@talk.nabble.com> References: <18232298.post@talk.nabble.com> <18232528.post@talk.nabble.com> Message-ID: <486B3D55.4070109@velseis.com.au> Alexnb wrote: > well okay, so what can I do? > > > Firstly, stop top posting. Replies to a thread "flow" better if bottom posted. Secondly, it sounds like you want to build a list of the results from your entry.get() calls. Try this: self.wordList = [] def getWords(self): for entry in self.listBuffer: self.wordList.append(entry.get()) print self.wordList From alexnbryan at gmail.com Tue Jul 15 11:39:31 2008 From: alexnbryan at gmail.com (Alexnb) Date: Tue, 15 Jul 2008 08:39:31 -0700 (PDT) Subject: Testing for Internet Connection In-Reply-To: <87bq0z8lym.fsf@benfinney.id.au> References: <18460572.post@talk.nabble.com> <87bq0z8lym.fsf@benfinney.id.au> Message-ID: <18468350.post@talk.nabble.com> Ben Finney-2 wrote: > > Alexnb writes: > >> I am wondering, is there a simple way to test for Internet >> connection? If not, what is the hard way :p > > Refine the question: What do you mean by "internet"? It isn't a single > entity. > > Do you mean "some particular internet host responding on a particular > network port"? > > If you can define exactly what you mean by "internet connection", the > test for it becomes correspondingly easier. > > -- > \ ?Why should I care about posterity? What's posterity ever done | > `\ for me?? ?Groucho Marx | > _o__) | > Ben Finney > -- > http://mail.python.org/mailman/listinfo/python-list > Well, really I just need to figure out if I am able to connect to one site. That site is dictionary.com. -- View this message in context: http://www.nabble.com/Testing-for-Internet-Connection-tp18460572p18468350.html Sent from the Python - python-list mailing list archive at Nabble.com. From piet at cs.uu.nl Thu Jul 10 16:50:06 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 10 Jul 2008 22:50:06 +0200 Subject: Terminate a python script from linux shell / bash script References: Message-ID: >>>>> Gros Bedo (GB) wrote: >GB> Yes I've seen that each python script calls its own instance of >GB> Python. But how to know which is the good one in bash ? Is there a >GB> command that gets the parameters of process, so I could use grep to >GB> select the one containing the name of my script ? The ps command will usually give you a list of the running processes with their argument, but using that is suboptimal. I suppose you start the process in the background, like: python myscript &. When you start the python script in bash (or any other process for that matter) in the background you can get the process id (pid) with $! (immediately after starting the process). Later on you can use this to kill the process: python myscript myargs & savepid=$! later: kill $savepid That is much better than trying to grep through the ps output. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From tjreedy at udel.edu Tue Jul 15 16:48:16 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Jul 2008 16:48:16 -0400 Subject: Python internals In-Reply-To: <008ca729$0$20313$c3e8da3@news.astraweb.com> References: <008ca729$0$20313$c3e8da3@news.astraweb.com> Message-ID: Peter Anderson wrote: > Hi! I am slowly teaching myself Python. I was reading David Beazley's > excellent book "Python - Essential Reference"; in particular about > variables. Let me quote: > > "Python is a dynamically typed language in which names can represent > values of different types during the execution of a program. In fact the > names used in the program are really just labels for various quantities > and objects. The assignment operator simply creates an association > between a name and a value. This is different from C, for example, in > which a name (variable) represents a fixed size and location in memory..." > > As an old mainframe programmer, I understand the way C does things with > variable but this text got me wondering how Python handles this > "association" between variable name and value at the lower level. Is it > like a fifo list? No. Names are associated with (references to) objects in a namespace. The details are implementation specific. For CPython, the references are addresses stored in an array. If the set of names is dynamic, names are converted to indexes by hashing during execution and the array of references is expanded before it gets full. If the set of names is static, as is usual for the local namespace of functions, an optimization converts the names to indexes (in a constant length array) during compilation. (On function startup, slots corresponding to non-parameter local vars are, I expect, initialized to invalid reference values to detect 'use before assignment' bugs.) Terry Jan Reedy From phillip.oldham at gmail.com Wed Jul 16 12:43:45 2008 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Wed, 16 Jul 2008 09:43:45 -0700 (PDT) Subject: Framework recommendations for web service? Message-ID: We're looking at the next phase of development for our webapp, and the main focus will be to move the core from the app to a web service so other systems can use the data we've gathered (we're thinking along the lines of the XML API of Highrise from 37Signals). Its possible that we'll extend the service to allow access via vanilla XML, JSON, and YAML at some point, however we've decided to use Facebook's Thrift for connectivity initially to support as many techs as possible and also because our web interface for the app is written in PHP. As we're extracting the core we'll be translating it to Python to make use of the wealth of well-structured libraries and hopefully make the project shorter. However, we've hit a snag in choosing a framework around which to rebuild the service. It seems the more popular frameworks (django, turbogears) are all focused on providing web content. Since our core will be using thrift to communicate, we don't need templating, feeds, admin pages (django), or ajax (turbogears). What we *do* need is a lightweight, simple framework that will allow us to create a RESTful interface and throw code together fast. We'll probably go with SQLObject (unless we can extract the ORM from django - lazy evaluation would be very useful), and we're just looking for something fast and light to sit between that and the thrift interfaces we'll create. So, can anyone suggest a lightweight python framework which just does the essentials? From python at rcn.com Fri Jul 4 00:40:27 2008 From: python at rcn.com (Raymond Hettinger) Date: Thu, 3 Jul 2008 21:40:27 -0700 (PDT) Subject: Nested generator caveat References: Message-ID: <6cfa41bf-9eb8-414f-976d-f5bcd70d6f64@u12g2000prd.googlegroups.com> On Jul 3, 9:20?pm, "Dieter Maurer" wrote: > The apparent reason is that the free variables in > nested generator definitions are not bound (to a value) at invocation > time but only at access time. That's what it is supposed to do. Welcome to a dynamic language. Raymond From Graham.Dumpleton at gmail.com Fri Jul 18 09:17:00 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Fri, 18 Jul 2008 06:17:00 -0700 (PDT) Subject: https in pylons References: Message-ID: <75acf330-16d5-4130-8a2c-0dba39478cb7@u36g2000pro.googlegroups.com> On Jul 18, 9:50?pm, sni... at gmail.com wrote: > Hello, > > I have a question about framework pylons - how to run(in paster) > webpages over https? Is it possible, or not? If Paste server that is uses doesn't already support HTTPS, then run Pylons under Apache/mod_wsgi, or just run Pylons with Paste server behind Apache/mod_proxy. In other words, use Apache to handle the HTTPS side of things. Graham From deets at nospam.web.de Mon Jul 28 04:53:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 10:53:31 +0200 Subject: Callback Python procedure from Delphi DLL References: Message-ID: <6f5fqcF9vgcaU1@mid.uni-berlin.de> durumdara at gmail.com wrote: > Hi! > > I have a component, and a tool in Delphi. > I wanna call it from Python. > > I can implement all things I need into a Delphi generated DLL. > It is ok, I can use this DLL from Python, but the DLL procedure needs a > callback procedure to return the partially output, and needs a python > passed variable to check terminate/abort signal. > > For example: > procedure ProcessFiles(InputFiles : string; CallBackProc: > ????????????????????????); export; > begin > .... > CallBackProc(ProcessedFiles, Percentage, NeedToAbort); > if NeedToAbort then Exit; > .... > end; > > > def CallBackProc(ProcessedFiles, Percentage, NeedToAbort): > ... > > But I don't know, how to call back this procedure, and how to pass > variables. > > The other way is a ActiveX. > This time I don't load the DLL, I only construct the Delphi based Com > Object, and I start the process. > > But in this way I also don't know how to implement the callback, because > the main code uses callback events, and I need to use too... > > Thanks for every usable help! ctypes allows to create callbacks. See the module-docs. Diez From Scott.Daniels at Acm.Org Thu Jul 10 23:24:38 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 10 Jul 2008 20:24:38 -0700 Subject: Loading just in time In-Reply-To: References: Message-ID: <0PmdnTvMhPidTevVnZ2dnUVZ_uLinZ2d@pdx.net> D'Arcy J.M. Cain wrote: > I am trying to create a utility module that only loads functions when > they are first called rather than loading everything. I have a bunch > of files in my utility directory with individual methods and for each I > have lines like this in __init__.py: > > def calc_tax(*arg, **name): > from calc_tax import calc_tax as _func_ > calc_tax = _func_ > return _func_(*arg, **name) > ... Well, you may well be "mired in premature optimization," but you _could_ do the following (you'll need to evaluate whether it addresses your issues). def calc_tax(*arg, **kwargs): from calc_tax import calc_tax globals()['calc_tax'] = calc_tax return calc_tax(*arg, **kwargs) But if you are terrifyingly clever, (or have enough motive*), you can define a function, '_remote', So that your __init__.py contains: ... _remote('some_tax') _remote('other', 'frogs') ... * The pythonic "enough motive" is how redundant your "__init__.py" looks. The "DRY" (Don't Repeat Yourself) principle comes into effect. The more your source looks like boilerplate, the more you should itch to replace the boilerplate. --Scott David Daniels Scott.Daniels at Acm.Org From rtw at freenet.co.uk Sat Jul 26 11:29:18 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 26 Jul 2008 10:29:18 -0500 Subject: Questions on 64 bit versions of Python References: <488aec52$0$21481$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote in news:488aec52$0$21481$9b622d9e at news.freenet.de in comp.lang.python: >> The end result of that is on a 32-bit machine IronPython runs in a >> 32-bit process and on a 64-bit machine it runs in a 64-bit process. > > > That's probably not exactly true (although I haven't checked). > > When you start a .NET .exe program, the operating system needs to > decide whether to create a 32-bit or a 64-bit process (assuming the > processor supports 64-bit mode). > > The Microsoft .NET commercial framework uses the PE architecture of the Whats the "Commercial framework" ? I've only come accross 3, the standard 32 bit one and 2 64 bit variants. > executable to make that decision (or, rather, it doesn't decide at all, > but the underlying OS decides). The C# compiler (more specifically, the > assembly linker) offers a choice of setting the .NET architecture to > Itanium, AMD64, x86, or "any"; people use typically "any". This "any" > choice is implemented by setting the PE architecture to "any", and then > indicating to the .NET run-time that any other architecture would be > fine as well. > > As a consequence, an architecture-any executable launches as a 32-bit > process on a 64-bit system. I just tested, I built a default C# forms app using the "AnyCPU" option and it ran as a 64 bit app (no *32 in Task Manager), this is on XP64. I have though installed the AMD64 version of the 2.0 framework and AFAICT neither windows update or the Visual Studio installer will install that by default, you have to go get it your self. > To have the executable launch as 64-bit > code, you must tell csc.exe to create an AMD64 binary (say), which > then means that the binary won't launch on a 32-bit system. I haven't > checked, but my guess is that IronPython uses architecture-any > executables (unless you adjust the build process). I just started ipy.exe the 1.1 and 2.0B1, both ran as 64 bit processes IronPython 1.1 (1.1) on .NET 2.0.50727.1433 Copyright (c) Microsoft Corporation. All rights reserved. >>> I don't know what happens if you have both 32 bit and 64 bit versions of the framwork installed (presumably with slightly different minor version numbers) as I uninstalled the 32 bit version before I installed the AMD64 version. Rob. -- http://www.victim-prime.dsl.pipex.com/ From wmcbrine at users.sf.net Wed Jul 30 14:48:28 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Wed, 30 Jul 2008 18:48:28 GMT Subject: like py2exe, but on a mac References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> <341kk.407$aA5.312@trnddc05> Message-ID: <0I2kk.565$rb5.429@trnddc04> On Wed, 30 Jul 2008 16:57:35 +0000, I wrote: > [bundlebuidler] does put in a version-specific #! line, but if I change > that to #!/usr/bin/env python, the app still works, and it seems to me > that it will work for any version of Python on OS 10.4, 10.5, and maybe > 10.3. Then again, I see now that it has more hardwired paths in the "Python" binary. Bah. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From duncan.booth at invalid.invalid Wed Jul 9 17:06:08 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jul 2008 21:06:08 GMT Subject: formatting list -> comma separated (slightly different) References: Message-ID: Michiel Overtoom wrote: > I occasionally have a need for printing lists of items too, but in the > form: "Butter, Cheese, Nuts and Bolts". The last separator is the > word 'and' instead of the comma. The clearest I could come up with in > Python is below. I wonder if there is a more pythonic solution for > this problem. Maybe something recursive? >>> from itertools import chain, repeat >>> def across(*iterables): iterables = map(iter, iterables) while 1: for it in iterables: yield it.next() >>> friends=['Anne','Bob','Chris','Debbie','Eve','Fred'] >>> ''.join(across(friends, chain(repeat(', ', len(friends)-2), [' and ']))) 'Anne, Bob, Chris, Debbie, Eve and Fred' I feel there ought to be an easier way of alternating between iterators but if there is I can't think of it offhand. Also it breaks down unless you have at least two friends. This version is a bit messy but seems to work reliably for any number of friends: >>> for i in range(len(friends)+1): f = friends[:i] print ' and '.join(s for s in [', '.join(f[:-1]), ''.join(f[-1:])] if s) Anne Anne and Bob Anne, Bob and Chris Anne, Bob, Chris and Debbie Anne, Bob, Chris, Debbie and Eve Anne, Bob, Chris, Debbie, Eve and Fred Of course neither works cleanly if you give it an iterator rather than a list. This is a bit longer but does work without knowing the length of the iterator in advance (and you could save a couple of lines by concatenating the adjacent yields): >>> def commaand(it): it = iter(it) yield it.next() n = it.next() for nxt in it: yield ', ' yield n n = nxt yield ' and ' yield n >>> for i in range(len(friends)+1): f = friends[:i] print ''.join(commaand(f)) Anne Anne and Bob Anne, Bob and Chris Anne, Bob, Chris and Debbie Anne, Bob, Chris, Debbie and Eve Anne, Bob, Chris, Debbie, Eve and Fred From bignose+hates-spam at benfinney.id.au Thu Jul 3 21:27:28 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 04 Jul 2008 11:27:28 +1000 Subject: Copyright issues for an application developed using django, python and mySQL References: <1f23a9fd-33a0-4a06-9733-241c8fd450d2@w4g2000prd.googlegroups.com> Message-ID: <87iqvm30cf.fsf@benfinney.id.au> Nagu writes: > I made a small recommendation engine for our company using python, > django, and mySQL. My supervisor and the senior management are > worried about the copyright and licensing issues. It's good that they're raising these concerns and making sure. > They want to find out the details on how to go about start using it, > like quoting python/django/ mySQL specifically on the bottom of the > web page or some other thing. You should read the licenses for these products (they're not long), and retain a lawyer to give an educated opinion addressing the specific concerns your managers have. > How do I go about addressing the copyright and licensing issues? (I > do not know if licensing is the right word here). Start with finding out exactly what those concerns are, gather the license terms of the works you're using, and consult a copyright lawyer. In parallel, you can read the license texts yourself and understand them to satisfy yourself about what the terms allow and require. However, that understanding is good only for making decisions that affect yourself; for making decisions that affect the company, your managers should get expert legal opinion. > Please advice. Hope that helps. -- \ ?I was gratified to be able to answer promptly and I did. I | `\ said I didn't know.? ?Mark Twain, _Life on the Mississippi_ | _o__) | Ben Finney From mitchell.peabody at gmail.com Wed Jul 16 18:37:00 2008 From: mitchell.peabody at gmail.com (mizhi) Date: Wed, 16 Jul 2008 15:37:00 -0700 (PDT) Subject: For_loops hurt my brain. References: <4874c21f-befa-4e9f-a99d-486cc9c9b5b8@d77g2000hsb.googlegroups.com> Message-ID: Other possibility, combining Dan and Fredrik's posts: import zipfile import os zips = { 'c:/spare.zip': ['c:/spare/huge.fm3', 'c:/spare/huge.wk3'], 'c:/seekfacts.zip': ['c:/seekfacts/bookmark.html', 'c:/seekfacts/ index.htm', 'c:/seekfacts/seek.css', 'c:/seekfacts/seek.js'] }; def zipdir(zFile, files): for f in files: zFile.write(f, os.path.basename(f), zipfile.ZIP_DEFLATED); def zipit(zipfilename, files): zFile = zipfile.ZipFile(zipfilename, 'w'); zipdir(zFile, files); zFile.close(); for zipfilename,files in zips.items(): zipit(zipfilename, files); From wegraps at gmail.com Wed Jul 23 00:30:43 2008 From: wegraps at gmail.com (Graps Graps) Date: Wed, 23 Jul 2008 10:00:43 +0530 Subject: How to replace the values with keys ? Message-ID: <92df0f7c0807222130n382edf5di8c7124690f3dffa7@mail.gmail.com> Hi all, I am a newbie to python... I have two text files text1 and text2. Text1 is a tabbed separated file, say like a b a c a d a g b c b d b h c d c h... and so on.. Text2 is a python dictionary containing data as {0: 'a', 1: 'b', 2: 'c'...} now I want the data in text1 to be replaced with the keys, say like 0 1 0 2 0 3 0 6 1 2... so on.. Is there some way I could do it in python? I tried import aDict import re infile = open('text1.txt','rw') outfile = open('text3.txt','w') def replace_words(infile, aDict): rc=re.compile('|'.join(map(re.escape, aDict))) def translate(match): return aDict[match.group(0)] return rc.sub(translate, infile) outfile = replace_words(infile,aDict) I am thrown with: Traceback (most recent call last): File "", line 1, in File "", line 2, in replace_words TypeError: argument 2 to map() must support iteration I imported text2.txt , containing python dictionary as aDict.py. I want the replaced values in a separate file text3.txt. Thanking in advance.., GraPs -------------- next part -------------- An HTML attachment was scrubbed... URL: From rowen at cesmail.net Tue Jul 29 15:24:49 2008 From: rowen at cesmail.net (Russell E. Owen) Date: Tue, 29 Jul 2008 12:24:49 -0700 Subject: like py2exe, but on a mac References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> Message-ID: In article <5K9jk.278$rb5.198 at trnddc04>, William McBrine wrote: > On Sun, 13 Jul 2008 00:58:59 +0200, Python.Arno wrote: > > > http://undefined.org/python/py2app.html > > py2app bundles Python itself into the app, right? I wonder, is there no > way to create an app bundle that relies on the existing installation of > Python, since OS X already comes with Python? I have a tiny little > program (~20k) that I'd like to make into an app bundle, if only to > suppress the console window, and I'd rather not lump in the whole Python > interpreter if I can avoid it. That is exactly what py2app does by default if you run py2app with the system python. If you run py2app with a non-system python then that python is bundled with the application. Note that different versions of MacOS X have different versions of system python. So if your application needs any 3rd party packages then including python with the app will allow it work with more versions of MacOS X. -- Russell From rocksportrocker at googlemail.com Sat Jul 12 06:44:37 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Sat, 12 Jul 2008 03:44:37 -0700 (PDT) Subject: sending input to an embedded application References: Message-ID: On 12 Jul., 09:08, George Oliver wrote: > hi, I'm a novice programmer trying to better define a hobby project > I'm thinking of. > > What I would like to do is take a program and embed it or put it > within a Python-run GUI, using the GUI just to capture and send input > to the application, and display the ouput. > > Specifically I want to use a Python module such as wxPython, pygame or > pyglet to build the UI, capture key presses, and then send a string to > the program, an interactive fiction interpreter; the reason for this > is that the interpreter on its own doesn't have the capability to > recognize certain key presses on the keyboard. I thought that writing > a middle layer rather than a brand new interpreter would be easier for > someone of my skill level. > > The interpreter would send its output to the Python GUI. The GUI then > would be as light/translucent as possible, just accepting input, > sending it to the interpreter, and displaying the output as if you > were just running the interpreter by itself. > > As I don't really know the issues involved, I'm hoping someone can > point me in the right direction. Do people 'frame' programs with > something like wxPython or pygame and use the frame to capture and > pass along input, and receive and display the output? > > thanks, George Which interface does your interpreter provide ? Just commandline or can you access by other methods ? http://sourceforge.net/projects/pexpect/ might help you Greetings, Uwe From jwahlmann at gmail.com Fri Jul 18 14:43:26 2008 From: jwahlmann at gmail.com (jwahlmann at gmail.com) Date: Fri, 18 Jul 2008 11:43:26 -0700 (PDT) Subject: Weird Python startup behavior between different drives on PowerPC platform Message-ID: <616d9012-5b71-43c7-9141-bc4b37072642@y22g2000prd.googlegroups.com> I'm experiencing some strange behavior when starting up python on a Debian-based PowerPC platform. Normally, I operate from this platform with a root file system on an IDE flash drive (/dev/hda1). However, I'm trying to get my system to run with root on a mechanical SATA drive (/dev/sda1). Both are installed on a PowerPC board via a PMC daughter board. When running off the flash drive, the Python interpreter loads and runs just fine. However, when running from SATA, the interpreter seems to have problems with importing things like site, os, etc. I've played around with PYTHONHOME to no effect. I even went as far as setting PYTHONHOME to some off the wall location (so no stdlibs will load) and invoking Python as: host$ PYTHONHOME=/tmp python -d -v -S # installing zipimport hook import zipimport # builtin # installed zipimport hook Python 2.4.4 (#2, Apr 5 2007, 19:01:44) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 >>> i=0 File "", line 1 i=0 ^ SyntaxError: invalid syntax >>> You'll note that doing something as simple as setting "i=0" results in a syntax error. If I run the same thing on the IDE flash drive, it works: host$ PYTHONHOME=/tmp python -d -v -S # installing zipimport hook import zipimport # builtin # installed zipimport hook Python 2.4.4 (#2, Apr 5 2007, 19:01:44) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 >>> i=0 >>> Any ideas?! What could possibly cause a difference of operation between running from a IDE flash drive (/dev/hda1) vs. SATA (/dev/ sda1)? Other than toggling hda1 vs. sda1 in /etc/fstab, the filesystems are being built identically. Could it be that shared libraries aren't being loaded correctly or fast enough off the SATA drive vs. flash? Shooting in the dark here... Thanks, Jon Wahlmann From alexnbryan at gmail.com Thu Jul 17 03:50:59 2008 From: alexnbryan at gmail.com (Alexnb) Date: Thu, 17 Jul 2008 00:50:59 -0700 (PDT) Subject: Getting a unknown word out of a list with no spaces In-Reply-To: <487EF7D9.8010400@promsoft.ru> References: <18502758.post@talk.nabble.com> <487EF593.5060505@promsoft.ru> <18503144.post@talk.nabble.com> <487EF7D9.8010400@promsoft.ru> Message-ID: <18503367.post@talk.nabble.com> Alexandr N Zamaraev wrote: > > Alexnb wrote: >>>>>> s = '--a href="/browse/brick"--brick--/a--' >>>>>> s >>> '--a href="/browse/brick"--brick--/a--' >>>>>> ''.join('<%s>' % l if i % 2 == 1 else l for i, l in >>> enumerate(s.split('--'))) >>> ' /browse/brick brick ' >> >> I'm sorry, I don't think I was being clear. I replaced the <'s with -- so >> it >> would post online w/o actually making a link. I just need to know how to >> get >> the "brick" out. > 1) if string really '--a href="/browse/brick"--brick--/a--' > >>> s.split('--', 3)[2] > brick > 2) if string ' /browse/brick brick ' > >>> s.split('>', 1)[1].split('<')[0] > brick > -- > http://mail.python.org/mailman/listinfo/python-list > > Excellent! it works. But I have one more question. How can I test to see if the first character of a string is what I want, for example, how can I test to see if the first char of a string is "<"? -- View this message in context: http://www.nabble.com/Getting-a-unknown-word-out-of-a-list-with-no-spaces-tp18502758p18503367.html Sent from the Python - python-list mailing list archive at Nabble.com. From asd at pittle.org Thu Jul 10 05:16:12 2008 From: asd at pittle.org (=?ISO-8859-1?Q?Ali_Servet_D=F6nmez?=) Date: Thu, 10 Jul 2008 02:16:12 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: Message-ID: <2320fe46-9e4d-483c-bbe5-4d8741951ffd@2g2000hsn.googlegroups.com> On Jul 10, 1:07?am, Gros Bedo wrote: > Hello, > Ali I totally support you, neither I couldn't find any really working code completion for python in a free software, and it's really a mess, at least on Linux. > > On Windows, there is PyScripter (http://pyscripter.googlepages.com/), but it is based on Delphi, and as such it's not portable. But it's a free software (even if I couldn't find the sources, they say you can download them). > > It is said to be working on Linux via Wine, so if you really need a code completion tool you could give it a try. > _________________________________________________________________ > T?l?chargez gratuitement des ?motic?nes pour pimenter vos conversations Messengerhttp://specials.fr.msn.com/femmes/amour/emoticonesLove.aspx Thanks. From theller at python.net Thu Jul 24 11:03:59 2008 From: theller at python.net (Thomas Heller) Date: Thu, 24 Jul 2008 17:03:59 +0200 Subject: Working with ctypes and char** data type In-Reply-To: <14b44a64-ec58-4ff2-abce-1cc44557e4e4@27g2000hsf.googlegroups.com> References: <14b44a64-ec58-4ff2-abce-1cc44557e4e4@27g2000hsf.googlegroups.com> Message-ID: <6erju5F88slmU2@mid.individual.net> Philluminati schrieb: > I'm a bit of a python newbie and I need to wrap a C library. > > I can initialise the library using CDLL('mcclient.so') > > and I can call functions correctly inside the library but I need to > invoke one function which has this function definition: > > char ** CAPAPI McSearch(HMCLINK Handle, > short nSearchType, > short nNoSelect, > char **pSelect, > short nNoWhere, > char **pWhere, > char **pData, > int iTimeout); > > For **pSelect I want to pass in an array of char points, which in C > would be declared as > > char *pData[] = { "ADDR", "POSTCODE" }; > > Can someone tell me how use pointers + char pointers together in > python with ctypes please? # create an array that holds two pointers to 'char *', and fill it with data: pData = (c_char_p * 2)() pData[0] = "ADDR" pData[1] = "POSTCODE" # Another way: pData = (c_char_p * 2)("ADDR", "POSTCODE") Thomas From code at pizzashack.org Mon Jul 21 12:12:41 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 21 Jul 2008 12:12:41 -0400 Subject: Change PC to Win or Windows In-Reply-To: References: Message-ID: <20080721161241.GA8793@dragontoe.org> On Fri, Jul 18, 2008 at 10:34:41PM -0700, Dennis Lee Bieber wrote: > On Fri, 18 Jul 2008 19:14:43 -0400, Derek Martin > declaimed the following in comp.lang.python: > > > On Fri, Jul 18, 2008 at 03:46:13PM -0700, Joel Teichroeb wrote: > > > Calling Windows PC seems to be something that Apple did so they would > > > not have to directly mention Windows. > > > > Actually it's something IBM did when they created the IBM PC. Of > > Bah... PC was short for Personal Computer... I'm well aware... congratulations on completely missing the point. I was describing how the term PC has become synonimous with Windows machines. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From motoom at xs4all.nl Mon Jul 14 12:30:26 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Mon, 14 Jul 2008 18:30:26 +0200 Subject: Determining when a file has finished copying Message-ID: <2.2.32.20080714163026.01217970@pop.xs4all.nl> Ethan wrote: > One more option may be to attempt to rename > the file -- if it's still open for copying, that will fail; > success indicates the copy is done. Caveat -- this is dependent on the operating system! Windows will indeed not allow you to rename or delete a file that's still open for writing by another process, at least not when the file is on a local NTFS filesystem, but don't count on this on Unix or networked filesystems. There you can easily rename, move or delete a filename from a directory whilst other processes still write to it. After all, a directory is nothing else than a list of filenames which map to certain inodes. Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From sjmachin at lexicon.net Sat Jul 19 01:32:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 18 Jul 2008 22:32:15 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> <9c344a52-4a3e-41de-a462-a78c891961ee@c58g2000hsc.googlegroups.com> Message-ID: <945275e9-8923-479c-8eec-258bd68063c0@z6g2000pre.googlegroups.com> On Jul 19, 12:04 pm, Andrew Freeman wrote: > To show if valid: > > if re.search(r'^[LRM]*$', 'LM'): > print 'Valid' > A couple of points: (1) Instead of search(r'^blahblah', ...) use match(r'blahblah', ...) (2) You need to choose your end-anchor correctly; your pattern is permitting a newline at the end: >>> re.search(r'^[LRM]*$', 'LM\n') <_sre.SRE_Match object at 0x00B9E528> >>> From steve at REMOVE-THIS-cybersource.com.au Sun Jul 27 05:14:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Jul 2008 09:14:26 GMT Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> Message-ID: <009c37fd$0$20302$c3e8da3@news.astraweb.com> On Sat, 26 Jul 2008 15:58:16 -0700, Carl Banks wrote: > On Jul 26, 5:07?pm, Terry Reedy wrote: >> Whether or not one should write 'if x' or 'if x != 0' [typo corrected] >> depends on whether one means the general 'if x is any non-null object >> for which bool(x) == True' or the specific 'if x is anything other than >> numeric zero'. ?The two are not equivalent. ?Ditto for the length >> example. > > Can you think of any use cases for the former? And I mean something > where it can't be boiled down to a simple explicit test for the sorts of > arguments you're expecting; something that really takes advantage of the > "all objects are either true or false" paradigm. But why do you need the explicit test? What benefit do you get from if len(alist) != 0 instead of the simpler and faster "if alist" ? If you need to know that alist is actually a list, isinstance() is the function you want; and if you want to know that it has a length, hasattr(alist, '__len__') is better. (Or call len() in a try...except block.) Either way, testing the length is zero explicitly gains you nothing, and risks failure for any sequence types that might distinguish between an empty sequence and a length of zero. > The best thing I can come up with out of my mind is cases where you want > to check for zero or an empty sequence, and you want to accept None as > an alternative negative as well. But that's pretty weak. You might find it pretty weak, but I find it a wonderful, powerful feature. I recently wrote a method that sequentially calls one function after another with the same argument, looking for the first function that claims a match by returning a non-false result. It looked something like this: def match(arg, *functions): for func in functions: if func(arg): return func I wanted the function itself, not the result of calling the function. I didn't care what the result was, only that it was something (indicates a match) or nothing (no match). In one application, the functions might return integers or floats; in another they might return strings. In a third, they might return re match objects or None. I don't need to care, because my code doesn't make any assumptions about the type of the result. -- Steven From python at bdurham.com Wed Jul 30 20:29:39 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 30 Jul 2008 20:29:39 -0400 Subject: Optimizing size of very large dictionaries Message-ID: <1217464179.31710.1266222419@webmail.messagingengine.com> Are there any techniques I can use to strip a dictionary data structure down to the smallest memory overhead possible? I'm working on a project where my available RAM is limited to 2G and I would like to use very large dictionaries vs. a traditional database. Background: I'm trying to identify duplicate records in very large text based transaction logs. I'm detecting duplicate records by creating a SHA1 checksum of each record and using this checksum as a dictionary key. This works great except for several files whose size is such that their associated checksum dictionaries are too big for my workstation's 2G of RAM. Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From larry.bates at websafe.com` Wed Jul 9 20:27:17 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 09 Jul 2008 19:27:17 -0500 Subject: Manipulating bitsets in struct In-Reply-To: References: Message-ID: Allen wrote: > I'm using Python to do some simple network programming, and found the > struct module very useful for such things, but is there a way to easily > manipulate bitsets such as a 16 bit word being split into 4 parts like 2 > bits, 1 bit, 4 bits, and 9 bits? > > Perhaps something like: > > struct.pack('!h(2:1:4:9)',2,0,1,100) > > > Brian Vanderburg II > > > > > Just 'or' them together after shifting to the left the appropriate number of bits. -Larry From henryar2 at gmail.com Fri Jul 11 11:38:47 2008 From: henryar2 at gmail.com (Henry Read) Date: Fri, 11 Jul 2008 23:38:47 +0800 Subject: Editra Message-ID: Editra is a multi-platform text editor with an implementation that focuses on creating an easy to use interface and features that aid in code development. Currently it supports syntax highlighting and variety of other useful features for over 60 programming languages. Editra is freely available under the terms of the wxWindows Licence. Currently the project is in the alpha development phase but test builds of "stable" points are available for download and trial as Windows and Mac OSX(Universal) binaries, currently other Unix and Linux based systems will have to install from source using the included setup script. Please feel free give it a try and to report bugs and request features. *Editra*.org | News It is a good editor for Python, also it is small.It can also support auto completion with Python modules. It is suitable for Python beginners. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dominic.rice at gmail.com Fri Jul 4 05:37:20 2008 From: dominic.rice at gmail.com (Dominic Rice) Date: Fri, 04 Jul 2008 10:37:20 +0100 Subject: running python from cmd.exe References: Message-ID: Miki wrote: > Hello, > >> I can't seem to get python to run my scripts using the command: python >> .py >> >> If I type python the interpreter runs as I sorted out the Path property, >> >> I'm afraid I don't know much about this kind of thing as I'm a science >> student who needs some Python not a programmer! > Can you be more specific about the error you get? > > Say you have a script hw.py that contains one line: > print "Hello Python" > > and you run > python hw.py > > What is the error you get? > > HTH, > -- > Miki > http://pythonwise.blogspot.com > Sure, I get: can't open file .py: [errorno 2]No such file or directory. Now if I've noticed that if I change directory to (for instance) \Python25 where the script is the command runs fine.(?) From bronger at physik.rwth-aachen.de Thu Jul 24 11:36:45 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 24 Jul 2008 17:36:45 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <32e12408-fc9f-4eb4-8b9d-fb7fa69bd2fc@f36g2000hsa.googlegroups.com> <87zlo7y2wn.fsf@physik.rwth-aachen.de> <48889a72$0$25165$426a74cc@news.free.fr> Message-ID: <874p6f5m5u.fsf@physik.rwth-aachen.de> Hall?chen! Bruno Desthuilliers writes: > Torsten Bronger a ?crit : > >> Kay Schluehr writes: >> >>> On 24 Jul., 11:40, Torsten Bronger >>> wrote: >>> >>>> [...] Just like this. However, the compiler could add "self" >>>> to non-decorated methods which are defined within "class". >>> >>> And $self2, $self3, ... to the object methods of nested classes >>> and $cls2, $cls3, ... to the classmethods of those classes...? >> >> One could surely find ways to realise this. However, the design >> goal should be: Make the frequent case simple, and the rare case >> possible. > > Given the (more and more prominent) use of decorators, metaclasses > and other meta-programming techniques in Python, I'm not sure the > cases where you really need access to Python's object model inners > are that "rare". Not in my code at least. What does "not rare" mean for you? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From bruno.desthuilliers at gmail.com Fri Jul 4 16:07:23 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 4 Jul 2008 13:07:23 -0700 (PDT) Subject: Getting a path from a file object References: <3c500ce7-c697-44e9-9f13-f65edc509e1c@a32g2000prf.googlegroups.com> Message-ID: <1e813aba-292a-49fa-8bb4-3f90269402ff@34g2000hsh.googlegroups.com> On 4 juil, 20:37, Andrew Fong wrote: > Newbie question: > > Let's say I open a new file for writing in a certain path. How do I > get that path back? > > Example: > > >>> f = open('/some/path/file.ext') > >>> some_function(f) > > '/some/path/file.ext' > > Does some_function(f) already exist? Nope. But: > And if not, how would I define > it? Not sure it's worth defining a function: def some_function(f): return f.name > -- Andrew From bj_666 at gmx.net Sat Jul 12 09:36:22 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Jul 2008 13:36:22 GMT Subject: How to create a timer/scheduler in Python? References: <0stg74t0eksmnfsslukn5m7f9s4rbub8kt@4ax.com> Message-ID: <6drqamF3sqd5U1@mid.uni-berlin.de> On Sat, 12 Jul 2008 10:30:00 +0100, John Dann wrote: > Looking around on the net I can see references to a thread timer, but > I'm not really looking to start any new threads (I just want part of > the GUI to update every 2 secs) and don't want to get into that sort > of complication while still just learning Python. Look into the GUI toolkit because that's typically something solved with functions from the specific toolkit. > Is there really no simple timer/scheduler function available in > Python? You can do that quite easily with threads but almost all GUI toolkits don't like it if you access the GUI from multiple threads. Ciao, Marc 'BlackJack' Rintsch From no at spam.no Sun Jul 13 11:25:03 2008 From: no at spam.no (Thin Myrna) Date: Sun, 13 Jul 2008 17:25:03 +0200 Subject: wxPython code giving strange errors. References: <01694ab5-7b5e-4e57-8b86-bf89b0beec82@m44g2000hsc.googlegroups.com> Message-ID: <487a1e4e$0$12126$3b214f66@aconews.univie.ac.at> teh_sAbEr wrote: > I'm busy trying to learn wxPython, and i'm trying to run the following > piece of code (its from the wxPyWiki tutorial): > > import wx > > ID_ABOUT = 101 > ID_EXIT = 110 > > class MainWindow(wx.Frame): > def __init__(self,parent,id,title): > wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) > self.control = wx.TextCtrl(self,1,style=wx.TE_MULTILINE) > self.CreateStatusBar() > > filemenu = wx.Menu() > filemenu.Append(ID_ABOUT,"&About"," Information about this > program.") > filemenu.AppendSeparator() > filemenu.Append(ID_EXIT,"E&xit"," Terminate the program.") > > menuBar = wx.MenuBar() > menuBar.Append(filemenu,"&File") > self.SetMenuBar(menuBar) > self.Show(True) > > app = wx.PySimpleApp() > frame = MainWindow(None, -1, "Sample editor") > app.MainLoop() > > Simple enough, but every single time I try to run it IDLE gives me > this instead of the app I was hoping for: > > Traceback (most recent call last): > File "C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap > \Python Stuff\Batch Picture Converter\main.py", line 24, in > frame = MainWindow(None, -1, "Sample editor") > File "C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap > \Python Stuff\Batch Picture Converter\main.py", line 9, in __init__ > wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) > File "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx > \_windows.py", line 501, in __init__ > _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, > **kwargs)) > PyNoAppError: The wx.App object must be created first! > > As far as I can tell, the wx.App object IS being created first. I > suspect a race condition of some sort here, but can anyone shed some > light on this? The main frame has to be created by the app itself, e.g. like so: class App(wx.App): def OnInit(self): self._frame = MainFrame( None, -1, _APP_CAPTION) self._frame.Show( True) self.SetTopWindow( self._frame) return True def Run(): app = App() app.MainLoop() if __name__ == '__main__': Run() HTH Thin From fredrik at pythonware.com Wed Jul 23 03:59:48 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 09:59:48 +0200 Subject: Undefined calling conventions in Python.h In-Reply-To: References: Message-ID: Jaco Naude wrote: > 1>application.obj : error LNK2031: unable to generate p/invoke for > "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@$$J0YMXH at Z); > calling convention missing in metadata > 1>frmPythonInterface.obj : error LNK2031: unable to generate p/invoke > for "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@$$J0YMXH at Z); > calling convention missing in metadata > > I'm probably missing something but I can't find any calling convention > details in Python.h or the other headers included in this file. the precence of name mangling indicates that your compiler doesn't understand that Python's a C library, and therefore uses C calling conventions. have you managed to override the defaults in some odd way? From mwilson at the-wire.com Mon Jul 7 20:41:20 2008 From: mwilson at the-wire.com (Mel) Date: Mon, 07 Jul 2008 20:41:20 -0400 Subject: "in"consistency? References: <87vdzhwf1v.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > "David C. Ullrich" writes: > >> >>> 'ab' in 'abc' >> True >> >>> [1,2] in [1,2,3] >> False > > > >> Is there a reason for the inconsistency? > > Probably. The special behaviour of string types was changed in Python > 2.3, according to that document. As it stands, you'd get [1,2] in [1,2,3] == False [1,2] in [1, [1,2], 3] == True This could be a good thing. Mel. > From lanclos at ucolick.org Wed Jul 16 21:46:08 2008 From: lanclos at ucolick.org (Kyle Lanclos) Date: Wed, 16 Jul 2008 18:46:08 -0700 Subject: Manually prompting garbage collection In-Reply-To: References: <20080716230911.GD22400@monkey.ucolick.org> <20080716235656.GE22400@monkey.ucolick.org> Message-ID: <20080717014608.GA28610@monkey.ucolick.org> Fredrik Lundh wrote: > Yeah, but what do you expect that garbage collection pass to result in? Basically, I want to toss the objects before I close the service that they depend on. > PyGC_Collect() does exactly that, so if that doesn't solve your problem, > the only way to fix is this is to go back to the drawing board (and even > if it would fix this, it's a good idea to get back to the drawing board > anyway; Python's not C++, and code that relies on destructors to fire in > a specific order, or before a specific event, is bound to fail sooner or > later.) I suspect that this is the root of the answer to my question-- if I can't rely on triggering the collection in a specific sequence, I'll need to implement my workaround. Your time and attention is greatly appreciated-- --Kyle From __peter__ at web.de Sun Jul 27 02:41:54 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 27 Jul 2008 08:41:54 +0200 Subject: Insert string into string References: <56ff99b9-b4d4-4077-8de1-97a771ac526a@k13g2000hse.googlegroups.com> Message-ID: Mensanator wrote: > I don't know why you're using stdin if you're reading from a file. >From Francesco's initial post in his previous thread I inferred that he had a script like f = open("xxx.pdb") for line in f: # process line print line and was calling it python script.py >outfile My hope was that import sys for line in sys.stdin: # process line sys.stdout.write(line) invoked as python script.py outfile would be an improvement as it avoids hardcoding the filename, but instead chaos ensued... Francesco: Mensanator's script looks like you can take it "as is". If you want to use Python to do other interesting things I highly recommend that you work your way through a tutorial of your choice. This will make subsequent trial-and-error much more fun. Following Roy's suggestion I also had a brief look at Biopython's PDB parser which has the advantage that it "understands" the file format. Unfortunately it is probably too complex for you to use at this point of your career as a pythonista ;) By the way, are you trying to modify the chain ID? Biopython locates that at position 21, so take this as a reminder that indices in Python start at 0, i. e. line[21] gives you the 22nd character in the line. Peter From __peter__ at web.de Sun Jul 6 14:57:00 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 06 Jul 2008 20:57:00 +0200 Subject: how are strings immutable in python? References: Message-ID: ssecorp wrote: >>>> h = "aja baja" >>>> h += 'e' >>>> h > 'aja bajae' >>>> The inplace-add operator doesn't mutate the lvalue, it just rebinds it: >>> a = b = "foo" >>> id(a) 47643036142016 >>> a += "bar" >>> id(a), a (47643036142064, 'foobar') >>> id(b), b (47643036142016, 'foo') Peter From motoom at xs4all.nl Sat Jul 12 06:09:11 2008 From: motoom at xs4all.nl (Michiel Overtoom) Date: Sat, 12 Jul 2008 12:09:11 +0200 Subject: Help with BeautifulSoup Message-ID: <2.2.32.20080712100911.01141b64@pop.xs4all.nl> Alex wrote... > >Okay, heres the general idea of the html I have to work with: > >
> noun > >
>
>
> verb >
>
>
> > >Okay, I left off some stuff. I wish you didn't, or at least provided an URL where I can get the page which you are trying to parse. Now I don't have a valid testcase to tinker with. And maybe you can also show your code which you already came up with. > I can easily get the tables but it is the span's than I am having trouble with. I can't see any SPAN tags in the example you provided. Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Vallopillil http://www.catb.org/~esr/halloween/halloween4.html From roy at panix.com Sat Jul 12 20:32:53 2008 From: roy at panix.com (Roy Smith) Date: Sat, 12 Jul 2008 20:32:53 -0400 Subject: Correct use of try,except and raise? References: <3b78898b-6131-4137-9c1d-64deaf460ee6@p25g2000hsf.googlegroups.com> Message-ID: In article <3b78898b-6131-4137-9c1d-64deaf460ee6 at p25g2000hsf.googlegroups.com>, ssecorp wrote: > Is this correct use of exceptions? to raise an indexerror and add my > own string insetad of just letting it raise a IndexError by itself and > "blaming" it on list.pop? > > class Stack(object): > def __init__(self, *items): > self.stack = list(items) > > def push(self, item): > self.stack.append(item) > > def pop(self): > try: > return self.stack.pop() > except: > raise IndexError, "pop from empty stack" > > class Queue(object): > def __init__(self, *items): > self.queue = list(items) > > def append(self, item): > self.queue.append(item) > > def pop(self): > try: > return self.queue.pop(0) > except: > raise IndexError, "pop from empty queue" I think you would do better defining a new exception, PopError, or something like that. Then you can write code which specifically catches that and do something with it. It's also not a good idea to catch all exceptions. Catch the most specific thing you can. Consider something like: try: kew.pop(0) except: raise IndexError, "pop from empty kew" When I run it, it prints, "IndexError: pop from empty kew". The problem is, the *real* error is "NameError: name 'kew' is not defined". By catching all exceptions, I've masked a programming error by turning the NameError into an IndexError. From norseman at hughes.net Tue Jul 15 12:50:44 2008 From: norseman at hughes.net (norseman) Date: Tue, 15 Jul 2008 09:50:44 -0700 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> References: <518776da-8098-4ff3-af6f-076409f3e385@f36g2000hsa.googlegroups.com> Message-ID: <487CD564.5020008@hughes.net> defn noob wrote: > isPrime works when just calling a nbr but not when iterating on a > list, why? adding x=1 makes it work though but why do I have to add > it? > Is there a cleaner way to do it? > > > def isPrime(nbr): > for x in range(2, nbr + 1): > if nbr % x == 0: > break > if x == nbr: > return True > else: > return False > >>>> [isPrime(y) for y in range(11)] > > Traceback (most recent call last): > File "", line 1, in > [isPrime(y) for y in range(11)] > File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > if x == nbr: > UnboundLocalError: local variable 'x' referenced before assignment > > >>>> map(isPrime, range(100)) > > Traceback (most recent call last): > File "", line 1, in > map(isPrime, range(100)) > File "C:\Python25\Progs\blandat\myMath.py", line 9, in isPrime > if x == nbr: > UnboundLocalError: local variable 'x' referenced before assignment >>>> isPrime(10) > False >>>> isPrime(11) > True > > > > adding x=1 makes it work though: > > def isPrime(nbr): > x=1 > for x in range(2, nbr + 1): > if nbr % x == 0: > break > if x == nbr: > return True > else: > return False > > >>>> [isPrime(y) for y in range(11)] > [False, True, True, True, False, True, False, True, False, False, > False] > -- > http://mail.python.org/mailman/listinfo/python-list > ======================================== Yep - "local variable 'x' referenced before assignment" is correct. You state: for x in range... but x doesn't exist until initialized. To save a loop, initialize x=2 (the minimum value) and loop executes on pass one. In a straight 'C' program ( for (x=1, x=(nbr+1), x++) etc... ) the x is initialized and forceably incremented. seems Python does not auto initialize but does auto increment. Steve norseman at hughes.net From ki4yjl at gmail.com Sun Jul 20 17:05:16 2008 From: ki4yjl at gmail.com (WDC) Date: Sun, 20 Jul 2008 14:05:16 -0700 (PDT) Subject: Testing out NewsProxy Message-ID: Please excuse this post, but I am seeing if NewsProxy actually filters out Google Groups or not. From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 3 11:09:45 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 03 Jul 2008 17:09:45 +0200 Subject: site-packages, unzipepd there but import fails In-Reply-To: References: Message-ID: <486cebad$0$15999$426a34cc@news.free.fr> defn noob a ?crit : > i unzipped what ? > and put the folder which folder > in site-packages. which one ? (remember that if you have more than one Python installation on your machine, you'll have more than one site-packages too). > when i run setup.py > install nothing happens. Well... usually, setup.py install takes care of putting the appropriate things at the appropriate place for your system, so you don't have to "put the folder in site-packages" by yourself. > when i do import pp from shell Which shell ? The Python shell ? A bash shell ? > it complains it doesnt exist. > > isnt placing the folder in site-packages enough? > move "the folder" from site-packages to somewhere else, cd to "the folder", then run python setup.py install (with appropriate permissions of course). And if you have more than one python install on your system, make sure the one you're using for running setup.py is the right one. > these setup.py-files often dont work Python-version confusion issues set aside, I've never had any problem with a setup.py so far (for 'so far' == since I've started using Python some height years ago). But I admit I never tried to copy "the folder" into site-packages *then* run setup.py install from there... From sjmachin at lexicon.net Thu Jul 10 07:28:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 10 Jul 2008 04:28:35 -0700 (PDT) Subject: TypeError, I know why but not how!? References: <03cbb0d2-6a0c-4b86-a75e-b73c5677acc7@c65g2000hsa.googlegroups.com> Message-ID: On Jul 10, 12:07 pm, ssecorp wrote: > pair1 = (student1,student2) > pair2 = (student2,student1) > if (pair1 or pair2) in incompatibles: Apart from the problems that others have mentioned, the above statement is NOT doing what you think it is. (pair1 or pair2) will always produce pair1, because pair1, a tuple of length 2, cannot be false. So the statement is equivalent to: if pair1 in incompatibles: What you want is: if pair1 in incompatibles or pair2 in incompatibles: Cheers, John From stefan_ml at behnel.de Sat Jul 19 03:56:29 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 19 Jul 2008 09:56:29 +0200 Subject: Best Python packages? In-Reply-To: References: <96774b25-6ac8-4b37-a3d7-d8825dd3b589@p25g2000hsf.googlegroups.com> <17861f55-8ad1-4703-ad22-838675f2afc4@w1g2000prk.googlegroups.com> Message-ID: <48819E2D.10903@behnel.de> Iain King wrote: > Well, if you're looking for a list of excellent 3rd party Python > libraries, then I can give you the ones I like and use a lot: [...] > BeautifulSoup : for real-world (i.e. not-at-all-recommendation- > compliant) HTML processing You forgot lxml.html, which is much faster, more memory friendly and more feature-rich than BS. Stefan From alexandre.Fayolle at logilab.fr Thu Jul 31 07:34:39 2008 From: alexandre.Fayolle at logilab.fr (alexandre.Fayolle@logilab.Fr) Date: Thu, 31 Jul 2008 04:34:39 -0700 (PDT) Subject: working pylint anyone? References: <6fdf17Fb2bboU1@mid.uni-berlin.de> Message-ID: <8a08b59f-f7f0-4706-84c9-19f0460f09ef@k30g2000hse.googlegroups.com> On Jul 31, 11:29?am, "Diez B. Roggisch" wrote: > Hi, > > until yesterday I was a happy user of pylint. Then I upgraded to ubuntu > hardy heron - and the trouble began. > > The packaged version of pylint (0.13.2) fails with this error (last line): > > logilab.common.configuration.UnsupportedAction: callback This is a bug in the pylint package in Ubuntu, which has a wrong versioned dependency on python-logilab-common. You should report this bug to ubuntu using the reportbug command. Which version of python-logilab-common and python-logilab-astng are installed on your machine ? > The same error happens if I use > > easy_install-2.5http://release.ingeniweb.com/third-party-dist/logilab.installer-0.1.tgz > > as found on the net. Using easy_install pylint misses logilab-common & > astng, installing these additionally (easy_install) creates two eggs - but > unfortunately, the don't actually create a namespace-package logilab, > instead either one of them is picked up depending on installation order. > > Then I tried the source releases - no luck either, either they produce the > same error or something similar. You are probably picking up the system installation of logilab-common when you do this. > I tried looking into the MLs - the last posts are from around 2006, so I > refrained from actually subscribing. I don't know where you checked, but there is some traffic on the mailing list, and questions generally get answered :-) (http://lists.logilab.org/pipermail/python-projects/ is the correct place) > So - anybody out here having an actually working pylint config and can tell > me what versions work together? I've become pretty dependend on it to be > honest... pylint 0.14.0 should work fine with logilab-common 0.33.0 and astng 0.17.2 Our Debian packages state that it should even work with logilab-common >= 0.22.0 and astng >= 0.17.1 (although to be perfectly honnest, I'm not sure that we have tested pylint with logilab-common 0.22.0, so we could be the ones who introduced the bug in the Ubuntu package). Hope this helps, -- Alexandre Fayolle LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services Informatique scientifique: http://www.logilab.fr/science From narutocanada at gmail.com Sun Jul 20 00:12:59 2008 From: narutocanada at gmail.com (narutocanada at gmail.com) Date: Sat, 19 Jul 2008 21:12:59 -0700 (PDT) Subject: atan2 weirdness Message-ID: <3b3ce28f-55d0-4db4-8eac-df0a9d1bc558@o40g2000prn.googlegroups.com> hi atan2 is supposed to return the angle to x-axis when given y and x, I suppose if I take [x,y] to one full circle, I should get 0-360 degree back---- but no, I get 3 full revolutions! maybe my understanding is wrong. from math import * def f(ang): a=ang if a>360: a-=360 if a>360: a-=360 if a<0: a+=360 if a<0: a+=360 return round(a) for i in range(0,360): t=2*pi*i/360.0 print i,f(atan2(sin(t),cos(t))*180.0) 0 0.0 1 3.0 2 6.0 3 9.0 4 13.0 5 16.0 6 19.0 7 22.0 8 25.0 9 28.0 10 31.0 11 35.0 12 38.0 13 41.0 14 44.0 15 47.0 16 50.0 17 53.0 18 57.0 19 60.0 20 63.0 21 66.0 22 69.0 23 72.0 24 75.0 25 79.0 26 82.0 27 85.0 28 88.0 29 91.0 30 94.0 31 97.0 32 101.0 33 104.0 34 107.0 35 110.0 36 113.0 37 116.0 38 119.0 39 123.0 40 126.0 41 129.0 42 132.0 43 135.0 44 138.0 45 141.0 46 145.0 47 148.0 48 151.0 49 154.0 50 157.0 51 160.0 52 163.0 53 167.0 54 170.0 55 173.0 56 176.0 57 179.0 58 182.0 59 185.0 60 188.0 61 192.0 62 195.0 63 198.0 64 201.0 65 204.0 66 207.0 67 210.0 68 214.0 69 217.0 70 220.0 71 223.0 72 226.0 73 229.0 74 232.0 75 236.0 76 239.0 77 242.0 78 245.0 79 248.0 80 251.0 81 254.0 82 258.0 83 261.0 84 264.0 85 267.0 86 270.0 87 273.0 88 276.0 89 280.0 90 283.0 91 286.0 92 289.0 93 292.0 94 295.0 95 298.0 96 302.0 97 305.0 98 308.0 99 311.0 100 314.0 101 317.0 102 320.0 103 324.0 104 327.0 105 330.0 106 333.0 107 336.0 108 339.0 109 342.0 110 346.0 111 349.0 112 352.0 113 355.0 114 358.0 115 1.0 116 4.0 117 8.0 118 11.0 119 14.0 120 17.0 121 20.0 122 23.0 123 26.0 124 30.0 125 33.0 126 36.0 127 39.0 128 42.0 129 45.0 130 48.0 131 52.0 132 55.0 133 58.0 134 61.0 135 64.0 136 67.0 137 70.0 138 74.0 139 77.0 140 80.0 141 83.0 142 86.0 143 89.0 144 92.0 145 96.0 146 99.0 147 102.0 148 105.0 149 108.0 150 111.0 151 114.0 152 118.0 153 121.0 154 124.0 155 127.0 156 130.0 157 133.0 158 136.0 159 140.0 160 143.0 161 146.0 162 149.0 163 152.0 164 155.0 165 158.0 166 162.0 167 165.0 168 168.0 169 171.0 170 174.0 171 177.0 172 180.0 173 183.0 174 187.0 175 190.0 176 193.0 177 196.0 178 199.0 179 202.0 180 205.0 181 158.0 182 161.0 183 164.0 184 167.0 185 170.0 186 173.0 187 177.0 188 180.0 189 183.0 190 186.0 191 189.0 192 192.0 193 195.0 194 198.0 195 202.0 196 205.0 197 208.0 198 211.0 199 214.0 200 217.0 201 220.0 202 224.0 203 227.0 204 230.0 205 233.0 206 236.0 207 239.0 208 242.0 209 246.0 210 249.0 211 252.0 212 255.0 213 258.0 214 261.0 215 264.0 216 268.0 217 271.0 218 274.0 219 277.0 220 280.0 221 283.0 222 286.0 223 290.0 224 293.0 225 296.0 226 299.0 227 302.0 228 305.0 229 308.0 230 312.0 231 315.0 232 318.0 233 321.0 234 324.0 235 327.0 236 330.0 237 334.0 238 337.0 239 340.0 240 343.0 241 346.0 242 349.0 243 352.0 244 356.0 245 359.0 246 2.0 247 5.0 248 8.0 249 11.0 250 14.0 251 18.0 252 21.0 253 24.0 254 27.0 255 30.0 256 33.0 257 36.0 258 40.0 259 43.0 260 46.0 261 49.0 262 52.0 263 55.0 264 58.0 265 62.0 266 65.0 267 68.0 268 71.0 269 74.0 270 77.0 271 80.0 272 84.0 273 87.0 274 90.0 275 93.0 276 96.0 277 99.0 278 102.0 279 106.0 280 109.0 281 112.0 282 115.0 283 118.0 284 121.0 285 124.0 286 128.0 287 131.0 288 134.0 289 137.0 290 140.0 291 143.0 292 146.0 293 150.0 294 153.0 295 156.0 296 159.0 297 162.0 298 165.0 299 168.0 300 172.0 301 175.0 302 178.0 303 181.0 304 184.0 305 187.0 306 190.0 307 193.0 308 197.0 309 200.0 310 203.0 311 206.0 312 209.0 313 212.0 314 215.0 315 219.0 316 222.0 317 225.0 318 228.0 319 231.0 320 234.0 321 237.0 322 241.0 323 244.0 324 247.0 325 250.0 326 253.0 327 256.0 328 259.0 329 263.0 330 266.0 331 269.0 332 272.0 333 275.0 334 278.0 335 281.0 336 285.0 337 288.0 338 291.0 339 294.0 340 297.0 341 300.0 342 303.0 343 307.0 344 310.0 345 313.0 346 316.0 347 319.0 348 322.0 349 325.0 350 329.0 351 332.0 352 335.0 353 338.0 354 341.0 355 344.0 356 347.0 357 351.0 358 354.0 359 357.0 From larry.bates at websafe.com` Thu Jul 10 20:21:52 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 10 Jul 2008 19:21:52 -0500 Subject: Can anyone suggest a date peocedure... In-Reply-To: References: Message-ID: RV wrote: > On Thu, 10 Jul 2008 13:39:29 -0700, Gary Herron > wrote: > > >> The datetime module has what you need. >> >> It has methods (with examples) on building a datetime object from a >> string, and it has a object named timedelta, and the ability to subtract >> a timedelta from a time. >> >> For instance, the time right now and the time exactly one day ago: >> >>>>> from datetime import * >>>>> datetime.today() >> datetime.datetime(2008, 7, 10, 13, 38, 48, 279539) >>>>> datetime.today()-timedelta(1) >> datetime.datetime(2008, 7, 9, 13, 38, 50, 939580) >> >> >> Gary Herron > > Thanks Gary! This works great. Now all I need to know is how to > plug the date into the datetime object from a string. > > Ron > I really shouldn't do this until you have put forth at least a little effort... Type the following into the Python interpreter: >>>import datetime >>>help(datetime.datetime.strptime) Help on built-in function strptime: strptime(...) string, format -> new datetime parsed from a string (like time.strptime()). Note: Looking in Python manual or Googling for time.strptime (to get proper format for YYYYMMDD) dstr = "20070710" dt = datetime.datetime.strptime(dstr, "%Y%m%d") >>>dt datetime.datetime(2008, 7, 10, 0, 0) -Larry From toby at tobiah.org Thu Jul 10 15:03:06 2008 From: toby at tobiah.org (Tobiah) Date: Thu, 10 Jul 2008 12:03:06 -0700 Subject: sort(cmp=func) References: Message-ID: On Wed, 09 Jul 2008 20:58:32 -0700, Daniel Fetchinson wrote: >> I have a list of objects that generate code. Some >> of them depend on others being listed first, to >> satisfy dependencies of others. >> >> I wrote a cmp function something like this: >> >> def dep_cmp(ob1, ob2): >> >> if ob1.name in ob2.deps: >> return -1 >> else: >> return 1 >> >> I also tried returning 0 when there were no dependency >> relationships between the objects. >> >> This failed, because every object was not compared with >> ever other. I imagine that this is because sort assumes >> that if a > b and b > c, then a > c. In my case, this >> isn't really true. If a is not dependent on b, and >> b is not dependent on c, that doesn't mean that a is not >> dependent on c. >> >> Is there a better way? > > It's only meaningful to talk about sorting if your particular > definition of "<" is transitive. I.e. a < b and b < c should imply a < > c. If this is not satisfied, it doesn't make sense to sort according > to your "<" definition. It's just not a well-defined operation and no > trick will make it work. There is a meaningful relationship here however. Basically, some items must precede some other items. There are more than one correct orders however. Here was my eventual solution. I had to compare each item with each other item, swapping on failed dependencies. Recursion simplified this greatly: def dep_sort(tables): for this_index in range(len(tables)): this_table = tables[this_index] for prev_index in range(this_index): prev_table = tables[prev_index] if this_table.name in prev_table.deps: tables[prev_index] = this_table tables[this_index] = prev_table dep_sort(tables) return ** Posted from http://www.teranews.com ** From robert.kern at gmail.com Wed Jul 9 22:17:02 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 09 Jul 2008 21:17:02 -0500 Subject: TypeError, I know why but not how!? In-Reply-To: <03cbb0d2-6a0c-4b86-a75e-b73c5677acc7@c65g2000hsa.googlegroups.com> References: <03cbb0d2-6a0c-4b86-a75e-b73c5677acc7@c65g2000hsa.googlegroups.com> Message-ID: ssecorp wrote: > Im looking into PvsNP: > http://www.claymath.org/millennium/P_vs_NP/ > so I thought I'd write the program just to get a feel for it. > > > But I run into a problem. Why does it all the sudden return None? I > mean I know why the program aborts but I dont understand why the None > is generated all the sudden. Hitting recursion depth isn't reported > with that error. def validate(placed): student = round(random.random()*401) if student in placed: # You need to explicitly return, here: return validate(placed) else: placed.append(student) return student, placed -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From maric at aristote.info Wed Jul 30 05:09:01 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 30 Jul 2008 11:09:01 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <2ac250ee-131d-44a3-9b0a-f2fb34758147@c65g2000hsa.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <2ac250ee-131d-44a3-9b0a-f2fb34758147@c65g2000hsa.googlegroups.com> Message-ID: <200807301109.02110.maric@aristote.info> Le Tuesday 29 July 2008 23:48:31 giltay at gmail.com, vous avez ?crit?: > Here's a function, print_members. ?It's just something that takes some > iterable and prints its members in XML. ?It's special-cased so that an > empty iterable gets an empty tag. ?(This is a bit of a trivial > example, I admit; the point is that the empty iterable is a special > case.) > > def print_members(iterable): > ? ? if not iterable: > ? ? ? ? print '' > ? ? ? ? return > ? ? print '' > ? ? for item in iterable: > ? ? ? ? print '%s' % item > ? ? print '' > > ... > So print_members can work on iterables that have no len(), and handle > the special case of an empty iterable, as long as __nonzero__ is > implemented. > But iterables can have no notion of emptiness too : >>>[25]: print_members((e for e in range(0))) Your function is just wrong assuming that, it should be written : >>>[31]: def print_members(iterable): print '' print '%s' % item print empty and '/>' or '' ....: ....: >>>[40]: print_members((e for e in range(0))) >>>[41]: print_members((e for e in range(1))) 0 > Counterexample: > > While "if x" works well in some circumstances, I don't like using it > for purely numeric types. ?For instance, I have a mutable Signal class > for doing some basic DSP. ?Among other things, I can apply a DC offset > to the signal (it just adds the offset to all the samples). ?I have a > special case for an offset of 0 so I don't have to loop through all > the samples (I also have a two-pass remove_offset method that > subtracts the average; if it's already properly centred, I can skip a > step). > > class Signal: > ? ? [...] > ? ? def dc_offset(self, amount): > ? ? ? ? if amount == 0: > ? ? ? ? ? ? return > ? ? ? ? self.samples = [sample + amount for sample in self.samples] This function is also wrong assuming that because amount compare to zero, it can be added to sample. If you want to make type checking just check the type or convert your parameter to an int, but the test "== 0" is of no help here. The only valuable point I see for this idiom is to make more explicit I am testing a numerical value. But your example is a good objection to this, with well chosen name, ie. amount, it's quite clear "if not amount :" is testing the zero value of a numerical value. -- _____________ Maric Michaud From peter.bulychev at gmail.com Wed Jul 2 10:27:46 2008 From: peter.bulychev at gmail.com (Peter Bulychev) Date: Wed, 2 Jul 2008 18:27:46 +0400 Subject: convert unicode characters to visibly similar ascii characters In-Reply-To: <040bbdba-169b-4340-aa76-a7d2d0954346@34g2000hsf.googlegroups.com> References: <040bbdba-169b-4340-aa76-a7d2d0954346@34g2000hsf.googlegroups.com> Message-ID: Thank you. That is exactly what I was looking for. 2008/7/2 Jim : > Peter Bulychev wrote: > > I want to convert unicode character into ascii one. > You have to make some arbitrary choices of what to translate. Based > on some materials on effbot's site, and a recipe, I made > ftp://alan.smcvt.edu/hefferon/unicode2ascii.py > which has at least some of what you are looking for. > $ grep HYPHEN unicode2ascii.py > u'\N{SOFT HYPHEN}':u'-', > u'\N{HYPHEN}':u'-', > u'\N{NON-BREAKING HYPHEN}':u'-', > u'\N{SOFT HYPHEN}': '-', > No doubt I have some terrible gaffes and some things missing. > Corrections appreciated. > > Jim > -- > http://mail.python.org/mailman/listinfo/python-list > -- Best regards, Peter Bulychev. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jordanrastrick at gmail.com Thu Jul 24 10:07:02 2008 From: jordanrastrick at gmail.com (Jordan) Date: Thu, 24 Jul 2008 07:07:02 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <88cec87e-e381-4d07-907a-0cec63f4efcb@u36g2000pro.googlegroups.com> <1de235af-4245-41aa-9091-bb7b112f4ce5@n33g2000pri.googlegroups.com> Message-ID: <20b5e80c-ba2a-4cd0-9a6a-beeef6134839@r35g2000prm.googlegroups.com> > Personally, I think it has more to do with statements like "there are > plenty of smart Python programmers who will > justify all kinds of idiocy in the name of their holy crusade" than > with your position. You don't begin a discussion by discrediting > anyone who might disagree with you as some kind of religious bigot > while simultaneously holding that you are the only sane voice > speaking. I didn't set out to discredit anyone who might disagree with me; in fact I didn't in anyway try to pre-empt any person who might disagree with my thesis. I merely stated an observation - I have in the past seen seemingly intelligent people take silly stands in the name of Explicit is greater than Implicit (not just on comp.lang.python, and not just concerning != or self). I wish in retrospect I'd had the time, patience and focus to edit the initial post to make it more measured and less inflammatory, because its clear the tone detracts from the argument I'm making, which I feel still stands. So if you wish, ignore the specifics of the frustration that inspired me and consider only the thrust of what I'm saying: "Explicit is better than Implict" considered harmful. Discuss. From alexandre.Fayolle at logilab.fr Thu Jul 31 10:09:52 2008 From: alexandre.Fayolle at logilab.fr (alexandre.Fayolle@logilab.Fr) Date: Thu, 31 Jul 2008 07:09:52 -0700 (PDT) Subject: working pylint anyone? References: <6fdf17Fb2bboU1@mid.uni-berlin.de> <8a08b59f-f7f0-4706-84c9-19f0460f09ef@k30g2000hse.googlegroups.com> <6fdq70Fb1t79U1@mid.uni-berlin.de> Message-ID: <8ffa9c09-4538-459e-b81c-2f437113dfa4@x35g2000hsb.googlegroups.com> On Jul 31, 2:39?pm, "Diez B. Roggisch" wrote: > > Which version of python-logilab-common and python-logilab-astng are > > installed on your machine ? > > By now, pylint 0.14 with logilab.common 0.27 and astng 0.17.2 > > I was able to track down the problem as being related to a custom init-hook. > > See the attached .pylintrc + hook. They don't actually *do* anything (or, > the hook that is), but confuse pylint to spit out the reported error. Maybe > you can track down the real reason for the error? Congratulation ! you've found a pylint bug (or more likely a logilab- common bug in our wrapper of optparse/optik) :-/ I have added it to our tracker (http://www.logilab.org/ticket/5677) and it should be fixed in the next release of pylint or logilab-common. > > I don't know where you checked, but there is some traffic on the > > mailing list, > > and questions generally get answered :-) > > On the website, I found this link: > > http://www.logilab.org/mailinglist/850 > > through the search. Ouch, this is actually a nasty bug on our site. I'm going to see what I can do about it. In the meantime, you may consider subscribing directly from http://lists.logilab.org/mailman/listinfo/python-projects -- Alexandre Fayolle LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services Informatique scientifique: http://www.logilab.fr/science From python at hope.cz Wed Jul 30 12:22:51 2008 From: python at hope.cz (Johny) Date: Wed, 30 Jul 2008 09:22:51 -0700 (PDT) Subject: Is there a such Python module ? Message-ID: Is there a Python module that can help with reading SMS message from a mobile phone? Or is there an example how to read SMS message using a program written in Python,C, or any other language? Thank you very much for help L. From gagsl-py2 at yahoo.com.ar Wed Jul 30 00:56:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 30 Jul 2008 01:56:28 -0300 Subject: Defunct when using subprocess.Popen References: <6D3D064BBC122445A4577CE1895FA06501755913@afsegbgex1.af.se> Message-ID: En Tue, 29 Jul 2008 10:04:46 -0300, Gordon Maria escribi?: > I'm running a GUI in python which is able to launch a separate python > process > that will run forever. In rare cases I will want to kill the launched > process. > Every time I do so, I end up with the process as defunct. Can anybody > help me > clean it up in a nice way? > > On request from GUI I do the following: > os.kill(process.pid,9) > > FYI, it is all running on Linux. You should call os.waitpid() after killing the child process, to let the OS free the resources allocated to it. -- Gabriel Genellina From george.sakkis at gmail.com Mon Jul 7 10:11:57 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 7 Jul 2008 07:11:57 -0700 (PDT) Subject: Dynamically Changing the Base Class References: <6d60c362-ba17-4414-babd-2cc254526bca@c58g2000hsc.googlegroups.com> Message-ID: On Jul 7, 9:31?am, "Adam C." wrote: > We have a situation where we want a Swig-generated Python class to > have a different base (not object). It doesn't appear that we can > coerce Swig into generating the class we want at present (but we are > still enquiring). > > Is it possible to dynamically change the base class to something else? > Initial experiments appear to show it is not: > -------------------------------- snip -------------------------------->>> class Foo(object): > > ? ? ? ? pass > > >>> class Foozle(object): > > ? ? ? ? pass > > >>> Foozle.__bases__ = (Foo,) > > Traceback (most recent call last): > ? File "", line 1, in > ? ? Foozle.__bases__ = (Foo,) > TypeError: __bases__ assignment: 'Foo' deallocator differs from > 'object' > -------------------------------- snip -------------------------------- > > Is there a solution I am missing? > > Thanks in advance. Supposedly it should (usually) work, there's a 6 year old patch for this (http://bugs.python.org/issue635933). Check if Swig can generate old-style classes (i.e. not inheriting from object) since __bases__ assignment works for them. HTH, George From larry.bates at websafe.com` Tue Jul 22 14:16:15 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 22 Jul 2008 13:16:15 -0500 Subject: Authentication for XML-RPC Calls In-Reply-To: <3e4258ac-40d8-485d-ba65-39d343b9561d@2g2000hsn.googlegroups.com> References: <3e4258ac-40d8-485d-ba65-39d343b9561d@2g2000hsn.googlegroups.com> Message-ID: whitemice wrote: > The only documentation regarding doing authentication for XML-RPC I > can find is - > > "Both the HTTP and HTTPS transports support the URL syntax extension > for HTTP Basic Authentication: http://user:pass at host:port/path. The > user:pass portion will be base64-encoded as an HTTP `Authorization' > header, and sent to the remote server as part of the connection > process when invoking an XML-RPC method. You only need to use this if > the remote server requires a Basic Authentication user and password." > > - from http://docs.python.org/lib/module-xmlrpclib.html > > Is this really the only way to do authentication for XML-RPC calls? > > Like this: > server = xmlrpclib.Server('http://adam:fred123 at localhost/zidestore/so/ > adam/' > > This works, but is pretty ugly. Is there no way to setup the > authentication through properties (like in most XML-RPC bindings), > like: > > server = xmlrpclib.Server('http://localhost/zidestore/so/adam/' > server.Username = 'adam' > server.Password = 'fred123' Just write a little factory class that does it for you: import urlparse class myauth(object): def __init__(self, scheme = None, domain = None, path = None): self.scheme = scheme self.domain = domain self.path = path self.Username = None self.Password = None def __str__(self): for attr in ['scheme', 'domain', 'path', 'Username', 'Password']: if getattr(self, attr) is None: raise ValueError('No %s attribute value given' % attr) url=urlparse.urlunsplit((self.scheme, '%s:%s@%s' % (self.Username, self.Password, self.domain), self.path, '', '')) return url if __name__ == "__main__": auth = auth = myauth(scheme = 'http', domain = 'localhost', path='/zidestore/so/adam/') auth.Username = 'adam' auth.Password = 'fred123' print auth In program auth = myauth(scheme = 'http', domain = 'localhost', path = '/zidestore/so/adam') auth.Username = 'adam' auth.Password = 'fred123' print auth 'http://adam:fred123 at docs.python.org/params;/lib/module-xmlrpclib.html' >>> -Larry From jwkenne at attglobal.net Tue Jul 22 15:57:21 2008 From: jwkenne at attglobal.net (John W Kennedy) Date: Tue, 22 Jul 2008 15:57:21 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: <48863ba1$0$5000$607ed4bc@cv.net> Rob Warnock wrote: > Thunks were something used by Algol 60 > *compiler writers* in the code generated by their compilers to > implement the semantics of Algol 60 call-by-name, but were not > visible to users at all [except that they allowed call-by-name > to "work right"]. ...unless you were a system programmer and had to write Algol-friendly assembler. -- John W. Kennedy "Give up vows and dogmas, and fixed things, and you may grow like That. ...you may come to think a blow bad, because it hurts, and not because it humiliates. You may come to think murder wrong, because it is violent, and not because it is unjust." -- G. K. Chesterton. "The Ball and the Cross" From Maria.Gordon at afconsult.com Tue Jul 29 09:04:46 2008 From: Maria.Gordon at afconsult.com (Gordon Maria) Date: Tue, 29 Jul 2008 15:04:46 +0200 Subject: Defunct when using subprocess.Popen Message-ID: <6D3D064BBC122445A4577CE1895FA06501755913@afsegbgex1.af.se> An HTML attachment was scrubbed... URL: From francofuji at gmail.com Wed Jul 9 14:56:27 2008 From: francofuji at gmail.com (Francisco Perez) Date: Wed, 9 Jul 2008 14:56:27 -0400 Subject: About Google App Engine Message-ID: <30fdaa240807091156o2540b1ccpfd22f4e36fbf98d1@mail.gmail.com> Hello every body: Recently the Google boy's announce their last toy: Google App Engine, a really great idea. Although the GAE site have documentations and guides, i think it not covers the some of the best practices when we really build a web site. I mean layers, design patterns, etc. In the link bellow [1] we can find a completelly functional Ads site. And the best thing is that for all tht people like me that are not too good in english, the site has a Help (Ayuda) that explains the Maiking Of (Como se Hizo) of de site. There is a great explanation in spanish of MVC patterns and hot apply it building a web site. Check it. [1] http://bazar.appspot.com From babacity2 at gmail.com Thu Jul 24 16:57:18 2008 From: babacity2 at gmail.com (babacity2 at gmail.com) Date: Thu, 24 Jul 2008 13:57:18 -0700 (PDT) Subject: Shown on efukt com - Amazing porn video collection Message-ID: shown on efukt com . >>>>>>>>>>Best Collection of Efukt Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE shown on efukt com VIDEOS<<<<<<<<<<< . shown on efukt com From castironpi at gmail.com Tue Jul 29 23:28:48 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 29 Jul 2008 20:28:48 -0700 (PDT) Subject: static variables in Python? References: <115a132d-7edd-4b07-ba4f-7855577992d1@x41g2000hsb.googlegroups.com> Message-ID: On Jul 29, 8:38?pm, pigmartian wrote: > bearophileH... at lycos.com wrote: > > kj: > >> OK, I guess that in Python the only way to do what I want to do > >> is with objects... > > > There are other ways, like assigning the value out of the function, > > because Python functions too are objects: > > ... > > But I suggest you to use a class in this situation, it's often the way > > that will keep your code more bug-free, and more readable by near- > > casual readers too. Python philosophy asks you to write readable code > > instead of clever code when possible, this is a difference from Perl, > > I presume. > > > Bye, > > bearophile > > Here's a solution using decorators, I like it, but I'm biased: > > def staticAttrs(**kwds): > ? ? ? ? """ > ? ? ? ? Adds attributes to a function, akin to c-style > ? ? ? ? "static" variables > ? ? ? ? """ > > ? ? ? ? def _decorator(fcn): > ? ? ? ? ? ? ? ? for k in kwds: > ? ? ? ? ? ? ? ? ? ? ? ? setattr(fcn, k, kwds[k]) > ? ? ? ? ? ? ? ? return fcn > ? ? ? ? return _decorator > > @staticAttrs(n=0) > def rememberCalls(): > ? ? ? ? """ > ? ? ? ? >>> rememberCalls() > ? ? ? ? 0 > ? ? ? ? >>> rememberCalls() > ? ? ? ? 1 > ? ? ? ? >>> rememberCalls() > ? ? ? ? 2 > ? ? ? ? """ > ? ? ? ? print rememberCalls.n > ? ? ? ? rememberCalls.n += 1 > > ~Scott I like it too. It also thought of (implementation not shown): @has_locals def rememberCalls( self ): self.val= 0 self.ref= object( ) where self is preserved between calls and is an instance of a custom class, possibly empty. If you want more than one, but still preserved: rememberCallsA= has_locals( rememberCalls ) rememberCallsB= has_locals( rememberCalls ) You might want to make self a small and lightweight dict-only object: @has_locals def rememberCalls( dic ): dic['val']= 0 dic['ref']= object( ) From exarkun at divmod.com Tue Jul 29 10:47:53 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 29 Jul 2008 10:47:53 -0400 Subject: block/lambda In-Reply-To: <0b6a5dff-dae5-4cd8-9dfd-18737c4a8746@f36g2000hsa.googlegroups.com> Message-ID: <20080729144753.29191.615503627.divmod.quotient.8219@ohm> On Tue, 29 Jul 2008 07:26:38 -0700 (PDT), "jiri.zahradil at gmail.com" wrote: > >> 2. Will it be possible in Python 3.0 to do the following: >> >> >>> def dotimes(n, callable): >> >> for i in range(n): callable() >> >> >>> def block(): >> >> nonlocal i >> for j in range(i): >> print j, >> print > >dotimes seems ok and what is wrong with that function "block"? You do >not need to specify that i is "nonlocal", global i will be used. > >>>> i=10 >>>> def block(): > for j in range(i): > print j, > print >>>> block() >0 1 2 3 4 5 6 7 8 9 > Python doesn't have dynamic scoping. >>> def dotimes(n, callable): ... for i in range(n): ... callable() ... >>> def block(): ... for j in range(i): ... print j, ... print ... >>> def f(): ... dotimes(5, block) ... >>> f() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in f File "", line 3, in dotimes File "", line 2, in block NameError: global name 'i' is not defined >>> The "nonlocal" keyword in Python 3 won't do this, either. It's for referencing names in outer lexical scopes, not outer dynamic scopes. Jean-Paul From usenet at solar-empire.de Tue Jul 29 09:26:55 2008 From: usenet at solar-empire.de (Marc Christiansen) Date: Tue, 29 Jul 2008 15:26:55 +0200 Subject: Swap memory in Python ? - three questions References: Message-ID: Robert LaMarca wrote: > Hi, > > I am using numpy and wish to create very large arrays. My system is > AMD 64 x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a > 15 GB swap drive. > > The command I have been trying to use is; > g=numpy.ones([1000,1000,1000],numpy.int32) > > This returns a memory error. Works for me on AMD64x2, 2GB RAM, 3GB swap. With much paging of course ;) Process size of python 4019508kB. > A smaller array ([500,500,500]) worked fine.. About 0.5GB.. no surprise. > Two smaller arrays again crashed the system. Crash as in "computer reboots"? Strange. And you say, that two [500, 500, 500] arrays are two much? > So... I did the math. a 1000x1000x1000 array at 32 bits should be > around 4gb RAM... Obviously larger than RAM, but much smaller than the > swap drive. Sounds like either your kernel or python are not 64bit. For the kernel, have a look at /proc/meminfo, which value you get for VmallocTotal. I have VmallocTotal: 34359738367 kB. For python, check sys.maxint. If it's 2147483647, then you have a 32bit python. Mine says 9223372036854775807. > 1. So... does Numpy have a really lot of overhead? Or is my system > just not somehow getting to make use of the 15gb swap area. No. Yes. > 2. Is there a way I can access the swap area, or direct numpy to do > so? Or do I have to write out my own numpy cache system... > 3. How difficult is it to use data compression internally on numpy > arrays? 2 + 3: Should not be necessary. I just tried a 32bit python on my 64bit system, using Numeric instead of numpy (don't have a 32bit numpy ready): g=Numeric.zeros([1000,1000,1000],Numeric.Int32) Traceback (most recent call last): File "", line 1, in MemoryError: can't allocate memory for array g=Numeric.zeros([1000,1000,500],Numeric.Int32) succeeds. So it looks like you have a 32bit kernel. Marc From ptmcg at austin.rr.com Thu Jul 31 18:58:01 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 31 Jul 2008 15:58:01 -0700 (PDT) Subject: find and replace with regular expressions References: Message-ID: <8160cc86-d0bd-444a-bc93-da732c76e3bb@c65g2000hsa.googlegroups.com> On Jul 31, 3:07?pm, chrispoliq... at gmail.com wrote: > > middle_abbr = re.compile('[A-Za-z0-9]\.[A-Za-z0-9]\.') > When defining re's with string literals, it is good practice to use the raw string literal format (precede with an 'r'): middle_abbr = re.compile(r'[A-Za-z0-9]\.[A-Za-z0-9]\.') What abbreviations have numeric digits in them? I hope your input string doesn't include something like this: For a good approximation of pi, use 3.1. -- Paul From stochashtic at yahoo.ca Mon Jul 28 03:40:19 2008 From: stochashtic at yahoo.ca (Suresh Pillai) Date: 28 Jul 2008 09:40:19 +0200 Subject: Execution speed question References: <4889a36f$1@news2-rz-ap.ethz.ch> <11c87113-8c09-4f47-b6b9-cfdfc4ea83ba@n33g2000pri.googlegroups.com> <1f2b72e1-689d-4ea3-8f69-a2c797725f97@z6g2000pre.googlegroups.com> <4889e5bc$1@news2-rz-ap.ethz.ch> <331bd56e-e446-4b08-bf72-be7482051f32@y22g2000prd.googlegroups.com> Message-ID: <488d77e3$1@news2-rz-ap.ethz.ch> On Fri, 25 Jul 2008 08:08:57 -0700, Iain King wrote: > On Jul 25, 3:39 pm, Suresh Pillai wrote: >> That's a good comparison for the general question I posed. Thanks. >> Although I do believe lists are less than ideal here and a different >> data structure should be used. >> >> To be more specific to my case: >> As mentioned in my original post, I also have the specific condition >> that one does not know which nodes to turn ON until after all the >> probabilities are calculated (lets say we take the top m for example). >> In this case, the second and third will perform worse as the second one >> will require a remove from the list after the fact and the third will >> require another loop through the nodes to build the new list. > > So you need to loops through twice regardless? i.e. loop once to gather > data on off nodes, do some calculation to work out what to turn on, then > loop again to turn on the relevant nodes? If so, then I think the > functions above remain the same, becoming the 2nd loop. Every iteration > you do a first loop over the off_nodes (or them all for (1)) to gather > the data on them, perform your calculation, and then perform one of the > above functions (minus the setup code at the begining; basically > starting at the 'for') as a second loop, with the goes_on function now > returning a value based on the calculation (rather than the calculation > itself as I had it). Performance should be similar. > > Iain If do I settle on an explicit loop to remove the nodes turned ON, then I realised this weekend that I could do this in the next iteration of the simulation (first loop above) and save some iteration overhead (the if checking will still be there of course). And thanks for pointing out that constructing a new list, for long lists, is faster than simple removal. It's obvious but I never really thought of it; good tip. From marcus at internetnowasp.net Sat Jul 12 22:08:22 2008 From: marcus at internetnowasp.net (Marcus Low) Date: Sun, 13 Jul 2008 10:08:22 +0800 Subject: Someone enlightened me Message-ID: <48796396.9090805@internetnowasp.net> Can someone explain to me, why the behaviour below is different when u remark "lister" and unremark "self.lister"? #-------------------------------------------------------------- class abc : # remark this later and unremark "self.lister" lister = [] def __init__ (self, val): #self.lister = [] self.lister.append(val) #-------------------------------------------------------------- globallist = [] #-------------------------------------------------------------- def test () : global l for x in range(10) : o = abc(x) globallist.append(o) o = "" for i in globallist : print i.lister #-------------------------------------------------------------- test() #-------------------------------------------------------------- From jstrickler at gmail.com Wed Jul 16 16:59:51 2008 From: jstrickler at gmail.com (John S) Date: Wed, 16 Jul 2008 13:59:51 -0700 (PDT) Subject: how to match whole word References: <97461ec5-151a-4527-a5fa-c5da07941e46@l42g2000hsc.googlegroups.com> Message-ID: <31b6a6c2-e152-418d-b5a1-477dc3dd15aa@s50g2000hsb.googlegroups.com> On Jul 16, 9:38 am, Peng Yu wrote: > On Jul 15, 10:29 pm, Gary Herron wrote: > > > > > Peng Yu wrote: > > > Hi, > > > > The following code snippet is from /usr/bin/rpl. I would like the it > > > to match a word, for example, "abc" in ":abc:". But the current one > > > would not match "abc" in ":abc:". I tried to modify it myself. Would > > > you please let me know what is the corrected way to do it? > > > > Thanks, > > > Peng > > > > if opts.whole_words: > > > regex = re.compile(r"(?:(?<=\s)|^)" + re.escape(old_str) + r"(?=\s| > > > $)", > > > opts.ignore_case and re.I or 0) > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > The regular expression "\w+" will match (what might be your definition > > of) a word, and in particular will match abc in :abc:. Regular > > expressions have lots of other special \-sequences that might be worth > > your while to read about: http://docs.python.org/lib/re-syntax.html > > > Gary Herron > > I didn't read the docs and tried the following code. > > regex = re.compile(r"\A" + re.escape(old_str) + r"\Z", > opts.ignore_case and re.I or 0) > > But I'm not sure why it is not working. > > Thanks, > Peng Not sure why you picked \A and \Z -- they are only useful if you are using the re.M flag. What you want is \b -- match word boundary, on either side of your word: regex = re.compile(r"\b" + re.escape(old_str) + r"\b",re.I) re.I is the same as re.IGNORECASE. More than one option may be OR'ed together. There's no such thing as "re.O" in Python. I can understand where you get the idea, as there is an 'o' modifier for REs in Perl. To summarize, \A and \Z match the beginning and end of a STRING, while \b matches the beginning or end of a WORD. -- john From modelnine at modelnine.org Tue Jul 29 05:15:05 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Tue, 29 Jul 2008 11:15:05 +0200 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: <200807291115.05701.modelnine@modelnine.org> Am Dienstag, 29. Juli 2008 10:37:45 schrieb Carl Banks: > You keep bringing up this notion of "more complex with no benefit", > which I'm simply not interested in talking about that at this time, > and I won't respond to any of your points. I am seeking the answer to > one question: whether "if x" can usefully do something a simple > explicit test can't. Everyone already knows that "if x" requires > fewer keystrokes and parses to fewer nodes. Yes, there are quite a lot of use cases. Think of a polymorphic function, where the input can be any object that implements the iterator protocol (concerning base types, I'm thinking of strings, tuples, lists, dicts and sets here, which are all iterable and yield a chain of singular values) and you want to check whether the iterable object is empty or not for special-casing that. "if x" uses the special interface method __nonzero__() if that's implemented (which all of the above types implement as returning True iff the container yields at least one value when iterated over, i.e., it isn't empty), and falls back to a test for __len__() != 0, otherwise x is considered to be true. Now, explicitly comparing x against the five "empty" values of the container types I specified above would be broken design in such a function: when I implement a container class myself, which implements the __iter__() and __nonzero__() methods, I can directly use it with the polymorphic function I wrote, and the special case for an empty container will work out of the box. In the case of explicit comparisons, I have to modify the polymorphic function to accept my container type in addition to those it already processes to be able to special-case the empty container for my type. I can't dig up a simple example from code I wrote quickly, but because of the fact that explicit comparisons always hamper polymorphism (which might not be needed initially, but you never know what comes up later, thinking of reusability of components), I personally always stick to the idiom "if x" rather than comparing it to an empty value, even when I'm sure that the type of x is a singular type. Additionally, IMHO "if x" is so much more readable than "if x != ". Just my 2 (euro)cents. -- Heiko Wundram From bsagert at gmail.com Wed Jul 16 13:42:18 2008 From: bsagert at gmail.com (bsagert at gmail.com) Date: Wed, 16 Jul 2008 10:42:18 -0700 (PDT) Subject: For_loops hurt my brain. Message-ID: <4874c21f-befa-4e9f-a99d-486cc9c9b5b8@d77g2000hsb.googlegroups.com> This script uses a simple for loop to zip some files. However I am repeating code that cries out for a nested loop. My two lists of files_to_be_zipped (spare and seekfacts) are of uneven length so I can't seem to decipher the "for_logic". I would appreciate any help. Thanks, Bill import zipfile import os zips = [ 'c:/spare.zip', 'c:/seekfacts.zip' ] spare = [ 'c:/spare/huge.fm3', 'c:/spare/huge.wk3' ] seekfacts = [ 'c:/seekfacts/bookmark.html', 'c:/seekfacts/index.htm', 'c:/seekfacts/seek.css', 'c:/seekfacts/seek.js' ] zFile = zipfile.ZipFile(zips[0], 'w') for files in spare: zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED) zFile.close() zFile = zipfile.ZipFile(zips[1], 'w') for files in seekfacts: zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED) zFile.close() From draeath.spamtrap at gmail.com Thu Jul 24 22:26:09 2008 From: draeath.spamtrap at gmail.com (draeath) Date: Fri, 25 Jul 2008 02:26:09 GMT Subject: Your message to CMake awaits moderator approval References: Message-ID: On Thu, 24 Jul 2008 18:43:34 -0400, cmake-bounces wrote: > Your mail to 'CMake' with the subject > > Status > > Is being held until the list moderator can review it for approval. > > The reason it is being held: > > Post by non-member to a members-only list > > Either the message will get posted to the list, or you will receive > notification of the moderator's decision. If you would like to cancel > this posting, please visit the following URL: > > Should this be showing up in a usenet group? From stefan_ml at behnel.de Fri Jul 11 01:31:41 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 11 Jul 2008 07:31:41 +0200 Subject: B-Soup: broken iterator, tag a keyword? In-Reply-To: <413d8bc0-6156-4502-93c1-8c8790128f56@d45g2000hsc.googlegroups.com> References: <413d8bc0-6156-4502-93c1-8c8790128f56@d45g2000hsc.googlegroups.com> Message-ID: <4876F03D.40407@behnel.de> Hi, Brendan wrote: > I have the following using Beautiful Soup: > > soup = BeautifulSoup(data) > tags = soup.findAll(href=re.compile("/MER_FRS_L2_Canada/MER_FRS_\S > +gz")) > for tag in tags: > print tag['href'] > print tag.parent.nextSibling.string > print tag.parent.nextSibling.nextSibling.string > print tag.parent.nextSibling.nextSibling.nextSibling.string > print > tag.parent.nextSibling.nextSibling.nextSibling.nextSibling.contents[0].string It's pretty impossible that the problem is the name "tag" here. But since you didn't state what the actual problem is, let me suggest not to parse markup with regular expressions in general (which BS does). Use a real XML/HTML parser for that. lxml will work just fine (and it also has a nicer API). http://codespeak.net/lxml/ Stefan From rridge at csclub.uwaterloo.ca Thu Jul 31 04:24:48 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Thu, 31 Jul 2008 04:24:48 -0400 Subject: Change PC to Win or Windows References: Message-ID: Dennis Lee Bieber wrote: > It gets even worse... No Windows-based "PC" has ever used the >"PowerPC" processor -- which had been a staple of the Macintosh before >they went Intel... Actually the were personal computers sold using PowerPC processors that ran Windows NT. I even remember seeing one that had ISA slots. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From jkugler at bigfoot.com Tue Jul 1 14:25:48 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Tue, 01 Jul 2008 10:25:48 -0800 Subject: Classes for processing/parsing Wiki Markup text References: <170543c70807010931x16938234n9df68ee3c6d0319a@mail.gmail.com> Message-ID: Michael Mabin wrote: > Does anyone know if there are any generally available classes for parsing > various wiki markup formats? Several here: http://pypi.python.org/pypi?%3Aaction=search&term=wiki&submit=search I'm sure you could find a good one, and add your own markup if needed. j From gh at ghaering.de Mon Jul 28 07:01:58 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 28 Jul 2008 13:01:58 +0200 Subject: Google Group: architectgurus In-Reply-To: References: Message-ID: Dear Guru, Sudhakar Chavali wrote: > Hi > > I have created a group called architectgurus (http://groups.google.com/ > group/architectgurus) or architectgurus at googlegroups.com . > Irrespective of technology, vendor, domain I will be discussing and > share my thoughts in homogenous and harmonious way. If you are > interested *even you* can join and contribute your thoughts in this > group. My intention doing these activities is to spread the knowledge > and thoughts across the globe. What? even me? That's really nice of you. -- Gerhard From bulg at ngs.ru Mon Jul 14 03:25:15 2008 From: bulg at ngs.ru (Yosifov Pavel) Date: Mon, 14 Jul 2008 00:25:15 -0700 (PDT) Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> <6e0564F4bvr4U2@mid.uni-berlin.de> Message-ID: <1ca3ddf2-7d41-44ae-8b5a-80d7be7b88eb@f36g2000hsa.googlegroups.com> > `tee()` doesn't copy the iterator or its internal state but just caches > it's results, so you can iterate over them again. That makes only sense > if you expect to use the two iterators in a way they don't get much out of > sync. If your usage pattern is "consume iterator 1 fully, and then > re-iterate with iterator 2" `tee()` has no advantage over building a list > of all results of the original iterator and iterate over that twice. > `tee()` would be building this list anyway. It's interesting and a concrete answer. Thanks a lot. > Because it's often not possible without generating a list with all > results, and the advantage of a low memory footprint is lost. > > Ciao, > Marc 'BlackJack' Rintsch Seems like "monada". But I think is possible to determine when there is a bounded external state (side-effects) or not, may be is needed some new class-protocol for it... or something else. Or another way: iterators may be re-iterable always, but if programmer need to point to the extra- (external) state, he has to raise some a special exception in __iter)) method... OK, it's only fantasies about language design :-) --pavel From sjmachin at lexicon.net Fri Jul 18 02:32:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 17 Jul 2008 23:32:47 -0700 (PDT) Subject: storing references instead of copies in a dictionary References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> <7c26ca26-be96-4e8c-8eb5-e43bd78e4e70@v21g2000pro.googlegroups.com> Message-ID: <374d1d4f-e958-455c-8e60-048c55bc493f@q28g2000prh.googlegroups.com> On Jul 18, 4:26?pm, castironpi wrote: > I delicately ask for an example in natural language and daily life in > which we change what object a name refers to, her, him, it, ... i.e. any pronoun From phil.lemelin at gmail.com Fri Jul 18 08:38:03 2008 From: phil.lemelin at gmail.com (phil lemelin) Date: Fri, 18 Jul 2008 08:38:03 -0400 Subject: Question regarding os.write() and write() method of a file descriptor Message-ID: Good Day python users, I have a question regarding os.write and the write method of a file descriptor object. My python was written on linux, under python 2.4 and I've recently migrated to python 2.5. My problem came from a pipe I used to to open and write to using : fd = os.open("myfifo","w+") os.write(fd,'some boring stuff\n') os.close(fd) I'm pretty sure that it worked on a previous version of python and linux but, on my mandriva 2008, running python 2.5, I get the following exception : os.write(fd,'some boring stuff\n') exceptions.TypeError: an integer is required Now, I solved my problem by changing my code to the following : fd open("myfifo","w+") fd.write("some less boring stuff\n") fd.close() I still cant explain why it works with the file descriptor method and i'm seeking an explanation. Please, forgive me if it's a dumb question, but i'm just trying to get better at python. I hope someone will take time to help me out. -- Philippe-Alexandre Lemelin -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Jul 24 05:20:05 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 11:20:05 +0200 Subject: Requires a character ... !! In-Reply-To: References: Message-ID: karthikbalaguru wrote: > I am new to python . I am face few problems related with > python and iam trying to resolve it. > > The below is the error that i get when i invoke my application by > giving > the necessary input file. > > [root at localhost hello]# Analyzer hello_input > Loading debug info: hello_input > Traceback (most recent call last): > File "/usr/local/SDK/host/bin/Analyzer", line 694, in ? > app.dbg.readObjectInfo(elf) > File "/usr/local/SDK/host/bin/debugprocessor.py", line 427, in > readObjectInfo > self.privateProcessorDwarfTree.readProcessorDwarfTree(filename) > File "/usr/local/SDK/bin/debugprocessor.py", line 314, in > readDwarfTree > if "DW_OP_reg" in value: > TypeError: 'in ' requires character as left operand > > Is this related with the version conflicts ? > Should i need to configure any environment variables or change some > source code. You should run the code on a Python version that supports the features your code is using. Support for arbitrary strings on the left side of the "in" operator was added in Python 2.3, which was released in 2003. What software is this? If you've written it yourself, make sure to use only features supported by the Python version you're actually using. If it's written by someone else, please read the requirements section for the software you're using, and follow the instructions in there. (hasn't people been telling you this about a hundred times before in this forum? or was that some other guy who also kept insisting on running some program on a python version it didn't support?) From fouff at fouff.com Thu Jul 3 05:34:16 2008 From: fouff at fouff.com (Fouff) Date: Thu, 03 Jul 2008 11:34:16 +0200 Subject: Creating an .exe with Tkinter involved In-Reply-To: References: Message-ID: Alex Bryan a ?crit : > I know this is possible so someone out there should be able to help me! > Okay, I have a program that uses Tkinter, and BeautifulSoup. I don't > think it should be a problem. I want to create an exe of it. I have > py2exe but I don't really know how to work it. I read their tutorial > thing and did a setup that looked something like this: > > from distutils.core import setup > import py2exe > > setup(console['myFunProgram.py']) > > (isn't really called myFunProgram) > > This seems terribly wrong however because... it isn't a console app. So > I am wondering if anyone can show me how or point me in the right > direction to a place where I can learn how to do this. I would > appreciate it! Hi. If your program isn't a concole one, maybe should you rename it .pyw and then in your setup.py file, replace the line > setup(console['myFunProgram.py']) by this one setup(windows=["myFunProgram.pyw"]) I use it under MS windows (I don't know if it is your case too). You will find more informations here http://www.py2exe.org/index.cgi/ListOfOptions and more generally at http://www.py2exe.org/ Fouff From bearophileHUGS at lycos.com Thu Jul 31 13:43:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 31 Jul 2008 10:43:11 -0700 (PDT) Subject: Non Continuous Subsequences References: <9e5a3$4891e9f5$18607848$1746@KNOLOGY.NET> Message-ID: <3e475fac-4ce6-41da-8f7c-1c013756656b@25g2000hsx.googlegroups.com> Bruce Frederiksen: Your solution is a bit different from what I was thinking about (I was thinking about a generator function, with yield), but it works. This line: > return itertools.chain( > itertools.imap(lambda ys: x + ys, ncsub(xs, s + p1)), > ncsub(xs, s + p2)) Can be written in a simpler way: return chain((x + ys for ys in ncsub(xs, s + p1)), ncsub(xs, s + p2)) I'll think more about all this, bye and thank you, bearophile From mariano.mara at gmail.com Thu Jul 3 00:37:15 2008 From: mariano.mara at gmail.com (Mariano Mara) Date: Thu, 03 Jul 2008 01:37:15 -0300 Subject: Queue/Priority Needed In-Reply-To: <21935b370807021426l11f1fa0ayc52593cc184869b3@mail.gmail.com> References: <21935b370807021426l11f1fa0ayc52593cc184869b3@mail.gmail.com> Message-ID: <486C577B.5010809@gmail.com> Keith Nation wrote: > I'm still very new to python, and I have a question about how to > prioritize jobs in a queue. > You can use the python 2.6 priority queue implementation: $ python Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import heapq >>> import Queue >>> >>> class PriorityQueue(Queue.Queue): ... """Variant of Queue that retrieves open entries in ... priority order (lowest first). ... Entries are typically tuples of the form: (priority number, ... data) ... This class can be found at: Python-2.6a3/Lib/Queue.py ... """ ... maxsize = 0 ... def _init(self, maxsize): ... self.queue = [] ... def _qsize(self, len=len): ... return len(self.queue) ... def _put(self, item, heappush=heapq.heappush): ... heappush(self.queue, item) ... def _get(self, heappop=heapq.heappop): ... return heappop(self.queue) ... >>> class example(object): ... def __init__(self, p1, p2, p3, p4): ... self.p1 = p1 ... self.p2 = p2 ... self.p3 = p3 ... self.p4 = p4 ... >>> pq = PriorityQueue() >>> ex = example('Task1', 'v03', '-start', 'Bonnie') >>> pq.put((1, ex)) >>> ex = example('Task3', 'v01', '-start', 'Bob') >>> pq.put((3, ex)) >>> ex = example('Task2', 'v01', '-start', 'Billy') >>> pq.put((2, ex)) >>> pr, ex = pq.get() # prints task 1 >>> print ex.p1, ex.p2, ex.p3, ex.p4 Task1 v03 -start Bonnie >>> pr, ex = pq.get() # prints task 2 >>> print ex.p1, ex.p2, ex.p3, ex.p4 Task2 v01 -start Billy From ethan at stoneleaf.us Mon Jul 7 19:12:27 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 07 Jul 2008 15:12:27 -0800 Subject: numeric emulation and __pos__ Message-ID: <4872A2DB.4090609@stoneleaf.us> Greetings, List! I'm working on a numeric data type for measured values that will keep track of and limit results to the number of significant digits originally defined for the values in question. I am doing this primarily because I enjoy playing with numbers, and also to get some experience with unit testing. At this point I have the __init__ portion finished, and am starting on the various operator functions. Questions for the group: 1) Any reason to support the less common operators? i.e. <<, >>, &, ^, | 2) What, exactly, does .__pos__() do? An example would help, too. Thanks for the feedback. -- Ethan From fredrik at pythonware.com Fri Jul 25 07:50:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Jul 2008 13:50:25 +0200 Subject: Automatically loading and initialising objects from a plugins directory In-Reply-To: <4889B888.8000600@ecs.soton.ac.uk> References: <488607BC.3040204@ecs.soton.ac.uk> <4889B888.8000600@ecs.soton.ac.uk> Message-ID: Dave Challis wrote: > I'll have a look into metaclasses too, haven't stumbled upon those yet > at all. It's a potentially brain-exploding topic, though, so if the above solution works for you, you might want to leave it at that ;-) But very briefly, a metaclass is a something that's responsible for creating a class, much like an ordinary class is responsible for creating an object. When Python executes the following statement, class Spam: attrib = 1 def func(self): pass # <-- end of class statement it will create a new scope for the class content, execute the class body, and then, when it reaches the end, call the "metaclass" to create the actual class object. The metaclass is given the requested name ("Spam" in this case), any base classes, and a dictionary containing everything from the class scope ("attrib" and "func", in this case). The thing that's returned is assigned to the "Spam" variable. The default metaclass ("type") just creates an ordinary class object, but if you replace that with your own metaclas, you can completely override that behaviour, or just extend it (e.g. by registering the subclasses in a common registry). Like, say, this: registry = [] # list of subclasses class Plugin(object): class __metaclass__(type): def __init__(cls, name, bases, dict): type.__init__(name, bases, dict) registry.append((name, cls)) class SpamPlugin(Plugin): pass class BaconPlugin(Plugin): pass for name, cls in registry: if cls is not Plugin: print name, cls Here, the presence of an inner __metaclass__ class (which is a subclass of "type") causes Python's class machinery to use that class instead of "type" when creating class objects for Plugin or any subclass thereof. The extra code in the __init__ method just all plugins to a list. For more on this, see e.g. http://www.python.org/download/releases/2.2/descrintro/#metaclasses From dullrich at sprynet.com Wed Jul 9 13:22:47 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Wed, 09 Jul 2008 12:22:47 -0500 Subject: "in"consistency? References: Message-ID: In article , Terry Reedy wrote: > David C. Ullrich wrote: > > In article , > > Terry Reedy wrote: > > >>> Is there a reason for the inconsistency? I would > >>> have thought "in" would check for elements of a > >>> sequence, regardless of what sort of sequence it was... > >> It is not an inconsistency but an extension corresponding to the > >> limitation of what an string element can be. > > > > It's an inconsistency. That doesn't mean it's a bad thing or that > > I want my money back. It may well be a reasonable inconsistency - > > strings _can_ work that way while it's clear lists had better not. > > But it's an inconsistency. > > To decisively argue 'inconsistency' as factual or not, versus us having > divergent opinions, you would have to supply a technical definition ;-) > The math definition of 'leading to a contradiction' in the sense of > being able to prove False is True, does not seem to apply here. > > However, > a) In common English, 'in' and 'contains', applied to strings of > characters (text), is understood as applying to substrings that appear > in the text. This is also true of many other programming languages. > 'Dictionary' contains 'diction'. This is even the basis of various word > games. > b) Python otherwise allows operators to vary in meaning for different > classes. > > In any case, back to your original question: the extension of meaning, > 'inconsistent' or not, was deliberated and adopted on the basis that the > usefulness of the extension would outweigh the confusion wrought by the > class-specific nature of the extension. (In other words, threads such > as this *were* anticipated ;-) I wasn't saying that the fact that the behavior of "in" for strings is inconsistent with the behavior for lists was a bad thing - I was just asking about the reason for it. (I also wasn't claiming that it was inconsistent with the common English usage of "in"...) People have pointed out that "in" for strings _can_ work that way, while (of course) "in" for lists had better not. That's fine. > Terry Jan Reedy -- David C. Ullrich From fetchinson at googlemail.com Wed Jul 9 23:58:32 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 9 Jul 2008 20:58:32 -0700 Subject: sort(cmp=func) In-Reply-To: References: Message-ID: > I have a list of objects that generate code. Some > of them depend on others being listed first, to > satisfy dependencies of others. > > I wrote a cmp function something like this: > > def dep_cmp(ob1, ob2): > > if ob1.name in ob2.deps: > return -1 > else: > return 1 > > I also tried returning 0 when there were no dependency > relationships between the objects. > > This failed, because every object was not compared with > ever other. I imagine that this is because sort assumes > that if a > b and b > c, then a > c. In my case, this > isn't really true. If a is not dependent on b, and > b is not dependent on c, that doesn't mean that a is not > dependent on c. > > Is there a better way? It's only meaningful to talk about sorting if your particular definition of "<" is transitive. I.e. a < b and b < c should imply a < c. If this is not satisfied, it doesn't make sense to sort according to your "<" definition. It's just not a well-defined operation and no trick will make it work. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From workitharder at gmail.com Sun Jul 13 14:32:22 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 13 Jul 2008 11:32:22 -0700 (PDT) Subject: socket.connect() hangs in SYN_SENT state. References: Message-ID: <804bccb2-42c7-42e9-8f50-7a780d3438fd@j22g2000hsf.googlegroups.com> On Jul 13, 1:14?am, Miles wrote: > On Sat, Jul 12, 2008 at 11:23 PM, bukzor wrote: > > I'm connecting to an apache2 process on the same machine, > > for testing. When looking at netstat, the socket is in the SYN_SENT > > state, like this: > > > $netstat -a -tcp > > tcp ? ? ? ?0 ? ? ?0 *:www ? ? ? ? ? ? ? ? ? *:* LISTEN ? ? ?7635/apache2 > > tcp ? ? ? ?0 ? ? ?1 bukzor:38234 ? ? ? ? ? ?adsl-75-61-84-249.d:www SYN_SENT ? ?9139/python > > > Anyone know a general reason this might happen? Even better, a way to > > fix it? > > That socket connection is to a remote machine, not the same one. ?Your > test code works fine for me. ?The "hang then crash" (and I'm assuming > "crash" here means an uncaught exception) just means that your packets > are being silently ignored by whatever machine you're actually > attempting to connect to. It's possible that your machine has odd DNS > settings causing buzkor.hopto.org to resolve to the wrong address. > > -Miles I'm connecting to my machine through the internet, and the resolved URL of my router is what you're seeing above. If you run the code above you'll see what I mean. Thanks tho, --Buck From mrkafk at gmail.com Sun Jul 13 12:55:11 2008 From: mrkafk at gmail.com (mk) Date: Sun, 13 Jul 2008 18:55:11 +0200 Subject: Magic? In-Reply-To: References: Message-ID: > However, it appears that somehow this object prints the value of 's' > attribute without me setting any specific methods to do that: > > >>> astr = lstr('abcdef') > >>> astr > 'abcdef' > >>> astr.swapcase() > 'ABCDEF' Correction: it doesn't really get the value from _s attribute: >>> astr = lstr('abcdef') >>> astr.s 'abcdef' >>> astr.s='xyzzy' >>> astr 'abcdef' >>> astr.s 'xyzzy' So my updated question is where does this lstr() instance keep the original value ('abcdef')? It obviously has smth to do with inheriting after str class, but I don't get the details of the mechanism. From mathieu.prevot at gmail.com Mon Jul 7 13:32:31 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Mon, 7 Jul 2008 19:32:31 +0200 Subject: do a sed / awk filter with python tools (at least as fast) Message-ID: <3e473cc60807071032s47afd4eap42adb5c1bddc0171@mail.gmail.com> Hi, I use in a bourne shell script the following filter: sed '/watch?v=/! d;s/.*v=//;s/\(.\{11\}\).*/\1/' \ | sort | uniq | awk 'ORS=" "{print $1}' that give me all sets of 11 characters that follows the "watch?v=" motif. I would like to do it in python on stdout from a subprocess.Popen instance, using python tools rather than sed awk etc. How can I do this ? Can I expect something as fast ? Thanks, Mathieu From comp.ogz at gmail.com Thu Jul 3 10:40:06 2008 From: comp.ogz at gmail.com (Oguz Yarimtepe) Date: Thu, 3 Jul 2008 17:40:06 +0300 Subject: detection of unplugged cable In-Reply-To: <20831c740807022158l38648a61l4966d11fae20297d@mail.gmail.com> References: <20831c740807022158l38648a61l4966d11fae20297d@mail.gmail.com> Message-ID: <20831c740807030740k16f90c1fx78a4649ca70c18ea@mail.gmail.com> Ok here is the exact problem. I have both S-Video, HDMI and VGA out at my machine. I tried to clone the LCD display to HDMI out but it worked only when i disable the LCD and send the display to HDMI. So when the HDMI cable is unplugged i want to revert the process and enable the LCD. I need to detect this signal or whatever it is. I tried with xrandr by thinking that when i used the --output LMDS --off i will see "LMDS disconnect" at the output but it was not true. So i should find a better way. Any idea? I am using Ubuntu Hardy with an Intel VGA card. -- O?uz Yar?mtepe From siddhantgoel at gmail.com Sun Jul 20 05:42:44 2008 From: siddhantgoel at gmail.com (Siddhant) Date: Sun, 20 Jul 2008 02:42:44 -0700 (PDT) Subject: Problems with curses References: Message-ID: On Jul 13, 6:22?pm, Clay Hobbs wrote: > > On Sat, 12 Jul 2008 20:49:56 -0400, Clay Hobbs wrote: > > > > ? ? ? Unfortunately, the error message isn't very helpful. > > > But it would be helpful to tell it. ?If you get exceptions, always > > copy'n'paste the traceback here. ?People might know what the exception > > means and share their wisdom. > > Here is the error message: > > Traceback (most recent call last): > ? File "./text_adventure.py", line 25, in > ? ? curses.wrapper(main) > ? File "/usr/lib/python2.5/curses/wrapper.py", line 44, in wrapper > ? ? return func(stdscr, *args, **kwds) > ? File "./text_adventure.py", line 19, in main > ? ? stdscr.scroll(3) > _curses.error: scroll() returned ERR > > -- Ratfink You need to put a stdscr.scrollok(True) in the beginning. That should avoid the exception. -Siddhant From alex.gaynor at gmail.com Sun Jul 13 01:33:20 2008 From: alex.gaynor at gmail.com (alex.gaynor at gmail.com) Date: Sat, 12 Jul 2008 22:33:20 -0700 (PDT) Subject: filtering keyword arguments References: <633d6159-7803-4d9b-8f16-2a4a0a197a86@t54g2000hsg.googlegroups.com> Message-ID: On Jul 12, 10:44?pm, Amir wrote: > How do you filter keyword arguments before passing them to a function? > > For example: > > def f(x=1): return x > > def g(a, **kwargs): print a, f(**kwargs) > > In [5]: g(1, x=3) > 1 3 > > In [6]: g(1, x=3, y=4) > TypeError: f() got an unexpected keyword argument 'y' > > Is there a way to do something like: > > def g(a, **kwargs): print a, f(filter_rules(f, **kwargs)) > > so only {'x': 3} is passed to f? > > I was hoping for a pythonic way of doing what in Mathematica is done > by FilterRules: > > http://reference.wolfram.com/mathematica/ref/FilterRules.html Sure, you could do: def call_with_relevant_args(func, kwargs): kwargs = dict([(k, v) for k, v in kwargs.iteritems() if k in func.func_code.co_varnames]) return func(**kwargs) From russblau at hotmail.com Wed Jul 30 17:55:03 2008 From: russblau at hotmail.com (Russell Blau) Date: Wed, 30 Jul 2008 17:55:03 -0400 Subject: Tkinter- Possibly a basic question References: <59dee72b-3fb6-414b-ab49-33cab8f9c9e8@26g2000hsk.googlegroups.com> Message-ID: wrote in message news:59dee72b-3fb6-414b-ab49-33cab8f9c9e8 at 26g2000hsk.googlegroups.com... >I hate to do this, but I've thoroughly exhausted google search. Yes, > it's that pesky root window and I have tried withdraw to no avail. I'm > assuming this is because of the methods I'm using. I guess my question > is two-fold. > 1) How do I get rid of that window? > 2) Any comments in general? I am just learning python (and coding with > classes), so I'm sure there are things I should pound into my head > before I learn bad habits. At the risk of overlooking something obvious, why don't you make your App class a subclass of Tkinter.Frame instead of Tkinter.Toplevel, and just pack it into the root window instead of worrying about how to get rid of the root window? Just delete "root.withdraw()" and then add "a.pack()" before "a.mainloop()". Russ From duncan.booth at invalid.invalid Sat Jul 19 12:10:06 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Jul 2008 16:10:06 GMT Subject: __del__ methods References: Message-ID: "Robert Rawlins" wrote: > I like this idea, I can definitely see the benefits to working with > this concept. One things I will take this quick opportunity to ask, > even though it's a little OT: > > What is the benefit of extending the base 'object' class? What does > that give me that en empty, non subclassed object doesn't? > Habit: certain things (such as properties) don't work properly with old-style classes, so it is good practice always to use new-style classes and that way you won't forget to do it when it really does matter. >> You can use gc.get_referrers() to find everything that references a >> particular objects and gradually trace backwards until you find the > problem >> reference (it is tricky though as any code which does this needs to >> ignore > >> its own references to the object in question). > > Yes, that's a very nice concept and like you say gives you quite a > nice visual reference of what objects are and aren't being destroyed. > See http://groups.google.co.uk/group/comp.lang.python/browse_thread/thread/394ba5b48f83ebfb/237dc92f3629dd9a#237dc92f3629dd9a for the code (although I seem to remember that there are some problems with that code so caveat emptor). From gagsl-py2 at yahoo.com.ar Fri Jul 11 04:46:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Jul 2008 05:46:31 -0300 Subject: Problems Returning an HTTP 200 Ok Message References: <1cf880cc-2036-42dc-8217-d52a714c1710@a70g2000hsh.googlegroups.com> <9bc65e72-be16-4f73-9dfb-6ddeaae34c21@m73g2000hsh.googlegroups.com> <8596af5b-fd0a-413e-8051-62d650e9a153@8g2000hse.googlegroups.com> Message-ID: En Thu, 10 Jul 2008 18:10:46 -0300, Guy Davidson escribi?: > On Jul 10, 12:38?pm, samwyse wrote: >> On Jul 10, 1:50?pm, Guy Davidson wrote: >> >> > My code (attached below) us supposed to read an HTTP Post message >> > coming from a power meter, parse it, and return a proper HTTP 200 Ok >> > message. The problem is that the socket fails to send the entire >> > message as one message, creating a fragmented message which the power >> > meter then fails to read and accept. >> >> From your description, I get the feeling that your power meter has a >> broken network stack, and you're trying to program around it. ?You >> need to repair the meter. > > The meter sends HTTP Post messages, and expects, as a reply, an HTTP > 200/Ok message. > > I try to send the following message, using the socket.send() command: > > 'HTTP/1.1 200 OK\r\nDate: Thu, 10 July 2008 14:07:50 GMT\r\nServer: > Apache/2.2.8 (Fedora)\r\nX-Powered-By: PHP/5.2.4\r\nContent-Length: 4\r > \nConnection: close\r\nContent-Type: text/html; charset=UTF-8\r\n\r > \n[0]\n' > > However, when I snoop on the packets in wireshark, here's what I see: > > HTTP/1.1 200 Ok: > > HTTP/1.1 200 OK > Date: Wed, 09 July 2008 14:55:50 GMT > Server: Apache/2.2.8 (Fedora) > X-Powered-By: > > Continuation or non-HTTP traffic: > > PHP/5.2.4 > Content-Length: 4 > Connection: close > Content-Type: text/html; charset=UTF-8 > > [0] > > It splits into two packages, which the meter can't read, and the > communication breaks down there. > > Any ideas? As Guy Davidson has already pointed out, this is a problem in the meter TCP implementation, and you should ask the vendor to fix it. (Anyway, looks like "somewhere" there is a buffer size of 100 bytes or so, very small). As a workaround, try to shorten your HTTP response; I guess the Server and X-Powered-By headers are not required; the Date probably isn't either; and if all your responses are like "[0]" a simple "Content-Type: text/plain" may suffice (the meter might just ignore it, anyway). -- Gabriel Genellina From hyugaricdeau at gmail.com Tue Jul 22 09:55:23 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Tue, 22 Jul 2008 06:55:23 -0700 (PDT) Subject: regarding SWIG References: <12e21dec-b269-4c34-9492-98424d207397@w7g2000hsa.googlegroups.com> Message-ID: On Jul 22, 5:34?am, Anish Chapagain wrote: > Hi.. > I'm new to SWIG and need to create Wrapper for C code, > so, I have installed the SWIG already but doesnot know how to run it > for generating Interface file... > My C code is in message.c so what do i need to do the first > step..uisng SWIG..i read the documentation but cannot grasp creating > interface file. > > thank's anish Not sure where you're having trouble. I can understand if there's a language barrier, but I think that the introductory SWIG documentation is pretty darn straightforward, even if you just look at the code, so I don't think there's anything that could be said here that's any more clear, as far as the basics are concerned. You'd have to explain exactly what it is you're stuck on. From straton at lampsacos.demon.co.uk Mon Jul 14 04:44:34 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Mon, 14 Jul 2008 09:44:34 +0100 Subject: Dictionary bidirectional In-Reply-To: References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: > On Sun, 13 Jul 2008 16:21:11 -0700 (PDT), Kless > declaimed the following in comp.lang.python: > >> I need a dictionary where get the result from a 'key' (on left), but >> also from a 'value' (on right), how to get it? >> >> I know that dictionaries aren't bidirectional, but is there any way >> without use two dictionaries? >> > Just out of curiosity... What do you expect to have returned from... > > aDict = { "one" : "two", > "three" : "four", > "What?" : "two" } > > when looking for the value "two"? > > In a dictionary, the /keys/ are unique... but the /values/ can be > duplicates. I wonder if anyone has implemented an 'equivalence class' class (for finite sets) based on this. Obviously the relation defined by k1~k2 iff D[k1] == D[k2] does partition the set of all keys as an equivalence class. So ... as a kind of inverse you could return a set, a subset of the keys. How you would get a canonical representative of that set is a different matter, of course. Unless, as in the OP's case, it is a singleton set. It would seem more efficient to do this when a key-value pair is added or removed from the original dictionary rather than iterating over all the keys each time you used it. From scott.pigman at gmail.com Sun Jul 27 07:47:33 2008 From: scott.pigman at gmail.com (Scott Pigman) Date: Sun, 27 Jul 2008 07:47:33 -0400 Subject: ctypes - unloading implicitly loaded dlls Message-ID: <14db0f2c0807270447t46b0acf2yf3814d97d9c7f03c@mail.gmail.com> Here's what I'm struggling with (as best as I can understand it): I'm writing a program that uses functionality from two different sets of cdlls which reside in two different directories, call them 'libA.dll' and 'libB.dll'. Although I don't directly use it, both directories contain a dll with the same name, although they aren't in fact identical. Call them, "libC.dll". However, the c-functions I call from the clls I do use seem to implicitly use "libC.dll". The problem that occurs is that after I load one dll and call functions in it, when I try to load the second dll I get windows errors because the second dll tries to call a function in its version of libC.dll, but it finds the version meant for libB.dll, which doesn't contain that function. Oy, I hope some sample code makes it clearer: def demo(): A = ctypes.cdll.LoadLibrary('/path1/libA.dll') A.foo() # implicitly uses '/path1/libC.dll' _ctypes.FreeLibrary(A._handle) # CRASH! "The procedure entry point some_func could not be located # in the dynamic link library libC.dll.": B = ctypes.cdll.LoadLibrary('/path2/libB.dll') # libB.dll wants to use code from '/path2/libC.dll', but # instead it finds '/path1/libC.dll' already loaded # in memory, which doesn't # contain the function call it wants. Assuming my understanding of things is correct, then I believe what I need to do is to remove /path1/libC.dll from memory before I try loading libB.dll, but I haven't found any way of doing that. Can anyone offer my some suggestions? Notes: * the two sets of dlls are supplied by a vendor for working with its COTS packages; I don't have any control over the dll names used or the code therein. * If I leave out the call to A.foo(), then I don't crash, but if I leave out the FreeLibrary call as well then I do crash. * I've tried manipulating the PATH before loading the dlls, to no effect. * I've tried del'ing A and running gc.collect() before loading B. -------------- next part -------------- An HTML attachment was scrubbed... URL: From benkasminbullock at gmail.com Tue Jul 1 08:02:24 2008 From: benkasminbullock at gmail.com (Ben Bullock) Date: Tue, 1 Jul 2008 12:02:24 +0000 (UTC) Subject: perl + python tutorial available for download References: <86c4090b-ed0b-4249-b3ee-517c94328741@z32g2000prh.googlegroups.com> Message-ID: On Mon, 30 Jun 2008 17:44:13 +0000, J?rgen Exner wrote: > Xah wrote: >>my perl and python tutorial >> >>http://xahlee.org/perl-python/index.html >> >>is now available for download for offline reading. > > Why anyone would have the idea to mix two different langauges in one > tutorial is beyond me. It's an interesting idea to present two or more languages in parallel - it would assist someone going "sideways" from one language to another. > And calling that web page a tutorial is a large stretch of imagination. > It is a random collection of primitve code samples, organized roughly by > area. No learning goals, no explanation of concepts, ... I'm a big fan of code samples - most of my code starts as other people's code samples. > Apparently you changed your ID to escape all the filters you have been a > permanent guest to. This 'tutorial' confirms that this is the best place > for you. So back you go again. I'm not interested in Xah Lee's tutorials enough to check whether they're any good or not, but he does have some interesting things to say about Emacs. From pavlovevidence at gmail.com Mon Jul 28 02:45:26 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 27 Jul 2008 23:45:26 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> Message-ID: <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> On Jul 27, 5:14 am, Steven D'Aprano wrote: > On Sat, 26 Jul 2008 15:58:16 -0700, Carl Banks wrote: > > On Jul 26, 5:07 pm, Terry Reedy wrote: > >> Whether or not one should write 'if x' or 'if x != 0' [typo corrected] > >> depends on whether one means the general 'if x is any non-null object > >> for which bool(x) == True' or the specific 'if x is anything other than > >> numeric zero'. The two are not equivalent. Ditto for the length > >> example. > > > Can you think of any use cases for the former? And I mean something > > where it can't be boiled down to a simple explicit test for the sorts of > > arguments you're expecting; something that really takes advantage of the > > "all objects are either true or false" paradigm. > > But why do you need the explicit test? I asked you first, buddy. [snip attempt to reverse argument] > > The best thing I can come up with out of my mind is cases where you want > > to check for zero or an empty sequence, and you want to accept None as > > an alternative negative as well. But that's pretty weak. > > You might find it pretty weak, but I find it a wonderful, powerful > feature. Powerful? You've got to be kidding me. If I have a function create_object(name) where one creates an anonymous object by passing an empty string, behold! now I can also create an anonymous object by passing None. You call that powerful? I call it simple convenience, and not something that we'd suffer much for for not having. But it's still the one thing I can think of that can't be replaced by a simple explicit test. > I recently wrote a method that sequentially calls one function after > another with the same argument, looking for the first function that > claims a match by returning a non-false result. It looked something like > this: > > def match(arg, *functions): > for func in functions: > if func(arg): > return func > > I wanted the function itself, not the result of calling the function. I > didn't care what the result was, only that it was something (indicates a > match) or nothing (no match). In one application, the functions might > return integers or floats; in another they might return strings. In a > third, they might return re match objects or None. I don't need to care, > because my code doesn't make any assumptions about the type of the result. Couldn't you write the function to return None on no match, then test if func(arg) is None? That way would seem a lot more natural to me. As an added bonus, you don't have to return some sort of wrapped object if suddenly you decide that you want to match a zero. Sorry, can't give it credit for the use case I was asking for. I want something where "if x" will do but a simple explicit test won't. Carl Bannks From Lie.1296 at gmail.com Wed Jul 16 08:44:28 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 16 Jul 2008 05:44:28 -0700 (PDT) Subject: Why is this blowing the stack, thought it was tail-recursive... References: <1f94a4cf-1543-4e7d-aa17-5992a0156f8b@k37g2000hsf.googlegroups.com> Message-ID: On Jul 13, 8:44?pm, Fuzzyman wrote: > On Jul 13, 7:56?am, Steven D'Aprano > > > cybersource.com.au> wrote: > > On Sat, 12 Jul 2008 19:25:18 -0400, Terry Reedy wrote: > > > ssecorp wrote: > > >> def fib(n): > > >> ? ? def fibt(a, b, n): > > >> ? ? ? ? if n <= 1: > > >> ? ? ? ? ? ? return b > > >> ? ? ? ? else: > > >> ? ? ? ? ? ? return fibt(b, a + b, n - 1) > > >> ? ? if n == 0: > > >> ? ? ? ? return 0 > > >> ? ? else: > > >> ? ? ? ? return fibt(0, 1, n); > > > >> and can memoization speed up this even more? tesintg with memoization > > >> doesnt really say anything because it is so fast it is instant anyway. > > > > Except for the fact that a+b gets slower as a and b get bigger, this > > > would already be linear time in n. ?Memoization (here by means of a > > > linear list) only helps if the list is preserved and one makes repeated > > > requests for various fib values. > > > > I am just curious what input you tried that blew the stack? ?It had to > > > be pretty large. > > > No, not really. Try it for yourself: on my system, I get RuntimeError: > > maximum recursion depth exceeded with fib(999). > > > fib(999) is a large number, with 208 digits, but not that large: > > > 268638100244853593861467272021429239676166093189869523401 > > 231759976179817002478816893383696544833565641918278561614 > > 433563129766736422103503246348504103776803673341511728991 > > 69723197082763985615764450078474174626L > > > -- > > Steven > > The default CPython recursion limit is 1000 - so hitting it with an > input of 999 is not that surprising... > > You can set a higher limit with sys.setrecursionlimit(...) Though that would be a kludge, not a fix. Using iteration or generator expression is better. From jeffober at gmail.com Tue Jul 8 07:41:27 2008 From: jeffober at gmail.com (Jeff) Date: Tue, 8 Jul 2008 04:41:27 -0700 (PDT) Subject: Emacs/Python Essentials? References: Message-ID: I just use Python mode. For Django work, there is a Django mode as well. Cedet is helpful, too. From fredrik at pythonware.com Tue Jul 22 18:45:36 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 00:45:36 +0200 Subject: How to match word boundary? In-Reply-To: <94c0d7d1-5263-45f6-a75d-a9751b3785f9@d45g2000hsc.googlegroups.com> References: <94c0d7d1-5263-45f6-a75d-a9751b3785f9@d45g2000hsc.googlegroups.com> Message-ID: Peng Yu wrote: > I would like to match "a::" in "a::b", but not in "a:: b". That is, > the character after "::" should be a alphanumeric character. sounds like a look-ahead assertion is what you need: >>> import re >>> re.match("\w::(?=\w)", "a::b") <_sre.SRE_Match object at 0x01442138> >>> _.group() 'a::' >>> re.match("\w::(?=\w)", "a:: b") >>> From darcy at druid.net Mon Jul 28 14:19:48 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Mon, 28 Jul 2008 14:19:48 -0400 Subject: We programming In-Reply-To: <488E0956.8070002@internetnowasp.net> References: <789038.29418.qm@web7906.mail.in.yahoo.com> <488E0956.8070002@internetnowasp.net> Message-ID: <20080728141948.03ada692.darcy@druid.net> On Tue, 29 Jul 2008 02:00:54 +0800 "Marcus.CM" wrote: > I hope this doesnt invite flames.....but for webpages i suggest stick > with php... Oh, come on. You're just asking for it. :-) [Turns flame thrower to low setting] OK, here is why I don't like PHP. When I am creating dynamic web content, chances are that it is part of a larger system. I may have command line utilities, server software and cron jobs all working on the same (usually database backed) systems. As a result it is really convenient to be able to reuse modules. Python gives me that quite easily. PHP, not so much. I am not going to write a server in PHP, for example. I also don't much care for PHP as a language anyway but that's actually a secondary consideration. I'll go put on my flame-retardent underwear now. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From stef.mientki at gmail.com Sat Jul 26 13:43:56 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 26 Jul 2008 19:43:56 +0200 Subject: how to upload files to "google code" filesection ? Message-ID: <488B625C.4060400@gmail.com> hello, In a program I want to download (updated) files from google code (not the svn section). I could find a python script to upload files, but not for downloading. Anyone has a hint or a solution ? thanks, Stef Mientki From __peter__ at web.de Thu Jul 24 11:27:38 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 Jul 2008 17:27:38 +0200 Subject: repr(string) References: Message-ID: Peter Otten wrote: > You could also use a csv file with a single row. Err, I meant column, but a row would also work. Your choice. Peter From thomas.troeger.ext at siemens.com Tue Jul 22 08:07:23 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Tue, 22 Jul 2008 14:07:23 +0200 Subject: Python embedding question (2). References: Message-ID: Carl Banks wrote: > On Jul 17, 9:57 am, Thomas Troeger > wrote: >>> I'd say that PyGame could be a solution. >>> Or otherwise you could do your own audio/graphics programming (you don't >>> tell us which OS you use, but there exist python modules that allow you >>> to do barebones graphics & sound programming on linux...). > Pyglet runs on top of OpenGL, which might have performance problems on > an embedded device, if OpenGL or Mesa is even supported. If it's > supported, I suspect performance will be adequate for 2D drawing. It > almost certainly is the lightest solution you can find. > > > Carl Banks I've managed to put together a small pyGame program, it runs smoothly and seems to be exactly what I wanted. It's fast! Even with 100 moving objects it still runs so fast that I can consider using Python/pyGame for the whole project. There are still some questions left which I haven't found out by myself, so maybe someone here can answer them: - I can't see how to create more sophisticated text output, it seems the built in font render facilities are limited to simple strings. Is that true? I'd need a way to at least render multiline text with paragraphs and bidirectionality, like pango does it. Is there a way to integrate pango support into pyGame? I'd prefer marked up text display with text properties ... - Is there some way to reserve screen areas so they are excluded from a blit, or do I have to manage stuff like this myself? I am thinking about several graphic layers where each layer is painted on top of the next layer, for example to draw a gui in front of a background image. - There seems to be support for video overlay, i.e. is it possible to have an external program paint an image from a camera into a portion of the screen while pyGame is running? Maybe this is the wrong list to ask, so please forgive the question but direct me to somewhere better. Cheers, Thomas. From robert.rawlins at thinkbluemedia.co.uk Mon Jul 28 10:16:48 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Mon, 28 Jul 2008 15:16:48 +0100 Subject: GUID Generation Message-ID: <019c01c8f0bc$92b56b20$b8204160$@rawlins@thinkbluemedia.co.uk> Chaps, I've been looking at the following recipe for generating a GUID http://code.activestate.com/recipes/163604/ however I note that its about 6 years old. Has python since adopted an internal module for GUID generation? Or is this 3rd part module still the best option? Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From koblas at gmail.com Tue Jul 29 23:56:31 2008 From: koblas at gmail.com (koblas) Date: Tue, 29 Jul 2008 20:56:31 -0700 (PDT) Subject: Native Code vs. Python code for modules Message-ID: Ruby has been getting pummeled for the last year or more on the performance subject. They've been working hard at improving it. From my arm chair perspective Python is sitting on it's laurels and not taking this as seriously as it probably should. In general it's possible to make many comments that swirl around religion and approach, one of the things that I've noticed is that wile Python has a much more disciplined developer community they're not using this for the greater good. Specifically, in looking at a benchmark that was posted, python was an order of magnitude (20 secs vs. 1 sec) slower than ruby. In investigating the performance bottleneck is the random module. This got me to think, why does python have "pickle" and "cPickle"? Comes down to lowest common denominator, or the inability for somebody to write an optimized package that can mimic a python package. To that end why would somebody write big try catch blocks to see if modules exist and if they exist alias their names. Wouldn't it be better if there was a way that if I have an "interface compatible" native (aka C) module that has better performance that there could be a way that python would give it preference. e.g. import random(version=1.2, lang=c) or import random(version=1.2, lang=py) # use the python version by default or import random # use the latest version in the "fastest" code (C given preference) where there could be a nice set of "standard" key value pairs that could provide addtional hints as to what language and version of a library was to be used. From 5lvqbwl02 at sneakemail.com Sat Jul 26 15:33:40 2008 From: 5lvqbwl02 at sneakemail.com (5lvqbwl02 at sneakemail.com) Date: Sat, 26 Jul 2008 12:33:40 -0700 (PDT) Subject: wx.Timer not working Message-ID: <7a2a1c54-6d74-475c-9566-4d94cb5b5962@a3g2000prm.googlegroups.com> Windows XP SP3 Python 2.5 wx.version() = '2.8.1.1 (msw-unicode)' ------ I have written the following *simplest* implementation of wx.timer I can think of. No workie. I want an exception, a print statement, or something. The wxpython demos all work, but for some reason this isn't. The demos are simple and straghtforward, so I think I understand how it should work. Clues please? I've tried variations of ID's, SetOwners, using and redefining Notify(), Bind, Connect, etc. In the cases where the interpreter doesn't complain about passed argument types, the callback function is never called. import wx class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, pos=(100, 100)) timer = wx.Timer(self, -1) self.Bind(wx.EVT_TIMER, self.OnTick, timer) timer.Start(100) def OnTick(self, event): print 'Hi. Bye.' 1/0 #<-- should crash as evidence callback is being called class MyApp(wx.App): def OnInit(self): frame1 = MyFrame(None, wx.ID_ANY, "This is a test") frame1.Show(True) return True app = MyApp(0) app.MainLoop() Thanks for any advice!! Michael From norseman at hughes.net Mon Jul 7 16:41:24 2008 From: norseman at hughes.net (norseman) Date: Mon, 07 Jul 2008 13:41:24 -0700 Subject: Cross Compiler for Python? In-Reply-To: <000901c8e009$dbd29e40$0d00a8c0@hendrik> References: <000901c8e009$dbd29e40$0d00a8c0@hendrik> Message-ID: <48727F74.9000708@hughes.net> I think I should have not used the 'reply' button but rather sent it back through the python-list at ... So here here goes. =============== Hendrik van Rooyen wrote: > Up to now, I have been innocently using the vanilla python > that comes with the Linux distribution (Suse in my case). > > For the past few days, I have been playing with a little > device called an eBox - it is basically a 486 with 128Mb > memory, and a 1Gig pcmcia flash drive. > > We want to try to use this as an industrial controller, so > I want to load python onto it. > > So I downloaded the sources, and got them into the box, > over its ethernet connection. > > Then I got stymied - the configure script will not run, > because the "distribution" has no C compiler - it is > basically a kernel, and Busybox, with precious little else. > > So I googled, and I found mobile python, and portable python, > both aimed at windows. - no good to me. > > Adding "embedded" to the Google string is also useless, > as it basically brings up instances of embedding the > interpreter into another app, not for small processors. > > So how does one do a compile of python on one machine > aimed at another one? - All I want is a vanilla installation > with the stuff in all the usual places. And just to make matters > interesting, the two Linux boxes I have available are both > 64 bit dual core animals, one Intel, one AMD... > > I don't need much more than the interpreter, sys, os, sockets > and ctypes. > > Alternatively, where can one find a set of binaries for > 32 bit Linux? > > Looking for some sane advice please. > > - Hendrik > > -- > http://mail.python.org/mailman/listinfo/python-list > ================================================== In case all else fails: This is not a cookbook answer, but: 1) gnu's gcc will compile to 16,32 or 64 bit intel architectures OK, the 32 bit version compiles to 16 or 32 & the 64 should. The 64 will run 32 bit programs, including the 32 bit gcc. chgroot can be (messy but) useful to maintain separation. 2) info gcc and look for compiler directives then info nasm and look for directives same for the linker I'm not specific because I use Slackware and different distros can use different modules. You may have an assembler with a different name. Switches can be different and so forth. On Slackware the installpkg (for tarballs already compiled) records the locations of where things go in /var/log/packages. I have to assume other distros have something similar since these are used to remove things later. Can we say 'updates'? If not you will need to wade through the .configure and Makefiles to root out what happens to get 'vanilla' locations. Like I said, it's not cookbook, but it will get you there and you will gain quite an insight into Linux. While the path may not be well marked in Linux, there usually is one. Sorry I don't have a more straight forward approach. Steve norseman at hughes.net From mail at timgolden.me.uk Tue Jul 15 13:01:25 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Jul 2008 18:01:25 +0100 Subject: need ldap windows binary and/or installation help In-Reply-To: <0A53725C4A497848A7B3A0874B259831011B09A1@acesxch01.ADVENTISTCORP.NET> References: <0A53725C4A497848A7B3A0874B259831011B09A1@acesxch01.ADVENTISTCORP.NET> Message-ID: <487CD7E5.5020805@timgolden.me.uk> Sells, Fred wrote: > I'm running python 2.5 (or 2.4) in an XP environment. > > I downloaded and installed the .dll's from OpenLDAP-2.4.8+OpenSSL-0.9.8g-Win32.zip and copied the .dll's in c:/windows/system32 as instructed > > now I get this error. Is there anyway to avoid building the python_ldap binaries? Apart from being lazy, I've got a secure system policy issue if I start compiling apps. I could give up and just start running in linux, but my xp environment is much friendlier to develop in. I've googled a lot, but all the links I've found talk to Unix or to compiling from source. Disclaimer. I know nothing about python-ldap. I simply Googled for it and came to: http://python-ldap.sourceforge.net/download.shtml which led me to http://www.osuch.org/python-ldap from which I downloaded and ran the .msi http://www.osuch.org/python-ldap-2.3.5.win32-py2.5.msi and Bob was at that point my uncle. Was there some obstacle to your doing this? (It wasn't clear whether some policy required you to compile from source). TJG From kris at FreeBSD.org Wed Jul 9 15:46:50 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Wed, 09 Jul 2008 21:46:50 +0200 Subject: re.search much slower then grep on some regular expressions In-Reply-To: <1343fa73-fd32-46c3-8a75-0efc85b2660e@a70g2000hsh.googlegroups.com> References: <897ef5df-0954-450c-bd2e-4035ff287981@f63g2000hsf.googlegroups.com> <092f7bc2-58f8-450f-82c9-028c9994da3b@m36g2000hse.googlegroups.com> <1343fa73-fd32-46c3-8a75-0efc85b2660e@a70g2000hsh.googlegroups.com> Message-ID: <487515AA.3070407@FreeBSD.org> samwyse wrote: > On Jul 8, 11:01 am, Kris Kennaway wrote: >> samwyse wrote: > >>> You might want to look at Plex. >>> http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/ >>> "Another advantage of Plex is that it compiles all of the regular >>> expressions into a single DFA. Once that's done, the input can be >>> processed in a time proportional to the number of characters to be >>> scanned, and independent of the number or complexity of the regular >>> expressions. Python's existing regular expression matchers do not have >>> this property. " > >> Hmm, unfortunately it's still orders of magnitude slower than grep in my >> own application that involves matching lots of strings and regexps >> against large files (I killed it after 400 seconds, compared to 1.5 for >> grep), and that's leaving aside the much longer compilation time (over a >> minute). If the matching was fast then I could possibly pickle the >> lexer though (but it's not). > > That's funny, the compilation is almost instantaneous for me. My lexicon was quite a bit bigger, containing about 150 strings and regexps. > However, I just tested it to several files, the first containing > 4875*'a', the rest each twice the size of the previous. And you're > right, for each doubling of the file size, the match take four times > as long, meaning O(n^2). 156000*'a' would probably take 8 hours. > Here are my results: The docs say it is supposed to be linear in the file size ;-) ;-( Kris From fredrik at pythonware.com Thu Jul 24 05:24:17 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 11:24:17 +0200 Subject: instance comparison In-Reply-To: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> References: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> Message-ID: King wrote: > Is this mean when you have overridden __str__ method then it comapre > with results of __str__ or else it will comapre whether they are the > same instances? Comparisons uses __cmp__ or the rich comparison set; see http://docs.python.org/ref/customization.html for details. Sets and dictionaries, also relies on hashing (the __hash__ method, also described on the linked page). The __str__ method only affects printing and conversion to string. From kris at FreeBSD.org Thu Jul 10 18:49:34 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Fri, 11 Jul 2008 00:49:34 +0200 Subject: multithreading in python ??? In-Reply-To: <486CAC9B.9000902@shopzeus.com> References: <674A912AA405814397CED58601AC8E251554964241@BLRKECMBX05.ad.infosys.com> <486CAC9B.9000902@shopzeus.com> Message-ID: <487691FE.7040903@FreeBSD.org> Laszlo Nagy wrote: > Abhishek Asthana wrote: >> >> Hi all , >> >> I have large set of data computation and I want to break it into >> small batches and assign it to different threads .I am implementing it >> in python only. Kindly help what all libraries should I refer to >> implement the multithreading in python. >> > You should not do this. Python can handle multiple threads but they > always use the same processor. (at least in CPython.) In order to take > advantage of multiple processors, use different processes. Only partly true. Threads executing in the python interpreter are serialized and only run on a single CPU at a time. Depending on what modules you use they may be able to operate independently on multiple CPUs. The term to research is "GIL" (Global Interpreter Lock). There are many webpages discussing it, and the alternative strategies you can use. Kris From vinay_sajip at yahoo.co.uk Tue Jul 15 09:45:50 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 15 Jul 2008 06:45:50 -0700 (PDT) Subject: logging via SocketHandler and TCPserver References: <81929250-449b-4686-acf3-dcc0095e341a@d1g2000hsg.googlegroups.com> Message-ID: On Jul 14, 11:16 pm, Larry Bates wrote: > Vinay, > > Thanks for your detailed explanation, but IMHO your suggested solution is almost > the opposite (right idea wrong direction) of what I'm looking for. Hypothetical > setup: > > application1 - SocketHandlerloggingturned on > application2 - SocketHandlerloggingturned on > application3 - SocketHandlerloggingturned on > . > . > . > applicationN > > monitoring app - ThreadingTCPServer target that Allows user to connect to ANY > running application and to view the real-time log messages. After monitoring, > it should be able to disconnect and connect to another application... The > clients (application1..N) never stop sending and don't ever send anything short > to disconnect themselves from the monitoring application. The disconnect/ > reconnect is done at the monitoring app end based on input from the user. I > think each one would beloggingto a different port, but I never really quite > got that far. Perhaps there is some other way that I'm missing. It seems like > this is something that might be able to be "generalized" into a robust > monitoring application for an arbitrary number of asynchronously running > applications. > > Each application's real-time log might be reached by clicking on a tab, menu, etc. Here's how I see it: the socket server listens, and receives logging events from numerous applications in real time. If the server is configured to monitor app1, then it quietly discards (or doesn't show in the UI) all events from other apps - it only collects/shows events from app1. When you click on a tab/menu/whatever to switch to monitoring app2, then this information is used to tell the server to discard (or not show) events from all apps except app2. You would of course need to ensure the communication between UI thread and server thread were done in a thread-safe manner. > As to the difficulty, I might just have a mental block but two modules that I've > had a real hard time getting my mind wrapped around is yourLoggingand Twisted. > They both have a multitude of options/ways to be used and not very many working > examples to work from. Might be a chance to make some money on a book. If it > was full of examples, I'd purchase it. > But there are numerous examples in the logging docs - the script you quoted as having put together after several hours of Googling is pretty much the same as the (working) version in the logging docs! If you have reviewed the logging docs and find them lacking examples, please provide more detail about the kind of examples you think are missing. And I can't speak for Twisted, but it does a lot more than logging - and I don't think there's enough complexity in Python logging to warrant a paid-for book. (No doubt people will tell me if they disagree!) Best regards, Vinay Sajip From arnimavidyarthy at gmail.com Fri Jul 18 07:04:34 2008 From: arnimavidyarthy at gmail.com (arni) Date: Fri, 18 Jul 2008 04:04:34 -0700 (PDT) Subject: trying to match a string References: Message-ID: <4b33b3b5-d87d-4333-948d-73f07c33c111@a3g2000prm.googlegroups.com> On Jul 18, 3:46?pm, ed... at holyrood.ed.ac.uk (Eddie Corns) wrote: > arnimavidyar... at gmail.com writes: > >Hi, > >Hi, > >I am taking a string as an input from the user and it should only > >contain the chars:L , M or R > >I tried the folllowing in kodos but they are still not perfect: > >[^A-K,^N-Q,^S-Z,^0-9] > >[L][M][R] > >[LRM]?L?[LRM]? etc but they do not exactly meet what I need. > >For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' .like that. > >regards, > >SZ > >The string may or may not have all the three chars. > >>> var ? ? = 'LRLRLRNL' > >>> residue = var.replace('L','').replace('R','').replace('M','') > >>> if residue != '': > > ... ? print 'Invalid characters in input',residue > ... > Invalid characters in input N That was quick.Thanks.Never thought it that angle :( From bearophileHUGS at lycos.com Thu Jul 31 21:56:45 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 31 Jul 2008 18:56:45 -0700 (PDT) Subject: Non Continuous Subsequences References: <650df4ae-2f63-4428-b780-3f7045164690@p25g2000hsf.googlegroups.com> Message-ID: <1d074ab3-e703-4741-be14-26c52af457ca@27g2000hsf.googlegroups.com> Kay Schluehr: >[Yes, I have too much time...] Thank you for your code. If you allow me to, I may put some code derived from yours back into the rosettacode.org site. >Here is an evil imperative, non-recursive generator: I like imperative, non-recursive code :-) If you count the number of items of the results, you find the sequence A002662: www.research.att.com/~njas/sequences/A002662 The series grows as: lambda n: sum(C(n, k) for k in xrange(3, n+1)) I have modified your code a little, here and there, so I can show it again. Here are some timings. Note: n = 19 => result = 261_972 subs n = 21 => result = 1_048_365 subs Timings, seconds, best of 3: N=19 N=21 v1: 2.51 17.88 v2: 0.63 3.58 v3: 2.47 10.65 v4: 0.61 3.55 v5: 0.84 5.45 v6: 0.64 2.67 v7: 0.58 3.07 v8: 0.44 1.83 v9: 0.07 0.21 v10: 2.22 9.58 v9 computes the 67_108_512 subs of n=27 in 14.54 s. The versions: v1) original eager Python+Psyco version v2) eager Python+Psyco version v3) lazy Python version v4) eager Python+Psyco version plus optimization v5) eager D version with my libs v6) lazy D version with my libs v7) eager D version without my libs plus optimization v8) lazy D version without my libs v9) lazy D version without my libs, no allocations 10) lazy Python version, no allocations Used DMD compiler V.1.033 with: -O -release -inline Python 2.5.2, Psyco 1.5.2. Some comments: - The current Python GC manages memory more efficienty than the current default D GC. This is a known issue, D is a much younger language, and there are various different situations (not just regarding its GC) where it's slower (for example regarding I/O, associative arrays, etc). - Being compiled, and having a very light iteration protocol, D is much faster in the lazy version. Avoiding to allocate new memory reduces total time a lot. - In D when n is small the eager version is faster, but things change with n is large, because this time the allocation time and the cache misses start to dominate. - The Python version doesn't improve much when you know much long the result is, while the D version improves significantly. This because the list append in Python is much more efficient than in D. Python is a much more refined language, and despite D supposed to be a fast compiled "to the metal" system language, it's often not faster. For example Python dicts are often faster than D AAs. D is currently in quick development so its data structures and many details aren't optimized. Python is much older and its data structures are well optized, lot of smart people has made them fast. - If you avoid memory allocation in D you can generally go quite fast. - Comparing different languages like this is useful for D, because it's young, and doing such comparisons I have found many performance problems in it, sometimes they have even being discussed, understood, addressed. - In D another possible output is an uint (integer not signed always 32 bits), where the bits = 1 are the items in the current subset. This may be fast enough. Bye, bearophile ------------------------- THE CODE: # 1) original eager Python+Psyco version from sys import argv def ncsub(seq, s=0): if seq: x = seq[:1] xs = seq[1:] p2 = s % 2 p1 = not p2 return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2) else: return [[]] if s >= 3 else [] import psyco; psyco.bind(ncsub) n = 10 if len(argv) < 2 else int(argv[1]) print len( ncsub(range(1, n)) ) ------------------------- # 2) eager Python+Psyco version from sys import argv def ncsub(seq): n = len(seq) res = [] for i in xrange(1, 2 ** n): S = [] nc = False for j in xrange(n + 1): k = i >> j if k == 0: if nc: res.append(S) break elif k % 2: S.append(seq[j]) elif S: nc = True return res import psyco; psyco.bind(ncsub) n = 10 if len(argv) < 2 else int(argv[1]) print len( ncsub(range(1, n)) ) ------------------------- # 3) lazy Python version # Psyco not used because makes it slower from sys import argv def leniter(iterator): nelements = 0 for _ in iterator: nelements += 1 return nelements def ncsub(seq): n = len(seq) for i in xrange(1, 2 ** n): S = [] nc = False for j in xrange(n + 1): k = i >> j if k == 0: if nc: yield S break elif k % 2: S.append(seq[j]) elif S: nc = True n = 10 if len(argv) < 2 else int(argv[1]) print leniter( ncsub(range(1, n)) ) ------------------------- # 4) eager Python+Psyco version plus optimization def C(n, k): result = 1 for d in xrange(1, k+1): result *= n n -= 1 result /= d return result # www.research.att.com/~njas/sequences/A002662 nsubs = lambda n: sum(C(n, k) for k in xrange(3, n+1)) def ncsub(seq): n = len(seq) result = [None] * nsubs(n) pos = 0 for i in xrange(1, 2 ** n): S = [] nc = False for j in xrange(n + 1): k = i >> j if k == 0: if nc: result[pos] = S pos += 1 break elif k % 2: S.append(seq[j]) elif S: nc = True return result from sys import argv import psyco; psyco.full() n = 10 if len(argv) < 2 else int(argv[1]) print len( ncsub(range(1, n)) ) ------------------------- // 5) eager D version with my libs // all the D code is generic (templated) import d.all, std.conv; T[][] ncsub(T)(T[] seq) { int n = len(seq); T[][] result; auto R = xrange(n + 1); foreach (i; xrange(1, 1 << n)) { T[] S; bool nc = false; foreach (j; R) { int k = i >> j; if (k == 0) { if (nc) result ~= S; break; } else if (k % 2) S ~= seq[j]; else if (S.length) nc = true; } } return result; } void main(string[] args) { int n = args.length == 2 ? toInt(args[1]) : 10; putr( len( ncsub(range(1, n)) ) ); } ------------------------- // 6) lazy D version with my libs import d.all, std.conv; struct Ncsub(T) { T[] seq; void generator() { int n = len(seq); foreach (i; xrange(1, 1 << n)) { T[] S; bool nc = false; foreach (j; xrange(n + 1)) { int k = i >> j; if (k == 0) { if (nc) yield(S); break; } else if (k % 2) S ~= seq[j]; else if (S.length) nc = true; } } } mixin Generator!(T[]); } void main(string[] args) { int n = args.length == 2 ? toInt(args[1]) : 10; putr( len( Ncsub!(int)(range(1, n)) ) ); } ------------------------- // 7) eager D version without my libs plus optimization import std.stdio: putr = writefln; import std.conv: toInt; long C(long n, long k) { long result = 1; for (long d = 1; d < k+1; d++) { result *= n; n--; result /= d; } return result; } long nsubs(long n) { // www.research.att.com/~njas/sequences/A002662 long tot = 0; for (int k = 3; k <= n; k++) tot += C(n, k); return tot; } T[][] ncsub(T)(T[] seq) { auto result = new T[][nsubs(seq.length)]; int pos; for (int i = 1; i < (1 << seq.length); i++) { T[] S; bool nc = false; for (int j; j < seq.length + 1; j++) { int k = i >> j; if (k == 0) { if (nc) result[pos++] = S; break; } else if (k % 2) S ~= seq[j]; else if (S.length) nc = true; } } return result; } void main(string[] args) { int n = args.length == 2 ? toInt(args[1]) : 10; auto range = new int[n - 1]; foreach (i, ref el; range) el = i + 1; putr( ncsub(range).length ); } ------------------------- // 8) lazy D version without my libs import std.conv: toInt; import std.stdio: putr = writefln; struct Ncsub(T) { T[] seq; int opApply(int delegate(ref int[]) dg) { int result, n = seq.length; OUTER: for (int i = 1; i < (1 << seq.length); i++) { T[] S; bool nc = false; for (int j; j < seq.length + 1; j++) { int k = i >> j; if (k == 0) { if (nc) { result = dg(S); if (result) break OUTER; } break; } else if (k % 2) S ~= seq[j]; else if (S.length) nc = true; } } return result; } } void main(string[] args) { int n = args.length == 2 ? toInt(args[1]) : 10; auto range = new int[n - 1]; foreach (i, ref el; range) el = i + 1; int count; foreach (sub; Ncsub!(int)(range)) count++; putr(count); } ------------------------- // 9) lazy D version without my libs, no allocations // the slicing S[0..len_S] doesn't copy memory import std.conv: toInt; import std.stdio: putr = writefln; struct Ncsub(T) { T[] seq; int opApply(int delegate(ref int[]) dg) { int result, n = seq.length; auto S = new int[n]; OUTER: for (int i = 1; i < (1 << seq.length); i++) { int len_S; bool nc = false; for (int j; j < seq.length + 1; j++) { int k = i >> j; if (k == 0) { if (nc) { T[] auxS = S[0 .. len_S]; result = dg(auxS); if (result) break OUTER; } break; } else if (k % 2) S[len_S++] = seq[j]; else if (len_S) nc = true; } } return result; } } void main(string[] args) { int n = args.length == 2 ? toInt(args[1]) : 10; auto range = new int[n - 1]; foreach (i, ref el; range) el = i + 1; int count; foreach (sub; Ncsub!(int)(range)) count++; putr(count); } ------------------------- # 10) lazy Python version, no allocations from sys import argv def leniter(iterator): nelements = 0 for _ in iterator: nelements += 1 return nelements def ncsub(seq, S): n = len(seq) for i in xrange(1, 2 ** n): lenS = 0 nc = False for j in xrange(n + 1): k = i >> j if k == 0: if nc: yield lenS break elif k % 2: S[lenS] = seq[j] lenS += 1 elif lenS: nc = True n = 10 if len(argv) < 2 else int(argv[1]) s = [None] * (n-1) print leniter( ncsub(range(1, n), s) ) ------------------------- From clay at lakeserv.net Wed Jul 23 11:00:32 2008 From: clay at lakeserv.net (Clay Hobbs) Date: Wed, 23 Jul 2008 11:00:32 -0400 Subject: How do I compare files? In-Reply-To: References: Message-ID: <1216825232.18962.11.camel@generator> On Tue, 2008-07-22 at 17:29 -0700, Matimus wrote: > On Jul 22, 4:27pm, Clay Hobbs wrote: > > I am making a program that (with urllib) that downloads two jpeg files > > and, if they are different, displays the new one. I need to find a way > > to compare two files in Python. How is this done? > > > > -- Ratfink > > Do you just want to check to see if they are the same? Or do you > actually want to know what the differences are? > > import urllib > > data1 = urllib.urlopen("http://url.of.jpg1").read() > data2 = urllib.urlopen("http://url.of.jpg2").read() > > if data1 == data2: > print "they are the same" > I just wanted to see if they are different. The code I was using that didn't work was almost the same, except that the lines that download the files didn't end in .read(). Thank you for your help -- Ratfink From areyoulookon at gmail.com Mon Jul 21 07:32:57 2008 From: areyoulookon at gmail.com (lookon) Date: Mon, 21 Jul 2008 04:32:57 -0700 (PDT) Subject: How to install simplejson on WinXP Message-ID: I am new to python and had difficulty in installing simplejson on WinXP...Could anyone help me? Thanks From fredrik at pythonware.com Sun Jul 20 09:43:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 20 Jul 2008 15:43:53 +0200 Subject: Not entirely serious: recursive lambda? In-Reply-To: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> References: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> Message-ID: Michael Tobis wrote: > I realize that lambda is something of an orphan and was arguably a bad > idea for anything besides obfuscation, but obfuscation is exactly my > purpose here. Can a lambda call itself without giving itself a name? > Google was not my friend on this one, and I suspect there is no > answer. Relax, I am not going to submit a PEP about it. gerson kurz' writings on lambdaization might be helpful (or not): http://www.p-nand-q.com/python/lambdaizing_quicksort.html http://www.p-nand-q.com/python/stupid_lambda_tricks.html From Bill at SynectixLtd.com Fri Jul 11 09:48:13 2008 From: Bill at SynectixLtd.com (Bill Davy) Date: Fri, 11 Jul 2008 14:48:13 +0100 Subject: win32com.client (Howto edit Contacts in Outlook) References: <9vKdnRgocZUji_PVnZ2dnUVZ8vydnZ2d@bt.com> Message-ID: "Tim Golden" wrote in message news:mailman.325.1215781777.20628.python-list at python.org... > Bill Davy wrote: >> and since then have been busy with work, and my other job, and the >> garden. > > Aha! So you're English, are you? Looks like you're in the West Country. > Weather map suggests you're not short of rain over there :) > >> Now I am back looking at this (and using WInUSB to talk to a Maxim 3421E >> etc etc but that's another story). So any help today will be much >> appreciated. >> Rgds, > > Can't remember what the particular obstacles were you > were facing, but this runs OK on my setup - > Python 2.5.2 / pywin32 211 / Outlook 2003: > > > import os, sys > import win32com.client > constants = win32com.client.constants > > def items (contacts): > items = contacts.Items > item = items.GetFirst () > while item: > yield item > item = items.GetNext () > > # > # Add whatever fields you like from: > # http://msdn.microsoft.com/en-us/library/aa210907(office.11).aspx > # > FIELDS = ['FullName', 'CompanyName', 'Email1Address'] > > outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") > ns = outlook.GetNamespace ("MAPI") > for contact in items (ns.GetDefaultFolder (constants.olFolderContacts)): > if contact.Class == constants.olContact: > print contact > for field in FIELDS: > print " ", field, "=>", getattr (contact, field, "") > > > > Hope that helps. > TJG jUST IN CASE,. i CUT'NPASTED THE PROGRAM: import os, sys import win32com.client constants = win32com.client.constants def items (contacts): items = contacts.Items item = items.GetFirst () while item: yield item item = items.GetNext () # # Add whatever fields you like from: # http://msdn.microsoft.com/en-us/library/aa210907(office.11).aspx # FIELDS = ['FullName', 'CompanyName', 'Email1Address'] outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") ns = outlook.GetNamespace ("MAPI") for contact in items (ns.GetDefaultFolder (constants.olFolderContacts)): if contact.Class == constants.olContact: print contact for field in FIELDS: print " ", field, "=>", getattr (contact, field, "") --------------------------------------------------------------------------------------------------- And then I ran it: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.2.2 >>> ================================ RESTART >>> ================================ >>> Traceback (most recent call last): File "H:/Personal/OutlookIF1/t2.py", line 18, in outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application") File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 536, in EnsureDispatch mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], bForDemand=bForDemand) File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 393, in EnsureModule module = GetModuleForTypelib(typelibCLSID, lcid, major, minor) File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 262, in GetModuleForTypelib AddModuleToCache(typelibCLSID, lcid, major, minor) File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 554, in AddModuleToCache dict = mod.CLSIDToClassMap AttributeError: 'module' object has no attribute 'CLSIDToClassMap' >>> ------------------------------------------------------------------------------------------------- Outlook is running fine. This is how the fucntion where the failure occurs begins: def AddModuleToCache(typelibclsid, lcid, major, minor, verbose = 1, bFlushNow = not is_readonly): """Add a newly generated file to the cache dictionary. """ fname = GetGeneratedFileName(typelibclsid, lcid, major, minor) mod = _GetModule(fname) # if mod._in_gencache_ is already true, then we are reloading this # module - this doesn't mean anything special though! mod._in_gencache_ = 1 dict = mod.CLSIDToClassMap info = str(typelibclsid), lcid, major, minor for clsid, cls in dict.items(): clsidToTypelib[clsid] = info ----------------------------------------------------------------------------------------------- Yes, we have suffiicient rain but the gaden needed it. I am about to become the proud tenant of half an allotment. Still, this time last year we had floods. TIA, Bill From gagsl-py2 at yahoo.com.ar Fri Jul 11 03:41:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Jul 2008 04:41:22 -0300 Subject: socket-module: different behaviour on windows / unix when a timeout is set References: <4874FD50.1070404@nanl.de> Message-ID: En Wed, 09 Jul 2008 15:02:56 -0300, Mirko Vogt escribi?: > it seems that the socket-module behaves differently on unix / windows > when a timeout is set. [...] > Now I will change the code slightly - to be precise I set a timeout on > the socket: > > > # test.py > > import socket > sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) > sock.settimeout(3.0) # <----- > print 'trying to connect...' > sock.connect(('127.0.0.1',9999)) > print 'connected!' > > > # executed on linux > > $ python test.py > trying to connect... > Traceback (most recent call last): > File "test.py", line 5, in > sock.connect(('127.0.0.1',9999)) > File "", line 1, in connect > socket.error: (111, 'Connection refused') > $ > > > # executed on windows > >> C:\Python25\python.exe test.py > trying to connect... > connected! Which Python version? Which Windows version? I've tried 2.3.4, 2.4.4, 2.5.1 and 3.0a4, all on WinXP SP2, and in all cases I got an exception (details differ between versions). In no case I could make the connection succeed when nobody was listening at port 9999, as expected. -- Gabriel Genellina From fredrik at pythonware.com Wed Jul 16 09:01:27 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 16 Jul 2008 15:01:27 +0200 Subject: isPrime works but UnBoundLocalError when mapping on list In-Reply-To: <8AEDA5E3386EA742B8C24C95FF0C7580046232B6@PDC-MAIL3.ubisoft.org> References: <8AEDA5E3386EA742B8C24C95FF0C758004623111@PDC-MAIL3.ubisoft.org> <487DDEE9.8060305@timgolden.me.uk> <8AEDA5E3386EA742B8C24C95FF0C7580046232B6@PDC-MAIL3.ubisoft.org> Message-ID: Andreas Tawn wrote: > I don't have experience of too many other languages, but in C++ (and I > guess C)... That's invalid C (you cannot declare variables in the "for" statement itself, at least not in C89). And back in the old days, some C++ compilers did in fact leak declarations from "for" loops, and others didn't... > Is the Python behaviour just a happy side effect of the target list > assignment or specific design decision? I'd say it all follows from the fact that Python doesn't have variable declarations; if you want to stick to the principle that variables can introduced simply by assigning to them, you cannot introduce new blocks nilly-willy. So none of the basic structural elements do that; variables introduced inside an "if" statement or a "for-in" statement are no different from variables introduced outside them. And intro- ducing a new block only for the loop variables would be confusing and rather impractical, given how fundamental looping over sequences and iterables are in Python. (the discussions about loop variables in list comprehensions and generator expressions are a bit different; they're expressions, not statements, and shouldn't really do assignments as a side effect, any more than function calls should leak parameter names into the calling scope...) From teebes at gmail.com Tue Jul 1 14:51:29 2008 From: teebes at gmail.com (teebes) Date: Tue, 1 Jul 2008 11:51:29 -0700 (PDT) Subject: connecting to DBMS References: <669fe460-77bf-4e53-9f05-1237f2147b10@j1g2000prb.googlegroups.com> Message-ID: <6c1e5903-e21f-4aac-a802-d4b18259ccd4@z72g2000hsb.googlegroups.com> On Jul 1, 9:35?am, varun chadha wrote: > i am a newbie to python and is working on an application which needs > to connect to the database. can anyone guide me through the DBMS that > i can use and the module to connect to it. currently i have MySQL > installed using the link on the python.org site but is unable to > connect to it through python. pls specify the link ?to the tutorials > which can guide to connect and execute my query. hopes u understood > what i meant to say. > thanks in advance mysql-python is probably your best bet for MySQL databases http://sourceforge.net/projects/mysql-python/ As far as tutorials are concerned, the presentation linked in this page is very good, given by the creator of the interface Andy Dustman: http://bogdan.org.ua/2007/09/07/mysql-python-good-mysqldb-tutorial-examples.html (scroll down to page 7 for the stuff on MySQL). - Teebes From vshankar0 at gmail.com Sat Jul 19 06:06:30 2008 From: vshankar0 at gmail.com (Venky K Shankar) Date: Sat, 19 Jul 2008 15:36:30 +0530 Subject: Question In-Reply-To: References: Message-ID: <200807191536.30757.vshankar0@gmail.com> On Saturday 19 July 2008 03:14:20 pm Peter Otten wrote: > perl_wizard at manx.net wrote: > > Why is Perl so much better than python? > > Because you have the video: > > http://mail.python.org/pipermail/python-list/2004-March/253370.html >> what about this ? i feel python's better :) >> http://www.monstersandcritics.com/people/news/article_1339060.php > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From countryone77 at yahoo.com Sat Jul 19 08:19:50 2008 From: countryone77 at yahoo.com (Bev in TX) Date: Sat, 19 Jul 2008 05:19:50 -0700 (PDT) Subject: Missing sqlite3.h Error when Building Debug Python -- Windows Vista Message-ID: <048b8df4-8468-47a1-ae15-d84ca9d43e0a@y38g2000hsy.googlegroups.com> I am a complete newbie at building Python. I am trying to build it under MS Windows Vista (64-bit AMD) with MS VS2005. I'm doing that because I need debug libraries, which I did not see in the standard distribution. I downloaded the source and found the MSVS8 solution/project files. However, when I tried to build it I got the following error: ...\python-2.5.2\modules\_sqlite\connection.h(33) : fatal error C1083: Cannot open include file: 'sqlite3.h': No such file or directory I searched on the web, and at one place it said I would just need to download sqlite3.h from sqlite.org. I looked around there, but I could not find the source for sqlite 3.3.4. I went back and reread the PCbuild8\readme.txt file, and it mentions using the following command to download the sqlite: svn export http://svn.python.org/projects/external/sqlite-source-3.3.4 Do I really need to get the whole thing, or will just sqlite3.h resolve the build problem. As far as I know, I don't really need sqlite. If I do need to execute that svn command, how do I execute that under MS Windows? Or is there some other way in which to circumvent this error? Thanks, Bev in TX From gary at byoteki.com Fri Jul 25 23:26:21 2008 From: gary at byoteki.com (Gary Josack) Date: Fri, 25 Jul 2008 23:26:21 -0400 Subject: How to find processes from Python In-Reply-To: <20080726022330.GA25922@cskk.homeip.net> References: <20080726022330.GA25922@cskk.homeip.net> Message-ID: <488A995D.2000101@byoteki.com> Cameron Simpson wrote: > On 25Jul2008 11:34, Johny wrote: > | Is there a way how to find out running processes?E.g. how many > | Appache's processes are running? > > See the popen function and use the "ps" system command. > Use of the popen functions is generally discouraged since being deprecated for the subprocess module. Look at the subprocess module which will allow you to run processes and capture the output. The docstrings have good examples for how to use it. From thomas.troeger.ext at siemens.com Fri Jul 4 07:48:07 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Fri, 04 Jul 2008 13:48:07 +0200 Subject: Static Class Initialization Question. Message-ID: Hello, I have a class that looks like this: class A(object): def __init__(self, a=0, b=1): self.a, self.b=a, b def __str__(self): return "%s(%d,%d)" % (type(a).__name__, self.a, self.b) I want to have a list of such classes instantiated automatically on startup of my program. My current (most probably clumsy) implementation looks like this: bla=[A(x[0], x[1]) for x in ((1, 2), (3, 4))] giving the following: >>> map(str, bla) ['A(1,2)', 'A(3,4)'] Is there a better way to construct a list of such classes? Basically what I want is something similar to the following C example: struct { int a; int b; } bla[]={ {1, 2}, {3, 4} }; Regards, T. From ptmcg at austin.rr.com Thu Jul 31 23:46:23 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 31 Jul 2008 20:46:23 -0700 (PDT) Subject: Genital Hair Removal References: Message-ID: <036d2619-cc7b-41bb-8481-381ee8afa108@s50g2000hsb.googlegroups.com> On Jul 31, 10:40?pm, "dr.jonver" wrote: > Genital Hair Removal http://misspelled_words_in_URLs_are_funny.blogspot.com/2008/07/genital-hair-removal.html Python provides the del command, as in: del self.genital_hair If "Genital Hair" is an element in a list, you can remove it using: items.remove("Genital Hair") Be careful though, you should not modify a sequence while iterating over it. -- Paul From adamc55 at gmail.com Mon Jul 7 14:08:56 2008 From: adamc55 at gmail.com (Adam C.) Date: Mon, 7 Jul 2008 11:08:56 -0700 (PDT) Subject: Dynamically Changing the Base Class References: <6d60c362-ba17-4414-babd-2cc254526bca@c58g2000hsc.googlegroups.com> Message-ID: On Jul 7, 9:11?am, George Sakkis wrote: > On Jul 7, 9:31?am, "Adam C." wrote: > > > > > We have a situation where we want a Swig-generated Python class to > > have a different base (not object). It doesn't appear that we can > > coerce Swig into generating the class we want at present (but we are > > still enquiring). > > > Is it possible to dynamically change the base class to something else? > > Initial experiments appear to show it is not: > > -------------------------------- snip -------------------------------->>> class Foo(object): > > > ? ? ? ? pass > > > >>> class Foozle(object): > > > ? ? ? ? pass > > > >>> Foozle.__bases__ = (Foo,) > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? ? Foozle.__bases__ = (Foo,) > > TypeError: __bases__ assignment: 'Foo' deallocator differs from > > 'object' > > -------------------------------- snip -------------------------------- > > > Is there a solution I am missing? > > > Thanks in advance. > > Supposedly it should (usually) work, there's a 6 year old patch for > this (http://bugs.python.org/issue635933). Check if Swig can generate > old-style classes (i.e. not inheriting from object) since __bases__ > assignment works for them. > > HTH, > George Thanks. I think we would want new-style classes, and 6-year-old patches strike me as maybe a little out of the desired path... so this really just doesn't work in modern Python? From digitig at gmail.com Fri Jul 4 11:19:34 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 4 Jul 2008 16:19:34 +0100 Subject: Can't get Python for Windows to run Message-ID: I have Python 2.5 working just fine on my system. I've tried downloading and installing the MS Windows Python extensions, but can't get pythonw.exe (that's the windows executable, right?) to do anything. I double-click it, nothing happens. I run it from a command prompt, it just returns me to the command prompt. The only possible clue I have is that the installation process produced the error message: "Can't install shortcuts - 'C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Python 2.5' is not a folder" That's right, it isn't a folder -- the relevant folder would have been C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Programming\\Python 2.5' but the installer never gave me the chance to choose that. That woudn't stop me running Pythonw directly from the folder in which it's installed, though, would it? -- Tim Rowe From john.tantalo at gmail.com Thu Jul 24 03:29:51 2008 From: john.tantalo at gmail.com (John Tantalo) Date: Thu, 24 Jul 2008 00:29:51 -0700 Subject: parameterized classes Message-ID: Is there is a better way to create parameterized classes than defining and returning a class in a closure? I ask because I want to create arbitrary BaseRequestHandler subclasses that delegate line handling to a given line handler, as in this example: from SocketServer import * class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass def LineRequestHandler(handler): class __LineRequestHandler(BaseRequestHandler): def handle(self): for line in self.lines(): handler.handle(line) def lines(self): line = self.line() while line: yield line line = self.line() def line(self): parts = [] while not parts or parts[-1] and not parts[-1][-1] == "\n": parts.append(self.request.recv(2**10)) if parts: return ''.join(parts)[0:-1] return __LineRequestHandler class SomeLineHandler: def handle(self, line): print "I got a line: %s" % line if __name__ == '__main__': s = ThreadingTCPServer(("", 2005), LineRequestHandler(SomeLineHandler())) s.serve_forever() I really wish I could create a class whose instances were classes that subclassed BaseRequestHandler. Is this possible, or is there a better way than my approach here? Or am I crazy? And I may be dense, so if there is an easier way to stream sockets as line streams, please let me know. I honestly don't think it should be this difficult to implement a socket handler this simple. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rgbaz.eu Tue Jul 1 08:30:04 2008 From: python at rgbaz.eu (Python.Arno) Date: Tue, 1 Jul 2008 14:30:04 +0200 Subject: raw_input into Tkinter ? In-Reply-To: <634e2b50-45ba-4b93-89b4-0afd739adaf3@z66g2000hsc.googlegroups.com> References: <634e2b50-45ba-4b93-89b4-0afd739adaf3@z66g2000hsc.googlegroups.com> Message-ID: On 30 jun 2008, at 18:55, jamitwidme at gmail.com wrote: > Is there any way to type into a Tkinter frame window? > I want to use raw_input() within a Tkinter frame. > -- > http://mail.python.org/mailman/listinfo/python-list > > You could use the Tkinter.Entry option from dialog windows... http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm gr Arno From rjagodic at gmail.com Thu Jul 17 12:27:27 2008 From: rjagodic at gmail.com (Ratko) Date: Thu, 17 Jul 2008 09:27:27 -0700 (PDT) Subject: properly delete item during "for item in..." Message-ID: <781b2deb-fa6b-44cd-ae7b-638de6acc43f@d45g2000hsc.googlegroups.com> Say you have something like this: for item in myList: del item Would this actually delete the item from the list or just decrement the reference counter because the item in myList is not associated with name "item" anymore (but still is with myList[itemIndex])? In other words, is "item" a temporary reference to myList[itemIndex] or is it actually that reference that myList has stored? I am not sure if this question even makes any sense anymore. I've been using python for years and never had any problems (and I don't now either) but now that I had to revisit c++/STL, I had to deal about these issues and was wondering how python does it. Thanks, Ratko From samwyse at gmail.com Wed Jul 9 11:07:39 2008 From: samwyse at gmail.com (samwyse) Date: Wed, 9 Jul 2008 08:07:39 -0700 (PDT) Subject: Logging to zero or more destinations References: <87r6a4du2k.fsf@merkury.smsnet.pl> Message-ID: On Jul 8, 3:01?pm, Rob Wolfe wrote: > samwyse writes: > > P.S. ?I tried researching this further by myself, but the logging > > module doesn't come with source (apparently it's written in C?) and I > > don't have the time to find and download the source to my laptop. > > Hmmm... that's strange. It is a pure Python package. > > $ ls /usr/lib/python2.5/logging/ > config.py ?config.pyc ?handlers.py ?handlers.pyc ?__init__.py ?__init__.pyc > > HTH, > Rob Oops, my bad. I was using IDLE and tried the "Open Module..." command on logging, not logging.something. From paul.hankin at gmail.com Sun Jul 13 18:29:56 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sun, 13 Jul 2008 15:29:56 -0700 (PDT) Subject: Functional/Best? References: <1215956345.3028.10.camel@localhost.localdomain> Message-ID: On Jul 13, 7:00?pm, Terry Reedy wrote: > Tim Cook wrote: > > I guess I can classify my application(s) as more procedural than > > anything else. ?But I have a question about the best way to handle > > something in Python. > > > When given a mapping of keywords, I want to call a function based on a > > certain keyword found when parsing a text file. ?The mapping looks like > > this: > > > definClassMap={'SECTION':'bldSection','COMPOSITION':'bldComposition','OBSER VATION':'bldObservation','ITEM_TREE':'bldItemTree'} > > > So if the text file contains 'ITEM_TREE' ?I want to call bldItemTree > > which creates an instance of the class ItemTree. ? > > > I currently use an if ..., elif ... construct. > > Is there a better, more efficient, more Pythonic way of doing this? > > Yes. Create a mapping of keywords to function objects rather than to > function names! > > def bldSection(): > ... > def bldItemTree(): > > class_map={ > ? ?'SECTION':bldSection, > ? ?'COMPOSITION':bldComposition, > ? ?'OBSERVATION':bldObservation, > ? ?'ITEM_TREE':bldItemTree, # trailing comma allows easy additions > > } > > for word in parselist: > ? ?try; > ? ? ?class_map[word]() > ? ?except KeyError: > ? ? ? A nice variant of this, which minimizes repetition, is to group all the factory methods together into a class, naming them the same as the keyword... class Builder(object): def SECTION(self): ... def COMPOSITION(self): ... def OBSERVATION(self): ... def ITEM_TREE(self): ... builder = Builder() for word in parse_list: item = getattr(builder, word)() ... -- Paul Hankin From max at alcyone.com Tue Jul 29 22:23:10 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 19:23:10 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> Message-ID: Carl Banks wrote: > Bzzt. "if len(x)!=0" is a simple explicit that would work for this > class and all built-in containers. (Or should--Steven D'Aprano's > objections notwithstanding, any reasonable container type should > support this invariant. From a language design standpoint, an "empty" > builtin could have been created to simplify this even more, but since > there isn't one len(x)!=0 will have to do.) That you choose not to test for non-emptiness doesn't change the fact that it's already a builtin part of the language that is supported by all fundamental types and is overridable by anyone writing a custom type. Use it or don't use it, but it's an example of precisely what you were asking for that is both practical and already in widespread use. > Now, you guys keep whining "But what if you don't know what kind of > object you're expecting?!!" It's a fair question, and my belief is > that, in practice, this almost never happens. Duck typing happens > between numeric types often, and between container types often, but > almost never between both numeric and container types. Their usages > are simply too different. What should a custom type return as its length to pass your non-emptiness test if it's a custom sequence class that is an infinite generator? It's non-empty, but doesn't have a length. You test for non-emptiness by Boolean comparison, not by testing its length. > So I present another question to you: Give me an useful, non-trivial, > example of some code that where x could be either a numeric or > container type. That would be the first step to finding a > counterexample. (The next step would be to show that it's useful to > use "if x" in such a context.) Well, asked and answered, but it apparently wasn't good enough, so I doubt anyone's going to enjoy playing your game much further. You're asking for an example of something that demonstrates a use case that's _already used by all the builtin types_, so eh, have fun drawing imaginary lines in the sand. > Once again, I'm invoking the contraint against simply using x in a > boolean context, or passing x to a function expecting a boolean > doesn't count, since in those cases x can be set to the result of the > explicit test. Next answer you're just add another constraint, so I suspect the only one enjoying this word game is you. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Love is the selfishness of two persons. -- Antoine de la Salle From duncan.booth at invalid.invalid Tue Jul 29 03:36:40 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Jul 2008 07:36:40 GMT Subject: block/lambda References: <0406eb4f-8dec-4ce2-b506-8e597de2958d@56g2000hsm.googlegroups.com> Message-ID: iu2 wrote: > Is it possible to grant Python another syntactic mark, similar to > triple quotes, that will actually make the enclosed code a compiled > code, or an anonymous function? > Yes, the syntactic mark you are looking for is 'def'. Your example becomes: >>> def dotimes(n, callable): for i in range(n): callable(i) >>> def block(i): for j in range(i): print j, print >>> dotimes(5, block) 0 0 1 0 1 2 0 1 2 3 The only thing you asked for that this doesn't do is make 'block' anonymous, but actually that is a good thing. -- Duncan Booth http://kupuguy.blogspot.com From deets at nospam.web.de Wed Jul 30 09:10:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 30 Jul 2008 15:10:19 +0200 Subject: Standard module for parsing emails? References: Message-ID: <6fb7k3Faok8fU1@mid.uni-berlin.de> Phillip B Oldham wrote: > Is there a standard library for parsing emails that can cope with the > different way email clients quote? AFAIK not - as unfortunately that's something the user can configure, and thus no atrocity is unimaginable. Hard to write a module for that... All you can try is to apply a heuristic like "if there are lines all starting with a certain prefix that contains non-alphanumeric characters". But then if the user configures to quote using XX you're doomed... Diez From bronger at physik.rwth-aachen.de Sat Jul 26 08:40:00 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 26 Jul 2008 14:40:00 +0200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> <009b130f$0$20313$c3e8da3@news.astraweb.com> Message-ID: <87wsj8akf3.fsf@physik.rwth-aachen.de> Hall?chen! Steven D'Aprano writes: > On Sat, 26 Jul 2008 11:08:12 +0200, Nikolaus Rath wrote: > >> [...] >> >> so 'self' should *automatically* only be inserted in the function >> declaration, and *manually* be typed for attributes. > > > That idea might have worked many years ago, but not now. The > problem is, what happens here? > > class Foo(object): > def foo(self, arg): > self.whatever = arg + 1 > @classmethod > def cfoo(cls, arg): > cls.whatever = arg - 1 > @staticmethod > def sfoo(arg): > print arg See . It is only added to non-decorated methods within a class. This implies that you can switch this mechanism off with a noop decorator. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bronger at jabber.rwth-aachen.de From animator333 at gmail.com Thu Jul 24 13:53:38 2008 From: animator333 at gmail.com (King) Date: Thu, 24 Jul 2008 10:53:38 -0700 (PDT) Subject: instance comparison References: <4de44b9e-0e0d-49b1-8aa5-4d3976fceafc@u12g2000prd.googlegroups.com> <4888879a$0$1043$426a74cc@news.free.fr> Message-ID: No, The the class is not subclass of another one. Problem still persist. The code is pretty huge and I am trying to post the information as clear as possible. From jdscript at gmail.com Sat Jul 12 03:49:48 2008 From: jdscript at gmail.com (happy) Date: Sat, 12 Jul 2008 00:49:48 -0700 (PDT) Subject: variable question References: <6f02608a-2b2e-478d-a153-d10bbfb58981@c58g2000hsc.googlegroups.com> <48782d93$0$20780$9b622d9e@news.freenet.de> Message-ID: <98553eaa-a435-488f-9f14-831d858ac800@m45g2000hsb.googlegroups.com> On Jul 12, 8:05?am, Robert Lehmann wrote: > On Fri, 11 Jul 2008 20:13:04 -0700, happy wrote: > > Can a variable be considered the simplest of the data structures. I am > > tutoring some kids about basics of programming using python. Not an > > expert in computer sciences, but am a python enthusiast. > > Why do you need this additional layer of indirection? Just explain the > real simple data structures ? la "look, kids, a string is a chain of > characters which are bytes actually. etc. here>". Although explaining encodings is an *important* thing (which > many programmers still get wrong), it might be second priority to kids > and you might just want to say "a string is text" and jump into higher- > order data structures. > > > I wanted to know if it is correct to say a variable is a data structure, > > it has a name and a value. > > Not at all. This sounds a lot like an explanation for variables in other > languages (such as C, where the value also has a type). In Python, we use > to speak of "names," not variables. They are more like name tags you can > put on objects -- or you don't. Depending on the age/interest of your > students, I'd insert an explanation about references, reference counting > and garbage collection here (they usually find that quite understandable > and it paves the way for The Real Stuff, even though you might argue that > the refcounting gc is a CPython detail and might become obsolete with > PyPy's rise ). > > The important thing is really that Python's approach of references is > nearly orthogonal to the common approach of variables. In other > languages, variables are (as you described above) containers (a bucket, > really!) in your memory where you can put stuff into. Assignment is > usually a copy or pointer operation. > Python does not care at all about your memory. You have abstract objects > (incidentally saved in your memory, okay) with names being one mechanism > to reference them. Here, assignment is always a "put the left-hand side > name tag onto the right-hand side object". > > > Put a stack of variables in a special data > > structure called a dictionary where the each name associates to a value. > > If in a data structure, one uses numbers starting from 0 to describe the > > name, it becomes a list and ?so forth.... > > First off, you really put objects in your data structures. Names are a > one-way mapping -- the object does not know which name tags are assigned > to it. > > Your explanation of dictionaries and lists sounds a little bit upside- > down (not the mapping name->value or number->value makes it a dict or > list -- the data structure makes it a mapping with this and that > behaviour). > > HTH, > > -- > Robert "Stargaming" Lehmann Thanks for the reply. I think its better to leave the "teach kiddies" tutoring opportunity for the python experts out there. Would "python experts" have an appetite for newbies and "kiddies"? Only time will tell... I must really focus on learning the language better. "Look kids, you will learn it when you grow up... Now get out of here..." From babacity4 at gmail.com Thu Jul 24 16:50:32 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:50:32 -0700 (PDT) Subject: www sextv1 pl - Amazing porn video collection Message-ID: <87a018bf-0bfe-4c53-9c0a-63979a49e7bb@w1g2000prk.googlegroups.com> www sextv1 pl . >>>>>>>>>>Best Collection of Sextv1 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE www sextv1 pl VIDEOS<<<<<<<<<<< . www sextv1 pl From Ming.YIN at murex.com Fri Jul 11 00:02:25 2008 From: Ming.YIN at murex.com (YIN Ming) Date: Fri, 11 Jul 2008 12:02:25 +0800 Subject: recommended gcc versions for python2.5 compilation on Solaris sparc/x86, AIX, Linux Message-ID: <9347F3EEF61FC542A7D9211A42CD7E6387E071@dolphin.sg.murex.com> Dear All, We are going to compile python2.5.1 with gcc on various platforms, including Solaris8(sparc), Solaris10(x86), AIX and Linux. Just want to check if there are recommended gcc versions for these platforms. We aim to: 1. use a single version of gcc for all platforms 2. use new version of gcc (rather than odd version) Thanks and best regards, Yin Ming -------------------------------------------------------- This e-mail contains information for the intended recipient only. It may contain proprietary material or confidential information. If you are not the intended recipient you are not authorised to distribute, copy or use this e-mail or any attachment to it. Murex cannot guarantee that it is virus free and accepts no responsibility for any loss or damage arising from its use. If you have received this e-mail in error please notify immediately the sender and delete the original email received, any attachments and all copies from your system. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Mon Jul 21 12:06:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 21 Jul 2008 17:06:03 +0100 Subject: Python Written in C? In-Reply-To: References: <2.2.32.20080721011801.011bf00c@pop.xs4all.nl> Message-ID: <4884B3EB.4090001@timgolden.me.uk> mk wrote: > Grant Edwards wrote: > >> Using punch-cards and paper-tape. Real programmers can edit >> their programs with a pointy stick and some home-made >> sticky-tape. > > Wrong! Real programmers can program using only Touring machine Is that some kind of bicycle? TJG From teh.saber at gmail.com Sun Jul 13 11:18:55 2008 From: teh.saber at gmail.com (teh_sAbEr) Date: Sun, 13 Jul 2008 08:18:55 -0700 (PDT) Subject: wxPython code giving strange errors. Message-ID: <01694ab5-7b5e-4e57-8b86-bf89b0beec82@m44g2000hsc.googlegroups.com> I'm busy trying to learn wxPython, and i'm trying to run the following piece of code (its from the wxPyWiki tutorial): import wx ID_ABOUT = 101 ID_EXIT = 110 class MainWindow(wx.Frame): def __init__(self,parent,id,title): wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) self.control = wx.TextCtrl(self,1,style=wx.TE_MULTILINE) self.CreateStatusBar() filemenu = wx.Menu() filemenu.Append(ID_ABOUT,"&About"," Information about this program.") filemenu.AppendSeparator() filemenu.Append(ID_EXIT,"E&xit"," Terminate the program.") menuBar = wx.MenuBar() menuBar.Append(filemenu,"&File") self.SetMenuBar(menuBar) self.Show(True) app = wx.PySimpleApp() frame = MainWindow(None, -1, "Sample editor") app.MainLoop() Simple enough, but every single time I try to run it IDLE gives me this instead of the app I was hoping for: Traceback (most recent call last): File "C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap \Python Stuff\Batch Picture Converter\main.py", line 24, in frame = MainWindow(None, -1, "Sample editor") File "C:\Documents and Settings\Enrico Jr\My Documents\Jr's Crap \Python Stuff\Batch Picture Converter\main.py", line 9, in __init__ wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,100)) File "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx \_windows.py", line 501, in __init__ _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs)) PyNoAppError: The wx.App object must be created first! As far as I can tell, the wx.App object IS being created first. I suspect a race condition of some sort here, but can anyone shed some light on this? From karthikbalaguru79 at gmail.com Tue Jul 22 05:06:14 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Tue, 22 Jul 2008 02:06:14 -0700 (PDT) Subject: Instance References: <120cea3a-33a9-49ec-8932-7cef2e5aef17@25g2000hsx.googlegroups.com> Message-ID: On Jul 17, 5:34 pm, "Calvin Spealman" wrote: > On Thu, Jul 17, 2008 at 2:56 AM, karthikbalaguru > > wrote: > > Hi, > > > I am new to python. I am trying to use the python files given to me > > for bringing up a setup. > > I get the following error while trying to use a python file - > > AttributeError : Classroom instance has no attribute 'desk_offset' > > > How to resolve this ? > > Should i need to define desk_offset to zero in the python file ? > > > Any ideas .. > > This means you did something like this: > > class Foo: > def __init__(self): > self.bar = 10 > > f = Foo() > print f.quu > ... > AttributeError : Foo instance has no attribute 'quu' > > See? You tried to use an attribute that simply doesn't exist. Look in > the traceback for where you used the desk_offset attribute, and figure > out why you thought the object had such an attribute and why it does > not. > Thx!! Your ideas were useful. I read some basic lessons on python and that were also very helpful in solving the problem. Thx , Karthik Balaguru From jadamwilson2 at gmail.com Tue Jul 22 09:35:50 2008 From: jadamwilson2 at gmail.com (jadamwil) Date: Tue, 22 Jul 2008 06:35:50 -0700 (PDT) Subject: fromfile error on windows, not mac References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> <9650a33b-40b5-46a7-a05e-5b059117891f@b1g2000hsg.googlegroups.com> Message-ID: <185cc290-18a5-4572-9fda-fa0bb785c831@z72g2000hsb.googlegroups.com> On Jul 22, 2:05?am, Uwe Schmitt wrote: > jadamwil schrieb: > > > > > Hello, > > I am using the numpy fromfile function to read binary data from a file > > on disk. The problem is that the program runs fine on a Mac, but gives > > an error or warning on windows when trying to read the data. I use it > > like this: > > > Signal = zeros((N, 16), dtype=float32) > > for sample in range(0, N): > > ? # this function gets the next position in the file to seek to > > ? s = getFilePos(sample) > > > ? # go to the correct location in the file; this IS checked to make > > sure it is within the file > > ? mFile.seek(s) > > > ? # read the 16 float32 values from the file > > ? D = fromfile(mFile, dtype=numpy.float32, 16) > > > ? # save D in Signal > > ? Signal[sample, :] = D > > > This will fail when sample is ~4. If I change the range to (5,N), > > skipping the "bad" file location, it will run fine for a few samples, > > and then give another error. The message it gives is: > > "16 items requested but only 7 read" > > > So D is a 7x1 vector, and the program dies when it tries to assign D > > to the slice of Signal ("ValueError: shape mismatch: objects cannot be > > broadcast to a single shape"). > > > On windows, the Python version is 2.5.2, and the most recent numpy and > > scipy are being used as well. I tried using Enthought, but it gave > > this error as well, in addition to a c runtime error whenever I > > imported scipy (which is another post topic...). > > > Any ideas on what might be causing this? Is there a way to debug the > > fromfile function? And, remember, this works perfectly on a Mac. Would > > compiling everything (python, scipy, numpy) potentially solve this? > > Did you open the file in binary mode ? > > Greetings, Uwe Yes I did. Would that make a difference between a mac and windows? Thanks From victorsubervi at gmail.com Tue Jul 29 12:47:48 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 29 Jul 2008 18:47:48 +0200 Subject: Windows Interpreter In-Reply-To: <488F1DB3.4010608@timgolden.me.uk> References: <4dc0cfea0807290606j9fa5edfkc6b70551715d06ac@mail.gmail.com> <488F1745.4020705@timgolden.me.uk> <4dc0cfea0807290626p4b05376en49ccb18f0e1eb4bb@mail.gmail.com> <488F1DB3.4010608@timgolden.me.uk> Message-ID: <4dc0cfea0807290947n5d5ebf6fw8d358c49bad8cd57@mail.gmail.com> I?ll try that. Back online in a week. Victor On 7/29/08, Tim Golden wrote: > > Victor Subervi wrote: > >> def a(): >> chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', >> '\\yz'] >> rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like the >> Beast? Who can wage war against him?\par' >> for char in chars: >> c = '(?<=' + char + ')' >> test = re.search(c, rtf_markup) >> try: >> junk = test.group(0) >> print char >> except: >> pass >> >> Now, I can paste that entire fn in linux. But in windows I have to paste >> it line_by_line. Pain in butt! And it indents automatically. How change that >> behavior. >> > > Well, I'm not really sure what to say. I've just copied that > whole section with drag-mouse, Ctrl-C. I then opened a new > interpreter window (effectively, Start > Run > python) and > right-clicked over the window. At this point, the lines I > copied were copied in and the function accepted by the > interpreter. > > I do have QuickEdit on by default in all by console windows, > but the only difference I expect that to make is that you'd > otherwise have to use the window's System Menu (Alt-Space, > Edit, Paste). > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From diordna at gmail.com Sat Jul 19 00:29:10 2008 From: diordna at gmail.com (Stephen Johnson) Date: Sat, 19 Jul 2008 00:29:10 -0400 Subject: Any Game Developers here? In-Reply-To: <76b841590807181951p10159677n881d2bdadf4f69fc@mail.gmail.com> References: <6fb70b9f-8f3c-4063-b74d-5581d716d836@c58g2000hsc.googlegroups.com> <4A235BC6-5E46-4402-AF2D-BA3DBC175517@gmail.com> <76b841590807181605r106995d2k98486993a4eaccc4@mail.gmail.com> <9B960401-8D79-44BC-B4A5-4BE2BD1869BC@gmail.com> <76b841590807181951p10159677n881d2bdadf4f69fc@mail.gmail.com> Message-ID: <104129B8-51F4-45DF-86B0-84597CA8D76E@gmail.com> Yes, I will put the demo up on my web site (www.steveasleep.com) with fully commented source code and will probably spend a couple more months on it making it into a proper game. -Steve Johnson On Jul 18, 2008, at 10:51 PM, Michael Lubker wrote: > PyOhio sounds fun... I've been wanting to get some sort of Barcamp or > GameJam running where I live (in Austin, so you'd think there would be > people interested) but no-one will bite. :/ > > Escort Wing was a fun project... I did a few mods for EW1. > > Will you release this demo anywhere? Just curious. > > Thanks > Michael > > On Fri, Jul 18, 2008 at 7:52 PM, Stephen Johnson > wrote: >> Yes, I wrote the music, the GUI, and bits of code here and there.. >> Will >> Hogben is working on EW 2 for Freeverse right now. But that was in >> BlitzMax, >> and I'm in greener pastures now, working on my demo for PyOhio. >> -Steve Johnson >> On Jul 18, 2008, at 7:05 PM, Michael Lubker wrote: >> >> I'm interested in general... I know about PyGame and Pyglet, and have >> used both. We're currently using Python-Ogre. In the end, I am >> looking >> to find people interested in my project ( see >> http://youtube.com/watch?v=E0QQ9JuclxE ), but I also want to find >> people experienced with Python in general, not just one library. >> (though of course I know that's not too likely) >> >> Aren't you one of the Escort Wing developers? :) >> >> Thanks >> Michael >> >> On Fri, Jul 18, 2008 at 5:13 PM, Stephen Johnson >> wrote: >> >> I use the Pyglet library to make games. You want to look at the >> pyglet and >> >> pygame mailing lists, not this one. Use Google. >> >> In my opinion, PyGame is clunky and Pyglet is elegant, simple, and >> >> comprehensive. PyGame has more examples available, but Pyglet has >> great >> >> documentation and enough examples to answer any questions you might >> have. >> >> Both have active communities. >> >> -Steve Johnson >> >> On Jul 18, 2008, at 5:38 PM, Michael Lubker wrote: >> >> Any people that use Python as the predominant language for their game >> >> development here? >> >> ~Michael >> >> -- >> >> http://mail.python.org/mailman/listinfo/python-list >> >> >> >> >> >> -- >> ~ "The world hates change, yet it is the only thing that has brought >> progress." ~ Charles Kettering >> >> http://snowballz.joey101.net >> >> > > > > -- > ~ "The world hates change, yet it is the only thing that has brought > progress." ~ Charles Kettering > > http://snowballz.joey101.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From thermostat at gmail.com Wed Jul 16 14:00:05 2008 From: thermostat at gmail.com (Dan) Date: Wed, 16 Jul 2008 11:00:05 -0700 (PDT) Subject: For_loops hurt my brain. References: <4874c21f-befa-4e9f-a99d-486cc9c9b5b8@d77g2000hsb.googlegroups.com> Message-ID: <2b90e4bd-2797-4be3-8a82-ef7b66493c48@d45g2000hsc.googlegroups.com> On Jul 16, 1:42 pm, bsag... at gmail.com wrote: > This script uses a simple for loop to zip some files. However I am > repeating code that cries out for a nested loop. My two lists of > files_to_be_zipped (spare and seekfacts) are of uneven length so I > can't seem to decipher the "for_logic". I would appreciate any help. > Thanks, Bill > > import zipfile > import os > > zips = [ > 'c:/spare.zip', > 'c:/seekfacts.zip' > ] > spare = [ > 'c:/spare/huge.fm3', > 'c:/spare/huge.wk3' > ] > seekfacts = [ > 'c:/seekfacts/bookmark.html', > 'c:/seekfacts/index.htm', > 'c:/seekfacts/seek.css', > 'c:/seekfacts/seek.js' > ] > > zFile = zipfile.ZipFile(zips[0], 'w') > for files in spare: > zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED) > zFile.close() > > zFile = zipfile.ZipFile(zips[1], 'w') > for files in seekfacts: > zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED) > zFile.close() I would do something like this: # UNTESTED import zipfile import os zip_dict = { 'spare' : ['c:/spare.zip', 'c:/seekfacts.zip'], 'seekfacts' : [ 'c:/seekfacts/bookmark.html', 'c:/seekfacts/index.htm', 'c:/seekfacts/seek.css', 'c:/seekfacts/seek.js' ] } for key,value in zip_dict.items(): zFile = zipfile.ZipFile("c:/%s.zip" % key, 'w') for fname in value: zFile.write(fname, os.path.basename(files), zipfile.ZIP_DEFLATED) zFile.close() # End untested code. This implicitly maps thing with the key foo to the zip file c:/ foo.zip, but if you want to be more general, I would suggest thinking about making a class. -Dan From sajmikins at gmail.com Mon Jul 28 17:56:24 2008 From: sajmikins at gmail.com (Simon Forman) Date: Mon, 28 Jul 2008 14:56:24 -0700 (PDT) Subject: Is it allowed to use function results as default arguments ? References: Message-ID: <936daef1-5ffb-4496-b67f-b68d82d021d4@z11g2000prl.googlegroups.com> On Jul 28, 1:28?pm, Stef Mientki wrote: > hello, > > I've a perfect working procedure, > at least as far I've tested it it works perfect. > > But I was just experimenting with inspect, > and saw that the default argument was not parsed correctly. > > So I wonder if this is allowed: > > def Get_Relative_Path ( target, base=os.curdir ) : > ? ... > > As inspect returns the following: > > (['target', 'base'], None, None, ('.',)) > > thanks, > Stef Mientki os.curdir is '.' on many platforms. What did you expect inspect to show? |>>> import os |>>> os.curdir '.' From bruno.42.desthuilliers at websiteburo.invalid Fri Jul 4 06:26:32 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 04 Jul 2008 12:26:32 +0200 Subject: Newbie, list has no attribute iteritems In-Reply-To: <12caa75c-455a-4ab3-a9c3-4bd191b6965d@k13g2000hse.googlegroups.com> References: <12caa75c-455a-4ab3-a9c3-4bd191b6965d@k13g2000hse.googlegroups.com> Message-ID: <486dfac7$0$3624$426a74cc@news.free.fr> rabad a ?crit : > Hi, > I've created a custom filter based on HTMLParser, with the following > source: > >(snip) > But when I use it, it gives me the following error message: > ERROR Processor exception: AttributeError: 'list' object has no > attribute 'iteritems' (snip) > File "d:\esp\lib\python2.3\processors\DocDumpF.py", line 178, in > __html_attrs > _attrs = ' %s' % (' '.join([('%s="%s"' % (k,v)) for k,v in > attrs.iteritems() > ])) > > Anybody knows why it says attrs is not a list element? Actually, what the traceback says is that 1/ attrs is a list object 2/ list objects have no attribute named iteritems If you assumed it was a dict, then it's probably time to re-read HTMLParser's doc. Else if you assumed list had an iteritems method, then it's probably time to re-read the Python's tutorial !-) IIRC, HTMLParser represents attributes as a list of (attrname, value) pairs. If so (please check it out), your method should be rewritten as return ' %s' % (' '.join(('%s="%s"') % attr for attr in attrs) As a side note: __double_leading_undescores is probably a bit extrem. The convention for implementation attributes is _single_leading_underscore. From ericdfirst at gmail.com Wed Jul 23 13:09:35 2008 From: ericdfirst at gmail.com (Eric First) Date: Wed, 23 Jul 2008 12:09:35 -0500 Subject: Wrapping std::set in Boost::Python Message-ID: <349c44440807231009g4908787ekdcbc930595781647@mail.gmail.com> All: Has anybody had success at wrapping std::set using Boost::Python? Any ideas, snippets of code, etc... would be very helpful. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwahler at gmail.com Thu Jul 10 00:13:31 2008 From: dwahler at gmail.com (David Wahler) Date: Wed, 9 Jul 2008 23:13:31 -0500 Subject: sort(cmp=func) In-Reply-To: References: Message-ID: On Wed, Jul 9, 2008 at 10:58 PM, Daniel Fetchinson wrote: > > > I have a list of objects that generate code. Some > > of them depend on others being listed first, to > > satisfy dependencies of others. > > > > I wrote a cmp function something like this: > > > > def dep_cmp(ob1, ob2): > > > > if ob1.name in ob2.deps: > > return -1 > > else: > > return 1 > > > > I also tried returning 0 when there were no dependency > > relationships between the objects. > > > > This failed, because every object was not compared with > > ever other. I imagine that this is because sort assumes > > that if a > b and b > c, then a > c. In my case, this > > isn't really true. If a is not dependent on b, and > > b is not dependent on c, that doesn't mean that a is not > > dependent on c. > > > > Is there a better way? > > It's only meaningful to talk about sorting if your particular > definition of "<" is transitive. I.e. a < b and b < c should imply a < > c. If this is not satisfied, it doesn't make sense to sort according > to your "<" definition. It's just not a well-defined operation and no > trick will make it work. > Presumably what the OP really wants is to sort using the transitive closure of dep_cmp, which is a topological sort. http://en.wikipedia.org/wiki/Topological_sorting has details and a linear-time algorithm. -- David From max at alcyone.com Tue Jul 29 16:12:48 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 13:12:48 -0700 Subject: iterating "by twos" In-Reply-To: References: <70a172ac-0491-4918-9c74-6a577f35068a@d45g2000hsc.googlegroups.com> Message-ID: giltay at gmail.com wrote: > Whoops, I misread the original post. That would be: > > for x, y in zip(a[::2], a[1::2]): > frob(x, y) > > ... which I don't use a lot. Sorry, posted before I saw your reply. Still, you're building three sublists in order to just iterate over them. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Tell me the truth / I'll take it like a man -- Chante Moore From goldtech at worldpost.com Sun Jul 13 17:00:04 2008 From: goldtech at worldpost.com (goldtech) Date: Sun, 13 Jul 2008 14:00:04 -0700 (PDT) Subject: SAX XML Parse Python error message References: <487A23A5.7000905@behnel.de> Message-ID: I would be grateful for support with the code I cited. It's not long and fairly standard. I'm sure my error(s) would be glaring to more experienced coders. I appreciated the "heads-up" about other options but I would be grateful for help getting this code to run. Thanks On Jul 13, 11:47 am, Stefan Behnel wrote: > goldtech wrote: > > My first attempt at SAX, but have an error message I need help with. > > Just in case you prefer writing readable code over debugging SAX code into > existence, try lxml. > > http://codespeak.net/lxml/ > > Here is a presentation you might find interesting. > > http://codespeak.net/lxml/s5/lxml-ep2008.html > > Stefan From tn.pablo at gmail.com Tue Jul 22 09:27:13 2008 From: tn.pablo at gmail.com (ptn) Date: Tue, 22 Jul 2008 06:27:13 -0700 (PDT) Subject: Converting List of String to Integer References: Message-ID: > n = [] > for k in a: > ? ? n.append([int(v) for v in k]) > print n > > Does anyone know what I am doing wrong? > > Thanks in advance. > > Samir Use extend instead of append: * Append -> add the one item to the end of the list * Extend -> add the list of items to the end of the list From larzluv at hotmail.com Sat Jul 19 19:08:27 2008 From: larzluv at hotmail.com (Larry Hale) Date: Sat, 19 Jul 2008 16:08:27 -0700 (PDT) Subject: Help Tracing urllib2 Error, Please? Message-ID: <263aa5e2-f620-4d17-b95d-bd0b81f934a6@8g2000hse.googlegroups.com> Since it seems I have a "unique" problem, I wonder if anyone could point me in the general/right direction for tracking down the issue and resolving it myself. See my prior post @ http://groups.google.com/group/comp.lang.python/browse_thread/thread/44775994a6b55161?hl=en# for more info. (Python 2.5.2 on Win XP 64 ==>> Squid Proxy requiring Authentication ==>> Internet not working.) I've looked the urllib2 source over, but am having trouble following it. As previously mentioned, urllib2 initiates the request, Squid replies "407 error" that auth's required, and then urllib2 just stops, throwing error 407. Any though(s) on what to check out? It's frustrating (to say the least) that it seems so many are successfully accomplishing this task, and all's working perfectly for them, but I'm failing miserably. Would any quotes viewed in the HTTP traffic help? (Wireshark shows all! :) I don't even know what other info could help. Any info to get about Squid's configuration that might make it "non standard" in a way that could cause my problem? Any question(s) I should ask my Net Admin to relay info to you all? As always, any/all help greatly appreciated. Thanks! :) -Larry From modelnine at modelnine.org Wed Jul 30 08:22:34 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Wed, 30 Jul 2008 14:22:34 +0200 Subject: Proxy server? In-Reply-To: References: <6f6sk7Fa4tf5U1@mid.uni-berlin.de> Message-ID: <200807301422.34853.modelnine@modelnine.org> Am Mittwoch, 30. Juli 2008 13:48:08 schrieb Gary: > "Diez B. Roggisch" wrote in message > news:6f6sk7Fa4tf5U1 at mid.uni-berlin.de... > > > Gary schrieb: > > > "Diez B. Roggisch" wrote in message > > > news:6f5rteF89muqU2 at mid.uni-berlin.de... > > > > You can't make any TCP/IP communication run through a proxy, unless it's > > transparent. > > Thanks for all the info. This is not entirely true. There are libc-plugins (i.e. LD_PRELOAD hacks) which use SOCKS (which is a generic proxying protocol for [TCP/]IP) to redirect all locally originating TCP/IP traffic _which is managed through the socket interface of the libc_ in the application that you applied the LD_PRELOAD hack to through a specified SOCKS-proxy (this should capture pretty much everything, except for communication originating in the *nix-kernel itself). I seem to recall that something similar exists for WinSock, but I wouldn't know for sure. Check the web for documentation on setting up a SOCKS proxy, and for the respective libc-plugins or WinSock SOCKS "hack". If you cannot make the user use SOCKS through a means like this (in which case there has to be no application support) or by instructing a specific application to use a SOCKS proxy directly (which all browsers can out of the box AFAIK), and you don't have the possibility to put yourself somewhere in the middle by means of a transparent proxy (i.e., a firewall applicance which does this; I seem to recall that there was some FreeBSD-based software which basically did just this kind of transparent proxying for a network), you're out of luck, just like Diez said. -- Heiko Wundram From RonVick at Nospam.com Thu Jul 10 16:21:16 2008 From: RonVick at Nospam.com (RLV) Date: Thu, 10 Jul 2008 16:21:16 -0400 Subject: Can anyone suggest a date peocedure... Message-ID: I'd like to find a simple... (I'm a simple person) procedure to subtract a numerical number from a six char date string YYYYMMDD and then convert back to a new date string. I'm sure there's a way to do it, but the date modules haven't been much help. TIA Ron From google at mrabarnett.plus.com Wed Jul 2 11:25:42 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 2 Jul 2008 08:25:42 -0700 (PDT) Subject: simple UnZip References: <5b915a0e-a227-460f-8273-ecc01b800884@2g2000hsn.googlegroups.com> Message-ID: On Jul 2, 3:07?pm, C?dric Lucantis wrote: > Le Wednesday 02 July 2008 15:39:51 noydb, vous avez ?crit?: > > > > > Can someone help me with this script, which I found posted elsewhere? > > I'm trying to figure out what is going on here so that I can alter it > > for my needs, but the lack of descriptive names is making it > > difficult. ?And, the script doesn't quite do anything worthwhile -- it > > unzips one file from a zipfile, not all files in a zipfile. > > > *** > > import zipfile, os, sys, glob > > > os.chdir("C:\\Temp") > > zips = glob.glob('*.zip') > > > for fzip in zips: > > ? ? if zipfile.is_zipfile(fzip): > > ? ? ? ? print fzip," is a zip" > > ? ? ? ? z = zipfile.ZipFile(fzip,'r') > > ? ? ? ? lstName = z.namelist() > > ? ? ? ? sHgt = lstName[0] > > ? ? ? ? print "Unpacking",sHgt > > ? ? ? ? hgt = z.read(sHgt) > > ? ? ? ? fHgt = open(sHgt,'wb') > > ? ? ? ? fHgt.write(hgt) > > ? ? ? ? # fHgt.flush > > ? ? ? ? fHgt.close > > print "Finished" > > *** > > > I changed it somewhat to > > &&& > > import zipfile, os, sys > > > event_zip = ("C:\\Temp\\data4event.zip") > > > z = zipfile.ZipFile(event_zip, 'r') > > > zList = z.namelist() > > > for zItem in zList: > > ? ? print "Unpacking",zItem > > ? ? zRead = z.read(zItem) > > ? ? z1File = open(zItem,'wb') > > ? ? z1File.write(zRead) > > ? ? z1File.close It's not actually closing the file. It should be: z1File.close() > > namelist() returns a list of relative file names, so you can just put them > anywhere you want with: > > zlFile = open(os.path.join(DESTDIR, zItem), 'wb') > > or change the current directory, but the first way should be preferred. > > > print "Finished" > > &&& > > > This works, but I want to be able to specify a different output > > location. > > -- > C?dric Lucantis From andreas.mock at web.de Tue Jul 15 08:27:33 2008 From: andreas.mock at web.de (McA) Date: Tue, 15 Jul 2008 05:27:33 -0700 (PDT) Subject: Logging to different addressees Message-ID: <8df30038-86c1-4376-b046-a50f2bcf0a2b@s50g2000hsb.googlegroups.com> Hi all, I need a recommendation. I would to like to use the logging module to create log messages the following way: a) Every log message does go to a admin sink. b) The logging of special messages should go to the admin sink AND to a sink specifically for a certain addressee. c) I don't want to write the log message to two different loggers for that purpose. I would like to do it this way: common_logger.log('bla') -> message to admin sink certain_logger.log('something' -> message to admin sink and addressee- sink d) Filtering and debug level should work as expected. I could I achieve this in a elegant way? Best regards Andreas Mock From ptmcg at austin.rr.com Thu Jul 31 19:05:21 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 31 Jul 2008 16:05:21 -0700 (PDT) Subject: simple problem with lists I am just forgetting References: Message-ID: On Jul 31, 2:51?pm, Alexnb wrote: > Lets say we have this list: > > funlist = ['a', 'b', 'c'] > > and lets say I do this: > > if funlist[4]: > ? ? print funlist[4] > > I will get the exception "list index out of range" > > How can I test if the list item is empty without getting that exception? Try using a slice. Slices are ignorant of list index validity. funlist = list("abc") # too lazy to type ['a', 'b', 'c'] if funlist[4:]: print funlist[4] Voila! No exception! -- Paul From deets at nospam.web.de Thu Jul 31 07:57:28 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 13:57:28 +0200 Subject: How smart is the Python interpreter? References: <58db6def-fd4d-446a-aee3-fc498f25ee18@l42g2000hsc.googlegroups.com> Message-ID: <6fdnnhFb5flqU1@mid.uni-berlin.de> ssecorp wrote: > def str_sort(string): > s = "" > for a in sorted(string): > s+=a > return s > > > if i instead do: > > def str_sort(string): > s = "" > so = sorted(string) > for a in so: > s+=a > return s > > > will that be faster or the interpreter can figure out that it only has > to do sorted(string) once? or that kind of cleverness is usually > reserved for compilers and not interpreters? There isn't much cleverness involved here - why on earth should one execute the sorted(string) several times? The for in construct will evaluate the of course only once. Diez From digitig at gmail.com Fri Jul 4 13:11:14 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 4 Jul 2008 18:11:14 +0100 Subject: Can't get Python for Windows to run In-Reply-To: <486E4125.5080201@timgolden.me.uk> References: <486E4125.5080201@timgolden.me.uk> Message-ID: 2008/7/4 Tim Golden : > Ummm. That's the Python interpreter but without a window so > (unhelpfully, from your point of view) it's doing exactly the > right thing. > > I assume you were trying to run the PythonWin Python > interpreter and dev env? On my system, that's: > > C:\Python25\Lib\site-packages\pythonwin\Pythonwin.exe Ah! Something that would have been blindingly obvious had it successfully installed the shortcuts, but something I would never have worked out as it was! Many thanks. Is it worth flagging as an issue somewhere the fact that the pywin installer assumes a particular structure for the start menu, and fails to install shortcuts if it doesn't find that structure? I'm used to programs asking me where they want to put the shortcuts, and creating folders if they don't find them (creating *without* asking would, of course, a Hostile Act). -- Tim Rowe From Tribulations at Paralleles.invalid Tue Jul 8 01:21:49 2008 From: Tribulations at Paralleles.invalid (TP) Date: Tue, 08 Jul 2008 07:21:49 +0200 Subject: interpretation of special characters in Python References: <3rq7k5-lqf.ln1@rama.nodalpoint> <6ddj74F21uhjU1@mid.individual.net> <4cv8k5-dsg.ln1@rama.nodalpoint> <6dg740F2b1mkU1@mid.individual.net> Message-ID: Peter Pearson wrote: > I don't understand exactly what you mean by "Sorry" I means: please forgive me for having said that it does not work with variables, because it is completely false. Thanks one more time Julien -- TP (Tribulations Parall?les) "Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert). From aaron.hildebrandt at gmail.com Wed Jul 23 17:19:34 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 23 Jul 2008 14:19:34 -0700 (PDT) Subject: Using variables across modules References: <855136ce-6c70-40ac-a462-dc0bbfa1fc3a@b2g2000prf.googlegroups.com> Message-ID: > first read this to learn how objects and variables work in Python: > > ? ? ?http://effbot.org/zone/python-objects.htm > > and then read this to learn how from-import works, and when you're > supposed to use it: > > ? ? ?http://effbot.org/zone/import-confusion.htm > > hope this helps! > Awesome. After reading those two pages, I was able to correct the code and get things up and running. Thanks! Aaron From Russ.Paielli at gmail.com Sun Jul 27 02:26:28 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sat, 26 Jul 2008 23:26:28 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> Message-ID: <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> On Jul 26, 11:18 pm, Terry Reedy wrote: > Colin J. Williams wrote: > > Russ P. wrote: > >> class MyClass: > > >> def func( , xxx, yyy): > > >> .xxx = xxx > > >> local = .yyy > > The use of '.' has been suggested before and rejected. Where and why? From emen999 at gmail.com Tue Jul 29 08:51:49 2008 From: emen999 at gmail.com (code_berzerker) Date: Tue, 29 Jul 2008 05:51:49 -0700 (PDT) Subject: SWIG and char* newb questions :) References: <7ec26fb6-3d6a-4e1b-b2c9-a0a254780153@26g2000hsk.googlegroups.com> Message-ID: Ok I think I got it: PyObject* myFuncXXX(char* p_1, int p_2, char* p_3, int p_4) { int res; char _host[255] = ""; int _port; res = funcXXX(p_1, p_2, p_3, p_4, _host, &_port); PyObject* res1 = PyInt_FromLong(res); PyObject* res2 = PyString_FromStringAndSize(_host, strlen(_host)); PyObject* res3 = PyInt_FromLong(_port); PyObject* resTuple = PyTuple_New(3); PyTuple_SetItem(resTuple, 0, res1); PyTuple_SetItem(resTuple, 1, res2); PyTuple_SetItem(resTuple, 2, res3); return resTuple; } It seems to work when I put it into swig's "*.i" file. me proud of me.self :D From jaycx2.3.calrobert at spamgourmet.com.remove Sun Jul 20 13:36:21 2008 From: jaycx2.3.calrobert at spamgourmet.com.remove (Robert Maas,) Date: Sun, 20 Jul 2008 10:36:21 -0700 Subject: The Importance of Terminology's Quality References: <48617847$0$5021$607ed4bc@cv.net> <486ae06b$0$5011$607ed4bc@cv.net> Message-ID: > >> ... the "thunks" were necessary at the machine-language level to > >> /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. > > Ah, thanks for the clarification. Is that info in the appropriate > > WikiPedia page? If not, maybe you would edit it in? > From: John W Kennedy > It is explained s.v. "thunk", which is referenced from "ALGOL > 60". The ALGOL "pass-by-name" argument/parameter matching was > perhaps the most extreme example ever of a language feature that > was "elegant" but insane. What it meant, in effect, was that, > unless otherwise marked, every argument was passed as two closures, > one that returned a fresh evaluation of the expression given as the > argument, which was called every time the parameter was read, and > one that set the argument to a new value, which was called every > time the parameter was set. Wow! All these years when I occasionally heard of a "thunk" I never was told, until now, what it really meant. Thanks for the info!! Followup question #1: I assume these are lexical closures in the environment of the point of the call, right? Followup question #2: For simple arithmetic expressions, I can possibly understand how the UPDATE closure might be implemeted (expressed in Lisp to make the intent clear): Call form: MyFunction(X+2); GET closure: (+ closedX 2) UPDATE closure: (lambda (newval) (setf closedX (- newval 2)) Thus from inside MyFunction where formal parameter Arg1 is bound to actual parameter X+2, after doing Arg1 := 7; X will have the value 5 so that calling Arg1 will return 7 as expected, right? But if the actual argument is something complicated, especially if it makes a nested function call, how can that possibly be implemented? Given an arbitrary expression that calls some external function, how can assigning a value to that expression make sufficient changes in the runtime environment such that subsequently evaluating that expression will yield the expected value i.e. the value that had been assigned? Or is the default of passing two closures (GET and UPDATE) *only* if the actual-argument expression is simple enough that it's invertible, and in complicated cases only a GET closure is passed (or the UPDATE closure is simply a signal of a runtime error that you're not allowed to assign a value to a complicated expression)? IMO the "right" way to pass parameters that can be modified is to use "locatatives" as in the Lisp Machine. That converts the idea of a "place" (as used by SETF in Common Lisp) into a "first class citizen" which can be passed around and stored etc., compared to a SETF place which is merely a compiletime-macro trick to convert place-references in source code into direct calls to the appropriate accessor just above the place followed by specialized SETter call to do the act. A hack to emulate a locative in CL would be to pass a closure where the code to find the object directly containing the place, and any parameters needed to find that place, and the function needed to perform the act. Then the called function would need to know it's going to get such a thunk-like closure, but since it's expecting to modify one of its parameters anyway, that's reasonable. Sketch of implementation (two special cases): (defun make-thunk-cadr (topptr) (let* ((midptr (cdr topptr)) (getclo (make-getter-closure :PARENT midptr :GETTERFN #'car :PARMS nil)) (setclo (make-setter-closure :PARENT midptr :SETTERFN #'rplaca :PARMS nil))) (make-thunk getclo setclo)) (defun make-thunk-aref1 (topptr arrindex1) (let ((getclo (make-getter-closure :PARENT topptr :GETTERFN #'aref1 :PARMS (list arrindex1))) (setclo (make-setter-closure :PARENT midptr :SETTERFN #'setaref1 :PARMS (list arrindex1)))) (make-thunk getclo setclo)) (defun swap (thunk1 thunk2) (prog (tmp) (setq tmp (thunk-get thunk1)) (thunk-set thunk1 (thunk-get thunk2)) (thunk-set thunk2 tmp))) ;Definitions of make-getter-closure make-setter-closure make-thunk ; thunk-get thunk-set not shown because they depend on whether ; closures and thunks are implemented via tagged assoc lists or ; DEFSTRUCT structures or CLOS objects or whatever. But I made the ; call to the constructors explicit enough that it should be obvious ; what components are inside each type of object. Note that with ; CLOS objects, this could all be condensed to have a single CLOS ; object which is the thunk which has two methods GET and SET, no ; need to make closures for get and set separately, templates for ; those closures are made automatically when the CLOS class is ; defined, and closures are generated from those templates whenever ; a new CLOS thunk-object is made. Thus: ; ... (make-CLOS-thunk :PARENT topptr :GETTERFN #'aref1 :SETTERFN #'setaref1 ; :PARMS (list arrindex1)) ... ;Example that should actually work: (format t " arr: ~S~% ixs: ~S~%" arr ixs) arr: #'(3 5 7 11 13)) ixs: (2 4) (setq arr #'(3 5 7 11 13)) (setq ixs (list 2 4)) (setq thunkcadr (make-thunk-cadr ixs)) ;Locative to the 4 in ixs (setq thunkaref (make-thunk-aref1 arr (thunk-get thunkcadr))) ;Locative to the 11 in the array (swap thunkcadr thunkaref) (format t " arr: ~S~% ixs: ~S~%" arr ixs) arr: #'(3 5 7 4 13)) ixs: (2 11) I haven't implemented this. I'm just specifying what the behaviour should be and giving a sketch how it ought to be easily doable in Common Lisp. And I'm not going to implement it because I have no use for this way of coding, at least not currently or in the foreseeable future. Generally my abstract data type is at a higher level where the caller doesn't know that a single place is going to need to be SETFed, so there's no point in getting a locative to work with. Instead there's some *kind* of update to do, and parameters to that *kind* of update; what really happens internally (one or more SETFs, or alternately re-build anything that changed and share what didn't change) doesn't need to be known by the caller. All the caller needs to know is generically whether the update is in-place or non-destructive. (If it's non-destructive, then the new edition of the data structure is one of the return values. If it's in-place, then there's no need to bother with setq of the new value, because my structures always have a header cell that has a tag for the intentional datatype, and that header cell always points to either the in-place-modified object or the latest-edition-of-object.) I'd rather program in "paranoid" mode than in "risk shoot foot" mode. The CAR of each ADT object is a keyword identifying the intentional type of that object, and every function that operates on that intentional type first checks if the parameter really does have the expected CAR, just to make sure I didn't copy&paste some inappropriate function name in my code. Yeah, it takes extra CPU cycles to do that checking on every calls, but it sure saves me from shooting myself in the foot and having to spend an hour to find out how I did it before I can fix it. TMI = Too Much Information (actually YMMV, some readers might like it) MTMI = More of Too Much Information EMTMI = Even More of Too Much Information (only newbies need read) Credits to Babylon Five for the "I spy" game in the cargo hold. I spy something that starts with the letter B. Boxes! I spy something that starts with the letter M. More boxes! From akathorn at gmail.com Mon Jul 14 10:01:07 2008 From: akathorn at gmail.com (Akathorn Greyhat) Date: Mon, 14 Jul 2008 15:01:07 +0100 Subject: Dictionary bidirectional In-Reply-To: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> Message-ID: This is a better version of the class that I sen't you, now it raises a KeyError when you try to insert a value that is already in ############################ class MyCoolDictionary(dict): def __init__(self, *args, **kargs): dict.__init__(self, *args, **kargs) def __setitem__(self, *args, **kargs): for i in dictio.values(): if args[0]==i or args[1]==i: raise KeyError, 'Value already exists' dict.__setitem__(self, *args, **kargs) def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: keys=[] for i in dictio.keys(): if dictio[i]==item: keys.append(i) if not keys: raise KeyError, 'Can\'t found key or value "' + str(item) + '"' return keys ############################ Feel free to change anything you want or need Regards, Akathorn Greyhat 2008/7/14 Kless : > I need a dictionary where get the result from a 'key' (on left), but > also from a 'value' (on right), how to get it? > > I know that dictionaries aren't bidirectional, but is there any way > without use two dictionaries? > > > Thanks in advance! > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stesch at no-spoon.de Wed Jul 16 04:35:07 2008 From: stesch at no-spoon.de (Stefan Scholl) Date: Wed, 16 Jul 2008 10:35:07 +0200 Subject: Amazon: "Practical Django Projects" by James Bennett (June 2008) References: <36e67a6e4e49fd922a449f110d1bbc54@anonymitaet-im-inter.net> Message-ID: <0T56n0ntIjlaNv8%stesch@parsec.no-spoon.de> Dave U. Random wrote: > http://snipr.com/PracticalDjango June 2008 is a bit too early. Django isn't ready. -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ From cartercc at gmail.com Tue Jul 22 15:56:39 2008 From: cartercc at gmail.com (cartercc) Date: Tue, 22 Jul 2008 12:56:39 -0700 (PDT) Subject: proliferation of computer languages References: <708b795b-70d6-4340-8717-94452acba31a@c2g2000pra.googlegroups.com> Message-ID: On Jul 18, 1:17 pm, "xah... at gmail.com" wrote: > Today, i took sometime to list some major or talked-about langs that > arose in recent years. You missed PowerShell and ActionScript. Languages are just tools. It may have escaped your notice, but it's a remarkable fact that no two languages are alike! It's not the language that we should focus on, but the task at hand. Personally, I feel that we can gain a lot more by studying the different kinds of problems we can solve by computing and relate the language to the job, rather than learning a language and then trying to find a fit with a particular class of problems. If you look at TIOBE and the like, you will note that the top four language categories (Java/JavaScript, C/C++, Basic, and Perl/Python/ Ruby) account for around eighty percent of the language usage (not counting PHP), and all the other languages quickly fall off. No. 13 on the TIOBE rating was PL/SQL at 0.073 percent. If you read the employment ads (Dice, etc.) the percentage is even greater for the big languages. To me, this indicates that we have several mainstream languages that account for the vast majority of work and a vast number of task specific languages for special purposes. CC From __peter__ at web.de Fri Jul 4 07:24:53 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Jul 2008 13:24:53 +0200 Subject: Bug in re.findall? References: Message-ID: Marcin Krol wrote: > Hello everyone, > > Is there a bug in re.findall in Python 2.4? See: > > subnetlist="192.168.100.0 , 192.168.101.0" > ipre=re.compile("([0-9]{1,3}\.){3}[0-9]{1,3}") > > >>> ipre.findall(subnetlist) > > ['100.', '101.'] > > > But: > > a=ipre.finditer(subnetlist) > > >>> a.next().group() > '192.168.100.0' > >>> a.next().group() > '192.168.101.0' > >>> a.next().group() > Traceback (most recent call last): > File "", line 1, in ? > StopIteration > > Also: > > >>> ipre.search(subnetlist).group() > '192.168.100.0' > > Is this a bug or am I doing smth wrong? >From the doc: """ findall( pattern, string[, flags]) Return a list of all non-overlapping matches of pattern in string. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. """ So findall()'s behaviour changes depending on the number of explicit groups None: [m.group() for m in re.finditer(...)] One: [m.group(1) for m in re.finditer(...)] More than one: [m.groups() for m in re.finditer(...)] all in accordance with the documentation. Peter From mrkafk at gmail.com Wed Jul 2 12:08:41 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Wed, 02 Jul 2008 18:08:41 +0200 Subject: Bloody signal handling (in embedded Python code) Message-ID: Hello everyone, And now for something completely different: signal handling sometimes works, sometimes it doesn't. When I embed following code, it works: count = 0 def test(): global count while True: count += 1 if (count % 100000 == 0): print count if __name__ == "__main__": test() It nicely does what signal handler function tells it to do and exits. However, when I embed this code, it segfaults on receiving the signal: import time def test(): time.sleep(1) print "success" time.sleep(90) if __name__ == "__main__": test() Does it have something to do with the fact that the program receiving the signal sleeps? The C code of segfaulting program: #include #include #include #include #include #include void userbreak(int sig) { Py_Finalize(); printf("Interrupted..\n"); exit(sig); } void terminaterun(int sig) { Py_Finalize(); printf("Received SIGTERM. Terminating.\n"); exit(sig); } int main(int argc, char **argv) { Py_Initialize(); PyObject *pyCode, *mainmodule, *maindict; mainmodule = PyImport_AddModule("__main__"); maindict = PyModule_GetDict(mainmodule); unsigned int size = 326; unsigned char python_code[] = { 0x63,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00, 0x40,0x00,0x00,0x00,0x73,0x2E,0x00,0x00,0x00,0x64, 0x00,0x00,0x6B,0x00,0x00,0x5A,0x00,0x00,0x64,0x01, 0x00,0x84,0x00,0x00,0x5A,0x01,0x00,0x65,0x02,0x00, 0x64,0x02,0x00,0x6A,0x02,0x00,0x6F,0x0B,0x00,0x01, 0x65,0x01,0x00,0x83,0x00,0x00,0x01,0x6E,0x01,0x00, 0x01,0x64,0x00,0x00,0x53,0x28,0x03,0x00,0x00,0x00, 0x4E,0x63,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x02,0x00,0x00,0x00,0x43,0x00,0x00,0x00,0x73,0x23, 0x00,0x00,0x00,0x74,0x00,0x00,0x69,0x01,0x00,0x64, 0x01,0x00,0x83,0x01,0x00,0x01,0x64,0x02,0x00,0x47, 0x48,0x74,0x00,0x00,0x69,0x01,0x00,0x64,0x03,0x00, 0x83,0x01,0x00,0x01,0x64,0x00,0x00,0x53,0x28,0x04, 0x00,0x00,0x00,0x4E,0x69,0x01,0x00,0x00,0x00,0x74, 0x07,0x00,0x00,0x00,0x73,0x75,0x63,0x63,0x65,0x73, 0x73,0x69,0x5A,0x00,0x00,0x00,0x28,0x02,0x00,0x00, 0x00,0x74,0x04,0x00,0x00,0x00,0x74,0x69,0x6D,0x65, 0x74,0x05,0x00,0x00,0x00,0x73,0x6C,0x65,0x65,0x70, 0x28,0x00,0x00,0x00,0x00,0x28,0x00,0x00,0x00,0x00, 0x28,0x00,0x00,0x00,0x00,0x74,0x07,0x00,0x00,0x00, 0x74,0x65,0x73,0x74,0x2E,0x70,0x79,0x74,0x04,0x00, 0x00,0x00,0x74,0x65,0x73,0x74,0x05,0x00,0x00,0x00, 0x73,0x06,0x00,0x00,0x00,0x00,0x01,0x0D,0x01,0x05, 0x01,0x74,0x08,0x00,0x00,0x00,0x5F,0x5F,0x6D,0x61, 0x69,0x6E,0x5F,0x5F,0x28,0x03,0x00,0x00,0x00,0x52, 0x01,0x00,0x00,0x00,0x52,0x04,0x00,0x00,0x00,0x74, 0x08,0x00,0x00,0x00,0x5F,0x5F,0x6E,0x61,0x6D,0x65, 0x5F,0x5F,0x28,0x02,0x00,0x00,0x00,0x52,0x04,0x00, 0x00,0x00,0x52,0x01,0x00,0x00,0x00,0x28,0x00,0x00, 0x00,0x00,0x28,0x00,0x00,0x00,0x00,0x52,0x03,0x00, 0x00,0x00,0x74,0x01,0x00,0x00,0x00,0x3F,0x03,0x00, 0x00,0x00,0x73,0x06,0x00,0x00,0x00,0x09,0x02,0x09, 0x05,0x0D,0x01 }; pyCode = PyMarshal_ReadObjectFromString((PyObject *) python_code, size); (void) signal(SIGINT, userbreak); (void) signal(SIGTERM, terminaterun); PyEval_EvalCode(pyCode, maindict, maindict); Py_Finalize(); } From Russ.Paielli at gmail.com Wed Jul 30 02:47:21 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Tue, 29 Jul 2008 23:47:21 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <95979c55-edb8-475d-ba84-834b5699c2a6@j1g2000prb.googlegroups.com> <9f1755e3-8b0c-4070-ac1b-0d53066a68ce@a2g2000prm.googlegroups.com> <6d906dd5-bf5a-44d5-a5a8-3875027f6b91@v26g2000prm.googlegroups.com> Message-ID: <0f0b03c9-794b-430b-88ab-18a68505109e@a21g2000prf.googlegroups.com> On Jul 29, 11:36 pm, Erik Max Francis wrote: > Russ P. wrote: > > Come to think of it, shouldn't the list type have an "isempty" method? > > Or does it? > > Yes. It's written: > > if not aList: > ... As you know, that is not quite exactly the same thing. An "isempty" method would fail if aList were an integer, and such failure might be desirable if someone mistakenly had aList pointing to an integer. From rcdailey at gmail.com Wed Jul 30 15:27:55 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 30 Jul 2008 14:27:55 -0500 Subject: Reasoning behind 'self' parameter in classes? In-Reply-To: <4890ACE4.4060703@acm.org> References: <496954360807300939v80000e7p124fd779ad87412c@mail.gmail.com> <4890ACE4.4060703@acm.org> Message-ID: <496954360807301227h1dea050eg735314beb0b5ff16@mail.gmail.com> On Wed, Jul 30, 2008 at 1:03 PM, Brett g Porter wrote: > Robert Dailey wrote: > > This is an example of a response I'm looking for: >> "The self parameter is required because the parser is a bit old and needs >> to know the exact object you're referencing" >> >> This is _not_ an example of what I'm looking for: >> "Specifying self is a great mysterious thing that we should never >> question. Do not question the language! The language is mighty! Don't bring >> C++ to Python!" >> >> > Fredrik Lundh has written a very clear explanation of this at > http://effbot.org/pyfaq/why-must-self-be-used-explicitly-in-method-definitions-and-calls.htm > > (or http://bit.ly/3EUiCf if you don't feel like stitching that URL back > together...) > This sounds like an article of opinion. He's not really given any reasons other than "Well, it makes this easier or look better". True that declarations are the determining factor in C/C++, however I was thinking of more or less an implied 'self'. For example: # Consider this normal syntax: class MyFoo: def DoFoo( self ): self._member = 6 # Elimintating 'self' in the parameter list should still work as far as the # interpreter is concerned, since 'self' in this case now acts like 'this' # in C++. The below code should be equivalent. class MyFoo: def DoFoo(): self._member = 6 Given the code samples above, is there any technical reason why this cannot be done? Thanks for the input guys, and thanks more over for keeping this easy-going. -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Sun Jul 27 14:10:33 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 27 Jul 2008 11:10:33 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <87d4l2v1op.fsf@nokile.rath.org> <87ljzpt3lv.fsf@nokile.rath.org> Message-ID: <826f6075-40ff-4da0-a178-b53d90ab3096@z66g2000hsc.googlegroups.com> On Jul 27, 2:56?am, Nikolaus Rath wrote: > Terry Reedy writes: > >> What he wants is to write > > > ?> class foo: > >> ? ?def bar(arg): > >> ? ? ? ?self.whatever = arg + 1 > > >> instead of > > >> class foo: > >> ? ?def bar(self, arg) > >> ? ? ? ?self.whatever = arg + 1 > > >> so 'self' should *automatically* only be inserted in the function > >> declaration, and *manually* be typed for attributes. > > > which means making 'self' a keyword just so it can be omitted. Silly > > and pernicious. > > Well, I guess that's more a matter of personal preference. I would go > for it immediately (and also try rename it to '@' at the same time). > > Best, > > ? ?-Nikolaus > > -- > ??It is not worth an intelligent man's time to be in the majority. > ? By definition, there are already enough people to do that.? > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?-J.H. Hardy Hardy has an interesting claim. OT. He has omitted a couple of lemmas, which aren't true. 1: There are enough people to be in the majority. 2: It is not worthwhile to be in the majority. 3: There is no majority of worthwhile timespending. 4: There is no majority of intelligent men. 5: Being in the majority takes time. It is worth some intelligent men's time to be in the majority; the majority of intelligent men are intelligent men, and are in the majority of intelligent men. Perhaps it is merely not worth their time to be. From mrkafk at gmail.com Wed Jul 2 11:44:18 2008 From: mrkafk at gmail.com (Marcin Krol) Date: Wed, 02 Jul 2008 17:44:18 +0200 Subject: Importing modules in embedded Python Message-ID: Hello everyone, I can embed Python interpreter in C code now, but now there's another problem, importing modules in Python code doesn't work: Exception exceptions.ImportError: '/usr/lib/python2.4/lib-dynload/timemodule.so: undefined symbol: PyModule_AddObject' in 'garbage collection' ignored Fatal Python error: unexpected exception during garbage collection Aborted The (autogenerated) C code: ---cut--- #include #include #include #include #include #include void userbreak(int sig) { Py_Finalize(); printf("Interrupted..\n"); exit(sig); } void terminaterun(int sig) { Py_Finalize(); printf("Received SIGTERM. Terminating.\n"); exit(sig); } int main(int argc, char **argv) { Py_Initialize(); PyObject *pyCode, *mainmodule, *maindict; mainmodule = PyImport_AddModule("__main__"); maindict = PyModule_GetDict(mainmodule); unsigned int size = 272; unsigned char python_code[] = { 0x63,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00, 0x40,0x00,0x00,0x00,0x73,0x16,0x00,0x00,0x00,0x64, 0x00,0x00,0x6B,0x00,0x00,0x5A,0x00,0x00,0x64,0x01, 0x00,0x84,0x00,0x00,0x5A,0x01,0x00,0x64,0x00,0x00, 0x53,0x28,0x02,0x00,0x00,0x00,0x4E,0x63,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00, 0x43,0x00,0x00,0x00,0x73,0x23,0x00,0x00,0x00,0x74, 0x00,0x00,0x69,0x01,0x00,0x64,0x01,0x00,0x83,0x01, 0x00,0x01,0x64,0x02,0x00,0x47,0x48,0x74,0x00,0x00, 0x69,0x01,0x00,0x64,0x03,0x00,0x83,0x01,0x00,0x01, 0x64,0x00,0x00,0x53,0x28,0x04,0x00,0x00,0x00,0x4E, 0x69,0x01,0x00,0x00,0x00,0x74,0x07,0x00,0x00,0x00, 0x73,0x75,0x63,0x63,0x65,0x73,0x73,0x69,0x5A,0x00, 0x00,0x00,0x28,0x02,0x00,0x00,0x00,0x74,0x04,0x00, 0x00,0x00,0x74,0x69,0x6D,0x65,0x74,0x05,0x00,0x00, 0x00,0x73,0x6C,0x65,0x65,0x70,0x28,0x00,0x00,0x00, 0x00,0x28,0x00,0x00,0x00,0x00,0x28,0x00,0x00,0x00, 0x00,0x74,0x07,0x00,0x00,0x00,0x74,0x65,0x73,0x74, 0x2E,0x70,0x79,0x74,0x04,0x00,0x00,0x00,0x74,0x65, 0x73,0x74,0x04,0x00,0x00,0x00,0x73,0x06,0x00,0x00, 0x00,0x00,0x01,0x0D,0x01,0x05,0x01,0x28,0x02,0x00, 0x00,0x00,0x52,0x01,0x00,0x00,0x00,0x52,0x04,0x00, 0x00,0x00,0x28,0x02,0x00,0x00,0x00,0x52,0x04,0x00, 0x00,0x00,0x52,0x01,0x00,0x00,0x00,0x28,0x00,0x00, 0x00,0x00,0x28,0x00,0x00,0x00,0x00,0x52,0x03,0x00, 0x00,0x00,0x74,0x01,0x00,0x00,0x00,0x3F,0x02,0x00, 0x00,0x00,0x73,0x02,0x00,0x00,0x00,0x09,0x02 }; pyCode = PyMarshal_ReadObjectFromString((PyObject *) python_code, size); (void) signal(SIGINT, userbreak); (void) signal(SIGTERM, terminaterun); PyEval_EvalCode(pyCode, maindict, maindict); Py_Finalize(); } ---cut--- The Python code: import time def test(): time.sleep(1) print "success" time.sleep(90) How do I manage to get modules imported? Anybody? From paddy3118 at googlemail.com Sun Jul 20 02:54:33 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 19 Jul 2008 23:54:33 -0700 (PDT) Subject: Question References: Message-ID: <2e60b845-58fa-416e-ac41-fac9f7e872bf@s50g2000hsb.googlegroups.com> On Jul 19, 10:27?am, perl_wiz... at manx.net wrote: > Why is Perl so much better than python? Coz its endorsed by: Chernobble valve controls. Barings Bank. The society of the Mortgage Brokers of America. The Bush Disaster relief fund for the Southern States. And, of course, is the tool of choice when looking for weapons of mass destruction in Iraq. - Paddy. From com.lewscanon at lew Tue Jul 22 09:54:06 2008 From: com.lewscanon at lew (Lew) Date: Tue, 22 Jul 2008 09:54:06 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <48617847$0$5021$607ed4bc@cv.net> Message-ID: Rob Warnock wrote: > Martin Gregorie wrote: > +--------------- > | John W Kennedy wrote: > | > No, the "thunks" were necessary at the machine-language level to > | > /implement/ ALGOL 60, but they could not be expressed /in/ ALGOL. > | > | Are you sure about that? > +--------------- > > I don't know if John is, but *I* am! ;-} At this point we are so far off topic for clj.programmer, but still impinging on functional programming issues with the discussion of closures, et al., that I respectfully request that you all exclude clj.programmer from followups to this thread. (f-u set to comp.lang.functional) -- Lew From deets at nospam.web.de Thu Jul 31 08:39:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 31 Jul 2008 14:39:50 +0200 Subject: working pylint anyone? References: <6fdf17Fb2bboU1@mid.uni-berlin.de> <8a08b59f-f7f0-4706-84c9-19f0460f09ef@k30g2000hse.googlegroups.com> Message-ID: <6fdq70Fb1t79U1@mid.uni-berlin.de> > Which version of python-logilab-common and python-logilab-astng are > installed on your machine ? By now, pylint 0.14 with logilab.common 0.27 and astng 0.17.2 I was able to track down the problem as being related to a custom init-hook. See the attached .pylintrc + hook. They don't actually *do* anything (or, the hook that is), but confuse pylint to spit out the reported error. Maybe you can track down the real reason for the error? > > I don't know where you checked, but there is some traffic on the > mailing list, > and questions generally get answered :-) On the website, I found this link: http://www.logilab.org/mailinglist/850 through the search. Diez -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: .pylint_init_hook.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: .pylintrc URL: From tjreedy at udel.edu Sat Jul 12 16:32:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Jul 2008 16:32:25 -0400 Subject: Weird lambda rebinding/reassignment without me doing it In-Reply-To: References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Thu, 10 Jul 2008 14:09:16 -0400, Terry Reedy wrote: > >>>>>>> g = lambda x:validate(x) >> This is doubly diseased. >> >> First, never write a 'name = lambda...' statement since it is equivalent >> to a def statement except that the resulting function object lacks a >> proper .funcname attribute. > > Using lambda in this way is no more "diseased" than aliasing any other > object. In the context of giving advice to a confused beginner, I disagree. He must learn def statements. Lambda expressions are optional. > It's a matter of personal preference not to bind a lambda to a > name. Functions, whether created by lambda or def, are first class > objects, and as such there's nothing wrong with binding them to names. When I brought this up on pydev, in the context of a style guide addition, about 9 of 10 respondants agreed that this should be discouraged. Alex Martelli reported his experience that this construction more often leads people to the useless wrapping of function calls, such as the OP posted, than the def statement equivalent does. One of the major reasons people give for wanting lambda expressions kept in Python and for using them is that they do not want to have to think up a name for short expressions. If such a person then turns around and binds the resulting function object to a name, then that rationale disappears. Over the years, people have written on c.l.p about 'lambdas' as if they were a separate class of objects somehow different from def objects (and not just an expression). I believe writing and reading both 'name = lambda ...' and 'def name(...' engenders and reinforces this delusion, especially for beginners. > Admittedly, the lack of a func_name attribute can sometimes make > tracebacks harder to understand, especially if you've got many bound > lambdas. Is saving two keystrokes worth that disadvantage, and the confusions mentioned above? To me, no. Hence my advice. Terry Jan Reedy From tbourden at doc.ic.ac.uk Sun Jul 27 14:26:39 2008 From: tbourden at doc.ic.ac.uk (Themistoklis Bourdenas) Date: Sun, 27 Jul 2008 19:26:39 +0100 Subject: method decorators and more on decorators Message-ID: <7fd737460807271126m3dbdea8cv4dbd8c9058d4faea@mail.gmail.com> Hi, is there any possible way to get the class or class name inside a method decorator? For example in the code sample below: def decorate(func): print type(func) return func class myclass: @decorate def foo(self): pass The output of this program will be the type of the supplied func in decorate, i.e. method foo. However, the type is function foo, a free function, not an instance method myclass.foo. On a related note, as the actual instance method of myclass is not foo but decorate(foo), why are they called method decorators? This does not decorate methods, they decorate functions and eventually the decorated functions become methods. The name method decorator sounds a bit misleading to me. So returning to my original question is there any way I can get the class inside decorate()? I guess there is not, but just asking to make sure. Speaking of decorators I'd also like to ask on the pending class decorators that should be coming in a following version of the language. Are they going to be in 2.6 or just 3.0? In the following example: def class_decorate(cls): print 'class_decorate' return cls def decorate(func): print 'decorate' return func @class_decorate class myclass: @decorate def foo(self): pass what will be the correct output? class_decorate decorate or decorate class_decorate In essence what is the order of application of class decorators compared to the function decorators of their methods? I couldn't find any mention of that issue in any of the PEPs. I guess it would be the latter, following the behavior of metaclasses, but better be certain than speculate :) Cheers, Themis -------------- next part -------------- An HTML attachment was scrubbed... URL: From digetl.try at gmail.com Sat Jul 26 06:01:11 2008 From: digetl.try at gmail.com (raja) Date: Sat, 26 Jul 2008 03:01:11 -0700 (PDT) Subject: EZ Recipe & Menu Costing Message-ID: <7edfbf9c-2c5b-4e0c-b767-3b835788d1c6@x29g2000prd.googlegroups.com> Customized Excel Workbook to Cost All Your Recipes & Menu Items http://food-drinks.page.tl/ From semanticist at gmail.com Sun Jul 13 22:29:27 2008 From: semanticist at gmail.com (Miles) Date: Sun, 13 Jul 2008 22:29:27 -0400 Subject: socket.connect() hangs in SYN_SENT state. In-Reply-To: References: Message-ID: On Sat, Jul 12, 2008 at 11:23 PM, bukzor wrote: > Anyone know a general reason this might happen? Even better, a way to > fix it? Another reason that a socket can hang in the SYN_SENT state (besides trying to connect to an unreachable host without getting an ICMP destination-unreachable message in response): if the server's listen queue is full, it will silently ignore SYN packets until there is room in the queue. Sorry again about the "bukzor" vs. "buzkor" thing. I don't know what's causing your problem (and it's probably not a DNS issue after all) but it's more likely to be a server issue than a client one. Maybe your client has an unusually low socket timeout for some reason, though; does increasing it (with socket.setdefaulttimeout) help? Mine seems to default to about 75 seconds. If you can't work out the root cause, but it only happens every once in a while, you could try changing your client code to catch the socket exception and retry a limited number of times. -Miles From sniipe at gmail.com Mon Jul 7 08:49:09 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Mon, 7 Jul 2008 05:49:09 -0700 (PDT) Subject: I am looking for svn library(module) Message-ID: <6e1097a0-2a99-4885-a1ef-0684af5aa6a1@d1g2000hsg.googlegroups.com> Hi, I am looking fo svn library(module) which is used in the svn- mailer(http://opensource.perlig.de/svnmailer/) project. Does anybody know where can I find it(download url)? This is information which I received from python error: from svn import core as svn_core ImportError: No module named svn Best regards From moogyd at yahoo.co.uk Mon Jul 14 10:46:35 2008 From: moogyd at yahoo.co.uk (moogyd at yahoo.co.uk) Date: Mon, 14 Jul 2008 07:46:35 -0700 (PDT) Subject: Beginner Question : Iterators and zip References: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> <0ea30e6f-fcf4-4f39-a091-10b2a2178efd@l64g2000hse.googlegroups.com> Message-ID: <090ad4d5-761a-49b2-8927-3949bad9578b@m44g2000hsc.googlegroups.com> On 13 Jul, 19:49, Terry Reedy wrote: > moo... at yahoo.co.uk wrote: > > What is this *lis operation called? I am having trouble finding any > > reference to it in the python docs or the book learning python. > > One might call this argument unpacking, but > Language Manual / Expressions / Primaries / Calls > simply calls it *expression syntax. > "If the syntax *expression appears in the function call, expression must > evaluate to a sequence. Elements from this sequence are treated as if > they were additional positional arguments; if there are positional > arguments x1,...,*xN* , and expression evaluates to a sequence > y1,...,*yM*, this is equivalent to a call with M+N positional arguments > x1,...,*xN*,*y1*,...,*yM*." > > See Compound Statements / Function definitions for the mirror syntax in > definitions. > > tjr Thanks, It's starting to make sense :-) Steven From giveitawhril2008 at gmail.com Mon Jul 21 20:42:44 2008 From: giveitawhril2008 at gmail.com (giveitawhril2008 at gmail.com) Date: Mon, 21 Jul 2008 17:42:44 -0700 (PDT) Subject: Python Written in C? References: Message-ID: <38394a86-80d0-4c19-84c6-12b5390aed9d@z72g2000hsb.googlegroups.com> On Jul 20, 9:18 pm, Michiel Overtoom wrote: . > > Many major text/word processing programs (Emacs, vi, MS-Word) are also > written in C. Does that mean you should do all your text processing in C? Well, actually, as a COBOL geezer I should not complain about Python. Rumor had it that the COMPUTE statement in COBOL invoked FORTRAN arithmetic modules. Yes, real programmers DO write in FORTRAN! Frankly, I say screw not only object-oriented programming but structured programming as well. I think someone should write a compiler, "Revenge of BASIC." It would have good old REMs, FOR...TO...NEXTs, GOSUBS, GOTOs, etc. Standard libraries of subroutines, and/or Copy Libraries of source code, could handle switching to new screens or forms, placement of objects, alteration of characteristics of all these, detection of mouse and keyboard actions, graphics, sound, placement of HTML code, EVERYTHING! If anyone wants to write this compiler, they should probably do it in Python. Make it open source, of course. I'm waiting! From fredrik at pythonware.com Sat Jul 26 03:29:54 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 26 Jul 2008 09:29:54 +0200 Subject: xml.dom's weirdness? In-Reply-To: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> References: <3109fa90-dcde-409b-b5c7-5fa7400ca88c@s21g2000prm.googlegroups.com> Message-ID: Lie wrote: > Why this generates AttributeError, then not? > > Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import xml >>>> xml.dom > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'dom' >>>> xml.dom > this is what I get, on both Windows and Linux: >>> import xml >>> xml.dom Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'dom' >>> xml.dom Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'dom' From __peter__ at web.de Mon Jul 14 04:34:05 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 14 Jul 2008 10:34:05 +0200 Subject: subprocess module References: <2e7f0504-cc1c-4cb6-b2d0-b67b004eca7d@x41g2000hsb.googlegroups.com> Message-ID: John Mechaniks wrote: > from subprocess import call > call(['ls', '-l']) > > How do I get the result (not the exit status of the command) of "ls - > l" into a variable? output = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE).stdout.read() Peter From deets at nospam.web.de Mon Jul 28 02:58:42 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 28 Jul 2008 08:58:42 +0200 Subject: Python program as daemon? In-Reply-To: References: <8bb6bd1a-cd85-4b7a-8fc9-844f3794bca0@c58g2000hsc.googlegroups.com> <13866da4-01ed-4330-8297-8bdecce1393a@x35g2000hsb.googlegroups.com> Message-ID: <6f5913F9qs32U1@mid.uni-berlin.de> Lawrence D'Oliveiro schrieb: > In message > <13866da4-01ed-4330-8297-8bdecce1393a at x35g2000hsb.googlegroups.com>, > sturlamolden wrote: > >> Basically it forks twice ... > > What's the advantage of forking twice over forking once and calling setsid? http://code.activestate.com/recipes/278731/ See the comments. Diez From mensanator at aol.com Sat Jul 26 19:32:15 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 26 Jul 2008 16:32:15 -0700 (PDT) Subject: Insert string into string References: Message-ID: <56ff99b9-b4d4-4077-8de1-97a771ac526a@k13g2000hse.googlegroups.com> On Jul 26, 4:40?pm, "Francesco Pietra" wrote: > I am posting ex novo as it became confusing to me. I take the > opportunity to ask advice for a second problem. > > FIRST PROBLEM > For file xxx.pdb, insert letter "A" into each line that starts with > "ATOM". "A" should be inserted at position 22, i.e., one space after > "LEU", leaving all other characters at the same position as in the > original example: > > ATOM ? ? ?1 ?N ? LEU ? ? 1 ? ? 146.615 ?40.494 103.776 ?1.00 73.04 ? ? ? 1SG ? 2 > > In all lines starting with "ATOM", "LEU" is constant as to position > only (18-20), i.e., "LEU" may be replaced by > three different uppercase letters. Therefore, the most direct > indication would be position 22. If specifying line starting with > "ATOM" makes complication, forget about that as most lines begin with > "ATOM" so that hand correction will be easy. > > Script > f = open("xxx.pdb", "w") > import sys > > for line in sys.stdin: > ? ? line = line[:22] + "A" + line[23:] > ? ? sys.stdout.write(line) > > destroys the xxxx.pdb file and python exits witha non zero exit status. > > The same occurs with script > > f = open("hASIC1a.B99990003.pdb", "w") > f.write(' line = line[:22] + "A" + line[23:]') > f.close() > > I must have misunderstood the suggestion I received on previous posting. > ____________________________________ > SECOND PROBLEM > File xxx.pdb above has 426 lines stating with "ATOM", this serial > number occupying positions 7-11, right justified (Thus 1, as in the > line example above, means first line). A second, similar file yyy.pdb > has to be concatenated to xxx.pdb. Before that it should be added of > "A" as above and renumbered at position 7-11, starting from 428 (there > is an intermediate line to add). How should a script look like for > this string insertion into string with recursive +1? > > Thanks > francesco I don't know why you're using stdin if you're reading from a file. Also, the serial number isn't 7-11, it's 6-10 (remember to count from 0, so character 1 is position 0, etc.) fx = open('xxx.pdb','r') # first input file fy = open('yyy.pdb','r') # second input file fz = open('zzz.pdb','w') # output file (to be created) for xline in fx: # read input one line at a time if len(xline) >= 80: # don't process invalid lines line_index = int(xline[7:12]) # keep track of this if xline[:4]=='ATOM': fz.write(xline[:22] + 'A' + xline[23:]) else: fz.write(xline) fx.close() # done with first file fz.write('the extra line \n') line_index += 1 # don't forget to count it for yline in fy: # read second file if len(yline) >= 80: # again, valid only line_index += 1 # ignore serial number, use # where we left off from # from first file if yline[:4]=='ATOM': # note use of .rjust(5) to creat new serial number fz.write(yline[:6] + \ str(line_index).rjust(5) + \ yline[11:22] + 'A' + yline[23:]) else: fz.write(yline[:6] + \ str(line_index).rjust(5) + yline[11:]) fy.close() # done with second file fz.close() # done with output file From rocksportrocker at googlemail.com Thu Jul 17 09:14:45 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 17 Jul 2008 06:14:45 -0700 (PDT) Subject: How to process a very large (4Gb) tarfile from python? References: Message-ID: <0e96241d-60a3-44fd-967a-394904ad5b34@e39g2000hsf.googlegroups.com> On 17 Jul., 10:01, Terry Carroll wrote: > I am trying to do something with a very large tarfile from within > Python, and am running into memory constraints. ?The tarfile in > question is a 4-gigabyte datafile from freedb.org,http://ftp.freedb.org/pub/freedb/, and has about 2.5 million members > in it. > > Here's a simple toy program that just goes through and counts the > number of members in the tarfile, printing a status message every N > records (N=10,000 for the smaller file; N=100,000 for the larger). > > I'm finding that memory usage goes through the roof, simply iterating > over the tarfile. ?I'm using over 2G when I'm barely halfway through > the file. This surprises me; I'd expect the memory associated with > each iteration to be released at the end of the iteration; but > something's obviously building up. > > On one system, this ends with a MemoryError exception. ?On another > system, it just hangs, bringing the system to its knees, to the point > that it takes a minute or so to do simple task switching. > > Any suggestions to process this beast? ?I suppose I could just untar > the file, and process 2.5 million individual files, but I'm thinking > I'd rather process it directly if that's possible. > > Here's the toy code. ?(One explanation about the "import tarfilex as > tarfile" statement. I'm running Activestate Python 2.5.0, and the > tarfile.py module of that vintage was buggy, to the point that it > couldn't read these files at all. ?I brought down the most recent > tarfile.py fromhttp://svn.python.org/view/python/trunk/Lib/tarfile.py > and saved it as tarfilex.py. ?It works, at least until I start > processing some very large files, anyway.) > > import tarfilex as tarfile > import os, time > SOURCEDIR = "F:/Installs/FreeDB/" > smallfile = "freedb-update-20080601-20080708.tar" # 63M file > smallint = 10000 > bigfile ? = "freedb-complete-20080708.tar" ?# 4,329M file > bigiTnt = 100000 > > TARFILENAME, INTERVAL = smallfile, smallint > # TARFILENAME, INTERVAL = bigfile, bigint > > def filetype(filename): > ? ? return os.path.splitext(filename)[1] > > def memusage(units="M"): > ? ? import win32process > ? ? current_process = win32process.GetCurrentProcess() > ? ? memory_info = win32process.GetProcessMemoryInfo(current_process) > ? ? bytes = 1 > ? ? Kbytes = 1024*bytes > ? ? Mbytes = 1024*Kbytes > ? ? Gbytes = 1024*Mbytes > ? ? unitfactors = {'B':1, 'K':Kbytes, 'M':Mbytes, 'G':Gbytes} > ? ? return memory_info["WorkingSetSize"]//unitfactors[units] > > def opentar(filename): > ? ? modes = {".tar":"r", ".gz":"r:gz", ".bz2":"r:bz2"} > ? ? openmode = modes[filetype(filename)] > ? ? openedfile = tarfile.open(filename, openmode) > ? ? return openedfile > > TFPATH=SOURCEDIR+'/'+TARFILENAME > assert os.path.exists(TFPATH) > assert tarfile.is_tarfile(TFPATH) > tf = opentar(TFPATH) > count = 0 > print "%s memory: %sM count: %s (starting)" % (time.asctime(), > memusage(), count) > for tarinfo in tf: > ? ? count += 1 > ? ? if count % INTERVAL == 0: > ? ? ? ? print "%s memory: %sM count: %s" % (time.asctime(), > memusage(), count) > print "%s memory: %sM count: %s (completed)" % (time.asctime(), > memusage(), count) > > Results with the smaller (63M) file: > > Thu Jul 17 00:18:21 2008 memory: 4M count: 0 (starting) > Thu Jul 17 00:18:23 2008 memory: 18M count: 10000 > Thu Jul 17 00:18:26 2008 memory: 32M count: 20000 > Thu Jul 17 00:18:28 2008 memory: 46M count: 30000 > Thu Jul 17 00:18:30 2008 memory: 55M count: 36128 (completed) > > Results with the larger (4.3G) file: > > Thu Jul 17 00:18:47 2008 memory: 4M count: 0 (starting) > Thu Jul 17 00:19:40 2008 memory: 146M count: 100000 > Thu Jul 17 00:20:41 2008 memory: 289M count: 200000 > Thu Jul 17 00:21:41 2008 memory: 432M count: 300000 > Thu Jul 17 00:22:42 2008 memory: 574M count: 400000 > Thu Jul 17 00:23:47 2008 memory: 717M count: 500000 > Thu Jul 17 00:24:49 2008 memory: 860M count: 600000 > Thu Jul 17 00:25:51 2008 memory: 1002M count: 700000 > Thu Jul 17 00:26:54 2008 memory: 1145M count: 800000 > Thu Jul 17 00:27:59 2008 memory: 1288M count: 900000 > Thu Jul 17 00:29:03 2008 memory: 1430M count: 1000000 > Thu Jul 17 00:30:07 2008 memory: 1573M count: 1100000 > Thu Jul 17 00:31:11 2008 memory: 1716M count: 1200000 > Thu Jul 17 00:32:15 2008 memory: 1859M count: 1300000 > Thu Jul 17 00:33:23 2008 memory: 2001M count: 1400000 > Traceback (most recent call last): > ? File "C:\test\freedb\tardemo.py", line 40, in > ? ? for tarinfo in tf: > ? File "C:\test\freedb\tarfilex.py", line 2406, in next > ? ? tarinfo = self.tarfile.next() > ? File "C:\test\freedb\tarfilex.py", line 2311, in next > ? ? tarinfo = self.tarinfo.fromtarfile(self) > ? File "C:\test\freedb\tarfilex.py", line 1235, in fromtarfile > ? ? obj = cls.frombuf(buf) > ? File "C:\test\freedb\tarfilex.py", line 1193, in frombuf > ? ? if chksum not in calc_chksums(buf): > ? File "C:\test\freedb\tarfilex.py", line 261, in calc_chksums > ? ? unsigned_chksum = 256 + sum(struct.unpack("148B", buf[:148]) + > struct.unpack("356B", buf[156:512])) > MemoryError I had a look at tarfile.py in my current Python 2.5 installations lib path. The iterator caches TarInfo objects in a list tf.members . If you only want to iterate and you are not interested in more functionallity, you could use "tf.members=[]" inside your loop. This is a dirty hack ! Greetings, Uwe From FongAndrew at gmail.com Fri Jul 4 14:37:37 2008 From: FongAndrew at gmail.com (Andrew Fong) Date: Fri, 4 Jul 2008 11:37:37 -0700 (PDT) Subject: Getting a path from a file object Message-ID: <3c500ce7-c697-44e9-9f13-f65edc509e1c@a32g2000prf.googlegroups.com> Newbie question: Let's say I open a new file for writing in a certain path. How do I get that path back? Example: >>> f = open('/some/path/file.ext') >>> some_function(f) '/some/path/file.ext' Does some_function(f) already exist? And if not, how would I define it? -- Andrew From lamciuloeng at gmail.com Mon Jul 14 09:40:45 2008 From: lamciuloeng at gmail.com (CL (Ciu Loeng) Lam) Date: Mon, 14 Jul 2008 21:40:45 +0800 Subject: Turbogear installing error. Message-ID: HI,there: I get the errors below when installing the Turebogear,could anyone help me ? Thanks in advance. error: Not a recognized archive type: c:\docume~1\admini~1\locals~1\ temp\easy_in stall-y2znne\PasteScript-1.6.3.tar.gz -------------- next part -------------- An HTML attachment was scrubbed... URL: From maestroQC at gmail.com Tue Jul 15 11:06:21 2008 From: maestroQC at gmail.com (maestroQC) Date: Tue, 15 Jul 2008 08:06:21 -0700 (PDT) Subject: MySQL Insert Message-ID: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> Hi, Its one of those days. I cannot solve this. Any help would be greatly appreciated! When I execute this: class Db(object): def insertAccount(self, date, accountNumber, description, openingBalance): dec = decimal.Decimal(openingBalance) db = MySQLdb.connect(host="localhost", user="dumb", passwd="dumber", db="rdc") cursor = db.cursor() cursor.execute("INSERT INTO es_accounts (dateCreated, accountNumber, description, openingBalance) VALUES (%s, %s, %s, %d)", (date, accountNumber, description, dec)) I get this error: Traceback (most recent call last): File "main.py", line 59, in main() File "main.py", line 40, in main dbObj.insertAccount(dateTo, item[0], item[1], item[8]) File "C:\projects\workspace\INYR_ES_0.1\src\db.py", line 19, in insertAccount cursor.execute("INSERT INTO es_accounts (dateCreated, accountNumber, description, openingBalance) VALUES (%s, %s, %s , %d)", (date, accountNumber, description, dec)) File "c:\python25\lib\site-packages\MySQLdb\cursors.py", line 151, in execute query = query % db.literal(args) TypeError: int argument required My table is defined as: CREATE TABLE es_accounts ( id int(6) not null auto_increment, dateCreated date DEFAULT '0000-00-00', accountNumber int(6) not null, description varchar(255) not null, openingBalance decimal(15,8) NOT NULL DEFAULT 0.00000000, primary key (id) ); TIA From gherron at islandtraining.com Mon Jul 28 18:58:37 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 28 Jul 2008 15:58:37 -0700 Subject: derivative in numpy In-Reply-To: References: Message-ID: <488E4F1D.3060908@islandtraining.com> knielsen73 at gmail.com wrote: > Hi, > > I am looking to do a simple derivative. I would expect such a function > to be available in numpy, but can't find it. I have written my own, > but just curious if anybody knows of such function in numpy. > Derivatives are a property of functions. Since numpy provides representations of arrays not functions, how would you expect this to work? To be more concrete, what you you expect the derivative of [ [ 1 2 ] [ 3 4 ] ] to be? Or do you have in mind some array representation of the coefficients of a function of some pre-defined type - like a polynomial? Gary Herron > Cheers, > Kim > -- > http://mail.python.org/mailman/listinfo/python-list > From waldemar.osuch at gmail.com Sun Jul 13 17:30:41 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Sun, 13 Jul 2008 14:30:41 -0700 (PDT) Subject: SAX XML Parse Python error message References: <487A23A5.7000905@behnel.de> Message-ID: <1c87a4e2-7c66-4ced-8622-b6eebc8664bb@i76g2000hsf.googlegroups.com> On Jul 13, 3:00 pm, goldtech wrote: > I would be grateful for support with the code I cited. It's not long > and fairly standard. I'm sure my error(s) would be glaring to more > experienced coders. I appreciated the "heads-up" about other options > but I would be grateful for help getting this code to run. Thanks Initialize self.coodinates in the __init__ or indent the "print self.description, str(self.coordinates)" one more level. You have to remember that "endElement" is being called on the end of every element. In your case it is called by but the parser did not see yet. In "def characters" you should be collecting the "ch" in a buffer. It may be called multiple times for the same element. Something like "self.description += ch" would do for starters. Also you do not need to convert self.coordinates to string before printing, it is already a string and even if it was not "print" would convert it for you. That's it for now :-) Others may spot more issues with your code or my response. On the positive side I really liked how you asked the question. There was a short runnable example and traceback. Waldemar From MDiPierro at cs.depaul.edu Wed Jul 16 18:56:21 2008 From: MDiPierro at cs.depaul.edu (Massimo Di Pierro) Date: Wed, 16 Jul 2008 17:56:21 -0500 Subject: Framework recommendations for web service? Message-ID: <8355B44C-7BA9-4E36-B804-F8E0CF0B137E@cs.depaul.edu> web2py (not to be confused with web.py although both of them are excellent) comes with XMLRPC, XML, JSON and RSS API. You can find an XMLRPC example here: http://mdp.cti.depaul.edu/examples/default/examples#xmlrpc_examples The web2py source (including the optional web based interface) fits in 1.3MBytes. Massimo > Phillip B Oldham wrote: > > So, can anyone suggest a lightweight python framework which just does > > the essentials? > > web.py is pretty slim (not to be confused with web2py). > > Pylons isn't very large, depending on what you call "essential." -------------- next part -------------- An HTML attachment was scrubbed... URL: From semanticist at gmail.com Fri Jul 18 20:44:52 2008 From: semanticist at gmail.com (Miles) Date: Fri, 18 Jul 2008 20:44:52 -0400 Subject: __del__ methods In-Reply-To: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> References: <981d94cd-2534-42ee-a0df-3f5f63b23c91@r66g2000hsg.googlegroups.com> Message-ID: On Fri, Jul 18, 2008 at 2:31 PM, Jason Baker wrote: > I have a class that I need to do some finalization on when it dies. I > know I can use the __del__ method, but I seem to recall that it > impedes garbage collection. Is this the case? Yes. "Objects that have __del__() methods and are part of a reference cycle cause the entire reference cycle to be uncollectable, including objects not necessarily in the cycle but reachable only from it. Python doesn't collect such cycles automatically because, in general, it isn't possible for Python to guess a safe order in which to run the __del__() methods." The uncollectable objects are stored in gc.garbage and will not be freed until their reference cycles are broken and they are removed from that list. http://docs.python.org/lib/module-gc.html -Miles From tjreedy at udel.edu Tue Jul 29 16:03:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 29 Jul 2008 16:03:43 -0400 Subject: Build tool for Python In-Reply-To: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> References: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Message-ID: Hussein B wrote: > Hi. > Apache Ant is the de facto building tool for Java (whether JSE, JEE > and JME) application. > With Ant you can do what ever you want: compile, generate docs, > generate code, packing, deploy, connecting to remote servers and every > thing. > Do we have such a tool for Python projects? Also see thread Continuous integration for Python projects and mention of buildbot. From circularfunc at gmail.com Thu Jul 10 16:40:12 2008 From: circularfunc at gmail.com (ssecorp) Date: Thu, 10 Jul 2008 13:40:12 -0700 (PDT) Subject: Weird lambda rebinding/reassignment without me doing it References: <02ff4326-7b07-4ae6-8607-f58ea61802ef@z72g2000hsb.googlegroups.com> Message-ID: ty very good answer. i know i shouldn't use lambda like that, i never do i was just playing around there and then this happened which i thought was weird. On Jul 10, 8:09?pm, Terry Reedy wrote: > David C. Ullrich wrote: > > In article > > <02ff4326-7b07-4ae6-8607-f58ea6180... at z72g2000hsb.googlegroups.com>, > > ?ssecorp wrote: > > >> I am never redefining the or reassigning the list when using validate > >> but since it spits the modified list back out that somehow means that > >> the modified list is part of the environment and not the old one. > >> i thought what happend inside a function stays inside a function > >> meaning what comes out is independent of what comes in. > >> Meaning if I want the list I send as a parameter to the function I > >> have to do x = func(x) and not just func(x) and x is magically what > >> comes out of func(). > > > A function cannot modify the value of a global variable > > Yes it can. > ?>>> a=[] > ?>>> def f(): > ? ? ? ? a.append('yes I can') > > ?>>> f() > ?>>> a > ['yes I can'] > > > (unless it specifies "global"). It doesn't reassign anything. > > The statement 'global a' would allow f to *rebind* the global *name* > 'a'. ?The word 'variable' should almost not be used in discussing Python > since it is often unclear whether it refers to a name (or collection > slot) or an object bound thereto. > > > But in the functions below you're not reassigning a variable, > > you're _modifiying_ an object. A function _can_ modify an > > object you pass to it: > > It can modify any mutable object it can access. > > >> Doesnt Python have closure or that isnt what this is about? > > Python does have closures. ?This is not about that. > > >> def validate(placed): > >> ? ? student = round(random.random()*401) > >> ? ? if student in placed: > >> ? ? ? ? return validate(placed) > >> ? ? else: > >> ? ? ? ? placed.append(student) > >> ? ? ? ? return student, placed > > Delete this. It is redundant with the below. > > >> def val(placed): > >> ? ? student = round(random.random()*401) > >> ? ? if student in placed: > >> ? ? ? ? return validate(placed) > >> ? ? else: > >> ? ? ? ? placed.append(student) > >> ? ? ? ? return student > > I believe this is equivalent to > > def addval(placed): > ? ?while True: > ? ? ?student = round(random.random()*401) > ? ? ?if student not in placed: > ? ? ? ?break > ? ?placed.append(student) > ? ?return student > > While this avoids the indefinite recursion depth problem, it does not > avoid the indefinite time problem. ?Use random.shuffle, or write your > own version if doing this for practice. ?Also consider removing the > return statement unless you actually directly use the added value. ?It > is easier to remember that addval mutates 'placed' without the return. > > >>>>> g = lambda x:validate(x) > > This is doubly diseased. > > First, never write a 'name = lambda...' statement since it is equivalent > to a def statement except that the resulting function object lacks a > proper .funcname attribute. ?The above only trivially abbreviates > ? ?def g(x): return validate(x) > by 3 characters. ?Another reason is that the lambda form somehow more > often tricks people into the next mistake . > > Second, never write a function (with either def or lambda) that simply > returns a function of the argument(s). ?The wrapping does nothing! ?This > is a waste of time and space for both you and the interpreter. ?The > above is functionally equivalent to > ? ?g = validate > and if you want that, you could name the function 'g' when you define it. > > >>>>> l=[] > > In some fonts, 'l' and '1' are nearly identical; please use something > else for public code, which you made this to be by posting it;-) > > >>>>> for x in range(1,10): > >> ? ? ? ?g(l) > > As said, the 'g' wrapper is useless. > ? ? ? ? addval(l) > > Hope this helps. > > Terry Jan Reedy From tjreedy at udel.edu Sat Jul 26 17:49:17 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 26 Jul 2008 17:49:17 -0400 Subject: Attack a sacred Python Cow In-Reply-To: References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <48884afe$0$10430$426a74cc@news.free.fr> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> Message-ID: Paul Boddie wrote: > On 26 Jul, 06:06, Terry Reedy wrote: >> Paul Boddie wrote: >>> "The problem is that the explicit requirement to have self at the >>> start of every method is something that should be shipped off to the >>> implicit category." > > Here, I presume that the author meant "at the start of every method > signature". > >> There is no requirement to have 'self' in the parameter list. It can be >> 's', 'this', 'me', 'yo'(Spanish for I), or 'cls' (for class methods), or >> any other identifier in whatever language. > > But Jordan apparently wanted to omit that parameter. The omission of > all mentions of "self" could be regarded as a bonus, but it's a non- > trivial goal. Reword. There is no requirement to name the instance anything in particular. Thus there is no requirement at present that the first parameter, which gives the name of the instance, be anything in particular. >> In 3.0, identifiers are not restricted to ascii but can be any unicode >> 'word' as defined in the manual. >> >> So the proposal would have to be that the compiler scan the function >> body and decide which dotted name prefix is the one to be implicitly >> added. Have fun writing the discovery algorithm. However, I think this >> is pretty silly. Just write the name you want. > > If, as I wrote, you permit the omission of "self" in method signatures > defined within class definitions, then you could still insist on > instance attribute qualification using "self" - exactly as one would > when writing Java according to certain style guidelines. Which is what I said in the first sentence of my next paragraph, which you clipped. "Or the proposal would have to be that 'self' is mandatory for all programmers in all languages." To clarify " ... that 'self' be the mandatory instance name for all Python programmers regardless of inclination or the natural language they otherwise use as a basis for identifiers." In sum, if the instance name is omitted from the parameter list, it must either be discovered or mandated, and def statements in direct class scope have to be treated differently from def statements elsewhere. Terry Jan Reedy From bdesth.quelquechose at free.quelquepart.fr Thu Jul 24 17:10:15 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 24 Jul 2008 23:10:15 +0200 Subject: Neat way to get rid of [" "] in sys.argv[n:] returns In-Reply-To: References: Message-ID: <4888efae$0$5589$426a74cc@news.free.fr> korean_dave a ?crit : > so, i code this: > ----------------------------- > #!/usr/bin/python > > import sys > import os > > for param in os.environ.keys(): > print "%20s %s" % (param,os.environ[param]) > > print(os.environ['PATH']) > > print(sys.argv[1:]) > -------------------------- > and then when i type in --> > > python test.py "testparameter" > > I get this output: > > ------------- > ['testparameter'] > ---------------- > > Is there a way to neatly, in one call to the parameter, to get rid of > the [' and '] without bothering to replace() '[ with "" and replace() > '] with ''? exact-but-useless-answer: print sys.argv[1] to-the-point-answer: print " ".join(sys.argv[1:]) and-if-I-may-ask: - do you understand why you get these "[' ']" ? From amdescombes at gmail.com Mon Jul 21 15:45:52 2008 From: amdescombes at gmail.com (AMD) Date: Mon, 21 Jul 2008 21:45:52 +0200 Subject: scanf in python In-Reply-To: <6ek4cgF7hq4vU1@mid.uni-berlin.de> References: <4884be5e$0$19722$426a74cc@news.free.fr> <6ek4cgF7hq4vU1@mid.uni-berlin.de> Message-ID: <4884e77a$0$29405$426a74cc@news.free.fr> > > I'm pretty certain python won't grow an additional operator for this. > Yet you are free to create a scanf-implementation as 3rd-party-module. > > IMHO the usability of the approach is very limited though. First of all, > the need to capture more than one input token is *very* seldom - nearly > all commandline-tools I know that do require interactive user-input > (like the linux kernel config tool) do so by providing either > line-by-line value entry (including defaults, something you can't do > with your approach), or even dialog-centric value entry with curses. > > So - I doubt you will gather much momentum on this. Good luck though. > > > Diez Actually it is quite common, it is used for processing of files not for reading parameters. You can use it whenever you need to read a simple csv file or fixed format file which contains many lines with several fields per line. The advantage of the approach is that it combines the parsing and conversion of the fields into one operation. Another advantage of using simple formatting strings is that it allows for easy translation of these lines, just like you have with the % operator for output. I don't see why python can have an operator for output but it can't have one for input, it's just not symmetrical. I don?t see why you can't use this method for line-by-line value entry, just add \n between your %s or %d. The method is quite versatile and much simpler than regular expressions plus conversion afterwards. Andr? From pyth0nc0d3r at gmail.com Sat Jul 19 14:38:49 2008 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Sat, 19 Jul 2008 13:38:49 -0500 Subject: How do you check if a program/process is running using python? Message-ID: How do you check if a program or process is running when using python? What I want to do is have an infinite loop to check if a program is running or not and send data to my web server to check yes or no. Is this possible? If so how? -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick83ola at gmail.com Tue Jul 1 11:26:29 2008 From: nick83ola at gmail.com (nickooooola) Date: Tue, 1 Jul 2008 08:26:29 -0700 (PDT) Subject: Implementing an 8 bit fixed point register References: <1f705855-1601-4d0e-9082-bb9258a5a586@f63g2000hsf.googlegroups.com> Message-ID: <72cb8cf8-a73d-4405-a347-197cb3d61c23@26g2000hsk.googlegroups.com> Thanks to all for the responses! to MEl: I also want to build a pic simulator, but I want to do this as "python for big project" learning exercise, I have used python in the past only for small script and now I want to use it for something more "big". do you have some code to share? myhdl seems interesting, I think that I can take a blick on its source code...I think that must have something like the 8 bit register class that I need somewhere I try what you people have said, and if it turns to be something useful, I report it to the community. Nicola Ps excuse me for my english... From jstrickler at gmail.com Fri Jul 18 12:28:42 2008 From: jstrickler at gmail.com (John S) Date: Fri, 18 Jul 2008 09:28:42 -0700 (PDT) Subject: trying to match a string References: <0d8163fa-645a-43e0-8ff0-18926b042408@w1g2000prk.googlegroups.com> <89516709-1cb5-4a47-b6ba-5418430a8697@v21g2000pro.googlegroups.com> <040b48f3-6489-4970-9cbb-bd623349dc36@r35g2000prm.googlegroups.com> <4880AD1A.6040707@gmail.com> Message-ID: On Jul 18, 7:51 am, Andrew Freeman wrote: > Andrew Freeman wrote: > > oj wrote: > >> On Jul 18, 12:10 pm, John Machin wrote: > > >>> On Jul 18, 9:05 pm, oj wrote: > > >>>> On Jul 18, 11:33 am, arnimavidyar... at gmail.com wrote: > > >>>>> Hi, > >>>>> Hi, > >>>>> I am taking a string as an input from the user and it > >>>>> should only > >>>>> contain the chars:L , M or R > >>>>> I tried the folllowing in kodos but they are still not > >>>>> perfect: > >>>>> [^A-K,^N-Q,^S-Z,^0-9] > >>>>> [L][M][R] > >>>>> [LRM]?L?[LRM]? etc but they do not exactly meet what I need. > >>>>> For eg: LRLRLRLRLM is ok but LRLRLRNL is not as it has 'N' > >>>>> .like that. > >>>>> regards, > >>>>> SZ > >>>>> The string may or may not have all the three chars. > > >>>> With regular expressions, [^LRM] matches a character that isn't L, R > >>>> or M. So: > >>>> import re > >>>> var = "LRLRLRLNR" > >>>> if re.search(r'[^LRM]', var): > >>>> print "Invalid" > > >>> Fails if var refers to the empty string. > > >> No it doesn't, it succeeds if var is an empty string. An empty string > >> doesn't contain characters that are not L, R or M. > > >> The OP doesn't specify whether an empty string is valid or not. My > >> interpretation was that an empty string would be valid. > > > Why not just use * instead of + like: > > > if re.search(r'^[^LRM]*$', var): # note: ^ outside [] is start of > > string; $ means end of string > > print "Invalid" > > > This will *only* print invalid when there is a character other than L, > > R, or M or a empty string. > > Sorry, forget the beginning and ending markers, I just tried it out, it > doesn't work. > use this instead: > > if re.search(r'[^LRM]*', var): > print "Invalid" This won't work -- every string in the universe contains 0 or more characters which are not 'L', 'R', or 'M'. That is, the regular expression X* could match the empty string, which can be found in all strings. From Caseyweb at gmail.com Fri Jul 11 19:46:41 2008 From: Caseyweb at gmail.com (Casey) Date: Fri, 11 Jul 2008 16:46:41 -0700 (PDT) Subject: Perfect hashing for Py References: Message-ID: <666edc45-098a-4894-99eb-8367d5f3edb4@k30g2000hse.googlegroups.com> On Jul 11, 8:01?am, bearophileH... at lycos.com wrote: > Following links from this thread:http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > I have found this perfect hash (minimal too) implementation:http://burtleburtle.net/bob/hash/perfect.html > > I have already translated part of it to D, and it seems to work well > enough. As discussed in the PyConDue, I think this may be used in > frozenset (and frozendict) to build a (minimal too?) perfect hash on > the fly, to allow (hopefully) faster retrieval of items that don't > change. > That code is C and I think it's public domain, so if experiments show > it gives enough speed up, it may be added to CPython 2.6/3. > > Bye, > bearophile It would be interesting to see if such an algorithm could actually provide any significant performance improvements for the size of sets that I suspect are most often used in practice. The chance of a hash collision for a good 32-bit general is fairly low even for a set of 1,000,000 unique elements, which seems to me to be a pretty large memory-based set. Compare that with the cost of determining a perfect hash (O(n**2)?). From my perspective, a perfect hash would certainly be a welcome addition to the Python library or even as an optional algorithm supporting hash-based collections. From deets at nospam.web.de Tue Jul 22 10:11:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 22 Jul 2008 16:11:31 +0200 Subject: tkinter for my python program !! References: <6em5snF7r22oU3@mid.uni-berlin.de> <63ff0b6f-8c75-4172-b836-8497870544ca@s50g2000hsb.googlegroups.com> Message-ID: <6em86gF7q9djU1@mid.uni-berlin.de> karthikbalaguru wrote: > On Jul 22, 6:32 pm, "Diez B. Roggisch" wrote: >> karthikbalaguru wrote: >> > Hi, >> >> > One of my python program needs tkinter to be installed to run >> > successfully. >> > I am using Redhat 9.0 and hence tried installing by copying the >> > tkinter-2.2.2-36.i386.rpm >> > alone from the CD 3 to my pc. But, it is not getting installed and is >> > failing by throwing >> > the below errors. Should i need to configure / install any specific >> > files for resolving this issue ? >> >> > [root at localhost karthik]# rpm -ivh tkinter-2.2.2-26.i386.rpm >> > warning: tkinter-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, >> > key ID db42a >> > 60e >> > error: Failed dependencies: >> > libtcl8.3.so is needed by tkinter-2.2.2-26.i386 >> > libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 >> > libtk8.3.so is needed by tkinter-2.2.2-26.i386 >> >> > Any ideas ? >> >> Yes: you should consider reading error-messages. What does >> >> error: Failed dependencies: >> libtcl8.3.so is needed by tkinter-2.2.2-26.i386 >> libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 >> libtk8.3.so is needed by tkinter-2.2.2-26.i386 >> >> look like for you? >> >> Small hint: if you install something that depends on something else, you >> need to .... the missing dependency first. Fill in the dots... >> > > I find that it needs python-2.2.2-26.i386 and hence i tried installing > python and i > land here :( :( > > [root at localhost karthik]# rpm -ivh python-2.2.2-26.i386.rpm > warning: python-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key > ID db42a60e > error: Failed dependencies: > libdb-4.0.so is needed by python-2.2.2-26.i386 > python < 2.4.3-18.fc6 conflicts with python- > devel-2.4.3-18.fc6.i386 > [root at localhost karthik]# > > > I find that python 2.4.3-18.fc6 is being used by many of applications. > But, the program i am trying to run needs python-2.2.2-26. > So, how to resolve this issue ? Are you *sure* it requires python2.2? If yes, why can't fedora install several python versions together? Ubuntu for sure can. But Python2.2 is *ancient* - you might need to compile it yourself. Diez From dfnsonfsduifb at gmx.de Mon Jul 21 09:26:18 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Mon, 21 Jul 2008 15:26:18 +0200 Subject: Python Written in C? In-Reply-To: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> References: <02b6e6fe-a2fa-4c78-8d4c-db55f7815841@z66g2000hsc.googlegroups.com> Message-ID: Mensanator schrieb: > You want cool? > THIS is cool: > > j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2])) > % xyz[1]**(k-1))/xyz[1]**(k-2) You call it cool, I call it NameError: name 'invert' is not defined. Regards, Johannes -- "Wer etwas kritisiert muss es noch lange nicht selber besser k?nnen. Es reicht zu wissen, da? andere es besser k?nnen und andere es auch besser machen um einen Vergleich zu bringen." - Wolfgang Gerber in de.sci.electronics <47fa8447$0$11545$9b622d9e at news.freenet.de> From spandanagella at gmail.com Thu Jul 3 02:52:45 2008 From: spandanagella at gmail.com (spandana g) Date: Thu, 3 Jul 2008 14:52:45 +0800 Subject: HTTP request error with urlopen Message-ID: Hello , I have written a code to get the page source of the google search page .. this is working for other urls. I have this problem with import re from urllib2 import urlopen string='http://www.google.com/search?num=20&hl=en&q=ipod&btnG=Search' file_source=file("google_source.txt",'w') file_source.write(urlopen(string).read()) page_content=file_source.readlines() Traceback (most recent call last) : File "C:/Python25/google.py", line 5,in file_source.write(urlopen(string).read()) File "C:\Python25\lib\urllib2.py", line 124 , in urlopen return__opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 387 , in open response =meth(req, response) File "C:\Python25\lib\urllib2.py", line 498 , in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 425, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 360, in __call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 506, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: Forbidden Actually urlopen is working for google labs sets page but not for the google.com and even I have same problem with wikipedia . Please let me know .. If any one of have any idea about this . Thank You, Spandana. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gherron at islandtraining.com Wed Jul 30 18:10:36 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 30 Jul 2008 15:10:36 -0700 Subject: overriding file.readline: "an integer is required" In-Reply-To: References: Message-ID: <4890E6DC.8080504@islandtraining.com> kj wrote: > I'm trying to subclass file, overriding the readline method. The > new method definition begins with > > def readline(self, size=None): > line = self.file.readline(size) > # etc., etc. > > ...where the self.file attribute is a regular file object. > > This works fine if I invoke the new method with an integer argument, > but if I invoke it without arguments, I get the error > > TypeError: an integer is required > > ...which I suppose comes from the call to self.file.readline(None). > > I know that I could rewrite the method like this: > > def readline(self, size=None): > if size == None: > line = self.file.readline() > else: > line = self.file.readline(size) > # etc., etc. > > ...but this seems to me exceptionally awkward. (Actually, it's worse > than awkward: it fails to complain when the overriding method is > called with the argument None. It would be better to test for the > number of arguments passed to the function, but I can't figure out > how to do this either.) > > Is there a better idiom? > Since the manual implies that negative values have no effect, try this: def readline(self, size=-1): line = self.file.readline(size) # etc., etc. I tested this (just barely), and it seems to work as you wish. Gary Herron > TIA! > > Kynn > From fredrik at pythonware.com Thu Jul 24 03:48:03 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 09:48:03 +0200 Subject: Attack a sacred Python Cow In-Reply-To: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> Message-ID: Jordan wrote: > Except when it comes to Classes. I added some classes to code that had > previously just been functions, and you know what I did - or rather, > forgot to do? Put in the 'self'. In front of some of the variable > accesses, but more noticably, at the start of *every single method > argument list.* This cannot be any longer blamed as a hangover from > Java - I've written a ton more code, more recently in Python than in > Java or any other OO language. What's more, every time I go back to > Python after a break of more than about a week or so, I start making > this 'mistake' again. The perennial justification for this 'feature' > of the language? That old Python favourite, "Explicit is better than > implicit." Do you seriously think that Python is designed by mindless application of a set of humorous and somewhat self-deprecating observations posted to a newsgroup a number of years ago? From pdorange at pas-de-pub-merci.mac.com Wed Jul 30 03:04:56 2008 From: pdorange at pas-de-pub-merci.mac.com (Pierre-Alain Dorange) Date: Wed, 30 Jul 2008 09:04:56 +0200 Subject: Python embedding question (2). References: Message-ID: <1ikuf8r.1s2a5ex11pfrveN%pdorange@pas-de-pub-merci.mac.com> Thomas Troeger wrote: > I've managed to put together a small pyGame program, it runs smoothly > and seems to be exactly what I wanted. It's fast! Even with 100 moving > objects it still runs so fast that I can consider using Python/pyGame > for the whole project. > > There are still some questions left which I haven't found out by myself, > so maybe someone here can answer them: > > - I can't see how to create more sophisticated text output, it seems the > built in font render facilities are limited to simple strings. Is that > true? Yes, for my part i start to make a (small) library myself for my little game in development (simple). Supporting bidirectionnal in such a case is not a big deal, but markups will be not trivial (but python has tools to parse text, this can help). Also have a look at somme gui library for pygame : It seems PGU is one of the most used. > - Is there some way to reserve screen areas so they are excluded from a > blit, or do I have to manage stuff like this myself? You can blit any rectangle it's trivial. for example group.draw render the sprites in it, into the surface given, this surface can be the screen or any other "virtual surface". You just have to render this "virtual" on screen whn done. You can also used the more sophisticate "dirty rect" (group.RenderUdates) or even better group.LayeredUpdates. I start with but a can not make all things work properly at that time. > I am thinking about > several graphic layers where each layer is painted on top of the next > layer, for example to draw a gui in front of a background image. For this is simply create sprite groups (one per layer) and than call group render (group.draw) in the order i need. Easy and efficient. > - There seems to be support for video overlay, i.e. is it possible to > have an external program paint an image from a camera into a portion of > the screen while pyGame is running? Don't know... -- Pierre-Alain Dorange Ce message est sous licence Creative Commons "by-nc-sa-2.0" From babacity4 at gmail.com Thu Jul 24 16:51:21 2008 From: babacity4 at gmail.com (babacity4 at gmail.com) Date: Thu, 24 Jul 2008 13:51:21 -0700 (PDT) Subject: sextv1 net - Amazing porn video collection Message-ID: <2ed8b9cd-466f-4589-8310-b906523c7e48@b30g2000prf.googlegroups.com> sextv1 net . >>>>>>>>>>Best Collection of Sextv1 Videos<<<<<< >>>>>>>>>>>>http://vids365.com/watch.php<<<<<<<<<<< >>>>>>>>>>>>>>FREE sextv1 net VIDEOS<<<<<<<<<<< . sextv1 net From mccredie at gmail.com Tue Jul 22 20:29:16 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 22 Jul 2008 17:29:16 -0700 (PDT) Subject: How do I compare files? References: Message-ID: On Jul 22, 4:27?pm, Clay Hobbs wrote: > I am making a program that (with urllib) that downloads two jpeg files > and, if they are different, displays the new one. ?I need to find a way > to compare two files in Python. ?How is this done? > > -- Ratfink Do you just want to check to see if they are the same? Or do you actually want to know what the differences are? import urllib data1 = urllib.urlopen("http://url.of.jpg1").read() data2 = urllib.urlopen("http://url.of.jpg2").read() if data1 == data2: print "they are the same" Doing a regular text diff won't tell you much. You could use PIL and do all sorts of image manipulation though. You might generate an image of the difference between each pixel. Something like this: import Image import ImageChops import urllib data1 = urllib.urlopen("http://url.of.jpg1").read() data2 = urllib.urlopen("http://url.of.jpg2").read() im1 = Image.fromstring(data1) im2 = Image.fromstring(data2) result = ImageChops.difference(im1, im2) result.save("result_image.jpg") Read up on PIL: http://www.pythonware.com/library/pil/handbook/index.htm Matt From wmcbrine at users.sf.net Mon Jul 28 14:22:50 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Mon, 28 Jul 2008 18:22:50 GMT Subject: like py2exe, but on a mac References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> Message-ID: <_7ojk.253$wS4.85@trnddc03> On Mon, 28 Jul 2008 19:51:26 +0200, Tommy Nordgren wrote: > There is Platypus, a general open source program to wrap a script > in an Macintosh (GUI) Application. Thanks. I tried Platypus, and it's close to what I want. But I still can't seem to get rid of the small "Console" window that pops up behind my Tkinter app. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From murugesan550 at gmail.com Thu Jul 24 23:27:49 2008 From: murugesan550 at gmail.com (muruges) Date: Thu, 24 Jul 2008 20:27:49 -0700 (PDT) Subject: .............................on line jobs........................................ Message-ID: <6f37bd72-02fb-46c2-9b67-2515fd93a424@v26g2000prm.googlegroups.com> we are selecting you for this online jobs. For more information see this website in this.............................. we are selecting you for this online jobs. For more information see this website in this.............................. Details .................. Name of the job.........................Online job.......................... Nature of work...........................Like data entry.......................... Qualification required........................good knowledge in computer Basics Earnings................More then Rs=1000 per day......................Earnings depends on your work............................. FOR MORE DETAILS: WWW.Bigconstructions5.blogspot.com From christopher.saunter at durham.ac.uk Wed Jul 23 07:03:13 2008 From: christopher.saunter at durham.ac.uk (c d saunter) Date: Wed, 23 Jul 2008 11:03:13 +0000 (UTC) Subject: Parsing VHDL with python, where to start. References: Message-ID: Svenn Are Bjerkem (svenn.bjerkem at googlemail.com) wrote: : Hi, : I am in the need to write an application for PyQt to visualise the : structure of a VHDL project I am working on. Looking for a sensible : way to parse VHDL files and putting them into a data structure that : PyQt can represent as a tree (or whatever the MVC is supporting) : through search engines does not give me many hints. From what I know, : VHDL is not a very easy language to parse. There seems to be a parser : for perl available, but I do not know if it is wise to use a perl : module as a template for writing something similar in python. Hi Sven, How much of VHDL are you looking to parse? Are you just looking at files intended for synthesis, or at simulation/testbench files as well? I wrote a basic parser a few years ago for automatically stringing modules together, but it was very limited in scope. I thought VHDL was quite simple to parse, it's very rigid. Having written a basic one I realised I'd coded myself into a dead-end as you say. Maybe not so simple after all... :-) If I started again I'd use pyparsing: http://pyparsing.wikispaces.com/ Looks like someone is already there in part: http://pyparsing.wikispaces.com/message/view/home/103973 Regards, Chris : My initial idea is to start simple and extend features in my : application, but I fear that I may start off with wrong ideas how to : parse and then code myself into a dead-end requiring myself to rewrite : the whole application in order to get any further. I would start : finding definitions of entities and the instantiations of these and : build a tree from a set of external vhdl files stored in a file : hierarchy. If somebody have a starting point where to get going with a : task like this, I would be happy to know. : -- : kind regards, : Svenn From JordanNealBerg at gmail.com Mon Jul 14 20:39:14 2008 From: JordanNealBerg at gmail.com (Jordan) Date: Mon, 14 Jul 2008 17:39:14 -0700 (PDT) Subject: Python ver of System.arraycopy() in Java Message-ID: <6041eb3a-6e32-44cb-a442-5cf3ac9b4d9d@59g2000hsb.googlegroups.com> I could seem to find a built in function that would serve the purpose of System.arraycopy() in java. I was able to accomplish it with something like this: def arraycopy(source, sourcepos, dest, destpos, numelem): dest[destpos:destpos+numelem] = source[sourcepos:sourcepos +numelem] is there a built in version, or better way of doing this... From tim.arnold at sas.com Wed Jul 30 12:41:38 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Wed, 30 Jul 2008 12:41:38 -0400 Subject: Build tool for Python References: <0137e820-162d-44cb-a69a-fc44cc9d6108@f63g2000hsf.googlegroups.com> Message-ID: "Terry Reedy" wrote in message news:mailman.868.1217361931.922.python-list at python.org... > > > Hussein B wrote: >> Hi. >> Apache Ant is the de facto building tool for Java (whether JSE, JEE >> and JME) application. >> With Ant you can do what ever you want: compile, generate docs, >> generate code, packing, deploy, connecting to remote servers and every >> thing. >> Do we have such a tool for Python projects? > > Also see thread Continuous integration for Python projects and mention of > buildbot. Surprised no one has mentioned SCons, http://www.scons.org/ I've used it a bit and found it pretty good, out of the box. --Tim Arnold From is_this at visible.com Thu Jul 31 12:36:05 2008 From: is_this at visible.com (Bruce Frederiksen) Date: Thu, 31 Jul 2008 16:36:05 +0000 Subject: Non Continuous Subsequences References: Message-ID: <9e5a3$4891e9f5$18607848$1746@KNOLOGY.NET> On Wed, 30 Jul 2008 09:32:25 -0700, bearophileHUGS wrote: > This post is not about practical stuff, so if you have little time, > you may ignore it. > > This is a task of the rosettacode.org site: > http://www.rosettacode.org/wiki/Non_Continuous_Subsequences > > A subsequence contains some subset of the elements of this sequence, > in the same order. A continuous subsequence is one in which no > elements are missing between the first and last elements of the > subsequence. The task is to enumerate all non-continuous subsequences > for a given sequence. > > Translating the Scheme code to Python was easy (and I think this is > quite more readable than the Scheme version): > > def ncsub(seq, s=0): > if seq: > x = seq[:1] > xs = seq[1:] > p2 = s % 2 > p1 = not p2 > return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + > p2) > else: > return [[]] if s >= 3 else [] > > Output: > >>>> ncsub(range(1, 4)) > [[1, 3]] >>>> ncsub(range(1, 5)) > [[1, 2, 4], [1, 3, 4], [1, 3], [1, 4], [2, 4]] >>>> ncsub(range(1, 6)) > [[1, 2, 3, 5], [1, 2, 4, 5], [1, 2, 4], [1, 2, 5], [1, 3, 4, 5], [1, > 3, 4], [1, 3, 5], [1, 3], [1, 4, 5], [1, 4], [1, 5], [2, 3, 5], [2, 4, > 5], [2, 4], [2, 5], [3, 5]] > > > > But in many cases you can create a lazy code in Python too, even if > that may be harder. So I have tried to create a lazy version for > Python, hoping to speed up the code avoiding the creation and joining > of most/all sublists, but I have failed so far (once I have created a > lazy Python version, I can probably create a short lazy version in D > too, my D libs contain most of itertools module too). > > In my failed attempts I have used chain() to join the sublists, > islice() to slice their items, and iter() to make the management more > uniform when the input seq is a Python list instead of an xrange, etc. Try this: import itertools def ncsub(seq, s = 0): if seq: x = seq[:1] xs = seq[1:] p2 = s % 2 p1 = 1 - p2 return itertools.chain( itertools.imap(lambda ys: x + ys, ncsub(xs, s + p1)), ncsub(xs, s + p2)) else: return [[]] if s >= 3 else [] >>> ncsub(range(1, 4)) >>> list(ncsub(range(1, 4))) [[1, 3]] >>> list(ncsub(range(1, 5))) [[1, 2, 4], [1, 3, 4], [1, 3], [1, 4], [2, 4]] >>> list(ncsub(range(1, 6))) [[1, 2, 3, 5], [1, 2, 4, 5], [1, 2, 4], [1, 2, 5], [1, 3, 4, 5], [1, 3, 4], [1, 3, 5], [1, 3], [1, 4, 5], [1, 4], [1, 5], [2, 3, 5], [2, 4, 5], [2, 4], [2, 5], [3, 5]] From shalupov at diverse.org.ru Thu Jul 31 08:11:34 2008 From: shalupov at diverse.org.ru (Leonid Shalupov) Date: Thu, 31 Jul 2008 16:11:34 +0400 Subject: Continuous integration for Python projects In-Reply-To: References: Message-ID: <4891ABF6.3090906@diverse.org.ru> Hello, Hussein B wrote: > Please correct my if I'm wrong but it seems to me that the major > continuous integration servers (Hudson, CruiseControl, TeamCity ..) > don't support Python based application. > It seems they mainly support Java, .NET and Ruby. > Can I use one of the previous listed servers for Python project? You can use TeamCity. Build and test your project with command-line runner and make sure you've installed modules for reporting tests to TeamCity. http://www.jetbrains.net/confluence/display/TW/Python+Unit+Test+Reporting -- Leonid. From max at alcyone.com Wed Jul 30 02:06:32 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 29 Jul 2008 23:06:32 -0700 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <68448887-4736-4af9-9f27-837bb5312cbd@o40g2000prn.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <89cb8bba-0454-41fc-b35d-1b2d06024a5f@u6g2000prc.googlegroups.com> <12701c01-f851-4632-8e3c-010818a6d0a5@a21g2000prf.googlegroups.com> <7f4a3d37-e551-4e21-b660-3618016cb67b@z6g2000pre.googlegroups.com> <68448887-4736-4af9-9f27-837bb5312cbd@o40g2000prn.googlegroups.com> Message-ID: Carl Banks wrote: > Bull. This is a request, that, if satisfied, would prove that "if x" > is more polymorphic than a simple explicit test. I posed the question > precisely to see if anyone could come up with a use case that shows > this benefit of "if x". Except you're the only one who's not convinced of it, and it's your test, and your rules. So who cares? >> "if x" _is_ a completely simple >> test. Simpler, in fact, than the ones you were advocating. > > It's not explicit. It's not explicit enough for you, yes, that much is obvious. Contests that rely on mind-reading aren't too much fun for anyone involved. > I've explained why I doubt that it helps polymorphism that much: you > almost never see code for which an integer and list both work, so > having the ability to spell a test the same way for both types isn't > useful. If you claim that "if x" does help polymorphism, please tell > me what's wrong with the above analysis. It helps polymorphism for types other that (say) numerics and sequences. There are plenty of container objects for which an "is this non-empty?" test is far simpler a "how many objects are in this container?" test, and several examples have already been given -- as in, O(1) vs. O(n) complexity or worse. You've seem to have even acknowledged this, but are still insisting on continuing the challenge. You're drawing an artificial line in the sand to compare length computation to a more specialized non-emptiness test. (And, as I've pointed out, what happens if you're dealing with a sequence type that _doesn't_ have a length? Then certainly `len(x) != 0` is nonsensical.) Perhaps in the particular use case you're thinking of (numeric types vs. container types), there aren't any good examples. But who cares? Polymorphism applies in more than just this one special case. You're setting up a challenge that isn't very interesting, and which is rigged so that no one can win because you're the one who. So, what's the point? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Can I be your friend / 'Till the end -- India Arie From wmcbrine at users.sf.net Sun Jul 27 21:59:29 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Mon, 28 Jul 2008 01:59:29 GMT Subject: like py2exe, but on a mac References: <18424336.post@talk.nabble.com> Message-ID: <5K9jk.278$rb5.198@trnddc04> On Sun, 13 Jul 2008 00:58:59 +0200, Python.Arno wrote: > http://undefined.org/python/py2app.html py2app bundles Python itself into the app, right? I wonder, is there no way to create an app bundle that relies on the existing installation of Python, since OS X already comes with Python? I have a tiny little program (~20k) that I'd like to make into an app bundle, if only to suppress the console window, and I'd rather not lump in the whole Python interpreter if I can avoid it. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From niklas.norrthon at hotmail.com Wed Jul 23 18:44:02 2008 From: niklas.norrthon at hotmail.com (Niklas Norrthon) Date: Wed, 23 Jul 2008 15:44:02 -0700 (PDT) Subject: Request Help Debugging Program References: <898dfe7a-4133-4337-8243-f4936b8a8092@8g2000hse.googlegroups.com> Message-ID: <864f60ea-39fb-40a6-b3f3-18fc019e193b@m44g2000hsc.googlegroups.com> On 24 Juli, 00:30, Samir wrote: > from math import sqrt > > def findSumOfDivisor(n): [...] > ? ? return sum(divisor) ? ? ? ? ? ? ? ?# return the sum of the > divisors > for i in range(2,10): ? ? ? ? ? ? ? ? ?# loop through integers 2 > through 9 [...] > ? ? ? ? sum = findSumOfDivisor(i) ? ? ?# then find the sum of its divisors [...] > Traceback (most recent call last): > ? File "pe_prob021.py", line 19, in > ? ? sum = findSumOfDivisor(i) ? ? ?# then find the sum of its divisors > ? File "pe_prob021.py", line 12, in findSumOfDivisor > ? ? return sum(divisor) ? ? ? ? ? ? ? ?# return the sum of the > divisors > TypeError: 'int' object is not callable > 'int' object is not callable... hmmm... >>> 42() Traceback (most recent call last): File "", line 1, in 42() TypeError: 'int' object is not callable >>> divisor = 1 >>> sum = 42 >>> sum(divisor) Traceback (most recent call last): File "", line 1, in sum(divisor) TypeError: 'int' object is not callable That must be it. No debugging, just reading the error message and the code... From fred.sells at adventistcare.org Tue Jul 15 15:16:34 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Tue, 15 Jul 2008 15:16:34 -0400 Subject: need ldap windows binary and/or installation help In-Reply-To: Message-ID: <0A53725C4A497848A7B3A0874B259831011B09A4@acesxch01.ADVENTISTCORP.NET> well, duh ;) as my granny used to say "If it had been a snake it would a bit ya". I could probably come up with some lame excuse why I didn't see the msi on osuch.org, but it would be lame and an excuse. anyway. Thanks! > -----Original Message----- > From: python-list-bounces+frsells=adventistcare.org at python.org > [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On > Behalf Of Michael Str?der > Sent: Tuesday, July 15, 2008 2:46 PM > To: python-list at python.org > Subject: Re: need ldap windows binary and/or installation help > > > Tim Golden wrote: > > Sells, Fred wrote: > >> I'm running python 2.5 (or 2.4) in an XP environment. > >> I downloaded and installed the .dll's from > >> OpenLDAP-2.4.8+OpenSSL-0.9.8g-Win32.zip and copied the .dll's in > >> c:/windows/system32 as instructed > >> now I get this error. Is there anyway to avoid building the > >> python_ldap binaries? > > > > Disclaimer. I know nothing about python-ldap. I simply > > Googled for it and came to: > > http://python-ldap.sourceforge.net/download.shtml > > which led me to > > http://www.osuch.org/python-ldap > > from which I downloaded and ran the .msi > > http://www.osuch.org/python-ldap-2.3.5.win32-py2.5.msi > > and Bob was at that point my uncle. > > When reading the original posting I wondered how to make > python-ldap's > web pages even more clear. Thanks that you pointed out that > it seems not > necessary. :-) > > Ciao, Michael. > -- > http://mail.python.org/mailman/listinfo/python-list > From sbcook at gmail.com Tue Jul 29 20:01:35 2008 From: sbcook at gmail.com (SteveC) Date: Tue, 29 Jul 2008 17:01:35 -0700 (PDT) Subject: POP3 - Using poplib only shows the first few hundred messages in the mailbox References: <503aa944-bbf6-4d86-bd98-b58adcd5a2bd@y22g2000prd.googlegroups.com> Message-ID: On Jul 25, 6:07?pm, MRAB wrote: > On Jul 25, 1:18?pm, SteveC wrote: > > > Hello, > > > I am trying to use POP3_SSL class of thepoplibmodule to read email > > from my gmail account. ?I can connect just fine using the example herehttp://www.python.org/doc/lib/pop3-example.html > > > import getpass,poplib > > > M =poplib.POP3('localhost') > > M.user(getpass.getuser()) > > M.pass_(getpass.getpass()) > > numMessages = len(M.list()[1]) > > for i in range(numMessages): > > ? ? for j in M.retr(i+1)[1]: > > ? ? ? ? print j > > > That is the above sample code from the python doc. ?While everything > > works fine, the problem is that when I use the list() function it only > > returns about 400 messages starting from the beginning of my inbox. ?I > > have probably 10,000 emails in my gmail account. ?I don't see any pop3 > > object functions to "move" around the inbox or anything of the like. > > > Could someone point me in the right direction? ?I'm sure there must be > > something simple I am missing. > > That's a lot of emails! :-) > > I had a quick look atpoplib.py and I couldn't see any limit in the > code itself. Perhaps it's the gmail server that's doing it. Can you > retrieve the later messages, eg have you tried M.retr(500)? If you can > then you could just try retrieving messages beyond what M.list() says > until it says there's no such message. Nothing changes when I retrieve the messages it first provides me. What baffles me is I see tons of examples online doing the same thing: http://python.about.com/od/simplerscripts/ss/backup_gmail_3.htm I'm not sure if it could be just a gmail thing either, because then it would seem that this would be a problem with any pop email client. From martin at v.loewis.de Wed Jul 16 01:43:40 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 16 Jul 2008 07:43:40 +0200 Subject: How to figure out if the platform is 32bit or 64bit? In-Reply-To: References: <157c8df1-119b-485b-83ab-3b5dd7b21b1f@25g2000hsx.googlegroups.com> Message-ID: <487D8A8C.7080307@v.loewis.de> >> I need to know if I'm running on 32bit or 64bit ... so far I haven't >> come up with how to get this info via python. sys.platform returns >> what python was built on ... but not what the current system is. >> >> I thought platform.uname() or just platform.processor() would have >> done it, but python returns an empty string on windows. Any ideas? >> > >>>> import sys >>>> hex(sys.maxint) > '0x7fffffff' I don't think that will satisfy the OP. Apparently, he wants to find out that the system is "running on 64bit" even when the interpreter is a 32-bit build executable ("what python was built on"). I don't think Python supports querying that information in general (i.e. "is the microprocessor supporting a 64-bit address space, even if the current process, and perhaps the current operating system only uses a 32-bit address space?") It is possible to answer that question with Python in a platform-specific manner, but the answer is more difficult than a single yes/no: - is the processor capable of executing 64-bit code? - is the operating system kernel operating the processor in 64-bit mode? - does the operating system support 64-bit user-space applications? (in some OSX and Solaris releases, the answer to this question was no, even though the answer to the previous question was yes, IIRC) - does the Python binary support 64-bit mode? - is the Python binary running in 64-bit mode? (again, this may vary from the previous question, in case of fat (universal) binaries) Whether any of these questions are of interest, and which of them the OP wanted to ask, I don't know. Regards, Martin From bj_666 at gmx.net Mon Jul 14 01:06:12 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 14 Jul 2008 05:06:12 GMT Subject: iterator clone References: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> <4f766113-91fc-49eb-9065-dd0feabd9a9a@y38g2000hsy.googlegroups.com> Message-ID: <6e0564F4bvr4U2@mid.uni-berlin.de> On Sun, 13 Jul 2008 18:51:19 -0700, Yosifov Pavel wrote: >> Well, I think Python's iterators, especially the generators, are beautiful. >> More importantly, I think there is no general way to make iterators >> copyable, regardless of the programming language. The problem is that most >> of the useful ones depend on external state. > > Hmm, but tee() de facto do it (clone iterator) and ignore side-effects > of iterator ("external" state). And tee() create independent > **internal** state of iterator (current position). `tee()` doesn't copy the iterator or its internal state but just caches it's results, so you can iterate over them again. That makes only sense if you expect to use the two iterators in a way they don't get much out of sync. If your usage pattern is "consume iterator 1 fully, and then re-iterate with iterator 2" `tee()` has no advantage over building a list of all results of the original iterator and iterate over that twice. `tee()` would be building this list anyway. > But **external** state - is headache of programmer. So, > iterator/generator have to be method for copy itself (the tee() > implementation) or be "re- startable". Why not? Because it's often not possible without generating a list with all results, and the advantage of a low memory footprint is lost. Ciao, Marc 'BlackJack' Rintsch From lotrpy at gmail.com Wed Jul 2 19:36:48 2008 From: lotrpy at gmail.com (lotrpy) Date: Wed, 2 Jul 2008 16:36:48 -0700 (PDT) Subject: Freesoftware for auto/intelligent code completing in Python References: Message-ID: <4b2f5f71-5f82-4dd8-b58c-9723f72504e5@v26g2000prm.googlegroups.com> On 7?1?, ??5?46?, Ali Servet D?nmez wrote: > I don't want to be so mean here, but how hard it could be be writing a > freesoftware which would automatically/intelligently auto complete > Python code? (I mean something that really does the job, like > Microsoft's Visual Studio or Sun's NetBeans or something else, you > name it, but just don't give me PyDev please...) > > This could be an extension, a plugin, an Emacs mode, a new editor or > even a brand new huge all-fancy IDE, I don't care, but what am I > missing here? > > Could someone please point me out something that I'm really missing > which is already present in the wild, otherwise I'd like discuss with > whoever is willing to help me to get this thing done. I made my mind > and I could volunteer to make this happen as thesis project for my > incoming graduation in the next year. > > Regards you all, > Ali Servet D?nmez ulipad clearly deserves a look. good lucky :) http://code.google.com/p/ulipad/ From bearophileHUGS at lycos.com Sun Jul 20 07:08:01 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 20 Jul 2008 04:08:01 -0700 (PDT) Subject: Not entirely serious: recursive lambda? References: <83297e77-ddba-46dc-9f84-2ef3e8f83a32@w7g2000hsa.googlegroups.com> Message-ID: Kay Schluehr: > Sure, use a fixed point combinator. I've just added this recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/576366 Does it work? Bye, bearophile From duncan.booth at invalid.invalid Mon Jul 21 13:59:22 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Jul 2008 17:59:22 GMT Subject: Almost keywords References: <30d1a9c0-331f-4263-9775-a1e639082769@m44g2000hsc.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > A possible way to avoid such bugs is to turn all those names like > "list", "map", "filter", "self", etc into keywords. But this may have > some disadvantages (well, I think I'd like to have "self" as keyword, > seen how all Python books strong suggest to not use a name different > from "self"). I'm not convinced by making 'self' a keyword. Forcing the first argument of a method to be named 'self' fails for many reasons (e.g. classmethod/staticmethod) so I don't really see a benefit to making it special in any way. For the other names though, this would have the advantage of allowing the compiler to optimise access to builtins which should provide a slight speed improvement and I think would also make life easier for some implementations (especially things like 'locals()'). A half-way house would be to generate a warning for any use of a name which masks one of the reserved builtins, but only optimise lookups in scopes where no such masking is seen by the compiler: this would prevent you overriding builtins by injecting a name into the global namespace from outside a module but not otherwise break existing code. Of course any of this would break some existing code and therefore isn't going to happen. From kmtracey at gmail.com Sat Jul 26 09:48:14 2008 From: kmtracey at gmail.com (Karen Tracey) Date: Sat, 26 Jul 2008 09:48:14 -0400 Subject: Stripping parts of a path In-Reply-To: <1217073555.2771.41.camel@localhost.localdomain> References: <1217073555.2771.41.camel@localhost.localdomain> Message-ID: On Sat, Jul 26, 2008 at 7:59 AM, Tim Cook wrote: > Hi All, > > I just ran into an issue with the rstrip method when using it on path > strings. > > When executing a function I have a need to strip off a portion of the > current working directory and add on a path to a log file. Initially > this worked great but then I added a branch in SVN which caused the path > to contain 'LNCCWorkshop'. The rstrip() then began removing the > characters 'shop' leaving an incorrect path to the log file. When I > hard coded this path it worked okay but then did the same thing later in > the file when I needed to point to a database. The code worked fine with > a different path. Here are some code fragments. > > > logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/at_build_errors.log' > > this worked when the path was: > /home/tim/ref_impl_python/TRUNK/oship/src/oship/atbldr > > the code above returns: > /home/tim/ref_impl_python/TRUNK/oship/log/at_build_errors.log > > but when I tried a branches version that has the path: > /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/src/oship/atbldr > > it SHOULD return: > > /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/log/at_build_errors.log > > but I get: > /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log > > logfile=os.getcwd() > print logfile is correct; but when I add the .rstrip('src/oship/atbldr') > it also strips the 'shop' off of LNCCWorkshop and returns > /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log > > I had two other people looking at this as we did troubleshooting and we > could not determine the cause. It is repeatable with this path name. > In resolution I renamed the branch to just LNCC and it works fine. > > Thoughts? > I think rstrip does not do what you think it does. From: http://docs.python.org/lib/string-methods.html "The chars argument is not a suffix; rather, all combinations of its values are stripped" Thus, since the characters p,o,h, and s are all in the argument you supplied to rstrip, they are removed, then stripping is stopped at the k because that is not in the chars arg you supplied. To do what you really want I think you need to use rfind/rindex to locate the last occurrence of the substring and then truncate the string yourself. Karen -------------- next part -------------- An HTML attachment was scrubbed... URL: From goldtech at worldpost.com Sun Jul 13 18:17:12 2008 From: goldtech at worldpost.com (goldtech) Date: Sun, 13 Jul 2008 15:17:12 -0700 (PDT) Subject: SAX XML Parse Python error message References: <487A23A5.7000905@behnel.de> <1c87a4e2-7c66-4ced-8622-b6eebc8664bb@i76g2000hsf.googlegroups.com> Message-ID: <4a19c059-0999-47fa-8ca2-c55b5d09c106@l42g2000hsc.googlegroups.com> On Jul 13, 5:30 pm, Waldemar Osuch wrote: > On Jul 13, 3:00 pm, goldtech wrote: > > > I would be grateful for support with the code I cited. It's not long > > and fairly standard. I'm sure my error(s) would be glaring to more > > experienced coders. I appreciated the "heads-up" about other options > > but I would be grateful for help getting this code to run. Thanks > > Initialize self.coodinates in the __init__ > or indent the "print self.description, str(self.coordinates)" > one more level. > You have to remember that "endElement" is being called on the end > of every element. In your case it is called by but > the parser did not see yet. > > In "def characters" you should be collecting the "ch" in a buffer. > It may be called multiple times for the same element. > Something like "self.description += ch" would do for starters. > > Also you do not need to convert self.coordinates to string before > printing, it is already a string and even if it was not "print" > would convert it for you. > > That's it for now :-) Others may spot more issues with > your code or my response. > On the positive side I really liked how you asked > the question. There was a short runnable example and traceback. > > Waldemar Putting the print statements were they won't cause trouble and using ...+= ch (vs. only =) in the character section fixed it: ... def endElement(self, name): ... if name == 'description': self.isdescriptionElement= 0 print self.description if name == 'coordinates': self.iscoordinatesElement = 0 print self.coordinates ... I need to read your answer again carefully - I don't know if what I did is best - but it seemed to fix it. Thank you for the clear and cogent answer. Lee G. From simon at brunningonline.net Sun Jul 6 09:12:32 2008 From: simon at brunningonline.net (Simon Brunning) Date: Sun, 6 Jul 2008 14:12:32 +0100 Subject: Recursive wildcard file search In-Reply-To: References: <496954360807031353n4f91f691recb330f7350cbf70@mail.gmail.com> Message-ID: <8c7f10c60807060612o39622188ld75d2bb0794394a8@mail.gmail.com> 2008/7/4 Gerhard H?ring : > Robert Dailey wrote: >> Is there a way to perform a recursive file search using wildcards in >> python 3.0b1? [...] > > glob.glob() or glob.iglob(). glob's not recursive AFAIK. This recipe probably still works under Pythion 3K, though: -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From aaron.hildebrandt at gmail.com Wed Jul 23 14:34:32 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 23 Jul 2008 11:34:32 -0700 (PDT) Subject: Using variables across modules Message-ID: <855136ce-6c70-40ac-a462-dc0bbfa1fc3a@b2g2000prf.googlegroups.com> I'm having some trouble understanding how Python handles variables across multiple modules. I've dug through the documentation, but I still find myself at a loss. When you import a module, are you creating an instance of the variables within? For instance, if I have one file, "variables.py", which contains "myvar = 0", and I import it into both "foo.py" and "bar.py" with the line "from variables import *", and then set myvar in "foo.py" and "bar.py" to different values, will each file have a different value for myvar? If so, how can I ensure that a change to myvar in "bar.py" is reflected by "foo.py"? Or am I completely off base? From bj_666 at gmx.net Mon Jul 21 04:26:45 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 21 Jul 2008 08:26:45 GMT Subject: What is the role of python2.6 and C++? References: Message-ID: <6eivi5F6vgp3U1@mid.uni-berlin.de> On Mon, 21 Jul 2008 16:17:00 +0800, ?? wrote: > I'm confused about the motivation of releasing python2.6 and python3.0 > at the *same* time. IMO, 2.6 should be compatible with 2.5 while 3.0 > is new style python. That's how it is. 2.6 is backwards compatible with 2.5. > [?] But even without the intermediate version 2.6, project transformation > with be smooth enough, and then 2.5, 2.6 will be replaced by 3.0. I will > not spend any time on studying 2.6. So why does python development team > put many efforts on 2.6? What is the role of 2.6? It's a version that makes the transition smoother. You really should take that "detour" via 2.6. There should be some of the changes from 3.0 in 2.6 that don't mess with backwards compatibility, and a script that tries to automate the conversion from 2.6 to 3.0. This spares a lot of work when porting to 3.0. Ciao, Marc 'BlackJack' Rintsch From roy at panix.com Sun Jul 20 20:37:23 2008 From: roy at panix.com (Roy Smith) Date: Sun, 20 Jul 2008 20:37:23 -0400 Subject: Python Written in C? References: Message-ID: In article , Mensanator wrote: > C isn't a high level language, that's part of its problem. C is the highest level assembler language I've ever used. And I've used a few. It really is cool that you can add two 32-bit integers and not have to worry about all those carry bits. From xahlee at gmail.com Fri Jul 11 02:32:27 2008 From: xahlee at gmail.com (xahlee at gmail.com) Date: Thu, 10 Jul 2008 23:32:27 -0700 (PDT) Subject: Elisp Lesson on file processing (make downloadable copy of a website) References: <7095dc5e-3008-45b8-8665-e746bff84dd6@m36g2000hse.googlegroups.com> Message-ID: <0219b84b-d524-4b3e-9031-ac399be322da@m3g2000hsc.googlegroups.com> Xah Lee wrote: ? ... emacs program and tutorial that does archiving a website for offline reading. (See http://xahlee.org/emacs/make_download_copy.html ) ? Sashi wrote: ?Why not use wget or curl?? The Emacs lisp program makes a archive of parts of website you own, so that readers of your website can click download to read it offline. For wget and curl, i have some tips here: http://xahlee.org/UnixResource_dir/unix_tips.html Xah ? http://xahlee.org/ ? From bearophileHUGS at lycos.com Wed Jul 16 12:10:44 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 16 Jul 2008 09:10:44 -0700 (PDT) Subject: Regular expression References: Message-ID: <47610734-5b49-4fd2-98ce-70976c257d14@d77g2000hsb.googlegroups.com> On Jul 16, 4:14 pm, Fredrik Lundh wrote: > Beema shafreen wrote: > > How do I write a regular expression for this kind of sequences > > > >gi|158028609|gb|ABW08583.1| CG8385-PF, isoform F [Drosophila melanogaster] > > MGNVFANLFKGLFGKKEMRILMVGLDAAGKTTILYKLKLGEIVTTIPTIGFNVETVE > > line.split("|") ? > > it's a bit hard to come up with a working RE with only a single sample; > what are the constraints for the different fields? is the last part > free form text or something else, etc. > > have you googled for existing implementations of the format you're using? That'a a fasta file, so for the header line this is enough: [part.strip() for part in line.split("|")] But better is to use the biopython libs that already perform all such things better. Bye, bearophile From wuwei23 at gmail.com Thu Jul 31 01:49:14 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 30 Jul 2008 22:49:14 -0700 (PDT) Subject: Insert character at a fixed position of lines References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> <7895c8b2-fa01-483c-8ba9-d90975ea688d@o40g2000prn.googlegroups.com> <8b0f4fe2-d8ab-4230-9032-ccd02878d349@v39g2000pro.googlegroups.com> Message-ID: <3ff98b50-ec9b-40d2-a9a5-235926fa1c9e@w39g2000prb.googlegroups.com> On Jul 30, 10:43?pm, Lie wrote: > Lessons learned, should test codes even if you thought it seemed > trivial. And I learned I should always make sure to cut&paste the right example :) From henrik at chamalulu.com Wed Jul 2 05:40:57 2008 From: henrik at chamalulu.com (chamalulu) Date: Wed, 2 Jul 2008 02:40:57 -0700 (PDT) Subject: Attribute reference design References: <6cvlk4F3s90U1@mid.uni-berlin.de> <486b38b6$0$7210$426a74cc@news.free.fr> Message-ID: <787ce82d-4e39-4c34-b91f-bbabd8c3bf14@f63g2000hsf.googlegroups.com> On Jul 2, 10:13 am, Bruno Desthuilliers wrote: > Nope. The wrapping happens at lookup time, thru the descriptor protocol > (the same thing that gives support for properties). Aha, I should read up on that. > Help on built-in function dir in module __builtin__: So, the dir function is a little more helpful than I thaught. I checked instance.__dict__ now instead of dir(instance). No methods. It's getting clearer. Thank you. I think you've provided me with a good reason for class instances to delegate attribute references to the class if class instance doesn't contain the attribute. Diez, Gary, Bruno; Thanks for your help. /Henrik From kyosohma at gmail.com Thu Jul 3 09:40:37 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 3 Jul 2008 06:40:37 -0700 (PDT) Subject: wxPython: How can I get window's HANDLE in wxPython. References: Message-ID: On Jul 2, 8:40?pm, "Leo Lee" wrote: > I need a window's handle to be passed to external c++. > Thanks in advance Are you talking about a wxPython wx.Window object or an external window handle? If the latter, then I recommend asking about that on the PyWin32 user's group. Otherwise, follow Paul's suggestion. Mike From ladasky at my-deja.com Sun Jul 20 03:52:13 2008 From: ladasky at my-deja.com (John Ladasky) Date: Sun, 20 Jul 2008 00:52:13 -0700 (PDT) Subject: Genetic programming: pygene, pygp, AST, or (gasp) Lisp? Message-ID: <7bfb3c41-b08b-49dc-9711-6e39a4667db2@b1g2000hsg.googlegroups.com> Hi folks, I've played around with neural nets for a while. I wrote my own slow, pure-Python NN package. I knew that there were Python NN packages out there -- but I couldn't really understand their features and documentation at first, not without some hands-on experience. I haven't yet solved any interesting problems with NN, but I learned a lot about both NN and about Python along the way. One of the unpleasant things I learned about NN was their propensity for becoming trapped in local minima. I also learned about overfitting, wasting many hours of CPU time in the process. In short, simple neural nets have disappointed me. I have now asked myself: wouldn't it be cool if, when you ceased to make progress on an optimization algorithm, you could divide your data set with an "if" statement, which would evolve a useful dividing line through your data set -- and then, develop divergent solutions to explain each subset better? In mathematical terms: Round 1 of evolutionary programming leads to a single, but sub-optimal solution, probably a solution in a local minimum: b = f(a) Round 2 would start by elaborating the solution of round 1, adding a condition that is initially meaningless: if disc(a) < c: b = f1(a) else: b = f2(a) Initially, f1() = f2() = the original f(). Therefore, the output of the starting state of round 2 will be identical to the output of the final state of round 1, regardless of the initial state of the discriminant function, disc(). But then, f1(), f2(), and disc() will all be permitted to evolve. This may provide a chance to "pop out" of the local minimum, without sacrificing any of the progress made in defining the solution of round 1. Of course, f(), f1(), f2(), and disc() could be complex functions. They would best be described with parse trees, which I've just discovered (I'm not formally trained in computer science). Some reading has led me to conclude that what I'm proposing is basically genetic programming. http://en.wikipedia.org/wiki/Genetic_programming I've tried my hand at this already in Python. I have devised a code tree class, which functions as a parse tree for functions and also handles multiple-line statements. I've tried cobbling together program strings from code trees, and then using the exec() function to run them. This is all very cool, but I'm finding it VERY cumbersome! As with neural nets, I know that there are genetic programming packages offered for Python: http://www.freenet.org.nz/python/pygene/ http://sourceforge.net/projects/pygp/ But I can't really understand what they do -- both of these packages are, alas, minimally documented. Is anyone out there using either of these? I can't tell whether they will implement algorithms of the type I've described here. Specifically, I don't know if conditional statements are included in their repertoire. Also, Pygene SEEMS to have a bent toward Boolean logic. I'm working with analog data, and I want complex, nonlinear functions. So, as with neural nets, shall I once again proceed on my own? There is apparently a layer in the Python interpreter at which code is represented as an abstract syntax tree (AST). http://docs.python.org/lib/ast.html Why not do genetic programming directly on Python code? Maybe my code tree data structure is redundant to something which already exists? But apparently Python's "_ast" module offers only one-way access -- it will generate an AST from a piece of code, but you can't modify an AST, and turn it back into executable code? I would definitely need this latter feature. ALTERNATELY -- and I don't mention this to start a flame war -- in pondering this problem I've noticed the frightening fact that Lisp seems set up to handle genetic programming by design. The s- expression syntax IS essentially a parse tree. Now, I've spent a few hours with Lisp so far, and I can't make it do much of anything -- but I DO see how Lisp could be helpful. Still, I'm reluctant to pursue a language I don't know, and which I'm finding much harder to grasp than any language I've tried before. Is there a way to interface Lisp to Python, so that I can do all the interface programming in the language I already know best -- and just do the genetic parts in Lisp? I haven't seen exception handling in Lisp, a feature I've come to love in Python. Since it is fairly easy for a randomly-generated program to generate illegal output (I already know this from my initial experiments in Python), I don't think I can live without exception handling. I also think that Python has a higher-level understanding of a variable's "type" or an object's "class" than Lisp does -- if I'm hacking at a parse tree and I want to minimize syntax errors, I need to know more than the fact that an element in an expression is an atom or a list. Producing human-readable code from my genetic programming search would be a great bonus -- and for me, at this moment, this seems to mean Algol-style syntax. (Sigh.) But it's not a requirement. Thanks for your advice! From cokofreedom at gmail.com Mon Jul 14 03:16:17 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 14 Jul 2008 00:16:17 -0700 (PDT) Subject: Beginner Question : Iterators and zip References: <99af6877-2381-42d7-b070-aba15a4b4c9f@i76g2000hsf.googlegroups.com> Message-ID: > > zip(*vec_list) will zip together all entries in vec_list > Do be aware that zip stops on the shortest iterable. So if vec[1] is > shorter than vec[0] and matches otherwise, your output line will be > truncated. Or if vec[1] is longer and vec[0] matches as far as it goes, > there will be no signal either. > Do note that from Python 3.0 there is another form of zip that will read until all lists are exhausted, with the other being filled up with a settable default value. Very useful! From circularfunc at gmail.com Sun Jul 27 08:13:36 2008 From: circularfunc at gmail.com (ssecorp) Date: Sun, 27 Jul 2008 05:13:36 -0700 (PDT) Subject: x*x if x>10 Message-ID: <59b5d431-8218-4a07-a9d7-5357f1c474f8@f36g2000hsa.googlegroups.com> I have seen somewhere that you can write something like: x*x if x>10 but exactly that doesn't work and I can't get any variation to work. it is possible to nest with an else too. how do you write it? and also, is it idiomatic? doesn't seem to add functionality, just another way of doing the same thing which is quite unpythonic but I remember reading it was added because it helped simplify the expression of a certain type of operation. From bulg at ngs.ru Sun Jul 13 02:53:46 2008 From: bulg at ngs.ru (Yosifov Pavel) Date: Sat, 12 Jul 2008 23:53:46 -0700 (PDT) Subject: iterator clone Message-ID: <201d4926-c53a-49d9-811c-652f9166eb2a@a1g2000hsb.googlegroups.com> Whats is the way to clone "independent" iterator? I can't use tee(), because I don't know how many "independent" iterators I need. copy and deepcopy doesn't work... --pavel From carsten.haese at gmail.com Wed Jul 23 16:15:48 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Wed, 23 Jul 2008 16:15:48 -0400 Subject: Raw Strings (I Think) In-Reply-To: References: Message-ID: Lanny wrote: > I've used glob.glob to get a list of files in a directory > and now I want to use os.system to execute one of > those files, the problem is that python automatically > puts a escape charater infront of the back slashes No, it doesn't. Instead of guessing what the cause might be, please show us your code and show us the error message you're getting, so that we can determine what the cause really is. -- Carsten Haese http://informixdb.sourceforge.net From hiursvapsisnowhere at gmail.com Wed Jul 23 08:31:04 2008 From: hiursvapsisnowhere at gmail.com (SvaPs) Date: Wed, 23 Jul 2008 05:31:04 -0700 (PDT) Subject: How to replace the values with keys ? References: <92df0f7c0807222130n382edf5di8c7124690f3dffa7@mail.gmail.com> Message-ID: <4c61674b-c81e-427a-a916-4aafbd645b7c@u12g2000prd.googlegroups.com> Hi all.., I tried with this.. def multiple_replace(text,adict): rx=re.compile('|'.join(map(re.escape,adict))) def one_xlat(match): return adict[match.group(0)] return rx.sub(one_xlat,text) print multiple_replace(text,adict) I am thrown with a error: Traceback (most recent call last): File "", line 1, in File "", line 2, in multiple_replace TypeError: argument 2 to map() must support iteration I would be grateful for any comments.. Thankin in advance' GraPs. Fredrik Lundh wrote: > "Graps Graps" wrote: > > > Text2 is a python dictionary containing data as > > > > {0: 'a', 1: 'b', 2: 'c'...} > > > > now I want the data in text1 to be replaced with the keys, say like > > > > 0 1 > > 0 2 > > 0 3 > > 0 6 > > 1 2... so on.. > > someone asked a very similar question not long ago, so maybe you're > really supposed to figure this out yourself. I'm sure your teacher > won't kill you if you ask for a hint. > > (if you asked me for a hint, I'd tell you to look for questions about > dictionaries in the mailing list archives). > > From Russ.Paielli at gmail.com Mon Jul 28 00:35:08 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 21:35:08 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> <6a5506b1-632e-4bf6-b0ce-4d51d1751aa9@i24g2000prf.googlegroups.com> <8b4b11c3-e306-4fe7-82d1-0a948c725f2f@r15g2000prd.googlegroups.com> <239a084f-b73d-4c20-aaaf-bbd05d452638@a2g2000prm.googlegroups.com> Message-ID: On Jul 27, 8:38 pm, alex23 wrote: > On Jul 28, 4:59 am, "Russ P." wrote: > > > On Jul 27, 3:11 am, alex23 wrote: > > > > On Jul 27, 4:26 pm, "Russ P." wrote: > > > > > On Jul 26, 11:18 pm, Terry Reedy wrote: > > > > > The use of '.' has been suggested before and rejected. > > > > > Where and why? > > > > Google is your friend:http://mail.python.org/pipermail/python-3000/2006-April/000793.html > > > What Guido rejected there is most certainly *not* > > what I suggested. I agree with Guido on that one. > > Orly? > > Ian Bicking wrote: "I propose that the self argument be removed from > > method definitions." > > Philip Eby suggested: > > > def .aMethod(arg1, arg2): > > return .otherMethod(arg1*2+arg2) > > Guido shot them all down by stating: > > > [Y]ou're proposing to hide a > > fundamental truth in Python, that methods are "just" functions whose > > first argument can be supplied using syntactic sugar > > Any more reading comprehension we can do for you? Dude, I agree with Guido completely on this one. You seem to be clueless about the issue here. You're the one with the reading comprehension problem. Please quit wasting my time with your irrelevant crap. From manuhack at gmail.com Wed Jul 23 16:09:28 2008 From: manuhack at gmail.com (Manu Hack) Date: Wed, 23 Jul 2008 16:09:28 -0400 Subject: fromfile error on windows, not mac In-Reply-To: References: <5a4f9f3c-e485-4a9c-9bea-0ab15e1b3994@k13g2000hse.googlegroups.com> Message-ID: <50af02ed0807231309p2f7b1333sf45f96a9f082d8f0@mail.gmail.com> On Wed, Jul 23, 2008 at 3:37 PM, jadamwil wrote: > I found the problem: I thought it was opening in binary mode on BOTH > windows and the mac, but on windows I passed "rb" with double quotes, > not 'rb' with single quotes to the open file function. Changing it to > 'rb' fixed it. > > by the way, anyone could explain why changing to single quote makes a difference? >>> "rb" == 'rb' True -------------- next part -------------- An HTML attachment was scrubbed... URL: From adamtaunowilliams at gmail.com Tue Jul 22 13:31:03 2008 From: adamtaunowilliams at gmail.com (whitemice) Date: Tue, 22 Jul 2008 10:31:03 -0700 (PDT) Subject: Authentication for XML-RPC Calls Message-ID: <3e4258ac-40d8-485d-ba65-39d343b9561d@2g2000hsn.googlegroups.com> The only documentation regarding doing authentication for XML-RPC I can find is - "Both the HTTP and HTTPS transports support the URL syntax extension for HTTP Basic Authentication: http://user:pass at host:port/path. The user:pass portion will be base64-encoded as an HTTP `Authorization' header, and sent to the remote server as part of the connection process when invoking an XML-RPC method. You only need to use this if the remote server requires a Basic Authentication user and password." - from http://docs.python.org/lib/module-xmlrpclib.html Is this really the only way to do authentication for XML-RPC calls? Like this: server = xmlrpclib.Server('http://adam:fred123 at localhost/zidestore/so/ adam/' This works, but is pretty ugly. Is there no way to setup the authentication through properties (like in most XML-RPC bindings), like: server = xmlrpclib.Server('http://localhost/zidestore/so/adam/' server.Username = 'adam' server.Password = 'fred123' From fredrik at pythonware.com Wed Jul 23 17:11:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 23:11:11 +0200 Subject: Taking the floating point distances and plotting histogram In-Reply-To: <73045cca0807231402m1c439414s516e5409a704506f@mail.gmail.com> References: <73045cca0807231402m1c439414s516e5409a704506f@mail.gmail.com> Message-ID: aditya shukla wrote: > I have a program whose output is stored in a text file , say test.txt > eg. > 0\9\10\11|0.50|c:\windows\apppatch/AcLayers.dll > 0\9\10\11|0.50|c:\windows\apppatch/AcRedir.dll > 0\9\10|0.66|c:\windows\apppatch/AcSpecfc.dll > 0\9|0.83|c:\windows\apppatch/iebrshim.dll > > After reading this text file i need to extract the float point values > from each line ie , 0.50,0.50,0.66.0.83 respectively > in this case, till the end of the file is reached and then i need to > plot a histogram based on these values . Extracting is easy; you can do something like data = [] for line in open("test.txt"): line = line.split("|") data.append(float(line[1])) (or maybe use the csv module with a custom separator) Plotting is a bit different -- there are many ways to do that, depending on where and how you want to display that histogram (on a website, in a window on your machine, in a PDF file, ...), but most solutions require additional libraries. Here's one such library: http://matplotlib.sourceforge.net/ From dstromberglists at gmail.com Wed Jul 9 02:46:09 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Wed, 09 Jul 2008 06:46:09 GMT Subject: how to remove oldest files up to a limit efficiently References: <1eb168ac-fc63-4724-8604-45e995a06b51@s50g2000hsb.googlegroups.com> Message-ID: On Tue, 08 Jul 2008 15:18:23 -0700, linuxnow at gmail.com wrote: > I need to mantain a filesystem where I'll keep only the most recently > used (MRU) files; least recently used ones (LRU) have to be removed to > leave space for newer ones. The filesystem in question is a clustered fs > (glusterfs) which is very slow on "find" operations. To add complexity > there are more than 10^6 files in 2 levels: 16? dirs with equally > distributed number of files inside. > > My first idea was to "os.walk" the filesystem, find oldest files and > remove them until I reach the threshold. But find proves to be too slow. > > My second thought was to run find -atime several times to remove the > oldest ones, and repeat the process with most recent atime until > threshold is reached. Again, this needs several walks through the fs. > > Then I thought about tmpwatch, but it needs, as find, a date to start > removing. > > The ideal way is to keep a sorted list if files by atime, probably in a > cache, something like updatedb. > This list could be also be built based only on the diratime of the first > level of dirs, seek them in order and so on, but it still seems > expensive to get his first level of dir sorted. > > Any suggestions of how to do it effectively? os.walk once. Build a list of all files in memory. Sort them by whatever time you prefer - you can get times from os.stat. Then figure out how many you need to delete from one end of your list, and delete them. If the filesystem is especially slow (or the directories especially large), you might cluster the files to delete into groups by the directories they're contained in, and cd to those directories prior to removing them. From jeffrey at fro.man Fri Jul 11 11:23:24 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Fri, 11 Jul 2008 08:23:24 -0700 Subject: read file into list of lists References: <48775fee$0$928$ba4acef3@news.orange.fr> Message-ID: Laurent Rahuel wrote that antar2 wrote: >> following text for example should be considered as a list of lists (3 >> columns and 3 rows), so that when I make the print statement list[0] >> [0], that the word pear appears >> >> >> pear noun singular >> books nouns plural >> table noun singular File objects are themselves iterable, returning one line per iteration. So a simple approach is: >>> table = [line.split() for line in open('sentences.txt')] >>> table[0][0] 'pear' Jeffrey From banuchandar46 at gmail.com Sat Jul 19 18:35:30 2008 From: banuchandar46 at gmail.com (Prabhu) Date: Sat, 19 Jul 2008 15:35:30 -0700 (PDT) Subject: Free online computer studies Message-ID: <4fee65d8-e4c5-4d51-abce-89d813e30b61@v1g2000pra.googlegroups.com> Free online computer studies super visualize study get all courses,hurry up limited offer http://vijaydollars.blogspot.com/ http://friendfinder.com/go/g981367 http://amigos.com/go/g981367 From kylotan at gmail.com Wed Jul 23 08:08:58 2008 From: kylotan at gmail.com (Ben Sizer) Date: Wed, 23 Jul 2008 05:08:58 -0700 (PDT) Subject: Undefined calling conventions in Python.h References: <8ff0448e-62d3-4d2c-8aed-8d8d3e301737@y38g2000hsy.googlegroups.com> <2f4d1ef0-3f9b-4351-84c4-5fbdb5d513ee@l64g2000hse.googlegroups.com> Message-ID: <216dcee8-ad3d-4ae1-ac4a-4f4819775c7e@d1g2000hsg.googlegroups.com> On Jul 23, 11:43?am, Jaco Naude wrote: > What Visual C++ is doing is that it is looking for mangled names since > it does not know the DLL contains C functions. I've managed to work > around this by declaring the Python functions as follows before using > them in the C++ application side: > > extern "C" > { > ? ? void Py_Initialize(void); > > } You should put the extern block around the #include call rather than individual functions, as surely the C calling convention should apply to everything within. > It is probably more of a C++ question it turns out, but I would think > that someone in the Python group would use the Python DLL in C++. More of a Visual C++ question specifically, since the __clrcall prefix is a MS specific extension (http://msdn.microsoft.com/en-us/library/ ec7sfckb(VS.80).aspx). If you're not using managed code in your app, disable it in the project/build options. If you are, then perhaps you just need to specify that you're not with this DLL, though I've never had to deal with anything like that myself. -- Ben Sizer From Russ.Paielli at gmail.com Sun Jul 27 14:59:05 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 11:59:05 -0700 (PDT) Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <874p6fzkkh.fsf@physik.rwth-aachen.de> <488898a5$0$12027$426a34cc@news.free.fr> <87zlo747gv.fsf@physik.rwth-aachen.de> <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <2dc64941-11f0-4269-b4b2-46cb9c8080e5@a3g2000prm.googlegroups.com> <488B9135.3010308@ncf.ca> <89eff98f-0e79-4c4e-956c-389e48b4abb2@i20g2000prf.googlegroups.com> <6a5506b1-632e-4bf6-b0ce-4d51d1751aa9@i24g2000prf.googlegroups.com> Message-ID: <8b4b11c3-e306-4fe7-82d1-0a948c725f2f@r15g2000prd.googlegroups.com> On Jul 27, 3:11 am, alex23 wrote: > On Jul 27, 4:26 pm, "Russ P." wrote: > > > On Jul 26, 11:18 pm, Terry Reedy wrote: > > > The use of '.' has been suggested before and rejected. > > > Where and why? > > Google is your friend:http://mail.python.org/pipermail/python-3000/2006-April/000793.html What Guido rejected there is most certainly *not* what I suggested. I agree with Guido on that one. From Russ.Paielli at gmail.com Mon Jul 28 00:27:19 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Sun, 27 Jul 2008 21:27:19 -0700 (PDT) Subject: Attack a sacred Python Cow References: <7862111b-4e1f-47e8-953d-c853fcf8d4c3@k36g2000pri.googlegroups.com> <05a69284-a560-46fc-9106-5a9b3c105e8a@m73g2000hsh.googlegroups.com> <87fxpxw0ku.fsf@physik.rwth-aachen.de> <87k5f8afjl.fsf@physik.rwth-aachen.de> <336aa69a-9a05-42bd-a961-bf44182dec5a@a3g2000prm.googlegroups.com> <009c2b11$0$20302$c3e8da3@news.astraweb.com> <488ceae5$0$11227$426a34cc@news.free.fr> Message-ID: On Jul 27, 6:21 pm, Terry Reedy wrote: > Russ P. wrote: > > On Jul 27, 12:39 pm, Bruno Desthuilliers > > All I am suggesting is that the programmer have the option of > > replacing "self.member" with simply ".member", since the word "self" > > is arbitrary and unnecessary. > > I presume you are proposing the opposite also, that ".member" would > internally be expanded to "self.member". > > As I said before, that, or something near like it (it is hard to exactly > compare underspecified proposals) has be suggested and rejected, even if > someone gave you not the exact reference. For one thing, as Guido > noted, a single . can be hard to see and easy to miss, depending on > one's eyesight, environmental lighting, and exact display medium, > including font. > > I suspect Guido's other reasons have been covered, but I do not want > misquote him. I will leave you to search the pydev list archives. > > > Otherwise, everything would work *EXACTLY* the same as it does now. > > If I understand you, that would mean that .attribute would raise > NameError: name 'self' is not defined > if used anywhere where 'self' was not defined. After thinking about this a bit more, let me try to be more specific. Forget about the empty first argument and the "." for the first argument. Just let the first argument be "self" or anything the programmer chooses. No change there. If access is needed to "self.var", let it be accessable as either "self.var" or simply ".var". Ditto for "self.method()", which would be accessible as ".method()". In other words, wherever ".var" appears, let it be interpreted as ".var". If the first argument is "self", then it should be equivalent to "self.var". If the first argument is "snafu", then ".var" should be equivalent to "snafu.var". I can't think of any technical problem with this proposal, but I may be overlooking something. If so, please let me know. This proposal should be relatively easy to implement, and it would reduce code clutter significantly. (I could probably write a pre- processor to implement myself it in less than a day.) From fredrik at pythonware.com Thu Jul 24 17:20:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 24 Jul 2008 23:20:52 +0200 Subject: Neat way to get rid of [" "] in sys.argv[n:] returns In-Reply-To: References: Message-ID: korean_dave wrote: > python test.py "testparameter" > > I get this output: > > ------------- > ['testparameter'] > ---------------- > > Is there a way to neatly, in one call to the parameter, to get rid of > the [' and '] without bothering to replace() '[ with "" and replace() > '] with ''? Since you're using slicing instead of indexing, you're printing a list, not a single string. There is no '[ or ]' in the string itself, and no need to replace it with anything. To print just that string, do print sys.argv[1] # fetch item instead of print sys.argv[1:] # slice list I suggest working through a tutorial or two. Pay special attention to the difference between an object's value and the various ways that value can be output. From joe at goldthwaites.com Thu Jul 3 12:00:52 2008 From: joe at goldthwaites.com (Joe Goldthwaite) Date: Thu, 3 Jul 2008 09:00:52 -0700 Subject: SQLite and Python 2.4 In-Reply-To: Message-ID: <200807031600.m63G0tJ6023817@vm-mailout1.fpw.ch> Thanks Guilherme. That helped. I guess I was thinking that pysqlite would automatically come with some version of sqlite. The fact that it doesn't is what was causing me to get the strange results. I downloaded the Windows version of the SQLite3.dll. I didn't know where to put it so I first put it in its own directory and tried to register it. That didn't work so I just moved it to the pysqlite directory in site-packages. That did the trick. It took way longer than I thought to figure out how this stuff worked. Here's an example putting it all together. It's Windows specific but only for the part that finds where the cookies.sqlite file is. Maybe it will save someone else the time. import ConfigParser from pysqlite2 import dbapi2 as sqlite import os def GetFirefoxCookies(domain, d): """This function gets all FireFox 3 cookies for the passed in domain and adds them to the dict object""" # Get the Firefox data path FireFoxPath = os.environ['AppData'] + '\Mozilla\Firefox' # use the FireFoxPath to load up the profies.ini file iniFileName = r'%s%s' % (FireFoxPath, r'\profiles.ini') # use the ConfigParser module to load in the contents of the ini file parser = ConfigParser.ConfigParser() parser.read(iniFileName) # I'm just getting the path from the [Profile0] section since this code # is only running on my system. For a production system, you'd probably # want to look for the section with "default=1". path = parser.get('Profile0','Path') # with all that, we can finally find the cookies.sqlite file dbfile = '%s\%s\%s' % (FireFoxPath, path.replace('/','\\'), 'cookies.sqlite') # Next create an sqlite connection object and load up the cookies table conn = sqlite.connect(dbfile) # get a cursor object c = conn.cursor() # get the name and cookie values c.execute("SELECT name, value FROM moz_cookies WHERE host = '%s'" % domain) # loop through the cookies and add their key and values to the # dictionary. for row in c.fetchall(): d[row[0].encode('utf-8')] = row[1].encode('utf-8') if __name__ == '__main__': domain = 'localhost' cookiedict = {} GetFirefoxCookies(domain, cookiedict) print cookiedict -----Original Message----- From: Guilherme Polo [mailto:ggpolo at gmail.com] Sent: Tuesday, July 01, 2008 6:15 PM To: joe at goldthwaites.com; python-list at python.org Subject: Re: SQLite and Python 2.4 On Tue, Jul 1, 2008 at 9:51 PM, Joe Goldthwaite wrote: > I'm confused. (Not a new experience). I've got a web application running > under Zope. I use the Wing IDE for testing and debugging. When trying to > recreate problems that come up on the web, I wrote some little routines that > pull my cookies out of the Firefox cookies.txt file into my code. That way, > I'm working with all the same options under Wing that my app uses when > running under Zope. > > That's worked great until I upgraded to Firefox 3. Firefox 3 moved their > cookies from cookies.txt to cookies.sqlite. I haven't worked with SQLite at > all so I started searching for examples and found this; > > import sqlite3 > conn = sqlite3.connect('test.db') > c = conn.cursor() > rows = c.execute('SELECT * from somefile') > > Looks simple enough but I can't get it to work. Here are my questions; > > 1. How do you get sqlite3 for Python 2.4? I can't find it anywhere. You need sqlite itself (www.sqlite.org) and bindings, pysqlite 2 (http://oss.itsystementwicklung.de/trac/pysqlite/) or aspw (http://code.google.com/p/apsw/) > > 2. If sqlite3 is only for Python 2.5, does sqlite2 work the same way? > You are confused, yes. The sqlite3 package that comes with python2.5 is actually pysqlite2, which interfaces with sqlite3. Also, sqlite3 and sqlite2 files format are not compatible. > 3. Looking at the cookies.sqlite file, I see some text right at the top > "SQLite format 3". Does that mean that I need to use sqlite3? Yes > > I kind of got the above example using pysqlite2.4.1 for python 2.4. I get > through the part where I create the connection object but the resulting > object doesn't have a cursor method. I thought that maybe it wasn't > recognizing the cookies.sqlite file as a SQLite database so I tried the same > code giving it a junk text file instead and it behaved the same way. Since > I didn't get an error message, I'm thinking that I've got the wrong version > for the Firefox cookies.sqlite file. > > I don't have a clue as to where else to look to trace it down. I'm hoping > that someone here is more familiar with it and can give me some pointers. > > Thanks, > > Joe Goldthwaite > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From weizhonghua.ati at gmail.com Wed Jul 16 06:00:38 2008 From: weizhonghua.ati at gmail.com (zhw) Date: Wed, 16 Jul 2008 03:00:38 -0700 (PDT) Subject: How can i use a variable without define it ? References: <87k5fm2p1x.fsf@benfinney.id.au> <1d09dd52-1e24-468c-b92f-f54dd306b3eb@l64g2000hse.googlegroups.com> <87fxqa2mu0.fsf@benfinney.id.au> Message-ID: <5dd91053-d239-4ff1-b693-d6afedf6bf24@x35g2000hsb.googlegroups.com> On 7?16?, ??5?35?, Ben Finney wrote: > zhw writes: > > Here is a example that I want to complete: > > >>> import sys, new > > >>> context={"name":"david", "sex":"male"} > > Here you have a set of values addressible by name. > > > >>> sys.modules["foo"] = new.module("foo") > > Why do you believe you need to create a module object? > > > >>> import foo > > >>> for attr in context: > > setattr(foo, attr, context[attr]) > > This doesn't appear to get you anything that isn't already available > with the 'context' mapping. > > > >>> def bar(): > > # here is a error > > # import * only allowed at module level > > from foo import * > > print name, sex > > You can simply do: > > >>> context = {'name': "david", 'sex': "male"} > >>> def bar(): > ... print context['name'], context['sex'] > ... > >>> bar() > david male > > Or, more flexible and more explicit: > > >>> foo = {'name': "david", 'sex': "male"} > >>> def bar(context): > ... print context['name'], context['sex'] > ... > >>> bar(foo) > david male > > What problem are you trying to solve? I an sorry, I can't tell you. If you can't give a solution, just ignore it! From mccredie at gmail.com Wed Jul 16 18:10:01 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 16 Jul 2008 15:10:01 -0700 (PDT) Subject: One step up from str.split() References: Message-ID: <0aa3b82e-9caa-4f02-8578-831300f53ebe@y21g2000hsf.googlegroups.com> On Jul 15, 4:28?pm, "Joel Koltner" wrote: > "Sion Arrowsmith" wrote in message > > news:Tiv*wYYhs at news.chiark.greenend.org.uk... > > > What's wrong with sys.argv ? > > Mainly that it doesn't exist. ?:-) ?The example was slightly contrived -- I'm > really dealing with commands interactively entered within a program in > response to raw_input(), although the format of the commands is meant to be > consistent with command-line usage. ?(A real command, for instance, would be > something like this: load "my firmware file.bin" .) > > I ended up using shlex.strip() -- works great! > > ---Joel Then... better yet... check out the cmd module (you can still use shlex if you like). [code] import cmd class MyCmd(cmd.Cmd): def do_blah(self, args): """Sing a song about bla""" print >>self.stdout, "bla bla bla" def do_foo(self, args): """Prints out the args""" print >>self.stdout, repr(args) def do_quit(self, args): """exit the command interpreter""" print >>self.stdout, "bye bye" return True do_exit = do_q = do_quit if __name__ == "__main__": MyCmd().cmdloop() [/code] When run, you will get a "(cmd)" prompt: (Cmd) help Documented commands (type help ): ======================================== blah exit foo q quit Undocumented commands: ====================== help (Cmd) help blah Sing a song about bla (Cmd) help exit exit the command interpreter (Cmd) help foo Prints out the args (Cmd) qu *** Unknown syntax: qu (Cmd) quit bye bye Documentation here: http://docs.python.org/lib/module-cmd.html Matt From darcy at druid.net Thu Jul 10 12:13:45 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 10 Jul 2008 12:13:45 -0400 Subject: Loading just in time In-Reply-To: References: Message-ID: <20080710121345.60d4fa02.darcy@druid.net> On Thu, 10 Jul 2008 11:03:10 -0500 Larry Bates wrote: > D'Arcy J.M. Cain wrote: > > def calc_tax(*arg, **name): > > from calc_tax import calc_tax as _func_ > > calc_tax = _func_ > > return _func_(*arg, **name) > You are stuck in a futile battle called "premature optimization". I would I thought that I might be. > suggest that you stop worrying about any performance you would gain from doing > something like this. Python has been "highly" optimized to handle imports in a > very efficient way. Just put your functions in a file and import them. Performance optimization wasn't really my goal here. What I was looking for was the ability to spread the functions around different files to manage them better from a proggrammer's POV. Oh well. I guess I will just combine them all again. At least I found some dead code, duplicate functions and just plain bad code doing this little exercise. :-) -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From fredrik at pythonware.com Tue Jul 22 12:54:01 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 22 Jul 2008 18:54:01 +0200 Subject: Question about inheritence In-Reply-To: References: Message-ID: Catherine Heathcote wrote: > If I create a new class inherited from another with a constructor, what > happens with the new class's constructer? assuming that you mean "is it called or not?": Python doesn't really have constructors; when you create an object, Python first creates the object and then calls the __init__ method, if available that method is an ordinary method, and behaves like all other methods: if you override it, your version is used. if you don't, the other one is used. >>> class Parent: ... def __init__(self): ... print "init parent" ... >>> class Child(Parent): ... pass ... >>> o = Child() init parent >>> class Child(Parent): ... def __init__(self): ... print "init child" ... >>> o = Child() init child if you want to override the parent's init method, but still use its functionality, you can add an explicit call to the method: >>> class Child(Parent): ... def __init__(self): ... Parent.__init__(self) ... print "init child" ... >>> o = Child() init parent init child since it's an ordinary method call, you don't have to initialize the parent the first thing you do. you can also pass in any arguments you want (including arguments passed to the child constructor): >>> class OtherChild(OtherParent): ... def __init__(self, a, b, c): ... self.c = c ... OtherParent.__init__(self, a + b) ... there's even a common pattern for passing along *all* arguments, no matter what they are: >>> class OtherChild(OtherParent): ... def __init__(self, *args, **kwargs): ... # do something here ... OtherParent.__init__(self, *args, **kwargs) ... # do something else here ... instead of explicitly naming the baseclass, you can use the "super" method to automatically look up the parent class, but this only works if the parent class inherits from "object" or a subclass thereof: >>> class Parent(object): ... def __init__(self): ... print "init parent" ... >>> class Child(Parent): ... def __init__(self): ... super(Child, self).__init__() ... print "init child" ... >>> o = Child() init parent init child hope this helps! From nicolas.pourcelot at gmail.com Fri Jul 18 05:09:57 2008 From: nicolas.pourcelot at gmail.com (nicolas.pourcelot at gmail.com) Date: Fri, 18 Jul 2008 02:09:57 -0700 (PDT) Subject: checking if an object IS in a list Message-ID: <96fbe7ea-9a82-44cc-86d3-0d9b6a9ca7a6@d19g2000prm.googlegroups.com> Hi, I want to test if an object IS in a list (identity and not equality test). I can if course write something like this : test = False myobject = MyCustomClass(*args, **kw) for element in mylist: if element is myobject: test = True break and I can even write a isinlist(elt, mylist) function. But most of the time, when I need some basic feature in python, I discover later it is in fact already implemented. ;-) So, is there already something like that in python ? I tried to write : 'element is in mylist' but this appeared to be incorrect syntax... All objects involved all have an '__eq__' method. Thanks, N. P. PS: Btw, how is set element comparison implemented ? My first impression was that 'a' and 'b' members are considered equal if and only if hash(a) == hash(b), but I was obviously wrong : >>> class A(object): ... def __eq__(self,y): ... return False ... def __hash__(self): ... return 5 ... >>> a=A();b=A() >>> a==b False >>> hash(b)==hash(a) True >>> b in set([a]) False >>> S=set([a]) >>> S.difference([b]) set([<__main__.A object at 0xb7a91dac>]) So there is some equality check also, maybe only if '__eq__' is implemented ? From linuxnow at gmail.com Tue Jul 8 18:18:23 2008 From: linuxnow at gmail.com (linuxnow at gmail.com) Date: Tue, 8 Jul 2008 15:18:23 -0700 (PDT) Subject: how to remove oldest files up to a limit efficiently Message-ID: <1eb168ac-fc63-4724-8604-45e995a06b51@s50g2000hsb.googlegroups.com> I need to mantain a filesystem where I'll keep only the most recently used (MRU) files; least recently used ones (LRU) have to be removed to leave space for newer ones. The filesystem in question is a clustered fs (glusterfs) which is very slow on "find" operations. To add complexity there are more than 10^6 files in 2 levels: 16? dirs with equally distributed number of files inside. My first idea was to "os.walk" the filesystem, find oldest files and remove them until I reach the threshold. But find proves to be too slow. My second thought was to run find -atime several times to remove the oldest ones, and repeat the process with most recent atime until threshold is reached. Again, this needs several walks through the fs. Then I thought about tmpwatch, but it needs, as find, a date to start removing. The ideal way is to keep a sorted list if files by atime, probably in a cache, something like updatedb. This list could be also be built based only on the diratime of the first level of dirs, seek them in order and so on, but it still seems expensive to get his first level of dir sorted. Any suggestions of how to do it effectively? From basti.wiesner at gmx.net Wed Jul 16 16:23:45 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Wed, 16 Jul 2008 22:23:45 +0200 Subject: Is there any component-oriented (non-MVC) web framework available for Python? References: <5fdd1388-bb1e-4a59-8fd1-2aa1ce7fa6e0@79g2000hsk.googlegroups.com> Message-ID: Alis : > Is there any component-oriented (non-MVC) web framework available for > Python? > > That is something like Apache Wicket, Tapestry or JSF, but I need it > to be in Python. Zope [1] might be worth trying. [1] http://www.zope.org -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From cs at zip.com.au Fri Jul 25 22:23:30 2008 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 26 Jul 2008 12:23:30 +1000 Subject: How to find processes from Python In-Reply-To: <9f04931c-867b-4ff3-820c-3f8d0bfd2618@e53g2000hsa.googlegroups.com> Message-ID: <20080726022330.GA25922@cskk.homeip.net> On 25Jul2008 11:34, Johny wrote: | Is there a way how to find out running processes?E.g. how many | Appache's processes are running? See the popen function and use the "ps" system command. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ When asked what would I most want to try before doing it, I said Death. - Michael Burton, michaelb at compnews.co.uk From pavlovevidence at gmail.com Wed Jul 30 22:00:18 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 30 Jul 2008 19:00:18 -0700 (PDT) Subject: Boolean tests [was Re: Attack a sacred Python Cow] References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> <1b7a218d-5781-409a-be26-6df7942d3b0a@t1g2000pra.googlegroups.com> <7c0166f8-5005-48b6-b340-c6735e830fdb@q5g2000prf.googlegroups.com> Message-ID: On Jul 30, 4:49 am, Ethan Furman wrote: > Carl Banks wrote: > > On Jul 29, 6:42 pm, Matthew Fitzgibbons wrote: > >> I don't have any postable code (it's in a half way state and I haven't > >> touched it for a while), but I'll see if I can't find the time to bang > >> something up to give you the gist. > > > I wouldn't bother at this point. I was looking to see if someone > > could come up with something to disprove my belief on the polymorphic > > uselessness of "if x" relative to explicit tests, and if (as I > > anticipated) they did not, I could claim that "if x" is really just a > > glorified keystroke saver. But I now realize that the failure of this > > bunch doesn't prove anything. I don't think most people even realize > > why answering the question I asked would demonstrate the usefulness of > > "if x". > > > Your example isn't exactly the smoking gun I was looking for, but I > > guess we'll have to admit that at least one usage will suffer for not > > having it. > > > Carl Banks > > Even for those that did realize, and in fact hoped that that is what you > were attempting to accomplish, I was not attempting to accomplish what you think I was. I was looking for it, but I didn't want to see it. I didn't expect to see it. I wanted to show that "if x" doesn't have the polymorphic advantage people mindlessly claim it does by posing the challenge and having people fail to meet it, and for the most part the examples that met the challenge were for minor usages. Ok, someone wrote a filter that truly benefits from polymorphism of "if x" against very different types, but really, these use cases aren't all that common. It's not like it's an everyday thing for you to write "if x" instead of "if x!=0", and that it actually saves you from having to rewrite the condition because later you decided to use a list. So I stand by the point I was trying to make: for your average day-to- day programming, the main benefit of "if x" is to save keystrokes. It doesn't help your code become more polymophic in practice. A little more polymorphic, yes. A lot, no. > it was still quite frustrating to see you > ignoring all the non-code, yet perfectly valid examples of why "if x" > was not only valid, but the most pythonic[1] way to get the task done. Pfft. The usage of "if x" might be Pythonic, but I think the best way is the way Java does it. > I think it would have been a better discussion if you had responded with > reasons why, and not just parroted the "show me the code!" line over and > over and over and ... It seemed as if you thought you were the > professor, impatiently trying to teach a class full of idiots by playing > the devil's advocate. I wasn't playing Devil's advocate, I was playing the Devil. That's why I did that. Sorry if it irritated people but I wasn't about to those things distract me. > I was sure hoping someone would get the actual > code example and post it, partly because I enjoy learning, but mostly > because it would (hopefully) shut you up and move the conversation > along. In fact, somebody did post some code about a custom matrix > class, where __len__ was useless, and still you kept on with... pah. I admit it! I downplay even successful examples because I just don't like implicit booleans. What can I say, I'm an optimist. I didn't see any custom matrix class, BTW. The only code I saw was Steven D'Aprano filter which he still apparently expects me to take his word for it that the alternative I proposed won't work, and Terry Reedy's empty-enabled iterator. Oh, also Heiko Wundram's integer set. > It's late, so before I say something stupid I'll finish this. My last > thought on the matter -- up until this thread I had looked forward to > your posts, Carl. I think you did more damage than good to yourself > with this stunt. Sorry, but I must go on a crusade every once in awhile, whatever damage it may cause my esteem. It's in my nature. Carl Banks From ethan at stoneleaf.us Thu Jul 10 11:34:35 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 10 Jul 2008 07:34:35 -0800 Subject: a simple 'for' question In-Reply-To: References: <4874017D.2000401@umbc.edu> <90B098E8-F2F7-41A9-8B22-A09AB3053696@bryant.edu> <487437E6.8010609@umbc.edu> <1215599630.2873.965.camel@localhost.localdomain> <48749F60.7030106@umbc.edu> Message-ID: <48762C0B.60407@stoneleaf.us> Tim Roberts wrote: > Ethan Furman wrote: > > >>Ben Keshet wrote: >> >>>it didn't help. it reads the pathway "as is" (see errors for both >>>tries). It looks like it had the write pathway the first time, but >>>could not find it because it searched in the path/way instead of in the >>>path\way. thanks for trying. >> >>The form of slash ('\' vs '/') is irrelevant to Python. At least on >>Windows. >> >> >>>folders= ['1','2','3'] >>>for x in folders: >>> print x # print the current folder >>> filename='Folder/%s/myfile.txt' %[x] >> >> ^- brackets not needed > > > More than that, the brackets are CAUSING this problem. The "%" formatting > operator expects to find either a single item, or a tuple containing > multiple items. It does NOT look for a generic iterator. In this case, > the %s will use the whole list as its parameter. Python converts the list > to string, and the string representation of that one-item list is ['1']. You are, of course, correct -- the brackets are causing the displayed problem below. But judging from the thread so far, there are actually multiple problems going on here, of which the brackets are only this one part. It looks like the OP also lacks understanding regarding absolute and relative path names, as well as (possibly) not knowing where his script/interpreter is running from. > > >>> f=open(filename,'r') >>> >>>gives: IOError: [Errno 2] No such file or directory: >>>"Folder/['1']/myfile.txt" > > > Just like that. > > >>As far as the Python question of string substitution, "%s" % var is an >>appropriate way. > > > Right. From jim.hefferon at gmail.com Tue Jul 1 20:42:41 2008 From: jim.hefferon at gmail.com (Jim) Date: Tue, 1 Jul 2008 17:42:41 -0700 (PDT) Subject: convert unicode characters to visibly similar ascii characters References: <17d4c282-8606-4d29-9e71-d34f5e6d13bb@m44g2000hsc.googlegroups.com> Message-ID: On Jul 1, 8:29 pm, John Machin wrote: > On Jul 2, 9:55 am, Jim wrote: > > Comments on the above grep output: > 1. You have SOFT HYPHEN twice, mapping it to u'-' and '-' Hmph. I'll correct that. Thanks. > 2. The idea of a soft hyphen is as a hint to a hyphenator about where > to insert a hyphen if one is necessary and the hyphenator is suspected > of acting cluelessly without the hint. IMHO, asciification should > substitute u'', not u'-'. Thanks also here. I'll think about it. > 3. Read PEP 8. s/:/: / I don't like the spacing in 8, personally. Thanks, Jim From chiendarret at gmail.com Sat Jul 26 11:47:52 2008 From: chiendarret at gmail.com (Francesco Pietra) Date: Sat, 26 Jul 2008 17:47:52 +0200 Subject: Insert character at a fixed position of lines In-Reply-To: <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> References: <066359b4-fd82-4d34-ac29-b966c45c4ac9@o40g2000prn.googlegroups.com> <2c769a85-b286-45a9-a956-0d08436f508e@i24g2000prf.googlegroups.com> Message-ID: Sorry to come again for the same problem. On commanding: $ python script.py 2>&1 | tee fileout.pdb nothing occurred (fileout.pdb was zero byte). The script reads: f = open("xxx.pdb", "w") f.write('line = line[:22] + "A" + line[23:]') f.close() File xxx.pdb is opened by the command: when I forgot the single quote ' after [23:] the error answer was: SynthaxError: EOL while scanning single-quoted string. Thanks francesco On Sat, Jul 26, 2008 at 1:10 PM, Lie wrote: > On Jul 26, 5:42 pm, "Francesco Pietra" wrote: >> I am still at the stone age, using scripts (e.g., to insert a string >> after a string) of the type >> >> f = open("xxx.pdb", "r") >> for line in f: >> print line >> if "H16Z POPC" in line: >> print "TER" >> f.close() >> >> That is, I have to learn about modules. In your scripts I am lost >> about the filename for the pdb file to modify, > > In Python, stdin and stdout (as provided by the sys module) is a file- > like object, i.e. it have similar behavior as regular files you opened > with open(). stdin is a read-only file, while stdout is a write-only > file. You already know how to make read-only file, f = open("xxx.pdb", > "r"), to make it writable, you've got to use 'w' as the mode: f = > open("xxx.pdb", "w") > > After that you can do this: > f.write('some string') > > >> francesco >> >> >> >> On Sat, Jul 26, 2008 at 11:35 AM, Lie wrote: >> > On Jul 26, 2:41 pm, "Francesco Pietra" wrote: >> >> How to insert letter "A" on each line (of a very long list of lines) >> >> at position 22, i.e., one space after "LEU", leaving all other >> >> characters at the same position as in the original example: >> >> >> ATOM 1 N LEU 1 146.615 40.494 103.776 1.00 73.04 1SG 2 >> >> >> In all lines"ATOM" is constant as to both position and string, while >> >> "LEU" is constant as to position only, i.e., "LEU" may be replaced by >> >> three different uppercase letters. Therefore, the most direct >> >> indication would be position 22. >> >> >> Should the script introduce blank lines, no problem. That I know how >> >> to correct with a subsequent script. >> >> >> Thanks >> >> chiendarret >> >> > If you want to leave the rest of the strings as-is (i.e. the letter A >> > overwrites whatever on position 22), Peter's code need to be modified >> > a little: >> > line = line[:22] + " " + line[23:] >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> -- >> Dr Francesco Pietra >> Professor of Chemistry >> Accademia Lucchese di Scienze, Lettere e Arti, founded in 1594 >> Palazzo Ducale >> 55100 Lucca (Italy) >> e-mail chiendar... at gmail.com > > -- > http://mail.python.org/mailman/listinfo/python-list > From wmcbrine at users.sf.net Mon Jul 28 20:39:17 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Tue, 29 Jul 2008 00:39:17 GMT Subject: like py2exe, but on a mac References: <18424336.post@talk.nabble.com> <5K9jk.278$rb5.198@trnddc04> <_7ojk.253$wS4.85@trnddc03> <488E1B93.1060408@codebykevin.com> Message-ID: On Mon, 28 Jul 2008 15:18:43 -0400, Kevin Walzer wrote: > Add this call to your Python script somewhere (modify as needed): > > try: > self.tk.call('console', 'hide') > except TclError: > pass Ah, yes! Thanks. -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From dickinsm at gmail.com Tue Jul 8 09:55:26 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 8 Jul 2008 06:55:26 -0700 (PDT) Subject: numeric emulation and __pos__ References: Message-ID: <92e3ea9f-5745-4072-9d09-7c14fd335828@f36g2000hsa.googlegroups.com> On Jul 8, 12:12?am, Ethan Furman wrote: > 1) Any reason to support the less common operators? > ? ? ? ? i.e. <<, >>, &, ^, | No reason to support any of these for a nonintegral nonbinary type, as far as I can see. > 2) What, exactly, does .__pos__() do? ?An example would help, too. > Very little: it implements the unary + operator, which for most numeric types is a no-op: >>> +5.0 5.0 So you could safely implement it as: def __pos__(self): return self By the way, have you met the Decimal type? It also keeps track of significant zeros. For example: >>> from decimal import Decimal >>> Decimal('1.95') + Decimal('2.05') Decimal("4.00") (Note that the output includes the extra zeros...) Interestingly, in Decimal the __pos__ operation isn't a no-op: it rounds a Decimal to the current context, and it also (mistakenly, in my opinion) changes -0.0 to 0.0: >>> +Decimal('-0.0') Decimal("0.0") >>> +Decimal('123456789123456789123456789123456789') Decimal("1.234567891234567891234567891E+35") Mark From gherron at islandtraining.com Mon Jul 28 18:00:16 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 28 Jul 2008 15:00:16 -0700 Subject: seemingly simple list indexing problem In-Reply-To: References: Message-ID: <488E4170.2020804@islandtraining.com> Guilherme Polo wrote: > On Mon, Jul 28, 2008 at 6:24 PM, Ervan Ensis wrote: > >> My programming skills are pretty rusty and I'm just learning Python so this >> problem is giving me trouble. >> >> I have a list like [108, 58, 68]. I want to return the sorted indices of >> these items in the same order as the original list. So I should return [2, >> 0, 1] >> > > You could simply do this: > > a = [108, 58, 68] > b = sorted(a) > [b.index(c) for c in a] > Yuck. Slow, and it fails if duplicate list elements exist. Also... This looks like a beginners programming assignment. Let's let him try it himself. We can offer help rather than full solutions if he has specific Python questions. > >> For a list that's already in order, I'll just return the indices, i.e. [56, >> 66, 76] should return [0, 1, 2] >> >> Any help would be appreciated. >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > > > From thomas.bugzilla at gmx.net Thu Jul 10 08:11:46 2008 From: thomas.bugzilla at gmx.net (Thomas) Date: Thu, 10 Jul 2008 14:11:46 +0200 Subject: Relative Package Import In-Reply-To: References: Message-ID: Peter Otten wrote: > Thomas wrote: > >> Robert Hancock wrote: >>> mypackage/ >>> __init__.py >>> push/ >>> __init__.py >>> dest.py >>> feed/ >>> __init__py >>> subject.py >>> >>> In subject.py I have >>> from ..push import dest >> There is no such thing as relative package imports. See >> http://www.python.org/doc/essays/packages.html > > Unless you are using Python 1.5 the following document is a bit more > relevant: > > http://www.python.org/dev/peps/pep-0328/ Oups, thanks for the pointer. I thought the old doc was still valid... (gee, there should be forward references). Thomas From swiftone at swiftone.org Sat Jul 26 15:38:14 2008 From: swiftone at swiftone.org (Brett Ritter) Date: Sat, 26 Jul 2008 12:38:14 -0700 (PDT) Subject: Simple Path issues References: <7bef6df9-45d6-4ef6-b802-1dd201ec66e3@k30g2000hse.googlegroups.com> Message-ID: <6093d9df-d68d-43e7-90d4-44f964529299@m3g2000hsc.googlegroups.com> On Jul 26, 2:57?pm, Gary Josack wrote: > sys.path is a list that will tell you where python is looking. You can > append to this in your scripts to have python look in a specific > directory for your own modules. I can, but that is almost certainly not the standard way to develop a module. I see nothing in sys.path that I have write permissions to. Is altering my PYTHONPATH the normal way to develop (under the assumption that later users will install in their conventional python search path)? From fredrik at pythonware.com Wed Jul 23 16:13:32 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 23 Jul 2008 22:13:32 +0200 Subject: Doubt In-Reply-To: References: Message-ID: ???????? wrote: > I am a Perl programmer new to Python. I have a small doubt. I suspect you mean "question", not "doubt". It's not quite the same thing. > How to convert the perl notation > $a = ""; expression in Python ? > > How to represent the loop > for ($a = $b; $a<=$c;$a++){ > } in Python Start here: http://www.lucasmanual.com/mywiki/PerlPythonPhrasebook and then read either of these (preferably both): http://www.swaroopch.com/byteofpython/ http://docs.python.org/tut/ From ldo at geek-central.gen.new_zealand Sun Jul 27 23:55:10 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 28 Jul 2008 15:55:10 +1200 Subject: Attack a sacred Python Cow References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <024ace13-f72f-4093-bcc9-f8a339c324e2@v1g2000pra.googlegroups.com> <6385b0a8-f7f3-4dc3-91be-e6f158ffb439@a1g2000hsb.googlegroups.com> Message-ID: In message <6385b0a8-f7f3-4dc3-91be-e6f158ffb439 at a1g2000hsb.googlegroups.com>, s0suk3 at gmail.com wrote: > On Jul 26, 6:47 pm, Lawrence D'Oliveiro central.gen.new_zealand> wrote: >> In message >> <024ace13-f72f-4093-bcc9-f8a339c32... at v1g2000pra.googlegroups.com>, >> >> s0s... at gmail.com wrote: >> > On Jul 24, 5:01 am, Lawrence D'Oliveiro > > central.gen.new_zealand> wrote: >> >> >> In message >> >> <52404933-ce08-4dc1-a558-935bbbae7... at r35g2000prm.googlegroups.com>, >> >> Jordan wrote: >> >> >> > Except when it comes to Classes. I added some classes to code that >> >> > had previously just been functions, and you know what I did - or >> >> > rather, forgot to do? Put in the 'self'. In front of some of the >> >> > variable accesses, but more noticably, at the start of *every single >> >> > method argument list.* >> >> >> The reason is quite simple. Python is not truly an "object-oriented" >> >> language. It's sufficiently close to fool those accustomed to OO ways >> >> of doing things, but it doesn't force you to do things that way. You >> >> still have the choice. An implicit "self" would take away that choice. >> >> > By that logic, C++ is not OO. >> >> Yes it is, because it has "this". > > You mean the keyword "this"? It's just a feature. How does that make a > difference on being or not being OO? Because it was one of the things the OP was complaining about (see above). From hv at tbz-pariv.de Wed Jul 2 07:08:40 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Wed, 02 Jul 2008 13:08:40 +0200 Subject: Scripting SAP GUI (Windows) Message-ID: <6d15tpFaec4U1@mid.individual.net> Hi, I need to script SAP GUI running on MS-Windows: Open SAP GUI window, if it is not already open, and then batch input some keystrokes. The following solutions were found by google: - autohotkey: not preferred, since it has an own programming language. This will slow down development. - pyHook - user pywin32 and SetWindowsHookEx I develop with python since seven years, but only on linux. Any hints? -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From workitharder at gmail.com Sun Jul 13 20:39:01 2008 From: workitharder at gmail.com (bukzor) Date: Sun, 13 Jul 2008 17:39:01 -0700 (PDT) Subject: Dictionary bidirectional References: <308c83f4-e093-4893-a82b-c13120674628@d77g2000hsb.googlegroups.com> Message-ID: <792048c1-5e18-4a2c-925d-a1c932d18a91@j22g2000hsf.googlegroups.com> On Jul 13, 4:21 pm, Kless wrote: > I need a dictionary where get the result from a 'key' (on left), but > also from a 'value' (on right), how to get it? > > I know that dictionaries aren't bidirectional, but is there any way > without use two dictionaries? > > Thanks in advance! You need to use two dictionaries. Here's a class that someone's written that wraps it up into a single dict-like object for you: http://www.faqts.com/knowledge_base/view.phtml/aid/4376 From tn.pablo at gmail.com Fri Jul 18 09:42:07 2008 From: tn.pablo at gmail.com (ptn) Date: Fri, 18 Jul 2008 06:42:07 -0700 (PDT) Subject: Question on Joining of list References: <3c982607-021d-44a8-aa9f-693271c61738@t12g2000prg.googlegroups.com> <3db7c643-56ca-4d6e-99eb-16176e1a2e88@d19g2000prm.googlegroups.com> Message-ID: <7b2d0e3b-0ee4-4f1b-90d5-90eae9f258a0@u6g2000prc.googlegroups.com> On Jul 18, 5:40?am, SUBHABRATA wrote: > Hi Peter,Peter Otten wrote: > > SUBHABRATA wrote: > > > > Thanx Peter, > > > I would change my variables next time I would post. > > > No, you should use meaningful variable names when you write your code no > > matter whether you plan to post it or not. > > Good You are teaching me something good in life. Thanx. > > > > And obviously, > > > thanx for your solution. I am reviewing it, I was also trying out some > > > solutions. > > > You misunderstood. I did not modify your code other than changing the > > variable names. My hope was that with this modification any errors sprang > > to you eye... > > I was seeing that. > I am almost near the solution. You can also try some hands if you > feel. > Best Regards, > Subhabrata. > > > > > Peter > > A couple more things on variable naming and coding style: - You used "a{digit}" to name variables of different types (a4 was an int, a2 was a list and the rest were strings). Remember C, where i, j, k are indices, p, q, r are pointers, s, t are strings and x, y, z are integers. For unimportant variables, you can skip long descriptive names, so long you don't use a confusing one. - You violated your own naming conventions. Why did you choose to use s to name that last string? Use descriptive names and stick to your own style. - You use whitespace weirdly (like in a4>-1 or a4=a3.find). Try reading PEP8 (http://www.python.org/dev/peps/pep-0008/), the Style Guide for Python Code. As for your code, you need to find where it is that missing_word and first_char are being updated, and assign to s before that happens. From Abhishek_Asthana01 at infosys.com Thu Jul 3 05:46:08 2008 From: Abhishek_Asthana01 at infosys.com (Abhishek Asthana) Date: Thu, 3 Jul 2008 15:16:08 +0530 Subject: multithreading in python ??? Message-ID: <674A912AA405814397CED58601AC8E251554964241@BLRKECMBX05.ad.infosys.com> Hi all , I have large set of data computation and I want to break it into small batches and assign it to different threads .I am implementing it in python only. Kindly help what all libraries should I refer to implement the multithreading in python. Thanks , Abhishek **************** CAUTION - Disclaimer ***************** This e-mail contains PRIVILEGED AND CONFIDENTIAL INFORMATION intended solely for the use of the addressee(s). If you are not the intended recipient, please notify the sender by e-mail and delete the original message. Further, you are not to copy, disclose, or distribute this e-mail or its contents to any other person and any such actions are unlawful. This e-mail may contain viruses. Infosys has taken every reasonable precaution to minimize this risk, but is not liable for any damage you may sustain as a result of any virus in this e-mail. You should carry out your own virus checks before opening the e-mail or attachment. Infosys reserves the right to monitor and review the content of all messages sent to or from this e-mail address. Messages sent to or from this e-mail address may be stored on the Infosys e-mail system. ***INFOSYS******** End of Disclaimer ********INFOSYS*** -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Thu Jul 10 06:35:57 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 10 Jul 2008 12:35:57 +0200 Subject: FOSS projects exhibiting clean/good OOP? In-Reply-To: <3bd416cf-6989-44fb-961d-658032231356@m73g2000hsh.googlegroups.com> References: <5d01ce45-dd34-4345-958d-ff31c558b1f8@a70g2000hsh.googlegroups.com> <14a58bec-3ed4-4af8-ba2e-ac4d3c12b064@b1g2000hsg.googlegroups.com> <3bd416cf-6989-44fb-961d-658032231356@m73g2000hsh.googlegroups.com> Message-ID: <4875e5d8$0$16991$426a34cc@news.free.fr> Phillip B Oldham a ?crit : > Thanks all - lots to go through there! :D > > I'd heard previously that Trac was a nice example, or rather its core > was, but I'd also heard that there were lots of problems with it and > that they were redeveloping it from scratch? Trac's plugin system is interesting, yes, but there were indeed quite a couple gotchas last time I used it (about 2 years ago). From asmodai at in-nomine.org Fri Jul 11 05:54:56 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 11 Jul 2008 11:54:56 +0200 Subject: recommended gcc versions for python2.5 compilation on Solaris sparc/x86, AIX, Linux In-Reply-To: <9347F3EEF61FC542A7D9211A42CD7E6387E071@dolphin.sg.murex.com> References: <9347F3EEF61FC542A7D9211A42CD7E6387E071@dolphin.sg.murex.com> Message-ID: <20080711095456.GW68329@nexus.in-nomine.org> -On [20080711 06:18], YIN Ming (Ming.YIN at murex.com) wrote: >2. use new version of gcc (rather than odd version) See http://www.in-nomine.org/2008/04/11/python-26a2-execution-times-with-various-compilers/ that I wrote a while ago. Basically for Python GCC 3.4.6 outperformed the newer GCCs. So do not automatically assume that newer is better. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B The weak can never forgive. Forgiveness is the attribute of the strong... From mal at egenix.com Thu Jul 17 18:01:57 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 18 Jul 2008 00:01:57 +0200 Subject: Converting from local -> UTC In-Reply-To: <44GdnYNOD4ZCM-LVnZ2dnUVZ_gydnZ2d@earthlink.com> References: <4627d685-6eb0-443d-83bb-6392ea83e8d1@2g2000hsn.googlegroups.com> <2170bbbd-0a9d-4e8b-88c0-beeef77c1f33@s50g2000hsb.googlegroups.com> <41d4ffc7-7fd5-4202-92ea-132c7d4f5cd4@s50g2000hsb.googlegroups.com> <44GdnYNOD4ZCM-LVnZ2dnUVZ_gydnZ2d@earthlink.com> Message-ID: <487FC155.30604@egenix.com> On 2008-07-17 22:43, Dennis Lee Bieber wrote: > On Thu, 17 Jul 2008 19:55:44 +0200, "M.-A. Lemburg" > declaimed the following in comp.lang.python: > > >> Use binding parameters and it should work: >> >> query = "INSERT INTO image VALUES(%d, %d, %s, '%s')" > > If this is MySQLdb interface: > > query = "INSERT INTO image VALUES(%s, %s, %s, '%s')" > > ... only %s is valid; all values have been converted to escaped/quoted > string before getting to the substitution. Right. I forgot to replace the %d's with %s's. The line should read: query = "INSERT INTO image VALUES(%s, %s, %s, %s)" -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 17 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From stefan_ml at behnel.de Thu Jul 3 01:02:27 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 03 Jul 2008 07:02:27 +0200 Subject: ANN: XML builder for Python In-Reply-To: <486C5CA1.3080105@behnel.de> References: <486C5CA1.3080105@behnel.de> Message-ID: <486C5D63.5030407@behnel.de> Stefan Behnel wrote: > Jonas Galvez wrote: >> Not sure if it's been done before, but still... > > Obviously ;) > > http://codespeak.net/lxml/tutorial.html#the-e-factory > > ... and tons of other tools that generate XML, check PyPI. Although it might be the first time I see the with statement "misused" for this. :) Stefan From fred.haab at gmail.com Tue Jul 29 23:43:55 2008 From: fred.haab at gmail.com (fred.haab) Date: Tue, 29 Jul 2008 20:43:55 -0700 (PDT) Subject: Is it allowed to use function results as default arguments ? References: Message-ID: Well, others have answered the question, but I thought I'd throw in that it would be more pythonic to do something like: def Get_Relative_Path(target, base = None): if base is None: base = os.curdir ... From ebgssth at gmail.com Wed Jul 9 19:16:34 2008 From: ebgssth at gmail.com (js) Date: Thu, 10 Jul 2008 08:16:34 +0900 Subject: Py_BuildValue for char **? Message-ID: Hi, I'm writing a wrapper module of C API. To make a C struct data avaiable to Python, I need to map C struct into a PyObject. I'm thinking that I use a tuple or dict to represent the struct but a problem is one of the members of the struct is char **, which is not supported by Py_BuildValue. Is there any idiomatic way of mapping char ** to Python? Any suggestions, pointers would be appreciated. From jaing08 at gmail.com Wed Jul 2 23:05:06 2008 From: jaing08 at gmail.com (Devil) Date: Thu, 3 Jul 2008 08:35:06 +0530 Subject: Need help on Python File write operation..... Message-ID: <7a2a9cc40807022005h2218c55fxb2fa3bf801281d9a@mail.gmail.com> Hi, I am stuck at below mention point. I am not able to find any way of doing it in python. I have google enough to find any sample code but unsuccessful. Plz help. I am trying to write a file of size (user specified size) so that it will pops(remove) the oldest line written (data item) to make room for newest line (data item ) when max size is reached. I also want to see data update while program running (some thing like flush() because file size some time is very huge... so need to check the data copying to file) Data written in file is a string (array of data of variable length ) ended by '\n'. Do help me as it is very urgent for me. Thanks in advance. Regards, jaing -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Sat Jul 19 11:39:00 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Jul 2008 15:39:00 GMT Subject: Question References: Message-ID: <6eeg4kF6k7g3U1@mid.uni-berlin.de> On Sat, 19 Jul 2008 10:27:28 +0100, perl_wizard wrote: > Why is Perl so much better than python? You are so much better than python? Ciao, Marc 'BlackJack' Rintsch From musiccomposition at gmail.com Tue Jul 22 23:06:10 2008 From: musiccomposition at gmail.com (Benjamin) Date: Tue, 22 Jul 2008 20:06:10 -0700 (PDT) Subject: Is this a valid use of 'import'? References: Message-ID: On Jul 22, 12:26?pm, Terry Reedy wrote: > > *Python2 has a built-in reload function, but in 3.0 it is removed > because it almost never did what people wanted or expected and thus lead > to surprising bugs. ?You can delete a module from sys.modules and > re-import it, but the module object and those it created will not > disappear as long as there are other references to them. It's not gone. It's been moved to imp. From phil at riverbankcomputing.com Sat Jul 5 12:09:28 2008 From: phil at riverbankcomputing.com (Phil Thompson) Date: Sat, 05 Jul 2008 17:09:28 +0100 Subject: Python with Ecmascript In-Reply-To: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> References: <8fd55f2a-8ef6-4e74-a039-f63c1d811644@25g2000hsx.googlegroups.com> Message-ID: On Sat, 5 Jul 2008 06:28:42 -0700 (PDT), "jiri.zahradil at gmail.com" wrote: > Hello, > > for my Python application (Windows platform) to be standards > compliant, I need to embbed Ecmascript(Javascript) interpreter - I > need to execute plugins written in this language. Which engine is > suitable for Python, I have found bunch of them. Any recomendations > are welcome. > > To be more specific, I think that plugins will be pretty simple, they > will be used to manipulate my class-based datamodel, no special > libraries dependencies ... therefore I prefer some rather simple > solution ... PyQt includes a Javascript interpreter. You can expose Python objects and properties as Javascript objects and properties. Phil From stefan_ml at behnel.de Thu Jul 31 13:59:39 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 31 Jul 2008 19:59:39 +0200 Subject: Python parsing iTunes XML/COM In-Reply-To: <5f3a28f9-5918-4d5a-857b-3fbe2af3b196@u12g2000prd.googlegroups.com> References: <2dccdae7-7b9a-4e82-b9da-1ea4914bbb6c@a21g2000prf.googlegroups.com> <7e3787ed-1fd6-4060-9e81-a78546390677@r35g2000prm.googlegroups.com> <289aad05-1f4e-4ac5-9f2d-6f37b2569d6d@z6g2000pre.googlegroups.com> <99937aba-b630-4174-8649-85a268932d19@q5g2000prf.googlegroups.com> <4ae2518f-10c0-49f2-b5d7-a75993b0a67d@z66g2000hsc.googlegroups.com> <48915761$0$11736$9b4e6d93@newsspool1.arcor-online.net> <5f3a28f9-5918-4d5a-857b-3fbe2af3b196@u12g2000prd.googlegroups.com> Message-ID: <4891fd8a$0$20708$9b4e6d93@newsspool4.arcor-online.net> william tanksley wrote: > I didn't > pass a string. I passed a file. It didn't error out; instead, it > produced bytestring-encoded output (not Unicode). >From my experience (and from the source code I have seen so far), ElementTree does not return UTF-8 encoded strings at the API level. Can you produce any evidence for your claims? Some code and an XML file that together produce the result you are talking about? From what you have written so far, it seems far more likely to me that your code is messed up than that you found a bug in ElementTree. Stefan From bgeddy at home.havin.a.break Thu Jul 17 20:16:17 2008 From: bgeddy at home.havin.a.break (bgeddy) Date: Fri, 18 Jul 2008 01:16:17 +0100 Subject: storing references instead of copies in a dictionary In-Reply-To: References: <76fd5acf0807170530q4d9cd55aw123d1727c3dcb983@mail.gmail.com> Message-ID: castironpi wrote: > On Jul 17, 10:05 am, mk wrote: >>> def f2(arg): >>> return "f2 "+arg >>> def f1(arg): >>> return "f1 "+arg >>> a={"1":"f1","2":"f2"} >>> print [eval(x[1])(x[0]) for x in a.items()] >>> def f2(arg): >>> return "New f2 "+arg >>> print [eval(x[1])(x[0]) for x in a.items()] >> Neat trick, if probably dangerous in some circumstances. Anyway, thanks, >> I didn't think of that. >> >>> Don't know if this is any use to you.. >> At least I learned something. :-) > > You want consistent access to a changing variable. Wrap it in an > object: > >>>> a= Blank( ) >>>> a.ref= 'X' >>>> a.ref > 'X' >>>> b= a >>>> b.ref > 'X' >>>> a.ref= 'Y' >>>> b.ref > 'Y' > My "old fashioned" programing paradigms think of this in terms of "pointers", a throw back to my schooling in 'C'. I find this general form of problem to be common across languages and in some ways hard to express in python. The whole idea of labels bound to objects is quite alien to traditional terminology. I find one of the main attractions of python is this new mindset that the language makes you adopt - a different set of tools are at hand for the old school programmer. castironpi - please give an example of what you are thinking as I find this interesting. preferably post some brief example code. From mal at egenix.com Fri Jul 25 06:35:10 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 25 Jul 2008 12:35:10 +0200 Subject: Questions on 64 bit versions of Python In-Reply-To: <1216966424.4685.1265275245@webmail.messagingengine.com> References: <1216966424.4685.1265275245@webmail.messagingengine.com> Message-ID: <4889AC5E.8090909@egenix.com> On 2008-07-25 08:13, python at bdurham.com wrote: > Background: I'm going to be processing some raw transaction logs that > are 30G in size. As part of this processing I may need to create some > very large dictionary structures. I will be running my scripts on a > version of Windows 2003 Server Enterprise Edition that supports 16G of > RAM. Yes, I could use a database in place of dictionaries, but I'm > looking for maximum performance. > > The following page lists two 64 bit versions of Python for Windows: > http://www.python.org/download/releases/2.5.2/ > > For Win64-Itanium users: python-2.5.2.ia64.msi > For Win64-AMD64 users: python-2.5.2.amd64.msi > > 1. It looks like the 64 bit versions of Python for Windows are CPU > vendor specific, eg. it doesn't look like there's a single, universal > executable for Windows 64 bit platforms. Is this true? Yes. But then Intel Itanium is being phased out anyway and the AMD64 build works on both Intel and AMD processors. > 2. Are there limitations to the using the 64 bit versions of Python? I > seem to remember reading that many 3rd party modules (especially Windows > OS specific modules) may not be compatible with the 64 bit versions of > Python for Windows. True. The extensions usually need to be recompiled and possibly also updated to support 64-bit architectures. The win32 tools are available on 64-bit Windows - if that's what you mean with "Windows OS specific modules". > 3. If I wanted to run a 64 bit version of Python under Linux, would I > need to recompile from source on 64 bit version of Linux or do 64 bit > versions of Linux automatically ship with 64 bit versions of Python? > (Any recommendations on a flavor of 64 bit of Linux for the Intel > architecture would be appreciated) Yes, 64-bit Linux versions ship with 64-bit builds of Python. Any recent Linux distro should work just fine. > 4. Is there a stable version of IronPython compiled under a 64 bit > version of .NET? Anyone have experience with such a beast? Can't comment on that one. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 25 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From comp.ogz at gmail.com Thu Jul 3 00:58:59 2008 From: comp.ogz at gmail.com (Oguz Yarimtepe) Date: Thu, 3 Jul 2008 07:58:59 +0300 Subject: detection of unplugged cable In-Reply-To: References: Message-ID: <20831c740807022158l38648a61l4966d11fae20297d@mail.gmail.com> On Thu, Jul 3, 2008 at 7:33 AM, Dennis Lee Bieber wrote: > On Wed, 2 Jul 2008 13:32:59 +0300, "Oguz Yarimtepe" > declaimed the following in comp.lang.python: > I'd be willing to bet that S-video outputs do NOT have feed-back to > the video driver as they only carry chroma and luminance signals. And > what is DMI? a low-resolution HDMI or a typo for DVI? > It is a DVI output. sorry for the typo. > For those connectors that do carry feedback, it is no doubt > something buried deep in the guts of the OS and video card drivers. > > Also, consider that, for example, my monitor has four inputs: VGA, > DVI, S-Video, and I believe plain old composite. I can have four devices > (two computers, a dvd-player, and a VCR, say) and switch between them. > What would your program do if the detected cable is not the one that is > displayed at the time? > -- It is a display switcher working in a simple way. I couldn't manage to clone my dvi output, i had to switch of lvds and set the output to dvi. When the cable is unplugged i planned to switch the lvds output on. -- O?uz Yar?mtepe From doug.farrell at gmail.com Wed Jul 9 11:52:04 2008 From: doug.farrell at gmail.com (writeson) Date: Wed, 9 Jul 2008 08:52:04 -0700 (PDT) Subject: Determining when a file has finished copying Message-ID: <4b1e1178-325e-4b92-9d12-94bce19f2f94@27g2000hsf.googlegroups.com> Hi all, I'm writing some code that monitors a directory for the appearance of files from a workflow. When those files appear I write a command file to a device that tells the device how to process the file. The appearance of the command file triggers the device to grab the original file. My problem is I don't want to write the command file to the device until the original file from the workflow has been copied completely. Since these files are large, my program has a good chance of scanning the directory while they are mid-copy, so I need to determine which files are finished being copied and which are still mid-copy. I haven't seen anything on Google talking about this, and I don't see an obvious way of doing this using the os.stat() method on the filepath. Anyone have any ideas about how I might accomplish this? Thanks in advance! Doug From sjmachin at lexicon.net Sun Jul 20 17:38:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 20 Jul 2008 14:38:28 -0700 (PDT) Subject: round function error??? References: <2da2f5f1-7ff2-46d7-a768-f0817e414615@f36g2000hsa.googlegroups.com> Message-ID: <4f1c4b26-ac4c-4079-adc3-3b978263ff22@b2g2000prf.googlegroups.com> On Jul 21, 12:56 am, Mark Dickinson wrote: > On Jul 19, 12:20 am, John Machin wrote: > > > On Jul 19, 8:05 am, Mark Dickinson wrote: > > > for more information. But I'm guessing that you're > > > questioning the fact that a value that's apparently > > > *less* than 3499.35 is rounded up to 3499.4, rather > > > than down to 3499.3. ? > > > "apparently" being the operative word. > > Well, it's not just an apparent problem: the closest > floating-point number to 3499.35 really *is* less than > 3499.35. I'm well aware of that. My point is that I hope that you weren't planning on changing that behaviour in an unannounced unstaged manner. From mrkafk at gmail.com Tue Jul 8 18:06:21 2008 From: mrkafk at gmail.com (mk) Date: Wed, 09 Jul 2008 00:06:21 +0200 Subject: (silly?) speed comparisons Message-ID: Out of curiosity I decided to make some speed comparisons of the same algorithm in Python and C++. Moving slices of lists of strings around seemed like a good test case. Python code: def move_slice(list_arg, start, stop, dest): frag = list_arg[start:stop] if dest > stop: idx = dest - (stop - start) else: idx = dest del list_arg[start:stop] list_arg[idx:idx] = frag return list_arg b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] >>> import timeit >>> t = timeit.Timer("move_slice.move_slice(move_slice.b, 4, 6, 7)", "import move_slice") >>> t.timeit() 3.879252810063849 (Python 2.5, Windows) Implementing the same algorithm in C++: #include #include #include using namespace std; vector move_slice(vector vec, int start, int stop, int dest) { int idx = stop - start; vector frag; // copy a fragment of vector for (idx = start; idx < stop; idx++) frag.push_back(vec.at(idx)); if( dest > stop) idx = dest - (stop - start); else idx = dest; // delete the corresponding fragment of orig vector vec.erase( vec.begin() + start, vec.begin() + stop); // insert the frag in proper position vec.insert( vec.begin() + idx, frag.begin(), frag.end()); return vec; } int main(int argc, char* argv) { vector slice; string u = "abcdefghij"; int pos; for (pos = 0; pos < u.length(); pos++) slice.push_back(u.substr(pos,1)); int i; for (i = 0; i<1000000; i++) move_slice(slice, 4, 6, 7); } Now this is my first take at vectors in C++, so it's entirely possible that an experienced coder would implement it in more efficient way. Still, vectors of strings seemed like a fair choice - after all, Python version is operating on similarly versatile objects. But I was still rather surprised to see that C++ version took 15% longer to execute! (vector, 4, 6, 7) $ time slice real 0m4.478s user 0m0.015s sys 0m0.031s Compiler: MinGW32/gcc 3.4.5, with -O2 optimization (not cygwin's gcc, which for some reason seems to produce sluggish code). When I changed moving the slice closer to the end of the list / vector, Python version executed even faster: >>> t = timeit.Timer("move_slice.move_slice(move_slice.b, 6, 7, 7)", "import move_slice") >>> t.timeit() 1.609766883779912 C++: (vector, 6, 7, 7) $ time slice.exe real 0m3.786s user 0m0.015s sys 0m0.015s Now C++ version took over twice the time to execute in comparison to Python time! Am I comparing apples to oranges? Should the implementations be different? Or does the MinGW compiler simply suck? Note: it appears that speed of Python lists falls down quickly the closer to the list beginning one deletes or inserts elements. C++ vectors do not seem to be as heavily position-dependent. From maestroQC at gmail.com Tue Jul 15 15:14:19 2008 From: maestroQC at gmail.com (maestroQC) Date: Tue, 15 Jul 2008 12:14:19 -0700 (PDT) Subject: MySQL Insert References: <4ece899b-7d0c-414d-a070-572e713f8c0c@a1g2000hsb.googlegroups.com> Message-ID: <41160444-1483-4aba-b1a5-2ceb4e343ee0@l42g2000hsc.googlegroups.com> Thanks for the information. However I must stick to decimal since I'm dealing with monetary values. I loose the decimals with int and float has only supports one decimal place. I tried as you suggested to use the %s instead of the %d to no avail. From ddasilva at umd.edu Wed Jul 30 19:36:21 2008 From: ddasilva at umd.edu (Daniel da Silva) Date: Wed, 30 Jul 2008 19:36:21 -0400 Subject: How can I check nbr of cores of computer? In-Reply-To: <8d9ec3dd0807301635g7997da2bxed2a022ebbec59aa@mail.gmail.com> References: <611a0eb0-db27-4ada-bdc2-4156fde9dd94@e53g2000hsa.googlegroups.com> <4890acd6$0$17215$742ec2ed@news.sonic.net> <5504f9ac0807301116i3907b46l383ed0dd683edfd1@mail.gmail.com> <8d9ec3dd0807301635g7997da2bxed2a022ebbec59aa@mail.gmail.com> Message-ID: <8d9ec3dd0807301636x562bc20fy98ac053d2e8d46df@mail.gmail.com> Single line using /proc/cpuinfo: numprocs = [ int(line.strip()[-1]) for line in open('/proc/cpuinfo', 'r') if \ line.startswith('processor') ][-1] + 1 On Wed, Jul 30, 2008 at 2:16 PM, Dan Upton wrote: > > On Wed, Jul 30, 2008 at 2:22 PM, John Nagle wrote: > > defn noob wrote: > >> > >> How can I check how many cores my computer has? > >> Is it possible to do this in a Python-app? > > > > Why do you care? Python can't use more than one of them at > > a time anyway. > > Per Python process, but you might fork multiple processes and want to > know how many cores there are to know how many to fork, and which > cores to pin them to. (I don't know if there's a direct way in Python > to force it to a certain core, so I instead just wrote an extension to > interface with sched_setaffinity on Linux.) > > On Linux, an almost assuredly non-ideal way to find out the number of > cores is to read /proc/cpuinfo and look for the highest-numbered > "processor: " line (and add 1). > -- > http://mail.python.org/mailman/listinfo/python-list From duncan-news at grisby.org Mon Jul 14 04:42:48 2008 From: duncan-news at grisby.org (Duncan Grisby) Date: Mon, 14 Jul 2008 08:42:48 GMT Subject: Does omniORBpy 3.2 supports DII? References: Message-ID: In article , Ilan wrote: >My apologies if this is not the correct forum for thses quiestions, by >I'm rather new to python+CORBA > >Has anyone used omniORBpy as CORBA implementation? are there any >drawbacks? As omniORBpy's author, I'm biased, so I'll let other people answer that... >Does omniORBpy 3.2 supports the Dynamic Invocation Interface? No, it doesn't. You can use Python's normal dynamic features to build dynamic requests, though. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From rparimi at gmail.com Tue Jul 15 10:15:54 2008 From: rparimi at gmail.com (rparimi at gmail.com) Date: Tue, 15 Jul 2008 07:15:54 -0700 (PDT) Subject: fork after creating temporary file using NamedTemporaryFile Message-ID: <0435315d-7b7d-4587-bc8c-000e3f2644a2@z72g2000hsb.googlegroups.com> Hello pythoners, When I create temporary file using the tempfile module, and forkI) later on in my program, I always see errors when the program exits. Is this because the child process deletes temp file? Here's a stripped down version of my script that exhibits this problem: #!/usr/bin/python import os import tempfile import sys cmd = [] cmd.append('/bin/ls') cmd.append('-l') cmd.append('/tmp') foo = tempfile.NamedTemporaryFile(mode='w+b') pid = os.fork() if pid: print 'I am parent' else: print 'I am child' sys.exit(0) $ python sub.py I am child I am parent Exception exceptions.OSError: (2, 'No such file or directory', '/tmp/ tmp-mZTPq') in ', mode 'w+b' at 0xb7d2a578>> ignored How can these warnings be avoided? I tried to catch this exception using try/except but it didn't work. thanks! From elessar at nienna.org Tue Jul 29 11:12:29 2008 From: elessar at nienna.org (Matthew Fitzgibbons) Date: Tue, 29 Jul 2008 09:12:29 -0600 Subject: Boolean tests [was Re: Attack a sacred Python Cow] In-Reply-To: <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> References: <52404933-ce08-4dc1-a558-935bbbae779b@r35g2000prm.googlegroups.com> <657c06c7-bafa-47df-9019-a7c6a92889c5@c2g2000pra.googlegroups.com> <49cf3107-78a8-43c1-9b1c-58ca2bc85ce5@l64g2000hse.googlegroups.com> <009c37fd$0$20302$c3e8da3@news.astraweb.com> <500eb432-6a7b-4c27-a47e-645eb8bb5132@r15g2000prh.googlegroups.com> <009dcc93$0$20313$c3e8da3@news.astraweb.com> <874752d3-d00e-4fa6-9741-15551483167c@a3g2000prm.googlegroups.com> <009e5c8d$0$20313$c3e8da3@news.astraweb.com> <3ce6f5bb-b4bf-43e1-9d92-12ff679045b7@j1g2000prb.googlegroups.com> Message-ID: <488F335D.8050901@nienna.org> Carl Banks wrote: > On Jul 28, 8:15 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: >>> On Jul 28, 10:00 am, Steven D'Aprano >> cybersource.com.au> wrote: >>>> Cutting to the crux of the discussion... >>>> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: >>>>> I want something where "if x" will do but a simple explicit test >>>>> won't. >>>> Explicit tests aren't simple unless you know what type x is. If x could >>>> be of any type, you can't write a simple test. Does x have a length? Is >>>> it a number? Maybe it's a fixed-length circular length, and the length >>>> is non-zero even when it's empty? Who knows? How many cases do you need >>>> to consider? >>> Use case, please. I'm asking for code, not arguments. Please give me a >>> piece of code where you can write "if x" that works but a simple >>> explicit test won't. >> I gave you a piece of code, actual code from one of my own projects. If >> you wouldn't accept that evidence then, why would you accept it now? > > I would accept as "evidence" something that satisfies my criteria, > which your example did not: it could have easily (and more robustly) > been written with a simple explicit test. I am looking for one that > can't. > > You keep bringing up this notion of "more complex with no benefit", > which I'm simply not interested in talking about that at this time, > and I won't respond to any of your points. I am seeking the answer to > one question: whether "if x" can usefully do something a simple > explicit test can't. Everyone already knows that "if x" requires > fewer keystrokes and parses to fewer nodes. > > > Carl Banks > -- > http://mail.python.org/mailman/listinfo/python-list > My use case involves a DAG of filters that pass data (of a variety of types--filters just pass on data types they don't understand) between them. I can also drop out of the filter chain at any point, using critera determined by the filters. These criteria, you guessed it, are bound to __nonzero__ in the filter and I determine whether or not to continue through the graph using "if x". You can't code explicit tests if you don't know what the tests even are beforehand. Also, I wanted to support builtins (ints and lists in particular) because they can be meaningful inputs to filters. Finally, as I add more filters and data types, I don't want to go back and mess with the code that decides whether or not to break out of the graph. -Matt From basti.wiesner at gmx.net Tue Jul 1 16:47:18 2008 From: basti.wiesner at gmx.net (Sebastian "lunar" Wiesner) Date: Tue, 01 Jul 2008 22:47:18 +0200 Subject: raw_input into Tkinter ? References: <634e2b50-45ba-4b93-89b4-0afd739adaf3@z66g2000hsc.googlegroups.com> <9571b5b0-7b18-4045-a912-6635a6e86500@l42g2000hsc.googlegroups.com> Message-ID: Matimus : > On Jun 30, 9:55?am, jamitwi... at gmail.com wrote: >> Is there any way to type into a Tkinter frame window? >> I want to use raw_input() within a Tkinter frame. > > `raw_input(prompt)` just calls `sys.stdout.write(prompt)` and returns > `sys.stdin.readline()`. It does more like providing readline support, if readline is loaded. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg)